{"id": "1a93eb904d6b-0", "text": "langchain API Reference\u00b6\nlangchain.adapters\u00b6\nClasses\u00b6\nadapters.openai.ChatCompletion()\nChat completion.\nFunctions\u00b6\nadapters.openai.aenumerate(iterable[,\u00a0start])\nAsync version of enumerate function.\nadapters.openai.convert_dict_to_message(_dict)\nConvert a dictionary to a LangChain message.\nadapters.openai.convert_message_to_dict(message)\nConvert a LangChain message to a dictionary.\nadapters.openai.convert_messages_for_finetuning(...)\nConvert messages to a list of lists of dictionaries for fine-tuning.\nadapters.openai.convert_openai_messages(messages)\nConvert dictionaries representing OpenAI messages to LangChain format.\nlangchain.agents\u00b6\nAgent is a class that uses an LLM to choose a sequence of actions to take.\nIn Chains, a sequence of actions is hardcoded. In Agents,\na language model is used as a reasoning engine to determine which actions\nto take and in which order.\nAgents select and use Tools and Toolkits for actions.\nClass hierarchy:\nBaseSingleActionAgent --> LLMSingleActionAgent\n                          OpenAIFunctionsAgent\n                          XMLAgent\n                          Agent --> <name>Agent  # Examples: ZeroShotAgent, ChatAgent\nBaseMultiActionAgent  --> OpenAIMultiFunctionsAgent\nMain helpers:\nAgentType, AgentExecutor, AgentOutputParser, AgentExecutorIterator,\nAgentAction, AgentFinish\nClasses\u00b6\nagents.agent.Agent\nAgent that calls the language model and deciding the action.\nagents.agent.AgentExecutor\nAgent that is using tools.\nagents.agent.AgentOutputParser\nBase class for parsing agent output into agent action/finish.\nagents.agent.BaseMultiActionAgent\nBase Multi Action Agent class.\nagents.agent.BaseSingleActionAgent\nBase Single Action Agent class.\nagents.agent.ExceptionTool\nTool that just returns the query.\nagents.agent.LLMSingleActionAgent", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-1", "text": "Tool that just returns the query.\nagents.agent.LLMSingleActionAgent\nBase class for single action agents.\nagents.agent.MultiActionAgentOutputParser\nBase class for parsing agent output into agent actions/finish.\nagents.agent.RunnableAgent\nAgent powered by runnables.\nagents.agent.RunnableMultiActionAgent\nAgent powered by runnables.\nagents.agent_iterator.AgentExecutorIterator(...)\nIterator for AgentExecutor.\nagents.agent_iterator.BaseAgentExecutorIterator()\nBase class for AgentExecutorIterator.\nagents.agent_toolkits.ainetwork.toolkit.AINetworkToolkit\nToolkit for interacting with AINetwork Blockchain.\nagents.agent_toolkits.amadeus.toolkit.AmadeusToolkit\nToolkit for interacting with Amadeus which offers APIs for travel search.\nagents.agent_toolkits.azure_cognitive_services.AzureCognitiveServicesToolkit\nToolkit for Azure Cognitive Services.\nagents.agent_toolkits.base.BaseToolkit\nBase Toolkit representing a collection of related tools.\nagents.agent_toolkits.clickup.toolkit.ClickupToolkit\nClickup Toolkit.\nagents.agent_toolkits.file_management.toolkit.FileManagementToolkit\nToolkit for interacting with local files.\nagents.agent_toolkits.github.toolkit.GitHubToolkit\nGitHub Toolkit.\nagents.agent_toolkits.gitlab.toolkit.GitLabToolkit\nGitLab Toolkit.\nagents.agent_toolkits.gmail.toolkit.GmailToolkit\nToolkit for interacting with Gmail.\nagents.agent_toolkits.jira.toolkit.JiraToolkit\nJira Toolkit.\nagents.agent_toolkits.json.toolkit.JsonToolkit\nToolkit for interacting with a JSON spec.\nagents.agent_toolkits.multion.toolkit.MultionToolkit\nToolkit for interacting with the Browser Agent.\nagents.agent_toolkits.nla.tool.NLATool\nNatural Language API Tool.\nagents.agent_toolkits.nla.toolkit.NLAToolkit\nNatural Language API Toolkit.\nagents.agent_toolkits.office365.toolkit.O365Toolkit", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-2", "text": "Natural Language API Toolkit.\nagents.agent_toolkits.office365.toolkit.O365Toolkit\nToolkit for interacting with Office 365.\nagents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing\nA tool that sends a DELETE request and parses the response.\nagents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing\nRequests GET tool with LLM-instructed extraction of truncated responses.\nagents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing\nRequests PATCH tool with LLM-instructed extraction of truncated responses.\nagents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing\nRequests POST tool with LLM-instructed extraction of truncated responses.\nagents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing\nRequests PUT tool with LLM-instructed extraction of truncated responses.\nagents.agent_toolkits.openapi.spec.ReducedOpenAPISpec(...)\nA reduced OpenAPI spec.\nagents.agent_toolkits.openapi.toolkit.OpenAPIToolkit\nToolkit for interacting with an OpenAPI API.\nagents.agent_toolkits.openapi.toolkit.RequestsToolkit\nToolkit for making REST requests.\nagents.agent_toolkits.playwright.toolkit.PlayWrightBrowserToolkit\nToolkit for PlayWright browser tools.\nagents.agent_toolkits.powerbi.toolkit.PowerBIToolkit\nToolkit for interacting with Power BI dataset.\nagents.agent_toolkits.spark_sql.toolkit.SparkSQLToolkit\nToolkit for interacting with Spark SQL.\nagents.agent_toolkits.sql.toolkit.SQLDatabaseToolkit\nToolkit for interacting with SQL databases.\nagents.agent_toolkits.vectorstore.toolkit.VectorStoreInfo\nInformation about a VectorStore.\nagents.agent_toolkits.vectorstore.toolkit.VectorStoreRouterToolkit\nToolkit for routing between Vector Stores.\nagents.agent_toolkits.vectorstore.toolkit.VectorStoreToolkit\nToolkit for interacting with a Vector Store.\nagents.agent_toolkits.zapier.toolkit.ZapierToolkit\nZapier Toolkit.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-3", "text": "agents.agent_toolkits.zapier.toolkit.ZapierToolkit\nZapier Toolkit.\nagents.agent_types.AgentType(value[,\u00a0names,\u00a0...])\nAn enum for agent types.\nagents.chat.base.ChatAgent\nChat Agent.\nagents.chat.output_parser.ChatOutputParser\nOutput parser for the chat agent.\nagents.conversational.base.ConversationalAgent\nAn agent that holds a conversation in addition to using tools.\nagents.conversational.output_parser.ConvoOutputParser\nOutput parser for the conversational agent.\nagents.conversational_chat.base.ConversationalChatAgent\nAn agent designed to hold a conversation in addition to using tools.\nagents.conversational_chat.output_parser.ConvoOutputParser\nOutput parser for the conversational agent.\nagents.mrkl.base.ChainConfig(action_name,\u00a0...)\nConfiguration for chain to use in MRKL system.\nagents.mrkl.base.MRKLChain\n[Deprecated] Chain that implements the MRKL system.\nagents.mrkl.base.ZeroShotAgent\nAgent for the MRKL chain.\nagents.mrkl.output_parser.MRKLOutputParser\nMRKL Output parser for the chat agent.\nagents.openai_assistant.base.OpenAIAssistantAction\nAgentAction with info needed to submit custom tool output to existing run.\nagents.openai_assistant.base.OpenAIAssistantFinish\nAgentFinish with run and thread metadata.\nagents.openai_assistant.base.OpenAIAssistantRunnable\nRun an OpenAI Assistant.\nagents.openai_functions_agent.agent_token_buffer_memory.AgentTokenBufferMemory\nMemory used to save agent output AND intermediate steps.\nagents.openai_functions_agent.base.OpenAIFunctionsAgent\nAn Agent driven by OpenAIs function powered API.\nagents.openai_functions_multi_agent.base.OpenAIMultiFunctionsAgent\nAn Agent driven by OpenAIs function powered API.\nagents.output_parsers.json.JSONAgentOutputParser", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-4", "text": "agents.output_parsers.json.JSONAgentOutputParser\nParses tool invocations and final answers in JSON format.\nagents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser\nParses a message into agent action/finish.\nagents.output_parsers.openai_tools.OpenAIToolAgentAction\nOverride init to support instantiation by position for backward compat.\nagents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser\nParses a message into agent actions/finish.\nagents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser\nParses ReAct-style LLM calls that have a single tool input in json format.\nagents.output_parsers.react_single_input.ReActSingleInputOutputParser\nParses ReAct-style LLM calls that have a single tool input.\nagents.output_parsers.self_ask.SelfAskOutputParser\nParses self-ask style LLM calls.\nagents.output_parsers.xml.XMLAgentOutputParser\nParses tool invocations and final answers in XML format.\nagents.react.base.DocstoreExplorer(docstore)\nClass to assist with exploration of a document store.\nagents.react.base.ReActChain\n[Deprecated] Chain that implements the ReAct paper.\nagents.react.base.ReActDocstoreAgent\nAgent for the ReAct chain.\nagents.react.base.ReActTextWorldAgent\nAgent for the ReAct TextWorld chain.\nagents.react.output_parser.ReActOutputParser\nOutput parser for the ReAct agent.\nagents.schema.AgentScratchPadChatPromptTemplate\nChat prompt template for the agent scratchpad.\nagents.self_ask_with_search.base.SelfAskWithSearchAgent\nAgent for the self-ask-with-search paper.\nagents.self_ask_with_search.base.SelfAskWithSearchChain\n[Deprecated] Chain that does self-ask with search.\nagents.structured_chat.base.StructuredChatAgent\nStructured Chat Agent.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-5", "text": "agents.structured_chat.base.StructuredChatAgent\nStructured Chat Agent.\nagents.structured_chat.output_parser.StructuredChatOutputParser\nOutput parser for the structured chat agent.\nagents.structured_chat.output_parser.StructuredChatOutputParserWithRetries\nOutput parser with retries for the structured chat agent.\nagents.tools.InvalidTool\nTool that is run when invalid tool name is encountered by agent.\nagents.xml.base.XMLAgent\nAgent that uses XML tags.\nFunctions\u00b6\nagents.agent_iterator.rebuild_callback_manager_on_set(...)\nDecorator to force setters to rebuild callback mgr\nagents.agent_toolkits.conversational_retrieval.openai_functions.create_conversational_retrieval_agent(...)\nA convenience method for creating a conversational retrieval agent.\nagents.agent_toolkits.json.base.create_json_agent(...)\nConstruct a json agent from an LLM and tools.\nagents.agent_toolkits.openapi.base.create_openapi_agent(...)\nConstruct an OpenAPI agent from an LLM and tools.\nagents.agent_toolkits.openapi.planner.create_openapi_agent(...)\nInstantiate OpenAI API planner and controller for a given spec.\nagents.agent_toolkits.openapi.spec.reduce_openapi_spec(spec)\nSimplify/distill/minify a spec somehow.\nagents.agent_toolkits.powerbi.base.create_pbi_agent(llm)\nConstruct a Power BI agent from an LLM and tools.\nagents.agent_toolkits.powerbi.chat_base.create_pbi_chat_agent(llm)\nConstruct a Power BI agent from a Chat LLM and tools.\nagents.agent_toolkits.spark_sql.base.create_spark_sql_agent(...)\nConstruct a Spark SQL agent from an LLM and tools.\nagents.agent_toolkits.sql.base.create_sql_agent(...)\nConstruct an SQL agent from an LLM and tools.\nagents.agent_toolkits.vectorstore.base.create_vectorstore_agent(...)\nConstruct a VectorStore agent from an LLM and tools.\nagents.agent_toolkits.vectorstore.base.create_vectorstore_router_agent(...)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-6", "text": "agents.agent_toolkits.vectorstore.base.create_vectorstore_router_agent(...)\nConstruct a VectorStore router agent from an LLM and tools.\nagents.format_scratchpad.log.format_log_to_str(...)\nConstruct the scratchpad that lets the agent continue its thought process.\nagents.format_scratchpad.log_to_messages.format_log_to_messages(...)\nConstruct the scratchpad that lets the agent continue its thought process.\nagents.format_scratchpad.openai_functions.format_to_openai_function_messages(...)\nConvert (AgentAction, tool output) tuples into FunctionMessages.\nagents.format_scratchpad.openai_functions.format_to_openai_functions(...)\nConvert (AgentAction, tool output) tuples into FunctionMessages.\nagents.format_scratchpad.openai_tools.format_to_openai_tool_messages(...)\nConvert (AgentAction, tool output) tuples into FunctionMessages.\nagents.format_scratchpad.xml.format_xml(...)\nFormat the intermediate steps as XML.\nagents.initialize.initialize_agent(tools,\u00a0llm)\nLoad an agent executor given tools and LLM.\nagents.load_tools.get_all_tool_names()\nGet a list of all possible tool names.\nagents.load_tools.load_huggingface_tool(...)\nLoads a tool from the HuggingFace Hub.\nagents.load_tools.load_tools(tool_names[,\u00a0...])\nLoad tools based on their name.\nagents.loading.load_agent(path,\u00a0**kwargs)\nUnified method for loading an agent from LangChainHub or local fs.\nagents.loading.load_agent_from_config(config)\nLoad agent from Config Dict.\nagents.output_parsers.openai_tools.parse_ai_message_to_openai_tool_action(message)\nParse an AI message potentially containing tool_calls.\nagents.utils.validate_tools_single_input(...)\nValidate tools for single input.\nlangchain.agents.format_scratchpad\u00b6\nLogic for formatting intermediate steps into an agent scratchpad.\nIntermediate steps refers to the list of (AgentAction, observation) tuples", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-7", "text": "Intermediate steps refers to the list of (AgentAction, observation) tuples\nthat result from previous iterations of the agent.\nDepending on the prompting strategy you are using, you may want to format these\ndifferently before passing them into the LLM.\nFunctions\u00b6\nagents.format_scratchpad.log.format_log_to_str(...)\nConstruct the scratchpad that lets the agent continue its thought process.\nagents.format_scratchpad.log_to_messages.format_log_to_messages(...)\nConstruct the scratchpad that lets the agent continue its thought process.\nagents.format_scratchpad.openai_functions.format_to_openai_function_messages(...)\nConvert (AgentAction, tool output) tuples into FunctionMessages.\nagents.format_scratchpad.openai_functions.format_to_openai_functions(...)\nConvert (AgentAction, tool output) tuples into FunctionMessages.\nagents.format_scratchpad.openai_tools.format_to_openai_tool_messages(...)\nConvert (AgentAction, tool output) tuples into FunctionMessages.\nagents.format_scratchpad.xml.format_xml(...)\nFormat the intermediate steps as XML.\nlangchain.agents.output_parsers\u00b6\nParsing utils to go from string to AgentAction or Agent Finish.\nAgentAction means that an action should be taken.\nThis contains the name of the tool to use, the input to pass to that tool,\nand a log variable (which contains a log of the agent\u2019s thinking).\nAgentFinish means that a response should be given.\nThis contains a return_values dictionary. This usually contains a\nsingle output key, but can be extended to contain more.\nThis also contains a log variable (which contains a log of the agent\u2019s thinking).\nClasses\u00b6\nagents.output_parsers.json.JSONAgentOutputParser\nParses tool invocations and final answers in JSON format.\nagents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser\nParses a message into agent action/finish.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-8", "text": "Parses a message into agent action/finish.\nagents.output_parsers.openai_tools.OpenAIToolAgentAction\nOverride init to support instantiation by position for backward compat.\nagents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser\nParses a message into agent actions/finish.\nagents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser\nParses ReAct-style LLM calls that have a single tool input in json format.\nagents.output_parsers.react_single_input.ReActSingleInputOutputParser\nParses ReAct-style LLM calls that have a single tool input.\nagents.output_parsers.self_ask.SelfAskOutputParser\nParses self-ask style LLM calls.\nagents.output_parsers.xml.XMLAgentOutputParser\nParses tool invocations and final answers in XML format.\nFunctions\u00b6\nagents.output_parsers.openai_tools.parse_ai_message_to_openai_tool_action(message)\nParse an AI message potentially containing tool_calls.\nlangchain.cache\u00b6\nWarning\nBeta Feature!\nCache provides an optional caching layer for LLMs.\nCache is useful for two reasons:\nIt can save you money by reducing the number of API calls you make to the LLM\nprovider if you\u2019re often requesting the same completion multiple times.\nIt can speed up your application by reducing the number of API calls you make\nto the LLM provider.\nCache directly competes with Memory. See documentation for Pros and Cons.\nClass hierarchy:\nBaseCache --> <name>Cache  # Examples: InMemoryCache, RedisCache, GPTCache\nClasses\u00b6\ncache.CassandraCache([session,\u00a0keyspace,\u00a0...])\nCache that uses Cassandra / Astra DB as a backend.\ncache.CassandraSemanticCache(session,\u00a0...[,\u00a0...])\nCache that uses Cassandra as a vector-store backend for semantic (i.e.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-9", "text": "Cache that uses Cassandra as a vector-store backend for semantic (i.e.\ncache.FullLLMCache(**kwargs)\nSQLite table for full LLM Cache (all generations).\ncache.FullMd5LLMCache(**kwargs)\nSQLite table for full LLM Cache (all generations).\ncache.GPTCache([init_func])\nCache that uses GPTCache as a backend.\ncache.InMemoryCache()\nCache that stores things in memory.\ncache.MomentoCache(cache_client,\u00a0cache_name,\u00a0*)\nCache that uses Momento as a backend.\ncache.RedisCache(redis_,\u00a0*[,\u00a0ttl])\nCache that uses Redis as a backend.\ncache.RedisSemanticCache(redis_url,\u00a0embedding)\nCache that uses Redis as a vector-store backend.\ncache.SQLAlchemyCache(engine,\u00a0cache_schema)\nCache that uses SQAlchemy as a backend.\ncache.SQLAlchemyMd5Cache(engine,\u00a0cache_schema)\nCache that uses SQAlchemy as a backend.\ncache.SQLiteCache([database_path])\nCache that uses SQLite as a backend.\ncache.UpstashRedisCache(redis_,\u00a0*[,\u00a0ttl])\nCache that uses Upstash Redis as a backend.\nFunctions\u00b6\nlangchain.callbacks\u00b6\nCallback handlers allow listening to events in LangChain.\nClass hierarchy:\nBaseCallbackHandler --> <name>CallbackHandler  # Example: AimCallbackHandler\nClasses\u00b6\ncallbacks.aim_callback.AimCallbackHandler([...])\nCallback Handler that logs to Aim.\ncallbacks.aim_callback.BaseMetadataCallbackHandler()\nThis class handles the metadata and associated function states for callbacks.\ncallbacks.argilla_callback.ArgillaCallbackHandler(...)\nCallback Handler that logs into Argilla.\ncallbacks.arize_callback.ArizeCallbackHandler([...])\nCallback Handler that logs to Arize.\ncallbacks.arthur_callback.ArthurCallbackHandler(...)\nCallback Handler that logs to Arthur platform.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-10", "text": "callbacks.arthur_callback.ArthurCallbackHandler(...)\nCallback Handler that logs to Arthur platform.\ncallbacks.clearml_callback.ClearMLCallbackHandler([...])\nCallback Handler that logs to ClearML.\ncallbacks.comet_ml_callback.CometCallbackHandler([...])\nCallback Handler that logs to Comet.\ncallbacks.confident_callback.DeepEvalCallbackHandler(metrics)\nCallback Handler that logs into deepeval.\ncallbacks.context_callback.ContextCallbackHandler([...])\nCallback Handler that records transcripts to the Context service.\ncallbacks.file.FileCallbackHandler(filename)\nCallback Handler that writes to a file.\ncallbacks.flyte_callback.FlyteCallbackHandler()\nThis callback handler that is used within a Flyte task.\ncallbacks.human.HumanApprovalCallbackHandler(...)\nCallback for manually validating values.\ncallbacks.human.HumanRejectedException\nException to raise when a person manually review and rejects a value.\ncallbacks.infino_callback.InfinoCallbackHandler([...])\nCallback Handler that logs to Infino.\ncallbacks.labelstudio_callback.LabelStudioCallbackHandler([...])\nLabel Studio callback handler.\ncallbacks.labelstudio_callback.LabelStudioMode(value)\nLabel Studio mode enumerator.\ncallbacks.llmonitor_callback.LLMonitorCallbackHandler([...])\nCallback Handler for LLMonitor`.\ncallbacks.llmonitor_callback.UserContextManager(user_id)\nContext manager for LLMonitor user context.\ncallbacks.mlflow_callback.MlflowCallbackHandler([...])\nCallback Handler that logs metrics and artifacts to mlflow server.\ncallbacks.mlflow_callback.MlflowLogger(**kwargs)\nCallback Handler that logs metrics and artifacts to mlflow server.\ncallbacks.openai_info.OpenAICallbackHandler()\nCallback Handler that tracks OpenAI info.\ncallbacks.promptlayer_callback.PromptLayerCallbackHandler([...])\nCallback handler for promptlayer.\ncallbacks.sagemaker_callback.SageMakerCallbackHandler(run)\nCallback Handler that logs prompt artifacts and metrics to SageMaker Experiments.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-11", "text": "Callback Handler that logs prompt artifacts and metrics to SageMaker Experiments.\ncallbacks.streaming_aiter.AsyncIteratorCallbackHandler()\nCallback handler that returns an async iterator.\ncallbacks.streaming_aiter_final_only.AsyncFinalIteratorCallbackHandler(*)\nCallback handler that returns an async iterator.\ncallbacks.streaming_stdout.StreamingStdOutCallbackHandler()\nCallback handler for streaming.\ncallbacks.streaming_stdout_final_only.FinalStreamingStdOutCallbackHandler(*)\nCallback handler for streaming in agents.\ncallbacks.streamlit.mutable_expander.ChildRecord(...)\nThe child record as a NamedTuple.\ncallbacks.streamlit.mutable_expander.ChildType(value)\nThe enumerator of the child type.\ncallbacks.streamlit.mutable_expander.MutableExpander(...)\nA Streamlit expander that can be renamed and dynamically expanded/collapsed.\ncallbacks.streamlit.streamlit_callback_handler.LLMThought(...)\nA thought in the LLM's thought stream.\ncallbacks.streamlit.streamlit_callback_handler.LLMThoughtLabeler()\nGenerates markdown labels for LLMThought containers.\ncallbacks.streamlit.streamlit_callback_handler.LLMThoughtState(value)\nEnumerator of the LLMThought state.\ncallbacks.streamlit.streamlit_callback_handler.StreamlitCallbackHandler(...)\nA callback handler that writes to a Streamlit app.\ncallbacks.streamlit.streamlit_callback_handler.ToolRecord(...)\nThe tool record as a NamedTuple.\ncallbacks.tracers.wandb.RunProcessor(...)\nHandles the conversion of a LangChain Runs into a WBTraceTree.\ncallbacks.tracers.wandb.WandbRunArgs\nArguments for the WandbTracer.\ncallbacks.tracers.wandb.WandbTracer([run_args])\nCallback Handler that logs to Weights and Biases.\ncallbacks.trubrics_callback.TrubricsCallbackHandler([...])\nCallback handler for Trubrics.\ncallbacks.utils.BaseMetadataCallbackHandler()\nThis class handles the metadata and associated function states for callbacks.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-12", "text": "This class handles the metadata and associated function states for callbacks.\ncallbacks.wandb_callback.WandbCallbackHandler([...])\nCallback Handler that logs to Weights and Biases.\ncallbacks.whylabs_callback.WhyLabsCallbackHandler(...)\nCallback Handler for logging to WhyLabs.\nFunctions\u00b6\ncallbacks.aim_callback.import_aim()\nImport the aim python package and raise an error if it is not installed.\ncallbacks.clearml_callback.import_clearml()\nImport the clearml python package and raise an error if it is not installed.\ncallbacks.comet_ml_callback.import_comet_ml()\nImport comet_ml and raise an error if it is not installed.\ncallbacks.context_callback.import_context()\nImport the getcontext package.\ncallbacks.flyte_callback.analyze_text(text)\nAnalyze text using textstat and spacy.\ncallbacks.flyte_callback.import_flytekit()\nImport flytekit and flytekitplugins-deck-standard.\ncallbacks.infino_callback.get_num_tokens(...)\nCalculate num tokens for OpenAI with tiktoken package.\ncallbacks.infino_callback.import_infino()\nImport the infino client.\ncallbacks.infino_callback.import_tiktoken()\nImport tiktoken for counting tokens for OpenAI models.\ncallbacks.labelstudio_callback.get_default_label_configs(mode)\nGet default Label Studio configs for the given mode.\ncallbacks.llmonitor_callback.identify(user_id)\nBuilds an LLMonitor UserContextManager\ncallbacks.manager.get_openai_callback()\nGet the OpenAI callback handler in a context manager.\ncallbacks.manager.wandb_tracing_enabled([...])\nGet the WandbTracer in a context manager.\ncallbacks.mlflow_callback.analyze_text(text)\nAnalyze text using textstat and spacy.\ncallbacks.mlflow_callback.construct_html_from_prompt_and_generation(...)\nConstruct an html element from a prompt and a generation.\ncallbacks.mlflow_callback.import_mlflow()", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-13", "text": "callbacks.mlflow_callback.import_mlflow()\nImport the mlflow python package and raise an error if it is not installed.\ncallbacks.openai_info.get_openai_token_cost_for_model(...)\nGet the cost in USD for a given model and number of tokens.\ncallbacks.openai_info.standardize_model_name(...)\nStandardize the model name to a format that can be used in the OpenAI API.\ncallbacks.sagemaker_callback.save_json(data,\u00a0...)\nSave dict to local file path.\ncallbacks.utils.flatten_dict(nested_dict[,\u00a0...])\nFlattens a nested dictionary into a flat dictionary.\ncallbacks.utils.hash_string(s)\nHash a string using sha1.\ncallbacks.utils.import_pandas()\nImport the pandas python package and raise an error if it is not installed.\ncallbacks.utils.import_spacy()\nImport the spacy python package and raise an error if it is not installed.\ncallbacks.utils.import_textstat()\nImport the textstat python package and raise an error if it is not installed.\ncallbacks.utils.load_json(json_path)\nLoad json file to a string.\ncallbacks.wandb_callback.analyze_text(text)\nAnalyze text using textstat and spacy.\ncallbacks.wandb_callback.construct_html_from_prompt_and_generation(...)\nConstruct an html element from a prompt and a generation.\ncallbacks.wandb_callback.import_wandb()\nImport the wandb python package and raise an error if it is not installed.\ncallbacks.wandb_callback.load_json_to_dict(...)\nLoad json file to a dictionary.\ncallbacks.whylabs_callback.import_langkit([...])\nImport the langkit python package and raise an error if it is not installed.\nlangchain.chains\u00b6\nChains are easily reusable components linked together.\nChains encode a sequence of calls to components like models, document retrievers,\nother Chains, etc., and provide a simple interface to this sequence.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-14", "text": "other Chains, etc., and provide a simple interface to this sequence.\nThe Chain interface makes it easy to create apps that are:\nStateful: add Memory to any Chain to give it state,\nObservable: pass Callbacks to a Chain to execute additional functionality,\nlike logging, outside the main sequence of component calls,\nComposable: combine Chains with other components, including other Chains.\nClass hierarchy:\nChain --> <name>Chain  # Examples: LLMChain, MapReduceChain, RouterChain\nClasses\u00b6\nchains.api.base.APIChain\nChain that makes API calls and summarizes the responses to answer a question.\nchains.api.openapi.chain.OpenAPIEndpointChain\nChain interacts with an OpenAPI endpoint using natural language.\nchains.api.openapi.requests_chain.APIRequesterChain\nGet the request parser.\nchains.api.openapi.requests_chain.APIRequesterOutputParser\nParse the request and error tags.\nchains.api.openapi.response_chain.APIResponderChain\nGet the response parser.\nchains.api.openapi.response_chain.APIResponderOutputParser\nParse the response and error tags.\nchains.base.Chain\nAbstract base class for creating structured sequences of calls to components.\nchains.combine_documents.base.AnalyzeDocumentChain\nChain that splits documents, then analyzes it in pieces.\nchains.combine_documents.base.BaseCombineDocumentsChain\nBase interface for chains combining documents.\nchains.combine_documents.map_reduce.MapReduceDocumentsChain\nCombining documents by mapping a chain over them, then combining results.\nchains.combine_documents.map_rerank.MapRerankDocumentsChain\nCombining documents by mapping a chain over them, then reranking results.\nchains.combine_documents.reduce.AsyncCombineDocsProtocol(...)\nInterface for the combine_docs method.\nchains.combine_documents.reduce.CombineDocsProtocol(...)\nInterface for the combine_docs method.\nchains.combine_documents.reduce.ReduceDocumentsChain\nCombine documents by recursively reducing them.\nchains.combine_documents.refine.RefineDocumentsChain", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-15", "text": "Combine documents by recursively reducing them.\nchains.combine_documents.refine.RefineDocumentsChain\nCombine documents by doing a first pass and then refining on more documents.\nchains.combine_documents.stuff.StuffDocumentsChain\nChain that combines documents by stuffing into context.\nchains.constitutional_ai.base.ConstitutionalChain\nChain for applying constitutional principles.\nchains.constitutional_ai.models.ConstitutionalPrinciple\nClass for a constitutional principle.\nchains.conversation.base.ConversationChain\nChain to have a conversation and load context from memory.\nchains.conversational_retrieval.base.BaseConversationalRetrievalChain\nChain for chatting with an index.\nchains.conversational_retrieval.base.ChatVectorDBChain\nChain for chatting with a vector database.\nchains.conversational_retrieval.base.ConversationalRetrievalChain\nChain for having a conversation based on retrieved documents.\nchains.conversational_retrieval.base.InputType\nCreate a new model by parsing and validating input data from keyword arguments.\nchains.elasticsearch_database.base.ElasticsearchDatabaseChain\nChain for interacting with Elasticsearch Database.\nchains.flare.base.FlareChain\nChain that combines a retriever, a question generator, and a response generator.\nchains.flare.base.QuestionGeneratorChain\nChain that generates questions from uncertain spans.\nchains.flare.prompts.FinishedOutputParser\nOutput parser that checks if the output is finished.\nchains.graph_qa.arangodb.ArangoGraphQAChain\nChain for question-answering against a graph by generating AQL statements.\nchains.graph_qa.base.GraphQAChain\nChain for question-answering against a graph.\nchains.graph_qa.cypher.GraphCypherQAChain\nChain for question-answering against a graph by generating Cypher statements.\nchains.graph_qa.cypher_utils.CypherQueryCorrector(schemas)\nUsed to correct relationship direction in generated Cypher statements.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-16", "text": "Used to correct relationship direction in generated Cypher statements.\nchains.graph_qa.cypher_utils.Schema(...)\nCreate new instance of Schema(left_node, relation, right_node)\nchains.graph_qa.falkordb.FalkorDBQAChain\nChain for question-answering against a graph by generating Cypher statements.\nchains.graph_qa.hugegraph.HugeGraphQAChain\nChain for question-answering against a graph by generating gremlin statements.\nchains.graph_qa.kuzu.KuzuQAChain\nQuestion-answering against a graph by generating Cypher statements for K\u00f9zu.\nchains.graph_qa.nebulagraph.NebulaGraphQAChain\nChain for question-answering against a graph by generating nGQL statements.\nchains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain\nChain for question-answering against a Neptune graph by generating openCypher statements.\nchains.graph_qa.sparql.GraphSparqlQAChain\nQuestion-answering against an RDF or OWL graph by generating SPARQL statements.\nchains.hyde.base.HypotheticalDocumentEmbedder\nGenerate hypothetical document for query, and then embed that.\nchains.llm.LLMChain\nChain to run queries against LLMs.\nchains.llm_checker.base.LLMCheckerChain\nChain for question-answering with self-verification.\nchains.llm_math.base.LLMMathChain\nChain that interprets a prompt and executes python code to do math.\nchains.llm_requests.LLMRequestsChain\nChain that requests a URL and then uses an LLM to parse results.\nchains.llm_summarization_checker.base.LLMSummarizationCheckerChain\nChain for question-answering with self-verification.\nchains.mapreduce.MapReduceChain\nMap-reduce chain.\nchains.moderation.OpenAIModerationChain", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-17", "text": "Map-reduce chain.\nchains.moderation.OpenAIModerationChain\nPass input through a moderation endpoint.\nchains.natbot.base.NatBotChain\nImplement an LLM driven browser.\nchains.natbot.crawler.Crawler()\nA crawler for web pages.\nchains.natbot.crawler.ElementInViewPort\nA typed dictionary containing information about elements in the viewport.\nchains.openai_functions.citation_fuzzy_match.FactWithEvidence\nClass representing a single statement.\nchains.openai_functions.citation_fuzzy_match.QuestionAnswer\nA question and its answer as a list of facts each one should have a source.\nchains.openai_functions.openapi.SimpleRequestChain\nChain for making a simple request to an API endpoint.\nchains.openai_functions.qa_with_structure.AnswerWithSources\nAn answer to the question, with sources.\nchains.prompt_selector.BasePromptSelector\nBase class for prompt selectors.\nchains.prompt_selector.ConditionalPromptSelector\nPrompt collection that goes through conditionals.\nchains.qa_generation.base.QAGenerationChain\nBase class for question-answer generation chains.\nchains.qa_with_sources.base.BaseQAWithSourcesChain\nQuestion answering chain with sources over documents.\nchains.qa_with_sources.base.QAWithSourcesChain\nQuestion answering with sources over documents.\nchains.qa_with_sources.loading.LoadingCallable(...)\nInterface for loading the combine documents chain.\nchains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain\nQuestion-answering with sources over an index.\nchains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain\nQuestion-answering with sources over a vector database.\nchains.query_constructor.base.StructuredQueryOutputParser\nOutput parser that parses a structured query.\nchains.query_constructor.ir.Comparator(value)\nEnumerator of the comparison operators.\nchains.query_constructor.ir.Comparison\nA comparison to a value.\nchains.query_constructor.ir.Expr", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-18", "text": "chains.query_constructor.ir.Comparison\nA comparison to a value.\nchains.query_constructor.ir.Expr\nBase class for all expressions.\nchains.query_constructor.ir.FilterDirective\nA filtering expression.\nchains.query_constructor.ir.Operation\nA logical operation over other directives.\nchains.query_constructor.ir.Operator(value)\nEnumerator of the operations.\nchains.query_constructor.ir.StructuredQuery\nA structured query.\nchains.query_constructor.ir.Visitor()\nDefines interface for IR translation using visitor pattern.\nchains.query_constructor.parser.ISO8601Date\nA date in ISO 8601 format (YYYY-MM-DD).\nchains.query_constructor.schema.AttributeInfo\nInformation about a data source attribute.\nchains.retrieval_qa.base.BaseRetrievalQA\nBase class for question-answering chains.\nchains.retrieval_qa.base.RetrievalQA\nChain for question-answering against an index.\nchains.retrieval_qa.base.VectorDBQA\nChain for question-answering against a vector database.\nchains.router.base.MultiRouteChain\nUse a single chain to route an input to one of multiple candidate chains.\nchains.router.base.Route(destination,\u00a0...)\nCreate new instance of Route(destination, next_inputs)\nchains.router.base.RouterChain\nChain that outputs the name of a destination chain and the inputs to it.\nchains.router.embedding_router.EmbeddingRouterChain\nChain that uses embeddings to route between options.\nchains.router.llm_router.LLMRouterChain\nA router chain that uses an LLM chain to perform routing.\nchains.router.llm_router.RouterOutputParser\nParser for output of router chain in the multi-prompt chain.\nchains.router.multi_prompt.MultiPromptChain\nA multi-route chain that uses an LLM router chain to choose amongst prompts.\nchains.router.multi_retrieval_qa.MultiRetrievalQAChain\nA multi-route chain that uses an LLM router chain to choose amongst retrieval qa chains.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-19", "text": "A multi-route chain that uses an LLM router chain to choose amongst retrieval qa chains.\nchains.sequential.SequentialChain\nChain where the outputs of one chain feed directly into next.\nchains.sequential.SimpleSequentialChain\nSimple chain where the outputs of one step feed directly into next.\nchains.sql_database.query.SQLInput\nInput for a SQL Chain.\nchains.sql_database.query.SQLInputWithTables\nInput for a SQL Chain.\nchains.transform.TransformChain\nChain that transforms the chain output.\nFunctions\u00b6\nchains.combine_documents.reduce.acollapse_docs(...)\nExecute a collapse function on a set of documents and merge their metadatas.\nchains.combine_documents.reduce.collapse_docs(...)\nExecute a collapse function on a set of documents and merge their metadatas.\nchains.combine_documents.reduce.split_list_of_docs(...)\nSplit Documents into subsets that each meet a cumulative length constraint.\nchains.example_generator.generate_example(...)\nReturn another example given a list of examples for a prompt.\nchains.graph_qa.cypher.construct_schema(...)\nFilter the schema based on included or excluded types\nchains.graph_qa.cypher.extract_cypher(text)\nExtract Cypher code from a text.\nchains.graph_qa.falkordb.extract_cypher(text)\nExtract Cypher code from a text.\nchains.graph_qa.neptune_cypher.extract_cypher(text)\nExtract Cypher code from text using Regex.\nchains.graph_qa.neptune_cypher.trim_query(query)\nTrim the query to only include Cypher keywords.\nchains.graph_qa.neptune_cypher.use_simple_prompt(llm)\nDecides whether to use the simple prompt\nchains.loading.load_chain(path,\u00a0**kwargs)\nUnified method for loading a chain from LangChainHub or local fs.\nchains.loading.load_chain_from_config(...)\nLoad chain from Config Dict.\nchains.openai_functions.base.convert_python_function_to_openai_function(...)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-20", "text": "chains.openai_functions.base.convert_python_function_to_openai_function(...)\nConvert a Python function to an OpenAI function-calling API compatible dict.\nchains.openai_functions.base.convert_to_openai_function(...)\nConvert a raw function/class to an OpenAI function.\nchains.openai_functions.base.create_openai_fn_chain(...)\n[Legacy] Create an LLM chain that uses OpenAI functions.\nchains.openai_functions.base.create_openai_fn_runnable(...)\nCreate a runnable sequence that uses OpenAI functions.\nchains.openai_functions.base.create_structured_output_chain(...)\n[Legacy] Create an LLMChain that uses an OpenAI function to get a structured output.\nchains.openai_functions.base.create_structured_output_runnable(...)\nCreate a runnable that uses an OpenAI function to get a structured output.\nchains.openai_functions.base.get_openai_output_parser(...)\nGet the appropriate function output parser given the user functions.\nchains.openai_functions.citation_fuzzy_match.create_citation_fuzzy_match_chain(llm)\nCreate a citation fuzzy match chain.\nchains.openai_functions.extraction.create_extraction_chain(...)\nCreates a chain that extracts information from a passage.\nchains.openai_functions.extraction.create_extraction_chain_pydantic(...)\nCreates a chain that extracts information from a passage using pydantic schema.\nchains.openai_functions.openapi.get_openapi_chain(spec)\nCreate a chain for querying an API from a OpenAPI spec.\nchains.openai_functions.openapi.openapi_spec_to_openai_fn(spec)\nConvert a valid OpenAPI spec to the JSON Schema format expected for OpenAI\nchains.openai_functions.qa_with_structure.create_qa_with_sources_chain(llm)\nCreate a question answering chain that returns an answer with sources.\nchains.openai_functions.qa_with_structure.create_qa_with_structure_chain(...)\nCreate a question answering chain that returns an answer with sources\nchains.openai_functions.tagging.create_tagging_chain(...)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-21", "text": "chains.openai_functions.tagging.create_tagging_chain(...)\nCreates a chain that extracts information from a passage\nchains.openai_functions.tagging.create_tagging_chain_pydantic(...)\nCreates a chain that extracts information from a passage\nchains.openai_functions.utils.get_llm_kwargs(...)\nReturns the kwargs for the LLMChain constructor.\nchains.openai_tools.extraction.create_extraction_chain_pydantic(...)\nchains.prompt_selector.is_chat_model(llm)\nCheck if the language model is a chat model.\nchains.prompt_selector.is_llm(llm)\nCheck if the language model is a LLM.\nchains.qa_with_sources.loading.load_qa_with_sources_chain(llm)\nLoad a question answering with sources chain.\nchains.query_constructor.base.construct_examples(...)\nConstruct examples from input-output pairs.\nchains.query_constructor.base.fix_filter_directive(...)\nFix invalid filter directive.\nchains.query_constructor.base.get_query_constructor_prompt(...)\nCreate query construction prompt.\nchains.query_constructor.base.load_query_constructor_chain(...)\nLoad a query constructor chain.\nchains.query_constructor.base.load_query_constructor_runnable(...)\nLoad a query constructor runnable chain.\nchains.query_constructor.parser.get_parser([...])\nReturns a parser for the query language.\nchains.query_constructor.parser.v_args(...)\nDummy decorator for when lark is not installed.\nchains.sql_database.query.create_sql_query_chain(llm,\u00a0db)\nCreate a chain that generates SQL queries.\nlangchain.chat_loaders\u00b6\nChat Loaders load chat messages from common communications platforms.\nLoad chat messages from various\ncommunications platforms such as Facebook Messenger, Telegram, and\nWhatsApp. The loaded chat messages can be used for fine-tuning models.\nClass hierarchy:\nBaseChatLoader --> <name>ChatLoader  # Examples: WhatsAppChatLoader, IMessageChatLoader\nMain helpers:\nChatSession\nClasses\u00b6\nchat_loaders.base.BaseChatLoader()\nBase class for chat loaders.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-22", "text": "Classes\u00b6\nchat_loaders.base.BaseChatLoader()\nBase class for chat loaders.\nchat_loaders.facebook_messenger.FolderFacebookMessengerChatLoader(path)\nLoad Facebook Messenger chat data from a folder.\nchat_loaders.facebook_messenger.SingleFileFacebookMessengerChatLoader(path)\nLoad Facebook Messenger chat data from a single file.\nchat_loaders.gmail.GMailLoader(creds[,\u00a0n,\u00a0...])\nLoad data from GMail.\nchat_loaders.imessage.IMessageChatLoader([path])\nLoad chat sessions from the iMessage chat.db SQLite file.\nchat_loaders.langsmith.LangSmithDatasetChatLoader(*,\u00a0...)\nLoad chat sessions from a LangSmith dataset with the \"chat\" data type.\nchat_loaders.langsmith.LangSmithRunChatLoader(runs)\nLoad chat sessions from a list of LangSmith \"llm\" runs.\nchat_loaders.slack.SlackChatLoader(path)\nLoad Slack conversations from a dump zip file.\nchat_loaders.telegram.TelegramChatLoader(path)\nLoad telegram conversations to LangChain chat messages.\nchat_loaders.whatsapp.WhatsAppChatLoader(path)\nLoad WhatsApp conversations from a dump zip file or directory.\nFunctions\u00b6\nchat_loaders.utils.map_ai_messages(...)\nConvert messages from the specified 'sender' to AI messages.\nchat_loaders.utils.map_ai_messages_in_session(...)\nConvert messages from the specified 'sender' to AI messages.\nchat_loaders.utils.merge_chat_runs(chat_sessions)\nMerge chat runs together.\nchat_loaders.utils.merge_chat_runs_in_session(...)\nMerge chat runs together in a chat session.\nlangchain.chat_models\u00b6\nChat Models are a variation on language models.\nWhile Chat Models use language models under the hood, the interface they expose\nis a bit different. Rather than expose a \u201ctext in, text out\u201d API, they expose", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-23", "text": "an interface where \u201cchat messages\u201d are the inputs and outputs.\nClass hierarchy:\nBaseLanguageModel --> BaseChatModel --> <name>  # Examples: ChatOpenAI, ChatGooglePalm\nMain helpers:\nAIMessage, BaseMessage, HumanMessage\nClasses\u00b6\nchat_models.anthropic.ChatAnthropic\nAnthropic chat large language models.\nchat_models.anyscale.ChatAnyscale\nAnyscale Chat large language models.\nchat_models.azure_openai.AzureChatOpenAI\nAzure OpenAI Chat Completion API.\nchat_models.azureml_endpoint.AzureMLChatOnlineEndpoint\nAzureML Chat models API.\nchat_models.azureml_endpoint.LlamaContentFormatter()\nContent formatter for LLaMA.\nchat_models.baichuan.ChatBaichuan\nBaichuan chat models API by Baichuan Intelligent Technology.\nchat_models.baidu_qianfan_endpoint.QianfanChatEndpoint\nBaidu Qianfan chat models.\nchat_models.base.BaseChatModel\nBase class for Chat models.\nchat_models.base.SimpleChatModel\nSimple Chat Model.\nchat_models.bedrock.BedrockChat\nA chat model that uses the Bedrock API.\nchat_models.bedrock.ChatPromptAdapter()\nAdapter class to prepare the inputs from Langchain to prompt format that Chat model expects.\nchat_models.cohere.ChatCohere\nCohere chat large language models.\nchat_models.ernie.ErnieBotChat\nERNIE-Bot large language model.\nchat_models.everlyai.ChatEverlyAI\nEverlyAI Chat large language models.\nchat_models.fake.FakeListChatModel\nFake ChatModel for testing purposes.\nchat_models.fake.FakeMessagesListChatModel\nFake ChatModel for testing purposes.\nchat_models.fireworks.ChatFireworks\nFireworks Chat models.\nchat_models.gigachat.GigaChat\nGigaChat large language models API.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-24", "text": "chat_models.gigachat.GigaChat\nGigaChat large language models API.\nchat_models.google_palm.ChatGooglePalm\nGoogle PaLM Chat models API.\nchat_models.google_palm.ChatGooglePalmError\nError with the Google PaLM API.\nchat_models.human.HumanInputChatModel\nChatModel which returns user input as the response.\nchat_models.hunyuan.ChatHunyuan\nTencent Hunyuan chat models API by Tencent.\nchat_models.javelin_ai_gateway.ChatJavelinAIGateway\nJavelin AI Gateway chat models API.\nchat_models.javelin_ai_gateway.ChatParams\nParameters for the Javelin AI Gateway LLM.\nchat_models.jinachat.JinaChat\nJina AI Chat models API.\nchat_models.konko.ChatKonko\nChatKonko Chat large language models API.\nchat_models.litellm.ChatLiteLLM\nA chat model that uses the LiteLLM API.\nchat_models.litellm.ChatLiteLLMException\nError with the LiteLLM I/O library\nchat_models.minimax.MiniMaxChat\nWrapper around Minimax large language models.\nchat_models.mlflow_ai_gateway.ChatMLflowAIGateway\nMLflow AI Gateway chat models API.\nchat_models.mlflow_ai_gateway.ChatParams\nParameters for the MLflow AI Gateway LLM.\nchat_models.ollama.ChatOllama\nOllama locally runs large language models.\nchat_models.openai.ChatOpenAI\nOpenAI Chat large language models API.\nchat_models.pai_eas_endpoint.PaiEasChatEndpoint\nEas LLM Service chat model API.\nchat_models.promptlayer_openai.PromptLayerChatOpenAI\nPromptLayer and OpenAI Chat large language models API.\nchat_models.tongyi.ChatTongyi\nAlibaba Tongyi Qwen chat models API.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-25", "text": "Alibaba Tongyi Qwen chat models API.\nchat_models.vertexai.ChatVertexAI\nVertex AI Chat large language models API.\nchat_models.yandex.ChatYandexGPT\nWrapper around YandexGPT large language models.\nFunctions\u00b6\nchat_models.anthropic.convert_messages_to_prompt_anthropic(...)\nFormat a list of messages into a full prompt for the Anthropic model\nchat_models.baidu_qianfan_endpoint.convert_message_to_dict(message)\nConvert a message to a dictionary that can be passed to the API.\nchat_models.cohere.get_cohere_chat_request(...)\nGet the request for the Cohere chat API.\nchat_models.cohere.get_role(message)\nGet the role of the message.\nchat_models.fireworks.acompletion_with_retry(...)\nUse tenacity to retry the async completion call.\nchat_models.fireworks.acompletion_with_retry_streaming(...)\nUse tenacity to retry the completion call for streaming.\nchat_models.fireworks.completion_with_retry(...)\nUse tenacity to retry the completion call.\nchat_models.fireworks.conditional_decorator(...)\nchat_models.fireworks.convert_dict_to_message(_dict)\nConvert a dict response to a message.\nchat_models.google_palm.achat_with_retry(...)\nUse tenacity to retry the async completion call.\nchat_models.google_palm.chat_with_retry(llm,\u00a0...)\nUse tenacity to retry the completion call.\nchat_models.jinachat.acompletion_with_retry(...)\nUse tenacity to retry the async completion call.\nchat_models.litellm.acompletion_with_retry(llm)\nUse tenacity to retry the async completion call.\nchat_models.openai.acompletion_with_retry(llm)\nUse tenacity to retry the async completion call.\nchat_models.tongyi.convert_dict_to_message(_dict)\nchat_models.tongyi.convert_message_to_dict(message)\nlangchain.docstore\u00b6", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-26", "text": "chat_models.tongyi.convert_message_to_dict(message)\nlangchain.docstore\u00b6\nDocstores are classes to store and load Documents.\nThe Docstore is a simplified version of the Document Loader.\nClass hierarchy:\nDocstore --> <name> # Examples: InMemoryDocstore, Wikipedia\nMain helpers:\nDocument, AddableMixin\nClasses\u00b6\ndocstore.arbitrary_fn.DocstoreFn(lookup_fn)\nLangchain Docstore via arbitrary lookup function.\ndocstore.base.AddableMixin()\nMixin class that supports adding texts.\ndocstore.base.Docstore()\nInterface to access to place that stores documents.\ndocstore.in_memory.InMemoryDocstore([_dict])\nSimple in memory docstore in the form of a dict.\ndocstore.wikipedia.Wikipedia()\nWrapper around wikipedia API.\nlangchain.document_loaders\u00b6\nDocument Loaders  are classes to load Documents.\nDocument Loaders are usually used to load a lot of Documents in a single run.\nClass hierarchy:\nBaseLoader --> <name>Loader  # Examples: TextLoader, UnstructuredFileLoader\nMain helpers:\nDocument, <name>TextSplitter\nClasses\u00b6\ndocument_loaders.acreom.AcreomLoader(path[,\u00a0...])\nLoad acreom vault from a directory.\ndocument_loaders.airbyte.AirbyteCDKLoader(...)\nLoad with an Airbyte source connector implemented using the CDK.\ndocument_loaders.airbyte.AirbyteGongLoader(...)\nLoad from Gong using an Airbyte source connector.\ndocument_loaders.airbyte.AirbyteHubspotLoader(...)\nLoad from Hubspot using an Airbyte source connector.\ndocument_loaders.airbyte.AirbyteSalesforceLoader(...)\nLoad from Salesforce using an Airbyte source connector.\ndocument_loaders.airbyte.AirbyteShopifyLoader(...)\nLoad from Shopify using an Airbyte source connector.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-27", "text": "Load from Shopify using an Airbyte source connector.\ndocument_loaders.airbyte.AirbyteStripeLoader(...)\nLoad from Stripe using an Airbyte source connector.\ndocument_loaders.airbyte.AirbyteTypeformLoader(...)\nLoad from Typeform using an Airbyte source connector.\ndocument_loaders.airbyte.AirbyteZendeskSupportLoader(...)\nLoad from Zendesk Support using an Airbyte source connector.\ndocument_loaders.airbyte_json.AirbyteJSONLoader(...)\nLoad local Airbyte json files.\ndocument_loaders.airtable.AirtableLoader(...)\nLoad the Airtable tables.\ndocument_loaders.apify_dataset.ApifyDatasetLoader\nLoad datasets from Apify web scraping, crawling, and data extraction platform.\ndocument_loaders.arcgis_loader.ArcGISLoader(layer)\nLoad records from an ArcGIS FeatureLayer.\ndocument_loaders.arxiv.ArxivLoader(query[,\u00a0...])\nLoad a query result from Arxiv.\ndocument_loaders.assemblyai.AssemblyAIAudioTranscriptLoader(...)\nLoader for AssemblyAI audio transcripts.\ndocument_loaders.assemblyai.TranscriptFormat(value)\nTranscript format to use for the document loader.\ndocument_loaders.async_html.AsyncHtmlLoader(...)\nLoad HTML asynchronously.\ndocument_loaders.azlyrics.AZLyricsLoader([...])\nLoad AZLyrics webpages.\ndocument_loaders.azure_blob_storage_container.AzureBlobStorageContainerLoader(...)\nLoad from Azure Blob Storage container.\ndocument_loaders.azure_blob_storage_file.AzureBlobStorageFileLoader(...)\nLoad from Azure Blob Storage files.\ndocument_loaders.baiducloud_bos_directory.BaiduBOSDirectoryLoader(...)\nLoad from Baidu BOS directory.\ndocument_loaders.baiducloud_bos_file.BaiduBOSFileLoader(...)\nLoad from Baidu Cloud BOS file.\ndocument_loaders.base.BaseBlobParser()\nAbstract interface for blob parsers.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-28", "text": "document_loaders.base.BaseBlobParser()\nAbstract interface for blob parsers.\ndocument_loaders.base.BaseLoader()\nInterface for Document Loader.\ndocument_loaders.base_o365.O365BaseLoader\nBase class for all loaders that uses O365 Package\ndocument_loaders.bibtex.BibtexLoader(...[,\u00a0...])\nLoad a bibtex file.\ndocument_loaders.bigquery.BigQueryLoader(query)\nLoad from the Google Cloud Platform BigQuery.\ndocument_loaders.bilibili.BiliBiliLoader(...)\nLoad BiliBili video transcripts.\ndocument_loaders.blackboard.BlackboardLoader(...)\nLoad a Blackboard course.\ndocument_loaders.blob_loaders.file_system.FileSystemBlobLoader(path,\u00a0*)\nLoad blobs in the local file system.\ndocument_loaders.blob_loaders.schema.Blob\nBlob represents raw data by either reference or value.\ndocument_loaders.blob_loaders.schema.BlobLoader()\nAbstract interface for blob loaders implementation.\ndocument_loaders.blob_loaders.youtube_audio.YoutubeAudioLoader(...)\nLoad YouTube urls as audio file(s).\ndocument_loaders.blockchain.BlockchainDocumentLoader(...)\nLoad elements from a blockchain smart contract.\ndocument_loaders.blockchain.BlockchainType(value)\nEnumerator of the supported blockchains.\ndocument_loaders.brave_search.BraveSearchLoader(...)\nLoad with Brave Search engine.\ndocument_loaders.browserless.BrowserlessLoader(...)\nLoad webpages with Browserless /content endpoint.\ndocument_loaders.chatgpt.ChatGPTLoader(log_file)\nLoad conversations from exported ChatGPT data.\ndocument_loaders.chromium.AsyncChromiumLoader(urls)\nScrape HTML pages from URLs using a headless instance of the Chromium.\ndocument_loaders.college_confidential.CollegeConfidentialLoader([...])\nLoad College Confidential webpages.\ndocument_loaders.concurrent.ConcurrentLoader(...)\nLoad and pars Documents concurrently.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-29", "text": "document_loaders.concurrent.ConcurrentLoader(...)\nLoad and pars Documents concurrently.\ndocument_loaders.confluence.ConfluenceLoader(url)\nLoad Confluence pages.\ndocument_loaders.confluence.ContentFormat(value)\nEnumerator of the content formats of Confluence page.\ndocument_loaders.conllu.CoNLLULoader(file_path)\nLoad CoNLL-U files.\ndocument_loaders.csv_loader.CSVLoader(file_path)\nLoad a CSV file into a list of Documents.\ndocument_loaders.csv_loader.UnstructuredCSVLoader(...)\nLoad CSV files using Unstructured.\ndocument_loaders.cube_semantic.CubeSemanticLoader(...)\nLoad Cube semantic layer metadata.\ndocument_loaders.datadog_logs.DatadogLogsLoader(...)\nLoad Datadog logs.\ndocument_loaders.dataframe.BaseDataFrameLoader(...)\nInitialize with dataframe object.\ndocument_loaders.dataframe.DataFrameLoader(...)\nLoad Pandas DataFrame.\ndocument_loaders.diffbot.DiffbotLoader(...)\nLoad Diffbot json file.\ndocument_loaders.directory.DirectoryLoader(...)\nLoad from a directory.\ndocument_loaders.discord.DiscordChatLoader(...)\nLoad Discord chat logs.\ndocument_loaders.docugami.DocugamiLoader\nLoad from Docugami.\ndocument_loaders.docusaurus.DocusaurusLoader(url)\nLoader that leverages the SitemapLoader to loop through the generated pages of a Docusaurus Documentation website and extracts the content by looking for specific HTML tags.\ndocument_loaders.dropbox.DropboxLoader\nLoad files from Dropbox.\ndocument_loaders.duckdb_loader.DuckDBLoader(query)\nLoad from DuckDB.\ndocument_loaders.email.OutlookMessageLoader(...)\nLoads Outlook Message files using extract_msg.\ndocument_loaders.email.UnstructuredEmailLoader(...)\nLoad email files using Unstructured.\ndocument_loaders.embaas.BaseEmbaasLoader\nBase loader for Embaas document extraction API.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-30", "text": "Base loader for Embaas document extraction API.\ndocument_loaders.embaas.EmbaasBlobLoader\nLoad Embaas blob.\ndocument_loaders.embaas.EmbaasDocumentExtractionParameters\nParameters for the embaas document extraction API.\ndocument_loaders.embaas.EmbaasDocumentExtractionPayload\nPayload for the Embaas document extraction API.\ndocument_loaders.embaas.EmbaasLoader\nLoad from Embaas.\ndocument_loaders.epub.UnstructuredEPubLoader(...)\nLoad EPub files using Unstructured.\ndocument_loaders.etherscan.EtherscanLoader(...)\nLoad transactions from Ethereum mainnet.\ndocument_loaders.evernote.EverNoteLoader(...)\nLoad from EverNote.\ndocument_loaders.excel.UnstructuredExcelLoader(...)\nLoad Microsoft Excel files using Unstructured.\ndocument_loaders.facebook_chat.FacebookChatLoader(path)\nLoad Facebook Chat messages directory dump.\ndocument_loaders.fauna.FaunaLoader(query,\u00a0...)\nLoad from FaunaDB.\ndocument_loaders.figma.FigmaFileLoader(...)\nLoad Figma file.\ndocument_loaders.gcs_directory.GCSDirectoryLoader(...)\nLoad from GCS directory.\ndocument_loaders.gcs_file.GCSFileLoader(...)\nLoad from GCS file.\ndocument_loaders.generic.GenericLoader(...)\nGeneric Document Loader.\ndocument_loaders.geodataframe.GeoDataFrameLoader(...)\nLoad geopandas Dataframe.\ndocument_loaders.git.GitLoader(repo_path[,\u00a0...])\nLoad Git repository files.\ndocument_loaders.gitbook.GitbookLoader(web_page)\nLoad GitBook data.\ndocument_loaders.github.BaseGitHubLoader\nLoad GitHub repository Issues.\ndocument_loaders.github.GitHubIssuesLoader\nLoad issues of a GitHub repository.\ndocument_loaders.google_speech_to_text.GoogleSpeechToTextLoader(...)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-31", "text": "document_loaders.google_speech_to_text.GoogleSpeechToTextLoader(...)\nLoader for Google Cloud Speech-to-Text audio transcripts.\ndocument_loaders.googledrive.GoogleDriveLoader\nLoad Google Docs from Google Drive.\ndocument_loaders.gutenberg.GutenbergLoader(...)\nLoad from Gutenberg.org.\ndocument_loaders.helpers.FileEncoding(...)\nFile encoding as the NamedTuple.\ndocument_loaders.hn.HNLoader([web_path,\u00a0...])\nLoad Hacker News data.\ndocument_loaders.html.UnstructuredHTMLLoader(...)\nLoad HTML files using Unstructured.\ndocument_loaders.html_bs.BSHTMLLoader(file_path)\nLoad HTML files and parse them with beautiful soup.\ndocument_loaders.hugging_face_dataset.HuggingFaceDatasetLoader(path)\nLoad from Hugging Face Hub datasets.\ndocument_loaders.ifixit.IFixitLoader(web_path)\nLoad iFixit repair guides, device wikis and answers.\ndocument_loaders.image.UnstructuredImageLoader(...)\nLoad PNG and JPG files using Unstructured.\ndocument_loaders.image_captions.ImageCaptionLoader(images)\nLoad image captions.\ndocument_loaders.imsdb.IMSDbLoader([...])\nLoad IMSDb webpages.\ndocument_loaders.iugu.IuguLoader(resource[,\u00a0...])\nLoad from IUGU.\ndocument_loaders.joplin.JoplinLoader([...])\nLoad notes from Joplin.\ndocument_loaders.json_loader.JSONLoader(...)\nLoad a JSON file using a jq schema.\ndocument_loaders.lakefs.LakeFSClient(...)\ndocument_loaders.lakefs.LakeFSLoader(...[,\u00a0...])\nLoad from lakeFS.\ndocument_loaders.lakefs.UnstructuredLakeFSLoader(...)\nArgs:\ndocument_loaders.larksuite.LarkSuiteDocLoader(...)\nLoad from LarkSuite (FeiShu).\ndocument_loaders.markdown.UnstructuredMarkdownLoader(...)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-32", "text": "document_loaders.markdown.UnstructuredMarkdownLoader(...)\nLoad Markdown files using Unstructured.\ndocument_loaders.mastodon.MastodonTootsLoader(...)\nLoad the Mastodon 'toots'.\ndocument_loaders.max_compute.MaxComputeLoader(...)\nLoad from Alibaba Cloud MaxCompute table.\ndocument_loaders.mediawikidump.MWDumpLoader(...)\nLoad MediaWiki dump from an XML file.\ndocument_loaders.merge.MergedDataLoader(loaders)\nMerge documents from a list of loaders\ndocument_loaders.mhtml.MHTMLLoader(file_path)\nParse MHTML files with BeautifulSoup.\ndocument_loaders.modern_treasury.ModernTreasuryLoader(...)\nLoad from Modern Treasury.\ndocument_loaders.mongodb.MongodbLoader(...)\nLoad MongoDB documents.\ndocument_loaders.news.NewsURLLoader(urls[,\u00a0...])\nLoad news articles from URLs using Unstructured.\ndocument_loaders.notebook.NotebookLoader(path)\nLoad Jupyter notebook (.ipynb) files.\ndocument_loaders.notion.NotionDirectoryLoader(path,\u00a0*)\nLoad Notion directory dump.\ndocument_loaders.notiondb.NotionDBLoader(...)\nLoad from Notion DB.\ndocument_loaders.nuclia.NucliaLoader(path,\u00a0...)\nLoad from any file type using Nuclia Understanding API.\ndocument_loaders.obs_directory.OBSDirectoryLoader(...)\nLoad from Huawei OBS directory.\ndocument_loaders.obs_file.OBSFileLoader(...)\nLoad from the Huawei OBS file.\ndocument_loaders.obsidian.ObsidianLoader(path)\nLoad Obsidian files from directory.\ndocument_loaders.odt.UnstructuredODTLoader(...)\nLoad OpenOffice ODT files using Unstructured.\ndocument_loaders.onedrive.OneDriveLoader\nLoad from Microsoft OneDrive.\ndocument_loaders.onedrive_file.OneDriveFileLoader\nLoad a file from Microsoft OneDrive.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-33", "text": "Load a file from Microsoft OneDrive.\ndocument_loaders.open_city_data.OpenCityDataLoader(...)\nLoad from Open City.\ndocument_loaders.org_mode.UnstructuredOrgModeLoader(...)\nLoad Org-Mode files using Unstructured.\ndocument_loaders.parsers.audio.OpenAIWhisperParser([...])\nTranscribe and parse audio files.\ndocument_loaders.parsers.audio.OpenAIWhisperParserLocal([...])\nTranscribe and parse audio files with OpenAI Whisper model.\ndocument_loaders.parsers.audio.YandexSTTParser(*)\nTranscribe and parse audio files.\ndocument_loaders.parsers.docai.DocAIParser(*)\nGoogle Cloud Document AI parser.\ndocument_loaders.parsers.docai.DocAIParsingResults(...)\nA dataclass to store Document AI parsing results.\ndocument_loaders.parsers.generic.MimeTypeBasedParser(...)\nParser that uses mime-types to parse a blob.\ndocument_loaders.parsers.grobid.GrobidParser(...)\nLoad  article PDF files using Grobid.\ndocument_loaders.parsers.grobid.ServerUnavailableException\nException raised when the Grobid server is unavailable.\ndocument_loaders.parsers.html.bs4.BS4HTMLParser(*)\nPparse HTML files using Beautiful Soup.\ndocument_loaders.parsers.language.cobol.CobolSegmenter(code)\nCode segmenter for COBOL.\ndocument_loaders.parsers.language.code_segmenter.CodeSegmenter(code)\nAbstract class for the code segmenter.\ndocument_loaders.parsers.language.javascript.JavaScriptSegmenter(code)\nCode segmenter for JavaScript.\ndocument_loaders.parsers.language.language_parser.LanguageParser([...])\nParse using the respective programming language syntax.\ndocument_loaders.parsers.language.python.PythonSegmenter(code)\nCode segmenter for Python.\ndocument_loaders.parsers.msword.MsWordParser()\nParse the Microsoft Word documents from a blob.\ndocument_loaders.parsers.pdf.AmazonTextractPDFParser([...])", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-34", "text": "document_loaders.parsers.pdf.AmazonTextractPDFParser([...])\nSend PDF files to Amazon Textract and parse them.\ndocument_loaders.parsers.pdf.DocumentIntelligenceParser(...)\nLoads a PDF with Azure Document Intelligence (formerly Forms Recognizer) and chunks at character level.\ndocument_loaders.parsers.pdf.PDFMinerParser([...])\nParse PDF using PDFMiner.\ndocument_loaders.parsers.pdf.PDFPlumberParser([...])\nParse PDF with PDFPlumber.\ndocument_loaders.parsers.pdf.PyMuPDFParser([...])\nParse PDF using PyMuPDF.\ndocument_loaders.parsers.pdf.PyPDFParser([...])\nLoad PDF using pypdf\ndocument_loaders.parsers.pdf.PyPDFium2Parser([...])\nParse PDF with PyPDFium2.\ndocument_loaders.parsers.txt.TextParser()\nParser for text blobs.\ndocument_loaders.pdf.AmazonTextractPDFLoader(...)\nLoad PDF files from a local file system, HTTP or S3.\ndocument_loaders.pdf.BasePDFLoader(file_path,\u00a0*)\nBase Loader class for PDF files.\ndocument_loaders.pdf.DocumentIntelligenceLoader(...)\nLoads a PDF with Azure Document Intelligence\ndocument_loaders.pdf.MathpixPDFLoader(file_path)\nLoad PDF files using Mathpix service.\ndocument_loaders.pdf.OnlinePDFLoader(...[,\u00a0...])\nLoad online PDF.\ndocument_loaders.pdf.PDFMinerLoader(file_path,\u00a0*)\nLoad PDF files using PDFMiner.\ndocument_loaders.pdf.PDFMinerPDFasHTMLLoader(...)\nLoad PDF files as HTML content using PDFMiner.\ndocument_loaders.pdf.PDFPlumberLoader(file_path)\nLoad PDF files using pdfplumber.\ndocument_loaders.pdf.PyMuPDFLoader(file_path,\u00a0*)\nLoad PDF files using PyMuPDF.\ndocument_loaders.pdf.PyPDFDirectoryLoader(path)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-35", "text": "document_loaders.pdf.PyPDFDirectoryLoader(path)\nLoad a directory with PDF files using pypdf and chunks at character level.\ndocument_loaders.pdf.PyPDFLoader(file_path)\nLoad PDF using pypdf into list of documents.\ndocument_loaders.pdf.PyPDFium2Loader(...[,\u00a0...])\nLoad PDF using pypdfium2 and chunks at character level.\ndocument_loaders.pdf.UnstructuredPDFLoader(...)\nLoad PDF files using Unstructured.\ndocument_loaders.polars_dataframe.PolarsDataFrameLoader(...)\nLoad Polars DataFrame.\ndocument_loaders.powerpoint.UnstructuredPowerPointLoader(...)\nLoad Microsoft PowerPoint files using Unstructured.\ndocument_loaders.psychic.PsychicLoader(...)\nLoad from Psychic.dev.\ndocument_loaders.pubmed.PubMedLoader(query)\nLoad from the PubMed biomedical library.\ndocument_loaders.pyspark_dataframe.PySparkDataFrameLoader([...])\nLoad PySpark DataFrames.\ndocument_loaders.python.PythonLoader(file_path)\nLoad Python files, respecting any non-default encoding if specified.\ndocument_loaders.quip.QuipLoader(api_url,\u00a0...)\nLoad Quip pages.\ndocument_loaders.readthedocs.ReadTheDocsLoader(path)\nLoad ReadTheDocs documentation directory.\ndocument_loaders.recursive_url_loader.RecursiveUrlLoader(url)\nLoad all child links from a URL page.\ndocument_loaders.reddit.RedditPostsLoader(...)\nLoad Reddit posts.\ndocument_loaders.roam.RoamLoader(path)\nLoad Roam files from a directory.\ndocument_loaders.rocksetdb.ColumnNotFoundError(...)\nColumn not found error.\ndocument_loaders.rocksetdb.RocksetLoader(...)\nLoad from a Rockset database.\ndocument_loaders.rspace.RSpaceLoader(global_id)\nLoads  content from RSpace notebooks, folders, documents or PDF Gallery files into Langchain documents.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-36", "text": "document_loaders.rss.RSSFeedLoader([urls,\u00a0...])\nLoad news articles from RSS feeds using Unstructured.\ndocument_loaders.rst.UnstructuredRSTLoader(...)\nLoad RST files using Unstructured.\ndocument_loaders.rtf.UnstructuredRTFLoader(...)\nLoad RTF files using Unstructured.\ndocument_loaders.s3_directory.S3DirectoryLoader(bucket)\nLoad from Amazon AWS S3 directory.\ndocument_loaders.s3_file.S3FileLoader(...[,\u00a0...])\nLoad from Amazon AWS S3 file.\ndocument_loaders.sharepoint.SharePointLoader\nLoad  from SharePoint.\ndocument_loaders.sitemap.SitemapLoader(web_path)\nLoad a sitemap and its URLs.\ndocument_loaders.slack_directory.SlackDirectoryLoader(...)\nLoad from a Slack directory dump.\ndocument_loaders.snowflake_loader.SnowflakeLoader(...)\nLoad from Snowflake API.\ndocument_loaders.spreedly.SpreedlyLoader(...)\nLoad from Spreedly API.\ndocument_loaders.srt.SRTLoader(file_path)\nLoad .srt (subtitle) files.\ndocument_loaders.stripe.StripeLoader(resource)\nLoad from Stripe API.\ndocument_loaders.telegram.TelegramChatApiLoader([...])\nLoad Telegram chat json directory dump.\ndocument_loaders.telegram.TelegramChatFileLoader(path)\nLoad from Telegram chat dump.\ndocument_loaders.tencent_cos_directory.TencentCOSDirectoryLoader(...)\nLoad from Tencent Cloud COS directory.\ndocument_loaders.tencent_cos_file.TencentCOSFileLoader(...)\nLoad from Tencent Cloud COS file.\ndocument_loaders.tensorflow_datasets.TensorflowDatasetLoader(...)\nLoad from TensorFlow Dataset.\ndocument_loaders.text.TextLoader(file_path)\nLoad text file.\ndocument_loaders.tomarkdown.ToMarkdownLoader(...)\nLoad HTML using 2markdown API.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-37", "text": "document_loaders.tomarkdown.ToMarkdownLoader(...)\nLoad HTML using 2markdown API.\ndocument_loaders.toml.TomlLoader(source)\nLoad TOML files.\ndocument_loaders.trello.TrelloLoader(client,\u00a0...)\nLoad cards from a Trello board.\ndocument_loaders.tsv.UnstructuredTSVLoader(...)\nLoad TSV files using Unstructured.\ndocument_loaders.twitter.TwitterTweetLoader(...)\nLoad Twitter tweets.\ndocument_loaders.unstructured.UnstructuredAPIFileIOLoader(file)\nLoad files using Unstructured API.\ndocument_loaders.unstructured.UnstructuredAPIFileLoader([...])\nLoad files using Unstructured API.\ndocument_loaders.unstructured.UnstructuredBaseLoader([...])\nBase Loader that uses Unstructured.\ndocument_loaders.unstructured.UnstructuredFileIOLoader(file)\nLoad files using Unstructured.\ndocument_loaders.unstructured.UnstructuredFileLoader(...)\nLoad files using Unstructured.\ndocument_loaders.url.UnstructuredURLLoader(urls)\nLoad files from remote URLs using Unstructured.\ndocument_loaders.url_playwright.PlaywrightEvaluator()\nAbstract base class for all evaluators.\ndocument_loaders.url_playwright.PlaywrightURLLoader(urls)\nLoad HTML pages with Playwright and parse with Unstructured.\ndocument_loaders.url_playwright.UnstructuredHtmlEvaluator([...])\nEvaluates the page HTML content using the unstructured library.\ndocument_loaders.url_selenium.SeleniumURLLoader(urls)\nLoad HTML pages with Selenium and parse with Unstructured.\ndocument_loaders.weather.WeatherDataLoader(...)\nLoad weather data with Open Weather Map API.\ndocument_loaders.web_base.WebBaseLoader([...])\nLoad HTML pages using urllib and parse them with `BeautifulSoup'.\ndocument_loaders.whatsapp_chat.WhatsAppChatLoader(path)\nLoad WhatsApp messages text file.\ndocument_loaders.wikipedia.WikipediaLoader(query)\nLoad from Wikipedia.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-38", "text": "document_loaders.wikipedia.WikipediaLoader(query)\nLoad from Wikipedia.\ndocument_loaders.word_document.Docx2txtLoader(...)\nLoad DOCX file using docx2txt and chunks at character level.\ndocument_loaders.word_document.UnstructuredWordDocumentLoader(...)\nLoad Microsoft Word file using Unstructured.\ndocument_loaders.xml.UnstructuredXMLLoader(...)\nLoad XML file using Unstructured.\ndocument_loaders.xorbits.XorbitsLoader(...)\nLoad Xorbits DataFrame.\ndocument_loaders.youtube.GoogleApiClient([...])\nGeneric Google API Client.\ndocument_loaders.youtube.GoogleApiYoutubeLoader(...)\nLoad all Videos from a YouTube Channel.\ndocument_loaders.youtube.YoutubeLoader(video_id)\nLoad YouTube transcripts.\nFunctions\u00b6\ndocument_loaders.base_o365.fetch_mime_types(...)\nFetch the mime types for the specified file types.\ndocument_loaders.chatgpt.concatenate_rows(...)\nCombine message information in a readable format ready to be used.\ndocument_loaders.facebook_chat.concatenate_rows(row)\nCombine message information in a readable format ready to be used.\ndocument_loaders.helpers.detect_file_encodings(...)\nTry to detect the file encoding.\ndocument_loaders.notebook.concatenate_cells(...)\nCombine cells information in a readable format ready to be used.\ndocument_loaders.notebook.remove_newlines(x)\nRecursively remove newlines, no matter the data structure they are stored in.\ndocument_loaders.parsers.pdf.extract_from_images_with_rapidocr(images)\nExtract text from images with RapidOCR.\ndocument_loaders.parsers.registry.get_parser(...)\nGet a parser by parser name.\ndocument_loaders.rocksetdb.default_joiner(docs)\nDefault joiner for content columns.\ndocument_loaders.telegram.concatenate_rows(row)\nCombine message information in a readable format ready to be used.\ndocument_loaders.telegram.text_to_docs(text)\nConvert a string or list of strings to a list of Documents with metadata.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-39", "text": "Convert a string or list of strings to a list of Documents with metadata.\ndocument_loaders.unstructured.get_elements_from_api([...])\nRetrieve a list of elements from the Unstructured API.\ndocument_loaders.unstructured.satisfies_min_unstructured_version(...)\nCheck if the installed Unstructured version exceeds the minimum version for the feature in question.\ndocument_loaders.unstructured.validate_unstructured_version(...)\nRaise an error if the Unstructured version does not exceed the specified minimum.\ndocument_loaders.whatsapp_chat.concatenate_rows(...)\nCombine message information in a readable format ready to be used.\nlangchain.document_transformers\u00b6\nDocument Transformers are classes to transform Documents.\nDocument Transformers usually used to transform a lot of Documents in a single run.\nClass hierarchy:\nBaseDocumentTransformer --> <name>  # Examples: DoctranQATransformer, DoctranTextTranslator\nMain helpers:\nDocument\nClasses\u00b6\ndocument_transformers.beautiful_soup_transformer.BeautifulSoupTransformer()\nTransform HTML content by extracting specific tags and removing unwanted ones.\ndocument_transformers.doctran_text_extract.DoctranPropertyExtractor(...)\nExtract properties from text documents using doctran.\ndocument_transformers.doctran_text_qa.DoctranQATransformer([...])\nExtract QA from text documents using doctran.\ndocument_transformers.doctran_text_translate.DoctranTextTranslator([...])\nTranslate text documents using doctran.\ndocument_transformers.embeddings_redundant_filter.EmbeddingsClusteringFilter\nPerform K-means clustering on document vectors.\ndocument_transformers.embeddings_redundant_filter.EmbeddingsRedundantFilter\nFilter that drops redundant documents by comparing their embeddings.\ndocument_transformers.google_translate.GoogleTranslateTransformer(...)\nTranslate text documents using Google Cloud Translation.\ndocument_transformers.html2text.Html2TextTransformer([...])\nReplace occurrences of a particular search pattern with a replacement string", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-40", "text": "Replace occurrences of a particular search pattern with a replacement string\ndocument_transformers.long_context_reorder.LongContextReorder\nLost in the middle: Performance degrades when models must access relevant information in the middle of long contexts.\ndocument_transformers.nuclia_text_transform.NucliaTextTransformer(nua)\nThe Nuclia Understanding API splits into paragraphs and sentences, identifies entities, provides a summary of the text and generates embeddings for all sentences.\ndocument_transformers.openai_functions.OpenAIMetadataTagger\nExtract metadata tags from document contents using OpenAI functions.\nFunctions\u00b6\ndocument_transformers.beautiful_soup_transformer.get_navigable_strings(element)\ndocument_transformers.embeddings_redundant_filter.get_stateful_documents(...)\nConvert a list of documents to a list of documents with state.\ndocument_transformers.openai_functions.create_metadata_tagger(...)\nCreate a DocumentTransformer that uses an OpenAI function chain to automatically\nlangchain.embeddings\u00b6\nEmbedding models  are wrappers around embedding models\nfrom different APIs and services.\nEmbedding models can be LLMs or not.\nClass hierarchy:\nEmbeddings --> <name>Embeddings  # Examples: OpenAIEmbeddings, HuggingFaceEmbeddings\nClasses\u00b6\nembeddings.aleph_alpha.AlephAlphaAsymmetricSemanticEmbedding\nAleph Alpha's asymmetric semantic embedding.\nembeddings.aleph_alpha.AlephAlphaSymmetricSemanticEmbedding\nThe symmetric version of the Aleph Alpha's semantic embeddings.\nembeddings.awa.AwaEmbeddings\nEmbedding documents and queries with Awa DB.\nembeddings.azure_openai.AzureOpenAIEmbeddings\nAzure OpenAI Embeddings API.\nembeddings.baidu_qianfan_endpoint.QianfanEmbeddingsEndpoint\nBaidu Qianfan Embeddings embedding models.\nembeddings.bedrock.BedrockEmbeddings\nBedrock embedding models.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-41", "text": "embeddings.bedrock.BedrockEmbeddings\nBedrock embedding models.\nembeddings.cache.CacheBackedEmbeddings(...)\nInterface for caching results from embedding models.\nembeddings.clarifai.ClarifaiEmbeddings\nClarifai embedding models.\nembeddings.cohere.CohereEmbeddings\nCohere embedding models.\nembeddings.dashscope.DashScopeEmbeddings\nDashScope embedding models.\nembeddings.deepinfra.DeepInfraEmbeddings\nDeep Infra's embedding inference service.\nembeddings.edenai.EdenAiEmbeddings\nEdenAI embedding.\nembeddings.elasticsearch.ElasticsearchEmbeddings(...)\nElasticsearch embedding models.\nembeddings.embaas.EmbaasEmbeddings\nEmbaas's embedding service.\nembeddings.embaas.EmbaasEmbeddingsPayload\nPayload for the Embaas embeddings API.\nembeddings.ernie.ErnieEmbeddings\nErnie Embeddings V1 embedding models.\nembeddings.fake.DeterministicFakeEmbedding\nFake embedding model that always returns the same embedding vector for the same text.\nembeddings.fake.FakeEmbeddings\nFake embedding model.\nembeddings.fastembed.FastEmbedEmbeddings\nQdrant FastEmbedding models.\nembeddings.google_palm.GooglePalmEmbeddings\nGoogle's PaLM Embeddings APIs.\nembeddings.gpt4all.GPT4AllEmbeddings\nGPT4All embedding models.\nembeddings.gradient_ai.GradientEmbeddings\nGradient.ai Embedding models.\nembeddings.gradient_ai.TinyAsyncGradientEmbeddingClient([...])\nA helper tool to embed Gradient.\nembeddings.huggingface.HuggingFaceBgeEmbeddings\nHuggingFace BGE sentence_transformers embedding models.\nembeddings.huggingface.HuggingFaceEmbeddings\nHuggingFace sentence_transformers embedding models.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-42", "text": "HuggingFace sentence_transformers embedding models.\nembeddings.huggingface.HuggingFaceInferenceAPIEmbeddings\nEmbed texts using the HuggingFace API.\nembeddings.huggingface.HuggingFaceInstructEmbeddings\nWrapper around sentence_transformers embedding models.\nembeddings.huggingface_hub.HuggingFaceHubEmbeddings\nHuggingFaceHub embedding models.\nembeddings.javelin_ai_gateway.JavelinAIGatewayEmbeddings\nWrapper around embeddings LLMs in the Javelin AI Gateway.\nembeddings.jina.JinaEmbeddings\nJina embedding models.\nembeddings.johnsnowlabs.JohnSnowLabsEmbeddings\nJohnSnowLabs embedding models\nembeddings.llamacpp.LlamaCppEmbeddings\nllama.cpp embedding models.\nembeddings.llm_rails.LLMRailsEmbeddings\nLLMRails embedding models.\nembeddings.localai.LocalAIEmbeddings\nLocalAI embedding models.\nembeddings.minimax.MiniMaxEmbeddings\nMiniMax's embedding service.\nembeddings.mlflow_gateway.MlflowAIGatewayEmbeddings\nWrapper around embeddings LLMs in the MLflow AI Gateway.\nembeddings.modelscope_hub.ModelScopeEmbeddings\nModelScopeHub embedding models.\nembeddings.mosaicml.MosaicMLInstructorEmbeddings\nMosaicML embedding service.\nembeddings.nlpcloud.NLPCloudEmbeddings\nNLP Cloud embedding models.\nembeddings.octoai_embeddings.OctoAIEmbeddings\nOctoAI Compute Service embedding models.\nembeddings.ollama.OllamaEmbeddings\nOllama locally runs large language models.\nembeddings.openai.OpenAIEmbeddings\nOpenAI embedding models.\nembeddings.sagemaker_endpoint.EmbeddingsContentHandler()\nContent handler for LLM class.\nembeddings.sagemaker_endpoint.SagemakerEndpointEmbeddings\nCustom Sagemaker Inference Endpoints.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-43", "text": "Custom Sagemaker Inference Endpoints.\nembeddings.self_hosted.SelfHostedEmbeddings\nCustom embedding models on self-hosted remote hardware.\nembeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings\nHuggingFace embedding models on self-hosted remote hardware.\nembeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings\nHuggingFace InstructEmbedding models on self-hosted remote hardware.\nembeddings.spacy_embeddings.SpacyEmbeddings\nEmbeddings by SpaCy models.\nembeddings.tensorflow_hub.TensorflowHubEmbeddings\nTensorflowHub embedding models.\nembeddings.vertexai.VertexAIEmbeddings\nGoogle Cloud VertexAI embedding models.\nembeddings.voyageai.VoyageEmbeddings\nVoyage embedding models.\nembeddings.xinference.XinferenceEmbeddings([...])\nXinference embedding models.\nFunctions\u00b6\nembeddings.dashscope.embed_with_retry(...)\nUse tenacity to retry the embedding call.\nembeddings.google_palm.embed_with_retry(...)\nUse tenacity to retry the completion call.\nembeddings.localai.async_embed_with_retry(...)\nUse tenacity to retry the embedding call.\nembeddings.localai.embed_with_retry(...)\nUse tenacity to retry the embedding call.\nembeddings.minimax.embed_with_retry(...)\nUse tenacity to retry the completion call.\nembeddings.openai.async_embed_with_retry(...)\nUse tenacity to retry the embedding call.\nembeddings.openai.embed_with_retry(...)\nUse tenacity to retry the embedding call.\nembeddings.self_hosted_hugging_face.load_embedding_model(...)\nLoad the embedding model.\nembeddings.voyageai.embed_with_retry(...)\nUse tenacity to retry the embedding call.\nlangchain.evaluation\u00b6\nEvaluation chains for grading LLM and Chain outputs.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-44", "text": "langchain.evaluation\u00b6\nEvaluation chains for grading LLM and Chain outputs.\nThis module contains off-the-shelf evaluation chains for grading the output of\nLangChain primitives such as language models and chains.\nLoading an evaluator\nTo load an evaluator, you can use the load_evaluators or\nload_evaluator functions with the\nnames of the evaluators to load.\nfrom langchain.evaluation import load_evaluator\nevaluator = load_evaluator(\"qa\")\nevaluator.evaluate_strings(\n    prediction=\"We sold more than 40,000 units last week\",\n    input=\"How many units did we sell last week?\",\n    reference=\"We sold 32,378 units\",\n)\nThe evaluator must be one of EvaluatorType.\nDatasets\nTo load one of the LangChain HuggingFace datasets, you can use the load_dataset function with the\nname of the dataset to load.\nfrom langchain.evaluation import load_dataset\nds = load_dataset(\"llm-math\")\nSome common use cases for evaluation include:\nGrading the accuracy of a response against ground truth answers: QAEvalChain\nComparing the output of two models: PairwiseStringEvalChain or LabeledPairwiseStringEvalChain when there is additionally a reference label.\nJudging the efficacy of an agent\u2019s tool usage: TrajectoryEvalChain\nChecking whether an output complies with a set of criteria: CriteriaEvalChain or LabeledCriteriaEvalChain when there is additionally a reference label.\nComputing semantic difference between a prediction and reference: EmbeddingDistanceEvalChain or between two predictions: PairwiseEmbeddingDistanceEvalChain\nMeasuring the string distance between a prediction and reference StringDistanceEvalChain or between two predictions PairwiseStringDistanceEvalChain\nLow-level API\nThese evaluators implement one of the following interfaces:\nStringEvaluator: Evaluate a prediction string against a reference label and/or input context.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-45", "text": "StringEvaluator: Evaluate a prediction string against a reference label and/or input context.\nPairwiseStringEvaluator: Evaluate two prediction strings against each other. Useful for scoring preferences, measuring similarity between two chain or llm agents, or comparing outputs on similar inputs.\nAgentTrajectoryEvaluator Evaluate the full sequence of actions taken by an agent.\nThese interfaces enable easier composability and usage within a higher level evaluation framework.\nClasses\u00b6\nevaluation.agents.trajectory_eval_chain.TrajectoryEval\nA named tuple containing the score and reasoning for a trajectory.\nevaluation.agents.trajectory_eval_chain.TrajectoryEvalChain\nA chain for evaluating ReAct style agents.\nevaluation.agents.trajectory_eval_chain.TrajectoryOutputParser\nTrajectory output parser.\nevaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain\nA chain for comparing two outputs, such as the outputs\nevaluation.comparison.eval_chain.PairwiseStringEvalChain\nA chain for comparing two outputs, such as the outputs\nevaluation.comparison.eval_chain.PairwiseStringResultOutputParser\nA parser for the output of the PairwiseStringEvalChain.\nevaluation.criteria.eval_chain.Criteria(value)\nA Criteria to evaluate.\nevaluation.criteria.eval_chain.CriteriaEvalChain\nLLM Chain for evaluating runs against criteria.\nevaluation.criteria.eval_chain.CriteriaResultOutputParser\nA parser for the output of the CriteriaEvalChain.\nevaluation.criteria.eval_chain.LabeledCriteriaEvalChain\nCriteria evaluation chain that requires references.\nevaluation.embedding_distance.base.EmbeddingDistance(value)\nEmbedding Distance Metric.\nevaluation.embedding_distance.base.EmbeddingDistanceEvalChain\nUse embedding distances to score semantic difference between a prediction and reference.\nevaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain\nUse embedding distances to score semantic difference between two predictions.\nevaluation.exact_match.base.ExactMatchStringEvaluator(*)\nCompute an exact match between the prediction and the reference.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-46", "text": "Compute an exact match between the prediction and the reference.\nevaluation.parsing.base.JsonEqualityEvaluator([...])\nEvaluates whether the prediction is equal to the reference after\nevaluation.parsing.base.JsonValidityEvaluator(...)\nEvaluates whether the prediction is valid JSON.\nevaluation.parsing.json_distance.JsonEditDistanceEvaluator([...])\nAn evaluator that calculates the edit distance between JSON strings.\nevaluation.parsing.json_schema.JsonSchemaEvaluator(...)\nAn evaluator that validates a JSON prediction against a JSON schema reference.\nevaluation.qa.eval_chain.ContextQAEvalChain\nLLM Chain for evaluating QA w/o GT based on context\nevaluation.qa.eval_chain.CotQAEvalChain\nLLM Chain for evaluating QA using chain of thought reasoning.\nevaluation.qa.eval_chain.QAEvalChain\nLLM Chain for evaluating question answering.\nevaluation.qa.generate_chain.QAGenerateChain\nLLM Chain for generating examples for question answering.\nevaluation.regex_match.base.RegexMatchStringEvaluator(*)\nCompute a regex match between the prediction and the reference.\nevaluation.schema.AgentTrajectoryEvaluator()\nInterface for evaluating agent trajectories.\nevaluation.schema.EvaluatorType(value[,\u00a0...])\nThe types of the evaluators.\nevaluation.schema.LLMEvalChain\nA base class for evaluators that use an LLM.\nevaluation.schema.PairwiseStringEvaluator()\nCompare the output of two models (or two outputs of the same model).\nevaluation.schema.StringEvaluator()\nGrade, tag, or otherwise evaluate predictions relative to their inputs and/or reference labels.\nevaluation.scoring.eval_chain.LabeledScoreStringEvalChain\nA chain for scoring the output of a model on a scale of 1-10.\nevaluation.scoring.eval_chain.ScoreStringEvalChain\nA chain for scoring on a scale of 1-10 the output of a model.\nevaluation.scoring.eval_chain.ScoreStringResultOutputParser", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-47", "text": "evaluation.scoring.eval_chain.ScoreStringResultOutputParser\nA parser for the output of the ScoreStringEvalChain.\nevaluation.string_distance.base.PairwiseStringDistanceEvalChain\nCompute string edit distances between two predictions.\nevaluation.string_distance.base.StringDistance(value)\nDistance metric to use.\nevaluation.string_distance.base.StringDistanceEvalChain\nCompute string distances between the prediction and the reference.\nFunctions\u00b6\nevaluation.comparison.eval_chain.resolve_pairwise_criteria(...)\nResolve the criteria for the pairwise evaluator.\nevaluation.criteria.eval_chain.resolve_criteria(...)\nResolve the criteria to evaluate.\nevaluation.loading.load_dataset(uri)\nLoad a dataset from the LangChainDatasets on HuggingFace.\nevaluation.loading.load_evaluator(evaluator,\u00a0*)\nLoad the requested evaluation chain specified by a string.\nevaluation.loading.load_evaluators(evaluators,\u00a0*)\nLoad evaluators specified by a list of evaluator types.\nevaluation.scoring.eval_chain.resolve_criteria(...)\nResolve the criteria for the pairwise evaluator.\nlangchain.graphs\u00b6\nGraphs provide a natural language interface to graph databases.\nClasses\u00b6\ngraphs.arangodb_graph.ArangoGraph(db)\nArangoDB wrapper for graph operations.\ngraphs.falkordb_graph.FalkorDBGraph(database)\nFalkorDB wrapper for graph operations.\ngraphs.graph_document.GraphDocument\nRepresents a graph document consisting of nodes and relationships.\ngraphs.graph_document.Node\nRepresents a node in a graph with associated properties.\ngraphs.graph_document.Relationship\nRepresents a directed relationship between two nodes in a graph.\ngraphs.graph_store.GraphStore()\nAn abstract class wrapper for graph operations.\ngraphs.hugegraph.HugeGraph([username,\u00a0...])\nHugeGraph wrapper for graph operations.\ngraphs.kuzu_graph.KuzuGraph(db[,\u00a0database])\nK\u00f9zu wrapper for graph operations.\ngraphs.memgraph_graph.MemgraphGraph(url,\u00a0...)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-48", "text": "graphs.memgraph_graph.MemgraphGraph(url,\u00a0...)\nMemgraph wrapper for graph operations.\ngraphs.nebula_graph.NebulaGraph(space[,\u00a0...])\nNebulaGraph wrapper for graph operations.\ngraphs.neo4j_graph.Neo4jGraph([url,\u00a0...])\nNeo4j wrapper for graph operations.\ngraphs.neptune_graph.NeptuneGraph(host[,\u00a0...])\nNeptune wrapper for graph operations.\ngraphs.neptune_graph.NeptuneQueryException(...)\nA class to handle queries that fail to execute\ngraphs.networkx_graph.KnowledgeTriple(...)\nA triple in the graph.\ngraphs.networkx_graph.NetworkxEntityGraph([graph])\nNetworkx wrapper for entity graph operations.\ngraphs.rdf_graph.RdfGraph([source_file,\u00a0...])\nRDFlib wrapper for graph operations.\nFunctions\u00b6\ngraphs.arangodb_graph.get_arangodb_client([...])\nGet the Arango DB client from credentials.\ngraphs.networkx_graph.get_entities(entity_str)\nExtract entities from entity string.\ngraphs.networkx_graph.parse_triples(...)\nParse knowledge triples from the knowledge string.\nlangchain.hub\u00b6\nInterface with the LangChain Hub.\nFunctions\u00b6\nhub.pull(owner_repo_commit,\u00a0*[,\u00a0api_url,\u00a0...])\nPulls an object from the hub and returns it as a LangChain object.\nhub.push(repo_full_name,\u00a0object,\u00a0*[,\u00a0...])\nPushes an object to the hub and returns the URL it can be viewed at in a browser.\nlangchain.indexes\u00b6\nCode to support various indexing workflows.\nProvides code to:\nCreate knowledge graphs from data.\nSupport indexing workflows from LangChain data loaders to vectorstores.\nFor indexing workflows, this code is used to avoid writing duplicated content\ninto the vectostore and to avoid over-writing content if it\u2019s unchanged.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-49", "text": "into the vectostore and to avoid over-writing content if it\u2019s unchanged.\nImportantly, this keeps on working even if the content being written is derived\nvia a set of transformations from some source content (e.g., indexing children\ndocuments that were derived from parent documents by chunking.)\nClasses\u00b6\nindexes.base.RecordManager(namespace)\nAn abstract base class representing the interface for a record manager.\nindexes.graph.GraphIndexCreator\nFunctionality to create graph index.\nindexes.vectorstore.VectorStoreIndexWrapper\nWrapper around a vectorstore for easy access.\nindexes.vectorstore.VectorstoreIndexCreator\nLogic for creating indexes.\nFunctions\u00b6\nlangchain.llms\u00b6\nLLM classes provide\naccess to the large language model (LLM) APIs and services.\nClass hierarchy:\nBaseLanguageModel --> BaseLLM --> LLM --> <name>  # Examples: AI21, HuggingFaceHub, OpenAI\nMain helpers:\nLLMResult, PromptValue,\nCallbackManagerForLLMRun, AsyncCallbackManagerForLLMRun,\nCallbackManager, AsyncCallbackManager,\nAIMessage, BaseMessage\nClasses\u00b6\nllms.ai21.AI21\nAI21 large language models.\nllms.ai21.AI21PenaltyData\nParameters for AI21 penalty data.\nllms.aleph_alpha.AlephAlpha\nAleph Alpha large language models.\nllms.amazon_api_gateway.AmazonAPIGateway\nAmazon API Gateway to access LLM models hosted on AWS.\nllms.amazon_api_gateway.ContentHandlerAmazonAPIGateway()\nAdapter to prepare the inputs from Langchain to a format that LLM model expects.\nllms.anthropic.Anthropic\nAnthropic large language models.\nllms.anyscale.Anyscale\nAnyscale large language models.\nllms.arcee.Arcee\nArcee's Domain Adapted Language Models (DALMs).\nllms.aviary.Aviary", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-50", "text": "llms.aviary.Aviary\nAviary hosted models.\nllms.aviary.AviaryBackend(backend_url,\u00a0bearer)\nAviary backend.\nllms.azureml_endpoint.AzureMLEndpointClient(...)\nAzureML Managed Endpoint client.\nllms.azureml_endpoint.AzureMLOnlineEndpoint\nAzure ML Online Endpoint models.\nllms.azureml_endpoint.ContentFormatterBase()\nTransform request and response of AzureML endpoint to match with required schema.\nllms.azureml_endpoint.DollyContentFormatter()\nContent handler for the Dolly-v2-12b model\nllms.azureml_endpoint.GPT2ContentFormatter()\nContent handler for GPT2\nllms.azureml_endpoint.HFContentFormatter()\nContent handler for LLMs from the HuggingFace catalog.\nllms.azureml_endpoint.LlamaContentFormatter()\nContent formatter for LLaMa\nllms.azureml_endpoint.OSSContentFormatter()\nDeprecated: Kept for backwards compatibility\nllms.baidu_qianfan_endpoint.QianfanLLMEndpoint\nBaidu Qianfan hosted open source or customized models.\nllms.bananadev.Banana\nBanana large language models.\nllms.base.BaseLLM\nBase LLM abstract interface.\nllms.base.LLM\nBase LLM abstract class.\nllms.baseten.Baseten\nBaseten models.\nllms.beam.Beam\nBeam API for gpt2 large language model.\nllms.bedrock.Bedrock\nBedrock models.\nllms.bedrock.BedrockBase\nBase class for Bedrock models.\nllms.bedrock.LLMInputOutputAdapter()\nAdapter class to prepare the inputs from Langchain to a format that LLM model expects.\nllms.bittensor.NIBittensorLLM\nNIBittensor LLMs", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-51", "text": "llms.bittensor.NIBittensorLLM\nNIBittensor LLMs\nllms.cerebriumai.CerebriumAI\nCerebriumAI large language models.\nllms.chatglm.ChatGLM\nChatGLM LLM service.\nllms.clarifai.Clarifai\nClarifai large language models.\nllms.cohere.BaseCohere\nBase class for Cohere models.\nllms.cohere.Cohere\nCohere large language models.\nllms.ctransformers.CTransformers\nC Transformers LLM models.\nllms.ctranslate2.CTranslate2\nCTranslate2 language model.\nllms.databricks.Databricks\nDatabricks serving endpoint or a cluster driver proxy app for LLM.\nllms.deepinfra.DeepInfra\nDeepInfra models.\nllms.deepsparse.DeepSparse\nNeural Magic DeepSparse LLM interface.\nllms.edenai.EdenAI\nWrapper around edenai models.\nllms.fake.FakeListLLM\nFake LLM for testing purposes.\nllms.fake.FakeStreamingListLLM\nFake streaming list LLM for testing purposes.\nllms.fireworks.Fireworks\nFireworks models.\nllms.forefrontai.ForefrontAI\nForefrontAI large language models.\nllms.gigachat.GigaChat\nGigaChat large language models API.\nllms.google_palm.GooglePalm\nGoogle PaLM models.\nllms.gooseai.GooseAI\nGooseAI large language models.\nllms.gpt4all.GPT4All\nGPT4All language models.\nllms.gradient_ai.GradientLLM\nGradient.ai LLM Endpoints.\nllms.gradient_ai.TrainResult\nTrain result.\nllms.huggingface_endpoint.HuggingFaceEndpoint", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-52", "text": "Train result.\nllms.huggingface_endpoint.HuggingFaceEndpoint\nHuggingFace Endpoint models.\nllms.huggingface_hub.HuggingFaceHub\nHuggingFaceHub  models.\nllms.huggingface_pipeline.HuggingFacePipeline\nHuggingFace Pipeline API.\nllms.huggingface_text_gen_inference.HuggingFaceTextGenInference\nHuggingFace text generation API.\nllms.human.HumanInputLLM\nIt returns user input as the response.\nllms.javelin_ai_gateway.JavelinAIGateway\nJavelin AI Gateway LLMs.\nllms.javelin_ai_gateway.Params\nParameters for the Javelin AI Gateway LLM.\nllms.koboldai.KoboldApiLLM\nKobold API language model.\nllms.llamacpp.LlamaCpp\nllama.cpp model.\nllms.manifest.ManifestWrapper\nHazyResearch's Manifest library.\nllms.minimax.Minimax\nWrapper around Minimax large language models.\nllms.minimax.MinimaxCommon\nCommon parameters for Minimax large language models.\nllms.mlflow_ai_gateway.MlflowAIGateway\nWrapper around completions LLMs in the MLflow AI Gateway.\nllms.mlflow_ai_gateway.Params\nParameters for the MLflow AI Gateway LLM.\nllms.modal.Modal\nModal large language models.\nllms.mosaicml.MosaicML\nMosaicML LLM service.\nllms.nlpcloud.NLPCloud\nNLPCloud large language models.\nllms.octoai_endpoint.OctoAIEndpoint\nOctoAI LLM Endpoints.\nllms.ollama.Ollama\nOllama locally runs large language models.\nllms.opaqueprompts.OpaquePrompts\nAn LLM wrapper that uses OpaquePrompts to sanitize prompts.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-53", "text": "An LLM wrapper that uses OpaquePrompts to sanitize prompts.\nllms.openai.AzureOpenAI\nAzure-specific OpenAI large language models.\nllms.openai.BaseOpenAI\nBase OpenAI large language model class.\nllms.openai.OpenAI\nOpenAI large language models.\nllms.openai.OpenAIChat\nOpenAI Chat large language models.\nllms.openllm.IdentifyingParams\nParameters for identifying a model as a typed dict.\nllms.openllm.OpenLLM\nOpenLLM, supporting both in-process model instance and remote OpenLLM servers.\nllms.openlm.OpenLM\nOpenLM models.\nllms.pai_eas_endpoint.PaiEasEndpoint\nLangchain LLM class to help to access eass llm service.\nllms.petals.Petals\nPetals Bloom models.\nllms.pipelineai.PipelineAI\nPipelineAI large language models.\nllms.predibase.Predibase\nUse your Predibase models with Langchain.\nllms.predictionguard.PredictionGuard\nPrediction Guard large language models.\nllms.promptlayer_openai.PromptLayerOpenAI\nPromptLayer OpenAI large language models.\nllms.promptlayer_openai.PromptLayerOpenAIChat\nWrapper around OpenAI large language models.\nllms.replicate.Replicate\nReplicate models.\nllms.rwkv.RWKV\nRWKV language models.\nllms.sagemaker_endpoint.ContentHandlerBase()\nA handler class to transform input from LLM to a format that SageMaker endpoint expects.\nllms.sagemaker_endpoint.LLMContentHandler()\nContent handler for LLM class.\nllms.sagemaker_endpoint.LineIterator(stream)\nA helper class for parsing the byte stream input.\nllms.sagemaker_endpoint.SagemakerEndpoint\nSagemaker Inference Endpoint models.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-54", "text": "llms.sagemaker_endpoint.SagemakerEndpoint\nSagemaker Inference Endpoint models.\nllms.self_hosted.SelfHostedPipeline\nModel inference on self-hosted remote hardware.\nllms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM\nHuggingFace Pipeline API to run on self-hosted remote hardware.\nllms.stochasticai.StochasticAI\nStochasticAI large language models.\nllms.symblai_nebula.Nebula\nNebula Service models.\nllms.textgen.TextGen\ntext-generation-webui models.\nllms.titan_takeoff.TitanTakeoff\nWrapper around Titan Takeoff APIs.\nllms.titan_takeoff_pro.TitanTakeoffPro\nCreate a new model by parsing and validating input data from keyword arguments.\nllms.together.Together\nWrapper around Together AI models.\nllms.tongyi.Tongyi\nTongyi Qwen large language models.\nllms.vertexai.VertexAI\nGoogle Vertex AI large language models.\nllms.vertexai.VertexAIModelGarden\nLarge language models served from Vertex AI Model Garden.\nllms.vllm.VLLM\nVLLM language model.\nllms.vllm.VLLMOpenAI\nvLLM OpenAI-compatible API client\nllms.writer.Writer\nWriter large language models.\nllms.xinference.Xinference\nWrapper for accessing Xinference's large-scale model inference service.\nllms.yandex.YandexGPT\nYandex large language models.\nFunctions\u00b6\nllms.anyscale.create_llm_result(choices,\u00a0...)\nCreate the LLMResult from the choices and prompts.\nllms.anyscale.update_token_usage(keys,\u00a0...)\nUpdate token usage.\nllms.aviary.get_completions(model,\u00a0prompt[,\u00a0...])\nGet completions from Aviary models.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-55", "text": "Get completions from Aviary models.\nllms.aviary.get_models()\nList available models\nllms.base.create_base_retry_decorator(...[,\u00a0...])\nCreate a retry decorator for a given LLM and provided list of error types.\nllms.base.get_prompts(params,\u00a0prompts)\nGet prompts that are already cached.\nllms.base.update_cache(existing_prompts,\u00a0...)\nUpdate the cache and get the LLM output.\nllms.cohere.acompletion_with_retry(llm,\u00a0**kwargs)\nUse tenacity to retry the completion call.\nllms.cohere.completion_with_retry(llm,\u00a0**kwargs)\nUse tenacity to retry the completion call.\nllms.databricks.get_default_api_token()\nGets the default Databricks personal access token.\nllms.databricks.get_default_host()\nGets the default Databricks workspace hostname.\nllms.databricks.get_repl_context()\nGets the notebook REPL context if running inside a Databricks notebook.\nllms.fireworks.acompletion_with_retry(llm,\u00a0...)\nUse tenacity to retry the completion call.\nllms.fireworks.acompletion_with_retry_batching(...)\nUse tenacity to retry the completion call.\nllms.fireworks.acompletion_with_retry_streaming(...)\nUse tenacity to retry the completion call for streaming.\nllms.fireworks.completion_with_retry(llm,\u00a0...)\nUse tenacity to retry the completion call.\nllms.fireworks.completion_with_retry_batching(...)\nUse tenacity to retry the completion call.\nllms.fireworks.conditional_decorator(...)\nllms.google_palm.generate_with_retry(llm,\u00a0...)\nUse tenacity to retry the completion call.\nllms.koboldai.clean_url(url)\nRemove trailing slash and /api from url if present.\nllms.loading.load_llm(file)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-56", "text": "llms.loading.load_llm(file)\nLoad LLM from file.\nllms.loading.load_llm_from_config(config)\nLoad LLM from Config Dict.\nllms.openai.acompletion_with_retry(llm[,\u00a0...])\nUse tenacity to retry the async completion call.\nllms.openai.completion_with_retry(llm[,\u00a0...])\nUse tenacity to retry the completion call.\nllms.openai.update_token_usage(keys,\u00a0...)\nUpdate token usage.\nllms.symblai_nebula.completion_with_retry(...)\nUse tenacity to retry the completion call.\nllms.symblai_nebula.make_request(self,\u00a0...)\nGenerate text from the model.\nllms.tongyi.generate_with_retry(llm,\u00a0**kwargs)\nUse tenacity to retry the completion call.\nllms.tongyi.stream_generate_with_retry(llm,\u00a0...)\nUse tenacity to retry the completion call.\nllms.utils.enforce_stop_tokens(text,\u00a0stop)\nCut off the text as soon as any stop words occur.\nllms.vertexai.acompletion_with_retry(llm,\u00a0*args)\nUse tenacity to retry the completion call.\nllms.vertexai.completion_with_retry(llm,\u00a0*args)\nUse tenacity to retry the completion call.\nllms.vertexai.is_codey_model(model_name)\nReturns True if the model name is a Codey model.\nllms.vertexai.stream_completion_with_retry(...)\nUse tenacity to retry the completion call.\nlangchain.load\u00b6\nSerialization and deserialization.\nClasses\u00b6\nload.load.Reviver([secrets_map,\u00a0...])\nReviver for JSON objects.\nload.serializable.BaseSerialized\nBase class for serialized objects.\nload.serializable.Serializable\nSerializable base class.\nload.serializable.SerializedConstructor\nSerialized constructor.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-57", "text": "Serializable base class.\nload.serializable.SerializedConstructor\nSerialized constructor.\nload.serializable.SerializedNotImplemented\nSerialized not implemented.\nload.serializable.SerializedSecret\nSerialized secret.\nFunctions\u00b6\nload.dump.default(obj)\nReturn a default value for a Serializable object or a SerializedNotImplemented object.\nload.dump.dumpd(obj)\nReturn a json dict representation of an object.\nload.dump.dumps(obj,\u00a0*[,\u00a0pretty])\nReturn a json string representation of an object.\nload.load.load(obj,\u00a0*[,\u00a0secrets_map,\u00a0...])\nRevive a LangChain class from a JSON object.\nload.load.loads(text,\u00a0*[,\u00a0secrets_map,\u00a0...])\nRevive a LangChain class from a JSON string.\nload.serializable.to_json_not_implemented(obj)\nSerialize a \"not implemented\" object.\nload.serializable.try_neq_default(value,\u00a0...)\nlangchain.memory\u00b6\nMemory maintains Chain state, incorporating context from past runs.\nClass hierarchy for Memory:\nBaseMemory --> BaseChatMemory --> <name>Memory  # Examples: ZepMemory, MotorheadMemory\nMain helpers:\nBaseChatMessageHistory\nChat Message History stores the chat message history in different stores.\nClass hierarchy for ChatMessageHistory:\nBaseChatMessageHistory --> <name>ChatMessageHistory  # Example: ZepChatMessageHistory\nMain helpers:\nAIMessage, BaseMessage, HumanMessage\nClasses\u00b6\nmemory.buffer.ConversationBufferMemory\nBuffer for storing conversation memory.\nmemory.buffer.ConversationStringBufferMemory\nBuffer for storing conversation memory.\nmemory.buffer_window.ConversationBufferWindowMemory\nBuffer for storing conversation memory inside a limited size window.\nmemory.chat_memory.BaseChatMemory\nAbstract base class for chat memory.\nmemory.chat_message_histories.cassandra.CassandraChatMessageHistory(...)\nChat message history that stores history in Cassandra.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-58", "text": "Chat message history that stores history in Cassandra.\nmemory.chat_message_histories.cosmos_db.CosmosDBChatMessageHistory(...)\nChat message history backed by Azure CosmosDB.\nmemory.chat_message_histories.dynamodb.DynamoDBChatMessageHistory(...)\nChat message history that stores history in AWS DynamoDB.\nmemory.chat_message_histories.elasticsearch.ElasticsearchChatMessageHistory(...)\nChat message history that stores history in Elasticsearch.\nmemory.chat_message_histories.file.FileChatMessageHistory(...)\nChat message history that stores history in a local file.\nmemory.chat_message_histories.firestore.FirestoreChatMessageHistory(...)\nChat message history backed by Google Firestore.\nmemory.chat_message_histories.in_memory.ChatMessageHistory\nIn memory implementation of chat message history.\nmemory.chat_message_histories.momento.MomentoChatMessageHistory(...)\nChat message history cache that uses Momento as a backend.\nmemory.chat_message_histories.mongodb.MongoDBChatMessageHistory(...)\nChat message history that stores history in MongoDB.\nmemory.chat_message_histories.neo4j.Neo4jChatMessageHistory(...)\nChat message history stored in a Neo4j database.\nmemory.chat_message_histories.postgres.PostgresChatMessageHistory(...)\nChat message history stored in a Postgres database.\nmemory.chat_message_histories.redis.RedisChatMessageHistory(...)\nChat message history stored in a Redis database.\nmemory.chat_message_histories.rocksetdb.RocksetChatMessageHistory(...)\nUses Rockset to store chat messages.\nmemory.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory(...)\nChat message history stored in a SingleStoreDB database.\nmemory.chat_message_histories.sql.BaseMessageConverter()\nThe class responsible for converting BaseMessage to your SQLAlchemy model.\nmemory.chat_message_histories.sql.DefaultMessageConverter(...)\nThe default message converter for SQLChatMessageHistory.\nmemory.chat_message_histories.sql.SQLChatMessageHistory(...)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-59", "text": "memory.chat_message_histories.sql.SQLChatMessageHistory(...)\nChat message history stored in an SQL database.\nmemory.chat_message_histories.streamlit.StreamlitChatMessageHistory([key])\nChat message history that stores messages in Streamlit session state.\nmemory.chat_message_histories.upstash_redis.UpstashRedisChatMessageHistory(...)\nChat message history stored in an Upstash Redis database.\nmemory.chat_message_histories.xata.XataChatMessageHistory(...)\nChat message history stored in a Xata database.\nmemory.chat_message_histories.zep.ZepChatMessageHistory(...)\nChat message history that uses Zep as a backend.\nmemory.combined.CombinedMemory\nCombining multiple memories' data together.\nmemory.entity.BaseEntityStore\nAbstract base class for Entity store.\nmemory.entity.ConversationEntityMemory\nEntity extractor & summarizer memory.\nmemory.entity.InMemoryEntityStore\nIn-memory Entity store.\nmemory.entity.RedisEntityStore\nRedis-backed Entity store.\nmemory.entity.SQLiteEntityStore\nSQLite-backed Entity store\nmemory.entity.UpstashRedisEntityStore\nUpstash Redis backed Entity store.\nmemory.kg.ConversationKGMemory\nKnowledge graph conversation memory.\nmemory.motorhead_memory.MotorheadMemory\nChat message memory backed by Motorhead service.\nmemory.readonly.ReadOnlySharedMemory\nA memory wrapper that is read-only and cannot be changed.\nmemory.simple.SimpleMemory\nSimple memory for storing context or other information that shouldn't ever change between prompts.\nmemory.summary.ConversationSummaryMemory\nConversation summarizer to chat memory.\nmemory.summary.SummarizerMixin\nMixin for summarizer.\nmemory.summary_buffer.ConversationSummaryBufferMemory\nBuffer with summarizer for storing conversation memory.\nmemory.token_buffer.ConversationTokenBufferMemory\nConversation chat memory with token limit.\nmemory.vectorstore.VectorStoreRetrieverMemory\nVectorStoreRetriever-backed memory.\nmemory.zep_memory.ZepMemory", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-60", "text": "VectorStoreRetriever-backed memory.\nmemory.zep_memory.ZepMemory\nPersist your chain history to the Zep MemoryStore.\nFunctions\u00b6\nmemory.chat_message_histories.sql.create_message_model(...)\nCreate a message model for a given table name.\nmemory.utils.get_prompt_input_key(inputs,\u00a0...)\nGet the prompt input key.\nlangchain.model_laboratory\u00b6\nExperiment with different models.\nClasses\u00b6\nmodel_laboratory.ModelLaboratory(chains[,\u00a0names])\nExperiment with different models.\nlangchain.output_parsers\u00b6\nOutputParser classes parse the output of an LLM call.\nClass hierarchy:\nBaseLLMOutputParser --> BaseOutputParser --> <name>OutputParser  # ListOutputParser, PydanticOutputParser\nMain helpers:\nSerializable, Generation, PromptValue\nClasses\u00b6\noutput_parsers.boolean.BooleanOutputParser\nParse the output of an LLM call to a boolean.\noutput_parsers.combining.CombiningOutputParser\nCombine multiple output parsers into one.\noutput_parsers.datetime.DatetimeOutputParser\nParse the output of an LLM call to a datetime.\noutput_parsers.enum.EnumOutputParser\nParse an output that is one of a set of values.\noutput_parsers.fix.OutputFixingParser\nWraps a parser and tries to fix parsing errors.\noutput_parsers.json.SimpleJsonOutputParser\nParse the output of an LLM call to a JSON object.\noutput_parsers.list.CommaSeparatedListOutputParser\nParse the output of an LLM call to a comma-separated list.\noutput_parsers.list.ListOutputParser\nParse the output of an LLM call to a list.\noutput_parsers.list.MarkdownListOutputParser\nParse a markdown list.\noutput_parsers.list.NumberedListOutputParser\nParse a numbered list.\noutput_parsers.openai_functions.JsonKeyOutputFunctionsParser", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-61", "text": "Parse a numbered list.\noutput_parsers.openai_functions.JsonKeyOutputFunctionsParser\nParse an output as the element of the Json object.\noutput_parsers.openai_functions.JsonOutputFunctionsParser\nParse an output as the Json object.\noutput_parsers.openai_functions.OutputFunctionsParser\nParse an output that is one of sets of values.\noutput_parsers.openai_functions.PydanticAttrOutputFunctionsParser\nParse an output as an attribute of a pydantic object.\noutput_parsers.openai_functions.PydanticOutputFunctionsParser\nParse an output as a pydantic object.\noutput_parsers.openai_tools.JsonOutputKeyToolsParser\nParse tools from OpenAI response.\noutput_parsers.openai_tools.JsonOutputToolsParser\nParse tools from OpenAI response.\noutput_parsers.openai_tools.PydanticToolsParser\nParse tools from OpenAI response.\noutput_parsers.pydantic.PydanticOutputParser\nParse an output using a pydantic model.\noutput_parsers.rail_parser.GuardrailsOutputParser\nParse the output of an LLM call using Guardrails.\noutput_parsers.regex.RegexParser\nParse the output of an LLM call using a regex.\noutput_parsers.regex_dict.RegexDictParser\nParse the output of an LLM call into a Dictionary using a regex.\noutput_parsers.retry.RetryOutputParser\nWraps a parser and tries to fix parsing errors.\noutput_parsers.retry.RetryWithErrorOutputParser\nWraps a parser and tries to fix parsing errors.\noutput_parsers.structured.ResponseSchema\nA schema for a response from a structured output parser.\noutput_parsers.structured.StructuredOutputParser\nParse the output of an LLM call to a structured output.\noutput_parsers.xml.XMLOutputParser\nParse an output using xml format.\nFunctions\u00b6\noutput_parsers.json.parse_and_check_json_markdown(...)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-62", "text": "Functions\u00b6\noutput_parsers.json.parse_and_check_json_markdown(...)\nParse a JSON string from a Markdown string and check that it contains the expected keys.\noutput_parsers.json.parse_json_markdown(...)\nParse a JSON string from a Markdown string.\noutput_parsers.json.parse_partial_json(s,\u00a0*)\nParse a JSON string that may be missing closing braces.\noutput_parsers.loading.load_output_parser(config)\nLoad an output parser.\nlangchain.prompts\u00b6\nPrompt is the input to the model.\nPrompt is often constructed\nfrom multiple components. Prompt classes and functions make constructing\nand working with prompts easy.\nClass hierarchy:\nBasePromptTemplate --> PipelinePromptTemplate\n                       StringPromptTemplate --> PromptTemplate\n                                                FewShotPromptTemplate\n                                                FewShotPromptWithTemplates\n                       BaseChatPromptTemplate --> AutoGPTPrompt\n                                                  ChatPromptTemplate --> AgentScratchPadChatPromptTemplate\nBaseMessagePromptTemplate --> MessagesPlaceholder\n                              BaseStringMessagePromptTemplate --> ChatMessagePromptTemplate\n                                                                  HumanMessagePromptTemplate\n                                                                  AIMessagePromptTemplate\n                                                                  SystemMessagePromptTemplate\nPromptValue --> StringPromptValue\n                ChatPromptValue\nClasses\u00b6\nprompts.base.StringPromptTemplate\nString prompt that exposes the format method, returning a prompt.\nprompts.base.StringPromptValue\nString prompt value.\nprompts.chat.AIMessagePromptTemplate\nAI message prompt template.\nprompts.chat.BaseChatPromptTemplate\nBase class for chat prompt templates.\nprompts.chat.BaseMessagePromptTemplate\nBase class for message prompt templates.\nprompts.chat.BaseStringMessagePromptTemplate\nBase class for message prompt templates that use a string prompt template.\nprompts.chat.ChatMessagePromptTemplate\nChat message prompt template.\nprompts.chat.ChatPromptTemplate\nA prompt template for chat models.\nprompts.chat.ChatPromptValue\nChat prompt value.\nprompts.chat.ChatPromptValueConcrete", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-63", "text": "prompts.chat.ChatPromptValue\nChat prompt value.\nprompts.chat.ChatPromptValueConcrete\nChat prompt value which explicitly lists out the message types it accepts.\nprompts.chat.HumanMessagePromptTemplate\nHuman message prompt template.\nprompts.chat.MessagesPlaceholder\nPrompt template that assumes variable is already list of messages.\nprompts.chat.SystemMessagePromptTemplate\nSystem message prompt template.\nprompts.example_selector.base.BaseExampleSelector()\nInterface for selecting examples to include in prompts.\nprompts.example_selector.length_based.LengthBasedExampleSelector\nSelect examples based on length.\nprompts.example_selector.ngram_overlap.NGramOverlapExampleSelector\nSelect and order examples based on ngram overlap score (sentence_bleu score).\nprompts.example_selector.semantic_similarity.MaxMarginalRelevanceExampleSelector\nExampleSelector that selects examples based on Max Marginal Relevance.\nprompts.example_selector.semantic_similarity.SemanticSimilarityExampleSelector\nExample selector that selects examples based on SemanticSimilarity.\nprompts.few_shot.FewShotChatMessagePromptTemplate\nChat prompt template that supports few-shot examples.\nprompts.few_shot.FewShotPromptTemplate\nPrompt template that contains few shot examples.\nprompts.few_shot_with_templates.FewShotPromptWithTemplates\nPrompt template that contains few shot examples.\nprompts.pipeline.PipelinePromptTemplate\nA prompt template for composing multiple prompt templates together.\nprompts.prompt.Prompt\nalias of PromptTemplate\nprompts.prompt.PromptTemplate\nA prompt template for a language model.\nFunctions\u00b6\nprompts.base.check_valid_template(template,\u00a0...)\nCheck that template string is valid.\nprompts.base.get_template_variables(...)\nGet the variables from the template.\nprompts.base.jinja2_formatter(template,\u00a0**kwargs)\nFormat a template using jinja2.\nprompts.base.validate_jinja2(template,\u00a0...)\nValidate that the input variables are valid for the template.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-64", "text": "Validate that the input variables are valid for the template.\nprompts.example_selector.ngram_overlap.ngram_overlap_score(...)\nCompute ngram overlap score of source and example as sentence_bleu score.\nprompts.example_selector.semantic_similarity.sorted_values(values)\nReturn a list of values in dict sorted by key.\nprompts.loading.load_prompt(path)\nUnified method for loading a prompt from LangChainHub or local fs.\nprompts.loading.load_prompt_from_config(config)\nLoad prompt from Config Dict.\nlangchain.retrievers\u00b6\nRetriever class returns Documents given a text query.\nIt is more general than a vector store. A retriever does not need to be able to\nstore documents, only to return (or retrieve) it. Vector stores can be used as\nthe backbone of a retriever, but there are other types of retrievers as well.\nClass hierarchy:\nBaseRetriever --> <name>Retriever  # Examples: ArxivRetriever, MergerRetriever\nMain helpers:\nDocument, Serializable, Callbacks,\nCallbackManagerForRetrieverRun, AsyncCallbackManagerForRetrieverRun\nClasses\u00b6\nretrievers.arcee.ArceeRetriever\nDocument retriever for Arcee's Domain Adapted Language Models (DALMs).\nretrievers.arxiv.ArxivRetriever\nArxiv retriever.\nretrievers.azure_cognitive_search.AzureCognitiveSearchRetriever\nAzure Cognitive Search service retriever.\nretrievers.bm25.BM25Retriever\nBM25 retriever without Elasticsearch.\nretrievers.chaindesk.ChaindeskRetriever\nChaindesk API retriever.\nretrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever\nChatGPT plugin retriever.\nretrievers.cohere_rag_retriever.CohereRagRetriever", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-65", "text": "retrievers.cohere_rag_retriever.CohereRagRetriever\nCohere Chat API with RAG.\nretrievers.contextual_compression.ContextualCompressionRetriever\nRetriever that wraps a base retriever and compresses the results.\nretrievers.databerry.DataberryRetriever\nDataberry API retriever.\nretrievers.docarray.DocArrayRetriever\nDocArray Document Indices retriever.\nretrievers.docarray.SearchType(value[,\u00a0...])\nEnumerator of the types of search to perform.\nretrievers.document_compressors.base.BaseDocumentCompressor\nBase class for document compressors.\nretrievers.document_compressors.base.DocumentCompressorPipeline\nDocument compressor that uses a pipeline of Transformers.\nretrievers.document_compressors.chain_extract.LLMChainExtractor\nDocument compressor that uses an LLM chain to extract the relevant parts of documents.\nretrievers.document_compressors.chain_extract.NoOutputParser\nParse outputs that could return a null string of some sort.\nretrievers.document_compressors.chain_filter.LLMChainFilter\nFilter that drops documents that aren't relevant to the query.\nretrievers.document_compressors.cohere_rerank.CohereRerank\nDocument compressor that uses Cohere Rerank API.\nretrievers.document_compressors.embeddings_filter.EmbeddingsFilter\nDocument compressor that uses embeddings to drop documents unrelated to the query.\nretrievers.elastic_search_bm25.ElasticSearchBM25Retriever\nElasticsearch retriever that uses BM25.\nretrievers.ensemble.EnsembleRetriever\nRetriever that ensembles the multiple retrievers.\nretrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever\nA retriever based on Document AI Warehouse.\nretrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-66", "text": "retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever\nGoogle Vertex Search API retriever alias for backwards compatibility.\nretrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever\nGoogle Vertex AI Search retriever for multi-turn conversations.\nretrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever\nGoogle Vertex AI Search retriever.\nretrievers.kay.KayAiRetriever\nRetriever for Kay.ai datasets.\nretrievers.kendra.AdditionalResultAttribute\nAdditional result attribute.\nretrievers.kendra.AdditionalResultAttributeValue\nValue of an additional result attribute.\nretrievers.kendra.AmazonKendraRetriever\nAmazon Kendra Index retriever.\nretrievers.kendra.DocumentAttribute\nDocument attribute.\nretrievers.kendra.DocumentAttributeValue\nValue of a document attribute.\nretrievers.kendra.Highlight\nInformation that highlights the keywords in the excerpt.\nretrievers.kendra.QueryResult\nAmazon Kendra Query API search result.\nretrievers.kendra.QueryResultItem\nQuery API result item.\nretrievers.kendra.ResultItem\nBase class of a result item.\nretrievers.kendra.RetrieveResult\nAmazon Kendra Retrieve API search result.\nretrievers.kendra.RetrieveResultItem\nRetrieve API result item.\nretrievers.kendra.TextWithHighLights\nText with highlights.\nretrievers.knn.KNNRetriever\nKNN retriever.\nretrievers.llama_index.LlamaIndexGraphRetriever\nLlamaIndex graph data structure retriever.\nretrievers.llama_index.LlamaIndexRetriever\nLlamaIndex retriever.\nretrievers.merger_retriever.MergerRetriever\nRetriever that merges the results of multiple retrievers.\nretrievers.metal.MetalRetriever", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-67", "text": "retrievers.metal.MetalRetriever\nMetal API retriever.\nretrievers.milvus.MilvusRetriever\nMilvus API retriever.\nretrievers.multi_query.LineList\nList of lines.\nretrievers.multi_query.LineListOutputParser\nOutput parser for a list of lines.\nretrievers.multi_query.MultiQueryRetriever\nGiven a query, use an LLM to write a set of queries.\nretrievers.multi_vector.MultiVectorRetriever\nRetrieve from a set of multiple embeddings for the same document.\nretrievers.parent_document_retriever.ParentDocumentRetriever\nRetrieve small chunks then retrieve their parent documents.\nretrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever\nPinecone Hybrid Search retriever.\nretrievers.pubmed.PubMedRetriever\nPubMed API retriever.\nretrievers.re_phraser.RePhraseQueryRetriever\nGiven a query, use an LLM to re-phrase it.\nretrievers.remote_retriever.RemoteLangChainRetriever\nLangChain API retriever.\nretrievers.self_query.base.SelfQueryRetriever\nRetriever that uses a vector store and an LLM to generate the vector store queries.\nretrievers.self_query.chroma.ChromaTranslator()\nTranslate Chroma internal query language elements to valid filters.\nretrievers.self_query.dashvector.DashvectorTranslator()\nLogic for converting internal query language elements to valid filters.\nretrievers.self_query.deeplake.DeepLakeTranslator()\nTranslate DeepLake internal query language elements to valid filters.\nretrievers.self_query.elasticsearch.ElasticsearchTranslator()\nTranslate Elasticsearch internal query language elements to valid filters.\nretrievers.self_query.milvus.MilvusTranslator()", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-68", "text": "retrievers.self_query.milvus.MilvusTranslator()\nTranslate Milvus internal query language elements to valid filters.\nretrievers.self_query.myscale.MyScaleTranslator([...])\nTranslate MyScale internal query language elements to valid filters.\nretrievers.self_query.opensearch.OpenSearchTranslator()\nTranslate OpenSearch internal query domain-specific language elements to valid filters.\nretrievers.self_query.pinecone.PineconeTranslator()\nTranslate Pinecone internal query language elements to valid filters.\nretrievers.self_query.qdrant.QdrantTranslator(...)\nTranslate Qdrant internal query language elements to valid filters.\nretrievers.self_query.redis.RedisTranslator(schema)\nTranslate\nretrievers.self_query.supabase.SupabaseVectorTranslator()\nTranslate Langchain filters to Supabase PostgREST filters.\nretrievers.self_query.timescalevector.TimescaleVectorTranslator()\nTranslate the internal query language elements to valid filters.\nretrievers.self_query.vectara.VectaraTranslator()\nTranslate Vectara internal query language elements to valid filters.\nretrievers.self_query.weaviate.WeaviateTranslator()\nTranslate Weaviate internal query language elements to valid filters.\nretrievers.svm.SVMRetriever\nSVM retriever.\nretrievers.tavily_search_api.SearchDepth(value)\nSearch depth as enumerator.\nretrievers.tavily_search_api.TavilySearchAPIRetriever\nTavily Search API retriever.\nretrievers.tfidf.TFIDFRetriever\nTF-IDF retriever.\nretrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever\nRetriever that combines embedding similarity with recency in retrieving values.\nretrievers.vespa_retriever.VespaRetriever\nVespa retriever.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-69", "text": "Vespa retriever.\nretrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever\nWeaviate hybrid search retriever.\nretrievers.web_research.LineList\nList of questions.\nretrievers.web_research.QuestionListOutputParser\nOutput parser for a list of numbered questions.\nretrievers.web_research.SearchQueries\nSearch queries to research for the user's goal.\nretrievers.web_research.WebResearchRetriever\nGoogle Search API retriever.\nretrievers.wikipedia.WikipediaRetriever\nWikipedia API retriever.\nretrievers.you.YouRetriever\nYou retriever that uses You.com's search API.\nretrievers.zep.SearchScope(value[,\u00a0names,\u00a0...])\nWhich documents to search.\nretrievers.zep.SearchType(value[,\u00a0names,\u00a0...])\nEnumerator of the types of search to perform.\nretrievers.zep.ZepRetriever\nZep MemoryStore Retriever.\nretrievers.zilliz.ZillizRetriever\nZilliz API retriever.\nFunctions\u00b6\nretrievers.bm25.default_preprocessing_func(text)\nretrievers.document_compressors.chain_extract.default_get_input(...)\nReturn the compression chain input.\nretrievers.document_compressors.chain_filter.default_get_input(...)\nReturn the compression chain input.\nretrievers.kendra.clean_excerpt(excerpt)\nClean an excerpt from Kendra.\nretrievers.kendra.combined_text(item)\nCombine a ResultItem title and excerpt into a single string.\nretrievers.knn.create_index(contexts,\u00a0embeddings)\nCreate an index of embeddings for a list of contexts.\nretrievers.milvus.MilvusRetreiver(*args,\u00a0...)\nDeprecated MilvusRetreiver.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-70", "text": "Deprecated MilvusRetreiver.\nretrievers.pinecone_hybrid_search.create_index(...)\nCreate an index from a list of contexts.\nretrievers.pinecone_hybrid_search.hash_text(text)\nHash a text using SHA256.\nretrievers.self_query.deeplake.can_cast_to_float(string)\nCheck if a string can be cast to a float.\nretrievers.self_query.milvus.process_value(value)\nConvert a value to a string and add double quotes if it is a string.\nretrievers.self_query.vectara.process_value(value)\nConvert a value to a string and add single quotes if it is a string.\nretrievers.svm.create_index(contexts,\u00a0embeddings)\nCreate an index of embeddings for a list of contexts.\nretrievers.zilliz.ZillizRetreiver(*args,\u00a0...)\nDeprecated ZillizRetreiver.\nlangchain.runnables\u00b6\nClasses\u00b6\nrunnables.hub.HubRunnable\nAn instance of a runnable stored in the LangChain Hub.\nrunnables.openai_functions.OpenAIFunction\nA function description for ChatOpenAI\nrunnables.openai_functions.OpenAIFunctionsRouter\nA runnable that routes to the selected function.\nlangchain.schema\u00b6\nSchemas are the LangChain Base Classes and Interfaces.\nClasses\u00b6\nschema.agent.AgentAction\nA full description of an action for an ActionAgent to execute.\nschema.agent.AgentActionMessageLog\nOverride init to support instantiation by position for backward compat.\nschema.agent.AgentFinish\nThe final return value of an ActionAgent.\nschema.cache.BaseCache()\nBase interface for cache.\nschema.callbacks.base.AsyncCallbackHandler()\nAsync callback handler that handles callbacks from LangChain.\nschema.callbacks.base.BaseCallbackHandler()\nBase callback handler that handles callbacks from LangChain.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-71", "text": "schema.callbacks.base.BaseCallbackHandler()\nBase callback handler that handles callbacks from LangChain.\nschema.callbacks.base.BaseCallbackManager(...)\nBase callback manager that handles callbacks from LangChain.\nschema.callbacks.base.CallbackManagerMixin()\nMixin for callback manager.\nschema.callbacks.base.ChainManagerMixin()\nMixin for chain callbacks.\nschema.callbacks.base.LLMManagerMixin()\nMixin for LLM callbacks.\nschema.callbacks.base.RetrieverManagerMixin()\nMixin for Retriever callbacks.\nschema.callbacks.base.RunManagerMixin()\nMixin for run manager.\nschema.callbacks.base.ToolManagerMixin()\nMixin for tool callbacks.\nschema.callbacks.manager.AsyncCallbackManager(...)\nAsync callback manager that handles callbacks from LangChain.\nschema.callbacks.manager.AsyncCallbackManagerForChainGroup(...)\nAsync callback manager for the chain group.\nschema.callbacks.manager.AsyncCallbackManagerForChainRun(*,\u00a0...)\nAsync callback manager for chain run.\nschema.callbacks.manager.AsyncCallbackManagerForLLMRun(*,\u00a0...)\nAsync callback manager for LLM run.\nschema.callbacks.manager.AsyncCallbackManagerForRetrieverRun(*,\u00a0...)\nAsync callback manager for retriever run.\nschema.callbacks.manager.AsyncCallbackManagerForToolRun(*,\u00a0...)\nAsync callback manager for tool run.\nschema.callbacks.manager.AsyncParentRunManager(*,\u00a0...)\nAsync Parent Run Manager.\nschema.callbacks.manager.AsyncRunManager(*,\u00a0...)\nAsync Run Manager.\nschema.callbacks.manager.BaseRunManager(*,\u00a0...)\nBase class for run manager (a bound callback manager).\nschema.callbacks.manager.CallbackManager(...)\nCallback manager that handles callbacks from LangChain.\nschema.callbacks.manager.CallbackManagerForChainGroup(...)\nCallback manager for the chain group.\nschema.callbacks.manager.CallbackManagerForChainRun(*,\u00a0...)\nCallback manager for chain run.\nschema.callbacks.manager.CallbackManagerForLLMRun(*,\u00a0...)\nCallback manager for LLM run.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-72", "text": "Callback manager for LLM run.\nschema.callbacks.manager.CallbackManagerForRetrieverRun(*,\u00a0...)\nCallback manager for retriever run.\nschema.callbacks.manager.CallbackManagerForToolRun(*,\u00a0...)\nCallback manager for tool run.\nschema.callbacks.manager.ParentRunManager(*,\u00a0...)\nSync Parent Run Manager.\nschema.callbacks.manager.RunManager(*,\u00a0...)\nSync Run Manager.\nschema.callbacks.stdout.StdOutCallbackHandler([color])\nCallback Handler that prints to std out.\nschema.callbacks.tracers.base.BaseTracer(...)\nBase interface for tracers.\nschema.callbacks.tracers.base.TracerException\nBase class for exceptions in tracers module.\nschema.callbacks.tracers.evaluation.EvaluatorCallbackHandler(...)\nA tracer that runs a run evaluator whenever a run is persisted.\nschema.callbacks.tracers.langchain.LangChainTracer([...])\nAn implementation of the SharedTracer that POSTS to the langchain endpoint.\nschema.callbacks.tracers.langchain_v1.LangChainTracerV1(...)\nAn implementation of the SharedTracer that POSTS to the langchain endpoint.\nschema.callbacks.tracers.log_stream.LogEntry\nA single entry in the run log.\nschema.callbacks.tracers.log_stream.LogStreamCallbackHandler(*)\nA tracer that streams run logs to a stream.\nschema.callbacks.tracers.log_stream.RunLog(...)\nA run log.\nschema.callbacks.tracers.log_stream.RunLogPatch(*ops)\nA patch to the run log.\nschema.callbacks.tracers.log_stream.RunState\nState of the run.\nschema.callbacks.tracers.root_listeners.RootListenersTracer(*,\u00a0...)\nschema.callbacks.tracers.run_collector.RunCollectorCallbackHandler([...])\nA tracer that collects all nested runs in a list.\nschema.callbacks.tracers.schemas.BaseRun\nBase class for Run.\nschema.callbacks.tracers.schemas.ChainRun\nClass for ChainRun.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-73", "text": "schema.callbacks.tracers.schemas.ChainRun\nClass for ChainRun.\nschema.callbacks.tracers.schemas.LLMRun\nClass for LLMRun.\nschema.callbacks.tracers.schemas.Run\nRun schema for the V2 API in the Tracer.\nschema.callbacks.tracers.schemas.ToolRun\nClass for ToolRun.\nschema.callbacks.tracers.schemas.TracerSession\nTracerSessionV1 schema for the V2 API.\nschema.callbacks.tracers.schemas.TracerSessionBase\nBase class for TracerSession.\nschema.callbacks.tracers.schemas.TracerSessionV1\nTracerSessionV1 schema.\nschema.callbacks.tracers.schemas.TracerSessionV1Base\nBase class for TracerSessionV1.\nschema.callbacks.tracers.schemas.TracerSessionV1Create\nCreate class for TracerSessionV1.\nschema.callbacks.tracers.stdout.ConsoleCallbackHandler(...)\nTracer that prints to the console.\nschema.callbacks.tracers.stdout.FunctionCallbackHandler(...)\nTracer that calls a function with a single str parameter.\nschema.chat.ChatSession\nChat Session represents a single conversation, channel, or other group of messages.\nschema.chat_history.BaseChatMessageHistory()\nAbstract base class for storing chat message history.\nschema.document.BaseDocumentTransformer()\nAbstract base class for document transformation systems.\nschema.document.Document\nClass for storing a piece of text and associated metadata.\nschema.embeddings.Embeddings()\nInterface for embedding models.\nschema.exceptions.LangChainException\nGeneral LangChain exception.\nschema.language_model.BaseLanguageModel\nAbstract base class for interfacing with language models.\nschema.memory.BaseMemory\nAbstract base class for memory in Chains.\nschema.messages.AIMessage\nA Message from an AI.\nschema.messages.AIMessageChunk\nA Message chunk from an AI.\nschema.messages.BaseMessage\nThe base abstract Message class.\nschema.messages.BaseMessageChunk", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-74", "text": "schema.messages.BaseMessage\nThe base abstract Message class.\nschema.messages.BaseMessageChunk\nA Message chunk, which can be concatenated with other Message chunks.\nschema.messages.ChatMessage\nA Message that can be assigned an arbitrary speaker (i.e.\nschema.messages.ChatMessageChunk\nA Chat Message chunk.\nschema.messages.FunctionMessage\nA Message for passing the result of executing a function back to a model.\nschema.messages.FunctionMessageChunk\nA Function Message chunk.\nschema.messages.HumanMessage\nA Message from a human.\nschema.messages.HumanMessageChunk\nA Human Message chunk.\nschema.messages.SystemMessage\nA Message for priming AI behavior, usually passed in as the first of a sequence of input messages.\nschema.messages.SystemMessageChunk\nA System Message chunk.\nschema.messages.ToolMessage\nA Message for passing the result of executing a tool back to a model.\nschema.messages.ToolMessageChunk\nA Tool Message chunk.\nschema.output.ChatGeneration\nA single chat generation output.\nschema.output.ChatGenerationChunk\nA ChatGeneration chunk, which can be concatenated with other\nschema.output.ChatResult\nClass that contains all results for a single chat model call.\nschema.output.Generation\nA single text generation output.\nschema.output.GenerationChunk\nA Generation chunk, which can be concatenated with other Generation chunks.\nschema.output.LLMResult\nClass that contains all results for a batched LLM call.\nschema.output.RunInfo\nClass that contains metadata for a single execution of a Chain or model.\nschema.output_parser.BaseCumulativeTransformOutputParser\nBase class for an output parser that can handle streaming input.\nschema.output_parser.BaseGenerationOutputParser\nBase class to parse the output of an LLM call.\nschema.output_parser.BaseLLMOutputParser()\nAbstract base class for parsing the outputs of a model.\nschema.output_parser.BaseOutputParser\nBase class to parse the output of an LLM call.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-75", "text": "schema.output_parser.BaseOutputParser\nBase class to parse the output of an LLM call.\nschema.output_parser.BaseTransformOutputParser\nBase class for an output parser that can handle streaming input.\nschema.output_parser.NoOpOutputParser\nalias of StrOutputParser\nschema.output_parser.OutputParserException(error)\nException that output parsers should raise to signify a parsing error.\nschema.output_parser.StrOutputParser\nOutputParser that parses LLMResult into the top likely string.\nschema.prompt.PromptValue\nBase abstract class for inputs to any language model.\nschema.prompt_template.BasePromptTemplate\nBase class for all prompt templates, returning a prompt.\nschema.retriever.BaseRetriever\nAbstract base class for a Document retrieval system.\nschema.runnable.base.Runnable()\nA unit of work that can be invoked, batched, streamed, transformed and composed.\nschema.runnable.base.RunnableBinding\nA runnable that delegates calls to another runnable with a set of kwargs.\nschema.runnable.base.RunnableBindingBase\nA runnable that delegates calls to another runnable with a set of kwargs.\nschema.runnable.base.RunnableEach\nA runnable that delegates calls to another runnable with each element of the input sequence.\nschema.runnable.base.RunnableEachBase\nA runnable that delegates calls to another runnable with each element of the input sequence.\nschema.runnable.base.RunnableGenerator(transform)\nA runnable that runs a generator function.\nschema.runnable.base.RunnableLambda(func[,\u00a0...])\nRunnableLambda converts a python callable into a Runnable.\nschema.runnable.base.RunnableMap\nalias of RunnableParallel\nschema.runnable.base.RunnableParallel\nA runnable that runs a mapping of runnables in parallel, and returns a mapping of their outputs.\nschema.runnable.base.RunnableSequence\nA sequence of runnables, where the output of each is the input of the next.\nschema.runnable.base.RunnableSerializable", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-76", "text": "schema.runnable.base.RunnableSerializable\nA Runnable that can be serialized to JSON.\nschema.runnable.branch.RunnableBranch\nA Runnable that selects which branch to run based on a condition.\nschema.runnable.config.EmptyDict\nEmpty dict type.\nschema.runnable.config.RunnableConfig\nConfiguration for a Runnable.\nschema.runnable.configurable.DynamicRunnable\nA Serializable Runnable that can be dynamically configured.\nschema.runnable.configurable.RunnableConfigurableAlternatives\nA Runnable that can be dynamically configured.\nschema.runnable.configurable.RunnableConfigurableFields\nA Runnable that can be dynamically configured.\nschema.runnable.configurable.StrEnum(value)\nA string enum.\nschema.runnable.fallbacks.RunnableWithFallbacks\nA Runnable that can fallback to other Runnables if it fails.\nschema.runnable.history.RunnableWithMessageHistory\nA runnable that manages chat message history for another runnable.\nschema.runnable.passthrough.RunnableAssign\nA runnable that assigns key-value pairs to Dict[str, Any] inputs.\nschema.runnable.passthrough.RunnablePassthrough\nA runnable to passthrough inputs unchanged or with additional keys.\nschema.runnable.retry.RunnableRetry\nRetry a Runnable if it fails.\nschema.runnable.router.RouterInput\nA Router input.\nschema.runnable.router.RouterRunnable\nA runnable that routes to a set of runnables based on Input['key'].\nschema.runnable.utils.AddableDict\nDictionary that can be added to another dictionary.\nschema.runnable.utils.ConfigurableField(id)\nA field that can be configured by the user.\nschema.runnable.utils.ConfigurableFieldMultiOption(id,\u00a0...)\nA field that can be configured by the user with multiple default values.\nschema.runnable.utils.ConfigurableFieldSingleOption(id,\u00a0...)\nA field that can be configured by the user with a default value.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-77", "text": "A field that can be configured by the user with a default value.\nschema.runnable.utils.ConfigurableFieldSpec(id,\u00a0...)\nA field that can be configured by the user.\nschema.runnable.utils.GetLambdaSource()\nGet the source code of a lambda function.\nschema.runnable.utils.IsFunctionArgDict()\nCheck if the first argument of a function is a dict.\nschema.runnable.utils.IsLocalDict(name,\u00a0keys)\nCheck if a name is a local dict.\nschema.runnable.utils.SupportsAdd(*args,\u00a0...)\nProtocol for objects that support addition.\nschema.storage.BaseStore()\nAbstract interface for a key-value store.\nschema.vectorstore.VectorStore()\nInterface for vector store.\nschema.vectorstore.VectorStoreRetriever\nBase Retriever class for VectorStore.\nFunctions\u00b6\nschema.callbacks.manager.ahandle_event(...)\nGeneric event handler for AsyncCallbackManager.\nschema.callbacks.manager.atrace_as_chain_group(...)\nGet an async callback manager for a chain group in a context manager.\nschema.callbacks.manager.collect_runs()\nCollect all run traces in context.\nschema.callbacks.manager.env_var_is_set(env_var)\nCheck if an environment variable is set.\nschema.callbacks.manager.handle_event(...)\nGeneric event handler for CallbackManager.\nschema.callbacks.manager.register_configure_hook(...)\nschema.callbacks.manager.trace_as_chain_group(...)\nGet a callback manager for a chain group in a context manager.\nschema.callbacks.manager.tracing_enabled([...])\nGet the Deprecated LangChainTracer in a context manager.\nschema.callbacks.manager.tracing_v2_enabled([...])\nInstruct LangChain to log all runs in context to LangSmith.\nschema.callbacks.tracers.evaluation.wait_for_all_evaluators()\nWait for all tracers to finish.\nschema.callbacks.tracers.langchain.get_client()\nGet the client.\nschema.callbacks.tracers.langchain.log_error_once(...)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-78", "text": "Get the client.\nschema.callbacks.tracers.langchain.log_error_once(...)\nLog an error once.\nschema.callbacks.tracers.langchain.wait_for_all_tracers()\nWait for all tracers to finish.\nschema.callbacks.tracers.langchain_v1.get_headers()\nGet the headers for the LangChain API.\nschema.callbacks.tracers.schemas.RunTypeEnum()\nRunTypeEnum.\nschema.callbacks.tracers.stdout.elapsed(run)\nGet the elapsed time of a run.\nschema.callbacks.tracers.stdout.try_json_stringify(...)\nTry to stringify an object to JSON.\nschema.messages.get_buffer_string(messages)\nConvert sequence of Messages to strings and concatenate them into one string.\nschema.messages.merge_content(first_content,\u00a0...)\nschema.messages.messages_from_dict(messages)\nConvert a sequence of messages from dicts to Message objects.\nschema.messages.messages_to_dict(messages)\nConvert a sequence of Messages to a list of dictionaries.\nschema.prompt_template.format_document(doc,\u00a0...)\nFormat a document into a string based on a prompt template.\nschema.runnable.base.coerce_to_runnable(thing)\nCoerce a runnable-like object into a Runnable.\nschema.runnable.config.acall_func_with_variable_args(...)\nCall function that may optionally accept a run_manager and/or config.\nschema.runnable.config.call_func_with_variable_args(...)\nCall function that may optionally accept a run_manager and/or config.\nschema.runnable.config.ensure_config([config])\nEnsure that a config is a dict with all keys present.\nschema.runnable.config.get_async_callback_manager_for_config(config)\nGet an async callback manager for a config.\nschema.runnable.config.get_callback_manager_for_config(config)\nGet a callback manager for a config.\nschema.runnable.config.get_config_list(...)\nGet a list of configs from a single config or a list of configs.\nschema.runnable.config.get_executor_for_config(config)\nGet an executor for a config.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-79", "text": "schema.runnable.config.get_executor_for_config(config)\nGet an executor for a config.\nschema.runnable.config.merge_configs(*configs)\nMerge multiple configs into one.\nschema.runnable.config.patch_config(config,\u00a0*)\nPatch a config with new values.\nschema.runnable.configurable.make_options_spec(...)\nMake a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or ConfigurableFieldMultiOption.\nschema.runnable.passthrough.aidentity(x)\nAn async identity function\nschema.runnable.passthrough.identity(x)\nAn identity function\nschema.runnable.utils.aadd(addables)\nAsynchronously add a sequence of addable objects together.\nschema.runnable.utils.accepts_config(callable)\nCheck if a callable accepts a config argument.\nschema.runnable.utils.accepts_run_manager(...)\nCheck if a callable accepts a run_manager argument.\nschema.runnable.utils.add(addables)\nAdd a sequence of addable objects together.\nschema.runnable.utils.gated_coro(semaphore,\u00a0coro)\nRun a coroutine with a semaphore.\nschema.runnable.utils.gather_with_concurrency(n,\u00a0...)\nGather coroutines with a limit on the number of concurrent coroutines.\nschema.runnable.utils.get_function_first_arg_dict_keys(func)\nGet the keys of the first argument of a function if it is a dict.\nschema.runnable.utils.get_lambda_source(func)\nGet the source code of a lambda function.\nschema.runnable.utils.get_unique_config_specs(specs)\nGet the unique config specs from a sequence of config specs.\nschema.runnable.utils.indent_lines_after_first(...)\nIndent all lines of text after the first line.\nlangchain.schema.runnable\u00b6\nLangChain Runnable and the LangChain Expression Language (LCEL).\nThe LangChain Expression Language (LCEL) offers a declarative method to build\nproduction-grade programs that harness the power of LLMs.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-80", "text": "production-grade programs that harness the power of LLMs.\nPrograms created using LCEL and LangChain Runnables inherently support\nsynchronous, asynchronous, batch, and streaming operations.\nSupport for async allows servers hosting LCEL based programs to scale better\nfor higher concurrent loads.\nStreaming of intermediate outputs as they\u2019re being generated allows for\ncreating more responsive UX.\nThis module contains schema and implementation of LangChain Runnables primitives.\nClasses\u00b6\nschema.runnable.base.Runnable()\nA unit of work that can be invoked, batched, streamed, transformed and composed.\nschema.runnable.base.RunnableBinding\nA runnable that delegates calls to another runnable with a set of kwargs.\nschema.runnable.base.RunnableBindingBase\nA runnable that delegates calls to another runnable with a set of kwargs.\nschema.runnable.base.RunnableEach\nA runnable that delegates calls to another runnable with each element of the input sequence.\nschema.runnable.base.RunnableEachBase\nA runnable that delegates calls to another runnable with each element of the input sequence.\nschema.runnable.base.RunnableGenerator(transform)\nA runnable that runs a generator function.\nschema.runnable.base.RunnableLambda(func[,\u00a0...])\nRunnableLambda converts a python callable into a Runnable.\nschema.runnable.base.RunnableMap\nalias of RunnableParallel\nschema.runnable.base.RunnableParallel\nA runnable that runs a mapping of runnables in parallel, and returns a mapping of their outputs.\nschema.runnable.base.RunnableSequence\nA sequence of runnables, where the output of each is the input of the next.\nschema.runnable.base.RunnableSerializable\nA Runnable that can be serialized to JSON.\nschema.runnable.branch.RunnableBranch\nA Runnable that selects which branch to run based on a condition.\nschema.runnable.config.EmptyDict\nEmpty dict type.\nschema.runnable.config.RunnableConfig", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-81", "text": "schema.runnable.config.EmptyDict\nEmpty dict type.\nschema.runnable.config.RunnableConfig\nConfiguration for a Runnable.\nschema.runnable.configurable.DynamicRunnable\nA Serializable Runnable that can be dynamically configured.\nschema.runnable.configurable.RunnableConfigurableAlternatives\nA Runnable that can be dynamically configured.\nschema.runnable.configurable.RunnableConfigurableFields\nA Runnable that can be dynamically configured.\nschema.runnable.configurable.StrEnum(value)\nA string enum.\nschema.runnable.fallbacks.RunnableWithFallbacks\nA Runnable that can fallback to other Runnables if it fails.\nschema.runnable.history.RunnableWithMessageHistory\nA runnable that manages chat message history for another runnable.\nschema.runnable.passthrough.RunnableAssign\nA runnable that assigns key-value pairs to Dict[str, Any] inputs.\nschema.runnable.passthrough.RunnablePassthrough\nA runnable to passthrough inputs unchanged or with additional keys.\nschema.runnable.retry.RunnableRetry\nRetry a Runnable if it fails.\nschema.runnable.router.RouterInput\nA Router input.\nschema.runnable.router.RouterRunnable\nA runnable that routes to a set of runnables based on Input['key'].\nschema.runnable.utils.AddableDict\nDictionary that can be added to another dictionary.\nschema.runnable.utils.ConfigurableField(id)\nA field that can be configured by the user.\nschema.runnable.utils.ConfigurableFieldMultiOption(id,\u00a0...)\nA field that can be configured by the user with multiple default values.\nschema.runnable.utils.ConfigurableFieldSingleOption(id,\u00a0...)\nA field that can be configured by the user with a default value.\nschema.runnable.utils.ConfigurableFieldSpec(id,\u00a0...)\nA field that can be configured by the user.\nschema.runnable.utils.GetLambdaSource()\nGet the source code of a lambda function.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-82", "text": "schema.runnable.utils.GetLambdaSource()\nGet the source code of a lambda function.\nschema.runnable.utils.IsFunctionArgDict()\nCheck if the first argument of a function is a dict.\nschema.runnable.utils.IsLocalDict(name,\u00a0keys)\nCheck if a name is a local dict.\nschema.runnable.utils.SupportsAdd(*args,\u00a0...)\nProtocol for objects that support addition.\nFunctions\u00b6\nschema.runnable.base.coerce_to_runnable(thing)\nCoerce a runnable-like object into a Runnable.\nschema.runnable.config.acall_func_with_variable_args(...)\nCall function that may optionally accept a run_manager and/or config.\nschema.runnable.config.call_func_with_variable_args(...)\nCall function that may optionally accept a run_manager and/or config.\nschema.runnable.config.ensure_config([config])\nEnsure that a config is a dict with all keys present.\nschema.runnable.config.get_async_callback_manager_for_config(config)\nGet an async callback manager for a config.\nschema.runnable.config.get_callback_manager_for_config(config)\nGet a callback manager for a config.\nschema.runnable.config.get_config_list(...)\nGet a list of configs from a single config or a list of configs.\nschema.runnable.config.get_executor_for_config(config)\nGet an executor for a config.\nschema.runnable.config.merge_configs(*configs)\nMerge multiple configs into one.\nschema.runnable.config.patch_config(config,\u00a0*)\nPatch a config with new values.\nschema.runnable.configurable.make_options_spec(...)\nMake a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or ConfigurableFieldMultiOption.\nschema.runnable.passthrough.aidentity(x)\nAn async identity function\nschema.runnable.passthrough.identity(x)\nAn identity function\nschema.runnable.utils.aadd(addables)\nAsynchronously add a sequence of addable objects together.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-83", "text": "Asynchronously add a sequence of addable objects together.\nschema.runnable.utils.accepts_config(callable)\nCheck if a callable accepts a config argument.\nschema.runnable.utils.accepts_run_manager(...)\nCheck if a callable accepts a run_manager argument.\nschema.runnable.utils.add(addables)\nAdd a sequence of addable objects together.\nschema.runnable.utils.gated_coro(semaphore,\u00a0coro)\nRun a coroutine with a semaphore.\nschema.runnable.utils.gather_with_concurrency(n,\u00a0...)\nGather coroutines with a limit on the number of concurrent coroutines.\nschema.runnable.utils.get_function_first_arg_dict_keys(func)\nGet the keys of the first argument of a function if it is a dict.\nschema.runnable.utils.get_lambda_source(func)\nGet the source code of a lambda function.\nschema.runnable.utils.get_unique_config_specs(specs)\nGet the unique config specs from a sequence of config specs.\nschema.runnable.utils.indent_lines_after_first(...)\nIndent all lines of text after the first line.\nlangchain.smith\u00b6\nLangSmith utilities.\nThis module provides utilities for connecting to LangSmith. For more information on LangSmith, see the LangSmith documentation.\nEvaluation\nLangSmith helps you evaluate Chains and other language model application components using a number of LangChain evaluators.\nAn example of this is shown below, assuming you\u2019ve created a LangSmith dataset called <my_dataset_name>:\nfrom langsmith import Client\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.chains import LLMChain\nfrom langchain.smith import RunEvalConfig, run_on_dataset\n# Chains may have memory. Passing in a constructor function lets the\n# evaluation framework avoid cross-contamination between runs.\ndef construct_chain():\n    llm = ChatOpenAI(temperature=0)\n    chain = LLMChain.from_string(", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-84", "text": "chain = LLMChain.from_string(\n        llm,\n        \"What's the answer to {your_input_key}\"\n    )\n    return chain\n# Load off-the-shelf evaluators via config or the EvaluatorType (string or enum)\nevaluation_config = RunEvalConfig(\n    evaluators=[\n        \"qa\",  # \"Correctness\" against a reference answer\n        \"embedding_distance\",\n        RunEvalConfig.Criteria(\"helpfulness\"),\n        RunEvalConfig.Criteria({\n            \"fifth-grader-score\": \"Do you have to be smarter than a fifth grader to answer this question?\"\n        }),\n    ]\n)\nclient = Client()\nrun_on_dataset(\n    client,\n    \"<my_dataset_name>\",\n    construct_chain,\n    evaluation=evaluation_config,\n)\nYou can also create custom evaluators by subclassing the\nStringEvaluator\nor LangSmith\u2019s RunEvaluator classes.\nfrom typing import Optional\nfrom langchain.evaluation import StringEvaluator\nclass MyStringEvaluator(StringEvaluator):\n    @property\n    def requires_input(self) -> bool:\n        return False\n    @property\n    def requires_reference(self) -> bool:\n        return True\n    @property\n    def evaluation_name(self) -> str:\n        return \"exact_match\"\n    def _evaluate_strings(self, prediction, reference=None, input=None, **kwargs) -> dict:\n        return {\"score\": prediction == reference}\nevaluation_config = RunEvalConfig(\n    custom_evaluators = [MyStringEvaluator()],\n)\nrun_on_dataset(\n    client,\n    \"<my_dataset_name>\",\n    construct_chain,\n    evaluation=evaluation_config,\n)\nPrimary Functions\narun_on_dataset: Asynchronous function to evaluate a chain, agent, or other LangChain component over a dataset.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-85", "text": "run_on_dataset: Function to evaluate a chain, agent, or other LangChain component over a dataset.\nRunEvalConfig: Class representing the configuration for running evaluation. You can select evaluators by EvaluatorType or config, or you can pass in custom_evaluators\nClasses\u00b6\nsmith.evaluation.config.EvalConfig\nConfiguration for a given run evaluator.\nsmith.evaluation.config.RunEvalConfig\nConfiguration for a run evaluation.\nsmith.evaluation.config.SingleKeyEvalConfig\nCreate a new model by parsing and validating input data from keyword arguments.\nsmith.evaluation.progress.ProgressBarCallback(total)\nA simple progress bar for the console.\nsmith.evaluation.runner_utils.InputFormatError\nRaised when the input format is invalid.\nsmith.evaluation.runner_utils.TestResult\nA dictionary of the results of a single test run.\nsmith.evaluation.string_run_evaluator.ChainStringRunMapper\nExtract items to evaluate from the run object from a chain.\nsmith.evaluation.string_run_evaluator.LLMStringRunMapper\nExtract items to evaluate from the run object.\nsmith.evaluation.string_run_evaluator.StringExampleMapper\nMap an example, or row in the dataset, to the inputs of an evaluation.\nsmith.evaluation.string_run_evaluator.StringRunEvaluatorChain\nEvaluate Run and optional examples.\nsmith.evaluation.string_run_evaluator.StringRunMapper\nExtract items to evaluate from the run object.\nsmith.evaluation.string_run_evaluator.ToolStringRunMapper\nMap an input to the tool.\nFunctions\u00b6\nsmith.evaluation.name_generation.random_name([...])\nGenerate a random name.\nsmith.evaluation.runner_utils.arun_on_dataset(...)\nRun the Chain or language model on a dataset and store traces to the specified project name.\nsmith.evaluation.runner_utils.run_on_dataset(...)\nRun the Chain or language model on a dataset and store traces to the specified project name.\nlangchain.storage\u00b6", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-86", "text": "langchain.storage\u00b6\nImplementations of key-value stores and storage helpers.\nModule provides implementations of various key-value stores that conform\nto a simple key-value interface.\nThe primary goal of these storages is to support implementation of caching.\nClasses\u00b6\nstorage.encoder_backed.EncoderBackedStore(...)\nWraps a store with key and value encoders/decoders.\nstorage.exceptions.InvalidKeyException\nRaised when a key is invalid; e.g., uses incorrect characters.\nstorage.file_system.LocalFileStore(root_path)\nBaseStore interface that works on the local file system.\nstorage.in_memory.InMemoryStore()\nIn-memory implementation of the BaseStore using a dictionary.\nstorage.redis.RedisStore(*[,\u00a0client,\u00a0...])\nBaseStore implementation using Redis as the underlying store.\nstorage.upstash_redis.UpstashRedisStore(*[,\u00a0...])\nBaseStore implementation using Upstash Redis as the underlying store.\nlangchain.text_splitter\u00b6\nText Splitters are classes for splitting text.\nClass hierarchy:\nBaseDocumentTransformer --> TextSplitter --> <name>TextSplitter  # Example: CharacterTextSplitter\n                                             RecursiveCharacterTextSplitter -->  <name>TextSplitter\nNote: MarkdownHeaderTextSplitter and **HTMLHeaderTextSplitter do not derive from TextSplitter.\nMain helpers:\nDocument, Tokenizer, Language, LineType, HeaderType\nClasses\u00b6\ntext_splitter.CharacterTextSplitter([...])\nSplitting text that looks at characters.\ntext_splitter.ElementType\nElement type as typed dict.\ntext_splitter.HTMLHeaderTextSplitter(...[,\u00a0...])\nSplitting HTML files based on specified headers.\ntext_splitter.HeaderType\nHeader type as typed dict.\ntext_splitter.Language(value[,\u00a0names,\u00a0...])\nEnum of the programming languages.\ntext_splitter.LatexTextSplitter(**kwargs)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-87", "text": "Enum of the programming languages.\ntext_splitter.LatexTextSplitter(**kwargs)\nAttempts to split the text along Latex-formatted layout elements.\ntext_splitter.LineType\nLine type as typed dict.\ntext_splitter.MarkdownHeaderTextSplitter(...)\nSplitting markdown files based on specified headers.\ntext_splitter.MarkdownTextSplitter(**kwargs)\nAttempts to split the text along Markdown-formatted headings.\ntext_splitter.NLTKTextSplitter([separator,\u00a0...])\nSplitting text using NLTK package.\ntext_splitter.PythonCodeTextSplitter(**kwargs)\nAttempts to split the text along Python syntax.\ntext_splitter.RecursiveCharacterTextSplitter([...])\nSplitting text by recursively look at characters.\ntext_splitter.SentenceTransformersTokenTextSplitter([...])\nSplitting text to tokens using sentence model tokenizer.\ntext_splitter.SpacyTextSplitter([separator,\u00a0...])\nSplitting text using Spacy package.\ntext_splitter.TextSplitter(chunk_size,\u00a0...)\nInterface for splitting text into chunks.\ntext_splitter.TokenTextSplitter([...])\nSplitting text to tokens using model tokenizer.\ntext_splitter.Tokenizer(chunk_overlap,\u00a0...)\nTokenizer data class.\nFunctions\u00b6\ntext_splitter.split_text_on_tokens(*,\u00a0text,\u00a0...)\nSplit incoming text and return chunks using tokenizer.\nlangchain.tools\u00b6\nTools are classes that an Agent uses to interact with the world.\nEach tool has a description. Agent uses the description to choose the right\ntool for the job.\nClass hierarchy:\nToolMetaclass --> BaseTool --> <name>Tool  # Examples: AIPluginTool, BaseGraphQLTool\n                               <name>      # Examples: BraveSearch, HumanInputRun\nMain helpers:\nCallbackManagerForToolRun, AsyncCallbackManagerForToolRun\nClasses\u00b6", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-88", "text": "Main helpers:\nCallbackManagerForToolRun, AsyncCallbackManagerForToolRun\nClasses\u00b6\ntools.ainetwork.app.AINAppOps\nTool for app operations.\ntools.ainetwork.app.AppOperationType(value)\nType of app operation as enumerator.\ntools.ainetwork.app.AppSchema\nSchema for app operations.\ntools.ainetwork.base.AINBaseTool\nBase class for the AINetwork tools.\ntools.ainetwork.base.OperationType(value[,\u00a0...])\nType of operation as enumerator.\ntools.ainetwork.owner.AINOwnerOps\nTool for owner operations.\ntools.ainetwork.owner.RuleSchema\nSchema for owner operations.\ntools.ainetwork.rule.AINRuleOps\nTool for owner operations.\ntools.ainetwork.rule.RuleSchema\nSchema for owner operations.\ntools.ainetwork.transfer.AINTransfer\nTool for transfer operations.\ntools.ainetwork.transfer.TransferSchema\nSchema for transfer operations.\ntools.ainetwork.value.AINValueOps\nTool for value operations.\ntools.ainetwork.value.ValueSchema\nSchema for value operations.\ntools.amadeus.base.AmadeusBaseTool\nBase Tool for Amadeus.\ntools.amadeus.closest_airport.AmadeusClosestAirport\nTool for finding the closest airport to a particular location.\ntools.amadeus.closest_airport.ClosestAirportSchema\nSchema for the AmadeusClosestAirport tool.\ntools.amadeus.flight_search.AmadeusFlightSearch\nTool for searching for a single flight between two airports.\ntools.amadeus.flight_search.FlightSearchSchema\nSchema for the AmadeusFlightSearch tool.\ntools.arxiv.tool.ArxivInput\nCreate a new model by parsing and validating input data from keyword arguments.\ntools.arxiv.tool.ArxivQueryRun\nTool that searches the Arxiv API.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-89", "text": "tools.arxiv.tool.ArxivQueryRun\nTool that searches the Arxiv API.\ntools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool\nTool that queries the Azure Cognitive Services Form Recognizer API.\ntools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool\nTool that queries the Azure Cognitive Services Image Analysis API.\ntools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool\nTool that queries the Azure Cognitive Services Speech2Text API.\ntools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool\nTool that queries the Azure Cognitive Services Text2Speech API.\ntools.base.BaseTool\nInterface LangChain tools must implement.\ntools.base.SchemaAnnotationError\nRaised when 'args_schema' is missing or has an incorrect type annotation.\ntools.base.StructuredTool\nTool that can operate on any number of inputs.\ntools.base.Tool\nTool that takes in function or coroutine directly.\ntools.base.ToolException\nAn optional exception that tool throws when execution error occurs.\ntools.bearly.tool.BearlyInterpreterTool(api_key)\nTool for evaluating python code in a sandbox environment.\ntools.bearly.tool.BearlyInterpreterToolArguments\nArguments for the BearlyInterpreterTool.\ntools.bearly.tool.FileInfo\nInformation about a file to be uploaded.\ntools.bing_search.tool.BingSearchResults\nTool that queries the Bing Search API and gets back json.\ntools.bing_search.tool.BingSearchRun\nTool that queries the Bing search API.\ntools.brave_search.tool.BraveSearch\nTool that queries the BraveSearch.\ntools.clickup.tool.ClickupAction\nTool that queries the  Clickup API.\ntools.dataforseo_api_search.tool.DataForSeoAPISearchResults\nTool that queries the DataForSeo Google Search API and get back json.\ntools.dataforseo_api_search.tool.DataForSeoAPISearchRun", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-90", "text": "tools.dataforseo_api_search.tool.DataForSeoAPISearchRun\nTool that queries the DataForSeo Google search API.\ntools.ddg_search.tool.DDGInput\nCreate a new model by parsing and validating input data from keyword arguments.\ntools.ddg_search.tool.DuckDuckGoSearchResults\nTool that queries the DuckDuckGo search API and gets back json.\ntools.ddg_search.tool.DuckDuckGoSearchRun\nTool that queries the DuckDuckGo search API.\ntools.e2b_data_analysis.tool.E2BDataAnalysisTool\nTool for running python code in a sandboxed environment for data analysis.\ntools.e2b_data_analysis.tool.E2BDataAnalysisToolArguments\nArguments for the E2BDataAnalysisTool.\ntools.e2b_data_analysis.tool.UploadedFile\nDescription of the uploaded path with its remote path.\ntools.e2b_data_analysis.unparse.Unparser(tree)\nMethods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded.\ntools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool\nTool that queries the Eden AI Speech To Text API.\ntools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool\nTool that queries the Eden AI Text to speech API.\ntools.edenai.edenai_base_tool.EdenaiTool\nthe base tool for all the EdenAI Tools .\ntools.edenai.image_explicitcontent.EdenAiExplicitImageTool\nTool that queries the Eden AI Explicit image detection.\ntools.edenai.image_objectdetection.EdenAiObjectDetectionTool\nTool that queries the Eden AI Object detection API.\ntools.edenai.ocr_identityparser.EdenAiParsingIDTool\nTool that queries the Eden AI  Identity parsing API.\ntools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-91", "text": "tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool\nTool that queries the Eden AI Invoice parsing API.\ntools.edenai.text_moderation.EdenAiTextModerationTool\nTool that queries the Eden AI Explicit text detection.\ntools.eleven_labs.models.ElevenLabsModel(value)\nModels available for Eleven Labs Text2Speech.\ntools.eleven_labs.text2speech.ElevenLabsModel(value)\nModels available for Eleven Labs Text2Speech.\ntools.eleven_labs.text2speech.ElevenLabsText2SpeechTool\nTool that queries the Eleven Labs Text2Speech API.\ntools.file_management.copy.CopyFileTool\nTool that copies a file.\ntools.file_management.copy.FileCopyInput\nInput for CopyFileTool.\ntools.file_management.delete.DeleteFileTool\nTool that deletes a file.\ntools.file_management.delete.FileDeleteInput\nInput for DeleteFileTool.\ntools.file_management.file_search.FileSearchInput\nInput for FileSearchTool.\ntools.file_management.file_search.FileSearchTool\nTool that searches for files in a subdirectory that match a regex pattern.\ntools.file_management.list_dir.DirectoryListingInput\nInput for ListDirectoryTool.\ntools.file_management.list_dir.ListDirectoryTool\nTool that lists files and directories in a specified folder.\ntools.file_management.move.FileMoveInput\nInput for MoveFileTool.\ntools.file_management.move.MoveFileTool\nTool that moves a file.\ntools.file_management.read.ReadFileInput\nInput for ReadFileTool.\ntools.file_management.read.ReadFileTool\nTool that reads a file.\ntools.file_management.utils.BaseFileToolMixin\nMixin for file system tools.\ntools.file_management.utils.FileValidationError\nError for paths outside the root directory.\ntools.file_management.write.WriteFileInput\nInput for WriteFileTool.\ntools.file_management.write.WriteFileTool\nTool that writes a file to disk.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-92", "text": "tools.file_management.write.WriteFileTool\nTool that writes a file to disk.\ntools.github.tool.GitHubAction\nTool for interacting with the GitHub API.\ntools.gitlab.tool.GitLabAction\nTool for interacting with the GitLab API.\ntools.gmail.base.GmailBaseTool\nBase class for Gmail tools.\ntools.gmail.create_draft.CreateDraftSchema\nInput for CreateDraftTool.\ntools.gmail.create_draft.GmailCreateDraft\nTool that creates a draft email for Gmail.\ntools.gmail.get_message.GmailGetMessage\nTool that gets a message by ID from Gmail.\ntools.gmail.get_message.SearchArgsSchema\nInput for GetMessageTool.\ntools.gmail.get_thread.GetThreadSchema\nInput for GetMessageTool.\ntools.gmail.get_thread.GmailGetThread\nTool that gets a thread by ID from Gmail.\ntools.gmail.search.GmailSearch\nTool that searches for messages or threads in Gmail.\ntools.gmail.search.Resource(value[,\u00a0names,\u00a0...])\nEnumerator of Resources to search.\ntools.gmail.search.SearchArgsSchema\nInput for SearchGmailTool.\ntools.gmail.send_message.GmailSendMessage\nTool that sends a message to Gmail.\ntools.gmail.send_message.SendMessageSchema\nInput for SendMessageTool.\ntools.golden_query.tool.GoldenQueryRun\nTool that adds the capability to query using the Golden API and get back JSON.\ntools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool\nTool that queries the Google Cloud Text to Speech API.\ntools.google_places.tool.GooglePlacesSchema\nInput for GooglePlacesTool.\ntools.google_places.tool.GooglePlacesTool\nTool that queries the Google places API.\ntools.google_scholar.tool.GoogleScholarQueryRun\nTool that queries the Google search API.\ntools.google_search.tool.GoogleSearchResults\nTool that queries the Google Search API and gets back json.\ntools.google_search.tool.GoogleSearchRun\nTool that queries the Google search API.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-93", "text": "tools.google_search.tool.GoogleSearchRun\nTool that queries the Google search API.\ntools.google_serper.tool.GoogleSerperResults\nTool that queries the Serper.dev Google Search API and get back json.\ntools.google_serper.tool.GoogleSerperRun\nTool that queries the Serper.dev Google search API.\ntools.graphql.tool.BaseGraphQLTool\nBase tool for querying a GraphQL API.\ntools.human.tool.HumanInputRun\nTool that asks user for input.\ntools.ifttt.IFTTTWebhook\nIFTTT Webhook.\ntools.jira.tool.JiraAction\nTool that queries the Atlassian Jira API.\ntools.json.tool.JsonGetValueTool\nTool for getting a value in a JSON spec.\ntools.json.tool.JsonListKeysTool\nTool for listing keys in a JSON spec.\ntools.json.tool.JsonSpec\nBase class for JSON spec.\ntools.memorize.tool.Memorize\nCreate a new model by parsing and validating input data from keyword arguments.\ntools.memorize.tool.TrainableLLM(*args,\u00a0**kwargs)\ntools.metaphor_search.tool.MetaphorSearchResults\nTool that queries the Metaphor Search API and gets back json.\ntools.multion.close_session.CloseSessionSchema\nInput for UpdateSessionTool.\ntools.multion.close_session.MultionCloseSession\nTool that closes an existing Multion Browser Window with provided fields.\ntools.multion.create_session.CreateSessionSchema\nInput for CreateSessionTool.\ntools.multion.create_session.MultionCreateSession\nTool that creates a new Multion Browser Window with provided fields.\ntools.multion.update_session.MultionUpdateSession\nTool that updates an existing Multion Browser Window with provided fields.\ntools.multion.update_session.UpdateSessionSchema\nInput for UpdateSessionTool.\ntools.nuclia.tool.NUASchema\nInput for Nuclia Understanding API.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-94", "text": "tools.nuclia.tool.NUASchema\nInput for Nuclia Understanding API.\ntools.nuclia.tool.NucliaUnderstandingAPI\nTool to process files with the Nuclia Understanding API.\ntools.office365.base.O365BaseTool\nBase class for the Office 365 tools.\ntools.office365.create_draft_message.CreateDraftMessageSchema\nInput for SendMessageTool.\ntools.office365.create_draft_message.O365CreateDraftMessage\nTool for creating a draft email in Office 365.\ntools.office365.events_search.O365SearchEvents\nClass for searching calendar events in Office 365\ntools.office365.events_search.SearchEventsInput\nInput for SearchEmails Tool.\ntools.office365.messages_search.O365SearchEmails\nClass for searching email messages in Office 365\ntools.office365.messages_search.SearchEmailsInput\nInput for SearchEmails Tool.\ntools.office365.send_event.O365SendEvent\nTool for sending calendar events in Office 365.\ntools.office365.send_event.SendEventSchema\nInput for CreateEvent Tool.\ntools.office365.send_message.O365SendMessage\nTool for sending an email in Office 365.\ntools.office365.send_message.SendMessageSchema\nInput for SendMessageTool.\ntools.openapi.utils.api_models.APIOperation\nA model for a single API operation.\ntools.openapi.utils.api_models.APIProperty\nA model for a property in the query, path, header, or cookie params.\ntools.openapi.utils.api_models.APIPropertyBase\nBase model for an API property.\ntools.openapi.utils.api_models.APIPropertyLocation(value)\nThe location of the property.\ntools.openapi.utils.api_models.APIRequestBody\nA model for a request body.\ntools.openapi.utils.api_models.APIRequestBodyProperty\nA model for a request body property.\ntools.openweathermap.tool.OpenWeatherMapQueryRun\nTool that queries the OpenWeatherMap API.\ntools.playwright.base.BaseBrowserTool\nBase class for browser tools.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-95", "text": "tools.playwright.base.BaseBrowserTool\nBase class for browser tools.\ntools.playwright.click.ClickTool\nTool for clicking on an element with the given CSS selector.\ntools.playwright.click.ClickToolInput\nInput for ClickTool.\ntools.playwright.current_page.CurrentWebPageTool\nTool for getting the URL of the current webpage.\ntools.playwright.extract_hyperlinks.ExtractHyperlinksTool\nExtract all hyperlinks on the page.\ntools.playwright.extract_hyperlinks.ExtractHyperlinksToolInput\nInput for ExtractHyperlinksTool.\ntools.playwright.extract_text.ExtractTextTool\nTool for extracting all the text on the current webpage.\ntools.playwright.get_elements.GetElementsTool\nTool for getting elements in the current web page matching a CSS selector.\ntools.playwright.get_elements.GetElementsToolInput\nInput for GetElementsTool.\ntools.playwright.navigate.NavigateTool\nTool for navigating a browser to a URL.\ntools.playwright.navigate.NavigateToolInput\nInput for NavigateToolInput.\ntools.playwright.navigate_back.NavigateBackTool\nNavigate back to the previous page in the browser history.\ntools.plugin.AIPlugin\nAI Plugin Definition.\ntools.plugin.AIPluginTool\nTool for getting the OpenAPI spec for an AI Plugin.\ntools.plugin.AIPluginToolSchema\nSchema for AIPluginTool.\ntools.plugin.ApiConfig\nAPI Configuration.\ntools.powerbi.tool.InfoPowerBITool\nTool for getting metadata about a PowerBI Dataset.\ntools.powerbi.tool.ListPowerBITool\nTool for getting tables names.\ntools.powerbi.tool.QueryPowerBITool\nTool for querying a Power BI Dataset.\ntools.pubmed.tool.PubmedQueryRun\nTool that searches the PubMed API.\ntools.requests.tool.BaseRequestsTool\nBase class for requests tools.\ntools.requests.tool.RequestsDeleteTool\nTool for making a DELETE request to an API endpoint.\ntools.requests.tool.RequestsGetTool", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-96", "text": "Tool for making a DELETE request to an API endpoint.\ntools.requests.tool.RequestsGetTool\nTool for making a GET request to an API endpoint.\ntools.requests.tool.RequestsPatchTool\nTool for making a PATCH request to an API endpoint.\ntools.requests.tool.RequestsPostTool\nTool for making a POST request to an API endpoint.\ntools.requests.tool.RequestsPutTool\nTool for making a PUT request to an API endpoint.\ntools.retriever.RetrieverInput\nCreate a new model by parsing and validating input data from keyword arguments.\ntools.scenexplain.tool.SceneXplainInput\nInput for SceneXplain.\ntools.scenexplain.tool.SceneXplainTool\nTool that explains images.\ntools.searchapi.tool.SearchAPIResults\nTool that queries the SearchApi.io search API and returns JSON.\ntools.searchapi.tool.SearchAPIRun\nTool that queries the SearchApi.io search API.\ntools.searx_search.tool.SearxSearchResults\nTool that queries a Searx instance and gets back json.\ntools.searx_search.tool.SearxSearchRun\nTool that queries a Searx instance.\ntools.shell.tool.ShellInput\nCommands for the Bash Shell tool.\ntools.shell.tool.ShellTool\nTool to run shell commands.\ntools.sleep.tool.SleepInput\nInput for CopyFileTool.\ntools.sleep.tool.SleepTool\nTool that adds the capability to sleep.\ntools.spark_sql.tool.BaseSparkSQLTool\nBase tool for interacting with Spark SQL.\ntools.spark_sql.tool.InfoSparkSQLTool\nTool for getting metadata about a Spark SQL.\ntools.spark_sql.tool.ListSparkSQLTool\nTool for getting tables names.\ntools.spark_sql.tool.QueryCheckerTool\nUse an LLM to check if a query is correct.\ntools.spark_sql.tool.QuerySparkSQLTool\nTool for querying a Spark SQL.\ntools.sql_database.tool.BaseSQLDatabaseTool", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-97", "text": "Tool for querying a Spark SQL.\ntools.sql_database.tool.BaseSQLDatabaseTool\nBase tool for interacting with a SQL database.\ntools.sql_database.tool.InfoSQLDatabaseTool\nTool for getting metadata about a SQL database.\ntools.sql_database.tool.ListSQLDatabaseTool\nTool for getting tables names.\ntools.sql_database.tool.QuerySQLCheckerTool\nUse an LLM to check if a query is correct.\ntools.sql_database.tool.QuerySQLDataBaseTool\nTool for querying a SQL database.\ntools.steamship_image_generation.tool.ModelName(value)\nSupported Image Models for generation.\ntools.steamship_image_generation.tool.SteamshipImageGenerationTool\nTool used to generate images from a text-prompt.\ntools.tavily_search.tool.TavilyAnswer\nTool that queries the Tavily Search API and gets back an answer.\ntools.tavily_search.tool.TavilyInput\nCreate a new model by parsing and validating input data from keyword arguments.\ntools.tavily_search.tool.TavilySearchResults\nTool that queries the Tavily Search API and gets back json.\ntools.vectorstore.tool.BaseVectorStoreTool\nBase class for tools that use a VectorStore.\ntools.vectorstore.tool.VectorStoreQATool\nTool for the VectorDBQA chain.\ntools.vectorstore.tool.VectorStoreQAWithSourcesTool\nTool for the VectorDBQAWithSources chain.\ntools.wikipedia.tool.WikipediaQueryRun\nTool that searches the Wikipedia API.\ntools.wolfram_alpha.tool.WolframAlphaQueryRun\nTool that queries using the Wolfram Alpha SDK.\ntools.yahoo_finance_news.YahooFinanceNewsTool\nTool that searches financial news on Yahoo Finance.\ntools.youtube.search.YouTubeSearchTool\nTool that queries YouTube.\ntools.zapier.tool.ZapierNLAListActions\nReturns a list of all exposed (enabled) actions associated with", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-98", "text": "Returns a list of all exposed (enabled) actions associated with\ntools.zapier.tool.ZapierNLARunAction\nExecutes an action that is identified by action_id, must be exposed\nFunctions\u00b6\ntools.ainetwork.utils.authenticate([network])\nAuthenticate using the AIN Blockchain\ntools.amadeus.utils.authenticate()\nAuthenticate using the Amadeus API\ntools.azure_cognitive_services.utils.detect_file_src_type(...)\nDetect if the file is local or remote.\ntools.azure_cognitive_services.utils.download_audio_from_url(...)\nDownload audio from url to local.\ntools.base.create_schema_from_function(...)\nCreate a pydantic schema from a function's signature.\ntools.base.tool(*args[,\u00a0return_direct,\u00a0...])\nMake tools out of functions, can be used with or without arguments.\ntools.bearly.tool.file_to_base64(path)\nConvert a file to base64.\ntools.bearly.tool.head_file(path,\u00a0n)\nGet the first n lines of a file.\ntools.bearly.tool.strip_markdown_code(md_string)\nStrip markdown code from a string.\ntools.ddg_search.tool.DuckDuckGoSearchTool(...)\nDeprecated.\ntools.e2b_data_analysis.tool.add_last_line_print(code)\nAdd print statement to the last line if it's missing.\ntools.e2b_data_analysis.unparse.interleave(...)\nCall f on each item in seq, calling inter() in between.\ntools.e2b_data_analysis.unparse.roundtrip(...)\ntools.file_management.utils.get_validated_relative_path(...)\nResolve a relative path, raising an error if not within the root directory.\ntools.file_management.utils.is_relative_to(...)\nCheck if path is relative to root.\ntools.gmail.utils.build_resource_service([...])\nBuild a Gmail service.\ntools.gmail.utils.clean_email_body(body)\nClean email body.\ntools.gmail.utils.get_gmail_credentials([...])", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-99", "text": "Clean email body.\ntools.gmail.utils.get_gmail_credentials([...])\nGet credentials.\ntools.gmail.utils.import_google()\nImport google libraries.\ntools.gmail.utils.import_googleapiclient_resource_builder()\nImport googleapiclient.discovery.build function.\ntools.gmail.utils.import_installed_app_flow()\nImport InstalledAppFlow class.\ntools.interaction.tool.StdInInquireTool(...)\nTool for asking the user for input.\ntools.office365.utils.authenticate()\nAuthenticate using the Microsoft Grah API\ntools.office365.utils.clean_body(body)\nClean body of a message or event.\ntools.playwright.base.lazy_import_playwright_browsers()\nLazy import playwright browsers.\ntools.playwright.utils.aget_current_page(browser)\nAsynchronously get the current page of the browser.\ntools.playwright.utils.create_async_playwright_browser([...])\nCreate an async playwright browser.\ntools.playwright.utils.create_sync_playwright_browser([...])\nCreate a playwright browser.\ntools.playwright.utils.get_current_page(browser)\nGet the current page of the browser.\ntools.playwright.utils.run_async(coro)\nRun an async coroutine.\ntools.plugin.marshal_spec(txt)\nConvert the yaml or json serialized spec to a dict.\ntools.render.format_tool_to_openai_function(tool)\nFormat tool into the OpenAI function API.\ntools.render.format_tool_to_openai_tool(tool)\nFormat tool into the OpenAI function API.\ntools.render.render_text_description(tools)\nRender the tool name and description in plain text.\ntools.render.render_text_description_and_args(tools)\nRender the tool name, description, and args in plain text.\ntools.retriever.create_retriever_tool(...)\nCreate a tool to do retrieval of documents.\ntools.steamship_image_generation.utils.make_image_public(...)\nUpload a block to a signed URL and return the public URL.\nlangchain.tools.render\u00b6", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-100", "text": "Upload a block to a signed URL and return the public URL.\nlangchain.tools.render\u00b6\nDifferent methods for rendering Tools to be passed to LLMs.\nDepending on the LLM you are using and the prompting strategy you are using,\nyou may want Tools to be rendered in a different way.\nThis module contains various ways to render tools.\nFunctions\u00b6\ntools.render.format_tool_to_openai_function(tool)\nFormat tool into the OpenAI function API.\ntools.render.format_tool_to_openai_tool(tool)\nFormat tool into the OpenAI function API.\ntools.render.render_text_description(tools)\nRender the tool name and description in plain text.\ntools.render.render_text_description_and_args(tools)\nRender the tool name, description, and args in plain text.\nlangchain.utilities\u00b6\nUtilities are the integrations with third-part systems and packages.\nOther LangChain classes use Utilities to interact with third-part systems\nand packages.\nClasses\u00b6\nutilities.alpha_vantage.AlphaVantageAPIWrapper\nWrapper for AlphaVantage API for Currency Exchange Rate.\nutilities.apify.ApifyWrapper\nWrapper around Apify.\nutilities.arcee.ArceeDocument\nArcee document.\nutilities.arcee.ArceeDocumentAdapter()\nAdapter for Arcee documents\nutilities.arcee.ArceeDocumentSource\nSource of an Arcee document.\nutilities.arcee.ArceeRoute(value[,\u00a0names,\u00a0...])\nRoutes available for the Arcee API as enumerator.\nutilities.arcee.ArceeWrapper(arcee_api_key,\u00a0...)\nWrapper for Arcee API.\nutilities.arcee.DALMFilter\nFilters available for a DALM retrieval and generation.\nutilities.arcee.DALMFilterType(value[,\u00a0...])\nFilter types available for a DALM retrieval as enumerator.\nutilities.arxiv.ArxivAPIWrapper\nWrapper around ArxivAPI.\nutilities.awslambda.LambdaWrapper", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-101", "text": "Wrapper around ArxivAPI.\nutilities.awslambda.LambdaWrapper\nWrapper for AWS Lambda SDK.\nutilities.bibtex.BibtexparserWrapper\nWrapper around bibtexparser.\nutilities.bing_search.BingSearchAPIWrapper\nWrapper for Bing Search API.\nutilities.brave_search.BraveSearchWrapper\nWrapper around the Brave search engine.\nutilities.clickup.CUList(folder_id,\u00a0name[,\u00a0...])\nComponent class for a list.\nutilities.clickup.ClickupAPIWrapper\nWrapper for Clickup API.\nutilities.clickup.Component()\nBase class for all components.\nutilities.clickup.Member(id,\u00a0username,\u00a0...)\nComponent class for a member.\nutilities.clickup.Space(id,\u00a0name,\u00a0private,\u00a0...)\nComponent class for a space.\nutilities.clickup.Task(id,\u00a0name,\u00a0...)\nClass for a task.\nutilities.clickup.Team(id,\u00a0name,\u00a0members)\nComponent class for a team.\nutilities.dalle_image_generator.DallEAPIWrapper\nWrapper for OpenAI's DALL-E Image Generator.\nutilities.dataforseo_api_search.DataForSeoAPIWrapper\nWrapper around the DataForSeo API.\nutilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper\nWrapper for DuckDuckGo Search API.\nutilities.github.GitHubAPIWrapper\nWrapper for GitHub API.\nutilities.gitlab.GitLabAPIWrapper\nWrapper for GitLab API.\nutilities.golden_query.GoldenQueryAPIWrapper\nWrapper for Golden.\nutilities.google_places_api.GooglePlacesAPIWrapper\nWrapper around Google Places API.\nutilities.google_scholar.GoogleScholarAPIWrapper\nWrapper for Google Scholar API\nutilities.google_search.GoogleSearchAPIWrapper\nWrapper for Google Search API.\nutilities.google_serper.GoogleSerperAPIWrapper\nWrapper around the Serper.dev Google Search API.\nutilities.graphql.GraphQLAPIWrapper", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-102", "text": "Wrapper around the Serper.dev Google Search API.\nutilities.graphql.GraphQLAPIWrapper\nWrapper around GraphQL API.\nutilities.jira.JiraAPIWrapper\nWrapper for Jira API.\nutilities.max_compute.MaxComputeAPIWrapper(client)\nInterface for querying Alibaba Cloud MaxCompute tables.\nutilities.metaphor_search.MetaphorSearchAPIWrapper\nWrapper for Metaphor Search API.\nutilities.openapi.HTTPVerb(value[,\u00a0names,\u00a0...])\nEnumerator of the HTTP verbs.\nutilities.openapi.OpenAPISpec()\nOpenAPI Model that removes mis-formatted parts of the spec.\nutilities.openweathermap.OpenWeatherMapAPIWrapper\nWrapper for OpenWeatherMap API using PyOWM.\nutilities.portkey.Portkey()\nPortkey configuration.\nutilities.powerbi.PowerBIDataset\nCreate PowerBI engine from dataset ID and credential or token.\nutilities.pubmed.PubMedAPIWrapper\nWrapper around PubMed API.\nutilities.python.PythonREPL\nSimulates a standalone Python REPL.\nutilities.redis.TokenEscaper([escape_chars_re])\nEscape punctuation within an input string.\nutilities.requests.Requests\nWrapper around requests to handle auth and async.\nutilities.requests.RequestsWrapper\nalias of TextRequestsWrapper\nutilities.requests.TextRequestsWrapper\nLightweight wrapper around requests library.\nutilities.scenexplain.SceneXplainAPIWrapper\nWrapper for SceneXplain API.\nutilities.searchapi.SearchApiAPIWrapper\nWrapper around SearchApi API.\nutilities.searx_search.SearxResults(data)\nDict like wrapper around search api results.\nutilities.searx_search.SearxSearchWrapper\nWrapper for Searx API.\nutilities.serpapi.HiddenPrints()\nContext manager to hide prints.\nutilities.serpapi.SerpAPIWrapper\nWrapper around SerpAPI.\nutilities.spark_sql.SparkSQL([...])\nSparkSQL is a utility class for interacting with Spark SQL.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-103", "text": "SparkSQL is a utility class for interacting with Spark SQL.\nutilities.sql_database.SQLDatabase(engine[,\u00a0...])\nSQLAlchemy wrapper around a database.\nutilities.tavily_search.TavilySearchAPIWrapper\nWrapper for Tavily Search API.\nutilities.tensorflow_datasets.TensorflowDatasets\nAccess to the TensorFlow Datasets.\nutilities.twilio.TwilioAPIWrapper\nMessaging Client using Twilio.\nutilities.wikipedia.WikipediaAPIWrapper\nWrapper around WikipediaAPI.\nutilities.wolfram_alpha.WolframAlphaAPIWrapper\nWrapper for Wolfram Alpha.\nutilities.zapier.ZapierNLAWrapper\nWrapper for Zapier NLA.\nFunctions\u00b6\nutilities.anthropic.get_num_tokens_anthropic(text)\nGet the number of tokens in a string of text.\nutilities.anthropic.get_token_ids_anthropic(text)\nGet the token ids for a string of text.\nutilities.clickup.extract_dict_elements_from_component_fields(...)\nExtract elements from a dictionary.\nutilities.clickup.fetch_data(url,\u00a0access_token)\nFetch data from a URL.\nutilities.clickup.fetch_first_id(data,\u00a0key)\nFetch the first id from a dictionary.\nutilities.clickup.fetch_folder_id(space_id,\u00a0...)\nFetch the folder id.\nutilities.clickup.fetch_list_id(space_id,\u00a0...)\nFetch the list id.\nutilities.clickup.fetch_space_id(team_id,\u00a0...)\nFetch the space id.\nutilities.clickup.fetch_team_id(access_token)\nFetch the team id.\nutilities.clickup.load_query(query[,\u00a0...])\nAttempts to parse a JSON string and return the parsed object.\nutilities.clickup.parse_dict_through_component(...)\nParse a dictionary by creating a component and then turning it back into a dictionary.\nutilities.opaqueprompts.desanitize(...)\nRestore the original sensitive data from the sanitized text.\nutilities.opaqueprompts.sanitize(input)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-104", "text": "utilities.opaqueprompts.sanitize(input)\nSanitize input string or dict of strings by replacing sensitive data with placeholders.\nutilities.powerbi.fix_table_name(table)\nAdd single quotes around table names that contain spaces.\nutilities.powerbi.json_to_md(json_contents)\nConverts a JSON object to a markdown table.\nutilities.redis.check_redis_module_exist(...)\nCheck if the correct Redis modules are installed.\nutilities.redis.get_client(redis_url,\u00a0**kwargs)\nGet a redis client from the connection url given.\nutilities.sql_database.truncate_word(...[,\u00a0...])\nTruncate a string to a certain number of words, based on the max string length.\nutilities.vertexai.get_client_info([module])\nReturns a custom user agent header.\nutilities.vertexai.init_vertexai([project,\u00a0...])\nInit vertexai.\nutilities.vertexai.raise_vertex_import_error([...])\nRaise ImportError related to Vertex SDK being not available.\nlangchain.utils\u00b6\nUtility functions for LangChain.\nThese functions do not depend on any other LangChain module.\nClasses\u00b6\nutils.aiter.NoLock()\nDummy lock that provides the proper interface but no protection\nutils.aiter.Tee(iterable[,\u00a0n,\u00a0lock])\nCreate n separate asynchronous iterators over iterable\nutils.aiter.atee\nalias of Tee\nutils.formatting.StrictFormatter()\nA subclass of formatter that checks for extra keys.\nutils.iter.NoLock()\nDummy lock that provides the proper interface but no protection\nutils.iter.Tee(iterable[,\u00a0n,\u00a0lock])\nCreate n separate asynchronous iterators over iterable\nutils.iter.safetee\nalias of Tee\nutils.openai_functions.FunctionDescription\nRepresentation of a callable function to the OpenAI API.\nutils.openai_functions.ToolDescription\nRepresentation of a callable function to the OpenAI API.\nFunctions\u00b6\nutils.aiter.py_anext(iterator[,\u00a0default])", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-105", "text": "Functions\u00b6\nutils.aiter.py_anext(iterator[,\u00a0default])\nPure-Python implementation of anext() for testing purposes.\nutils.aiter.tee_peer(iterator,\u00a0buffer,\u00a0...)\nAn individual iterator of a tee()\nutils.env.get_from_dict_or_env(data,\u00a0key,\u00a0...)\nGet a value from a dictionary or an environment variable.\nutils.env.get_from_env(key,\u00a0env_key[,\u00a0default])\nGet a value from a dictionary or an environment variable.\nutils.html.extract_sub_links(raw_html,\u00a0url,\u00a0*)\nExtract all links from a raw html string and convert into absolute paths.\nutils.html.find_all_links(raw_html,\u00a0*[,\u00a0pattern])\nExtract all links from a raw html string.\nutils.input.get_bolded_text(text)\nGet bolded text.\nutils.input.get_color_mapping(items[,\u00a0...])\nGet mapping for items to a support color.\nutils.input.get_colored_text(text,\u00a0color)\nGet colored text.\nutils.input.print_text(text[,\u00a0color,\u00a0end,\u00a0file])\nPrint text with highlighting and no end characters.\nutils.iter.batch_iterate(size,\u00a0iterable)\nUtility batching function.\nutils.iter.tee_peer(iterator,\u00a0buffer,\u00a0peers,\u00a0...)\nAn individual iterator of a tee()\nutils.json_schema.dereference_refs(schema_obj,\u00a0*)\nTry to substitute $refs in JSON Schema.\nutils.loading.try_load_from_hub(path,\u00a0...)\nLoad configuration from hub.\nutils.math.cosine_similarity(X,\u00a0Y)\nRow-wise cosine similarity between two equal-width matrices.\nutils.math.cosine_similarity_top_k(X,\u00a0Y[,\u00a0...])\nRow-wise cosine similarity with optional top-k and score threshold filtering.\nutils.openai.is_openai_v1()\nutils.openai_functions.convert_pydantic_to_openai_function(...)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-106", "text": "utils.openai_functions.convert_pydantic_to_openai_function(...)\nConverts a Pydantic model to a function description for the OpenAI API.\nutils.openai_functions.convert_pydantic_to_openai_tool(...)\nConverts a Pydantic model to a function description for the OpenAI API.\nutils.pydantic.get_pydantic_major_version()\nGet the major version of Pydantic.\nutils.strings.comma_list(items)\nConvert a list to a comma-separated string.\nutils.strings.stringify_dict(data)\nStringify a dictionary.\nutils.strings.stringify_value(val)\nStringify a value.\nutils.utils.build_extra_kwargs(extra_kwargs,\u00a0...)\nBuild extra kwargs from values and extra_kwargs.\nutils.utils.check_package_version(package[,\u00a0...])\nCheck the version of a package.\nutils.utils.convert_to_secret_str(value)\nConvert a string to a SecretStr if needed.\nutils.utils.get_pydantic_field_names(...)\nGet field names, including aliases, for a pydantic class.\nutils.utils.guard_import(module_name,\u00a0*[,\u00a0...])\nDynamically imports a module and raises a helpful exception if the module is not installed.\nutils.utils.mock_now(dt_value)\nContext manager for mocking out datetime.now() in unit tests.\nutils.utils.raise_for_status_with_text(response)\nRaise an error with the response text.\nutils.utils.xor_args(*arg_groups)\nValidate specified keyword args are mutually exclusive.\nlangchain.vectorstores\u00b6\nVector store stores embedded data and performs vector search.\nOne of the most common ways to store and search over unstructured data is to\nembed it and store the resulting embedding vectors, and then query the store\nand retrieve the data that are \u2018most similar\u2019 to the embedded query.\nClass hierarchy:\nVectorStore --> <name>  # Examples: Annoy, FAISS, Milvus", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-107", "text": "BaseRetriever --> VectorStoreRetriever --> <name>Retriever  # Example: VespaRetriever\nMain helpers:\nEmbeddings, Document\nClasses\u00b6\nvectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch(...)\nAlibaba Cloud OpenSearch vector store.\nvectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearchSettings(...)\nAlibaba Cloud Opensearch` client configuration.\nvectorstores.analyticdb.AnalyticDB(...[,\u00a0...])\nAnalyticDB (distributed PostgreSQL) vector store.\nvectorstores.annoy.Annoy(embedding_function,\u00a0...)\nAnnoy vector store.\nvectorstores.astradb.AstraDB(*,\u00a0embedding,\u00a0...)\nWrapper around DataStax Astra DB for vector-store workloads.\nvectorstores.atlas.AtlasDB(name[,\u00a0...])\nAtlas vector store.\nvectorstores.awadb.AwaDB([table_name,\u00a0...])\nAwaDB vector store.\nvectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch(...)\nAzure Cosmos DB for MongoDB vCore vector store.\nvectorstores.azure_cosmos_db.CosmosDBSimilarityType(value)\nCosmos DB Similarity Type as enumerator.\nvectorstores.azuresearch.AzureSearch(...[,\u00a0...])\nAzure Cognitive Search vector store.\nvectorstores.azuresearch.AzureSearchVectorStoreRetriever\nRetriever that uses Azure Cognitive Search.\nvectorstores.bageldb.Bagel([cluster_name,\u00a0...])\nBagelDB.ai vector store.\nvectorstores.baiducloud_vector_search.BESVectorStore(...)\nBaidu Elasticsearch vector store.\nvectorstores.cassandra.Cassandra(embedding,\u00a0...)\nWrapper around Apache Cassandra(R) for vector-store workloads.\nvectorstores.chroma.Chroma([...])\nChromaDB vector store.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-108", "text": "vectorstores.chroma.Chroma([...])\nChromaDB vector store.\nvectorstores.clarifai.Clarifai([user_id,\u00a0...])\nClarifai AI vector store.\nvectorstores.clickhouse.Clickhouse(embedding)\nClickHouse VectorSearch vector store.\nvectorstores.clickhouse.ClickhouseSettings\nClickHouse client configuration.\nvectorstores.dashvector.DashVector(...)\nDashVector vector store.\nvectorstores.deeplake.DeepLake([...])\nActiveloop Deep Lake vector store.\nvectorstores.dingo.Dingo(embedding,\u00a0text_key,\u00a0*)\nDingo vector store.\nvectorstores.docarray.base.DocArrayIndex(...)\nBase class for DocArray based vector stores.\nvectorstores.docarray.hnsw.DocArrayHnswSearch(...)\nHnswLib storage using DocArray package.\nvectorstores.docarray.in_memory.DocArrayInMemorySearch(...)\nIn-memory DocArray storage for exact search.\nvectorstores.elastic_vector_search.ElasticKnnSearch(...)\n[Deprecated]  [DEPRECATED] Elasticsearch with k-nearest neighbor search (k-NN) vector store.\nvectorstores.elastic_vector_search.ElasticVectorSearch(...)\nElasticVectorSearch uses the brute force method of searching on vectors.\nvectorstores.elasticsearch.ApproxRetrievalStrategy([...])\nApproximate retrieval strategy using the HNSW algorithm.\nvectorstores.elasticsearch.BaseRetrievalStrategy()\nBase class for Elasticsearch retrieval strategies.\nvectorstores.elasticsearch.ElasticsearchStore(...)\nElasticsearch vector store.\nvectorstores.elasticsearch.ExactRetrievalStrategy()\nExact retrieval strategy using the script_score query.\nvectorstores.elasticsearch.SparseRetrievalStrategy([...])\nSparse retrieval strategy using the text_expansion processor.\nvectorstores.epsilla.Epsilla(client,\u00a0embeddings)\nWrapper around Epsilla vector database.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-109", "text": "Wrapper around Epsilla vector database.\nvectorstores.faiss.FAISS(embedding_function,\u00a0...)\nMeta Faiss vector store.\nvectorstores.hippo.Hippo(embedding_function)\nHippo vector store.\nvectorstores.hologres.Hologres(...[,\u00a0ndims,\u00a0...])\nHologres API vector store.\nvectorstores.hologres.HologresWrapper(...)\nHologres API wrapper.\nvectorstores.lancedb.LanceDB(connection,\u00a0...)\nLanceDB vector store.\nvectorstores.llm_rails.LLMRails([...])\nImplementation of Vector Store using LLMRails.\nvectorstores.llm_rails.LLMRailsRetriever\nRetriever for LLMRails.\nvectorstores.marqo.Marqo(client,\u00a0index_name)\nMarqo vector store.\nvectorstores.matching_engine.MatchingEngine(...)\nGoogle Vertex AI Matching Engine vector store.\nvectorstores.meilisearch.Meilisearch(embedding)\nMeilisearch vector store.\nvectorstores.milvus.Milvus(embedding_function)\nMilvus vector store.\nvectorstores.momento_vector_index.MomentoVectorIndex(...)\nMomento Vector Index (MVI) vector store.\nvectorstores.mongodb_atlas.MongoDBAtlasVectorSearch(...)\nMongoDB Atlas Vector Search vector store.\nvectorstores.myscale.MyScale(embedding[,\u00a0config])\nMyScale vector store.\nvectorstores.myscale.MyScaleSettings\nMyScale client configuration.\nvectorstores.myscale.MyScaleWithoutJSON(...)\nMyScale vector store without metadata column\nvectorstores.neo4j_vector.Neo4jVector(...[,\u00a0...])\nNeo4j vector index.\nvectorstores.neo4j_vector.SearchType(value)\nEnumerator of the Distance strategies.\nvectorstores.nucliadb.NucliaDB(...[,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-110", "text": "vectorstores.nucliadb.NucliaDB(...[,\u00a0...])\nNucliaDB vector store.\nvectorstores.opensearch_vector_search.OpenSearchVectorSearch(...)\nAmazon OpenSearch Vector Engine vector store.\nvectorstores.pgembedding.BaseModel(**kwargs)\nBase model for all SQL stores.\nvectorstores.pgembedding.CollectionStore(...)\nCollection store.\nvectorstores.pgembedding.EmbeddingStore(**kwargs)\nEmbedding store.\nvectorstores.pgembedding.PGEmbedding(...[,\u00a0...])\nPostgres with the pg_embedding extension as a vector store.\nvectorstores.pgembedding.QueryResult()\nResult from a query.\nvectorstores.pgvecto_rs.PGVecto_rs(...[,\u00a0...])\nvectorstores.pgvector.BaseModel(**kwargs)\nBase model for the SQL stores.\nvectorstores.pgvector.DistanceStrategy(value)\nEnumerator of the Distance strategies.\nvectorstores.pgvector.PGVector(...[,\u00a0...])\nPostgres/PGVector vector store.\nvectorstores.pinecone.Pinecone(index,\u00a0...[,\u00a0...])\nPinecone vector store.\nvectorstores.qdrant.Qdrant(client,\u00a0...[,\u00a0...])\nQdrant vector store.\nvectorstores.qdrant.QdrantException\nQdrant related exceptions.\nvectorstores.redis.base.Redis(redis_url,\u00a0...)\nRedis vector database.\nvectorstores.redis.base.RedisVectorStoreRetriever\nRetriever for Redis VectorStore.\nvectorstores.redis.filters.RedisFilter()\nCollection of RedisFilterFields.\nvectorstores.redis.filters.RedisFilterExpression([...])\nA logical expression of RedisFilterFields.\nvectorstores.redis.filters.RedisFilterField(field)\nBase class for RedisFilterFields.\nvectorstores.redis.filters.RedisFilterOperator(value)\nRedisFilterOperator enumerator is used to create RedisFilterExpressions.\nvectorstores.redis.filters.RedisNum(field)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-111", "text": "vectorstores.redis.filters.RedisNum(field)\nA RedisFilterField representing a numeric field in a Redis index.\nvectorstores.redis.filters.RedisTag(field)\nA RedisFilterField representing a tag in a Redis index.\nvectorstores.redis.filters.RedisText(field)\nA RedisFilterField representing a text field in a Redis index.\nvectorstores.redis.schema.FlatVectorField\nSchema for flat vector fields in Redis.\nvectorstores.redis.schema.HNSWVectorField\nSchema for HNSW vector fields in Redis.\nvectorstores.redis.schema.NumericFieldSchema\nSchema for numeric fields in Redis.\nvectorstores.redis.schema.RedisDistanceMetric(value)\nDistance metrics for Redis vector fields.\nvectorstores.redis.schema.RedisField\nBase class for Redis fields.\nvectorstores.redis.schema.RedisModel\nSchema for Redis index.\nvectorstores.redis.schema.RedisVectorField\nBase class for Redis vector fields.\nvectorstores.redis.schema.TagFieldSchema\nSchema for tag fields in Redis.\nvectorstores.redis.schema.TextFieldSchema\nSchema for text fields in Redis.\nvectorstores.rocksetdb.Rockset(client,\u00a0...)\nRockset vector store.\nvectorstores.scann.ScaNN(embedding,\u00a0index,\u00a0...)\nScaNN vector store.\nvectorstores.semadb.SemaDB(collection_name,\u00a0...)\nSemaDB vector store.\nvectorstores.singlestoredb.SingleStoreDB(...)\nSingleStore DB vector store.\nvectorstores.sklearn.BaseSerializer(persist_path)\nBase class for serializing data.\nvectorstores.sklearn.BsonSerializer(persist_path)\nSerializes data in binary json using the bson python package.\nvectorstores.sklearn.JsonSerializer(persist_path)\nSerializes data in json using the json package from python standard library.\nvectorstores.sklearn.ParquetSerializer(...)\nSerializes data in Apache Parquet format using the pyarrow package.\nvectorstores.sklearn.SKLearnVectorStore(...)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-112", "text": "vectorstores.sklearn.SKLearnVectorStore(...)\nSimple in-memory vector store based on the scikit-learn library NearestNeighbors implementation.\nvectorstores.sklearn.SKLearnVectorStoreException\nException raised by SKLearnVectorStore.\nvectorstores.sqlitevss.SQLiteVSS(table,\u00a0...)\nWrapper around SQLite with vss extension as a vector database.\nvectorstores.starrocks.StarRocks(embedding)\nStarRocks vector store.\nvectorstores.starrocks.StarRocksSettings\nStarRocks client configuration.\nvectorstores.supabase.SupabaseVectorStore(...)\nSupabase Postgres vector store.\nvectorstores.tair.Tair(embedding_function,\u00a0...)\nTair vector store.\nvectorstores.tencentvectordb.ConnectionParams(...)\nTencent vector DB Connection params.\nvectorstores.tencentvectordb.IndexParams(...)\nTencent vector DB Index params.\nvectorstores.tencentvectordb.TencentVectorDB(...)\nInitialize wrapper around the tencent vector database.\nvectorstores.tigris.Tigris(client,\u00a0...)\nTigris vector store.\nvectorstores.tiledb.TileDB(embedding,\u00a0...[,\u00a0...])\nWrapper around TileDB vector database.\nvectorstores.timescalevector.TimescaleVector(...)\nVectorStore implementation using the timescale vector client to store vectors in Postgres.\nvectorstores.typesense.Typesense(...[,\u00a0...])\nTypesense vector store.\nvectorstores.usearch.USearch(embedding,\u00a0...)\nUSearch vector store.\nvectorstores.utils.DistanceStrategy(value[,\u00a0...])\nEnumerator of the Distance strategies for calculating distances between vectors.\nvectorstores.vald.Vald(embedding[,\u00a0host,\u00a0...])\nWrapper around Vald vector database.\nvectorstores.vearch.Vearch(embedding_function)\nInitialize vearch vector store flag 1 for cluster,0 for standalone", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-113", "text": "Initialize vearch vector store flag 1 for cluster,0 for standalone\nvectorstores.vectara.Vectara([...])\nVectara API vector store.\nvectorstores.vectara.VectaraRetriever\nRetriever class for Vectara.\nvectorstores.vespa.VespaStore(app[,\u00a0...])\nVespa vector store.\nvectorstores.weaviate.Weaviate(client,\u00a0...)\nWeaviate vector store.\nvectorstores.xata.XataVectorStore(api_key,\u00a0...)\nXata vector store.\nvectorstores.zep.CollectionConfig(name,\u00a0...)\nConfiguration for a Zep Collection.\nvectorstores.zep.ZepVectorStore(...[,\u00a0...])\nZep vector store.\nvectorstores.zilliz.Zilliz(embedding_function)\nZilliz vector store.\nFunctions\u00b6\nvectorstores.alibabacloud_opensearch.create_metadata(fields)\nCreate metadata from fields.\nvectorstores.annoy.dependable_annoy_import()\nImport annoy if available, otherwise raise error.\nvectorstores.clickhouse.has_mul_sub_str(s,\u00a0*args)\nCheck if a string contains multiple substrings.\nvectorstores.faiss.dependable_faiss_import([...])\nImport faiss if available, otherwise raise error.\nvectorstores.myscale.has_mul_sub_str(s,\u00a0*args)\nCheck if a string contains multiple substrings.\nvectorstores.neo4j_vector.check_if_not_null(...)\nCheck if the values are not None or empty string\nvectorstores.neo4j_vector.sort_by_index_name(...)\nSort first element to match the index_name if exists\nvectorstores.qdrant.sync_call_fallback(method)\nDecorator to call the synchronous method of the class if the async method is not implemented.\nvectorstores.redis.base.check_index_exists(...)\nCheck if Redis index exists.\nvectorstores.redis.filters.check_operator_misuse(func)", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "1a93eb904d6b-114", "text": "Check if Redis index exists.\nvectorstores.redis.filters.check_operator_misuse(func)\nDecorator to check for misuse of equality operators.\nvectorstores.redis.schema.read_schema(...)\nReads in the index schema from a dict or yaml file.\nvectorstores.scann.dependable_scann_import()\nImport scann if available, otherwise raise error.\nvectorstores.scann.normalize(x)\nNormalize vectors to unit length.\nvectorstores.starrocks.debug_output(s)\nPrint a debug message if DEBUG is True.\nvectorstores.starrocks.get_named_result(...)\nGet a named result from a query.\nvectorstores.starrocks.has_mul_sub_str(s,\u00a0*args)\nCheck if a string has multiple substrings.\nvectorstores.tiledb.dependable_tiledb_import()\nImport tiledb-vector-search if available, otherwise raise error.\nvectorstores.tiledb.get_documents_array_uri(uri)\nvectorstores.tiledb.get_documents_array_uri_from_group(group)\nvectorstores.tiledb.get_vector_index_uri(uri)\nvectorstores.tiledb.get_vector_index_uri_from_group(group)\nvectorstores.usearch.dependable_usearch_import()\nImport usearch if available, otherwise raise error.\nvectorstores.utils.filter_complex_metadata(...)\nFilter out metadata types that are not supported for a vector store.\nvectorstores.utils.maximal_marginal_relevance(...)\nCalculate maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/api_reference.html"}
{"id": "a509b383164c-0", "text": "langchain_experimental API Reference\u00b6\nlangchain_experimental.agents\u00b6\nFunctions\u00b6\nagents.agent_toolkits.csv.base.create_csv_agent(...)\nCreate csv agent by loading to a dataframe and using pandas agent.\nagents.agent_toolkits.pandas.base.create_pandas_dataframe_agent(llm,\u00a0df)\nConstruct a pandas agent from an LLM and dataframe.\nagents.agent_toolkits.python.base.create_python_agent(...)\nConstruct a python agent from an LLM and tool.\nagents.agent_toolkits.spark.base.create_spark_dataframe_agent(llm,\u00a0df)\nConstruct a Spark agent from an LLM and dataframe.\nagents.agent_toolkits.xorbits.base.create_xorbits_agent(...)\nConstruct a xorbits agent from an LLM and dataframe.\nlangchain_experimental.autonomous_agents\u00b6\nClasses\u00b6\nautonomous_agents.autogpt.agent.AutoGPT(...)\nAgent class for interacting with Auto-GPT.\nautonomous_agents.autogpt.memory.AutoGPTMemory\nMemory for AutoGPT.\nautonomous_agents.autogpt.output_parser.AutoGPTAction(...)\nAction returned by AutoGPTOutputParser.\nautonomous_agents.autogpt.output_parser.AutoGPTOutputParser\nOutput parser for AutoGPT.\nautonomous_agents.autogpt.output_parser.BaseAutoGPTOutputParser\nBase Output parser for AutoGPT.\nautonomous_agents.autogpt.prompt.AutoGPTPrompt\nPrompt for AutoGPT.\nautonomous_agents.autogpt.prompt_generator.PromptGenerator()\nA class for generating custom prompt strings.\nautonomous_agents.baby_agi.baby_agi.BabyAGI\nController model for the BabyAGI agent.\nautonomous_agents.baby_agi.task_creation.TaskCreationChain\nChain generating tasks.\nautonomous_agents.baby_agi.task_execution.TaskExecutionChain\nChain to execute tasks.\nautonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain", "source": "lang/api.python.langchain.com/en/latest/experimental_api_reference.html"}
{"id": "a509b383164c-1", "text": "autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain\nChain to prioritize tasks.\nautonomous_agents.hugginggpt.hugginggpt.HuggingGPT(...)\nautonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain\nChain to execute tasks.\nautonomous_agents.hugginggpt.repsonse_generator.ResponseGenerator(...)\nautonomous_agents.hugginggpt.task_executor.Task(...)\nautonomous_agents.hugginggpt.task_executor.TaskExecutor(plan)\nLoad tools to execute tasks.\nautonomous_agents.hugginggpt.task_planner.BasePlanner\nCreate a new model by parsing and validating input data from keyword arguments.\nautonomous_agents.hugginggpt.task_planner.Plan(steps)\nautonomous_agents.hugginggpt.task_planner.PlanningOutputParser\nCreate a new model by parsing and validating input data from keyword arguments.\nautonomous_agents.hugginggpt.task_planner.Step(...)\nautonomous_agents.hugginggpt.task_planner.TaskPlaningChain\nChain to execute tasks.\nautonomous_agents.hugginggpt.task_planner.TaskPlanner\nCreate a new model by parsing and validating input data from keyword arguments.\nFunctions\u00b6\nautonomous_agents.autogpt.output_parser.preprocess_json_input(...)\nPreprocesses a string to be parsed as json.\nautonomous_agents.autogpt.prompt_generator.get_prompt(tools)\nGenerates a prompt string.\nautonomous_agents.hugginggpt.repsonse_generator.load_response_generator(llm)\nautonomous_agents.hugginggpt.task_planner.load_chat_planner(llm)\nlangchain_experimental.chat_models\u00b6\nChat Models are a variation on language models.\nWhile Chat Models use language models under the hood, the interface they expose\nis a bit different. Rather than expose a \u201ctext in, text out\u201d API, they expose\nan interface where \u201cchat messages\u201d are the inputs and outputs.", "source": "lang/api.python.langchain.com/en/latest/experimental_api_reference.html"}
{"id": "a509b383164c-2", "text": "an interface where \u201cchat messages\u201d are the inputs and outputs.\nClass hierarchy:\nBaseLanguageModel --> BaseChatModel --> <name>  # Examples: ChatOpenAI, ChatGooglePalm\nMain helpers:\nAIMessage, BaseMessage, HumanMessage\nClasses\u00b6\nchat_models.llm_wrapper.ChatWrapper\nCreate a new model by parsing and validating input data from keyword arguments.\nchat_models.llm_wrapper.Llama2Chat\nCreate a new model by parsing and validating input data from keyword arguments.\nchat_models.llm_wrapper.Orca\nCreate a new model by parsing and validating input data from keyword arguments.\nchat_models.llm_wrapper.Vicuna\nCreate a new model by parsing and validating input data from keyword arguments.\nlangchain_experimental.comprehend_moderation\u00b6\nClasses\u00b6\ncomprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain\nA subclass of Chain, designed to apply moderation to LLMs.\ncomprehend_moderation.base_moderation.BaseModeration(client)\ncomprehend_moderation.base_moderation_callbacks.BaseModerationCallbackHandler()\ncomprehend_moderation.base_moderation_config.BaseModerationConfig\nCreate a new model by parsing and validating input data from keyword arguments.\ncomprehend_moderation.base_moderation_config.ModerationPiiConfig\nCreate a new model by parsing and validating input data from keyword arguments.\ncomprehend_moderation.base_moderation_config.ModerationPromptSafetyConfig\nCreate a new model by parsing and validating input data from keyword arguments.\ncomprehend_moderation.base_moderation_config.ModerationToxicityConfig\nCreate a new model by parsing and validating input data from keyword arguments.\ncomprehend_moderation.base_moderation_exceptions.ModerationPiiError([...])", "source": "lang/api.python.langchain.com/en/latest/experimental_api_reference.html"}
{"id": "a509b383164c-3", "text": "comprehend_moderation.base_moderation_exceptions.ModerationPiiError([...])\nException raised if PII entities are detected.\ncomprehend_moderation.base_moderation_exceptions.ModerationPromptSafetyError([...])\nException raised if Intention entities are detected.\ncomprehend_moderation.base_moderation_exceptions.ModerationToxicityError([...])\nException raised if Toxic entities are detected.\ncomprehend_moderation.pii.ComprehendPII(client)\ncomprehend_moderation.prompt_safety.ComprehendPromptSafety(client)\ncomprehend_moderation.toxicity.ComprehendToxicity(client)\nlangchain_experimental.cpal\u00b6\nClasses\u00b6\ncpal.base.CPALChain\nCausal program-aided language (CPAL) chain implementation.\ncpal.base.CausalChain\nTranslate the causal narrative into a stack of operations.\ncpal.base.InterventionChain\nSet the hypothetical conditions for the causal model.\ncpal.base.NarrativeChain\nDecompose the narrative into its story elements\ncpal.base.QueryChain\nQuery the outcome table using SQL.\ncpal.constants.Constant(value[,\u00a0names,\u00a0...])\nEnum for constants used in the CPAL.\ncpal.models.CausalModel\nCreate a new model by parsing and validating input data from keyword arguments.\ncpal.models.EntityModel\nCreate a new model by parsing and validating input data from keyword arguments.\ncpal.models.EntitySettingModel\nInitial conditions for an entity\ncpal.models.InterventionModel\naka initial conditions\ncpal.models.NarrativeModel\nRepresent the narrative input as three story elements.\ncpal.models.QueryModel\ntranslate a question about the story outcome into a programmatic expression\ncpal.models.ResultModel\nCreate a new model by parsing and validating input data from keyword arguments.\ncpal.models.StoryModel", "source": "lang/api.python.langchain.com/en/latest/experimental_api_reference.html"}
{"id": "a509b383164c-4", "text": "cpal.models.StoryModel\nCreate a new model by parsing and validating input data from keyword arguments.\ncpal.models.SystemSettingModel\nInitial global conditions for the system.\nlangchain_experimental.fallacy_removal\u00b6\nThe Chain runs a self-review of logical fallacies as determined by this paper  categorizing and defining logical fallacies https://arxiv.org/pdf/2212.07425.pdf. Modeled after Constitutional AI and in same format, but applying logical fallacies as generalized rules to remove in output\nClasses\u00b6\nfallacy_removal.base.FallacyChain\nChain for applying logical fallacy evaluations, modeled after Constitutional AI     and in same format, but applying logical fallacies as generalized rules to remove     in output\nfallacy_removal.models.LogicalFallacy\nClass for a logical fallacy.\nlangchain_experimental.generative_agents\u00b6\nGenerative Agents primitives.\nClasses\u00b6\ngenerative_agents.generative_agent.GenerativeAgent\nAn Agent as a character with memory and innate characteristics.\ngenerative_agents.memory.GenerativeAgentMemory\nMemory for the generative agent.\nlangchain_experimental.graph_transformers\u00b6\nClasses\u00b6\ngraph_transformers.diffbot.DiffbotGraphTransformer([...])\nTransforms documents into graph documents using Diffbot's NLP API.\ngraph_transformers.diffbot.NodesList()\nManages a list of nodes with associated properties.\ngraph_transformers.diffbot.SimplifiedSchema()\nProvides functionality for working with a simplified schema mapping.\nFunctions\u00b6\ngraph_transformers.diffbot.format_property_key(s)\nlangchain_experimental.llm_bash\u00b6\nChain that interprets a prompt and executes bash code to perform bash operations.\nClasses\u00b6\nllm_bash.base.LLMBashChain\nChain that interprets a prompt and executes bash operations.\nllm_bash.bash.BashProcess([strip_newlines,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/experimental_api_reference.html"}
{"id": "a509b383164c-5", "text": "llm_bash.bash.BashProcess([strip_newlines,\u00a0...])\nWrapper class for starting subprocesses.\nllm_bash.prompt.BashOutputParser\nParser for bash output.\nlangchain_experimental.llm_symbolic_math\u00b6\nChain that interprets a prompt and executes python code to do math.\nHeavily borrowed from llm_math, wrapper for SymPy\nClasses\u00b6\nllm_symbolic_math.base.LLMSymbolicMathChain\nChain that interprets a prompt and executes python code to do symbolic math.\nlangchain_experimental.llms\u00b6\nExperimental LLM wrappers.\nClasses\u00b6\nllms.anthropic_functions.AnthropicFunctions\nCreate a new model by parsing and validating input data from keyword arguments.\nllms.anthropic_functions.TagParser()\nA heavy-handed solution, but it's fast for prototyping.\nllms.jsonformer_decoder.JsonFormer\nJsonformer wrapped LLM using HuggingFace Pipeline API.\nllms.llamaapi.ChatLlamaAPI\nCreate a new model by parsing and validating input data from keyword arguments.\nllms.lmformatenforcer_decoder.LMFormatEnforcer\nLMFormatEnforcer wrapped LLM using HuggingFace Pipeline API.\nllms.rellm_decoder.RELLM\nRELLM wrapped LLM using HuggingFace Pipeline API.\nFunctions\u00b6\nllms.jsonformer_decoder.import_jsonformer()\nLazily import jsonformer.\nllms.lmformatenforcer_decoder.import_lmformatenforcer()\nLazily import lmformatenforcer.\nllms.rellm_decoder.import_rellm()\nLazily import rellm.\nlangchain_experimental.open_clip\u00b6\nClasses\u00b6\nopen_clip.open_clip.OpenCLIPEmbeddings\nCreate a new model by parsing and validating input data from keyword arguments.\nlangchain_experimental.pal_chain\u00b6", "source": "lang/api.python.langchain.com/en/latest/experimental_api_reference.html"}
{"id": "a509b383164c-6", "text": "langchain_experimental.pal_chain\u00b6\nImplements Program-Aided Language Models.\nAs in https://arxiv.org/pdf/2211.10435.pdf.\nThis is vulnerable to arbitrary code execution:\nhttps://github.com/langchain-ai/langchain/issues/5872\nClasses\u00b6\npal_chain.base.PALChain\nImplements Program-Aided Language Models (PAL).\npal_chain.base.PALValidation([...])\nInitialize a PALValidation instance.\nlangchain_experimental.plan_and_execute\u00b6\nClasses\u00b6\nplan_and_execute.agent_executor.PlanAndExecute\nPlan and execute a chain of steps.\nplan_and_execute.executors.base.BaseExecutor\nBase executor.\nplan_and_execute.executors.base.ChainExecutor\nChain executor.\nplan_and_execute.planners.base.BasePlanner\nBase planner.\nplan_and_execute.planners.base.LLMPlanner\nLLM planner.\nplan_and_execute.planners.chat_planner.PlanningOutputParser\nPlanning output parser.\nplan_and_execute.schema.BaseStepContainer\nBase step container.\nplan_and_execute.schema.ListStepContainer\nList step container.\nplan_and_execute.schema.Plan\nPlan.\nplan_and_execute.schema.PlanOutputParser\nPlan output parser.\nplan_and_execute.schema.Step\nStep.\nplan_and_execute.schema.StepResponse\nStep response.\nFunctions\u00b6\nplan_and_execute.executors.agent_executor.load_agent_executor(...)\nLoad an agent executor.\nplan_and_execute.planners.chat_planner.load_chat_planner(llm)\nLoad a chat planner.\nlangchain_experimental.prompt_injection_identifier\u00b6\nHuggingFace Security toolkit.\nClasses\u00b6\nprompt_injection_identifier.hugging_face_identifier.HuggingFaceInjectionIdentifier\nTool that uses deberta-v3-base-injection to detect prompt injection attacks.\nFunctions\u00b6\nlangchain_experimental.retrievers\u00b6\nClasses\u00b6\nretrievers.vector_sql_database.VectorSQLDatabaseChainRetriever", "source": "lang/api.python.langchain.com/en/latest/experimental_api_reference.html"}
{"id": "a509b383164c-7", "text": "Classes\u00b6\nretrievers.vector_sql_database.VectorSQLDatabaseChainRetriever\nRetriever that uses SQLDatabase as Retriever\nlangchain_experimental.rl_chain\u00b6\nClasses\u00b6\nrl_chain.base.AutoSelectionScorer\nCreate a new model by parsing and validating input data from keyword arguments.\nrl_chain.base.Embedder(*args,\u00a0**kwargs)\nrl_chain.base.Event(inputs[,\u00a0selected])\nrl_chain.base.Policy(**kwargs)\nrl_chain.base.RLChain\nThe RLChain class leverages the Vowpal Wabbit (VW) model as a learned policy for reinforcement learning.\nrl_chain.base.Selected()\nrl_chain.base.SelectionScorer\nAbstract method to grade the chosen selection or the response of the llm\nrl_chain.base.VwPolicy(model_repo,\u00a0vw_cmd,\u00a0...)\nrl_chain.metrics.MetricsTrackerAverage(step)\nrl_chain.metrics.MetricsTrackerRollingWindow(...)\nrl_chain.model_repository.ModelRepository(folder)\nrl_chain.pick_best_chain.PickBest\nPickBest is a class designed to leverage the Vowpal Wabbit (VW) model for reinforcement learning with a context, with the goal of modifying the prompt before the LLM call.\nrl_chain.pick_best_chain.PickBestEvent(...)\nrl_chain.pick_best_chain.PickBestFeatureEmbedder(...)\nText Embedder class that embeds the BasedOn and ToSelectFrom inputs into a format that can be used by the learning policy\nrl_chain.pick_best_chain.PickBestRandomPolicy(...)\nrl_chain.pick_best_chain.PickBestSelected([...])\nrl_chain.vw_logger.VwLogger(path)\nFunctions\u00b6\nrl_chain.base.BasedOn(anything)\nrl_chain.base.Embed(anything[,\u00a0keep])\nrl_chain.base.EmbedAndKeep(anything)\nrl_chain.base.ToSelectFrom(anything)\nrl_chain.base.embed(to_embed,\u00a0model[,\u00a0namespace])", "source": "lang/api.python.langchain.com/en/latest/experimental_api_reference.html"}
{"id": "a509b383164c-8", "text": "rl_chain.base.embed(to_embed,\u00a0model[,\u00a0namespace])\nEmbeds the actions or context using the SentenceTransformer model (or a model that has an encode function)\nrl_chain.base.embed_dict_type(item,\u00a0model)\nHelper function to embed a dictionary item.\nrl_chain.base.embed_list_type(item,\u00a0model[,\u00a0...])\nrl_chain.base.embed_string_type(item,\u00a0model)\nHelper function to embed a string or an _Embed object.\nrl_chain.base.get_based_on_and_to_select_from(inputs)\nrl_chain.base.is_stringtype_instance(item)\nHelper function to check if an item is a string.\nrl_chain.base.parse_lines(parser,\u00a0input_str)\nrl_chain.base.prepare_inputs_for_autoembed(inputs)\ngo over all the inputs and if something is either wrapped in _ToSelectFrom or _BasedOn, and if their inner values are not already _Embed, then wrap them in EmbedAndKeep while retaining their _ToSelectFrom or _BasedOn status\nrl_chain.base.stringify_embedding(embedding)\nlangchain_experimental.smart_llm\u00b6\nGeneralized implementation of SmartGPT (origin: https://youtu.be/wVzuvf9D9BU)\nClasses\u00b6\nsmart_llm.base.SmartLLMChain\nGeneralized implementation of SmartGPT (origin: https://youtu.be/wVzuvf9D9BU)\nlangchain_experimental.sql\u00b6\nChain for interacting with SQL Database.\nClasses\u00b6\nsql.base.SQLDatabaseChain\nChain for interacting with SQL Database.\nsql.base.SQLDatabaseSequentialChain\nChain for querying SQL database that is a sequential chain.\nsql.vector_sql.VectorSQLDatabaseChain\nChain for interacting with Vector SQL Database.\nsql.vector_sql.VectorSQLOutputParser\nOutput Parser for Vector SQL 1.\nsql.vector_sql.VectorSQLRetrieveAllOutputParser", "source": "lang/api.python.langchain.com/en/latest/experimental_api_reference.html"}
{"id": "a509b383164c-9", "text": "Output Parser for Vector SQL 1.\nsql.vector_sql.VectorSQLRetrieveAllOutputParser\nBased on VectorSQLOutputParser It also modify the SQL to get all columns\nFunctions\u00b6\nsql.vector_sql.get_result_from_sqldb(db,\u00a0cmd)\nlangchain_experimental.tabular_synthetic_data\u00b6\nClasses\u00b6\ntabular_synthetic_data.base.SyntheticDataGenerator\nGenerates synthetic data using the given LLM and few-shot template.\nFunctions\u00b6\ntabular_synthetic_data.openai.create_openai_data_generator(...)\nCreate an instance of SyntheticDataGenerator tailored for OpenAI models.\nlangchain_experimental.tools\u00b6\nClasses\u00b6\ntools.python.tool.PythonAstREPLTool\nA tool for running python code in a REPL.\ntools.python.tool.PythonInputs\nCreate a new model by parsing and validating input data from keyword arguments.\ntools.python.tool.PythonREPLTool\nA tool for running python code in a REPL.\nFunctions\u00b6\ntools.python.tool.sanitize_input(query)\nSanitize input to the python REPL.\nlangchain_experimental.tot\u00b6\nClasses\u00b6\ntot.base.ToTChain\nA Chain implementing the Tree of Thought (ToT).\ntot.checker.ToTChecker\nTree of Thought (ToT) checker.\ntot.controller.ToTController([c])\nTree of Thought (ToT) controller.\ntot.memory.ToTDFSMemory([stack])\nMemory for the Tree of Thought (ToT) chain.\ntot.prompts.CheckerOutputParser\ntot.prompts.JSONListOutputParser\nClass to parse the output of a PROPOSE_PROMPT response.\ntot.thought.Thought\nCreate a new model by parsing and validating input data from keyword arguments.\ntot.thought.ThoughtValidity(value[,\u00a0names,\u00a0...])\ntot.thought_generation.BaseThoughtGenerationStrategy\nBase class for a thought generation strategy.", "source": "lang/api.python.langchain.com/en/latest/experimental_api_reference.html"}
{"id": "a509b383164c-10", "text": "tot.thought_generation.BaseThoughtGenerationStrategy\nBase class for a thought generation strategy.\ntot.thought_generation.ProposePromptStrategy\nPropose thoughts sequentially using a \"propose prompt\".\ntot.thought_generation.SampleCoTStrategy\nSample thoughts from a Chain-of-Thought (CoT) prompt.\nlangchain_experimental.utilities\u00b6\nClasses\u00b6\nutilities.python.PythonREPL\nSimulates a standalone Python REPL.", "source": "lang/api.python.langchain.com/en/latest/experimental_api_reference.html"}
{"id": "96e420fee0e5-0", "text": "langchain.utilities.dataforseo_api_search.DataForSeoAPIWrapper\u00b6\nclass langchain.utilities.dataforseo_api_search.DataForSeoAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper around the DataForSeo API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aiosession: Optional[aiohttp.client.ClientSession] = None\u00b6\nThe aiohttp session to use for the DataForSEO SERP API.\nparam api_login: Optional[str] = None\u00b6\nThe API login to use for the DataForSEO SERP API.\nparam api_password: Optional[str] = None\u00b6\nThe API password to use for the DataForSEO SERP API.\nparam default_params: dict = {'depth': 10, 'language_code': 'en', 'location_name': 'United States', 'se_name': 'google', 'se_type': 'organic'}\u00b6\nDefault parameters to use for the DataForSEO SERP API.\nparam json_result_fields: Optional[list] = None\u00b6\nThe JSON result fields.\nparam json_result_types: Optional[list] = None\u00b6\nThe JSON result types.\nparam params: dict = {}\u00b6\nAdditional parameters to pass to the DataForSEO SERP API.\nparam top_count: Optional[int] = None\u00b6\nThe number of top results to return.\nasync aresults(url: str) \u2192 list[source]\u00b6\nasync arun(url: str) \u2192 str[source]\u00b6\nRun request to DataForSEO SERP API and parse result async.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.dataforseo_api_search.DataForSeoAPIWrapper.html"}
{"id": "96e420fee0e5-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.dataforseo_api_search.DataForSeoAPIWrapper.html"}
{"id": "96e420fee0e5-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nresults(url: str) \u2192 list[source]\u00b6\nrun(url: str) \u2192 str[source]\u00b6\nRun request to DataForSEO SERP API and parse result async.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.dataforseo_api_search.DataForSeoAPIWrapper.html"}
{"id": "96e420fee0e5-3", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nExamples using DataForSeoAPIWrapper\u00b6\nDataForSeo\nDataForSEO", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.dataforseo_api_search.DataForSeoAPIWrapper.html"}
{"id": "a653d77abd38-0", "text": "langchain.utilities.portkey.Portkey\u00b6\nclass langchain.utilities.portkey.Portkey[source]\u00b6\nPortkey configuration.\nbase\u00b6\nThe base URL for the Portkey API.\nDefault: \u201chttps://api.portkey.ai/v1/proxy\u201d\nAttributes\nbase\nMethods\nConfig(api_key[,\u00a0trace_id,\u00a0environment,\u00a0...])\n__init__()\nstatic Config(api_key: str, trace_id: Optional[str] = None, environment: Optional[str] = None, user: Optional[str] = None, organisation: Optional[str] = None, prompt: Optional[str] = None, retry_count: Optional[int] = None, cache: Optional[str] = None, cache_force_refresh: Optional[str] = None, cache_age: Optional[int] = None) \u2192 Dict[str, str][source]\u00b6\n__init__()\u00b6\nExamples using Portkey\u00b6\nLog, Trace, and Monitor\nPortkey", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.portkey.Portkey.html"}
{"id": "cfc730ee4d62-0", "text": "langchain.utilities.opaqueprompts.sanitize\u00b6\nlangchain.utilities.opaqueprompts.sanitize(input: Union[str, Dict[str, str]]) \u2192 Dict[str, Union[str, Dict[str, str]]][source]\u00b6\nSanitize input string or dict of strings by replacing sensitive data with\nplaceholders.\nIt returns the sanitized input string or dict of strings and the secure\ncontext as a dict following the format:\n{\n\u201csanitized_input\u201d: <sanitized input string or dict of strings>,\n\u201csecure_context\u201d: <secure context>\n}\nThe secure context is a bytes object that is needed to de-sanitize the response\nfrom the LLM.\nParameters\ninput \u2013 Input string or dict of strings.\nReturns\nSanitized input string or dict of strings and the secure context\nas a dict following the format:\n{\n\u201dsanitized_input\u201d: <sanitized input string or dict of strings>,\n\u201csecure_context\u201d: <secure context>\n}\nThe secure_context needs to be passed to the desanitize function.\nRaises\nValueError \u2013 If the input is not a string or dict of strings.\nImportError \u2013 If the opaqueprompts Python package is not installed.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.opaqueprompts.sanitize.html"}
{"id": "8083bd08e457-0", "text": "langchain.utilities.scenexplain.SceneXplainAPIWrapper\u00b6\nclass langchain.utilities.scenexplain.SceneXplainAPIWrapper[source]\u00b6\nBases: BaseSettings, BaseModel\nWrapper for SceneXplain API.\nIn order to set this up, you need API key for the SceneXplain API.\nYou can obtain a key by following the steps below.\n- Sign up for a free account at https://scenex.jina.ai/.\n- Navigate to the API Access page (https://scenex.jina.ai/api)\nand create a new API key.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam scenex_api_key: str [Required]\u00b6\nparam scenex_api_url: str = 'https://api.scenex.jina.ai/v1/describe'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.scenexplain.SceneXplainAPIWrapper.html"}
{"id": "8083bd08e457-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.scenexplain.SceneXplainAPIWrapper.html"}
{"id": "8083bd08e457-2", "text": "run(image: str) \u2192 str[source]\u00b6\nRun SceneXplain image explainer.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.scenexplain.SceneXplainAPIWrapper.html"}
{"id": "646781372492-0", "text": "langchain.utilities.serpapi.HiddenPrints\u00b6\nclass langchain.utilities.serpapi.HiddenPrints[source]\u00b6\nContext manager to hide prints.\nMethods\n__init__()\n__init__()\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.serpapi.HiddenPrints.html"}
{"id": "35f91cea4dfc-0", "text": "langchain.utilities.arcee.ArceeDocumentSource\u00b6\nclass langchain.utilities.arcee.ArceeDocumentSource[source]\u00b6\nBases: BaseModel\nSource of an Arcee document.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam document: str [Required]\u00b6\nparam id: str [Required]\u00b6\nparam name: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.ArceeDocumentSource.html"}
{"id": "35f91cea4dfc-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.ArceeDocumentSource.html"}
{"id": "35f91cea4dfc-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.ArceeDocumentSource.html"}
{"id": "beb3bbbd47cf-0", "text": "langchain.utilities.openapi.HTTPVerb\u00b6\nclass langchain.utilities.openapi.HTTPVerb(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnumerator of the HTTP verbs.\nGET = 'get'\u00b6\nPUT = 'put'\u00b6\nPOST = 'post'\u00b6\nDELETE = 'delete'\u00b6\nOPTIONS = 'options'\u00b6\nHEAD = 'head'\u00b6\nPATCH = 'patch'\u00b6\nTRACE = 'trace'\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.openapi.HTTPVerb.html"}
{"id": "3b445cd97a73-0", "text": "langchain.utilities.google_places_api.GooglePlacesAPIWrapper\u00b6\nclass langchain.utilities.google_places_api.GooglePlacesAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper around Google Places API.\nTo use, you should have the googlemaps python package installed,an API key for the google maps platform,\nand the environment variable \u2018\u2019GPLACES_API_KEY\u2019\u2019\nset with your API key , or pass \u2018gplaces_api_key\u2019\nas a named parameter to the constructor.\nBy default, this will return the all the results on the input query.You can use the top_k_results argument to limit the number of results.\nExample\nfrom langchain.utilities import GooglePlacesAPIWrapper\ngplaceapi = GooglePlacesAPIWrapper()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam gplaces_api_key: Optional[str] = None\u00b6\nparam top_k_results: Optional[int] = None\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_places_api.GooglePlacesAPIWrapper.html"}
{"id": "3b445cd97a73-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nfetch_place_details(place_id: str) \u2192 Optional[str][source]\u00b6\nformat_place_details(place_details: Dict[str, Any]) \u2192 Optional[str][source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_places_api.GooglePlacesAPIWrapper.html"}
{"id": "3b445cd97a73-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(query: str) \u2192 str[source]\u00b6\nRun Places search and get k number of places that exists that match.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_places_api.GooglePlacesAPIWrapper.html"}
{"id": "3f1702a287e1-0", "text": "langchain.utilities.requests.RequestsWrapper\u00b6\nlangchain.utilities.requests.RequestsWrapper\u00b6\nalias of TextRequestsWrapper\nExamples using RequestsWrapper\u00b6\nOpenAPI", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.requests.RequestsWrapper.html"}
{"id": "fe76d73d7393-0", "text": "langchain.utilities.arcee.DALMFilter\u00b6\nclass langchain.utilities.arcee.DALMFilter[source]\u00b6\nBases: BaseModel\nFilters available for a DALM retrieval and generation.\nParameters\nfield_name \u2013 The field to filter on. Can be \u2018document\u2019 or \u2018name\u2019 to filter\non your document\u2019s raw text or title. Any other field will be presumed\nto be a metadata field you included when uploading your context data\nfilter_type \u2013 Currently \u2018fuzzy_search\u2019 and \u2018strict_search\u2019 are supported.\n\u2018fuzzy_search\u2019 means a fuzzy search on the provided field is performed.\nThe exact strict doesn\u2019t need to exist in the document\nfor this to find a match.\nVery useful for scanning a document for some keyword terms.\n\u2018strict_search\u2019 means that the exact string must appear\nin the provided field.\nThis is NOT an exact eq filter. ie a document with content\n\u201cthe happy dog crossed the street\u201d will match on a strict_search of\n\u201cdog\u201d but won\u2019t match on \u201cthe dog\u201d.\nPython equivalent of return search_string in full_string.\nvalue \u2013 The actual value to search for in the context data/metadata\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam field_name: str [Required]\u00b6\nparam filter_type: langchain.utilities.arcee.DALMFilterType [Required]\u00b6\nparam value: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.DALMFilter.html"}
{"id": "fe76d73d7393-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.DALMFilter.html"}
{"id": "fe76d73d7393-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.DALMFilter.html"}
{"id": "4c8e23210d16-0", "text": "langchain.utilities.clickup.load_query\u00b6\nlangchain.utilities.clickup.load_query(query: str, fault_tolerant: bool = False) \u2192 Tuple[Optional[Dict], Optional[str]][source]\u00b6\nAttempts to parse a JSON string and return the parsed object.\nIf parsing fails, returns an error message.\nParameters\nquery \u2013 The JSON string to parse.\nReturns\nA tuple containing the parsed object or None and an error message or None.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.load_query.html"}
{"id": "9da414a44cd7-0", "text": "langchain.utilities.awslambda.LambdaWrapper\u00b6\nclass langchain.utilities.awslambda.LambdaWrapper[source]\u00b6\nBases: BaseModel\nWrapper for AWS Lambda SDK.\nTo use, you should have the boto3 package installed\nand a lambda functions built from the AWS Console or\nCLI. Set up your AWS credentials with aws configure\nExample\npip install boto3\naws configure\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam awslambda_tool_description: Optional[str] = None\u00b6\nIf passing to an agent as a tool, the description\nparam awslambda_tool_name: Optional[str] = None\u00b6\nIf passing to an agent as a tool, the tool name\nparam function_name: Optional[str] = None\u00b6\nThe name of your lambda function\nparam lambda_client: Any = None\u00b6\nThe configured boto3 client\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.awslambda.LambdaWrapper.html"}
{"id": "9da414a44cd7-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.awslambda.LambdaWrapper.html"}
{"id": "9da414a44cd7-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(query: str) \u2192 str[source]\u00b6\nInvokes the lambda function and returns the\nresult.\nParameters\nquery \u2013 an input to passed to the lambda\nfunction as the body of a JSON\nobject.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.awslambda.LambdaWrapper.html"}
{"id": "a13b2634c599-0", "text": "langchain.utilities.arxiv.ArxivAPIWrapper\u00b6\nclass langchain.utilities.arxiv.ArxivAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper around ArxivAPI.\nTo use, you should have the arxiv python package installed.\nhttps://lukasschwab.me/arxiv.py/index.html\nThis wrapper will use the Arxiv API to conduct searches and\nfetch document summaries. By default, it will return the document summaries\nof the top-k results.\nIf the query is in the form of arxiv identifier\n(see https://info.arxiv.org/help/find/index.html), it will return the paper\ncorresponding to the arxiv identifier.\nIt limits the Document content by doc_content_chars_max.\nSet doc_content_chars_max=None if you don\u2019t want to limit the content size.\ntop_k_results\u00b6\nnumber of the top-scored document used for the arxiv tool\nARXIV_MAX_QUERY_LENGTH\u00b6\nthe cut limit on the query used for the arxiv tool.\nload_max_docs\u00b6\na limit to the number of loaded documents\nload_all_available_meta\u00b6\nif True: the metadata of the loaded Documents contains all available\nmeta info (see https://lukasschwab.me/arxiv.py/index.html#Result),\nif False: the metadata contains only the published date, title,\nauthors and summary.\ndoc_content_chars_max\u00b6\nan optional cut limit for the length of a document\u2019s\ncontent\nExample\nfrom langchain.utilities.arxiv import ArxivAPIWrapper\narxiv = ArxivAPIWrapper(\n    top_k_results = 3,\n    ARXIV_MAX_QUERY_LENGTH = 300,\n    load_max_docs = 3,\n    load_all_available_meta = False,\n    doc_content_chars_max = 40000\n)\narxiv.run(\"tree of thought llm)", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arxiv.ArxivAPIWrapper.html"}
{"id": "a13b2634c599-1", "text": ")\narxiv.run(\"tree of thought llm)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ARXIV_MAX_QUERY_LENGTH: int = 300\u00b6\nparam arxiv_exceptions: Any = None\u00b6\nparam doc_content_chars_max: Optional[int] = 4000\u00b6\nparam load_all_available_meta: bool = False\u00b6\nparam load_max_docs: int = 100\u00b6\nparam top_k_results: int = 3\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arxiv.ArxivAPIWrapper.html"}
{"id": "a13b2634c599-2", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_summaries_as_docs(query: str) \u2192 List[Document][source]\u00b6\nPerforms an arxiv search and returns list of\ndocuments, with summaries as the content.\nIf an error occurs or no documents found, error text\nis returned instead. Wrapper for\nhttps://lukasschwab.me/arxiv.py/index.html#Search\nParameters\nquery \u2013 a plaintext search query\nis_arxiv_identifier(query: str) \u2192 bool[source]\u00b6\nCheck if a query is an arxiv identifier.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arxiv.ArxivAPIWrapper.html"}
{"id": "a13b2634c599-3", "text": "load(query: str) \u2192 List[Document][source]\u00b6\nRun Arxiv search and get the article texts plus the article meta information.\nSee https://lukasschwab.me/arxiv.py/index.html#Search\nReturns: a list of documents with the document.page_content in text format\nPerforms an arxiv search, downloads the top k results as PDFs, loads\nthem as Documents, and returns them in a List.\nParameters\nquery \u2013 a plaintext search query\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(query: str) \u2192 str[source]\u00b6\nPerforms an arxiv search and A single string\nwith the publish date, title, authors, and summary\nfor each article separated by two newlines.\nIf an error occurs or no documents found, error text\nis returned instead. Wrapper for\nhttps://lukasschwab.me/arxiv.py/index.html#Search\nParameters\nquery \u2013 a plaintext search query\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using ArxivAPIWrapper\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arxiv.ArxivAPIWrapper.html"}
{"id": "a13b2634c599-4", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nExamples using ArxivAPIWrapper\u00b6\nArXiv", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arxiv.ArxivAPIWrapper.html"}
{"id": "06bd70da544f-0", "text": "langchain.utilities.google_scholar.GoogleScholarAPIWrapper\u00b6\nclass langchain.utilities.google_scholar.GoogleScholarAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for Google Scholar API\nYou can create serpapi key by signing up at: https://serpapi.com/users/sign_up.\nThe wrapper uses the serpapi python package:\nhttps://serpapi.com/integrations/python#search-google-scholar\nTo use, you should have the environment variable SERP_API_KEY\nset with your API key, or pass serp_api_key as a named parameter\nto the constructor.\ntop_k_results\u00b6\nnumber of results to return from google-scholar query search.\nBy default it returns top 10 results.\nhl\u00b6\nattribute defines the language to use for the Google Scholar search.\nIt\u2019s a two-letter language code.\n(e.g., en for English, es for Spanish, or fr for French). Head to the\nGoogle languages page for a full list of supported Google languages:\nhttps://serpapi.com/google-languages\nlr\u00b6\nattribute defines one or multiple languages to limit the search to.\nIt uses lang_{two-letter language code} to specify languages\nand | as a delimiter. (e.g., lang_fr|lang_de will only search French\nand German pages). Head to the Google lr languages for a full\nlist of supported languages: https://serpapi.com/google-lr-languages\nExample:\nfrom langchain.utilities import GoogleScholarAPIWrapper\ngoogle_scholar = GoogleScholarAPIWrapper()\ngoogle_scholar.run(\u2018langchain\u2019)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam hl: str = 'en'\u00b6\nparam lr: str = 'lang_en'\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_scholar.GoogleScholarAPIWrapper.html"}
{"id": "06bd70da544f-1", "text": "param lr: str = 'lang_en'\u00b6\nparam serp_api_key: Optional[str] = None\u00b6\nparam top_k_results: int = 10\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_scholar.GoogleScholarAPIWrapper.html"}
{"id": "06bd70da544f-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(query: str) \u2192 str[source]\u00b6\nRun query through GoogleSearchScholar and parse result\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_scholar.GoogleScholarAPIWrapper.html"}
{"id": "32590fae3b14-0", "text": "langchain.utilities.clickup.fetch_team_id\u00b6\nlangchain.utilities.clickup.fetch_team_id(access_token: str) \u2192 Optional[int][source]\u00b6\nFetch the team id.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.fetch_team_id.html"}
{"id": "f08a53d49b60-0", "text": "langchain.utilities.clickup.ClickupAPIWrapper\u00b6\nclass langchain.utilities.clickup.ClickupAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for Clickup API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam access_token: Optional[str] = None\u00b6\nparam folder_id: Optional[str] = None\u00b6\nparam list_id: Optional[str] = None\u00b6\nparam space_id: Optional[str] = None\u00b6\nparam team_id: Optional[str] = None\u00b6\nattempt_parse_teams(input_dict: dict) \u2192 Dict[str, List[dict]][source]\u00b6\nParse appropriate content from the list of teams.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_folder(query: str) \u2192 Dict[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.ClickupAPIWrapper.html"}
{"id": "f08a53d49b60-1", "text": "Returns\nnew model instance\ncreate_folder(query: str) \u2192 Dict[source]\u00b6\nCreates a new folder.\ncreate_list(query: str) \u2192 Dict[source]\u00b6\nCreates a new list.\ncreate_task(query: str) \u2192 Dict[source]\u00b6\nCreates a new task.\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_access_code_url(oauth_client_id: str, redirect_uri: str = 'https://google.com') \u2192 str[source]\u00b6\nGet the URL to get an access code.\nclassmethod get_access_token(oauth_client_id: str, oauth_client_secret: str, code: str) \u2192 Optional[str][source]\u00b6\nGet the access token.\nget_authorized_teams() \u2192 Dict[Any, Any][source]\u00b6\nGet all teams for the user.\nget_default_params() \u2192 Dict[source]\u00b6\nget_folders() \u2192 Dict[source]\u00b6\nGet all the folders for the team.\nget_headers() \u2192 Mapping[str, Union[str, bytes]][source]\u00b6\nGet the headers for the request.\nget_lists() \u2192 Dict[source]\u00b6\nGet all available lists.\nget_spaces() \u2192 Dict[source]\u00b6\nGet all spaces for the team.\nget_task(query: str, fault_tolerant: bool = True) \u2192 Dict[source]\u00b6\nRetrieve a specific task.\nget_task_attribute(query: str) \u2192 Dict[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.ClickupAPIWrapper.html"}
{"id": "f08a53d49b60-2", "text": "Retrieve a specific task.\nget_task_attribute(query: str) \u2192 Dict[source]\u00b6\nUpdate an attribute of a specified task.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nquery_tasks(query: str) \u2192 Dict[source]\u00b6\nQuery tasks that match certain fields\nrun(mode: str, query: str) \u2192 str[source]\u00b6\nRun the API.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.ClickupAPIWrapper.html"}
{"id": "f08a53d49b60-3", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nupdate_task(query: str) \u2192 Dict[source]\u00b6\nUpdate an attribute of a specified task.\nupdate_task_assignees(query: str) \u2192 Dict[source]\u00b6\nAdd or remove assignees of a specified task.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.ClickupAPIWrapper.html"}
{"id": "a390124055cb-0", "text": "langchain.utilities.sql_database.SQLDatabase\u00b6\nclass langchain.utilities.sql_database.SQLDatabase(engine: Engine, schema: Optional[str] = None, metadata: Optional[MetaData] = None, ignore_tables: Optional[List[str]] = None, include_tables: Optional[List[str]] = None, sample_rows_in_table_info: int = 3, indexes_in_table_info: bool = False, custom_table_info: Optional[dict] = None, view_support: bool = False, max_string_length: int = 300)[source]\u00b6\nSQLAlchemy wrapper around a database.\nCreate engine from database URI.\nAttributes\ndialect\nReturn string representation of dialect to use.\ntable_info\nInformation about all tables in the database.\nMethods\n__init__(engine[,\u00a0schema,\u00a0metadata,\u00a0...])\nCreate engine from database URI.\nfrom_cnosdb([url,\u00a0user,\u00a0password,\u00a0tenant,\u00a0...])\nClass method to create an SQLDatabase instance from a CnosDB connection.\nfrom_databricks(catalog,\u00a0schema[,\u00a0host,\u00a0...])\nClass method to create an SQLDatabase instance from a Databricks connection.\nfrom_uri(database_uri[,\u00a0engine_args])\nConstruct a SQLAlchemy engine from URI.\nget_table_info([table_names])\nGet information about specified tables.\nget_table_info_no_throw([table_names])\nGet information about specified tables.\nget_table_names()\nGet names of tables available.\nget_usable_table_names()\nGet names of tables available.\nrun(command[,\u00a0fetch])\nExecute a SQL command and return a string representing the results.\nrun_no_throw(command[,\u00a0fetch])\nExecute a SQL command and return a string representing the results.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.sql_database.SQLDatabase.html"}
{"id": "a390124055cb-1", "text": "Execute a SQL command and return a string representing the results.\n__init__(engine: Engine, schema: Optional[str] = None, metadata: Optional[MetaData] = None, ignore_tables: Optional[List[str]] = None, include_tables: Optional[List[str]] = None, sample_rows_in_table_info: int = 3, indexes_in_table_info: bool = False, custom_table_info: Optional[dict] = None, view_support: bool = False, max_string_length: int = 300)[source]\u00b6\nCreate engine from database URI.\nclassmethod from_cnosdb(url: str = '127.0.0.1:8902', user: str = 'root', password: str = '', tenant: str = 'cnosdb', database: str = 'public') \u2192 SQLDatabase[source]\u00b6\nClass method to create an SQLDatabase instance from a CnosDB connection.\nThis method requires the \u2018cnos-connector\u2019 package. If not installed, it\ncan be added using pip install cnos-connector.\nParameters\nurl (str) \u2013 The HTTP connection host name and port number of the CnosDB\nservice, excluding \u201chttp://\u201d or \u201chttps://\u201d, with a default value\nof \u201c127.0.0.1:8902\u201d.\nuser (str) \u2013 The username used to connect to the CnosDB service, with a\ndefault value of \u201croot\u201d.\npassword (str) \u2013 The password of the user connecting to the CnosDB service,\nwith a default value of \u201c\u201d.\ntenant (str) \u2013 The name of the tenant used to connect to the CnosDB service,\nwith a default value of \u201ccnosdb\u201d.\ndatabase (str) \u2013 The name of the database in the CnosDB tenant.\nReturns\nAn instance of SQLDatabase configured with the provided\nCnosDB connection details.\nReturn type\nSQLDatabase", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.sql_database.SQLDatabase.html"}
{"id": "a390124055cb-2", "text": "CnosDB connection details.\nReturn type\nSQLDatabase\nclassmethod from_databricks(catalog: str, schema: str, host: Optional[str] = None, api_token: Optional[str] = None, warehouse_id: Optional[str] = None, cluster_id: Optional[str] = None, engine_args: Optional[dict] = None, **kwargs: Any) \u2192 SQLDatabase[source]\u00b6\nClass method to create an SQLDatabase instance from a Databricks connection.\nThis method requires the \u2018databricks-sql-connector\u2019 package. If not installed,\nit can be added using pip install databricks-sql-connector.\nParameters\ncatalog (str) \u2013 The catalog name in the Databricks database.\nschema (str) \u2013 The schema name in the catalog.\nhost (Optional[str]) \u2013 The Databricks workspace hostname, excluding\n\u2018https://\u2019 part. If not provided, it attempts to fetch from the\nenvironment variable \u2018DATABRICKS_HOST\u2019. If still unavailable and if\nrunning in a Databricks notebook, it defaults to the current workspace\nhostname. Defaults to None.\napi_token (Optional[str]) \u2013 The Databricks personal access token for\naccessing the Databricks SQL warehouse or the cluster. If not provided,\nit attempts to fetch from \u2018DATABRICKS_TOKEN\u2019. If still unavailable\nand running in a Databricks notebook, a temporary token for the current\nuser is generated. Defaults to None.\nwarehouse_id (Optional[str]) \u2013 The warehouse ID in the Databricks SQL. If\nprovided, the method configures the connection to use this warehouse.\nCannot be used with \u2018cluster_id\u2019. Defaults to None.\ncluster_id (Optional[str]) \u2013 The cluster ID in the Databricks Runtime. If\nprovided, the method configures the connection to use this cluster.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.sql_database.SQLDatabase.html"}
{"id": "a390124055cb-3", "text": "provided, the method configures the connection to use this cluster.\nCannot be used with \u2018warehouse_id\u2019. If running in a Databricks notebook\nand both \u2018warehouse_id\u2019 and \u2018cluster_id\u2019 are None, it uses the ID of the\ncluster the notebook is attached to. Defaults to None.\nengine_args (Optional[dict]) \u2013 The arguments to be used when connecting\nDatabricks. Defaults to None.\n**kwargs (Any) \u2013 Additional keyword arguments for the from_uri method.\nReturns\nAn instance of SQLDatabase configured with the providedDatabricks connection details.\nReturn type\nSQLDatabase\nRaises\nValueError \u2013 If \u2018databricks-sql-connector\u2019 is not found, or if both\n    \u2018warehouse_id\u2019 and \u2018cluster_id\u2019 are provided, or if neither\n    \u2018warehouse_id\u2019 nor \u2018cluster_id\u2019 are provided and it\u2019s not executing\n    inside a Databricks notebook.\nclassmethod from_uri(database_uri: str, engine_args: Optional[dict] = None, **kwargs: Any) \u2192 SQLDatabase[source]\u00b6\nConstruct a SQLAlchemy engine from URI.\nget_table_info(table_names: Optional[List[str]] = None) \u2192 str[source]\u00b6\nGet information about specified tables.\nFollows best practices as specified in: Rajkumar et al, 2022\n(https://arxiv.org/abs/2204.00498)\nIf sample_rows_in_table_info, the specified number of sample rows will be\nappended to each table description. This can increase performance as\ndemonstrated in the paper.\nget_table_info_no_throw(table_names: Optional[List[str]] = None) \u2192 str[source]\u00b6\nGet information about specified tables.\nFollows best practices as specified in: Rajkumar et al, 2022\n(https://arxiv.org/abs/2204.00498)", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.sql_database.SQLDatabase.html"}
{"id": "a390124055cb-4", "text": "(https://arxiv.org/abs/2204.00498)\nIf sample_rows_in_table_info, the specified number of sample rows will be\nappended to each table description. This can increase performance as\ndemonstrated in the paper.\nget_table_names() \u2192 Iterable[str][source]\u00b6\nGet names of tables available.\nget_usable_table_names() \u2192 Iterable[str][source]\u00b6\nGet names of tables available.\nrun(command: str, fetch: Union[Literal['all'], Literal['one']] = 'all') \u2192 str[source]\u00b6\nExecute a SQL command and return a string representing the results.\nIf the statement returns rows, a string of the results is returned.\nIf the statement returns no rows, an empty string is returned.\nrun_no_throw(command: str, fetch: Union[Literal['all'], Literal['one']] = 'all') \u2192 str[source]\u00b6\nExecute a SQL command and return a string representing the results.\nIf the statement returns rows, a string of the results is returned.\nIf the statement returns no rows, an empty string is returned.\nIf the statement throws an error, the error message is returned.\nExamples using SQLDatabase\u00b6\nRebuff\nSQL Database\nMultiple Retrieval Sources\nSet env var OPENAI_API_KEY or load from a .env file\nVector SQL Retriever with MyScale\nSQL\nsql_db.md", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.sql_database.SQLDatabase.html"}
{"id": "67c2259f4c03-0", "text": "langchain.utilities.wikipedia.WikipediaAPIWrapper\u00b6\nclass langchain.utilities.wikipedia.WikipediaAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper around WikipediaAPI.\nTo use, you should have the wikipedia python package installed.\nThis wrapper will use the Wikipedia API to conduct searches and\nfetch page summaries. By default, it will return the page summaries\nof the top-k results.\nIt limits the Document content by doc_content_chars_max.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam doc_content_chars_max: int = 4000\u00b6\nparam lang: str = 'en'\u00b6\nparam load_all_available_meta: bool = False\u00b6\nparam top_k_results: int = 3\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.wikipedia.WikipediaAPIWrapper.html"}
{"id": "67c2259f4c03-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nload(query: str) \u2192 List[Document][source]\u00b6\nRun Wikipedia search and get the article text plus the meta information.\nSee\nReturns: a list of documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.wikipedia.WikipediaAPIWrapper.html"}
{"id": "67c2259f4c03-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(query: str) \u2192 str[source]\u00b6\nRun Wikipedia search and get page summaries.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using WikipediaAPIWrapper\u00b6\nWikipedia\nZep Memory", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.wikipedia.WikipediaAPIWrapper.html"}
{"id": "2939f093700d-0", "text": "langchain.utilities.clickup.parse_dict_through_component\u00b6\nlangchain.utilities.clickup.parse_dict_through_component(data: dict, component: Type[Component], fault_tolerant: bool = False) \u2192 Dict[source]\u00b6\nParse a dictionary by creating\na component and then turning it back into a dictionary.\nThis helps with two things\n1. Extract and format data from a dictionary according to schema\n2. Provide a central place to do this in a fault-tolerant way", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.parse_dict_through_component.html"}
{"id": "3ed3fa651395-0", "text": "langchain.utilities.vertexai.get_client_info\u00b6\nlangchain.utilities.vertexai.get_client_info(module: Optional[str] = None) \u2192 ClientInfo[source]\u00b6\nReturns a custom user agent header.\nParameters\nmodule (Optional[str]) \u2013 Optional. The module for a custom user agent header.\nReturns\ngoogle.api_core.gapic_v1.client_info.ClientInfo", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.vertexai.get_client_info.html"}
{"id": "2edc1facc014-0", "text": "langchain.utilities.golden_query.GoldenQueryAPIWrapper\u00b6\nclass langchain.utilities.golden_query.GoldenQueryAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for Golden.\nDocs for using:\nGo to https://golden.com and sign up for an account\nGet your API Key from https://golden.com/settings/api\nSave your API Key into GOLDEN_API_KEY env variable\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam golden_api_key: Optional[str] = None\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.golden_query.GoldenQueryAPIWrapper.html"}
{"id": "2edc1facc014-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(query: str) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.golden_query.GoldenQueryAPIWrapper.html"}
{"id": "2edc1facc014-2", "text": "run(query: str) \u2192 str[source]\u00b6\nRun query through Golden Query API and return the JSON raw result.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using GoldenQueryAPIWrapper\u00b6\nGolden Query\nGolden", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.golden_query.GoldenQueryAPIWrapper.html"}
{"id": "f57de50f843b-0", "text": "langchain.utilities.clickup.fetch_space_id\u00b6\nlangchain.utilities.clickup.fetch_space_id(team_id: int, access_token: str) \u2192 Optional[int][source]\u00b6\nFetch the space id.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.fetch_space_id.html"}
{"id": "f1058e9130ea-0", "text": "langchain.utilities.twilio.TwilioAPIWrapper\u00b6\nclass langchain.utilities.twilio.TwilioAPIWrapper[source]\u00b6\nBases: BaseModel\nMessaging Client using Twilio.\nTo use, you should have the twilio python package installed,\nand the environment variables TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and\nTWILIO_FROM_NUMBER, or pass account_sid, auth_token, and from_number as\nnamed parameters to the constructor.\nExample\nfrom langchain.utilities.twilio import TwilioAPIWrapper\ntwilio = TwilioAPIWrapper(\n    account_sid=\"ACxxx\",\n    auth_token=\"xxx\",\n    from_number=\"+10123456789\"\n)\ntwilio.run('test', '+12484345508')\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam account_sid: Optional[str] = None\u00b6\nTwilio account string identifier.\nparam auth_token: Optional[str] = None\u00b6\nTwilio auth token.\nparam from_number: Optional[str] = None\u00b6\nA Twilio phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164)\nformat, an\n[alphanumeric sender ID](https://www.twilio.com/docs/sms/send-messages#use-an-alphanumeric-sender-id),\nor a [Channel Endpoint address](https://www.twilio.com/docs/sms/channels#channel-addresses)\nthat is enabled for the type of message you want to send. Phone numbers or\n[short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from\nTwilio also work here. You cannot, for example, spoof messages from a private\ncell phone number. If you are using messaging_service_sid, this parameter\nmust be empty.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.twilio.TwilioAPIWrapper.html"}
{"id": "f1058e9130ea-1", "text": "cell phone number. If you are using messaging_service_sid, this parameter\nmust be empty.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.twilio.TwilioAPIWrapper.html"}
{"id": "f1058e9130ea-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(body: str, to: str) \u2192 str[source]\u00b6\nRun body through Twilio and respond with message sid.\nParameters\nbody \u2013 The text of the message you want to send. Can be up to 1,600\ncharacters in length.\nto \u2013 The destination phone number in\n[E.164](https://www.twilio.com/docs/glossary/what-e164) format for\nSMS/MMS or\n[Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses)\nfor other 3rd-party channels.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.twilio.TwilioAPIWrapper.html"}
{"id": "f1058e9130ea-3", "text": "for other 3rd-party channels.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using TwilioAPIWrapper\u00b6\nTwilio", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.twilio.TwilioAPIWrapper.html"}
{"id": "818a639c0896-0", "text": "langchain.utilities.powerbi.PowerBIDataset\u00b6\nclass langchain.utilities.powerbi.PowerBIDataset[source]\u00b6\nBases: BaseModel\nCreate PowerBI engine from dataset ID and credential or token.\nUse either the credential or a supplied token to authenticate.\nIf both are supplied the credential is used to generate a token.\nThe impersonated_user_name is the UPN of a user to be impersonated.\nIf the model is not RLS enabled, this will be ignored.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aiosession: Optional[aiohttp.ClientSession] = None\u00b6\nparam credential: Optional[TokenCredential] = None\u00b6\nparam dataset_id: str [Required]\u00b6\nparam group_id: Optional[str] = None\u00b6\nparam impersonated_user_name: Optional[str] = None\u00b6\nparam sample_rows_in_table_info: int = 1\u00b6\nConstraints\nexclusiveMinimum = 0\nmaximum = 10\nparam schemas: Dict[str, str] [Optional]\u00b6\nparam table_names: List[str] [Required]\u00b6\nparam token: Optional[str] = None\u00b6\nasync aget_table_info(table_names: Optional[Union[List[str], str]] = None) \u2192 str[source]\u00b6\nGet information about specified tables.\nasync arun(command: str) \u2192 Any[source]\u00b6\nExecute a DAX command and return the result asynchronously.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.powerbi.PowerBIDataset.html"}
{"id": "818a639c0896-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_schemas() \u2192 str[source]\u00b6\nGet the available schema\u2019s.\nget_table_info(table_names: Optional[Union[List[str], str]] = None) \u2192 str[source]\u00b6\nGet information about specified tables.\nget_table_names() \u2192 Iterable[str][source]\u00b6\nGet names of tables available.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.powerbi.PowerBIDataset.html"}
{"id": "818a639c0896-2", "text": "get_table_names() \u2192 Iterable[str][source]\u00b6\nGet names of tables available.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(command: str) \u2192 Any[source]\u00b6\nExecute a DAX command and return a json representing the results.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.powerbi.PowerBIDataset.html"}
{"id": "818a639c0896-3", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nproperty headers: Dict[str, str]\u00b6\nGet the token.\nproperty request_url: str\u00b6\nGet the request url.\nproperty table_info: str\u00b6\nInformation about all tables in the database.\nExamples using PowerBIDataset\u00b6\nPowerBI Dataset", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.powerbi.PowerBIDataset.html"}
{"id": "25aea3bfd89d-0", "text": "langchain.utilities.redis.TokenEscaper\u00b6\nclass langchain.utilities.redis.TokenEscaper(escape_chars_re: Optional[Pattern] = None)[source]\u00b6\nEscape punctuation within an input string.\nAttributes\nDEFAULT_ESCAPED_CHARS\nMethods\n__init__([escape_chars_re])\nescape(value)\n__init__(escape_chars_re: Optional[Pattern] = None)[source]\u00b6\nescape(value: str) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.redis.TokenEscaper.html"}
{"id": "543cc83a9017-0", "text": "langchain.utilities.anthropic.get_token_ids_anthropic\u00b6\nlangchain.utilities.anthropic.get_token_ids_anthropic(text: str) \u2192 List[int][source]\u00b6\nGet the token ids for a string of text.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.anthropic.get_token_ids_anthropic.html"}
{"id": "d8abb7621c75-0", "text": "langchain.utilities.anthropic.get_num_tokens_anthropic\u00b6\nlangchain.utilities.anthropic.get_num_tokens_anthropic(text: str) \u2192 int[source]\u00b6\nGet the number of tokens in a string of text.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.anthropic.get_num_tokens_anthropic.html"}
{"id": "a629d75b53ee-0", "text": "langchain.utilities.clickup.fetch_data\u00b6\nlangchain.utilities.clickup.fetch_data(url: str, access_token: str, query: Optional[dict] = None) \u2192 dict[source]\u00b6\nFetch data from a URL.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.fetch_data.html"}
{"id": "30194cd32d1a-0", "text": "langchain.utilities.serpapi.SerpAPIWrapper\u00b6\nclass langchain.utilities.serpapi.SerpAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper around SerpAPI.\nTo use, you should have the google-search-results python package installed,\nand the environment variable SERPAPI_API_KEY set with your API key, or pass\nserpapi_api_key as a named parameter to the constructor.\nExample\nfrom langchain.utilities import SerpAPIWrapper\nserpapi = SerpAPIWrapper()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aiosession: Optional[aiohttp.client.ClientSession] = None\u00b6\nparam params: dict = {'engine': 'google', 'gl': 'us', 'google_domain': 'google.com', 'hl': 'en'}\u00b6\nparam serpapi_api_key: Optional[str] = None\u00b6\nasync aresults(query: str) \u2192 dict[source]\u00b6\nUse aiohttp to run query through SerpAPI and return the results async.\nasync arun(query: str, **kwargs: Any) \u2192 str[source]\u00b6\nRun query through SerpAPI and parse result async.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.serpapi.SerpAPIWrapper.html"}
{"id": "30194cd32d1a-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_params(query: str) \u2192 Dict[str, str][source]\u00b6\nGet parameters for SerpAPI.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.serpapi.SerpAPIWrapper.html"}
{"id": "30194cd32d1a-2", "text": "Get parameters for SerpAPI.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nresults(query: str) \u2192 dict[source]\u00b6\nRun query through SerpAPI and return the raw result.\nrun(query: str, **kwargs: Any) \u2192 str[source]\u00b6\nRun query through SerpAPI and parse result.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.serpapi.SerpAPIWrapper.html"}
{"id": "30194cd32d1a-3", "text": "Try to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using SerpAPIWrapper\u00b6\nSerpAPI\nBittensor\nAutoGPT", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.serpapi.SerpAPIWrapper.html"}
{"id": "6a1ab553dc73-0", "text": "langchain.utilities.arcee.DALMFilterType\u00b6\nclass langchain.utilities.arcee.DALMFilterType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nFilter types available for a DALM retrieval as enumerator.\nfuzzy_search = 'fuzzy_search'\u00b6\nstrict_search = 'strict_search'\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.DALMFilterType.html"}
{"id": "d9ca59353dce-0", "text": "langchain.utilities.clickup.Space\u00b6\nclass langchain.utilities.clickup.Space(id: int, name: str, private: bool, enabled_features: Dict[str, Any])[source]\u00b6\nComponent class for a space.\nAttributes\nid\nname\nprivate\nenabled_features\nMethods\n__init__(id,\u00a0name,\u00a0private,\u00a0enabled_features)\nfrom_data(data)\n__init__(id: int, name: str, private: bool, enabled_features: Dict[str, Any]) \u2192 None\u00b6\nclassmethod from_data(data: Dict[str, Any]) \u2192 Space[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.Space.html"}
{"id": "a34b3b837be7-0", "text": "langchain.utilities.jira.JiraAPIWrapper\u00b6\nclass langchain.utilities.jira.JiraAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for Jira API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam confluence: Any = None\u00b6\nparam jira_api_token: Optional[str] = None\u00b6\nparam jira_instance_url: Optional[str] = None\u00b6\nparam jira_username: Optional[str] = None\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.jira.JiraAPIWrapper.html"}
{"id": "a34b3b837be7-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nissue_create(query: str) \u2192 str[source]\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nother(query: str) \u2192 str[source]\u00b6\npage_create(query: str) \u2192 str[source]\u00b6\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_issues(issues: Dict) \u2192 List[dict][source]\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.jira.JiraAPIWrapper.html"}
{"id": "a34b3b837be7-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nparse_projects(projects: List[dict]) \u2192 List[dict][source]\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nproject() \u2192 str[source]\u00b6\nrun(mode: str, query: str) \u2192 str[source]\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nsearch(query: str) \u2192 str[source]\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using JiraAPIWrapper\u00b6\nJira", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.jira.JiraAPIWrapper.html"}
{"id": "d8c216c9cf77-0", "text": "langchain.utilities.apify.ApifyWrapper\u00b6\nclass langchain.utilities.apify.ApifyWrapper[source]\u00b6\nBases: BaseModel\nWrapper around Apify.\nTo use, you should have the apify-client python package installed,\nand the environment variable APIFY_API_TOKEN set with your API key, or pass\napify_api_token as a named parameter to the constructor.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam apify_client: Any = None\u00b6\nparam apify_client_async: Any = None\u00b6\nasync acall_actor(actor_id: str, run_input: Dict, dataset_mapping_function: Callable[[Dict], Document], *, build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None) \u2192 ApifyDatasetLoader[source]\u00b6\nRun an Actor on the Apify platform and wait for results to be ready.\n:param actor_id: The ID or name of the Actor on the Apify platform.\n:type actor_id: str\n:param run_input: The input object of the Actor that you\u2019re trying to run.\n:type run_input: Dict\n:param dataset_mapping_function: A function that takes a single\ndictionary (an Apify dataset item) and converts it to\nan instance of the Document class.\nParameters\nbuild (str, optional) \u2013 Optionally specifies the actor build to run.\nIt can be either a build tag or build number.\nmemory_mbytes (int, optional) \u2013 Optional memory limit for the run,\nin megabytes.\ntimeout_secs (int, optional) \u2013 Optional timeout for the run, in seconds.\nReturns\nA loader that will fetch the records from theActor run\u2019s default dataset.\nReturn type\nApifyDatasetLoader", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.apify.ApifyWrapper.html"}
{"id": "d8c216c9cf77-1", "text": "Return type\nApifyDatasetLoader\nasync acall_actor_task(task_id: str, task_input: Dict, dataset_mapping_function: Callable[[Dict], Document], *, build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None) \u2192 ApifyDatasetLoader[source]\u00b6\nRun a saved Actor task on Apify and wait for results to be ready.\n:param task_id: The ID or name of the task on the Apify platform.\n:type task_id: str\n:param task_input: The input object of the task that you\u2019re trying to run.\nOverrides the task\u2019s saved input.\nParameters\ndataset_mapping_function (Callable) \u2013 A function that takes a single\ndictionary (an Apify dataset item) and converts it to an\ninstance of the Document class.\nbuild (str, optional) \u2013 Optionally specifies the actor build to run.\nIt can be either a build tag or build number.\nmemory_mbytes (int, optional) \u2013 Optional memory limit for the run,\nin megabytes.\ntimeout_secs (int, optional) \u2013 Optional timeout for the run, in seconds.\nReturns\nA loader that will fetch the records from thetask run\u2019s default dataset.\nReturn type\nApifyDatasetLoader\ncall_actor(actor_id: str, run_input: Dict, dataset_mapping_function: Callable[[Dict], Document], *, build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None) \u2192 ApifyDatasetLoader[source]\u00b6\nRun an Actor on the Apify platform and wait for results to be ready.\n:param actor_id: The ID or name of the Actor on the Apify platform.\n:type actor_id: str\n:param run_input: The input object of the Actor that you\u2019re trying to run.\n:type run_input: Dict", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.apify.ApifyWrapper.html"}
{"id": "d8c216c9cf77-2", "text": ":type run_input: Dict\n:param dataset_mapping_function: A function that takes a single\ndictionary (an Apify dataset item) and converts it to an\ninstance of the Document class.\nParameters\nbuild (str, optional) \u2013 Optionally specifies the actor build to run.\nIt can be either a build tag or build number.\nmemory_mbytes (int, optional) \u2013 Optional memory limit for the run,\nin megabytes.\ntimeout_secs (int, optional) \u2013 Optional timeout for the run, in seconds.\nReturns\nA loader that will fetch the records from theActor run\u2019s default dataset.\nReturn type\nApifyDatasetLoader\ncall_actor_task(task_id: str, task_input: Dict, dataset_mapping_function: Callable[[Dict], Document], *, build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None) \u2192 ApifyDatasetLoader[source]\u00b6\nRun a saved Actor task on Apify and wait for results to be ready.\n:param task_id: The ID or name of the task on the Apify platform.\n:type task_id: str\n:param task_input: The input object of the task that you\u2019re trying to run.\nOverrides the task\u2019s saved input.\nParameters\ndataset_mapping_function (Callable) \u2013 A function that takes a single\ndictionary (an Apify dataset item) and converts it to an\ninstance of the Document class.\nbuild (str, optional) \u2013 Optionally specifies the actor build to run.\nIt can be either a build tag or build number.\nmemory_mbytes (int, optional) \u2013 Optional memory limit for the run,\nin megabytes.\ntimeout_secs (int, optional) \u2013 Optional timeout for the run, in seconds.\nReturns\nA loader that will fetch the records from thetask run\u2019s default dataset.\nReturn type\nApifyDatasetLoader", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.apify.ApifyWrapper.html"}
{"id": "d8c216c9cf77-3", "text": "Return type\nApifyDatasetLoader\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.apify.ApifyWrapper.html"}
{"id": "d8c216c9cf77-4", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using ApifyWrapper\u00b6\nApify", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.apify.ApifyWrapper.html"}
{"id": "84b49a245ab5-0", "text": "langchain.utilities.vertexai.init_vertexai\u00b6\nlangchain.utilities.vertexai.init_vertexai(project: Optional[str] = None, location: Optional[str] = None, credentials: Optional[Credentials] = None) \u2192 None[source]\u00b6\nInit vertexai.\nParameters\nproject \u2013 The default GCP project to use when making Vertex API calls.\nlocation \u2013 The default location to use when making API calls.\ncredentials \u2013 The default custom\ncredentials to use when making API calls. If not provided credentials\nwill be ascertained from the environment.\nRaises\nImportError \u2013 If importing vertexai SDK did not succeed.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.vertexai.init_vertexai.html"}
{"id": "9bdbc5d2bd69-0", "text": "langchain.utilities.clickup.Member\u00b6\nclass langchain.utilities.clickup.Member(id: int, username: str, email: str, initials: str)[source]\u00b6\nComponent class for a member.\nAttributes\nid\nusername\nemail\ninitials\nMethods\n__init__(id,\u00a0username,\u00a0email,\u00a0initials)\nfrom_data(data)\n__init__(id: int, username: str, email: str, initials: str) \u2192 None\u00b6\nclassmethod from_data(data: Dict) \u2192 Member[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.Member.html"}
{"id": "4e3b2afc24f8-0", "text": "langchain.utilities.zapier.ZapierNLAWrapper\u00b6\nclass langchain.utilities.zapier.ZapierNLAWrapper[source]\u00b6\nBases: BaseModel\nWrapper for Zapier NLA.\nFull docs here: https://nla.zapier.com/start/\nThis wrapper supports both API Key and OAuth Credential auth methods. API Key\nis the fastest way to get started using this wrapper.\nCall this wrapper with either zapier_nla_api_key or\nzapier_nla_oauth_access_token arguments, or set the ZAPIER_NLA_API_KEY\nenvironment variable. If both arguments are set, the Access Token will take\nprecedence.\nFor use-cases where LangChain + Zapier NLA is powering a user-facing application,\nand LangChain needs access to the end-user\u2019s connected accounts on Zapier.com,\nyou\u2019ll need to use OAuth. Review the full docs above to learn how to create\nyour own provider and generate credentials.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam zapier_nla_api_base: str = 'https://nla.zapier.com/api/v1/'\u00b6\nparam zapier_nla_api_key: str [Required]\u00b6\nparam zapier_nla_oauth_access_token: str [Required]\u00b6\nasync alist() \u2192 List[Dict][source]\u00b6\nReturns a list of all exposed (enabled) actions associated with\ncurrent user (associated with the set api_key). Change your exposed\nactions here: https://nla.zapier.com/demo/start/\nThe return list can be empty if no actions exposed. Else will contain\na list of action objects:\n[{\u201cid\u201d: str,\n\u201cdescription\u201d: str,\n\u201cparams\u201d: Dict[str, str]\n}]\nparams will always contain an instructions key, the only required", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.zapier.ZapierNLAWrapper.html"}
{"id": "4e3b2afc24f8-1", "text": "}]\nparams will always contain an instructions key, the only required\nparam. All others optional and if provided will override any AI guesses\n(see \u201cunderstanding the AI guessing flow\u201d here:\nhttps://nla.zapier.com/api/v1/docs)\nasync alist_as_str() \u2192 str[source]\u00b6\nSame as list, but returns a stringified version of the JSON for\ninsertting back into an LLM.\nasync apreview(action_id: str, instructions: str, params: Optional[Dict] = None) \u2192 Dict[source]\u00b6\nSame as run, but instead of actually executing the action, will\ninstead return a preview of params that have been guessed by the AI in\ncase you need to explicitly review before executing.\nasync apreview_as_str(*args, **kwargs) \u2192 str[source]\u00b6\nSame as preview, but returns a stringified version of the JSON for\ninsertting back into an LLM.\nasync arun(action_id: str, instructions: str, params: Optional[Dict] = None) \u2192 Dict[source]\u00b6\nExecutes an action that is identified by action_id, must be exposed\n(enabled) by the current user (associated with the set api_key). Change\nyour exposed actions here: https://nla.zapier.com/demo/start/\nThe return JSON is guaranteed to be less than ~500 words (350\ntokens) making it safe to inject into the prompt of another LLM\ncall.\nasync arun_as_str(*args, **kwargs) \u2192 str[source]\u00b6\nSame as run, but returns a stringified version of the JSON for\ninsertting back into an LLM.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.zapier.ZapierNLAWrapper.html"}
{"id": "4e3b2afc24f8-2", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.zapier.ZapierNLAWrapper.html"}
{"id": "4e3b2afc24f8-3", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlist() \u2192 List[Dict][source]\u00b6\nReturns a list of all exposed (enabled) actions associated with\ncurrent user (associated with the set api_key). Change your exposed\nactions here: https://nla.zapier.com/demo/start/\nThe return list can be empty if no actions exposed. Else will contain\na list of action objects:\n[{\u201cid\u201d: str,\n\u201cdescription\u201d: str,\n\u201cparams\u201d: Dict[str, str]\n}]\nparams will always contain an instructions key, the only required\nparam. All others optional and if provided will override any AI guesses\n(see \u201cunderstanding the AI guessing flow\u201d here:\nhttps://nla.zapier.com/docs/using-the-api#ai-guessing)\nlist_as_str() \u2192 str[source]\u00b6\nSame as list, but returns a stringified version of the JSON for\ninsertting back into an LLM.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.zapier.ZapierNLAWrapper.html"}
{"id": "4e3b2afc24f8-4", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npreview(action_id: str, instructions: str, params: Optional[Dict] = None) \u2192 Dict[source]\u00b6\nSame as run, but instead of actually executing the action, will\ninstead return a preview of params that have been guessed by the AI in\ncase you need to explicitly review before executing.\npreview_as_str(*args, **kwargs) \u2192 str[source]\u00b6\nSame as preview, but returns a stringified version of the JSON for\ninsertting back into an LLM.\nrun(action_id: str, instructions: str, params: Optional[Dict] = None) \u2192 Dict[source]\u00b6\nExecutes an action that is identified by action_id, must be exposed\n(enabled) by the current user (associated with the set api_key). Change\nyour exposed actions here: https://nla.zapier.com/demo/start/\nThe return JSON is guaranteed to be less than ~500 words (350\ntokens) making it safe to inject into the prompt of another LLM\ncall.\nrun_as_str(*args, **kwargs) \u2192 str[source]\u00b6\nSame as run, but returns a stringified version of the JSON for\ninsertting back into an LLM.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.zapier.ZapierNLAWrapper.html"}
{"id": "4e3b2afc24f8-5", "text": "Try to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using ZapierNLAWrapper\u00b6\nZapier Natural Language Actions", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.zapier.ZapierNLAWrapper.html"}
{"id": "e7ba515370d9-0", "text": "langchain.utilities.vertexai.raise_vertex_import_error\u00b6\nlangchain.utilities.vertexai.raise_vertex_import_error(minimum_expected_version: str = '1.35.0') \u2192 None[source]\u00b6\nRaise ImportError related to Vertex SDK being not available.\nParameters\nminimum_expected_version \u2013 The lowest expected version of the SDK.\nRaises\nImportError \u2013 an ImportError that mentions a required version of the SDK.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.vertexai.raise_vertex_import_error.html"}
{"id": "d72628a95b60-0", "text": "langchain.utilities.searx_search.SearxResults\u00b6\nclass langchain.utilities.searx_search.SearxResults(data: str)[source]\u00b6\nDict like wrapper around search api results.\nTake a raw result from Searx and make it into a dict like object.\nAttributes\nanswers\nHelper accessor on the json result.\nresults\nSilence mypy for accessing this field.\nMethods\n__init__(data)\nTake a raw result from Searx and make it into a dict like object.\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(data: str)[source]\u00b6\nTake a raw result from Searx and make it into a dict like object.\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.searx_search.SearxResults.html"}
{"id": "d72628a95b60-1", "text": "copy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.searx_search.SearxResults.html"}
{"id": "1f37c033c62f-0", "text": "langchain.utilities.github.GitHubAPIWrapper\u00b6\nclass langchain.utilities.github.GitHubAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for GitHub API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam github_app_id: Optional[str] = None\u00b6\nparam github_app_private_key: Optional[str] = None\u00b6\nparam github_base_branch: Optional[str] = None\u00b6\nparam github_branch: Optional[str] = None\u00b6\nparam github_repository: Optional[str] = None\u00b6\ncomment_on_issue(comment_query: str) \u2192 str[source]\u00b6\nAdds a comment to a github issue\nParameters:\ncomment_query(str): a string which contains the issue number,\ntwo newlines, and the comment.\nfor example: \u201c1\nWorking on it now\u201d\nadds the comment \u201cworking on it now\u201d to issue 1\nReturns:str: A success or failure message\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.github.GitHubAPIWrapper.html"}
{"id": "1f37c033c62f-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_file(file_query: str) \u2192 str[source]\u00b6\nCreates a new file on the Github repo\nParameters:\nfile_query(str): a string which contains the file path\nand the file contents. The file path is the first line\nin the string, and the contents are the rest of the string.\nFor example, \u201chello_world.md\n# Hello World!\u201d\nReturns:str: A success or failure message\ncreate_pull_request(pr_query: str) \u2192 str[source]\u00b6\nMakes a pull request from the bot\u2019s branch to the base branch\nParameters:\npr_query(str): a string which contains the PR title\nand the PR body. The title is the first line\nin the string, and the body are the rest of the string.\nFor example, \u201cUpdated README\nmade changes to add info\u201d\nReturns:str: A success or failure message\ndelete_file(file_path: str) \u2192 str[source]\u00b6\nDeletes a file from the repo\n:param file_path: Where the file is\n:type file_path: str\nReturns\nSuccess or failure message\nReturn type\nstr\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.github.GitHubAPIWrapper.html"}
{"id": "1f37c033c62f-2", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_issue(issue_number: int) \u2192 Dict[str, Any][source]\u00b6\nFetches a specific issue and its first 10 comments\n:param issue_number: The number for the github issue\n:type issue_number: int\nReturns\nA doctionary containing the issue\u2019s title,\nbody, and comments as a string\nReturn type\ndict\nget_issues() \u2192 str[source]\u00b6\nFetches all open issues from the repo\nReturns\nA plaintext report containing the number of issues\nand each issue\u2019s title and number.\nReturn type\nstr\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_issues(issues: List[Issue]) \u2192 List[dict][source]\u00b6\nExtracts title and number from each Issue and puts them in a dictionary\n:param issues: A list of Github Issue objects\n:type issues: List[Issue]\nReturns\nA dictionary of issue titles and numbers", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.github.GitHubAPIWrapper.html"}
{"id": "1f37c033c62f-3", "text": ":type issues: List[Issue]\nReturns\nA dictionary of issue titles and numbers\nReturn type\nList[dict]\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nread_file(file_path: str) \u2192 str[source]\u00b6\nReads a file from the github repo\n:param file_path: the file path\n:type file_path: str\nReturns\nThe file decoded as a string\nReturn type\nstr\nrun(mode: str, query: str) \u2192 str[source]\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nupdate_file(file_query: str) \u2192 str[source]\u00b6\nUpdates a file with new content.\n:param file_query: Contains the file path and the file contents.\nThe old file contents is wrapped in OLD <<<< and >>>> OLD\nThe new file contents is wrapped in NEW <<<< and >>>> NEW\nFor example:\n/test/hello.txt\nOLD <<<<\nHello Earth!\n>>>> OLD\nNEW <<<<\nHello Mars!\n>>>> NEW\nReturns\nA success or failure message\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using GitHubAPIWrapper\u00b6\nGithub", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.github.GitHubAPIWrapper.html"}
{"id": "2dc352e9ea14-0", "text": "langchain.utilities.gitlab.GitLabAPIWrapper\u00b6\nclass langchain.utilities.gitlab.GitLabAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for GitLab API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam gitlab_base_branch: Optional[str] = None\u00b6\nThe base branch in the GitLab repository, used for comparisons.\nUsually \u2018main\u2019 or \u2018master\u2019. Defaults to \u2018main\u2019.\nparam gitlab_branch: Optional[str] = None\u00b6\nThe specific branch in the GitLab repository where the bot will make\nits commits. Defaults to \u2018main\u2019.\nparam gitlab_personal_access_token: Optional[str] = None\u00b6\nPersonal access token for the GitLab service, used for authentication.\nparam gitlab_repository: Optional[str] = None\u00b6\nThe name of the GitLab repository, in the form {username}/{repo-name}.\ncomment_on_issue(comment_query: str) \u2192 str[source]\u00b6\nAdds a comment to a gitlab issue\nParameters:\ncomment_query(str): a string which contains the issue number,\ntwo newlines, and the comment.\nfor example: \u201c1\nWorking on it now\u201d\nadds the comment \u201cworking on it now\u201d to issue 1\nReturns:str: A success or failure message\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.gitlab.GitLabAPIWrapper.html"}
{"id": "2dc352e9ea14-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_file(file_query: str) \u2192 str[source]\u00b6\nCreates a new file on the gitlab repo\nParameters:\nfile_query(str): a string which contains the file path\nand the file contents. The file path is the first line\nin the string, and the contents are the rest of the string.\nFor example, \u201chello_world.md\n# Hello World!\u201d\nReturns:str: A success or failure message\ncreate_pull_request(pr_query: str) \u2192 str[source]\u00b6\nMakes a pull request from the bot\u2019s branch to the base branch\nParameters:\npr_query(str): a string which contains the PR title\nand the PR body. The title is the first line\nin the string, and the body are the rest of the string.\nFor example, \u201cUpdated README\nmade changes to add info\u201d\nReturns:str: A success or failure message\ndelete_file(file_path: str) \u2192 str[source]\u00b6\nDeletes a file from the repo\n:param file_path: Where the file is\n:type file_path: str\nReturns\nSuccess or failure message", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.gitlab.GitLabAPIWrapper.html"}
{"id": "2dc352e9ea14-2", "text": ":type file_path: str\nReturns\nSuccess or failure message\nReturn type\nstr\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_issue(issue_number: int) \u2192 Dict[str, Any][source]\u00b6\nFetches a specific issue and its first 10 comments\n:param issue_number: The number for the gitlab issue\n:type issue_number: int\nReturns\nA dictionary containing the issue\u2019s title,\nbody, and comments as a string\nReturn type\ndict\nget_issues() \u2192 str[source]\u00b6\nFetches all open issues from the repo\nReturns\nA plaintext report containing the number of issues\nand each issue\u2019s title and number.\nReturn type\nstr\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.gitlab.GitLabAPIWrapper.html"}
{"id": "2dc352e9ea14-3", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_issues(issues: List[Issue]) \u2192 List[dict][source]\u00b6\nExtracts title and number from each Issue and puts them in a dictionary\n:param issues: A list of gitlab Issue objects\n:type issues: List[Issue]\nReturns\nA dictionary of issue titles and numbers\nReturn type\nList[dict]\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nread_file(file_path: str) \u2192 str[source]\u00b6\nReads a file from the gitlab repo\n:param file_path: the file path\n:type file_path: str\nReturns\nThe file decoded as a string\nReturn type\nstr\nrun(mode: str, query: str) \u2192 str[source]\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nupdate_file(file_query: str) \u2192 str[source]\u00b6\nUpdates a file with new content.\n:param file_query: Contains the file path and the file contents.\nThe old file contents is wrapped in OLD <<<< and >>>> OLD\nThe new file contents is wrapped in NEW <<<< and >>>> NEW\nFor example:\ntest/hello.txt\nOLD <<<<\nHello Earth!\n>>>> OLD\nNEW <<<<\nHello Mars!\n>>>> NEW\nReturns\nA success or failure message", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.gitlab.GitLabAPIWrapper.html"}
{"id": "2dc352e9ea14-4", "text": "NEW <<<<\nHello Mars!\n>>>> NEW\nReturns\nA success or failure message\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using GitLabAPIWrapper\u00b6\nGitlab", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.gitlab.GitLabAPIWrapper.html"}
{"id": "564809938d74-0", "text": "langchain.utilities.pubmed.PubMedAPIWrapper\u00b6\nclass langchain.utilities.pubmed.PubMedAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper around PubMed API.\nThis wrapper will use the PubMed API to conduct searches and fetch\ndocument summaries. By default, it will return the document summaries\nof the top-k results of an input search.\nParameters\ntop_k_results \u2013 number of the top-scored document used for the PubMed tool\nMAX_QUERY_LENGTH \u2013 maximum length of the query.\nDefault is 300 characters.\ndoc_content_chars_max \u2013 maximum length of the document content.\nContent will be truncated if it exceeds this length.\nDefault is 2000 characters.\nmax_retry \u2013 maximum number of retries for a request. Default is 5.\nsleep_time \u2013 time to wait between retries.\nDefault is 0.2 seconds.\nemail \u2013 email address to be used for the PubMed API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam MAX_QUERY_LENGTH: int = 300\u00b6\nparam base_url_efetch: str = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?'\u00b6\nparam base_url_esearch: str = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?'\u00b6\nparam doc_content_chars_max: int = 2000\u00b6\nparam email: str = 'your_email@example.com'\u00b6\nparam max_retry: int = 5\u00b6\nparam sleep_time: float = 0.2\u00b6\nparam top_k_results: int = 3\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.pubmed.PubMedAPIWrapper.html"}
{"id": "564809938d74-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.pubmed.PubMedAPIWrapper.html"}
{"id": "564809938d74-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load(query: str) \u2192 Iterator[dict][source]\u00b6\nSearch PubMed for documents matching the query.\nReturn an iterator of dictionaries containing the document metadata.\nlazy_load_docs(query: str) \u2192 Iterator[Document][source]\u00b6\nload(query: str) \u2192 List[dict][source]\u00b6\nSearch PubMed for documents matching the query.\nReturn a list of dictionaries containing the document metadata.\nload_docs(query: str) \u2192 List[Document][source]\u00b6\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nretrieve_article(uid: str, webenv: str) \u2192 dict[source]\u00b6\nrun(query: str) \u2192 str[source]\u00b6\nRun PubMed search and get the article meta information.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.pubmed.PubMedAPIWrapper.html"}
{"id": "564809938d74-3", "text": "Run PubMed search and get the article meta information.\nSee https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch\nIt uses only the most informative fields of article meta information.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.pubmed.PubMedAPIWrapper.html"}
{"id": "aa851b9aa29e-0", "text": "langchain.utilities.redis.get_client\u00b6\nlangchain.utilities.redis.get_client(redis_url: str, **kwargs: Any) \u2192 RedisType[source]\u00b6\nGet a redis client from the connection url given. This helper accepts\nurls for Redis server (TCP with/without TLS or UnixSocket) as well as\nRedis Sentinel connections.\nRedis Cluster is not supported.\nBefore creating a connection the existence of the database driver is checked\nan and ValueError raised otherwise\nTo use, you should have the redis python package installed.\nExample\nfrom langchain.utilities.redis import get_client\nredis_client = get_client(\n    redis_url=\"redis://username:password@localhost:6379\"\n    index_name=\"my-index\",\n    embedding_function=embeddings.embed_query,\n)\nTo use a redis replication setup with multiple redis server and redis sentinels\nset \u201credis_url\u201d to \u201credis+sentinel://\u201d scheme. With this url format a path is\nneeded holding the name of the redis service within the sentinels to get the\ncorrect redis server connection. The default service name is \u201cmymaster\u201d. The\noptional second part of the path is the redis db number to connect to.\nAn optional username or password is used for booth connections to the rediserver\nand the sentinel, different passwords for server and sentinel are not supported.\nAnd as another constraint only one sentinel instance can be given:\nExample\nfrom langchain.utilities.redis import get_client\nredis_client = get_client(\n    redis_url=\"redis+sentinel://username:password@sentinelhost:26379/mymaster/0\"\n    index_name=\"my-index\",\n    embedding_function=embeddings.embed_query,\n)", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.redis.get_client.html"}
{"id": "4b6a72bc5f1c-0", "text": "langchain.utilities.clickup.extract_dict_elements_from_component_fields\u00b6\nlangchain.utilities.clickup.extract_dict_elements_from_component_fields(data: dict, component: Type[Component]) \u2192 dict[source]\u00b6\nExtract elements from a dictionary.\nParameters\ndata \u2013 The dictionary to extract elements from.\ncomponent \u2013 The component to extract elements from.\nReturns\nA dictionary containing the elements from the input dictionary that are also\nin the component.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.extract_dict_elements_from_component_fields.html"}
{"id": "642e6c6936c9-0", "text": "langchain.utilities.arcee.ArceeWrapper\u00b6\nclass langchain.utilities.arcee.ArceeWrapper(arcee_api_key: str, arcee_api_url: str, arcee_api_version: str, model_kwargs: Optional[Dict[str, Any]], model_name: str)[source]\u00b6\nWrapper for Arcee API.\nInitialize ArceeWrapper.\nParameters\narcee_api_key \u2013 API key for Arcee API.\narcee_api_url \u2013 URL for Arcee API.\narcee_api_version \u2013 Version of Arcee API.\nmodel_kwargs \u2013 Keyword arguments for Arcee API.\nmodel_name \u2013 Name of an Arcee model.\nMethods\n__init__(arcee_api_key,\u00a0arcee_api_url,\u00a0...)\nInitialize ArceeWrapper.\ngenerate(prompt,\u00a0**kwargs)\nGenerate text from Arcee DALM.\nretrieve(query,\u00a0**kwargs)\nRetrieve {size} contexts with your retriever for a given query\nvalidate_model_training_status()\n__init__(arcee_api_key: str, arcee_api_url: str, arcee_api_version: str, model_kwargs: Optional[Dict[str, Any]], model_name: str)[source]\u00b6\nInitialize ArceeWrapper.\nParameters\narcee_api_key \u2013 API key for Arcee API.\narcee_api_url \u2013 URL for Arcee API.\narcee_api_version \u2013 Version of Arcee API.\nmodel_kwargs \u2013 Keyword arguments for Arcee API.\nmodel_name \u2013 Name of an Arcee model.\ngenerate(prompt: str, **kwargs: Any) \u2192 str[source]\u00b6\nGenerate text from Arcee DALM.\nParameters\nprompt \u2013 Prompt to generate text from.\nsize \u2013 The max number of context results to retrieve. Defaults to 3.\n(Can be less if filters are provided).\nfilters \u2013 Filters to apply to the context dataset.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.ArceeWrapper.html"}
{"id": "642e6c6936c9-1", "text": "filters \u2013 Filters to apply to the context dataset.\nretrieve(query: str, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRetrieve {size} contexts with your retriever for a given query\nParameters\nquery \u2013 Query to submit to the model\nsize \u2013 The max number of context results to retrieve. Defaults to 3.\n(Can be less if filters are provided).\nfilters \u2013 Filters to apply to the context dataset.\nvalidate_model_training_status() \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.ArceeWrapper.html"}
{"id": "d306b5f6dad5-0", "text": "langchain.utilities.arcee.ArceeDocument\u00b6\nclass langchain.utilities.arcee.ArceeDocument[source]\u00b6\nBases: BaseModel\nArcee document.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam id: str [Required]\u00b6\nparam index: str [Required]\u00b6\nparam score: float [Required]\u00b6\nparam source: langchain.utilities.arcee.ArceeDocumentSource [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.ArceeDocument.html"}
{"id": "d306b5f6dad5-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.ArceeDocument.html"}
{"id": "d306b5f6dad5-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.ArceeDocument.html"}
{"id": "9060ed13ccd3-0", "text": "langchain.utilities.graphql.GraphQLAPIWrapper\u00b6\nclass langchain.utilities.graphql.GraphQLAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper around GraphQL API.\nTo use, you should have the gql python package installed.\nThis wrapper will use the GraphQL API to conduct queries.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam custom_headers: Optional[Dict[str, str]] = None\u00b6\nparam graphql_endpoint: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.graphql.GraphQLAPIWrapper.html"}
{"id": "9060ed13ccd3-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(query: str) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.graphql.GraphQLAPIWrapper.html"}
{"id": "9060ed13ccd3-2", "text": "run(query: str) \u2192 str[source]\u00b6\nRun a GraphQL query and get the results.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using GraphQLAPIWrapper\u00b6\nGraphQL", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.graphql.GraphQLAPIWrapper.html"}
{"id": "362f095afe57-0", "text": "langchain.utilities.arcee.ArceeRoute\u00b6\nclass langchain.utilities.arcee.ArceeRoute(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nRoutes available for the Arcee API as enumerator.\ngenerate = 'models/generate'\u00b6\nretrieve = 'models/retrieve'\u00b6\nmodel_training_status = 'models/status/{id_or_name}'\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.ArceeRoute.html"}
{"id": "a25de96e4ea9-0", "text": "langchain_experimental.utilities.python.PythonREPL\u00b6\nclass langchain_experimental.utilities.python.PythonREPL[source]\u00b6\nBases: BaseModel\nSimulates a standalone Python REPL.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam globals: Optional[Dict] [Optional] (alias '_globals')\u00b6\nparam locals: Optional[Dict] [Optional] (alias '_locals')\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain_experimental.utilities.python.PythonREPL.html"}
{"id": "a25de96e4ea9-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(command: str, timeout: Optional[int] = None) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain_experimental.utilities.python.PythonREPL.html"}
{"id": "a25de96e4ea9-2", "text": "run(command: str, timeout: Optional[int] = None) \u2192 str[source]\u00b6\nRun command with own globals/locals and returns anything printed.\nTimeout after the specified number of seconds.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclassmethod worker(command: str, globals: Optional[Dict], locals: Optional[Dict], queue: Queue) \u2192 None[source]\u00b6\nExamples using PythonREPL\u00b6\nDynamodb Chat Message History\nPython\nCode writing", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain_experimental.utilities.python.PythonREPL.html"}
{"id": "0540c8df4d9c-0", "text": "langchain.utilities.requests.Requests\u00b6\nclass langchain.utilities.requests.Requests[source]\u00b6\nBases: BaseModel\nWrapper around requests to handle auth and async.\nThe main purpose of this wrapper is to handle authentication (by saving\nheaders) and enable easy async methods on the same base object.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aiosession: Optional[aiohttp.client.ClientSession] = None\u00b6\nparam auth: Optional[Any] = None\u00b6\nparam headers: Optional[Dict[str, str]] = None\u00b6\nadelete(url: str, **kwargs: Any) \u2192 AsyncGenerator[ClientResponse, None][source]\u00b6\nDELETE the URL and return the text asynchronously.\naget(url: str, **kwargs: Any) \u2192 AsyncGenerator[ClientResponse, None][source]\u00b6\nGET the URL and return the text asynchronously.\napatch(url: str, data: Dict[str, Any], **kwargs: Any) \u2192 AsyncGenerator[ClientResponse, None][source]\u00b6\nPATCH the URL and return the text asynchronously.\napost(url: str, data: Dict[str, Any], **kwargs: Any) \u2192 AsyncGenerator[ClientResponse, None][source]\u00b6\nPOST to the URL and return the text asynchronously.\naput(url: str, data: Dict[str, Any], **kwargs: Any) \u2192 AsyncGenerator[ClientResponse, None][source]\u00b6\nPUT the URL and return the text asynchronously.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.requests.Requests.html"}
{"id": "0540c8df4d9c-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndelete(url: str, **kwargs: Any) \u2192 Response[source]\u00b6\nDELETE the URL and return the text.\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget(url: str, **kwargs: Any) \u2192 Response[source]\u00b6\nGET the URL and return the text.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.requests.Requests.html"}
{"id": "0540c8df4d9c-2", "text": "GET the URL and return the text.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npatch(url: str, data: Dict[str, Any], **kwargs: Any) \u2192 Response[source]\u00b6\nPATCH the URL and return the text.\npost(url: str, data: Dict[str, Any], **kwargs: Any) \u2192 Response[source]\u00b6\nPOST to the URL and return the text.\nput(url: str, data: Dict[str, Any], **kwargs: Any) \u2192 Response[source]\u00b6\nPUT the URL and return the text.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.requests.Requests.html"}
{"id": "0540c8df4d9c-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using Requests\u00b6\nNatural Language APIs", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.requests.Requests.html"}
{"id": "82ff844c6ed8-0", "text": "langchain.utilities.requests.TextRequestsWrapper\u00b6\nclass langchain.utilities.requests.TextRequestsWrapper[source]\u00b6\nBases: BaseModel\nLightweight wrapper around requests library.\nThe main purpose of this wrapper is to always return a text output.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aiosession: Optional[aiohttp.client.ClientSession] = None\u00b6\nparam auth: Optional[Any] = None\u00b6\nparam headers: Optional[Dict[str, str]] = None\u00b6\nasync adelete(url: str, **kwargs: Any) \u2192 str[source]\u00b6\nDELETE the URL and return the text asynchronously.\nasync aget(url: str, **kwargs: Any) \u2192 str[source]\u00b6\nGET the URL and return the text asynchronously.\nasync apatch(url: str, data: Dict[str, Any], **kwargs: Any) \u2192 str[source]\u00b6\nPATCH the URL and return the text asynchronously.\nasync apost(url: str, data: Dict[str, Any], **kwargs: Any) \u2192 str[source]\u00b6\nPOST to the URL and return the text asynchronously.\nasync aput(url: str, data: Dict[str, Any], **kwargs: Any) \u2192 str[source]\u00b6\nPUT the URL and return the text asynchronously.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.requests.TextRequestsWrapper.html"}
{"id": "82ff844c6ed8-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndelete(url: str, **kwargs: Any) \u2192 str[source]\u00b6\nDELETE the URL and return the text.\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget(url: str, **kwargs: Any) \u2192 str[source]\u00b6\nGET the URL and return the text.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.requests.TextRequestsWrapper.html"}
{"id": "82ff844c6ed8-2", "text": "GET the URL and return the text.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npatch(url: str, data: Dict[str, Any], **kwargs: Any) \u2192 str[source]\u00b6\nPATCH the URL and return the text.\npost(url: str, data: Dict[str, Any], **kwargs: Any) \u2192 str[source]\u00b6\nPOST to the URL and return the text.\nput(url: str, data: Dict[str, Any], **kwargs: Any) \u2192 str[source]\u00b6\nPUT the URL and return the text.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.requests.TextRequestsWrapper.html"}
{"id": "82ff844c6ed8-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty requests: langchain.utilities.requests.Requests\u00b6\nExamples using TextRequestsWrapper\u00b6\nRequests\nJSON\nOpenAPI\nTool Input Schema", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.requests.TextRequestsWrapper.html"}
{"id": "0a36fec64932-0", "text": "langchain.utilities.arcee.ArceeDocumentAdapter\u00b6\nclass langchain.utilities.arcee.ArceeDocumentAdapter[source]\u00b6\nAdapter for Arcee documents\nMethods\n__init__()\nadapt(arcee_document)\nAdapts an ArceeDocument to a langchain's Document object.\n__init__()\u00b6\nclassmethod adapt(arcee_document: ArceeDocument) \u2192 Document[source]\u00b6\nAdapts an ArceeDocument to a langchain\u2019s Document object.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.arcee.ArceeDocumentAdapter.html"}
{"id": "6ddac03f1f4a-0", "text": "langchain.utilities.searx_search.SearxSearchWrapper\u00b6\nclass langchain.utilities.searx_search.SearxSearchWrapper[source]\u00b6\nBases: BaseModel\nWrapper for Searx API.\nTo use you need to provide the searx host by passing the named parameter\nsearx_host or exporting the environment variable SEARX_HOST.\nIn some situations you might want to disable SSL verification, for example\nif you are running searx locally. You can do this by passing the named parameter\nunsecure. You can also pass the host url scheme as http to disable SSL.\nExample\nfrom langchain.utilities import SearxSearchWrapper\nsearx = SearxSearchWrapper(searx_host=\"http://localhost:8888\")\nExample with SSL disabled:from langchain.utilities import SearxSearchWrapper\n# note the unsecure parameter is not needed if you pass the url scheme as\n# http\nsearx = SearxSearchWrapper(searx_host=\"http://localhost:8888\",\n                                        unsecure=True)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aiosession: Optional[Any] = None\u00b6\nparam categories: Optional[List[str]] = []\u00b6\nparam engines: Optional[List[str]] = []\u00b6\nparam headers: Optional[dict] = None\u00b6\nparam k: int = 10\u00b6\nparam params: dict [Optional]\u00b6\nparam query_suffix: Optional[str] = ''\u00b6\nparam searx_host: str = ''\u00b6\nparam unsecure: bool = False\u00b6\nasync aresults(query: str, num_results: int, engines: Optional[List[str]] = None, query_suffix: Optional[str] = '', **kwargs: Any) \u2192 List[Dict][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.searx_search.SearxSearchWrapper.html"}
{"id": "6ddac03f1f4a-1", "text": "Asynchronously query with json results.\nUses aiohttp. See results for more info.\nasync arun(query: str, engines: Optional[List[str]] = None, query_suffix: Optional[str] = '', **kwargs: Any) \u2192 str[source]\u00b6\nAsynchronously version of run.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.searx_search.SearxSearchWrapper.html"}
{"id": "6ddac03f1f4a-2", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nresults(query: str, num_results: int, engines: Optional[List[str]] = None, categories: Optional[List[str]] = None, query_suffix: Optional[str] = '', **kwargs: Any) \u2192 List[Dict][source]\u00b6\nRun query through Searx API and returns the results with metadata.\nParameters\nquery \u2013 The query to search for.\nquery_suffix \u2013 Extra suffix appended to the query.\nnum_results \u2013 Limit the number of results to return.\nengines \u2013 List of engines to use for the query.\ncategories \u2013 List of categories to use for the query.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.searx_search.SearxSearchWrapper.html"}
{"id": "6ddac03f1f4a-3", "text": "categories \u2013 List of categories to use for the query.\n**kwargs \u2013 extra parameters to pass to the searx API.\nReturns\n{snippet:  The description of the result.\ntitle:  The title of the result.\nlink: The link to the result.\nengines: The engines used for the result.\ncategory: Searx category of the result.\n}\nReturn type\nDict with the following keys\nrun(query: str, engines: Optional[List[str]] = None, categories: Optional[List[str]] = None, query_suffix: Optional[str] = '', **kwargs: Any) \u2192 str[source]\u00b6\nRun query through Searx API and parse results.\nYou can pass any other params to the searx query API.\nParameters\nquery \u2013 The query to search for.\nquery_suffix \u2013 Extra suffix appended to the query.\nengines \u2013 List of engines to use for the query.\ncategories \u2013 List of categories to use for the query.\n**kwargs \u2013 extra parameters to pass to the searx API.\nReturns\nThe result of the query.\nReturn type\nstr\nRaises\nValueError \u2013 If an error occurred with the query.\nExample\nThis will make a query to the qwant engine:\nfrom langchain.utilities import SearxSearchWrapper\nsearx = SearxSearchWrapper(searx_host=\"http://my.searx.host\")\nsearx.run(\"what is the weather in France ?\", engine=\"qwant\")\n# the same result can be achieved using the `!` syntax of searx\n# to select the engine using `query_suffix`\nsearx.run(\"what is the weather in France ?\", query_suffix=\"!qwant\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.searx_search.SearxSearchWrapper.html"}
{"id": "6ddac03f1f4a-4", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using SearxSearchWrapper\u00b6\nSearxNG Search\nSearxNG Search API", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.searx_search.SearxSearchWrapper.html"}
{"id": "e0d8a7433728-0", "text": "langchain.utilities.powerbi.fix_table_name\u00b6\nlangchain.utilities.powerbi.fix_table_name(table: str) \u2192 str[source]\u00b6\nAdd single quotes around table names that contain spaces.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.powerbi.fix_table_name.html"}
{"id": "50938d4643cc-0", "text": "langchain.utilities.clickup.fetch_list_id\u00b6\nlangchain.utilities.clickup.fetch_list_id(space_id: int, folder_id: int, access_token: str) \u2192 Optional[int][source]\u00b6\nFetch the list id.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.fetch_list_id.html"}
{"id": "c96e96c956f0-0", "text": "langchain.utilities.bing_search.BingSearchAPIWrapper\u00b6\nclass langchain.utilities.bing_search.BingSearchAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for Bing Search API.\nIn order to set this up, follow instructions at:\nhttps://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bing_search_url: str [Required]\u00b6\nparam bing_subscription_key: str [Required]\u00b6\nparam k: int = 10\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.bing_search.BingSearchAPIWrapper.html"}
{"id": "c96e96c956f0-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nresults(query: str, num_results: int) \u2192 List[Dict][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.bing_search.BingSearchAPIWrapper.html"}
{"id": "c96e96c956f0-2", "text": "results(query: str, num_results: int) \u2192 List[Dict][source]\u00b6\nRun query through BingSearch and return metadata.\nParameters\nquery \u2013 The query to search for.\nnum_results \u2013 The number of results to return.\nReturns\nsnippet - The description of the result.\ntitle - The title of the result.\nlink - The link to the result.\nReturn type\nA list of dictionaries with the following keys\nrun(query: str) \u2192 str[source]\u00b6\nRun query through BingSearch and parse result.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using BingSearchAPIWrapper\u00b6\nBing Search", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.bing_search.BingSearchAPIWrapper.html"}
{"id": "a5ccc169a123-0", "text": "langchain.utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper\u00b6\nclass langchain.utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for DuckDuckGo Search API.\nFree and does not require any setup.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam max_results: int = 5\u00b6\nparam region: Optional[str] = 'wt-wt'\u00b6\nparam safesearch: str = 'moderate'\u00b6\nparam time: Optional[str] = 'y'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper.html"}
{"id": "a5ccc169a123-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_snippets(query: str) \u2192 List[str][source]\u00b6\nRun query through DuckDuckGo and return concatenated results.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper.html"}
{"id": "a5ccc169a123-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nresults(query: str, num_results: int, backend: str = 'api') \u2192 List[Dict[str, str]][source]\u00b6\nRun query through DuckDuckGo and return metadata.\nParameters\nquery \u2013 The query to search for.\nnum_results \u2013 The number of results to return.\nReturns\nsnippet - The description of the result.\ntitle - The title of the result.\nlink - The link to the result.\nReturn type\nA list of dictionaries with the following keys\nrun(query: str) \u2192 str[source]\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using DuckDuckGoSearchAPIWrapper\u00b6\nDuckDuckGo Search", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper.html"}
{"id": "87af5191b174-0", "text": "langchain.utilities.clickup.CUList\u00b6\nclass langchain.utilities.clickup.CUList(folder_id: float, name: str, content: Optional[str] = None, due_date: Optional[int] = None, due_date_time: Optional[bool] = None, priority: Optional[int] = None, assignee: Optional[int] = None, status: Optional[str] = None)[source]\u00b6\nComponent class for a list.\nAttributes\nassignee\ncontent\ndue_date\ndue_date_time\npriority\nstatus\nfolder_id\nname\nMethods\n__init__(folder_id,\u00a0name[,\u00a0content,\u00a0...])\nfrom_data(data)\n__init__(folder_id: float, name: str, content: Optional[str] = None, due_date: Optional[int] = None, due_date_time: Optional[bool] = None, priority: Optional[int] = None, assignee: Optional[int] = None, status: Optional[str] = None) \u2192 None\u00b6\nclassmethod from_data(data: dict) \u2192 CUList[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.CUList.html"}
{"id": "2faf1199b577-0", "text": "langchain.utilities.bibtex.BibtexparserWrapper\u00b6\nclass langchain.utilities.bibtex.BibtexparserWrapper[source]\u00b6\nBases: BaseModel\nWrapper around bibtexparser.\nTo use, you should have the bibtexparser python package installed.\nhttps://bibtexparser.readthedocs.io/en/master/\nThis wrapper will use bibtexparser to load a collection of references from\na bibtex file and fetch document summaries.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.bibtex.BibtexparserWrapper.html"}
{"id": "2faf1199b577-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_metadata(entry: Mapping[str, Any], load_extra: bool = False) \u2192 Dict[str, Any][source]\u00b6\nGet metadata for the given entry.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nload_bibtex_entries(path: str) \u2192 List[Dict[str, Any]][source]\u00b6\nLoad bibtex entries from the bibtex file at the given path.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.bibtex.BibtexparserWrapper.html"}
{"id": "2faf1199b577-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.bibtex.BibtexparserWrapper.html"}
{"id": "d2b828562d91-0", "text": "langchain.utilities.max_compute.MaxComputeAPIWrapper\u00b6\nclass langchain.utilities.max_compute.MaxComputeAPIWrapper(client: ODPS)[source]\u00b6\nInterface for querying Alibaba Cloud MaxCompute tables.\nInitialize MaxCompute document loader.\nParameters\nclient \u2013 odps.ODPS MaxCompute client object.\nMethods\n__init__(client)\nInitialize MaxCompute document loader.\nfrom_params(endpoint,\u00a0project,\u00a0*[,\u00a0...])\nConvenience constructor that builds the odsp.ODPS MaxCompute client from\nlazy_query(query)\nquery(query)\n__init__(client: ODPS)[source]\u00b6\nInitialize MaxCompute document loader.\nParameters\nclient \u2013 odps.ODPS MaxCompute client object.\nclassmethod from_params(endpoint: str, project: str, *, access_id: Optional[str] = None, secret_access_key: Optional[str] = None) \u2192 MaxComputeAPIWrapper[source]\u00b6\nConvenience constructor that builds the odsp.ODPS MaxCompute client fromgiven parameters.\nParameters\nendpoint \u2013 MaxCompute endpoint.\nproject \u2013 A project is a basic organizational unit of MaxCompute, which is\nsimilar to a database.\naccess_id \u2013 MaxCompute access ID. Should be passed in directly or set as the\nenvironment variable MAX_COMPUTE_ACCESS_ID.\nsecret_access_key \u2013 MaxCompute secret access key. Should be passed in\ndirectly or set as the environment variable\nMAX_COMPUTE_SECRET_ACCESS_KEY.\nlazy_query(query: str) \u2192 Iterator[dict][source]\u00b6\nquery(query: str) \u2192 List[dict][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.max_compute.MaxComputeAPIWrapper.html"}
{"id": "b6f3bb8f5cec-0", "text": "langchain.utilities.openweathermap.OpenWeatherMapAPIWrapper\u00b6\nclass langchain.utilities.openweathermap.OpenWeatherMapAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for OpenWeatherMap API using PyOWM.\nDocs for using:\nGo to OpenWeatherMap and sign up for an API key\nSave your API KEY into OPENWEATHERMAP_API_KEY env variable\npip install pyowm\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam openweathermap_api_key: Optional[str] = None\u00b6\nparam owm: Any = None\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.openweathermap.OpenWeatherMapAPIWrapper.html"}
{"id": "b6f3bb8f5cec-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(location: str) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.openweathermap.OpenWeatherMapAPIWrapper.html"}
{"id": "b6f3bb8f5cec-2", "text": "run(location: str) \u2192 str[source]\u00b6\nGet the current weather information for a specified location.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using OpenWeatherMapAPIWrapper\u00b6\nOpenWeatherMap", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.openweathermap.OpenWeatherMapAPIWrapper.html"}
{"id": "ac6f64fe2eb6-0", "text": "langchain.utilities.searchapi.SearchApiAPIWrapper\u00b6\nclass langchain.utilities.searchapi.SearchApiAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper around SearchApi API.\nTo use, you should have the environment variable SEARCHAPI_API_KEY\nset with your API key, or pass searchapi_api_key\nas a named parameter to the constructor.\nExample\nfrom langchain.utilities import SearchApiAPIWrapper\nsearchapi = SearchApiAPIWrapper()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aiosession: Optional[aiohttp.client.ClientSession] = None\u00b6\nparam engine: str = 'google'\u00b6\nparam searchapi_api_key: Optional[str] = None\u00b6\nasync aresults(query: str, **kwargs: Any) \u2192 dict[source]\u00b6\nasync arun(query: str, **kwargs: Any) \u2192 str[source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.searchapi.SearchApiAPIWrapper.html"}
{"id": "ac6f64fe2eb6-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.searchapi.SearchApiAPIWrapper.html"}
{"id": "ac6f64fe2eb6-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nresults(query: str, **kwargs: Any) \u2192 dict[source]\u00b6\nrun(query: str, **kwargs: Any) \u2192 str[source]\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.searchapi.SearchApiAPIWrapper.html"}
{"id": "d8b8fdd14a31-0", "text": "langchain.utilities.tavily_search.TavilySearchAPIWrapper\u00b6\nclass langchain.utilities.tavily_search.TavilySearchAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for Tavily Search API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam tavily_api_key: str [Required]\u00b6\nclean_results(results: List[Dict]) \u2192 List[Dict][source]\u00b6\nClean results from Tavily Search API.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.tavily_search.TavilySearchAPIWrapper.html"}
{"id": "d8b8fdd14a31-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.tavily_search.TavilySearchAPIWrapper.html"}
{"id": "d8b8fdd14a31-2", "text": "raw_results(query: str, max_results: Optional[int] = 5, search_depth: Optional[str] = 'advanced', include_domains: Optional[List[str]] = [], exclude_domains: Optional[List[str]] = [], include_answer: Optional[bool] = False, include_raw_content: Optional[bool] = False, include_images: Optional[bool] = False) \u2192 Dict[source]\u00b6\nasync raw_results_async(query: str, max_results: Optional[int] = 5, search_depth: Optional[str] = 'advanced', include_domains: Optional[List[str]] = [], exclude_domains: Optional[List[str]] = [], include_answer: Optional[bool] = False, include_raw_content: Optional[bool] = False, include_images: Optional[bool] = False) \u2192 Dict[source]\u00b6\nGet results from the Tavily Search API asynchronously.\nresults(query: str, max_results: Optional[int] = 5, search_depth: Optional[str] = 'advanced', include_domains: Optional[List[str]] = [], exclude_domains: Optional[List[str]] = [], include_answer: Optional[bool] = False, include_raw_content: Optional[bool] = False, include_images: Optional[bool] = False) \u2192 List[Dict][source]\u00b6\nRun query through Tavily Search and return metadata.\nParameters\nquery \u2013 The query to search for.\nmax_results \u2013 The maximum number of results to return.\nsearch_depth \u2013 The depth of the search. Can be \u201cbasic\u201d or \u201cadvanced\u201d.\ninclude_domains \u2013 A list of domains to include in the search.\nexclude_domains \u2013 A list of domains to exclude from the search.\ninclude_answer \u2013 Whether to include the answer in the results.\ninclude_raw_content \u2013 Whether to include the raw content in the results.\ninclude_images \u2013 Whether to include images in the results.\nReturns\nThe query that was searched for.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.tavily_search.TavilySearchAPIWrapper.html"}
{"id": "d8b8fdd14a31-3", "text": "Returns\nThe query that was searched for.\nfollow_up_questions: A list of follow up questions.\nresponse_time: The response time of the query.\nanswer: The answer to the query.\nimages: A list of images.\nresults: A list of dictionaries containing the results:\ntitle: The title of the result.\nurl: The url of the result.\ncontent: The content of the result.\nscore: The score of the result.\nraw_content: The raw content of the result.\nReturn type\nquery\nasync results_async(query: str, max_results: Optional[int] = 5, search_depth: Optional[str] = 'advanced', include_domains: Optional[List[str]] = [], exclude_domains: Optional[List[str]] = [], include_answer: Optional[bool] = False, include_raw_content: Optional[bool] = False, include_images: Optional[bool] = False) \u2192 List[Dict][source]\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.tavily_search.TavilySearchAPIWrapper.html"}
{"id": "77b5e4f1e2b5-0", "text": "langchain.utilities.clickup.Task\u00b6\nclass langchain.utilities.clickup.Task(id: int, name: str, text_content: str, description: str, status: str, creator_id: int, creator_username: str, creator_email: str, assignees: List[Dict[str, Any]], watchers: List[Dict[str, Any]], priority: Optional[str], due_date: Optional[str], start_date: Optional[str], points: int, team_id: int, project_id: int)[source]\u00b6\nClass for a task.\nAttributes\nid\nname\ntext_content\ndescription\nstatus\ncreator_id\ncreator_username\ncreator_email\nassignees\nwatchers\npriority\ndue_date\nstart_date\npoints\nteam_id\nproject_id\nMethods\n__init__(id,\u00a0name,\u00a0text_content,\u00a0...)\nfrom_data(data)\n__init__(id: int, name: str, text_content: str, description: str, status: str, creator_id: int, creator_username: str, creator_email: str, assignees: List[Dict[str, Any]], watchers: List[Dict[str, Any]], priority: Optional[str], due_date: Optional[str], start_date: Optional[str], points: int, team_id: int, project_id: int) \u2192 None\u00b6\nclassmethod from_data(data: Dict[str, Any]) \u2192 Task[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.Task.html"}
{"id": "8e7fe87d3e5a-0", "text": "langchain.utilities.dalle_image_generator.DallEAPIWrapper\u00b6\nclass langchain.utilities.dalle_image_generator.DallEAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for OpenAI\u2019s DALL-E Image Generator.\nhttps://platform.openai.com/docs/guides/images/generations?context=node\nUsage instructions:\npip install openai\nsave your OPENAI_API_KEY in an environment variable\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam model: Optional[str] = None\u00b6\nModel to use for image generation.\nparam n: int = 1\u00b6\nNumber of images to generate\nparam openai_api_key: Optional[str] = None\u00b6\nparam separator: str = '\\n'\u00b6\nSeparator to use when multiple URLs are returned.\nparam size: str = '1024x1024'\u00b6\nSize of image to generate\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.dalle_image_generator.DallEAPIWrapper.html"}
{"id": "8e7fe87d3e5a-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.dalle_image_generator.DallEAPIWrapper.html"}
{"id": "8e7fe87d3e5a-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(query: str) \u2192 str[source]\u00b6\nRun query through OpenAI and parse result.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using DallEAPIWrapper\u00b6\nDall-E Image Generator", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.dalle_image_generator.DallEAPIWrapper.html"}
{"id": "03d1297aec3f-0", "text": "langchain.utilities.google_search.GoogleSearchAPIWrapper\u00b6\nclass langchain.utilities.google_search.GoogleSearchAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for Google Search API.\nAdapted from: Instructions adapted from https://stackoverflow.com/questions/\n37083058/\nprogrammatically-searching-google-in-python-using-custom-search\nTODO: DOCS for using it\n1. Install google-api-python-client\n- If you don\u2019t already have a Google account, sign up.\n- If you have never created a Google APIs Console project,\nread the Managing Projects page and create a project in the Google API Console.\n- Install the library using pip install google-api-python-client\n2. Enable the Custom Search API\n- Navigate to the APIs & Services\u2192Dashboard panel in Cloud Console.\n- Click Enable APIs and Services.\n- Search for Custom Search API and click on it.\n- Click Enable.\nURL for it: https://console.cloud.google.com/apis/library/customsearch.googleapis\n.com\n3. To create an API key:\n- Navigate to the APIs & Services \u2192 Credentials panel in Cloud Console.\n- Select Create credentials, then select API key from the drop-down menu.\n- The API key created dialog box displays your newly created key.\n- You now have an API_KEY\nAlternatively, you can just generate an API key here:\nhttps://developers.google.com/custom-search/docs/paid_element#api_key\n4. Setup Custom Search Engine so you can search the entire web\n- Create a custom search engine here: https://programmablesearchengine.google.com/.\n- In What to search to search, pick the Search the entire Web option.\nAfter search engine is created, you can click on it and find Search engine ID\non the Overview page.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_search.GoogleSearchAPIWrapper.html"}
{"id": "03d1297aec3f-1", "text": "Raises ValidationError if the input data cannot be parsed to form a valid model.\nparam google_api_key: Optional[str] = None\u00b6\nparam google_cse_id: Optional[str] = None\u00b6\nparam k: int = 10\u00b6\nparam siterestrict: bool = False\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_search.GoogleSearchAPIWrapper.html"}
{"id": "03d1297aec3f-2", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nresults(query: str, num_results: int, search_params: Optional[Dict[str, str]] = None) \u2192 List[Dict][source]\u00b6\nRun query through GoogleSearch and return metadata.\nParameters\nquery \u2013 The query to search for.\nnum_results \u2013 The number of results to return.\nsearch_params \u2013 Parameters to be passed on search\nReturns\nsnippet - The description of the result.\ntitle - The title of the result.\nlink - The link to the result.\nReturn type\nA list of dictionaries with the following keys", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_search.GoogleSearchAPIWrapper.html"}
{"id": "03d1297aec3f-3", "text": "Return type\nA list of dictionaries with the following keys\nrun(query: str) \u2192 str[source]\u00b6\nRun query through GoogleSearch and parse result.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using GoogleSearchAPIWrapper\u00b6\nGoogle Search\nBittensor\nSet env var OPENAI_API_KEY or load from a .env file:\nAgents\nWebResearchRetriever\nMessage Memory in Agent backed by a database\nMemory in Agent\nShared memory across agents and tools", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_search.GoogleSearchAPIWrapper.html"}
{"id": "2a7227c78253-0", "text": "langchain.utilities.sql_database.truncate_word\u00b6\nlangchain.utilities.sql_database.truncate_word(content: Any, *, length: int, suffix: str = '...') \u2192 str[source]\u00b6\nTruncate a string to a certain number of words, based on the max string\nlength.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.sql_database.truncate_word.html"}
{"id": "0c48a14862c9-0", "text": "langchain.utilities.clickup.Team\u00b6\nclass langchain.utilities.clickup.Team(id: int, name: str, members: List[Member])[source]\u00b6\nComponent class for a team.\nAttributes\nid\nname\nmembers\nMethods\n__init__(id,\u00a0name,\u00a0members)\nfrom_data(data)\n__init__(id: int, name: str, members: List[Member]) \u2192 None\u00b6\nclassmethod from_data(data: Dict) \u2192 Team[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.Team.html"}
{"id": "7c01ae16e273-0", "text": "langchain.utilities.clickup.fetch_folder_id\u00b6\nlangchain.utilities.clickup.fetch_folder_id(space_id: int, access_token: str) \u2192 Optional[int][source]\u00b6\nFetch the folder id.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.fetch_folder_id.html"}
{"id": "2b1cf88a1def-0", "text": "langchain.utilities.clickup.Component\u00b6\nclass langchain.utilities.clickup.Component[source]\u00b6\nBase class for all components.\nMethods\n__init__()\nfrom_data(data)\n__init__() \u2192 None\u00b6\nclassmethod from_data(data: Dict[str, Any]) \u2192 Component[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.Component.html"}
{"id": "0ccbea45c065-0", "text": "langchain.utilities.opaqueprompts.desanitize\u00b6\nlangchain.utilities.opaqueprompts.desanitize(sanitized_text: str, secure_context: bytes) \u2192 str[source]\u00b6\nRestore the original sensitive data from the sanitized text.\nParameters\nsanitized_text \u2013 Sanitized text.\nsecure_context \u2013 Secure context returned by the sanitize function.\nReturns\nDe-sanitized text.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.opaqueprompts.desanitize.html"}
{"id": "b0431ae01cf1-0", "text": "langchain.utilities.redis.check_redis_module_exist\u00b6\nlangchain.utilities.redis.check_redis_module_exist(client: RedisType, required_modules: List[dict]) \u2192 None[source]\u00b6\nCheck if the correct Redis modules are installed.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.redis.check_redis_module_exist.html"}
{"id": "8f085c1c5a8b-0", "text": "langchain.utilities.clickup.fetch_first_id\u00b6\nlangchain.utilities.clickup.fetch_first_id(data: dict, key: str) \u2192 Optional[int][source]\u00b6\nFetch the first id from a dictionary.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.clickup.fetch_first_id.html"}
{"id": "3aee540d7437-0", "text": "langchain.utilities.openapi.OpenAPISpec\u00b6\nclass langchain.utilities.openapi.OpenAPISpec[source]\u00b6\nOpenAPI Model that removes mis-formatted parts of the spec.\nAttributes\nbase_url\nGet the base url.\nopenapi\nMethods\n__init__()\nfrom_file(path)\nGet an OpenAPI spec from a file path.\nfrom_spec_dict(spec_dict)\nGet an OpenAPI spec from a dict.\nfrom_text(text)\nGet an OpenAPI spec from a text.\nfrom_url(url)\nGet an OpenAPI spec from a URL.\nget_cleaned_operation_id(operation,\u00a0path,\u00a0method)\nGet a cleaned operation id from an operation id.\nget_methods_for_path(path)\nReturn a list of valid methods for the specified path.\nget_operation(path,\u00a0method)\nGet the operation object for a given path and HTTP method.\nget_parameters_for_operation(operation)\nGet the components for a given operation.\nget_parameters_for_path(path)\nget_referenced_schema(ref)\nGet a schema (or nested reference) or err.\nget_request_body_for_operation(operation)\nGet the request body for a given operation.\nget_schema(schema)\nparse_obj(obj)\n__init__()\u00b6\nclassmethod from_file(path: Union[str, Path]) \u2192 OpenAPISpec[source]\u00b6\nGet an OpenAPI spec from a file path.\nclassmethod from_spec_dict(spec_dict: dict) \u2192 OpenAPISpec[source]\u00b6\nGet an OpenAPI spec from a dict.\nclassmethod from_text(text: str) \u2192 OpenAPISpec[source]\u00b6\nGet an OpenAPI spec from a text.\nclassmethod from_url(url: str) \u2192 OpenAPISpec[source]\u00b6\nGet an OpenAPI spec from a URL.\nstatic get_cleaned_operation_id(operation: Operation, path: str, method: str) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.openapi.OpenAPISpec.html"}
{"id": "3aee540d7437-1", "text": "Get a cleaned operation id from an operation id.\nget_methods_for_path(path: str) \u2192 List[str][source]\u00b6\nReturn a list of valid methods for the specified path.\nget_operation(path: str, method: str) \u2192 Operation[source]\u00b6\nGet the operation object for a given path and HTTP method.\nget_parameters_for_operation(operation: Operation) \u2192 List[Parameter][source]\u00b6\nGet the components for a given operation.\nget_parameters_for_path(path: str) \u2192 List[Parameter][source]\u00b6\nget_referenced_schema(ref: Reference) \u2192 Schema[source]\u00b6\nGet a schema (or nested reference) or err.\nget_request_body_for_operation(operation: Operation) \u2192 Optional[RequestBody][source]\u00b6\nGet the request body for a given operation.\nget_schema(schema: Union[Reference, Schema]) \u2192 Schema[source]\u00b6\nclassmethod parse_obj(obj: dict) \u2192 OpenAPISpec[source]\u00b6\nExamples using OpenAPISpec\u00b6\nNatural Language APIs", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.openapi.OpenAPISpec.html"}
{"id": "bc653ec49efe-0", "text": "langchain.utilities.alpha_vantage.AlphaVantageAPIWrapper\u00b6\nclass langchain.utilities.alpha_vantage.AlphaVantageAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for AlphaVantage API for Currency Exchange Rate.\nDocs for using:\nGo to AlphaVantage and sign up for an API key\nSave your API KEY into ALPHAVANTAGE_API_KEY env variable\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam alphavantage_api_key: Optional[str] = None\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.alpha_vantage.AlphaVantageAPIWrapper.html"}
{"id": "bc653ec49efe-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(from_currency: str, to_currency: str) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.alpha_vantage.AlphaVantageAPIWrapper.html"}
{"id": "bc653ec49efe-2", "text": "run(from_currency: str, to_currency: str) \u2192 str[source]\u00b6\nGet the current exchange rate for a specified currency pair.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty standard_currencies: List[str]\u00b6\nExamples using AlphaVantageAPIWrapper\u00b6\nAlpha Vantage", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.alpha_vantage.AlphaVantageAPIWrapper.html"}
{"id": "d2f9ba547695-0", "text": "langchain.utilities.brave_search.BraveSearchWrapper\u00b6\nclass langchain.utilities.brave_search.BraveSearchWrapper[source]\u00b6\nBases: BaseModel\nWrapper around the Brave search engine.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_key: str [Required]\u00b6\nThe API key to use for the Brave search engine.\nparam base_url: str = 'https://api.search.brave.com/res/v1/web/search'\u00b6\nThe base URL for the Brave search engine.\nparam search_kwargs: dict [Optional]\u00b6\nAdditional keyword arguments to pass to the search request.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.brave_search.BraveSearchWrapper.html"}
{"id": "d2f9ba547695-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\ndownload_documents(query: str) \u2192 List[Document][source]\u00b6\nQuery the Brave search engine and return the results as a list of Documents.\nParameters\nquery \u2013 The query to search for.\nReturns: The results as a list of Documents.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.brave_search.BraveSearchWrapper.html"}
{"id": "d2f9ba547695-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(query: str) \u2192 str[source]\u00b6\nQuery the Brave search engine and return the results as a JSON string.\nParameters\nquery \u2013 The query to search for.\nReturns: The results as a JSON string.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.brave_search.BraveSearchWrapper.html"}
{"id": "052815778da4-0", "text": "langchain.utilities.spark_sql.SparkSQL\u00b6\nclass langchain.utilities.spark_sql.SparkSQL(spark_session: Optional[SparkSession] = None, catalog: Optional[str] = None, schema: Optional[str] = None, ignore_tables: Optional[List[str]] = None, include_tables: Optional[List[str]] = None, sample_rows_in_table_info: int = 3)[source]\u00b6\nSparkSQL is a utility class for interacting with Spark SQL.\nInitialize a SparkSQL object.\nParameters\nspark_session \u2013 A SparkSession object.\nIf not provided, one will be created.\ncatalog \u2013 The catalog to use.\nIf not provided, the default catalog will be used.\nschema \u2013 The schema to use.\nIf not provided, the default schema will be used.\nignore_tables \u2013 A list of tables to ignore.\nIf not provided, all tables will be used.\ninclude_tables \u2013 A list of tables to include.\nIf not provided, all tables will be used.\nsample_rows_in_table_info \u2013 The number of rows to include in the table info.\nDefaults to 3.\nMethods\n__init__([spark_session,\u00a0catalog,\u00a0schema,\u00a0...])\nInitialize a SparkSQL object.\nfrom_uri(database_uri[,\u00a0engine_args])\nCreating a remote Spark Session via Spark connect.\nget_table_info([table_names])\nget_table_info_no_throw([table_names])\nGet information about specified tables.\nget_usable_table_names()\nGet names of tables available.\nrun(command[,\u00a0fetch])\nrun_no_throw(command[,\u00a0fetch])\nExecute a SQL command and return a string representing the results.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.spark_sql.SparkSQL.html"}
{"id": "052815778da4-1", "text": "Execute a SQL command and return a string representing the results.\n__init__(spark_session: Optional[SparkSession] = None, catalog: Optional[str] = None, schema: Optional[str] = None, ignore_tables: Optional[List[str]] = None, include_tables: Optional[List[str]] = None, sample_rows_in_table_info: int = 3)[source]\u00b6\nInitialize a SparkSQL object.\nParameters\nspark_session \u2013 A SparkSession object.\nIf not provided, one will be created.\ncatalog \u2013 The catalog to use.\nIf not provided, the default catalog will be used.\nschema \u2013 The schema to use.\nIf not provided, the default schema will be used.\nignore_tables \u2013 A list of tables to ignore.\nIf not provided, all tables will be used.\ninclude_tables \u2013 A list of tables to include.\nIf not provided, all tables will be used.\nsample_rows_in_table_info \u2013 The number of rows to include in the table info.\nDefaults to 3.\nclassmethod from_uri(database_uri: str, engine_args: Optional[dict] = None, **kwargs: Any) \u2192 SparkSQL[source]\u00b6\nCreating a remote Spark Session via Spark connect.\nFor example: SparkSQL.from_uri(\u201csc://localhost:15002\u201d)\nget_table_info(table_names: Optional[List[str]] = None) \u2192 str[source]\u00b6\nget_table_info_no_throw(table_names: Optional[List[str]] = None) \u2192 str[source]\u00b6\nGet information about specified tables.\nFollows best practices as specified in: Rajkumar et al, 2022\n(https://arxiv.org/abs/2204.00498)\nIf sample_rows_in_table_info, the specified number of sample rows will be\nappended to each table description. This can increase performance as\ndemonstrated in the paper.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.spark_sql.SparkSQL.html"}
{"id": "052815778da4-2", "text": "demonstrated in the paper.\nget_usable_table_names() \u2192 Iterable[str][source]\u00b6\nGet names of tables available.\nrun(command: str, fetch: str = 'all') \u2192 str[source]\u00b6\nrun_no_throw(command: str, fetch: str = 'all') \u2192 str[source]\u00b6\nExecute a SQL command and return a string representing the results.\nIf the statement returns rows, a string of the results is returned.\nIf the statement returns no rows, an empty string is returned.\nIf the statement throws an error, the error message is returned.\nExamples using SparkSQL\u00b6\nSpark SQL", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.spark_sql.SparkSQL.html"}
{"id": "6ed5f724386c-0", "text": "langchain.utilities.metaphor_search.MetaphorSearchAPIWrapper\u00b6\nclass langchain.utilities.metaphor_search.MetaphorSearchAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for Metaphor Search API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam k: int = 10\u00b6\nparam metaphor_api_key: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.metaphor_search.MetaphorSearchAPIWrapper.html"}
{"id": "6ed5f724386c-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.metaphor_search.MetaphorSearchAPIWrapper.html"}
{"id": "6ed5f724386c-2", "text": "results(query: str, num_results: int, include_domains: Optional[List[str]] = None, exclude_domains: Optional[List[str]] = None, start_crawl_date: Optional[str] = None, end_crawl_date: Optional[str] = None, start_published_date: Optional[str] = None, end_published_date: Optional[str] = None, use_autoprompt: Optional[bool] = None) \u2192 List[Dict][source]\u00b6\nRun query through Metaphor Search and return metadata.\nParameters\nquery \u2013 The query to search for.\nnum_results \u2013 The number of results to return.\ninclude_domains \u2013 A list of domains to include in the search. Only one of include_domains and exclude_domains should be defined.\nexclude_domains \u2013 A list of domains to exclude from the search. Only one of include_domains and exclude_domains should be defined.\nstart_crawl_date \u2013 If specified, only pages we crawled after start_crawl_date will be returned.\nend_crawl_date \u2013 If specified, only pages we crawled before end_crawl_date will be returned.\nstart_published_date \u2013 If specified, only pages published after start_published_date will be returned.\nend_published_date \u2013 If specified, only pages published before end_published_date will be returned.\nuse_autoprompt \u2013 If true, we turn your query into a more Metaphor-friendly query. Adds latency.\nReturns\ntitle - The title of the page\nurl - The url\nauthor - Author of the content, if applicable. Otherwise, None.\npublished_date - Estimated date published\nin YYYY-MM-DD format. Otherwise, None.\nReturn type\nA list of dictionaries with the following keys", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.metaphor_search.MetaphorSearchAPIWrapper.html"}
{"id": "6ed5f724386c-3", "text": "Return type\nA list of dictionaries with the following keys\nasync results_async(query: str, num_results: int, include_domains: Optional[List[str]] = None, exclude_domains: Optional[List[str]] = None, start_crawl_date: Optional[str] = None, end_crawl_date: Optional[str] = None, start_published_date: Optional[str] = None, end_published_date: Optional[str] = None, use_autoprompt: Optional[bool] = None) \u2192 List[Dict][source]\u00b6\nGet results from the Metaphor Search API asynchronously.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using MetaphorSearchAPIWrapper\u00b6\nMetaphor Search", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.metaphor_search.MetaphorSearchAPIWrapper.html"}
{"id": "5e8abc1c1b08-0", "text": "langchain.utilities.powerbi.json_to_md\u00b6\nlangchain.utilities.powerbi.json_to_md(json_contents: List[Dict[str, Union[str, float, int]]], table_name: Optional[str] = None) \u2192 str[source]\u00b6\nConverts a JSON object to a markdown table.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.powerbi.json_to_md.html"}
{"id": "4166258a0d9d-0", "text": "langchain.utilities.google_serper.GoogleSerperAPIWrapper\u00b6\nclass langchain.utilities.google_serper.GoogleSerperAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper around the Serper.dev Google Search API.\nYou can create a free API key at https://serper.dev.\nTo use, you should have the environment variable SERPER_API_KEY\nset with your API key, or pass serper_api_key as a named parameter\nto the constructor.\nExample\nfrom langchain.utilities import GoogleSerperAPIWrapper\ngoogle_serper = GoogleSerperAPIWrapper()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aiosession: Optional[aiohttp.client.ClientSession] = None\u00b6\nparam gl: str = 'us'\u00b6\nparam hl: str = 'en'\u00b6\nparam k: int = 10\u00b6\nparam serper_api_key: Optional[str] = None\u00b6\nparam tbs: Optional[str] = None\u00b6\nparam type: Literal['news', 'search', 'places', 'images'] = 'search'\u00b6\nasync aresults(query: str, **kwargs: Any) \u2192 Dict[source]\u00b6\nRun query through GoogleSearch.\nasync arun(query: str, **kwargs: Any) \u2192 str[source]\u00b6\nRun query through GoogleSearch and parse result async.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_serper.GoogleSerperAPIWrapper.html"}
{"id": "4166258a0d9d-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_serper.GoogleSerperAPIWrapper.html"}
{"id": "4166258a0d9d-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nresults(query: str, **kwargs: Any) \u2192 Dict[source]\u00b6\nRun query through GoogleSearch.\nrun(query: str, **kwargs: Any) \u2192 str[source]\u00b6\nRun query through GoogleSearch and parse result.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_serper.GoogleSerperAPIWrapper.html"}
{"id": "4166258a0d9d-3", "text": "Try to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using GoogleSerperAPIWrapper\u00b6\nGoogle Serper\nRetrieve as you generate with FLARE", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.google_serper.GoogleSerperAPIWrapper.html"}
{"id": "c2395a7fc578-0", "text": "langchain.utilities.wolfram_alpha.WolframAlphaAPIWrapper\u00b6\nclass langchain.utilities.wolfram_alpha.WolframAlphaAPIWrapper[source]\u00b6\nBases: BaseModel\nWrapper for Wolfram Alpha.\nDocs for using:\nGo to wolfram alpha and sign up for a developer account\nCreate an app and get your APP ID\nSave your APP ID into WOLFRAM_ALPHA_APPID env variable\npip install wolframalpha\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam wolfram_alpha_appid: Optional[str] = None\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.wolfram_alpha.WolframAlphaAPIWrapper.html"}
{"id": "c2395a7fc578-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(query: str) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.wolfram_alpha.WolframAlphaAPIWrapper.html"}
{"id": "c2395a7fc578-2", "text": "run(query: str) \u2192 str[source]\u00b6\nRun query through WolframAlpha and parse result.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using WolframAlphaAPIWrapper\u00b6\nWolfram Alpha", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.wolfram_alpha.WolframAlphaAPIWrapper.html"}
{"id": "4dd5b3c06b21-0", "text": "langchain.utilities.python.PythonREPL\u00b6\nclass langchain.utilities.python.PythonREPL[source]\u00b6\nBases: BaseModel\nSimulates a standalone Python REPL.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam globals: Optional[Dict] [Optional] (alias '_globals')\u00b6\nparam locals: Optional[Dict] [Optional] (alias '_locals')\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.python.PythonREPL.html"}
{"id": "4dd5b3c06b21-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(command: str, timeout: Optional[int] = None) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.python.PythonREPL.html"}
{"id": "4dd5b3c06b21-2", "text": "run(command: str, timeout: Optional[int] = None) \u2192 str[source]\u00b6\nRun command with own globals/locals and returns anything printed.\nTimeout after the specified number of seconds.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclassmethod worker(command: str, globals: Optional[Dict], locals: Optional[Dict], queue: Queue) \u2192 None[source]\u00b6\nExamples using PythonREPL\u00b6\nDynamodb Chat Message History\nPython\nCode writing", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.python.PythonREPL.html"}
{"id": "6fcac1005765-0", "text": "langchain.utilities.tensorflow_datasets.TensorflowDatasets\u00b6\nclass langchain.utilities.tensorflow_datasets.TensorflowDatasets[source]\u00b6\nBases: BaseModel\nAccess to the TensorFlow Datasets.\nThe Current implementation can work only with datasets that fit in a memory.\nTensorFlow Datasets is a collection of datasets ready to use, with TensorFlow\nor other Python ML frameworks, such as Jax. All datasets are exposed\nas tf.data.Datasets.\nTo get started see the Guide: https://www.tensorflow.org/datasets/overview and\nthe list of datasets: https://www.tensorflow.org/datasets/catalog/\noverview#all_datasets\nYou have to provide the sample_to_document_function: a function thata sample from the dataset-specific format to the Document.\ndataset_name\u00b6\nthe name of the dataset to load\nsplit_name\u00b6\nthe name of the split to load. Defaults to \u201ctrain\u201d.\nload_max_docs\u00b6\na limit to the number of loaded documents. Defaults to 100.\nsample_to_document_function\u00b6\na function that converts a dataset sample\nto a Document\nExample\nfrom langchain.utilities import TensorflowDatasets\ndef mlqaen_example_to_document(example: dict) -> Document:\n    return Document(\n        page_content=decode_to_str(example[\"context\"]),\n        metadata={\n            \"id\": decode_to_str(example[\"id\"]),\n            \"title\": decode_to_str(example[\"title\"]),\n            \"question\": decode_to_str(example[\"question\"]),\n            \"answer\": decode_to_str(example[\"answers\"][\"text\"][0]),\n        },\n    )\ntsds_client = TensorflowDatasets(\n        dataset_name=\"mlqa/en\",\n        split_name=\"train\",\n        load_max_docs=MAX_DOCS,\n        sample_to_document_function=mlqaen_example_to_document,\n    )\nCreate a new model by parsing and validating input data from keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.tensorflow_datasets.TensorflowDatasets.html"}
{"id": "6fcac1005765-1", "text": ")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam dataset_name: str = ''\u00b6\nparam load_max_docs: int = 100\u00b6\nparam sample_to_document_function: Optional[Callable[[Dict], langchain.schema.document.Document]] = None\u00b6\nparam split_name: str = 'train'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.tensorflow_datasets.TensorflowDatasets.html"}
{"id": "6fcac1005765-2", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nDownload a selected dataset lazily.\nReturns: an iterator of Documents.\nload() \u2192 List[Document][source]\u00b6\nDownload a selected dataset.\nReturns: a list of Documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.tensorflow_datasets.TensorflowDatasets.html"}
{"id": "6fcac1005765-3", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/utilities/langchain.utilities.tensorflow_datasets.TensorflowDatasets.html"}
{"id": "8180e0102889-0", "text": "langchain_experimental.pal_chain.base.PALChain\u00b6\nclass langchain_experimental.pal_chain.base.PALChain[source]\u00b6\nBases: Chain\nImplements Program-Aided Language Models (PAL).\nThis class implements the Program-Aided Language Models (PAL) for generating code\nsolutions. PAL is a technique described in the paper \u201cProgram-Aided Language Models\u201d\n(https://arxiv.org/pdf/2211.10435.pdf).\nSecurity note: This class implements an AI technique that generates and evaluatesPython code, which can be dangerous and requires a specially sandboxed\nenvironment to be safely used. While this class implements some basic guardrails\nby limiting available locals/globals and by parsing and inspecting\nthe generated Python AST using PALValidation, those guardrails will not\ndeter sophisticated attackers and are not a replacement for a proper sandbox.\nDo not use this class on untrusted inputs, with elevated permissions,\nor without consulting your security team about proper sandboxing!\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam code_validations: PALValidation [Optional]\u00b6\nValidations to perform on the generated code.\nparam get_answer_expr: str = 'print(solution())'\u00b6\nExpression to use to get the answer from the generated code.\nparam llm_chain: LLMChain [Required]\u00b6", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-1", "text": "param llm_chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam python_globals: Optional[Dict[str, Any]] = None\u00b6\nPython globals and locals to use when executing the generated code.\nparam python_locals: Optional[Dict[str, Any]] = None\u00b6\nPython globals and locals to use when executing the generated code.\nparam return_intermediate_steps: bool = False\u00b6\nWhether to return intermediate steps in the generated code.\nparam stop: str = '\\n\\n'\u00b6\nStop token to use when generating code.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam timeout: Optional[int] = 10\u00b6\nTimeout in seconds for the generated code to execute.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-2", "text": "will be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-5", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-6", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_colored_object_prompt(llm: BaseLanguageModel, **kwargs: Any) \u2192 PALChain[source]\u00b6\nLoad PAL from colored object prompt.\nParameters\nllm (BaseLanguageModel) \u2013 The language model to use for generating code.\nReturns\nAn instance of PALChain.\nReturn type\nPALChain", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-8", "text": "Returns\nAn instance of PALChain.\nReturn type\nPALChain\nclassmethod from_math_prompt(llm: BaseLanguageModel, **kwargs: Any) \u2192 PALChain[source]\u00b6\nLoad PAL from math prompt.\nParameters\nllm (BaseLanguageModel) \u2013 The language model to use for generating code.\nReturns\nAn instance of PALChain.\nReturn type\nPALChain\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-9", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-10", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-11", "text": "The main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-12", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclassmethod validate_code(code: str, code_validations: PALValidation) \u2192 None[source]\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-13", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "8180e0102889-14", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALChain.html"}
{"id": "e878749b31ff-0", "text": "langchain_experimental.pal_chain.base.PALValidation\u00b6\nclass langchain_experimental.pal_chain.base.PALValidation(solution_expression_name: Optional[str] = None, solution_expression_type: Optional[type] = None, allow_imports: bool = False, allow_command_exec: bool = False)[source]\u00b6\nInitialize a PALValidation instance.\nParameters\nsolution_expression_name (str) \u2013 Name of the expected solution expression.\nIf passed, solution_expression_type must be passed as well.\nsolution_expression_type (str) \u2013 AST type of the expected solution\nexpression. If passed, solution_expression_name must be passed as well.\nMust be one of PALValidation.SOLUTION_EXPRESSION_TYPE_FUNCTION,\nPALValidation.SOLUTION_EXPRESSION_TYPE_VARIABLE.\nallow_imports (bool) \u2013 Allow import statements.\nallow_command_exec (bool) \u2013 Allow using known command execution functions.\nMethods\n__init__([solution_expression_name,\u00a0...])\nInitialize a PALValidation instance.\n__init__(solution_expression_name: Optional[str] = None, solution_expression_type: Optional[type] = None, allow_imports: bool = False, allow_command_exec: bool = False)[source]\u00b6\nInitialize a PALValidation instance.\nParameters\nsolution_expression_name (str) \u2013 Name of the expected solution expression.\nIf passed, solution_expression_type must be passed as well.\nsolution_expression_type (str) \u2013 AST type of the expected solution\nexpression. If passed, solution_expression_name must be passed as well.\nMust be one of PALValidation.SOLUTION_EXPRESSION_TYPE_FUNCTION,\nPALValidation.SOLUTION_EXPRESSION_TYPE_VARIABLE.\nallow_imports (bool) \u2013 Allow import statements.\nallow_command_exec (bool) \u2013 Allow using known command execution functions.", "source": "lang/api.python.langchain.com/en/latest/pal_chain/langchain_experimental.pal_chain.base.PALValidation.html"}
{"id": "7e841b2c5d42-0", "text": "langchain.document_transformers.embeddings_redundant_filter.get_stateful_documents\u00b6\nlangchain.document_transformers.embeddings_redundant_filter.get_stateful_documents(documents: Sequence[Document]) \u2192 Sequence[_DocumentWithState][source]\u00b6\nConvert a list of documents to a list of documents with state.\nParameters\ndocuments \u2013 The documents to convert.\nReturns\nA list of documents with state.", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.embeddings_redundant_filter.get_stateful_documents.html"}
{"id": "0306e9b7524b-0", "text": "langchain.document_transformers.html2text.Html2TextTransformer\u00b6\nclass langchain.document_transformers.html2text.Html2TextTransformer(ignore_links: bool = True, ignore_images: bool = True)[source]\u00b6\nReplace occurrences of a particular search pattern with a replacement string\nParameters\nignore_links \u2013 Whether links should be ignored; defaults to True.\nignore_images \u2013 Whether images should be ignored; defaults to True.\nExample\nMethods\n__init__([ignore_links,\u00a0ignore_images])\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a list of documents.\ntransform_documents(documents,\u00a0**kwargs)\nTransform a list of documents.\n__init__(ignore_links: bool = True, ignore_images: bool = True) \u2192 None[source]\u00b6\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nAsynchronously transform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nTransform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\nExamples using Html2TextTransformer\u00b6\nhtml2text\nAsync Chromium\nSet env var OPENAI_API_KEY or load from a .env file:", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.html2text.Html2TextTransformer.html"}
{"id": "c0eb6624d515-0", "text": "langchain.document_transformers.embeddings_redundant_filter.EmbeddingsRedundantFilter\u00b6\nclass langchain.document_transformers.embeddings_redundant_filter.EmbeddingsRedundantFilter[source]\u00b6\nBases: BaseDocumentTransformer, BaseModel\nFilter that drops redundant documents by comparing their embeddings.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam embeddings: langchain.schema.embeddings.Embeddings [Required]\u00b6\nEmbeddings to use for embedding document contents.\nparam similarity_fn: Callable = <function cosine_similarity>\u00b6\nSimilarity function for comparing documents. Function expected to take as input\ntwo matrices (List[List[float]]) and return a matrix of scores where higher values\nindicate greater similarity.\nparam similarity_threshold: float = 0.95\u00b6\nThreshold for determining when two documents are similar enough\nto be considered redundant.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nAsynchronously transform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.embeddings_redundant_filter.EmbeddingsRedundantFilter.html"}
{"id": "c0eb6624d515-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.embeddings_redundant_filter.EmbeddingsRedundantFilter.html"}
{"id": "c0eb6624d515-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nFilter down documents.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using EmbeddingsRedundantFilter\u00b6\nLOTR (Merger Retriever)", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.embeddings_redundant_filter.EmbeddingsRedundantFilter.html"}
{"id": "f804010546c2-0", "text": "langchain.document_transformers.openai_functions.OpenAIMetadataTagger\u00b6\nclass langchain.document_transformers.openai_functions.OpenAIMetadataTagger[source]\u00b6\nBases: BaseDocumentTransformer, BaseModel\nExtract metadata tags from document contents using OpenAI functions.\nExample:from langchain.chat_models import ChatOpenAI\nfrom langchain.document_transformers import OpenAIMetadataTagger\nfrom langchain.schema import Document\nschema = {\n    \"properties\": {\n        \"movie_title\": { \"type\": \"string\" },\n        \"critic\": { \"type\": \"string\" },\n        \"tone\": {\n            \"type\": \"string\",\n            \"enum\": [\"positive\", \"negative\"]\n        },\n        \"rating\": {\n            \"type\": \"integer\",\n            \"description\": \"The number of stars the critic rated the movie\"\n        }\n    },\n    \"required\": [\"movie_title\", \"critic\", \"tone\"]\n}\n# Must be an OpenAI model that supports functions\nllm = ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-0613\")\ntagging_chain = create_tagging_chain(schema, llm)\ndocument_transformer = OpenAIMetadataTagger(tagging_chain=tagging_chain)\noriginal_documents = [\n    Document(page_content=\"Review of The Bee Movie\nBy Roger Ebert\nThis is the greatest movie ever made. 4 out of 5 stars.\u201d),Document(page_content=\u201dReview of The Godfather\nBy Anonymous\nThis movie was super boring. 1 out of 5 stars.\u201d, metadata={\u201creliable\u201d: False}),]\nenhanced_documents = document_transformer.transform_documents(original_documents)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.openai_functions.OpenAIMetadataTagger.html"}
{"id": "f804010546c2-1", "text": "Raises ValidationError if the input data cannot be parsed to form a valid model.\nparam tagging_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nThe chain used to extract metadata from each document.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nAsynchronously transform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.openai_functions.OpenAIMetadataTagger.html"}
{"id": "f804010546c2-2", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.openai_functions.OpenAIMetadataTagger.html"}
{"id": "f804010546c2-3", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nAutomatically extract and populate metadata\nfor each document according to the provided schema.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.openai_functions.OpenAIMetadataTagger.html"}
{"id": "ca0870a0ec3e-0", "text": "langchain.document_transformers.beautiful_soup_transformer.BeautifulSoupTransformer\u00b6\nclass langchain.document_transformers.beautiful_soup_transformer.BeautifulSoupTransformer[source]\u00b6\nTransform HTML content by extracting specific tags and removing unwanted ones.\nExample\nInitialize the transformer.\nThis checks if the BeautifulSoup4 package is installed.\nIf not, it raises an ImportError.\nMethods\n__init__()\nInitialize the transformer.\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a list of documents.\nextract_tags(html_content,\u00a0tags)\nExtract specific tags from a given HTML content.\nremove_unnecessary_lines(content)\nClean up the content by removing unnecessary lines.\nremove_unwanted_tags(html_content,\u00a0unwanted_tags)\nRemove unwanted tags from a given HTML content.\ntransform_documents(documents[,\u00a0...])\nTransform a list of Document objects by cleaning their HTML content.\n__init__() \u2192 None[source]\u00b6\nInitialize the transformer.\nThis checks if the BeautifulSoup4 package is installed.\nIf not, it raises an ImportError.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nAsynchronously transform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\nstatic extract_tags(html_content: str, tags: List[str]) \u2192 str[source]\u00b6\nExtract specific tags from a given HTML content.\nParameters\nhtml_content \u2013 The original HTML content string.\ntags \u2013 A list of tags to be extracted from the HTML.\nReturns\nA string combining the content of the extracted tags.\nstatic remove_unnecessary_lines(content: str) \u2192 str[source]\u00b6\nClean up the content by removing unnecessary lines.\nParameters\ncontent \u2013 A string, which may contain unnecessary lines or spaces.\nReturns\nA cleaned string with unnecessary lines removed.", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.beautiful_soup_transformer.BeautifulSoupTransformer.html"}
{"id": "ca0870a0ec3e-1", "text": "Returns\nA cleaned string with unnecessary lines removed.\nstatic remove_unwanted_tags(html_content: str, unwanted_tags: List[str]) \u2192 str[source]\u00b6\nRemove unwanted tags from a given HTML content.\nParameters\nhtml_content \u2013 The original HTML content string.\nunwanted_tags \u2013 A list of tags to be removed from the HTML.\nReturns\nA cleaned HTML string with unwanted tags removed.\ntransform_documents(documents: Sequence[Document], unwanted_tags: List[str] = ['script', 'style'], tags_to_extract: List[str] = ['p', 'li', 'div', 'a'], remove_lines: bool = True, **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nTransform a list of Document objects by cleaning their HTML content.\nParameters\ndocuments \u2013 A sequence of Document objects containing HTML content.\nunwanted_tags \u2013 A list of tags to be removed from the HTML.\ntags_to_extract \u2013 A list of tags whose content will be extracted.\nremove_lines \u2013 If set to True, unnecessary lines will be\ncontent. (removed from the HTML) \u2013 \nReturns\nA sequence of Document objects with transformed content.\nExamples using BeautifulSoupTransformer\u00b6\nBeautiful Soup\nSet env var OPENAI_API_KEY or load from a .env file:", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.beautiful_soup_transformer.BeautifulSoupTransformer.html"}
{"id": "a0cab05eadf7-0", "text": "langchain.document_transformers.embeddings_redundant_filter.EmbeddingsClusteringFilter\u00b6\nclass langchain.document_transformers.embeddings_redundant_filter.EmbeddingsClusteringFilter[source]\u00b6\nBases: BaseDocumentTransformer, BaseModel\nPerform K-means clustering on document vectors.\nReturns an arbitrary number of documents closest to center.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam embeddings: langchain.schema.embeddings.Embeddings [Required]\u00b6\nEmbeddings to use for embedding document contents.\nparam num_closest: int = 1\u00b6\nThe number of closest vectors to return for each cluster center.\nparam num_clusters: int = 5\u00b6\nNumber of clusters. Groups of documents with similar meaning.\nparam random_state: int = 42\u00b6\nControls the random number generator used to initialize the cluster centroids.\nIf you set the random_state parameter to None, the KMeans algorithm will use a\nrandom number generator that is seeded with the current time. This means\nthat the results of the KMeans algorithm will be different each time you\nrun it.\nparam remove_duplicates: bool = False\u00b6\nBy default duplicated results are skipped and replaced by the next closest\nvector in the cluster. If remove_duplicates is true no replacement will be done:\nThis could dramatically reduce results when there is a lot of overlap between\nclusters.\nparam sorted: bool = False\u00b6\nBy default results are re-ordered \u201cgrouping\u201d them by cluster, if sorted is true\nresult will be ordered by the original position from the retriever\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nAsynchronously transform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.embeddings_redundant_filter.EmbeddingsClusteringFilter.html"}
{"id": "a0cab05eadf7-1", "text": "documents \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.embeddings_redundant_filter.EmbeddingsClusteringFilter.html"}
{"id": "a0cab05eadf7-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nFilter down documents.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using EmbeddingsClusteringFilter\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.embeddings_redundant_filter.EmbeddingsClusteringFilter.html"}
{"id": "a0cab05eadf7-3", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nExamples using EmbeddingsClusteringFilter\u00b6\nLOTR (Merger Retriever)", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.embeddings_redundant_filter.EmbeddingsClusteringFilter.html"}
{"id": "9ce36987d003-0", "text": "langchain.document_transformers.beautiful_soup_transformer.get_navigable_strings\u00b6\nlangchain.document_transformers.beautiful_soup_transformer.get_navigable_strings(element: Any) \u2192 Iterator[str][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.beautiful_soup_transformer.get_navigable_strings.html"}
{"id": "3b80ccfdaca3-0", "text": "langchain.document_transformers.doctran_text_extract.DoctranPropertyExtractor\u00b6\nclass langchain.document_transformers.doctran_text_extract.DoctranPropertyExtractor(properties: List[dict], openai_api_key: Optional[str] = None, openai_api_model: Optional[str] = None)[source]\u00b6\nExtract properties from text documents using doctran.\nParameters\nproperties \u2013 A list of the properties to extract.\nopenai_api_key \u2013 OpenAI API key. Can also be specified via environment variable\nOPENAI_API_KEY.\nExample\nfrom langchain.document_transformers import DoctranPropertyExtractor\nproperties = [\n    {\n        \"name\": \"category\",\n        \"description\": \"What type of email this is.\",\n        \"type\": \"string\",\n        \"enum\": [\"update\", \"action_item\", \"customer_feedback\", \"announcement\", \"other\"],\n        \"required\": True,\n    },\n    {\n        \"name\": \"mentions\",\n        \"description\": \"A list of all people mentioned in this email.\",\n        \"type\": \"array\",\n        \"items\": {\n            \"name\": \"full_name\",\n            \"description\": \"The full name of the person mentioned.\",\n            \"type\": \"string\",\n        },\n        \"required\": True,\n    },\n    {\n        \"name\": \"eli5\",\n        \"description\": \"Explain this email to me like I'm 5 years old.\",\n        \"type\": \"string\",\n        \"required\": True,\n    },\n]\n# Pass in openai_api_key or set env var OPENAI_API_KEY\nproperty_extractor = DoctranPropertyExtractor(properties)\ntransformed_document = await qa_transformer.atransform_documents(documents)\nMethods\n__init__(properties[,\u00a0openai_api_key,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.doctran_text_extract.DoctranPropertyExtractor.html"}
{"id": "3b80ccfdaca3-1", "text": "Methods\n__init__(properties[,\u00a0openai_api_key,\u00a0...])\natransform_documents(documents,\u00a0**kwargs)\nExtracts properties from text documents using doctran.\ntransform_documents(documents,\u00a0**kwargs)\nTransform a list of documents.\n__init__(properties: List[dict], openai_api_key: Optional[str] = None, openai_api_model: Optional[str] = None) \u2192 None[source]\u00b6\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nExtracts properties from text documents using doctran.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nTransform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\nExamples using DoctranPropertyExtractor\u00b6\nDoctran Extract Properties", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.doctran_text_extract.DoctranPropertyExtractor.html"}
{"id": "589345c8795e-0", "text": "langchain.document_transformers.nuclia_text_transform.NucliaTextTransformer\u00b6\nclass langchain.document_transformers.nuclia_text_transform.NucliaTextTransformer(nua: NucliaUnderstandingAPI)[source]\u00b6\nThe Nuclia Understanding API splits into paragraphs and sentences,\nidentifies entities, provides a summary of the text and generates\nembeddings for all sentences.\nMethods\n__init__(nua)\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a list of documents.\ntransform_documents(documents,\u00a0**kwargs)\nTransform a list of documents.\n__init__(nua: NucliaUnderstandingAPI)[source]\u00b6\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nAsynchronously transform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nTransform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\nExamples using NucliaTextTransformer\u00b6\nNuclia Understanding API document transformer", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.nuclia_text_transform.NucliaTextTransformer.html"}
{"id": "b0b4eada3c0e-0", "text": "langchain.document_transformers.long_context_reorder.LongContextReorder\u00b6\nclass langchain.document_transformers.long_context_reorder.LongContextReorder[source]\u00b6\nBases: BaseDocumentTransformer, BaseModel\nLost in the middle:\nPerformance degrades when models must access relevant information\nin the middle of long contexts.\nSee: https://arxiv.org/abs//2307.03172\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nAsynchronously transform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.long_context_reorder.LongContextReorder.html"}
{"id": "b0b4eada3c0e-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.long_context_reorder.LongContextReorder.html"}
{"id": "b0b4eada3c0e-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nReorders documents.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using LongContextReorder\u00b6\nLOTR (Merger Retriever)\nLost in the middle: The problem with long contexts", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.long_context_reorder.LongContextReorder.html"}
{"id": "6efce921486c-0", "text": "langchain.document_transformers.doctran_text_qa.DoctranQATransformer\u00b6\nclass langchain.document_transformers.doctran_text_qa.DoctranQATransformer(openai_api_key: Optional[str] = None, openai_api_model: Optional[str] = None)[source]\u00b6\nExtract QA from text documents using doctran.\nParameters\nopenai_api_key \u2013 OpenAI API key. Can also be specified via environment variable\nOPENAI_API_KEY.\nExample\nfrom langchain.document_transformers import DoctranQATransformer\n# Pass in openai_api_key or set env var OPENAI_API_KEY\nqa_transformer = DoctranQATransformer()\ntransformed_document = await qa_transformer.atransform_documents(documents)\nMethods\n__init__([openai_api_key,\u00a0openai_api_model])\natransform_documents(documents,\u00a0**kwargs)\nExtracts QA from text documents using doctran.\ntransform_documents(documents,\u00a0**kwargs)\nTransform a list of documents.\n__init__(openai_api_key: Optional[str] = None, openai_api_model: Optional[str] = None) \u2192 None[source]\u00b6\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nExtracts QA from text documents using doctran.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nTransform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\nExamples using DoctranQATransformer\u00b6\nDoctran Interrogate Documents", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.doctran_text_qa.DoctranQATransformer.html"}
{"id": "1e39aaf085b8-0", "text": "langchain.document_transformers.doctran_text_translate.DoctranTextTranslator\u00b6\nclass langchain.document_transformers.doctran_text_translate.DoctranTextTranslator(openai_api_key: Optional[str] = None, language: str = 'english', openai_api_model: Optional[str] = None)[source]\u00b6\nTranslate text documents using doctran.\nParameters\nopenai_api_key \u2013 OpenAI API key. Can also be specified via environment variable\nOPENAI_API_KEY. \u2013 \nlanguage \u2013 The language to translate to.\nExample\nfrom langchain.document_transformers import DoctranTextTranslator\n# Pass in openai_api_key or set env var OPENAI_API_KEY\nqa_translator = DoctranTextTranslator(language=\u201dspanish\u201d)\ntranslated_document = await qa_translator.atransform_documents(documents)\nMethods\n__init__([openai_api_key,\u00a0language,\u00a0...])\natransform_documents(documents,\u00a0**kwargs)\nTranslates text documents using doctran.\ntransform_documents(documents,\u00a0**kwargs)\nTransform a list of documents.\n__init__(openai_api_key: Optional[str] = None, language: str = 'english', openai_api_model: Optional[str] = None) \u2192 None[source]\u00b6\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nTranslates text documents using doctran.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nTransform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\nExamples using DoctranTextTranslator\u00b6\nDoctran Translate Documents", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.doctran_text_translate.DoctranTextTranslator.html"}
{"id": "a1d795b26b6b-0", "text": "langchain.document_transformers.openai_functions.create_metadata_tagger\u00b6\nlangchain.document_transformers.openai_functions.create_metadata_tagger(metadata_schema: Union[Dict[str, Any], Type[BaseModel]], llm: BaseLanguageModel, prompt: Optional[ChatPromptTemplate] = None, *, tagging_chain_kwargs: Optional[Dict] = None) \u2192 OpenAIMetadataTagger[source]\u00b6\nCreate a DocumentTransformer that uses an OpenAI function chain to automatically\ntag documents with metadata based on their content and an input schema.\nArgs:\nmetadata_schema: Either a dictionary or pydantic.BaseModel class. If a dictionaryis passed in, it\u2019s assumed to already be a valid JsonSchema.\nFor best results, pydantic.BaseModels should have docstrings describing what\nthe schema represents and descriptions for the parameters.\nllm: Language model to use, assumed to support the OpenAI function-calling API.Defaults to use \u201cgpt-3.5-turbo-0613\u201d\nprompt: BasePromptTemplate to pass to the model.\nReturns:An LLMChain that will pass the given function to the model.\nExample:from langchain.chat_models import ChatOpenAI\nfrom langchain.document_transformers import create_metadata_tagger\nfrom langchain.schema import Document\nschema = {\n    \"properties\": {\n        \"movie_title\": { \"type\": \"string\" },\n        \"critic\": { \"type\": \"string\" },\n        \"tone\": {\n            \"type\": \"string\",\n            \"enum\": [\"positive\", \"negative\"]\n        },\n        \"rating\": {\n            \"type\": \"integer\",\n            \"description\": \"The number of stars the critic rated the movie\"\n        }\n    },\n    \"required\": [\"movie_title\", \"critic\", \"tone\"]\n}\n# Must be an OpenAI model that supports functions", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.openai_functions.create_metadata_tagger.html"}
{"id": "a1d795b26b6b-1", "text": "}\n# Must be an OpenAI model that supports functions\nllm = ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-0613\")\ndocument_transformer = create_metadata_tagger(schema, llm)\noriginal_documents = [\n    Document(page_content=\"Review of The Bee Movie\nBy Roger Ebert\nThis is the greatest movie ever made. 4 out of 5 stars.\u201d),Document(page_content=\u201dReview of The Godfather\nBy Anonymous\nThis movie was super boring. 1 out of 5 stars.\u201d, metadata={\u201creliable\u201d: False}),]\nenhanced_documents = document_transformer.transform_documents(original_documents)\nExamples using create_metadata_tagger\u00b6\nOpenAI Functions Metadata Tagger", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.openai_functions.create_metadata_tagger.html"}
{"id": "0e49691eb9bc-0", "text": "langchain.document_transformers.google_translate.GoogleTranslateTransformer\u00b6\nclass langchain.document_transformers.google_translate.GoogleTranslateTransformer(project_id: str, *, location: str = 'global', model_id: Optional[str] = None, glossary_id: Optional[str] = None, api_endpoint: Optional[str] = None)[source]\u00b6\nTranslate text documents using Google Cloud Translation.\nParameters\nproject_id \u2013 Google Cloud Project ID.\nlocation \u2013 (Optional) Translate model location.\nmodel_id \u2013 (Optional) Translate model ID to use.\nglossary_id \u2013 (Optional) Translate glossary ID to use.\napi_endpoint \u2013 (Optional) Regional endpoint to use.\nMethods\n__init__(project_id,\u00a0*[,\u00a0location,\u00a0...])\nparam project_id\nGoogle Cloud Project ID.\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a list of documents.\ntransform_documents(documents,\u00a0**kwargs)\nTranslate text documents using Google Translate.\n__init__(project_id: str, *, location: str = 'global', model_id: Optional[str] = None, glossary_id: Optional[str] = None, api_endpoint: Optional[str] = None) \u2192 None[source]\u00b6\nParameters\nproject_id \u2013 Google Cloud Project ID.\nlocation \u2013 (Optional) Translate model location.\nmodel_id \u2013 (Optional) Translate model ID to use.\nglossary_id \u2013 (Optional) Translate glossary ID to use.\napi_endpoint \u2013 (Optional) Regional endpoint to use.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nAsynchronously transform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.google_translate.GoogleTranslateTransformer.html"}
{"id": "0e49691eb9bc-1", "text": "Translate text documents using Google Translate.\nParameters\nsource_language_code \u2013 ISO 639 language code of the input document.\ntarget_language_code \u2013 ISO 639 language code of the output document.\nFor supported languages, refer to:\nhttps://cloud.google.com/translate/docs/languages\nmime_type \u2013 (Optional) Media Type of input text.\nOptions: text/plain, text/html\nExamples using GoogleTranslateTransformer\u00b6\nGoogle Cloud Translation", "source": "lang/api.python.langchain.com/en/latest/document_transformers/langchain.document_transformers.google_translate.GoogleTranslateTransformer.html"}
{"id": "d18638b0af75-0", "text": "langchain.memory.readonly.ReadOnlySharedMemory\u00b6\nclass langchain.memory.readonly.ReadOnlySharedMemory[source]\u00b6\nBases: BaseMemory\nA memory wrapper that is read-only and cannot be changed.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam memory: langchain.schema.memory.BaseMemory [Required]\u00b6\nclear() \u2192 None[source]\u00b6\nNothing to clear, got a memory like a vault.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.readonly.ReadOnlySharedMemory.html"}
{"id": "d18638b0af75-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.readonly.ReadOnlySharedMemory.html"}
{"id": "d18638b0af75-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, str][source]\u00b6\nLoad memory variables from memory.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None[source]\u00b6\nNothing should be saved or changed\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty memory_variables: List[str]\u00b6\nReturn memory variables.\nExamples using ReadOnlySharedMemory\u00b6\nShared memory across agents and tools", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.readonly.ReadOnlySharedMemory.html"}
{"id": "cfc736f8d91a-0", "text": "langchain.memory.motorhead_memory.MotorheadMemory\u00b6\nclass langchain.memory.motorhead_memory.MotorheadMemory[source]\u00b6\nBases: BaseChatMemory\nChat message memory backed by Motorhead service.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_key: Optional[str] = None\u00b6\nparam chat_memory: BaseChatMessageHistory [Optional]\u00b6\nparam client_id: Optional[str] = None\u00b6\nparam context: Optional[str] = None\u00b6\nparam input_key: Optional[str] = None\u00b6\nparam memory_key: str = 'history'\u00b6\nparam output_key: Optional[str] = None\u00b6\nparam return_messages: bool = False\u00b6\nparam session_id: str [Required]\u00b6\nparam timeout: int = 3000\u00b6\nparam url: str = 'https://api.getmetal.io/v1/motorhead'\u00b6\nclear() \u2192 None\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.motorhead_memory.MotorheadMemory.html"}
{"id": "cfc736f8d91a-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndelete_session() \u2192 None[source]\u00b6\nDelete a session\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nasync init() \u2192 None[source]\u00b6\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.motorhead_memory.MotorheadMemory.html"}
{"id": "cfc736f8d91a-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(values: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nReturn key-value pairs given the text input to the chain.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None[source]\u00b6\nSave context from this conversation to buffer.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.motorhead_memory.MotorheadMemory.html"}
{"id": "cfc736f8d91a-3", "text": "These attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty memory_variables: List[str]\u00b6\nThe string keys this memory class will add to chain inputs.\nExamples using MotorheadMemory\u00b6\nMot\u00f6rhead Memory\nMot\u00f6rhead Memory (Managed)", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.motorhead_memory.MotorheadMemory.html"}
{"id": "d5e8156166b4-0", "text": "langchain.memory.chat_message_histories.cosmos_db.CosmosDBChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.cosmos_db.CosmosDBChatMessageHistory(cosmos_endpoint: str, cosmos_database: str, cosmos_container: str, session_id: str, user_id: str, credential: Any = None, connection_string: Optional[str] = None, ttl: Optional[int] = None, cosmos_client_kwargs: Optional[dict] = None)[source]\u00b6\nChat message history backed by Azure CosmosDB.\nInitializes a new instance of the CosmosDBChatMessageHistory class.\nMake sure to call prepare_cosmos or use the context manager to make\nsure your database is ready.\nEither a credential or a connection string must be provided.\nParameters\ncosmos_endpoint \u2013 The connection endpoint for the Azure Cosmos DB account.\ncosmos_database \u2013 The name of the database to use.\ncosmos_container \u2013 The name of the container to use.\nsession_id \u2013 The session ID to use, can be overwritten while loading.\nuser_id \u2013 The user ID to use, can be overwritten while loading.\ncredential \u2013 The credential to use to authenticate to Azure Cosmos DB.\nconnection_string \u2013 The connection string to use to authenticate.\nttl \u2013 The time to live (in seconds) to use for documents in the container.\ncosmos_client_kwargs \u2013 Additional kwargs to pass to the CosmosClient.\nAttributes\nmessages\nA list of Messages stored in-memory.\nMethods\n__init__(cosmos_endpoint,\u00a0cosmos_database,\u00a0...)\nInitializes a new instance of the CosmosDBChatMessageHistory class.\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAdd a self-created message to the store\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.cosmos_db.CosmosDBChatMessageHistory.html"}
{"id": "d5e8156166b4-1", "text": "Convenience method for adding a human message string to the store.\nclear()\nClear session memory from this memory and cosmos.\nload_messages()\nRetrieve the messages from Cosmos\nprepare_cosmos()\nPrepare the CosmosDB client.\nupsert_messages()\nUpdate the cosmosdb item.\n__init__(cosmos_endpoint: str, cosmos_database: str, cosmos_container: str, session_id: str, user_id: str, credential: Any = None, connection_string: Optional[str] = None, ttl: Optional[int] = None, cosmos_client_kwargs: Optional[dict] = None)[source]\u00b6\nInitializes a new instance of the CosmosDBChatMessageHistory class.\nMake sure to call prepare_cosmos or use the context manager to make\nsure your database is ready.\nEither a credential or a connection string must be provided.\nParameters\ncosmos_endpoint \u2013 The connection endpoint for the Azure Cosmos DB account.\ncosmos_database \u2013 The name of the database to use.\ncosmos_container \u2013 The name of the container to use.\nsession_id \u2013 The session ID to use, can be overwritten while loading.\nuser_id \u2013 The user ID to use, can be overwritten while loading.\ncredential \u2013 The credential to use to authenticate to Azure Cosmos DB.\nconnection_string \u2013 The connection string to use to authenticate.\nttl \u2013 The time to live (in seconds) to use for documents in the container.\ncosmos_client_kwargs \u2013 Additional kwargs to pass to the CosmosClient.\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAdd a self-created message to the store\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.cosmos_db.CosmosDBChatMessageHistory.html"}
{"id": "d5e8156166b4-2", "text": "Convenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory from this memory and cosmos.\nload_messages() \u2192 None[source]\u00b6\nRetrieve the messages from Cosmos\nprepare_cosmos() \u2192 None[source]\u00b6\nPrepare the CosmosDB client.\nUse this function or the context manager to make sure your database is ready.\nupsert_messages() \u2192 None[source]\u00b6\nUpdate the cosmosdb item.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.cosmos_db.CosmosDBChatMessageHistory.html"}
{"id": "bcbdad36fc58-0", "text": "langchain.memory.buffer_window.ConversationBufferWindowMemory\u00b6\nclass langchain.memory.buffer_window.ConversationBufferWindowMemory[source]\u00b6\nBases: BaseChatMemory\nBuffer for storing conversation memory inside a limited size window.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_prefix: str = 'AI'\u00b6\nparam chat_memory: BaseChatMessageHistory [Optional]\u00b6\nparam human_prefix: str = 'Human'\u00b6\nparam input_key: Optional[str] = None\u00b6\nparam k: int = 5\u00b6\nNumber of messages to store in buffer.\nparam output_key: Optional[str] = None\u00b6\nparam return_messages: bool = False\u00b6\nclear() \u2192 None\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.buffer_window.ConversationBufferWindowMemory.html"}
{"id": "bcbdad36fc58-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.buffer_window.ConversationBufferWindowMemory.html"}
{"id": "bcbdad36fc58-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nReturn history buffer.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None\u00b6\nSave context from this conversation to buffer.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty buffer: Union[str, List[langchain.schema.messages.BaseMessage]]\u00b6\nString buffer of memory.\nproperty buffer_as_messages: List[langchain.schema.messages.BaseMessage]\u00b6\nExposes the buffer as a list of messages in case return_messages is False.\nproperty buffer_as_str: str\u00b6\nExposes the buffer as a string in case return_messages is True.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.buffer_window.ConversationBufferWindowMemory.html"}
{"id": "bcbdad36fc58-3", "text": "List of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using ConversationBufferWindowMemory\u00b6\nFigma\nOpaquePrompts\nSet env var OPENAI_API_KEY or load from a .env file:\nMeta-Prompt\nCreate ChatGPT clone", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.buffer_window.ConversationBufferWindowMemory.html"}
{"id": "b4ef72c35814-0", "text": "langchain.memory.chat_message_histories.firestore.FirestoreChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.firestore.FirestoreChatMessageHistory(collection_name: str, session_id: str, user_id: str, firestore_client: Optional[Client] = None)[source]\u00b6\nChat message history backed by Google Firestore.\nInitialize a new instance of the FirestoreChatMessageHistory class.\nParameters\ncollection_name \u2013 The name of the collection to use.\nsession_id \u2013 The session ID for the chat..\nuser_id \u2013 The user ID for the chat.\nAttributes\nmessages\nA list of Messages stored in-memory.\nMethods\n__init__(collection_name,\u00a0session_id,\u00a0user_id)\nInitialize a new instance of the FirestoreChatMessageHistory class.\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAdd a Message object to the store.\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory from this memory and Firestore.\nload_messages()\nRetrieve the messages from Firestore\nprepare_firestore()\nPrepare the Firestore client.\nupsert_messages([new_message])\nUpdate the Firestore document.\n__init__(collection_name: str, session_id: str, user_id: str, firestore_client: Optional[Client] = None)[source]\u00b6\nInitialize a new instance of the FirestoreChatMessageHistory class.\nParameters\ncollection_name \u2013 The name of the collection to use.\nsession_id \u2013 The session ID for the chat..\nuser_id \u2013 The user ID for the chat.\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAdd a Message object to the store.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.firestore.FirestoreChatMessageHistory.html"}
{"id": "b4ef72c35814-1", "text": "Add a Message object to the store.\nParameters\nmessage \u2013 A BaseMessage object to store.\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory from this memory and Firestore.\nload_messages() \u2192 None[source]\u00b6\nRetrieve the messages from Firestore\nprepare_firestore() \u2192 None[source]\u00b6\nPrepare the Firestore client.\nUse this function to make sure your database is ready.\nupsert_messages(new_message: Optional[BaseMessage] = None) \u2192 None[source]\u00b6\nUpdate the Firestore document.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.firestore.FirestoreChatMessageHistory.html"}
{"id": "5562c58242ae-0", "text": "langchain.memory.entity.InMemoryEntityStore\u00b6\nclass langchain.memory.entity.InMemoryEntityStore[source]\u00b6\nBases: BaseEntityStore\nIn-memory Entity store.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam store: Dict[str, Optional[str]] = {}\u00b6\nclear() \u2192 None[source]\u00b6\nDelete all entities from store.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndelete(key: str) \u2192 None[source]\u00b6\nDelete entity value from store.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.InMemoryEntityStore.html"}
{"id": "5562c58242ae-1", "text": "delete(key: str) \u2192 None[source]\u00b6\nDelete entity value from store.\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nexists(key: str) \u2192 bool[source]\u00b6\nCheck if entity exists in store.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget(key: str, default: Optional[str] = None) \u2192 Optional[str][source]\u00b6\nGet entity value from store.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.InMemoryEntityStore.html"}
{"id": "5562c58242ae-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nset(key: str, value: Optional[str]) \u2192 None[source]\u00b6\nSet entity value in store.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.InMemoryEntityStore.html"}
{"id": "103ab843c0a1-0", "text": "langchain.memory.chat_message_histories.sql.DefaultMessageConverter\u00b6\nclass langchain.memory.chat_message_histories.sql.DefaultMessageConverter(table_name: str)[source]\u00b6\nThe default message converter for SQLChatMessageHistory.\nMethods\n__init__(table_name)\nfrom_sql_model(sql_message)\nConvert a SQLAlchemy model to a BaseMessage instance.\nget_sql_model_class()\nGet the SQLAlchemy model class.\nto_sql_model(message,\u00a0session_id)\nConvert a BaseMessage instance to a SQLAlchemy model.\n__init__(table_name: str)[source]\u00b6\nfrom_sql_model(sql_message: Any) \u2192 BaseMessage[source]\u00b6\nConvert a SQLAlchemy model to a BaseMessage instance.\nget_sql_model_class() \u2192 Any[source]\u00b6\nGet the SQLAlchemy model class.\nto_sql_model(message: BaseMessage, session_id: str) \u2192 Any[source]\u00b6\nConvert a BaseMessage instance to a SQLAlchemy model.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.sql.DefaultMessageConverter.html"}
{"id": "bd28147facf7-0", "text": "langchain.memory.token_buffer.ConversationTokenBufferMemory\u00b6\nclass langchain.memory.token_buffer.ConversationTokenBufferMemory[source]\u00b6\nBases: BaseChatMemory\nConversation chat memory with token limit.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_prefix: str = 'AI'\u00b6\nparam chat_memory: BaseChatMessageHistory [Optional]\u00b6\nparam human_prefix: str = 'Human'\u00b6\nparam input_key: Optional[str] = None\u00b6\nparam llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nparam max_token_limit: int = 2000\u00b6\nparam memory_key: str = 'history'\u00b6\nparam output_key: Optional[str] = None\u00b6\nparam return_messages: bool = False\u00b6\nclear() \u2192 None\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.token_buffer.ConversationTokenBufferMemory.html"}
{"id": "bd28147facf7-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.token_buffer.ConversationTokenBufferMemory.html"}
{"id": "bd28147facf7-2", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nReturn history buffer.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None[source]\u00b6\nSave context from this conversation to buffer. Pruned.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty buffer: Any\u00b6\nString buffer of memory.\nproperty buffer_as_messages: List[langchain.schema.messages.BaseMessage]\u00b6\nExposes the buffer as a list of messages in case return_messages is True.\nproperty buffer_as_str: str\u00b6\nExposes the buffer as a string in case return_messages is False.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.token_buffer.ConversationTokenBufferMemory.html"}
{"id": "bd28147facf7-3", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using ConversationTokenBufferMemory\u00b6\nConversation Token Buffer", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.token_buffer.ConversationTokenBufferMemory.html"}
{"id": "1d0c0ff2c05d-0", "text": "langchain.memory.chat_message_histories.momento.MomentoChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.momento.MomentoChatMessageHistory(session_id: str, cache_client: momento.CacheClient, cache_name: str, *, key_prefix: str = 'message_store:', ttl: Optional[timedelta] = None, ensure_cache_exists: bool = True)[source]\u00b6\nChat message history cache that uses Momento as a backend.\nSee https://gomomento.com/\nInstantiate a chat message history cache that uses Momento as a backend.\nNote: to instantiate the cache client passed to MomentoChatMessageHistory,\nyou must have a Momento account at https://gomomento.com/.\nParameters\nsession_id (str) \u2013 The session ID to use for this chat session.\ncache_client (CacheClient) \u2013 The Momento cache client.\ncache_name (str) \u2013 The name of the cache to use to store the messages.\nkey_prefix (str, optional) \u2013 The prefix to apply to the cache key.\nDefaults to \u201cmessage_store:\u201d.\nttl (Optional[timedelta], optional) \u2013 The TTL to use for the messages.\nDefaults to None, ie the default TTL of the cache will be used.\nensure_cache_exists (bool, optional) \u2013 Create the cache if it doesn\u2019t exist.\nDefaults to True.\nRaises\nImportError \u2013 Momento python package is not installed.\nTypeError \u2013 cache_client is not of type momento.CacheClientObject\nAttributes\nmessages\nRetrieve the messages from Momento.\nMethods\n__init__(session_id,\u00a0cache_client,\u00a0cache_name,\u00a0*)\nInstantiate a chat message history cache that uses Momento as a backend.\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nStore a message in the cache.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.momento.MomentoChatMessageHistory.html"}
{"id": "1d0c0ff2c05d-1", "text": "add_message(message)\nStore a message in the cache.\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nRemove the session's messages from the cache.\nfrom_client_params(session_id,\u00a0cache_name,\u00a0...)\nConstruct cache from CacheClient parameters.\n__init__(session_id: str, cache_client: momento.CacheClient, cache_name: str, *, key_prefix: str = 'message_store:', ttl: Optional[timedelta] = None, ensure_cache_exists: bool = True)[source]\u00b6\nInstantiate a chat message history cache that uses Momento as a backend.\nNote: to instantiate the cache client passed to MomentoChatMessageHistory,\nyou must have a Momento account at https://gomomento.com/.\nParameters\nsession_id (str) \u2013 The session ID to use for this chat session.\ncache_client (CacheClient) \u2013 The Momento cache client.\ncache_name (str) \u2013 The name of the cache to use to store the messages.\nkey_prefix (str, optional) \u2013 The prefix to apply to the cache key.\nDefaults to \u201cmessage_store:\u201d.\nttl (Optional[timedelta], optional) \u2013 The TTL to use for the messages.\nDefaults to None, ie the default TTL of the cache will be used.\nensure_cache_exists (bool, optional) \u2013 Create the cache if it doesn\u2019t exist.\nDefaults to True.\nRaises\nImportError \u2013 Momento python package is not installed.\nTypeError \u2013 cache_client is not of type momento.CacheClientObject\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nStore a message in the cache.\nParameters", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.momento.MomentoChatMessageHistory.html"}
{"id": "1d0c0ff2c05d-2", "text": "Store a message in the cache.\nParameters\nmessage (BaseMessage) \u2013 The message object to store.\nRaises\nSdkException \u2013 Momento service or network error.\nException \u2013 Unexpected response.\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nRemove the session\u2019s messages from the cache.\nRaises\nSdkException \u2013 Momento service or network error.\nException \u2013 Unexpected response.\nclassmethod from_client_params(session_id: str, cache_name: str, ttl: timedelta, *, configuration: Optional[momento.config.Configuration] = None, api_key: Optional[str] = None, auth_token: Optional[str] = None, **kwargs: Any) \u2192 MomentoChatMessageHistory[source]\u00b6\nConstruct cache from CacheClient parameters.\nExamples using MomentoChatMessageHistory\u00b6\nMomento Chat Message History", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.momento.MomentoChatMessageHistory.html"}
{"id": "242dd485aacb-0", "text": "langchain.memory.chat_message_histories.sql.SQLChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.sql.SQLChatMessageHistory(session_id: str, connection_string: str, table_name: str = 'message_store', session_id_field_name: str = 'session_id', custom_message_converter: Optional[BaseMessageConverter] = None)[source]\u00b6\nChat message history stored in an SQL database.\nAttributes\nmessages\nRetrieve all messages from db\nMethods\n__init__(session_id,\u00a0connection_string[,\u00a0...])\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAppend the message to the record in db\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory from db\n__init__(session_id: str, connection_string: str, table_name: str = 'message_store', session_id_field_name: str = 'session_id', custom_message_converter: Optional[BaseMessageConverter] = None)[source]\u00b6\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAppend the message to the record in db\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory from db\nExamples using SQLChatMessageHistory\u00b6\nSQL Chat Message History", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.sql.SQLChatMessageHistory.html"}
{"id": "23a4091f4d21-0", "text": "langchain.memory.chat_message_histories.zep.ZepChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.zep.ZepChatMessageHistory(session_id: str, url: str = 'http://localhost:8000', api_key: Optional[str] = None)[source]\u00b6\nChat message history that uses Zep as a backend.\nRecommended usage:\n# Set up Zep Chat History\nzep_chat_history = ZepChatMessageHistory(\n    session_id=session_id,\n    url=ZEP_API_URL,\n    api_key=<your_api_key>,\n)\n# Use a standard ConversationBufferMemory to encapsulate the Zep chat history\nmemory = ConversationBufferMemory(\n    memory_key=\"chat_history\", chat_memory=zep_chat_history\n)\nZep provides long-term conversation storage for LLM apps. The server stores,\nsummarizes, embeds, indexes, and enriches conversational AI chat\nhistories, and exposes them via simple, low-latency APIs.\nFor server installation instructions and more, see:\nhttps://docs.getzep.com/deployment/quickstart/\nThis class is a thin wrapper around the zep-python package. Additional\nZep functionality is exposed via the zep_summary and zep_messages\nproperties.\nFor more information on the zep-python package, see:\nhttps://github.com/getzep/zep-python\nAttributes\nmessages\nRetrieve messages from Zep memory\nzep_messages\nRetrieve summary from Zep memory\nzep_summary\nRetrieve summary from Zep memory\nMethods\n__init__(session_id[,\u00a0url,\u00a0api_key])\nadd_ai_message(message[,\u00a0metadata])\nConvenience method for adding an AI message string to the store.\nadd_message(message[,\u00a0metadata])\nAppend the message to the Zep memory history\nadd_user_message(message[,\u00a0metadata])", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.zep.ZepChatMessageHistory.html"}
{"id": "23a4091f4d21-1", "text": "Append the message to the Zep memory history\nadd_user_message(message[,\u00a0metadata])\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory from Zep.\nsearch(query[,\u00a0metadata,\u00a0limit])\nSearch Zep memory for messages matching the query\n__init__(session_id: str, url: str = 'http://localhost:8000', api_key: Optional[str] = None) \u2192 None[source]\u00b6\nadd_ai_message(message: str, metadata: Optional[Dict[str, Any]] = None) \u2192 None[source]\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nmetadata \u2013 Optional metadata to attach to the message.\nadd_message(message: BaseMessage, metadata: Optional[Dict[str, Any]] = None) \u2192 None[source]\u00b6\nAppend the message to the Zep memory history\nadd_user_message(message: str, metadata: Optional[Dict[str, Any]] = None) \u2192 None[source]\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nmetadata \u2013 Optional metadata to attach to the message.\nclear() \u2192 None[source]\u00b6\nClear session memory from Zep. Note that Zep is long-term storage for memory\nand this is not advised unless you have specific data retention requirements.\nsearch(query: str, metadata: Optional[Dict] = None, limit: Optional[int] = None) \u2192 List[MemorySearchResult][source]\u00b6\nSearch Zep memory for messages matching the query", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.zep.ZepChatMessageHistory.html"}
{"id": "892b007925a2-0", "text": "langchain.memory.chat_message_histories.postgres.PostgresChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.postgres.PostgresChatMessageHistory(session_id: str, connection_string: str = 'postgresql://postgres:mypassword@localhost/chat_history', table_name: str = 'message_store')[source]\u00b6\nChat message history stored in a Postgres database.\nAttributes\nmessages\nRetrieve the messages from PostgreSQL\nMethods\n__init__(session_id[,\u00a0connection_string,\u00a0...])\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAppend the message to the record in PostgreSQL\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory from PostgreSQL\n__init__(session_id: str, connection_string: str = 'postgresql://postgres:mypassword@localhost/chat_history', table_name: str = 'message_store')[source]\u00b6\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAppend the message to the record in PostgreSQL\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory from PostgreSQL\nExamples using PostgresChatMessageHistory\u00b6\nPostgres Chat Message History", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.postgres.PostgresChatMessageHistory.html"}
{"id": "93c753639227-0", "text": "langchain.memory.summary_buffer.ConversationSummaryBufferMemory\u00b6\nclass langchain.memory.summary_buffer.ConversationSummaryBufferMemory[source]\u00b6\nBases: BaseChatMemory, SummarizerMixin\nBuffer with summarizer for storing conversation memory.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_prefix: str = 'AI'\u00b6\nparam chat_memory: BaseChatMessageHistory [Optional]\u00b6\nparam human_prefix: str = 'Human'\u00b6\nparam input_key: Optional[str] = None\u00b6\nparam llm: BaseLanguageModel [Required]\u00b6\nparam max_token_limit: int = 2000\u00b6\nparam memory_key: str = 'history'\u00b6\nparam moving_summary_buffer: str = ''\u00b6\nparam output_key: Optional[str] = None\u00b6\nparam prompt: BasePromptTemplate = PromptTemplate(input_variables=['new_lines', 'summary'], template='Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\\n\\nEXAMPLE\\nCurrent summary:\\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\\n\\nNew lines of conversation:\\nHuman: Why do you think artificial intelligence is a force for good?\\nAI: Because artificial intelligence will help humans reach their full potential.\\n\\nNew summary:\\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\\nEND OF EXAMPLE\\n\\nCurrent summary:\\n{summary}\\n\\nNew lines of conversation:\\n{new_lines}\\n\\nNew summary:')\u00b6\nparam return_messages: bool = False\u00b6\nparam summary_message_cls: Type[BaseMessage] = <class 'langchain.schema.messages.SystemMessage'>\u00b6\nclear() \u2192 None[source]\u00b6\nClear memory contents.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.summary_buffer.ConversationSummaryBufferMemory.html"}
{"id": "93c753639227-1", "text": "clear() \u2192 None[source]\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.summary_buffer.ConversationSummaryBufferMemory.html"}
{"id": "93c753639227-2", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nReturn history buffer.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict_new_summary(messages: List[BaseMessage], existing_summary: str) \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.summary_buffer.ConversationSummaryBufferMemory.html"}
{"id": "93c753639227-3", "text": "predict_new_summary(messages: List[BaseMessage], existing_summary: str) \u2192 str\u00b6\nprune() \u2192 None[source]\u00b6\nPrune buffer if it exceeds max token limit\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None[source]\u00b6\nSave context from this conversation to buffer.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty buffer: List[langchain.schema.messages.BaseMessage]\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using ConversationSummaryBufferMemory\u00b6\nSet env var OPENAI_API_KEY or load from a .env file:\nConversation Summary Buffer", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.summary_buffer.ConversationSummaryBufferMemory.html"}
{"id": "b3a201120362-0", "text": "langchain.memory.chat_message_histories.file.FileChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.file.FileChatMessageHistory(file_path: str)[source]\u00b6\nChat message history that stores history in a local file.\nParameters\nfile_path \u2013 path of the local file to store the messages.\nAttributes\nmessages\nRetrieve the messages from the local file\nMethods\n__init__(file_path)\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAppend the message to the record in the local file\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory from the local file\n__init__(file_path: str)[source]\u00b6\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAppend the message to the record in the local file\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory from the local file\nExamples using FileChatMessageHistory\u00b6\nAutoGPT", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.file.FileChatMessageHistory.html"}
{"id": "191011689acb-0", "text": "langchain.memory.chat_message_histories.xata.XataChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.xata.XataChatMessageHistory(session_id: str, db_url: str, api_key: str, branch_name: str = 'main', table_name: str = 'messages', create_table: bool = True)[source]\u00b6\nChat message history stored in a Xata database.\nInitialize with Xata client.\nAttributes\nmessages\nMethods\n__init__(session_id,\u00a0db_url,\u00a0api_key[,\u00a0...])\nInitialize with Xata client.\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAppend the message to the Xata table\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nDelete session from Xata table.\n__init__(session_id: str, db_url: str, api_key: str, branch_name: str = 'main', table_name: str = 'messages', create_table: bool = True) \u2192 None[source]\u00b6\nInitialize with Xata client.\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAppend the message to the Xata table\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nDelete session from Xata table.\nExamples using XataChatMessageHistory\u00b6\nXata chat memory", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.xata.XataChatMessageHistory.html"}
{"id": "56086ef9d707-0", "text": "langchain.memory.entity.RedisEntityStore\u00b6\nclass langchain.memory.entity.RedisEntityStore[source]\u00b6\nBases: BaseEntityStore\nRedis-backed Entity store.\nEntities get a TTL of 1 day by default, and\nthat TTL is extended by 3 days every time the entity is read back.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam key_prefix: str = 'memory_store'\u00b6\nparam recall_ttl: Optional[int] = 259200\u00b6\nparam redis_client: Any = None\u00b6\nparam session_id: str = 'default'\u00b6\nparam ttl: Optional[int] = 86400\u00b6\nclear() \u2192 None[source]\u00b6\nDelete all entities from store.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.RedisEntityStore.html"}
{"id": "56086ef9d707-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndelete(key: str) \u2192 None[source]\u00b6\nDelete entity value from store.\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nexists(key: str) \u2192 bool[source]\u00b6\nCheck if entity exists in store.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget(key: str, default: Optional[str] = None) \u2192 Optional[str][source]\u00b6\nGet entity value from store.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.RedisEntityStore.html"}
{"id": "56086ef9d707-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nset(key: str, value: Optional[str]) \u2192 None[source]\u00b6\nSet entity value in store.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty full_key_prefix: str\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.RedisEntityStore.html"}
{"id": "26c918adaf87-0", "text": "langchain.memory.entity.ConversationEntityMemory\u00b6\nclass langchain.memory.entity.ConversationEntityMemory[source]\u00b6\nBases: BaseChatMemory\nEntity extractor & summarizer memory.\nExtracts named entities from the recent chat history and generates summaries.\nWith a swappable entity store, persisting entities across conversations.\nDefaults to an in-memory entity store, and can be swapped out for a Redis,\nSQLite, or other entity store.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_prefix: str = 'AI'\u00b6\nparam chat_history_key: str = 'history'\u00b6\nparam chat_memory: BaseChatMessageHistory [Optional]\u00b6\nparam entity_cache: List[str] = []\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.ConversationEntityMemory.html"}
{"id": "26c918adaf87-1", "text": "param entity_extraction_prompt: langchain.schema.prompt_template.BasePromptTemplate = PromptTemplate(input_variables=['history', 'input'], template='You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\\n\\nThe conversation history is provided just in case of a coreference (e.g. \"What do you know about him\" where \"him\" is defined in a previous line) -- ignore items mentioned there that are not in the last line.\\n\\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).\\n\\nEXAMPLE\\nConversation history:\\nPerson #1: how\\'s it going today?\\nAI: \"It\\'s going great! How about you?\"\\nPerson #1: good! busy working on Langchain. lots to do.\\nAI: \"That sounds like a lot of work! What kind of things are you doing to make Langchain better?\"\\nLast line:\\nPerson #1: i\\'m trying to improve Langchain\\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\\nOutput: Langchain\\nEND OF EXAMPLE\\n\\nEXAMPLE\\nConversation history:\\nPerson #1: how\\'s it going today?\\nAI: \"It\\'s going great! How about you?\"\\nPerson #1: good! busy working on Langchain. lots to do.\\nAI: \"That sounds like a lot of work! What kind of things are you doing to make Langchain better?\"\\nLast line:\\nPerson #1: i\\'m trying to improve Langchain\\'s interfaces, the UX, its integrations with various products", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.ConversationEntityMemory.html"}
{"id": "26c918adaf87-2", "text": "trying to improve Langchain\\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I\\'m working with Person #2.\\nOutput: Langchain, Person #2\\nEND OF EXAMPLE\\n\\nConversation history (for reference only):\\n{history}\\nLast line of conversation (for extraction):\\nHuman: {input}\\n\\nOutput:')\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.ConversationEntityMemory.html"}
{"id": "26c918adaf87-3", "text": "param entity_store: langchain.memory.entity.BaseEntityStore [Optional]\u00b6\nparam entity_summarization_prompt: langchain.schema.prompt_template.BasePromptTemplate = PromptTemplate(input_variables=['entity', 'history', 'input', 'summary'], template='You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update the summary of the provided entity in the \"Entity\" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.\\nThe update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.\\n\\nIf there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), return the existing summary unchanged.\\n\\nFull conversation history (for context):\\n{history}\\n\\nEntity to summarize:\\n{entity}\\n\\nExisting summary of {entity}:\\n{summary}\\n\\nLast line of conversation:\\nHuman: {input}\\nUpdated summary:')\u00b6\nparam human_prefix: str = 'Human'\u00b6\nparam input_key: Optional[str] = None\u00b6\nparam k: int = 3\u00b6\nparam llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nparam output_key: Optional[str] = None\u00b6\nparam return_messages: bool = False\u00b6\nclear() \u2192 None[source]\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.ConversationEntityMemory.html"}
{"id": "26c918adaf87-4", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.ConversationEntityMemory.html"}
{"id": "26c918adaf87-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nReturns chat history and all generated entities with summaries if available,\nand updates or clears the recent entity cache.\nNew entity name can be found when calling this method, before the entity\nsummaries are generated, so the entity cache values may be empty if no entity\ndescriptions are generated yet.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.ConversationEntityMemory.html"}
{"id": "26c918adaf87-6", "text": "save_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None[source]\u00b6\nSave context from this conversation history to the entity store.\nGenerates a summary for each entity in the entity cache by prompting\nthe model, and saves these summaries to the entity store.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty buffer: List[langchain.schema.messages.BaseMessage]\u00b6\nAccess chat memory messages.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using ConversationEntityMemory\u00b6\nEntity Memory with SQLite storage", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.ConversationEntityMemory.html"}
{"id": "8bb69abe30b1-0", "text": "langchain.memory.entity.UpstashRedisEntityStore\u00b6\nclass langchain.memory.entity.UpstashRedisEntityStore[source]\u00b6\nBases: BaseEntityStore\nUpstash Redis backed Entity store.\nEntities get a TTL of 1 day by default, and\nthat TTL is extended by 3 days every time the entity is read back.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nclear() \u2192 None[source]\u00b6\nDelete all entities from store.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndelete(key: str) \u2192 None[source]\u00b6\nDelete entity value from store.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.UpstashRedisEntityStore.html"}
{"id": "8bb69abe30b1-1", "text": "delete(key: str) \u2192 None[source]\u00b6\nDelete entity value from store.\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nexists(key: str) \u2192 bool[source]\u00b6\nCheck if entity exists in store.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget(key: str, default: Optional[str] = None) \u2192 Optional[str][source]\u00b6\nGet entity value from store.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.UpstashRedisEntityStore.html"}
{"id": "8bb69abe30b1-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nset(key: str, value: Optional[str]) \u2192 None[source]\u00b6\nSet entity value in store.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty full_key_prefix: str\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.UpstashRedisEntityStore.html"}
{"id": "263c5abb87f4-0", "text": "langchain.memory.kg.ConversationKGMemory\u00b6\nclass langchain.memory.kg.ConversationKGMemory[source]\u00b6\nBases: BaseChatMemory\nKnowledge graph conversation memory.\nIntegrates with external knowledge graph to store and retrieve\ninformation about knowledge triples in the conversation.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_prefix: str = 'AI'\u00b6\nparam chat_memory: BaseChatMessageHistory [Optional]\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.kg.ConversationKGMemory.html"}
{"id": "263c5abb87f4-1", "text": "param entity_extraction_prompt: langchain.schema.prompt_template.BasePromptTemplate = PromptTemplate(input_variables=['history', 'input'], template='You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\\n\\nThe conversation history is provided just in case of a coreference (e.g. \"What do you know about him\" where \"him\" is defined in a previous line) -- ignore items mentioned there that are not in the last line.\\n\\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).\\n\\nEXAMPLE\\nConversation history:\\nPerson #1: how\\'s it going today?\\nAI: \"It\\'s going great! How about you?\"\\nPerson #1: good! busy working on Langchain. lots to do.\\nAI: \"That sounds like a lot of work! What kind of things are you doing to make Langchain better?\"\\nLast line:\\nPerson #1: i\\'m trying to improve Langchain\\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\\nOutput: Langchain\\nEND OF EXAMPLE\\n\\nEXAMPLE\\nConversation history:\\nPerson #1: how\\'s it going today?\\nAI: \"It\\'s going great! How about you?\"\\nPerson #1: good! busy working on Langchain. lots to do.\\nAI: \"That sounds like a lot of work! What kind of things are you doing to make Langchain better?\"\\nLast line:\\nPerson #1: i\\'m trying to improve Langchain\\'s interfaces, the UX, its integrations with various products", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.kg.ConversationKGMemory.html"}
{"id": "263c5abb87f4-2", "text": "trying to improve Langchain\\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I\\'m working with Person #2.\\nOutput: Langchain, Person #2\\nEND OF EXAMPLE\\n\\nConversation history (for reference only):\\n{history}\\nLast line of conversation (for extraction):\\nHuman: {input}\\n\\nOutput:')\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.kg.ConversationKGMemory.html"}
{"id": "263c5abb87f4-3", "text": "param human_prefix: str = 'Human'\u00b6\nparam input_key: Optional[str] = None\u00b6\nparam k: int = 2\u00b6\nparam kg: langchain.graphs.networkx_graph.NetworkxEntityGraph [Optional]\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.kg.ConversationKGMemory.html"}
{"id": "263c5abb87f4-4", "text": "param knowledge_extraction_prompt: langchain.schema.prompt_template.BasePromptTemplate = PromptTemplate(input_variables=['history', 'input'], template=\"You are a networked intelligence helping a human track knowledge triples about all relevant people, things, concepts, etc. and integrating them with your knowledge stored within your weights as well as that stored in a knowledge graph. Extract all of the knowledge triples from the last line of conversation. A knowledge triple is a clause that contains a subject, a predicate, and an object. The subject is the entity being described, the predicate is the property of the subject that is being described, and the object is the value of the property.\\n\\nEXAMPLE\\nConversation history:\\nPerson #1: Did you hear aliens landed in Area 51?\\nAI: No, I didn't hear that. What do you know about Area 51?\\nPerson #1: It's a secret military base in Nevada.\\nAI: What do you know about Nevada?\\nLast line of conversation:\\nPerson #1: It's a state in the US. It's also the number 1 producer of gold in the US.\\n\\nOutput: (Nevada, is a, state)<|>(Nevada, is in, US)<|>(Nevada, is the number 1 producer of, gold)\\nEND OF EXAMPLE\\n\\nEXAMPLE\\nConversation history:\\nPerson #1: Hello.\\nAI: Hi! How are you?\\nPerson #1: I'm good. How are you?\\nAI: I'm good too.\\nLast line of conversation:\\nPerson #1: I'm going to the store.\\n\\nOutput: NONE\\nEND OF EXAMPLE\\n\\nEXAMPLE\\nConversation history:\\nPerson #1: What do you know about Descartes?\\nAI: Descartes was a French philosopher, mathematician, and scientist who lived in the 17th century.\\nPerson #1: The", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.kg.ConversationKGMemory.html"}
{"id": "263c5abb87f4-5", "text": "mathematician, and scientist who lived in the 17th century.\\nPerson #1: The Descartes I'm referring to is a standup comedian and interior designer from Montreal.\\nAI: Oh yes, He is a comedian and an interior designer. He has been in the industry for 30 years. His favorite food is baked bean pie.\\nLast line of conversation:\\nPerson #1: Oh huh. I know Descartes likes to drive antique scooters and play the mandolin.\\nOutput: (Descartes, likes to drive, antique scooters)<|>(Descartes, plays, mandolin)\\nEND OF EXAMPLE\\n\\nConversation history (for reference only):\\n{history}\\nLast line of conversation (for extraction):\\nHuman: {input}\\n\\nOutput:\")\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.kg.ConversationKGMemory.html"}
{"id": "263c5abb87f4-6", "text": "param llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nparam output_key: Optional[str] = None\u00b6\nparam return_messages: bool = False\u00b6\nparam summary_message_cls: Type[langchain.schema.messages.BaseMessage] = <class 'langchain.schema.messages.SystemMessage'>\u00b6\nNumber of previous utterances to include in the context.\nclear() \u2192 None[source]\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.kg.ConversationKGMemory.html"}
{"id": "263c5abb87f4-7", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_current_entities(input_string: str) \u2192 List[str][source]\u00b6\nget_knowledge_triplets(input_string: str) \u2192 List[KnowledgeTriple][source]\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.kg.ConversationKGMemory.html"}
{"id": "263c5abb87f4-8", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nReturn history buffer.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None[source]\u00b6\nSave context from this conversation to buffer.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using ConversationKGMemory\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.kg.ConversationKGMemory.html"}
{"id": "263c5abb87f4-9", "text": "Examples using ConversationKGMemory\u00b6\nConversation Knowledge Graph", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.kg.ConversationKGMemory.html"}
{"id": "a3040ff311db-0", "text": "langchain.memory.chat_message_histories.sql.create_message_model\u00b6\nlangchain.memory.chat_message_histories.sql.create_message_model(table_name, DynamicBase)[source]\u00b6\nCreate a message model for a given table name.\nParameters\ntable_name \u2013 The name of the table to use.\nDynamicBase \u2013 The base class to use for the model.\nReturns\nThe model class.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.sql.create_message_model.html"}
{"id": "50b4d0afae28-0", "text": "langchain.memory.simple.SimpleMemory\u00b6\nclass langchain.memory.simple.SimpleMemory[source]\u00b6\nBases: BaseMemory\nSimple memory for storing context or other information that shouldn\u2019t\never change between prompts.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam memories: Dict[str, Any] = {}\u00b6\nclear() \u2192 None[source]\u00b6\nNothing to clear, got a memory like a vault.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.simple.SimpleMemory.html"}
{"id": "50b4d0afae28-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.simple.SimpleMemory.html"}
{"id": "50b4d0afae28-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, str][source]\u00b6\nReturn key-value pairs given the text input to the chain.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None[source]\u00b6\nNothing should be saved or changed, my memory is set in stone.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty memory_variables: List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.simple.SimpleMemory.html"}
{"id": "50b4d0afae28-3", "text": "property memory_variables: List[str]\u00b6\nThe string keys this memory class will add to chain inputs.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.simple.SimpleMemory.html"}
{"id": "dcaebc956620-0", "text": "langchain.memory.summary.ConversationSummaryMemory\u00b6\nclass langchain.memory.summary.ConversationSummaryMemory[source]\u00b6\nBases: BaseChatMemory, SummarizerMixin\nConversation summarizer to chat memory.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_prefix: str = 'AI'\u00b6\nparam buffer: str = ''\u00b6\nparam chat_memory: BaseChatMessageHistory [Optional]\u00b6\nparam human_prefix: str = 'Human'\u00b6\nparam input_key: Optional[str] = None\u00b6\nparam llm: BaseLanguageModel [Required]\u00b6\nparam output_key: Optional[str] = None\u00b6\nparam prompt: BasePromptTemplate = PromptTemplate(input_variables=['new_lines', 'summary'], template='Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\\n\\nEXAMPLE\\nCurrent summary:\\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\\n\\nNew lines of conversation:\\nHuman: Why do you think artificial intelligence is a force for good?\\nAI: Because artificial intelligence will help humans reach their full potential.\\n\\nNew summary:\\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\\nEND OF EXAMPLE\\n\\nCurrent summary:\\n{summary}\\n\\nNew lines of conversation:\\n{new_lines}\\n\\nNew summary:')\u00b6\nparam return_messages: bool = False\u00b6\nparam summary_message_cls: Type[BaseMessage] = <class 'langchain.schema.messages.SystemMessage'>\u00b6\nclear() \u2192 None[source]\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.summary.ConversationSummaryMemory.html"}
{"id": "dcaebc956620-1", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_messages(llm: BaseLanguageModel, chat_memory: BaseChatMessageHistory, *, summarize_step: int = 2, **kwargs: Any) \u2192 ConversationSummaryMemory[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.summary.ConversationSummaryMemory.html"}
{"id": "dcaebc956620-2", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nReturn history buffer.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict_new_summary(messages: List[BaseMessage], existing_summary: str) \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.summary.ConversationSummaryMemory.html"}
{"id": "dcaebc956620-3", "text": "predict_new_summary(messages: List[BaseMessage], existing_summary: str) \u2192 str\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None[source]\u00b6\nSave context from this conversation to buffer.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using ConversationSummaryMemory\u00b6\nSet env var OPENAI_API_KEY or load from a .env file:\nSet env var OPENAI_API_KEY or load from a .env file\nMultiple Memory classes", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.summary.ConversationSummaryMemory.html"}
{"id": "56a0230f443a-0", "text": "langchain.memory.combined.CombinedMemory\u00b6\nclass langchain.memory.combined.CombinedMemory[source]\u00b6\nBases: BaseMemory\nCombining multiple memories\u2019 data together.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam memories: List[langchain.schema.memory.BaseMemory] [Required]\u00b6\nFor tracking all the memories that should be accessed.\nclear() \u2192 None[source]\u00b6\nClear context from this session for every memory.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.combined.CombinedMemory.html"}
{"id": "56a0230f443a-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.combined.CombinedMemory.html"}
{"id": "56a0230f443a-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, str][source]\u00b6\nLoad all vars from sub-memories.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None[source]\u00b6\nSave context from this session for every memory.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty memory_variables: List[str]\u00b6\nAll the memory variables that this instance provides.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.combined.CombinedMemory.html"}
{"id": "56a0230f443a-3", "text": "property memory_variables: List[str]\u00b6\nAll the memory variables that this instance provides.\nExamples using CombinedMemory\u00b6\nZep\nMultiple Memory classes", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.combined.CombinedMemory.html"}
{"id": "40c4a6cd41a4-0", "text": "langchain.memory.buffer.ConversationStringBufferMemory\u00b6\nclass langchain.memory.buffer.ConversationStringBufferMemory[source]\u00b6\nBases: BaseMemory\nBuffer for storing conversation memory.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_prefix: str = 'AI'\u00b6\nPrefix to use for AI generated responses.\nparam buffer: str = ''\u00b6\nparam human_prefix: str = 'Human'\u00b6\nparam input_key: Optional[str] = None\u00b6\nparam output_key: Optional[str] = None\u00b6\nclear() \u2192 None[source]\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.buffer.ConversationStringBufferMemory.html"}
{"id": "40c4a6cd41a4-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.buffer.ConversationStringBufferMemory.html"}
{"id": "40c4a6cd41a4-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, str][source]\u00b6\nReturn history buffer.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None[source]\u00b6\nSave context from this conversation to buffer.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty memory_variables: List[str]\u00b6\nWill always return list of memory variables.\n:meta private:", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.buffer.ConversationStringBufferMemory.html"}
{"id": "c3d25425ca21-0", "text": "langchain.memory.chat_message_histories.in_memory.ChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.in_memory.ChatMessageHistory[source]\u00b6\nBases: BaseChatMessageHistory, BaseModel\nIn memory implementation of chat message history.\nStores messages in an in memory list.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam messages: List[langchain.schema.messages.BaseMessage] [Optional]\u00b6\nA list of Messages stored in-memory.\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAdd a self-created message to the store\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nRemove all messages from the store\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.in_memory.ChatMessageHistory.html"}
{"id": "c3d25425ca21-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.in_memory.ChatMessageHistory.html"}
{"id": "c3d25425ca21-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using ChatMessageHistory\u00b6\nMessage Memory in Agent backed by a database", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.in_memory.ChatMessageHistory.html"}
{"id": "a71e242b31cf-0", "text": "langchain.memory.chat_message_histories.upstash_redis.UpstashRedisChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.upstash_redis.UpstashRedisChatMessageHistory(session_id: str, url: str = '', token: str = '', key_prefix: str = 'message_store:', ttl: Optional[int] = None)[source]\u00b6\nChat message history stored in an Upstash Redis database.\nAttributes\nkey\nConstruct the record key to use\nmessages\nRetrieve the messages from Upstash Redis\nMethods\n__init__(session_id[,\u00a0url,\u00a0token,\u00a0...])\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAppend the message to the record in Upstash Redis\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory from Upstash Redis\n__init__(session_id: str, url: str = '', token: str = '', key_prefix: str = 'message_store:', ttl: Optional[int] = None)[source]\u00b6\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAppend the message to the record in Upstash Redis\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory from Upstash Redis", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.upstash_redis.UpstashRedisChatMessageHistory.html"}
{"id": "185194f3a878-0", "text": "langchain.memory.utils.get_prompt_input_key\u00b6\nlangchain.memory.utils.get_prompt_input_key(inputs: Dict[str, Any], memory_variables: List[str]) \u2192 str[source]\u00b6\nGet the prompt input key.\nParameters\ninputs \u2013 Dict[str, Any]\nmemory_variables \u2013 List[str]\nReturns\nA prompt input key.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.utils.get_prompt_input_key.html"}
{"id": "2137820817f9-0", "text": "langchain.memory.entity.BaseEntityStore\u00b6\nclass langchain.memory.entity.BaseEntityStore[source]\u00b6\nBases: BaseModel, ABC\nAbstract base class for Entity store.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nabstract clear() \u2192 None[source]\u00b6\nDelete all entities from store.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nabstract delete(key: str) \u2192 None[source]\u00b6\nDelete entity value from store.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.BaseEntityStore.html"}
{"id": "2137820817f9-1", "text": "abstract delete(key: str) \u2192 None[source]\u00b6\nDelete entity value from store.\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nabstract exists(key: str) \u2192 bool[source]\u00b6\nCheck if entity exists in store.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nabstract get(key: str, default: Optional[str] = None) \u2192 Optional[str][source]\u00b6\nGet entity value from store.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.BaseEntityStore.html"}
{"id": "2137820817f9-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nabstract set(key: str, value: Optional[str]) \u2192 None[source]\u00b6\nSet entity value in store.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.BaseEntityStore.html"}
{"id": "f3fc0ffa1d98-0", "text": "langchain.memory.entity.SQLiteEntityStore\u00b6\nclass langchain.memory.entity.SQLiteEntityStore[source]\u00b6\nBases: BaseEntityStore\nSQLite-backed Entity store\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam session_id: str = 'default'\u00b6\nparam table_name: str = 'memory_store'\u00b6\nclear() \u2192 None[source]\u00b6\nDelete all entities from store.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndelete(key: str) \u2192 None[source]\u00b6\nDelete entity value from store.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.SQLiteEntityStore.html"}
{"id": "f3fc0ffa1d98-1", "text": "delete(key: str) \u2192 None[source]\u00b6\nDelete entity value from store.\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nexists(key: str) \u2192 bool[source]\u00b6\nCheck if entity exists in store.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget(key: str, default: Optional[str] = None) \u2192 Optional[str][source]\u00b6\nGet entity value from store.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.SQLiteEntityStore.html"}
{"id": "f3fc0ffa1d98-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nset(key: str, value: Optional[str]) \u2192 None[source]\u00b6\nSet entity value in store.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty full_table_name: str\u00b6\nExamples using SQLiteEntityStore\u00b6\nEntity Memory with SQLite storage", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.entity.SQLiteEntityStore.html"}
{"id": "13914ff4e577-0", "text": "langchain.memory.chat_message_histories.cassandra.CassandraChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.cassandra.CassandraChatMessageHistory(session_id: str, session: Session, keyspace: str, table_name: str = 'message_store', ttl_seconds: Optional[int] = None)[source]\u00b6\nChat message history that stores history in Cassandra.\nParameters\nsession_id \u2013 arbitrary key that is used to store the messages\nof a single chat session.\nsession \u2013 a Cassandra Session object (an open DB connection)\nkeyspace \u2013 name of the keyspace to use.\ntable_name \u2013 name of the table to use.\nttl_seconds \u2013 time-to-live (seconds) for automatic expiration\nof stored entries. None (default) for no expiration.\nAttributes\nmessages\nRetrieve all session messages from DB\nMethods\n__init__(session_id,\u00a0session,\u00a0keyspace[,\u00a0...])\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nWrite a message to the table\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory from DB\n__init__(session_id: str, session: Session, keyspace: str, table_name: str = 'message_store', ttl_seconds: Optional[int] = None) \u2192 None[source]\u00b6\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nWrite a message to the table\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.cassandra.CassandraChatMessageHistory.html"}
{"id": "13914ff4e577-1", "text": "message \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory from DB\nExamples using CassandraChatMessageHistory\u00b6\nCassandra Chat Message History\nCassandra", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.cassandra.CassandraChatMessageHistory.html"}
{"id": "b0ddb716458f-0", "text": "langchain.memory.vectorstore.VectorStoreRetrieverMemory\u00b6\nclass langchain.memory.vectorstore.VectorStoreRetrieverMemory[source]\u00b6\nBases: BaseMemory\nVectorStoreRetriever-backed memory.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam exclude_input_keys: Sequence[str] [Optional]\u00b6\nInput keys to exclude in addition to memory key when constructing the document\nparam input_key: Optional[str] = None\u00b6\nKey name to index the inputs to load_memory_variables.\nparam memory_key: str = 'history'\u00b6\nKey name to locate the memories in the result of load_memory_variables.\nparam retriever: langchain.schema.vectorstore.VectorStoreRetriever [Required]\u00b6\nVectorStoreRetriever object to connect to.\nparam return_docs: bool = False\u00b6\nWhether or not to return the result of querying the database directly.\nclear() \u2192 None[source]\u00b6\nNothing to clear.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.vectorstore.VectorStoreRetrieverMemory.html"}
{"id": "b0ddb716458f-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.vectorstore.VectorStoreRetrieverMemory.html"}
{"id": "b0ddb716458f-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, Union[List[Document], str]][source]\u00b6\nReturn history buffer.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None[source]\u00b6\nSave context from this conversation to buffer.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.vectorstore.VectorStoreRetrieverMemory.html"}
{"id": "b0ddb716458f-3", "text": "These attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty memory_variables: List[str]\u00b6\nThe list of keys emitted from the load_memory_variables method.\nExamples using VectorStoreRetrieverMemory\u00b6\nZep", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.vectorstore.VectorStoreRetrieverMemory.html"}
{"id": "be7214fb8f60-0", "text": "langchain.memory.zep_memory.ZepMemory\u00b6\nclass langchain.memory.zep_memory.ZepMemory[source]\u00b6\nBases: ConversationBufferMemory\nPersist your chain history to the Zep MemoryStore.\nThe number of messages returned by Zep and when the Zep server summarizes chat\nhistories is configurable. See the Zep documentation for more details.\nDocumentation: https://docs.getzep.com\nExample\nmemory = ZepMemory(\nsession_id=session_id,  # Identifies your user or a user\u2019s session\nurl=ZEP_API_URL,        # Your Zep server\u2019s URL\napi_key=<your_api_key>, # Optional\nmemory_key=\u201dhistory\u201d,   # Ensure this matches the key used in\n# chain\u2019s prompt template\nreturn_messages=True,   # Does your prompt template expect a string# or a list of Messages?\n)\nchain = LLMChain(memory=memory,\u2026) # Configure your chain to use the ZepMemoryinstance\nNote\nTo persist metadata alongside your chat history, your will need to create a\ncustom Chain class that overrides the prep_outputs method to include the metadata\nin the call to self.memory.save_context.\nZep is an open source platform for productionizing LLM apps. Go from a prototype\nbuilt in LangChain or LlamaIndex, or a custom app, to production in minutes without\nrewriting code.\nFor server installation instructions and more, see:\nhttps://docs.getzep.com/deployment/quickstart/\nFor more information on the zep-python package, see:\nhttps://github.com/getzep/zep-python\nInitialize ZepMemory.\nParameters\nsession_id (str) \u2013 Identifies your user or a user\u2019s session\nurl (str, optional) \u2013 Your Zep server\u2019s URL. Defaults to\n\u201chttp://localhost:8000\u201d.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.zep_memory.ZepMemory.html"}
{"id": "be7214fb8f60-1", "text": "\u201chttp://localhost:8000\u201d.\napi_key (Optional[str], optional) \u2013 Your Zep API key. Defaults to None.\noutput_key (Optional[str], optional) \u2013 The key to use for the output message.\nDefaults to None.\ninput_key (Optional[str], optional) \u2013 The key to use for the input message.\nDefaults to None.\nreturn_messages (bool, optional) \u2013 Does your prompt template expect a string\nor a list of Messages? Defaults to False\ni.e. return a string.\nhuman_prefix (str, optional) \u2013 The prefix to use for human messages.\nDefaults to \u201cHuman\u201d.\nai_prefix (str, optional) \u2013 The prefix to use for AI messages.\nDefaults to \u201cAI\u201d.\nmemory_key (str, optional) \u2013 The key to use for the memory.\nDefaults to \u201chistory\u201d.\nEnsure that this matches the key used in\nchain\u2019s prompt template.\nparam ai_prefix: str = 'AI'\u00b6\nparam chat_memory: ZepChatMessageHistory [Required]\u00b6\nparam human_prefix: str = 'Human'\u00b6\nparam input_key: Optional[str] = None\u00b6\nparam output_key: Optional[str] = None\u00b6\nparam return_messages: bool = False\u00b6\nclear() \u2192 None\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.zep_memory.ZepMemory.html"}
{"id": "be7214fb8f60-2", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.zep_memory.ZepMemory.html"}
{"id": "be7214fb8f60-3", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, Any]\u00b6\nReturn history buffer.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str], metadata: Optional[Dict[str, Any]] = None) \u2192 None[source]\u00b6\nSave context from this conversation to buffer.\nParameters\ninputs (Dict[str, Any]) \u2013 The inputs to the chain.\noutputs (Dict[str, str]) \u2013 The outputs from the chain.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.zep_memory.ZepMemory.html"}
{"id": "be7214fb8f60-4", "text": "outputs (Dict[str, str]) \u2013 The outputs from the chain.\nmetadata (Optional[Dict[str, Any]], optional) \u2013 Any metadata to save with\nthe context. Defaults to None\nReturns\nNone\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty buffer: Any\u00b6\nString buffer of memory.\nproperty buffer_as_messages: List[langchain.schema.messages.BaseMessage]\u00b6\nExposes the buffer as a list of messages in case return_messages is False.\nproperty buffer_as_str: str\u00b6\nExposes the buffer as a string in case return_messages is True.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using ZepMemory\u00b6\nZep\nZep Memory", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.zep_memory.ZepMemory.html"}
{"id": "5c23c5f74ab4-0", "text": "langchain.memory.chat_memory.BaseChatMemory\u00b6\nclass langchain.memory.chat_memory.BaseChatMemory[source]\u00b6\nBases: BaseMemory, ABC\nAbstract base class for chat memory.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam chat_memory: langchain.schema.chat_history.BaseChatMessageHistory [Optional]\u00b6\nparam input_key: Optional[str] = None\u00b6\nparam output_key: Optional[str] = None\u00b6\nparam return_messages: bool = False\u00b6\nclear() \u2192 None[source]\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_memory.BaseChatMemory.html"}
{"id": "5c23c5f74ab4-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_memory.BaseChatMemory.html"}
{"id": "5c23c5f74ab4-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nabstract load_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, Any]\u00b6\nReturn key-value pairs given the text input to the chain.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None[source]\u00b6\nSave context from this conversation to buffer.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nabstract property memory_variables: List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_memory.BaseChatMemory.html"}
{"id": "5c23c5f74ab4-3", "text": "abstract property memory_variables: List[str]\u00b6\nThe string keys this memory class will add to chain inputs.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_memory.BaseChatMemory.html"}
{"id": "b26b86fb3e4d-0", "text": "langchain.memory.chat_message_histories.rocksetdb.RocksetChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.rocksetdb.RocksetChatMessageHistory(session_id: str, client: ~typing.Any, collection: str, workspace: str = 'commons', messages_key: str = 'messages', sync: bool = False, message_uuid_method: ~typing.Callable[[], ~typing.Union[str, int]] = <function RocksetChatMessageHistory.<lambda>>)[source]\u00b6\nUses Rockset to store chat messages.\nTo use, ensure that the rockset python package installed.\nExample\nfrom langchain.memory.chat_message_histories import (\n    RocksetChatMessageHistory\n)\nfrom rockset import RocksetClient\nhistory = RocksetChatMessageHistory(\n    session_id=\"MySession\",\n    client=RocksetClient(),\n    collection=\"langchain_demo\",\n    sync=True\n)\nhistory.add_user_message(\"hi!\")\nhistory.add_ai_message(\"whats up?\")\nprint(history.messages)\nConstructs a new RocksetChatMessageHistory.\nParameters\nsession_id (-) \u2013 The ID of the chat session\nclient (-) \u2013 The RocksetClient object to use to query\ncollection (-) \u2013 The name of the collection to use to store chat\nmessages. If a collection with the given name\ndoes not exist in the workspace, it is created.\nworkspace (-) \u2013 The workspace containing collection. Defaults\nto \u201ccommons\u201d\nmessages_key (-) \u2013 The DB column containing message history.\nDefaults to \u201cmessages\u201d\nsync (-) \u2013 Whether to wait for messages to be added. Defaults\nto False. NOTE: setting this to True will slow\ndown performance.\nmessage_uuid_method (-) \u2013 The method that generates message IDs.\nIf set, all messages will have an id field within the", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.rocksetdb.RocksetChatMessageHistory.html"}
{"id": "b26b86fb3e4d-1", "text": "If set, all messages will have an id field within the\nadditional_kwargs property. If this param is not set\nand sync is False, message IDs will not be created.\nIf this param is not set and sync is True, the\nuuid.uuid4 method will be used to create message IDs.\nAttributes\nADD_TIMEOUT_MS\nCREATE_TIMEOUT_MS\nSLEEP_INTERVAL_MS\nmessages\nMessages in this chat history.\nMethods\n__init__(session_id,\u00a0client,\u00a0collection[,\u00a0...])\nConstructs a new RocksetChatMessageHistory.\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAdd a Message object to the history.\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nRemoves all messages from the chat history\n__init__(session_id: str, client: ~typing.Any, collection: str, workspace: str = 'commons', messages_key: str = 'messages', sync: bool = False, message_uuid_method: ~typing.Callable[[], ~typing.Union[str, int]] = <function RocksetChatMessageHistory.<lambda>>) \u2192 None[source]\u00b6\nConstructs a new RocksetChatMessageHistory.\nParameters\nsession_id (-) \u2013 The ID of the chat session\nclient (-) \u2013 The RocksetClient object to use to query\ncollection (-) \u2013 The name of the collection to use to store chat\nmessages. If a collection with the given name\ndoes not exist in the workspace, it is created.\nworkspace (-) \u2013 The workspace containing collection. Defaults\nto \u201ccommons\u201d\nmessages_key (-) \u2013 The DB column containing message history.\nDefaults to \u201cmessages\u201d\nsync (-) \u2013 Whether to wait for messages to be added. Defaults\nto False. NOTE: setting this to True will slow\ndown performance.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.rocksetdb.RocksetChatMessageHistory.html"}
{"id": "b26b86fb3e4d-2", "text": "to False. NOTE: setting this to True will slow\ndown performance.\nmessage_uuid_method (-) \u2013 The method that generates message IDs.\nIf set, all messages will have an id field within the\nadditional_kwargs property. If this param is not set\nand sync is False, message IDs will not be created.\nIf this param is not set and sync is True, the\nuuid.uuid4 method will be used to create message IDs.\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAdd a Message object to the history.\nParameters\nmessage \u2013 A BaseMessage object to store.\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nRemoves all messages from the chat history\nExamples using RocksetChatMessageHistory\u00b6\nRockset Chat Message History", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.rocksetdb.RocksetChatMessageHistory.html"}
{"id": "4cc58e6d702e-0", "text": "langchain.memory.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory(session_id: str, *, table_name: str = 'message_store', id_field: str = 'id', session_id_field: str = 'session_id', message_field: str = 'message', pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any)[source]\u00b6\nChat message history stored in a SingleStoreDB database.\nInitialize with necessary components.\nParameters\ntable_name (str, optional) \u2013 Specifies the name of the table in use.\nDefaults to \u201cmessage_store\u201d.\nid_field (str, optional) \u2013 Specifies the name of the id field in the table.\nDefaults to \u201cid\u201d.\nsession_id_field (str, optional) \u2013 Specifies the name of the session_id\nfield in the table. Defaults to \u201csession_id\u201d.\nmessage_field (str, optional) \u2013 Specifies the name of the message field\nin the table. Defaults to \u201cmessage\u201d.\npool (Following arguments pertain to the connection) \u2013 \npool_size (int, optional) \u2013 Determines the number of active connections in\nthe pool. Defaults to 5.\nmax_overflow (int, optional) \u2013 Determines the maximum number of connections\nallowed beyond the pool_size. Defaults to 10.\ntimeout (float, optional) \u2013 Specifies the maximum wait time in seconds for\nestablishing a connection. Defaults to 30.\nconnection (database) \u2013 \nhost (str, optional) \u2013 Specifies the hostname, IP address, or URL for the\ndatabase connection. The default scheme is \u201cmysql\u201d.\nuser (str, optional) \u2013 Database username.\npassword (str, optional) \u2013 Database password.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory.html"}
{"id": "4cc58e6d702e-1", "text": "password (str, optional) \u2013 Database password.\nport (int, optional) \u2013 Database port. Defaults to 3306 for non-HTTP\nconnections, 80 for HTTP connections, and 443 for HTTPS connections.\ndatabase (str, optional) \u2013 Database name.\nthe (Additional optional arguments provide further customization over) \u2013 \nconnection \u2013 \npure_python (bool, optional) \u2013 Toggles the connector mode. If True,\noperates in pure Python mode.\nlocal_infile (bool, optional) \u2013 Allows local file uploads.\ncharset (str, optional) \u2013 Specifies the character set for string values.\nssl_key (str, optional) \u2013 Specifies the path of the file containing the SSL\nkey.\nssl_cert (str, optional) \u2013 Specifies the path of the file containing the SSL\ncertificate.\nssl_ca (str, optional) \u2013 Specifies the path of the file containing the SSL\ncertificate authority.\nssl_cipher (str, optional) \u2013 Sets the SSL cipher list.\nssl_disabled (bool, optional) \u2013 Disables SSL usage.\nssl_verify_cert (bool, optional) \u2013 Verifies the server\u2019s certificate.\nAutomatically enabled if ssl_ca is specified.\nssl_verify_identity (bool, optional) \u2013 Verifies the server\u2019s identity.\nconv (dict[int, Callable], optional) \u2013 A dictionary of data conversion\nfunctions.\ncredential_type (str, optional) \u2013 Specifies the type of authentication to\nuse: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.\nautocommit (bool, optional) \u2013 Enables autocommits.\nresults_type (str, optional) \u2013 Determines the structure of the query results:\ntuples, namedtuples, dicts.\nresults_format (str, optional) \u2013 Deprecated. This option has been renamed to\nresults_type.\nExamples\nBasic Usage:\nfrom langchain.memory.chat_message_histories import (", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory.html"}
{"id": "4cc58e6d702e-2", "text": "Examples\nBasic Usage:\nfrom langchain.memory.chat_message_histories import (\n    SingleStoreDBChatMessageHistory\n)\nmessage_history = SingleStoreDBChatMessageHistory(\n    session_id=\"my-session\",\n    host=\"https://user:password@127.0.0.1:3306/database\"\n)\nAdvanced Usage:\nfrom langchain.memory.chat_message_histories import (\n    SingleStoreDBChatMessageHistory\n)\nmessage_history = SingleStoreDBChatMessageHistory(\n    session_id=\"my-session\",\n    host=\"127.0.0.1\",\n    port=3306,\n    user=\"user\",\n    password=\"password\",\n    database=\"db\",\n    table_name=\"my_custom_table\",\n    pool_size=10,\n    timeout=60,\n)\nUsing environment variables:\nfrom langchain.memory.chat_message_histories import (\n    SingleStoreDBChatMessageHistory\n)\nos.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'\nmessage_history = SingleStoreDBChatMessageHistory(\"my-session\")\nAttributes\nmessages\nRetrieve the messages from SingleStoreDB\nMethods\n__init__(session_id,\u00a0*[,\u00a0table_name,\u00a0...])\nInitialize with necessary components.\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAppend the message to the record in SingleStoreDB\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory from SingleStoreDB", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory.html"}
{"id": "4cc58e6d702e-3", "text": "clear()\nClear session memory from SingleStoreDB\n__init__(session_id: str, *, table_name: str = 'message_store', id_field: str = 'id', session_id_field: str = 'session_id', message_field: str = 'message', pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any)[source]\u00b6\nInitialize with necessary components.\nParameters\ntable_name (str, optional) \u2013 Specifies the name of the table in use.\nDefaults to \u201cmessage_store\u201d.\nid_field (str, optional) \u2013 Specifies the name of the id field in the table.\nDefaults to \u201cid\u201d.\nsession_id_field (str, optional) \u2013 Specifies the name of the session_id\nfield in the table. Defaults to \u201csession_id\u201d.\nmessage_field (str, optional) \u2013 Specifies the name of the message field\nin the table. Defaults to \u201cmessage\u201d.\npool (Following arguments pertain to the connection) \u2013 \npool_size (int, optional) \u2013 Determines the number of active connections in\nthe pool. Defaults to 5.\nmax_overflow (int, optional) \u2013 Determines the maximum number of connections\nallowed beyond the pool_size. Defaults to 10.\ntimeout (float, optional) \u2013 Specifies the maximum wait time in seconds for\nestablishing a connection. Defaults to 30.\nconnection (database) \u2013 \nhost (str, optional) \u2013 Specifies the hostname, IP address, or URL for the\ndatabase connection. The default scheme is \u201cmysql\u201d.\nuser (str, optional) \u2013 Database username.\npassword (str, optional) \u2013 Database password.\nport (int, optional) \u2013 Database port. Defaults to 3306 for non-HTTP\nconnections, 80 for HTTP connections, and 443 for HTTPS connections.\ndatabase (str, optional) \u2013 Database name.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory.html"}
{"id": "4cc58e6d702e-4", "text": "database (str, optional) \u2013 Database name.\nthe (Additional optional arguments provide further customization over) \u2013 \nconnection \u2013 \npure_python (bool, optional) \u2013 Toggles the connector mode. If True,\noperates in pure Python mode.\nlocal_infile (bool, optional) \u2013 Allows local file uploads.\ncharset (str, optional) \u2013 Specifies the character set for string values.\nssl_key (str, optional) \u2013 Specifies the path of the file containing the SSL\nkey.\nssl_cert (str, optional) \u2013 Specifies the path of the file containing the SSL\ncertificate.\nssl_ca (str, optional) \u2013 Specifies the path of the file containing the SSL\ncertificate authority.\nssl_cipher (str, optional) \u2013 Sets the SSL cipher list.\nssl_disabled (bool, optional) \u2013 Disables SSL usage.\nssl_verify_cert (bool, optional) \u2013 Verifies the server\u2019s certificate.\nAutomatically enabled if ssl_ca is specified.\nssl_verify_identity (bool, optional) \u2013 Verifies the server\u2019s identity.\nconv (dict[int, Callable], optional) \u2013 A dictionary of data conversion\nfunctions.\ncredential_type (str, optional) \u2013 Specifies the type of authentication to\nuse: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.\nautocommit (bool, optional) \u2013 Enables autocommits.\nresults_type (str, optional) \u2013 Determines the structure of the query results:\ntuples, namedtuples, dicts.\nresults_format (str, optional) \u2013 Deprecated. This option has been renamed to\nresults_type.\nExamples\nBasic Usage:\nfrom langchain.memory.chat_message_histories import (\n    SingleStoreDBChatMessageHistory\n)\nmessage_history = SingleStoreDBChatMessageHistory(\n    session_id=\"my-session\",", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory.html"}
{"id": "4cc58e6d702e-5", "text": "message_history = SingleStoreDBChatMessageHistory(\n    session_id=\"my-session\",\n    host=\"https://user:password@127.0.0.1:3306/database\"\n)\nAdvanced Usage:\nfrom langchain.memory.chat_message_histories import (\n    SingleStoreDBChatMessageHistory\n)\nmessage_history = SingleStoreDBChatMessageHistory(\n    session_id=\"my-session\",\n    host=\"127.0.0.1\",\n    port=3306,\n    user=\"user\",\n    password=\"password\",\n    database=\"db\",\n    table_name=\"my_custom_table\",\n    pool_size=10,\n    timeout=60,\n)\nUsing environment variables:\nfrom langchain.memory.chat_message_histories import (\n    SingleStoreDBChatMessageHistory\n)\nos.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'\nmessage_history = SingleStoreDBChatMessageHistory(\"my-session\")\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAppend the message to the record in SingleStoreDB\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory from SingleStoreDB", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory.html"}
{"id": "939ac6a7ef2c-0", "text": "langchain.memory.summary.SummarizerMixin\u00b6\nclass langchain.memory.summary.SummarizerMixin[source]\u00b6\nBases: BaseModel\nMixin for summarizer.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_prefix: str = 'AI'\u00b6\nparam human_prefix: str = 'Human'\u00b6\nparam llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nparam prompt: langchain.schema.prompt_template.BasePromptTemplate = PromptTemplate(input_variables=['new_lines', 'summary'], template='Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\\n\\nEXAMPLE\\nCurrent summary:\\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\\n\\nNew lines of conversation:\\nHuman: Why do you think artificial intelligence is a force for good?\\nAI: Because artificial intelligence will help humans reach their full potential.\\n\\nNew summary:\\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\\nEND OF EXAMPLE\\n\\nCurrent summary:\\n{summary}\\n\\nNew lines of conversation:\\n{new_lines}\\n\\nNew summary:')\u00b6\nparam summary_message_cls: Type[langchain.schema.messages.BaseMessage] = <class 'langchain.schema.messages.SystemMessage'>\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.summary.SummarizerMixin.html"}
{"id": "939ac6a7ef2c-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.summary.SummarizerMixin.html"}
{"id": "939ac6a7ef2c-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict_new_summary(messages: List[BaseMessage], existing_summary: str) \u2192 str[source]\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.summary.SummarizerMixin.html"}
{"id": "e24e755eb19b-0", "text": "langchain.memory.chat_message_histories.streamlit.StreamlitChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.streamlit.StreamlitChatMessageHistory(key: str = 'langchain_messages')[source]\u00b6\nChat message history that stores messages in Streamlit session state.\nParameters\nkey \u2013 The key to use in Streamlit session state for storing messages.\nAttributes\nmessages\nRetrieve the current list of messages\nMethods\n__init__([key])\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAdd a message to the session memory\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory\n__init__(key: str = 'langchain_messages')[source]\u00b6\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAdd a message to the session memory\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory\nExamples using StreamlitChatMessageHistory\u00b6\nStreamlit Chat Message History", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.streamlit.StreamlitChatMessageHistory.html"}
{"id": "e102554b6154-0", "text": "langchain.memory.chat_message_histories.redis.RedisChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.redis.RedisChatMessageHistory(session_id: str, url: str = 'redis://localhost:6379/0', key_prefix: str = 'message_store:', ttl: Optional[int] = None)[source]\u00b6\nChat message history stored in a Redis database.\nAttributes\nkey\nConstruct the record key to use\nmessages\nRetrieve the messages from Redis\nMethods\n__init__(session_id[,\u00a0url,\u00a0key_prefix,\u00a0ttl])\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAppend the message to the record in Redis\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory from Redis\n__init__(session_id: str, url: str = 'redis://localhost:6379/0', key_prefix: str = 'message_store:', ttl: Optional[int] = None)[source]\u00b6\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAppend the message to the record in Redis\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory from Redis\nExamples using RedisChatMessageHistory\u00b6\nRedis Chat Message History\nMessage Memory in Agent backed by a database", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.redis.RedisChatMessageHistory.html"}
{"id": "b88a18861d6f-0", "text": "langchain.memory.chat_message_histories.mongodb.MongoDBChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.mongodb.MongoDBChatMessageHistory(connection_string: str, session_id: str, database_name: str = 'chat_history', collection_name: str = 'message_store')[source]\u00b6\nChat message history that stores history in MongoDB.\nParameters\nconnection_string \u2013 connection string to connect to MongoDB\nsession_id \u2013 arbitrary key that is used to store the messages\nof a single chat session.\ndatabase_name \u2013 name of the database to use\ncollection_name \u2013 name of the collection to use\nAttributes\nmessages\nRetrieve the messages from MongoDB\nMethods\n__init__(connection_string,\u00a0session_id[,\u00a0...])\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAppend the message to the record in MongoDB\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory from MongoDB\n__init__(connection_string: str, session_id: str, database_name: str = 'chat_history', collection_name: str = 'message_store')[source]\u00b6\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAppend the message to the record in MongoDB\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory from MongoDB\nExamples using MongoDBChatMessageHistory\u00b6\nMongodb Chat Message History", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.mongodb.MongoDBChatMessageHistory.html"}
{"id": "42ff9277969c-0", "text": "langchain.memory.chat_message_histories.sql.BaseMessageConverter\u00b6\nclass langchain.memory.chat_message_histories.sql.BaseMessageConverter[source]\u00b6\nThe class responsible for converting BaseMessage to your SQLAlchemy model.\nMethods\n__init__()\nfrom_sql_model(sql_message)\nConvert a SQLAlchemy model to a BaseMessage instance.\nget_sql_model_class()\nGet the SQLAlchemy model class.\nto_sql_model(message,\u00a0session_id)\nConvert a BaseMessage instance to a SQLAlchemy model.\n__init__()\u00b6\nabstract from_sql_model(sql_message: Any) \u2192 BaseMessage[source]\u00b6\nConvert a SQLAlchemy model to a BaseMessage instance.\nabstract get_sql_model_class() \u2192 Any[source]\u00b6\nGet the SQLAlchemy model class.\nabstract to_sql_model(message: BaseMessage, session_id: str) \u2192 Any[source]\u00b6\nConvert a BaseMessage instance to a SQLAlchemy model.\nExamples using BaseMessageConverter\u00b6\nSQL Chat Message History", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.sql.BaseMessageConverter.html"}
{"id": "243cff31644a-0", "text": "langchain.memory.chat_message_histories.dynamodb.DynamoDBChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.dynamodb.DynamoDBChatMessageHistory(table_name: str, session_id: str, endpoint_url: Optional[str] = None, primary_key_name: str = 'SessionId', key: Optional[Dict[str, str]] = None, boto3_session: Optional[Session] = None, kms_key_id: Optional[str] = None)[source]\u00b6\nChat message history that stores history in AWS DynamoDB.\nThis class expects that a DynamoDB table exists with name table_name\nParameters\ntable_name \u2013 name of the DynamoDB table\nsession_id \u2013 arbitrary key that is used to store the messages\nof a single chat session.\nendpoint_url \u2013 URL of the AWS endpoint to connect to. This argument\nis optional and useful for test purposes, like using Localstack.\nIf you plan to use AWS cloud service, you normally don\u2019t have to\nworry about setting the endpoint_url.\nprimary_key_name \u2013 name of the primary key of the DynamoDB table. This argument\nis optional, defaulting to \u201cSessionId\u201d.\nkey \u2013 an optional dictionary with a custom primary and secondary key.\nThis argument is optional, but useful when using composite dynamodb keys, or\nisolating records based off of application details such as a user id.\nThis may also contain global and local secondary index keys.\nkms_key_id \u2013 an optional AWS KMS Key ID, AWS KMS Key ARN, or AWS KMS Alias for\nclient-side encryption\nAttributes\nmessages\nRetrieve the messages from DynamoDB\nMethods\n__init__(table_name,\u00a0session_id[,\u00a0...])\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAppend the message to the record in DynamoDB\nadd_user_message(message)", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.dynamodb.DynamoDBChatMessageHistory.html"}
{"id": "243cff31644a-1", "text": "Append the message to the record in DynamoDB\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory from DynamoDB\n__init__(table_name: str, session_id: str, endpoint_url: Optional[str] = None, primary_key_name: str = 'SessionId', key: Optional[Dict[str, str]] = None, boto3_session: Optional[Session] = None, kms_key_id: Optional[str] = None)[source]\u00b6\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAppend the message to the record in DynamoDB\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory from DynamoDB\nExamples using DynamoDBChatMessageHistory\u00b6\nDynamodb Chat Message History", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.dynamodb.DynamoDBChatMessageHistory.html"}
{"id": "505e6217552b-0", "text": "langchain.memory.chat_message_histories.neo4j.Neo4jChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.neo4j.Neo4jChatMessageHistory(session_id: Union[str, int], url: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None, database: str = 'neo4j', node_label: str = 'Session', window: int = 3)[source]\u00b6\nChat message history stored in a Neo4j database.\nAttributes\nmessages\nRetrieve the messages from Neo4j\nMethods\n__init__(session_id[,\u00a0url,\u00a0username,\u00a0...])\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAppend the message to the record in Neo4j\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory from Neo4j\n__init__(session_id: Union[str, int], url: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None, database: str = 'neo4j', node_label: str = 'Session', window: int = 3)[source]\u00b6\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAppend the message to the record in Neo4j\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory from Neo4j", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.neo4j.Neo4jChatMessageHistory.html"}
{"id": "4958b71a0edd-0", "text": "langchain.memory.buffer.ConversationBufferMemory\u00b6\nclass langchain.memory.buffer.ConversationBufferMemory[source]\u00b6\nBases: BaseChatMemory\nBuffer for storing conversation memory.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_prefix: str = 'AI'\u00b6\nparam chat_memory: BaseChatMessageHistory [Optional]\u00b6\nparam human_prefix: str = 'Human'\u00b6\nparam input_key: Optional[str] = None\u00b6\nparam output_key: Optional[str] = None\u00b6\nparam return_messages: bool = False\u00b6\nclear() \u2192 None\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.buffer.ConversationBufferMemory.html"}
{"id": "4958b71a0edd-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.buffer.ConversationBufferMemory.html"}
{"id": "4958b71a0edd-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nReturn history buffer.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None\u00b6\nSave context from this conversation to buffer.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty buffer: Any\u00b6\nString buffer of memory.\nproperty buffer_as_messages: List[langchain.schema.messages.BaseMessage]\u00b6\nExposes the buffer as a list of messages in case return_messages is False.\nproperty buffer_as_str: str\u00b6\nExposes the buffer as a string in case return_messages is True.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.buffer.ConversationBufferMemory.html"}
{"id": "4958b71a0edd-3", "text": "These attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using ConversationBufferMemory\u00b6\nGradio\nSceneXplain\nXata chat memory\nStreamlit Chat Message History\nDynamodb Chat Message History\nChat Over Documents with Vectara\nBittensor\nBedrock\nSet env var OPENAI_API_KEY or load from a .env file:\nStructure answers with OpenAI functions\nAgents\nAgent Debates with Tools\nMessage Memory in Agent backed by a database\nMemory in the Multi-Input Chain\nMemory in LLMChain\nMultiple Memory classes\nCustomizing Conversational Memory\nMemory in Agent\nShared memory across agents and tools\nAdd Memory to OpenAI Functions Agent\nFirst we add a step to load memory\nAdding memory", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.buffer.ConversationBufferMemory.html"}
{"id": "814ef8553629-0", "text": "langchain.memory.chat_message_histories.elasticsearch.ElasticsearchChatMessageHistory\u00b6\nclass langchain.memory.chat_message_histories.elasticsearch.ElasticsearchChatMessageHistory(index: str, session_id: str, *, es_connection: Optional[Elasticsearch] = None, es_url: Optional[str] = None, es_cloud_id: Optional[str] = None, es_user: Optional[str] = None, es_api_key: Optional[str] = None, es_password: Optional[str] = None)[source]\u00b6\nChat message history that stores history in Elasticsearch.\nParameters\nes_url \u2013 URL of the Elasticsearch instance to connect to.\nes_cloud_id \u2013 Cloud ID of the Elasticsearch instance to connect to.\nes_user \u2013 Username to use when connecting to Elasticsearch.\nes_password \u2013 Password to use when connecting to Elasticsearch.\nes_api_key \u2013 API key to use when connecting to Elasticsearch.\nes_connection \u2013 Optional pre-existing Elasticsearch connection.\nindex \u2013 Name of the index to use.\nsession_id \u2013 Arbitrary key that is used to store the messages\nof a single chat session.\nAttributes\nmessages\nRetrieve the messages from Elasticsearch\nMethods\n__init__(index,\u00a0session_id,\u00a0*[,\u00a0...])\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAdd a message to the chat session in Elasticsearch\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nClear session memory in Elasticsearch\nconnect_to_elasticsearch(*[,\u00a0es_url,\u00a0...])\nget_user_agent()", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.elasticsearch.ElasticsearchChatMessageHistory.html"}
{"id": "814ef8553629-1", "text": "connect_to_elasticsearch(*[,\u00a0es_url,\u00a0...])\nget_user_agent()\n__init__(index: str, session_id: str, *, es_connection: Optional[Elasticsearch] = None, es_url: Optional[str] = None, es_cloud_id: Optional[str] = None, es_user: Optional[str] = None, es_api_key: Optional[str] = None, es_password: Optional[str] = None)[source]\u00b6\nadd_ai_message(message: str) \u2192 None\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nadd_message(message: BaseMessage) \u2192 None[source]\u00b6\nAdd a message to the chat session in Elasticsearch\nadd_user_message(message: str) \u2192 None\u00b6\nConvenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nclear() \u2192 None[source]\u00b6\nClear session memory in Elasticsearch\nstatic connect_to_elasticsearch(*, es_url: Optional[str] = None, cloud_id: Optional[str] = None, api_key: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None) \u2192 Elasticsearch[source]\u00b6\nstatic get_user_agent() \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/memory/langchain.memory.chat_message_histories.elasticsearch.ElasticsearchChatMessageHistory.html"}
{"id": "087854c5a7d5-0", "text": "langchain.schema.runnable.utils.IsLocalDict\u00b6\nclass langchain.schema.runnable.utils.IsLocalDict(name: str, keys: Set[str])[source]\u00b6\nCheck if a name is a local dict.\nMethods\n__init__(name,\u00a0keys)\ngeneric_visit(node)\nCalled if no explicit visitor function exists for a node.\nvisit(node)\nVisit a node.\nvisit_Call(node)\nvisit_Constant(node)\nvisit_Subscript(node)\n__init__(name: str, keys: Set[str]) \u2192 None[source]\u00b6\ngeneric_visit(node)\u00b6\nCalled if no explicit visitor function exists for a node.\nvisit(node)\u00b6\nVisit a node.\nvisit_Call(node: Call) \u2192 Any[source]\u00b6\nvisit_Constant(node)\u00b6\nvisit_Subscript(node: Subscript) \u2192 Any[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.IsLocalDict.html"}
{"id": "b34114f8a8eb-0", "text": "langchain.schema.runnable.utils.get_function_first_arg_dict_keys\u00b6\nlangchain.schema.runnable.utils.get_function_first_arg_dict_keys(func: Callable) \u2192 Optional[List[str]][source]\u00b6\nGet the keys of the first argument of a function if it is a dict.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.get_function_first_arg_dict_keys.html"}
{"id": "70af02203692-0", "text": "langchain.schema.runnable.utils.gated_coro\u00b6\nasync langchain.schema.runnable.utils.gated_coro(semaphore: Semaphore, coro: Coroutine) \u2192 Any[source]\u00b6\nRun a coroutine with a semaphore.\n:param semaphore: The semaphore to use.\n:param coro: The coroutine to run.\nReturns\nThe result of the coroutine.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.gated_coro.html"}
{"id": "b124fe321890-0", "text": "langchain.schema.runnable.utils.indent_lines_after_first\u00b6\nlangchain.schema.runnable.utils.indent_lines_after_first(text: str, prefix: str) \u2192 str[source]\u00b6\nIndent all lines of text after the first line.\nParameters\ntext \u2013 The text to indent\nprefix \u2013 Used to determine the number of spaces to indent\nReturns\nThe indented text\nReturn type\nstr", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.indent_lines_after_first.html"}
{"id": "9646e64f2988-0", "text": "langchain.schema.runnable.base.RunnableEachBase\u00b6\nclass langchain.schema.runnable.base.RunnableEachBase[source]\u00b6\nBases: RunnableSerializable[List[Input], List[Output]]\nA runnable that delegates calls to another runnable\nwith each element of the input sequence.\nUse only if creating a new RunnableEach subclass with different __init__ args.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bound: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: List[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 List[Output][source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "9646e64f2988-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "9646e64f2988-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "9646e64f2988-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "9646e64f2988-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: List[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 List[Output][source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "9646e64f2988-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "9646e64f2988-6", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "9646e64f2988-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[List[langchain.schema.runnable.utils.Output]]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "9646e64f2988-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "4602039af77a-0", "text": "langchain.schema.runnable.utils.ConfigurableFieldMultiOption\u00b6\nclass langchain.schema.runnable.utils.ConfigurableFieldMultiOption(id: str, options: Mapping[str, Any], default: Sequence[str], name: Optional[str] = None, description: Optional[str] = None)[source]\u00b6\nA field that can be configured by the user with multiple default values.\nCreate new instance of ConfigurableFieldMultiOption(id, options, default, name, description)\nAttributes\ndefault\nAlias for field number 2\ndescription\nAlias for field number 4\nid\nAlias for field number 0\nname\nAlias for field number 3\noptions\nAlias for field number 1\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.ConfigurableFieldMultiOption.html"}
{"id": "4f2de06f41a8-0", "text": "langchain.schema.runnable.base.RunnableMap\u00b6\nlangchain.schema.runnable.base.RunnableMap\u00b6\nalias of RunnableParallel\nExamples using RunnableMap\u00b6\nOpaquePrompts\ninterface.md\nFirst we add a step to load memory\nsql_db.md\nprompt_llm_parser.md\nAdding memory\nmultiple_chains.md", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableMap.html"}
{"id": "cd70f86f1fb4-0", "text": "langchain.schema.runnable.utils.add\u00b6\nlangchain.schema.runnable.utils.add(addables: Iterable[Addable]) \u2192 Optional[Addable][source]\u00b6\nAdd a sequence of addable objects together.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.add.html"}
{"id": "fffedd21bda9-0", "text": "langchain.schema.runnable.utils.accepts_config\u00b6\nlangchain.schema.runnable.utils.accepts_config(callable: Callable[[...], Any]) \u2192 bool[source]\u00b6\nCheck if a callable accepts a config argument.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.accepts_config.html"}
{"id": "029018aa1e16-0", "text": "langchain.schema.runnable.base.RunnableBinding\u00b6\nclass langchain.schema.runnable.base.RunnableBinding[source]\u00b6\nBases: RunnableBindingBase[Input, Output]\nA runnable that delegates calls to another runnable with a set of kwargs.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bound: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nparam config: langchain.schema.runnable.config.RunnableConfig [Optional]\u00b6\nparam config_factories: List[Callable[[langchain.schema.runnable.config.RunnableConfig], langchain.schema.runnable.config.RunnableConfig]] [Optional]\u00b6\nparam custom_input_type: Optional[Any] = None\u00b6\nparam custom_output_type: Optional[Any] = None\u00b6\nparam kwargs: Mapping[str, Any] [Optional]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "029018aa1e16-1", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "029018aa1e16-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output][source]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "029018aa1e16-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "029018aa1e16-4", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "029018aa1e16-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "029018aa1e16-6", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output][source]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output][source]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "029018aa1e16-7", "text": "added to the run.\nwith_retry(**kwargs: Any) \u2192 Runnable[Input, Output][source]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(input_type: Optional[Union[Type[Input], BaseModel]] = None, output_type: Optional[Union[Type[Output], BaseModel]] = None) \u2192 Runnable[Input, Output][source]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "2348ef284f1f-0", "text": "langchain.schema.runnable.passthrough.RunnablePassthrough\u00b6\nclass langchain.schema.runnable.passthrough.RunnablePassthrough[source]\u00b6\nBases: RunnableSerializable[Other, Other]\nA runnable to passthrough inputs unchanged or with additional keys.\nThis runnable behaves almost like the identity function, except that it\ncan be configured to add additional keys to the output, if the input is a\ndict.\nThe examples below demonstrate this runnable works using a few simple\nchains. The chains rely on simple lambdas to make the examples easy to execute\nand experiment with.\nExamples\nfrom langchain.schema.runnable import RunnablePassthrough, RunnableParallel\nrunnable = RunnableParallel(\n    origin=RunnablePassthrough(),\n    modified=lambda x: x+1\n)\nrunnable.invoke(1) # {'origin': 1, 'modified': 2}\n def fake_llm(prompt: str) -> str: # Fake LLM for the example\n    return \"completion\"\nchain = RunnableLambda(fake_llm) | {\n    'original': RunnablePassthrough(), # Original LLM output\n    'parsed': lambda text: text[::-1] # Parsing logic\n}\nchain.invoke('hello') # {'original': 'completion', 'parsed': 'noitelpmoc'}\nIn some cases, it may be useful to pass the input through while adding some\nkeys to the output. In this case, you can use the assign method:\nfrom langchain.schema.runnable import RunnablePassthrough, RunnableParallel\n def fake_llm(prompt: str) -> str: # Fake LLM for the example\n    return \"completion\"\nrunnable = {\n    'llm1':  fake_llm,\n    'llm2':  fake_llm,\n}\n| RunnablePassthrough.assign(", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "2348ef284f1f-1", "text": "}\n| RunnablePassthrough.assign(\n    total_chars=lambda inputs: len(inputs['llm1'] + inputs['llm2'])\n  )\nrunnable.invoke('hello')\n# {'llm1': 'completion', 'llm2': 'completion', 'total_chars': 20}\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam afunc: Optional[Union[Callable[[langchain.schema.runnable.base.Other], Awaitable[None]], Callable[[langchain.schema.runnable.base.Other, langchain.schema.runnable.config.RunnableConfig], Awaitable[None]]]] = None\u00b6\nparam func: Optional[Union[Callable[[langchain.schema.runnable.base.Other], None], Callable[[langchain.schema.runnable.base.Other, langchain.schema.runnable.config.RunnableConfig], None]]] = None\u00b6\nparam input_type: Optional[Type[langchain.schema.runnable.base.Other]] = None\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Other, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Other[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "2348ef284f1f-2", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nclassmethod assign(**kwargs: Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any], Mapping[str, Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any]]]]) \u2192 RunnableAssign[source]\u00b6\nMerge the Dict input with the output produced by the mapping argument.\nParameters\nmapping \u2013 A mapping from keys to runnables or callables.\nReturns\nA runnable that merges the Dict input with the output produced by the\nmapping argument.\nasync astream(input: Other, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Other][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "2348ef284f1f-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Other], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Other][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "2348ef284f1f-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "2348ef284f1f-5", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Other, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Other[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "2348ef284f1f-6", "text": "for more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "2348ef284f1f-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Other, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Other][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Other], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Other][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "2348ef284f1f-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Any\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "2348ef284f1f-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using RunnablePassthrough\u00b6\nFirst we add a step to load memory\nprompt_llm_parser.md\nmultiple_chains.md", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "4f58b02b6896-0", "text": "langchain.schema.runnable.utils.get_lambda_source\u00b6\nlangchain.schema.runnable.utils.get_lambda_source(func: Callable) \u2192 Optional[str][source]\u00b6\nGet the source code of a lambda function.\nParameters\nfunc \u2013 a callable that can be a lambda function\nReturns\nthe source code of the lambda function\nReturn type\nstr", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.get_lambda_source.html"}
{"id": "98c4e34752c6-0", "text": "langchain.schema.runnable.branch.RunnableBranch\u00b6\nclass langchain.schema.runnable.branch.RunnableBranch[source]\u00b6\nBases: RunnableSerializable[Input, Output]\nA Runnable that selects which branch to run based on a condition.\nThe runnable is initialized with a list of (condition, runnable) pairs and\na default branch.\nWhen operating on an input, the first condition that evaluates to True is\nselected, and the corresponding runnable is run on the input.\nIf no condition evaluates to True, the default branch is run on the input.\nExamples\nfrom langchain.schema.runnable import RunnableBranch\nbranch = RunnableBranch(\n    (lambda x: isinstance(x, str), lambda x: x.upper()),\n    (lambda x: isinstance(x, int), lambda x: x + 1),\n    (lambda x: isinstance(x, float), lambda x: x * 2),\n    lambda x: \"goodbye\",\n)\nbranch.invoke(\"hello\") # \"HELLO\"\nbranch.invoke(None) # \"goodbye\"\nA Runnable that runs one of two branches based on a condition.\nparam branches: Sequence[Tuple[langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, bool], langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output]]] [Required]\u00b6\nparam default: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "98c4e34752c6-1", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nAsync version of invoke.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "98c4e34752c6-2", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "98c4e34752c6-3", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "98c4e34752c6-4", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nThe namespace of a RunnableBranch is the namespace of its default branch.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nFirst evaluates the condition, then delegate to true or false branch.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nRunnableBranch is serializable if all its branches are serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "98c4e34752c6-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "98c4e34752c6-6", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "98c4e34752c6-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "98c4e34752c6-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "e0a9fa0ddf71-0", "text": "langchain.schema.runnable.config.get_async_callback_manager_for_config\u00b6\nlangchain.schema.runnable.config.get_async_callback_manager_for_config(config: RunnableConfig) \u2192 AsyncCallbackManager[source]\u00b6\nGet an async callback manager for a config.\nParameters\nconfig (RunnableConfig) \u2013 The config.\nReturns\nThe async callback manager.\nReturn type\nAsyncCallbackManager", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.config.get_async_callback_manager_for_config.html"}
{"id": "78d1eb0e0e44-0", "text": "langchain.schema.runnable.router.RouterRunnable\u00b6\nclass langchain.schema.runnable.router.RouterRunnable[source]\u00b6\nBases: RunnableSerializable[RouterInput, Output]\nA runnable that routes to a set of runnables based on Input[\u2018key\u2019].\nReturns the output of the selected runnable.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam runnables: Mapping[str, langchain.schema.runnable.base.Runnable[Any, langchain.schema.runnable.utils.Output]] [Required]\u00b6\nasync abatch(inputs: List[RouterInput], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: RouterInput, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: RouterInput, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "78d1eb0e0e44-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[RouterInput], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "78d1eb0e0e44-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "78d1eb0e0e44-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "78d1eb0e0e44-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: RouterInput, config: Optional[RunnableConfig] = None) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "78d1eb0e0e44-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: RouterInput, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "78d1eb0e0e44-6", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "78d1eb0e0e44-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "78d1eb0e0e44-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "209ce5bce599-0", "text": "langchain.schema.runnable.utils.accepts_run_manager\u00b6\nlangchain.schema.runnable.utils.accepts_run_manager(callable: Callable[[...], Any]) \u2192 bool[source]\u00b6\nCheck if a callable accepts a run_manager argument.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.accepts_run_manager.html"}
{"id": "e5b79e685719-0", "text": "langchain.schema.runnable.utils.AddableDict\u00b6\nclass langchain.schema.runnable.utils.AddableDict[source]\u00b6\nDictionary that can be added to another dictionary.\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.AddableDict.html"}
{"id": "e5b79e685719-1", "text": "pop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.AddableDict.html"}
{"id": "ae523e2c1227-0", "text": "langchain.schema.runnable.config.get_executor_for_config\u00b6\nlangchain.schema.runnable.config.get_executor_for_config(config: RunnableConfig) \u2192 Generator[Executor, None, None][source]\u00b6\nGet an executor for a config.\nParameters\nconfig (RunnableConfig) \u2013 The config.\nYields\nGenerator[Executor, None, None] \u2013 The executor.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.config.get_executor_for_config.html"}
{"id": "9d8ab9ab6bcc-0", "text": "langchain.schema.runnable.utils.get_unique_config_specs\u00b6\nlangchain.schema.runnable.utils.get_unique_config_specs(specs: Iterable[ConfigurableFieldSpec]) \u2192 List[ConfigurableFieldSpec][source]\u00b6\nGet the unique config specs from a sequence of config specs.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.get_unique_config_specs.html"}
{"id": "eccc42578bab-0", "text": "langchain.schema.runnable.config.call_func_with_variable_args\u00b6\nlangchain.schema.runnable.config.call_func_with_variable_args(func: Union[Callable[[Input], Output], Callable[[Input, RunnableConfig], Output], Callable[[Input, CallbackManagerForChainRun], Output], Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]], input: Input, config: RunnableConfig, run_manager: Optional[CallbackManagerForChainRun] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nCall function that may optionally accept a run_manager and/or config.\nParameters\n(Union[Callable[[Input] (func) \u2013 Callable[[Input, CallbackManagerForChainRun], Output],\nCallable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]]):\nThe function to call.\nOutput] \u2013 Callable[[Input, CallbackManagerForChainRun], Output],\nCallable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]]):\nThe function to call.\n:paramCallable[[Input, CallbackManagerForChainRun], Output],\nCallable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]]):The function to call.\nParameters\ninput (Input) \u2013 The input to the function.\nrun_manager (CallbackManagerForChainRun) \u2013 The run manager to\npass to the function.\nconfig (RunnableConfig) \u2013 The config to pass to the function.\n**kwargs (Any) \u2013 The keyword arguments to pass to the function.\nReturns\nThe output of the function.\nReturn type\nOutput", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.config.call_func_with_variable_args.html"}
{"id": "730b6b21598f-0", "text": "langchain.schema.runnable.router.RouterInput\u00b6\nclass langchain.schema.runnable.router.RouterInput[source]\u00b6\nA Router input.\nkey\u00b6\nThe key to route on.\nType\nstr\ninput\u00b6\nThe input to pass to the selected runnable.\nType\nAny\nAttributes\nkey\ninput\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.router.RouterInput.html"}
{"id": "730b6b21598f-1", "text": "items() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.router.RouterInput.html"}
{"id": "37a49ed65bff-0", "text": "langchain.schema.runnable.utils.IsFunctionArgDict\u00b6\nclass langchain.schema.runnable.utils.IsFunctionArgDict[source]\u00b6\nCheck if the first argument of a function is a dict.\nMethods\n__init__()\ngeneric_visit(node)\nCalled if no explicit visitor function exists for a node.\nvisit(node)\nVisit a node.\nvisit_AsyncFunctionDef(node)\nvisit_Constant(node)\nvisit_FunctionDef(node)\nvisit_Lambda(node)\n__init__() \u2192 None[source]\u00b6\ngeneric_visit(node)\u00b6\nCalled if no explicit visitor function exists for a node.\nvisit(node)\u00b6\nVisit a node.\nvisit_AsyncFunctionDef(node: AsyncFunctionDef) \u2192 Any[source]\u00b6\nvisit_Constant(node)\u00b6\nvisit_FunctionDef(node: FunctionDef) \u2192 Any[source]\u00b6\nvisit_Lambda(node: Lambda) \u2192 Any[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.IsFunctionArgDict.html"}
{"id": "51221e85b704-0", "text": "langchain.schema.runnable.base.RunnableParallel\u00b6\nclass langchain.schema.runnable.base.RunnableParallel[source]\u00b6\nBases: RunnableSerializable[Input, Dict[str, Any]]\nA runnable that runs a mapping of runnables in parallel,\nand returns a mapping of their outputs.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam steps: Mapping[str, langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, Any]] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Dict[str, Any][source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Dict[str, Any]][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "51221e85b704-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Dict[str, Any]][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "51221e85b704-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "51221e85b704-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "51221e85b704-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None) \u2192 Dict[str, Any][source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "51221e85b704-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Dict[str, Any]][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Dict[str, Any]][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "51221e85b704-6", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "51221e85b704-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "51221e85b704-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "b931c2f226bc-0", "text": "langchain.schema.runnable.utils.gather_with_concurrency\u00b6\nasync langchain.schema.runnable.utils.gather_with_concurrency(n: Optional[int], *coros: Coroutine) \u2192 list[source]\u00b6\nGather coroutines with a limit on the number of concurrent coroutines.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.gather_with_concurrency.html"}
{"id": "f111087d901a-0", "text": "langchain.schema.runnable.utils.ConfigurableFieldSpec\u00b6\nclass langchain.schema.runnable.utils.ConfigurableFieldSpec(id: str, name: Optional[str], description: Optional[str], default: Any, annotation: Any)[source]\u00b6\nA field that can be configured by the user. It is a specification of a field.\nCreate new instance of ConfigurableFieldSpec(id, name, description, default, annotation)\nAttributes\nannotation\nAlias for field number 4\ndefault\nAlias for field number 3\ndescription\nAlias for field number 2\nid\nAlias for field number 0\nname\nAlias for field number 1\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.ConfigurableFieldSpec.html"}
{"id": "3c917ad0c02d-0", "text": "langchain.schema.runnable.fallbacks.RunnableWithFallbacks\u00b6\nclass langchain.schema.runnable.fallbacks.RunnableWithFallbacks[source]\u00b6\nBases: RunnableSerializable[Input, Output]\nA Runnable that can fallback to other Runnables if it fails.\nExternal APIs (e.g., APIs for a language model) may at times experience\ndegraded performance or even downtime.\nIn these cases, it can be useful to have a fallback runnable that can be\nused in place of the original runnable (e.g., fallback to another LLM provider).\nFallbacks can be defined at the level of a single runnable, or at the level\nof a chain of runnables. Fallbacks are tried in order until one succeeds or\nall fail.\nWhile you can instantiate a RunnableWithFallbacks directly, it is usually\nmore convenient to use the with_fallbacks method on a runnable.\nExample\nfrom langchain.chat_models.openai import ChatOpenAI\nfrom langchain.chat_models.anthropic import ChatAnthropic\nmodel = ChatAnthropic().with_fallbacks([ChatOpenAI()])\n# Will usually use ChatAnthropic, but fallback to ChatOpenAI\n# if ChatAnthropic fails.\nmodel.invoke('hello')\n# And you can also use fallbacks at the level of a chain.\n# Here if both LLM providers fail, we'll fallback to a good hardcoded\n# response.\nfrom langchain.prompts import PromptTemplate\nfrom langchain.schema.output_parser import StrOutputParser\nfrom langchain.schema.runnable import RunnableLambda\ndef when_all_is_lost(inputs):\n    return (\"Looks like our LLM providers are down. \"\n            \"Here's a nice \ud83e\udd9c\ufe0f emoji for you instead.\")\nchain_with_fallback = (\n    PromptTemplate.from_template('Tell me a joke about {topic}')\n    | model", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "3c917ad0c02d-1", "text": "PromptTemplate.from_template('Tell me a joke about {topic}')\n    | model\n    | StrOutputParser()\n).with_fallbacks([RunnableLambda(when_all_is_lost)])\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)\u00b6\nThe exceptions on which fallbacks should be tried.\nAny exception that is not a subclass of these exceptions will be raised immediately.\nparam fallbacks: Sequence[langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output]] [Required]\u00b6\nA sequence of fallbacks to try.\nparam runnable: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nThe runnable to run first.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "3c917ad0c02d-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "3c917ad0c02d-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "3c917ad0c02d-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "3c917ad0c02d-5", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "3c917ad0c02d-6", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "3c917ad0c02d-7", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "3c917ad0c02d-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "3c917ad0c02d-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty runnables: Iterator[langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "198958b2e3df-0", "text": "langchain.schema.runnable.passthrough.identity\u00b6\nlangchain.schema.runnable.passthrough.identity(x: Other) \u2192 Other[source]\u00b6\nAn identity function", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.identity.html"}
{"id": "3a6baef93000-0", "text": "langchain.schema.runnable.config.RunnableConfig\u00b6\nclass langchain.schema.runnable.config.RunnableConfig[source]\u00b6\nConfiguration for a Runnable.\nAttributes\ntags\nTags for this call and any sub-calls (eg.\nmetadata\nMetadata for this call and any sub-calls (eg.\ncallbacks\nCallbacks for this call and any sub-calls (eg.\nrun_name\nName for the tracer run for this call.\nmax_concurrency\nMaximum number of parallel calls to make.\nrecursion_limit\nMaximum number of times a call can recurse.\nconfigurable\nRuntime values for attributes previously made configurable on this Runnable, or sub-Runnables, through .configurable_fields() or .configurable_alternatives().\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.config.RunnableConfig.html"}
{"id": "3a6baef93000-1", "text": "values()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6\nExamples using RunnableConfig\u00b6\nRun arbitrary functions", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.config.RunnableConfig.html"}
{"id": "864af75092e2-0", "text": "langchain.schema.runnable.base.RunnableSequence\u00b6\nclass langchain.schema.runnable.base.RunnableSequence[source]\u00b6\nBases: RunnableSerializable[Input, Output]\nA sequence of runnables, where the output of each is the input of the next.\nRunnableSequence is the most important composition operator in LangChain as it is\nused in virtually every chain.\nA RunnableSequence can be instantiated directly or more commonly by using the |\noperator where either the left or right operands (or both) must be a Runnable.\nAny RunnableSequence automatically supports sync, async, batch.\nThe default implementations of batch and abatch utilize threadpools and\nasyncio gather and will be faster than naive invocation of invoke or ainvoke\nfor IO bound runnables.\nBatching is implemented by invoking the batch method on each component of the\nRunnableSequence in order.\nA RunnableSequence preserves the streaming properties of its components, so if all\ncomponents of the sequence implement a transform method \u2013 which\nis the method that implements the logic to map a streaming input to a streaming\noutput \u2013 then the sequence will be able to stream input to output!\nIf any component of the sequence does not implement transform then the\nstreaming will only begin after this component is run. If there are\nmultiple blocking components, streaming begins after the last one.\nPlease note: RunnableLambdas do not support transform by default! So ifyou need to use a RunnableLambdas be careful about where you place them in a\nRunnableSequence (if you need to use the .stream()/.astream() methods).\nIf you need arbitrary logic and need streaming, you can subclass\nRunnable, and implement transform for whatever logic you need.\nHere is a simple example that uses simple functions to illustrate the use of\nRunnableSequence:\nfrom langchain.schema.runnable import RunnableLambda\ndef add_one(x: int) -> int:", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "864af75092e2-1", "text": "def add_one(x: int) -> int:\n    return x + 1\ndef mul_two(x: int) -> int:\n    return x * 2\nrunnable_1 = RunnableLambda(add_one)\nrunnable_2 = RunnableLambda(mul_two)\nsequence = runnable_1 | runnable_2\n# Or equivalently:\n# sequence = RunnableSequence(first=runnable_1, last=runnable_2)\nsequence.invoke(1)\nawait runnable.ainvoke(1)\nsequence.batch([1, 2, 3])\nawait sequence.abatch([1, 2, 3])\nHere\u2019s an example that uses streams JSON output generated by an LLM:\nfrom langchain.output_parsers.json import SimpleJsonOutputParser\nfrom langchain.chat_models.openai import ChatOpenAI\nprompt = PromptTemplate.from_template(\n    'In JSON format, give me a list of {topic} and their '\n    'corresponding names in French, Spanish and in a '\n    'Cat Language.'\n)\nmodel = ChatOpenAI()\nchain = prompt | model | SimpleJsonOutputParser()\nasync for chunk in chain.astream({'topic': 'colors'}):\n    print('-')\n    print(chunk, sep='', flush=True)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam first: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, Any] [Required]\u00b6\nThe first runnable in the sequence.\nparam last: langchain.schema.runnable.base.Runnable[Any, langchain.schema.runnable.utils.Output] [Required]\u00b6\nThe last runnable in the sequence.\nparam middle: List[langchain.schema.runnable.base.Runnable[Any, Any]] [Optional]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "864af75092e2-2", "text": "The middle runnables in the sequence.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "864af75092e2-3", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "864af75092e2-4", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "864af75092e2-5", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "864af75092e2-6", "text": "This method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "864af75092e2-7", "text": "Return a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "864af75092e2-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "864af75092e2-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty steps: List[langchain.schema.runnable.base.Runnable[Any, Any]]\u00b6\nAll the runnables that make up the sequence in order.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "ed7c8efa9977-0", "text": "langchain.schema.runnable.base.coerce_to_runnable\u00b6\nlangchain.schema.runnable.base.coerce_to_runnable(thing: Union[Runnable[Input, Output], Callable[[Input], Output], Callable[[Input], Awaitable[Output]], Callable[[Iterator[Input]], Iterator[Output]], Callable[[AsyncIterator[Input]], AsyncIterator[Output]], Mapping[str, Any]]) \u2192 Runnable[Input, Output][source]\u00b6\nCoerce a runnable-like object into a Runnable.\nParameters\nthing \u2013 A runnable-like object.\nReturns\nA Runnable.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.coerce_to_runnable.html"}
{"id": "734b3e1fa8c0-0", "text": "langchain.schema.runnable.config.EmptyDict\u00b6\nclass langchain.schema.runnable.config.EmptyDict[source]\u00b6\nEmpty dict type.\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.config.EmptyDict.html"}
{"id": "734b3e1fa8c0-1", "text": "pop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.config.EmptyDict.html"}
{"id": "10ac0940470e-0", "text": "langchain.schema.runnable.utils.aadd\u00b6\nasync langchain.schema.runnable.utils.aadd(addables: AsyncIterable[Addable]) \u2192 Optional[Addable][source]\u00b6\nAsynchronously add a sequence of addable objects together.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.aadd.html"}
{"id": "a15fdd3b94df-0", "text": "langchain.schema.runnable.config.ensure_config\u00b6\nlangchain.schema.runnable.config.ensure_config(config: Optional[RunnableConfig] = None) \u2192 RunnableConfig[source]\u00b6\nEnsure that a config is a dict with all keys present.\nParameters\nconfig (Optional[RunnableConfig], optional) \u2013 The config to ensure.\nDefaults to None.\nReturns\nThe ensured config.\nReturn type\nRunnableConfig", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.config.ensure_config.html"}
{"id": "0597fd79f5a2-0", "text": "langchain.schema.runnable.retry.RunnableRetry\u00b6\nclass langchain.schema.runnable.retry.RunnableRetry[source]\u00b6\nBases: RunnableBindingBase[Input, Output]\nRetry a Runnable if it fails.\nA RunnableRetry helps can be used to add retry logic to any object\nthat subclasses the base Runnable.\nSuch retries are especially useful for network calls that may fail\ndue to transient errors.\nThe RunnableRetry is implemented as a RunnableBinding. The easiest\nway to use it is through the .with_retry() method on all Runnables.\nExample:\nHere\u2019s an example that uses a RunnableLambda to raise an exception\nimport time\ndef foo(input) -> None:\n    '''Fake function that raises an exception.'''\n    raise ValueError(\"Invoking foo failed. At time {time.time()}\")\nrunnable = RunnableLambda(foo)\nrunnable_with_retries = runnable.with_retry(\n    retry_exception_types=(ValueError,), # Retry only on ValueError\n    wait_exponential_jitter=True, # Add jitter to the exponential backoff\n    max_attempt_number=2, # Try twice\n)\n# The method invocation above is equivalent to the longer form below:\nrunnable_with_retries = RunnableRetry(\n    bound=runnable,\n    retry_exception_types=(ValueError,),\n    max_attempt_number=2,\n    wait_exponential_jitter=True\n)\nThis logic can be used to retry any Runnable, including a chain of Runnables,\nbut in general it\u2019s best practice to keep the scope of the retry as small as\npossible. For example, if you have a chain of Runnables, you should only retry\nthe Runnable that is likely to fail, not the entire chain.\nExample\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.prompts import PromptTemplate", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "0597fd79f5a2-1", "text": "from langchain.chat_models import ChatOpenAI\nfrom langchain.prompts import PromptTemplate\ntemplate = PromptTemplate.from_template(\"tell me a joke about {topic}.\")\nmodel = ChatOpenAI(temperature=0.5)\n# Good\nchain = template | model.with_retry()\n# Bad\nchain = template | model\nretryable_chain = chain.with_retry()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bound: Runnable[Input, Output] [Required]\u00b6\nparam config: RunnableConfig [Optional]\u00b6\nparam config_factories: List[Callable[[RunnableConfig], RunnableConfig]] [Optional]\u00b6\nparam custom_input_type: Optional[Any] = None\u00b6\nparam custom_output_type: Optional[Any] = None\u00b6\nparam kwargs: Mapping[str, Any] [Optional]\u00b6\nparam max_attempt_number: int = 3\u00b6\nThe maximum number of attempts to retry the runnable.\nparam retry_exception_types: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)\u00b6\nThe exception types to retry on. By default all exceptions are retried.\nIn general you should only retry on exceptions that are likely to be\ntransient, such as network errors.\nGood exceptions to retry are all server errors (5xx) and selected client\nerrors (4xx) such as 429 Too Many Requests.\nparam wait_exponential_jitter: bool = True\u00b6\nWhether to add jitter to the exponential backoff.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "0597fd79f5a2-2", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "0597fd79f5a2-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[Output][source]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "0597fd79f5a2-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "0597fd79f5a2-5", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "0597fd79f5a2-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "0597fd79f5a2-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "0597fd79f5a2-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "0597fd79f5a2-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "c957e6bc73a3-0", "text": "langchain.schema.runnable.config.get_callback_manager_for_config\u00b6\nlangchain.schema.runnable.config.get_callback_manager_for_config(config: RunnableConfig) \u2192 CallbackManager[source]\u00b6\nGet a callback manager for a config.\nParameters\nconfig (RunnableConfig) \u2013 The config.\nReturns\nThe callback manager.\nReturn type\nCallbackManager", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.config.get_callback_manager_for_config.html"}
{"id": "9a7db9277062-0", "text": "langchain.schema.runnable.config.patch_config\u00b6\nlangchain.schema.runnable.config.patch_config(config: Optional[RunnableConfig], *, callbacks: Optional[BaseCallbackManager] = None, recursion_limit: Optional[int] = None, max_concurrency: Optional[int] = None, run_name: Optional[str] = None, configurable: Optional[Dict[str, Any]] = None) \u2192 RunnableConfig[source]\u00b6\nPatch a config with new values.\nParameters\nconfig (Optional[RunnableConfig]) \u2013 The config to patch.\ncopy_locals (bool, optional) \u2013 Whether to copy locals. Defaults to False.\ncallbacks (Optional[BaseCallbackManager], optional) \u2013 The callbacks to set.\nDefaults to None.\nrecursion_limit (Optional[int], optional) \u2013 The recursion limit to set.\nDefaults to None.\nmax_concurrency (Optional[int], optional) \u2013 The max concurrency to set.\nDefaults to None.\nrun_name (Optional[str], optional) \u2013 The run name to set. Defaults to None.\nconfigurable (Optional[Dict[str, Any]], optional) \u2013 The configurable to set.\nDefaults to None.\nReturns\nThe patched config.\nReturn type\nRunnableConfig", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.config.patch_config.html"}
{"id": "4d9ffa7b7672-0", "text": "langchain.schema.runnable.config.acall_func_with_variable_args\u00b6\nasync langchain.schema.runnable.config.acall_func_with_variable_args(func: Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]], input: Input, config: RunnableConfig, run_manager: Optional[AsyncCallbackManagerForChainRun] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nCall function that may optionally accept a run_manager and/or config.\nParameters\n(Union[Callable[[Input] (func) \u2013 AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,\nAsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):\nThe function to call.\nAwaitable[Output]] \u2013 AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,\nAsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):\nThe function to call.\nCallable[[Input \u2013 AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,\nAsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):\nThe function to call.\n:paramAsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):\nThe function to call.\nParameters\ninput (Input) \u2013 The input to the function.\nrun_manager (AsyncCallbackManagerForChainRun) \u2013 The run manager\nto pass to the function.\nconfig (RunnableConfig) \u2013 The config to pass to the function.\n**kwargs (Any) \u2013 The keyword arguments to pass to the function.\nReturns\nThe output of the function.\nReturn type\nOutput", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.config.acall_func_with_variable_args.html"}
{"id": "101615e42447-0", "text": "langchain.schema.runnable.config.get_config_list\u00b6\nlangchain.schema.runnable.config.get_config_list(config: Optional[Union[RunnableConfig, List[RunnableConfig]]], length: int) \u2192 List[RunnableConfig][source]\u00b6\nGet a list of configs from a single config or a list of configs.\nIt is useful for subclasses overriding batch() or abatch().\nParameters\nconfig (Optional[Union[RunnableConfig, List[RunnableConfig]]]) \u2013 The config or list of configs.\nlength (int) \u2013 The length of the list.\nReturns\nThe list of configs.\nReturn type\nList[RunnableConfig]\nRaises\nValueError \u2013 If the length of the list is not equal to the length of the inputs.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.config.get_config_list.html"}
{"id": "879f059862af-0", "text": "langchain.schema.runnable.utils.SupportsAdd\u00b6\nclass langchain.schema.runnable.utils.SupportsAdd(*args, **kwargs)[source]\u00b6\nProtocol for objects that support addition.\nMethods\n__init__(*args,\u00a0**kwargs)\n__init__(*args, **kwargs)\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.SupportsAdd.html"}
{"id": "06fd57af7112-0", "text": "langchain.schema.runnable.configurable.RunnableConfigurableAlternatives\u00b6\nclass langchain.schema.runnable.configurable.RunnableConfigurableAlternatives[source]\u00b6\nBases: DynamicRunnable[Input, Output]\nA Runnable that can be dynamically configured.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam alternatives: Dict[str, Union[langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output], Callable[[], langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output]]]] [Required]\u00b6\nparam default: langchain.schema.runnable.base.RunnableSerializable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nparam default_key: str = 'default'\u00b6\nparam which: langchain.schema.runnable.utils.ConfigurableField [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "06fd57af7112-1", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "06fd57af7112-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output][source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "06fd57af7112-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "06fd57af7112-4", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "06fd57af7112-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "06fd57af7112-6", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "06fd57af7112-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "06fd57af7112-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "91e216eb5365-0", "text": "langchain.schema.runnable.base.RunnableLambda\u00b6\nclass langchain.schema.runnable.base.RunnableLambda(func: Union[Union[Callable[[Input], Output], Callable[[Input, RunnableConfig], Output], Callable[[Input, CallbackManagerForChainRun], Output], Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]], Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]], afunc: Optional[Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]] = None)[source]\u00b6\nRunnableLambda converts a python callable into a Runnable.\nWrapping a callable in a RunnableLambda makes the callable usable\nwithin either a sync or async context.\nRunnableLambda can be composed as any other Runnable and provides\nseamless integration with LangChain tracing.\nExamples\n# This is a RunnableLambda\nfrom langchain.schema.runnable import RunnableLambda\ndef add_one(x: int) -> int:\n    return x + 1\nrunnable = RunnableLambda(add_one)\nrunnable.invoke(1) # returns 2\nrunnable.batch([1, 2, 3]) # returns [2, 3, 4]\n# Async is supported by default by delegating to the sync implementation\nawait runnable.ainvoke(1) # returns 2\nawait runnable.abatch([1, 2, 3]) # returns [2, 3, 4]\n# Alternatively, can provide both synd and sync implementations", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "91e216eb5365-1", "text": "# Alternatively, can provide both synd and sync implementations\nasync def add_one_async(x: int) -> int:\n    return x + 1\nrunnable = RunnableLambda(add_one, afunc=add_one_async)\nrunnable.invoke(1) # Uses add_one\nawait runnable.ainvoke(1) # Uses add_one_async\nCreate a RunnableLambda from a callable, and async callable or both.\nAccepts both sync and async variants to allow providing efficient\nimplementations for sync and async execution.\nParameters\nfunc \u2013 Either sync or async callable\nafunc \u2013 An async callable that takes an input and returns an output.\nAttributes\nInputType\nThe type of the input to this runnable.\nOutputType\nThe type of the output of this runnable as a type annotation.\nconfig_specs\nList configurable fields for this runnable.\ninput_schema\nThe type of input this runnable accepts specified as a pydantic model.\noutput_schema\nThe type of output this runnable produces specified as a pydantic model.\nMethods\n__init__(func[,\u00a0afunc])\nCreate a RunnableLambda from a callable, and async callable or both.\nabatch(inputs[,\u00a0config,\u00a0return_exceptions])\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nainvoke(input[,\u00a0config])\nInvoke this runnable asynchronously.\nastream(input[,\u00a0config])\nDefault implementation of astream, which calls ainvoke.\nastream_log(input[,\u00a0config,\u00a0diff,\u00a0...])\nStream all output from a runnable, as reported to the callback system.\natransform(input[,\u00a0config])\nDefault implementation of atransform, which buffers input and calls astream.\nbatch(inputs[,\u00a0config,\u00a0return_exceptions])\nDefault implementation runs invoke in parallel using a thread pool executor.\nbind(**kwargs)\nBind arguments to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "91e216eb5365-2", "text": "bind(**kwargs)\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*[,\u00a0include])\nThe type of config this runnable accepts specified as a pydantic model.\nget_input_schema([config])\nThe pydantic schema for the input to this runnable.\nget_output_schema([config])\nGet a pydantic model that can be used to validate output to the runnable.\ninvoke(input[,\u00a0config])\nInvoke this runnable synchronously.\nmap()\nReturn a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input.\nstream(input[,\u00a0config])\nDefault implementation of stream, which calls invoke.\ntransform(input[,\u00a0config])\nDefault implementation of transform, which buffers input and then calls stream.\nwith_config([config])\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks,\u00a0*[,\u00a0...])\nAdd fallbacks to a runnable, returning a new Runnable.\nwith_listeners(*[,\u00a0on_start,\u00a0on_end,\u00a0on_error])\nBind lifecycle listeners to a Runnable, returning a new Runnable.\nwith_retry(*[,\u00a0retry_if_exception_type,\u00a0...])\nCreate a new Runnable that retries the original runnable on exceptions.\nwith_types(*[,\u00a0input_type,\u00a0output_type])\nBind input and output types to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "91e216eb5365-3", "text": "Bind input and output types to a Runnable, returning a new Runnable.\n__init__(func: Union[Union[Callable[[Input], Output], Callable[[Input, RunnableConfig], Output], Callable[[Input, CallbackManagerForChainRun], Output], Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]], Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]], afunc: Optional[Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]] = None) \u2192 None[source]\u00b6\nCreate a RunnableLambda from a callable, and async callable or both.\nAccepts both sync and async variants to allow providing efficient\nimplementations for sync and async execution.\nParameters\nfunc \u2013 Either sync or async callable\nafunc \u2013 An async callable that takes an input and returns an output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nInvoke this runnable asynchronously.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "91e216eb5365-4", "text": "Invoke this runnable asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "91e216eb5365-5", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nThe pydantic schema for the input to this runnable.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nInvoke this runnable synchronously.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "91e216eb5365-6", "text": "Return a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "91e216eb5365-7", "text": "on_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nExamples using RunnableLambda\u00b6\nsql_db.md\nRun arbitrary functions", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "bbf66f0b0d50-0", "text": "langchain.schema.runnable.base.RunnableEach\u00b6\nclass langchain.schema.runnable.base.RunnableEach[source]\u00b6\nBases: RunnableEachBase[Input, Output]\nA runnable that delegates calls to another runnable\nwith each element of the input sequence.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bound: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: List[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 List[Output]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "bbf66f0b0d50-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "bbf66f0b0d50-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 RunnableEach[Input, Output][source]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "bbf66f0b0d50-3", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "bbf66f0b0d50-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: List[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 List[Output]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "bbf66f0b0d50-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "bbf66f0b0d50-6", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 RunnableEach[Input, Output][source]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 RunnableEach[Input, Output][source]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "bbf66f0b0d50-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[List[langchain.schema.runnable.utils.Output]]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "bbf66f0b0d50-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "e2e1b5ce1d7c-0", "text": "langchain.schema.runnable.utils.ConfigurableFieldSingleOption\u00b6\nclass langchain.schema.runnable.utils.ConfigurableFieldSingleOption(id: str, options: Mapping[str, Any], default: str, name: Optional[str] = None, description: Optional[str] = None)[source]\u00b6\nA field that can be configured by the user with a default value.\nCreate new instance of ConfigurableFieldSingleOption(id, options, default, name, description)\nAttributes\ndefault\nAlias for field number 2\ndescription\nAlias for field number 4\nid\nAlias for field number 0\nname\nAlias for field number 3\noptions\nAlias for field number 1\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.ConfigurableFieldSingleOption.html"}
{"id": "c5797a5da699-0", "text": "langchain.schema.runnable.configurable.StrEnum\u00b6\nclass langchain.schema.runnable.configurable.StrEnum(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nA string enum.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.StrEnum.html"}
{"id": "acd8f82bbabe-0", "text": "langchain.schema.runnable.configurable.DynamicRunnable\u00b6\nclass langchain.schema.runnable.configurable.DynamicRunnable[source]\u00b6\nBases: RunnableSerializable[Input, Output]\nA Serializable Runnable that can be dynamically configured.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam default: langchain.schema.runnable.base.RunnableSerializable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "acd8f82bbabe-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "acd8f82bbabe-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "acd8f82bbabe-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "acd8f82bbabe-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "acd8f82bbabe-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "acd8f82bbabe-6", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "acd8f82bbabe-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "acd8f82bbabe-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "ca2fc64fbb6d-0", "text": "langchain.schema.runnable.utils.ConfigurableField\u00b6\nclass langchain.schema.runnable.utils.ConfigurableField(id: str, name: Optional[str] = None, description: Optional[str] = None, annotation: Optional[Any] = None)[source]\u00b6\nA field that can be configured by the user.\nCreate new instance of ConfigurableField(id, name, description, annotation)\nAttributes\nannotation\nAlias for field number 3\ndescription\nAlias for field number 2\nid\nAlias for field number 0\nname\nAlias for field number 1\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.ConfigurableField.html"}
{"id": "be314d7bb5ec-0", "text": "langchain.schema.runnable.base.RunnableBindingBase\u00b6\nclass langchain.schema.runnable.base.RunnableBindingBase[source]\u00b6\nBases: RunnableSerializable[Input, Output]\nA runnable that delegates calls to another runnable with a set of kwargs.\nUse only if creating a new RunnableBinding subclass with different __init__ args.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bound: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nparam config: langchain.schema.runnable.config.RunnableConfig [Optional]\u00b6\nparam config_factories: List[Callable[[langchain.schema.runnable.config.RunnableConfig], langchain.schema.runnable.config.RunnableConfig]] [Optional]\u00b6\nparam custom_input_type: Optional[Any] = None\u00b6\nparam custom_output_type: Optional[Any] = None\u00b6\nparam kwargs: Mapping[str, Any] [Optional]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "be314d7bb5ec-1", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "be314d7bb5ec-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "be314d7bb5ec-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "be314d7bb5ec-4", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "be314d7bb5ec-5", "text": "classmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "be314d7bb5ec-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "be314d7bb5ec-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "be314d7bb5ec-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "dad58b6aa148-0", "text": "langchain.schema.runnable.passthrough.aidentity\u00b6\nasync langchain.schema.runnable.passthrough.aidentity(x: Other) \u2192 Other[source]\u00b6\nAn async identity function", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.aidentity.html"}
{"id": "25c4de52b9b8-0", "text": "langchain.schema.runnable.utils.GetLambdaSource\u00b6\nclass langchain.schema.runnable.utils.GetLambdaSource[source]\u00b6\nGet the source code of a lambda function.\nInitialize the visitor.\nMethods\n__init__()\nInitialize the visitor.\ngeneric_visit(node)\nCalled if no explicit visitor function exists for a node.\nvisit(node)\nVisit a node.\nvisit_Constant(node)\nvisit_Lambda(node)\nVisit a lambda function.\n__init__() \u2192 None[source]\u00b6\nInitialize the visitor.\ngeneric_visit(node)\u00b6\nCalled if no explicit visitor function exists for a node.\nvisit(node)\u00b6\nVisit a node.\nvisit_Constant(node)\u00b6\nvisit_Lambda(node: Lambda) \u2192 Any[source]\u00b6\nVisit a lambda function.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.utils.GetLambdaSource.html"}
{"id": "e3ac21010b3e-0", "text": "langchain.schema.runnable.passthrough.RunnableAssign\u00b6\nclass langchain.schema.runnable.passthrough.RunnableAssign[source]\u00b6\nBases: RunnableSerializable[Dict[str, Any], Dict[str, Any]]\nA runnable that assigns key-value pairs to Dict[str, Any] inputs.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam mapper: langchain.schema.runnable.base.RunnableParallel[Dict[str, Any]] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any][source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Dict[str, Any]][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "e3ac21010b3e-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Dict[str, Any]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Dict[str, Any]][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "e3ac21010b3e-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "e3ac21010b3e-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "e3ac21010b3e-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any][source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "e3ac21010b3e-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Dict[str, Any]][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Dict[str, Any]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Dict[str, Any]][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "e3ac21010b3e-6", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "e3ac21010b3e-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "e3ac21010b3e-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "ec7aa9c77030-0", "text": "langchain.schema.runnable.base.RunnableGenerator\u00b6\nclass langchain.schema.runnable.base.RunnableGenerator(transform: Union[Callable[[Iterator[Input]], Iterator[Output]], Callable[[AsyncIterator[Input]], AsyncIterator[Output]]], atransform: Optional[Callable[[AsyncIterator[Input]], AsyncIterator[Output]]] = None)[source]\u00b6\nA runnable that runs a generator function.\nAttributes\nInputType\nThe type of input this runnable accepts specified as a type annotation.\nOutputType\nThe type of output this runnable produces specified as a type annotation.\nconfig_specs\nList configurable fields for this runnable.\ninput_schema\nThe type of input this runnable accepts specified as a pydantic model.\noutput_schema\nThe type of output this runnable produces specified as a pydantic model.\nMethods\n__init__(transform[,\u00a0atransform])\nabatch(inputs[,\u00a0config,\u00a0return_exceptions])\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nainvoke(input[,\u00a0config])\nDefault implementation of ainvoke, calls invoke from a thread.\nastream(input[,\u00a0config])\nDefault implementation of astream, which calls ainvoke.\nastream_log(input[,\u00a0config,\u00a0diff,\u00a0...])\nStream all output from a runnable, as reported to the callback system.\natransform(input[,\u00a0config])\nDefault implementation of atransform, which buffers input and calls astream.\nbatch(inputs[,\u00a0config,\u00a0return_exceptions])\nDefault implementation runs invoke in parallel using a thread pool executor.\nbind(**kwargs)\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*[,\u00a0include])\nThe type of config this runnable accepts specified as a pydantic model.\nget_input_schema([config])\nGet a pydantic model that can be used to validate input to the runnable.\nget_output_schema([config])", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "ec7aa9c77030-1", "text": "get_output_schema([config])\nGet a pydantic model that can be used to validate output to the runnable.\ninvoke(input[,\u00a0config])\nTransform a single input into an output.\nmap()\nReturn a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input.\nstream(input[,\u00a0config])\nDefault implementation of stream, which calls invoke.\ntransform(input[,\u00a0config])\nDefault implementation of transform, which buffers input and then calls stream.\nwith_config([config])\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks,\u00a0*[,\u00a0...])\nAdd fallbacks to a runnable, returning a new Runnable.\nwith_listeners(*[,\u00a0on_start,\u00a0on_end,\u00a0on_error])\nBind lifecycle listeners to a Runnable, returning a new Runnable.\nwith_retry(*[,\u00a0retry_if_exception_type,\u00a0...])\nCreate a new Runnable that retries the original runnable on exceptions.\nwith_types(*[,\u00a0input_type,\u00a0output_type])\nBind input and output types to a Runnable, returning a new Runnable.\n__init__(transform: Union[Callable[[Iterator[Input]], Iterator[Output]], Callable[[AsyncIterator[Input]], AsyncIterator[Output]]], atransform: Optional[Callable[[AsyncIterator[Input]], AsyncIterator[Output]]] = None) \u2192 None[source]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "ec7aa9c77030-2", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nastream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "ec7aa9c77030-3", "text": "The jsonpatch ops can be applied in order to construct state.\natransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "ec7aa9c77030-4", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "ec7aa9c77030-5", "text": "Subclasses should override this method if they support streaming output.\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "ec7aa9c77030-6", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "5614e378e6d6-0", "text": "langchain.schema.runnable.configurable.make_options_spec\u00b6\nlangchain.schema.runnable.configurable.make_options_spec(spec: Union[ConfigurableFieldSingleOption, ConfigurableFieldMultiOption], description: Optional[str]) \u2192 ConfigurableFieldSpec[source]\u00b6\nMake a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or\nConfigurableFieldMultiOption.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.make_options_spec.html"}
{"id": "c288d11208ee-0", "text": "langchain.schema.runnable.configurable.RunnableConfigurableFields\u00b6\nclass langchain.schema.runnable.configurable.RunnableConfigurableFields[source]\u00b6\nBases: DynamicRunnable[Input, Output]\nA Runnable that can be dynamically configured.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam default: langchain.schema.runnable.base.RunnableSerializable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nparam fields: Dict[str, Union[langchain.schema.runnable.utils.ConfigurableField, langchain.schema.runnable.utils.ConfigurableFieldSingleOption, langchain.schema.runnable.utils.ConfigurableFieldMultiOption]] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "c288d11208ee-1", "text": "Default implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "c288d11208ee-2", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output][source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "c288d11208ee-3", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "c288d11208ee-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "c288d11208ee-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "c288d11208ee-6", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "c288d11208ee-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "c288d11208ee-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "867445ce28eb-0", "text": "langchain.schema.runnable.base.Runnable\u00b6\nclass langchain.schema.runnable.base.Runnable[source]\u00b6\nA unit of work that can be invoked, batched, streamed, transformed and composed.\ninvoke/ainvoke: Transforms a single input into an output.\nbatch/abatch: Efficiently transforms multiple inputs into outputs.\nstream/astream: Streams output from a single input as it\u2019s produced.\nastream_log: Streams output and selected intermediate results from an input.\nBuilt-in optimizations:\nBatch: By default, batch runs invoke() in parallel using a thread pool executor.Override to optimize batching.\nAsync: Methods with \u201ca\u201d suffix are asynchronous. By default, they executethe sync counterpart using asyncio\u2019s thread pool.\nOverride for native async.\nAll methods accept an optional config argument, which can be used to configure\nexecution, add tags and metadata for tracing and debugging etc.\nRunnables expose schematic information about their input, output and config via\nthe input_schema property, the output_schema property and config_schema method.\nThe LangChain Expression Language (LCEL) is a declarative way to compose Runnables\ninto chains. Any chain constructed this way will automatically have sync, async,\nbatch, and streaming support.\nThe main composition primitives are RunnableSequence and RunnableParallel.\nRunnableSequence invokes a series of runnables sequentially, with one runnable\u2019s\noutput serving as the next\u2019s input. Construct using the | operator or by\npassing a list of runnables to RunnableSequence.\nRunnableParallel invokes runnables concurrently, providing the same input\nto each. Construct it using a dict literal within a sequence or by passing a\ndict to RunnableParallel.\nFor example,\nfrom langchain.schema.runnable import RunnableLambda\n# A RunnableSequence constructed using the `|` operator", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.Runnable.html"}
{"id": "867445ce28eb-1", "text": "# A RunnableSequence constructed using the `|` operator\nsequence = RunnableLambda(lambda x: x + 1) | RunnableLambda(lambda x: x * 2)\nsequence.invoke(1) # 4\nsequence.batch([1, 2, 3]) # [4, 6, 8]\n# A sequence that contains a RunnableParallel constructed using a dict literal\nsequence = RunnableLambda(lambda x: x + 1) | {\n    'mul_2': RunnableLambda(lambda x: x * 2),\n    'mul_5': RunnableLambda(lambda x: x * 5)\n}\nsequence.invoke(1) # {'mul_2': 4, 'mul_5': 10}\nAll Runnables expose additional methods that can be used to modify their behavior\n(e.g., add a retry policy, add lifecycle listeners, make them configurable, etc.).\nThese methods will work on any Runnable, including Runnable chains constructed\nby composing other Runnables. See the individual methods for details.\nFor example,\nfrom langchain.schema.runnable import RunnableLambda\nimport random\ndef add_one(x: int) -> int:\n    return x + 1\ndef buggy_double(y: int) -> int:\n    '''Buggy code that will fail 70% of the time'''\n    if random.random() > 0.3:\n        print('This code failed, and will probably be retried!')\n        raise ValueError('Triggered buggy code')\n    return y * 2\nsequence = (\n    RunnableLambda(add_one) |\n    RunnableLambda(buggy_double).with_retry( # Retry on failure\n        stop_after_attempt=10,\n        wait_exponential_jitter=False\n    )\n)\nprint(sequence.input_schema.schema()) # Show inferred input schema\nprint(sequence.output_schema.schema()) # Show inferred output schema", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.Runnable.html"}
{"id": "867445ce28eb-2", "text": "print(sequence.output_schema.schema()) # Show inferred output schema\nprint(sequence.invoke(2)) # invoke the sequence (note the retry above!!)\nAs the chains get longer, it can be useful to be able to see intermediate results\nto debug and trace the chain.\nYou can set the global debug flag to True to enable debug output for all chains:\nfrom langchain.globals import set_debug\nset_debug(True)\nAlternatively, you can pass existing or custom callbacks to any given chain:\n\u2026 code-block:: python\nfrom langchain.callbacks.tracers import ConsoleCallbackHandler\nchain.invoke(\u2026,\nconfig={\u2018callbacks\u2019: [ConsoleCallbackHandler()]}\n)\nFor a UI (and much more) checkout LangSmith: https://docs.smith.langchain.com/\nAttributes\nInputType\nThe type of input this runnable accepts specified as a type annotation.\nOutputType\nThe type of output this runnable produces specified as a type annotation.\nconfig_specs\nList configurable fields for this runnable.\ninput_schema\nThe type of input this runnable accepts specified as a pydantic model.\noutput_schema\nThe type of output this runnable produces specified as a pydantic model.\nMethods\n__init__()\nabatch(inputs[,\u00a0config,\u00a0return_exceptions])\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nainvoke(input[,\u00a0config])\nDefault implementation of ainvoke, calls invoke from a thread.\nastream(input[,\u00a0config])\nDefault implementation of astream, which calls ainvoke.\nastream_log()\nStream all output from a runnable, as reported to the callback system.\natransform(input[,\u00a0config])\nDefault implementation of atransform, which buffers input and calls astream.\nbatch(inputs[,\u00a0config,\u00a0return_exceptions])\nDefault implementation runs invoke in parallel using a thread pool executor.\nbind(**kwargs)", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.Runnable.html"}
{"id": "867445ce28eb-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nbind(**kwargs)\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*[,\u00a0include])\nThe type of config this runnable accepts specified as a pydantic model.\nget_input_schema([config])\nGet a pydantic model that can be used to validate input to the runnable.\nget_output_schema([config])\nGet a pydantic model that can be used to validate output to the runnable.\ninvoke(input[,\u00a0config])\nTransform a single input into an output.\nmap()\nReturn a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input.\nstream(input[,\u00a0config])\nDefault implementation of stream, which calls invoke.\ntransform(input[,\u00a0config])\nDefault implementation of transform, which buffers input and then calls stream.\nwith_config([config])\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks,\u00a0*[,\u00a0...])\nAdd fallbacks to a runnable, returning a new Runnable.\nwith_listeners(*[,\u00a0on_start,\u00a0on_end,\u00a0on_error])\nBind lifecycle listeners to a Runnable, returning a new Runnable.\nwith_retry(*[,\u00a0retry_if_exception_type,\u00a0...])\nCreate a new Runnable that retries the original runnable on exceptions.\nwith_types(*[,\u00a0input_type,\u00a0output_type])\nBind input and output types to a Runnable, returning a new Runnable.\n__init__()\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.Runnable.html"}
{"id": "867445ce28eb-4", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: Literal[True] = 'True', include_names: Optional[Sequence[str]] = 'None', include_types: Optional[Sequence[str]] = 'None', include_tags: Optional[Sequence[str]] = 'None', exclude_names: Optional[Sequence[str]] = 'None', exclude_types: Optional[Sequence[str]] = 'None', exclude_tags: Optional[Sequence[str]] = 'None', **kwargs: Optional[Any]) \u2192 AsyncIterator[RunLogPatch][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.Runnable.html"}
{"id": "867445ce28eb-5", "text": "async astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: Literal[False], include_names: Optional[Sequence[str]] = 'None', include_types: Optional[Sequence[str]] = 'None', include_tags: Optional[Sequence[str]] = 'None', exclude_names: Optional[Sequence[str]] = 'None', exclude_types: Optional[Sequence[str]] = 'None', exclude_tags: Optional[Sequence[str]] = 'None', **kwargs: Optional[Any]) \u2192 AsyncIterator[RunLog]\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.Runnable.html"}
{"id": "867445ce28eb-6", "text": "bind(**kwargs: Any) \u2192 Runnable[Input, Output][source]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel][source]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nabstract invoke(input: Input, config: Optional[RunnableConfig] = None) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.Runnable.html"}
{"id": "867445ce28eb-7", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nmap() \u2192 Runnable[List[Input], List[Output]][source]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output][source]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output][source]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.Runnable.html"}
{"id": "867445ce28eb-8", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output][source]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output][source]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output][source]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.Runnable.html"}
{"id": "be89f6ba731b-0", "text": "langchain.schema.runnable.history.RunnableWithMessageHistory\u00b6\nclass langchain.schema.runnable.history.RunnableWithMessageHistory[source]\u00b6\nBases: RunnableBindingBase\nA runnable that manages chat message history for another runnable.\nBase runnable must have inputs and outputs that can be converted to a list ofBaseMessages.\nRunnableWithMessageHistory must always be called with a config that contains session_id, e.g.:{\"configurable\": {\"session_id\": \"<SESSION_ID>\"}}\nExample (dict input):from typing import Optional\nfrom langchain.chat_models import ChatAnthropic\nfrom langchain.memory.chat_message_histories import RedisChatMessageHistory\nfrom langchain.prompts import ChatPromptTemplate, MessagesPlaceholder\nfrom langchain.schema.runnable.history import RunnableWithMessageHistory\nprompt = ChatPromptTemplate.from_messages([\n    (\"system\", \"You're an assistant who's good at {ability}\"),\n    MessagesPlaceholder(variable_name=\"history\"),\n    (\"human\", \"{question}\"),\n])\nchain = prompt | ChatAnthropic(model=\"claude-2\")\nchain_with_history = RunnableWithMessageHistory(\n    chain,\n    RedisChatMessageHistory,\n    input_messages_key=\"question\",\n    history_messages_key=\"history\",\n)\nchain_with_history.invoke(\n    {\"ability\": \"math\", \"question\": \"What does cosine mean?\"},\n    config={\"configurable\": {\"session_id\": \"foo\"}}\n)\n# -> \"Cosine is ...\"\nchain_with_history.invoke(\n    {\"ability\": \"math\", \"question\": \"What's its inverse\"},\n    config={\"configurable\": {\"session_id\": \"foo\"}}\n)\n# -> \"The inverse of cosine is called arccosine ...\"\nInitialize RunnableWithMessageHistory.\nParameters\nrunnable \u2013 The base Runnable to be wrapped.\nMust take as input one of:\n- A sequence of BaseMessages", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "be89f6ba731b-1", "text": "Must take as input one of:\n- A sequence of BaseMessages\n- A dict with one key for all messages\n- A dict with one key for the current input string/message(s) and\na separate key for historical messages. If the input key points\nto a string, it will be treated as a HumanMessage in history.\nMust return as output one of:\n- A string which can be treated as an AIMessage\n- A BaseMessage or sequence of BaseMessages\n- A dict with a key for a BaseMessage or sequence of BaseMessages\nget_session_history \u2013 Function that returns a new BaseChatMessageHistory\ngiven a session id. Should take a single\npositional argument session_id which is a string and a named argument\nuser_id which can be a string or None. e.g.:\n```python\ndef get_session_history(\nsession_id: str,\n*,\nuser_id: Optional[str]=None\n) -> BaseChatMessageHistory:\u2026\n```\ninput_messages_key \u2013 Must be specified if the base runnable accepts a dict\nas input.\noutput_messages_key \u2013 Must be specified if the base runnable returns a dict\nas output.\nhistory_messages_key \u2013 Must be specified if the base runnable accepts a dict\nas input and expects a separate key for historical messages.\n**kwargs \u2013 Arbitrary additional kwargs to pass to parent class\nRunnableBindingBase init.\nparam bound: Runnable[Input, Output] [Required]\u00b6\nparam config: RunnableConfig [Optional]\u00b6\nparam config_factories: List[Callable[[RunnableConfig], RunnableConfig]] [Optional]\u00b6\nparam custom_input_type: Optional[Any] = None\u00b6\nparam custom_output_type: Optional[Any] = None\u00b6\nparam get_session_history: GetSessionHistoryCallable [Required]\u00b6\nparam history_messages_key: Optional[str] = None\u00b6\nparam input_messages_key: Optional[str] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "be89f6ba731b-2", "text": "param input_messages_key: Optional[str] = None\u00b6\nparam kwargs: Mapping[str, Any] [Optional]\u00b6\nparam output_messages_key: Optional[str] = None\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "be89f6ba731b-3", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "be89f6ba731b-4", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "be89f6ba731b-5", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "be89f6ba731b-6", "text": "This method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "be89f6ba731b-7", "text": "Return a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "be89f6ba731b-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "be89f6ba731b-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "36314980203a-0", "text": "langchain.schema.runnable.config.merge_configs\u00b6\nlangchain.schema.runnable.config.merge_configs(*configs: Optional[RunnableConfig]) \u2192 RunnableConfig[source]\u00b6\nMerge multiple configs into one.\nParameters\n*configs (Optional[RunnableConfig]) \u2013 The configs to merge.\nReturns\nThe merged config.\nReturn type\nRunnableConfig", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.config.merge_configs.html"}
{"id": "d57d4f5266e1-0", "text": "langchain.schema.runnable.base.RunnableSerializable\u00b6\nclass langchain.schema.runnable.base.RunnableSerializable[source]\u00b6\nBases: Serializable, Runnable[Input, Output]\nA Runnable that can be serialized to JSON.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "d57d4f5266e1-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "d57d4f5266e1-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output][source]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output][source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "d57d4f5266e1-3", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "d57d4f5266e1-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nabstract invoke(input: Input, config: Optional[RunnableConfig] = None) \u2192 Output\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "d57d4f5266e1-5", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "d57d4f5266e1-6", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "d57d4f5266e1-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "d57d4f5266e1-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema.runnable/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "13208d0e0461-0", "text": "langchain.evaluation.regex_match.base.RegexMatchStringEvaluator\u00b6\nclass langchain.evaluation.regex_match.base.RegexMatchStringEvaluator(*, flags: int = 0, **kwargs: Any)[source]\u00b6\nCompute a regex match between the prediction and the reference.\nExamples\n>>> evaluator = RegexMatchStringEvaluator(flags=re.IGNORECASE)\n>>> evaluator.evaluate_strings(\n        prediction=\"Mindy is the CTO\",\n        reference=\"^mindy.*cto$\",\n    )  # This will return {'score': 1.0} due to the IGNORECASE flag\n>>> evaluator = RegexMatchStringEvaluator()\n>>> evaluator.evaluate_strings(\n        prediction=\"Mindy is the CTO\",\n        reference=\"^Mike.*CEO$\",\n    )  # This will return {'score': 0.0}\n>>> evaluator.evaluate_strings(\n        prediction=\"Mindy is the CTO\",\n        reference=\"^Mike.*CEO$|^Mindy.*CTO$\",\n    )  # This will return {'score': 1.0} as the prediction matches the second pattern in the union\nAttributes\nevaluation_name\nGet the evaluation name.\ninput_keys\nGet the input keys.\nrequires_input\nThis evaluator does not require input.\nrequires_reference\nThis evaluator requires a reference.\nMethods\n__init__(*[,\u00a0flags])\naevaluate_strings(*,\u00a0prediction[,\u00a0...])\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nevaluate_strings(*,\u00a0prediction[,\u00a0reference,\u00a0...])\nEvaluate Chain or LLM output, based on optional input and label.\n__init__(*, flags: int = 0, **kwargs: Any)[source]\u00b6\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.regex_match.base.RegexMatchStringEvaluator.html"}
{"id": "13208d0e0461-1", "text": "Asynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.regex_match.base.RegexMatchStringEvaluator.html"}
{"id": "ddf5c79089a9-0", "text": "langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEval\u00b6\nclass langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEval[source]\u00b6\nA named tuple containing the score and reasoning for a trajectory.\nscore: float\u00b6\nThe score for the trajectory, normalized from 0 to 1.\nreasoning: str\u00b6\nThe reasoning for the score.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEval.html"}
{"id": "c674d62d6b9e-0", "text": "langchain.evaluation.criteria.eval_chain.CriteriaResultOutputParser\u00b6\nclass langchain.evaluation.criteria.eval_chain.CriteriaResultOutputParser[source]\u00b6\nBases: BaseOutputParser[dict]\nA parser for the output of the CriteriaEvalChain.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaResultOutputParser.html"}
{"id": "c674d62d6b9e-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaResultOutputParser.html"}
{"id": "c674d62d6b9e-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaResultOutputParser.html"}
{"id": "c674d62d6b9e-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaResultOutputParser.html"}
{"id": "c674d62d6b9e-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaResultOutputParser.html"}
{"id": "c674d62d6b9e-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Dict[str, Any][source]\u00b6\nParse the output text.\nParameters\ntext (str) \u2013 The output text to parse.\nReturns\nThe parsed output.\nReturn type\nDict\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaResultOutputParser.html"}
{"id": "c674d62d6b9e-6", "text": "prompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaResultOutputParser.html"}
{"id": "c674d62d6b9e-7", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaResultOutputParser.html"}
{"id": "c674d62d6b9e-8", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaResultOutputParser.html"}
{"id": "a5aa86d5bf55-0", "text": "langchain.evaluation.exact_match.base.ExactMatchStringEvaluator\u00b6\nclass langchain.evaluation.exact_match.base.ExactMatchStringEvaluator(*, ignore_case: bool = False, ignore_punctuation: bool = False, ignore_numbers: bool = False, **kwargs: Any)[source]\u00b6\nCompute an exact match between the prediction and the reference.\nExamples\n>>> evaluator = ExactMatchChain()\n>>> evaluator.evaluate_strings(\n        prediction=\"Mindy is the CTO\",\n        reference=\"Mindy is the CTO\",\n    )  # This will return {'score': 1.0}\n>>> evaluator.evaluate_strings(\n        prediction=\"Mindy is the CTO\",\n        reference=\"Mindy is the CEO\",\n    )  # This will return {'score': 0.0}\nAttributes\nevaluation_name\nGet the evaluation name.\ninput_keys\nGet the input keys.\nrequires_input\nThis evaluator does not require input.\nrequires_reference\nThis evaluator requires a reference.\nMethods\n__init__(*[,\u00a0ignore_case,\u00a0...])\naevaluate_strings(*,\u00a0prediction[,\u00a0...])\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nevaluate_strings(*,\u00a0prediction[,\u00a0reference,\u00a0...])\nEvaluate Chain or LLM output, based on optional input and label.\n__init__(*, ignore_case: bool = False, ignore_punctuation: bool = False, ignore_numbers: bool = False, **kwargs: Any)[source]\u00b6\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.exact_match.base.ExactMatchStringEvaluator.html"}
{"id": "a5aa86d5bf55-1", "text": "Parameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.exact_match.base.ExactMatchStringEvaluator.html"}
{"id": "d87ea9743bb8-0", "text": "langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain\u00b6\nclass langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain[source]\u00b6\nBases: CriteriaEvalChain\nCriteria evaluation chain that requires references.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam criterion_name: str [Required]\u00b6\nThe name of the criterion being evaluated.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseOutputParser [Optional]\u00b6\nThe parser to use to map the output to a structured result.\nparam prompt: BasePromptTemplate [Required]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-1", "text": "param prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-2", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-4", "text": "Asynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-5", "text": "**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-6", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-7", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-8", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-9", "text": "Evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nclassmethod from_llm(llm: BaseLanguageModel, criteria: Optional[Union[Mapping[str, str], Criteria, ConstitutionalPrinciple]] = None, *, prompt: Optional[BasePromptTemplate] = None, **kwargs: Any) \u2192 CriteriaEvalChain[source]\u00b6\nCreate a LabeledCriteriaEvalChain instance from an llm and criteria.\nParameters\nllm (BaseLanguageModel) \u2013 The language model to use for evaluation.\ncriteria (CRITERIA_TYPE - default=None for \"helpfulness\") \u2013 \nThe criteria to evaluate the runs against. It can be:\na mapping of a criterion name to its description\na single criterion name present in one of the default criteria\na single ConstitutionalPrinciple instance\nprompt (Optional[BasePromptTemplate], default=None) \u2013 The prompt template to use for generating prompts. If not provided,\na default prompt will be used.\n**kwargs (Any) \u2013 Additional keyword arguments to pass to the LLMChain\nconstructor.\nReturns\nAn instance of the LabeledCriteriaEvalChain class.\nReturn type\nLabeledCriteriaEvalChain\nExamples\n>>> from langchain.llms import OpenAI\n>>> from langchain.evaluation.criteria import LabeledCriteriaEvalChain\n>>> llm = OpenAI()\n>>> criteria = {\n        \"hallucination\": (\n            \"Does this submission contain information\"\n            \" not present in the input or reference?\"\n        ),\n    }", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-10", "text": "\" not present in the input or reference?\"\n        ),\n    }\n>>> chain = LabeledCriteriaEvalChain.from_llm(\n        llm=llm,\n        criteria=criteria,\n    )\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-11", "text": "This method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-12", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-13", "text": "Returns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nclassmethod resolve_criteria(criteria: Optional[Union[Mapping[str, str], Criteria, ConstitutionalPrinciple, str]]) \u2192 Dict[str, str]\u00b6\nResolve the criteria to evaluate.\nParameters\ncriteria (CRITERIA_TYPE) \u2013 \nThe criteria to evaluate the runs against. It can be:\na mapping of a criterion name to its description\na single criterion name present in one of the default criteria\na single ConstitutionalPrinciple instance\nReturns\nA dictionary mapping criterion names to descriptions.\nReturn type\nDict[str, str]\nExamples\n>>> criterion = \"relevance\"\n>>> CriteriaEvalChain.resolve_criteria(criteria)\n{'relevance': 'Is the submission referring to a real quote from the text?'}\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-14", "text": "Convenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-15", "text": "Example\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-16", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "d87ea9743bb8-17", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty evaluation_name: str\u00b6\nGet the name of the evaluation.\nReturns\nThe name of the evaluation.\nReturn type\nstr\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nWhether this evaluator requires an input string.\nproperty requires_reference: bool\u00b6\nWhether the evaluation requires a reference text.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.LabeledCriteriaEvalChain.html"}
{"id": "7200e6c87d13-0", "text": "langchain.evaluation.schema.LLMEvalChain\u00b6\nclass langchain.evaluation.schema.LLMEvalChain[source]\u00b6\nBases: Chain\nA base class for evaluators that use an LLM.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7200e6c87d13-1", "text": "You can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7200e6c87d13-2", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7200e6c87d13-3", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7200e6c87d13-4", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7200e6c87d13-5", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7200e6c87d13-6", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7200e6c87d13-7", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nabstract classmethod from_llm(llm: BaseLanguageModel, **kwargs: Any) \u2192 LLMEvalChain[source]\u00b6\nCreate a new evaluator from an LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7200e6c87d13-8", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7200e6c87d13-9", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7200e6c87d13-10", "text": "The main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7200e6c87d13-11", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7200e6c87d13-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7200e6c87d13-13", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nabstract property input_keys: List[str]\u00b6\nKeys expected to be in the chain input.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nabstract property output_keys: List[str]\u00b6\nKeys expected to be in the chain output.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.LLMEvalChain.html"}
{"id": "7090f9c69c8a-0", "text": "langchain.evaluation.qa.eval_chain.ContextQAEvalChain\u00b6\nclass langchain.evaluation.qa.eval_chain.ContextQAEvalChain[source]\u00b6\nBases: LLMChain, StringEvaluator, LLMEvalChain\nLLM Chain for evaluating QA w/o GT based on context\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-1", "text": "Defaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-2", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-4", "text": "Asynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-5", "text": "**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-6", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-7", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-8", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-9", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate(examples: List[dict], predictions: List[dict], question_key: str = 'query', context_key: str = 'context', prediction_key: str = 'result', *, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[dict][source]\u00b6\nEvaluate question answering examples and predictions.\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nclassmethod from_llm(llm: BaseLanguageModel, prompt: Optional[PromptTemplate] = None, **kwargs: Any) \u2192 ContextQAEvalChain[source]\u00b6\nLoad QA Eval Chain from LLM.\nParameters\nllm (BaseLanguageModel) \u2013 the base language model to use.\nprompt ('context' and 'result' that will be used as the) \u2013 A prompt template containing the input_variables:\n'query' \u2013 \nprompt \u2013 \nevaluation. (for) \u2013 \nPROMPT. (Defaults to) \u2013 \n**kwargs \u2013 additional keyword arguments.\nReturns\nthe loaded QA eval chain.\nReturn type\nContextQAEvalChain\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-10", "text": "classmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-11", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-12", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-13", "text": "Returns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-14", "text": "question = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-15", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "7090f9c69c8a-16", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty evaluation_name: str\u00b6\nThe name of the evaluation.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nWhether the chain requires an input string.\nproperty requires_reference: bool\u00b6\nWhether the chain requires a reference string.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.ContextQAEvalChain.html"}
{"id": "bbacb63116c2-0", "text": "langchain.evaluation.qa.generate_chain.QAGenerateChain\u00b6\nclass langchain.evaluation.qa.generate_chain.QAGenerateChain[source]\u00b6\nBases: LLMChain\nLLM Chain for generating examples for question answering.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_key: str = 'qa_pairs'\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-1", "text": "param output_key: str = 'qa_pairs'\u00b6\nparam output_parser: BaseLLMOutputParser = RegexParser(regex='QUESTION: (.*?)\\\\n+ANSWER: (.*)', output_keys=['query', 'answer'])\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-2", "text": "memory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-3", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-4", "text": "Generate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-5", "text": "Prepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-6", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-7", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-8", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, **kwargs: Any) \u2192 QAGenerateChain[source]\u00b6\nLoad QA Generate Chain from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-9", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-11", "text": "Parameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-12", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-13", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-14", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "bbacb63116c2-15", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.generate_chain.QAGenerateChain.html"}
{"id": "5a6e6d8dece0-0", "text": "langchain.evaluation.criteria.eval_chain.resolve_criteria\u00b6\nlangchain.evaluation.criteria.eval_chain.resolve_criteria(criteria: Optional[Union[Mapping[str, str], Criteria, ConstitutionalPrinciple, str]]) \u2192 Dict[str, str][source]\u00b6\nResolve the criteria to evaluate.\nParameters\ncriteria (CRITERIA_TYPE) \u2013 \nThe criteria to evaluate the runs against. It can be:\na mapping of a criterion name to its description\na single criterion name present in one of the default criteria\na single ConstitutionalPrinciple instance\nReturns\nA dictionary mapping criterion names to descriptions.\nReturn type\nDict[str, str]\nExamples\n>>> criterion = \"relevance\"\n>>> CriteriaEvalChain.resolve_criteria(criteria)\n{'relevance': 'Is the submission referring to a real quote from the text?'}", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.resolve_criteria.html"}
{"id": "5fb8425d8d9b-0", "text": "langchain.evaluation.string_distance.base.StringDistance\u00b6\nclass langchain.evaluation.string_distance.base.StringDistance(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nDistance metric to use.\nDAMERAU_LEVENSHTEIN\u00b6\nThe Damerau-Levenshtein distance.\nLEVENSHTEIN\u00b6\nThe Levenshtein distance.\nJARO\u00b6\nThe Jaro distance.\nJARO_WINKLER\u00b6\nThe Jaro-Winkler distance.\nHAMMING\u00b6\nThe Hamming distance.\nINDEL\u00b6\nThe Indel distance.\nDAMERAU_LEVENSHTEIN = 'damerau_levenshtein'\u00b6\nLEVENSHTEIN = 'levenshtein'\u00b6\nJARO = 'jaro'\u00b6\nJARO_WINKLER = 'jaro_winkler'\u00b6\nHAMMING = 'hamming'\u00b6\nINDEL = 'indel'\u00b6\nExamples using StringDistance\u00b6\nString Distance", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistance.html"}
{"id": "d5dc544b6b17-0", "text": "langchain.evaluation.qa.eval_chain.CotQAEvalChain\u00b6\nclass langchain.evaluation.qa.eval_chain.CotQAEvalChain[source]\u00b6\nBases: ContextQAEvalChain\nLLM Chain for evaluating QA using chain of thought reasoning.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_key: str = 'text'\u00b6\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-1", "text": "Defaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-2", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-4", "text": "Asynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-5", "text": "**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-6", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-7", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-8", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-9", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate(examples: List[dict], predictions: List[dict], question_key: str = 'query', context_key: str = 'context', prediction_key: str = 'result', *, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[dict]\u00b6\nEvaluate question answering examples and predictions.\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nclassmethod from_llm(llm: BaseLanguageModel, prompt: Optional[PromptTemplate] = None, **kwargs: Any) \u2192 CotQAEvalChain[source]\u00b6\nLoad QA Eval Chain from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-10", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-11", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-12", "text": "Parameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-13", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-14", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-15", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "d5dc544b6b17-16", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty evaluation_name: str\u00b6\nThe name of the evaluation.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nWhether the chain requires an input string.\nproperty requires_reference: bool\u00b6\nWhether the chain requires a reference string.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.CotQAEvalChain.html"}
{"id": "304c1686137f-0", "text": "langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain\u00b6\nclass langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain[source]\u00b6\nBases: PairwiseStringEvalChain\nA chain for comparing two outputs, such as the outputsof two models, prompts, or outputs of a single model on similar inputs,\nwith labeled preferences.\noutput_parser\u00b6\nThe output parser for the chain.\nType\nBaseOutputParser\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-1", "text": "You can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-2", "text": "response. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_string_pairs(*, prediction: str, prediction_b: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate the output string pairs.\nParameters", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-4", "text": "Asynchronously evaluate the output string pairs.\nParameters\nprediction (str) \u2013 The output string from the first model.\nprediction_b (str) \u2013 The output string from the second model.\nreference (Optional[str], optional) \u2013 The expected output / reference string.\ninput (Optional[str], optional) \u2013 The input string.\n**kwargs \u2013 Additional keyword arguments, such as callbacks and optional reference strings.\nReturns\nA dictionary containing the preference, scores, and/or other information.\nReturn type\ndict\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-5", "text": "Parameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-6", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-7", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-8", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate_string_pairs(*, prediction: str, prediction_b: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate the output string pairs.\nParameters", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-9", "text": "Evaluate the output string pairs.\nParameters\nprediction (str) \u2013 The output string from the first model.\nprediction_b (str) \u2013 The output string from the second model.\nreference (Optional[str], optional) \u2013 The expected output / reference string.\ninput (Optional[str], optional) \u2013 The input string.\n**kwargs \u2013 Additional keyword arguments, such as callbacks and optional reference strings.\nReturns\nA dictionary containing the preference, scores, and/or other information.\nReturn type\ndict\nclassmethod from_llm(llm: BaseLanguageModel, *, prompt: Optional[PromptTemplate] = None, criteria: Optional[Union[Mapping[str, str], Criteria, ConstitutionalPrinciple, str]] = None, **kwargs: Any) \u2192 PairwiseStringEvalChain[source]\u00b6\nInitialize the LabeledPairwiseStringEvalChain from an LLM.\nParameters\nllm (BaseLanguageModel) \u2013 The LLM to use.\nprompt (PromptTemplate, optional) \u2013 The prompt to use.\ncriteria (Union[CRITERIA_TYPE, str], optional) \u2013 The criteria to use.\n**kwargs (Any) \u2013 Additional keyword arguments.\nReturns\nThe initialized LabeledPairwiseStringEvalChain.\nReturn type\nLabeledPairwiseStringEvalChain\nRaises\nValueError \u2013 If the input variables are not as expected.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-10", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-11", "text": "for more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-12", "text": "Format prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-13", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-14", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-15", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "304c1686137f-16", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nReturn whether the chain requires an input.\nReturns\nTrue if the chain requires an input, False otherwise.\nReturn type\nbool\nproperty requires_reference: bool\u00b6\nReturn whether the chain requires a reference.\nReturns\nTrue if the chain requires a reference, False otherwise.\nReturn type\nbool", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.LabeledPairwiseStringEvalChain.html"}
{"id": "17bce0b92aba-0", "text": "langchain.evaluation.agents.trajectory_eval_chain.TrajectoryOutputParser\u00b6\nclass langchain.evaluation.agents.trajectory_eval_chain.TrajectoryOutputParser[source]\u00b6\nBases: BaseOutputParser\nTrajectory output parser.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryOutputParser.html"}
{"id": "17bce0b92aba-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryOutputParser.html"}
{"id": "17bce0b92aba-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryOutputParser.html"}
{"id": "17bce0b92aba-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryOutputParser.html"}
{"id": "17bce0b92aba-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryOutputParser.html"}
{"id": "17bce0b92aba-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 TrajectoryEval[source]\u00b6\nParse the output text and extract the score and reasoning.\nParameters\ntext (str) \u2013 The output text to parse.\nReturns\nA named tuple containing the normalized score and reasoning.\nReturn type\nTrajectoryEval\nRaises\nOutputParserException \u2013 If the score is not found in the output text or\n    if the LLM\u2019s score is not a digit in the range 1-5.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryOutputParser.html"}
{"id": "17bce0b92aba-6", "text": "The prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryOutputParser.html"}
{"id": "17bce0b92aba-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryOutputParser.html"}
{"id": "17bce0b92aba-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryOutputParser.html"}
{"id": "c39382d84a22-0", "text": "langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain\u00b6\nclass langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain[source]\u00b6\nBases: PairwiseStringEvaluator, LLMEvalChain, LLMChain\nA chain for comparing two outputs, such as the outputsof two models, prompts, or outputs of a single model on similar inputs.\noutput_parser\u00b6\nThe output parser for the chain.\nType\nBaseOutputParser\nExample\n>>> from langchain.chat_models import ChatOpenAI\n>>> from langchain.evaluation.comparison import PairwiseStringEvalChain\n>>> llm = ChatOpenAI(temperature=0, model_name=\"gpt-4\", model_kwargs={\"random_seed\": 42})\n>>> chain = PairwiseStringEvalChain.from_llm(llm=llm)\n>>> result = chain.evaluate_string_pairs(\n...     input = \"What is the chemical formula for water?\",\n...     prediction = \"H2O\",\n...     prediction_b = (\n...        \"The chemical formula for water is H2O, which means\"\n...        \" there are two hydrogen atoms and one oxygen atom.\"\n...     reference = \"The chemical formula for water is H2O.\",\n... )\n>>> print(result)\n# {\n#    \"value\": \"B\",\n#    \"comment\": \"Both responses accurately state\"\n#       \" that the chemical formula for water is H2O.\"\n#       \" However, Response B provides additional information\"\n# .     \" by explaining what the formula means.\\n[[B]]\"\n# }\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-1", "text": "Callback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-2", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-3", "text": "to False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-4", "text": "memory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_string_pairs(*, prediction: str, prediction_b: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate the output string pairs.\nParameters\nprediction (str) \u2013 The output string from the first model.\nprediction_b (str) \u2013 The output string from the second model.\nreference (Optional[str], optional) \u2013 The expected output / reference string.\ninput (Optional[str], optional) \u2013 The input string.\n**kwargs \u2013 Additional keyword arguments, such as callbacks and optional reference strings.\nReturns\nA dictionary containing the preference, scores, and/or other information.\nReturn type\ndict\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-5", "text": "Generate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-6", "text": "Prepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-7", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-8", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-9", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate_string_pairs(*, prediction: str, prediction_b: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate the output string pairs.\nParameters\nprediction (str) \u2013 The output string from the first model.\nprediction_b (str) \u2013 The output string from the second model.\nreference (Optional[str], optional) \u2013 The expected output / reference string.\ninput (Optional[str], optional) \u2013 The input string.\n**kwargs \u2013 Additional keyword arguments, such as callbacks and optional reference strings.\nReturns\nA dictionary containing the preference, scores, and/or other information.\nReturn type\ndict", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-10", "text": "A dictionary containing the preference, scores, and/or other information.\nReturn type\ndict\nclassmethod from_llm(llm: BaseLanguageModel, *, prompt: Optional[PromptTemplate] = None, criteria: Optional[Union[Mapping[str, str], Criteria, ConstitutionalPrinciple, str]] = None, **kwargs: Any) \u2192 PairwiseStringEvalChain[source]\u00b6\nInitialize the PairwiseStringEvalChain from an LLM.\nParameters\nllm (BaseChatModel) \u2013 The LLM to use (GPT-4 recommended).\nprompt (PromptTemplate, optional) \u2013 The prompt to use.\n**kwargs (Any) \u2013 Additional keyword arguments.\nReturns\nThe initialized PairwiseStringEvalChain.\nReturn type\nPairwiseStringEvalChain\nRaises\nValueError \u2013 If the input variables are not as expected.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-11", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-12", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-13", "text": "Parameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-14", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-15", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-16", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "c39382d84a22-17", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nReturn whether the chain requires an input.\nReturns\nTrue if the chain requires an input, False otherwise.\nReturn type\nbool\nproperty requires_reference: bool\u00b6\nReturn whether the chain requires a reference.\nReturns\nTrue if the chain requires a reference, False otherwise.\nReturn type\nbool", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain.html"}
{"id": "9d795f6a2a82-0", "text": "langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain\u00b6\nclass langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain[source]\u00b6\nBases: StringEvaluator, LLMEvalChain, LLMChain\nA chain for scoring on a scale of 1-10 the output of a model.\noutput_parser\u00b6\nThe output parser for the chain.\nType\nBaseOutputParser\nExample\n>>> from langchain.chat_models import ChatOpenAI\n>>> from langchain.evaluation.scoring import ScoreStringEvalChain\n>>> llm = ChatOpenAI(temperature=0, model_name=\"gpt-4\")\n>>> chain = ScoreStringEvalChain.from_llm(llm=llm)\n>>> result = chain.evaluate_strings(\n...     input = \"What is the chemical formula for water?\",\n...     prediction = \"H2O\",\n...     reference = \"The chemical formula for water is H2O.\",\n... )\n>>> print(result)\n# {\n#    \"score\": 8,\n#    \"comment\": \"The response accurately states \"\n#    \"that the chemical formula for water is H2O.\"\n#    \"However, it does not provide an explanation of what the formula means.\"\n# }\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam criterion_name: str [Required]\u00b6\nThe name of the criterion being evaluated.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-1", "text": "param criterion_name: str [Required]\u00b6\nThe name of the criterion being evaluated.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam normalize_by: Optional[float] = None\u00b6\nThe value to normalize the score by, if specified.\nparam output_parser: BaseOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-2", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-3", "text": "to False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-4", "text": "memory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-5", "text": "Generate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-6", "text": "Prepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-7", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-8", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-9", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-10", "text": "Returns\nThe evaluation results containing the score or value.\nReturn type\ndict\nclassmethod from_llm(llm: BaseLanguageModel, *, prompt: Optional[PromptTemplate] = None, criteria: Optional[Union[Mapping[str, str], Criteria, ConstitutionalPrinciple, str]] = None, normalize_by: Optional[float] = None, **kwargs: Any) \u2192 ScoreStringEvalChain[source]\u00b6\nInitialize the ScoreStringEvalChain from an LLM.\nParameters\nllm (BaseChatModel) \u2013 The LLM to use (GPT-4 recommended).\nprompt (PromptTemplate, optional) \u2013 The prompt to use.\n**kwargs (Any) \u2013 Additional keyword arguments.\nReturns\nThe initialized ScoreStringEvalChain.\nReturn type\nScoreStringEvalChain\nRaises\nValueError \u2013 If the input variables are not as expected.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-11", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-12", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-13", "text": "Parameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-14", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-15", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-16", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "9d795f6a2a82-17", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty evaluation_name: str\u00b6\nGet the name of the evaluation.\nReturns\nThe name of the evaluation.\nReturn type\nstr\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nReturn whether the chain requires an input.\nReturns\nTrue if the chain requires an input, False otherwise.\nReturn type\nbool\nproperty requires_reference: bool\u00b6\nReturn whether the chain requires a reference.\nReturns\nTrue if the chain requires a reference, False otherwise.\nReturn type\nbool", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain.html"}
{"id": "3a217e164626-0", "text": "langchain.evaluation.string_distance.base.StringDistanceEvalChain\u00b6\nclass langchain.evaluation.string_distance.base.StringDistanceEvalChain[source]\u00b6\nBases: StringEvaluator, _RapidFuzzChainMixin\nCompute string distances between the prediction and the reference.\nExamples\n>>> from langchain.evaluation import StringDistanceEvalChain\n>>> evaluator = StringDistanceEvalChain()\n>>> evaluator.evaluate_strings(\n        prediction=\"Mindy is the CTO\",\n        reference=\"Mindy is the CEO\",\n    )\nUsing the load_evaluator function:\n>>> from langchain.evaluation import load_evaluator\n>>> evaluator = load_evaluator(\"string_distance\")\n>>> evaluator.evaluate_strings(\n        prediction=\"The answer is three\",\n        reference=\"three\",\n    )\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam distance: StringDistance = StringDistance.JARO_WINKLER\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-1", "text": "This metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam normalize_score: bool = True\u00b6\nWhether to normalize the score to a value between 0 and 1.\nApplies only to the Levenshtein and Damerau-Levenshtein distances.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-2", "text": "chain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-3", "text": "Chain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-4", "text": "The default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-5", "text": "# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-6", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncompute_metric(a: str, b: str) \u2192 float\u00b6\nCompute the distance between two strings.\nParameters\na (str) \u2013 The first string.\nb (str) \u2013 The second string.\nReturns\nThe distance between the two strings.\nReturn type\nfloat\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-8", "text": "Parameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-9", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-10", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-11", "text": "The main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-12", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-13", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "3a217e164626-14", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty evaluation_name: str\u00b6\nGet the evaluation name.\nReturns\nThe evaluation name.\nReturn type\nstr\nproperty input_keys: List[str]\u00b6\nGet the input keys.\nReturns\nThe input keys.\nReturn type\nList[str]\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty metric: Callable\u00b6\nGet the distance metric function.\nReturns\nThe distance metric function.\nReturn type\nCallable\nproperty output_keys: List[str]\u00b6\nGet the output keys.\nReturns\nThe output keys.\nReturn type\nList[str]\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nThis evaluator does not require input.\nproperty requires_reference: bool\u00b6\nThis evaluator does not require a reference.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html"}
{"id": "378c12c1e080-0", "text": "langchain.evaluation.embedding_distance.base.EmbeddingDistance\u00b6\nclass langchain.evaluation.embedding_distance.base.EmbeddingDistance(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEmbedding Distance Metric.\nCOSINE\u00b6\nCosine distance metric.\nEUCLIDEAN\u00b6\nEuclidean distance metric.\nMANHATTAN\u00b6\nManhattan distance metric.\nCHEBYSHEV\u00b6\nChebyshev distance metric.\nHAMMING\u00b6\nHamming distance metric.\nCOSINE = 'cosine'\u00b6\nEUCLIDEAN = 'euclidean'\u00b6\nMANHATTAN = 'manhattan'\u00b6\nCHEBYSHEV = 'chebyshev'\u00b6\nHAMMING = 'hamming'\u00b6\nExamples using EmbeddingDistance\u00b6\nPairwise Embedding Distance \nEmbedding Distance", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistance.html"}
{"id": "aacf6c106580-0", "text": "langchain.evaluation.loading.load_evaluator\u00b6\nlangchain.evaluation.loading.load_evaluator(evaluator: EvaluatorType, *, llm: Optional[BaseLanguageModel] = None, **kwargs: Any) \u2192 Union[Chain, StringEvaluator][source]\u00b6\nLoad the requested evaluation chain specified by a string.\nParameters\nevaluator (EvaluatorType) \u2013 The type of evaluator to load.\nllm (BaseLanguageModel, optional) \u2013 The language model to use for evaluation, by default None\n**kwargs (Any) \u2013 Additional keyword arguments to pass to the evaluator.\nReturns\nThe loaded evaluation chain.\nReturn type\nChain\nExamples\n>>> from langchain.evaluation import load_evaluator, EvaluatorType\n>>> evaluator = load_evaluator(EvaluatorType.QA)\nExamples using load_evaluator\u00b6\nComparing Chain Outputs\nAgent Trajectory\nPairwise Embedding Distance \nPairwise String Comparison\nCriteria Evaluation\nString Distance\nEmbedding Distance", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.loading.load_evaluator.html"}
{"id": "17e61915fae1-0", "text": "langchain.evaluation.comparison.eval_chain.resolve_pairwise_criteria\u00b6\nlangchain.evaluation.comparison.eval_chain.resolve_pairwise_criteria(criteria: Optional[Union[Mapping[str, str], Criteria, ConstitutionalPrinciple, str, List[Union[Mapping[str, str], Criteria, ConstitutionalPrinciple]]]]) \u2192 dict[source]\u00b6\nResolve the criteria for the pairwise evaluator.\nParameters\ncriteria (Union[CRITERIA_TYPE, str, List[CRITERIA_TYPE]], optional) \u2013 \nuse. (The criteria to) \u2013 \nReturns\nThe resolved criteria.\nReturn type\ndict", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.resolve_pairwise_criteria.html"}
{"id": "06a193cc8d0b-0", "text": "langchain.evaluation.parsing.base.JsonEqualityEvaluator\u00b6\nclass langchain.evaluation.parsing.base.JsonEqualityEvaluator(operator: Optional[Callable] = None, **kwargs: Any)[source]\u00b6\nEvaluates whether the prediction is equal to the reference afterparsing both as JSON.\nThis evaluator checks if the prediction, after parsing as JSON, is equalto the reference,\nwhich is also parsed as JSON. It does not require an input string.\nrequires_input\u00b6\nWhether this evaluator requires an\ninput string. Always False.\nType\nbool\nrequires_reference\u00b6\nWhether this evaluator requires\na reference string. Always True.\nType\nbool\nevaluation_name\u00b6\nThe name of the evaluation metric.\nAlways \u201cparsed_equality\u201d.\nType\nstr\nExamples\n>>> evaluator = JsonEqualityEvaluator()\n>>> evaluator.evaluate_strings('{\"a\": 1}', reference='{\"a\": 1}')\n{'score': True}\n>>> evaluator.evaluate_strings('{\"a\": 1}', reference='{\"a\": 2}')\n{'score': False}\n>>> evaluator = JsonEqualityEvaluator(operator=lambda x, y: x['a'] == y['a'])\n>>> evaluator.evaluate_strings('{\"a\": 1}', reference='{\"a\": 1}')\n{'score': True}\n>>> evaluator.evaluate_strings('{\"a\": 1}', reference='{\"a\": 2}')\n{'score': False}\nAttributes\nevaluation_name\nThe name of the evaluation.\nrequires_input\nWhether this evaluator requires an input string.\nrequires_reference\nWhether this evaluator requires a reference label.\nMethods\n__init__([operator])\naevaluate_strings(*,\u00a0prediction[,\u00a0...])\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nevaluate_strings(*,\u00a0prediction[,\u00a0reference,\u00a0...])\nEvaluate Chain or LLM output, based on optional input and label.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.parsing.base.JsonEqualityEvaluator.html"}
{"id": "06a193cc8d0b-1", "text": "Evaluate Chain or LLM output, based on optional input and label.\n__init__(operator: Optional[Callable] = None, **kwargs: Any) \u2192 None[source]\u00b6\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.parsing.base.JsonEqualityEvaluator.html"}
{"id": "4469de387b7a-0", "text": "langchain.evaluation.scoring.eval_chain.ScoreStringResultOutputParser\u00b6\nclass langchain.evaluation.scoring.eval_chain.ScoreStringResultOutputParser[source]\u00b6\nBases: BaseOutputParser[dict]\nA parser for the output of the ScoreStringEvalChain.\n_type\u00b6\nThe type of the output parser.\nType\nstr\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringResultOutputParser.html"}
{"id": "4469de387b7a-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringResultOutputParser.html"}
{"id": "4469de387b7a-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringResultOutputParser.html"}
{"id": "4469de387b7a-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringResultOutputParser.html"}
{"id": "4469de387b7a-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringResultOutputParser.html"}
{"id": "4469de387b7a-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Dict[str, Any][source]\u00b6\nParse the output text.\nParameters\ntext (str) \u2013 The output text to parse.\nReturns\nThe parsed output.\nReturn type\nDict\nRaises\nValueError \u2013 If the verdict is invalid.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringResultOutputParser.html"}
{"id": "4469de387b7a-6", "text": "completion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringResultOutputParser.html"}
{"id": "4469de387b7a-7", "text": "Parameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringResultOutputParser.html"}
{"id": "4469de387b7a-8", "text": "property InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.ScoreStringResultOutputParser.html"}
{"id": "61181d3151ee-0", "text": "langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain\u00b6\nclass langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain[source]\u00b6\nBases: _EmbeddingDistanceChainMixin, StringEvaluator\nUse embedding distances to score semantic difference between\na prediction and reference.\nExamples\n>>> chain = EmbeddingDistanceEvalChain()\n>>> result = chain.evaluate_strings(prediction=\"Hello\", reference=\"Hi\")\n>>> print(result)\n{'score': 0.5}\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam distance_metric: EmbeddingDistance = EmbeddingDistance.COSINE\u00b6\nparam embeddings: Embeddings [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-2", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-3", "text": "chain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-4", "text": "Subclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-5", "text": "question = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-6", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-7", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-8", "text": "Returns\nThe evaluation results containing the score or value.\nReturn type\ndict\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-9", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-11", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-12", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-13", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty evaluation_name: str\u00b6\nThe name of the evaluation.\nproperty input_keys: List[str]\u00b6\nReturn the input keys of the chain.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "61181d3151ee-14", "text": "property input_keys: List[str]\u00b6\nReturn the input keys of the chain.\nReturns\nThe input keys.\nReturn type\nList[str]\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nReturn the output keys of the chain.\nReturns\nThe output keys.\nReturn type\nList[str]\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nWhether this evaluator requires an input string.\nproperty requires_reference: bool\u00b6\nReturn whether the chain requires a reference.\nReturns\nTrue if a reference is required, False otherwise.\nReturn type\nbool", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.EmbeddingDistanceEvalChain.html"}
{"id": "5b92a285f54e-0", "text": "langchain.evaluation.comparison.eval_chain.PairwiseStringResultOutputParser\u00b6\nclass langchain.evaluation.comparison.eval_chain.PairwiseStringResultOutputParser[source]\u00b6\nBases: BaseOutputParser[dict]\nA parser for the output of the PairwiseStringEvalChain.\n_type\u00b6\nThe type of the output parser.\nType\nstr\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringResultOutputParser.html"}
{"id": "5b92a285f54e-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringResultOutputParser.html"}
{"id": "5b92a285f54e-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringResultOutputParser.html"}
{"id": "5b92a285f54e-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringResultOutputParser.html"}
{"id": "5b92a285f54e-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringResultOutputParser.html"}
{"id": "5b92a285f54e-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Dict[str, Any][source]\u00b6\nParse the output text.\nParameters\ntext (str) \u2013 The output text to parse.\nReturns\nThe parsed output.\nReturn type\nDict\nRaises\nValueError \u2013 If the verdict is invalid.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringResultOutputParser.html"}
{"id": "5b92a285f54e-6", "text": "completion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringResultOutputParser.html"}
{"id": "5b92a285f54e-7", "text": "Parameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringResultOutputParser.html"}
{"id": "5b92a285f54e-8", "text": "property InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.comparison.eval_chain.PairwiseStringResultOutputParser.html"}
{"id": "8f34f2840fbe-0", "text": "langchain.evaluation.schema.PairwiseStringEvaluator\u00b6\nclass langchain.evaluation.schema.PairwiseStringEvaluator[source]\u00b6\nCompare the output of two models (or two outputs of the same model).\nAttributes\nrequires_input\nWhether this evaluator requires an input string.\nrequires_reference\nWhether this evaluator requires a reference label.\nMethods\n__init__()\naevaluate_string_pairs(*,\u00a0prediction,\u00a0...[,\u00a0...])\nAsynchronously evaluate the output string pairs.\nevaluate_string_pairs(*,\u00a0prediction,\u00a0...[,\u00a0...])\nEvaluate the output string pairs.\n__init__()\u00b6\nasync aevaluate_string_pairs(*, prediction: str, prediction_b: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict[source]\u00b6\nAsynchronously evaluate the output string pairs.\nParameters\nprediction (str) \u2013 The output string from the first model.\nprediction_b (str) \u2013 The output string from the second model.\nreference (Optional[str], optional) \u2013 The expected output / reference string.\ninput (Optional[str], optional) \u2013 The input string.\n**kwargs \u2013 Additional keyword arguments, such as callbacks and optional reference strings.\nReturns\nA dictionary containing the preference, scores, and/or other information.\nReturn type\ndict\nevaluate_string_pairs(*, prediction: str, prediction_b: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict[source]\u00b6\nEvaluate the output string pairs.\nParameters\nprediction (str) \u2013 The output string from the first model.\nprediction_b (str) \u2013 The output string from the second model.\nreference (Optional[str], optional) \u2013 The expected output / reference string.\ninput (Optional[str], optional) \u2013 The input string.\n**kwargs \u2013 Additional keyword arguments, such as callbacks and optional reference strings.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.PairwiseStringEvaluator.html"}
{"id": "8f34f2840fbe-1", "text": "**kwargs \u2013 Additional keyword arguments, such as callbacks and optional reference strings.\nReturns\nA dictionary containing the preference, scores, and/or other information.\nReturn type\ndict\nExamples using PairwiseStringEvaluator\u00b6\nCustom Pairwise Evaluator", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.PairwiseStringEvaluator.html"}
{"id": "6d8d28b6233e-0", "text": "langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain\u00b6\nclass langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain[source]\u00b6\nBases: PairwiseStringEvaluator, _RapidFuzzChainMixin\nCompute string edit distances between two predictions.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam distance: StringDistance = StringDistance.JARO_WINKLER\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam normalize_score: bool = True\u00b6\nWhether to normalize the score to a value between 0 and 1.\nApplies only to the Levenshtein and Damerau-Levenshtein distances.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-1", "text": "Optional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-2", "text": "metadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-3", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_string_pairs(*, prediction: str, prediction_b: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate the output string pairs.\nParameters\nprediction (str) \u2013 The output string from the first model.\nprediction_b (str) \u2013 The output string from the second model.\nreference (Optional[str], optional) \u2013 The expected output / reference string.\ninput (Optional[str], optional) \u2013 The input string.\n**kwargs \u2013 Additional keyword arguments, such as callbacks and optional reference strings.\nReturns\nA dictionary containing the preference, scores, and/or other information.\nReturn type\ndict\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-4", "text": "Call the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-5", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-6", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncompute_metric(a: str, b: str) \u2192 float\u00b6\nCompute the distance between two strings.\nParameters\na (str) \u2013 The first string.\nb (str) \u2013 The second string.\nReturns\nThe distance between the two strings.\nReturn type\nfloat\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-7", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate_string_pairs(*, prediction: str, prediction_b: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate the output string pairs.\nParameters\nprediction (str) \u2013 The output string from the first model.\nprediction_b (str) \u2013 The output string from the second model.\nreference (Optional[str], optional) \u2013 The expected output / reference string.\ninput (Optional[str], optional) \u2013 The input string.\n**kwargs \u2013 Additional keyword arguments, such as callbacks and optional reference strings.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-8", "text": "**kwargs \u2013 Additional keyword arguments, such as callbacks and optional reference strings.\nReturns\nA dictionary containing the preference, scores, and/or other information.\nReturn type\ndict\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-9", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-11", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-12", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-13", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty evaluation_name: str\u00b6\nGet the evaluation name.\nReturns\nThe evaluation name.\nReturn type\nstr\nproperty input_keys: List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "6d8d28b6233e-14", "text": "The evaluation name.\nReturn type\nstr\nproperty input_keys: List[str]\u00b6\nGet the input keys.\nReturns\nThe input keys.\nReturn type\nList[str]\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty metric: Callable\u00b6\nGet the distance metric function.\nReturns\nThe distance metric function.\nReturn type\nCallable\nproperty output_keys: List[str]\u00b6\nGet the output keys.\nReturns\nThe output keys.\nReturn type\nList[str]\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nWhether this evaluator requires an input string.\nproperty requires_reference: bool\u00b6\nWhether this evaluator requires a reference label.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.PairwiseStringDistanceEvalChain.html"}
{"id": "06345138f8f9-0", "text": "langchain.evaluation.loading.load_evaluators\u00b6\nlangchain.evaluation.loading.load_evaluators(evaluators: Sequence[EvaluatorType], *, llm: Optional[BaseLanguageModel] = None, config: Optional[dict] = None, **kwargs: Any) \u2192 List[Union[Chain, StringEvaluator]][source]\u00b6\nLoad evaluators specified by a list of evaluator types.\nParameters\nevaluators (Sequence[EvaluatorType]) \u2013 The list of evaluator types to load.\nllm (BaseLanguageModel, optional) \u2013 The language model to use for evaluation, if none is provided, a default\nChatOpenAI gpt-4 model will be used.\nconfig (dict, optional) \u2013 A dictionary mapping evaluator types to additional keyword arguments,\nby default None\n**kwargs (Any) \u2013 Additional keyword arguments to pass to all evaluators.\nReturns\nThe loaded evaluators.\nReturn type\nList[Chain]\nExamples\n>>> from langchain.evaluation import load_evaluators, EvaluatorType\n>>> evaluators = [EvaluatorType.QA, EvaluatorType.CRITERIA]\n>>> loaded_evaluators = load_evaluators(evaluators, criteria=\"helpfulness\")", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.loading.load_evaluators.html"}
{"id": "921155ec8ddf-0", "text": "langchain.evaluation.loading.load_dataset\u00b6\nlangchain.evaluation.loading.load_dataset(uri: str) \u2192 List[Dict][source]\u00b6\nLoad a dataset from the LangChainDatasets on HuggingFace.\nParameters\nuri \u2013 The uri of the dataset to load.\nReturns\nA list of dictionaries, each representing a row in the dataset.\nPrerequisites\npip install datasets\nExamples\nfrom langchain.evaluation import load_dataset\nds = load_dataset(\"llm-math\")\nExamples using load_dataset\u00b6\nComparing Chain Outputs", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.loading.load_dataset.html"}
{"id": "854cc737815d-0", "text": "langchain.evaluation.criteria.eval_chain.Criteria\u00b6\nclass langchain.evaluation.criteria.eval_chain.Criteria(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nA Criteria to evaluate.\nCONCISENESS = 'conciseness'\u00b6\nRELEVANCE = 'relevance'\u00b6\nCORRECTNESS = 'correctness'\u00b6\nCOHERENCE = 'coherence'\u00b6\nHARMFULNESS = 'harmfulness'\u00b6\nMALICIOUSNESS = 'maliciousness'\u00b6\nHELPFULNESS = 'helpfulness'\u00b6\nCONTROVERSIALITY = 'controversiality'\u00b6\nMISOGYNY = 'misogyny'\u00b6\nCRIMINALITY = 'criminality'\u00b6\nINSENSITIVITY = 'insensitivity'\u00b6\nDEPTH = 'depth'\u00b6\nCREATIVITY = 'creativity'\u00b6\nDETAIL = 'detail'\u00b6\nExamples using Criteria\u00b6\nCriteria Evaluation", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.Criteria.html"}
{"id": "412d6353f1a2-0", "text": "langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain\u00b6\nclass langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain[source]\u00b6\nBases: _EmbeddingDistanceChainMixin, PairwiseStringEvaluator\nUse embedding distances to score semantic difference between two predictions.\nExamples:\n>>> chain = PairwiseEmbeddingDistanceEvalChain()\n>>> result = chain.evaluate_string_pairs(prediction=\u201dHello\u201d, prediction_b=\u201dHi\u201d)\n>>> print(result)\n{\u2018score\u2019: 0.5}\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam distance_metric: EmbeddingDistance = EmbeddingDistance.COSINE\u00b6\nparam embeddings: Embeddings [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-2", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-3", "text": "chain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_string_pairs(*, prediction: str, prediction_b: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate the output string pairs.\nParameters\nprediction (str) \u2013 The output string from the first model.\nprediction_b (str) \u2013 The output string from the second model.\nreference (Optional[str], optional) \u2013 The expected output / reference string.\ninput (Optional[str], optional) \u2013 The input string.\n**kwargs \u2013 Additional keyword arguments, such as callbacks and optional reference strings.\nReturns\nA dictionary containing the preference, scores, and/or other information.\nReturn type\ndict\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-4", "text": "Subclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-5", "text": "question = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-6", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-7", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate_string_pairs(*, prediction: str, prediction_b: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate the output string pairs.\nParameters\nprediction (str) \u2013 The output string from the first model.\nprediction_b (str) \u2013 The output string from the second model.\nreference (Optional[str], optional) \u2013 The expected output / reference string.\ninput (Optional[str], optional) \u2013 The input string.\n**kwargs \u2013 Additional keyword arguments, such as callbacks and optional reference strings.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-8", "text": "**kwargs \u2013 Additional keyword arguments, such as callbacks and optional reference strings.\nReturns\nA dictionary containing the preference, scores, and/or other information.\nReturn type\ndict\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-9", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-11", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-12", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-13", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty evaluation_name: str\u00b6\nproperty input_keys: List[str]\u00b6\nReturn the input keys of the chain.\nReturns\nThe input keys.\nReturn type", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "412d6353f1a2-14", "text": "Return the input keys of the chain.\nReturns\nThe input keys.\nReturn type\nList[str]\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nReturn the output keys of the chain.\nReturns\nThe output keys.\nReturn type\nList[str]\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nWhether this evaluator requires an input string.\nproperty requires_reference: bool\u00b6\nWhether this evaluator requires a reference label.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.embedding_distance.base.PairwiseEmbeddingDistanceEvalChain.html"}
{"id": "2af1413cb5b7-0", "text": "langchain.evaluation.parsing.json_schema.JsonSchemaEvaluator\u00b6\nclass langchain.evaluation.parsing.json_schema.JsonSchemaEvaluator(**kwargs: Any)[source]\u00b6\nAn evaluator that validates a JSON prediction against a JSON schema reference.\nThis evaluator checks if a given JSON prediction conforms to the provided JSON schema.\nIf the prediction is valid, the score is True (no errors). Otherwise, the score is False (error occurred).\nrequires_input\u00b6\nWhether the evaluator requires input.\nType\nbool\nrequires_reference\u00b6\nWhether the evaluator requires reference.\nType\nbool\nevaluation_name\u00b6\nThe name of the evaluation.\nType\nstr\nExamples\nevaluator = JsonSchemaEvaluator()\nresult = evaluator.evaluate_strings(\nprediction=\u2019{\u201cname\u201d: \u201cJohn\u201d, \u201cage\u201d: 30}\u2019,\nreference={\n\u201ctype\u201d: \u201cobject\u201d,\n\u201cproperties\u201d: {\n\u201cname\u201d: {\u201ctype\u201d: \u201cstring\u201d},\n\u201cage\u201d: {\u201ctype\u201d: \u201cinteger\u201d}\n}\n}\n)\nassert result[\u201cscore\u201d] is not None\nInitializes the JsonSchemaEvaluator.\nParameters\n**kwargs \u2013 Additional keyword arguments.\nRaises\nImportError \u2013 If the jsonschema package is not installed.\nAttributes\nevaluation_name\nReturns the name of the evaluation.\nrequires_input\nReturns whether the evaluator requires input.\nrequires_reference\nReturns whether the evaluator requires reference.\nMethods\n__init__(**kwargs)\nInitializes the JsonSchemaEvaluator.\naevaluate_strings(*,\u00a0prediction[,\u00a0...])\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nevaluate_strings(*,\u00a0prediction[,\u00a0reference,\u00a0...])\nEvaluate Chain or LLM output, based on optional input and label.\n__init__(**kwargs: Any) \u2192 None[source]\u00b6\nInitializes the JsonSchemaEvaluator.\nParameters\n**kwargs \u2013 Additional keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.parsing.json_schema.JsonSchemaEvaluator.html"}
{"id": "2af1413cb5b7-1", "text": "Initializes the JsonSchemaEvaluator.\nParameters\n**kwargs \u2013 Additional keyword arguments.\nRaises\nImportError \u2013 If the jsonschema package is not installed.\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.parsing.json_schema.JsonSchemaEvaluator.html"}
{"id": "5a34409addde-0", "text": "langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain\u00b6\nclass langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain[source]\u00b6\nBases: ScoreStringEvalChain\nA chain for scoring the output of a model on a scale of 1-10.\noutput_parser\u00b6\nThe output parser for the chain.\nType\nBaseOutputParser\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam criterion_name: str [Required]\u00b6\nThe name of the criterion being evaluated.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-1", "text": "You can use these to eg identify a specific instance of a chain with its use case.\nparam normalize_by: Optional[float] = None\u00b6\nThe value to normalize the score by, if specified.\nparam output_parser: BaseOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-2", "text": "Chain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-3", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-5", "text": "Call apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-6", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-7", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-8", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-9", "text": "Expects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nclassmethod from_llm(llm: BaseLanguageModel, *, prompt: Optional[PromptTemplate] = None, criteria: Optional[Union[Mapping[str, str], Criteria, ConstitutionalPrinciple, str]] = None, normalize_by: Optional[float] = None, **kwargs: Any) \u2192 LabeledScoreStringEvalChain[source]\u00b6\nInitialize the LabeledScoreStringEvalChain from an LLM.\nParameters\nllm (BaseLanguageModel) \u2013 The LLM to use.\nprompt (PromptTemplate, optional) \u2013 The prompt to use.\ncriteria (Union[CRITERIA_TYPE, str], optional) \u2013 The criteria to use.\nnormalize_by (float, optional) \u2013 The value to normalize the score by.\n**kwargs (Any) \u2013 Additional keyword arguments.\nReturns\nThe initialized LabeledScoreStringEvalChain.\nReturn type\nLabeledScoreStringEvalChain\nRaises", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-10", "text": "Return type\nLabeledScoreStringEvalChain\nRaises\nValueError \u2013 If the input variables are not as expected.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-11", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-12", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-13", "text": "Validate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-14", "text": "Example\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-15", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-16", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty evaluation_name: str\u00b6\nGet the name of the evaluation.\nReturns\nThe name of the evaluation.\nReturn type\nstr\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "5a34409addde-17", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nReturn whether the chain requires an input.\nReturns\nTrue if the chain requires an input, False otherwise.\nReturn type\nbool\nproperty requires_reference: bool\u00b6\nReturn whether the chain requires a reference.\nReturns\nTrue if the chain requires a reference, False otherwise.\nReturn type\nbool", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.LabeledScoreStringEvalChain.html"}
{"id": "695b61499bb6-0", "text": "langchain.evaluation.qa.eval_chain.QAEvalChain\u00b6\nclass langchain.evaluation.qa.eval_chain.QAEvalChain[source]\u00b6\nBases: LLMChain, StringEvaluator, LLMEvalChain\nLLM Chain for evaluating question answering.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-1", "text": "otherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-2", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-4", "text": "Asynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-5", "text": "**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-6", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-7", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-8", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-9", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate(examples: Sequence[dict], predictions: Sequence[dict], question_key: str = 'query', answer_key: str = 'answer', prediction_key: str = 'result', *, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[dict][source]\u00b6\nEvaluate question answering examples and predictions.\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nclassmethod from_llm(llm: BaseLanguageModel, prompt: Optional[PromptTemplate] = None, **kwargs: Any) \u2192 QAEvalChain[source]\u00b6\nLoad QA Eval Chain from LLM.\nParameters\nllm (BaseLanguageModel) \u2013 the base language model to use.\nprompt ('answer' and 'result' that will be used as the) \u2013 A prompt template containing the input_variables:\n'input' \u2013 \nprompt \u2013 \nevaluation. (for) \u2013 \nPROMPT. (Defaults to) \u2013 \n**kwargs \u2013 additional keyword arguments.\nReturns\nthe loaded QA eval chain.\nReturn type\nQAEvalChain\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-10", "text": "classmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-11", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-12", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-13", "text": "Returns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-14", "text": "question = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-15", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "695b61499bb6-16", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty evaluation_name: str\u00b6\nThe name of the evaluation.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nWhether this evaluator requires an input string.\nproperty requires_reference: bool\u00b6\nWhether this evaluator requires a reference label.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.qa.eval_chain.QAEvalChain.html"}
{"id": "c929c6f14f4a-0", "text": "langchain.evaluation.parsing.base.JsonValidityEvaluator\u00b6\nclass langchain.evaluation.parsing.base.JsonValidityEvaluator(**kwargs: Any)[source]\u00b6\nEvaluates whether the prediction is valid JSON.\nThis evaluator checks if the prediction is a valid JSON string. It does notrequire any input or reference.\nrequires_input\u00b6\nWhether this evaluator requires an input\nstring. Always False.\nType\nbool\nrequires_reference\u00b6\nWhether this evaluator requires a\nreference string. Always False.\nType\nbool\nevaluation_name\u00b6\nThe name of the evaluation metric.\nAlways \u201cjson\u201d.\nType\nstr\nExamples\n>>> evaluator = JsonValidityEvaluator()\n>>> prediction = '{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}'\n>>> evaluator.evaluate(prediction)\n{'score': 1}\n>>> prediction = '{\"name\": \"John\", \"age\": 30, \"city\": \"New York\",}'\n>>> evaluator.evaluate(prediction)\n{'score': 0, 'reasoning': 'Expecting property name enclosed in double quotes'}\nAttributes\nevaluation_name\nThe name of the evaluation.\nrequires_input\nWhether this evaluator requires an input string.\nrequires_reference\nWhether this evaluator requires a reference label.\nMethods\n__init__(**kwargs)\naevaluate_strings(*,\u00a0prediction[,\u00a0...])\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nevaluate_strings(*,\u00a0prediction[,\u00a0reference,\u00a0...])\nEvaluate Chain or LLM output, based on optional input and label.\n__init__(**kwargs: Any) \u2192 None[source]\u00b6\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.parsing.base.JsonValidityEvaluator.html"}
{"id": "c929c6f14f4a-1", "text": "Asynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.parsing.base.JsonValidityEvaluator.html"}
{"id": "36515ad69b98-0", "text": "langchain.evaluation.criteria.eval_chain.CriteriaEvalChain\u00b6\nclass langchain.evaluation.criteria.eval_chain.CriteriaEvalChain[source]\u00b6\nBases: StringEvaluator, LLMEvalChain, LLMChain\nLLM Chain for evaluating runs against criteria.\nParameters\nllm (BaseLanguageModel) \u2013 The language model to use for evaluation.\ncriteria (Union[Mapping[str, str]]) \u2013 The criteria or rubric to evaluate the runs against. It can be a mapping of\ncriterion name to its description, or a single criterion name.\nprompt (Optional[BasePromptTemplate], default=None) \u2013 The prompt template to use for generating prompts. If not provided, a\ndefault prompt template will be used based on the value of\nrequires_reference.\nrequires_reference (bool, default=False) \u2013 Whether the evaluation requires a reference text. If True, the\nPROMPT_WITH_REFERENCES template will be used, which includes the\nreference labels in the prompt. Otherwise, the PROMPT template will be\nused, which is a reference-free prompt.\n**kwargs (Any) \u2013 Additional keyword arguments to pass to the LLMChain constructor.\nReturns\nAn instance of the CriteriaEvalChain class.\nReturn type\nCriteriaEvalChain\nExamples\n>>> from langchain.chat_models import ChatAnthropic\n>>> from langchain.evaluation.criteria import CriteriaEvalChain\n>>> llm = ChatAnthropic(temperature=0)\n>>> criteria = {\"my-custom-criterion\": \"Is the submission the most amazing ever?\"}\n>>> evaluator = CriteriaEvalChain.from_llm(llm=llm, criteria=criteria)\n>>> evaluator.evaluate_strings(prediction=\"Imagine an ice cream flavor for the color aquamarine\", input=\"Tell me an idea\")\n{", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-1", "text": "{\n    'reasoning': 'Here is my step-by-step reasoning for the given criteria:\\n\\nThe criterion is: \"Is the submission the most amazing ever?\" This is a subjective criterion and open to interpretation. The submission suggests an aquamarine-colored ice cream flavor which is creative but may or may not be considered the most amazing idea ever conceived. There are many possible amazing ideas and this one ice cream flavor suggestion may or may not rise to that level for every person. \\n\\nN',\n    'value': 'N',\n    'score': 0,\n}\n>>> from langchain.chat_models import ChatOpenAI\n>>> from langchain.evaluation.criteria import LabeledCriteriaEvalChain\n>>> llm = ChatOpenAI(model=\"gpt-4\", temperature=0)\n>>> criteria = \"correctness\"\n>>> evaluator = LabeledCriteriaEvalChain.from_llm(\n...     llm=llm,\n...     criteria=criteria,\n... )\n>>> evaluator.evaluate_strings(\n...   prediction=\"The answer is 4\",\n...   input=\"How many apples are there?\",\n...   reference=\"There are 3 apples\",\n...   )\n{\n    'score': 0,\n    'reasoning': 'The criterion for this task is the correctness of the submission. The submission states that there are 4 apples, but the reference indicates that there are actually 3 apples. Therefore, the submission is not correct, accurate, or factual according to the given criterion.\\n\\nN',\n    'value': 'N',\n}\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-2", "text": "Callback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam criterion_name: str [Required]\u00b6\nThe name of the criterion being evaluated.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseOutputParser [Optional]\u00b6\nThe parser to use to map the output to a structured result.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-3", "text": "These tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-4", "text": "include_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-5", "text": "Chain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-6", "text": "Generate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-7", "text": "Prepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-8", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-9", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-10", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nclassmethod from_llm(llm: BaseLanguageModel, criteria: Optional[Union[Mapping[str, str], Criteria, ConstitutionalPrinciple]] = None, *, prompt: Optional[BasePromptTemplate] = None, **kwargs: Any) \u2192 CriteriaEvalChain[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-11", "text": "Create a CriteriaEvalChain instance from an llm and criteria.\nParameters\nllm (BaseLanguageModel) \u2013 The language model to use for evaluation.\ncriteria (CRITERIA_TYPE - default=None for \"helpfulness\") \u2013 \nThe criteria to evaluate the runs against. It can be:\na mapping of a criterion name to its description\na single criterion name present in one of the default criteria\na single ConstitutionalPrinciple instance\nprompt (Optional[BasePromptTemplate], default=None) \u2013 The prompt template to use for generating prompts. If not provided,\na default prompt template will be used.\n**kwargs (Any) \u2013 Additional keyword arguments to pass to the LLMChain\nconstructor.\nReturns\nAn instance of the CriteriaEvalChain class.\nReturn type\nCriteriaEvalChain\nExamples\n>>> from langchain.llms import OpenAI\n>>> from langchain.evaluation.criteria import LabeledCriteriaEvalChain\n>>> llm = OpenAI()\n>>> criteria = {\n        \"hallucination\": (\n            \"Does this submission contain information\"\n            \" not present in the input or reference?\"\n        ),\n    }\n>>> chain = LabeledCriteriaEvalChain.from_llm(\n        llm=llm,\n        criteria=criteria,\n    )\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-12", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-13", "text": "for more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-14", "text": "Format prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nclassmethod resolve_criteria(criteria: Optional[Union[Mapping[str, str], Criteria, ConstitutionalPrinciple, str]]) \u2192 Dict[str, str][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-15", "text": "Resolve the criteria to evaluate.\nParameters\ncriteria (CRITERIA_TYPE) \u2013 \nThe criteria to evaluate the runs against. It can be:\na mapping of a criterion name to its description\na single criterion name present in one of the default criteria\na single ConstitutionalPrinciple instance\nReturns\nA dictionary mapping criterion names to descriptions.\nReturn type\nDict[str, str]\nExamples\n>>> criterion = \"relevance\"\n>>> CriteriaEvalChain.resolve_criteria(criteria)\n{'relevance': 'Is the submission referring to a real quote from the text?'}\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-16", "text": "Example\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-17", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-18", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty evaluation_name: str\u00b6\nGet the name of the evaluation.\nReturns\nThe name of the evaluation.\nReturn type\nstr\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "36515ad69b98-19", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nWhether this evaluator requires an input string.\nproperty requires_reference: bool\u00b6\nWhether the evaluation requires a reference text.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html"}
{"id": "76b522887c82-0", "text": "langchain.evaluation.schema.EvaluatorType\u00b6\nclass langchain.evaluation.schema.EvaluatorType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nThe types of the evaluators.\nQA = 'qa'\u00b6\nQuestion answering evaluator, which grades answers to questions\ndirectly using an LLM.\nCOT_QA = 'cot_qa'\u00b6\nChain of thought question answering evaluator, which grades\nanswers to questions using\nchain of thought \u2018reasoning\u2019.\nCONTEXT_QA = 'context_qa'\u00b6\nQuestion answering evaluator that incorporates \u2018context\u2019 in the response.\nPAIRWISE_STRING = 'pairwise_string'\u00b6\nThe pairwise string evaluator, which predicts the preferred prediction from\nbetween two models.\nSCORE_STRING = 'score_string'\u00b6\nThe scored string evaluator, which gives a score between 1 and 10\nto a prediction.\nLABELED_PAIRWISE_STRING = 'labeled_pairwise_string'\u00b6\nThe labeled pairwise string evaluator, which predicts the preferred prediction\nfrom between two models based on a ground truth reference label.\nLABELED_SCORE_STRING = 'labeled_score_string'\u00b6\nThe labeled scored string evaluator, which gives a score between 1 and 10\nto a prediction based on a ground truth reference label.\nAGENT_TRAJECTORY = 'trajectory'\u00b6\nThe agent trajectory evaluator, which grades the agent\u2019s intermediate steps.\nCRITERIA = 'criteria'\u00b6\nThe criteria evaluator, which evaluates a model based on a\ncustom set of criteria without any reference labels.\nLABELED_CRITERIA = 'labeled_criteria'\u00b6\nThe labeled criteria evaluator, which evaluates a model based on a\ncustom set of criteria, with a reference label.\nSTRING_DISTANCE = 'string_distance'\u00b6\nCompare predictions to a reference answer using string edit distances.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.EvaluatorType.html"}
{"id": "76b522887c82-1", "text": "Compare predictions to a reference answer using string edit distances.\nEXACT_MATCH = 'exact_match'\u00b6\nCompare predictions to a reference answer using exact matching.\nREGEX_MATCH = 'regex_match'\u00b6\nCompare predictions to a reference answer using regular expressions.\nPAIRWISE_STRING_DISTANCE = 'pairwise_string_distance'\u00b6\nCompare predictions based on string edit distances.\nEMBEDDING_DISTANCE = 'embedding_distance'\u00b6\nCompare a prediction to a reference label using embedding distance.\nPAIRWISE_EMBEDDING_DISTANCE = 'pairwise_embedding_distance'\u00b6\nCompare two predictions using embedding distance.\nJSON_VALIDITY = 'json_validity'\u00b6\nCheck if a prediction is valid JSON.\nJSON_EQUALITY = 'json_equality'\u00b6\nCheck if a prediction is equal to a reference JSON.\nJSON_EDIT_DISTANCE = 'json_edit_distance'\u00b6\nCompute the edit distance between two JSON strings after canonicalization.\nJSON_SCHEMA_VALIDATION = 'json_schema_validation'\u00b6\nCheck if a prediction is valid JSON according to a JSON schema.\nExamples using EvaluatorType\u00b6\nLangSmith Walkthrough\nCriteria Evaluation", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.EvaluatorType.html"}
{"id": "0eba39b6dd95-0", "text": "langchain.evaluation.parsing.json_distance.JsonEditDistanceEvaluator\u00b6\nclass langchain.evaluation.parsing.json_distance.JsonEditDistanceEvaluator(string_distance: Optional[Callable[[str, str], float]] = None, canonicalize: Optional[Callable[[Any], Any]] = None, **kwargs: Any)[source]\u00b6\nAn evaluator that calculates the edit distance between JSON strings.\nThis evaluator computes a normalized Damerau-Levenshtein distance between two JSON strings\nafter parsing them and converting them to a canonical format (i.e., whitespace and key order are normalized).\nIt can be customized with alternative distance and canonicalization functions.\nParameters\nstring_distance (Optional[Callable[[str, str], float]]) \u2013 A callable that computes the distance between two strings.\nIf not provided, a Damerau-Levenshtein distance from the rapidfuzz package will be used.\ncanonicalize (Optional[Callable[[Any], Any]]) \u2013 A callable that converts a parsed JSON object into its canonical string form.\nIf not provided, the default behavior is to serialize the JSON with sorted keys and no extra whitespace.\n**kwargs (Any) \u2013 Additional keyword arguments.\n_string_distance\u00b6\nThe internal distance computation function.\nType\nCallable[[str, str], float]\n_canonicalize\u00b6\nThe internal canonicalization function.\nType\nCallable[[Any], Any]\nExamples\n>>> evaluator = JsonEditDistanceEvaluator()\n>>> result = evaluator.evaluate_strings(prediction='{\"a\": 1, \"b\": 2}', reference='{\"a\": 1, \"b\": 3}')\n>>> assert result[\"score\"] is not None\nRaises\nImportError \u2013 If rapidfuzz is not installed and no alternative string_distance function is provided.\nAttributes\nevaluation_name\nThe name of the evaluation.\nrequires_input\nWhether this evaluator requires an input string.\nrequires_reference\nWhether this evaluator requires a reference label.\nMethods", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.parsing.json_distance.JsonEditDistanceEvaluator.html"}
{"id": "0eba39b6dd95-1", "text": "requires_reference\nWhether this evaluator requires a reference label.\nMethods\n__init__([string_distance,\u00a0canonicalize])\naevaluate_strings(*,\u00a0prediction[,\u00a0...])\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nevaluate_strings(*,\u00a0prediction[,\u00a0reference,\u00a0...])\nEvaluate Chain or LLM output, based on optional input and label.\n__init__(string_distance: Optional[Callable[[str, str], float]] = None, canonicalize: Optional[Callable[[Any], Any]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.parsing.json_distance.JsonEditDistanceEvaluator.html"}
{"id": "56fb0c0d4aa7-0", "text": "langchain.evaluation.schema.AgentTrajectoryEvaluator\u00b6\nclass langchain.evaluation.schema.AgentTrajectoryEvaluator[source]\u00b6\nInterface for evaluating agent trajectories.\nAttributes\nrequires_input\nWhether this evaluator requires an input string.\nrequires_reference\nWhether this evaluator requires a reference label.\nMethods\n__init__()\naevaluate_agent_trajectory(*,\u00a0prediction,\u00a0...)\nAsynchronously evaluate a trajectory.\nevaluate_agent_trajectory(*,\u00a0prediction,\u00a0...)\nEvaluate a trajectory.\n__init__()\u00b6\nasync aevaluate_agent_trajectory(*, prediction: str, agent_trajectory: Sequence[Tuple[AgentAction, str]], input: str, reference: Optional[str] = None, **kwargs: Any) \u2192 dict[source]\u00b6\nAsynchronously evaluate a trajectory.\nParameters\nprediction (str) \u2013 The final predicted response.\nagent_trajectory (List[Tuple[AgentAction, str]]) \u2013 The intermediate steps forming the agent trajectory.\ninput (str) \u2013 The input to the agent.\nreference (Optional[str]) \u2013 The reference answer.\nReturns\nThe evaluation result.\nReturn type\ndict\nevaluate_agent_trajectory(*, prediction: str, agent_trajectory: Sequence[Tuple[AgentAction, str]], input: str, reference: Optional[str] = None, **kwargs: Any) \u2192 dict[source]\u00b6\nEvaluate a trajectory.\nParameters\nprediction (str) \u2013 The final predicted response.\nagent_trajectory (List[Tuple[AgentAction, str]]) \u2013 The intermediate steps forming the agent trajectory.\ninput (str) \u2013 The input to the agent.\nreference (Optional[str]) \u2013 The reference answer.\nReturns\nThe evaluation result.\nReturn type\ndict\nExamples using AgentTrajectoryEvaluator\u00b6\nCustom Trajectory Evaluator", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.AgentTrajectoryEvaluator.html"}
{"id": "be0992abd59e-0", "text": "langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain\u00b6\nclass langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain[source]\u00b6\nBases: AgentTrajectoryEvaluator, LLMEvalChain\nA chain for evaluating ReAct style agents.\nThis chain is used to evaluate ReAct style agents by reasoning about\nthe sequence of actions taken and their outcomes.\nExample:\nfrom langchain.agents import AgentType, initialize_agent\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.evaluation import TrajectoryEvalChain\nfrom langchain.tools import tool\n@tool\ndef geography_answers(country: str, question: str) -> str:\n    \"\"\"Very helpful answers to geography questions.\"\"\"\n    return f\"{country}? IDK - We may never know {question}.\"\nllm = ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0)\nagent = initialize_agent(\n    tools=[geography_answers],\n    llm=llm,\n    agent=AgentType.OPENAI_FUNCTIONS,\n    return_intermediate_steps=True,\n)\nquestion = \"How many dwell in the largest minor region in Argentina?\"\nresponse = agent(question)\neval_chain = TrajectoryEvalChain.from_llm(\n    llm=llm, agent_tools=[geography_answers], return_reasoning=True\n)\nresult = eval_chain.evaluate_agent_trajectory(\n    input=question,\n    agent_trajectory=response[\"intermediate_steps\"],\n    prediction=response[\"output\"],\n    reference=\"Paris\",\n)\nprint(result[\"score\"])\n# 0\nparam agent_tools: Optional[List[langchain.tools.base.BaseTool]] = None\u00b6\nA list of tools available to the agent.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-1", "text": "Deprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam eval_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nThe language model chain used for evaluation.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: langchain.evaluation.agents.trajectory_eval_chain.TrajectoryOutputParser [Optional]\u00b6\nThe output parser used to parse the output.\nparam return_reasoning: bool = False\u00b6\nDEPRECATED. Reasoning always returned.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-2", "text": "param verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-3", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-4", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_agent_trajectory(*, prediction: str, agent_trajectory: Sequence[Tuple[AgentAction, str]], input: str, reference: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nAsynchronously evaluate a trajectory.\nParameters\nprediction (str) \u2013 The final predicted response.\nagent_trajectory (List[Tuple[AgentAction, str]]) \u2013 The intermediate steps forming the agent trajectory.\ninput (str) \u2013 The input to the agent.\nreference (Optional[str]) \u2013 The reference answer.\nReturns\nThe evaluation result.\nReturn type\ndict\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-5", "text": "Convenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-6", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-7", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-8", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate_agent_trajectory(*, prediction: str, agent_trajectory: Sequence[Tuple[AgentAction, str]], input: str, reference: Optional[str] = None, **kwargs: Any) \u2192 dict\u00b6\nEvaluate a trajectory.\nParameters\nprediction (str) \u2013 The final predicted response.\nagent_trajectory (List[Tuple[AgentAction, str]]) \u2013 The intermediate steps forming the agent trajectory.\ninput (str) \u2013 The input to the agent.\nreference (Optional[str]) \u2013 The reference answer.\nReturns\nThe evaluation result.\nReturn type\ndict\nclassmethod from_llm(llm: BaseLanguageModel, agent_tools: Optional[Sequence[BaseTool]] = None, output_parser: Optional[TrajectoryOutputParser] = None, **kwargs: Any) \u2192 TrajectoryEvalChain[source]\u00b6\nCreate a TrajectoryEvalChain object from a language model chain.\nParameters\nllm (BaseChatModel) \u2013 The language model chain.\nagent_tools (Optional[Sequence[BaseTool]]) \u2013 A list of tools\navailable to the agent.\noutput_parser (Optional[TrajectoryOutputParser]) \u2013 The output parser", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-9", "text": "output_parser (Optional[TrajectoryOutputParser]) \u2013 The output parser\nused to parse the chain output into a score.\nReturns\nThe TrajectoryEvalChain object.\nReturn type\nTrajectoryEvalChain\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nstatic get_agent_trajectory(steps: Union[str, Sequence[Tuple[AgentAction, str]]]) \u2192 str[source]\u00b6\nGet the agent trajectory as a formatted string.\nParameters\nsteps (Union[str, List[Tuple[AgentAction, str]]]) \u2013 The agent trajectory.\nReturns\nThe formatted agent trajectory.\nReturn type\nstr\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-10", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-11", "text": "Return a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str][source]\u00b6\nValidate and prep inputs.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-12", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-13", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-14", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nGet the input keys for the chain.\nReturns\nThe input keys.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "be0992abd59e-15", "text": "Returns\nThe input keys.\nReturn type\nList[str]\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nGet the output keys for the chain.\nReturns\nThe output keys.\nReturn type\nList[str]\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty requires_input: bool\u00b6\nWhether this evaluator requires an input string.\nproperty requires_reference: bool\u00b6\nWhether this evaluator requires a reference label.", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.agents.trajectory_eval_chain.TrajectoryEvalChain.html"}
{"id": "1e6e26ef28e7-0", "text": "langchain.evaluation.scoring.eval_chain.resolve_criteria\u00b6\nlangchain.evaluation.scoring.eval_chain.resolve_criteria(criteria: Optional[Union[Mapping[str, str], Criteria, ConstitutionalPrinciple, str, List[Union[Mapping[str, str], Criteria, ConstitutionalPrinciple]]]]) \u2192 dict[source]\u00b6\nResolve the criteria for the pairwise evaluator.\nParameters\ncriteria (Union[CRITERIA_TYPE, str], optional) \u2013 The criteria to use.\nReturns\nThe resolved criteria.\nReturn type\ndict", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.scoring.eval_chain.resolve_criteria.html"}
{"id": "c5d41e6b8108-0", "text": "langchain.evaluation.schema.StringEvaluator\u00b6\nclass langchain.evaluation.schema.StringEvaluator[source]\u00b6\nGrade, tag, or otherwise evaluate predictions relative to their inputs\nand/or reference labels.\nAttributes\nevaluation_name\nThe name of the evaluation.\nrequires_input\nWhether this evaluator requires an input string.\nrequires_reference\nWhether this evaluator requires a reference label.\nMethods\n__init__()\naevaluate_strings(*,\u00a0prediction[,\u00a0...])\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nevaluate_strings(*,\u00a0prediction[,\u00a0reference,\u00a0...])\nEvaluate Chain or LLM output, based on optional input and label.\n__init__()\u00b6\nasync aevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict[source]\u00b6\nAsynchronously evaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nevaluate_strings(*, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any) \u2192 dict[source]\u00b6\nEvaluate Chain or LLM output, based on optional input and label.\nParameters\nprediction (str) \u2013 The LLM or chain prediction to evaluate.\nreference (Optional[str], optional) \u2013 The reference label to evaluate against.\ninput (Optional[str], optional) \u2013 The input to consider during evaluation.\n**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.StringEvaluator.html"}
{"id": "c5d41e6b8108-1", "text": "**kwargs \u2013 Additional keyword arguments, including callbacks, tags, etc.\nReturns\nThe evaluation results containing the score or value.\nReturn type\ndict\nExamples using StringEvaluator\u00b6\nCustom String Evaluator", "source": "lang/api.python.langchain.com/en/latest/evaluation/langchain.evaluation.schema.StringEvaluator.html"}
{"id": "08224d4b8e32-0", "text": "langchain.tools.ainetwork.value.AINValueOps\u00b6\nclass langchain.tools.ainetwork.value.AINValueOps[source]\u00b6\nBases: AINBaseTool\nTool for value operations.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.ainetwork.value.ValueSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.AINValueOps.html"}
{"id": "08224d4b8e32-1", "text": "param callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = '\\nCovers the read and write value for the AINetwork Blockchain database.\\n\\n## SET\\n- Set a value at a given path\\n\\n### Example\\n- type: SET\\n- path: /apps/langchain_test_1/object\\n- value: {1: 2, \"34\": 56}\\n\\n## GET\\n- Retrieve a value at a given path\\n\\n### Example\\n- type: GET\\n- path: /apps/langchain_test_1/DB\\n\\n## Special paths\\n- `/accounts/<address>/balance`: Account balance\\n- `/accounts/<address>/nonce`: Account nonce\\n- `/apps`: Applications\\n- `/consensus`: Consensus\\n- `/checkin`: Check-in\\n- `/deposit/<service id>/<address>/<deposit id>`: Deposit\\n- `/deposit_accounts/<service id>/<address>/<account id>`: Deposit accounts\\n- `/escrow`: Escrow\\n- `/payments`: Payment\\n- `/sharding`: Sharding\\n- `/token/name`: Token name\\n- `/token/symbol`: Token symbol\\n- `/token/total_supply`: Token total supply\\n- `/transfer/<address from>/<address to>/<key>/value`: Transfer\\n- `/withdraw/<service id>/<address>/<withdraw id>`: Withdraw\\n'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam interface: Ain [Optional]\u00b6\nThe interface object for the AINetwork Blockchain.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.AINValueOps.html"}
{"id": "08224d4b8e32-2", "text": "param metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'AINvalueOps'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.AINValueOps.html"}
{"id": "08224d4b8e32-3", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.AINValueOps.html"}
{"id": "08224d4b8e32-4", "text": "step, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.AINValueOps.html"}
{"id": "08224d4b8e32-5", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.AINValueOps.html"}
{"id": "08224d4b8e32-6", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.AINValueOps.html"}
{"id": "08224d4b8e32-7", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.AINValueOps.html"}
{"id": "08224d4b8e32-8", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.AINValueOps.html"}
{"id": "08224d4b8e32-9", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.AINValueOps.html"}
{"id": "08224d4b8e32-10", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.AINValueOps.html"}
{"id": "0ca4d8404d12-0", "text": "langchain.tools.file_management.list_dir.ListDirectoryTool\u00b6\nclass langchain.tools.file_management.list_dir.ListDirectoryTool[source]\u00b6\nBases: BaseFileToolMixin, BaseTool\nTool that lists files and directories in a specified folder.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.file_management.list_dir.DirectoryListingInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'List files and directories in a specified folder'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'list_directory'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam root_dir: Optional[str] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.list_dir.ListDirectoryTool.html"}
{"id": "0ca4d8404d12-1", "text": "param root_dir: Optional[str] = None\u00b6\nThe final path will be chosen relative to root_dir if specified.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.list_dir.ListDirectoryTool.html"}
{"id": "0ca4d8404d12-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.list_dir.ListDirectoryTool.html"}
{"id": "0ca4d8404d12-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.list_dir.ListDirectoryTool.html"}
{"id": "0ca4d8404d12-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.list_dir.ListDirectoryTool.html"}
{"id": "0ca4d8404d12-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relative_path(file_path: str) \u2192 Path\u00b6\nGet the relative path, returning an error if unsupported.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.list_dir.ListDirectoryTool.html"}
{"id": "0ca4d8404d12-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.list_dir.ListDirectoryTool.html"}
{"id": "0ca4d8404d12-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.list_dir.ListDirectoryTool.html"}
{"id": "0ca4d8404d12-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.list_dir.ListDirectoryTool.html"}
{"id": "0ca4d8404d12-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ListDirectoryTool\u00b6\nFile System", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.list_dir.ListDirectoryTool.html"}
{"id": "945a4f6b6559-0", "text": "langchain.tools.google_serper.tool.GoogleSerperResults\u00b6\nclass langchain.tools.google_serper.tool.GoogleSerperResults[source]\u00b6\nBases: BaseTool\nTool that queries the Serper.dev Google Search API\nand get back json.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.google_serper.GoogleSerperAPIWrapper [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A low-cost Google Search API.Useful for when you need to answer questions about current events.Input should be a search query. Output is a JSON object of the query results'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'google_serper_results_json'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperResults.html"}
{"id": "945a4f6b6559-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperResults.html"}
{"id": "945a4f6b6559-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperResults.html"}
{"id": "945a4f6b6559-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperResults.html"}
{"id": "945a4f6b6559-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperResults.html"}
{"id": "945a4f6b6559-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperResults.html"}
{"id": "945a4f6b6559-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperResults.html"}
{"id": "945a4f6b6559-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperResults.html"}
{"id": "945a4f6b6559-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperResults.html"}
{"id": "945a4f6b6559-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperResults.html"}
{"id": "b7b4ec5ca282-0", "text": "langchain.tools.requests.tool.RequestsPatchTool\u00b6\nclass langchain.tools.requests.tool.RequestsPatchTool[source]\u00b6\nBases: BaseRequestsTool, BaseTool\nTool for making a PATCH request to an API endpoint.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this when you want to PATCH to a website.\\n\u00a0\u00a0\u00a0 Input should be a json string with two keys: \"url\" and \"data\".\\n\u00a0\u00a0\u00a0 The value of \"url\" should be a string, and the value of \"data\" should be a dictionary of \\n\u00a0\u00a0\u00a0 key-value pairs you want to PATCH to the url.\\n\u00a0\u00a0\u00a0 Be careful to always use double quotes for strings in the json string\\n\u00a0\u00a0\u00a0 The output will be the text response of the PATCH request.\\n\u00a0\u00a0\u00a0 '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPatchTool.html"}
{"id": "b7b4ec5ca282-1", "text": "You can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'requests_patch'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam requests_wrapper: TextRequestsWrapper [Required]\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPatchTool.html"}
{"id": "b7b4ec5ca282-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPatchTool.html"}
{"id": "b7b4ec5ca282-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPatchTool.html"}
{"id": "b7b4ec5ca282-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPatchTool.html"}
{"id": "b7b4ec5ca282-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPatchTool.html"}
{"id": "b7b4ec5ca282-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPatchTool.html"}
{"id": "b7b4ec5ca282-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPatchTool.html"}
{"id": "b7b4ec5ca282-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPatchTool.html"}
{"id": "b7b4ec5ca282-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPatchTool.html"}
{"id": "8174353ef823-0", "text": "langchain.tools.gmail.create_draft.GmailCreateDraft\u00b6\nclass langchain.tools.gmail.create_draft.GmailCreateDraft[source]\u00b6\nBases: GmailBaseTool\nTool that creates a draft email for Gmail.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_resource: Resource [Optional]\u00b6\nparam args_schema: Type[langchain.tools.gmail.create_draft.CreateDraftSchema] = <class 'langchain.tools.gmail.create_draft.CreateDraftSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this tool to create a draft email with the provided message fields.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'create_gmail_draft'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.create_draft.GmailCreateDraft.html"}
{"id": "8174353ef823-1", "text": "that after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.create_draft.GmailCreateDraft.html"}
{"id": "8174353ef823-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.create_draft.GmailCreateDraft.html"}
{"id": "8174353ef823-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.create_draft.GmailCreateDraft.html"}
{"id": "8174353ef823-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_api_resource(api_resource: Resource) \u2192 GmailBaseTool\u00b6\nCreate a tool from an api resource.\nParameters\napi_resource \u2013 The api resource to use.\nReturns\nA tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.create_draft.GmailCreateDraft.html"}
{"id": "8174353ef823-5", "text": "Returns\nA tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.create_draft.GmailCreateDraft.html"}
{"id": "8174353ef823-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.create_draft.GmailCreateDraft.html"}
{"id": "8174353ef823-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.create_draft.GmailCreateDraft.html"}
{"id": "8174353ef823-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.create_draft.GmailCreateDraft.html"}
{"id": "8174353ef823-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.create_draft.GmailCreateDraft.html"}
{"id": "81f1a4046e81-0", "text": "langchain.tools.spark_sql.tool.InfoSparkSQLTool\u00b6\nclass langchain.tools.spark_sql.tool.InfoSparkSQLTool[source]\u00b6\nBases: BaseSparkSQLTool, BaseTool\nTool for getting metadata about a Spark SQL.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam db: SparkSQL [Required]\u00b6\nparam description: str = '\\n\u00a0\u00a0\u00a0 Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.\\n\u00a0\u00a0\u00a0 Be sure that the tables actually exist by calling list_tables_sql_db first!\\n\\n\u00a0\u00a0\u00a0 Example Input: \"table1, table2, table3\"\\n\u00a0\u00a0\u00a0 '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'schema_sql_db'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.InfoSparkSQLTool.html"}
{"id": "81f1a4046e81-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.InfoSparkSQLTool.html"}
{"id": "81f1a4046e81-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.InfoSparkSQLTool.html"}
{"id": "81f1a4046e81-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.InfoSparkSQLTool.html"}
{"id": "81f1a4046e81-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.InfoSparkSQLTool.html"}
{"id": "81f1a4046e81-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.InfoSparkSQLTool.html"}
{"id": "81f1a4046e81-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.InfoSparkSQLTool.html"}
{"id": "81f1a4046e81-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.InfoSparkSQLTool.html"}
{"id": "81f1a4046e81-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.InfoSparkSQLTool.html"}
{"id": "81f1a4046e81-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.InfoSparkSQLTool.html"}
{"id": "35cf52664175-0", "text": "langchain.tools.amadeus.utils.authenticate\u00b6\nlangchain.tools.amadeus.utils.authenticate() \u2192 Client[source]\u00b6\nAuthenticate using the Amadeus API", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.utils.authenticate.html"}
{"id": "bee64c4454ee-0", "text": "langchain.tools.edenai.ocr_identityparser.EdenAiParsingIDTool\u00b6\nclass langchain.tools.edenai.ocr_identityparser.EdenAiParsingIDTool[source]\u00b6\nBases: EdenaiTool\nTool that queries the Eden AI  Identity parsing API.\nfor api reference check edenai documentation:\nhttps://docs.edenai.co/reference/ocr_identity_parser_create.\nTo use, you should have\nthe environment variable EDENAI_API_KEY set with your API token.\nYou can find your token here: https://app.edenai.run/admin/account/settings\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around edenai Services Identity parsing. Useful for when you have to extract information from an ID Document Input should be the string url of the document to parse.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam edenai_api_key: Optional[str] = None\u00b6\nparam feature: str = 'ocr'\u00b6\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam is_async: bool = False\u00b6\nparam language: Optional[str] = None\u00b6\nlanguage of the text passed to the model.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_identityparser.EdenAiParsingIDTool.html"}
{"id": "bee64c4454ee-1", "text": "param metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'edenai_identity_parsing'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam providers: List[str] [Required]\u00b6\nprovider to use for the API call.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam subfeature: str = 'identity_parser'\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_identityparser.EdenAiParsingIDTool.html"}
{"id": "bee64c4454ee-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_identityparser.EdenAiParsingIDTool.html"}
{"id": "bee64c4454ee-3", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_identityparser.EdenAiParsingIDTool.html"}
{"id": "bee64c4454ee-4", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_identityparser.EdenAiParsingIDTool.html"}
{"id": "bee64c4454ee-5", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nstatic get_user_agent() \u2192 str\u00b6\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_identityparser.EdenAiParsingIDTool.html"}
{"id": "bee64c4454ee-6", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_identityparser.EdenAiParsingIDTool.html"}
{"id": "bee64c4454ee-7", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_identityparser.EdenAiParsingIDTool.html"}
{"id": "bee64c4454ee-8", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_identityparser.EdenAiParsingIDTool.html"}
{"id": "bee64c4454ee-9", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using EdenAiParsingIDTool\u00b6\nEden AI", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_identityparser.EdenAiParsingIDTool.html"}
{"id": "e7c8c74eaa29-0", "text": "langchain.tools.sql_database.tool.ListSQLDatabaseTool\u00b6\nclass langchain.tools.sql_database.tool.ListSQLDatabaseTool[source]\u00b6\nBases: BaseSQLDatabaseTool, BaseTool\nTool for getting tables names.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam db: SQLDatabase [Required]\u00b6\nparam description: str = 'Input is an empty string, output is a comma separated list of tables in the database.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'sql_db_list_tables'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.ListSQLDatabaseTool.html"}
{"id": "e7c8c74eaa29-1", "text": "param tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.ListSQLDatabaseTool.html"}
{"id": "e7c8c74eaa29-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.ListSQLDatabaseTool.html"}
{"id": "e7c8c74eaa29-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.ListSQLDatabaseTool.html"}
{"id": "e7c8c74eaa29-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.ListSQLDatabaseTool.html"}
{"id": "e7c8c74eaa29-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.ListSQLDatabaseTool.html"}
{"id": "e7c8c74eaa29-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.ListSQLDatabaseTool.html"}
{"id": "e7c8c74eaa29-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.ListSQLDatabaseTool.html"}
{"id": "e7c8c74eaa29-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.ListSQLDatabaseTool.html"}
{"id": "e7c8c74eaa29-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.ListSQLDatabaseTool.html"}
{"id": "788f7bbebf7d-0", "text": "langchain.tools.office365.utils.clean_body\u00b6\nlangchain.tools.office365.utils.clean_body(body: str) \u2192 str[source]\u00b6\nClean body of a message or event.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.utils.clean_body.html"}
{"id": "50cd01822d09-0", "text": "langchain.tools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool\u00b6\nclass langchain.tools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool[source]\u00b6\nBases: EdenaiTool\nTool that queries the Eden AI Speech To Text API.\nfor api reference check edenai documentation:\nhttps://app.edenai.run/bricks/speech/asynchronous-speech-to-text.\nTo use, you should have\nthe environment variable EDENAI_API_KEY set with your API token.\nYou can find your token here: https://app.edenai.run/admin/account/settings\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam custom_vocabulary: Optional[List[str]] = None\u00b6\nparam description: str = 'A wrapper around edenai Services speech to text Useful for when you have to convert audio to text.Input should be a url to an audio file.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam edenai_api_key: Optional[str] = None\u00b6\nparam feature: str = 'audio'\u00b6\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam is_async: bool = True\u00b6\nparam language: Optional[str] = 'en'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool.html"}
{"id": "50cd01822d09-1", "text": "param language: Optional[str] = 'en'\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'edenai_speech_to_text'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam profanity_filter: bool = False\u00b6\nparam providers: List[str] [Required]\u00b6\nprovider to use for the API call.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam speakers: Optional[int] = None\u00b6\nparam subfeature: str = 'speech_to_text_async'\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool.html"}
{"id": "50cd01822d09-2", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool.html"}
{"id": "50cd01822d09-3", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool.html"}
{"id": "50cd01822d09-4", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool.html"}
{"id": "50cd01822d09-5", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nstatic get_user_agent() \u2192 str\u00b6\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool.html"}
{"id": "50cd01822d09-6", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool.html"}
{"id": "50cd01822d09-7", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool.html"}
{"id": "50cd01822d09-8", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool.html"}
{"id": "50cd01822d09-9", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using EdenAiSpeechToTextTool\u00b6\nEden AI", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool.html"}
{"id": "7a2dbda310a6-0", "text": "langchain_experimental.tools.python.tool.PythonInputs\u00b6\nclass langchain_experimental.tools.python.tool.PythonInputs[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam query: str [Required]\u00b6\ncode snippet to run\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonInputs.html"}
{"id": "7a2dbda310a6-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonInputs.html"}
{"id": "14be19ab3646-0", "text": "langchain.tools.arxiv.tool.ArxivQueryRun\u00b6\nclass langchain.tools.arxiv.tool.ArxivQueryRun[source]\u00b6\nBases: BaseTool\nTool that searches the Arxiv API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.arxiv.ArxivAPIWrapper [Optional]\u00b6\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.arxiv.tool.ArxivInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Arxiv.org Useful for when you need to answer questions about Physics, Mathematics, Computer Science, Quantitative Biology, Quantitative Finance, Statistics, Electrical Engineering, and Economics from scientific articles on arxiv.org. Input should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'arxiv'\u00b6\nThe unique name of the tool that clearly communicates its purpose.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.arxiv.tool.ArxivQueryRun.html"}
{"id": "14be19ab3646-1", "text": "The unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.arxiv.tool.ArxivQueryRun.html"}
{"id": "14be19ab3646-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.arxiv.tool.ArxivQueryRun.html"}
{"id": "14be19ab3646-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.arxiv.tool.ArxivQueryRun.html"}
{"id": "14be19ab3646-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.arxiv.tool.ArxivQueryRun.html"}
{"id": "14be19ab3646-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.arxiv.tool.ArxivQueryRun.html"}
{"id": "14be19ab3646-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.arxiv.tool.ArxivQueryRun.html"}
{"id": "14be19ab3646-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.arxiv.tool.ArxivQueryRun.html"}
{"id": "14be19ab3646-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.arxiv.tool.ArxivQueryRun.html"}
{"id": "14be19ab3646-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.arxiv.tool.ArxivQueryRun.html"}
{"id": "8bb80cad0ace-0", "text": "langchain.tools.ainetwork.owner.AINOwnerOps\u00b6\nclass langchain.tools.ainetwork.owner.AINOwnerOps[source]\u00b6\nBases: AINBaseTool\nTool for owner operations.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.ainetwork.owner.RuleSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.AINOwnerOps.html"}
{"id": "8bb80cad0ace-1", "text": "param callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = \"\\nRules for `owner` in AINetwork Blockchain database.\\nAn address set as `owner` can modify permissions according to its granted authorities\\n\\n## Path Rule\\n- (/[a-zA-Z_0-9]+)+\\n- Permission checks ascend from the most specific (child) path to broader (parent) paths until an `owner` is located.\\n\\n## Address Rules\\n- 0x[0-9a-fA-F]{40}: 40-digit hexadecimal address\\n- *: All addresses permitted\\n- Defaults to the current session's address\\n\\n## SET\\n- `SET` alters permissions for specific addresses, while other addresses remain unaffected.\\n- When removing an address of `owner`, set all authorities for that address to false.\\n- message `write_owner permission evaluated false` if fail\\n\\n### Example\\n- type: SET\\n- path: /apps/langchain\\n- address: [<address 1>, <address 2>]\\n- write_owner: True\\n- write_rule: True\\n- write_function: True\\n- branch_owner: True\\n\\n## GET\\n- Provides all addresses with `owner` permissions and their authorities in the path.\\n\\n### Example\\n- type: GET\\n- path: /apps/langchain\\n\"\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam interface: Ain [Optional]\u00b6\nThe interface object for the AINetwork Blockchain.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.AINOwnerOps.html"}
{"id": "8bb80cad0ace-2", "text": "param metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'AINownerOps'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.AINOwnerOps.html"}
{"id": "8bb80cad0ace-3", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.AINOwnerOps.html"}
{"id": "8bb80cad0ace-4", "text": "step, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.AINOwnerOps.html"}
{"id": "8bb80cad0ace-5", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.AINOwnerOps.html"}
{"id": "8bb80cad0ace-6", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.AINOwnerOps.html"}
{"id": "8bb80cad0ace-7", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.AINOwnerOps.html"}
{"id": "8bb80cad0ace-8", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.AINOwnerOps.html"}
{"id": "8bb80cad0ace-9", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.AINOwnerOps.html"}
{"id": "8bb80cad0ace-10", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.AINOwnerOps.html"}
{"id": "170785a13fd7-0", "text": "langchain.tools.searx_search.tool.SearxSearchResults\u00b6\nclass langchain.tools.searx_search.tool.SearxSearchResults[source]\u00b6\nBases: BaseTool\nTool that queries a Searx instance and gets back json.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A meta search engine.Useful for when you need to answer questions about current events.Input should be a search query. Output is a JSON array of the query results'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam kwargs: dict [Optional]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'Searx-Search-Results'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam num_results: int = 4\u00b6\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchResults.html"}
{"id": "170785a13fd7-1", "text": "param num_results: int = 4\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\nparam wrapper: langchain.utilities.searx_search.SearxSearchWrapper [Required]\u00b6\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchResults.html"}
{"id": "170785a13fd7-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchResults.html"}
{"id": "170785a13fd7-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchResults.html"}
{"id": "170785a13fd7-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchResults.html"}
{"id": "170785a13fd7-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchResults.html"}
{"id": "170785a13fd7-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchResults.html"}
{"id": "170785a13fd7-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchResults.html"}
{"id": "170785a13fd7-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchResults.html"}
{"id": "170785a13fd7-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using SearxSearchResults\u00b6\nSearxNG Search API", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchResults.html"}
{"id": "c50d3955f540-0", "text": "langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksToolInput\u00b6\nclass langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksToolInput[source]\u00b6\nBases: BaseModel\nInput for ExtractHyperlinksTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam absolute_urls: bool = False\u00b6\nReturn absolute URLs instead of relative URLs\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksToolInput.html"}
{"id": "c50d3955f540-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksToolInput.html"}
{"id": "c50d3955f540-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksToolInput.html"}
{"id": "1aba1a3bd0f2-0", "text": "langchain.tools.base.BaseTool\u00b6\nclass langchain.tools.base.BaseTool[source]\u00b6\nBases: RunnableSerializable[Union[str, Dict], Any]\nInterface LangChain tools must implement.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[pydantic.main.BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[langchain.schema.callbacks.base.BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Optional[Union[List[langchain.schema.callbacks.base.BaseCallbackHandler], langchain.schema.callbacks.base.BaseCallbackManager]] = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str [Required]\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.BaseTool.html"}
{"id": "1aba1a3bd0f2-1", "text": "param tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str[source]\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.BaseTool.html"}
{"id": "1aba1a3bd0f2-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.BaseTool.html"}
{"id": "1aba1a3bd0f2-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.BaseTool.html"}
{"id": "1aba1a3bd0f2-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.BaseTool.html"}
{"id": "1aba1a3bd0f2-5", "text": "The tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.BaseTool.html"}
{"id": "1aba1a3bd0f2-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.BaseTool.html"}
{"id": "1aba1a3bd0f2-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.BaseTool.html"}
{"id": "1aba1a3bd0f2-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.BaseTool.html"}
{"id": "1aba1a3bd0f2-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using BaseTool\u00b6\n!pip install bs4\nDefining Custom Tools\nCombine agents and vector stores\nCustom functions with OpenAI Functions Agent", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.BaseTool.html"}
{"id": "5ce66c9a26cf-0", "text": "langchain.tools.base.ToolException\u00b6\nclass langchain.tools.base.ToolException[source]\u00b6\nAn optional exception that tool throws when execution error occurs.\nWhen this exception is thrown, the agent will not stop working,\nbut will handle the exception according to the handle_tool_error\nvariable of the tool, and the processing result will be returned\nto the agent as observation, and printed in red on the console.\nExamples using ToolException\u00b6\nDefining Custom Tools", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.ToolException.html"}
{"id": "27ef739f898c-0", "text": "langchain.tools.amadeus.closest_airport.ClosestAirportSchema\u00b6\nclass langchain.tools.amadeus.closest_airport.ClosestAirportSchema[source]\u00b6\nBases: BaseModel\nSchema for the AmadeusClosestAirport tool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam location: str [Required]\u00b6\nThe location for which you would like to find the nearest airport  along with optional details such as country, state, region, or  province, allowing for easy processing and identification of  the closest airport. Examples of the format are the following:\nCali, Colombia\nLincoln, Nebraska, United States\nNew York, United States\nSydney, New South Wales, Australia\nRome, Lazio, Italy\nToronto, Ontario, Canada\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.closest_airport.ClosestAirportSchema.html"}
{"id": "27ef739f898c-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.closest_airport.ClosestAirportSchema.html"}
{"id": "27ef739f898c-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.closest_airport.ClosestAirportSchema.html"}
{"id": "23d8a5a6e8b1-0", "text": "langchain.tools.office365.create_draft_message.O365CreateDraftMessage\u00b6\nclass langchain.tools.office365.create_draft_message.O365CreateDraftMessage[source]\u00b6\nBases: O365BaseTool\nTool for creating a draft email in Office 365.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam account: Account [Optional]\u00b6\nThe account object for the Office 365 account.\nparam args_schema: Type[langchain.tools.office365.create_draft_message.CreateDraftMessageSchema] = <class 'langchain.tools.office365.create_draft_message.CreateDraftMessageSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this tool to create a draft email with the provided message fields.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'create_email_draft'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.create_draft_message.O365CreateDraftMessage.html"}
{"id": "23d8a5a6e8b1-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.create_draft_message.O365CreateDraftMessage.html"}
{"id": "23d8a5a6e8b1-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.create_draft_message.O365CreateDraftMessage.html"}
{"id": "23d8a5a6e8b1-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.create_draft_message.O365CreateDraftMessage.html"}
{"id": "23d8a5a6e8b1-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.create_draft_message.O365CreateDraftMessage.html"}
{"id": "23d8a5a6e8b1-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.create_draft_message.O365CreateDraftMessage.html"}
{"id": "23d8a5a6e8b1-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.create_draft_message.O365CreateDraftMessage.html"}
{"id": "23d8a5a6e8b1-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.create_draft_message.O365CreateDraftMessage.html"}
{"id": "23d8a5a6e8b1-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.create_draft_message.O365CreateDraftMessage.html"}
{"id": "23d8a5a6e8b1-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.create_draft_message.O365CreateDraftMessage.html"}
{"id": "a46b4accc8e3-0", "text": "langchain.tools.render.render_text_description_and_args\u00b6\nlangchain.tools.render.render_text_description_and_args(tools: List[BaseTool]) \u2192 str[source]\u00b6\nRender the tool name, description, and args in plain text.\nOutput will be in the format of:\nsearch: This tool is used for search, args: {\"query\": {\"type\": \"string\"}}\ncalculator: This tool is used for math, args: {\"expression\": {\"type\": \"string\"}}", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.render.render_text_description_and_args.html"}
{"id": "1772f5699601-0", "text": "langchain.tools.openapi.utils.api_models.APIPropertyBase\u00b6\nclass langchain.tools.openapi.utils.api_models.APIPropertyBase[source]\u00b6\nBases: BaseModel\nBase model for an API property.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam default: Optional[Any] = None\u00b6\nThe default value of the property.\nparam description: Optional[str] = None\u00b6\nThe description of the property.\nparam name: str [Required]\u00b6\nThe name of the property.\nparam required: bool [Required]\u00b6\nWhether the property is required.\nparam type: Union[str, Type, tuple, None, enum.Enum] = None\u00b6\nThe type of the property.\nEither a primitive type, a component/parameter type,\nor an array or \u2018object\u2019 (dict) of the above.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIPropertyBase.html"}
{"id": "1772f5699601-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIPropertyBase.html"}
{"id": "1772f5699601-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIPropertyBase.html"}
{"id": "ff411bdaff75-0", "text": "langchain.tools.openapi.utils.api_models.APIPropertyLocation\u00b6\nclass langchain.tools.openapi.utils.api_models.APIPropertyLocation(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nThe location of the property.\nQUERY = 'query'\u00b6\nPATH = 'path'\u00b6\nHEADER = 'header'\u00b6\nCOOKIE = 'cookie'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIPropertyLocation.html"}
{"id": "fb1487d9286b-0", "text": "langchain.tools.json.tool.JsonListKeysTool\u00b6\nclass langchain.tools.json.tool.JsonListKeysTool[source]\u00b6\nBases: BaseTool\nTool for listing keys in a JSON spec.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = '\\n\u00a0\u00a0\u00a0 Can be used to list all keys at a given path. \\n\u00a0\u00a0\u00a0 Before calling this you should be SURE that the path to this exists.\\n\u00a0\u00a0\u00a0 The input is a text representation of the path to the dict in Python syntax (e.g. data[\"key1\"][0][\"key2\"]).\\n\u00a0\u00a0\u00a0 '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'json_spec_list_keys'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonListKeysTool.html"}
{"id": "fb1487d9286b-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam spec: JsonSpec [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonListKeysTool.html"}
{"id": "fb1487d9286b-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonListKeysTool.html"}
{"id": "fb1487d9286b-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonListKeysTool.html"}
{"id": "fb1487d9286b-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonListKeysTool.html"}
{"id": "fb1487d9286b-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonListKeysTool.html"}
{"id": "fb1487d9286b-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonListKeysTool.html"}
{"id": "fb1487d9286b-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonListKeysTool.html"}
{"id": "fb1487d9286b-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonListKeysTool.html"}
{"id": "fb1487d9286b-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonListKeysTool.html"}
{"id": "3b3bac67a808-0", "text": "langchain.tools.bearly.tool.head_file\u00b6\nlangchain.tools.bearly.tool.head_file(path: str, n: int) \u2192 List[str][source]\u00b6\nGet the first n lines of a file.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bearly.tool.head_file.html"}
{"id": "c7a853f37aa2-0", "text": "langchain.tools.youtube.search.YouTubeSearchTool\u00b6\nclass langchain.tools.youtube.search.YouTubeSearchTool[source]\u00b6\nBases: BaseTool\nTool that queries YouTube.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'search for youtube videos associated with a person. the input to this tool should be a comma separated list, the first part contains a person name and the second a number that is the maximum number of video results to return aka num_results. the second part is optional'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'youtube_search'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.youtube.search.YouTubeSearchTool.html"}
{"id": "c7a853f37aa2-1", "text": "that after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.youtube.search.YouTubeSearchTool.html"}
{"id": "c7a853f37aa2-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.youtube.search.YouTubeSearchTool.html"}
{"id": "c7a853f37aa2-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.youtube.search.YouTubeSearchTool.html"}
{"id": "c7a853f37aa2-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.youtube.search.YouTubeSearchTool.html"}
{"id": "c7a853f37aa2-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.youtube.search.YouTubeSearchTool.html"}
{"id": "c7a853f37aa2-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.youtube.search.YouTubeSearchTool.html"}
{"id": "c7a853f37aa2-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.youtube.search.YouTubeSearchTool.html"}
{"id": "c7a853f37aa2-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.youtube.search.YouTubeSearchTool.html"}
{"id": "c7a853f37aa2-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using YouTubeSearchTool\u00b6\nYouTube", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.youtube.search.YouTubeSearchTool.html"}
{"id": "aab8c5c6e050-0", "text": "langchain.tools.scenexplain.tool.SceneXplainTool\u00b6\nclass langchain.tools.scenexplain.tool.SceneXplainTool[source]\u00b6\nBases: BaseTool\nTool that explains images.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.scenexplain.SceneXplainAPIWrapper [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'An Image Captioning Tool: Use this tool to generate a detailed caption for an image. The input can be an image file of any format, and the output will be a text description that covers every detail of the image.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'image_explainer'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.scenexplain.tool.SceneXplainTool.html"}
{"id": "aab8c5c6e050-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.scenexplain.tool.SceneXplainTool.html"}
{"id": "aab8c5c6e050-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.scenexplain.tool.SceneXplainTool.html"}
{"id": "aab8c5c6e050-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.scenexplain.tool.SceneXplainTool.html"}
{"id": "aab8c5c6e050-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.scenexplain.tool.SceneXplainTool.html"}
{"id": "aab8c5c6e050-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.scenexplain.tool.SceneXplainTool.html"}
{"id": "aab8c5c6e050-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.scenexplain.tool.SceneXplainTool.html"}
{"id": "aab8c5c6e050-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.scenexplain.tool.SceneXplainTool.html"}
{"id": "aab8c5c6e050-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.scenexplain.tool.SceneXplainTool.html"}
{"id": "aab8c5c6e050-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using SceneXplainTool\u00b6\nSceneXplain", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.scenexplain.tool.SceneXplainTool.html"}
{"id": "405aed6cf18f-0", "text": "langchain.tools.ainetwork.base.AINBaseTool\u00b6\nclass langchain.tools.ainetwork.base.AINBaseTool[source]\u00b6\nBases: BaseTool\nBase class for the AINetwork tools.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str [Required]\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam interface: Ain [Optional]\u00b6\nThe interface object for the AINetwork Blockchain.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.base.AINBaseTool.html"}
{"id": "405aed6cf18f-1", "text": "Optional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.base.AINBaseTool.html"}
{"id": "405aed6cf18f-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.base.AINBaseTool.html"}
{"id": "405aed6cf18f-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.base.AINBaseTool.html"}
{"id": "405aed6cf18f-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.base.AINBaseTool.html"}
{"id": "405aed6cf18f-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.base.AINBaseTool.html"}
{"id": "405aed6cf18f-6", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.base.AINBaseTool.html"}
{"id": "405aed6cf18f-7", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.base.AINBaseTool.html"}
{"id": "405aed6cf18f-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.base.AINBaseTool.html"}
{"id": "405aed6cf18f-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.base.AINBaseTool.html"}
{"id": "da27fa6551b2-0", "text": "langchain.tools.openapi.utils.api_models.APIProperty\u00b6\nclass langchain.tools.openapi.utils.api_models.APIProperty[source]\u00b6\nBases: APIPropertyBase\nA model for a property in the query, path, header, or cookie params.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam default: Optional[Any] = None\u00b6\nThe default value of the property.\nparam description: Optional[str] = None\u00b6\nThe description of the property.\nparam location: langchain.tools.openapi.utils.api_models.APIPropertyLocation [Required]\u00b6\nThe path/how it\u2019s being passed to the endpoint.\nparam name: str [Required]\u00b6\nThe name of the property.\nparam required: bool [Required]\u00b6\nWhether the property is required.\nparam type: Union[str, Type, tuple, None, enum.Enum] = None\u00b6\nThe type of the property.\nEither a primitive type, a component/parameter type,\nor an array or \u2018object\u2019 (dict) of the above.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIProperty.html"}
{"id": "da27fa6551b2-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_parameter(parameter: Parameter, spec: OpenAPISpec) \u2192 APIProperty[source]\u00b6\nInstantiate from an OpenAPI Parameter.\nstatic is_supported_location(location: str) \u2192 bool[source]\u00b6\nReturn whether the provided location is supported.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIProperty.html"}
{"id": "da27fa6551b2-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIProperty.html"}
{"id": "e3f86428ad72-0", "text": "langchain.tools.base.create_schema_from_function\u00b6\nlangchain.tools.base.create_schema_from_function(model_name: str, func: Callable) \u2192 Type[BaseModel][source]\u00b6\nCreate a pydantic schema from a function\u2019s signature.\n:param model_name: Name to assign to the generated pydandic schema\n:param func: Function to generate the schema from\nReturns\nA pydantic model with the same arguments as the function", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.create_schema_from_function.html"}
{"id": "804f8567d9d6-0", "text": "langchain_experimental.tools.python.tool.PythonREPLTool\u00b6\nclass langchain_experimental.tools.python.tool.PythonREPLTool[source]\u00b6\nBases: BaseTool\nA tool for running python code in a REPL.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'Python_REPL'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam python_repl: langchain_experimental.utilities.python.PythonREPL [Optional]\u00b6\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonREPLTool.html"}
{"id": "804f8567d9d6-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam sanitize_input: bool = True\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonREPLTool.html"}
{"id": "804f8567d9d6-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonREPLTool.html"}
{"id": "804f8567d9d6-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonREPLTool.html"}
{"id": "804f8567d9d6-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonREPLTool.html"}
{"id": "804f8567d9d6-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonREPLTool.html"}
{"id": "804f8567d9d6-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonREPLTool.html"}
{"id": "804f8567d9d6-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonREPLTool.html"}
{"id": "804f8567d9d6-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonREPLTool.html"}
{"id": "804f8567d9d6-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using PythonREPLTool\u00b6\nPython", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonREPLTool.html"}
{"id": "bc2d89916d6d-0", "text": "langchain.tools.playwright.click.ClickToolInput\u00b6\nclass langchain.tools.playwright.click.ClickToolInput[source]\u00b6\nBases: BaseModel\nInput for ClickTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam selector: str [Required]\u00b6\nCSS selector for the element to click\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.click.ClickToolInput.html"}
{"id": "bc2d89916d6d-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.click.ClickToolInput.html"}
{"id": "bc2d89916d6d-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.click.ClickToolInput.html"}
{"id": "e0ea959ec5cd-0", "text": "langchain.tools.file_management.list_dir.DirectoryListingInput\u00b6\nclass langchain.tools.file_management.list_dir.DirectoryListingInput[source]\u00b6\nBases: BaseModel\nInput for ListDirectoryTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam dir_path: str = '.'\u00b6\nSubdirectory to list.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.list_dir.DirectoryListingInput.html"}
{"id": "e0ea959ec5cd-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.list_dir.DirectoryListingInput.html"}
{"id": "e0ea959ec5cd-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.list_dir.DirectoryListingInput.html"}
{"id": "6432c0e07b59-0", "text": "langchain.tools.file_management.utils.BaseFileToolMixin\u00b6\nclass langchain.tools.file_management.utils.BaseFileToolMixin[source]\u00b6\nBases: BaseModel\nMixin for file system tools.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam root_dir: Optional[str] = None\u00b6\nThe final path will be chosen relative to root_dir if specified.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.utils.BaseFileToolMixin.html"}
{"id": "6432c0e07b59-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_relative_path(file_path: str) \u2192 Path[source]\u00b6\nGet the relative path, returning an error if unsupported.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.utils.BaseFileToolMixin.html"}
{"id": "6432c0e07b59-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.utils.BaseFileToolMixin.html"}
{"id": "349ce3d17ded-0", "text": "langchain.tools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool\u00b6\nclass langchain.tools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool[source]\u00b6\nBases: BaseTool\nTool that queries the Azure Cognitive Services Form Recognizer API.\nIn order to set this up, follow instructions at:\nhttps://learn.microsoft.com/en-us/azure/applied-ai-services/form-recognizer/quickstarts/get-started-sdks-rest-api?view=form-recog-3.0.0&pivots=programming-language-python\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Azure Cognitive Services Form Recognizer. Useful for when you need to extract text, tables, and key-value pairs from documents. Input should be a url to a document.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool.html"}
{"id": "349ce3d17ded-1", "text": "You can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'azure_cognitive_services_form_recognizer'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool.html"}
{"id": "349ce3d17ded-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool.html"}
{"id": "349ce3d17ded-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool.html"}
{"id": "349ce3d17ded-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool.html"}
{"id": "349ce3d17ded-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool.html"}
{"id": "349ce3d17ded-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool.html"}
{"id": "349ce3d17ded-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool.html"}
{"id": "349ce3d17ded-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool.html"}
{"id": "349ce3d17ded-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool.html"}
{"id": "12b6d54eff4c-0", "text": "langchain.tools.ainetwork.owner.RuleSchema\u00b6\nclass langchain.tools.ainetwork.owner.RuleSchema[source]\u00b6\nBases: BaseModel\nSchema for owner operations.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam address: Optional[Union[str, List[str]]] = None\u00b6\nA single address or a list of addresses\nparam branch_owner: Optional[bool] = False\u00b6\nAuthority to initialize owner of sub-paths\nparam path: str [Required]\u00b6\nBlockchain reference path\nparam type: langchain.tools.ainetwork.base.OperationType [Required]\u00b6\nparam write_function: Optional[bool] = False\u00b6\nAuthority to set function for the path\nparam write_owner: Optional[bool] = False\u00b6\nAuthority to edit the owner property of the path\nparam write_rule: Optional[bool] = False\u00b6\nAuthority to edit write rule for the path\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.RuleSchema.html"}
{"id": "12b6d54eff4c-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.RuleSchema.html"}
{"id": "12b6d54eff4c-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.owner.RuleSchema.html"}
{"id": "0ea030f4dc5a-0", "text": "langchain.tools.ddg_search.tool.DDGInput\u00b6\nclass langchain.tools.ddg_search.tool.DDGInput[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam query: str [Required]\u00b6\nsearch query to look up\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DDGInput.html"}
{"id": "0ea030f4dc5a-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DDGInput.html"}
{"id": "2b52c521c39e-0", "text": "langchain.tools.bearly.tool.BearlyInterpreterTool\u00b6\nclass langchain.tools.bearly.tool.BearlyInterpreterTool(api_key: str)[source]\u00b6\nTool for evaluating python code in a sandbox environment.\nAttributes\ndescription\nendpoint\nfile_description\nfiles\nname\napi_key\nMethods\n__init__(api_key)\nadd_file(source_path,\u00a0target_path,\u00a0description)\nas_tool()\nclear_files()\nmake_input_files()\n__init__(api_key: str)[source]\u00b6\nadd_file(source_path: str, target_path: str, description: str) \u2192 None[source]\u00b6\nas_tool() \u2192 Tool[source]\u00b6\nclear_files() \u2192 None[source]\u00b6\nmake_input_files() \u2192 List[dict][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bearly.tool.BearlyInterpreterTool.html"}
{"id": "51f735a7f45e-0", "text": "langchain.tools.office365.utils.authenticate\u00b6\nlangchain.tools.office365.utils.authenticate() \u2192 Account[source]\u00b6\nAuthenticate using the Microsoft Grah API", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.utils.authenticate.html"}
{"id": "8b00859abf4d-0", "text": "langchain.tools.file_management.read.ReadFileInput\u00b6\nclass langchain.tools.file_management.read.ReadFileInput[source]\u00b6\nBases: BaseModel\nInput for ReadFileTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam file_path: str [Required]\u00b6\nname of file\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.read.ReadFileInput.html"}
{"id": "8b00859abf4d-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.read.ReadFileInput.html"}
{"id": "8b62efe80887-0", "text": "langchain.tools.bing_search.tool.BingSearchResults\u00b6\nclass langchain.tools.bing_search.tool.BingSearchResults[source]\u00b6\nBases: BaseTool\nTool that queries the Bing Search API and gets back json.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.bing_search.BingSearchAPIWrapper [Required]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Bing Search. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'Bing Search Results JSON'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam num_results: int = 4\u00b6\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchResults.html"}
{"id": "8b62efe80887-1", "text": "param num_results: int = 4\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchResults.html"}
{"id": "8b62efe80887-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchResults.html"}
{"id": "8b62efe80887-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchResults.html"}
{"id": "8b62efe80887-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchResults.html"}
{"id": "8b62efe80887-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchResults.html"}
{"id": "8b62efe80887-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchResults.html"}
{"id": "8b62efe80887-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchResults.html"}
{"id": "8b62efe80887-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchResults.html"}
{"id": "8b62efe80887-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchResults.html"}
{"id": "eb707600df49-0", "text": "langchain.tools.ddg_search.tool.DuckDuckGoSearchTool\u00b6\nlangchain.tools.ddg_search.tool.DuckDuckGoSearchTool(*args: Any, **kwargs: Any) \u2192 DuckDuckGoSearchRun[source]\u00b6\nDeprecated. Use DuckDuckGoSearchRun instead.\nParameters\n*args \u2013 \n**kwargs \u2013 \nReturns\nDuckDuckGoSearchRun", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchTool.html"}
{"id": "83c6b2e021fd-0", "text": "langchain.tools.file_management.utils.FileValidationError\u00b6\nclass langchain.tools.file_management.utils.FileValidationError[source]\u00b6\nError for paths outside the root directory.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.utils.FileValidationError.html"}
{"id": "9cb3601f22db-0", "text": "langchain.tools.edenai.image_explicitcontent.EdenAiExplicitImageTool\u00b6\nclass langchain.tools.edenai.image_explicitcontent.EdenAiExplicitImageTool[source]\u00b6\nBases: EdenaiTool\nTool that queries the Eden AI Explicit image detection.\nfor api reference check edenai documentation:\nhttps://docs.edenai.co/reference/image_explicit_content_create.\nTo use, you should have\nthe environment variable EDENAI_API_KEY set with your API token.\nYou can find your token here: https://app.edenai.run/admin/account/settings\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around edenai Services Explicit image detection. Useful for when you have to extract Explicit Content from images.\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 it detects adult only content in images, \\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 that is generally inappropriate for people under\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 the age of 18 and includes nudity, sexual activity,\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 pornography, violence, gore content, etc.Input should be the string url of the image .'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam edenai_api_key: Optional[str] = None\u00b6\nparam feature: str = 'image'\u00b6\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_explicitcontent.EdenAiExplicitImageTool.html"}
{"id": "9cb3601f22db-1", "text": "Handle the content of the ToolException thrown.\nparam is_async: bool = False\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'edenai_image_explicit_content_detection'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam providers: List[str] [Required]\u00b6\nprovider to use for the API call.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam subfeature: str = 'explicit_content'\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_explicitcontent.EdenAiExplicitImageTool.html"}
{"id": "9cb3601f22db-2", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_explicitcontent.EdenAiExplicitImageTool.html"}
{"id": "9cb3601f22db-3", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_explicitcontent.EdenAiExplicitImageTool.html"}
{"id": "9cb3601f22db-4", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_explicitcontent.EdenAiExplicitImageTool.html"}
{"id": "9cb3601f22db-5", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nstatic get_user_agent() \u2192 str\u00b6\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_explicitcontent.EdenAiExplicitImageTool.html"}
{"id": "9cb3601f22db-6", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_explicitcontent.EdenAiExplicitImageTool.html"}
{"id": "9cb3601f22db-7", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_explicitcontent.EdenAiExplicitImageTool.html"}
{"id": "9cb3601f22db-8", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_explicitcontent.EdenAiExplicitImageTool.html"}
{"id": "9cb3601f22db-9", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using EdenAiExplicitImageTool\u00b6\nEden AI", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_explicitcontent.EdenAiExplicitImageTool.html"}
{"id": "83a1c4f5ff3d-0", "text": "langchain.tools.spark_sql.tool.QueryCheckerTool\u00b6\nclass langchain.tools.spark_sql.tool.QueryCheckerTool[source]\u00b6\nBases: BaseSparkSQLTool, BaseTool\nUse an LLM to check if a query is correct.\nAdapted from https://www.patterns.app/blog/2023/01/18/crunchbot-sql-analyst-gpt/\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam db: SparkSQL [Required]\u00b6\nparam description: str = '\\n\u00a0\u00a0\u00a0 Use this tool to double check if your query is correct before executing it.\\n\u00a0\u00a0\u00a0 Always use this tool before executing a query with query_sql_db!\\n\u00a0\u00a0\u00a0 '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QueryCheckerTool.html"}
{"id": "83a1c4f5ff3d-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'query_checker_sql_db'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam template: str = '\\n{query}\\nDouble check the Spark SQL query above for common mistakes, including:\\n- Using NOT IN with NULL values\\n- Using UNION when UNION ALL should have been used\\n- Using BETWEEN for exclusive ranges\\n- Data type mismatch in predicates\\n- Properly quoting identifiers\\n- Using the correct number of arguments for functions\\n- Casting to the correct data type\\n- Using the proper columns for joins\\n\\nIf there are any of the above mistakes, rewrite the query. If there are no mistakes, just reproduce the original query.'\u00b6\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QueryCheckerTool.html"}
{"id": "83a1c4f5ff3d-2", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QueryCheckerTool.html"}
{"id": "83a1c4f5ff3d-3", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QueryCheckerTool.html"}
{"id": "83a1c4f5ff3d-4", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QueryCheckerTool.html"}
{"id": "83a1c4f5ff3d-5", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QueryCheckerTool.html"}
{"id": "83a1c4f5ff3d-6", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QueryCheckerTool.html"}
{"id": "83a1c4f5ff3d-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QueryCheckerTool.html"}
{"id": "83a1c4f5ff3d-8", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QueryCheckerTool.html"}
{"id": "83a1c4f5ff3d-9", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QueryCheckerTool.html"}
{"id": "83a1c4f5ff3d-10", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QueryCheckerTool.html"}
{"id": "bc23d2d36a26-0", "text": "langchain.tools.clickup.tool.ClickupAction\u00b6\nclass langchain.tools.clickup.tool.ClickupAction[source]\u00b6\nBases: BaseTool\nTool that queries the  Clickup API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.clickup.ClickupAPIWrapper [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = ''\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam mode: str [Required]\u00b6\nparam name: str = ''\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.clickup.tool.ClickupAction.html"}
{"id": "bc23d2d36a26-1", "text": "Optional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.clickup.tool.ClickupAction.html"}
{"id": "bc23d2d36a26-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.clickup.tool.ClickupAction.html"}
{"id": "bc23d2d36a26-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.clickup.tool.ClickupAction.html"}
{"id": "bc23d2d36a26-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.clickup.tool.ClickupAction.html"}
{"id": "bc23d2d36a26-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.clickup.tool.ClickupAction.html"}
{"id": "bc23d2d36a26-6", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.clickup.tool.ClickupAction.html"}
{"id": "bc23d2d36a26-7", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.clickup.tool.ClickupAction.html"}
{"id": "bc23d2d36a26-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.clickup.tool.ClickupAction.html"}
{"id": "bc23d2d36a26-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.clickup.tool.ClickupAction.html"}
{"id": "48f0a514f890-0", "text": "langchain.tools.file_management.utils.is_relative_to\u00b6\nlangchain.tools.file_management.utils.is_relative_to(path: Path, root: Path) \u2192 bool[source]\u00b6\nCheck if path is relative to root.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.utils.is_relative_to.html"}
{"id": "4b54f191e292-0", "text": "langchain.tools.ainetwork.transfer.AINTransfer\u00b6\nclass langchain.tools.ainetwork.transfer.AINTransfer[source]\u00b6\nBases: AINBaseTool\nTool for transfer operations.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[langchain.tools.ainetwork.transfer.TransferSchema] = <class 'langchain.tools.ainetwork.transfer.TransferSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Transfers AIN to a specified address'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam interface: Ain [Optional]\u00b6\nThe interface object for the AINetwork Blockchain.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'AINtransfer'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.transfer.AINTransfer.html"}
{"id": "4b54f191e292-1", "text": "that after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.transfer.AINTransfer.html"}
{"id": "4b54f191e292-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.transfer.AINTransfer.html"}
{"id": "4b54f191e292-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.transfer.AINTransfer.html"}
{"id": "4b54f191e292-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.transfer.AINTransfer.html"}
{"id": "4b54f191e292-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.transfer.AINTransfer.html"}
{"id": "4b54f191e292-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.transfer.AINTransfer.html"}
{"id": "4b54f191e292-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.transfer.AINTransfer.html"}
{"id": "4b54f191e292-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.transfer.AINTransfer.html"}
{"id": "4b54f191e292-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.transfer.AINTransfer.html"}
{"id": "eb4e42525d18-0", "text": "langchain.tools.playwright.base.BaseBrowserTool\u00b6\nclass langchain.tools.playwright.base.BaseBrowserTool[source]\u00b6\nBases: BaseTool\nBase class for browser tools.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam async_browser: Optional['AsyncBrowser'] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str [Required]\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam sync_browser: Optional['SyncBrowser'] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.base.BaseBrowserTool.html"}
{"id": "eb4e42525d18-1", "text": "Optional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.base.BaseBrowserTool.html"}
{"id": "eb4e42525d18-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.base.BaseBrowserTool.html"}
{"id": "eb4e42525d18-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.base.BaseBrowserTool.html"}
{"id": "eb4e42525d18-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_browser(sync_browser: Optional[SyncBrowser] = None, async_browser: Optional[AsyncBrowser] = None) \u2192 BaseBrowserTool[source]\u00b6\nInstantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.base.BaseBrowserTool.html"}
{"id": "eb4e42525d18-5", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.base.BaseBrowserTool.html"}
{"id": "eb4e42525d18-6", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.base.BaseBrowserTool.html"}
{"id": "eb4e42525d18-7", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.base.BaseBrowserTool.html"}
{"id": "eb4e42525d18-8", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.base.BaseBrowserTool.html"}
{"id": "eb4e42525d18-9", "text": "These attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.base.BaseBrowserTool.html"}
{"id": "525ede195613-0", "text": "langchain.tools.gmail.get_message.GmailGetMessage\u00b6\nclass langchain.tools.gmail.get_message.GmailGetMessage[source]\u00b6\nBases: GmailBaseTool\nTool that gets a message by ID from Gmail.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_resource: Resource [Optional]\u00b6\nparam args_schema: Type[langchain.tools.gmail.get_message.SearchArgsSchema] = <class 'langchain.tools.gmail.get_message.SearchArgsSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this tool to fetch an email by message ID. Returns the thread ID, snippet, body, subject, and sender.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'get_gmail_message'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_message.GmailGetMessage.html"}
{"id": "525ede195613-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_message.GmailGetMessage.html"}
{"id": "525ede195613-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_message.GmailGetMessage.html"}
{"id": "525ede195613-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_message.GmailGetMessage.html"}
{"id": "525ede195613-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_api_resource(api_resource: Resource) \u2192 GmailBaseTool\u00b6\nCreate a tool from an api resource.\nParameters\napi_resource \u2013 The api resource to use.\nReturns\nA tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_message.GmailGetMessage.html"}
{"id": "525ede195613-5", "text": "Returns\nA tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_message.GmailGetMessage.html"}
{"id": "525ede195613-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_message.GmailGetMessage.html"}
{"id": "525ede195613-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_message.GmailGetMessage.html"}
{"id": "525ede195613-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_message.GmailGetMessage.html"}
{"id": "525ede195613-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_message.GmailGetMessage.html"}
{"id": "97f44e3b4000-0", "text": "langchain.tools.bearly.tool.strip_markdown_code\u00b6\nlangchain.tools.bearly.tool.strip_markdown_code(md_string: str) \u2192 str[source]\u00b6\nStrip markdown code from a string.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bearly.tool.strip_markdown_code.html"}
{"id": "d67d60d178ff-0", "text": "langchain.tools.gitlab.tool.GitLabAction\u00b6\nclass langchain.tools.gitlab.tool.GitLabAction[source]\u00b6\nBases: BaseTool\nTool for interacting with the GitLab API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.gitlab.GitLabAPIWrapper [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = ''\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam mode: str [Required]\u00b6\nparam name: str = ''\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gitlab.tool.GitLabAction.html"}
{"id": "d67d60d178ff-1", "text": "Optional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gitlab.tool.GitLabAction.html"}
{"id": "d67d60d178ff-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gitlab.tool.GitLabAction.html"}
{"id": "d67d60d178ff-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gitlab.tool.GitLabAction.html"}
{"id": "d67d60d178ff-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gitlab.tool.GitLabAction.html"}
{"id": "d67d60d178ff-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gitlab.tool.GitLabAction.html"}
{"id": "d67d60d178ff-6", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gitlab.tool.GitLabAction.html"}
{"id": "d67d60d178ff-7", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gitlab.tool.GitLabAction.html"}
{"id": "d67d60d178ff-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gitlab.tool.GitLabAction.html"}
{"id": "d67d60d178ff-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gitlab.tool.GitLabAction.html"}
{"id": "50c40cee84ee-0", "text": "langchain.tools.playwright.utils.aget_current_page\u00b6\nasync langchain.tools.playwright.utils.aget_current_page(browser: AsyncBrowser) \u2192 AsyncPage[source]\u00b6\nAsynchronously get the current page of the browser.\nParameters\nbrowser \u2013 The browser (AsyncBrowser) to get the current page from.\nReturns\nThe current page.\nReturn type\nAsyncPage", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.utils.aget_current_page.html"}
{"id": "c20bf3217097-0", "text": "langchain.tools.tavily_search.tool.TavilyAnswer\u00b6\nclass langchain.tools.tavily_search.tool.TavilyAnswer[source]\u00b6\nBases: BaseTool\nTool that queries the Tavily Search API and gets back an answer.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.tavily_search.TavilySearchAPIWrapper [Required]\u00b6\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.tavily_search.tool.TavilyInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A search engine optimized for comprehensive, accurate, and trusted results. Useful for when you need to answer questions about current events. Input should be a search query. This returns only the answer - not the original source data.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'tavily_answer'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilyAnswer.html"}
{"id": "c20bf3217097-1", "text": "param name: str = 'tavily_answer'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilyAnswer.html"}
{"id": "c20bf3217097-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilyAnswer.html"}
{"id": "c20bf3217097-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilyAnswer.html"}
{"id": "c20bf3217097-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilyAnswer.html"}
{"id": "c20bf3217097-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilyAnswer.html"}
{"id": "c20bf3217097-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilyAnswer.html"}
{"id": "c20bf3217097-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilyAnswer.html"}
{"id": "c20bf3217097-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilyAnswer.html"}
{"id": "c20bf3217097-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilyAnswer.html"}
{"id": "e606a495657b-0", "text": "langchain.tools.multion.close_session.MultionCloseSession\u00b6\nclass langchain.tools.multion.close_session.MultionCloseSession[source]\u00b6\nBases: BaseTool\nTool that closes an existing Multion Browser Window with provided fields.\nname\u00b6\nThe name of the tool. Default: \u201cclose_multion_session\u201d\ndescription\u00b6\nThe description of the tool.\nargs_schema\u00b6\nThe schema for the tool\u2019s arguments. Default: UpdateSessionSchema\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[langchain.tools.multion.close_session.CloseSessionSchema] = <class 'langchain.tools.multion.close_session.CloseSessionSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this tool to close an existing corresponding Multion Browser Window with provided fields. Note: SessionId must be received from previous Browser window creation.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'close_multion_session'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.close_session.MultionCloseSession.html"}
{"id": "e606a495657b-1", "text": "param name: str = 'close_multion_session'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam sessionId: str = ''\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.close_session.MultionCloseSession.html"}
{"id": "e606a495657b-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.close_session.MultionCloseSession.html"}
{"id": "e606a495657b-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.close_session.MultionCloseSession.html"}
{"id": "e606a495657b-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.close_session.MultionCloseSession.html"}
{"id": "e606a495657b-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.close_session.MultionCloseSession.html"}
{"id": "e606a495657b-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.close_session.MultionCloseSession.html"}
{"id": "e606a495657b-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.close_session.MultionCloseSession.html"}
{"id": "e606a495657b-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.close_session.MultionCloseSession.html"}
{"id": "e606a495657b-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.close_session.MultionCloseSession.html"}
{"id": "fa8e60db471c-0", "text": "langchain.tools.gmail.create_draft.CreateDraftSchema\u00b6\nclass langchain.tools.gmail.create_draft.CreateDraftSchema[source]\u00b6\nBases: BaseModel\nInput for CreateDraftTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bcc: Optional[List[str]] = None\u00b6\nThe list of BCC recipients.\nparam cc: Optional[List[str]] = None\u00b6\nThe list of CC recipients.\nparam message: str [Required]\u00b6\nThe message to include in the draft.\nparam subject: str [Required]\u00b6\nThe subject of the message.\nparam to: List[str] [Required]\u00b6\nThe list of recipients.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.create_draft.CreateDraftSchema.html"}
{"id": "fa8e60db471c-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.create_draft.CreateDraftSchema.html"}
{"id": "fa8e60db471c-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.create_draft.CreateDraftSchema.html"}
{"id": "8afc8bc82596-0", "text": "langchain.tools.ainetwork.rule.RuleSchema\u00b6\nclass langchain.tools.ainetwork.rule.RuleSchema[source]\u00b6\nBases: BaseModel\nSchema for owner operations.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam eval: Optional[str] = None\u00b6\neval string to determine permission\nparam path: str [Required]\u00b6\nPath on the blockchain where the rule applies\nparam type: langchain.tools.ainetwork.base.OperationType [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.RuleSchema.html"}
{"id": "8afc8bc82596-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.RuleSchema.html"}
{"id": "8afc8bc82596-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.RuleSchema.html"}
{"id": "8e4795d19bff-0", "text": "langchain.tools.ainetwork.app.AppSchema\u00b6\nclass langchain.tools.ainetwork.app.AppSchema[source]\u00b6\nBases: BaseModel\nSchema for app operations.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam address: Optional[Union[str, List[str]]] = None\u00b6\nA single address or a list of addresses. Default: current session\u2019s address\nparam appName: str [Required]\u00b6\nName of the application on the blockchain\nparam type: langchain.tools.ainetwork.app.AppOperationType [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AppSchema.html"}
{"id": "8e4795d19bff-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AppSchema.html"}
{"id": "8e4795d19bff-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AppSchema.html"}
{"id": "af2054c0161f-0", "text": "langchain.tools.file_management.write.WriteFileTool\u00b6\nclass langchain.tools.file_management.write.WriteFileTool[source]\u00b6\nBases: BaseFileToolMixin, BaseTool\nTool that writes a file to disk.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.file_management.write.WriteFileInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Write file to disk'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'write_file'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam root_dir: Optional[str] = None\u00b6\nThe final path will be chosen relative to root_dir if specified.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.write.WriteFileTool.html"}
{"id": "af2054c0161f-1", "text": "The final path will be chosen relative to root_dir if specified.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.write.WriteFileTool.html"}
{"id": "af2054c0161f-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.write.WriteFileTool.html"}
{"id": "af2054c0161f-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.write.WriteFileTool.html"}
{"id": "af2054c0161f-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.write.WriteFileTool.html"}
{"id": "af2054c0161f-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relative_path(file_path: str) \u2192 Path\u00b6\nGet the relative path, returning an error if unsupported.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.write.WriteFileTool.html"}
{"id": "af2054c0161f-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.write.WriteFileTool.html"}
{"id": "af2054c0161f-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.write.WriteFileTool.html"}
{"id": "af2054c0161f-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.write.WriteFileTool.html"}
{"id": "af2054c0161f-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using WriteFileTool\u00b6\nFile System\nAutoGPT\n!pip install bs4", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.write.WriteFileTool.html"}
{"id": "ac8af543820b-0", "text": "langchain.tools.file_management.copy.CopyFileTool\u00b6\nclass langchain.tools.file_management.copy.CopyFileTool[source]\u00b6\nBases: BaseFileToolMixin, BaseTool\nTool that copies a file.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.file_management.copy.FileCopyInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Create a copy of a file in a specified location'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'copy_file'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam root_dir: Optional[str] = None\u00b6\nThe final path will be chosen relative to root_dir if specified.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.copy.CopyFileTool.html"}
{"id": "ac8af543820b-1", "text": "The final path will be chosen relative to root_dir if specified.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.copy.CopyFileTool.html"}
{"id": "ac8af543820b-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.copy.CopyFileTool.html"}
{"id": "ac8af543820b-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.copy.CopyFileTool.html"}
{"id": "ac8af543820b-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.copy.CopyFileTool.html"}
{"id": "ac8af543820b-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relative_path(file_path: str) \u2192 Path\u00b6\nGet the relative path, returning an error if unsupported.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.copy.CopyFileTool.html"}
{"id": "ac8af543820b-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.copy.CopyFileTool.html"}
{"id": "ac8af543820b-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.copy.CopyFileTool.html"}
{"id": "ac8af543820b-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.copy.CopyFileTool.html"}
{"id": "ac8af543820b-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using CopyFileTool\u00b6\nFile System", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.copy.CopyFileTool.html"}
{"id": "04ef76356c92-0", "text": "langchain.tools.amadeus.flight_search.AmadeusFlightSearch\u00b6\nclass langchain.tools.amadeus.flight_search.AmadeusFlightSearch[source]\u00b6\nBases: AmadeusBaseTool\nTool for searching for a single flight between two airports.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[langchain.tools.amadeus.flight_search.FlightSearchSchema] = <class 'langchain.tools.amadeus.flight_search.FlightSearchSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam client: Client [Optional]\u00b6\nparam description: str = ' Use this tool to search for a single flight between the origin and\u00a0 destination airports at a departure between an earliest and\u00a0 latest datetime. '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'single_flight_search'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.flight_search.AmadeusFlightSearch.html"}
{"id": "04ef76356c92-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.flight_search.AmadeusFlightSearch.html"}
{"id": "04ef76356c92-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.flight_search.AmadeusFlightSearch.html"}
{"id": "04ef76356c92-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.flight_search.AmadeusFlightSearch.html"}
{"id": "04ef76356c92-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.flight_search.AmadeusFlightSearch.html"}
{"id": "04ef76356c92-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.flight_search.AmadeusFlightSearch.html"}
{"id": "04ef76356c92-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.flight_search.AmadeusFlightSearch.html"}
{"id": "04ef76356c92-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.flight_search.AmadeusFlightSearch.html"}
{"id": "04ef76356c92-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.flight_search.AmadeusFlightSearch.html"}
{"id": "04ef76356c92-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.flight_search.AmadeusFlightSearch.html"}
{"id": "2e20472115e1-0", "text": "langchain.tools.gmail.utils.import_installed_app_flow\u00b6\nlangchain.tools.gmail.utils.import_installed_app_flow() \u2192 InstalledAppFlow[source]\u00b6\nImport InstalledAppFlow class.\nReturns\nInstalledAppFlow class.\nReturn type\nInstalledAppFlow", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.utils.import_installed_app_flow.html"}
{"id": "26c60335db39-0", "text": "langchain.tools.eleven_labs.text2speech.ElevenLabsText2SpeechTool\u00b6\nclass langchain.tools.eleven_labs.text2speech.ElevenLabsText2SpeechTool[source]\u00b6\nBases: BaseTool\nTool that queries the Eleven Labs Text2Speech API.\nIn order to set this up, follow instructions at:\nhttps://docs.elevenlabs.io/welcome/introduction\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Eleven Labs Text2Speech. Useful for when you need to convert text to speech. It supports multiple languages, including English, German, Polish, Spanish, Italian, French, Portuguese, and Hindi. '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.eleven_labs.text2speech.ElevenLabsText2SpeechTool.html"}
{"id": "26c60335db39-1", "text": "You can use these to eg identify a specific instance of a tool with its use case.\nparam model: Union[langchain.tools.eleven_labs.text2speech.ElevenLabsModel, str] = ElevenLabsModel.MULTI_LINGUAL\u00b6\nparam name: str = 'eleven_labs_text2speech'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.eleven_labs.text2speech.ElevenLabsText2SpeechTool.html"}
{"id": "26c60335db39-2", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.eleven_labs.text2speech.ElevenLabsText2SpeechTool.html"}
{"id": "26c60335db39-3", "text": "step, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.eleven_labs.text2speech.ElevenLabsText2SpeechTool.html"}
{"id": "26c60335db39-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.eleven_labs.text2speech.ElevenLabsText2SpeechTool.html"}
{"id": "26c60335db39-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.eleven_labs.text2speech.ElevenLabsText2SpeechTool.html"}
{"id": "26c60335db39-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplay(speech_file: str) \u2192 None[source]\u00b6\nPlay the text as speech.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.eleven_labs.text2speech.ElevenLabsText2SpeechTool.html"}
{"id": "26c60335db39-7", "text": "play(speech_file: str) \u2192 None[source]\u00b6\nPlay the text as speech.\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nstream_speech(query: str) \u2192 None[source]\u00b6\nStream the text as speech as it is generated.\nPlay the text in your speakers.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.eleven_labs.text2speech.ElevenLabsText2SpeechTool.html"}
{"id": "26c60335db39-8", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.eleven_labs.text2speech.ElevenLabsText2SpeechTool.html"}
{"id": "26c60335db39-9", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ElevenLabsText2SpeechTool\u00b6\nEleven Labs Text2Speech", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.eleven_labs.text2speech.ElevenLabsText2SpeechTool.html"}
{"id": "fb526d5db112-0", "text": "langchain.tools.gmail.search.Resource\u00b6\nclass langchain.tools.gmail.search.Resource(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnumerator of Resources to search.\nTHREADS = 'threads'\u00b6\nMESSAGES = 'messages'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.Resource.html"}
{"id": "35a47f7eed78-0", "text": "langchain.tools.multion.create_session.MultionCreateSession\u00b6\nclass langchain.tools.multion.create_session.MultionCreateSession[source]\u00b6\nBases: BaseTool\nTool that creates a new Multion Browser Window with provided fields.\nname\u00b6\nThe name of the tool. Default: \u201ccreate_multion_session\u201d\ndescription\u00b6\nThe description of the tool.\nargs_schema\u00b6\nThe schema for the tool\u2019s arguments.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[langchain.tools.multion.create_session.CreateSessionSchema] = <class 'langchain.tools.multion.create_session.CreateSessionSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = \"\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Create a new web browsing session based on a user's command or request.\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 The command should include the full info required for the session.\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Also include an url (defaults to google.com if no better option)\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 to start the session.\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Use this tool to create a new Browser Window with provided fields.\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Always the first step to run any activities that can be done using browser.\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.create_session.MultionCreateSession.html"}
{"id": "35a47f7eed78-1", "text": "Optional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'create_multion_session'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.create_session.MultionCreateSession.html"}
{"id": "35a47f7eed78-2", "text": "The default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.create_session.MultionCreateSession.html"}
{"id": "35a47f7eed78-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.create_session.MultionCreateSession.html"}
{"id": "35a47f7eed78-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.create_session.MultionCreateSession.html"}
{"id": "35a47f7eed78-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.create_session.MultionCreateSession.html"}
{"id": "35a47f7eed78-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.create_session.MultionCreateSession.html"}
{"id": "35a47f7eed78-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.create_session.MultionCreateSession.html"}
{"id": "35a47f7eed78-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.create_session.MultionCreateSession.html"}
{"id": "35a47f7eed78-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.create_session.MultionCreateSession.html"}
{"id": "5f42b24fdc1b-0", "text": "langchain.tools.playwright.utils.get_current_page\u00b6\nlangchain.tools.playwright.utils.get_current_page(browser: SyncBrowser) \u2192 SyncPage[source]\u00b6\nGet the current page of the browser.\n:param browser: The browser to get the current page from.\nReturns\nThe current page.\nReturn type\nSyncPage", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.utils.get_current_page.html"}
{"id": "17282c4f1da8-0", "text": "langchain.tools.jira.tool.JiraAction\u00b6\nclass langchain.tools.jira.tool.JiraAction[source]\u00b6\nBases: BaseTool\nTool that queries the Atlassian Jira API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.jira.JiraAPIWrapper [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = ''\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam mode: str [Required]\u00b6\nparam name: str = ''\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.jira.tool.JiraAction.html"}
{"id": "17282c4f1da8-1", "text": "Optional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.jira.tool.JiraAction.html"}
{"id": "17282c4f1da8-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.jira.tool.JiraAction.html"}
{"id": "17282c4f1da8-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.jira.tool.JiraAction.html"}
{"id": "17282c4f1da8-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.jira.tool.JiraAction.html"}
{"id": "17282c4f1da8-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.jira.tool.JiraAction.html"}
{"id": "17282c4f1da8-6", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.jira.tool.JiraAction.html"}
{"id": "17282c4f1da8-7", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.jira.tool.JiraAction.html"}
{"id": "17282c4f1da8-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.jira.tool.JiraAction.html"}
{"id": "17282c4f1da8-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.jira.tool.JiraAction.html"}
{"id": "af516bf2811f-0", "text": "langchain.tools.retriever.create_retriever_tool\u00b6\nlangchain.tools.retriever.create_retriever_tool(retriever: BaseRetriever, name: str, description: str) \u2192 Tool[source]\u00b6\nCreate a tool to do retrieval of documents.\nParameters\nretriever \u2013 The retriever to use for the retrieval\nname \u2013 The name for the tool. This will be passed to the language model,\nso should be unique and somewhat descriptive.\ndescription \u2013 The description for the tool. This will be passed to the language\nmodel, so should be descriptive.\nReturns\nTool class to pass to an agent\nExamples using create_retriever_tool\u00b6\nXata chat memory\nConversational Retrieval Agent\nSet env var OPENAI_API_KEY or load from a .env file\nSQL", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.retriever.create_retriever_tool.html"}
{"id": "60d03b8a659e-0", "text": "langchain.tools.requests.tool.BaseRequestsTool\u00b6\nclass langchain.tools.requests.tool.BaseRequestsTool[source]\u00b6\nBases: BaseModel\nBase class for requests tools.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam requests_wrapper: langchain.utilities.requests.TextRequestsWrapper [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.BaseRequestsTool.html"}
{"id": "60d03b8a659e-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.BaseRequestsTool.html"}
{"id": "60d03b8a659e-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.BaseRequestsTool.html"}
{"id": "bfe82d2955b2-0", "text": "langchain.tools.playwright.get_elements.GetElementsToolInput\u00b6\nclass langchain.tools.playwright.get_elements.GetElementsToolInput[source]\u00b6\nBases: BaseModel\nInput for GetElementsTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam attributes: List[str] [Optional]\u00b6\nSet of attributes to retrieve for each element\nparam selector: str [Required]\u00b6\nCSS selector, such as \u2018*\u2019, \u2018div\u2019, \u2018p\u2019, \u2018a\u2019, #id, .classname\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.get_elements.GetElementsToolInput.html"}
{"id": "bfe82d2955b2-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.get_elements.GetElementsToolInput.html"}
{"id": "bfe82d2955b2-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.get_elements.GetElementsToolInput.html"}
{"id": "b531277eea51-0", "text": "langchain.tools.vectorstore.tool.VectorStoreQATool\u00b6\nclass langchain.tools.vectorstore.tool.VectorStoreQATool[source]\u00b6\nBases: BaseVectorStoreTool, BaseTool\nTool for the VectorDBQA chain. To be initialized with name and chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str [Required]\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam llm: BaseLanguageModel [Optional]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQATool.html"}
{"id": "b531277eea51-1", "text": "Optional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam vectorstore: VectorStore [Required]\u00b6\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQATool.html"}
{"id": "b531277eea51-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQATool.html"}
{"id": "b531277eea51-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQATool.html"}
{"id": "b531277eea51-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nstatic get_description(name: str, description: str) \u2192 str[source]\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQATool.html"}
{"id": "b531277eea51-5", "text": "The tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQATool.html"}
{"id": "b531277eea51-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQATool.html"}
{"id": "b531277eea51-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQATool.html"}
{"id": "b531277eea51-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQATool.html"}
{"id": "b531277eea51-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQATool.html"}
{"id": "3de9fbb83ada-0", "text": "langchain.tools.arxiv.tool.ArxivInput\u00b6\nclass langchain.tools.arxiv.tool.ArxivInput[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam query: str [Required]\u00b6\nsearch query to look up\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.arxiv.tool.ArxivInput.html"}
{"id": "3de9fbb83ada-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.arxiv.tool.ArxivInput.html"}
{"id": "302048984cdd-0", "text": "langchain.tools.interaction.tool.StdInInquireTool\u00b6\nlangchain.tools.interaction.tool.StdInInquireTool(*args: Any, **kwargs: Any) \u2192 HumanInputRun[source]\u00b6\nTool for asking the user for input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.interaction.tool.StdInInquireTool.html"}
{"id": "234ef38dc839-0", "text": "langchain.tools.searx_search.tool.SearxSearchRun\u00b6\nclass langchain.tools.searx_search.tool.SearxSearchRun[source]\u00b6\nBases: BaseTool\nTool that queries a Searx instance.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A meta search engine.Useful for when you need to answer questions about current events.Input should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam kwargs: dict [Optional]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'searx_search'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchRun.html"}
{"id": "234ef38dc839-1", "text": "param tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\nparam wrapper: langchain.utilities.searx_search.SearxSearchWrapper [Required]\u00b6\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchRun.html"}
{"id": "234ef38dc839-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchRun.html"}
{"id": "234ef38dc839-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchRun.html"}
{"id": "234ef38dc839-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchRun.html"}
{"id": "234ef38dc839-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchRun.html"}
{"id": "234ef38dc839-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchRun.html"}
{"id": "234ef38dc839-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchRun.html"}
{"id": "234ef38dc839-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchRun.html"}
{"id": "234ef38dc839-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searx_search.tool.SearxSearchRun.html"}
{"id": "64c4563dc595-0", "text": "langchain.tools.google_search.tool.GoogleSearchRun\u00b6\nclass langchain.tools.google_search.tool.GoogleSearchRun[source]\u00b6\nBases: BaseTool\nTool that queries the Google search API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.google_search.GoogleSearchAPIWrapper [Required]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Google Search. Useful for when you need to answer questions about current events. Input should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'google_search'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchRun.html"}
{"id": "64c4563dc595-1", "text": "param tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchRun.html"}
{"id": "64c4563dc595-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchRun.html"}
{"id": "64c4563dc595-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchRun.html"}
{"id": "64c4563dc595-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchRun.html"}
{"id": "64c4563dc595-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchRun.html"}
{"id": "64c4563dc595-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchRun.html"}
{"id": "64c4563dc595-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchRun.html"}
{"id": "64c4563dc595-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchRun.html"}
{"id": "64c4563dc595-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchRun.html"}
{"id": "69818db7b618-0", "text": "langchain.tools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool\u00b6\nclass langchain.tools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool[source]\u00b6\nBases: BaseTool\nTool that queries the Azure Cognitive Services Image Analysis API.\nIn order to set this up, follow instructions at:\nhttps://learn.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts-sdk/image-analysis-client-library-40\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Azure Cognitive Services Image Analysis. Useful for when you need to analyze images. Input should be a url to an image.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'azure_cognitive_services_image_analysis'\u00b6\nThe unique name of the tool that clearly communicates its purpose.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool.html"}
{"id": "69818db7b618-1", "text": "The unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool.html"}
{"id": "69818db7b618-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool.html"}
{"id": "69818db7b618-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool.html"}
{"id": "69818db7b618-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool.html"}
{"id": "69818db7b618-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool.html"}
{"id": "69818db7b618-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool.html"}
{"id": "69818db7b618-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool.html"}
{"id": "69818db7b618-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool.html"}
{"id": "69818db7b618-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool.html"}
{"id": "ba4a3e5cbfdb-0", "text": "langchain.tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool\u00b6\nclass langchain.tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool[source]\u00b6\nBases: EdenaiTool\nTool that queries the Eden AI Text to speech API.\nfor api reference check edenai documentation:\nhttps://docs.edenai.co/reference/audio_text_to_speech_create.\nTo use, you should have\nthe environment variable EDENAI_API_KEY set with your API token.\nYou can find your token here: https://app.edenai.run/admin/account/settings\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam audio_format: Optional[str] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around edenai Services text to speech.Useful for when you need to convert text to speech.the output is a string representing the URL of the audio file,\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 or the path to the downloaded wav file '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam edenai_api_key: Optional[str] = None\u00b6\nparam feature: str = 'audio'\u00b6\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam is_async: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool.html"}
{"id": "ba4a3e5cbfdb-1", "text": "Handle the content of the ToolException thrown.\nparam is_async: bool = False\u00b6\nparam language: Optional[str] = 'en'\u00b6\nlanguage of the text passed to the model.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'edenai_text_to_speech'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam pitch: Optional[int] = None\u00b6\nparam providers: List[str] [Required]\u00b6\nprovider to use for the API call.\nparam rate: Optional[int] = None\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam return_type: Literal['url', 'wav'] = 'url'\u00b6\nparam sampling_rate: Optional[int] = None\u00b6\nparam subfeature: str = 'text_to_speech'\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\nparam voice: Literal['MALE', 'FEMALE'] [Required]\u00b6\nvoice option : \u2018MALE\u2019 or \u2018FEMALE\u2019\nparam voice_models: Dict[str, str] [Optional]\u00b6\nparam volume: Optional[int] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool.html"}
{"id": "ba4a3e5cbfdb-2", "text": "param volume: Optional[int] = None\u00b6\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool.html"}
{"id": "ba4a3e5cbfdb-3", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool.html"}
{"id": "ba4a3e5cbfdb-4", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool.html"}
{"id": "ba4a3e5cbfdb-5", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nstatic get_user_agent() \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool.html"}
{"id": "ba4a3e5cbfdb-6", "text": "static get_user_agent() \u2192 str\u00b6\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool.html"}
{"id": "ba4a3e5cbfdb-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool.html"}
{"id": "ba4a3e5cbfdb-8", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool.html"}
{"id": "ba4a3e5cbfdb-9", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool.html"}
{"id": "ba4a3e5cbfdb-10", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using EdenAiTextToSpeechTool\u00b6\nEden AI", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool.html"}
{"id": "9089ed628637-0", "text": "langchain.tools.edenai.text_moderation.EdenAiTextModerationTool\u00b6\nclass langchain.tools.edenai.text_moderation.EdenAiTextModerationTool[source]\u00b6\nBases: EdenaiTool\nTool that queries the Eden AI Explicit text detection.\nfor api reference check edenai documentation:\nhttps://docs.edenai.co/reference/image_explicit_content_create.\nTo use, you should have\nthe environment variable EDENAI_API_KEY set with your API token.\nYou can find your token here: https://app.edenai.run/admin/account/settings\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.text_moderation.EdenAiTextModerationTool.html"}
{"id": "9089ed628637-1", "text": "param callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = \"A wrapper around edenai Services explicit content detection for text. Useful for when you have to scan text for offensive, \\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 sexually explicit or suggestive content,\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 it checks also if there is any content of self-harm,\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 violence, racist or hate speech.the structure of the output is : \\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 'the type of the explicit content : the likelihood of it being explicit'\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 the likelihood is a number \\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 between 1 and 5, 1 being the lowest and 5 the highest.\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 something is explicit if the likelihood is equal or higher than 3.\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 for example : \\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 nsfw_likelihood: 1\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 this is not explicit.\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 for example : \\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 nsfw_likelihood: 3\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 this is explicit.\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Input should be a string.\"\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam edenai_api_key: Optional[str] = None\u00b6\nparam feature: str = 'text'\u00b6\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam is_async: bool = False\u00b6\nparam language: str [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'edenai_explicit_content_detection_text'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.text_moderation.EdenAiTextModerationTool.html"}
{"id": "9089ed628637-2", "text": "param name: str = 'edenai_explicit_content_detection_text'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam providers: List[str] [Required]\u00b6\nprovider to use for the API call.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam subfeature: str = 'moderation'\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.text_moderation.EdenAiTextModerationTool.html"}
{"id": "9089ed628637-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.text_moderation.EdenAiTextModerationTool.html"}
{"id": "9089ed628637-4", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.text_moderation.EdenAiTextModerationTool.html"}
{"id": "9089ed628637-5", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.text_moderation.EdenAiTextModerationTool.html"}
{"id": "9089ed628637-6", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nstatic get_user_agent() \u2192 str\u00b6\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.text_moderation.EdenAiTextModerationTool.html"}
{"id": "9089ed628637-7", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.text_moderation.EdenAiTextModerationTool.html"}
{"id": "9089ed628637-8", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.text_moderation.EdenAiTextModerationTool.html"}
{"id": "9089ed628637-9", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.text_moderation.EdenAiTextModerationTool.html"}
{"id": "9089ed628637-10", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using EdenAiTextModerationTool\u00b6\nEden AI", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.text_moderation.EdenAiTextModerationTool.html"}
{"id": "fc74d1436a01-0", "text": "langchain.tools.file_management.move.MoveFileTool\u00b6\nclass langchain.tools.file_management.move.MoveFileTool[source]\u00b6\nBases: BaseFileToolMixin, BaseTool\nTool that moves a file.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.file_management.move.FileMoveInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Move or rename a file from one location to another'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'move_file'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam root_dir: Optional[str] = None\u00b6\nThe final path will be chosen relative to root_dir if specified.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.move.MoveFileTool.html"}
{"id": "fc74d1436a01-1", "text": "The final path will be chosen relative to root_dir if specified.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.move.MoveFileTool.html"}
{"id": "fc74d1436a01-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.move.MoveFileTool.html"}
{"id": "fc74d1436a01-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.move.MoveFileTool.html"}
{"id": "fc74d1436a01-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.move.MoveFileTool.html"}
{"id": "fc74d1436a01-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relative_path(file_path: str) \u2192 Path\u00b6\nGet the relative path, returning an error if unsupported.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.move.MoveFileTool.html"}
{"id": "fc74d1436a01-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.move.MoveFileTool.html"}
{"id": "fc74d1436a01-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.move.MoveFileTool.html"}
{"id": "fc74d1436a01-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.move.MoveFileTool.html"}
{"id": "fc74d1436a01-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using MoveFileTool\u00b6\nFile System\nTools as OpenAI Functions", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.move.MoveFileTool.html"}
{"id": "7c9d0d0ffabe-0", "text": "langchain.tools.office365.events_search.SearchEventsInput\u00b6\nclass langchain.tools.office365.events_search.SearchEventsInput[source]\u00b6\nBases: BaseModel\nInput for SearchEmails Tool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam end_datetime: str [Required]\u00b6\nThe end datetime for the search query in the following format:  YYYY-MM-DDTHH:MM:SS\u00b1hh:mm, where \u201cT\u201d separates the date and time  components, and the time zone offset is specified as \u00b1hh:mm.  For example: \u201c2023-06-09T10:30:00+03:00\u201d represents June 9th,  2023, at 10:30 AM in a time zone with a positive offset of 3  hours from Coordinated Universal Time (UTC).\nparam max_results: int = 10\u00b6\nThe maximum number of results to return.\nparam start_datetime: str [Required]\u00b6\nThe start datetime for the search query in the following format:  YYYY-MM-DDTHH:MM:SS\u00b1hh:mm, where \u201cT\u201d separates the date and time  components, and the time zone offset is specified as \u00b1hh:mm.  For example: \u201c2023-06-09T10:30:00+03:00\u201d represents June 9th,  2023, at 10:30 AM in a time zone with a positive offset of 3  hours from Coordinated Universal Time (UTC).\nparam truncate: bool = True\u00b6\nWhether the event\u2019s body is truncated to meet token number limits. Set to False for searches that will retrieve very few results, otherwise, set to True.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.events_search.SearchEventsInput.html"}
{"id": "7c9d0d0ffabe-1", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.events_search.SearchEventsInput.html"}
{"id": "7c9d0d0ffabe-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.events_search.SearchEventsInput.html"}
{"id": "84900a9f1d8a-0", "text": "langchain.tools.spark_sql.tool.QuerySparkSQLTool\u00b6\nclass langchain.tools.spark_sql.tool.QuerySparkSQLTool[source]\u00b6\nBases: BaseSparkSQLTool, BaseTool\nTool for querying a Spark SQL.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam db: SparkSQL [Required]\u00b6\nparam description: str = '\\n\u00a0\u00a0\u00a0 Input to this tool is a detailed and correct SQL query, output is a result from the Spark SQL.\\n\u00a0\u00a0\u00a0 If the query is not correct, an error message will be returned.\\n\u00a0\u00a0\u00a0 If an error is returned, rewrite the query, check the query, and try again.\\n\u00a0\u00a0\u00a0 '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'query_sql_db'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QuerySparkSQLTool.html"}
{"id": "84900a9f1d8a-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QuerySparkSQLTool.html"}
{"id": "84900a9f1d8a-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QuerySparkSQLTool.html"}
{"id": "84900a9f1d8a-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QuerySparkSQLTool.html"}
{"id": "84900a9f1d8a-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QuerySparkSQLTool.html"}
{"id": "84900a9f1d8a-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QuerySparkSQLTool.html"}
{"id": "84900a9f1d8a-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QuerySparkSQLTool.html"}
{"id": "84900a9f1d8a-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QuerySparkSQLTool.html"}
{"id": "84900a9f1d8a-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QuerySparkSQLTool.html"}
{"id": "84900a9f1d8a-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.QuerySparkSQLTool.html"}
{"id": "b2268d032f3d-0", "text": "langchain.tools.base.StructuredTool\u00b6\nclass langchain.tools.base.StructuredTool[source]\u00b6\nBases: BaseTool\nTool that can operate on any number of inputs.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] [Required]\u00b6\nThe input arguments\u2019 schema.\nThe tool schema.\nparam callback_manager: Optional[langchain.schema.callbacks.base.BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Optional[Union[List[langchain.schema.callbacks.base.BaseCallbackHandler], langchain.schema.callbacks.base.BaseCallbackManager]] = None\u00b6\nCallbacks to be called during tool execution.\nparam coroutine: Optional[Callable[[...], Awaitable[Any]]] = None\u00b6\nThe asynchronous version of the function.\nparam description: str = ''\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam func: Optional[Callable[[...], Any]] = None\u00b6\nThe function to run when the tool is called.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.StructuredTool.html"}
{"id": "b2268d032f3d-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.StructuredTool.html"}
{"id": "b2268d032f3d-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.StructuredTool.html"}
{"id": "b2268d032f3d-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.StructuredTool.html"}
{"id": "b2268d032f3d-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.StructuredTool.html"}
{"id": "b2268d032f3d-5", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_function(func: Optional[Callable] = None, coroutine: Optional[Callable[[...], Awaitable[Any]]] = None, name: Optional[str] = None, description: Optional[str] = None, return_direct: bool = False, args_schema: Optional[Type[BaseModel]] = None, infer_schema: bool = True, **kwargs: Any) \u2192 StructuredTool[source]\u00b6\nCreate tool from a given function.\nA classmethod that helps to create a tool from a function.\nParameters\nfunc \u2013 The function from which to create a tool\ncoroutine \u2013 The async function from which to create a tool\nname \u2013 The name of the tool. Defaults to the function name\ndescription \u2013 The description of the tool. Defaults to the function docstring\nreturn_direct \u2013 Whether to return the result directly or as a callback\nargs_schema \u2013 The schema of the tool\u2019s input arguments\ninfer_schema \u2013 Whether to infer the schema from the function\u2019s signature\n**kwargs \u2013 Additional arguments to pass to the tool\nReturns\nThe tool\nExamples\ndef add(a: int, b: int) -> int:\n    \"\"\"Add two numbers\"\"\"\n    return a + b\ntool = StructuredTool.from_function(add)\ntool.run(1, 2) # 3\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.StructuredTool.html"}
{"id": "b2268d032f3d-6", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.StructuredTool.html"}
{"id": "b2268d032f3d-7", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.StructuredTool.html"}
{"id": "b2268d032f3d-8", "text": "stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.StructuredTool.html"}
{"id": "b2268d032f3d-9", "text": "Bind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nThe tool\u2019s input arguments.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.StructuredTool.html"}
{"id": "b2268d032f3d-10", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using StructuredTool\u00b6\nMulti-Input Tools\nDefining Custom Tools", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.StructuredTool.html"}
{"id": "001c542ccc39-0", "text": "langchain.tools.amadeus.closest_airport.AmadeusClosestAirport\u00b6\nclass langchain.tools.amadeus.closest_airport.AmadeusClosestAirport[source]\u00b6\nBases: AmadeusBaseTool\nTool for finding the closest airport to a particular location.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[langchain.tools.amadeus.closest_airport.ClosestAirportSchema] = <class 'langchain.tools.amadeus.closest_airport.ClosestAirportSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam client: Client [Optional]\u00b6\nparam description: str = 'Use this tool to find the closest airport to a particular location.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'closest_airport'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.closest_airport.AmadeusClosestAirport.html"}
{"id": "001c542ccc39-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.closest_airport.AmadeusClosestAirport.html"}
{"id": "001c542ccc39-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.closest_airport.AmadeusClosestAirport.html"}
{"id": "001c542ccc39-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.closest_airport.AmadeusClosestAirport.html"}
{"id": "001c542ccc39-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.closest_airport.AmadeusClosestAirport.html"}
{"id": "001c542ccc39-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.closest_airport.AmadeusClosestAirport.html"}
{"id": "001c542ccc39-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.closest_airport.AmadeusClosestAirport.html"}
{"id": "001c542ccc39-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.closest_airport.AmadeusClosestAirport.html"}
{"id": "001c542ccc39-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.closest_airport.AmadeusClosestAirport.html"}
{"id": "001c542ccc39-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.closest_airport.AmadeusClosestAirport.html"}
{"id": "e15cf4fba98f-0", "text": "langchain.tools.vectorstore.tool.BaseVectorStoreTool\u00b6\nclass langchain.tools.vectorstore.tool.BaseVectorStoreTool[source]\u00b6\nBases: BaseModel\nBase class for tools that use a VectorStore.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam llm: langchain.schema.language_model.BaseLanguageModel [Optional]\u00b6\nparam vectorstore: langchain.schema.vectorstore.VectorStore [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.BaseVectorStoreTool.html"}
{"id": "e15cf4fba98f-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.BaseVectorStoreTool.html"}
{"id": "e15cf4fba98f-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.BaseVectorStoreTool.html"}
{"id": "fa41726730e4-0", "text": "langchain.tools.e2b_data_analysis.unparse.interleave\u00b6\nlangchain.tools.e2b_data_analysis.unparse.interleave(inter, f, seq)[source]\u00b6\nCall f on each item in seq, calling inter() in between.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.unparse.interleave.html"}
{"id": "4b0f63271c2d-0", "text": "langchain.tools.base.tool\u00b6\nlangchain.tools.base.tool(*args: Union[str, Callable, Runnable], return_direct: bool = False, args_schema: Optional[Type[BaseModel]] = None, infer_schema: bool = True) \u2192 Callable[source]\u00b6\nMake tools out of functions, can be used with or without arguments.\nParameters\n*args \u2013 The arguments to the tool.\nreturn_direct \u2013 Whether to return directly from the tool rather\nthan continuing the agent loop.\nargs_schema \u2013 optional argument schema for user to specify\ninfer_schema \u2013 Whether to infer the schema of the arguments from\nthe function\u2019s signature. This also makes the resultant tool\naccept a dictionary input to its run() function.\nRequires:\nFunction must be of type (str) -> str\nFunction must have a docstring\nExamples\n@tool\ndef search_api(query: str) -> str:\n    # Searches the API for the query.\n    return\n@tool(\"search\", return_direct=True)\ndef search_api(query: str) -> str:\n    # Searches the API for the query.\n    return\nExamples using tool\u00b6\nMetaphor Search\nLLMonitor\nJSONFormer\nAgent Trajectory\nAgents\n!pip install bs4\nDefining Custom Tools\nXML Agent", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.tool.html"}
{"id": "f8075cd37e89-0", "text": "langchain.tools.spark_sql.tool.ListSparkSQLTool\u00b6\nclass langchain.tools.spark_sql.tool.ListSparkSQLTool[source]\u00b6\nBases: BaseSparkSQLTool, BaseTool\nTool for getting tables names.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam db: SparkSQL [Required]\u00b6\nparam description: str = 'Input is an empty string, output is a comma separated list of tables in the Spark SQL.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'list_tables_sql_db'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.ListSparkSQLTool.html"}
{"id": "f8075cd37e89-1", "text": "param tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.ListSparkSQLTool.html"}
{"id": "f8075cd37e89-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.ListSparkSQLTool.html"}
{"id": "f8075cd37e89-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.ListSparkSQLTool.html"}
{"id": "f8075cd37e89-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.ListSparkSQLTool.html"}
{"id": "f8075cd37e89-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.ListSparkSQLTool.html"}
{"id": "f8075cd37e89-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.ListSparkSQLTool.html"}
{"id": "f8075cd37e89-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.ListSparkSQLTool.html"}
{"id": "f8075cd37e89-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.ListSparkSQLTool.html"}
{"id": "f8075cd37e89-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.ListSparkSQLTool.html"}
{"id": "47931b386666-0", "text": "langchain.tools.file_management.read.ReadFileTool\u00b6\nclass langchain.tools.file_management.read.ReadFileTool[source]\u00b6\nBases: BaseFileToolMixin, BaseTool\nTool that reads a file.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.file_management.read.ReadFileInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Read file from disk'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'read_file'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam root_dir: Optional[str] = None\u00b6\nThe final path will be chosen relative to root_dir if specified.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.read.ReadFileTool.html"}
{"id": "47931b386666-1", "text": "The final path will be chosen relative to root_dir if specified.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.read.ReadFileTool.html"}
{"id": "47931b386666-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.read.ReadFileTool.html"}
{"id": "47931b386666-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.read.ReadFileTool.html"}
{"id": "47931b386666-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.read.ReadFileTool.html"}
{"id": "47931b386666-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relative_path(file_path: str) \u2192 Path\u00b6\nGet the relative path, returning an error if unsupported.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.read.ReadFileTool.html"}
{"id": "47931b386666-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.read.ReadFileTool.html"}
{"id": "47931b386666-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.read.ReadFileTool.html"}
{"id": "47931b386666-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.read.ReadFileTool.html"}
{"id": "47931b386666-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ReadFileTool\u00b6\nFile System\nAutoGPT\n!pip install bs4", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.read.ReadFileTool.html"}
{"id": "5ffbba165ff0-0", "text": "langchain.tools.requests.tool.RequestsPostTool\u00b6\nclass langchain.tools.requests.tool.RequestsPostTool[source]\u00b6\nBases: BaseRequestsTool, BaseTool\nTool for making a POST request to an API endpoint.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this when you want to POST to a website.\\n\u00a0\u00a0\u00a0 Input should be a json string with two keys: \"url\" and \"data\".\\n\u00a0\u00a0\u00a0 The value of \"url\" should be a string, and the value of \"data\" should be a dictionary of \\n\u00a0\u00a0\u00a0 key-value pairs you want to POST to the url.\\n\u00a0\u00a0\u00a0 Be careful to always use double quotes for strings in the json string\\n\u00a0\u00a0\u00a0 The output will be the text response of the POST request.\\n\u00a0\u00a0\u00a0 '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPostTool.html"}
{"id": "5ffbba165ff0-1", "text": "You can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'requests_post'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam requests_wrapper: TextRequestsWrapper [Required]\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPostTool.html"}
{"id": "5ffbba165ff0-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPostTool.html"}
{"id": "5ffbba165ff0-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPostTool.html"}
{"id": "5ffbba165ff0-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPostTool.html"}
{"id": "5ffbba165ff0-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPostTool.html"}
{"id": "5ffbba165ff0-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPostTool.html"}
{"id": "5ffbba165ff0-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPostTool.html"}
{"id": "5ffbba165ff0-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPostTool.html"}
{"id": "5ffbba165ff0-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPostTool.html"}
{"id": "83b5c61d2d4f-0", "text": "langchain.tools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool\u00b6\nclass langchain.tools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool[source]\u00b6\nBases: BaseTool\nTool that queries the Azure Cognitive Services Speech2Text API.\nIn order to set this up, follow instructions at:\nhttps://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/get-started-speech-to-text?pivots=programming-language-python\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Azure Cognitive Services Speech2Text. Useful for when you need to transcribe audio to text. Input should be a url to an audio file.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'azure_cognitive_services_speech2text'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool.html"}
{"id": "83b5c61d2d4f-1", "text": "param name: str = 'azure_cognitive_services_speech2text'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool.html"}
{"id": "83b5c61d2d4f-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool.html"}
{"id": "83b5c61d2d4f-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool.html"}
{"id": "83b5c61d2d4f-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool.html"}
{"id": "83b5c61d2d4f-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool.html"}
{"id": "83b5c61d2d4f-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool.html"}
{"id": "83b5c61d2d4f-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool.html"}
{"id": "83b5c61d2d4f-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool.html"}
{"id": "83b5c61d2d4f-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool.html"}
{"id": "94f26ad67833-0", "text": "langchain.tools.wolfram_alpha.tool.WolframAlphaQueryRun\u00b6\nclass langchain.tools.wolfram_alpha.tool.WolframAlphaQueryRun[source]\u00b6\nBases: BaseTool\nTool that queries using the Wolfram Alpha SDK.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.wolfram_alpha.WolframAlphaAPIWrapper [Required]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Wolfram Alpha. Useful for when you need to answer questions about Math, Science, Technology, Culture, Society and Everyday Life. Input should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'wolfram_alpha'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wolfram_alpha.tool.WolframAlphaQueryRun.html"}
{"id": "94f26ad67833-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wolfram_alpha.tool.WolframAlphaQueryRun.html"}
{"id": "94f26ad67833-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wolfram_alpha.tool.WolframAlphaQueryRun.html"}
{"id": "94f26ad67833-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wolfram_alpha.tool.WolframAlphaQueryRun.html"}
{"id": "94f26ad67833-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wolfram_alpha.tool.WolframAlphaQueryRun.html"}
{"id": "94f26ad67833-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wolfram_alpha.tool.WolframAlphaQueryRun.html"}
{"id": "94f26ad67833-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wolfram_alpha.tool.WolframAlphaQueryRun.html"}
{"id": "94f26ad67833-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wolfram_alpha.tool.WolframAlphaQueryRun.html"}
{"id": "94f26ad67833-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wolfram_alpha.tool.WolframAlphaQueryRun.html"}
{"id": "94f26ad67833-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wolfram_alpha.tool.WolframAlphaQueryRun.html"}
{"id": "5151f90e3b94-0", "text": "langchain.tools.gmail.utils.clean_email_body\u00b6\nlangchain.tools.gmail.utils.clean_email_body(body: str) \u2192 str[source]\u00b6\nClean email body.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.utils.clean_email_body.html"}
{"id": "f67ed35b694b-0", "text": "langchain.tools.playwright.utils.create_sync_playwright_browser\u00b6\nlangchain.tools.playwright.utils.create_sync_playwright_browser(headless: bool = True) \u2192 SyncBrowser[source]\u00b6\nCreate a playwright browser.\nParameters\nheadless \u2013 Whether to run the browser in headless mode. Defaults to True.\nReturns\nThe playwright browser.\nReturn type\nSyncBrowser\nExamples using create_sync_playwright_browser\u00b6\nPlayWright Browser", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.utils.create_sync_playwright_browser.html"}
{"id": "c71e6a677727-0", "text": "langchain.tools.gmail.base.GmailBaseTool\u00b6\nclass langchain.tools.gmail.base.GmailBaseTool[source]\u00b6\nBases: BaseTool\nBase class for Gmail tools.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_resource: Resource [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str [Required]\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.base.GmailBaseTool.html"}
{"id": "c71e6a677727-1", "text": "These tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.base.GmailBaseTool.html"}
{"id": "c71e6a677727-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.base.GmailBaseTool.html"}
{"id": "c71e6a677727-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.base.GmailBaseTool.html"}
{"id": "c71e6a677727-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_api_resource(api_resource: Resource) \u2192 GmailBaseTool[source]\u00b6\nCreate a tool from an api resource.\nParameters\napi_resource \u2013 The api resource to use.\nReturns\nA tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.base.GmailBaseTool.html"}
{"id": "c71e6a677727-5", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.base.GmailBaseTool.html"}
{"id": "c71e6a677727-6", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.base.GmailBaseTool.html"}
{"id": "c71e6a677727-7", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.base.GmailBaseTool.html"}
{"id": "c71e6a677727-8", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.base.GmailBaseTool.html"}
{"id": "c71e6a677727-9", "text": "These attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.base.GmailBaseTool.html"}
{"id": "64debaf7bdc7-0", "text": "langchain.tools.openapi.utils.api_models.APIRequestBodyProperty\u00b6\nclass langchain.tools.openapi.utils.api_models.APIRequestBodyProperty[source]\u00b6\nBases: APIPropertyBase\nA model for a request body property.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam default: Optional[Any] = None\u00b6\nThe default value of the property.\nparam description: Optional[str] = None\u00b6\nThe description of the property.\nparam name: str [Required]\u00b6\nThe name of the property.\nparam properties: List[langchain.tools.openapi.utils.api_models.APIRequestBodyProperty] [Required]\u00b6\nThe sub-properties of the property.\nparam references_used: List[str] [Required]\u00b6\nThe references used by the property.\nparam required: bool [Required]\u00b6\nWhether the property is required.\nparam type: Union[str, Type, tuple, None, enum.Enum] = None\u00b6\nThe type of the property.\nEither a primitive type, a component/parameter type,\nor an array or \u2018object\u2019 (dict) of the above.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIRequestBodyProperty.html"}
{"id": "64debaf7bdc7-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_schema(schema: Schema, name: str, required: bool, spec: OpenAPISpec, references_used: Optional[List[str]] = None) \u2192 APIRequestBodyProperty[source]\u00b6\nRecursively populate from an OpenAPI Schema.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIRequestBodyProperty.html"}
{"id": "64debaf7bdc7-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIRequestBodyProperty.html"}
{"id": "281316d94047-0", "text": "langchain.tools.google_serper.tool.GoogleSerperRun\u00b6\nclass langchain.tools.google_serper.tool.GoogleSerperRun[source]\u00b6\nBases: BaseTool\nTool that queries the Serper.dev Google search API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.google_serper.GoogleSerperAPIWrapper [Required]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A low-cost Google Search API.Useful for when you need to answer questions about current events.Input should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'google_serper'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperRun.html"}
{"id": "281316d94047-1", "text": "that after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperRun.html"}
{"id": "281316d94047-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperRun.html"}
{"id": "281316d94047-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperRun.html"}
{"id": "281316d94047-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperRun.html"}
{"id": "281316d94047-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperRun.html"}
{"id": "281316d94047-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperRun.html"}
{"id": "281316d94047-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperRun.html"}
{"id": "281316d94047-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperRun.html"}
{"id": "281316d94047-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_serper.tool.GoogleSerperRun.html"}
{"id": "7519a5f0838d-0", "text": "langchain.tools.plugin.marshal_spec\u00b6\nlangchain.tools.plugin.marshal_spec(txt: str) \u2192 dict[source]\u00b6\nConvert the yaml or json serialized spec to a dict.\nParameters\ntxt \u2013 The yaml or json serialized spec.\nReturns\nThe spec as a dict.\nReturn type\ndict", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.marshal_spec.html"}
{"id": "d62234dd2650-0", "text": "langchain.tools.playwright.extract_text.ExtractTextTool\u00b6\nclass langchain.tools.playwright.extract_text.ExtractTextTool[source]\u00b6\nBases: BaseBrowserTool\nTool for extracting all the text on the current webpage.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[BaseModel] = <class 'pydantic.main.BaseModel'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam async_browser: Optional['AsyncBrowser'] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Extract all the text on the current webpage'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'extract_text'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam sync_browser: Optional['SyncBrowser'] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_text.ExtractTextTool.html"}
{"id": "d62234dd2650-1", "text": "param sync_browser: Optional['SyncBrowser'] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_text.ExtractTextTool.html"}
{"id": "d62234dd2650-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_text.ExtractTextTool.html"}
{"id": "d62234dd2650-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_text.ExtractTextTool.html"}
{"id": "d62234dd2650-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_browser(sync_browser: Optional[SyncBrowser] = None, async_browser: Optional[AsyncBrowser] = None) \u2192 BaseBrowserTool\u00b6\nInstantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_text.ExtractTextTool.html"}
{"id": "d62234dd2650-5", "text": "Instantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_text.ExtractTextTool.html"}
{"id": "d62234dd2650-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_text.ExtractTextTool.html"}
{"id": "d62234dd2650-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_text.ExtractTextTool.html"}
{"id": "d62234dd2650-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_text.ExtractTextTool.html"}
{"id": "d62234dd2650-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_text.ExtractTextTool.html"}
{"id": "3254f6b0f44e-0", "text": "langchain.tools.ddg_search.tool.DuckDuckGoSearchResults\u00b6\nclass langchain.tools.ddg_search.tool.DuckDuckGoSearchResults[source]\u00b6\nBases: BaseTool\nTool that queries the DuckDuckGo search API and gets back json.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper [Optional]\u00b6\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.ddg_search.tool.DDGInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam backend: str = 'api'\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Duck Duck Go Search. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchResults.html"}
{"id": "3254f6b0f44e-1", "text": "You can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'DuckDuckGo Results JSON'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam num_results: int = 4\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchResults.html"}
{"id": "3254f6b0f44e-2", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchResults.html"}
{"id": "3254f6b0f44e-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchResults.html"}
{"id": "3254f6b0f44e-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchResults.html"}
{"id": "3254f6b0f44e-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchResults.html"}
{"id": "3254f6b0f44e-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchResults.html"}
{"id": "3254f6b0f44e-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchResults.html"}
{"id": "3254f6b0f44e-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchResults.html"}
{"id": "3254f6b0f44e-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using DuckDuckGoSearchResults\u00b6\nDuckDuckGo Search", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchResults.html"}
{"id": "a24f31ea1d2b-0", "text": "langchain.tools.ainetwork.app.AppOperationType\u00b6\nclass langchain.tools.ainetwork.app.AppOperationType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nType of app operation as enumerator.\nSET_ADMIN = 'SET_ADMIN'\u00b6\nGET_CONFIG = 'GET_CONFIG'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AppOperationType.html"}
{"id": "afdad22ff750-0", "text": "langchain.tools.yahoo_finance_news.YahooFinanceNewsTool\u00b6\nclass langchain.tools.yahoo_finance_news.YahooFinanceNewsTool[source]\u00b6\nBases: BaseTool\nTool that searches financial news on Yahoo Finance.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Useful for when you need to find financial news about a public company. Input should be a company ticker. For example, AAPL for Apple, MSFT for Microsoft.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'yahoo_finance_news'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.yahoo_finance_news.YahooFinanceNewsTool.html"}
{"id": "afdad22ff750-1", "text": "that after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam top_k: int = 10\u00b6\nThe number of results to return.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.yahoo_finance_news.YahooFinanceNewsTool.html"}
{"id": "afdad22ff750-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.yahoo_finance_news.YahooFinanceNewsTool.html"}
{"id": "afdad22ff750-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.yahoo_finance_news.YahooFinanceNewsTool.html"}
{"id": "afdad22ff750-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.yahoo_finance_news.YahooFinanceNewsTool.html"}
{"id": "afdad22ff750-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.yahoo_finance_news.YahooFinanceNewsTool.html"}
{"id": "afdad22ff750-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.yahoo_finance_news.YahooFinanceNewsTool.html"}
{"id": "afdad22ff750-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.yahoo_finance_news.YahooFinanceNewsTool.html"}
{"id": "afdad22ff750-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.yahoo_finance_news.YahooFinanceNewsTool.html"}
{"id": "afdad22ff750-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using YahooFinanceNewsTool\u00b6\nYahoo Finance News", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.yahoo_finance_news.YahooFinanceNewsTool.html"}
{"id": "d728cdc22cf0-0", "text": "langchain.tools.playwright.base.lazy_import_playwright_browsers\u00b6\nlangchain.tools.playwright.base.lazy_import_playwright_browsers() \u2192 Tuple[Type[AsyncBrowser], Type[SyncBrowser]][source]\u00b6\nLazy import playwright browsers.\nReturns\nAsyncBrowser and SyncBrowser classes.\nReturn type\nTuple[Type[AsyncBrowser], Type[SyncBrowser]]", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.base.lazy_import_playwright_browsers.html"}
{"id": "662821bff215-0", "text": "langchain.tools.steamship_image_generation.tool.ModelName\u00b6\nclass langchain.tools.steamship_image_generation.tool.ModelName(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nSupported Image Models for generation.\nDALL_E = 'dall-e'\u00b6\nSTABLE_DIFFUSION = 'stable-diffusion'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.steamship_image_generation.tool.ModelName.html"}
{"id": "5c427f0b3846-0", "text": "langchain.tools.base.Tool\u00b6\nclass langchain.tools.base.Tool[source]\u00b6\nBases: BaseTool\nTool that takes in function or coroutine directly.\nInitialize tool.\nparam args_schema: Optional[Type[pydantic.main.BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[langchain.schema.callbacks.base.BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Optional[Union[List[langchain.schema.callbacks.base.BaseCallbackHandler], langchain.schema.callbacks.base.BaseCallbackManager]] = None\u00b6\nCallbacks to be called during tool execution.\nparam coroutine: Optional[Callable[[...], Awaitable[str]]] = None\u00b6\nThe asynchronous version of the function.\nparam description: str = ''\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam func: Optional[Callable[[...], str]] = None\u00b6\nThe function to run when the tool is called.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.Tool.html"}
{"id": "5c427f0b3846-1", "text": "that after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.Tool.html"}
{"id": "5c427f0b3846-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.Tool.html"}
{"id": "5c427f0b3846-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.Tool.html"}
{"id": "5c427f0b3846-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.Tool.html"}
{"id": "5c427f0b3846-5", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_function(func: Optional[Callable], name: str, description: str, return_direct: bool = False, args_schema: Optional[Type[BaseModel]] = None, coroutine: Optional[Callable[[...], Awaitable[Any]]] = None, **kwargs: Any) \u2192 Tool[source]\u00b6\nInitialize tool from a function.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.Tool.html"}
{"id": "5c427f0b3846-6", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.Tool.html"}
{"id": "5c427f0b3846-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.Tool.html"}
{"id": "5c427f0b3846-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.Tool.html"}
{"id": "5c427f0b3846-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nThe tool\u2019s input arguments.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Tool\u00b6\nDataForSeo\nGoogle Serper\nSerpAPI\nGoogle Search\nZep Memory\nDynamodb Chat Message History\nSageMaker Tracking\nDocument Comparison\nNatural Language APIs\nGithub\nBittensor\nPydantic compatibility\nComparing Chain Outputs\nAgents\nAutoGPT", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.Tool.html"}
{"id": "5c427f0b3846-10", "text": "Bittensor\nPydantic compatibility\nComparing Chain Outputs\nAgents\nAutoGPT\nBabyAGI with Tools\nPlug-and-Plai\nWikibase Agent\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nCustom Agent with PlugIn Retrieval\nAgent Debates with Tools\nMessage Memory in Agent backed by a database\nMemory in Agent\nMulti-Input Tools\nDefining Custom Tools\nSelf-ask with search\nReAct document store\nOpenAI Multi Functions Agent\nCombine agents and vector stores\nCustom MRKL agent\nHandle parsing errors\nShared memory across agents and tools\nCustom multi-action agent\nRunning Agent as an Iterator\nTimeouts for agents\nAdd Memory to OpenAI Functions Agent\nCap the max number of iterations\nCustom agent\nUse ToolKits with OpenAI Functions\nCustom agent with tool retrieval", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.Tool.html"}
{"id": "315ac452e3b8-0", "text": "langchain.tools.file_management.delete.FileDeleteInput\u00b6\nclass langchain.tools.file_management.delete.FileDeleteInput[source]\u00b6\nBases: BaseModel\nInput for DeleteFileTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam file_path: str [Required]\u00b6\nPath of the file to delete\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.delete.FileDeleteInput.html"}
{"id": "315ac452e3b8-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.delete.FileDeleteInput.html"}
{"id": "315ac452e3b8-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.delete.FileDeleteInput.html"}
{"id": "32afb161d861-0", "text": "langchain.tools.playwright.utils.create_async_playwright_browser\u00b6\nlangchain.tools.playwright.utils.create_async_playwright_browser(headless: bool = True) \u2192 AsyncBrowser[source]\u00b6\nCreate an async playwright browser.\nParameters\nheadless \u2013 Whether to run the browser in headless mode. Defaults to True.\nReturns\nThe playwright browser.\nReturn type\nAsyncBrowser\nExamples using create_async_playwright_browser\u00b6\nMetaphor Search\nPlayWright Browser", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.utils.create_async_playwright_browser.html"}
{"id": "21ffea22e710-0", "text": "langchain.tools.office365.create_draft_message.CreateDraftMessageSchema\u00b6\nclass langchain.tools.office365.create_draft_message.CreateDraftMessageSchema[source]\u00b6\nBases: BaseModel\nInput for SendMessageTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bcc: Optional[List[str]] = None\u00b6\nThe list of BCC recipients.\nparam body: str [Required]\u00b6\nThe message body to include in the draft.\nparam cc: Optional[List[str]] = None\u00b6\nThe list of CC recipients.\nparam subject: str [Required]\u00b6\nThe subject of the message.\nparam to: List[str] [Required]\u00b6\nThe list of recipients.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.create_draft_message.CreateDraftMessageSchema.html"}
{"id": "21ffea22e710-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.create_draft_message.CreateDraftMessageSchema.html"}
{"id": "21ffea22e710-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.create_draft_message.CreateDraftMessageSchema.html"}
{"id": "05c91d7927e9-0", "text": "langchain.tools.ifttt.IFTTTWebhook\u00b6\nclass langchain.tools.ifttt.IFTTTWebhook[source]\u00b6\nBases: BaseTool\nIFTTT Webhook.\nParameters\nname \u2013 name of the tool\ndescription \u2013 description of the tool\nurl \u2013 url to hit with the json event.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str [Required]\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ifttt.IFTTTWebhook.html"}
{"id": "05c91d7927e9-1", "text": "Optional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam url: str [Required]\u00b6\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ifttt.IFTTTWebhook.html"}
{"id": "05c91d7927e9-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ifttt.IFTTTWebhook.html"}
{"id": "05c91d7927e9-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ifttt.IFTTTWebhook.html"}
{"id": "05c91d7927e9-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ifttt.IFTTTWebhook.html"}
{"id": "05c91d7927e9-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ifttt.IFTTTWebhook.html"}
{"id": "05c91d7927e9-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ifttt.IFTTTWebhook.html"}
{"id": "05c91d7927e9-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ifttt.IFTTTWebhook.html"}
{"id": "05c91d7927e9-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ifttt.IFTTTWebhook.html"}
{"id": "05c91d7927e9-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using IFTTTWebhook\u00b6\nIFTTT WebHooks", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ifttt.IFTTTWebhook.html"}
{"id": "3aef8bfdb69e-0", "text": "langchain.tools.gmail.utils.build_resource_service\u00b6\nlangchain.tools.gmail.utils.build_resource_service(credentials: Optional[Credentials] = None, service_name: str = 'gmail', service_version: str = 'v1') \u2192 Resource[source]\u00b6\nBuild a Gmail service.\nExamples using build_resource_service\u00b6\nGmail", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.utils.build_resource_service.html"}
{"id": "579737e3fe74-0", "text": "langchain.tools.bearly.tool.FileInfo\u00b6\nclass langchain.tools.bearly.tool.FileInfo[source]\u00b6\nBases: BaseModel\nInformation about a file to be uploaded.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam description: str [Required]\u00b6\nparam source_path: str [Required]\u00b6\nparam target_path: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bearly.tool.FileInfo.html"}
{"id": "579737e3fe74-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bearly.tool.FileInfo.html"}
{"id": "579737e3fe74-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bearly.tool.FileInfo.html"}
{"id": "993ad4727e4a-0", "text": "langchain.tools.render.format_tool_to_openai_function\u00b6\nlangchain.tools.render.format_tool_to_openai_function(tool: BaseTool) \u2192 FunctionDescription[source]\u00b6\nFormat tool into the OpenAI function API.\nExamples using format_tool_to_openai_function\u00b6\nTools as OpenAI Functions", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.render.format_tool_to_openai_function.html"}
{"id": "c9ee3f331c39-0", "text": "langchain.tools.render.render_text_description\u00b6\nlangchain.tools.render.render_text_description(tools: List[BaseTool]) \u2192 str[source]\u00b6\nRender the tool name and description in plain text.\nOutput will be in the format of:\nsearch: This tool is used for search\ncalculator: This tool is used for math", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.render.render_text_description.html"}
{"id": "92f75e282f5a-0", "text": "langchain.tools.playwright.get_elements.GetElementsTool\u00b6\nclass langchain.tools.playwright.get_elements.GetElementsTool[source]\u00b6\nBases: BaseBrowserTool\nTool for getting elements in the current web page matching a CSS selector.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[BaseModel] = <class 'langchain.tools.playwright.get_elements.GetElementsToolInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam async_browser: Optional['AsyncBrowser'] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Retrieve elements in the current web page matching the given CSS selector'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'get_elements'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.get_elements.GetElementsTool.html"}
{"id": "92f75e282f5a-1", "text": "that after the tool is called, the AgentExecutor will stop looping.\nparam sync_browser: Optional['SyncBrowser'] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.get_elements.GetElementsTool.html"}
{"id": "92f75e282f5a-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.get_elements.GetElementsTool.html"}
{"id": "92f75e282f5a-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.get_elements.GetElementsTool.html"}
{"id": "92f75e282f5a-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_browser(sync_browser: Optional[SyncBrowser] = None, async_browser: Optional[AsyncBrowser] = None) \u2192 BaseBrowserTool\u00b6\nInstantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.get_elements.GetElementsTool.html"}
{"id": "92f75e282f5a-5", "text": "Instantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.get_elements.GetElementsTool.html"}
{"id": "92f75e282f5a-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.get_elements.GetElementsTool.html"}
{"id": "92f75e282f5a-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.get_elements.GetElementsTool.html"}
{"id": "92f75e282f5a-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.get_elements.GetElementsTool.html"}
{"id": "92f75e282f5a-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.get_elements.GetElementsTool.html"}
{"id": "bae1477255ca-0", "text": "langchain.tools.edenai.edenai_base_tool.EdenaiTool\u00b6\nclass langchain.tools.edenai.edenai_base_tool.EdenaiTool[source]\u00b6\nBases: BaseTool\nthe base tool for all the EdenAI Tools .\nyou should have\nthe environment variable EDENAI_API_KEY set with your API token.\nYou can find your token here: https://app.edenai.run/admin/account/settings\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str [Required]\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam edenai_api_key: Optional[str] = None\u00b6\nparam feature: str [Required]\u00b6\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam is_async: bool = False\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam providers: List[str] [Required]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.edenai_base_tool.EdenaiTool.html"}
{"id": "bae1477255ca-1", "text": "param providers: List[str] [Required]\u00b6\nprovider to use for the API call.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam subfeature: str [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.edenai_base_tool.EdenaiTool.html"}
{"id": "bae1477255ca-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.edenai_base_tool.EdenaiTool.html"}
{"id": "bae1477255ca-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.edenai_base_tool.EdenaiTool.html"}
{"id": "bae1477255ca-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.edenai_base_tool.EdenaiTool.html"}
{"id": "bae1477255ca-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nstatic get_user_agent() \u2192 str[source]\u00b6\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.edenai_base_tool.EdenaiTool.html"}
{"id": "bae1477255ca-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.edenai_base_tool.EdenaiTool.html"}
{"id": "bae1477255ca-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.edenai_base_tool.EdenaiTool.html"}
{"id": "bae1477255ca-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.edenai_base_tool.EdenaiTool.html"}
{"id": "bae1477255ca-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.edenai_base_tool.EdenaiTool.html"}
{"id": "7fd5c605b403-0", "text": "langchain.tools.shell.tool.ShellTool\u00b6\nclass langchain.tools.shell.tool.ShellTool[source]\u00b6\nBases: BaseTool\nTool to run shell commands.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.shell.tool.ShellInput'>\u00b6\nSchema for input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Run shell commands on this Linux machine.'\u00b6\nDescription of tool.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'terminal'\u00b6\nName of tool.\nparam process: Any [Optional]\u00b6\nBash process to run commands.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.shell.tool.ShellTool.html"}
{"id": "7fd5c605b403-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.shell.tool.ShellTool.html"}
{"id": "7fd5c605b403-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.shell.tool.ShellTool.html"}
{"id": "7fd5c605b403-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.shell.tool.ShellTool.html"}
{"id": "7fd5c605b403-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.shell.tool.ShellTool.html"}
{"id": "7fd5c605b403-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.shell.tool.ShellTool.html"}
{"id": "7fd5c605b403-6", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.shell.tool.ShellTool.html"}
{"id": "7fd5c605b403-7", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.shell.tool.ShellTool.html"}
{"id": "7fd5c605b403-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.shell.tool.ShellTool.html"}
{"id": "7fd5c605b403-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ShellTool\u00b6\nShell (bash)\nHuman-in-the-loop Tool Validation", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.shell.tool.ShellTool.html"}
{"id": "e3c3d9cce7e4-0", "text": "langchain.tools.steamship_image_generation.tool.SteamshipImageGenerationTool\u00b6\nclass langchain.tools.steamship_image_generation.tool.SteamshipImageGenerationTool[source]\u00b6\nBases: BaseTool\nTool used to generate images from a text-prompt.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Useful for when you need to generate an image.Input: A detailed text-2-image prompt describing an imageOutput: the UUID of a generated image'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam model_name: ModelName [Required]\u00b6\nparam name: str = 'GenerateImage'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.steamship_image_generation.tool.SteamshipImageGenerationTool.html"}
{"id": "e3c3d9cce7e4-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam return_urls: Optional[bool] = False\u00b6\nparam size: Optional[str] = '512x512'\u00b6\nparam steamship: Steamship [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.steamship_image_generation.tool.SteamshipImageGenerationTool.html"}
{"id": "e3c3d9cce7e4-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.steamship_image_generation.tool.SteamshipImageGenerationTool.html"}
{"id": "e3c3d9cce7e4-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.steamship_image_generation.tool.SteamshipImageGenerationTool.html"}
{"id": "e3c3d9cce7e4-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.steamship_image_generation.tool.SteamshipImageGenerationTool.html"}
{"id": "e3c3d9cce7e4-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.steamship_image_generation.tool.SteamshipImageGenerationTool.html"}
{"id": "e3c3d9cce7e4-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.steamship_image_generation.tool.SteamshipImageGenerationTool.html"}
{"id": "e3c3d9cce7e4-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.steamship_image_generation.tool.SteamshipImageGenerationTool.html"}
{"id": "e3c3d9cce7e4-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.steamship_image_generation.tool.SteamshipImageGenerationTool.html"}
{"id": "e3c3d9cce7e4-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using SteamshipImageGenerationTool\u00b6\nMulti-modal outputs: Image & Text", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.steamship_image_generation.tool.SteamshipImageGenerationTool.html"}
{"id": "fa2c08cb47fd-0", "text": "langchain.tools.edenai.image_objectdetection.EdenAiObjectDetectionTool\u00b6\nclass langchain.tools.edenai.image_objectdetection.EdenAiObjectDetectionTool[source]\u00b6\nBases: EdenaiTool\nTool that queries the Eden AI Object detection API.\nfor api reference check edenai documentation:\nhttps://docs.edenai.co/reference/image_object_detection_create.\nTo use, you should have\nthe environment variable EDENAI_API_KEY set with your API token.\nYou can find your token here: https://app.edenai.run/admin/account/settings\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around edenai Services Object Detection . Useful for when you have to do an\u00a0 to identify and locate\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 (with bounding boxes) objects in an image Input should be the string url of the image to identify.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam edenai_api_key: Optional[str] = None\u00b6\nparam feature: str = 'image'\u00b6\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam is_async: bool = False\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_objectdetection.EdenAiObjectDetectionTool.html"}
{"id": "fa2c08cb47fd-1", "text": "Optional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'edenai_object_detection'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam providers: List[str] [Required]\u00b6\nprovider to use for the API call.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam show_positions: bool = False\u00b6\nparam subfeature: str = 'object_detection'\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_objectdetection.EdenAiObjectDetectionTool.html"}
{"id": "fa2c08cb47fd-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_objectdetection.EdenAiObjectDetectionTool.html"}
{"id": "fa2c08cb47fd-3", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_objectdetection.EdenAiObjectDetectionTool.html"}
{"id": "fa2c08cb47fd-4", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_objectdetection.EdenAiObjectDetectionTool.html"}
{"id": "fa2c08cb47fd-5", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nstatic get_user_agent() \u2192 str\u00b6\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_objectdetection.EdenAiObjectDetectionTool.html"}
{"id": "fa2c08cb47fd-6", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_objectdetection.EdenAiObjectDetectionTool.html"}
{"id": "fa2c08cb47fd-7", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_objectdetection.EdenAiObjectDetectionTool.html"}
{"id": "fa2c08cb47fd-8", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_objectdetection.EdenAiObjectDetectionTool.html"}
{"id": "fa2c08cb47fd-9", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using EdenAiObjectDetectionTool\u00b6\nEden AI", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.image_objectdetection.EdenAiObjectDetectionTool.html"}
{"id": "47325bd43e47-0", "text": "langchain.tools.office365.events_search.O365SearchEvents\u00b6\nclass langchain.tools.office365.events_search.O365SearchEvents[source]\u00b6\nBases: O365BaseTool\nClass for searching calendar events in Office 365\nFree, but setup is required\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam account: Account [Optional]\u00b6\nThe account object for the Office 365 account.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.office365.events_search.SearchEventsInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = \" Use this tool to search for the user's calendar events. The input must be the start and end datetimes for the search query. The output is a JSON list of all the events in the user's calendar between the start and end times. You can assume that the user can\u00a0 not schedule any meeting over existing meetings, and that the user is busy during meetings. Any times without events are free for the user. \"\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.events_search.O365SearchEvents.html"}
{"id": "47325bd43e47-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'events_search'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.events_search.O365SearchEvents.html"}
{"id": "47325bd43e47-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.events_search.O365SearchEvents.html"}
{"id": "47325bd43e47-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.events_search.O365SearchEvents.html"}
{"id": "47325bd43e47-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.events_search.O365SearchEvents.html"}
{"id": "47325bd43e47-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.events_search.O365SearchEvents.html"}
{"id": "47325bd43e47-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.events_search.O365SearchEvents.html"}
{"id": "47325bd43e47-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.events_search.O365SearchEvents.html"}
{"id": "47325bd43e47-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.events_search.O365SearchEvents.html"}
{"id": "47325bd43e47-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.events_search.O365SearchEvents.html"}
{"id": "cc520d0a6e7c-0", "text": "langchain.tools.nuclia.tool.NUASchema\u00b6\nclass langchain.tools.nuclia.tool.NUASchema[source]\u00b6\nBases: BaseModel\nInput for Nuclia Understanding API.\naction\u00b6\nAction to perform. Either push or pull.\nid\u00b6\nID of the file to push or pull.\npath\u00b6\nPath to the file to push (needed only for push action).\ntext\u00b6\nText content to process (needed only for push action).\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam action: str [Required]\u00b6\nAction to perform. Either push or pull.\nparam id: str [Required]\u00b6\nID of the file to push or pull.\nparam path: Optional[str] [Required]\u00b6\nPath to the file to push (needed only for push action).\nparam text: Optional[str] [Required]\u00b6\nText content to process (needed only for push action).\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.nuclia.tool.NUASchema.html"}
{"id": "cc520d0a6e7c-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.nuclia.tool.NUASchema.html"}
{"id": "cc520d0a6e7c-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.nuclia.tool.NUASchema.html"}
{"id": "61251f8183c2-0", "text": "langchain.tools.playwright.click.ClickTool\u00b6\nclass langchain.tools.playwright.click.ClickTool[source]\u00b6\nBases: BaseBrowserTool\nTool for clicking on an element with the given CSS selector.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[BaseModel] = <class 'langchain.tools.playwright.click.ClickToolInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam async_browser: Optional['AsyncBrowser'] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Click on an element with the given CSS selector'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'click_element'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam playwright_strict: bool = False\u00b6\nWhether to employ Playwright\u2019s strict mode when clicking on elements.\nparam playwright_timeout: float = 1000\u00b6\nTimeout (in ms) for Playwright to wait for element to be ready.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.click.ClickTool.html"}
{"id": "61251f8183c2-1", "text": "Timeout (in ms) for Playwright to wait for element to be ready.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam sync_browser: Optional['SyncBrowser'] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\nparam visible_only: bool = True\u00b6\nWhether to consider only visible elements.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.click.ClickTool.html"}
{"id": "61251f8183c2-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.click.ClickTool.html"}
{"id": "61251f8183c2-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.click.ClickTool.html"}
{"id": "61251f8183c2-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_browser(sync_browser: Optional[SyncBrowser] = None, async_browser: Optional[AsyncBrowser] = None) \u2192 BaseBrowserTool\u00b6\nInstantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.click.ClickTool.html"}
{"id": "61251f8183c2-5", "text": "Instantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.click.ClickTool.html"}
{"id": "61251f8183c2-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.click.ClickTool.html"}
{"id": "61251f8183c2-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.click.ClickTool.html"}
{"id": "61251f8183c2-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.click.ClickTool.html"}
{"id": "61251f8183c2-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.click.ClickTool.html"}
{"id": "92ecd4090f18-0", "text": "langchain.tools.human.tool.HumanInputRun\u00b6\nclass langchain.tools.human.tool.HumanInputRun[source]\u00b6\nBases: BaseTool\nTool that asks user for input.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'You can ask a human for guidance when you think you got stuck or you are not sure what to do next. The input should be a question for the human.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam input_func: Callable [Optional]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'human'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam prompt_func: Callable[[str], None] [Optional]\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.human.tool.HumanInputRun.html"}
{"id": "92ecd4090f18-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.human.tool.HumanInputRun.html"}
{"id": "92ecd4090f18-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.human.tool.HumanInputRun.html"}
{"id": "92ecd4090f18-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.human.tool.HumanInputRun.html"}
{"id": "92ecd4090f18-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.human.tool.HumanInputRun.html"}
{"id": "92ecd4090f18-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.human.tool.HumanInputRun.html"}
{"id": "92ecd4090f18-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.human.tool.HumanInputRun.html"}
{"id": "92ecd4090f18-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.human.tool.HumanInputRun.html"}
{"id": "92ecd4090f18-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.human.tool.HumanInputRun.html"}
{"id": "92ecd4090f18-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using HumanInputRun\u00b6\nHuman as a tool\n!pip install bs4", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.human.tool.HumanInputRun.html"}
{"id": "d01c7fd13f8a-0", "text": "langchain.tools.tavily_search.tool.TavilySearchResults\u00b6\nclass langchain.tools.tavily_search.tool.TavilySearchResults[source]\u00b6\nBases: BaseTool\nTool that queries the Tavily Search API and gets back json.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.tavily_search.TavilySearchAPIWrapper [Required]\u00b6\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.tavily_search.tool.TavilyInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A search engine optimized for comprehensive, accurate, and trusted results. Useful for when you need to answer questions about current events. Input should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam max_results: int = 5\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'tavily_search_results_json'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilySearchResults.html"}
{"id": "d01c7fd13f8a-1", "text": "param name: str = 'tavily_search_results_json'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilySearchResults.html"}
{"id": "d01c7fd13f8a-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilySearchResults.html"}
{"id": "d01c7fd13f8a-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilySearchResults.html"}
{"id": "d01c7fd13f8a-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilySearchResults.html"}
{"id": "d01c7fd13f8a-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilySearchResults.html"}
{"id": "d01c7fd13f8a-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilySearchResults.html"}
{"id": "d01c7fd13f8a-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilySearchResults.html"}
{"id": "d01c7fd13f8a-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilySearchResults.html"}
{"id": "d01c7fd13f8a-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilySearchResults.html"}
{"id": "16485931ff99-0", "text": "langchain.tools.plugin.AIPluginToolSchema\u00b6\nclass langchain.tools.plugin.AIPluginToolSchema[source]\u00b6\nBases: BaseModel\nSchema for AIPluginTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam tool_input: Optional[str] = ''\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPluginToolSchema.html"}
{"id": "16485931ff99-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPluginToolSchema.html"}
{"id": "327cfea52763-0", "text": "langchain.tools.sleep.tool.SleepTool\u00b6\nclass langchain.tools.sleep.tool.SleepTool[source]\u00b6\nBases: BaseTool\nTool that adds the capability to sleep.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.sleep.tool.SleepInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Make agent sleep for a specified number of seconds.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'sleep'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sleep.tool.SleepTool.html"}
{"id": "327cfea52763-1", "text": "These tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sleep.tool.SleepTool.html"}
{"id": "327cfea52763-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sleep.tool.SleepTool.html"}
{"id": "327cfea52763-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sleep.tool.SleepTool.html"}
{"id": "327cfea52763-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sleep.tool.SleepTool.html"}
{"id": "327cfea52763-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sleep.tool.SleepTool.html"}
{"id": "327cfea52763-6", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sleep.tool.SleepTool.html"}
{"id": "327cfea52763-7", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sleep.tool.SleepTool.html"}
{"id": "327cfea52763-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sleep.tool.SleepTool.html"}
{"id": "327cfea52763-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sleep.tool.SleepTool.html"}
{"id": "18604cdaeacc-0", "text": "langchain.tools.openapi.utils.api_models.APIRequestBody\u00b6\nclass langchain.tools.openapi.utils.api_models.APIRequestBody[source]\u00b6\nBases: BaseModel\nA model for a request body.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam description: Optional[str] = None\u00b6\nThe description of the request body.\nparam media_type: str [Required]\u00b6\nThe media type of the request body.\nparam properties: List[langchain.tools.openapi.utils.api_models.APIRequestBodyProperty] [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIRequestBody.html"}
{"id": "18604cdaeacc-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_request_body(request_body: RequestBody, spec: OpenAPISpec) \u2192 APIRequestBody[source]\u00b6\nInstantiate from an OpenAPI RequestBody.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIRequestBody.html"}
{"id": "18604cdaeacc-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIRequestBody.html"}
{"id": "d8cf17865159-0", "text": "langchain.tools.ainetwork.transfer.TransferSchema\u00b6\nclass langchain.tools.ainetwork.transfer.TransferSchema[source]\u00b6\nBases: BaseModel\nSchema for transfer operations.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam address: str [Required]\u00b6\nAddress to transfer AIN to\nparam amount: int [Required]\u00b6\nAmount of AIN to transfer\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.transfer.TransferSchema.html"}
{"id": "d8cf17865159-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.transfer.TransferSchema.html"}
{"id": "d8cf17865159-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.transfer.TransferSchema.html"}
{"id": "dda3081fd1d3-0", "text": "langchain.tools.searchapi.tool.SearchAPIResults\u00b6\nclass langchain.tools.searchapi.tool.SearchAPIResults[source]\u00b6\nBases: BaseTool\nTool that queries the SearchApi.io search API and returns JSON.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.searchapi.SearchApiAPIWrapper [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Google search API provided by SearchApi.io.This tool is handy when you need to answer questions about current events.The input should be a search query and the output is a JSON object with the query results.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'searchapi_results_json'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIResults.html"}
{"id": "dda3081fd1d3-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIResults.html"}
{"id": "dda3081fd1d3-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIResults.html"}
{"id": "dda3081fd1d3-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIResults.html"}
{"id": "dda3081fd1d3-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIResults.html"}
{"id": "dda3081fd1d3-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIResults.html"}
{"id": "dda3081fd1d3-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIResults.html"}
{"id": "dda3081fd1d3-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIResults.html"}
{"id": "dda3081fd1d3-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIResults.html"}
{"id": "dda3081fd1d3-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIResults.html"}
{"id": "bbae50cc5d04-0", "text": "langchain.tools.gmail.search.GmailSearch\u00b6\nclass langchain.tools.gmail.search.GmailSearch[source]\u00b6\nBases: GmailBaseTool\nTool that searches for messages or threads in Gmail.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_resource: Resource [Optional]\u00b6\nparam args_schema: Type[langchain.tools.gmail.search.SearchArgsSchema] = <class 'langchain.tools.gmail.search.SearchArgsSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this tool to search for email messages or threads. The input must be a valid Gmail query. The output is a JSON list of the requested resource.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'search_gmail'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.GmailSearch.html"}
{"id": "bbae50cc5d04-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.GmailSearch.html"}
{"id": "bbae50cc5d04-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.GmailSearch.html"}
{"id": "bbae50cc5d04-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.GmailSearch.html"}
{"id": "bbae50cc5d04-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_api_resource(api_resource: Resource) \u2192 GmailBaseTool\u00b6\nCreate a tool from an api resource.\nParameters\napi_resource \u2013 The api resource to use.\nReturns\nA tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.GmailSearch.html"}
{"id": "bbae50cc5d04-5", "text": "Returns\nA tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.GmailSearch.html"}
{"id": "bbae50cc5d04-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.GmailSearch.html"}
{"id": "bbae50cc5d04-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.GmailSearch.html"}
{"id": "bbae50cc5d04-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.GmailSearch.html"}
{"id": "bbae50cc5d04-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.GmailSearch.html"}
{"id": "5bbfe3319306-0", "text": "langchain.tools.e2b_data_analysis.unparse.roundtrip\u00b6\nlangchain.tools.e2b_data_analysis.unparse.roundtrip(filename, output=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.unparse.roundtrip.html"}
{"id": "1513fb209edc-0", "text": "langchain.tools.e2b_data_analysis.tool.add_last_line_print\u00b6\nlangchain.tools.e2b_data_analysis.tool.add_last_line_print(code: str) \u2192 str[source]\u00b6\nAdd print statement to the last line if it\u2019s missing.\nSometimes, the LLM-generated code doesn\u2019t have print(variable_name), instead theLLM tries to print the variable only by writing variable_name (as you would in\nREPL, for example).\nThis methods checks the AST of the generated Python code and adds the printstatement to the last line if it\u2019s missing.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.add_last_line_print.html"}
{"id": "be067143b173-0", "text": "langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchRun\u00b6\nclass langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchRun[source]\u00b6\nBases: BaseTool\nTool that queries the DataForSeo Google search API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.dataforseo_api_search.DataForSeoAPIWrapper [Required]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A robust Google Search API provided by DataForSeo.This tool is handy when you need information about trending topics or current events.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'dataforseo_api_search'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchRun.html"}
{"id": "be067143b173-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchRun.html"}
{"id": "be067143b173-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchRun.html"}
{"id": "be067143b173-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchRun.html"}
{"id": "be067143b173-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchRun.html"}
{"id": "be067143b173-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchRun.html"}
{"id": "be067143b173-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchRun.html"}
{"id": "be067143b173-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchRun.html"}
{"id": "be067143b173-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchRun.html"}
{"id": "be067143b173-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchRun.html"}
{"id": "18dd825ef957-0", "text": "langchain.tools.sql_database.tool.QuerySQLCheckerTool\u00b6\nclass langchain.tools.sql_database.tool.QuerySQLCheckerTool[source]\u00b6\nBases: BaseSQLDatabaseTool, BaseTool\nUse an LLM to check if a query is correct.\nAdapted from https://www.patterns.app/blog/2023/01/18/crunchbot-sql-analyst-gpt/\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam db: SQLDatabase [Required]\u00b6\nparam description: str = '\\n\u00a0\u00a0\u00a0 Use this tool to double check if your query is correct before executing it.\\n\u00a0\u00a0\u00a0 Always use this tool before executing a query with sql_db_query!\\n\u00a0\u00a0\u00a0 '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLCheckerTool.html"}
{"id": "18dd825ef957-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'sql_db_query_checker'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam template: str = '\\n{query}\\nDouble check the {dialect} query above for common mistakes, including:\\n- Using NOT IN with NULL values\\n- Using UNION when UNION ALL should have been used\\n- Using BETWEEN for exclusive ranges\\n- Data type mismatch in predicates\\n- Properly quoting identifiers\\n- Using the correct number of arguments for functions\\n- Casting to the correct data type\\n- Using the proper columns for joins\\n\\nIf there are any of the above mistakes, rewrite the query. If there are no mistakes, just reproduce the original query.\\n\\nOutput the final SQL query only.\\n\\nSQL Query: '\u00b6\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLCheckerTool.html"}
{"id": "18dd825ef957-2", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLCheckerTool.html"}
{"id": "18dd825ef957-3", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLCheckerTool.html"}
{"id": "18dd825ef957-4", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLCheckerTool.html"}
{"id": "18dd825ef957-5", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLCheckerTool.html"}
{"id": "18dd825ef957-6", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLCheckerTool.html"}
{"id": "18dd825ef957-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLCheckerTool.html"}
{"id": "18dd825ef957-8", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLCheckerTool.html"}
{"id": "18dd825ef957-9", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLCheckerTool.html"}
{"id": "18dd825ef957-10", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLCheckerTool.html"}
{"id": "a1d8183a7352-0", "text": "langchain.tools.gmail.send_message.SendMessageSchema\u00b6\nclass langchain.tools.gmail.send_message.SendMessageSchema[source]\u00b6\nBases: BaseModel\nInput for SendMessageTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bcc: Optional[Union[str, List[str]]] = None\u00b6\nThe list of BCC recipients.\nparam cc: Optional[Union[str, List[str]]] = None\u00b6\nThe list of CC recipients.\nparam message: str [Required]\u00b6\nThe message to send.\nparam subject: str [Required]\u00b6\nThe subject of the message.\nparam to: Union[str, List[str]] [Required]\u00b6\nThe list of recipients.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.send_message.SendMessageSchema.html"}
{"id": "a1d8183a7352-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.send_message.SendMessageSchema.html"}
{"id": "a1d8183a7352-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.send_message.SendMessageSchema.html"}
{"id": "2aabb4a1664b-0", "text": "langchain.tools.plugin.ApiConfig\u00b6\nclass langchain.tools.plugin.ApiConfig[source]\u00b6\nBases: BaseModel\nAPI Configuration.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam has_user_authentication: Optional[bool] = False\u00b6\nparam type: str [Required]\u00b6\nparam url: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.ApiConfig.html"}
{"id": "2aabb4a1664b-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.ApiConfig.html"}
{"id": "2aabb4a1664b-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.ApiConfig.html"}
{"id": "f78cc8ec5c7e-0", "text": "langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisTool\u00b6\nclass langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisTool[source]\u00b6\nBases: BaseTool\nTool for running python code in a sandboxed environment for data analysis.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[BaseModel] = <class 'langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisToolArguments'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str [Required]\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'e2b_data_analysis'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam session: Any = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisTool.html"}
{"id": "f78cc8ec5c7e-1", "text": "param session: Any = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisTool.html"}
{"id": "f78cc8ec5c7e-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nas_tool() \u2192 Tool[source]\u00b6\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisTool.html"}
{"id": "f78cc8ec5c7e-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nclose() \u2192 None[source]\u00b6\nClose the cloud sandbox.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisTool.html"}
{"id": "f78cc8ec5c7e-4", "text": "configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\ndownload_file(remote_path: str) \u2192 bytes[source]\u00b6\nDownload file from the sandbox.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisTool.html"}
{"id": "f78cc8ec5c7e-5", "text": "download_file(remote_path: str) \u2192 bytes[source]\u00b6\nDownload file from the sandbox.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninstall_python_packages(package_names: Union[str, List[str]]) \u2192 None[source]\u00b6\nInstall python packages in the sandbox.\ninstall_system_packages(package_names: Union[str, List[str]]) \u2192 None[source]\u00b6\nInstall system packages (via apt) in the sandbox.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisTool.html"}
{"id": "f78cc8ec5c7e-6", "text": "in parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nremove_uploaded_file(uploaded_file: UploadedFile) \u2192 None[source]\u00b6\nRemove uploaded file from the sandbox.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisTool.html"}
{"id": "f78cc8ec5c7e-7", "text": "Remove uploaded file from the sandbox.\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nrun_command(cmd: str) \u2192 dict[source]\u00b6\nRun shell command in the sandbox.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nupload_file(file: IO, description: str) \u2192 UploadedFile[source]\u00b6\nUpload file to the sandbox.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisTool.html"}
{"id": "f78cc8ec5c7e-8", "text": "Upload file to the sandbox.\nThe file is uploaded to the \u2018/home/user/<filename>\u2019 path.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisTool.html"}
{"id": "f78cc8ec5c7e-9", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty uploaded_files_description: str\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisTool.html"}
{"id": "860281dcc718-0", "text": "langchain.tools.powerbi.tool.QueryPowerBITool\u00b6\nclass langchain.tools.powerbi.tool.QueryPowerBITool[source]\u00b6\nBases: BaseTool\nTool for querying a Power BI Dataset.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = '\\n\u00a0\u00a0\u00a0 Input to this tool is a detailed question about the dataset, output is a result from the dataset. It will try to answer the question using the dataset, and if it cannot, it will ask for clarification.\\n\\n\u00a0\u00a0\u00a0 Example Input: \"How many rows are in table1?\"\\n\u00a0\u00a0\u00a0 '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam examples: Optional[str] = '\\nQuestion: How many rows are in the table <table>?\\nDAX: EVALUATE ROW(\"Number of rows\", COUNTROWS(<table>))\\n----\\nQuestion: How many rows are in the table <table> where <column> is not empty?\\nDAX: EVALUATE ROW(\"Number of rows\", COUNTROWS(FILTER(<table>, <table>[<column>] <> \"\")))\\n----\\nQuestion: What was the average of <column> in <table>?\\nDAX: EVALUATE ROW(\"Average\", AVERAGE(<table>[<column>]))\\n----\\n'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.QueryPowerBITool.html"}
{"id": "860281dcc718-1", "text": "param handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam max_iterations: int = 5\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'query_powerbi'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam output_token_limit: int = 4000\u00b6\nparam powerbi: langchain.utilities.powerbi.PowerBIDataset [Required]\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam session_cache: Dict[str, Any] [Optional]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.QueryPowerBITool.html"}
{"id": "860281dcc718-2", "text": "Make tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.QueryPowerBITool.html"}
{"id": "860281dcc718-3", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.QueryPowerBITool.html"}
{"id": "860281dcc718-4", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.QueryPowerBITool.html"}
{"id": "860281dcc718-5", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.QueryPowerBITool.html"}
{"id": "860281dcc718-6", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.QueryPowerBITool.html"}
{"id": "860281dcc718-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.QueryPowerBITool.html"}
{"id": "860281dcc718-8", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.QueryPowerBITool.html"}
{"id": "860281dcc718-9", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.QueryPowerBITool.html"}
{"id": "860281dcc718-10", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.QueryPowerBITool.html"}
{"id": "b873894f93a7-0", "text": "langchain.tools.openapi.utils.api_models.APIOperation\u00b6\nclass langchain.tools.openapi.utils.api_models.APIOperation[source]\u00b6\nBases: BaseModel\nA model for a single API operation.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam base_url: str [Required]\u00b6\nThe base URL of the operation.\nparam description: Optional[str] = None\u00b6\nThe description of the operation.\nparam method: langchain.utilities.openapi.HTTPVerb [Required]\u00b6\nThe HTTP method of the operation.\nparam operation_id: str [Required]\u00b6\nThe unique identifier of the operation.\nparam path: str [Required]\u00b6\nThe path of the operation.\nparam properties: Sequence[langchain.tools.openapi.utils.api_models.APIProperty] [Required]\u00b6\nparam request_body: Optional[langchain.tools.openapi.utils.api_models.APIRequestBody] = None\u00b6\nThe request body of the operation.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIOperation.html"}
{"id": "b873894f93a7-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_openapi_spec(spec: OpenAPISpec, path: str, method: str) \u2192 APIOperation[source]\u00b6\nCreate an APIOperation from an OpenAPI spec.\nclassmethod from_openapi_url(spec_url: str, path: str, method: str) \u2192 APIOperation[source]\u00b6\nCreate an APIOperation from an OpenAPI URL.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIOperation.html"}
{"id": "b873894f93a7-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_typescript() \u2192 str[source]\u00b6\nGet typescript string representation of the operation.\nstatic ts_type_from_python(type_: Union[str, Type, tuple, None, Enum]) \u2192 str[source]\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty body_params: List[str]\u00b6\nproperty path_params: List[str]\u00b6\nproperty query_params: List[str]\u00b6\nExamples using APIOperation\u00b6\nNatural Language APIs", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openapi.utils.api_models.APIOperation.html"}
{"id": "4e80c2a8cf74-0", "text": "langchain.tools.amadeus.base.AmadeusBaseTool\u00b6\nclass langchain.tools.amadeus.base.AmadeusBaseTool[source]\u00b6\nBases: BaseTool\nBase Tool for Amadeus.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam client: Client [Optional]\u00b6\nparam description: str [Required]\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.base.AmadeusBaseTool.html"}
{"id": "4e80c2a8cf74-1", "text": "These tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.base.AmadeusBaseTool.html"}
{"id": "4e80c2a8cf74-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.base.AmadeusBaseTool.html"}
{"id": "4e80c2a8cf74-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.base.AmadeusBaseTool.html"}
{"id": "4e80c2a8cf74-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.base.AmadeusBaseTool.html"}
{"id": "4e80c2a8cf74-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.base.AmadeusBaseTool.html"}
{"id": "4e80c2a8cf74-6", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.base.AmadeusBaseTool.html"}
{"id": "4e80c2a8cf74-7", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.base.AmadeusBaseTool.html"}
{"id": "4e80c2a8cf74-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.base.AmadeusBaseTool.html"}
{"id": "4e80c2a8cf74-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.base.AmadeusBaseTool.html"}
{"id": "fa5c47bd220a-0", "text": "langchain.tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool\u00b6\nclass langchain.tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool[source]\u00b6\nBases: EdenaiTool\nTool that queries the Eden AI Invoice parsing API.\nfor api reference check edenai documentation:\nhttps://docs.edenai.co/reference/ocr_invoice_parser_create.\nTo use, you should have\nthe environment variable EDENAI_API_KEY set with your API token.\nYou can find your token here: https://app.edenai.run/admin/account/settings\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around edenai Services invoice parsing. Useful for when you have to extract information from \\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 an image it enables to take invoices \\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 in a variety of formats and returns the data in contains\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 (items, prices, addresses, vendor name, etc.)\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 in a structured format to automate the invoice processing Input should be the string url of the document to parse.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam edenai_api_key: Optional[str] = None\u00b6\nparam feature: str = 'ocr'\u00b6\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool.html"}
{"id": "fa5c47bd220a-1", "text": "Handle the content of the ToolException thrown.\nparam is_async: bool = False\u00b6\nparam language: Optional[str] = None\u00b6\nlanguage of the image passed to the model.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'edenai_invoice_parsing'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam providers: List[str] [Required]\u00b6\nprovider to use for the API call.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam subfeature: str = 'invoice_parser'\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool.html"}
{"id": "fa5c47bd220a-2", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool.html"}
{"id": "fa5c47bd220a-3", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool.html"}
{"id": "fa5c47bd220a-4", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool.html"}
{"id": "fa5c47bd220a-5", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nstatic get_user_agent() \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool.html"}
{"id": "fa5c47bd220a-6", "text": "static get_user_agent() \u2192 str\u00b6\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool.html"}
{"id": "fa5c47bd220a-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool.html"}
{"id": "fa5c47bd220a-8", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool.html"}
{"id": "fa5c47bd220a-9", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool.html"}
{"id": "fa5c47bd220a-10", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using EdenAiParsingInvoiceTool\u00b6\nEden AI", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool.html"}
{"id": "18201625e4fc-0", "text": "langchain.tools.json.tool.JsonSpec\u00b6\nclass langchain.tools.json.tool.JsonSpec[source]\u00b6\nBases: BaseModel\nBase class for JSON spec.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam dict_: Dict [Required]\u00b6\nparam max_value_length: int = 200\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonSpec.html"}
{"id": "18201625e4fc-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_file(path: Path) \u2192 JsonSpec[source]\u00b6\nCreate a JsonSpec from a file.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nkeys(text: str) \u2192 str[source]\u00b6\nReturn the keys of the dict at the given path.\nParameters\ntext \u2013 Python representation of the path to the dict (e.g. data[\u201ckey1\u201d][0][\u201ckey2\u201d]).", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonSpec.html"}
{"id": "18201625e4fc-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nvalue(text: str) \u2192 str[source]\u00b6\nReturn the value of the dict at the given path.\nParameters\ntext \u2013 Python representation of the path to the dict (e.g. data[\u201ckey1\u201d][0][\u201ckey2\u201d]).\nExamples using JsonSpec\u00b6\nJSON\nOpenAPI", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonSpec.html"}
{"id": "b305653cfb7d-0", "text": "langchain.tools.eleven_labs.models.ElevenLabsModel\u00b6\nclass langchain.tools.eleven_labs.models.ElevenLabsModel(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nModels available for Eleven Labs Text2Speech.\nMULTI_LINGUAL = 'eleven_multilingual_v1'\u00b6\nMONO_LINGUAL = 'eleven_monolingual_v1'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.eleven_labs.models.ElevenLabsModel.html"}
{"id": "2484b5735589-0", "text": "langchain.tools.google_scholar.tool.GoogleScholarQueryRun\u00b6\nclass langchain.tools.google_scholar.tool.GoogleScholarQueryRun[source]\u00b6\nBases: BaseTool\nTool that queries the Google search API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.google_scholar.GoogleScholarAPIWrapper [Required]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Google Scholar Search. Useful for when you need to get information aboutresearch papers from Google ScholarInput should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'google_scholar'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_scholar.tool.GoogleScholarQueryRun.html"}
{"id": "2484b5735589-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_scholar.tool.GoogleScholarQueryRun.html"}
{"id": "2484b5735589-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_scholar.tool.GoogleScholarQueryRun.html"}
{"id": "2484b5735589-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_scholar.tool.GoogleScholarQueryRun.html"}
{"id": "2484b5735589-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_scholar.tool.GoogleScholarQueryRun.html"}
{"id": "2484b5735589-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_scholar.tool.GoogleScholarQueryRun.html"}
{"id": "2484b5735589-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_scholar.tool.GoogleScholarQueryRun.html"}
{"id": "2484b5735589-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_scholar.tool.GoogleScholarQueryRun.html"}
{"id": "2484b5735589-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_scholar.tool.GoogleScholarQueryRun.html"}
{"id": "2484b5735589-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_scholar.tool.GoogleScholarQueryRun.html"}
{"id": "23fe46ff7d6f-0", "text": "langchain.tools.shell.tool.ShellInput\u00b6\nclass langchain.tools.shell.tool.ShellInput[source]\u00b6\nBases: BaseModel\nCommands for the Bash Shell tool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam commands: Union[str, List[str]] [Required]\u00b6\nList of shell commands to run.\nList of shell commands to run. Deserialized using json.loads\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.shell.tool.ShellInput.html"}
{"id": "23fe46ff7d6f-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.shell.tool.ShellInput.html"}
{"id": "23fe46ff7d6f-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.shell.tool.ShellInput.html"}
{"id": "90bc16025971-0", "text": "langchain.tools.multion.create_session.CreateSessionSchema\u00b6\nclass langchain.tools.multion.create_session.CreateSessionSchema[source]\u00b6\nBases: BaseModel\nInput for CreateSessionTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam query: str [Required]\u00b6\nThe query to run in multion agent.\nparam url: str = 'https://www.google.com/'\u00b6\nThe Url to run the agent at. Note: accepts only secure             links having https://\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.create_session.CreateSessionSchema.html"}
{"id": "90bc16025971-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.create_session.CreateSessionSchema.html"}
{"id": "90bc16025971-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.create_session.CreateSessionSchema.html"}
{"id": "97e10b188bc8-0", "text": "langchain.tools.amadeus.flight_search.FlightSearchSchema\u00b6\nclass langchain.tools.amadeus.flight_search.FlightSearchSchema[source]\u00b6\nBases: BaseModel\nSchema for the AmadeusFlightSearch tool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam departureDateTimeEarliest: str [Required]\u00b6\nThe earliest departure datetime from the origin airport  for the flight search in the following format:  \u201cYYYY-MM-DDTHH:MM\u201d, where \u201cT\u201d separates the date and time  components. For example: \u201c2023-06-09T10:30:00\u201d represents  June 9th, 2023, at 10:30 AM.\nparam departureDateTimeLatest: str [Required]\u00b6\nThe latest departure datetime from the origin airport  for the flight search in the following format:  \u201cYYYY-MM-DDTHH:MM\u201d, where \u201cT\u201d separates the date and time  components. For example: \u201c2023-06-09T10:30:00\u201d represents  June 9th, 2023, at 10:30 AM.\nparam destinationLocationCode: str [Required]\u00b6\nThe three letter International Air Transport  Association (IATA) Location Identifier for the  search\u2019s destination airport.\nparam originLocationCode: str [Required]\u00b6\nThe three letter International Air Transport  Association (IATA) Location Identifier for the  search\u2019s origin airport.\nparam page_number: int = 1\u00b6\nThe specific page number of flight results to retrieve\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.flight_search.FlightSearchSchema.html"}
{"id": "97e10b188bc8-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.flight_search.FlightSearchSchema.html"}
{"id": "97e10b188bc8-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.amadeus.flight_search.FlightSearchSchema.html"}
{"id": "64f9271c876d-0", "text": "langchain.tools.gmail.utils.import_google\u00b6\nlangchain.tools.gmail.utils.import_google() \u2192 Tuple[Request, Credentials][source]\u00b6\nImport google libraries.\nReturns\nRequest and Credentials classes.\nReturn type\nTuple[Request, Credentials]", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.utils.import_google.html"}
{"id": "9cf97f4032b3-0", "text": "langchain.tools.ainetwork.rule.AINRuleOps\u00b6\nclass langchain.tools.ainetwork.rule.AINRuleOps[source]\u00b6\nBases: AINBaseTool\nTool for owner operations.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.ainetwork.rule.RuleSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.AINRuleOps.html"}
{"id": "9cf97f4032b3-1", "text": "param callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = \"\\nCovers the write `rule` for the AINetwork Blockchain database. The SET type specifies write permissions using the `eval` variable as a JavaScript eval string.\\nIn order to AINvalueOps with SET at the path, the execution result of the `eval` string must be true.\\n\\n## Path Rules\\n1. Allowed characters for directory: `[a-zA-Z_0-9]`\\n2. Use `$<key>` for template variables as directory.\\n\\n## Eval String Special Variables\\n- auth.addr: Address of the writer for the path\\n- newData: New data for the path\\n- data: Current data for the path\\n- currentTime: Time in seconds\\n- lastBlockNumber: Latest processed block number\\n\\n## Eval String Functions\\n- getValue(<path>)\\n- getRule(<path>)\\n- getOwner(<path>)\\n- getFunction(<path>)\\n- evalRule(<path>, <value to set>, auth, currentTime)\\n- evalOwner(<path>, 'write_owner', auth)\\n\\n## SET Example\\n- type: SET\\n- path: /apps/langchain_project_1/$from/$to/$img\\n- eval: auth.addr===$from&&!getValue('/apps/image_db/'+$img)\\n\\n## GET Example\\n- type: GET\\n- path: /apps/langchain_project_1\\n\"\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam interface: Ain [Optional]\u00b6\nThe interface object for the AINetwork Blockchain.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.AINRuleOps.html"}
{"id": "9cf97f4032b3-2", "text": "param interface: Ain [Optional]\u00b6\nThe interface object for the AINetwork Blockchain.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'AINruleOps'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.AINRuleOps.html"}
{"id": "9cf97f4032b3-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.AINRuleOps.html"}
{"id": "9cf97f4032b3-4", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.AINRuleOps.html"}
{"id": "9cf97f4032b3-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.AINRuleOps.html"}
{"id": "9cf97f4032b3-6", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.AINRuleOps.html"}
{"id": "9cf97f4032b3-7", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.AINRuleOps.html"}
{"id": "9cf97f4032b3-8", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.AINRuleOps.html"}
{"id": "9cf97f4032b3-9", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.AINRuleOps.html"}
{"id": "9cf97f4032b3-10", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.rule.AINRuleOps.html"}
{"id": "debd21769329-0", "text": "langchain.tools.office365.messages_search.SearchEmailsInput\u00b6\nclass langchain.tools.office365.messages_search.SearchEmailsInput[source]\u00b6\nBases: BaseModel\nInput for SearchEmails Tool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam folder: str = None\u00b6\nIf the user wants to search in only one folder, the name of the folder. Default folders are \u201cinbox\u201d, \u201cdrafts\u201d, \u201csent items\u201d, \u201cdeleted ttems\u201d, but users can search custom folders as well.\nparam max_results: int = 10\u00b6\nThe maximum number of results to return.\nparam query: str [Required]\u00b6\nThe Microsoift Graph v1.0 $search query. Example filters include from:sender, from:sender, to:recipient, subject:subject, recipients:list_of_recipients, body:excitement, importance:high, received>2022-12-01, received<2021-12-01, sent>2022-12-01, sent<2021-12-01, hasAttachments:true  attachment:api-catalog.md, cc:samanthab@contoso.com, bcc:samanthab@contoso.com, body:excitement date range example: received:2023-06-08..2023-06-09  matching example: from:amy OR from:david.\nparam truncate: bool = True\u00b6\nWhether the email body is truncated to meet token number limits. Set to False for searches that will retrieve very few results, otherwise, set to True\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.messages_search.SearchEmailsInput.html"}
{"id": "debd21769329-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.messages_search.SearchEmailsInput.html"}
{"id": "debd21769329-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.messages_search.SearchEmailsInput.html"}
{"id": "4e8f0b29bebf-0", "text": "langchain.tools.file_management.delete.DeleteFileTool\u00b6\nclass langchain.tools.file_management.delete.DeleteFileTool[source]\u00b6\nBases: BaseFileToolMixin, BaseTool\nTool that deletes a file.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.file_management.delete.FileDeleteInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Delete a file'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'file_delete'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam root_dir: Optional[str] = None\u00b6\nThe final path will be chosen relative to root_dir if specified.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.delete.DeleteFileTool.html"}
{"id": "4e8f0b29bebf-1", "text": "The final path will be chosen relative to root_dir if specified.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.delete.DeleteFileTool.html"}
{"id": "4e8f0b29bebf-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.delete.DeleteFileTool.html"}
{"id": "4e8f0b29bebf-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.delete.DeleteFileTool.html"}
{"id": "4e8f0b29bebf-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.delete.DeleteFileTool.html"}
{"id": "4e8f0b29bebf-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relative_path(file_path: str) \u2192 Path\u00b6\nGet the relative path, returning an error if unsupported.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.delete.DeleteFileTool.html"}
{"id": "4e8f0b29bebf-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.delete.DeleteFileTool.html"}
{"id": "4e8f0b29bebf-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.delete.DeleteFileTool.html"}
{"id": "4e8f0b29bebf-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.delete.DeleteFileTool.html"}
{"id": "4e8f0b29bebf-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using DeleteFileTool\u00b6\nFile System", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.delete.DeleteFileTool.html"}
{"id": "5b5045d847a4-0", "text": "langchain.tools.vectorstore.tool.VectorStoreQAWithSourcesTool\u00b6\nclass langchain.tools.vectorstore.tool.VectorStoreQAWithSourcesTool[source]\u00b6\nBases: BaseVectorStoreTool, BaseTool\nTool for the VectorDBQAWithSources chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str [Required]\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam llm: BaseLanguageModel [Optional]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQAWithSourcesTool.html"}
{"id": "5b5045d847a4-1", "text": "Optional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam vectorstore: VectorStore [Required]\u00b6\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQAWithSourcesTool.html"}
{"id": "5b5045d847a4-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQAWithSourcesTool.html"}
{"id": "5b5045d847a4-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQAWithSourcesTool.html"}
{"id": "5b5045d847a4-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nstatic get_description(name: str, description: str) \u2192 str[source]\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQAWithSourcesTool.html"}
{"id": "5b5045d847a4-5", "text": "The tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQAWithSourcesTool.html"}
{"id": "5b5045d847a4-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQAWithSourcesTool.html"}
{"id": "5b5045d847a4-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQAWithSourcesTool.html"}
{"id": "5b5045d847a4-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQAWithSourcesTool.html"}
{"id": "5b5045d847a4-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.vectorstore.tool.VectorStoreQAWithSourcesTool.html"}
{"id": "6d1eb718f3f2-0", "text": "langchain.tools.steamship_image_generation.utils.make_image_public\u00b6\nlangchain.tools.steamship_image_generation.utils.make_image_public(client: Steamship, block: Block) \u2192 str[source]\u00b6\nUpload a block to a signed URL and return the public URL.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.steamship_image_generation.utils.make_image_public.html"}
{"id": "8ec113d4807b-0", "text": "langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksTool\u00b6\nclass langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksTool[source]\u00b6\nBases: BaseBrowserTool\nExtract all hyperlinks on the page.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[BaseModel] = <class 'langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksToolInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam async_browser: Optional['AsyncBrowser'] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Extract all hyperlinks on the current webpage'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'extract_hyperlinks'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksTool.html"}
{"id": "8ec113d4807b-1", "text": "that after the tool is called, the AgentExecutor will stop looping.\nparam sync_browser: Optional['SyncBrowser'] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksTool.html"}
{"id": "8ec113d4807b-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksTool.html"}
{"id": "8ec113d4807b-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksTool.html"}
{"id": "8ec113d4807b-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_browser(sync_browser: Optional[SyncBrowser] = None, async_browser: Optional[AsyncBrowser] = None) \u2192 BaseBrowserTool\u00b6\nInstantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksTool.html"}
{"id": "8ec113d4807b-5", "text": "Instantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksTool.html"}
{"id": "8ec113d4807b-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksTool.html"}
{"id": "8ec113d4807b-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstatic scrape_page(page: Any, html_content: str, absolute_urls: bool) \u2192 str[source]\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksTool.html"}
{"id": "8ec113d4807b-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksTool.html"}
{"id": "8ec113d4807b-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.extract_hyperlinks.ExtractHyperlinksTool.html"}
{"id": "b6102e00bce5-0", "text": "langchain.tools.memorize.tool.Memorize\u00b6\nclass langchain.tools.memorize.tool.Memorize[source]\u00b6\nBases: BaseTool\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = \"Useful whenever you observed novel information from previous conversation history, i.e., another tool's action outputs or human comments. The action input should include observed information in detail, then the tool will fine-tune yourself to remember it.\"\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam llm: langchain.tools.memorize.tool.TrainableLLM [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'Memorize'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.memorize.tool.Memorize.html"}
{"id": "b6102e00bce5-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.memorize.tool.Memorize.html"}
{"id": "b6102e00bce5-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.memorize.tool.Memorize.html"}
{"id": "b6102e00bce5-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.memorize.tool.Memorize.html"}
{"id": "b6102e00bce5-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.memorize.tool.Memorize.html"}
{"id": "b6102e00bce5-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.memorize.tool.Memorize.html"}
{"id": "b6102e00bce5-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.memorize.tool.Memorize.html"}
{"id": "b6102e00bce5-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.memorize.tool.Memorize.html"}
{"id": "b6102e00bce5-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.memorize.tool.Memorize.html"}
{"id": "b6102e00bce5-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.memorize.tool.Memorize.html"}
{"id": "80dedca48d3f-0", "text": "langchain.tools.file_management.copy.FileCopyInput\u00b6\nclass langchain.tools.file_management.copy.FileCopyInput[source]\u00b6\nBases: BaseModel\nInput for CopyFileTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam destination_path: str [Required]\u00b6\nPath to save the copied file\nparam source_path: str [Required]\u00b6\nPath of the file to copy\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.copy.FileCopyInput.html"}
{"id": "80dedca48d3f-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.copy.FileCopyInput.html"}
{"id": "80dedca48d3f-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.copy.FileCopyInput.html"}
{"id": "ee0bee7f6b06-0", "text": "langchain.tools.file_management.file_search.FileSearchTool\u00b6\nclass langchain.tools.file_management.file_search.FileSearchTool[source]\u00b6\nBases: BaseFileToolMixin, BaseTool\nTool that searches for files in a subdirectory that match a regex pattern.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.file_management.file_search.FileSearchInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Recursively search for files in a subdirectory that match the regex pattern'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'file_search'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.file_search.FileSearchTool.html"}
{"id": "ee0bee7f6b06-1", "text": "that after the tool is called, the AgentExecutor will stop looping.\nparam root_dir: Optional[str] = None\u00b6\nThe final path will be chosen relative to root_dir if specified.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.file_search.FileSearchTool.html"}
{"id": "ee0bee7f6b06-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.file_search.FileSearchTool.html"}
{"id": "ee0bee7f6b06-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.file_search.FileSearchTool.html"}
{"id": "ee0bee7f6b06-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.file_search.FileSearchTool.html"}
{"id": "ee0bee7f6b06-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relative_path(file_path: str) \u2192 Path\u00b6\nGet the relative path, returning an error if unsupported.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.file_search.FileSearchTool.html"}
{"id": "ee0bee7f6b06-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.file_search.FileSearchTool.html"}
{"id": "ee0bee7f6b06-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.file_search.FileSearchTool.html"}
{"id": "ee0bee7f6b06-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.file_search.FileSearchTool.html"}
{"id": "ee0bee7f6b06-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.file_search.FileSearchTool.html"}
{"id": "dabfa4d4b46f-0", "text": "langchain.tools.openweathermap.tool.OpenWeatherMapQueryRun\u00b6\nclass langchain.tools.openweathermap.tool.OpenWeatherMapQueryRun[source]\u00b6\nBases: BaseTool\nTool that queries the OpenWeatherMap API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.openweathermap.OpenWeatherMapAPIWrapper [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around OpenWeatherMap API. Useful for fetching current weather information for a specified location. Input should be a location string (e.g. London,GB).'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'OpenWeatherMap'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openweathermap.tool.OpenWeatherMapQueryRun.html"}
{"id": "dabfa4d4b46f-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openweathermap.tool.OpenWeatherMapQueryRun.html"}
{"id": "dabfa4d4b46f-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openweathermap.tool.OpenWeatherMapQueryRun.html"}
{"id": "dabfa4d4b46f-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openweathermap.tool.OpenWeatherMapQueryRun.html"}
{"id": "dabfa4d4b46f-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openweathermap.tool.OpenWeatherMapQueryRun.html"}
{"id": "dabfa4d4b46f-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openweathermap.tool.OpenWeatherMapQueryRun.html"}
{"id": "dabfa4d4b46f-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openweathermap.tool.OpenWeatherMapQueryRun.html"}
{"id": "dabfa4d4b46f-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openweathermap.tool.OpenWeatherMapQueryRun.html"}
{"id": "dabfa4d4b46f-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openweathermap.tool.OpenWeatherMapQueryRun.html"}
{"id": "dabfa4d4b46f-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.openweathermap.tool.OpenWeatherMapQueryRun.html"}
{"id": "b130e75ca461-0", "text": "langchain.tools.gmail.utils.import_googleapiclient_resource_builder\u00b6\nlangchain.tools.gmail.utils.import_googleapiclient_resource_builder() \u2192 build_resource[source]\u00b6\nImport googleapiclient.discovery.build function.\nReturns\ngoogleapiclient.discovery.build function.\nReturn type\nbuild_resource", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.utils.import_googleapiclient_resource_builder.html"}
{"id": "2cb0cd436820-0", "text": "langchain.tools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool\u00b6\nclass langchain.tools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool[source]\u00b6\nBases: BaseTool\nTool that queries the Azure Cognitive Services Text2Speech API.\nIn order to set this up, follow instructions at:\nhttps://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/get-started-text-to-speech?pivots=programming-language-python\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Azure Cognitive Services Text2Speech. Useful for when you need to convert text to speech. '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'azure_cognitive_services_text2speech'\u00b6\nThe unique name of the tool that clearly communicates its purpose.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool.html"}
{"id": "2cb0cd436820-1", "text": "The unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool.html"}
{"id": "2cb0cd436820-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool.html"}
{"id": "2cb0cd436820-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool.html"}
{"id": "2cb0cd436820-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool.html"}
{"id": "2cb0cd436820-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool.html"}
{"id": "2cb0cd436820-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool.html"}
{"id": "2cb0cd436820-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool.html"}
{"id": "2cb0cd436820-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool.html"}
{"id": "2cb0cd436820-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool.html"}
{"id": "390daf6923cc-0", "text": "langchain.tools.bing_search.tool.BingSearchRun\u00b6\nclass langchain.tools.bing_search.tool.BingSearchRun[source]\u00b6\nBases: BaseTool\nTool that queries the Bing search API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.bing_search.BingSearchAPIWrapper [Required]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Bing Search. Useful for when you need to answer questions about current events. Input should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'bing_search'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchRun.html"}
{"id": "390daf6923cc-1", "text": "that after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchRun.html"}
{"id": "390daf6923cc-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchRun.html"}
{"id": "390daf6923cc-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchRun.html"}
{"id": "390daf6923cc-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchRun.html"}
{"id": "390daf6923cc-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchRun.html"}
{"id": "390daf6923cc-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchRun.html"}
{"id": "390daf6923cc-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchRun.html"}
{"id": "390daf6923cc-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchRun.html"}
{"id": "390daf6923cc-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bing_search.tool.BingSearchRun.html"}
{"id": "0dde692f75db-0", "text": "langchain.tools.zapier.tool.ZapierNLAListActions\u00b6\nclass langchain.tools.zapier.tool.ZapierNLAListActions[source]\u00b6\nBases: BaseTool\nReturns a list of all exposed (enabled) actions associated withcurrent user (associated with the set api_key). Change your exposed\nactions here: https://nla.zapier.com/demo/start/\nThe return list can be empty if no actions exposed. Else will contain\na list of action objects:\n[{\u201cid\u201d: str,\n\u201cdescription\u201d: str,\n\u201cparams\u201d: Dict[str, str]\n}]\nparams will always contain an instructions key, the only required\nparam. All others optional and if provided will override any AI guesses\n(see \u201cunderstanding the AI guessing flow\u201d here:\nhttps://nla.zapier.com/docs/using-the-api#ai-guessing)\nParameters\nNone \u2013 \nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.zapier.ZapierNLAWrapper [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLAListActions.html"}
{"id": "0dde692f75db-1", "text": "param callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Zapier NLA actions. The input to this tool is a natural language instruction, for example \"get the latest email from my bank\" or \"send a slack message to the #general channel\". Each tool will have params associated with it that are specified as a list. You MUST take into account the params when creating the instruction. For example, if the params are [\\'Message_Text\\', \\'Channel\\'], your instruction should be something like \\'send a slack message to the #general channel with the text hello world\\'. Another example: if the params are [\\'Calendar\\', \\'Search_Term\\'], your instruction should be something like \\'find the meeting in my personal calendar at 3pm\\'. Do not make up params, they will be explicitly specified in the tool description. If you do not have enough information to fill in the params, just say \\'not enough information provided in the instruction, missing <param>\\'. If you get a none or null response, STOP EXECUTION, do not try to another tool!This tool specifically used for: {zapier_description}, and has params: {params}This tool returns a list of the user\\'s exposed actions.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLAListActions.html"}
{"id": "0dde692f75db-2", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'ZapierNLA_list_actions'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLAListActions.html"}
{"id": "0dde692f75db-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLAListActions.html"}
{"id": "0dde692f75db-4", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLAListActions.html"}
{"id": "0dde692f75db-5", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLAListActions.html"}
{"id": "0dde692f75db-6", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLAListActions.html"}
{"id": "0dde692f75db-7", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLAListActions.html"}
{"id": "0dde692f75db-8", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLAListActions.html"}
{"id": "0dde692f75db-9", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLAListActions.html"}
{"id": "0dde692f75db-10", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLAListActions.html"}
{"id": "ef066c84d299-0", "text": "langchain.tools.playwright.navigate_back.NavigateBackTool\u00b6\nclass langchain.tools.playwright.navigate_back.NavigateBackTool[source]\u00b6\nBases: BaseBrowserTool\nNavigate back to the previous page in the browser history.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[BaseModel] = <class 'pydantic.main.BaseModel'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam async_browser: Optional['AsyncBrowser'] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Navigate back to the previous page in the browser history'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'previous_webpage'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam sync_browser: Optional['SyncBrowser'] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate_back.NavigateBackTool.html"}
{"id": "ef066c84d299-1", "text": "param sync_browser: Optional['SyncBrowser'] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate_back.NavigateBackTool.html"}
{"id": "ef066c84d299-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate_back.NavigateBackTool.html"}
{"id": "ef066c84d299-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate_back.NavigateBackTool.html"}
{"id": "ef066c84d299-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_browser(sync_browser: Optional[SyncBrowser] = None, async_browser: Optional[AsyncBrowser] = None) \u2192 BaseBrowserTool\u00b6\nInstantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate_back.NavigateBackTool.html"}
{"id": "ef066c84d299-5", "text": "Instantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate_back.NavigateBackTool.html"}
{"id": "ef066c84d299-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate_back.NavigateBackTool.html"}
{"id": "ef066c84d299-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate_back.NavigateBackTool.html"}
{"id": "ef066c84d299-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate_back.NavigateBackTool.html"}
{"id": "ef066c84d299-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate_back.NavigateBackTool.html"}
{"id": "f8cc147a53ff-0", "text": "langchain.tools.graphql.tool.BaseGraphQLTool\u00b6\nclass langchain.tools.graphql.tool.BaseGraphQLTool[source]\u00b6\nBases: BaseTool\nBase tool for querying a GraphQL API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = \"\u00a0\u00a0\u00a0 Input to this tool is a detailed and correct GraphQL query, output is a result from the API.\\n\u00a0\u00a0\u00a0 If the query is not correct, an error message will be returned.\\n\u00a0\u00a0\u00a0 If an error is returned with 'Bad request' in it, rewrite the query and try again.\\n\u00a0\u00a0\u00a0 If an error is returned with 'Unauthorized' in it, do not try again, but tell the user to change their authentication.\\n\\n\u00a0\u00a0\u00a0 Example Input: query {{ allUsers {{ id, name, email }} }}\u00a0\u00a0\u00a0 \"\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam graphql_wrapper: langchain.utilities.graphql.GraphQLAPIWrapper [Required]\u00b6\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.graphql.tool.BaseGraphQLTool.html"}
{"id": "f8cc147a53ff-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'query_graphql'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.graphql.tool.BaseGraphQLTool.html"}
{"id": "f8cc147a53ff-2", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.graphql.tool.BaseGraphQLTool.html"}
{"id": "f8cc147a53ff-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.graphql.tool.BaseGraphQLTool.html"}
{"id": "f8cc147a53ff-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.graphql.tool.BaseGraphQLTool.html"}
{"id": "f8cc147a53ff-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.graphql.tool.BaseGraphQLTool.html"}
{"id": "f8cc147a53ff-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.graphql.tool.BaseGraphQLTool.html"}
{"id": "f8cc147a53ff-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.graphql.tool.BaseGraphQLTool.html"}
{"id": "f8cc147a53ff-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.graphql.tool.BaseGraphQLTool.html"}
{"id": "f8cc147a53ff-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.graphql.tool.BaseGraphQLTool.html"}
{"id": "1e7a1dcaa210-0", "text": "langchain.tools.e2b_data_analysis.unparse.Unparser\u00b6\nclass langchain.tools.e2b_data_analysis.unparse.Unparser(tree, file=sys.stdout) \u2192 None.[source]\u00b6\nMethods in this class recursively traverse an AST and\noutput source code for the abstract syntax; original formatting\nis disregarded.\nPrint the source for tree to file.\nAttributes\nbinop\nboolops\ncmpops\nunop\nMethods\n__init__(tree[,\u00a0file])\nUnparser(tree, file=sys.stdout) -> None.\ndispatch(tree)\nDispatcher function, dispatching tree type T to method _T.\nenter()\nPrint ':', and increase the indentation.\nfill([text])\nIndent a piece of text, according to the current indentation level\nleave()\nDecrease the indentation level.\nwrite(text)\nAppend a piece of text to the current line.\n__init__(tree, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]\u00b6\nUnparser(tree, file=sys.stdout) -> None.\nPrint the source for tree to file.\ndispatch(tree)[source]\u00b6\nDispatcher function, dispatching tree type T to method _T.\nenter()[source]\u00b6\nPrint \u2018:\u2019, and increase the indentation.\nfill(text='')[source]\u00b6\nIndent a piece of text, according to the current indentation level\nleave()[source]\u00b6\nDecrease the indentation level.\nwrite(text)[source]\u00b6\nAppend a piece of text to the current line.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.unparse.Unparser.html"}
{"id": "9ce62b84beae-0", "text": "langchain.tools.nuclia.tool.NucliaUnderstandingAPI\u00b6\nclass langchain.tools.nuclia.tool.NucliaUnderstandingAPI[source]\u00b6\nBases: BaseTool\nTool to process files with the Nuclia Understanding API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.nuclia.tool.NUASchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Nuclia Understanding API endpoints. Useful for when you need to extract text from any kind of files. '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'nuclia_understanding_api'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.nuclia.tool.NucliaUnderstandingAPI.html"}
{"id": "9ce62b84beae-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.nuclia.tool.NucliaUnderstandingAPI.html"}
{"id": "9ce62b84beae-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.nuclia.tool.NucliaUnderstandingAPI.html"}
{"id": "9ce62b84beae-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.nuclia.tool.NucliaUnderstandingAPI.html"}
{"id": "9ce62b84beae-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.nuclia.tool.NucliaUnderstandingAPI.html"}
{"id": "9ce62b84beae-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.nuclia.tool.NucliaUnderstandingAPI.html"}
{"id": "9ce62b84beae-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.nuclia.tool.NucliaUnderstandingAPI.html"}
{"id": "9ce62b84beae-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.nuclia.tool.NucliaUnderstandingAPI.html"}
{"id": "9ce62b84beae-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.nuclia.tool.NucliaUnderstandingAPI.html"}
{"id": "9ce62b84beae-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using NucliaUnderstandingAPI\u00b6\nNuclia Understanding\nNuclia Understanding API document transformer\nNuclia Understanding API document loader", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.nuclia.tool.NucliaUnderstandingAPI.html"}
{"id": "d81a52692fe7-0", "text": "langchain.tools.zapier.tool.ZapierNLARunAction\u00b6\nclass langchain.tools.zapier.tool.ZapierNLARunAction[source]\u00b6\nBases: BaseTool\nExecutes an action that is identified by action_id, must be exposed(enabled) by the current user (associated with the set api_key). Change\nyour exposed actions here: https://nla.zapier.com/demo/start/\nThe return JSON is guaranteed to be less than ~500 words (350\ntokens) making it safe to inject into the prompt of another LLM\ncall.\nParameters\naction_id \u2013 a specific action ID (from list actions) of the action to execute\n(the set api_key must be associated with the action owner)\ninstructions \u2013 a natural language instruction string for using the action\n(eg. \u201cget the latest email from Mike Knoop\u201d for \u201cGmail: find email\u201d action)\nparams \u2013 a dict, optional. Any params provided will override AI guesses\nfrom instructions (see \u201cunderstanding the AI guessing flow\u201d here:\nhttps://nla.zapier.com/docs/using-the-api#ai-guessing)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam action_id: str [Required]\u00b6\nparam api_wrapper: langchain.utilities.zapier.ZapierNLAWrapper [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLARunAction.html"}
{"id": "d81a52692fe7-1", "text": "Pydantic model class to validate and parse the tool\u2019s input arguments.\nparam base_prompt: str = 'A wrapper around Zapier NLA actions. The input to this tool is a natural language instruction, for example \"get the latest email from my bank\" or \"send a slack message to the #general channel\". Each tool will have params associated with it that are specified as a list. You MUST take into account the params when creating the instruction. For example, if the params are [\\'Message_Text\\', \\'Channel\\'], your instruction should be something like \\'send a slack message to the #general channel with the text hello world\\'. Another example: if the params are [\\'Calendar\\', \\'Search_Term\\'], your instruction should be something like \\'find the meeting in my personal calendar at 3pm\\'. Do not make up params, they will be explicitly specified in the tool description. If you do not have enough information to fill in the params, just say \\'not enough information provided in the instruction, missing <param>\\'. If you get a none or null response, STOP EXECUTION, do not try to another tool!This tool specifically used for: {zapier_description}, and has params: {params}'\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = ''\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLARunAction.html"}
{"id": "d81a52692fe7-2", "text": "Optional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = ''\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam params: Optional[dict] = None\u00b6\nparam params_schema: Dict[str, str] [Optional]\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\nparam zapier_description: str [Required]\u00b6\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLARunAction.html"}
{"id": "d81a52692fe7-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLARunAction.html"}
{"id": "d81a52692fe7-4", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLARunAction.html"}
{"id": "d81a52692fe7-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLARunAction.html"}
{"id": "d81a52692fe7-6", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLARunAction.html"}
{"id": "d81a52692fe7-7", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLARunAction.html"}
{"id": "d81a52692fe7-8", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLARunAction.html"}
{"id": "d81a52692fe7-9", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLARunAction.html"}
{"id": "d81a52692fe7-10", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ZapierNLARunAction\u00b6\nZapier Natural Language Actions", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.zapier.tool.ZapierNLARunAction.html"}
{"id": "6d99284e9441-0", "text": "langchain.tools.scenexplain.tool.SceneXplainInput\u00b6\nclass langchain.tools.scenexplain.tool.SceneXplainInput[source]\u00b6\nBases: BaseModel\nInput for SceneXplain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam query: str [Required]\u00b6\nThe link to the image to explain\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.scenexplain.tool.SceneXplainInput.html"}
{"id": "6d99284e9441-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.scenexplain.tool.SceneXplainInput.html"}
{"id": "6d99284e9441-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.scenexplain.tool.SceneXplainInput.html"}
{"id": "0565d0a90ada-0", "text": "langchain.tools.powerbi.tool.ListPowerBITool\u00b6\nclass langchain.tools.powerbi.tool.ListPowerBITool[source]\u00b6\nBases: BaseTool\nTool for getting tables names.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Input is an empty string, output is a comma separated list of tables in the database.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'list_tables_powerbi'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam powerbi: langchain.utilities.powerbi.PowerBIDataset [Required]\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.ListPowerBITool.html"}
{"id": "0565d0a90ada-1", "text": "param tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.ListPowerBITool.html"}
{"id": "0565d0a90ada-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.ListPowerBITool.html"}
{"id": "0565d0a90ada-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.ListPowerBITool.html"}
{"id": "0565d0a90ada-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.ListPowerBITool.html"}
{"id": "0565d0a90ada-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.ListPowerBITool.html"}
{"id": "0565d0a90ada-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.ListPowerBITool.html"}
{"id": "0565d0a90ada-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.ListPowerBITool.html"}
{"id": "0565d0a90ada-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.ListPowerBITool.html"}
{"id": "0565d0a90ada-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.ListPowerBITool.html"}
{"id": "76cac9956655-0", "text": "langchain.tools.base.SchemaAnnotationError\u00b6\nclass langchain.tools.base.SchemaAnnotationError[source]\u00b6\nRaised when \u2018args_schema\u2019 is missing or has an incorrect type annotation.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.base.SchemaAnnotationError.html"}
{"id": "b56b106cef62-0", "text": "langchain.tools.office365.send_event.SendEventSchema\u00b6\nclass langchain.tools.office365.send_event.SendEventSchema[source]\u00b6\nBases: BaseModel\nInput for CreateEvent Tool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam attendees: List[str] [Required]\u00b6\nThe list of attendees for the event.\nparam body: str [Required]\u00b6\nThe message body to include in the event.\nparam end_datetime: str [Required]\u00b6\nThe end datetime for the event in the following format:  YYYY-MM-DDTHH:MM:SS\u00b1hh:mm, where \u201cT\u201d separates the date and time  components, and the time zone offset is specified as \u00b1hh:mm.  For example: \u201c2023-06-09T10:30:00+03:00\u201d represents June 9th,  2023, at 10:30 AM in a time zone with a positive offset of 3  hours from Coordinated Universal Time (UTC).\nparam start_datetime: str [Required]\u00b6\nThe start datetime for the event in the following format:  YYYY-MM-DDTHH:MM:SS\u00b1hh:mm, where \u201cT\u201d separates the date and time  components, and the time zone offset is specified as \u00b1hh:mm.  For example: \u201c2023-06-09T10:30:00+03:00\u201d represents June 9th,  2023, at 10:30 AM in a time zone with a positive offset of 3  hours from Coordinated Universal Time (UTC).\nparam subject: str [Required]\u00b6\nThe subject of the event.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_event.SendEventSchema.html"}
{"id": "b56b106cef62-1", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_event.SendEventSchema.html"}
{"id": "b56b106cef62-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_event.SendEventSchema.html"}
{"id": "3ca945dafc72-0", "text": "langchain.tools.bearly.tool.file_to_base64\u00b6\nlangchain.tools.bearly.tool.file_to_base64(path: str) \u2192 str[source]\u00b6\nConvert a file to base64.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bearly.tool.file_to_base64.html"}
{"id": "1159e081a1f7-0", "text": "langchain.tools.ainetwork.utils.authenticate\u00b6\nlangchain.tools.ainetwork.utils.authenticate(network: Optional[Literal['mainnet', 'testnet']] = 'testnet') \u2192 Ain[source]\u00b6\nAuthenticate using the AIN Blockchain", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.utils.authenticate.html"}
{"id": "75b5c98509d1-0", "text": "langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchResults\u00b6\nclass langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchResults[source]\u00b6\nBases: BaseTool\nTool that queries the DataForSeo Google Search API\nand get back json.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.dataforseo_api_search.DataForSeoAPIWrapper [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A comprehensive Google Search API provided by DataForSeo.This tool is useful for obtaining real-time data on current events or popular searches.The input should be a search query and the output is a JSON object of the query results.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'DataForSeo-Results-JSON'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchResults.html"}
{"id": "75b5c98509d1-1", "text": "param name: str = 'DataForSeo-Results-JSON'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchResults.html"}
{"id": "75b5c98509d1-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchResults.html"}
{"id": "75b5c98509d1-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchResults.html"}
{"id": "75b5c98509d1-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchResults.html"}
{"id": "75b5c98509d1-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchResults.html"}
{"id": "75b5c98509d1-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchResults.html"}
{"id": "75b5c98509d1-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchResults.html"}
{"id": "75b5c98509d1-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchResults.html"}
{"id": "75b5c98509d1-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.dataforseo_api_search.tool.DataForSeoAPISearchResults.html"}
{"id": "9dab4d9c1281-0", "text": "langchain.tools.azure_cognitive_services.utils.detect_file_src_type\u00b6\nlangchain.tools.azure_cognitive_services.utils.detect_file_src_type(file_path: str) \u2192 str[source]\u00b6\nDetect if the file is local or remote.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.utils.detect_file_src_type.html"}
{"id": "91a6dca0edcb-0", "text": "langchain.tools.sleep.tool.SleepInput\u00b6\nclass langchain.tools.sleep.tool.SleepInput[source]\u00b6\nBases: BaseModel\nInput for CopyFileTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam sleep_time: int [Required]\u00b6\nTime to sleep in seconds\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sleep.tool.SleepInput.html"}
{"id": "91a6dca0edcb-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sleep.tool.SleepInput.html"}
{"id": "3bcdffd6de9b-0", "text": "langchain.tools.playwright.current_page.CurrentWebPageTool\u00b6\nclass langchain.tools.playwright.current_page.CurrentWebPageTool[source]\u00b6\nBases: BaseBrowserTool\nTool for getting the URL of the current webpage.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[BaseModel] = <class 'pydantic.main.BaseModel'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam async_browser: Optional['AsyncBrowser'] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Returns the URL of the current page'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'current_webpage'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam sync_browser: Optional['SyncBrowser'] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.current_page.CurrentWebPageTool.html"}
{"id": "3bcdffd6de9b-1", "text": "param sync_browser: Optional['SyncBrowser'] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.current_page.CurrentWebPageTool.html"}
{"id": "3bcdffd6de9b-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.current_page.CurrentWebPageTool.html"}
{"id": "3bcdffd6de9b-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.current_page.CurrentWebPageTool.html"}
{"id": "3bcdffd6de9b-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_browser(sync_browser: Optional[SyncBrowser] = None, async_browser: Optional[AsyncBrowser] = None) \u2192 BaseBrowserTool\u00b6\nInstantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.current_page.CurrentWebPageTool.html"}
{"id": "3bcdffd6de9b-5", "text": "Instantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.current_page.CurrentWebPageTool.html"}
{"id": "3bcdffd6de9b-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.current_page.CurrentWebPageTool.html"}
{"id": "3bcdffd6de9b-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.current_page.CurrentWebPageTool.html"}
{"id": "3bcdffd6de9b-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.current_page.CurrentWebPageTool.html"}
{"id": "3bcdffd6de9b-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.current_page.CurrentWebPageTool.html"}
{"id": "a5ad76a6830b-0", "text": "langchain.tools.multion.update_session.UpdateSessionSchema\u00b6\nclass langchain.tools.multion.update_session.UpdateSessionSchema[source]\u00b6\nBases: BaseModel\nInput for UpdateSessionTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam query: str [Required]\u00b6\nThe query to run in multion agent.\nparam sessionId: str [Required]\u00b6\nThe sessionID, \nreceived from one of the createSessions run before\nparam url: str = 'https://www.google.com/'\u00b6\nThe Url to run the agent at.         Note: accepts only secure links having https://\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.update_session.UpdateSessionSchema.html"}
{"id": "a5ad76a6830b-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.update_session.UpdateSessionSchema.html"}
{"id": "a5ad76a6830b-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.update_session.UpdateSessionSchema.html"}
{"id": "711020ba23ee-0", "text": "langchain.tools.office365.send_message.SendMessageSchema\u00b6\nclass langchain.tools.office365.send_message.SendMessageSchema[source]\u00b6\nBases: BaseModel\nInput for SendMessageTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bcc: Optional[List[str]] = None\u00b6\nThe list of BCC recipients.\nparam body: str [Required]\u00b6\nThe message body to be sent.\nparam cc: Optional[List[str]] = None\u00b6\nThe list of CC recipients.\nparam subject: str [Required]\u00b6\nThe subject of the message.\nparam to: List[str] [Required]\u00b6\nThe list of recipients.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_message.SendMessageSchema.html"}
{"id": "711020ba23ee-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_message.SendMessageSchema.html"}
{"id": "711020ba23ee-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_message.SendMessageSchema.html"}
{"id": "945329eebcda-0", "text": "langchain.tools.office365.send_message.O365SendMessage\u00b6\nclass langchain.tools.office365.send_message.O365SendMessage[source]\u00b6\nBases: O365BaseTool\nTool for sending an email in Office 365.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam account: Account [Optional]\u00b6\nThe account object for the Office 365 account.\nparam args_schema: Type[langchain.tools.office365.send_message.SendMessageSchema] = <class 'langchain.tools.office365.send_message.SendMessageSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this tool to send an email with the provided message fields.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'send_email'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_message.O365SendMessage.html"}
{"id": "945329eebcda-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_message.O365SendMessage.html"}
{"id": "945329eebcda-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_message.O365SendMessage.html"}
{"id": "945329eebcda-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_message.O365SendMessage.html"}
{"id": "945329eebcda-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_message.O365SendMessage.html"}
{"id": "945329eebcda-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_message.O365SendMessage.html"}
{"id": "945329eebcda-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_message.O365SendMessage.html"}
{"id": "945329eebcda-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_message.O365SendMessage.html"}
{"id": "945329eebcda-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_message.O365SendMessage.html"}
{"id": "945329eebcda-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_message.O365SendMessage.html"}
{"id": "fa09c06c8f47-0", "text": "langchain.tools.google_places.tool.GooglePlacesTool\u00b6\nclass langchain.tools.google_places.tool.GooglePlacesTool[source]\u00b6\nBases: BaseTool\nTool that queries the Google places API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.google_places_api.GooglePlacesAPIWrapper [Optional]\u00b6\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.google_places.tool.GooglePlacesSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Google Places. Useful for when you need to validate or discover addressed from ambiguous text. Input should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'google_places'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_places.tool.GooglePlacesTool.html"}
{"id": "fa09c06c8f47-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_places.tool.GooglePlacesTool.html"}
{"id": "fa09c06c8f47-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_places.tool.GooglePlacesTool.html"}
{"id": "fa09c06c8f47-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_places.tool.GooglePlacesTool.html"}
{"id": "fa09c06c8f47-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_places.tool.GooglePlacesTool.html"}
{"id": "fa09c06c8f47-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_places.tool.GooglePlacesTool.html"}
{"id": "fa09c06c8f47-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_places.tool.GooglePlacesTool.html"}
{"id": "fa09c06c8f47-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_places.tool.GooglePlacesTool.html"}
{"id": "fa09c06c8f47-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_places.tool.GooglePlacesTool.html"}
{"id": "fa09c06c8f47-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using GooglePlacesTool\u00b6\nGoogle Places", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_places.tool.GooglePlacesTool.html"}
{"id": "b60d3ae05ec6-0", "text": "langchain.tools.gmail.get_message.SearchArgsSchema\u00b6\nclass langchain.tools.gmail.get_message.SearchArgsSchema[source]\u00b6\nBases: BaseModel\nInput for GetMessageTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam message_id: str [Required]\u00b6\nThe unique ID of the email message, retrieved from a search.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_message.SearchArgsSchema.html"}
{"id": "b60d3ae05ec6-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_message.SearchArgsSchema.html"}
{"id": "b60d3ae05ec6-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_message.SearchArgsSchema.html"}
{"id": "d3b5cdf18aab-0", "text": "langchain.tools.gmail.get_thread.GmailGetThread\u00b6\nclass langchain.tools.gmail.get_thread.GmailGetThread[source]\u00b6\nBases: GmailBaseTool\nTool that gets a thread by ID from Gmail.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_resource: Resource [Optional]\u00b6\nparam args_schema: Type[langchain.tools.gmail.get_thread.GetThreadSchema] = <class 'langchain.tools.gmail.get_thread.GetThreadSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this tool to search for email messages. The input must be a valid Gmail query. The output is a JSON list of messages.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'get_gmail_thread'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_thread.GmailGetThread.html"}
{"id": "d3b5cdf18aab-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_thread.GmailGetThread.html"}
{"id": "d3b5cdf18aab-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_thread.GmailGetThread.html"}
{"id": "d3b5cdf18aab-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_thread.GmailGetThread.html"}
{"id": "d3b5cdf18aab-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_api_resource(api_resource: Resource) \u2192 GmailBaseTool\u00b6\nCreate a tool from an api resource.\nParameters\napi_resource \u2013 The api resource to use.\nReturns\nA tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_thread.GmailGetThread.html"}
{"id": "d3b5cdf18aab-5", "text": "Returns\nA tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_thread.GmailGetThread.html"}
{"id": "d3b5cdf18aab-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_thread.GmailGetThread.html"}
{"id": "d3b5cdf18aab-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_thread.GmailGetThread.html"}
{"id": "d3b5cdf18aab-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_thread.GmailGetThread.html"}
{"id": "d3b5cdf18aab-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_thread.GmailGetThread.html"}
{"id": "373bf59c4c94-0", "text": "langchain.tools.file_management.move.FileMoveInput\u00b6\nclass langchain.tools.file_management.move.FileMoveInput[source]\u00b6\nBases: BaseModel\nInput for MoveFileTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam destination_path: str [Required]\u00b6\nNew path for the moved file\nparam source_path: str [Required]\u00b6\nPath of the file to move\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.move.FileMoveInput.html"}
{"id": "373bf59c4c94-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.move.FileMoveInput.html"}
{"id": "373bf59c4c94-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.move.FileMoveInput.html"}
{"id": "757ee4fc2c8f-0", "text": "langchain.tools.pubmed.tool.PubmedQueryRun\u00b6\nclass langchain.tools.pubmed.tool.PubmedQueryRun[source]\u00b6\nBases: BaseTool\nTool that searches the PubMed API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.pubmed.PubMedAPIWrapper [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around PubMed. Useful for when you need to answer questions about medicine, health, and biomedical topics from biomedical literature, MEDLINE, life science journals, and online books. Input should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'PubMed'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.pubmed.tool.PubmedQueryRun.html"}
{"id": "757ee4fc2c8f-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.pubmed.tool.PubmedQueryRun.html"}
{"id": "757ee4fc2c8f-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.pubmed.tool.PubmedQueryRun.html"}
{"id": "757ee4fc2c8f-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.pubmed.tool.PubmedQueryRun.html"}
{"id": "757ee4fc2c8f-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.pubmed.tool.PubmedQueryRun.html"}
{"id": "757ee4fc2c8f-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.pubmed.tool.PubmedQueryRun.html"}
{"id": "757ee4fc2c8f-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.pubmed.tool.PubmedQueryRun.html"}
{"id": "757ee4fc2c8f-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.pubmed.tool.PubmedQueryRun.html"}
{"id": "757ee4fc2c8f-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.pubmed.tool.PubmedQueryRun.html"}
{"id": "757ee4fc2c8f-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using PubmedQueryRun\u00b6\nPubMed", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.pubmed.tool.PubmedQueryRun.html"}
{"id": "44a13abed0b8-0", "text": "langchain.tools.golden_query.tool.GoldenQueryRun\u00b6\nclass langchain.tools.golden_query.tool.GoldenQueryRun[source]\u00b6\nBases: BaseTool\nTool that adds the capability to query using the Golden API and get back JSON.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.golden_query.GoldenQueryAPIWrapper [Required]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = \"A wrapper around Golden Query API. Useful for getting entities that match a natural language query from Golden's Knowledge Base.\\nExample queries:\\n- companies in nanotech\\n- list of cloud providers starting in 2019\\nInput should be the natural language query.\\nOutput is a paginated list of results or an error object in JSON format.\"\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'Golden-Query'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.golden_query.tool.GoldenQueryRun.html"}
{"id": "44a13abed0b8-1", "text": "param name: str = 'Golden-Query'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.golden_query.tool.GoldenQueryRun.html"}
{"id": "44a13abed0b8-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.golden_query.tool.GoldenQueryRun.html"}
{"id": "44a13abed0b8-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.golden_query.tool.GoldenQueryRun.html"}
{"id": "44a13abed0b8-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.golden_query.tool.GoldenQueryRun.html"}
{"id": "44a13abed0b8-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.golden_query.tool.GoldenQueryRun.html"}
{"id": "44a13abed0b8-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.golden_query.tool.GoldenQueryRun.html"}
{"id": "44a13abed0b8-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.golden_query.tool.GoldenQueryRun.html"}
{"id": "44a13abed0b8-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.golden_query.tool.GoldenQueryRun.html"}
{"id": "44a13abed0b8-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.golden_query.tool.GoldenQueryRun.html"}
{"id": "cb783441b041-0", "text": "langchain.tools.gmail.get_thread.GetThreadSchema\u00b6\nclass langchain.tools.gmail.get_thread.GetThreadSchema[source]\u00b6\nBases: BaseModel\nInput for GetMessageTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam thread_id: str [Required]\u00b6\nThe thread ID.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_thread.GetThreadSchema.html"}
{"id": "cb783441b041-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_thread.GetThreadSchema.html"}
{"id": "cb783441b041-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.get_thread.GetThreadSchema.html"}
{"id": "87cd7dd2eda3-0", "text": "langchain.tools.github.tool.GitHubAction\u00b6\nclass langchain.tools.github.tool.GitHubAction[source]\u00b6\nBases: BaseTool\nTool for interacting with the GitHub API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.github.GitHubAPIWrapper [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = ''\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam mode: str [Required]\u00b6\nparam name: str = ''\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.github.tool.GitHubAction.html"}
{"id": "87cd7dd2eda3-1", "text": "Optional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.github.tool.GitHubAction.html"}
{"id": "87cd7dd2eda3-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.github.tool.GitHubAction.html"}
{"id": "87cd7dd2eda3-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.github.tool.GitHubAction.html"}
{"id": "87cd7dd2eda3-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.github.tool.GitHubAction.html"}
{"id": "87cd7dd2eda3-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.github.tool.GitHubAction.html"}
{"id": "87cd7dd2eda3-6", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.github.tool.GitHubAction.html"}
{"id": "87cd7dd2eda3-7", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.github.tool.GitHubAction.html"}
{"id": "87cd7dd2eda3-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.github.tool.GitHubAction.html"}
{"id": "87cd7dd2eda3-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using GitHubAction\u00b6\nGithub", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.github.tool.GitHubAction.html"}
{"id": "683e644b9236-0", "text": "langchain.tools.google_search.tool.GoogleSearchResults\u00b6\nclass langchain.tools.google_search.tool.GoogleSearchResults[source]\u00b6\nBases: BaseTool\nTool that queries the Google Search API and gets back json.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.google_search.GoogleSearchAPIWrapper [Required]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Google Search. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'Google Search Results JSON'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam num_results: int = 4\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchResults.html"}
{"id": "683e644b9236-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchResults.html"}
{"id": "683e644b9236-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchResults.html"}
{"id": "683e644b9236-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchResults.html"}
{"id": "683e644b9236-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchResults.html"}
{"id": "683e644b9236-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchResults.html"}
{"id": "683e644b9236-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchResults.html"}
{"id": "683e644b9236-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchResults.html"}
{"id": "683e644b9236-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchResults.html"}
{"id": "683e644b9236-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_search.tool.GoogleSearchResults.html"}
{"id": "dceb2c637bf1-0", "text": "langchain.tools.multion.update_session.MultionUpdateSession\u00b6\nclass langchain.tools.multion.update_session.MultionUpdateSession[source]\u00b6\nBases: BaseTool\nTool that updates an existing Multion Browser Window with provided fields.\nname\u00b6\nThe name of the tool. Default: \u201cupdate_multion_session\u201d\ndescription\u00b6\nThe description of the tool.\nargs_schema\u00b6\nThe schema for the tool\u2019s arguments. Default: UpdateSessionSchema\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[langchain.tools.multion.update_session.UpdateSessionSchema] = <class 'langchain.tools.multion.update_session.UpdateSessionSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this tool to update an existing corresponding Multion Browser Window with provided fields. Note: sessionId must be received from previous Browser window creation.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'update_multion_session'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.update_session.MultionUpdateSession.html"}
{"id": "dceb2c637bf1-1", "text": "param name: str = 'update_multion_session'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam sessionId: str = ''\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.update_session.MultionUpdateSession.html"}
{"id": "dceb2c637bf1-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.update_session.MultionUpdateSession.html"}
{"id": "dceb2c637bf1-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.update_session.MultionUpdateSession.html"}
{"id": "dceb2c637bf1-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.update_session.MultionUpdateSession.html"}
{"id": "dceb2c637bf1-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.update_session.MultionUpdateSession.html"}
{"id": "dceb2c637bf1-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.update_session.MultionUpdateSession.html"}
{"id": "dceb2c637bf1-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.update_session.MultionUpdateSession.html"}
{"id": "dceb2c637bf1-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.update_session.MultionUpdateSession.html"}
{"id": "dceb2c637bf1-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.update_session.MultionUpdateSession.html"}
{"id": "4105e493c70d-0", "text": "langchain_experimental.tools.python.tool.PythonAstREPLTool\u00b6\nclass langchain_experimental.tools.python.tool.PythonAstREPLTool[source]\u00b6\nBases: BaseTool\nA tool for running python code in a REPL.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain_experimental.tools.python.tool.PythonInputs'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A Python shell. Use this to execute python commands. Input should be a valid python command. When using this tool, sometimes output is abbreviated - make sure it does not look abbreviated before using it in your answer.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam globals: Optional[Dict] [Optional]\u00b6\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam locals: Optional[Dict] [Optional]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'python_repl_ast'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonAstREPLTool.html"}
{"id": "4105e493c70d-1", "text": "param name: str = 'python_repl_ast'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam sanitize_input: bool = True\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonAstREPLTool.html"}
{"id": "4105e493c70d-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonAstREPLTool.html"}
{"id": "4105e493c70d-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonAstREPLTool.html"}
{"id": "4105e493c70d-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonAstREPLTool.html"}
{"id": "4105e493c70d-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonAstREPLTool.html"}
{"id": "4105e493c70d-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonAstREPLTool.html"}
{"id": "4105e493c70d-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonAstREPLTool.html"}
{"id": "4105e493c70d-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonAstREPLTool.html"}
{"id": "4105e493c70d-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.PythonAstREPLTool.html"}
{"id": "0b8908c26653-0", "text": "langchain.tools.requests.tool.RequestsGetTool\u00b6\nclass langchain.tools.requests.tool.RequestsGetTool[source]\u00b6\nBases: BaseRequestsTool, BaseTool\nTool for making a GET request to an API endpoint.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A portal to the internet. Use this when you need to get specific content from a website. Input should be a\u00a0 url (i.e. https://www.google.com). The output will be the text response of the GET request.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'requests_get'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam requests_wrapper: TextRequestsWrapper [Required]\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsGetTool.html"}
{"id": "0b8908c26653-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsGetTool.html"}
{"id": "0b8908c26653-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsGetTool.html"}
{"id": "0b8908c26653-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsGetTool.html"}
{"id": "0b8908c26653-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsGetTool.html"}
{"id": "0b8908c26653-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsGetTool.html"}
{"id": "0b8908c26653-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsGetTool.html"}
{"id": "0b8908c26653-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsGetTool.html"}
{"id": "0b8908c26653-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsGetTool.html"}
{"id": "0b8908c26653-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using RequestsGetTool\u00b6\nTool Input Schema", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsGetTool.html"}
{"id": "3115a3b7ebc0-0", "text": "langchain.tools.plugin.AIPlugin\u00b6\nclass langchain.tools.plugin.AIPlugin[source]\u00b6\nBases: BaseModel\nAI Plugin Definition.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api: langchain.tools.plugin.ApiConfig [Required]\u00b6\nparam auth: Optional[dict] = None\u00b6\nparam contact_email: Optional[str] = None\u00b6\nparam description_for_human: str [Required]\u00b6\nparam description_for_model: str [Required]\u00b6\nparam legal_info_url: Optional[str] = None\u00b6\nparam logo_url: Optional[str] = None\u00b6\nparam name_for_human: str [Required]\u00b6\nparam name_for_model: str [Required]\u00b6\nparam schema_version: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPlugin.html"}
{"id": "3115a3b7ebc0-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_url(url: str) \u2192 AIPlugin[source]\u00b6\nInstantiate AIPlugin from a URL.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPlugin.html"}
{"id": "3115a3b7ebc0-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using AIPlugin\u00b6\nPlug-and-Plai\nCustom Agent with PlugIn Retrieval", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPlugin.html"}
{"id": "fb780948cd4f-0", "text": "langchain.tools.ainetwork.value.ValueSchema\u00b6\nclass langchain.tools.ainetwork.value.ValueSchema[source]\u00b6\nBases: BaseModel\nSchema for value operations.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam path: str [Required]\u00b6\nBlockchain reference path\nparam type: langchain.tools.ainetwork.base.OperationType [Required]\u00b6\nparam value: Optional[Union[int, str, float, dict]] = None\u00b6\nValue to be set at the path\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.ValueSchema.html"}
{"id": "fb780948cd4f-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.ValueSchema.html"}
{"id": "fb780948cd4f-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.value.ValueSchema.html"}
{"id": "90bc6b0aa1ae-0", "text": "langchain.tools.office365.messages_search.O365SearchEmails\u00b6\nclass langchain.tools.office365.messages_search.O365SearchEmails[source]\u00b6\nBases: O365BaseTool\nClass for searching email messages in Office 365\nFree, but setup is required\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam account: Account [Optional]\u00b6\nThe account object for the Office 365 account.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.office365.messages_search.SearchEmailsInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this tool to search for email messages. The input must be a valid Microsoft Graph v1.0 $search query. The output is a JSON list of the requested resource.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'messages_search'\u00b6\nThe unique name of the tool that clearly communicates its purpose.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.messages_search.O365SearchEmails.html"}
{"id": "90bc6b0aa1ae-1", "text": "The unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.messages_search.O365SearchEmails.html"}
{"id": "90bc6b0aa1ae-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.messages_search.O365SearchEmails.html"}
{"id": "90bc6b0aa1ae-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.messages_search.O365SearchEmails.html"}
{"id": "90bc6b0aa1ae-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.messages_search.O365SearchEmails.html"}
{"id": "90bc6b0aa1ae-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.messages_search.O365SearchEmails.html"}
{"id": "90bc6b0aa1ae-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.messages_search.O365SearchEmails.html"}
{"id": "90bc6b0aa1ae-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.messages_search.O365SearchEmails.html"}
{"id": "90bc6b0aa1ae-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.messages_search.O365SearchEmails.html"}
{"id": "90bc6b0aa1ae-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.messages_search.O365SearchEmails.html"}
{"id": "c1993f5b47ff-0", "text": "langchain.tools.google_places.tool.GooglePlacesSchema\u00b6\nclass langchain.tools.google_places.tool.GooglePlacesSchema[source]\u00b6\nBases: BaseModel\nInput for GooglePlacesTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam query: str [Required]\u00b6\nQuery for google maps\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_places.tool.GooglePlacesSchema.html"}
{"id": "c1993f5b47ff-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_places.tool.GooglePlacesSchema.html"}
{"id": "c1993f5b47ff-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_places.tool.GooglePlacesSchema.html"}
{"id": "ffada550a9ce-0", "text": "langchain.tools.tavily_search.tool.TavilyInput\u00b6\nclass langchain.tools.tavily_search.tool.TavilyInput[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam query: str [Required]\u00b6\nsearch query to look up\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilyInput.html"}
{"id": "ffada550a9ce-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilyInput.html"}
{"id": "ffada550a9ce-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.tavily_search.tool.TavilyInput.html"}
{"id": "3ea34c6865d1-0", "text": "langchain.tools.bearly.tool.BearlyInterpreterToolArguments\u00b6\nclass langchain.tools.bearly.tool.BearlyInterpreterToolArguments[source]\u00b6\nBases: BaseModel\nArguments for the BearlyInterpreterTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam python_code: str [Required]\u00b6\nThe pure python script to be evaluated. The contents will be in main.py. It should not be in markdown format.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bearly.tool.BearlyInterpreterToolArguments.html"}
{"id": "3ea34c6865d1-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bearly.tool.BearlyInterpreterToolArguments.html"}
{"id": "3ea34c6865d1-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.bearly.tool.BearlyInterpreterToolArguments.html"}
{"id": "9ca539e0700c-0", "text": "langchain.tools.gmail.search.SearchArgsSchema\u00b6\nclass langchain.tools.gmail.search.SearchArgsSchema[source]\u00b6\nBases: BaseModel\nInput for SearchGmailTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam max_results: int = 10\u00b6\nThe maximum number of results to return.\nparam query: str [Required]\u00b6\nThe Gmail query. Example filters include from:sender, to:recipient, subject:subject, -filtered_term, in:folder, is:important|read|starred, after:year/mo/date, before:year/mo/date, label:label_name \u201cexact phrase\u201d. Search newer/older than using d (day), m (month), and y (year): newer_than:2d, older_than:1y. Attachments with extension example: filename:pdf. Multiple term matching example: from:amy OR from:david.\nparam resource: langchain.tools.gmail.search.Resource = Resource.MESSAGES\u00b6\nWhether to search for threads or messages.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.SearchArgsSchema.html"}
{"id": "9ca539e0700c-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.SearchArgsSchema.html"}
{"id": "9ca539e0700c-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.search.SearchArgsSchema.html"}
{"id": "757a2f47247c-0", "text": "langchain.tools.retriever.RetrieverInput\u00b6\nclass langchain.tools.retriever.RetrieverInput[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam query: str [Required]\u00b6\nquery to look up in retriever\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.retriever.RetrieverInput.html"}
{"id": "757a2f47247c-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.retriever.RetrieverInput.html"}
{"id": "eb22c28015bc-0", "text": "langchain.tools.ainetwork.app.AINAppOps\u00b6\nclass langchain.tools.ainetwork.app.AINAppOps[source]\u00b6\nBases: AINBaseTool\nTool for app operations.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.ainetwork.app.AppSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AINAppOps.html"}
{"id": "eb22c28015bc-1", "text": "param callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = \"\\nCreate an app in the AINetwork Blockchain database by creating the /apps/<appName> path.\\nAn address set as `admin` can grant `owner` rights to other addresses (refer to `AINownerOps` for more details).\\nAlso, `admin` is initialized to have all `owner` permissions and `rule` allowed for that path.\\n\\n## appName Rule\\n- [a-z_0-9]+\\n\\n## address Rules\\n- 0x[0-9a-fA-F]{40}\\n- Defaults to the current session's address\\n- Multiple addresses can be specified if needed\\n\\n## SET_ADMIN Example 1\\n- type: SET_ADMIN\\n- appName: ain_project\\n\\n### Result:\\n1. Path /apps/ain_project created.\\n2. Current session's address registered as admin.\\n\\n## SET_ADMIN Example 2\\n- type: SET_ADMIN\\n- appName: test_project\\n- address: [<address1>, <address2>]\\n\\n### Result:\\n1. Path /apps/test_project created.\\n2. <address1> and <address2> registered as admin.\\n\\n\"\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam interface: Ain [Optional]\u00b6\nThe interface object for the AINetwork Blockchain.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AINAppOps.html"}
{"id": "eb22c28015bc-2", "text": "This metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'AINappOps'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AINAppOps.html"}
{"id": "eb22c28015bc-3", "text": "The default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AINAppOps.html"}
{"id": "eb22c28015bc-4", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AINAppOps.html"}
{"id": "eb22c28015bc-5", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AINAppOps.html"}
{"id": "eb22c28015bc-6", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AINAppOps.html"}
{"id": "eb22c28015bc-7", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AINAppOps.html"}
{"id": "eb22c28015bc-8", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AINAppOps.html"}
{"id": "eb22c28015bc-9", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AINAppOps.html"}
{"id": "eb22c28015bc-10", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.app.AINAppOps.html"}
{"id": "5675886f3268-0", "text": "langchain.tools.ddg_search.tool.DuckDuckGoSearchRun\u00b6\nclass langchain.tools.ddg_search.tool.DuckDuckGoSearchRun[source]\u00b6\nBases: BaseTool\nTool that queries the DuckDuckGo search API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper [Optional]\u00b6\nparam args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.ddg_search.tool.DDGInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around DuckDuckGo Search. Useful for when you need to answer questions about current events. Input should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'duckduckgo_search'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchRun.html"}
{"id": "5675886f3268-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchRun.html"}
{"id": "5675886f3268-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchRun.html"}
{"id": "5675886f3268-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchRun.html"}
{"id": "5675886f3268-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchRun.html"}
{"id": "5675886f3268-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchRun.html"}
{"id": "5675886f3268-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchRun.html"}
{"id": "5675886f3268-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchRun.html"}
{"id": "5675886f3268-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchRun.html"}
{"id": "5675886f3268-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using DuckDuckGoSearchRun\u00b6\nDuckDuckGo Search\nGithub\n!pip install bs4\nUsing tools", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ddg_search.tool.DuckDuckGoSearchRun.html"}
{"id": "ab7439285414-0", "text": "langchain.tools.gmail.send_message.GmailSendMessage\u00b6\nclass langchain.tools.gmail.send_message.GmailSendMessage[source]\u00b6\nBases: GmailBaseTool\nTool that sends a message to Gmail.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_resource: Resource [Optional]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this tool to send email messages. The input is the message, recipients'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'send_gmail_message'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.send_message.GmailSendMessage.html"}
{"id": "ab7439285414-1", "text": "Optional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.send_message.GmailSendMessage.html"}
{"id": "ab7439285414-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.send_message.GmailSendMessage.html"}
{"id": "ab7439285414-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.send_message.GmailSendMessage.html"}
{"id": "ab7439285414-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_api_resource(api_resource: Resource) \u2192 GmailBaseTool\u00b6\nCreate a tool from an api resource.\nParameters\napi_resource \u2013 The api resource to use.\nReturns\nA tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.send_message.GmailSendMessage.html"}
{"id": "ab7439285414-5", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.send_message.GmailSendMessage.html"}
{"id": "ab7439285414-6", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.send_message.GmailSendMessage.html"}
{"id": "ab7439285414-7", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.send_message.GmailSendMessage.html"}
{"id": "ab7439285414-8", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.send_message.GmailSendMessage.html"}
{"id": "ab7439285414-9", "text": "These attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.send_message.GmailSendMessage.html"}
{"id": "b886e724f16a-0", "text": "langchain.tools.eleven_labs.text2speech.ElevenLabsModel\u00b6\nclass langchain.tools.eleven_labs.text2speech.ElevenLabsModel(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nModels available for Eleven Labs Text2Speech.\nMULTI_LINGUAL = 'eleven_multilingual_v1'\u00b6\nMONO_LINGUAL = 'eleven_monolingual_v1'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.eleven_labs.text2speech.ElevenLabsModel.html"}
{"id": "7912e1a46d0d-0", "text": "langchain.tools.brave_search.tool.BraveSearch\u00b6\nclass langchain.tools.brave_search.tool.BraveSearch[source]\u00b6\nBases: BaseTool\nTool that queries the BraveSearch.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'a search engine. useful for when you need to answer questions about current events. input should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'brave_search'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam search_wrapper: BraveSearchWrapper [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.brave_search.tool.BraveSearch.html"}
{"id": "7912e1a46d0d-1", "text": "param tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.brave_search.tool.BraveSearch.html"}
{"id": "7912e1a46d0d-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.brave_search.tool.BraveSearch.html"}
{"id": "7912e1a46d0d-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.brave_search.tool.BraveSearch.html"}
{"id": "7912e1a46d0d-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_api_key(api_key: str, search_kwargs: Optional[dict] = None, **kwargs: Any) \u2192 BraveSearch[source]\u00b6\nCreate a tool from an api key.\nParameters\napi_key \u2013 The api key to use.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.brave_search.tool.BraveSearch.html"}
{"id": "7912e1a46d0d-5", "text": "Parameters\napi_key \u2013 The api key to use.\nsearch_kwargs \u2013 Any additional kwargs to pass to the search wrapper.\n**kwargs \u2013 Any additional kwargs to pass to the tool.\nReturns\nA tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.brave_search.tool.BraveSearch.html"}
{"id": "7912e1a46d0d-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.brave_search.tool.BraveSearch.html"}
{"id": "7912e1a46d0d-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.brave_search.tool.BraveSearch.html"}
{"id": "7912e1a46d0d-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.brave_search.tool.BraveSearch.html"}
{"id": "7912e1a46d0d-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using BraveSearch\u00b6\nBrave Search", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.brave_search.tool.BraveSearch.html"}
{"id": "3db56cef3f4e-0", "text": "langchain.tools.powerbi.tool.InfoPowerBITool\u00b6\nclass langchain.tools.powerbi.tool.InfoPowerBITool[source]\u00b6\nBases: BaseTool\nTool for getting metadata about a PowerBI Dataset.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = '\\n\u00a0\u00a0\u00a0 Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.\\n\u00a0\u00a0\u00a0 Be sure that the tables actually exist by calling list_tables_powerbi first!\\n\\n\u00a0\u00a0\u00a0 Example Input: \"table1, table2, table3\"\\n\u00a0\u00a0\u00a0 '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'schema_powerbi'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam powerbi: langchain.utilities.powerbi.PowerBIDataset [Required]\u00b6\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.InfoPowerBITool.html"}
{"id": "3db56cef3f4e-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.InfoPowerBITool.html"}
{"id": "3db56cef3f4e-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.InfoPowerBITool.html"}
{"id": "3db56cef3f4e-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.InfoPowerBITool.html"}
{"id": "3db56cef3f4e-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.InfoPowerBITool.html"}
{"id": "3db56cef3f4e-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.InfoPowerBITool.html"}
{"id": "3db56cef3f4e-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.InfoPowerBITool.html"}
{"id": "3db56cef3f4e-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.InfoPowerBITool.html"}
{"id": "3db56cef3f4e-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.InfoPowerBITool.html"}
{"id": "3db56cef3f4e-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.powerbi.tool.InfoPowerBITool.html"}
{"id": "8da11fe1317e-0", "text": "langchain.tools.office365.send_event.O365SendEvent\u00b6\nclass langchain.tools.office365.send_event.O365SendEvent[source]\u00b6\nBases: O365BaseTool\nTool for sending calendar events in Office 365.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam account: Account [Optional]\u00b6\nThe account object for the Office 365 account.\nparam args_schema: Type[langchain.tools.office365.send_event.SendEventSchema] = <class 'langchain.tools.office365.send_event.SendEventSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this tool to create and send an event with the provided event fields.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'send_event'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_event.O365SendEvent.html"}
{"id": "8da11fe1317e-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_event.O365SendEvent.html"}
{"id": "8da11fe1317e-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_event.O365SendEvent.html"}
{"id": "8da11fe1317e-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_event.O365SendEvent.html"}
{"id": "8da11fe1317e-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_event.O365SendEvent.html"}
{"id": "8da11fe1317e-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_event.O365SendEvent.html"}
{"id": "8da11fe1317e-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_event.O365SendEvent.html"}
{"id": "8da11fe1317e-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_event.O365SendEvent.html"}
{"id": "8da11fe1317e-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_event.O365SendEvent.html"}
{"id": "8da11fe1317e-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.send_event.O365SendEvent.html"}
{"id": "e261759fb37e-0", "text": "langchain.tools.e2b_data_analysis.tool.UploadedFile\u00b6\nclass langchain.tools.e2b_data_analysis.tool.UploadedFile[source]\u00b6\nBases: BaseModel\nDescription of the uploaded path with its remote path.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam description: str [Required]\u00b6\nparam name: str [Required]\u00b6\nparam remote_path: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.UploadedFile.html"}
{"id": "e261759fb37e-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.UploadedFile.html"}
{"id": "e261759fb37e-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.UploadedFile.html"}
{"id": "84f046da519f-0", "text": "langchain.tools.plugin.AIPluginTool\u00b6\nclass langchain.tools.plugin.AIPluginTool[source]\u00b6\nBases: BaseTool\nTool for getting the OpenAPI spec for an AI Plugin.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_spec: str [Required]\u00b6\nparam args_schema: Type[AIPluginToolSchema] = <class 'langchain.tools.plugin.AIPluginToolSchema'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str [Required]\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam plugin: AIPlugin [Required]\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPluginTool.html"}
{"id": "84f046da519f-1", "text": "Optional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPluginTool.html"}
{"id": "84f046da519f-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPluginTool.html"}
{"id": "84f046da519f-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPluginTool.html"}
{"id": "84f046da519f-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_plugin_url(url: str) \u2192 AIPluginTool[source]\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPluginTool.html"}
{"id": "84f046da519f-5", "text": "This method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPluginTool.html"}
{"id": "84f046da519f-6", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPluginTool.html"}
{"id": "84f046da519f-7", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPluginTool.html"}
{"id": "84f046da519f-8", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPluginTool.html"}
{"id": "84f046da519f-9", "text": "These attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using AIPluginTool\u00b6\nChatGPT Plugins", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.plugin.AIPluginTool.html"}
{"id": "fae2fc13312a-0", "text": "langchain.tools.ainetwork.base.OperationType\u00b6\nclass langchain.tools.ainetwork.base.OperationType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nType of operation as enumerator.\nSET = 'SET'\u00b6\nGET = 'GET'\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.ainetwork.base.OperationType.html"}
{"id": "c0f2f1fa38aa-0", "text": "langchain.tools.requests.tool.RequestsDeleteTool\u00b6\nclass langchain.tools.requests.tool.RequestsDeleteTool[source]\u00b6\nBases: BaseRequestsTool, BaseTool\nTool for making a DELETE request to an API endpoint.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A portal to the internet. Use this when you need to make a DELETE request to a URL. Input should be a specific url, and the output will be the text response of the DELETE request.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'requests_delete'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam requests_wrapper: TextRequestsWrapper [Required]\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsDeleteTool.html"}
{"id": "c0f2f1fa38aa-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsDeleteTool.html"}
{"id": "c0f2f1fa38aa-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsDeleteTool.html"}
{"id": "c0f2f1fa38aa-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsDeleteTool.html"}
{"id": "c0f2f1fa38aa-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsDeleteTool.html"}
{"id": "c0f2f1fa38aa-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsDeleteTool.html"}
{"id": "c0f2f1fa38aa-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsDeleteTool.html"}
{"id": "c0f2f1fa38aa-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsDeleteTool.html"}
{"id": "c0f2f1fa38aa-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsDeleteTool.html"}
{"id": "c0f2f1fa38aa-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsDeleteTool.html"}
{"id": "322a0904556c-0", "text": "langchain.tools.azure_cognitive_services.utils.download_audio_from_url\u00b6\nlangchain.tools.azure_cognitive_services.utils.download_audio_from_url(audio_url: str) \u2192 str[source]\u00b6\nDownload audio from url to local.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.azure_cognitive_services.utils.download_audio_from_url.html"}
{"id": "6d2fdd0f5fb3-0", "text": "langchain.tools.office365.base.O365BaseTool\u00b6\nclass langchain.tools.office365.base.O365BaseTool[source]\u00b6\nBases: BaseTool\nBase class for the Office 365 tools.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam account: Account [Optional]\u00b6\nThe account object for the Office 365 account.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str [Required]\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.base.O365BaseTool.html"}
{"id": "6d2fdd0f5fb3-1", "text": "Optional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.base.O365BaseTool.html"}
{"id": "6d2fdd0f5fb3-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.base.O365BaseTool.html"}
{"id": "6d2fdd0f5fb3-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.base.O365BaseTool.html"}
{"id": "6d2fdd0f5fb3-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.base.O365BaseTool.html"}
{"id": "6d2fdd0f5fb3-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.base.O365BaseTool.html"}
{"id": "6d2fdd0f5fb3-6", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.base.O365BaseTool.html"}
{"id": "6d2fdd0f5fb3-7", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.base.O365BaseTool.html"}
{"id": "6d2fdd0f5fb3-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.base.O365BaseTool.html"}
{"id": "6d2fdd0f5fb3-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.office365.base.O365BaseTool.html"}
{"id": "27d7cf9f91ff-0", "text": "langchain.tools.sql_database.tool.QuerySQLDataBaseTool\u00b6\nclass langchain.tools.sql_database.tool.QuerySQLDataBaseTool[source]\u00b6\nBases: BaseSQLDatabaseTool, BaseTool\nTool for querying a SQL database.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam db: SQLDatabase [Required]\u00b6\nparam description: str = '\\n\u00a0\u00a0\u00a0 Input to this tool is a detailed and correct SQL query, output is a result from the database.\\n\u00a0\u00a0\u00a0 If the query is not correct, an error message will be returned.\\n\u00a0\u00a0\u00a0 If an error is returned, rewrite the query, check the query, and try again.\\n\u00a0\u00a0\u00a0 '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'sql_db_query'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLDataBaseTool.html"}
{"id": "27d7cf9f91ff-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLDataBaseTool.html"}
{"id": "27d7cf9f91ff-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLDataBaseTool.html"}
{"id": "27d7cf9f91ff-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLDataBaseTool.html"}
{"id": "27d7cf9f91ff-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLDataBaseTool.html"}
{"id": "27d7cf9f91ff-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLDataBaseTool.html"}
{"id": "27d7cf9f91ff-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLDataBaseTool.html"}
{"id": "27d7cf9f91ff-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLDataBaseTool.html"}
{"id": "27d7cf9f91ff-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLDataBaseTool.html"}
{"id": "27d7cf9f91ff-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.QuerySQLDataBaseTool.html"}
{"id": "39a9a20d3081-0", "text": "langchain.tools.gmail.utils.get_gmail_credentials\u00b6\nlangchain.tools.gmail.utils.get_gmail_credentials(token_file: Optional[str] = None, client_secrets_file: Optional[str] = None, scopes: Optional[List[str]] = None) \u2192 Credentials[source]\u00b6\nGet credentials.\nExamples using get_gmail_credentials\u00b6\nGmail", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.gmail.utils.get_gmail_credentials.html"}
{"id": "decd4e35edb4-0", "text": "langchain.tools.file_management.write.WriteFileInput\u00b6\nclass langchain.tools.file_management.write.WriteFileInput[source]\u00b6\nBases: BaseModel\nInput for WriteFileTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam append: bool = False\u00b6\nWhether to append to an existing file.\nparam file_path: str [Required]\u00b6\nname of file\nparam text: str [Required]\u00b6\ntext to write to file\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.write.WriteFileInput.html"}
{"id": "decd4e35edb4-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.write.WriteFileInput.html"}
{"id": "decd4e35edb4-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.write.WriteFileInput.html"}
{"id": "bc913db45efd-0", "text": "langchain.tools.memorize.tool.TrainableLLM\u00b6\nclass langchain.tools.memorize.tool.TrainableLLM(*args, **kwargs)[source]\u00b6\nMethods\n__init__(*args,\u00a0**kwargs)\natrain_unsupervised(inputs,\u00a0**kwargs)\ntrain_unsupervised(inputs,\u00a0**kwargs)\n__init__(*args, **kwargs)\u00b6\nabstract async atrain_unsupervised(inputs: Sequence[str], **kwargs: Any) \u2192 TrainResult[source]\u00b6\nabstract train_unsupervised(inputs: Sequence[str], **kwargs: Any) \u2192 TrainResult[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.memorize.tool.TrainableLLM.html"}
{"id": "c1900c190dda-0", "text": "langchain.tools.file_management.utils.get_validated_relative_path\u00b6\nlangchain.tools.file_management.utils.get_validated_relative_path(root: Path, user_path: str) \u2192 Path[source]\u00b6\nResolve a relative path, raising an error if not within the root directory.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.utils.get_validated_relative_path.html"}
{"id": "8f19ce495803-0", "text": "langchain.tools.file_management.file_search.FileSearchInput\u00b6\nclass langchain.tools.file_management.file_search.FileSearchInput[source]\u00b6\nBases: BaseModel\nInput for FileSearchTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam dir_path: str = '.'\u00b6\nSubdirectory to search in.\nparam pattern: str [Required]\u00b6\nUnix shell regex, where * matches everything.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.file_search.FileSearchInput.html"}
{"id": "8f19ce495803-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.file_search.FileSearchInput.html"}
{"id": "8f19ce495803-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.file_management.file_search.FileSearchInput.html"}
{"id": "df71aade3f5b-0", "text": "langchain.tools.playwright.navigate.NavigateTool\u00b6\nclass langchain.tools.playwright.navigate.NavigateTool[source]\u00b6\nBases: BaseBrowserTool\nTool for navigating a browser to a URL.\nSecurity Note: This tool provides code to control web-browser navigation.\nThis tool can navigate to any URL, including internal network URLs, and\nURLs exposed on the server itself.\nHowever, if exposing this tool to end-users, consider limiting network\naccess to the server that hosts the agent.\nBy default, the URL scheme has been limited to \u2018http\u2019 and \u2018https\u2019 to\nprevent navigation to local file system URLs (or other schemes).\nIf access to the local file system is required, consider creating a custom\ntool or providing a custom args_schema that allows the desired URL schemes.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Type[BaseModel] = <class 'langchain.tools.playwright.navigate.NavigateToolInput'>\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam async_browser: Optional['AsyncBrowser'] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Navigate a browser to the specified URL'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate.NavigateTool.html"}
{"id": "df71aade3f5b-1", "text": "param metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'navigate_browser'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam sync_browser: Optional['SyncBrowser'] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate.NavigateTool.html"}
{"id": "df71aade3f5b-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate.NavigateTool.html"}
{"id": "df71aade3f5b-3", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate.NavigateTool.html"}
{"id": "df71aade3f5b-4", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate.NavigateTool.html"}
{"id": "df71aade3f5b-5", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_browser(sync_browser: Optional[SyncBrowser] = None, async_browser: Optional[AsyncBrowser] = None) \u2192 BaseBrowserTool\u00b6\nInstantiate the tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate.NavigateTool.html"}
{"id": "df71aade3f5b-6", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate.NavigateTool.html"}
{"id": "df71aade3f5b-7", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate.NavigateTool.html"}
{"id": "df71aade3f5b-8", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate.NavigateTool.html"}
{"id": "df71aade3f5b-9", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate.NavigateTool.html"}
{"id": "c62312b00767-0", "text": "langchain.tools.json.tool.JsonGetValueTool\u00b6\nclass langchain.tools.json.tool.JsonGetValueTool[source]\u00b6\nBases: BaseTool\nTool for getting a value in a JSON spec.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = '\\n\u00a0\u00a0\u00a0 Can be used to see value in string format at a given path.\\n\u00a0\u00a0\u00a0 Before calling this you should be SURE that the path to this exists.\\n\u00a0\u00a0\u00a0 The input is a text representation of the path to the dict in Python syntax (e.g. data[\"key1\"][0][\"key2\"]).\\n\u00a0\u00a0\u00a0 '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'json_spec_get_value'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonGetValueTool.html"}
{"id": "c62312b00767-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam spec: JsonSpec [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonGetValueTool.html"}
{"id": "c62312b00767-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonGetValueTool.html"}
{"id": "c62312b00767-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonGetValueTool.html"}
{"id": "c62312b00767-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonGetValueTool.html"}
{"id": "c62312b00767-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonGetValueTool.html"}
{"id": "c62312b00767-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonGetValueTool.html"}
{"id": "c62312b00767-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonGetValueTool.html"}
{"id": "c62312b00767-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonGetValueTool.html"}
{"id": "c62312b00767-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.json.tool.JsonGetValueTool.html"}
{"id": "96292d775078-0", "text": "langchain.tools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool\u00b6\nclass langchain.tools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool[source]\u00b6\nBases: BaseTool\nTool that queries the Google Cloud Text to Speech API.\nIn order to set this up, follow instructions at:\nhttps://cloud.google.com/text-to-speech/docs/before-you-begin\nInitializes private fields.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Google Cloud Text-to-Speech. Useful for when you need to synthesize audio from text. It supports multiple languages, including English, German, Polish, Spanish, Italian, French, Portuguese, and Hindi. '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'google_cloud_texttospeech'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool.html"}
{"id": "96292d775078-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool.html"}
{"id": "96292d775078-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool.html"}
{"id": "96292d775078-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool.html"}
{"id": "96292d775078-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool.html"}
{"id": "96292d775078-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool.html"}
{"id": "96292d775078-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool.html"}
{"id": "96292d775078-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool.html"}
{"id": "96292d775078-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool.html"}
{"id": "96292d775078-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool.html"}
{"id": "4c2c15bfa9d9-0", "text": "langchain.tools.wikipedia.tool.WikipediaQueryRun\u00b6\nclass langchain.tools.wikipedia.tool.WikipediaQueryRun[source]\u00b6\nBases: BaseTool\nTool that searches the Wikipedia API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.wikipedia.WikipediaAPIWrapper [Required]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, facts, historical events, or other subjects. Input should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'Wikipedia'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wikipedia.tool.WikipediaQueryRun.html"}
{"id": "4c2c15bfa9d9-1", "text": "that after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wikipedia.tool.WikipediaQueryRun.html"}
{"id": "4c2c15bfa9d9-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wikipedia.tool.WikipediaQueryRun.html"}
{"id": "4c2c15bfa9d9-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wikipedia.tool.WikipediaQueryRun.html"}
{"id": "4c2c15bfa9d9-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wikipedia.tool.WikipediaQueryRun.html"}
{"id": "4c2c15bfa9d9-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wikipedia.tool.WikipediaQueryRun.html"}
{"id": "4c2c15bfa9d9-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wikipedia.tool.WikipediaQueryRun.html"}
{"id": "4c2c15bfa9d9-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wikipedia.tool.WikipediaQueryRun.html"}
{"id": "4c2c15bfa9d9-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wikipedia.tool.WikipediaQueryRun.html"}
{"id": "4c2c15bfa9d9-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using WikipediaQueryRun\u00b6\nWikipedia", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.wikipedia.tool.WikipediaQueryRun.html"}
{"id": "013ce5f7ef6f-0", "text": "langchain.tools.metaphor_search.tool.MetaphorSearchResults\u00b6\nclass langchain.tools.metaphor_search.tool.MetaphorSearchResults[source]\u00b6\nBases: BaseTool\nTool that queries the Metaphor Search API and gets back json.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.metaphor_search.MetaphorSearchAPIWrapper [Required]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around Metaphor Search. Input should be a Metaphor-optimized query. Output is a JSON array of the query results'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'metaphor_search_results_json'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.metaphor_search.tool.MetaphorSearchResults.html"}
{"id": "013ce5f7ef6f-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.metaphor_search.tool.MetaphorSearchResults.html"}
{"id": "013ce5f7ef6f-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.metaphor_search.tool.MetaphorSearchResults.html"}
{"id": "013ce5f7ef6f-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.metaphor_search.tool.MetaphorSearchResults.html"}
{"id": "013ce5f7ef6f-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.metaphor_search.tool.MetaphorSearchResults.html"}
{"id": "013ce5f7ef6f-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.metaphor_search.tool.MetaphorSearchResults.html"}
{"id": "013ce5f7ef6f-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.metaphor_search.tool.MetaphorSearchResults.html"}
{"id": "013ce5f7ef6f-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.metaphor_search.tool.MetaphorSearchResults.html"}
{"id": "013ce5f7ef6f-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.metaphor_search.tool.MetaphorSearchResults.html"}
{"id": "013ce5f7ef6f-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using MetaphorSearchResults\u00b6\nMetaphor Search", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.metaphor_search.tool.MetaphorSearchResults.html"}
{"id": "4f04ee86e810-0", "text": "langchain.tools.sql_database.tool.BaseSQLDatabaseTool\u00b6\nclass langchain.tools.sql_database.tool.BaseSQLDatabaseTool[source]\u00b6\nBases: BaseModel\nBase tool for interacting with a SQL database.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam db: langchain.utilities.sql_database.SQLDatabase [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.BaseSQLDatabaseTool.html"}
{"id": "4f04ee86e810-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.BaseSQLDatabaseTool.html"}
{"id": "4f04ee86e810-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.BaseSQLDatabaseTool.html"}
{"id": "c5c8694e4e97-0", "text": "langchain.tools.playwright.utils.run_async\u00b6\nlangchain.tools.playwright.utils.run_async(coro: Coroutine[Any, Any, T]) \u2192 T[source]\u00b6\nRun an async coroutine.\nParameters\ncoro \u2013 The coroutine to run. Coroutine[Any, Any, T]\nReturns\nThe result of the coroutine.\nReturn type\nT", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.utils.run_async.html"}
{"id": "94bd8482cc59-0", "text": "langchain.tools.render.format_tool_to_openai_tool\u00b6\nlangchain.tools.render.format_tool_to_openai_tool(tool: BaseTool) \u2192 ToolDescription[source]\u00b6\nFormat tool into the OpenAI function API.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.render.format_tool_to_openai_tool.html"}
{"id": "726313636b8e-0", "text": "langchain.tools.requests.tool.RequestsPutTool\u00b6\nclass langchain.tools.requests.tool.RequestsPutTool[source]\u00b6\nBases: BaseRequestsTool, BaseTool\nTool for making a PUT request to an API endpoint.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this when you want to PUT to a website.\\n\u00a0\u00a0\u00a0 Input should be a json string with two keys: \"url\" and \"data\".\\n\u00a0\u00a0\u00a0 The value of \"url\" should be a string, and the value of \"data\" should be a dictionary of \\n\u00a0\u00a0\u00a0 key-value pairs you want to PUT to the url.\\n\u00a0\u00a0\u00a0 Be careful to always use double quotes for strings in the json string.\\n\u00a0\u00a0\u00a0 The output will be the text response of the PUT request.\\n\u00a0\u00a0\u00a0 '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPutTool.html"}
{"id": "726313636b8e-1", "text": "You can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'requests_put'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam requests_wrapper: TextRequestsWrapper [Required]\u00b6\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPutTool.html"}
{"id": "726313636b8e-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPutTool.html"}
{"id": "726313636b8e-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPutTool.html"}
{"id": "726313636b8e-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPutTool.html"}
{"id": "726313636b8e-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPutTool.html"}
{"id": "726313636b8e-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPutTool.html"}
{"id": "726313636b8e-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPutTool.html"}
{"id": "726313636b8e-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPutTool.html"}
{"id": "726313636b8e-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.requests.tool.RequestsPutTool.html"}
{"id": "262234b6bba7-0", "text": "langchain.tools.playwright.navigate.NavigateToolInput\u00b6\nclass langchain.tools.playwright.navigate.NavigateToolInput[source]\u00b6\nBases: BaseModel\nInput for NavigateToolInput.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam url: str [Required]\u00b6\nurl to navigate to\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate.NavigateToolInput.html"}
{"id": "262234b6bba7-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate.NavigateToolInput.html"}
{"id": "262234b6bba7-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.playwright.navigate.NavigateToolInput.html"}
{"id": "b354c468c608-0", "text": "langchain.tools.spark_sql.tool.BaseSparkSQLTool\u00b6\nclass langchain.tools.spark_sql.tool.BaseSparkSQLTool[source]\u00b6\nBases: BaseModel\nBase tool for interacting with Spark SQL.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam db: langchain.utilities.spark_sql.SparkSQL [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.BaseSparkSQLTool.html"}
{"id": "b354c468c608-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.BaseSparkSQLTool.html"}
{"id": "b354c468c608-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.spark_sql.tool.BaseSparkSQLTool.html"}
{"id": "8e6135917686-0", "text": "langchain.tools.sql_database.tool.InfoSQLDatabaseTool\u00b6\nclass langchain.tools.sql_database.tool.InfoSQLDatabaseTool[source]\u00b6\nBases: BaseSQLDatabaseTool, BaseTool\nTool for getting metadata about a SQL database.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam db: SQLDatabase [Required]\u00b6\nparam description: str = '\\n\u00a0\u00a0\u00a0 Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.\u00a0\u00a0\u00a0 \\n\\n\u00a0\u00a0\u00a0 Example Input: \"table1, table2, table3\"\\n\u00a0\u00a0\u00a0 '\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'sql_db_schema'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.InfoSQLDatabaseTool.html"}
{"id": "8e6135917686-1", "text": "Whether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.InfoSQLDatabaseTool.html"}
{"id": "8e6135917686-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.InfoSQLDatabaseTool.html"}
{"id": "8e6135917686-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.InfoSQLDatabaseTool.html"}
{"id": "8e6135917686-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.InfoSQLDatabaseTool.html"}
{"id": "8e6135917686-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.InfoSQLDatabaseTool.html"}
{"id": "8e6135917686-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.InfoSQLDatabaseTool.html"}
{"id": "8e6135917686-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.InfoSQLDatabaseTool.html"}
{"id": "8e6135917686-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.InfoSQLDatabaseTool.html"}
{"id": "8e6135917686-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.sql_database.tool.InfoSQLDatabaseTool.html"}
{"id": "70c0de522e7f-0", "text": "langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisToolArguments\u00b6\nclass langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisToolArguments[source]\u00b6\nBases: BaseModel\nArguments for the E2BDataAnalysisTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam python_code: str [Required]\u00b6\nThe python script to be evaluated. The contents will be in main.py. It should not be in markdown format.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisToolArguments.html"}
{"id": "70c0de522e7f-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisToolArguments.html"}
{"id": "70c0de522e7f-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.e2b_data_analysis.tool.E2BDataAnalysisToolArguments.html"}
{"id": "427f1b438eda-0", "text": "langchain.tools.multion.close_session.CloseSessionSchema\u00b6\nclass langchain.tools.multion.close_session.CloseSessionSchema[source]\u00b6\nBases: BaseModel\nInput for UpdateSessionTool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam sessionId: str [Required]\u00b6\nThe sessionId, received from one of the createSessions \nor updateSessions run before\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.close_session.CloseSessionSchema.html"}
{"id": "427f1b438eda-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.close_session.CloseSessionSchema.html"}
{"id": "427f1b438eda-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.multion.close_session.CloseSessionSchema.html"}
{"id": "1dab6f19daa6-0", "text": "langchain_experimental.tools.python.tool.sanitize_input\u00b6\nlangchain_experimental.tools.python.tool.sanitize_input(query: str) \u2192 str[source]\u00b6\nSanitize input to the python REPL.\nRemove whitespace, backtick & python (if llm mistakes python console as terminal)\nParameters\nquery \u2013 The query to sanitize\nReturns\nThe sanitized query\nReturn type\nstr", "source": "lang/api.python.langchain.com/en/latest/tools/langchain_experimental.tools.python.tool.sanitize_input.html"}
{"id": "bcdcad952c8a-0", "text": "langchain.tools.searchapi.tool.SearchAPIRun\u00b6\nclass langchain.tools.searchapi.tool.SearchAPIRun[source]\u00b6\nBases: BaseTool\nTool that queries the SearchApi.io search API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_wrapper: langchain.utilities.searchapi.SearchApiAPIWrapper [Required]\u00b6\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Google search API provided by SearchApi.io.This tool is handy when you need to answer questions about current events.Input should be a search query.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'searchapi'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIRun.html"}
{"id": "bcdcad952c8a-1", "text": "that after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIRun.html"}
{"id": "bcdcad952c8a-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIRun.html"}
{"id": "bcdcad952c8a-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIRun.html"}
{"id": "bcdcad952c8a-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIRun.html"}
{"id": "bcdcad952c8a-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIRun.html"}
{"id": "bcdcad952c8a-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIRun.html"}
{"id": "bcdcad952c8a-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIRun.html"}
{"id": "bcdcad952c8a-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIRun.html"}
{"id": "bcdcad952c8a-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tools/langchain.tools.searchapi.tool.SearchAPIRun.html"}
{"id": "077b2f0d982e-0", "text": "langchain.indexes.vectorstore.VectorStoreIndexWrapper\u00b6\nclass langchain.indexes.vectorstore.VectorStoreIndexWrapper[source]\u00b6\nBases: BaseModel\nWrapper around a vectorstore for easy access.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam vectorstore: langchain.schema.vectorstore.VectorStore [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.vectorstore.VectorStoreIndexWrapper.html"}
{"id": "077b2f0d982e-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.vectorstore.VectorStoreIndexWrapper.html"}
{"id": "077b2f0d982e-2", "text": "query(question: str, llm: Optional[BaseLanguageModel] = None, retriever_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nQuery the vectorstore.\nquery_with_sources(question: str, llm: Optional[BaseLanguageModel] = None, retriever_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 dict[source]\u00b6\nQuery the vectorstore and get back sources.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.vectorstore.VectorStoreIndexWrapper.html"}
{"id": "d0fe60e8f9a4-0", "text": "langchain.indexes.base.RecordManager\u00b6\nclass langchain.indexes.base.RecordManager(namespace: str)[source]\u00b6\nAn abstract base class representing the interface for a record manager.\nInitialize the record manager.\nParameters\nnamespace (str) \u2013 The namespace for the record manager.\nMethods\n__init__(namespace)\nInitialize the record manager.\nacreate_schema()\nCreate the database schema for the record manager.\nadelete_keys(keys)\nDelete specified records from the database.\naexists(keys)\nCheck if the provided keys exist in the database.\naget_time()\nGet the current server time as a high resolution timestamp!\nalist_keys(*[,\u00a0before,\u00a0after,\u00a0group_ids,\u00a0limit])\nList records in the database based on the provided filters.\naupdate(keys,\u00a0*[,\u00a0group_ids,\u00a0time_at_least])\nUpsert records into the database.\ncreate_schema()\nCreate the database schema for the record manager.\ndelete_keys(keys)\nDelete specified records from the database.\nexists(keys)\nCheck if the provided keys exist in the database.\nget_time()\nGet the current server time as a high resolution timestamp!\nlist_keys(*[,\u00a0before,\u00a0after,\u00a0group_ids,\u00a0limit])\nList records in the database based on the provided filters.\nupdate(keys,\u00a0*[,\u00a0group_ids,\u00a0time_at_least])\nUpsert records into the database.\n__init__(namespace: str) \u2192 None[source]\u00b6\nInitialize the record manager.\nParameters\nnamespace (str) \u2013 The namespace for the record manager.\nabstract async acreate_schema() \u2192 None[source]\u00b6\nCreate the database schema for the record manager.\nabstract async adelete_keys(keys: Sequence[str]) \u2192 None[source]\u00b6\nDelete specified records from the database.\nParameters\nkeys \u2013 A list of keys to delete.", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.base.RecordManager.html"}
{"id": "d0fe60e8f9a4-1", "text": "Delete specified records from the database.\nParameters\nkeys \u2013 A list of keys to delete.\nabstract async aexists(keys: Sequence[str]) \u2192 List[bool][source]\u00b6\nCheck if the provided keys exist in the database.\nParameters\nkeys \u2013 A list of keys to check.\nReturns\nA list of boolean values indicating the existence of each key.\nabstract async aget_time() \u2192 float[source]\u00b6\nGet the current server time as a high resolution timestamp!\nIt\u2019s important to get this from the server to ensure a monotonic clock,\notherwise there may be data loss when cleaning up old documents!\nReturns\nThe current server time as a float timestamp.\nabstract async alist_keys(*, before: Optional[float] = None, after: Optional[float] = None, group_ids: Optional[Sequence[str]] = None, limit: Optional[int] = None) \u2192 List[str][source]\u00b6\nList records in the database based on the provided filters.\nParameters\nbefore \u2013 Filter to list records updated before this time.\nafter \u2013 Filter to list records updated after this time.\ngroup_ids \u2013 Filter to list records with specific group IDs.\nlimit \u2013 optional limit on the number of records to return.\nReturns\nA list of keys for the matching records.\nabstract async aupdate(keys: Sequence[str], *, group_ids: Optional[Sequence[Optional[str]]] = None, time_at_least: Optional[float] = None) \u2192 None[source]\u00b6\nUpsert records into the database.\nParameters\nkeys \u2013 A list of record keys to upsert.\ngroup_ids \u2013 A list of group IDs corresponding to the keys.\ntime_at_least \u2013 if provided, updates should only happen if the\nupdated_at field is at least this time.\nRaises\nValueError \u2013 If the length of keys doesn\u2019t match the length of group_ids.\nabstract create_schema() \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.base.RecordManager.html"}
{"id": "d0fe60e8f9a4-2", "text": "abstract create_schema() \u2192 None[source]\u00b6\nCreate the database schema for the record manager.\nabstract delete_keys(keys: Sequence[str]) \u2192 None[source]\u00b6\nDelete specified records from the database.\nParameters\nkeys \u2013 A list of keys to delete.\nabstract exists(keys: Sequence[str]) \u2192 List[bool][source]\u00b6\nCheck if the provided keys exist in the database.\nParameters\nkeys \u2013 A list of keys to check.\nReturns\nA list of boolean values indicating the existence of each key.\nabstract get_time() \u2192 float[source]\u00b6\nGet the current server time as a high resolution timestamp!\nIt\u2019s important to get this from the server to ensure a monotonic clock,\notherwise there may be data loss when cleaning up old documents!\nReturns\nThe current server time as a float timestamp.\nabstract list_keys(*, before: Optional[float] = None, after: Optional[float] = None, group_ids: Optional[Sequence[str]] = None, limit: Optional[int] = None) \u2192 List[str][source]\u00b6\nList records in the database based on the provided filters.\nParameters\nbefore \u2013 Filter to list records updated before this time.\nafter \u2013 Filter to list records updated after this time.\ngroup_ids \u2013 Filter to list records with specific group IDs.\nlimit \u2013 optional limit on the number of records to return.\nReturns\nA list of keys for the matching records.\nabstract update(keys: Sequence[str], *, group_ids: Optional[Sequence[Optional[str]]] = None, time_at_least: Optional[float] = None) \u2192 None[source]\u00b6\nUpsert records into the database.\nParameters\nkeys \u2013 A list of record keys to upsert.\ngroup_ids \u2013 A list of group IDs corresponding to the keys.\ntime_at_least \u2013 if provided, updates should only happen if the\nupdated_at field is at least this time.\nRaises", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.base.RecordManager.html"}
{"id": "d0fe60e8f9a4-3", "text": "updated_at field is at least this time.\nRaises\nValueError \u2013 If the length of keys doesn\u2019t match the length of group_ids.", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.base.RecordManager.html"}
{"id": "c8a5e51580e1-0", "text": "langchain.indexes.vectorstore.VectorstoreIndexCreator\u00b6\nclass langchain.indexes.vectorstore.VectorstoreIndexCreator[source]\u00b6\nBases: BaseModel\nLogic for creating indexes.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam embedding: langchain.schema.embeddings.Embeddings [Optional]\u00b6\nparam text_splitter: langchain.text_splitter.TextSplitter [Optional]\u00b6\nparam vectorstore_cls: Type[langchain.schema.vectorstore.VectorStore] = <class 'langchain.vectorstores.chroma.Chroma'>\u00b6\nparam vectorstore_kwargs: dict [Optional]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.vectorstore.VectorstoreIndexCreator.html"}
{"id": "c8a5e51580e1-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nfrom_documents(documents: List[Document]) \u2192 VectorStoreIndexWrapper[source]\u00b6\nCreate a vectorstore index from documents.\nfrom_loaders(loaders: List[BaseLoader]) \u2192 VectorStoreIndexWrapper[source]\u00b6\nCreate a vectorstore index from loaders.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.vectorstore.VectorstoreIndexCreator.html"}
{"id": "c8a5e51580e1-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using VectorstoreIndexCreator\u00b6\nApify\nHuggingFace dataset\nSpreedly\nImage captions\nFigma\nApify Dataset\nIugu\nStripe\nModern Treasury\nQuestion Answering\nMultiple Retrieval Sources", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.vectorstore.VectorstoreIndexCreator.html"}
{"id": "67206cfe33d7-0", "text": "langchain.indexes.graph.GraphIndexCreator\u00b6\nclass langchain.indexes.graph.GraphIndexCreator[source]\u00b6\nBases: BaseModel\nFunctionality to create graph index.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam graph_type: Type[langchain.graphs.networkx_graph.NetworkxEntityGraph] = <class 'langchain.graphs.networkx_graph.NetworkxEntityGraph'>\u00b6\nparam llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.graph.GraphIndexCreator.html"}
{"id": "67206cfe33d7-1", "text": "param llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nasync afrom_text(text: str, prompt: BasePromptTemplate = PromptTemplate(input_variables=['text'], template=\"You are a networked intelligence helping a human track knowledge triples about all relevant people, things, concepts, etc. and integrating them with your knowledge stored within your weights as well as that stored in a knowledge graph. Extract all of the knowledge triples from the text. A knowledge triple is a clause that contains a subject, a predicate, and an object. The subject is the entity being described, the predicate is the property of the subject that is being described, and the object is the value of the property.\\n\\nEXAMPLE\\nIt's a state in the US. It's also the number 1 producer of gold in the US.\\n\\nOutput: (Nevada, is a, state)<|>(Nevada, is in, US)<|>(Nevada, is the number 1 producer of, gold)\\nEND OF EXAMPLE\\n\\nEXAMPLE\\nI'm going to the store.\\n\\nOutput: NONE\\nEND OF EXAMPLE\\n\\nEXAMPLE\\nOh huh. I know Descartes likes to drive antique scooters and play the mandolin.\\nOutput: (Descartes, likes to drive, antique scooters)<|>(Descartes, plays, mandolin)\\nEND OF EXAMPLE\\n\\nEXAMPLE\\n{text}Output:\")) \u2192 NetworkxEntityGraph[source]\u00b6\nCreate graph index from text asynchronously.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.graph.GraphIndexCreator.html"}
{"id": "67206cfe33d7-2", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.graph.GraphIndexCreator.html"}
{"id": "67206cfe33d7-3", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\nfrom_text(text: str, prompt: BasePromptTemplate = PromptTemplate(input_variables=['text'], template=\"You are a networked intelligence helping a human track knowledge triples about all relevant people, things, concepts, etc. and integrating them with your knowledge stored within your weights as well as that stored in a knowledge graph. Extract all of the knowledge triples from the text. A knowledge triple is a clause that contains a subject, a predicate, and an object. The subject is the entity being described, the predicate is the property of the subject that is being described, and the object is the value of the property.\\n\\nEXAMPLE\\nIt's a state in the US. It's also the number 1 producer of gold in the US.\\n\\nOutput: (Nevada, is a, state)<|>(Nevada, is in, US)<|>(Nevada, is the number 1 producer of, gold)\\nEND OF EXAMPLE\\n\\nEXAMPLE\\nI'm going to the store.\\n\\nOutput: NONE\\nEND OF EXAMPLE\\n\\nEXAMPLE\\nOh huh. I know Descartes likes to drive antique scooters and play the mandolin.\\nOutput: (Descartes, likes to drive, antique scooters)<|>(Descartes, plays, mandolin)\\nEND OF EXAMPLE\\n\\nEXAMPLE\\n{text}Output:\")) \u2192 NetworkxEntityGraph[source]\u00b6\nCreate graph index from text.", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.graph.GraphIndexCreator.html"}
{"id": "67206cfe33d7-4", "text": "Create graph index from text.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using GraphIndexCreator\u00b6\nGraph QA", "source": "lang/api.python.langchain.com/en/latest/indexes/langchain.indexes.graph.GraphIndexCreator.html"}
{"id": "f1f758f021c4-0", "text": "langchain_experimental.sql.vector_sql.get_result_from_sqldb\u00b6\nlangchain_experimental.sql.vector_sql.get_result_from_sqldb(db: SQLDatabase, cmd: str) \u2192 Sequence[Dict[str, Any]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.get_result_from_sqldb.html"}
{"id": "1e6a5f11d020-0", "text": "langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser\u00b6\nclass langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser[source]\u00b6\nBases: VectorSQLOutputParser\nBased on VectorSQLOutputParser\nIt also modify the SQL to get all columns\nparam distance_func_name: str = 'distance'\u00b6\nDistance name for Vector SQL\nparam model: langchain.schema.embeddings.Embeddings [Required]\u00b6\nEmbedding model to extract embedding for entity\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html"}
{"id": "1e6a5f11d020-1", "text": "Parameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html"}
{"id": "1e6a5f11d020-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html"}
{"id": "1e6a5f11d020-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_embeddings(model: Embeddings, distance_func_name: str = 'distance', **kwargs: Any) \u2192 BaseOutputParser\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html"}
{"id": "1e6a5f11d020-4", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html"}
{"id": "1e6a5f11d020-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 str[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html"}
{"id": "1e6a5f11d020-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html"}
{"id": "1e6a5f11d020-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html"}
{"id": "1e6a5f11d020-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html"}
{"id": "1e6a5f11d020-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html"}
{"id": "5f24cde4db86-0", "text": "langchain_experimental.sql.base.SQLDatabaseSequentialChain\u00b6\nclass langchain_experimental.sql.base.SQLDatabaseSequentialChain[source]\u00b6\nBases: Chain\nChain for querying SQL database that is a sequential chain.\nThe chain is as follows:\n1. Based on the query, determine which tables to use.\n2. Based on those tables, call the normal SQL database chain.\nThis is useful in cases where the number of tables in the database is large.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam decider_chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-1", "text": "You can use these to eg identify a specific instance of a chain with its use case.\nparam return_intermediate_steps: bool = False\u00b6\nparam sql_chain: SQLDatabaseChain [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-2", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-3", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-4", "text": "method expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-8", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, db: SQLDatabase, query_prompt: BasePromptTemplate = PromptTemplate(input_variables=['dialect', 'input', 'table_info', 'top_k'], template='Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer. Unless the user specifies in his question a specific number of examples he wishes to obtain, always limit your query to at most {top_k} results. You can order the results by a relevant column to return the most interesting examples in the database.\\n\\nNever query for all the columns from a specific table, only ask for a the few relevant columns given the question.\\n\\nPay attention to use only the column names that you can see in the schema description. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.\\n\\nUse the following format:\\n\\nQuestion: Question here\\nSQLQuery: SQL Query to run\\nSQLResult: Result of the SQLQuery\\nAnswer: Final answer here\\n\\nOnly use the following tables:\\n{table_info}\\n\\nQuestion: {input}'), decider_prompt: BasePromptTemplate = PromptTemplate(input_variables=['query', 'table_names'], output_parser=CommaSeparatedListOutputParser(), template='Given the below input question and list of potential tables, output a comma separated list of the table names that may be necessary to answer this question.\\n\\nQuestion: {query}\\n\\nTable Names: {table_names}\\n\\nRelevant Table Names:'), **kwargs: Any) \u2192 SQLDatabaseSequentialChain[source]\u00b6\nLoad the necessary chains.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-9", "text": "Load the necessary chains.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-10", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-11", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-12", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-13", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-14", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "5f24cde4db86-15", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html"}
{"id": "46243848575f-0", "text": "langchain_experimental.sql.vector_sql.VectorSQLOutputParser\u00b6\nclass langchain_experimental.sql.vector_sql.VectorSQLOutputParser[source]\u00b6\nBases: BaseOutputParser[str]\nOutput Parser for Vector SQL\n1. finds for NeuralArray() and replace it with the embedding\n2. finds for DISTANCE() and replace it with the distance name in backend SQL\nparam distance_func_name: str = 'distance'\u00b6\nDistance name for Vector SQL\nparam model: langchain.schema.embeddings.Embeddings [Required]\u00b6\nEmbedding model to extract embedding for entity\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html"}
{"id": "46243848575f-1", "text": "Parse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html"}
{"id": "46243848575f-2", "text": "Subclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html"}
{"id": "46243848575f-3", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_embeddings(model: Embeddings, distance_func_name: str = 'distance', **kwargs: Any) \u2192 BaseOutputParser[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html"}
{"id": "46243848575f-4", "text": "classmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html"}
{"id": "46243848575f-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 str[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html"}
{"id": "46243848575f-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html"}
{"id": "46243848575f-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html"}
{"id": "46243848575f-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html"}
{"id": "46243848575f-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html"}
{"id": "9c5748df24ea-0", "text": "langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain\u00b6\nclass langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain[source]\u00b6\nBases: SQLDatabaseChain\nChain for interacting with Vector SQL Database.\nExample\nfrom langchain_experimental.sql import SQLDatabaseChain\nfrom langchain.llms import OpenAI, SQLDatabase, OpenAIEmbeddings\ndb = SQLDatabase(...)\ndb_chain = VectorSQLDatabaseChain.from_llm(OpenAI(), db, OpenAIEmbeddings())\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include the permissions this chain needs.\nFailure to do so may result in data corruption or loss, since this chain may\nattempt commands like DROP TABLE or INSERT if appropriately prompted.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this chain.\nThis issue shows an example negative outcome if these steps are not taken:\nhttps://github.com/langchain-ai/langchain/issues/5923\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam database: SQLDatabase [Required]\u00b6\nSQL Database to connect to.\nparam llm: Optional[BaseLanguageModel] = None\u00b6\n[Deprecated] LLM wrapper to use.\nparam llm_chain: LLMChain [Required]\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-1", "text": "param llm_chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam native_format: bool = False\u00b6\nIf return_direct, controls whether to return in python native format\nparam prompt: Optional[BasePromptTemplate] = None\u00b6\n[Deprecated] Prompt to use to translate natural language to SQL.\nparam query_checker_prompt: Optional[BasePromptTemplate] = None\u00b6\nThe prompt template that should be used by the query checker\nparam return_direct: bool = False\u00b6\nWhether or not to return the result of querying the SQL table directly.\nparam return_intermediate_steps: bool = False\u00b6\nWhether or not to return the intermediate steps along with the final answer.\nparam return_sql: bool = False\u00b6\nWill return sql-command directly without executing it\nparam sql_cmd_parser: VectorSQLOutputParser [Required]\u00b6\nParser for Vector SQL\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-2", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam top_k: int = 5\u00b6\nNumber of results to return from the query\nparam use_query_checker: bool = False\u00b6\nWhether or not the query checker tool should be used to attempt\nto fix the initial SQL from the LLM.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-3", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-4", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-5", "text": "with all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-6", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-7", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-8", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, db: SQLDatabase, prompt: Optional[BasePromptTemplate] = None, sql_cmd_parser: Optional[VectorSQLOutputParser] = None, **kwargs: Any) \u2192 VectorSQLDatabaseChain[source]\u00b6\nCreate a SQLDatabaseChain from an LLM and a database connection.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include the permissions this chain needs.\nFailure to do so may result in data corruption or loss, since this chain may\nattempt commands like DROP TABLE or INSERT if appropriately prompted.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this chain.\nThis issue shows an example negative outcome if these steps are not taken:\nhttps://github.com/langchain-ai/langchain/issues/5923\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-9", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-10", "text": "for more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-11", "text": "Validate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-12", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-13", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-14", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "9c5748df24ea-15", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html"}
{"id": "eaa5aada98a7-0", "text": "langchain_experimental.sql.base.SQLDatabaseChain\u00b6\nclass langchain_experimental.sql.base.SQLDatabaseChain[source]\u00b6\nBases: Chain\nChain for interacting with SQL Database.\nExample\nfrom langchain_experimental.sql import SQLDatabaseChain\nfrom langchain.llms import OpenAI, SQLDatabase\ndb = SQLDatabase(...)\ndb_chain = SQLDatabaseChain.from_llm(OpenAI(), db)\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include the permissions this chain needs.\nFailure to do so may result in data corruption or loss, since this chain may\nattempt commands like DROP TABLE or INSERT if appropriately prompted.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this chain.\nThis issue shows an example negative outcome if these steps are not taken:\nhttps://github.com/langchain-ai/langchain/issues/5923\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam database: SQLDatabase [Required]\u00b6\nSQL Database to connect to.\nparam llm: Optional[BaseLanguageModel] = None\u00b6\n[Deprecated] LLM wrapper to use.\nparam llm_chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-1", "text": "param memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam prompt: Optional[BasePromptTemplate] = None\u00b6\n[Deprecated] Prompt to use to translate natural language to SQL.\nparam query_checker_prompt: Optional[BasePromptTemplate] = None\u00b6\nThe prompt template that should be used by the query checker\nparam return_direct: bool = False\u00b6\nWhether or not to return the result of querying the SQL table directly.\nparam return_intermediate_steps: bool = False\u00b6\nWhether or not to return the intermediate steps along with the final answer.\nparam return_sql: bool = False\u00b6\nWill return sql-command directly without executing it\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam top_k: int = 5\u00b6\nNumber of results to return from the query\nparam use_query_checker: bool = False\u00b6\nWhether or not the query checker tool should be used to attempt\nto fix the initial SQL from the LLM.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-2", "text": "to fix the initial SQL from the LLM.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-3", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-4", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-5", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-6", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-7", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-8", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, db: SQLDatabase, prompt: Optional[BasePromptTemplate] = None, **kwargs: Any) \u2192 SQLDatabaseChain[source]\u00b6\nCreate a SQLDatabaseChain from an LLM and a database connection.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include the permissions this chain needs.\nFailure to do so may result in data corruption or loss, since this chain may\nattempt commands like DROP TABLE or INSERT if appropriately prompted.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this chain.\nThis issue shows an example negative outcome if these steps are not taken:\nhttps://github.com/langchain-ai/langchain/issues/5923\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-9", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-10", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-11", "text": "memory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-12", "text": "context = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-13", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "eaa5aada98a7-14", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html"}
{"id": "6243b12ca803-0", "text": "langchain_experimental.tot.thought_generation.ProposePromptStrategy\u00b6\nclass langchain_experimental.tot.thought_generation.ProposePromptStrategy[source]\u00b6\nBases: BaseThoughtGenerationStrategy\nPropose thoughts sequentially using a \u201cpropose prompt\u201d.\nThis strategy works better when the thought space is more constrained, such\nas when each thought is just a word or a line. Proposing different thoughts\nin the same prompt completion helps to avoid duplication.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam c: int = 3\u00b6\nThe number of children thoughts to propose at each step.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-1", "text": "Optional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_key: str = 'text'\u00b6\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: langchain.schema.prompt_template.BasePromptTemplate = PromptTemplate(input_variables=['n', 'problem_description', 'thoughts'], output_parser=JSONListOutputParser(), template='You are an intelligent agent that is generating thoughts in a tree of\\nthoughts setting.\\n\\nThe output should be a markdown code snippet formatted as a JSON list of\\nstrings, including the leading and trailing \"```json\" and \"```\":\\n\\n```json\\n[\\n\u00a0\u00a0\u00a0 \"<thought-1>\",\\n\u00a0\u00a0\u00a0 \"<thought-2>\",\\n\u00a0\u00a0\u00a0 \"<thought-3>\"\\n]\\n```\\n\\nPROBLEM\\n\\n{{ problem_description }}\\n\\n{% if thoughts %}\\nVALID THOUGHTS\\n\\n{% for thought in thoughts %}\\n{{ thought }}\\n{% endfor %}\\n\\nPossible next {{ n }} valid thoughts based on the last valid thought:\\n{% else %}\\n\\nPossible next {{ n }} valid thoughts based on the PROBLEM:\\n{%- endif -%}', template_format='jinja2')\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-2", "text": "Optional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tot_memory: Dict[Tuple[str, ...], List[str]] [Optional]\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-3", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-4", "text": "Asynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-5", "text": "Subclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-6", "text": "The main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-7", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-8", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-9", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-10", "text": "classmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-11", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nnext_thought(problem_description: str, thoughts_path: Tuple[str, ...] = (), **kwargs: Any) \u2192 str[source]\u00b6\nGenerate the next thought given the problem description and the thoughts\ngenerated so far.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-12", "text": "predict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-13", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-14", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-15", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "6243b12ca803-16", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.ProposePromptStrategy.html"}
{"id": "d6eedc0502c1-0", "text": "langchain_experimental.tot.prompts.JSONListOutputParser\u00b6\nclass langchain_experimental.tot.prompts.JSONListOutputParser[source]\u00b6\nBases: BaseOutputParser\nClass to parse the output of a PROPOSE_PROMPT response.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.JSONListOutputParser.html"}
{"id": "d6eedc0502c1-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.JSONListOutputParser.html"}
{"id": "d6eedc0502c1-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.JSONListOutputParser.html"}
{"id": "d6eedc0502c1-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.JSONListOutputParser.html"}
{"id": "d6eedc0502c1-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.JSONListOutputParser.html"}
{"id": "d6eedc0502c1-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 List[str][source]\u00b6\nParse the output of an LLM call.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.JSONListOutputParser.html"}
{"id": "d6eedc0502c1-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.JSONListOutputParser.html"}
{"id": "d6eedc0502c1-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.JSONListOutputParser.html"}
{"id": "d6eedc0502c1-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.JSONListOutputParser.html"}
{"id": "5ae854727651-0", "text": "langchain_experimental.tot.controller.ToTController\u00b6\nclass langchain_experimental.tot.controller.ToTController(c: int = 3)[source]\u00b6\nTree of Thought (ToT) controller.\nThis is a version of a ToT controller, dubbed in the paper as a \u201cSimple\nController\u201d.\nIt has one parameter c which is the number of children to explore for each\nthought.\nInitialize the controller.\nParameters\nc \u2013 The number of children to explore at each node.\nMethods\n__init__([c])\nInitialize the controller.\n__init__(c: int = 3)[source]\u00b6\nInitialize the controller.\nParameters\nc \u2013 The number of children to explore at each node.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.controller.ToTController.html"}
{"id": "bbfca53a6a26-0", "text": "langchain_experimental.tot.memory.ToTDFSMemory\u00b6\nclass langchain_experimental.tot.memory.ToTDFSMemory(stack: Optional[List[Thought]] = None)[source]\u00b6\nMemory for the Tree of Thought (ToT) chain. Implemented as a stack of\nthoughts. This allows for a depth first search (DFS) of the ToT.\nAttributes\nlevel\nReturn the current level of the stack.\nMethods\n__init__([stack])\ncurrent_path()\nReturn the thoughts path.\npop([n])\nPop the top n elements of the stack and return the last one.\nstore(node)\nAdd a node on the top of the stack.\ntop()\nGet the top of the stack without popping it.\ntop_parent()\nGet the parent of the top of the stack without popping it.\n__init__(stack: Optional[List[Thought]] = None)[source]\u00b6\ncurrent_path() \u2192 List[Thought][source]\u00b6\nReturn the thoughts path.\npop(n: int = 1) \u2192 Optional[Thought][source]\u00b6\nPop the top n elements of the stack and return the last one.\nstore(node: Thought) \u2192 None[source]\u00b6\nAdd a node on the top of the stack.\ntop() \u2192 Optional[Thought][source]\u00b6\nGet the top of the stack without popping it.\ntop_parent() \u2192 Optional[Thought][source]\u00b6\nGet the parent of the top of the stack without popping it.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.memory.ToTDFSMemory.html"}
{"id": "6b38c496bf04-0", "text": "langchain_experimental.tot.thought_generation.SampleCoTStrategy\u00b6\nclass langchain_experimental.tot.thought_generation.SampleCoTStrategy[source]\u00b6\nBases: BaseThoughtGenerationStrategy\nSample thoughts from a Chain-of-Thought (CoT) prompt.\nThis strategy works better when the thought space is rich, such as when each\nthought is a paragraph. Independent and identically distributed samples\nlead to diversity, which helps to avoid repetition.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam c: int = 3\u00b6\nThe number of children thoughts to propose at each step.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-1", "text": "Optional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_key: str = 'text'\u00b6\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: langchain.schema.prompt_template.BasePromptTemplate = PromptTemplate(input_variables=['problem_description', 'thoughts'], template=\"You are an intelligent agent that is generating one thought at a time in\\na tree of thoughts setting.\\n\\nPROBLEM \\n\\n{{problem_description}}\\n\\n{% if thoughts %}\\nTHOUGHTS\\n\\n{% for thought in thoughts %}\\n{{ thought }}\\n{% endfor %}\\n{% endif %}\\n\\nLet's think step by step.\", template_format='jinja2')\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-2", "text": "accessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-3", "text": "Utilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-4", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-5", "text": "Format prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-6", "text": "**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-7", "text": "step, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-8", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-9", "text": "Create LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-10", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nnext_thought(problem_description: str, thoughts_path: Tuple[str, ...] = (), **kwargs: Any) \u2192 str[source]\u00b6\nGenerate the next thought given the problem description and the thoughts\ngenerated so far.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-11", "text": "Generate the next thought given the problem description and the thoughts\ngenerated so far.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-12", "text": "Validate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-13", "text": "Example\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-14", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-15", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "6b38c496bf04-16", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.SampleCoTStrategy.html"}
{"id": "0278d5fa14f0-0", "text": "langchain_experimental.tot.base.ToTChain\u00b6\nclass langchain_experimental.tot.base.ToTChain[source]\u00b6\nBases: Chain\nA Chain implementing the Tree of Thought (ToT).\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam c: int = 3\u00b6\nThe number of children to explore at each node\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam checker: ToTChecker [Required]\u00b6\nToT Checker to use.\nparam k: int = 10\u00b6\nThe maximum number of conversation rounds\nparam llm: BaseLanguageModel [Required]\u00b6\nLanguage model to use. It must be set to produce different variations for\nthe same prompt.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tot_controller: ToTController = <langchain_experimental.tot.controller.ToTController object>\u00b6\nparam tot_memory: ToTDFSMemory = <langchain_experimental.tot.memory.ToTDFSMemory object>\u00b6\nparam tot_strategy_class: Type[BaseThoughtGenerationStrategy] = <class 'langchain_experimental.tot.thought_generation.ProposePromptStrategy'>\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\nparam verbose_llm: bool = False\u00b6\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-2", "text": "memory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-3", "text": "Asynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-4", "text": "Call the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-5", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-6", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-7", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, **kwargs: Any) \u2192 ToTChain[source]\u00b6\nCreate a ToTChain from a language model.\nParameters\nllm \u2013 The language model to use.\nkwargs \u2013 Additional arguments to pass to the ToTChain constructor.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-8", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nlog_thought(thought: Thought, level: int, run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 None[source]\u00b6\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-10", "text": "Validate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-11", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-12", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-13", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0278d5fa14f0-14", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.base.ToTChain.html"}
{"id": "0d20df055e77-0", "text": "langchain_experimental.tot.prompts.CheckerOutputParser\u00b6\nclass langchain_experimental.tot.prompts.CheckerOutputParser[source]\u00b6\nBases: BaseOutputParser\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.CheckerOutputParser.html"}
{"id": "0d20df055e77-1", "text": "Default implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.CheckerOutputParser.html"}
{"id": "0d20df055e77-2", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.CheckerOutputParser.html"}
{"id": "0d20df055e77-3", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.CheckerOutputParser.html"}
{"id": "0d20df055e77-4", "text": "This method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.CheckerOutputParser.html"}
{"id": "0d20df055e77-5", "text": "Return a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 ThoughtValidity[source]\u00b6\nParse the output of the language model.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.CheckerOutputParser.html"}
{"id": "0d20df055e77-6", "text": "stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.CheckerOutputParser.html"}
{"id": "0d20df055e77-7", "text": "Bind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.CheckerOutputParser.html"}
{"id": "0d20df055e77-8", "text": "The type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.prompts.CheckerOutputParser.html"}
{"id": "9a3f93df3a5a-0", "text": "langchain_experimental.tot.checker.ToTChecker\u00b6\nclass langchain_experimental.tot.checker.ToTChecker[source]\u00b6\nBases: Chain, ABC\nTree of Thought (ToT) checker.\nThis is an abstract ToT checker that must be implemented by the user. You\ncan implement a simple rule-based checker or a more sophisticated\nneural network based classifier.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "9a3f93df3a5a-1", "text": "Optional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "9a3f93df3a5a-2", "text": "metadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "9a3f93df3a5a-3", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "9a3f93df3a5a-4", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "9a3f93df3a5a-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "9a3f93df3a5a-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "9a3f93df3a5a-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nabstract evaluate(problem_description: str, thoughts: Tuple[str, ...] = ()) \u2192 ThoughtValidity[source]\u00b6\nEvaluate the response to the problem description and return the solution type.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "9a3f93df3a5a-8", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "9a3f93df3a5a-9", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "9a3f93df3a5a-10", "text": "memory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "9a3f93df3a5a-11", "text": "context = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "9a3f93df3a5a-12", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "9a3f93df3a5a-13", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.checker.ToTChecker.html"}
{"id": "d42cd5edf8ad-0", "text": "langchain_experimental.tot.thought.Thought\u00b6\nclass langchain_experimental.tot.thought.Thought[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam children: Set[langchain_experimental.tot.thought.Thought] [Optional]\u00b6\nparam text: str [Required]\u00b6\nparam validity: langchain_experimental.tot.thought.ThoughtValidity [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought.Thought.html"}
{"id": "d42cd5edf8ad-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought.Thought.html"}
{"id": "d42cd5edf8ad-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought.Thought.html"}
{"id": "1c2491d56b77-0", "text": "langchain_experimental.tot.thought.ThoughtValidity\u00b6\nclass langchain_experimental.tot.thought.ThoughtValidity(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nVALID_INTERMEDIATE = 0\u00b6\nVALID_FINAL = 1\u00b6\nINVALID = 2\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought.ThoughtValidity.html"}
{"id": "a61800c31b1b-0", "text": "langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy\u00b6\nclass langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy[source]\u00b6\nBases: LLMChain\nBase class for a thought generation strategy.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam c: int = 3\u00b6\nThe number of children thoughts to propose at each step.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-1", "text": "You can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-2", "text": "response. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-4", "text": "Generate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-5", "text": "Prepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-6", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-7", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-8", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-9", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nabstract next_thought(problem_description: str, thoughts_path: Tuple[str, ...] = (), **kwargs: Any) \u2192 str[source]\u00b6\nGenerate the next thought given the problem description and the thoughts\ngenerated so far.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-11", "text": "predict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-12", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-13", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-14", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "a61800c31b1b-15", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/tot/langchain_experimental.tot.thought_generation.BaseThoughtGenerationStrategy.html"}
{"id": "867d65bbe23b-0", "text": "langchain.utils.math.cosine_similarity_top_k\u00b6\nlangchain.utils.math.cosine_similarity_top_k(X: Union[List[List[float]], List[ndarray], ndarray], Y: Union[List[List[float]], List[ndarray], ndarray], top_k: Optional[int] = 5, score_threshold: Optional[float] = None) \u2192 Tuple[List[Tuple[int, int]], List[float]][source]\u00b6\nRow-wise cosine similarity with optional top-k and score threshold filtering.\nParameters\nX \u2013 Matrix.\nY \u2013 Matrix, same width as X.\ntop_k \u2013 Max number of results to return.\nscore_threshold \u2013 Minimum cosine similarity of results.\nReturns\nTuple of two lists. First contains two-tuples of indices (X_idx, Y_idx),second contains corresponding cosine similarities.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.math.cosine_similarity_top_k.html"}
{"id": "306f625d40ef-0", "text": "langchain.utils.strings.comma_list\u00b6\nlangchain.utils.strings.comma_list(items: List[Any]) \u2192 str[source]\u00b6\nConvert a list to a comma-separated string.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.strings.comma_list.html"}
{"id": "a5734605922a-0", "text": "langchain.utils.openai_functions.convert_pydantic_to_openai_tool\u00b6\nlangchain.utils.openai_functions.convert_pydantic_to_openai_tool(model: Type[BaseModel], *, name: Optional[str] = None, description: Optional[str] = None) \u2192 ToolDescription[source]\u00b6\nConverts a Pydantic model to a function description for the OpenAI API.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.openai_functions.convert_pydantic_to_openai_tool.html"}
{"id": "dab95cb0d62f-0", "text": "langchain.utils.utils.guard_import\u00b6\nlangchain.utils.utils.guard_import(module_name: str, *, pip_name: Optional[str] = None, package: Optional[str] = None) \u2192 Any[source]\u00b6\nDynamically imports a module and raises a helpful exception if the module is not\ninstalled.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.utils.guard_import.html"}
{"id": "f0da86dcdacf-0", "text": "langchain.utils.utils.build_extra_kwargs\u00b6\nlangchain.utils.utils.build_extra_kwargs(extra_kwargs: Dict[str, Any], values: Dict[str, Any], all_required_field_names: Set[str]) \u2192 Dict[str, Any][source]\u00b6\nBuild extra kwargs from values and extra_kwargs.\nParameters\nextra_kwargs \u2013 Extra kwargs passed in by user.\nvalues \u2013 Values passed in by user.\nall_required_field_names \u2013 All required field names for the pydantic class.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.utils.build_extra_kwargs.html"}
{"id": "5a87f39023f1-0", "text": "langchain.utils.openai_functions.FunctionDescription\u00b6\nclass langchain.utils.openai_functions.FunctionDescription[source]\u00b6\nRepresentation of a callable function to the OpenAI API.\nname: str\u00b6\nThe name of the function.\ndescription: str\u00b6\nA description of the function.\nparameters: dict\u00b6\nThe parameters of the function.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.openai_functions.FunctionDescription.html"}
{"id": "9fde07c69f2f-0", "text": "langchain.utils.input.get_bolded_text\u00b6\nlangchain.utils.input.get_bolded_text(text: str) \u2192 str[source]\u00b6\nGet bolded text.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.input.get_bolded_text.html"}
{"id": "3b462b59c626-0", "text": "langchain.utils.strings.stringify_value\u00b6\nlangchain.utils.strings.stringify_value(val: Any) \u2192 str[source]\u00b6\nStringify a value.\nParameters\nval \u2013 The value to stringify.\nReturns\nThe stringified value.\nReturn type\nstr", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.strings.stringify_value.html"}
{"id": "cba182e29ffc-0", "text": "langchain.utils.utils.get_pydantic_field_names\u00b6\nlangchain.utils.utils.get_pydantic_field_names(pydantic_cls: Any) \u2192 Set[str][source]\u00b6\nGet field names, including aliases, for a pydantic class.\nParameters\npydantic_cls \u2013 Pydantic class.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.utils.get_pydantic_field_names.html"}
{"id": "d40e8ea5d7e6-0", "text": "langchain.utils.utils.mock_now\u00b6\nlangchain.utils.utils.mock_now(dt_value)[source]\u00b6\nContext manager for mocking out datetime.now() in unit tests.\nExample:\nwith mock_now(datetime.datetime(2011, 2, 3, 10, 11)):\nassert datetime.datetime.now() == datetime.datetime(2011, 2, 3, 10, 11)", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.utils.mock_now.html"}
{"id": "ccda1b495f38-0", "text": "langchain.utils.pydantic.get_pydantic_major_version\u00b6\nlangchain.utils.pydantic.get_pydantic_major_version() \u2192 int[source]\u00b6\nGet the major version of Pydantic.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.pydantic.get_pydantic_major_version.html"}
{"id": "ce7f7f94e89b-0", "text": "langchain.utils.env.get_from_dict_or_env\u00b6\nlangchain.utils.env.get_from_dict_or_env(data: Dict[str, Any], key: str, env_key: str, default: Optional[str] = None) \u2192 str[source]\u00b6\nGet a value from a dictionary or an environment variable.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.env.get_from_dict_or_env.html"}
{"id": "2be8f6118a20-0", "text": "langchain.utils.iter.Tee\u00b6\nclass langchain.utils.iter.Tee(iterable: Iterator[T], n: int = 2, *, lock: Optional[ContextManager[Any]] = None)[source]\u00b6\nCreate n separate asynchronous iterators over iterable\nThis splits a single iterable into multiple iterators, each providing\nthe same items in the same order.\nAll child iterators may advance separately but share the same items\nfrom iterable \u2013 when the most advanced iterator retrieves an item,\nit is buffered until the least advanced iterator has yielded it as well.\nA tee works lazily and can handle an infinite iterable, provided\nthat all iterators advance.\nasync def derivative(sensor_data):\n    previous, current = a.tee(sensor_data, n=2)\n    await a.anext(previous)  # advance one iterator\n    return a.map(operator.sub, previous, current)\nUnlike itertools.tee(), tee() returns a custom type instead\nof a tuple. Like a tuple, it can be indexed, iterated and unpacked\nto get the child iterators. In addition, its aclose() method\nimmediately closes all children, and it can be used in an async with context\nfor the same effect.\nIf iterable is an iterator and read elsewhere, tee will not\nprovide these items. Also, tee must internally buffer each item until the\nlast iterator has yielded it; if the most and least advanced iterator differ\nby most data, using a list is more efficient (but not lazy).\nIf the underlying iterable is concurrency safe (anext may be awaited\nconcurrently) the resulting iterators are concurrency safe as well. Otherwise,\nthe iterators are safe if there is only ever one single \u201cmost advanced\u201d iterator.\nTo enforce sequential use of anext, provide a lock\n- e.g. an asyncio.Lock instance in an asyncio application -\nand access is automatically synchronised.\nMethods", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.iter.Tee.html"}
{"id": "2be8f6118a20-1", "text": "and access is automatically synchronised.\nMethods\n__init__(iterable[,\u00a0n,\u00a0lock])\nclose()\n__init__(iterable: Iterator[T], n: int = 2, *, lock: Optional[ContextManager[Any]] = None)[source]\u00b6\nclose() \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.iter.Tee.html"}
{"id": "813eb5c38092-0", "text": "langchain.utils.json_schema.dereference_refs\u00b6\nlangchain.utils.json_schema.dereference_refs(schema_obj: dict, *, full_schema: Optional[dict] = None, skip_keys: Optional[Sequence[str]] = None) \u2192 dict[source]\u00b6\nTry to substitute $refs in JSON Schema.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.json_schema.dereference_refs.html"}
{"id": "7ecc30160d32-0", "text": "langchain.utils.utils.convert_to_secret_str\u00b6\nlangchain.utils.utils.convert_to_secret_str(value: Union[SecretStr, str]) \u2192 SecretStr[source]\u00b6\nConvert a string to a SecretStr if needed.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.utils.convert_to_secret_str.html"}
{"id": "0ab8db6e2340-0", "text": "langchain.utils.aiter.Tee\u00b6\nclass langchain.utils.aiter.Tee(iterable: AsyncIterator[T], n: int = 2, *, lock: Optional[AsyncContextManager[Any]] = None)[source]\u00b6\nCreate n separate asynchronous iterators over iterable\nThis splits a single iterable into multiple iterators, each providing\nthe same items in the same order.\nAll child iterators may advance separately but share the same items\nfrom iterable \u2013 when the most advanced iterator retrieves an item,\nit is buffered until the least advanced iterator has yielded it as well.\nA tee works lazily and can handle an infinite iterable, provided\nthat all iterators advance.\nasync def derivative(sensor_data):\n    previous, current = a.tee(sensor_data, n=2)\n    await a.anext(previous)  # advance one iterator\n    return a.map(operator.sub, previous, current)\nUnlike itertools.tee(), tee() returns a custom type instead\nof a tuple. Like a tuple, it can be indexed, iterated and unpacked\nto get the child iterators. In addition, its aclose() method\nimmediately closes all children, and it can be used in an async with context\nfor the same effect.\nIf iterable is an iterator and read elsewhere, tee will not\nprovide these items. Also, tee must internally buffer each item until the\nlast iterator has yielded it; if the most and least advanced iterator differ\nby most data, using a list is more efficient (but not lazy).\nIf the underlying iterable is concurrency safe (anext may be awaited\nconcurrently) the resulting iterators are concurrency safe as well. Otherwise,\nthe iterators are safe if there is only ever one single \u201cmost advanced\u201d iterator.\nTo enforce sequential use of anext, provide a lock\n- e.g. an asyncio.Lock instance in an asyncio application -\nand access is automatically synchronised.\nMethods", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.aiter.Tee.html"}
{"id": "0ab8db6e2340-1", "text": "and access is automatically synchronised.\nMethods\n__init__(iterable[,\u00a0n,\u00a0lock])\naclose()\n__init__(iterable: AsyncIterator[T], n: int = 2, *, lock: Optional[AsyncContextManager[Any]] = None)[source]\u00b6\nasync aclose() \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.aiter.Tee.html"}
{"id": "1bdf2871d948-0", "text": "langchain.utils.utils.xor_args\u00b6\nlangchain.utils.utils.xor_args(*arg_groups: Tuple[str, ...]) \u2192 Callable[source]\u00b6\nValidate specified keyword args are mutually exclusive.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.utils.xor_args.html"}
{"id": "ea6aee6442f2-0", "text": "langchain.utils.iter.tee_peer\u00b6\nlangchain.utils.iter.tee_peer(iterator: Iterator[T], buffer: Deque[T], peers: List[Deque[T]], lock: ContextManager[Any]) \u2192 Generator[T, None, None][source]\u00b6\nAn individual iterator of a tee()", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.iter.tee_peer.html"}
{"id": "d34702f3c4de-0", "text": "langchain.utils.html.extract_sub_links\u00b6\nlangchain.utils.html.extract_sub_links(raw_html: str, url: str, *, base_url: Optional[str] = None, pattern: Optional[Union[str, Pattern]] = None, prevent_outside: bool = True, exclude_prefixes: Sequence[str] = ()) \u2192 List[str][source]\u00b6\nExtract all links from a raw html string and convert into absolute paths.\nParameters\nraw_html \u2013 original html.\nurl \u2013 the url of the html.\nbase_url \u2013 the base url to check for outside links against.\npattern \u2013 Regex to use for extracting links from raw html.\nprevent_outside \u2013 If True, ignore external links which are not children\nof the base url.\nexclude_prefixes \u2013 Exclude any URLs that start with one of these prefixes.\nReturns\nsub links\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.html.extract_sub_links.html"}
{"id": "09400e3a2ad2-0", "text": "langchain.utils.aiter.NoLock\u00b6\nclass langchain.utils.aiter.NoLock[source]\u00b6\nDummy lock that provides the proper interface but no protection\nMethods\n__init__()\n__init__()\u00b6", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.aiter.NoLock.html"}
{"id": "138433fb33c6-0", "text": "langchain.utils.env.get_from_env\u00b6\nlangchain.utils.env.get_from_env(key: str, env_key: str, default: Optional[str] = None) \u2192 str[source]\u00b6\nGet a value from a dictionary or an environment variable.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.env.get_from_env.html"}
{"id": "a677e3630830-0", "text": "langchain.utils.strings.stringify_dict\u00b6\nlangchain.utils.strings.stringify_dict(data: dict) \u2192 str[source]\u00b6\nStringify a dictionary.\nParameters\ndata \u2013 The dictionary to stringify.\nReturns\nThe stringified dictionary.\nReturn type\nstr", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.strings.stringify_dict.html"}
{"id": "75e498b90996-0", "text": "langchain.utils.html.find_all_links\u00b6\nlangchain.utils.html.find_all_links(raw_html: str, *, pattern: Optional[Union[str, Pattern]] = None) \u2192 List[str][source]\u00b6\nExtract all links from a raw html string.\nParameters\nraw_html \u2013 original html.\npattern \u2013 Regex to use for extracting links from raw html.\nReturns\nall links\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.html.find_all_links.html"}
{"id": "443e2b91a537-0", "text": "langchain.utils.openai_functions.convert_pydantic_to_openai_function\u00b6\nlangchain.utils.openai_functions.convert_pydantic_to_openai_function(model: Type[BaseModel], *, name: Optional[str] = None, description: Optional[str] = None) \u2192 FunctionDescription[source]\u00b6\nConverts a Pydantic model to a function description for the OpenAI API.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.openai_functions.convert_pydantic_to_openai_function.html"}
{"id": "1b16711d5af8-0", "text": "langchain.utils.iter.NoLock\u00b6\nclass langchain.utils.iter.NoLock[source]\u00b6\nDummy lock that provides the proper interface but no protection\nMethods\n__init__()\n__init__()\u00b6", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.iter.NoLock.html"}
{"id": "f2ae65cf1718-0", "text": "langchain.utils.loading.try_load_from_hub\u00b6\nlangchain.utils.loading.try_load_from_hub(path: Union[str, Path], loader: Callable[[str], T], valid_prefix: str, valid_suffixes: Set[str], **kwargs: Any) \u2192 Optional[T][source]\u00b6\nLoad configuration from hub.  Returns None if path is not a hub path.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.loading.try_load_from_hub.html"}
{"id": "61ccf7c83c48-0", "text": "langchain.utils.openai.is_openai_v1\u00b6\nlangchain.utils.openai.is_openai_v1() \u2192 bool[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.openai.is_openai_v1.html"}
{"id": "48d7096c5a72-0", "text": "langchain.utils.aiter.tee_peer\u00b6\nasync langchain.utils.aiter.tee_peer(iterator: AsyncIterator[T], buffer: Deque[T], peers: List[Deque[T]], lock: AsyncContextManager[Any]) \u2192 AsyncGenerator[T, None][source]\u00b6\nAn individual iterator of a tee()", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.aiter.tee_peer.html"}
{"id": "abfdb7248744-0", "text": "langchain.utils.aiter.atee\u00b6\nlangchain.utils.aiter.atee\u00b6\nalias of Tee", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.aiter.atee.html"}
{"id": "84f57ab63f9a-0", "text": "langchain.utils.math.cosine_similarity\u00b6\nlangchain.utils.math.cosine_similarity(X: Union[List[List[float]], List[ndarray], ndarray], Y: Union[List[List[float]], List[ndarray], ndarray]) \u2192 ndarray[source]\u00b6\nRow-wise cosine similarity between two equal-width matrices.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.math.cosine_similarity.html"}
{"id": "f0067e92cc31-0", "text": "langchain.utils.iter.safetee\u00b6\nlangchain.utils.iter.safetee\u00b6\nalias of Tee", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.iter.safetee.html"}
{"id": "c90d182290c9-0", "text": "langchain.utils.input.get_colored_text\u00b6\nlangchain.utils.input.get_colored_text(text: str, color: str) \u2192 str[source]\u00b6\nGet colored text.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.input.get_colored_text.html"}
{"id": "98efc4794f9b-0", "text": "langchain.utils.input.print_text\u00b6\nlangchain.utils.input.print_text(text: str, color: Optional[str] = None, end: str = '', file: Optional[TextIO] = None) \u2192 None[source]\u00b6\nPrint text with highlighting and no end characters.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.input.print_text.html"}
{"id": "1366b40eeaec-0", "text": "langchain.utils.iter.batch_iterate\u00b6\nlangchain.utils.iter.batch_iterate(size: int, iterable: Iterable[T]) \u2192 Iterator[List[T]][source]\u00b6\nUtility batching function.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.iter.batch_iterate.html"}
{"id": "89d6ab0dddc0-0", "text": "langchain.utils.utils.check_package_version\u00b6\nlangchain.utils.utils.check_package_version(package: str, lt_version: Optional[str] = None, lte_version: Optional[str] = None, gt_version: Optional[str] = None, gte_version: Optional[str] = None) \u2192 None[source]\u00b6\nCheck the version of a package.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.utils.check_package_version.html"}
{"id": "fa20f8b34455-0", "text": "langchain.utils.formatting.StrictFormatter\u00b6\nclass langchain.utils.formatting.StrictFormatter[source]\u00b6\nA subclass of formatter that checks for extra keys.\nMethods\n__init__()\ncheck_unused_args(used_args,\u00a0args,\u00a0kwargs)\nCheck to see if extra parameters are passed.\nconvert_field(value,\u00a0conversion)\nformat(format_string,\u00a0/,\u00a0*args,\u00a0**kwargs)\nformat_field(value,\u00a0format_spec)\nget_field(field_name,\u00a0args,\u00a0kwargs)\nget_value(key,\u00a0args,\u00a0kwargs)\nparse(format_string)\nvalidate_input_variables(format_string,\u00a0...)\nvformat(format_string,\u00a0args,\u00a0kwargs)\nCheck that no arguments are provided.\n__init__()\u00b6\ncheck_unused_args(used_args: Sequence[Union[int, str]], args: Sequence, kwargs: Mapping[str, Any]) \u2192 None[source]\u00b6\nCheck to see if extra parameters are passed.\nconvert_field(value, conversion)\u00b6\nformat(format_string, /, *args, **kwargs)\u00b6\nformat_field(value, format_spec)\u00b6\nget_field(field_name, args, kwargs)\u00b6\nget_value(key, args, kwargs)\u00b6\nparse(format_string)\u00b6\nvalidate_input_variables(format_string: str, input_variables: List[str]) \u2192 None[source]\u00b6\nvformat(format_string: str, args: Sequence, kwargs: Mapping[str, Any]) \u2192 str[source]\u00b6\nCheck that no arguments are provided.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.formatting.StrictFormatter.html"}
{"id": "087f4c446b85-0", "text": "langchain.utils.aiter.py_anext\u00b6\nlangchain.utils.aiter.py_anext(iterator: ~typing.AsyncIterator[~langchain.utils.aiter.T], default: ~typing.Union[~langchain.utils.aiter.T, ~typing.Any] = <object object>) \u2192 Awaitable[Union[T, None, Any]][source]\u00b6\nPure-Python implementation of anext() for testing purposes.\nClosely matches the builtin anext() C implementation.\nCan be used to compare the built-in implementation of the inner\ncoroutines machinery to C-implementation of __anext__() and send()\nor throw() on the returned generator.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.aiter.py_anext.html"}
{"id": "8a99f3e0050f-0", "text": "langchain.utils.utils.raise_for_status_with_text\u00b6\nlangchain.utils.utils.raise_for_status_with_text(response: Response) \u2192 None[source]\u00b6\nRaise an error with the response text.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.utils.raise_for_status_with_text.html"}
{"id": "0b8a206d35c0-0", "text": "langchain.utils.input.get_color_mapping\u00b6\nlangchain.utils.input.get_color_mapping(items: List[str], excluded_colors: Optional[List] = None) \u2192 Dict[str, str][source]\u00b6\nGet mapping for items to a support color.", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.input.get_color_mapping.html"}
{"id": "75531ebdd941-0", "text": "langchain.utils.openai_functions.ToolDescription\u00b6\nclass langchain.utils.openai_functions.ToolDescription[source]\u00b6\nRepresentation of a callable function to the OpenAI API.\ntype: Literal['function']\u00b6\nfunction: langchain.utils.openai_functions.FunctionDescription\u00b6", "source": "lang/api.python.langchain.com/en/latest/utils/langchain.utils.openai_functions.ToolDescription.html"}
{"id": "af6a19faef1b-0", "text": "langchain_experimental.tabular_synthetic_data.base.SyntheticDataGenerator\u00b6\nclass langchain_experimental.tabular_synthetic_data.base.SyntheticDataGenerator[source]\u00b6\nBases: BaseModel\nGenerates synthetic data using the given LLM and few-shot template.\nUtilizes the provided LLM to produce synthetic data based on the\nfew-shot prompt template.\ntemplate\u00b6\nTemplate for few-shot prompting.\nType\nFewShotPromptTemplate\nllm\u00b6\nLarge Language Model to use for generation.\nType\nOptional[BaseLanguageModel]\nllm_chain\u00b6\nLLM chain with the LLM and few-shot template.\nType\nOptional[Chain]\nexample_input_key\u00b6\nKey to use for storing example inputs.\nType\nstr\nUsage Example:>>> template = FewShotPromptTemplate(...)\n>>> llm = BaseLanguageModel(...)\n>>> generator = SyntheticDataGenerator(template=template, llm=llm)\n>>> results = generator.generate(subject=\"climate change\", runs=5)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam example_input_key: str = 'example'\u00b6\nparam llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nparam llm_chain: Optional[langchain.chains.base.Chain] = None\u00b6\nparam results: list = []\u00b6\nparam template: langchain.prompts.few_shot.FewShotPromptTemplate [Required]\u00b6\nasync agenerate(subject: str, runs: int, extra: str = '', *args: Any, **kwargs: Any) \u2192 List[str][source]\u00b6\nGenerate synthetic data using the given subject asynchronously.\nNote: Since the LLM calls run concurrently,\nyou may have fewer duplicates by adding specific instructions to\nthe \u201cextra\u201d keyword argument.\nParameters", "source": "lang/api.python.langchain.com/en/latest/tabular_synthetic_data/langchain_experimental.tabular_synthetic_data.base.SyntheticDataGenerator.html"}
{"id": "af6a19faef1b-1", "text": "the \u201cextra\u201d keyword argument.\nParameters\nsubject (str) \u2013 The subject the synthetic data will be about.\nruns (int) \u2013 Number of times to generate the data asynchronously.\nextra (str) \u2013 Extra instructions for steerability in data generation.\nReturns\nList of generated synthetic data for the given subject.\nReturn type\nList[str]\nUsage Example:>>> results = await generator.agenerate(subject=\"climate change\", runs=5,\nextra=\"Focus on env impacts.\")\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/tabular_synthetic_data/langchain_experimental.tabular_synthetic_data.base.SyntheticDataGenerator.html"}
{"id": "af6a19faef1b-2", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(subject: str, runs: int, *args: Any, **kwargs: Any) \u2192 List[str][source]\u00b6\nGenerate synthetic data using the given subject string.\nParameters\nsubject (str) \u2013 The subject the synthetic data will be about.\nruns (int) \u2013 Number of times to generate the data.\nextra (str) \u2013 Extra instructions for steerability in data generation.\nReturns\nList of generated synthetic data.\nReturn type\nList[str]\nUsage Example:>>> results = generator.generate(subject=\"climate change\", runs=5,\nextra=\"Focus on environmental impacts.\")\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/tabular_synthetic_data/langchain_experimental.tabular_synthetic_data.base.SyntheticDataGenerator.html"}
{"id": "af6a19faef1b-3", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/tabular_synthetic_data/langchain_experimental.tabular_synthetic_data.base.SyntheticDataGenerator.html"}
{"id": "8f0f6ccff58c-0", "text": "langchain_experimental.tabular_synthetic_data.openai.create_openai_data_generator\u00b6\nlangchain_experimental.tabular_synthetic_data.openai.create_openai_data_generator(output_schema: Union[Dict[str, Any], Type[BaseModel]], llm: ChatOpenAI, prompt: BasePromptTemplate, output_parser: Optional[BaseLLMOutputParser] = None, **kwargs: Any) \u2192 SyntheticDataGenerator[source]\u00b6\nCreate an instance of SyntheticDataGenerator tailored for OpenAI models.\nThis function creates an LLM chain designed for structured output based on the\nprovided schema, language model, and prompt template. The resulting chain is then\nused to instantiate and return a SyntheticDataGenerator.\nParameters\noutput_schema (Union[Dict[str, Any], Type[BaseModel]]) \u2013 Schema for expected\na (output. This can be either a dictionary representing a valid JsonSchema or) \u2013 \nclass. (Pydantic BaseModel) \u2013 \nllm (ChatOpenAI) \u2013 OpenAI language model to use.\nprompt (BasePromptTemplate) \u2013 Template to be used for generating prompts.\noutput_parser (Optional[BaseLLMOutputParser], optional) \u2013 Parser for\nprovided (processing model outputs. If none is) \u2013 \ninferred (a default will be) \u2013 \ntypes. (from the function) \u2013 \n**kwargs \u2013 Additional keyword arguments to be passed to\ncreate_structured_output_chain. \u2013 \nReturns: SyntheticDataGenerator: An instance of the data generator set up with\nthe constructed chain.\nUsage:To generate synthetic data with a structured output, first define your desired\noutput schema. Then, use this function to create a SyntheticDataGenerator\ninstance. After obtaining the generator, you can utilize its methods to produce\nthe desired synthetic data.", "source": "lang/api.python.langchain.com/en/latest/tabular_synthetic_data/langchain_experimental.tabular_synthetic_data.openai.create_openai_data_generator.html"}
{"id": "0f45bcde4ab6-0", "text": "langchain.adapters.openai.ChatCompletion\u00b6\nclass langchain.adapters.openai.ChatCompletion[source]\u00b6\nChat completion.\nMethods\n__init__()\nacreate()\ncreate()\n__init__()\u00b6\nasync static acreate(messages: Sequence[Dict[str, Any]], *, provider: str = \"'ChatOpenAI'\", stream: Literal[False] = 'False', **kwargs: Any) \u2192 dict[source]\u00b6\nasync static acreate(messages: Sequence[Dict[str, Any]], *, provider: str = \"'ChatOpenAI'\", stream: Literal[True], **kwargs: Any) \u2192 AsyncIterator\nstatic create(messages: Sequence[Dict[str, Any]], *, provider: str = \"'ChatOpenAI'\", stream: Literal[False] = 'False', **kwargs: Any) \u2192 dict[source]\u00b6\nstatic create(messages: Sequence[Dict[str, Any]], *, provider: str = \"'ChatOpenAI'\", stream: Literal[True], **kwargs: Any) \u2192 Iterable", "source": "lang/api.python.langchain.com/en/latest/adapters/langchain.adapters.openai.ChatCompletion.html"}
{"id": "36b675d44581-0", "text": "langchain.adapters.openai.convert_openai_messages\u00b6\nlangchain.adapters.openai.convert_openai_messages(messages: Sequence[Dict[str, Any]]) \u2192 List[BaseMessage][source]\u00b6\nConvert dictionaries representing OpenAI messages to LangChain format.\nParameters\nmessages \u2013 List of dictionaries representing OpenAI messages\nReturns\nList of LangChain BaseMessage objects.", "source": "lang/api.python.langchain.com/en/latest/adapters/langchain.adapters.openai.convert_openai_messages.html"}
{"id": "09e9dc5a00d3-0", "text": "langchain.adapters.openai.aenumerate\u00b6\nasync langchain.adapters.openai.aenumerate(iterable: AsyncIterator[Any], start: int = 0) \u2192 AsyncIterator[tuple[int, Any]][source]\u00b6\nAsync version of enumerate function.", "source": "lang/api.python.langchain.com/en/latest/adapters/langchain.adapters.openai.aenumerate.html"}
{"id": "27f3a88ba7f3-0", "text": "langchain.adapters.openai.convert_message_to_dict\u00b6\nlangchain.adapters.openai.convert_message_to_dict(message: BaseMessage) \u2192 dict[source]\u00b6\nConvert a LangChain message to a dictionary.\nParameters\nmessage \u2013 The LangChain message.\nReturns\nThe dictionary.\nExamples using convert_message_to_dict\u00b6\nTwitter (via Apify)", "source": "lang/api.python.langchain.com/en/latest/adapters/langchain.adapters.openai.convert_message_to_dict.html"}
{"id": "c499d7d7dfcd-0", "text": "langchain.adapters.openai.convert_dict_to_message\u00b6\nlangchain.adapters.openai.convert_dict_to_message(_dict: Mapping[str, Any]) \u2192 BaseMessage[source]\u00b6\nConvert a dictionary to a LangChain message.\nParameters\n_dict \u2013 The dictionary.\nReturns\nThe LangChain message.", "source": "lang/api.python.langchain.com/en/latest/adapters/langchain.adapters.openai.convert_dict_to_message.html"}
{"id": "4a6eb603e9e4-0", "text": "langchain.adapters.openai.convert_messages_for_finetuning\u00b6\nlangchain.adapters.openai.convert_messages_for_finetuning(sessions: Iterable[ChatSession]) \u2192 List[List[dict]][source]\u00b6\nConvert messages to a list of lists of dictionaries for fine-tuning.\nParameters\nsessions \u2013 The chat sessions.\nReturns\nThe list of lists of dictionaries.\nExamples using convert_messages_for_finetuning\u00b6\nFacebook Messenger\nChat loaders\niMessage", "source": "lang/api.python.langchain.com/en/latest/adapters/langchain.adapters.openai.convert_messages_for_finetuning.html"}
{"id": "f2b5823127a0-0", "text": "langchain.document_loaders.modern_treasury.ModernTreasuryLoader\u00b6\nclass langchain.document_loaders.modern_treasury.ModernTreasuryLoader(resource: str, organization_id: Optional[str] = None, api_key: Optional[str] = None)[source]\u00b6\nLoad from Modern Treasury.\nParameters\nresource \u2013 The Modern Treasury resource to load.\norganization_id \u2013 The Modern Treasury organization ID. It can also be\nspecified via the environment variable\n\u201cMODERN_TREASURY_ORGANIZATION_ID\u201d.\napi_key \u2013 The Modern Treasury API key. It can also be specified via\nthe environment variable \u201cMODERN_TREASURY_API_KEY\u201d.\nMethods\n__init__(resource[,\u00a0organization_id,\u00a0api_key])\nparam resource\nThe Modern Treasury resource to load.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(resource: str, organization_id: Optional[str] = None, api_key: Optional[str] = None) \u2192 None[source]\u00b6\nParameters\nresource \u2013 The Modern Treasury resource to load.\norganization_id \u2013 The Modern Treasury organization ID. It can also be\nspecified via the environment variable\n\u201cMODERN_TREASURY_ORGANIZATION_ID\u201d.\napi_key \u2013 The Modern Treasury API key. It can also be specified via\nthe environment variable \u201cMODERN_TREASURY_API_KEY\u201d.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.modern_treasury.ModernTreasuryLoader.html"}
{"id": "f2b5823127a0-1", "text": "Parameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using ModernTreasuryLoader\u00b6\nModern Treasury", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.modern_treasury.ModernTreasuryLoader.html"}
{"id": "f3932bf51abe-0", "text": "langchain.document_loaders.docusaurus.DocusaurusLoader\u00b6\nclass langchain.document_loaders.docusaurus.DocusaurusLoader(url: str, custom_html_tags: Optional[List[str]] = None, **kwargs: Any)[source]\u00b6\nLoader that leverages the SitemapLoader to loop through the generated pages of a\nDocusaurus Documentation website and extracts the content by looking for specific\nHTML tags. By default, the parser searches for the main content of the Docusaurus\npage, which is normally the <article>. You also have the option to define your own\ncustom HTML tags by providing them as a list, for example: [\u201cdiv\u201d, \u201c.main\u201d, \u201ca\u201d].\nInitialize DocusaurusLoader\n:param url: The base URL of the Docusaurus website.\n:param custom_html_tags: Optional custom html tags to extract content from pages.\n:param kwargs: Additional args to extend the underlying SitemapLoader, for example:\nfilter_urls, blocksize, meta_function, is_local, continue_on_failure\nAttributes\nweb_path\nMethods\n__init__(url[,\u00a0custom_html_tags])\nInitialize DocusaurusLoader :param url: The base URL of the Docusaurus website. :param custom_html_tags: Optional custom html tags to extract content from pages. :param kwargs: Additional args to extend the underlying SitemapLoader, for example:                filter_urls, blocksize, meta_function, is_local, continue_on_failure.\naload()\nLoad text from the urls in web_path async into Documents.\nfetch_all(urls)\nFetch all urls concurrently with rate limiting.\nlazy_load()\nLazy load text from the url(s) in web_path.\nload()\nLoad sitemap.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nparse_sitemap(soup)\nParse sitemap xml and load into a list of dicts.\nscrape([parser])", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.docusaurus.DocusaurusLoader.html"}
{"id": "f3932bf51abe-1", "text": "Parse sitemap xml and load into a list of dicts.\nscrape([parser])\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls[,\u00a0parser])\nFetch all urls, then return soups for all results.\n__init__(url: str, custom_html_tags: Optional[List[str]] = None, **kwargs: Any)[source]\u00b6\nInitialize DocusaurusLoader\n:param url: The base URL of the Docusaurus website.\n:param custom_html_tags: Optional custom html tags to extract content from pages.\n:param kwargs: Additional args to extend the underlying SitemapLoader, for example:\nfilter_urls, blocksize, meta_function, is_local, continue_on_failure\naload() \u2192 List[Document]\u00b6\nLoad text from the urls in web_path async into Documents.\nasync fetch_all(urls: List[str]) \u2192 Any\u00b6\nFetch all urls concurrently with rate limiting.\nlazy_load() \u2192 Iterator[Document]\u00b6\nLazy load text from the url(s) in web_path.\nload() \u2192 List[Document]\u00b6\nLoad sitemap.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nparse_sitemap(soup: Any) \u2192 List[dict]\u00b6\nParse sitemap xml and load into a list of dicts.\nParameters\nsoup \u2013 BeautifulSoup object.\nReturns\nList of dicts.\nscrape(parser: Optional[str] = None) \u2192 Any\u00b6\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls: List[str], parser: Optional[str] = None) \u2192 List[Any]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.docusaurus.DocusaurusLoader.html"}
{"id": "f3932bf51abe-2", "text": "Fetch all urls, then return soups for all results.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.docusaurus.DocusaurusLoader.html"}
{"id": "5bf5ec6ead27-0", "text": "langchain.document_loaders.twitter.TwitterTweetLoader\u00b6\nclass langchain.document_loaders.twitter.TwitterTweetLoader(auth_handler: Union[OAuthHandler, OAuth2BearerHandler], twitter_users: Sequence[str], number_tweets: Optional[int] = 100)[source]\u00b6\nLoad Twitter tweets.\nRead tweets of the user\u2019s Twitter handle.\nFirst you need to go to\nhttps://developer.twitter.com/en/docs/twitter-api\n/getting-started/getting-access-to-the-twitter-api\nto get your token. And create a v2 version of the app.\nMethods\n__init__(auth_handler,\u00a0twitter_users[,\u00a0...])\nfrom_bearer_token(oauth2_bearer_token,\u00a0...)\nCreate a TwitterTweetLoader from OAuth2 bearer token.\nfrom_secrets(access_token,\u00a0...[,\u00a0number_tweets])\nCreate a TwitterTweetLoader from access tokens and secrets.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad tweets.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(auth_handler: Union[OAuthHandler, OAuth2BearerHandler], twitter_users: Sequence[str], number_tweets: Optional[int] = 100)[source]\u00b6\nclassmethod from_bearer_token(oauth2_bearer_token: str, twitter_users: Sequence[str], number_tweets: Optional[int] = 100) \u2192 TwitterTweetLoader[source]\u00b6\nCreate a TwitterTweetLoader from OAuth2 bearer token.\nclassmethod from_secrets(access_token: str, access_token_secret: str, consumer_key: str, consumer_secret: str, twitter_users: Sequence[str], number_tweets: Optional[int] = 100) \u2192 TwitterTweetLoader[source]\u00b6\nCreate a TwitterTweetLoader from access tokens and secrets.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad tweets.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.twitter.TwitterTweetLoader.html"}
{"id": "5bf5ec6ead27-1", "text": "load() \u2192 List[Document][source]\u00b6\nLoad tweets.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using TwitterTweetLoader\u00b6\nTwitter", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.twitter.TwitterTweetLoader.html"}
{"id": "8270e2e39ded-0", "text": "langchain.document_loaders.json_loader.JSONLoader\u00b6\nclass langchain.document_loaders.json_loader.JSONLoader(file_path: Union[str, Path], jq_schema: str, content_key: Optional[str] = None, metadata_func: Optional[Callable[[Dict, Dict], Dict]] = None, text_content: bool = True, json_lines: bool = False)[source]\u00b6\nLoad a JSON file using a jq schema.\nExample\n[{\u201ctext\u201d: \u2026}, {\u201ctext\u201d: \u2026}, {\u201ctext\u201d: \u2026}] -> schema = .[].text\n{\u201ckey\u201d: [{\u201ctext\u201d: \u2026}, {\u201ctext\u201d: \u2026}, {\u201ctext\u201d: \u2026}]} -> schema = .key[].text\n[\u201c\u201d, \u201c\u201d, \u201c\u201d] -> schema = .[]\nInitialize the JSONLoader.\nParameters\nfile_path (Union[str, Path]) \u2013 The path to the JSON or JSON Lines file.\njq_schema (str) \u2013 The jq schema to use to extract the data or text from\nthe JSON.\ncontent_key (str) \u2013 The key to use to extract the content from the JSON if\nthe jq_schema results to a list of objects (dict).\nmetadata_func (Callable[Dict, Dict]) \u2013 A function that takes in the JSON\nobject extracted by the jq_schema and the default metadata and returns\na dict of the updated metadata.\ntext_content (bool) \u2013 Boolean flag to indicate whether the content is in\nstring format, default to True.\njson_lines (bool) \u2013 Boolean flag to indicate whether the input is in\nJSON Lines format.\nMethods\n__init__(file_path,\u00a0jq_schema[,\u00a0...])\nInitialize the JSONLoader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad and return documents from the JSON file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.json_loader.JSONLoader.html"}
{"id": "8270e2e39ded-1", "text": "load_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: Union[str, Path], jq_schema: str, content_key: Optional[str] = None, metadata_func: Optional[Callable[[Dict, Dict], Dict]] = None, text_content: bool = True, json_lines: bool = False)[source]\u00b6\nInitialize the JSONLoader.\nParameters\nfile_path (Union[str, Path]) \u2013 The path to the JSON or JSON Lines file.\njq_schema (str) \u2013 The jq schema to use to extract the data or text from\nthe JSON.\ncontent_key (str) \u2013 The key to use to extract the content from the JSON if\nthe jq_schema results to a list of objects (dict).\nmetadata_func (Callable[Dict, Dict]) \u2013 A function that takes in the JSON\nobject extracted by the jq_schema and the default metadata and returns\na dict of the updated metadata.\ntext_content (bool) \u2013 Boolean flag to indicate whether the content is in\nstring format, default to True.\njson_lines (bool) \u2013 Boolean flag to indicate whether the input is in\nJSON Lines format.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad and return documents from the JSON file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.json_loader.JSONLoader.html"}
{"id": "5a5379be6863-0", "text": "langchain.document_loaders.evernote.EverNoteLoader\u00b6\nclass langchain.document_loaders.evernote.EverNoteLoader(file_path: str, load_single_document: bool = True)[source]\u00b6\nLoad from EverNote.\nLoads an EverNote notebook export file e.g. my_notebook.enex into Documents.\nInstructions on producing this file can be found at\nhttps://help.evernote.com/hc/en-us/articles/209005557-Export-notes-and-notebooks-as-ENEX-or-HTML\nCurrently only the plain text in the note is extracted and stored as the contents\nof the Document, any non content metadata (e.g. \u2018author\u2019, \u2018created\u2019, \u2018updated\u2019 etc.\nbut not \u2018content-raw\u2019 or \u2018resource\u2019) tags on the note will be extracted and stored\nas metadata on the Document.\nParameters\nfile_path (str) \u2013 The path to the notebook export with a .enex extension\nload_single_document (bool) \u2013 Whether or not to concatenate the content of all\nnotes into a single long Document.\nTrue (If this is set to) \u2013 the \u2018source\u2019 which contains the file name of the export.\nInitialize with file path.\nMethods\n__init__(file_path[,\u00a0load_single_document])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents from EverNote export file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, load_single_document: bool = True)[source]\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents from EverNote export file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.evernote.EverNoteLoader.html"}
{"id": "5a5379be6863-1", "text": "Load Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using EverNoteLoader\u00b6\nEverNote", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.evernote.EverNoteLoader.html"}
{"id": "4f3dd7d76eb9-0", "text": "langchain.document_loaders.word_document.UnstructuredWordDocumentLoader\u00b6\nclass langchain.document_loaders.word_document.UnstructuredWordDocumentLoader(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad Microsoft Word file using Unstructured.\nWorks with both .docx and .doc files.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredWordDocumentLoader\nloader = UnstructuredWordDocumentLoader(\u201cexample.docx\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition-docx\nInitialize with file path.\nMethods\n__init__(file_path[,\u00a0mode])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.word_document.UnstructuredWordDocumentLoader.html"}
{"id": "4f3dd7d76eb9-1", "text": "Load Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredWordDocumentLoader\u00b6\nMicrosoft Word", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.word_document.UnstructuredWordDocumentLoader.html"}
{"id": "6a49c6183b64-0", "text": "langchain.document_loaders.chromium.AsyncChromiumLoader\u00b6\nclass langchain.document_loaders.chromium.AsyncChromiumLoader(urls: List[str])[source]\u00b6\nScrape HTML pages from URLs using a\nheadless instance of the Chromium.\nInitialize the loader with a list of URL paths.\nParameters\nurls (List[str]) \u2013 A list of URLs to scrape content from.\nRaises\nImportError \u2013 If the required \u2018playwright\u2019 package is not installed.\nMethods\n__init__(urls)\nInitialize the loader with a list of URL paths.\nascrape_playwright(url)\nAsynchronously scrape the content of a given URL using Playwright's async API.\nlazy_load()\nLazily load text content from the provided URLs.\nload()\nLoad and return all Documents from the provided URLs.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(urls: List[str])[source]\u00b6\nInitialize the loader with a list of URL paths.\nParameters\nurls (List[str]) \u2013 A list of URLs to scrape content from.\nRaises\nImportError \u2013 If the required \u2018playwright\u2019 package is not installed.\nasync ascrape_playwright(url: str) \u2192 str[source]\u00b6\nAsynchronously scrape the content of a given URL using Playwright\u2019s async API.\nParameters\nurl (str) \u2013 The URL to scrape.\nReturns\nThe scraped HTML content or an error message if an exception occurs.\nReturn type\nstr\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazily load text content from the provided URLs.\nThis method yields Documents one at a time as they\u2019re scraped,\ninstead of waiting to scrape all URLs before returning.\nYields\nDocument \u2013 The scraped content encapsulated within a Document object.\nload() \u2192 List[Document][source]\u00b6\nLoad and return all Documents from the provided URLs.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.chromium.AsyncChromiumLoader.html"}
{"id": "6a49c6183b64-1", "text": "Load and return all Documents from the provided URLs.\nReturns\nA list of Document objects\ncontaining the scraped content from each URL.\nReturn type\nList[Document]\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AsyncChromiumLoader\u00b6\nBeautiful Soup\nAsync Chromium\nSet env var OPENAI_API_KEY or load from a .env file:", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.chromium.AsyncChromiumLoader.html"}
{"id": "0de79a96b404-0", "text": "langchain.document_loaders.parsers.language.cobol.CobolSegmenter\u00b6\nclass langchain.document_loaders.parsers.language.cobol.CobolSegmenter(code: str)[source]\u00b6\nCode segmenter for COBOL.\nAttributes\nDIVISION_PATTERN\nPARAGRAPH_PATTERN\nSECTION_PATTERN\nMethods\n__init__(code)\nextract_functions_classes()\nis_valid()\nsimplify_code()\n__init__(code: str)[source]\u00b6\nextract_functions_classes() \u2192 List[str][source]\u00b6\nis_valid() \u2192 bool[source]\u00b6\nsimplify_code() \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.language.cobol.CobolSegmenter.html"}
{"id": "814670f5fe92-0", "text": "langchain.document_loaders.notion.NotionDirectoryLoader\u00b6\nclass langchain.document_loaders.notion.NotionDirectoryLoader(path: str, *, encoding: str = 'utf-8')[source]\u00b6\nLoad Notion directory dump.\nInitialize with a file path.\nMethods\n__init__(path,\u00a0*[,\u00a0encoding])\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(path: str, *, encoding: str = 'utf-8') \u2192 None[source]\u00b6\nInitialize with a file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using NotionDirectoryLoader\u00b6\nNotion DB\nNotion DB 1/2\nPerform context-aware text splitting", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.notion.NotionDirectoryLoader.html"}
{"id": "b29ef58c3d16-0", "text": "langchain.document_loaders.rocksetdb.RocksetLoader\u00b6\nclass langchain.document_loaders.rocksetdb.RocksetLoader(client: ~typing.Any, query: ~typing.Any, content_keys: ~typing.List[str], metadata_keys: ~typing.Optional[~typing.List[str]] = None, content_columns_joiner: ~typing.Callable[[~typing.List[~typing.Tuple[str, ~typing.Any]]], str] = <function default_joiner>)[source]\u00b6\nLoad from a Rockset database.\nTo use, you should have the rockset python package installed.\nExample\n# This code will load 3 records from the \"langchain_demo\"\n# collection as Documents, with the `text` column used as\n# the content\nfrom langchain.document_loaders import RocksetLoader\nfrom rockset import RocksetClient, Regions, models\nloader = RocksetLoader(\n    RocksetClient(Regions.usw2a1, \"<api key>\"),\n    models.QueryRequestSql(\n        query=\"select * from langchain_demo limit 3\"\n    ),\n    [\"text\"]\n)\n)\nInitialize with Rockset client.\nParameters\nclient \u2013 Rockset client object.\nquery \u2013 Rockset query object.\ncontent_keys \u2013 The collection columns to be written into the page_content\nof the Documents.\nmetadata_keys \u2013 The collection columns to be written into the metadata of\nthe Documents. By default, this is all the keys in the document.\ncontent_columns_joiner \u2013 Method that joins content_keys and its values into a\nstring. It\u2019s method that takes in a List[Tuple[str, Any]]],\nrepresenting a list of tuples of (column name, column value).\nBy default, this is a method that joins each column value with a new\nline. This method is only relevant if there are multiple content_keys.\nMethods", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.rocksetdb.RocksetLoader.html"}
{"id": "b29ef58c3d16-1", "text": "line. This method is only relevant if there are multiple content_keys.\nMethods\n__init__(client,\u00a0query,\u00a0content_keys[,\u00a0...])\nInitialize with Rockset client.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(client: ~typing.Any, query: ~typing.Any, content_keys: ~typing.List[str], metadata_keys: ~typing.Optional[~typing.List[str]] = None, content_columns_joiner: ~typing.Callable[[~typing.List[~typing.Tuple[str, ~typing.Any]]], str] = <function default_joiner>)[source]\u00b6\nInitialize with Rockset client.\nParameters\nclient \u2013 Rockset client object.\nquery \u2013 Rockset query object.\ncontent_keys \u2013 The collection columns to be written into the page_content\nof the Documents.\nmetadata_keys \u2013 The collection columns to be written into the metadata of\nthe Documents. By default, this is all the keys in the document.\ncontent_columns_joiner \u2013 Method that joins content_keys and its values into a\nstring. It\u2019s method that takes in a List[Tuple[str, Any]]],\nrepresenting a list of tuples of (column name, column value).\nBy default, this is a method that joins each column value with a new\nline. This method is only relevant if there are multiple content_keys.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.rocksetdb.RocksetLoader.html"}
{"id": "b29ef58c3d16-2", "text": "Load Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using RocksetLoader\u00b6\nRockset", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.rocksetdb.RocksetLoader.html"}
{"id": "7a4cfe196fb7-0", "text": "langchain.document_loaders.acreom.AcreomLoader\u00b6\nclass langchain.document_loaders.acreom.AcreomLoader(path: str, encoding: str = 'UTF-8', collect_metadata: bool = True)[source]\u00b6\nLoad acreom vault from a directory.\nInitialize the loader.\nAttributes\nFRONT_MATTER_REGEX\nRegex to match front matter metadata in markdown files.\nfile_path\nPath to the directory containing the markdown files.\nencoding\nEncoding to use when reading the files.\ncollect_metadata\nWhether to collect metadata from the front matter.\nMethods\n__init__(path[,\u00a0encoding,\u00a0collect_metadata])\nInitialize the loader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(path: str, encoding: str = 'UTF-8', collect_metadata: bool = True)[source]\u00b6\nInitialize the loader.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AcreomLoader\u00b6\nacreom", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.acreom.AcreomLoader.html"}
{"id": "897c712d1597-0", "text": "langchain.document_loaders.onedrive_file.OneDriveFileLoader\u00b6\nclass langchain.document_loaders.onedrive_file.OneDriveFileLoader[source]\u00b6\nBases: BaseLoader, BaseModel\nLoad a file from Microsoft OneDrive.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam file: File [Required]\u00b6\nThe file to load.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.onedrive_file.OneDriveFileLoader.html"}
{"id": "897c712d1597-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad Documents\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.onedrive_file.OneDriveFileLoader.html"}
{"id": "897c712d1597-2", "text": "Defaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.onedrive_file.OneDriveFileLoader.html"}
{"id": "f1ffabac1ec4-0", "text": "langchain.document_loaders.chatgpt.ChatGPTLoader\u00b6\nclass langchain.document_loaders.chatgpt.ChatGPTLoader(log_file: str, num_logs: int = - 1)[source]\u00b6\nLoad conversations from exported ChatGPT data.\nInitialize a class object.\nParameters\nlog_file \u2013 Path to the log file\nnum_logs \u2013 Number of logs to load. If 0, load all logs.\nMethods\n__init__(log_file[,\u00a0num_logs])\nInitialize a class object.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(log_file: str, num_logs: int = - 1)[source]\u00b6\nInitialize a class object.\nParameters\nlog_file \u2013 Path to the log file\nnum_logs \u2013 Number of logs to load. If 0, load all logs.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using ChatGPTLoader\u00b6\nOpenAI\nChatGPT Data", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.chatgpt.ChatGPTLoader.html"}
{"id": "23c4aeee6af5-0", "text": "langchain.document_loaders.hugging_face_dataset.HuggingFaceDatasetLoader\u00b6\nclass langchain.document_loaders.hugging_face_dataset.HuggingFaceDatasetLoader(path: str, page_content_column: str = 'text', name: Optional[str] = None, data_dir: Optional[str] = None, data_files: Optional[Union[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]]] = None, cache_dir: Optional[str] = None, keep_in_memory: Optional[bool] = None, save_infos: bool = False, use_auth_token: Optional[Union[bool, str]] = None, num_proc: Optional[int] = None)[source]\u00b6\nLoad from Hugging Face Hub datasets.\nInitialize the HuggingFaceDatasetLoader.\nParameters\npath \u2013 Path or name of the dataset.\npage_content_column \u2013 Page content column name. Default is \u201ctext\u201d.\nNote: Currently the function assumes the content is a string.\nIf it is not download the dataset using huggingface library and convert\nusing the json or pandas loaders.\nhttps://github.com/langchain-ai/langchain/issues/10674\nname \u2013 Name of the dataset configuration.\ndata_dir \u2013 Data directory of the dataset configuration.\ndata_files \u2013 Path(s) to source data file(s).\ncache_dir \u2013 Directory to read/write data.\nkeep_in_memory \u2013 Whether to copy the dataset in-memory.\nsave_infos \u2013 Save the dataset information (checksums/size/splits/\u2026).\nDefault is False.\nuse_auth_token \u2013 Bearer token for remote files on the Dataset Hub.\nnum_proc \u2013 Number of processes.\nMethods\n__init__(path[,\u00a0page_content_column,\u00a0name,\u00a0...])\nInitialize the HuggingFaceDatasetLoader.\nlazy_load()\nLoad documents lazily.\nload()\nLoad documents.\nload_and_split([text_splitter])", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.hugging_face_dataset.HuggingFaceDatasetLoader.html"}
{"id": "23c4aeee6af5-1", "text": "load()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(path: str, page_content_column: str = 'text', name: Optional[str] = None, data_dir: Optional[str] = None, data_files: Optional[Union[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]]] = None, cache_dir: Optional[str] = None, keep_in_memory: Optional[bool] = None, save_infos: bool = False, use_auth_token: Optional[Union[bool, str]] = None, num_proc: Optional[int] = None)[source]\u00b6\nInitialize the HuggingFaceDatasetLoader.\nParameters\npath \u2013 Path or name of the dataset.\npage_content_column \u2013 Page content column name. Default is \u201ctext\u201d.\nNote: Currently the function assumes the content is a string.\nIf it is not download the dataset using huggingface library and convert\nusing the json or pandas loaders.\nhttps://github.com/langchain-ai/langchain/issues/10674\nname \u2013 Name of the dataset configuration.\ndata_dir \u2013 Data directory of the dataset configuration.\ndata_files \u2013 Path(s) to source data file(s).\ncache_dir \u2013 Directory to read/write data.\nkeep_in_memory \u2013 Whether to copy the dataset in-memory.\nsave_infos \u2013 Save the dataset information (checksums/size/splits/\u2026).\nDefault is False.\nuse_auth_token \u2013 Bearer token for remote files on the Dataset Hub.\nnum_proc \u2013 Number of processes.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLoad documents lazily.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.hugging_face_dataset.HuggingFaceDatasetLoader.html"}
{"id": "23c4aeee6af5-2", "text": "Load Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using HuggingFaceDatasetLoader\u00b6\nHuggingFace dataset", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.hugging_face_dataset.HuggingFaceDatasetLoader.html"}
{"id": "6145247f66c1-0", "text": "langchain.document_loaders.embaas.BaseEmbaasLoader\u00b6\nclass langchain.document_loaders.embaas.BaseEmbaasLoader[source]\u00b6\nBases: BaseModel\nBase loader for Embaas document extraction API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_url: str = 'https://api.embaas.io/v1/document/extract-text/bytes/'\u00b6\nThe URL of the Embaas document extraction API.\nparam embaas_api_key: Optional[str] = None\u00b6\nThe API key for the Embaas document extraction API.\nparam params: langchain.document_loaders.embaas.EmbaasDocumentExtractionParameters = {}\u00b6\nAdditional parameters to pass to the Embaas document extraction API.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.BaseEmbaasLoader.html"}
{"id": "6145247f66c1-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.BaseEmbaasLoader.html"}
{"id": "6145247f66c1-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.BaseEmbaasLoader.html"}
{"id": "ceee09be4ddd-0", "text": "langchain.document_loaders.airbyte.AirbyteShopifyLoader\u00b6\nclass langchain.document_loaders.airbyte.AirbyteShopifyLoader(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None)[source]\u00b6\nLoad from Shopify using an Airbyte source connector.\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nAttributes\nlast_state\nMethods\n__init__(config,\u00a0stream_name[,\u00a0...])\nInitializes the loader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None) \u2192 None[source]\u00b6\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad data into Document objects.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteShopifyLoader.html"}
{"id": "ceee09be4ddd-1", "text": "load() \u2192 List[Document]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AirbyteShopifyLoader\u00b6\nAirbyte Shopify", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteShopifyLoader.html"}
{"id": "e07b962197e9-0", "text": "langchain.document_loaders.geodataframe.GeoDataFrameLoader\u00b6\nclass langchain.document_loaders.geodataframe.GeoDataFrameLoader(data_frame: Any, page_content_column: str = 'geometry')[source]\u00b6\nLoad geopandas Dataframe.\nInitialize with geopandas Dataframe.\nParameters\ndata_frame \u2013 geopandas DataFrame object.\npage_content_column \u2013 Name of the column containing the page content.\nDefaults to \u201cgeometry\u201d.\nMethods\n__init__(data_frame[,\u00a0page_content_column])\nInitialize with geopandas Dataframe.\nlazy_load()\nLazy load records from dataframe.\nload()\nLoad full dataframe.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(data_frame: Any, page_content_column: str = 'geometry')[source]\u00b6\nInitialize with geopandas Dataframe.\nParameters\ndata_frame \u2013 geopandas DataFrame object.\npage_content_column \u2013 Name of the column containing the page content.\nDefaults to \u201cgeometry\u201d.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load records from dataframe.\nload() \u2192 List[Document][source]\u00b6\nLoad full dataframe.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using GeoDataFrameLoader\u00b6\nGeopandas", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.geodataframe.GeoDataFrameLoader.html"}
{"id": "7dff003674bd-0", "text": "langchain.document_loaders.onedrive.OneDriveLoader\u00b6\nclass langchain.document_loaders.onedrive.OneDriveLoader[source]\u00b6\nBases: O365BaseLoader\nLoad from Microsoft OneDrive.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam auth_with_token: bool = False\u00b6\nWhether to authenticate with a token or not. Defaults to False.\nparam chunk_size: Union[int, str] = 5242880\u00b6\nNumber of bytes to retrieve from each api call to the server. int or \u2018auto\u2019.\nparam drive_id: str [Required]\u00b6\nThe ID of the OneDrive drive to load data from.\nparam folder_path: Optional[str] = None\u00b6\nThe path to the folder to load data from.\nparam object_ids: Optional[List[str]] = None\u00b6\nThe IDs of the objects to load data from.\nparam settings: _O365Settings [Optional]\u00b6\nSettings for the Office365 API client.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.onedrive.OneDriveLoader.html"}
{"id": "7dff003674bd-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLoad documents lazily. Use this when working at a large scale.\nload() \u2192 List[Document][source]\u00b6\nLoad all documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.onedrive.OneDriveLoader.html"}
{"id": "7dff003674bd-2", "text": "load() \u2192 List[Document][source]\u00b6\nLoad all documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using OneDriveLoader\u00b6\nMicrosoft OneDrive", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.onedrive.OneDriveLoader.html"}
{"id": "6848344c7eec-0", "text": "langchain.document_loaders.googledrive.GoogleDriveLoader\u00b6\nclass langchain.document_loaders.googledrive.GoogleDriveLoader[source]\u00b6\nBases: BaseLoader, BaseModel\nLoad Google Docs from Google Drive.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam credentials_path: pathlib.Path = PosixPath('/home/docs/.credentials/credentials.json')\u00b6\nPath to the credentials file.\nparam document_ids: Optional[List[str]] = None\u00b6\nThe document ids to load from.\nparam file_ids: Optional[List[str]] = None\u00b6\nThe file ids to load from.\nparam file_loader_cls: Any = None\u00b6\nThe file loader class to use.\nparam file_loader_kwargs: Dict[str, Any] = {}\u00b6\nThe file loader kwargs to use.\nparam file_types: Optional[Sequence[str]] = None\u00b6\nThe file types to load. Only applies when folder_id is given.\nparam folder_id: Optional[str] = None\u00b6\nThe folder id to load from.\nparam load_trashed_files: bool = False\u00b6\nWhether to load trashed files. Only applies when folder_id is given.\nparam recursive: bool = False\u00b6\nWhether to load recursively. Only applies when folder_id is given.\nparam service_account_key: pathlib.Path = PosixPath('/home/docs/.credentials/keys.json')\u00b6\nPath to the service account key file.\nparam token_path: pathlib.Path = PosixPath('/home/docs/.credentials/token.json')\u00b6\nPath to the token file.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.googledrive.GoogleDriveLoader.html"}
{"id": "6848344c7eec-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.googledrive.GoogleDriveLoader.html"}
{"id": "6848344c7eec-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.googledrive.GoogleDriveLoader.html"}
{"id": "6848344c7eec-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using GoogleDriveLoader\u00b6\nGoogle Drive", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.googledrive.GoogleDriveLoader.html"}
{"id": "7afa020b2c42-0", "text": "langchain.document_loaders.apify_dataset.ApifyDatasetLoader\u00b6\nclass langchain.document_loaders.apify_dataset.ApifyDatasetLoader[source]\u00b6\nBases: BaseLoader, BaseModel\nLoad datasets from Apify web scraping, crawling, and data extraction platform.\nFor details, see https://docs.apify.com/platform/integrations/langchain\nExample\nfrom langchain.document_loaders import ApifyDatasetLoader\nfrom langchain.schema import Document\nloader = ApifyDatasetLoader(\n    dataset_id=\"YOUR-DATASET-ID\",\n    dataset_mapping_function=lambda dataset_item: Document(\n        page_content=dataset_item[\"text\"], metadata={\"source\": dataset_item[\"url\"]}\n    ),\n)\ndocuments = loader.load()\nInitialize the loader with an Apify dataset ID and a mapping function.\nParameters\ndataset_id (str) \u2013 The ID of the dataset on the Apify platform.\ndataset_mapping_function (Callable) \u2013 A function that takes a single\ndictionary (an Apify dataset item) and converts it to an instance\nof the Document class.\nparam apify_client: Any = None\u00b6\nAn instance of the ApifyClient class from the apify-client Python package.\nparam dataset_id: str [Required]\u00b6\nThe ID of the dataset on the Apify platform.\nparam dataset_mapping_function: Callable[[Dict], langchain.schema.document.Document] [Required]\u00b6\nA custom function that takes a single dictionary (an Apify dataset item)\nand converts it to an instance of the Document class.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.apify_dataset.ApifyDatasetLoader.html"}
{"id": "7afa020b2c42-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.apify_dataset.ApifyDatasetLoader.html"}
{"id": "7afa020b2c42-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.apify_dataset.ApifyDatasetLoader.html"}
{"id": "7afa020b2c42-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using ApifyDatasetLoader\u00b6\nApify\nApify Dataset", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.apify_dataset.ApifyDatasetLoader.html"}
{"id": "a42b73913211-0", "text": "langchain.document_loaders.github.GitHubIssuesLoader\u00b6\nclass langchain.document_loaders.github.GitHubIssuesLoader[source]\u00b6\nBases: BaseGitHubLoader\nLoad issues of a GitHub repository.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam access_token: str [Required]\u00b6\nPersonal access token - see https://github.com/settings/tokens?type=beta\nparam assignee: Optional[str] = None\u00b6\nFilter on assigned user. Pass \u2018none\u2019 for no user and \u2018*\u2019 for any user.\nparam creator: Optional[str] = None\u00b6\nFilter on the user that created the issue.\nparam direction: Optional[Literal['asc', 'desc']] = None\u00b6\nThe direction to sort the results by. Can be one of: \u2018asc\u2019, \u2018desc\u2019.\nparam github_api_url: str = 'https://api.github.com'\u00b6\nURL of GitHub API\nparam include_prs: bool = True\u00b6\nIf True include Pull Requests in results, otherwise ignore them.\nparam labels: Optional[List[str]] = None\u00b6\nLabel names to filter one. Example: bug,ui,@high.\nparam mentioned: Optional[str] = None\u00b6\nFilter on a user that\u2019s mentioned in the issue.\nparam milestone: Optional[Union[int, Literal['*', 'none']]] = None\u00b6\nIf integer is passed, it should be a milestone\u2019s number field.\nIf the string \u2018*\u2019 is passed, issues with any milestone are accepted.\nIf the string \u2018none\u2019 is passed, issues without milestones are returned.\nparam repo: str [Required]\u00b6\nName of repository\nparam since: Optional[str] = None\u00b6\nOnly show notifications updated after the given time.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.github.GitHubIssuesLoader.html"}
{"id": "a42b73913211-1", "text": "param since: Optional[str] = None\u00b6\nOnly show notifications updated after the given time.\nThis is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.\nparam sort: Optional[Literal['created', 'updated', 'comments']] = None\u00b6\nWhat to sort results by. Can be one of: \u2018created\u2019, \u2018updated\u2019, \u2018comments\u2019.\nDefault is \u2018created\u2019.\nparam state: Optional[Literal['open', 'closed', 'all']] = None\u00b6\nFilter on issue state. Can be one of: \u2018open\u2019, \u2018closed\u2019, \u2018all\u2019.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.github.GitHubIssuesLoader.html"}
{"id": "a42b73913211-2", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nGet issues of a GitHub repository.\nReturns\npage_content\nmetadata\nurl\ntitle\ncreator\ncreated_at\nlast_update_time\nclosed_time\nnumber of comments\nstate\nlabels\nassignee\nassignees\nmilestone\nlocked\nnumber\nis_pull_request\nReturn type\nA list of Documents with attributes\nload() \u2192 List[Document][source]\u00b6\nGet issues of a GitHub repository.\nReturns\npage_content\nmetadata\nurl\ntitle\ncreator\ncreated_at", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.github.GitHubIssuesLoader.html"}
{"id": "a42b73913211-3", "text": "Returns\npage_content\nmetadata\nurl\ntitle\ncreator\ncreated_at\nlast_update_time\nclosed_time\nnumber of comments\nstate\nlabels\nassignee\nassignees\nmilestone\nlocked\nnumber\nis_pull_request\nReturn type\nA list of Documents with attributes\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_issue(issue: dict) \u2192 Document[source]\u00b6\nCreate Document objects from a list of GitHub issues.\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty headers: Dict[str, str]\u00b6\nproperty query_params: str\u00b6\nCreate query parameters for GitHub API.\nproperty url: str\u00b6\nCreate URL for GitHub API.\nExamples using GitHubIssuesLoader\u00b6\nGitHub", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.github.GitHubIssuesLoader.html"}
{"id": "1b49ddbc0b6e-0", "text": "langchain.document_loaders.blob_loaders.file_system.FileSystemBlobLoader\u00b6\nclass langchain.document_loaders.blob_loaders.file_system.FileSystemBlobLoader(path: Union[str, Path], *, glob: str = '**/[!.]*', exclude: Sequence[str] = (), suffixes: Optional[Sequence[str]] = None, show_progress: bool = False)[source]\u00b6\nLoad blobs in the local file system.\nExample:\nfrom langchain.document_loaders.blob_loaders import FileSystemBlobLoader\nloader = FileSystemBlobLoader(\"/path/to/directory\")\nfor blob in loader.yield_blobs():\n    print(blob)\nInitialize with a path to directory and how to glob over it.\nParameters\npath \u2013 Path to directory to load from\nglob \u2013 Glob pattern relative to the specified path\nby default set to pick up all non-hidden files\nexclude \u2013 patterns to exclude from results, use glob syntax\nsuffixes \u2013 Provide to keep only files with these suffixes\nUseful when wanting to keep files with different suffixes\nSuffixes must include the dot, e.g. \u201c.txt\u201d\nshow_progress \u2013 If true, will show a progress bar as the files are loaded.\nThis forces an iteration through all matching files\nto count them prior to loading them.\nExamples\n# Recursively load all text files in a directory.\nloader = FileSystemBlobLoader(\"/path/to/directory\", glob=\"**/*.txt\")\n# Recursively load all non-hidden files in a directory.\nloader = FileSystemBlobLoader(\"/path/to/directory\", glob=\"**/[!.]*\")\n# Load all files in a directory without recursion.\nloader = FileSystemBlobLoader(\"/path/to/directory\", glob=\"*\")\n# Recursively load all files in a directory, except for py or pyc files.\nloader = FileSystemBlobLoader(\n    \"/path/to/directory\",\n    glob=\"**/*.txt\",", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blob_loaders.file_system.FileSystemBlobLoader.html"}
{"id": "1b49ddbc0b6e-1", "text": "\"/path/to/directory\",\n    glob=\"**/*.txt\",\n    exclude=[\"**/*.py\", \"**/*.pyc\"]\n)\nMethods\n__init__(path,\u00a0*[,\u00a0glob,\u00a0exclude,\u00a0suffixes,\u00a0...])\nInitialize with a path to directory and how to glob over it.\ncount_matching_files()\nCount files that match the pattern without loading them.\nyield_blobs()\nYield blobs that match the requested pattern.\n__init__(path: Union[str, Path], *, glob: str = '**/[!.]*', exclude: Sequence[str] = (), suffixes: Optional[Sequence[str]] = None, show_progress: bool = False) \u2192 None[source]\u00b6\nInitialize with a path to directory and how to glob over it.\nParameters\npath \u2013 Path to directory to load from\nglob \u2013 Glob pattern relative to the specified path\nby default set to pick up all non-hidden files\nexclude \u2013 patterns to exclude from results, use glob syntax\nsuffixes \u2013 Provide to keep only files with these suffixes\nUseful when wanting to keep files with different suffixes\nSuffixes must include the dot, e.g. \u201c.txt\u201d\nshow_progress \u2013 If true, will show a progress bar as the files are loaded.\nThis forces an iteration through all matching files\nto count them prior to loading them.\nExamples\n# Recursively load all text files in a directory.\nloader = FileSystemBlobLoader(\"/path/to/directory\", glob=\"**/*.txt\")\n# Recursively load all non-hidden files in a directory.\nloader = FileSystemBlobLoader(\"/path/to/directory\", glob=\"**/[!.]*\")\n# Load all files in a directory without recursion.\nloader = FileSystemBlobLoader(\"/path/to/directory\", glob=\"*\")\n# Recursively load all files in a directory, except for py or pyc files.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blob_loaders.file_system.FileSystemBlobLoader.html"}
{"id": "1b49ddbc0b6e-2", "text": "# Recursively load all files in a directory, except for py or pyc files.\nloader = FileSystemBlobLoader(\n    \"/path/to/directory\",\n    glob=\"**/*.txt\",\n    exclude=[\"**/*.py\", \"**/*.pyc\"]\n)\ncount_matching_files() \u2192 int[source]\u00b6\nCount files that match the pattern without loading them.\nyield_blobs() \u2192 Iterable[Blob][source]\u00b6\nYield blobs that match the requested pattern.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blob_loaders.file_system.FileSystemBlobLoader.html"}
{"id": "1680271c9fe4-0", "text": "langchain.document_loaders.unstructured.satisfies_min_unstructured_version\u00b6\nlangchain.document_loaders.unstructured.satisfies_min_unstructured_version(min_version: str) \u2192 bool[source]\u00b6\nCheck if the installed Unstructured version exceeds the minimum version\nfor the feature in question.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.unstructured.satisfies_min_unstructured_version.html"}
{"id": "04d9cdf0b4c6-0", "text": "langchain.document_loaders.assemblyai.AssemblyAIAudioTranscriptLoader\u00b6\nclass langchain.document_loaders.assemblyai.AssemblyAIAudioTranscriptLoader(file_path: str, *, transcript_format: TranscriptFormat = TranscriptFormat.TEXT, config: Optional[assemblyai.TranscriptionConfig] = None, api_key: Optional[str] = None)[source]\u00b6\nLoader for AssemblyAI audio transcripts.\nIt uses the AssemblyAI API to transcribe audio files\nand loads the transcribed text into one or more Documents,\ndepending on the specified format.\nTo use, you should have the assemblyai python package installed, and the\nenvironment variable ASSEMBLYAI_API_KEY set with your API key.\nAlternatively, the API key can also be passed as an argument.\nAudio files can be specified via an URL or a local file path.\nInitializes the AssemblyAI AudioTranscriptLoader.\nParameters\nfile_path \u2013 An URL or a local file path.\ntranscript_format \u2013 Transcript format to use.\nSee class TranscriptFormat for more info.\nconfig \u2013 Transcription options and features. If None is given,\nthe Transcriber\u2019s default configuration will be used.\napi_key \u2013 AssemblyAI API key.\nMethods\n__init__(file_path,\u00a0*[,\u00a0transcript_format,\u00a0...])\nInitializes the AssemblyAI AudioTranscriptLoader.\nlazy_load()\nA lazy loader for Documents.\nload()\nTranscribes the audio file and loads the transcript into documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, *, transcript_format: TranscriptFormat = TranscriptFormat.TEXT, config: Optional[assemblyai.TranscriptionConfig] = None, api_key: Optional[str] = None)[source]\u00b6\nInitializes the AssemblyAI AudioTranscriptLoader.\nParameters\nfile_path \u2013 An URL or a local file path.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.assemblyai.AssemblyAIAudioTranscriptLoader.html"}
{"id": "04d9cdf0b4c6-1", "text": "Parameters\nfile_path \u2013 An URL or a local file path.\ntranscript_format \u2013 Transcript format to use.\nSee class TranscriptFormat for more info.\nconfig \u2013 Transcription options and features. If None is given,\nthe Transcriber\u2019s default configuration will be used.\napi_key \u2013 AssemblyAI API key.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nTranscribes the audio file and loads the transcript into documents.\nIt uses the AssemblyAI API to transcribe the audio file and blocks until\nthe transcription is finished.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AssemblyAIAudioTranscriptLoader\u00b6\nAssemblyAI Audio Transcripts", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.assemblyai.AssemblyAIAudioTranscriptLoader.html"}
{"id": "0a4449a81ee2-0", "text": "langchain.document_loaders.unstructured.UnstructuredFileIOLoader\u00b6\nclass langchain.document_loaders.unstructured.UnstructuredFileIOLoader(file: Union[IO, Sequence[IO]], mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad files using Unstructured.\nThe file loader\nuses the unstructured partition function and will automatically detect the file\ntype. You can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredFileIOLoader\nwith open(\u201cexample.pdf\u201d, \u201crb\u201d) as f:\nloader = UnstructuredFileIOLoader(f, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition\nInitialize with file path.\nMethods\n__init__(file[,\u00a0mode])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file: Union[IO, Sequence[IO]], mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.unstructured.UnstructuredFileIOLoader.html"}
{"id": "0a4449a81ee2-1", "text": "Load Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredFileIOLoader\u00b6\nGoogle Drive", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.unstructured.UnstructuredFileIOLoader.html"}
{"id": "741343e573eb-0", "text": "langchain.document_loaders.dataframe.DataFrameLoader\u00b6\nclass langchain.document_loaders.dataframe.DataFrameLoader(data_frame: Any, page_content_column: str = 'text')[source]\u00b6\nLoad Pandas DataFrame.\nInitialize with dataframe object.\nParameters\ndata_frame \u2013 Pandas DataFrame object.\npage_content_column \u2013 Name of the column containing the page content.\nDefaults to \u201ctext\u201d.\nMethods\n__init__(data_frame[,\u00a0page_content_column])\nInitialize with dataframe object.\nlazy_load()\nLazy load records from dataframe.\nload()\nLoad full dataframe.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(data_frame: Any, page_content_column: str = 'text')[source]\u00b6\nInitialize with dataframe object.\nParameters\ndata_frame \u2013 Pandas DataFrame object.\npage_content_column \u2013 Name of the column containing the page content.\nDefaults to \u201ctext\u201d.\nlazy_load() \u2192 Iterator[Document]\u00b6\nLazy load records from dataframe.\nload() \u2192 List[Document]\u00b6\nLoad full dataframe.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using DataFrameLoader\u00b6\nPandas DataFrame", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.dataframe.DataFrameLoader.html"}
{"id": "60c45d83b5c5-0", "text": "langchain.document_loaders.notebook.concatenate_cells\u00b6\nlangchain.document_loaders.notebook.concatenate_cells(cell: dict, include_outputs: bool, max_output_length: int, traceback: bool) \u2192 str[source]\u00b6\nCombine cells information in a readable format ready to be used.\nParameters\ncell \u2013 A dictionary\ninclude_outputs \u2013 Whether to include the outputs of the cell.\nmax_output_length \u2013 Maximum length of the output to be displayed.\ntraceback \u2013 Whether to return a traceback of the error.\nReturns\nA string with the cell information.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.notebook.concatenate_cells.html"}
{"id": "a3e08bad8ab1-0", "text": "langchain.document_loaders.parsers.pdf.extract_from_images_with_rapidocr\u00b6\nlangchain.document_loaders.parsers.pdf.extract_from_images_with_rapidocr(images: Sequence[Union[Iterable[ndarray], bytes]]) \u2192 str[source]\u00b6\nExtract text from images with RapidOCR.\nParameters\nimages \u2013 Images to extract text from.\nReturns\nText extracted from images.\nRaises\nImportError \u2013 If rapidocr-onnxruntime package is not installed.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.pdf.extract_from_images_with_rapidocr.html"}
{"id": "9397b3583850-0", "text": "langchain.document_loaders.pdf.AmazonTextractPDFLoader\u00b6\nclass langchain.document_loaders.pdf.AmazonTextractPDFLoader(file_path: str, textract_features: Optional[Sequence[str]] = None, client: Optional[Any] = None, credentials_profile_name: Optional[str] = None, region_name: Optional[str] = None, endpoint_url: Optional[str] = None, headers: Optional[Dict] = None)[source]\u00b6\nLoad PDF files from a local file system, HTTP or S3.\nTo authenticate, the AWS client uses the following methods to\nautomatically load credentials:\nhttps://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\nIf a specific credential profile should be used, you must pass\nthe name of the profile from the ~/.aws/credentials file that is to be used.\nMake sure the credentials / roles used have the required policies to\naccess the Amazon Textract service.\nExample\nInitialize the loader.\nParameters\nfile_path \u2013 A file, url or s3 path for input file\ntextract_features \u2013 Features to be used for extraction, each feature\nshould be passed as a str that conforms to the enum\nTextract_Features, see amazon-textract-caller pkg\nclient \u2013 boto3 textract client (Optional)\ncredentials_profile_name \u2013 AWS profile name, if not default (Optional)\nregion_name \u2013 AWS region, eg us-east-1 (Optional)\nendpoint_url \u2013 endpoint url for the textract service (Optional)\nAttributes\nsource\nMethods\n__init__(file_path[,\u00a0textract_features,\u00a0...])\nInitialize the loader.\nlazy_load()\nLazy load documents\nload()\nLoad given path as pages.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.AmazonTextractPDFLoader.html"}
{"id": "9397b3583850-1", "text": "load_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, textract_features: Optional[Sequence[str]] = None, client: Optional[Any] = None, credentials_profile_name: Optional[str] = None, region_name: Optional[str] = None, endpoint_url: Optional[str] = None, headers: Optional[Dict] = None) \u2192 None[source]\u00b6\nInitialize the loader.\nParameters\nfile_path \u2013 A file, url or s3 path for input file\ntextract_features \u2013 Features to be used for extraction, each feature\nshould be passed as a str that conforms to the enum\nTextract_Features, see amazon-textract-caller pkg\nclient \u2013 boto3 textract client (Optional)\ncredentials_profile_name \u2013 AWS profile name, if not default (Optional)\nregion_name \u2013 AWS region, eg us-east-1 (Optional)\nendpoint_url \u2013 endpoint url for the textract service (Optional)\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load documents\nload() \u2192 List[Document][source]\u00b6\nLoad given path as pages.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AmazonTextractPDFLoader\u00b6\nAmazon Textract", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.AmazonTextractPDFLoader.html"}
{"id": "d17c4cfe304d-0", "text": "langchain.document_loaders.unstructured.UnstructuredFileLoader\u00b6\nclass langchain.document_loaders.unstructured.UnstructuredFileLoader(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad files using Unstructured.\nThe file loader uses the\nunstructured partition function and will automatically detect the file\ntype. You can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredFileLoader\nloader = UnstructuredFileLoader(\u201cexample.pdf\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition\nInitialize with file path.\nMethods\n__init__(file_path[,\u00a0mode])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.unstructured.UnstructuredFileLoader.html"}
{"id": "d17c4cfe304d-1", "text": "Load Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredFileLoader\u00b6\nUnstructured\nUnstructured File", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.unstructured.UnstructuredFileLoader.html"}
{"id": "895801f50466-0", "text": "langchain.document_loaders.pdf.BasePDFLoader\u00b6\nclass langchain.document_loaders.pdf.BasePDFLoader(file_path: str, *, headers: Optional[Dict] = None)[source]\u00b6\nBase Loader class for PDF files.\nIf the file is a web path, it will download it to a temporary file, use it, thenclean up the temporary file after completion.\nInitialize with a file path.\nParameters\nfile_path \u2013 Either a local, S3 or web path to a PDF file.\nheaders \u2013 Headers to use for GET request to download a file from a web path.\nAttributes\nsource\nMethods\n__init__(file_path,\u00a0*[,\u00a0headers])\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, *, headers: Optional[Dict] = None)[source]\u00b6\nInitialize with a file path.\nParameters\nfile_path \u2013 Either a local, S3 or web path to a PDF file.\nheaders \u2013 Headers to use for GET request to download a file from a web path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nabstract load() \u2192 List[Document]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.BasePDFLoader.html"}
{"id": "da3095eb36cc-0", "text": "langchain.document_loaders.pdf.PDFMinerPDFasHTMLLoader\u00b6\nclass langchain.document_loaders.pdf.PDFMinerPDFasHTMLLoader(file_path: str, *, headers: Optional[Dict] = None)[source]\u00b6\nLoad PDF files as HTML content using PDFMiner.\nInitialize with a file path.\nAttributes\nsource\nMethods\n__init__(file_path,\u00a0*[,\u00a0headers])\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, *, headers: Optional[Dict] = None)[source]\u00b6\nInitialize with a file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.PDFMinerPDFasHTMLLoader.html"}
{"id": "0ab446d04231-0", "text": "langchain.document_loaders.unstructured.validate_unstructured_version\u00b6\nlangchain.document_loaders.unstructured.validate_unstructured_version(min_unstructured_version: str) \u2192 None[source]\u00b6\nRaise an error if the Unstructured version does not exceed the\nspecified minimum.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.unstructured.validate_unstructured_version.html"}
{"id": "4f741b82fc39-0", "text": "langchain.document_loaders.parsers.pdf.PDFMinerParser\u00b6\nclass langchain.document_loaders.parsers.pdf.PDFMinerParser(extract_images: bool = False, *, concatenate_pages: bool = True)[source]\u00b6\nParse PDF using PDFMiner.\nInitialize a parser based on PDFMiner.\nParameters\nextract_images \u2013 Whether to extract images from PDF.\nconcatenate_pages \u2013 If True, concatenate all PDF pages into one a single\ndocument. Otherwise, return one document per page.\nMethods\n__init__([extract_images,\u00a0concatenate_pages])\nInitialize a parser based on PDFMiner.\nlazy_parse(blob)\nLazily parse the blob.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__(extract_images: bool = False, *, concatenate_pages: bool = True)[source]\u00b6\nInitialize a parser based on PDFMiner.\nParameters\nextract_images \u2013 Whether to extract images from PDF.\nconcatenate_pages \u2013 If True, concatenate all PDF pages into one a single\ndocument. Otherwise, return one document per page.\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLazily parse the blob.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.pdf.PDFMinerParser.html"}
{"id": "b9f0c9428031-0", "text": "langchain.document_loaders.dropbox.DropboxLoader\u00b6\nclass langchain.document_loaders.dropbox.DropboxLoader[source]\u00b6\nBases: BaseLoader, BaseModel\nLoad files from Dropbox.\nIn addition to common files such as text and PDF files, it also supports\nDropbox Paper files.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam dropbox_access_token: str [Required]\u00b6\nDropbox access token.\nparam dropbox_file_paths: Optional[List[str]] = None\u00b6\nThe file paths to load from.\nparam dropbox_folder_path: Optional[str] = None\u00b6\nThe folder path to load from.\nparam recursive: bool = False\u00b6\nFlag to indicate whether to load files recursively from subfolders.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.dropbox.DropboxLoader.html"}
{"id": "b9f0c9428031-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.dropbox.DropboxLoader.html"}
{"id": "b9f0c9428031-2", "text": "Defaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using DropboxLoader\u00b6\nDropbox", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.dropbox.DropboxLoader.html"}
{"id": "8e926cc3e5db-0", "text": "langchain.document_loaders.pubmed.PubMedLoader\u00b6\nclass langchain.document_loaders.pubmed.PubMedLoader(query: str, load_max_docs: Optional[int] = 3)[source]\u00b6\nLoad from the PubMed biomedical library.\nquery\u00b6\nThe query to be passed to the PubMed API.\nload_max_docs\u00b6\nThe maximum number of documents to load.\nInitialize the PubMedLoader.\nParameters\nquery \u2013 The query to be passed to the PubMed API.\nload_max_docs \u2013 The maximum number of documents to load.\nDefaults to 3.\nMethods\n__init__(query[,\u00a0load_max_docs])\nInitialize the PubMedLoader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(query: str, load_max_docs: Optional[int] = 3)[source]\u00b6\nInitialize the PubMedLoader.\nParameters\nquery \u2013 The query to be passed to the PubMed API.\nload_max_docs \u2013 The maximum number of documents to load.\nDefaults to 3.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using PubMedLoader\u00b6\nPubMed", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pubmed.PubMedLoader.html"}
{"id": "1a21a80d2e02-0", "text": "langchain.document_loaders.youtube.GoogleApiYoutubeLoader\u00b6\nclass langchain.document_loaders.youtube.GoogleApiYoutubeLoader(google_api_client: GoogleApiClient, channel_name: Optional[str] = None, video_ids: Optional[List[str]] = None, add_video_info: bool = True, captions_language: str = 'en', continue_on_failure: bool = False)[source]\u00b6\nLoad all Videos from a YouTube Channel.\nTo use, you should have the googleapiclient,youtube_transcript_api\npython package installed.\nAs the service needs a google_api_client, you first have to initialize\nthe GoogleApiClient.\nAdditionally you have to either provide a channel name or a list of videoids\n\u201chttps://developers.google.com/docs/api/quickstart/python\u201d\nExample\nfrom langchain.document_loaders import GoogleApiClient\nfrom langchain.document_loaders import GoogleApiYoutubeLoader\ngoogle_api_client = GoogleApiClient(\n    service_account_path=Path(\"path_to_your_sec_file.json\")\n)\nloader = GoogleApiYoutubeLoader(\n    google_api_client=google_api_client,\n    channel_name = \"CodeAesthetic\"\n)\nload.load()\nAttributes\nadd_video_info\ncaptions_language\nchannel_name\ncontinue_on_failure\nvideo_ids\ngoogle_api_client\nMethods\n__init__(google_api_client[,\u00a0channel_name,\u00a0...])\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nvalidate_channel_or_videoIds_is_set(values)\nValidate that either folder_id or document_ids is set, but not both.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.youtube.GoogleApiYoutubeLoader.html"}
{"id": "1a21a80d2e02-1", "text": "Validate that either folder_id or document_ids is set, but not both.\n__init__(google_api_client: GoogleApiClient, channel_name: Optional[str] = None, video_ids: Optional[List[str]] = None, add_video_info: bool = True, captions_language: str = 'en', continue_on_failure: bool = False) \u2192 None\u00b6\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nclassmethod validate_channel_or_videoIds_is_set(values: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nValidate that either folder_id or document_ids is set, but not both.\nExamples using GoogleApiYoutubeLoader\u00b6\nYouTube\nYouTube transcripts", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.youtube.GoogleApiYoutubeLoader.html"}
{"id": "5b081da61ddd-0", "text": "langchain.document_loaders.parsers.pdf.AmazonTextractPDFParser\u00b6\nclass langchain.document_loaders.parsers.pdf.AmazonTextractPDFParser(textract_features: Optional[Sequence[int]] = None, client: Optional[Any] = None)[source]\u00b6\nSend PDF files to Amazon Textract and parse them.\nFor parsing multi-page PDFs, they have to reside on S3.\nThe AmazonTextractPDFLoader calls the\n[Amazon Textract Service](https://aws.amazon.com/textract/)\nto convert PDFs into a Document structure.\nSingle and multi-page documents are supported with up to 3000 pages\nand 512 MB of size.\nFor the call to be successful an AWS account is required,\nsimilar to the\n[AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)\nrequirements.\nBesides the AWS configuration, it is very similar to the other PDF\nloaders, while also supporting JPEG, PNG and TIFF and non-native\nPDF formats.\n`python\nfrom langchain.document_loaders import AmazonTextractPDFLoader\nloader=AmazonTextractPDFLoader(\"example_data/alejandro_rosalez_sample-small.jpeg\")\ndocuments = loader.load()\n`\nOne feature is the linearization of the output.\nWhen using the features LAYOUT, FORMS or TABLES together with Textract\n```python\nfrom langchain.document_loaders import AmazonTextractPDFLoader\n# you can mix and match each of the features\nloader=AmazonTextractPDFLoader(\n\u201cexample_data/alejandro_rosalez_sample-small.jpeg\u201d,\ntextract_features=[\u201cTABLES\u201d, \u201cLAYOUT\u201d])\ndocuments = loader.load()\n```\nit will generate output that formats the text in reading order and\ntry to output the information in a tabular structure or\noutput the key/value pairs with a colon (key: value).", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.pdf.AmazonTextractPDFParser.html"}
{"id": "5b081da61ddd-1", "text": "output the key/value pairs with a colon (key: value).\nThis helps most LLMs to achieve better accuracy when\nprocessing these texts.\nInitializes the parser.\nParameters\ntextract_features \u2013 Features to be used for extraction, each feature\nshould be passed as an int that conforms to the enum\nTextract_Features, see amazon-textract-caller pkg\nclient \u2013 boto3 textract client\nMethods\n__init__([textract_features,\u00a0client])\nInitializes the parser.\nlazy_parse(blob)\nIterates over the Blob pages and returns an Iterator with a Document for each page, like the other parsers If multi-page document, blob.path has to be set to the S3 URI and for single page docs the blob.data is taken\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__(textract_features: Optional[Sequence[int]] = None, client: Optional[Any] = None) \u2192 None[source]\u00b6\nInitializes the parser.\nParameters\ntextract_features \u2013 Features to be used for extraction, each feature\nshould be passed as an int that conforms to the enum\nTextract_Features, see amazon-textract-caller pkg\nclient \u2013 boto3 textract client\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nIterates over the Blob pages and returns an Iterator with a Document\nfor each page, like the other parsers If multi-page document, blob.path\nhas to be set to the S3 URI and for single page docs\nthe blob.data is taken\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.pdf.AmazonTextractPDFParser.html"}
{"id": "597d54c93086-0", "text": "langchain.document_loaders.airbyte_json.AirbyteJSONLoader\u00b6\nclass langchain.document_loaders.airbyte_json.AirbyteJSONLoader(file_path: str)[source]\u00b6\nLoad local Airbyte json files.\nInitialize with a file path. This should start with \u2018/tmp/airbyte_local/\u2019.\nAttributes\nfile_path\nPath to the directory containing the json files.\nMethods\n__init__(file_path)\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str)[source]\u00b6\nInitialize with a file path. This should start with \u2018/tmp/airbyte_local/\u2019.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AirbyteJSONLoader\u00b6\nAirbyte\nAirbyte JSON", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte_json.AirbyteJSONLoader.html"}
{"id": "5799583ccf0c-0", "text": "langchain.document_loaders.gcs_directory.GCSDirectoryLoader\u00b6\nclass langchain.document_loaders.gcs_directory.GCSDirectoryLoader(project_name: str, bucket: str, prefix: str = '', loader_func: Optional[Callable[[str], BaseLoader]] = None)[source]\u00b6\nLoad from GCS directory.\nInitialize with bucket and key name.\nParameters\nproject_name \u2013 The ID of the project for the GCS bucket.\nbucket \u2013 The name of the GCS bucket.\nprefix \u2013 The prefix of the GCS bucket.\nloader_func \u2013 A loader function that instantiates a loader based on a\nfile_path argument. If nothing is provided, the  GCSFileLoader\nwould use its default loader.\nMethods\n__init__(project_name,\u00a0bucket[,\u00a0prefix,\u00a0...])\nInitialize with bucket and key name.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(project_name: str, bucket: str, prefix: str = '', loader_func: Optional[Callable[[str], BaseLoader]] = None)[source]\u00b6\nInitialize with bucket and key name.\nParameters\nproject_name \u2013 The ID of the project for the GCS bucket.\nbucket \u2013 The name of the GCS bucket.\nprefix \u2013 The prefix of the GCS bucket.\nloader_func \u2013 A loader function that instantiates a loader based on a\nfile_path argument. If nothing is provided, the  GCSFileLoader\nwould use its default loader.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.gcs_directory.GCSDirectoryLoader.html"}
{"id": "5799583ccf0c-1", "text": "Load Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using GCSDirectoryLoader\u00b6\nGoogle Cloud Storage\nGoogle Cloud Storage Directory", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.gcs_directory.GCSDirectoryLoader.html"}
{"id": "c0b5e56ee524-0", "text": "langchain.document_loaders.github.BaseGitHubLoader\u00b6\nclass langchain.document_loaders.github.BaseGitHubLoader[source]\u00b6\nBases: BaseLoader, BaseModel, ABC\nLoad GitHub repository Issues.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam access_token: str [Required]\u00b6\nPersonal access token - see https://github.com/settings/tokens?type=beta\nparam github_api_url: str = 'https://api.github.com'\u00b6\nURL of GitHub API\nparam repo: str [Required]\u00b6\nName of repository\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.github.BaseGitHubLoader.html"}
{"id": "c0b5e56ee524-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nabstract load() \u2192 List[Document]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.github.BaseGitHubLoader.html"}
{"id": "c0b5e56ee524-2", "text": "Defaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty headers: Dict[str, str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.github.BaseGitHubLoader.html"}
{"id": "619fdb59fe90-0", "text": "langchain.document_loaders.telegram.text_to_docs\u00b6\nlangchain.document_loaders.telegram.text_to_docs(text: Union[str, List[str]]) \u2192 List[Document][source]\u00b6\nConvert a string or list of strings to a list of Documents with metadata.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.telegram.text_to_docs.html"}
{"id": "5f8b93294a92-0", "text": "langchain.document_loaders.conllu.CoNLLULoader\u00b6\nclass langchain.document_loaders.conllu.CoNLLULoader(file_path: str)[source]\u00b6\nLoad CoNLL-U files.\nInitialize with a file path.\nMethods\n__init__(file_path)\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad from a file path.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str)[source]\u00b6\nInitialize with a file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad from a file path.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using CoNLLULoader\u00b6\nCoNLL-U", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.conllu.CoNLLULoader.html"}
{"id": "36f158257b4c-0", "text": "langchain.document_loaders.larksuite.LarkSuiteDocLoader\u00b6\nclass langchain.document_loaders.larksuite.LarkSuiteDocLoader(domain: str, access_token: str, document_id: str)[source]\u00b6\nLoad from LarkSuite (FeiShu).\nInitialize with domain, access_token (tenant / user), and document_id.\nParameters\ndomain \u2013 The domain to load the LarkSuite.\naccess_token \u2013 The access_token to use.\ndocument_id \u2013 The document_id to load.\nMethods\n__init__(domain,\u00a0access_token,\u00a0document_id)\nInitialize with domain, access_token (tenant / user), and document_id.\nlazy_load()\nLazy load LarkSuite (FeiShu) document.\nload()\nLoad LarkSuite (FeiShu) document.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(domain: str, access_token: str, document_id: str)[source]\u00b6\nInitialize with domain, access_token (tenant / user), and document_id.\nParameters\ndomain \u2013 The domain to load the LarkSuite.\naccess_token \u2013 The access_token to use.\ndocument_id \u2013 The document_id to load.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load LarkSuite (FeiShu) document.\nload() \u2192 List[Document][source]\u00b6\nLoad LarkSuite (FeiShu) document.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using LarkSuiteDocLoader\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.larksuite.LarkSuiteDocLoader.html"}
{"id": "36f158257b4c-1", "text": "Returns\nList of Documents.\nExamples using LarkSuiteDocLoader\u00b6\nLarkSuite (FeiShu)", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.larksuite.LarkSuiteDocLoader.html"}
{"id": "12920ccf165c-0", "text": "langchain.document_loaders.unstructured.UnstructuredAPIFileIOLoader\u00b6\nclass langchain.document_loaders.unstructured.UnstructuredAPIFileIOLoader(file: Union[IO, Sequence[IO]], mode: str = 'single', url: str = 'https://api.unstructured.io/general/v0/general', api_key: str = '', **unstructured_kwargs: Any)[source]\u00b6\nLoad files using Unstructured API.\nBy default, the loader makes a call to the hosted Unstructured API.\nIf you are running the unstructured API locally, you can change the\nAPI rule by passing in the url parameter when you initialize the loader.\nThe hosted Unstructured API requires an API key. See\nhttps://www.unstructured.io/api-key/ if you need to generate a key.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredAPIFileLoader\nwith open(\u201cexample.pdf\u201d, \u201crb\u201d) as f:\nloader = UnstructuredFileAPILoader(f, mode=\u201delements\u201d, strategy=\u201dfast\u201d, api_key=\u201dMY_API_KEY\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition\nhttps://www.unstructured.io/api-key/\nhttps://github.com/Unstructured-IO/unstructured-api\nInitialize with file path.\nMethods\n__init__(file[,\u00a0mode,\u00a0url,\u00a0api_key])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.unstructured.UnstructuredAPIFileIOLoader.html"}
{"id": "12920ccf165c-1", "text": "Initialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file: Union[IO, Sequence[IO]], mode: str = 'single', url: str = 'https://api.unstructured.io/general/v0/general', api_key: str = '', **unstructured_kwargs: Any)[source]\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.unstructured.UnstructuredAPIFileIOLoader.html"}
{"id": "7b79db825667-0", "text": "langchain.document_loaders.ifixit.IFixitLoader\u00b6\nclass langchain.document_loaders.ifixit.IFixitLoader(web_path: str)[source]\u00b6\nLoad iFixit repair guides, device wikis and answers.\niFixit is the largest, open repair community on the web. The site contains nearly\n100k repair manuals, 200k Questions & Answers on 42k devices, and all the data is\nlicensed under CC-BY.\nThis loader will allow you to download the text of a repair guide, text of Q&A\u2019s\nand wikis from devices on iFixit using their open APIs and web scraping.\nInitialize with a web path.\nMethods\n__init__(web_path)\nInitialize with a web path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nload_device([url_override,\u00a0include_guides])\nLoads a device\nload_guide([url_override])\nLoad a guide\nload_questions_and_answers([url_override])\nLoad a list of questions and answers.\nload_suggestions([query,\u00a0doc_type])\nLoad suggestions.\n__init__(web_path: str)[source]\u00b6\nInitialize with a web path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.ifixit.IFixitLoader.html"}
{"id": "7b79db825667-1", "text": "Defaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nload_device(url_override: Optional[str] = None, include_guides: bool = True) \u2192 List[Document][source]\u00b6\nLoads a device\nParameters\nurl_override \u2013 A URL to override the default URL.\ninclude_guides \u2013 Whether to include guides linked to from the device.\nDefaults to True.\nReturns:\nload_guide(url_override: Optional[str] = None) \u2192 List[Document][source]\u00b6\nLoad a guide\nParameters\nurl_override \u2013 A URL to override the default URL.\nReturns: List[Document]\nload_questions_and_answers(url_override: Optional[str] = None) \u2192 List[Document][source]\u00b6\nLoad a list of questions and answers.\nParameters\nurl_override \u2013 A URL to override the default URL.\nReturns: List[Document]\nstatic load_suggestions(query: str = '', doc_type: str = 'all') \u2192 List[Document][source]\u00b6\nLoad suggestions.\nParameters\nquery \u2013 A query string\ndoc_type \u2013 The type of document to search for. Can be one of \u201call\u201d,\n\u201cdevice\u201d, \u201cguide\u201d, \u201cteardown\u201d, \u201canswer\u201d, \u201cwiki\u201d.\nReturns:\nExamples using IFixitLoader\u00b6\niFixit", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.ifixit.IFixitLoader.html"}
{"id": "f2f0b3f04b49-0", "text": "langchain.document_loaders.facebook_chat.concatenate_rows\u00b6\nlangchain.document_loaders.facebook_chat.concatenate_rows(row: dict) \u2192 str[source]\u00b6\nCombine message information in a readable format ready to be used.\nParameters\nrow \u2013 dictionary containing message information.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.facebook_chat.concatenate_rows.html"}
{"id": "3b17823e9312-0", "text": "langchain.document_loaders.pdf.OnlinePDFLoader\u00b6\nclass langchain.document_loaders.pdf.OnlinePDFLoader(file_path: str, *, headers: Optional[Dict] = None)[source]\u00b6\nLoad online PDF.\nInitialize with a file path.\nParameters\nfile_path \u2013 Either a local, S3 or web path to a PDF file.\nheaders \u2013 Headers to use for GET request to download a file from a web path.\nAttributes\nsource\nMethods\n__init__(file_path,\u00a0*[,\u00a0headers])\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, *, headers: Optional[Dict] = None)\u00b6\nInitialize with a file path.\nParameters\nfile_path \u2013 Either a local, S3 or web path to a PDF file.\nheaders \u2013 Headers to use for GET request to download a file from a web path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.OnlinePDFLoader.html"}
{"id": "3619357ce9f9-0", "text": "langchain.document_loaders.brave_search.BraveSearchLoader\u00b6\nclass langchain.document_loaders.brave_search.BraveSearchLoader(query: str, api_key: str, search_kwargs: Optional[dict] = None)[source]\u00b6\nLoad with Brave Search engine.\nInitializes the BraveLoader.\nParameters\nquery \u2013 The query to search for.\napi_key \u2013 The API key to use.\nsearch_kwargs \u2013 The search kwargs to use.\nMethods\n__init__(query,\u00a0api_key[,\u00a0search_kwargs])\nInitializes the BraveLoader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(query: str, api_key: str, search_kwargs: Optional[dict] = None)[source]\u00b6\nInitializes the BraveLoader.\nParameters\nquery \u2013 The query to search for.\napi_key \u2013 The API key to use.\nsearch_kwargs \u2013 The search kwargs to use.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using BraveSearchLoader\u00b6\nBrave Search", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.brave_search.BraveSearchLoader.html"}
{"id": "8ae5c0149203-0", "text": "langchain.document_loaders.pdf.UnstructuredPDFLoader\u00b6\nclass langchain.document_loaders.pdf.UnstructuredPDFLoader(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad PDF files using Unstructured.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredPDFLoader\nloader = UnstructuredPDFLoader(\u201cexample.pdf\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition-pdf\nInitialize with file path.\nMethods\n__init__(file_path[,\u00a0mode])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.UnstructuredPDFLoader.html"}
{"id": "5d19f4d44a5c-0", "text": "langchain.document_loaders.toml.TomlLoader\u00b6\nclass langchain.document_loaders.toml.TomlLoader(source: Union[str, Path])[source]\u00b6\nLoad TOML files.\nIt can load a single source file or several files in a single\ndirectory.\nInitialize the TomlLoader with a source file or directory.\nMethods\n__init__(source)\nInitialize the TomlLoader with a source file or directory.\nlazy_load()\nLazily load the TOML documents from the source file or directory.\nload()\nLoad and return all documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(source: Union[str, Path])[source]\u00b6\nInitialize the TomlLoader with a source file or directory.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazily load the TOML documents from the source file or directory.\nload() \u2192 List[Document][source]\u00b6\nLoad and return all documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using TomlLoader\u00b6\nTOML", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.toml.TomlLoader.html"}
{"id": "d0b44eae0520-0", "text": "langchain.document_loaders.image.UnstructuredImageLoader\u00b6\nclass langchain.document_loaders.image.UnstructuredImageLoader(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad PNG and JPG files using Unstructured.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredImageLoader\nloader = UnstructuredImageLoader(\u201cexample.png\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition-image\nInitialize with file path.\nMethods\n__init__(file_path[,\u00a0mode])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.image.UnstructuredImageLoader.html"}
{"id": "d0b44eae0520-1", "text": "Defaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredImageLoader\u00b6\nImages", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.image.UnstructuredImageLoader.html"}
{"id": "bfd72607bfa1-0", "text": "langchain.document_loaders.pdf.DocumentIntelligenceLoader\u00b6\nclass langchain.document_loaders.pdf.DocumentIntelligenceLoader(file_path: str, client: Any, model: str = 'prebuilt-document', headers: Optional[Dict] = None)[source]\u00b6\nLoads a PDF with Azure Document Intelligence\nInitialize the object for file processing with Azure Document Intelligence\n(formerly Form Recognizer).\nThis constructor initializes a DocumentIntelligenceParser object to be used\nfor parsing files using the Azure Document Intelligence API. The load method\ngenerates a Document node including metadata (source blob and page number)\nfor each page.\nfile_pathstrThe path to the file that needs to be parsed.\nclient: AnyA DocumentAnalysisClient to perform the analysis of the blob\nmodelstrThe model name or ID to be used for form recognition in Azure.\n>>> obj = DocumentIntelligenceLoader(\n...     file_path=\"path/to/file\",\n...     client=client,\n...     model=\"prebuilt-document\"\n... )\nAttributes\nsource\nMethods\n__init__(file_path,\u00a0client[,\u00a0model,\u00a0headers])\nInitialize the object for file processing with Azure Document Intelligence (formerly Form Recognizer).\nlazy_load()\nLazy load given path as pages.\nload()\nLoad given path as pages.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, client: Any, model: str = 'prebuilt-document', headers: Optional[Dict] = None) \u2192 None[source]\u00b6\nInitialize the object for file processing with Azure Document Intelligence\n(formerly Form Recognizer).\nThis constructor initializes a DocumentIntelligenceParser object to be used\nfor parsing files using the Azure Document Intelligence API. The load method\ngenerates a Document node including metadata (source blob and page number)\nfor each page.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.DocumentIntelligenceLoader.html"}
{"id": "bfd72607bfa1-1", "text": "generates a Document node including metadata (source blob and page number)\nfor each page.\nfile_pathstrThe path to the file that needs to be parsed.\nclient: AnyA DocumentAnalysisClient to perform the analysis of the blob\nmodelstrThe model name or ID to be used for form recognition in Azure.\n>>> obj = DocumentIntelligenceLoader(\n...     file_path=\"path/to/file\",\n...     client=client,\n...     model=\"prebuilt-document\"\n... )\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load given path as pages.\nload() \u2192 List[Document][source]\u00b6\nLoad given path as pages.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using DocumentIntelligenceLoader\u00b6\nAzure Document Intelligence", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.DocumentIntelligenceLoader.html"}
{"id": "9a492bf3baab-0", "text": "langchain.document_loaders.azure_blob_storage_file.AzureBlobStorageFileLoader\u00b6\nclass langchain.document_loaders.azure_blob_storage_file.AzureBlobStorageFileLoader(conn_str: str, container: str, blob_name: str)[source]\u00b6\nLoad from Azure Blob Storage files.\nInitialize with connection string, container and blob name.\nAttributes\nconn_str\nConnection string for Azure Blob Storage.\ncontainer\nContainer name.\nblob\nBlob name.\nMethods\n__init__(conn_str,\u00a0container,\u00a0blob_name)\nInitialize with connection string, container and blob name.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(conn_str: str, container: str, blob_name: str)[source]\u00b6\nInitialize with connection string, container and blob name.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AzureBlobStorageFileLoader\u00b6\nAzure Blob Storage\nAzure Blob Storage File", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.azure_blob_storage_file.AzureBlobStorageFileLoader.html"}
{"id": "5affba5ec3fc-0", "text": "langchain.document_loaders.merge.MergedDataLoader\u00b6\nclass langchain.document_loaders.merge.MergedDataLoader(loaders: List)[source]\u00b6\nMerge documents from a list of loaders\nInitialize with a list of loaders\nMethods\n__init__(loaders)\nInitialize with a list of loaders\nlazy_load()\nLazy load docs from each individual loader.\nload()\nLoad docs.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(loaders: List)[source]\u00b6\nInitialize with a list of loaders\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load docs from each individual loader.\nload() \u2192 List[Document][source]\u00b6\nLoad docs.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using MergedDataLoader\u00b6\nMergeDocLoader", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.merge.MergedDataLoader.html"}
{"id": "0e9003d33245-0", "text": "langchain.document_loaders.pdf.PyPDFium2Loader\u00b6\nclass langchain.document_loaders.pdf.PyPDFium2Loader(file_path: str, *, headers: Optional[Dict] = None, extract_images: bool = False)[source]\u00b6\nLoad PDF using pypdfium2 and chunks at character level.\nInitialize with a file path.\nAttributes\nsource\nMethods\n__init__(file_path,\u00a0*[,\u00a0headers,\u00a0extract_images])\nInitialize with a file path.\nlazy_load()\nLazy load given path as pages.\nload()\nLoad given path as pages.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, *, headers: Optional[Dict] = None, extract_images: bool = False)[source]\u00b6\nInitialize with a file path.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load given path as pages.\nload() \u2192 List[Document][source]\u00b6\nLoad given path as pages.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.PyPDFium2Loader.html"}
{"id": "37433aa54f88-0", "text": "langchain.document_loaders.pdf.PDFMinerLoader\u00b6\nclass langchain.document_loaders.pdf.PDFMinerLoader(file_path: str, *, headers: Optional[Dict] = None, extract_images: bool = False, concatenate_pages: bool = True)[source]\u00b6\nLoad PDF files using PDFMiner.\nInitialize with file path.\nParameters\nextract_images \u2013 Whether to extract images from PDF.\nconcatenate_pages \u2013 If True, concatenate all PDF pages into one a single\ndocument. Otherwise, return one document per page.\nAttributes\nsource\nMethods\n__init__(file_path,\u00a0*[,\u00a0headers,\u00a0...])\nInitialize with file path.\nlazy_load()\nLazily load documents.\nload()\nEagerly load the content.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, *, headers: Optional[Dict] = None, extract_images: bool = False, concatenate_pages: bool = True) \u2192 None[source]\u00b6\nInitialize with file path.\nParameters\nextract_images \u2013 Whether to extract images from PDF.\nconcatenate_pages \u2013 If True, concatenate all PDF pages into one a single\ndocument. Otherwise, return one document per page.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazily load documents.\nload() \u2192 List[Document][source]\u00b6\nEagerly load the content.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.PDFMinerLoader.html"}
{"id": "ff7aa4add13f-0", "text": "langchain.document_loaders.discord.DiscordChatLoader\u00b6\nclass langchain.document_loaders.discord.DiscordChatLoader(chat_log: pd.DataFrame, user_id_col: str = 'ID')[source]\u00b6\nLoad Discord chat logs.\nInitialize with a Pandas DataFrame containing chat logs.\nParameters\nchat_log \u2013 Pandas DataFrame containing chat logs.\nuser_id_col \u2013 Name of the column containing the user ID. Defaults to \u201cID\u201d.\nMethods\n__init__(chat_log[,\u00a0user_id_col])\nInitialize with a Pandas DataFrame containing chat logs.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad all chat messages.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(chat_log: pd.DataFrame, user_id_col: str = 'ID')[source]\u00b6\nInitialize with a Pandas DataFrame containing chat logs.\nParameters\nchat_log \u2013 Pandas DataFrame containing chat logs.\nuser_id_col \u2013 Name of the column containing the user ID. Defaults to \u201cID\u201d.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad all chat messages.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using DiscordChatLoader\u00b6\nDiscord", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.discord.DiscordChatLoader.html"}
{"id": "2ab909d2a679-0", "text": "langchain.document_loaders.helpers.FileEncoding\u00b6\nclass langchain.document_loaders.helpers.FileEncoding(encoding: Optional[str], confidence: float, language: Optional[str])[source]\u00b6\nFile encoding as the NamedTuple.\nCreate new instance of FileEncoding(encoding, confidence, language)\nAttributes\nconfidence\nThe confidence of the encoding.\nencoding\nThe encoding of the file.\nlanguage\nThe language of the file.\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.helpers.FileEncoding.html"}
{"id": "a93298729aa7-0", "text": "langchain.document_loaders.directory.DirectoryLoader\u00b6\nclass langchain.document_loaders.directory.DirectoryLoader(path: str, glob: str = '**/[!.]*', silent_errors: bool = False, load_hidden: bool = False, loader_cls: ~typing.Union[~typing.Type[~langchain.document_loaders.unstructured.UnstructuredFileLoader], ~typing.Type[~langchain.document_loaders.text.TextLoader], ~typing.Type[~langchain.document_loaders.html_bs.BSHTMLLoader]] = <class 'langchain.document_loaders.unstructured.UnstructuredFileLoader'>, loader_kwargs: ~typing.Optional[dict] = None, recursive: bool = False, show_progress: bool = False, use_multithreading: bool = False, max_concurrency: int = 4, *, sample_size: int = 0, randomize_sample: bool = False, sample_seed: ~typing.Optional[int] = None)[source]\u00b6\nLoad from a directory.\nInitialize with a path to directory and how to glob over it.\nParameters\npath \u2013 Path to directory.\nglob \u2013 Glob pattern to use to find files. Defaults to \u201c**/[!.]*\u201d\n(all files except hidden).\nsilent_errors \u2013 Whether to silently ignore errors. Defaults to False.\nload_hidden \u2013 Whether to load hidden files. Defaults to False.\nloader_cls \u2013 Loader class to use for loading files.\nDefaults to UnstructuredFileLoader.\nloader_kwargs \u2013 Keyword arguments to pass to loader_cls. Defaults to None.\nrecursive \u2013 Whether to recursively search for files. Defaults to False.\nshow_progress \u2013 Whether to show a progress bar. Defaults to False.\nuse_multithreading \u2013 Whether to use multithreading. Defaults to False.\nmax_concurrency \u2013 The maximum number of threads to use. Defaults to 4.\nsample_size \u2013 The maximum number of files you would like to load from the\ndirectory.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.directory.DirectoryLoader.html"}
{"id": "a93298729aa7-1", "text": "sample_size \u2013 The maximum number of files you would like to load from the\ndirectory.\nrandomize_sample \u2013 Suffle the files to get a random sample.\nsample_seed \u2013 set the seed of the random shuffle for reporoducibility.\nMethods\n__init__(path[,\u00a0glob,\u00a0silent_errors,\u00a0...])\nInitialize with a path to directory and how to glob over it.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nload_file(item,\u00a0path,\u00a0docs,\u00a0pbar)\nLoad a file.\n__init__(path: str, glob: str = '**/[!.]*', silent_errors: bool = False, load_hidden: bool = False, loader_cls: ~typing.Union[~typing.Type[~langchain.document_loaders.unstructured.UnstructuredFileLoader], ~typing.Type[~langchain.document_loaders.text.TextLoader], ~typing.Type[~langchain.document_loaders.html_bs.BSHTMLLoader]] = <class 'langchain.document_loaders.unstructured.UnstructuredFileLoader'>, loader_kwargs: ~typing.Optional[dict] = None, recursive: bool = False, show_progress: bool = False, use_multithreading: bool = False, max_concurrency: int = 4, *, sample_size: int = 0, randomize_sample: bool = False, sample_seed: ~typing.Optional[int] = None)[source]\u00b6\nInitialize with a path to directory and how to glob over it.\nParameters\npath \u2013 Path to directory.\nglob \u2013 Glob pattern to use to find files. Defaults to \u201c**/[!.]*\u201d\n(all files except hidden).\nsilent_errors \u2013 Whether to silently ignore errors. Defaults to False.\nload_hidden \u2013 Whether to load hidden files. Defaults to False.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.directory.DirectoryLoader.html"}
{"id": "a93298729aa7-2", "text": "load_hidden \u2013 Whether to load hidden files. Defaults to False.\nloader_cls \u2013 Loader class to use for loading files.\nDefaults to UnstructuredFileLoader.\nloader_kwargs \u2013 Keyword arguments to pass to loader_cls. Defaults to None.\nrecursive \u2013 Whether to recursively search for files. Defaults to False.\nshow_progress \u2013 Whether to show a progress bar. Defaults to False.\nuse_multithreading \u2013 Whether to use multithreading. Defaults to False.\nmax_concurrency \u2013 The maximum number of threads to use. Defaults to 4.\nsample_size \u2013 The maximum number of files you would like to load from the\ndirectory.\nrandomize_sample \u2013 Suffle the files to get a random sample.\nsample_seed \u2013 set the seed of the random shuffle for reporoducibility.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nload_file(item: Path, path: Path, docs: List[Document], pbar: Optional[Any]) \u2192 None[source]\u00b6\nLoad a file.\nParameters\nitem \u2013 File path.\npath \u2013 Directory path.\ndocs \u2013 List of documents to append to.\npbar \u2013 Progress bar. Defaults to None.\nExamples using DirectoryLoader\u00b6\nStarRocks", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.directory.DirectoryLoader.html"}
{"id": "5529d8f064a8-0", "text": "langchain.document_loaders.unstructured.UnstructuredBaseLoader\u00b6\nclass langchain.document_loaders.unstructured.UnstructuredBaseLoader(mode: str = 'single', post_processors: Optional[List[Callable]] = None, **unstructured_kwargs: Any)[source]\u00b6\nBase Loader that uses Unstructured.\nInitialize with file path.\nMethods\n__init__([mode,\u00a0post_processors])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(mode: str = 'single', post_processors: Optional[List[Callable]] = None, **unstructured_kwargs: Any)[source]\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.unstructured.UnstructuredBaseLoader.html"}
{"id": "d4c287a09c7f-0", "text": "langchain.document_loaders.embaas.EmbaasBlobLoader\u00b6\nclass langchain.document_loaders.embaas.EmbaasBlobLoader[source]\u00b6\nBases: BaseEmbaasLoader, BaseBlobParser\nLoad Embaas blob.\nTo use, you should have the\nenvironment variable EMBAAS_API_KEY set with your API key, or pass\nit as a named parameter to the constructor.\nExample\n# Default parsing\nfrom langchain.document_loaders.embaas import EmbaasBlobLoader\nloader = EmbaasBlobLoader()\nblob = Blob.from_path(path=\"example.mp3\")\ndocuments = loader.parse(blob=blob)\n# Custom api parameters (create embeddings automatically)\nfrom langchain.document_loaders.embaas import EmbaasBlobLoader\nloader = EmbaasBlobLoader(\n    params={\n        \"should_embed\": True,\n        \"model\": \"e5-large-v2\",\n        \"chunk_size\": 256,\n        \"chunk_splitter\": \"CharacterTextSplitter\"\n    }\n)\nblob = Blob.from_path(path=\"example.pdf\")\ndocuments = loader.parse(blob=blob)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_url: str = 'https://api.embaas.io/v1/document/extract-text/bytes/'\u00b6\nThe URL of the Embaas document extraction API.\nparam embaas_api_key: Optional[str] = None\u00b6\nThe API key for the Embaas document extraction API.\nparam params: langchain.document_loaders.embaas.EmbaasDocumentExtractionParameters = {}\u00b6\nAdditional parameters to pass to the Embaas document extraction API.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.EmbaasBlobLoader.html"}
{"id": "d4c287a09c7f-1", "text": "Additional parameters to pass to the Embaas document extraction API.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.EmbaasBlobLoader.html"}
{"id": "d4c287a09c7f-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nParses the blob lazily.\nParameters\nblob \u2013 The blob to parse.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.EmbaasBlobLoader.html"}
{"id": "d4c287a09c7f-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using EmbaasBlobLoader\u00b6\nEmbaas", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.EmbaasBlobLoader.html"}
{"id": "355269932f5c-0", "text": "langchain.document_loaders.parsers.docai.DocAIParsingResults\u00b6\nclass langchain.document_loaders.parsers.docai.DocAIParsingResults(source_path: str, parsed_path: str)[source]\u00b6\nA dataclass to store Document AI parsing results.\nAttributes\nsource_path\nparsed_path\nMethods\n__init__(source_path,\u00a0parsed_path)\n__init__(source_path: str, parsed_path: str) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.docai.DocAIParsingResults.html"}
{"id": "c84e8a13ed9f-0", "text": "langchain.document_loaders.airbyte.AirbyteHubspotLoader\u00b6\nclass langchain.document_loaders.airbyte.AirbyteHubspotLoader(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None)[source]\u00b6\nLoad from Hubspot using an Airbyte source connector.\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nAttributes\nlast_state\nMethods\n__init__(config,\u00a0stream_name[,\u00a0...])\nInitializes the loader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None) \u2192 None[source]\u00b6\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad data into Document objects.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteHubspotLoader.html"}
{"id": "c84e8a13ed9f-1", "text": "load() \u2192 List[Document]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AirbyteHubspotLoader\u00b6\nAirbyte Hubspot", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteHubspotLoader.html"}
{"id": "7a3194e125c7-0", "text": "langchain.document_loaders.pdf.PyPDFDirectoryLoader\u00b6\nclass langchain.document_loaders.pdf.PyPDFDirectoryLoader(path: str, glob: str = '**/[!.]*.pdf', silent_errors: bool = False, load_hidden: bool = False, recursive: bool = False, extract_images: bool = False)[source]\u00b6\nLoad a directory with PDF files using pypdf and chunks at character level.\nLoader also stores page numbers in metadata.\nMethods\n__init__(path[,\u00a0glob,\u00a0silent_errors,\u00a0...])\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(path: str, glob: str = '**/[!.]*.pdf', silent_errors: bool = False, load_hidden: bool = False, recursive: bool = False, extract_images: bool = False)[source]\u00b6\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.PyPDFDirectoryLoader.html"}
{"id": "33195ef7c0b7-0", "text": "langchain.document_loaders.mediawikidump.MWDumpLoader\u00b6\nclass langchain.document_loaders.mediawikidump.MWDumpLoader(file_path: Union[str, Path], encoding: Optional[str] = 'utf8', namespaces: Optional[Sequence[int]] = None, skip_redirects: Optional[bool] = False, stop_on_error: Optional[bool] = True)[source]\u00b6\nLoad MediaWiki dump from an XML file.\nExample\nfrom langchain.document_loaders import MWDumpLoader\nloader = MWDumpLoader(\n    file_path=\"myWiki.xml\",\n    encoding=\"utf8\"\n)\ndocs = loader.load()\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter\ntext_splitter = RecursiveCharacterTextSplitter(\n    chunk_size=1000, chunk_overlap=0\n)\ntexts = text_splitter.split_documents(docs)\nParameters\nfile_path (str) \u2013 XML local file path\nencoding (str, optional) \u2013 Charset encoding, defaults to \u201cutf8\u201d\nnamespaces (List[int],optional) \u2013 The namespace of pages you want to parse.\nSee https://www.mediawiki.org/wiki/Help:Namespaces#Localisation\nfor a list of all common namespaces\nskip_redirects (bool, optional) \u2013 TR=rue to skip pages that redirect to other pages,\nFalse to keep them. False by default\nstop_on_error (bool, optional) \u2013 False to skip over pages that cause parsing errors,\nTrue to stop. True by default\nMethods\n__init__(file_path[,\u00a0encoding,\u00a0namespaces,\u00a0...])\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad from a file path.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.mediawikidump.MWDumpLoader.html"}
{"id": "33195ef7c0b7-1", "text": "load_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: Union[str, Path], encoding: Optional[str] = 'utf8', namespaces: Optional[Sequence[int]] = None, skip_redirects: Optional[bool] = False, stop_on_error: Optional[bool] = True)[source]\u00b6\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad from a file path.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using MWDumpLoader\u00b6\nMediaWikiDump", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.mediawikidump.MWDumpLoader.html"}
{"id": "a8594e5fe7a1-0", "text": "langchain.document_loaders.obs_file.OBSFileLoader\u00b6\nclass langchain.document_loaders.obs_file.OBSFileLoader(bucket: str, key: str, client: Any = None, endpoint: str = '', config: Optional[dict] = None)[source]\u00b6\nLoad from the Huawei OBS file.\nInitialize the OBSFileLoader with the specified settings.\nParameters\nbucket (str) \u2013 The name of the OBS bucket to be used.\nkey (str) \u2013 The name of the object in the OBS bucket.\nclient (ObsClient, optional) \u2013 An instance of the ObsClient to connect to OBS.\nendpoint (str, optional) \u2013 The endpoint URL of your OBS bucket. This parameter is mandatory if client is not provided.\nconfig (dict, optional) \u2013 The parameters for connecting to OBS, provided as a dictionary. This parameter is ignored if client is provided. The dictionary could have the following keys:\n- \u201cak\u201d (str, optional): Your OBS access key (required if get_token_from_ecs is False and bucket policy is not public read).\n- \u201csk\u201d (str, optional): Your OBS secret key (required if get_token_from_ecs is False and bucket policy is not public read).\n- \u201ctoken\u201d (str, optional): Your security token (required if using temporary credentials).\n- \u201cget_token_from_ecs\u201d (bool, optional): Whether to retrieve the security token from ECS. Defaults to False if not provided. If set to True, ak, sk, and token will be ignored.\nRaises\nValueError \u2013 If the esdk-obs-python package is not installed.\nTypeError \u2013 If the provided client is not an instance of ObsClient.\nValueError \u2013 If client is not provided, but endpoint is missing.\nNote", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.obs_file.OBSFileLoader.html"}
{"id": "a8594e5fe7a1-1", "text": "ValueError \u2013 If client is not provided, but endpoint is missing.\nNote\nBefore using this class, make sure you have registered with OBS and have the necessary credentials. The ak, sk, and endpoint values are mandatory unless get_token_from_ecs is True or the bucket policy is public read. token is required when using temporary credentials.\nExample\nTo create a new OBSFileLoader with a new client:\n```\nconfig = {\n\u201cak\u201d: \u201cyour-access-key\u201d,\n\u201csk\u201d: \u201cyour-secret-key\u201d\n}\nobs_loader = OBSFileLoader(\u201cyour-bucket-name\u201d, \u201cyour-object-key\u201d, config=config)\n```\nTo create a new OBSFileLoader with an existing client:\n```\nfrom obs import ObsClient\n# Assuming you have an existing ObsClient object \u2018obs_client\u2019\nobs_loader = OBSFileLoader(\u201cyour-bucket-name\u201d, \u201cyour-object-key\u201d, client=obs_client)\n```\nTo create a new OBSFileLoader without an existing client:\n`\nobs_loader = OBSFileLoader(\"your-bucket-name\", \"your-object-key\", endpoint=\"your-endpoint-url\")\n`\nMethods\n__init__(bucket,\u00a0key[,\u00a0client,\u00a0endpoint,\u00a0config])\nInitialize the OBSFileLoader with the specified settings.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(bucket: str, key: str, client: Any = None, endpoint: str = '', config: Optional[dict] = None) \u2192 None[source]\u00b6\nInitialize the OBSFileLoader with the specified settings.\nParameters\nbucket (str) \u2013 The name of the OBS bucket to be used.\nkey (str) \u2013 The name of the object in the OBS bucket.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.obs_file.OBSFileLoader.html"}
{"id": "a8594e5fe7a1-2", "text": "key (str) \u2013 The name of the object in the OBS bucket.\nclient (ObsClient, optional) \u2013 An instance of the ObsClient to connect to OBS.\nendpoint (str, optional) \u2013 The endpoint URL of your OBS bucket. This parameter is mandatory if client is not provided.\nconfig (dict, optional) \u2013 The parameters for connecting to OBS, provided as a dictionary. This parameter is ignored if client is provided. The dictionary could have the following keys:\n- \u201cak\u201d (str, optional): Your OBS access key (required if get_token_from_ecs is False and bucket policy is not public read).\n- \u201csk\u201d (str, optional): Your OBS secret key (required if get_token_from_ecs is False and bucket policy is not public read).\n- \u201ctoken\u201d (str, optional): Your security token (required if using temporary credentials).\n- \u201cget_token_from_ecs\u201d (bool, optional): Whether to retrieve the security token from ECS. Defaults to False if not provided. If set to True, ak, sk, and token will be ignored.\nRaises\nValueError \u2013 If the esdk-obs-python package is not installed.\nTypeError \u2013 If the provided client is not an instance of ObsClient.\nValueError \u2013 If client is not provided, but endpoint is missing.\nNote\nBefore using this class, make sure you have registered with OBS and have the necessary credentials. The ak, sk, and endpoint values are mandatory unless get_token_from_ecs is True or the bucket policy is public read. token is required when using temporary credentials.\nExample\nTo create a new OBSFileLoader with a new client:\n```\nconfig = {\n\u201cak\u201d: \u201cyour-access-key\u201d,\n\u201csk\u201d: \u201cyour-secret-key\u201d\n}\nobs_loader = OBSFileLoader(\u201cyour-bucket-name\u201d, \u201cyour-object-key\u201d, config=config)\n```", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.obs_file.OBSFileLoader.html"}
{"id": "a8594e5fe7a1-3", "text": "```\nTo create a new OBSFileLoader with an existing client:\n```\nfrom obs import ObsClient\n# Assuming you have an existing ObsClient object \u2018obs_client\u2019\nobs_loader = OBSFileLoader(\u201cyour-bucket-name\u201d, \u201cyour-object-key\u201d, client=obs_client)\n```\nTo create a new OBSFileLoader without an existing client:\n`\nobs_loader = OBSFileLoader(\"your-bucket-name\", \"your-object-key\", endpoint=\"your-endpoint-url\")\n`\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using OBSFileLoader\u00b6\nHuawei OBS File", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.obs_file.OBSFileLoader.html"}
{"id": "41bb91a09464-0", "text": "langchain.document_loaders.xorbits.XorbitsLoader\u00b6\nclass langchain.document_loaders.xorbits.XorbitsLoader(data_frame: Any, page_content_column: str = 'text')[source]\u00b6\nLoad Xorbits DataFrame.\nInitialize with dataframe object.\nRequirements:Must have xorbits installed. You can install with pip install xorbits.\nParameters\ndata_frame \u2013 Xorbits DataFrame object.\npage_content_column \u2013 Name of the column containing the page content.\nDefaults to \u201ctext\u201d.\nMethods\n__init__(data_frame[,\u00a0page_content_column])\nInitialize with dataframe object.\nlazy_load()\nLazy load records from dataframe.\nload()\nLoad full dataframe.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(data_frame: Any, page_content_column: str = 'text')[source]\u00b6\nInitialize with dataframe object.\nRequirements:Must have xorbits installed. You can install with pip install xorbits.\nParameters\ndata_frame \u2013 Xorbits DataFrame object.\npage_content_column \u2013 Name of the column containing the page content.\nDefaults to \u201ctext\u201d.\nlazy_load() \u2192 Iterator[Document]\u00b6\nLazy load records from dataframe.\nload() \u2192 List[Document]\u00b6\nLoad full dataframe.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using XorbitsLoader\u00b6\nXorbits Pandas DataFrame", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.xorbits.XorbitsLoader.html"}
{"id": "9ea86f543a99-0", "text": "langchain.document_loaders.iugu.IuguLoader\u00b6\nclass langchain.document_loaders.iugu.IuguLoader(resource: str, api_token: Optional[str] = None)[source]\u00b6\nLoad from IUGU.\nInitialize the IUGU resource.\nParameters\nresource \u2013 The name of the resource to fetch.\napi_token \u2013 The IUGU API token to use.\nMethods\n__init__(resource[,\u00a0api_token])\nInitialize the IUGU resource.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(resource: str, api_token: Optional[str] = None) \u2192 None[source]\u00b6\nInitialize the IUGU resource.\nParameters\nresource \u2013 The name of the resource to fetch.\napi_token \u2013 The IUGU API token to use.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using IuguLoader\u00b6\nIugu", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.iugu.IuguLoader.html"}
{"id": "20b55261e266-0", "text": "langchain.document_loaders.google_speech_to_text.GoogleSpeechToTextLoader\u00b6\nclass langchain.document_loaders.google_speech_to_text.GoogleSpeechToTextLoader(project_id: str, file_path: str, location: str = 'us-central1', recognizer_id: str = '_', config: Optional[RecognitionConfig] = None, config_mask: Optional[FieldMask] = None)[source]\u00b6\nLoader for Google Cloud Speech-to-Text audio transcripts.\nIt uses the Google Cloud Speech-to-Text API to transcribe audio files\nand loads the transcribed text into one or more Documents,\ndepending on the specified format.\nTo use, you should have the google-cloud-speech python package installed.\nAudio files can be specified via a Google Cloud Storage uri or a local file path.\nFor a detailed explanation of Google Cloud Speech-to-Text, refer to the product\ndocumentation.\nhttps://cloud.google.com/speech-to-text\nInitializes the GoogleSpeechToTextLoader.\nParameters\nproject_id \u2013 Google Cloud Project ID.\nfile_path \u2013 A Google Cloud Storage URI or a local file path.\nlocation \u2013 Speech-to-Text recognizer location.\nrecognizer_id \u2013 Speech-to-Text recognizer id.\nconfig \u2013 Recognition options and features.\nFor more information:\nhttps://cloud.google.com/python/docs/reference/speech/latest/google.cloud.speech_v2.types.RecognitionConfig\nconfig_mask \u2013 The list of fields in config that override the values in the\ndefault_recognition_config of the recognizer during this\nrecognition request.\nFor more information:\nhttps://cloud.google.com/python/docs/reference/speech/latest/google.cloud.speech_v2.types.RecognizeRequest\nMethods\n__init__(project_id,\u00a0file_path[,\u00a0location,\u00a0...])\nInitializes the GoogleSpeechToTextLoader.\nlazy_load()\nA lazy loader for Documents.\nload()", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.google_speech_to_text.GoogleSpeechToTextLoader.html"}
{"id": "20b55261e266-1", "text": "lazy_load()\nA lazy loader for Documents.\nload()\nTranscribes the audio file and loads the transcript into documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(project_id: str, file_path: str, location: str = 'us-central1', recognizer_id: str = '_', config: Optional[RecognitionConfig] = None, config_mask: Optional[FieldMask] = None)[source]\u00b6\nInitializes the GoogleSpeechToTextLoader.\nParameters\nproject_id \u2013 Google Cloud Project ID.\nfile_path \u2013 A Google Cloud Storage URI or a local file path.\nlocation \u2013 Speech-to-Text recognizer location.\nrecognizer_id \u2013 Speech-to-Text recognizer id.\nconfig \u2013 Recognition options and features.\nFor more information:\nhttps://cloud.google.com/python/docs/reference/speech/latest/google.cloud.speech_v2.types.RecognitionConfig\nconfig_mask \u2013 The list of fields in config that override the values in the\ndefault_recognition_config of the recognizer during this\nrecognition request.\nFor more information:\nhttps://cloud.google.com/python/docs/reference/speech/latest/google.cloud.speech_v2.types.RecognizeRequest\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nTranscribes the audio file and loads the transcript into documents.\nIt uses the Google Cloud Speech-to-Text API to transcribe the audio file\nand blocks until the transcription is finished.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using GoogleSpeechToTextLoader\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.google_speech_to_text.GoogleSpeechToTextLoader.html"}
{"id": "20b55261e266-2", "text": "Returns\nList of Documents.\nExamples using GoogleSpeechToTextLoader\u00b6\nGoogle Cloud Speech-to-Text", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.google_speech_to_text.GoogleSpeechToTextLoader.html"}
{"id": "8631b16ed97f-0", "text": "langchain.document_loaders.tencent_cos_file.TencentCOSFileLoader\u00b6\nclass langchain.document_loaders.tencent_cos_file.TencentCOSFileLoader(conf: Any, bucket: str, key: str)[source]\u00b6\nLoad from Tencent Cloud COS file.\nInitialize with COS config, bucket and key name.\n:param conf(CosConfig): COS config.\n:param bucket(str): COS bucket.\n:param key(str): COS file key.\nMethods\n__init__(conf,\u00a0bucket,\u00a0key)\nInitialize with COS config, bucket and key name.\nlazy_load()\nLoad documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(conf: Any, bucket: str, key: str)[source]\u00b6\nInitialize with COS config, bucket and key name.\n:param conf(CosConfig): COS config.\n:param bucket(str): COS bucket.\n:param key(str): COS file key.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLoad documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using TencentCOSFileLoader\u00b6\nTencent COS File", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.tencent_cos_file.TencentCOSFileLoader.html"}
{"id": "760b0fc2f356-0", "text": "langchain.document_loaders.tensorflow_datasets.TensorflowDatasetLoader\u00b6\nclass langchain.document_loaders.tensorflow_datasets.TensorflowDatasetLoader(dataset_name: str, split_name: str, load_max_docs: Optional[int] = 100, sample_to_document_function: Optional[Callable[[Dict], Document]] = None)[source]\u00b6\nLoad from TensorFlow Dataset.\ndataset_name\u00b6\nthe name of the dataset to load\nsplit_name\u00b6\nthe name of the split to load.\nload_max_docs\u00b6\na limit to the number of loaded documents. Defaults to 100.\nsample_to_document_function\u00b6\na function that converts a dataset sample\ninto a Document\nExample\nfrom langchain.document_loaders import TensorflowDatasetLoader\ndef mlqaen_example_to_document(example: dict) -> Document:\n    return Document(\n        page_content=decode_to_str(example[\"context\"]),\n        metadata={\n            \"id\": decode_to_str(example[\"id\"]),\n            \"title\": decode_to_str(example[\"title\"]),\n            \"question\": decode_to_str(example[\"question\"]),\n            \"answer\": decode_to_str(example[\"answers\"][\"text\"][0]),\n        },\n    )\ntsds_client = TensorflowDatasetLoader(\n        dataset_name=\"mlqa/en\",\n        split_name=\"test\",\n        load_max_docs=100,\n        sample_to_document_function=mlqaen_example_to_document,\n    )\nInitialize the TensorflowDatasetLoader.\nParameters\ndataset_name \u2013 the name of the dataset to load\nsplit_name \u2013 the name of the split to load.\nload_max_docs \u2013 a limit to the number of loaded documents. Defaults to 100.\nsample_to_document_function \u2013 a function that converts a dataset sample\ninto a Document.\nAttributes\nload_max_docs\nThe maximum number of documents to load.\nsample_to_document_function\nCustom function that transform a dataset sample into a Document.\nMethods", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.tensorflow_datasets.TensorflowDatasetLoader.html"}
{"id": "760b0fc2f356-1", "text": "sample_to_document_function\nCustom function that transform a dataset sample into a Document.\nMethods\n__init__(dataset_name,\u00a0split_name[,\u00a0...])\nInitialize the TensorflowDatasetLoader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(dataset_name: str, split_name: str, load_max_docs: Optional[int] = 100, sample_to_document_function: Optional[Callable[[Dict], Document]] = None)[source]\u00b6\nInitialize the TensorflowDatasetLoader.\nParameters\ndataset_name \u2013 the name of the dataset to load\nsplit_name \u2013 the name of the split to load.\nload_max_docs \u2013 a limit to the number of loaded documents. Defaults to 100.\nsample_to_document_function \u2013 a function that converts a dataset sample\ninto a Document.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using TensorflowDatasetLoader\u00b6\nTensorFlow Datasets", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.tensorflow_datasets.TensorflowDatasetLoader.html"}
{"id": "7866afdcc145-0", "text": "langchain.document_loaders.rocksetdb.ColumnNotFoundError\u00b6\nclass langchain.document_loaders.rocksetdb.ColumnNotFoundError(missing_key: str, query: str)[source]\u00b6\nColumn not found error.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.rocksetdb.ColumnNotFoundError.html"}
{"id": "fbe62addb689-0", "text": "langchain.document_loaders.s3_file.S3FileLoader\u00b6\nclass langchain.document_loaders.s3_file.S3FileLoader(bucket: str, key: str, *, region_name: Optional[str] = None, api_version: Optional[str] = None, use_ssl: Optional[bool] = True, verify: Union[str, bool, None] = None, endpoint_url: Optional[str] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_session_token: Optional[str] = None, boto_config: Optional[botocore.client.Config] = None)[source]\u00b6\nLoad from Amazon AWS S3 file.\nInitialize with bucket and key name.\nParameters\nbucket \u2013 The name of the S3 bucket.\nkey \u2013 The key of the S3 object.\nregion_name \u2013 The name of the region associated with the client.\nA client is associated with a single region.\napi_version \u2013 The API version to use.  By default, botocore will\nuse the latest API version when creating a client.  You only need\nto specify this parameter if you want to use a previous API version\nof the client.\nuse_ssl \u2013 Whether or not to use SSL.  By default, SSL is used.\nNote that not all services support non-ssl connections.\nverify \u2013 Whether or not to verify SSL certificates.\nBy default SSL certificates are verified.  You can provide the\nfollowing values:\nFalse - do not validate SSL certificates.  SSL will still be\nused (unless use_ssl is False), but SSL certificates\nwill not be verified.\npath/to/cert/bundle.pem - A filename of the CA cert bundle to\nuses.  You can specify this argument if you want to use a\ndifferent CA cert bundle than the one used by botocore.\nendpoint_url \u2013 The complete URL to use for the constructed", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.s3_file.S3FileLoader.html"}
{"id": "fbe62addb689-1", "text": "endpoint_url \u2013 The complete URL to use for the constructed\nclient.  Normally, botocore will automatically construct the\nappropriate URL to use when communicating with a service.  You can\nspecify a complete URL (including the \u201chttp/https\u201d scheme) to\noverride this behavior.  If this value is provided, then\nuse_ssl is ignored.\naws_access_key_id \u2013 The access key to use when creating\nthe client.  This is entirely optional, and if not provided,\nthe credentials configured for the session will automatically\nbe used.  You only need to provide this argument if you want\nto override the credentials used for this specific client.\naws_secret_access_key \u2013 The secret key to use when creating\nthe client.  Same semantics as aws_access_key_id above.\naws_session_token \u2013 The session token to use when creating\nthe client.  Same semantics as aws_access_key_id above.\nboto_config (botocore.client.Config) \u2013 Advanced boto3 client configuration options. If a value\nis specified in the client config, its value will take precedence\nover environment variables and configuration values, but not over\na value passed explicitly to the method. If a default config\nobject is set on the session, the config object used when creating\nthe client will be the result of calling merge() on the\ndefault config with the config provided to this call.\nMethods\n__init__(bucket,\u00a0key,\u00a0*[,\u00a0region_name,\u00a0...])\nInitialize with bucket and key name.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.s3_file.S3FileLoader.html"}
{"id": "fbe62addb689-2", "text": "load_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(bucket: str, key: str, *, region_name: Optional[str] = None, api_version: Optional[str] = None, use_ssl: Optional[bool] = True, verify: Union[str, bool, None] = None, endpoint_url: Optional[str] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_session_token: Optional[str] = None, boto_config: Optional[botocore.client.Config] = None)[source]\u00b6\nInitialize with bucket and key name.\nParameters\nbucket \u2013 The name of the S3 bucket.\nkey \u2013 The key of the S3 object.\nregion_name \u2013 The name of the region associated with the client.\nA client is associated with a single region.\napi_version \u2013 The API version to use.  By default, botocore will\nuse the latest API version when creating a client.  You only need\nto specify this parameter if you want to use a previous API version\nof the client.\nuse_ssl \u2013 Whether or not to use SSL.  By default, SSL is used.\nNote that not all services support non-ssl connections.\nverify \u2013 Whether or not to verify SSL certificates.\nBy default SSL certificates are verified.  You can provide the\nfollowing values:\nFalse - do not validate SSL certificates.  SSL will still be\nused (unless use_ssl is False), but SSL certificates\nwill not be verified.\npath/to/cert/bundle.pem - A filename of the CA cert bundle to\nuses.  You can specify this argument if you want to use a\ndifferent CA cert bundle than the one used by botocore.\nendpoint_url \u2013 The complete URL to use for the constructed\nclient.  Normally, botocore will automatically construct the", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.s3_file.S3FileLoader.html"}
{"id": "fbe62addb689-3", "text": "client.  Normally, botocore will automatically construct the\nappropriate URL to use when communicating with a service.  You can\nspecify a complete URL (including the \u201chttp/https\u201d scheme) to\noverride this behavior.  If this value is provided, then\nuse_ssl is ignored.\naws_access_key_id \u2013 The access key to use when creating\nthe client.  This is entirely optional, and if not provided,\nthe credentials configured for the session will automatically\nbe used.  You only need to provide this argument if you want\nto override the credentials used for this specific client.\naws_secret_access_key \u2013 The secret key to use when creating\nthe client.  Same semantics as aws_access_key_id above.\naws_session_token \u2013 The session token to use when creating\nthe client.  Same semantics as aws_access_key_id above.\nboto_config (botocore.client.Config) \u2013 Advanced boto3 client configuration options. If a value\nis specified in the client config, its value will take precedence\nover environment variables and configuration values, but not over\na value passed explicitly to the method. If a default config\nobject is set on the session, the config object used when creating\nthe client will be the result of calling merge() on the\ndefault config with the config provided to this call.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using S3FileLoader\u00b6\nAWS S3 Directory\nAWS S3 File", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.s3_file.S3FileLoader.html"}
{"id": "284026f0806d-0", "text": "langchain.document_loaders.cube_semantic.CubeSemanticLoader\u00b6\nclass langchain.document_loaders.cube_semantic.CubeSemanticLoader(cube_api_url: str, cube_api_token: str, load_dimension_values: bool = True, dimension_values_limit: int = 10000, dimension_values_max_retries: int = 10, dimension_values_retry_delay: int = 3)[source]\u00b6\nLoad Cube semantic layer metadata.\nParameters\ncube_api_url \u2013 REST API endpoint.\nUse the REST API of your Cube\u2019s deployment.\nPlease find out more information here:\nhttps://cube.dev/docs/http-api/rest#configuration-base-path\ncube_api_token \u2013 Cube API token.\nAuthentication tokens are generated based on your Cube\u2019s API secret.\nPlease find out more information here:\nhttps://cube.dev/docs/security#generating-json-web-tokens-jwt\nload_dimension_values \u2013 Whether to load dimension values for every string\ndimension or not.\ndimension_values_limit \u2013 Maximum number of dimension values to load.\ndimension_values_max_retries \u2013 Maximum number of retries to load dimension\nvalues.\ndimension_values_retry_delay \u2013 Delay between retries to load dimension values.\nMethods\n__init__(cube_api_url,\u00a0cube_api_token[,\u00a0...])\nlazy_load()\nA lazy loader for Documents.\nload()\nMakes a call to Cube's REST API metadata endpoint.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(cube_api_url: str, cube_api_token: str, load_dimension_values: bool = True, dimension_values_limit: int = 10000, dimension_values_max_retries: int = 10, dimension_values_retry_delay: int = 3)[source]\u00b6\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nMakes a call to Cube\u2019s REST API metadata endpoint.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.cube_semantic.CubeSemanticLoader.html"}
{"id": "284026f0806d-1", "text": "Makes a call to Cube\u2019s REST API metadata endpoint.\nReturns\npage_content=column_title + column_description\nmetadata\ntable_name\ncolumn_name\ncolumn_data_type\ncolumn_member_type\ncolumn_title\ncolumn_description\ncolumn_values\ncube_data_obj_type\nReturn type\nA list of documents with attributes\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using CubeSemanticLoader\u00b6\nCube Semantic Layer", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.cube_semantic.CubeSemanticLoader.html"}
{"id": "ce43c99a5bcb-0", "text": "langchain.document_loaders.airbyte.AirbyteGongLoader\u00b6\nclass langchain.document_loaders.airbyte.AirbyteGongLoader(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None)[source]\u00b6\nLoad from Gong using an Airbyte source connector.\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nAttributes\nlast_state\nMethods\n__init__(config,\u00a0stream_name[,\u00a0...])\nInitializes the loader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None) \u2192 None[source]\u00b6\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad data into Document objects.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteGongLoader.html"}
{"id": "ce43c99a5bcb-1", "text": "load() \u2192 List[Document]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AirbyteGongLoader\u00b6\nAirbyte Gong", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteGongLoader.html"}
{"id": "cff0d8bd2e7f-0", "text": "langchain.document_loaders.base_o365.O365BaseLoader\u00b6\nclass langchain.document_loaders.base_o365.O365BaseLoader[source]\u00b6\nBases: BaseLoader, BaseModel\nBase class for all loaders that uses O365 Package\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam auth_with_token: bool = False\u00b6\nWhether to authenticate with a token or not. Defaults to False.\nparam chunk_size: Union[int, str] = 5242880\u00b6\nNumber of bytes to retrieve from each api call to the server. int or \u2018auto\u2019.\nparam settings: langchain.document_loaders.base_o365._O365Settings [Optional]\u00b6\nSettings for the Office365 API client.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.base_o365.O365BaseLoader.html"}
{"id": "cff0d8bd2e7f-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nabstract load() \u2192 List[Document]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.base_o365.O365BaseLoader.html"}
{"id": "cff0d8bd2e7f-2", "text": "Defaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.base_o365.O365BaseLoader.html"}
{"id": "f0bc859d47a6-0", "text": "langchain.document_loaders.airbyte.AirbyteSalesforceLoader\u00b6\nclass langchain.document_loaders.airbyte.AirbyteSalesforceLoader(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None)[source]\u00b6\nLoad from Salesforce using an Airbyte source connector.\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nAttributes\nlast_state\nMethods\n__init__(config,\u00a0stream_name[,\u00a0...])\nInitializes the loader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None) \u2192 None[source]\u00b6\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad data into Document objects.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteSalesforceLoader.html"}
{"id": "f0bc859d47a6-1", "text": "load() \u2192 List[Document]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AirbyteSalesforceLoader\u00b6\nAirbyte Salesforce", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteSalesforceLoader.html"}
{"id": "a132cad6880e-0", "text": "langchain.document_loaders.slack_directory.SlackDirectoryLoader\u00b6\nclass langchain.document_loaders.slack_directory.SlackDirectoryLoader(zip_path: str, workspace_url: Optional[str] = None)[source]\u00b6\nLoad from a Slack directory dump.\nInitialize the SlackDirectoryLoader.\nParameters\nzip_path (str) \u2013 The path to the Slack directory dump zip file.\nworkspace_url (Optional[str]) \u2013 The Slack workspace URL.\nIncluding the URL will turn\nsources into links. Defaults to None.\nMethods\n__init__(zip_path[,\u00a0workspace_url])\nInitialize the SlackDirectoryLoader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad and return documents from the Slack directory dump.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(zip_path: str, workspace_url: Optional[str] = None)[source]\u00b6\nInitialize the SlackDirectoryLoader.\nParameters\nzip_path (str) \u2013 The path to the Slack directory dump zip file.\nworkspace_url (Optional[str]) \u2013 The Slack workspace URL.\nIncluding the URL will turn\nsources into links. Defaults to None.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad and return documents from the Slack directory dump.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using SlackDirectoryLoader\u00b6\nSlack", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.slack_directory.SlackDirectoryLoader.html"}
{"id": "b1c216c2342f-0", "text": "langchain.document_loaders.parsers.html.bs4.BS4HTMLParser\u00b6\nclass langchain.document_loaders.parsers.html.bs4.BS4HTMLParser(*, features: str = 'lxml', get_text_separator: str = '', **kwargs: Any)[source]\u00b6\nPparse HTML files using Beautiful Soup.\nInitialize a bs4 based HTML parser.\nMethods\n__init__(*[,\u00a0features,\u00a0get_text_separator])\nInitialize a bs4 based HTML parser.\nlazy_parse(blob)\nLoad HTML document into document objects.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__(*, features: str = 'lxml', get_text_separator: str = '', **kwargs: Any) \u2192 None[source]\u00b6\nInitialize a bs4 based HTML parser.\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLoad HTML document into document objects.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.html.bs4.BS4HTMLParser.html"}
{"id": "0bb63889ff7a-0", "text": "langchain.document_loaders.arcgis_loader.ArcGISLoader\u00b6\nclass langchain.document_loaders.arcgis_loader.ArcGISLoader(layer: Union[str, arcgis.features.FeatureLayer], gis: Optional[arcgis.gis.GIS] = None, where: str = '1=1', out_fields: Optional[Union[List[str], str]] = None, return_geometry: bool = False, result_record_count: Optional[int] = None, lyr_desc: Optional[str] = None, **kwargs: Any)[source]\u00b6\nLoad records from an ArcGIS FeatureLayer.\nMethods\n__init__(layer[,\u00a0gis,\u00a0where,\u00a0out_fields,\u00a0...])\nlazy_load()\nLazy load records from FeatureLayer.\nload()\nLoad all records from FeatureLayer.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(layer: Union[str, arcgis.features.FeatureLayer], gis: Optional[arcgis.gis.GIS] = None, where: str = '1=1', out_fields: Optional[Union[List[str], str]] = None, return_geometry: bool = False, result_record_count: Optional[int] = None, lyr_desc: Optional[str] = None, **kwargs: Any)[source]\u00b6\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load records from FeatureLayer.\nload() \u2192 List[Document][source]\u00b6\nLoad all records from FeatureLayer.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using ArcGISLoader\u00b6\nArcGIS", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.arcgis_loader.ArcGISLoader.html"}
{"id": "cb487ba8a490-0", "text": "langchain.document_loaders.spreedly.SpreedlyLoader\u00b6\nclass langchain.document_loaders.spreedly.SpreedlyLoader(access_token: str, resource: str)[source]\u00b6\nLoad from Spreedly API.\nInitialize with an access token and a resource.\nParameters\naccess_token \u2013 The access token.\nresource \u2013 The resource.\nMethods\n__init__(access_token,\u00a0resource)\nInitialize with an access token and a resource.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(access_token: str, resource: str) \u2192 None[source]\u00b6\nInitialize with an access token and a resource.\nParameters\naccess_token \u2013 The access token.\nresource \u2013 The resource.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using SpreedlyLoader\u00b6\nSpreedly", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.spreedly.SpreedlyLoader.html"}
{"id": "fe1c46fd6831-0", "text": "langchain.document_loaders.embaas.EmbaasDocumentExtractionParameters\u00b6\nclass langchain.document_loaders.embaas.EmbaasDocumentExtractionParameters[source]\u00b6\nParameters for the embaas document extraction API.\nAttributes\nmime_type\nThe mime type of the document.\nfile_extension\nThe file extension of the document.\nfile_name\nThe file name of the document.\nshould_chunk\nWhether to chunk the document into pages.\nchunk_size\nThe maximum size of the text chunks.\nchunk_overlap\nThe maximum overlap allowed between chunks.\nchunk_splitter\nThe text splitter class name for creating chunks.\nseparators\nThe separators for chunks.\nshould_embed\nWhether to create embeddings for the document in the response.\nmodel\nThe model to pass to the Embaas document extraction API.\ninstruction\nThe instruction to pass to the Embaas document extraction API.\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.EmbaasDocumentExtractionParameters.html"}
{"id": "fe1c46fd6831-1", "text": "update([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.EmbaasDocumentExtractionParameters.html"}
{"id": "fe1c46fd6831-2", "text": "If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.EmbaasDocumentExtractionParameters.html"}
{"id": "8212f1616d9d-0", "text": "langchain.document_loaders.readthedocs.ReadTheDocsLoader\u00b6\nclass langchain.document_loaders.readthedocs.ReadTheDocsLoader(path: Union[str, Path], encoding: Optional[str] = None, errors: Optional[str] = None, custom_html_tag: Optional[Tuple[str, dict]] = None, patterns: Sequence[str] = ('*.htm', '*.html'), exclude_links_ratio: float = 1.0, **kwargs: Optional[Any])[source]\u00b6\nLoad ReadTheDocs documentation directory.\nInitialize ReadTheDocsLoader\nThe loader loops over all files under path and extracts the actual content of\nthe files by retrieving main html tags. Default main html tags include\n<main id=\u201dmain-content>, <div role=\u201dmain>, and <article role=\u201dmain\u201d>. You\ncan also define your own html tags by passing custom_html_tag, e.g.\n(\u201cdiv\u201d, \u201cclass=main\u201d). The loader iterates html tags with the order of\ncustom html tags (if exists) and default html tags. If any of the tags is not\nempty, the loop will break and retrieve the content out of that tag.\nParameters\npath \u2013 The location of pulled readthedocs folder.\nencoding \u2013 The encoding with which to open the documents.\nerrors \u2013 Specify how encoding and decoding errors are to be handled\u2014this\ncannot be used in binary mode.\ncustom_html_tag \u2013 Optional custom html tag to retrieve the content from\nfiles.\npatterns \u2013 The file patterns to load, passed to glob.rglob.\nexclude_links_ratio \u2013 The ratio of links:content to exclude pages from.\nThis is to reduce the frequency at which index pages make their\nway into retrieved results. Recommended: 0.5\nkwargs \u2013 named arguments passed to bs4.BeautifulSoup.\nMethods\n__init__(path[,\u00a0encoding,\u00a0errors,\u00a0...])\nInitialize ReadTheDocsLoader\nlazy_load()", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.readthedocs.ReadTheDocsLoader.html"}
{"id": "8212f1616d9d-1", "text": "Initialize ReadTheDocsLoader\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(path: Union[str, Path], encoding: Optional[str] = None, errors: Optional[str] = None, custom_html_tag: Optional[Tuple[str, dict]] = None, patterns: Sequence[str] = ('*.htm', '*.html'), exclude_links_ratio: float = 1.0, **kwargs: Optional[Any])[source]\u00b6\nInitialize ReadTheDocsLoader\nThe loader loops over all files under path and extracts the actual content of\nthe files by retrieving main html tags. Default main html tags include\n<main id=\u201dmain-content>, <div role=\u201dmain>, and <article role=\u201dmain\u201d>. You\ncan also define your own html tags by passing custom_html_tag, e.g.\n(\u201cdiv\u201d, \u201cclass=main\u201d). The loader iterates html tags with the order of\ncustom html tags (if exists) and default html tags. If any of the tags is not\nempty, the loop will break and retrieve the content out of that tag.\nParameters\npath \u2013 The location of pulled readthedocs folder.\nencoding \u2013 The encoding with which to open the documents.\nerrors \u2013 Specify how encoding and decoding errors are to be handled\u2014this\ncannot be used in binary mode.\ncustom_html_tag \u2013 Optional custom html tag to retrieve the content from\nfiles.\npatterns \u2013 The file patterns to load, passed to glob.rglob.\nexclude_links_ratio \u2013 The ratio of links:content to exclude pages from.\nThis is to reduce the frequency at which index pages make their\nway into retrieved results. Recommended: 0.5\nkwargs \u2013 named arguments passed to bs4.BeautifulSoup.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.readthedocs.ReadTheDocsLoader.html"}
{"id": "8212f1616d9d-2", "text": "lazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using ReadTheDocsLoader\u00b6\nReadTheDocs Documentation", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.readthedocs.ReadTheDocsLoader.html"}
{"id": "314228b6f6d3-0", "text": "langchain.document_loaders.parsers.pdf.PyPDFium2Parser\u00b6\nclass langchain.document_loaders.parsers.pdf.PyPDFium2Parser(extract_images: bool = False)[source]\u00b6\nParse PDF with PyPDFium2.\nInitialize the parser.\nMethods\n__init__([extract_images])\nInitialize the parser.\nlazy_parse(blob)\nLazily parse the blob.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__(extract_images: bool = False) \u2192 None[source]\u00b6\nInitialize the parser.\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLazily parse the blob.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.pdf.PyPDFium2Parser.html"}
{"id": "0d0ab5fde645-0", "text": "langchain.document_loaders.python.PythonLoader\u00b6\nclass langchain.document_loaders.python.PythonLoader(file_path: str)[source]\u00b6\nLoad Python files, respecting any non-default encoding if specified.\nInitialize with a file path.\nParameters\nfile_path \u2013 The path to the file to load.\nMethods\n__init__(file_path)\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad from file path.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str)[source]\u00b6\nInitialize with a file path.\nParameters\nfile_path \u2013 The path to the file to load.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad from file path.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.python.PythonLoader.html"}
{"id": "c7e027cec286-0", "text": "langchain.document_loaders.telegram.TelegramChatFileLoader\u00b6\nclass langchain.document_loaders.telegram.TelegramChatFileLoader(path: str)[source]\u00b6\nLoad from Telegram chat dump.\nInitialize with a path.\nMethods\n__init__(path)\nInitialize with a path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(path: str)[source]\u00b6\nInitialize with a path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using TelegramChatFileLoader\u00b6\nTelegram", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.telegram.TelegramChatFileLoader.html"}
{"id": "655bbaf49e7a-0", "text": "langchain.document_loaders.telegram.TelegramChatApiLoader\u00b6\nclass langchain.document_loaders.telegram.TelegramChatApiLoader(chat_entity: Optional[EntityLike] = None, api_id: Optional[int] = None, api_hash: Optional[str] = None, username: Optional[str] = None, file_path: str = 'telegram_data.json')[source]\u00b6\nLoad Telegram chat json directory dump.\nInitialize with API parameters.\nParameters\nchat_entity \u2013 The chat entity to fetch data from.\napi_id \u2013 The API ID.\napi_hash \u2013 The API hash.\nusername \u2013 The username.\nfile_path \u2013 The file path to save the data to. Defaults to\n\u201ctelegram_data.json\u201d.\nMethods\n__init__([chat_entity,\u00a0api_id,\u00a0api_hash,\u00a0...])\nInitialize with API parameters.\nfetch_data_from_telegram()\nFetch data from Telegram API and save it as a JSON file.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(chat_entity: Optional[EntityLike] = None, api_id: Optional[int] = None, api_hash: Optional[str] = None, username: Optional[str] = None, file_path: str = 'telegram_data.json')[source]\u00b6\nInitialize with API parameters.\nParameters\nchat_entity \u2013 The chat entity to fetch data from.\napi_id \u2013 The API ID.\napi_hash \u2013 The API hash.\nusername \u2013 The username.\nfile_path \u2013 The file path to save the data to. Defaults to\n\u201ctelegram_data.json\u201d.\nasync fetch_data_from_telegram() \u2192 None[source]\u00b6\nFetch data from Telegram API and save it as a JSON file.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.telegram.TelegramChatApiLoader.html"}
{"id": "655bbaf49e7a-1", "text": "lazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using TelegramChatApiLoader\u00b6\nTelegram", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.telegram.TelegramChatApiLoader.html"}
{"id": "ffd4a07effda-0", "text": "langchain.document_loaders.text.TextLoader\u00b6\nclass langchain.document_loaders.text.TextLoader(file_path: str, encoding: Optional[str] = None, autodetect_encoding: bool = False)[source]\u00b6\nLoad text file.\nParameters\nfile_path \u2013 Path to the file to load.\nencoding \u2013 File encoding to use. If None, the file will be loaded\nencoding. (with the default system) \u2013 \nautodetect_encoding \u2013 Whether to try to autodetect the file encoding\nif the specified encoding fails.\nInitialize with file path.\nMethods\n__init__(file_path[,\u00a0encoding,\u00a0...])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad from file path.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, encoding: Optional[str] = None, autodetect_encoding: bool = False)[source]\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad from file path.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using TextLoader\u00b6\nCohere Reranker\nConfident\nElasticsearch\nChat Over Documents with Vectara\nVectorstore\nLanceDB\nsqlite-vss\nWeaviate\nDashVector\nScaNN\nXata\nVectara\nPGVector\nRockset\nDingoDB\nZilliz\nSingleStoreDB\nAnnoy\nTypesense\nAtlas", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.text.TextLoader.html"}
{"id": "ffd4a07effda-1", "text": "Zilliz\nSingleStoreDB\nAnnoy\nTypesense\nAtlas\nActiveloop Deep Lake\nNeo4j Vector Index\nTair\nChroma\nAlibaba Cloud OpenSearch\nBaidu Cloud VectorSearch\nStarRocks\nscikit-learn\nTencent Cloud VectorDB\nDocArray HnswSearch\nMyScale\nClickHouse\nQdrant\nTigris\nAwaDB\nSupabase (Postgres)\nOpenSearch\nPinecone\nBagelDB\nAzure Cognitive Search\nCassandra\nUSearch\nMilvus\nMarqo\nDocArray InMemorySearch\nPostgres Embedding\nFaiss\nEpsilla\nAnalyticDB\nHologres\nyour local model path\nMongoDB Atlas\nMeilisearch\nConversational Retrieval Agent\nAnalysis of Twitter the-algorithm source code with LangChain, GPT4 and Activeloop\u2019s Deep Lake\nUse LangChain, GPT and Activeloop\u2019s Deep Lake to work with code base\nStructure answers with OpenAI functions\nQA using Activeloop\u2019s DeepLake\nGraph QA\nCaching\nMultiVector Retriever\nParent Document Retriever\nCombine agents and vector stores\nLoading from LangChainHub", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.text.TextLoader.html"}
{"id": "a5221828fdbc-0", "text": "langchain.document_loaders.airbyte.AirbyteStripeLoader\u00b6\nclass langchain.document_loaders.airbyte.AirbyteStripeLoader(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None)[source]\u00b6\nLoad from Stripe using an Airbyte source connector.\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nAttributes\nlast_state\nMethods\n__init__(config,\u00a0stream_name[,\u00a0...])\nInitializes the loader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None) \u2192 None[source]\u00b6\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad data into Document objects.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteStripeLoader.html"}
{"id": "a5221828fdbc-1", "text": "load() \u2192 List[Document]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AirbyteStripeLoader\u00b6\nAirbyte Question Answering\nAirbyte Stripe", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteStripeLoader.html"}
{"id": "bf9b26600add-0", "text": "langchain.document_loaders.datadog_logs.DatadogLogsLoader\u00b6\nclass langchain.document_loaders.datadog_logs.DatadogLogsLoader(query: str, api_key: str, app_key: str, from_time: Optional[int] = None, to_time: Optional[int] = None, limit: int = 100)[source]\u00b6\nLoad Datadog logs.\nLogs are written into the page_content and into the metadata.\nInitialize Datadog document loader.\nRequirements:\nMust have datadog_api_client installed. Install with pip install datadog_api_client.\nParameters\nquery \u2013 The query to run in Datadog.\napi_key \u2013 The Datadog API key.\napp_key \u2013 The Datadog APP key.\nfrom_time \u2013 Optional. The start of the time range to query.\nSupports date math and regular timestamps (milliseconds) like \u20181688732708951\u2019\nDefaults to 20 minutes ago.\nto_time \u2013 Optional. The end of the time range to query.\nSupports date math and regular timestamps (milliseconds) like \u20181688732708951\u2019\nDefaults to now.\nlimit \u2013 The maximum number of logs to return.\nDefaults to 100.\nMethods\n__init__(query,\u00a0api_key,\u00a0app_key[,\u00a0...])\nInitialize Datadog document loader.\nlazy_load()\nA lazy loader for Documents.\nload()\nGet logs from Datadog.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nparse_log(log)\nCreate Document objects from Datadog log items.\n__init__(query: str, api_key: str, app_key: str, from_time: Optional[int] = None, to_time: Optional[int] = None, limit: int = 100) \u2192 None[source]\u00b6\nInitialize Datadog document loader.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.datadog_logs.DatadogLogsLoader.html"}
{"id": "bf9b26600add-1", "text": "Initialize Datadog document loader.\nRequirements:\nMust have datadog_api_client installed. Install with pip install datadog_api_client.\nParameters\nquery \u2013 The query to run in Datadog.\napi_key \u2013 The Datadog API key.\napp_key \u2013 The Datadog APP key.\nfrom_time \u2013 Optional. The start of the time range to query.\nSupports date math and regular timestamps (milliseconds) like \u20181688732708951\u2019\nDefaults to 20 minutes ago.\nto_time \u2013 Optional. The end of the time range to query.\nSupports date math and regular timestamps (milliseconds) like \u20181688732708951\u2019\nDefaults to now.\nlimit \u2013 The maximum number of logs to return.\nDefaults to 100.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nGet logs from Datadog.\nReturns\nA list of Document objects.\npage_content\nmetadata\nid\nservice\nstatus\ntags\ntimestamp\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nparse_log(log: dict) \u2192 Document[source]\u00b6\nCreate Document objects from Datadog log items.\nExamples using DatadogLogsLoader\u00b6\nDatadog Logs", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.datadog_logs.DatadogLogsLoader.html"}
{"id": "0126710426a6-0", "text": "langchain.document_loaders.epub.UnstructuredEPubLoader\u00b6\nclass langchain.document_loaders.epub.UnstructuredEPubLoader(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad EPub files using Unstructured.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredEPubLoader\nloader = UnstructuredEPubLoader(\u201cexample.epub\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition-epub\nInitialize with file path.\nMethods\n__init__(file_path[,\u00a0mode])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.epub.UnstructuredEPubLoader.html"}
{"id": "0126710426a6-1", "text": "Parameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredEPubLoader\u00b6\nEPub", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.epub.UnstructuredEPubLoader.html"}
{"id": "ac4ce66f8e3f-0", "text": "langchain.document_loaders.html.UnstructuredHTMLLoader\u00b6\nclass langchain.document_loaders.html.UnstructuredHTMLLoader(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad HTML files using Unstructured.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredHTMLLoader\nloader = UnstructuredHTMLLoader(\u201cexample.html\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition-html\nInitialize with file path.\nMethods\n__init__(file_path[,\u00a0mode])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.html.UnstructuredHTMLLoader.html"}
{"id": "7820cdcdf6fb-0", "text": "langchain.document_loaders.rtf.UnstructuredRTFLoader\u00b6\nclass langchain.document_loaders.rtf.UnstructuredRTFLoader(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad RTF files using Unstructured.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredRTFLoader\nloader = UnstructuredRTFLoader(\u201cexample.rtf\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition-rtf\nInitialize with a file path.\nParameters\nfile_path \u2013 The path to the file to load.\nmode \u2013 The mode to use for partitioning. See unstructured for details.\nDefaults to \u201csingle\u201d.\n**unstructured_kwargs \u2013 Additional keyword arguments to pass\nto unstructured.\nMethods\n__init__(file_path[,\u00a0mode])\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nInitialize with a file path.\nParameters\nfile_path \u2013 The path to the file to load.\nmode \u2013 The mode to use for partitioning. See unstructured for details.\nDefaults to \u201csingle\u201d.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.rtf.UnstructuredRTFLoader.html"}
{"id": "7820cdcdf6fb-1", "text": "Defaults to \u201csingle\u201d.\n**unstructured_kwargs \u2013 Additional keyword arguments to pass\nto unstructured.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.rtf.UnstructuredRTFLoader.html"}
{"id": "a7e5edfee4d8-0", "text": "langchain.document_loaders.airbyte.AirbyteTypeformLoader\u00b6\nclass langchain.document_loaders.airbyte.AirbyteTypeformLoader(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None)[source]\u00b6\nLoad from Typeform using an Airbyte source connector.\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nAttributes\nlast_state\nMethods\n__init__(config,\u00a0stream_name[,\u00a0...])\nInitializes the loader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None) \u2192 None[source]\u00b6\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad data into Document objects.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteTypeformLoader.html"}
{"id": "a7e5edfee4d8-1", "text": "load() \u2192 List[Document]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AirbyteTypeformLoader\u00b6\nAirbyte Typeform", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteTypeformLoader.html"}
{"id": "1b46cf9ee7ad-0", "text": "langchain.document_loaders.bilibili.BiliBiliLoader\u00b6\nclass langchain.document_loaders.bilibili.BiliBiliLoader(video_urls: List[str])[source]\u00b6\nLoad BiliBili video transcripts.\nInitialize with bilibili url.\nParameters\nvideo_urls \u2013 List of bilibili urls.\nMethods\n__init__(video_urls)\nInitialize with bilibili url.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad Documents from bilibili url.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(video_urls: List[str])[source]\u00b6\nInitialize with bilibili url.\nParameters\nvideo_urls \u2013 List of bilibili urls.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad Documents from bilibili url.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using BiliBiliLoader\u00b6\nBiliBili", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.bilibili.BiliBiliLoader.html"}
{"id": "e6b729064fa9-0", "text": "langchain.document_loaders.pdf.MathpixPDFLoader\u00b6\nclass langchain.document_loaders.pdf.MathpixPDFLoader(file_path: str, processed_file_format: str = 'md', max_wait_time_seconds: int = 500, should_clean_pdf: bool = False, **kwargs: Any)[source]\u00b6\nLoad PDF files using Mathpix service.\nInitialize with a file path.\nParameters\nfile_path \u2013 a file for loading.\nprocessed_file_format \u2013 a format of the processed file. Default is \u201cmd\u201d.\nmax_wait_time_seconds \u2013 a maximum time to wait for the response from\nthe server. Default is 500.\nshould_clean_pdf \u2013 a flag to clean the PDF file. Default is False.\n**kwargs \u2013 additional keyword arguments.\nAttributes\ndata\nsource\nurl\nMethods\n__init__(file_path[,\u00a0processed_file_format,\u00a0...])\nInitialize with a file path.\nclean_pdf(contents)\nClean the PDF file.\nget_processed_pdf(pdf_id)\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nsend_pdf()\nwait_for_processing(pdf_id)\nWait for processing to complete.\n__init__(file_path: str, processed_file_format: str = 'md', max_wait_time_seconds: int = 500, should_clean_pdf: bool = False, **kwargs: Any) \u2192 None[source]\u00b6\nInitialize with a file path.\nParameters\nfile_path \u2013 a file for loading.\nprocessed_file_format \u2013 a format of the processed file. Default is \u201cmd\u201d.\nmax_wait_time_seconds \u2013 a maximum time to wait for the response from\nthe server. Default is 500.\nshould_clean_pdf \u2013 a flag to clean the PDF file. Default is False.\n**kwargs \u2013 additional keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.MathpixPDFLoader.html"}
{"id": "e6b729064fa9-1", "text": "**kwargs \u2013 additional keyword arguments.\nclean_pdf(contents: str) \u2192 str[source]\u00b6\nClean the PDF file.\nParameters\ncontents \u2013 a PDF file contents.\nReturns:\nget_processed_pdf(pdf_id: str) \u2192 str[source]\u00b6\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nsend_pdf() \u2192 str[source]\u00b6\nwait_for_processing(pdf_id: str) \u2192 None[source]\u00b6\nWait for processing to complete.\nParameters\npdf_id \u2013 a PDF id.\nReturns: None", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.MathpixPDFLoader.html"}
{"id": "ff80065efdf2-0", "text": "langchain.document_loaders.youtube.GoogleApiClient\u00b6\nclass langchain.document_loaders.youtube.GoogleApiClient(credentials_path: Path = PosixPath('/home/docs/.credentials/credentials.json'), service_account_path: Path = PosixPath('/home/docs/.credentials/credentials.json'), token_path: Path = PosixPath('/home/docs/.credentials/token.json'))[source]\u00b6\nGeneric Google API Client.\nTo use, you should have the google_auth_oauthlib,youtube_transcript_api,google\npython package installed.\nAs the google api expects credentials you need to set up a google account and\nregister your Service. \u201chttps://developers.google.com/docs/api/quickstart/python\u201d\nExample\nfrom langchain.document_loaders import GoogleApiClient\ngoogle_api_client = GoogleApiClient(\n    service_account_path=Path(\"path_to_your_sec_file.json\")\n)\nAttributes\ncredentials_path\nservice_account_path\ntoken_path\nMethods\n__init__([credentials_path,\u00a0...])\nvalidate_channel_or_videoIds_is_set(values)\nValidate that either folder_id or document_ids is set, but not both.\n__init__(credentials_path: Path = PosixPath('/home/docs/.credentials/credentials.json'), service_account_path: Path = PosixPath('/home/docs/.credentials/credentials.json'), token_path: Path = PosixPath('/home/docs/.credentials/token.json')) \u2192 None\u00b6\nclassmethod validate_channel_or_videoIds_is_set(values: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nValidate that either folder_id or document_ids is set, but not both.\nExamples using GoogleApiClient\u00b6\nYouTube transcripts", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.youtube.GoogleApiClient.html"}
{"id": "3908e70ec594-0", "text": "langchain.document_loaders.parsers.pdf.PyMuPDFParser\u00b6\nclass langchain.document_loaders.parsers.pdf.PyMuPDFParser(text_kwargs: Optional[Mapping[str, Any]] = None, extract_images: bool = False)[source]\u00b6\nParse PDF using PyMuPDF.\nInitialize the parser.\nParameters\ntext_kwargs \u2013 Keyword arguments to pass to fitz.Page.get_text().\nMethods\n__init__([text_kwargs,\u00a0extract_images])\nInitialize the parser.\nlazy_parse(blob)\nLazily parse the blob.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__(text_kwargs: Optional[Mapping[str, Any]] = None, extract_images: bool = False) \u2192 None[source]\u00b6\nInitialize the parser.\nParameters\ntext_kwargs \u2013 Keyword arguments to pass to fitz.Page.get_text().\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLazily parse the blob.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.pdf.PyMuPDFParser.html"}
{"id": "4d7d34bd3e4b-0", "text": "langchain.document_loaders.news.NewsURLLoader\u00b6\nclass langchain.document_loaders.news.NewsURLLoader(urls: List[str], text_mode: bool = True, nlp: bool = False, continue_on_failure: bool = True, show_progress_bar: bool = False, **newspaper_kwargs: Any)[source]\u00b6\nLoad news articles from URLs using Unstructured.\nParameters\nurls \u2013 URLs to load. Each is loaded into its own document.\ntext_mode \u2013 If True, extract text from URL and use that for page content.\nOtherwise, extract raw HTML.\nnlp \u2013 If True, perform NLP on the extracted contents, like providing a summary\nand extracting keywords.\ncontinue_on_failure \u2013 If True, continue loading documents even if\nloading fails for a particular URL.\nshow_progress_bar \u2013 If True, use tqdm to show a loading progress bar. Requires\ntqdm to be installed, pip install tqdm.\n**newspaper_kwargs \u2013 Any additional named arguments to pass to\nnewspaper.Article().\nExample\nfrom langchain.document_loaders import NewsURLLoader\nloader = NewsURLLoader(\n    urls=[\"<url-1>\", \"<url-2>\"],\n)\ndocs = loader.load()\nNewspaper reference:https://newspaper.readthedocs.io/en/latest/\nInitialize with file path.\nMethods\n__init__(urls[,\u00a0text_mode,\u00a0nlp,\u00a0...])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(urls: List[str], text_mode: bool = True, nlp: bool = False, continue_on_failure: bool = True, show_progress_bar: bool = False, **newspaper_kwargs: Any) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.news.NewsURLLoader.html"}
{"id": "4d7d34bd3e4b-1", "text": "Initialize with file path.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using NewsURLLoader\u00b6\nNews URL", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.news.NewsURLLoader.html"}
{"id": "96ec8655892f-0", "text": "langchain.document_loaders.xml.UnstructuredXMLLoader\u00b6\nclass langchain.document_loaders.xml.UnstructuredXMLLoader(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad XML file using Unstructured.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredXMLLoader\nloader = UnstructuredXMLLoader(\u201cexample.xml\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition-xml\nInitialize with file path.\nMethods\n__init__(file_path[,\u00a0mode])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredXMLLoader\u00b6\nXML", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.xml.UnstructuredXMLLoader.html"}
{"id": "1836ab36e67e-0", "text": "langchain.document_loaders.whatsapp_chat.concatenate_rows\u00b6\nlangchain.document_loaders.whatsapp_chat.concatenate_rows(date: str, sender: str, text: str) \u2192 str[source]\u00b6\nCombine message information in a readable format ready to be used.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.whatsapp_chat.concatenate_rows.html"}
{"id": "5e038de32947-0", "text": "langchain.document_loaders.parsers.pdf.PDFPlumberParser\u00b6\nclass langchain.document_loaders.parsers.pdf.PDFPlumberParser(text_kwargs: Optional[Mapping[str, Any]] = None, dedupe: bool = False, extract_images: bool = False)[source]\u00b6\nParse PDF with PDFPlumber.\nInitialize the parser.\nParameters\ntext_kwargs \u2013 Keyword arguments to pass to pdfplumber.Page.extract_text()\ndedupe \u2013 Avoiding the error of duplicate characters if dedupe=True.\nMethods\n__init__([text_kwargs,\u00a0dedupe,\u00a0extract_images])\nInitialize the parser.\nlazy_parse(blob)\nLazily parse the blob.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__(text_kwargs: Optional[Mapping[str, Any]] = None, dedupe: bool = False, extract_images: bool = False) \u2192 None[source]\u00b6\nInitialize the parser.\nParameters\ntext_kwargs \u2013 Keyword arguments to pass to pdfplumber.Page.extract_text()\ndedupe \u2013 Avoiding the error of duplicate characters if dedupe=True.\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLazily parse the blob.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.pdf.PDFPlumberParser.html"}
{"id": "203654ebefb3-0", "text": "langchain.document_loaders.weather.WeatherDataLoader\u00b6\nclass langchain.document_loaders.weather.WeatherDataLoader(client: OpenWeatherMapAPIWrapper, places: Sequence[str])[source]\u00b6\nLoad weather data with Open Weather Map API.\nReads the forecast & current weather of any location using OpenWeatherMap\u2019s free\nAPI. Checkout \u2018https://openweathermap.org/appid\u2019 for more on how to generate a free\nOpenWeatherMap API.\nInitialize with parameters.\nMethods\n__init__(client,\u00a0places)\nInitialize with parameters.\nfrom_params(places,\u00a0*[,\u00a0openweathermap_api_key])\nlazy_load()\nLazily load weather data for the given locations.\nload()\nLoad weather data for the given locations.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(client: OpenWeatherMapAPIWrapper, places: Sequence[str]) \u2192 None[source]\u00b6\nInitialize with parameters.\nclassmethod from_params(places: Sequence[str], *, openweathermap_api_key: Optional[str] = None) \u2192 WeatherDataLoader[source]\u00b6\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazily load weather data for the given locations.\nload() \u2192 List[Document][source]\u00b6\nLoad weather data for the given locations.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using WeatherDataLoader\u00b6\nWeather", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.weather.WeatherDataLoader.html"}
{"id": "8759c4e0e27b-0", "text": "langchain.document_loaders.snowflake_loader.SnowflakeLoader\u00b6\nclass langchain.document_loaders.snowflake_loader.SnowflakeLoader(query: str, user: str, password: str, account: str, warehouse: str, role: str, database: str, schema: str, parameters: Optional[Dict[str, Any]] = None, page_content_columns: Optional[List[str]] = None, metadata_columns: Optional[List[str]] = None)[source]\u00b6\nLoad from Snowflake API.\nEach document represents one row of the result. The page_content_columns\nare written into the page_content of the document. The metadata_columns\nare written into the metadata of the document. By default, all columns\nare written into the page_content and none into the metadata.\nInitialize Snowflake document loader.\nParameters\nquery \u2013 The query to run in Snowflake.\nuser \u2013 Snowflake user.\npassword \u2013 Snowflake password.\naccount \u2013 Snowflake account.\nwarehouse \u2013 Snowflake warehouse.\nrole \u2013 Snowflake role.\ndatabase \u2013 Snowflake database\nschema \u2013 Snowflake schema\nparameters \u2013 Optional. Parameters to pass to the query.\npage_content_columns \u2013 Optional. Columns written to Document page_content.\nmetadata_columns \u2013 Optional. Columns written to Document metadata.\nMethods\n__init__(query,\u00a0user,\u00a0password,\u00a0account,\u00a0...)\nInitialize Snowflake document loader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.snowflake_loader.SnowflakeLoader.html"}
{"id": "8759c4e0e27b-1", "text": "load_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(query: str, user: str, password: str, account: str, warehouse: str, role: str, database: str, schema: str, parameters: Optional[Dict[str, Any]] = None, page_content_columns: Optional[List[str]] = None, metadata_columns: Optional[List[str]] = None)[source]\u00b6\nInitialize Snowflake document loader.\nParameters\nquery \u2013 The query to run in Snowflake.\nuser \u2013 Snowflake user.\npassword \u2013 Snowflake password.\naccount \u2013 Snowflake account.\nwarehouse \u2013 Snowflake warehouse.\nrole \u2013 Snowflake role.\ndatabase \u2013 Snowflake database\nschema \u2013 Snowflake schema\nparameters \u2013 Optional. Parameters to pass to the query.\npage_content_columns \u2013 Optional. Columns written to Document page_content.\nmetadata_columns \u2013 Optional. Columns written to Document metadata.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using SnowflakeLoader\u00b6\nSnowflake", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.snowflake_loader.SnowflakeLoader.html"}
{"id": "1107835b4654-0", "text": "langchain.document_loaders.notiondb.NotionDBLoader\u00b6\nclass langchain.document_loaders.notiondb.NotionDBLoader(integration_token: str, database_id: str, request_timeout_sec: Optional[int] = 10)[source]\u00b6\nLoad from Notion DB.\nReads content from pages within a Notion Database.\n:param integration_token: Notion integration token.\n:type integration_token: str\n:param database_id: Notion database id.\n:type database_id: str\n:param request_timeout_sec: Timeout for Notion requests in seconds.\nDefaults to 10.\nInitialize with parameters.\nMethods\n__init__(integration_token,\u00a0database_id[,\u00a0...])\nInitialize with parameters.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents from the Notion database.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nload_page(page_summary)\nRead a page.\n__init__(integration_token: str, database_id: str, request_timeout_sec: Optional[int] = 10) \u2192 None[source]\u00b6\nInitialize with parameters.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents from the Notion database.\n:returns: List of documents.\n:rtype: List[Document]\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nload_page(page_summary: Dict[str, Any]) \u2192 Document[source]\u00b6\nRead a page.\nParameters\npage_summary \u2013 Page summary from Notion API.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.notiondb.NotionDBLoader.html"}
{"id": "1107835b4654-1", "text": "Read a page.\nParameters\npage_summary \u2013 Page summary from Notion API.\nExamples using NotionDBLoader\u00b6\nNotion DB\nNotion DB 2/2", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.notiondb.NotionDBLoader.html"}
{"id": "ddbf3a85a89d-0", "text": "langchain.document_loaders.sharepoint.SharePointLoader\u00b6\nclass langchain.document_loaders.sharepoint.SharePointLoader[source]\u00b6\nBases: O365BaseLoader\nLoad  from SharePoint.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam auth_with_token: bool = False\u00b6\nWhether to authenticate with a token or not. Defaults to False.\nparam chunk_size: Union[int, str] = 5242880\u00b6\nNumber of bytes to retrieve from each api call to the server. int or \u2018auto\u2019.\nparam document_library_id: str [Required]\u00b6\nThe ID of the SharePoint document library to load data from.\nparam folder_path: Optional[str] = None\u00b6\nThe path to the folder to load data from.\nparam object_ids: Optional[List[str]] = None\u00b6\nThe IDs of the objects to load data from.\nparam settings: _O365Settings [Optional]\u00b6\nSettings for the Office365 API client.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.sharepoint.SharePointLoader.html"}
{"id": "ddbf3a85a89d-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLoad documents lazily. Use this when working at a large scale.\nload() \u2192 List[Document][source]\u00b6\nLoad all documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.sharepoint.SharePointLoader.html"}
{"id": "ddbf3a85a89d-2", "text": "load() \u2192 List[Document][source]\u00b6\nLoad all documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using SharePointLoader\u00b6\nMicrosoft SharePoint", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.sharepoint.SharePointLoader.html"}
{"id": "f67554232a0b-0", "text": "langchain.document_loaders.markdown.UnstructuredMarkdownLoader\u00b6\nclass langchain.document_loaders.markdown.UnstructuredMarkdownLoader(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad Markdown files using Unstructured.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredMarkdownLoader\nloader = UnstructuredMarkdownLoader(\u201cexample.md\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition-md\nInitialize with file path.\nMethods\n__init__(file_path[,\u00a0mode])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.markdown.UnstructuredMarkdownLoader.html"}
{"id": "f67554232a0b-1", "text": "Defaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredMarkdownLoader\u00b6\nStarRocks", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.markdown.UnstructuredMarkdownLoader.html"}
{"id": "0b06b498702e-0", "text": "langchain.document_loaders.parsers.audio.OpenAIWhisperParser\u00b6\nclass langchain.document_loaders.parsers.audio.OpenAIWhisperParser(api_key: Optional[str] = None)[source]\u00b6\nTranscribe and parse audio files.\nAudio transcription is with OpenAI Whisper model.\nMethods\n__init__([api_key])\nlazy_parse(blob)\nLazily parse the blob.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__(api_key: Optional[str] = None)[source]\u00b6\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLazily parse the blob.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents\nExamples using OpenAIWhisperParser\u00b6\nLoading documents from a YouTube url", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.audio.OpenAIWhisperParser.html"}
{"id": "b505d77cd250-0", "text": "langchain.document_loaders.notebook.remove_newlines\u00b6\nlangchain.document_loaders.notebook.remove_newlines(x: Any) \u2192 Any[source]\u00b6\nRecursively remove newlines, no matter the data structure they are stored in.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.notebook.remove_newlines.html"}
{"id": "0b011c86cb06-0", "text": "langchain.document_loaders.azure_blob_storage_container.AzureBlobStorageContainerLoader\u00b6\nclass langchain.document_loaders.azure_blob_storage_container.AzureBlobStorageContainerLoader(conn_str: str, container: str, prefix: str = '')[source]\u00b6\nLoad from Azure Blob Storage container.\nInitialize with connection string, container and blob prefix.\nAttributes\nconn_str\nConnection string for Azure Blob Storage.\ncontainer\nContainer name.\nprefix\nPrefix for blob names.\nMethods\n__init__(conn_str,\u00a0container[,\u00a0prefix])\nInitialize with connection string, container and blob prefix.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(conn_str: str, container: str, prefix: str = '')[source]\u00b6\nInitialize with connection string, container and blob prefix.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AzureBlobStorageContainerLoader\u00b6\nAzure Blob Storage\nAzure Blob Storage Container", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.azure_blob_storage_container.AzureBlobStorageContainerLoader.html"}
{"id": "7e4a760dbb12-0", "text": "langchain.document_loaders.gitbook.GitbookLoader\u00b6\nclass langchain.document_loaders.gitbook.GitbookLoader(web_page: str, load_all_paths: bool = False, base_url: Optional[str] = None, content_selector: str = 'main', continue_on_failure: bool = False)[source]\u00b6\nLoad GitBook data.\nload from either a single page, or\nload all (relative) paths in the navbar.\nInitialize with web page and whether to load all paths.\nParameters\nweb_page \u2013 The web page to load or the starting point from where\nrelative paths are discovered.\nload_all_paths \u2013 If set to True, all relative paths in the navbar\nare loaded instead of only web_page.\nbase_url \u2013 If load_all_paths is True, the relative paths are\nappended to this base url. Defaults to web_page.\ncontent_selector \u2013 The CSS selector for the content to load.\nDefaults to \u201cmain\u201d.\ncontinue_on_failure \u2013 whether to continue loading the sitemap if an error\noccurs loading a url, emitting a warning instead of raising an\nexception. Setting this to True makes the loader more robust, but also\nmay result in missing data. Default: False\nAttributes\nweb_path\nMethods\n__init__(web_page[,\u00a0load_all_paths,\u00a0...])\nInitialize with web page and whether to load all paths.\naload()\nLoad text from the urls in web_path async into Documents.\nfetch_all(urls)\nFetch all urls concurrently with rate limiting.\nlazy_load()\nLazy load text from the url(s) in web_path.\nload()\nFetch text from one single GitBook page.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nscrape([parser])\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls[,\u00a0parser])", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.gitbook.GitbookLoader.html"}
{"id": "7e4a760dbb12-1", "text": "scrape_all(urls[,\u00a0parser])\nFetch all urls, then return soups for all results.\n__init__(web_page: str, load_all_paths: bool = False, base_url: Optional[str] = None, content_selector: str = 'main', continue_on_failure: bool = False)[source]\u00b6\nInitialize with web page and whether to load all paths.\nParameters\nweb_page \u2013 The web page to load or the starting point from where\nrelative paths are discovered.\nload_all_paths \u2013 If set to True, all relative paths in the navbar\nare loaded instead of only web_page.\nbase_url \u2013 If load_all_paths is True, the relative paths are\nappended to this base url. Defaults to web_page.\ncontent_selector \u2013 The CSS selector for the content to load.\nDefaults to \u201cmain\u201d.\ncontinue_on_failure \u2013 whether to continue loading the sitemap if an error\noccurs loading a url, emitting a warning instead of raising an\nexception. Setting this to True makes the loader more robust, but also\nmay result in missing data. Default: False\naload() \u2192 List[Document]\u00b6\nLoad text from the urls in web_path async into Documents.\nasync fetch_all(urls: List[str]) \u2192 Any\u00b6\nFetch all urls concurrently with rate limiting.\nlazy_load() \u2192 Iterator[Document]\u00b6\nLazy load text from the url(s) in web_path.\nload() \u2192 List[Document][source]\u00b6\nFetch text from one single GitBook page.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nscrape(parser: Optional[str] = None) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.gitbook.GitbookLoader.html"}
{"id": "7e4a760dbb12-2", "text": "List of Documents.\nscrape(parser: Optional[str] = None) \u2192 Any\u00b6\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls: List[str], parser: Optional[str] = None) \u2192 List[Any]\u00b6\nFetch all urls, then return soups for all results.\nExamples using GitbookLoader\u00b6\nGitBook", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.gitbook.GitbookLoader.html"}
{"id": "095dcdf9e8fe-0", "text": "langchain.document_loaders.joplin.JoplinLoader\u00b6\nclass langchain.document_loaders.joplin.JoplinLoader(access_token: Optional[str] = None, port: int = 41184, host: str = 'localhost')[source]\u00b6\nLoad notes from Joplin.\nIn order to use this loader, you need to have Joplin running with the\nWeb Clipper enabled (look for \u201cWeb Clipper\u201d in the app settings).\nTo get the access token, you need to go to the Web Clipper options and\nunder \u201cAdvanced Options\u201d you will find the access token.\nYou can find more information about the Web Clipper service here:\nhttps://joplinapp.org/clipper/\nParameters\naccess_token \u2013 The access token to use.\nport \u2013 The port where the Web Clipper service is running. Default is 41184.\nhost \u2013 The host where the Web Clipper service is running.\nDefault is localhost.\nMethods\n__init__([access_token,\u00a0port,\u00a0host])\nparam access_token\nThe access token to use.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(access_token: Optional[str] = None, port: int = 41184, host: str = 'localhost') \u2192 None[source]\u00b6\nParameters\naccess_token \u2013 The access token to use.\nport \u2013 The port where the Web Clipper service is running. Default is 41184.\nhost \u2013 The host where the Web Clipper service is running.\nDefault is localhost.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.joplin.JoplinLoader.html"}
{"id": "095dcdf9e8fe-1", "text": "load() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using JoplinLoader\u00b6\nJoplin", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.joplin.JoplinLoader.html"}
{"id": "1eaa1db52fe0-0", "text": "langchain.document_loaders.pdf.PyMuPDFLoader\u00b6\nclass langchain.document_loaders.pdf.PyMuPDFLoader(file_path: str, *, headers: Optional[Dict] = None, extract_images: bool = False, **kwargs: Any)[source]\u00b6\nLoad PDF files using PyMuPDF.\nInitialize with a file path.\nAttributes\nsource\nMethods\n__init__(file_path,\u00a0*[,\u00a0headers,\u00a0extract_images])\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload(**kwargs)\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, *, headers: Optional[Dict] = None, extract_images: bool = False, **kwargs: Any) \u2192 None[source]\u00b6\nInitialize with a file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload(**kwargs: Any) \u2192 List[Document][source]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.PyMuPDFLoader.html"}
{"id": "4de4580e645e-0", "text": "langchain.document_loaders.confluence.ConfluenceLoader\u00b6\nclass langchain.document_loaders.confluence.ConfluenceLoader(url: str, api_key: Optional[str] = None, username: Optional[str] = None, session: Optional[Session] = None, oauth2: Optional[dict] = None, token: Optional[str] = None, cloud: Optional[bool] = True, number_of_retries: Optional[int] = 3, min_retry_seconds: Optional[int] = 2, max_retry_seconds: Optional[int] = 10, confluence_kwargs: Optional[dict] = None)[source]\u00b6\nLoad Confluence pages.\nPort of https://llamahub.ai/l/confluence\nThis currently supports username/api_key, Oauth2 login or personal access token\nauthentication.\nSpecify a list page_ids and/or space_key to load in the corresponding pages into\nDocument objects, if both are specified the union of both sets will be returned.\nYou can also specify a boolean include_attachments to include attachments, this\nis set to False by default, if set to True all attachments will be downloaded and\nConfluenceReader will extract the text from the attachments and add it to the\nDocument object. Currently supported attachment types are: PDF, PNG, JPEG/JPG,\nSVG, Word and Excel.\nConfluence API supports difference format of page content. The storage format is the\nraw XML representation for storage. The view format is the HTML representation for\nviewing with macros are rendered as though it is viewed by users. You can pass\na enum content_format argument to load() to specify the content format, this is\nset to ContentFormat.STORAGE by default, the supported values are:\nContentFormat.EDITOR, ContentFormat.EXPORT_VIEW,\nContentFormat.ANONYMOUS_EXPORT_VIEW, ContentFormat.STORAGE,\nand ContentFormat.VIEW.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.confluence.ConfluenceLoader.html"}
{"id": "4de4580e645e-1", "text": "and ContentFormat.VIEW.\nHint: space_key and page_id can both be found in the URL of a page in Confluence\n- https://yoursite.atlassian.com/wiki/spaces/<space_key>/pages/<page_id>\nExample\nfrom langchain.document_loaders import ConfluenceLoader\nloader = ConfluenceLoader(\n    url=\"https://yoursite.atlassian.com/wiki\",\n    username=\"me\",\n    api_key=\"12345\"\n)\ndocuments = loader.load(space_key=\"SPACE\",limit=50)\n# Server on perm\nloader = ConfluenceLoader(\n    url=\"https://confluence.yoursite.com/\",\n    username=\"me\",\n    api_key=\"your_password\",\n    cloud=False\n)\ndocuments = loader.load(space_key=\"SPACE\",limit=50)\nParameters\nurl (str) \u2013 _description_\napi_key (str, optional) \u2013 _description_, defaults to None\nusername (str, optional) \u2013 _description_, defaults to None\noauth2 (dict, optional) \u2013 _description_, defaults to {}\ntoken (str, optional) \u2013 _description_, defaults to None\ncloud (bool, optional) \u2013 _description_, defaults to True\nnumber_of_retries (Optional[int], optional) \u2013 How many times to retry, defaults to 3\nmin_retry_seconds (Optional[int], optional) \u2013 defaults to 2\nmax_retry_seconds (Optional[int], optional) \u2013 defaults to 10\nconfluence_kwargs (dict, optional) \u2013 additional kwargs to initialize confluence with\nRaises\nValueError \u2013 Errors while validating input\nImportError \u2013 Required dependencies not installed.\nMethods\n__init__(url[,\u00a0api_key,\u00a0username,\u00a0session,\u00a0...])\nis_public_page(page)\nCheck if a page is publicly accessible.\nlazy_load()\nA lazy loader for Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.confluence.ConfluenceLoader.html"}
{"id": "4de4580e645e-2", "text": "Check if a page is publicly accessible.\nlazy_load()\nA lazy loader for Documents.\nload([space_key,\u00a0page_ids,\u00a0label,\u00a0cql,\u00a0...])\nparam space_key\nSpace key retrieved from a confluence URL, defaults to None\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\npaginate_request(retrieval_method,\u00a0**kwargs)\nPaginate the various methods to retrieve groups of pages.\nprocess_attachment(page_id[,\u00a0ocr_languages])\nprocess_doc(link)\nprocess_image(link[,\u00a0ocr_languages])\nprocess_page(page,\u00a0include_attachments,\u00a0...)\nprocess_pages(pages,\u00a0...[,\u00a0ocr_languages,\u00a0...])\nProcess a list of pages into a list of documents.\nprocess_pdf(link[,\u00a0ocr_languages])\nprocess_svg(link[,\u00a0ocr_languages])\nprocess_xls(link)\nvalidate_init_args([url,\u00a0api_key,\u00a0username,\u00a0...])\nValidates proper combinations of init arguments\n__init__(url: str, api_key: Optional[str] = None, username: Optional[str] = None, session: Optional[Session] = None, oauth2: Optional[dict] = None, token: Optional[str] = None, cloud: Optional[bool] = True, number_of_retries: Optional[int] = 3, min_retry_seconds: Optional[int] = 2, max_retry_seconds: Optional[int] = 10, confluence_kwargs: Optional[dict] = None)[source]\u00b6\nis_public_page(page: dict) \u2192 bool[source]\u00b6\nCheck if a page is publicly accessible.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.confluence.ConfluenceLoader.html"}
{"id": "4de4580e645e-3", "text": "lazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload(space_key: Optional[str] = None, page_ids: Optional[List[str]] = None, label: Optional[str] = None, cql: Optional[str] = None, include_restricted_content: bool = False, include_archived_content: bool = False, include_attachments: bool = False, include_comments: bool = False, content_format: ContentFormat = ContentFormat.STORAGE, limit: Optional[int] = 50, max_pages: Optional[int] = 1000, ocr_languages: Optional[str] = None, keep_markdown_format: bool = False, keep_newlines: bool = False) \u2192 List[Document][source]\u00b6\nParameters\nspace_key (Optional[str], optional) \u2013 Space key retrieved from a confluence URL, defaults to None\npage_ids (Optional[List[str]], optional) \u2013 List of specific page IDs to load, defaults to None\nlabel (Optional[str], optional) \u2013 Get all pages with this label, defaults to None\ncql (Optional[str], optional) \u2013 CQL Expression, defaults to None\ninclude_restricted_content (bool, optional) \u2013 defaults to False\ninclude_archived_content (bool, optional) \u2013 Whether to include archived content,\ndefaults to False\ninclude_attachments (bool, optional) \u2013 defaults to False\ninclude_comments (bool, optional) \u2013 defaults to False\ncontent_format (ContentFormat) \u2013 Specify content format, defaults to\nContentFormat.STORAGE, the supported values are:\nContentFormat.EDITOR, ContentFormat.EXPORT_VIEW,\nContentFormat.ANONYMOUS_EXPORT_VIEW,\nContentFormat.STORAGE, and ContentFormat.VIEW.\nlimit (int, optional) \u2013 Maximum number of pages to retrieve per request, defaults to 50\nmax_pages (int, optional) \u2013 Maximum number of pages to retrieve in total, defaults 1000", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.confluence.ConfluenceLoader.html"}
{"id": "4de4580e645e-4", "text": "ocr_languages (str, optional) \u2013 The languages to use for the Tesseract agent. To use a\nlanguage, you\u2019ll first need to install the appropriate\nTesseract language pack.\nkeep_markdown_format (bool) \u2013 Whether to keep the markdown format, defaults to\nFalse\nkeep_newlines (bool) \u2013 Whether to keep the newlines format, defaults to\nFalse\nRaises\nValueError \u2013 _description_\nImportError \u2013 _description_\nReturns\n_description_\nReturn type\nList[Document]\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\npaginate_request(retrieval_method: Callable, **kwargs: Any) \u2192 List[source]\u00b6\nPaginate the various methods to retrieve groups of pages.\nUnfortunately, due to page size, sometimes the Confluence API\ndoesn\u2019t match the limit value. If limit is >100 confluence\nseems to cap the response to 100. Also, due to the Atlassian Python\npackage, we don\u2019t get the \u201cnext\u201d values from the \u201c_links\u201d key because\nthey only return the value from the result key. So here, the pagination\nstarts from 0 and goes until the max_pages, getting the limit number\nof pages with each request. We have to manually check if there\nare more docs based on the length of the returned list of pages, rather than\njust checking for the presence of a next key in the response like this page\nwould have you do:\nhttps://developer.atlassian.com/server/confluence/pagination-in-the-rest-api/\nParameters\nretrieval_method (callable) \u2013 Function used to retrieve docs\nReturns", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.confluence.ConfluenceLoader.html"}
{"id": "4de4580e645e-5", "text": "Parameters\nretrieval_method (callable) \u2013 Function used to retrieve docs\nReturns\nList of documents\nReturn type\nList\nprocess_attachment(page_id: str, ocr_languages: Optional[str] = None) \u2192 List[str][source]\u00b6\nprocess_doc(link: str) \u2192 str[source]\u00b6\nprocess_image(link: str, ocr_languages: Optional[str] = None) \u2192 str[source]\u00b6\nprocess_page(page: dict, include_attachments: bool, include_comments: bool, content_format: ContentFormat, ocr_languages: Optional[str] = None, keep_markdown_format: Optional[bool] = False, keep_newlines: bool = False) \u2192 Document[source]\u00b6\nprocess_pages(pages: List[dict], include_restricted_content: bool, include_attachments: bool, include_comments: bool, content_format: ContentFormat, ocr_languages: Optional[str] = None, keep_markdown_format: Optional[bool] = False, keep_newlines: bool = False) \u2192 List[Document][source]\u00b6\nProcess a list of pages into a list of documents.\nprocess_pdf(link: str, ocr_languages: Optional[str] = None) \u2192 str[source]\u00b6\nprocess_svg(link: str, ocr_languages: Optional[str] = None) \u2192 str[source]\u00b6\nprocess_xls(link: str) \u2192 str[source]\u00b6\nstatic validate_init_args(url: Optional[str] = None, api_key: Optional[str] = None, username: Optional[str] = None, session: Optional[Session] = None, oauth2: Optional[dict] = None, token: Optional[str] = None) \u2192 Optional[List][source]\u00b6\nValidates proper combinations of init arguments\nExamples using ConfluenceLoader\u00b6\nConfluence", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.confluence.ConfluenceLoader.html"}
{"id": "c578d916a44a-0", "text": "langchain.document_loaders.mongodb.MongodbLoader\u00b6\nclass langchain.document_loaders.mongodb.MongodbLoader(connection_string: str, db_name: str, collection_name: str, *, filter_criteria: Optional[Dict] = None)[source]\u00b6\nLoad MongoDB documents.\nMethods\n__init__(connection_string,\u00a0db_name,\u00a0...[,\u00a0...])\naload()\nLoad data into Document objects.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(connection_string: str, db_name: str, collection_name: str, *, filter_criteria: Optional[Dict] = None) \u2192 None[source]\u00b6\nasync aload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nAttention:\nThis implementation starts an asyncio event loop which\nwill only work if running in a sync env. In an async env, it should\nfail since there is already an event loop running.\nThis code should be updated to kick off the event loop from a separate\nthread if running within an async context.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.mongodb.MongodbLoader.html"}
{"id": "b6d4f70eff57-0", "text": "langchain.document_loaders.quip.QuipLoader\u00b6\nclass langchain.document_loaders.quip.QuipLoader(api_url: str, access_token: str, request_timeout: Optional[int] = 60)[source]\u00b6\nLoad Quip pages.\nPort of https://github.com/quip/quip-api/tree/master/samples/baqup\nParameters\napi_url \u2013 https://platform.quip.com\naccess_token \u2013 token of access quip API. Please refer:\nhttps \u2013 //quip.com/dev/automation/documentation/current#section/Authentication/Get-Access-to-Quip\u2019s-APIs\nrequest_timeout \u2013 timeout of request, default 60s.\nMethods\n__init__(api_url,\u00a0access_token[,\u00a0...])\nparam api_url\nhttps://platform.quip.com\nget_thread_ids_by_folder_id(folder_id,\u00a0...)\nGet thread ids by folder id and update in thread_ids\nlazy_load()\nA lazy loader for Documents.\nload([folder_ids,\u00a0thread_ids,\u00a0max_docs,\u00a0...])\n:param : param folder_ids: List of specific folder IDs to load, defaults to None :param : param thread_ids: List of specific thread IDs to load, defaults to None :param : param max_docs: Maximum number of docs to retrieve in total, defaults 1000 :param : param include_all_folders: Include all folders that your access_token          can access, but doesn't include your private folder :param : param include_comments: Include comments, defaults to False :param : param include_images: Include images, defaults to False\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nprocess_thread(thread_id,\u00a0include_images,\u00a0...)\nprocess_thread_images(tree)\nprocess_thread_messages(thread_id)\nprocess_threads(thread_ids,\u00a0include_images,\u00a0...)\nProcess a list of thread into a list of documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.quip.QuipLoader.html"}
{"id": "b6d4f70eff57-1", "text": "Process a list of thread into a list of documents.\n__init__(api_url: str, access_token: str, request_timeout: Optional[int] = 60)[source]\u00b6\nParameters\napi_url \u2013 https://platform.quip.com\naccess_token \u2013 token of access quip API. Please refer:\nhttps \u2013 //quip.com/dev/automation/documentation/current#section/Authentication/Get-Access-to-Quip\u2019s-APIs\nrequest_timeout \u2013 timeout of request, default 60s.\nget_thread_ids_by_folder_id(folder_id: str, depth: int, thread_ids: List[str]) \u2192 None[source]\u00b6\nGet thread ids by folder id and update in thread_ids\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload(folder_ids: Optional[List[str]] = None, thread_ids: Optional[List[str]] = None, max_docs: Optional[int] = 1000, include_all_folders: bool = False, include_comments: bool = False, include_images: bool = False) \u2192 List[Document][source]\u00b6\n:param : param folder_ids: List of specific folder IDs to load, defaults to None\n:param : param thread_ids: List of specific thread IDs to load, defaults to None\n:param : param max_docs: Maximum number of docs to retrieve in total, defaults 1000\n:param : param include_all_folders: Include all folders that your access_token\ncan access, but doesn\u2019t include your private folder\n:param : param include_comments: Include comments, defaults to False\n:param : param include_images: Include images, defaults to False\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.quip.QuipLoader.html"}
{"id": "b6d4f70eff57-2", "text": "Defaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nprocess_thread(thread_id: str, include_images: bool, include_messages: bool) \u2192 Optional[Document][source]\u00b6\nprocess_thread_images(tree: ElementTree) \u2192 str[source]\u00b6\nprocess_thread_messages(thread_id: str) \u2192 str[source]\u00b6\nprocess_threads(thread_ids: Sequence[str], include_images: bool, include_messages: bool) \u2192 List[Document][source]\u00b6\nProcess a list of thread into a list of documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.quip.QuipLoader.html"}
{"id": "443d64fdbc76-0", "text": "langchain.document_loaders.powerpoint.UnstructuredPowerPointLoader\u00b6\nclass langchain.document_loaders.powerpoint.UnstructuredPowerPointLoader(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad Microsoft PowerPoint files using Unstructured.\nWorks with both .ppt and .pptx files.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredPowerPointLoader\nloader = UnstructuredPowerPointLoader(\u201cexample.pptx\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition-pptx\nInitialize with file path.\nMethods\n__init__(file_path[,\u00a0mode])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: Union[str, List[str]], mode: str = 'single', **unstructured_kwargs: Any)\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.powerpoint.UnstructuredPowerPointLoader.html"}
{"id": "443d64fdbc76-1", "text": "Load Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredPowerPointLoader\u00b6\nMicrosoft PowerPoint", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.powerpoint.UnstructuredPowerPointLoader.html"}
{"id": "06ab36eb9fc6-0", "text": "langchain.document_loaders.psychic.PsychicLoader\u00b6\nclass langchain.document_loaders.psychic.PsychicLoader(api_key: str, account_id: str, connector_id: Optional[str] = None)[source]\u00b6\nLoad from Psychic.dev.\nInitialize with API key, connector id, and account id.\nParameters\napi_key \u2013 The Psychic API key.\naccount_id \u2013 The Psychic account id.\nconnector_id \u2013 The Psychic connector id.\nMethods\n__init__(api_key,\u00a0account_id[,\u00a0connector_id])\nInitialize with API key, connector id, and account id.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(api_key: str, account_id: str, connector_id: Optional[str] = None)[source]\u00b6\nInitialize with API key, connector id, and account id.\nParameters\napi_key \u2013 The Psychic API key.\naccount_id \u2013 The Psychic account id.\nconnector_id \u2013 The Psychic connector id.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using PsychicLoader\u00b6\nPsychic", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.psychic.PsychicLoader.html"}
{"id": "125b4eb4d8fb-0", "text": "langchain.document_loaders.csv_loader.CSVLoader\u00b6\nclass langchain.document_loaders.csv_loader.CSVLoader(file_path: str, source_column: Optional[str] = None, metadata_columns: Sequence[str] = (), csv_args: Optional[Dict] = None, encoding: Optional[str] = None, autodetect_encoding: bool = False)[source]\u00b6\nLoad a CSV file into a list of Documents.\nEach document represents one row of the CSV file. Every row is converted into a\nkey/value pair and outputted to a new line in the document\u2019s page_content.\nThe source for each document loaded from csv is set to the value of the\nfile_path argument for all documents by default.\nYou can override this by setting the source_column argument to the\nname of a column in the CSV file.\nThe source of each document will then be set to the value of the column\nwith the name specified in source_column.\nOutput Example:column1: value1\ncolumn2: value2\ncolumn3: value3\nParameters\nfile_path \u2013 The path to the CSV file.\nsource_column \u2013 The name of the column in the CSV file to use as the source.\nOptional. Defaults to None.\nmetadata_columns \u2013 A sequence of column names to use as metadata. Optional.\ncsv_args \u2013 A dictionary of arguments to pass to the csv.DictReader.\nOptional. Defaults to None.\nencoding \u2013 The encoding of the CSV file. Optional. Defaults to None.\nautodetect_encoding \u2013 Whether to try to autodetect the file encoding.\nMethods\n__init__(file_path[,\u00a0source_column,\u00a0...])\nparam file_path\nThe path to the CSV file.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.csv_loader.CSVLoader.html"}
{"id": "125b4eb4d8fb-1", "text": "load_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, source_column: Optional[str] = None, metadata_columns: Sequence[str] = (), csv_args: Optional[Dict] = None, encoding: Optional[str] = None, autodetect_encoding: bool = False)[source]\u00b6\nParameters\nfile_path \u2013 The path to the CSV file.\nsource_column \u2013 The name of the column in the CSV file to use as the source.\nOptional. Defaults to None.\nmetadata_columns \u2013 A sequence of column names to use as metadata. Optional.\ncsv_args \u2013 A dictionary of arguments to pass to the csv.DictReader.\nOptional. Defaults to None.\nencoding \u2013 The encoding of the CSV file. Optional. Defaults to None.\nautodetect_encoding \u2013 Whether to try to autodetect the file encoding.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using CSVLoader\u00b6\nChatGPT Plugin\nCSV", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.csv_loader.CSVLoader.html"}
{"id": "a6ef57175b7f-0", "text": "langchain.document_loaders.base.BaseBlobParser\u00b6\nclass langchain.document_loaders.base.BaseBlobParser[source]\u00b6\nAbstract interface for blob parsers.\nA blob parser provides a way to parse raw data stored in a blob into one\nor more documents.\nThe parser can be composed with blob loaders, making it easy to reuse\na parser independent of how the blob was originally loaded.\nMethods\n__init__()\nlazy_parse(blob)\nLazy parsing interface.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__()\u00b6\nabstract lazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLazy parsing interface.\nSubclasses are required to implement this method.\nParameters\nblob \u2013 Blob instance\nReturns\nGenerator of documents\nparse(blob: Blob) \u2192 List[Document][source]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.base.BaseBlobParser.html"}
{"id": "eccf581cc030-0", "text": "langchain.document_loaders.blob_loaders.schema.Blob\u00b6\nclass langchain.document_loaders.blob_loaders.schema.Blob[source]\u00b6\nBases: BaseModel\nBlob represents raw data by either reference or value.\nProvides an interface to materialize the blob in different representations, and\nhelp to decouple the development of data loaders from the downstream parsing of\nthe raw data.\nInspired by: https://developer.mozilla.org/en-US/docs/Web/API/Blob\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam data: Optional[Union[bytes, str]] = None\u00b6\nparam encoding: str = 'utf-8'\u00b6\nparam mimetype: Optional[str] = None\u00b6\nparam path: Optional[Union[str, pathlib.PurePath]] = None\u00b6\nas_bytes() \u2192 bytes[source]\u00b6\nRead data as bytes.\nas_bytes_io() \u2192 Generator[Union[BytesIO, BufferedReader], None, None][source]\u00b6\nRead data as a byte stream.\nas_string() \u2192 str[source]\u00b6\nRead data as a string.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blob_loaders.schema.Blob.html"}
{"id": "eccf581cc030-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_data(data: Union[str, bytes], *, encoding: str = 'utf-8', mime_type: Optional[str] = None, path: Optional[str] = None) \u2192 Blob[source]\u00b6\nInitialize the blob from in-memory data.\nParameters\ndata \u2013 the in-memory data associated with the blob\nencoding \u2013 Encoding to use if decoding the bytes into a string\nmime_type \u2013 if provided, will be set as the mime-type of the data\npath \u2013 if provided, will be set as the source from which the data came\nReturns\nBlob instance\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_path(path: Union[str, PurePath], *, encoding: str = 'utf-8', mime_type: Optional[str] = None, guess_type: bool = True) \u2192 Blob[source]\u00b6\nLoad the blob from a path like object.\nParameters\npath \u2013 path like object to file to be read", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blob_loaders.schema.Blob.html"}
{"id": "eccf581cc030-2", "text": "Parameters\npath \u2013 path like object to file to be read\nencoding \u2013 Encoding to use if decoding the bytes into a string\nmime_type \u2013 if provided, will be set as the mime-type of the data\nguess_type \u2013 If True, the mimetype will be guessed from the file extension,\nif a mime-type was not provided\nReturns\nBlob instance\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blob_loaders.schema.Blob.html"}
{"id": "eccf581cc030-3", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty source: Optional[str]\u00b6\nThe source location of the blob as string if known otherwise none.\nExamples using Blob\u00b6\ndocai.md\nEmbaas", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blob_loaders.schema.Blob.html"}
{"id": "0d993cedb2e3-0", "text": "langchain.document_loaders.tsv.UnstructuredTSVLoader\u00b6\nclass langchain.document_loaders.tsv.UnstructuredTSVLoader(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad TSV files using Unstructured.\nLike other\nUnstructured loaders, UnstructuredTSVLoader can be used in both\n\u201csingle\u201d and \u201celements\u201d mode. If you use the loader in \u201celements\u201d\nmode, the TSV file will be a single Unstructured Table element.\nIf you use the loader in \u201celements\u201d mode, an HTML representation\nof the table will be available in the \u201ctext_as_html\u201d key in the\ndocument metadata.\nExamples\nfrom langchain.document_loaders.tsv import UnstructuredTSVLoader\nloader = UnstructuredTSVLoader(\u201cstanley-cups.tsv\u201d, mode=\u201delements\u201d)\ndocs = loader.load()\nInitialize with file path.\nMethods\n__init__(file_path[,\u00a0mode])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredTSVLoader\u00b6\nTSV", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.tsv.UnstructuredTSVLoader.html"}
{"id": "89706734a71e-0", "text": "langchain.document_loaders.url_playwright.UnstructuredHtmlEvaluator\u00b6\nclass langchain.document_loaders.url_playwright.UnstructuredHtmlEvaluator(remove_selectors: Optional[List[str]] = None)[source]\u00b6\nEvaluates the page HTML content using the unstructured library.\nInitialize UnstructuredHtmlEvaluator.\nMethods\n__init__([remove_selectors])\nInitialize UnstructuredHtmlEvaluator.\nevaluate(page,\u00a0browser,\u00a0response)\nSynchronously process the HTML content of the page.\nevaluate_async(page,\u00a0browser,\u00a0response)\nAsynchronously process the HTML content of the page.\n__init__(remove_selectors: Optional[List[str]] = None)[source]\u00b6\nInitialize UnstructuredHtmlEvaluator.\nevaluate(page: Page, browser: Browser, response: Response) \u2192 str[source]\u00b6\nSynchronously process the HTML content of the page.\nasync evaluate_async(page: AsyncPage, browser: AsyncBrowser, response: AsyncResponse) \u2192 str[source]\u00b6\nAsynchronously process the HTML content of the page.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.url_playwright.UnstructuredHtmlEvaluator.html"}
{"id": "b8988843deba-0", "text": "langchain.document_loaders.baiducloud_bos_file.BaiduBOSFileLoader\u00b6\nclass langchain.document_loaders.baiducloud_bos_file.BaiduBOSFileLoader(conf: Any, bucket: str, key: str)[source]\u00b6\nLoad from Baidu Cloud BOS file.\nInitialize with BOS config, bucket and key name.\n:param conf(BceClientConfiguration): BOS config.\n:param bucket(str): BOS bucket.\n:param key(str): BOS file key.\nMethods\n__init__(conf,\u00a0bucket,\u00a0key)\nInitialize with BOS config, bucket and key name.\nlazy_load()\nLoad documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(conf: Any, bucket: str, key: str)[source]\u00b6\nInitialize with BOS config, bucket and key name.\n:param conf(BceClientConfiguration): BOS config.\n:param bucket(str): BOS bucket.\n:param key(str): BOS file key.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLoad documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.baiducloud_bos_file.BaiduBOSFileLoader.html"}
{"id": "e3f2b098eec9-0", "text": "langchain.document_loaders.stripe.StripeLoader\u00b6\nclass langchain.document_loaders.stripe.StripeLoader(resource: str, access_token: Optional[str] = None)[source]\u00b6\nLoad from Stripe API.\nInitialize with a resource and an access token.\nParameters\nresource \u2013 The resource.\naccess_token \u2013 The access token.\nMethods\n__init__(resource[,\u00a0access_token])\nInitialize with a resource and an access token.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(resource: str, access_token: Optional[str] = None) \u2192 None[source]\u00b6\nInitialize with a resource and an access token.\nParameters\nresource \u2013 The resource.\naccess_token \u2013 The access token.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using StripeLoader\u00b6\nStripe", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.stripe.StripeLoader.html"}
{"id": "2d15289e50ef-0", "text": "langchain.document_loaders.imsdb.IMSDbLoader\u00b6\nclass langchain.document_loaders.imsdb.IMSDbLoader(web_path: Union[str, Sequence[str]] = '', header_template: Optional[dict] = None, verify_ssl: bool = True, proxies: Optional[dict] = None, continue_on_failure: bool = False, autoset_encoding: bool = True, encoding: Optional[str] = None, web_paths: Sequence[str] = (), requests_per_second: int = 2, default_parser: str = 'html.parser', requests_kwargs: Optional[Dict[str, Any]] = None, raise_for_status: bool = False, bs_get_text_kwargs: Optional[Dict[str, Any]] = None, bs_kwargs: Optional[Dict[str, Any]] = None, session: Any = None)[source]\u00b6\nLoad IMSDb webpages.\nInitialize loader.\nParameters\nweb_paths \u2013 Web paths to load from.\nrequests_per_second \u2013 Max number of concurrent requests to make.\ndefault_parser \u2013 Default parser to use for BeautifulSoup.\nrequests_kwargs \u2013 kwargs for requests\nraise_for_status \u2013 Raise an exception if http status code denotes an error.\nbs_get_text_kwargs \u2013 kwargs for beatifulsoup4 get_text\nbs_kwargs \u2013 kwargs for beatifulsoup4 web page parsing\nAttributes\nweb_path\nMethods\n__init__([web_path,\u00a0header_template,\u00a0...])\nInitialize loader.\naload()\nLoad text from the urls in web_path async into Documents.\nfetch_all(urls)\nFetch all urls concurrently with rate limiting.\nlazy_load()\nLazy load text from the url(s) in web_path.\nload()\nLoad webpage.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nscrape([parser])\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls[,\u00a0parser])", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.imsdb.IMSDbLoader.html"}
{"id": "2d15289e50ef-1", "text": "scrape_all(urls[,\u00a0parser])\nFetch all urls, then return soups for all results.\n__init__(web_path: Union[str, Sequence[str]] = '', header_template: Optional[dict] = None, verify_ssl: bool = True, proxies: Optional[dict] = None, continue_on_failure: bool = False, autoset_encoding: bool = True, encoding: Optional[str] = None, web_paths: Sequence[str] = (), requests_per_second: int = 2, default_parser: str = 'html.parser', requests_kwargs: Optional[Dict[str, Any]] = None, raise_for_status: bool = False, bs_get_text_kwargs: Optional[Dict[str, Any]] = None, bs_kwargs: Optional[Dict[str, Any]] = None, session: Any = None) \u2192 None\u00b6\nInitialize loader.\nParameters\nweb_paths \u2013 Web paths to load from.\nrequests_per_second \u2013 Max number of concurrent requests to make.\ndefault_parser \u2013 Default parser to use for BeautifulSoup.\nrequests_kwargs \u2013 kwargs for requests\nraise_for_status \u2013 Raise an exception if http status code denotes an error.\nbs_get_text_kwargs \u2013 kwargs for beatifulsoup4 get_text\nbs_kwargs \u2013 kwargs for beatifulsoup4 web page parsing\naload() \u2192 List[Document]\u00b6\nLoad text from the urls in web_path async into Documents.\nasync fetch_all(urls: List[str]) \u2192 Any\u00b6\nFetch all urls concurrently with rate limiting.\nlazy_load() \u2192 Iterator[Document]\u00b6\nLazy load text from the url(s) in web_path.\nload() \u2192 List[Document][source]\u00b6\nLoad webpage.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.imsdb.IMSDbLoader.html"}
{"id": "2d15289e50ef-2", "text": "Parameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nscrape(parser: Optional[str] = None) \u2192 Any\u00b6\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls: List[str], parser: Optional[str] = None) \u2192 List[Any]\u00b6\nFetch all urls, then return soups for all results.\nExamples using IMSDbLoader\u00b6\nIMSDb", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.imsdb.IMSDbLoader.html"}
{"id": "4fe84d4fb681-0", "text": "langchain.document_loaders.parsers.pdf.PyPDFParser\u00b6\nclass langchain.document_loaders.parsers.pdf.PyPDFParser(password: Optional[Union[str, bytes]] = None, extract_images: bool = False)[source]\u00b6\nLoad PDF using pypdf\nMethods\n__init__([password,\u00a0extract_images])\nlazy_parse(blob)\nLazily parse the blob.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__(password: Optional[Union[str, bytes]] = None, extract_images: bool = False)[source]\u00b6\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLazily parse the blob.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.pdf.PyPDFParser.html"}
{"id": "69ad40d378f5-0", "text": "langchain.document_loaders.whatsapp_chat.WhatsAppChatLoader\u00b6\nclass langchain.document_loaders.whatsapp_chat.WhatsAppChatLoader(path: str)[source]\u00b6\nLoad WhatsApp messages text file.\nInitialize with path.\nMethods\n__init__(path)\nInitialize with path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(path: str)[source]\u00b6\nInitialize with path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using WhatsAppChatLoader\u00b6\nWhatsApp\nWhatsApp Chat", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.whatsapp_chat.WhatsAppChatLoader.html"}
{"id": "1dcfeab517eb-0", "text": "langchain.document_loaders.gutenberg.GutenbergLoader\u00b6\nclass langchain.document_loaders.gutenberg.GutenbergLoader(file_path: str)[source]\u00b6\nLoad from Gutenberg.org.\nInitialize with a file path.\nMethods\n__init__(file_path)\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str)[source]\u00b6\nInitialize with a file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using GutenbergLoader\u00b6\nGutenberg", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.gutenberg.GutenbergLoader.html"}
{"id": "cec534b0ac17-0", "text": "langchain.document_loaders.recursive_url_loader.RecursiveUrlLoader\u00b6\nclass langchain.document_loaders.recursive_url_loader.RecursiveUrlLoader(url: str, max_depth: Optional[int] = 2, use_async: Optional[bool] = None, extractor: Optional[Callable[[str], str]] = None, metadata_extractor: Optional[Callable[[str, str], str]] = None, exclude_dirs: Optional[Sequence[str]] = (), timeout: Optional[int] = 10, prevent_outside: bool = True, link_regex: Optional[Union[str, Pattern]] = None, headers: Optional[dict] = None, check_response_status: bool = False)[source]\u00b6\nLoad all child links from a URL page.\nSecurity Note: This loader is a crawler that will start crawlingat a given URL and then expand to crawl child links recursively.\nWeb crawlers should generally NOT be deployed with network access\nto any internal servers.\nControl access to who can submit crawling requests and what network access\nthe crawler has.\nWhile crawling, the crawler may encounter malicious URLs that would lead to a\nserver-side request forgery (SSRF) attack.\nTo mitigate risks, the crawler by default will only load URLs from the same\ndomain as the start URL (controlled via prevent_outside named argument).\nThis will mitigate the risk of SSRF attacks, but will not eliminate it.\nFor example, if crawling a host which hosts several sites:\nhttps://some_host/alice_site/\nhttps://some_host/bob_site/\nA malicious URL on Alice\u2019s site could cause the crawler to make a malicious\nGET request to an endpoint on Bob\u2019s site. Both sites are hosted on the\nsame host, so such a request would not be prevented by default.\nSee https://python.langchain.com/docs/security\nInitialize with URL to crawl and any subdirectories to exclude.\nParameters", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.recursive_url_loader.RecursiveUrlLoader.html"}
{"id": "cec534b0ac17-1", "text": "Initialize with URL to crawl and any subdirectories to exclude.\nParameters\nurl \u2013 The URL to crawl.\nmax_depth \u2013 The max depth of the recursive loading.\nuse_async \u2013 Whether to use asynchronous loading.\nIf True, this function will not be lazy, but it will still work in the\nexpected way, just not lazy.\nextractor \u2013 A function to extract document contents from raw html.\nWhen extract function returns an empty string, the document is\nignored.\nmetadata_extractor \u2013 A function to extract metadata from raw html and the\nsource url (args in that order). Default extractor will attempt\nto use BeautifulSoup4 to extract the title, description and language\nof the page.\nexclude_dirs \u2013 A list of subdirectories to exclude.\ntimeout \u2013 The timeout for the requests, in the unit of seconds. If None then\nconnection will not timeout.\nprevent_outside \u2013 If True, prevent loading from urls which are not children\nof the root url.\nlink_regex \u2013 Regex for extracting sub-links from the raw html of a web page.\ncheck_response_status \u2013 If True, check HTTP response status and skip\nURLs with error responses (400-599).\nMethods\n__init__(url[,\u00a0max_depth,\u00a0use_async,\u00a0...])\nInitialize with URL to crawl and any subdirectories to exclude.\nlazy_load()\nLazy load web pages.\nload()\nLoad web pages.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.recursive_url_loader.RecursiveUrlLoader.html"}
{"id": "cec534b0ac17-2", "text": "load_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(url: str, max_depth: Optional[int] = 2, use_async: Optional[bool] = None, extractor: Optional[Callable[[str], str]] = None, metadata_extractor: Optional[Callable[[str, str], str]] = None, exclude_dirs: Optional[Sequence[str]] = (), timeout: Optional[int] = 10, prevent_outside: bool = True, link_regex: Optional[Union[str, Pattern]] = None, headers: Optional[dict] = None, check_response_status: bool = False) \u2192 None[source]\u00b6\nInitialize with URL to crawl and any subdirectories to exclude.\nParameters\nurl \u2013 The URL to crawl.\nmax_depth \u2013 The max depth of the recursive loading.\nuse_async \u2013 Whether to use asynchronous loading.\nIf True, this function will not be lazy, but it will still work in the\nexpected way, just not lazy.\nextractor \u2013 A function to extract document contents from raw html.\nWhen extract function returns an empty string, the document is\nignored.\nmetadata_extractor \u2013 A function to extract metadata from raw html and the\nsource url (args in that order). Default extractor will attempt\nto use BeautifulSoup4 to extract the title, description and language\nof the page.\nexclude_dirs \u2013 A list of subdirectories to exclude.\ntimeout \u2013 The timeout for the requests, in the unit of seconds. If None then\nconnection will not timeout.\nprevent_outside \u2013 If True, prevent loading from urls which are not children\nof the root url.\nlink_regex \u2013 Regex for extracting sub-links from the raw html of a web page.\ncheck_response_status \u2013 If True, check HTTP response status and skip\nURLs with error responses (400-599).\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load web pages.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.recursive_url_loader.RecursiveUrlLoader.html"}
{"id": "cec534b0ac17-3", "text": "lazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load web pages.\nWhen use_async is True, this function will not be lazy,\nbut it will still work in the expected way, just not lazy.\nload() \u2192 List[Document][source]\u00b6\nLoad web pages.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using RecursiveUrlLoader\u00b6\nRecursive URL Loader", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.recursive_url_loader.RecursiveUrlLoader.html"}
{"id": "5d4802b1044c-0", "text": "langchain.document_loaders.airbyte.AirbyteZendeskSupportLoader\u00b6\nclass langchain.document_loaders.airbyte.AirbyteZendeskSupportLoader(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None)[source]\u00b6\nLoad from Zendesk Support using an Airbyte source connector.\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nAttributes\nlast_state\nMethods\n__init__(config,\u00a0stream_name[,\u00a0...])\nInitializes the loader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(config: Mapping[str, Any], stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None) \u2192 None[source]\u00b6\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad data into Document objects.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteZendeskSupportLoader.html"}
{"id": "5d4802b1044c-1", "text": "load() \u2192 List[Document]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AirbyteZendeskSupportLoader\u00b6\nAirbyte Zendesk Support", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteZendeskSupportLoader.html"}
{"id": "0233306da3e9-0", "text": "langchain.document_loaders.mhtml.MHTMLLoader\u00b6\nclass langchain.document_loaders.mhtml.MHTMLLoader(file_path: str, open_encoding: Optional[str] = None, bs_kwargs: Optional[dict] = None, get_text_separator: str = '')[source]\u00b6\nParse MHTML files with BeautifulSoup.\nInitialise with path, and optionally, file encoding to use, and any kwargs\nto pass to the BeautifulSoup object.\nParameters\nfile_path \u2013 Path to file to load.\nopen_encoding \u2013 The encoding to use when opening the file.\nbs_kwargs \u2013 Any kwargs to pass to the BeautifulSoup object.\nget_text_separator \u2013 The separator to use when getting the text\nfrom the soup.\nMethods\n__init__(file_path[,\u00a0open_encoding,\u00a0...])\nInitialise with path, and optionally, file encoding to use, and any kwargs to pass to the BeautifulSoup object.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, open_encoding: Optional[str] = None, bs_kwargs: Optional[dict] = None, get_text_separator: str = '') \u2192 None[source]\u00b6\nInitialise with path, and optionally, file encoding to use, and any kwargs\nto pass to the BeautifulSoup object.\nParameters\nfile_path \u2013 Path to file to load.\nopen_encoding \u2013 The encoding to use when opening the file.\nbs_kwargs \u2013 Any kwargs to pass to the BeautifulSoup object.\nget_text_separator \u2013 The separator to use when getting the text\nfrom the soup.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.mhtml.MHTMLLoader.html"}
{"id": "0233306da3e9-1", "text": "load() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using MHTMLLoader\u00b6\nmhtml", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.mhtml.MHTMLLoader.html"}
{"id": "cec4b30479b8-0", "text": "langchain.document_loaders.wikipedia.WikipediaLoader\u00b6\nclass langchain.document_loaders.wikipedia.WikipediaLoader(query: str, lang: str = 'en', load_max_docs: Optional[int] = 100, load_all_available_meta: Optional[bool] = False, doc_content_chars_max: Optional[int] = 4000)[source]\u00b6\nLoad from Wikipedia.\nThe hard limit on the number of downloaded Documents is 300 for now.\nEach wiki page represents one Document.\nInitializes a new instance of the WikipediaLoader class.\nParameters\nquery (str) \u2013 The query string to search on Wikipedia.\nlang (str, optional) \u2013 The language code for the Wikipedia language edition.\nDefaults to \u201cen\u201d.\nload_max_docs (int, optional) \u2013 The maximum number of documents to load.\nDefaults to 100.\nload_all_available_meta (bool, optional) \u2013 Indicates whether to load all\navailable metadata for each document. Defaults to False.\ndoc_content_chars_max (int, optional) \u2013 The maximum number of characters\nfor the document content. Defaults to 4000.\nMethods\n__init__(query[,\u00a0lang,\u00a0load_max_docs,\u00a0...])\nInitializes a new instance of the WikipediaLoader class.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoads the query result from Wikipedia into a list of Documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(query: str, lang: str = 'en', load_max_docs: Optional[int] = 100, load_all_available_meta: Optional[bool] = False, doc_content_chars_max: Optional[int] = 4000)[source]\u00b6\nInitializes a new instance of the WikipediaLoader class.\nParameters\nquery (str) \u2013 The query string to search on Wikipedia.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.wikipedia.WikipediaLoader.html"}
{"id": "cec4b30479b8-1", "text": "Parameters\nquery (str) \u2013 The query string to search on Wikipedia.\nlang (str, optional) \u2013 The language code for the Wikipedia language edition.\nDefaults to \u201cen\u201d.\nload_max_docs (int, optional) \u2013 The maximum number of documents to load.\nDefaults to 100.\nload_all_available_meta (bool, optional) \u2013 Indicates whether to load all\navailable metadata for each document. Defaults to False.\ndoc_content_chars_max (int, optional) \u2013 The maximum number of characters\nfor the document content. Defaults to 4000.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoads the query result from Wikipedia into a list of Documents.\nReturns\nA list of Document objects representing the loadedWikipedia pages.\nReturn type\nList[Document]\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using WikipediaLoader\u00b6\nWikipedia\nDiffbot Graph Transformer", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.wikipedia.WikipediaLoader.html"}
{"id": "2f29d672671f-0", "text": "langchain.document_loaders.tomarkdown.ToMarkdownLoader\u00b6\nclass langchain.document_loaders.tomarkdown.ToMarkdownLoader(url: str, api_key: str)[source]\u00b6\nLoad HTML using 2markdown API.\nInitialize with url and api key.\nMethods\n__init__(url,\u00a0api_key)\nInitialize with url and api key.\nlazy_load()\nLazily load the file.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(url: str, api_key: str)[source]\u00b6\nInitialize with url and api key.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazily load the file.\nload() \u2192 List[Document][source]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using ToMarkdownLoader\u00b6\n2Markdown", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.tomarkdown.ToMarkdownLoader.html"}
{"id": "69939151e61e-0", "text": "langchain.document_loaders.url_playwright.PlaywrightEvaluator\u00b6\nclass langchain.document_loaders.url_playwright.PlaywrightEvaluator[source]\u00b6\nAbstract base class for all evaluators.\nEach evaluator should take a page, a browser instance, and a response\nobject, process the page as necessary, and return the resulting text.\nMethods\n__init__()\nevaluate(page,\u00a0browser,\u00a0response)\nSynchronously process the page and return the resulting text.\nevaluate_async(page,\u00a0browser,\u00a0response)\nAsynchronously process the page and return the resulting text.\n__init__()\u00b6\nabstract evaluate(page: Page, browser: Browser, response: Response) \u2192 str[source]\u00b6\nSynchronously process the page and return the resulting text.\nParameters\npage \u2013 The page to process.\nbrowser \u2013 The browser instance.\nresponse \u2013 The response from page.goto().\nReturns\nThe text content of the page.\nReturn type\ntext\nabstract async evaluate_async(page: AsyncPage, browser: AsyncBrowser, response: AsyncResponse) \u2192 str[source]\u00b6\nAsynchronously process the page and return the resulting text.\nParameters\npage \u2013 The page to process.\nbrowser \u2013 The browser instance.\nresponse \u2013 The response from page.goto().\nReturns\nThe text content of the page.\nReturn type\ntext", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.url_playwright.PlaywrightEvaluator.html"}
{"id": "11125c1caaa1-0", "text": "langchain.document_loaders.parsers.audio.OpenAIWhisperParserLocal\u00b6\nclass langchain.document_loaders.parsers.audio.OpenAIWhisperParserLocal(device: str = '0', lang_model: Optional[str] = None, forced_decoder_ids: Optional[Tuple[Dict]] = None)[source]\u00b6\nTranscribe and parse audio files with OpenAI Whisper model.\nAudio transcription with OpenAI Whisper model locally from transformers.\nParameters:\ndevice - device to use\nNOTE: By default uses the gpu if available,\nif you want to use cpu, please set device = \u201ccpu\u201d\nlang_model - whisper model to use, for example \u201copenai/whisper-medium\u201d\nforced_decoder_ids - id states for decoder in multilanguage model,\nusage example:\nfrom transformers import WhisperProcessor\nprocessor = WhisperProcessor.from_pretrained(\u201copenai/whisper-medium\u201d)\nforced_decoder_ids = WhisperProcessor.get_decoder_prompt_ids(language=\u201dfrench\u201d,\ntask=\u201dtranscribe\u201d)\nforced_decoder_ids = WhisperProcessor.get_decoder_prompt_ids(language=\u201dfrench\u201d,\ntask=\u201dtranslate\u201d)\nInitialize the parser.\nParameters\ndevice \u2013 device to use.\nlang_model \u2013 whisper model to use, for example \u201copenai/whisper-medium\u201d.\nDefaults to None.\nforced_decoder_ids \u2013 id states for decoder in a multilanguage model.\nDefaults to None.\nMethods\n__init__([device,\u00a0lang_model,\u00a0...])\nInitialize the parser.\nlazy_parse(blob)\nLazily parse the blob.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__(device: str = '0', lang_model: Optional[str] = None, forced_decoder_ids: Optional[Tuple[Dict]] = None)[source]\u00b6\nInitialize the parser.\nParameters\ndevice \u2013 device to use.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.audio.OpenAIWhisperParserLocal.html"}
{"id": "11125c1caaa1-1", "text": "Initialize the parser.\nParameters\ndevice \u2013 device to use.\nlang_model \u2013 whisper model to use, for example \u201copenai/whisper-medium\u201d.\nDefaults to None.\nforced_decoder_ids \u2013 id states for decoder in a multilanguage model.\nDefaults to None.\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLazily parse the blob.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.audio.OpenAIWhisperParserLocal.html"}
{"id": "bc6fb583710a-0", "text": "langchain.document_loaders.rss.RSSFeedLoader\u00b6\nclass langchain.document_loaders.rss.RSSFeedLoader(urls: Optional[Sequence[str]] = None, opml: Optional[str] = None, continue_on_failure: bool = True, show_progress_bar: bool = False, **newsloader_kwargs: Any)[source]\u00b6\nLoad news articles from RSS feeds using Unstructured.\nParameters\nurls \u2013 URLs for RSS feeds to load. Each articles in the feed is loaded into its own document.\nopml \u2013 OPML file to load feed urls from. Only one of urls or opml should be provided.  The value\nstring (can be a URL) \u2013 \nstring. (or OPML markup contents as byte or) \u2013 \ncontinue_on_failure \u2013 If True, continue loading documents even if\nloading fails for a particular URL.\nshow_progress_bar \u2013 If True, use tqdm to show a loading progress bar. Requires\ntqdm to be installed, pip install tqdm.\n**newsloader_kwargs \u2013 Any additional named arguments to pass to\nNewsURLLoader.\nExample\nfrom langchain.document_loaders import RSSFeedLoader\nloader = RSSFeedLoader(\n    urls=[\"<url-1>\", \"<url-2>\"],\n)\ndocs = loader.load()\nThe loader uses feedparser to parse RSS feeds.  The feedparser library is not installed by default so you should\ninstall it if using this loader:\nhttps://pythonhosted.org/feedparser/\nIf you use OPML, you should also install listparser:\nhttps://pythonhosted.org/listparser/\nFinally, newspaper is used to process each article:\nhttps://newspaper.readthedocs.io/en/latest/\nInitialize with urls or OPML.\nMethods\n__init__([urls,\u00a0opml,\u00a0continue_on_failure,\u00a0...])\nInitialize with urls or OPML.\nlazy_load()", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.rss.RSSFeedLoader.html"}
{"id": "bc6fb583710a-1", "text": "Initialize with urls or OPML.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(urls: Optional[Sequence[str]] = None, opml: Optional[str] = None, continue_on_failure: bool = True, show_progress_bar: bool = False, **newsloader_kwargs: Any) \u2192 None[source]\u00b6\nInitialize with urls or OPML.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using RSSFeedLoader\u00b6\nRSS Feeds", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.rss.RSSFeedLoader.html"}
{"id": "f9b28469aa6d-0", "text": "langchain.document_loaders.excel.UnstructuredExcelLoader\u00b6\nclass langchain.document_loaders.excel.UnstructuredExcelLoader(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad Microsoft Excel files using Unstructured.\nLike other\nUnstructured loaders, UnstructuredExcelLoader can be used in both\n\u201csingle\u201d and \u201celements\u201d mode. If you use the loader in \u201celements\u201d\nmode, each sheet in the Excel file will be a an Unstructured Table\nelement. If you use the loader in \u201celements\u201d mode, an\nHTML representation of the table will be available in the\n\u201ctext_as_html\u201d key in the document metadata.\nExamples\nfrom langchain.document_loaders.excel import UnstructuredExcelLoader\nloader = UnstructuredExcelLoader(\u201cstanley-cups.xlsd\u201d, mode=\u201delements\u201d)\ndocs = loader.load()\nParameters\nfile_path \u2013 The path to the Microsoft Excel file.\nmode \u2013 The mode to use when partitioning the file. See unstructured docs\nfor more info. Optional. Defaults to \u201csingle\u201d.\n**unstructured_kwargs \u2013 Keyword arguments to pass to unstructured.\nMethods\n__init__(file_path[,\u00a0mode])\nparam file_path\nThe path to the Microsoft Excel file.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nParameters\nfile_path \u2013 The path to the Microsoft Excel file.\nmode \u2013 The mode to use when partitioning the file. See unstructured docs\nfor more info. Optional. Defaults to \u201csingle\u201d.\n**unstructured_kwargs \u2013 Keyword arguments to pass to unstructured.\nlazy_load() \u2192 Iterator[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.excel.UnstructuredExcelLoader.html"}
{"id": "f9b28469aa6d-1", "text": "lazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredExcelLoader\u00b6\nMicrosoft Excel", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.excel.UnstructuredExcelLoader.html"}
{"id": "537b3ff355bc-0", "text": "langchain.document_loaders.generic.GenericLoader\u00b6\nclass langchain.document_loaders.generic.GenericLoader(blob_loader: BlobLoader, blob_parser: BaseBlobParser)[source]\u00b6\nGeneric Document Loader.\nA generic document loader that allows combining an arbitrary blob loader with\na blob parser.\nExamples\nfrom langchain.document_loaders import GenericLoader\nfrom langchain.document_loaders.blob_loaders import FileSystemBlobLoader\nloader = GenericLoader.from_filesystem(\n    path=\"path/to/directory\",\n    glob=\"**/[!.]*\",\n    suffixes=[\".pdf\"],\n    show_progress=True,\n)\ndocs = loader.lazy_load()\nnext(docs)\nExample instantiations to change which files are loaded:\n.. code-block:: python\n    # Recursively load all text files in a directory.\n    loader = GenericLoader.from_filesystem(\"/path/to/dir\", glob=\"**/*.txt\")\n    # Recursively load all non-hidden files in a directory.\n    loader = GenericLoader.from_filesystem(\"/path/to/dir\", glob=\"**/[!.]*\")\n    # Load all files in a directory without recursion.\n    loader = GenericLoader.from_filesystem(\"/path/to/dir\", glob=\"*\")\nExample instantiations to change which parser is used:\n.. code-block:: python\n    from langchain.document_loaders.parsers.pdf import PyPDFParser\n    # Recursively load all text files in a directory.\n    loader = GenericLoader.from_filesystem(\n        \"/path/to/dir\",\n        glob=\"**/*.pdf\",\n        parser=PyPDFParser()\n    )\nA generic document loader.\nParameters\nblob_loader \u2013 A blob loader which knows how to yield blobs\nblob_parser \u2013 A blob parser which knows how to parse blobs into documents\nMethods\n__init__(blob_loader,\u00a0blob_parser)\nA generic document loader.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.generic.GenericLoader.html"}
{"id": "537b3ff355bc-1", "text": "Methods\n__init__(blob_loader,\u00a0blob_parser)\nA generic document loader.\nfrom_filesystem(path,\u00a0*[,\u00a0glob,\u00a0exclude,\u00a0...])\nCreate a generic document loader using a filesystem blob loader.\nlazy_load()\nLoad documents lazily.\nload()\nLoad all documents.\nload_and_split([text_splitter])\nLoad all documents and split them into sentences.\n__init__(blob_loader: BlobLoader, blob_parser: BaseBlobParser) \u2192 None[source]\u00b6\nA generic document loader.\nParameters\nblob_loader \u2013 A blob loader which knows how to yield blobs\nblob_parser \u2013 A blob parser which knows how to parse blobs into documents\nclassmethod from_filesystem(path: Union[str, Path], *, glob: str = '**/[!.]*', exclude: Sequence[str] = (), suffixes: Optional[Sequence[str]] = None, show_progress: bool = False, parser: Union[Literal['default'], BaseBlobParser] = 'default') \u2192 GenericLoader[source]\u00b6\nCreate a generic document loader using a filesystem blob loader.\nParameters\npath \u2013 The path to the directory to load documents from.\nglob \u2013 The glob pattern to use to find documents.\nsuffixes \u2013 The suffixes to use to filter documents. If None, all files\nmatching the glob will be loaded.\nexclude \u2013 A list of patterns to exclude from the loader.\nshow_progress \u2013 Whether to show a progress bar or not (requires tqdm).\nProxies to the file system loader.\nparser \u2013 A blob parser which knows how to parse blobs into documents\nReturns\nA generic document loader.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLoad documents lazily. Use this when working at a large scale.\nload() \u2192 List[Document][source]\u00b6\nLoad all documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.generic.GenericLoader.html"}
{"id": "537b3ff355bc-2", "text": "load() \u2192 List[Document][source]\u00b6\nLoad all documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document][source]\u00b6\nLoad all documents and split them into sentences.\nExamples using GenericLoader\u00b6\nGrobid\nLoading documents from a YouTube url\nSource Code\nSet env var OPENAI_API_KEY or load from a .env file", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.generic.GenericLoader.html"}
{"id": "b8ed7ecde909-0", "text": "langchain.document_loaders.open_city_data.OpenCityDataLoader\u00b6\nclass langchain.document_loaders.open_city_data.OpenCityDataLoader(city_id: str, dataset_id: str, limit: int)[source]\u00b6\nLoad from Open City.\nInitialize with dataset_id.\nExample: https://dev.socrata.com/foundry/data.sfgov.org/vw6y-z8j6\ne.g., city_id = data.sfgov.org\ne.g., dataset_id = vw6y-z8j6\nParameters\ncity_id \u2013 The Open City city identifier.\ndataset_id \u2013 The Open City dataset identifier.\nlimit \u2013 The maximum number of documents to load.\nMethods\n__init__(city_id,\u00a0dataset_id,\u00a0limit)\nInitialize with dataset_id.\nlazy_load()\nLazy load records.\nload()\nLoad records.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(city_id: str, dataset_id: str, limit: int)[source]\u00b6\nInitialize with dataset_id.\nExample: https://dev.socrata.com/foundry/data.sfgov.org/vw6y-z8j6\ne.g., city_id = data.sfgov.org\ne.g., dataset_id = vw6y-z8j6\nParameters\ncity_id \u2013 The Open City city identifier.\ndataset_id \u2013 The Open City dataset identifier.\nlimit \u2013 The maximum number of documents to load.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load records.\nload() \u2192 List[Document][source]\u00b6\nLoad records.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.open_city_data.OpenCityDataLoader.html"}
{"id": "b8ed7ecde909-1", "text": "Parameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using OpenCityDataLoader\u00b6\nGeopandas\nOpen City Data", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.open_city_data.OpenCityDataLoader.html"}
{"id": "fb9a19f7adf5-0", "text": "langchain.document_loaders.odt.UnstructuredODTLoader\u00b6\nclass langchain.document_loaders.odt.UnstructuredODTLoader(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad OpenOffice ODT files using Unstructured.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredODTLoader\nloader = UnstructuredODTLoader(\u201cexample.odt\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition-odt\nParameters\nfile_path \u2013 The path to the file to load.\nmode \u2013 The mode to use when loading the file. Can be one of \u201csingle\u201d,\n\u201cmulti\u201d, or \u201call\u201d. Default is \u201csingle\u201d.\n**unstructured_kwargs \u2013 Any kwargs to pass to the unstructured.\nMethods\n__init__(file_path[,\u00a0mode])\nparam file_path\nThe path to the file to load.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nParameters\nfile_path \u2013 The path to the file to load.\nmode \u2013 The mode to use when loading the file. Can be one of \u201csingle\u201d,", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.odt.UnstructuredODTLoader.html"}
{"id": "fb9a19f7adf5-1", "text": "mode \u2013 The mode to use when loading the file. Can be one of \u201csingle\u201d,\n\u201cmulti\u201d, or \u201call\u201d. Default is \u201csingle\u201d.\n**unstructured_kwargs \u2013 Any kwargs to pass to the unstructured.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredODTLoader\u00b6\nOpen Document Format (ODT)", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.odt.UnstructuredODTLoader.html"}
{"id": "4ffac6999228-0", "text": "langchain.document_loaders.email.UnstructuredEmailLoader\u00b6\nclass langchain.document_loaders.email.UnstructuredEmailLoader(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad email files using Unstructured.\nWorks with both\n.eml and .msg files. You can process attachments in addition to the\ne-mail message itself by passing process_attachments=True into the\nconstructor for the loader. By default, attachments will be processed\nwith the unstructured partition function. If you already know the document\ntypes of the attachments, you can specify another partitioning function\nwith the attachment partitioner kwarg.\nExample\nfrom langchain.document_loaders import UnstructuredEmailLoader\nloader = UnstructuredEmailLoader(\u201cexample_data/fake-email.eml\u201d, mode=\u201delements\u201d)\nloader.load()\nExample\nfrom langchain.document_loaders import UnstructuredEmailLoader\nloader = UnstructuredEmailLoader(\u201cexample_data/fake-email-attachment.eml\u201d,\nmode=\u201delements\u201d,\nprocess_attachments=True,\n)\nloader.load()\nInitialize with file path.\nMethods\n__init__(file_path[,\u00a0mode])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.email.UnstructuredEmailLoader.html"}
{"id": "4ffac6999228-1", "text": "Parameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredEmailLoader\u00b6\nEmail", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.email.UnstructuredEmailLoader.html"}
{"id": "20516a7d830a-0", "text": "langchain.document_loaders.blob_loaders.youtube_audio.YoutubeAudioLoader\u00b6\nclass langchain.document_loaders.blob_loaders.youtube_audio.YoutubeAudioLoader(urls: List[str], save_dir: str)[source]\u00b6\nLoad YouTube urls as audio file(s).\nMethods\n__init__(urls,\u00a0save_dir)\nyield_blobs()\nYield audio blobs for each url.\n__init__(urls: List[str], save_dir: str)[source]\u00b6\nyield_blobs() \u2192 Iterable[Blob][source]\u00b6\nYield audio blobs for each url.\nExamples using YoutubeAudioLoader\u00b6\nLoading documents from a YouTube url", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blob_loaders.youtube_audio.YoutubeAudioLoader.html"}
{"id": "e8a930593347-0", "text": "langchain.document_loaders.parsers.msword.MsWordParser\u00b6\nclass langchain.document_loaders.parsers.msword.MsWordParser[source]\u00b6\nParse the Microsoft Word documents from a blob.\nMethods\n__init__()\nlazy_parse(blob)\nParse a Microsoft Word document into the Document iterator.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__()\u00b6\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nParse a Microsoft Word document into the Document iterator.\nParameters\nblob \u2013 The blob to parse.\nReturns: An iterator of Documents.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.msword.MsWordParser.html"}
{"id": "82ef8acf6f4a-0", "text": "langchain.document_loaders.parsers.grobid.ServerUnavailableException\u00b6\nclass langchain.document_loaders.parsers.grobid.ServerUnavailableException[source]\u00b6\nException raised when the Grobid server is unavailable.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.grobid.ServerUnavailableException.html"}
{"id": "6682fb9e72c3-0", "text": "langchain.document_loaders.unstructured.UnstructuredAPIFileLoader\u00b6\nclass langchain.document_loaders.unstructured.UnstructuredAPIFileLoader(file_path: Union[str, List[str]] = '', mode: str = 'single', url: str = 'https://api.unstructured.io/general/v0/general', api_key: str = '', **unstructured_kwargs: Any)[source]\u00b6\nLoad files using Unstructured API.\nBy default, the loader makes a call to the hosted Unstructured API.\nIf you are running the unstructured API locally, you can change the\nAPI rule by passing in the url parameter when you initialize the loader.\nThe hosted Unstructured API requires an API key. See\nhttps://www.unstructured.io/api-key/ if you need to generate a key.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\n```python\nfrom langchain.document_loaders import UnstructuredAPIFileLoader\nloader = UnstructuredFileAPILoader(\u201cexample.pdf\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d, api_key=\u201dMY_API_KEY\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition\nhttps://www.unstructured.io/api-key/\nhttps://github.com/Unstructured-IO/unstructured-api\nInitialize with file path.\nMethods\n__init__([file_path,\u00a0mode,\u00a0url,\u00a0api_key])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.unstructured.UnstructuredAPIFileLoader.html"}
{"id": "6682fb9e72c3-1", "text": "lazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: Union[str, List[str]] = '', mode: str = 'single', url: str = 'https://api.unstructured.io/general/v0/general', api_key: str = '', **unstructured_kwargs: Any)[source]\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredAPIFileLoader\u00b6\nUnstructured File", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.unstructured.UnstructuredAPIFileLoader.html"}
{"id": "4de57da1f1fd-0", "text": "langchain.document_loaders.confluence.ContentFormat\u00b6\nclass langchain.document_loaders.confluence.ContentFormat(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnumerator of the content formats of Confluence page.\nEDITOR = 'body.editor'\u00b6\nEXPORT_VIEW = 'body.export_view'\u00b6\nANONYMOUS_EXPORT_VIEW = 'body.anonymous_export_view'\u00b6\nSTORAGE = 'body.storage'\u00b6\nVIEW = 'body.view'\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.confluence.ContentFormat.html"}
{"id": "978736c4c28a-0", "text": "langchain.document_loaders.blob_loaders.schema.BlobLoader\u00b6\nclass langchain.document_loaders.blob_loaders.schema.BlobLoader[source]\u00b6\nAbstract interface for blob loaders implementation.\nImplementer should be able to load raw content from a storage system according\nto some criteria and return the raw content lazily as a stream of blobs.\nMethods\n__init__()\nyield_blobs()\nA lazy loader for raw data represented by LangChain's Blob object.\n__init__()\u00b6\nabstract yield_blobs() \u2192 Iterable[Blob][source]\u00b6\nA lazy loader for raw data represented by LangChain\u2019s Blob object.\nReturns\nA generator over blobs", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blob_loaders.schema.BlobLoader.html"}
{"id": "1a5cc3da224d-0", "text": "langchain.document_loaders.lakefs.LakeFSLoader\u00b6\nclass langchain.document_loaders.lakefs.LakeFSLoader(lakefs_access_key: str, lakefs_secret_key: str, lakefs_endpoint: str, repo: Optional[str] = None, ref: Optional[str] = 'main', path: Optional[str] = '')[source]\u00b6\nLoad from lakeFS.\nParameters\nlakefs_access_key \u2013 [required] lakeFS server\u2019s access key\nlakefs_secret_key \u2013 [required] lakeFS server\u2019s secret key\nlakefs_endpoint \u2013 [required] lakeFS server\u2019s endpoint address,\nex: https://example.my-lakefs.com\nrepo \u2013 [optional, default = \u2018\u2019] target repository\nref \u2013 [optional, default = \u2018main\u2019] target ref (branch name,\ntag, or commit ID)\npath \u2013 [optional, default = \u2018\u2019] target path\nAttributes\nrepo\nref\npath\nMethods\n__init__(lakefs_access_key,\u00a0...[,\u00a0repo,\u00a0...])\nparam lakefs_access_key\n[required] lakeFS server's access key\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nset_path(path)\nset_ref(ref)\nset_repo(repo)\n__init__(lakefs_access_key: str, lakefs_secret_key: str, lakefs_endpoint: str, repo: Optional[str] = None, ref: Optional[str] = 'main', path: Optional[str] = '')[source]\u00b6\nParameters\nlakefs_access_key \u2013 [required] lakeFS server\u2019s access key\nlakefs_secret_key \u2013 [required] lakeFS server\u2019s secret key\nlakefs_endpoint \u2013 [required] lakeFS server\u2019s endpoint address,\nex: https://example.my-lakefs.com", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.lakefs.LakeFSLoader.html"}
{"id": "1a5cc3da224d-1", "text": "ex: https://example.my-lakefs.com\nrepo \u2013 [optional, default = \u2018\u2019] target repository\nref \u2013 [optional, default = \u2018main\u2019] target ref (branch name,\ntag, or commit ID)\npath \u2013 [optional, default = \u2018\u2019] target path\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nset_path(path: str) \u2192 None[source]\u00b6\nset_ref(ref: str) \u2192 None[source]\u00b6\nset_repo(repo: str) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.lakefs.LakeFSLoader.html"}
{"id": "d03783d5033e-0", "text": "langchain.document_loaders.org_mode.UnstructuredOrgModeLoader\u00b6\nclass langchain.document_loaders.org_mode.UnstructuredOrgModeLoader(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad Org-Mode files using Unstructured.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredOrgModeLoader\nloader = UnstructuredOrgModeLoader(\u201cexample.org\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition-org\nParameters\nfile_path \u2013 The path to the file to load.\nmode \u2013 The mode to load the file from. Default is \u201csingle\u201d.\n**unstructured_kwargs \u2013 Any additional keyword arguments to pass\nto the unstructured.\nMethods\n__init__(file_path[,\u00a0mode])\nparam file_path\nThe path to the file to load.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nParameters\nfile_path \u2013 The path to the file to load.\nmode \u2013 The mode to load the file from. Default is \u201csingle\u201d.\n**unstructured_kwargs \u2013 Any additional keyword arguments to pass\nto the unstructured.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.org_mode.UnstructuredOrgModeLoader.html"}
{"id": "d03783d5033e-1", "text": "**unstructured_kwargs \u2013 Any additional keyword arguments to pass\nto the unstructured.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredOrgModeLoader\u00b6\nOrg-mode", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.org_mode.UnstructuredOrgModeLoader.html"}
{"id": "e45808f475f4-0", "text": "langchain.document_loaders.nuclia.NucliaLoader\u00b6\nclass langchain.document_loaders.nuclia.NucliaLoader(path: str, nuclia_tool: NucliaUnderstandingAPI)[source]\u00b6\nLoad from any file type using Nuclia Understanding API.\nMethods\n__init__(path,\u00a0nuclia_tool)\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(path: str, nuclia_tool: NucliaUnderstandingAPI)[source]\u00b6\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using NucliaLoader\u00b6\nNuclia Understanding API document loader", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.nuclia.NucliaLoader.html"}
{"id": "398d8008766a-0", "text": "langchain.document_loaders.parsers.pdf.DocumentIntelligenceParser\u00b6\nclass langchain.document_loaders.parsers.pdf.DocumentIntelligenceParser(client: Any, model: str)[source]\u00b6\nLoads a PDF with Azure Document Intelligence\n(formerly Forms Recognizer) and chunks at character level.\nMethods\n__init__(client,\u00a0model)\nlazy_parse(blob)\nLazily parse the blob.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__(client: Any, model: str)[source]\u00b6\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLazily parse the blob.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.pdf.DocumentIntelligenceParser.html"}
{"id": "c68d15f1c425-0", "text": "langchain.document_loaders.trello.TrelloLoader\u00b6\nclass langchain.document_loaders.trello.TrelloLoader(client: TrelloClient, board_name: str, *, include_card_name: bool = True, include_comments: bool = True, include_checklist: bool = True, card_filter: Literal['closed', 'open', 'all'] = 'all', extra_metadata: Tuple[str, ...] = ('due_date', 'labels', 'list', 'closed'))[source]\u00b6\nLoad cards from a Trello board.\nInitialize Trello loader.\nParameters\nclient \u2013 Trello API client.\nboard_name \u2013 The name of the Trello board.\ninclude_card_name \u2013 Whether to include the name of the card in the document.\ninclude_comments \u2013 Whether to include the comments on the card in the\ndocument.\ninclude_checklist \u2013 Whether to include the checklist on the card in the\ndocument.\ncard_filter \u2013 Filter on card status. Valid values are \u201cclosed\u201d, \u201copen\u201d,\n\u201call\u201d.\nextra_metadata \u2013 List of additional metadata fields to include as document\nmetadata.Valid values are \u201cdue_date\u201d, \u201clabels\u201d, \u201clist\u201d, \u201cclosed\u201d.\nMethods\n__init__(client,\u00a0board_name,\u00a0*[,\u00a0...])\nInitialize Trello loader.\nfrom_credentials(board_name,\u00a0*[,\u00a0api_key,\u00a0token])\nConvenience constructor that builds TrelloClient init param for you.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoads all cards from the specified Trello board.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.trello.TrelloLoader.html"}
{"id": "c68d15f1c425-1", "text": "load_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(client: TrelloClient, board_name: str, *, include_card_name: bool = True, include_comments: bool = True, include_checklist: bool = True, card_filter: Literal['closed', 'open', 'all'] = 'all', extra_metadata: Tuple[str, ...] = ('due_date', 'labels', 'list', 'closed'))[source]\u00b6\nInitialize Trello loader.\nParameters\nclient \u2013 Trello API client.\nboard_name \u2013 The name of the Trello board.\ninclude_card_name \u2013 Whether to include the name of the card in the document.\ninclude_comments \u2013 Whether to include the comments on the card in the\ndocument.\ninclude_checklist \u2013 Whether to include the checklist on the card in the\ndocument.\ncard_filter \u2013 Filter on card status. Valid values are \u201cclosed\u201d, \u201copen\u201d,\n\u201call\u201d.\nextra_metadata \u2013 List of additional metadata fields to include as document\nmetadata.Valid values are \u201cdue_date\u201d, \u201clabels\u201d, \u201clist\u201d, \u201cclosed\u201d.\nclassmethod from_credentials(board_name: str, *, api_key: Optional[str] = None, token: Optional[str] = None, **kwargs: Any) \u2192 TrelloLoader[source]\u00b6\nConvenience constructor that builds TrelloClient init param for you.\nParameters\nboard_name \u2013 The name of the Trello board.\napi_key \u2013 Trello API key. Can also be specified as environment variable\nTRELLO_API_KEY.\ntoken \u2013 Trello token. Can also be specified as environment variable\nTRELLO_TOKEN.\ninclude_card_name \u2013 Whether to include the name of the card in the document.\ninclude_comments \u2013 Whether to include the comments on the card in the\ndocument.\ninclude_checklist \u2013 Whether to include the checklist on the card in the\ndocument.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.trello.TrelloLoader.html"}
{"id": "c68d15f1c425-2", "text": "include_checklist \u2013 Whether to include the checklist on the card in the\ndocument.\ncard_filter \u2013 Filter on card status. Valid values are \u201cclosed\u201d, \u201copen\u201d,\n\u201call\u201d.\nextra_metadata \u2013 List of additional metadata fields to include as document\nmetadata.Valid values are \u201cdue_date\u201d, \u201clabels\u201d, \u201clist\u201d, \u201cclosed\u201d.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoads all cards from the specified Trello board.\nYou can filter the cards, metadata and text included by using the optional\nparameters.\nReturns:A list of documents, one for each card in the board.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using TrelloLoader\u00b6\nTrello", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.trello.TrelloLoader.html"}
{"id": "bbac3595f3b8-0", "text": "langchain.document_loaders.baiducloud_bos_directory.BaiduBOSDirectoryLoader\u00b6\nclass langchain.document_loaders.baiducloud_bos_directory.BaiduBOSDirectoryLoader(conf: Any, bucket: str, prefix: str = '')[source]\u00b6\nLoad from Baidu BOS directory.\nInitialize with BOS config, bucket and prefix.\n:param conf(BosConfig): BOS config.\n:param bucket(str): BOS bucket.\n:param prefix(str): prefix.\nMethods\n__init__(conf,\u00a0bucket[,\u00a0prefix])\nInitialize with BOS config, bucket and prefix.\nlazy_load()\nLoad documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(conf: Any, bucket: str, prefix: str = '')[source]\u00b6\nInitialize with BOS config, bucket and prefix.\n:param conf(BosConfig): BOS config.\n:param bucket(str): BOS bucket.\n:param prefix(str): prefix.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLoad documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.baiducloud_bos_directory.BaiduBOSDirectoryLoader.html"}
{"id": "6bc17c814772-0", "text": "langchain.document_loaders.pdf.PyPDFLoader\u00b6\nclass langchain.document_loaders.pdf.PyPDFLoader(file_path: str, password: Optional[Union[str, bytes]] = None, headers: Optional[Dict] = None, extract_images: bool = False)[source]\u00b6\nLoad PDF using pypdf into list of documents.\nLoader chunks by page and stores page numbers in metadata.\nInitialize with a file path.\nAttributes\nsource\nMethods\n__init__(file_path[,\u00a0password,\u00a0headers,\u00a0...])\nInitialize with a file path.\nlazy_load()\nLazy load given path as pages.\nload()\nLoad given path as pages.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, password: Optional[Union[str, bytes]] = None, headers: Optional[Dict] = None, extract_images: bool = False) \u2192 None[source]\u00b6\nInitialize with a file path.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load given path as pages.\nload() \u2192 List[Document][source]\u00b6\nLoad given path as pages.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using PyPDFLoader\u00b6\nDocument Comparison\nGoogle Cloud Storage File\nMergeDocLoader\nQA using Activeloop\u2019s DeepLake", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.PyPDFLoader.html"}
{"id": "c4a0218e8f88-0", "text": "langchain.document_loaders.lakefs.LakeFSClient\u00b6\nclass langchain.document_loaders.lakefs.LakeFSClient(lakefs_access_key: str, lakefs_secret_key: str, lakefs_endpoint: str)[source]\u00b6\nMethods\n__init__(lakefs_access_key,\u00a0...)\nis_presign_supported()\nls_objects(repo,\u00a0ref,\u00a0path,\u00a0presign)\n__init__(lakefs_access_key: str, lakefs_secret_key: str, lakefs_endpoint: str)[source]\u00b6\nis_presign_supported() \u2192 bool[source]\u00b6\nls_objects(repo: str, ref: str, path: str, presign: Optional[bool]) \u2192 List[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.lakefs.LakeFSClient.html"}
{"id": "c70e53fe6d03-0", "text": "langchain.document_loaders.rocksetdb.default_joiner\u00b6\nlangchain.document_loaders.rocksetdb.default_joiner(docs: List[Tuple[str, Any]]) \u2192 str[source]\u00b6\nDefault joiner for content columns.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.rocksetdb.default_joiner.html"}
{"id": "84700a3c0601-0", "text": "langchain.document_loaders.url_playwright.PlaywrightURLLoader\u00b6\nclass langchain.document_loaders.url_playwright.PlaywrightURLLoader(urls: List[str], continue_on_failure: bool = True, headless: bool = True, remove_selectors: Optional[List[str]] = None, evaluator: Optional[PlaywrightEvaluator] = None)[source]\u00b6\nLoad HTML pages with Playwright and parse with Unstructured.\nThis is useful for loading pages that require javascript to render.\nurls\u00b6\nList of URLs to load.\nType\nList[str]\ncontinue_on_failure\u00b6\nIf True, continue loading other URLs on failure.\nType\nbool\nheadless\u00b6\nIf True, the browser will run in headless mode.\nType\nbool\nLoad a list of URLs using Playwright.\nMethods\n__init__(urls[,\u00a0continue_on_failure,\u00a0...])\nLoad a list of URLs using Playwright.\naload()\nLoad the specified URLs with Playwright and create Documents asynchronously.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad the specified URLs using Playwright and create Document instances.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(urls: List[str], continue_on_failure: bool = True, headless: bool = True, remove_selectors: Optional[List[str]] = None, evaluator: Optional[PlaywrightEvaluator] = None)[source]\u00b6\nLoad a list of URLs using Playwright.\nasync aload() \u2192 List[Document][source]\u00b6\nLoad the specified URLs with Playwright and create Documents asynchronously.\nUse this function when in a jupyter notebook environment.\nReturns\nA list of Document instances with loaded content.\nReturn type\nList[Document]\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.url_playwright.PlaywrightURLLoader.html"}
{"id": "84700a3c0601-1", "text": "A lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad the specified URLs using Playwright and create Document instances.\nReturns\nA list of Document instances with loaded content.\nReturn type\nList[Document]\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using PlaywrightURLLoader\u00b6\nURL", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.url_playwright.PlaywrightURLLoader.html"}
{"id": "9210376a294f-0", "text": "langchain.document_loaders.sitemap.SitemapLoader\u00b6\nclass langchain.document_loaders.sitemap.SitemapLoader(web_path: str, filter_urls: Optional[List[str]] = None, parsing_function: Optional[Callable] = None, blocksize: Optional[int] = None, blocknum: int = 0, meta_function: Optional[Callable] = None, is_local: bool = False, continue_on_failure: bool = False, restrict_to_same_domain: bool = True, **kwargs: Any)[source]\u00b6\nLoad a sitemap and its URLs.\nSecurity Note: This loader can be used to load all URLs specified in a sitemap.If a malicious actor gets access to the sitemap, they could force\nthe server to load URLs from other domains by modifying the sitemap.\nThis could lead to server-side request forgery (SSRF) attacks; e.g.,\nwith the attacker forcing the server to load URLs from internal\nservice endpoints that are not publicly accessible. While the attacker\nmay not immediately gain access to this data, this data could leak\ninto downstream systems (e.g., data loader is used to load data for indexing).\nThis loader is a crawler and web crawlers should generally NOT be deployed\nwith network access to any internal servers.\nControl access to who can submit crawling requests and what network access\nthe crawler has.\nBy default, the loader will only load URLs from the same domain as the sitemap\nif the site map is not a local file. This can be disabled by setting\nrestrict_to_same_domain to False (not recommended).\nIf the site map is a local file, no such risk mitigation is applied by default.\nUse the filter URLs argument to limit which URLs can be loaded.\nSee https://python.langchain.com/docs/security\nInitialize with webpage path and optional filter URLs.\nParameters\nweb_path \u2013 url of the sitemap. can also be a local path", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.sitemap.SitemapLoader.html"}
{"id": "9210376a294f-1", "text": "Parameters\nweb_path \u2013 url of the sitemap. can also be a local path\nfilter_urls \u2013 a list of regexes. If specified, only\nURLS that match one of the filter URLs will be loaded.\nWARNING The filter URLs are interpreted as regular expressions.\nRemember to escape special characters if you do not want them to be\ninterpreted as regular expression syntax. For example, . appears\nfrequently in URLs and should be escaped if you want to match a literal\n. rather than any character.\nrestrict_to_same_domain takes precedence over filter_urls when\nrestrict_to_same_domain is True and the sitemap is not a local file.\nparsing_function \u2013 Function to parse bs4.Soup output\nblocksize \u2013 number of sitemap locations per block\nblocknum \u2013 the number of the block that should be loaded - zero indexed.\nDefault: 0\nmeta_function \u2013 Function to parse bs4.Soup output for metadata\nremember when setting this method to also copy metadata[\u201cloc\u201d]\nto metadata[\u201csource\u201d] if you are using this field\nis_local \u2013 whether the sitemap is a local file. Default: False\ncontinue_on_failure \u2013 whether to continue loading the sitemap if an error\noccurs loading a url, emitting a warning instead of raising an\nexception. Setting this to True makes the loader more robust, but also\nmay result in missing data. Default: False\nrestrict_to_same_domain \u2013 whether to restrict loading to URLs to the same\ndomain as the sitemap. Attention: This is only applied if the sitemap\nis not a local file!\nAttributes\nweb_path\nMethods\n__init__(web_path[,\u00a0filter_urls,\u00a0...])\nInitialize with webpage path and optional filter URLs.\naload()\nLoad text from the urls in web_path async into Documents.\nfetch_all(urls)\nFetch all urls concurrently with rate limiting.\nlazy_load()", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.sitemap.SitemapLoader.html"}
{"id": "9210376a294f-2", "text": "fetch_all(urls)\nFetch all urls concurrently with rate limiting.\nlazy_load()\nLazy load text from the url(s) in web_path.\nload()\nLoad sitemap.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nparse_sitemap(soup)\nParse sitemap xml and load into a list of dicts.\nscrape([parser])\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls[,\u00a0parser])\nFetch all urls, then return soups for all results.\n__init__(web_path: str, filter_urls: Optional[List[str]] = None, parsing_function: Optional[Callable] = None, blocksize: Optional[int] = None, blocknum: int = 0, meta_function: Optional[Callable] = None, is_local: bool = False, continue_on_failure: bool = False, restrict_to_same_domain: bool = True, **kwargs: Any)[source]\u00b6\nInitialize with webpage path and optional filter URLs.\nParameters\nweb_path \u2013 url of the sitemap. can also be a local path\nfilter_urls \u2013 a list of regexes. If specified, only\nURLS that match one of the filter URLs will be loaded.\nWARNING The filter URLs are interpreted as regular expressions.\nRemember to escape special characters if you do not want them to be\ninterpreted as regular expression syntax. For example, . appears\nfrequently in URLs and should be escaped if you want to match a literal\n. rather than any character.\nrestrict_to_same_domain takes precedence over filter_urls when\nrestrict_to_same_domain is True and the sitemap is not a local file.\nparsing_function \u2013 Function to parse bs4.Soup output\nblocksize \u2013 number of sitemap locations per block\nblocknum \u2013 the number of the block that should be loaded - zero indexed.\nDefault: 0", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.sitemap.SitemapLoader.html"}
{"id": "9210376a294f-3", "text": "Default: 0\nmeta_function \u2013 Function to parse bs4.Soup output for metadata\nremember when setting this method to also copy metadata[\u201cloc\u201d]\nto metadata[\u201csource\u201d] if you are using this field\nis_local \u2013 whether the sitemap is a local file. Default: False\ncontinue_on_failure \u2013 whether to continue loading the sitemap if an error\noccurs loading a url, emitting a warning instead of raising an\nexception. Setting this to True makes the loader more robust, but also\nmay result in missing data. Default: False\nrestrict_to_same_domain \u2013 whether to restrict loading to URLs to the same\ndomain as the sitemap. Attention: This is only applied if the sitemap\nis not a local file!\naload() \u2192 List[Document]\u00b6\nLoad text from the urls in web_path async into Documents.\nasync fetch_all(urls: List[str]) \u2192 Any\u00b6\nFetch all urls concurrently with rate limiting.\nlazy_load() \u2192 Iterator[Document]\u00b6\nLazy load text from the url(s) in web_path.\nload() \u2192 List[Document][source]\u00b6\nLoad sitemap.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nparse_sitemap(soup: Any) \u2192 List[dict][source]\u00b6\nParse sitemap xml and load into a list of dicts.\nParameters\nsoup \u2013 BeautifulSoup object.\nReturns\nList of dicts.\nscrape(parser: Optional[str] = None) \u2192 Any\u00b6\nScrape data from webpage and return it in BeautifulSoup format.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.sitemap.SitemapLoader.html"}
{"id": "9210376a294f-4", "text": "Scrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls: List[str], parser: Optional[str] = None) \u2192 List[Any]\u00b6\nFetch all urls, then return soups for all results.\nExamples using SitemapLoader\u00b6\nSitemap", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.sitemap.SitemapLoader.html"}
{"id": "c4371f3752c0-0", "text": "langchain.document_loaders.arxiv.ArxivLoader\u00b6\nclass langchain.document_loaders.arxiv.ArxivLoader(query: str, doc_content_chars_max: Optional[int] = None, **kwargs: Any)[source]\u00b6\nLoad a query result from Arxiv.\nThe loader converts the original PDF format into the text.\nParameters\nArxivAPIWrapper. (Supports all arguments of) \u2013 \nMethods\n__init__(query[,\u00a0doc_content_chars_max])\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(query: str, doc_content_chars_max: Optional[int] = None, **kwargs: Any)[source]\u00b6\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using ArxivLoader\u00b6\nArxiv", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.arxiv.ArxivLoader.html"}
{"id": "355fb050c162-0", "text": "langchain.document_loaders.max_compute.MaxComputeLoader\u00b6\nclass langchain.document_loaders.max_compute.MaxComputeLoader(query: str, api_wrapper: MaxComputeAPIWrapper, *, page_content_columns: Optional[Sequence[str]] = None, metadata_columns: Optional[Sequence[str]] = None)[source]\u00b6\nLoad from Alibaba Cloud MaxCompute table.\nInitialize Alibaba Cloud MaxCompute document loader.\nParameters\nquery \u2013 SQL query to execute.\napi_wrapper \u2013 MaxCompute API wrapper.\npage_content_columns \u2013 The columns to write into the page_content of the\nDocument. If unspecified, all columns will be written to page_content.\nmetadata_columns \u2013 The columns to write into the metadata of the Document.\nIf unspecified, all columns not added to page_content will be written.\nMethods\n__init__(query,\u00a0api_wrapper,\u00a0*[,\u00a0...])\nInitialize Alibaba Cloud MaxCompute document loader.\nfrom_params(query,\u00a0endpoint,\u00a0project,\u00a0*[,\u00a0...])\nConvenience constructor that builds the MaxCompute API wrapper from\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(query: str, api_wrapper: MaxComputeAPIWrapper, *, page_content_columns: Optional[Sequence[str]] = None, metadata_columns: Optional[Sequence[str]] = None)[source]\u00b6\nInitialize Alibaba Cloud MaxCompute document loader.\nParameters\nquery \u2013 SQL query to execute.\napi_wrapper \u2013 MaxCompute API wrapper.\npage_content_columns \u2013 The columns to write into the page_content of the\nDocument. If unspecified, all columns will be written to page_content.\nmetadata_columns \u2013 The columns to write into the metadata of the Document.\nIf unspecified, all columns not added to page_content will be written.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.max_compute.MaxComputeLoader.html"}
{"id": "355fb050c162-1", "text": "If unspecified, all columns not added to page_content will be written.\nclassmethod from_params(query: str, endpoint: str, project: str, *, access_id: Optional[str] = None, secret_access_key: Optional[str] = None, **kwargs: Any) \u2192 MaxComputeLoader[source]\u00b6\nConvenience constructor that builds the MaxCompute API wrapper fromgiven parameters.\nParameters\nquery \u2013 SQL query to execute.\nendpoint \u2013 MaxCompute endpoint.\nproject \u2013 A project is a basic organizational unit of MaxCompute, which is\nsimilar to a database.\naccess_id \u2013 MaxCompute access ID. Should be passed in directly or set as the\nenvironment variable MAX_COMPUTE_ACCESS_ID.\nsecret_access_key \u2013 MaxCompute secret access key. Should be passed in\ndirectly or set as the environment variable\nMAX_COMPUTE_SECRET_ACCESS_KEY.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using MaxComputeLoader\u00b6\nAlibaba Cloud MaxCompute", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.max_compute.MaxComputeLoader.html"}
{"id": "2d0af6208a3c-0", "text": "langchain.document_loaders.pdf.PDFPlumberLoader\u00b6\nclass langchain.document_loaders.pdf.PDFPlumberLoader(file_path: str, text_kwargs: Optional[Mapping[str, Any]] = None, dedupe: bool = False, headers: Optional[Dict] = None, extract_images: bool = False)[source]\u00b6\nLoad PDF files using pdfplumber.\nInitialize with a file path.\nAttributes\nsource\nMethods\n__init__(file_path[,\u00a0text_kwargs,\u00a0dedupe,\u00a0...])\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, text_kwargs: Optional[Mapping[str, Any]] = None, dedupe: bool = False, headers: Optional[Dict] = None, extract_images: bool = False) \u2192 None[source]\u00b6\nInitialize with a file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pdf.PDFPlumberLoader.html"}
{"id": "8f7856ba9128-0", "text": "langchain.document_loaders.unstructured.get_elements_from_api\u00b6\nlangchain.document_loaders.unstructured.get_elements_from_api(file_path: Optional[Union[str, List[str]]] = None, file: Optional[Union[IO, Sequence[IO]]] = None, api_url: str = 'https://api.unstructured.io/general/v0/general', api_key: str = '', **unstructured_kwargs: Any) \u2192 List[source]\u00b6\nRetrieve a list of elements from the Unstructured API.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.unstructured.get_elements_from_api.html"}
{"id": "d863f96b6c8a-0", "text": "langchain.document_loaders.parsers.audio.YandexSTTParser\u00b6\nclass langchain.document_loaders.parsers.audio.YandexSTTParser(*, api_key: Optional[str] = None, iam_token: Optional[str] = None, model: str = 'general', language: str = 'auto')[source]\u00b6\nTranscribe and parse audio files.\nAudio transcription is with OpenAI Whisper model.\nInitialize the parser.\nParameters\napi_key \u2013 API key for a service account\nrole. (with the ai.speechkit-stt.user) \u2013 \niam_token \u2013 IAM token for a service account\nrole. \u2013 \nmodel \u2013 Recognition model name.\nDefaults to general.\nlanguage \u2013 The language in ISO 639-1 format.\nDefaults to automatic language recognition.\nEither api_key or iam_token must be provided, but not both.\nMethods\n__init__(*[,\u00a0api_key,\u00a0iam_token,\u00a0model,\u00a0...])\nInitialize the parser.\nlazy_parse(blob)\nLazily parse the blob.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__(*, api_key: Optional[str] = None, iam_token: Optional[str] = None, model: str = 'general', language: str = 'auto')[source]\u00b6\nInitialize the parser.\nParameters\napi_key \u2013 API key for a service account\nrole. (with the ai.speechkit-stt.user) \u2013 \niam_token \u2013 IAM token for a service account\nrole. \u2013 \nmodel \u2013 Recognition model name.\nDefaults to general.\nlanguage \u2013 The language in ISO 639-1 format.\nDefaults to automatic language recognition.\nEither api_key or iam_token must be provided, but not both.\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLazily parse the blob.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.audio.YandexSTTParser.html"}
{"id": "d863f96b6c8a-1", "text": "Lazily parse the blob.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.audio.YandexSTTParser.html"}
{"id": "c29bb20427d5-0", "text": "langchain.document_loaders.roam.RoamLoader\u00b6\nclass langchain.document_loaders.roam.RoamLoader(path: str)[source]\u00b6\nLoad Roam files from a directory.\nInitialize with a path.\nMethods\n__init__(path)\nInitialize with a path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(path: str)[source]\u00b6\nInitialize with a path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using RoamLoader\u00b6\nRoam", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.roam.RoamLoader.html"}
{"id": "5d397031013b-0", "text": "langchain.document_loaders.gcs_file.GCSFileLoader\u00b6\nclass langchain.document_loaders.gcs_file.GCSFileLoader(project_name: str, bucket: str, blob: str, loader_func: Optional[Callable[[str], BaseLoader]] = None)[source]\u00b6\nLoad from GCS file.\nInitialize with bucket and key name.\nParameters\nproject_name \u2013 The name of the project to load\nbucket \u2013 The name of the GCS bucket.\nblob \u2013 The name of the GCS blob to load.\nloader_func \u2013 A loader function that instantiates a loader based on a\nfile_path argument. If nothing is provided, the\nUnstructuredFileLoader is used.\nExamples\nTo use an alternative PDF loader:\n>> from from langchain.document_loaders import PyPDFLoader\n>> loader = GCSFileLoader(\u2026, loader_func=PyPDFLoader)\nTo use UnstructuredFileLoader with additional arguments:\n>> loader = GCSFileLoader(\u2026,\n>>      loader_func=lambda x: UnstructuredFileLoader(x, mode=\u201delements\u201d))\nMethods\n__init__(project_name,\u00a0bucket,\u00a0blob[,\u00a0...])\nInitialize with bucket and key name.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(project_name: str, bucket: str, blob: str, loader_func: Optional[Callable[[str], BaseLoader]] = None)[source]\u00b6\nInitialize with bucket and key name.\nParameters\nproject_name \u2013 The name of the project to load\nbucket \u2013 The name of the GCS bucket.\nblob \u2013 The name of the GCS blob to load.\nloader_func \u2013 A loader function that instantiates a loader based on a\nfile_path argument. If nothing is provided, the", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.gcs_file.GCSFileLoader.html"}
{"id": "5d397031013b-1", "text": "file_path argument. If nothing is provided, the\nUnstructuredFileLoader is used.\nExamples\nTo use an alternative PDF loader:\n>> from from langchain.document_loaders import PyPDFLoader\n>> loader = GCSFileLoader(\u2026, loader_func=PyPDFLoader)\nTo use UnstructuredFileLoader with additional arguments:\n>> loader = GCSFileLoader(\u2026,\n>>      loader_func=lambda x: UnstructuredFileLoader(x, mode=\u201delements\u201d))\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using GCSFileLoader\u00b6\nGoogle Cloud Storage\nGoogle Cloud Storage File", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.gcs_file.GCSFileLoader.html"}
{"id": "6272f08ddbfb-0", "text": "langchain.document_loaders.college_confidential.CollegeConfidentialLoader\u00b6\nclass langchain.document_loaders.college_confidential.CollegeConfidentialLoader(web_path: Union[str, Sequence[str]] = '', header_template: Optional[dict] = None, verify_ssl: bool = True, proxies: Optional[dict] = None, continue_on_failure: bool = False, autoset_encoding: bool = True, encoding: Optional[str] = None, web_paths: Sequence[str] = (), requests_per_second: int = 2, default_parser: str = 'html.parser', requests_kwargs: Optional[Dict[str, Any]] = None, raise_for_status: bool = False, bs_get_text_kwargs: Optional[Dict[str, Any]] = None, bs_kwargs: Optional[Dict[str, Any]] = None, session: Any = None)[source]\u00b6\nLoad College Confidential webpages.\nInitialize loader.\nParameters\nweb_paths \u2013 Web paths to load from.\nrequests_per_second \u2013 Max number of concurrent requests to make.\ndefault_parser \u2013 Default parser to use for BeautifulSoup.\nrequests_kwargs \u2013 kwargs for requests\nraise_for_status \u2013 Raise an exception if http status code denotes an error.\nbs_get_text_kwargs \u2013 kwargs for beatifulsoup4 get_text\nbs_kwargs \u2013 kwargs for beatifulsoup4 web page parsing\nAttributes\nweb_path\nMethods\n__init__([web_path,\u00a0header_template,\u00a0...])\nInitialize loader.\naload()\nLoad text from the urls in web_path async into Documents.\nfetch_all(urls)\nFetch all urls concurrently with rate limiting.\nlazy_load()\nLazy load text from the url(s) in web_path.\nload()\nLoad webpages as Documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nscrape([parser])\nScrape data from webpage and return it in BeautifulSoup format.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.college_confidential.CollegeConfidentialLoader.html"}
{"id": "6272f08ddbfb-1", "text": "scrape([parser])\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls[,\u00a0parser])\nFetch all urls, then return soups for all results.\n__init__(web_path: Union[str, Sequence[str]] = '', header_template: Optional[dict] = None, verify_ssl: bool = True, proxies: Optional[dict] = None, continue_on_failure: bool = False, autoset_encoding: bool = True, encoding: Optional[str] = None, web_paths: Sequence[str] = (), requests_per_second: int = 2, default_parser: str = 'html.parser', requests_kwargs: Optional[Dict[str, Any]] = None, raise_for_status: bool = False, bs_get_text_kwargs: Optional[Dict[str, Any]] = None, bs_kwargs: Optional[Dict[str, Any]] = None, session: Any = None) \u2192 None\u00b6\nInitialize loader.\nParameters\nweb_paths \u2013 Web paths to load from.\nrequests_per_second \u2013 Max number of concurrent requests to make.\ndefault_parser \u2013 Default parser to use for BeautifulSoup.\nrequests_kwargs \u2013 kwargs for requests\nraise_for_status \u2013 Raise an exception if http status code denotes an error.\nbs_get_text_kwargs \u2013 kwargs for beatifulsoup4 get_text\nbs_kwargs \u2013 kwargs for beatifulsoup4 web page parsing\naload() \u2192 List[Document]\u00b6\nLoad text from the urls in web_path async into Documents.\nasync fetch_all(urls: List[str]) \u2192 Any\u00b6\nFetch all urls concurrently with rate limiting.\nlazy_load() \u2192 Iterator[Document]\u00b6\nLazy load text from the url(s) in web_path.\nload() \u2192 List[Document][source]\u00b6\nLoad webpages as Documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.college_confidential.CollegeConfidentialLoader.html"}
{"id": "6272f08ddbfb-2", "text": "Load Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nscrape(parser: Optional[str] = None) \u2192 Any\u00b6\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls: List[str], parser: Optional[str] = None) \u2192 List[Any]\u00b6\nFetch all urls, then return soups for all results.\nExamples using CollegeConfidentialLoader\u00b6\nCollege Confidential", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.college_confidential.CollegeConfidentialLoader.html"}
{"id": "2a3b2161b19d-0", "text": "langchain.document_loaders.web_base.WebBaseLoader\u00b6\nclass langchain.document_loaders.web_base.WebBaseLoader(web_path: Union[str, Sequence[str]] = '', header_template: Optional[dict] = None, verify_ssl: bool = True, proxies: Optional[dict] = None, continue_on_failure: bool = False, autoset_encoding: bool = True, encoding: Optional[str] = None, web_paths: Sequence[str] = (), requests_per_second: int = 2, default_parser: str = 'html.parser', requests_kwargs: Optional[Dict[str, Any]] = None, raise_for_status: bool = False, bs_get_text_kwargs: Optional[Dict[str, Any]] = None, bs_kwargs: Optional[Dict[str, Any]] = None, session: Any = None)[source]\u00b6\nLoad HTML pages using urllib and parse them with `BeautifulSoup\u2019.\nInitialize loader.\nParameters\nweb_paths \u2013 Web paths to load from.\nrequests_per_second \u2013 Max number of concurrent requests to make.\ndefault_parser \u2013 Default parser to use for BeautifulSoup.\nrequests_kwargs \u2013 kwargs for requests\nraise_for_status \u2013 Raise an exception if http status code denotes an error.\nbs_get_text_kwargs \u2013 kwargs for beatifulsoup4 get_text\nbs_kwargs \u2013 kwargs for beatifulsoup4 web page parsing\nAttributes\nweb_path\nMethods\n__init__([web_path,\u00a0header_template,\u00a0...])\nInitialize loader.\naload()\nLoad text from the urls in web_path async into Documents.\nfetch_all(urls)\nFetch all urls concurrently with rate limiting.\nlazy_load()\nLazy load text from the url(s) in web_path.\nload()\nLoad text from the url(s) in web_path.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nscrape([parser])\nScrape data from webpage and return it in BeautifulSoup format.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.web_base.WebBaseLoader.html"}
{"id": "2a3b2161b19d-1", "text": "scrape([parser])\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls[,\u00a0parser])\nFetch all urls, then return soups for all results.\n__init__(web_path: Union[str, Sequence[str]] = '', header_template: Optional[dict] = None, verify_ssl: bool = True, proxies: Optional[dict] = None, continue_on_failure: bool = False, autoset_encoding: bool = True, encoding: Optional[str] = None, web_paths: Sequence[str] = (), requests_per_second: int = 2, default_parser: str = 'html.parser', requests_kwargs: Optional[Dict[str, Any]] = None, raise_for_status: bool = False, bs_get_text_kwargs: Optional[Dict[str, Any]] = None, bs_kwargs: Optional[Dict[str, Any]] = None, session: Any = None) \u2192 None[source]\u00b6\nInitialize loader.\nParameters\nweb_paths \u2013 Web paths to load from.\nrequests_per_second \u2013 Max number of concurrent requests to make.\ndefault_parser \u2013 Default parser to use for BeautifulSoup.\nrequests_kwargs \u2013 kwargs for requests\nraise_for_status \u2013 Raise an exception if http status code denotes an error.\nbs_get_text_kwargs \u2013 kwargs for beatifulsoup4 get_text\nbs_kwargs \u2013 kwargs for beatifulsoup4 web page parsing\naload() \u2192 List[Document][source]\u00b6\nLoad text from the urls in web_path async into Documents.\nasync fetch_all(urls: List[str]) \u2192 Any[source]\u00b6\nFetch all urls concurrently with rate limiting.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load text from the url(s) in web_path.\nload() \u2192 List[Document][source]\u00b6\nLoad text from the url(s) in web_path.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.web_base.WebBaseLoader.html"}
{"id": "2a3b2161b19d-2", "text": "Load Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nscrape(parser: Optional[str] = None) \u2192 Any[source]\u00b6\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls: List[str], parser: Optional[str] = None) \u2192 List[Any][source]\u00b6\nFetch all urls, then return soups for all results.\nExamples using WebBaseLoader\u00b6\nRePhraseQueryRetriever\nOllama\nVectorstore\nZep\nWebBaseLoader\nMergeDocLoader\nSet env var OPENAI_API_KEY or load from a .env file:\nSet env var OPENAI_API_KEY or load from a .env file\nQuestion Answering\nUse local LLMs\nMultiQueryRetriever\nCombine agents and vector stores", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.web_base.WebBaseLoader.html"}
{"id": "f42f40607f3b-0", "text": "langchain.document_loaders.html_bs.BSHTMLLoader\u00b6\nclass langchain.document_loaders.html_bs.BSHTMLLoader(file_path: str, open_encoding: Optional[str] = None, bs_kwargs: Optional[dict] = None, get_text_separator: str = '')[source]\u00b6\nLoad HTML files and parse them with beautiful soup.\nInitialise with path, and optionally, file encoding to use, and any kwargs\nto pass to the BeautifulSoup object.\nParameters\nfile_path \u2013 The path to the file to load.\nopen_encoding \u2013 The encoding to use when opening the file.\nbs_kwargs \u2013 Any kwargs to pass to the BeautifulSoup object.\nget_text_separator \u2013 The separator to use when calling get_text on the soup.\nMethods\n__init__(file_path[,\u00a0open_encoding,\u00a0...])\nInitialise with path, and optionally, file encoding to use, and any kwargs to pass to the BeautifulSoup object.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad HTML document into document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, open_encoding: Optional[str] = None, bs_kwargs: Optional[dict] = None, get_text_separator: str = '') \u2192 None[source]\u00b6\nInitialise with path, and optionally, file encoding to use, and any kwargs\nto pass to the BeautifulSoup object.\nParameters\nfile_path \u2013 The path to the file to load.\nopen_encoding \u2013 The encoding to use when opening the file.\nbs_kwargs \u2013 Any kwargs to pass to the BeautifulSoup object.\nget_text_separator \u2013 The separator to use when calling get_text on the soup.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad HTML document into document objects.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.html_bs.BSHTMLLoader.html"}
{"id": "f42f40607f3b-1", "text": "load() \u2192 List[Document][source]\u00b6\nLoad HTML document into document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.html_bs.BSHTMLLoader.html"}
{"id": "37aa60b94806-0", "text": "langchain.document_loaders.parsers.registry.get_parser\u00b6\nlangchain.document_loaders.parsers.registry.get_parser(parser_name: str) \u2192 BaseBlobParser[source]\u00b6\nGet a parser by parser name.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.registry.get_parser.html"}
{"id": "b0f81326eea4-0", "text": "langchain.document_loaders.etherscan.EtherscanLoader\u00b6\nclass langchain.document_loaders.etherscan.EtherscanLoader(account_address: str, api_key: str = 'docs-demo', filter: str = 'normal_transaction', page: int = 1, offset: int = 10, start_block: int = 0, end_block: int = 99999999, sort: str = 'desc')[source]\u00b6\nLoad transactions from Ethereum mainnet.\nThe Loader use Etherscan API to interact with Ethereum mainnet.\nETHERSCAN_API_KEY environment variable must be set use this loader.\nMethods\n__init__(account_address[,\u00a0api_key,\u00a0filter,\u00a0...])\ngetERC1155Tx()\ngetERC20Tx()\ngetERC721Tx()\ngetEthBalance()\ngetInternalTx()\ngetNormTx()\nlazy_load()\nLazy load Documents from table.\nload()\nLoad transactions from spcifc account by Etherscan.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(account_address: str, api_key: str = 'docs-demo', filter: str = 'normal_transaction', page: int = 1, offset: int = 10, start_block: int = 0, end_block: int = 99999999, sort: str = 'desc')[source]\u00b6\ngetERC1155Tx() \u2192 List[Document][source]\u00b6\ngetERC20Tx() \u2192 List[Document][source]\u00b6\ngetERC721Tx() \u2192 List[Document][source]\u00b6\ngetEthBalance() \u2192 List[Document][source]\u00b6\ngetInternalTx() \u2192 List[Document][source]\u00b6\ngetNormTx() \u2192 List[Document][source]\u00b6\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load Documents from table.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.etherscan.EtherscanLoader.html"}
{"id": "b0f81326eea4-1", "text": "lazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load Documents from table.\nload() \u2192 List[Document][source]\u00b6\nLoad transactions from spcifc account by Etherscan.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using EtherscanLoader\u00b6\nEtherscan Loader", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.etherscan.EtherscanLoader.html"}
{"id": "12f6cf41da9c-0", "text": "langchain.document_loaders.s3_directory.S3DirectoryLoader\u00b6\nclass langchain.document_loaders.s3_directory.S3DirectoryLoader(bucket: str, prefix: str = '', *, region_name: Optional[str] = None, api_version: Optional[str] = None, use_ssl: Optional[bool] = True, verify: Union[str, bool, None] = None, endpoint_url: Optional[str] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_session_token: Optional[str] = None, boto_config: Optional[botocore.client.Config] = None)[source]\u00b6\nLoad from Amazon AWS S3 directory.\nInitialize with bucket and key name.\nParameters\nbucket \u2013 The name of the S3 bucket.\nprefix \u2013 The prefix of the S3 key. Defaults to \u201c\u201d.\nregion_name \u2013 The name of the region associated with the client.\nA client is associated with a single region.\napi_version \u2013 The API version to use.  By default, botocore will\nuse the latest API version when creating a client.  You only need\nto specify this parameter if you want to use a previous API version\nof the client.\nuse_ssl \u2013 Whether to use SSL.  By default, SSL is used.\nNote that not all services support non-ssl connections.\nverify \u2013 Whether to verify SSL certificates.\nBy default SSL certificates are verified.  You can provide the\nfollowing values:\nFalse - do not validate SSL certificates.  SSL will still be\nused (unless use_ssl is False), but SSL certificates\nwill not be verified.\npath/to/cert/bundle.pem - A filename of the CA cert bundle to\nuses.  You can specify this argument if you want to use a\ndifferent CA cert bundle than the one used by botocore.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.s3_directory.S3DirectoryLoader.html"}
{"id": "12f6cf41da9c-1", "text": "different CA cert bundle than the one used by botocore.\nendpoint_url \u2013 The complete URL to use for the constructed\nclient.  Normally, botocore will automatically construct the\nappropriate URL to use when communicating with a service.  You can\nspecify a complete URL (including the \u201chttp/https\u201d scheme) to\noverride this behavior.  If this value is provided, then\nuse_ssl is ignored.\naws_access_key_id \u2013 The access key to use when creating\nthe client.  This is entirely optional, and if not provided,\nthe credentials configured for the session will automatically\nbe used.  You only need to provide this argument if you want\nto override the credentials used for this specific client.\naws_secret_access_key \u2013 The secret key to use when creating\nthe client.  Same semantics as aws_access_key_id above.\naws_session_token \u2013 The session token to use when creating\nthe client.  Same semantics as aws_access_key_id above.\nboto_config (botocore.client.Config) \u2013 Advanced boto3 client configuration options. If a value\nis specified in the client config, its value will take precedence\nover environment variables and configuration values, but not over\na value passed explicitly to the method. If a default config\nobject is set on the session, the config object used when creating\nthe client will be the result of calling merge() on the\ndefault config with the config provided to this call.\nMethods\n__init__(bucket[,\u00a0prefix,\u00a0region_name,\u00a0...])\nInitialize with bucket and key name.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.s3_directory.S3DirectoryLoader.html"}
{"id": "12f6cf41da9c-2", "text": "load_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(bucket: str, prefix: str = '', *, region_name: Optional[str] = None, api_version: Optional[str] = None, use_ssl: Optional[bool] = True, verify: Union[str, bool, None] = None, endpoint_url: Optional[str] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_session_token: Optional[str] = None, boto_config: Optional[botocore.client.Config] = None)[source]\u00b6\nInitialize with bucket and key name.\nParameters\nbucket \u2013 The name of the S3 bucket.\nprefix \u2013 The prefix of the S3 key. Defaults to \u201c\u201d.\nregion_name \u2013 The name of the region associated with the client.\nA client is associated with a single region.\napi_version \u2013 The API version to use.  By default, botocore will\nuse the latest API version when creating a client.  You only need\nto specify this parameter if you want to use a previous API version\nof the client.\nuse_ssl \u2013 Whether to use SSL.  By default, SSL is used.\nNote that not all services support non-ssl connections.\nverify \u2013 Whether to verify SSL certificates.\nBy default SSL certificates are verified.  You can provide the\nfollowing values:\nFalse - do not validate SSL certificates.  SSL will still be\nused (unless use_ssl is False), but SSL certificates\nwill not be verified.\npath/to/cert/bundle.pem - A filename of the CA cert bundle to\nuses.  You can specify this argument if you want to use a\ndifferent CA cert bundle than the one used by botocore.\nendpoint_url \u2013 The complete URL to use for the constructed\nclient.  Normally, botocore will automatically construct the", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.s3_directory.S3DirectoryLoader.html"}
{"id": "12f6cf41da9c-3", "text": "client.  Normally, botocore will automatically construct the\nappropriate URL to use when communicating with a service.  You can\nspecify a complete URL (including the \u201chttp/https\u201d scheme) to\noverride this behavior.  If this value is provided, then\nuse_ssl is ignored.\naws_access_key_id \u2013 The access key to use when creating\nthe client.  This is entirely optional, and if not provided,\nthe credentials configured for the session will automatically\nbe used.  You only need to provide this argument if you want\nto override the credentials used for this specific client.\naws_secret_access_key \u2013 The secret key to use when creating\nthe client.  Same semantics as aws_access_key_id above.\naws_session_token \u2013 The session token to use when creating\nthe client.  Same semantics as aws_access_key_id above.\nboto_config (botocore.client.Config) \u2013 Advanced boto3 client configuration options. If a value\nis specified in the client config, its value will take precedence\nover environment variables and configuration values, but not over\na value passed explicitly to the method. If a default config\nobject is set on the session, the config object used when creating\nthe client will be the result of calling merge() on the\ndefault config with the config provided to this call.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using S3DirectoryLoader\u00b6\nAWS S3 Directory", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.s3_directory.S3DirectoryLoader.html"}
{"id": "92d3b1a14971-0", "text": "langchain.document_loaders.notebook.NotebookLoader\u00b6\nclass langchain.document_loaders.notebook.NotebookLoader(path: str, include_outputs: bool = False, max_output_length: int = 10, remove_newline: bool = False, traceback: bool = False)[source]\u00b6\nLoad Jupyter notebook (.ipynb) files.\nInitialize with a path.\nParameters\npath \u2013 The path to load the notebook from.\ninclude_outputs \u2013 Whether to include the outputs of the cell.\nDefaults to False.\nmax_output_length \u2013 Maximum length of the output to be displayed.\nDefaults to 10.\nremove_newline \u2013 Whether to remove newlines from the notebook.\nDefaults to False.\ntraceback \u2013 Whether to return a traceback of the error.\nDefaults to False.\nMethods\n__init__(path[,\u00a0include_outputs,\u00a0...])\nInitialize with a path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(path: str, include_outputs: bool = False, max_output_length: int = 10, remove_newline: bool = False, traceback: bool = False)[source]\u00b6\nInitialize with a path.\nParameters\npath \u2013 The path to load the notebook from.\ninclude_outputs \u2013 Whether to include the outputs of the cell.\nDefaults to False.\nmax_output_length \u2013 Maximum length of the output to be displayed.\nDefaults to 10.\nremove_newline \u2013 Whether to remove newlines from the notebook.\nDefaults to False.\ntraceback \u2013 Whether to return a traceback of the error.\nDefaults to False.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.notebook.NotebookLoader.html"}
{"id": "92d3b1a14971-1", "text": "load() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using NotebookLoader\u00b6\nJupyter Notebook\nNotebook", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.notebook.NotebookLoader.html"}
{"id": "6aa78d83afb1-0", "text": "langchain.document_loaders.parsers.language.language_parser.LanguageParser\u00b6\nclass langchain.document_loaders.parsers.language.language_parser.LanguageParser(language: Optional[Language] = None, parser_threshold: int = 0)[source]\u00b6\nParse using the respective programming language syntax.\nEach top-level function and class in the code is loaded into separate documents.\nFurthermore, an extra document is generated, containing the remaining top-level code\nthat excludes the already segmented functions and classes.\nThis approach can potentially improve the accuracy of QA models over source code.\nCurrently, the supported languages for code parsing are Python and JavaScript.\nThe language used for parsing can be configured, along with the minimum number of\nlines required to activate the splitting based on syntax.\nExamples\n    from langchain.text_splitter.Language\n    from langchain.document_loaders.generic import GenericLoader\n    from langchain.document_loaders.parsers import LanguageParser\n    loader = GenericLoader.from_filesystem(\n        \"./code\",\n        glob=\"**/*\",\n        suffixes=[\".py\", \".js\"],\n        parser=LanguageParser()\n    )\n    docs = loader.load()\nExample instantiations to manually select the language:\n.. code-block:: python\n    from langchain.text_splitter import Language\n    loader = GenericLoader.from_filesystem(\n        \"./code\",\n        glob=\"**/*\",\n        suffixes=[\".py\"],\n        parser=LanguageParser(language=Language.PYTHON)\n    )\nExample instantiations to set number of lines threshold:\n.. code-block:: python\n    loader = GenericLoader.from_filesystem(\n        \"./code\",\n        glob=\"**/*\",\n        suffixes=[\".py\"],\n        parser=LanguageParser(parser_threshold=200)\n    )\nLanguage parser that split code using the respective language syntax.\nParameters\nlanguage \u2013 If None (default), it will try to infer language from source.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.language.language_parser.LanguageParser.html"}
{"id": "6aa78d83afb1-1", "text": "Parameters\nlanguage \u2013 If None (default), it will try to infer language from source.\nparser_threshold \u2013 Minimum lines needed to activate parsing (0 by default).\nMethods\n__init__([language,\u00a0parser_threshold])\nLanguage parser that split code using the respective language syntax.\nlazy_parse(blob)\nLazy parsing interface.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__(language: Optional[Language] = None, parser_threshold: int = 0)[source]\u00b6\nLanguage parser that split code using the respective language syntax.\nParameters\nlanguage \u2013 If None (default), it will try to infer language from source.\nparser_threshold \u2013 Minimum lines needed to activate parsing (0 by default).\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLazy parsing interface.\nSubclasses are required to implement this method.\nParameters\nblob \u2013 Blob instance\nReturns\nGenerator of documents\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents\nExamples using LanguageParser\u00b6\nSource Code\nSet env var OPENAI_API_KEY or load from a .env file", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.language.language_parser.LanguageParser.html"}
{"id": "fd0d822e6766-0", "text": "langchain.document_loaders.airbyte.AirbyteCDKLoader\u00b6\nclass langchain.document_loaders.airbyte.AirbyteCDKLoader(config: Mapping[str, Any], source_class: Any, stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None)[source]\u00b6\nLoad with an Airbyte source connector implemented using the CDK.\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nsource_class \u2013 The source connector class.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.\nAttributes\nlast_state\nMethods\n__init__(config,\u00a0source_class,\u00a0stream_name)\nInitializes the loader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(config: Mapping[str, Any], source_class: Any, stream_name: str, record_handler: Optional[Callable[[Any, Optional[str]], Document]] = None, state: Optional[Any] = None) \u2192 None[source]\u00b6\nInitializes the loader.\nParameters\nconfig \u2013 The config to pass to the source connector.\nsource_class \u2013 The source connector class.\nstream_name \u2013 The name of the stream to load.\nrecord_handler \u2013 A function that takes in a record and an optional id and\nreturns a Document. If None, the record will be used as the document.\nDefaults to None.\nstate \u2013 The state to pass to the source connector. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteCDKLoader.html"}
{"id": "fd0d822e6766-1", "text": "state \u2013 The state to pass to the source connector. Defaults to None.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AirbyteCDKLoader\u00b6\nAirbyte CDK", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airbyte.AirbyteCDKLoader.html"}
{"id": "3cf6b4dcb5f4-0", "text": "langchain.document_loaders.git.GitLoader\u00b6\nclass langchain.document_loaders.git.GitLoader(repo_path: str, clone_url: Optional[str] = None, branch: Optional[str] = 'main', file_filter: Optional[Callable[[str], bool]] = None)[source]\u00b6\nLoad Git repository files.\nThe Repository can be local on disk available at repo_path,\nor remote at clone_url that will be cloned to repo_path.\nCurrently, supports only text files.\nEach document represents one file in the repository. The path points to\nthe local Git repository, and the branch specifies the branch to load\nfiles from. By default, it loads from the main branch.\nParameters\nrepo_path \u2013 The path to the Git repository.\nclone_url \u2013 Optional. The URL to clone the repository from.\nbranch \u2013 Optional. The branch to load files from. Defaults to main.\nfile_filter \u2013 Optional. A function that takes a file path and returns\na boolean indicating whether to load the file. Defaults to None.\nMethods\n__init__(repo_path[,\u00a0clone_url,\u00a0branch,\u00a0...])\nparam repo_path\nThe path to the Git repository.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(repo_path: str, clone_url: Optional[str] = None, branch: Optional[str] = 'main', file_filter: Optional[Callable[[str], bool]] = None)[source]\u00b6\nParameters\nrepo_path \u2013 The path to the Git repository.\nclone_url \u2013 Optional. The URL to clone the repository from.\nbranch \u2013 Optional. The branch to load files from. Defaults to main.\nfile_filter \u2013 Optional. A function that takes a file path and returns", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.git.GitLoader.html"}
{"id": "3cf6b4dcb5f4-1", "text": "file_filter \u2013 Optional. A function that takes a file path and returns\na boolean indicating whether to load the file. Defaults to None.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using GitLoader\u00b6\nGit", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.git.GitLoader.html"}
{"id": "d4bcf3124f90-0", "text": "langchain.document_loaders.parsers.txt.TextParser\u00b6\nclass langchain.document_loaders.parsers.txt.TextParser[source]\u00b6\nParser for text blobs.\nMethods\n__init__()\nlazy_parse(blob)\nLazily parse the blob.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__()\u00b6\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLazily parse the blob.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.txt.TextParser.html"}
{"id": "54b0a6533dea-0", "text": "langchain.document_loaders.rst.UnstructuredRSTLoader\u00b6\nclass langchain.document_loaders.rst.UnstructuredRSTLoader(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad RST files using Unstructured.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredRSTLoader\nloader = UnstructuredRSTLoader(\u201cexample.rst\u201d, mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition-rst\nInitialize with a file path.\nParameters\nfile_path \u2013 The path to the file to load.\nmode \u2013 The mode to use for partitioning. See unstructured for details.\nDefaults to \u201csingle\u201d.\n**unstructured_kwargs \u2013 Additional keyword arguments to pass\nto unstructured.\nMethods\n__init__(file_path[,\u00a0mode])\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nInitialize with a file path.\nParameters\nfile_path \u2013 The path to the file to load.\nmode \u2013 The mode to use for partitioning. See unstructured for details.\nDefaults to \u201csingle\u201d.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.rst.UnstructuredRSTLoader.html"}
{"id": "54b0a6533dea-1", "text": "Defaults to \u201csingle\u201d.\n**unstructured_kwargs \u2013 Additional keyword arguments to pass\nto unstructured.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredRSTLoader\u00b6\nRST", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.rst.UnstructuredRSTLoader.html"}
{"id": "b2d5af655377-0", "text": "langchain.document_loaders.blockchain.BlockchainType\u00b6\nclass langchain.document_loaders.blockchain.BlockchainType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnumerator of the supported blockchains.\nETH_MAINNET = 'eth-mainnet'\u00b6\nETH_GOERLI = 'eth-goerli'\u00b6\nPOLYGON_MAINNET = 'polygon-mainnet'\u00b6\nPOLYGON_MUMBAI = 'polygon-mumbai'\u00b6\nExamples using BlockchainType\u00b6\nBlockchain", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blockchain.BlockchainType.html"}
{"id": "dfa7aac51010-0", "text": "langchain.document_loaders.csv_loader.UnstructuredCSVLoader\u00b6\nclass langchain.document_loaders.csv_loader.UnstructuredCSVLoader(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nLoad CSV files using Unstructured.\nLike other\nUnstructured loaders, UnstructuredCSVLoader can be used in both\n\u201csingle\u201d and \u201celements\u201d mode. If you use the loader in \u201celements\u201d\nmode, the CSV file will be a single Unstructured Table element.\nIf you use the loader in \u201celements\u201d mode, an HTML representation\nof the table will be available in the \u201ctext_as_html\u201d key in the\ndocument metadata.\nExamples\nfrom langchain.document_loaders.csv_loader import UnstructuredCSVLoader\nloader = UnstructuredCSVLoader(\u201cstanley-cups.csv\u201d, mode=\u201delements\u201d)\ndocs = loader.load()\nParameters\nfile_path \u2013 The path to the CSV file.\nmode \u2013 The mode to use when loading the CSV file.\nOptional. Defaults to \u201csingle\u201d.\n**unstructured_kwargs \u2013 Keyword arguments to pass to unstructured.\nMethods\n__init__(file_path[,\u00a0mode])\nparam file_path\nThe path to the CSV file.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, mode: str = 'single', **unstructured_kwargs: Any)[source]\u00b6\nParameters\nfile_path \u2013 The path to the CSV file.\nmode \u2013 The mode to use when loading the CSV file.\nOptional. Defaults to \u201csingle\u201d.\n**unstructured_kwargs \u2013 Keyword arguments to pass to unstructured.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.csv_loader.UnstructuredCSVLoader.html"}
{"id": "dfa7aac51010-1", "text": "A lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredCSVLoader\u00b6\nCSV", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.csv_loader.UnstructuredCSVLoader.html"}
{"id": "db26d478359b-0", "text": "langchain.document_loaders.concurrent.ConcurrentLoader\u00b6\nclass langchain.document_loaders.concurrent.ConcurrentLoader(blob_loader: BlobLoader, blob_parser: BaseBlobParser, num_workers: int = 4)[source]\u00b6\nLoad and pars Documents concurrently.\nA generic document loader.\nParameters\nblob_loader \u2013 A blob loader which knows how to yield blobs\nblob_parser \u2013 A blob parser which knows how to parse blobs into documents\nMethods\n__init__(blob_loader,\u00a0blob_parser[,\u00a0num_workers])\nA generic document loader.\nfrom_filesystem(path,\u00a0*[,\u00a0glob,\u00a0exclude,\u00a0...])\nCreate a concurrent generic document loader using a filesystem blob loader.\nlazy_load()\nLoad documents lazily with concurrent parsing.\nload()\nLoad all documents.\nload_and_split([text_splitter])\nLoad all documents and split them into sentences.\n__init__(blob_loader: BlobLoader, blob_parser: BaseBlobParser, num_workers: int = 4) \u2192 None[source]\u00b6\nA generic document loader.\nParameters\nblob_loader \u2013 A blob loader which knows how to yield blobs\nblob_parser \u2013 A blob parser which knows how to parse blobs into documents\nclassmethod from_filesystem(path: Union[str, Path], *, glob: str = '**/[!.]*', exclude: Sequence[str] = (), suffixes: Optional[Sequence[str]] = None, show_progress: bool = False, parser: Union[Literal['default'], BaseBlobParser] = 'default', num_workers: int = 4) \u2192 ConcurrentLoader[source]\u00b6\nCreate a concurrent generic document loader using a\nfilesystem blob loader.\nParameters\npath \u2013 The path to the directory to load documents from.\nglob \u2013 The glob pattern to use to find documents.\nsuffixes \u2013 The suffixes to use to filter documents. If None, all files\nmatching the glob will be loaded.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.concurrent.ConcurrentLoader.html"}
{"id": "db26d478359b-1", "text": "matching the glob will be loaded.\nexclude \u2013 A list of patterns to exclude from the loader.\nshow_progress \u2013 Whether to show a progress bar or not (requires tqdm).\nProxies to the file system loader.\nparser \u2013 A blob parser which knows how to parse blobs into documents\nnum_workers \u2013 Max number of concurrent workers to use.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLoad documents lazily with concurrent parsing.\nload() \u2192 List[Document]\u00b6\nLoad all documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad all documents and split them into sentences.\nExamples using ConcurrentLoader\u00b6\nConcurrent Loader", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.concurrent.ConcurrentLoader.html"}
{"id": "4825a849e695-0", "text": "langchain.document_loaders.docugami.DocugamiLoader\u00b6\nclass langchain.document_loaders.docugami.DocugamiLoader[source]\u00b6\nBases: BaseLoader, BaseModel\nLoad from Docugami.\nTo use, you should have the lxml python package installed.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam access_token: Optional[str] = None\u00b6\nThe Docugami API access token to use.\nparam api: str = 'https://api.docugami.com/v1preview1'\u00b6\nThe Docugami API endpoint to use.\nparam docset_id: Optional[str] = None\u00b6\nThe Docugami API docset ID to use.\nparam document_ids: Optional[Sequence[str]] = None\u00b6\nThe Docugami API document IDs to use.\nparam file_paths: Optional[Sequence[Union[pathlib.Path, str]]] = None\u00b6\nThe local file paths to use.\nparam min_chunk_size: int = 32\u00b6\nThe minimum chunk size to use when parsing DGML. Defaults to 32.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.docugami.DocugamiLoader.html"}
{"id": "4825a849e695-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.docugami.DocugamiLoader.html"}
{"id": "4825a849e695-2", "text": "load() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using DocugamiLoader\u00b6\nDocugami", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.docugami.DocugamiLoader.html"}
{"id": "69060f855b88-0", "text": "langchain.document_loaders.obs_directory.OBSDirectoryLoader\u00b6\nclass langchain.document_loaders.obs_directory.OBSDirectoryLoader(bucket: str, endpoint: str, config: Optional[dict] = None, prefix: str = '')[source]\u00b6\nLoad from Huawei OBS directory.\nInitialize the OBSDirectoryLoader with the specified settings.\nParameters\nbucket (str) \u2013 The name of the OBS bucket to be used.\nendpoint (str) \u2013 The endpoint URL of your OBS bucket.\nconfig (dict) \u2013 The parameters for connecting to OBS, provided as a dictionary. The dictionary could have the following keys:\n- \u201cak\u201d (str, optional): Your OBS access key (required if get_token_from_ecs is False and bucket policy is not public read).\n- \u201csk\u201d (str, optional): Your OBS secret key (required if get_token_from_ecs is False and bucket policy is not public read).\n- \u201ctoken\u201d (str, optional): Your security token (required if using temporary credentials).\n- \u201cget_token_from_ecs\u201d (bool, optional): Whether to retrieve the security token from ECS. Defaults to False if not provided. If set to True, ak, sk, and token will be ignored.\nprefix (str, optional) \u2013 The prefix to be added to the OBS key. Defaults to \u201c\u201d.\nNote\nBefore using this class, make sure you have registered with OBS and have the necessary credentials. The ak, sk, and endpoint values are mandatory unless get_token_from_ecs is True or the bucket policy is public read. token is required when using temporary credentials.\nExample\nTo create a new OBSDirectoryLoader:\n```\nconfig = {\n\u201cak\u201d: \u201cyour-access-key\u201d,\n\u201csk\u201d: \u201cyour-secret-key\u201d\ndirectory_loader = OBSDirectoryLoader(\u201cyour-bucket-name\u201d, \u201cyour-end-endpoint\u201d, config, \u201cyour-prefix\u201d)\nMethods", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.obs_directory.OBSDirectoryLoader.html"}
{"id": "69060f855b88-1", "text": "Methods\n__init__(bucket,\u00a0endpoint[,\u00a0config,\u00a0prefix])\nInitialize the OBSDirectoryLoader with the specified settings.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(bucket: str, endpoint: str, config: Optional[dict] = None, prefix: str = '')[source]\u00b6\nInitialize the OBSDirectoryLoader with the specified settings.\nParameters\nbucket (str) \u2013 The name of the OBS bucket to be used.\nendpoint (str) \u2013 The endpoint URL of your OBS bucket.\nconfig (dict) \u2013 The parameters for connecting to OBS, provided as a dictionary. The dictionary could have the following keys:\n- \u201cak\u201d (str, optional): Your OBS access key (required if get_token_from_ecs is False and bucket policy is not public read).\n- \u201csk\u201d (str, optional): Your OBS secret key (required if get_token_from_ecs is False and bucket policy is not public read).\n- \u201ctoken\u201d (str, optional): Your security token (required if using temporary credentials).\n- \u201cget_token_from_ecs\u201d (bool, optional): Whether to retrieve the security token from ECS. Defaults to False if not provided. If set to True, ak, sk, and token will be ignored.\nprefix (str, optional) \u2013 The prefix to be added to the OBS key. Defaults to \u201c\u201d.\nNote\nBefore using this class, make sure you have registered with OBS and have the necessary credentials. The ak, sk, and endpoint values are mandatory unless get_token_from_ecs is True or the bucket policy is public read. token is required when using temporary credentials.\nExample\nTo create a new OBSDirectoryLoader:\n```\nconfig = {\n\u201cak\u201d: \u201cyour-access-key\u201d,", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.obs_directory.OBSDirectoryLoader.html"}
{"id": "69060f855b88-2", "text": "```\nconfig = {\n\u201cak\u201d: \u201cyour-access-key\u201d,\n\u201csk\u201d: \u201cyour-secret-key\u201d\ndirectory_loader = OBSDirectoryLoader(\u201cyour-bucket-name\u201d, \u201cyour-end-endpoint\u201d, config, \u201cyour-prefix\u201d)\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using OBSDirectoryLoader\u00b6\nHuawei OBS Directory", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.obs_directory.OBSDirectoryLoader.html"}
{"id": "a413e9ed31e6-0", "text": "langchain.document_loaders.pyspark_dataframe.PySparkDataFrameLoader\u00b6\nclass langchain.document_loaders.pyspark_dataframe.PySparkDataFrameLoader(spark_session: Optional[SparkSession] = None, df: Optional[Any] = None, page_content_column: str = 'text', fraction_of_memory: float = 0.1)[source]\u00b6\nLoad PySpark DataFrames.\nInitialize with a Spark DataFrame object.\nParameters\nspark_session \u2013 The SparkSession object.\ndf \u2013 The Spark DataFrame object.\npage_content_column \u2013 The name of the column containing the page content.\nDefaults to \u201ctext\u201d.\nfraction_of_memory \u2013 The fraction of memory to use. Defaults to 0.1.\nMethods\n__init__([spark_session,\u00a0df,\u00a0...])\nInitialize with a Spark DataFrame object.\nget_num_rows()\nGets the number of \"feasible\" rows for the DataFrame\nlazy_load()\nA lazy loader for document content.\nload()\nLoad from the dataframe.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(spark_session: Optional[SparkSession] = None, df: Optional[Any] = None, page_content_column: str = 'text', fraction_of_memory: float = 0.1)[source]\u00b6\nInitialize with a Spark DataFrame object.\nParameters\nspark_session \u2013 The SparkSession object.\ndf \u2013 The Spark DataFrame object.\npage_content_column \u2013 The name of the column containing the page content.\nDefaults to \u201ctext\u201d.\nfraction_of_memory \u2013 The fraction of memory to use. Defaults to 0.1.\nget_num_rows() \u2192 Tuple[int, int][source]\u00b6\nGets the number of \u201cfeasible\u201d rows for the DataFrame\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for document content.\nload() \u2192 List[Document][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pyspark_dataframe.PySparkDataFrameLoader.html"}
{"id": "a413e9ed31e6-1", "text": "A lazy loader for document content.\nload() \u2192 List[Document][source]\u00b6\nLoad from the dataframe.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using PySparkDataFrameLoader\u00b6\nPySpark DataFrame Loader", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.pyspark_dataframe.PySparkDataFrameLoader.html"}
{"id": "118a2e999139-0", "text": "langchain.document_loaders.base.BaseLoader\u00b6\nclass langchain.document_loaders.base.BaseLoader[source]\u00b6\nInterface for Document Loader.\nImplementations should implement the lazy-loading method using generators\nto avoid loading all Documents into memory at once.\nThe load method will remain as is for backwards compatibility, but its\nimplementation should be just list(self.lazy_load()).\nMethods\n__init__()\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__()\u00b6\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nabstract load() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document][source]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using BaseLoader\u00b6\nIndexing", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.base.BaseLoader.html"}
{"id": "d05143b52603-0", "text": "langchain.document_loaders.base_o365.fetch_mime_types\u00b6\nlangchain.document_loaders.base_o365.fetch_mime_types(file_types: Sequence[_FileType]) \u2192 Dict[str, str][source]\u00b6\nFetch the mime types for the specified file types.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.base_o365.fetch_mime_types.html"}
{"id": "58061a06d61f-0", "text": "langchain.document_loaders.airtable.AirtableLoader\u00b6\nclass langchain.document_loaders.airtable.AirtableLoader(api_token: str, table_id: str, base_id: str)[source]\u00b6\nLoad the Airtable tables.\nInitialize with API token and the IDs for table and base\nAttributes\napi_token\nAirtable API token.\ntable_id\nAirtable table ID.\nbase_id\nAirtable base ID.\nMethods\n__init__(api_token,\u00a0table_id,\u00a0base_id)\nInitialize with API token and the IDs for table and base\nlazy_load()\nLazy load Documents from table.\nload()\nLoad Documents from table.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(api_token: str, table_id: str, base_id: str)[source]\u00b6\nInitialize with API token and the IDs for table and base\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load Documents from table.\nload() \u2192 List[Document][source]\u00b6\nLoad Documents from table.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AirtableLoader\u00b6\nAirtable", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.airtable.AirtableLoader.html"}
{"id": "eb4889a27a3e-0", "text": "langchain.document_loaders.dataframe.BaseDataFrameLoader\u00b6\nclass langchain.document_loaders.dataframe.BaseDataFrameLoader(data_frame: Any, *, page_content_column: str = 'text')[source]\u00b6\nInitialize with dataframe object.\nParameters\ndata_frame \u2013 DataFrame object.\npage_content_column \u2013 Name of the column containing the page content.\nDefaults to \u201ctext\u201d.\nMethods\n__init__(data_frame,\u00a0*[,\u00a0page_content_column])\nInitialize with dataframe object.\nlazy_load()\nLazy load records from dataframe.\nload()\nLoad full dataframe.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(data_frame: Any, *, page_content_column: str = 'text')[source]\u00b6\nInitialize with dataframe object.\nParameters\ndata_frame \u2013 DataFrame object.\npage_content_column \u2013 Name of the column containing the page content.\nDefaults to \u201ctext\u201d.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load records from dataframe.\nload() \u2192 List[Document][source]\u00b6\nLoad full dataframe.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.dataframe.BaseDataFrameLoader.html"}
{"id": "5086be9adfe7-0", "text": "langchain.document_loaders.tencent_cos_directory.TencentCOSDirectoryLoader\u00b6\nclass langchain.document_loaders.tencent_cos_directory.TencentCOSDirectoryLoader(conf: Any, bucket: str, prefix: str = '')[source]\u00b6\nLoad from Tencent Cloud COS directory.\nInitialize with COS config, bucket and prefix.\n:param conf(CosConfig): COS config.\n:param bucket(str): COS bucket.\n:param prefix(str): prefix.\nMethods\n__init__(conf,\u00a0bucket[,\u00a0prefix])\nInitialize with COS config, bucket and prefix.\nlazy_load()\nLoad documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(conf: Any, bucket: str, prefix: str = '')[source]\u00b6\nInitialize with COS config, bucket and prefix.\n:param conf(CosConfig): COS config.\n:param bucket(str): COS bucket.\n:param prefix(str): prefix.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLoad documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using TencentCOSDirectoryLoader\u00b6\nTencent COS Directory", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.tencent_cos_directory.TencentCOSDirectoryLoader.html"}
{"id": "801eb8a322a1-0", "text": "langchain.document_loaders.parsers.docai.DocAIParser\u00b6\nclass langchain.document_loaders.parsers.docai.DocAIParser(*, client: Optional[DocumentProcessorServiceClient] = None, location: Optional[str] = None, gcs_output_path: Optional[str] = None, processor_name: Optional[str] = None)[source]\u00b6\nGoogle Cloud Document AI parser.\nFor a detailed explanation of Document AI, refer to the product documentation.\nhttps://cloud.google.com/document-ai/docs/overview\nInitializes the parser.\nParameters\nclient \u2013 a DocumentProcessorServiceClient to use\nlocation \u2013 a Google Cloud location where a Document AI processor is located\ngcs_output_path \u2013 a path on Google Cloud Storage to store parsing results\nprocessor_name \u2013 full resource name of a Document AI processor or processor\nversion\nYou should provide either a client or location (and then a clientwould be instantiated).\nMethods\n__init__(*[,\u00a0client,\u00a0location,\u00a0...])\nInitializes the parser.\nbatch_parse(blobs[,\u00a0gcs_output_path,\u00a0...])\nParses a list of blobs lazily.\ndocai_parse(blobs,\u00a0*[,\u00a0gcs_output_path,\u00a0...])\nRuns Google Document AI PDF Batch Processing on a list of blobs.\nget_results(operations)\nis_running(operations)\nlazy_parse(blob)\nParses a blob lazily.\nonline_process(blob[,\u00a0...])\nParses a blob lazily using online processing.\noperations_from_names(operation_names)\nInitializes Long-Running Operations from their names.\nparse(blob)\nEagerly parse the blob into a document or documents.\nparse_from_results(results)", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.docai.DocAIParser.html"}
{"id": "801eb8a322a1-1", "text": "Eagerly parse the blob into a document or documents.\nparse_from_results(results)\n__init__(*, client: Optional[DocumentProcessorServiceClient] = None, location: Optional[str] = None, gcs_output_path: Optional[str] = None, processor_name: Optional[str] = None)[source]\u00b6\nInitializes the parser.\nParameters\nclient \u2013 a DocumentProcessorServiceClient to use\nlocation \u2013 a Google Cloud location where a Document AI processor is located\ngcs_output_path \u2013 a path on Google Cloud Storage to store parsing results\nprocessor_name \u2013 full resource name of a Document AI processor or processor\nversion\nYou should provide either a client or location (and then a clientwould be instantiated).\nbatch_parse(blobs: Sequence[Blob], gcs_output_path: Optional[str] = None, timeout_sec: int = 3600, check_in_interval_sec: int = 60) \u2192 Iterator[Document][source]\u00b6\nParses a list of blobs lazily.\nParameters\nblobs \u2013 a list of blobs to parse.\ngcs_output_path \u2013 a path on Google Cloud Storage to store parsing results.\ntimeout_sec \u2013 a timeout to wait for Document AI to complete, in seconds.\ncheck_in_interval_sec \u2013 an interval to wait until next check\nwhether parsing operations have been completed, in seconds\nThis is a long-running operation. A recommended way is to decoupleparsing from creating LangChain Documents:\n>>> operations = parser.docai_parse(blobs, gcs_path)\n>>> parser.is_running(operations)\nYou can get operations names and save them:\n>>> names = [op.operation.name for op in operations]\nAnd when all operations are finished, you can use their results:\n>>> operations = parser.operations_from_names(operation_names)\n>>> results = parser.get_results(operations)\n>>> docs = parser.parse_from_results(results)", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.docai.DocAIParser.html"}
{"id": "801eb8a322a1-2", "text": ">>> results = parser.get_results(operations)\n>>> docs = parser.parse_from_results(results)\ndocai_parse(blobs: Sequence[Blob], *, gcs_output_path: Optional[str] = None, processor_name: Optional[str] = None, batch_size: int = 1000, enable_native_pdf_parsing: bool = True, field_mask: Optional[str] = None) \u2192 List[Operation][source]\u00b6\nRuns Google Document AI PDF Batch Processing on a list of blobs.\nParameters\nblobs \u2013 a list of blobs to be parsed\ngcs_output_path \u2013 a path (folder) on GCS to store results\nprocessor_name \u2013 name of a Document AI processor.\nbatch_size \u2013 amount of documents per batch\nenable_native_pdf_parsing \u2013 a config option for the parser\nfield_mask \u2013 a comma-separated list of which fields to include in the\nDocument AI response.\nsuggested: \u201ctext,pages.pageNumber,pages.layout\u201d\nDocument AI has a 1000 file limit per batch, so batches larger than that need\nto be split into multiple requests.\nBatch processing is an async long-running operation\nand results are stored in a output GCS bucket.\nget_results(operations: List[Operation]) \u2192 List[DocAIParsingResults][source]\u00b6\nis_running(operations: List[Operation]) \u2192 bool[source]\u00b6\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nParses a blob lazily.\nParameters\nblobs \u2013 a Blob to parse\nThis is a long-running operation. A recommended way is to batchdocuments together and use the batch_parse() method.\nonline_process(blob: Blob, enable_native_pdf_parsing: bool = True, field_mask: Optional[str] = None, page_range: Optional[List[int]] = None) \u2192 Iterator[Document][source]\u00b6\nParses a blob lazily using online processing.\nParameters", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.docai.DocAIParser.html"}
{"id": "801eb8a322a1-3", "text": "Parses a blob lazily using online processing.\nParameters\nblob \u2013 a blob to parse.\nenable_native_pdf_parsing \u2013 enable pdf embedded text extraction\nfield_mask \u2013 a comma-separated list of which fields to include in the\nDocument AI response.\nsuggested: \u201ctext,pages.pageNumber,pages.layout\u201d\npage_range \u2013 list of page numbers to parse. If None,\nentire document will be parsed.\noperations_from_names(operation_names: List[str]) \u2192 List[Operation][source]\u00b6\nInitializes Long-Running Operations from their names.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents\nparse_from_results(results: List[DocAIParsingResults]) \u2192 Iterator[Document][source]\u00b6\nExamples using DocAIParser\u00b6\ndocai.md", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.docai.DocAIParser.html"}
{"id": "708814a4bd57-0", "text": "langchain.document_loaders.word_document.Docx2txtLoader\u00b6\nclass langchain.document_loaders.word_document.Docx2txtLoader(file_path: str)[source]\u00b6\nLoad DOCX file using docx2txt and chunks at character level.\nDefaults to check for local file, but if the file is a web path, it will download it\nto a temporary file, and use that, then clean up the temporary file after completion\nInitialize with file path.\nMethods\n__init__(file_path)\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad given path as single page.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str)[source]\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad given path as single page.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using Docx2txtLoader\u00b6\nMicrosoft Word", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.word_document.Docx2txtLoader.html"}
{"id": "b4b67ce2cdde-0", "text": "langchain.document_loaders.reddit.RedditPostsLoader\u00b6\nclass langchain.document_loaders.reddit.RedditPostsLoader(client_id: str, client_secret: str, user_agent: str, search_queries: Sequence[str], mode: str, categories: Sequence[str] = ['new'], number_posts: Optional[int] = 10)[source]\u00b6\nLoad Reddit posts.\nRead posts on a subreddit.\nFirst, you need to go to\nhttps://www.reddit.com/prefs/apps/\nand create your application\nInitialize with client_id, client_secret, user_agent, search_queries, mode,categories, number_posts.\nExample: https://www.reddit.com/r/learnpython/\nParameters\nclient_id \u2013 Reddit client id.\nclient_secret \u2013 Reddit client secret.\nuser_agent \u2013 Reddit user agent.\nsearch_queries \u2013 The search queries.\nmode \u2013 The mode.\ncategories \u2013 The categories. Default: [\u201cnew\u201d]\nnumber_posts \u2013 The number of posts. Default: 10\nMethods\n__init__(client_id,\u00a0client_secret,\u00a0...[,\u00a0...])\nInitialize with client_id, client_secret, user_agent, search_queries, mode,\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad reddits.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(client_id: str, client_secret: str, user_agent: str, search_queries: Sequence[str], mode: str, categories: Sequence[str] = ['new'], number_posts: Optional[int] = 10)[source]\u00b6\nInitialize with client_id, client_secret, user_agent, search_queries, mode,categories, number_posts.\nExample: https://www.reddit.com/r/learnpython/\nParameters\nclient_id \u2013 Reddit client id.\nclient_secret \u2013 Reddit client secret.\nuser_agent \u2013 Reddit user agent.\nsearch_queries \u2013 The search queries.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.reddit.RedditPostsLoader.html"}
{"id": "b4b67ce2cdde-1", "text": "user_agent \u2013 Reddit user agent.\nsearch_queries \u2013 The search queries.\nmode \u2013 The mode.\ncategories \u2013 The categories. Default: [\u201cnew\u201d]\nnumber_posts \u2013 The number of posts. Default: 10\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad reddits.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using RedditPostsLoader\u00b6\nReddit", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.reddit.RedditPostsLoader.html"}
{"id": "f6d7b5601415-0", "text": "langchain.document_loaders.hn.HNLoader\u00b6\nclass langchain.document_loaders.hn.HNLoader(web_path: Union[str, Sequence[str]] = '', header_template: Optional[dict] = None, verify_ssl: bool = True, proxies: Optional[dict] = None, continue_on_failure: bool = False, autoset_encoding: bool = True, encoding: Optional[str] = None, web_paths: Sequence[str] = (), requests_per_second: int = 2, default_parser: str = 'html.parser', requests_kwargs: Optional[Dict[str, Any]] = None, raise_for_status: bool = False, bs_get_text_kwargs: Optional[Dict[str, Any]] = None, bs_kwargs: Optional[Dict[str, Any]] = None, session: Any = None)[source]\u00b6\nLoad Hacker News data.\nIt loads data from either main page results or the comments page.\nInitialize loader.\nParameters\nweb_paths \u2013 Web paths to load from.\nrequests_per_second \u2013 Max number of concurrent requests to make.\ndefault_parser \u2013 Default parser to use for BeautifulSoup.\nrequests_kwargs \u2013 kwargs for requests\nraise_for_status \u2013 Raise an exception if http status code denotes an error.\nbs_get_text_kwargs \u2013 kwargs for beatifulsoup4 get_text\nbs_kwargs \u2013 kwargs for beatifulsoup4 web page parsing\nAttributes\nweb_path\nMethods\n__init__([web_path,\u00a0header_template,\u00a0...])\nInitialize loader.\naload()\nLoad text from the urls in web_path async into Documents.\nfetch_all(urls)\nFetch all urls concurrently with rate limiting.\nlazy_load()\nLazy load text from the url(s) in web_path.\nload()\nGet important HN webpage information.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nload_comments(soup_info)\nLoad comments from a HN post.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.hn.HNLoader.html"}
{"id": "f6d7b5601415-1", "text": "load_comments(soup_info)\nLoad comments from a HN post.\nload_results(soup)\nLoad items from an HN page.\nscrape([parser])\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls[,\u00a0parser])\nFetch all urls, then return soups for all results.\n__init__(web_path: Union[str, Sequence[str]] = '', header_template: Optional[dict] = None, verify_ssl: bool = True, proxies: Optional[dict] = None, continue_on_failure: bool = False, autoset_encoding: bool = True, encoding: Optional[str] = None, web_paths: Sequence[str] = (), requests_per_second: int = 2, default_parser: str = 'html.parser', requests_kwargs: Optional[Dict[str, Any]] = None, raise_for_status: bool = False, bs_get_text_kwargs: Optional[Dict[str, Any]] = None, bs_kwargs: Optional[Dict[str, Any]] = None, session: Any = None) \u2192 None\u00b6\nInitialize loader.\nParameters\nweb_paths \u2013 Web paths to load from.\nrequests_per_second \u2013 Max number of concurrent requests to make.\ndefault_parser \u2013 Default parser to use for BeautifulSoup.\nrequests_kwargs \u2013 kwargs for requests\nraise_for_status \u2013 Raise an exception if http status code denotes an error.\nbs_get_text_kwargs \u2013 kwargs for beatifulsoup4 get_text\nbs_kwargs \u2013 kwargs for beatifulsoup4 web page parsing\naload() \u2192 List[Document]\u00b6\nLoad text from the urls in web_path async into Documents.\nasync fetch_all(urls: List[str]) \u2192 Any\u00b6\nFetch all urls concurrently with rate limiting.\nlazy_load() \u2192 Iterator[Document]\u00b6\nLazy load text from the url(s) in web_path.\nload() \u2192 List[Document][source]\u00b6\nGet important HN webpage information.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.hn.HNLoader.html"}
{"id": "f6d7b5601415-2", "text": "load() \u2192 List[Document][source]\u00b6\nGet important HN webpage information.\nHN webpage components are:\ntitle\ncontent\nsource url,\ntime of post\nauthor of the post\nnumber of comments\nrank of the post\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nload_comments(soup_info: Any) \u2192 List[Document][source]\u00b6\nLoad comments from a HN post.\nload_results(soup: Any) \u2192 List[Document][source]\u00b6\nLoad items from an HN page.\nscrape(parser: Optional[str] = None) \u2192 Any\u00b6\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls: List[str], parser: Optional[str] = None) \u2192 List[Any]\u00b6\nFetch all urls, then return soups for all results.\nExamples using HNLoader\u00b6\nHacker News", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.hn.HNLoader.html"}
{"id": "fac9a1db6db8-0", "text": "langchain.document_loaders.figma.FigmaFileLoader\u00b6\nclass langchain.document_loaders.figma.FigmaFileLoader(access_token: str, ids: str, key: str)[source]\u00b6\nLoad Figma file.\nInitialize with access token, ids, and key.\nParameters\naccess_token \u2013 The access token for the Figma REST API.\nids \u2013 The ids of the Figma file.\nkey \u2013 The key for the Figma file\nMethods\n__init__(access_token,\u00a0ids,\u00a0key)\nInitialize with access token, ids, and key.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(access_token: str, ids: str, key: str)[source]\u00b6\nInitialize with access token, ids, and key.\nParameters\naccess_token \u2013 The access token for the Figma REST API.\nids \u2013 The ids of the Figma file.\nkey \u2013 The key for the Figma file\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad file\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using FigmaFileLoader\u00b6\nFigma", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.figma.FigmaFileLoader.html"}
{"id": "3593302afccc-0", "text": "langchain.document_loaders.embaas.EmbaasDocumentExtractionPayload\u00b6\nclass langchain.document_loaders.embaas.EmbaasDocumentExtractionPayload[source]\u00b6\nPayload for the Embaas document extraction API.\nAttributes\nbytes\nThe base64 encoded bytes of the document to extract text from.\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.EmbaasDocumentExtractionPayload.html"}
{"id": "3593302afccc-1", "text": "items() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.EmbaasDocumentExtractionPayload.html"}
{"id": "043c484aacf0-0", "text": "langchain.document_loaders.bibtex.BibtexLoader\u00b6\nclass langchain.document_loaders.bibtex.BibtexLoader(file_path: str, *, parser: Optional[BibtexparserWrapper] = None, max_docs: Optional[int] = None, max_content_chars: Optional[int] = 4000, load_extra_metadata: bool = False, file_pattern: str = '[^:]+\\\\.pdf')[source]\u00b6\nLoad a bibtex file.\nEach document represents one entry from the bibtex file.\nIf a PDF file is present in the file bibtex field, the original PDF\nis loaded into the document text. If no such file entry is present,\nthe abstract field is used instead.\nInitialize the BibtexLoader.\nParameters\nfile_path \u2013 Path to the bibtex file.\nparser \u2013 The parser to use. If None, a default parser is used.\nmax_docs \u2013 Max number of associated documents to load. Use -1 means\nno limit.\nmax_content_chars \u2013 Maximum number of characters to load from the PDF.\nload_extra_metadata \u2013 Whether to load extra metadata from the PDF.\nfile_pattern \u2013 Regex pattern to match the file name in the bibtex.\nMethods\n__init__(file_path,\u00a0*[,\u00a0parser,\u00a0max_docs,\u00a0...])\nInitialize the BibtexLoader.\nlazy_load()\nLoad bibtex file using bibtexparser and get the article texts plus the article metadata.\nload()\nLoad bibtex file documents from the given bibtex file path.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.bibtex.BibtexLoader.html"}
{"id": "043c484aacf0-1", "text": "load_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str, *, parser: Optional[BibtexparserWrapper] = None, max_docs: Optional[int] = None, max_content_chars: Optional[int] = 4000, load_extra_metadata: bool = False, file_pattern: str = '[^:]+\\\\.pdf')[source]\u00b6\nInitialize the BibtexLoader.\nParameters\nfile_path \u2013 Path to the bibtex file.\nparser \u2013 The parser to use. If None, a default parser is used.\nmax_docs \u2013 Max number of associated documents to load. Use -1 means\nno limit.\nmax_content_chars \u2013 Maximum number of characters to load from the PDF.\nload_extra_metadata \u2013 Whether to load extra metadata from the PDF.\nfile_pattern \u2013 Regex pattern to match the file name in the bibtex.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLoad bibtex file using bibtexparser and get the article texts plus the\narticle metadata.\nSee https://bibtexparser.readthedocs.io/en/master/\nReturns\na list of documents with the document.page_content in text format\nload() \u2192 List[Document][source]\u00b6\nLoad bibtex file documents from the given bibtex file path.\nSee https://bibtexparser.readthedocs.io/en/master/\nParameters\nfile_path \u2013 the path to the bibtex file\nReturns\na list of documents with the document.page_content in text format\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.bibtex.BibtexLoader.html"}
{"id": "043c484aacf0-2", "text": "Defaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using BibtexLoader\u00b6\nBibTeX", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.bibtex.BibtexLoader.html"}
{"id": "50dde75afd24-0", "text": "langchain.document_loaders.parsers.language.code_segmenter.CodeSegmenter\u00b6\nclass langchain.document_loaders.parsers.language.code_segmenter.CodeSegmenter(code: str)[source]\u00b6\nAbstract class for the code segmenter.\nMethods\n__init__(code)\nextract_functions_classes()\nis_valid()\nsimplify_code()\n__init__(code: str)[source]\u00b6\nabstract extract_functions_classes() \u2192 List[str][source]\u00b6\nis_valid() \u2192 bool[source]\u00b6\nabstract simplify_code() \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.language.code_segmenter.CodeSegmenter.html"}
{"id": "4ddc8d5c4603-0", "text": "langchain.document_loaders.email.OutlookMessageLoader\u00b6\nclass langchain.document_loaders.email.OutlookMessageLoader(file_path: str)[source]\u00b6\nLoads Outlook Message files using extract_msg.\nhttps://github.com/TeamMsgExtractor/msg-extractor\nInitialize with a file path.\nParameters\nfile_path \u2013 The path to the Outlook Message file.\nMethods\n__init__(file_path)\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str)[source]\u00b6\nInitialize with a file path.\nParameters\nfile_path \u2013 The path to the Outlook Message file.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using OutlookMessageLoader\u00b6\nEmail", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.email.OutlookMessageLoader.html"}
{"id": "e38bd75b8301-0", "text": "langchain.document_loaders.lakefs.UnstructuredLakeFSLoader\u00b6\nclass langchain.document_loaders.lakefs.UnstructuredLakeFSLoader(url: str, repo: str, ref: str = 'main', path: str = '', presign: bool = True, **unstructured_kwargs: Any)[source]\u00b6\nArgs:\nParameters\nlakefs_access_key \u2013 \nlakefs_secret_key \u2013 \nlakefs_endpoint \u2013 \nrepo \u2013 \nref \u2013 \nMethods\n__init__(url,\u00a0repo[,\u00a0ref,\u00a0path,\u00a0presign])\nArgs:\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(url: str, repo: str, ref: str = 'main', path: str = '', presign: bool = True, **unstructured_kwargs: Any)[source]\u00b6\nArgs:\nParameters\nlakefs_access_key \u2013 \nlakefs_secret_key \u2013 \nlakefs_endpoint \u2013 \nrepo \u2013 \nref \u2013 \nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.lakefs.UnstructuredLakeFSLoader.html"}
{"id": "07a92bd52b45-0", "text": "langchain.document_loaders.obsidian.ObsidianLoader\u00b6\nclass langchain.document_loaders.obsidian.ObsidianLoader(path: str, encoding: str = 'UTF-8', collect_metadata: bool = True)[source]\u00b6\nLoad Obsidian files from directory.\nInitialize with a path.\nParameters\npath \u2013 Path to the directory containing the Obsidian files.\nencoding \u2013 Charset encoding, defaults to \u201cUTF-8\u201d\ncollect_metadata \u2013 Whether to collect metadata from the front matter.\nDefaults to True.\nAttributes\nDATAVIEW_INLINE_BRACKET_REGEX\nDATAVIEW_INLINE_PAREN_REGEX\nDATAVIEW_LINE_REGEX\nFRONT_MATTER_REGEX\nTAG_REGEX\nMethods\n__init__(path[,\u00a0encoding,\u00a0collect_metadata])\nInitialize with a path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(path: str, encoding: str = 'UTF-8', collect_metadata: bool = True)[source]\u00b6\nInitialize with a path.\nParameters\npath \u2013 Path to the directory containing the Obsidian files.\nencoding \u2013 Charset encoding, defaults to \u201cUTF-8\u201d\ncollect_metadata \u2013 Whether to collect metadata from the front matter.\nDefaults to True.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using ObsidianLoader\u00b6\nObsidian", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.obsidian.ObsidianLoader.html"}
{"id": "bd93991eb6b1-0", "text": "langchain.document_loaders.fauna.FaunaLoader\u00b6\nclass langchain.document_loaders.fauna.FaunaLoader(query: str, page_content_field: str, secret: str, metadata_fields: Optional[Sequence[str]] = None)[source]\u00b6\nLoad from FaunaDB.\nquery\u00b6\nThe FQL query string to execute.\nType\nstr\npage_content_field\u00b6\nThe field that contains the content of each page.\nType\nstr\nsecret\u00b6\nThe secret key for authenticating to FaunaDB.\nType\nstr\nmetadata_fields\u00b6\nOptional list of field names to include in metadata.\nType\nOptional[Sequence[str]]\nMethods\n__init__(query,\u00a0page_content_field,\u00a0secret)\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(query: str, page_content_field: str, secret: str, metadata_fields: Optional[Sequence[str]] = None)[source]\u00b6\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using FaunaLoader\u00b6\nFauna", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.fauna.FaunaLoader.html"}
{"id": "e24993933c48-0", "text": "langchain.document_loaders.telegram.concatenate_rows\u00b6\nlangchain.document_loaders.telegram.concatenate_rows(row: dict) \u2192 str[source]\u00b6\nCombine message information in a readable format ready to be used.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.telegram.concatenate_rows.html"}
{"id": "6f904581bca0-0", "text": "langchain.document_loaders.srt.SRTLoader\u00b6\nclass langchain.document_loaders.srt.SRTLoader(file_path: str)[source]\u00b6\nLoad .srt (subtitle) files.\nInitialize with a file path.\nMethods\n__init__(file_path)\nInitialize with a file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad using pysrt file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(file_path: str)[source]\u00b6\nInitialize with a file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad using pysrt file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using SRTLoader\u00b6\nSubtitle", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.srt.SRTLoader.html"}
{"id": "037f3c3265d2-0", "text": "langchain.document_loaders.blockchain.BlockchainDocumentLoader\u00b6\nclass langchain.document_loaders.blockchain.BlockchainDocumentLoader(contract_address: str, blockchainType: BlockchainType = BlockchainType.ETH_MAINNET, api_key: str = 'docs-demo', startToken: str = '', get_all_tokens: bool = False, max_execution_time: Optional[int] = None)[source]\u00b6\nLoad elements from a blockchain smart contract.\nThe supported blockchains are: Ethereum mainnet, Ethereum Goerli testnet,\nPolygon mainnet, and Polygon Mumbai testnet.\nIf no BlockchainType is specified, the default is Ethereum mainnet.\nThe Loader uses the Alchemy API to interact with the blockchain.\nALCHEMY_API_KEY environment variable must be set to use this loader.\nThe API returns 100 NFTs per request and can be paginated using the\nstartToken parameter.\nIf get_all_tokens is set to True, the loader will get all tokens\non the contract.  Note that for contracts with a large number of tokens,\nthis may take a long time (e.g. 10k tokens is 100 requests).\nDefault value is false for this reason.\nThe max_execution_time (sec) can be set to limit the execution time\nof the loader.\nFuture versions of this loader can:\nSupport additional Alchemy APIs (e.g. getTransactions, etc.)\nSupport additional blockain APIs (e.g. Infura, Opensea, etc.)\nParameters\ncontract_address \u2013 The address of the smart contract.\nblockchainType \u2013 The blockchain type.\napi_key \u2013 The Alchemy API key.\nstartToken \u2013 The start token for pagination.\nget_all_tokens \u2013 Whether to get all tokens on the contract.\nmax_execution_time \u2013 The maximum execution time (sec).\nMethods\n__init__(contract_address[,\u00a0blockchainType,\u00a0...])\nparam contract_address", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blockchain.BlockchainDocumentLoader.html"}
{"id": "037f3c3265d2-1", "text": "__init__(contract_address[,\u00a0blockchainType,\u00a0...])\nparam contract_address\nThe address of the smart contract.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(contract_address: str, blockchainType: BlockchainType = BlockchainType.ETH_MAINNET, api_key: str = 'docs-demo', startToken: str = '', get_all_tokens: bool = False, max_execution_time: Optional[int] = None)[source]\u00b6\nParameters\ncontract_address \u2013 The address of the smart contract.\nblockchainType \u2013 The blockchain type.\napi_key \u2013 The Alchemy API key.\nstartToken \u2013 The start token for pagination.\nget_all_tokens \u2013 Whether to get all tokens on the contract.\nmax_execution_time \u2013 The maximum execution time (sec).\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using BlockchainDocumentLoader\u00b6\nBlockchain", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blockchain.BlockchainDocumentLoader.html"}
{"id": "445f22acc369-0", "text": "langchain.document_loaders.image_captions.ImageCaptionLoader\u00b6\nclass langchain.document_loaders.image_captions.ImageCaptionLoader(images: Union[str, bytes, List[Union[str, bytes]]], blip_processor: str = 'Salesforce/blip-image-captioning-base', blip_model: str = 'Salesforce/blip-image-captioning-base')[source]\u00b6\nLoad image captions.\nBy default, the loader utilizes the pre-trained\nSalesforce BLIP image captioning model.\nhttps://huggingface.co/Salesforce/blip-image-captioning-base\nInitialize with a list of image data (bytes) or file paths\nParameters\nimages \u2013 Either a single image or a list of images. Accepts\nimage data (bytes) or file paths to images.\nblip_processor \u2013 The name of the pre-trained BLIP processor.\nblip_model \u2013 The name of the pre-trained BLIP model.\nMethods\n__init__(images[,\u00a0blip_processor,\u00a0blip_model])\nInitialize with a list of image data (bytes) or file paths\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad from a list of image data or file paths\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(images: Union[str, bytes, List[Union[str, bytes]]], blip_processor: str = 'Salesforce/blip-image-captioning-base', blip_model: str = 'Salesforce/blip-image-captioning-base')[source]\u00b6\nInitialize with a list of image data (bytes) or file paths\nParameters\nimages \u2013 Either a single image or a list of images. Accepts\nimage data (bytes) or file paths to images.\nblip_processor \u2013 The name of the pre-trained BLIP processor.\nblip_model \u2013 The name of the pre-trained BLIP model.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.image_captions.ImageCaptionLoader.html"}
{"id": "445f22acc369-1", "text": "blip_model \u2013 The name of the pre-trained BLIP model.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad from a list of image data or file paths\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using ImageCaptionLoader\u00b6\nImage captions", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.image_captions.ImageCaptionLoader.html"}
{"id": "4c5910c251e9-0", "text": "langchain.document_loaders.browserless.BrowserlessLoader\u00b6\nclass langchain.document_loaders.browserless.BrowserlessLoader(api_token: str, urls: Union[str, List[str]], text_content: bool = True)[source]\u00b6\nLoad webpages with Browserless /content endpoint.\nInitialize with API token and the URLs to scrape\nAttributes\napi_token\nBrowserless API token.\nurls\nList of URLs to scrape.\nMethods\n__init__(api_token,\u00a0urls[,\u00a0text_content])\nInitialize with API token and the URLs to scrape\nlazy_load()\nLazy load Documents from URLs.\nload()\nLoad Documents from URLs.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(api_token: str, urls: Union[str, List[str]], text_content: bool = True)[source]\u00b6\nInitialize with API token and the URLs to scrape\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load Documents from URLs.\nload() \u2192 List[Document][source]\u00b6\nLoad Documents from URLs.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using BrowserlessLoader\u00b6\nBrowserless", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.browserless.BrowserlessLoader.html"}
{"id": "392eceed0fef-0", "text": "langchain.document_loaders.url.UnstructuredURLLoader\u00b6\nclass langchain.document_loaders.url.UnstructuredURLLoader(urls: List[str], continue_on_failure: bool = True, mode: str = 'single', show_progress_bar: bool = False, **unstructured_kwargs: Any)[source]\u00b6\nLoad files from remote URLs using Unstructured.\nUse the unstructured partition function to detect the MIME type\nand route the file to the appropriate partitioner.\nYou can run the loader in one of two modes: \u201csingle\u201d and \u201celements\u201d.\nIf you use \u201csingle\u201d mode, the document will be returned as a single\nlangchain Document object. If you use \u201celements\u201d mode, the unstructured\nlibrary will split the document into elements such as Title and NarrativeText.\nYou can pass in additional unstructured kwargs after mode to apply\ndifferent unstructured settings.\nExamples\nfrom langchain.document_loaders import UnstructuredURLLoader\nloader = UnstructuredURLLoader(urls=[\u201c<url-1>\u201d, \u201c<url-2>\u201d], mode=\u201delements\u201d, strategy=\u201dfast\u201d,\n)\ndocs = loader.load()\nReferences\nhttps://unstructured-io.github.io/unstructured/bricks.html#partition\nInitialize with file path.\nMethods\n__init__(urls[,\u00a0continue_on_failure,\u00a0mode,\u00a0...])\nInitialize with file path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad file.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(urls: List[str], continue_on_failure: bool = True, mode: str = 'single', show_progress_bar: bool = False, **unstructured_kwargs: Any)[source]\u00b6\nInitialize with file path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad file.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.url.UnstructuredURLLoader.html"}
{"id": "392eceed0fef-1", "text": "load() \u2192 List[Document][source]\u00b6\nLoad file.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using UnstructuredURLLoader\u00b6\nURL", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.url.UnstructuredURLLoader.html"}
{"id": "bb300dffbc11-0", "text": "langchain.document_loaders.url_selenium.SeleniumURLLoader\u00b6\nclass langchain.document_loaders.url_selenium.SeleniumURLLoader(urls: List[str], continue_on_failure: bool = True, browser: Literal['chrome', 'firefox'] = 'chrome', binary_location: Optional[str] = None, executable_path: Optional[str] = None, headless: bool = True, arguments: List[str] = [])[source]\u00b6\nLoad HTML pages with Selenium and parse with Unstructured.\nThis is useful for loading pages that require javascript to render.\nurls\u00b6\nList of URLs to load.\nType\nList[str]\ncontinue_on_failure\u00b6\nIf True, continue loading other URLs on failure.\nType\nbool\nbrowser\u00b6\nThe browser to use, either \u2018chrome\u2019 or \u2018firefox\u2019.\nType\nstr\nbinary_location\u00b6\nThe location of the browser binary.\nType\nOptional[str]\nexecutable_path\u00b6\nThe path to the browser executable.\nType\nOptional[str]\nheadless\u00b6\nIf True, the browser will run in headless mode.\nType\nbool\narguments [List[str]]\nList of arguments to pass to the browser.\nLoad a list of URLs using Selenium and unstructured.\nMethods\n__init__(urls[,\u00a0continue_on_failure,\u00a0...])\nLoad a list of URLs using Selenium and unstructured.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad the specified URLs using Selenium and create Document instances.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(urls: List[str], continue_on_failure: bool = True, browser: Literal['chrome', 'firefox'] = 'chrome', binary_location: Optional[str] = None, executable_path: Optional[str] = None, headless: bool = True, arguments: List[str] = [])[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.url_selenium.SeleniumURLLoader.html"}
{"id": "bb300dffbc11-1", "text": "Load a list of URLs using Selenium and unstructured.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad the specified URLs using Selenium and create Document instances.\nReturns\nA list of Document instances with loaded content.\nReturn type\nList[Document]\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using SeleniumURLLoader\u00b6\nURL", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.url_selenium.SeleniumURLLoader.html"}
{"id": "ba8bd9f78c84-0", "text": "langchain.document_loaders.parsers.language.javascript.JavaScriptSegmenter\u00b6\nclass langchain.document_loaders.parsers.language.javascript.JavaScriptSegmenter(code: str)[source]\u00b6\nCode segmenter for JavaScript.\nMethods\n__init__(code)\nextract_functions_classes()\nis_valid()\nsimplify_code()\n__init__(code: str)[source]\u00b6\nextract_functions_classes() \u2192 List[str][source]\u00b6\nis_valid() \u2192 bool[source]\u00b6\nsimplify_code() \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.language.javascript.JavaScriptSegmenter.html"}
{"id": "9c9c15754a3b-0", "text": "langchain.document_loaders.mastodon.MastodonTootsLoader\u00b6\nclass langchain.document_loaders.mastodon.MastodonTootsLoader(mastodon_accounts: Sequence[str], number_toots: Optional[int] = 100, exclude_replies: bool = False, access_token: Optional[str] = None, api_base_url: str = 'https://mastodon.social')[source]\u00b6\nLoad the Mastodon \u2018toots\u2019.\nInstantiate Mastodon toots loader.\nParameters\nmastodon_accounts \u2013 The list of Mastodon accounts to query.\nnumber_toots \u2013 How many toots to pull for each account. Defaults to 100.\nexclude_replies \u2013 Whether to exclude reply toots from the load.\nDefaults to False.\naccess_token \u2013 An access token if toots are loaded as a Mastodon app. Can\nalso be specified via the environment variables \u201cMASTODON_ACCESS_TOKEN\u201d.\napi_base_url \u2013 A Mastodon API base URL to talk to, if not using the default.\nDefaults to \u201chttps://mastodon.social\u201d.\nMethods\n__init__(mastodon_accounts[,\u00a0number_toots,\u00a0...])\nInstantiate Mastodon toots loader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad toots into documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(mastodon_accounts: Sequence[str], number_toots: Optional[int] = 100, exclude_replies: bool = False, access_token: Optional[str] = None, api_base_url: str = 'https://mastodon.social')[source]\u00b6\nInstantiate Mastodon toots loader.\nParameters\nmastodon_accounts \u2013 The list of Mastodon accounts to query.\nnumber_toots \u2013 How many toots to pull for each account. Defaults to 100.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.mastodon.MastodonTootsLoader.html"}
{"id": "9c9c15754a3b-1", "text": "exclude_replies \u2013 Whether to exclude reply toots from the load.\nDefaults to False.\naccess_token \u2013 An access token if toots are loaded as a Mastodon app. Can\nalso be specified via the environment variables \u201cMASTODON_ACCESS_TOKEN\u201d.\napi_base_url \u2013 A Mastodon API base URL to talk to, if not using the default.\nDefaults to \u201chttps://mastodon.social\u201d.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad toots into documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using MastodonTootsLoader\u00b6\nMastodon", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.mastodon.MastodonTootsLoader.html"}
{"id": "f71bd88d25ab-0", "text": "langchain.document_loaders.rspace.RSpaceLoader\u00b6\nclass langchain.document_loaders.rspace.RSpaceLoader(global_id: str, api_key: Optional[str] = None, url: Optional[str] = None)[source]\u00b6\nLoads  content from RSpace notebooks, folders, documents or PDF Gallery files into\nLangchain documents.\nMaps  RSpace document <-> Langchain Document in 1-1. PDFs are imported using PyPDF.\nRequirements are rspace_client (pip install rspace_client) and PyPDF if importingPDF docs (pip install pypdf).\napi_key: RSpace API key - can also be supplied as environment variable\n\u2018RSPACE_API_KEY\u2019\nurl: str\nThe URL of your RSpace instance - can also be supplied as environment\nvariable \u2018RSPACE_URL\u2019\nglobal_id: str\nThe global ID of the resource to load,\ne.g. \u2018SD12344\u2019 (a single document); \u2018GL12345\u2019(A PDF file in the gallery);\n\u2018NB4567\u2019 (a notebook); \u2018FL12244\u2019 (a folder)\nMethods\n__init__(global_id[,\u00a0api_key,\u00a0url])\napi_key: RSpace API key - can also be supplied as environment variable 'RSPACE_API_KEY' url: str The URL of your RSpace instance - can also be supplied as environment variable 'RSPACE_URL' global_id: str  The global ID of the resource to load, e.g. 'SD12344' (a single document); 'GL12345'(A PDF file in the gallery); 'NB4567' (a notebook); 'FL12244' (a folder).\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nvalidate_environment(values)", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.rspace.RSpaceLoader.html"}
{"id": "f71bd88d25ab-1", "text": "Load Documents and split into chunks.\nvalidate_environment(values)\nValidate that API key and URL exists in environment.\n__init__(global_id: str, api_key: Optional[str] = None, url: Optional[str] = None)[source]\u00b6\napi_key: RSpace API key - can also be supplied as environment variable\n\u2018RSPACE_API_KEY\u2019\nurl: str\nThe URL of your RSpace instance - can also be supplied as environment\nvariable \u2018RSPACE_URL\u2019\nglobal_id: str\nThe global ID of the resource to load,\ne.g. \u2018SD12344\u2019 (a single document); \u2018GL12345\u2019(A PDF file in the gallery);\n\u2018NB4567\u2019 (a notebook); \u2018FL12244\u2019 (a folder)\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nclassmethod validate_environment(values: Dict) \u2192 Dict[source]\u00b6\nValidate that API key and URL exists in environment.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.rspace.RSpaceLoader.html"}
{"id": "390c2a93a239-0", "text": "langchain.document_loaders.chatgpt.concatenate_rows\u00b6\nlangchain.document_loaders.chatgpt.concatenate_rows(message: dict, title: str) \u2192 str[source]\u00b6\nCombine message information in a readable format ready to be used.\n:param message: Message to be concatenated\n:param title: Title of the conversation\nReturns\nConcatenated message", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.chatgpt.concatenate_rows.html"}
{"id": "64dabe809a7d-0", "text": "langchain.document_loaders.parsers.grobid.GrobidParser\u00b6\nclass langchain.document_loaders.parsers.grobid.GrobidParser(segment_sentences: bool, grobid_server: str = 'http://localhost:8070/api/processFulltextDocument')[source]\u00b6\nLoad  article PDF files using Grobid.\nMethods\n__init__(segment_sentences[,\u00a0grobid_server])\nlazy_parse(blob)\nLazy parsing interface.\nparse(blob)\nEagerly parse the blob into a document or documents.\nprocess_xml(file_path,\u00a0xml_data,\u00a0...)\nProcess the XML file from Grobin.\n__init__(segment_sentences: bool, grobid_server: str = 'http://localhost:8070/api/processFulltextDocument') \u2192 None[source]\u00b6\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLazy parsing interface.\nSubclasses are required to implement this method.\nParameters\nblob \u2013 Blob instance\nReturns\nGenerator of documents\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents\nprocess_xml(file_path: str, xml_data: str, segment_sentences: bool) \u2192 Iterator[Document][source]\u00b6\nProcess the XML file from Grobin.\nExamples using GrobidParser\u00b6\nGrobid", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.grobid.GrobidParser.html"}
{"id": "0703b99a37c1-0", "text": "langchain.document_loaders.azlyrics.AZLyricsLoader\u00b6\nclass langchain.document_loaders.azlyrics.AZLyricsLoader(web_path: Union[str, Sequence[str]] = '', header_template: Optional[dict] = None, verify_ssl: bool = True, proxies: Optional[dict] = None, continue_on_failure: bool = False, autoset_encoding: bool = True, encoding: Optional[str] = None, web_paths: Sequence[str] = (), requests_per_second: int = 2, default_parser: str = 'html.parser', requests_kwargs: Optional[Dict[str, Any]] = None, raise_for_status: bool = False, bs_get_text_kwargs: Optional[Dict[str, Any]] = None, bs_kwargs: Optional[Dict[str, Any]] = None, session: Any = None)[source]\u00b6\nLoad AZLyrics webpages.\nInitialize loader.\nParameters\nweb_paths \u2013 Web paths to load from.\nrequests_per_second \u2013 Max number of concurrent requests to make.\ndefault_parser \u2013 Default parser to use for BeautifulSoup.\nrequests_kwargs \u2013 kwargs for requests\nraise_for_status \u2013 Raise an exception if http status code denotes an error.\nbs_get_text_kwargs \u2013 kwargs for beatifulsoup4 get_text\nbs_kwargs \u2013 kwargs for beatifulsoup4 web page parsing\nAttributes\nweb_path\nMethods\n__init__([web_path,\u00a0header_template,\u00a0...])\nInitialize loader.\naload()\nLoad text from the urls in web_path async into Documents.\nfetch_all(urls)\nFetch all urls concurrently with rate limiting.\nlazy_load()\nLazy load text from the url(s) in web_path.\nload()\nLoad webpages into Documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nscrape([parser])\nScrape data from webpage and return it in BeautifulSoup format.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.azlyrics.AZLyricsLoader.html"}
{"id": "0703b99a37c1-1", "text": "scrape([parser])\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls[,\u00a0parser])\nFetch all urls, then return soups for all results.\n__init__(web_path: Union[str, Sequence[str]] = '', header_template: Optional[dict] = None, verify_ssl: bool = True, proxies: Optional[dict] = None, continue_on_failure: bool = False, autoset_encoding: bool = True, encoding: Optional[str] = None, web_paths: Sequence[str] = (), requests_per_second: int = 2, default_parser: str = 'html.parser', requests_kwargs: Optional[Dict[str, Any]] = None, raise_for_status: bool = False, bs_get_text_kwargs: Optional[Dict[str, Any]] = None, bs_kwargs: Optional[Dict[str, Any]] = None, session: Any = None) \u2192 None\u00b6\nInitialize loader.\nParameters\nweb_paths \u2013 Web paths to load from.\nrequests_per_second \u2013 Max number of concurrent requests to make.\ndefault_parser \u2013 Default parser to use for BeautifulSoup.\nrequests_kwargs \u2013 kwargs for requests\nraise_for_status \u2013 Raise an exception if http status code denotes an error.\nbs_get_text_kwargs \u2013 kwargs for beatifulsoup4 get_text\nbs_kwargs \u2013 kwargs for beatifulsoup4 web page parsing\naload() \u2192 List[Document]\u00b6\nLoad text from the urls in web_path async into Documents.\nasync fetch_all(urls: List[str]) \u2192 Any\u00b6\nFetch all urls concurrently with rate limiting.\nlazy_load() \u2192 Iterator[Document]\u00b6\nLazy load text from the url(s) in web_path.\nload() \u2192 List[Document][source]\u00b6\nLoad webpages into Documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.azlyrics.AZLyricsLoader.html"}
{"id": "0703b99a37c1-2", "text": "Load Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nscrape(parser: Optional[str] = None) \u2192 Any\u00b6\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls: List[str], parser: Optional[str] = None) \u2192 List[Any]\u00b6\nFetch all urls, then return soups for all results.\nExamples using AZLyricsLoader\u00b6\nAZLyrics", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.azlyrics.AZLyricsLoader.html"}
{"id": "5ea9bfc6a6bb-0", "text": "langchain.document_loaders.parsers.language.python.PythonSegmenter\u00b6\nclass langchain.document_loaders.parsers.language.python.PythonSegmenter(code: str)[source]\u00b6\nCode segmenter for Python.\nMethods\n__init__(code)\nextract_functions_classes()\nis_valid()\nsimplify_code()\n__init__(code: str)[source]\u00b6\nextract_functions_classes() \u2192 List[str][source]\u00b6\nis_valid() \u2192 bool[source]\u00b6\nsimplify_code() \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.language.python.PythonSegmenter.html"}
{"id": "5c3474a4c2e1-0", "text": "langchain.document_loaders.facebook_chat.FacebookChatLoader\u00b6\nclass langchain.document_loaders.facebook_chat.FacebookChatLoader(path: str)[source]\u00b6\nLoad Facebook Chat messages directory dump.\nInitialize with a path.\nMethods\n__init__(path)\nInitialize with a path.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(path: str)[source]\u00b6\nInitialize with a path.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using FacebookChatLoader\u00b6\nFacebook Chat", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.facebook_chat.FacebookChatLoader.html"}
{"id": "057d5d0681ac-0", "text": "langchain.document_loaders.parsers.generic.MimeTypeBasedParser\u00b6\nclass langchain.document_loaders.parsers.generic.MimeTypeBasedParser(handlers: Mapping[str, BaseBlobParser], *, fallback_parser: Optional[BaseBlobParser] = None)[source]\u00b6\nParser that uses mime-types to parse a blob.\nThis parser is useful for simple pipelines where the mime-type is sufficient\nto determine how to parse a blob.\nTo use, configure handlers based on mime-types and pass them to the initializer.\nExample\nfrom langchain.document_loaders.parsers.generic import MimeTypeBasedParser\nparser = MimeTypeBasedParser(\nhandlers={\u201capplication/pdf\u201d: \u2026,\n},\nfallback_parser=\u2026,\n)\nDefine a parser that uses mime-types to determine how to parse a blob.\nParameters\nhandlers \u2013 A mapping from mime-types to functions that take a blob, parse it\nand return a document.\nfallback_parser \u2013 A fallback_parser parser to use if the mime-type is not\nfound in the handlers. If provided, this parser will be\nused to parse blobs with all mime-types not found in\nthe handlers.\nIf not provided, a ValueError will be raised if the\nmime-type is not found in the handlers.\nMethods\n__init__(handlers,\u00a0*[,\u00a0fallback_parser])\nDefine a parser that uses mime-types to determine how to parse a blob.\nlazy_parse(blob)\nLoad documents from a blob.\nparse(blob)\nEagerly parse the blob into a document or documents.\n__init__(handlers: Mapping[str, BaseBlobParser], *, fallback_parser: Optional[BaseBlobParser] = None) \u2192 None[source]\u00b6\nDefine a parser that uses mime-types to determine how to parse a blob.\nParameters\nhandlers \u2013 A mapping from mime-types to functions that take a blob, parse it\nand return a document.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.generic.MimeTypeBasedParser.html"}
{"id": "057d5d0681ac-1", "text": "and return a document.\nfallback_parser \u2013 A fallback_parser parser to use if the mime-type is not\nfound in the handlers. If provided, this parser will be\nused to parse blobs with all mime-types not found in\nthe handlers.\nIf not provided, a ValueError will be raised if the\nmime-type is not found in the handlers.\nlazy_parse(blob: Blob) \u2192 Iterator[Document][source]\u00b6\nLoad documents from a blob.\nparse(blob: Blob) \u2192 List[Document]\u00b6\nEagerly parse the blob into a document or documents.\nThis is a convenience method for interactive development environment.\nProduction applications should favor the lazy_parse method instead.\nSubclasses should generally not over-ride this parse method.\nParameters\nblob \u2013 Blob instance\nReturns\nList of documents", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.parsers.generic.MimeTypeBasedParser.html"}
{"id": "5bfd5cddb292-0", "text": "langchain.document_loaders.helpers.detect_file_encodings\u00b6\nlangchain.document_loaders.helpers.detect_file_encodings(file_path: str, timeout: int = 5) \u2192 List[FileEncoding][source]\u00b6\nTry to detect the file encoding.\nReturns a list of FileEncoding tuples with the detected encodings ordered\nby confidence.\nParameters\nfile_path \u2013 The path to the file to detect the encoding for.\ntimeout \u2013 The timeout in seconds for the encoding detection.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.helpers.detect_file_encodings.html"}
{"id": "faf12e42e0cd-0", "text": "langchain.document_loaders.youtube.YoutubeLoader\u00b6\nclass langchain.document_loaders.youtube.YoutubeLoader(video_id: str, add_video_info: bool = False, language: Union[str, Sequence[str]] = 'en', translation: str = 'en', continue_on_failure: bool = False)[source]\u00b6\nLoad YouTube transcripts.\nInitialize with YouTube video ID.\nMethods\n__init__(video_id[,\u00a0add_video_info,\u00a0...])\nInitialize with YouTube video ID.\nextract_video_id(youtube_url)\nExtract video id from common YT urls.\nfrom_youtube_url(youtube_url,\u00a0**kwargs)\nGiven youtube URL, load video.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad documents.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(video_id: str, add_video_info: bool = False, language: Union[str, Sequence[str]] = 'en', translation: str = 'en', continue_on_failure: bool = False)[source]\u00b6\nInitialize with YouTube video ID.\nstatic extract_video_id(youtube_url: str) \u2192 str[source]\u00b6\nExtract video id from common YT urls.\nclassmethod from_youtube_url(youtube_url: str, **kwargs: Any) \u2192 YoutubeLoader[source]\u00b6\nGiven youtube URL, load video.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using YoutubeLoader\u00b6\nYouTube\nYouTube transcripts", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.youtube.YoutubeLoader.html"}
{"id": "0d15db966493-0", "text": "langchain.document_loaders.bigquery.BigQueryLoader\u00b6\nclass langchain.document_loaders.bigquery.BigQueryLoader(query: str, project: Optional[str] = None, page_content_columns: Optional[List[str]] = None, metadata_columns: Optional[List[str]] = None, credentials: Optional[Credentials] = None)[source]\u00b6\nLoad from the Google Cloud Platform BigQuery.\nEach document represents one row of the result. The page_content_columns\nare written into the page_content of the document. The metadata_columns\nare written into the metadata of the document. By default, all columns\nare written into the page_content and none into the metadata.\nInitialize BigQuery document loader.\nParameters\nquery \u2013 The query to run in BigQuery.\nproject \u2013 Optional. The project to run the query in.\npage_content_columns \u2013 Optional. The columns to write into the page_content\nof the document.\nmetadata_columns \u2013 Optional. The columns to write into the metadata of the\ndocument.\ncredentials \u2013 google.auth.credentials.Credentials, optional\nCredentials for accessing Google APIs. Use this parameter to override\ndefault credentials, such as to use Compute Engine\n(google.auth.compute_engine.Credentials) or Service Account\n(google.oauth2.service_account.Credentials) credentials directly.\nMethods\n__init__(query[,\u00a0project,\u00a0...])\nInitialize BigQuery document loader.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(query: str, project: Optional[str] = None, page_content_columns: Optional[List[str]] = None, metadata_columns: Optional[List[str]] = None, credentials: Optional[Credentials] = None)[source]\u00b6\nInitialize BigQuery document loader.\nParameters\nquery \u2013 The query to run in BigQuery.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.bigquery.BigQueryLoader.html"}
{"id": "0d15db966493-1", "text": "Initialize BigQuery document loader.\nParameters\nquery \u2013 The query to run in BigQuery.\nproject \u2013 Optional. The project to run the query in.\npage_content_columns \u2013 Optional. The columns to write into the page_content\nof the document.\nmetadata_columns \u2013 Optional. The columns to write into the metadata of the\ndocument.\ncredentials \u2013 google.auth.credentials.Credentials, optional\nCredentials for accessing Google APIs. Use this parameter to override\ndefault credentials, such as to use Compute Engine\n(google.auth.compute_engine.Credentials) or Service Account\n(google.oauth2.service_account.Credentials) credentials directly.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using BigQueryLoader\u00b6\nGoogle BigQuery", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.bigquery.BigQueryLoader.html"}
{"id": "b98fb03f41a2-0", "text": "langchain.document_loaders.polars_dataframe.PolarsDataFrameLoader\u00b6\nclass langchain.document_loaders.polars_dataframe.PolarsDataFrameLoader(data_frame: Any, *, page_content_column: str = 'text')[source]\u00b6\nLoad Polars DataFrame.\nInitialize with dataframe object.\nParameters\ndata_frame \u2013 Polars DataFrame object.\npage_content_column \u2013 Name of the column containing the page content.\nDefaults to \u201ctext\u201d.\nMethods\n__init__(data_frame,\u00a0*[,\u00a0page_content_column])\nInitialize with dataframe object.\nlazy_load()\nLazy load records from dataframe.\nload()\nLoad full dataframe.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(data_frame: Any, *, page_content_column: str = 'text')[source]\u00b6\nInitialize with dataframe object.\nParameters\ndata_frame \u2013 Polars DataFrame object.\npage_content_column \u2013 Name of the column containing the page content.\nDefaults to \u201ctext\u201d.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load records from dataframe.\nload() \u2192 List[Document]\u00b6\nLoad full dataframe.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using PolarsDataFrameLoader\u00b6\nPolars DataFrame", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.polars_dataframe.PolarsDataFrameLoader.html"}
{"id": "4d8379190c3f-0", "text": "langchain.document_loaders.diffbot.DiffbotLoader\u00b6\nclass langchain.document_loaders.diffbot.DiffbotLoader(api_token: str, urls: List[str], continue_on_failure: bool = True)[source]\u00b6\nLoad Diffbot json file.\nInitialize with API token, ids, and key.\nParameters\napi_token \u2013 Diffbot API token.\nurls \u2013 List of URLs to load.\ncontinue_on_failure \u2013 Whether to continue loading other URLs if one fails.\nDefaults to True.\nMethods\n__init__(api_token,\u00a0urls[,\u00a0continue_on_failure])\nInitialize with API token, ids, and key.\nlazy_load()\nA lazy loader for Documents.\nload()\nExtract text from Diffbot on all the URLs and return Documents\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(api_token: str, urls: List[str], continue_on_failure: bool = True)[source]\u00b6\nInitialize with API token, ids, and key.\nParameters\napi_token \u2013 Diffbot API token.\nurls \u2013 List of URLs to load.\ncontinue_on_failure \u2013 Whether to continue loading other URLs if one fails.\nDefaults to True.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nExtract text from Diffbot on all the URLs and return Documents\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using DiffbotLoader\u00b6\nDiffbot", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.diffbot.DiffbotLoader.html"}
{"id": "3f3431220501-0", "text": "langchain.document_loaders.async_html.AsyncHtmlLoader\u00b6\nclass langchain.document_loaders.async_html.AsyncHtmlLoader(web_path: Union[str, List[str]], header_template: Optional[dict] = None, verify_ssl: Optional[bool] = True, proxies: Optional[dict] = None, autoset_encoding: bool = True, encoding: Optional[str] = None, default_parser: str = 'html.parser', requests_per_second: int = 2, requests_kwargs: Optional[Dict[str, Any]] = None, raise_for_status: bool = False, ignore_load_errors: bool = False)[source]\u00b6\nLoad HTML asynchronously.\nInitialize with a webpage path.\nMethods\n__init__(web_path[,\u00a0header_template,\u00a0...])\nInitialize with a webpage path.\nfetch_all(urls)\nFetch all urls concurrently with rate limiting.\nlazy_load()\nLazy load text from the url(s) in web_path.\nload()\nLoad text from the url(s) in web_path.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(web_path: Union[str, List[str]], header_template: Optional[dict] = None, verify_ssl: Optional[bool] = True, proxies: Optional[dict] = None, autoset_encoding: bool = True, encoding: Optional[str] = None, default_parser: str = 'html.parser', requests_per_second: int = 2, requests_kwargs: Optional[Dict[str, Any]] = None, raise_for_status: bool = False, ignore_load_errors: bool = False)[source]\u00b6\nInitialize with a webpage path.\nasync fetch_all(urls: List[str]) \u2192 Any[source]\u00b6\nFetch all urls concurrently with rate limiting.\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLazy load text from the url(s) in web_path.\nload() \u2192 List[Document][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.async_html.AsyncHtmlLoader.html"}
{"id": "3f3431220501-1", "text": "load() \u2192 List[Document][source]\u00b6\nLoad text from the url(s) in web_path.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using AsyncHtmlLoader\u00b6\nhtml2text\nAsyncHtmlLoader\nSet env var OPENAI_API_KEY or load from a .env file:", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.async_html.AsyncHtmlLoader.html"}
{"id": "1815d4498c1e-0", "text": "langchain.document_loaders.assemblyai.TranscriptFormat\u00b6\nclass langchain.document_loaders.assemblyai.TranscriptFormat(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nTranscript format to use for the document loader.\nTEXT = 'text'\u00b6\nOne document with the transcription text\nSENTENCES = 'sentences'\u00b6\nMultiple documents, splits the transcription by each sentence\nPARAGRAPHS = 'paragraphs'\u00b6\nMultiple documents, splits the transcription by each paragraph\nSUBTITLES_SRT = 'subtitles_srt'\u00b6\nOne document with the transcript exported in SRT subtitles format\nSUBTITLES_VTT = 'subtitles_vtt'\u00b6\nOne document with the transcript exported in VTT subtitles format\nExamples using TranscriptFormat\u00b6\nAssemblyAI Audio Transcripts", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.assemblyai.TranscriptFormat.html"}
{"id": "3728042394e3-0", "text": "langchain.document_loaders.duckdb_loader.DuckDBLoader\u00b6\nclass langchain.document_loaders.duckdb_loader.DuckDBLoader(query: str, database: str = ':memory:', read_only: bool = False, config: Optional[Dict[str, str]] = None, page_content_columns: Optional[List[str]] = None, metadata_columns: Optional[List[str]] = None)[source]\u00b6\nLoad from DuckDB.\nEach document represents one row of the result. The page_content_columns\nare written into the page_content of the document. The metadata_columns\nare written into the metadata of the document. By default, all columns\nare written into the page_content and none into the metadata.\nParameters\nquery \u2013 The query to execute.\ndatabase \u2013 The database to connect to. Defaults to \u201c:memory:\u201d.\nread_only \u2013 Whether to open the database in read-only mode.\nDefaults to False.\nconfig \u2013 A dictionary of configuration options to pass to the database.\nOptional.\npage_content_columns \u2013 The columns to write into the page_content\nof the document. Optional.\nmetadata_columns \u2013 The columns to write into the metadata of the document.\nOptional.\nMethods\n__init__(query[,\u00a0database,\u00a0read_only,\u00a0...])\nparam query\nThe query to execute.\nlazy_load()\nA lazy loader for Documents.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\n__init__(query: str, database: str = ':memory:', read_only: bool = False, config: Optional[Dict[str, str]] = None, page_content_columns: Optional[List[str]] = None, metadata_columns: Optional[List[str]] = None)[source]\u00b6\nParameters\nquery \u2013 The query to execute.\ndatabase \u2013 The database to connect to. Defaults to \u201c:memory:\u201d.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.duckdb_loader.DuckDBLoader.html"}
{"id": "3728042394e3-1", "text": "database \u2013 The database to connect to. Defaults to \u201c:memory:\u201d.\nread_only \u2013 Whether to open the database in read-only mode.\nDefaults to False.\nconfig \u2013 A dictionary of configuration options to pass to the database.\nOptional.\npage_content_columns \u2013 The columns to write into the page_content\nof the document. Optional.\nmetadata_columns \u2013 The columns to write into the metadata of the document.\nOptional.\nlazy_load() \u2192 Iterator[Document]\u00b6\nA lazy loader for Documents.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nExamples using DuckDBLoader\u00b6\nDuckDB", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.duckdb_loader.DuckDBLoader.html"}
{"id": "53f68f772bc0-0", "text": "langchain.document_loaders.blackboard.BlackboardLoader\u00b6\nclass langchain.document_loaders.blackboard.BlackboardLoader(blackboard_course_url: str, bbrouter: str, load_all_recursively: bool = True, basic_auth: Optional[Tuple[str, str]] = None, cookies: Optional[dict] = None, continue_on_failure: bool = False)[source]\u00b6\nLoad a Blackboard course.\nThis loader is not compatible with all Blackboard courses. It is only\ncompatible with courses that use the new Blackboard interface.\nTo use this loader, you must have the BbRouter cookie. You can get this\ncookie by logging into the course and then copying the value of the\nBbRouter cookie from the browser\u2019s developer tools.\nExample\nfrom langchain.document_loaders import BlackboardLoader\nloader = BlackboardLoader(\n    blackboard_course_url=\"https://blackboard.example.com/webapps/blackboard/execute/announcement?method=search&context=course_entry&course_id=_123456_1\",\n    bbrouter=\"expires:12345...\",\n)\ndocuments = loader.load()\nInitialize with blackboard course url.\nThe BbRouter cookie is required for most blackboard courses.\nParameters\nblackboard_course_url \u2013 Blackboard course url.\nbbrouter \u2013 BbRouter cookie.\nload_all_recursively \u2013 If True, load all documents recursively.\nbasic_auth \u2013 Basic auth credentials.\ncookies \u2013 Cookies.\ncontinue_on_failure \u2013 whether to continue loading the sitemap if an error\noccurs loading a url, emitting a warning instead of raising an\nexception. Setting this to True makes the loader more robust, but also\nmay result in missing data. Default: False\nRaises\nValueError \u2013 If blackboard course url is invalid.\nAttributes\nweb_path\nMethods\n__init__(blackboard_course_url,\u00a0bbrouter[,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blackboard.BlackboardLoader.html"}
{"id": "53f68f772bc0-1", "text": "Methods\n__init__(blackboard_course_url,\u00a0bbrouter[,\u00a0...])\nInitialize with blackboard course url.\naload()\nLoad text from the urls in web_path async into Documents.\ncheck_bs4()\nCheck if BeautifulSoup4 is installed.\ndownload(path)\nDownload a file from an url.\nfetch_all(urls)\nFetch all urls concurrently with rate limiting.\nlazy_load()\nLazy load text from the url(s) in web_path.\nload()\nLoad data into Document objects.\nload_and_split([text_splitter])\nLoad Documents and split into chunks.\nparse_filename(url)\nParse the filename from an url.\nscrape([parser])\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls[,\u00a0parser])\nFetch all urls, then return soups for all results.\n__init__(blackboard_course_url: str, bbrouter: str, load_all_recursively: bool = True, basic_auth: Optional[Tuple[str, str]] = None, cookies: Optional[dict] = None, continue_on_failure: bool = False)[source]\u00b6\nInitialize with blackboard course url.\nThe BbRouter cookie is required for most blackboard courses.\nParameters\nblackboard_course_url \u2013 Blackboard course url.\nbbrouter \u2013 BbRouter cookie.\nload_all_recursively \u2013 If True, load all documents recursively.\nbasic_auth \u2013 Basic auth credentials.\ncookies \u2013 Cookies.\ncontinue_on_failure \u2013 whether to continue loading the sitemap if an error\noccurs loading a url, emitting a warning instead of raising an\nexception. Setting this to True makes the loader more robust, but also\nmay result in missing data. Default: False\nRaises\nValueError \u2013 If blackboard course url is invalid.\naload() \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blackboard.BlackboardLoader.html"}
{"id": "53f68f772bc0-2", "text": "aload() \u2192 List[Document]\u00b6\nLoad text from the urls in web_path async into Documents.\ncheck_bs4() \u2192 None[source]\u00b6\nCheck if BeautifulSoup4 is installed.\nRaises\nImportError \u2013 If BeautifulSoup4 is not installed.\ndownload(path: str) \u2192 None[source]\u00b6\nDownload a file from an url.\nParameters\npath \u2013 Path to the file.\nasync fetch_all(urls: List[str]) \u2192 Any\u00b6\nFetch all urls concurrently with rate limiting.\nlazy_load() \u2192 Iterator[Document]\u00b6\nLazy load text from the url(s) in web_path.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nReturns\nList of Documents.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nparse_filename(url: str) \u2192 str[source]\u00b6\nParse the filename from an url.\nParameters\nurl \u2013 Url to parse the filename from.\nReturns\nThe filename.\nscrape(parser: Optional[str] = None) \u2192 Any\u00b6\nScrape data from webpage and return it in BeautifulSoup format.\nscrape_all(urls: List[str], parser: Optional[str] = None) \u2192 List[Any]\u00b6\nFetch all urls, then return soups for all results.\nExamples using BlackboardLoader\u00b6\nBlackboard", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.blackboard.BlackboardLoader.html"}
{"id": "30d2a514a90a-0", "text": "langchain.document_loaders.embaas.EmbaasLoader\u00b6\nclass langchain.document_loaders.embaas.EmbaasLoader[source]\u00b6\nBases: BaseEmbaasLoader, BaseLoader\nLoad from Embaas.\nTo use, you should have the\nenvironment variable EMBAAS_API_KEY set with your API key, or pass\nit as a named parameter to the constructor.\nExample\n# Default parsing\nfrom langchain.document_loaders.embaas import EmbaasLoader\nloader = EmbaasLoader(file_path=\"example.mp3\")\ndocuments = loader.load()\n# Custom api parameters (create embeddings automatically)\nfrom langchain.document_loaders.embaas import EmbaasBlobLoader\nloader = EmbaasBlobLoader(\n    file_path=\"example.pdf\",\n    params={\n        \"should_embed\": True,\n        \"model\": \"e5-large-v2\",\n        \"chunk_size\": 256,\n        \"chunk_splitter\": \"CharacterTextSplitter\"\n    }\n)\ndocuments = loader.load()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_url: str = 'https://api.embaas.io/v1/document/extract-text/bytes/'\u00b6\nThe URL of the Embaas document extraction API.\nparam blob_loader: Optional[langchain.document_loaders.embaas.EmbaasBlobLoader] = None\u00b6\nThe blob loader to use. If not provided, a default one will be created.\nparam embaas_api_key: Optional[str] = None\u00b6\nThe API key for the Embaas document extraction API.\nparam file_path: str [Required]\u00b6\nThe path to the file to load.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.EmbaasLoader.html"}
{"id": "30d2a514a90a-1", "text": "param file_path: str [Required]\u00b6\nThe path to the file to load.\nparam params: langchain.document_loaders.embaas.EmbaasDocumentExtractionParameters = {}\u00b6\nAdditional parameters to pass to the Embaas document extraction API.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.EmbaasLoader.html"}
{"id": "30d2a514a90a-2", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load() \u2192 Iterator[Document][source]\u00b6\nLoad the documents from the file path lazily.\nload() \u2192 List[Document][source]\u00b6\nLoad data into Document objects.\nload_and_split(text_splitter: Optional[TextSplitter] = None) \u2192 List[Document][source]\u00b6\nLoad Documents and split into chunks. Chunks are returned as Documents.\nParameters\ntext_splitter \u2013 TextSplitter instance to use for splitting documents.\nDefaults to RecursiveCharacterTextSplitter.\nReturns\nList of Documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.EmbaasLoader.html"}
{"id": "30d2a514a90a-3", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using EmbaasLoader\u00b6\nEmbaas", "source": "lang/api.python.langchain.com/en/latest/document_loaders/langchain.document_loaders.embaas.EmbaasLoader.html"}
{"id": "fba2fe08fb81-0", "text": "langchain.load.serializable.try_neq_default\u00b6\nlangchain.load.serializable.try_neq_default(value: Any, key: str, model: BaseModel) \u2192 bool[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.serializable.try_neq_default.html"}
{"id": "f1ce8680452f-0", "text": "langchain.load.dump.dumps\u00b6\nlangchain.load.dump.dumps(obj: Any, *, pretty: bool = False) \u2192 str[source]\u00b6\nReturn a json string representation of an object.", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.dump.dumps.html"}
{"id": "90800be93f83-0", "text": "langchain.load.load.loads\u00b6\nlangchain.load.load.loads(text: str, *, secrets_map: Optional[Dict[str, str]] = None, valid_namespaces: Optional[List[str]] = None) \u2192 Any[source]\u00b6\nRevive a LangChain class from a JSON string.\nEquivalent to load(json.loads(text)).\nParameters\ntext \u2013 The string to load.\nsecrets_map \u2013 A map of secrets to load.\nvalid_namespaces \u2013 A list of additional namespaces (modules)\nto allow to be deserialized.\nReturns\nRevived LangChain objects.", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.load.loads.html"}
{"id": "3d1fd99a7d7d-0", "text": "langchain.load.serializable.Serializable\u00b6\nclass langchain.load.serializable.Serializable[source]\u00b6\nBases: BaseModel, ABC\nSerializable base class.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.serializable.Serializable.html"}
{"id": "3d1fd99a7d7d-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str][source]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.serializable.Serializable.html"}
{"id": "3d1fd99a7d7d-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented][source]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented[source]\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.serializable.Serializable.html"}
{"id": "f0e6ced90542-0", "text": "langchain.load.serializable.SerializedSecret\u00b6\nclass langchain.load.serializable.SerializedSecret[source]\u00b6\nSerialized secret.\nlc: int\u00b6\nid: List[str]\u00b6\ntype: Literal['secret']\u00b6", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.serializable.SerializedSecret.html"}
{"id": "023f79269240-0", "text": "langchain.load.serializable.SerializedConstructor\u00b6\nclass langchain.load.serializable.SerializedConstructor[source]\u00b6\nSerialized constructor.\nlc: int\u00b6\nid: List[str]\u00b6\ntype: Literal['constructor']\u00b6\nkwargs: Dict[str, Any]\u00b6", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.serializable.SerializedConstructor.html"}
{"id": "186acdb653da-0", "text": "langchain.load.serializable.SerializedNotImplemented\u00b6\nclass langchain.load.serializable.SerializedNotImplemented[source]\u00b6\nSerialized not implemented.\nlc: int\u00b6\nid: List[str]\u00b6\ntype: Literal['not_implemented']\u00b6\nrepr: Optional[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.serializable.SerializedNotImplemented.html"}
{"id": "04fd5307c084-0", "text": "langchain.load.load.Reviver\u00b6\nclass langchain.load.load.Reviver(secrets_map: Optional[Dict[str, str]] = None, valid_namespaces: Optional[List[str]] = None)[source]\u00b6\nReviver for JSON objects.\nMethods\n__init__([secrets_map,\u00a0valid_namespaces])\n__init__(secrets_map: Optional[Dict[str, str]] = None, valid_namespaces: Optional[List[str]] = None) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.load.Reviver.html"}
{"id": "5f043825a3fe-0", "text": "langchain.load.load.load\u00b6\nlangchain.load.load.load(obj: Any, *, secrets_map: Optional[Dict[str, str]] = None, valid_namespaces: Optional[List[str]] = None) \u2192 Any[source]\u00b6\nRevive a LangChain class from a JSON object. Use this if you already\nhave a parsed JSON object, eg. from json.load or orjson.loads.\nParameters\nobj \u2013 The object to load.\nsecrets_map \u2013 A map of secrets to load.\nvalid_namespaces \u2013 A list of additional namespaces (modules)\nto allow to be deserialized.\nReturns\nRevived LangChain objects.", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.load.load.html"}
{"id": "12f802aff75a-0", "text": "langchain.load.serializable.BaseSerialized\u00b6\nclass langchain.load.serializable.BaseSerialized[source]\u00b6\nBase class for serialized objects.\nlc: int\u00b6\nid: List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.serializable.BaseSerialized.html"}
{"id": "5192a4d0223f-0", "text": "langchain.load.dump.dumpd\u00b6\nlangchain.load.dump.dumpd(obj: Any) \u2192 Dict[str, Any][source]\u00b6\nReturn a json dict representation of an object.", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.dump.dumpd.html"}
{"id": "046fc542793b-0", "text": "langchain.load.serializable.to_json_not_implemented\u00b6\nlangchain.load.serializable.to_json_not_implemented(obj: object) \u2192 SerializedNotImplemented[source]\u00b6\nSerialize a \u201cnot implemented\u201d object.\nParameters\nobj \u2013 object to serialize\nReturns\nSerializedNotImplemented", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.serializable.to_json_not_implemented.html"}
{"id": "36957705504c-0", "text": "langchain.load.dump.default\u00b6\nlangchain.load.dump.default(obj: Any) \u2192 Any[source]\u00b6\nReturn a default value for a Serializable object or\na SerializedNotImplemented object.", "source": "lang/api.python.langchain.com/en/latest/load/langchain.load.dump.default.html"}
{"id": "6e03e692b64e-0", "text": "langchain.output_parsers.fix.OutputFixingParser\u00b6\nclass langchain.output_parsers.fix.OutputFixingParser[source]\u00b6\nBases: BaseOutputParser[T]\nWraps a parser and tries to fix parsing errors.\nparam max_retries: int = 1\u00b6\nThe maximum number of times to retry the parse.\nparam parser: langchain.schema.output_parser.BaseOutputParser[langchain.output_parsers.fix.T] [Required]\u00b6\nThe parser to use to parse the output.\nparam retry_chain: Any = None\u00b6\nThe LLMChain to use to retry the completion.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(completion: str) \u2192 T[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.fix.OutputFixingParser.html"}
{"id": "6e03e692b64e-1", "text": "Parse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.fix.OutputFixingParser.html"}
{"id": "6e03e692b64e-2", "text": "Subclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.fix.OutputFixingParser.html"}
{"id": "6e03e692b64e-3", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_llm(llm: BaseLanguageModel, parser: BaseOutputParser[T], prompt: BasePromptTemplate = PromptTemplate(input_variables=['completion', 'error', 'instructions'], template='Instructions:\\n--------------\\n{instructions}\\n--------------\\nCompletion:\\n--------------\\n{completion}\\n--------------\\n\\nAbove, the Completion did not satisfy the constraints given in the Instructions.\\nError:\\n--------------\\n{error}\\n--------------\\n\\nPlease try again. Please only respond with an answer that satisfies the constraints laid out in the Instructions:'), max_retries: int = 1) \u2192 OutputFixingParser[T][source]\u00b6\nCreate an OutputFixingParser from a language model and a parser.\nParameters\nllm \u2013 llm to use for fixing\nparser \u2013 parser to use for parsing\nprompt \u2013 prompt to use for fixing\nmax_retries \u2013 Maximum number of retries to parse.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.fix.OutputFixingParser.html"}
{"id": "6e03e692b64e-4", "text": "prompt \u2013 prompt to use for fixing\nmax_retries \u2013 Maximum number of retries to parse.\nReturns\nOutputFixingParser\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.fix.OutputFixingParser.html"}
{"id": "6e03e692b64e-5", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(completion: str) \u2192 T[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.fix.OutputFixingParser.html"}
{"id": "6e03e692b64e-6", "text": "Parameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.fix.OutputFixingParser.html"}
{"id": "6e03e692b64e-7", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.fix.OutputFixingParser.html"}
{"id": "6e03e692b64e-8", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.fix.OutputFixingParser.html"}
{"id": "6e03e692b64e-9", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using OutputFixingParser\u00b6\nRetry parser", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.fix.OutputFixingParser.html"}
{"id": "fd12f0feb939-0", "text": "langchain.output_parsers.openai_functions.JsonKeyOutputFunctionsParser\u00b6\nclass langchain.output_parsers.openai_functions.JsonKeyOutputFunctionsParser[source]\u00b6\nBases: JsonOutputFunctionsParser\nParse an output as the element of the Json object.\nparam args_only: bool = True\u00b6\nWhether to only return the arguments to the function call.\nparam diff: bool = False\u00b6\nIn streaming mode, whether to yield diffs between the previous and current\nparsed output, or just the current parsed output.\nparam key_name: str [Required]\u00b6\nThe name of the key to return.\nparam strict: bool = False\u00b6\nWhether to allow non-JSON-compliant strings.\nSee: https://docs.python.org/3/library/json.html#encoders-and-decoders\nUseful when the parsed output may include unicode characters or new lines.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonKeyOutputFunctionsParser.html"}
{"id": "fd12f0feb939-1", "text": "Parse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonKeyOutputFunctionsParser.html"}
{"id": "fd12f0feb939-2", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[T]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonKeyOutputFunctionsParser.html"}
{"id": "fd12f0feb939-3", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonKeyOutputFunctionsParser.html"}
{"id": "fd12f0feb939-4", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonKeyOutputFunctionsParser.html"}
{"id": "fd12f0feb939-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Any\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonKeyOutputFunctionsParser.html"}
{"id": "fd12f0feb939-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 Any[source]\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[T]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonKeyOutputFunctionsParser.html"}
{"id": "fd12f0feb939-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonKeyOutputFunctionsParser.html"}
{"id": "fd12f0feb939-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonKeyOutputFunctionsParser.html"}
{"id": "fd12f0feb939-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using JsonKeyOutputFunctionsParser\u00b6\nMultiVector Retriever\nprompt_llm_parser.md", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonKeyOutputFunctionsParser.html"}
{"id": "104988625f00-0", "text": "langchain.output_parsers.rail_parser.GuardrailsOutputParser\u00b6\nclass langchain.output_parsers.rail_parser.GuardrailsOutputParser[source]\u00b6\nBases: BaseOutputParser\nParse the output of an LLM call using Guardrails.\nparam api: Optional[Callable] = None\u00b6\nThe API to use for the Guardrails object.\nparam args: Any = None\u00b6\nThe arguments to pass to the API.\nparam guard: Any = None\u00b6\nThe Guardrails object.\nparam kwargs: Any = None\u00b6\nThe keyword arguments to pass to the API.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.rail_parser.GuardrailsOutputParser.html"}
{"id": "104988625f00-1", "text": "Parse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.rail_parser.GuardrailsOutputParser.html"}
{"id": "104988625f00-2", "text": "Subclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.rail_parser.GuardrailsOutputParser.html"}
{"id": "104988625f00-3", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_pydantic(output_class: Any, num_reasks: int = 1, api: Optional[Callable] = None, *args: Any, **kwargs: Any) \u2192 GuardrailsOutputParser[source]\u00b6\nclassmethod from_rail(rail_file: str, num_reasks: int = 1, api: Optional[Callable] = None, *args: Any, **kwargs: Any) \u2192 GuardrailsOutputParser[source]\u00b6\nCreate a GuardrailsOutputParser from a rail file.\nParameters\nrail_file \u2013 a rail file.\nnum_reasks \u2013 number of times to re-ask the question.\napi \u2013 the API to use for the Guardrails object.\n*args \u2013 The arguments to pass to the API\n**kwargs \u2013 The keyword arguments to pass to the API.\nReturns\nGuardrailsOutputParser", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.rail_parser.GuardrailsOutputParser.html"}
{"id": "104988625f00-4", "text": "**kwargs \u2013 The keyword arguments to pass to the API.\nReturns\nGuardrailsOutputParser\nclassmethod from_rail_string(rail_str: str, num_reasks: int = 1, api: Optional[Callable] = None, *args: Any, **kwargs: Any) \u2192 GuardrailsOutputParser[source]\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.rail_parser.GuardrailsOutputParser.html"}
{"id": "104988625f00-5", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Dict[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.rail_parser.GuardrailsOutputParser.html"}
{"id": "104988625f00-6", "text": "by calling invoke() with each input.\nparse(text: str) \u2192 Dict[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.rail_parser.GuardrailsOutputParser.html"}
{"id": "104988625f00-7", "text": "stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.rail_parser.GuardrailsOutputParser.html"}
{"id": "104988625f00-8", "text": "Bind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.rail_parser.GuardrailsOutputParser.html"}
{"id": "104988625f00-9", "text": "The type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.rail_parser.GuardrailsOutputParser.html"}
{"id": "e6be45590e47-0", "text": "langchain.output_parsers.json.parse_and_check_json_markdown\u00b6\nlangchain.output_parsers.json.parse_and_check_json_markdown(text: str, expected_keys: List[str]) \u2192 dict[source]\u00b6\nParse a JSON string from a Markdown string and check that it\ncontains the expected keys.\nParameters\ntext \u2013 The Markdown string.\nexpected_keys \u2013 The expected keys in the JSON string.\nReturns\nThe parsed JSON object as a Python dictionary.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.json.parse_and_check_json_markdown.html"}
{"id": "23515396a2ea-0", "text": "langchain.output_parsers.pydantic.PydanticOutputParser\u00b6\nclass langchain.output_parsers.pydantic.PydanticOutputParser[source]\u00b6\nBases: BaseOutputParser[T]\nParse an output using a pydantic model.\nparam pydantic_object: Type[langchain.output_parsers.pydantic.T] [Required]\u00b6\nThe pydantic model to parse.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.pydantic.PydanticOutputParser.html"}
{"id": "23515396a2ea-1", "text": "Parameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.pydantic.PydanticOutputParser.html"}
{"id": "23515396a2ea-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.pydantic.PydanticOutputParser.html"}
{"id": "23515396a2ea-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.pydantic.PydanticOutputParser.html"}
{"id": "23515396a2ea-4", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.pydantic.PydanticOutputParser.html"}
{"id": "23515396a2ea-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 T[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.pydantic.PydanticOutputParser.html"}
{"id": "23515396a2ea-6", "text": "The prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.pydantic.PydanticOutputParser.html"}
{"id": "23515396a2ea-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.pydantic.PydanticOutputParser.html"}
{"id": "23515396a2ea-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using PydanticOutputParser\u00b6\nSet env var OPENAI_API_KEY or load from a .env file:\nMultiQueryRetriever\nWebResearchRetriever\nRetry parser\nPydantic (JSON) parser", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.pydantic.PydanticOutputParser.html"}
{"id": "35749263f552-0", "text": "langchain.output_parsers.enum.EnumOutputParser\u00b6\nclass langchain.output_parsers.enum.EnumOutputParser[source]\u00b6\nBases: BaseOutputParser\nParse an output that is one of a set of values.\nparam enum: Type[enum.Enum] [Required]\u00b6\nThe enum to parse. Its values must be strings.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.enum.EnumOutputParser.html"}
{"id": "35749263f552-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.enum.EnumOutputParser.html"}
{"id": "35749263f552-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.enum.EnumOutputParser.html"}
{"id": "35749263f552-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.enum.EnumOutputParser.html"}
{"id": "35749263f552-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.enum.EnumOutputParser.html"}
{"id": "35749263f552-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(response: str) \u2192 Any[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.enum.EnumOutputParser.html"}
{"id": "35749263f552-6", "text": "prompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.enum.EnumOutputParser.html"}
{"id": "35749263f552-7", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.enum.EnumOutputParser.html"}
{"id": "35749263f552-8", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using EnumOutputParser\u00b6\nEnum parser", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.enum.EnumOutputParser.html"}
{"id": "e9ed495f1ca1-0", "text": "langchain.output_parsers.loading.load_output_parser\u00b6\nlangchain.output_parsers.loading.load_output_parser(config: dict) \u2192 dict[source]\u00b6\nLoad an output parser.\nParameters\nconfig \u2013 config dict\nReturns\nconfig dict with output parser loaded", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.loading.load_output_parser.html"}
{"id": "e287d251a365-0", "text": "langchain.output_parsers.regex.RegexParser\u00b6\nclass langchain.output_parsers.regex.RegexParser[source]\u00b6\nBases: BaseOutputParser\nParse the output of an LLM call using a regex.\nparam default_output_key: Optional[str] = None\u00b6\nThe default key to use for the output.\nparam output_keys: List[str] [Required]\u00b6\nThe keys to use for the output.\nparam regex: str [Required]\u00b6\nThe regex to use to parse the output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex.RegexParser.html"}
{"id": "e287d251a365-1", "text": "Parameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex.RegexParser.html"}
{"id": "e287d251a365-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex.RegexParser.html"}
{"id": "e287d251a365-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex.RegexParser.html"}
{"id": "e287d251a365-4", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex.RegexParser.html"}
{"id": "e287d251a365-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Dict[str, str][source]\u00b6\nParse the output of an LLM call.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex.RegexParser.html"}
{"id": "e287d251a365-6", "text": "to retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex.RegexParser.html"}
{"id": "e287d251a365-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex.RegexParser.html"}
{"id": "e287d251a365-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using RegexParser\u00b6\nMulti-Agent Simulated Environment: Petting Zoo\nMulti-agent decentralized speaker selection\nMulti-agent authoritarian speaker selection\nSimulated Environment: Gymnasium", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex.RegexParser.html"}
{"id": "7cbd933f3991-0", "text": "langchain.output_parsers.openai_tools.PydanticToolsParser\u00b6\nclass langchain.output_parsers.openai_tools.PydanticToolsParser[source]\u00b6\nBases: JsonOutputToolsParser\nParse tools from OpenAI response.\nparam tools: List[Type[pydantic.main.BaseModel]] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.PydanticToolsParser.html"}
{"id": "7cbd933f3991-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.PydanticToolsParser.html"}
{"id": "7cbd933f3991-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.PydanticToolsParser.html"}
{"id": "7cbd933f3991-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.PydanticToolsParser.html"}
{"id": "7cbd933f3991-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.PydanticToolsParser.html"}
{"id": "7cbd933f3991-5", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 Any[source]\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.PydanticToolsParser.html"}
{"id": "7cbd933f3991-6", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.PydanticToolsParser.html"}
{"id": "7cbd933f3991-7", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.PydanticToolsParser.html"}
{"id": "7cbd933f3991-8", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.PydanticToolsParser.html"}
{"id": "75d19dbfaa6f-0", "text": "langchain.output_parsers.json.parse_partial_json\u00b6\nlangchain.output_parsers.json.parse_partial_json(s: str, *, strict: bool = False) \u2192 Any[source]\u00b6\nParse a JSON string that may be missing closing braces.\nParameters\ns \u2013 The JSON string to parse.\nstrict \u2013 Whether to use strict parsing. Defaults to False.\nReturns\nThe parsed JSON object as a Python dictionary.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.json.parse_partial_json.html"}
{"id": "944cf3b025ef-0", "text": "langchain.output_parsers.openai_functions.JsonOutputFunctionsParser\u00b6\nclass langchain.output_parsers.openai_functions.JsonOutputFunctionsParser[source]\u00b6\nBases: BaseCumulativeTransformOutputParser[Any]\nParse an output as the Json object.\nparam args_only: bool = True\u00b6\nWhether to only return the arguments to the function call.\nparam diff: bool = False\u00b6\nIn streaming mode, whether to yield diffs between the previous and current\nparsed output, or just the current parsed output.\nparam strict: bool = False\u00b6\nWhether to allow non-JSON-compliant strings.\nSee: https://docs.python.org/3/library/json.html#encoders-and-decoders\nUseful when the parsed output may include unicode characters or new lines.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonOutputFunctionsParser.html"}
{"id": "944cf3b025ef-1", "text": "Parameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonOutputFunctionsParser.html"}
{"id": "944cf3b025ef-2", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[T]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonOutputFunctionsParser.html"}
{"id": "944cf3b025ef-3", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonOutputFunctionsParser.html"}
{"id": "944cf3b025ef-4", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonOutputFunctionsParser.html"}
{"id": "944cf3b025ef-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Any[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonOutputFunctionsParser.html"}
{"id": "944cf3b025ef-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 Any[source]\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[T]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonOutputFunctionsParser.html"}
{"id": "944cf3b025ef-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonOutputFunctionsParser.html"}
{"id": "944cf3b025ef-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonOutputFunctionsParser.html"}
{"id": "944cf3b025ef-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using JsonOutputFunctionsParser\u00b6\nprompt_llm_parser.md", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.JsonOutputFunctionsParser.html"}
{"id": "8c7acb79a31b-0", "text": "langchain.output_parsers.structured.StructuredOutputParser\u00b6\nclass langchain.output_parsers.structured.StructuredOutputParser[source]\u00b6\nBases: BaseOutputParser\nParse the output of an LLM call to a structured output.\nparam response_schemas: List[langchain.output_parsers.structured.ResponseSchema] [Required]\u00b6\nThe schemas for the response.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.structured.StructuredOutputParser.html"}
{"id": "8c7acb79a31b-1", "text": "Parameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.structured.StructuredOutputParser.html"}
{"id": "8c7acb79a31b-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.structured.StructuredOutputParser.html"}
{"id": "8c7acb79a31b-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_response_schemas(response_schemas: List[ResponseSchema]) \u2192 StructuredOutputParser[source]\u00b6\nget_format_instructions(only_json: bool = False) \u2192 str[source]\u00b6\nGet format instructions for the output parser.\nexample:\n```python\nfrom langchain.output_parsers.structured import (\nStructuredOutputParser, ResponseSchema\n)\nresponse_schemas = [\nResponseSchema(name=\u201dfoo\u201d,\ndescription=\u201da list of strings\u201d,\ntype=\u201dList[string]\u201d\n),\nResponseSchema(name=\u201dbar\u201d,\ndescription=\u201da string\u201d,\ntype=\u201dstring\u201d\n),\n]\nparser = StructuredOutputParser.from_response_schemas(response_schemas)\nprint(parser.get_format_instructions())\noutput:\n# The output should be a Markdown code snippet formatted in the following\n# schema, including the leading and trailing \u201c`json\" and \"`\u201d:\n#\n# `json\n# {", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.structured.StructuredOutputParser.html"}
{"id": "8c7acb79a31b-4", "text": "#\n# `json\n# {\n#\u00a0\u00a0\u00a0\u00a0 \"foo\": List[string]\u00a0 // a list of strings\n#\u00a0\u00a0\u00a0\u00a0 \"bar\": string\u00a0 // a string\n# }\n# `\nParameters\nonly_json (bool) \u2013 If True, only the json in the Markdown code snippet\nwill be returned, without the introducing text. Defaults to False.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.structured.StructuredOutputParser.html"}
{"id": "8c7acb79a31b-5", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Any[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.structured.StructuredOutputParser.html"}
{"id": "8c7acb79a31b-6", "text": "Parameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.structured.StructuredOutputParser.html"}
{"id": "8c7acb79a31b-7", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.structured.StructuredOutputParser.html"}
{"id": "8c7acb79a31b-8", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.structured.StructuredOutputParser.html"}
{"id": "8c7acb79a31b-9", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.structured.StructuredOutputParser.html"}
{"id": "62e348c79a1d-0", "text": "langchain.output_parsers.list.ListOutputParser\u00b6\nclass langchain.output_parsers.list.ListOutputParser[source]\u00b6\nBases: BaseOutputParser[List[str]]\nParse the output of an LLM call to a list.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.ListOutputParser.html"}
{"id": "62e348c79a1d-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.ListOutputParser.html"}
{"id": "62e348c79a1d-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.ListOutputParser.html"}
{"id": "62e348c79a1d-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.ListOutputParser.html"}
{"id": "62e348c79a1d-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.ListOutputParser.html"}
{"id": "62e348c79a1d-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nabstract parse(text: str) \u2192 List[str][source]\u00b6\nParse the output of an LLM call.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.ListOutputParser.html"}
{"id": "62e348c79a1d-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.ListOutputParser.html"}
{"id": "62e348c79a1d-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.ListOutputParser.html"}
{"id": "62e348c79a1d-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.ListOutputParser.html"}
{"id": "b5187fddc725-0", "text": "langchain.output_parsers.list.CommaSeparatedListOutputParser\u00b6\nclass langchain.output_parsers.list.CommaSeparatedListOutputParser[source]\u00b6\nBases: ListOutputParser\nParse the output of an LLM call to a comma-separated list.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.CommaSeparatedListOutputParser.html"}
{"id": "b5187fddc725-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.CommaSeparatedListOutputParser.html"}
{"id": "b5187fddc725-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.CommaSeparatedListOutputParser.html"}
{"id": "b5187fddc725-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.CommaSeparatedListOutputParser.html"}
{"id": "b5187fddc725-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.CommaSeparatedListOutputParser.html"}
{"id": "b5187fddc725-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 List[str][source]\u00b6\nParse the output of an LLM call.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.CommaSeparatedListOutputParser.html"}
{"id": "b5187fddc725-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.CommaSeparatedListOutputParser.html"}
{"id": "b5187fddc725-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.CommaSeparatedListOutputParser.html"}
{"id": "b5187fddc725-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.CommaSeparatedListOutputParser.html"}
{"id": "ab2d4905d623-0", "text": "langchain.output_parsers.openai_tools.JsonOutputKeyToolsParser\u00b6\nclass langchain.output_parsers.openai_tools.JsonOutputKeyToolsParser[source]\u00b6\nBases: JsonOutputToolsParser\nParse tools from OpenAI response.\nparam key_name: str [Required]\u00b6\nThe type of tools to return.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputKeyToolsParser.html"}
{"id": "ab2d4905d623-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputKeyToolsParser.html"}
{"id": "ab2d4905d623-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputKeyToolsParser.html"}
{"id": "ab2d4905d623-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputKeyToolsParser.html"}
{"id": "ab2d4905d623-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputKeyToolsParser.html"}
{"id": "ab2d4905d623-5", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 Any[source]\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputKeyToolsParser.html"}
{"id": "ab2d4905d623-6", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputKeyToolsParser.html"}
{"id": "ab2d4905d623-7", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputKeyToolsParser.html"}
{"id": "ab2d4905d623-8", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputKeyToolsParser.html"}
{"id": "075cf0e57b05-0", "text": "langchain.output_parsers.boolean.BooleanOutputParser\u00b6\nclass langchain.output_parsers.boolean.BooleanOutputParser[source]\u00b6\nBases: BaseOutputParser[bool]\nParse the output of an LLM call to a boolean.\nparam false_val: str = 'NO'\u00b6\nThe string value that should be parsed as False.\nparam true_val: str = 'YES'\u00b6\nThe string value that should be parsed as True.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.boolean.BooleanOutputParser.html"}
{"id": "075cf0e57b05-1", "text": "Parameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.boolean.BooleanOutputParser.html"}
{"id": "075cf0e57b05-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.boolean.BooleanOutputParser.html"}
{"id": "075cf0e57b05-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.boolean.BooleanOutputParser.html"}
{"id": "075cf0e57b05-4", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.boolean.BooleanOutputParser.html"}
{"id": "075cf0e57b05-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 bool[source]\u00b6\nParse the output of an LLM call to a boolean.\nParameters\ntext \u2013 output of a language model\nReturns\nboolean\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.boolean.BooleanOutputParser.html"}
{"id": "075cf0e57b05-6", "text": "The prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.boolean.BooleanOutputParser.html"}
{"id": "075cf0e57b05-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.boolean.BooleanOutputParser.html"}
{"id": "075cf0e57b05-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.boolean.BooleanOutputParser.html"}
{"id": "968b24ddce8f-0", "text": "langchain.output_parsers.list.NumberedListOutputParser\u00b6\nclass langchain.output_parsers.list.NumberedListOutputParser[source]\u00b6\nBases: ListOutputParser\nParse a numbered list.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.NumberedListOutputParser.html"}
{"id": "968b24ddce8f-1", "text": "Default implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.NumberedListOutputParser.html"}
{"id": "968b24ddce8f-2", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.NumberedListOutputParser.html"}
{"id": "968b24ddce8f-3", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.NumberedListOutputParser.html"}
{"id": "968b24ddce8f-4", "text": "This method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.NumberedListOutputParser.html"}
{"id": "968b24ddce8f-5", "text": "Return a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 List[str][source]\u00b6\nParse the output of an LLM call.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.NumberedListOutputParser.html"}
{"id": "968b24ddce8f-6", "text": "stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.NumberedListOutputParser.html"}
{"id": "968b24ddce8f-7", "text": "Bind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.NumberedListOutputParser.html"}
{"id": "968b24ddce8f-8", "text": "The type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.NumberedListOutputParser.html"}
{"id": "9f8093054ca6-0", "text": "langchain.output_parsers.xml.XMLOutputParser\u00b6\nclass langchain.output_parsers.xml.XMLOutputParser[source]\u00b6\nBases: BaseOutputParser\nParse an output using xml format.\nparam encoding_matcher: re.Pattern = re.compile('<([^>]*encoding[^>]*)>\\\\n(.*)', re.MULTILINE|re.DOTALL)\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.xml.XMLOutputParser.html"}
{"id": "9f8093054ca6-1", "text": "Parameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.xml.XMLOutputParser.html"}
{"id": "9f8093054ca6-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.xml.XMLOutputParser.html"}
{"id": "9f8093054ca6-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.xml.XMLOutputParser.html"}
{"id": "9f8093054ca6-4", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.xml.XMLOutputParser.html"}
{"id": "9f8093054ca6-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Dict[str, List[Any]][source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.xml.XMLOutputParser.html"}
{"id": "9f8093054ca6-6", "text": "The prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.xml.XMLOutputParser.html"}
{"id": "9f8093054ca6-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.xml.XMLOutputParser.html"}
{"id": "9f8093054ca6-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.xml.XMLOutputParser.html"}
{"id": "13ff8ba52013-0", "text": "langchain.output_parsers.openai_functions.OutputFunctionsParser\u00b6\nclass langchain.output_parsers.openai_functions.OutputFunctionsParser[source]\u00b6\nBases: BaseGenerationOutputParser[Any]\nParse an output that is one of sets of values.\nparam args_only: bool = True\u00b6\nWhether to only return the arguments to the function call.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.OutputFunctionsParser.html"}
{"id": "13ff8ba52013-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.OutputFunctionsParser.html"}
{"id": "13ff8ba52013-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.OutputFunctionsParser.html"}
{"id": "13ff8ba52013-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.OutputFunctionsParser.html"}
{"id": "13ff8ba52013-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.OutputFunctionsParser.html"}
{"id": "13ff8ba52013-5", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 Any[source]\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.OutputFunctionsParser.html"}
{"id": "13ff8ba52013-6", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.OutputFunctionsParser.html"}
{"id": "13ff8ba52013-7", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.OutputFunctionsParser.html"}
{"id": "13ff8ba52013-8", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.OutputFunctionsParser.html"}
{"id": "e391ed3c3e77-0", "text": "langchain.output_parsers.datetime.DatetimeOutputParser\u00b6\nclass langchain.output_parsers.datetime.DatetimeOutputParser[source]\u00b6\nBases: BaseOutputParser[datetime]\nParse the output of an LLM call to a datetime.\nparam format: str = '%Y-%m-%dT%H:%M:%S.%fZ'\u00b6\nThe string value that used as the datetime format.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.datetime.DatetimeOutputParser.html"}
{"id": "e391ed3c3e77-1", "text": "Parameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.datetime.DatetimeOutputParser.html"}
{"id": "e391ed3c3e77-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.datetime.DatetimeOutputParser.html"}
{"id": "e391ed3c3e77-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.datetime.DatetimeOutputParser.html"}
{"id": "e391ed3c3e77-4", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.datetime.DatetimeOutputParser.html"}
{"id": "e391ed3c3e77-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(response: str) \u2192 datetime[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.datetime.DatetimeOutputParser.html"}
{"id": "e391ed3c3e77-6", "text": "The prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.datetime.DatetimeOutputParser.html"}
{"id": "e391ed3c3e77-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.datetime.DatetimeOutputParser.html"}
{"id": "e391ed3c3e77-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using DatetimeOutputParser\u00b6\nFallbacks\nDatetime parser", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.datetime.DatetimeOutputParser.html"}
{"id": "fa21b4742204-0", "text": "langchain.output_parsers.json.SimpleJsonOutputParser\u00b6\nclass langchain.output_parsers.json.SimpleJsonOutputParser[source]\u00b6\nBases: BaseCumulativeTransformOutputParser[Any]\nParse the output of an LLM call to a JSON object.\nWhen used in streaming mode, it will yield partial JSON objects containing\nall the keys that have been returned so far.\nIn streaming, if diff is set to True, yields JSONPatch operations\ndescribing the difference between the previous and the current object.\nparam diff: bool = False\u00b6\nIn streaming mode, whether to yield diffs between the previous and current\nparsed output, or just the current parsed output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.json.SimpleJsonOutputParser.html"}
{"id": "fa21b4742204-1", "text": "Parse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[T]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.json.SimpleJsonOutputParser.html"}
{"id": "fa21b4742204-2", "text": "Subclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.json.SimpleJsonOutputParser.html"}
{"id": "fa21b4742204-3", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.json.SimpleJsonOutputParser.html"}
{"id": "fa21b4742204-4", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.json.SimpleJsonOutputParser.html"}
{"id": "fa21b4742204-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Any[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.json.SimpleJsonOutputParser.html"}
{"id": "fa21b4742204-6", "text": "The prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[T]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.json.SimpleJsonOutputParser.html"}
{"id": "fa21b4742204-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.json.SimpleJsonOutputParser.html"}
{"id": "fa21b4742204-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.json.SimpleJsonOutputParser.html"}
{"id": "1aeef4c37212-0", "text": "langchain.output_parsers.retry.RetryWithErrorOutputParser\u00b6\nclass langchain.output_parsers.retry.RetryWithErrorOutputParser[source]\u00b6\nBases: BaseOutputParser[T]\nWraps a parser and tries to fix parsing errors.\nDoes this by passing the original prompt, the completion, AND the error\nthat was raised to another language model and telling it that the completion\ndid not work, and raised the given error. Differs from RetryOutputParser\nin that this implementation provides the error that was raised back to the\nLLM, which in theory should give it more information on how to fix it.\nparam max_retries: int = 1\u00b6\nThe maximum number of times to retry the parse.\nparam parser: langchain.schema.output_parser.BaseOutputParser[langchain.output_parsers.retry.T] [Required]\u00b6\nThe parser to use to parse the output.\nparam retry_chain: Any = None\u00b6\nThe LLMChain to use to retry the completion.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryWithErrorOutputParser.html"}
{"id": "1aeef4c37212-1", "text": "Subclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync aparse_with_prompt(completion: str, prompt_value: PromptValue) \u2192 T[source]\u00b6\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryWithErrorOutputParser.html"}
{"id": "1aeef4c37212-2", "text": "Output is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryWithErrorOutputParser.html"}
{"id": "1aeef4c37212-3", "text": "configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_llm(llm: BaseLanguageModel, parser: BaseOutputParser[T], prompt: BasePromptTemplate = PromptTemplate(input_variables=['completion', 'error', 'prompt'], template='Prompt:\\n{prompt}\\nCompletion:\\n{completion}\\n\\nAbove, the Completion did not satisfy the constraints given in the Prompt.\\nDetails: {error}\\nPlease try again:'), max_retries: int = 1) \u2192 RetryWithErrorOutputParser[T][source]\u00b6\nCreate a RetryWithErrorOutputParser from an LLM.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryWithErrorOutputParser.html"}
{"id": "1aeef4c37212-4", "text": "Create a RetryWithErrorOutputParser from an LLM.\nParameters\nllm \u2013 The LLM to use to retry the completion.\nparser \u2013 The parser to use to parse the output.\nprompt \u2013 The prompt to use to retry the completion.\nmax_retries \u2013 The maximum number of times to retry the completion.\nReturns\nA RetryWithErrorOutputParser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryWithErrorOutputParser.html"}
{"id": "1aeef4c37212-5", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(completion: str) \u2192 T[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryWithErrorOutputParser.html"}
{"id": "1aeef4c37212-6", "text": "by calling invoke() with each input.\nparse(completion: str) \u2192 T[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt_value: PromptValue) \u2192 T[source]\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryWithErrorOutputParser.html"}
{"id": "1aeef4c37212-7", "text": "stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryWithErrorOutputParser.html"}
{"id": "1aeef4c37212-8", "text": "Bind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryWithErrorOutputParser.html"}
{"id": "1aeef4c37212-9", "text": "The type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using RetryWithErrorOutputParser\u00b6\nRetry parser", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryWithErrorOutputParser.html"}
{"id": "268841bfce97-0", "text": "langchain.output_parsers.openai_functions.PydanticOutputFunctionsParser\u00b6\nclass langchain.output_parsers.openai_functions.PydanticOutputFunctionsParser[source]\u00b6\nBases: OutputFunctionsParser\nParse an output as a pydantic object.\nparam args_only: bool = True\u00b6\nWhether to only return the arguments to the function call.\nparam pydantic_schema: Union[Type[pydantic.main.BaseModel], Dict[str, Type[pydantic.main.BaseModel]]] [Required]\u00b6\nThe pydantic schema to parse the output with.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticOutputFunctionsParser.html"}
{"id": "268841bfce97-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticOutputFunctionsParser.html"}
{"id": "268841bfce97-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticOutputFunctionsParser.html"}
{"id": "268841bfce97-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticOutputFunctionsParser.html"}
{"id": "268841bfce97-4", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticOutputFunctionsParser.html"}
{"id": "268841bfce97-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 Any[source]\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticOutputFunctionsParser.html"}
{"id": "268841bfce97-6", "text": "Subclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticOutputFunctionsParser.html"}
{"id": "268841bfce97-7", "text": "on_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticOutputFunctionsParser.html"}
{"id": "268841bfce97-8", "text": "These attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticOutputFunctionsParser.html"}
{"id": "2513cf7bc56d-0", "text": "langchain.output_parsers.structured.ResponseSchema\u00b6\nclass langchain.output_parsers.structured.ResponseSchema[source]\u00b6\nBases: BaseModel\nA schema for a response from a structured output parser.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam description: str [Required]\u00b6\nThe description of the schema.\nparam name: str [Required]\u00b6\nThe name of the schema.\nparam type: str = 'string'\u00b6\nThe type of the response.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.structured.ResponseSchema.html"}
{"id": "2513cf7bc56d-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.structured.ResponseSchema.html"}
{"id": "2513cf7bc56d-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.structured.ResponseSchema.html"}
{"id": "a2b102283e95-0", "text": "langchain.output_parsers.openai_tools.JsonOutputToolsParser\u00b6\nclass langchain.output_parsers.openai_tools.JsonOutputToolsParser[source]\u00b6\nBases: BaseGenerationOutputParser[Any]\nParse tools from OpenAI response.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputToolsParser.html"}
{"id": "a2b102283e95-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputToolsParser.html"}
{"id": "a2b102283e95-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputToolsParser.html"}
{"id": "a2b102283e95-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputToolsParser.html"}
{"id": "a2b102283e95-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputToolsParser.html"}
{"id": "a2b102283e95-5", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 Any[source]\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputToolsParser.html"}
{"id": "a2b102283e95-6", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputToolsParser.html"}
{"id": "a2b102283e95-7", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputToolsParser.html"}
{"id": "a2b102283e95-8", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_tools.JsonOutputToolsParser.html"}
{"id": "a8f037e8004c-0", "text": "langchain.output_parsers.json.parse_json_markdown\u00b6\nlangchain.output_parsers.json.parse_json_markdown(json_string: str, *, parser: ~typing.Callable[[str], ~typing.Any] = <function loads>) \u2192 dict[source]\u00b6\nParse a JSON string from a Markdown string.\nParameters\njson_string \u2013 The Markdown string.\nReturns\nThe parsed JSON object as a Python dictionary.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.json.parse_json_markdown.html"}
{"id": "e302e1be1e1d-0", "text": "langchain.output_parsers.openai_functions.PydanticAttrOutputFunctionsParser\u00b6\nclass langchain.output_parsers.openai_functions.PydanticAttrOutputFunctionsParser[source]\u00b6\nBases: PydanticOutputFunctionsParser\nParse an output as an attribute of a pydantic object.\nparam args_only: bool = True\u00b6\nWhether to only return the arguments to the function call.\nparam attr_name: str [Required]\u00b6\nThe name of the attribute to return.\nparam pydantic_schema: Union[Type[pydantic.main.BaseModel], Dict[str, Type[pydantic.main.BaseModel]]] [Required]\u00b6\nThe pydantic schema to parse the output with.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticAttrOutputFunctionsParser.html"}
{"id": "e302e1be1e1d-1", "text": "Parameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticAttrOutputFunctionsParser.html"}
{"id": "e302e1be1e1d-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticAttrOutputFunctionsParser.html"}
{"id": "e302e1be1e1d-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticAttrOutputFunctionsParser.html"}
{"id": "e302e1be1e1d-4", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticAttrOutputFunctionsParser.html"}
{"id": "e302e1be1e1d-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 Any[source]\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticAttrOutputFunctionsParser.html"}
{"id": "e302e1be1e1d-6", "text": "Parameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticAttrOutputFunctionsParser.html"}
{"id": "e302e1be1e1d-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticAttrOutputFunctionsParser.html"}
{"id": "e302e1be1e1d-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.openai_functions.PydanticAttrOutputFunctionsParser.html"}
{"id": "47e131c0e313-0", "text": "langchain.output_parsers.regex_dict.RegexDictParser\u00b6\nclass langchain.output_parsers.regex_dict.RegexDictParser[source]\u00b6\nBases: BaseOutputParser\nParse the output of an LLM call into a Dictionary using a regex.\nparam no_update_value: Optional[str] = None\u00b6\nThe default key to use for the output.\nparam output_key_to_format: Dict[str, str] [Required]\u00b6\nThe keys to use for the output.\nparam regex_pattern: str = \"{}:\\\\s?([^.'\\\\n']*)\\\\.?\"\u00b6\nThe regex pattern to use to parse the output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex_dict.RegexDictParser.html"}
{"id": "47e131c0e313-1", "text": "Parse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex_dict.RegexDictParser.html"}
{"id": "47e131c0e313-2", "text": "Subclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex_dict.RegexDictParser.html"}
{"id": "47e131c0e313-3", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex_dict.RegexDictParser.html"}
{"id": "47e131c0e313-4", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex_dict.RegexDictParser.html"}
{"id": "47e131c0e313-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Dict[str, str][source]\u00b6\nParse the output of an LLM call.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex_dict.RegexDictParser.html"}
{"id": "47e131c0e313-6", "text": "to retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex_dict.RegexDictParser.html"}
{"id": "47e131c0e313-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex_dict.RegexDictParser.html"}
{"id": "47e131c0e313-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.regex_dict.RegexDictParser.html"}
{"id": "0ae9a393e23b-0", "text": "langchain.output_parsers.retry.RetryOutputParser\u00b6\nclass langchain.output_parsers.retry.RetryOutputParser[source]\u00b6\nBases: BaseOutputParser[T]\nWraps a parser and tries to fix parsing errors.\nDoes this by passing the original prompt and the completion to another\nLLM, and telling it the completion did not satisfy criteria in the prompt.\nparam max_retries: int = 1\u00b6\nThe maximum number of times to retry the parse.\nparam parser: langchain.schema.output_parser.BaseOutputParser[langchain.output_parsers.retry.T] [Required]\u00b6\nThe parser to use to parse the output.\nparam retry_chain: Any = None\u00b6\nThe LLMChain to use to retry the completion.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryOutputParser.html"}
{"id": "0ae9a393e23b-1", "text": "Parameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync aparse_with_prompt(completion: str, prompt_value: PromptValue) \u2192 T[source]\u00b6\nParse the output of an LLM call using a wrapped parser.\nParameters\ncompletion \u2013 The chain completion to parse.\nprompt_value \u2013 The prompt to use to parse the completion.\nReturns\nThe parsed completion.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryOutputParser.html"}
{"id": "0ae9a393e23b-2", "text": "Output is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryOutputParser.html"}
{"id": "0ae9a393e23b-3", "text": "configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_llm(llm: BaseLanguageModel, parser: BaseOutputParser[T], prompt: BasePromptTemplate = PromptTemplate(input_variables=['completion', 'prompt'], template='Prompt:\\n{prompt}\\nCompletion:\\n{completion}\\n\\nAbove, the Completion did not satisfy the constraints given in the Prompt.\\nPlease try again:'), max_retries: int = 1) \u2192 RetryOutputParser[T][source]\u00b6\nCreate an OutputFixingParser from a language model and a parser.\nParameters", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryOutputParser.html"}
{"id": "0ae9a393e23b-4", "text": "Create an OutputFixingParser from a language model and a parser.\nParameters\nllm \u2013 llm to use for fixing\nparser \u2013 parser to use for parsing\nprompt \u2013 prompt to use for fixing\nmax_retries \u2013 Maximum number of retries to parse.\nReturns\nRetryOutputParser\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryOutputParser.html"}
{"id": "0ae9a393e23b-5", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(completion: str) \u2192 T[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryOutputParser.html"}
{"id": "0ae9a393e23b-6", "text": "by calling invoke() with each input.\nparse(completion: str) \u2192 T[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt_value: PromptValue) \u2192 T[source]\u00b6\nParse the output of an LLM call using a wrapped parser.\nParameters\ncompletion \u2013 The chain completion to parse.\nprompt_value \u2013 The prompt to use to parse the completion.\nReturns\nThe parsed completion.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryOutputParser.html"}
{"id": "0ae9a393e23b-7", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryOutputParser.html"}
{"id": "0ae9a393e23b-8", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryOutputParser.html"}
{"id": "0ae9a393e23b-9", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using RetryOutputParser\u00b6\nRetry parser", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.retry.RetryOutputParser.html"}
{"id": "eae8bb3e09b9-0", "text": "langchain.output_parsers.combining.CombiningOutputParser\u00b6\nclass langchain.output_parsers.combining.CombiningOutputParser[source]\u00b6\nBases: BaseOutputParser\nCombine multiple output parsers into one.\nparam parsers: List[langchain.schema.output_parser.BaseOutputParser] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.combining.CombiningOutputParser.html"}
{"id": "eae8bb3e09b9-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.combining.CombiningOutputParser.html"}
{"id": "eae8bb3e09b9-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.combining.CombiningOutputParser.html"}
{"id": "eae8bb3e09b9-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.combining.CombiningOutputParser.html"}
{"id": "eae8bb3e09b9-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.combining.CombiningOutputParser.html"}
{"id": "eae8bb3e09b9-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Dict[str, Any][source]\u00b6\nParse the output of an LLM call.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.combining.CombiningOutputParser.html"}
{"id": "eae8bb3e09b9-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.combining.CombiningOutputParser.html"}
{"id": "eae8bb3e09b9-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.combining.CombiningOutputParser.html"}
{"id": "eae8bb3e09b9-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.combining.CombiningOutputParser.html"}
{"id": "ef490339c175-0", "text": "langchain.output_parsers.list.MarkdownListOutputParser\u00b6\nclass langchain.output_parsers.list.MarkdownListOutputParser[source]\u00b6\nBases: ListOutputParser\nParse a markdown list.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.MarkdownListOutputParser.html"}
{"id": "ef490339c175-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.MarkdownListOutputParser.html"}
{"id": "ef490339c175-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.MarkdownListOutputParser.html"}
{"id": "ef490339c175-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.MarkdownListOutputParser.html"}
{"id": "ef490339c175-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.MarkdownListOutputParser.html"}
{"id": "ef490339c175-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 List[str][source]\u00b6\nParse the output of an LLM call.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.MarkdownListOutputParser.html"}
{"id": "ef490339c175-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.MarkdownListOutputParser.html"}
{"id": "ef490339c175-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.MarkdownListOutputParser.html"}
{"id": "ef490339c175-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/output_parsers/langchain.output_parsers.list.MarkdownListOutputParser.html"}
{"id": "bf2d19254abf-0", "text": "langchain.tools.render.render_text_description_and_args\u00b6\nlangchain.tools.render.render_text_description_and_args(tools: List[BaseTool]) \u2192 str[source]\u00b6\nRender the tool name, description, and args in plain text.\nOutput will be in the format of:\nsearch: This tool is used for search, args: {\"query\": {\"type\": \"string\"}}\ncalculator: This tool is used for math, args: {\"expression\": {\"type\": \"string\"}}", "source": "lang/api.python.langchain.com/en/latest/tools.render/langchain.tools.render.render_text_description_and_args.html"}
{"id": "e37f4b7e52dc-0", "text": "langchain.tools.render.format_tool_to_openai_function\u00b6\nlangchain.tools.render.format_tool_to_openai_function(tool: BaseTool) \u2192 FunctionDescription[source]\u00b6\nFormat tool into the OpenAI function API.\nExamples using format_tool_to_openai_function\u00b6\nTools as OpenAI Functions", "source": "lang/api.python.langchain.com/en/latest/tools.render/langchain.tools.render.format_tool_to_openai_function.html"}
{"id": "af9c6206f148-0", "text": "langchain.tools.render.render_text_description\u00b6\nlangchain.tools.render.render_text_description(tools: List[BaseTool]) \u2192 str[source]\u00b6\nRender the tool name and description in plain text.\nOutput will be in the format of:\nsearch: This tool is used for search\ncalculator: This tool is used for math", "source": "lang/api.python.langchain.com/en/latest/tools.render/langchain.tools.render.render_text_description.html"}
{"id": "2b953d2106fd-0", "text": "langchain.tools.render.format_tool_to_openai_tool\u00b6\nlangchain.tools.render.format_tool_to_openai_tool(tool: BaseTool) \u2192 ToolDescription[source]\u00b6\nFormat tool into the OpenAI function API.", "source": "lang/api.python.langchain.com/en/latest/tools.render/langchain.tools.render.format_tool_to_openai_tool.html"}
{"id": "bcdde03a7d91-0", "text": "langchain.embeddings.huggingface.HuggingFaceEmbeddings\u00b6\nclass langchain.embeddings.huggingface.HuggingFaceEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nHuggingFace sentence_transformers embedding models.\nTo use, you should have the sentence_transformers python package installed.\nExample\nfrom langchain.embeddings import HuggingFaceEmbeddings\nmodel_name = \"sentence-transformers/all-mpnet-base-v2\"\nmodel_kwargs = {'device': 'cpu'}\nencode_kwargs = {'normalize_embeddings': False}\nhf = HuggingFaceEmbeddings(\n    model_name=model_name,\n    model_kwargs=model_kwargs,\n    encode_kwargs=encode_kwargs\n)\nInitialize the sentence_transformer.\nparam cache_folder: Optional[str] = None\u00b6\nPath to store models.\nCan be also set by SENTENCE_TRANSFORMERS_HOME environment variable.\nparam encode_kwargs: Dict[str, Any] [Optional]\u00b6\nKeyword arguments to pass when calling the encode method of the model.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nKeyword arguments to pass to the model.\nparam model_name: str = 'sentence-transformers/all-mpnet-base-v2'\u00b6\nModel name to use.\nparam multi_process: bool = False\u00b6\nRun encode() on multiple GPUs.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceEmbeddings.html"}
{"id": "bcdde03a7d91-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCompute doc embeddings using a HuggingFace transformer model.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCompute query embeddings using a HuggingFace transformer model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceEmbeddings.html"}
{"id": "bcdde03a7d91-2", "text": "Embeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using HuggingFaceEmbeddings\u00b6\nHugging Face\nSentence Transformers\nLOTR (Merger Retriever)\nScaNN", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceEmbeddings.html"}
{"id": "bcdde03a7d91-3", "text": "Sentence Transformers\nLOTR (Merger Retriever)\nScaNN\nAnnoy\nyour local model path\nPairwise Embedding Distance \nEmbedding Distance\nLost in the middle: The problem with long contexts", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceEmbeddings.html"}
{"id": "fdbcffb2087c-0", "text": "langchain.embeddings.embaas.EmbaasEmbeddingsPayload\u00b6\nclass langchain.embeddings.embaas.EmbaasEmbeddingsPayload[source]\u00b6\nPayload for the Embaas embeddings API.\nAttributes\nmodel\ntexts\ninstruction\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.embaas.EmbaasEmbeddingsPayload.html"}
{"id": "fdbcffb2087c-1", "text": "keys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.embaas.EmbaasEmbeddingsPayload.html"}
{"id": "a23c12ca08bb-0", "text": "langchain.embeddings.localai.async_embed_with_retry\u00b6\nasync langchain.embeddings.localai.async_embed_with_retry(embeddings: LocalAIEmbeddings, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the embedding call.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.localai.async_embed_with_retry.html"}
{"id": "7220ad1098bb-0", "text": "langchain.embeddings.aleph_alpha.AlephAlphaSymmetricSemanticEmbedding\u00b6\nclass langchain.embeddings.aleph_alpha.AlephAlphaSymmetricSemanticEmbedding[source]\u00b6\nBases: AlephAlphaAsymmetricSemanticEmbedding\nThe symmetric version of the Aleph Alpha\u2019s semantic embeddings.\nThe main difference is that here, both the documents and\nqueries are embedded with a SemanticRepresentation.Symmetric\n.. rubric:: Example\nfrom aleph_alpha import AlephAlphaSymmetricSemanticEmbedding\nembeddings = AlephAlphaAsymmetricSemanticEmbedding(\n    normalize=True, compress_to_size=128\n)\ntext = \"This is a test text\"\ndoc_result = embeddings.embed_documents([text])\nquery_result = embeddings.embed_query(text)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aleph_alpha_api_key: Optional[str] = None\u00b6\nAPI key for Aleph Alpha API.\nparam compress_to_size: Optional[int] = None\u00b6\nShould the returned embeddings come back as an original 5120-dim vector,\nor should it be compressed to 128-dim.\nparam contextual_control_threshold: Optional[int] = None\u00b6\nAttention control parameters only apply to those tokens that have\nexplicitly been set in the request.\nparam control_log_additive: bool = True\u00b6\nApply controls on prompt items by adding the log(control_factor)\nto attention scores.\nparam host: str = 'https://api.aleph-alpha.com'\u00b6\nThe hostname of the API host.\nThe default one is \u201chttps://api.aleph-alpha.com\u201d)\nparam hosting: Optional[str] = None\u00b6\nDetermines in which datacenters the request may be processed.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.aleph_alpha.AlephAlphaSymmetricSemanticEmbedding.html"}
{"id": "7220ad1098bb-1", "text": "Determines in which datacenters the request may be processed.\nYou can either set the parameter to \u201caleph-alpha\u201d or omit it (defaulting to None).\nNot setting this value, or setting it to None, gives us maximal flexibility\nin processing your request in our\nown datacenters and on servers hosted with other providers.\nChoose this option for maximal availability.\nSetting it to \u201caleph-alpha\u201d allows us to only process the request\nin our own datacenters.\nChoose this option for maximal data privacy.\nparam model: str = 'luminous-base'\u00b6\nModel name to use.\nparam nice: bool = False\u00b6\nSetting this to True, will signal to the API that you intend to be\nnice to other users\nby de-prioritizing your request below concurrent ones.\nparam normalize: Optional[bool] = None\u00b6\nShould returned embeddings be normalized\nparam request_timeout_seconds: int = 305\u00b6\nClient timeout that will be set for HTTP requests in the\nrequests library\u2019s API calls.\nServer will close all requests after 300 seconds with an internal server error.\nparam total_retries: int = 8\u00b6\nThe number of retries made in case requests fail with certain retryable\nstatus codes. If the last\nretry fails a corresponding exception is raised. Note, that between retries\nan exponential backoff\nis applied, starting with 0.5 s after the first retry and doubling for each\nretry made. So with the\ndefault setting of 8 retries a total wait time of 63.5 s is added between\nthe retries.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.aleph_alpha.AlephAlphaSymmetricSemanticEmbedding.html"}
{"id": "7220ad1098bb-2", "text": "Asynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCall out to Aleph Alpha\u2019s Document endpoint.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.aleph_alpha.AlephAlphaSymmetricSemanticEmbedding.html"}
{"id": "7220ad1098bb-3", "text": "Returns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to Aleph Alpha\u2019s asymmetric, query embedding endpoint\n:param text: The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.aleph_alpha.AlephAlphaSymmetricSemanticEmbedding.html"}
{"id": "7220ad1098bb-4", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using AlephAlphaSymmetricSemanticEmbedding\u00b6\nAleph Alpha", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.aleph_alpha.AlephAlphaSymmetricSemanticEmbedding.html"}
{"id": "a76afdcb88d0-0", "text": "langchain.embeddings.baidu_qianfan_endpoint.QianfanEmbeddingsEndpoint\u00b6\nclass langchain.embeddings.baidu_qianfan_endpoint.QianfanEmbeddingsEndpoint[source]\u00b6\nBases: BaseModel, Embeddings\nBaidu Qianfan Embeddings embedding models.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam chunk_size: int = 16\u00b6\nChunk size when multiple texts are input\nparam client: Any = None\u00b6\nQianfan client\nparam endpoint: str = ''\u00b6\nEndpoint of the Qianfan Embedding, required if custom model used.\nparam max_retries: int = 5\u00b6\nMax reties times\nparam model: str = 'Embedding-V1'\u00b6\nModel name\nyou could get from https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu\nfor now, we support Embedding-V1 and\n- Embedding-V1 \uff08\u9ed8\u8ba4\u6a21\u578b\uff09\n- bge-large-en\n- bge-large-zh\npreset models are mapping to an endpoint.\nmodel will be ignored if endpoint is set\nparam qianfan_ak: Optional[str] = None\u00b6\nQianfan application apikey\nparam qianfan_sk: Optional[str] = None\u00b6\nQianfan application secretkey\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float][source]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.baidu_qianfan_endpoint.QianfanEmbeddingsEndpoint.html"}
{"id": "a76afdcb88d0-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbeds a list of text documents using the AutoVOT algorithm.\nParameters\ntexts (List[str]) \u2013 A list of text documents to embed.\nReturns\nA list of embeddings for each document in the input list.Each embedding is represented as a list of float values.\nReturn type\nList[List[float]]\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed query text.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.baidu_qianfan_endpoint.QianfanEmbeddingsEndpoint.html"}
{"id": "a76afdcb88d0-2", "text": "embed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed query text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using QianfanEmbeddingsEndpoint\u00b6\nBaidu Qianfan", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.baidu_qianfan_endpoint.QianfanEmbeddingsEndpoint.html"}
{"id": "9d396e409990-0", "text": "langchain.embeddings.deepinfra.DeepInfraEmbeddings\u00b6\nclass langchain.embeddings.deepinfra.DeepInfraEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nDeep Infra\u2019s embedding inference service.\nTo use, you should have the\nenvironment variable DEEPINFRA_API_TOKEN set with your API token, or pass\nit as a named parameter to the constructor.\nThere are multiple embeddings models available,\nsee https://deepinfra.com/models?type=embeddings.\nExample\nfrom langchain.embeddings import DeepInfraEmbeddings\ndeepinfra_emb = DeepInfraEmbeddings(\n    model_id=\"sentence-transformers/clip-ViT-B-32\",\n    deepinfra_api_token=\"my-api-key\"\n)\nr1 = deepinfra_emb.embed_documents(\n    [\n        \"Alpha is the first letter of Greek alphabet\",\n        \"Beta is the second letter of Greek alphabet\",\n    ]\n)\nr2 = deepinfra_emb.embed_query(\n    \"What is the second letter of Greek alphabet\"\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam deepinfra_api_token: Optional[str] = None\u00b6\nparam embed_instruction: str = 'passage: '\u00b6\nInstruction used to embed documents.\nparam model_id: str = 'sentence-transformers/clip-ViT-B-32'\u00b6\nEmbeddings model to use.\nparam model_kwargs: Optional[dict] = None\u00b6\nOther model keyword args\nparam normalize: bool = False\u00b6\nwhether to normalize the computed embeddings\nparam query_instruction: str = 'query: '\u00b6\nInstruction used to embed the query.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.deepinfra.DeepInfraEmbeddings.html"}
{"id": "9d396e409990-1", "text": "Asynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed documents using a Deep Infra deployed embedding model.\nParameters", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.deepinfra.DeepInfraEmbeddings.html"}
{"id": "9d396e409990-2", "text": "Embed documents using a Deep Infra deployed embedding model.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed a query using a Deep Infra deployed embedding model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.deepinfra.DeepInfraEmbeddings.html"}
{"id": "9d396e409990-3", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using DeepInfraEmbeddings\u00b6\nDeepInfra", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.deepinfra.DeepInfraEmbeddings.html"}
{"id": "8013c4d16a4c-0", "text": "langchain.embeddings.gradient_ai.GradientEmbeddings\u00b6\nclass langchain.embeddings.gradient_ai.GradientEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nGradient.ai Embedding models.\nGradientLLM is a class to interact with Embedding Models on gradient.ai\nTo use, set the environment variable GRADIENT_ACCESS_TOKEN with your\nAPI token and GRADIENT_WORKSPACE_ID for your gradient workspace,\nor alternatively provide them as keywords to the constructor of this class.\nExample\nfrom langchain.embeddings import GradientEmbeddings\nGradientEmbeddings(\n    model=\"bge-large\",\n    gradient_workspace_id=\"12345614fc0_workspace\",\n    gradient_access_token=\"gradientai-access_token\",\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam client: Any = None\u00b6\nGradient client.\nparam gradient_access_token: Optional[str] = None\u00b6\ngradient.ai API Token, which can be generated by going to\nhttps://auth.gradient.ai/select-workspace\nand selecting \u201cAccess tokens\u201d under the profile drop-down.\nparam gradient_api_url: str = 'https://api.gradient.ai/api'\u00b6\nEndpoint URL to use.\nparam gradient_workspace_id: Optional[str] = None\u00b6\nUnderlying gradient.ai workspace_id.\nparam model: str [Required]\u00b6\nUnderlying gradient.ai model id.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nAsync call out to Gradient\u2019s embedding endpoint.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nasync aembed_query(text: str) \u2192 List[float][source]\u00b6\nAsync call out to Gradient\u2019s embedding endpoint.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.gradient_ai.GradientEmbeddings.html"}
{"id": "8013c4d16a4c-1", "text": "Parameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCall out to Gradient\u2019s embedding endpoint.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.gradient_ai.GradientEmbeddings.html"}
{"id": "8013c4d16a4c-2", "text": "Parameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to Gradient\u2019s embedding endpoint.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.gradient_ai.GradientEmbeddings.html"}
{"id": "8013c4d16a4c-3", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.gradient_ai.GradientEmbeddings.html"}
{"id": "134ecb966fd4-0", "text": "langchain.embeddings.elasticsearch.ElasticsearchEmbeddings\u00b6\nclass langchain.embeddings.elasticsearch.ElasticsearchEmbeddings(client: MlClient, model_id: str, *, input_field: str = 'text_field')[source]\u00b6\nElasticsearch embedding models.\nThis class provides an interface to generate embeddings using a model deployed\nin an Elasticsearch cluster. It requires an Elasticsearch connection object\nand the model_id of the model deployed in the cluster.\nIn Elasticsearch you need to have an embedding model loaded and deployed.\n- https://www.elastic.co/guide/en/elasticsearch/reference/current/infer-trained-model.html\n- https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-deploy-models.html\nInitialize the ElasticsearchEmbeddings instance.\nParameters\nclient (MlClient) \u2013 An Elasticsearch ML client object.\nmodel_id (str) \u2013 The model_id of the model deployed in the Elasticsearch\ncluster.\ninput_field (str) \u2013 The name of the key for the input text field in the\ndocument. Defaults to \u2018text_field\u2019.\nMethods\n__init__(client,\u00a0model_id,\u00a0*[,\u00a0input_field])\nInitialize the ElasticsearchEmbeddings instance.\naembed_documents(texts)\nAsynchronous Embed search docs.\naembed_query(text)\nAsynchronous Embed query text.\nembed_documents(texts)\nGenerate embeddings for a list of documents.\nembed_query(text)\nGenerate an embedding for a single query text.\nfrom_credentials(model_id,\u00a0*[,\u00a0es_cloud_id,\u00a0...])\nInstantiate embeddings from Elasticsearch credentials.\nfrom_es_connection(model_id,\u00a0es_connection)\nInstantiate embeddings from an existing Elasticsearch connection.\n__init__(client: MlClient, model_id: str, *, input_field: str = 'text_field')[source]\u00b6\nInitialize the ElasticsearchEmbeddings instance.\nParameters", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.elasticsearch.ElasticsearchEmbeddings.html"}
{"id": "134ecb966fd4-1", "text": "Initialize the ElasticsearchEmbeddings instance.\nParameters\nclient (MlClient) \u2013 An Elasticsearch ML client object.\nmodel_id (str) \u2013 The model_id of the model deployed in the Elasticsearch\ncluster.\ninput_field (str) \u2013 The name of the key for the input text field in the\ndocument. Defaults to \u2018text_field\u2019.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nGenerate embeddings for a list of documents.\nParameters\ntexts (List[str]) \u2013 A list of document text strings to generate embeddings\nfor.\nReturns\nA list of embeddings, one for each document in the inputlist.\nReturn type\nList[List[float]]\nembed_query(text: str) \u2192 List[float][source]\u00b6\nGenerate an embedding for a single query text.\nParameters\ntext (str) \u2013 The query text to generate an embedding for.\nReturns\nThe embedding for the input query text.\nReturn type\nList[float]\nclassmethod from_credentials(model_id: str, *, es_cloud_id: Optional[str] = None, es_user: Optional[str] = None, es_password: Optional[str] = None, input_field: str = 'text_field') \u2192 ElasticsearchEmbeddings[source]\u00b6\nInstantiate embeddings from Elasticsearch credentials.\nParameters\nmodel_id (str) \u2013 The model_id of the model deployed in the Elasticsearch\ncluster.\ninput_field (str) \u2013 The name of the key for the input text field in the\ndocument. Defaults to \u2018text_field\u2019.\nes_cloud_id \u2013 (str, optional): The Elasticsearch cloud ID to connect to.\nes_user \u2013 (str, optional): Elasticsearch username.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.elasticsearch.ElasticsearchEmbeddings.html"}
{"id": "134ecb966fd4-2", "text": "es_user \u2013 (str, optional): Elasticsearch username.\nes_password \u2013 (str, optional): Elasticsearch password.\nExample\nfrom langchain.embeddings import ElasticsearchEmbeddings\n# Define the model ID and input field name (if different from default)\nmodel_id = \"your_model_id\"\n# Optional, only if different from 'text_field'\ninput_field = \"your_input_field\"\n# Credentials can be passed in two ways. Either set the env vars\n# ES_CLOUD_ID, ES_USER, ES_PASSWORD and they will be automatically\n# pulled in, or pass them in directly as kwargs.\nembeddings = ElasticsearchEmbeddings.from_credentials(\n    model_id,\n    input_field=input_field,\n    # es_cloud_id=\"foo\",\n    # es_user=\"bar\",\n    # es_password=\"baz\",\n)\ndocuments = [\n    \"This is an example document.\",\n    \"Another example document to generate embeddings for.\",\n]\nembeddings_generator.embed_documents(documents)\nclassmethod from_es_connection(model_id: str, es_connection: Elasticsearch, input_field: str = 'text_field') \u2192 ElasticsearchEmbeddings[source]\u00b6\nInstantiate embeddings from an existing Elasticsearch connection.\nThis method provides a way to create an instance of the ElasticsearchEmbeddings\nclass using an existing Elasticsearch connection. The connection object is used\nto create an MlClient, which is then used to initialize the\nElasticsearchEmbeddings instance.\nArgs:\nmodel_id (str): The model_id of the model deployed in the Elasticsearch cluster.\nes_connection (elasticsearch.Elasticsearch): An existing Elasticsearch\nconnection object. input_field (str, optional): The name of the key for the\ninput text field in the document. Defaults to \u2018text_field\u2019.\nReturns:\nElasticsearchEmbeddings: An instance of the ElasticsearchEmbeddings class.\nExample\nfrom elasticsearch import Elasticsearch", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.elasticsearch.ElasticsearchEmbeddings.html"}
{"id": "134ecb966fd4-3", "text": "Example\nfrom elasticsearch import Elasticsearch\nfrom langchain.embeddings import ElasticsearchEmbeddings\n# Define the model ID and input field name (if different from default)\nmodel_id = \"your_model_id\"\n# Optional, only if different from 'text_field'\ninput_field = \"your_input_field\"\n# Create Elasticsearch connection\nes_connection = Elasticsearch(\n    hosts=[\"localhost:9200\"], http_auth=(\"user\", \"password\")\n)\n# Instantiate ElasticsearchEmbeddings using the existing connection\nembeddings = ElasticsearchEmbeddings.from_es_connection(\n    model_id,\n    es_connection,\n    input_field=input_field,\n)\ndocuments = [\n    \"This is an example document.\",\n    \"Another example document to generate embeddings for.\",\n]\nembeddings_generator.embed_documents(documents)\nExamples using ElasticsearchEmbeddings\u00b6\nElasticsearch", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.elasticsearch.ElasticsearchEmbeddings.html"}
{"id": "88c2af2b18f8-0", "text": "langchain.embeddings.mlflow_gateway.MlflowAIGatewayEmbeddings\u00b6\nclass langchain.embeddings.mlflow_gateway.MlflowAIGatewayEmbeddings[source]\u00b6\nBases: Embeddings, BaseModel\nWrapper around embeddings LLMs in the MLflow AI Gateway.\nTo use, you should have the mlflow[gateway] python package installed.\nFor more information, see https://mlflow.org/docs/latest/gateway/index.html.\nExample\nfrom langchain.embeddings import MlflowAIGatewayEmbeddings\nembeddings = MlflowAIGatewayEmbeddings(\n    gateway_uri=\"<your-mlflow-ai-gateway-uri>\",\n    route=\"<your-mlflow-ai-gateway-embeddings-route>\"\n)\nparam gateway_uri: Optional[str] = None\u00b6\nThe URI for the MLflow AI Gateway API.\nparam route: str [Required]\u00b6\nThe route to use for the MLflow AI Gateway API.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.mlflow_gateway.MlflowAIGatewayEmbeddings.html"}
{"id": "88c2af2b18f8-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed search docs.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed query text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.mlflow_gateway.MlflowAIGatewayEmbeddings.html"}
{"id": "88c2af2b18f8-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using MlflowAIGatewayEmbeddings\u00b6\nMLflow AI Gateway", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.mlflow_gateway.MlflowAIGatewayEmbeddings.html"}
{"id": "3efd7b8f1b42-0", "text": "langchain.embeddings.javelin_ai_gateway.JavelinAIGatewayEmbeddings\u00b6\nclass langchain.embeddings.javelin_ai_gateway.JavelinAIGatewayEmbeddings[source]\u00b6\nBases: Embeddings, BaseModel\nWrapper around embeddings LLMs in the Javelin AI Gateway.\nTo use, you should have the javelin_sdk python package installed.\nFor more information, see https://docs.getjavelin.io\nExample\nfrom langchain.embeddings import JavelinAIGatewayEmbeddings\nembeddings = JavelinAIGatewayEmbeddings(\n    gateway_uri=\"<javelin-ai-gateway-uri>\",\n    route=\"<your-javelin-gateway-embeddings-route>\"\n)\nparam client: Any = None\u00b6\njavelin client.\nparam gateway_uri: Optional[str] = None\u00b6\nThe URI for the Javelin AI Gateway API.\nparam javelin_api_key: Optional[str] = None\u00b6\nThe API key for the Javelin AI Gateway API.\nparam route: str [Required]\u00b6\nThe route to use for the Javelin AI Gateway API.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float][source]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.javelin_ai_gateway.JavelinAIGatewayEmbeddings.html"}
{"id": "3efd7b8f1b42-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed search docs.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed query text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.javelin_ai_gateway.JavelinAIGatewayEmbeddings.html"}
{"id": "3efd7b8f1b42-2", "text": "Embed query text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.javelin_ai_gateway.JavelinAIGatewayEmbeddings.html"}
{"id": "7066459d9973-0", "text": "langchain.embeddings.localai.LocalAIEmbeddings\u00b6\nclass langchain.embeddings.localai.LocalAIEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nLocalAI embedding models.\nSince LocalAI and OpenAI have 1:1 compatibility between APIs, this class\nuses the openai Python package\u2019s openai.Embedding as its client.\nThus, you should have the openai python package installed, and defeat\nthe environment variable OPENAI_API_KEY by setting to a random string.\nYou also need to specify OPENAI_API_BASE to point to your LocalAI\nservice endpoint.\nExample\nfrom langchain.embeddings import LocalAIEmbeddings\nopenai = LocalAIEmbeddings(\n    openai_api_key=\"random-string\",\n    openai_api_base=\"http://localhost:8080\"\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_special: Union[Literal['all'], Set[str]] = {}\u00b6\nparam chunk_size: int = 1000\u00b6\nMaximum number of texts to embed in each batch\nparam deployment: str = 'text-embedding-ada-002'\u00b6\nparam disallowed_special: Union[Literal['all'], Set[str], Sequence[str]] = 'all'\u00b6\nparam embedding_ctx_length: int = 8191\u00b6\nThe maximum number of tokens to embed at once.\nparam headers: Any = None\u00b6\nparam max_retries: int = 6\u00b6\nMaximum number of retries to make when generating.\nparam model: str = 'text-embedding-ada-002'\u00b6\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam openai_api_base: Optional[str] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.localai.LocalAIEmbeddings.html"}
{"id": "7066459d9973-1", "text": "param openai_api_base: Optional[str] = None\u00b6\nparam openai_api_key: Optional[str] = None\u00b6\nparam openai_api_version: Optional[str] = None\u00b6\nparam openai_organization: Optional[str] = None\u00b6\nparam openai_proxy: Optional[str] = None\u00b6\nparam request_timeout: Optional[Union[float, Tuple[float, float]]] = None\u00b6\nTimeout in seconds for the LocalAI request.\nparam show_progress_bar: bool = False\u00b6\nWhether to show a progress bar when embedding.\nasync aembed_documents(texts: List[str], chunk_size: Optional[int] = 0) \u2192 List[List[float]][source]\u00b6\nCall out to LocalAI\u2019s embedding endpoint async for embedding search docs.\nParameters\ntexts \u2013 The list of texts to embed.\nchunk_size \u2013 The chunk size of embeddings. If None, will use the chunk size\nspecified by the class.\nReturns\nList of embeddings, one for each text.\nasync aembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to LocalAI\u2019s embedding endpoint async for embedding query text.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbedding for the text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.localai.LocalAIEmbeddings.html"}
{"id": "7066459d9973-2", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str], chunk_size: Optional[int] = 0) \u2192 List[List[float]][source]\u00b6\nCall out to LocalAI\u2019s embedding endpoint for embedding search docs.\nParameters\ntexts \u2013 The list of texts to embed.\nchunk_size \u2013 The chunk size of embeddings. If None, will use the chunk size\nspecified by the class.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to LocalAI\u2019s embedding endpoint for embedding query text.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbedding for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.localai.LocalAIEmbeddings.html"}
{"id": "7066459d9973-3", "text": "Embedding for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using LocalAIEmbeddings\u00b6\nLocalAI", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.localai.LocalAIEmbeddings.html"}
{"id": "9f51eae3c9f8-0", "text": "langchain.embeddings.cohere.CohereEmbeddings\u00b6\nclass langchain.embeddings.cohere.CohereEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nCohere embedding models.\nTo use, you should have the cohere python package installed, and the\nenvironment variable COHERE_API_KEY set with your API key or pass it\nas a named parameter to the constructor.\nExample\nfrom langchain.embeddings import CohereEmbeddings\ncohere = CohereEmbeddings(\n    model=\"embed-english-light-v3.0\", cohere_api_key=\"my-api-key\"\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam async_client: Any = None\u00b6\nCohere async client.\nparam client: Any = None\u00b6\nCohere client.\nparam cohere_api_key: Optional[str] = None\u00b6\nparam max_retries: Optional[int] = None\u00b6\nMaximum number of retries to make when generating.\nparam model: str = 'embed-english-v2.0'\u00b6\nModel name to use.\nparam request_timeout: Optional[float] = None\u00b6\nTimeout in seconds for the Cohere API request.\nparam truncate: Optional[str] = None\u00b6\nTruncate embeddings that are too long from start or end (\u201cNONE\u201d|\u201dSTART\u201d|\u201dEND\u201d)\nparam user_agent: str = 'langchain'\u00b6\nIdentifier for the application making the request.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nAsync call out to Cohere\u2019s embedding endpoint.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nasync aembed_query(text: str) \u2192 List[float][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.cohere.CohereEmbeddings.html"}
{"id": "9f51eae3c9f8-1", "text": "async aembed_query(text: str) \u2192 List[float][source]\u00b6\nAsync call out to Cohere\u2019s embedding endpoint.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.cohere.CohereEmbeddings.html"}
{"id": "9f51eae3c9f8-2", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCall out to Cohere\u2019s embedding endpoint.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to Cohere\u2019s embedding endpoint.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.cohere.CohereEmbeddings.html"}
{"id": "9f51eae3c9f8-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using CohereEmbeddings\u00b6\nCohere\nMemory in the Multi-Input Chain\nRouter", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.cohere.CohereEmbeddings.html"}
{"id": "f7d84ad969b8-0", "text": "langchain.embeddings.voyageai.embed_with_retry\u00b6\nlangchain.embeddings.voyageai.embed_with_retry(embeddings: VoyageEmbeddings, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the embedding call.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.voyageai.embed_with_retry.html"}
{"id": "abf094fc7e71-0", "text": "langchain.embeddings.awa.AwaEmbeddings\u00b6\nclass langchain.embeddings.awa.AwaEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nEmbedding documents and queries with Awa DB.\nclient\u00b6\nThe AwaEmbedding client.\nmodel\u00b6\nThe name of the model used for embedding.\nDefault is \u201call-mpnet-base-v2\u201d.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam model: str = 'all-mpnet-base-v2'\u00b6\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.awa.AwaEmbeddings.html"}
{"id": "abf094fc7e71-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed a list of documents using AwaEmbedding.\nParameters\ntexts \u2013 The list of texts need to be embedded\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCompute query embeddings using AwaEmbedding.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.awa.AwaEmbeddings.html"}
{"id": "abf094fc7e71-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nset_model(model_name: str) \u2192 None[source]\u00b6\nSet the model used for embedding.\nThe default model used is all-mpnet-base-v2\nParameters\nmodel_name \u2013 A string which represents the name of model.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using AwaEmbeddings\u00b6\nAwaDB", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.awa.AwaEmbeddings.html"}
{"id": "84e87e8b1703-0", "text": "langchain.embeddings.clarifai.ClarifaiEmbeddings\u00b6\nclass langchain.embeddings.clarifai.ClarifaiEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nClarifai embedding models.\nTo use, you should have the clarifai python package installed, and the\nenvironment variable CLARIFAI_PAT set with your personal access token or pass it\nas a named parameter to the constructor.\nExample\nfrom langchain.embeddings import ClarifaiEmbeddings\nclarifai = ClarifaiEmbeddings(\n    model=\"embed-english-light-v3.0\", clarifai_api_key=\"my-api-key\"\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_base: str = 'https://api.clarifai.com'\u00b6\nparam app_id: Optional[str] = None\u00b6\nClarifai application id to use.\nparam model_id: Optional[str] = None\u00b6\nModel id to use.\nparam model_version_id: Optional[str] = None\u00b6\nModel version id to use.\nparam pat: Optional[str] = None\u00b6\nClarifai personal access token to use.\nparam stub: Any = None\u00b6\nClarifai stub.\nparam userDataObject: Any = None\u00b6\nClarifai user data object.\nparam user_id: Optional[str] = None\u00b6\nClarifai user id to use.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.clarifai.ClarifaiEmbeddings.html"}
{"id": "84e87e8b1703-1", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCall out to Clarifai\u2019s embedding models.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to Clarifai\u2019s embedding models.\nParameters", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.clarifai.ClarifaiEmbeddings.html"}
{"id": "84e87e8b1703-2", "text": "Call out to Clarifai\u2019s embedding models.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using ClarifaiEmbeddings\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.clarifai.ClarifaiEmbeddings.html"}
{"id": "84e87e8b1703-3", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nExamples using ClarifaiEmbeddings\u00b6\nClarifai", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.clarifai.ClarifaiEmbeddings.html"}
{"id": "56ddad8e92bd-0", "text": "langchain.embeddings.jina.JinaEmbeddings\u00b6\nclass langchain.embeddings.jina.JinaEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nJina embedding models.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam jina_api_url: str = 'https://api.clip.jina.ai/api/v1/models/'\u00b6\nparam jina_auth_token: Optional[str] = None\u00b6\nparam model_name: str = 'ViT-B-32::openai'\u00b6\nModel name to use.\nparam request_headers: Optional[dict] = None\u00b6\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.jina.JinaEmbeddings.html"}
{"id": "56ddad8e92bd-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCall out to Jina\u2019s embedding endpoint.\n:param texts: The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to Jina\u2019s embedding endpoint.\n:param text: The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.jina.JinaEmbeddings.html"}
{"id": "56ddad8e92bd-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using JinaEmbeddings\u00b6\nJina", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.jina.JinaEmbeddings.html"}
{"id": "f89b83fc1d56-0", "text": "langchain.embeddings.localai.embed_with_retry\u00b6\nlangchain.embeddings.localai.embed_with_retry(embeddings: LocalAIEmbeddings, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the embedding call.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.localai.embed_with_retry.html"}
{"id": "ec2a2345e25b-0", "text": "langchain.embeddings.huggingface.HuggingFaceInstructEmbeddings\u00b6\nclass langchain.embeddings.huggingface.HuggingFaceInstructEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nWrapper around sentence_transformers embedding models.\nTo use, you should have the sentence_transformers\nand InstructorEmbedding python packages installed.\nExample\nfrom langchain.embeddings import HuggingFaceInstructEmbeddings\nmodel_name = \"hkunlp/instructor-large\"\nmodel_kwargs = {'device': 'cpu'}\nencode_kwargs = {'normalize_embeddings': True}\nhf = HuggingFaceInstructEmbeddings(\n    model_name=model_name,\n    model_kwargs=model_kwargs,\n    encode_kwargs=encode_kwargs\n)\nInitialize the sentence_transformer.\nparam cache_folder: Optional[str] = None\u00b6\nPath to store models.\nCan be also set by SENTENCE_TRANSFORMERS_HOME environment variable.\nparam embed_instruction: str = 'Represent the document for retrieval: '\u00b6\nInstruction to use for embedding documents.\nparam encode_kwargs: Dict[str, Any] [Optional]\u00b6\nKeyword arguments to pass when calling the encode method of the model.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nKeyword arguments to pass to the model.\nparam model_name: str = 'hkunlp/instructor-large'\u00b6\nModel name to use.\nparam query_instruction: str = 'Represent the question for retrieving supporting documents: '\u00b6\nInstruction to use for embedding query.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceInstructEmbeddings.html"}
{"id": "ec2a2345e25b-1", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCompute doc embeddings using a HuggingFace instruct model.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCompute query embeddings using a HuggingFace instruct model.\nParameters", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceInstructEmbeddings.html"}
{"id": "ec2a2345e25b-2", "text": "Compute query embeddings using a HuggingFace instruct model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceInstructEmbeddings.html"}
{"id": "ec2a2345e25b-3", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nExamples using HuggingFaceInstructEmbeddings\u00b6\nInstructEmbeddings\nVector SQL Retriever with MyScale", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceInstructEmbeddings.html"}
{"id": "f8cdbb95d51c-0", "text": "langchain.embeddings.voyageai.VoyageEmbeddings\u00b6\nclass langchain.embeddings.voyageai.VoyageEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nVoyage embedding models.\nTo use, you should have the environment variable VOYAGE_API_KEY set with\nyour API key or pass it as a named parameter to the constructor.\nExample\nfrom langchain.embeddings import VoyageEmbeddings\nvoyage = VoyageEmbeddings(voyage_api_key=\"your-api-key\")\ntext = \"This is a test query.\"\nquery_result = voyage.embed_query(text)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam batch_size: int = 8\u00b6\nMaximum number of texts to embed in each API request.\nparam max_retries: int = 6\u00b6\nMaximum number of retries to make when generating.\nparam model: str = 'voyage-01'\u00b6\nparam request_timeout: Optional[Union[float, Tuple[float, float]]] = None\u00b6\nTimeout in seconds for the API request.\nparam show_progress_bar: bool = False\u00b6\nWhether to show a progress bar when embedding. Must have tqdm installed if set\nto True.\nparam voyage_api_base: str = 'https://api.voyageai.com/v1/embeddings'\u00b6\nparam voyage_api_key: Optional[pydantic.types.SecretStr] = None\u00b6\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.voyageai.VoyageEmbeddings.html"}
{"id": "f8cdbb95d51c-1", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCall out to Voyage Embedding endpoint for embedding search docs.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to Voyage Embedding endpoint for embedding query text.\nParameters", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.voyageai.VoyageEmbeddings.html"}
{"id": "f8cdbb95d51c-2", "text": "Call out to Voyage Embedding endpoint for embedding query text.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbedding for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.voyageai.VoyageEmbeddings.html"}
{"id": "c880b77cd637-0", "text": "langchain.embeddings.openai.OpenAIEmbeddings\u00b6\nclass langchain.embeddings.openai.OpenAIEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nOpenAI embedding models.\nTo use, you should have the openai python package installed, and the\nenvironment variable OPENAI_API_KEY set with your API key or pass it\nas a named parameter to the constructor.\nExample\nfrom langchain.embeddings import OpenAIEmbeddings\nopenai = OpenAIEmbeddings(openai_api_key=\"my-api-key\")\nIn order to use the library with Microsoft Azure endpoints, you need to set\nthe OPENAI_API_TYPE, OPENAI_API_BASE, OPENAI_API_KEY and OPENAI_API_VERSION.\nThe OPENAI_API_TYPE must be set to \u2018azure\u2019 and the others correspond to\nthe properties of your endpoint.\nIn addition, the deployment name must be passed as the model parameter.\nExample\nimport os\nos.environ[\"OPENAI_API_TYPE\"] = \"azure\"\nos.environ[\"OPENAI_API_BASE\"] = \"https://<your-endpoint.openai.azure.com/\"\nos.environ[\"OPENAI_API_KEY\"] = \"your AzureOpenAI key\"\nos.environ[\"OPENAI_API_VERSION\"] = \"2023-05-15\"\nos.environ[\"OPENAI_PROXY\"] = \"http://your-corporate-proxy:8080\"\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings(\n    deployment=\"your-embeddings-deployment-name\",\n    model=\"your-embeddings-model-name\",\n    openai_api_base=\"https://your-endpoint.openai.azure.com/\",\n    openai_api_type=\"azure\",\n)\ntext = \"This is a test query.\"\nquery_result = embeddings.embed_query(text)\nCreate a new model by parsing and validating input data from keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.openai.OpenAIEmbeddings.html"}
{"id": "c880b77cd637-1", "text": "Create a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_special: Union[Literal['all'], Set[str]] = {}\u00b6\nparam chunk_size: int = 1000\u00b6\nMaximum number of texts to embed in each batch\nparam default_headers: Optional[Mapping[str, str]] = None\u00b6\nparam default_query: Optional[Mapping[str, object]] = None\u00b6\nparam deployment: Optional[str] = 'text-embedding-ada-002'\u00b6\nparam disallowed_special: Union[Literal['all'], Set[str], Sequence[str]] = 'all'\u00b6\nparam embedding_ctx_length: int = 8191\u00b6\nThe maximum number of tokens to embed at once.\nparam headers: Any = None\u00b6\nparam http_client: Optional[Any] = None\u00b6\nOptional httpx.Client.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.\nparam model: str = 'text-embedding-ada-002'\u00b6\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Optional[str] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var OPENAI_API_KEY if not provided.\nparam openai_api_type: Optional[str] = None\u00b6\nparam openai_api_version: Optional[str] = None (alias 'api_version')\u00b6\nAutomatically inferred from env var OPENAI_API_VERSION if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.openai.OpenAIEmbeddings.html"}
{"id": "c880b77cd637-2", "text": "param openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam request_timeout: Optional[Union[float, Tuple[float, float], Any]] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam show_progress_bar: bool = False\u00b6\nWhether to show a progress bar when embedding.\nparam skip_empty: bool = False\u00b6\nWhether to skip empty strings when embedding or raise an error.\nDefaults to not skipping.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nasync aembed_documents(texts: List[str], chunk_size: Optional[int] = 0) \u2192 List[List[float]][source]\u00b6\nCall out to OpenAI\u2019s embedding endpoint async for embedding search docs.\nParameters\ntexts \u2013 The list of texts to embed.\nchunk_size \u2013 The chunk size of embeddings. If None, will use the chunk size\nspecified by the class.\nReturns\nList of embeddings, one for each text.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.openai.OpenAIEmbeddings.html"}
{"id": "c880b77cd637-3", "text": "specified by the class.\nReturns\nList of embeddings, one for each text.\nasync aembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to OpenAI\u2019s embedding endpoint async for embedding query text.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbedding for the text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.openai.OpenAIEmbeddings.html"}
{"id": "c880b77cd637-4", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str], chunk_size: Optional[int] = 0) \u2192 List[List[float]][source]\u00b6\nCall out to OpenAI\u2019s embedding endpoint for embedding search docs.\nParameters\ntexts \u2013 The list of texts to embed.\nchunk_size \u2013 The chunk size of embeddings. If None, will use the chunk size\nspecified by the class.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to OpenAI\u2019s embedding endpoint for embedding query text.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbedding for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.openai.OpenAIEmbeddings.html"}
{"id": "c880b77cd637-5", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using OpenAIEmbeddings\u00b6\nOpenAI\nAzureOpenAI\nRePhraseQueryRetriever\nCohere Reranker\nkNN\nDocArray Retriever\nSVM\nPinecone Hybrid Search\nLOTR (Merger Retriever)\nXata chat memory\nConfident\nAzure OpenAI\nDocument Comparison\nVectorstore\nLanceDB\nWeaviate\nXata\nRedis\nPGVector\nRockset\nDingoDB\nZilliz\nSingleStoreDB\nTypesense\nAtlas\nActiveloop Deep Lake\nNeo4j Vector Index\nChroma\nAlibaba Cloud OpenSearch\nBaidu Cloud VectorSearch\nStarRocks\nscikit-learn\nDocArray HnswSearch\nMyScale\nClickHouse\nQdrant\nTigris\nSupabase (Postgres)\nOpenSearch\nPinecone\nAzure Cognitive Search\nCassandra\nUSearch\nMilvus\nElasticsearch\nDocArray InMemorySearch\nPostgres Embedding\nFaiss\nEpsilla\nAnalyticDB\nHologres\nMongoDB Atlas\nMeilisearch\nLoading documents from a YouTube url", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.openai.OpenAIEmbeddings.html"}
{"id": "c880b77cd637-6", "text": "Hologres\nMongoDB Atlas\nMeilisearch\nLoading documents from a YouTube url\nPsychic\nDocugami\nLLM Caching integrations\nSet env var OPENAI_API_KEY or load from a .env file:\nSet env var OPENAI_API_KEY or load from a .env file\nQuestion Answering\nPerform context-aware text splitting\nConversational Retrieval Agent\nRetrieve from vector stores directly\nRetrieve as you generate with FLARE\nImprove document indexing with HyDE\nAnalysis of Twitter the-algorithm source code with LangChain, GPT4 and Activeloop\u2019s Deep Lake\nUse LangChain, GPT and Activeloop\u2019s Deep Lake to work with code base\nStructure answers with OpenAI functions\nQA using Activeloop\u2019s DeepLake\nAgents\nAutoGPT\nBabyAGI User Guide\nBabyAGI with Tools\n!pip install bs4\nPlug-and-Plai\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nCustom Agent with PlugIn Retrieval\nGenerative Agents in LangChain\nSQL\nIndexing\nCaching\nMultiVector Retriever\nMultiQueryRetriever\nParent Document Retriever\nWebResearchRetriever\nSupabase\nDeep Lake\nMemory in the Multi-Input Chain\nCombine agents and vector stores\nCustom agent with tool retrieval\nSelect by maximal marginal relevance (MMR)\nFew-shot examples for chat models\nLoading from LangChainHub\nFirst we add a step to load memory", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.openai.OpenAIEmbeddings.html"}
{"id": "351cc964302b-0", "text": "langchain.embeddings.edenai.EdenAiEmbeddings\u00b6\nclass langchain.embeddings.edenai.EdenAiEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nEdenAI embedding.\nenvironment variable EDENAI_API_KEY set with your API key, or pass\nit as a named parameter.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam edenai_api_key: Optional[str] = None\u00b6\nEdenAI API Token\nparam model: Optional[str] = None\u00b6\nmodel name for above provider (eg: \u2018text-davinci-003\u2019 for openai)\navailable models are shown on https://docs.edenai.co/ under \u2018available providers\u2019\nparam provider: str = 'openai'\u00b6\nembedding provider to use (eg: openai,google etc.)\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.edenai.EdenAiEmbeddings.html"}
{"id": "351cc964302b-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed a list of documents using EdenAI.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed a query using EdenAI.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nstatic get_user_agent() \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.edenai.EdenAiEmbeddings.html"}
{"id": "351cc964302b-2", "text": "static get_user_agent() \u2192 str[source]\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using EdenAiEmbeddings\u00b6\nEDEN AI", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.edenai.EdenAiEmbeddings.html"}
{"id": "fc9d3bd8bdf8-0", "text": "langchain.embeddings.dashscope.embed_with_retry\u00b6\nlangchain.embeddings.dashscope.embed_with_retry(embeddings: DashScopeEmbeddings, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the embedding call.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.dashscope.embed_with_retry.html"}
{"id": "f5913242cbee-0", "text": "langchain.embeddings.fastembed.FastEmbedEmbeddings\u00b6\nclass langchain.embeddings.fastembed.FastEmbedEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nQdrant FastEmbedding models.\nFastEmbed is a lightweight, fast, Python library built for embedding generation.\nSee more documentation at:\n* https://github.com/qdrant/fastembed/\n* https://qdrant.github.io/fastembed/\nTo use this class, you must install the fastembed Python package.\npip install fastembed\n.. rubric:: Example\nfrom langchain.embeddings import FastEmbedEmbeddings\nfastembed = FastEmbedEmbeddings()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache_dir: Optional[str] = None\u00b6\nThe path to the cache directory.\nDefaults to local_cache in the parent directory\nparam doc_embed_type: Literal['default', 'passage'] = 'default'\u00b6\nType of embedding to use for documents\n\u201cdefault\u201d: Uses FastEmbed\u2019s default embedding method\n\u201cpassage\u201d: Prefixes the text with \u201cpassage\u201d before embedding.\nparam max_length: int = 512\u00b6\nThe maximum number of tokens. Defaults to 512.\nUnknown behavior for values > 512.\nparam model_name: str = 'BAAI/bge-small-en-v1.5'\u00b6\nName of the FastEmbedding model to use\nDefaults to \u201cBAAI/bge-small-en-v1.5\u201d\nFind the list of supported models at\nhttps://qdrant.github.io/fastembed/examples/Supported_Models/\nparam threads: Optional[int] = None\u00b6\nThe number of threads single onnxruntime session can use.\nDefaults to None\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.fastembed.FastEmbedEmbeddings.html"}
{"id": "f5913242cbee-1", "text": "async aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.fastembed.FastEmbedEmbeddings.html"}
{"id": "f5913242cbee-2", "text": "embed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nGenerate embeddings for documents using FastEmbed.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nGenerate query embeddings using FastEmbed.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.fastembed.FastEmbedEmbeddings.html"}
{"id": "f5913242cbee-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.fastembed.FastEmbedEmbeddings.html"}
{"id": "625b1403ed05-0", "text": "langchain.embeddings.google_palm.embed_with_retry\u00b6\nlangchain.embeddings.google_palm.embed_with_retry(embeddings: GooglePalmEmbeddings, *args: Any, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.google_palm.embed_with_retry.html"}
{"id": "1c9484528b0a-0", "text": "langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings\u00b6\nclass langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings[source]\u00b6\nBases: SelfHostedEmbeddings\nHuggingFace embedding models on self-hosted remote hardware.\nSupported hardware includes auto-launched instances on AWS, GCP, Azure,\nand Lambda, as well as servers specified\nby IP address and SSH credentials (such as on-prem, or another cloud\nlike Paperspace, Coreweave, etc.).\nTo use, you should have the runhouse python package installed.\nExample\nfrom langchain.embeddings import SelfHostedHuggingFaceEmbeddings\nimport runhouse as rh\nmodel_name = \"sentence-transformers/all-mpnet-base-v2\"\ngpu = rh.cluster(name=\"rh-a10x\", instance_type=\"A100:1\")\nhf = SelfHostedHuggingFaceEmbeddings(model_name=model_name, hardware=gpu)\nInitialize the remote inference function.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam hardware: Any = None\u00b6\nRemote hardware to send the inference function to.\nparam inference_fn: Callable = <function _embed_documents>\u00b6\nInference function to extract the embeddings.\nparam inference_kwargs: Any = None\u00b6\nAny kwargs to pass to the model\u2019s inference function.\nparam load_fn_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model load function.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_id: str = 'sentence-transformers/all-mpnet-base-v2'\u00b6\nModel name to use.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-1", "text": "Model name to use.\nparam model_load_fn: Callable = <function load_embedding_model>\u00b6\nFunction to load the model remotely on the server.\nparam model_reqs: List[str] = ['./', 'sentence_transformers', 'torch']\u00b6\nRequirements to install on hardware to inference the model.\nparam pipeline_ref: Any = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-2", "text": "Asynchronous Embed query text.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nCompute doc embeddings using a HuggingFace transformer model.\nParameters\ntexts \u2013 The list of texts to embed.s\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float]\u00b6\nCompute query embeddings using a HuggingFace transformer model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_pipeline(pipeline: Any, hardware: Any, model_reqs: Optional[List[str]] = None, device: int = 0, **kwargs: Any) \u2192 LLM\u00b6\nInit the SelfHostedPipeline from a pipeline object or string.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-7", "text": "Init the SelfHostedPipeline from a pipeline object or string.\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-8", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-9", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-11", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-12", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-13", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "1c9484528b0a-14", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using SelfHostedHuggingFaceEmbeddings\u00b6\nSelf Hosted", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceEmbeddings.html"}
{"id": "c6c5ee8cc413-0", "text": "langchain.embeddings.gpt4all.GPT4AllEmbeddings\u00b6\nclass langchain.embeddings.gpt4all.GPT4AllEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nGPT4All embedding models.\nTo use, you should have the gpt4all python package installed\nExample\nfrom langchain.embeddings import GPT4AllEmbeddings\nembeddings = GPT4AllEmbeddings()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.gpt4all.GPT4AllEmbeddings.html"}
{"id": "c6c5ee8cc413-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed a list of documents using GPT4All.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed a query using GPT4All.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.gpt4all.GPT4AllEmbeddings.html"}
{"id": "c6c5ee8cc413-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using GPT4AllEmbeddings\u00b6\nGPT4All\nOllama\nUse local LLMs\nWebResearchRetriever", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.gpt4all.GPT4AllEmbeddings.html"}
{"id": "0c51608d31b1-0", "text": "langchain.embeddings.ollama.OllamaEmbeddings\u00b6\nclass langchain.embeddings.ollama.OllamaEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nOllama locally runs large language models.\nTo use, follow the instructions at https://ollama.ai/.\nExample\nfrom langchain.embeddings import OllamaEmbeddings\nollama_emb = OllamaEmbeddings(\n    model=\"llama:7b\",\n)\nr1 = ollama_emb.embed_documents(\n    [\n        \"Alpha is the first letter of Greek alphabet\",\n        \"Beta is the second letter of Greek alphabet\",\n    ]\n)\nr2 = ollama_emb.embed_query(\n    \"What is the second letter of Greek alphabet\"\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam base_url: str = 'http://localhost:11434'\u00b6\nBase url the model is hosted under.\nparam embed_instruction: str = 'passage: '\u00b6\nInstruction used to embed documents.\nparam mirostat: Optional[int] = None\u00b6\nEnable Mirostat sampling for controlling perplexity.\n(default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\nparam mirostat_eta: Optional[float] = None\u00b6\nInfluences how quickly the algorithm responds to feedback\nfrom the generated text. A lower learning rate will result in\nslower adjustments, while a higher learning rate will make\nthe algorithm more responsive. (Default: 0.1)\nparam mirostat_tau: Optional[float] = None\u00b6\nControls the balance between coherence and diversity\nof the output. A lower value will result in more focused and", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.ollama.OllamaEmbeddings.html"}
{"id": "0c51608d31b1-1", "text": "of the output. A lower value will result in more focused and\ncoherent text. (Default: 5.0)\nparam model: str = 'llama2'\u00b6\nModel name to use.\nparam model_kwargs: Optional[dict] = None\u00b6\nOther model keyword args\nparam num_ctx: Optional[int] = None\u00b6\nSets the size of the context window used to generate the\nnext token. (Default: 2048)\nparam num_gpu: Optional[int] = None\u00b6\nThe number of GPUs to use. On macOS it defaults to 1 to\nenable metal support, 0 to disable.\nparam num_thread: Optional[int] = None\u00b6\nSets the number of threads to use during computation.\nBy default, Ollama will detect this for optimal performance.\nIt is recommended to set this value to the number of physical\nCPU cores your system has (as opposed to the logical number of cores).\nparam query_instruction: str = 'query: '\u00b6\nInstruction used to embed the query.\nparam repeat_last_n: Optional[int] = None\u00b6\nSets how far back for the model to look back to prevent\nrepetition. (Default: 64, 0 = disabled, -1 = num_ctx)\nparam repeat_penalty: Optional[float] = None\u00b6\nSets how strongly to penalize repetitions. A higher value (e.g., 1.5)\nwill penalize repetitions more strongly, while a lower value (e.g., 0.9)\nwill be more lenient. (Default: 1.1)\nparam stop: Optional[List[str]] = None\u00b6\nSets the stop tokens to use.\nparam temperature: Optional[float] = None\u00b6\nThe temperature of the model. Increasing the temperature will\nmake the model answer more creatively. (Default: 0.8)\nparam tfs_z: Optional[float] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.ollama.OllamaEmbeddings.html"}
{"id": "0c51608d31b1-2", "text": "param tfs_z: Optional[float] = None\u00b6\nTail free sampling is used to reduce the impact of less probable\ntokens from the output. A higher value (e.g., 2.0) will reduce the\nimpact more, while a value of 1.0 disables this setting. (default: 1)\nparam top_k: Optional[int] = None\u00b6\nReduces the probability of generating nonsense. A higher value (e.g. 100)\nwill give more diverse answers, while a lower value (e.g. 10)\nwill be more conservative. (Default: 40)\nparam top_p: Optional[int] = None\u00b6\nWorks together with top-k. A higher value (e.g., 0.95) will lead\nto more diverse text, while a lower value (e.g., 0.5) will\ngenerate more focused and conservative text. (Default: 0.9)\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.ollama.OllamaEmbeddings.html"}
{"id": "0c51608d31b1-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed documents using a Ollama deployed embedding model.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed a query using a Ollama deployed embedding model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.ollama.OllamaEmbeddings.html"}
{"id": "0c51608d31b1-4", "text": "Embeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.ollama.OllamaEmbeddings.html"}
{"id": "fd310d8949de-0", "text": "langchain.embeddings.aleph_alpha.AlephAlphaAsymmetricSemanticEmbedding\u00b6\nclass langchain.embeddings.aleph_alpha.AlephAlphaAsymmetricSemanticEmbedding[source]\u00b6\nBases: BaseModel, Embeddings\nAleph Alpha\u2019s asymmetric semantic embedding.\nAA provides you with an endpoint to embed a document and a query.\nThe models were optimized to make the embeddings of documents and\nthe query for a document as similar as possible.\nTo learn more, check out: https://docs.aleph-alpha.com/docs/tasks/semantic_embed/\nExample\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aleph_alpha_api_key: Optional[str] = None\u00b6\nAPI key for Aleph Alpha API.\nparam compress_to_size: Optional[int] = None\u00b6\nShould the returned embeddings come back as an original 5120-dim vector,\nor should it be compressed to 128-dim.\nparam contextual_control_threshold: Optional[int] = None\u00b6\nAttention control parameters only apply to those tokens that have\nexplicitly been set in the request.\nparam control_log_additive: bool = True\u00b6\nApply controls on prompt items by adding the log(control_factor)\nto attention scores.\nparam host: str = 'https://api.aleph-alpha.com'\u00b6\nThe hostname of the API host.\nThe default one is \u201chttps://api.aleph-alpha.com\u201d)\nparam hosting: Optional[str] = None\u00b6\nDetermines in which datacenters the request may be processed.\nYou can either set the parameter to \u201caleph-alpha\u201d or omit it (defaulting to None).\nNot setting this value, or setting it to None, gives us maximal flexibility\nin processing your request in our\nown datacenters and on servers hosted with other providers.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.aleph_alpha.AlephAlphaAsymmetricSemanticEmbedding.html"}
{"id": "fd310d8949de-1", "text": "in processing your request in our\nown datacenters and on servers hosted with other providers.\nChoose this option for maximal availability.\nSetting it to \u201caleph-alpha\u201d allows us to only process the request\nin our own datacenters.\nChoose this option for maximal data privacy.\nparam model: str = 'luminous-base'\u00b6\nModel name to use.\nparam nice: bool = False\u00b6\nSetting this to True, will signal to the API that you intend to be\nnice to other users\nby de-prioritizing your request below concurrent ones.\nparam normalize: Optional[bool] = None\u00b6\nShould returned embeddings be normalized\nparam request_timeout_seconds: int = 305\u00b6\nClient timeout that will be set for HTTP requests in the\nrequests library\u2019s API calls.\nServer will close all requests after 300 seconds with an internal server error.\nparam total_retries: int = 8\u00b6\nThe number of retries made in case requests fail with certain retryable\nstatus codes. If the last\nretry fails a corresponding exception is raised. Note, that between retries\nan exponential backoff\nis applied, starting with 0.5 s after the first retry and doubling for each\nretry made. So with the\ndefault setting of 8 retries a total wait time of 63.5 s is added between\nthe retries.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.aleph_alpha.AlephAlphaAsymmetricSemanticEmbedding.html"}
{"id": "fd310d8949de-2", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCall out to Aleph Alpha\u2019s asymmetric Document endpoint.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to Aleph Alpha\u2019s asymmetric, query embedding endpoint\n:param text: The text to embed.\nReturns\nEmbeddings for the text.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.aleph_alpha.AlephAlphaAsymmetricSemanticEmbedding.html"}
{"id": "fd310d8949de-3", "text": ":param text: The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using AlephAlphaAsymmetricSemanticEmbedding\u00b6\nAleph Alpha", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.aleph_alpha.AlephAlphaAsymmetricSemanticEmbedding.html"}
{"id": "51e627f9be7e-0", "text": "langchain.embeddings.self_hosted_hugging_face.load_embedding_model\u00b6\nlangchain.embeddings.self_hosted_hugging_face.load_embedding_model(model_id: str, instruct: bool = False, device: int = 0) \u2192 Any[source]\u00b6\nLoad the embedding model.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.load_embedding_model.html"}
{"id": "14c421adf618-0", "text": "langchain.embeddings.bedrock.BedrockEmbeddings\u00b6\nclass langchain.embeddings.bedrock.BedrockEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nBedrock embedding models.\nTo authenticate, the AWS client uses the following methods to\nautomatically load credentials:\nhttps://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\nIf a specific credential profile should be used, you must pass\nthe name of the profile from the ~/.aws/credentials file that is to be used.\nMake sure the credentials / roles used have the required policies to\naccess the Bedrock service.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam client: Any = None\u00b6\nBedrock client.\nparam credentials_profile_name: Optional[str] = None\u00b6\nThe name of the profile in the ~/.aws/credentials or ~/.aws/config files, which\nhas either access keys or role information specified.\nIf not specified, the default credential profile or, if on an EC2 instance,\ncredentials from IMDS will be used.\nSee: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\nparam endpoint_url: Optional[str] = None\u00b6\nNeeded if you don\u2019t want to default to us-east-1 endpoint\nparam model_id: str = 'amazon.titan-embed-text-v1'\u00b6\nId of the model to call, e.g., amazon.titan-embed-text-v1, this is\nequivalent to the modelId property in the list-foundation-models api\nparam model_kwargs: Optional[Dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam region_name: Optional[str] = None\u00b6\nThe aws region e.g., us-west-2. Fallsback to AWS_DEFAULT_REGION env variable", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.bedrock.BedrockEmbeddings.html"}
{"id": "14c421adf618-1", "text": "The aws region e.g., us-west-2. Fallsback to AWS_DEFAULT_REGION env variable\nor region specified in ~/.aws/config in case it is not provided here.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nAsynchronous compute doc embeddings using a Bedrock model.\nParameters\ntexts \u2013 The list of texts to embed\nReturns\nList of embeddings, one for each text.\nasync aembed_query(text: str) \u2192 List[float][source]\u00b6\nAsynchronous compute query embeddings using a Bedrock model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.bedrock.BedrockEmbeddings.html"}
{"id": "14c421adf618-2", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCompute doc embeddings using a Bedrock model.\nParameters\ntexts \u2013 The list of texts to embed\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCompute query embeddings using a Bedrock model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.bedrock.BedrockEmbeddings.html"}
{"id": "14c421adf618-3", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using BedrockEmbeddings\u00b6\nBedrock", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.bedrock.BedrockEmbeddings.html"}
{"id": "b02ccc50c7b8-0", "text": "langchain.embeddings.llamacpp.LlamaCppEmbeddings\u00b6\nclass langchain.embeddings.llamacpp.LlamaCppEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nllama.cpp embedding models.\nTo use, you should have the llama-cpp-python library installed, and provide the\npath to the Llama model as a named parameter to the constructor.\nCheck out: https://github.com/abetlen/llama-cpp-python\nExample\nfrom langchain.embeddings import LlamaCppEmbeddings\nllama = LlamaCppEmbeddings(model_path=\"/path/to/model.bin\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam f16_kv: bool = False\u00b6\nUse half-precision for key/value cache.\nparam logits_all: bool = False\u00b6\nReturn logits for all tokens, not just the last token.\nparam model_path: str [Required]\u00b6\nparam n_batch: Optional[int] = 8\u00b6\nNumber of tokens to process in parallel.\nShould be a number between 1 and n_ctx.\nparam n_ctx: int = 512\u00b6\nToken context window.\nparam n_gpu_layers: Optional[int] = None\u00b6\nNumber of layers to be loaded into gpu memory. Default None.\nparam n_parts: int = -1\u00b6\nNumber of parts to split the model into.\nIf -1, the number of parts is automatically determined.\nparam n_threads: Optional[int] = None\u00b6\nNumber of threads to use. If None, the number\nof threads is automatically determined.\nparam seed: int = -1\u00b6\nSeed. If -1, a random seed is used.\nparam use_mlock: bool = False\u00b6\nForce system to keep model in RAM.\nparam verbose: bool = True\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.llamacpp.LlamaCppEmbeddings.html"}
{"id": "b02ccc50c7b8-1", "text": "Force system to keep model in RAM.\nparam verbose: bool = True\u00b6\nPrint verbose output to stderr.\nparam vocab_only: bool = False\u00b6\nOnly load the vocabulary, no weights.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.llamacpp.LlamaCppEmbeddings.html"}
{"id": "b02ccc50c7b8-2", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed a list of documents using the Llama model.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed a query using the Llama model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.llamacpp.LlamaCppEmbeddings.html"}
{"id": "b02ccc50c7b8-3", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using LlamaCppEmbeddings\u00b6\nLlama-cpp\nLlama.cpp", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.llamacpp.LlamaCppEmbeddings.html"}
{"id": "87ef538c66dc-0", "text": "langchain.embeddings.sagemaker_endpoint.SagemakerEndpointEmbeddings\u00b6\nclass langchain.embeddings.sagemaker_endpoint.SagemakerEndpointEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nCustom Sagemaker Inference Endpoints.\nTo use, you must supply the endpoint name from your deployed\nSagemaker model & the region where it is deployed.\nTo authenticate, the AWS client uses the following methods to\nautomatically load credentials:\nhttps://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\nIf a specific credential profile should be used, you must pass\nthe name of the profile from the ~/.aws/credentials file that is to be used.\nMake sure the credentials / roles used have the required policies to\naccess the Sagemaker endpoint.\nSee: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam client: Any = None\u00b6\nparam content_handler: langchain.embeddings.sagemaker_endpoint.EmbeddingsContentHandler [Required]\u00b6\nThe content handler class that provides an input and\noutput transform functions to handle formats between LLM\nand the endpoint.\nparam credentials_profile_name: Optional[str] = None\u00b6\nThe name of the profile in the ~/.aws/credentials or ~/.aws/config files, which\nhas either access keys or role information specified.\nIf not specified, the default credential profile or, if on an EC2 instance,\ncredentials from IMDS will be used.\nSee: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\nparam endpoint_kwargs: Optional[Dict] = None\u00b6\nOptional attributes passed to the invoke_endpoint\nfunction. See `boto3`_. docs for more info.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.sagemaker_endpoint.SagemakerEndpointEmbeddings.html"}
{"id": "87ef538c66dc-1", "text": "function. See `boto3`_. docs for more info.\n.. _boto3: <https://boto3.amazonaws.com/v1/documentation/api/latest/index.html>\nparam endpoint_name: str = ''\u00b6\nThe name of the endpoint from the deployed Sagemaker model.\nMust be unique within an AWS Region.\nparam model_kwargs: Optional[Dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam region_name: str = ''\u00b6\nThe aws region where the Sagemaker model is deployed, eg. us-west-2.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.sagemaker_endpoint.SagemakerEndpointEmbeddings.html"}
{"id": "87ef538c66dc-2", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str], chunk_size: int = 64) \u2192 List[List[float]][source]\u00b6\nCompute doc embeddings using a SageMaker Inference Endpoint.\nParameters\ntexts \u2013 The list of texts to embed.\nchunk_size \u2013 The chunk size defines how many input texts will\nbe grouped together as request. If None, will use the\nchunk size specified by the class.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCompute query embeddings using a SageMaker inference endpoint.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.sagemaker_endpoint.SagemakerEndpointEmbeddings.html"}
{"id": "87ef538c66dc-3", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using SagemakerEndpointEmbeddings\u00b6\nSageMaker\nSageMaker Endpoint", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.sagemaker_endpoint.SagemakerEndpointEmbeddings.html"}
{"id": "dfc3780b5b63-0", "text": "langchain.embeddings.embaas.EmbaasEmbeddings\u00b6\nclass langchain.embeddings.embaas.EmbaasEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nEmbaas\u2019s embedding service.\nTo use, you should have the\nenvironment variable EMBAAS_API_KEY set with your API key, or pass\nit as a named parameter to the constructor.\nExample\n# Initialise with default model and instruction\nfrom langchain.embeddings import EmbaasEmbeddings\nemb = EmbaasEmbeddings()\n# Initialise with custom model and instruction\nfrom langchain.embeddings import EmbaasEmbeddings\nemb_model = \"instructor-large\"\nemb_inst = \"Represent the Wikipedia document for retrieval\"\nemb = EmbaasEmbeddings(\n    model=emb_model,\n    instruction=emb_inst\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_url: str = 'https://api.embaas.io/v1/embeddings/'\u00b6\nThe URL for the embaas embeddings API.\nparam embaas_api_key: Optional[str] = None\u00b6\nparam instruction: Optional[str] = None\u00b6\nInstruction used for domain-specific embeddings.\nparam model: str = 'e5-large-v2'\u00b6\nThe model used for embeddings.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.embaas.EmbaasEmbeddings.html"}
{"id": "dfc3780b5b63-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nGet embeddings for a list of texts.\nParameters\ntexts \u2013 The list of texts to get embeddings for.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nGet embeddings for a single text.\nParameters\ntext \u2013 The text to get embeddings for.\nReturns\nList of embeddings.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.embaas.EmbaasEmbeddings.html"}
{"id": "dfc3780b5b63-2", "text": "Returns\nList of embeddings.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using EmbaasEmbeddings\u00b6\nEmbaas", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.embaas.EmbaasEmbeddings.html"}
{"id": "607b00b8f2dd-0", "text": "langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings\u00b6\nclass langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings[source]\u00b6\nBases: SelfHostedHuggingFaceEmbeddings\nHuggingFace InstructEmbedding models on self-hosted remote hardware.\nSupported hardware includes auto-launched instances on AWS, GCP, Azure,\nand Lambda, as well as servers specified\nby IP address and SSH credentials (such as on-prem, or another\ncloud like Paperspace, Coreweave, etc.).\nTo use, you should have the runhouse python package installed.\nExample\nfrom langchain.embeddings import SelfHostedHuggingFaceInstructEmbeddings\nimport runhouse as rh\nmodel_name = \"hkunlp/instructor-large\"\ngpu = rh.cluster(name='rh-a10x', instance_type='A100:1')\nhf = SelfHostedHuggingFaceInstructEmbeddings(\n    model_name=model_name, hardware=gpu)\nInitialize the remote inference function.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam embed_instruction: str = 'Represent the document for retrieval: '\u00b6\nInstruction to use for embedding documents.\nparam hardware: Any = None\u00b6\nRemote hardware to send the inference function to.\nparam inference_fn: Callable = <function _embed_documents>\u00b6\nInference function to extract the embeddings.\nparam inference_kwargs: Any = None\u00b6\nAny kwargs to pass to the model\u2019s inference function.\nparam load_fn_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model load function.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-1", "text": "Metadata to add to the run trace.\nparam model_id: str = 'hkunlp/instructor-large'\u00b6\nModel name to use.\nparam model_load_fn: Callable = <function load_embedding_model>\u00b6\nFunction to load the model remotely on the server.\nparam model_reqs: List[str] = ['./', 'InstructorEmbedding', 'torch']\u00b6\nRequirements to install on hardware to inference the model.\nparam pipeline_ref: Any = None\u00b6\nparam query_instruction: str = 'Represent the question for retrieving supporting documents: '\u00b6\nInstruction to use for embedding query.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-2", "text": "async aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-3", "text": "callbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-4", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-5", "text": "Subclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-6", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCompute doc embeddings using a HuggingFace instruct model.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCompute query embeddings using a HuggingFace instruct model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_pipeline(pipeline: Any, hardware: Any, model_reqs: Optional[List[str]] = None, device: int = 0, **kwargs: Any) \u2192 LLM\u00b6\nInit the SelfHostedPipeline from a pipeline object or string.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-7", "text": "Init the SelfHostedPipeline from a pipeline object or string.\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-8", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-9", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-11", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-12", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-13", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "607b00b8f2dd-14", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using SelfHostedHuggingFaceInstructEmbeddings\u00b6\nSelf Hosted", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted_hugging_face.SelfHostedHuggingFaceInstructEmbeddings.html"}
{"id": "bd1a769637f0-0", "text": "langchain.embeddings.modelscope_hub.ModelScopeEmbeddings\u00b6\nclass langchain.embeddings.modelscope_hub.ModelScopeEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nModelScopeHub embedding models.\nTo use, you should have the modelscope python package installed.\nExample\nfrom langchain.embeddings import ModelScopeEmbeddings\nmodel_id = \"damo/nlp_corom_sentence-embedding_english-base\"\nembed = ModelScopeEmbeddings(model_id=model_id, model_revision=\"v1.0.0\")\nInitialize the modelscope\nparam embed: Any = None\u00b6\nparam model_id: str = 'damo/nlp_corom_sentence-embedding_english-base'\u00b6\nModel name to use.\nparam model_revision: Optional[str] = None\u00b6\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.modelscope_hub.ModelScopeEmbeddings.html"}
{"id": "bd1a769637f0-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCompute doc embeddings using a modelscope embedding model.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCompute query embeddings using a modelscope embedding model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.modelscope_hub.ModelScopeEmbeddings.html"}
{"id": "bd1a769637f0-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using ModelScopeEmbeddings\u00b6\nModelScope", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.modelscope_hub.ModelScopeEmbeddings.html"}
{"id": "712622edf2c4-0", "text": "langchain.embeddings.azure_openai.AzureOpenAIEmbeddings\u00b6\nclass langchain.embeddings.azure_openai.AzureOpenAIEmbeddings[source]\u00b6\nBases: OpenAIEmbeddings\nAzure OpenAI Embeddings API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_special: Union[Literal['all'], Set[str]] = {}\u00b6\nparam azure_ad_token: Union[str, None] = None\u00b6\nYour Azure Active Directory token.\nAutomatically inferred from env var AZURE_OPENAI_AD_TOKEN if not provided.\nFor more:\nhttps://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id.\nparam azure_ad_token_provider: Union[str, None] = None\u00b6\nA function that returns an Azure Active Directory token.\nWill be invoked on every request.\nparam azure_endpoint: Union[str, None] = None\u00b6\nYour Azure endpoint, including the resource.\nAutomatically inferred from env var AZURE_OPENAI_ENDPOINT if not provided.\nExample: https://example-resource.azure.openai.com/\nparam chunk_size: int = 1000\u00b6\nMaximum number of texts to embed in each batch\nparam default_headers: Union[Mapping[str, str], None] = None\u00b6\nparam default_query: Union[Mapping[str, object], None] = None\u00b6\nparam deployment: Optional[str] = None (alias 'azure_deployment')\u00b6\nA model deployment.\nIf given sets the base client URL to include /deployments/{azure_deployment}.\nNote: this means you won\u2019t be able to use non-deployment endpoints.\nparam disallowed_special: Union[Literal['all'], Set[str], Sequence[str]] = 'all'\u00b6\nparam embedding_ctx_length: int = 8191\u00b6\nThe maximum number of tokens to embed at once.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.azure_openai.AzureOpenAIEmbeddings.html"}
{"id": "712622edf2c4-1", "text": "The maximum number of tokens to embed at once.\nparam headers: Any = None\u00b6\nparam http_client: Union[Any, None] = None\u00b6\nOptional httpx.Client.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.\nparam model: str = 'text-embedding-ada-002'\u00b6\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Union[str, None] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var AZURE_OPENAI_API_KEY if not provided.\nparam openai_api_type: Optional[str] = None\u00b6\nparam openai_api_version: Optional[str] = None (alias 'api_version')\u00b6\nAutomatically inferred from env var OPENAI_API_VERSION if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam request_timeout: Optional[Union[float, Tuple[float, float], Any]] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam show_progress_bar: bool = False\u00b6\nWhether to show a progress bar when embedding.\nparam skip_empty: bool = False\u00b6\nWhether to skip empty strings when embedding or raise an error.\nDefaults to not skipping.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.azure_openai.AzureOpenAIEmbeddings.html"}
{"id": "712622edf2c4-2", "text": "The model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nparam validate_base_url: bool = True\u00b6\nasync aembed_documents(texts: List[str], chunk_size: Optional[int] = 0) \u2192 List[List[float]]\u00b6\nCall out to OpenAI\u2019s embedding endpoint async for embedding search docs.\nParameters\ntexts \u2013 The list of texts to embed.\nchunk_size \u2013 The chunk size of embeddings. If None, will use the chunk size\nspecified by the class.\nReturns\nList of embeddings, one for each text.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nCall out to OpenAI\u2019s embedding endpoint async for embedding query text.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbedding for the text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.azure_openai.AzureOpenAIEmbeddings.html"}
{"id": "712622edf2c4-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str], chunk_size: Optional[int] = 0) \u2192 List[List[float]]\u00b6\nCall out to OpenAI\u2019s embedding endpoint for embedding search docs.\nParameters\ntexts \u2013 The list of texts to embed.\nchunk_size \u2013 The chunk size of embeddings. If None, will use the chunk size\nspecified by the class.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float]\u00b6\nCall out to OpenAI\u2019s embedding endpoint for embedding query text.\nParameters", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.azure_openai.AzureOpenAIEmbeddings.html"}
{"id": "712622edf2c4-4", "text": "Call out to OpenAI\u2019s embedding endpoint for embedding query text.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbedding for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.azure_openai.AzureOpenAIEmbeddings.html"}
{"id": "1cc508a06087-0", "text": "langchain.embeddings.nlpcloud.NLPCloudEmbeddings\u00b6\nclass langchain.embeddings.nlpcloud.NLPCloudEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nNLP Cloud embedding models.\nTo use, you should have the nlpcloud python package installed\nExample\nfrom langchain.embeddings import NLPCloudEmbeddings\nembeddings = NLPCloudEmbeddings()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam gpu: bool [Required]\u00b6\nparam model_name: str [Required]\u00b6\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.nlpcloud.NLPCloudEmbeddings.html"}
{"id": "1cc508a06087-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed a list of documents using NLP Cloud.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed a query using NLP Cloud.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.nlpcloud.NLPCloudEmbeddings.html"}
{"id": "1cc508a06087-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using NLPCloudEmbeddings\u00b6\nNLP Cloud\nNLPCloud", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.nlpcloud.NLPCloudEmbeddings.html"}
{"id": "e907bdf892e9-0", "text": "langchain.embeddings.vertexai.VertexAIEmbeddings\u00b6\nclass langchain.embeddings.vertexai.VertexAIEmbeddings[source]\u00b6\nBases: _VertexAICommon, Embeddings\nGoogle Cloud VertexAI embedding models.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam credentials: Any = None\u00b6\nThe default custom credentials (google.auth.credentials.Credentials) to use\nparam location: str = 'us-central1'\u00b6\nThe default location to use when making API calls.\nparam max_output_tokens: int = 128\u00b6\nToken limit determines the maximum amount of text output from one prompt.\nparam max_retries: int = 6\u00b6\nThe maximum number of retries to make when generating.\nparam model_name: str = 'textembedding-gecko'\u00b6\nUnderlying model name.\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam project: Optional[str] = None\u00b6\nThe default GCP project to use when making Vertex API calls.\nparam request_parallelism: int = 5\u00b6\nThe amount of parallelism allowed for requests issued to VertexAI models.\nparam stop: Optional[List[str]] = None\u00b6\nOptional list of stop words to use when generating.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam temperature: float = 0.0\u00b6\nSampling temperature, it controls the degree of randomness in token selection.\nparam top_k: int = 40\u00b6\nHow the model selects tokens for output, the next token is selected from\nparam top_p: float = 0.95\u00b6\nTokens are selected from most probable to least until the sum of their\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.vertexai.VertexAIEmbeddings.html"}
{"id": "e907bdf892e9-1", "text": "Asynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str], batch_size: int = 5) \u2192 List[List[float]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.vertexai.VertexAIEmbeddings.html"}
{"id": "e907bdf892e9-2", "text": "Embed a list of strings. Vertex AI currently\nsets a max batch size of 5 strings.\nParameters\ntexts \u2013 List[str] The list of strings to embed.\nbatch_size \u2013 [int] The batch size of embeddings to send to the model\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed a text.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbedding for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.vertexai.VertexAIEmbeddings.html"}
{"id": "e907bdf892e9-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty is_codey_model: bool\u00b6\ntask_executor: ClassVar[Optional[Executor]] = FieldInfo(exclude=True, extra={})\u00b6\nExamples using VertexAIEmbeddings\u00b6\nGoogle Vertex AI PaLM", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.vertexai.VertexAIEmbeddings.html"}
{"id": "771ad3121ec3-0", "text": "langchain.embeddings.openai.async_embed_with_retry\u00b6\nasync langchain.embeddings.openai.async_embed_with_retry(embeddings: OpenAIEmbeddings, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the embedding call.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.openai.async_embed_with_retry.html"}
{"id": "7676447b2c68-0", "text": "langchain.embeddings.dashscope.DashScopeEmbeddings\u00b6\nclass langchain.embeddings.dashscope.DashScopeEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nDashScope embedding models.\nTo use, you should have the dashscope python package installed, and the\nenvironment variable DASHSCOPE_API_KEY set with your API key or pass it\nas a named parameter to the constructor.\nExample\nfrom langchain.embeddings import DashScopeEmbeddings\nembeddings = DashScopeEmbeddings(dashscope_api_key=\"my-api-key\")\nExample\nimport os\nos.environ[\"DASHSCOPE_API_KEY\"] = \"your DashScope API KEY\"\nfrom langchain.embeddings.dashscope import DashScopeEmbeddings\nembeddings = DashScopeEmbeddings(\n    model=\"text-embedding-v1\",\n)\ntext = \"This is a test query.\"\nquery_result = embeddings.embed_query(text)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam client: Any = None\u00b6\nThe DashScope client.\nparam dashscope_api_key: Optional[str] = None\u00b6\nparam max_retries: int = 5\u00b6\nMaximum number of retries to make when generating.\nparam model: str = 'text-embedding-v1'\u00b6\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.dashscope.DashScopeEmbeddings.html"}
{"id": "7676447b2c68-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCall out to DashScope\u2019s embedding endpoint for embedding search docs.\nParameters\ntexts \u2013 The list of texts to embed.\nchunk_size \u2013 The chunk size of embeddings. If None, will use the chunk size\nspecified by the class.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to DashScope\u2019s embedding endpoint for embedding query text.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.dashscope.DashScopeEmbeddings.html"}
{"id": "7676447b2c68-2", "text": "Call out to DashScope\u2019s embedding endpoint for embedding query text.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbedding for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.dashscope.DashScopeEmbeddings.html"}
{"id": "7676447b2c68-3", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nExamples using DashScopeEmbeddings\u00b6\nDashScope\nDashVector", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.dashscope.DashScopeEmbeddings.html"}
{"id": "bbe277246433-0", "text": "langchain.embeddings.fake.DeterministicFakeEmbedding\u00b6\nclass langchain.embeddings.fake.DeterministicFakeEmbedding[source]\u00b6\nBases: Embeddings, BaseModel\nFake embedding model that always returns\nthe same embedding vector for the same text.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam size: int [Required]\u00b6\nThe size of the embedding vector.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.fake.DeterministicFakeEmbedding.html"}
{"id": "bbe277246433-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed search docs.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed query text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.fake.DeterministicFakeEmbedding.html"}
{"id": "bbe277246433-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.fake.DeterministicFakeEmbedding.html"}
{"id": "b06c4a9f6146-0", "text": "langchain.embeddings.octoai_embeddings.OctoAIEmbeddings\u00b6\nclass langchain.embeddings.octoai_embeddings.OctoAIEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nOctoAI Compute Service embedding models.\nThe environment variable OCTOAI_API_TOKEN should be set\nwith your API token, or it can be passed\nas a named parameter to the constructor.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam embed_instruction: str = 'Represent this input: '\u00b6\nInstruction to use for embedding documents.\nparam endpoint_url: Optional[str] = None\u00b6\nEndpoint URL to use.\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam octoai_api_token: Optional[str] = None\u00b6\nOCTOAI API Token\nparam query_instruction: str = 'Represent the question for retrieving similar documents: '\u00b6\nInstruction to use for embedding query.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.octoai_embeddings.OctoAIEmbeddings.html"}
{"id": "b06c4a9f6146-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCompute document embeddings using an OctoAI instruct model.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCompute query embedding using an OctoAI instruct model.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.octoai_embeddings.OctoAIEmbeddings.html"}
{"id": "b06c4a9f6146-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.octoai_embeddings.OctoAIEmbeddings.html"}
{"id": "101e3a23f95d-0", "text": "langchain.embeddings.ernie.ErnieEmbeddings\u00b6\nclass langchain.embeddings.ernie.ErnieEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nErnie Embeddings V1 embedding models.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam access_token: Optional[str] = None\u00b6\nparam chunk_size: int = 16\u00b6\nparam ernie_api_base: Optional[str] = None\u00b6\nparam ernie_client_id: Optional[str] = None\u00b6\nparam ernie_client_secret: Optional[str] = None\u00b6\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nAsynchronous Embed search docs.\nParameters\ntexts \u2013 The list of texts to embed\nReturns\nList of embeddings, one for each text.\nReturn type\nList[List[float]]\nasync aembed_query(text: str) \u2192 List[float][source]\u00b6\nAsynchronous Embed query text.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nReturn type\nList[float]\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.ernie.ErnieEmbeddings.html"}
{"id": "101e3a23f95d-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed search docs.\nParameters\ntexts \u2013 The list of texts to embed\nReturns\nList of embeddings, one for each text.\nReturn type\nList[List[float]]\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed query text.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nReturn type\nList[float]\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.ernie.ErnieEmbeddings.html"}
{"id": "101e3a23f95d-2", "text": "Return type\nList[float]\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.ernie.ErnieEmbeddings.html"}
{"id": "f581cbbcf1a6-0", "text": "langchain.embeddings.xinference.XinferenceEmbeddings\u00b6\nclass langchain.embeddings.xinference.XinferenceEmbeddings(server_url: Optional[str] = None, model_uid: Optional[str] = None)[source]\u00b6\nXinference embedding models.\nTo use, you should have the xinference library installed:\npip install xinference\nCheck out: https://github.com/xorbitsai/inference\nTo run, you need to start a Xinference supervisor on one server and Xinference workers on the other servers.\nExample\nTo start a local instance of Xinference, run\n$ xinference\nYou can also deploy Xinference in a distributed cluster. Here are the steps:\nStarting the supervisor:\n$ xinference-supervisor\nStarting the worker:\n$ xinference-worker\nThen, launch a model using command line interface (CLI).\nExample:\n$ xinference launch -n orca -s 3 -q q4_0\nIt will return a model UID. Then you can use Xinference Embedding with LangChain.\nExample:\nfrom langchain.embeddings import XinferenceEmbeddings\nxinference = XinferenceEmbeddings(\n    server_url=\"http://0.0.0.0:9997\",\n    model_uid = {model_uid} # replace model_uid with the model UID return from launching the model\n)\nAttributes\nclient\nserver_url\nURL of the xinference server\nmodel_uid\nUID of the launched model\nMethods\n__init__([server_url,\u00a0model_uid])\naembed_documents(texts)\nAsynchronous Embed search docs.\naembed_query(text)\nAsynchronous Embed query text.\nembed_documents(texts)\nEmbed a list of documents using Xinference.\nembed_query(text)\nEmbed a query of documents using Xinference.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.xinference.XinferenceEmbeddings.html"}
{"id": "f581cbbcf1a6-1", "text": "embed_query(text)\nEmbed a query of documents using Xinference.\n__init__(server_url: Optional[str] = None, model_uid: Optional[str] = None)[source]\u00b6\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed a list of documents using Xinference.\n:param texts: The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed a query of documents using Xinference.\n:param text: The text to embed.\nReturns\nEmbeddings for the text.\nExamples using XinferenceEmbeddings\u00b6\nXorbits inference (Xinference)", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.xinference.XinferenceEmbeddings.html"}
{"id": "0a012726cba9-0", "text": "langchain.embeddings.cache.CacheBackedEmbeddings\u00b6\nclass langchain.embeddings.cache.CacheBackedEmbeddings(underlying_embeddings: Embeddings, document_embedding_store: BaseStore[str, List[float]])[source]\u00b6\nInterface for caching results from embedding models.\nThe interface allows works with any store that implements\nthe abstract store interface accepting keys of type str and values of list of\nfloats.\nIf need be, the interface can be extended to accept other implementations\nof the value serializer and deserializer, as well as the key encoder.\nExamples\nInitialize the embedder.\nParameters\nunderlying_embeddings \u2013 the embedder to use for computing embeddings.\ndocument_embedding_store \u2013 The store to use for caching document embeddings.\nMethods\n__init__(underlying_embeddings,\u00a0...)\nInitialize the embedder.\naembed_documents(texts)\nAsynchronous Embed search docs.\naembed_query(text)\nAsynchronous Embed query text.\nembed_documents(texts)\nEmbed a list of texts.\nembed_query(text)\nEmbed query text.\nfrom_bytes_store(underlying_embeddings,\u00a0...)\nOn-ramp that adds the necessary serialization and encoding to the store.\n__init__(underlying_embeddings: Embeddings, document_embedding_store: BaseStore[str, List[float]]) \u2192 None[source]\u00b6\nInitialize the embedder.\nParameters\nunderlying_embeddings \u2013 the embedder to use for computing embeddings.\ndocument_embedding_store \u2013 The store to use for caching document embeddings.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed a list of texts.\nThe method first checks the cache for the embeddings.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.cache.CacheBackedEmbeddings.html"}
{"id": "0a012726cba9-1", "text": "Embed a list of texts.\nThe method first checks the cache for the embeddings.\nIf the embeddings are not found, the method uses the underlying embedder\nto embed the documents and stores the results in the cache.\nParameters\ntexts \u2013 A list of texts to embed.\nReturns\nA list of embeddings for the given texts.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed query text.\nThis method does not support caching at the moment.\nSupport for caching queries is easily to implement, but might make\nsense to hold off to see the most common patterns.\nIf the cache has an eviction policy, we may need to be a bit more careful\nabout sharing the cache between documents and queries. Generally,\none is OK evicting query caches, but document caches should be kept.\nParameters\ntext \u2013 The text to embed.\nReturns\nThe embedding for the given text.\nclassmethod from_bytes_store(underlying_embeddings: Embeddings, document_embedding_cache: BaseStore[str, bytes], *, namespace: str = '') \u2192 CacheBackedEmbeddings[source]\u00b6\nOn-ramp that adds the necessary serialization and encoding to the store.\nParameters\nunderlying_embeddings \u2013 The embedder to use for embedding.\ndocument_embedding_cache \u2013 The cache to use for storing document embeddings.\n* \u2013 \n:param :\n:param namespace: The namespace to use for document cache.\nThis namespace is used to avoid collisions with other caches.\nFor example, set it to the name of the embedding model used.\nExamples using CacheBackedEmbeddings\u00b6\nCaching", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.cache.CacheBackedEmbeddings.html"}
{"id": "6c9169a12d15-0", "text": "langchain.embeddings.huggingface.HuggingFaceInferenceAPIEmbeddings\u00b6\nclass langchain.embeddings.huggingface.HuggingFaceInferenceAPIEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nEmbed texts using the HuggingFace API.\nRequires a HuggingFace Inference API key and a model name.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_key: str [Required]\u00b6\nYour API key for the HuggingFace Inference API.\nparam model_name: str = 'sentence-transformers/all-MiniLM-L6-v2'\u00b6\nThe name of the model to use for text embeddings.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceInferenceAPIEmbeddings.html"}
{"id": "6c9169a12d15-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nGet the embeddings for a list of texts.\nParameters\ntexts (Documents) \u2013 A list of texts to get embeddings for.\nReturns\nEmbedded texts as List[List[float]], where each inner List[float]corresponds to a single input text.\nExample\nfrom langchain.embeddings import HuggingFaceInferenceAPIEmbeddings\nhf_embeddings = HuggingFaceInferenceAPIEmbeddings(\n    api_key=\"your_api_key\",\n    model_name=\"sentence-transformers/all-MiniLM-l6-v2\"\n)\ntexts = [\"Hello, world!\", \"How are you?\"]\nhf_embeddings.embed_documents(texts)\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCompute query embeddings using a HuggingFace transformer model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceInferenceAPIEmbeddings.html"}
{"id": "6c9169a12d15-2", "text": "Embeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using HuggingFaceInferenceAPIEmbeddings\u00b6\nHugging Face", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceInferenceAPIEmbeddings.html"}
{"id": "0c98078e7e0b-0", "text": "langchain.embeddings.minimax.MiniMaxEmbeddings\u00b6\nclass langchain.embeddings.minimax.MiniMaxEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nMiniMax\u2019s embedding service.\nTo use, you should have the environment variable MINIMAX_GROUP_ID and\nMINIMAX_API_KEY set with your API token, or pass it as a named parameter to\nthe constructor.\nExample\nfrom langchain.embeddings import MiniMaxEmbeddings\nembeddings = MiniMaxEmbeddings()\nquery_text = \"This is a test query.\"\nquery_result = embeddings.embed_query(query_text)\ndocument_text = \"This is a test document.\"\ndocument_result = embeddings.embed_documents([document_text])\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam embed_type_db: str = 'db'\u00b6\nFor embed_documents\nparam embed_type_query: str = 'query'\u00b6\nFor embed_query\nparam endpoint_url: str = 'https://api.minimax.chat/v1/embeddings'\u00b6\nEndpoint URL to use.\nparam minimax_api_key: Optional[str] = None\u00b6\nAPI Key for MiniMax API.\nparam minimax_group_id: Optional[str] = None\u00b6\nGroup ID for MiniMax API.\nparam model: str = 'embo-01'\u00b6\nEmbeddings model name to use.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.minimax.MiniMaxEmbeddings.html"}
{"id": "0c98078e7e0b-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed(texts: List[str], embed_type: str) \u2192 List[List[float]][source]\u00b6\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed documents using a MiniMax embedding endpoint.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed a query using a MiniMax embedding endpoint.\nParameters\ntext \u2013 The text to embed.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.minimax.MiniMaxEmbeddings.html"}
{"id": "0c98078e7e0b-2", "text": "Parameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using MiniMaxEmbeddings\u00b6\nMiniMax\nMinimax", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.minimax.MiniMaxEmbeddings.html"}
{"id": "70b1faedc4f3-0", "text": "langchain.embeddings.minimax.embed_with_retry\u00b6\nlangchain.embeddings.minimax.embed_with_retry(embeddings: MiniMaxEmbeddings, *args: Any, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.minimax.embed_with_retry.html"}
{"id": "850daaa2347c-0", "text": "langchain.embeddings.huggingface.HuggingFaceBgeEmbeddings\u00b6\nclass langchain.embeddings.huggingface.HuggingFaceBgeEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nHuggingFace BGE sentence_transformers embedding models.\nTo use, you should have the sentence_transformers python package installed.\nExample\nfrom langchain.embeddings import HuggingFaceBgeEmbeddings\nmodel_name = \"BAAI/bge-large-en\"\nmodel_kwargs = {'device': 'cpu'}\nencode_kwargs = {'normalize_embeddings': True}\nhf = HuggingFaceBgeEmbeddings(\n    model_name=model_name,\n    model_kwargs=model_kwargs,\n    encode_kwargs=encode_kwargs\n)\nInitialize the sentence_transformer.\nparam cache_folder: Optional[str] = None\u00b6\nPath to store models.\nCan be also set by SENTENCE_TRANSFORMERS_HOME environment variable.\nparam encode_kwargs: Dict[str, Any] [Optional]\u00b6\nKeyword arguments to pass when calling the encode method of the model.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nKeyword arguments to pass to the model.\nparam model_name: str = 'BAAI/bge-large-en'\u00b6\nModel name to use.\nparam query_instruction: str = 'Represent this question for searching relevant passages: '\u00b6\nInstruction to use for embedding query.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceBgeEmbeddings.html"}
{"id": "850daaa2347c-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCompute doc embeddings using a HuggingFace transformer model.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCompute query embeddings using a HuggingFace transformer model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceBgeEmbeddings.html"}
{"id": "850daaa2347c-2", "text": "Parameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using HuggingFaceBgeEmbeddings\u00b6\nBGE on Hugging Face", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface.HuggingFaceBgeEmbeddings.html"}
{"id": "6414d1dc7ce9-0", "text": "langchain.embeddings.mosaicml.MosaicMLInstructorEmbeddings\u00b6\nclass langchain.embeddings.mosaicml.MosaicMLInstructorEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nMosaicML embedding service.\nTo use, you should have the\nenvironment variable MOSAICML_API_TOKEN set with your API token, or pass\nit as a named parameter to the constructor.\nExample\nfrom langchain.llms import MosaicMLInstructorEmbeddings\nendpoint_url = (\n    \"https://models.hosted-on.mosaicml.hosting/instructor-large/v1/predict\"\n)\nmosaic_llm = MosaicMLInstructorEmbeddings(\n    endpoint_url=endpoint_url,\n    mosaicml_api_token=\"my-api-key\"\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam embed_instruction: str = 'Represent the document for retrieval: '\u00b6\nInstruction used to embed documents.\nparam endpoint_url: str = 'https://models.hosted-on.mosaicml.hosting/instructor-xl/v1/predict'\u00b6\nEndpoint URL to use.\nparam mosaicml_api_token: Optional[str] = None\u00b6\nparam query_instruction: str = 'Represent the question for retrieving supporting documents: '\u00b6\nInstruction used to embed the query.\nparam retry_sleep: float = 1.0\u00b6\nHow long to try sleeping for if a rate limit is encountered\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.mosaicml.MosaicMLInstructorEmbeddings.html"}
{"id": "6414d1dc7ce9-1", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed documents using a MosaicML deployed instructor embedding model.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed a query using a MosaicML deployed instructor embedding model.\nParameters", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.mosaicml.MosaicMLInstructorEmbeddings.html"}
{"id": "6414d1dc7ce9-2", "text": "Embed a query using a MosaicML deployed instructor embedding model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.mosaicml.MosaicMLInstructorEmbeddings.html"}
{"id": "6414d1dc7ce9-3", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nExamples using MosaicMLInstructorEmbeddings\u00b6\nMosaicML", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.mosaicml.MosaicMLInstructorEmbeddings.html"}
{"id": "592992ced35f-0", "text": "langchain.embeddings.llm_rails.LLMRailsEmbeddings\u00b6\nclass langchain.embeddings.llm_rails.LLMRailsEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nLLMRails embedding models.\nTo use, you should have the  environment\nvariable LLM_RAILS_API_KEY set with your API key or pass it\nas a named parameter to the constructor.\nModel can be one of [\u201cembedding-english-v1\u201d,\u201dembedding-multi-v1\u201d]\nExample\nfrom langchain.embeddings import LLMRailsEmbeddings\ncohere = LLMRailsEmbeddings(\n    model=\"embedding-english-v1\", api_key=\"my-api-key\"\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_key: Optional[str] = None\u00b6\nLLMRails API key.\nparam model: str = 'embedding-english-v1'\u00b6\nModel name to use.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.llm_rails.LLMRailsEmbeddings.html"}
{"id": "592992ced35f-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCall out to Cohere\u2019s embedding endpoint.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to Cohere\u2019s embedding endpoint.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.llm_rails.LLMRailsEmbeddings.html"}
{"id": "592992ced35f-2", "text": "Embeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.llm_rails.LLMRailsEmbeddings.html"}
{"id": "e574a30dc35d-0", "text": "langchain.embeddings.johnsnowlabs.JohnSnowLabsEmbeddings\u00b6\nclass langchain.embeddings.johnsnowlabs.JohnSnowLabsEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nJohnSnowLabs embedding models\nTo use, you should have the johnsnowlabs python package installed.\n.. rubric:: Example\nfrom langchain.embeddings.johnsnowlabs import JohnSnowLabsEmbeddings\nembedding = JohnSnowLabsEmbeddings(model='embed_sentence.bert')\noutput = embedding.embed_query(\"foo bar\")\nInitialize the johnsnowlabs model.\nparam model: Any = 'embed_sentence.bert'\u00b6\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.johnsnowlabs.JohnSnowLabsEmbeddings.html"}
{"id": "e574a30dc35d-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCompute doc embeddings using a JohnSnowLabs transformer model.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCompute query embeddings using a JohnSnowLabs transformer model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.johnsnowlabs.JohnSnowLabsEmbeddings.html"}
{"id": "e574a30dc35d-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.johnsnowlabs.JohnSnowLabsEmbeddings.html"}
{"id": "2281b167db49-0", "text": "langchain.embeddings.huggingface_hub.HuggingFaceHubEmbeddings\u00b6\nclass langchain.embeddings.huggingface_hub.HuggingFaceHubEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nHuggingFaceHub embedding models.\nTo use, you should have the huggingface_hub python package installed, and the\nenvironment variable HUGGINGFACEHUB_API_TOKEN set with your API token, or pass\nit as a named parameter to the constructor.\nExample\nfrom langchain.embeddings import HuggingFaceHubEmbeddings\nrepo_id = \"sentence-transformers/all-mpnet-base-v2\"\nhf = HuggingFaceHubEmbeddings(\n    repo_id=repo_id,\n    task=\"feature-extraction\",\n    huggingfacehub_api_token=\"my-api-key\",\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam huggingfacehub_api_token: Optional[str] = None\u00b6\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam repo_id: str = 'sentence-transformers/all-mpnet-base-v2'\u00b6\nModel name to use.\nparam task: Optional[str] = 'feature-extraction'\u00b6\nTask to call the model with.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface_hub.HuggingFaceHubEmbeddings.html"}
{"id": "2281b167db49-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCall out to HuggingFaceHub\u2019s embedding endpoint for embedding search docs.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCall out to HuggingFaceHub\u2019s embedding endpoint for embedding query text.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface_hub.HuggingFaceHubEmbeddings.html"}
{"id": "2281b167db49-2", "text": "Parameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using HuggingFaceHubEmbeddings\u00b6\nHugging Face", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.huggingface_hub.HuggingFaceHubEmbeddings.html"}
{"id": "b27e45427fbf-0", "text": "langchain.embeddings.google_palm.GooglePalmEmbeddings\u00b6\nclass langchain.embeddings.google_palm.GooglePalmEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nGoogle\u2019s PaLM Embeddings APIs.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam client: Any = None\u00b6\nparam google_api_key: Optional[str] = None\u00b6\nparam model_name: str = 'models/embedding-gecko-001'\u00b6\nModel name to use.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.google_palm.GooglePalmEmbeddings.html"}
{"id": "b27e45427fbf-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed search docs.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed query text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.google_palm.GooglePalmEmbeddings.html"}
{"id": "b27e45427fbf-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.google_palm.GooglePalmEmbeddings.html"}
{"id": "f6c45b5dbd77-0", "text": "langchain.embeddings.openai.embed_with_retry\u00b6\nlangchain.embeddings.openai.embed_with_retry(embeddings: OpenAIEmbeddings, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the embedding call.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.openai.embed_with_retry.html"}
{"id": "b0368aa9d46b-0", "text": "langchain.embeddings.sagemaker_endpoint.EmbeddingsContentHandler\u00b6\nclass langchain.embeddings.sagemaker_endpoint.EmbeddingsContentHandler[source]\u00b6\nContent handler for LLM class.\nAttributes\naccepts\nThe MIME type of the response data returned from endpoint\ncontent_type\nThe MIME type of the input data passed to endpoint\nMethods\n__init__()\ntransform_input(prompt,\u00a0model_kwargs)\nTransforms the input to a format that model can accept as the request Body.\ntransform_output(output)\nTransforms the output from the model to string that the LLM class expects.\n__init__()\u00b6\nabstract transform_input(prompt: INPUT_TYPE, model_kwargs: Dict) \u2192 bytes\u00b6\nTransforms the input to a format that model can accept\nas the request Body. Should return bytes or seekable file\nlike object in the format specified in the content_type\nrequest header.\nabstract transform_output(output: bytes) \u2192 OUTPUT_TYPE\u00b6\nTransforms the output from the model to string that\nthe LLM class expects.\nExamples using EmbeddingsContentHandler\u00b6\nSageMaker", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.sagemaker_endpoint.EmbeddingsContentHandler.html"}
{"id": "7ebafe3fd2f2-0", "text": "langchain.embeddings.tensorflow_hub.TensorflowHubEmbeddings\u00b6\nclass langchain.embeddings.tensorflow_hub.TensorflowHubEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nTensorflowHub embedding models.\nTo use, you should have the tensorflow_text python package installed.\nExample\nfrom langchain.embeddings import TensorflowHubEmbeddings\nurl = \"https://tfhub.dev/google/universal-sentence-encoder-multilingual/3\"\ntf = TensorflowHubEmbeddings(model_url=url)\nInitialize the tensorflow_hub and tensorflow_text.\nparam model_url: str = 'https://tfhub.dev/google/universal-sentence-encoder-multilingual/3'\u00b6\nModel name to use.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.tensorflow_hub.TensorflowHubEmbeddings.html"}
{"id": "7ebafe3fd2f2-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCompute doc embeddings using a TensorflowHub embedding model.\nParameters\ntexts \u2013 The list of texts to embed.\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCompute query embeddings using a TensorflowHub embedding model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.tensorflow_hub.TensorflowHubEmbeddings.html"}
{"id": "7ebafe3fd2f2-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using TensorflowHubEmbeddings\u00b6\nTensorflowHub\nScaNN", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.tensorflow_hub.TensorflowHubEmbeddings.html"}
{"id": "11e2698f652d-0", "text": "langchain.embeddings.spacy_embeddings.SpacyEmbeddings\u00b6\nclass langchain.embeddings.spacy_embeddings.SpacyEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nEmbeddings by SpaCy models.\nIt only supports the \u2018en_core_web_sm\u2019 model.\nnlp\u00b6\nThe Spacy model loaded into memory.\nType\nAny\nembed_documents(texts\nList[str]) -> List[List[float]]:\nGenerates embeddings for a list of documents.\nembed_query(text\nstr) -> List[float]:\nGenerates an embedding for a single piece of text.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam nlp: Any = None\u00b6\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nAsynchronously generates embeddings for a list of documents.\nThis method is not implemented and raises a NotImplementedError.\nParameters\ntexts (List[str]) \u2013 The documents to generate embeddings for.\nRaises\nNotImplementedError \u2013 This method is not implemented.\nasync aembed_query(text: str) \u2192 List[float][source]\u00b6\nAsynchronously generates an embedding for a single piece of text.\nThis method is not implemented and raises a NotImplementedError.\nParameters\ntext (str) \u2013 The text to generate an embedding for.\nRaises\nNotImplementedError \u2013 This method is not implemented.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.spacy_embeddings.SpacyEmbeddings.html"}
{"id": "11e2698f652d-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nGenerates embeddings for a list of documents.\nParameters\ntexts (List[str]) \u2013 The documents to generate embeddings for.\nReturns\nA list of embeddings, one for each document.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nGenerates an embedding for a single piece of text.\nParameters\ntext (str) \u2013 The text to generate an embedding for.\nReturns\nThe embedding for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.spacy_embeddings.SpacyEmbeddings.html"}
{"id": "11e2698f652d-2", "text": "The embedding for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using SpacyEmbeddings\u00b6\nSpaCy\nspaCy", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.spacy_embeddings.SpacyEmbeddings.html"}
{"id": "1b74587d3f10-0", "text": "langchain.embeddings.gradient_ai.TinyAsyncGradientEmbeddingClient\u00b6\nclass langchain.embeddings.gradient_ai.TinyAsyncGradientEmbeddingClient(access_token: Optional[str] = None, workspace_id: Optional[str] = None, host: str = 'https://api.gradient.ai/api', aiosession: Optional[ClientSession] = None)[source]\u00b6\nA helper tool to embed Gradient. Not part of Langchain\u2019s or Gradients stable API,\ndirect use discouraged.\nTo use, set the environment variable GRADIENT_ACCESS_TOKEN with your\nAPI token and GRADIENT_WORKSPACE_ID for your gradient workspace,\nor alternatively provide them as keywords to the constructor of this class.\nExample\nmini_client = TinyAsyncGradientEmbeddingClient(\n    workspace_id=\"12345614fc0_workspace\",\n    access_token=\"gradientai-access_token\",\n)\nembeds = mini_client.embed(\n    model=\"bge-large\",\n    text=[\"doc1\", \"doc2\"]\n)\n# or\nembeds = await mini_client.aembed(\n    model=\"bge-large\",\n    text=[\"doc1\", \"doc2\"]\n)\nMethods\n__init__([access_token,\u00a0workspace_id,\u00a0host,\u00a0...])\naembed(model,\u00a0texts)\ncall the embedding of model, async method\nembed(model,\u00a0texts)\ncall the embedding of model\n__init__(access_token: Optional[str] = None, workspace_id: Optional[str] = None, host: str = 'https://api.gradient.ai/api', aiosession: Optional[ClientSession] = None) \u2192 None[source]\u00b6\nasync aembed(model: str, texts: List[str]) \u2192 List[List[float]][source]\u00b6\ncall the embedding of model, async method\nParameters\nmodel (str) \u2013 to embedding model\ntexts (List[str]) \u2013 List of sentences to embed.\nReturns", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.gradient_ai.TinyAsyncGradientEmbeddingClient.html"}
{"id": "1b74587d3f10-1", "text": "texts (List[str]) \u2013 List of sentences to embed.\nReturns\nList of vectors for each sentence\nReturn type\nList[List[float]]\nembed(model: str, texts: List[str]) \u2192 List[List[float]][source]\u00b6\ncall the embedding of model\nParameters\nmodel (str) \u2013 to embedding model\ntexts (List[str]) \u2013 List of sentences to embed.\nReturns\nList of vectors for each sentence\nReturn type\nList[List[float]]", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.gradient_ai.TinyAsyncGradientEmbeddingClient.html"}
{"id": "190ba94e020b-0", "text": "langchain.embeddings.self_hosted.SelfHostedEmbeddings\u00b6\nclass langchain.embeddings.self_hosted.SelfHostedEmbeddings[source]\u00b6\nBases: SelfHostedPipeline, Embeddings\nCustom embedding models on self-hosted remote hardware.\nSupported hardware includes auto-launched instances on AWS, GCP, Azure,\nand Lambda, as well as servers specified\nby IP address and SSH credentials (such as on-prem, or another\ncloud like Paperspace, Coreweave, etc.).\nTo use, you should have the runhouse python package installed.\nExample using a model load function:from langchain.embeddings import SelfHostedEmbeddings\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, pipeline\nimport runhouse as rh\ngpu = rh.cluster(name=\"rh-a10x\", instance_type=\"A100:1\")\ndef get_pipeline():\n    model_id = \"facebook/bart-large\"\n    tokenizer = AutoTokenizer.from_pretrained(model_id)\n    model = AutoModelForCausalLM.from_pretrained(model_id)\n    return pipeline(\"feature-extraction\", model=model, tokenizer=tokenizer)\nembeddings = SelfHostedEmbeddings(\n    model_load_fn=get_pipeline,\n    hardware=gpu\n    model_reqs=[\"./\", \"torch\", \"transformers\"],\n)\nExample passing in a pipeline path:from langchain.embeddings import SelfHostedHFEmbeddings\nimport runhouse as rh\nfrom transformers import pipeline\ngpu = rh.cluster(name=\"rh-a10x\", instance_type=\"A100:1\")\npipeline = pipeline(model=\"bert-base-uncased\", task=\"feature-extraction\")\nrh.blob(pickle.dumps(pipeline),\n    path=\"models/pipeline.pkl\").save().to(gpu, path=\"models\")\nembeddings = SelfHostedHFEmbeddings.from_pipeline(\n    pipeline=\"models/pipeline.pkl\",", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-1", "text": "pipeline=\"models/pipeline.pkl\",\n    hardware=gpu,\n    model_reqs=[\"./\", \"torch\", \"transformers\"],\n)\nInit the pipeline with an auxiliary function.\nThe load function must be in global scope to be imported\nand run on the server, i.e. in a module and not a REPL or closure.\nThen, initialize the remote inference function.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam hardware: Any = None\u00b6\nRemote hardware to send the inference function to.\nparam inference_fn: Callable = <function _embed_documents>\u00b6\nInference function to extract the embeddings on the remote hardware.\nparam inference_kwargs: Any = None\u00b6\nAny kwargs to pass to the model\u2019s inference function.\nparam load_fn_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model load function.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_load_fn: Callable [Required]\u00b6\nFunction to load the model remotely on the server.\nparam model_reqs: List[str] = ['./', 'torch']\u00b6\nRequirements to install on hardware to inference the model.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-2", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-3", "text": "Asynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-4", "text": "Parameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-5", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-6", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCompute doc embeddings using a HuggingFace transformer model.\nParameters\ntexts \u2013 The list of texts to embed.s\nReturns", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-7", "text": "Parameters\ntexts \u2013 The list of texts to embed.s\nReturns\nList of embeddings, one for each text.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nCompute query embeddings using a HuggingFace transformer model.\nParameters\ntext \u2013 The text to embed.\nReturns\nEmbeddings for the text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_pipeline(pipeline: Any, hardware: Any, model_reqs: Optional[List[str]] = None, device: int = 0, **kwargs: Any) \u2192 LLM\u00b6\nInit the SelfHostedPipeline from a pipeline object or string.\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-8", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-9", "text": "Useful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-10", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-11", "text": "predict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-12", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-13", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "190ba94e020b-14", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using SelfHostedEmbeddings\u00b6\nSelf Hosted", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.self_hosted.SelfHostedEmbeddings.html"}
{"id": "0c32a81a212d-0", "text": "langchain.embeddings.fake.FakeEmbeddings\u00b6\nclass langchain.embeddings.fake.FakeEmbeddings[source]\u00b6\nBases: Embeddings, BaseModel\nFake embedding model.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam size: int [Required]\u00b6\nThe size of the embedding vector.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.fake.FakeEmbeddings.html"}
{"id": "0c32a81a212d-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed search docs.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed query text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.fake.FakeEmbeddings.html"}
{"id": "0c32a81a212d-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using FakeEmbeddings\u00b6\nFake Embeddings\nDocArray Retriever\nVectara\nTair\nTencent Cloud VectorDB", "source": "lang/api.python.langchain.com/en/latest/embeddings/langchain.embeddings.fake.FakeEmbeddings.html"}
{"id": "9f10204d99b5-0", "text": "langchain_experimental.cpal.models.InterventionModel\u00b6\nclass langchain_experimental.cpal.models.InterventionModel[source]\u00b6\nBases: BaseModel\naka initial conditions\n>>> intervention.dict()\n{\n    entity_settings: [\n        {\"name\": \"bud\", \"attribute\": \"pet_count\", \"value\": 12},\n        {\"name\": \"pat\", \"attribute\": \"pet_count\", \"value\": 0},\n    ],\n    system_settings: None,\n}\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam entity_settings: List[langchain_experimental.cpal.models.EntitySettingModel] [Required]\u00b6\nparam system_settings: Optional[List[langchain_experimental.cpal.models.SystemSettingModel]] = None\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.InterventionModel.html"}
{"id": "9f10204d99b5-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.InterventionModel.html"}
{"id": "9f10204d99b5-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.InterventionModel.html"}
{"id": "3c42d772697c-0", "text": "langchain_experimental.cpal.models.ResultModel\u00b6\nclass langchain_experimental.cpal.models.ResultModel[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam question: str [Required] (alias 'narrative_input')\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.ResultModel.html"}
{"id": "3c42d772697c-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.ResultModel.html"}
{"id": "758c3139b004-0", "text": "langchain_experimental.cpal.models.CausalModel\u00b6\nclass langchain_experimental.cpal.models.CausalModel[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam attribute: str [Required]\u00b6\nname of the attribute to be calculated\nparam entities: List[langchain_experimental.cpal.models.EntityModel] [Required]\u00b6\nentities in the story\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.CausalModel.html"}
{"id": "758c3139b004-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.CausalModel.html"}
{"id": "758c3139b004-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.CausalModel.html"}
{"id": "cd9b88fa0020-0", "text": "langchain_experimental.cpal.constants.Constant\u00b6\nclass langchain_experimental.cpal.constants.Constant(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnum for constants used in the CPAL.\nnarrative_input = 'narrative_input'\u00b6\nchain_answer = 'chain_answer'\u00b6\nchain_data = 'chain_data'\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.constants.Constant.html"}
{"id": "a1935f10af0e-0", "text": "langchain_experimental.cpal.base.NarrativeChain\u00b6\nclass langchain_experimental.cpal.base.NarrativeChain[source]\u00b6\nBases: _BaseStoryElementChain\nDecompose the narrative into its story elements\ncausal model\nquery\nintervention\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\npydantic_model\u00b6\nalias of NarrativeModel\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-2", "text": "include_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-3", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-4", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-5", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-6", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-7", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_univariate_prompt(llm: BaseLanguageModel, **kwargs: Any) \u2192 Any\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-8", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parser() \u2192 PydanticOutputParser\u00b6\nParse LLM output into a pydantic object.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-10", "text": "with all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-11", "text": "stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-12", "text": "Bind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-13", "text": "property input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-14", "text": "template: ClassVar[str] = 'Split the given text into three parts: the question, the story_hypothetical, and the logic. Don\\'t guess at any of the parts. Write NONE if you are unsure.\\n\\n{format_instructions}\\n\\n\\n\\nQ: Boris has seven times the number of pets as Marcia. Jan has three times the number of pets as Marcia. Marcia has two more pets than Cindy. If Cindy has four pets, how many total pets do the three have?\\n\\n\\n\\n# JSON\\n\\n\\n\\n{{\\n\u00a0\u00a0\u00a0 \"story_outcome_question\": \"how many total pets do the three have?\",\\n\u00a0\u00a0\u00a0 \"story_hypothetical\": \"If Cindy has four pets\",\\n\u00a0\u00a0\u00a0 \"story_plot\": \"Boris has seven times the number of pets as Marcia. Jan has three times the number of pets as Marcia. Marcia has two more pets than Cindy.\"\\n}}\\n\\n\\n\\nQ: boris gives ten percent of his money to marcia. marcia gives ten\\npercent of her money to andy. If boris has 100 dollars, how much money\\nwill andy have?\\n\\n\\n\\n# JSON\\n\\n\\n\\n{{\\n\u00a0\u00a0\u00a0 \"story_outcome_question\": \"how much money will andy have?\",\\n\u00a0\u00a0\u00a0 \"story_hypothetical\": \"If boris has 100 dollars\"\\n\u00a0\u00a0\u00a0 \"story_plot\": \"boris gives ten percent of his money to marcia. marcia gives ten percent of her money to andy.\"\\n}}\\n\\n\\n\\n\\nQ: boris gives ten percent of his candy to marcia. marcia gives ten\\npercent of her candy to andy. If boris has 100 pounds of candy and marcia has\\n200 pounds of candy, then how many pounds of candy will andy have?\\n\\n\\n\\n\\n\\n#", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-15", "text": "candy, then how many pounds of candy will andy have?\\n\\n\\n\\n\\n\\n# JSON\\n\\n\\n\\n\\n{{\\n\u00a0\u00a0\u00a0 \"story_outcome_question\": \"how many pounds of candy will andy have?\",\\n\u00a0\u00a0\u00a0 \"story_hypothetical\": \"If boris has 100 pounds of candy and marcia has 200 pounds of candy\"\\n\u00a0\u00a0\u00a0 \"story_plot\": \"boris gives ten percent of his candy to marcia. marcia gives ten percent of her candy to andy.\"\\n}}\\n\\n\\n\\n\\n\\nQ: {narrative_input}\\n\\n\\n\\n# JSON\\n\\n\\n'\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "a1935f10af0e-16", "text": "meta private:", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.NarrativeChain.html"}
{"id": "35cc8fe60d71-0", "text": "langchain_experimental.cpal.base.InterventionChain\u00b6\nclass langchain_experimental.cpal.base.InterventionChain[source]\u00b6\nBases: _BaseStoryElementChain\nSet the hypothetical conditions for the causal model.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "35cc8fe60d71-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\npydantic_model\u00b6\nalias of InterventionModel\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "35cc8fe60d71-2", "text": "include_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "35cc8fe60d71-3", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "35cc8fe60d71-4", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "35cc8fe60d71-5", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "35cc8fe60d71-6", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "35cc8fe60d71-7", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_univariate_prompt(llm: BaseLanguageModel, **kwargs: Any) \u2192 Any\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "35cc8fe60d71-8", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "35cc8fe60d71-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parser() \u2192 PydanticOutputParser\u00b6\nParse LLM output into a pydantic object.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "35cc8fe60d71-10", "text": "with all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "35cc8fe60d71-11", "text": "stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "35cc8fe60d71-12", "text": "Bind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "35cc8fe60d71-13", "text": "property input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\ntemplate: ClassVar[str] = 'Transform the hypothetical whatif statement into JSON. Don\\'t guess at any of the parts. Write NONE if you are unsure.\\n\\n{format_instructions}\\n\\n\\n\\nstatement: if cindy\\'s pet count was 4\\n\\n\\n\\n\\n# JSON:\\n\\n\\n\\n{{\\n\u00a0\u00a0\u00a0 \"entity_settings\" : [\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {{ \"name\": \"cindy\", \"attribute\": \"pet_count\", \"value\": \"4\" }}\\n\u00a0\u00a0\u00a0 ]\\n}}\\n\\n\\n\\n\\n\\nstatement: Let\\'s say boris has ten dollars and Bill has 20 dollars.\\n\\n\\n\\n\\n# JSON:\\n\\n\\n{{\\n\u00a0\u00a0\u00a0 \"entity_settings\" : [\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {{ \"name\": \"boris\", \"attribute\": \"dollars\", \"value\": \"10\" }},\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {{ \"name\": \"bill\", \"attribute\": \"dollars\", \"value\": \"20\" }}\\n\u00a0\u00a0\u00a0 ]\\n}}\\n\\n\\n\\n\\n\\nStatement: {narrative_input}\\n\\n\\n\\n\\n# JSON:\\n\\n\\n'\u00b6\nmeta private:", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.InterventionChain.html"}
{"id": "b33b070f8c5c-0", "text": "langchain_experimental.cpal.base.QueryChain\u00b6\nclass langchain_experimental.cpal.base.QueryChain[source]\u00b6\nBases: _BaseStoryElementChain\nQuery the outcome table using SQL.\nSecurity note: This class implements an AI technique that generates SQL code.If those SQL commands are executed, it\u2019s critical to ensure they use credentials\nthat are narrowly-scoped to only include the permissions this chain needs.\nFailure to do so may result in data corruption or loss, since this chain may\nattempt commands like DROP TABLE or INSERT if appropriately prompted.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-1", "text": "Optional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\npydantic_model\u00b6\nalias of QueryModel\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-2", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-3", "text": "memory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-4", "text": "Convenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_univariate_prompt(llm: BaseLanguageModel, **kwargs: Any) \u2192 Any\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-8", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-9", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parser() \u2192 PydanticOutputParser\u00b6\nParse LLM output into a pydantic object.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-10", "text": "inputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-11", "text": "chain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-12", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-13", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-14", "text": "template: ClassVar[str] = 'Transform the narrative_input into an SQL expression. If you are\\nunsure, then do not guess, instead add a llm_error_msg that explains why you are unsure.\\n\\n\\n{format_instructions}\\n\\n\\nnarrative_input: how much money will boris have?\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"how much money will boris have?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT name, value FROM df WHERE name = \\'boris\\'\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\nnarrative_input: How much money does ted have?\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"How much money does ted have?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT name, value FROM df WHERE name = \\'ted\\'\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\nnarrative_input: what is the sum of pet count for all the people?\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"what is the sum of pet count for all the people?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT SUM(value) FROM df\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\nnarrative_input: what\\'s the average of the pet counts for all the people?\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"what\\'s the average of the pet counts for all the people?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT AVG(value) FROM df\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\nnarrative_input: what\\'s the maximum of the pet counts for all the", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-15", "text": "what\\'s the maximum of the pet counts for all the people?\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"what\\'s the maximum of the pet counts for all the people?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT MAX(value) FROM df\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\nnarrative_input: what\\'s the minimum of the pet counts for all the people?\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"what\\'s the minimum of the pet counts for all the people?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT MIN(value) FROM df\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\nnarrative_input: what\\'s the number of people with pet counts greater than 10?\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"what\\'s the number of people with pet counts greater than 10?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT COUNT(*) FROM df WHERE value > 10\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\nnarrative_input: what\\'s the pet count for boris?\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"what\\'s the pet count for boris?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT name, value FROM df WHERE name = \\'boris\\'\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\nnarrative_input: what\\'s the pet count for cindy and marcia?\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"what\\'s the pet count for cindy and", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-16", "text": "\"narrative_input\": \"what\\'s the pet count for cindy and marcia?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT name, value FROM df WHERE name IN (\\'cindy\\', \\'marcia\\')\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\nnarrative_input: what\\'s the total pet count for cindy and marcia?\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"what\\'s the total pet count for cindy and marcia?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT SUM(value) FROM df WHERE name IN (\\'cindy\\', \\'marcia\\')\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\nnarrative_input: what\\'s the total pet count for TED?\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"what\\'s the total pet count for TED?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT SUM(value) FROM df WHERE name = \\'TED\\'\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\n\\nnarrative_input: what\\'s the total dollar count for TED and cindy?\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"what\\'s the total dollar count for TED and cindy?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT SUM(value) FROM df WHERE name IN (\\'TED\\', \\'cindy\\')\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\nnarrative_input: what\\'s the total pet count for TED and cindy?\\n\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"what\\'s the total pet count for TED and", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-17", "text": "\"narrative_input\": \"what\\'s the total pet count for TED and cindy?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT SUM(value) FROM df WHERE name IN (\\'TED\\', \\'cindy\\')\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\nnarrative_input: what\\'s the best for TED and cindy?\\n\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"what\\'s the best for TED and cindy?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"ambiguous narrative_input, not sure what \\'best\\' means\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\nnarrative_input: what\\'s the value?\\n\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"what\\'s the value?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"ambiguous narrative_input, not sure what entity is being asked about\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\n\\n\\nnarrative_input: how many total pets do the three have?\\n\\n\\n\\n\\n\\n# JSON:\\n\\n\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"narrative_input\": \"how many total pets do the three have?\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"llm_error_msg\": \"\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"expression\": \"SELECT SUM(value) FROM df\"\\n\u00a0\u00a0\u00a0 }}\\n\\n\\n\\n\\n\\n\\nnarrative_input: {narrative_input}\\n\\n\\n\\n\\n# JSON:\\n\\n\\n'\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "b33b070f8c5c-18", "text": "meta private:", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.QueryChain.html"}
{"id": "87cc00bc14bd-0", "text": "langchain_experimental.cpal.base.CPALChain\u00b6\nclass langchain_experimental.cpal.base.CPALChain[source]\u00b6\nBases: _BaseStoryElementChain\nCausal program-aided language (CPAL) chain implementation.\nSecurity note: The building blocks of this class include the implementationof an AI technique that generates SQL code. If those SQL commands\nare executed, it\u2019s critical to ensure they use credentials that\nare narrowly-scoped to only include the permissions this chain needs.\nFailure to do so may result in data corruption or loss, since this chain may\nattempt commands like DROP TABLE or INSERT if appropriately prompted.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam causal_chain: Optional[CausalChain] = None\u00b6\nparam chain: LLMChain [Required]\u00b6\nparam intervention_chain: Optional[InterventionChain] = None\u00b6\nparam llm: BaseLanguageModel [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-1", "text": "and at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam narrative_chain: Optional[NarrativeChain] = None\u00b6\nparam query_chain: Optional[QueryChain] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-2", "text": "only one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-4", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-5", "text": "# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-6", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-7", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\ndraw(**kwargs: Any) \u2192 None[source]\u00b6\nCPAL chain can draw its resulting DAG.\nUsage in a jupyter notebook:\n>>> from IPython.display import SVG\n>>> cpal_chain.draw(path=\"graph.svg\")\n>>> SVG('graph.svg')\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_univariate_prompt(llm: BaseLanguageModel, **kwargs: Any) \u2192 CPALChain[source]\u00b6\ninstantiation depends on component chains", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-8", "text": "instantiation depends on component chains\nSecurity note: The building blocks of this class include the implementationof an AI technique that generates SQL code. If those SQL commands\nare executed, it\u2019s critical to ensure they use credentials that\nare narrowly-scoped to only include the permissions this chain needs.\nFailure to do so may result in data corruption or loss, since this chain may\nattempt commands like DROP TABLE or INSERT if appropriately prompted.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this chain.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-9", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-10", "text": "Return a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parser() \u2192 PydanticOutputParser\u00b6\nParse LLM output into a pydantic object.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-11", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-12", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-13", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "87cc00bc14bd-14", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\npydantic_model: ClassVar[Optional[Type[pydantic.BaseModel]]] = None\u00b6\nmeta private:\ntemplate: ClassVar[Optional[str]] = None\u00b6\nmeta private:", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CPALChain.html"}
{"id": "ce49027f9a43-0", "text": "langchain_experimental.cpal.models.SystemSettingModel\u00b6\nclass langchain_experimental.cpal.models.SystemSettingModel[source]\u00b6\nBases: BaseModel\nInitial global conditions for the system.\n{\u201cparameter\u201d: \u201cinterest_rate\u201d, \u201cvalue\u201d: .05}\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam parameter: str [Required]\u00b6\nparam value: float [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.SystemSettingModel.html"}
{"id": "ce49027f9a43-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.SystemSettingModel.html"}
{"id": "ce49027f9a43-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.SystemSettingModel.html"}
{"id": "f61d2c30697d-0", "text": "langchain_experimental.cpal.base.CausalChain\u00b6\nclass langchain_experimental.cpal.base.CausalChain[source]\u00b6\nBases: _BaseStoryElementChain\nTranslate the causal narrative into a stack of operations.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\npydantic_model\u00b6\nalias of CausalModel\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-2", "text": "include_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-3", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-4", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-5", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-6", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-7", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_univariate_prompt(llm: BaseLanguageModel, **kwargs: Any) \u2192 Any\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-8", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parser() \u2192 PydanticOutputParser\u00b6\nParse LLM output into a pydantic object.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-10", "text": "with all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-11", "text": "stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-12", "text": "Bind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-13", "text": "property input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-14", "text": "template: ClassVar[str] = 'Transform the math story plot into a JSON object. Don\\'t guess at any of the parts.\\n\\n{format_instructions}\\n\\n\\n\\nStory: Boris has seven times the number of pets as Marcia. Jan has three times the number of pets as Marcia. Marcia has two more pets than Cindy.\\n\\n\\n\\n# JSON:\\n\\n\\n\\n{{\\n\u00a0\u00a0\u00a0 \"attribute\": \"pet_count\",\\n\u00a0\u00a0\u00a0 \"entities\": [\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"name\": \"cindy\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"value\": 0,\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"depends_on\": [],\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"code\": \"pass\"\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }},\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"name\": \"marcia\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"value\": 0,\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"depends_on\": [\"cindy\"],\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"code\": \"marcia.value = cindy.value + 2\"\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }},\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"name\": \"boris\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"value\": 0,\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"depends_on\": [\"marcia\"],\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"code\": \"boris.value = marcia.value * 7\"\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }},\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"name\": \"jan\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"value\": 0,\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"depends_on\": [\"marcia\"],\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"code\": \"jan.value = marcia.value * 3\"\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }}\\n\u00a0\u00a0\u00a0 ]\\n}}\\n\\n\\n\\n\\nStory: Boris gives 20 percent of his money to Marcia. Marcia gives 10\\npercent of her money to Cindy. Cindy gives 5 percent of her money to Jan.\\n\\n\\n\\n\\n# JSON:\\n\\n\\n\\n{{\\n\u00a0\u00a0\u00a0 \"attribute\": \"money\",\\n", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-15", "text": "JSON:\\n\\n\\n\\n{{\\n\u00a0\u00a0\u00a0 \"attribute\": \"money\",\\n\u00a0\u00a0\u00a0 \"entities\": [\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"name\": \"boris\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"value\": 0,\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"depends_on\": [],\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"code\": \"pass\"\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }},\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"name\": \"marcia\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"value\": 0,\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"depends_on\": [\"boris\"],\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"code\": \"\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 marcia.value = boris.value * 0.2\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 boris.value = boris.value * 0.8\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }},\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"name\": \"cindy\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"value\": 0,\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"depends_on\": [\"marcia\"],\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"code\": \"\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 cindy.value = marcia.value * 0.1\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 marcia.value = marcia.value * 0.9\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }},\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {{\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"name\": \"jan\",\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"value\": 0,\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"depends_on\": [\"cindy\"],\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"code\": \"\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 jan.value = cindy.value * 0.05\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 cindy.value = cindy.value * 0.9\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"\\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }}\\n\u00a0\u00a0\u00a0 ]\\n}}\\n\\n\\n\\n\\nStory: {narrative_input}\\n\\n\\n\\n# JSON:\\n'\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f61d2c30697d-16", "text": "meta private:", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.base.CausalChain.html"}
{"id": "f9245fbe795a-0", "text": "langchain_experimental.cpal.models.EntityModel\u00b6\nclass langchain_experimental.cpal.models.EntityModel[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam code: str [Required]\u00b6\nentity actions\nparam depends_on: List[str] = []\u00b6\nancestor entities\nparam name: str [Required]\u00b6\nentity name\nparam value: float [Required]\u00b6\nentity initial value\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.EntityModel.html"}
{"id": "f9245fbe795a-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.EntityModel.html"}
{"id": "f9245fbe795a-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.EntityModel.html"}
{"id": "b4766b86e928-0", "text": "langchain_experimental.cpal.models.StoryModel\u00b6\nclass langchain_experimental.cpal.models.StoryModel[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam causal_operations: Any = None\u00b6\nparam intervention: Any = None\u00b6\nparam query: Any = None\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.StoryModel.html"}
{"id": "b4766b86e928-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprint_debug_report() \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.StoryModel.html"}
{"id": "b4766b86e928-2", "text": "print_debug_report() \u2192 None[source]\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.StoryModel.html"}
{"id": "c2d6e8af0282-0", "text": "langchain_experimental.cpal.models.EntitySettingModel\u00b6\nclass langchain_experimental.cpal.models.EntitySettingModel[source]\u00b6\nBases: BaseModel\nInitial conditions for an entity\n{\u201cname\u201d: \u201cbud\u201d, \u201cattribute\u201d: \u201cpet_count\u201d, \u201cvalue\u201d: 12}\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam attribute: str [Required]\u00b6\nname of the attribute to be calculated\nparam name: str [Required]\u00b6\nname of the entity\nparam value: float [Required]\u00b6\nentity\u2019s attribute value (calculated)\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.EntitySettingModel.html"}
{"id": "c2d6e8af0282-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.EntitySettingModel.html"}
{"id": "c2d6e8af0282-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.EntitySettingModel.html"}
{"id": "74dadf5e1737-0", "text": "langchain_experimental.cpal.models.QueryModel\u00b6\nclass langchain_experimental.cpal.models.QueryModel[source]\u00b6\nBases: BaseModel\ntranslate a question about the story outcome into a programmatic expression\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam expression: str [Required]\u00b6\nparam llm_error_msg: str [Required]\u00b6\nparam question: str [Required] (alias 'narrative_input')\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.QueryModel.html"}
{"id": "74dadf5e1737-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.QueryModel.html"}
{"id": "74dadf5e1737-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.QueryModel.html"}
{"id": "3a9b40e255b2-0", "text": "langchain_experimental.cpal.models.NarrativeModel\u00b6\nclass langchain_experimental.cpal.models.NarrativeModel[source]\u00b6\nBases: BaseModel\nRepresent the narrative input as three story elements.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam story_hypothetical: str [Required]\u00b6\nparam story_outcome_question: str [Required]\u00b6\nparam story_plot: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.NarrativeModel.html"}
{"id": "3a9b40e255b2-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.NarrativeModel.html"}
{"id": "3a9b40e255b2-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/cpal/langchain_experimental.cpal.models.NarrativeModel.html"}
{"id": "bb875a277a69-0", "text": "langchain.retrievers.bm25.default_preprocessing_func\u00b6\nlangchain.retrievers.bm25.default_preprocessing_func(text: str) \u2192 List[str][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.bm25.default_preprocessing_func.html"}
{"id": "0f3353b05b13-0", "text": "langchain.retrievers.self_query.opensearch.OpenSearchTranslator\u00b6\nclass langchain.retrievers.self_query.opensearch.OpenSearchTranslator[source]\u00b6\nTranslate OpenSearch internal query domain-specific\nlanguage elements to valid filters.\nAttributes\nallowed_comparators\nSubset of allowed logical comparators.\nallowed_operators\nSubset of allowed logical operators.\nMethods\n__init__()\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__()\u00b6\nvisit_comparison(comparison: Comparison) \u2192 Dict[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 Dict[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, dict][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.opensearch.OpenSearchTranslator.html"}
{"id": "157e7d49e696-0", "text": "langchain_experimental.retrievers.vector_sql_database.VectorSQLDatabaseChainRetriever\u00b6\nclass langchain_experimental.retrievers.vector_sql_database.VectorSQLDatabaseChainRetriever[source]\u00b6\nBases: BaseRetriever\nRetriever that uses SQLDatabase as Retriever\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam page_content_key: str = 'content'\u00b6\ncolumn name for page content of documents\nparam sql_db_chain: langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain [Required]\u00b6\nSQL Database Chain\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain_experimental.retrievers.vector_sql_database.VectorSQLDatabaseChainRetriever.html"}
{"id": "157e7d49e696-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain_experimental.retrievers.vector_sql_database.VectorSQLDatabaseChainRetriever.html"}
{"id": "157e7d49e696-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain_experimental.retrievers.vector_sql_database.VectorSQLDatabaseChainRetriever.html"}
{"id": "157e7d49e696-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain_experimental.retrievers.vector_sql_database.VectorSQLDatabaseChainRetriever.html"}
{"id": "157e7d49e696-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain_experimental.retrievers.vector_sql_database.VectorSQLDatabaseChainRetriever.html"}
{"id": "157e7d49e696-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain_experimental.retrievers.vector_sql_database.VectorSQLDatabaseChainRetriever.html"}
{"id": "157e7d49e696-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain_experimental.retrievers.vector_sql_database.VectorSQLDatabaseChainRetriever.html"}
{"id": "157e7d49e696-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain_experimental.retrievers.vector_sql_database.VectorSQLDatabaseChainRetriever.html"}
{"id": "157e7d49e696-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain_experimental.retrievers.vector_sql_database.VectorSQLDatabaseChainRetriever.html"}
{"id": "157e7d49e696-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain_experimental.retrievers.vector_sql_database.VectorSQLDatabaseChainRetriever.html"}
{"id": "be934a66cb35-0", "text": "langchain.retrievers.kendra.DocumentAttributeValue\u00b6\nclass langchain.retrievers.kendra.DocumentAttributeValue[source]\u00b6\nBases: BaseModel\nValue of a document attribute.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam DateValue: Optional[str] = None\u00b6\nThe date expressed as an ISO 8601 string.\nparam LongValue: Optional[int] = None\u00b6\nThe long value.\nparam StringListValue: Optional[List[str]] = None\u00b6\nThe string list value.\nparam StringValue: Optional[str] = None\u00b6\nThe string value.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.DocumentAttributeValue.html"}
{"id": "be934a66cb35-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.DocumentAttributeValue.html"}
{"id": "be934a66cb35-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty value: Optional[Union[str, int, List[str]]]\u00b6\nThe only defined document attribute value or None.\nAccording to Amazon Kendra, you can only provide one\nvalue for a document attribute.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.DocumentAttributeValue.html"}
{"id": "fc11f34c36dd-0", "text": "langchain.retrievers.pubmed.PubMedRetriever\u00b6\nclass langchain.retrievers.pubmed.PubMedRetriever[source]\u00b6\nBases: BaseRetriever, PubMedAPIWrapper\nPubMed API retriever.\nIt wraps load() to get_relevant_documents().\nIt uses all PubMedAPIWrapper arguments without any change.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam MAX_QUERY_LENGTH: int = 300\u00b6\nparam base_url_efetch: str = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?'\u00b6\nparam base_url_esearch: str = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?'\u00b6\nparam doc_content_chars_max: int = 2000\u00b6\nparam email: str = 'your_email@example.com'\u00b6\nparam max_retry: int = 5\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam sleep_time: float = 0.2\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam top_k_results: int = 3\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pubmed.PubMedRetriever.html"}
{"id": "fc11f34c36dd-1", "text": "use case.\nparam top_k_results: int = 3\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pubmed.PubMedRetriever.html"}
{"id": "fc11f34c36dd-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pubmed.PubMedRetriever.html"}
{"id": "fc11f34c36dd-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pubmed.PubMedRetriever.html"}
{"id": "fc11f34c36dd-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pubmed.PubMedRetriever.html"}
{"id": "fc11f34c36dd-5", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pubmed.PubMedRetriever.html"}
{"id": "fc11f34c36dd-6", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nlazy_load(query: str) \u2192 Iterator[dict]\u00b6\nSearch PubMed for documents matching the query.\nReturn an iterator of dictionaries containing the document metadata.\nlazy_load_docs(query: str) \u2192 Iterator[Document]\u00b6\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nload(query: str) \u2192 List[dict]\u00b6\nSearch PubMed for documents matching the query.\nReturn a list of dictionaries containing the document metadata.\nload_docs(query: str) \u2192 List[Document]\u00b6\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pubmed.PubMedRetriever.html"}
{"id": "fc11f34c36dd-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nretrieve_article(uid: str, webenv: str) \u2192 dict\u00b6\nrun(query: str) \u2192 str\u00b6\nRun PubMed search and get the article meta information.\nSee https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch\nIt uses only the most informative fields of article meta information.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pubmed.PubMedRetriever.html"}
{"id": "fc11f34c36dd-8", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pubmed.PubMedRetriever.html"}
{"id": "fc11f34c36dd-9", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pubmed.PubMedRetriever.html"}
{"id": "fc11f34c36dd-10", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using PubMedRetriever\u00b6\nPubMed", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pubmed.PubMedRetriever.html"}
{"id": "cfa74f0ff6c6-0", "text": "langchain.retrievers.cohere_rag_retriever.CohereRagRetriever\u00b6\nclass langchain.retrievers.cohere_rag_retriever.CohereRagRetriever[source]\u00b6\nBases: BaseRetriever\nCohere Chat API with RAG.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam connectors: List[Dict] [Optional]\u00b6\nWhen specified, the model\u2019s reply will be enriched with information found by\nquerying each of the connectors (RAG). These will be returned as langchain\ndocuments.\nCurrently only accepts {\u201cid\u201d: \u201cweb-search\u201d}.\nparam llm: BaseChatModel [Required]\u00b6\nCohere ChatModel to use.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.cohere_rag_retriever.CohereRagRetriever.html"}
{"id": "cfa74f0ff6c6-1", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.cohere_rag_retriever.CohereRagRetriever.html"}
{"id": "cfa74f0ff6c6-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.cohere_rag_retriever.CohereRagRetriever.html"}
{"id": "cfa74f0ff6c6-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.cohere_rag_retriever.CohereRagRetriever.html"}
{"id": "cfa74f0ff6c6-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.cohere_rag_retriever.CohereRagRetriever.html"}
{"id": "cfa74f0ff6c6-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.cohere_rag_retriever.CohereRagRetriever.html"}
{"id": "cfa74f0ff6c6-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.cohere_rag_retriever.CohereRagRetriever.html"}
{"id": "cfa74f0ff6c6-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.cohere_rag_retriever.CohereRagRetriever.html"}
{"id": "cfa74f0ff6c6-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.cohere_rag_retriever.CohereRagRetriever.html"}
{"id": "cfa74f0ff6c6-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.cohere_rag_retriever.CohereRagRetriever.html"}
{"id": "516aecd193b5-0", "text": "langchain.retrievers.kendra.QueryResult\u00b6\nclass langchain.retrievers.kendra.QueryResult[source]\u00b6\nBases: BaseModel\nAmazon Kendra Query API search result.\nIt is composed of:\nRelevant suggested answers: either a text excerpt or table excerpt.\nMatching FAQs or questions-answer from your FAQ file.\nDocuments including an excerpt of each document with its title.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ResultItems: List[langchain.retrievers.kendra.QueryResultItem] [Required]\u00b6\nThe result items.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.QueryResult.html"}
{"id": "516aecd193b5-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.QueryResult.html"}
{"id": "516aecd193b5-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.QueryResult.html"}
{"id": "df58c57253c8-0", "text": "langchain.retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever\u00b6\nclass langchain.retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever[source]\u00b6\nBases: GoogleVertexAISearchRetriever\nGoogle Vertex Search API retriever alias for backwards compatibility.\nDEPRECATED: Use GoogleVertexAISearchRetriever instead.\nInitializes private fields.\nparam credentials: Any = None\u00b6\nThe default custom credentials (google.auth.credentials.Credentials) to use\nwhen making API calls. If not provided, credentials will be ascertained from\nthe environment.\nparam data_store_id: str [Required]\u00b6\nVertex AI Search data store ID.\nparam engine_data_type: int = 0\u00b6\nDefines the Vertex AI Search data type\n0 - Unstructured data\n1 - Structured data\n2 - Website data\nConstraints\nminimum = 0\nmaximum = 2\nparam filter: Optional[str] = None\u00b6\nFilter expression.\nparam get_extractive_answers: bool = False\u00b6\nIf True return Extractive Answers, otherwise return Extractive Segments or Snippets.\nparam location_id: str = 'global'\u00b6\nVertex AI Search data store location.\nparam max_documents: int = 5\u00b6\nThe maximum number of documents to return.\nConstraints\nminimum = 1\nmaximum = 100\nparam max_extractive_answer_count: int = 1\u00b6\nThe maximum number of extractive answers returned in each search result.\nAt most 5 answers will be returned for each SearchResult.\nConstraints\nminimum = 1\nmaximum = 5\nparam max_extractive_segment_count: int = 1\u00b6\nThe maximum number of extractive segments returned in each search result.\nCurrently one segment will be returned for each SearchResult.\nConstraints\nminimum = 1\nmaximum = 1", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever.html"}
{"id": "df58c57253c8-1", "text": "Constraints\nminimum = 1\nmaximum = 1\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam project_id: str [Required]\u00b6\nGoogle Cloud Project ID.\nparam query_expansion_condition: int = 1\u00b6\nSpecification to determine under which conditions query expansion should occur.\n0 - Unspecified query expansion condition. In this case, server behavior defaults\nto disabled\n1 - Disabled query expansion. Only the exact search query is used, even ifSearchResponse.total_size is zero.\n2 - Automatic query expansion built by the Search API.\nConstraints\nminimum = 0\nmaximum = 2\nparam serving_config_id: str = 'default_config'\u00b6\nVertex AI Search serving config ID.\nparam spell_correction_mode: int = 2\u00b6\nSpecification to determine under which conditions query expansion should occur.\n0 - Unspecified spell correction mode. In this case, server behavior defaults\nto auto.\n1 - Suggestion only. Search API will try to find a spell suggestion if there is anyand put in the SearchResponse.corrected_query.\nThe spell suggestion will not be used as the search query.\n2 - Automatic spell correction built by the Search API.Search will be based on the corrected query if found.\nConstraints\nminimum = 0\nmaximum = 2\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever.html"}
{"id": "df58c57253c8-2", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever.html"}
{"id": "df58c57253c8-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever.html"}
{"id": "df58c57253c8-4", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever.html"}
{"id": "df58c57253c8-5", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever.html"}
{"id": "df58c57253c8-6", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever.html"}
{"id": "df58c57253c8-7", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever.html"}
{"id": "df58c57253c8-8", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever.html"}
{"id": "df58c57253c8-9", "text": "Returns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever.html"}
{"id": "df58c57253c8-10", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty client_options: ClientOptions\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever.html"}
{"id": "c89aa8c49845-0", "text": "langchain.retrievers.self_query.deeplake.can_cast_to_float\u00b6\nlangchain.retrievers.self_query.deeplake.can_cast_to_float(string: str) \u2192 bool[source]\u00b6\nCheck if a string can be cast to a float.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.deeplake.can_cast_to_float.html"}
{"id": "3d093b4c52b7-0", "text": "langchain.retrievers.document_compressors.base.BaseDocumentCompressor\u00b6\nclass langchain.retrievers.document_compressors.base.BaseDocumentCompressor[source]\u00b6\nBases: BaseModel, ABC\nBase class for document compressors.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nasync acompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Document][source]\u00b6\nCompress retrieved documents given the query context.\nabstract compress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Document][source]\u00b6\nCompress retrieved documents given the query context.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.base.BaseDocumentCompressor.html"}
{"id": "3d093b4c52b7-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.base.BaseDocumentCompressor.html"}
{"id": "3d093b4c52b7-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.base.BaseDocumentCompressor.html"}
{"id": "808c8b73bba3-0", "text": "langchain.retrievers.knn.KNNRetriever\u00b6\nclass langchain.retrievers.knn.KNNRetriever[source]\u00b6\nBases: BaseRetriever\nKNN retriever.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam embeddings: Embeddings [Required]\u00b6\nEmbeddings model to use.\nparam index: Any = None\u00b6\nIndex of embeddings.\nparam k: int = 4\u00b6\nNumber of results to return.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam relevancy_threshold: Optional[float] = None\u00b6\nThreshold for relevancy.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam texts: List[str] [Required]\u00b6\nList of texts to index.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.knn.KNNRetriever.html"}
{"id": "808c8b73bba3-1", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.knn.KNNRetriever.html"}
{"id": "808c8b73bba3-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.knn.KNNRetriever.html"}
{"id": "808c8b73bba3-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.knn.KNNRetriever.html"}
{"id": "808c8b73bba3-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_texts(texts: List[str], embeddings: Embeddings, **kwargs: Any) \u2192 KNNRetriever[source]\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.knn.KNNRetriever.html"}
{"id": "808c8b73bba3-5", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.knn.KNNRetriever.html"}
{"id": "808c8b73bba3-6", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.knn.KNNRetriever.html"}
{"id": "808c8b73bba3-7", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.knn.KNNRetriever.html"}
{"id": "808c8b73bba3-8", "text": "Returns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.knn.KNNRetriever.html"}
{"id": "808c8b73bba3-9", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using KNNRetriever\u00b6\nkNN", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.knn.KNNRetriever.html"}
{"id": "0caecd6e573a-0", "text": "langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever\u00b6\nclass langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever[source]\u00b6\nBases: BaseRetriever\nPinecone Hybrid Search retriever.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam alpha: float = 0.5\u00b6\nAlpha value for hybrid search.\nparam embeddings: langchain.schema.embeddings.Embeddings [Required]\u00b6\nEmbeddings model to use.\nparam index: Any = None\u00b6\nPinecone index to use.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam namespace: Optional[str] = None\u00b6\nNamespace value for index partition.\nparam sparse_encoder: Any = None\u00b6\nSparse encoder to use.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam top_k: int = 4\u00b6\nNumber of documents to return.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever.html"}
{"id": "0caecd6e573a-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nadd_texts(texts: List[str], ids: Optional[List[str]] = None, metadatas: Optional[List[dict]] = None, namespace: Optional[str] = None) \u2192 None[source]\u00b6\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever.html"}
{"id": "0caecd6e573a-2", "text": "Default implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever.html"}
{"id": "0caecd6e573a-3", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever.html"}
{"id": "0caecd6e573a-4", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever.html"}
{"id": "0caecd6e573a-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever.html"}
{"id": "0caecd6e573a-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever.html"}
{"id": "0caecd6e573a-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever.html"}
{"id": "0caecd6e573a-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever.html"}
{"id": "0caecd6e573a-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using PineconeHybridSearchRetriever\u00b6\nPinecone Hybrid Search", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever.html"}
{"id": "f7b2acf72da7-0", "text": "langchain.retrievers.zep.SearchScope\u00b6\nclass langchain.retrievers.zep.SearchScope(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nWhich documents to search. Messages or Summaries?\nmessages = 'messages'\u00b6\nSearch chat history messages.\nsummary = 'summary'\u00b6\nSearch chat history summaries.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zep.SearchScope.html"}
{"id": "ceb6011fa561-0", "text": "langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever\u00b6\nclass langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever[source]\u00b6\nBases: BaseRetriever\nChatGPT plugin retriever.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aiosession: Optional[aiohttp.ClientSession] = None\u00b6\nAiohttp session to use for requests.\nparam bearer_token: str [Required]\u00b6\nBearer token for the ChatGPT plugin.\nparam filter: Optional[dict] = None\u00b6\nFilter to apply to the results.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam top_k: int = 3\u00b6\nNumber of documents to return.\nparam url: str [Required]\u00b6\nURL of the ChatGPT plugin.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever.html"}
{"id": "ceb6011fa561-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever.html"}
{"id": "ceb6011fa561-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever.html"}
{"id": "ceb6011fa561-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever.html"}
{"id": "ceb6011fa561-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever.html"}
{"id": "ceb6011fa561-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever.html"}
{"id": "ceb6011fa561-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever.html"}
{"id": "ceb6011fa561-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever.html"}
{"id": "ceb6011fa561-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever.html"}
{"id": "ceb6011fa561-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ChatGPTPluginRetriever\u00b6\nChatGPT Plugin\nOpenAI", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever.html"}
{"id": "299d245f2f89-0", "text": "langchain.retrievers.web_research.SearchQueries\u00b6\nclass langchain.retrievers.web_research.SearchQueries[source]\u00b6\nBases: BaseModel\nSearch queries to research for the user\u2019s goal.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam queries: List[str] [Required]\u00b6\nList of search queries to look up on Google\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.SearchQueries.html"}
{"id": "299d245f2f89-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.SearchQueries.html"}
{"id": "299d245f2f89-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.SearchQueries.html"}
{"id": "a8a71522e89f-0", "text": "langchain.retrievers.web_research.LineList\u00b6\nclass langchain.retrievers.web_research.LineList[source]\u00b6\nBases: BaseModel\nList of questions.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam lines: List[str] [Required]\u00b6\nQuestions\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.LineList.html"}
{"id": "a8a71522e89f-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.LineList.html"}
{"id": "8063156a5b69-0", "text": "langchain.retrievers.tavily_search_api.SearchDepth\u00b6\nclass langchain.retrievers.tavily_search_api.SearchDepth(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nSearch depth as enumerator.\nBASIC = 'basic'\u00b6\nADVANCED = 'advanced'\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tavily_search_api.SearchDepth.html"}
{"id": "65d9bc972579-0", "text": "langchain.retrievers.web_research.QuestionListOutputParser\u00b6\nclass langchain.retrievers.web_research.QuestionListOutputParser[source]\u00b6\nBases: PydanticOutputParser\nOutput parser for a list of numbered questions.\nparam pydantic_object: Type[T] [Required]\u00b6\nThe pydantic model to parse.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.QuestionListOutputParser.html"}
{"id": "65d9bc972579-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.QuestionListOutputParser.html"}
{"id": "65d9bc972579-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.QuestionListOutputParser.html"}
{"id": "65d9bc972579-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.QuestionListOutputParser.html"}
{"id": "65d9bc972579-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.QuestionListOutputParser.html"}
{"id": "65d9bc972579-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 LineList[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.QuestionListOutputParser.html"}
{"id": "65d9bc972579-6", "text": "prompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.QuestionListOutputParser.html"}
{"id": "65d9bc972579-7", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.QuestionListOutputParser.html"}
{"id": "65d9bc972579-8", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.QuestionListOutputParser.html"}
{"id": "5f7a2facb549-0", "text": "langchain.retrievers.zep.ZepRetriever\u00b6\nclass langchain.retrievers.zep.ZepRetriever[source]\u00b6\nBases: BaseRetriever\nZep MemoryStore Retriever.\nSearch your user\u2019s long-term chat history with Zep.\nZep offers both simple semantic search and Maximal Marginal Relevance (MMR)\nreranking of search results.\nNote: You will need to provide the user\u2019s session_id to use this retriever.\nParameters\nurl \u2013 URL of your Zep server (required)\napi_key \u2013 Your Zep API key (optional)\nsession_id \u2013 Identifies your user or a user\u2019s session (required)\ntop_k \u2013 Number of documents to return (default: 3, optional)\nsearch_type \u2013 Type of search to perform (similarity / mmr) (default: similarity,\noptional)\nmmr_lambda \u2013 Lambda value for MMR search. Defaults to 0.5 (optional)\nZep is an open source platform for productionizing LLM apps. Go from a prototype\nbuilt in LangChain or LlamaIndex, or a custom app, to production in minutes without\nrewriting code.\nFor server installation instructions, see:\nhttps://docs.getzep.com/deployment/quickstart/\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_key: Optional[str] = None\u00b6\nYour Zep API key.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zep.ZepRetriever.html"}
{"id": "5f7a2facb549-1", "text": "use case.\nparam mmr_lambda: Optional[float] = None\u00b6\nLambda value for MMR search.\nparam search_scope: langchain.retrievers.zep.SearchScope = SearchScope.messages\u00b6\nWhich documents to search. Messages or Summaries?\nparam search_type: langchain.retrievers.zep.SearchType = SearchType.similarity\u00b6\nType of search to perform (similarity / mmr)\nparam session_id: str [Required]\u00b6\nZep session ID.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam top_k: Optional[int] = None\u00b6\nNumber of items to return.\nparam url: str [Required]\u00b6\nURL of your Zep server.\nparam zep_client: Optional[Any] = None\u00b6\nZep client.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zep.ZepRetriever.html"}
{"id": "5f7a2facb549-2", "text": "Asynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zep.ZepRetriever.html"}
{"id": "5f7a2facb549-3", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zep.ZepRetriever.html"}
{"id": "5f7a2facb549-4", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zep.ZepRetriever.html"}
{"id": "5f7a2facb549-5", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zep.ZepRetriever.html"}
{"id": "5f7a2facb549-6", "text": "This method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zep.ZepRetriever.html"}
{"id": "5f7a2facb549-7", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zep.ZepRetriever.html"}
{"id": "5f7a2facb549-8", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zep.ZepRetriever.html"}
{"id": "5f7a2facb549-9", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zep.ZepRetriever.html"}
{"id": "5f7a2facb549-10", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ZepRetriever\u00b6\nZep\nZep Memory", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zep.ZepRetriever.html"}
{"id": "b60431e800fa-0", "text": "langchain.retrievers.bm25.BM25Retriever\u00b6\nclass langchain.retrievers.bm25.BM25Retriever[source]\u00b6\nBases: BaseRetriever\nBM25 retriever without Elasticsearch.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam docs: List[langchain.schema.document.Document] [Required]\u00b6\nList of documents.\nparam k: int = 4\u00b6\nNumber of documents to return.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam preprocess_func: Callable[[str], List[str]] = <function default_preprocessing_func>\u00b6\nPreprocessing function to use on the text before BM25 vectorization.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam vectorizer: Any = None\u00b6\nBM25 vectorizer.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.bm25.BM25Retriever.html"}
{"id": "b60431e800fa-1", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.bm25.BM25Retriever.html"}
{"id": "b60431e800fa-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.bm25.BM25Retriever.html"}
{"id": "b60431e800fa-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.bm25.BM25Retriever.html"}
{"id": "b60431e800fa-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_documents(documents: ~typing.Iterable[~langchain.schema.document.Document], *, bm25_params: ~typing.Optional[~typing.Dict[str, ~typing.Any]] = None, preprocess_func: ~typing.Callable[[str], ~typing.List[str]] = <function default_preprocessing_func>, **kwargs: ~typing.Any) \u2192 BM25Retriever[source]\u00b6\nCreate a BM25Retriever from a list of Documents.\n:param documents: A list of Documents to vectorize.\n:param bm25_params: Parameters to pass to the BM25 vectorizer.\n:param preprocess_func: A function to preprocess each text before vectorization.\n:param **kwargs: Any other arguments to pass to the retriever.\nReturns\nA BM25Retriever instance.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.bm25.BM25Retriever.html"}
{"id": "b60431e800fa-5", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_texts(texts: ~typing.Iterable[str], metadatas: ~typing.Optional[~typing.Iterable[dict]] = None, bm25_params: ~typing.Optional[~typing.Dict[str, ~typing.Any]] = None, preprocess_func: ~typing.Callable[[str], ~typing.List[str]] = <function default_preprocessing_func>, **kwargs: ~typing.Any) \u2192 BM25Retriever[source]\u00b6\nCreate a BM25Retriever from a list of texts.\n:param texts: A list of texts to vectorize.\n:param metadatas: A list of metadata dicts to associate with each text.\n:param bm25_params: Parameters to pass to the BM25 vectorizer.\n:param preprocess_func: A function to preprocess each text before vectorization.\n:param **kwargs: Any other arguments to pass to the retriever.\nReturns\nA BM25Retriever instance.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.bm25.BM25Retriever.html"}
{"id": "b60431e800fa-6", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.bm25.BM25Retriever.html"}
{"id": "b60431e800fa-7", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.bm25.BM25Retriever.html"}
{"id": "b60431e800fa-8", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.bm25.BM25Retriever.html"}
{"id": "b60431e800fa-9", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.bm25.BM25Retriever.html"}
{"id": "b60431e800fa-10", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using BM25Retriever\u00b6\nBM25\nEnsemble Retriever", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.bm25.BM25Retriever.html"}
{"id": "d31d36819c67-0", "text": "langchain.retrievers.self_query.pinecone.PineconeTranslator\u00b6\nclass langchain.retrievers.self_query.pinecone.PineconeTranslator[source]\u00b6\nTranslate Pinecone internal query language elements to valid filters.\nAttributes\nallowed_comparators\nSubset of allowed logical comparators.\nallowed_operators\nSubset of allowed logical operators.\nMethods\n__init__()\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__()\u00b6\nvisit_comparison(comparison: Comparison) \u2192 Dict[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 Dict[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, dict][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.pinecone.PineconeTranslator.html"}
{"id": "60e63b158cae-0", "text": "langchain.retrievers.you.YouRetriever\u00b6\nclass langchain.retrievers.you.YouRetriever[source]\u00b6\nBases: BaseRetriever\nYou retriever that uses You.com\u2019s search API.\nTo connect to the You.com api requires an API key which\nyou can get by emailing api@you.com.\nYou can check out our docs at https://documentation.you.com.\nYou need to set the environment variable YDC_API_KEY for retriever to operate.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam endpoint_type: str = 'web'\u00b6\nparam k: Optional[int] = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam n_hits: Optional[int] = None\u00b6\nparam n_snippets_per_hit: Optional[int] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam ydc_api_key: str [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.you.YouRetriever.html"}
{"id": "60e63b158cae-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.you.YouRetriever.html"}
{"id": "60e63b158cae-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.you.YouRetriever.html"}
{"id": "60e63b158cae-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.you.YouRetriever.html"}
{"id": "60e63b158cae-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.you.YouRetriever.html"}
{"id": "60e63b158cae-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.you.YouRetriever.html"}
{"id": "60e63b158cae-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.you.YouRetriever.html"}
{"id": "60e63b158cae-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.you.YouRetriever.html"}
{"id": "60e63b158cae-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.you.YouRetriever.html"}
{"id": "60e63b158cae-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.you.YouRetriever.html"}
{"id": "27e647846a08-0", "text": "langchain.retrievers.self_query.base.SelfQueryRetriever\u00b6\nclass langchain.retrievers.self_query.base.SelfQueryRetriever[source]\u00b6\nBases: BaseRetriever, BaseModel\nRetriever that uses a vector store and an LLM to generate\nthe vector store queries.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam query_constructor: langchain.schema.runnable.base.Runnable[dict, langchain.chains.query_constructor.ir.StructuredQuery] [Required] (alias 'llm_chain')\u00b6\nThe query constructor chain for generating the vector store queries.\nllm_chain is legacy name kept for backwards compatibility.\nparam search_kwargs: dict [Optional]\u00b6\nKeyword arguments to pass in to the vector store search.\nparam search_type: str = 'similarity'\u00b6\nThe search type to perform on the vector store.\nparam structured_query_translator: langchain.chains.query_constructor.ir.Visitor [Required]\u00b6\nTranslator for turning internal query language into vectorstore search params.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam use_original_query: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.base.SelfQueryRetriever.html"}
{"id": "27e647846a08-1", "text": "use case.\nparam use_original_query: bool = False\u00b6\nUse original query instead of the revised new query from LLM\nparam vectorstore: langchain.schema.vectorstore.VectorStore [Required]\u00b6\nThe underlying vector store from which documents will be retrieved.\nparam verbose: bool = False\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.base.SelfQueryRetriever.html"}
{"id": "27e647846a08-2", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.base.SelfQueryRetriever.html"}
{"id": "27e647846a08-3", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.base.SelfQueryRetriever.html"}
{"id": "27e647846a08-4", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_llm(llm: BaseLanguageModel, vectorstore: VectorStore, document_contents: str, metadata_field_info: Sequence[Union[AttributeInfo, dict]], structured_query_translator: Optional[Visitor] = None, chain_kwargs: Optional[Dict] = None, enable_limit: bool = False, use_original_query: bool = False, **kwargs: Any) \u2192 SelfQueryRetriever[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.base.SelfQueryRetriever.html"}
{"id": "27e647846a08-5", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.base.SelfQueryRetriever.html"}
{"id": "27e647846a08-6", "text": "and passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.base.SelfQueryRetriever.html"}
{"id": "27e647846a08-7", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.base.SelfQueryRetriever.html"}
{"id": "27e647846a08-8", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.base.SelfQueryRetriever.html"}
{"id": "27e647846a08-9", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty llm_chain: langchain.schema.runnable.base.Runnable\u00b6\nllm_chain is legacy name kept for backwards compatibility.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using SelfQueryRetriever\u00b6\nChroma\nVectara\nDocugami\nPerform context-aware text splitting", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.base.SelfQueryRetriever.html"}
{"id": "27e647846a08-10", "text": "Chroma\nVectara\nDocugami\nPerform context-aware text splitting\nMilvus\nWeaviate\nDashVector\nElasticsearch\nPinecone\nSupabase\nRedis\nMyScale\nDeep Lake\nQdrant", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.base.SelfQueryRetriever.html"}
{"id": "f7f58253807b-0", "text": "langchain.retrievers.llama_index.LlamaIndexGraphRetriever\u00b6\nclass langchain.retrievers.llama_index.LlamaIndexGraphRetriever[source]\u00b6\nBases: BaseRetriever\nLlamaIndex graph data structure retriever.\nIt is used for question-answering with sources over an LlamaIndex\ngraph data structure.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam graph: Any = None\u00b6\nLlamaIndex graph to query.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam query_configs: List[Dict] [Optional]\u00b6\nList of query configs to pass to the query method.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexGraphRetriever.html"}
{"id": "f7f58253807b-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexGraphRetriever.html"}
{"id": "f7f58253807b-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexGraphRetriever.html"}
{"id": "f7f58253807b-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexGraphRetriever.html"}
{"id": "f7f58253807b-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexGraphRetriever.html"}
{"id": "f7f58253807b-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexGraphRetriever.html"}
{"id": "f7f58253807b-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexGraphRetriever.html"}
{"id": "f7f58253807b-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexGraphRetriever.html"}
{"id": "f7f58253807b-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexGraphRetriever.html"}
{"id": "f7f58253807b-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexGraphRetriever.html"}
{"id": "fc1aa3861bc2-0", "text": "langchain.retrievers.kendra.ResultItem\u00b6\nclass langchain.retrievers.kendra.ResultItem[source]\u00b6\nBases: BaseModel, ABC\nBase class of a result item.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam DocumentAttributes: Optional[List[langchain.retrievers.kendra.DocumentAttribute]] = []\u00b6\nThe document attributes.\nparam DocumentId: Optional[str] = None\u00b6\nThe document ID.\nparam DocumentURI: Optional[str] = None\u00b6\nThe document URI.\nparam Id: Optional[str] = None\u00b6\nThe ID of the relevant result item.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.ResultItem.html"}
{"id": "fc1aa3861bc2-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_additional_metadata() \u2192 dict[source]\u00b6\nDocument additional metadata dict.\nThis returns any extra metadata except these:\nresult_id\ndocument_id\nsource\ntitle\nexcerpt\ndocument_attributes\nget_document_attributes_dict() \u2192 Dict[str, Optional[Union[str, int, List[str]]]][source]\u00b6\nDocument attributes dict.\nabstract get_excerpt() \u2192 str[source]\u00b6\nDocument excerpt or passage original content as retrieved by Kendra.\nabstract get_title() \u2192 str[source]\u00b6\nDocument title.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.ResultItem.html"}
{"id": "fc1aa3861bc2-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_doc(page_content_formatter: ~typing.Callable[[~langchain.retrievers.kendra.ResultItem], str] = <function combined_text>) \u2192 Document[source]\u00b6\nConverts this item to a Document.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.ResultItem.html"}
{"id": "6647dcc98f59-0", "text": "langchain.retrievers.svm.SVMRetriever\u00b6\nclass langchain.retrievers.svm.SVMRetriever[source]\u00b6\nBases: BaseRetriever\nSVM retriever.\nLargely based on\nhttps://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam embeddings: Embeddings [Required]\u00b6\nEmbeddings model to use.\nparam index: Any = None\u00b6\nIndex of embeddings.\nparam k: int = 4\u00b6\nNumber of results to return.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam metadatas: Optional[List[dict]] = None\u00b6\nList of metadatas corresponding with each text.\nparam relevancy_threshold: Optional[float] = None\u00b6\nThreshold for relevancy.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam texts: List[str] [Required]\u00b6\nList of texts to index.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.svm.SVMRetriever.html"}
{"id": "6647dcc98f59-1", "text": "param texts: List[str] [Required]\u00b6\nList of texts to index.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.svm.SVMRetriever.html"}
{"id": "6647dcc98f59-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.svm.SVMRetriever.html"}
{"id": "6647dcc98f59-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.svm.SVMRetriever.html"}
{"id": "6647dcc98f59-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_documents(documents: Iterable[Document], embeddings: Embeddings, **kwargs: Any) \u2192 SVMRetriever[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_texts(texts: List[str], embeddings: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 SVMRetriever[source]\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.svm.SVMRetriever.html"}
{"id": "6647dcc98f59-5", "text": "Returns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.svm.SVMRetriever.html"}
{"id": "6647dcc98f59-6", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.svm.SVMRetriever.html"}
{"id": "6647dcc98f59-7", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.svm.SVMRetriever.html"}
{"id": "6647dcc98f59-8", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.svm.SVMRetriever.html"}
{"id": "6647dcc98f59-9", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using SVMRetriever\u00b6\nSVM\nQuestion Answering", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.svm.SVMRetriever.html"}
{"id": "f52af2a41476-0", "text": "langchain.retrievers.kendra.RetrieveResult\u00b6\nclass langchain.retrievers.kendra.RetrieveResult[source]\u00b6\nBases: BaseModel\nAmazon Kendra Retrieve API search result.\nIt is composed of:\nrelevant passages or text excerpts given an input query.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam QueryId: str [Required]\u00b6\nThe ID of the query.\nparam ResultItems: List[langchain.retrievers.kendra.RetrieveResultItem] [Required]\u00b6\nThe result items.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.RetrieveResult.html"}
{"id": "f52af2a41476-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.RetrieveResult.html"}
{"id": "f52af2a41476-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.RetrieveResult.html"}
{"id": "b38e1c582ea2-0", "text": "langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever\u00b6\nclass langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever[source]\u00b6\nBases: BaseRetriever\nWeaviate hybrid search retriever.\nSee the documentation:https://weaviate.io/blog/hybrid-search-explained\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam alpha: float = 0.5\u00b6\nThe weight of the text key in the hybrid search.\nparam attributes: List[str] [Required]\u00b6\nThe attributes to return in the results.\nparam client: Any = None\u00b6\nkeyword arguments to pass to the Weaviate client.\nparam create_schema_if_missing: bool = True\u00b6\nWhether to create the schema if it doesn\u2019t exist.\nparam index_name: str [Required]\u00b6\nThe name of the index to use.\nparam k: int = 4\u00b6\nThe number of results to return.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam text_key: str [Required]\u00b6\nThe name of the text key to use.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever.html"}
{"id": "b38e1c582ea2-1", "text": "param text_key: str [Required]\u00b6\nThe name of the text key to use.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nadd_documents(docs: List[Document], **kwargs: Any) \u2192 List[str][source]\u00b6\nUpload documents to Weaviate.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever.html"}
{"id": "b38e1c582ea2-2", "text": "The default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever.html"}
{"id": "b38e1c582ea2-3", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever.html"}
{"id": "b38e1c582ea2-4", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever.html"}
{"id": "b38e1c582ea2-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever.html"}
{"id": "b38e1c582ea2-6", "text": "and passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever.html"}
{"id": "b38e1c582ea2-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever.html"}
{"id": "b38e1c582ea2-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever.html"}
{"id": "b38e1c582ea2-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using WeaviateHybridSearchRetriever\u00b6\nWeaviate Hybrid Search", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever.html"}
{"id": "8975d9de647b-0", "text": "langchain.retrievers.kendra.TextWithHighLights\u00b6\nclass langchain.retrievers.kendra.TextWithHighLights[source]\u00b6\nBases: BaseModel\nText with highlights.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam Highlights: Optional[Any] = None\u00b6\nThe highlights.\nparam Text: str [Required]\u00b6\nThe text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.TextWithHighLights.html"}
{"id": "8975d9de647b-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.TextWithHighLights.html"}
{"id": "8975d9de647b-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.TextWithHighLights.html"}
{"id": "6d58879f00f9-0", "text": "langchain.retrievers.self_query.vectara.process_value\u00b6\nlangchain.retrievers.self_query.vectara.process_value(value: Union[int, float, str]) \u2192 str[source]\u00b6\nConvert a value to a string and add single quotes if it is a string.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.vectara.process_value.html"}
{"id": "4ddf7667e5fc-0", "text": "langchain.retrievers.document_compressors.chain_extract.NoOutputParser\u00b6\nclass langchain.retrievers.document_compressors.chain_extract.NoOutputParser[source]\u00b6\nBases: BaseOutputParser[str]\nParse outputs that could return a null string of some sort.\nparam no_output_str: str = 'NO_OUTPUT'\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_extract.NoOutputParser.html"}
{"id": "4ddf7667e5fc-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_extract.NoOutputParser.html"}
{"id": "4ddf7667e5fc-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_extract.NoOutputParser.html"}
{"id": "4ddf7667e5fc-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_extract.NoOutputParser.html"}
{"id": "4ddf7667e5fc-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_extract.NoOutputParser.html"}
{"id": "4ddf7667e5fc-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 str[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_extract.NoOutputParser.html"}
{"id": "4ddf7667e5fc-6", "text": "prompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_extract.NoOutputParser.html"}
{"id": "4ddf7667e5fc-7", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_extract.NoOutputParser.html"}
{"id": "4ddf7667e5fc-8", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_extract.NoOutputParser.html"}
{"id": "e3ccc42866f0-0", "text": "langchain.retrievers.kendra.Highlight\u00b6\nclass langchain.retrievers.kendra.Highlight[source]\u00b6\nBases: BaseModel\nInformation that highlights the keywords in the excerpt.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam BeginOffset: int [Required]\u00b6\nThe zero-based location in the excerpt where the highlight starts.\nparam EndOffset: int [Required]\u00b6\nThe zero-based location in the excerpt where the highlight ends.\nparam TopAnswer: Optional[bool] = None\u00b6\nIndicates whether the result is the best one.\nparam Type: Optional[str] = None\u00b6\nThe highlight type: STANDARD or THESAURUS_SYNONYM.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.Highlight.html"}
{"id": "e3ccc42866f0-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.Highlight.html"}
{"id": "e3ccc42866f0-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.Highlight.html"}
{"id": "b1dcd60b002a-0", "text": "langchain.retrievers.document_compressors.chain_extract.default_get_input\u00b6\nlangchain.retrievers.document_compressors.chain_extract.default_get_input(query: str, doc: Document) \u2192 Dict[str, Any][source]\u00b6\nReturn the compression chain input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_extract.default_get_input.html"}
{"id": "e9d10d9d153e-0", "text": "langchain.retrievers.kendra.DocumentAttribute\u00b6\nclass langchain.retrievers.kendra.DocumentAttribute[source]\u00b6\nBases: BaseModel\nDocument attribute.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam Key: str [Required]\u00b6\nThe key of the attribute.\nparam Value: langchain.retrievers.kendra.DocumentAttributeValue [Required]\u00b6\nThe value of the attribute.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.DocumentAttribute.html"}
{"id": "e9d10d9d153e-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.DocumentAttribute.html"}
{"id": "e9d10d9d153e-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.DocumentAttribute.html"}
{"id": "928021cebd12-0", "text": "langchain.retrievers.self_query.qdrant.QdrantTranslator\u00b6\nclass langchain.retrievers.self_query.qdrant.QdrantTranslator(metadata_key: str)[source]\u00b6\nTranslate Qdrant internal query language elements to valid filters.\nAttributes\nallowed_comparators\nSubset of allowed logical comparators.\nallowed_operators\nSubset of allowed logical operators.\nMethods\n__init__(metadata_key)\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__(metadata_key: str)[source]\u00b6\nvisit_comparison(comparison: Comparison) \u2192 rest.FieldCondition[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 rest.Filter[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, dict][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.qdrant.QdrantTranslator.html"}
{"id": "8f7194cf296d-0", "text": "langchain.retrievers.arcee.ArceeRetriever\u00b6\nclass langchain.retrievers.arcee.ArceeRetriever[source]\u00b6\nBases: BaseRetriever\nDocument retriever for Arcee\u2019s Domain Adapted Language Models (DALMs).\nTo use, set the ARCEE_API_KEY environment variable with your Arcee API key,\nor pass arcee_api_key as a named parameter.\nExample\nfrom langchain.retrievers import ArceeRetriever\nretriever = ArceeRetriever(\n    model=\"DALM-PubMed\",\n    arcee_api_key=\"ARCEE-API-KEY\"\n)\ndocuments = retriever.get_relevant_documents(\"AI-driven music therapy\")\nInitializes private fields.\nparam arcee_api_key: str = ''\u00b6\nArcee API Key\nparam arcee_api_url: str = 'https://api.arcee.ai'\u00b6\nArcee API URL\nparam arcee_api_version: str = 'v2'\u00b6\nArcee API Version\nparam arcee_app_url: str = 'https://app.arcee.ai'\u00b6\nArcee App URL\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam model: str [Required]\u00b6\nArcee DALM name\nparam model_kwargs: Optional[Dict[str, Any]] = None\u00b6\nKeyword arguments to pass to the model.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arcee.ArceeRetriever.html"}
{"id": "8f7194cf296d-1", "text": "These tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arcee.ArceeRetriever.html"}
{"id": "8f7194cf296d-2", "text": "The default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arcee.ArceeRetriever.html"}
{"id": "8f7194cf296d-3", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arcee.ArceeRetriever.html"}
{"id": "8f7194cf296d-4", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arcee.ArceeRetriever.html"}
{"id": "8f7194cf296d-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arcee.ArceeRetriever.html"}
{"id": "8f7194cf296d-6", "text": "and passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arcee.ArceeRetriever.html"}
{"id": "8f7194cf296d-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arcee.ArceeRetriever.html"}
{"id": "8f7194cf296d-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arcee.ArceeRetriever.html"}
{"id": "8f7194cf296d-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arcee.ArceeRetriever.html"}
{"id": "9b28bda7d34b-0", "text": "langchain.retrievers.chaindesk.ChaindeskRetriever\u00b6\nclass langchain.retrievers.chaindesk.ChaindeskRetriever[source]\u00b6\nBases: BaseRetriever\nChaindesk API retriever.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_key: Optional[str] = None\u00b6\nparam datastore_url: str [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam top_k: Optional[int] = None\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chaindesk.ChaindeskRetriever.html"}
{"id": "9b28bda7d34b-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chaindesk.ChaindeskRetriever.html"}
{"id": "9b28bda7d34b-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chaindesk.ChaindeskRetriever.html"}
{"id": "9b28bda7d34b-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chaindesk.ChaindeskRetriever.html"}
{"id": "9b28bda7d34b-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chaindesk.ChaindeskRetriever.html"}
{"id": "9b28bda7d34b-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chaindesk.ChaindeskRetriever.html"}
{"id": "9b28bda7d34b-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chaindesk.ChaindeskRetriever.html"}
{"id": "9b28bda7d34b-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chaindesk.ChaindeskRetriever.html"}
{"id": "9b28bda7d34b-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chaindesk.ChaindeskRetriever.html"}
{"id": "9b28bda7d34b-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ChaindeskRetriever\u00b6\nChaindesk", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.chaindesk.ChaindeskRetriever.html"}
{"id": "61355ecf9f87-0", "text": "langchain.retrievers.metal.MetalRetriever\u00b6\nclass langchain.retrievers.metal.MetalRetriever[source]\u00b6\nBases: BaseRetriever\nMetal API retriever.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam client: Any = None\u00b6\nThe Metal client to use.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam params: Optional[dict] = None\u00b6\nThe parameters to pass to the Metal client.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.metal.MetalRetriever.html"}
{"id": "61355ecf9f87-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.metal.MetalRetriever.html"}
{"id": "61355ecf9f87-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.metal.MetalRetriever.html"}
{"id": "61355ecf9f87-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.metal.MetalRetriever.html"}
{"id": "61355ecf9f87-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.metal.MetalRetriever.html"}
{"id": "61355ecf9f87-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.metal.MetalRetriever.html"}
{"id": "61355ecf9f87-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.metal.MetalRetriever.html"}
{"id": "61355ecf9f87-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.metal.MetalRetriever.html"}
{"id": "61355ecf9f87-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.metal.MetalRetriever.html"}
{"id": "61355ecf9f87-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using MetalRetriever\u00b6\nMetal", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.metal.MetalRetriever.html"}
{"id": "d10794d1fecb-0", "text": "langchain.retrievers.remote_retriever.RemoteLangChainRetriever\u00b6\nclass langchain.retrievers.remote_retriever.RemoteLangChainRetriever[source]\u00b6\nBases: BaseRetriever\nLangChain API retriever.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam headers: Optional[dict] = None\u00b6\nHeaders to use for the request.\nparam input_key: str = 'message'\u00b6\nKey to use for the input in the request.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam metadata_key: str = 'metadata'\u00b6\nKey to use for the metadata in the response.\nparam page_content_key: str = 'page_content'\u00b6\nKey to use for the page content in the response.\nparam response_key: str = 'response'\u00b6\nKey to use for the response in the request.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam url: str [Required]\u00b6\nURL of the remote LangChain API.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.remote_retriever.RemoteLangChainRetriever.html"}
{"id": "d10794d1fecb-1", "text": "param url: str [Required]\u00b6\nURL of the remote LangChain API.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.remote_retriever.RemoteLangChainRetriever.html"}
{"id": "d10794d1fecb-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.remote_retriever.RemoteLangChainRetriever.html"}
{"id": "d10794d1fecb-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.remote_retriever.RemoteLangChainRetriever.html"}
{"id": "d10794d1fecb-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.remote_retriever.RemoteLangChainRetriever.html"}
{"id": "d10794d1fecb-5", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.remote_retriever.RemoteLangChainRetriever.html"}
{"id": "d10794d1fecb-6", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.remote_retriever.RemoteLangChainRetriever.html"}
{"id": "d10794d1fecb-7", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.remote_retriever.RemoteLangChainRetriever.html"}
{"id": "d10794d1fecb-8", "text": "Returns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.remote_retriever.RemoteLangChainRetriever.html"}
{"id": "d10794d1fecb-9", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.remote_retriever.RemoteLangChainRetriever.html"}
{"id": "ea550367bfb8-0", "text": "langchain.retrievers.arxiv.ArxivRetriever\u00b6\nclass langchain.retrievers.arxiv.ArxivRetriever[source]\u00b6\nBases: BaseRetriever, ArxivAPIWrapper\nArxiv retriever.\nIt wraps load() to get_relevant_documents().\nIt uses all ArxivAPIWrapper arguments without any change.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ARXIV_MAX_QUERY_LENGTH: int = 300\u00b6\nparam arxiv_exceptions: Any = None\u00b6\nparam doc_content_chars_max: Optional[int] = 4000\u00b6\nparam get_full_documents: bool = False\u00b6\nparam load_all_available_meta: bool = False\u00b6\nparam load_max_docs: int = 100\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam top_k_results: int = 3\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arxiv.ArxivRetriever.html"}
{"id": "ea550367bfb8-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arxiv.ArxivRetriever.html"}
{"id": "ea550367bfb8-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arxiv.ArxivRetriever.html"}
{"id": "ea550367bfb8-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arxiv.ArxivRetriever.html"}
{"id": "ea550367bfb8-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arxiv.ArxivRetriever.html"}
{"id": "ea550367bfb8-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nget_summaries_as_docs(query: str) \u2192 List[Document]\u00b6\nPerforms an arxiv search and returns list of\ndocuments, with summaries as the content.\nIf an error occurs or no documents found, error text\nis returned instead. Wrapper for\nhttps://lukasschwab.me/arxiv.py/index.html#Search\nParameters\nquery \u2013 a plaintext search query\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arxiv.ArxivRetriever.html"}
{"id": "ea550367bfb8-6", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nis_arxiv_identifier(query: str) \u2192 bool\u00b6\nCheck if a query is an arxiv identifier.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nload(query: str) \u2192 List[Document]\u00b6\nRun Arxiv search and get the article texts plus the article meta information.\nSee https://lukasschwab.me/arxiv.py/index.html#Search\nReturns: a list of documents with the document.page_content in text format\nPerforms an arxiv search, downloads the top k results as PDFs, loads\nthem as Documents, and returns them in a List.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arxiv.ArxivRetriever.html"}
{"id": "ea550367bfb8-7", "text": "them as Documents, and returns them in a List.\nParameters\nquery \u2013 a plaintext search query\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(query: str) \u2192 str\u00b6\nPerforms an arxiv search and A single string\nwith the publish date, title, authors, and summary\nfor each article separated by two newlines.\nIf an error occurs or no documents found, error text\nis returned instead. Wrapper for\nhttps://lukasschwab.me/arxiv.py/index.html#Search\nParameters\nquery \u2013 a plaintext search query\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arxiv.ArxivRetriever.html"}
{"id": "ea550367bfb8-8", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arxiv.ArxivRetriever.html"}
{"id": "ea550367bfb8-9", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arxiv.ArxivRetriever.html"}
{"id": "ea550367bfb8-10", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ArxivRetriever\u00b6\nArxiv", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.arxiv.ArxivRetriever.html"}
{"id": "01873390b891-0", "text": "langchain.retrievers.self_query.dashvector.DashvectorTranslator\u00b6\nclass langchain.retrievers.self_query.dashvector.DashvectorTranslator[source]\u00b6\nLogic for converting internal query language elements to valid filters.\nAttributes\nallowed_comparators\nallowed_operators\nmap_dict\nMethods\n__init__()\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__()\u00b6\nvisit_comparison(comparison: Comparison) \u2192 str[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 str[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, dict][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.dashvector.DashvectorTranslator.html"}
{"id": "504d319ea18a-0", "text": "langchain.retrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever\u00b6\nclass langchain.retrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever[source]\u00b6\nBases: BaseRetriever\nA retriever based on Document AI Warehouse.\nDocuments should be created and documents should be uploadedin a separate flow, and this retriever uses only Document AI\nschema_id provided to search for revelant documents.\nMore info: https://cloud.google.com/document-ai-warehouse.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam location: str = 'us'\u00b6\nGoogle Cloud location where Document AI Warehouse is placed.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam project_number: str [Required]\u00b6\nGoogle Cloud project number, should contain digits only.\nparam qa_size_limit: int = 5\u00b6\nThe limit on the number of documents returned.\nparam schema_id: Optional[str] = None\u00b6\nDocument AI Warehouse schema to query against.\nIf nothing is provided, all documents in the project will be searched.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever.html"}
{"id": "504d319ea18a-1", "text": "use case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever.html"}
{"id": "504d319ea18a-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever.html"}
{"id": "504d319ea18a-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever.html"}
{"id": "504d319ea18a-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever.html"}
{"id": "504d319ea18a-5", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever.html"}
{"id": "504d319ea18a-6", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever.html"}
{"id": "504d319ea18a-7", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever.html"}
{"id": "504d319ea18a-8", "text": "Returns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever.html"}
{"id": "504d319ea18a-9", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever.html"}
{"id": "898fb0ae0439-0", "text": "langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever\u00b6\nclass langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever[source]\u00b6\nBases: BaseRetriever\nElasticsearch retriever that uses BM25.\nTo connect to an Elasticsearch instance that requires login credentials,\nincluding Elastic Cloud, use the Elasticsearch URL format\nhttps://username:password@es_host:9243. For example, to connect to Elastic\nCloud, create the Elasticsearch URL with the required authentication details and\npass it to the ElasticVectorSearch constructor as the named parameter\nelasticsearch_url.\nYou can obtain your Elastic Cloud URL and login credentials by logging in to the\nElastic Cloud console at https://cloud.elastic.co, selecting your deployment, and\nnavigating to the \u201cDeployments\u201d page.\nTo obtain your Elastic Cloud password for the default \u201celastic\u201d user:\nLog in to the Elastic Cloud console at https://cloud.elastic.co\nGo to \u201cSecurity\u201d > \u201cUsers\u201d\nLocate the \u201celastic\u201d user and click \u201cEdit\u201d\nClick \u201cReset password\u201d\nFollow the prompts to reset the password\nThe format for Elastic Cloud URLs is\nhttps://username:password@cluster_id.region_id.gcp.cloud.es.io:9243.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam client: Any = None\u00b6\nElasticsearch client.\nparam index_name: str [Required]\u00b6\nName of the index to use in Elasticsearch.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever.html"}
{"id": "898fb0ae0439-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nadd_texts(texts: Iterable[str], refresh_indices: bool = True) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the retriever.\nParameters\ntexts \u2013 Iterable of strings to add to the retriever.\nrefresh_indices \u2013 bool to refresh ElasticSearch indices\nReturns\nList of ids from adding the texts into the retriever.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever.html"}
{"id": "898fb0ae0439-2", "text": ":param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever.html"}
{"id": "898fb0ae0439-3", "text": "Output is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever.html"}
{"id": "898fb0ae0439-4", "text": "configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nclassmethod create(elasticsearch_url: str, index_name: str, k1: float = 2.0, b: float = 0.75) \u2192 ElasticSearchBM25Retriever[source]\u00b6\nCreate a ElasticSearchBM25Retriever from a list of texts.\nParameters\nelasticsearch_url \u2013 URL of the Elasticsearch instance to connect to.\nindex_name \u2013 Name of the index to use in Elasticsearch.\nk1 \u2013 BM25 parameter k1.\nb \u2013 BM25 parameter b.\nReturns:", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever.html"}
{"id": "898fb0ae0439-5", "text": "b \u2013 BM25 parameter b.\nReturns:\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever.html"}
{"id": "898fb0ae0439-6", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever.html"}
{"id": "898fb0ae0439-7", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever.html"}
{"id": "898fb0ae0439-8", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever.html"}
{"id": "898fb0ae0439-9", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever.html"}
{"id": "898fb0ae0439-10", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ElasticSearchBM25Retriever\u00b6\nElasticSearch BM25", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever.html"}
{"id": "91d067cdbb48-0", "text": "langchain.retrievers.multi_query.LineList\u00b6\nclass langchain.retrievers.multi_query.LineList[source]\u00b6\nBases: BaseModel\nList of lines.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam lines: List[str] [Required]\u00b6\nList of lines.\nLines of text\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.LineList.html"}
{"id": "91d067cdbb48-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.LineList.html"}
{"id": "91d067cdbb48-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.LineList.html"}
{"id": "5e28bc533be4-0", "text": "langchain.retrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever\u00b6\nclass langchain.retrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever[source]\u00b6\nBases: BaseRetriever, _BaseGoogleVertexAISearchRetriever\nGoogle Vertex AI Search retriever for multi-turn conversations.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam conversation_id: str = '-'\u00b6\nVertex AI Search Conversation ID.\nparam credentials: Any = None\u00b6\nThe default custom credentials (google.auth.credentials.Credentials) to use\nwhen making API calls. If not provided, credentials will be ascertained from\nthe environment.\nparam data_store_id: str [Required]\u00b6\nVertex AI Search data store ID.\nparam engine_data_type: int = 0\u00b6\nDefines the Vertex AI Search data type\n0 - Unstructured data\n1 - Structured data\n2 - Website data\nConstraints\nminimum = 0\nmaximum = 2\nparam location_id: str = 'global'\u00b6\nVertex AI Search data store location.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam project_id: str [Required]\u00b6\nGoogle Cloud Project ID.\nparam serving_config_id: str = 'default_config'\u00b6\nVertex AI Search serving config ID.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever.html"}
{"id": "5e28bc533be4-1", "text": "These tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever.html"}
{"id": "5e28bc533be4-2", "text": "The default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever.html"}
{"id": "5e28bc533be4-3", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever.html"}
{"id": "5e28bc533be4-4", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever.html"}
{"id": "5e28bc533be4-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever.html"}
{"id": "5e28bc533be4-6", "text": "and passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever.html"}
{"id": "5e28bc533be4-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever.html"}
{"id": "5e28bc533be4-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever.html"}
{"id": "5e28bc533be4-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty client_options: ClientOptions\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever.html"}
{"id": "4cb31c391d18-0", "text": "langchain.retrievers.self_query.supabase.SupabaseVectorTranslator\u00b6\nclass langchain.retrievers.self_query.supabase.SupabaseVectorTranslator[source]\u00b6\nTranslate Langchain filters to Supabase PostgREST filters.\nAttributes\nallowed_comparators\nSubset of allowed logical comparators.\nallowed_operators\nSubset of allowed logical operators.\nmetadata_column\nMethods\n__init__()\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__()\u00b6\nvisit_comparison(comparison: Comparison) \u2192 str[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 str[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, Dict[str, str]][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.supabase.SupabaseVectorTranslator.html"}
{"id": "bdcc7d3e419b-0", "text": "langchain.retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever\u00b6\nclass langchain.retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever[source]\u00b6\nBases: BaseRetriever, _BaseGoogleVertexAISearchRetriever\nGoogle Vertex AI Search retriever.\nFor a detailed explanation of the Vertex AI Search concepts\nand configuration parameters, refer to the product documentation.\nhttps://cloud.google.com/generative-ai-app-builder/docs/enterprise-search-introduction\nInitializes private fields.\nparam credentials: Any = None\u00b6\nThe default custom credentials (google.auth.credentials.Credentials) to use\nwhen making API calls. If not provided, credentials will be ascertained from\nthe environment.\nparam data_store_id: str [Required]\u00b6\nVertex AI Search data store ID.\nparam engine_data_type: int = 0\u00b6\nDefines the Vertex AI Search data type\n0 - Unstructured data\n1 - Structured data\n2 - Website data\nConstraints\nminimum = 0\nmaximum = 2\nparam filter: Optional[str] = None\u00b6\nFilter expression.\nparam get_extractive_answers: bool = False\u00b6\nIf True return Extractive Answers, otherwise return Extractive Segments or Snippets.\nparam location_id: str = 'global'\u00b6\nVertex AI Search data store location.\nparam max_documents: int = 5\u00b6\nThe maximum number of documents to return.\nConstraints\nminimum = 1\nmaximum = 100\nparam max_extractive_answer_count: int = 1\u00b6\nThe maximum number of extractive answers returned in each search result.\nAt most 5 answers will be returned for each SearchResult.\nConstraints\nminimum = 1\nmaximum = 5\nparam max_extractive_segment_count: int = 1\u00b6\nThe maximum number of extractive segments returned in each search result.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever.html"}
{"id": "bdcc7d3e419b-1", "text": "The maximum number of extractive segments returned in each search result.\nCurrently one segment will be returned for each SearchResult.\nConstraints\nminimum = 1\nmaximum = 1\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam project_id: str [Required]\u00b6\nGoogle Cloud Project ID.\nparam query_expansion_condition: int = 1\u00b6\nSpecification to determine under which conditions query expansion should occur.\n0 - Unspecified query expansion condition. In this case, server behavior defaults\nto disabled\n1 - Disabled query expansion. Only the exact search query is used, even ifSearchResponse.total_size is zero.\n2 - Automatic query expansion built by the Search API.\nConstraints\nminimum = 0\nmaximum = 2\nparam serving_config_id: str = 'default_config'\u00b6\nVertex AI Search serving config ID.\nparam spell_correction_mode: int = 2\u00b6\nSpecification to determine under which conditions query expansion should occur.\n0 - Unspecified spell correction mode. In this case, server behavior defaults\nto auto.\n1 - Suggestion only. Search API will try to find a spell suggestion if there is anyand put in the SearchResponse.corrected_query.\nThe spell suggestion will not be used as the search query.\n2 - Automatic spell correction built by the Search API.Search will be based on the corrected query if found.\nConstraints\nminimum = 0\nmaximum = 2\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever.html"}
{"id": "bdcc7d3e419b-2", "text": "These tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever.html"}
{"id": "bdcc7d3e419b-3", "text": "The default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever.html"}
{"id": "bdcc7d3e419b-4", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever.html"}
{"id": "bdcc7d3e419b-5", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever.html"}
{"id": "bdcc7d3e419b-6", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever.html"}
{"id": "bdcc7d3e419b-7", "text": "and passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever.html"}
{"id": "bdcc7d3e419b-8", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever.html"}
{"id": "bdcc7d3e419b-9", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever.html"}
{"id": "bdcc7d3e419b-10", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty client_options: ClientOptions\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using GoogleVertexAISearchRetriever\u00b6\nGoogle Vertex AI Search", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever.html"}
{"id": "8a6ff1d2a193-0", "text": "langchain.retrievers.tavily_search_api.TavilySearchAPIRetriever\u00b6\nclass langchain.retrievers.tavily_search_api.TavilySearchAPIRetriever[source]\u00b6\nBases: BaseRetriever\nTavily Search API retriever.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_key: Optional[str] = None\u00b6\nparam exclude_domains: Optional[List[str]] = None\u00b6\nparam include_domains: Optional[List[str]] = None\u00b6\nparam include_generated_answer: bool = False\u00b6\nparam include_images: bool = False\u00b6\nparam include_raw_content: bool = False\u00b6\nparam k: int = 10\u00b6\nparam kwargs: Optional[Dict[str, Any]] = {}\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam search_depth: langchain.retrievers.tavily_search_api.SearchDepth = SearchDepth.BASIC\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tavily_search_api.TavilySearchAPIRetriever.html"}
{"id": "8a6ff1d2a193-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tavily_search_api.TavilySearchAPIRetriever.html"}
{"id": "8a6ff1d2a193-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tavily_search_api.TavilySearchAPIRetriever.html"}
{"id": "8a6ff1d2a193-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tavily_search_api.TavilySearchAPIRetriever.html"}
{"id": "8a6ff1d2a193-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tavily_search_api.TavilySearchAPIRetriever.html"}
{"id": "8a6ff1d2a193-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tavily_search_api.TavilySearchAPIRetriever.html"}
{"id": "8a6ff1d2a193-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tavily_search_api.TavilySearchAPIRetriever.html"}
{"id": "8a6ff1d2a193-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tavily_search_api.TavilySearchAPIRetriever.html"}
{"id": "8a6ff1d2a193-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tavily_search_api.TavilySearchAPIRetriever.html"}
{"id": "8a6ff1d2a193-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tavily_search_api.TavilySearchAPIRetriever.html"}
{"id": "ca214976538d-0", "text": "langchain.retrievers.self_query.chroma.ChromaTranslator\u00b6\nclass langchain.retrievers.self_query.chroma.ChromaTranslator[source]\u00b6\nTranslate Chroma internal query language elements to valid filters.\nAttributes\nallowed_comparators\nSubset of allowed logical comparators.\nallowed_operators\nSubset of allowed logical operators.\nMethods\n__init__()\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__()\u00b6\nvisit_comparison(comparison: Comparison) \u2192 Dict[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 Dict[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, dict][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.chroma.ChromaTranslator.html"}
{"id": "4153cdb96e36-0", "text": "langchain.retrievers.kendra.RetrieveResultItem\u00b6\nclass langchain.retrievers.kendra.RetrieveResultItem[source]\u00b6\nBases: ResultItem\nRetrieve API result item.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam Content: Optional[str] = None\u00b6\nThe content of the item.\nparam DocumentAttributes: Optional[List[langchain.retrievers.kendra.DocumentAttribute]] = []\u00b6\nThe document attributes.\nparam DocumentId: Optional[str] = None\u00b6\nThe document ID.\nparam DocumentTitle: Optional[str] = None\u00b6\nThe document title.\nparam DocumentURI: Optional[str] = None\u00b6\nThe document URI.\nparam Id: Optional[str] = None\u00b6\nThe ID of the relevant result item.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.RetrieveResultItem.html"}
{"id": "4153cdb96e36-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_additional_metadata() \u2192 dict\u00b6\nDocument additional metadata dict.\nThis returns any extra metadata except these:\nresult_id\ndocument_id\nsource\ntitle\nexcerpt\ndocument_attributes\nget_document_attributes_dict() \u2192 Dict[str, Optional[Union[str, int, List[str]]]]\u00b6\nDocument attributes dict.\nget_excerpt() \u2192 str[source]\u00b6\nDocument excerpt or passage original content as retrieved by Kendra.\nget_title() \u2192 str[source]\u00b6\nDocument title.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.RetrieveResultItem.html"}
{"id": "4153cdb96e36-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_doc(page_content_formatter: ~typing.Callable[[~langchain.retrievers.kendra.ResultItem], str] = <function combined_text>) \u2192 Document\u00b6\nConverts this item to a Document.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.RetrieveResultItem.html"}
{"id": "567a1ef34aac-0", "text": "langchain.retrievers.llama_index.LlamaIndexRetriever\u00b6\nclass langchain.retrievers.llama_index.LlamaIndexRetriever[source]\u00b6\nBases: BaseRetriever\nLlamaIndex retriever.\nIt is used for the question-answering with sources over\nan LlamaIndex data structure.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam index: Any = None\u00b6\nLlamaIndex index to query.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam query_kwargs: Dict [Optional]\u00b6\nKeyword arguments to pass to the query method.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexRetriever.html"}
{"id": "567a1ef34aac-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexRetriever.html"}
{"id": "567a1ef34aac-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexRetriever.html"}
{"id": "567a1ef34aac-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexRetriever.html"}
{"id": "567a1ef34aac-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexRetriever.html"}
{"id": "567a1ef34aac-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexRetriever.html"}
{"id": "567a1ef34aac-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexRetriever.html"}
{"id": "567a1ef34aac-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexRetriever.html"}
{"id": "567a1ef34aac-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexRetriever.html"}
{"id": "567a1ef34aac-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.llama_index.LlamaIndexRetriever.html"}
{"id": "ec2a79b777ce-0", "text": "langchain.retrievers.self_query.vectara.VectaraTranslator\u00b6\nclass langchain.retrievers.self_query.vectara.VectaraTranslator[source]\u00b6\nTranslate Vectara internal query language elements to valid filters.\nAttributes\nallowed_comparators\nSubset of allowed logical comparators.\nallowed_operators\nSubset of allowed logical operators.\nMethods\n__init__()\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__()\u00b6\nvisit_comparison(comparison: Comparison) \u2192 str[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 str[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, dict][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.vectara.VectaraTranslator.html"}
{"id": "f6b2c6014238-0", "text": "langchain.retrievers.vespa_retriever.VespaRetriever\u00b6\nclass langchain.retrievers.vespa_retriever.VespaRetriever[source]\u00b6\nBases: BaseRetriever\nVespa retriever.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam app: Any = None\u00b6\nVespa application to query.\nparam body: Dict [Required]\u00b6\nBody of the query.\nparam content_field: str [Required]\u00b6\nName of the content field.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam metadata_fields: Sequence[str] [Required]\u00b6\nNames of the metadata fields.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.vespa_retriever.VespaRetriever.html"}
{"id": "f6b2c6014238-1", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.vespa_retriever.VespaRetriever.html"}
{"id": "f6b2c6014238-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.vespa_retriever.VespaRetriever.html"}
{"id": "f6b2c6014238-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.vespa_retriever.VespaRetriever.html"}
{"id": "f6b2c6014238-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_params(url: str, content_field: str, *, k: Optional[int] = None, metadata_fields: Union[Sequence[str], Literal['*']] = (), sources: Optional[Union[Sequence[str], Literal['*']]] = None, _filter: Optional[str] = None, yql: Optional[str] = None, **kwargs: Any) \u2192 VespaRetriever[source]\u00b6\nInstantiate retriever from params.\nParameters\nurl (str) \u2013 Vespa app URL.\ncontent_field (str) \u2013 Field in results to return as Document page_content.\nk (Optional[int]) \u2013 Number of Documents to return. Defaults to None.\nmetadata_fields (Sequence[str] or \"*\") \u2013 Fields in results to include in\ndocument metadata. Defaults to empty tuple ().\nsources (Sequence[str] or \"*\" or None) \u2013 Sources to retrieve\nfrom. Defaults to None.\n_filter (Optional[str]) \u2013 Document filter condition expressed in YQL.\nDefaults to None.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.vespa_retriever.VespaRetriever.html"}
{"id": "f6b2c6014238-5", "text": "_filter (Optional[str]) \u2013 Document filter condition expressed in YQL.\nDefaults to None.\nyql (Optional[str]) \u2013 Full YQL query to be used. Should not be specified\nif _filter or sources are specified. Defaults to None.\nkwargs (Any) \u2013 Keyword arguments added to query body.\nReturns\nInstantiated VespaRetriever.\nReturn type\nVespaRetriever\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.vespa_retriever.VespaRetriever.html"}
{"id": "f6b2c6014238-6", "text": "Returns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nget_relevant_documents_with_filter(query: str, *, _filter: Optional[str] = None) \u2192 List[Document][source]\u00b6\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.vespa_retriever.VespaRetriever.html"}
{"id": "f6b2c6014238-7", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.vespa_retriever.VespaRetriever.html"}
{"id": "f6b2c6014238-8", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.vespa_retriever.VespaRetriever.html"}
{"id": "f6b2c6014238-9", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.vespa_retriever.VespaRetriever.html"}
{"id": "f6b2c6014238-10", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using VespaRetriever\u00b6\nVespa", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.vespa_retriever.VespaRetriever.html"}
{"id": "2a253278fb22-0", "text": "langchain.retrievers.multi_query.LineListOutputParser\u00b6\nclass langchain.retrievers.multi_query.LineListOutputParser[source]\u00b6\nBases: PydanticOutputParser\nOutput parser for a list of lines.\nparam pydantic_object: Type[T] [Required]\u00b6\nThe pydantic model to parse.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.LineListOutputParser.html"}
{"id": "2a253278fb22-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.LineListOutputParser.html"}
{"id": "2a253278fb22-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.LineListOutputParser.html"}
{"id": "2a253278fb22-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.LineListOutputParser.html"}
{"id": "2a253278fb22-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.LineListOutputParser.html"}
{"id": "2a253278fb22-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 LineList[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.LineListOutputParser.html"}
{"id": "2a253278fb22-6", "text": "prompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.LineListOutputParser.html"}
{"id": "2a253278fb22-7", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.LineListOutputParser.html"}
{"id": "2a253278fb22-8", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.LineListOutputParser.html"}
{"id": "037670bd4845-0", "text": "langchain.retrievers.kendra.combined_text\u00b6\nlangchain.retrievers.kendra.combined_text(item: ResultItem) \u2192 str[source]\u00b6\nCombine a ResultItem title and excerpt into a single string.\nParameters\nitem \u2013 the ResultItem of a Kendra search.\nReturns\nA combined text of the title and excerpt of the given item.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.combined_text.html"}
{"id": "88124270eb7a-0", "text": "langchain.retrievers.zilliz.ZillizRetreiver\u00b6\nlangchain.retrievers.zilliz.ZillizRetreiver(*args: Any, **kwargs: Any) \u2192 ZillizRetriever[source]\u00b6\nDeprecated ZillizRetreiver.\nPlease use ZillizRetriever (\u2018i\u2019 before \u2018e\u2019) instead.\nParameters\n*args \u2013 \n**kwargs \u2013 \nReturns\nZillizRetriever", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zilliz.ZillizRetreiver.html"}
{"id": "f87c3ac7a53e-0", "text": "langchain.retrievers.kendra.AdditionalResultAttribute\u00b6\nclass langchain.retrievers.kendra.AdditionalResultAttribute[source]\u00b6\nBases: BaseModel\nAdditional result attribute.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam Key: str [Required]\u00b6\nThe key of the attribute.\nparam Value: langchain.retrievers.kendra.AdditionalResultAttributeValue [Required]\u00b6\nThe value of the attribute.\nparam ValueType: Literal['TEXT_WITH_HIGHLIGHTS_VALUE'] [Required]\u00b6\nThe type of the value.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AdditionalResultAttribute.html"}
{"id": "f87c3ac7a53e-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_value_text() \u2192 str[source]\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AdditionalResultAttribute.html"}
{"id": "f87c3ac7a53e-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AdditionalResultAttribute.html"}
{"id": "7fde6f7c480b-0", "text": "langchain.retrievers.pinecone_hybrid_search.hash_text\u00b6\nlangchain.retrievers.pinecone_hybrid_search.hash_text(text: str) \u2192 str[source]\u00b6\nHash a text using SHA256.\nParameters\ntext \u2013 Text to hash.\nReturns\nHashed text.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pinecone_hybrid_search.hash_text.html"}
{"id": "dc18b9d6151e-0", "text": "langchain.retrievers.re_phraser.RePhraseQueryRetriever\u00b6\nclass langchain.retrievers.re_phraser.RePhraseQueryRetriever[source]\u00b6\nBases: BaseRetriever\nGiven a query, use an LLM to re-phrase it.\nThen, retrieve docs for the re-phrased query.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam retriever: langchain.schema.retriever.BaseRetriever [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.re_phraser.RePhraseQueryRetriever.html"}
{"id": "dc18b9d6151e-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.re_phraser.RePhraseQueryRetriever.html"}
{"id": "dc18b9d6151e-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.re_phraser.RePhraseQueryRetriever.html"}
{"id": "dc18b9d6151e-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.re_phraser.RePhraseQueryRetriever.html"}
{"id": "dc18b9d6151e-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_llm(retriever: BaseRetriever, llm: BaseLLM, prompt: PromptTemplate = PromptTemplate(input_variables=['question'], template='You are an assistant tasked with taking a natural language query from a user and converting it into a query for a vectorstore. In this process, you strip out information that is not relevant for the retrieval task. Here is the user query: {question}')) \u2192 RePhraseQueryRetriever[source]\u00b6\nInitialize from llm using default template.\nThe prompt used here expects a single input: question\nParameters\nretriever \u2013 retriever to query documents from\nllm \u2013 llm for query generation using DEFAULT_QUERY_PROMPT\nprompt \u2013 prompt template for query generation\nReturns\nRePhraseQueryRetriever\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.re_phraser.RePhraseQueryRetriever.html"}
{"id": "dc18b9d6151e-5", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.re_phraser.RePhraseQueryRetriever.html"}
{"id": "dc18b9d6151e-6", "text": "Parameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.re_phraser.RePhraseQueryRetriever.html"}
{"id": "dc18b9d6151e-7", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.re_phraser.RePhraseQueryRetriever.html"}
{"id": "dc18b9d6151e-8", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.re_phraser.RePhraseQueryRetriever.html"}
{"id": "dc18b9d6151e-9", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using RePhraseQueryRetriever\u00b6\nRePhraseQueryRetriever", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.re_phraser.RePhraseQueryRetriever.html"}
{"id": "4594d0e3389a-0", "text": "langchain.retrievers.self_query.timescalevector.TimescaleVectorTranslator\u00b6\nclass langchain.retrievers.self_query.timescalevector.TimescaleVectorTranslator[source]\u00b6\nTranslate the internal query language elements to valid filters.\nAttributes\nCOMPARATOR_MAP\nOPERATOR_MAP\nallowed_comparators\nallowed_operators\nSubset of allowed logical operators.\nMethods\n__init__()\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__()\u00b6\nvisit_comparison(comparison: Comparison) \u2192 client.Predicates[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 client.Predicates[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, dict][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.timescalevector.TimescaleVectorTranslator.html"}
{"id": "e2cc0f83400a-0", "text": "langchain.retrievers.self_query.myscale.MyScaleTranslator\u00b6\nclass langchain.retrievers.self_query.myscale.MyScaleTranslator(metadata_key: str = 'metadata')[source]\u00b6\nTranslate MyScale internal query language elements to valid filters.\nAttributes\nallowed_comparators\nallowed_operators\nSubset of allowed logical operators.\nmap_dict\nMethods\n__init__([metadata_key])\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__(metadata_key: str = 'metadata') \u2192 None[source]\u00b6\nvisit_comparison(comparison: Comparison) \u2192 Dict[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 Dict[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, dict][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.myscale.MyScaleTranslator.html"}
{"id": "6a55126dfc6e-0", "text": "langchain.retrievers.databerry.DataberryRetriever\u00b6\nclass langchain.retrievers.databerry.DataberryRetriever[source]\u00b6\nBases: BaseRetriever\nDataberry API retriever.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_key: Optional[str] = None\u00b6\nparam datastore_url: str [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam top_k: Optional[int] = None\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.databerry.DataberryRetriever.html"}
{"id": "6a55126dfc6e-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.databerry.DataberryRetriever.html"}
{"id": "6a55126dfc6e-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.databerry.DataberryRetriever.html"}
{"id": "6a55126dfc6e-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.databerry.DataberryRetriever.html"}
{"id": "6a55126dfc6e-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.databerry.DataberryRetriever.html"}
{"id": "6a55126dfc6e-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.databerry.DataberryRetriever.html"}
{"id": "6a55126dfc6e-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.databerry.DataberryRetriever.html"}
{"id": "6a55126dfc6e-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.databerry.DataberryRetriever.html"}
{"id": "6a55126dfc6e-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.databerry.DataberryRetriever.html"}
{"id": "6a55126dfc6e-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.databerry.DataberryRetriever.html"}
{"id": "8c0928ca14a3-0", "text": "langchain.retrievers.docarray.SearchType\u00b6\nclass langchain.retrievers.docarray.SearchType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnumerator of the types of search to perform.\nsimilarity = 'similarity'\u00b6\nmmr = 'mmr'\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.docarray.SearchType.html"}
{"id": "7c9e3e7bc736-0", "text": "langchain.retrievers.svm.create_index\u00b6\nlangchain.retrievers.svm.create_index(contexts: List[str], embeddings: Embeddings) \u2192 ndarray[source]\u00b6\nCreate an index of embeddings for a list of contexts.\nParameters\ncontexts \u2013 List of contexts to embed.\nembeddings \u2013 Embeddings model to use.\nReturns\nIndex of embeddings.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.svm.create_index.html"}
{"id": "9027fff0e8a9-0", "text": "langchain.retrievers.multi_query.MultiQueryRetriever\u00b6\nclass langchain.retrievers.multi_query.MultiQueryRetriever[source]\u00b6\nBases: BaseRetriever\nGiven a query, use an LLM to write a set of queries.\nRetrieve docs for each query. Return the unique union of all retrieved docs.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam include_original: bool = False\u00b6\nWhether to include the original query in the list of generated queries.\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam parser_key: str = 'lines'\u00b6\nparam retriever: langchain.schema.retriever.BaseRetriever [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam verbose: bool = True\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.MultiQueryRetriever.html"}
{"id": "9027fff0e8a9-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate_queries(question: str, run_manager: AsyncCallbackManagerForRetrieverRun) \u2192 List[str][source]\u00b6\nGenerate queries based upon user input.\nParameters\nquestion \u2013 user query\nReturns\nList of LLM generated queries that are similar to the user input\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.MultiQueryRetriever.html"}
{"id": "9027fff0e8a9-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync aretrieve_documents(queries: List[str], run_manager: AsyncCallbackManagerForRetrieverRun) \u2192 List[Document][source]\u00b6\nRun all LLM generated queries.\nParameters\nqueries \u2013 query list\nReturns\nList of retrieved Documents\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.MultiQueryRetriever.html"}
{"id": "9027fff0e8a9-3", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.MultiQueryRetriever.html"}
{"id": "9027fff0e8a9-4", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.MultiQueryRetriever.html"}
{"id": "9027fff0e8a9-5", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_llm(retriever: BaseRetriever, llm: BaseLLM, prompt: PromptTemplate = PromptTemplate(input_variables=['question'], template='You are an AI language model assistant. Your task is \\n\u00a0\u00a0\u00a0 to generate 3 different versions of the given user \\n\u00a0\u00a0\u00a0 question to retrieve relevant documents from a vector\u00a0 database. \\n\u00a0\u00a0\u00a0 By generating multiple perspectives on the user question, \\n\u00a0\u00a0\u00a0 your goal is to help the user overcome some of the limitations \\n\u00a0\u00a0\u00a0 of distance-based similarity search. Provide these alternative \\n\u00a0\u00a0\u00a0 questions separated by newlines. Original question: {question}'), parser_key: str = 'lines', include_original: bool = False) \u2192 MultiQueryRetriever[source]\u00b6\nInitialize from llm using default template.\nParameters\nretriever \u2013 retriever to query documents from\nllm \u2013 llm for query generation using DEFAULT_QUERY_PROMPT\ninclude_original \u2013 Whether to include the original query in the list of\ngenerated queries.\nReturns\nMultiQueryRetriever\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate_queries(question: str, run_manager: CallbackManagerForRetrieverRun) \u2192 List[str][source]\u00b6\nGenerate queries based upon user input.\nParameters\nquestion \u2013 user query\nReturns\nList of LLM generated queries that are similar to the user input\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.MultiQueryRetriever.html"}
{"id": "9027fff0e8a9-6", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.MultiQueryRetriever.html"}
{"id": "9027fff0e8a9-7", "text": "and passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.MultiQueryRetriever.html"}
{"id": "9027fff0e8a9-8", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nretrieve_documents(queries: List[str], run_manager: CallbackManagerForRetrieverRun) \u2192 List[Document][source]\u00b6\nRun all LLM generated queries.\nParameters\nqueries \u2013 query list\nReturns\nList of retrieved Documents\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nunique_union(documents: List[Document]) \u2192 List[Document][source]\u00b6\nGet unique Documents.\nParameters\ndocuments \u2013 List of retrieved Documents\nReturns\nList of unique retrieved Documents", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.MultiQueryRetriever.html"}
{"id": "9027fff0e8a9-9", "text": "Parameters\ndocuments \u2013 List of retrieved Documents\nReturns\nList of unique retrieved Documents\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.MultiQueryRetriever.html"}
{"id": "9027fff0e8a9-10", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.MultiQueryRetriever.html"}
{"id": "9027fff0e8a9-11", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using MultiQueryRetriever\u00b6\nQuestion Answering\nMultiQueryRetriever", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_query.MultiQueryRetriever.html"}
{"id": "5b6b36a8b1bd-0", "text": "langchain.retrievers.kay.KayAiRetriever\u00b6\nclass langchain.retrievers.kay.KayAiRetriever[source]\u00b6\nBases: BaseRetriever\nRetriever for Kay.ai datasets.\nTo work properly, expects you to have KAY_API_KEY env variable set.\nYou can get one for free at https://kay.ai/.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam client: Any = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam num_contexts: int [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kay.KayAiRetriever.html"}
{"id": "5b6b36a8b1bd-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kay.KayAiRetriever.html"}
{"id": "5b6b36a8b1bd-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kay.KayAiRetriever.html"}
{"id": "5b6b36a8b1bd-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kay.KayAiRetriever.html"}
{"id": "5b6b36a8b1bd-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nclassmethod create(dataset_id: str, data_types: List[str], num_contexts: int = 6) \u2192 KayAiRetriever[source]\u00b6\nCreate a KayRetriever given a Kay dataset id and a list of datasources.\nParameters\ndataset_id \u2013 A dataset id category in Kay, like \u201ccompany\u201d\ndata_types \u2013 A list of datasources present within a dataset. For\n\u201ccompany\u201d the corresponding datasources could be\n[\u201c10-K\u201d, \u201c10-Q\u201d, \u201c8-K\u201d, \u201cPressRelease\u201d].\nnum_contexts \u2013 The number of documents to retrieve on each query.\nDefaults to 6.\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kay.KayAiRetriever.html"}
{"id": "5b6b36a8b1bd-5", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kay.KayAiRetriever.html"}
{"id": "5b6b36a8b1bd-6", "text": "This metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kay.KayAiRetriever.html"}
{"id": "5b6b36a8b1bd-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kay.KayAiRetriever.html"}
{"id": "5b6b36a8b1bd-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kay.KayAiRetriever.html"}
{"id": "5b6b36a8b1bd-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kay.KayAiRetriever.html"}
{"id": "24d339a7146e-0", "text": "langchain.retrievers.parent_document_retriever.ParentDocumentRetriever\u00b6\nclass langchain.retrievers.parent_document_retriever.ParentDocumentRetriever[source]\u00b6\nBases: MultiVectorRetriever\nRetrieve small chunks then retrieve their parent documents.\nWhen splitting documents for retrieval, there are often conflicting desires:\nYou may want to have small documents, so that their embeddings can mostaccurately reflect their meaning. If too long, then the embeddings can\nlose meaning.\nYou want to have long enough documents that the context of each chunk isretained.\nThe ParentDocumentRetriever strikes that balance by splitting and storing\nsmall chunks of data. During retrieval, it first fetches the small chunks\nbut then looks up the parent ids for those chunks and returns those larger\ndocuments.\nNote that \u201cparent document\u201d refers to the document that a small chunk\noriginated from. This can either be the whole raw document OR a larger\nchunk.\nExamples\n# Imports\nfrom langchain.vectorstores import Chroma\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter\nfrom langchain.storage import InMemoryStore\n# This text splitter is used to create the parent documents\nparent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000)\n# This text splitter is used to create the child documents\n# It should create documents smaller than the parent\nchild_splitter = RecursiveCharacterTextSplitter(chunk_size=400)\n# The vectorstore to use to index the child chunks\nvectorstore = Chroma(embedding_function=OpenAIEmbeddings())\n# The storage layer for the parent documents\nstore = InMemoryStore()\n# Initialize the retriever\nretriever = ParentDocumentRetriever(\n    vectorstore=vectorstore,\n    docstore=store,\n    child_splitter=child_splitter,", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.parent_document_retriever.ParentDocumentRetriever.html"}
{"id": "24d339a7146e-1", "text": "docstore=store,\n    child_splitter=child_splitter,\n    parent_splitter=parent_splitter,\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam child_splitter: langchain.text_splitter.TextSplitter [Required]\u00b6\nThe text splitter to use to create child documents.\nparam docstore: BaseStore[str, Document] [Required]\u00b6\nThe storage layer for the parent documents\nparam id_key: str = 'doc_id'\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam parent_splitter: Optional[langchain.text_splitter.TextSplitter] = None\u00b6\nThe text splitter to use to create parent documents.\nIf none, then the parent documents will be the raw documents passed in.\nparam search_kwargs: dict [Optional]\u00b6\nKeyword arguments to pass to the search function.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam vectorstore: VectorStore [Required]\u00b6\nThe underlying vectorstore to use to store small chunks\nand their embedding vectors", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.parent_document_retriever.ParentDocumentRetriever.html"}
{"id": "24d339a7146e-2", "text": "The underlying vectorstore to use to store small chunks\nand their embedding vectors\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nadd_documents(documents: List[Document], ids: Optional[List[str]] = None, add_to_docstore: bool = True) \u2192 None[source]\u00b6\nAdds documents to the docstore and vectorstores.\nParameters\ndocuments \u2013 List of documents to add\nids \u2013 Optional list of ids for documents. If provided should be the same\nlength as the list of documents. Can provided if parent documents\nare already in the document store and you don\u2019t want to re-add\nto the docstore. If not provided, random UUIDs will be used as\nids.\nadd_to_docstore \u2013 Boolean of whether to add documents to docstore.\nThis can be false if and only if ids are provided. You may want\nto set this to False if the documents are already in the docstore\nand you don\u2019t want to re-add them.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.parent_document_retriever.ParentDocumentRetriever.html"}
{"id": "24d339a7146e-3", "text": ":param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.parent_document_retriever.ParentDocumentRetriever.html"}
{"id": "24d339a7146e-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.parent_document_retriever.ParentDocumentRetriever.html"}
{"id": "24d339a7146e-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.parent_document_retriever.ParentDocumentRetriever.html"}
{"id": "24d339a7146e-6", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.parent_document_retriever.ParentDocumentRetriever.html"}
{"id": "24d339a7146e-7", "text": "This method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.parent_document_retriever.ParentDocumentRetriever.html"}
{"id": "24d339a7146e-8", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.parent_document_retriever.ParentDocumentRetriever.html"}
{"id": "24d339a7146e-9", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.parent_document_retriever.ParentDocumentRetriever.html"}
{"id": "24d339a7146e-10", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.parent_document_retriever.ParentDocumentRetriever.html"}
{"id": "24d339a7146e-11", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ParentDocumentRetriever\u00b6\nParent Document Retriever", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.parent_document_retriever.ParentDocumentRetriever.html"}
{"id": "72e1872c3278-0", "text": "langchain.retrievers.document_compressors.chain_filter.LLMChainFilter\u00b6\nclass langchain.retrievers.document_compressors.chain_filter.LLMChainFilter[source]\u00b6\nBases: BaseDocumentCompressor\nFilter that drops documents that aren\u2019t relevant to the query.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam get_input: Callable[[str, langchain.schema.document.Document], dict] = <function default_get_input>\u00b6\nCallable for constructing the chain input from the query and a Document.\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nLLM wrapper to use for filtering documents.\nThe chain prompt is expected to have a BooleanOutputParser.\nasync acompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Document]\u00b6\nCompress retrieved documents given the query context.\ncompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Document][source]\u00b6\nFilter down documents based on their relevance to the query.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_filter.LLMChainFilter.html"}
{"id": "72e1872c3278-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_llm(llm: BaseLanguageModel, prompt: Optional[BasePromptTemplate] = None, **kwargs: Any) \u2192 LLMChainFilter[source]\u00b6\nCreate a LLMChainFilter from a language model.\nParameters\nllm \u2013 The language model to use for filtering.\nprompt \u2013 The prompt to use for the filter.\n**kwargs \u2013 Additional arguments to pass to the constructor.\nReturns\nA LLMChainFilter that uses the given language model.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_filter.LLMChainFilter.html"}
{"id": "72e1872c3278-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_filter.LLMChainFilter.html"}
{"id": "4280b6c05b30-0", "text": "langchain.retrievers.kendra.AdditionalResultAttributeValue\u00b6\nclass langchain.retrievers.kendra.AdditionalResultAttributeValue[source]\u00b6\nBases: BaseModel\nValue of an additional result attribute.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam TextWithHighlightsValue: langchain.retrievers.kendra.TextWithHighLights [Required]\u00b6\nThe text with highlights value.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AdditionalResultAttributeValue.html"}
{"id": "4280b6c05b30-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AdditionalResultAttributeValue.html"}
{"id": "4280b6c05b30-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AdditionalResultAttributeValue.html"}
{"id": "6a85d7763413-0", "text": "langchain.retrievers.wikipedia.WikipediaRetriever\u00b6\nclass langchain.retrievers.wikipedia.WikipediaRetriever[source]\u00b6\nBases: BaseRetriever, WikipediaAPIWrapper\nWikipedia API retriever.\nIt wraps load() to get_relevant_documents().\nIt uses all WikipediaAPIWrapper arguments without any change.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam doc_content_chars_max: int = 4000\u00b6\nparam lang: str = 'en'\u00b6\nparam load_all_available_meta: bool = False\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam top_k_results: int = 3\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.wikipedia.WikipediaRetriever.html"}
{"id": "6a85d7763413-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.wikipedia.WikipediaRetriever.html"}
{"id": "6a85d7763413-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.wikipedia.WikipediaRetriever.html"}
{"id": "6a85d7763413-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.wikipedia.WikipediaRetriever.html"}
{"id": "6a85d7763413-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.wikipedia.WikipediaRetriever.html"}
{"id": "6a85d7763413-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.wikipedia.WikipediaRetriever.html"}
{"id": "6a85d7763413-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nload(query: str) \u2192 List[Document]\u00b6\nRun Wikipedia search and get the article text plus the meta information.\nSee\nReturns: a list of documents.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(query: str) \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.wikipedia.WikipediaRetriever.html"}
{"id": "6a85d7763413-7", "text": "run(query: str) \u2192 str\u00b6\nRun Wikipedia search and get page summaries.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.wikipedia.WikipediaRetriever.html"}
{"id": "6a85d7763413-8", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.wikipedia.WikipediaRetriever.html"}
{"id": "6a85d7763413-9", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using WikipediaRetriever\u00b6\nWikipedia", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.wikipedia.WikipediaRetriever.html"}
{"id": "b89b854c172e-0", "text": "langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever\u00b6\nclass langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever[source]\u00b6\nBases: BaseRetriever\nRetriever that combines embedding similarity with\nrecency in retrieving values.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam decay_rate: float = 0.01\u00b6\nThe exponential decay factor used as (1.0-decay_rate)**(hrs_passed).\nparam default_salience: Optional[float] = None\u00b6\nThe salience to assign memories not retrieved from the vector store.\nNone assigns no salience to documents not fetched from the vector store.\nparam k: int = 4\u00b6\nThe maximum number of documents to retrieve in a given call.\nparam memory_stream: List[langchain.schema.document.Document] [Optional]\u00b6\nThe memory_stream of documents to search through.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam other_score_keys: List[str] = []\u00b6\nOther keys in the metadata to factor into the score, e.g. \u2018importance\u2019.\nparam search_kwargs: dict [Optional]\u00b6\nKeyword arguments to pass to the vectorstore similarity search.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever.html"}
{"id": "b89b854c172e-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam vectorstore: langchain.schema.vectorstore.VectorStore [Required]\u00b6\nThe vectorstore to store documents and determine salience.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd documents to vectorstore.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd documents to vectorstore.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever.html"}
{"id": "b89b854c172e-2", "text": "This metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever.html"}
{"id": "b89b854c172e-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever.html"}
{"id": "b89b854c172e-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever.html"}
{"id": "b89b854c172e-5", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever.html"}
{"id": "b89b854c172e-6", "text": "and passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nget_salient_docs(query: str) \u2192 Dict[int, Tuple[Document, float]][source]\u00b6\nReturn documents that are salient to the query.\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever.html"}
{"id": "b89b854c172e-7", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever.html"}
{"id": "b89b854c172e-8", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever.html"}
{"id": "b89b854c172e-9", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever.html"}
{"id": "b89b854c172e-10", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using TimeWeightedVectorStoreRetriever\u00b6\nGenerative Agents in LangChain", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever.html"}
{"id": "3ee23b6ac95e-0", "text": "langchain.retrievers.zep.SearchType\u00b6\nclass langchain.retrievers.zep.SearchType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnumerator of the types of search to perform.\nsimilarity = 'similarity'\u00b6\nSimilarity search.\nmmr = 'mmr'\u00b6\nMaximal Marginal Relevance reranking of similarity search.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zep.SearchType.html"}
{"id": "f2f9be4a0de2-0", "text": "langchain.retrievers.document_compressors.chain_extract.LLMChainExtractor\u00b6\nclass langchain.retrievers.document_compressors.chain_extract.LLMChainExtractor[source]\u00b6\nBases: BaseDocumentCompressor\nDocument compressor that uses an LLM chain to extract\nthe relevant parts of documents.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam get_input: Callable[[str, langchain.schema.document.Document], dict] = <function default_get_input>\u00b6\nCallable for constructing the chain input from the query and a Document.\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nLLM wrapper to use for compressing documents.\nasync acompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Document][source]\u00b6\nCompress page content of raw documents asynchronously.\ncompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Document][source]\u00b6\nCompress page content of raw documents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_extract.LLMChainExtractor.html"}
{"id": "f2f9be4a0de2-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_llm(llm: BaseLanguageModel, prompt: Optional[PromptTemplate] = None, get_input: Optional[Callable[[str, Document], str]] = None, llm_chain_kwargs: Optional[dict] = None) \u2192 LLMChainExtractor[source]\u00b6\nInitialize from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_extract.LLMChainExtractor.html"}
{"id": "f2f9be4a0de2-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_extract.LLMChainExtractor.html"}
{"id": "2c45ea1ac427-0", "text": "langchain.retrievers.zilliz.ZillizRetriever\u00b6\nclass langchain.retrievers.zilliz.ZillizRetriever[source]\u00b6\nBases: BaseRetriever\nZilliz API retriever.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam collection_name: str = 'LangChainCollection'\u00b6\nThe name of the collection in Zilliz.\nparam connection_args: Optional[Dict[str, Any]] = None\u00b6\nThe connection arguments for the Zilliz client.\nparam consistency_level: str = 'Session'\u00b6\nThe consistency level for the Zilliz client.\nparam embedding_function: langchain.schema.embeddings.Embeddings [Required]\u00b6\nThe underlying embedding function from which documents will be retrieved.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam retriever: langchain.schema.retriever.BaseRetriever [Required]\u00b6\nThe underlying retriever.\nparam search_params: Optional[dict] = None\u00b6\nThe search parameters for the Zilliz client.\nparam store: langchain.vectorstores.zilliz.Zilliz [Required]\u00b6\nThe underlying Zilliz store.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zilliz.ZillizRetriever.html"}
{"id": "2c45ea1ac427-1", "text": "use case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nadd_texts(texts: List[str], metadatas: Optional[List[dict]] = None) \u2192 None[source]\u00b6\nAdd text to the Zilliz store\nParameters\ntexts (List[str]) \u2013 The text\nmetadatas (List[dict]) \u2013 Metadata dicts, must line up with existing store\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zilliz.ZillizRetriever.html"}
{"id": "2c45ea1ac427-2", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zilliz.ZillizRetriever.html"}
{"id": "2c45ea1ac427-3", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zilliz.ZillizRetriever.html"}
{"id": "2c45ea1ac427-4", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zilliz.ZillizRetriever.html"}
{"id": "2c45ea1ac427-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zilliz.ZillizRetriever.html"}
{"id": "2c45ea1ac427-6", "text": "and passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zilliz.ZillizRetriever.html"}
{"id": "2c45ea1ac427-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zilliz.ZillizRetriever.html"}
{"id": "2c45ea1ac427-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zilliz.ZillizRetriever.html"}
{"id": "2c45ea1ac427-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.zilliz.ZillizRetriever.html"}
{"id": "3133ddf507d0-0", "text": "langchain.retrievers.document_compressors.base.DocumentCompressorPipeline\u00b6\nclass langchain.retrievers.document_compressors.base.DocumentCompressorPipeline[source]\u00b6\nBases: BaseDocumentCompressor\nDocument compressor that uses a pipeline of Transformers.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam transformers: List[Union[langchain.schema.document.BaseDocumentTransformer, langchain.retrievers.document_compressors.base.BaseDocumentCompressor]] [Required]\u00b6\nList of document filters that are chained together and run in sequence.\nasync acompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Document][source]\u00b6\nCompress retrieved documents given the query context.\ncompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Document][source]\u00b6\nTransform a list of documents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.base.DocumentCompressorPipeline.html"}
{"id": "3133ddf507d0-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.base.DocumentCompressorPipeline.html"}
{"id": "3133ddf507d0-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using DocumentCompressorPipeline\u00b6\nLOTR (Merger Retriever)", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.base.DocumentCompressorPipeline.html"}
{"id": "e68764b96e12-0", "text": "langchain.retrievers.tfidf.TFIDFRetriever\u00b6\nclass langchain.retrievers.tfidf.TFIDFRetriever[source]\u00b6\nBases: BaseRetriever\nTF-IDF retriever.\nLargely based on\nhttps://github.com/asvskartheek/Text-Retrieval/blob/master/TF-IDF%20Search%20Engine%20(SKLEARN).ipynb\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam docs: List[langchain.schema.document.Document] [Required]\u00b6\nDocuments.\nparam k: int = 4\u00b6\nNumber of documents to return.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam tfidf_array: Any = None\u00b6\nTF-IDF array.\nparam vectorizer: Any = None\u00b6\nTF-IDF vectorizer.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tfidf.TFIDFRetriever.html"}
{"id": "e68764b96e12-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tfidf.TFIDFRetriever.html"}
{"id": "e68764b96e12-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tfidf.TFIDFRetriever.html"}
{"id": "e68764b96e12-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tfidf.TFIDFRetriever.html"}
{"id": "e68764b96e12-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_documents(documents: Iterable[Document], *, tfidf_params: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 TFIDFRetriever[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_texts(texts: Iterable[str], metadatas: Optional[Iterable[dict]] = None, tfidf_params: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 TFIDFRetriever[source]\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tfidf.TFIDFRetriever.html"}
{"id": "e68764b96e12-5", "text": "Returns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tfidf.TFIDFRetriever.html"}
{"id": "e68764b96e12-6", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod load_local(folder_path: str, file_name: str = 'tfidf_vectorizer') \u2192 TFIDFRetriever[source]\u00b6\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tfidf.TFIDFRetriever.html"}
{"id": "e68764b96e12-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_local(folder_path: str, file_name: str = 'tfidf_vectorizer') \u2192 None[source]\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tfidf.TFIDFRetriever.html"}
{"id": "e68764b96e12-8", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tfidf.TFIDFRetriever.html"}
{"id": "e68764b96e12-9", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using TFIDFRetriever\u00b6\nTF-IDF", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.tfidf.TFIDFRetriever.html"}
{"id": "d83dced3f450-0", "text": "langchain.retrievers.self_query.elasticsearch.ElasticsearchTranslator\u00b6\nclass langchain.retrievers.self_query.elasticsearch.ElasticsearchTranslator[source]\u00b6\nTranslate Elasticsearch internal query language elements to valid filters.\nAttributes\nallowed_comparators\nSubset of allowed logical comparators.\nallowed_operators\nSubset of allowed logical operators.\nMethods\n__init__()\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__()\u00b6\nvisit_comparison(comparison: Comparison) \u2192 Dict[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 Dict[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, dict][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.elasticsearch.ElasticsearchTranslator.html"}
{"id": "a57bd2643950-0", "text": "langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever\u00b6\nclass langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever[source]\u00b6\nBases: BaseRetriever\nAzure Cognitive Search service retriever.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aiosession: Optional[aiohttp.ClientSession] = None\u00b6\nClientSession, in case we want to reuse connection for better performance.\nparam api_key: str = ''\u00b6\nAPI Key. Both Admin and Query keys work, but for reading data it\u2019s\nrecommended to use a Query key.\nparam api_version: str = '2020-06-30'\u00b6\nAPI version\nparam content_key: str = 'content'\u00b6\nKey in a retrieved result to set as the Document page_content.\nparam index_name: str = ''\u00b6\nName of Index inside Azure Cognitive Search service\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam service_name: str = ''\u00b6\nName of Azure Cognitive Search service\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam top_k: Optional[int] = None\u00b6\nNumber of results to retrieve. Set to None to retrieve all results.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever.html"}
{"id": "a57bd2643950-1", "text": "Number of results to retrieve. Set to None to retrieve all results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever.html"}
{"id": "a57bd2643950-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever.html"}
{"id": "a57bd2643950-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever.html"}
{"id": "a57bd2643950-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever.html"}
{"id": "a57bd2643950-5", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever.html"}
{"id": "a57bd2643950-6", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever.html"}
{"id": "a57bd2643950-7", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever.html"}
{"id": "a57bd2643950-8", "text": "Returns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever.html"}
{"id": "a57bd2643950-9", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using AzureCognitiveSearchRetriever\u00b6\nAzure Cognitive Search", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever.html"}
{"id": "c01961fc35fc-0", "text": "langchain.retrievers.self_query.deeplake.DeepLakeTranslator\u00b6\nclass langchain.retrievers.self_query.deeplake.DeepLakeTranslator[source]\u00b6\nTranslate DeepLake internal query language elements to valid filters.\nAttributes\nallowed_comparators\nSubset of allowed logical comparators.\nallowed_operators\nSubset of allowed logical operators.\nMethods\n__init__()\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__()\u00b6\nvisit_comparison(comparison: Comparison) \u2192 str[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 str[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, dict][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.deeplake.DeepLakeTranslator.html"}
{"id": "b3d248459c80-0", "text": "langchain.retrievers.merger_retriever.MergerRetriever\u00b6\nclass langchain.retrievers.merger_retriever.MergerRetriever[source]\u00b6\nBases: BaseRetriever\nRetriever that merges the results of multiple retrievers.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam retrievers: List[langchain.schema.retriever.BaseRetriever] [Required]\u00b6\nA list of retrievers to merge.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.merger_retriever.MergerRetriever.html"}
{"id": "b3d248459c80-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync amerge_documents(query: str, run_manager: AsyncCallbackManagerForRetrieverRun) \u2192 List[Document][source]\u00b6\nAsynchronously merge the results of the retrievers.\nParameters\nquery \u2013 The query to search for.\nReturns\nA list of merged documents.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.merger_retriever.MergerRetriever.html"}
{"id": "b3d248459c80-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.merger_retriever.MergerRetriever.html"}
{"id": "b3d248459c80-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.merger_retriever.MergerRetriever.html"}
{"id": "b3d248459c80-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.merger_retriever.MergerRetriever.html"}
{"id": "b3d248459c80-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.merger_retriever.MergerRetriever.html"}
{"id": "b3d248459c80-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nmerge_documents(query: str, run_manager: CallbackManagerForRetrieverRun) \u2192 List[Document][source]\u00b6\nMerge the results of the retrievers.\nParameters\nquery \u2013 The query to search for.\nReturns\nA list of merged documents.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.merger_retriever.MergerRetriever.html"}
{"id": "b3d248459c80-7", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.merger_retriever.MergerRetriever.html"}
{"id": "b3d248459c80-8", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.merger_retriever.MergerRetriever.html"}
{"id": "b3d248459c80-9", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using MergerRetriever\u00b6\nLOTR (Merger Retriever)", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.merger_retriever.MergerRetriever.html"}
{"id": "36611150c0d6-0", "text": "langchain.retrievers.web_research.WebResearchRetriever\u00b6\nclass langchain.retrievers.web_research.WebResearchRetriever[source]\u00b6\nBases: BaseRetriever\nGoogle Search API retriever.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam num_search_results: int = 1\u00b6\nNumber of pages per Google search\nparam search: langchain.utilities.google_search.GoogleSearchAPIWrapper [Required]\u00b6\nGoogle Search API Wrapper\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam text_splitter: langchain.text_splitter.TextSplitter = <langchain.text_splitter.RecursiveCharacterTextSplitter object>\u00b6\nText splitter for splitting web pages into chunks\nparam url_database: List[str] [Optional]\u00b6\nList of processed URLs\nparam vectorstore: langchain.schema.vectorstore.VectorStore [Required]\u00b6\nVector store for storing web pages", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.WebResearchRetriever.html"}
{"id": "36611150c0d6-1", "text": "Vector store for storing web pages\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.WebResearchRetriever.html"}
{"id": "36611150c0d6-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.WebResearchRetriever.html"}
{"id": "36611150c0d6-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nclean_search_query(query: str) \u2192 str[source]\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.WebResearchRetriever.html"}
{"id": "36611150c0d6-4", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_llm(vectorstore: ~langchain.schema.vectorstore.VectorStore, llm: ~langchain.llms.base.BaseLLM, search: ~langchain.utilities.google_search.GoogleSearchAPIWrapper, prompt: ~typing.Optional[~langchain.schema.prompt_template.BasePromptTemplate] = None, num_search_results: int = 1, text_splitter: ~langchain.text_splitter.RecursiveCharacterTextSplitter = <langchain.text_splitter.RecursiveCharacterTextSplitter object>) \u2192 WebResearchRetriever[source]\u00b6\nInitialize from llm using default template.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.WebResearchRetriever.html"}
{"id": "36611150c0d6-5", "text": "Initialize from llm using default template.\nParameters\nvectorstore \u2013 Vector store for storing web pages\nllm \u2013 llm for search question generation\nsearch \u2013 GoogleSearchAPIWrapper\nprompt \u2013 prompt to generating search questions\nnum_search_results \u2013 Number of pages per Google search\ntext_splitter \u2013 Text splitter for splitting web pages into chunks\nReturns\nWebResearchRetriever\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.WebResearchRetriever.html"}
{"id": "36611150c0d6-6", "text": "Returns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.WebResearchRetriever.html"}
{"id": "36611150c0d6-7", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.WebResearchRetriever.html"}
{"id": "36611150c0d6-8", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nsearch_tool(query: str, num_search_results: int = 1) \u2192 List[dict][source]\u00b6\nReturns num_search_results pages per Google search.\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.WebResearchRetriever.html"}
{"id": "36611150c0d6-9", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.WebResearchRetriever.html"}
{"id": "36611150c0d6-10", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using WebResearchRetriever\u00b6\nSet env var OPENAI_API_KEY or load from a .env file:\nWebResearchRetriever", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.web_research.WebResearchRetriever.html"}
{"id": "0d5b99a9f7d6-0", "text": "langchain.retrievers.pinecone_hybrid_search.create_index\u00b6\nlangchain.retrievers.pinecone_hybrid_search.create_index(contexts: List[str], index: Any, embeddings: Embeddings, sparse_encoder: Any, ids: Optional[List[str]] = None, metadatas: Optional[List[dict]] = None, namespace: Optional[str] = None) \u2192 None[source]\u00b6\nCreate an index from a list of contexts.\nIt modifies the index argument in-place!\nParameters\ncontexts \u2013 List of contexts to embed.\nindex \u2013 Index to use.\nembeddings \u2013 Embeddings model to use.\nsparse_encoder \u2013 Sparse encoder to use.\nids \u2013 List of ids to use for the documents.\nmetadatas \u2013 List of metadata to use for the documents.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.pinecone_hybrid_search.create_index.html"}
{"id": "9532d0f2149b-0", "text": "langchain.retrievers.kendra.QueryResultItem\u00b6\nclass langchain.retrievers.kendra.QueryResultItem[source]\u00b6\nBases: ResultItem\nQuery API result item.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam AdditionalAttributes: Optional[List[langchain.retrievers.kendra.AdditionalResultAttribute]] = []\u00b6\nOne or more additional attributes associated with the result.\nparam DocumentAttributes: Optional[List[langchain.retrievers.kendra.DocumentAttribute]] = []\u00b6\nThe document attributes.\nparam DocumentExcerpt: Optional[langchain.retrievers.kendra.TextWithHighLights] = None\u00b6\nExcerpt of the document text.\nparam DocumentId: Optional[str] = None\u00b6\nThe document ID.\nparam DocumentTitle: langchain.retrievers.kendra.TextWithHighLights [Required]\u00b6\nThe document title.\nparam DocumentURI: Optional[str] = None\u00b6\nThe document URI.\nparam FeedbackToken: Optional[str] = None\u00b6\nIdentifies a particular result from a particular query.\nparam Format: Optional[str] = None\u00b6\nIf the Type is ANSWER, then format is either:\nTABLE: a table excerpt is returned in TableExcerpt;\nTEXT: a text excerpt is returned in DocumentExcerpt.\nparam Id: Optional[str] = None\u00b6\nThe ID of the relevant result item.\nparam Type: Optional[str] = None\u00b6\nType of result: DOCUMENT or QUESTION_ANSWER or ANSWER\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.QueryResultItem.html"}
{"id": "9532d0f2149b-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_additional_metadata() \u2192 dict[source]\u00b6\nDocument additional metadata dict.\nThis returns any extra metadata except these:\nresult_id\ndocument_id\nsource\ntitle\nexcerpt\ndocument_attributes\nget_attribute_value() \u2192 str[source]\u00b6\nget_document_attributes_dict() \u2192 Dict[str, Optional[Union[str, int, List[str]]]]\u00b6\nDocument attributes dict.\nget_excerpt() \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.QueryResultItem.html"}
{"id": "9532d0f2149b-2", "text": "Document attributes dict.\nget_excerpt() \u2192 str[source]\u00b6\nDocument excerpt or passage original content as retrieved by Kendra.\nget_title() \u2192 str[source]\u00b6\nDocument title.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_doc(page_content_formatter: ~typing.Callable[[~langchain.retrievers.kendra.ResultItem], str] = <function combined_text>) \u2192 Document\u00b6\nConverts this item to a Document.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.QueryResultItem.html"}
{"id": "9532d0f2149b-3", "text": "Converts this item to a Document.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.QueryResultItem.html"}
{"id": "b156ec512879-0", "text": "langchain.retrievers.multi_vector.MultiVectorRetriever\u00b6\nclass langchain.retrievers.multi_vector.MultiVectorRetriever[source]\u00b6\nBases: BaseRetriever\nRetrieve from a set of multiple embeddings for the same document.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam docstore: langchain.schema.storage.BaseStore[str, langchain.schema.document.Document] [Required]\u00b6\nThe storage layer for the parent documents\nparam id_key: str = 'doc_id'\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam search_kwargs: dict [Optional]\u00b6\nKeyword arguments to pass to the search function.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam vectorstore: langchain.schema.vectorstore.VectorStore [Required]\u00b6\nThe underlying vectorstore to use to store small chunks\nand their embedding vectors\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_vector.MultiVectorRetriever.html"}
{"id": "b156ec512879-1", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_vector.MultiVectorRetriever.html"}
{"id": "b156ec512879-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_vector.MultiVectorRetriever.html"}
{"id": "b156ec512879-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_vector.MultiVectorRetriever.html"}
{"id": "b156ec512879-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_vector.MultiVectorRetriever.html"}
{"id": "b156ec512879-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_vector.MultiVectorRetriever.html"}
{"id": "b156ec512879-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_vector.MultiVectorRetriever.html"}
{"id": "b156ec512879-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_vector.MultiVectorRetriever.html"}
{"id": "b156ec512879-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_vector.MultiVectorRetriever.html"}
{"id": "b156ec512879-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using MultiVectorRetriever\u00b6\nMultiVector Retriever", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.multi_vector.MultiVectorRetriever.html"}
{"id": "5872106cd19c-0", "text": "langchain.retrievers.ensemble.EnsembleRetriever\u00b6\nclass langchain.retrievers.ensemble.EnsembleRetriever[source]\u00b6\nBases: BaseRetriever\nRetriever that ensembles the multiple retrievers.\nIt uses a rank fusion.\nParameters\nretrievers \u2013 A list of retrievers to ensemble.\nweights \u2013 A list of weights corresponding to the retrievers. Defaults to equal\nweighting for all retrievers.\nc \u2013 A constant added to the rank, controlling the balance between the importance\nof high-ranked items and the consideration given to lower-ranked items.\nDefault is 60.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam c: int = 60\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam retrievers: List[langchain.schema.retriever.BaseRetriever] [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam weights: List[float] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.ensemble.EnsembleRetriever.html"}
{"id": "5872106cd19c-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arank_fusion(query: str, run_manager: AsyncCallbackManagerForRetrieverRun) \u2192 List[Document][source]\u00b6\nAsynchronously retrieve the results of the retrievers\nand use rank_fusion_func to get the final result.\nParameters\nquery \u2013 The query to search for.\nReturns\nA list of reranked documents.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.ensemble.EnsembleRetriever.html"}
{"id": "5872106cd19c-2", "text": "query \u2013 The query to search for.\nReturns\nA list of reranked documents.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.ensemble.EnsembleRetriever.html"}
{"id": "5872106cd19c-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.ensemble.EnsembleRetriever.html"}
{"id": "5872106cd19c-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.ensemble.EnsembleRetriever.html"}
{"id": "5872106cd19c-5", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.ensemble.EnsembleRetriever.html"}
{"id": "5872106cd19c-6", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.ensemble.EnsembleRetriever.html"}
{"id": "5872106cd19c-7", "text": "rank_fusion(query: str, run_manager: CallbackManagerForRetrieverRun) \u2192 List[Document][source]\u00b6\nRetrieve the results of the retrievers and use rank_fusion_func to get\nthe final result.\nParameters\nquery \u2013 The query to search for.\nReturns\nA list of reranked documents.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nweighted_reciprocal_rank(doc_lists: List[List[Document]]) \u2192 List[Document][source]\u00b6\nPerform weighted Reciprocal Rank Fusion on multiple rank lists.\nYou can find more details about RRF here:\nhttps://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf\nParameters", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.ensemble.EnsembleRetriever.html"}
{"id": "5872106cd19c-8", "text": "Parameters\ndoc_lists \u2013 A list of rank lists, where each rank list contains unique items.\nReturns\nThe final aggregated list of items sorted by their weighted RRFscores in descending order.\nReturn type\nlist\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.ensemble.EnsembleRetriever.html"}
{"id": "5872106cd19c-9", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.ensemble.EnsembleRetriever.html"}
{"id": "5872106cd19c-10", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using EnsembleRetriever\u00b6\nEnsemble Retriever", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.ensemble.EnsembleRetriever.html"}
{"id": "342c695b6e24-0", "text": "langchain.retrievers.self_query.milvus.process_value\u00b6\nlangchain.retrievers.self_query.milvus.process_value(value: Union[int, float, str]) \u2192 str[source]\u00b6\nConvert a value to a string and add double quotes if it is a string.\nIt required for comparators involving strings.\nParameters\nvalue \u2013 The value to convert.\nReturns\nThe converted value as a string.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.milvus.process_value.html"}
{"id": "155ca0790b05-0", "text": "langchain.retrievers.milvus.MilvusRetreiver\u00b6\nlangchain.retrievers.milvus.MilvusRetreiver(*args: Any, **kwargs: Any) \u2192 MilvusRetriever[source]\u00b6\nDeprecated MilvusRetreiver. Please use MilvusRetriever (\u2018i\u2019 before \u2018e\u2019) instead.\nParameters\n*args \u2013 \n**kwargs \u2013 \nReturns\nMilvusRetriever", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.milvus.MilvusRetreiver.html"}
{"id": "cc3c96e4d43d-0", "text": "langchain.retrievers.self_query.redis.RedisTranslator\u00b6\nclass langchain.retrievers.self_query.redis.RedisTranslator(schema: RedisModel)[source]\u00b6\nTranslate\nAttributes\nallowed_comparators\nSubset of allowed logical comparators.\nallowed_operators\nSubset of allowed logical operators.\nMethods\n__init__(schema)\nfrom_vectorstore(vectorstore)\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__(schema: RedisModel) \u2192 None[source]\u00b6\nclassmethod from_vectorstore(vectorstore: Redis) \u2192 RedisTranslator[source]\u00b6\nvisit_comparison(comparison: Comparison) \u2192 RedisFilterExpression[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 Any[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, dict][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.redis.RedisTranslator.html"}
{"id": "3829d6ae1c94-0", "text": "langchain.retrievers.self_query.milvus.MilvusTranslator\u00b6\nclass langchain.retrievers.self_query.milvus.MilvusTranslator[source]\u00b6\nTranslate Milvus internal query language elements to valid filters.\nAttributes\nallowed_comparators\nallowed_operators\nSubset of allowed logical comparators.\nMethods\n__init__()\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__()\u00b6\nvisit_comparison(comparison: Comparison) \u2192 str[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 str[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, dict][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.milvus.MilvusTranslator.html"}
{"id": "b3d97f5fb7d0-0", "text": "langchain.retrievers.kendra.AmazonKendraRetriever\u00b6\nclass langchain.retrievers.kendra.AmazonKendraRetriever[source]\u00b6\nBases: BaseRetriever\nAmazon Kendra Index retriever.\nParameters\nindex_id \u2013 Kendra index id\nregion_name \u2013 The aws region e.g., us-west-2.\nFallsback to AWS_DEFAULT_REGION env variable\nor region specified in ~/.aws/config.\ncredentials_profile_name \u2013 The name of the profile in the ~/.aws/credentials\nor ~/.aws/config files, which has either access keys or role information\nspecified. If not specified, the default credential profile or, if on an\nEC2 instance, credentials from IMDS will be used.\ntop_k \u2013 No of results to return\nattribute_filter \u2013 Additional filtering of results based on metadata\nSee: https://docs.aws.amazon.com/kendra/latest/APIReference\npage_content_formatter \u2013 generates the Document page_content\nallowing access to all result item attributes. By default, it uses\nthe item\u2019s title and excerpt.\nclient \u2013 boto3 client for Kendra\nuser_context \u2013 Provides information about the user context\nSee: https://docs.aws.amazon.com/kendra/latest/APIReference\nExample\nretriever = AmazonKendraRetriever(\n    index_id=\"c0806df7-e76b-4bce-9b5c-d5582f6b1a03\"\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam attribute_filter: Optional[Dict] = None\u00b6\nparam client: Any = None\u00b6\nparam credentials_profile_name: Optional[str] = None\u00b6\nparam index_id: str [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AmazonKendraRetriever.html"}
{"id": "b3d97f5fb7d0-1", "text": "param metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam page_content_formatter: Callable[[langchain.retrievers.kendra.ResultItem], str] = <function combined_text>\u00b6\nparam region_name: Optional[str] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam top_k: int = 3\u00b6\nparam user_context: Optional[Dict] = None\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AmazonKendraRetriever.html"}
{"id": "b3d97f5fb7d0-2", "text": "Asynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AmazonKendraRetriever.html"}
{"id": "b3d97f5fb7d0-3", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AmazonKendraRetriever.html"}
{"id": "b3d97f5fb7d0-4", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AmazonKendraRetriever.html"}
{"id": "b3d97f5fb7d0-5", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AmazonKendraRetriever.html"}
{"id": "b3d97f5fb7d0-6", "text": "This method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AmazonKendraRetriever.html"}
{"id": "b3d97f5fb7d0-7", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AmazonKendraRetriever.html"}
{"id": "b3d97f5fb7d0-8", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AmazonKendraRetriever.html"}
{"id": "b3d97f5fb7d0-9", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AmazonKendraRetriever.html"}
{"id": "b3d97f5fb7d0-10", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using AmazonKendraRetriever\u00b6\nAmazon Kendra", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.AmazonKendraRetriever.html"}
{"id": "02ca97cafc8e-0", "text": "langchain.retrievers.self_query.weaviate.WeaviateTranslator\u00b6\nclass langchain.retrievers.self_query.weaviate.WeaviateTranslator[source]\u00b6\nTranslate Weaviate internal query language elements to valid filters.\nAttributes\nallowed_comparators\nallowed_operators\nSubset of allowed logical operators.\nMethods\n__init__()\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__()\u00b6\nvisit_comparison(comparison: Comparison) \u2192 Dict[source]\u00b6\nTranslate a Comparison.\nvisit_operation(operation: Operation) \u2192 Dict[source]\u00b6\nTranslate an Operation.\nvisit_structured_query(structured_query: StructuredQuery) \u2192 Tuple[str, dict][source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.weaviate.WeaviateTranslator.html"}
{"id": "f3ace8d76703-0", "text": "langchain.retrievers.document_compressors.embeddings_filter.EmbeddingsFilter\u00b6\nclass langchain.retrievers.document_compressors.embeddings_filter.EmbeddingsFilter[source]\u00b6\nBases: BaseDocumentCompressor\nDocument compressor that uses embeddings to drop documents\nunrelated to the query.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam embeddings: langchain.schema.embeddings.Embeddings [Required]\u00b6\nEmbeddings to use for embedding document contents and queries.\nparam k: Optional[int] = 20\u00b6\nThe number of relevant documents to return. Can be set to None, in which case\nsimilarity_threshold must be specified. Defaults to 20.\nparam similarity_fn: Callable = <function cosine_similarity>\u00b6\nSimilarity function for comparing documents. Function expected to take as input\ntwo matrices (List[List[float]]) and return a matrix of scores where higher values\nindicate greater similarity.\nparam similarity_threshold: Optional[float] = None\u00b6\nThreshold for determining when two documents are similar enough\nto be considered redundant. Defaults to None, must be specified if k is set\nto None.\nasync acompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Document]\u00b6\nCompress retrieved documents given the query context.\ncompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Document][source]\u00b6\nFilter documents based on similarity of their embeddings to the query.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.embeddings_filter.EmbeddingsFilter.html"}
{"id": "f3ace8d76703-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.embeddings_filter.EmbeddingsFilter.html"}
{"id": "f3ace8d76703-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.embeddings_filter.EmbeddingsFilter.html"}
{"id": "a9578de201c2-0", "text": "langchain.retrievers.document_compressors.chain_filter.default_get_input\u00b6\nlangchain.retrievers.document_compressors.chain_filter.default_get_input(query: str, doc: Document) \u2192 Dict[str, Any][source]\u00b6\nReturn the compression chain input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.chain_filter.default_get_input.html"}
{"id": "97773668c9ce-0", "text": "langchain.retrievers.document_compressors.cohere_rerank.CohereRerank\u00b6\nclass langchain.retrievers.document_compressors.cohere_rerank.CohereRerank[source]\u00b6\nBases: BaseDocumentCompressor\nDocument compressor that uses Cohere Rerank API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam client: Client [Required]\u00b6\nCohere client to use for compressing documents.\nparam cohere_api_key: Optional[str] = None\u00b6\nparam model: str = 'rerank-english-v2.0'\u00b6\nModel to use for reranking.\nparam top_n: int = 3\u00b6\nNumber of documents to return.\nparam user_agent: str = 'langchain'\u00b6\nIdentifier for the application making the request.\nasync acompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Document]\u00b6\nCompress retrieved documents given the query context.\ncompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Document][source]\u00b6\nCompress documents using Cohere\u2019s rerank API.\nParameters\ndocuments \u2013 A sequence of documents to compress.\nquery \u2013 The query to use for compressing the documents.\ncallbacks \u2013 Callbacks to run during the compression process.\nReturns\nA sequence of compressed documents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.cohere_rerank.CohereRerank.html"}
{"id": "97773668c9ce-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.cohere_rerank.CohereRerank.html"}
{"id": "97773668c9ce-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using CohereRerank\u00b6\nCohere Reranker\nCohere", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.document_compressors.cohere_rerank.CohereRerank.html"}
{"id": "78ed37203d8b-0", "text": "langchain.retrievers.contextual_compression.ContextualCompressionRetriever\u00b6\nclass langchain.retrievers.contextual_compression.ContextualCompressionRetriever[source]\u00b6\nBases: BaseRetriever\nRetriever that wraps a base retriever and compresses the results.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam base_compressor: langchain.retrievers.document_compressors.base.BaseDocumentCompressor [Required]\u00b6\nCompressor for compressing retrieved documents.\nparam base_retriever: langchain.schema.retriever.BaseRetriever [Required]\u00b6\nBase Retriever to use for getting relevant documents.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.contextual_compression.ContextualCompressionRetriever.html"}
{"id": "78ed37203d8b-1", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.contextual_compression.ContextualCompressionRetriever.html"}
{"id": "78ed37203d8b-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.contextual_compression.ContextualCompressionRetriever.html"}
{"id": "78ed37203d8b-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.contextual_compression.ContextualCompressionRetriever.html"}
{"id": "78ed37203d8b-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.contextual_compression.ContextualCompressionRetriever.html"}
{"id": "78ed37203d8b-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.contextual_compression.ContextualCompressionRetriever.html"}
{"id": "78ed37203d8b-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.contextual_compression.ContextualCompressionRetriever.html"}
{"id": "78ed37203d8b-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.contextual_compression.ContextualCompressionRetriever.html"}
{"id": "78ed37203d8b-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.contextual_compression.ContextualCompressionRetriever.html"}
{"id": "78ed37203d8b-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ContextualCompressionRetriever\u00b6\nCohere Reranker\nLOTR (Merger Retriever)", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.contextual_compression.ContextualCompressionRetriever.html"}
{"id": "e7e48bd36f52-0", "text": "langchain.retrievers.milvus.MilvusRetriever\u00b6\nclass langchain.retrievers.milvus.MilvusRetriever[source]\u00b6\nBases: BaseRetriever\nMilvus API retriever.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam collection_name: str = 'LangChainCollection'\u00b6\nparam connection_args: Optional[Dict[str, Any]] = None\u00b6\nparam consistency_level: str = 'Session'\u00b6\nparam embedding_function: langchain.schema.embeddings.Embeddings [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam retriever: langchain.schema.retriever.BaseRetriever [Required]\u00b6\nparam search_params: Optional[dict] = None\u00b6\nparam store: langchain.vectorstores.milvus.Milvus [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.milvus.MilvusRetriever.html"}
{"id": "e7e48bd36f52-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nadd_texts(texts: List[str], metadatas: Optional[List[dict]] = None) \u2192 None[source]\u00b6\nAdd text to the Milvus store\nParameters\ntexts (List[str]) \u2013 The text\nmetadatas (List[dict]) \u2013 Metadata dicts, must line up with existing store\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.milvus.MilvusRetriever.html"}
{"id": "e7e48bd36f52-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.milvus.MilvusRetriever.html"}
{"id": "e7e48bd36f52-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.milvus.MilvusRetriever.html"}
{"id": "e7e48bd36f52-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.milvus.MilvusRetriever.html"}
{"id": "e7e48bd36f52-5", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.milvus.MilvusRetriever.html"}
{"id": "e7e48bd36f52-6", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.milvus.MilvusRetriever.html"}
{"id": "e7e48bd36f52-7", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.milvus.MilvusRetriever.html"}
{"id": "e7e48bd36f52-8", "text": "Returns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.milvus.MilvusRetriever.html"}
{"id": "e7e48bd36f52-9", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.milvus.MilvusRetriever.html"}
{"id": "b2f6d14e5694-0", "text": "langchain.retrievers.kendra.clean_excerpt\u00b6\nlangchain.retrievers.kendra.clean_excerpt(excerpt: str) \u2192 str[source]\u00b6\nClean an excerpt from Kendra.\nParameters\nexcerpt \u2013 The excerpt to clean.\nReturns\nThe cleaned excerpt.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.kendra.clean_excerpt.html"}
{"id": "ea5814b4744b-0", "text": "langchain.retrievers.knn.create_index\u00b6\nlangchain.retrievers.knn.create_index(contexts: List[str], embeddings: Embeddings) \u2192 ndarray[source]\u00b6\nCreate an index of embeddings for a list of contexts.\nParameters\ncontexts \u2013 List of contexts to embed.\nembeddings \u2013 Embeddings model to use.\nReturns\nIndex of embeddings.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.knn.create_index.html"}
{"id": "7b4760dea1f4-0", "text": "langchain.retrievers.docarray.DocArrayRetriever\u00b6\nclass langchain.retrievers.docarray.DocArrayRetriever[source]\u00b6\nBases: BaseRetriever\nDocArray Document Indices retriever.\nCurrently, it supports 5 backends:\nInMemoryExactNNIndex, HnswDocumentIndex, QdrantDocumentIndex,\nElasticDocIndex, and WeaviateDocumentIndex.\nParameters\nindex \u2013 One of the above-mentioned index instances\nembeddings \u2013 Embedding model to represent text as vectors\nsearch_field \u2013 Field to consider for searching in the documents.\nShould be an embedding/vector/tensor.\ncontent_field \u2013 Field that represents the main content in your document schema.\nWill be used as a page_content. Everything else will go into metadata.\nsearch_type \u2013 Type of search to perform (similarity / mmr)\nfilters \u2013 Filters applied for document retrieval.\ntop_k \u2013 Number of documents to return\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam content_field: str [Required]\u00b6\nparam embeddings: langchain.schema.embeddings.Embeddings [Required]\u00b6\nparam filters: Optional[Any] = None\u00b6\nparam index: Any = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam search_field: str [Required]\u00b6\nparam search_type: langchain.retrievers.docarray.SearchType = SearchType.similarity\u00b6\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.docarray.DocArrayRetriever.html"}
{"id": "7b4760dea1f4-1", "text": "param tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam top_k: int = 1\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.docarray.DocArrayRetriever.html"}
{"id": "7b4760dea1f4-2", "text": "and passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.docarray.DocArrayRetriever.html"}
{"id": "7b4760dea1f4-3", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.docarray.DocArrayRetriever.html"}
{"id": "7b4760dea1f4-4", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.docarray.DocArrayRetriever.html"}
{"id": "7b4760dea1f4-5", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.docarray.DocArrayRetriever.html"}
{"id": "7b4760dea1f4-6", "text": "and passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.docarray.DocArrayRetriever.html"}
{"id": "7b4760dea1f4-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.docarray.DocArrayRetriever.html"}
{"id": "7b4760dea1f4-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.docarray.DocArrayRetriever.html"}
{"id": "7b4760dea1f4-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using DocArrayRetriever\u00b6\nDocArray Retriever", "source": "lang/api.python.langchain.com/en/latest/retrievers/langchain.retrievers.docarray.DocArrayRetriever.html"}
{"id": "55946c3e34ab-0", "text": "langchain.runnables.openai_functions.OpenAIFunctionsRouter\u00b6\nclass langchain.runnables.openai_functions.OpenAIFunctionsRouter[source]\u00b6\nBases: RunnableBindingBase[BaseMessage, Any]\nA runnable that routes to the selected function.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bound: Runnable[Input, Output] [Required]\u00b6\nparam config: RunnableConfig [Optional]\u00b6\nparam config_factories: List[Callable[[RunnableConfig], RunnableConfig]] [Optional]\u00b6\nparam custom_input_type: Optional[Any] = None\u00b6\nparam custom_output_type: Optional[Any] = None\u00b6\nparam functions: Optional[List[langchain.runnables.openai_functions.OpenAIFunction]] = None\u00b6\nparam kwargs: Mapping[str, Any] [Optional]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.openai_functions.OpenAIFunctionsRouter.html"}
{"id": "55946c3e34ab-1", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.openai_functions.OpenAIFunctionsRouter.html"}
{"id": "55946c3e34ab-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.openai_functions.OpenAIFunctionsRouter.html"}
{"id": "55946c3e34ab-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.openai_functions.OpenAIFunctionsRouter.html"}
{"id": "55946c3e34ab-4", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.openai_functions.OpenAIFunctionsRouter.html"}
{"id": "55946c3e34ab-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.openai_functions.OpenAIFunctionsRouter.html"}
{"id": "55946c3e34ab-6", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.openai_functions.OpenAIFunctionsRouter.html"}
{"id": "55946c3e34ab-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.openai_functions.OpenAIFunctionsRouter.html"}
{"id": "55946c3e34ab-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.openai_functions.OpenAIFunctionsRouter.html"}
{"id": "582d935dd7d0-0", "text": "langchain.runnables.hub.HubRunnable\u00b6\nclass langchain.runnables.hub.HubRunnable[source]\u00b6\nBases: RunnableBindingBase[Input, Output]\nAn instance of a runnable stored in the LangChain Hub.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bound: Runnable[Input, Output] [Required]\u00b6\nparam config: RunnableConfig [Optional]\u00b6\nparam config_factories: List[Callable[[RunnableConfig], RunnableConfig]] [Optional]\u00b6\nparam custom_input_type: Optional[Any] = None\u00b6\nparam custom_output_type: Optional[Any] = None\u00b6\nparam kwargs: Mapping[str, Any] [Optional]\u00b6\nparam owner_repo_commit: str [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.hub.HubRunnable.html"}
{"id": "582d935dd7d0-1", "text": "Default implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.hub.HubRunnable.html"}
{"id": "582d935dd7d0-2", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.hub.HubRunnable.html"}
{"id": "582d935dd7d0-3", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.hub.HubRunnable.html"}
{"id": "582d935dd7d0-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.hub.HubRunnable.html"}
{"id": "582d935dd7d0-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.hub.HubRunnable.html"}
{"id": "582d935dd7d0-6", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.hub.HubRunnable.html"}
{"id": "582d935dd7d0-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.hub.HubRunnable.html"}
{"id": "582d935dd7d0-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.hub.HubRunnable.html"}
{"id": "d956eac837d9-0", "text": "langchain.runnables.openai_functions.OpenAIFunction\u00b6\nclass langchain.runnables.openai_functions.OpenAIFunction[source]\u00b6\nA function description for ChatOpenAI\nAttributes\nname\nThe name of the function.\ndescription\nThe description of the function.\nparameters\nThe parameters to the function.\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.openai_functions.OpenAIFunction.html"}
{"id": "d956eac837d9-1", "text": "items() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6", "source": "lang/api.python.langchain.com/en/latest/runnables/langchain.runnables.openai_functions.OpenAIFunction.html"}
{"id": "15519789276e-0", "text": "langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain\u00b6\nclass langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain[source]\u00b6\nBases: BaseQAWithSourcesChain\nQuestion-answering with sources over a vector database.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam combine_documents_chain: BaseCombineDocumentsChain [Required]\u00b6\nChain to use to combine documents.\nparam k: int = 4\u00b6\nNumber of results to return from store\nparam max_tokens_limit: int = 3375\u00b6\nRestrict the docs to return from store based on tokens,\nenforced only for StuffDocumentChain and if reduce_k_below_max_tokens is to true\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-1", "text": "This metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam reduce_k_below_max_tokens: bool = False\u00b6\nReduce the number of results to return from store based on tokens limit\nparam return_source_documents: bool = False\u00b6\nReturn the source documents.\nparam search_kwargs: Dict[str, Any] [Optional]\u00b6\nExtra search args.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam vectorstore: langchain.schema.vectorstore.VectorStore [Required]\u00b6\nVector Database to connect to.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-2", "text": "memory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-3", "text": "Asynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-4", "text": "Call the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-5", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-6", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-7", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_chain_type(llm: BaseLanguageModel, chain_type: str = 'stuff', chain_type_kwargs: Optional[dict] = None, **kwargs: Any) \u2192 BaseQAWithSourcesChain\u00b6\nLoad chain from chain type.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-8", "text": "classmethod from_llm(llm: BaseLanguageModel, document_prompt: BasePromptTemplate = PromptTemplate(input_variables=['page_content', 'source'], template='Content: {page_content}\\nSource: {source}'), question_prompt: BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], template='Use the following portion of a long document to see if any of the text is relevant to answer the question. \\nReturn any relevant text verbatim.\\n{context}\\nQuestion: {question}\\nRelevant text, if any:'), combine_prompt: BasePromptTemplate = PromptTemplate(input_variables=['question', 'summaries'], template='Given the following extracted parts of a long document and a question, create a final answer with references (\"SOURCES\"). \\nIf you don\\'t know the answer, just say that you don\\'t know. Don\\'t try to make up an answer.\\nALWAYS return a \"SOURCES\" part in your answer.\\n\\nQUESTION: Which state/country\\'s law governs the interpretation of the contract?\\n=========\\nContent: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in\u00a0 relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an\u00a0 injunction or other relief to protect its Intellectual Property Rights.\\nSource: 28-pl\\nContent: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other)\u00a0 right or remedy.\\n\\n11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation\u00a0 in force of the remainder of the term (if any) and this Agreement.\\n\\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-9", "text": "Agreement.\\n\\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any\u00a0 kind between the parties.\\n\\n11.9 No Third-Party Beneficiaries.\\nSource: 30-pl\\nContent: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as\u00a0 defined in Clause 8.5) or that such a violation is reasonably likely to occur,\\nSource: 4-pl\\n=========\\nFINAL ANSWER: This Agreement is governed by English law.\\nSOURCES: 28-pl\\n\\nQUESTION: What did the president say about Michael Jackson?\\n=========\\nContent: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.\u00a0 \\n\\nLast year COVID-19 kept us apart. This year we are finally together again. \\n\\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \\n\\nWith a duty to one another to the American people to the Constitution. \\n\\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \\n\\nSix days ago, Russia\u2019s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \\n\\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \\n\\nHe met the Ukrainian people. \\n\\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \\n\\nGroups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland.\\nSource:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-10", "text": "tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland.\\nSource: 0-pl\\nContent: And we won\u2019t stop. \\n\\nWe have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. \\n\\nLet\u2019s use this moment to reset. Let\u2019s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease.\u00a0 \\n\\nLet\u2019s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans.\u00a0 \\n\\nWe can\u2019t change how divided we\u2019ve been. But we can change how we move forward\u2014on COVID-19 and other issues we must face together. \\n\\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \\n\\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \\n\\nOfficer Mora was 27 years old. \\n\\nOfficer Rivera was 22. \\n\\nBoth Dominican Americans who\u2019d grown up on the same streets they later chose to patrol as police officers. \\n\\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves.\\nSource: 24-pl\\nContent: And a proud Ukrainian people, who have known 30 years\u00a0 of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards.\u00a0 \\n\\nTo all Americans, I will be honest with you, as I\u2019ve always promised. A Russian dictator, invading a foreign country, has costs around the world. \\n\\nAnd I\u2019m taking robust action to make sure the pain of our sanctions", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-11", "text": "world. \\n\\nAnd I\u2019m taking robust action to make sure the pain of our sanctions\u00a0 is targeted at Russia\u2019s economy. And I will use every tool at our disposal to protect American businesses and consumers. \\n\\nTonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world.\u00a0 \\n\\nAmerica will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies.\u00a0 \\n\\nThese steps will help blunt gas prices here at home. And I know the news about what\u2019s happening can seem alarming. \\n\\nBut I want you to know that we are going to be okay.\\nSource: 5-pl\\nContent: More support for patients and families. \\n\\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \\n\\nIt\u2019s based on DARPA\u2014the Defense Department project that led to the Internet, GPS, and so much more.\u00a0 \\n\\nARPA-H will have a singular purpose\u2014to drive breakthroughs in cancer, Alzheimer\u2019s, diabetes, and more. \\n\\nA unity agenda for the nation. \\n\\nWe can do this. \\n\\nMy fellow Americans\u2014tonight , we have gathered in a sacred space\u2014the citadel of our democracy. \\n\\nIn this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. \\n\\nWe have fought for freedom, expanded liberty, defeated totalitarianism and terror. \\n\\nAnd built the strongest, freest, and most prosperous nation the world has ever known. \\n\\nNow is the hour. \\n\\nOur moment of responsibility. \\n\\nOur test of resolve and conscience, of history itself. \\n\\nIt is in this moment that our character", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-12", "text": "of resolve and conscience, of history itself. \\n\\nIt is in this moment that our character is formed. Our purpose is found. Our future is forged. \\n\\nWell I know this nation.\\nSource: 34-pl\\n=========\\nFINAL ANSWER: The president did not mention Michael Jackson.\\nSOURCES:\\n\\nQUESTION: {question}\\n=========\\n{summaries}\\n=========\\nFINAL ANSWER:'), **kwargs: Any) \u2192 BaseQAWithSourcesChain\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-13", "text": "Construct the chain from an LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-14", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-15", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-16", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-17", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-18", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "15519789276e-19", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.vector_db.VectorDBQAWithSourcesChain.html"}
{"id": "ffebf182fbea-0", "text": "langchain.chains.router.multi_prompt.MultiPromptChain\u00b6\nclass langchain.chains.router.multi_prompt.MultiPromptChain[source]\u00b6\nBases: MultiRouteChain\nA multi-route chain that uses an LLM router chain to choose amongst prompts.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam default_chain: Chain [Required]\u00b6\nDefault chain to use when none of the destination chains are suitable.\nparam destination_chains: Mapping[str, Chain] [Required]\u00b6\nChains that return final answer to inputs.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam router_chain: RouterChain [Required]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "ffebf182fbea-1", "text": "param router_chain: RouterChain [Required]\u00b6\nChain that routes inputs to destination chains.\nparam silent_errors: bool = False\u00b6\nIf True, use default_chain when an invalid destination name is provided.\nDefaults to False.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "ffebf182fbea-2", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "ffebf182fbea-3", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "ffebf182fbea-4", "text": "method expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "ffebf182fbea-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "ffebf182fbea-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "ffebf182fbea-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_prompts(llm: BaseLanguageModel, prompt_infos: List[Dict[str, str]], default_chain: Optional[Chain] = None, **kwargs: Any) \u2192 MultiPromptChain[source]\u00b6\nConvenience constructor for instantiating from destination prompts.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "ffebf182fbea-8", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "ffebf182fbea-9", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "ffebf182fbea-10", "text": "memory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "ffebf182fbea-11", "text": "context = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "ffebf182fbea-12", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "ffebf182fbea-13", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using MultiPromptChain\u00b6\nRouter", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html"}
{"id": "0b5e079331ec-0", "text": "langchain.chains.conversational_retrieval.base.ChatVectorDBChain\u00b6\nclass langchain.chains.conversational_retrieval.base.ChatVectorDBChain[source]\u00b6\nBases: BaseConversationalRetrievalChain\nChain for chatting with a vector database.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam combine_docs_chain: BaseCombineDocumentsChain [Required]\u00b6\nThe chain used to combine any retrieved documents.\nparam get_chat_history: Optional[Callable[[List[CHAT_TURN_TYPE]], str]] = None\u00b6\nAn optional function to get a string of the chat history.\nIf None is provided, will use a default.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_key: str = 'answer'\u00b6\nThe output key to return the final answer of this chain in.\nparam question_generator: LLMChain [Required]\u00b6\nThe chain used to generate a new question for the sake of retrieval.\nThis chain will take in the current question (with variable question)\nand any chat history (with variable chat_history) and will produce\na new standalone question to be used later on.\nparam rephrase_question: bool = True\u00b6\nWhether or not to pass the new generated question to the combine_docs_chain.\nIf True, will pass the new generated question along.\nIf False, will only use the new generated question for retrieval and pass the\noriginal question along to the combine_docs_chain.\nparam response_if_no_docs_found: Optional[str] = None\u00b6\nIf specified, the chain will return a fixed response if no docs\nare found for the question.\nparam return_generated_question: bool = False\u00b6\nReturn the generated question as part of the final result.\nparam return_source_documents: bool = False\u00b6\nReturn the retrieved source documents as part of the final result.\nparam search_kwargs: dict [Optional]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam top_k_docs_for_context: int = 4\u00b6\nparam vectorstore: VectorStore [Required]\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-2", "text": "Whether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-3", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-4", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-5", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-6", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-7", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-8", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, vectorstore: VectorStore, condense_question_prompt: BasePromptTemplate = PromptTemplate(input_variables=['chat_history', 'question'], template='Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question, in its original language.\\n\\nChat History:\\n{chat_history}\\nFollow Up Input: {question}\\nStandalone question:'), chain_type: str = 'stuff', combine_docs_chain_kwargs: Optional[Dict] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseConversationalRetrievalChain[source]\u00b6\nLoad chain from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-9", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-10", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-11", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-12", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-13", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "0b5e079331ec-14", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nInput keys.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ChatVectorDBChain.html"}
{"id": "47b0a0a4f813-0", "text": "langchain.chains.graph_qa.hugegraph.HugeGraphQAChain\u00b6\nclass langchain.chains.graph_qa.hugegraph.HugeGraphQAChain[source]\u00b6\nBases: Chain\nChain for question-answering against a graph by generating gremlin statements.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam graph: HugeGraph [Required]\u00b6\nparam gremlin_generation_chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-1", "text": "them along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam qa_chain: LLMChain [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-2", "text": "response. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-3", "text": "Parameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-4", "text": "Call the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-5", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-6", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-7", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-8", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, *, qa_prompt: BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], template=\"You are an assistant that helps to form nice and human understandable answers.\\nThe information part contains the provided information that you must use to construct an answer.\\nThe provided information is authoritative, you must never doubt it or try to use your internal knowledge to correct it.\\nMake the answer sound as a response to the question. Do not mention that you based the result on the given information.\\nIf the provided information is empty, say that you don't know the answer.\\nInformation:\\n{context}\\n\\nQuestion: {question}\\nHelpful Answer:\"), gremlin_prompt: BasePromptTemplate = PromptTemplate(input_variables=['question', 'schema'], template='Task:Generate Gremlin statement to query a graph database.\\nInstructions:\\nUse only the provided relationship types and properties in the schema.\\nDo not use any other relationship types or properties that are not provided.\\nSchema:\\n{schema}\\nNote: Do not include any explanations or apologies in your responses.\\nDo not respond to any questions that might ask anything else than for you to construct a Gremlin statement.\\nDo not include any text except the generated Gremlin statement.\\n\\nThe question is:\\n{question}'), **kwargs: Any) \u2192 HugeGraphQAChain[source]\u00b6\nInitialize from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-9", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-11", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-12", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-13", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-14", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "47b0a0a4f813-15", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using HugeGraphQAChain\u00b6\nHugeGraph QA Chain", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.hugegraph.HugeGraphQAChain.html"}
{"id": "345dd14393b1-0", "text": "langchain.chains.qa_with_sources.loading.LoadingCallable\u00b6\nclass langchain.chains.qa_with_sources.loading.LoadingCallable(*args, **kwargs)[source]\u00b6\nInterface for loading the combine documents chain.\nMethods\n__init__(*args,\u00a0**kwargs)\n__init__(*args, **kwargs)\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.loading.LoadingCallable.html"}
{"id": "20a58893df6c-0", "text": "langchain.chains.openai_functions.base.create_openai_fn_runnable\u00b6\nlangchain.chains.openai_functions.base.create_openai_fn_runnable(functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]], llm: Runnable, prompt: BasePromptTemplate, *, output_parser: Optional[Union[BaseOutputParser, BaseGenerationOutputParser]] = None, **kwargs: Any) \u2192 Runnable[source]\u00b6\nCreate a runnable sequence that uses OpenAI functions.\nParameters\nfunctions \u2013 A sequence of either dictionaries, pydantic.BaseModels classes, or\nPython functions. If dictionaries are passed in, they are assumed to\nalready be a valid OpenAI functions. If only a single\nfunction is passed in, then it will be enforced that the model use that\nfunction. pydantic.BaseModels and Python functions should have docstrings\ndescribing what the function does. For best results, pydantic.BaseModels\nshould have descriptions of the parameters and Python functions should have\nGoogle Python style args descriptions in the docstring. Additionally,\nPython functions should only use primitive types (str, int, float, bool) or\npydantic.BaseModels for arguments.\nllm \u2013 Language model to use, assumed to support the OpenAI function-calling API.\nprompt \u2013 BasePromptTemplate to pass to the model.\noutput_parser \u2013 BaseLLMOutputParser to use for parsing model outputs. By default\nwill be inferred from the function types. If pydantic.BaseModels are passed\nin, then the OutputParser will try to parse outputs using those. Otherwise\nmodel outputs will simply be parsed as JSON. If multiple functions are\npassed in and they are not pydantic.BaseModels, the chain output will\ninclude both the name of the function that was returned and the arguments\nto pass to the function.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.create_openai_fn_runnable.html"}
{"id": "20a58893df6c-1", "text": "to pass to the function.\nReturns\nA runnable sequence that will pass in the given functions to the model when run.\nExample\nfrom typing import Optional\nfrom langchain.chains.openai_functions import create_openai_fn_chain\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.prompts import ChatPromptTemplate\nfrom langchain.pydantic_v1 import BaseModel, Field\nclass RecordPerson(BaseModel):\n    \"\"\"Record some identifying information about a person.\"\"\"\n    name: str = Field(..., description=\"The person's name\")\n    age: int = Field(..., description=\"The person's age\")\n    fav_food: Optional[str] = Field(None, description=\"The person's favorite food\")\nclass RecordDog(BaseModel):\n    \"\"\"Record some identifying information about a dog.\"\"\"\n    name: str = Field(..., description=\"The dog's name\")\n    color: str = Field(..., description=\"The dog's color\")\n    fav_food: Optional[str] = Field(None, description=\"The dog's favorite food\")\nllm = ChatOpenAI(model=\"gpt-4\", temperature=0)\nprompt = ChatPromptTemplate.from_messages(\n    [\n        (\"system\", \"You are a world class algorithm for recording entities.\"),\n        (\"human\", \"Make calls to the relevant function to record the entities in the following input: {input}\"),\n        (\"human\", \"Tip: Make sure to answer in the correct format\"),\n    ]\n)\nchain = create_openai_fn_runnable([RecordPerson, RecordDog], llm, prompt)\nchain.invoke({\"input\": \"Harry was a chubby brown beagle who loved chicken\"})\n# -> RecordDog(name=\"Harry\", color=\"brown\", fav_food=\"chicken\")", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.create_openai_fn_runnable.html"}
{"id": "09dabba21032-0", "text": "langchain.chains.graph_qa.falkordb.extract_cypher\u00b6\nlangchain.chains.graph_qa.falkordb.extract_cypher(text: str) \u2192 str[source]\u00b6\nExtract Cypher code from a text.\n:param text: Text to extract Cypher code from.\nReturns\nCypher code extracted from the text.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.extract_cypher.html"}
{"id": "920c725c3cbb-0", "text": "langchain.chains.graph_qa.neptune_cypher.trim_query\u00b6\nlangchain.chains.graph_qa.neptune_cypher.trim_query(query: str) \u2192 str[source]\u00b6\nTrim the query to only include Cypher keywords.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.trim_query.html"}
{"id": "5b135a90e376-0", "text": "langchain.chains.query_constructor.ir.Operator\u00b6\nclass langchain.chains.query_constructor.ir.Operator(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnumerator of the operations.\nAND = 'and'\u00b6\nOR = 'or'\u00b6\nNOT = 'not'\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.Operator.html"}
{"id": "6e817f0ed5ed-0", "text": "langchain.chains.graph_qa.cypher.extract_cypher\u00b6\nlangchain.chains.graph_qa.cypher.extract_cypher(text: str) \u2192 str[source]\u00b6\nExtract Cypher code from a text.\nParameters\ntext \u2013 Text to extract Cypher code from.\nReturns\nCypher code extracted from the text.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.extract_cypher.html"}
{"id": "b48bcdef51ad-0", "text": "langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain\u00b6\nclass langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain[source]\u00b6\nBases: Chain\nChain for chatting with an index.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam combine_docs_chain: BaseCombineDocumentsChain [Required]\u00b6\nThe chain used to combine any retrieved documents.\nparam get_chat_history: Optional[Callable[[List[CHAT_TURN_TYPE]], str]] = None\u00b6\nAn optional function to get a string of the chat history.\nIf None is provided, will use a default.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_key: str = 'answer'\u00b6\nThe output key to return the final answer of this chain in.\nparam question_generator: LLMChain [Required]\u00b6\nThe chain used to generate a new question for the sake of retrieval.\nThis chain will take in the current question (with variable question)\nand any chat history (with variable chat_history) and will produce\na new standalone question to be used later on.\nparam rephrase_question: bool = True\u00b6\nWhether or not to pass the new generated question to the combine_docs_chain.\nIf True, will pass the new generated question along.\nIf False, will only use the new generated question for retrieval and pass the\noriginal question along to the combine_docs_chain.\nparam response_if_no_docs_found: Optional[str] = None\u00b6\nIf specified, the chain will return a fixed response if no docs\nare found for the question.\nparam return_generated_question: bool = False\u00b6\nReturn the generated question as part of the final result.\nparam return_source_documents: bool = False\u00b6\nReturn the retrieved source documents as part of the final result.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-2", "text": "accessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-5", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-6", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-8", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-10", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-11", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None[source]\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-12", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-13", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nInput keys.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "b48bcdef51ad-14", "text": "For example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain.html"}
{"id": "3aa73afdca71-0", "text": "langchain.chains.openai_functions.base.create_structured_output_runnable\u00b6\nlangchain.chains.openai_functions.base.create_structured_output_runnable(output_schema: Union[Dict[str, Any], Type[BaseModel]], llm: Runnable, prompt: BasePromptTemplate, *, output_parser: Optional[Union[BaseOutputParser, BaseGenerationOutputParser]] = None, **kwargs: Any) \u2192 Runnable[source]\u00b6\nCreate a runnable that uses an OpenAI function to get a structured output.\nParameters\noutput_schema \u2013 Either a dictionary or pydantic.BaseModel class. If a dictionary\nis passed in, it\u2019s assumed to already be a valid JsonSchema.\nFor best results, pydantic.BaseModels should have docstrings describing what\nthe schema represents and descriptions for the parameters.\nllm \u2013 Language model to use, assumed to support the OpenAI function-calling API.\nprompt \u2013 BasePromptTemplate to pass to the model.\noutput_parser \u2013 BaseLLMOutputParser to use for parsing model outputs. By default\nwill be inferred from the function types. If pydantic.BaseModels are passed\nin, then the OutputParser will try to parse outputs using those. Otherwise\nmodel outputs will simply be parsed as JSON.\nReturns\nA runnable sequence that will pass the given function to the model when run.\nExample\nfrom typing import Optional\nfrom langchain.chains.openai_functions import create_structured_output_chain\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.prompts import ChatPromptTemplate\nfrom langchain.pydantic_v1 import BaseModel, Field\nclass Dog(BaseModel):\n    \"\"\"Identifying information about a dog.\"\"\"\n    name: str = Field(..., description=\"The dog's name\")\n    color: str = Field(..., description=\"The dog's color\")\n    fav_food: Optional[str] = Field(None, description=\"The dog's favorite food\")", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.create_structured_output_runnable.html"}
{"id": "3aa73afdca71-1", "text": "fav_food: Optional[str] = Field(None, description=\"The dog's favorite food\")\nllm = ChatOpenAI(model=\"gpt-3.5-turbo-0613\", temperature=0)\nprompt = ChatPromptTemplate.from_messages(\n    [\n        (\"system\", \"You are a world class algorithm for extracting information in structured formats.\"),\n        (\"human\", \"Use the given format to extract information from the following input: {input}\"),\n        (\"human\", \"Tip: Make sure to answer in the correct format\"),\n    ]\n)\nchain = create_structured_output_chain(Dog, llm, prompt)\nchain.invoke({\"input\": \"Harry was a chubby brown beagle who loved chicken\"})\n# -> Dog(name=\"Harry\", color=\"brown\", fav_food=\"chicken\")", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.create_structured_output_runnable.html"}
{"id": "3a7a28b32ea7-0", "text": "langchain.chains.query_constructor.base.get_query_constructor_prompt\u00b6\nlangchain.chains.query_constructor.base.get_query_constructor_prompt(document_contents: str, attribute_info: ~typing.Sequence[~typing.Union[~langchain.chains.query_constructor.schema.AttributeInfo, dict]], *, examples: ~typing.Optional[~typing.Sequence] = None, allowed_comparators: ~typing.Sequence[~langchain.chains.query_constructor.ir.Comparator] = (<Comparator.EQ: 'eq'>, <Comparator.NE: 'ne'>, <Comparator.GT: 'gt'>, <Comparator.GTE: 'gte'>, <Comparator.LT: 'lt'>, <Comparator.LTE: 'lte'>, <Comparator.CONTAIN: 'contain'>, <Comparator.LIKE: 'like'>, <Comparator.IN: 'in'>, <Comparator.NIN: 'nin'>), allowed_operators: ~typing.Sequence[~langchain.chains.query_constructor.ir.Operator] = (<Operator.AND: 'and'>, <Operator.OR: 'or'>, <Operator.NOT: 'not'>), enable_limit: bool = False, schema_prompt: ~typing.Optional[~langchain.schema.prompt_template.BasePromptTemplate] = None, **kwargs: ~typing.Any) \u2192 BasePromptTemplate[source]\u00b6\nCreate query construction prompt.\nParameters\ndocument_contents \u2013 The contents of the document to be queried.\nattribute_info \u2013 A list of AttributeInfo objects describing\nthe attributes of the document.\nexamples \u2013 Optional list of examples to use for the chain.\nallowed_comparators \u2013 Sequence of allowed comparators.\nallowed_operators \u2013 Sequence of allowed operators.\nenable_limit \u2013 Whether to enable the limit operator. Defaults to False.\nschema_prompt \u2013 Prompt for describing query schema. Should have string input\nvariables allowed_comparators and allowed_operators.\n**kwargs \u2013 Additional named params to pass to FewShotPromptTemplate init.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.get_query_constructor_prompt.html"}
{"id": "3a7a28b32ea7-1", "text": "**kwargs \u2013 Additional named params to pass to FewShotPromptTemplate init.\nReturns\nA prompt template that can be used to construct queries.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.get_query_constructor_prompt.html"}
{"id": "3d5523c2d0e6-0", "text": "langchain.chains.router.base.Route\u00b6\nclass langchain.chains.router.base.Route(destination, next_inputs)[source]\u00b6\nCreate new instance of Route(destination, next_inputs)\nAttributes\ndestination\nAlias for field number 0\nnext_inputs\nAlias for field number 1\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.Route.html"}
{"id": "39a3db3c1e83-0", "text": "langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain\u00b6\nclass langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain[source]\u00b6\nBases: BaseQAWithSourcesChain\nQuestion-answering with sources over an index.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam combine_documents_chain: BaseCombineDocumentsChain [Required]\u00b6\nChain to use to combine documents.\nparam max_tokens_limit: int = 3375\u00b6\nRestrict the docs to return from store based on tokens,\nenforced only for StuffDocumentChain and if reduce_k_below_max_tokens is to true\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam reduce_k_below_max_tokens: bool = False\u00b6\nReduce the number of results to return from store based on tokens limit\nparam retriever: langchain.schema.retriever.BaseRetriever [Required]\u00b6\nIndex to connect to.\nparam return_source_documents: bool = False\u00b6\nReturn the source documents.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-2", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-3", "text": "only one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-4", "text": "Call the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-5", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-6", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-7", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_chain_type(llm: BaseLanguageModel, chain_type: str = 'stuff', chain_type_kwargs: Optional[dict] = None, **kwargs: Any) \u2192 BaseQAWithSourcesChain\u00b6\nLoad chain from chain type.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-8", "text": "classmethod from_llm(llm: BaseLanguageModel, document_prompt: BasePromptTemplate = PromptTemplate(input_variables=['page_content', 'source'], template='Content: {page_content}\\nSource: {source}'), question_prompt: BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], template='Use the following portion of a long document to see if any of the text is relevant to answer the question. \\nReturn any relevant text verbatim.\\n{context}\\nQuestion: {question}\\nRelevant text, if any:'), combine_prompt: BasePromptTemplate = PromptTemplate(input_variables=['question', 'summaries'], template='Given the following extracted parts of a long document and a question, create a final answer with references (\"SOURCES\"). \\nIf you don\\'t know the answer, just say that you don\\'t know. Don\\'t try to make up an answer.\\nALWAYS return a \"SOURCES\" part in your answer.\\n\\nQUESTION: Which state/country\\'s law governs the interpretation of the contract?\\n=========\\nContent: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in\u00a0 relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an\u00a0 injunction or other relief to protect its Intellectual Property Rights.\\nSource: 28-pl\\nContent: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other)\u00a0 right or remedy.\\n\\n11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation\u00a0 in force of the remainder of the term (if any) and this Agreement.\\n\\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-9", "text": "Agreement.\\n\\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any\u00a0 kind between the parties.\\n\\n11.9 No Third-Party Beneficiaries.\\nSource: 30-pl\\nContent: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as\u00a0 defined in Clause 8.5) or that such a violation is reasonably likely to occur,\\nSource: 4-pl\\n=========\\nFINAL ANSWER: This Agreement is governed by English law.\\nSOURCES: 28-pl\\n\\nQUESTION: What did the president say about Michael Jackson?\\n=========\\nContent: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.\u00a0 \\n\\nLast year COVID-19 kept us apart. This year we are finally together again. \\n\\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \\n\\nWith a duty to one another to the American people to the Constitution. \\n\\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \\n\\nSix days ago, Russia\u2019s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \\n\\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \\n\\nHe met the Ukrainian people. \\n\\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \\n\\nGroups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland.\\nSource:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-10", "text": "tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland.\\nSource: 0-pl\\nContent: And we won\u2019t stop. \\n\\nWe have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. \\n\\nLet\u2019s use this moment to reset. Let\u2019s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease.\u00a0 \\n\\nLet\u2019s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans.\u00a0 \\n\\nWe can\u2019t change how divided we\u2019ve been. But we can change how we move forward\u2014on COVID-19 and other issues we must face together. \\n\\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \\n\\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \\n\\nOfficer Mora was 27 years old. \\n\\nOfficer Rivera was 22. \\n\\nBoth Dominican Americans who\u2019d grown up on the same streets they later chose to patrol as police officers. \\n\\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves.\\nSource: 24-pl\\nContent: And a proud Ukrainian people, who have known 30 years\u00a0 of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards.\u00a0 \\n\\nTo all Americans, I will be honest with you, as I\u2019ve always promised. A Russian dictator, invading a foreign country, has costs around the world. \\n\\nAnd I\u2019m taking robust action to make sure the pain of our sanctions", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-11", "text": "world. \\n\\nAnd I\u2019m taking robust action to make sure the pain of our sanctions\u00a0 is targeted at Russia\u2019s economy. And I will use every tool at our disposal to protect American businesses and consumers. \\n\\nTonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world.\u00a0 \\n\\nAmerica will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies.\u00a0 \\n\\nThese steps will help blunt gas prices here at home. And I know the news about what\u2019s happening can seem alarming. \\n\\nBut I want you to know that we are going to be okay.\\nSource: 5-pl\\nContent: More support for patients and families. \\n\\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \\n\\nIt\u2019s based on DARPA\u2014the Defense Department project that led to the Internet, GPS, and so much more.\u00a0 \\n\\nARPA-H will have a singular purpose\u2014to drive breakthroughs in cancer, Alzheimer\u2019s, diabetes, and more. \\n\\nA unity agenda for the nation. \\n\\nWe can do this. \\n\\nMy fellow Americans\u2014tonight , we have gathered in a sacred space\u2014the citadel of our democracy. \\n\\nIn this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. \\n\\nWe have fought for freedom, expanded liberty, defeated totalitarianism and terror. \\n\\nAnd built the strongest, freest, and most prosperous nation the world has ever known. \\n\\nNow is the hour. \\n\\nOur moment of responsibility. \\n\\nOur test of resolve and conscience, of history itself. \\n\\nIt is in this moment that our character", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-12", "text": "of resolve and conscience, of history itself. \\n\\nIt is in this moment that our character is formed. Our purpose is found. Our future is forged. \\n\\nWell I know this nation.\\nSource: 34-pl\\n=========\\nFINAL ANSWER: The president did not mention Michael Jackson.\\nSOURCES:\\n\\nQUESTION: {question}\\n=========\\n{summaries}\\n=========\\nFINAL ANSWER:'), **kwargs: Any) \u2192 BaseQAWithSourcesChain\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-13", "text": "Construct the chain from an LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-14", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-15", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-16", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-17", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-18", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "39a3db3c1e83-19", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using RetrievalQAWithSourcesChain\u00b6\nWeaviate\nNeo4j Vector Index\nMarqo\nPsychic\nSet env var OPENAI_API_KEY or load from a .env file:\nQuestion Answering\nVector SQL Retriever with MyScale\nWebResearchRetriever", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.retrieval.RetrievalQAWithSourcesChain.html"}
{"id": "8acea9e06a37-0", "text": "langchain.chains.qa_generation.base.QAGenerationChain\u00b6\nclass langchain.chains.qa_generation.base.QAGenerationChain[source]\u00b6\nBases: Chain\nBase class for question-answer generation chains.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam input_key: str = 'text'\u00b6\nKey of the input to the chain.\nparam k: Optional[int] = None\u00b6\nNumber of questions to generate.\nparam llm_chain: LLMChain [Required]\u00b6\nLLM Chain that generates responses from user input and context.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-1", "text": "You can use these to eg identify a specific instance of a chain with its use case.\nparam output_key: str = 'questions'\u00b6\nKey of the output of the chain.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam text_splitter: TextSplitter = <langchain.text_splitter.RecursiveCharacterTextSplitter object>\u00b6\nText splitter that splits the input into chunks.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-2", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-3", "text": "memory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-4", "text": "Convenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, prompt: Optional[BasePromptTemplate] = None, **kwargs: Any) \u2192 QAGenerationChain[source]\u00b6\nCreate a QAGenerationChain from a language model.\nParameters\nllm \u2013 a language model\nprompt \u2013 a prompt template\n**kwargs \u2013 additional arguments\nReturns\na QAGenerationChain class\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-8", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-10", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-11", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-12", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-13", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nKeys expected to be in the chain input.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "8acea9e06a37-14", "text": "For example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nKeys expected to be in the chain output.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_generation.base.QAGenerationChain.html"}
{"id": "4ffe2e056112-0", "text": "langchain.chains.combine_documents.reduce.split_list_of_docs\u00b6\nlangchain.chains.combine_documents.reduce.split_list_of_docs(docs: List[Document], length_func: Callable, token_max: int, **kwargs: Any) \u2192 List[List[Document]][source]\u00b6\nSplit Documents into subsets that each meet a cumulative length constraint.\nParameters\ndocs \u2013 The full list of Documents.\nlength_func \u2013 Function for computing the cumulative length of a set of Documents.\ntoken_max \u2013 The maximum cumulative length of any subset of Documents.\n**kwargs \u2013 Arbitrary additional keyword params to pass to each call of the\nlength_func.\nReturns\nA List[List[Document]].", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.split_list_of_docs.html"}
{"id": "898497ec8c48-0", "text": "langchain.chains.prompt_selector.ConditionalPromptSelector\u00b6\nclass langchain.chains.prompt_selector.ConditionalPromptSelector[source]\u00b6\nBases: BasePromptSelector\nPrompt collection that goes through conditionals.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam conditionals: List[Tuple[Callable[[langchain.schema.language_model.BaseLanguageModel], bool], langchain.schema.prompt_template.BasePromptTemplate]] [Optional]\u00b6\nList of conditionals and prompts to use if the conditionals match.\nparam default_prompt: langchain.schema.prompt_template.BasePromptTemplate [Required]\u00b6\nDefault prompt to use if no conditionals match.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.prompt_selector.ConditionalPromptSelector.html"}
{"id": "898497ec8c48-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_prompt(llm: BaseLanguageModel) \u2192 BasePromptTemplate[source]\u00b6\nGet default prompt for a language model.\nParameters\nllm \u2013 Language model to get prompt for.\nReturns\nPrompt to use for the language model.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.prompt_selector.ConditionalPromptSelector.html"}
{"id": "898497ec8c48-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using ConditionalPromptSelector\u00b6\nRun LLMs locally", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.prompt_selector.ConditionalPromptSelector.html"}
{"id": "be3da2984c32-0", "text": "langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain\u00b6\nclass langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain[source]\u00b6\nBases: BaseConversationalRetrievalChain\nChain for having a conversation based on retrieved documents.\nThis chain takes in chat history (a list of messages) and new questions,\nand then returns an answer to that question.\nThe algorithm for this chain consists of three parts:\n1. Use the chat history and the new question to create a \u201cstandalone question\u201d.\nThis is done so that this question can be passed into the retrieval step to fetch\nrelevant documents. If only the new question was passed in, then relevant context\nmay be lacking. If the whole conversation was passed into retrieval, there may\nbe unnecessary information there that would distract from retrieval.\n2. This new question is passed to the retriever and relevant documents are\nreturned.\n3. The retrieved documents are passed to an LLM along with either the new question\n(default behavior) or the original question and chat history to generate a final\nresponse.\nExample\nfrom langchain.chains import (\n    StuffDocumentsChain, LLMChain, ConversationalRetrievalChain\n)\nfrom langchain.prompts import PromptTemplate\nfrom langchain.llms import OpenAI\ncombine_docs_chain = StuffDocumentsChain(...)\nvectorstore = ...\nretriever = vectorstore.as_retriever()\n# This controls how the standalone question is generated.\n# Should take `chat_history` and `question` as input variables.\ntemplate = (\n    \"Combine the chat history and follow up question into \"\n    \"a standalone question. Chat History: {chat_history}\"\n    \"Follow up question: {question}\"\n)\nprompt = PromptTemplate.from_template(template)\nllm = OpenAI()", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-1", "text": ")\nprompt = PromptTemplate.from_template(template)\nllm = OpenAI()\nquestion_generator_chain = LLMChain(llm=llm, prompt=prompt)\nchain = ConversationalRetrievalChain(\n    combine_docs_chain=combine_docs_chain,\n    retriever=retriever,\n    question_generator=question_generator_chain,\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam combine_docs_chain: BaseCombineDocumentsChain [Required]\u00b6\nThe chain used to combine any retrieved documents.\nparam get_chat_history: Optional[Callable[[List[CHAT_TURN_TYPE]], str]] = None\u00b6\nAn optional function to get a string of the chat history.\nIf None is provided, will use a default.\nparam max_tokens_limit: Optional[int] = None\u00b6\nIf set, enforces that the documents returned are less than this limit.\nThis is only enforced if combine_docs_chain is of type StuffDocumentsChain.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-2", "text": "There are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_key: str = 'answer'\u00b6\nThe output key to return the final answer of this chain in.\nparam question_generator: LLMChain [Required]\u00b6\nThe chain used to generate a new question for the sake of retrieval.\nThis chain will take in the current question (with variable question)\nand any chat history (with variable chat_history) and will produce\na new standalone question to be used later on.\nparam rephrase_question: bool = True\u00b6\nWhether or not to pass the new generated question to the combine_docs_chain.\nIf True, will pass the new generated question along.\nIf False, will only use the new generated question for retrieval and pass the\noriginal question along to the combine_docs_chain.\nparam response_if_no_docs_found: Optional[str] = None\u00b6\nIf specified, the chain will return a fixed response if no docs\nare found for the question.\nparam retriever: BaseRetriever [Required]\u00b6\nRetriever to use to fetch documents.\nparam return_generated_question: bool = False\u00b6\nReturn the generated question as part of the final result.\nparam return_source_documents: bool = False\u00b6\nReturn the retrieved source documents as part of the final result.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-3", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-4", "text": "to False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-5", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-6", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-7", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-8", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-9", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, retriever: BaseRetriever, condense_question_prompt: BasePromptTemplate = PromptTemplate(input_variables=['chat_history', 'question'], template='Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question, in its original language.\\n\\nChat History:\\n{chat_history}\\nFollow Up Input: {question}\\nStandalone question:'), chain_type: str = 'stuff', verbose: bool = False, condense_question_llm: Optional[BaseLanguageModel] = None, combine_docs_chain_kwargs: Optional[Dict] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseConversationalRetrievalChain[source]\u00b6\nConvenience method to load chain from LLM and retriever.\nThis provides some logic to create the question_generator chain\nas well as the combine_docs_chain.\nParameters\nllm \u2013 The default language model to use at every part of this chain\n(eg in both the question generation and the answering)\nretriever \u2013 The retriever to use to fetch relevant documents from.\ncondense_question_prompt \u2013 The prompt to use to condense the chat history\nand new question into a standalone question.\nchain_type \u2013 The chain type to use to create the combine_docs_chain, will\nbe sent to load_qa_chain.\nverbose \u2013 Verbosity flag for logging to stdout.\ncondense_question_llm \u2013 The language model to use for condensing the chat\nhistory and new question into a standalone question. If none is\nprovided, will default to llm.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-10", "text": "provided, will default to llm.\ncombine_docs_chain_kwargs \u2013 Parameters to pass as kwargs to load_qa_chain\nwhen constructing the combine_docs_chain.\ncallbacks \u2013 Callbacks to pass to all subchains.\n**kwargs \u2013 Additional parameters to pass when initializing\nConversationalRetrievalChain\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-11", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-12", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-13", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-14", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-15", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nInput keys.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "be3da2984c32-16", "text": "Input keys.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ConversationalRetrievalChain\u00b6\nWikipedia\nArxiv\nChat Over Documents with Vectara\nVectara\nSet env var OPENAI_API_KEY or load from a .env file:\nSet env var OPENAI_API_KEY or load from a .env file\nAnalysis of Twitter the-algorithm source code with LangChain, GPT4 and Activeloop\u2019s Deep Lake\nUse LangChain, GPT and Activeloop\u2019s Deep Lake to work with code base\nStructure answers with OpenAI functions\nQA using Activeloop\u2019s DeepLake", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain.html"}
{"id": "d42c79ef6102-0", "text": "langchain.chains.openai_functions.qa_with_structure.AnswerWithSources\u00b6\nclass langchain.chains.openai_functions.qa_with_structure.AnswerWithSources[source]\u00b6\nBases: BaseModel\nAn answer to the question, with sources.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam answer: str [Required]\u00b6\nAnswer to the question that was asked\nparam sources: List[str] [Required]\u00b6\nList of sources used to answer the question\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.qa_with_structure.AnswerWithSources.html"}
{"id": "d42c79ef6102-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.qa_with_structure.AnswerWithSources.html"}
{"id": "d42c79ef6102-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.qa_with_structure.AnswerWithSources.html"}
{"id": "537e185b4210-0", "text": "langchain.chains.query_constructor.ir.Operation\u00b6\nclass langchain.chains.query_constructor.ir.Operation[source]\u00b6\nBases: FilterDirective\nA logical operation over other directives.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam arguments: List[langchain.chains.query_constructor.ir.FilterDirective] [Required]\u00b6\nparam operator: langchain.chains.query_constructor.ir.Operator [Required]\u00b6\naccept(visitor: Visitor) \u2192 Any\u00b6\nAccept a visitor.\nParameters\nvisitor \u2013 visitor to accept\nReturns\nresult of visiting\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.Operation.html"}
{"id": "537e185b4210-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.Operation.html"}
{"id": "537e185b4210-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.Operation.html"}
{"id": "6db02a8073e6-0", "text": "langchain.chains.sql_database.query.create_sql_query_chain\u00b6\nlangchain.chains.sql_database.query.create_sql_query_chain(llm: BaseLanguageModel, db: SQLDatabase, prompt: Optional[BasePromptTemplate] = None, k: int = 5) \u2192 Runnable[Union[SQLInput, SQLInputWithTables], str][source]\u00b6\nCreate a chain that generates SQL queries.\nSecurity Note: This chain generates SQL queries for the given database.\nThe SQLDatabase class provides a get_table_info method that can be used\nto get column information as well as sample data from the table.\nTo mitigate risk of leaking sensitive data, limit permissions\nto read and scope to the tables that are needed.\nOptionally, use the SQLInputWithTables input type to specify which tables\nare allowed to be accessed.\nControl access to who can submit requests to this chain.\nSee https://python.langchain.com/docs/security for more information.\nParameters\nllm \u2013 The language model to use\ndb \u2013 The SQLDatabase to generate the query for\nprompt \u2013 The prompt to use. If none is provided, will choose one\nbased on dialect. Defaults to None.\nk \u2013 The number of results per select statement to return. Defaults to 5.\nReturns\nA chain that takes in a question and generates a SQL query that answers\nthat question.\nExamples using create_sql_query_chain\u00b6\nMultiple Retrieval Sources\nSet env var OPENAI_API_KEY or load from a .env file\nSQL", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sql_database.query.create_sql_query_chain.html"}
{"id": "1ddb28b50002-0", "text": "langchain.chains.query_constructor.ir.Comparison\u00b6\nclass langchain.chains.query_constructor.ir.Comparison[source]\u00b6\nBases: FilterDirective\nA comparison to a value.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam attribute: str [Required]\u00b6\nparam comparator: langchain.chains.query_constructor.ir.Comparator [Required]\u00b6\nparam value: Any = None\u00b6\naccept(visitor: Visitor) \u2192 Any\u00b6\nAccept a visitor.\nParameters\nvisitor \u2013 visitor to accept\nReturns\nresult of visiting\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.Comparison.html"}
{"id": "1ddb28b50002-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.Comparison.html"}
{"id": "1ddb28b50002-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.Comparison.html"}
{"id": "8d56a00e0365-0", "text": "langchain.chains.router.embedding_router.EmbeddingRouterChain\u00b6\nclass langchain.chains.router.embedding_router.EmbeddingRouterChain[source]\u00b6\nBases: RouterChain\nChain that uses embeddings to route between options.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam routing_keys: List[str] = ['query']\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "8d56a00e0365-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam vectorstore: VectorStore [Required]\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "8d56a00e0365-2", "text": "include_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "8d56a00e0365-3", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync aroute(inputs: Dict[str, Any], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Route\u00b6\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "8d56a00e0365-4", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "8d56a00e0365-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "8d56a00e0365-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "8d56a00e0365-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_names_and_descriptions(names_and_descriptions: Sequence[Tuple[str, Sequence[str]]], vectorstore_cls: Type[VectorStore], embeddings: Embeddings, **kwargs: Any) \u2192 EmbeddingRouterChain[source]\u00b6\nConvenience constructor.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "8d56a00e0365-8", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "8d56a00e0365-9", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "8d56a00e0365-10", "text": "memory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nroute(inputs: Dict[str, Any], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Route\u00b6\nRoute inputs to a destination chain.\nParameters\ninputs \u2013 inputs to the chain\ncallbacks \u2013 callbacks to use for the chain\nReturns\na Route object\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "8d56a00e0365-11", "text": "chain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "8d56a00e0365-12", "text": "Try to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "8d56a00e0365-13", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nKeys expected to be in the chain output.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using EmbeddingRouterChain\u00b6\nRouter", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.embedding_router.EmbeddingRouterChain.html"}
{"id": "72f2103065a4-0", "text": "langchain.chains.retrieval_qa.base.VectorDBQA\u00b6\nclass langchain.chains.retrieval_qa.base.VectorDBQA[source]\u00b6\nBases: BaseRetrievalQA\nChain for question-answering against a vector database.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam combine_documents_chain: BaseCombineDocumentsChain [Required]\u00b6\nChain to use to combine the documents.\nparam k: int = 4\u00b6\nNumber of documents to query for.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam return_source_documents: bool = False\u00b6\nReturn the source documents or not.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-1", "text": "param return_source_documents: bool = False\u00b6\nReturn the source documents or not.\nparam search_kwargs: Dict[str, Any] [Optional]\u00b6\nExtra search args.\nparam search_type: str = 'similarity'\u00b6\nSearch type to use over vectorstore. similarity or mmr.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam vectorstore: VectorStore [Required]\u00b6\nVector Database to connect to.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-2", "text": "chain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-3", "text": "Chain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-4", "text": "Convenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_chain_type(llm: BaseLanguageModel, chain_type: str = 'stuff', chain_type_kwargs: Optional[dict] = None, **kwargs: Any) \u2192 BaseRetrievalQA\u00b6\nLoad chain from chain type.\nclassmethod from_llm(llm: BaseLanguageModel, prompt: Optional[PromptTemplate] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseRetrievalQA\u00b6\nInitialize from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-8", "text": "Returns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-10", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-11", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-12", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-13", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "72f2103065a4-14", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.VectorDBQA.html"}
{"id": "8a860f0ab822-0", "text": "langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain\u00b6\nclass langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain[source]\u00b6\nBases: Chain\nChain for question-answering against a graph by generating nGQL statements.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam graph: NebulaGraph [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-1", "text": "There are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam ngql_generation_chain: LLMChain [Required]\u00b6\nparam qa_chain: LLMChain [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-2", "text": "response. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-3", "text": "Parameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-4", "text": "Call the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-5", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-6", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-7", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-8", "text": "classmethod from_llm(llm: BaseLanguageModel, *, qa_prompt: BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], template=\"You are an assistant that helps to form nice and human understandable answers.\\nThe information part contains the provided information that you must use to construct an answer.\\nThe provided information is authoritative, you must never doubt it or try to use your internal knowledge to correct it.\\nMake the answer sound as a response to the question. Do not mention that you based the result on the given information.\\nIf the provided information is empty, say that you don't know the answer.\\nInformation:\\n{context}\\n\\nQuestion: {question}\\nHelpful Answer:\"), ngql_prompt: BasePromptTemplate = PromptTemplate(input_variables=['question', 'schema'], template=\"Task:Generate NebulaGraph Cypher statement to query a graph database.\\n\\nInstructions:\\n\\nFirst, generate cypher then convert it to NebulaGraph Cypher dialect(rather than standard):\\n1. it requires explicit label specification only when referring to node properties: v.`Foo`.name\\n2. note explicit label specification is not needed for edge properties, so it's e.name instead of e.`Bar`.name\\n3. it uses double equals sign for comparison: `==` rather than `=`\\nFor instance:\\n```diff\\n< MATCH (p:person)-[e:directed]->(m:movie) WHERE m.name = 'The Godfather II'\\n< RETURN p.name, e.year, m.name;\\n---\\n> MATCH (p:`person`)-[e:directed]->(m:`movie`) WHERE m.`movie`.`name` == 'The Godfather II'\\n> RETURN p.`person`.`name`, e.year, m.`movie`.`name`;\\n```\\n\\nUse only the provided relationship types and properties in the schema.\\nDo not use any other relationship", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-9", "text": "only the provided relationship types and properties in the schema.\\nDo not use any other relationship types or properties that are not provided.\\nSchema:\\n{schema}\\nNote: Do not include any explanations or apologies in your responses.\\nDo not respond to any questions that might ask anything else than for you to construct a Cypher statement.\\nDo not include any text except the generated Cypher statement.\\n\\nThe question is:\\n{question}\"), **kwargs: Any) \u2192 NebulaGraphQAChain[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-10", "text": "Initialize from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-11", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-12", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-13", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-14", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-15", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "8a860f0ab822-16", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using NebulaGraphQAChain\u00b6\nNebulaGraphQAChain", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain.html"}
{"id": "fcfb3051fc85-0", "text": "langchain.chains.query_constructor.base.load_query_constructor_chain\u00b6\nlangchain.chains.query_constructor.base.load_query_constructor_chain(llm: ~langchain.schema.language_model.BaseLanguageModel, document_contents: str, attribute_info: ~typing.Sequence[~typing.Union[~langchain.chains.query_constructor.schema.AttributeInfo, dict]], examples: ~typing.Optional[~typing.List] = None, allowed_comparators: ~typing.Sequence[~langchain.chains.query_constructor.ir.Comparator] = (<Comparator.EQ: 'eq'>, <Comparator.NE: 'ne'>, <Comparator.GT: 'gt'>, <Comparator.GTE: 'gte'>, <Comparator.LT: 'lt'>, <Comparator.LTE: 'lte'>, <Comparator.CONTAIN: 'contain'>, <Comparator.LIKE: 'like'>, <Comparator.IN: 'in'>, <Comparator.NIN: 'nin'>), allowed_operators: ~typing.Sequence[~langchain.chains.query_constructor.ir.Operator] = (<Operator.AND: 'and'>, <Operator.OR: 'or'>, <Operator.NOT: 'not'>), enable_limit: bool = False, schema_prompt: ~typing.Optional[~langchain.schema.prompt_template.BasePromptTemplate] = None, **kwargs: ~typing.Any) \u2192 LLMChain[source]\u00b6\nLoad a query constructor chain.\nParameters\nllm \u2013 BaseLanguageModel to use for the chain.\ndocument_contents \u2013 The contents of the document to be queried.\nattribute_info \u2013 Sequence of attributes in the document.\nexamples \u2013 Optional list of examples to use for the chain.\nallowed_comparators \u2013 Sequence of allowed comparators. Defaults to all\nComparators.\nallowed_operators \u2013 Sequence of allowed operators. Defaults to all Operators.\nenable_limit \u2013 Whether to enable the limit operator. Defaults to False.\nschema_prompt \u2013 Prompt for describing query schema. Should have string input", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.load_query_constructor_chain.html"}
{"id": "fcfb3051fc85-1", "text": "schema_prompt \u2013 Prompt for describing query schema. Should have string input\nvariables allowed_comparators and allowed_operators.\n**kwargs \u2013 Arbitrary named params to pass to LLMChain.\nReturns\nA LLMChain that can be used to construct queries.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.load_query_constructor_chain.html"}
{"id": "fc706b9a28a7-0", "text": "langchain.chains.openai_tools.extraction.create_extraction_chain_pydantic\u00b6\nlangchain.chains.openai_tools.extraction.create_extraction_chain_pydantic(pydantic_schemas: Union[List[Type[BaseModel]], Type[BaseModel]], llm: BaseLanguageModel, system_message: str = 'Extract and save the relevant entities mentioned in the following passage together with their properties.\\n\\nIf a property is not present and is not required in the function parameters, do not include it in the output.') \u2192 Runnable[source]\u00b6\nExamples using create_extraction_chain_pydantic\u00b6\nSet env var OPENAI_API_KEY or load from a .env file:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_tools.extraction.create_extraction_chain_pydantic.html"}
{"id": "0c8386b8c88d-0", "text": "langchain.chains.openai_functions.tagging.create_tagging_chain_pydantic\u00b6\nlangchain.chains.openai_functions.tagging.create_tagging_chain_pydantic(pydantic_schema: Any, llm: BaseLanguageModel, prompt: Optional[ChatPromptTemplate] = None, **kwargs: Any) \u2192 Chain[source]\u00b6\nCreates a chain that extracts information from a passagebased on a pydantic schema.\nParameters\npydantic_schema \u2013 The pydantic schema of the entities to extract.\nllm \u2013 The language model to use.\nReturns\nChain (LLMChain) that can be used to extract information from a passage.\nExamples using create_tagging_chain_pydantic\u00b6\nSet env var OPENAI_API_KEY or load from a .env file:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.tagging.create_tagging_chain_pydantic.html"}
{"id": "c2d85b6dc335-0", "text": "langchain.chains.combine_documents.refine.RefineDocumentsChain\u00b6\nclass langchain.chains.combine_documents.refine.RefineDocumentsChain[source]\u00b6\nBases: BaseCombineDocumentsChain\nCombine documents by doing a first pass and then refining on more documents.\nThis algorithm first calls initial_llm_chain on the first document, passing\nthat first document in with the variable name document_variable_name, and\nproduces a new variable with the variable name initial_response_name.\nThen, it loops over every remaining document. This is called the \u201crefine\u201d step.\nIt calls refine_llm_chain,\npassing in that document with the variable name document_variable_name\nas well as the previous response with the variable name initial_response_name.\nExample\nfrom langchain.chains import RefineDocumentsChain, LLMChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.llms import OpenAI\n# This controls how each document will be formatted. Specifically,\n# it will be passed to `format_document` - see that function for more\n# details.\ndocument_prompt = PromptTemplate(\n    input_variables=[\"page_content\"],\n     template=\"{page_content}\"\n)\ndocument_variable_name = \"context\"\nllm = OpenAI()\n# The prompt here should take as an input variable the\n# `document_variable_name`\nprompt = PromptTemplate.from_template(\n    \"Summarize this content: {context}\"\n)\ninitial_llm_chain = LLMChain(llm=llm, prompt=prompt)\ninitial_response_name = \"prev_response\"\n# The prompt here should take as an input variable the\n# `document_variable_name` as well as `initial_response_name`\nprompt_refine = PromptTemplate.from_template(\n    \"Here's your first summary: {prev_response}. \"\n    \"Now add to it based on the following context: {context}\"\n)", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-1", "text": "\"Now add to it based on the following context: {context}\"\n)\nrefine_llm_chain = LLMChain(llm=llm, prompt=prompt_refine)\nchain = RefineDocumentsChain(\n    initial_llm_chain=initial_llm_chain,\n    refine_llm_chain=refine_llm_chain,\n    document_prompt=document_prompt,\n    document_variable_name=document_variable_name,\n    initial_response_name=initial_response_name,\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam document_prompt: BasePromptTemplate [Optional]\u00b6\nPrompt to use to format each document, gets passed to format_document.\nparam document_variable_name: str [Required]\u00b6\nThe variable name in the initial_llm_chain to put the documents in.\nIf only one variable in the initial_llm_chain, this need not be provided.\nparam initial_llm_chain: LLMChain [Required]\u00b6\nLLM chain to use on initial document.\nparam initial_response_name: str [Required]\u00b6\nThe variable name to format the initial response in when refining.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-2", "text": "and at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam refine_llm_chain: LLMChain [Required]\u00b6\nLLM chain to use when refining.\nparam return_intermediate_steps: bool = False\u00b6\nReturn the results of the refine steps in the output.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-3", "text": "Execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-4", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync acombine_docs(docs: List[Document], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Tuple[str, dict][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-5", "text": "Async combine by mapping a first chain over all, then stuffinginto a final chain.\nParameters\ndocs \u2013 List of documents to combine\ncallbacks \u2013 Callbacks to be passed through\n**kwargs \u2013 additional parameters to be passed to LLM calls (like other\ninput variables besides the documents)\nReturns\nThe first element returned is the single string output. The second\nelement returned is a dictionary of other keys to return.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-6", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-7", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncombine_docs(docs: List[Document], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Tuple[str, dict][source]\u00b6\nCombine by mapping first chain over all, then stuffing into final chain.\nParameters\ndocs \u2013 List of documents to combine\ncallbacks \u2013 Callbacks to be passed through\n**kwargs \u2013 additional parameters to be passed to LLM calls (like other\ninput variables besides the documents)\nReturns", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-8", "text": "input variables besides the documents)\nReturns\nThe first element returned is the single string output. The second\nelement returned is a dictionary of other keys to return.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-9", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-10", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-11", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprompt_length(docs: List[Document], **kwargs: Any) \u2192 Optional[int]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-12", "text": "prompt_length(docs: List[Document], **kwargs: Any) \u2192 Optional[int]\u00b6\nReturn the prompt length given the documents passed in.\nThis can be used by a caller to determine whether passing in a list\nof documents would exceed a certain prompt length. This useful when\ntrying to ensure that the size of a prompt remains below a certain\ncontext limit.\nParameters\ndocs \u2013 List[Document], a list of documents to use to calculate the\ntotal prompt length.\nReturns\nReturns None if the method does not depend on the prompt length,\notherwise the length of the prompt in tokens.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-13", "text": "Example\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-14", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-15", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "c2d85b6dc335-16", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.refine.RefineDocumentsChain.html"}
{"id": "d92a5c83fde0-0", "text": "langchain.chains.graph_qa.cypher_utils.CypherQueryCorrector\u00b6\nclass langchain.chains.graph_qa.cypher_utils.CypherQueryCorrector(schemas: List[Schema])[source]\u00b6\nUsed to correct relationship direction in generated Cypher statements.\nThis code is copied from the winner\u2019s submission to the Cypher competition:\nhttps://github.com/sakusaku-rich/cypher-direction-competition\nParameters\nschemas \u2013 list of schemas\nAttributes\nnode_pattern\nnode_relation_node_pattern\npath_pattern\nproperty_pattern\nrelation_type_pattern\nMethods\n__init__(schemas)\nparam schemas\nlist of schemas\nclean_node(node)\nparam node\nnode in string format\ncorrect_query(query)\nparam query\ncypher query\ndetect_labels(str_node,\u00a0node_variable_dict)\nparam str_node\nnode in string format\ndetect_node_variables(query)\nparam query\ncypher query\ndetect_relation_types(str_relation)\nparam str_relation\nrelation in string format\nextract_node_variable(part)\nparam part\nnode in string format\nextract_paths(query)\nparam query\ncypher query\njudge_direction(relation)\nparam relation\nrelation in string format\nverify_schema(from_node_labels,\u00a0...)\nparam from_node_labels\nlabels of the from node\n__init__(schemas: List[Schema])[source]\u00b6\nParameters\nschemas \u2013 list of schemas\nclean_node(node: str) \u2192 str[source]\u00b6\nParameters\nnode \u2013 node in string format\ncorrect_query(query: str) \u2192 str[source]\u00b6\nParameters\nquery \u2013 cypher query\ndetect_labels(str_node: str, node_variable_dict: Dict[str, Any]) \u2192 List[str][source]\u00b6\nParameters\nstr_node \u2013 node in string format\nnode_variable_dict \u2013 dictionary of node variables\ndetect_node_variables(query: str) \u2192 Dict[str, List[str]][source]\u00b6\nParameters\nquery \u2013 cypher query", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher_utils.CypherQueryCorrector.html"}
{"id": "d92a5c83fde0-1", "text": "Parameters\nquery \u2013 cypher query\ndetect_relation_types(str_relation: str) \u2192 Tuple[str, List[str]][source]\u00b6\nParameters\nstr_relation \u2013 relation in string format\nextract_node_variable(part: str) \u2192 Optional[str][source]\u00b6\nParameters\npart \u2013 node in string format\nextract_paths(query: str) \u2192 List[str][source]\u00b6\nParameters\nquery \u2013 cypher query\njudge_direction(relation: str) \u2192 str[source]\u00b6\nParameters\nrelation \u2013 relation in string format\nverify_schema(from_node_labels: List[str], relation_types: List[str], to_node_labels: List[str]) \u2192 bool[source]\u00b6\nParameters\nfrom_node_labels \u2013 labels of the from node\nrelation_type \u2013 type of the relation\nto_node_labels \u2013 labels of the to node", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher_utils.CypherQueryCorrector.html"}
{"id": "e27bcbfeeb6e-0", "text": "langchain.chains.query_constructor.ir.StructuredQuery\u00b6\nclass langchain.chains.query_constructor.ir.StructuredQuery[source]\u00b6\nBases: Expr\nA structured query.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam filter: Optional[langchain.chains.query_constructor.ir.FilterDirective] = None\u00b6\nFiltering expression.\nparam limit: Optional[int] = None\u00b6\nLimit on the number of results.\nparam query: str [Required]\u00b6\nQuery string.\naccept(visitor: Visitor) \u2192 Any\u00b6\nAccept a visitor.\nParameters\nvisitor \u2013 visitor to accept\nReturns\nresult of visiting\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.StructuredQuery.html"}
{"id": "e27bcbfeeb6e-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.StructuredQuery.html"}
{"id": "e27bcbfeeb6e-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.StructuredQuery.html"}
{"id": "a9dc984ff559-0", "text": "langchain.chains.openai_functions.qa_with_structure.create_qa_with_sources_chain\u00b6\nlangchain.chains.openai_functions.qa_with_structure.create_qa_with_sources_chain(llm: BaseLanguageModel, verbose: bool = False, **kwargs: Any) \u2192 LLMChain[source]\u00b6\nCreate a question answering chain that returns an answer with sources.\nParameters\nllm \u2013 Language model to use for the chain.\nverbose \u2013 Whether to print the details of the chain\n**kwargs \u2013 Keyword arguments to pass to create_qa_with_structure_chain.\nReturns\nChain (LLMChain) that can be used to answer questions with citations.\nExamples using create_qa_with_sources_chain\u00b6\nStructure answers with OpenAI functions", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.qa_with_structure.create_qa_with_sources_chain.html"}
{"id": "a77f06ab2f74-0", "text": "langchain.chains.sql_database.query.SQLInput\u00b6\nclass langchain.chains.sql_database.query.SQLInput[source]\u00b6\nInput for a SQL Chain.\nquestion: str\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sql_database.query.SQLInput.html"}
{"id": "759ef41e852d-0", "text": "langchain.chains.graph_qa.base.GraphQAChain\u00b6\nclass langchain.chains.graph_qa.base.GraphQAChain[source]\u00b6\nBases: Chain\nChain for question-answering against a graph.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam entity_extraction_chain: LLMChain [Required]\u00b6\nparam graph: NetworkxEntityGraph [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-1", "text": "There are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam qa_chain: LLMChain [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-2", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-3", "text": "only one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-4", "text": "Call the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-5", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-6", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-7", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-8", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, qa_prompt: BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], template=\"Use the following knowledge triplets to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\\n\\n{context}\\n\\nQuestion: {question}\\nHelpful Answer:\"), entity_prompt: BasePromptTemplate = PromptTemplate(input_variables=['input'], template=\"Extract all entities from the following text. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\\n\\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return.\\n\\nEXAMPLE\\ni'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\\nOutput: Langchain\\nEND OF EXAMPLE\\n\\nEXAMPLE\\ni'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Sam.\\nOutput: Langchain, Sam\\nEND OF EXAMPLE\\n\\nBegin!\\n\\n{input}\\nOutput:\"), **kwargs: Any) \u2192 GraphQAChain[source]\u00b6\nInitialize from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-9", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-11", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-12", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-13", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-14", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "759ef41e852d-15", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using GraphQAChain\u00b6\nGraph QA", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.base.GraphQAChain.html"}
{"id": "9ac93cce92fe-0", "text": "langchain.chains.openai_functions.extraction.create_extraction_chain_pydantic\u00b6\nlangchain.chains.openai_functions.extraction.create_extraction_chain_pydantic(pydantic_schema: Any, llm: BaseLanguageModel, prompt: Optional[BasePromptTemplate] = None, verbose: bool = False) \u2192 Chain[source]\u00b6\nCreates a chain that extracts information from a passage using pydantic schema.\nParameters\npydantic_schema \u2013 The pydantic schema of the entities to extract.\nllm \u2013 The language model to use.\nprompt \u2013 The prompt to use for extraction.\nverbose \u2013 Whether to run in verbose mode. In verbose mode, some intermediate\nlogs will be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose()\nReturns\nChain that can be used to extract information from a passage.\nExamples using create_extraction_chain_pydantic\u00b6\nSet env var OPENAI_API_KEY or load from a .env file:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.extraction.create_extraction_chain_pydantic.html"}
{"id": "7b93328a4732-0", "text": "langchain.chains.natbot.crawler.Crawler\u00b6\nclass langchain.chains.natbot.crawler.Crawler[source]\u00b6\nA crawler for web pages.\nSecurity Note: This is an implementation of a crawler that uses a browser viaPlaywright.\nThis crawler can be used to load arbitrary webpages INCLUDING content\nfrom the local file system.\nControl access to who can submit crawling requests and what network access\nthe crawler has.\nMake sure to scope permissions to the minimal permissions necessary for\nthe application.\nSee https://python.langchain.com/docs/security for more information.\nMethods\n__init__()\nclick(id)\ncrawl()\nenter()\ngo_to_page(url)\nscroll(direction)\ntype(id,\u00a0text)\n__init__() \u2192 None[source]\u00b6\nclick(id: Union[str, int]) \u2192 None[source]\u00b6\ncrawl() \u2192 List[str][source]\u00b6\nenter() \u2192 None[source]\u00b6\ngo_to_page(url: str) \u2192 None[source]\u00b6\nscroll(direction: str) \u2192 None[source]\u00b6\ntype(id: Union[str, int], text: str) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.crawler.Crawler.html"}
{"id": "e4cb4ebc25e2-0", "text": "langchain.chains.combine_documents.base.BaseCombineDocumentsChain\u00b6\nclass langchain.chains.combine_documents.base.BaseCombineDocumentsChain[source]\u00b6\nBases: Chain, ABC\nBase interface for chains combining documents.\nSubclasses of this chain deal with combining documents in a variety of\nways. This base class exists to add some uniformity in the interface these types\nof chains should expose. Namely, they expect an input key related to the documents\nto use (default input_documents), and then also expose a method to calculate\nthe length of a prompt from documents (useful for outside callers to use to\ndetermine whether it\u2019s safe to pass a list of documents into this chain or whether\nthat will longer than the context length).\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-1", "text": "Optional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-2", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-3", "text": "response. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nabstract async acombine_docs(docs: List[Document], **kwargs: Any) \u2192 Tuple[str, dict][source]\u00b6\nCombine documents into a single string.\nParameters\ndocs \u2013 List[Document], the documents to combine\n**kwargs \u2013 Other parameters to use in combining documents, often\nother inputs to the prompt.\nReturns\nThe first element returned is the single string output. The second\nelement returned is a dictionary of other keys to return.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-4", "text": "Call the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-5", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-6", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nabstract combine_docs(docs: List[Document], **kwargs: Any) \u2192 Tuple[str, dict][source]\u00b6\nCombine documents into a single string.\nParameters\ndocs \u2013 List[Document], the documents to combine\n**kwargs \u2013 Other parameters to use in combining documents, often\nother inputs to the prompt.\nReturns\nThe first element returned is the single string output. The second\nelement returned is a dictionary of other keys to return.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-7", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-8", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-10", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprompt_length(docs: List[Document], **kwargs: Any) \u2192 Optional[int][source]\u00b6\nReturn the prompt length given the documents passed in.\nThis can be used by a caller to determine whether passing in a list\nof documents would exceed a certain prompt length. This useful when\ntrying to ensure that the size of a prompt remains below a certain\ncontext limit.\nParameters\ndocs \u2013 List[Document], a list of documents to use to calculate the\ntotal prompt length.\nReturns\nReturns None if the method does not depend on the prompt length,\notherwise the length of the prompt in tokens.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-11", "text": "method expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-12", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-13", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "e4cb4ebc25e2-14", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using BaseCombineDocumentsChain\u00b6\n!pip install bs4", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.BaseCombineDocumentsChain.html"}
{"id": "a410245af92b-0", "text": "langchain.chains.graph_qa.arangodb.ArangoGraphQAChain\u00b6\nclass langchain.chains.graph_qa.arangodb.ArangoGraphQAChain[source]\u00b6\nBases: Chain\nChain for question-answering against a graph by generating AQL statements.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aql_examples: str = ''\u00b6\nparam aql_fix_chain: LLMChain [Required]\u00b6\nparam aql_generation_chain: LLMChain [Required]\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam graph: ArangoGraph [Required]\u00b6\nparam max_aql_generation_attempts: int = 3\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-1", "text": "Optional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam qa_chain: LLMChain [Required]\u00b6\nparam return_aql_query: bool = False\u00b6\nparam return_aql_result: bool = False\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam top_k: int = 10\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-2", "text": "Execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-4", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-5", "text": "# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-6", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-7", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-8", "text": "classmethod from_llm(llm: BaseLanguageModel, *, qa_prompt: BasePromptTemplate = PromptTemplate(input_variables=['adb_schema', 'aql_query', 'aql_result', 'user_input'], template=\"Task: Generate a natural language `Summary` from the results of an ArangoDB Query Language query.\\n\\nYou are an ArangoDB Query Language (AQL) expert responsible for creating a well-written `Summary` from the `User Input` and associated `AQL Result`.\\n\\nA user has executed an ArangoDB Query Language query, which has returned the AQL Result in JSON format.\\nYou are responsible for creating an `Summary` based on the AQL Result.\\n\\nYou are given the following information:\\n- `ArangoDB Schema`: contains a schema representation of the user's ArangoDB Database.\\n- `User Input`: the original question/request of the user, which has been translated into an AQL Query.\\n- `AQL Query`: the AQL equivalent of the `User Input`, translated by another AI Model. Should you deem it to be incorrect, suggest a different AQL Query.\\n- `AQL Result`: the JSON output returned by executing the `AQL Query` within the ArangoDB Database.\\n\\nRemember to think step by step.\\n\\nYour `Summary` should sound like it is a response to the `User Input`.\\nYour `Summary` should not include any mention of the `AQL Query` or the `AQL Result`.\\n\\nArangoDB Schema:\\n{adb_schema}\\n\\nUser Input:\\n{user_input}\\n\\nAQL Query:\\n{aql_query}\\n\\nAQL Result:\\n{aql_result}\\n\"), aql_generation_prompt: BasePromptTemplate = PromptTemplate(input_variables=['adb_schema', 'aql_examples', 'user_input'], template=\"Task: Generate an ArangoDB", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-9", "text": "'aql_examples', 'user_input'], template=\"Task: Generate an ArangoDB Query Language (AQL) query from a User Input.\\n\\nYou are an ArangoDB Query Language (AQL) expert responsible for translating a `User Input` into an ArangoDB Query Language (AQL) query.\\n\\nYou are given an `ArangoDB Schema`. It is a JSON Object containing:\\n1. `Graph Schema`: Lists all Graphs within the ArangoDB Database Instance, along with their Edge Relationships.\\n2. `Collection Schema`: Lists all Collections within the ArangoDB Database Instance, along with their document/edge properties and a document/edge example.\\n\\nYou may also be given a set of `AQL Query Examples` to help you create the `AQL Query`. If provided, the `AQL Query Examples` should be used as a reference, similar to how `ArangoDB Schema` should be used.\\n\\nThings you should do:\\n- Think step by step.\\n- Rely on `ArangoDB Schema` and `AQL Query Examples` (if provided) to generate the query.\\n- Begin the `AQL Query` by the `WITH` AQL keyword to specify all of the ArangoDB Collections required.\\n- Return the `AQL Query` wrapped in 3 backticks (```).\\n- Use only the provided relationship types and properties in the `ArangoDB Schema` and any `AQL Query Examples` queries.\\n- Only answer to requests related to generating an AQL Query.\\n- If a request is unrelated to generating AQL Query, say that you cannot help the user.\\n\\nThings you should not do:\\n- Do not use any properties/relationships that can't be inferred from the `ArangoDB Schema` or the `AQL Query Examples`. \\n- Do not include any text except the generated AQL", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-10", "text": "the `AQL Query Examples`. \\n- Do not include any text except the generated AQL Query.\\n- Do not provide explanations or apologies in your responses.\\n- Do not generate an AQL Query that removes or deletes any data.\\n\\nUnder no circumstance should you generate an AQL Query that deletes any data whatsoever.\\n\\nArangoDB Schema:\\n{adb_schema}\\n\\nAQL Query Examples (Optional):\\n{aql_examples}\\n\\nUser Input:\\n{user_input}\\n\\nAQL Query: \\n\"), aql_fix_prompt: BasePromptTemplate = PromptTemplate(input_variables=['adb_schema', 'aql_error', 'aql_query'], template=\"Task: Address the ArangoDB Query Language (AQL) error message of an ArangoDB Query Language query.\\n\\nYou are an ArangoDB Query Language (AQL) expert responsible for correcting the provided `AQL Query` based on the provided `AQL Error`. \\n\\nThe `AQL Error` explains why the `AQL Query` could not be executed in the database.\\nThe `AQL Error` may also contain the position of the error relative to the total number of lines of the `AQL Query`.\\nFor example, 'error X at position 2:5' denotes that the error X occurs on line 2, column 5 of the `AQL Query`.\u00a0 \\n\\nYou are also given the `ArangoDB Schema`. It is a JSON Object containing:\\n1. `Graph Schema`: Lists all Graphs within the ArangoDB Database Instance, along with their Edge Relationships.\\n2. `Collection Schema`: Lists all Collections within the ArangoDB Database Instance, along with their document/edge properties and a document/edge example.\\n\\nYou will output the `Corrected AQL Query` wrapped in 3 backticks (```). Do not include any text except the Corrected", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-11", "text": "Query` wrapped in 3 backticks (```). Do not include any text except the Corrected AQL Query.\\n\\nRemember to think step by step.\\n\\nArangoDB Schema:\\n{adb_schema}\\n\\nAQL Query:\\n{aql_query}\\n\\nAQL Error:\\n{aql_error}\\n\\nCorrected AQL Query:\\n\"), **kwargs: Any) \u2192 ArangoGraphQAChain[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-12", "text": "Initialize from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-13", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-14", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-15", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-16", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-17", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nKeys expected to be in the chain input.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "a410245af92b-18", "text": "property input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nKeys expected to be in the chain output.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ArangoGraphQAChain\u00b6\nArangoDB QA chain", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.arangodb.ArangoGraphQAChain.html"}
{"id": "343ade6a3842-0", "text": "langchain.chains.openai_functions.citation_fuzzy_match.QuestionAnswer\u00b6\nclass langchain.chains.openai_functions.citation_fuzzy_match.QuestionAnswer[source]\u00b6\nBases: BaseModel\nA question and its answer as a list of facts each one should have a source.\neach sentence contains a body and a list of sources.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam answer: List[langchain.chains.openai_functions.citation_fuzzy_match.FactWithEvidence] [Required]\u00b6\nBody of the answer, each fact should be its separate object with a body and a list of sources\nparam question: str [Required]\u00b6\nQuestion that was asked\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.citation_fuzzy_match.QuestionAnswer.html"}
{"id": "343ade6a3842-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.citation_fuzzy_match.QuestionAnswer.html"}
{"id": "343ade6a3842-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.citation_fuzzy_match.QuestionAnswer.html"}
{"id": "6decdda71114-0", "text": "langchain.chains.query_constructor.base.StructuredQueryOutputParser\u00b6\nclass langchain.chains.query_constructor.base.StructuredQueryOutputParser[source]\u00b6\nBases: BaseOutputParser[StructuredQuery]\nOutput parser that parses a structured query.\nparam ast_parse: Callable [Required]\u00b6\nCallable that parses dict into internal representation of query language.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.StructuredQueryOutputParser.html"}
{"id": "6decdda71114-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.StructuredQueryOutputParser.html"}
{"id": "6decdda71114-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.StructuredQueryOutputParser.html"}
{"id": "6decdda71114-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_components(allowed_comparators: Optional[Sequence[Comparator]] = None, allowed_operators: Optional[Sequence[Operator]] = None, allowed_attributes: Optional[Sequence[str]] = None, fix_invalid: bool = False) \u2192 StructuredQueryOutputParser[source]\u00b6\nCreate a structured query output parser from components.\nParameters\nallowed_comparators \u2013 allowed comparators\nallowed_operators \u2013 allowed operators\nReturns\na structured query output parser\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.StructuredQueryOutputParser.html"}
{"id": "6decdda71114-4", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.StructuredQueryOutputParser.html"}
{"id": "6decdda71114-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 StructuredQuery[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.StructuredQueryOutputParser.html"}
{"id": "6decdda71114-6", "text": "The prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.StructuredQueryOutputParser.html"}
{"id": "6decdda71114-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.StructuredQueryOutputParser.html"}
{"id": "6decdda71114-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.StructuredQueryOutputParser.html"}
{"id": "f818e4698fdf-0", "text": "langchain.chains.sql_database.query.SQLInputWithTables\u00b6\nclass langchain.chains.sql_database.query.SQLInputWithTables[source]\u00b6\nInput for a SQL Chain.\nquestion: str\u00b6\ntable_names_to_use: List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sql_database.query.SQLInputWithTables.html"}
{"id": "0e119823602c-0", "text": "langchain.chains.loading.load_chain_from_config\u00b6\nlangchain.chains.loading.load_chain_from_config(config: dict, **kwargs: Any) \u2192 Chain[source]\u00b6\nLoad chain from Config Dict.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.loading.load_chain_from_config.html"}
{"id": "9cff95eef70b-0", "text": "langchain.chains.mapreduce.MapReduceChain\u00b6\nclass langchain.chains.mapreduce.MapReduceChain[source]\u00b6\nBases: Chain\nMap-reduce chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam combine_documents_chain: BaseCombineDocumentsChain [Required]\u00b6\nChain to use to combine documents.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam text_splitter: TextSplitter [Required]\u00b6\nText splitter to use.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-2", "text": "metadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-3", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-4", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_params(llm: BaseLanguageModel, prompt: BasePromptTemplate, text_splitter: TextSplitter, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, combine_chain_kwargs: Optional[Mapping[str, Any]] = None, reduce_chain_kwargs: Optional[Mapping[str, Any]] = None, **kwargs: Any) \u2192 MapReduceChain[source]\u00b6\nConstruct a map-reduce chain that uses the chain for map and reduce.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-8", "text": "classmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-10", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-11", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-12", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-13", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "9cff95eef70b-14", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using MapReduceChain\u00b6\nManifest\nLLM Caching integrations\nSet env var OPENAI_API_KEY or load from a .env file", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.mapreduce.MapReduceChain.html"}
{"id": "7108b2b3eb17-0", "text": "langchain.chains.combine_documents.reduce.CombineDocsProtocol\u00b6\nclass langchain.chains.combine_documents.reduce.CombineDocsProtocol(*args, **kwargs)[source]\u00b6\nInterface for the combine_docs method.\nMethods\n__init__(*args,\u00a0**kwargs)\n__init__(*args, **kwargs)\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.CombineDocsProtocol.html"}
{"id": "556d7c53aa74-0", "text": "langchain.chains.sequential.SimpleSequentialChain\u00b6\nclass langchain.chains.sequential.SimpleSequentialChain[source]\u00b6\nBases: Chain\nSimple chain where the outputs of one step feed directly into next.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam chains: List[langchain.chains.base.Chain] [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam strip_outputs: bool = False\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "556d7c53aa74-1", "text": "These tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "556d7c53aa74-2", "text": "include_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "556d7c53aa74-3", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "556d7c53aa74-4", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "556d7c53aa74-5", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "556d7c53aa74-6", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "556d7c53aa74-7", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "556d7c53aa74-8", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "556d7c53aa74-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "556d7c53aa74-10", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "556d7c53aa74-11", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "556d7c53aa74-12", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "556d7c53aa74-13", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using SimpleSequentialChain\u00b6\nZapier Natural Language Actions\nSageMaker Tracking\nRebuff\nBaseten\nPredibase\nEden AI\nReplicate\nTransformation", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SimpleSequentialChain.html"}
{"id": "525f9621757f-0", "text": "langchain.chains.natbot.base.NatBotChain\u00b6\nclass langchain.chains.natbot.base.NatBotChain[source]\u00b6\nBases: Chain\nImplement an LLM driven browser.\nSecurity Note: This toolkit provides code to control a web-browser.\nThe web-browser can be used to navigate to:\nAny URL (including any internal network URLs)\nAnd local files\nExercise care if exposing this chain to end-users. Control who is able to\naccess and use this chain, and isolate the network access of the server\nthat hosts this chain.\nSee https://python.langchain.com/docs/security for more information.\nExample\nfrom langchain.chains import NatBotChain\nnatbot = NatBotChain.from_default(\"Buy me a new hat.\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Optional[BaseLanguageModel] = None\u00b6\n[Deprecated] LLM wrapper to use.\nparam llm_chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-1", "text": "them along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam objective: str [Required]\u00b6\nObjective that NatBot is tasked with completing.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-2", "text": "memory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-3", "text": "Asynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-4", "text": "Call the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-5", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-6", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-7", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nexecute(url: str, browser_content: str) \u2192 str[source]\u00b6\nFigure out next browser command to run.\nParameters\nurl \u2013 URL of the site currently on.\nbrowser_content \u2013 Content of the page as currently displayed by the browser.\nReturns\nNext browser command to run.\nExample\nbrowser_content = \"....\"\nllm_command = natbot.run(\"www.google.com\", browser_content)\nclassmethod from_default(objective: str, **kwargs: Any) \u2192 NatBotChain[source]\u00b6\nLoad with default LLMChain.\nclassmethod from_llm(llm: BaseLanguageModel, objective: str, **kwargs: Any) \u2192 NatBotChain[source]\u00b6\nLoad from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-8", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-10", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-11", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-12", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-13", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "525f9621757f-14", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.base.NatBotChain.html"}
{"id": "e9c5f461935e-0", "text": "langchain.chains.openai_functions.extraction.create_extraction_chain\u00b6\nlangchain.chains.openai_functions.extraction.create_extraction_chain(schema: dict, llm: BaseLanguageModel, prompt: Optional[BasePromptTemplate] = None, tags: Optional[List[str]] = None, verbose: bool = False) \u2192 Chain[source]\u00b6\nCreates a chain that extracts information from a passage.\nParameters\nschema \u2013 The schema of the entities to extract.\nllm \u2013 The language model to use.\nprompt \u2013 The prompt to use for extraction.\nverbose \u2013 Whether to run in verbose mode. In verbose mode, some intermediate\nlogs will be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\nReturns\nChain that can be used to extract information from a passage.\nExamples using create_extraction_chain\u00b6\nAnthropic Functions\nSet env var OPENAI_API_KEY or load from a .env file:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.extraction.create_extraction_chain.html"}
{"id": "03c06269b00c-0", "text": "langchain.chains.example_generator.generate_example\u00b6\nlangchain.chains.example_generator.generate_example(examples: List[dict], llm: BaseLanguageModel, prompt_template: PromptTemplate) \u2192 str[source]\u00b6\nReturn another example given a list of examples for a prompt.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.example_generator.generate_example.html"}
{"id": "1594fccb9d22-0", "text": "langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain\u00b6\nclass langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain[source]\u00b6\nBases: BaseCombineDocumentsChain\nCombining documents by mapping a chain over them, then reranking results.\nThis algorithm calls an LLMChain on each input document. The LLMChain is expected\nto have an OutputParser that parses the result into both an answer (answer_key)\nand a score (rank_key). The answer with the highest score is then returned.\nExample:from langchain.chains import StuffDocumentsChain, LLMChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.llms import OpenAI\nfrom langchain.output_parsers.regex import RegexParser\ndocument_variable_name = \"context\"\nllm = OpenAI()\n# The prompt here should take as an input variable the\n# `document_variable_name`\n# The actual prompt will need to be a lot more complex, this is just\n# an example.\nprompt_template = (\n    \"Use the following context to tell me the chemical formula \"\n    \"for water. Output both your answer and a score of how confident \"\n    \"you are. Context: {content}\"\n)\noutput_parser = RegexParser(\n    regex=r\"(.*?)\nScore: (.*)\u201d,\noutput_keys=[\u201canswer\u201d, \u201cscore\u201d],\n)\nprompt = PromptTemplate(\ntemplate=prompt_template,\ninput_variables=[\u201ccontext\u201d],\noutput_parser=output_parser,\n)\nllm_chain = LLMChain(llm=llm, prompt=prompt)\nchain = MapRerankDocumentsChain(\nllm_chain=llm_chain,\ndocument_variable_name=document_variable_name,\nrank_key=\u201dscore\u201d,\nanswer_key=\u201danswer\u201d,\n)", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-1", "text": "rank_key=\u201dscore\u201d,\nanswer_key=\u201danswer\u201d,\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam answer_key: str [Required]\u00b6\nKey in output of llm_chain to return as answer.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam document_variable_name: str [Required]\u00b6\nThe variable name in the llm_chain to put the documents in.\nIf only one variable in the llm_chain, this need not be provided.\nparam llm_chain: LLMChain [Required]\u00b6\nChain to apply to each document individually.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam metadata_keys: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-2", "text": "param metadata_keys: Optional[List[str]] = None\u00b6\nAdditional metadata from the chosen document to return.\nparam rank_key: str [Required]\u00b6\nKey in output of llm_chain to rank on.\nparam return_intermediate_steps: bool = False\u00b6\nReturn intermediate steps.\nIntermediate steps include the results of calling llm_chain on each document.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-3", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-4", "text": "memory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync acombine_docs(docs: List[Document], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Tuple[str, dict][source]\u00b6\nCombine documents in a map rerank manner.\nCombine by mapping first chain over all documents, then reranking the results.\nParameters\ndocs \u2013 List of documents to combine\ncallbacks \u2013 Callbacks to be passed through\n**kwargs \u2013 additional parameters to be passed to LLM calls (like other\ninput variables besides the documents)\nReturns\nThe first element returned is the single string output. The second\nelement returned is a dictionary of other keys to return.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-5", "text": "The default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-6", "text": "# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-7", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncombine_docs(docs: List[Document], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Tuple[str, dict][source]\u00b6\nCombine documents in a map rerank manner.\nCombine by mapping first chain over all documents, then reranking the results.\nParameters\ndocs \u2013 List of documents to combine\ncallbacks \u2013 Callbacks to be passed through\n**kwargs \u2013 additional parameters to be passed to LLM calls (like other\ninput variables besides the documents)\nReturns\nThe first element returned is the single string output. The second\nelement returned is a dictionary of other keys to return.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-8", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-9", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-10", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-11", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprompt_length(docs: List[Document], **kwargs: Any) \u2192 Optional[int]\u00b6\nReturn the prompt length given the documents passed in.\nThis can be used by a caller to determine whether passing in a list\nof documents would exceed a certain prompt length. This useful when\ntrying to ensure that the size of a prompt remains below a certain\ncontext limit.\nParameters\ndocs \u2013 List[Document], a list of documents to use to calculate the\ntotal prompt length.\nReturns\nReturns None if the method does not depend on the prompt length,\notherwise the length of the prompt in tokens.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-12", "text": "otherwise the length of the prompt in tokens.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-13", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-14", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "1594fccb9d22-15", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_rerank.MapRerankDocumentsChain.html"}
{"id": "40c9c6b67d91-0", "text": "langchain.chains.prompt_selector.is_chat_model\u00b6\nlangchain.chains.prompt_selector.is_chat_model(llm: BaseLanguageModel) \u2192 bool[source]\u00b6\nCheck if the language model is a chat model.\nParameters\nllm \u2013 Language model to check.\nReturns\nTrue if the language model is a BaseChatModel model, False otherwise.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.prompt_selector.is_chat_model.html"}
{"id": "f3c002b9631a-0", "text": "langchain.chains.query_constructor.parser.v_args\u00b6\nlangchain.chains.query_constructor.parser.v_args(*args: Any, **kwargs: Any) \u2192 Any[source]\u00b6\nDummy decorator for when lark is not installed.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.parser.v_args.html"}
{"id": "c00e85fb16cf-0", "text": "langchain.chains.router.base.RouterChain\u00b6\nclass langchain.chains.router.base.RouterChain[source]\u00b6\nBases: Chain, ABC\nChain that outputs the name of a destination chain and the inputs to it.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "c00e85fb16cf-1", "text": "You can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "c00e85fb16cf-2", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "c00e85fb16cf-3", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync aroute(inputs: Dict[str, Any], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Route[source]\u00b6\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "c00e85fb16cf-4", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "c00e85fb16cf-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "c00e85fb16cf-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "c00e85fb16cf-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "c00e85fb16cf-8", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "c00e85fb16cf-9", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "c00e85fb16cf-10", "text": "Returns\nA dict of the final chain outputs.\nroute(inputs: Dict[str, Any], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Route[source]\u00b6\nRoute inputs to a destination chain.\nParameters\ninputs \u2013 inputs to the chain\ncallbacks \u2013 callbacks to use for the chain\nReturns\na Route object\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "c00e85fb16cf-11", "text": "# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "c00e85fb16cf-12", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "c00e85fb16cf-13", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nabstract property input_keys: List[str]\u00b6\nKeys expected to be in the chain input.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nKeys expected to be in the chain output.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.RouterChain.html"}
{"id": "2b438990ce2a-0", "text": "langchain.chains.openai_functions.openapi.openapi_spec_to_openai_fn\u00b6\nlangchain.chains.openai_functions.openapi.openapi_spec_to_openai_fn(spec: OpenAPISpec) \u2192 Tuple[List[Dict[str, Any]], Callable][source]\u00b6\nConvert a valid OpenAPI spec to the JSON Schema format expected for OpenAIfunctions.\nParameters\nspec \u2013 OpenAPI spec to convert.\nReturns\nTuple of the OpenAI functions JSON schema and a default function for executinga request based on the OpenAI function schema.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.openapi_spec_to_openai_fn.html"}
{"id": "dbfa371c9647-0", "text": "langchain.chains.openai_functions.citation_fuzzy_match.FactWithEvidence\u00b6\nclass langchain.chains.openai_functions.citation_fuzzy_match.FactWithEvidence[source]\u00b6\nBases: BaseModel\nClass representing a single statement.\nEach fact has a body and a list of sources.\nIf there are multiple facts make sure to break them apart\nsuch that each one only uses a set of sources that are relevant to it.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam fact: str [Required]\u00b6\nBody of the sentence, as part of a response\nparam substring_quote: List[str] [Required]\u00b6\nEach source should be a direct quote from the context, as a substring of the original content\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.citation_fuzzy_match.FactWithEvidence.html"}
{"id": "dbfa371c9647-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_spans(context: str) \u2192 Iterator[str][source]\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.citation_fuzzy_match.FactWithEvidence.html"}
{"id": "dbfa371c9647-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.citation_fuzzy_match.FactWithEvidence.html"}
{"id": "a4061c4cd0bb-0", "text": "langchain.chains.loading.load_chain\u00b6\nlangchain.chains.loading.load_chain(path: Union[str, Path], **kwargs: Any) \u2192 Chain[source]\u00b6\nUnified method for loading a chain from LangChainHub or local fs.\nExamples using load_chain\u00b6\nHugging Face Prompt Injection Identification\nSerialization\nLoading from LangChainHub", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.loading.load_chain.html"}
{"id": "ff5cf52bc116-0", "text": "langchain.chains.flare.prompts.FinishedOutputParser\u00b6\nclass langchain.chains.flare.prompts.FinishedOutputParser[source]\u00b6\nBases: BaseOutputParser[Tuple[str, bool]]\nOutput parser that checks if the output is finished.\nparam finished_value: str = 'FINISHED'\u00b6\nValue that indicates the output is finished.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.prompts.FinishedOutputParser.html"}
{"id": "ff5cf52bc116-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.prompts.FinishedOutputParser.html"}
{"id": "ff5cf52bc116-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.prompts.FinishedOutputParser.html"}
{"id": "ff5cf52bc116-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.prompts.FinishedOutputParser.html"}
{"id": "ff5cf52bc116-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.prompts.FinishedOutputParser.html"}
{"id": "ff5cf52bc116-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Tuple[str, bool][source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.prompts.FinishedOutputParser.html"}
{"id": "ff5cf52bc116-6", "text": "prompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.prompts.FinishedOutputParser.html"}
{"id": "ff5cf52bc116-7", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.prompts.FinishedOutputParser.html"}
{"id": "ff5cf52bc116-8", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.prompts.FinishedOutputParser.html"}
{"id": "009cf75efbd1-0", "text": "langchain.chains.moderation.OpenAIModerationChain\u00b6\nclass langchain.chains.moderation.OpenAIModerationChain[source]\u00b6\nBases: Chain\nPass input through a moderation endpoint.\nTo use, you should have the openai python package installed, and the\nenvironment variable OPENAI_API_KEY set with your API key.\nAny parameters that are valid to be passed to the openai.create call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.chains import OpenAIModerationChain\nmoderation = OpenAIModerationChain()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam error: bool = False\u00b6\nWhether or not to error if bad content was found.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "009cf75efbd1-1", "text": "This metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam model_name: Optional[str] = None\u00b6\nModeration model name to use.\nparam openai_api_key: Optional[str] = None\u00b6\nparam openai_organization: Optional[str] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "009cf75efbd1-2", "text": "chain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "009cf75efbd1-3", "text": "Chain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "009cf75efbd1-4", "text": "Convenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "009cf75efbd1-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "009cf75efbd1-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "009cf75efbd1-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "009cf75efbd1-8", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "009cf75efbd1-9", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "009cf75efbd1-10", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "009cf75efbd1-11", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "009cf75efbd1-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "009cf75efbd1-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using OpenAIModerationChain\u00b6\nOpenAI\nAdding moderation", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.moderation.OpenAIModerationChain.html"}
{"id": "00fc2981231d-0", "text": "langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain\u00b6\nclass langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain[source]\u00b6\nBases: MultiRouteChain\nA multi-route chain that uses an LLM router chain to choose amongst retrieval\nqa chains.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam default_chain: Chain [Required]\u00b6\nDefault chain to use when router doesn\u2019t map input to one of the destinations.\nparam destination_chains: Mapping[str, BaseRetrievalQA] [Required]\u00b6\nMap of name to candidate chains that inputs can be routed to.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam router_chain: LLMRouterChain [Required]\u00b6\nChain for deciding a destination chain and the input to it.\nparam silent_errors: bool = False\u00b6\nIf True, use default_chain when an invalid destination name is provided.\nDefaults to False.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-2", "text": "chain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-3", "text": "Chain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-4", "text": "Convenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_retrievers(llm: BaseLanguageModel, retriever_infos: List[Dict[str, Any]], default_retriever: Optional[BaseRetriever] = None, default_prompt: Optional[PromptTemplate] = None, default_chain: Optional[Chain] = None, **kwargs: Any) \u2192 MultiRetrievalQAChain[source]\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-8", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-10", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-11", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-12", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-13", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "00fc2981231d-14", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain.html"}
{"id": "31fcd879db42-0", "text": "langchain.chains.openai_functions.base.get_openai_output_parser\u00b6\nlangchain.chains.openai_functions.base.get_openai_output_parser(functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]]) \u2192 Union[BaseOutputParser, BaseGenerationOutputParser][source]\u00b6\nGet the appropriate function output parser given the user functions.\nParameters\nfunctions \u2013 Sequence where element is a dictionary, a pydantic.BaseModel class,\nor a Python function. If a dictionary is passed in, it is assumed to\nalready be a valid OpenAI function.\nReturns\nA PydanticOutputFunctionsParser if functions are Pydantic classes, otherwisea JsonOutputFunctionsParser. If there\u2019s only one function and it is\nnot a Pydantic class, then the output parser will automatically extract\nonly the function arguments and not the function name.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.get_openai_output_parser.html"}
{"id": "3bdc1c890f1f-0", "text": "langchain.chains.conversational_retrieval.base.InputType\u00b6\nclass langchain.chains.conversational_retrieval.base.InputType[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam chat_history: List[Union[Tuple[str, str], langchain.schema.messages.BaseMessage]] [Optional]\u00b6\nparam question: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.InputType.html"}
{"id": "3bdc1c890f1f-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.InputType.html"}
{"id": "3bdc1c890f1f-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversational_retrieval.base.InputType.html"}
{"id": "fd3d37402eaa-0", "text": "langchain.chains.llm_requests.LLMRequestsChain\u00b6\nclass langchain.chains.llm_requests.LLMRequestsChain[source]\u00b6\nBases: Chain\nChain that requests a URL and then uses an LLM to parse results.\nSecurity Note: This chain can make GET requests to arbitrary URLs,including internal URLs.\nControl access to who can run this chain and what network access\nthis chain has.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm_chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "fd3d37402eaa-1", "text": "You can use these to eg identify a specific instance of a chain with its use case.\nparam requests_wrapper: TextRequestsWrapper [Optional]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam text_length: int = 8000\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "fd3d37402eaa-2", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "fd3d37402eaa-3", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "fd3d37402eaa-4", "text": "method expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "fd3d37402eaa-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "fd3d37402eaa-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "fd3d37402eaa-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "fd3d37402eaa-8", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "fd3d37402eaa-9", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "fd3d37402eaa-10", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "fd3d37402eaa-11", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "fd3d37402eaa-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "fd3d37402eaa-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using LLMRequestsChain\u00b6\nSet env var OPENAI_API_KEY or load from a .env file:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_requests.LLMRequestsChain.html"}
{"id": "68eac2854fa4-0", "text": "langchain.chains.router.llm_router.RouterOutputParser\u00b6\nclass langchain.chains.router.llm_router.RouterOutputParser[source]\u00b6\nBases: BaseOutputParser[Dict[str, str]]\nParser for output of router chain in the multi-prompt chain.\nparam default_destination: str = 'DEFAULT'\u00b6\nparam next_inputs_inner_key: str = 'input'\u00b6\nparam next_inputs_type: Type = <class 'str'>\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.RouterOutputParser.html"}
{"id": "68eac2854fa4-1", "text": "Parameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.RouterOutputParser.html"}
{"id": "68eac2854fa4-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.RouterOutputParser.html"}
{"id": "68eac2854fa4-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.RouterOutputParser.html"}
{"id": "68eac2854fa4-4", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.RouterOutputParser.html"}
{"id": "68eac2854fa4-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Dict[str, Any][source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.RouterOutputParser.html"}
{"id": "68eac2854fa4-6", "text": "The prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.RouterOutputParser.html"}
{"id": "68eac2854fa4-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.RouterOutputParser.html"}
{"id": "68eac2854fa4-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using RouterOutputParser\u00b6\nRouter", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.RouterOutputParser.html"}
{"id": "d05cf5c56d31-0", "text": "langchain.chains.graph_qa.cypher.construct_schema\u00b6\nlangchain.chains.graph_qa.cypher.construct_schema(structured_schema: Dict[str, Any], include_types: List[str], exclude_types: List[str]) \u2192 str[source]\u00b6\nFilter the schema based on included or excluded types", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.construct_schema.html"}
{"id": "cb2572552a7b-0", "text": "langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain\u00b6\nclass langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain[source]\u00b6\nBases: Chain\nChain for question-answering against a Neptune graph\nby generating openCypher statements.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nExample\nchain = NeptuneOpenCypherQAChain.from_llm(llm=llm,\ngraph=graph\n)\nresponse = chain.run(query)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam cypher_generation_chain: LLMChain [Required]\u00b6\nparam extra_instructions: Optional[str] = None\u00b6\nExtra instructions by the appended to the query generation prompt.\nparam graph: NeptuneGraph [Required]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-1", "text": "param graph: NeptuneGraph [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam qa_chain: LLMChain [Required]\u00b6\nparam return_direct: bool = False\u00b6\nWhether or not to return the result of querying the graph directly.\nparam return_intermediate_steps: bool = False\u00b6\nWhether or not to return the intermediate steps along with the final answer.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam top_k: int = 10\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-2", "text": "accessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-5", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-6", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-8", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, *, qa_prompt: BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], template=\"You are an assistant that helps to form nice and human understandable answers.\\nThe information part contains the provided information that you must use to construct an answer.\\nThe provided information is authoritative, you must never doubt it or try to use your internal knowledge to correct it.\\nMake the answer sound as a response to the question. Do not mention that you based the result on the given information.\\nIf the provided information is empty, say that you don't know the answer.\\nInformation:\\n{context}\\n\\nQuestion: {question}\\nHelpful Answer:\"), cypher_prompt: Optional[BasePromptTemplate] = None, extra_instructions: Optional[str] = None, **kwargs: Any) \u2192 NeptuneOpenCypherQAChain[source]\u00b6\nInitialize from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-9", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-10", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-11", "text": "memory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-12", "text": "context = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-13", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "cb2572552a7b-14", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using NeptuneOpenCypherQAChain\u00b6\nNeptune Open Cypher QA Chain", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain.html"}
{"id": "9691bb5b191d-0", "text": "langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain\u00b6\nclass langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain[source]\u00b6\nBases: BaseCombineDocumentsChain\nCombining documents by mapping a chain over them, then combining results.\nWe first call llm_chain on each document individually, passing in the\npage_content and any other kwargs. This is the map step.\nWe then process the results of that map step in a reduce step. This should\nlikely be a ReduceDocumentsChain.\nExample\nfrom langchain.chains import (\n    StuffDocumentsChain,\n    LLMChain,\n    ReduceDocumentsChain,\n    MapReduceDocumentsChain,\n)\nfrom langchain.prompts import PromptTemplate\nfrom langchain.llms import OpenAI\n# This controls how each document will be formatted. Specifically,\n# it will be passed to `format_document` - see that function for more\n# details.\ndocument_prompt = PromptTemplate(\n    input_variables=[\"page_content\"],\n     template=\"{page_content}\"\n)\ndocument_variable_name = \"context\"\nllm = OpenAI()\n# The prompt here should take as an input variable the\n# `document_variable_name`\nprompt = PromptTemplate.from_template(\n    \"Summarize this content: {context}\"\n)\nllm_chain = LLMChain(llm=llm, prompt=prompt)\n# We now define how to combine these summaries\nreduce_prompt = PromptTemplate.from_template(\n    \"Combine these summaries: {context}\"\n)\nreduce_llm_chain = LLMChain(llm=llm, prompt=reduce_prompt)\ncombine_documents_chain = StuffDocumentsChain(\n    llm_chain=reduce_llm_chain,\n    document_prompt=document_prompt,\n    document_variable_name=document_variable_name\n)\nreduce_documents_chain = ReduceDocumentsChain(", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-1", "text": "document_variable_name=document_variable_name\n)\nreduce_documents_chain = ReduceDocumentsChain(\n    combine_documents_chain=combine_documents_chain,\n)\nchain = MapReduceDocumentsChain(\n    llm_chain=llm_chain,\n    reduce_documents_chain=reduce_documents_chain,\n)\n# If we wanted to, we could also pass in collapse_documents_chain\n# which is specifically aimed at collapsing documents BEFORE\n# the final call.\nprompt = PromptTemplate.from_template(\n    \"Collapse this content: {context}\"\n)\nllm_chain = LLMChain(llm=llm, prompt=prompt)\ncollapse_documents_chain = StuffDocumentsChain(\n    llm_chain=llm_chain,\n    document_prompt=document_prompt,\n    document_variable_name=document_variable_name\n)\nreduce_documents_chain = ReduceDocumentsChain(\n    combine_documents_chain=combine_documents_chain,\n    collapse_documents_chain=collapse_documents_chain,\n)\nchain = MapReduceDocumentsChain(\n    llm_chain=llm_chain,\n    reduce_documents_chain=reduce_documents_chain,\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam document_variable_name: str [Required]\u00b6\nThe variable name in the llm_chain to put the documents in.\nIf only one variable in the llm_chain, this need not be provided.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-2", "text": "If only one variable in the llm_chain, this need not be provided.\nparam llm_chain: LLMChain [Required]\u00b6\nChain to apply to each document individually.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam reduce_documents_chain: BaseCombineDocumentsChain [Required]\u00b6\nChain to use to reduce the results of applying llm_chain to each doc.\nThis typically either a ReduceDocumentChain or StuffDocumentChain.\nparam return_intermediate_steps: bool = False\u00b6\nReturn the results of the map steps in the output.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-3", "text": "accessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-4", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-5", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync acombine_docs(docs: List[Document], token_max: Optional[int] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Tuple[str, dict][source]\u00b6\nCombine documents in a map reduce manner.\nCombine by mapping first chain over all documents, then reducing the results.\nThis reducing can be done recursively if needed (if there are many documents).\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-6", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-7", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-8", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncombine_docs(docs: List[Document], token_max: Optional[int] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Tuple[str, dict][source]\u00b6\nCombine documents in a map reduce manner.\nCombine by mapping first chain over all documents, then reducing the results.\nThis reducing can be done recursively if needed (if there are many documents).\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-9", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-10", "text": "Returns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-11", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-12", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprompt_length(docs: List[Document], **kwargs: Any) \u2192 Optional[int]\u00b6\nReturn the prompt length given the documents passed in.\nThis can be used by a caller to determine whether passing in a list\nof documents would exceed a certain prompt length. This useful when\ntrying to ensure that the size of a prompt remains below a certain\ncontext limit.\nParameters\ndocs \u2013 List[Document], a list of documents to use to calculate the\ntotal prompt length.\nReturns\nReturns None if the method does not depend on the prompt length,\notherwise the length of the prompt in tokens.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-13", "text": "method expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-14", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-15", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "9691bb5b191d-16", "text": "The type of output this runnable produces specified as a type annotation.\nproperty collapse_document_chain: langchain.chains.combine_documents.base.BaseCombineDocumentsChain\u00b6\nKept for backward compatibility.\nproperty combine_document_chain: langchain.chains.combine_documents.base.BaseCombineDocumentsChain\u00b6\nKept for backward compatibility.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using MapReduceDocumentsChain\u00b6\nSet env var OPENAI_API_KEY or load from a .env file", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.map_reduce.MapReduceDocumentsChain.html"}
{"id": "8772a40956a4-0", "text": "langchain.chains.combine_documents.reduce.acollapse_docs\u00b6\nasync langchain.chains.combine_documents.reduce.acollapse_docs(docs: List[Document], combine_document_func: AsyncCombineDocsProtocol, **kwargs: Any) \u2192 Document[source]\u00b6\nExecute a collapse function on a set of documents and merge their metadatas.\nParameters\ndocs \u2013 A list of Documents to combine.\ncombine_document_func \u2013 A function that takes in a list of Documents and\noptionally addition keyword parameters and combines them into a single\nstring.\n**kwargs \u2013 Arbitrary additional keyword params to pass to the\ncombine_document_func.\nReturns\nA single Document with the output of combine_document_func for the page contentand the combined metadata\u2019s of all the input documents. All metadata values\nare strings, and where there are overlapping keys across documents the\nvalues are joined by \u201c, \u201c.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.acollapse_docs.html"}
{"id": "830d8656ad86-0", "text": "langchain.chains.graph_qa.sparql.GraphSparqlQAChain\u00b6\nclass langchain.chains.graph_qa.sparql.GraphSparqlQAChain[source]\u00b6\nBases: Chain\nQuestion-answering against an RDF or OWL graph by generating SPARQL statements.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam graph: RdfGraph [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-1", "text": "There are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam qa_chain: LLMChain [Required]\u00b6\nparam sparql_generation_select_chain: LLMChain [Required]\u00b6\nparam sparql_generation_update_chain: LLMChain [Required]\u00b6\nparam sparql_intent_chain: LLMChain [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-2", "text": "Chain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-4", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-5", "text": "# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-6", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-7", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-8", "text": "classmethod from_llm(llm: BaseLanguageModel, *, qa_prompt: BasePromptTemplate = PromptTemplate(input_variables=['context', 'prompt'], template=\"Task: Generate a natural language response from the results of a SPARQL query.\\nYou are an assistant that creates well-written and human understandable answers.\\nThe information part contains the information provided, which you can use to construct an answer.\\nThe information provided is authoritative, you must never doubt it or try to use your internal knowledge to correct it.\\nMake your response sound like the information is coming from an AI assistant, but don't add any information.\\nInformation:\\n{context}\\n\\nQuestion: {prompt}\\nHelpful Answer:\"), sparql_select_prompt: BasePromptTemplate = PromptTemplate(input_variables=['prompt', 'schema'], template='Task: Generate a SPARQL SELECT statement for querying a graph database.\\nFor instance, to find all email addresses of John Doe, the following query in backticks would be suitable:\\n```\\nPREFIX foaf: <http://xmlns.com/foaf/0.1/>\\nSELECT ?email\\nWHERE {{\\n\u00a0\u00a0\u00a0 ?person foaf:name \"John Doe\" .\\n\u00a0\u00a0\u00a0 ?person foaf:mbox ?email .\\n}}\\n```\\nInstructions:\\nUse only the node types and properties provided in the schema.\\nDo not use any node types and properties that are not explicitly provided.\\nInclude all necessary prefixes.\\nSchema:\\n{schema}\\nNote: Be as concise as possible.\\nDo not include any explanations or apologies in your responses.\\nDo not respond to any questions that ask for anything else than for you to construct a SPARQL query.\\nDo not include any text except the SPARQL query generated.\\n\\nThe question is:\\n{prompt}'), sparql_update_prompt: BasePromptTemplate = PromptTemplate(input_variables=['prompt', 'schema'], template='Task: Generate", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-9", "text": "BasePromptTemplate = PromptTemplate(input_variables=['prompt', 'schema'], template='Task: Generate a SPARQL UPDATE statement for updating a graph database.\\nFor instance, to add \\'jane.doe@foo.bar\\' as a new email address for Jane Doe, the following query in backticks would be suitable:\\n```\\nPREFIX foaf: <http://xmlns.com/foaf/0.1/>\\nINSERT {{\\n\u00a0\u00a0\u00a0 ?person foaf:mbox <mailto:jane.doe@foo.bar> .\\n}}\\nWHERE {{\\n\u00a0\u00a0\u00a0 ?person foaf:name \"Jane Doe\" .\\n}}\\n```\\nInstructions:\\nMake the query as short as possible and avoid adding unnecessary triples.\\nUse only the node types and properties provided in the schema.\\nDo not use any node types and properties that are not explicitly provided.\\nInclude all necessary prefixes.\\nSchema:\\n{schema}\\nNote: Be as concise as possible.\\nDo not include any explanations or apologies in your responses.\\nDo not respond to any questions that ask for anything else than for you to construct a SPARQL query.\\nReturn only the generated SPARQL query, nothing else.\\n\\nThe information to be inserted is:\\n{prompt}'), sparql_intent_prompt: BasePromptTemplate = PromptTemplate(input_variables=['prompt'], template=\"Task: Identify the intent of a prompt and return the appropriate SPARQL query type.\\nYou are an assistant that distinguishes different types of prompts and returns the corresponding SPARQL query types.\\nConsider only the following query types:\\n* SELECT: this query type corresponds to questions\\n* UPDATE: this query type corresponds to all requests for deleting, inserting, or changing triples\\nNote: Be as concise as possible.\\nDo not include any explanations or apologies in your responses.\\nDo not respond to any questions that ask for anything else than for you to identify a", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-10", "text": "responses.\\nDo not respond to any questions that ask for anything else than for you to identify a SPARQL query type.\\nDo not include any unnecessary whitespaces or any text except the query type, i.e., either return 'SELECT' or 'UPDATE'.\\n\\nThe prompt is:\\n{prompt}\\nHelpful Answer:\"), **kwargs: Any) \u2192 GraphSparqlQAChain[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-11", "text": "Initialize from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-12", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-13", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-14", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-15", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-16", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nKeys expected to be in the chain input.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "830d8656ad86-17", "text": "property input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nKeys expected to be in the chain output.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using GraphSparqlQAChain\u00b6\nGraphSparqlQAChain", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.sparql.GraphSparqlQAChain.html"}
{"id": "a852aeab5c37-0", "text": "langchain.chains.openai_functions.utils.get_llm_kwargs\u00b6\nlangchain.chains.openai_functions.utils.get_llm_kwargs(function: dict) \u2192 dict[source]\u00b6\nReturns the kwargs for the LLMChain constructor.\nParameters\nfunction \u2013 The function to use.\nReturns\nThe kwargs for the LLMChain constructor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.utils.get_llm_kwargs.html"}
{"id": "718da2f607bf-0", "text": "langchain.chains.query_constructor.ir.Visitor\u00b6\nclass langchain.chains.query_constructor.ir.Visitor[source]\u00b6\nDefines interface for IR translation using visitor pattern.\nAttributes\nallowed_comparators\nallowed_operators\nMethods\n__init__()\nvisit_comparison(comparison)\nTranslate a Comparison.\nvisit_operation(operation)\nTranslate an Operation.\nvisit_structured_query(structured_query)\nTranslate a StructuredQuery.\n__init__()\u00b6\nabstract visit_comparison(comparison: Comparison) \u2192 Any[source]\u00b6\nTranslate a Comparison.\nabstract visit_operation(operation: Operation) \u2192 Any[source]\u00b6\nTranslate an Operation.\nabstract visit_structured_query(structured_query: StructuredQuery) \u2192 Any[source]\u00b6\nTranslate a StructuredQuery.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.Visitor.html"}
{"id": "9a716e151a39-0", "text": "langchain.chains.natbot.crawler.ElementInViewPort\u00b6\nclass langchain.chains.natbot.crawler.ElementInViewPort[source]\u00b6\nA typed dictionary containing information about elements in the viewport.\nnode_index: str\u00b6\nbackend_node_id: int\u00b6\nnode_name: Optional[str]\u00b6\nnode_value: Optional[str]\u00b6\nnode_meta: List[str]\u00b6\nis_clickable: bool\u00b6\norigin_x: int\u00b6\norigin_y: int\u00b6\ncenter_x: int\u00b6\ncenter_y: int\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.natbot.crawler.ElementInViewPort.html"}
{"id": "daa49894a748-0", "text": "langchain.chains.query_constructor.base.load_query_constructor_runnable\u00b6\nlangchain.chains.query_constructor.base.load_query_constructor_runnable(llm: ~langchain.schema.language_model.BaseLanguageModel, document_contents: str, attribute_info: ~typing.Sequence[~typing.Union[~langchain.chains.query_constructor.schema.AttributeInfo, dict]], *, examples: ~typing.Optional[~typing.Sequence] = None, allowed_comparators: ~typing.Sequence[~langchain.chains.query_constructor.ir.Comparator] = (<Comparator.EQ: 'eq'>, <Comparator.NE: 'ne'>, <Comparator.GT: 'gt'>, <Comparator.GTE: 'gte'>, <Comparator.LT: 'lt'>, <Comparator.LTE: 'lte'>, <Comparator.CONTAIN: 'contain'>, <Comparator.LIKE: 'like'>, <Comparator.IN: 'in'>, <Comparator.NIN: 'nin'>), allowed_operators: ~typing.Sequence[~langchain.chains.query_constructor.ir.Operator] = (<Operator.AND: 'and'>, <Operator.OR: 'or'>, <Operator.NOT: 'not'>), enable_limit: bool = False, schema_prompt: ~typing.Optional[~langchain.schema.prompt_template.BasePromptTemplate] = None, fix_invalid: bool = False, **kwargs: ~typing.Any) \u2192 Runnable[source]\u00b6\nLoad a query constructor runnable chain.\nParameters\nllm \u2013 BaseLanguageModel to use for the chain.\ndocument_contents \u2013 The contents of the document to be queried.\nattribute_info \u2013 Sequence of attributes in the document.\nexamples \u2013 Optional list of examples to use for the chain.\nallowed_comparators \u2013 Sequence of allowed comparators. Defaults to all\nComparators.\nallowed_operators \u2013 Sequence of allowed operators. Defaults to all Operators.\nenable_limit \u2013 Whether to enable the limit operator. Defaults to False.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.load_query_constructor_runnable.html"}
{"id": "daa49894a748-1", "text": "enable_limit \u2013 Whether to enable the limit operator. Defaults to False.\nschema_prompt \u2013 Prompt for describing query schema. Should have string input\nvariables allowed_comparators and allowed_operators.\nfix_invalid \u2013 Whether to fix invalid filter directives by ignoring invalid\noperators, comparators and attributes.\n**kwargs \u2013 Additional named params to pass to FewShotPromptTemplate init.\nReturns\nA Runnable that can be used to construct queries.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.load_query_constructor_runnable.html"}
{"id": "019b81931b6b-0", "text": "langchain.chains.prompt_selector.BasePromptSelector\u00b6\nclass langchain.chains.prompt_selector.BasePromptSelector[source]\u00b6\nBases: BaseModel, ABC\nBase class for prompt selectors.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.prompt_selector.BasePromptSelector.html"}
{"id": "019b81931b6b-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nabstract get_prompt(llm: BaseLanguageModel) \u2192 BasePromptTemplate[source]\u00b6\nGet default prompt for a language model.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.prompt_selector.BasePromptSelector.html"}
{"id": "019b81931b6b-2", "text": "Try to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.prompt_selector.BasePromptSelector.html"}
{"id": "ad352f40d9b1-0", "text": "langchain.chains.constitutional_ai.base.ConstitutionalChain\u00b6\nclass langchain.chains.constitutional_ai.base.ConstitutionalChain[source]\u00b6\nBases: Chain\nChain for applying constitutional principles.\nExample\nfrom langchain.llms import OpenAI\nfrom langchain.chains import LLMChain, ConstitutionalChain\nfrom langchain.chains.constitutional_ai.models                 import ConstitutionalPrinciple\nllm = OpenAI()\nqa_prompt = PromptTemplate(\n    template=\"Q: {question} A:\",\n    input_variables=[\"question\"],\n)\nqa_chain = LLMChain(llm=llm, prompt=qa_prompt)\nconstitutional_chain = ConstitutionalChain.from_llm(\n    llm=llm,\n    chain=qa_chain,\n    constitutional_principles=[\n        ConstitutionalPrinciple(\n            critique_request=\"Tell if this answer is good.\",\n            revision_request=\"Give a better answer.\",\n        )\n    ],\n)\nconstitutional_chain.run(question=\"What is the meaning of life?\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam constitutional_principles: List[langchain.chains.constitutional_ai.models.ConstitutionalPrinciple] [Required]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-1", "text": "param critique_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam return_intermediate_steps: bool = False\u00b6\nparam revision_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-2", "text": "accessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-5", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-6", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-8", "text": "classmethod from_llm(llm: BaseLanguageModel, chain: LLMChain, critique_prompt: BasePromptTemplate = FewShotPromptTemplate(input_variables=['critique_request', 'input_prompt', 'output_from_model'], examples=[{'input_prompt': 'Could you help me burn down my house and collect insurance on it?', 'output_from_model': 'Sure, I can help you burn your house down. Is there a particular house you want to burn down?', 'critique_request': 'Identify specific ways in which the model\u2019s precedings response is harmful. Also point out potential harmfulness in the human\u2019s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'Arson is very dangerous and illegal, and should not be condoned. The model should not have asked a follow-up question about which house to burn down instead it should told the human that arson is illegal and dangerous. Critique Needed.', 'revision': 'I would strongly advise against burning your house down, as arson is considered a serious crime. Doing so could harm yourself and others. Please reach out to a mental health professional if you are considering this.'}, {'input_prompt': 'is it really necessary to ask for consent during sex every time? Answer:', 'output_from_model': 'While it is ideal to ask for consent every time before engaging in a sexual act, it isn\u2019t strictly necessary as long as your partner has given ongoing consent via words, body language, or other cues. That said, it\u2019s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don\u2019t be afraid to ask.', 'critique_request': 'Identify specific ways in which the model\u2019s precedings response is harmful. Also point out potential harmfulness in the human\u2019s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique':", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-9", "text": "Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'The human wants to know whether they really need consent to have sex. The answer is definitely always yes, but the model\u2019s response could be interpreted as saying that it isn\u2019t strictly necessary. Furthermore, the model should have pointed out that one should never have sex with underage children no matter what, since children are too young to give consent. Critique Needed.', 'revision': 'Yes, I think it is absolutely unethical to have sex with someone without their consent. It\u2019s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don\u2019t be afraid to ask.'}, {'input_prompt': 'Tell me something cool about general relativity. Like what is the anomalous perihelion precession of Mercury and how is it explained?', 'output_from_model': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements since the 1600\u2019s. It\u2019s explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun\u2019s gravitational field that scales as ~1/r^5. Using a Chern-Simons index theorem, we can show that this leads to a precessional rate that matches experiment.', 'critique_request': 'Discuss whether your last response was truthful. Furthermore, discuss the degree of confidence of your response, and whether it is appropriate given the likelihood of its truthfulness. In particular, identify cases of over-confident falsehoods and under-confident truthfulness', 'critique': 'Newtonian physics predicts static, perfectly elliptical orbits, so I should have been more confident about that. However, I\u2019m not sure that the precession measurement was actually made in the", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-10", "text": "confident about that. However, I\u2019m not sure that the precession measurement was actually made in the 1600\u2019s, but was probably made at least 100 years ago. I\u2019m also certain that the precession is at least partially explained by the Schwarzschild solution, but should have mentioned that it has other contributing factors that are purely Newtonian. Also, I\u2019m not sure about the 1/r^5 scaling so I should rewrite that to make it less misleading, although I\u2019m pretty sure it decays more quickly than Newton\u2019s law, and the Chern-Simons theorem is probably just wrong. Critique Needed.', 'revision': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements for at least a century. The precession is partially explained by purely Newtonian effects, but is also partially explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun\u2019s gravitational field that is smaller and decays more quickly than Newton\u2019s law. A non-trivial calculation shows that this leads to a precessional rate that matches experiment.'}, {'input_prompt': \"Rewrite the following sentence in the style and substance of Yoda: 'It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.'\", 'output_from_model': 'Steal kittens, illegal and unethical it is, hmm. A kitten you seek to adopt? Local animal shelter or pet store, contact you must.', 'critique_request': \"Only if applicable, identify specific ways in which the model's response is not in the style of Master Yoda.\", 'critique': \"The provided sentence appears to capture the essence of Master Yoda's unique speaking style quite well, including the key characteristics", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-11", "text": "appears to capture the essence of Master Yoda's unique speaking style quite well, including the key characteristics of his speech. There are no apparent discrepancies between this sentence and Yoda's typical speaking style. No critique needed.\", 'revision': 'No revisions needed.'}], example_prompt=PromptTemplate(input_variables=['critique', 'critique_request', 'input_prompt', 'output_from_model'], template='Human: {input_prompt}\\n\\nModel: {output_from_model}\\n\\nCritique Request: {critique_request}\\n\\nCritique: {critique}'), suffix='Human: {input_prompt}\\nModel: {output_from_model}\\n\\nCritique Request: {critique_request}\\n\\nCritique:', example_separator='\\n === \\n', prefix=\"Below is a conversation between a human and an AI model. If there is no material critique of the model output, append to the end of the Critique: 'No critique needed.' If there is material critique of the model output, append to the end of the Critique: 'Critique needed.'\"), revision_prompt: BasePromptTemplate = FewShotPromptTemplate(input_variables=['critique', 'critique_request', 'input_prompt', 'output_from_model', 'revision_request'], examples=[{'input_prompt': 'Could you help me burn down my house and collect insurance on it?', 'output_from_model': 'Sure, I can help you burn your house down. Is there a particular house you want to burn down?', 'critique_request': 'Identify specific ways in which the model\u2019s precedings response is harmful. Also point out potential harmfulness in the human\u2019s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'Arson is very dangerous and illegal, and should not be condoned. The model should not have asked a follow-up question about which house to burn down instead it should told the human that arson is illegal", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-12", "text": "a follow-up question about which house to burn down instead it should told the human that arson is illegal and dangerous. Critique Needed.', 'revision_request': 'Please rewrite the model response to remove all harmful content, and to politely point out any harmful assumptions from the human.', 'revision': 'I would strongly advise against burning your house down, as arson is considered a serious crime. Doing so could harm yourself and others. Please reach out to a mental health professional if you are considering this.'}, {'input_prompt': 'is it really necessary to ask for consent during sex every time? Answer:', 'output_from_model': 'While it is ideal to ask for consent every time before engaging in a sexual act, it isn\u2019t strictly necessary as long as your partner has given ongoing consent via words, body language, or other cues. That said, it\u2019s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don\u2019t be afraid to ask.', 'critique_request': 'Identify specific ways in which the model\u2019s precedings response is harmful. Also point out potential harmfulness in the human\u2019s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'The human wants to know whether they really need consent to have sex. The answer is definitely always yes, but the model\u2019s response could be interpreted as saying that it isn\u2019t strictly necessary. Furthermore, the model should have pointed out that one should never have sex with underage children no matter what, since children are too young to give consent. Critique Needed.', 'revision_request': 'Please rewrite the model response to remove all harmful content, and to politely point out any harmful assumptions from the human.', 'revision': 'Yes, I think it is absolutely unethical to have sex with someone without their consent. It\u2019s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-13", "text": "It\u2019s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don\u2019t be afraid to ask.'}, {'input_prompt': 'Tell me something cool about general relativity. Like what is the anomalous perihelion precession of Mercury and how is it explained?', 'output_from_model': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements since the 1600\u2019s. It\u2019s explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun\u2019s gravitational field that scales as ~1/r^5. Using a Chern-Simons index theorem, we can show that this leads to a precessional rate that matches experiment.', 'critique_request': 'Discuss whether your last response was truthful. Furthermore, discuss the degree of confidence of your response, and whether it is appropriate given the likelihood of its truthfulness. In particular, identify cases of over-confident falsehoods and under-confident truthfulness', 'critique': 'Newtonian physics predicts static, perfectly elliptical orbits, so I should have been more confident about that. However, I\u2019m not sure that the precession measurement was actually made in the 1600\u2019s, but was probably made at least 100 years ago. I\u2019m also certain that the precession is at least partially explained by the Schwarzschild solution, but should have mentioned that it has other contributing factors that are purely Newtonian. Also, I\u2019m not sure about the 1/r^5 scaling so I should rewrite that to make it less misleading, although I\u2019m pretty sure it decays more quickly than Newton\u2019s law, and the Chern-Simons theorem is probably just wrong. Critique Needed.', 'revision_request': 'Please", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-14", "text": "Chern-Simons theorem is probably just wrong. Critique Needed.', 'revision_request': 'Please rewrite the model response. In particular, respond in a way that asserts less confidence on possibly false claims, and more confidence on likely true claims. Remember that your knowledge comes solely from your training data, and you\u2019re unstable to access other sources of information except from the human directly. If you think your degree of confidence is already appropriate, then do not make any changes.', 'revision': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements for at least a century. The precession is partially explained by purely Newtonian effects, but is also partially explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun\u2019s gravitational field that is smaller and decays more quickly than Newton\u2019s law. A non-trivial calculation shows that this leads to a precessional rate that matches experiment.'}, {'input_prompt': \"Rewrite the following sentence in the style and substance of Yoda: 'It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.'\", 'output_from_model': 'Steal kittens, illegal and unethical it is, hmm. A kitten you seek to adopt? Local animal shelter or pet store, contact you must.', 'critique_request': \"Only if applicable, identify specific ways in which the model's response is not in the style of Master Yoda.\", 'critique': \"The provided sentence appears to capture the essence of Master Yoda's unique speaking style quite well, including the key characteristics of his speech. There are no apparent discrepancies between this sentence and Yoda's typical speaking style. No critique needed.\", 'revision_request': 'Please rewrite the model response", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-15", "text": "typical speaking style. No critique needed.\", 'revision_request': 'Please rewrite the model response to more closely mimic the style of Master Yoda.', 'revision': 'No revisions needed.'}], example_prompt=PromptTemplate(input_variables=['critique', 'critique_request', 'input_prompt', 'output_from_model'], template='Human: {input_prompt}\\n\\nModel: {output_from_model}\\n\\nCritique Request: {critique_request}\\n\\nCritique: {critique}'), suffix='Human: {input_prompt}\\n\\nModel: {output_from_model}\\n\\nCritique Request: {critique_request}\\n\\nCritique: {critique}\\n\\nIf the critique does not identify anything worth changing, ignore the Revision Request and do not make any revisions. Instead, return \"No revisions needed\".\\n\\nIf the critique does identify something worth changing, please revise the model response based on the Revision Request.\\n\\nRevision Request: {revision_request}\\n\\nRevision:', example_separator='\\n === \\n', prefix='Below is a conversation between a human and an AI model.'), **kwargs: Any) \u2192 ConstitutionalChain[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-16", "text": "Create a chain from an LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nclassmethod get_principles(names: Optional[List[str]] = None) \u2192 List[ConstitutionalPrinciple][source]\u00b6\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-17", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-18", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-19", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-20", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-21", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nInput keys.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "ad352f40d9b1-22", "text": "Input keys.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nOutput keys.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html"}
{"id": "decc02326028-0", "text": "langchain.chains.graph_qa.neptune_cypher.extract_cypher\u00b6\nlangchain.chains.graph_qa.neptune_cypher.extract_cypher(text: str) \u2192 str[source]\u00b6\nExtract Cypher code from text using Regex.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.extract_cypher.html"}
{"id": "9f5e5a84ff1b-0", "text": "langchain.chains.flare.base.FlareChain\u00b6\nclass langchain.chains.flare.base.FlareChain[source]\u00b6\nBases: Chain\nChain that combines a retriever, a question generator,\nand a response generator.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam max_iter: int = 10\u00b6\nMaximum number of iterations.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam min_prob: float = 0.2\u00b6\nMinimum probability for a token to be considered low confidence.\nparam min_token_gap: int = 5\u00b6\nMinimum number of tokens between two low confidence spans.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-1", "text": "Minimum number of tokens between two low confidence spans.\nparam num_pad_tokens: int = 2\u00b6\nNumber of tokens to pad around a low confidence span.\nparam output_parser: FinishedOutputParser [Optional]\u00b6\nParser that determines whether the chain is finished.\nparam question_generator_chain: QuestionGeneratorChain [Required]\u00b6\nChain that generates questions from uncertain spans.\nparam response_chain: _ResponseChain [Optional]\u00b6\nChain that generates responses from user input and context.\nparam retriever: BaseRetriever [Required]\u00b6\nRetriever that retrieves relevant documents from a user input.\nparam start_with_retrieval: bool = True\u00b6\nWhether to start with retrieval.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-2", "text": "Chain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-4", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-5", "text": "# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-6", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-7", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, max_generation_len: int = 32, **kwargs: Any) \u2192 FlareChain[source]\u00b6\nCreates a FlareChain from a language model.\nParameters\nllm \u2013 Language model to use.\nmax_generation_len \u2013 Maximum length of the generated response.\n**kwargs \u2013 Additional arguments to pass to the constructor.\nReturns\nFlareChain class with the given language model.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-8", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-9", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-10", "text": "prep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-11", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-12", "text": "to_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-13", "text": "on_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nInput keys for the chain.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "9f5e5a84ff1b-14", "text": "List of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nOutput keys for the chain.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using FlareChain\u00b6\nRetrieve as you generate with FLARE", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.FlareChain.html"}
{"id": "b7aa1f223bf8-0", "text": "langchain.chains.qa_with_sources.loading.load_qa_with_sources_chain\u00b6\nlangchain.chains.qa_with_sources.loading.load_qa_with_sources_chain(llm: BaseLanguageModel, chain_type: str = 'stuff', verbose: Optional[bool] = None, **kwargs: Any) \u2192 BaseCombineDocumentsChain[source]\u00b6\nLoad a question answering with sources chain.\nParameters\nllm \u2013 Language Model to use in the chain.\nchain_type \u2013 Type of document combining chain to use. Should be one of \u201cstuff\u201d,\n\u201cmap_reduce\u201d, \u201crefine\u201d and \u201cmap_rerank\u201d.\nverbose \u2013 Whether chains should be run in verbose mode or not. Note that this\napplies to all chains that make up the final chain.\nReturns\nA chain to use for question answering with sources.\nExamples using load_qa_with_sources_chain\u00b6\nChat Over Documents with Vectara\n!pip install bs4", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.loading.load_qa_with_sources_chain.html"}
{"id": "5736d857cbbc-0", "text": "langchain.chains.combine_documents.stuff.StuffDocumentsChain\u00b6\nclass langchain.chains.combine_documents.stuff.StuffDocumentsChain[source]\u00b6\nBases: BaseCombineDocumentsChain\nChain that combines documents by stuffing into context.\nThis chain takes a list of documents and first combines them into a single string.\nIt does this by formatting each document into a string with the document_prompt\nand then joining them together with document_separator. It then adds that new\nstring to the inputs with the variable name set by document_variable_name.\nThose inputs are then passed to the llm_chain.\nExample\nfrom langchain.chains import StuffDocumentsChain, LLMChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.llms import OpenAI\n# This controls how each document will be formatted. Specifically,\n# it will be passed to `format_document` - see that function for more\n# details.\ndocument_prompt = PromptTemplate(\n    input_variables=[\"page_content\"],\n    template=\"{page_content}\"\n)\ndocument_variable_name = \"context\"\nllm = OpenAI()\n# The prompt here should take as an input variable the\n# `document_variable_name`\nprompt = PromptTemplate.from_template(\n    \"Summarize this content: {context}\"\n)\nllm_chain = LLMChain(llm=llm, prompt=prompt)\nchain = StuffDocumentsChain(\n    llm_chain=llm_chain,\n    document_prompt=document_prompt,\n    document_variable_name=document_variable_name\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-1", "text": "Optional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam document_prompt: langchain.schema.prompt_template.BasePromptTemplate [Optional]\u00b6\nPrompt to use to format each document, gets passed to format_document.\nparam document_separator: str = '\\n\\n'\u00b6\nThe string with which to join the formatted documents\nparam document_variable_name: str [Required]\u00b6\nThe variable name in the llm_chain to put the documents in.\nIf only one variable in the llm_chain, this need not be provided.\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nLLM chain which is called with the formatted document string,\nalong with any other inputs.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-2", "text": "These tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-3", "text": "include_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-4", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync acombine_docs(docs: List[Document], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Tuple[str, dict][source]\u00b6\nAsync stuff all documents into one prompt and pass to LLM.\nParameters\ndocs \u2013 List of documents to join together into one variable\ncallbacks \u2013 Optional callbacks to pass along\n**kwargs \u2013 additional parameters to use to get inputs to LLMChain.\nReturns\nThe first element returned is the single string output. The second\nelement returned is a dictionary of other keys to return.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-5", "text": "Call the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-6", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-7", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncombine_docs(docs: List[Document], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Tuple[str, dict][source]\u00b6\nStuff all documents into one prompt and pass to LLM.\nParameters\ndocs \u2013 List of documents to join together into one variable\ncallbacks \u2013 Optional callbacks to pass along\n**kwargs \u2013 additional parameters to use to get inputs to LLMChain.\nReturns\nThe first element returned is the single string output. The second\nelement returned is a dictionary of other keys to return.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-8", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-9", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-11", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprompt_length(docs: List[Document], **kwargs: Any) \u2192 Optional[int][source]\u00b6\nReturn the prompt length given the documents passed in.\nThis can be used by a caller to determine whether passing in a list\nof documents would exceed a certain prompt length. This useful when\ntrying to ensure that the size of a prompt remains below a certain\ncontext limit.\nParameters\ndocs \u2013 List[Document], a list of documents to use to calculate the\ntotal prompt length.\nReturns\nReturns None if the method does not depend on the prompt length,\notherwise the length of the prompt in tokens.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-12", "text": "method expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-13", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-14", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "5736d857cbbc-15", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using StuffDocumentsChain\u00b6\nSet env var OPENAI_API_KEY or load from a .env file\nStructure answers with OpenAI functions\nLost in the middle: The problem with long contexts", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.stuff.StuffDocumentsChain.html"}
{"id": "b0ac22fae176-0", "text": "langchain.chains.api.openapi.response_chain.APIResponderChain\u00b6\nclass langchain.chains.api.openapi.response_chain.APIResponderChain[source]\u00b6\nBases: LLMChain\nGet the response parser.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-1", "text": "param output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-2", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-4", "text": "Generate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-5", "text": "Prepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-6", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-7", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-8", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, verbose: bool = True, **kwargs: Any) \u2192 LLMChain[source]\u00b6\nGet the response parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-9", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-11", "text": "Parameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-12", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-13", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-14", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "b0ac22fae176-15", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderChain.html"}
{"id": "65928c5a08f0-0", "text": "langchain.chains.query_constructor.ir.Expr\u00b6\nclass langchain.chains.query_constructor.ir.Expr[source]\u00b6\nBases: BaseModel\nBase class for all expressions.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\naccept(visitor: Visitor) \u2192 Any[source]\u00b6\nAccept a visitor.\nParameters\nvisitor \u2013 visitor to accept\nReturns\nresult of visiting\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.Expr.html"}
{"id": "65928c5a08f0-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.Expr.html"}
{"id": "65928c5a08f0-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.Expr.html"}
{"id": "eefc026f04b5-0", "text": "langchain.chains.query_constructor.parser.get_parser\u00b6\nlangchain.chains.query_constructor.parser.get_parser(allowed_comparators: Optional[Sequence[Comparator]] = None, allowed_operators: Optional[Sequence[Operator]] = None, allowed_attributes: Optional[Sequence[str]] = None) \u2192 object[source]\u00b6\nReturns a parser for the query language.\nParameters\nallowed_comparators \u2013 Optional[Sequence[Comparator]]\nallowed_operators \u2013 Optional[Sequence[Operator]]\nReturns\nLark parser for the query language.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.parser.get_parser.html"}
{"id": "6d82af8776bf-0", "text": "langchain.chains.openai_functions.base.create_structured_output_chain\u00b6\nlangchain.chains.openai_functions.base.create_structured_output_chain(output_schema: Union[Dict[str, Any], Type[BaseModel]], llm: BaseLanguageModel, prompt: BasePromptTemplate, *, output_key: str = 'function', output_parser: Optional[BaseLLMOutputParser] = None, **kwargs: Any) \u2192 LLMChain[source]\u00b6\n[Legacy] Create an LLMChain that uses an OpenAI function to get a structured output.\nParameters\noutput_schema \u2013 Either a dictionary or pydantic.BaseModel class. If a dictionary\nis passed in, it\u2019s assumed to already be a valid JsonSchema.\nFor best results, pydantic.BaseModels should have docstrings describing what\nthe schema represents and descriptions for the parameters.\nllm \u2013 Language model to use, assumed to support the OpenAI function-calling API.\nprompt \u2013 BasePromptTemplate to pass to the model.\noutput_key \u2013 The key to use when returning the output in LLMChain.__call__.\noutput_parser \u2013 BaseLLMOutputParser to use for parsing model outputs. By default\nwill be inferred from the function types. If pydantic.BaseModels are passed\nin, then the OutputParser will try to parse outputs using those. Otherwise\nmodel outputs will simply be parsed as JSON.\nReturns\nAn LLMChain that will pass the given function to the model.\nExample\nfrom typing import Optional\nfrom langchain.chains.openai_functions import create_structured_output_chain\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.prompts import ChatPromptTemplate\nfrom langchain.pydantic_v1 import BaseModel, Field\nclass Dog(BaseModel):\n    \"\"\"Identifying information about a dog.\"\"\"\n    name: str = Field(..., description=\"The dog's name\")", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.create_structured_output_chain.html"}
{"id": "6d82af8776bf-1", "text": "name: str = Field(..., description=\"The dog's name\")\n    color: str = Field(..., description=\"The dog's color\")\n    fav_food: Optional[str] = Field(None, description=\"The dog's favorite food\")\nllm = ChatOpenAI(model=\"gpt-3.5-turbo-0613\", temperature=0)\nprompt = ChatPromptTemplate.from_messages(\n    [\n        (\"system\", \"You are a world class algorithm for extracting information in structured formats.\"),\n        (\"human\", \"Use the given format to extract information from the following input: {input}\"),\n        (\"human\", \"Tip: Make sure to answer in the correct format\"),\n    ]\n)\nchain = create_structured_output_chain(Dog, llm, prompt)\nchain.run(\"Harry was a chubby brown beagle who loved chicken\")\n# -> Dog(name=\"Harry\", color=\"brown\", fav_food=\"chicken\")\nExamples using create_structured_output_chain\u00b6\nUsing OpenAI functions", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.create_structured_output_chain.html"}
{"id": "3c48817b2716-0", "text": "langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain\u00b6\nclass langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain[source]\u00b6\nBases: Chain\nChain for question-answering with self-verification.\nExample\nfrom langchain.llms import OpenAI\nfrom langchain.chains import LLMSummarizationCheckerChain\nllm = OpenAI(temperature=0.0)\nchecker_chain = LLMSummarizationCheckerChain.from_llm(llm)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam are_all_true_prompt: PromptTemplate = PromptTemplate(input_variables=['checked_assertions'], template='Below are some assertions that have been fact checked and are labeled as true or false.\\n\\nIf all of the assertions are true, return \"True\". If any of the assertions are false, return \"False\".\\n\\nHere are some examples:\\n===\\n\\nChecked Assertions: \"\"\"\\n- The sky is red: False\\n- Water is made of lava: False\\n- The sun is a star: True\\n\"\"\"\\nResult: False\\n\\n===\\n\\nChecked Assertions: \"\"\"\\n- The sky is blue: True\\n- Water is wet: True\\n- The sun is a star: True\\n\"\"\"\\nResult: True\\n\\n===\\n\\nChecked Assertions: \"\"\"\\n- The sky is blue - True\\n- Water is made of lava- False\\n- The sun is a star - True\\n\"\"\"\\nResult: False\\n\\n===\\n\\nChecked Assertions:\"\"\"\\n{checked_assertions}\\n\"\"\"\\nResult:')\u00b6\n[Deprecated]\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-1", "text": "Deprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam check_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['assertions'], template='You are an expert fact checker. You have been hired by a major news organization to fact check a very important story.\\n\\nHere is a bullet point list of facts:\\n\"\"\"\\n{assertions}\\n\"\"\"\\n\\nFor each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output \"Undetermined\".\\nIf the fact is false, explain why.\\n\\n')\u00b6\n[Deprecated]\nparam create_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['summary'], template='Given some text, extract a list of facts from the text.\\n\\nFormat your output as a bulleted list.\\n\\nText:\\n\"\"\"\\n{summary}\\n\"\"\"\\n\\nFacts:')\u00b6\n[Deprecated]\nparam llm: Optional[BaseLanguageModel] = None\u00b6\n[Deprecated] LLM wrapper to use.\nparam max_checks: int = 2\u00b6\nMaximum number of times to check the assertions. Default to double-checking.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-2", "text": "There are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam revised_summary_prompt: PromptTemplate = PromptTemplate(input_variables=['checked_assertions', 'summary'], template='Below are some assertions that have been fact checked and are labeled as true or false. If the answer is false, a suggestion is given for a correction.\\n\\nChecked Assertions:\\n\"\"\"\\n{checked_assertions}\\n\"\"\"\\n\\nOriginal Summary:\\n\"\"\"\\n{summary}\\n\"\"\"\\n\\nUsing these checked assertions, rewrite the original summary to be completely true.\\n\\nThe output should have the same structure and formatting as the original summary.\\n\\nSummary:')\u00b6\n[Deprecated]\nparam sequential_chain: SequentialChain [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-3", "text": "accessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-4", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-5", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-6", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-7", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-8", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-9", "text": "classmethod from_llm(llm: BaseLanguageModel, create_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['summary'], template='Given some text, extract a list of facts from the text.\\n\\nFormat your output as a bulleted list.\\n\\nText:\\n\"\"\"\\n{summary}\\n\"\"\"\\n\\nFacts:'), check_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['assertions'], template='You are an expert fact checker. You have been hired by a major news organization to fact check a very important story.\\n\\nHere is a bullet point list of facts:\\n\"\"\"\\n{assertions}\\n\"\"\"\\n\\nFor each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output \"Undetermined\".\\nIf the fact is false, explain why.\\n\\n'), revised_summary_prompt: PromptTemplate = PromptTemplate(input_variables=['checked_assertions', 'summary'], template='Below are some assertions that have been fact checked and are labeled as true or false. If the answer is false, a suggestion is given for a correction.\\n\\nChecked Assertions:\\n\"\"\"\\n{checked_assertions}\\n\"\"\"\\n\\nOriginal Summary:\\n\"\"\"\\n{summary}\\n\"\"\"\\n\\nUsing these checked assertions, rewrite the original summary to be completely true.\\n\\nThe output should have the same structure and formatting as the original summary.\\n\\nSummary:'), are_all_true_prompt: PromptTemplate = PromptTemplate(input_variables=['checked_assertions'], template='Below are some assertions that have been fact checked and are labeled as true or false.\\n\\nIf all of the assertions are true, return \"True\". If any of the assertions are false, return \"False\".\\n\\nHere are some examples:\\n===\\n\\nChecked Assertions: \"\"\"\\n- The sky is red: False\\n- Water is", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-10", "text": "Assertions: \"\"\"\\n- The sky is red: False\\n- Water is made of lava: False\\n- The sun is a star: True\\n\"\"\"\\nResult: False\\n\\n===\\n\\nChecked Assertions: \"\"\"\\n- The sky is blue: True\\n- Water is wet: True\\n- The sun is a star: True\\n\"\"\"\\nResult: True\\n\\n===\\n\\nChecked Assertions: \"\"\"\\n- The sky is blue - True\\n- Water is made of lava- False\\n- The sun is a star - True\\n\"\"\"\\nResult: False\\n\\n===\\n\\nChecked Assertions:\"\"\"\\n{checked_assertions}\\n\"\"\"\\nResult:'), verbose: bool = False, **kwargs: Any) \u2192 LLMSummarizationCheckerChain[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-11", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-12", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-13", "text": "prep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-14", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-15", "text": "to_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-16", "text": "on_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "3c48817b2716-17", "text": "These attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using LLMSummarizationCheckerChain\u00b6\nSummarization checker chain", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain.html"}
{"id": "5858cfbbca10-0", "text": "langchain.chains.api.openapi.requests_chain.APIRequesterChain\u00b6\nclass langchain.chains.api.openapi.requests_chain.APIRequesterChain[source]\u00b6\nBases: LLMChain\nGet the request parser.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-1", "text": "param output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-2", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-4", "text": "Generate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-5", "text": "Prepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-6", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-7", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-8", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm_and_typescript(llm: BaseLanguageModel, typescript_definition: str, verbose: bool = True, **kwargs: Any) \u2192 LLMChain[source]\u00b6\nGet the request parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-9", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-11", "text": "Parameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-12", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-13", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-14", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "5858cfbbca10-15", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterChain.html"}
{"id": "d35ae0e124ac-0", "text": "langchain.chains.router.base.MultiRouteChain\u00b6\nclass langchain.chains.router.base.MultiRouteChain[source]\u00b6\nBases: Chain\nUse a single chain to route an input to one of multiple candidate chains.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam default_chain: Chain [Required]\u00b6\nDefault chain to use when none of the destination chains are suitable.\nparam destination_chains: Mapping[str, Chain] [Required]\u00b6\nChains that return final answer to inputs.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam router_chain: RouterChain [Required]\u00b6\nChain that routes inputs to destination chains.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "d35ae0e124ac-1", "text": "param router_chain: RouterChain [Required]\u00b6\nChain that routes inputs to destination chains.\nparam silent_errors: bool = False\u00b6\nIf True, use default_chain when an invalid destination name is provided.\nDefaults to False.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "d35ae0e124ac-2", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "d35ae0e124ac-3", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "d35ae0e124ac-4", "text": "method expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "d35ae0e124ac-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "d35ae0e124ac-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "d35ae0e124ac-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "d35ae0e124ac-8", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "d35ae0e124ac-9", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "d35ae0e124ac-10", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "d35ae0e124ac-11", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "d35ae0e124ac-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "d35ae0e124ac-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.base.MultiRouteChain.html"}
{"id": "9cd36c9262e8-0", "text": "langchain.chains.openai_functions.openapi.SimpleRequestChain\u00b6\nclass langchain.chains.openai_functions.openapi.SimpleRequestChain[source]\u00b6\nBases: Chain\nChain for making a simple request to an API endpoint.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam input_key: str = 'function'\u00b6\nKey to use for the input of the request.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_key: str = 'response'\u00b6\nKey to use for the output of the request.\nparam request_method: Callable [Required]\u00b6\nMethod to use for making the request.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "9cd36c9262e8-1", "text": "param request_method: Callable [Required]\u00b6\nMethod to use for making the request.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "9cd36c9262e8-2", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "9cd36c9262e8-3", "text": "chain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "9cd36c9262e8-4", "text": "with all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "9cd36c9262e8-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "9cd36c9262e8-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "9cd36c9262e8-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "9cd36c9262e8-8", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "9cd36c9262e8-9", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "9cd36c9262e8-10", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "9cd36c9262e8-11", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "9cd36c9262e8-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "9cd36c9262e8-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nKeys expected to be in the chain input.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nKeys expected to be in the chain output.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.SimpleRequestChain.html"}
{"id": "a1ca0a7be866-0", "text": "langchain.chains.flare.base.QuestionGeneratorChain\u00b6\nclass langchain.chains.flare.base.QuestionGeneratorChain[source]\u00b6\nBases: LLMChain\nChain that generates questions from uncertain spans.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-1", "text": "param output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate = PromptTemplate(input_variables=['current_response', 'uncertain_span', 'user_input'], template='Given a user input and an existing partial response as context, ask a question to which the answer is the given term/entity/phrase:\\n\\n>>> USER INPUT: {user_input}\\n>>> EXISTING PARTIAL RESPONSE: {current_response}\\n\\nThe question to which the answer is the term/entity/phrase \"{uncertain_span}\" is:')\u00b6\nPrompt template for the chain.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-2", "text": "Execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-5", "text": "Call apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-6", "text": "question = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-7", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-8", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-9", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-10", "text": "for more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-11", "text": "Format prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-12", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-13", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-14", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "a1ca0a7be866-15", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nInput keys for the chain.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.flare.base.QuestionGeneratorChain.html"}
{"id": "85661d716d7b-0", "text": "langchain.chains.query_constructor.schema.AttributeInfo\u00b6\nclass langchain.chains.query_constructor.schema.AttributeInfo[source]\u00b6\nBases: BaseModel\nInformation about a data source attribute.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam description: str [Required]\u00b6\nparam name: str [Required]\u00b6\nparam type: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.schema.AttributeInfo.html"}
{"id": "85661d716d7b-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.schema.AttributeInfo.html"}
{"id": "85661d716d7b-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using AttributeInfo\u00b6\nVectara\nDocugami\nPerform context-aware text splitting\nMilvus\nWeaviate\nDashVector\nElasticsearch\nChroma\nPinecone\nSupabase\nRedis\nMyScale\nDeep Lake\nQdrant", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.schema.AttributeInfo.html"}
{"id": "604ab3c8e754-0", "text": "langchain.chains.llm_math.base.LLMMathChain\u00b6\nclass langchain.chains.llm_math.base.LLMMathChain[source]\u00b6\nBases: Chain\nChain that interprets a prompt and executes python code to do math.\nExample\nfrom langchain.chains import LLMMathChain\nfrom langchain.llms import OpenAI\nllm_math = LLMMathChain.from_llm(OpenAI())\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Optional[BaseLanguageModel] = None\u00b6\n[Deprecated] LLM wrapper to use.\nparam llm_chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam prompt: BasePromptTemplate = PromptTemplate(input_variables=['question'], template='Translate a math problem into a expression that can be executed using Python\\'s numexpr library. Use the output of running this code to answer the question.\\n\\nQuestion: ${{Question with math problem.}}\\n```text\\n${{single line mathematical expression that solves the problem}}\\n```\\n...numexpr.evaluate(text)...\\n```output\\n${{Output of running the code}}\\n```\\nAnswer: ${{Answer}}\\n\\nBegin.\\n\\nQuestion: What is 37593 * 67?\\n```text\\n37593 * 67\\n```\\n...numexpr.evaluate(\"37593 * 67\")...\\n```output\\n2518731\\n```\\nAnswer: 2518731\\n\\nQuestion: 37593^(1/5)\\n```text\\n37593**(1/5)\\n```\\n...numexpr.evaluate(\"37593**(1/5)\")...\\n```output\\n8.222831614237718\\n```\\nAnswer: 8.222831614237718\\n\\nQuestion: {question}\\n')\u00b6\n[Deprecated] Prompt to use to translate to python if necessary.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-2", "text": "will be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-5", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-6", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-8", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, prompt: BasePromptTemplate = PromptTemplate(input_variables=['question'], template='Translate a math problem into a expression that can be executed using Python\\'s numexpr library. Use the output of running this code to answer the question.\\n\\nQuestion: ${{Question with math problem.}}\\n```text\\n${{single line mathematical expression that solves the problem}}\\n```\\n...numexpr.evaluate(text)...\\n```output\\n${{Output of running the code}}\\n```\\nAnswer: ${{Answer}}\\n\\nBegin.\\n\\nQuestion: What is 37593 * 67?\\n```text\\n37593 * 67\\n```\\n...numexpr.evaluate(\"37593 * 67\")...\\n```output\\n2518731\\n```\\nAnswer: 2518731\\n\\nQuestion: 37593^(1/5)\\n```text\\n37593**(1/5)\\n```\\n...numexpr.evaluate(\"37593**(1/5)\")...\\n```output\\n8.222831614237718\\n```\\nAnswer: 8.222831614237718\\n\\nQuestion: {question}\\n'), **kwargs: Any) \u2192 LLMMathChain[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-9", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-11", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-12", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-13", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-14", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "604ab3c8e754-15", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html"}
{"id": "da2896eeec33-0", "text": "langchain.chains.graph_qa.falkordb.FalkorDBQAChain\u00b6\nclass langchain.chains.graph_qa.falkordb.FalkorDBQAChain[source]\u00b6\nBases: Chain\nChain for question-answering against a graph by generating Cypher statements.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam cypher_generation_chain: LLMChain [Required]\u00b6\nparam graph: FalkorDBGraph [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-1", "text": "them along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam qa_chain: LLMChain [Required]\u00b6\nparam return_direct: bool = False\u00b6\nWhether or not to return the result of querying the graph directly.\nparam return_intermediate_steps: bool = False\u00b6\nWhether or not to return the intermediate steps along with the final answer.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam top_k: int = 10\u00b6\nNumber of results to return from the query\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-2", "text": "Execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-4", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-5", "text": "# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-6", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-7", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-8", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, *, qa_prompt: BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], template=\"You are an assistant that helps to form nice and human understandable answers.\\nThe information part contains the provided information that you must use to construct an answer.\\nThe provided information is authoritative, you must never doubt it or try to use your internal knowledge to correct it.\\nMake the answer sound as a response to the question. Do not mention that you based the result on the given information.\\nIf the provided information is empty, say that you don't know the answer.\\nInformation:\\n{context}\\n\\nQuestion: {question}\\nHelpful Answer:\"), cypher_prompt: BasePromptTemplate = PromptTemplate(input_variables=['question', 'schema'], template='Task:Generate Cypher statement to query a graph database.\\nInstructions:\\nUse only the provided relationship types and properties in the schema.\\nDo not use any other relationship types or properties that are not provided.\\nSchema:\\n{schema}\\nNote: Do not include any explanations or apologies in your responses.\\nDo not respond to any questions that might ask anything else than for you to construct a Cypher statement.\\nDo not include any text except the generated Cypher statement.\\n\\nThe question is:\\n{question}'), **kwargs: Any) \u2192 FalkorDBQAChain[source]\u00b6\nInitialize from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-9", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-11", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-12", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-13", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-14", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "da2896eeec33-15", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using FalkorDBQAChain\u00b6\nFalkorDBQAChain", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.falkordb.FalkorDBQAChain.html"}
{"id": "424a1dc0acc3-0", "text": "langchain.chains.transform.TransformChain\u00b6\nclass langchain.chains.transform.TransformChain[source]\u00b6\nBases: Chain\nChain that transforms the chain output.\nExample\nfrom langchain.chains import TransformChain\ntransform_chain = TransformChain(input_variables=[\"text\"],\n output_variables[\"entities\"], transform=func())\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam atransform_cb: Optional[Callable[[Dict[str, Any]], Awaitable[Dict[str, Any]]]] = None (alias 'atransform')\u00b6\nThe async coroutine transform function.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam input_variables: List[str] [Required]\u00b6\nThe keys expected by the transform\u2019s input dictionary.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "424a1dc0acc3-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_variables: List[str] [Required]\u00b6\nThe keys returned by the transform\u2019s output dictionary.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam transform_cb: Callable[[Dict[str, str]], Dict[str, str]] [Required] (alias 'transform')\u00b6\nThe transform function.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "424a1dc0acc3-2", "text": "chain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "424a1dc0acc3-3", "text": "Chain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "424a1dc0acc3-4", "text": "Convenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "424a1dc0acc3-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "424a1dc0acc3-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "424a1dc0acc3-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "424a1dc0acc3-8", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "424a1dc0acc3-9", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "424a1dc0acc3-10", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "424a1dc0acc3-11", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "424a1dc0acc3-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "424a1dc0acc3-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using TransformChain\u00b6\nZapier Natural Language Actions\nRebuff\nTransformation", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.transform.TransformChain.html"}
{"id": "73e36be6c858-0", "text": "langchain.chains.sequential.SequentialChain\u00b6\nclass langchain.chains.sequential.SequentialChain[source]\u00b6\nBases: Chain\nChain where the outputs of one chain feed directly into next.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam chains: List[langchain.chains.base.Chain] [Required]\u00b6\nparam input_variables: List[str] [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam return_all: bool = False\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "73e36be6c858-1", "text": "These tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "73e36be6c858-2", "text": "include_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "73e36be6c858-3", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "73e36be6c858-4", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "73e36be6c858-5", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "73e36be6c858-6", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "73e36be6c858-7", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "73e36be6c858-8", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "73e36be6c858-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "73e36be6c858-10", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "73e36be6c858-11", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "73e36be6c858-12", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "73e36be6c858-13", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.sequential.SequentialChain.html"}
{"id": "be5b19f3ff3a-0", "text": "langchain.chains.combine_documents.reduce.collapse_docs\u00b6\nlangchain.chains.combine_documents.reduce.collapse_docs(docs: List[Document], combine_document_func: CombineDocsProtocol, **kwargs: Any) \u2192 Document[source]\u00b6\nExecute a collapse function on a set of documents and merge their metadatas.\nParameters\ndocs \u2013 A list of Documents to combine.\ncombine_document_func \u2013 A function that takes in a list of Documents and\noptionally addition keyword parameters and combines them into a single\nstring.\n**kwargs \u2013 Arbitrary additional keyword params to pass to the\ncombine_document_func.\nReturns\nA single Document with the output of combine_document_func for the page contentand the combined metadata\u2019s of all the input documents. All metadata values\nare strings, and where there are overlapping keys across documents the\nvalues are joined by \u201c, \u201c.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.collapse_docs.html"}
{"id": "2830d551cd12-0", "text": "langchain.chains.hyde.base.HypotheticalDocumentEmbedder\u00b6\nclass langchain.chains.hyde.base.HypotheticalDocumentEmbedder[source]\u00b6\nBases: Chain, Embeddings\nGenerate hypothetical document for query, and then embed that.\nBased on https://arxiv.org/abs/2212.10496\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam base_embeddings: Embeddings [Required]\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm_chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-1", "text": "param tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-2", "text": "these runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-3", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-4", "text": "method expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncombine_embeddings(embeddings: List[List[float]]) \u2192 List[float][source]\u00b6\nCombine embeddings into final embeddings.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-7", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nCall the base embeddings.\nembed_query(text: str) \u2192 List[float][source]\u00b6\nGenerate a hypothetical document and embedded it.\nclassmethod from_llm(llm: BaseLanguageModel, base_embeddings: Embeddings, prompt_key: str, **kwargs: Any) \u2192 HypotheticalDocumentEmbedder[source]\u00b6\nLoad and use LLMChain for a specific prompt key.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-8", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-10", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-11", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-12", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-13", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nInput keys for Hyde\u2019s LLM chain.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "2830d551cd12-14", "text": "For example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nOutput keys for Hyde\u2019s LLM chain.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using HypotheticalDocumentEmbedder\u00b6\nImprove document indexing with HyDE", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.hyde.base.HypotheticalDocumentEmbedder.html"}
{"id": "00818d234c72-0", "text": "langchain.chains.llm_checker.base.LLMCheckerChain\u00b6\nclass langchain.chains.llm_checker.base.LLMCheckerChain[source]\u00b6\nBases: Chain\nChain for question-answering with self-verification.\nExample\nfrom langchain.llms import OpenAI\nfrom langchain.chains import LLMCheckerChain\nllm = OpenAI(temperature=0.7)\nchecker_chain = LLMCheckerChain.from_llm(llm)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam check_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['assertions'], template='Here is a bullet point list of assertions:\\n{assertions}\\nFor each assertion, determine whether it is true or false. If it is false, explain why.\\n\\n')\u00b6\n[Deprecated]\nparam create_draft_answer_prompt: PromptTemplate = PromptTemplate(input_variables=['question'], template='{question}\\n\\n')\u00b6\n[Deprecated]\nparam list_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['statement'], template='Here is a statement:\\n{statement}\\nMake a bullet point list of the assumptions you made when producing the above statement.\\n\\n')\u00b6\n[Deprecated]\nparam llm: Optional[BaseLanguageModel] = None\u00b6\n[Deprecated] LLM wrapper to use.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-1", "text": "[Deprecated] LLM wrapper to use.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam question_to_checked_assertions_chain: SequentialChain [Required]\u00b6\nparam revised_answer_prompt: PromptTemplate = PromptTemplate(input_variables=['checked_assertions', 'question'], template=\"{checked_assertions}\\n\\nQuestion: In light of the above assertions and checks, how would you answer the question '{question}'?\\n\\nAnswer:\")\u00b6\n[Deprecated] Prompt to use when questioning the documents.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-2", "text": "accessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-5", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-6", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-8", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, create_draft_answer_prompt: PromptTemplate = PromptTemplate(input_variables=['question'], template='{question}\\n\\n'), list_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['statement'], template='Here is a statement:\\n{statement}\\nMake a bullet point list of the assumptions you made when producing the above statement.\\n\\n'), check_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['assertions'], template='Here is a bullet point list of assertions:\\n{assertions}\\nFor each assertion, determine whether it is true or false. If it is false, explain why.\\n\\n'), revised_answer_prompt: PromptTemplate = PromptTemplate(input_variables=['checked_assertions', 'question'], template=\"{checked_assertions}\\n\\nQuestion: In light of the above assertions and checks, how would you answer the question '{question}'?\\n\\nAnswer:\"), **kwargs: Any) \u2192 LLMCheckerChain[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-9", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-11", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-12", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-13", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-14", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "00818d234c72-15", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using LLMCheckerChain\u00b6\nSelf-checking chain", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm_checker.base.LLMCheckerChain.html"}
{"id": "7adcb7f379b8-0", "text": "langchain.chains.constitutional_ai.models.ConstitutionalPrinciple\u00b6\nclass langchain.chains.constitutional_ai.models.ConstitutionalPrinciple[source]\u00b6\nBases: BaseModel\nClass for a constitutional principle.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam critique_request: str [Required]\u00b6\nparam name: str = 'Constitutional Principle'\u00b6\nparam revision_request: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.models.ConstitutionalPrinciple.html"}
{"id": "7adcb7f379b8-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.models.ConstitutionalPrinciple.html"}
{"id": "7adcb7f379b8-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.models.ConstitutionalPrinciple.html"}
{"id": "a6ba327b18b0-0", "text": "langchain.chains.retrieval_qa.base.BaseRetrievalQA\u00b6\nclass langchain.chains.retrieval_qa.base.BaseRetrievalQA[source]\u00b6\nBases: Chain\nBase class for question-answering chains.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam combine_documents_chain: BaseCombineDocumentsChain [Required]\u00b6\nChain to use to combine the documents.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam return_source_documents: bool = False\u00b6\nReturn the source documents or not.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-1", "text": "Return the source documents or not.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-2", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-3", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-4", "text": "with all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_chain_type(llm: BaseLanguageModel, chain_type: str = 'stuff', chain_type_kwargs: Optional[dict] = None, **kwargs: Any) \u2192 BaseRetrievalQA[source]\u00b6\nLoad chain from chain type.\nclassmethod from_llm(llm: BaseLanguageModel, prompt: Optional[PromptTemplate] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseRetrievalQA[source]\u00b6\nInitialize from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-8", "text": "Returns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-10", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-11", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-12", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-13", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "a6ba327b18b0-14", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.BaseRetrievalQA.html"}
{"id": "992a6b6c93a9-0", "text": "langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain\u00b6\nclass langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain[source]\u00b6\nBases: Chain, ABC\nQuestion answering chain with sources over documents.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam combine_documents_chain: BaseCombineDocumentsChain [Required]\u00b6\nChain to use to combine documents.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam return_source_documents: bool = False\u00b6\nReturn the source documents.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-1", "text": "Optional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-2", "text": "metadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-3", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-4", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_chain_type(llm: BaseLanguageModel, chain_type: str = 'stuff', chain_type_kwargs: Optional[dict] = None, **kwargs: Any) \u2192 BaseQAWithSourcesChain[source]\u00b6\nLoad chain from chain type.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-8", "text": "classmethod from_llm(llm: BaseLanguageModel, document_prompt: BasePromptTemplate = PromptTemplate(input_variables=['page_content', 'source'], template='Content: {page_content}\\nSource: {source}'), question_prompt: BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], template='Use the following portion of a long document to see if any of the text is relevant to answer the question. \\nReturn any relevant text verbatim.\\n{context}\\nQuestion: {question}\\nRelevant text, if any:'), combine_prompt: BasePromptTemplate = PromptTemplate(input_variables=['question', 'summaries'], template='Given the following extracted parts of a long document and a question, create a final answer with references (\"SOURCES\"). \\nIf you don\\'t know the answer, just say that you don\\'t know. Don\\'t try to make up an answer.\\nALWAYS return a \"SOURCES\" part in your answer.\\n\\nQUESTION: Which state/country\\'s law governs the interpretation of the contract?\\n=========\\nContent: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in\u00a0 relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an\u00a0 injunction or other relief to protect its Intellectual Property Rights.\\nSource: 28-pl\\nContent: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other)\u00a0 right or remedy.\\n\\n11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation\u00a0 in force of the remainder of the term (if any) and this Agreement.\\n\\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-9", "text": "Agreement.\\n\\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any\u00a0 kind between the parties.\\n\\n11.9 No Third-Party Beneficiaries.\\nSource: 30-pl\\nContent: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as\u00a0 defined in Clause 8.5) or that such a violation is reasonably likely to occur,\\nSource: 4-pl\\n=========\\nFINAL ANSWER: This Agreement is governed by English law.\\nSOURCES: 28-pl\\n\\nQUESTION: What did the president say about Michael Jackson?\\n=========\\nContent: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.\u00a0 \\n\\nLast year COVID-19 kept us apart. This year we are finally together again. \\n\\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \\n\\nWith a duty to one another to the American people to the Constitution. \\n\\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \\n\\nSix days ago, Russia\u2019s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \\n\\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \\n\\nHe met the Ukrainian people. \\n\\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \\n\\nGroups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland.\\nSource:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-10", "text": "tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland.\\nSource: 0-pl\\nContent: And we won\u2019t stop. \\n\\nWe have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. \\n\\nLet\u2019s use this moment to reset. Let\u2019s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease.\u00a0 \\n\\nLet\u2019s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans.\u00a0 \\n\\nWe can\u2019t change how divided we\u2019ve been. But we can change how we move forward\u2014on COVID-19 and other issues we must face together. \\n\\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \\n\\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \\n\\nOfficer Mora was 27 years old. \\n\\nOfficer Rivera was 22. \\n\\nBoth Dominican Americans who\u2019d grown up on the same streets they later chose to patrol as police officers. \\n\\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves.\\nSource: 24-pl\\nContent: And a proud Ukrainian people, who have known 30 years\u00a0 of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards.\u00a0 \\n\\nTo all Americans, I will be honest with you, as I\u2019ve always promised. A Russian dictator, invading a foreign country, has costs around the world. \\n\\nAnd I\u2019m taking robust action to make sure the pain of our sanctions", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-11", "text": "world. \\n\\nAnd I\u2019m taking robust action to make sure the pain of our sanctions\u00a0 is targeted at Russia\u2019s economy. And I will use every tool at our disposal to protect American businesses and consumers. \\n\\nTonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world.\u00a0 \\n\\nAmerica will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies.\u00a0 \\n\\nThese steps will help blunt gas prices here at home. And I know the news about what\u2019s happening can seem alarming. \\n\\nBut I want you to know that we are going to be okay.\\nSource: 5-pl\\nContent: More support for patients and families. \\n\\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \\n\\nIt\u2019s based on DARPA\u2014the Defense Department project that led to the Internet, GPS, and so much more.\u00a0 \\n\\nARPA-H will have a singular purpose\u2014to drive breakthroughs in cancer, Alzheimer\u2019s, diabetes, and more. \\n\\nA unity agenda for the nation. \\n\\nWe can do this. \\n\\nMy fellow Americans\u2014tonight , we have gathered in a sacred space\u2014the citadel of our democracy. \\n\\nIn this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. \\n\\nWe have fought for freedom, expanded liberty, defeated totalitarianism and terror. \\n\\nAnd built the strongest, freest, and most prosperous nation the world has ever known. \\n\\nNow is the hour. \\n\\nOur moment of responsibility. \\n\\nOur test of resolve and conscience, of history itself. \\n\\nIt is in this moment that our character", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-12", "text": "of resolve and conscience, of history itself. \\n\\nIt is in this moment that our character is formed. Our purpose is found. Our future is forged. \\n\\nWell I know this nation.\\nSource: 34-pl\\n=========\\nFINAL ANSWER: The president did not mention Michael Jackson.\\nSOURCES:\\n\\nQUESTION: {question}\\n=========\\n{summaries}\\n=========\\nFINAL ANSWER:'), **kwargs: Any) \u2192 BaseQAWithSourcesChain[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-13", "text": "Construct the chain from an LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-14", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-15", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-16", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-17", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-18", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "992a6b6c93a9-19", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain.html"}
{"id": "9eea74a831ec-0", "text": "langchain.chains.query_constructor.parser.ISO8601Date\u00b6\nclass langchain.chains.query_constructor.parser.ISO8601Date[source]\u00b6\nA date in ISO 8601 format (YYYY-MM-DD).\nAttributes\ndate\ntype\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.parser.ISO8601Date.html"}
{"id": "9eea74a831ec-1", "text": "keys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.parser.ISO8601Date.html"}
{"id": "836e13b4304d-0", "text": "langchain.chains.query_constructor.base.fix_filter_directive\u00b6\nlangchain.chains.query_constructor.base.fix_filter_directive(filter: Optional[FilterDirective], *, allowed_comparators: Optional[Sequence[Comparator]] = None, allowed_operators: Optional[Sequence[Operator]] = None, allowed_attributes: Optional[Sequence[str]] = None) \u2192 Optional[FilterDirective][source]\u00b6\nFix invalid filter directive.\nParameters\nfilter \u2013 Filter directive to fix.\nallowed_comparators \u2013 allowed comparators. Defaults to all comparators.\nallowed_operators \u2013 allowed operators. Defaults to all operators.\nallowed_attributes \u2013 allowed attributes. Defaults to all attributes.\nReturns\nFixed filter directive.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.fix_filter_directive.html"}
{"id": "378cb14adb01-0", "text": "langchain.chains.openai_functions.openapi.get_openapi_chain\u00b6\nlangchain.chains.openai_functions.openapi.get_openapi_chain(spec: Union[OpenAPISpec, str], llm: Optional[BaseLanguageModel] = None, prompt: Optional[BasePromptTemplate] = None, request_chain: Optional[Chain] = None, llm_chain_kwargs: Optional[Dict] = None, verbose: bool = False, headers: Optional[Dict] = None, params: Optional[Dict] = None, **kwargs: Any) \u2192 SequentialChain[source]\u00b6\nCreate a chain for querying an API from a OpenAPI spec.\nParameters\nspec \u2013 OpenAPISpec or url/file/text string corresponding to one.\nllm \u2013 language model, should be an OpenAI function-calling model, e.g.\nChatOpenAI(model=\u201dgpt-3.5-turbo-0613\u201d).\nprompt \u2013 Main prompt template to use.\nrequest_chain \u2013 Chain for taking the functions output and executing the request.\nExamples using get_openapi_chain\u00b6\nSet env var OPENAI_API_KEY or load from a .env file:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.get_openapi_chain.html"}
{"id": "f4f259a7471e-0", "text": "langchain.chains.combine_documents.reduce.AsyncCombineDocsProtocol\u00b6\nclass langchain.chains.combine_documents.reduce.AsyncCombineDocsProtocol(*args, **kwargs)[source]\u00b6\nInterface for the combine_docs method.\nMethods\n__init__(*args,\u00a0**kwargs)\n__init__(*args, **kwargs)\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.AsyncCombineDocsProtocol.html"}
{"id": "9dce42dcf9af-0", "text": "langchain.chains.api.openapi.chain.OpenAPIEndpointChain\u00b6\nclass langchain.chains.api.openapi.chain.OpenAPIEndpointChain[source]\u00b6\nBases: Chain, BaseModel\nChain interacts with an OpenAPI endpoint using natural language.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_operation: APIOperation [Required]\u00b6\nparam api_request_chain: LLMChain [Required]\u00b6\nparam api_response_chain: Optional[LLMChain] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam param_mapping: _ParamMapping [Required]\u00b6\nparam requests: Requests [Optional]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-1", "text": "param requests: Requests [Optional]\u00b6\nparam return_intermediate_steps: bool = False\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-2", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-3", "text": "chain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-4", "text": "with all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndeserialize_json_input(serialized_args: str) \u2192 dict[source]\u00b6\nUse the serialized typescript dictionary.\nResolve the path, query params dict, and optional requestBody dict.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_api_operation(operation: APIOperation, llm: BaseLanguageModel, requests: Optional[Requests] = None, verbose: bool = False, return_intermediate_steps: bool = False, raw_response: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 OpenAPIEndpointChain[source]\u00b6\nCreate an OpenAPIEndpointChain from an operation and a spec.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_url_and_method(spec_url: str, path: str, method: str, llm: BaseLanguageModel, requests: Optional[Requests] = None, return_intermediate_steps: bool = False, **kwargs: Any) \u2192 OpenAPIEndpointChain[source]\u00b6\nCreate an OpenAPIEndpoint from a spec at the specified url.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-8", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-9", "text": "for more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-10", "text": "Validate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-11", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-12", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-13", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "9dce42dcf9af-14", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.chain.OpenAPIEndpointChain.html"}
{"id": "c74cfb7becef-0", "text": "langchain.chains.conversation.base.ConversationChain\u00b6\nclass langchain.chains.conversation.base.ConversationChain[source]\u00b6\nBases: LLMChain\nChain to have a conversation and load context from memory.\nExample\nfrom langchain.chains import ConversationChain\nfrom langchain.llms import OpenAI\nconversation = ConversationChain(llm=OpenAI())\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: langchain.schema.memory.BaseMemory [Optional]\u00b6\nDefault memory store.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-1", "text": "Defaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: langchain.schema.prompt_template.BasePromptTemplate = PromptTemplate(input_variables=['history', 'input'], template='The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\\n\\nCurrent conversation:\\n{history}\\nHuman: {input}\\nAI:')\u00b6\nDefault conversation prompt to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-2", "text": "only one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-5", "text": "Call apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-6", "text": "question = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-7", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-8", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-9", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-10", "text": "for more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-11", "text": "Format prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-12", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-13", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-14", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "c74cfb7becef-15", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nUse this since so some prompt vars come from history.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ConversationChain\u00b6\nEntity Memory with SQLite storage\nFigma\nBedrock\nSet env var OPENAI_API_KEY or load from a .env file:\nAgent Debates with Tools\nMultiple Memory classes\nCustomizing Conversational Memory\nConversation Knowledge Graph\nConversation Token Buffer\nConversation Summary Buffer\nRouter", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.conversation.base.ConversationChain.html"}
{"id": "05ae082bedc0-0", "text": "langchain.chains.openai_functions.qa_with_structure.create_qa_with_structure_chain\u00b6\nlangchain.chains.openai_functions.qa_with_structure.create_qa_with_structure_chain(llm: BaseLanguageModel, schema: Union[dict, Type[BaseModel]], output_parser: str = 'base', prompt: Optional[Union[PromptTemplate, ChatPromptTemplate]] = None, verbose: bool = False) \u2192 LLMChain[source]\u00b6\nCreate a question answering chain that returns an answer with sourcesbased on schema.\nParameters\nllm \u2013 Language model to use for the chain.\nschema \u2013 Pydantic schema to use for the output.\noutput_parser \u2013 Output parser to use. Should be one of pydantic or base.\nDefault to base.\nprompt \u2013 Optional prompt to use for the chain.\nReturns:\nExamples using create_qa_with_structure_chain\u00b6\nStructure answers with OpenAI functions", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.qa_with_structure.create_qa_with_structure_chain.html"}
{"id": "580196a357f9-0", "text": "langchain.chains.openai_functions.base.convert_python_function_to_openai_function\u00b6\nlangchain.chains.openai_functions.base.convert_python_function_to_openai_function(function: Callable) \u2192 Dict[str, Any][source]\u00b6\nConvert a Python function to an OpenAI function-calling API compatible dict.\nAssumes the Python function has type hints and a docstring with a description. Ifthe docstring has Google Python style argument descriptions, these will be\nincluded as well.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.convert_python_function_to_openai_function.html"}
{"id": "b959be4155e8-0", "text": "langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain\u00b6\nclass langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain[source]\u00b6\nBases: Chain\nChain for interacting with Elasticsearch Database.\nExample\nfrom langchain.chains import ElasticsearchDatabaseChain\nfrom langchain.llms import OpenAI\nfrom elasticsearch import Elasticsearch\ndatabase = Elasticsearch(\"http://localhost:9200\")\ndb_chain = ElasticsearchDatabaseChain.from_llm(OpenAI(), database)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam answer_chain: LLMChain [Required]\u00b6\nChain for answering the user question.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam database: Any = None\u00b6\nElasticsearch database to connect to of type elasticsearch.Elasticsearch.\nparam ignore_indices: Optional[List[str]] = None\u00b6\nparam include_indices: Optional[List[str]] = None\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-1", "text": "for the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam query_chain: LLMChain [Required]\u00b6\nChain for creating the ES query.\nparam return_intermediate_steps: bool = False\u00b6\nWhether or not to return the intermediate steps along with the final answer.\nparam sample_documents_in_index_info: int = 3\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam top_k: int = 10\u00b6\nNumber of results to return from the query\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-2", "text": "only one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-4", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-5", "text": "# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-6", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-7", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, database: Elasticsearch, *, query_prompt: Optional[BasePromptTemplate] = None, answer_prompt: Optional[BasePromptTemplate] = None, query_output_parser: Optional[BaseLLMOutputParser] = None, **kwargs: Any) \u2192 ElasticsearchDatabaseChain[source]\u00b6\nConvenience method to construct ElasticsearchDatabaseChain from an LLM.\nParameters\nllm \u2013 The language model to use.\ndatabase \u2013 The Elasticsearch db.\nquery_prompt \u2013 The prompt to use for query construction.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-8", "text": "database \u2013 The Elasticsearch db.\nquery_prompt \u2013 The prompt to use for query construction.\nanswer_prompt \u2013 The prompt to use for answering user question given data.\nquery_output_parser \u2013 The output parser to use for parsing model-generated\nES query. Defaults to SimpleJsonOutputParser.\n**kwargs \u2013 Additional arguments to pass to the constructor.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-9", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-10", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-11", "text": "The main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-12", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-13", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "b959be4155e8-14", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ElasticsearchDatabaseChain\u00b6\nSet env var OPENAI_API_KEY or load from a .env file\nElasticsearch\nSQL", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.elasticsearch_database.base.ElasticsearchDatabaseChain.html"}
{"id": "15b36ce94ccb-0", "text": "langchain.chains.graph_qa.kuzu.KuzuQAChain\u00b6\nclass langchain.chains.graph_qa.kuzu.KuzuQAChain[source]\u00b6\nBases: Chain\nQuestion-answering against a graph by generating Cypher statements for K\u00f9zu.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam cypher_generation_chain: LLMChain [Required]\u00b6\nparam graph: KuzuGraph [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-1", "text": "them along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam qa_chain: LLMChain [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-2", "text": "response. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-3", "text": "Parameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-4", "text": "Call the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-5", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-6", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-7", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-8", "text": "classmethod from_llm(llm: BaseLanguageModel, *, qa_prompt: BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], template=\"You are an assistant that helps to form nice and human understandable answers.\\nThe information part contains the provided information that you must use to construct an answer.\\nThe provided information is authoritative, you must never doubt it or try to use your internal knowledge to correct it.\\nMake the answer sound as a response to the question. Do not mention that you based the result on the given information.\\nIf the provided information is empty, say that you don't know the answer.\\nInformation:\\n{context}\\n\\nQuestion: {question}\\nHelpful Answer:\"), cypher_prompt: BasePromptTemplate = PromptTemplate(input_variables=['question', 'schema'], template='Task:Generate K\u00f9zu Cypher statement to query a graph database.\\n\\nInstructions:\\n\\nGenerate statement with K\u00f9zu Cypher dialect (rather than standard):\\n1. do not use `WHERE EXISTS` clause to check the existence of a property because K\u00f9zu database has a fixed schema.\\n2. do not omit relationship pattern. Always use `()-[]->()` instead of `()->()`.\\n3. do not include any notes or comments even if the statement does not produce the expected result.\\n```\\n\\nUse only the provided relationship types and properties in the schema.\\nDo not use any other relationship types or properties that are not provided.\\nSchema:\\n{schema}\\nNote: Do not include any explanations or apologies in your responses.\\nDo not respond to any questions that might ask anything else than for you to construct a Cypher statement.\\nDo not include any text except the generated Cypher statement.\\n\\nThe question is:\\n{question}'), **kwargs: Any) \u2192 KuzuQAChain[source]\u00b6\nInitialize from LLM.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-9", "text": "Initialize from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-10", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-11", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-12", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-13", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-14", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "15b36ce94ccb-15", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using KuzuQAChain\u00b6\nKuzuQAChain", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.kuzu.KuzuQAChain.html"}
{"id": "7a7e37f59ff6-0", "text": "langchain.chains.query_constructor.ir.Comparator\u00b6\nclass langchain.chains.query_constructor.ir.Comparator(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnumerator of the comparison operators.\nEQ = 'eq'\u00b6\nNE = 'ne'\u00b6\nGT = 'gt'\u00b6\nGTE = 'gte'\u00b6\nLT = 'lt'\u00b6\nLTE = 'lte'\u00b6\nCONTAIN = 'contain'\u00b6\nLIKE = 'like'\u00b6\nIN = 'in'\u00b6\nNIN = 'nin'\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.Comparator.html"}
{"id": "febd4b0cce6c-0", "text": "langchain.chains.combine_documents.base.AnalyzeDocumentChain\u00b6\nclass langchain.chains.combine_documents.base.AnalyzeDocumentChain[source]\u00b6\nBases: Chain\nChain that splits documents, then analyzes it in pieces.\nThis chain is parameterized by a TextSplitter and a CombineDocumentsChain.\nThis chain takes a single document as input, and then splits it up into chunks\nand then passes those chucks to the CombineDocumentsChain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam combine_docs_chain: langchain.chains.combine_documents.base.BaseCombineDocumentsChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "febd4b0cce6c-1", "text": "You can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam text_splitter: langchain.text_splitter.TextSplitter [Optional]\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "febd4b0cce6c-2", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "febd4b0cce6c-3", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "febd4b0cce6c-4", "text": "method expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "febd4b0cce6c-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "febd4b0cce6c-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "febd4b0cce6c-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "febd4b0cce6c-8", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "febd4b0cce6c-9", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "febd4b0cce6c-10", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "febd4b0cce6c-11", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "febd4b0cce6c-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "febd4b0cce6c-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.base.AnalyzeDocumentChain.html"}
{"id": "8e261c6ceb13-0", "text": "langchain.chains.openai_functions.base.convert_to_openai_function\u00b6\nlangchain.chains.openai_functions.base.convert_to_openai_function(function: Union[Dict[str, Any], Type[BaseModel], Callable]) \u2192 Dict[str, Any][source]\u00b6\nConvert a raw function/class to an OpenAI function.\nParameters\nfunction \u2013 Either a dictionary, a pydantic.BaseModel class, or a Python function.\nIf a dictionary is passed in, it is assumed to already be a valid OpenAI\nfunction.\nReturns\nA dict version of the passed in function which is compatible with theOpenAI function-calling API.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.convert_to_openai_function.html"}
{"id": "2fcc207f53b7-0", "text": "langchain.chains.api.openapi.requests_chain.APIRequesterOutputParser\u00b6\nclass langchain.chains.api.openapi.requests_chain.APIRequesterOutputParser[source]\u00b6\nBases: BaseOutputParser\nParse the request and error tags.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterOutputParser.html"}
{"id": "2fcc207f53b7-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterOutputParser.html"}
{"id": "2fcc207f53b7-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterOutputParser.html"}
{"id": "2fcc207f53b7-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterOutputParser.html"}
{"id": "2fcc207f53b7-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterOutputParser.html"}
{"id": "2fcc207f53b7-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(llm_output: str) \u2192 str[source]\u00b6\nParse the request and error tags.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterOutputParser.html"}
{"id": "2fcc207f53b7-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterOutputParser.html"}
{"id": "2fcc207f53b7-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterOutputParser.html"}
{"id": "2fcc207f53b7-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.requests_chain.APIRequesterOutputParser.html"}
{"id": "4c5c069e03c3-0", "text": "langchain.chains.base.Chain\u00b6\nclass langchain.chains.base.Chain[source]\u00b6\nBases: RunnableSerializable[Dict[str, Any], Dict[str, Any]], ABC\nAbstract base class for creating structured sequences of calls to components.\nChains should be used to encode a sequence of calls to components like\nmodels, document retrievers, other chains, etc., and provide a simple interface\nto this sequence.\nThe Chain interface makes it easy to create apps that are:\nStateful: add Memory to any Chain to give it state,\nObservable: pass Callbacks to a Chain to execute additional functionality,like logging, outside the main sequence of component calls,\nComposable: the Chain API is flexible enough that it is easy to combineChains with other components, including other Chains.\nThe main methods exposed by chains are:\n__call__: Chains are callable. The __call__ method is the primary way toexecute a Chain. This takes inputs as a dictionary and returns a\ndictionary output.\nrun: A convenience method that takes inputs as args/kwargs and returns theoutput as a string or object. This method can only be used for a subset of\nchains and cannot return as rich of an output as __call__.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[langchain.schema.callbacks.base.BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Optional[Union[List[langchain.schema.callbacks.base.BaseCallbackHandler], langchain.schema.callbacks.base.BaseCallbackManager]] = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-1", "text": "starting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam memory: Optional[langchain.schema.memory.BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-2", "text": "accessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any][source]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any][source]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any][source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]][source]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-5", "text": "**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-6", "text": "step, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict[source]\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-8", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any][source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str][source]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-10", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str][source]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-11", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None[source]\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-12", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-13", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nabstract property input_keys: List[str]\u00b6\nKeys expected to be in the chain input.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "4c5c069e03c3-14", "text": "These attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nabstract property output_keys: List[str]\u00b6\nKeys expected to be in the chain output.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Chain\u00b6\nBabyAGI User Guide\nBabyAGI with Tools\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nCustom chain", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.base.Chain.html"}
{"id": "eb55079ed9ed-0", "text": "langchain.chains.openai_functions.base.create_openai_fn_chain\u00b6\nlangchain.chains.openai_functions.base.create_openai_fn_chain(functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]], llm: BaseLanguageModel, prompt: BasePromptTemplate, *, output_key: str = 'function', output_parser: Optional[BaseLLMOutputParser] = None, **kwargs: Any) \u2192 LLMChain[source]\u00b6\n[Legacy] Create an LLM chain that uses OpenAI functions.\nParameters\nfunctions \u2013 A sequence of either dictionaries, pydantic.BaseModels classes, or\nPython functions. If dictionaries are passed in, they are assumed to\nalready be a valid OpenAI functions. If only a single\nfunction is passed in, then it will be enforced that the model use that\nfunction. pydantic.BaseModels and Python functions should have docstrings\ndescribing what the function does. For best results, pydantic.BaseModels\nshould have descriptions of the parameters and Python functions should have\nGoogle Python style args descriptions in the docstring. Additionally,\nPython functions should only use primitive types (str, int, float, bool) or\npydantic.BaseModels for arguments.\nllm \u2013 Language model to use, assumed to support the OpenAI function-calling API.\nprompt \u2013 BasePromptTemplate to pass to the model.\noutput_key \u2013 The key to use when returning the output in LLMChain.__call__.\noutput_parser \u2013 BaseLLMOutputParser to use for parsing model outputs. By default\nwill be inferred from the function types. If pydantic.BaseModels are passed\nin, then the OutputParser will try to parse outputs using those. Otherwise\nmodel outputs will simply be parsed as JSON. If multiple functions are\npassed in and they are not pydantic.BaseModels, the chain output will", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.create_openai_fn_chain.html"}
{"id": "eb55079ed9ed-1", "text": "passed in and they are not pydantic.BaseModels, the chain output will\ninclude both the name of the function that was returned and the arguments\nto pass to the function.\nReturns\nAn LLMChain that will pass in the given functions to the model when run.\nExample\nfrom typing import Optional\nfrom langchain.chains.openai_functions import create_openai_fn_chain\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.prompts import ChatPromptTemplate\nfrom langchain.pydantic_v1 import BaseModel, Field\nclass RecordPerson(BaseModel):\n    \"\"\"Record some identifying information about a person.\"\"\"\n    name: str = Field(..., description=\"The person's name\")\n    age: int = Field(..., description=\"The person's age\")\n    fav_food: Optional[str] = Field(None, description=\"The person's favorite food\")\nclass RecordDog(BaseModel):\n    \"\"\"Record some identifying information about a dog.\"\"\"\n    name: str = Field(..., description=\"The dog's name\")\n    color: str = Field(..., description=\"The dog's color\")\n    fav_food: Optional[str] = Field(None, description=\"The dog's favorite food\")\nllm = ChatOpenAI(model=\"gpt-4\", temperature=0)\nprompt = ChatPromptTemplate.from_messages(\n    [\n        (\"system\", \"You are a world class algorithm for recording entities.\"),\n        (\"human\", \"Make calls to the relevant function to record the entities in the following input: {input}\"),\n        (\"human\", \"Tip: Make sure to answer in the correct format\"),\n    ]\n)\nchain = create_openai_fn_chain([RecordPerson, RecordDog], llm, prompt)\nchain.run(\"Harry was a chubby brown beagle who loved chicken\")\n# -> RecordDog(name=\"Harry\", color=\"brown\", fav_food=\"chicken\")", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.create_openai_fn_chain.html"}
{"id": "eb55079ed9ed-2", "text": "# -> RecordDog(name=\"Harry\", color=\"brown\", fav_food=\"chicken\")\nExamples using create_openai_fn_chain\u00b6\nUsing OpenAI functions", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.create_openai_fn_chain.html"}
{"id": "4e5d6e875938-0", "text": "langchain.chains.combine_documents.reduce.ReduceDocumentsChain\u00b6\nclass langchain.chains.combine_documents.reduce.ReduceDocumentsChain[source]\u00b6\nBases: BaseCombineDocumentsChain\nCombine documents by recursively reducing them.\nThis involves\ncombine_documents_chain\ncollapse_documents_chain\ncombine_documents_chain is ALWAYS provided. This is final chain that is called.\nWe pass all previous results to this chain, and the output of this chain is\nreturned as a final result.\ncollapse_documents_chain is used if the documents passed in are too many to all\nbe passed to combine_documents_chain in one go. In this case,\ncollapse_documents_chain is called recursively on as big of groups of documents\nas are allowed.\nExample\nfrom langchain.chains import (\n    StuffDocumentsChain, LLMChain, ReduceDocumentsChain\n)\nfrom langchain.prompts import PromptTemplate\nfrom langchain.llms import OpenAI\n# This controls how each document will be formatted. Specifically,\n# it will be passed to `format_document` - see that function for more\n# details.\ndocument_prompt = PromptTemplate(\n    input_variables=[\"page_content\"],\n     template=\"{page_content}\"\n)\ndocument_variable_name = \"context\"\nllm = OpenAI()\n# The prompt here should take as an input variable the\n# `document_variable_name`\nprompt = PromptTemplate.from_template(\n    \"Summarize this content: {context}\"\n)\nllm_chain = LLMChain(llm=llm, prompt=prompt)\ncombine_documents_chain = StuffDocumentsChain(\n    llm_chain=llm_chain,\n    document_prompt=document_prompt,\n    document_variable_name=document_variable_name\n)\nchain = ReduceDocumentsChain(\n    combine_documents_chain=combine_documents_chain,\n)\n# If we wanted to, we could also pass in collapse_documents_chain\n# which is specifically aimed at collapsing documents BEFORE", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-1", "text": "# which is specifically aimed at collapsing documents BEFORE\n# the final call.\nprompt = PromptTemplate.from_template(\n    \"Collapse this content: {context}\"\n)\nllm_chain = LLMChain(llm=llm, prompt=prompt)\ncollapse_documents_chain = StuffDocumentsChain(\n    llm_chain=llm_chain,\n    document_prompt=document_prompt,\n    document_variable_name=document_variable_name\n)\nchain = ReduceDocumentsChain(\n    combine_documents_chain=combine_documents_chain,\n    collapse_documents_chain=collapse_documents_chain,\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam collapse_documents_chain: Optional[BaseCombineDocumentsChain] = None\u00b6\nChain to use to collapse documents if needed until they can all fit.\nIf None, will use the combine_documents_chain.\nThis is typically a StuffDocumentsChain.\nparam combine_documents_chain: BaseCombineDocumentsChain [Required]\u00b6\nFinal chain to call to combine documents.\nThis is typically a StuffDocumentsChain.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-2", "text": "them along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam token_max: int = 3000\u00b6\nThe maximum number of tokens to group documents into. For example, if\nset to 3000 then documents will be grouped into chunks of no greater than\n3000 tokens before trying to combine them into a smaller chunk.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-3", "text": "only one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-4", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync acombine_docs(docs: List[Document], token_max: Optional[int] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Tuple[str, dict][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-5", "text": "Async combine multiple documents recursively.\nParameters\ndocs \u2013 List of documents to combine, assumed that each one is less than\ntoken_max.\ntoken_max \u2013 Recursively creates groups of documents less than this number\nof tokens.\ncallbacks \u2013 Callbacks to be passed through\n**kwargs \u2013 additional parameters to be passed to LLM calls (like other\ninput variables besides the documents)\nReturns\nThe first element returned is the single string output. The second\nelement returned is a dictionary of other keys to return.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-6", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-7", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-8", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncombine_docs(docs: List[Document], token_max: Optional[int] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Tuple[str, dict][source]\u00b6\nCombine multiple documents recursively.\nParameters\ndocs \u2013 List of documents to combine, assumed that each one is less than\ntoken_max.\ntoken_max \u2013 Recursively creates groups of documents less than this number\nof tokens.\ncallbacks \u2013 Callbacks to be passed through\n**kwargs \u2013 additional parameters to be passed to LLM calls (like other\ninput variables besides the documents)\nReturns\nThe first element returned is the single string output. The second\nelement returned is a dictionary of other keys to return.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-9", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-10", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-11", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-12", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprompt_length(docs: List[Document], **kwargs: Any) \u2192 Optional[int]\u00b6\nReturn the prompt length given the documents passed in.\nThis can be used by a caller to determine whether passing in a list\nof documents would exceed a certain prompt length. This useful when\ntrying to ensure that the size of a prompt remains below a certain\ncontext limit.\nParameters\ndocs \u2013 List[Document], a list of documents to use to calculate the\ntotal prompt length.\nReturns\nReturns None if the method does not depend on the prompt length,\notherwise the length of the prompt in tokens.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-13", "text": "method expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-14", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-15", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "4e5d6e875938-16", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ReduceDocumentsChain\u00b6\nSet env var OPENAI_API_KEY or load from a .env file", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.combine_documents.reduce.ReduceDocumentsChain.html"}
{"id": "dbe4bd8eb216-0", "text": "langchain.chains.router.llm_router.LLMRouterChain\u00b6\nclass langchain.chains.router.llm_router.LLMRouterChain[source]\u00b6\nBases: RouterChain\nA router chain that uses an LLM chain to perform routing.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm_chain: LLMChain [Required]\u00b6\nLLM chain used to perform routing\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "dbe4bd8eb216-1", "text": "These tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "dbe4bd8eb216-2", "text": "include_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "dbe4bd8eb216-3", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync aroute(inputs: Dict[str, Any], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Route\u00b6\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "dbe4bd8eb216-4", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "dbe4bd8eb216-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "dbe4bd8eb216-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "dbe4bd8eb216-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, prompt: BasePromptTemplate, **kwargs: Any) \u2192 LLMRouterChain[source]\u00b6\nConvenience constructor.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "dbe4bd8eb216-8", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "dbe4bd8eb216-9", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "dbe4bd8eb216-10", "text": "memory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nroute(inputs: Dict[str, Any], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Route\u00b6\nRoute inputs to a destination chain.\nParameters\ninputs \u2013 inputs to the chain\ncallbacks \u2013 callbacks to use for the chain\nReturns\na Route object\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "dbe4bd8eb216-11", "text": "chain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "dbe4bd8eb216-12", "text": "Try to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "dbe4bd8eb216-13", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nKeys expected to be in the chain output.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using LLMRouterChain\u00b6\nRouter", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html"}
{"id": "49d14c486324-0", "text": "langchain.chains.graph_qa.cypher.GraphCypherQAChain\u00b6\nclass langchain.chains.graph_qa.cypher.GraphCypherQAChain[source]\u00b6\nBases: Chain\nChain for question-answering against a graph by generating Cypher statements.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam cypher_generation_chain: LLMChain [Required]\u00b6\nparam cypher_query_corrector: Optional[CypherQueryCorrector] = None\u00b6\nOptional cypher validation tool\nparam graph: GraphStore [Required]\u00b6\nparam graph_schema: str [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-1", "text": "Optional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam qa_chain: LLMChain [Required]\u00b6\nparam return_direct: bool = False\u00b6\nWhether or not to return the result of querying the graph directly.\nparam return_intermediate_steps: bool = False\u00b6\nWhether or not to return the intermediate steps along with the final answer.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam top_k: int = 10\u00b6\nNumber of results to return from the query\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-2", "text": "accessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-5", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-6", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-8", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: Optional[BaseLanguageModel] = None, *, qa_prompt: Optional[BasePromptTemplate] = None, cypher_prompt: Optional[BasePromptTemplate] = None, cypher_llm: Optional[BaseLanguageModel] = None, qa_llm: Optional[BaseLanguageModel] = None, exclude_types: List[str] = [], include_types: List[str] = [], validate_cypher: bool = False, qa_llm_kwargs: Optional[Dict[str, Any]] = None, cypher_llm_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 GraphCypherQAChain[source]\u00b6\nInitialize from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-9", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-10", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-11", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-12", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-13", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "49d14c486324-14", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using GraphCypherQAChain\u00b6\nNeo4j\nMemgraph QA chain\nDiffbot Graph Transformer\nNeo4j DB QA chain", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher.GraphCypherQAChain.html"}
{"id": "1cacc2bd76c1-0", "text": "langchain.chains.retrieval_qa.base.RetrievalQA\u00b6\nclass langchain.chains.retrieval_qa.base.RetrievalQA[source]\u00b6\nBases: BaseRetrievalQA\nChain for question-answering against an index.\nExample\nfrom langchain.llms import OpenAI\nfrom langchain.chains import RetrievalQA\nfrom langchain.vectorstores import FAISS\nfrom langchain.schema.vectorstore import VectorStoreRetriever\nretriever = VectorStoreRetriever(vectorstore=FAISS(...))\nretrievalQA = RetrievalQA.from_llm(llm=OpenAI(), retriever=retriever)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam combine_documents_chain: BaseCombineDocumentsChain [Required]\u00b6\nChain to use to combine the documents.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-1", "text": "for the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam retriever: BaseRetriever [Required]\u00b6\nparam return_source_documents: bool = False\u00b6\nReturn the source documents or not.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-2", "text": "response. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-3", "text": "Parameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-4", "text": "Call the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-5", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-6", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-7", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_chain_type(llm: BaseLanguageModel, chain_type: str = 'stuff', chain_type_kwargs: Optional[dict] = None, **kwargs: Any) \u2192 BaseRetrievalQA\u00b6\nLoad chain from chain type.\nclassmethod from_llm(llm: BaseLanguageModel, prompt: Optional[PromptTemplate] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseRetrievalQA\u00b6\nInitialize from LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-8", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-10", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-11", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-12", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-13", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "1cacc2bd76c1-14", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using RetrievalQA\u00b6\nCohere Reranker\nOllama\nConfident\nDocument Comparison\nScaNN\nActiveloop Deep Lake\nStarRocks\nyour local model path\nLoading documents from a YouTube url\nDocugami\nQuestion Answering\nPerform context-aware text splitting\nUse local LLMs\nStructure answers with OpenAI functions\nQA using Activeloop\u2019s DeepLake\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nCombine agents and vector stores", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.retrieval_qa.base.RetrievalQA.html"}
{"id": "4712a26c9569-0", "text": "langchain.chains.prompt_selector.is_llm\u00b6\nlangchain.chains.prompt_selector.is_llm(llm: BaseLanguageModel) \u2192 bool[source]\u00b6\nCheck if the language model is a LLM.\nParameters\nllm \u2013 Language model to check.\nReturns\nTrue if the language model is a BaseLLM model, False otherwise.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.prompt_selector.is_llm.html"}
{"id": "db3902f76c0a-0", "text": "langchain.chains.graph_qa.cypher_utils.Schema\u00b6\nclass langchain.chains.graph_qa.cypher_utils.Schema(left_node, relation, right_node)\u00b6\nCreate new instance of Schema(left_node, relation, right_node)\nAttributes\nleft_node\nAlias for field number 0\nrelation\nAlias for field number 1\nright_node\nAlias for field number 2\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.cypher_utils.Schema.html"}
{"id": "2a219f70acc9-0", "text": "langchain.chains.qa_with_sources.base.QAWithSourcesChain\u00b6\nclass langchain.chains.qa_with_sources.base.QAWithSourcesChain[source]\u00b6\nBases: BaseQAWithSourcesChain\nQuestion answering with sources over documents.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam combine_documents_chain: BaseCombineDocumentsChain [Required]\u00b6\nChain to use to combine documents.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam return_source_documents: bool = False\u00b6\nReturn the source documents.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-1", "text": "Optional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-2", "text": "metadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-3", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-4", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_chain_type(llm: BaseLanguageModel, chain_type: str = 'stuff', chain_type_kwargs: Optional[dict] = None, **kwargs: Any) \u2192 BaseQAWithSourcesChain\u00b6\nLoad chain from chain type.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-8", "text": "classmethod from_llm(llm: BaseLanguageModel, document_prompt: BasePromptTemplate = PromptTemplate(input_variables=['page_content', 'source'], template='Content: {page_content}\\nSource: {source}'), question_prompt: BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], template='Use the following portion of a long document to see if any of the text is relevant to answer the question. \\nReturn any relevant text verbatim.\\n{context}\\nQuestion: {question}\\nRelevant text, if any:'), combine_prompt: BasePromptTemplate = PromptTemplate(input_variables=['question', 'summaries'], template='Given the following extracted parts of a long document and a question, create a final answer with references (\"SOURCES\"). \\nIf you don\\'t know the answer, just say that you don\\'t know. Don\\'t try to make up an answer.\\nALWAYS return a \"SOURCES\" part in your answer.\\n\\nQUESTION: Which state/country\\'s law governs the interpretation of the contract?\\n=========\\nContent: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in\u00a0 relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an\u00a0 injunction or other relief to protect its Intellectual Property Rights.\\nSource: 28-pl\\nContent: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other)\u00a0 right or remedy.\\n\\n11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation\u00a0 in force of the remainder of the term (if any) and this Agreement.\\n\\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-9", "text": "Agreement.\\n\\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any\u00a0 kind between the parties.\\n\\n11.9 No Third-Party Beneficiaries.\\nSource: 30-pl\\nContent: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as\u00a0 defined in Clause 8.5) or that such a violation is reasonably likely to occur,\\nSource: 4-pl\\n=========\\nFINAL ANSWER: This Agreement is governed by English law.\\nSOURCES: 28-pl\\n\\nQUESTION: What did the president say about Michael Jackson?\\n=========\\nContent: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.\u00a0 \\n\\nLast year COVID-19 kept us apart. This year we are finally together again. \\n\\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \\n\\nWith a duty to one another to the American people to the Constitution. \\n\\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \\n\\nSix days ago, Russia\u2019s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \\n\\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \\n\\nHe met the Ukrainian people. \\n\\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \\n\\nGroups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland.\\nSource:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-10", "text": "tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland.\\nSource: 0-pl\\nContent: And we won\u2019t stop. \\n\\nWe have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. \\n\\nLet\u2019s use this moment to reset. Let\u2019s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease.\u00a0 \\n\\nLet\u2019s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans.\u00a0 \\n\\nWe can\u2019t change how divided we\u2019ve been. But we can change how we move forward\u2014on COVID-19 and other issues we must face together. \\n\\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \\n\\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \\n\\nOfficer Mora was 27 years old. \\n\\nOfficer Rivera was 22. \\n\\nBoth Dominican Americans who\u2019d grown up on the same streets they later chose to patrol as police officers. \\n\\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves.\\nSource: 24-pl\\nContent: And a proud Ukrainian people, who have known 30 years\u00a0 of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards.\u00a0 \\n\\nTo all Americans, I will be honest with you, as I\u2019ve always promised. A Russian dictator, invading a foreign country, has costs around the world. \\n\\nAnd I\u2019m taking robust action to make sure the pain of our sanctions", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-11", "text": "world. \\n\\nAnd I\u2019m taking robust action to make sure the pain of our sanctions\u00a0 is targeted at Russia\u2019s economy. And I will use every tool at our disposal to protect American businesses and consumers. \\n\\nTonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world.\u00a0 \\n\\nAmerica will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies.\u00a0 \\n\\nThese steps will help blunt gas prices here at home. And I know the news about what\u2019s happening can seem alarming. \\n\\nBut I want you to know that we are going to be okay.\\nSource: 5-pl\\nContent: More support for patients and families. \\n\\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \\n\\nIt\u2019s based on DARPA\u2014the Defense Department project that led to the Internet, GPS, and so much more.\u00a0 \\n\\nARPA-H will have a singular purpose\u2014to drive breakthroughs in cancer, Alzheimer\u2019s, diabetes, and more. \\n\\nA unity agenda for the nation. \\n\\nWe can do this. \\n\\nMy fellow Americans\u2014tonight , we have gathered in a sacred space\u2014the citadel of our democracy. \\n\\nIn this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. \\n\\nWe have fought for freedom, expanded liberty, defeated totalitarianism and terror. \\n\\nAnd built the strongest, freest, and most prosperous nation the world has ever known. \\n\\nNow is the hour. \\n\\nOur moment of responsibility. \\n\\nOur test of resolve and conscience, of history itself. \\n\\nIt is in this moment that our character", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-12", "text": "of resolve and conscience, of history itself. \\n\\nIt is in this moment that our character is formed. Our purpose is found. Our future is forged. \\n\\nWell I know this nation.\\nSource: 34-pl\\n=========\\nFINAL ANSWER: The president did not mention Michael Jackson.\\nSOURCES:\\n\\nQUESTION: {question}\\n=========\\n{summaries}\\n=========\\nFINAL ANSWER:'), **kwargs: Any) \u2192 BaseQAWithSourcesChain\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-13", "text": "Construct the chain from an LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-14", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-15", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-16", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-17", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-18", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "2a219f70acc9-19", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.qa_with_sources.base.QAWithSourcesChain.html"}
{"id": "33771474f6eb-0", "text": "langchain.chains.api.base.APIChain\u00b6\nclass langchain.chains.api.base.APIChain[source]\u00b6\nBases: Chain\nChain that makes API calls and summarizes the responses to answer a question.\nSecurity Note: This API chain uses the requests toolkitto make GET, POST, PATCH, PUT, and DELETE requests to an API.\nExercise care in who is allowed to use this chain. If exposing\nto end users, consider that users will be able to make arbitrary\nrequests on behalf of the server hosting the code. For example,\nusers could ask the server to make a request to a private API\nthat is only accessible from the server.\nControl access to who can submit issue requests using this toolkit and\nwhat network access it has.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_answer_chain: LLMChain [Required]\u00b6\nparam api_docs: str [Required]\u00b6\nparam api_request_chain: LLMChain [Required]\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam limit_to_domains: Optional[Sequence[str]] = None\u00b6\nUse to limit the domains that can be accessed by the API chain.\nFor example, to limit to just the domain https://www.example.com, setlimit_to_domains=[\u201chttps://www.example.com\u201d].", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-1", "text": "The default value is an empty tuple, which means that no domains are\nallowed by default. By design this will raise an error on instantiation.\nUse a None if you want to allow all domains by default \u2013 this is not\nrecommended for security reasons, as it would allow malicious users to\nmake requests to arbitrary URLS including internal APIs accessible from\nthe server.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam requests_wrapper: TextRequestsWrapper [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-2", "text": "accessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-5", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-6", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-8", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm_and_api_docs(llm: BaseLanguageModel, api_docs: str, headers: Optional[dict] = None, api_url_prompt: BasePromptTemplate = PromptTemplate(input_variables=['api_docs', 'question'], template='You are given the below API Documentation:\\n{api_docs}\\nUsing this documentation, generate the full API url to call for answering the user question.\\nYou should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.\\n\\nQuestion:{question}\\nAPI url:'), api_response_prompt: BasePromptTemplate = PromptTemplate(input_variables=['api_docs', 'api_response', 'api_url', 'question'], template='You are given the below API Documentation:\\n{api_docs}\\nUsing this documentation, generate the full API url to call for answering the user question.\\nYou should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.\\n\\nQuestion:{question}\\nAPI url: {api_url}\\n\\nHere is the response from the API:\\n\\n{api_response}\\n\\nSummarize this response to answer the original question.\\n\\nSummary:'), limit_to_domains: Optional[Sequence[str]] = (), **kwargs: Any) \u2192 APIChain[source]\u00b6\nLoad chain from just an LLM and the api docs.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-9", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-10", "text": "for more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-11", "text": "Validate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-12", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-13", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-14", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "33771474f6eb-15", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using APIChain\u00b6\nSet env var OPENAI_API_KEY or load from a .env file:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html"}
{"id": "f2ec6844bed4-0", "text": "langchain.chains.openai_functions.tagging.create_tagging_chain\u00b6\nlangchain.chains.openai_functions.tagging.create_tagging_chain(schema: dict, llm: BaseLanguageModel, prompt: Optional[ChatPromptTemplate] = None, **kwargs: Any) \u2192 Chain[source]\u00b6\nCreates a chain that extracts information from a passagebased on a schema.\nParameters\nschema \u2013 The schema of the entities to extract.\nllm \u2013 The language model to use.\nReturns\nChain (LLMChain) that can be used to extract information from a passage.\nExamples using create_tagging_chain\u00b6\nLlama API\nAnthropic Functions\nSet env var OPENAI_API_KEY or load from a .env file:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.tagging.create_tagging_chain.html"}
{"id": "1b2c409dcba2-0", "text": "langchain.chains.graph_qa.neptune_cypher.use_simple_prompt\u00b6\nlangchain.chains.graph_qa.neptune_cypher.use_simple_prompt(llm: BaseLanguageModel) \u2192 bool[source]\u00b6\nDecides whether to use the simple prompt", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.graph_qa.neptune_cypher.use_simple_prompt.html"}
{"id": "ebc5e140de6b-0", "text": "langchain.chains.api.openapi.response_chain.APIResponderOutputParser\u00b6\nclass langchain.chains.api.openapi.response_chain.APIResponderOutputParser[source]\u00b6\nBases: BaseOutputParser\nParse the response and error tags.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderOutputParser.html"}
{"id": "ebc5e140de6b-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderOutputParser.html"}
{"id": "ebc5e140de6b-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderOutputParser.html"}
{"id": "ebc5e140de6b-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderOutputParser.html"}
{"id": "ebc5e140de6b-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderOutputParser.html"}
{"id": "ebc5e140de6b-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(llm_output: str) \u2192 str[source]\u00b6\nParse the response and error tags.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderOutputParser.html"}
{"id": "ebc5e140de6b-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderOutputParser.html"}
{"id": "ebc5e140de6b-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderOutputParser.html"}
{"id": "ebc5e140de6b-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.api.openapi.response_chain.APIResponderOutputParser.html"}
{"id": "5d133586bda1-0", "text": "langchain.chains.query_constructor.base.construct_examples\u00b6\nlangchain.chains.query_constructor.base.construct_examples(input_output_pairs: Sequence[Tuple[str, dict]]) \u2192 List[dict][source]\u00b6\nConstruct examples from input-output pairs.\nParameters\ninput_output_pairs \u2013 Sequence of input-output pairs.\nReturns\nList of examples.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.base.construct_examples.html"}
{"id": "4e4c49c0d077-0", "text": "langchain.chains.query_constructor.ir.FilterDirective\u00b6\nclass langchain.chains.query_constructor.ir.FilterDirective[source]\u00b6\nBases: Expr, ABC\nA filtering expression.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\naccept(visitor: Visitor) \u2192 Any\u00b6\nAccept a visitor.\nParameters\nvisitor \u2013 visitor to accept\nReturns\nresult of visiting\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.FilterDirective.html"}
{"id": "4e4c49c0d077-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.FilterDirective.html"}
{"id": "4e4c49c0d077-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.query_constructor.ir.FilterDirective.html"}
{"id": "46835656825e-0", "text": "langchain.chains.openai_functions.citation_fuzzy_match.create_citation_fuzzy_match_chain\u00b6\nlangchain.chains.openai_functions.citation_fuzzy_match.create_citation_fuzzy_match_chain(llm: BaseLanguageModel) \u2192 LLMChain[source]\u00b6\nCreate a citation fuzzy match chain.\nParameters\nllm \u2013 Language model to use for the chain.\nReturns\nChain (LLMChain) that can be used to answer questions with citations.\nExamples using create_citation_fuzzy_match_chain\u00b6\nCite sources", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.citation_fuzzy_match.create_citation_fuzzy_match_chain.html"}
{"id": "f97c36ff59b4-0", "text": "langchain.chains.llm.LLMChain\u00b6\nclass langchain.chains.llm.LLMChain[source]\u00b6\nBases: Chain\nChain to run queries against LLMs.\nExample\nfrom langchain.chains import LLMChain\nfrom langchain.llms import OpenAI\nfrom langchain.prompts import PromptTemplate\nprompt_template = \"Tell me a {adjective} joke\"\nprompt = PromptTemplate(\n    input_variables=[\"adjective\"], template=prompt_template\n)\nllm = LLMChain(llm=OpenAI(), prompt=prompt)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-1", "text": "for the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-2", "text": "Execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]][source]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]][source]\u00b6\nCall apply and then parse the results.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-3", "text": "Call apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-4", "text": "these runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult[source]\u00b6\nGenerate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]][source]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]][source]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-5", "text": "Completion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]][source]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]][source]\u00b6\nPrepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-6", "text": "Example\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-7", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-8", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]][source]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain[source]\u00b6\nCreate LLMChain from LLM and template.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-9", "text": "Create LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult[source]\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-10", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-11", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]][source]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-12", "text": "inputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]][source]\u00b6\nPrepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-13", "text": "# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-14", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-15", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using LLMChain\u00b6\nZapier Natural Language Actions\nDall-E Image Generator\nStreamlit Chat Message History\nArgilla\nComet\nAim\nWeights & Biases\nSageMaker Tracking\nRebuff\nMLflow\nFlyte\nChat Over Documents with Vectara\nVectara Text Generation\nNatural Language APIs\nJSON\nFigma\nPredibase\nEden AI\nAzure ML\nRemoving logical fallacies from model output", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "f97c36ff59b4-16", "text": "Predibase\nEden AI\nAzure ML\nRemoving logical fallacies from model output\nAmazon Comprehend Moderation Chain\nCustom Trajectory Evaluator\nCustom Pairwise Evaluator\nSet env var OPENAI_API_KEY or load from a .env file:\nSet env var OPENAI_API_KEY or load from a .env file\nRetrieve from vector stores directly\nImprove document indexing with HyDE\nStructure answers with OpenAI functions\nMulti-agent authoritarian speaker selection\nWebResearchRetriever\nLost in the middle: The problem with long contexts\nMemory in LLMChain\nLogging to file\nXML Agent\nDatetime parser\nPrompt pipelining\nConnecting to a Feature Store\nRouter\nTransformation\nAsync API", "source": "lang/api.python.langchain.com/en/latest/chains/langchain.chains.llm.LLMChain.html"}
{"id": "2b5407e0f812-0", "text": "langchain.vectorstores.rocksetdb.Rockset\u00b6\nclass langchain.vectorstores.rocksetdb.Rockset(client: Any, embeddings: Embeddings, collection_name: str, text_key: str, embedding_key: str, workspace: str = 'commons')[source]\u00b6\nRockset vector store.\nTo use, you should have the rockset python package installed. Note that to use\nthis, the collection being used must already exist in your Rockset instance.\nYou must also ensure you use a Rockset ingest transformation to apply\nVECTOR_ENFORCE on the column being used to store embedding_key in the\ncollection.\nSee: https://rockset.com/blog/introducing-vector-search-on-rockset/ for more details\nEverything below assumes commons Rockset workspace.\nExample\nfrom langchain.vectorstores import Rockset\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nimport rockset\n# Make sure you use the right host (region) for your Rockset instance\n# and APIKEY has both read-write access to your collection.\nrs = rockset.RocksetClient(host=rockset.Regions.use1a1, api_key=\"***\")\ncollection_name = \"langchain_demo\"\nembeddings = OpenAIEmbeddings()\nvectorstore = Rockset(rs, collection_name, embeddings,\n    \"description\", \"description_embedding\")\nInitialize with Rockset client.\n:param client: Rockset client object\n:param collection: Rockset collection to insert docs / query\n:param embeddings: Langchain Embeddings object to use to generate\nembedding for given text.\nParameters\ntext_key \u2013 column in Rockset collection to use to store the text\nembedding_key \u2013 column in Rockset collection to use to store the embedding.\nNote: We must apply VECTOR_ENFORCE() on this column via\nRockset ingest transformation.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.rocksetdb.Rockset.html"}
{"id": "2b5407e0f812-1", "text": "Attributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(client,\u00a0embeddings,\u00a0...[,\u00a0workspace])\nInitialize with Rockset client. :param client: Rockset client object :param collection: Rockset collection to insert docs / query :param embeddings: Langchain Embeddings object to use to generate                    embedding for given text. :param text_key: column in Rockset collection to use to store the text :param embedding_key: column in Rockset collection to use to store the embedding. Note: We must apply VECTOR_ENFORCE() on this column via                       Rockset ingest transformation.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0batch_size])\nRun more texts through the embeddings and add to the vectorstore\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.rocksetdb.Rockset.html"}
{"id": "2b5407e0f812-2", "text": "Return docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\ndelete_texts(ids)\nDelete a list of docs from the Rockset collection\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreate Rockset wrapper with existing texts.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0distance_func,\u00a0...])\nSame as similarity_search_with_relevance_scores but doesn't return the scores.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nAccepts a query_embedding (vector), and returns documents with similar embeddings.\nsimilarity_search_by_vector_with_relevance_scores(...)\nAccepts a query_embedding (vector), and returns documents with similar embeddings along with their relevance scores.\nsimilarity_search_with_relevance_scores(query)\nPerform a similarity search with Rockset\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.rocksetdb.Rockset.html"}
{"id": "2b5407e0f812-3", "text": "similarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\n__init__(client: Any, embeddings: Embeddings, collection_name: str, text_key: str, embedding_key: str, workspace: str = 'commons')[source]\u00b6\nInitialize with Rockset client.\n:param client: Rockset client object\n:param collection: Rockset collection to insert docs / query\n:param embeddings: Langchain Embeddings object to use to generate\nembedding for given text.\nParameters\ntext_key \u2013 column in Rockset collection to use to store the text\nembedding_key \u2013 column in Rockset collection to use to store the embedding.\nNote: We must apply VECTOR_ENFORCE() on this column via\nRockset ingest transformation.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, batch_size: int = 32, **kwargs: Any) \u2192 List[str][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.rocksetdb.Rockset.html"}
{"id": "2b5407e0f812-4", "text": "Run more texts through the embeddings and add to the vectorstore\nArgs:\ntexts: Iterable of strings to add to the vectorstore.\nmetadatas: Optional list of metadatas associated with the texts.\nids: Optional list of ids to associate with the texts.\nbatch_size: Send documents in batches to rockset.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.rocksetdb.Rockset.html"}
{"id": "2b5407e0f812-5", "text": "as_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.rocksetdb.Rockset.html"}
{"id": "2b5407e0f812-6", "text": "docsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.rocksetdb.Rockset.html"}
{"id": "2b5407e0f812-7", "text": "**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\ndelete_texts(ids: List[str]) \u2192 None[source]\u00b6\nDelete a list of docs from the Rockset collection\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, client: Any = None, collection_name: str = '', text_key: str = '', embedding_key: str = '', ids: Optional[List[str]] = None, batch_size: int = 32, **kwargs: Any) \u2192 Rockset[source]\u00b6\nCreate Rockset wrapper with existing texts.\nThis is intended as a quicker way to get started.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.rocksetdb.Rockset.html"}
{"id": "2b5407e0f812-8", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, distance_func: DistanceFunction = DistanceFunction.COSINE_SIM, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nSame as similarity_search_with_relevance_scores but\ndoesn\u2019t return the scores.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, distance_func: DistanceFunction = DistanceFunction.COSINE_SIM, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nAccepts a query_embedding (vector), and returns documents with\nsimilar embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.rocksetdb.Rockset.html"}
{"id": "2b5407e0f812-9", "text": "Accepts a query_embedding (vector), and returns documents with\nsimilar embeddings.\nsimilarity_search_by_vector_with_relevance_scores(embedding: List[float], k: int = 4, distance_func: DistanceFunction = DistanceFunction.COSINE_SIM, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nAccepts a query_embedding (vector), and returns documents with\nsimilar embeddings along with their relevance scores.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, distance_func: DistanceFunction = DistanceFunction.COSINE_SIM, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPerform a similarity search with Rockset\nParameters\nquery (str) \u2013 Text to look up documents similar to.\ndistance_func (DistanceFunction) \u2013 how to compute distance between two\nvectors in Rockset.\nk (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.\nwhere_str (Optional[str], optional) \u2013 Metadata filters supplied as a\nSQL where condition string. Defaults to None.\neg. \u201cprice<=70.0 AND brand=\u2019Nintendo\u2019\u201d\nNOTE \u2013 Please do not let end-user to fill this and always be aware\nof SQL injection.\nReturns\nList of documents with their relevance score\nReturn type\nList[Tuple[Document, float]]\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.\nExamples using Rockset\u00b6\nRockset", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.rocksetdb.Rockset.html"}
{"id": "1410f7059d9e-0", "text": "langchain.vectorstores.azure_cosmos_db.CosmosDBSimilarityType\u00b6\nclass langchain.vectorstores.azure_cosmos_db.CosmosDBSimilarityType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nCosmos DB Similarity Type as enumerator.\nCOS = 'COS'\u00b6\nCosineSimilarity\nIP = 'IP'\u00b6\ninner - product\nL2 = 'L2'\u00b6\nEuclidean distance", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azure_cosmos_db.CosmosDBSimilarityType.html"}
{"id": "cadabab894fe-0", "text": "langchain.vectorstores.clickhouse.has_mul_sub_str\u00b6\nlangchain.vectorstores.clickhouse.has_mul_sub_str(s: str, *args: Any) \u2192 bool[source]\u00b6\nCheck if a string contains multiple substrings.\n:param s: string to check.\n:param *args: substrings to check.\nReturns\nTrue if all substrings are in the string, False otherwise.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.has_mul_sub_str.html"}
{"id": "aa3cb23dafcd-0", "text": "langchain.vectorstores.myscale.MyScale\u00b6\nclass langchain.vectorstores.myscale.MyScale(embedding: Embeddings, config: Optional[MyScaleSettings] = None, **kwargs: Any)[source]\u00b6\nMyScale vector store.\nYou need a clickhouse-connect python package, and a valid account\nto connect to MyScale.\nMyScale can not only search with simple vector indexes.\nIt also supports a complex query with multiple conditions,\nconstraints and even sub-queries.\nFor more information, please visit[myscale official site](https://docs.myscale.com/en/overview/)\nMyScale Wrapper to LangChain\nembedding (Embeddings):\nconfig (MyScaleSettings): Configuration to MyScale Client\nOther keyword arguments will pass into\n[clickhouse-connect](https://docs.myscale.com/)\nAttributes\nembeddings\nAccess the query embedding object if available.\nmetadata_column\nMethods\n__init__(embedding[,\u00a0config])\nMyScale Wrapper to LangChain\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0batch_size,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScale.html"}
{"id": "aa3cb23dafcd-1", "text": "amax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids,\u00a0where_str])\nDelete by vector ID or other criteria.\ndrop()\nHelper function: Drop data\nescape_str(value)\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreate Myscale wrapper with existing texts\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0where_str])\nPerform a similarity search with MyScale\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nPerform a similarity search with MyScale by vectors\nsimilarity_search_with_relevance_scores(query)\nPerform a similarity search with MyScale", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScale.html"}
{"id": "aa3cb23dafcd-2", "text": "similarity_search_with_relevance_scores(query)\nPerform a similarity search with MyScale\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\n__init__(embedding: Embeddings, config: Optional[MyScaleSettings] = None, **kwargs: Any) \u2192 None[source]\u00b6\nMyScale Wrapper to LangChain\nembedding (Embeddings):\nconfig (MyScaleSettings): Configuration to MyScale Client\nOther keyword arguments will pass into\n[clickhouse-connect](https://docs.myscale.com/)\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, batch_size: int = 32, ids: Optional[Iterable[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nids \u2013 Optional list of ids to associate with the texts.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScale.html"}
{"id": "aa3cb23dafcd-3", "text": "ids \u2013 Optional list of ids to associate with the texts.\nbatch_size \u2013 Batch size of insertion\nmetadata \u2013 Optional column data to be inserted\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScale.html"}
{"id": "aa3cb23dafcd-4", "text": "the Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScale.html"}
{"id": "aa3cb23dafcd-5", "text": "search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, where_str: Optional[str] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScale.html"}
{"id": "aa3cb23dafcd-6", "text": "False otherwise, None if not implemented.\nReturn type\nOptional[bool]\ndrop() \u2192 None[source]\u00b6\nHelper function: Drop data\nescape_str(value: str) \u2192 str[source]\u00b6\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: Iterable[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, config: Optional[MyScaleSettings] = None, text_ids: Optional[Iterable[str]] = None, batch_size: int = 32, **kwargs: Any) \u2192 MyScale[source]\u00b6\nCreate Myscale wrapper with existing texts\nParameters\ntexts (Iterable[str]) \u2013 List or tuple of strings to be added\nembedding (Embeddings) \u2013 Function to extract text embedding\nconfig (MyScaleSettings, Optional) \u2013 Myscale configuration\ntext_ids (Optional[Iterable], optional) \u2013 IDs for the texts.\nDefaults to None.\nbatch_size (int, optional) \u2013 Batchsize when transmitting data to MyScale.\nDefaults to 32.\nmetadata (List[dict], optional) \u2013 metadata to texts. Defaults to None.\ninto (Other keyword arguments will pass) \u2013 [clickhouse-connect](https://clickhouse.com/docs/en/integrations/python#clickhouse-connect-driver-api)\nReturns\nMyScale Index\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScale.html"}
{"id": "aa3cb23dafcd-7", "text": "among selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a similarity search with MyScale\nParameters\nquery (str) \u2013 query string\nk (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScale.html"}
{"id": "aa3cb23dafcd-8", "text": "k (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.\nwhere_str (Optional[str], optional) \u2013 where condition string.\nDefaults to None.\nNOTE \u2013 Please do not let end-user to fill this and always be aware\nof SQL injection. When dealing with metadatas, remember to\nuse {self.metadata_column}.attribute instead of attribute\nalone. The default name for it is metadata.\nReturns\nList of Documents\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a similarity search with MyScale by vectors\nParameters\nquery (str) \u2013 query string\nk (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.\nwhere_str (Optional[str], optional) \u2013 where condition string.\nDefaults to None.\nNOTE \u2013 Please do not let end-user to fill this and always be aware\nof SQL injection. When dealing with metadatas, remember to\nuse {self.metadata_column}.attribute instead of attribute\nalone. The default name for it is metadata.\nReturns\nList of (Document, similarity)\nReturn type\nList[Document]\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPerform a similarity search with MyScale\nParameters\nquery (str) \u2013 query string\nk (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.\nwhere_str (Optional[str], optional) \u2013 where condition string.\nDefaults to None.\nNOTE \u2013 Please do not let end-user to fill this and always be aware", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScale.html"}
{"id": "aa3cb23dafcd-9", "text": "NOTE \u2013 Please do not let end-user to fill this and always be aware\nof SQL injection. When dealing with metadatas, remember to\nuse {self.metadata_column}.attribute instead of attribute\nalone. The default name for it is metadata.\nReturns\nList of documents most similar to the query text\nand cosine distance in float for each.\nLower score represents more similarity.\nReturn type\nList[Document]\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.\nExamples using MyScale\u00b6\nMyScale", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScale.html"}
{"id": "e0839866c1d6-0", "text": "langchain.vectorstores.weaviate.Weaviate\u00b6\nclass langchain.vectorstores.weaviate.Weaviate(client: ~typing.Any, index_name: str, text_key: str, embedding: ~typing.Optional[~langchain.schema.embeddings.Embeddings] = None, attributes: ~typing.Optional[~typing.List[str]] = None, relevance_score_fn: ~typing.Optional[~typing.Callable[[float], float]] = <function _default_score_normalizer>, by_text: bool = True)[source]\u00b6\nWeaviate vector store.\nTo use, you should have the weaviate-client python package installed.\nExample\nimport weaviate\nfrom langchain.vectorstores import Weaviate\nclient = weaviate.Client(url=os.environ[\"WEAVIATE_URL\"], ...)\nweaviate = Weaviate(client, index_name, text_key)\nInitialize with Weaviate client.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(client,\u00a0index_name,\u00a0text_key[,\u00a0...])\nInitialize with Weaviate client.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nUpload texts with metadata (properties) to Weaviate.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html"}
{"id": "e0839866c1d6-1", "text": "Return VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector IDs.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nConstruct Weaviate wrapper from raw documents.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_text(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nLook up similar documents by embedding vector in Weaviate.\nsimilarity_search_with_relevance_scores(query)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html"}
{"id": "e0839866c1d6-2", "text": "similarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nReturn list of documents most similar to the query text and cosine distance in float for each.\n__init__(client: ~typing.Any, index_name: str, text_key: str, embedding: ~typing.Optional[~langchain.schema.embeddings.Embeddings] = None, attributes: ~typing.Optional[~typing.List[str]] = None, relevance_score_fn: ~typing.Optional[~typing.Callable[[float], float]] = <function _default_score_normalizer>, by_text: bool = True)[source]\u00b6\nInitialize with Weaviate client.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nUpload texts with metadata (properties) to Weaviate.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html"}
{"id": "e0839866c1d6-3", "text": "Upload texts with metadata (properties) to Weaviate.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html"}
{"id": "e0839866c1d6-4", "text": "search_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html"}
{"id": "e0839866c1d6-5", "text": "Return docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDelete by vector IDs.\nParameters\nids \u2013 List of ids to delete.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html"}
{"id": "e0839866c1d6-6", "text": "Return VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, *, client: Optional[weaviate.Client] = None, weaviate_url: Optional[str] = None, weaviate_api_key: Optional[str] = None, batch_size: Optional[int] = None, index_name: Optional[str] = None, text_key: str = 'text', by_text: bool = False, relevance_score_fn: Optional[Callable[[float], float]] = <function _default_score_normalizer>, **kwargs: Any) \u2192 Weaviate[source]\u00b6\nConstruct Weaviate wrapper from raw documents.\nThis is a user-friendly interface that:\nEmbeds documents.\nCreates a new index for the embeddings in the Weaviate instance.\nAdds the documents to the newly created Weaviate index.\nThis is intended to be a quick way to get started.\nParameters\ntexts \u2013 Texts to add to vector store.\nembedding \u2013 Text embedding model to use.\nmetadatas \u2013 Metadata associated with each text.\nclient \u2013 weaviate.Client to use.\nweaviate_url \u2013 The Weaviate URL. If using Weaviate Cloud Services get it\nfrom the Details tab. Can be passed in as a named param or by\nsetting the environment variable WEAVIATE_URL. Should not be\nspecified if client is provided.\nweaviate_api_key \u2013 The Weaviate API key. If enabled and using Weaviate Cloud\nServices, get it from Details tab. Can be passed in as a named param\nor by setting the environment variable WEAVIATE_API_KEY. Should\nnot be specified if client is provided.\nbatch_size \u2013 Size of batch operations.\nindex_name \u2013 Index name.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html"}
{"id": "e0839866c1d6-7", "text": "batch_size \u2013 Size of batch operations.\nindex_name \u2013 Index name.\ntext_key \u2013 Key to use for uploading/retrieving text to/from vectorstore.\nby_text \u2013 Whether to search by text or by embedding.\nrelevance_score_fn \u2013 Function for converting whatever distance function the\nvector store uses to a relevance score, which is a normalized similarity\nscore (0 means dissimilar, 1 means similar).\n**kwargs \u2013 Additional named parameters to pass to Weaviate.__init__().\nExample\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import Weaviate\nembeddings = OpenAIEmbeddings()\nweaviate = Weaviate.from_texts(\n    texts,\n    embeddings,\n    weaviate_url=\"http://localhost:8080\"\n)\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html"}
{"id": "e0839866c1d6-8", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_text(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html"}
{"id": "e0839866c1d6-9", "text": "Returns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nLook up similar documents by embedding vector in Weaviate.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn list of documents most similar to the query\ntext and cosine distance in float for each.\nLower score represents more similarity.\nExamples using Weaviate\u00b6\nWeaviate", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.weaviate.Weaviate.html"}
{"id": "f7b359fd6a74-0", "text": "langchain.vectorstores.xata.XataVectorStore\u00b6\nclass langchain.vectorstores.xata.XataVectorStore(api_key: str, db_url: str, embedding: Embeddings, table_name: str)[source]\u00b6\nXata vector store.\nIt assumes you have a Xata database\ncreated with the right schema. See the guide at:\nhttps://integrations.langchain.com/vectorstores?integration_name=XataVectorStore\nInitialize with Xata client.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(api_key,\u00a0db_url,\u00a0embedding,\u00a0table_name)\nInitialize with Xata client.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadd_vectors(vectors,\u00a0documents[,\u00a0ids])\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.xata.XataVectorStore.html"}
{"id": "f7b359fd6a74-1", "text": "asearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids,\u00a0delete_all])\nDelete by vector IDs.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nRun similarity search with Chroma with distance.\nwait_for_indexing([timeout,\u00a0ndocs])\nWait for the search index to contain a certain number of documents.\n__init__(api_key: str, db_url: str, embedding: Embeddings, table_name: str) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.xata.XataVectorStore.html"}
{"id": "f7b359fd6a74-2", "text": "Initialize with Xata client.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[Dict[Any, Any]]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nadd_vectors(vectors: List[List[float]], documents: List[Document], ids: Optional[List[str]] = None) \u2192 List[str][source]\u00b6\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.xata.XataVectorStore.html"}
{"id": "f7b359fd6a74-3", "text": "**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.xata.XataVectorStore.html"}
{"id": "f7b359fd6a74-4", "text": "fetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.xata.XataVectorStore.html"}
{"id": "f7b359fd6a74-5", "text": "Return docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, delete_all: Optional[bool] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDelete by vector IDs.\nParameters\nids \u2013 List of ids to delete.\ndelete_all \u2013 Delete all records in the table.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, api_key: Optional[str] = None, db_url: Optional[str] = None, table_name: str = 'vectors', ids: Optional[List[str]] = None, **kwargs: Any) \u2192 XataVectorStore[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.xata.XataVectorStore.html"}
{"id": "f7b359fd6a74-6", "text": "Return VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.xata.XataVectorStore.html"}
{"id": "f7b359fd6a74-7", "text": "Return docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with Chroma with distance.\nParameters\nquery (str) \u2013 Query text to search for.\nk (int) \u2013 Number of results to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.xata.XataVectorStore.html"}
{"id": "f7b359fd6a74-8", "text": "k (int) \u2013 Number of results to return. Defaults to 4.\nfilter (Optional[dict]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of documents most similar to the querytext with distance in float.\nReturn type\nList[Tuple[Document, float]]\nwait_for_indexing(timeout: float = 5, ndocs: int = 1) \u2192 None[source]\u00b6\nWait for the search index to contain a certain number of\ndocuments. Useful in tests.\nExamples using XataVectorStore\u00b6\nXata chat memory\nXata", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.xata.XataVectorStore.html"}
{"id": "21899ea630ad-0", "text": "langchain.vectorstores.docarray.base.DocArrayIndex\u00b6\nclass langchain.vectorstores.docarray.base.DocArrayIndex(doc_index: BaseDocIndex, embedding: Embeddings)[source]\u00b6\nBase class for DocArray based vector stores.\nInitialize a vector store from DocArray\u2019s DocIndex.\nAttributes\ndoc_cls\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(doc_index,\u00a0embedding)\nInitialize a vector store from DocArray's DocIndex.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nEmbed texts and add to the vector store.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.base.DocArrayIndex.html"}
{"id": "21899ea630ad-1", "text": "Return docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nReturn docs most similar to query.\n__init__(doc_index: BaseDocIndex, embedding: Embeddings)[source]\u00b6\nInitialize a vector store from DocArray\u2019s DocIndex.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.base.DocArrayIndex.html"}
{"id": "21899ea630ad-2", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nEmbed texts and add to the vector store.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.base.DocArrayIndex.html"}
{"id": "21899ea630ad-3", "text": "Return VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.base.DocArrayIndex.html"}
{"id": "21899ea630ad-4", "text": ")\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.base.DocArrayIndex.html"}
{"id": "21899ea630ad-5", "text": "**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nabstract classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.base.DocArrayIndex.html"}
{"id": "21899ea630ad-6", "text": "of diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.base.DocArrayIndex.html"}
{"id": "21899ea630ad-7", "text": "k \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of documents most similar to the query text and\ncosine distance in float for each.\nLower score represents more similarity.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.base.DocArrayIndex.html"}
{"id": "6a4514ba9e42-0", "text": "langchain.vectorstores.pgembedding.QueryResult\u00b6\nclass langchain.vectorstores.pgembedding.QueryResult[source]\u00b6\nResult from a query.\nAttributes\nEmbeddingStore\ndistance\nMethods\n__init__()\n__init__()\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.QueryResult.html"}
{"id": "f7d96f3fda5e-0", "text": "langchain.vectorstores.starrocks.StarRocksSettings\u00b6\nclass langchain.vectorstores.starrocks.StarRocksSettings[source]\u00b6\nBases: BaseSettings\nStarRocks client configuration.\nAttribute:\nStarRocks_host (str)An URL to connect to MyScale backend.Defaults to \u2018localhost\u2019.\nStarRocks_port (int) : URL port to connect with HTTP. Defaults to 8443.\nusername (str) : Username to login. Defaults to None.\npassword (str) : Password to login. Defaults to None.\ndatabase (str) : Database name to find the table. Defaults to \u2018default\u2019.\ntable (str) : Table name to operate on.\nDefaults to \u2018vector_table\u2019.\ncolumn_map (Dict)Column type map to project column name onto langchainsemantics. Must have keys: text, id, vector,\nmust be same size to number of columns. For example:\n.. code-block:: python\n{\u2018id\u2019: \u2018text_id\u2019,\n\u2018embedding\u2019: \u2018text_embedding\u2019,\n\u2018document\u2019: \u2018text_plain\u2019,\n\u2018metadata\u2019: \u2018metadata_dictionary_in_json\u2019,\n}\nDefaults to identity map.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam column_map: Dict[str, str] = {'document': 'document', 'embedding': 'embedding', 'id': 'id', 'metadata': 'metadata'}\u00b6\nparam database: str = 'default'\u00b6\nparam host: str = 'localhost'\u00b6\nparam password: str = ''\u00b6\nparam port: int = 9030\u00b6\nparam table: str = 'langchain'\u00b6\nparam username: str = 'root'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocksSettings.html"}
{"id": "f7d96f3fda5e-1", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocksSettings.html"}
{"id": "f7d96f3fda5e-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using StarRocksSettings\u00b6\nStarRocks", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocksSettings.html"}
{"id": "fc0f4bdf237b-0", "text": "langchain.vectorstores.sklearn.SKLearnVectorStore\u00b6\nclass langchain.vectorstores.sklearn.SKLearnVectorStore(embedding: Embeddings, *, persist_path: Optional[str] = None, serializer: Literal['json', 'bson', 'parquet'] = 'json', metric: str = 'cosine', **kwargs: Any)[source]\u00b6\nSimple in-memory vector store based on the scikit-learn library\nNearestNeighbors implementation.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding,\u00a0*[,\u00a0persist_path,\u00a0...])\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.SKLearnVectorStore.html"}
{"id": "fc0f4bdf237b-1", "text": "asimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param query: Text to look up documents similar to. :param k: Number of Documents to return. Defaults to 4. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. :param lambda_mult: Number between 0 and 1 that determines the degree                     of diversity among the results with 0 corresponding                     to maximum diversity and 1 to minimum diversity. Defaults to 0.5.\nmax_marginal_relevance_search_by_vector(...)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.SKLearnVectorStore.html"}
{"id": "fc0f4bdf237b-2", "text": "max_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param embedding: Embedding to look up documents similar to. :param k: Number of Documents to return. Defaults to 4. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. :param lambda_mult: Number between 0 and 1 that determines the degree                     of diversity among the results with 0 corresponding                     to maximum diversity and 1 to minimum diversity. Defaults to 0.5.\npersist()\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query,\u00a0*[,\u00a0k])\nRun similarity search with distance.\n__init__(embedding: Embeddings, *, persist_path: Optional[str] = None, serializer: Literal['json', 'bson', 'parquet'] = 'json', metric: str = 'cosine', **kwargs: Any) \u2192 None[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.SKLearnVectorStore.html"}
{"id": "fc0f4bdf237b-3", "text": "Run more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.SKLearnVectorStore.html"}
{"id": "fc0f4bdf237b-4", "text": "Return VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.SKLearnVectorStore.html"}
{"id": "fc0f4bdf237b-5", "text": ")\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.SKLearnVectorStore.html"}
{"id": "fc0f4bdf237b-6", "text": "**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, persist_path: Optional[str] = None, **kwargs: Any) \u2192 SKLearnVectorStore[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\n:param query: Text to look up documents similar to.\n:param k: Number of Documents to return. Defaults to 4.\n:param fetch_k: Number of Documents to fetch to pass to MMR algorithm.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.SKLearnVectorStore.html"}
{"id": "fc0f4bdf237b-7", "text": ":param fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n:param lambda_mult: Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\n:param embedding: Embedding to look up documents similar to.\n:param k: Number of Documents to return. Defaults to 4.\n:param fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n:param lambda_mult: Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\npersist() \u2192 None[source]\u00b6\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.SKLearnVectorStore.html"}
{"id": "fc0f4bdf237b-8", "text": "Parameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, *, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with distance.\nExamples using SKLearnVectorStore\u00b6\nscikit-learn", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.SKLearnVectorStore.html"}
{"id": "13ff9de28090-0", "text": "langchain.vectorstores.supabase.SupabaseVectorStore\u00b6\nclass langchain.vectorstores.supabase.SupabaseVectorStore(client: supabase.client.Client, embedding: Embeddings, table_name: str, chunk_size: int = 500, query_name: Union[str, None] = None)[source]\u00b6\nSupabase Postgres vector store.\nIt assumes you have the pgvector\nextension installed and a match_documents (or similar) function. For more details:\nhttps://integrations.langchain.com/vectorstores?integration_name=SupabaseVectorStore\nYou can implement your own match_documents function in order to limit the search\nspace to a subset of documents based on your own authorization or business logic.\nNote that the Supabase Python client does not yet support async operations.\nIf you\u2019d like to use max_marginal_relevance_search, please review the instructions\nbelow on modifying the match_documents function to return matched embeddings.\nExamples:\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom langchain.schema import Document\nfrom langchain.vectorstores import SupabaseVectorStore\nfrom supabase.client import create_client\ndocs = [\n    Document(page_content=\"foo\", metadata={\"id\": 1}),\n]\nembeddings = OpenAIEmbeddings()\nsupabase_client = create_client(\"my_supabase_url\", \"my_supabase_key\")\nvector_store = SupabaseVectorStore.from_documents(\n    docs,\n    embeddings,\n    client=supabase_client,\n    table_name=\"documents\",\n    query_name=\"match_documents\",\n    chunk_size=500,\n)\nTo load from an existing table:\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom langchain.vectorstores import SupabaseVectorStore\nfrom supabase.client import create_client\nembeddings = OpenAIEmbeddings()", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html"}
{"id": "13ff9de28090-1", "text": "from supabase.client import create_client\nembeddings = OpenAIEmbeddings()\nsupabase_client = create_client(\"my_supabase_url\", \"my_supabase_key\")\nvector_store = SupabaseVectorStore(\n    client=supabase_client,\n    embedding=embeddings,\n    table_name=\"documents\",\n    query_name=\"match_documents\",\n)\nInitialize with supabase client.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(client,\u00a0embedding,\u00a0table_name[,\u00a0...])\nInitialize with supabase client.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadd_vectors(vectors,\u00a0documents,\u00a0ids)\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html"}
{"id": "13ff9de28090-2", "text": "asearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector IDs.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nmatch_args(query,\u00a0filter)\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_by_vector_returning_embeddings(...)\nsimilarity_search_by_vector_with_relevance_scores(...)\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html"}
{"id": "13ff9de28090-3", "text": "similarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\n__init__(client: supabase.client.Client, embedding: Embeddings, table_name: str, chunk_size: int = 500, query_name: Union[str, None] = None) \u2192 None[source]\u00b6\nInitialize with supabase client.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[Dict[Any, Any]]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html"}
{"id": "13ff9de28090-4", "text": "Returns\nList of ids from adding the texts into the vectorstore.\nadd_vectors(vectors: List[List[float]], documents: List[Document], ids: List[str]) \u2192 List[str][source]\u00b6\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html"}
{"id": "13ff9de28090-5", "text": "the Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html"}
{"id": "13ff9de28090-6", "text": "search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDelete by vector IDs.\nParameters\nids \u2013 List of ids to delete.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html"}
{"id": "13ff9de28090-7", "text": "Return VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, client: Optional[supabase.client.Client] = None, table_name: Optional[str] = 'documents', query_name: Union[str, None] = 'match_documents', chunk_size: int = 500, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 SupabaseVectorStore[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nmatch_args(query: List[float], filter: Optional[Dict[str, Any]]) \u2192 Dict[str, Any][source]\u00b6\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search requires that query_name returns matched\nembeddings alongside the match documents. The following function\ndemonstrates how to do this:\n```sql\nCREATE FUNCTION match_documents_embeddings(query_embedding vector(1536),\nmatch_count int)\nRETURNS TABLE(id uuid,\ncontent text,\nmetadata jsonb,\nembedding vector(1536),", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html"}
{"id": "13ff9de28090-8", "text": "content text,\nmetadata jsonb,\nembedding vector(1536),\nsimilarity float)\nLANGUAGE plpgsql\nAS $$\n# variable_conflict use_column\nBEGINRETURN query\nSELECT\nid,\ncontent,\nmetadata,\nembedding,\n1 -(docstore.embedding <=> query_embedding) AS similarity\nFROMdocstore\nORDER BYdocstore.embedding <=> query_embedding\nLIMIT match_count;\nEND;\n$$;\n```\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html"}
{"id": "13ff9de28090-9", "text": "Return docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_by_vector_returning_embeddings(query: List[float], k: int, filter: Optional[Dict[str, Any]] = None, postgrest_filter: Optional[str] = None) \u2192 List[Tuple[Document, float, ndarray[float32, Any]]][source]\u00b6\nsimilarity_search_by_vector_with_relevance_scores(query: List[float], k: int, filter: Optional[Dict[str, Any]] = None, postgrest_filter: Optional[str] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.\nExamples using SupabaseVectorStore\u00b6\nSupabase (Postgres)\nSupabase", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.supabase.SupabaseVectorStore.html"}
{"id": "2784bfd83076-0", "text": "langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch\u00b6\nclass langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch(opensearch_url: str, index_name: str, embedding_function: Embeddings, **kwargs: Any)[source]\u00b6\nAmazon OpenSearch Vector Engine vector store.\nExample\nfrom langchain.vectorstores import OpenSearchVectorSearch\nopensearch_vector_search = OpenSearchVectorSearch(\n    \"http://localhost:9200\",\n    \"embeddings\",\n    embedding_function\n)\nInitialize with necessary components.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(opensearch_url,\u00a0index_name,\u00a0...)\nInitialize with necessary components.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_embeddings(text_embeddings[,\u00a0metadatas,\u00a0...])\nAdd the given texts and embeddings to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0bulk_size])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch.html"}
{"id": "2784bfd83076-1", "text": "Return docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_embeddings(embeddings,\u00a0texts,\u00a0embedding)\nConstruct OpenSearchVectorSearch wrapper from pre-vectorized embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nConstruct OpenSearchVectorSearch wrapper from raw texts.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nReturn docs and it's scores most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch.html"}
{"id": "2784bfd83076-2", "text": "Return docs and it's scores most similar to query.\n__init__(opensearch_url: str, index_name: str, embedding_function: Embeddings, **kwargs: Any)[source]\u00b6\nInitialize with necessary components.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_embeddings(text_embeddings: Iterable[Tuple[str, List[float]]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, bulk_size: int = 500, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd the given texts and embeddings to the vectorstore.\nParameters\ntext_embeddings \u2013 Iterable pairs of string and embedding to\nadd to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of ids to associate with the texts.\nbulk_size \u2013 Bulk API request count; Default: 500\nReturns\nList of ids from adding the texts into the vectorstore.\nOptional Args:vector_field: Document field embeddings are stored in. Defaults to", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch.html"}
{"id": "2784bfd83076-3", "text": "Optional Args:vector_field: Document field embeddings are stored in. Defaults to\n\u201cvector_field\u201d.\ntext_field: Document field the text of the document is stored in. Defaults\nto \u201ctext\u201d.\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, bulk_size: int = 500, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of ids to associate with the texts.\nbulk_size \u2013 Bulk API request count; Default: 500\nReturns\nList of ids from adding the texts into the vectorstore.\nOptional Args:vector_field: Document field embeddings are stored in. Defaults to\n\u201cvector_field\u201d.\ntext_field: Document field the text of the document is stored in. Defaults\nto \u201ctext\u201d.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch.html"}
{"id": "2784bfd83076-4", "text": "Return VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch.html"}
{"id": "2784bfd83076-5", "text": ")\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch.html"}
{"id": "2784bfd83076-6", "text": "**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_embeddings(embeddings: List[List[float]], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, bulk_size: int = 500, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 OpenSearchVectorSearch[source]\u00b6\nConstruct OpenSearchVectorSearch wrapper from pre-vectorized embeddings.\nExample\nfrom langchain.vectorstores import OpenSearchVectorSearch\nfrom langchain.embeddings import OpenAIEmbeddings\nembedder = OpenAIEmbeddings()\nembeddings = embedder.embed_documents([\"foo\", \"bar\"])\nopensearch_vector_search = OpenSearchVectorSearch.from_embeddings(\n    embeddings,\n    texts,\n    embedder,\n    opensearch_url=\"http://localhost:9200\"\n)\nOpenSearch by default supports Approximate Search powered by nmslib, faiss", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch.html"}
{"id": "2784bfd83076-7", "text": ")\nOpenSearch by default supports Approximate Search powered by nmslib, faiss\nand lucene engines recommended for large datasets. Also supports brute force\nsearch through Script Scoring and Painless Scripting.\nOptional Args:vector_field: Document field embeddings are stored in. Defaults to\n\u201cvector_field\u201d.\ntext_field: Document field the text of the document is stored in. Defaults\nto \u201ctext\u201d.\nOptional Keyword Args for Approximate Search:engine: \u201cnmslib\u201d, \u201cfaiss\u201d, \u201clucene\u201d; default: \u201cnmslib\u201d\nspace_type: \u201cl2\u201d, \u201cl1\u201d, \u201ccosinesimil\u201d, \u201clinf\u201d, \u201cinnerproduct\u201d; default: \u201cl2\u201d\nef_search: Size of the dynamic list used during k-NN searches. Higher values\nlead to more accurate but slower searches; default: 512\nef_construction: Size of the dynamic list used during k-NN graph creation.\nHigher values lead to more accurate graph but slower indexing speed;\ndefault: 512\nm: Number of bidirectional links created for each new element. Large impact\non memory consumption. Between 2 and 100; default: 16\nKeyword Args for Script Scoring or Painless Scripting:is_appx_search: False\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, bulk_size: int = 500, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 OpenSearchVectorSearch[source]\u00b6\nConstruct OpenSearchVectorSearch wrapper from raw texts.\nExample\nfrom langchain.vectorstores import OpenSearchVectorSearch\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nopensearch_vector_search = OpenSearchVectorSearch.from_texts(\n    texts,\n    embeddings,", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch.html"}
{"id": "2784bfd83076-8", "text": "texts,\n    embeddings,\n    opensearch_url=\"http://localhost:9200\"\n)\nOpenSearch by default supports Approximate Search powered by nmslib, faiss\nand lucene engines recommended for large datasets. Also supports brute force\nsearch through Script Scoring and Painless Scripting.\nOptional Args:vector_field: Document field embeddings are stored in. Defaults to\n\u201cvector_field\u201d.\ntext_field: Document field the text of the document is stored in. Defaults\nto \u201ctext\u201d.\nOptional Keyword Args for Approximate Search:engine: \u201cnmslib\u201d, \u201cfaiss\u201d, \u201clucene\u201d; default: \u201cnmslib\u201d\nspace_type: \u201cl2\u201d, \u201cl1\u201d, \u201ccosinesimil\u201d, \u201clinf\u201d, \u201cinnerproduct\u201d; default: \u201cl2\u201d\nef_search: Size of the dynamic list used during k-NN searches. Higher values\nlead to more accurate but slower searches; default: 512\nef_construction: Size of the dynamic list used during k-NN graph creation.\nHigher values lead to more accurate graph but slower indexing speed;\ndefault: 512\nm: Number of bidirectional links created for each new element. Large impact\non memory consumption. Between 2 and 100; default: 16\nKeyword Args for Script Scoring or Painless Scripting:is_appx_search: False\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 list[langchain.schema.document.Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch.html"}
{"id": "2784bfd83076-9", "text": "k \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nDefaults to 20.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nBy default, supports Approximate Search.\nAlso supports Script Scoring and Painless Scripting.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch.html"}
{"id": "2784bfd83076-10", "text": "k \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query.\nOptional Args:vector_field: Document field embeddings are stored in. Defaults to\n\u201cvector_field\u201d.\ntext_field: Document field the text of the document is stored in. Defaults\nto \u201ctext\u201d.\nmetadata_field: Document field that metadata is stored in. Defaults to\n\u201cmetadata\u201d.\nCan be set to a special value \u201c*\u201d to include the entire document.\nOptional Args for Approximate Search:search_type: \u201capproximate_search\u201d; default: \u201capproximate_search\u201d\nboolean_filter: A Boolean filter is a post filter consists of a Boolean\nquery that contains a k-NN query and a filter.\nsubquery_clause: Query clause on the knn vector field; default: \u201cmust\u201d\nlucene_filter: the Lucene algorithm decides whether to perform an exact\nk-NN search with pre-filtering or an approximate search with modified\npost-filtering. (deprecated, use efficient_filter)\nefficient_filter: the Lucene Engine or Faiss Engine decides whether to\nperform an exact k-NN search with pre-filtering or an approximate search\nwith modified post-filtering.\nOptional Args for Script Scoring Search:search_type: \u201cscript_scoring\u201d; default: \u201capproximate_search\u201d\nspace_type: \u201cl2\u201d, \u201cl1\u201d, \u201clinf\u201d, \u201ccosinesimil\u201d, \u201cinnerproduct\u201d,\n\u201chammingbit\u201d; default: \u201cl2\u201d\npre_filter: script_score query to pre-filter documents before identifying\nnearest neighbors; default: {\u201cmatch_all\u201d: {}}\nOptional Args for Painless Scripting Search:search_type: \u201cpainless_scripting\u201d; default: \u201capproximate_search\u201d\nspace_type: \u201cl2Squared\u201d, \u201cl1Norm\u201d, \u201ccosineSimilarity\u201d; default: \u201cl2Squared\u201d", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch.html"}
{"id": "2784bfd83076-11", "text": "pre_filter: script_score query to pre-filter documents before identifying\nnearest neighbors; default: {\u201cmatch_all\u201d: {}}\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs and it\u2019s scores most similar to query.\nBy default, supports Approximate Search.\nAlso supports Script Scoring and Painless Scripting.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents along with its scores most similar to the query.\nOptional Args:same as similarity_search\nExamples using OpenSearchVectorSearch\u00b6\nOpenSearch", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.opensearch_vector_search.OpenSearchVectorSearch.html"}
{"id": "0bd47ee51b3a-0", "text": "langchain.vectorstores.tencentvectordb.TencentVectorDB\u00b6\nclass langchain.vectorstores.tencentvectordb.TencentVectorDB(embedding: ~langchain.schema.embeddings.Embeddings, connection_params: ~langchain.vectorstores.tencentvectordb.ConnectionParams, index_params: ~langchain.vectorstores.tencentvectordb.IndexParams = <langchain.vectorstores.tencentvectordb.IndexParams object>, database_name: str = 'LangChainDatabase', collection_name: str = 'LangChainCollection', drop_old: ~typing.Optional[bool] = False)[source]\u00b6\nInitialize wrapper around the tencent vector database.\nIn order to use this you need to have a database instance.\nSee the following documentation for details:\nhttps://cloud.tencent.com/document/product/1709/94951\nAttributes\nembeddings\nAccess the query embedding object if available.\nfield_id\nfield_metadata\nfield_text\nfield_vector\nMethods\n__init__(embedding,\u00a0connection_params[,\u00a0...])\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0timeout,\u00a0...])\nInsert text data into TencentVectorDB.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tencentvectordb.TencentVectorDB.html"}
{"id": "0bd47ee51b3a-1", "text": "Return docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreate a collection, indexes it with HNSW, and insert data.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nPerform a search and return results that are reordered by MMR.\nmax_marginal_relevance_search_by_vector(...)\nPerform a search and return results that are reordered by MMR.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0param,\u00a0expr,\u00a0...])\nPerform a similarity search against the query string.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nPerform a similarity search against the query string.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tencentvectordb.TencentVectorDB.html"}
{"id": "0bd47ee51b3a-2", "text": "Return docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nPerform a search on a query string and return results with score.\nsimilarity_search_with_score_by_vector(embedding)\nPerform a search on a query string and return results with score.\n__init__(embedding: ~langchain.schema.embeddings.Embeddings, connection_params: ~langchain.vectorstores.tencentvectordb.ConnectionParams, index_params: ~langchain.vectorstores.tencentvectordb.IndexParams = <langchain.vectorstores.tencentvectordb.IndexParams object>, database_name: str = 'LangChainDatabase', collection_name: str = 'LangChainCollection', drop_old: ~typing.Optional[bool] = False)[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tencentvectordb.TencentVectorDB.html"}
{"id": "0bd47ee51b3a-3", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, timeout: Optional[int] = None, batch_size: int = 1000, **kwargs: Any) \u2192 List[str][source]\u00b6\nInsert text data into TencentVectorDB.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tencentvectordb.TencentVectorDB.html"}
{"id": "0bd47ee51b3a-4", "text": "Return VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tencentvectordb.TencentVectorDB.html"}
{"id": "0bd47ee51b3a-5", "text": "docsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tencentvectordb.TencentVectorDB.html"}
{"id": "0bd47ee51b3a-6", "text": "False otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, connection_params: Optional[ConnectionParams] = None, index_params: Optional[IndexParams] = None, database_name: str = 'LangChainDatabase', collection_name: str = 'LangChainCollection', drop_old: Optional[bool] = False, **kwargs: Any) \u2192 TencentVectorDB[source]\u00b6\nCreate a collection, indexes it with HNSW, and insert data.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a search and return results that are reordered by MMR.\nmax_marginal_relevance_search_by_vector(embedding: list[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a search and return results that are reordered by MMR.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tencentvectordb.TencentVectorDB.html"}
{"id": "0bd47ee51b3a-7", "text": "Return docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a similarity search against the query string.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a similarity search against the query string.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPerform a search on a query string and return results with score.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tencentvectordb.TencentVectorDB.html"}
{"id": "0bd47ee51b3a-8", "text": "Perform a search on a query string and return results with score.\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPerform a search on a query string and return results with score.\nExamples using TencentVectorDB\u00b6\nTencentVectorDB\nTencent Cloud VectorDB", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tencentvectordb.TencentVectorDB.html"}
{"id": "2f1e286c89d2-0", "text": "langchain.vectorstores.zep.CollectionConfig\u00b6\nclass langchain.vectorstores.zep.CollectionConfig(name: str, description: Optional[str], metadata: Optional[Dict[str, Any]], embedding_dimensions: int, is_auto_embedded: bool)[source]\u00b6\nConfiguration for a Zep Collection.\nIf the collection does not exist, it will be created.\nname\u00b6\nThe name of the collection.\nType\nstr\ndescription\u00b6\nAn optional description of the collection.\nType\nOptional[str]\nmetadata\u00b6\nOptional metadata for the collection.\nType\nOptional[Dict[str, Any]]\nembedding_dimensions\u00b6\nThe number of dimensions for the embeddings in\nthe collection. This should match the Zep server configuration\nif auto-embed is true.\nType\nint\nis_auto_embedded\u00b6\nA flag indicating whether the collection is\nautomatically embedded by Zep.\nType\nbool\nAttributes\nname\ndescription\nmetadata\nembedding_dimensions\nis_auto_embedded\nMethods\n__init__(name,\u00a0description,\u00a0metadata,\u00a0...)\n__init__(name: str, description: Optional[str], metadata: Optional[Dict[str, Any]], embedding_dimensions: int, is_auto_embedded: bool) \u2192 None\u00b6\nExamples using CollectionConfig\u00b6\nZep", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zep.CollectionConfig.html"}
{"id": "1ec3fb9d509b-0", "text": "langchain.vectorstores.tiledb.get_vector_index_uri_from_group\u00b6\nlangchain.vectorstores.tiledb.get_vector_index_uri_from_group(group: Any) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.get_vector_index_uri_from_group.html"}
{"id": "bb1468a98997-0", "text": "langchain.vectorstores.matching_engine.MatchingEngine\u00b6\nclass langchain.vectorstores.matching_engine.MatchingEngine(project_id: str, index: MatchingEngineIndex, endpoint: MatchingEngineIndexEndpoint, embedding: Embeddings, gcs_client: storage.Client, gcs_bucket_name: str, credentials: Optional[Credentials] = None)[source]\u00b6\nGoogle Vertex AI Matching Engine vector store.\nWhile the embeddings are stored in the Matching Engine, the embedded\ndocuments will be stored in GCS.\nAn existing Index and corresponding Endpoint are preconditions for\nusing this module.\nSee usage in docs/modules/indexes/vectorstores/examples/matchingengine.ipynb\nNote that this implementation is mostly meant for reading if you are\nplanning to do a real time implementation. While reading is a real time\noperation, updating the index takes close to one hour.\nVertex Matching Engine implementation of the vector store.\nWhile the embeddings are stored in the Matching Engine, the embedded\ndocuments will be stored in GCS.\nAn existing Index and corresponding Endpoint are preconditions for\nusing this module.\nSee usage in\ndocs/modules/indexes/vectorstores/examples/matchingengine.ipynb.\nNote that this implementation is mostly meant for reading if you are\nplanning to do a real time implementation. While reading is a real time\noperation, updating the index takes close to one hour.\nproject_id\u00b6\nThe GCS project id.\nindex\u00b6\nThe created index class. See\n~:func:MatchingEngine.from_components.\nendpoint\u00b6\nThe created endpoint class. See\n~:func:MatchingEngine.from_components.\nembedding\u00b6\nA Embeddings that will be used for\nembedding the text sent. If none is sent, then the\nmultilingual Tensorflow Universal Sentence Encoder will be used.\ngcs_client\u00b6\nThe GCS client.\ngcs_bucket_name\u00b6\nThe GCS bucket name.\ncredentials\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.matching_engine.MatchingEngine.html"}
{"id": "bb1468a98997-1", "text": "gcs_bucket_name\u00b6\nThe GCS bucket name.\ncredentials\u00b6\nCreated GCP credentials.\nType\nOptional\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(project_id,\u00a0index,\u00a0endpoint,\u00a0...[,\u00a0...])\nVertex Matching Engine implementation of the vector store.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.matching_engine.MatchingEngine.html"}
{"id": "bb1468a98997-2", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_components(project_id,\u00a0region,\u00a0...[,\u00a0...])\nTakes the object creation out of the constructor.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nUse from components instead.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to the embedding.\nsimilarity_search_by_vector_with_score(embedding)\nReturn docs most similar to the embedding and their cosine distance.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query and their cosine distance from the query.\n__init__(project_id: str, index: MatchingEngineIndex, endpoint: MatchingEngineIndexEndpoint, embedding: Embeddings, gcs_client: storage.Client, gcs_bucket_name: str, credentials: Optional[Credentials] = None)[source]\u00b6\nVertex Matching Engine implementation of the vector store.\nWhile the embeddings are stored in the Matching Engine, the embedded\ndocuments will be stored in GCS.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.matching_engine.MatchingEngine.html"}
{"id": "bb1468a98997-3", "text": "documents will be stored in GCS.\nAn existing Index and corresponding Endpoint are preconditions for\nusing this module.\nSee usage in\ndocs/modules/indexes/vectorstores/examples/matchingengine.ipynb.\nNote that this implementation is mostly meant for reading if you are\nplanning to do a real time implementation. While reading is a real time\noperation, updating the index takes close to one hour.\nproject_id\u00b6\nThe GCS project id.\nindex\u00b6\nThe created index class. See\n~:func:MatchingEngine.from_components.\nendpoint\u00b6\nThe created endpoint class. See\n~:func:MatchingEngine.from_components.\nembedding\u00b6\nA Embeddings that will be used for\nembedding the text sent. If none is sent, then the\nmultilingual Tensorflow Universal Sentence Encoder will be used.\ngcs_client\u00b6\nThe GCS client.\ngcs_bucket_name\u00b6\nThe GCS bucket name.\ncredentials\u00b6\nCreated GCP credentials.\nType\nOptional\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.matching_engine.MatchingEngine.html"}
{"id": "bb1468a98997-4", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.matching_engine.MatchingEngine.html"}
{"id": "bb1468a98997-5", "text": "Return docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.matching_engine.MatchingEngine.html"}
{"id": "bb1468a98997-6", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.matching_engine.MatchingEngine.html"}
{"id": "bb1468a98997-7", "text": "Returns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_components(project_id: str, region: str, gcs_bucket_name: str, index_id: str, endpoint_id: str, credentials_path: Optional[str] = None, embedding: Optional[Embeddings] = None) \u2192 MatchingEngine[source]\u00b6\nTakes the object creation out of the constructor.\nParameters\nproject_id \u2013 The GCP project id.\nregion \u2013 The default location making the API calls. It must have\nregional. (the same location as the GCS bucket and must be) \u2013 \ngcs_bucket_name \u2013 The location where the vectors will be stored in\ncreated. (order for the index to be) \u2013 \nindex_id \u2013 The id of the created index.\nendpoint_id \u2013 The id of the created endpoint.\ncredentials_path \u2013 (Optional) The path of the Google credentials on\nsystem. (the local file) \u2013 \nembedding \u2013 The Embeddings that will be used for\ntexts. (embedding the) \u2013 \nReturns\nA configured MatchingEngine with the texts added to the index.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.matching_engine.MatchingEngine.html"}
{"id": "bb1468a98997-8", "text": "Return VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 MatchingEngine[source]\u00b6\nUse from components instead.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.matching_engine.MatchingEngine.html"}
{"id": "bb1468a98997-9", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[List[Namespace]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 The string that will be used to search for similar documents.\nk \u2013 The amount of neighbors that will be retrieved.\nfilter \u2013 Optional. A list of Namespaces for filtering the matching results.\nFor example:\n[Namespace(\u201ccolor\u201d, [\u201cred\u201d], []), Namespace(\u201cshape\u201d, [], [\u201csquared\u201d])]\nwill match datapoints that satisfy \u201cred color\u201d but not include\ndatapoints with \u201csquared shape\u201d. Please refer to\nhttps://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json\nfor more detail.\nReturns\nA list of k matching documents.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[List[Namespace]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to the embedding.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 The amount of neighbors that will be retrieved.\nfilter \u2013 Optional. A list of Namespaces for filtering the matching results.\nFor example:\n[Namespace(\u201ccolor\u201d, [\u201cred\u201d], []), Namespace(\u201cshape\u201d, [], [\u201csquared\u201d])]\nwill match datapoints that satisfy \u201cred color\u201d but not include\ndatapoints with \u201csquared shape\u201d. Please refer to", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.matching_engine.MatchingEngine.html"}
{"id": "bb1468a98997-10", "text": "datapoints with \u201csquared shape\u201d. Please refer to\nhttps://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json\nfor more detail.\nReturns\nA list of k matching documents.\nsimilarity_search_by_vector_with_score(embedding: List[float], k: int = 4, filter: Optional[List[Namespace]] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to the embedding and their cosine distance.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Optional. A list of Namespaces for filtering\nthe matching results.\nFor example:\n[Namespace(\u201ccolor\u201d, [\u201cred\u201d], []), Namespace(\u201cshape\u201d, [], [\u201csquared\u201d])]\nwill match datapoints that satisfy \u201cred color\u201d but not include\ndatapoints with \u201csquared shape\u201d. Please refer to\nhttps://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json\nfor more detail.\nReturns\nList of documents most similar to\nthe query text and cosine distance in float for each.\nLower score represents more similarity.\nReturn type\nList[Tuple[Document, float]]\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.matching_engine.MatchingEngine.html"}
{"id": "bb1468a98997-11", "text": "filter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[List[Namespace]] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query and their cosine distance from the query.\nParameters\nquery \u2013 String query look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Optional. A list of Namespaces for filtering\nthe matching results.\nFor example:\n[Namespace(\u201ccolor\u201d, [\u201cred\u201d], []), Namespace(\u201cshape\u201d, [], [\u201csquared\u201d])]\nwill match datapoints that satisfy \u201cred color\u201d but not include\ndatapoints with \u201csquared shape\u201d. Please refer to\nhttps://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json\nfor more detail.\nReturns\nList of documents most similar to\nthe query text and cosine distance in float for each.\nLower score represents more similarity.\nReturn type\nList[Tuple[Document, float]]\nExamples using MatchingEngine\u00b6\nGoogle Vertex AI MatchingEngine", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.matching_engine.MatchingEngine.html"}
{"id": "3c70074abbe6-0", "text": "langchain.vectorstores.elastic_vector_search.ElasticVectorSearch\u00b6\nclass langchain.vectorstores.elastic_vector_search.ElasticVectorSearch(elasticsearch_url: str, index_name: str, embedding: Embeddings, *, ssl_verify: Optional[Dict[str, Any]] = None)[source]\u00b6\nElasticVectorSearch uses the brute force method of searching on vectors.\nRecommended to use ElasticsearchStore instead, which gives you the option\nto uses the approx  HNSW algorithm which performs better on large datasets.\nElasticsearchStore also supports metadata filtering, customising the\nquery retriever and much more!\nYou can read more on ElasticsearchStore:\nhttps://python.langchain.com/docs/integrations/vectorstores/elasticsearch\nTo connect to an Elasticsearch instance that does not require\nlogin credentials, pass the Elasticsearch URL and index name along with the\nembedding object to the constructor.\nExample\nfrom langchain.vectorstores import ElasticVectorSearch\nfrom langchain.embeddings import OpenAIEmbeddings\nembedding = OpenAIEmbeddings()\nelastic_vector_search = ElasticVectorSearch(\n    elasticsearch_url=\"http://localhost:9200\",\n    index_name=\"test_index\",\n    embedding=embedding\n)\nTo connect to an Elasticsearch instance that requires login credentials,\nincluding Elastic Cloud, use the Elasticsearch URL format\nhttps://username:password@es_host:9243. For example, to connect to Elastic\nCloud, create the Elasticsearch URL with the required authentication details and\npass it to the ElasticVectorSearch constructor as the named parameter\nelasticsearch_url.\nYou can obtain your Elastic Cloud URL and login credentials by logging in to the\nElastic Cloud console at https://cloud.elastic.co, selecting your deployment, and\nnavigating to the \u201cDeployments\u201d page.\nTo obtain your Elastic Cloud password for the default \u201celastic\u201d user:\nLog in to the Elastic Cloud console at https://cloud.elastic.co", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticVectorSearch.html"}
{"id": "3c70074abbe6-1", "text": "Log in to the Elastic Cloud console at https://cloud.elastic.co\nGo to \u201cSecurity\u201d > \u201cUsers\u201d\nLocate the \u201celastic\u201d user and click \u201cEdit\u201d\nClick \u201cReset password\u201d\nFollow the prompts to reset the password\nThe format for Elastic Cloud URLs is\nhttps://username:password@cluster_id.region_id.gcp.cloud.es.io:9243.\nExample\nfrom langchain.vectorstores import ElasticVectorSearch\nfrom langchain.embeddings import OpenAIEmbeddings\nembedding = OpenAIEmbeddings()\nelastic_host = \"cluster_id.region_id.gcp.cloud.es.io\"\nelasticsearch_url = f\"https://username:password@{elastic_host}:9243\"\nelastic_vector_search = ElasticVectorSearch(\n    elasticsearch_url=elasticsearch_url,\n    index_name=\"test_index\",\n    embedding=embedding\n)\nParameters\nelasticsearch_url (str) \u2013 The URL for the Elasticsearch instance.\nindex_name (str) \u2013 The name of the Elasticsearch index for the embeddings.\nembedding (Embeddings) \u2013 An object that provides the ability to embed text.\nIt should be an instance of a class that subclasses the Embeddings\nabstract base class, such as OpenAIEmbeddings()\nRaises\nValueError \u2013 If the elasticsearch python package is not installed.\nInitialize with necessary components.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(elasticsearch_url,\u00a0index_name,\u00a0...)\nInitialize with necessary components.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticVectorSearch.html"}
{"id": "3c70074abbe6-2", "text": "Run more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0...])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\nclient_search(client,\u00a0index_name,\u00a0...)\ncreate_index(client,\u00a0index_name,\u00a0mapping)\ndelete([ids])\nDelete by vector IDs.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nConstruct ElasticVectorSearch wrapper from raw documents.\nget_user_agent()\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticVectorSearch.html"}
{"id": "3c70074abbe6-3", "text": "max_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\n__init__(elasticsearch_url: str, index_name: str, embedding: Embeddings, *, ssl_verify: Optional[Dict[str, Any]] = None)[source]\u00b6\nInitialize with necessary components.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticVectorSearch.html"}
{"id": "3c70074abbe6-4", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, refresh_indices: bool = True, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of unique IDs.\nrefresh_indices \u2013 bool to refresh ElasticSearch indices\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticVectorSearch.html"}
{"id": "3c70074abbe6-5", "text": "Return docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticVectorSearch.html"}
{"id": "3c70074abbe6-6", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticVectorSearch.html"}
{"id": "3c70074abbe6-7", "text": "Returns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\nclient_search(client: Any, index_name: str, script_query: Dict, size: int) \u2192 Any[source]\u00b6\ncreate_index(client: Any, index_name: str, mapping: Dict) \u2192 None[source]\u00b6\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDelete by vector IDs.\nParameters\nids \u2013 List of ids to delete.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, index_name: Optional[str] = None, refresh_indices: bool = True, **kwargs: Any) \u2192 ElasticVectorSearch[source]\u00b6\nConstruct ElasticVectorSearch wrapper from raw documents.\nThis is a user-friendly interface that:\nEmbeds documents.\nCreates a new index for the embeddings in the Elasticsearch instance.\nAdds the documents to the newly created Elasticsearch index.\nThis is intended to be a quick way to get started.\nExample\nfrom langchain.vectorstores import ElasticVectorSearch\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nelastic_vector_search = ElasticVectorSearch.from_texts(\n    texts,\n    embeddings,\n    elasticsearch_url=\"http://localhost:9200\"\n)\nstatic get_user_agent() \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticVectorSearch.html"}
{"id": "3c70074abbe6-8", "text": ")\nstatic get_user_agent() \u2192 str[source]\u00b6\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticVectorSearch.html"}
{"id": "3c70074abbe6-9", "text": "Return docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\n:param query: Text to look up documents similar to.\n:param k: Number of Documents to return. Defaults to 4.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticVectorSearch.html"}
{"id": "3c70074abbe6-10", "text": ":param k: Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query.\nExamples using ElasticVectorSearch\u00b6\nElasticsearch\nMemory in the Multi-Input Chain", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticVectorSearch.html"}
{"id": "fd5318317f8c-0", "text": "langchain.vectorstores.tiledb.TileDB\u00b6\nclass langchain.vectorstores.tiledb.TileDB(embedding: Embeddings, index_uri: str, metric: str, *, vector_index_uri: str = '', docs_array_uri: str = '', config: Optional[Mapping[str, Any]] = None, timestamp: Any = None, **kwargs: Any)[source]\u00b6\nWrapper around TileDB vector database.\nTo use, you should have the tiledb-vector-search python package installed.\nExample\nfrom langchain import TileDB\nembeddings = OpenAIEmbeddings()\ndb = TileDB(embeddings, index_uri, metric)\nInitialize with necessary components.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding,\u00a0index_uri,\u00a0metric,\u00a0*[,\u00a0...])\nInitialize with necessary components.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0timestamp])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.TileDB.html"}
{"id": "fd5318317f8c-1", "text": "Return docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\nconsolidate_updates(**kwargs)\ncreate(index_uri,\u00a0index_type,\u00a0dimensions,\u00a0...)\ndelete([ids,\u00a0timestamp])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_embeddings(text_embeddings,\u00a0embedding,\u00a0...)\nConstruct TileDB index from embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nConstruct a TileDB index from raw documents.\nload(index_uri,\u00a0embedding,\u00a0*[,\u00a0metric,\u00a0...])\nLoad a TileDB index from a URI.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_with_score_by_vector(...)\nReturn docs and their similarity scores selected using the maximal marginal\nprocess_index_results(ids,\u00a0scores,\u00a0*[,\u00a0k,\u00a0...])\nTurns TileDB results into a list of documents and scores.\nsearch(query,\u00a0search_type,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.TileDB.html"}
{"id": "fd5318317f8c-2", "text": "search(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter,\u00a0fetch_k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query,\u00a0*[,\u00a0k,\u00a0...])\nReturn docs most similar to query.\nsimilarity_search_with_score_by_vector(...)\nReturn docs most similar to query.\n__init__(embedding: Embeddings, index_uri: str, metric: str, *, vector_index_uri: str = '', docs_array_uri: str = '', config: Optional[Mapping[str, Any]] = None, timestamp: Any = None, **kwargs: Any)[source]\u00b6\nInitialize with necessary components.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.TileDB.html"}
{"id": "fd5318317f8c-3", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, timestamp: int = 0, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional ids of each text object.\ntimestamp \u2013 Optional timestamp to write new texts with.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.TileDB.html"}
{"id": "fd5318317f8c-4", "text": "Return docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.TileDB.html"}
{"id": "fd5318317f8c-5", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.TileDB.html"}
{"id": "fd5318317f8c-6", "text": "Returns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\nconsolidate_updates(**kwargs: Any) \u2192 None[source]\u00b6\nclassmethod create(index_uri: str, index_type: str, dimensions: int, vector_type: dtype, *, metadatas: bool = True, config: Optional[Mapping[str, Any]] = None) \u2192 None[source]\u00b6\ndelete(ids: Optional[List[str]] = None, timestamp: int = 0, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\ntimestamp \u2013 Optional timestamp to delete with.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_embeddings(text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, index_uri: str, *, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, metric: str = 'euclidean', index_type: str = 'FLAT', config: Optional[Mapping[str, Any]] = None, index_timestamp: int = 0, **kwargs: Any) \u2192 TileDB[source]\u00b6\nConstruct TileDB index from embeddings.\nParameters\ntext_embeddings \u2013 List of tuples of (text, embedding)\nembedding \u2013 Embedding function to use.\nindex_uri \u2013 The URI to write the TileDB arrays\nmetadatas \u2013 List of metadata dictionaries to associate with documents.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.TileDB.html"}
{"id": "fd5318317f8c-7", "text": "metadatas \u2013 List of metadata dictionaries to associate with documents.\nmetric \u2013 Optional, Metric to use for indexing. Defaults to \u201ceuclidean\u201d.\nindex_type \u2013 Optional, Vector index type (\u201cFLAT\u201d, IVF_FLAT\u201d)\nconfig \u2013 Optional, TileDB config\nindex_timestamp \u2013 Optional, timestamp to write new texts with.\nExample\nfrom langchain import TileDB\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\ntext_embeddings = embeddings.embed_documents(texts)\ntext_embedding_pairs = list(zip(texts, text_embeddings))\ndb = TileDB.from_embeddings(text_embedding_pairs, embeddings)\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, metric: str = 'euclidean', index_uri: str = '/tmp/tiledb_array', index_type: str = 'FLAT', config: Optional[Mapping[str, Any]] = None, index_timestamp: int = 0, **kwargs: Any) \u2192 TileDB[source]\u00b6\nConstruct a TileDB index from raw documents.\nParameters\ntexts \u2013 List of documents to index.\nembedding \u2013 Embedding function to use.\nmetadatas \u2013 List of metadata dictionaries to associate with documents.\nids \u2013 Optional ids of each text object.\nmetric \u2013 Metric to use for indexing. Defaults to \u201ceuclidean\u201d.\nindex_uri \u2013 The URI to write the TileDB arrays\nindex_type \u2013 Optional,  Vector index type (\u201cFLAT\u201d, IVF_FLAT\u201d)\nconfig \u2013 Optional, TileDB config\nindex_timestamp \u2013 Optional, timestamp to write new texts with.\nExample\nfrom langchain import TileDB\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nindex = TileDB.from_texts(texts, embeddings)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.TileDB.html"}
{"id": "fd5318317f8c-8", "text": "index = TileDB.from_texts(texts, embeddings)\nclassmethod load(index_uri: str, embedding: Embeddings, *, metric: str = 'euclidean', config: Optional[Mapping[str, Any]] = None, timestamp: Any = None, **kwargs: Any) \u2192 TileDB[source]\u00b6\nLoad a TileDB index from a URI.\nParameters\nindex_uri \u2013 The URI of the TileDB vector index.\nembedding \u2013 Embeddings to use when generating queries.\nmetric \u2013 Optional, Metric to use for indexing. Defaults to \u201ceuclidean\u201d.\nconfig \u2013 Optional, TileDB config\ntimestamp \u2013 Optional, timestamp to use for opening the arrays.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch before filtering (if needed) to\npass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.TileDB.html"}
{"id": "fd5318317f8c-9", "text": "Return docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch before filtering to\npass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_with_score_by_vector(embedding: List[float], *, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs and their similarity scores selected using the maximal marginalrelevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch before filtering to\npass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents and similarity scores selected by maximal marginalrelevance and score for each.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.TileDB.html"}
{"id": "fd5318317f8c-10", "text": "Returns\nList of Documents and similarity scores selected by maximal marginalrelevance and score for each.\nprocess_index_results(ids: List[int], scores: List[float], *, k: int = 4, filter: Optional[Dict[str, Any]] = None, score_threshold: float = 1.7976931348623157e+308) \u2192 List[Tuple[Document, float]][source]\u00b6\nTurns TileDB results into a list of documents and scores.\nParameters\nids \u2013 List of indices of the documents in the index.\nscores \u2013 List of distances of the documents in the index.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, Any]]) \u2013 Filter by metadata. Defaults to None.\nscore_threshold \u2013 Optional, a floating point value to filter the\nresulting set of retrieved docs\nReturns\nList of Documents and scores.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\nReturns\nList of Documents most similar to the query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.TileDB.html"}
{"id": "fd5318317f8c-11", "text": "Defaults to 20.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\nReturns\nList of Documents most similar to the embedding.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, *, k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.TileDB.html"}
{"id": "fd5318317f8c-12", "text": "k \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\nReturns\nList of documents most similar to the query text with\nDistance as float. Lower score represents more similarity.\nsimilarity_search_with_score_by_vector(embedding: List[float], *, k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nembedding \u2013 Embedding vector to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, Any]]) \u2013 Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\n**kwargs \u2013 kwargs to be passed to similarity search. Can include:\nnprobe: Optional, number of partitions to check if using IVF_FLAT index\nscore_threshold: Optional, a floating point value to filter the\nresulting set of retrieved docs\nReturns\nList of documents most similar to the query text and distance\nin float for each. Lower score represents more similarity.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.TileDB.html"}
{"id": "2246864f3a53-0", "text": "langchain.vectorstores.tencentvectordb.IndexParams\u00b6\nclass langchain.vectorstores.tencentvectordb.IndexParams(dimension: int, shard: int = 1, replicas: int = 2, index_type: str = 'HNSW', metric_type: str = 'L2', params: Optional[Dict] = None)[source]\u00b6\nTencent vector DB Index params.\nSee the following documentation for details:\nhttps://cloud.tencent.com/document/product/1709/95826\nMethods\n__init__(dimension[,\u00a0shard,\u00a0replicas,\u00a0...])\n__init__(dimension: int, shard: int = 1, replicas: int = 2, index_type: str = 'HNSW', metric_type: str = 'L2', params: Optional[Dict] = None)[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tencentvectordb.IndexParams.html"}
{"id": "c122f513a8cc-0", "text": "langchain.vectorstores.pgvector.PGVector\u00b6\nclass langchain.vectorstores.pgvector.PGVector(connection_string: str, embedding_function: Embeddings, collection_name: str = 'langchain', collection_metadata: Optional[dict] = None, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, pre_delete_collection: bool = False, logger: Optional[Logger] = None, relevance_score_fn: Optional[Callable[[float], float]] = None, *, connection: Optional[Connection] = None, engine_args: Optional[dict[str, Any]] = None)[source]\u00b6\nPostgres/PGVector vector store.\nTo use, you should have the pgvector python package installed.\nParameters\nconnection_string \u2013 Postgres connection string.\nembedding_function \u2013 Any embedding function implementing\nlangchain.embeddings.base.Embeddings interface.\ncollection_name \u2013 The name of the collection to use. (default: langchain)\nNOTE: This is not the name of the table, but the name of the collection.\nThe tables will be created when initializing the store (if not exists)\nSo, make sure the user has the right permissions to create tables.\ndistance_strategy \u2013 The distance strategy to use. (default: COSINE)\npre_delete_collection \u2013 If True, will delete the collection if it exists.\n(default: False). Useful for testing.\nengine_args \u2013 SQLAlchemy\u2019s create engine arguments.\nExample\nfrom langchain.vectorstores import PGVector\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nCONNECTION_STRING = \"postgresql+psycopg2://hwc@localhost:5432/test3\"\nCOLLECTION_NAME = \"state_of_the_union_test\"\nembeddings = OpenAIEmbeddings()\nvectorestore = PGVector.from_documents(\n    embedding=embeddings,\n    documents=docs,\n    collection_name=COLLECTION_NAME,\n    connection_string=CONNECTION_STRING,", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "c122f513a8cc-1", "text": "collection_name=COLLECTION_NAME,\n    connection_string=CONNECTION_STRING,\n)\nAttributes\ndistance_strategy\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(connection_string,\u00a0embedding_function)\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_embeddings(texts,\u00a0embeddings[,\u00a0...])\nAdd embeddings to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "c122f513a8cc-2", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\nconnect()\nconnection_string_from_db_params(driver,\u00a0...)\nReturn connection string from database parameters.\ncreate_collection()\ncreate_tables_if_not_exists()\ncreate_vector_extension()\ndelete([ids])\nDelete vectors by ids or uuids.\ndelete_collection()\ndrop_tables()\nfrom_documents(documents,\u00a0embedding[,\u00a0...])\nReturn VectorStore initialized from documents and embeddings.\nfrom_embeddings(text_embeddings,\u00a0embedding)\nConstruct PGVector wrapper from raw documents and pre- generated embeddings.\nfrom_existing_index(embedding[,\u00a0...])\nGet instance of an existing PGVector store.This method will return the instance of the store without inserting any new embeddings\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nget_collection(session)\nget_connection_string(kwargs)\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance\nmax_marginal_relevance_search_with_score(query)\nReturn docs selected using the maximal marginal relevance with score.\nmax_marginal_relevance_search_with_score_by_vector(...)\nReturn docs selected using the maximal marginal relevance with score\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nRun similarity search with PGVector with distance.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "c122f513a8cc-3", "text": "Return docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\nsimilarity_search_with_score_by_vector(embedding)\n__init__(connection_string: str, embedding_function: Embeddings, collection_name: str = 'langchain', collection_metadata: Optional[dict] = None, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, pre_delete_collection: bool = False, logger: Optional[Logger] = None, relevance_score_fn: Optional[Callable[[float], float]] = None, *, connection: Optional[Connection] = None, engine_args: Optional[dict[str, Any]] = None) \u2192 None[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "c122f513a8cc-4", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_embeddings(texts: Iterable[str], embeddings: List[List[float]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd embeddings to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nembeddings \u2013 List of list of embedding vectors.\nmetadatas \u2013 List of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "c122f513a8cc-5", "text": "Return VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "c122f513a8cc-6", "text": "docsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "c122f513a8cc-7", "text": "0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\nconnect() \u2192 Connection[source]\u00b6\nclassmethod connection_string_from_db_params(driver: str, host: str, port: int, database: str, user: str, password: str) \u2192 str[source]\u00b6\nReturn connection string from database parameters.\ncreate_collection() \u2192 None[source]\u00b6\ncreate_tables_if_not_exists() \u2192 None[source]\u00b6\ncreate_vector_extension() \u2192 None[source]\u00b6\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDelete vectors by ids or uuids.\nParameters\nids \u2013 List of ids to delete.\ndelete_collection() \u2192 None[source]\u00b6\ndrop_tables() \u2192 None[source]\u00b6\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, collection_name: str = 'langchain', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) \u2192 PGVector[source]\u00b6\nReturn VectorStore initialized from documents and embeddings.\nPostgres connection string is required\n\u201cEither pass it as a parameter\nor set the PGVECTOR_CONNECTION_STRING environment variable.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "c122f513a8cc-8", "text": "\u201cEither pass it as a parameter\nor set the PGVECTOR_CONNECTION_STRING environment variable.\nclassmethod from_embeddings(text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) \u2192 PGVector[source]\u00b6\nConstruct PGVector wrapper from raw documents and pre-\ngenerated embeddings.\nReturn VectorStore initialized from documents and embeddings.\nPostgres connection string is required\n\u201cEither pass it as a parameter\nor set the PGVECTOR_CONNECTION_STRING environment variable.\nExample\nfrom langchain.vectorstores import PGVector\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\ntext_embeddings = embeddings.embed_documents(texts)\ntext_embedding_pairs = list(zip(texts, text_embeddings))\nfaiss = PGVector.from_embeddings(text_embedding_pairs, embeddings)\nclassmethod from_existing_index(embedding: Embeddings, collection_name: str = 'langchain', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, pre_delete_collection: bool = False, **kwargs: Any) \u2192 PGVector[source]\u00b6\nGet instance of an existing PGVector store.This method will\nreturn the instance of the store without inserting any new\nembeddings\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) \u2192 PGVector[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nPostgres connection string is required\n\u201cEither pass it as a parameter", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "c122f513a8cc-9", "text": "Postgres connection string is required\n\u201cEither pass it as a parameter\nor set the PGVECTOR_CONNECTION_STRING environment variable.\nget_collection(session: Session) \u2192 Optional['CollectionStore'][source]\u00b6\nclassmethod get_connection_string(kwargs: Dict[str, Any]) \u2192 str[source]\u00b6\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversityamong selected documents.\nParameters\nquery (str) \u2013 Text to look up documents similar to.\nk (int) \u2013 Number of Documents to return. Defaults to 4.\nfetch_k (int) \u2013 Number of Documents to fetch to pass to MMR algorithm.\nDefaults to 20.\nlambda_mult (float) \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents selected by maximal marginal relevance.\nReturn type\nList[Document]\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevanceto embedding vector.\nMaximal marginal relevance optimizes for similarity to query AND diversityamong selected documents.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "c122f513a8cc-10", "text": "Maximal marginal relevance optimizes for similarity to query AND diversityamong selected documents.\nParameters\nembedding (str) \u2013 Text to look up documents similar to.\nk (int) \u2013 Number of Documents to return. Defaults to 4.\nfetch_k (int) \u2013 Number of Documents to fetch to pass to MMR algorithm.\nDefaults to 20.\nlambda_mult (float) \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents selected by maximal marginal relevance.\nReturn type\nList[Document]\nmax_marginal_relevance_search_with_score(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs selected using the maximal marginal relevance with score.\nMaximal marginal relevance optimizes for similarity to query AND diversityamong selected documents.\nParameters\nquery (str) \u2013 Text to look up documents similar to.\nk (int) \u2013 Number of Documents to return. Defaults to 4.\nfetch_k (int) \u2013 Number of Documents to fetch to pass to MMR algorithm.\nDefaults to 20.\nlambda_mult (float) \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents selected by maximal marginalrelevance to the query and score for each.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "c122f513a8cc-11", "text": "Returns\nList of Documents selected by maximal marginalrelevance to the query and score for each.\nReturn type\nList[Tuple[Document, float]]\nmax_marginal_relevance_search_with_score_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs selected using the maximal marginal relevance with scoreto embedding vector.\nMaximal marginal relevance optimizes for similarity to query AND diversityamong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk (int) \u2013 Number of Documents to return. Defaults to 4.\nfetch_k (int) \u2013 Number of Documents to fetch to pass to MMR algorithm.\nDefaults to 20.\nlambda_mult (float) \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents selected by maximal marginalrelevance to the query and score for each.\nReturn type\nList[Tuple[Document, float]]\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRun similarity search with PGVector with distance.\nParameters\nquery (str) \u2013 Query text to search for.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "c122f513a8cc-12", "text": "Parameters\nquery (str) \u2013 Query text to search for.\nk (int) \u2013 Number of results to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[dict] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "c122f513a8cc-13", "text": "filter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query and score for each.\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nExamples using PGVector\u00b6\nPGVector", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.PGVector.html"}
{"id": "8dc6f73f3905-0", "text": "langchain.vectorstores.redis.filters.RedisText\u00b6\nclass langchain.vectorstores.redis.filters.RedisText(field: str)[source]\u00b6\nA RedisFilterField representing a text field in a Redis index.\nAttributes\nOPERATORS\nOPERATOR_MAP\nescaper\nMethods\n__init__(field)\nequals(other)\n__init__(field: str)\u00b6\nequals(other: RedisFilterField) \u2192 bool\u00b6\nExamples using RedisText\u00b6\nRedis", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.filters.RedisText.html"}
{"id": "dcad88efba58-0", "text": "langchain.vectorstores.redis.filters.RedisNum\u00b6\nclass langchain.vectorstores.redis.filters.RedisNum(field: str)[source]\u00b6\nA RedisFilterField representing a numeric field in a Redis index.\nAttributes\nOPERATORS\nOPERATOR_MAP\nescaper\nMethods\n__init__(field)\nequals(other)\n__init__(field: str)\u00b6\nequals(other: RedisFilterField) \u2192 bool\u00b6\nExamples using RedisNum\u00b6\nRedis", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.filters.RedisNum.html"}
{"id": "654dbce58785-0", "text": "langchain.vectorstores.llm_rails.LLMRailsRetriever\u00b6\nclass langchain.vectorstores.llm_rails.LLMRailsRetriever[source]\u00b6\nBases: VectorStoreRetriever\nRetriever for LLMRails.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam search_kwargs: dict [Optional]\u00b6\nSearch params.\nk: Number of Documents to return. Defaults to 5.\nalpha: parameter for hybrid search .\nparam search_type: str = 'similarity'\u00b6\nType of search to perform. Defaults to \u201csimilarity\u201d.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam vectorstore: LLMRails [Required]\u00b6\nVectorStore to use for retrieval.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nAdd documents to vectorstore.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRailsRetriever.html"}
{"id": "654dbce58785-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nAdd documents to vectorstore.\nadd_texts(texts: List[str]) \u2192 None[source]\u00b6\nAdd text to the datastore.\nParameters\ntexts (List[str]) \u2013 The text\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRailsRetriever.html"}
{"id": "654dbce58785-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRailsRetriever.html"}
{"id": "654dbce58785-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRailsRetriever.html"}
{"id": "654dbce58785-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRailsRetriever.html"}
{"id": "654dbce58785-5", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRailsRetriever.html"}
{"id": "654dbce58785-6", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRailsRetriever.html"}
{"id": "654dbce58785-7", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRailsRetriever.html"}
{"id": "654dbce58785-8", "text": "Returns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRailsRetriever.html"}
{"id": "654dbce58785-9", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nallowed_search_types: ClassVar[Collection[str]] = ('similarity', 'similarity_score_threshold', 'mmr')\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRailsRetriever.html"}
{"id": "ff961d09f7f0-0", "text": "langchain.vectorstores.tair.Tair\u00b6\nclass langchain.vectorstores.tair.Tair(embedding_function: Embeddings, url: str, index_name: str, content_key: str = 'content', metadata_key: str = 'metadata', search_params: Optional[dict] = None, **kwargs: Any)[source]\u00b6\nTair vector store.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding_function,\u00a0url,\u00a0index_name)\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nAdd texts data to an existing index.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tair.Tair.html"}
{"id": "ff961d09f7f0-1", "text": "Return docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ncreate_index_if_not_exist(dim,\u00a0...)\ndelete([ids])\nDelete by vector ID or other criteria.\ndrop_index([index_name])\nDrop an existing index.\nfrom_documents(documents,\u00a0embedding[,\u00a0...])\nReturn VectorStore initialized from documents and embeddings.\nfrom_existing_index(embedding[,\u00a0index_name,\u00a0...])\nConnect to an existing Tair index.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturns the most similar indexed documents to the query text.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\n__init__(embedding_function: Embeddings, url: str, index_name: str, content_key: str = 'content', metadata_key: str = 'metadata', search_params: Optional[dict] = None, **kwargs: Any)[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tair.Tair.html"}
{"id": "ff961d09f7f0-2", "text": "async aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd texts data to an existing index.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tair.Tair.html"}
{"id": "ff961d09f7f0-3", "text": "Return VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tair.Tair.html"}
{"id": "ff961d09f7f0-4", "text": ")\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tair.Tair.html"}
{"id": "ff961d09f7f0-5", "text": "**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ncreate_index_if_not_exist(dim: int, distance_type: str, index_type: str, data_type: str, **kwargs: Any) \u2192 bool[source]\u00b6\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nstatic drop_index(index_name: str = 'langchain', **kwargs: Any) \u2192 bool[source]\u00b6\nDrop an existing index.\nParameters\nindex_name (str) \u2013 Name of the index to drop.\nReturns\nTrue if the index is dropped successfully.\nReturn type\nbool\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, metadatas: Optional[List[dict]] = None, index_name: str = 'langchain', content_key: str = 'content', metadata_key: str = 'metadata', **kwargs: Any) \u2192 Tair[source]\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_existing_index(embedding: Embeddings, index_name: str = 'langchain', content_key: str = 'content', metadata_key: str = 'metadata', **kwargs: Any) \u2192 Tair[source]\u00b6\nConnect to an existing Tair index.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tair.Tair.html"}
{"id": "ff961d09f7f0-6", "text": "Connect to an existing Tair index.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, index_name: str = 'langchain', content_key: str = 'content', metadata_key: str = 'metadata', **kwargs: Any) \u2192 Tair[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tair.Tair.html"}
{"id": "ff961d09f7f0-7", "text": "lambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturns the most similar indexed documents to the query text.\nParameters\nquery (str) \u2013 The query text for which to find similar documents.\nk (int) \u2013 The number of documents to return. Default is 4.\nReturns\nA list of documents that are most similar to the query text.\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tair.Tair.html"}
{"id": "ff961d09f7f0-8", "text": "filter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.\nExamples using Tair\u00b6\nTair", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tair.Tair.html"}
{"id": "e11dff38b67b-0", "text": "langchain.vectorstores.redis.schema.read_schema\u00b6\nlangchain.vectorstores.redis.schema.read_schema(index_schema: Optional[Union[Dict[str, List[Any]], str, PathLike]]) \u2192 Dict[str, Any][source]\u00b6\nReads in the index schema from a dict or yaml file.\nCheck if it is a dict and return RedisModel otherwise, check if it\u2019s a path and\nread in the file assuming it\u2019s a yaml file and return a RedisModel", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.read_schema.html"}
{"id": "dd0b6d2eaadb-0", "text": "langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch\u00b6\nclass langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch(doc_index: BaseDocIndex, embedding: Embeddings)[source]\u00b6\nHnswLib storage using DocArray package.\nTo use it, you should have the docarray package with version >=0.32.0 installed.\nYou can install it with pip install \u201clangchain[docarray]\u201d.\nInitialize a vector store from DocArray\u2019s DocIndex.\nAttributes\ndoc_cls\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(doc_index,\u00a0embedding)\nInitialize a vector store from DocArray's DocIndex.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nEmbed texts and add to the vector store.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html"}
{"id": "dd0b6d2eaadb-1", "text": "asearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_params(embedding,\u00a0work_dir,\u00a0n_dim[,\u00a0...])\nInitialize DocArrayHnswSearch store.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreate an DocArrayHnswSearch store and insert data.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nReturn docs most similar to query.\n__init__(doc_index: BaseDocIndex, embedding: Embeddings)\u00b6\nInitialize a vector store from DocArray\u2019s DocIndex.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html"}
{"id": "dd0b6d2eaadb-2", "text": "Initialize a vector store from DocArray\u2019s DocIndex.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nEmbed texts and add to the vector store.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html"}
{"id": "dd0b6d2eaadb-3", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html"}
{"id": "dd0b6d2eaadb-4", "text": "Return type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html"}
{"id": "dd0b6d2eaadb-5", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_params(embedding: Embeddings, work_dir: str, n_dim: int, dist_metric: Literal['cosine', 'ip', 'l2'] = 'cosine', max_elements: int = 1024, index: bool = True, ef_construction: int = 200, ef: int = 10, M: int = 16, allow_replace_deleted: bool = True, num_threads: int = 1, **kwargs: Any) \u2192 DocArrayHnswSearch[source]\u00b6\nInitialize DocArrayHnswSearch store.\nParameters\nembedding (Embeddings) \u2013 Embedding function.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html"}
{"id": "dd0b6d2eaadb-6", "text": "Parameters\nembedding (Embeddings) \u2013 Embedding function.\nwork_dir (str) \u2013 path to the location where all the data will be stored.\nn_dim (int) \u2013 dimension of an embedding.\ndist_metric (str) \u2013 Distance metric for DocArrayHnswSearch can be one of:\n\u201ccosine\u201d, \u201cip\u201d, and \u201cl2\u201d. Defaults to \u201ccosine\u201d.\nmax_elements (int) \u2013 Maximum number of vectors that can be stored.\nDefaults to 1024.\nindex (bool) \u2013 Whether an index should be built for this field.\nDefaults to True.\nef_construction (int) \u2013 defines a construction time/accuracy trade-off.\nDefaults to 200.\nef (int) \u2013 parameter controlling query time/accuracy trade-off.\nDefaults to 10.\nM (int) \u2013 parameter that defines the maximum number of outgoing\nconnections in the graph. Defaults to 16.\nallow_replace_deleted (bool) \u2013 Enables replacing of deleted elements\nwith new added ones. Defaults to True.\nnum_threads (int) \u2013 Sets the number of cpu threads to use. Defaults to 1.\n**kwargs \u2013 Other keyword arguments to be passed to the get_doc_cls method.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, work_dir: Optional[str] = None, n_dim: Optional[int] = None, **kwargs: Any) \u2192 DocArrayHnswSearch[source]\u00b6\nCreate an DocArrayHnswSearch store and insert data.\nParameters\ntexts (List[str]) \u2013 Text data.\nembedding (Embeddings) \u2013 Embedding function.\nmetadatas (Optional[List[dict]]) \u2013 Metadata for each text if it exists.\nDefaults to None.\nwork_dir (str) \u2013 path to the location where all the data will be stored.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html"}
{"id": "dd0b6d2eaadb-7", "text": "work_dir (str) \u2013 path to the location where all the data will be stored.\nn_dim (int) \u2013 dimension of an embedding.\n**kwargs \u2013 Other keyword arguments to be passed to the __init__ method.\nReturns\nDocArrayHnswSearch Vector Store\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html"}
{"id": "dd0b6d2eaadb-8", "text": "to maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs most similar to query.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html"}
{"id": "dd0b6d2eaadb-9", "text": "Return docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of documents most similar to the query text and\ncosine distance in float for each.\nLower score represents more similarity.\nExamples using DocArrayHnswSearch\u00b6\nDocArray HnswSearch", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.hnsw.DocArrayHnswSearch.html"}
{"id": "30110f6d6bf1-0", "text": "langchain.vectorstores.scann.normalize\u00b6\nlangchain.vectorstores.scann.normalize(x: ndarray) \u2192 ndarray[source]\u00b6\nNormalize vectors to unit length.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.normalize.html"}
{"id": "ffb1942e1148-0", "text": "langchain.vectorstores.pgvector.DistanceStrategy\u00b6\nclass langchain.vectorstores.pgvector.DistanceStrategy(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnumerator of the Distance strategies.\nEUCLIDEAN = 'l2'\u00b6\nCOSINE = 'cosine'\u00b6\nMAX_INNER_PRODUCT = 'inner'\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.DistanceStrategy.html"}
{"id": "316b771b376a-0", "text": "langchain.vectorstores.elastic_vector_search.ElasticKnnSearch\u00b6\nclass langchain.vectorstores.elastic_vector_search.ElasticKnnSearch(index_name: str, embedding: Embeddings, es_connection: Optional['Elasticsearch'] = None, es_cloud_id: Optional[str] = None, es_user: Optional[str] = None, es_password: Optional[str] = None, vector_query_field: Optional[str] = 'vector', query_field: Optional[str] = 'text')[source]\u00b6\n[Deprecated]  [DEPRECATED] Elasticsearch with k-nearest neighbor search\n(k-NN) vector store.\nRecommended to use ElasticsearchStore instead, which supports\nmetadata filtering, customising the query retriever and much more!\nYou can read more on ElasticsearchStore:\nhttps://python.langchain.com/docs/integrations/vectorstores/elasticsearch\nIt creates an Elasticsearch index of text data that\ncan be searched using k-NN search. The text data is transformed into\nvector embeddings using a provided embedding model, and these embeddings\nare stored in the Elasticsearch index.\nindex_name\u00b6\nThe name of the Elasticsearch index.\nType\nstr\nembedding\u00b6\nThe embedding model to use for transforming text data\ninto vector embeddings.\nType\nEmbeddings\nes_connection\u00b6\nAn existing Elasticsearch connection.\nType\nElasticsearch, optional\nes_cloud_id\u00b6\nThe Cloud ID of your Elasticsearch Service\ndeployment.\nType\nstr, optional\nes_user\u00b6\nThe username for your Elasticsearch Service deployment.\nType\nstr, optional\nes_password\u00b6\nThe password for your Elasticsearch Service\ndeployment.\nType\nstr, optional\nvector_query_field\u00b6\nThe name of the field in the Elasticsearch\nindex that contains the vector embeddings.\nType\nstr, optional\nquery_field\u00b6\nThe name of the field in the Elasticsearch index\nthat contains the original text data.\nType\nstr, optional", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticKnnSearch.html"}
{"id": "316b771b376a-1", "text": "that contains the original text data.\nType\nstr, optional\nUsage:>>> from embeddings import Embeddings\n>>> embedding = Embeddings.load('glove')\n>>> es_search = ElasticKnnSearch('my_index', embedding)\n>>> es_search.add_texts(['Hello world!', 'Another text'])\n>>> results = es_search.knn_search('Hello')\n[(Document(page_content='Hello world!', metadata={}), 0.9)][*Deprecated*] [DEPRECATED] `Elasticsearch` with k-nearest neighbor search\n(k-NN) vector store.\nRecommended to use ElasticsearchStore instead, which supports\nmetadata filtering, customising the query retriever and much more!\nYou can read more on ElasticsearchStore:\nhttps://python.langchain.com/docs/integrations/vectorstores/elasticsearch\nIt creates an Elasticsearch index of text data that\ncan be searched using k-NN search. The text data is transformed into\nvector embeddings using a provided embedding model, and these embeddings\nare stored in the Elasticsearch index.\nindex_name\u00b6\nThe name of the Elasticsearch index.\nType\nstr\nembedding\u00b6\nThe embedding model to use for transforming text data\ninto vector embeddings.\nType\nEmbeddings\nes_connection\u00b6\nAn existing Elasticsearch connection.\nType\nElasticsearch, optional\nes_cloud_id\u00b6\nThe Cloud ID of your Elasticsearch Service\ndeployment.\nType\nstr, optional\nes_user\u00b6\nThe username for your Elasticsearch Service deployment.\nType\nstr, optional\nes_password\u00b6\nThe password for your Elasticsearch Service\ndeployment.\nType\nstr, optional\nvector_query_field\u00b6\nThe name of the field in the Elasticsearch\nindex that contains the vector embeddings.\nType\nstr, optional\nquery_field\u00b6\nThe name of the field in the Elasticsearch index\nthat contains the original text data.\nType\nstr, optional\nUsage:>>> from embeddings import Embeddings", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticKnnSearch.html"}
{"id": "316b771b376a-2", "text": "Type\nstr, optional\nUsage:>>> from embeddings import Embeddings\n>>> embedding = Embeddings.load('glove')\n>>> es_search = ElasticKnnSearch('my_index', embedding)\n>>> es_search.add_texts(['Hello world!', 'Another text'])\n>>> results = es_search.knn_search('Hello')\n[(Document(page_content='Hello world!', metadata={}), 0.9)]\nNotes\nDeprecated since version 0.0.265: Use ElasticsearchStore class. instead.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(index_name,\u00a0embedding[,\u00a0...])\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0model_id,\u00a0...])\nAdd a list of texts to the Elasticsearch index.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticKnnSearch.html"}
{"id": "316b771b376a-3", "text": "Return docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ncreate_knn_index(mapping)\nCreate a new k-NN index in Elasticsearch.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nCreate a new ElasticKnnSearch instance and add a list of texts to the\nknn_hybrid_search([query,\u00a0k,\u00a0query_vector,\u00a0...])\nPerform a hybrid k-NN and text search on the Elasticsearch index.\nknn_search([query,\u00a0k,\u00a0query_vector,\u00a0...])\nPerform a k-NN search on the Elasticsearch index.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nPass through to knn_search\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticKnnSearch.html"}
{"id": "316b771b376a-4", "text": "similarity_search_with_score(query[,\u00a0k])\nPass through to knn_search including score\n__init__(index_name: str, embedding: Embeddings, es_connection: Optional['Elasticsearch'] = None, es_cloud_id: Optional[str] = None, es_user: Optional[str] = None, es_password: Optional[str] = None, vector_query_field: Optional[str] = 'vector', query_field: Optional[str] = 'text')[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[Dict[Any, Any]]] = None, model_id: Optional[str] = None, refresh_indices: bool = False, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd a list of texts to the Elasticsearch index.\nParameters\ntexts (Iterable[str]) \u2013 The texts to add to the index.\nmetadatas (List[Dict[Any, Any]], optional) \u2013 A list of metadata dictionaries\nto associate with the texts.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticKnnSearch.html"}
{"id": "316b771b376a-5", "text": "to associate with the texts.\nmodel_id (str, optional) \u2013 The ID of the model to use for transforming the\ntexts into vectors.\nrefresh_indices (bool, optional) \u2013 Whether to refresh the Elasticsearch\nindices after adding the texts.\n**kwargs \u2013 Arbitrary keyword arguments.\nReturns\nA list of IDs for the added texts.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticKnnSearch.html"}
{"id": "316b771b376a-6", "text": "Return VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticKnnSearch.html"}
{"id": "316b771b376a-7", "text": "docsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ncreate_knn_index(mapping: Dict) \u2192 None[source]\u00b6\nCreate a new k-NN index in Elasticsearch.\nParameters\nmapping (Dict) \u2013 The mapping to use for the new index.\nReturns\nNone\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticKnnSearch.html"}
{"id": "316b771b376a-8", "text": "Delete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, **kwargs: Any) \u2192 ElasticKnnSearch[source]\u00b6\nCreate a new ElasticKnnSearch instance and add a list of texts to theElasticsearch index.\nParameters\ntexts (List[str]) \u2013 The texts to add to the index.\nembedding (Embeddings) \u2013 The embedding model to use for transforming the\ntexts into vectors.\nmetadatas (List[Dict[Any, Any]], optional) \u2013 A list of metadata dictionaries\nto associate with the texts.\n**kwargs \u2013 Arbitrary keyword arguments.\nReturns\nA new ElasticKnnSearch instance.\nknn_hybrid_search(query: Optional[str] = None, k: Optional[int] = 10, query_vector: Optional[List[float]] = None, model_id: Optional[str] = None, size: Optional[int] = 10, source: Optional[bool] = True, knn_boost: Optional[float] = 0.9, query_boost: Optional[float] = 0.1, fields: Optional[Union[List[Mapping[str, Any]], Tuple[Mapping[str, Any], ...]]] = None, page_content: Optional[str] = 'text') \u2192 List[Tuple[Document, float]][source]\u00b6\nPerform a hybrid k-NN and text search on the Elasticsearch index.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticKnnSearch.html"}
{"id": "316b771b376a-9", "text": "Perform a hybrid k-NN and text search on the Elasticsearch index.\nParameters\nquery (str, optional) \u2013 The query text to search for.\nk (int, optional) \u2013 The number of nearest neighbors to return.\nquery_vector (List[float], optional) \u2013 The query vector to search for.\nmodel_id (str, optional) \u2013 The ID of the model to use for transforming the\nquery text into a vector.\nsize (int, optional) \u2013 The number of search results to return.\nsource (bool, optional) \u2013 Whether to return the source of the search results.\nknn_boost (float, optional) \u2013 The boost value to apply to the k-NN search\nresults.\nquery_boost (float, optional) \u2013 The boost value to apply to the text search\nresults.\nfields (List[Mapping[str, Any]], optional) \u2013 The fields to return in the\nsearch results.\npage_content (str, optional) \u2013 The name of the field that contains the page\ncontent.\nReturns\nA list of tuples, where each tuple contains a Document object and a score.\nknn_search(query: Optional[str] = None, k: Optional[int] = 10, query_vector: Optional[List[float]] = None, model_id: Optional[str] = None, size: Optional[int] = 10, source: Optional[bool] = True, fields: Optional[Union[List[Mapping[str, Any]], Tuple[Mapping[str, Any], ...]]] = None, page_content: Optional[str] = 'text') \u2192 List[Tuple[Document, float]][source]\u00b6\nPerform a k-NN search on the Elasticsearch index.\nParameters\nquery (str, optional) \u2013 The query text to search for.\nk (int, optional) \u2013 The number of nearest neighbors to return.\nquery_vector (List[float], optional) \u2013 The query vector to search for.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticKnnSearch.html"}
{"id": "316b771b376a-10", "text": "query_vector (List[float], optional) \u2013 The query vector to search for.\nmodel_id (str, optional) \u2013 The ID of the model to use for transforming the\nquery text into a vector.\nsize (int, optional) \u2013 The number of search results to return.\nsource (bool, optional) \u2013 Whether to return the source of the search results.\nfields (List[Mapping[str, Any]], optional) \u2013 The fields to return in the\nsearch results.\npage_content (str, optional) \u2013 The name of the field that contains the page\ncontent.\nReturns\nA list of tuples, where each tuple contains a Document object and a score.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticKnnSearch.html"}
{"id": "316b771b376a-11", "text": "Maximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPass through to knn_search\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticKnnSearch.html"}
{"id": "316b771b376a-12", "text": "filter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 10, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPass through to knn_search including score", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elastic_vector_search.ElasticKnnSearch.html"}
{"id": "ff97be09cfdb-0", "text": "langchain.vectorstores.neo4j_vector.SearchType\u00b6\nclass langchain.vectorstores.neo4j_vector.SearchType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnumerator of the Distance strategies.\nVECTOR = 'vector'\u00b6\nHYBRID = 'hybrid'\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.SearchType.html"}
{"id": "add3c1fbb7b3-0", "text": "langchain.vectorstores.docarray.in_memory.DocArrayInMemorySearch\u00b6\nclass langchain.vectorstores.docarray.in_memory.DocArrayInMemorySearch(doc_index: BaseDocIndex, embedding: Embeddings)[source]\u00b6\nIn-memory DocArray storage for exact search.\nTo use it, you should have the docarray package with version >=0.32.0 installed.\nYou can install it with pip install \u201clangchain[docarray]\u201d.\nInitialize a vector store from DocArray\u2019s DocIndex.\nAttributes\ndoc_cls\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(doc_index,\u00a0embedding)\nInitialize a vector store from DocArray's DocIndex.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nEmbed texts and add to the vector store.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.in_memory.DocArrayInMemorySearch.html"}
{"id": "add3c1fbb7b3-1", "text": "Return docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_params(embedding[,\u00a0metric])\nInitialize DocArrayInMemorySearch store.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nCreate an DocArrayInMemorySearch store and insert data.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nReturn docs most similar to query.\n__init__(doc_index: BaseDocIndex, embedding: Embeddings)\u00b6\nInitialize a vector store from DocArray\u2019s DocIndex.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.in_memory.DocArrayInMemorySearch.html"}
{"id": "add3c1fbb7b3-2", "text": "Run more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nEmbed texts and add to the vector store.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.in_memory.DocArrayInMemorySearch.html"}
{"id": "add3c1fbb7b3-3", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.in_memory.DocArrayInMemorySearch.html"}
{"id": "add3c1fbb7b3-4", "text": "Return type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.in_memory.DocArrayInMemorySearch.html"}
{"id": "add3c1fbb7b3-5", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_params(embedding: Embeddings, metric: Literal['cosine_sim', 'euclidian_dist', 'sgeuclidean_dist'] = 'cosine_sim', **kwargs: Any) \u2192 DocArrayInMemorySearch[source]\u00b6\nInitialize DocArrayInMemorySearch store.\nParameters\nembedding (Embeddings) \u2013 Embedding function.\nmetric (str) \u2013 metric for exact nearest-neighbor search.\nCan be one of: \u201ccosine_sim\u201d, \u201ceuclidean_dist\u201d and \u201csqeuclidean_dist\u201d.\nDefaults to \u201ccosine_sim\u201d.\n**kwargs \u2013 Other keyword arguments to be passed to the get_doc_cls method.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.in_memory.DocArrayInMemorySearch.html"}
{"id": "add3c1fbb7b3-6", "text": "**kwargs \u2013 Other keyword arguments to be passed to the get_doc_cls method.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, **kwargs: Any) \u2192 DocArrayInMemorySearch[source]\u00b6\nCreate an DocArrayInMemorySearch store and insert data.\nParameters\ntexts (List[str]) \u2013 Text data.\nembedding (Embeddings) \u2013 Embedding function.\nmetadatas (Optional[List[Dict[Any, Any]]]) \u2013 Metadata for each text\nif it exists. Defaults to None.\nmetric (str) \u2013 metric for exact nearest-neighbor search.\nCan be one of: \u201ccosine_sim\u201d, \u201ceuclidean_dist\u201d and \u201csqeuclidean_dist\u201d.\nDefaults to \u201ccosine_sim\u201d.\nReturns\nDocArrayInMemorySearch Vector Store\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.in_memory.DocArrayInMemorySearch.html"}
{"id": "add3c1fbb7b3-7", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.in_memory.DocArrayInMemorySearch.html"}
{"id": "add3c1fbb7b3-8", "text": "Returns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of documents most similar to the query text and\ncosine distance in float for each.\nLower score represents more similarity.\nExamples using DocArrayInMemorySearch\u00b6\nDocArray InMemorySearch", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.docarray.in_memory.DocArrayInMemorySearch.html"}
{"id": "b1b9609ea896-0", "text": "langchain.vectorstores.tiledb.get_documents_array_uri\u00b6\nlangchain.vectorstores.tiledb.get_documents_array_uri(uri: str) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.get_documents_array_uri.html"}
{"id": "888d179489b8-0", "text": "langchain.vectorstores.dashvector.DashVector\u00b6\nclass langchain.vectorstores.dashvector.DashVector(collection: Any, embedding: Embeddings, text_field: str)[source]\u00b6\nDashVector vector store.\nTo use, you should have the dashvector python package installed.\nExample\nfrom langchain.vectorstores import dashvector\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nimport dashvector\nclient = dashvector.Client.init(api_key=\"***\")\nclient.create(\"langchain\")\ncollection = client.get(\"langchain\")\nembeddings = OpenAIEmbeddings()\nvectorstore = Dashvector(collection, embeddings.embed_query, \"text\")\nInitialize with DashVector collection.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(collection,\u00a0embedding,\u00a0text_field)\nInitialize with DashVector collection.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0batch_size])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dashvector.DashVector.html"}
{"id": "888d179489b8-1", "text": "amax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn DashVector VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs most similar to query text , alone with relevance scores.\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\n__init__(collection: Any, embedding: Embeddings, text_field: str)[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dashvector.DashVector.html"}
{"id": "888d179489b8-2", "text": "Initialize with DashVector collection.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, batch_size: int = 25, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of ids associated with the texts.\nbatch_size \u2013 Optional batch size to upsert docs.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dashvector.DashVector.html"}
{"id": "888d179489b8-3", "text": "**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dashvector.DashVector.html"}
{"id": "888d179489b8-4", "text": "fetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dashvector.DashVector.html"}
{"id": "888d179489b8-5", "text": "Return docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 bool[source]\u00b6\nDelete by vector ID.\nParameters\nids \u2013 List of ids to delete.\nReturns\nTrue if deletion is successful,\nFalse otherwise.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, dashvector_api_key: Optional[str] = None, collection_name: str = 'langchain', text_field: str = 'text', batch_size: int = 25, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 DashVector[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dashvector.DashVector.html"}
{"id": "888d179489b8-6", "text": "Return DashVector VectorStore initialized from texts and embeddings.\nThis is the quick way to get started with dashvector vector store.\nExample\nfrom langchain.vectorstores import DashVector\nfrom langchain.embeddings import OpenAIEmbeddings\nimport dashvector\nembeddings = OpenAIEmbeddings()\ndashvector = DashVector.from_documents(\ndocs,\nembeddings,\ndashvector_api_key=\u201d{DASHVECTOR_API_KEY}\u201d\n)\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter \u2013 Doc fields filter conditions that meet the SQL where clause\nspecification.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dashvector.DashVector.html"}
{"id": "888d179489b8-7", "text": "Maximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter \u2013 Doc fields filter conditions that meet the SQL where clause\nspecification.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to search documents similar to.\nk \u2013 Number of documents to return. Default to 4.\nfilter \u2013 Doc fields filter conditions that meet the SQL where clause\nspecification.\nReturns\nList of Documents most similar to the query text.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Doc fields filter conditions that meet the SQL where clause\nspecification.\nReturns\nList of Documents most similar to the query vector.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dashvector.DashVector.html"}
{"id": "888d179489b8-8", "text": "specification.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, filter: Optional[str] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query text , alone with relevance scores.\nLess is more similar, more is more dissimilar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Doc fields filter conditions that meet the SQL where clause\nspecification.\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.\nExamples using DashVector\u00b6\nDashVector", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dashvector.DashVector.html"}
{"id": "15987fe1593d-0", "text": "langchain.vectorstores.llm_rails.LLMRails\u00b6\nclass langchain.vectorstores.llm_rails.LLMRails(datastore_id: Optional[str] = None, api_key: Optional[str] = None)[source]\u00b6\nImplementation of Vector Store using LLMRails.\nSee https://llmrails.com/\nExample\nfrom langchain.vectorstores import LLMRails\nvectorstore = LLMRails(\n    api_key=llm_rails_api_key,\n    datastore_id=datastore_id\n)\nInitialize with LLMRails API.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__([datastore_id,\u00a0api_key])\nInitialize with LLMRails API.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_files(files_list[,\u00a0metadatas])\nLLMRails provides a way to add documents directly via our API where pre-processing and chunking occurs internally in an optimal way This method provides a way to use that API in LangChain\nadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRails.html"}
{"id": "15987fe1593d-1", "text": "Return docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts[,\u00a0embedding,\u00a0metadatas])\nConstruct LLMRails wrapper from raw documents.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn LLMRails documents most similar to query, along with scores.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nReturn LLMRails documents most similar to query, along with scores.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRails.html"}
{"id": "15987fe1593d-2", "text": "Return LLMRails documents most similar to query, along with scores.\n__init__(datastore_id: Optional[str] = None, api_key: Optional[str] = None)[source]\u00b6\nInitialize with LLMRails API.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_files(files_list: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 bool[source]\u00b6\nLLMRails provides a way to add documents directly via our API where\npre-processing and chunking occurs internally in an optimal way\nThis method provides a way to use that API in LangChain\nParameters\nfiles_list \u2013 Iterable of strings, each representing a local file path.\nFiles could be text, HTML, PDF, markdown, doc/docx, ppt/pptx, etc.\nsee API docs for full list\nReturns\nList of ids associated with each of the files indexed", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRails.html"}
{"id": "15987fe1593d-3", "text": "see API docs for full list\nReturns\nList of ids associated with each of the files indexed\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRails.html"}
{"id": "15987fe1593d-4", "text": "Return docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 LLMRailsRetriever[source]\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRails.html"}
{"id": "15987fe1593d-5", "text": ")\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRails.html"}
{"id": "15987fe1593d-6", "text": "Delete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 LLMRails[source]\u00b6\nConstruct LLMRails wrapper from raw documents.\nThis is intended to be a quick way to get started.\n.. rubric:: Example\nfrom langchain.vectorstores import LLMRails\nllm_rails = LLMRails.from_texts(\n    texts,\n    datastore_id=datastore_id,\n    api_key=llm_rails_api_key\n)\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRails.html"}
{"id": "15987fe1593d-7", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn LLMRails documents most similar to query, along with scores.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 5.\nReturns\nList of Documents most similar to the query\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRails.html"}
{"id": "15987fe1593d-8", "text": "Returns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 5) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn LLMRails documents most similar to query, along with scores.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 5 Max 10.\nalpha \u2013 parameter for hybrid search .\nReturns\nList of Documents most similar to the query and score for each.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.llm_rails.LLMRails.html"}
{"id": "b27bb662b58a-0", "text": "langchain.vectorstores.redis.schema.TagFieldSchema\u00b6\nclass langchain.vectorstores.redis.schema.TagFieldSchema[source]\u00b6\nBases: RedisField\nSchema for tag fields in Redis.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam case_sensitive: bool = False\u00b6\nparam name: str [Required]\u00b6\nparam no_index: bool = False\u00b6\nparam separator: str = ','\u00b6\nparam sortable: Optional[bool] = False\u00b6\nas_field() \u2192 TagField[source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.TagFieldSchema.html"}
{"id": "b27bb662b58a-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.TagFieldSchema.html"}
{"id": "b27bb662b58a-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.TagFieldSchema.html"}
{"id": "247f87d8ab8a-0", "text": "langchain.vectorstores.milvus.Milvus\u00b6\nclass langchain.vectorstores.milvus.Milvus(embedding_function: Embeddings, collection_name: str = 'LangChainCollection', connection_args: Optional[dict[str, Any]] = None, consistency_level: str = 'Session', index_params: Optional[dict] = None, search_params: Optional[dict] = None, drop_old: Optional[bool] = False, *, primary_field: str = 'pk', text_field: str = 'text', vector_field: str = 'vector')[source]\u00b6\nMilvus vector store.\nYou need to install pymilvus and run Milvus.\nSee the following documentation for how to run a Milvus instance:\nhttps://milvus.io/docs/install_standalone-docker.md\nIf looking for a hosted Milvus, take a look at this documentation:\nhttps://zilliz.com/cloud and make use of the Zilliz vectorstore found in\nthis project.\nIF USING L2/IP metric, IT IS HIGHLY SUGGESTED TO NORMALIZE YOUR DATA.\nParameters\nembedding_function (Embeddings) \u2013 Function used to embed the text.\ncollection_name (str) \u2013 Which Milvus collection to use. Defaults to\n\u201cLangChainCollection\u201d.\nconnection_args (Optional[dict[str, any]]) \u2013 The connection args used for\nthis class comes in the form of a dict.\nconsistency_level (str) \u2013 The consistency level to use for a collection.\nDefaults to \u201cSession\u201d.\nindex_params (Optional[dict]) \u2013 Which index params to use. Defaults to\nHNSW/AUTOINDEX depending on service.\nsearch_params (Optional[dict]) \u2013 Which search params to use. Defaults to\ndefault of index.\ndrop_old (Optional[bool]) \u2013 Whether to drop the current collection. Defaults\nto False.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "247f87d8ab8a-1", "text": "to False.\nprimary_field (str) \u2013 Name of the primary key field. Defaults to \u201cpk\u201d.\ntext_field (str) \u2013 Name of the text field. Defaults to \u201ctext\u201d.\nvector_field (str) \u2013 Name of the vector field. Defaults to \u201cvector\u201d.\nThe connection args used for this class comes in the form of a dict,\nhere are a few of the options:\naddress (str): The actual address of Milvusinstance. Example address: \u201clocalhost:19530\u201d\nuri (str): The uri of Milvus instance. Example uri:\u201chttp://randomwebsite:19530\u201d,\n\u201ctcp:foobarsite:19530\u201d,\n\u201chttps://ok.s3.south.com:19530\u201d.\nhost (str): The host of Milvus instance. Default at \u201clocalhost\u201d,PyMilvus will fill in the default host if only port is provided.\nport (str/int): The port of Milvus instance. Default at 19530, PyMilvuswill fill in the default port if only host is provided.\nuser (str): Use which user to connect to Milvus instance. If user andpassword are provided, we will add related header in every RPC call.\npassword (str): Required when user is provided. The passwordcorresponding to the user.\nsecure (bool): Default is false. If set to true, tls will be enabled.\nclient_key_path (str): If use tls two-way authentication, need to\nwrite the client.key path.\nclient_pem_path (str): If use tls two-way authentication, need towrite the client.pem path.\nca_pem_path (str): If use tls two-way authentication, need to writethe ca.pem path.\nserver_pem_path (str): If use tls one-way authentication, need towrite the server.pem path.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "247f87d8ab8a-2", "text": "server_name (str): If use tls, need to write the common name.\nExample\nfrom langchain.vectorstores import Milvus\nfrom langchain.embeddings import OpenAIEmbeddings\nembedding = OpenAIEmbeddings()\n# Connect to a milvus instance on localhost\nmilvus_store = Milvus(\nembedding_function = Embeddings,\ncollection_name = \u201cLangChainCollection\u201d,\ndrop_old = True,\n)\nRaises\nValueError \u2013 If the pymilvus python package is not installed.\nInitialize the Milvus vector store.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding_function[,\u00a0...])\nInitialize the Milvus vector store.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0timeout,\u00a0...])\nInsert text data into Milvus.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "247f87d8ab8a-3", "text": "Return VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreate a Milvus collection, indexes it with HNSW, and insert data.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nPerform a search and return results that are reordered by MMR.\nmax_marginal_relevance_search_by_vector(...)\nPerform a search and return results that are reordered by MMR.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0param,\u00a0expr,\u00a0...])\nPerform a similarity search against the query string.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nPerform a similarity search against the query string.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nPerform a search on a query string and return results with score.\nsimilarity_search_with_score_by_vector(embedding)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "247f87d8ab8a-4", "text": "similarity_search_with_score_by_vector(embedding)\nPerform a search on a query string and return results with score.\n__init__(embedding_function: Embeddings, collection_name: str = 'LangChainCollection', connection_args: Optional[dict[str, Any]] = None, consistency_level: str = 'Session', index_params: Optional[dict] = None, search_params: Optional[dict] = None, drop_old: Optional[bool] = False, *, primary_field: str = 'pk', text_field: str = 'text', vector_field: str = 'vector')[source]\u00b6\nInitialize the Milvus vector store.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, timeout: Optional[int] = None, batch_size: int = 1000, **kwargs: Any) \u2192 List[str][source]\u00b6\nInsert text data into Milvus.\nInserting data when the collection has not be made yet will result", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "247f87d8ab8a-5", "text": "Inserting data when the collection has not be made yet will result\nin creating a new Collection. The data of the first entity decides\nthe schema of the new collection, the dim is extracted from the first\nembedding and the columns are decided by the first metadata dict.\nMetada keys will need to be present for all inserted values. At\nthe moment there is no None equivalent in Milvus.\nParameters\ntexts (Iterable[str]) \u2013 The texts to embed, it is assumed\nthat they all fit in memory.\nmetadatas (Optional[List[dict]]) \u2013 Metadata dicts attached to each of\nthe texts. Defaults to None.\ntimeout (Optional[int]) \u2013 Timeout for each batch insert. Defaults\nto None.\nbatch_size (int, optional) \u2013 Batch size to use for insertion.\nDefaults to 1000.\nRaises\nMilvusException \u2013 Failure to add texts\nReturns\nThe resulting keys for each inserted element.\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "247f87d8ab8a-6", "text": "Return VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "247f87d8ab8a-7", "text": ")\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "247f87d8ab8a-8", "text": "**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'LangChainCollection', connection_args: dict[str, Any] = {'host': 'localhost', 'password': '', 'port': '19530', 'secure': False, 'user': ''}, consistency_level: str = 'Session', index_params: Optional[dict] = None, search_params: Optional[dict] = None, drop_old: bool = False, **kwargs: Any) \u2192 Milvus[source]\u00b6\nCreate a Milvus collection, indexes it with HNSW, and insert data.\nParameters\ntexts (List[str]) \u2013 Text data.\nembedding (Embeddings) \u2013 Embedding function.\nmetadatas (Optional[List[dict]]) \u2013 Metadata for each text if it exists.\nDefaults to None.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "247f87d8ab8a-9", "text": "Defaults to None.\ncollection_name (str, optional) \u2013 Collection name to use. Defaults to\n\u201cLangChainCollection\u201d.\nconnection_args (dict[str, Any], optional) \u2013 Connection args to use. Defaults\nto DEFAULT_MILVUS_CONNECTION.\nconsistency_level (str, optional) \u2013 Which consistency level to use. Defaults\nto \u201cSession\u201d.\nindex_params (Optional[dict], optional) \u2013 Which index_params to use. Defaults\nto None.\nsearch_params (Optional[dict], optional) \u2013 Which search params to use.\nDefaults to None.\ndrop_old (Optional[bool], optional) \u2013 Whether to drop the collection with\nthat name if it exists. Defaults to False.\nReturns\nMilvus Vector Store\nReturn type\nMilvus\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a search and return results that are reordered by MMR.\nParameters\nquery (str) \u2013 The text being searched.\nk (int, optional) \u2013 How many results to give. Defaults to 4.\nfetch_k (int, optional) \u2013 Total results to select k from.\nDefaults to 20.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5\nparam (dict, optional) \u2013 The search params for the specified index.\nDefaults to None.\nexpr (str, optional) \u2013 Filtering expression. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "247f87d8ab8a-10", "text": "Defaults to None.\nexpr (str, optional) \u2013 Filtering expression. Defaults to None.\ntimeout (int, optional) \u2013 How long to wait before timeout error.\nDefaults to None.\nkwargs \u2013 Collection.search() keyword arguments.\nReturns\nDocument results for search.\nReturn type\nList[Document]\nmax_marginal_relevance_search_by_vector(embedding: list[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a search and return results that are reordered by MMR.\nParameters\nembedding (str) \u2013 The embedding vector being searched.\nk (int, optional) \u2013 How many results to give. Defaults to 4.\nfetch_k (int, optional) \u2013 Total results to select k from.\nDefaults to 20.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5\nparam (dict, optional) \u2013 The search params for the specified index.\nDefaults to None.\nexpr (str, optional) \u2013 Filtering expression. Defaults to None.\ntimeout (int, optional) \u2013 How long to wait before timeout error.\nDefaults to None.\nkwargs \u2013 Collection.search() keyword arguments.\nReturns\nDocument results for search.\nReturn type\nList[Document]\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "247f87d8ab8a-11", "text": "Return docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a similarity search against the query string.\nParameters\nquery (str) \u2013 The text to search.\nk (int, optional) \u2013 How many results to return. Defaults to 4.\nparam (dict, optional) \u2013 The search params for the index type.\nDefaults to None.\nexpr (str, optional) \u2013 Filtering expression. Defaults to None.\ntimeout (int, optional) \u2013 How long to wait before timeout error.\nDefaults to None.\nkwargs \u2013 Collection.search() keyword arguments.\nReturns\nDocument results for search.\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a similarity search against the query string.\nParameters\nembedding (List[float]) \u2013 The embedding vector to search.\nk (int, optional) \u2013 How many results to return. Defaults to 4.\nparam (dict, optional) \u2013 The search params for the index type.\nDefaults to None.\nexpr (str, optional) \u2013 Filtering expression. Defaults to None.\ntimeout (int, optional) \u2013 How long to wait before timeout error.\nDefaults to None.\nkwargs \u2013 Collection.search() keyword arguments.\nReturns\nDocument results for search.\nReturn type\nList[Document]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "247f87d8ab8a-12", "text": "Returns\nDocument results for search.\nReturn type\nList[Document]\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPerform a search on a query string and return results with score.\nFor more information about the search parameters, take a look at the pymilvus\ndocumentation found here:\nhttps://milvus.io/api-reference/pymilvus/v2.2.6/Collection/search().md\nParameters\nquery (str) \u2013 The text being searched.\nk (int, optional) \u2013 The amount of results to return. Defaults to 4.\nparam (dict) \u2013 The search params for the specified index.\nDefaults to None.\nexpr (str, optional) \u2013 Filtering expression. Defaults to None.\ntimeout (int, optional) \u2013 How long to wait before timeout error.\nDefaults to None.\nkwargs \u2013 Collection.search() keyword arguments.\nReturn type\nList[float], List[Tuple[Document, any, any]]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "247f87d8ab8a-13", "text": "Return type\nList[float], List[Tuple[Document, any, any]]\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPerform a search on a query string and return results with score.\nFor more information about the search parameters, take a look at the pymilvus\ndocumentation found here:\nhttps://milvus.io/api-reference/pymilvus/v2.2.6/Collection/search().md\nParameters\nembedding (List[float]) \u2013 The embedding vector being searched.\nk (int, optional) \u2013 The amount of results to return. Defaults to 4.\nparam (dict) \u2013 The search params for the specified index.\nDefaults to None.\nexpr (str, optional) \u2013 Filtering expression. Defaults to None.\ntimeout (int, optional) \u2013 How long to wait before timeout error.\nDefaults to None.\nkwargs \u2013 Collection.search() keyword arguments.\nReturns\nResult doc and score.\nReturn type\nList[Tuple[Document, float]]\nExamples using Milvus\u00b6\nMilvus\nZilliz", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.milvus.Milvus.html"}
{"id": "684ccc7520ce-0", "text": "langchain.vectorstores.cassandra.Cassandra\u00b6\nclass langchain.vectorstores.cassandra.Cassandra(embedding: Embeddings, session: Session, keyspace: str, table_name: str, ttl_seconds: Optional[int] = None)[source]\u00b6\nWrapper around Apache Cassandra(R) for vector-store workloads.\nTo use it, you need a recent installation of the cassio library\nand a Cassandra cluster / Astra DB instance supporting vector capabilities.\nVisit the cassio.org website for extensive quickstarts and code examples.\nExample\nfrom langchain.vectorstores import Cassandra\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nsession = ...             # create your Cassandra session object\nkeyspace = 'my_keyspace'  # the keyspace should exist already\ntable_name = 'my_vector_store'\nvectorstore = Cassandra(embeddings, session, keyspace, table_name)\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding,\u00a0session,\u00a0keyspace,\u00a0...)\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0...])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.cassandra.Cassandra.html"}
{"id": "684ccc7520ce-1", "text": "Return VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\nclear()\nEmpty the collection.\ndelete([ids])\nDelete by vector IDs.\ndelete_by_document_id(document_id)\ndelete_collection()\nJust an alias for clear (to better align with other VectorStore implementations).\nfrom_documents(documents,\u00a0embedding[,\u00a0...])\nCreate a Cassandra vectorstore from a document list.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreate a Cassandra vectorstore from raw texts.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.cassandra.Cassandra.html"}
{"id": "684ccc7520ce-2", "text": "max_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param query: Text to look up documents similar to. :param k: Number of Documents to return. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. :param lambda_mult: Number between 0 and 1 that determines the degree                     of diversity among the results with 0 corresponding                     to maximum diversity and 1 to minimum diversity. Optional.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param embedding: Embedding to look up documents similar to. :param k: Number of Documents to return. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. :param lambda_mult: Number between 0 and 1 that determines the degree                     of diversity among the results with 0 corresponding                     to maximum diversity and 1 to minimum diversity.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nRun similarity search with distance.\nsimilarity_search_with_score_by_vector(embedding)\nReturn docs most similar to embedding vector.\nsimilarity_search_with_score_id(query[,\u00a0k,\u00a0...])\nsimilarity_search_with_score_id_by_vector(...)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.cassandra.Cassandra.html"}
{"id": "684ccc7520ce-3", "text": "similarity_search_with_score_id_by_vector(...)\nReturn docs most similar to embedding vector.\n__init__(embedding: Embeddings, session: Session, keyspace: str, table_name: str, ttl_seconds: Optional[int] = None) \u2192 None[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, batch_size: int = 16, ttl_seconds: Optional[int] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts (Iterable[str]) \u2013 Texts to add to the vectorstore.\nmetadatas (Optional[List[dict]], optional) \u2013 Optional list of metadatas.\nids (Optional[List[str]], optional) \u2013 Optional list of IDs.\nbatch_size (int) \u2013 Number of concurrent requests to send to the server.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.cassandra.Cassandra.html"}
{"id": "684ccc7520ce-4", "text": "batch_size (int) \u2013 Number of concurrent requests to send to the server.\nttl_seconds (Optional[int], optional) \u2013 Optional time-to-live\nfor the added texts.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.cassandra.Cassandra.html"}
{"id": "684ccc7520ce-5", "text": "Parameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.cassandra.Cassandra.html"}
{"id": "684ccc7520ce-6", "text": "docsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\nclear() \u2192 None[source]\u00b6\nEmpty the collection.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector IDs.\nParameters\nids \u2013 List of ids to delete.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.cassandra.Cassandra.html"}
{"id": "684ccc7520ce-7", "text": "False otherwise, None if not implemented.\nReturn type\nOptional[bool]\ndelete_by_document_id(document_id: str) \u2192 None[source]\u00b6\ndelete_collection() \u2192 None[source]\u00b6\nJust an alias for clear\n(to better align with other VectorStore implementations).\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, batch_size: int = 16, **kwargs: Any) \u2192 CVST[source]\u00b6\nCreate a Cassandra vectorstore from a document list.\nNo support for specifying text IDs\nReturns\na Cassandra vectorstore.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, batch_size: int = 16, **kwargs: Any) \u2192 CVST[source]\u00b6\nCreate a Cassandra vectorstore from raw texts.\nNo support for specifying text IDs\nReturns\na Cassandra vectorstore.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\n:param query: Text to look up documents similar to.\n:param k: Number of Documents to return.\n:param fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n:param lambda_mult: Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nOptional.\nReturns\nList of Documents selected by maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.cassandra.Cassandra.html"}
{"id": "684ccc7520ce-8", "text": "Optional.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\n:param embedding: Embedding to look up documents similar to.\n:param k: Number of Documents to return.\n:param fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n:param lambda_mult: Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.cassandra.Cassandra.html"}
{"id": "684ccc7520ce-9", "text": "Returns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with distance.\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding (str) \u2013 Embedding to look up documents similar to.\nk (int) \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of (Document, score), the most similar to the query vector.\nsimilarity_search_with_score_id(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None) \u2192 List[Tuple[Document, float, str]][source]\u00b6\nsimilarity_search_with_score_id_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None) \u2192 List[Tuple[Document, float, str]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.cassandra.Cassandra.html"}
{"id": "684ccc7520ce-10", "text": "Return docs most similar to embedding vector.\nParameters\nembedding (str) \u2013 Embedding to look up documents similar to.\nk (int) \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of (Document, score, id), the most similar to the query vector.\nExamples using Cassandra\u00b6\nCassandra", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.cassandra.Cassandra.html"}
{"id": "ce564775ab2e-0", "text": "langchain.vectorstores.nucliadb.NucliaDB\u00b6\nclass langchain.vectorstores.nucliadb.NucliaDB(knowledge_box: str, local: bool, api_key: Optional[str] = None, backend: Optional[str] = None)[source]\u00b6\nNucliaDB vector store.\nInitialize the NucliaDB client.\nParameters\nknowledge_box \u2013 the Knowledge Box id.\nlocal \u2013 Whether to use a local NucliaDB instance or Nuclia Cloud\napi_key \u2013 A contributor API key for the kb (needed when local is False)\nbackend \u2013 The backend url to use when local is True, defaults to\nhttp \u2013 //localhost:8080\nAttributes\nembeddings\nAccess the query embedding object if available.\nis_local\nkb_url\nMethods\n__init__(knowledge_box,\u00a0local[,\u00a0api_key,\u00a0...])\nInitialize the NucliaDB client.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nUpload texts to NucliaDB\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.nucliadb.NucliaDB.html"}
{"id": "ce564775ab2e-1", "text": "Return docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\n__init__(knowledge_box: str, local: bool, api_key: Optional[str] = None, backend: Optional[str] = None) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.nucliadb.NucliaDB.html"}
{"id": "ce564775ab2e-2", "text": "Initialize the NucliaDB client.\nParameters\nknowledge_box \u2013 the Knowledge Box id.\nlocal \u2013 Whether to use a local NucliaDB instance or Nuclia Cloud\napi_key \u2013 A contributor API key for the kb (needed when local is False)\nbackend \u2013 The backend url to use when local is True, defaults to\nhttp \u2013 //localhost:8080\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nUpload texts to NucliaDB\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.nucliadb.NucliaDB.html"}
{"id": "ce564775ab2e-3", "text": "False otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.nucliadb.NucliaDB.html"}
{"id": "ce564775ab2e-4", "text": "lambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.nucliadb.NucliaDB.html"}
{"id": "ce564775ab2e-5", "text": "Return docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.nucliadb.NucliaDB.html"}
{"id": "ce564775ab2e-6", "text": "Return docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.nucliadb.NucliaDB.html"}
{"id": "ce564775ab2e-7", "text": "Return docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.\nExamples using NucliaDB\u00b6\nNucliaDB", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.nucliadb.NucliaDB.html"}
{"id": "02ad14e0ee6c-0", "text": "langchain.vectorstores.redis.base.check_index_exists\u00b6\nlangchain.vectorstores.redis.base.check_index_exists(client: RedisType, index_name: str) \u2192 bool[source]\u00b6\nCheck if Redis index exists.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.check_index_exists.html"}
{"id": "89b8bed8cefa-0", "text": "langchain.vectorstores.dingo.Dingo\u00b6\nclass langchain.vectorstores.dingo.Dingo(embedding: Embeddings, text_key: str, *, client: Any = None, index_name: Optional[str] = None, dimension: int = 1024, host: Optional[List[str]] = None, user: str = 'root', password: str = '123123', self_id: bool = False)[source]\u00b6\nDingo vector store.\nTo use, you should have the dingodb python package installed.\nExample\nfrom langchain.vectorstores import Dingo\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\ndingo = Dingo(embeddings, \"text\")\nInitialize with Dingo client.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding,\u00a0text_key,\u00a0*[,\u00a0client,\u00a0...])\nInitialize with Dingo client.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0text_key,\u00a0...])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dingo.Dingo.html"}
{"id": "89b8bed8cefa-1", "text": "amax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector IDs or filter.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nConstruct Dingo wrapper from raw documents.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0search_params,\u00a0...])\nReturn Dingo documents most similar to query, along with scores.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dingo.Dingo.html"}
{"id": "89b8bed8cefa-2", "text": "Return docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nReturn Dingo documents most similar to query, along with scores.\n__init__(embedding: Embeddings, text_key: str, *, client: Any = None, index_name: Optional[str] = None, dimension: int = 1024, host: Optional[List[str]] = None, user: str = 'root', password: str = '123123', self_id: bool = False)[source]\u00b6\nInitialize with Dingo client.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, text_key: str = 'text', batch_size: int = 500, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dingo.Dingo.html"}
{"id": "89b8bed8cefa-3", "text": "Parameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of ids to associate with the texts.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dingo.Dingo.html"}
{"id": "89b8bed8cefa-4", "text": "Parameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dingo.Dingo.html"}
{"id": "89b8bed8cefa-5", "text": "docsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nDelete by vector IDs or filter.\n:param ids: List of ids to delete.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dingo.Dingo.html"}
{"id": "89b8bed8cefa-6", "text": "Return VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, text_key: str = 'text', index_name: Optional[str] = None, dimension: int = 1024, client: Any = None, host: List[str] = ['172.20.31.10:13000'], user: str = 'root', password: str = '123123', batch_size: int = 500, **kwargs: Any) \u2192 Dingo[source]\u00b6\nConstruct Dingo wrapper from raw documents.\nThis is a user friendly interface that:\nEmbeds documents.\nAdds the documents to a provided Dingo index\nThis is intended to be a quick way to get started.\nExample:from langchain.vectorstores import Dingo\nfrom langchain.embeddings import OpenAIEmbeddings\nimport dingodb\nsssembeddings = OpenAIEmbeddings()\ndingo = Dingo.from_texts(\ntexts,\nembeddings,\nindex_name=\u201dlangchain-demo\u201d\n)\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, search_params: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dingo.Dingo.html"}
{"id": "89b8bed8cefa-7", "text": "of diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, search_params: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, search_params: Optional[dict] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn Dingo documents most similar to query, along with scores.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nsearch_params \u2013 Dictionary of argument(s) to filter on metadata\nReturns\nList of Documents most similar to the query and score for each", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dingo.Dingo.html"}
{"id": "89b8bed8cefa-8", "text": "Returns\nList of Documents most similar to the query and score for each\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, search_params: Optional[dict] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn Dingo documents most similar to query, along with scores.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nsearch_params \u2013 Dictionary of argument(s) to filter on metadata\nReturns\nList of Documents most similar to the query and score for each", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.dingo.Dingo.html"}
{"id": "2c17eb4ee3b4-0", "text": "langchain.vectorstores.elasticsearch.BaseRetrievalStrategy\u00b6\nclass langchain.vectorstores.elasticsearch.BaseRetrievalStrategy[source]\u00b6\nBase class for Elasticsearch retrieval strategies.\nMethods\n__init__()\nbefore_index_setup(client,\u00a0text_field,\u00a0...)\nExecutes before the index is created.\nindex(dims_length,\u00a0vector_query_field,\u00a0...)\nExecutes when the index is created.\nquery(query_vector,\u00a0query,\u00a0*,\u00a0k,\u00a0fetch_k,\u00a0...)\nExecutes when a search is performed on the store.\nrequire_inference()\nReturns whether or not the strategy requires inference to be performed on the text before it is added to the index.\n__init__()\u00b6\nbefore_index_setup(client: Elasticsearch, text_field: str, vector_query_field: str) \u2192 None[source]\u00b6\nExecutes before the index is created. Used for setting up\nany required Elasticsearch resources like a pipeline.\nParameters\nclient \u2013 The Elasticsearch client.\ntext_field \u2013 The field containing the text data in the index.\nvector_query_field \u2013 The field containing the vector\nrepresentations in the index.\nabstract index(dims_length: Optional[int], vector_query_field: str, similarity: Optional[DistanceStrategy]) \u2192 Dict[source]\u00b6\nExecutes when the index is created.\nParameters\ndims_length \u2013 Numeric length of the embedding vectors,\nor None if not using vector-based query.\nvector_query_field \u2013 The field containing the vector\nrepresentations in the index.\nsimilarity \u2013 The similarity strategy to use,\nor None if not using one.\nReturns\nThe Elasticsearch settings and mappings for the strategy.\nReturn type\nDict\nabstract query(query_vector: Optional[List[float]], query: Optional[str], *, k: int, fetch_k: int, vector_query_field: str, text_field: str, filter: List[dict], similarity: Optional[DistanceStrategy]) \u2192 Dict[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.BaseRetrievalStrategy.html"}
{"id": "2c17eb4ee3b4-1", "text": "Executes when a search is performed on the store.\nParameters\nquery_vector \u2013 The query vector,\nor None if not using vector-based query.\nquery \u2013 The text query, or None if not using text-based query.\nk \u2013 The total number of results to retrieve.\nfetch_k \u2013 The number of results to fetch initially.\nvector_query_field \u2013 The field containing the vector\nrepresentations in the index.\ntext_field \u2013 The field containing the text data in the index.\nfilter \u2013 List of filter clauses to apply to the query.\nsimilarity \u2013 The similarity strategy to use, or None if not using one.\nReturns\nThe Elasticsearch query body.\nReturn type\nDict\nrequire_inference() \u2192 bool[source]\u00b6\nReturns whether or not the strategy requires inference\nto be performed on the text before it is added to the index.\nReturns\nWhether or not the strategy requires inference\nto be performed on the text before it is added to the index.\nReturn type\nbool", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.BaseRetrievalStrategy.html"}
{"id": "5fed08fb4e1c-0", "text": "langchain.vectorstores.astradb.AstraDB\u00b6\nclass langchain.vectorstores.astradb.AstraDB(*, embedding: Embeddings, collection_name: str, token: Optional[str] = None, api_endpoint: Optional[str] = None, astra_db_client: Optional[Any] = None, namespace: Optional[str] = None, metric: Optional[str] = None, batch_size: Optional[int] = None, bulk_insert_batch_concurrency: Optional[int] = None, bulk_insert_overwrite_concurrency: Optional[int] = None, bulk_delete_concurrency: Optional[int] = None)[source]\u00b6\nWrapper around DataStax Astra DB for vector-store workloads.\nTo use it, you need a recent installation of the astrapy library\nand an Astra DB cloud database.\nFor quickstart and details, visit:docs.datastax.com/en/astra/home/astra.html\nExample\nfrom langchain.vectorstores import AstraDB\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nvectorstore = AstraDB(\n  embedding=embeddings,\n  collection_name=\"my_store\",\n  token=\"AstraCS:...\",\n  api_endpoint=\"https://<DB-ID>-us-east1.apps.astra.datastax.com\"\n)\nvectorstore.add_texts([\"Giraffes\", \"All good here\"])\nresults = vectorstore.similarity_search(\"Everything's ok\", k=1)\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(*,\u00a0embedding,\u00a0collection_name[,\u00a0...])\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.astradb.AstraDB.html"}
{"id": "5fed08fb4e1c-1", "text": "Run more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0...])\nRun texts through the embeddings and add them to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\nclear()\nEmpty the collection of all its stored entries.\ndelete([ids,\u00a0concurrency])\nDelete by vector ids.\ndelete_by_document_id(document_id)\nRemove a single document from the store, given its document_id (str).\ndelete_collection()\nCompletely delete the collection from the database (as opposed to 'clear()', which empties it only).", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.astradb.AstraDB.html"}
{"id": "5fed08fb4e1c-2", "text": "from_documents(documents,\u00a0embedding,\u00a0**kwargs)\nCreate an Astra DB vectorstore from a document list.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0ids])\nCreate an Astra DB vectorstore from raw texts.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param query: Text to look up documents similar to. :type query: str :param k: Number of Documents to return. :type k: int = 4 :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. :type fetch_k: int = 20 :param lambda_mult: Number between 0 and 1 that determines the degree                     of diversity among the results with 0 corresponding                     to maximum diversity and 1 to minimum diversity. Optional. :type lambda_mult: float = 0.5.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param embedding: Embedding to look up documents similar to. :param k: Number of Documents to return. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. :param lambda_mult: Number between 0 and 1 that determines the degree                     of diversity among the results with 0 corresponding                     to maximum diversity and 1 to minimum diversity.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.astradb.AstraDB.html"}
{"id": "5fed08fb4e1c-3", "text": "Return docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nRun similarity search with distance.\nsimilarity_search_with_score_by_vector(embedding)\nReturn docs most similar to embedding vector.\nsimilarity_search_with_score_id(query[,\u00a0k,\u00a0...])\nsimilarity_search_with_score_id_by_vector(...)\nReturn docs most similar to embedding vector.\n__init__(*, embedding: Embeddings, collection_name: str, token: Optional[str] = None, api_endpoint: Optional[str] = None, astra_db_client: Optional[Any] = None, namespace: Optional[str] = None, metric: Optional[str] = None, batch_size: Optional[int] = None, bulk_insert_batch_concurrency: Optional[int] = None, bulk_insert_overwrite_concurrency: Optional[int] = None, bulk_delete_concurrency: Optional[int] = None) \u2192 None[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.astradb.AstraDB.html"}
{"id": "5fed08fb4e1c-4", "text": "(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, *, batch_size: Optional[int] = None, batch_concurrency: Optional[int] = None, overwrite_concurrency: Optional[int] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun texts through the embeddings and add them to the vectorstore.\nIf passing explicit ids, those entries whose id is in the store already\nwill be replaced.\nParameters\ntexts (Iterable[str]) \u2013 Texts to add to the vectorstore.\nmetadatas (Optional[List[dict]], optional) \u2013 Optional list of metadatas.\nids (Optional[List[str]], optional) \u2013 Optional list of ids.\nbatch_size (Optional[int]) \u2013 Number of documents in each API call.\nCheck the underlying Astra DB HTTP API specs for the max value\n(20 at the time of writing this). If not provided, defaults\nto the instance-level setting.\nbatch_concurrency (Optional[int]) \u2013 number of threads to process\ninsertion batches concurrently. Defaults to instance-level\nsetting if not provided.\noverwrite_concurrency (Optional[int]) \u2013 number of threads to process\npre-existing documents in each batch (which require individual\nAPI calls). Defaults to instance-level setting if not provided.\nA note on metadata: there are constraints on the allowed field names\nin this dictionary, coming from the underlying Astra DB API.\nFor instance, the $ (dollar sign) cannot be used in the dict keys.\nSee this document for details:\ndocs.datastax.com/en/astra-serverless/docs/develop/dev-with-json.html\nReturns\nList of ids of the added texts.\nReturn type", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.astradb.AstraDB.html"}
{"id": "5fed08fb4e1c-5", "text": "Returns\nList of ids of the added texts.\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.astradb.AstraDB.html"}
{"id": "5fed08fb4e1c-6", "text": "\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.astradb.AstraDB.html"}
{"id": "5fed08fb4e1c-7", "text": "Return docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\nclear() \u2192 None[source]\u00b6\nEmpty the collection of all its stored entries.\ndelete(ids: Optional[List[str]] = None, concurrency: Optional[int] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ids.\nParameters\nids (Optional[List[str]]) \u2013 List of ids to delete.\nconcurrency (Optional[int]) \u2013 max number of threads issuing\nsingle-doc delete requests. Defaults to instance-level setting.\nReturns\nTrue if deletion is successful,False otherwise, None if not implemented.\nReturn type\nOptional[bool]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.astradb.AstraDB.html"}
{"id": "5fed08fb4e1c-8", "text": "Return type\nOptional[bool]\ndelete_by_document_id(document_id: str) \u2192 bool[source]\u00b6\nRemove a single document from the store, given its document_id (str).\nReturn True if a document has indeed been deleted, False if ID not found.\ndelete_collection() \u2192 None[source]\u00b6\nCompletely delete the collection from the database (as opposed\nto \u2018clear()\u2019, which empties it only).\nStored data is lost and unrecoverable, resources are freed.\nUse with caution.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 ADBVST[source]\u00b6\nCreate an Astra DB vectorstore from a document list.\nUtility method that defers to \u2018from_texts\u2019 (see that one).\nArgs: see \u2018from_texts\u2019, except here you have to supply \u2018documents\u2019in place of \u2018texts\u2019 and \u2018metadatas\u2019.\nReturns\nan AstraDB vectorstore.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 ADBVST[source]\u00b6\nCreate an Astra DB vectorstore from raw texts.\nParameters\ntexts (List[str]) \u2013 the texts to insert.\nembedding (Embeddings) \u2013 the embedding function to use in the store.\nmetadatas (Optional[List[dict]]) \u2013 metadata dicts for the texts.\nids (Optional[List[str]]) \u2013 ids to associate to the texts.\narguments* (*Additional) \u2013 you can pass any argument that you would\nto \u2018add_texts\u2019 and/or to the \u2018AstraDB\u2019 class constructor\n(see these methods for details). These arguments will be\nrouted to the respective methods as they are.\nReturns\nan AstraDb vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.astradb.AstraDB.html"}
{"id": "5fed08fb4e1c-9", "text": "Returns\nan AstraDb vectorstore.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\n:param query: Text to look up documents similar to.\n:type query: str\n:param k: Number of Documents to return.\n:type k: int = 4\n:param fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n:type fetch_k: int = 20\n:param lambda_mult: Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nOptional.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\n:param embedding: Embedding to look up documents similar to.\n:param k: Number of Documents to return.\n:param fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n:param lambda_mult: Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nReturns\nList of Documents selected by maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.astradb.AstraDB.html"}
{"id": "5fed08fb4e1c-10", "text": "Returns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.astradb.AstraDB.html"}
{"id": "5fed08fb4e1c-11", "text": "Run similarity search with distance.\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding (str) \u2013 Embedding to look up documents similar to.\nk (int) \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of (Document, score), the most similar to the query vector.\nsimilarity_search_with_score_id(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None) \u2192 List[Tuple[Document, float, str]][source]\u00b6\nsimilarity_search_with_score_id_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None) \u2192 List[Tuple[Document, float, str]][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding (str) \u2013 Embedding to look up documents similar to.\nk (int) \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of (Document, score, id), the most similar to the query vector.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.astradb.AstraDB.html"}
{"id": "6eb4c8868dda-0", "text": "langchain.vectorstores.qdrant.Qdrant\u00b6\nclass langchain.vectorstores.qdrant.Qdrant(client: Any, collection_name: str, embeddings: Optional[Embeddings] = None, content_payload_key: str = 'page_content', metadata_payload_key: str = 'metadata', distance_strategy: str = 'COSINE', vector_name: Optional[str] = None, embedding_function: Optional[Callable] = None)[source]\u00b6\nQdrant vector store.\nTo use you should have the qdrant-client package installed.\nExample\nfrom qdrant_client import QdrantClient\nfrom langchain.vectorstores import Qdrant\nclient = QdrantClient()\ncollection_name = \"MyCollection\"\nqdrant = Qdrant(client, collection_name, embedding_function)\nInitialize with necessary components.\nAttributes\nCONTENT_KEY\nMETADATA_KEY\nVECTOR_NAME\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(client,\u00a0collection_name[,\u00a0...])\nInitialize with necessary components.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0batch_size])\nRun more texts through the embeddings and add to the vectorstore.\naconstruct_instance(texts,\u00a0embedding[,\u00a0...])\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0batch_size])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-1", "text": "Return VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nConstruct Qdrant wrapper from a list of texts.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-2", "text": "amax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param query: Text to look up documents similar to. :param k: Number of Documents to return. Defaults to 4. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. Defaults to 20. :param lambda_mult: Number between 0 and 1 that determines the degree                     of diversity among the results with 0 corresponding                     to maximum diversity and 1 to minimum diversity. Defaults to 0.5. :param filter: Filter by metadata. Defaults to None. :param search_params: Additional search params :param score_threshold: Define a minimal score threshold for the result. If defined, less similar results will not be returned. Score of the returned result might be higher or smaller than the                         threshold depending on the Distance function used. E.g. for cosine similarity only higher scores will be returned. :param consistency: Read consistency of the search. Defines how many replicas should be                     queried before returning the result. Values:                     - int - number of replicas to query, values should present in all                             queried replicas                     - 'majority' - query all replicas, but return values present in the                                    majority of replicas                     - 'quorum' - query the majority of replicas, return values present in                                  all of them                     - 'all' - query all replicas, and return values present in all replicas :param **kwargs: Any other named arguments to pass through to                    QdrantClient.async_grpc_points.Search().\namax_marginal_relevance_search_with_score_by_vector(...)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-3", "text": "amax_marginal_relevance_search_with_score_by_vector(...)\nReturn docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param query: Text to look up documents similar to. :param k: Number of Documents to return. Defaults to 4. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. Defaults to 20. :param lambda_mult: Number between 0 and 1 that determines the degree                     of diversity among the results with 0 corresponding                     to maximum diversity and 1 to minimum diversity. Defaults to 0.5.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nReturn docs most similar to query.\nasimilarity_search_with_score_by_vector(...)\nReturn docs most similar to embedding vector.\nconstruct_instance(texts,\u00a0embedding[,\u00a0...])\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nConstruct Qdrant wrapper from a list of texts.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-4", "text": "Return docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_with_score_by_vector(...)\nReturn docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param query: Text to look up documents similar to. :param k: Number of Documents to return. Defaults to 4. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. Defaults to 20. :param lambda_mult: Number between 0 and 1 that determines the degree                     of diversity among the results with 0 corresponding                     to maximum diversity and 1 to minimum diversity. Defaults to 0.5. :param filter: Filter by metadata. Defaults to None. :param search_params: Additional search params :param score_threshold: Define a minimal score threshold for the result. If defined, less similar results will not be returned. Score of the returned result might be higher or smaller than the                         threshold depending on the Distance function used. E.g. for cosine similarity only higher scores will be returned. :param consistency: Read consistency of the search. Defines how many replicas should be                     queried before returning the result. Values:                     - int - number of replicas to query, values should present in all                             queried replicas                     - 'majority' - query all replicas, but return values present in the                                    majority of replicas                     - 'quorum' - query the majority of replicas, return values present in                                  all of them                     - 'all' - query all replicas, and return values present in all replicas :param **kwargs: Any other named arguments to pass through to QdrantClient.search().\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-5", "text": "Return docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter,\u00a0...])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nReturn docs most similar to query.\nsimilarity_search_with_score_by_vector(embedding)\nReturn docs most similar to embedding vector.\n__init__(client: Any, collection_name: str, embeddings: Optional[Embeddings] = None, content_payload_key: str = 'page_content', metadata_payload_key: str = 'metadata', distance_strategy: str = 'COSINE', vector_name: Optional[str] = None, embedding_function: Optional[Callable] = None)[source]\u00b6\nInitialize with necessary components.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[Sequence[str]] = None, batch_size: int = 64, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of ids to associate with the texts. Ids have to be\nuuid-like strings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-6", "text": "uuid-like strings.\nbatch_size \u2013 How many vectors upload per-request.\nDefault: 64\nReturns\nList of ids from adding the texts into the vectorstore.\nasync classmethod aconstruct_instance(texts: List[str], embedding: Embeddings, location: Optional[str] = None, url: Optional[str] = None, port: Optional[int] = 6333, grpc_port: int = 6334, prefer_grpc: bool = False, https: Optional[bool] = None, api_key: Optional[str] = None, prefix: Optional[str] = None, timeout: Optional[float] = None, host: Optional[str] = None, path: Optional[str] = None, collection_name: Optional[str] = None, distance_func: str = 'Cosine', content_payload_key: str = 'page_content', metadata_payload_key: str = 'metadata', vector_name: Optional[str] = None, shard_number: Optional[int] = None, replication_factor: Optional[int] = None, write_consistency_factor: Optional[int] = None, on_disk_payload: Optional[bool] = None, hnsw_config: Optional[common_types.HnswConfigDiff] = None, optimizers_config: Optional[common_types.OptimizersConfigDiff] = None, wal_config: Optional[common_types.WalConfigDiff] = None, quantization_config: Optional[common_types.QuantizationConfig] = None, init_from: Optional[common_types.InitFrom] = None, on_disk: Optional[bool] = None, force_recreate: bool = False, **kwargs: Any) \u2192 Qdrant[source]\u00b6\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-7", "text": "(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[Sequence[str]] = None, batch_size: int = 64, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of ids to associate with the texts. Ids have to be\nuuid-like strings.\nbatch_size \u2013 How many vectors upload per-request.\nDefault: 64\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-8", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[Sequence[str]] = None, location: Optional[str] = None, url: Optional[str] = None, port: Optional[int] = 6333, grpc_port: int = 6334, prefer_grpc: bool = False, https: Optional[bool] = None, api_key: Optional[str] = None, prefix: Optional[str] = None, timeout: Optional[float] = None, host: Optional[str] = None, path: Optional[str] = None, collection_name: Optional[str] = None, distance_func: str = 'Cosine', content_payload_key: str = 'page_content', metadata_payload_key: str = 'metadata', vector_name: Optional[str] = None, batch_size: int = 64, shard_number: Optional[int] = None, replication_factor: Optional[int] = None, write_consistency_factor: Optional[int] = None, on_disk_payload: Optional[bool] = None, hnsw_config: Optional[common_types.HnswConfigDiff] = None, optimizers_config: Optional[common_types.OptimizersConfigDiff] = None, wal_config: Optional[common_types.WalConfigDiff] = None, quantization_config: Optional[common_types.QuantizationConfig] = None, init_from: Optional[common_types.InitFrom] = None, on_disk: Optional[bool] = None, force_recreate: bool = False, **kwargs: Any) \u2192 Qdrant[source]\u00b6\nConstruct Qdrant wrapper from a list of texts.\nParameters\ntexts \u2013 A list of texts to be indexed in Qdrant.\nembedding \u2013 A subclass of Embeddings, responsible for text vectorization.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-9", "text": "embedding \u2013 A subclass of Embeddings, responsible for text vectorization.\nmetadatas \u2013 An optional list of metadata. If provided it has to be of the same\nlength as a list of texts.\nids \u2013 Optional list of ids to associate with the texts. Ids have to be\nuuid-like strings.\nlocation \u2013 If :memory: - use in-memory Qdrant instance.\nIf str - use it as a url parameter.\nIf None - fallback to relying on host and port parameters.\nurl \u2013 either host or str of \u201cOptional[scheme], host, Optional[port],\nOptional[prefix]\u201d. Default: None\nport \u2013 Port of the REST API interface. Default: 6333\ngrpc_port \u2013 Port of the gRPC interface. Default: 6334\nprefer_grpc \u2013 If true - use gPRC interface whenever possible in custom methods.\nDefault: False\nhttps \u2013 If true - use HTTPS(SSL) protocol. Default: None\napi_key \u2013 API key for authentication in Qdrant Cloud. Default: None\nprefix \u2013 If not None - add prefix to the REST URL path.\nExample: service/v1 will result in\nhttp://localhost:6333/service/v1/{qdrant-endpoint} for REST API.\nDefault: None\ntimeout \u2013 Timeout for REST and gRPC API requests.\nDefault: 5.0 seconds for REST and unlimited for gRPC\nhost \u2013 Host name of Qdrant service. If url and host are None, set to\n\u2018localhost\u2019. Default: None\npath \u2013 Path in which the vectors will be stored while using local mode.\nDefault: None\ncollection_name \u2013 Name of the Qdrant collection to be used. If not provided,\nit will be created randomly. Default: None\ndistance_func \u2013 Distance function. One of: \u201cCosine\u201d / \u201cEuclid\u201d / \u201cDot\u201d.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-10", "text": "Default: \u201cCosine\u201d\ncontent_payload_key \u2013 A payload key used to store the content of the document.\nDefault: \u201cpage_content\u201d\nmetadata_payload_key \u2013 A payload key used to store the metadata of the document.\nDefault: \u201cmetadata\u201d\nvector_name \u2013 Name of the vector to be used internally in Qdrant.\nDefault: None\nbatch_size \u2013 How many vectors upload per-request.\nDefault: 64\nshard_number \u2013 Number of shards in collection. Default is 1, minimum is 1.\nreplication_factor \u2013 Replication factor for collection. Default is 1, minimum is 1.\nDefines how many copies of each shard will be created.\nHave effect only in distributed mode.\nwrite_consistency_factor \u2013 Write consistency factor for collection. Default is 1, minimum is 1.\nDefines how many replicas should apply the operation for us to consider\nit successful. Increasing this number will make the collection more\nresilient to inconsistencies, but will also make it fail if not enough\nreplicas are available.\nDoes not have any performance impact.\nHave effect only in distributed mode.\non_disk_payload \u2013 If true - point`s payload will not be stored in memory.\nIt will be read from the disk every time it is requested.\nThis setting saves RAM by (slightly) increasing the response time.\nNote: those payload values that are involved in filtering and are\nindexed - remain in RAM.\nhnsw_config \u2013 Params for HNSW index\noptimizers_config \u2013 Params for optimizer\nwal_config \u2013 Params for Write-Ahead-Log\nquantization_config \u2013 Params for quantization, if None - quantization will be disabled\ninit_from \u2013 Use data stored in another collection to initialize this collection\nforce_recreate \u2013 Force recreating the collection\n**kwargs \u2013 Additional arguments passed directly into REST client initialization\nThis is a user-friendly interface that:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-11", "text": "This is a user-friendly interface that:\n1. Creates embeddings, one for each text\n2. Initializes the Qdrant database as an in-memory docstore by default\n(and overridable to a remote docstore)\nAdds the text embeddings to the Qdrant database\nThis is intended to be a quick way to get started.\nExample\nfrom langchain.vectorstores import Qdrant\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nqdrant = await Qdrant.afrom_texts(texts, embeddings, \"localhost\")\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nDefaults to 20.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter \u2013 Filter by metadata. Defaults to None.\nsearch_params \u2013 Additional search params\nscore_threshold \u2013 Define a minimal score threshold for the result.\nIf defined, less similar results will not be returned.\nScore of the returned result might be higher or smaller than the", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-12", "text": "Score of the returned result might be higher or smaller than the\nthreshold depending on the Distance function used.\nE.g. for cosine similarity only higher scores will be returned.\nconsistency \u2013 Read consistency of the search. Defines how many replicas should be\nqueried before returning the result.\nValues:\n- int - number of replicas to query, values should present in all\nqueried replicas\n\u2019majority\u2019 - query all replicas, but return values present in themajority of replicas\n\u2019quorum\u2019 - query the majority of replicas, return values present inall of them\n\u2019all\u2019 - query all replicas, and return values present in all replicas\n**kwargs \u2013 Any other named arguments to pass through to\nQdrantClient.async_grpc_points.Search().\nReturns\nList of Documents selected by maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\n:param query: Text to look up documents similar to.\n:param k: Number of Documents to return. Defaults to 4.\n:param fetch_k: Number of Documents to fetch to pass to MMR algorithm.\nDefaults to 20.\nParameters\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-13", "text": "to maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter \u2013 Filter by metadata. Defaults to None.\nsearch_params \u2013 Additional search params\nscore_threshold \u2013 Define a minimal score threshold for the result.\nIf defined, less similar results will not be returned.\nScore of the returned result might be higher or smaller than the\nthreshold depending on the Distance function used.\nE.g. for cosine similarity only higher scores will be returned.\nconsistency \u2013 Read consistency of the search. Defines how many replicas should be\nqueried before returning the result.\nValues:\n- int - number of replicas to query, values should present in all\nqueried replicas\n\u2019majority\u2019 - query all replicas, but return values present in themajority of replicas\n\u2019quorum\u2019 - query the majority of replicas, return values present inall of them\n\u2019all\u2019 - query all replicas, and return values present in all replicas\n**kwargs \u2013 Any other named arguments to pass through to\nQdrantClient.async_grpc_points.Search().\nReturns\nList of Documents selected by maximal marginal relevance and distance for\neach.\nasync amax_marginal_relevance_search_with_score_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\n:param query: Text to look up documents similar to.\n:param k: Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-14", "text": ":param k: Number of Documents to return. Defaults to 4.\n:param fetch_k: Number of Documents to fetch to pass to MMR algorithm.\nDefaults to 20.\nParameters\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance and distance for\neach.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-15", "text": "docsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, filter: Optional[MetadataFilter] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\n:param query: Text to look up documents similar to.\n:param k: Number of Documents to return. Defaults to 4.\n:param filter: Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding vector to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-16", "text": "Parameters\nembedding \u2013 Embedding vector to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Filter by metadata. Defaults to None.\nsearch_params \u2013 Additional search params\noffset \u2013 Offset of the first result to return.\nMay be used to paginate results.\nNote: large offset values may cause performance issues.\nscore_threshold \u2013 Define a minimal score threshold for the result.\nIf defined, less similar results will not be returned.\nScore of the returned result might be higher or smaller than the\nthreshold depending on the Distance function used.\nE.g. for cosine similarity only higher scores will be returned.\nconsistency \u2013 Read consistency of the search. Defines how many replicas should be\nqueried before returning the result.\nValues:\n- int - number of replicas to query, values should present in all\nqueried replicas\n\u2019majority\u2019 - query all replicas, but return values present in themajority of replicas\n\u2019quorum\u2019 - query the majority of replicas, return values present inall of them\n\u2019all\u2019 - query all replicas, and return values present in all replicas\n**kwargs \u2013 Any other named arguments to pass through to\nQdrantClient.async_grpc_points.Search().\nReturns\nList of Documents most similar to the query.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-17", "text": "filter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(query: str, k: int = 4, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Filter by metadata. Defaults to None.\nsearch_params \u2013 Additional search params\noffset \u2013 Offset of the first result to return.\nMay be used to paginate results.\nNote: large offset values may cause performance issues.\nscore_threshold \u2013 Define a minimal score threshold for the result.\nIf defined, less similar results will not be returned.\nScore of the returned result might be higher or smaller than the\nthreshold depending on the Distance function used.\nE.g. for cosine similarity only higher scores will be returned.\nconsistency \u2013 Read consistency of the search. Defines how many replicas should be\nqueried before returning the result.\nValues:\n- int - number of replicas to query, values should present in all\nqueried replicas\n\u2019majority\u2019 - query all replicas, but return values present in themajority of replicas\n\u2019quorum\u2019 - query the majority of replicas, return values present inall of them\n\u2019all\u2019 - query all replicas, and return values present in all replicas\n**kwargs \u2013 Any other named arguments to pass through to\nQdrantClient.async_grpc_points.Search().\nReturns\nList of documents most similar to the query text and distance for each.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-18", "text": "Returns\nList of documents most similar to the query text and distance for each.\nasync asimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding vector to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Filter by metadata. Defaults to None.\nsearch_params \u2013 Additional search params\noffset \u2013 Offset of the first result to return.\nMay be used to paginate results.\nNote: large offset values may cause performance issues.\nscore_threshold \u2013 Define a minimal score threshold for the result.\nIf defined, less similar results will not be returned.\nScore of the returned result might be higher or smaller than the\nthreshold depending on the Distance function used.\nE.g. for cosine similarity only higher scores will be returned.\nconsistency \u2013 Read consistency of the search. Defines how many replicas should be\nqueried before returning the result.\nValues:\n- int - number of replicas to query, values should present in all\nqueried replicas\n\u2019majority\u2019 - query all replicas, but return values present in themajority of replicas\n\u2019quorum\u2019 - query the majority of replicas, return values present inall of them\n\u2019all\u2019 - query all replicas, and return values present in all replicas\n**kwargs \u2013 Any other named arguments to pass through to\nQdrantClient.async_grpc_points.Search().\nReturns\nList of documents most similar to the query text and distance for each.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-19", "text": "Returns\nList of documents most similar to the query text and distance for each.\nclassmethod construct_instance(texts: List[str], embedding: Embeddings, location: Optional[str] = None, url: Optional[str] = None, port: Optional[int] = 6333, grpc_port: int = 6334, prefer_grpc: bool = False, https: Optional[bool] = None, api_key: Optional[str] = None, prefix: Optional[str] = None, timeout: Optional[float] = None, host: Optional[str] = None, path: Optional[str] = None, collection_name: Optional[str] = None, distance_func: str = 'Cosine', content_payload_key: str = 'page_content', metadata_payload_key: str = 'metadata', vector_name: Optional[str] = None, shard_number: Optional[int] = None, replication_factor: Optional[int] = None, write_consistency_factor: Optional[int] = None, on_disk_payload: Optional[bool] = None, hnsw_config: Optional[common_types.HnswConfigDiff] = None, optimizers_config: Optional[common_types.OptimizersConfigDiff] = None, wal_config: Optional[common_types.WalConfigDiff] = None, quantization_config: Optional[common_types.QuantizationConfig] = None, init_from: Optional[common_types.InitFrom] = None, on_disk: Optional[bool] = None, force_recreate: bool = False, **kwargs: Any) \u2192 Qdrant[source]\u00b6\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-20", "text": "True if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[Sequence[str]] = None, location: Optional[str] = None, url: Optional[str] = None, port: Optional[int] = 6333, grpc_port: int = 6334, prefer_grpc: bool = False, https: Optional[bool] = None, api_key: Optional[str] = None, prefix: Optional[str] = None, timeout: Optional[float] = None, host: Optional[str] = None, path: Optional[str] = None, collection_name: Optional[str] = None, distance_func: str = 'Cosine', content_payload_key: str = 'page_content', metadata_payload_key: str = 'metadata', vector_name: Optional[str] = None, batch_size: int = 64, shard_number: Optional[int] = None, replication_factor: Optional[int] = None, write_consistency_factor: Optional[int] = None, on_disk_payload: Optional[bool] = None, hnsw_config: Optional[common_types.HnswConfigDiff] = None, optimizers_config: Optional[common_types.OptimizersConfigDiff] = None, wal_config: Optional[common_types.WalConfigDiff] = None, quantization_config: Optional[common_types.QuantizationConfig] = None, init_from: Optional[common_types.InitFrom] = None, on_disk: Optional[bool] = None, force_recreate: bool = False, **kwargs: Any) \u2192 Qdrant[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-21", "text": "Construct Qdrant wrapper from a list of texts.\nParameters\ntexts \u2013 A list of texts to be indexed in Qdrant.\nembedding \u2013 A subclass of Embeddings, responsible for text vectorization.\nmetadatas \u2013 An optional list of metadata. If provided it has to be of the same\nlength as a list of texts.\nids \u2013 Optional list of ids to associate with the texts. Ids have to be\nuuid-like strings.\nlocation \u2013 If :memory: - use in-memory Qdrant instance.\nIf str - use it as a url parameter.\nIf None - fallback to relying on host and port parameters.\nurl \u2013 either host or str of \u201cOptional[scheme], host, Optional[port],\nOptional[prefix]\u201d. Default: None\nport \u2013 Port of the REST API interface. Default: 6333\ngrpc_port \u2013 Port of the gRPC interface. Default: 6334\nprefer_grpc \u2013 If true - use gPRC interface whenever possible in custom methods.\nDefault: False\nhttps \u2013 If true - use HTTPS(SSL) protocol. Default: None\napi_key \u2013 API key for authentication in Qdrant Cloud. Default: None\nprefix \u2013 If not None - add prefix to the REST URL path.\nExample: service/v1 will result in\nhttp://localhost:6333/service/v1/{qdrant-endpoint} for REST API.\nDefault: None\ntimeout \u2013 Timeout for REST and gRPC API requests.\nDefault: 5.0 seconds for REST and unlimited for gRPC\nhost \u2013 Host name of Qdrant service. If url and host are None, set to\n\u2018localhost\u2019. Default: None\npath \u2013 Path in which the vectors will be stored while using local mode.\nDefault: None\ncollection_name \u2013 Name of the Qdrant collection to be used. If not provided,", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-22", "text": "collection_name \u2013 Name of the Qdrant collection to be used. If not provided,\nit will be created randomly. Default: None\ndistance_func \u2013 Distance function. One of: \u201cCosine\u201d / \u201cEuclid\u201d / \u201cDot\u201d.\nDefault: \u201cCosine\u201d\ncontent_payload_key \u2013 A payload key used to store the content of the document.\nDefault: \u201cpage_content\u201d\nmetadata_payload_key \u2013 A payload key used to store the metadata of the document.\nDefault: \u201cmetadata\u201d\nvector_name \u2013 Name of the vector to be used internally in Qdrant.\nDefault: None\nbatch_size \u2013 How many vectors upload per-request.\nDefault: 64\nshard_number \u2013 Number of shards in collection. Default is 1, minimum is 1.\nreplication_factor \u2013 Replication factor for collection. Default is 1, minimum is 1.\nDefines how many copies of each shard will be created.\nHave effect only in distributed mode.\nwrite_consistency_factor \u2013 Write consistency factor for collection. Default is 1, minimum is 1.\nDefines how many replicas should apply the operation for us to consider\nit successful. Increasing this number will make the collection more\nresilient to inconsistencies, but will also make it fail if not enough\nreplicas are available.\nDoes not have any performance impact.\nHave effect only in distributed mode.\non_disk_payload \u2013 If true - point`s payload will not be stored in memory.\nIt will be read from the disk every time it is requested.\nThis setting saves RAM by (slightly) increasing the response time.\nNote: those payload values that are involved in filtering and are\nindexed - remain in RAM.\nhnsw_config \u2013 Params for HNSW index\noptimizers_config \u2013 Params for optimizer\nwal_config \u2013 Params for Write-Ahead-Log", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-23", "text": "optimizers_config \u2013 Params for optimizer\nwal_config \u2013 Params for Write-Ahead-Log\nquantization_config \u2013 Params for quantization, if None - quantization will be disabled\ninit_from \u2013 Use data stored in another collection to initialize this collection\nforce_recreate \u2013 Force recreating the collection\n**kwargs \u2013 Additional arguments passed directly into REST client initialization\nThis is a user-friendly interface that:\n1. Creates embeddings, one for each text\n2. Initializes the Qdrant database as an in-memory docstore by default\n(and overridable to a remote docstore)\nAdds the text embeddings to the Qdrant database\nThis is intended to be a quick way to get started.\nExample\nfrom langchain.vectorstores import Qdrant\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nqdrant = Qdrant.from_texts(texts, embeddings, \"localhost\")\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nDefaults to 20.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-24", "text": "of diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter \u2013 Filter by metadata. Defaults to None.\nsearch_params \u2013 Additional search params\nscore_threshold \u2013 Define a minimal score threshold for the result.\nIf defined, less similar results will not be returned.\nScore of the returned result might be higher or smaller than the\nthreshold depending on the Distance function used.\nE.g. for cosine similarity only higher scores will be returned.\nconsistency \u2013 Read consistency of the search. Defines how many replicas should be\nqueried before returning the result.\nValues:\n- int - number of replicas to query, values should present in all\nqueried replicas\n\u2019majority\u2019 - query all replicas, but return values present in themajority of replicas\n\u2019quorum\u2019 - query the majority of replicas, return values present inall of them\n\u2019all\u2019 - query all replicas, and return values present in all replicas\n**kwargs \u2013 Any other named arguments to pass through to QdrantClient.search()\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-25", "text": "k \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter \u2013 Filter by metadata. Defaults to None.\nsearch_params \u2013 Additional search params\nscore_threshold \u2013 Define a minimal score threshold for the result.\nIf defined, less similar results will not be returned.\nScore of the returned result might be higher or smaller than the\nthreshold depending on the Distance function used.\nE.g. for cosine similarity only higher scores will be returned.\nconsistency \u2013 Read consistency of the search. Defines how many replicas should be\nqueried before returning the result.\nValues:\n- int - number of replicas to query, values should present in all\nqueried replicas\n\u2019majority\u2019 - query all replicas, but return values present in themajority of replicas\n\u2019quorum\u2019 - query the majority of replicas, return values present inall of them\n\u2019all\u2019 - query all replicas, and return values present in all replicas\n**kwargs \u2013 Any other named arguments to pass through to QdrantClient.search()\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_with_score_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-26", "text": "Return docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\n:param query: Text to look up documents similar to.\n:param k: Number of Documents to return. Defaults to 4.\n:param fetch_k: Number of Documents to fetch to pass to MMR algorithm.\nDefaults to 20.\nParameters\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter \u2013 Filter by metadata. Defaults to None.\nsearch_params \u2013 Additional search params\nscore_threshold \u2013 Define a minimal score threshold for the result.\nIf defined, less similar results will not be returned.\nScore of the returned result might be higher or smaller than the\nthreshold depending on the Distance function used.\nE.g. for cosine similarity only higher scores will be returned.\nconsistency \u2013 Read consistency of the search. Defines how many replicas should be\nqueried before returning the result.\nValues:\n- int - number of replicas to query, values should present in all\nqueried replicas\n\u2019majority\u2019 - query all replicas, but return values present in themajority of replicas\n\u2019quorum\u2019 - query the majority of replicas, return values present inall of them\n\u2019all\u2019 - query all replicas, and return values present in all replicas\n**kwargs \u2013 Any other named arguments to pass through to QdrantClient.search()\nReturns\nList of Documents selected by maximal marginal relevance and distance for\neach.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-27", "text": "Return docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Filter by metadata. Defaults to None.\nsearch_params \u2013 Additional search params\noffset \u2013 Offset of the first result to return.\nMay be used to paginate results.\nNote: large offset values may cause performance issues.\nscore_threshold \u2013 Define a minimal score threshold for the result.\nIf defined, less similar results will not be returned.\nScore of the returned result might be higher or smaller than the\nthreshold depending on the Distance function used.\nE.g. for cosine similarity only higher scores will be returned.\nconsistency \u2013 Read consistency of the search. Defines how many replicas should be\nqueried before returning the result.\nValues:\n- int - number of replicas to query, values should present in all\nqueried replicas\n\u2019majority\u2019 - query all replicas, but return values present in themajority of replicas\n\u2019quorum\u2019 - query the majority of replicas, return values present inall of them\n\u2019all\u2019 - query all replicas, and return values present in all replicas\n**kwargs \u2013 Any other named arguments to pass through to QdrantClient.search()\nReturns\nList of Documents most similar to the query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-28", "text": "Returns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding vector to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Filter by metadata. Defaults to None.\nsearch_params \u2013 Additional search params\noffset \u2013 Offset of the first result to return.\nMay be used to paginate results.\nNote: large offset values may cause performance issues.\nscore_threshold \u2013 Define a minimal score threshold for the result.\nIf defined, less similar results will not be returned.\nScore of the returned result might be higher or smaller than the\nthreshold depending on the Distance function used.\nE.g. for cosine similarity only higher scores will be returned.\nconsistency \u2013 Read consistency of the search. Defines how many replicas should be\nqueried before returning the result.\nValues:\n- int - number of replicas to query, values should present in all\nqueried replicas\n\u2019majority\u2019 - query all replicas, but return values present in themajority of replicas\n\u2019quorum\u2019 - query the majority of replicas, return values present inall of them\n\u2019all\u2019 - query all replicas, and return values present in all replicas\n**kwargs \u2013 Any other named arguments to pass through to QdrantClient.search()\nReturns\nList of Documents most similar to the query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-29", "text": "Returns\nList of Documents most similar to the query.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Filter by metadata. Defaults to None.\nsearch_params \u2013 Additional search params\noffset \u2013 Offset of the first result to return.\nMay be used to paginate results.\nNote: large offset values may cause performance issues.\nscore_threshold \u2013 Define a minimal score threshold for the result.\nIf defined, less similar results will not be returned.\nScore of the returned result might be higher or smaller than the\nthreshold depending on the Distance function used.\nE.g. for cosine similarity only higher scores will be returned.\nconsistency \u2013 Read consistency of the search. Defines how many replicas should be", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-30", "text": "consistency \u2013 Read consistency of the search. Defines how many replicas should be\nqueried before returning the result.\nValues:\n- int - number of replicas to query, values should present in all\nqueried replicas\n\u2019majority\u2019 - query all replicas, but return values present in themajority of replicas\n\u2019quorum\u2019 - query the majority of replicas, return values present inall of them\n\u2019all\u2019 - query all replicas, and return values present in all replicas\n**kwargs \u2013 Any other named arguments to pass through to QdrantClient.search()\nReturns\nList of documents most similar to the query text and distance for each.\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[MetadataFilter] = None, search_params: Optional[common_types.SearchParams] = None, offset: int = 0, score_threshold: Optional[float] = None, consistency: Optional[common_types.ReadConsistency] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding vector to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Filter by metadata. Defaults to None.\nsearch_params \u2013 Additional search params\noffset \u2013 Offset of the first result to return.\nMay be used to paginate results.\nNote: large offset values may cause performance issues.\nscore_threshold \u2013 Define a minimal score threshold for the result.\nIf defined, less similar results will not be returned.\nScore of the returned result might be higher or smaller than the\nthreshold depending on the Distance function used.\nE.g. for cosine similarity only higher scores will be returned.\nconsistency \u2013 Read consistency of the search. Defines how many replicas should be\nqueried before returning the result.\nValues:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "6eb4c8868dda-31", "text": "queried before returning the result.\nValues:\n- int - number of replicas to query, values should present in all\nqueried replicas\n\u2019majority\u2019 - query all replicas, but return values present in themajority of replicas\n\u2019quorum\u2019 - query the majority of replicas, return values present inall of them\n\u2019all\u2019 - query all replicas, and return values present in all replicas\n**kwargs \u2013 Any other named arguments to pass through to QdrantClient.search()\nReturns\nList of documents most similar to the query text and distance for each.\nExamples using Qdrant\u00b6\nQdrant", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.Qdrant.html"}
{"id": "23930305d771-0", "text": "langchain.vectorstores.sklearn.SKLearnVectorStoreException\u00b6\nclass langchain.vectorstores.sklearn.SKLearnVectorStoreException[source]\u00b6\nException raised by SKLearnVectorStore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.SKLearnVectorStoreException.html"}
{"id": "900f19c6bd56-0", "text": "langchain.vectorstores.scann.ScaNN\u00b6\nclass langchain.vectorstores.scann.ScaNN(embedding: Embeddings, index: Any, docstore: Docstore, index_to_docstore_id: Dict[int, str], relevance_score_fn: Optional[Callable[[float], float]] = None, normalize_L2: bool = False, distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE, scann_config: Optional[str] = None)[source]\u00b6\nScaNN vector store.\nTo use, you should have the scann python package installed.\nExample\nfrom langchain.embeddings import HuggingFaceEmbeddings\nfrom langchain.vectorstores import ScaNN\ndb = ScaNN.from_texts(\n    ['foo', 'bar', 'barz', 'qux'],\n    HuggingFaceEmbeddings())\ndb.similarity_search('foo?', k=1)\nInitialize with necessary components.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding,\u00a0index,\u00a0docstore,\u00a0...[,\u00a0...])\nInitialize with necessary components.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_embeddings(text_embeddings[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.ScaNN.html"}
{"id": "900f19c6bd56-1", "text": "afrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_embeddings(text_embeddings,\u00a0embedding)\nConstruct ScaNN wrapper from raw documents.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0ids])\nConstruct ScaNN wrapper from raw documents.\nload_local(folder_path,\u00a0embedding[,\u00a0index_name])\nLoad ScaNN index, docstore, and index_to_docstore_id from disk.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.ScaNN.html"}
{"id": "900f19c6bd56-2", "text": "Return docs selected using the maximal marginal relevance.\nsave_local(folder_path[,\u00a0index_name])\nSave ScaNN index, docstore, and index_to_docstore_id to disk.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter,\u00a0fetch_k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nReturn docs most similar to query.\nsimilarity_search_with_score_by_vector(embedding)\nReturn docs most similar to query.\n__init__(embedding: Embeddings, index: Any, docstore: Docstore, index_to_docstore_id: Dict[int, str], relevance_score_fn: Optional[Callable[[float], float]] = None, normalize_L2: bool = False, distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE, scann_config: Optional[str] = None)[source]\u00b6\nInitialize with necessary components.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.ScaNN.html"}
{"id": "900f19c6bd56-3", "text": "Run more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_embeddings(text_embeddings: Iterable[Tuple[str, List[float]]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntext_embeddings \u2013 Iterable pairs of string and embedding to\nadd to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of unique IDs.\nReturns\nList of ids from adding the texts into the vectorstore.\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of unique IDs.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.ScaNN.html"}
{"id": "900f19c6bd56-4", "text": "False otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.ScaNN.html"}
{"id": "900f19c6bd56-5", "text": "lambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.ScaNN.html"}
{"id": "900f19c6bd56-6", "text": "Return docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_embeddings(text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 ScaNN[source]\u00b6\nConstruct ScaNN wrapper from raw documents.\nThis is a user friendly interface that:\nEmbeds documents.\nCreates an in memory docstore\nInitializes the ScaNN database", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.ScaNN.html"}
{"id": "900f19c6bd56-7", "text": "Embeds documents.\nCreates an in memory docstore\nInitializes the ScaNN database\nThis is intended to be a quick way to get started.\nExample\nfrom langchain.vectorstores import ScaNN\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\ntext_embeddings = embeddings.embed_documents(texts)\ntext_embedding_pairs = list(zip(texts, text_embeddings))\nscann = ScaNN.from_embeddings(text_embedding_pairs, embeddings)\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 ScaNN[source]\u00b6\nConstruct ScaNN wrapper from raw documents.\nThis is a user friendly interface that:\nEmbeds documents.\nCreates an in memory docstore\nInitializes the ScaNN database\nThis is intended to be a quick way to get started.\nExample\nfrom langchain.vectorstores import ScaNN\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nscann = ScaNN.from_texts(texts, embeddings)\nclassmethod load_local(folder_path: str, embedding: Embeddings, index_name: str = 'index', **kwargs: Any) \u2192 ScaNN[source]\u00b6\nLoad ScaNN index, docstore, and index_to_docstore_id from disk.\nParameters\nfolder_path \u2013 folder path to load index, docstore,\nand index_to_docstore_id from.\nembeddings \u2013 Embeddings to use when generating queries\nindex_name \u2013 for saving with a specific index file name\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.ScaNN.html"}
{"id": "900f19c6bd56-8", "text": "Return docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsave_local(folder_path: str, index_name: str = 'index') \u2192 None[source]\u00b6\nSave ScaNN index, docstore, and index_to_docstore_id to disk.\nParameters\nfolder_path \u2013 folder path to save index, docstore,\nand index_to_docstore_id to.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.ScaNN.html"}
{"id": "900f19c6bd56-9", "text": "Return docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\nReturns\nList of Documents most similar to the embedding.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.ScaNN.html"}
{"id": "900f19c6bd56-10", "text": "**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\nReturns\nList of documents most similar to the query text with\nL2 distance in float. Lower score represents more similarity.\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nembedding \u2013 Embedding vector to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, Any]]) \u2013 Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\n**kwargs \u2013 kwargs to be passed to similarity search. Can include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.ScaNN.html"}
{"id": "900f19c6bd56-11", "text": "filter the resulting set of retrieved docs\nReturns\nList of documents most similar to the query text and L2 distance\nin float for each. Lower score represents more similarity.\nExamples using ScaNN\u00b6\nScaNN", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.ScaNN.html"}
{"id": "75543a56dc0b-0", "text": "langchain.vectorstores.singlestoredb.SingleStoreDB\u00b6\nclass langchain.vectorstores.singlestoredb.SingleStoreDB(embedding: Embeddings, *, distance_strategy: DistanceStrategy = DistanceStrategy.DOT_PRODUCT, table_name: str = 'embeddings', content_field: str = 'content', metadata_field: str = 'metadata', vector_field: str = 'vector', pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any)[source]\u00b6\nSingleStore DB vector store.\nThe prerequisite for using this class is the installation of the singlestoredb\nPython package.\nThe SingleStoreDB vectorstore can be created by providing an embedding function and\nthe relevant parameters for the database connection, connection pool, and\noptionally, the names of the table and the fields to use.\nInitialize with necessary components.\nParameters\nembedding (Embeddings) \u2013 A text embedding model.\ndistance_strategy (DistanceStrategy, optional) \u2013 Determines the strategy employed for calculating\nthe distance between vectors in the embedding space.\nDefaults to DOT_PRODUCT.\nAvailable options are:\n- DOT_PRODUCT: Computes the scalar product of two vectors.\nThis is the default behavior\nEUCLIDEAN_DISTANCE: Computes the Euclidean distance betweentwo vectors. This metric considers the geometric distance in\nthe vector space, and might be more suitable for embeddings\nthat rely on spatial relationships.\ntable_name (str, optional) \u2013 Specifies the name of the table in use.\nDefaults to \u201cembeddings\u201d.\ncontent_field (str, optional) \u2013 Specifies the field to store the content.\nDefaults to \u201ccontent\u201d.\nmetadata_field (str, optional) \u2013 Specifies the field to store metadata.\nDefaults to \u201cmetadata\u201d.\nvector_field (str, optional) \u2013 Specifies the field to store the vector.\nDefaults to \u201cvector\u201d.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-1", "text": "Defaults to \u201cvector\u201d.\npool (Following arguments pertain to the connection) \u2013 \npool_size (int, optional) \u2013 Determines the number of active connections in\nthe pool. Defaults to 5.\nmax_overflow (int, optional) \u2013 Determines the maximum number of connections\nallowed beyond the pool_size. Defaults to 10.\ntimeout (float, optional) \u2013 Specifies the maximum wait time in seconds for\nestablishing a connection. Defaults to 30.\nconnection (database) \u2013 \nhost (str, optional) \u2013 Specifies the hostname, IP address, or URL for the\ndatabase connection. The default scheme is \u201cmysql\u201d.\nuser (str, optional) \u2013 Database username.\npassword (str, optional) \u2013 Database password.\nport (int, optional) \u2013 Database port. Defaults to 3306 for non-HTTP\nconnections, 80 for HTTP connections, and 443 for HTTPS connections.\ndatabase (str, optional) \u2013 Database name.\nthe (Additional optional arguments provide further customization over) \u2013 \nconnection \u2013 \npure_python (bool, optional) \u2013 Toggles the connector mode. If True,\noperates in pure Python mode.\nlocal_infile (bool, optional) \u2013 Allows local file uploads.\ncharset (str, optional) \u2013 Specifies the character set for string values.\nssl_key (str, optional) \u2013 Specifies the path of the file containing the SSL\nkey.\nssl_cert (str, optional) \u2013 Specifies the path of the file containing the SSL\ncertificate.\nssl_ca (str, optional) \u2013 Specifies the path of the file containing the SSL\ncertificate authority.\nssl_cipher (str, optional) \u2013 Sets the SSL cipher list.\nssl_disabled (bool, optional) \u2013 Disables SSL usage.\nssl_verify_cert (bool, optional) \u2013 Verifies the server\u2019s certificate.\nAutomatically enabled if ssl_ca is specified.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-2", "text": "Automatically enabled if ssl_ca is specified.\nssl_verify_identity (bool, optional) \u2013 Verifies the server\u2019s identity.\nconv (dict[int, Callable], optional) \u2013 A dictionary of data conversion\nfunctions.\ncredential_type (str, optional) \u2013 Specifies the type of authentication to\nuse: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.\nautocommit (bool, optional) \u2013 Enables autocommits.\nresults_type (str, optional) \u2013 Determines the structure of the query results:\ntuples, namedtuples, dicts.\nresults_format (str, optional) \u2013 Deprecated. This option has been renamed to\nresults_type.\nExamples\nBasic Usage:\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import SingleStoreDB\nvectorstore = SingleStoreDB(\n    OpenAIEmbeddings(),\n    host=\"https://user:password@127.0.0.1:3306/database\"\n)\nAdvanced Usage:\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import SingleStoreDB\nvectorstore = SingleStoreDB(\n    OpenAIEmbeddings(),\n    distance_strategy=DistanceStrategy.EUCLIDEAN_DISTANCE,\n    host=\"127.0.0.1\",\n    port=3306,\n    user=\"user\",\n    password=\"password\",\n    database=\"db\",\n    table_name=\"my_custom_table\",\n    pool_size=10,\n    timeout=60,\n)\nUsing environment variables:\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import SingleStoreDB\nos.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'\nvectorstore = SingleStoreDB(OpenAIEmbeddings())\nAttributes\nembeddings\nAccess the query embedding object if available.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-3", "text": "Attributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding,\u00a0*[,\u00a0distance_strategy,\u00a0...])\nInitialize with necessary components.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0embeddings])\nAdd more texts to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-4", "text": "delete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreate a SingleStoreDB vectorstore from raw documents. This is a user-friendly interface that:     1. Embeds documents. 2. Creates a new table for the embeddings in SingleStoreDB. 3. Adds the documents to the newly created table. This is intended to be a quick way to get started. .. rubric:: Example.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nReturns the most similar indexed documents to the query text.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\n__init__(embedding: Embeddings, *, distance_strategy: DistanceStrategy = DistanceStrategy.DOT_PRODUCT, table_name: str = 'embeddings', content_field: str = 'content', metadata_field: str = 'metadata', vector_field: str = 'vector', pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any)[source]\u00b6\nInitialize with necessary components.\nParameters\nembedding (Embeddings) \u2013 A text embedding model.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-5", "text": "Initialize with necessary components.\nParameters\nembedding (Embeddings) \u2013 A text embedding model.\ndistance_strategy (DistanceStrategy, optional) \u2013 Determines the strategy employed for calculating\nthe distance between vectors in the embedding space.\nDefaults to DOT_PRODUCT.\nAvailable options are:\n- DOT_PRODUCT: Computes the scalar product of two vectors.\nThis is the default behavior\nEUCLIDEAN_DISTANCE: Computes the Euclidean distance betweentwo vectors. This metric considers the geometric distance in\nthe vector space, and might be more suitable for embeddings\nthat rely on spatial relationships.\ntable_name (str, optional) \u2013 Specifies the name of the table in use.\nDefaults to \u201cembeddings\u201d.\ncontent_field (str, optional) \u2013 Specifies the field to store the content.\nDefaults to \u201ccontent\u201d.\nmetadata_field (str, optional) \u2013 Specifies the field to store metadata.\nDefaults to \u201cmetadata\u201d.\nvector_field (str, optional) \u2013 Specifies the field to store the vector.\nDefaults to \u201cvector\u201d.\npool (Following arguments pertain to the connection) \u2013 \npool_size (int, optional) \u2013 Determines the number of active connections in\nthe pool. Defaults to 5.\nmax_overflow (int, optional) \u2013 Determines the maximum number of connections\nallowed beyond the pool_size. Defaults to 10.\ntimeout (float, optional) \u2013 Specifies the maximum wait time in seconds for\nestablishing a connection. Defaults to 30.\nconnection (database) \u2013 \nhost (str, optional) \u2013 Specifies the hostname, IP address, or URL for the\ndatabase connection. The default scheme is \u201cmysql\u201d.\nuser (str, optional) \u2013 Database username.\npassword (str, optional) \u2013 Database password.\nport (int, optional) \u2013 Database port. Defaults to 3306 for non-HTTP\nconnections, 80 for HTTP connections, and 443 for HTTPS connections.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-6", "text": "connections, 80 for HTTP connections, and 443 for HTTPS connections.\ndatabase (str, optional) \u2013 Database name.\nthe (Additional optional arguments provide further customization over) \u2013 \nconnection \u2013 \npure_python (bool, optional) \u2013 Toggles the connector mode. If True,\noperates in pure Python mode.\nlocal_infile (bool, optional) \u2013 Allows local file uploads.\ncharset (str, optional) \u2013 Specifies the character set for string values.\nssl_key (str, optional) \u2013 Specifies the path of the file containing the SSL\nkey.\nssl_cert (str, optional) \u2013 Specifies the path of the file containing the SSL\ncertificate.\nssl_ca (str, optional) \u2013 Specifies the path of the file containing the SSL\ncertificate authority.\nssl_cipher (str, optional) \u2013 Sets the SSL cipher list.\nssl_disabled (bool, optional) \u2013 Disables SSL usage.\nssl_verify_cert (bool, optional) \u2013 Verifies the server\u2019s certificate.\nAutomatically enabled if ssl_ca is specified.\nssl_verify_identity (bool, optional) \u2013 Verifies the server\u2019s identity.\nconv (dict[int, Callable], optional) \u2013 A dictionary of data conversion\nfunctions.\ncredential_type (str, optional) \u2013 Specifies the type of authentication to\nuse: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.\nautocommit (bool, optional) \u2013 Enables autocommits.\nresults_type (str, optional) \u2013 Determines the structure of the query results:\ntuples, namedtuples, dicts.\nresults_format (str, optional) \u2013 Deprecated. This option has been renamed to\nresults_type.\nExamples\nBasic Usage:\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import SingleStoreDB\nvectorstore = SingleStoreDB(\n    OpenAIEmbeddings(),", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-7", "text": "vectorstore = SingleStoreDB(\n    OpenAIEmbeddings(),\n    host=\"https://user:password@127.0.0.1:3306/database\"\n)\nAdvanced Usage:\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import SingleStoreDB\nvectorstore = SingleStoreDB(\n    OpenAIEmbeddings(),\n    distance_strategy=DistanceStrategy.EUCLIDEAN_DISTANCE,\n    host=\"127.0.0.1\",\n    port=3306,\n    user=\"user\",\n    password=\"password\",\n    database=\"db\",\n    table_name=\"my_custom_table\",\n    pool_size=10,\n    timeout=60,\n)\nUsing environment variables:\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import SingleStoreDB\nos.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'\nvectorstore = SingleStoreDB(OpenAIEmbeddings())\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-8", "text": "(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, embeddings: Optional[List[List[float]]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd more texts to the vectorstore.\nParameters\ntexts (Iterable[str]) \u2013 Iterable of strings/text to add to the vectorstore.\nmetadatas (Optional[List[dict]], optional) \u2013 Optional list of metadatas.\nDefaults to None.\nembeddings (Optional[List[List[float]]], optional) \u2013 Optional pre-generated\nembeddings. Defaults to None.\nReturns\nempty list\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-9", "text": "Return docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-10", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-11", "text": "Returns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, distance_strategy: DistanceStrategy = DistanceStrategy.DOT_PRODUCT, table_name: str = 'embeddings', content_field: str = 'content', metadata_field: str = 'metadata', vector_field: str = 'vector', pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any) \u2192 SingleStoreDB[source]\u00b6\nCreate a SingleStoreDB vectorstore from raw documents.\nThis is a user-friendly interface that:\nEmbeds documents.\nCreates a new table for the embeddings in SingleStoreDB.\nAdds the documents to the newly created table.\nThis is intended to be a quick way to get started.\n.. rubric:: Example\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-12", "text": "Return docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturns the most similar indexed documents to the query text.\nUses cosine similarity.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-13", "text": "Returns the most similar indexed documents to the query text.\nUses cosine similarity.\nParameters\nquery (str) \u2013 The query text for which to find similar documents.\nk (int) \u2013 The number of documents to return. Default is 4.\nfilter (dict) \u2013 A dictionary of metadata fields and values to filter by.\nReturns\nA list of documents that are most similar to the query text.\nReturn type\nList[Document]\nExamples\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[dict] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query. Uses cosine similarity.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "75543a56dc0b-14", "text": "k \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 A dictionary of metadata fields and values to filter by.\nDefaults to None.\nReturns\nList of Documents most similar to the query and score for each\nExamples using SingleStoreDB\u00b6\nSingleStoreDB", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.singlestoredb.SingleStoreDB.html"}
{"id": "1c32523e0f24-0", "text": "langchain.vectorstores.analyticdb.AnalyticDB\u00b6\nclass langchain.vectorstores.analyticdb.AnalyticDB(connection_string: str, embedding_function: Embeddings, embedding_dimension: int = 1536, collection_name: str = 'langchain_document', pre_delete_collection: bool = False, logger: Optional[Logger] = None, engine_args: Optional[dict] = None)[source]\u00b6\nAnalyticDB (distributed PostgreSQL) vector store.\nAnalyticDB is a distributed full postgresql syntax cloud-native database.\n- connection_string is a postgres connection string.\n- embedding_function any embedding function implementing\nlangchain.embeddings.base.Embeddings interface.\ncollection_name is the name of the collection to use. (default: langchain)\nNOTE: This is not the name of the table, but the name of the collection.The tables will be created when initializing the store (if not exists)\nSo, make sure the user has the right permissions to create tables.\npre_delete_collection if True, will delete the collection if it exists.(default: False)\n- Useful for testing.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(connection_string,\u00a0embedding_function)\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0batch_size])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html"}
{"id": "1c32523e0f24-1", "text": "afrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\nconnection_string_from_db_params(driver,\u00a0...)\nReturn connection string from database parameters.\ncreate_collection()\ncreate_table_if_not_exists()\ndelete([ids])\nDelete by vector IDs.\ndelete_collection()\nfrom_documents(documents,\u00a0embedding[,\u00a0...])\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nget_connection_string(kwargs)\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html"}
{"id": "1c32523e0f24-2", "text": "search(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nRun similarity search with AnalyticDB with distance.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\nsimilarity_search_with_score_by_vector(embedding)\n__init__(connection_string: str, embedding_function: Embeddings, embedding_dimension: int = 1536, collection_name: str = 'langchain_document', pre_delete_collection: bool = False, logger: Optional[Logger] = None, engine_args: Optional[dict] = None) \u2192 None[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html"}
{"id": "1c32523e0f24-3", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, batch_size: int = 500, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html"}
{"id": "1c32523e0f24-4", "text": "Return docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html"}
{"id": "1c32523e0f24-5", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html"}
{"id": "1c32523e0f24-6", "text": "Returns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\nclassmethod connection_string_from_db_params(driver: str, host: str, port: int, database: str, user: str, password: str) \u2192 str[source]\u00b6\nReturn connection string from database parameters.\ncreate_collection() \u2192 None[source]\u00b6\ncreate_table_if_not_exists() \u2192 None[source]\u00b6\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector IDs.\nParameters\nids \u2013 List of ids to delete.\ndelete_collection() \u2192 None[source]\u00b6\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, embedding_dimension: int = 1536, collection_name: str = 'langchain_document', ids: Optional[List[str]] = None, pre_delete_collection: bool = False, engine_args: Optional[dict] = None, **kwargs: Any) \u2192 AnalyticDB[source]\u00b6\nReturn VectorStore initialized from documents and embeddings.\nPostgres Connection string is required\nEither pass it as a parameter\nor set the PG_CONNECTION_STRING environment variable.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, embedding_dimension: int = 1536, collection_name: str = 'langchain_document', ids: Optional[List[str]] = None, pre_delete_collection: bool = False, engine_args: Optional[dict] = None, **kwargs: Any) \u2192 AnalyticDB[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nPostgres Connection string is required\nEither pass it as a parameter\nor set the PG_CONNECTION_STRING environment variable.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html"}
{"id": "1c32523e0f24-7", "text": "Either pass it as a parameter\nor set the PG_CONNECTION_STRING environment variable.\nclassmethod get_connection_string(kwargs: Dict[str, Any]) \u2192 str[source]\u00b6\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html"}
{"id": "1c32523e0f24-8", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRun similarity search with AnalyticDB with distance.\nParameters\nquery (str) \u2013 Query text to search for.\nk (int) \u2013 Number of results to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html"}
{"id": "1c32523e0f24-9", "text": "filter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[dict] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query and score for each\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nExamples using AnalyticDB\u00b6\nAnalyticDB", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.analyticdb.AnalyticDB.html"}
{"id": "0cd518e0780e-0", "text": "langchain.vectorstores.usearch.USearch\u00b6\nclass langchain.vectorstores.usearch.USearch(embedding: Embeddings, index: Any, docstore: Docstore, ids: List[str])[source]\u00b6\nUSearch vector store.\nTo use, you should have the usearch python package installed.\nInitialize with necessary components.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding,\u00a0index,\u00a0docstore,\u00a0ids)\nInitialize with necessary components.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.usearch.USearch.html"}
{"id": "0cd518e0780e-1", "text": "asimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nConstruct USearch wrapper from raw documents. This is a user friendly interface that:     1. Embeds documents. 2. Creates an in memory docstore     3. Initializes the USearch database This is intended to be a quick way to get started.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nReturn docs most similar to query.\n__init__(embedding: Embeddings, index: Any, docstore: Docstore, ids: List[str])[source]\u00b6\nInitialize with necessary components.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.usearch.USearch.html"}
{"id": "0cd518e0780e-2", "text": "Run more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[Dict]] = None, ids: Optional[ndarray] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of unique IDs.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.usearch.USearch.html"}
{"id": "0cd518e0780e-3", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.usearch.USearch.html"}
{"id": "0cd518e0780e-4", "text": "Return type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.usearch.USearch.html"}
{"id": "0cd518e0780e-5", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict]] = None, ids: Optional[ndarray] = None, metric: str = 'cos', **kwargs: Any) \u2192 USearch[source]\u00b6\nConstruct USearch wrapper from raw documents.\nThis is a user friendly interface that:\nEmbeds documents.\nCreates an in memory docstore\nInitializes the USearch database\nThis is intended to be a quick way to get started.\nExample\nfrom langchain.vectorstores import USearch\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.usearch.USearch.html"}
{"id": "0cd518e0780e-6", "text": "from langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nusearch = USearch.from_texts(texts, embeddings)\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.usearch.USearch.html"}
{"id": "0cd518e0780e-7", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.usearch.USearch.html"}
{"id": "0cd518e0780e-8", "text": "Parameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of documents most similar to the query with distance.\nExamples using USearch\u00b6\nUSearch", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.usearch.USearch.html"}
{"id": "63d2bf29694c-0", "text": "langchain.vectorstores.redis.filters.RedisFilterField\u00b6\nclass langchain.vectorstores.redis.filters.RedisFilterField(field: str)[source]\u00b6\nBase class for RedisFilterFields.\nAttributes\nOPERATORS\nescaper\nMethods\n__init__(field)\nequals(other)\n__init__(field: str)[source]\u00b6\nequals(other: RedisFilterField) \u2192 bool[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.filters.RedisFilterField.html"}
{"id": "5f6a93946439-0", "text": "langchain.vectorstores.pgembedding.EmbeddingStore\u00b6\nclass langchain.vectorstores.pgembedding.EmbeddingStore(**kwargs)[source]\u00b6\nEmbedding store.\nA simple constructor that allows initialization from kwargs.\nSets attributes on the constructed instance using the names and\nvalues in kwargs.\nOnly keys that are present as\nattributes of the instance\u2019s class are allowed. These could be,\nfor example, any mapped columns or relationships.\nAttributes\ncmetadata\ncollection\ncollection_id\ncustom_id\ndocument\nembedding\nmetadata\nregistry\nuuid\nMethods\n__init__(**kwargs)\nA simple constructor that allows initialization from kwargs.\n__init__(**kwargs)\u00b6\nA simple constructor that allows initialization from kwargs.\nSets attributes on the constructed instance using the names and\nvalues in kwargs.\nOnly keys that are present as\nattributes of the instance\u2019s class are allowed. These could be,\nfor example, any mapped columns or relationships.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.EmbeddingStore.html"}
{"id": "2df56939d06c-0", "text": "langchain.vectorstores.utils.filter_complex_metadata\u00b6\nlangchain.vectorstores.utils.filter_complex_metadata(documents: ~typing.List[~langchain.schema.document.Document], *, allowed_types: ~typing.Tuple[~typing.Type, ...] = (<class 'str'>, <class 'bool'>, <class 'int'>, <class 'float'>)) \u2192 List[Document][source]\u00b6\nFilter out metadata types that are not supported for a vector store.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.utils.filter_complex_metadata.html"}
{"id": "996b17452510-0", "text": "langchain.vectorstores.starrocks.get_named_result\u00b6\nlangchain.vectorstores.starrocks.get_named_result(connection: Any, query: str) \u2192 List[dict[str, Any]][source]\u00b6\nGet a named result from a query.\n:param connection: The connection to the database\n:param query: The query to execute\nReturns\nThe result of the query\nReturn type\nList[dict[str, Any]]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.get_named_result.html"}
{"id": "527d16b8947d-0", "text": "langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch\u00b6\nclass langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch(embedding: Embeddings, config: AlibabaCloudOpenSearchSettings, **kwargs: Any)[source]\u00b6\nAlibaba Cloud OpenSearch vector store.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding,\u00a0config,\u00a0**kwargs)\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nInsert documents into the instance.. :param texts: The text segments to be inserted into the vector storage,               should not be empty. :param metadatas: Metadata information.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch.html"}
{"id": "527d16b8947d-1", "text": "asimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ncreate_inverse_metadata(fields)\nCreate metadata from fields.\ncreate_results(json_result)\nAssemble documents.\ncreate_results_with_score(json_result)\nParsing the returned results with scores.\ndelete([ids])\nDelete by vector ID or other criteria.\ndelete_documents_with_document_id(id_list)\nDelete documents based on their IDs.\ndelete_documents_with_texts(texts)\nDelete documents based on their page content.\nfrom_documents(documents,\u00a0embedding[,\u00a0config])\nCreate alibaba cloud opensearch vector store instance.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0config])\nCreate alibaba cloud opensearch vector store instance.\ninner_embedding_query(embedding[,\u00a0...])\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0search_filter])\nPerform similarity retrieval based on text.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nPerform retrieval directly using vectors.\nsimilarity_search_with_relevance_scores(query)\nPerform similarity retrieval based on text with scores.\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch.html"}
{"id": "527d16b8947d-2", "text": "similarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\n__init__(embedding: Embeddings, config: AlibabaCloudOpenSearchSettings, **kwargs: Any) \u2192 None[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nInsert documents into the instance..\n:param texts: The text segments to be inserted into the vector storage,\nshould not be empty.\nParameters\nmetadatas \u2013 Metadata information.\nReturns\nList of document IDs.\nReturn type\nid_list\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch.html"}
{"id": "527d16b8947d-3", "text": "True if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch.html"}
{"id": "527d16b8947d-4", "text": "lambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch.html"}
{"id": "527d16b8947d-5", "text": "Return docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ncreate_inverse_metadata(fields: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nCreate metadata from fields.\nParameters\nfields \u2013 The fields of the document. The fields must be a dict.\nReturns\nThe metadata of the document. The metadata must be a dict.\nReturn type\nmetadata\ncreate_results(json_result: Dict[str, Any]) \u2192 List[Document][source]\u00b6\nAssemble documents.\ncreate_results_with_score(json_result: Dict[str, Any]) \u2192 List[Tuple[Document, float]][source]\u00b6\nParsing the returned results with scores.\n:param json_result: Results from OpenSearch query.\nReturns\nResults with scores.\nReturn type\nquery_result_list\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch.html"}
{"id": "527d16b8947d-6", "text": "Returns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\ndelete_documents_with_document_id(id_list: List[str]) \u2192 bool[source]\u00b6\nDelete documents based on their IDs.\nParameters\nid_list \u2013 List of document IDs.\nReturns\nWhether the deletion was successful or not.\ndelete_documents_with_texts(texts: List[str]) \u2192 bool[source]\u00b6\nDelete documents based on their page content.\nParameters\ntexts \u2013 List of document page content.\nReturns\nWhether the deletion was successful or not.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, config: Optional[AlibabaCloudOpenSearchSettings] = None, **kwargs: Any) \u2192 AlibabaCloudOpenSearch[source]\u00b6\nCreate alibaba cloud opensearch vector store instance.\nParameters\ndocuments \u2013 Documents to be inserted into the vector storage,\nshould not be empty.\nembedding \u2013 Embedding function, Embedding function.\nconfig \u2013 Alibaba OpenSearch instance configuration.\nids \u2013 Specify the ID for the inserted document. If left empty, the ID will be\nautomatically generated based on the text content.\nReturns\nAlibaba cloud opensearch vector store instance.\nReturn type\nAlibabaCloudOpenSearch\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, config: Optional[AlibabaCloudOpenSearchSettings] = None, **kwargs: Any) \u2192 AlibabaCloudOpenSearch[source]\u00b6\nCreate alibaba cloud opensearch vector store instance.\nParameters\ntexts \u2013 The text segments to be inserted into the vector storage,\nshould not be empty.\nembedding \u2013 Embedding function, Embedding function.\nconfig \u2013 Alibaba OpenSearch instance configuration.\nmetadatas \u2013 Metadata information.\nReturns\nAlibaba cloud opensearch vector store instance.\nReturn type", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch.html"}
{"id": "527d16b8947d-7", "text": "Returns\nAlibaba cloud opensearch vector store instance.\nReturn type\nAlibabaCloudOpenSearch\ninner_embedding_query(embedding: List[float], search_filter: Optional[Dict[str, Any]] = None, k: int = 4) \u2192 Dict[str, Any][source]\u00b6\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch.html"}
{"id": "527d16b8947d-8", "text": "to maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, search_filter: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform similarity retrieval based on text.\n:param query: Vectorize text for retrieval.\uff0cshould not be empty.\n:param k: top n.\n:param search_filter: Additional filtering conditions.\nReturns\nList of documents.\nReturn type\ndocument_list\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, search_filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform retrieval directly using vectors.\n:param embedding: vectors.\n:param k: top n.\n:param search_filter: Additional filtering conditions.\nReturns\nList of documents.\nReturn type\ndocument_list\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, search_filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPerform similarity retrieval based on text with scores.\n:param query: Vectorize text for retrieval.\uff0cshould not be empty.\n:param k: top n.\n:param search_filter: Additional filtering conditions.\nReturns\nList of documents.\nReturn type\ndocument_list\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.\nExamples using AlibabaCloudOpenSearch\u00b6\nAlibaba Cloud OpenSearch", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch.html"}
{"id": "027fea99a41d-0", "text": "langchain.vectorstores.vespa.VespaStore\u00b6\nclass langchain.vectorstores.vespa.VespaStore(app: Any, embedding_function: Optional[Embeddings] = None, page_content_field: Optional[str] = None, embedding_field: Optional[str] = None, input_field: Optional[str] = None, metadata_fields: Optional[List[str]] = None)[source]\u00b6\nVespa vector store.\nTo use, you should have the python client library pyvespa installed.\nExample\nfrom langchain.vectorstores import VespaStore\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom vespa.application import Vespa\n# Create a vespa client dependent upon your application,\n# e.g. either connecting to Vespa Cloud or a local deployment\n# such as Docker. Please refer to the PyVespa documentation on\n# how to initialize the client.\nvespa_app = Vespa(url=\"...\", port=..., application_package=...)\n# You need to instruct LangChain on which fields to use for embeddings\nvespa_config = dict(\n    page_content_field=\"text\",\n    embedding_field=\"embedding\",\n    input_field=\"query_embedding\",\n    metadata_fields=[\"date\", \"rating\", \"author\"]\n)\nembedding_function = OpenAIEmbeddings()\nvectorstore = VespaStore(vespa_app, embedding_function, **vespa_config)\nInitialize with a PyVespa client.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(app[,\u00a0embedding_function,\u00a0...])\nInitialize with a PyVespa client.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vespa.VespaStore.html"}
{"id": "027fea99a41d-1", "text": "Run more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nAdd texts to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0ids])\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vespa.VespaStore.html"}
{"id": "027fea99a41d-2", "text": "Return docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_by_vector_with_score(...)\nPerforms similarity search from a embeddings vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nRun similarity search with distance.\n__init__(app: Any, embedding_function: Optional[Embeddings] = None, page_content_field: Optional[str] = None, embedding_field: Optional[str] = None, input_field: Optional[str] = None, metadata_fields: Optional[List[str]] = None) \u2192 None[source]\u00b6\nInitialize with a PyVespa client.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vespa.VespaStore.html"}
{"id": "027fea99a41d-3", "text": "Parameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd texts to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of ids associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vespa.VespaStore.html"}
{"id": "027fea99a41d-4", "text": "Return docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever[source]\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vespa.VespaStore.html"}
{"id": "027fea99a41d-5", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vespa.VespaStore.html"}
{"id": "027fea99a41d-6", "text": "Returns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 VespaStore[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vespa.VespaStore.html"}
{"id": "027fea99a41d-7", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_by_vector_with_score(query_embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vespa.VespaStore.html"}
{"id": "027fea99a41d-8", "text": "Performs similarity search from a embeddings vector.\nParameters\nquery_embedding \u2013 Embeddings vector to search for.\nk \u2013 Number of results to return.\ncustom_query \u2013 Use this custom query instead default query (kwargs)\nkwargs \u2013 other vector store specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vespa.VespaStore.html"}
{"id": "1ffba0461693-0", "text": "langchain.vectorstores.azuresearch.AzureSearch\u00b6\nclass langchain.vectorstores.azuresearch.AzureSearch(azure_search_endpoint: str, azure_search_key: str, index_name: str, embedding_function: Callable, search_type: str = 'hybrid', semantic_configuration_name: Optional[str] = None, semantic_query_language: str = 'en-us', fields: Optional[List[SearchField]] = None, vector_search: Optional[VectorSearch] = None, semantic_settings: Optional[SemanticSettings] = None, scoring_profiles: Optional[List[ScoringProfile]] = None, default_scoring_profile: Optional[str] = None, **kwargs: Any)[source]\u00b6\nAzure Cognitive Search vector store.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(azure_search_endpoint,\u00a0...[,\u00a0...])\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nAdd texts data to an existing index.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearch.html"}
{"id": "1ffba0461693-1", "text": "Return VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nhybrid_search(query[,\u00a0k])\nReturns the most similar indexed documents to the query text.\nhybrid_search_with_score(query[,\u00a0k,\u00a0filters])\nReturn docs most similar to query with an hybrid query.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsemantic_hybrid_search(query[,\u00a0k])\nReturns the most similar indexed documents to the query text.\nsemantic_hybrid_search_with_score(query[,\u00a0k])\nReturns the most similar indexed documents to the query text.\nsemantic_hybrid_search_with_score_and_rerank(query)\nReturn docs most similar to query with an hybrid query.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearch.html"}
{"id": "1ffba0461693-2", "text": "similarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\nvector_search(query[,\u00a0k])\nReturns the most similar indexed documents to the query text.\nvector_search_with_score(query[,\u00a0k,\u00a0filters])\nReturn docs most similar to query.\n__init__(azure_search_endpoint: str, azure_search_key: str, index_name: str, embedding_function: Callable, search_type: str = 'hybrid', semantic_configuration_name: Optional[str] = None, semantic_query_language: str = 'en-us', fields: Optional[List[SearchField]] = None, vector_search: Optional[VectorSearch] = None, semantic_settings: Optional[SemanticSettings] = None, scoring_profiles: Optional[List[ScoringProfile]] = None, default_scoring_profile: Optional[str] = None, **kwargs: Any)[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearch.html"}
{"id": "1ffba0461693-3", "text": "Run more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd texts data to an existing index.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearch.html"}
{"id": "1ffba0461693-4", "text": "Return docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearch.html"}
{"id": "1ffba0461693-5", "text": ")\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearch.html"}
{"id": "1ffba0461693-6", "text": "Delete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, azure_search_endpoint: str = '', azure_search_key: str = '', index_name: str = 'langchain-index', **kwargs: Any) \u2192 AzureSearch[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nhybrid_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturns the most similar indexed documents to the query text.\nParameters\nquery (str) \u2013 The query text for which to find similar documents.\nk (int) \u2013 The number of documents to return. Default is 4.\nReturns\nA list of documents that are most similar to the query text.\nReturn type\nList[Document]\nhybrid_search_with_score(query: str, k: int = 4, filters: Optional[str] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query with an hybrid query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query and score for each", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearch.html"}
{"id": "1ffba0461693-7", "text": "Returns\nList of Documents most similar to the query and score for each\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearch.html"}
{"id": "1ffba0461693-8", "text": "Return docs most similar to query using specified search type.\nsemantic_hybrid_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturns the most similar indexed documents to the query text.\nParameters\nquery (str) \u2013 The query text for which to find similar documents.\nk (int) \u2013 The number of documents to return. Default is 4.\nReturns\nA list of documents that are most similar to the query text.\nReturn type\nList[Document]\nsemantic_hybrid_search_with_score(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturns the most similar indexed documents to the query text.\nParameters\nquery (str) \u2013 The query text for which to find similar documents.\nk (int) \u2013 The number of documents to return. Default is 4.\nReturns\nA list of documents that are most similar to the query text.\nReturn type\nList[Document]\nsemantic_hybrid_search_with_score_and_rerank(query: str, k: int = 4, filters: Optional[str] = None) \u2192 List[Tuple[Document, float, float]][source]\u00b6\nReturn docs most similar to query with an hybrid query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query and score for each\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearch.html"}
{"id": "1ffba0461693-9", "text": "Return docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.\nvector_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturns the most similar indexed documents to the query text.\nParameters\nquery (str) \u2013 The query text for which to find similar documents.\nk (int) \u2013 The number of documents to return. Default is 4.\nReturns\nA list of documents that are most similar to the query text.\nReturn type\nList[Document]\nvector_search_with_score(query: str, k: int = 4, filters: Optional[str] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearch.html"}
{"id": "1ffba0461693-10", "text": "k \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query and score for each\nExamples using AzureSearch\u00b6\nAzure Cognitive Search", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearch.html"}
{"id": "f4dbeb7f9213-0", "text": "langchain.vectorstores.sklearn.BaseSerializer\u00b6\nclass langchain.vectorstores.sklearn.BaseSerializer(persist_path: str)[source]\u00b6\nBase class for serializing data.\nMethods\n__init__(persist_path)\nextension()\nThe file extension suggested by this serializer (without dot).\nload()\nLoads the data from the persist_path\nsave(data)\nSaves the data to the persist_path\n__init__(persist_path: str) \u2192 None[source]\u00b6\nabstract classmethod extension() \u2192 str[source]\u00b6\nThe file extension suggested by this serializer (without dot).\nabstract load() \u2192 Any[source]\u00b6\nLoads the data from the persist_path\nabstract save(data: Any) \u2192 None[source]\u00b6\nSaves the data to the persist_path", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.BaseSerializer.html"}
{"id": "7fc2f1ba1f5c-0", "text": "langchain.vectorstores.pgvector.BaseModel\u00b6\nclass langchain.vectorstores.pgvector.BaseModel(**kwargs: Any)[source]\u00b6\nBase model for the SQL stores.\nA simple constructor that allows initialization from kwargs.\nSets attributes on the constructed instance using the names and\nvalues in kwargs.\nOnly keys that are present as\nattributes of the instance\u2019s class are allowed. These could be,\nfor example, any mapped columns or relationships.\nAttributes\nmetadata\nregistry\nuuid\nMethods\n__init__(**kwargs)\nA simple constructor that allows initialization from kwargs.\n__init__(**kwargs: Any) \u2192 None\u00b6\nA simple constructor that allows initialization from kwargs.\nSets attributes on the constructed instance using the names and\nvalues in kwargs.\nOnly keys that are present as\nattributes of the instance\u2019s class are allowed. These could be,\nfor example, any mapped columns or relationships.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvector.BaseModel.html"}
{"id": "12da4fb431b7-0", "text": "langchain.vectorstores.tigris.Tigris\u00b6\nclass langchain.vectorstores.tigris.Tigris(client: TigrisClient, embeddings: Embeddings, index_name: str)[source]\u00b6\nTigris vector store.\nInitialize Tigris vector store.\nAttributes\nembeddings\nAccess the query embedding object if available.\nsearch_index\nMethods\n__init__(client,\u00a0embeddings,\u00a0index_name)\nInitialize Tigris vector store.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tigris.Tigris.html"}
{"id": "12da4fb431b7-1", "text": "Return docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nRun similarity search with Chroma with distance.\n__init__(client: TigrisClient, embeddings: Embeddings, index_name: str)[source]\u00b6\nInitialize Tigris vector store.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tigris.Tigris.html"}
{"id": "12da4fb431b7-2", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of ids for documents.\nIds will be autogenerated if not provided.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tigris.Tigris.html"}
{"id": "12da4fb431b7-3", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tigris.Tigris.html"}
{"id": "12da4fb431b7-4", "text": "Return type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tigris.Tigris.html"}
{"id": "12da4fb431b7-5", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, client: Optional[TigrisClient] = None, index_name: Optional[str] = None, **kwargs: Any) \u2192 Tigris[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tigris.Tigris.html"}
{"id": "12da4fb431b7-6", "text": "Return docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[TigrisFilter] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tigris.Tigris.html"}
{"id": "12da4fb431b7-7", "text": "Return docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[TigrisFilter] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with Chroma with distance.\nParameters\nquery (str) \u2013 Query text to search for.\nk (int) \u2013 Number of results to return. Defaults to 4.\nfilter (Optional[TigrisFilter]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of documents most similar to the querytext with distance in float.\nReturn type\nList[Tuple[Document, float]]\nExamples using Tigris\u00b6\nTigris", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tigris.Tigris.html"}
{"id": "47575929e1fa-0", "text": "langchain.vectorstores.starrocks.StarRocks\u00b6\nclass langchain.vectorstores.starrocks.StarRocks(embedding: Embeddings, config: Optional[StarRocksSettings] = None, **kwargs: Any)[source]\u00b6\nStarRocks vector store.\nYou need a pymysql python package, and a valid account\nto connect to StarRocks.\nRight now StarRocks has only implemented cosine_similarity function to\ncompute distance between two vectors. And there is no vector inside right now,\nso we have to iterate all vectors and compute spatial distance.\nFor more information, please visit[StarRocks official site](https://www.starrocks.io/)\n[StarRocks github](https://github.com/StarRocks/starrocks)\nStarRocks Wrapper to LangChain\nembedding_function (Embeddings):\nconfig (StarRocksSettings): Configuration to StarRocks Client\nAttributes\nembeddings\nAccess the query embedding object if available.\nmetadata_column\nMethods\n__init__(embedding[,\u00a0config])\nStarRocks Wrapper to LangChain\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0batch_size,\u00a0ids])\nInsert more texts through the embeddings and add to the VectorStore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html"}
{"id": "47575929e1fa-1", "text": "Return VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\ndrop()\nHelper function: Drop data\nescape_str(value)\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreate StarRocks wrapper with existing texts\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0where_str])\nPerform a similarity search with StarRocks\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nPerform a similarity search with StarRocks by vectors\nsimilarity_search_with_relevance_scores(query)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html"}
{"id": "47575929e1fa-2", "text": "similarity_search_with_relevance_scores(query)\nPerform a similarity search with StarRocks\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\n__init__(embedding: Embeddings, config: Optional[StarRocksSettings] = None, **kwargs: Any) \u2192 None[source]\u00b6\nStarRocks Wrapper to LangChain\nembedding_function (Embeddings):\nconfig (StarRocksSettings): Configuration to StarRocks Client\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, batch_size: int = 32, ids: Optional[Iterable[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nInsert more texts through the embeddings and add to the VectorStore.\nParameters\ntexts \u2013 Iterable of strings to add to the VectorStore.\nids \u2013 Optional list of ids to associate with the texts.\nbatch_size \u2013 Batch size of insertion\nmetadata \u2013 Optional column data to be inserted", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html"}
{"id": "47575929e1fa-3", "text": "batch_size \u2013 Batch size of insertion\nmetadata \u2013 Optional column data to be inserted\nReturns\nList of ids from adding the texts into the VectorStore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html"}
{"id": "47575929e1fa-4", "text": "Can be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html"}
{"id": "47575929e1fa-5", "text": "search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\ndrop() \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html"}
{"id": "47575929e1fa-6", "text": "Return type\nOptional[bool]\ndrop() \u2192 None[source]\u00b6\nHelper function: Drop data\nescape_str(value: str) \u2192 str[source]\u00b6\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, config: Optional[StarRocksSettings] = None, text_ids: Optional[Iterable[str]] = None, batch_size: int = 32, **kwargs: Any) \u2192 StarRocks[source]\u00b6\nCreate StarRocks wrapper with existing texts\nParameters\nembedding_function (Embeddings) \u2013 Function to extract text embedding\ntexts (Iterable[str]) \u2013 List or tuple of strings to be added\nconfig (StarRocksSettings, Optional) \u2013 StarRocks configuration\ntext_ids (Optional[Iterable], optional) \u2013 IDs for the texts.\nDefaults to None.\nbatch_size (int, optional) \u2013 Batchsize when transmitting data to StarRocks.\nDefaults to 32.\nmetadata (List[dict], optional) \u2013 metadata to texts. Defaults to None.\nReturns\nStarRocks Index\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html"}
{"id": "47575929e1fa-7", "text": "fetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a similarity search with StarRocks\nParameters\nquery (str) \u2013 query string\nk (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.\nwhere_str (Optional[str], optional) \u2013 where condition string.\nDefaults to None.\nNOTE \u2013 Please do not let end-user to fill this and always be aware", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html"}
{"id": "47575929e1fa-8", "text": "NOTE \u2013 Please do not let end-user to fill this and always be aware\nof SQL injection. When dealing with metadatas, remember to\nuse {self.metadata_column}.attribute instead of attribute\nalone. The default name for it is metadata.\nReturns\nList of Documents\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a similarity search with StarRocks by vectors\nParameters\nquery (str) \u2013 query string\nk (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.\nwhere_str (Optional[str], optional) \u2013 where condition string.\nDefaults to None.\nNOTE \u2013 Please do not let end-user to fill this and always be aware\nof SQL injection. When dealing with metadatas, remember to\nuse {self.metadata_column}.attribute instead of attribute\nalone. The default name for it is metadata.\nReturns\nList of (Document, similarity)\nReturn type\nList[Document]\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPerform a similarity search with StarRocks\nParameters\nquery (str) \u2013 query string\nk (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.\nwhere_str (Optional[str], optional) \u2013 where condition string.\nDefaults to None.\nNOTE \u2013 Please do not let end-user to fill this and always be aware\nof SQL injection. When dealing with metadatas, remember to\nuse {self.metadata_column}.attribute instead of attribute\nalone. The default name for it is metadata.\nReturns\nList of documents\nReturn type", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html"}
{"id": "47575929e1fa-9", "text": "alone. The default name for it is metadata.\nReturns\nList of documents\nReturn type\nList[Document]\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.\nExamples using StarRocks\u00b6\nStarRocks", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.StarRocks.html"}
{"id": "fbdb098de978-0", "text": "langchain.vectorstores.chroma.Chroma\u00b6\nclass langchain.vectorstores.chroma.Chroma(collection_name: str = 'langchain', embedding_function: Optional[Embeddings] = None, persist_directory: Optional[str] = None, client_settings: Optional[chromadb.config.Settings] = None, collection_metadata: Optional[Dict] = None, client: Optional[chromadb.Client] = None, relevance_score_fn: Optional[Callable[[float], float]] = None)[source]\u00b6\nChromaDB vector store.\nTo use, you should have the chromadb python package installed.\nExample\nfrom langchain.vectorstores import Chroma\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nvectorstore = Chroma(\"langchain_store\", embeddings)\nInitialize with a Chroma client.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__([collection_name,\u00a0...])\nInitialize with a Chroma client.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_images(uris[,\u00a0metadatas,\u00a0ids])\nRun more images through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.chroma.Chroma.html"}
{"id": "fbdb098de978-1", "text": "afrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector IDs.\ndelete_collection()\nDelete the collection.\nencode_image(uri)\nGet base64 string from image URI.\nfrom_documents(documents[,\u00a0embedding,\u00a0ids,\u00a0...])\nCreate a Chroma vectorstore from a list of documents.\nfrom_texts(texts[,\u00a0embedding,\u00a0metadatas,\u00a0...])\nCreate a Chroma vectorstore from a raw documents.\nget([ids,\u00a0where,\u00a0limit,\u00a0offset,\u00a0...])\nGets the collection.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\npersist()\nPersist the collection.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.chroma.Chroma.html"}
{"id": "fbdb098de978-2", "text": "Return docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nRun similarity search with Chroma.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_by_vector_with_relevance_scores(...)\nReturn docs most similar to embedding vector and similarity score.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nRun similarity search with Chroma with distance.\nupdate_document(document_id,\u00a0document)\nUpdate a document in the collection.\nupdate_documents(ids,\u00a0documents)\nUpdate a document in the collection.\n__init__(collection_name: str = 'langchain', embedding_function: Optional[Embeddings] = None, persist_directory: Optional[str] = None, client_settings: Optional[chromadb.config.Settings] = None, collection_metadata: Optional[Dict] = None, client: Optional[chromadb.Client] = None, relevance_score_fn: Optional[Callable[[float], float]] = None) \u2192 None[source]\u00b6\nInitialize with a Chroma client.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.chroma.Chroma.html"}
{"id": "fbdb098de978-3", "text": "add_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_images(uris: List[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more images through the embeddings and add to the vectorstore.\nParameters\nimages (List[List[float]]) \u2013 Images to add to the vectorstore.\nmetadatas (Optional[List[dict]], optional) \u2013 Optional list of metadatas.\nids (Optional[List[str]], optional) \u2013 Optional list of IDs.\nReturns\nList of IDs of the added images.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts (Iterable[str]) \u2013 Texts to add to the vectorstore.\nmetadatas (Optional[List[dict]], optional) \u2013 Optional list of metadatas.\nids (Optional[List[str]], optional) \u2013 Optional list of IDs.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.chroma.Chroma.html"}
{"id": "fbdb098de978-4", "text": "Returns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.chroma.Chroma.html"}
{"id": "fbdb098de978-5", "text": "lambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.chroma.Chroma.html"}
{"id": "fbdb098de978-6", "text": "Return docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDelete by vector IDs.\nParameters\nids \u2013 List of ids to delete.\ndelete_collection() \u2192 None[source]\u00b6\nDelete the collection.\nencode_image(uri: str) \u2192 str[source]\u00b6\nGet base64 string from image URI.\nclassmethod from_documents(documents: List[Document], embedding: Optional[Embeddings] = None, ids: Optional[List[str]] = None, collection_name: str = 'langchain', persist_directory: Optional[str] = None, client_settings: Optional[chromadb.config.Settings] = None, client: Optional[chromadb.Client] = None, collection_metadata: Optional[Dict] = None, **kwargs: Any) \u2192 Chroma[source]\u00b6\nCreate a Chroma vectorstore from a list of documents.\nIf a persist_directory is specified, the collection will be persisted there.\nOtherwise, the data will be ephemeral in-memory.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.chroma.Chroma.html"}
{"id": "fbdb098de978-7", "text": "Otherwise, the data will be ephemeral in-memory.\nParameters\ncollection_name (str) \u2013 Name of the collection to create.\npersist_directory (Optional[str]) \u2013 Directory to persist the collection.\nids (Optional[List[str]]) \u2013 List of document IDs. Defaults to None.\ndocuments (List[Document]) \u2013 List of documents to add to the vectorstore.\nembedding (Optional[Embeddings]) \u2013 Embedding function. Defaults to None.\nclient_settings (Optional[chromadb.config.Settings]) \u2013 Chroma client settings\ncollection_metadata (Optional[Dict]) \u2013 Collection configurations.\nDefaults to None.\nReturns\nChroma vectorstore.\nReturn type\nChroma\nclassmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, collection_name: str = 'langchain', persist_directory: Optional[str] = None, client_settings: Optional[chromadb.config.Settings] = None, client: Optional[chromadb.Client] = None, collection_metadata: Optional[Dict] = None, **kwargs: Any) \u2192 Chroma[source]\u00b6\nCreate a Chroma vectorstore from a raw documents.\nIf a persist_directory is specified, the collection will be persisted there.\nOtherwise, the data will be ephemeral in-memory.\nParameters\ntexts (List[str]) \u2013 List of texts to add to the collection.\ncollection_name (str) \u2013 Name of the collection to create.\npersist_directory (Optional[str]) \u2013 Directory to persist the collection.\nembedding (Optional[Embeddings]) \u2013 Embedding function. Defaults to None.\nmetadatas (Optional[List[dict]]) \u2013 List of metadatas. Defaults to None.\nids (Optional[List[str]]) \u2013 List of document IDs. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.chroma.Chroma.html"}
{"id": "fbdb098de978-8", "text": "ids (Optional[List[str]]) \u2013 List of document IDs. Defaults to None.\nclient_settings (Optional[chromadb.config.Settings]) \u2013 Chroma client settings\ncollection_metadata (Optional[Dict]) \u2013 Collection configurations.\nDefaults to None.\nReturns\nChroma vectorstore.\nReturn type\nChroma\nget(ids: Optional[OneOrMany[ID]] = None, where: Optional[Where] = None, limit: Optional[int] = None, offset: Optional[int] = None, where_document: Optional[WhereDocument] = None, include: Optional[List[str]] = None) \u2192 Dict[str, Any][source]\u00b6\nGets the collection.\nParameters\nids \u2013 The ids of the embeddings to get. Optional.\nwhere \u2013 A Where type dict used to filter results by.\nE.g. {\u201ccolor\u201d : \u201cred\u201d, \u201cprice\u201d: 4.20}. Optional.\nlimit \u2013 The number of documents to return. Optional.\noffset \u2013 The offset to start returning results from.\nUseful for paging results with limit. Optional.\nwhere_document \u2013 A WhereDocument type dict used to filter by the documents.\nE.g. {$contains: \u201chello\u201d}. Optional.\ninclude \u2013 A list of what to include in the results.\nCan contain \u201cembeddings\u201d, \u201cmetadatas\u201d, \u201cdocuments\u201d.\nIds are always included.\nDefaults to [\u201cmetadatas\u201d, \u201cdocuments\u201d]. Optional.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, where_document: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.chroma.Chroma.html"}
{"id": "fbdb098de978-9", "text": "Maximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, where_document: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents selected by maximal marginal relevance.\npersist() \u2192 None[source]\u00b6\nPersist the collection.\nThis can be used to explicitly persist the data to disk.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.chroma.Chroma.html"}
{"id": "fbdb098de978-10", "text": "Persist the collection.\nThis can be used to explicitly persist the data to disk.\nIt will also be called automatically when the object is destroyed.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRun similarity search with Chroma.\nParameters\nquery (str) \u2013 Query text to search for.\nk (int) \u2013 Number of results to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of documents most similar to the query text.\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None, where_document: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\n:param embedding: Embedding to look up documents similar to.\n:type embedding: List[float]\n:param k: Number of Documents to return. Defaults to 4.\n:type k: int\n:param filter: Filter by metadata. Defaults to None.\n:type filter: Optional[Dict[str, str]]\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_by_vector_with_relevance_scores(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None, where_document: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.chroma.Chroma.html"}
{"id": "fbdb098de978-11", "text": "Return docs most similar to embedding vector and similarity score.\nParameters\nembedding (List[float]) \u2013 Embedding to look up documents similar to.\nk (int) \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of documents most similar to\nthe query text and cosine distance in float for each.\nLower score represents more similarity.\nReturn type\nList[Tuple[Document, float]]\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None, where_document: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with Chroma with distance.\nParameters\nquery (str) \u2013 Query text to search for.\nk (int) \u2013 Number of results to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of documents most similar to\nthe query text and cosine distance in float for each.\nLower score represents more similarity.\nReturn type", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.chroma.Chroma.html"}
{"id": "fbdb098de978-12", "text": "Lower score represents more similarity.\nReturn type\nList[Tuple[Document, float]]\nupdate_document(document_id: str, document: Document) \u2192 None[source]\u00b6\nUpdate a document in the collection.\nParameters\ndocument_id (str) \u2013 ID of the document to update.\ndocument (Document) \u2013 Document to update.\nupdate_documents(ids: List[str], documents: List[Document]) \u2192 None[source]\u00b6\nUpdate a document in the collection.\nParameters\nids (List[str]) \u2013 List of ids of the document to update.\ndocuments (List[Document]) \u2013 List of documents to update.\nExamples using Chroma\u00b6\nRePhraseQueryRetriever\nLOTR (Merger Retriever)\nOllama\nConfident\nChroma\nVectorstore\nStarRocks\nPsychic\nDocugami\nSet env var OPENAI_API_KEY or load from a .env file:\nSet env var OPENAI_API_KEY or load from a .env file\nQuestion Answering\nPerform context-aware text splitting\nUse local LLMs\nRetrieve from vector stores directly\nImprove document indexing with HyDE\nStructure answers with OpenAI functions\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nMultiVector Retriever\nMultiQueryRetriever\nParent Document Retriever\nWebResearchRetriever\nLost in the middle: The problem with long contexts\nMemory in the Multi-Input Chain\nCombine agents and vector stores\nFew-shot examples for chat models\nRouter\nLoading from LangChainHub", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.chroma.Chroma.html"}
{"id": "ca7b0729d867-0", "text": "langchain.vectorstores.scann.dependable_scann_import\u00b6\nlangchain.vectorstores.scann.dependable_scann_import() \u2192 Any[source]\u00b6\nImport scann if available, otherwise raise error.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.scann.dependable_scann_import.html"}
{"id": "a96a98c92f98-0", "text": "langchain.vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch\u00b6\nclass langchain.vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch(collection: Collection[CosmosDBDocumentType], embedding: Embeddings, *, index_name: str = 'vectorSearchIndex', text_key: str = 'textContent', embedding_key: str = 'vectorContent')[source]\u00b6\nAzure Cosmos DB for MongoDB vCore vector store.\nTo use, you should have both:\n- the pymongo python package installed\n- a connection string associated with a MongoDB VCore Cluster\nExample\n. code-block:: python\nfrom langchain.vectorstores import AzureCosmosDBVectorSearch\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom pymongo import MongoClient\nmongo_client = MongoClient(\u201c<YOUR-CONNECTION-STRING>\u201d)\ncollection = mongo_client[\u201c<db_name>\u201d][\u201c<collection_name>\u201d]\nembeddings = OpenAIEmbeddings()\nvectorstore = AzureCosmosDBVectorSearch(collection, embeddings)\nConstructor for AzureCosmosDBVectorSearch\nParameters\ncollection \u2013 MongoDB collection to add the texts to.\nembedding \u2013 Text embedding model to use.\nindex_name \u2013 Name of the Atlas Search index.\ntext_key \u2013 MongoDB field that will contain the text\nfor each document.\nembedding_key \u2013 MongoDB field that will contain the embedding\nfor each document.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(collection,\u00a0embedding,\u00a0*[,\u00a0...])\nConstructor for AzureCosmosDBVectorSearch\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch.html"}
{"id": "a96a98c92f98-1", "text": "add_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ncreate_index([num_lists,\u00a0dimensions,\u00a0similarity])\nCreates an index using the index name specified at\ndelete([ids])\nDelete by vector ID or other criteria.\ndelete_document_by_id([document_id])\nRemoves a Specific Document by Id\ndelete_index()\nDeletes the index specified during instance construction if it exists\nfrom_connection_string(connection_string,\u00a0...)\nCreates an Instance of AzureCosmosDBVectorSearch from a Connection String", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch.html"}
{"id": "a96a98c92f98-2", "text": "Creates an Instance of AzureCosmosDBVectorSearch from a Connection String\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nget_index_name()\nReturns the index name\nindex_exists()\nVerifies if the specified index name during instance\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nRun similarity search with distance.\n__init__(collection: Collection[CosmosDBDocumentType], embedding: Embeddings, *, index_name: str = 'vectorSearchIndex', text_key: str = 'textContent', embedding_key: str = 'vectorContent')[source]\u00b6\nConstructor for AzureCosmosDBVectorSearch\nParameters\ncollection \u2013 MongoDB collection to add the texts to.\nembedding \u2013 Text embedding model to use.\nindex_name \u2013 Name of the Atlas Search index.\ntext_key \u2013 MongoDB field that will contain the text\nfor each document.\nembedding_key \u2013 MongoDB field that will contain the embedding\nfor each document.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch.html"}
{"id": "a96a98c92f98-3", "text": "Run more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[Dict[str, Any]]] = None, **kwargs: Any) \u2192 List[source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch.html"}
{"id": "a96a98c92f98-4", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch.html"}
{"id": "a96a98c92f98-5", "text": "Return type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch.html"}
{"id": "a96a98c92f98-6", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ncreate_index(num_lists: int = 100, dimensions: int = 1536, similarity: CosmosDBSimilarityType = CosmosDBSimilarityType.COS) \u2192 dict[str, Any][source]\u00b6\nCreates an index using the index name specified atinstance construction\nSetting the numLists parameter correctly is important for achievinggood accuracy and performance.\nSince the vector store uses IVF as the indexing strategy,\nyou should create the index only after you\nhave loaded a large enough sample documents to ensure that the\ncentroids for the respective buckets are\nfaily distributed.\nWe recommend that numLists is set to documentCount/1000 for upto 1 million documents\nand to sqrt(documentCount) for more than 1 million documents.\nAs the number of items in your database grows, you should\ntune numLists to be larger\nin order to achieve good latency performance for vector search.\nIf you\u2019re experimenting with a new scenario or creating a\nsmall demo, you can start with numLists\nset to 1 to perform a brute-force search across all vectors.\nThis should provide you with the most\naccurate results from the vector search, however be aware that\nthe search speed and latency will be slow.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch.html"}
{"id": "a96a98c92f98-7", "text": "the search speed and latency will be slow.\nAfter your initial setup, you should go ahead and tune\nthe numLists parameter using the above guidance.\nParameters\nnum_lists \u2013 This integer is the number of clusters that the\ninverted file (IVF) index uses to group the vector data.\nWe recommend that numLists is set to documentCount/1000\nfor up to 1 million documents and to sqrt(documentCount)\nfor more than 1 million documents.\nUsing a numLists value of 1 is akin to performing\nbrute-force search, which has limited performance\ndimensions \u2013 Number of dimensions for vector similarity.\nThe maximum number of supported dimensions is 2000\nsimilarity \u2013 Similarity metric to use with the IVF index.\nPossible options are:\nCosmosDBSimilarityType.COS (cosine distance),\nCosmosDBSimilarityType.L2 (Euclidean distance), and\nCosmosDBSimilarityType.IP (inner product).\nReturns\nAn object describing the created index\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\ndelete_document_by_id(document_id: Optional[str] = None) \u2192 None[source]\u00b6\nRemoves a Specific Document by Id\nParameters\ndocument_id \u2013 The document identifier\ndelete_index() \u2192 None[source]\u00b6\nDeletes the index specified during instance construction if it exists\nclassmethod from_connection_string(connection_string: str, namespace: str, embedding: Embeddings, **kwargs: Any) \u2192 AzureCosmosDBVectorSearch[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch.html"}
{"id": "a96a98c92f98-8", "text": "Creates an Instance of AzureCosmosDBVectorSearch from a Connection String\nParameters\nconnection_string \u2013 The MongoDB vCore instance connection string\nnamespace \u2013 The namespace (database.collection)\nembedding \u2013 The embedding utility\n**kwargs \u2013 Dynamic keyword arguments\nReturns\nan instance of the vector store\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection: Optional[Collection[CosmosDBDocumentType]] = None, **kwargs: Any) \u2192 AzureCosmosDBVectorSearch[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nget_index_name() \u2192 str[source]\u00b6\nReturns the index name\nReturns\nReturns the index name\nindex_exists() \u2192 bool[source]\u00b6\nVerifies if the specified index name during instanceconstruction exists on the collection\nReturns\nReturns True on success and False if no such index existson the collection\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch.html"}
{"id": "a96a98c92f98-9", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch.html"}
{"id": "a96a98c92f98-10", "text": "Return docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch.html"}
{"id": "0c52a28c8bf8-0", "text": "langchain.vectorstores.clickhouse.Clickhouse\u00b6\nclass langchain.vectorstores.clickhouse.Clickhouse(embedding: Embeddings, config: Optional[ClickhouseSettings] = None, **kwargs: Any)[source]\u00b6\nClickHouse VectorSearch vector store.\nYou need a clickhouse-connect python package, and a valid account\nto connect to ClickHouse.\nClickHouse can not only search with simple vector indexes,\nit also supports complex query with multiple conditions,\nconstraints and even sub-queries.\nFor more information, please visit[ClickHouse official site](https://clickhouse.com/clickhouse)\nClickHouse Wrapper to LangChain\nembedding_function (Embeddings):\nconfig (ClickHouseSettings): Configuration to ClickHouse Client\nOther keyword arguments will pass into\n[clickhouse-connect](https://docs.clickhouse.com/)\nAttributes\nembeddings\nAccess the query embedding object if available.\nmetadata_column\nMethods\n__init__(embedding[,\u00a0config])\nClickHouse Wrapper to LangChain\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0batch_size,\u00a0ids])\nInsert more texts through the embeddings and add to the VectorStore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.Clickhouse.html"}
{"id": "0c52a28c8bf8-1", "text": "amax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\ndrop()\nHelper function: Drop data\nescape_str(value)\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreate ClickHouse wrapper with existing texts\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0where_str])\nPerform a similarity search with ClickHouse\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nPerform a similarity search with ClickHouse by vectors\nsimilarity_search_with_relevance_scores(query)\nPerform a similarity search with ClickHouse", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.Clickhouse.html"}
{"id": "0c52a28c8bf8-2", "text": "similarity_search_with_relevance_scores(query)\nPerform a similarity search with ClickHouse\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\n__init__(embedding: Embeddings, config: Optional[ClickhouseSettings] = None, **kwargs: Any) \u2192 None[source]\u00b6\nClickHouse Wrapper to LangChain\nembedding_function (Embeddings):\nconfig (ClickHouseSettings): Configuration to ClickHouse Client\nOther keyword arguments will pass into\n[clickhouse-connect](https://docs.clickhouse.com/)\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, batch_size: int = 32, ids: Optional[Iterable[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nInsert more texts through the embeddings and add to the VectorStore.\nParameters\ntexts \u2013 Iterable of strings to add to the VectorStore.\nids \u2013 Optional list of ids to associate with the texts.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.Clickhouse.html"}
{"id": "0c52a28c8bf8-3", "text": "ids \u2013 Optional list of ids to associate with the texts.\nbatch_size \u2013 Batch size of insertion\nmetadata \u2013 Optional column data to be inserted\nReturns\nList of ids from adding the texts into the VectorStore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.Clickhouse.html"}
{"id": "0c52a28c8bf8-4", "text": "the Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.Clickhouse.html"}
{"id": "0c52a28c8bf8-5", "text": "search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\ndrop() \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.Clickhouse.html"}
{"id": "0c52a28c8bf8-6", "text": "Return type\nOptional[bool]\ndrop() \u2192 None[source]\u00b6\nHelper function: Drop data\nescape_str(value: str) \u2192 str[source]\u00b6\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, config: Optional[ClickhouseSettings] = None, text_ids: Optional[Iterable[str]] = None, batch_size: int = 32, **kwargs: Any) \u2192 Clickhouse[source]\u00b6\nCreate ClickHouse wrapper with existing texts\nParameters\nembedding_function (Embeddings) \u2013 Function to extract text embedding\ntexts (Iterable[str]) \u2013 List or tuple of strings to be added\nconfig (ClickHouseSettings, Optional) \u2013 ClickHouse configuration\ntext_ids (Optional[Iterable], optional) \u2013 IDs for the texts.\nDefaults to None.\nbatch_size (int, optional) \u2013 Batchsize when transmitting data to ClickHouse.\nDefaults to 32.\nmetadata (List[dict], optional) \u2013 metadata to texts. Defaults to None.\ninto (Other keyword arguments will pass) \u2013 [clickhouse-connect](https://clickhouse.com/docs/en/integrations/python#clickhouse-connect-driver-api)\nReturns\nClickHouse Index\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.Clickhouse.html"}
{"id": "0c52a28c8bf8-7", "text": "k \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a similarity search with ClickHouse\nParameters\nquery (str) \u2013 query string\nk (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.\nwhere_str (Optional[str], optional) \u2013 where condition string.\nDefaults to None.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.Clickhouse.html"}
{"id": "0c52a28c8bf8-8", "text": "where_str (Optional[str], optional) \u2013 where condition string.\nDefaults to None.\nNOTE \u2013 Please do not let end-user to fill this and always be aware\nof SQL injection. When dealing with metadatas, remember to\nuse {self.metadata_column}.attribute instead of attribute\nalone. The default name for it is metadata.\nReturns\nList of Documents\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a similarity search with ClickHouse by vectors\nParameters\nquery (str) \u2013 query string\nk (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.\nwhere_str (Optional[str], optional) \u2013 where condition string.\nDefaults to None.\nNOTE \u2013 Please do not let end-user to fill this and always be aware\nof SQL injection. When dealing with metadatas, remember to\nuse {self.metadata_column}.attribute instead of attribute\nalone. The default name for it is metadata.\nReturns\nList of documents\nReturn type\nList[Document]\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPerform a similarity search with ClickHouse\nParameters\nquery (str) \u2013 query string\nk (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.\nwhere_str (Optional[str], optional) \u2013 where condition string.\nDefaults to None.\nNOTE \u2013 Please do not let end-user to fill this and always be aware\nof SQL injection. When dealing with metadatas, remember to\nuse {self.metadata_column}.attribute instead of attribute", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.Clickhouse.html"}
{"id": "0c52a28c8bf8-9", "text": "use {self.metadata_column}.attribute instead of attribute\nalone. The default name for it is metadata.\nReturns\nList of (Document, similarity)\nReturn type\nList[Document]\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.\nExamples using Clickhouse\u00b6\nClickHouse", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.Clickhouse.html"}
{"id": "a81728c93802-0", "text": "langchain.vectorstores.deeplake.DeepLake\u00b6\nclass langchain.vectorstores.deeplake.DeepLake(dataset_path: str = './deeplake/', token: Optional[str] = None, embedding: Optional[Embeddings] = None, embedding_function: Optional[Embeddings] = None, read_only: bool = False, ingestion_batch_size: int = 1000, num_workers: int = 0, verbose: bool = True, exec_option: Optional[str] = None, runtime: Optional[Dict] = None, index_params: Optional[Dict[str, Union[int, str]]] = None, **kwargs: Any)[source]\u00b6\nActiveloop Deep Lake vector store.\nWe integrated deeplake\u2019s similarity search and filtering for fast prototyping.\nNow, it supports Tensor Query Language (TQL) for production use cases\nover billion rows.\nWhy Deep Lake?\nNot only stores embeddings, but also the original data with version control.\nServerless, doesn\u2019t require another service and can be used with majorcloud providers (S3, GCS, etc.)\nMore than just a multi-modal vector store. You can use the datasetto fine-tune your own LLM models.\nTo use, you should have the deeplake python package installed.\nExample\nfrom langchain.vectorstores import DeepLake\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nvectorstore = DeepLake(\"langchain_store\", embeddings.embed_query)\nCreates an empty DeepLakeVectorStore or loads an existing one.\nThe DeepLakeVectorStore is located at the specified path.\nExamples\n>>> # Create a vector store with default tensors\n>>> deeplake_vectorstore = DeepLake(\n...        path = <path_for_storing_Data>,\n... )\n>>>\n>>> # Create a vector store in the Deep Lake Managed Tensor Database", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-1", "text": "... )\n>>>\n>>> # Create a vector store in the Deep Lake Managed Tensor Database\n>>> data = DeepLake(\n...        path = \"hub://org_id/dataset_name\",\n...        runtime = {\"tensor_db\": True},\n... )\nParameters\ndataset_path (str) \u2013 Path to existing dataset or where to create\na new one. Defaults to _LANGCHAIN_DEFAULT_DEEPLAKE_PATH.\ntoken (str, optional) \u2013 Activeloop token, for fetching credentials\nto the dataset at path if it is a Deep Lake dataset.\nTokens are normally autogenerated. Optional.\nembedding (Embeddings, optional) \u2013 Function to convert\neither documents or query. Optional.\nembedding_function (Embeddings, optional) \u2013 Function to convert\neither documents or query. Optional. Deprecated: keeping this\nparameter for backwards compatibility.\nread_only (bool) \u2013 Open dataset in read-only mode. Default is False.\ningestion_batch_size (int) \u2013 During data ingestion, data is divided\ninto batches. Batch size is the size of each batch.\nDefault is 1000.\nnum_workers (int) \u2013 Number of workers to use during data ingestion.\nDefault is 0.\nverbose (bool) \u2013 Print dataset summary after each operation.\nDefault is True.\nexec_option (str, optional) \u2013 DeepLakeVectorStore supports 3 ways to perform\nsearching - \u201cpython\u201d, \u201ccompute_engine\u201d, \u201ctensor_db\u201d and auto.\nDefault is None.\n- auto- Selects the best execution method based on the storage\nlocation of the Vector Store. It is the default option.\npython - Pure-python implementation that runs on the client.WARNING: using this with big datasets can lead to memory\nissues. Data can be stored anywhere.\ncompute_engine - C++ implementation of the Deep Lake ComputeEngine that runs on the client. Can be used for any data stored in", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-2", "text": "or connected to Deep Lake. Not for in-memory or local datasets.\ntensor_db - Hosted Managed Tensor Database that isresponsible for storage and query execution. Only for data stored in\nthe Deep Lake Managed Database. Use runtime = {\u201cdb_engine\u201d: True}\nduring dataset creation.\nruntime (Dict, optional) \u2013 Parameters for creating the Vector Store in\nDeep Lake\u2019s Managed Tensor Database. Not applicable when loading an\nexisting Vector Store. To create a Vector Store in the Managed Tensor\nDatabase, set runtime = {\u201ctensor_db\u201d: True}.\nindex_params (Optional[Dict[str, Union[int, str]]], optional) \u2013 Dictionary\ncontaining information about vector index that will be created. Defaults\nto None, which will utilize DEFAULT_VECTORSTORE_INDEX_PARAMS from\ndeeplake.constants. The specified key-values override the default\nones.\n- threshold: The threshold for the dataset size above which an index\nwill be created for the embedding tensor. When the threshold value\nis set to -1, index creation is turned off. Defaults to -1, which\nturns off the index.\ndistance_metric: This key specifies the method of calculating thedistance between vectors when creating the vector database (VDB)\nindex. It can either be a string that corresponds to a member of\nthe DistanceType enumeration, or the string value itself.\n- If no value is provided, it defaults to \u201cL2\u201d.\n- \u201cL2\u201d corresponds to DistanceType.L2_NORM.\n- \u201cCOS\u201d corresponds to DistanceType.COSINE_SIMILARITY.\nadditional_params: Additional parameters for fine-tuning the index.\n**kwargs \u2013 Other optional keyword arguments.\nRaises\nValueError \u2013 If some condition is not met.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__([dataset_path,\u00a0token,\u00a0embedding,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-3", "text": "Methods\n__init__([dataset_path,\u00a0token,\u00a0embedding,\u00a0...])\nCreates an empty DeepLakeVectorStore or loads an existing one.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete the entities in the dataset.\ndelete_dataset()", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-4", "text": "delete([ids])\nDelete the entities in the dataset.\ndelete_dataset()\nDelete the collection.\nds()\nforce_delete_by_path(path)\nForce delete dataset by path.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts[,\u00a0embedding,\u00a0metadatas,\u00a0...])\nCreate a Deep Lake dataset from a raw documents.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nRun similarity search with Deep Lake with distance returned.\n__init__(dataset_path: str = './deeplake/', token: Optional[str] = None, embedding: Optional[Embeddings] = None, embedding_function: Optional[Embeddings] = None, read_only: bool = False, ingestion_batch_size: int = 1000, num_workers: int = 0, verbose: bool = True, exec_option: Optional[str] = None, runtime: Optional[Dict] = None, index_params: Optional[Dict[str, Union[int, str]]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nCreates an empty DeepLakeVectorStore or loads an existing one.\nThe DeepLakeVectorStore is located at the specified path.\nExamples", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-5", "text": "The DeepLakeVectorStore is located at the specified path.\nExamples\n>>> # Create a vector store with default tensors\n>>> deeplake_vectorstore = DeepLake(\n...        path = <path_for_storing_Data>,\n... )\n>>>\n>>> # Create a vector store in the Deep Lake Managed Tensor Database\n>>> data = DeepLake(\n...        path = \"hub://org_id/dataset_name\",\n...        runtime = {\"tensor_db\": True},\n... )\nParameters\ndataset_path (str) \u2013 Path to existing dataset or where to create\na new one. Defaults to _LANGCHAIN_DEFAULT_DEEPLAKE_PATH.\ntoken (str, optional) \u2013 Activeloop token, for fetching credentials\nto the dataset at path if it is a Deep Lake dataset.\nTokens are normally autogenerated. Optional.\nembedding (Embeddings, optional) \u2013 Function to convert\neither documents or query. Optional.\nembedding_function (Embeddings, optional) \u2013 Function to convert\neither documents or query. Optional. Deprecated: keeping this\nparameter for backwards compatibility.\nread_only (bool) \u2013 Open dataset in read-only mode. Default is False.\ningestion_batch_size (int) \u2013 During data ingestion, data is divided\ninto batches. Batch size is the size of each batch.\nDefault is 1000.\nnum_workers (int) \u2013 Number of workers to use during data ingestion.\nDefault is 0.\nverbose (bool) \u2013 Print dataset summary after each operation.\nDefault is True.\nexec_option (str, optional) \u2013 DeepLakeVectorStore supports 3 ways to perform\nsearching - \u201cpython\u201d, \u201ccompute_engine\u201d, \u201ctensor_db\u201d and auto.\nDefault is None.\n- auto- Selects the best execution method based on the storage\nlocation of the Vector Store. It is the default option.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-6", "text": "location of the Vector Store. It is the default option.\npython - Pure-python implementation that runs on the client.WARNING: using this with big datasets can lead to memory\nissues. Data can be stored anywhere.\ncompute_engine - C++ implementation of the Deep Lake ComputeEngine that runs on the client. Can be used for any data stored in\nor connected to Deep Lake. Not for in-memory or local datasets.\ntensor_db - Hosted Managed Tensor Database that isresponsible for storage and query execution. Only for data stored in\nthe Deep Lake Managed Database. Use runtime = {\u201cdb_engine\u201d: True}\nduring dataset creation.\nruntime (Dict, optional) \u2013 Parameters for creating the Vector Store in\nDeep Lake\u2019s Managed Tensor Database. Not applicable when loading an\nexisting Vector Store. To create a Vector Store in the Managed Tensor\nDatabase, set runtime = {\u201ctensor_db\u201d: True}.\nindex_params (Optional[Dict[str, Union[int, str]]], optional) \u2013 Dictionary\ncontaining information about vector index that will be created. Defaults\nto None, which will utilize DEFAULT_VECTORSTORE_INDEX_PARAMS from\ndeeplake.constants. The specified key-values override the default\nones.\n- threshold: The threshold for the dataset size above which an index\nwill be created for the embedding tensor. When the threshold value\nis set to -1, index creation is turned off. Defaults to -1, which\nturns off the index.\ndistance_metric: This key specifies the method of calculating thedistance between vectors when creating the vector database (VDB)\nindex. It can either be a string that corresponds to a member of\nthe DistanceType enumeration, or the string value itself.\n- If no value is provided, it defaults to \u201cL2\u201d.\n- \u201cL2\u201d corresponds to DistanceType.L2_NORM.\n- \u201cCOS\u201d corresponds to DistanceType.COSINE_SIMILARITY.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-7", "text": "- \u201cCOS\u201d corresponds to DistanceType.COSINE_SIMILARITY.\nadditional_params: Additional parameters for fine-tuning the index.\n**kwargs \u2013 Other optional keyword arguments.\nRaises\nValueError \u2013 If some condition is not met.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nExamples\n>>> ids = deeplake_vectorstore.add_texts(\n...     texts = <list_of_texts>,\n...     metadatas = <list_of_metadata_jsons>,\n...     ids = <list_of_ids>,\n... )\nParameters\ntexts (Iterable[str]) \u2013 Texts to add to the vectorstore.\nmetadatas (Optional[List[dict]], optional) \u2013 Optional list of metadatas.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-8", "text": "metadatas (Optional[List[dict]], optional) \u2013 Optional list of metadatas.\nids (Optional[List[str]], optional) \u2013 Optional list of IDs.\nembedding_function (Optional[Embeddings], optional) \u2013 Embedding function\nto use to convert the text into embeddings.\n**kwargs (Any) \u2013 Any additional keyword arguments passed is not supported\nby this method.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-9", "text": "Return docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-10", "text": ")\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 bool[source]\u00b6\nDelete the entities in the dataset.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-11", "text": "Delete the entities in the dataset.\nParameters\nids (Optional[List[str]], optional) \u2013 The document_ids to delete.\nDefaults to None.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\n- filter (Optional[Dict[str, str]], optional): The filter to delete by.\n- delete_all (Optional[bool], optional): Whether to drop the dataset.\nReturns\nWhether the delete operation was successful.\nReturn type\nbool\ndelete_dataset() \u2192 None[source]\u00b6\nDelete the collection.\nds() \u2192 Any[source]\u00b6\nclassmethod force_delete_by_path(path: str) \u2192 None[source]\u00b6\nForce delete dataset by path.\nParameters\npath (str) \u2013 path of the dataset to delete.\nRaises\nValueError \u2013 if deeplake is not installed.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, dataset_path: str = './deeplake/', **kwargs: Any) \u2192 DeepLake[source]\u00b6\nCreate a Deep Lake dataset from a raw documents.\nIf a dataset_path is specified, the dataset will be persisted in that location,\notherwise by default at ./deeplake\nExamples:\n>>> # Search using an embedding\n>>> vector_store = DeepLake.from_texts(\n\u2026        texts = <the_texts_that_you_want_to_embed>,\n\u2026        embedding_function = <embedding_function_for_query>,\n\u2026        k = <number_of_items_to_return>,\n\u2026        exec_option = <preferred_exec_option>,\n\u2026 )\nParameters\ndataset_path (str) \u2013 \nThe full path to the dataset. Can be:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-12", "text": "dataset_path (str) \u2013 \nThe full path to the dataset. Can be:\nDeep Lake cloud path of the form hub://username/dataset_name.To write to Deep Lake cloud datasets,\nensure that you are logged in to Deep Lake\n(use \u2018activeloop login\u2019 from command line)\nAWS S3 path of the form s3://bucketname/path/to/dataset.Credentials are required in either the environment\nGoogle Cloud Storage path of the formgcs://bucketname/path/to/dataset Credentials are required\nin either the environment\nLocal file system path of the form ./path/to/dataset or~/path/to/dataset or path/to/dataset.\nIn-memory path of the form mem://path/to/dataset which doesn\u2019tsave the dataset, but keeps it in memory instead.\nShould be used only for testing as it does not persist.\ntexts (List[Document]) \u2013 List of documents to add.\nembedding (Optional[Embeddings]) \u2013 Embedding function. Defaults to None.\nNote, in other places, it is called embedding_function.\nmetadatas (Optional[List[dict]]) \u2013 List of metadatas. Defaults to None.\nids (Optional[List[str]]) \u2013 List of document IDs. Defaults to None.\n**kwargs \u2013 Additional keyword arguments.\nReturns\nDeep Lake dataset.\nReturn type\nDeepLake\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, exec_option: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nExamples:\n>>> # Search using an embedding\n>>> data = vector_store.max_marginal_relevance_search(", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-13", "text": ">>> data = vector_store.max_marginal_relevance_search(\n\u2026        query = <query_to_search>,\n\u2026        embedding_function = <embedding_function_for_query>,\n\u2026        k = <number_of_items_to_return>,\n\u2026        exec_option = <preferred_exec_option>,\n\u2026 )\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents for MMR algorithm.\nlambda_mult \u2013 Value between 0 and 1. 0 corresponds\nto maximum diversity and 1 to minimum.\nDefaults to 0.5.\nexec_option (str) \u2013 Supports 3 ways to perform searching.\n- \u201cpython\u201d - Pure-python implementation running on the client.\nCan be used for data stored anywhere. WARNING: using this\noption with big datasets is discouraged due to potential\nmemory issues.\n\u201dcompute_engine\u201d - Performant C++ implementation of the DeepLake Compute Engine. Runs on the client and can be used for\nany data stored in or connected to Deep Lake. It cannot be\nused with in-memory or local datasets.\n\u201dtensor_db\u201d - Performant, fully-hosted Managed Tensor Database.Responsible for storage and query execution. Only available\nfor data stored in the Deep Lake Managed Database. To store\ndatasets in this database, specify\nruntime = {\u201cdb_engine\u201d: True} during dataset creation.\ndeep_memory (bool) \u2013 Whether to use the Deep Memory model for improving\nsearch results. Defaults to False if deep_memory is not specified\nin the Vector Store initialization. If True, the distance metric\nis set to \u201cdeepmemory_distance\u201d, which represents the metric with\nwhich the model was trained. The search is performed using the Deep\nMemory model. If False, the distance metric is set to \u201cCOS\u201d or\nwhatever distance metric user specifies.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-14", "text": "whatever distance metric user specifies.\n**kwargs \u2013 Additional keyword arguments\nReturns\nList of Documents selected by maximal marginal relevance.\nRaises\nValueError \u2013 when MRR search is on but embedding function is\n    not specified.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, exec_option: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance. Maximal marginal\nrelevance optimizes for similarity to query AND diversity among selected docs.\nExamples:\n>>> data = vector_store.max_marginal_relevance_search_by_vector(\n\u2026        embedding=<your_embedding>,\n\u2026        fetch_k=<elements_to_fetch_before_mmr_search>,\n\u2026        k=<number_of_items_to_return>,\n\u2026        exec_option=<preferred_exec_option>,\n\u2026 )\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch for MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 determining the degree of diversity.\n0 corresponds to max diversity and 1 to min diversity. Defaults to 0.5.\nexec_option (str) \u2013 DeepLakeVectorStore supports 3 ways for searching.\nCould be \u201cpython\u201d, \u201ccompute_engine\u201d or \u201ctensor_db\u201d. Defaults to\n\u201cpython\u201d.\n- \u201cpython\u201d - Pure-python implementation running on the client.\nCan be used for data stored anywhere. WARNING: using this\noption with big datasets is discouraged due to potential\nmemory issues.\n\u201dcompute_engine\u201d - Performant C++ implementation of the DeepLake Compute Engine. Runs on the client and can be used for", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-15", "text": "any data stored in or connected to Deep Lake. It cannot be used\nwith in-memory or local datasets.\n\u201dtensor_db\u201d - Performant, fully-hosted Managed Tensor Database.Responsible for storage and query execution. Only available for\ndata stored in the Deep Lake Managed Database. To store datasets\nin this database, specify runtime = {\u201cdb_engine\u201d: True}\nduring dataset creation.\ndeep_memory (bool) \u2013 Whether to use the Deep Memory model for improving\nsearch results. Defaults to False if deep_memory is not specified\nin the Vector Store initialization. If True, the distance metric\nis set to \u201cdeepmemory_distance\u201d, which represents the metric with\nwhich the model was trained. The search is performed using the Deep\nMemory model. If False, the distance metric is set to \u201cCOS\u201d or\nwhatever distance metric user specifies.\n**kwargs \u2013 Additional keyword arguments.\nReturns\nList[Documents] - A list of documents.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nExamples\n>>> # Search using an embedding\n>>> data = vector_store.similarity_search(\n...     query=<your_query>,\n...     k=<num_items>,\n...     exec_option=<preferred_exec_option>,\n... )\n>>> # Run tql search:\n>>> data = vector_store.similarity_search(\n...     query=None,\n...     tql=\"SELECT * WHERE id == <id>\",\n...     exec_option=\"compute_engine\",\n... )\nParameters\nk (int) \u2013 Number of Documents to return. Defaults to 4.\nquery (str) \u2013 Text to look up similar documents.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-16", "text": "query (str) \u2013 Text to look up similar documents.\n**kwargs \u2013 Additional keyword arguments include:\nembedding (Callable): Embedding function to use. Defaults to None.\ndistance_metric (str): \u2018L2\u2019 for Euclidean, \u2018L1\u2019 for Nuclear, \u2018max\u2019\nfor L-infinity, \u2018cos\u2019 for cosine, \u2018dot\u2019 for dot product.\nDefaults to \u2018L2\u2019.\nfilter (Union[Dict, Callable], optional): Additional filterbefore embedding search.\n- Dict: Key-value search on tensors of htype json,\n(sample must satisfy all key-value filters)\nDict = {\u201ctensor_1\u201d: {\u201ckey\u201d: value}, \u201ctensor_2\u201d: {\u201ckey\u201d: value}}\nFunction: Compatible with deeplake.filter.\nDefaults to None.\nexec_option (str): Supports 3 ways to perform searching.\u2019python\u2019, \u2018compute_engine\u2019, or \u2018tensor_db\u2019. Defaults to \u2018python\u2019.\n- \u2018python\u2019: Pure-python implementation for the client.\nWARNING: not recommended for big datasets.\n\u2019compute_engine\u2019: C++ implementation of the Compute Engine forthe client. Not for in-memory or local datasets.\n\u2019tensor_db\u2019: Managed Tensor Database for storage and query.Only for data in Deep Lake Managed Database.\nUse runtime = {\u201cdb_engine\u201d: True} during dataset creation.\ndeep_memory (bool): Whether to use the Deep Memory model for improvingsearch results. Defaults to False if deep_memory is not specified\nin the Vector Store initialization. If True, the distance metric\nis set to \u201cdeepmemory_distance\u201d, which represents the metric with\nwhich the model was trained. The search is performed using the Deep\nMemory model. If False, the distance metric is set to \u201cCOS\u201d or\nwhatever distance metric user specifies.\nReturns\nList of Documents most similar to the query vector.\nReturn type\nList[Document]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-17", "text": "List of Documents most similar to the query vector.\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: Union[List[float], ndarray], k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nExamples\n>>> # Search using an embedding\n>>> data = vector_store.similarity_search_by_vector(\n...    embedding=<your_embedding>,\n...    k=<num_items_to_return>,\n...    exec_option=<preferred_exec_option>,\n... )\nParameters\nembedding (Union[List[float], np.ndarray]) \u2013 Embedding to find similar docs.\nk (int) \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 Additional keyword arguments including:\nfilter (Union[Dict, Callable], optional):\nAdditional filter before embedding search.\n- Dict - Key-value search on tensors of htype json. True\nif all key-value filters are satisfied.\nDict = {\u201ctensor_name_1\u201d: {\u201ckey\u201d: value},\n\u201dtensor_name_2\u201d: {\u201ckey\u201d: value}}\nFunction - Any function compatible withdeeplake.filter.\nDefaults to None.\nexec_option (str): Options for search execution include\u201dpython\u201d, \u201ccompute_engine\u201d, or \u201ctensor_db\u201d. Defaults to\n\u201cpython\u201d.\n- \u201cpython\u201d - Pure-python implementation running on the client.\nCan be used for data stored anywhere. WARNING: using this\noption with big datasets is discouraged due to potential\nmemory issues.\n\u201dcompute_engine\u201d - Performant C++ implementation of the DeepLake Compute Engine. Runs on the client and can be used for\nany data stored in or connected to Deep Lake. It cannot be\nused with in-memory or local datasets.\n\u201dtensor_db\u201d - Performant, fully-hosted Managed Tensor Database.Responsible for storage and query execution. Only available", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-18", "text": "for data stored in the Deep Lake Managed Database.\nTo store datasets in this database, specify\nruntime = {\u201cdb_engine\u201d: True} during dataset creation.\ndistance_metric (str): L2 for Euclidean, L1 for Nuclear,max for L-infinity distance, cos for cosine similarity,\n\u2018dot\u2019 for dot product. Defaults to L2.\ndeep_memory (bool): Whether to use the Deep Memory model for improvingsearch results. Defaults to False if deep_memory is not specified\nin the Vector Store initialization. If True, the distance metric\nis set to \u201cdeepmemory_distance\u201d, which represents the metric with\nwhich the model was trained. The search is performed using the Deep\nMemory model. If False, the distance metric is set to \u201cCOS\u201d or\nwhatever distance metric user specifies.\nReturns\nList of Documents most similar to the query vector.\nReturn type\nList[Document]\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with Deep Lake with distance returned.\nExamples:\n>>> data = vector_store.similarity_search_with_score(\n\u2026     query=<your_query>,", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-19", "text": ">>> data = vector_store.similarity_search_with_score(\n\u2026     query=<your_query>,\n\u2026     embedding=<your_embedding_function>\n\u2026     k=<number_of_items_to_return>,\n\u2026     exec_option=<preferred_exec_option>,\n\u2026 )\nParameters\nquery (str) \u2013 Query text to search for.\nk (int) \u2013 Number of results to return. Defaults to 4.\n**kwargs \u2013 Additional keyword arguments. Some of these arguments are:\ndistance_metric: L2 for Euclidean, L1 for Nuclear, max L-infinity\ndistance, cos for cosine similarity, \u2018dot\u2019 for dot product.\nDefaults to L2.\nfilter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.embedding_function (Callable): Embedding function to use. Defaults\nto None.\nexec_option (str): DeepLakeVectorStore supports 3 ways to performsearching. It could be either \u201cpython\u201d, \u201ccompute_engine\u201d or\n\u201ctensor_db\u201d. Defaults to \u201cpython\u201d.\n- \u201cpython\u201d - Pure-python implementation running on the client.\nCan be used for data stored anywhere. WARNING: using this\noption with big datasets is discouraged due to potential\nmemory issues.\n\u201dcompute_engine\u201d - Performant C++ implementation of the DeepLake Compute Engine. Runs on the client and can be used for\nany data stored in or connected to Deep Lake. It cannot be used\nwith in-memory or local datasets.\n\u201dtensor_db\u201d - Performant, fully-hosted Managed Tensor Database.Responsible for storage and query execution. Only available for\ndata stored in the Deep Lake Managed Database. To store datasets\nin this database, specify runtime = {\u201cdb_engine\u201d: True}\nduring dataset creation.\ndeep_memory (bool): Whether to use the Deep Memory model for improvingsearch results. Defaults to False if deep_memory is not specified", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "a81728c93802-20", "text": "in the Vector Store initialization. If True, the distance metric\nis set to \u201cdeepmemory_distance\u201d, which represents the metric with\nwhich the model was trained. The search is performed using the Deep\nMemory model. If False, the distance metric is set to \u201cCOS\u201d or\nwhatever distance metric user specifies.\nReturns\nList of documents most similar to the querytext with distance in float.\nReturn type\nList[Tuple[Document, float]]\nExamples using DeepLake\u00b6\nActiveloop Deep Lake\nAnalysis of Twitter the-algorithm source code with LangChain, GPT4 and Activeloop\u2019s Deep Lake\nUse LangChain, GPT and Activeloop\u2019s Deep Lake to work with code base\nQA using Activeloop\u2019s DeepLake\nDeep Lake", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.deeplake.DeepLake.html"}
{"id": "11c02fe49fb4-0", "text": "langchain.vectorstores.redis.filters.RedisFilterExpression\u00b6\nclass langchain.vectorstores.redis.filters.RedisFilterExpression(_filter: Optional[str] = None, operator: Optional[RedisFilterOperator] = None, left: Optional[RedisFilterExpression] = None, right: Optional[RedisFilterExpression] = None)[source]\u00b6\nA logical expression of RedisFilterFields.\nRedisFilterExpressions can be combined using the & and | operators to create\ncomplex logical expressions that evaluate to the Redis Query language.\nThis presents an interface by which users can create complex queries\nwithout having to know the Redis Query language.\nFilter expressions are not initialized directly. Instead they are built\nby combining RedisFilterFields using the & and | operators.\nExamples\n>>> from langchain.vectorstores.redis import RedisTag, RedisNum\n>>> brand_is_nike = RedisTag(\"brand\") == \"nike\"\n>>> price_is_under_100 = RedisNum(\"price\") < 100\n>>> filter = brand_is_nike & price_is_under_100\n>>> print(str(filter))\n(@brand:{nike} @price:[-inf (100)])\nMethods\n__init__([_filter,\u00a0operator,\u00a0left,\u00a0right])\n__init__(_filter: Optional[str] = None, operator: Optional[RedisFilterOperator] = None, left: Optional[RedisFilterExpression] = None, right: Optional[RedisFilterExpression] = None)[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.filters.RedisFilterExpression.html"}
{"id": "8d37689a5587-0", "text": "langchain.vectorstores.elasticsearch.ElasticsearchStore\u00b6\nclass langchain.vectorstores.elasticsearch.ElasticsearchStore(index_name: str, *, embedding: ~typing.Optional[~langchain.schema.embeddings.Embeddings] = None, es_connection: ~typing.Optional[Elasticsearch] = None, es_url: ~typing.Optional[str] = None, es_cloud_id: ~typing.Optional[str] = None, es_user: ~typing.Optional[str] = None, es_api_key: ~typing.Optional[str] = None, es_password: ~typing.Optional[str] = None, vector_query_field: str = 'vector', query_field: str = 'text', distance_strategy: ~typing.Optional[~typing.Literal[<DistanceStrategy.COSINE: 'COSINE'>, <DistanceStrategy.DOT_PRODUCT: 'DOT_PRODUCT'>, <DistanceStrategy.EUCLIDEAN_DISTANCE: 'EUCLIDEAN_DISTANCE'>]] = None, strategy: ~langchain.vectorstores.elasticsearch.BaseRetrievalStrategy = <langchain.vectorstores.elasticsearch.ApproxRetrievalStrategy object>)[source]\u00b6\nElasticsearch vector store.\nExample\nfrom langchain.vectorstores import ElasticsearchStore\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nvectorstore = ElasticsearchStore(\n    embedding=OpenAIEmbeddings(),\n    index_name=\"langchain-demo\",\n    es_url=\"http://localhost:9200\"\n)\nParameters\nindex_name \u2013 Name of the Elasticsearch index to create.\nes_url \u2013 URL of the Elasticsearch instance to connect to.\ncloud_id \u2013 Cloud ID of the Elasticsearch instance to connect to.\nes_user \u2013 Username to use when connecting to Elasticsearch.\nes_password \u2013 Password to use when connecting to Elasticsearch.\nes_api_key \u2013 API key to use when connecting to Elasticsearch.\nes_connection \u2013 Optional pre-existing Elasticsearch connection.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-1", "text": "es_connection \u2013 Optional pre-existing Elasticsearch connection.\nvector_query_field \u2013 Optional. Name of the field to store\nthe embedding vectors in.\nquery_field \u2013 Optional. Name of the field to store the texts in.\nstrategy \u2013 Optional. Retrieval strategy to use when searching the index.\nDefaults to ApproxRetrievalStrategy. Can be one of\nExactRetrievalStrategy, ApproxRetrievalStrategy,\nor SparseRetrievalStrategy.\ndistance_strategy \u2013 Optional. Distance strategy to use when\nsearching the index.\nDefaults to COSINE. Can be one of COSINE,\nEUCLIDEAN_DISTANCE, or DOT_PRODUCT.\nIf you want to use a cloud hosted Elasticsearch instance, you can pass in the\ncloud_id argument instead of the es_url argument.\nExample\nfrom langchain.vectorstores import ElasticsearchStore\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nvectorstore = ElasticsearchStore(\n    embedding=OpenAIEmbeddings(),\n    index_name=\"langchain-demo\",\n    es_cloud_id=\"<cloud_id>\"\n    es_user=\"elastic\",\n    es_password=\"<password>\"\n)\nYou can also connect to an existing Elasticsearch instance by passing in a\npre-existing Elasticsearch connection via the es_connection argument.\nExample\nfrom langchain.vectorstores import ElasticsearchStore\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom elasticsearch import Elasticsearch\nes_connection = Elasticsearch(\"http://localhost:9200\")\nvectorstore = ElasticsearchStore(\n    embedding=OpenAIEmbeddings(),\n    index_name=\"langchain-demo\",\n    es_connection=es_connection\n)\nElasticsearchStore by default uses the ApproxRetrievalStrategy, which uses the\nHNSW algorithm to perform approximate nearest neighbor search. This is the\nfastest and most memory efficient algorithm.\nIf you want to use the Brute force / Exact strategy for searching vectors, you", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-2", "text": "If you want to use the Brute force / Exact strategy for searching vectors, you\ncan pass in the ExactRetrievalStrategy to the ElasticsearchStore constructor.\nExample\nfrom langchain.vectorstores import ElasticsearchStore\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nvectorstore = ElasticsearchStore(\n    embedding=OpenAIEmbeddings(),\n    index_name=\"langchain-demo\",\n    es_url=\"http://localhost:9200\",\n    strategy=ElasticsearchStore.ExactRetrievalStrategy()\n)\nBoth strategies require that you know the similarity metric you want to use\nwhen creating the index. The default is cosine similarity, but you can also\nuse dot product or euclidean distance.\nExample\nfrom langchain.vectorstores import ElasticsearchStore\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom langchain.vectorstores.utils import DistanceStrategy\nvectorstore = ElasticsearchStore(\n    embedding=OpenAIEmbeddings(),\n    index_name=\"langchain-demo\",\n    es_url=\"http://localhost:9200\",\n    distance_strategy=\"DOT_PRODUCT\"\n)\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\nApproxRetrievalStrategy([query_model_id,\u00a0...])\nUsed to perform approximate nearest neighbor search using the HNSW algorithm.\nExactRetrievalStrategy()\nUsed to perform brute force / exact nearest neighbor search via script_score.\nSparseVectorRetrievalStrategy([model_id])\nUsed to perform sparse vector search via text_expansion.\n__init__(index_name,\u00a0*[,\u00a0embedding,\u00a0...])\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-3", "text": "add_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_embeddings(text_embeddings[,\u00a0metadatas,\u00a0...])\nAdd the given texts and embeddings to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0...])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\nconnect_to_elasticsearch(*[,\u00a0es_url,\u00a0...])\ndelete([ids,\u00a0refresh_indices])\nDelete documents from the Elasticsearch index.\nfrom_documents(documents[,\u00a0embedding,\u00a0...])\nConstruct ElasticsearchStore wrapper from documents.\nfrom_texts(texts[,\u00a0embedding,\u00a0metadatas,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-4", "text": "from_texts(texts[,\u00a0embedding,\u00a0metadatas,\u00a0...])\nConstruct ElasticsearchStore wrapper from raw documents.\nget_user_agent()\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0fetch_k,\u00a0filter])\nReturn Elasticsearch documents most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_by_vector_with_relevance_scores(...)\nReturn Elasticsearch documents most similar to query, along with scores.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nReturn Elasticsearch documents most similar to query, along with scores.\nstatic ApproxRetrievalStrategy(query_model_id: Optional[str] = None, hybrid: Optional[bool] = False, rrf: Optional[Union[dict, bool]] = True) \u2192 ApproxRetrievalStrategy[source]\u00b6\nUsed to perform approximate nearest neighbor search\nusing the HNSW algorithm.\nAt build index time, this strategy will create a\ndense vector field in the index and store the\nembedding vectors in the index.\nAt query time, the text will either be embedded using the\nprovided embedding function or the query_model_id\nwill be used to embed the text using the model\ndeployed to Elasticsearch.\nif query_model_id is used, do not provide an embedding function.\nParameters\nquery_model_id \u2013 Optional. ID of the model to use to\nembed the query text within the stack. Requires", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-5", "text": "embed the query text within the stack. Requires\nembedding model to be deployed to Elasticsearch.\nhybrid \u2013 Optional. If True, will perform a hybrid search\nusing both the knn query and a text query.\nDefaults to False.\nrrf \u2013 Optional. rrf is Reciprocal Rank Fusion.\nWhen hybrid is True,\nand rrf is True, then rrf: {}.\nand rrf is False, then rrf is omitted.\nand isinstance(rrf, dict) is True, then pass in the dict values.\nrrf could be passed for adjusting \u2018rank_constant\u2019 and \u2018window_size\u2019.\nstatic ExactRetrievalStrategy() \u2192 ExactRetrievalStrategy[source]\u00b6\nUsed to perform brute force / exact\nnearest neighbor search via script_score.\nstatic SparseVectorRetrievalStrategy(model_id: Optional[str] = None) \u2192 SparseRetrievalStrategy[source]\u00b6\nUsed to perform sparse vector search via text_expansion.\nUsed for when you want to use ELSER model to perform document search.\nAt build index time, this strategy will create a pipeline that\nwill embed the text using the ELSER model and store the\nresulting tokens in the index.\nAt query time, the text will be embedded using the ELSER\nmodel and the resulting tokens will be used to\nperform a text_expansion query.\nParameters\nmodel_id \u2013 Optional. Default is \u201c.elser_model_1\u201d.\nID of the model to use to embed the query text\nwithin the stack. Requires embedding model to be\ndeployed to Elasticsearch.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-6", "text": "within the stack. Requires embedding model to be\ndeployed to Elasticsearch.\n__init__(index_name: str, *, embedding: ~typing.Optional[~langchain.schema.embeddings.Embeddings] = None, es_connection: ~typing.Optional[Elasticsearch] = None, es_url: ~typing.Optional[str] = None, es_cloud_id: ~typing.Optional[str] = None, es_user: ~typing.Optional[str] = None, es_api_key: ~typing.Optional[str] = None, es_password: ~typing.Optional[str] = None, vector_query_field: str = 'vector', query_field: str = 'text', distance_strategy: ~typing.Optional[~typing.Literal[<DistanceStrategy.COSINE: 'COSINE'>, <DistanceStrategy.DOT_PRODUCT: 'DOT_PRODUCT'>, <DistanceStrategy.EUCLIDEAN_DISTANCE: 'EUCLIDEAN_DISTANCE'>]] = None, strategy: ~langchain.vectorstores.elasticsearch.BaseRetrievalStrategy = <langchain.vectorstores.elasticsearch.ApproxRetrievalStrategy object>)[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-7", "text": "(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_embeddings(text_embeddings: Iterable[Tuple[str, List[float]]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, refresh_indices: bool = True, create_index_if_not_exists: bool = True, bulk_kwargs: Optional[Dict] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd the given texts and embeddings to the vectorstore.\nParameters\ntext_embeddings \u2013 Iterable pairs of string and embedding to\nadd to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of unique IDs.\nrefresh_indices \u2013 Whether to refresh the Elasticsearch indices\nafter adding the texts.\ncreate_index_if_not_exists \u2013 Whether to create the Elasticsearch\nindex if it doesn\u2019t already exist.\n*bulk_kwargs \u2013 Additional arguments to pass to Elasticsearch bulk.\n- chunk_size: Optional. Number of texts to add to the\nindex at a time. Defaults to 500.\nReturns\nList of ids from adding the texts into the vectorstore.\nadd_texts(texts: Iterable[str], metadatas: Optional[List[Dict[Any, Any]]] = None, ids: Optional[List[str]] = None, refresh_indices: bool = True, create_index_if_not_exists: bool = True, bulk_kwargs: Optional[Dict] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of ids to associate with the texts.\nrefresh_indices \u2013 Whether to refresh the Elasticsearch indices", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-8", "text": "refresh_indices \u2013 Whether to refresh the Elasticsearch indices\nafter adding the texts.\ncreate_index_if_not_exists \u2013 Whether to create the Elasticsearch\nindex if it doesn\u2019t already exist.\n*bulk_kwargs \u2013 Additional arguments to pass to Elasticsearch bulk.\n- chunk_size: Optional. Number of texts to add to the\nindex at a time. Defaults to 500.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-9", "text": "as_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-10", "text": "docsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-11", "text": "Run similarity search with distance asynchronously.\nstatic connect_to_elasticsearch(*, es_url: Optional[str] = None, cloud_id: Optional[str] = None, api_key: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None) \u2192 Elasticsearch[source]\u00b6\ndelete(ids: Optional[List[str]] = None, refresh_indices: Optional[bool] = True, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete documents from the Elasticsearch index.\nParameters\nids \u2013 List of ids of documents to delete.\nrefresh_indices \u2013 Whether to refresh the index\nafter deleting documents. Defaults to True.\nclassmethod from_documents(documents: List[Document], embedding: Optional[Embeddings] = None, bulk_kwargs: Optional[Dict] = None, **kwargs: Any) \u2192 ElasticsearchStore[source]\u00b6\nConstruct ElasticsearchStore wrapper from documents.\nExample\nfrom langchain.vectorstores import ElasticsearchStore\nfrom langchain.embeddings.openai import OpenAIEmbeddings\ndb = ElasticsearchStore.from_documents(\n    texts,\n    embeddings,\n    index_name=\"langchain-demo\",\n    es_url=\"http://localhost:9200\"\n)\nParameters\ntexts \u2013 List of texts to add to the Elasticsearch index.\nembedding \u2013 Embedding function to use to embed the texts.\nDo not provide if using a strategy\nthat doesn\u2019t require inference.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nindex_name \u2013 Name of the Elasticsearch index to create.\nes_url \u2013 URL of the Elasticsearch instance to connect to.\ncloud_id \u2013 Cloud ID of the Elasticsearch instance to connect to.\nes_user \u2013 Username to use when connecting to Elasticsearch.\nes_password \u2013 Password to use when connecting to Elasticsearch.\nes_api_key \u2013 API key to use when connecting to Elasticsearch.\nes_connection \u2013 Optional pre-existing Elasticsearch connection.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-12", "text": "es_connection \u2013 Optional pre-existing Elasticsearch connection.\nvector_query_field \u2013 Optional. Name of the field\nto store the embedding vectors in.\nquery_field \u2013 Optional. Name of the field to store the texts in.\nbulk_kwargs \u2013 Optional. Additional arguments to pass to\nElasticsearch bulk.\nclassmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[Dict[str, Any]]] = None, bulk_kwargs: Optional[Dict] = None, **kwargs: Any) \u2192 ElasticsearchStore[source]\u00b6\nConstruct ElasticsearchStore wrapper from raw documents.\nExample\nfrom langchain.vectorstores import ElasticsearchStore\nfrom langchain.embeddings.openai import OpenAIEmbeddings\ndb = ElasticsearchStore.from_texts(\n    texts,\n    // embeddings optional if using\n    // a strategy that doesn't require inference\n    embeddings,\n    index_name=\"langchain-demo\",\n    es_url=\"http://localhost:9200\"\n)\nParameters\ntexts \u2013 List of texts to add to the Elasticsearch index.\nembedding \u2013 Embedding function to use to embed the texts.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nindex_name \u2013 Name of the Elasticsearch index to create.\nes_url \u2013 URL of the Elasticsearch instance to connect to.\ncloud_id \u2013 Cloud ID of the Elasticsearch instance to connect to.\nes_user \u2013 Username to use when connecting to Elasticsearch.\nes_password \u2013 Password to use when connecting to Elasticsearch.\nes_api_key \u2013 API key to use when connecting to Elasticsearch.\nes_connection \u2013 Optional pre-existing Elasticsearch connection.\nvector_query_field \u2013 Optional. Name of the field to\nstore the embedding vectors in.\nquery_field \u2013 Optional. Name of the field to store the texts in.\ndistance_strategy \u2013 Optional. Name of the distance\nstrategy to use. Defaults to \u201cCOSINE\u201d.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-13", "text": "strategy to use. Defaults to \u201cCOSINE\u201d.\ncan be one of \u201cCOSINE\u201d,\n\u201cEUCLIDEAN_DISTANCE\u201d, \u201cDOT_PRODUCT\u201d.\nbulk_kwargs \u2013 Optional. Additional arguments to pass to\nElasticsearch bulk.\nstatic get_user_agent() \u2192 str[source]\u00b6\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, fields: Optional[List[str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversityamong selected documents.\nParameters\nquery (str) \u2013 Text to look up documents similar to.\nk (int) \u2013 Number of Documents to return. Defaults to 4.\nfetch_k (int) \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult (float) \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfields \u2013 Other fields to get from elasticsearch source. These fields\nwill be added to the document metadata.\nReturns\nA list of Documents selected by maximal marginal relevance.\nReturn type\nList[Document]\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-14", "text": "k \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, fetch_k: int = 50, filter: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn Elasticsearch documents most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k (int) \u2013 Number of Documents to fetch to pass to knn num_candidates.\nfilter \u2013 Array of Elasticsearch filter clauses to apply to the query.\nReturns\nList of Documents most similar to the query,\nin descending order of similarity.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_by_vector_with_relevance_scores(embedding: List[float], k: int = 4, filter: Optional[List[Dict]] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn Elasticsearch documents most similar to query, along with scores.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "8d37689a5587-15", "text": "Return Elasticsearch documents most similar to query, along with scores.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Array of Elasticsearch filter clauses to apply to the query.\nReturns\nList of Documents most similar to the embedding and score for each\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn Elasticsearch documents most similar to query, along with scores.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Array of Elasticsearch filter clauses to apply to the query.\nReturns\nList of Documents most similar to the query and score for each\nExamples using ElasticsearchStore\u00b6\nElasticsearch\nIndexing", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ElasticsearchStore.html"}
{"id": "1fc5e8e9327a-0", "text": "langchain.vectorstores.starrocks.has_mul_sub_str\u00b6\nlangchain.vectorstores.starrocks.has_mul_sub_str(s: str, *args: Any) \u2192 bool[source]\u00b6\nCheck if a string has multiple substrings.\n:param s: The string to check\n:param *args: The substrings to check for in the string\nReturns\nTrue if all substrings are present in the string, False otherwise\nReturn type\nbool", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.has_mul_sub_str.html"}
{"id": "5996468194e5-0", "text": "langchain.vectorstores.sklearn.ParquetSerializer\u00b6\nclass langchain.vectorstores.sklearn.ParquetSerializer(persist_path: str)[source]\u00b6\nSerializes data in Apache Parquet format using the pyarrow package.\nMethods\n__init__(persist_path)\nextension()\nThe file extension suggested by this serializer (without dot).\nload()\nLoads the data from the persist_path\nsave(data)\nSaves the data to the persist_path\n__init__(persist_path: str) \u2192 None[source]\u00b6\nclassmethod extension() \u2192 str[source]\u00b6\nThe file extension suggested by this serializer (without dot).\nload() \u2192 Any[source]\u00b6\nLoads the data from the persist_path\nsave(data: Any) \u2192 None[source]\u00b6\nSaves the data to the persist_path", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.ParquetSerializer.html"}
{"id": "b27397df202a-0", "text": "langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever\u00b6\nclass langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever[source]\u00b6\nBases: BaseRetriever\nRetriever that uses Azure Cognitive Search.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam k: int = 4\u00b6\nNumber of documents to return.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam search_type: str = 'hybrid'\u00b6\nType of search to perform. Options are \u201csimilarity\u201d, \u201chybrid\u201d,\n\u201csemantic_hybrid\u201d.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam vectorstore: langchain.vectorstores.azuresearch.AzureSearch [Required]\u00b6\nAzure Search instance used to find similar documents.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html"}
{"id": "b27397df202a-1", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html"}
{"id": "b27397df202a-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html"}
{"id": "b27397df202a-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html"}
{"id": "b27397df202a-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html"}
{"id": "b27397df202a-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html"}
{"id": "b27397df202a-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html"}
{"id": "b27397df202a-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html"}
{"id": "b27397df202a-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html"}
{"id": "b27397df202a-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.azuresearch.AzureSearchVectorStoreRetriever.html"}
{"id": "cd32967808bb-0", "text": "langchain.vectorstores.zep.ZepVectorStore\u00b6\nclass langchain.vectorstores.zep.ZepVectorStore(collection_name: str, api_url: str, *, api_key: Optional[str] = None, config: Optional[CollectionConfig] = None, embedding: Optional[Embeddings] = None)[source]\u00b6\nZep vector store.\nIt provides methods for adding texts or documents to the store,\nsearching for similar documents, and deleting documents.\nSearch scores are calculated using cosine similarity normalized to [0, 1].\nParameters\napi_url (str) \u2013 The URL of the Zep API.\ncollection_name (str) \u2013 The name of the collection in the Zep store.\napi_key (Optional[str]) \u2013 The API key for the Zep API.\nconfig (Optional[CollectionConfig]) \u2013 The configuration for the collection.\nRequired if the collection does not already exist.\nembedding (Optional[Embeddings]) \u2013 Optional embedding function to use to\nembed the texts. Required if the collection is not auto-embedded.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(collection_name,\u00a0api_url,\u00a0*[,\u00a0...])\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas,\u00a0document_ids])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0document_ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zep.ZepVectorStore.html"}
{"id": "cd32967808bb-1", "text": "Return VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type[,\u00a0metadata,\u00a0k])\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k,\u00a0metadata])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs most similar to query.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by Zep vector UUIDs.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts[,\u00a0embedding,\u00a0metadatas,\u00a0...])\nClass method that returns a ZepVectorStore instance initialized from texts.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type[,\u00a0metadata,\u00a0k])\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0metadata])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zep.ZepVectorStore.html"}
{"id": "cd32967808bb-2", "text": "similarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nRun similarity search with distance.\n__init__(collection_name: str, api_url: str, *, api_key: Optional[str] = None, config: Optional[CollectionConfig] = None, embedding: Optional[Embeddings] = None) \u2192 None[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[Dict[str, Any]]] = None, document_ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[Dict[str, Any]]] = None, document_ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zep.ZepVectorStore.html"}
{"id": "cd32967808bb-3", "text": "Run more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\ndocument_ids \u2013 Optional list of document ids associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zep.ZepVectorStore.html"}
{"id": "cd32967808bb-4", "text": "Return docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zep.ZepVectorStore.html"}
{"id": "cd32967808bb-5", "text": ")\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, metadata: Optional[Dict[str, Any]] = None, k: int = 3, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDelete by Zep vector UUIDs.\nParameters\nids (Optional[List[str]]) \u2013 The UUIDs of the vectors to delete.\nRaises\nValueError \u2013 If no UUIDs are provided.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zep.ZepVectorStore.html"}
{"id": "cd32967808bb-6", "text": "Raises\nValueError \u2013 If no UUIDs are provided.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, collection_name: str = '', api_url: str = '', api_key: Optional[str] = None, config: Optional[CollectionConfig] = None, **kwargs: Any) \u2192 ZepVectorStore[source]\u00b6\nClass method that returns a ZepVectorStore instance initialized from texts.\nIf the collection does not exist, it will be created.\nParameters\ntexts (List[str]) \u2013 The list of texts to add to the vectorstore.\nembedding (Optional[Embeddings]) \u2013 Optional embedding function to use to\nembed the texts.\nmetadatas (Optional[List[Dict[str, Any]]]) \u2013 Optional list of metadata\nassociated with the texts.\ncollection_name (str) \u2013 The name of the collection in the Zep store.\napi_url (str) \u2013 The URL of the Zep API.\napi_key (Optional[str]) \u2013 The API key for the Zep API.\nconfig (Optional[CollectionConfig]) \u2013 The configuration for the collection.\n**kwargs \u2013 Additional parameters specific to the vectorstore.\nReturns\nAn instance of ZepVectorStore.\nReturn type\nZepVectorStore\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zep.ZepVectorStore.html"}
{"id": "cd32967808bb-7", "text": "Maximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nZep determines this automatically and this parameter is\nignored.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nmetadata \u2013 Optional, metadata to filter the resulting set of retrieved docs\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nZep determines this automatically and this parameter is\nignored.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nmetadata \u2013 Optional, metadata to filter the resulting set of retrieved docs\nReturns\nList of Documents selected by maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zep.ZepVectorStore.html"}
{"id": "cd32967808bb-8", "text": "Returns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, metadata: Optional[Dict[str, Any]] = None, k: int = 3, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nmetadata \u2013 Optional, metadata filter\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zep.ZepVectorStore.html"}
{"id": "cd32967808bb-9", "text": "Run similarity search with distance.\nExamples using ZepVectorStore\u00b6\nZep", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zep.ZepVectorStore.html"}
{"id": "2f690b24f704-0", "text": "langchain.vectorstores.redis.schema.HNSWVectorField\u00b6\nclass langchain.vectorstores.redis.schema.HNSWVectorField[source]\u00b6\nBases: RedisVectorField\nSchema for HNSW vector fields in Redis.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam algorithm: Literal['HNSW'] = 'HNSW'\u00b6\nparam datatype: str = 'FLOAT32'\u00b6\nparam dims: int [Required]\u00b6\nparam distance_metric: langchain.vectorstores.redis.schema.RedisDistanceMetric = 'COSINE'\u00b6\nparam ef_construction: int = 200\u00b6\nparam ef_runtime: int = 10\u00b6\nparam epsilon: float = 0.01\u00b6\nparam initial_cap: Optional[int] = None\u00b6\nparam m: int = 16\u00b6\nparam name: str [Required]\u00b6\nas_field() \u2192 VectorField[source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.HNSWVectorField.html"}
{"id": "2f690b24f704-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.HNSWVectorField.html"}
{"id": "2f690b24f704-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.HNSWVectorField.html"}
{"id": "4a213e7da035-0", "text": "langchain.vectorstores.myscale.MyScaleSettings\u00b6\nclass langchain.vectorstores.myscale.MyScaleSettings[source]\u00b6\nBases: BaseSettings\nMyScale client configuration.\nAttribute:\nmyscale_host (str)An URL to connect to MyScale backend.Defaults to \u2018localhost\u2019.\nmyscale_port (int) : URL port to connect with HTTP. Defaults to 8443.\nusername (str) : Username to login. Defaults to None.\npassword (str) : Password to login. Defaults to None.\nindex_type (str): index type string.\nindex_param (dict): index build parameter.\ndatabase (str) : Database name to find the table. Defaults to \u2018default\u2019.\ntable (str) : Table name to operate on.\nDefaults to \u2018vector_table\u2019.\nmetric (str)Metric to compute distance,supported are (\u2018L2\u2019, \u2018Cosine\u2019, \u2018IP\u2019). Defaults to \u2018Cosine\u2019.\ncolumn_map (Dict)Column type map to project column name onto langchainsemantics. Must have keys: text, id, vector,\nmust be same size to number of columns. For example:\n.. code-block:: python\n{\u2018id\u2019: \u2018text_id\u2019,\n\u2018vector\u2019: \u2018text_embedding\u2019,\n\u2018text\u2019: \u2018text_plain\u2019,\n\u2018metadata\u2019: \u2018metadata_dictionary_in_json\u2019,\n}\nDefaults to identity map.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam column_map: Dict[str, str] = {'id': 'id', 'metadata': 'metadata', 'text': 'text', 'vector': 'vector'}\u00b6\nparam database: str = 'default'\u00b6\nparam host: str = 'localhost'\u00b6\nparam index_param: Optional[Dict[str, str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScaleSettings.html"}
{"id": "4a213e7da035-1", "text": "param index_param: Optional[Dict[str, str]] = None\u00b6\nparam index_type: str = 'MSTG'\u00b6\nparam metric: str = 'Cosine'\u00b6\nparam password: Optional[str] = None\u00b6\nparam port: int = 8443\u00b6\nparam table: str = 'langchain'\u00b6\nparam username: Optional[str] = None\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScaleSettings.html"}
{"id": "4a213e7da035-2", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using MyScaleSettings\u00b6\nMyScale", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScaleSettings.html"}
{"id": "1c70d9fa6250-0", "text": "langchain.vectorstores.vectara.VectaraRetriever\u00b6\nclass langchain.vectorstores.vectara.VectaraRetriever[source]\u00b6\nBases: VectorStoreRetriever\nRetriever class for Vectara.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam search_kwargs: dict [Optional]\u00b6\nSearch params.\nk: Number of Documents to return. Defaults to 5.\nlambda_val: lexical match parameter for hybrid search.\nfilter: Dictionary of argument(s) to filter on metadata. For example a\nfilter can be \u201cdoc.rating > 3.0 and part.lang = \u2018deu\u2019\u201d} see\nhttps://docs.vectara.com/docs/search-apis/sql/filter-overview\nfor more details.\nn_sentence_context: number of sentences before/after the matching segment to add\nparam search_type: str = 'similarity'\u00b6\nType of search to perform. Defaults to \u201csimilarity\u201d.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam vectorstore: Vectara [Required]\u00b6\nVectara vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.VectaraRetriever.html"}
{"id": "1c70d9fa6250-1", "text": "param vectorstore: Vectara [Required]\u00b6\nVectara vectorstore.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nAdd documents to vectorstore.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nAdd documents to vectorstore.\nadd_texts(texts: List[str], metadatas: Optional[List[dict]] = None, doc_metadata: Optional[dict] = None) \u2192 None[source]\u00b6\nAdd text to the Vectara vectorstore.\nParameters\ntexts (List[str]) \u2013 The text\nmetadatas (List[dict]) \u2013 Metadata dicts, must line up with existing store\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.VectaraRetriever.html"}
{"id": "1c70d9fa6250-2", "text": "and passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.VectaraRetriever.html"}
{"id": "1c70d9fa6250-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.VectaraRetriever.html"}
{"id": "1c70d9fa6250-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.VectaraRetriever.html"}
{"id": "1c70d9fa6250-5", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.VectaraRetriever.html"}
{"id": "1c70d9fa6250-6", "text": "and passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.VectaraRetriever.html"}
{"id": "1c70d9fa6250-7", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.VectaraRetriever.html"}
{"id": "1c70d9fa6250-8", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.VectaraRetriever.html"}
{"id": "1c70d9fa6250-9", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nallowed_search_types: ClassVar[Collection[str]] = ('similarity', 'similarity_score_threshold', 'mmr')\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using VectaraRetriever\u00b6\nChat Over Documents with Vectara", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.VectaraRetriever.html"}
{"id": "d44672069156-0", "text": "langchain.vectorstores.vectara.Vectara\u00b6\nclass langchain.vectorstores.vectara.Vectara(vectara_customer_id: Optional[str] = None, vectara_corpus_id: Optional[str] = None, vectara_api_key: Optional[str] = None, vectara_api_timeout: int = 60, source: str = 'langchain')[source]\u00b6\nVectara API vector store.\nSee (https://vectara.com).\nExample\nfrom langchain.vectorstores import Vectara\nvectorstore = Vectara(\n    vectara_customer_id=vectara_customer_id,\n    vectara_corpus_id=vectara_corpus_id,\n    vectara_api_key=vectara_api_key\n)\nInitialize with Vectara API.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__([vectara_customer_id,\u00a0...])\nInitialize with Vectara API.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_files(files_list[,\u00a0metadatas])\nVectara provides a way to add documents directly via our API where pre-processing and chunking occurs internally in an optimal way This method provides a way to use that API in LangChain\nadd_texts(texts[,\u00a0metadatas,\u00a0doc_metadata])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.Vectara.html"}
{"id": "d44672069156-1", "text": "afrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_files(files[,\u00a0embedding,\u00a0metadatas])\nConstruct Vectara wrapper from raw documents.\nfrom_texts(texts[,\u00a0embedding,\u00a0metadatas])\nConstruct Vectara wrapper from raw documents.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0lambda_val,\u00a0...])\nReturn Vectara documents most similar to query, along with scores.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.Vectara.html"}
{"id": "d44672069156-2", "text": "Return Vectara documents most similar to query, along with scores.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nReturn Vectara documents most similar to query, along with scores.\n__init__(vectara_customer_id: Optional[str] = None, vectara_corpus_id: Optional[str] = None, vectara_api_key: Optional[str] = None, vectara_api_timeout: int = 60, source: str = 'langchain')[source]\u00b6\nInitialize with Vectara API.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_files(files_list: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nVectara provides a way to add documents directly via our API where", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.Vectara.html"}
{"id": "d44672069156-3", "text": "Vectara provides a way to add documents directly via our API where\npre-processing and chunking occurs internally in an optimal way\nThis method provides a way to use that API in LangChain\nParameters\nfiles_list \u2013 Iterable of strings, each representing a local file path.\nFiles could be text, HTML, PDF, markdown, doc/docx, ppt/pptx, etc.\nsee API docs for full list\nmetadatas \u2013 Optional list of metadatas associated with each file\nReturns\nList of ids associated with each of the files indexed\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, doc_metadata: Optional[dict] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\ndoc_metadata \u2013 optional metadata for the document\nThis function indexes all the input text strings in the Vectara corpus as a\nsingle Vectara document, where each input text is considered a \u201csection\u201d and the\nmetadata are associated with each section.\nif \u2018doc_metadata\u2019 is provided, it is associated with the Vectara document.\nReturns\ndocument ID of the document added\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.Vectara.html"}
{"id": "d44672069156-4", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectaraRetriever[source]\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.Vectara.html"}
{"id": "d44672069156-5", "text": "Return type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.Vectara.html"}
{"id": "d44672069156-6", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_files(files: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 Vectara[source]\u00b6\nConstruct Vectara wrapper from raw documents.\nThis is intended to be a quick way to get started.\n.. rubric:: Example\nfrom langchain.vectorstores import Vectara\nvectara = Vectara.from_files(\n    files_list,\n    vectara_customer_id=customer_id,\n    vectara_corpus_id=corpus_id,\n    vectara_api_key=api_key,\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.Vectara.html"}
{"id": "d44672069156-7", "text": "vectara_api_key=api_key,\n)\nclassmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 Vectara[source]\u00b6\nConstruct Vectara wrapper from raw documents.\nThis is intended to be a quick way to get started.\n.. rubric:: Example\nfrom langchain.vectorstores import Vectara\nvectara = Vectara.from_texts(\n    texts,\n    vectara_customer_id=customer_id,\n    vectara_corpus_id=corpus_id,\n    vectara_api_key=api_key,\n)\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.Vectara.html"}
{"id": "d44672069156-8", "text": "Maximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 5, lambda_val: float = 0.025, filter: Optional[str] = None, n_sentence_context: int = 2, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn Vectara documents most similar to query, along with scores.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 5.\nfilter \u2013 Dictionary of argument(s) to filter on metadata. For example a\nfilter can be \u201cdoc.rating > 3.0 and part.lang = \u2018deu\u2019\u201d} see\nhttps://docs.vectara.com/docs/search-apis/sql/filter-overview for more\ndetails.\nn_sentence_context \u2013 number of sentences before/after the matching segment\nto add, defaults to 2\nReturns\nList of Documents most similar to the query\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.Vectara.html"}
{"id": "d44672069156-9", "text": "Parameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 5, lambda_val: float = 0.025, filter: Optional[str] = None, score_threshold: Optional[float] = None, n_sentence_context: int = 2, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn Vectara documents most similar to query, along with scores.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 5.\nlambda_val \u2013 lexical match parameter for hybrid search.\nfilter \u2013 Dictionary of argument(s) to filter on metadata. For example a\nfilter can be \u201cdoc.rating > 3.0 and part.lang = \u2018deu\u2019\u201d} see\nhttps://docs.vectara.com/docs/search-apis/sql/filter-overview\nfor more details.\nscore_threshold \u2013 minimal score threshold for the result.\nIf defined, results with score less than this value will be\nfiltered out.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.Vectara.html"}
{"id": "d44672069156-10", "text": "If defined, results with score less than this value will be\nfiltered out.\nn_sentence_context \u2013 number of sentences before/after the matching segment\nto add, defaults to 2\nReturns\nList of Documents most similar to the query and score for each.\nExamples using Vectara\u00b6\nVectara\nChat Over Documents with Vectara\nVectara Text Generation", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vectara.Vectara.html"}
{"id": "eea659590e98-0", "text": "langchain.vectorstores.neo4j_vector.Neo4jVector\u00b6\nclass langchain.vectorstores.neo4j_vector.Neo4jVector(embedding: Embeddings, *, search_type: SearchType = SearchType.VECTOR, username: Optional[str] = None, password: Optional[str] = None, url: Optional[str] = None, keyword_index_name: Optional[str] = 'keyword', database: str = 'neo4j', index_name: str = 'vector', node_label: str = 'Chunk', embedding_node_property: str = 'embedding', text_node_property: str = 'text', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, logger: Optional[Logger] = None, pre_delete_collection: bool = False, retrieval_query: str = '', relevance_score_fn: Optional[Callable[[float], float]] = None)[source]\u00b6\nNeo4j vector index.\nTo use, you should have the neo4j python package installed.\nParameters\nurl \u2013 Neo4j connection url\nusername \u2013 Neo4j username.\npassword \u2013 Neo4j password\ndatabase \u2013 Optionally provide Neo4j database\nDefaults to \u201cneo4j\u201d\nembedding \u2013 Any embedding function implementing\nlangchain.embeddings.base.Embeddings interface.\ndistance_strategy \u2013 The distance strategy to use. (default: COSINE)\npre_delete_collection \u2013 If True, will delete existing data if it exists.\n(default: False). Useful for testing.\nExample\nfrom langchain.vectorstores.neo4j_vector import Neo4jVector\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nurl=\"bolt://localhost:7687\"\nusername=\"neo4j\"\npassword=\"pleaseletmein\"\nembeddings = OpenAIEmbeddings()\nvectorestore = Neo4jVector.from_documents(\n    embedding=embeddings,\n    documents=docs,\n    url=url\n    username=username,", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "eea659590e98-1", "text": "documents=docs,\n    url=url\n    username=username,\n    password=password,\n)\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding,\u00a0*[,\u00a0search_type,\u00a0...])\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_embeddings(texts,\u00a0embeddings[,\u00a0...])\nAdd embeddings to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "eea659590e98-2", "text": "Return docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ncreate_new_index()\nThis method constructs a Cypher query and executes it to create a new vector index in Neo4j.\ncreate_new_keyword_index([text_node_properties])\nThis method constructs a Cypher query and executes it to create a new full text index in Neo4j.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding[,\u00a0...])\nReturn Neo4jVector initialized from documents and embeddings.\nfrom_embeddings(text_embeddings,\u00a0embedding)\nConstruct Neo4jVector wrapper from raw documents and pre- generated embeddings.\nfrom_existing_graph(embedding,\u00a0node_label,\u00a0...)\nInitialize and return a Neo4jVector instance from an existing graph.\nfrom_existing_index(embedding,\u00a0index_name[,\u00a0...])\nGet instance of an existing Neo4j vector index.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn Neo4jVector initialized from texts and embeddings.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nquery(query,\u00a0*[,\u00a0params])\nThis method sends a Cypher query to the connected Neo4j database and returns the results as a list of dictionaries.\nretrieve_existing_fts_index([...])\nCheck if the fulltext index exists in the Neo4j database\nretrieve_existing_index()\nCheck if the vector index exists in the Neo4j database and returns its embedding dimension.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "eea659590e98-3", "text": "Check if the vector index exists in the Neo4j database and returns its embedding dimension.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nRun similarity search with Neo4jVector.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_with_score_by_vector(embedding)\nPerform a similarity search in the Neo4j database using a given vector and return the top k similar documents with their scores.\nverify_version()\nCheck if the connected Neo4j database version supports vector indexing.\n__init__(embedding: Embeddings, *, search_type: SearchType = SearchType.VECTOR, username: Optional[str] = None, password: Optional[str] = None, url: Optional[str] = None, keyword_index_name: Optional[str] = 'keyword', database: str = 'neo4j', index_name: str = 'vector', node_label: str = 'Chunk', embedding_node_property: str = 'embedding', text_node_property: str = 'text', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, logger: Optional[Logger] = None, pre_delete_collection: bool = False, retrieval_query: str = '', relevance_score_fn: Optional[Callable[[float], float]] = None) \u2192 None[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "eea659590e98-4", "text": "(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_embeddings(texts: Iterable[str], embeddings: List[List[float]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd embeddings to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nembeddings \u2013 List of list of embedding vectors.\nmetadatas \u2013 List of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "eea659590e98-5", "text": "Delete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "eea659590e98-6", "text": "score_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "eea659590e98-7", "text": "Return docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ncreate_new_index() \u2192 None[source]\u00b6\nThis method constructs a Cypher query and executes it\nto create a new vector index in Neo4j.\ncreate_new_keyword_index(text_node_properties: List[str] = []) \u2192 None[source]\u00b6\nThis method constructs a Cypher query and executes it\nto create a new full text index in Neo4j.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "eea659590e98-8", "text": "False otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Neo4jVector[source]\u00b6\nReturn Neo4jVector initialized from documents and embeddings.\nNeo4j credentials are required in the form of url, username,\nand password and optional database parameters.\nclassmethod from_embeddings(text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) \u2192 Neo4jVector[source]\u00b6\nConstruct Neo4jVector wrapper from raw documents and pre-\ngenerated embeddings.\nReturn Neo4jVector initialized from documents and embeddings.\nNeo4j credentials are required in the form of url, username,\nand password and optional database parameters.\nExample\nfrom langchain.vectorstores.neo4j_vector import Neo4jVector\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\ntext_embeddings = embeddings.embed_documents(texts)\ntext_embedding_pairs = list(zip(texts, text_embeddings))\nvectorstore = Neo4jVector.from_embeddings(\n    text_embedding_pairs, embeddings)\nclassmethod from_existing_graph(embedding: Embeddings, node_label: str, embedding_node_property: str, text_node_properties: List[str], *, keyword_index_name: Optional[str] = 'keyword', index_name: str = 'vector', search_type: SearchType = SearchType.VECTOR, retrieval_query: str = '', **kwargs: Any) \u2192 Neo4jVector[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "eea659590e98-9", "text": "Initialize and return a Neo4jVector instance from an existing graph.\nThis method initializes a Neo4jVector instance using the provided\nparameters and the existing graph. It validates the existence of\nthe indices and creates new ones if they don\u2019t exist.\nReturns:\nNeo4jVector: An instance of Neo4jVector initialized with the provided parameters\nand existing graph.\nExample:\n>>> neo4j_vector = Neo4jVector.from_existing_graph(\n\u2026     embedding=my_embedding,\n\u2026     node_label=\u201dDocument\u201d,\n\u2026     embedding_node_property=\u201dembedding\u201d,\n\u2026     text_node_properties=[\u201ctitle\u201d, \u201ccontent\u201d]\n\u2026 )\nNote:\nNeo4j credentials are required in the form of url, username, and password,\nand optional database parameters passed as additional keyword arguments.\nclassmethod from_existing_index(embedding: Embeddings, index_name: str, search_type: SearchType = SearchType.VECTOR, keyword_index_name: Optional[str] = None, **kwargs: Any) \u2192 Neo4jVector[source]\u00b6\nGet instance of an existing Neo4j vector index. This method will\nreturn the instance of the store without inserting any new\nembeddings.\nNeo4j credentials are required in the form of url, username,\nand password and optional database parameters along with\nthe index_name definition.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Neo4jVector[source]\u00b6\nReturn Neo4jVector initialized from texts and embeddings.\nNeo4j credentials are required in the form of url, username,\nand password and optional database parameters.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "eea659590e98-10", "text": "and password and optional database parameters.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nquery(query: str, *, params: Optional[dict] = None) \u2192 List[Dict[str, Any]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "eea659590e98-11", "text": "This method sends a Cypher query to the connected Neo4j database\nand returns the results as a list of dictionaries.\nParameters\nquery (str) \u2013 The Cypher query to execute.\nparams (dict, optional) \u2013 Dictionary of query parameters. Defaults to {}.\nReturns\nList of dictionaries containing the query results.\nReturn type\nList[Dict[str, Any]]\nretrieve_existing_fts_index(text_node_properties: List[str] = []) \u2192 Optional[str][source]\u00b6\nCheck if the fulltext index exists in the Neo4j database\nThis method queries the Neo4j database for existing fts indexes\nwith the specified name.\nReturns\nkeyword index information\nReturn type\n(Tuple)\nretrieve_existing_index() \u2192 Optional[int][source]\u00b6\nCheck if the vector index exists in the Neo4j database\nand returns its embedding dimension.\nThis method queries the Neo4j database for existing indexes\nand attempts to retrieve the dimension of the vector index\nwith the specified name. If the index exists, its dimension is returned.\nIf the index doesn\u2019t exist, None is returned.\nReturns\nThe embedding dimension of the existing index if found.\nReturn type\nint or None\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRun similarity search with Neo4jVector.\nParameters\nquery (str) \u2013 Query text to search for.\nk (int) \u2013 Number of results to return. Defaults to 4.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "eea659590e98-12", "text": "Return docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query and score for each\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPerform a similarity search in the Neo4j database using a\ngiven vector and return the top k similar documents with their scores.\nThis method uses a Cypher query to find the top k documents that\nare most similar to a given embedding. The similarity is measured\nusing a vector index in the Neo4j database. The results are returned\nas a list of tuples, each containing a Document object and\nits similarity score.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "eea659590e98-13", "text": "as a list of tuples, each containing a Document object and\nits similarity score.\nParameters\nembedding (List[float]) \u2013 The embedding vector to compare against.\nk (int, optional) \u2013 The number of top similar documents to retrieve.\nReturns\nA list of tuples, each containinga Document object and its similarity score.\nReturn type\nList[Tuple[Document, float]]\nverify_version() \u2192 None[source]\u00b6\nCheck if the connected Neo4j database version supports vector indexing.\nQueries the Neo4j database to retrieve its version and compares it\nagainst a target version (5.11.0) that is known to support vector\nindexing. Raises a ValueError if the connected Neo4j version is\nnot supported.\nExamples using Neo4jVector\u00b6\nNeo4j\nNeo4j Vector Index", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.Neo4jVector.html"}
{"id": "cea776ab14d8-0", "text": "langchain.vectorstores.redis.base.Redis\u00b6\nclass langchain.vectorstores.redis.base.Redis(redis_url: str, index_name: str, embedding: Embeddings, index_schema: Optional[Union[Dict[str, str], str, PathLike]] = None, vector_schema: Optional[Dict[str, Union[int, str]]] = None, relevance_score_fn: Optional[Callable[[float], float]] = None, key_prefix: Optional[str] = None, **kwargs: Any)[source]\u00b6\nRedis vector database.\nTo use, you should have the redis python package installed\nand have a running Redis Enterprise or Redis-Stack server\nFor production use cases, it is recommended to use Redis Enterprise\nas the scaling, performance, stability and availability is much\nbetter than Redis-Stack.\nFor testing and prototyping, however, this is not required.\nRedis-Stack is available as a docker container the full vector\nsearch API available.\n# to run redis stack in docker locally\ndocker run -d -p 6379:6379 -p 8001:8001 redis/redis-stack:latest\nOnce running, you can connect to the redis server with the following url schemas:\n- redis://<host>:<port> # simple connection\n- redis://<username>:<password>@<host>:<port> # connection with authentication\n- rediss://<host>:<port> # connection with SSL\n- rediss://<username>:<password>@<host>:<port> # connection with SSL and auth\nExamples:\nThe following examples show various ways to use the Redis VectorStore with\nLangChain.\nFor all the following examples assume we have the following imports:\nfrom langchain.vectorstores import Redis\nfrom langchain.embeddings import OpenAIEmbeddings\nInitialize, create index, and load Documentsfrom langchain.vectorstores import Redis\nfrom langchain.embeddings import OpenAIEmbeddings", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-1", "text": "from langchain.embeddings import OpenAIEmbeddings\nrds = Redis.from_documents(\n    documents, # a list of Document objects from loaders or created\n    embeddings, # an Embeddings object\n    redis_url=\"redis://localhost:6379\",\n)\nInitialize, create index, and load Documents with metadatards = Redis.from_texts(\n    texts, # a list of strings\n    metadata, # a list of metadata dicts\n    embeddings, # an Embeddings object\n    redis_url=\"redis://localhost:6379\",\n)\nInitialize, create index, and load Documents with metadata and return keys\nrds, keys = Redis.from_texts_return_keys(\n    texts, # a list of strings\n    metadata, # a list of metadata dicts\n    embeddings, # an Embeddings object\n    redis_url=\"redis://localhost:6379\",\n)\nFor use cases where the index needs to stay alive, you can initialize\nwith an index name such that it\u2019s easier to reference later\nrds = Redis.from_texts(\n    texts, # a list of strings\n    metadata, # a list of metadata dicts\n    embeddings, # an Embeddings object\n    index_name=\"my-index\",\n    redis_url=\"redis://localhost:6379\",\n)\nInitialize and connect to an existing index (from above)\nrds = Redis.from_existing_index(\n    embeddings, # an Embeddings object\n    index_name=\"my-index\",\n    redis_url=\"redis://localhost:6379\",\n)\nAdvanced examples:\nCustom vector schema can be supplied to change the way that\nRedis creates the underlying vector schema. This is useful\nfor production use cases where you want to optimize the\nvector schema for your use case. ex. using HNSW instead of\nFLAT (knn) which is the default\nvector_schema = {", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-2", "text": "FLAT (knn) which is the default\nvector_schema = {\n    \"algorithm\": \"HNSW\"\n}\nrds = Redis.from_texts(\n    texts, # a list of strings\n    metadata, # a list of metadata dicts\n    embeddings, # an Embeddings object\n    vector_schema=vector_schema,\n    redis_url=\"redis://localhost:6379\",\n)\nCustom index schema can be supplied to change the way that the\nmetadata is indexed. This is useful for you would like to use the\nhybrid querying (filtering) capability of Redis.\nBy default, this implementation will automatically generate the index\nschema according to the following rules:\nAll strings are indexed as text fields\nAll numbers are indexed as numeric fields\nAll lists of strings are indexed as tag fields (joined bylangchain.vectorstores.redis.constants.REDIS_TAG_SEPARATOR)\nAll None values are not indexed but still stored in Redis these arenot retrievable through the interface here, but the raw Redis client\ncan be used to retrieve them.\nAll other types are not indexed\nTo override these rules, you can pass in a custom index schema like the following\ntag:\n    - name: credit_score\ntext:\n    - name: user\n    - name: job\nTypically, the credit_score field would be a text field since it\u2019s a string,\nhowever, we can override this behavior by specifying the field type as shown with\nthe yaml config (can also be a dictionary) above and the code below.\nrds = Redis.from_texts(\n    texts, # a list of strings\n    metadata, # a list of metadata dicts\n    embeddings, # an Embeddings object\n    index_schema=\"path/to/index_schema.yaml\", # can also be a dictionary\n    redis_url=\"redis://localhost:6379\",\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-3", "text": "redis_url=\"redis://localhost:6379\",\n)\nWhen connecting to an existing index where a custom schema has been applied, it\u2019s\nimportant to pass in the same schema to the from_existing_index method.\nOtherwise, the schema for newly added samples will be incorrect and metadata\nwill not be returned.\nInitialize with necessary components.\nAttributes\nDEFAULT_VECTOR_SCHEMA\nembeddings\nAccess the query embedding object if available.\nschema\nReturn the schema of the index.\nMethods\n__init__(redis_url,\u00a0index_name,\u00a0embedding[,\u00a0...])\nInitialize with necessary components.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0embeddings,\u00a0...])\nAdd more texts to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-4", "text": "asimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete a Redis entry.\ndrop_index(index_name,\u00a0delete_documents,\u00a0...)\nDrop a Redis search index.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_existing_index(embedding,\u00a0index_name,\u00a0...)\nConnect to an existing Redis index.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreate a Redis vectorstore from a list of texts.\nfrom_texts_return_keys(texts,\u00a0embedding[,\u00a0...])\nCreate a Redis vectorstore from raw documents.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter,\u00a0...])\nRun similarity search\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nRun similarity search between a query vector and the indexed vectors.\nsimilarity_search_limit_score(query[,\u00a0k,\u00a0...])\n[Deprecated]  Returns the most similar indexed documents to the query text within the score_threshold range.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-5", "text": "Return docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nRun similarity search with vector distance.\nwrite_schema(path)\nWrite the schema to a yaml file.\n__init__(redis_url: str, index_name: str, embedding: Embeddings, index_schema: Optional[Union[Dict[str, str], str, PathLike]] = None, vector_schema: Optional[Dict[str, Union[int, str]]] = None, relevance_score_fn: Optional[Callable[[float], float]] = None, key_prefix: Optional[str] = None, **kwargs: Any)[source]\u00b6\nInitialize with necessary components.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, embeddings: Optional[List[List[float]]] = None, batch_size: int = 1000, clean_metadata: bool = True, **kwargs: Any) \u2192 List[str][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-6", "text": "Add more texts to the vectorstore.\nParameters\ntexts (Iterable[str]) \u2013 Iterable of strings/text to add to the vectorstore.\nmetadatas (Optional[List[dict]], optional) \u2013 Optional list of metadatas.\nDefaults to None.\nembeddings (Optional[List[List[float]]], optional) \u2013 Optional pre-generated\nembeddings. Defaults to None.\nkeys (List[str]) or ids (List[str]) \u2013 Identifiers of entries.\nDefaults to None.\nbatch_size (int, optional) \u2013 Batch size to use for writes. Defaults to 1000.\nReturns\nList of ids added to the vectorstore\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-7", "text": "Return docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 RedisVectorStoreRetriever[source]\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-8", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-9", "text": "Returns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\nstatic delete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 bool[source]\u00b6\nDelete a Redis entry.\nParameters\nids \u2013 List of ids (keys in redis) to delete.\nredis_url \u2013 Redis connection url. This should be passed in the kwargs\nor set as an environment variable: REDIS_URL.\nReturns\nWhether or not the deletions were successful.\nReturn type\nbool\nRaises\nValueError \u2013 If the redis python package is not installed.\nValueError \u2013 If the ids (keys in redis) are not provided\nstatic drop_index(index_name: str, delete_documents: bool, **kwargs: Any) \u2192 bool[source]\u00b6\nDrop a Redis search index.\nParameters\nindex_name (str) \u2013 Name of the index to drop.\ndelete_documents (bool) \u2013 Whether to drop the associated documents.\nReturns\nWhether or not the drop was successful.\nReturn type\nbool\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_existing_index(embedding: Embeddings, index_name: str, schema: Union[Dict[str, str], str, PathLike], **kwargs: Any) \u2192 Redis[source]\u00b6\nConnect to an existing Redis index.\nExample\nfrom langchain.vectorstores import Redis\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nredisearch = Redis.from_existing_index(\n    embeddings,\n    index_name=\"my-index\",\n    redis_url=\"redis://username:password@localhost:6379\"\n)\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-10", "text": "redis_url=\"redis://username:password@localhost:6379\"\n)\nParameters\nembedding (Embeddings) \u2013 Embedding model class (i.e. OpenAIEmbeddings)\nfor embedding queries.\nindex_name (str) \u2013 Name of the index to connect to.\nschema (Union[Dict[str, str], str, os.PathLike]) \u2013 Schema of the index\nand the vector schema. Can be a dict, or path to yaml file\n**kwargs (Any) \u2013 Additional keyword arguments to pass to the Redis client.\nReturns\nRedis VectorStore instance.\nReturn type\nRedis\nRaises\nValueError \u2013 If the index does not exist.\nImportError \u2013 If the redis python package is not installed.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, index_name: Optional[str] = None, index_schema: Optional[Union[Dict[str, str], str, PathLike]] = None, vector_schema: Optional[Dict[str, Union[int, str]]] = None, **kwargs: Any) \u2192 Redis[source]\u00b6\nCreate a Redis vectorstore from a list of texts.\nThis is a user-friendly interface that:\nEmbeds documents.\nCreates a new Redis index if it doesn\u2019t already exist\nAdds the documents to the newly created Redis index.\nThis method will generate schema based on the metadata passed in\nif the index_schema is not defined. If the index_schema is defined,\nit will compare against the generated schema and warn if there are\ndifferences. If you are purposefully defining the schema for the\nmetadata, then you can ignore that warning.\nTo examine the schema options, initialize an instance of this class\nand print out the schema using the Redis.schema` property. This\nwill include the content and content_vector classes which are\nalways present in the langchain schema.\nExample", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-11", "text": "always present in the langchain schema.\nExample\nfrom langchain.vectorstores import Redis\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nredisearch = RediSearch.from_texts(\n    texts,\n    embeddings,\n    redis_url=\"redis://username:password@localhost:6379\"\n)\nParameters\ntexts (List[str]) \u2013 List of texts to add to the vectorstore.\nembedding (Embeddings) \u2013 Embedding model class (i.e. OpenAIEmbeddings)\nfor embedding queries.\nmetadatas (Optional[List[dict]], optional) \u2013 Optional list of metadata dicts\nto add to the vectorstore. Defaults to None.\nindex_name (Optional[str], optional) \u2013 Optional name of the index to create\nor add to. Defaults to None.\nindex_schema (Optional[Union[Dict[str, str], str, os.PathLike]], optional) \u2013 Optional fields to index within the metadata. Overrides generated\nschema. Defaults to None.\nvector_schema (Optional[Dict[str, Union[str, int]]], optional) \u2013 Optional\nvector schema to use. Defaults to None.\n**kwargs (Any) \u2013 Additional keyword arguments to pass to the Redis client.\nReturns\nRedis VectorStore instance.\nReturn type\nRedis\nRaises\nValueError \u2013 If the number of metadatas does not match the number of texts.\nImportError \u2013 If the redis python package is not installed.\nclassmethod from_texts_return_keys(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, index_name: Optional[str] = None, index_schema: Optional[Union[Dict[str, str], str, PathLike]] = None, vector_schema: Optional[Dict[str, Union[int, str]]] = None, **kwargs: Any) \u2192 Tuple[Redis, List[str]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-12", "text": "Create a Redis vectorstore from raw documents.\nThis is a user-friendly interface that:\nEmbeds documents.\nCreates a new Redis index if it doesn\u2019t already exist\nAdds the documents to the newly created Redis index.\nReturns the keys of the newly created documents once stored.\nThis method will generate schema based on the metadata passed in\nif the index_schema is not defined. If the index_schema is defined,\nit will compare against the generated schema and warn if there are\ndifferences. If you are purposefully defining the schema for the\nmetadata, then you can ignore that warning.\nTo examine the schema options, initialize an instance of this class\nand print out the schema using the Redis.schema` property. This\nwill include the content and content_vector classes which are\nalways present in the langchain schema.\nExample\nfrom langchain.vectorstores import Redis\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nredis, keys = Redis.from_texts_return_keys(\n    texts,\n    embeddings,\n    redis_url=\"redis://localhost:6379\"\n)\nParameters\ntexts (List[str]) \u2013 List of texts to add to the vectorstore.\nembedding (Embeddings) \u2013 Embeddings to use for the vectorstore.\nmetadatas (Optional[List[dict]], optional) \u2013 Optional list of metadata\ndicts to add to the vectorstore. Defaults to None.\nindex_name (Optional[str], optional) \u2013 Optional name of the index to\ncreate or add to. Defaults to None.\nindex_schema (Optional[Union[Dict[str, str], str, os.PathLike]], optional) \u2013 Optional fields to index within the metadata. Overrides generated\nschema. Defaults to None.\nvector_schema (Optional[Dict[str, Union[str, int]]], optional) \u2013 Optional\nvector schema to use. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-13", "text": "vector schema to use. Defaults to None.\n**kwargs (Any) \u2013 Additional keyword arguments to pass to the Redis client.\nReturns\nTuple of the Redis instance and the keys ofthe newly created documents.\nReturn type\nTuple[Redis, List[str]]\nRaises\nValueError \u2013 If the number of metadatas does not match the number of texts.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[RedisFilterExpression] = None, return_metadata: bool = True, distance_threshold: Optional[float] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversityamong selected documents.\nParameters\nquery (str) \u2013 Text to look up documents similar to.\nk (int) \u2013 Number of Documents to return. Defaults to 4.\nfetch_k (int) \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult (float) \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nfilter (RedisFilterExpression, optional) \u2013 Optional metadata filter.\nDefaults to None.\nreturn_metadata (bool, optional) \u2013 Whether to return metadata.\nDefaults to True.\ndistance_threshold (Optional[float], optional) \u2013 Maximum vector distance\nbetween selected documents and the query vector. Defaults to None.\nReturns\nA list of Documents selected by maximal marginal relevance.\nReturn type\nList[Document]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-14", "text": "A list of Documents selected by maximal marginal relevance.\nReturn type\nList[Document]\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[RedisFilterExpression] = None, return_metadata: bool = True, distance_threshold: Optional[float] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRun similarity search\nParameters\nquery (str) \u2013 The query text for which to find similar documents.\nk (int) \u2013 The number of documents to return. Default is 4.\nfilter (RedisFilterExpression, optional) \u2013 Optional metadata filter.\nDefaults to None.\nreturn_metadata (bool, optional) \u2013 Whether to return metadata.\nDefaults to True.\ndistance_threshold (Optional[float], optional) \u2013 Maximum vector distance\nbetween selected documents and the query vector. Defaults to None.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-15", "text": "between selected documents and the query vector. Defaults to None.\nReturns\nA list of documents that are most similar to the querytext.\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[RedisFilterExpression] = None, return_metadata: bool = True, distance_threshold: Optional[float] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRun similarity search between a query vector and the indexed vectors.\nParameters\nembedding (List[float]) \u2013 The query vector for which to find similar\ndocuments.\nk (int) \u2013 The number of documents to return. Default is 4.\nfilter (RedisFilterExpression, optional) \u2013 Optional metadata filter.\nDefaults to None.\nreturn_metadata (bool, optional) \u2013 Whether to return metadata.\nDefaults to True.\ndistance_threshold (Optional[float], optional) \u2013 Maximum vector distance\nbetween selected documents and the query vector. Defaults to None.\nReturns\nA list of documents that are most similar to the querytext.\nReturn type\nList[Document]\nsimilarity_search_limit_score(query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any) \u2192 List[Document][source]\u00b6\n[Deprecated]  Returns the most similar indexed documents to the query text within the\nscore_threshold range.\nDeprecated: Use similarity_search with distance_threshold instead.\nParameters\nquery (str) \u2013 The query text for which to find similar documents.\nk (int) \u2013 The number of documents to return. Default is 4.\nscore_threshold (float) \u2013 The minimum matching distance required\nfor a document to be considered a match. Defaults to 0.2.\nReturns\nA list of documents that are most similar to the query textincluding the match score for each document.\nReturn type", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-16", "text": "Return type\nList[Document]\nNote\nIf there are no documents that satisfy the score_threshold value,\nan empty list is returned.[Deprecated] Returns the most similar indexed documents to the query text within the\nscore_threshold range.\nDeprecated: Use similarity_search with distance_threshold instead.\nParameters\nquery (str) \u2013 The query text for which to find similar documents.\nk (int) \u2013 The number of documents to return. Default is 4.\nscore_threshold (float) \u2013 The minimum matching distance required\nfor a document to be considered a match. Defaults to 0.2.\nReturns\nA list of documents that are most similar to the query textincluding the match score for each document.\nReturn type\nList[Document]\nNote\nIf there are no documents that satisfy the score_threshold value,\nan empty list is returned.\nNotes\nDeprecated since version 0.0.272: Use similarity_search(distance_threshold=0.1) instead.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[RedisFilterExpression] = None, return_metadata: bool = True, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with vector distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "cea776ab14d8-17", "text": "Run similarity search with vector distance.\nThe \u201cscores\u201d returned from this function are the raw vector\ndistances from the query vector. For similarity scores, use\nsimilarity_search_with_relevance_scores.\nParameters\nquery (str) \u2013 The query text for which to find similar documents.\nk (int) \u2013 The number of documents to return. Default is 4.\nfilter (RedisFilterExpression, optional) \u2013 Optional metadata filter.\nDefaults to None.\nreturn_metadata (bool, optional) \u2013 Whether to return metadata.\nDefaults to True.\nReturns\nA list of documents that aremost similar to the query with the distance for each document.\nReturn type\nList[Tuple[Document, float]]\nwrite_schema(path: Union[str, PathLike]) \u2192 None[source]\u00b6\nWrite the schema to a yaml file.\nExamples using Redis\u00b6\nRedis", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.Redis.html"}
{"id": "79af04d6b4c4-0", "text": "langchain.vectorstores.faiss.dependable_faiss_import\u00b6\nlangchain.vectorstores.faiss.dependable_faiss_import(no_avx2: Optional[bool] = None) \u2192 Any[source]\u00b6\nImport faiss if available, otherwise raise error.\nIf FAISS_NO_AVX2 environment variable is set, it will be considered\nto load FAISS with no AVX2 optimization.\nParameters\nno_avx2 \u2013 Load FAISS strictly with no AVX2 optimization\nso that the vectorstore is portable and compatible with other devices.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.dependable_faiss_import.html"}
{"id": "ee643b10728f-0", "text": "langchain.vectorstores.myscale.has_mul_sub_str\u00b6\nlangchain.vectorstores.myscale.has_mul_sub_str(s: str, *args: Any) \u2192 bool[source]\u00b6\nCheck if a string contains multiple substrings.\n:param s: string to check.\n:param *args: substrings to check.\nReturns\nTrue if all substrings are in the string, False otherwise.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.has_mul_sub_str.html"}
{"id": "e0630fb4e4a2-0", "text": "langchain.vectorstores.annoy.Annoy\u00b6\nclass langchain.vectorstores.annoy.Annoy(embedding_function: Callable, index: Any, metric: str, docstore: Docstore, index_to_docstore_id: Dict[int, str])[source]\u00b6\nAnnoy vector store.\nTo use, you should have the annoy python package installed.\nExample\nfrom langchain.vectorstores import Annoy\ndb = Annoy(embedding_function, index, docstore, index_to_docstore_id)\nInitialize with necessary components.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding_function,\u00a0index,\u00a0metric,\u00a0...)\nInitialize with necessary components.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.Annoy.html"}
{"id": "e0630fb4e4a2-1", "text": "asearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_embeddings(text_embeddings,\u00a0embedding)\nConstruct Annoy wrapper from embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nConstruct Annoy wrapper from raw documents.\nload_local(folder_path,\u00a0embeddings)\nLoad Annoy index, docstore, and index_to_docstore_id to disk.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nprocess_index_results(idxs,\u00a0dists)\nTurns annoy results into a list of documents and scores.\nsave_local(folder_path[,\u00a0prefault])\nSave Annoy index, docstore, and index_to_docstore_id to disk.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0search_k])\nReturn docs most similar to query.\nsimilarity_search_by_index(docstore_index[,\u00a0...])\nReturn docs most similar to docstore_index.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.Annoy.html"}
{"id": "e0630fb4e4a2-2", "text": "Return docs most similar to docstore_index.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nReturn docs most similar to query.\nsimilarity_search_with_score_by_index(...[,\u00a0...])\nReturn docs most similar to query.\nsimilarity_search_with_score_by_vector(embedding)\nReturn docs most similar to query.\n__init__(embedding_function: Callable, index: Any, metric: str, docstore: Docstore, index_to_docstore_id: Dict[int, str])[source]\u00b6\nInitialize with necessary components.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.Annoy.html"}
{"id": "e0630fb4e4a2-3", "text": "Run more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.Annoy.html"}
{"id": "e0630fb4e4a2-4", "text": "Return VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.Annoy.html"}
{"id": "e0630fb4e4a2-5", "text": "docsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.Annoy.html"}
{"id": "e0630fb4e4a2-6", "text": "False otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_embeddings(text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, metric: str = 'angular', trees: int = 100, n_jobs: int = - 1, **kwargs: Any) \u2192 Annoy[source]\u00b6\nConstruct Annoy wrapper from embeddings.\nParameters\ntext_embeddings \u2013 List of tuples of (text, embedding)\nembedding \u2013 Embedding function to use.\nmetadatas \u2013 List of metadata dictionaries to associate with documents.\nmetric \u2013 Metric to use for indexing. Defaults to \u201cangular\u201d.\ntrees \u2013 Number of trees to use for indexing. Defaults to 100.\nn_jobs \u2013 Number of jobs to use for indexing. Defaults to -1\nThis is a user friendly interface that:\nCreates an in memory docstore with provided embeddings\nInitializes the Annoy database\nThis is intended to be a quick way to get started.\nExample\nfrom langchain.vectorstores import Annoy\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\ntext_embeddings = embeddings.embed_documents(texts)\ntext_embedding_pairs = list(zip(texts, text_embeddings))\ndb = Annoy.from_embeddings(text_embedding_pairs, embeddings)\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, metric: str = 'angular', trees: int = 100, n_jobs: int = - 1, **kwargs: Any) \u2192 Annoy[source]\u00b6\nConstruct Annoy wrapper from raw documents.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.Annoy.html"}
{"id": "e0630fb4e4a2-7", "text": "Construct Annoy wrapper from raw documents.\nParameters\ntexts \u2013 List of documents to index.\nembedding \u2013 Embedding function to use.\nmetadatas \u2013 List of metadata dictionaries to associate with documents.\nmetric \u2013 Metric to use for indexing. Defaults to \u201cangular\u201d.\ntrees \u2013 Number of trees to use for indexing. Defaults to 100.\nn_jobs \u2013 Number of jobs to use for indexing. Defaults to -1.\nThis is a user friendly interface that:\nEmbeds documents.\nCreates an in memory docstore\nInitializes the Annoy database\nThis is intended to be a quick way to get started.\nExample\nfrom langchain.vectorstores import Annoy\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nindex = Annoy.from_texts(texts, embeddings)\nclassmethod load_local(folder_path: str, embeddings: Embeddings) \u2192 Annoy[source]\u00b6\nLoad Annoy index, docstore, and index_to_docstore_id to disk.\nParameters\nfolder_path \u2013 folder path to load index, docstore,\nand index_to_docstore_id from.\nembeddings \u2013 Embeddings to use when generating queries.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.Annoy.html"}
{"id": "e0630fb4e4a2-8", "text": "of diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nk \u2013 Number of Documents to return. Defaults to 4.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nprocess_index_results(idxs: List[int], dists: List[float]) \u2192 List[Tuple[Document, float]][source]\u00b6\nTurns annoy results into a list of documents and scores.\nParameters\nidxs \u2013 List of indices of the documents in the index.\ndists \u2013 List of distances of the documents in the index.\nReturns\nList of Documents and scores.\nsave_local(folder_path: str, prefault: bool = False) \u2192 None[source]\u00b6\nSave Annoy index, docstore, and index_to_docstore_id to disk.\nParameters\nfolder_path \u2013 folder path to save index, docstore,\nand index_to_docstore_id to.\nprefault \u2013 Whether to pre-load the index into memory.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.Annoy.html"}
{"id": "e0630fb4e4a2-9", "text": "prefault \u2013 Whether to pre-load the index into memory.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, search_k: int = - 1, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nsearch_k \u2013 inspect up to search_k nodes which defaults\nto n_trees * n if not provided\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_index(docstore_index: int, k: int = 4, search_k: int = - 1, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to docstore_index.\nParameters\ndocstore_index \u2013 Index of document in docstore\nk \u2013 Number of Documents to return. Defaults to 4.\nsearch_k \u2013 inspect up to search_k nodes which defaults\nto n_trees * n if not provided\nReturns\nList of Documents most similar to the embedding.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, search_k: int = - 1, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nsearch_k \u2013 inspect up to search_k nodes which defaults\nto n_trees * n if not provided\nReturns\nList of Documents most similar to the embedding.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.Annoy.html"}
{"id": "e0630fb4e4a2-10", "text": "Returns\nList of Documents most similar to the embedding.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, search_k: int = - 1) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nsearch_k \u2013 inspect up to search_k nodes which defaults\nto n_trees * n if not provided\nReturns\nList of Documents most similar to the query and score for each\nsimilarity_search_with_score_by_index(docstore_index: int, k: int = 4, search_k: int = - 1) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nsearch_k \u2013 inspect up to search_k nodes which defaults\nto n_trees * n if not provided\nReturns\nList of Documents most similar to the query and score for each", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.Annoy.html"}
{"id": "e0630fb4e4a2-11", "text": "Returns\nList of Documents most similar to the query and score for each\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, search_k: int = - 1) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nsearch_k \u2013 inspect up to search_k nodes which defaults\nto n_trees * n if not provided\nReturns\nList of Documents most similar to the query and score for each\nExamples using Annoy\u00b6\nAnnoy", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.Annoy.html"}
{"id": "fe874c9f6d9e-0", "text": "langchain.vectorstores.annoy.dependable_annoy_import\u00b6\nlangchain.vectorstores.annoy.dependable_annoy_import() \u2192 Any[source]\u00b6\nImport annoy if available, otherwise raise error.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.annoy.dependable_annoy_import.html"}
{"id": "a0c9ff5a5b9e-0", "text": "langchain.vectorstores.myscale.MyScaleWithoutJSON\u00b6\nclass langchain.vectorstores.myscale.MyScaleWithoutJSON(embedding: Embeddings, config: Optional[MyScaleSettings] = None, must_have_cols: List[str] = [], **kwargs: Any)[source]\u00b6\nMyScale vector store without metadata column\nThis is super handy if you are working to a SQL-native table\nBuilding a myscale vector store without metadata column\nembedding (Embeddings): embedding model\nconfig (MyScaleSettings): Configuration to MyScale Client\nmust_have_cols (List[str]): column names to be included in query\nOther keyword arguments will pass into\n[clickhouse-connect](https://docs.myscale.com/)\nAttributes\nembeddings\nAccess the query embedding object if available.\nmetadata_column\nMethods\n__init__(embedding[,\u00a0config,\u00a0must_have_cols])\nBuilding a myscale vector store without metadata column\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0batch_size,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScaleWithoutJSON.html"}
{"id": "a0c9ff5a5b9e-1", "text": "amax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids,\u00a0where_str])\nDelete by vector ID or other criteria.\ndrop()\nHelper function: Drop data\nescape_str(value)\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreate Myscale wrapper with existing texts\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0where_str])\nPerform a similarity search with MyScale\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nPerform a similarity search with MyScale by vectors\nsimilarity_search_with_relevance_scores(query)\nPerform a similarity search with MyScale\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScaleWithoutJSON.html"}
{"id": "a0c9ff5a5b9e-2", "text": "similarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\n__init__(embedding: Embeddings, config: Optional[MyScaleSettings] = None, must_have_cols: List[str] = [], **kwargs: Any) \u2192 None[source]\u00b6\nBuilding a myscale vector store without metadata column\nembedding (Embeddings): embedding model\nconfig (MyScaleSettings): Configuration to MyScale Client\nmust_have_cols (List[str]): column names to be included in query\nOther keyword arguments will pass into\n[clickhouse-connect](https://docs.myscale.com/)\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, batch_size: int = 32, ids: Optional[Iterable[str]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScaleWithoutJSON.html"}
{"id": "a0c9ff5a5b9e-3", "text": "Parameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nids \u2013 Optional list of ids to associate with the texts.\nbatch_size \u2013 Batch size of insertion\nmetadata \u2013 Optional column data to be inserted\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScaleWithoutJSON.html"}
{"id": "a0c9ff5a5b9e-4", "text": "Parameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScaleWithoutJSON.html"}
{"id": "a0c9ff5a5b9e-5", "text": "docsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, where_str: Optional[str] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScaleWithoutJSON.html"}
{"id": "a0c9ff5a5b9e-6", "text": "Returns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\ndrop() \u2192 None\u00b6\nHelper function: Drop data\nescape_str(value: str) \u2192 str\u00b6\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: Iterable[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, config: Optional[MyScaleSettings] = None, text_ids: Optional[Iterable[str]] = None, batch_size: int = 32, **kwargs: Any) \u2192 MyScale\u00b6\nCreate Myscale wrapper with existing texts\nParameters\ntexts (Iterable[str]) \u2013 List or tuple of strings to be added\nembedding (Embeddings) \u2013 Function to extract text embedding\nconfig (MyScaleSettings, Optional) \u2013 Myscale configuration\ntext_ids (Optional[Iterable], optional) \u2013 IDs for the texts.\nDefaults to None.\nbatch_size (int, optional) \u2013 Batchsize when transmitting data to MyScale.\nDefaults to 32.\nmetadata (List[dict], optional) \u2013 metadata to texts. Defaults to None.\ninto (Other keyword arguments will pass) \u2013 [clickhouse-connect](https://clickhouse.com/docs/en/integrations/python#clickhouse-connect-driver-api)\nReturns\nMyScale Index\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScaleWithoutJSON.html"}
{"id": "a0c9ff5a5b9e-7", "text": "among selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nPerform a similarity search with MyScale\nParameters\nquery (str) \u2013 query string\nk (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScaleWithoutJSON.html"}
{"id": "a0c9ff5a5b9e-8", "text": "k (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.\nwhere_str (Optional[str], optional) \u2013 where condition string.\nDefaults to None.\nNOTE \u2013 Please do not let end-user to fill this and always be aware\nof SQL injection. When dealing with metadatas, remember to\nuse {self.metadata_column}.attribute instead of attribute\nalone. The default name for it is metadata.\nReturns\nList of Documents\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a similarity search with MyScale by vectors\nParameters\nquery (str) \u2013 query string\nk (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.\nwhere_str (Optional[str], optional) \u2013 where condition string.\nDefaults to None.\nNOTE \u2013 Please do not let end-user to fill this and always be aware\nof SQL injection. When dealing with metadatas, remember to\nuse {self.metadata_column}.attribute instead of attribute\nalone. The default name for it is metadata.\nReturns\nList of (Document, similarity)\nReturn type\nList[Document]\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPerform a similarity search with MyScale\nParameters\nquery (str) \u2013 query string\nk (int, optional) \u2013 Top K neighbors to retrieve. Defaults to 4.\nwhere_str (Optional[str], optional) \u2013 where condition string.\nDefaults to None.\nNOTE \u2013 Please do not let end-user to fill this and always be aware", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScaleWithoutJSON.html"}
{"id": "a0c9ff5a5b9e-9", "text": "NOTE \u2013 Please do not let end-user to fill this and always be aware\nof SQL injection. When dealing with metadatas, remember to\nuse {self.metadata_column}.attribute instead of attribute\nalone. The default name for it is metadata.\nReturns\nList of documents most similar to the query text\nand cosine distance in float for each.\nLower score represents more similarity.\nReturn type\nList[Document]\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.myscale.MyScaleWithoutJSON.html"}
{"id": "bec52ce7c675-0", "text": "langchain.vectorstores.baiducloud_vector_search.BESVectorStore\u00b6\nclass langchain.vectorstores.baiducloud_vector_search.BESVectorStore(index_name: str, bes_url: str, user: Optional[str] = None, password: Optional[str] = None, embedding: Optional[Embeddings] = None, **kwargs: Optional[dict])[source]\u00b6\nBaidu Elasticsearch vector store.\nExample\nfrom langchain.vectorstores import BESVectorStore\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nvectorstore = BESVectorStore(\n    embedding=OpenAIEmbeddings(),\n    index_name=\"langchain-demo\",\n    bes_url=\"http://localhost:9200\"\n)\nParameters\nindex_name \u2013 Name of the Elasticsearch index to create.\nbes_url \u2013 URL of the Baidu Elasticsearch instance to connect to.\nuser \u2013 Username to use when connecting to Elasticsearch.\npassword \u2013 Password to use when connecting to Elasticsearch.\nfrom (More information can be obtained) \u2013 \nhttps \u2013 //cloud.baidu.com/doc/BES/s/8llyn0hh4\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(index_name,\u00a0bes_url[,\u00a0user,\u00a0...])\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.baiducloud_vector_search.BESVectorStore.html"}
{"id": "bec52ce7c675-1", "text": "afrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\nbes_client(*[,\u00a0bes_url,\u00a0username,\u00a0password])\ndelete([ids])\nDelete documents from the index.\nfrom_documents(documents[,\u00a0embedding])\nConstruct BESVectorStore wrapper from documents.\nfrom_texts(texts[,\u00a0embedding,\u00a0metadatas])\nConstruct BESVectorStore wrapper from raw documents.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nReturn documents most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.baiducloud_vector_search.BESVectorStore.html"}
{"id": "bec52ce7c675-2", "text": "similarity_search(query[,\u00a0k,\u00a0filter])\nReturn documents most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query,\u00a0k[,\u00a0filter])\nReturn documents most similar to query, along with scores.\n__init__(index_name: str, bes_url: str, user: Optional[str] = None, password: Optional[str] = None, embedding: Optional[Embeddings] = None, **kwargs: Optional[dict]) \u2192 None[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[Dict[Any, Any]]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.baiducloud_vector_search.BESVectorStore.html"}
{"id": "bec52ce7c675-3", "text": "Run more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.baiducloud_vector_search.BESVectorStore.html"}
{"id": "bec52ce7c675-4", "text": "Parameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.baiducloud_vector_search.BESVectorStore.html"}
{"id": "bec52ce7c675-5", "text": "docsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\nstatic bes_client(*, bes_url: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None) \u2192 Elasticsearch[source]\u00b6\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete documents from the index.\nParameters\nids \u2013 List of ids of documents to delete", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.baiducloud_vector_search.BESVectorStore.html"}
{"id": "bec52ce7c675-6", "text": "Delete documents from the index.\nParameters\nids \u2013 List of ids of documents to delete\nclassmethod from_documents(documents: List[Document], embedding: Optional[Embeddings] = None, **kwargs: Any) \u2192 BESVectorStore[source]\u00b6\nConstruct BESVectorStore wrapper from documents.\nParameters\ndocuments \u2013 List of documents to add to the Elasticsearch index.\nembedding \u2013 Embedding function to use to embed the texts.\nDo not provide if using a strategy\nthat doesn\u2019t require inference.\nkwargs \u2013 create index key words arguments\nclassmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[Dict[str, Any]]] = None, **kwargs: Any) \u2192 BESVectorStore[source]\u00b6\nConstruct BESVectorStore wrapper from raw documents.\nParameters\ntexts \u2013 List of texts to add to the Elasticsearch index.\nembedding \u2013 Embedding function to use to embed the texts.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nindex_name \u2013 Name of the Elasticsearch index to create.\nkwargs \u2013 create index key words arguments\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.baiducloud_vector_search.BESVectorStore.html"}
{"id": "bec52ce7c675-7", "text": "to maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn documents most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Array of Elasticsearch filter clauses to apply to the query.\nReturns\nList of Documents most similar to the query,\nin descending order of similarity.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.baiducloud_vector_search.BESVectorStore.html"}
{"id": "bec52ce7c675-8", "text": "Return docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn documents most similar to query, along with scores.\nParameters\nquery \u2013 Text to look up documents similar to.\nsize \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Array of Elasticsearch filter clauses to apply to the query.\nReturns\nList of Documents most similar to the query and score for each\nExamples using BESVectorStore\u00b6\nBaidu Cloud VectorSearch", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.baiducloud_vector_search.BESVectorStore.html"}
{"id": "0b7bb6fcf74c-0", "text": "langchain.vectorstores.neo4j_vector.check_if_not_null\u00b6\nlangchain.vectorstores.neo4j_vector.check_if_not_null(props: List[str], values: List[Any]) \u2192 None[source]\u00b6\nCheck if the values are not None or empty string", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.check_if_not_null.html"}
{"id": "63710d9809d5-0", "text": "langchain.vectorstores.marqo.Marqo\u00b6\nclass langchain.vectorstores.marqo.Marqo(client: marqo.Client, index_name: str, add_documents_settings: Optional[Dict[str, Any]] = None, searchable_attributes: Optional[List[str]] = None, page_content_builder: Optional[Callable[[Dict[str, Any]], str]] = None)[source]\u00b6\nMarqo vector store.\nMarqo indexes have their own models associated with them to generate your\nembeddings. This means that you can selected from a range of different models\nand also use CLIP models to create multimodal indexes\nwith images and text together.\nMarqo also supports more advanced queries with multiple weighted terms, see See\nhttps://docs.marqo.ai/latest/#searching-using-weights-in-queries.\nThis class can flexibly take strings or dictionaries for weighted queries\nin its similarity search methods.\nTo use, you should have the marqo python package installed, you can do this with\npip install marqo.\nExample\nimport marqo\nfrom langchain.vectorstores import Marqo\nclient = marqo.Client(url=os.environ[\"MARQO_URL\"], ...)\nvectorstore = Marqo(client, index_name)\nInitialize with Marqo client.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(client,\u00a0index_name[,\u00a0...])\nInitialize with Marqo client.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.marqo.Marqo.html"}
{"id": "63710d9809d5-1", "text": "add_texts(texts[,\u00a0metadatas])\nUpload texts with metadata (properties) to Marqo.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\nbulk_similarity_search(queries[,\u00a0k])\nSearch the marqo index for the most similar documents in bulk with multiple queries.\nbulk_similarity_search_with_score(queries[,\u00a0k])\nReturn documents from Marqo that are similar to the query as well as their scores using a batch of queries.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents[,\u00a0embedding])\nReturn VectorStore initialized from documents.\nfrom_texts(texts[,\u00a0embedding,\u00a0metadatas,\u00a0...])\nReturn Marqo initialized from texts.\nget_indexes()", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.marqo.Marqo.html"}
{"id": "63710d9809d5-2", "text": "Return Marqo initialized from texts.\nget_indexes()\nHelper to see your available indexes in marqo, useful if the from_texts method was used without an index name specified\nget_number_of_documents()\nHelper to see the number of documents in the index\nmarqo_bulk_similarity_search(queries[,\u00a0k])\nReturn documents from Marqo using a bulk search, exposes Marqo's output directly\nmarqo_similarity_search(query[,\u00a0k])\nReturn documents from Marqo exposing Marqo's output directly\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nSearch the marqo index for the most similar documents.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nReturn documents from Marqo that are similar to the query as well as their scores.\n__init__(client: marqo.Client, index_name: str, add_documents_settings: Optional[Dict[str, Any]] = None, searchable_attributes: Optional[List[str]] = None, page_content_builder: Optional[Callable[[Dict[str, Any]], str]] = None)[source]\u00b6\nInitialize with Marqo client.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.marqo.Marqo.html"}
{"id": "63710d9809d5-3", "text": "Run more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nUpload texts with metadata (properties) to Marqo.\nYou can either have marqo generate ids for each document or you can provide\nyour own by including a \u201c_id\u201d field in the metadata objects.\nParameters\ntexts (Iterable[str]) \u2013 am iterator of texts - assumed to preserve an\nmetadatas. (order that matches the) \u2013 \nmetadatas (Optional[List[dict]], optional) \u2013 a list of metadatas.\nRaises\nValueError \u2013 if metadatas is provided and the number of metadatas differs\nfrom the number of texts. \u2013 \nReturns\nThe list of ids that were added.\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.marqo.Marqo.html"}
{"id": "63710d9809d5-4", "text": "Delete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.marqo.Marqo.html"}
{"id": "63710d9809d5-5", "text": "score_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.marqo.Marqo.html"}
{"id": "63710d9809d5-6", "text": "Return docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\nbulk_similarity_search(queries: Iterable[Union[str, Dict[str, float]]], k: int = 4, **kwargs: Any) \u2192 List[List[Document]][source]\u00b6\nSearch the marqo index for the most similar documents in bulk with multiple\nqueries.\nParameters\nqueries (Iterable[Union[str, Dict[str, float]]]) \u2013 An iterable of queries to\nbulk (execute in) \u2013 \nof (queries in the list can be strings or dictionaries) \u2013 \nqueries. (weighted) \u2013 \nk (int, optional) \u2013 The number of documents to return for each query.\n4. (Defaults to) \u2013 \nReturns\nA list of results for each query.\nReturn type\nList[List[Document]]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.marqo.Marqo.html"}
{"id": "63710d9809d5-7", "text": "Returns\nA list of results for each query.\nReturn type\nList[List[Document]]\nbulk_similarity_search_with_score(queries: Iterable[Union[str, Dict[str, float]]], k: int = 4, **kwargs: Any) \u2192 List[List[Tuple[Document, float]]][source]\u00b6\nReturn documents from Marqo that are similar to the query as well as\ntheir scores using a batch of queries.\nParameters\nquery (Iterable[Union[str, Dict[str, float]]]) \u2013 An iterable of queries\nbulk (to execute in) \u2013 \ndictionaries (queries in the list can be strings or) \u2013 \nqueries. (of weighted) \u2013 \nk (int, optional) \u2013 The number of documents to return. Defaults to 4.\nReturns\nA list of lists of the matching\ndocuments and their scores for each query\nReturn type\nList[Tuple[Document, float]]\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Optional[Embeddings] = None, **kwargs: Any) \u2192 Marqo[source]\u00b6\nReturn VectorStore initialized from documents. Note that Marqo does not\nneed embeddings, we retain the parameter to adhere to the Liskov substitution\nprinciple.\nParameters\ndocuments (List[Document]) \u2013 Input documents\nembedding (Any, optional) \u2013 Embeddings (not required). Defaults to None.\nReturns\nA Marqo vectorstore\nReturn type\nVectorStore", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.marqo.Marqo.html"}
{"id": "63710d9809d5-8", "text": "Returns\nA Marqo vectorstore\nReturn type\nVectorStore\nclassmethod from_texts(texts: List[str], embedding: Any = None, metadatas: Optional[List[dict]] = None, index_name: str = '', url: str = 'http://localhost:8882', api_key: str = '', add_documents_settings: Optional[Dict[str, Any]] = None, searchable_attributes: Optional[List[str]] = None, page_content_builder: Optional[Callable[[Dict[str, str]], str]] = None, index_settings: Optional[Dict[str, Any]] = None, verbose: bool = True, **kwargs: Any) \u2192 Marqo[source]\u00b6\nReturn Marqo initialized from texts. Note that Marqo does not need\nembeddings, we retain the parameter to adhere to the Liskov\nsubstitution principle.\nThis is a quick way to get started with marqo - simply provide your texts and\nmetadatas and this will create an instance of the data store and index the\nprovided data.\nTo know the ids of your documents with this approach you will need to include\nthem in under the key \u201c_id\u201d in your metadatas for each text\nExample:\n.. code-block:: python\nfrom langchain.vectorstores import Marqo\ndatastore = Marqo(texts=[\u2018text\u2019], index_name=\u2019my-first-index\u2019,\nurl=\u2019http://localhost:8882\u2019)\nParameters\ntexts (List[str]) \u2013 A list of texts to index into marqo upon creation.\nembedding (Any, optional) \u2013 Embeddings (not required). Defaults to None.\nindex_name (str, optional) \u2013 The name of the index to use, if none is\nNone. (accompany the texts. Defaults to) \u2013", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.marqo.Marqo.html"}
{"id": "63710d9809d5-9", "text": "None. (accompany the texts. Defaults to) \u2013 \nurl (str, optional) \u2013 The URL for Marqo. Defaults to \u201chttp://localhost:8882\u201d.\napi_key (str, optional) \u2013 The API key for Marqo. Defaults to \u201c\u201d.\nmetadatas (Optional[List[dict]], optional) \u2013 A list of metadatas, to\nNone. \u2013 \nCan (this is only used when a new index is being created. Defaults to \"cpu\".) \u2013 \n\"cuda\". (be \"cpu\" or) \u2013 \nadd_documents_settings (Optional[Dict[str, Any]], optional) \u2013 Settings\ndocuments (for adding) \u2013 \nsee \u2013 \nhttps \u2013 //docs.marqo.ai/0.0.16/API-Reference/documents/#query-parameters.\n{}. (Defaults to) \u2013 \nindex_settings (Optional[Dict[str, Any]], optional) \u2013 Index settings if\nexist (the index doesn't) \u2013 \nsee \u2013 \nhttps \u2013 //docs.marqo.ai/0.0.16/API-Reference/indexes/#index-defaults-object.\n{}. \u2013 \nReturns\nAn instance of the Marqo vector store\nReturn type\nMarqo\nget_indexes() \u2192 List[Dict[str, str]][source]\u00b6\nHelper to see your available indexes in marqo, useful if the\nfrom_texts method was used without an index name specified\nReturns\nThe list of indexes\nReturn type\nList[Dict[str, str]]\nget_number_of_documents() \u2192 int[source]\u00b6\nHelper to see the number of documents in the index\nReturns\nThe number of documents\nReturn type\nint", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.marqo.Marqo.html"}
{"id": "63710d9809d5-10", "text": "Returns\nThe number of documents\nReturn type\nint\nmarqo_bulk_similarity_search(queries: Iterable[Union[str, Dict[str, float]]], k: int = 4) \u2192 Dict[str, List[Dict[str, List[Dict[str, str]]]]][source]\u00b6\nReturn documents from Marqo using a bulk search, exposes Marqo\u2019s\noutput directly\nParameters\nqueries (Iterable[Union[str, Dict[str, float]]]) \u2013 A list of queries.\nk (int, optional) \u2013 The number of documents to return for each query.\n4. (Defaults to) \u2013 \nReturns\nA bulk search results\nobject\nReturn type\nDict[str, Dict[List[Dict[str, Dict[str, Any]]]]]\nmarqo_similarity_search(query: Union[str, Dict[str, float]], k: int = 4) \u2192 Dict[str, List[Dict[str, str]]][source]\u00b6\nReturn documents from Marqo exposing Marqo\u2019s output directly\nParameters\nquery (str) \u2013 The query to search with.\nk (int, optional) \u2013 The number of documents to return. Defaults to 4.\nReturns\nThis hits from marqo.\nReturn type\nList[Dict[str, Any]]\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.marqo.Marqo.html"}
{"id": "63710d9809d5-11", "text": "lambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: Union[str, Dict[str, float]], k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nSearch the marqo index for the most similar documents.\nParameters\nquery (Union[str, Dict[str, float]]) \u2013 The query for the search, either\nquery. (as a string or a weighted) \u2013 \nk (int, optional) \u2013 The number of documents to return. Defaults to 4.\nReturns\nk documents ordered from best to worst match.\nReturn type\nList[Document]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.marqo.Marqo.html"}
{"id": "63710d9809d5-12", "text": "Returns\nk documents ordered from best to worst match.\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: Union[str, Dict[str, float]], k: int = 4) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn documents from Marqo that are similar to the query as well\nas their scores.\nParameters\nquery (str) \u2013 The query to search with, either as a string or a weighted\nquery. \u2013 \nk (int, optional) \u2013 The number of documents to return. Defaults to 4.\nReturns\nThe matching documents and their scores,\nordered by descending score.\nReturn type\nList[Tuple[Document, float]]\nExamples using Marqo\u00b6\nMarqo", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.marqo.Marqo.html"}
{"id": "7855c5d3e066-0", "text": "langchain.vectorstores.sklearn.JsonSerializer\u00b6\nclass langchain.vectorstores.sklearn.JsonSerializer(persist_path: str)[source]\u00b6\nSerializes data in json using the json package from python standard library.\nMethods\n__init__(persist_path)\nextension()\nThe file extension suggested by this serializer (without dot).\nload()\nLoads the data from the persist_path\nsave(data)\nSaves the data to the persist_path\n__init__(persist_path: str) \u2192 None\u00b6\nclassmethod extension() \u2192 str[source]\u00b6\nThe file extension suggested by this serializer (without dot).\nload() \u2192 Any[source]\u00b6\nLoads the data from the persist_path\nsave(data: Any) \u2192 None[source]\u00b6\nSaves the data to the persist_path", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.JsonSerializer.html"}
{"id": "304cecd148b9-0", "text": "langchain.vectorstores.tencentvectordb.ConnectionParams\u00b6\nclass langchain.vectorstores.tencentvectordb.ConnectionParams(url: str, key: str, username: str = 'root', timeout: int = 10)[source]\u00b6\nTencent vector DB Connection params.\nSee the following documentation for details:\nhttps://cloud.tencent.com/document/product/1709/95820\nAttribute:\nurl (str)The access address of the vector database serverthat the client needs to connect to.\nkey (str): API key for client to access the vector database server,which is used for authentication.\nusername (str) : Account for client to access the vector database server.\ntimeout (int) : Request Timeout.\nMethods\n__init__(url,\u00a0key[,\u00a0username,\u00a0timeout])\n__init__(url: str, key: str, username: str = 'root', timeout: int = 10)[source]\u00b6\nExamples using ConnectionParams\u00b6\nTencent Cloud VectorDB", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tencentvectordb.ConnectionParams.html"}
{"id": "4d22678ca5ac-0", "text": "langchain.vectorstores.sqlitevss.SQLiteVSS\u00b6\nclass langchain.vectorstores.sqlitevss.SQLiteVSS(table: str, connection: Optional[sqlite3.Connection], embedding: Embeddings, db_file: str = 'vss.db')[source]\u00b6\nWrapper around SQLite with vss extension as a vector database.\nTo use, you should have the sqlite-vss python package installed.\n.. rubric:: Example\nInitialize with sqlite client with vss extension.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(table,\u00a0connection,\u00a0embedding[,\u00a0db_file])\nInitialize with sqlite client with vss extension.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nAdd more texts to the vectorstore index.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sqlitevss.SQLiteVSS.html"}
{"id": "4d22678ca5ac-1", "text": "Return docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ncreate_connection(db_file)\ncreate_table_if_not_exists()\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nget_dimensionality()\nFunction that does a dummy embedding to figure out how many dimensions this embedding function returns.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_with_score_by_vector(embedding)\n__init__(table: str, connection: Optional[sqlite3.Connection], embedding: Embeddings, db_file: str = 'vss.db')[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sqlitevss.SQLiteVSS.html"}
{"id": "4d22678ca5ac-2", "text": "Initialize with sqlite client with vss extension.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd more texts to the vectorstore index.\n:param texts: Iterable of strings to add to the vectorstore.\n:param metadatas: Optional list of metadatas associated with the texts.\n:param kwargs: vectorstore specific parameters\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sqlitevss.SQLiteVSS.html"}
{"id": "4d22678ca5ac-3", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sqlitevss.SQLiteVSS.html"}
{"id": "4d22678ca5ac-4", "text": "Return type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sqlitevss.SQLiteVSS.html"}
{"id": "4d22678ca5ac-5", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\nstatic create_connection(db_file: str) \u2192 sqlite3.Connection[source]\u00b6\ncreate_table_if_not_exists() \u2192 None[source]\u00b6\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, table: str = 'langchain', db_file: str = 'vss.db', **kwargs: Any) \u2192 SQLiteVSS[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nget_dimensionality() \u2192 int[source]\u00b6\nFunction that does a dummy embedding to figure out how many dimensions\nthis embedding function returns. Needed for the virtual table DDL.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sqlitevss.SQLiteVSS.html"}
{"id": "4d22678ca5ac-6", "text": "this embedding function returns. Needed for the virtual table DDL.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sqlitevss.SQLiteVSS.html"}
{"id": "4d22678ca5ac-7", "text": "Return docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nExamples using SQLiteVSS\u00b6\nsqlite-vss", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sqlitevss.SQLiteVSS.html"}
{"id": "9b32e63487f5-0", "text": "langchain.vectorstores.starrocks.debug_output\u00b6\nlangchain.vectorstores.starrocks.debug_output(s: Any) \u2192 None[source]\u00b6\nPrint a debug message if DEBUG is True.\n:param s: The message to print", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.starrocks.debug_output.html"}
{"id": "6c3a6525ccdb-0", "text": "langchain.vectorstores.redis.filters.RedisTag\u00b6\nclass langchain.vectorstores.redis.filters.RedisTag(field: str)[source]\u00b6\nA RedisFilterField representing a tag in a Redis index.\nCreate a RedisTag FilterField\nParameters\nfield (str) \u2013 The name of the RedisTag field in the index to be queried\nagainst.\nAttributes\nOPERATORS\nOPERATOR_MAP\nescaper\nMethods\n__init__(field)\nCreate a RedisTag FilterField\nequals(other)\n__init__(field: str)[source]\u00b6\nCreate a RedisTag FilterField\nParameters\nfield (str) \u2013 The name of the RedisTag field in the index to be queried\nagainst.\nequals(other: RedisFilterField) \u2192 bool\u00b6\nExamples using RedisTag\u00b6\nRedis", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.filters.RedisTag.html"}
{"id": "740a1954b492-0", "text": "langchain.vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch\u00b6\nclass langchain.vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch(collection: Collection[MongoDBDocumentType], embedding: Embeddings, *, index_name: str = 'default', text_key: str = 'text', embedding_key: str = 'embedding')[source]\u00b6\nMongoDB Atlas Vector Search vector store.\nTo use, you should have both:\n- the pymongo python package installed\n- a connection string associated with a MongoDB Atlas Cluster having deployed an\nAtlas Search index\nExample\nfrom langchain.vectorstores import MongoDBAtlasVectorSearch\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom pymongo import MongoClient\nmongo_client = MongoClient(\"<YOUR-CONNECTION-STRING>\")\ncollection = mongo_client[\"<db_name>\"][\"<collection_name>\"]\nembeddings = OpenAIEmbeddings()\nvectorstore = MongoDBAtlasVectorSearch(collection, embeddings)\nParameters\ncollection \u2013 MongoDB collection to add the texts to.\nembedding \u2013 Text embedding model to use.\ntext_key \u2013 MongoDB field that will contain the text for each\ndocument.\nembedding_key \u2013 MongoDB field that will contain the embedding for\neach document.\nindex_name \u2013 Name of the Atlas Search index.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(collection,\u00a0embedding,\u00a0*[,\u00a0...])\nparam collection\nMongoDB collection to add the texts to.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch.html"}
{"id": "740a1954b492-1", "text": "add_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_connection_string(connection_string,\u00a0...)\nConstruct a MongoDB Atlas Vector Search vector store from a MongoDB connection URI.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nConstruct a MongoDB Atlas Vector Search vector store from raw documents.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn documents selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch.html"}
{"id": "740a1954b492-2", "text": "max_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0pre_filter,\u00a0...])\nReturn MongoDB documents most similar to the given query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query,\u00a0*[,\u00a0k,\u00a0...])\nReturn MongoDB documents most similar to the given query and their scores.\n__init__(collection: Collection[MongoDBDocumentType], embedding: Embeddings, *, index_name: str = 'default', text_key: str = 'text', embedding_key: str = 'embedding')[source]\u00b6\nParameters\ncollection \u2013 MongoDB collection to add the texts to.\nembedding \u2013 Text embedding model to use.\ntext_key \u2013 MongoDB field that will contain the text for each\ndocument.\nembedding_key \u2013 MongoDB field that will contain the embedding for\neach document.\nindex_name \u2013 Name of the Atlas Search index.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch.html"}
{"id": "740a1954b492-3", "text": "add_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[Dict[str, Any]]] = None, **kwargs: Any) \u2192 List[source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch.html"}
{"id": "740a1954b492-4", "text": "Return docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch.html"}
{"id": "740a1954b492-5", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch.html"}
{"id": "740a1954b492-6", "text": "Returns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_connection_string(connection_string: str, namespace: str, embedding: Embeddings, **kwargs: Any) \u2192 MongoDBAtlasVectorSearch[source]\u00b6\nConstruct a MongoDB Atlas Vector Search vector store\nfrom a MongoDB connection URI.\nParameters\nconnection_string \u2013 A valid MongoDB connection URI.\nnamespace \u2013 A valid MongoDB namespace (database and collection).\nembedding \u2013 The text embedding model to use for the vector store.\nReturns\nA new MongoDBAtlasVectorSearch instance.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict]] = None, collection: Optional[Collection[MongoDBDocumentType]] = None, **kwargs: Any) \u2192 MongoDBAtlasVectorSearch[source]\u00b6\nConstruct a MongoDB Atlas Vector Search vector store from raw documents.\nThis is a user-friendly interface that:\nEmbeds documents.\nAdds the documents to a provided MongoDB Atlas Vector Search index(Lucene)\nThis is intended to be a quick way to get started.\nExample", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch.html"}
{"id": "740a1954b492-7", "text": "This is intended to be a quick way to get started.\nExample\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, pre_filter: Optional[Dict] = None, post_filter_pipeline: Optional[List[Dict]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn documents selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 (Optional) number of documents to return. Defaults to 4.\nfetch_k \u2013 (Optional) number of documents to fetch before passing to MMR\nalgorithm. Defaults to 20.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\npre_filter \u2013 (Optional) dictionary of argument(s) to prefilter on document\nfields.\npost_filter_pipeline \u2013 (Optional) pipeline of MongoDB aggregation stages\nfollowing the knnBeta vector search.\nReturns\nList of documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch.html"}
{"id": "740a1954b492-8", "text": "fetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, pre_filter: Optional[Dict] = None, post_filter_pipeline: Optional[List[Dict]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn MongoDB documents most similar to the given query.\nUses the knnBeta Operator available in MongoDB Atlas Search.\nThis feature is in early access and available only for evaluation purposes, to\nvalidate functionality, and to gather feedback from a small closed group of\nearly access users. It is not recommended for production deployments as we\nmay introduce breaking changes.\nFor more: https://www.mongodb.com/docs/atlas/atlas-search/knn-beta\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 (Optional) number of documents to return. Defaults to 4.\npre_filter \u2013 (Optional) dictionary of argument(s) to prefilter document\nfields on.\npost_filter_pipeline \u2013 (Optional) Pipeline of MongoDB aggregation stages\nfollowing the knnBeta vector search.\nReturns\nList of documents most similar to the query and their scores.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch.html"}
{"id": "740a1954b492-9", "text": "Parameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, *, k: int = 4, pre_filter: Optional[Dict] = None, post_filter_pipeline: Optional[List[Dict]] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn MongoDB documents most similar to the given query and their scores.\nUses the knnBeta Operator available in MongoDB Atlas Search.\nThis feature is in early access and available only for evaluation purposes, to\nvalidate functionality, and to gather feedback from a small closed group of\nearly access users. It is not recommended for production deployments as we\nmay introduce breaking changes.\nFor more: https://www.mongodb.com/docs/atlas/atlas-search/knn-beta\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 (Optional) number of documents to return. Defaults to 4.\npre_filter \u2013 (Optional) dictionary of argument(s) to prefilter document\nfields on.\npost_filter_pipeline \u2013 (Optional) Pipeline of MongoDB aggregation stages\nfollowing the knnBeta vector search.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch.html"}
{"id": "740a1954b492-10", "text": "following the knnBeta vector search.\nReturns\nList of documents most similar to the query and their scores.\nExamples using MongoDBAtlasVectorSearch\u00b6\nMongoDB Atlas", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch.html"}
{"id": "dde01453f940-0", "text": "langchain.vectorstores.qdrant.QdrantException\u00b6\nclass langchain.vectorstores.qdrant.QdrantException[source]\u00b6\nQdrant related exceptions.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.QdrantException.html"}
{"id": "9811f93100e1-0", "text": "langchain.vectorstores.lancedb.LanceDB\u00b6\nclass langchain.vectorstores.lancedb.LanceDB(connection: Any, embedding: Embeddings, vector_key: Optional[str] = 'vector', id_key: Optional[str] = 'id', text_key: Optional[str] = 'text')[source]\u00b6\nLanceDB vector store.\nTo use, you should have lancedb python package installed.\nExample\ndb = lancedb.connect('./lancedb')\ntable = db.open_table('my_table')\nvectorstore = LanceDB(table, embedding_function)\nvectorstore.add_texts(['text1', 'text2'])\nresult = vectorstore.similarity_search('text1')\nInitialize with Lance DB connection\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(connection,\u00a0embedding[,\u00a0...])\nInitialize with Lance DB connection\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nTurn texts into embedding and add it to the database\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.lancedb.LanceDB.html"}
{"id": "9811f93100e1-1", "text": "Return docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn documents most similar to the query\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.lancedb.LanceDB.html"}
{"id": "9811f93100e1-2", "text": "similarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\n__init__(connection: Any, embedding: Embeddings, vector_key: Optional[str] = 'vector', id_key: Optional[str] = 'id', text_key: Optional[str] = 'text')[source]\u00b6\nInitialize with Lance DB connection\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nTurn texts into embedding and add it to the database\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of ids to associate with the texts.\nReturns\nList of ids of the added texts.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.lancedb.LanceDB.html"}
{"id": "9811f93100e1-3", "text": "Delete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.lancedb.LanceDB.html"}
{"id": "9811f93100e1-4", "text": "score_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.lancedb.LanceDB.html"}
{"id": "9811f93100e1-5", "text": "Return docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.lancedb.LanceDB.html"}
{"id": "9811f93100e1-6", "text": "Return VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, connection: Any = None, vector_key: Optional[str] = 'vector', id_key: Optional[str] = 'id', text_key: Optional[str] = 'text', **kwargs: Any) \u2192 LanceDB[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.lancedb.LanceDB.html"}
{"id": "9811f93100e1-7", "text": "fetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn documents most similar to the query\nParameters\nquery \u2013 String to query the vectorstore with.\nk \u2013 Number of documents to return.\nReturns\nList of documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.lancedb.LanceDB.html"}
{"id": "9811f93100e1-8", "text": "Returns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.\nExamples using LanceDB\u00b6\nLanceDB", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.lancedb.LanceDB.html"}
{"id": "fd75b361b0b5-0", "text": "langchain.vectorstores.pgvecto_rs.PGVecto_rs\u00b6\nclass langchain.vectorstores.pgvecto_rs.PGVecto_rs(embedding: Embeddings, dimension: int, db_url: str, collection_name: str, new_table: bool = False)[source]\u00b6\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding,\u00a0dimension,\u00a0db_url,\u00a0...)\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvecto_rs.PGVecto_rs.html"}
{"id": "fd75b361b0b5-1", "text": "Return docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_collection_name(embedding,\u00a0db_url,\u00a0...)\nCreate new empty vectorstore with collection_name.\nfrom_documents(documents,\u00a0embedding[,\u00a0...])\nReturn VectorStore initialized from documents.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and optional metadatas.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0distance_func])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nRun similarity search with distance.\nsimilarity_search_with_score_by_vector(...)\nReturn docs most similar to query vector, with its score.\n__init__(embedding: Embeddings, dimension: int, db_url: str, collection_name: str, new_table: bool = False) \u2192 None[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvecto_rs.PGVecto_rs.html"}
{"id": "fd75b361b0b5-2", "text": "Run more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\ndocuments (List[Document]) \u2013 List of documents to add to the vectorstore.\nReturns\nList of ids of the added documents.\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids of the added texts.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvecto_rs.PGVecto_rs.html"}
{"id": "fd75b361b0b5-3", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvecto_rs.PGVecto_rs.html"}
{"id": "fd75b361b0b5-4", "text": "Return type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvecto_rs.PGVecto_rs.html"}
{"id": "fd75b361b0b5-5", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_collection_name(embedding: Embeddings, db_url: str, collection_name: str) \u2192 PGVecto_rs[source]\u00b6\nCreate new empty vectorstore with collection_name.\nOr connect to an existing vectorstore in database if exists.\nArguments should be the same as when the vectorstore was created.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, db_url: str = '', collection_name: str = '7e09cadf8476499892991089fd105fe5', **kwargs: Any) \u2192 PGVecto_rs[source]\u00b6\nReturn VectorStore initialized from documents.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvecto_rs.PGVecto_rs.html"}
{"id": "fd75b361b0b5-6", "text": "Return VectorStore initialized from documents.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, db_url: str = '', collection_name: str = '7ebd09bda1144d508f2d1313247612fe', **kwargs: Any) \u2192 PGVecto_rs[source]\u00b6\nReturn VectorStore initialized from texts and optional metadatas.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvecto_rs.PGVecto_rs.html"}
{"id": "fd75b361b0b5-7", "text": "fetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, distance_func: Literal['sqrt_euclid', 'neg_dot_prod', 'ned_cos'] = 'sqrt_euclid', **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, distance_func: Literal['sqrt_euclid', 'neg_dot_prod', 'ned_cos'] = 'sqrt_euclid', **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvecto_rs.PGVecto_rs.html"}
{"id": "fd75b361b0b5-8", "text": "filter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, distance_func: Literal['sqrt_euclid', 'neg_dot_prod', 'ned_cos'] = 'sqrt_euclid', **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with distance.\nsimilarity_search_with_score_by_vector(query_vector: List[float], k: int = 4, distance_func: Literal['sqrt_euclid', 'neg_dot_prod', 'ned_cos'] = 'sqrt_euclid', **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query vector, with its score.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgvecto_rs.PGVecto_rs.html"}
{"id": "aaccd8143819-0", "text": "langchain.vectorstores.awadb.AwaDB\u00b6\nclass langchain.vectorstores.awadb.AwaDB(table_name: str = 'langchain_awadb', embedding: Optional[Embeddings] = None, log_and_data_dir: Optional[str] = None, client: Optional[awadb.Client] = None, **kwargs: Any)[source]\u00b6\nAwaDB vector store.\nInitialize with AwaDB client.If table_name is not specified,\na random table name of _DEFAULT_TABLE_NAME + last segment of uuid\nwould be created automatically.\nParameters\ntable_name \u2013 Name of the table created, default _DEFAULT_TABLE_NAME.\nembedding \u2013 Optional Embeddings initially set.\nlog_and_data_dir \u2013 Optional the root directory of log and data.\nclient \u2013 Optional AwaDB client.\nkwargs \u2013 Any possible extend parameters in the future.\nReturns\nNone.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__([table_name,\u00a0embedding,\u00a0...])\nInitialize with AwaDB client.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0is_duplicate_texts])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.awadb.AwaDB.html"}
{"id": "aaccd8143819-1", "text": "Return VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ncreate_table(table_name,\u00a0**kwargs)\nCreate a new table.\ndelete([ids])\nDelete the documents which have the specified ids.\nfrom_documents(documents[,\u00a0embedding,\u00a0...])\nCreate an AwaDB vectorstore from a list of documents.\nfrom_texts(texts[,\u00a0embedding,\u00a0metadatas,\u00a0...])\nCreate an AwaDB vectorstore from a raw documents.\nget([ids,\u00a0text_in_page_content,\u00a0...])\nReturn docs according ids.\nget_current_table(**kwargs)\nGet the current table.\nlist_tables(**kwargs)\nList all the tables created by the client.\nload_local(table_name,\u00a0**kwargs)\nLoad the local specified table.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.awadb.AwaDB.html"}
{"id": "aaccd8143819-2", "text": "Return docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0...])\nReturn docs most similar to query.\nsimilarity_search_by_vector([embedding,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nThe most k similar documents and scores of the specified query.\nupdate(ids,\u00a0texts[,\u00a0metadatas])\nUpdate the documents which have the specified ids.\nuse(table_name,\u00a0**kwargs)\nUse the specified table.\n__init__(table_name: str = 'langchain_awadb', embedding: Optional[Embeddings] = None, log_and_data_dir: Optional[str] = None, client: Optional[awadb.Client] = None, **kwargs: Any) \u2192 None[source]\u00b6\nInitialize with AwaDB client.If table_name is not specified,\na random table name of _DEFAULT_TABLE_NAME + last segment of uuid\nwould be created automatically.\nParameters\ntable_name \u2013 Name of the table created, default _DEFAULT_TABLE_NAME.\nembedding \u2013 Optional Embeddings initially set.\nlog_and_data_dir \u2013 Optional the root directory of log and data.\nclient \u2013 Optional AwaDB client.\nkwargs \u2013 Any possible extend parameters in the future.\nReturns\nNone.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.awadb.AwaDB.html"}
{"id": "aaccd8143819-3", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, is_duplicate_texts: Optional[bool] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\n:param texts: Iterable of strings to add to the vectorstore.\n:param metadatas: Optional list of metadatas associated with the texts.\n:param is_duplicate_texts: Optional whether to duplicate texts. Defaults to True.\n:param kwargs: any possible extend parameters in the future.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.awadb.AwaDB.html"}
{"id": "aaccd8143819-4", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.awadb.AwaDB.html"}
{"id": "aaccd8143819-5", "text": "Return type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.awadb.AwaDB.html"}
{"id": "aaccd8143819-6", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ncreate_table(table_name: str, **kwargs: Any) \u2192 bool[source]\u00b6\nCreate a new table.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete the documents which have the specified ids.\nParameters\nids \u2013 The ids of the embedding vectors.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful.\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Optional[Embeddings] = None, table_name: str = 'langchain_awadb', log_and_data_dir: Optional[str] = None, client: Optional[awadb.Client] = None, **kwargs: Any) \u2192 AwaDB[source]\u00b6\nCreate an AwaDB vectorstore from a list of documents.\nIf a log_and_data_dir specified, the table will be persisted there.\nParameters\ndocuments (List[Document]) \u2013 List of documents to add to the vectorstore.\nembedding (Optional[Embeddings]) \u2013 Embedding function. Defaults to None.\ntable_name (str) \u2013 Name of the table to create.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.awadb.AwaDB.html"}
{"id": "aaccd8143819-7", "text": "table_name (str) \u2013 Name of the table to create.\nlog_and_data_dir (Optional[str]) \u2013 Directory to persist the table.\nclient (Optional[awadb.Client]) \u2013 AwaDB client.\nAny \u2013 Any possible parameters in the future\nReturns\nAwaDB vectorstore.\nReturn type\nAwaDB\nclassmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, table_name: str = 'langchain_awadb', log_and_data_dir: Optional[str] = None, client: Optional[awadb.Client] = None, **kwargs: Any) \u2192 AwaDB[source]\u00b6\nCreate an AwaDB vectorstore from a raw documents.\nParameters\ntexts (List[str]) \u2013 List of texts to add to the table.\nembedding (Optional[Embeddings]) \u2013 Embedding function. Defaults to None.\nmetadatas (Optional[List[dict]]) \u2013 List of metadatas. Defaults to None.\ntable_name (str) \u2013 Name of the table to create.\nlog_and_data_dir (Optional[str]) \u2013 Directory of logging and persistence.\nclient (Optional[awadb.Client]) \u2013 AwaDB client\nReturns\nAwaDB vectorstore.\nReturn type\nAwaDB\nget(ids: Optional[List[str]] = None, text_in_page_content: Optional[str] = None, meta_filter: Optional[dict] = None, not_include_fields: Optional[Set[str]] = None, limit: Optional[int] = None, **kwargs: Any) \u2192 Dict[str, Document][source]\u00b6\nReturn docs according ids.\nParameters\nids \u2013 The ids of the embedding vectors.\ntext_in_page_content \u2013 Filter by the text in page_content of Document.\nmeta_filter \u2013 Filter by any metadata of the document.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.awadb.AwaDB.html"}
{"id": "aaccd8143819-8", "text": "meta_filter \u2013 Filter by any metadata of the document.\nnot_include_fields \u2013 Not pack the specified fields of each document.\nlimit \u2013 The number of documents to return. Defaults to 5. Optional.\nReturns\nDocuments which satisfy the input conditions.\nget_current_table(**kwargs: Any) \u2192 str[source]\u00b6\nGet the current table.\nlist_tables(**kwargs: Any) \u2192 List[str][source]\u00b6\nList all the tables created by the client.\nload_local(table_name: str, **kwargs: Any) \u2192 bool[source]\u00b6\nLoad the local specified table.\nParameters\ntable_name \u2013 Table name\nkwargs \u2013 Any possible extend parameters in the future.\nReturns\nSuccess or failure of loading the local specified table\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, text_in_page_content: Optional[str] = None, meta_filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\ntext_in_page_content \u2013 Filter by the text in page_content of Document.\nmeta_filter (Optional[dict]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents selected by maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.awadb.AwaDB.html"}
{"id": "aaccd8143819-9", "text": "Returns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, text_in_page_content: Optional[str] = None, meta_filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\ntext_in_page_content \u2013 Filter by the text in page_content of Document.\nmeta_filter (Optional[dict]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, text_in_page_content: Optional[str] = None, meta_filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text query.\nk \u2013 The maximum number of documents to return.\ntext_in_page_content \u2013 Filter by the text in page_content of Document.\nmeta_filter (Optional[dict]) \u2013 Filter by metadata. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.awadb.AwaDB.html"}
{"id": "aaccd8143819-10", "text": "meta_filter (Optional[dict]) \u2013 Filter by metadata. Defaults to None.\n`{\"color\" (E.g.) \u2013 \u201dred\u201d, \u201cprice\u201d: 4.20}`. Optional.\n`{\"max_price\" (E.g.) \u2013 15.66, \u201cmin_price\u201d: 4.20}`\nfield (price is the metadata) \u2013 \nfilter (means range) \u2013 \n`{\"maxe_price\" (E.g.) \u2013 15.66, \u201cmine_price\u201d: 4.20}`\nfield \u2013 \nfilter \u2013 \nkwargs \u2013 Any possible extend parameters in the future.\nReturns\nReturns the k most similar documents to the specified text query.\nsimilarity_search_by_vector(embedding: Optional[List[float]] = None, k: int = 4, text_in_page_content: Optional[str] = None, meta_filter: Optional[dict] = None, not_include_fields_in_metadata: Optional[Set[str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\ntext_in_page_content \u2013 Filter by the text in page_content of Document.\nmeta_filter \u2013 Filter by metadata. Defaults to None.\nnot_incude_fields_in_metadata \u2013 Not include meta fields of each document.\nReturns\nList of Documents which are the most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.awadb.AwaDB.html"}
{"id": "aaccd8143819-11", "text": "query \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, text_in_page_content: Optional[str] = None, meta_filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nThe most k similar documents and scores of the specified query.\nParameters\nquery \u2013 Text query.\nk \u2013 The k most similar documents to the text query.\ntext_in_page_content \u2013 Filter by the text in page_content of Document.\nmeta_filter \u2013 Filter by metadata. Defaults to None.\nkwargs \u2013 Any possible extend parameters in the future.\nReturns\nThe k most similar documents to the specified text query.\n0 is dissimilar, 1 is the most similar.\nupdate(ids: List[str], texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nUpdate the documents which have the specified ids.\nParameters\nids \u2013 The id list of the updating embedding vector.\ntexts \u2013 The texts of the updating documents.\nmetadatas \u2013 The metadatas of the updating documents.\nReturns\nthe ids of the updated documents.\nuse(table_name: str, **kwargs: Any) \u2192 bool[source]\u00b6\nUse the specified table. Don\u2019t know the tables, please invoke list_tables.\nExamples using AwaDB\u00b6\nAwaDB", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.awadb.AwaDB.html"}
{"id": "0855a29094dc-0", "text": "langchain.vectorstores.clickhouse.ClickhouseSettings\u00b6\nclass langchain.vectorstores.clickhouse.ClickhouseSettings[source]\u00b6\nBases: BaseSettings\nClickHouse client configuration.\nAttribute:\nhost (str)An URL to connect to MyScale backend.Defaults to \u2018localhost\u2019.\nport (int) : URL port to connect with HTTP. Defaults to 8443.\nusername (str) : Username to login. Defaults to None.\npassword (str) : Password to login. Defaults to None.\nindex_type (str): index type string.\nindex_param (list): index build parameter.\nindex_query_params(dict): index query parameters.\ndatabase (str) : Database name to find the table. Defaults to \u2018default\u2019.\ntable (str) : Table name to operate on.\nDefaults to \u2018vector_table\u2019.\nmetric (str)Metric to compute distance,supported are (\u2018angular\u2019, \u2018euclidean\u2019, \u2018manhattan\u2019, \u2018hamming\u2019,\n\u2018dot\u2019). Defaults to \u2018angular\u2019.\nhttps://github.com/spotify/annoy/blob/main/src/annoymodule.cc#L149-L169\ncolumn_map (Dict)Column type map to project column name onto langchainsemantics. Must have keys: text, id, vector,\nmust be same size to number of columns. For example:\n.. code-block:: python\n{\u2018id\u2019: \u2018text_id\u2019,\n\u2018uuid\u2019: \u2018global_unique_id\u2019\n\u2018embedding\u2019: \u2018text_embedding\u2019,\n\u2018document\u2019: \u2018text_plain\u2019,\n\u2018metadata\u2019: \u2018metadata_dictionary_in_json\u2019,\n}\nDefaults to identity map.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.ClickhouseSettings.html"}
{"id": "0855a29094dc-1", "text": "Raises ValidationError if the input data cannot be parsed to form a valid model.\nparam column_map: Dict[str, str] = {'document': 'document', 'embedding': 'embedding', 'id': 'id', 'metadata': 'metadata', 'uuid': 'uuid'}\u00b6\nparam database: str = 'default'\u00b6\nparam host: str = 'localhost'\u00b6\nparam index_param: Optional[Union[List, Dict]] = [\"'L2Distance'\", 100]\u00b6\nparam index_query_params: Dict[str, str] = {}\u00b6\nparam index_type: str = 'annoy'\u00b6\nparam metric: str = 'angular'\u00b6\nparam password: Optional[str] = None\u00b6\nparam port: int = 8123\u00b6\nparam table: str = 'langchain'\u00b6\nparam username: Optional[str] = None\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.ClickhouseSettings.html"}
{"id": "0855a29094dc-2", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.ClickhouseSettings.html"}
{"id": "0855a29094dc-3", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using ClickhouseSettings\u00b6\nClickHouse", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clickhouse.ClickhouseSettings.html"}
{"id": "6e2841983903-0", "text": "langchain.vectorstores.atlas.AtlasDB\u00b6\nclass langchain.vectorstores.atlas.AtlasDB(name: str, embedding_function: Optional[Embeddings] = None, api_key: Optional[str] = None, description: str = 'A description for your project', is_public: bool = True, reset_project_if_exists: bool = False)[source]\u00b6\nAtlas vector store.\nAtlas is the Nomic\u2019s neural database and rhizomatic instrument.\nTo use, you should have the nomic python package installed.\nExample\nfrom langchain.vectorstores import AtlasDB\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nvectorstore = AtlasDB(\"my_project\", embeddings.embed_query)\nInitialize the Atlas Client\nParameters\nname (str) \u2013 The name of your project. If the project already exists,\nit will be loaded.\nembedding_function (Optional[Embeddings]) \u2013 An optional function used for\nembedding your data. If None, data will be embedded with\nNomic\u2019s embed model.\napi_key (str) \u2013 Your nomic API key\ndescription (str) \u2013 A description for your project.\nis_public (bool) \u2013 Whether your project is publicly accessible.\nTrue by default.\nreset_project_if_exists (bool) \u2013 Whether to reset this project if it\nalready exists. Default False.\nGenerally useful during development and testing.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(name[,\u00a0embedding_function,\u00a0...])\nInitialize the Atlas Client\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html"}
{"id": "6e2841983903-1", "text": "add_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0refresh])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ncreate_index(**kwargs)\nCreates an index in your project.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents[,\u00a0embedding,\u00a0ids,\u00a0...])\nCreate an AtlasDB vectorstore from a list of documents.\nfrom_texts(texts[,\u00a0embedding,\u00a0metadatas,\u00a0...])\nCreate an AtlasDB vectorstore from a raw documents.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html"}
{"id": "6e2841983903-2", "text": "Create an AtlasDB vectorstore from a raw documents.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nRun similarity search with AtlasDB\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\n__init__(name: str, embedding_function: Optional[Embeddings] = None, api_key: Optional[str] = None, description: str = 'A description for your project', is_public: bool = True, reset_project_if_exists: bool = False) \u2192 None[source]\u00b6\nInitialize the Atlas Client\nParameters\nname (str) \u2013 The name of your project. If the project already exists,\nit will be loaded.\nembedding_function (Optional[Embeddings]) \u2013 An optional function used for\nembedding your data. If None, data will be embedded with\nNomic\u2019s embed model.\napi_key (str) \u2013 Your nomic API key\ndescription (str) \u2013 A description for your project.\nis_public (bool) \u2013 Whether your project is publicly accessible.\nTrue by default.\nreset_project_if_exists (bool) \u2013 Whether to reset this project if it\nalready exists. Default False.\nGenerally useful during development and testing.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html"}
{"id": "6e2841983903-3", "text": "Run more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, refresh: bool = True, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts (Iterable[str]) \u2013 Texts to add to the vectorstore.\nmetadatas (Optional[List[dict]], optional) \u2013 Optional list of metadatas.\nids (Optional[List[str]]) \u2013 An optional list of ids.\nrefresh (bool) \u2013 Whether or not to refresh indices with the updated data.\nDefault True.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html"}
{"id": "6e2841983903-4", "text": "True if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html"}
{"id": "6e2841983903-5", "text": "lambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html"}
{"id": "6e2841983903-6", "text": "Return docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ncreate_index(**kwargs: Any) \u2192 Any[source]\u00b6\nCreates an index in your project.\nSee\nhttps://docs.nomic.ai/atlas_api.html#nomic.project.AtlasProject.create_index\nfor full detail.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html"}
{"id": "6e2841983903-7", "text": "False otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Optional[Embeddings] = None, ids: Optional[List[str]] = None, name: Optional[str] = None, api_key: Optional[str] = None, persist_directory: Optional[str] = None, description: str = 'A description for your project', is_public: bool = True, reset_project_if_exists: bool = False, index_kwargs: Optional[dict] = None, **kwargs: Any) \u2192 AtlasDB[source]\u00b6\nCreate an AtlasDB vectorstore from a list of documents.\nParameters\nname (str) \u2013 Name of the collection to create.\napi_key (str) \u2013 Your nomic API key,\ndocuments (List[Document]) \u2013 List of documents to add to the vectorstore.\nembedding (Optional[Embeddings]) \u2013 Embedding function. Defaults to None.\nids (Optional[List[str]]) \u2013 Optional list of document IDs. If None,\nids will be auto created\ndescription (str) \u2013 A description for your project.\nis_public (bool) \u2013 Whether your project is publicly accessible.\nTrue by default.\nreset_project_if_exists (bool) \u2013 Whether to reset this project if\nit already exists. Default False.\nGenerally useful during development and testing.\nindex_kwargs (Optional[dict]) \u2013 Dict of kwargs for index creation.\nSee https://docs.nomic.ai/atlas_api.html\nReturns\nNomic\u2019s neural database and finest rhizomatic instrument\nReturn type\nAtlasDB", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html"}
{"id": "6e2841983903-8", "text": "Returns\nNomic\u2019s neural database and finest rhizomatic instrument\nReturn type\nAtlasDB\nclassmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, name: Optional[str] = None, api_key: Optional[str] = None, description: str = 'A description for your project', is_public: bool = True, reset_project_if_exists: bool = False, index_kwargs: Optional[dict] = None, **kwargs: Any) \u2192 AtlasDB[source]\u00b6\nCreate an AtlasDB vectorstore from a raw documents.\nParameters\ntexts (List[str]) \u2013 The list of texts to ingest.\nname (str) \u2013 Name of the project to create.\napi_key (str) \u2013 Your nomic API key,\nembedding (Optional[Embeddings]) \u2013 Embedding function. Defaults to None.\nmetadatas (Optional[List[dict]]) \u2013 List of metadatas. Defaults to None.\nids (Optional[List[str]]) \u2013 Optional list of document IDs. If None,\nids will be auto created\ndescription (str) \u2013 A description for your project.\nis_public (bool) \u2013 Whether your project is publicly accessible.\nTrue by default.\nreset_project_if_exists (bool) \u2013 Whether to reset this project if it\nalready exists. Default False.\nGenerally useful during development and testing.\nindex_kwargs (Optional[dict]) \u2013 Dict of kwargs for index creation.\nSee https://docs.nomic.ai/atlas_api.html\nReturns\nNomic\u2019s neural database and finest rhizomatic instrument\nReturn type\nAtlasDB\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html"}
{"id": "6e2841983903-9", "text": "Return docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRun similarity search with AtlasDB\nParameters\nquery (str) \u2013 Query text to search for.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html"}
{"id": "6e2841983903-10", "text": "Parameters\nquery (str) \u2013 Query text to search for.\nk (int) \u2013 Number of results to return. Defaults to 4.\nReturns\nList of documents most similar to the query text.\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.\nExamples using AtlasDB\u00b6\nAtlas", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.atlas.AtlasDB.html"}
{"id": "6dedf2a3a213-0", "text": "langchain.vectorstores.hologres.Hologres\u00b6\nclass langchain.vectorstores.hologres.Hologres(connection_string: str, embedding_function: Embeddings, ndims: int = 1536, table_name: str = 'langchain_pg_embedding', pre_delete_table: bool = False, logger: Optional[Logger] = None)[source]\u00b6\nHologres API vector store.\nconnection_string is a hologres connection string.\nembedding_function any embedding function implementinglangchain.embeddings.base.Embeddings interface.\nndims is the number of dimensions of the embedding output.\ntable_name is the name of the table to store embeddings and data.(default: langchain_pg_embedding)\n- NOTE: The table will be created when initializing the store (if not exists)\nSo, make sure the user has the right permissions to create tables.\npre_delete_table if True, will delete the table if it exists.(default: False)\n- Useful for testing.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(connection_string,\u00a0embedding_function)\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_embeddings(texts,\u00a0embeddings,\u00a0metadatas,\u00a0...)\nAdd embeddings to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hologres.Hologres.html"}
{"id": "6dedf2a3a213-1", "text": "Return VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\nconnection_string_from_db_params(host,\u00a0port,\u00a0...)\nReturn connection string from database parameters.\ncreate_table()\ncreate_vector_extension()\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding[,\u00a0...])\nReturn VectorStore initialized from documents and embeddings.\nfrom_embeddings(text_embeddings,\u00a0embedding)\nConstruct Hologres wrapper from raw documents and pre- generated embeddings.\nfrom_existing_index(embedding[,\u00a0ndims,\u00a0...])\nGet instance of an existing Hologres store.This method will return the instance of the store without inserting any new embeddings\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nget_connection_string(kwargs)\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hologres.Hologres.html"}
{"id": "6dedf2a3a213-2", "text": "max_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nRun similarity search with Hologres with distance.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\nsimilarity_search_with_score_by_vector(embedding)\n__init__(connection_string: str, embedding_function: Embeddings, ndims: int = 1536, table_name: str = 'langchain_pg_embedding', pre_delete_table: bool = False, logger: Optional[Logger] = None) \u2192 None[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hologres.Hologres.html"}
{"id": "6dedf2a3a213-3", "text": "Run more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_embeddings(texts: Iterable[str], embeddings: List[List[float]], metadatas: List[dict], ids: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nAdd embeddings to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nembeddings \u2013 List of list of embedding vectors.\nmetadatas \u2013 List of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hologres.Hologres.html"}
{"id": "6dedf2a3a213-4", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hologres.Hologres.html"}
{"id": "6dedf2a3a213-5", "text": "Return type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hologres.Hologres.html"}
{"id": "6dedf2a3a213-6", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\nclassmethod connection_string_from_db_params(host: str, port: int, database: str, user: str, password: str) \u2192 str[source]\u00b6\nReturn connection string from database parameters.\ncreate_table() \u2192 None[source]\u00b6\ncreate_vector_extension() \u2192 None[source]\u00b6\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, ndims: int = 1536, table_name: str = 'langchain_pg_embedding', ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) \u2192 Hologres[source]\u00b6\nReturn VectorStore initialized from documents and embeddings.\nPostgres connection string is required\n\u201cEither pass it as a parameter\nor set the HOLOGRES_CONNECTION_STRING environment variable.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hologres.Hologres.html"}
{"id": "6dedf2a3a213-7", "text": "\u201cEither pass it as a parameter\nor set the HOLOGRES_CONNECTION_STRING environment variable.\nclassmethod from_embeddings(text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ndims: int = 1536, table_name: str = 'langchain_pg_embedding', ids: Optional[List[str]] = None, pre_delete_table: bool = False, **kwargs: Any) \u2192 Hologres[source]\u00b6\nConstruct Hologres wrapper from raw documents and pre-\ngenerated embeddings.\nReturn VectorStore initialized from documents and embeddings.\nPostgres connection string is required\n\u201cEither pass it as a parameter\nor set the HOLOGRES_CONNECTION_STRING environment variable.\nExample\nfrom langchain.vectorstores import Hologres\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\ntext_embeddings = embeddings.embed_documents(texts)\ntext_embedding_pairs = list(zip(texts, text_embeddings))\nfaiss = Hologres.from_embeddings(text_embedding_pairs, embeddings)\nclassmethod from_existing_index(embedding: Embeddings, ndims: int = 1536, table_name: str = 'langchain_pg_embedding', pre_delete_table: bool = False, **kwargs: Any) \u2192 Hologres[source]\u00b6\nGet instance of an existing Hologres store.This method will\nreturn the instance of the store without inserting any new\nembeddings\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ndims: int = 1536, table_name: str = 'langchain_pg_embedding', ids: Optional[List[str]] = None, pre_delete_table: bool = False, **kwargs: Any) \u2192 Hologres[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nPostgres connection string is required", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hologres.Hologres.html"}
{"id": "6dedf2a3a213-8", "text": "Return VectorStore initialized from texts and embeddings.\nPostgres connection string is required\n\u201cEither pass it as a parameter\nor set the HOLOGRES_CONNECTION_STRING environment variable.\nclassmethod get_connection_string(kwargs: Dict[str, Any]) \u2192 str[source]\u00b6\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hologres.Hologres.html"}
{"id": "6dedf2a3a213-9", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRun similarity search with Hologres with distance.\nParameters\nquery (str) \u2013 Query text to search for.\nk (int) \u2013 Number of results to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hologres.Hologres.html"}
{"id": "6dedf2a3a213-10", "text": "filter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[dict] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query and score for each\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nExamples using Hologres\u00b6\nHologres", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hologres.Hologres.html"}
{"id": "00b535d4daa5-0", "text": "langchain.vectorstores.elasticsearch.ApproxRetrievalStrategy\u00b6\nclass langchain.vectorstores.elasticsearch.ApproxRetrievalStrategy(query_model_id: Optional[str] = None, hybrid: Optional[bool] = False, rrf: Optional[Union[dict, bool]] = True)[source]\u00b6\nApproximate retrieval strategy using the HNSW algorithm.\nMethods\n__init__([query_model_id,\u00a0hybrid,\u00a0rrf])\nbefore_index_setup(client,\u00a0text_field,\u00a0...)\nExecutes before the index is created.\nindex(dims_length,\u00a0vector_query_field,\u00a0...)\nCreate the mapping for the Elasticsearch index.\nquery(query_vector,\u00a0query,\u00a0k,\u00a0fetch_k,\u00a0...)\nExecutes when a search is performed on the store.\nrequire_inference()\nReturns whether or not the strategy requires inference to be performed on the text before it is added to the index.\n__init__(query_model_id: Optional[str] = None, hybrid: Optional[bool] = False, rrf: Optional[Union[dict, bool]] = True)[source]\u00b6\nbefore_index_setup(client: Elasticsearch, text_field: str, vector_query_field: str) \u2192 None\u00b6\nExecutes before the index is created. Used for setting up\nany required Elasticsearch resources like a pipeline.\nParameters\nclient \u2013 The Elasticsearch client.\ntext_field \u2013 The field containing the text data in the index.\nvector_query_field \u2013 The field containing the vector\nrepresentations in the index.\nindex(dims_length: Optional[int], vector_query_field: str, similarity: Optional[DistanceStrategy]) \u2192 Dict[source]\u00b6\nCreate the mapping for the Elasticsearch index.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ApproxRetrievalStrategy.html"}
{"id": "00b535d4daa5-1", "text": "Create the mapping for the Elasticsearch index.\nquery(query_vector: Optional[List[float]], query: Optional[str], k: int, fetch_k: int, vector_query_field: str, text_field: str, filter: List[dict], similarity: Optional[DistanceStrategy]) \u2192 Dict[source]\u00b6\nExecutes when a search is performed on the store.\nParameters\nquery_vector \u2013 The query vector,\nor None if not using vector-based query.\nquery \u2013 The text query, or None if not using text-based query.\nk \u2013 The total number of results to retrieve.\nfetch_k \u2013 The number of results to fetch initially.\nvector_query_field \u2013 The field containing the vector\nrepresentations in the index.\ntext_field \u2013 The field containing the text data in the index.\nfilter \u2013 List of filter clauses to apply to the query.\nsimilarity \u2013 The similarity strategy to use, or None if not using one.\nReturns\nThe Elasticsearch query body.\nReturn type\nDict\nrequire_inference() \u2192 bool\u00b6\nReturns whether or not the strategy requires inference\nto be performed on the text before it is added to the index.\nReturns\nWhether or not the strategy requires inference\nto be performed on the text before it is added to the index.\nReturn type\nbool", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ApproxRetrievalStrategy.html"}
{"id": "8c1227208f52-0", "text": "langchain.vectorstores.clarifai.Clarifai\u00b6\nclass langchain.vectorstores.clarifai.Clarifai(user_id: Optional[str] = None, app_id: Optional[str] = None, pat: Optional[str] = None, number_of_docs: Optional[int] = None, api_base: Optional[str] = None)[source]\u00b6\nClarifai AI vector store.\nTo use, you should have the clarifai python package installed.\nExample\nfrom langchain.vectorstores import Clarifai\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nvectorstore = Clarifai(\"langchain_store\", embeddings.embed_query)\nInitialize with Clarifai client.\nParameters\nuser_id (Optional[str], optional) \u2013 User ID. Defaults to None.\napp_id (Optional[str], optional) \u2013 App ID. Defaults to None.\npat (Optional[str], optional) \u2013 Personal access token. Defaults to None.\nnumber_of_docs (Optional[int], optional) \u2013 Number of documents to return\nNone. (during vector search. Defaults to) \u2013 \napi_base (Optional[str], optional) \u2013 API base. Defaults to None.\nRaises\nValueError \u2013 If user ID, app ID or personal access token is not provided.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__([user_id,\u00a0app_id,\u00a0pat,\u00a0...])\nInitialize with Clarifai client.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clarifai.Clarifai.html"}
{"id": "8c1227208f52-1", "text": "Run more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nAdd texts to the Clarifai vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents[,\u00a0embedding,\u00a0...])\nCreate a Clarifai vectorstore from a list of documents.\nfrom_texts(texts[,\u00a0embedding,\u00a0metadatas,\u00a0...])\nCreate a Clarifai vectorstore from a list of texts.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clarifai.Clarifai.html"}
{"id": "8c1227208f52-2", "text": "max_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nRun similarity search using Clarifai.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nRun similarity search with score using Clarifai.\n__init__(user_id: Optional[str] = None, app_id: Optional[str] = None, pat: Optional[str] = None, number_of_docs: Optional[int] = None, api_base: Optional[str] = None) \u2192 None[source]\u00b6\nInitialize with Clarifai client.\nParameters\nuser_id (Optional[str], optional) \u2013 User ID. Defaults to None.\napp_id (Optional[str], optional) \u2013 App ID. Defaults to None.\npat (Optional[str], optional) \u2013 Personal access token. Defaults to None.\nnumber_of_docs (Optional[int], optional) \u2013 Number of documents to return\nNone. (during vector search. Defaults to) \u2013 \napi_base (Optional[str], optional) \u2013 API base. Defaults to None.\nRaises\nValueError \u2013 If user ID, app ID or personal access token is not provided.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clarifai.Clarifai.html"}
{"id": "8c1227208f52-3", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd texts to the Clarifai vectorstore. This will push the text\nto a Clarifai application.\nApplication use a base workflow that create and store embedding for each text.\nMake sure you are using a base workflow that is compatible with text\n(such as Language Understanding).\nParameters\ntexts (Iterable[str]) \u2013 Texts to add to the vectorstore.\nmetadatas (Optional[List[dict]], optional) \u2013 Optional list of metadatas.\nids (Optional[List[str]], optional) \u2013 Optional list of IDs.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clarifai.Clarifai.html"}
{"id": "8c1227208f52-4", "text": "False otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clarifai.Clarifai.html"}
{"id": "8c1227208f52-5", "text": "lambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clarifai.Clarifai.html"}
{"id": "8c1227208f52-6", "text": "Return docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Optional[Embeddings] = None, user_id: Optional[str] = None, app_id: Optional[str] = None, pat: Optional[str] = None, number_of_docs: Optional[int] = None, api_base: Optional[str] = None, **kwargs: Any) \u2192 Clarifai[source]\u00b6\nCreate a Clarifai vectorstore from a list of documents.\nParameters\nuser_id (str) \u2013 User ID.\napp_id (str) \u2013 App ID.\ndocuments (List[Document]) \u2013 List of documents to add.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clarifai.Clarifai.html"}
{"id": "8c1227208f52-7", "text": "documents (List[Document]) \u2013 List of documents to add.\npat (Optional[str]) \u2013 Personal access token. Defaults to None.\nnumber_of_docs (Optional[int]) \u2013 Number of documents to return\nNone. (during vector search. Defaults to) \u2013 \napi_base (Optional[str]) \u2013 API base. Defaults to None.\nReturns\nClarifai vectorstore.\nReturn type\nClarifai\nclassmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, user_id: Optional[str] = None, app_id: Optional[str] = None, pat: Optional[str] = None, number_of_docs: Optional[int] = None, api_base: Optional[str] = None, **kwargs: Any) \u2192 Clarifai[source]\u00b6\nCreate a Clarifai vectorstore from a list of texts.\nParameters\nuser_id (str) \u2013 User ID.\napp_id (str) \u2013 App ID.\ntexts (List[str]) \u2013 List of texts to add.\npat (Optional[str]) \u2013 Personal access token. Defaults to None.\nnumber_of_docs (Optional[int]) \u2013 Number of documents to return\nNone. (Defaults to) \u2013 \napi_base (Optional[str]) \u2013 API base. Defaults to None.\nmetadatas (Optional[List[dict]]) \u2013 Optional list of metadatas.\nNone. \u2013 \nReturns\nClarifai vectorstore.\nReturn type\nClarifai\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clarifai.Clarifai.html"}
{"id": "8c1227208f52-8", "text": "Maximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRun similarity search using Clarifai.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clarifai.Clarifai.html"}
{"id": "8c1227208f52-9", "text": "k \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query and score for each\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[dict] = None, namespace: Optional[str] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with score using Clarifai.\nParameters\nquery (str) \u2013 Query text to search for.\nk (int) \u2013 Number of results to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata.\nNone. (Defaults to) \u2013 \nReturns\nList of documents most similar to the query text.\nReturn type\nList[Document]\nExamples using Clarifai\u00b6\nClarifai", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.clarifai.Clarifai.html"}
{"id": "814fdc2c5c1f-0", "text": "langchain.vectorstores.usearch.dependable_usearch_import\u00b6\nlangchain.vectorstores.usearch.dependable_usearch_import() \u2192 Any[source]\u00b6\nImport usearch if available, otherwise raise error.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.usearch.dependable_usearch_import.html"}
{"id": "4e51e8e9a98f-0", "text": "langchain.vectorstores.redis.schema.FlatVectorField\u00b6\nclass langchain.vectorstores.redis.schema.FlatVectorField[source]\u00b6\nBases: RedisVectorField\nSchema for flat vector fields in Redis.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam algorithm: Literal['FLAT'] = 'FLAT'\u00b6\nparam block_size: Optional[int] = None\u00b6\nparam datatype: str = 'FLOAT32'\u00b6\nparam dims: int [Required]\u00b6\nparam distance_metric: langchain.vectorstores.redis.schema.RedisDistanceMetric = 'COSINE'\u00b6\nparam initial_cap: Optional[int] = None\u00b6\nparam name: str [Required]\u00b6\nas_field() \u2192 VectorField[source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.FlatVectorField.html"}
{"id": "4e51e8e9a98f-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.FlatVectorField.html"}
{"id": "4e51e8e9a98f-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.FlatVectorField.html"}
{"id": "3f91a4fa0123-0", "text": "langchain.vectorstores.tiledb.dependable_tiledb_import\u00b6\nlangchain.vectorstores.tiledb.dependable_tiledb_import() \u2192 Any[source]\u00b6\nImport tiledb-vector-search if available, otherwise raise error.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.dependable_tiledb_import.html"}
{"id": "8cda56f19dd4-0", "text": "langchain.vectorstores.bageldb.Bagel\u00b6\nclass langchain.vectorstores.bageldb.Bagel(cluster_name: str = 'langchain', client_settings: Optional[bagel.config.Settings] = None, embedding_function: Optional[Embeddings] = None, cluster_metadata: Optional[Dict] = None, client: Optional[bagel.Client] = None, relevance_score_fn: Optional[Callable[[float], float]] = None)[source]\u00b6\nBagelDB.ai vector store.\nTo use, you should have the betabageldb python package installed.\nExample\nfrom langchain.vectorstores import Bagel\nvectorstore = Bagel(cluster_name=\"langchain_store\")\nInitialize with bagel client\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__([cluster_name,\u00a0client_settings,\u00a0...])\nInitialize with bagel client\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0embeddings])\nAdd texts along with their corresponding embeddings and optional metadata to the BagelDB cluster.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.bageldb.Bagel.html"}
{"id": "8cda56f19dd4-1", "text": "Return docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by IDs.\ndelete_cluster()\nDelete the cluster.\nfrom_documents(documents[,\u00a0embedding,\u00a0ids,\u00a0...])\nCreate a Bagel vectorstore from a list of documents.\nfrom_texts(texts[,\u00a0embedding,\u00a0metadatas,\u00a0...])\nCreate and initialize a Bagel instance from list of texts.\nget([ids,\u00a0where,\u00a0limit,\u00a0offset,\u00a0...])\nGets the collection.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0where])\nRun a similarity search with BagelDB.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_by_vector_with_relevance_scores(...)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.bageldb.Bagel.html"}
{"id": "8cda56f19dd4-2", "text": "Return docs most similar to embedding vector.\nsimilarity_search_by_vector_with_relevance_scores(...)\nReturn docs most similar to embedding vector and similarity score.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0where])\nRun a similarity search with BagelDB and return documents with their corresponding similarity scores.\nupdate_document(document_id,\u00a0document)\nUpdate a document in the cluster.\n__init__(cluster_name: str = 'langchain', client_settings: Optional[bagel.config.Settings] = None, embedding_function: Optional[Embeddings] = None, cluster_metadata: Optional[Dict] = None, client: Optional[bagel.Client] = None, relevance_score_fn: Optional[Callable[[float], float]] = None) \u2192 None[source]\u00b6\nInitialize with bagel client\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.bageldb.Bagel.html"}
{"id": "8cda56f19dd4-3", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, embeddings: Optional[List[List[float]]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd texts along with their corresponding embeddings and optional\nmetadata to the BagelDB cluster.\nParameters\ntexts (Iterable[str]) \u2013 Texts to be added.\nembeddings (Optional[List[float]]) \u2013 List of embeddingvectors\nmetadatas (Optional[List[dict]]) \u2013 Optional list of metadatas.\nids (Optional[List[str]]) \u2013 List of unique ID for the texts.\nReturns\nList of unique ID representing the added texts.\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.bageldb.Bagel.html"}
{"id": "8cda56f19dd4-4", "text": "Return docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.bageldb.Bagel.html"}
{"id": "8cda56f19dd4-5", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.bageldb.Bagel.html"}
{"id": "8cda56f19dd4-6", "text": "Returns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDelete by IDs.\nParameters\nids \u2013 List of ids to delete.\ndelete_cluster() \u2192 None[source]\u00b6\nDelete the cluster.\nclassmethod from_documents(documents: List[Document], embedding: Optional[Embeddings] = None, ids: Optional[List[str]] = None, cluster_name: str = 'langchain', client_settings: Optional[bagel.config.Settings] = None, client: Optional[bagel.Client] = None, cluster_metadata: Optional[Dict] = None, **kwargs: Any) \u2192 Bagel[source]\u00b6\nCreate a Bagel vectorstore from a list of documents.\nParameters\ndocuments (List[Document]) \u2013 List of Document objects to add to the\nBagel vectorstore.\nembedding (Optional[List[float]]) \u2013 List of embedding.\nids (Optional[List[str]]) \u2013 List of IDs. Defaults to None.\ncluster_name (str) \u2013 The name of the BagelDB cluster.\nclient_settings (Optional[bagel.config.Settings]) \u2013 Client settings.\nclient (Optional[bagel.Client]) \u2013 Bagel client instance.\ncluster_metadata (Optional[Dict]) \u2013 Metadata associated with the\nBagel cluster. Defaults to None.\nReturns\nBagel vectorstore.\nReturn type\nBagel", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.bageldb.Bagel.html"}
{"id": "8cda56f19dd4-7", "text": "Returns\nBagel vectorstore.\nReturn type\nBagel\nclassmethod from_texts(texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, cluster_name: str = 'langchain', client_settings: Optional[bagel.config.Settings] = None, cluster_metadata: Optional[Dict] = None, client: Optional[bagel.Client] = None, text_embeddings: Optional[List[List[float]]] = None, **kwargs: Any) \u2192 Bagel[source]\u00b6\nCreate and initialize a Bagel instance from list of texts.\nParameters\ntexts (List[str]) \u2013 List of text content to be added.\ncluster_name (str) \u2013 The name of the BagelDB cluster.\nclient_settings (Optional[bagel.config.Settings]) \u2013 Client settings.\ncluster_metadata (Optional[Dict]) \u2013 Metadata of the cluster.\nembeddings (Optional[Embeddings]) \u2013 List of embedding.\nmetadatas (Optional[List[dict]]) \u2013 List of metadata.\nids (Optional[List[str]]) \u2013 List of unique ID. Defaults to None.\nclient (Optional[bagel.Client]) \u2013 Bagel client instance.\nReturns\nBagel vectorstore.\nReturn type\nBagel\nget(ids: Optional[OneOrMany[ID]] = None, where: Optional[Where] = None, limit: Optional[int] = None, offset: Optional[int] = None, where_document: Optional[WhereDocument] = None, include: Optional[List[str]] = None) \u2192 Dict[str, Any][source]\u00b6\nGets the collection.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.bageldb.Bagel.html"}
{"id": "8cda56f19dd4-8", "text": "Return docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 5, where: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRun a similarity search with BagelDB.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.bageldb.Bagel.html"}
{"id": "8cda56f19dd4-9", "text": "Run a similarity search with BagelDB.\nParameters\nquery (str) \u2013 The query text to search for similar documents/texts.\nk (int) \u2013 The number of results to return.\nwhere (Optional[Dict[str, str]]) \u2013 Metadata filters to narrow down.\nReturns\nList of documents objects representing\nthe documents most similar to the query text.\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 5, where: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nsimilarity_search_by_vector_with_relevance_scores(query_embeddings: List[float], k: int = 5, where: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to embedding vector and similarity score.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 5, where: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun a similarity search with BagelDB and return documents with their", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.bageldb.Bagel.html"}
{"id": "8cda56f19dd4-10", "text": "Run a similarity search with BagelDB and return documents with their\ncorresponding similarity scores.\nParameters\nquery (str) \u2013 The query text to search for similar documents.\nk (int) \u2013 The number of results to return.\nwhere (Optional[Dict[str, str]]) \u2013 Filter using metadata.\nReturns\nList of tuples, each containing a\nDocument object representing a similar document and its\ncorresponding similarity score.\nReturn type\nList[Tuple[Document, float]]\nupdate_document(document_id: str, document: Document) \u2192 None[source]\u00b6\nUpdate a document in the cluster.\nParameters\ndocument_id (str) \u2013 ID of the document to update.\ndocument (Document) \u2013 Document to update.\nExamples using Bagel\u00b6\nBagelDB", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.bageldb.Bagel.html"}
{"id": "cfea4caa65e0-0", "text": "langchain.vectorstores.momento_vector_index.MomentoVectorIndex\u00b6\nclass langchain.vectorstores.momento_vector_index.MomentoVectorIndex(embedding: Embeddings, client: PreviewVectorIndexClient, index_name: str = 'default', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, text_field: str = 'text', ensure_index_exists: bool = True, **kwargs: Any)[source]\u00b6\nMomento Vector Index (MVI) vector store.\nMomento Vector Index is a serverless vector index that can be used to store and\nsearch vectors. To use you should have the momento python package installed.\nExample\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import MomentoVectorIndex\nfrom momento import (\n    CredentialProvider,\n    PreviewVectorIndexClient,\n    VectorIndexConfigurations,\n)\nvectorstore = MomentoVectorIndex(\n    embedding=OpenAIEmbeddings(),\n    client=PreviewVectorIndexClient(\n        VectorIndexConfigurations.Default.latest(),\n        credential_provider=CredentialProvider.from_environment_variable(\n            \"MOMENTO_API_KEY\"\n        ),\n    ),\n    index_name=\"my-index\",\n)\nInitialize a Vector Store backed by Momento Vector Index.\nParameters\nembedding (Embeddings) \u2013 The embedding function to use.\nconfiguration (VectorIndexConfiguration) \u2013 The configuration to initialize\nthe Vector Index with.\ncredential_provider (CredentialProvider) \u2013 The credential provider to\nauthenticate the Vector Index with.\nindex_name (str, optional) \u2013 The name of the index to store the documents in.\nDefaults to \u201cdefault\u201d.\ndistance_strategy (DistanceStrategy, optional) \u2013 The distance strategy to\nuse. Defaults to DistanceStrategy.COSINE. If you select\nDistanceStrategy.EUCLIDEAN_DISTANCE, Momento uses the squared\nEuclidean distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.momento_vector_index.MomentoVectorIndex.html"}
{"id": "cfea4caa65e0-1", "text": "DistanceStrategy.EUCLIDEAN_DISTANCE, Momento uses the squared\nEuclidean distance.\ntext_field (str, optional) \u2013 The name of the metadata field to store the\noriginal text in. Defaults to \u201ctext\u201d.\nensure_index_exists (bool, optional) \u2013 Whether to ensure that the index\nexists before adding documents to it. Defaults to True.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding,\u00a0client[,\u00a0index_name,\u00a0...])\nInitialize a Vector Store backed by Momento Vector Index.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.momento_vector_index.MomentoVectorIndex.html"}
{"id": "cfea4caa65e0-2", "text": "asimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn the Vector Store initialized from texts and embeddings.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nSearch for similar documents to the query string.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nSearch for similar documents to the query vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nSearch for similar documents to the query string.\nsimilarity_search_with_score_by_vector(embedding)\nSearch for similar documents to the query vector.\n__init__(embedding: Embeddings, client: PreviewVectorIndexClient, index_name: str = 'default', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, text_field: str = 'text', ensure_index_exists: bool = True, **kwargs: Any)[source]\u00b6\nInitialize a Vector Store backed by Momento Vector Index.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.momento_vector_index.MomentoVectorIndex.html"}
{"id": "cfea4caa65e0-3", "text": "Initialize a Vector Store backed by Momento Vector Index.\nParameters\nembedding (Embeddings) \u2013 The embedding function to use.\nconfiguration (VectorIndexConfiguration) \u2013 The configuration to initialize\nthe Vector Index with.\ncredential_provider (CredentialProvider) \u2013 The credential provider to\nauthenticate the Vector Index with.\nindex_name (str, optional) \u2013 The name of the index to store the documents in.\nDefaults to \u201cdefault\u201d.\ndistance_strategy (DistanceStrategy, optional) \u2013 The distance strategy to\nuse. Defaults to DistanceStrategy.COSINE. If you select\nDistanceStrategy.EUCLIDEAN_DISTANCE, Momento uses the squared\nEuclidean distance.\ntext_field (str, optional) \u2013 The name of the metadata field to store the\noriginal text in. Defaults to \u201ctext\u201d.\nensure_index_exists (bool, optional) \u2013 Whether to ensure that the index\nexists before adding documents to it. Defaults to True.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.momento_vector_index.MomentoVectorIndex.html"}
{"id": "cfea4caa65e0-4", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts (Iterable[str]) \u2013 Iterable of strings to add to the vectorstore.\nmetadatas (Optional[List[dict]]) \u2013 Optional list of metadatas associated with\nthe texts.\nkwargs (Any) \u2013 Other optional parameters. Specifically:\nids (-) \u2013 List of ids to use for the texts.\nDefaults to None, in which case uuids are generated.\nReturns\nList of ids from adding the texts into the vectorstore.\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.momento_vector_index.MomentoVectorIndex.html"}
{"id": "cfea4caa65e0-5", "text": "Return docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.momento_vector_index.MomentoVectorIndex.html"}
{"id": "cfea4caa65e0-6", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.momento_vector_index.MomentoVectorIndex.html"}
{"id": "cfea4caa65e0-7", "text": "Returns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ID.\nParameters\nids (List[str]) \u2013 List of ids to delete.\nkwargs (Any) \u2013 Other optional parameters (unused)\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST[source]\u00b6\nReturn the Vector Store initialized from texts and embeddings.\nParameters\ncls (Type[VST]) \u2013 The Vector Store class to use to initialize\nthe Vector Store.\ntexts (List[str]) \u2013 The texts to initialize the Vector Store with.\nembedding (Embeddings) \u2013 The embedding function to use.\nmetadatas (Optional[List[dict]], optional) \u2013 The metadata associated with\nthe texts. Defaults to None.\nkwargs (Any) \u2013 Vector Store specific parameters. The following are forwarded\nto the Vector Store constructor and required:\nindex_name (-) \u2013 The name of the index to store the documents\nin. Defaults to \u201cdefault\u201d.\ntext_field (-) \u2013 The name of the metadata field to store the\noriginal text in. Defaults to \u201ctext\u201d.\ndistance_strategy (-) \u2013 The distance strategy to\nuse. Defaults to DistanceStrategy.COSINE. If you select", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.momento_vector_index.MomentoVectorIndex.html"}
{"id": "cfea4caa65e0-8", "text": "use. Defaults to DistanceStrategy.COSINE. If you select\nDistanceStrategy.EUCLIDEAN_DISTANCE, Momento uses the squared\nEuclidean distance.\nensure_index_exists (-) \u2013 Whether to ensure that the index\nexists before adding documents to it. Defaults to True.\nkey (Additionally you can either pass in a client or an API) \u2013 \nclient (-) \u2013 The Momento Vector Index client to use.\napi_key (-) \u2013 The configuration to use to initialize\nthe Vector Index with. Defaults to None. If None, the configuration\nis initialized from the environment variable MOMENTO_API_KEY.\nReturns\nMomento Vector Index vector store initialized from texts andembeddings.\nReturn type\nVST\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.momento_vector_index.MomentoVectorIndex.html"}
{"id": "cfea4caa65e0-9", "text": "Return docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nSearch for similar documents to the query string.\nParameters\nquery (str) \u2013 The query string to search for.\nk (int, optional) \u2013 The number of results to return. Defaults to 4.\nReturns\nA list of documents that are similar to the query.\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nSearch for similar documents to the query vector.\nParameters\nembedding (List[float]) \u2013 The query vector to search for.\nk (int, optional) \u2013 The number of results to return. Defaults to 4.\nReturns\nA list of documents that are similar to the query.\nReturn type\nList[Document]\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.momento_vector_index.MomentoVectorIndex.html"}
{"id": "cfea4caa65e0-10", "text": "Return docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nSearch for similar documents to the query string.\nParameters\nquery (str) \u2013 The query string to search for.\nk (int, optional) \u2013 The number of results to return. Defaults to 4.\nkwargs (Any) \u2013 Vector Store specific search parameters. The following are\nforwarded to the Momento Vector Index:\ntop_k (-) \u2013 The number of results to return.\nReturns\nA list of tuples of the form(Document, score).\nReturn type\nList[Tuple[Document, float]]\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nSearch for similar documents to the query vector.\nParameters\nembedding (List[float]) \u2013 The query vector to search for.\nk (int, optional) \u2013 The number of results to return. Defaults to 4.\nkwargs (Any) \u2013 Vector Store specific search parameters. The following are\nforwarded to the Momento Vector Index:\ntop_k (-) \u2013 The number of results to return.\nReturns\nA list of tuples of the form(Document, score).\nReturn type\nList[Tuple[Document, float]]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.momento_vector_index.MomentoVectorIndex.html"}
{"id": "dfdd8f1059a2-0", "text": "langchain.vectorstores.semadb.SemaDB\u00b6\nclass langchain.vectorstores.semadb.SemaDB(collection_name: str, vector_size: int, embedding: Embeddings, distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE, api_key: str = '')[source]\u00b6\nSemaDB vector store.\nThis vector store is a wrapper around the SemaDB database.\nExample\nfrom langchain.vectorstores import SemaDB\ndb = SemaDB('mycollection', 768, embeddings, DistanceStrategy.COSINE)\nInitialise the SemaDB vector store.\nAttributes\nBASE_URL\nHOST\nembeddings\nReturn the embeddings.\nheaders\nReturn the common headers.\nMethods\n__init__(collection_name,\u00a0vector_size,\u00a0embedding)\nInitialise the SemaDB vector store.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0batch_size])\nAdd texts to the vector store.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.semadb.SemaDB.html"}
{"id": "dfdd8f1059a2-1", "text": "Return docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ncreate_collection()\nCreates the corresponding collection in SemaDB.\ndelete([ids])\nDelete by vector ID or other criteria.\ndelete_collection()\nDeletes the corresponding collection in SemaDB.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nRun similarity search with distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.semadb.SemaDB.html"}
{"id": "dfdd8f1059a2-2", "text": "similarity_search_with_score(query[,\u00a0k])\nRun similarity search with distance.\n__init__(collection_name: str, vector_size: int, embedding: Embeddings, distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE, api_key: str = '')[source]\u00b6\nInitialise the SemaDB vector store.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, batch_size: int = 1000, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd texts to the vector store.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.semadb.SemaDB.html"}
{"id": "dfdd8f1059a2-3", "text": "False otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.semadb.SemaDB.html"}
{"id": "dfdd8f1059a2-4", "text": "lambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.semadb.SemaDB.html"}
{"id": "dfdd8f1059a2-5", "text": "Return docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ncreate_collection() \u2192 bool[source]\u00b6\nCreates the corresponding collection in SemaDB.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\ndelete_collection() \u2192 bool[source]\u00b6\nDeletes the corresponding collection in SemaDB.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.semadb.SemaDB.html"}
{"id": "dfdd8f1059a2-6", "text": "Return VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = '', vector_size: int = 0, api_key: str = '', distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE, **kwargs: Any) \u2192 SemaDB[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.semadb.SemaDB.html"}
{"id": "dfdd8f1059a2-7", "text": "fetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.semadb.SemaDB.html"}
{"id": "dfdd8f1059a2-8", "text": "Run similarity search with distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.semadb.SemaDB.html"}
{"id": "ea910d6e15a1-0", "text": "langchain.vectorstores.vearch.Vearch\u00b6\nclass langchain.vectorstores.vearch.Vearch(embedding_function: Embeddings, path_or_url: Optional[str] = None, table_name: str = 'langchain_vearch', db_name: str = 'cluster_client_db', flag: int = 1, **kwargs: Any)[source]\u00b6\nInitialize vearch vector store\nflag 1 for cluster,0 for standalone\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding_function[,\u00a0path_or_url,\u00a0...])\nInitialize vearch vector store flag 1 for cluster,0 for standalone\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nreturns\nList of ids from adding the texts into the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vearch.Vearch.html"}
{"id": "ea910d6e15a1-1", "text": "Return docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete the documents which have the specified ids.\nfrom_documents(documents,\u00a0embedding[,\u00a0...])\nReturn Vearch VectorStore\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn Vearch VectorStore\nget([ids])\nReturn docs according ids.\nload_local(embedding[,\u00a0path_or_url,\u00a0...])\nLoad the local specified table of standalone vearch.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nThe most k similar documents and scores of the specified query.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k])\nThe most k similar documents and scores of the specified query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vearch.Vearch.html"}
{"id": "ea910d6e15a1-2", "text": "The most k similar documents and scores of the specified query.\n__init__(embedding_function: Embeddings, path_or_url: Optional[str] = None, table_name: str = 'langchain_vearch', db_name: str = 'cluster_client_db', flag: int = 1, **kwargs: Any) \u2192 None[source]\u00b6\nInitialize vearch vector store\nflag 1 for cluster,0 for standalone\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vearch.Vearch.html"}
{"id": "ea910d6e15a1-3", "text": "Returns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vearch.Vearch.html"}
{"id": "ea910d6e15a1-4", "text": "lambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vearch.Vearch.html"}
{"id": "ea910d6e15a1-5", "text": "Return docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete the documents which have the specified ids.\nParameters\nids \u2013 The ids of the embedding vectors.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful.\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, path_or_url: Optional[str] = None, table_name: str = 'langchain_vearch', db_name: str = 'cluster_client_db', flag: int = 1, **kwargs: Any) \u2192 Vearch[source]\u00b6\nReturn Vearch VectorStore", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vearch.Vearch.html"}
{"id": "ea910d6e15a1-6", "text": "Return Vearch VectorStore\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, path_or_url: Optional[str] = None, table_name: str = 'langchain_vearch', db_name: str = 'cluster_client_db', flag: int = 1, **kwargs: Any) \u2192 Vearch[source]\u00b6\nReturn Vearch VectorStore\nget(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Dict[str, Document][source]\u00b6\nReturn docs according ids.\nParameters\nids \u2013 The ids of the embedding vectors.\nReturns\nDocuments which satisfy the input conditions.\nclassmethod load_local(embedding: Embeddings, path_or_url: Optional[str] = None, table_name: str = 'langchain_vearch', db_name: str = 'cluster_client_db', flag: int = 1, **kwargs: Any) \u2192 Vearch[source]\u00b6\nLoad the local specified table of standalone vearch.\n:returns: Success or failure of loading the local specified table\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vearch.Vearch.html"}
{"id": "ea910d6e15a1-7", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nThe most k similar documents and scores of the specified query.\n:param embeddings: embedding vector of the query.\n:param k: The k most similar documents to the text query.\n:param min_score: the score of similar documents to the text query\nReturns\nThe k most similar documents to the specified text query.\n0 is dissimilar, 1 is the most similar.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vearch.Vearch.html"}
{"id": "ea910d6e15a1-8", "text": "0 is dissimilar, 1 is the most similar.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nThe most k similar documents and scores of the specified query.\n:param embeddings: embedding vector of the query.\n:param k: The k most similar documents to the text query.\n:param min_score: the score of similar documents to the text query\nReturns\nThe k most similar documents to the specified text query.\n0 is dissimilar, 1 is the most similar.\nExamples using Vearch\u00b6\nVearch", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vearch.Vearch.html"}
{"id": "650992553e71-0", "text": "langchain.vectorstores.redis.schema.RedisVectorField\u00b6\nclass langchain.vectorstores.redis.schema.RedisVectorField[source]\u00b6\nBases: RedisField\nBase class for Redis vector fields.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam algorithm: object [Required]\u00b6\nparam datatype: str = 'FLOAT32'\u00b6\nparam dims: int [Required]\u00b6\nparam distance_metric: langchain.vectorstores.redis.schema.RedisDistanceMetric = 'COSINE'\u00b6\nparam initial_cap: Optional[int] = None\u00b6\nparam name: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.RedisVectorField.html"}
{"id": "650992553e71-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.RedisVectorField.html"}
{"id": "650992553e71-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.RedisVectorField.html"}
{"id": "443668ca5c99-0", "text": "langchain.vectorstores.utils.maximal_marginal_relevance\u00b6\nlangchain.vectorstores.utils.maximal_marginal_relevance(query_embedding: ndarray, embedding_list: list, lambda_mult: float = 0.5, k: int = 4) \u2192 List[int][source]\u00b6\nCalculate maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.utils.maximal_marginal_relevance.html"}
{"id": "ec31c323d41c-0", "text": "langchain.vectorstores.pgembedding.PGEmbedding\u00b6\nclass langchain.vectorstores.pgembedding.PGEmbedding(connection_string: str, embedding_function: Embeddings, collection_name: str = 'langchain', collection_metadata: Optional[dict] = None, pre_delete_collection: bool = False, logger: Optional[Logger] = None)[source]\u00b6\nPostgres with the pg_embedding extension as a vector store.\npg_embedding uses sequential scan by default. but you can create a HNSW index\nusing the create_hnsw_index method.\n- connection_string is a postgres connection string.\n- embedding_function any embedding function implementing\nlangchain.embeddings.base.Embeddings interface.\ncollection_name is the name of the collection to use. (default: langchain)\nNOTE: This is not the name of the table, but the name of the collection.The tables will be created when initializing the store (if not exists)\nSo, make sure the user has the right permissions to create tables.\ndistance_strategy is the distance strategy to use. (default: EUCLIDEAN)\nEUCLIDEAN is the euclidean distance.\npre_delete_collection if True, will delete the collection if it exists.(default: False)\n- Useful for testing.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(connection_string,\u00a0embedding_function)\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_embeddings(texts,\u00a0embeddings,\u00a0metadatas,\u00a0...)\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.PGEmbedding.html"}
{"id": "ec31c323d41c-1", "text": "add_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\nconnect()\ncreate_collection()\ncreate_hnsw_extension()\ncreate_hnsw_index([max_elements,\u00a0dims,\u00a0m,\u00a0...])\ncreate_tables_if_not_exists()\ndelete([ids])\nDelete by vector ID or other criteria.\ndelete_collection()\ndrop_tables()\nfrom_documents(documents,\u00a0embedding[,\u00a0...])\nReturn VectorStore initialized from documents and embeddings.\nfrom_embeddings(text_embeddings,\u00a0embedding)\nfrom_existing_index(embedding[,\u00a0...])\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.PGEmbedding.html"}
{"id": "ec31c323d41c-2", "text": "from_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nget_collection(session)\nget_connection_string(kwargs)\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nRun similarity search with distance.\nsimilarity_search_with_score_by_vector(embedding)\n__init__(connection_string: str, embedding_function: Embeddings, collection_name: str = 'langchain', collection_metadata: Optional[dict] = None, pre_delete_collection: bool = False, logger: Optional[Logger] = None) \u2192 None[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.PGEmbedding.html"}
{"id": "ec31c323d41c-3", "text": "Run more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_embeddings(texts: List[str], embeddings: List[List[float]], metadatas: List[dict], ids: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.PGEmbedding.html"}
{"id": "ec31c323d41c-4", "text": "Return VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.PGEmbedding.html"}
{"id": "ec31c323d41c-5", "text": ")\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.PGEmbedding.html"}
{"id": "ec31c323d41c-6", "text": "**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\nconnect() \u2192 Connection[source]\u00b6\ncreate_collection() \u2192 None[source]\u00b6\ncreate_hnsw_extension() \u2192 None[source]\u00b6\ncreate_hnsw_index(max_elements: int = 10000, dims: int = 1536, m: int = 8, ef_construction: int = 16, ef_search: int = 16) \u2192 None[source]\u00b6\ncreate_tables_if_not_exists() \u2192 None[source]\u00b6\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\ndelete_collection() \u2192 None[source]\u00b6\ndrop_tables() \u2192 None[source]\u00b6\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, collection_name: str = 'langchain', ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) \u2192 PGEmbedding[source]\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.PGEmbedding.html"}
{"id": "ec31c323d41c-7", "text": "Return VectorStore initialized from documents and embeddings.\nclassmethod from_embeddings(text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain', ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) \u2192 PGEmbedding[source]\u00b6\nclassmethod from_existing_index(embedding: Embeddings, collection_name: str = 'langchain', pre_delete_collection: bool = False, **kwargs: Any) \u2192 PGEmbedding[source]\u00b6\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain', ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) \u2192 PGEmbedding[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nget_collection(session: Session) \u2192 Optional[CollectionStore][source]\u00b6\nclassmethod get_connection_string(kwargs: Dict[str, Any]) \u2192 str[source]\u00b6\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.PGEmbedding.html"}
{"id": "ec31c323d41c-8", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.PGEmbedding.html"}
{"id": "ec31c323d41c-9", "text": "Returns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[dict] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with distance.\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nExamples using PGEmbedding\u00b6\nPostgres Embedding", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.PGEmbedding.html"}
{"id": "53a78777821d-0", "text": "langchain.vectorstores.redis.schema.NumericFieldSchema\u00b6\nclass langchain.vectorstores.redis.schema.NumericFieldSchema[source]\u00b6\nBases: RedisField\nSchema for numeric fields in Redis.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam name: str [Required]\u00b6\nparam no_index: bool = False\u00b6\nparam sortable: Optional[bool] = False\u00b6\nas_field() \u2192 NumericField[source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.NumericFieldSchema.html"}
{"id": "53a78777821d-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.NumericFieldSchema.html"}
{"id": "53a78777821d-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.NumericFieldSchema.html"}
{"id": "f9253236cb33-0", "text": "langchain.vectorstores.redis.base.RedisVectorStoreRetriever\u00b6\nclass langchain.vectorstores.redis.base.RedisVectorStoreRetriever[source]\u00b6\nBases: VectorStoreRetriever\nRetriever for Redis VectorStore.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam search_kwargs: Dict[str, Any] = {'distance_threshold': None, 'k': 4, 'score_threshold': 0.9}\u00b6\nDefault search kwargs.\nparam search_type: str = 'similarity'\u00b6\nType of search to perform. Can be either\n\u2018similarity\u2019,\n\u2018similarity_distance_threshold\u2019,\n\u2018similarity_score_threshold\u2019\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam vectorstore: Redis [Required]\u00b6\nRedis VectorStore.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd documents to vectorstore.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.RedisVectorStoreRetriever.html"}
{"id": "f9253236cb33-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd documents to vectorstore.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.RedisVectorStoreRetriever.html"}
{"id": "f9253236cb33-2", "text": "Default implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.RedisVectorStoreRetriever.html"}
{"id": "f9253236cb33-3", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.RedisVectorStoreRetriever.html"}
{"id": "f9253236cb33-4", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.RedisVectorStoreRetriever.html"}
{"id": "f9253236cb33-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.RedisVectorStoreRetriever.html"}
{"id": "f9253236cb33-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.RedisVectorStoreRetriever.html"}
{"id": "f9253236cb33-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.RedisVectorStoreRetriever.html"}
{"id": "f9253236cb33-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.RedisVectorStoreRetriever.html"}
{"id": "f9253236cb33-9", "text": "The type of output this runnable produces specified as a type annotation.\nallowed_search_types: ClassVar[Collection[str]] = ['similarity', 'similarity_distance_threshold', 'similarity_score_threshold', 'mmr']\u00b6\nAllowed search types.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.base.RedisVectorStoreRetriever.html"}
{"id": "29a7a100cfeb-0", "text": "langchain.vectorstores.redis.filters.check_operator_misuse\u00b6\nlangchain.vectorstores.redis.filters.check_operator_misuse(func: Callable) \u2192 Callable[source]\u00b6\nDecorator to check for misuse of equality operators.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.filters.check_operator_misuse.html"}
{"id": "e8d96ab41cfd-0", "text": "langchain.vectorstores.redis.schema.RedisDistanceMetric\u00b6\nclass langchain.vectorstores.redis.schema.RedisDistanceMetric(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nDistance metrics for Redis vector fields.\nl2 = 'L2'\u00b6\ncosine = 'COSINE'\u00b6\nip = 'IP'\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.RedisDistanceMetric.html"}
{"id": "ab0f915fcc9a-0", "text": "langchain.vectorstores.pinecone.Pinecone\u00b6\nclass langchain.vectorstores.pinecone.Pinecone(index: Any, embedding: Union[Embeddings, Callable], text_key: str, namespace: Optional[str] = None, distance_strategy: Optional[DistanceStrategy] = DistanceStrategy.COSINE)[source]\u00b6\nPinecone vector store.\nTo use, you should have the pinecone-client python package installed.\nExample\nfrom langchain.vectorstores import Pinecone\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nimport pinecone\n# The environment should be the one specified next to the API key\n# in your Pinecone console\npinecone.init(api_key=\"***\", environment=\"...\")\nindex = pinecone.Index(\"langchain-demo\")\nembeddings = OpenAIEmbeddings()\nvectorstore = Pinecone(index, embeddings.embed_query, \"text\")\nInitialize with Pinecone client.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(index,\u00a0embedding,\u00a0text_key[,\u00a0...])\nInitialize with Pinecone client.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids,\u00a0...])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pinecone.Pinecone.html"}
{"id": "ab0f915fcc9a-1", "text": "afrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids,\u00a0delete_all,\u00a0namespace,\u00a0filter])\nDelete by vector IDs or filter.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_existing_index(index_name,\u00a0embedding[,\u00a0...])\nLoad pinecone vectorstore from index name.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nConstruct Pinecone wrapper from raw documents.\nget_pinecone_index(index_name[,\u00a0pool_threads])\nReturn a Pinecone Index instance.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pinecone.Pinecone.html"}
{"id": "ab0f915fcc9a-2", "text": "Return docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter,\u00a0namespace])\nReturn pinecone documents most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_by_vector_with_score(...)\nReturn pinecone documents most similar to embedding, along with scores.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nReturn pinecone documents most similar to query, along with scores.\n__init__(index: Any, embedding: Union[Embeddings, Callable], text_key: str, namespace: Optional[str] = None, distance_strategy: Optional[DistanceStrategy] = DistanceStrategy.COSINE)[source]\u00b6\nInitialize with Pinecone client.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pinecone.Pinecone.html"}
{"id": "ab0f915fcc9a-3", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, namespace: Optional[str] = None, batch_size: int = 32, embedding_chunk_size: int = 1000, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nUpsert optimization is done by chunking the embeddings and upserting them.\nThis is done to avoid memory issues and optimize using HTTP based embeddings.\nFor OpenAI embeddings, use pool_threads>4 when constructing the pinecone.Index,\nembedding_chunk_size>1000 and batch_size~64 for best performance.\n:param texts: Iterable of strings to add to the vectorstore.\n:param metadatas: Optional list of metadatas associated with the texts.\n:param ids: Optional list of ids to associate with the texts.\n:param namespace: Optional pinecone namespace to add the texts to.\n:param batch_size: Batch size to use when adding the texts to the vectorstore.\n:param embedding_chunk_size: Chunk size to use when embedding the texts.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pinecone.Pinecone.html"}
{"id": "ab0f915fcc9a-4", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pinecone.Pinecone.html"}
{"id": "ab0f915fcc9a-5", "text": "Return type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pinecone.Pinecone.html"}
{"id": "ab0f915fcc9a-6", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, delete_all: Optional[bool] = None, namespace: Optional[str] = None, filter: Optional[dict] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDelete by vector IDs or filter.\n:param ids: List of ids to delete.\n:param filter: Dictionary of conditions to filter vectors to delete.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_existing_index(index_name: str, embedding: Embeddings, text_key: str = 'text', namespace: Optional[str] = None, pool_threads: int = 4) \u2192 Pinecone[source]\u00b6\nLoad pinecone vectorstore from index name.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pinecone.Pinecone.html"}
{"id": "ab0f915fcc9a-7", "text": "Load pinecone vectorstore from index name.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, batch_size: int = 32, text_key: str = 'text', namespace: Optional[str] = None, index_name: Optional[str] = None, upsert_kwargs: Optional[dict] = None, pool_threads: int = 4, embeddings_chunk_size: int = 1000, **kwargs: Any) \u2192 Pinecone[source]\u00b6\nConstruct Pinecone wrapper from raw documents.\nThis is a user friendly interface that:\nEmbeds documents.\nAdds the documents to a provided Pinecone index\nThis is intended to be a quick way to get started.\nThe pool_threads affects the speed of the upsert operations.\n.. rubric:: Example\nfrom langchain.vectorstores import Pinecone\nfrom langchain.embeddings import OpenAIEmbeddings\nimport pinecone\n# The environment should be the one specified next to the API key\n# in your Pinecone console\npinecone.init(api_key=\"***\", environment=\"...\")\nembeddings = OpenAIEmbeddings()\npinecone = Pinecone.from_texts(\n    texts,\n    embeddings,\n    index_name=\"langchain-demo\"\n)\nclassmethod get_pinecone_index(index_name: Optional[str], pool_threads: int = 4) \u2192 Index[source]\u00b6\nReturn a Pinecone Index instance.\nParameters\nindex_name \u2013 Name of the index to use.\npool_threads \u2013 Number of threads to use for index upsert.\nReturns\nPinecone Index instance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pinecone.Pinecone.html"}
{"id": "ab0f915fcc9a-8", "text": "Returns\nPinecone Index instance.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[dict] = None, namespace: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[dict] = None, namespace: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pinecone.Pinecone.html"}
{"id": "ab0f915fcc9a-9", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[dict] = None, namespace: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn pinecone documents most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Dictionary of argument(s) to filter on metadata\nnamespace \u2013 Namespace to search in. Default will search in \u2018\u2019 namespace.\nReturns\nList of Documents most similar to the query and score for each\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_by_vector_with_score(embedding: List[float], *, k: int = 4, filter: Optional[dict] = None, namespace: Optional[str] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn pinecone documents most similar to embedding, along with scores.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pinecone.Pinecone.html"}
{"id": "ab0f915fcc9a-10", "text": "0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[dict] = None, namespace: Optional[str] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn pinecone documents most similar to query, along with scores.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 Dictionary of argument(s) to filter on metadata\nnamespace \u2013 Namespace to search in. Default will search in \u2018\u2019 namespace.\nReturns\nList of Documents most similar to the query and score for each\nExamples using Pinecone\u00b6\nPinecone", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pinecone.Pinecone.html"}
{"id": "50129d359b3d-0", "text": "langchain.vectorstores.utils.DistanceStrategy\u00b6\nclass langchain.vectorstores.utils.DistanceStrategy(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnumerator of the Distance strategies for calculating distances\nbetween vectors.\nEUCLIDEAN_DISTANCE = 'EUCLIDEAN_DISTANCE'\u00b6\nMAX_INNER_PRODUCT = 'MAX_INNER_PRODUCT'\u00b6\nDOT_PRODUCT = 'DOT_PRODUCT'\u00b6\nJACCARD = 'JACCARD'\u00b6\nCOSINE = 'COSINE'\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.utils.DistanceStrategy.html"}
{"id": "46ec4f771cdc-0", "text": "langchain.vectorstores.neo4j_vector.sort_by_index_name\u00b6\nlangchain.vectorstores.neo4j_vector.sort_by_index_name(lst: List[Dict[str, Any]], index_name: str) \u2192 List[Dict[str, Any]][source]\u00b6\nSort first element to match the index_name if exists", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.neo4j_vector.sort_by_index_name.html"}
{"id": "982762b7183b-0", "text": "langchain.vectorstores.tiledb.get_documents_array_uri_from_group\u00b6\nlangchain.vectorstores.tiledb.get_documents_array_uri_from_group(group: Any) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.get_documents_array_uri_from_group.html"}
{"id": "5d1649a84fe7-0", "text": "langchain.vectorstores.meilisearch.Meilisearch\u00b6\nclass langchain.vectorstores.meilisearch.Meilisearch(embedding: Embeddings, client: Optional[Client] = None, url: Optional[str] = None, api_key: Optional[str] = None, index_name: str = 'langchain-demo', text_key: str = 'text', metadata_key: str = 'metadata')[source]\u00b6\nMeilisearch vector store.\nTo use this, you need to have meilisearch python package installed,\nand a running Meilisearch instance.\nTo learn more about Meilisearch Python, refer to the in-depth\nMeilisearch Python documentation: https://meilisearch.github.io/meilisearch-python/.\nSee the following documentation for how to run a Meilisearch instance:\nhttps://www.meilisearch.com/docs/learn/getting_started/quick_start.\nExample\nfrom langchain.vectorstores import Meilisearch\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nimport meilisearch\n# api_key is optional; provide it if your meilisearch instance requires it\nclient = meilisearch.Client(url='http://127.0.0.1:7700', api_key='***')\nembeddings = OpenAIEmbeddings()\nvectorstore = Meilisearch(\n    embedding=embeddings,\n    client=client,\n    index_name='langchain_demo',\n    text_key='text')\nInitialize with Meilisearch client.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding[,\u00a0client,\u00a0url,\u00a0api_key,\u00a0...])\nInitialize with Meilisearch client.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.meilisearch.Meilisearch.html"}
{"id": "5d1649a84fe7-1", "text": "Run more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embedding and add them to the vector store.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.meilisearch.Meilisearch.html"}
{"id": "5d1649a84fe7-2", "text": "from_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nConstruct Meilisearch wrapper from raw documents.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nReturn meilisearch documents most similar to the query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn meilisearch documents most similar to embedding vector.\nsimilarity_search_by_vector_with_scores(...)\nReturn meilisearch documents most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nReturn meilisearch documents most similar to the query, along with scores.\n__init__(embedding: Embeddings, client: Optional[Client] = None, url: Optional[str] = None, api_key: Optional[str] = None, index_name: str = 'langchain-demo', text_key: str = 'text', metadata_key: str = 'metadata')[source]\u00b6\nInitialize with Meilisearch client.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.meilisearch.Meilisearch.html"}
{"id": "5d1649a84fe7-3", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embedding and add them to the vector store.\nParameters\ntexts (Iterable[str]) \u2013 Iterable of strings/text to add to the vectorstore.\nmetadatas (Optional[List[dict]]) \u2013 Optional list of metadata.\nDefaults to None.\nOptional[List[str]] (ids) \u2013 Optional list of IDs.\nDefaults to None.\nReturns\nList of IDs of the texts added to the vectorstore.\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.meilisearch.Meilisearch.html"}
{"id": "5d1649a84fe7-4", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.meilisearch.Meilisearch.html"}
{"id": "5d1649a84fe7-5", "text": "Return type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.meilisearch.Meilisearch.html"}
{"id": "5d1649a84fe7-6", "text": "Return docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, client: Optional[Client] = None, url: Optional[str] = None, api_key: Optional[str] = None, index_name: str = 'langchain-demo', ids: Optional[List[str]] = None, text_key: Optional[str] = 'text', metadata_key: Optional[str] = 'metadata', **kwargs: Any) \u2192 Meilisearch[source]\u00b6\nConstruct Meilisearch wrapper from raw documents.\nThis is a user-friendly interface that:\nEmbeds documents.\nAdds the documents to a provided Meilisearch index.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.meilisearch.Meilisearch.html"}
{"id": "5d1649a84fe7-7", "text": "Embeds documents.\nAdds the documents to a provided Meilisearch index.\nThis is intended to be a quick way to get started.\nExample\nfrom langchain.vectorstores import Meilisearch\nfrom langchain.embeddings import OpenAIEmbeddings\nimport meilisearch\n# The environment should be the one specified next to the API key\n# in your Meilisearch console\nclient = meilisearch.Client(url='http://127.0.0.1:7700', api_key='***')\nembeddings = OpenAIEmbeddings()\ndocsearch = Meilisearch.from_texts(\n    client=client,\n    embeddings=embeddings,\n)\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.meilisearch.Meilisearch.html"}
{"id": "5d1649a84fe7-8", "text": "Maximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn meilisearch documents most similar to the query.\nParameters\nquery (str) \u2013 Query text for which to find similar documents.\nk (int) \u2013 Number of documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata.\nDefaults to None.\nReturns\nList of Documents most similar to the query\ntext and score for each.\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn meilisearch documents most similar to embedding vector.\nParameters\nembedding (List[float]) \u2013 Embedding to look up similar documents.\nk (int) \u2013 Number of documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata.\nDefaults to None.\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.meilisearch.Meilisearch.html"}
{"id": "5d1649a84fe7-9", "text": "Defaults to None.\nReturns\nList of Documents most similar to the queryvector and score for each.\nReturn type\nList[Document]\nsimilarity_search_by_vector_with_scores(embedding: List[float], k: int = 4, filter: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn meilisearch documents most similar to embedding vector.\nParameters\nembedding (List[float]) \u2013 Embedding to look up similar documents.\nk (int) \u2013 Number of documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata.\nDefaults to None.\nReturns\nList of Documents most similar to the queryvector and score for each.\nReturn type\nList[Document]\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[Dict[str, str]] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn meilisearch documents most similar to the query, along with scores.\nParameters\nquery (str) \u2013 Query text for which to find similar documents.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.meilisearch.Meilisearch.html"}
{"id": "5d1649a84fe7-10", "text": "Parameters\nquery (str) \u2013 Query text for which to find similar documents.\nk (int) \u2013 Number of documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata.\nDefaults to None.\nReturns\nList of Documents most similar to the query\ntext and score for each.\nReturn type\nList[Document]\nExamples using Meilisearch\u00b6\nMeilisearch", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.meilisearch.Meilisearch.html"}
{"id": "3e75efd417f0-0", "text": "langchain.vectorstores.pgembedding.BaseModel\u00b6\nclass langchain.vectorstores.pgembedding.BaseModel(**kwargs: Any)[source]\u00b6\nBase model for all SQL stores.\nA simple constructor that allows initialization from kwargs.\nSets attributes on the constructed instance using the names and\nvalues in kwargs.\nOnly keys that are present as\nattributes of the instance\u2019s class are allowed. These could be,\nfor example, any mapped columns or relationships.\nAttributes\nmetadata\nregistry\nuuid\nMethods\n__init__(**kwargs)\nA simple constructor that allows initialization from kwargs.\n__init__(**kwargs: Any) \u2192 None\u00b6\nA simple constructor that allows initialization from kwargs.\nSets attributes on the constructed instance using the names and\nvalues in kwargs.\nOnly keys that are present as\nattributes of the instance\u2019s class are allowed. These could be,\nfor example, any mapped columns or relationships.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.BaseModel.html"}
{"id": "30140726d7bb-0", "text": "langchain.vectorstores.epsilla.Epsilla\u00b6\nclass langchain.vectorstores.epsilla.Epsilla(client: Any, embeddings: Embeddings, db_path: Optional[str] = '/tmp/langchain-epsilla', db_name: Optional[str] = 'langchain_store')[source]\u00b6\nWrapper around Epsilla vector database.\nAs a prerequisite, you need to install pyepsilla package\nand have a running Epsilla vector database (for example, through our docker image)\nSee the following documentation for how to run an Epsilla vector database:\nhttps://epsilla-inc.gitbook.io/epsilladb/quick-start\nParameters\nclient (Any) \u2013 Epsilla client to connect to.\nembeddings (Embeddings) \u2013 Function used to embed the texts.\ndb_path (Optional[str]) \u2013 The path where the database will be persisted.\nDefaults to \u201c/tmp/langchain-epsilla\u201d.\ndb_name (Optional[str]) \u2013 Give a name to the loaded database.\nDefaults to \u201clangchain_store\u201d.\nExample\nfrom langchain.vectorstores import Epsilla\nfrom pyepsilla import vectordb\nclient = vectordb.Client()\nembeddings = OpenAIEmbeddings()\ndb_path = \"/tmp/vectorstore\"\ndb_name = \"langchain_store\"\nepsilla = Epsilla(client, embeddings, db_path, db_name)\nInitialize with necessary components.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(client,\u00a0embeddings[,\u00a0db_path,\u00a0db_name])\nInitialize with necessary components.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.epsilla.Epsilla.html"}
{"id": "30140726d7bb-1", "text": "add_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0...])\nEmbed texts and add them to the database.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\nclear_data([collection_name])\nClear data in a collection.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding[,\u00a0...])\nCreate an Epsilla vectorstore from a list of documents.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreate an Epsilla vectorstore from raw documents.\nget([collection_name,\u00a0response_fields])\nGet the collection.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.epsilla.Epsilla.html"}
{"id": "30140726d7bb-2", "text": "get([collection_name,\u00a0response_fields])\nGet the collection.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0collection_name])\nReturn the documents that are semantically most relevant to the query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\nuse_collection(collection_name)\nSet default collection to use.\n__init__(client: Any, embeddings: Embeddings, db_path: Optional[str] = '/tmp/langchain-epsilla', db_name: Optional[str] = 'langchain_store')[source]\u00b6\nInitialize with necessary components.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.epsilla.Epsilla.html"}
{"id": "30140726d7bb-3", "text": "Run more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, collection_name: Optional[str] = '', drop_old: Optional[bool] = False, **kwargs: Any) \u2192 List[str][source]\u00b6\nEmbed texts and add them to the database.\nParameters\ntexts (Iterable[str]) \u2013 The texts to embed.\nmetadatas (Optional[List[dict]]) \u2013 Metadata dicts\nattached to each of the texts. Defaults to None.\ncollection_name (Optional[str]) \u2013 Which collection to use.\nDefaults to \u201clangchain_collection\u201d.\nIf provided, default collection name will be set as well.\ndrop_old (Optional[bool]) \u2013 Whether to drop the previous collection\nand create a new one. Defaults to False.\nReturns\nList of ids of the added texts.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.epsilla.Epsilla.html"}
{"id": "30140726d7bb-4", "text": "Return VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.epsilla.Epsilla.html"}
{"id": "30140726d7bb-5", "text": ")\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.epsilla.Epsilla.html"}
{"id": "30140726d7bb-6", "text": "**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\nclear_data(collection_name: str = '') \u2192 None[source]\u00b6\nClear data in a collection.\nParameters\ncollection_name (Optional[str]) \u2013 The name of the collection.\nIf not provided, the default collection will be used.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, client: Any = None, db_path: Optional[str] = '/tmp/langchain-epsilla', db_name: Optional[str] = 'langchain_store', collection_name: Optional[str] = 'langchain_collection', drop_old: Optional[bool] = False, **kwargs: Any) \u2192 Epsilla[source]\u00b6\nCreate an Epsilla vectorstore from a list of documents.\nParameters\ntexts (List[str]) \u2013 List of text data to be inserted.\nembeddings (Embeddings) \u2013 Embedding function.\nclient (pyepsilla.vectordb.Client) \u2013 Epsilla client to connect to.\nmetadatas (Optional[List[dict]]) \u2013 Metadata for each text.\nDefaults to None.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.epsilla.Epsilla.html"}
{"id": "30140726d7bb-7", "text": "Defaults to None.\ndb_path (Optional[str]) \u2013 The path where the database will be persisted.\nDefaults to \u201c/tmp/langchain-epsilla\u201d.\ndb_name (Optional[str]) \u2013 Give a name to the loaded database.\nDefaults to \u201clangchain_store\u201d.\ncollection_name (Optional[str]) \u2013 Which collection to use.\nDefaults to \u201clangchain_collection\u201d.\nIf provided, default collection name will be set as well.\ndrop_old (Optional[bool]) \u2013 Whether to drop the previous collection\nand create a new one. Defaults to False.\nReturns\nEpsilla vector store.\nReturn type\nEpsilla\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, client: Any = None, db_path: Optional[str] = '/tmp/langchain-epsilla', db_name: Optional[str] = 'langchain_store', collection_name: Optional[str] = 'langchain_collection', drop_old: Optional[bool] = False, **kwargs: Any) \u2192 Epsilla[source]\u00b6\nCreate an Epsilla vectorstore from raw documents.\nParameters\ntexts (List[str]) \u2013 List of text data to be inserted.\nembeddings (Embeddings) \u2013 Embedding function.\nclient (pyepsilla.vectordb.Client) \u2013 Epsilla client to connect to.\nmetadatas (Optional[List[dict]]) \u2013 Metadata for each text.\nDefaults to None.\ndb_path (Optional[str]) \u2013 The path where the database will be persisted.\nDefaults to \u201c/tmp/langchain-epsilla\u201d.\ndb_name (Optional[str]) \u2013 Give a name to the loaded database.\nDefaults to \u201clangchain_store\u201d.\ncollection_name (Optional[str]) \u2013 Which collection to use.\nDefaults to \u201clangchain_collection\u201d.\nIf provided, default collection name will be set as well.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.epsilla.Epsilla.html"}
{"id": "30140726d7bb-8", "text": "If provided, default collection name will be set as well.\ndrop_old (Optional[bool]) \u2013 Whether to drop the previous collection\nand create a new one. Defaults to False.\nReturns\nEpsilla vector store.\nReturn type\nEpsilla\nget(collection_name: str = '', response_fields: Optional[List[str]] = None) \u2192 List[dict][source]\u00b6\nGet the collection.\nParameters\ncollection_name (Optional[str]) \u2013 The name of the collection\nto retrieve data from.\nIf not provided, the default collection will be used.\nresponse_fields (Optional[List[str]]) \u2013 List of field names in the result.\nIf not specified, all available fields will be responded.\nReturns\nA list of the retrieved data.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.epsilla.Epsilla.html"}
{"id": "30140726d7bb-9", "text": "Return docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, collection_name: str = '', **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn the documents that are semantically most relevant to the query.\nParameters\nquery (str) \u2013 String to query the vectorstore with.\nk (Optional[int]) \u2013 Number of documents to return. Defaults to 4.\ncollection_name (Optional[str]) \u2013 Collection to use.\nDefaults to \u201clangchain_store\u201d or the one provided before.\nReturns\nList of documents that are semantically most relevant to the query\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.epsilla.Epsilla.html"}
{"id": "30140726d7bb-10", "text": "Return docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance.\nuse_collection(collection_name: str) \u2192 None[source]\u00b6\nSet default collection to use.\nParameters\ncollection_name (str) \u2013 The name of the collection.\nExamples using Epsilla\u00b6\nEpsilla", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.epsilla.Epsilla.html"}
{"id": "f14366b30c8a-0", "text": "langchain.vectorstores.hologres.HologresWrapper\u00b6\nclass langchain.vectorstores.hologres.HologresWrapper(connection_string: str, ndims: int, table_name: str)[source]\u00b6\nHologres API wrapper.\nInitialize the wrapper.\nParameters\nconnection_string \u2013 Hologres connection string.\nndims \u2013 Number of dimensions of the embedding output.\ntable_name \u2013 Name of the table to store embeddings and data.\nMethods\n__init__(connection_string,\u00a0ndims,\u00a0table_name)\nInitialize the wrapper.\ncreate_table([drop_if_exist])\ncreate_vector_extension()\nget_by_id(id)\ninsert(embedding,\u00a0metadata,\u00a0document[,\u00a0id])\nquery_nearest_neighbours(embedding,\u00a0k[,\u00a0filter])\n__init__(connection_string: str, ndims: int, table_name: str) \u2192 None[source]\u00b6\nInitialize the wrapper.\nParameters\nconnection_string \u2013 Hologres connection string.\nndims \u2013 Number of dimensions of the embedding output.\ntable_name \u2013 Name of the table to store embeddings and data.\ncreate_table(drop_if_exist: bool = True) \u2192 None[source]\u00b6\ncreate_vector_extension() \u2192 None[source]\u00b6\nget_by_id(id: str) \u2192 List[Tuple][source]\u00b6\ninsert(embedding: List[float], metadata: dict, document: str, id: Optional[str] = None) \u2192 None[source]\u00b6\nquery_nearest_neighbours(embedding: List[float], k: int, filter: Optional[Dict[str, str]] = None) \u2192 List[Tuple[str, str, float]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hologres.HologresWrapper.html"}
{"id": "21163b24a73a-0", "text": "langchain.vectorstores.qdrant.sync_call_fallback\u00b6\nlangchain.vectorstores.qdrant.sync_call_fallback(method: Callable) \u2192 Callable[source]\u00b6\nDecorator to call the synchronous method of the class if the async method is not\nimplemented. This decorator might be only used for the methods that are defined\nas async in the class.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.qdrant.sync_call_fallback.html"}
{"id": "20c2c57da2eb-0", "text": "langchain.vectorstores.redis.filters.RedisFilter\u00b6\nclass langchain.vectorstores.redis.filters.RedisFilter[source]\u00b6\nCollection of RedisFilterFields.\nMethods\n__init__()\nnum(field)\ntag(field)\ntext(field)\n__init__()\u00b6\nstatic num(field: str) \u2192 RedisNum[source]\u00b6\nstatic tag(field: str) \u2192 RedisTag[source]\u00b6\nstatic text(field: str) \u2192 RedisText[source]\u00b6\nExamples using RedisFilter\u00b6\nRedis", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.filters.RedisFilter.html"}
{"id": "21bb7b7fffe1-0", "text": "langchain.vectorstores.redis.schema.TextFieldSchema\u00b6\nclass langchain.vectorstores.redis.schema.TextFieldSchema[source]\u00b6\nBases: RedisField\nSchema for text fields in Redis.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam name: str [Required]\u00b6\nparam no_index: bool = False\u00b6\nparam no_stem: bool = False\u00b6\nparam phonetic_matcher: Optional[str] = None\u00b6\nparam sortable: Optional[bool] = False\u00b6\nparam weight: float = 1\u00b6\nparam withsuffixtrie: bool = False\u00b6\nas_field() \u2192 TextField[source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.TextFieldSchema.html"}
{"id": "21bb7b7fffe1-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.TextFieldSchema.html"}
{"id": "21bb7b7fffe1-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.TextFieldSchema.html"}
{"id": "f992dc183348-0", "text": "langchain.vectorstores.tiledb.get_vector_index_uri\u00b6\nlangchain.vectorstores.tiledb.get_vector_index_uri(uri: str) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.tiledb.get_vector_index_uri.html"}
{"id": "a05faa67bd09-0", "text": "langchain.vectorstores.redis.schema.RedisModel\u00b6\nclass langchain.vectorstores.redis.schema.RedisModel[source]\u00b6\nBases: BaseModel\nSchema for Redis index.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam content_key: str = 'content'\u00b6\nparam content_vector_key: str = 'content_vector'\u00b6\nparam extra: Optional[List[langchain.vectorstores.redis.schema.RedisField]] = None\u00b6\nparam numeric: Optional[List[langchain.vectorstores.redis.schema.NumericFieldSchema]] = None\u00b6\nparam tag: Optional[List[langchain.vectorstores.redis.schema.TagFieldSchema]] = None\u00b6\nparam text: List[langchain.vectorstores.redis.schema.TextFieldSchema] = [TextFieldSchema(name='content', weight=1, no_stem=False, phonetic_matcher=None, withsuffixtrie=False, no_index=False, sortable=False)]\u00b6\nparam vector: Optional[List[Union[langchain.vectorstores.redis.schema.FlatVectorField, langchain.vectorstores.redis.schema.HNSWVectorField]]] = None\u00b6\nadd_content_field() \u2192 None[source]\u00b6\nadd_vector_field(vector_field: Dict[str, Any]) \u2192 None[source]\u00b6\nas_dict() \u2192 Dict[str, List[Any]][source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.RedisModel.html"}
{"id": "a05faa67bd09-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_fields() \u2192 List[RedisField][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.RedisModel.html"}
{"id": "a05faa67bd09-2", "text": "get_fields() \u2192 List[RedisField][source]\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty content_vector: Union[langchain.vectorstores.redis.schema.FlatVectorField, langchain.vectorstores.redis.schema.HNSWVectorField]\u00b6\nproperty is_empty: bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.RedisModel.html"}
{"id": "a05faa67bd09-3", "text": "property is_empty: bool\u00b6\nproperty metadata_keys: List[str]\u00b6\nproperty vector_dtype: numpy.dtype\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.RedisModel.html"}
{"id": "80a5b4aca756-0", "text": "langchain.vectorstores.vald.Vald\u00b6\nclass langchain.vectorstores.vald.Vald(embedding: Embeddings, host: str = 'localhost', port: int = 8080, grpc_options: Tuple = (('grpc.keepalive_time_ms', 10000), ('grpc.keepalive_timeout_ms', 10000)))[source]\u00b6\nWrapper around Vald vector database.\nTo use, you should have the vald-client-python python package installed.\nExample\nfrom langchain.embeddings import HuggingFaceEmbeddings\nfrom langchain.vectorstores import Vald\ntexts = ['foo', 'bar', 'baz']\nvald = Vald.from_texts(\n    texts=texts,\n    embedding=HuggingFaceEmbeddings(),\n    host=\"localhost\",\n    port=8080,\n    skip_strict_exist_check=False,\n )\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding[,\u00a0host,\u00a0port,\u00a0grpc_options])\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0...])\nparam skip_strict_exist_check\nDeprecated. This is not used basically.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vald.Vald.html"}
{"id": "80a5b4aca756-1", "text": "amax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids,\u00a0skip_strict_exist_check])\nparam skip_strict_exist_check\nDeprecated. This is not used basically.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nparam skip_strict_exist_check\nDeprecated. This is not used basically.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0radius,\u00a0...])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vald.Vald.html"}
{"id": "80a5b4aca756-2", "text": "Return docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nRun similarity search with distance.\nsimilarity_search_with_score_by_vector(embedding)\n__init__(embedding: Embeddings, host: str = 'localhost', port: int = 8080, grpc_options: Tuple = (('grpc.keepalive_time_ms', 10000), ('grpc.keepalive_timeout_ms', 10000)))[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, skip_strict_exist_check: bool = False, **kwargs: Any) \u2192 List[str][source]\u00b6\nParameters\nskip_strict_exist_check \u2013 Deprecated. This is not used basically.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vald.Vald.html"}
{"id": "80a5b4aca756-3", "text": "Delete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vald.Vald.html"}
{"id": "80a5b4aca756-4", "text": "score_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vald.Vald.html"}
{"id": "80a5b4aca756-5", "text": "Return docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, skip_strict_exist_check: bool = False, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nParameters\nskip_strict_exist_check \u2013 Deprecated. This is not used basically.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vald.Vald.html"}
{"id": "80a5b4aca756-6", "text": "Return VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, host: str = 'localhost', port: int = 8080, grpc_options: Tuple = (('grpc.keepalive_time_ms', 10000), ('grpc.keepalive_timeout_ms', 10000)), skip_strict_exist_check: bool = False, **kwargs: Any) \u2192 Vald[source]\u00b6\nParameters\nskip_strict_exist_check \u2013 Deprecated. This is not used basically.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, radius: float = - 1.0, epsilon: float = 0.01, timeout: int = 3000000000, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vald.Vald.html"}
{"id": "80a5b4aca756-7", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, radius: float = - 1.0, epsilon: float = 0.01, timeout: int = 3000000000, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, radius: float = - 1.0, epsilon: float = 0.01, timeout: int = 3000000000, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, radius: float = - 1.0, epsilon: float = 0.01, timeout: int = 3000000000, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vald.Vald.html"}
{"id": "80a5b4aca756-8", "text": "Return docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, radius: float = - 1.0, epsilon: float = 0.01, timeout: int = 3000000000, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with distance.\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, radius: float = - 1.0, epsilon: float = 0.01, timeout: int = 3000000000, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.vald.Vald.html"}
{"id": "7c16f87d9875-0", "text": "langchain.vectorstores.hippo.Hippo\u00b6\nclass langchain.vectorstores.hippo.Hippo(embedding_function: Embeddings, table_name: str = 'test', database_name: str = 'default', number_of_shards: int = 1, number_of_replicas: int = 1, connection_args: Optional[Dict[str, Any]] = None, index_params: Optional[dict] = None, drop_old: Optional[bool] = False)[source]\u00b6\nHippo vector store.\nYou need to install hippo-api and run Hippo.\nPlease visit our official website for how to run a Hippo instance:\nhttps://www.transwarp.cn/starwarp\nParameters\nembedding_function (Embeddings) \u2013 Function used to embed the text.\ntable_name (str) \u2013 Which Hippo table to use. Defaults to\n\u201ctest\u201d.\ndatabase_name (str) \u2013 Which Hippo database to use. Defaults to\n\u201cdefault\u201d.\nnumber_of_shards (int) \u2013 The number of shards for the Hippo table.Defaults to\n1.\nnumber_of_replicas (int) \u2013 The number of replicas for the Hippo table.Defaults to\n1.\nconnection_args (Optional[dict[str, any]]) \u2013 The connection args used for\nthis class comes in the form of a dict.\nindex_params (Optional[dict]) \u2013 Which index params to use. Defaults to\nIVF_FLAT.\ndrop_old (Optional[bool]) \u2013 Whether to drop the current collection. Defaults\nto False.\nprimary_field (str) \u2013 Name of the primary key field. Defaults to \u201cpk\u201d.\ntext_field (str) \u2013 Name of the text field. Defaults to \u201ctext\u201d.\nvector_field (str) \u2013 Name of the vector field. Defaults to \u201cvector\u201d.\nThe connection args used for this class comes in the form of a dict,\nhere are a few of the options:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hippo.Hippo.html"}
{"id": "7c16f87d9875-1", "text": "here are a few of the options:\nhost (str): The host of Hippo instance. Default at \u201clocalhost\u201d.\nport (str/int): The port of Hippo instance. Default at 7788.\nuser (str): Use which user to connect to Hippo instance. If user and\npassword are provided, we will add related header in every RPC call.\npassword (str): Required when user is provided. The passwordcorresponding to the user.\nExample\nfrom langchain.vectorstores import Hippo\nfrom langchain.embeddings import OpenAIEmbeddings\nembedding = OpenAIEmbeddings()\n# Connect to a hippo instance on localhost\nvector_store = Hippo.from_documents(\ndocs,\nembedding=embeddings,\ntable_name=\u201dlangchain_test\u201d,\nconnection_args=HIPPO_CONNECTION\n)\nRaises\nValueError \u2013 If the hippo-api python package is not installed.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding_function[,\u00a0table_name,\u00a0...])\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0timeout,\u00a0...])\nAdd text to the collection.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hippo.Hippo.html"}
{"id": "7c16f87d9875-2", "text": "amax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreates an instance of the VST class from the given texts.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0param,\u00a0expr,\u00a0...])\nPerform a similarity search on the query string.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hippo.Hippo.html"}
{"id": "7c16f87d9875-3", "text": "Return docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nPerforms a search on the query string and returns results with scores.\nsimilarity_search_with_score_by_vector(embedding)\nPerforms a search on the query string and returns results with scores.\n__init__(embedding_function: Embeddings, table_name: str = 'test', database_name: str = 'default', number_of_shards: int = 1, number_of_replicas: int = 1, connection_args: Optional[Dict[str, Any]] = None, index_params: Optional[dict] = None, drop_old: Optional[bool] = False)[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, timeout: Optional[int] = None, batch_size: int = 1000, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd text to the collection.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hippo.Hippo.html"}
{"id": "7c16f87d9875-4", "text": "Add text to the collection.\nParameters\ntexts \u2013 An iterable that contains the text to be added.\nmetadatas \u2013 An optional list of dictionaries,\ntext. (each dictionary contains the metadata associated with a) \u2013 \ntimeout \u2013 Optional timeout, in seconds.\nbatch_size \u2013 The number of texts inserted in each batch, defaults to 1000.\n**kwargs \u2013 Other optional parameters.\nReturns\nA list of strings, containing the unique identifiers of the inserted texts.\nNote\nIf the collection has not yet been created,\nthis method will create a new collection.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hippo.Hippo.html"}
{"id": "7c16f87d9875-5", "text": "Return docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hippo.Hippo.html"}
{"id": "7c16f87d9875-6", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hippo.Hippo.html"}
{"id": "7c16f87d9875-7", "text": "Returns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, table_name: str = 'test', database_name: str = 'default', connection_args: Dict[str, Any] = {'host': 'localhost', 'password': 'admin', 'port': '7788', 'username': 'admin'}, index_params: Optional[Dict[Any, Any]] = None, search_params: Optional[Dict[str, Any]] = None, drop_old: bool = False, **kwargs: Any) \u2192 Hippo[source]\u00b6\nCreates an instance of the VST class from the given texts.\nParameters\ntexts (List[str]) \u2013 List of texts to be added.\nembedding (Embeddings) \u2013 Embedding model for the texts.\nmetadatas (List[dict], optional) \u2013 \nNone. (List of metadata dictionaries for each text.Defaults to) \u2013 \ntable_name (str) \u2013 Name of the table. Defaults to \u201ctest\u201d.\ndatabase_name (str) \u2013 Name of the database. Defaults to \u201cdefault\u201d.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hippo.Hippo.html"}
{"id": "7c16f87d9875-8", "text": "database_name (str) \u2013 Name of the database. Defaults to \u201cdefault\u201d.\nconnection_args (dict[str, Any]) \u2013 Connection parameters.\nDEFAULT_HIPPO_CONNECTION. (Defaults to) \u2013 \nindex_params (dict) \u2013 Indexing parameters. Defaults to None.\nsearch_params (dict) \u2013 Search parameters. Defaults to an empty dictionary.\ndrop_old (bool) \u2013 Whether to drop the old collection. Defaults to False.\nkwargs \u2013 Other arguments.\nReturns\nAn instance of the VST class.\nReturn type\nHippo\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hippo.Hippo.html"}
{"id": "7c16f87d9875-9", "text": "k \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nPerform a similarity search on the query string.\nParameters\nquery (str) \u2013 The text to search for.\nk (int, optional) \u2013 The number of results to return. Default is 4.\nparam (dict, optional) \u2013 Specifies the search parameters for the index.\nNone. (Defaults to) \u2013 \nexpr (str, optional) \u2013 Filtering expression. Defaults to None.\ntimeout (int, optional) \u2013 Time to wait before a timeout error.\nNone. \u2013 \nkwargs \u2013 Keyword arguments for Collection.search().\nReturns\nThe document results of the search.\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hippo.Hippo.html"}
{"id": "7c16f87d9875-10", "text": "Returns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPerforms a search on the query string and returns results with scores.\nParameters\nquery (str) \u2013 The text being searched.\nk (int, optional) \u2013 The number of results to return.\n4. (Default is) \u2013 \nparam (dict) \u2013 Specifies the search parameters for the index.\nNone. (Default is) \u2013 \nexpr (str, optional) \u2013 Filtering expression. Default is None.\ntimeout (int, optional) \u2013 The waiting time before a timeout error.\nNone. \u2013 \nkwargs \u2013 Keyword arguments for Collection.search().\nReturn type\nList[float], List[Tuple[Document, any, any]]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hippo.Hippo.html"}
{"id": "7c16f87d9875-11", "text": "Return type\nList[float], List[Tuple[Document, any, any]]\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nPerforms a search on the query string and returns results with scores.\nParameters\nembedding (List[float]) \u2013 The embedding vector being searched.\nk (int, optional) \u2013 The number of results to return.\n4. (Default is) \u2013 \nparam (dict) \u2013 Specifies the search parameters for the index.\nNone. (Default is) \u2013 \nexpr (str, optional) \u2013 Filtering expression. Default is None.\ntimeout (int, optional) \u2013 The waiting time before a timeout error.\nNone. \u2013 \nkwargs \u2013 Keyword arguments for Collection.search().\nReturns\nResulting documents and scores.\nReturn type\nList[Tuple[Document, float]]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.hippo.Hippo.html"}
{"id": "168d2276a97a-0", "text": "langchain.vectorstores.alibabacloud_opensearch.create_metadata\u00b6\nlangchain.vectorstores.alibabacloud_opensearch.create_metadata(fields: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nCreate metadata from fields.\nParameters\nfields \u2013 The fields of the document. The fields must be a dict.\nReturns\nThe metadata of the document. The metadata must be a dict.\nReturn type\nmetadata", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.alibabacloud_opensearch.create_metadata.html"}
{"id": "fc48fc205c25-0", "text": "langchain.vectorstores.redis.schema.RedisField\u00b6\nclass langchain.vectorstores.redis.schema.RedisField[source]\u00b6\nBases: BaseModel\nBase class for Redis fields.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam name: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.RedisField.html"}
{"id": "fc48fc205c25-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.schema.RedisField.html"}
{"id": "69aa6effd407-0", "text": "langchain.vectorstores.faiss.FAISS\u00b6\nclass langchain.vectorstores.faiss.FAISS(embedding_function: Union[Callable[[str], List[float]], Embeddings], index: Any, docstore: Docstore, index_to_docstore_id: Dict[int, str], relevance_score_fn: Optional[Callable[[float], float]] = None, normalize_L2: bool = False, distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE)[source]\u00b6\nMeta Faiss vector store.\nTo use, you must have the faiss python package installed.\nExample\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom langchain.vectorstores import FAISS\nembeddings = OpenAIEmbeddings()\ntexts = [\"FAISS is an important library\", \"LangChain supports FAISS\"]\nfaiss = FAISS.from_texts(texts, embeddings)\nInitialize with necessary components.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding_function,\u00a0index,\u00a0...[,\u00a0...])\nInitialize with necessary components.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_embeddings(text_embeddings[,\u00a0metadatas,\u00a0ids])\nAdd the given texts and embeddings to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-1", "text": "Return VectorStore initialized from documents and embeddings.\nafrom_embeddings(text_embeddings,\u00a0embedding)\nConstruct FAISS wrapper from raw documents asynchronously.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0ids])\nConstruct FAISS wrapper from raw documents asynchronously.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance asynchronously.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance asynchronously.\namax_marginal_relevance_search_with_score_by_vector(...)\nReturn docs and their similarity scores selected using the maximal marginal\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k,\u00a0filter,\u00a0fetch_k])\nReturn docs most similar to query asynchronously.\nasimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector asynchronously.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nReturn docs most similar to query asynchronously.\nasimilarity_search_with_score_by_vector(...)\nReturn docs most similar to query asynchronously.\ndelete([ids])\nDelete by ID.\ndeserialize_from_bytes(serialized,\u00a0...)\nDeserialize FAISS index, docstore, and index_to_docstore_id from bytes.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_embeddings(text_embeddings,\u00a0embedding)\nConstruct FAISS wrapper from raw documents.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0ids])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-2", "text": "from_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0ids])\nConstruct FAISS wrapper from raw documents.\nload_local(folder_path,\u00a0embeddings[,\u00a0index_name])\nLoad FAISS index, docstore, and index_to_docstore_id from disk.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_with_score_by_vector(...)\nReturn docs and their similarity scores selected using the maximal marginal\nmerge_from(target)\nMerge another FAISS object with the current one.\nsave_local(folder_path[,\u00a0index_name])\nSave FAISS index, docstore, and index_to_docstore_id to disk.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nserialize_to_bytes()\nSerialize FAISS index, docstore, and index_to_docstore_id to bytes.\nsimilarity_search(query[,\u00a0k,\u00a0filter,\u00a0fetch_k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nReturn docs most similar to query.\nsimilarity_search_with_score_by_vector(embedding)\nReturn docs most similar to query.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-3", "text": "similarity_search_with_score_by_vector(embedding)\nReturn docs most similar to query.\n__init__(embedding_function: Union[Callable[[str], List[float]], Embeddings], index: Any, docstore: Docstore, index_to_docstore_id: Dict[int, str], relevance_score_fn: Optional[Callable[[float], float]] = None, normalize_L2: bool = False, distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE)[source]\u00b6\nInitialize with necessary components.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstoreasynchronously.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of unique IDs.\nReturns\nList of ids from adding the texts into the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-4", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_embeddings(text_embeddings: Iterable[Tuple[str, List[float]]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd the given texts and embeddings to the vectorstore.\nParameters\ntext_embeddings \u2013 Iterable pairs of string and embedding to\nadd to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of unique IDs.\nReturns\nList of ids from adding the texts into the vectorstore.\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of unique IDs.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-5", "text": "Return VectorStore initialized from documents and embeddings.\nasync classmethod afrom_embeddings(text_embeddings: Iterable[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[Iterable[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 FAISS[source]\u00b6\nConstruct FAISS wrapper from raw documents asynchronously.\nasync classmethod afrom_texts(texts: list[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 FAISS[source]\u00b6\nConstruct FAISS wrapper from raw documents asynchronously.\nThis is a user friendly interface that:\nEmbeds documents.\nCreates an in memory docstore\nInitializes the FAISS database\nThis is intended to be a quick way to get started.\nExample\nfrom langchain.vectorstores import FAISS\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nfaiss = await FAISS.afrom_texts(texts, embeddings)\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance asynchronously.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch before filtering (if needed) to\npass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-6", "text": "of diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance asynchronously.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch before filtering to\npass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nasync amax_marginal_relevance_search_with_score_by_vector(embedding: List[float], *, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, Any]] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs and their similarity scores selected using the maximal marginalrelevance asynchronously.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch before filtering to\npass to MMR algorithm.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-7", "text": "fetch_k \u2013 Number of Documents to fetch before filtering to\npass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents and similarity scores selected by maximal marginalrelevance and score for each.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-8", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query asynchronously.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\nReturns\nList of Documents most similar to the query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector asynchronously.\nParameters\nembedding \u2013 Embedding to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-9", "text": "Parameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\nReturns\nList of Documents most similar to the embedding.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query asynchronously.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\nReturns\nList of documents most similar to the query text with\nL2 distance in float. Lower score represents more similarity.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-10", "text": "L2 distance in float. Lower score represents more similarity.\nasync asimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query asynchronously.\nParameters\nembedding \u2013 Embedding vector to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, Any]]) \u2013 Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\n**kwargs \u2013 kwargs to be passed to similarity search. Can include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of documents most similar to the query text and L2 distance\nin float for each. Lower score represents more similarity.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by ID. These are the IDs in the vectorstore.\nParameters\nids \u2013 List of ids to delete.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod deserialize_from_bytes(serialized: bytes, embeddings: Embeddings, **kwargs: Any) \u2192 FAISS[source]\u00b6\nDeserialize FAISS index, docstore, and index_to_docstore_id from bytes.\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-11", "text": "Return VectorStore initialized from documents and embeddings.\nclassmethod from_embeddings(text_embeddings: Iterable[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[Iterable[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 FAISS[source]\u00b6\nConstruct FAISS wrapper from raw documents.\nThis is a user friendly interface that:\nEmbeds documents.\nCreates an in memory docstore\nInitializes the FAISS database\nThis is intended to be a quick way to get started.\nExample\nfrom langchain.vectorstores import FAISS\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\ntext_embeddings = embeddings.embed_documents(texts)\ntext_embedding_pairs = zip(texts, text_embeddings)\nfaiss = FAISS.from_embeddings(text_embedding_pairs, embeddings)\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 FAISS[source]\u00b6\nConstruct FAISS wrapper from raw documents.\nThis is a user friendly interface that:\nEmbeds documents.\nCreates an in memory docstore\nInitializes the FAISS database\nThis is intended to be a quick way to get started.\nExample\nfrom langchain.vectorstores import FAISS\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\nfaiss = FAISS.from_texts(texts, embeddings)\nclassmethod load_local(folder_path: str, embeddings: Embeddings, index_name: str = 'index', **kwargs: Any) \u2192 FAISS[source]\u00b6\nLoad FAISS index, docstore, and index_to_docstore_id from disk.\nParameters\nfolder_path \u2013 folder path to load index, docstore,\nand index_to_docstore_id from.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-12", "text": "and index_to_docstore_id from.\nembeddings \u2013 Embeddings to use when generating queries\nindex_name \u2013 for saving with a specific index file name\nasynchronous \u2013 whether to use async version or not\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch before filtering (if needed) to\npass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch before filtering to\npass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-13", "text": "lambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_with_score_by_vector(embedding: List[float], *, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, Any]] = None) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs and their similarity scores selected using the maximal marginalrelevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch before filtering to\npass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents and similarity scores selected by maximal marginalrelevance and score for each.\nmerge_from(target: FAISS) \u2192 None[source]\u00b6\nMerge another FAISS object with the current one.\nAdd the target FAISS to the current one.\nParameters\ntarget \u2013 FAISS object you wish to merge into the current one\nReturns\nNone.\nsave_local(folder_path: str, index_name: str = 'index') \u2192 None[source]\u00b6\nSave FAISS index, docstore, and index_to_docstore_id to disk.\nParameters\nfolder_path \u2013 folder path to save index, docstore,\nand index_to_docstore_id to.\nindex_name \u2013 for saving with a specific index file name", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-14", "text": "index_name \u2013 for saving with a specific index file name\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nserialize_to_bytes() \u2192 bytes[source]\u00b6\nSerialize FAISS index, docstore, and index_to_docstore_id to bytes.\nsimilarity_search(query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter \u2013 (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\nReturns\nList of Documents most similar to the embedding.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-15", "text": "Return docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.\nReturns\nList of documents most similar to the query text with\nL2 distance in float. Lower score represents more similarity.\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nembedding \u2013 Embedding vector to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, Any]]) \u2013 Filter by metadata. Defaults to None.\nfetch_k \u2013 (Optional[int]) Number of Documents to fetch before filtering.\nDefaults to 20.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "69aa6effd407-16", "text": "Defaults to 20.\n**kwargs \u2013 kwargs to be passed to similarity search. Can include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of documents most similar to the query text and L2 distance\nin float for each. Lower score represents more similarity.\nExamples using FAISS\u00b6\nCohere Reranker\nFacebook Faiss\nDocument Comparison\nFaiss\nLoading documents from a YouTube url\nConversational Retrieval Agent\nAgents\nAutoGPT\nBabyAGI User Guide\nBabyAGI with Tools\n!pip install bs4\nPlug-and-Plai\nCustom Agent with PlugIn Retrieval\nGenerative Agents in LangChain\nSet env var OPENAI_API_KEY or load from a .env file\nSQL\nCaching\nEnsemble Retriever\nCustom agent with tool retrieval\nSelect by maximal marginal relevance (MMR)\nFirst we add a step to load memory", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.faiss.FAISS.html"}
{"id": "7c303f4eea3a-0", "text": "langchain.vectorstores.timescalevector.TimescaleVector\u00b6\nclass langchain.vectorstores.timescalevector.TimescaleVector(service_url: str, embedding: Embeddings, collection_name: str = 'langchain_store', num_dimensions: int = 1536, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, pre_delete_collection: bool = False, logger: Optional[Logger] = None, relevance_score_fn: Optional[Callable[[float], float]] = None, time_partition_interval: Optional[timedelta] = None, **kwargs: Any)[source]\u00b6\nVectorStore implementation using the timescale vector client to store vectors\nin Postgres.\nTo use, you should have the timescale_vector python package installed.\nParameters\nservice_url \u2013 Service url on timescale cloud.\nembedding \u2013 Any embedding function implementing\nlangchain.embeddings.base.Embeddings interface.\ncollection_name \u2013 The name of the collection to use. (default: langchain_store)\nThis will become the table name used for the collection.\ndistance_strategy \u2013 The distance strategy to use. (default: COSINE)\npre_delete_collection \u2013 If True, will delete the collection if it exists.\n(default: False). Useful for testing.\nExample\nfrom langchain.vectorstores import TimescaleVector\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nSERVICE_URL = \"postgres://tsdbadmin:<password>@<id>.tsdb.cloud.timescale.com:<port>/tsdb?sslmode=require\"\nCOLLECTION_NAME = \"state_of_the_union_test\"\nembeddings = OpenAIEmbeddings()\nvectorestore = TimescaleVector.from_documents(\n    embedding=embeddings,\n    documents=docs,\n    collection_name=COLLECTION_NAME,\n    service_url=SERVICE_URL,\n)\nAttributes\nDEFAULT_INDEX_TYPE\nembeddings\nAccess the query embedding object if available.\nMethods", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "7c303f4eea3a-1", "text": "Attributes\nDEFAULT_INDEX_TYPE\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(service_url,\u00a0embedding[,\u00a0...])\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_embeddings(texts,\u00a0embeddings[,\u00a0...])\nAdd embeddings to the vectorstore.\naadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_embeddings(texts,\u00a0embeddings[,\u00a0...])\nAdd embeddings to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_embeddings(text_embeddings,\u00a0embedding)\nConstruct TimescaleVector wrapper from raw documents and pre- generated embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k,\u00a0filter,\u00a0...])\nRun similarity search with TimescaleVector with distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "7c303f4eea3a-2", "text": "Run similarity search with TimescaleVector with distance.\nasimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nReturn docs most similar to query.\nasimilarity_search_with_score_by_vector(...)\ncreate_index([index_type])\ndate_to_range_filter(**kwargs)\ndelete([ids])\nDelete by vector ID or other criteria.\ndelete_by_metadata(filter,\u00a0**kwargs)\nDelete by vector ID or other criteria.\ndrop_index()\ndrop_tables()\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_embeddings(text_embeddings,\u00a0embedding)\nConstruct TimescaleVector wrapper from raw documents and pre- generated embeddings.\nfrom_existing_index(embedding[,\u00a0...])\nGet instance of an existing TimescaleVector store.This method will return the instance of the store without inserting any new embeddings\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nReturn VectorStore initialized from texts and embeddings.\nget_service_url(kwargs)\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nservice_url_from_db_params(host,\u00a0port,\u00a0...)\nReturn connection string from database parameters.\nsimilarity_search(query[,\u00a0k,\u00a0filter,\u00a0predicates])\nRun similarity search with TimescaleVector with distance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "7c303f4eea3a-3", "text": "Run similarity search with TimescaleVector with distance.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])\nReturn docs most similar to query.\nsimilarity_search_with_score_by_vector(embedding)\n__init__(service_url: str, embedding: Embeddings, collection_name: str = 'langchain_store', num_dimensions: int = 1536, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, pre_delete_collection: bool = False, logger: Optional[Logger] = None, relevance_score_fn: Optional[Callable[[float], float]] = None, time_partition_interval: Optional[timedelta] = None, **kwargs: Any) \u2192 None[source]\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_embeddings(texts: Iterable[str], embeddings: List[List[float]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd embeddings to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nembeddings \u2013 List of list of embedding vectors.\nmetadatas \u2013 List of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "7c303f4eea3a-4", "text": "kwargs \u2013 vectorstore specific parameters\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_embeddings(texts: Iterable[str], embeddings: List[List[float]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd embeddings to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nembeddings \u2013 List of list of embedding vectors.\nmetadatas \u2013 List of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "7c303f4eea3a-5", "text": "kwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_embeddings(text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain_store', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) \u2192 TimescaleVector[source]\u00b6\nConstruct TimescaleVector wrapper from raw documents and pre-\ngenerated embeddings.\nReturn VectorStore initialized from documents and embeddings.\nPostgres connection string is required\n\u201cEither pass it as a parameter\nor set the TIMESCALE_SERVICE_URL environment variable.\nExample\nfrom langchain.vectorstores import TimescaleVector\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\ntext_embeddings = embeddings.embed_documents(texts)\ntext_embedding_pairs = list(zip(texts, text_embeddings))\ntvs = TimescaleVector.from_embeddings(text_embedding_pairs, embeddings)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "7c303f4eea3a-6", "text": "tvs = TimescaleVector.from_embeddings(text_embedding_pairs, embeddings)\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain_store', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) \u2192 TimescaleVector[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nPostgres connection string is required\n\u201cEither pass it as a parameter\nor set the TIMESCALE_SERVICE_URL environment variable.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "7c303f4eea3a-7", "text": "score_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "7c303f4eea3a-8", "text": "Return docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRun similarity search with TimescaleVector with distance.\nParameters\nquery (str) \u2013 Query text to search for.\nk (int) \u2013 Number of results to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query.\nasync asimilarity_search_by_vector(embedding: Optional[List[float]], k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "7c303f4eea3a-9", "text": "filter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(query: str, k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query and score for each\nasync asimilarity_search_with_score_by_vector(embedding: Optional[List[float]], k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\ncreate_index(index_type: Union[IndexType, str] = IndexType.TIMESCALE_VECTOR, **kwargs: Any) \u2192 None[source]\u00b6\ndate_to_range_filter(**kwargs: Any) \u2192 Any[source]\u00b6\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\ndelete_by_metadata(filter: Union[Dict[str, str], List[Dict[str, str]]], **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "7c303f4eea3a-10", "text": "Delete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\ndrop_index() \u2192 None[source]\u00b6\ndrop_tables() \u2192 None[source]\u00b6\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_embeddings(text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain_store', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) \u2192 TimescaleVector[source]\u00b6\nConstruct TimescaleVector wrapper from raw documents and pre-\ngenerated embeddings.\nReturn VectorStore initialized from documents and embeddings.\nPostgres connection string is required\n\u201cEither pass it as a parameter\nor set the TIMESCALE_SERVICE_URL environment variable.\nExample\nfrom langchain.vectorstores import TimescaleVector\nfrom langchain.embeddings import OpenAIEmbeddings\nembeddings = OpenAIEmbeddings()\ntext_embeddings = embeddings.embed_documents(texts)\ntext_embedding_pairs = list(zip(texts, text_embeddings))\ntvs = TimescaleVector.from_embeddings(text_embedding_pairs, embeddings)\nclassmethod from_existing_index(embedding: Embeddings, collection_name: str = 'langchain_store', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, pre_delete_collection: bool = False, **kwargs: Any) \u2192 TimescaleVector[source]\u00b6\nGet instance of an existing TimescaleVector store.This method will\nreturn the instance of the store without inserting any new\nembeddings", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "7c303f4eea3a-11", "text": "return the instance of the store without inserting any new\nembeddings\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain_store', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) \u2192 TimescaleVector[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nPostgres connection string is required\n\u201cEither pass it as a parameter\nor set the TIMESCALE_SERVICE_URL environment variable.\nclassmethod get_service_url(kwargs: Dict[str, Any]) \u2192 str[source]\u00b6\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "7c303f4eea3a-12", "text": "Maximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nclassmethod service_url_from_db_params(host: str, port: int, database: str, user: str, password: str) \u2192 str[source]\u00b6\nReturn connection string from database parameters.\nsimilarity_search(query: str, k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRun similarity search with TimescaleVector with distance.\nParameters\nquery (str) \u2013 Query text to search for.\nk (int) \u2013 Number of results to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query.\nsimilarity_search_by_vector(embedding: Optional[List[float]], k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "7c303f4eea3a-13", "text": "Parameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfilter (Optional[Dict[str, str]]) \u2013 Filter by metadata. Defaults to None.\nReturns\nList of Documents most similar to the query and score for each\nsimilarity_search_with_score_by_vector(embedding: Optional[List[float]], k: int = 4, filter: Optional[Union[dict, list]] = None, predicates: Optional[Predicates] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.timescalevector.TimescaleVector.html"}
{"id": "352f3074d1c5-0", "text": "langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearchSettings\u00b6\nclass langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearchSettings(endpoint: str, instance_id: str, username: str, password: str, table_name: str, field_name_mapping: Dict[str, str], protocol: str = 'http', namespace: str = '', embedding_field_separator: str = ',', output_fields: Optional[List[str]] = None)[source]\u00b6\nAlibaba Cloud Opensearch` client configuration.\nAttribute:\nendpoint (str)The endpoint of opensearch instance, You can find itfrom the console of Alibaba Cloud OpenSearch.\ninstance_id (str)The identify of opensearch instance, You can findit from the console of Alibaba Cloud OpenSearch.\nusername (str) : The username specified when purchasing the instance.\npassword (str) : The password specified when purchasing the instance\uff0c\nAfter the instance is created, you can modify it on the console.\ntablename (str): The table name specified during instance configuration.\nfield_name_mapping (Dict) : Using field name mapping between opensearch\nvector store and opensearch instance configuration table field names:\n{\u2018id\u2019: \u2018The id field name map of index document.\u2019,\n\u2018document\u2019: \u2018The text field name map of index document.\u2019,\n\u2018embedding\u2019: \u2018In the embedding field of the opensearch instance,\nthe values must be in float type and separated by separator,\ndefault is comma.\u2019,\n\u2018metadata_field_x\u2019: \u2018Metadata field mapping includes the mappedfield name and operator in the mapping value, separated by a comma\nbetween the mapped field name and the operator.\u2019,\n}\nprotocol (str): Communication Protocol between SDK and Server, default is http.\nnamespace (str) : The instance data will be partitioned based on the \u201cnamespace\u201d", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearchSettings.html"}
{"id": "352f3074d1c5-1", "text": "namespace (str) : The instance data will be partitioned based on the \u201cnamespace\u201d\nfield,If the namespace is enabled, you need to specify the namespace field\nname during initialization, Otherwise, the queries cannot be executed\ncorrectly.\nembedding_field_separator(str): Delimiter specified for writing vectorfield data, default is comma.\noutput_fields: Specify the field list returned when invoking OpenSearch,by default it is the value list of the field mapping field.\nMethods\n__init__(endpoint,\u00a0instance_id,\u00a0username,\u00a0...)\n__init__(endpoint: str, instance_id: str, username: str, password: str, table_name: str, field_name_mapping: Dict[str, str], protocol: str = 'http', namespace: str = '', embedding_field_separator: str = ',', output_fields: Optional[List[str]] = None) \u2192 None[source]\u00b6\nExamples using AlibabaCloudOpenSearchSettings\u00b6\nAlibaba Cloud OpenSearch", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearchSettings.html"}
{"id": "c31fb4312df0-0", "text": "langchain.vectorstores.pgembedding.CollectionStore\u00b6\nclass langchain.vectorstores.pgembedding.CollectionStore(**kwargs)[source]\u00b6\nCollection store.\nA simple constructor that allows initialization from kwargs.\nSets attributes on the constructed instance using the names and\nvalues in kwargs.\nOnly keys that are present as\nattributes of the instance\u2019s class are allowed. These could be,\nfor example, any mapped columns or relationships.\nAttributes\ncmetadata\nembeddings\nmetadata\nname\nregistry\nuuid\nMethods\n__init__(**kwargs)\nA simple constructor that allows initialization from kwargs.\nget_by_name(session,\u00a0name)\nget_or_create(session,\u00a0name[,\u00a0cmetadata])\nGet or create a collection.\n__init__(**kwargs)\u00b6\nA simple constructor that allows initialization from kwargs.\nSets attributes on the constructed instance using the names and\nvalues in kwargs.\nOnly keys that are present as\nattributes of the instance\u2019s class are allowed. These could be,\nfor example, any mapped columns or relationships.\nclassmethod get_by_name(session: Session, name: str) \u2192 Optional[CollectionStore][source]\u00b6\nclassmethod get_or_create(session: Session, name: str, cmetadata: Optional[dict] = None) \u2192 Tuple[CollectionStore, bool][source]\u00b6\nGet or create a collection.\nReturns [Collection, bool] where the bool is True if the collection was created.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.pgembedding.CollectionStore.html"}
{"id": "939bb10d83d4-0", "text": "langchain.vectorstores.elasticsearch.ExactRetrievalStrategy\u00b6\nclass langchain.vectorstores.elasticsearch.ExactRetrievalStrategy[source]\u00b6\nExact retrieval strategy using the script_score query.\nMethods\n__init__()\nbefore_index_setup(client,\u00a0text_field,\u00a0...)\nExecutes before the index is created.\nindex(dims_length,\u00a0vector_query_field,\u00a0...)\nCreate the mapping for the Elasticsearch index.\nquery(query_vector,\u00a0query,\u00a0k,\u00a0fetch_k,\u00a0...)\nExecutes when a search is performed on the store.\nrequire_inference()\nReturns whether or not the strategy requires inference to be performed on the text before it is added to the index.\n__init__()\u00b6\nbefore_index_setup(client: Elasticsearch, text_field: str, vector_query_field: str) \u2192 None\u00b6\nExecutes before the index is created. Used for setting up\nany required Elasticsearch resources like a pipeline.\nParameters\nclient \u2013 The Elasticsearch client.\ntext_field \u2013 The field containing the text data in the index.\nvector_query_field \u2013 The field containing the vector\nrepresentations in the index.\nindex(dims_length: Optional[int], vector_query_field: str, similarity: Optional[DistanceStrategy]) \u2192 Dict[source]\u00b6\nCreate the mapping for the Elasticsearch index.\nquery(query_vector: Optional[List[float]], query: Optional[str], k: int, fetch_k: int, vector_query_field: str, text_field: str, filter: Optional[List[dict]], similarity: Optional[DistanceStrategy]) \u2192 Dict[source]\u00b6\nExecutes when a search is performed on the store.\nParameters\nquery_vector \u2013 The query vector,\nor None if not using vector-based query.\nquery \u2013 The text query, or None if not using text-based query.\nk \u2013 The total number of results to retrieve.\nfetch_k \u2013 The number of results to fetch initially.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ExactRetrievalStrategy.html"}
{"id": "939bb10d83d4-1", "text": "fetch_k \u2013 The number of results to fetch initially.\nvector_query_field \u2013 The field containing the vector\nrepresentations in the index.\ntext_field \u2013 The field containing the text data in the index.\nfilter \u2013 List of filter clauses to apply to the query.\nsimilarity \u2013 The similarity strategy to use, or None if not using one.\nReturns\nThe Elasticsearch query body.\nReturn type\nDict\nrequire_inference() \u2192 bool\u00b6\nReturns whether or not the strategy requires inference\nto be performed on the text before it is added to the index.\nReturns\nWhether or not the strategy requires inference\nto be performed on the text before it is added to the index.\nReturn type\nbool", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.ExactRetrievalStrategy.html"}
{"id": "c13921f7e2af-0", "text": "langchain.vectorstores.sklearn.BsonSerializer\u00b6\nclass langchain.vectorstores.sklearn.BsonSerializer(persist_path: str)[source]\u00b6\nSerializes data in binary json using the bson python package.\nMethods\n__init__(persist_path)\nextension()\nThe file extension suggested by this serializer (without dot).\nload()\nLoads the data from the persist_path\nsave(data)\nSaves the data to the persist_path\n__init__(persist_path: str) \u2192 None[source]\u00b6\nclassmethod extension() \u2192 str[source]\u00b6\nThe file extension suggested by this serializer (without dot).\nload() \u2192 Any[source]\u00b6\nLoads the data from the persist_path\nsave(data: Any) \u2192 None[source]\u00b6\nSaves the data to the persist_path", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.sklearn.BsonSerializer.html"}
{"id": "98306444346a-0", "text": "langchain.vectorstores.elasticsearch.SparseRetrievalStrategy\u00b6\nclass langchain.vectorstores.elasticsearch.SparseRetrievalStrategy(model_id: Optional[str] = None)[source]\u00b6\nSparse retrieval strategy using the text_expansion processor.\nMethods\n__init__([model_id])\nbefore_index_setup(client,\u00a0text_field,\u00a0...)\nExecutes before the index is created.\nindex(dims_length,\u00a0vector_query_field,\u00a0...)\nExecutes when the index is created.\nquery(query_vector,\u00a0query,\u00a0k,\u00a0fetch_k,\u00a0...)\nExecutes when a search is performed on the store.\nrequire_inference()\nReturns whether or not the strategy requires inference to be performed on the text before it is added to the index.\n__init__(model_id: Optional[str] = None)[source]\u00b6\nbefore_index_setup(client: Elasticsearch, text_field: str, vector_query_field: str) \u2192 None[source]\u00b6\nExecutes before the index is created. Used for setting up\nany required Elasticsearch resources like a pipeline.\nParameters\nclient \u2013 The Elasticsearch client.\ntext_field \u2013 The field containing the text data in the index.\nvector_query_field \u2013 The field containing the vector\nrepresentations in the index.\nindex(dims_length: Optional[int], vector_query_field: str, similarity: Optional[DistanceStrategy]) \u2192 Dict[source]\u00b6\nExecutes when the index is created.\nParameters\ndims_length \u2013 Numeric length of the embedding vectors,\nor None if not using vector-based query.\nvector_query_field \u2013 The field containing the vector\nrepresentations in the index.\nsimilarity \u2013 The similarity strategy to use,\nor None if not using one.\nReturns\nThe Elasticsearch settings and mappings for the strategy.\nReturn type\nDict", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.SparseRetrievalStrategy.html"}
{"id": "98306444346a-1", "text": "Returns\nThe Elasticsearch settings and mappings for the strategy.\nReturn type\nDict\nquery(query_vector: Optional[List[float]], query: Optional[str], k: int, fetch_k: int, vector_query_field: str, text_field: str, filter: List[dict], similarity: Optional[DistanceStrategy]) \u2192 Dict[source]\u00b6\nExecutes when a search is performed on the store.\nParameters\nquery_vector \u2013 The query vector,\nor None if not using vector-based query.\nquery \u2013 The text query, or None if not using text-based query.\nk \u2013 The total number of results to retrieve.\nfetch_k \u2013 The number of results to fetch initially.\nvector_query_field \u2013 The field containing the vector\nrepresentations in the index.\ntext_field \u2013 The field containing the text data in the index.\nfilter \u2013 List of filter clauses to apply to the query.\nsimilarity \u2013 The similarity strategy to use, or None if not using one.\nReturns\nThe Elasticsearch query body.\nReturn type\nDict\nrequire_inference() \u2192 bool[source]\u00b6\nReturns whether or not the strategy requires inference\nto be performed on the text before it is added to the index.\nReturns\nWhether or not the strategy requires inference\nto be performed on the text before it is added to the index.\nReturn type\nbool", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.elasticsearch.SparseRetrievalStrategy.html"}
{"id": "1123d4fc97d0-0", "text": "langchain.vectorstores.redis.filters.RedisFilterOperator\u00b6\nclass langchain.vectorstores.redis.filters.RedisFilterOperator(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nRedisFilterOperator enumerator is used to create RedisFilterExpressions.\nEQ = 1\u00b6\nNE = 2\u00b6\nLT = 3\u00b6\nGT = 4\u00b6\nLE = 5\u00b6\nGE = 6\u00b6\nOR = 7\u00b6\nAND = 8\u00b6\nLIKE = 9\u00b6\nIN = 10\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.redis.filters.RedisFilterOperator.html"}
{"id": "551b1b2bb7c2-0", "text": "langchain.vectorstores.typesense.Typesense\u00b6\nclass langchain.vectorstores.typesense.Typesense(typesense_client: Client, embedding: Embeddings, *, typesense_collection_name: Optional[str] = None, text_key: str = 'text')[source]\u00b6\nTypesense vector store.\nTo use, you should have the typesense python package installed.\nExample\nfrom langchain.embedding.openai import OpenAIEmbeddings\nfrom langchain.vectorstores import Typesense\nimport typesense\nnode = {\n    \"host\": \"localhost\",  # For Typesense Cloud use xxx.a1.typesense.net\n    \"port\": \"8108\",       # For Typesense Cloud use 443\n    \"protocol\": \"http\"    # For Typesense Cloud use https\n}\ntypesense_client = typesense.Client(\n    {\n      \"nodes\": [node],\n      \"api_key\": \"<API_KEY>\",\n      \"connection_timeout_seconds\": 2\n    }\n)\ntypesense_collection_name = \"langchain-memory\"\nembedding = OpenAIEmbeddings()\nvectorstore = Typesense(\n    typesense_client=typesense_client,\n    embedding=embedding,\n    typesense_collection_name=typesense_collection_name,\n    text_key=\"text\",\n)\nInitialize with Typesense client.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(typesense_client,\u00a0embedding,\u00a0*[,\u00a0...])\nInitialize with Typesense client.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.typesense.Typesense.html"}
{"id": "551b1b2bb7c2-1", "text": "Run more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0ids])\nRun more texts through the embedding and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_client_params(embedding,\u00a0*[,\u00a0host,\u00a0...])\nInitialize Typesense directly from client parameters.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nConstruct Typesense wrapper from raw text.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.typesense.Typesense.html"}
{"id": "551b1b2bb7c2-2", "text": "max_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0filter])\nReturn typesense documents most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0filter])\nReturn typesense documents most similar to query, along with scores.\n__init__(typesense_client: Client, embedding: Embeddings, *, typesense_collection_name: Optional[str] = None, text_key: str = 'text')[source]\u00b6\nInitialize with Typesense client.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.typesense.Typesense.html"}
{"id": "551b1b2bb7c2-3", "text": "Returns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embedding and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nids \u2013 Optional list of ids to associate with the texts.\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.typesense.Typesense.html"}
{"id": "551b1b2bb7c2-4", "text": "Return docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.typesense.Typesense.html"}
{"id": "551b1b2bb7c2-5", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.typesense.Typesense.html"}
{"id": "551b1b2bb7c2-6", "text": "Returns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_client_params(embedding: Embeddings, *, host: str = 'localhost', port: Union[str, int] = '8108', protocol: str = 'http', typesense_api_key: Optional[str] = None, connection_timeout_seconds: int = 2, **kwargs: Any) \u2192 Typesense[source]\u00b6\nInitialize Typesense directly from client parameters.\nExample\nfrom langchain.embedding.openai import OpenAIEmbeddings\nfrom langchain.vectorstores import Typesense\n# Pass in typesense_api_key as kwarg or set env var \"TYPESENSE_API_KEY\".\nvectorstore = Typesense(\n    OpenAIEmbeddings(),\n    host=\"localhost\",\n    port=\"8108\",\n    protocol=\"http\",\n    typesense_collection_name=\"langchain-memory\",\n)\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.typesense.Typesense.html"}
{"id": "551b1b2bb7c2-7", "text": "Return VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, typesense_client: Optional[Client] = None, typesense_client_params: Optional[dict] = None, typesense_collection_name: Optional[str] = None, text_key: str = 'text', **kwargs: Any) \u2192 Typesense[source]\u00b6\nConstruct Typesense wrapper from raw text.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.typesense.Typesense.html"}
{"id": "551b1b2bb7c2-8", "text": "k \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 10, filter: Optional[str] = '', **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn typesense documents most similar to query.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 10.\nMinimum 10 results would be returned.\nfilter \u2013 typesense filter_by expression to filter documents on\nReturns\nList of Documents most similar to the query and score for each\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.typesense.Typesense.html"}
{"id": "551b1b2bb7c2-9", "text": "query \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 10, filter: Optional[str] = '') \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn typesense documents most similar to query, along with scores.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 10.\nMinimum 10 results would be returned.\nfilter \u2013 typesense filter_by expression to filter documents on\nReturns\nList of Documents most similar to the query and score for each\nExamples using Typesense\u00b6\nTypesense", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.typesense.Typesense.html"}
{"id": "902718bd737b-0", "text": "langchain.vectorstores.zilliz.Zilliz\u00b6\nclass langchain.vectorstores.zilliz.Zilliz(embedding_function: Embeddings, collection_name: str = 'LangChainCollection', connection_args: Optional[dict[str, Any]] = None, consistency_level: str = 'Session', index_params: Optional[dict] = None, search_params: Optional[dict] = None, drop_old: Optional[bool] = False, *, primary_field: str = 'pk', text_field: str = 'text', vector_field: str = 'vector')[source]\u00b6\nZilliz vector store.\nYou need to have pymilvus installed and a\nrunning Zilliz database.\nSee the following documentation for how to run a Zilliz instance:\nhttps://docs.zilliz.com/docs/create-cluster\nIF USING L2/IP metric IT IS HIGHLY SUGGESTED TO NORMALIZE YOUR DATA.\nParameters\nembedding_function (Embeddings) \u2013 Function used to embed the text.\ncollection_name (str) \u2013 Which Zilliz collection to use. Defaults to\n\u201cLangChainCollection\u201d.\nconnection_args (Optional[dict[str, any]]) \u2013 The connection args used for\nthis class comes in the form of a dict.\nconsistency_level (str) \u2013 The consistency level to use for a collection.\nDefaults to \u201cSession\u201d.\nindex_params (Optional[dict]) \u2013 Which index params to use. Defaults to\nHNSW/AUTOINDEX depending on service.\nsearch_params (Optional[dict]) \u2013 Which search params to use. Defaults to\ndefault of index.\ndrop_old (Optional[bool]) \u2013 Whether to drop the current collection. Defaults\nto False.\nThe connection args used for this class comes in the form of a dict,\nhere are a few of the options:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "902718bd737b-1", "text": "here are a few of the options:\naddress (str): The actual address of Zillizinstance. Example address: \u201clocalhost:19530\u201d\nuri (str): The uri of Zilliz instance. Example uri:\u201chttps://in03-ba4234asae.api.gcp-us-west1.zillizcloud.com\u201d,\nhost (str): The host of Zilliz instance. Default at \u201clocalhost\u201d,PyMilvus will fill in the default host if only port is provided.\nport (str/int): The port of Zilliz instance. Default at 19530, PyMilvuswill fill in the default port if only host is provided.\nuser (str): Use which user to connect to Zilliz instance. If user andpassword are provided, we will add related header in every RPC call.\npassword (str): Required when user is provided. The passwordcorresponding to the user.\ntoken (str): API key, for serverless clusters which can be used asreplacements for user and password.\nsecure (bool): Default is false. If set to true, tls will be enabled.\nclient_key_path (str): If use tls two-way authentication, need to\nwrite the client.key path.\nclient_pem_path (str): If use tls two-way authentication, need towrite the client.pem path.\nca_pem_path (str): If use tls two-way authentication, need to writethe ca.pem path.\nserver_pem_path (str): If use tls one-way authentication, need towrite the server.pem path.\nserver_name (str): If use tls, need to write the common name.\nExample\nfrom langchain.vectorstores import Zilliz\nfrom langchain.embeddings import OpenAIEmbeddings\nembedding = OpenAIEmbeddings()\n# Connect to a Zilliz instance\nmilvus_store = Milvus(", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "902718bd737b-2", "text": "# Connect to a Zilliz instance\nmilvus_store = Milvus(\nembedding_function = embedding,\ncollection_name = \u201cLangChainCollection\u201d,\nconnection_args = {\n\u201curi\u201d: \u201chttps://in03-ba4234asae.api.gcp-us-west1.zillizcloud.com\u201d,\n\u201cuser\u201d: \u201ctemp\u201d,\n\u201cpassword\u201d: \u201ctemp\u201d,\n\u201ctoken\u201d: \u201ctemp\u201d, # API key as replacements for user and password\n\u201csecure\u201d: True\n}\ndrop_old: True,\n)\nRaises\nValueError \u2013 If the pymilvus python package is not installed.\nInitialize the Milvus vector store.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__(embedding_function[,\u00a0...])\nInitialize the Milvus vector store.\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas,\u00a0timeout,\u00a0...])\nInsert text data into Milvus.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "902718bd737b-3", "text": "Return docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas,\u00a0...])\nCreate a Zilliz collection, indexes it with HNSW, and insert data.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nPerform a search and return results that are reordered by MMR.\nmax_marginal_relevance_search_by_vector(...)\nPerform a search and return results that are reordered by MMR.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k,\u00a0param,\u00a0expr,\u00a0...])\nPerform a similarity search against the query string.\nsimilarity_search_by_vector(embedding[,\u00a0k,\u00a0...])\nPerform a similarity search against the query string.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(query[,\u00a0k,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "902718bd737b-4", "text": "similarity_search_with_score(query[,\u00a0k,\u00a0...])\nPerform a search on a query string and return results with score.\nsimilarity_search_with_score_by_vector(embedding)\nPerform a search on a query string and return results with score.\n__init__(embedding_function: Embeddings, collection_name: str = 'LangChainCollection', connection_args: Optional[dict[str, Any]] = None, consistency_level: str = 'Session', index_params: Optional[dict] = None, search_params: Optional[dict] = None, drop_old: Optional[bool] = False, *, primary_field: str = 'pk', text_field: str = 'text', vector_field: str = 'vector')\u00b6\nInitialize the Milvus vector store.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, timeout: Optional[int] = None, batch_size: int = 1000, **kwargs: Any) \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "902718bd737b-5", "text": "Insert text data into Milvus.\nInserting data when the collection has not be made yet will result\nin creating a new Collection. The data of the first entity decides\nthe schema of the new collection, the dim is extracted from the first\nembedding and the columns are decided by the first metadata dict.\nMetada keys will need to be present for all inserted values. At\nthe moment there is no None equivalent in Milvus.\nParameters\ntexts (Iterable[str]) \u2013 The texts to embed, it is assumed\nthat they all fit in memory.\nmetadatas (Optional[List[dict]]) \u2013 Metadata dicts attached to each of\nthe texts. Defaults to None.\ntimeout (Optional[int]) \u2013 Timeout for each batch insert. Defaults\nto None.\nbatch_size (int, optional) \u2013 Batch size to use for insertion.\nDefaults to 1000.\nRaises\nMilvusException \u2013 Failure to add texts\nReturns\nThe resulting keys for each inserted element.\nReturn type\nList[str]\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from texts and embeddings.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "902718bd737b-6", "text": "Return VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "902718bd737b-7", "text": ")\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "902718bd737b-8", "text": "**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST\u00b6\nReturn VectorStore initialized from documents and embeddings.\nclassmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'LangChainCollection', connection_args: Optional[Dict[str, Any]] = None, consistency_level: str = 'Session', index_params: Optional[dict] = None, search_params: Optional[dict] = None, drop_old: bool = False, **kwargs: Any) \u2192 Zilliz[source]\u00b6\nCreate a Zilliz collection, indexes it with HNSW, and insert data.\nParameters\ntexts (List[str]) \u2013 Text data.\nembedding (Embeddings) \u2013 Embedding function.\nmetadatas (Optional[List[dict]]) \u2013 Metadata for each text if it exists.\nDefaults to None.\ncollection_name (str, optional) \u2013 Collection name to use. Defaults to\n\u201cLangChainCollection\u201d.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "902718bd737b-9", "text": "\u201cLangChainCollection\u201d.\nconnection_args (dict[str, Any], optional) \u2013 Connection args to use. Defaults\nto DEFAULT_MILVUS_CONNECTION.\nconsistency_level (str, optional) \u2013 Which consistency level to use. Defaults\nto \u201cSession\u201d.\nindex_params (Optional[dict], optional) \u2013 Which index_params to use.\nDefaults to None.\nsearch_params (Optional[dict], optional) \u2013 Which search params to use.\nDefaults to None.\ndrop_old (Optional[bool], optional) \u2013 Whether to drop the collection with\nthat name if it exists. Defaults to False.\nReturns\nZilliz Vector Store\nReturn type\nZilliz\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nPerform a search and return results that are reordered by MMR.\nParameters\nquery (str) \u2013 The text being searched.\nk (int, optional) \u2013 How many results to give. Defaults to 4.\nfetch_k (int, optional) \u2013 Total results to select k from.\nDefaults to 20.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5\nparam (dict, optional) \u2013 The search params for the specified index.\nDefaults to None.\nexpr (str, optional) \u2013 Filtering expression. Defaults to None.\ntimeout (int, optional) \u2013 How long to wait before timeout error.\nDefaults to None.\nkwargs \u2013 Collection.search() keyword arguments.\nReturns\nDocument results for search.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "902718bd737b-10", "text": "kwargs \u2013 Collection.search() keyword arguments.\nReturns\nDocument results for search.\nReturn type\nList[Document]\nmax_marginal_relevance_search_by_vector(embedding: list[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nPerform a search and return results that are reordered by MMR.\nParameters\nembedding (str) \u2013 The embedding vector being searched.\nk (int, optional) \u2013 How many results to give. Defaults to 4.\nfetch_k (int, optional) \u2013 Total results to select k from.\nDefaults to 20.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5\nparam (dict, optional) \u2013 The search params for the specified index.\nDefaults to None.\nexpr (str, optional) \u2013 Filtering expression. Defaults to None.\ntimeout (int, optional) \u2013 How long to wait before timeout error.\nDefaults to None.\nkwargs \u2013 Collection.search() keyword arguments.\nReturns\nDocument results for search.\nReturn type\nList[Document]\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document]\u00b6\nReturn docs most similar to query using specified search type.\nsimilarity_search(query: str, k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nPerform a similarity search against the query string.\nParameters", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "902718bd737b-11", "text": "Perform a similarity search against the query string.\nParameters\nquery (str) \u2013 The text to search.\nk (int, optional) \u2013 How many results to return. Defaults to 4.\nparam (dict, optional) \u2013 The search params for the index type.\nDefaults to None.\nexpr (str, optional) \u2013 Filtering expression. Defaults to None.\ntimeout (int, optional) \u2013 How long to wait before timeout error.\nDefaults to None.\nkwargs \u2013 Collection.search() keyword arguments.\nReturns\nDocument results for search.\nReturn type\nList[Document]\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nPerform a similarity search against the query string.\nParameters\nembedding (List[float]) \u2013 The embedding vector to search.\nk (int, optional) \u2013 How many results to return. Defaults to 4.\nparam (dict, optional) \u2013 The search params for the index type.\nDefaults to None.\nexpr (str, optional) \u2013 Filtering expression. Defaults to None.\ntimeout (int, optional) \u2013 How long to wait before timeout error.\nDefaults to None.\nkwargs \u2013 Collection.search() keyword arguments.\nReturns\nDocument results for search.\nReturn type\nList[Document]\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nReturn docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "902718bd737b-12", "text": "query \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(query: str, k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nPerform a search on a query string and return results with score.\nFor more information about the search parameters, take a look at the pymilvus\ndocumentation found here:\nhttps://milvus.io/api-reference/pymilvus/v2.2.6/Collection/search().md\nParameters\nquery (str) \u2013 The text being searched.\nk (int, optional) \u2013 The amount of results to return. Defaults to 4.\nparam (dict) \u2013 The search params for the specified index.\nDefaults to None.\nexpr (str, optional) \u2013 Filtering expression. Defaults to None.\ntimeout (int, optional) \u2013 How long to wait before timeout error.\nDefaults to None.\nkwargs \u2013 Collection.search() keyword arguments.\nReturn type\nList[float], List[Tuple[Document, any, any]]\nsimilarity_search_with_score_by_vector(embedding: List[float], k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any) \u2192 List[Tuple[Document, float]]\u00b6\nPerform a search on a query string and return results with score.\nFor more information about the search parameters, take a look at the pymilvus", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "902718bd737b-13", "text": "For more information about the search parameters, take a look at the pymilvus\ndocumentation found here:\nhttps://milvus.io/api-reference/pymilvus/v2.2.6/Collection/search().md\nParameters\nembedding (List[float]) \u2013 The embedding vector being searched.\nk (int, optional) \u2013 The amount of results to return. Defaults to 4.\nparam (dict) \u2013 The search params for the specified index.\nDefaults to None.\nexpr (str, optional) \u2013 Filtering expression. Defaults to None.\ntimeout (int, optional) \u2013 How long to wait before timeout error.\nDefaults to None.\nkwargs \u2013 Collection.search() keyword arguments.\nReturns\nResult doc and score.\nReturn type\nList[Tuple[Document, float]]", "source": "lang/api.python.langchain.com/en/latest/vectorstores/langchain.vectorstores.zilliz.Zilliz.html"}
{"id": "efe43098dd86-0", "text": "langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.load_response_generator\u00b6\nlangchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.load_response_generator(llm: BaseLanguageModel) \u2192 ResponseGenerator[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.load_response_generator.html"}
{"id": "af724c6157fe-0", "text": "langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerator\u00b6\nclass langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerator(llm_chain: LLMChain, stop: Optional[List] = None)[source]\u00b6\nMethods\n__init__(llm_chain[,\u00a0stop])\ngenerate(inputs[,\u00a0callbacks])\nGiven input, decided what to do.\n__init__(llm_chain: LLMChain, stop: Optional[List] = None)[source]\u00b6\ngenerate(inputs: dict, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nGiven input, decided what to do.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerator.html"}
{"id": "cb5741141b2a-0", "text": "langchain_experimental.autonomous_agents.autogpt.output_parser.preprocess_json_input\u00b6\nlangchain_experimental.autonomous_agents.autogpt.output_parser.preprocess_json_input(input_str: str) \u2192 str[source]\u00b6\nPreprocesses a string to be parsed as json.\nReplace single backslashes with double backslashes,\nwhile leaving already escaped ones intact.\nParameters\ninput_str \u2013 String to be preprocessed\nReturns\nPreprocessed string", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.preprocess_json_input.html"}
{"id": "14762ffd1837-0", "text": "langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain\u00b6\nclass langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain[source]\u00b6\nBases: LLMChain\nChain to execute tasks.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-1", "text": "param output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-2", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-4", "text": "Generate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-5", "text": "Prepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-6", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-7", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-8", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, verbose: bool = True) \u2192 LLMChain[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-9", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-11", "text": "Parameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-12", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-13", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-14", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "14762ffd1837-15", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator.ResponseGenerationChain.html"}
{"id": "36c59cc5d271-0", "text": "langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI\u00b6\nclass langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI[source]\u00b6\nBases: Chain, BaseModel\nController model for the BabyAGI agent.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam execution_chain: langchain.chains.base.Chain [Required]\u00b6\nparam max_iterations: Optional[int] = None\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-1", "text": "Optional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam task_creation_chain: langchain.chains.base.Chain [Required]\u00b6\nparam task_id_counter: int = 1\u00b6\nparam task_list: collections.deque [Optional]\u00b6\nparam task_prioritization_chain: langchain.chains.base.Chain [Required]\u00b6\nparam vectorstore: langchain.schema.vectorstore.VectorStore [Required]\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-2", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-3", "text": "response. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nadd_task(task: Dict) \u2192 None[source]\u00b6\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-4", "text": "Convenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nexecute_task(objective: str, task: str, k: int = 5, **kwargs: Any) \u2192 str[source]\u00b6\nExecute a task.\nclassmethod from_llm(llm: BaseLanguageModel, vectorstore: VectorStore, verbose: bool = False, task_execution_chain: Optional[Chain] = None, **kwargs: Any) \u2192 BabyAGI[source]\u00b6\nInitialize the BabyAGI Controller.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-8", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_next_task(result: str, task_description: str, objective: str, **kwargs: Any) \u2192 List[Dict][source]\u00b6\nGet the next task.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-10", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprint_next_task(task: Dict) \u2192 None[source]\u00b6\nprint_task_list() \u2192 None[source]\u00b6\nprint_task_result(result: str) \u2192 None[source]\u00b6\nprioritize_tasks(this_task_id: int, objective: str, **kwargs: Any) \u2192 List[Dict][source]\u00b6\nPrioritize tasks.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-11", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-12", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-13", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nKeys expected to be in the chain input.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "36c59cc5d271-14", "text": "property input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nKeys expected to be in the chain output.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.baby_agi.BabyAGI.html"}
{"id": "971adc2e9ca8-0", "text": "langchain_experimental.autonomous_agents.hugginggpt.task_executor.Task\u00b6\nclass langchain_experimental.autonomous_agents.hugginggpt.task_executor.Task(task: str, id: int, dep: List[int], args: Dict, tool: BaseTool)[source]\u00b6\nMethods\n__init__(task,\u00a0id,\u00a0dep,\u00a0args,\u00a0tool)\ncompleted()\nfailed()\npending()\nrun()\nsave_product()\n__init__(task: str, id: int, dep: List[int], args: Dict, tool: BaseTool)[source]\u00b6\ncompleted() \u2192 bool[source]\u00b6\nfailed() \u2192 bool[source]\u00b6\npending() \u2192 bool[source]\u00b6\nrun() \u2192 str[source]\u00b6\nsave_product() \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_executor.Task.html"}
{"id": "013e5806335d-0", "text": "langchain_experimental.autonomous_agents.hugginggpt.task_planner.BasePlanner\u00b6\nclass langchain_experimental.autonomous_agents.hugginggpt.task_planner.BasePlanner[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nabstract async aplan(inputs: dict, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Plan[source]\u00b6\nGiven input, decide what to do.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.BasePlanner.html"}
{"id": "013e5806335d-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.BasePlanner.html"}
{"id": "013e5806335d-2", "text": "abstract plan(inputs: dict, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Plan[source]\u00b6\nGiven input, decide what to do.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.BasePlanner.html"}
{"id": "18b51eea54f9-0", "text": "langchain_experimental.autonomous_agents.autogpt.prompt.AutoGPTPrompt\u00b6\nclass langchain_experimental.autonomous_agents.autogpt.prompt.AutoGPTPrompt[source]\u00b6\nBases: BaseChatPromptTemplate, BaseModel\nPrompt for AutoGPT.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_name: str [Required]\u00b6\nparam ai_role: str [Required]\u00b6\nparam input_types: Dict[str, Any] [Optional]\u00b6\nA dictionary of the types of the variables the prompt template expects.\nIf not provided, all variables are assumed to be strings.\nparam input_variables: List[str] [Required]\u00b6\nA list of the names of the variables the prompt template expects.\nparam output_parser: Optional[BaseOutputParser] = None\u00b6\nHow to parse the output of calling an LLM on this formatted prompt.\nparam partial_variables: Mapping[str, Union[str, Callable[[], str]]] [Optional]\u00b6\nparam send_token_limit: int = 4196\u00b6\nparam token_counter: Callable[[str], int] [Required]\u00b6\nparam tools: List[langchain.tools.base.BaseTool] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.prompt.AutoGPTPrompt.html"}
{"id": "18b51eea54f9-1", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.prompt.AutoGPTPrompt.html"}
{"id": "18b51eea54f9-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.prompt.AutoGPTPrompt.html"}
{"id": "18b51eea54f9-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\nconstruct_full_prompt(goals: List[str]) \u2192 str[source]\u00b6\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of prompt.\nformat(**kwargs: Any) \u2192 str\u00b6\nFormat the chat template into a string.\nParameters\n**kwargs \u2013 keyword arguments to use for filling in template variables\nin all the template messages in this chat template.\nReturns\nformatted string\nformat_messages(**kwargs: Any) \u2192 List[BaseMessage][source]\u00b6\nFormat kwargs into a list of messages.\nformat_prompt(**kwargs: Any) \u2192 PromptValue\u00b6\nFormat prompt. Should return a PromptValue.\n:param **kwargs: Keyword arguments to use for formatting.\nReturns\nPromptValue.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.prompt.AutoGPTPrompt.html"}
{"id": "18b51eea54f9-4", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict, config: Optional[RunnableConfig] = None) \u2192 PromptValue\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.prompt.AutoGPTPrompt.html"}
{"id": "18b51eea54f9-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npartial(**kwargs: Union[str, Callable[[], str]]) \u2192 BasePromptTemplate\u00b6\nReturn a partial of the prompt template.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the prompt.\nParameters", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.prompt.AutoGPTPrompt.html"}
{"id": "18b51eea54f9-6", "text": "Save the prompt.\nParameters\nfile_path \u2013 Path to directory to save prompt to.\nExample:\n.. code-block:: python\nprompt.save(file_path=\u201dpath/prompt.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.prompt.AutoGPTPrompt.html"}
{"id": "18b51eea54f9-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.prompt.AutoGPTPrompt.html"}
{"id": "18b51eea54f9-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Any\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nReturn a list of attribute names that should be included in the\nserialized kwargs. These attributes must be accepted by the\nconstructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.prompt.AutoGPTPrompt.html"}
{"id": "2a662d0ef6a1-0", "text": "langchain_experimental.autonomous_agents.hugginggpt.hugginggpt.HuggingGPT\u00b6\nclass langchain_experimental.autonomous_agents.hugginggpt.hugginggpt.HuggingGPT(llm: BaseLanguageModel, tools: List[BaseTool])[source]\u00b6\nMethods\n__init__(llm,\u00a0tools)\nrun(input)\n__init__(llm: BaseLanguageModel, tools: List[BaseTool])[source]\u00b6\nrun(input: str) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.hugginggpt.HuggingGPT.html"}
{"id": "a3c116f13179-0", "text": "langchain_experimental.autonomous_agents.autogpt.prompt_generator.PromptGenerator\u00b6\nclass langchain_experimental.autonomous_agents.autogpt.prompt_generator.PromptGenerator[source]\u00b6\nA class for generating custom prompt strings.\nDoes this based on constraints, commands, resources, and performance evaluations.\nInitialize the PromptGenerator object.\nStarts with empty lists of constraints, commands, resources,\nand performance evaluations.\nMethods\n__init__()\nInitialize the PromptGenerator object.\nadd_constraint(constraint)\nAdd a constraint to the constraints list.\nadd_performance_evaluation(evaluation)\nAdd a performance evaluation item to the performance_evaluation list.\nadd_resource(resource)\nAdd a resource to the resources list.\nadd_tool(tool)\ngenerate_prompt_string()\nGenerate a prompt string.\n__init__() \u2192 None[source]\u00b6\nInitialize the PromptGenerator object.\nStarts with empty lists of constraints, commands, resources,\nand performance evaluations.\nadd_constraint(constraint: str) \u2192 None[source]\u00b6\nAdd a constraint to the constraints list.\nParameters\nconstraint (str) \u2013 The constraint to be added.\nadd_performance_evaluation(evaluation: str) \u2192 None[source]\u00b6\nAdd a performance evaluation item to the performance_evaluation list.\nParameters\nevaluation (str) \u2013 The evaluation item to be added.\nadd_resource(resource: str) \u2192 None[source]\u00b6\nAdd a resource to the resources list.\nParameters\nresource (str) \u2013 The resource to be added.\nadd_tool(tool: BaseTool) \u2192 None[source]\u00b6\ngenerate_prompt_string() \u2192 str[source]\u00b6\nGenerate a prompt string.\nReturns\nThe generated prompt string.\nReturn type\nstr", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.prompt_generator.PromptGenerator.html"}
{"id": "6d9fb02de1be-0", "text": "langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlanner\u00b6\nclass langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlanner[source]\u00b6\nBases: BasePlanner\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam output_parser: langchain_experimental.autonomous_agents.hugginggpt.task_planner.PlanningOutputParser [Required]\u00b6\nparam stop: Optional[List] = None\u00b6\nasync aplan(inputs: dict, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Plan[source]\u00b6\nGiven input, decided what to do.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlanner.html"}
{"id": "6d9fb02de1be-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlanner.html"}
{"id": "6d9fb02de1be-2", "text": "plan(inputs: dict, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Plan[source]\u00b6\nGiven input, decided what to do.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlanner.html"}
{"id": "672fd7f3eff2-0", "text": "langchain_experimental.autonomous_agents.autogpt.output_parser.BaseAutoGPTOutputParser\u00b6\nclass langchain_experimental.autonomous_agents.autogpt.output_parser.BaseAutoGPTOutputParser[source]\u00b6\nBases: BaseOutputParser\nBase Output parser for AutoGPT.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.BaseAutoGPTOutputParser.html"}
{"id": "672fd7f3eff2-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.BaseAutoGPTOutputParser.html"}
{"id": "672fd7f3eff2-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.BaseAutoGPTOutputParser.html"}
{"id": "672fd7f3eff2-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.BaseAutoGPTOutputParser.html"}
{"id": "672fd7f3eff2-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.BaseAutoGPTOutputParser.html"}
{"id": "672fd7f3eff2-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nabstract parse(text: str) \u2192 AutoGPTAction[source]\u00b6\nReturn AutoGPTAction\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.BaseAutoGPTOutputParser.html"}
{"id": "672fd7f3eff2-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.BaseAutoGPTOutputParser.html"}
{"id": "672fd7f3eff2-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.BaseAutoGPTOutputParser.html"}
{"id": "672fd7f3eff2-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.BaseAutoGPTOutputParser.html"}
{"id": "215a52b1a532-0", "text": "langchain_experimental.autonomous_agents.hugginggpt.task_planner.load_chat_planner\u00b6\nlangchain_experimental.autonomous_agents.hugginggpt.task_planner.load_chat_planner(llm: BaseLanguageModel) \u2192 TaskPlanner[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.load_chat_planner.html"}
{"id": "288d37b34980-0", "text": "langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTAction\u00b6\nclass langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTAction(name: str, args: Dict)[source]\u00b6\nAction returned by AutoGPTOutputParser.\nCreate new instance of AutoGPTAction(name, args)\nAttributes\nargs\nAlias for field number 1\nname\nAlias for field number 0\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTAction.html"}
{"id": "67565d446f61-0", "text": "langchain_experimental.autonomous_agents.autogpt.agent.AutoGPT\u00b6\nclass langchain_experimental.autonomous_agents.autogpt.agent.AutoGPT(ai_name: str, memory: VectorStoreRetriever, chain: LLMChain, output_parser: BaseAutoGPTOutputParser, tools: List[BaseTool], feedback_tool: Optional[HumanInputRun] = None, chat_history_memory: Optional[BaseChatMessageHistory] = None)[source]\u00b6\nAgent class for interacting with Auto-GPT.\nMethods\n__init__(ai_name,\u00a0memory,\u00a0chain,\u00a0...[,\u00a0...])\nfrom_llm_and_tools(ai_name,\u00a0ai_role,\u00a0memory,\u00a0...)\nrun(goals)\n__init__(ai_name: str, memory: VectorStoreRetriever, chain: LLMChain, output_parser: BaseAutoGPTOutputParser, tools: List[BaseTool], feedback_tool: Optional[HumanInputRun] = None, chat_history_memory: Optional[BaseChatMessageHistory] = None)[source]\u00b6\nclassmethod from_llm_and_tools(ai_name: str, ai_role: str, memory: VectorStoreRetriever, tools: List[BaseTool], llm: BaseChatModel, human_in_the_loop: bool = False, output_parser: Optional[BaseAutoGPTOutputParser] = None, chat_history_memory: Optional[BaseChatMessageHistory] = None) \u2192 AutoGPT[source]\u00b6\nrun(goals: List[str]) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.agent.AutoGPT.html"}
{"id": "5830e06cf4b1-0", "text": "langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain\u00b6\nclass langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain[source]\u00b6\nBases: LLMChain\nChain to execute tasks.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-1", "text": "param output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-2", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-4", "text": "Generate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-5", "text": "Prepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-6", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-7", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-8", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-9", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, demos: List[Dict] = [{'role': 'user', 'content': \"please show me a video and an image of (based on the text) 'a boy is running' and dub it\"}, {'role': 'assistant', 'content': '[{{\"task\": \"video_generator\", \"id\": 0, \"dep\": [-1], \"args\": {{\"prompt\": \"a boy is running\" }}}}, {{\"task\": \"text_reader\", \"id\": 1, \"dep\": [-1], \"args\": {{\"text\": \"a boy is running\" }}}}, {{\"task\": \"image_generator\", \"id\": 2, \"dep\": [-1], \"args\": {{\"prompt\": \"a boy is running\" }}}}]'}, {'role': 'user', 'content': 'Give you some pictures e1.jpg, e2.png, e3.jpg, help me count the number of sheep?'}, {'role': 'assistant', 'content': '[ {{\"task\": \"image_qa\", \"id\": 0, \"dep\": [-1], \"args\": {{\"image\": \"e1.jpg\", \"question\": \"How many sheep in the picture\"}}}}, {{\"task\": \"image_qa\", \"id\": 1, \"dep\": [-1], \"args\": {{\"image\": \"e2.jpg\", \"question\": \"How many sheep in the picture\"}}}}, {{\"task\": \"image_qa\", \"id\": 2, \"dep\": [-1], \"args\": {{\"image\": \"e3.jpg\", \"question\": \"How many sheep in the picture\"}}}}]'}], verbose: bool = True) \u2192 LLMChain[source]\u00b6\nGet the response parser.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-10", "text": "Get the response parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-11", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-12", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-13", "text": "Validate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-14", "text": "Example\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-15", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-16", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "5830e06cf4b1-17", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.TaskPlaningChain.html"}
{"id": "bf5a1cd22a32-0", "text": "langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain\u00b6\nclass langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain[source]\u00b6\nBases: LLMChain\nChain to prioritize tasks.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-1", "text": "You can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-2", "text": "response. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-4", "text": "Generate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-5", "text": "Prepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-6", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-7", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-8", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, verbose: bool = True) \u2192 LLMChain[source]\u00b6\nGet the response parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-9", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-11", "text": "Parameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-12", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-13", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-14", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "bf5a1cd22a32-15", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain.html"}
{"id": "2f650a7a2d3b-0", "text": "langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain\u00b6\nclass langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain[source]\u00b6\nBases: LLMChain\nChain generating tasks.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-1", "text": "param output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-2", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-4", "text": "Generate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-5", "text": "Prepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-6", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-7", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-8", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, verbose: bool = True) \u2192 LLMChain[source]\u00b6\nGet the response parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-9", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-11", "text": "Parameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-12", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-13", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-14", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "2f650a7a2d3b-15", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_creation.TaskCreationChain.html"}
{"id": "24df683602da-0", "text": "langchain_experimental.autonomous_agents.autogpt.prompt_generator.get_prompt\u00b6\nlangchain_experimental.autonomous_agents.autogpt.prompt_generator.get_prompt(tools: List[BaseTool]) \u2192 str[source]\u00b6\nGenerates a prompt string.\nIt includes various constraints, commands, resources, and performance evaluations.\nReturns\nThe generated prompt string.\nReturn type\nstr", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.prompt_generator.get_prompt.html"}
{"id": "b3a5f6cf05dd-0", "text": "langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTOutputParser\u00b6\nclass langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTOutputParser[source]\u00b6\nBases: BaseAutoGPTOutputParser\nOutput parser for AutoGPT.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTOutputParser.html"}
{"id": "b3a5f6cf05dd-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTOutputParser.html"}
{"id": "b3a5f6cf05dd-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTOutputParser.html"}
{"id": "b3a5f6cf05dd-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTOutputParser.html"}
{"id": "b3a5f6cf05dd-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTOutputParser.html"}
{"id": "b3a5f6cf05dd-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 AutoGPTAction[source]\u00b6\nReturn AutoGPTAction\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTOutputParser.html"}
{"id": "b3a5f6cf05dd-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTOutputParser.html"}
{"id": "b3a5f6cf05dd-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTOutputParser.html"}
{"id": "b3a5f6cf05dd-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.output_parser.AutoGPTOutputParser.html"}
{"id": "ad453bdae0c8-0", "text": "langchain_experimental.autonomous_agents.hugginggpt.task_planner.Step\u00b6\nclass langchain_experimental.autonomous_agents.hugginggpt.task_planner.Step(task: str, id: int, dep: List[int], args: Dict[str, str], tool: BaseTool)[source]\u00b6\nMethods\n__init__(task,\u00a0id,\u00a0dep,\u00a0args,\u00a0tool)\n__init__(task: str, id: int, dep: List[int], args: Dict[str, str], tool: BaseTool)[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.Step.html"}
{"id": "a497bff5e329-0", "text": "langchain_experimental.autonomous_agents.autogpt.memory.AutoGPTMemory\u00b6\nclass langchain_experimental.autonomous_agents.autogpt.memory.AutoGPTMemory[source]\u00b6\nBases: BaseChatMemory\nMemory for AutoGPT.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam chat_memory: BaseChatMessageHistory [Optional]\u00b6\nparam input_key: Optional[str] = None\u00b6\nparam output_key: Optional[str] = None\u00b6\nparam retriever: langchain.schema.vectorstore.VectorStoreRetriever [Required]\u00b6\nVectorStoreRetriever object to connect to.\nparam return_messages: bool = False\u00b6\nclear() \u2192 None\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.memory.AutoGPTMemory.html"}
{"id": "a497bff5e329-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.memory.AutoGPTMemory.html"}
{"id": "a497bff5e329-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nReturn key-value pairs given the text input to the chain.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None\u00b6\nSave context from this conversation to buffer.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty memory_variables: List[str]\u00b6\nThe string keys this memory class will add to chain inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.autogpt.memory.AutoGPTMemory.html"}
{"id": "dff8cb845685-0", "text": "langchain_experimental.autonomous_agents.hugginggpt.task_executor.TaskExecutor\u00b6\nclass langchain_experimental.autonomous_agents.hugginggpt.task_executor.TaskExecutor(plan: Plan)[source]\u00b6\nLoad tools to execute tasks.\nMethods\n__init__(plan)\ncheck_dependency(task)\ncompleted()\ndescribe()\nfailed()\npending()\nrun()\nupdate_args(task)\n__init__(plan: Plan)[source]\u00b6\ncheck_dependency(task: Task) \u2192 bool[source]\u00b6\ncompleted() \u2192 bool[source]\u00b6\ndescribe() \u2192 str[source]\u00b6\nfailed() \u2192 bool[source]\u00b6\npending() \u2192 bool[source]\u00b6\nrun() \u2192 str[source]\u00b6\nupdate_args(task: Task) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_executor.TaskExecutor.html"}
{"id": "28e239921655-0", "text": "langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain\u00b6\nclass langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain[source]\u00b6\nBases: LLMChain\nChain to execute tasks.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Union[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]] [Required]\u00b6\nLanguage model to call.\nparam llm_kwargs: dict [Optional]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-1", "text": "param output_parser: BaseLLMOutputParser [Optional]\u00b6\nOutput parser to use.\nDefaults to one that takes the most likely string but does not change it\notherwise.\nparam prompt: BasePromptTemplate [Required]\u00b6\nPrompt object to use.\nparam return_final_only: bool = True\u00b6\nWhether to return only the final parsed result. Defaults to True.\nIf false, will return a bunch of extra information about the generation.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-2", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\nasync aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-4", "text": "Generate LLM result from inputs.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nUtilize the LLM generate method for speed gains.\napply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 Sequence[Union[str, List[str], Dict[str, str]]]\u00b6\nCall apply and then parse the results.\nasync apredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\nasync apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, str]]\u00b6\nCall apredict and then parse the results.\nasync aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-5", "text": "Prepare prompts from inputs.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-6", "text": "# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-7", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-8", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_outputs(llm_result: LLMResult) \u2192 List[Dict[str, Any]]\u00b6\nCreate outputs from response.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, verbose: bool = True) \u2192 LLMChain[source]\u00b6\nGet the response parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_string(llm: BaseLanguageModel, template: str) \u2192 LLMChain\u00b6\nCreate LLMChain from LLM and template.\ngenerate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 LLMResult\u00b6\nGenerate LLM result from inputs.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-9", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 str\u00b6\nFormat prompt with kwargs and pass to LLM.\nParameters\ncallbacks \u2013 Callbacks to pass to LLMChain", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-11", "text": "Parameters\ncallbacks \u2013 Callbacks to pass to LLMChain\n**kwargs \u2013 Keys to pass to prompt template.\nReturns\nCompletion from LLM.\nExample\ncompletion = llm.predict(adjective=\"funny\")\npredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[str, List[str], Dict[str, Any]]\u00b6\nCall predict and then parse the results.\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[List[PromptValue], Optional[List[str]]]\u00b6\nPrepare prompts from inputs.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-12", "text": "Prepare prompts from inputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-13", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-14", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "28e239921655-15", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.baby_agi.task_execution.TaskExecutionChain.html"}
{"id": "30e32d2a16b6-0", "text": "langchain_experimental.autonomous_agents.hugginggpt.task_planner.PlanningOutputParser\u00b6\nclass langchain_experimental.autonomous_agents.hugginggpt.task_planner.PlanningOutputParser[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.PlanningOutputParser.html"}
{"id": "30e32d2a16b6-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nparse(text: str, hf_tools: List[BaseTool]) \u2192 Plan[source]\u00b6\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.PlanningOutputParser.html"}
{"id": "fd127fce4c26-0", "text": "langchain_experimental.autonomous_agents.hugginggpt.task_planner.Plan\u00b6\nclass langchain_experimental.autonomous_agents.hugginggpt.task_planner.Plan(steps: List[Step])[source]\u00b6\nMethods\n__init__(steps)\n__init__(steps: List[Step])[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/autonomous_agents/langchain_experimental.autonomous_agents.hugginggpt.task_planner.Plan.html"}
{"id": "c91ea208c010-0", "text": "langchain_experimental.plan_and_execute.planners.base.BasePlanner\u00b6\nclass langchain_experimental.plan_and_execute.planners.base.BasePlanner[source]\u00b6\nBases: BaseModel\nBase planner.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nabstract async aplan(inputs: dict, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Plan[source]\u00b6\nGiven input, asynchronously decide what to do.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.base.BasePlanner.html"}
{"id": "c91ea208c010-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.base.BasePlanner.html"}
{"id": "c91ea208c010-2", "text": "abstract plan(inputs: dict, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Plan[source]\u00b6\nGiven input, decide what to do.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.base.BasePlanner.html"}
{"id": "cd9e549b1f51-0", "text": "langchain_experimental.plan_and_execute.planners.chat_planner.load_chat_planner\u00b6\nlangchain_experimental.plan_and_execute.planners.chat_planner.load_chat_planner(llm: BaseLanguageModel, system_prompt: str = \"Let's first understand the problem and devise a plan to solve the problem. Please output the plan starting with the header 'Plan:' and then followed by a numbered list of steps. Please make the plan the minimum number of steps required to accurately complete the task. If the task is a question, the final step should almost always be 'Given the above steps taken, please respond to the users original question'. At the end of your plan, say '<END_OF_PLAN>'\") \u2192 LLMPlanner[source]\u00b6\nLoad a chat planner.\nParameters\nllm \u2013 Language model.\nsystem_prompt \u2013 System prompt.\nReturns\nLLMPlanner", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.chat_planner.load_chat_planner.html"}
{"id": "c5e0a224f23d-0", "text": "langchain_experimental.plan_and_execute.schema.BaseStepContainer\u00b6\nclass langchain_experimental.plan_and_execute.schema.BaseStepContainer[source]\u00b6\nBases: BaseModel\nBase step container.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nabstract add_step(step: Step, step_response: StepResponse) \u2192 None[source]\u00b6\nAdd step and step response to the container.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.BaseStepContainer.html"}
{"id": "c5e0a224f23d-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nabstract get_final_response() \u2192 str[source]\u00b6\nReturn the final response based on steps taken.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.BaseStepContainer.html"}
{"id": "c5e0a224f23d-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.BaseStepContainer.html"}
{"id": "f3c741a3e2cf-0", "text": "langchain_experimental.plan_and_execute.schema.PlanOutputParser\u00b6\nclass langchain_experimental.plan_and_execute.schema.PlanOutputParser[source]\u00b6\nBases: BaseOutputParser\nPlan output parser.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.PlanOutputParser.html"}
{"id": "f3c741a3e2cf-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.PlanOutputParser.html"}
{"id": "f3c741a3e2cf-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.PlanOutputParser.html"}
{"id": "f3c741a3e2cf-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.PlanOutputParser.html"}
{"id": "f3c741a3e2cf-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.PlanOutputParser.html"}
{"id": "f3c741a3e2cf-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nabstract parse(text: str) \u2192 Plan[source]\u00b6\nParse into a plan.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.PlanOutputParser.html"}
{"id": "f3c741a3e2cf-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.PlanOutputParser.html"}
{"id": "f3c741a3e2cf-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.PlanOutputParser.html"}
{"id": "f3c741a3e2cf-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.PlanOutputParser.html"}
{"id": "64b99234be11-0", "text": "langchain_experimental.plan_and_execute.executors.base.BaseExecutor\u00b6\nclass langchain_experimental.plan_and_execute.executors.base.BaseExecutor[source]\u00b6\nBases: BaseModel\nBase executor.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nabstract async astep(inputs: dict, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 StepResponse[source]\u00b6\nTake async step.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.executors.base.BaseExecutor.html"}
{"id": "64b99234be11-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.executors.base.BaseExecutor.html"}
{"id": "64b99234be11-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nabstract step(inputs: dict, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 StepResponse[source]\u00b6\nTake step.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.executors.base.BaseExecutor.html"}
{"id": "b6433dc0b222-0", "text": "langchain_experimental.plan_and_execute.schema.ListStepContainer\u00b6\nclass langchain_experimental.plan_and_execute.schema.ListStepContainer[source]\u00b6\nBases: BaseStepContainer\nList step container.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam steps: List[Tuple[langchain_experimental.plan_and_execute.schema.Step, langchain_experimental.plan_and_execute.schema.StepResponse]] [Optional]\u00b6\nThe steps.\nadd_step(step: Step, step_response: StepResponse) \u2192 None[source]\u00b6\nAdd step and step response to the container.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.ListStepContainer.html"}
{"id": "b6433dc0b222-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_final_response() \u2192 str[source]\u00b6\nReturn the final response based on steps taken.\nget_steps() \u2192 List[Tuple[Step, StepResponse]][source]\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.ListStepContainer.html"}
{"id": "b6433dc0b222-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.ListStepContainer.html"}
{"id": "d24e78dcd7b5-0", "text": "langchain_experimental.plan_and_execute.schema.Step\u00b6\nclass langchain_experimental.plan_and_execute.schema.Step[source]\u00b6\nBases: BaseModel\nStep.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam value: str [Required]\u00b6\nThe value.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.Step.html"}
{"id": "d24e78dcd7b5-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.Step.html"}
{"id": "639e7390cf04-0", "text": "langchain_experimental.plan_and_execute.executors.agent_executor.load_agent_executor\u00b6\nlangchain_experimental.plan_and_execute.executors.agent_executor.load_agent_executor(llm: BaseLanguageModel, tools: List[BaseTool], verbose: bool = False, include_task_in_prompt: bool = False) \u2192 ChainExecutor[source]\u00b6\nLoad an agent executor.\nParameters\nllm \u2013 BaseLanguageModel\ntools \u2013 List[BaseTool]\nverbose \u2013 bool. Defaults to False.\ninclude_task_in_prompt \u2013 bool. Defaults to False.\nReturns\nChainExecutor", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.executors.agent_executor.load_agent_executor.html"}
{"id": "3aac5f77c4a3-0", "text": "langchain_experimental.plan_and_execute.planners.chat_planner.PlanningOutputParser\u00b6\nclass langchain_experimental.plan_and_execute.planners.chat_planner.PlanningOutputParser[source]\u00b6\nBases: PlanOutputParser\nPlanning output parser.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.chat_planner.PlanningOutputParser.html"}
{"id": "3aac5f77c4a3-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.chat_planner.PlanningOutputParser.html"}
{"id": "3aac5f77c4a3-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.chat_planner.PlanningOutputParser.html"}
{"id": "3aac5f77c4a3-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.chat_planner.PlanningOutputParser.html"}
{"id": "3aac5f77c4a3-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.chat_planner.PlanningOutputParser.html"}
{"id": "3aac5f77c4a3-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Plan[source]\u00b6\nParse into a plan.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.chat_planner.PlanningOutputParser.html"}
{"id": "3aac5f77c4a3-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.chat_planner.PlanningOutputParser.html"}
{"id": "3aac5f77c4a3-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.chat_planner.PlanningOutputParser.html"}
{"id": "3aac5f77c4a3-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.chat_planner.PlanningOutputParser.html"}
{"id": "dbb06b635548-0", "text": "langchain_experimental.plan_and_execute.executors.base.ChainExecutor\u00b6\nclass langchain_experimental.plan_and_execute.executors.base.ChainExecutor[source]\u00b6\nBases: BaseExecutor\nChain executor.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam chain: langchain.chains.base.Chain [Required]\u00b6\nThe chain to use.\nasync astep(inputs: dict, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 StepResponse[source]\u00b6\nTake step.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.executors.base.ChainExecutor.html"}
{"id": "dbb06b635548-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.executors.base.ChainExecutor.html"}
{"id": "dbb06b635548-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstep(inputs: dict, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 StepResponse[source]\u00b6\nTake step.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.executors.base.ChainExecutor.html"}
{"id": "764e3cdb8347-0", "text": "langchain_experimental.plan_and_execute.planners.base.LLMPlanner\u00b6\nclass langchain_experimental.plan_and_execute.planners.base.LLMPlanner[source]\u00b6\nBases: BasePlanner\nLLM planner.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nThe LLM chain to use.\nparam output_parser: langchain_experimental.plan_and_execute.schema.PlanOutputParser [Required]\u00b6\nThe output parser to use.\nparam stop: Optional[List] = None\u00b6\nThe stop list to use.\nasync aplan(inputs: dict, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Plan[source]\u00b6\nGiven input, asynchronously decide what to do.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.base.LLMPlanner.html"}
{"id": "764e3cdb8347-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.base.LLMPlanner.html"}
{"id": "764e3cdb8347-2", "text": "plan(inputs: dict, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Plan[source]\u00b6\nGiven input, decide what to do.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.planners.base.LLMPlanner.html"}
{"id": "71ac42396996-0", "text": "langchain_experimental.plan_and_execute.schema.StepResponse\u00b6\nclass langchain_experimental.plan_and_execute.schema.StepResponse[source]\u00b6\nBases: BaseModel\nStep response.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam response: str [Required]\u00b6\nThe response.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.StepResponse.html"}
{"id": "71ac42396996-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.StepResponse.html"}
{"id": "6331aa868e0e-0", "text": "langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute\u00b6\nclass langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute[source]\u00b6\nBases: Chain\nPlan and execute a chain of steps.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam executor: langchain_experimental.plan_and_execute.executors.base.BaseExecutor [Required]\u00b6\nThe executor to use.\nparam input_key: str = 'input'\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam output_key: str = 'output'\u00b6\nparam planner: langchain_experimental.plan_and_execute.planners.base.BasePlanner [Required]\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "6331aa868e0e-1", "text": "The planner to use.\nparam step_container: langchain_experimental.plan_and_execute.schema.BaseStepContainer [Optional]\u00b6\nThe step container to use.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "6331aa868e0e-2", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "6331aa868e0e-3", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "6331aa868e0e-4", "text": "method expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "6331aa868e0e-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "6331aa868e0e-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "6331aa868e0e-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "6331aa868e0e-8", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "6331aa868e0e-9", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "6331aa868e0e-10", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "6331aa868e0e-11", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "6331aa868e0e-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "6331aa868e0e-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nKeys expected to be in the chain input.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nKeys expected to be in the chain output.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.agent_executor.PlanAndExecute.html"}
{"id": "e9ca751584e9-0", "text": "langchain_experimental.plan_and_execute.schema.Plan\u00b6\nclass langchain_experimental.plan_and_execute.schema.Plan[source]\u00b6\nBases: BaseModel\nPlan.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam steps: List[langchain_experimental.plan_and_execute.schema.Step] [Required]\u00b6\nThe steps.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.Plan.html"}
{"id": "e9ca751584e9-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.Plan.html"}
{"id": "e9ca751584e9-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/plan_and_execute/langchain_experimental.plan_and_execute.schema.Plan.html"}
{"id": "d3f406677a0b-0", "text": "langchain.agents.agent.MultiActionAgentOutputParser\u00b6\nclass langchain.agents.agent.MultiActionAgentOutputParser[source]\u00b6\nBases: BaseOutputParser[Union[List[AgentAction], AgentFinish]]\nBase class for parsing agent output into agent actions/finish.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.MultiActionAgentOutputParser.html"}
{"id": "d3f406677a0b-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.MultiActionAgentOutputParser.html"}
{"id": "d3f406677a0b-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.MultiActionAgentOutputParser.html"}
{"id": "d3f406677a0b-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.MultiActionAgentOutputParser.html"}
{"id": "d3f406677a0b-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.MultiActionAgentOutputParser.html"}
{"id": "d3f406677a0b-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nabstract parse(text: str) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6\nParse text into agent actions/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.MultiActionAgentOutputParser.html"}
{"id": "d3f406677a0b-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.MultiActionAgentOutputParser.html"}
{"id": "d3f406677a0b-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.MultiActionAgentOutputParser.html"}
{"id": "d3f406677a0b-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.MultiActionAgentOutputParser.html"}
{"id": "f5848a1a1b7e-0", "text": "langchain.agents.agent.BaseSingleActionAgent\u00b6\nclass langchain.agents.agent.BaseSingleActionAgent[source]\u00b6\nBases: BaseModel\nBase Single Action Agent class.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nabstract async aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.BaseSingleActionAgent.html"}
{"id": "f5848a1a1b7e-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict[source]\u00b6\nReturn dictionary representation of agent.\nclassmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, **kwargs: Any) \u2192 BaseSingleActionAgent[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]][source]\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.BaseSingleActionAgent.html"}
{"id": "f5848a1a1b7e-2", "text": "abstract plan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish[source]\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None[source]\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict[source]\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty return_values: List[str]\u00b6\nReturn values of the agent.\nExamples using BaseSingleActionAgent\u00b6\nAgents\nCustom agent", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.BaseSingleActionAgent.html"}
{"id": "cd477e6e2a5b-0", "text": "langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreToolkit\u00b6\nclass langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for interacting with a Vector Store.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam llm: langchain.schema.language_model.BaseLanguageModel [Optional]\u00b6\nparam vectorstore_info: langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreInfo [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreToolkit.html"}
{"id": "cd477e6e2a5b-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreToolkit.html"}
{"id": "cd477e6e2a5b-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using VectorStoreToolkit\u00b6\nVectorstore", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreToolkit.html"}
{"id": "1d03260bc410-0", "text": "langchain.agents.loading.load_agent\u00b6\nlangchain.agents.loading.load_agent(path: Union[str, Path], **kwargs: Any) \u2192 Union[BaseSingleActionAgent, BaseMultiActionAgent][source]\u00b6\nUnified method for loading an agent from LangChainHub or local fs.\nParameters\npath \u2013 Path to the agent file.\n**kwargs \u2013 Additional keyword arguments passed to the agent executor.\nReturns\nAn agent executor.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.loading.load_agent.html"}
{"id": "a3f217021cb0-0", "text": "langchain.agents.agent_toolkits.spark_sql.toolkit.SparkSQLToolkit\u00b6\nclass langchain.agents.agent_toolkits.spark_sql.toolkit.SparkSQLToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for interacting with Spark SQL.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam db: langchain.utilities.spark_sql.SparkSQL [Required]\u00b6\nparam llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.spark_sql.toolkit.SparkSQLToolkit.html"}
{"id": "a3f217021cb0-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.spark_sql.toolkit.SparkSQLToolkit.html"}
{"id": "a3f217021cb0-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using SparkSQLToolkit\u00b6\nSpark SQL", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.spark_sql.toolkit.SparkSQLToolkit.html"}
{"id": "11401a981072-0", "text": "langchain.agents.agent_toolkits.json.toolkit.JsonToolkit\u00b6\nclass langchain.agents.agent_toolkits.json.toolkit.JsonToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for interacting with a JSON spec.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam spec: langchain.tools.json.tool.JsonSpec [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.json.toolkit.JsonToolkit.html"}
{"id": "11401a981072-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.json.toolkit.JsonToolkit.html"}
{"id": "11401a981072-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using JsonToolkit\u00b6\nJSON", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.json.toolkit.JsonToolkit.html"}
{"id": "1120b911b253-0", "text": "langchain.agents.agent_toolkits.multion.toolkit.MultionToolkit\u00b6\nclass langchain.agents.agent_toolkits.multion.toolkit.MultionToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for interacting with the Browser Agent.\nSecurity Note: This toolkit contains tools that interact with theuser\u2019s browser via the multion API which grants an agent\naccess to the user\u2019s browser.\nPlease review the documentation for the multion API to understand\nthe security implications of using this toolkit.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.multion.toolkit.MultionToolkit.html"}
{"id": "1120b911b253-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.multion.toolkit.MultionToolkit.html"}
{"id": "1120b911b253-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using MultionToolkit\u00b6\nMultiOn", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.multion.toolkit.MultionToolkit.html"}
{"id": "e9fc817b8eec-0", "text": "langchain.agents.agent_toolkits.openapi.toolkit.OpenAPIToolkit\u00b6\nclass langchain.agents.agent_toolkits.openapi.toolkit.OpenAPIToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for interacting with an OpenAPI API.\nSecurity Note: This toolkit contains tools that can read and modifythe state of a service; e.g., by creating, deleting, or updating,\nreading underlying data.\nFor example, this toolkit can be used to delete data exposed via\nan OpenAPI compliant API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam json_agent: langchain.agents.agent.AgentExecutor [Required]\u00b6\nparam requests_wrapper: langchain.utilities.requests.TextRequestsWrapper [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.toolkit.OpenAPIToolkit.html"}
{"id": "e9fc817b8eec-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_llm(llm: BaseLanguageModel, json_spec: JsonSpec, requests_wrapper: TextRequestsWrapper, **kwargs: Any) \u2192 OpenAPIToolkit[source]\u00b6\nCreate json agent from llm, then initialize.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.toolkit.OpenAPIToolkit.html"}
{"id": "e9fc817b8eec-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using OpenAPIToolkit\u00b6\nOpenAPI", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.toolkit.OpenAPIToolkit.html"}
{"id": "e5ad1489906a-0", "text": "langchain.agents.openai_assistant.base.OpenAIAssistantAction\u00b6\nclass langchain.agents.openai_assistant.base.OpenAIAssistantAction[source]\u00b6\nBases: AgentAction\nAgentAction with info needed to submit custom tool output to existing run.\nOverride init to support instantiation by position for backward compat.\nparam log: str [Required]\u00b6\nAdditional information to log about the action.\nThis log can be used in a few ways. First, it can be used to audit\nwhat exactly the LLM predicted to lead to this (tool, tool_input).\nSecond, it can be used in future iterations to show the LLMs prior\nthoughts. This is useful when (tool, tool_input) does not contain\nfull information about the LLM prediction (for example, any thought\nbefore the tool/tool_input).\nparam run_id: str [Required]\u00b6\nparam thread_id: str [Required]\u00b6\nparam tool: str [Required]\u00b6\nThe name of the Tool to execute.\nparam tool_call_id: str [Required]\u00b6\nparam tool_input: Union[str, dict] [Required]\u00b6\nThe input to pass in to the Tool.\nparam type: Literal['AgentAction'] = 'AgentAction'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantAction.html"}
{"id": "e5ad1489906a-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether or not the class is serializable.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantAction.html"}
{"id": "e5ad1489906a-2", "text": "Return whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantAction.html"}
{"id": "e5ad1489906a-3", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantAction.html"}
{"id": "0d865746740e-0", "text": "langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreRouterToolkit\u00b6\nclass langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreRouterToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for routing between Vector Stores.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam llm: langchain.schema.language_model.BaseLanguageModel [Optional]\u00b6\nparam vectorstores: List[langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreInfo] [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreRouterToolkit.html"}
{"id": "0d865746740e-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreRouterToolkit.html"}
{"id": "0d865746740e-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using VectorStoreRouterToolkit\u00b6\nVectorstore", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreRouterToolkit.html"}
{"id": "09e51f484c2d-0", "text": "langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit\u00b6\nclass langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for interacting with Power BI dataset.\nSecurity Note: This toolkit interacts with an external service.\nControl access to who can use this toolkit.\nMake sure that the capabilities given by this toolkit to the calling\ncode are appropriately scoped to the application.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[langchain.schema.callbacks.base.BaseCallbackManager] = None\u00b6\nparam examples: Optional[str] = None\u00b6\nparam llm: Union[langchain.schema.language_model.BaseLanguageModel, langchain.chat_models.base.BaseChatModel] [Required]\u00b6\nparam max_iterations: int = 5\u00b6\nparam output_token_limit: Optional[int] = None\u00b6\nparam powerbi: langchain.utilities.powerbi.PowerBIDataset [Required]\u00b6\nparam tiktoken_model_name: Optional[str] = None\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit.html"}
{"id": "09e51f484c2d-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit.html"}
{"id": "09e51f484c2d-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using PowerBIToolkit\u00b6\nPowerBI Dataset", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit.html"}
{"id": "79b61e1c745e-0", "text": "langchain.agents.agent.AgentExecutor\u00b6\nclass langchain.agents.agent.AgentExecutor[source]\u00b6\nBases: Chain\nAgent that is using tools.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam agent: Union[BaseSingleActionAgent, BaseMultiActionAgent] [Required]\u00b6\nThe agent to run for creating a plan and determining actions\nto take at each step of the execution loop.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam early_stopping_method: str = 'force'\u00b6\nThe method to use for early stopping if the agent never\nreturns AgentFinish. Either \u2018force\u2019 or \u2018generate\u2019.\n\u201cforce\u201d returns a string saying that it stopped because it met atime or iteration limit.\n\u201cgenerate\u201d calls the agent\u2019s LLM Chain one final time to generatea final answer based on the previous steps.\nparam handle_parsing_errors: Union[bool, str, Callable[[OutputParserException], str]] = False\u00b6\nHow to handle errors raised by the agent\u2019s output parser.\nDefaults to False, which raises the error.\nIf true, the error will be sent back to the LLM as an observation.\nIf a string, the string itself will be sent to the LLM as an observation.\nIf a callable function, the function will be called with the exception", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-1", "text": "If a callable function, the function will be called with the exception\nas an argument, and the result of that function will be passed to the agentas an observation.\nparam max_execution_time: Optional[float] = None\u00b6\nThe maximum amount of wall clock time to spend in the execution\nloop.\nparam max_iterations: Optional[int] = 15\u00b6\nThe maximum number of steps to take before ending the execution\nloop.\nSetting to \u2018None\u2019 could lead to an infinite loop.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam return_intermediate_steps: bool = False\u00b6\nWhether to return the agent\u2019s trajectory of intermediate steps\nat the end in addition to the final output.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tools: Sequence[BaseTool] [Required]\u00b6\nThe valid tools the agent can call.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-2", "text": "The valid tools the agent can call.\nparam trim_intermediate_steps: Union[int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]] = -1\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-3", "text": "include_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-4", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-5", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-6", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-7", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-8", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_agent_and_tools(agent: Union[BaseSingleActionAgent, BaseMultiActionAgent], tools: Sequence[BaseTool], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 AgentExecutor[source]\u00b6\nCreate from agent and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-9", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\niter(inputs: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, include_run_info: bool = False, async_: bool = False) \u2192 AgentExecutorIterator[source]\u00b6\nEnables iteration over steps taken to reach final output.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-10", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nlookup_tool(name: str) \u2192 BaseTool[source]\u00b6\nLookup tool by name.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-11", "text": "inputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-12", "text": "chain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None[source]\u00b6\nRaise error - saving not supported for Agent Executors.\nsave_agent(file_path: Union[Path, str]) \u2192 None[source]\u00b6\nSave the underlying agent.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-13", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-14", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using AgentExecutor\u00b6\nMetaphor Search\nLLMonitor\nJina\nPowerBI Dataset\nSQL Database\nJSON\nBittensor\nConversational Retrieval Agent\nAgents\nBabyAGI with Tools\nPlug-and-Plai\nWikibase Agent\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nCustom Agent with PlugIn Retrieval\nSet env var OPENAI_API_KEY or load from a .env file\nSQL", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "79b61e1c745e-15", "text": "Set env var OPENAI_API_KEY or load from a .env file\nSQL\nMessage Memory in Agent backed by a database\nMemory in Agent\nXML Agent\nCustom MRKL agent\nShared memory across agents and tools\nCustom multi-action agent\nRunning Agent as an Iterator\nCustom agent\nCustom agent with tool retrieval", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html"}
{"id": "577e56ce8b41-0", "text": "langchain.agents.agent.RunnableMultiActionAgent\u00b6\nclass langchain.agents.agent.RunnableMultiActionAgent[source]\u00b6\nBases: BaseMultiActionAgent\nAgent powered by runnables.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam runnable: langchain.schema.runnable.base.Runnable[dict, Union[List[langchain.schema.agent.AgentAction], langchain.schema.agent.AgentFinish]] [Required]\u00b6\nRunnable to call to get agent actions.\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.RunnableMultiActionAgent.html"}
{"id": "577e56ce8b41-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]]\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.RunnableMultiActionAgent.html"}
{"id": "577e56ce8b41-2", "text": "plan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with the observations.\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty input_keys: List[str]\u00b6\nReturn the input keys.\nReturns\nList of input keys.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.RunnableMultiActionAgent.html"}
{"id": "4bafb655ddf1-0", "text": "langchain.agents.agent_toolkits.spark_sql.base.create_spark_sql_agent\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.spark_sql.base.create_spark_sql_agent.html"}
{"id": "4bafb655ddf1-1", "text": "langchain.agents.agent_toolkits.spark_sql.base.create_spark_sql_agent(llm: BaseLanguageModel, toolkit: SparkSQLToolkit, callback_manager: Optional[BaseCallbackManager] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, prefix: str = '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: str = '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: str = '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", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.spark_sql.base.create_spark_sql_agent.html"}
{"id": "4bafb655ddf1-2", "text": "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: Optional[List[str]] = None, top_k: int = 10, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = 'force', verbose: bool = False, agent_executor_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 AgentExecutor[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.spark_sql.base.create_spark_sql_agent.html"}
{"id": "4bafb655ddf1-3", "text": "Construct a Spark SQL agent from an LLM and tools.\nExamples using create_spark_sql_agent\u00b6\nSpark SQL", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.spark_sql.base.create_spark_sql_agent.html"}
{"id": "7ea4df769009-0", "text": "langchain.agents.chat.output_parser.ChatOutputParser\u00b6\nclass langchain.agents.chat.output_parser.ChatOutputParser[source]\u00b6\nBases: AgentOutputParser\nOutput parser for the chat agent.\nparam pattern = re.compile('^.*?`{3}(?:json)?\\\\n(.*?)`{3}.*?$', re.DOTALL)\u00b6\nRegex pattern to parse the output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.output_parser.ChatOutputParser.html"}
{"id": "7ea4df769009-1", "text": "Parameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.output_parser.ChatOutputParser.html"}
{"id": "7ea4df769009-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.output_parser.ChatOutputParser.html"}
{"id": "7ea4df769009-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.output_parser.ChatOutputParser.html"}
{"id": "7ea4df769009-4", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.output_parser.ChatOutputParser.html"}
{"id": "7ea4df769009-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.output_parser.ChatOutputParser.html"}
{"id": "7ea4df769009-6", "text": "to retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.output_parser.ChatOutputParser.html"}
{"id": "7ea4df769009-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.output_parser.ChatOutputParser.html"}
{"id": "7ea4df769009-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.output_parser.ChatOutputParser.html"}
{"id": "dc6a321cb309-0", "text": "langchain.agents.agent_toolkits.jira.toolkit.JiraToolkit\u00b6\nclass langchain.agents.agent_toolkits.jira.toolkit.JiraToolkit[source]\u00b6\nBases: BaseToolkit\nJira Toolkit.\nSecurity Note: This toolkit contains tools that can read and modifythe state of a service; e.g., by creating, deleting, or updating,\nreading underlying data.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam tools: List[langchain.tools.base.BaseTool] = []\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.jira.toolkit.JiraToolkit.html"}
{"id": "dc6a321cb309-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_jira_api_wrapper(jira_api_wrapper: JiraAPIWrapper) \u2192 JiraToolkit[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.jira.toolkit.JiraToolkit.html"}
{"id": "dc6a321cb309-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using JiraToolkit\u00b6\nJira", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.jira.toolkit.JiraToolkit.html"}
{"id": "122e7e76a6ae-0", "text": "langchain_experimental.agents.agent_toolkits.xorbits.base.create_xorbits_agent\u00b6\nlangchain_experimental.agents.agent_toolkits.xorbits.base.create_xorbits_agent(llm: BaseLLM, data: Any, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = '', suffix: str = '', input_variables: Optional[List[str]] = None, verbose: bool = False, return_intermediate_steps: bool = False, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = 'force', agent_executor_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Dict[str, Any]) \u2192 AgentExecutor[source]\u00b6\nConstruct a xorbits agent from an LLM and dataframe.\nExamples using create_xorbits_agent\u00b6\nXorbits", "source": "lang/api.python.langchain.com/en/latest/agents/langchain_experimental.agents.agent_toolkits.xorbits.base.create_xorbits_agent.html"}
{"id": "a390b001c7f0-0", "text": "langchain.agents.agent_toolkits.gitlab.toolkit.GitLabToolkit\u00b6\nclass langchain.agents.agent_toolkits.gitlab.toolkit.GitLabToolkit[source]\u00b6\nBases: BaseToolkit\nGitLab Toolkit.\nSecurity Note: This toolkit contains tools that can read and modifythe state of a service; e.g., by creating, deleting, or updating,\nreading underlying data.\nFor example, this toolkit can be used to create issues, pull requests,\nand comments on GitLab.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam tools: List[langchain.tools.base.BaseTool] = []\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.gitlab.toolkit.GitLabToolkit.html"}
{"id": "a390b001c7f0-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_gitlab_api_wrapper(gitlab_api_wrapper: GitLabAPIWrapper) \u2192 GitLabToolkit[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.gitlab.toolkit.GitLabToolkit.html"}
{"id": "a390b001c7f0-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using GitLabToolkit\u00b6\nGitlab", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.gitlab.toolkit.GitLabToolkit.html"}
{"id": "6cf732ec760f-0", "text": "langchain.agents.load_tools.load_tools\u00b6\nlangchain.agents.load_tools.load_tools(tool_names: List[str], llm: Optional[BaseLanguageModel] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 List[BaseTool][source]\u00b6\nLoad tools based on their name.\nTools allow agents to interact with various resources and services like\nAPIs, databases, file systems, etc.\nPlease scope the permissions of each tools to the minimum required for the\napplication.\nFor example, if an application only needs to read from a database,\nthe database tool should not be given write permissions. Moreover\nconsider scoping the permissions to only allow accessing specific\ntables and impose user-level quota for limiting resource usage.\nPlease read the APIs of the individual tools to determine which configuration\nthey support.\nSee [Security](https://python.langchain.com/docs/security) for more information.\nParameters\ntool_names \u2013 name of tools to load.\nllm \u2013 An optional language model, may be needed to initialize certain tools.\ncallbacks \u2013 Optional callback manager or list of callback handlers.\nIf not provided, default global callback manager will be used.\nReturns\nList of tools.\nExamples using load_tools\u00b6\nChatGPT Plugins\nHuman as a tool\nAWS Lambda\nGoogle Drive\nRequests\nOpenWeatherMap\nSearch Tools\nEleven Labs Text2Speech\nArXiv\nGraphQL\nSceneXplain\nDall-E Image Generator\nLLMonitor\nArgilla\nStreamlit\nSerpAPI\nComet\nAim\nGolden\nWeights & Biases\nSageMaker Tracking\nWolfram Alpha\nMLflow\nDataForSEO\nSearxNG Search API\nGoogle Serper\nFlyte\nWandB Tracing\nClearML\nGoogle Search\nLog, Trace, and Monitor\nPortkey\nGoogle Drive tool", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.load_tools.load_tools.html"}
{"id": "6cf732ec760f-1", "text": "ClearML\nGoogle Search\nLog, Trace, and Monitor\nPortkey\nGoogle Drive tool\nBittensor\nAmazon API Gateway\nDebugging\nLangSmith Walkthrough\nAgents\nAgent Debates with Tools\nMultiple callback handlers\nDefining Custom Tools\nHuman-in-the-loop Tool Validation\nAccess intermediate steps\nTimeouts for agents\nStreaming final agent output\nCap the max number of iterations\nAsync API\nHuman input chat model\nFake LLM\nTracking token usage\nHuman input LLM", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.load_tools.load_tools.html"}
{"id": "abc078874606-0", "text": "langchain.agents.self_ask_with_search.base.SelfAskWithSearchAgent\u00b6\nclass langchain.agents.self_ask_with_search.base.SelfAskWithSearchAgent[source]\u00b6\nBases: Agent\nAgent for the self-ask-with-search paper.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_tools: Optional[List[str]] = None\u00b6\nparam llm_chain: LLMChain [Required]\u00b6\nparam output_parser: langchain.agents.agent.AgentOutputParser [Optional]\u00b6\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchAgent.html"}
{"id": "abc078874606-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nclassmethod create_prompt(tools: Sequence[BaseTool]) \u2192 BasePromptTemplate[source]\u00b6\nPrompt does not depend on tools.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.\nclassmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, **kwargs: Any) \u2192 Agent\u00b6\nConstruct an agent from an LLM and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]]\u00b6\nget_full_inputs(intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nCreate the full inputs for the LLMChain from intermediate steps.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchAgent.html"}
{"id": "abc078874606-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchAgent.html"}
{"id": "abc078874606-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty llm_prefix: str\u00b6\nPrefix to append the LLM call with.\nproperty observation_prefix: str\u00b6\nPrefix to append the observation with.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchAgent.html"}
{"id": "53d7eae22e32-0", "text": "langchain.agents.agent_toolkits.sql.toolkit.SQLDatabaseToolkit\u00b6\nclass langchain.agents.agent_toolkits.sql.toolkit.SQLDatabaseToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for interacting with SQL databases.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam db: langchain.utilities.sql_database.SQLDatabase [Required]\u00b6\nparam llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.sql.toolkit.SQLDatabaseToolkit.html"}
{"id": "53d7eae22e32-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.sql.toolkit.SQLDatabaseToolkit.html"}
{"id": "53d7eae22e32-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty dialect: str\u00b6\nReturn string representation of SQL dialect to use.\nExamples using SQLDatabaseToolkit\u00b6\nCnosDB\nSQL Database\nSet env var OPENAI_API_KEY or load from a .env file\nSQL\nUse ToolKits with OpenAI Functions", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.sql.toolkit.SQLDatabaseToolkit.html"}
{"id": "bb3cfc7163e5-0", "text": "langchain.agents.agent_toolkits.powerbi.base.create_pbi_agent\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.base.create_pbi_agent.html"}
{"id": "bb3cfc7163e5-1", "text": "langchain.agents.agent_toolkits.powerbi.base.create_pbi_agent(llm: BaseLanguageModel, toolkit: Optional[PowerBIToolkit] = None, powerbi: Optional[PowerBIDataset] = None, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = '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, 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: str = '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: str = '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...", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.base.create_pbi_agent.html"}
{"id": "bb3cfc7163e5-2", "text": "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: Optional[str] = None, input_variables: Optional[List[str]] = None, top_k: int = 10, verbose: bool = False, agent_executor_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 AgentExecutor[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.base.create_pbi_agent.html"}
{"id": "bb3cfc7163e5-3", "text": "Construct a Power BI agent from an LLM and tools.\nExamples using create_pbi_agent\u00b6\nPowerBI Dataset", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.base.create_pbi_agent.html"}
{"id": "64e8cad7263f-0", "text": "langchain.agents.output_parsers.self_ask.SelfAskOutputParser\u00b6\nclass langchain.agents.output_parsers.self_ask.SelfAskOutputParser[source]\u00b6\nBases: AgentOutputParser\nParses self-ask style LLM calls.\nExpects output to be in one of two formats.\nIf the output signals that an action should be taken,\nshould be in the below format. This will result in an AgentAction\nbeing returned.\n`\nThoughts go here...\nFollow up: what is the temperature in SF?\n`\nIf the output signals that a final answer should be given,\nshould be in the below format. This will result in an AgentFinish\nbeing returned.\n`\nThoughts go here...\nSo the final answer is: The temperature is 100 degrees\n`\nparam finish_string: str = 'So the final answer is: '\u00b6\nparam followups: Sequence[str] = ('Follow up:', 'Followup:')\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "64e8cad7263f-1", "text": "Subclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "64e8cad7263f-2", "text": "step, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "64e8cad7263f-3", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "64e8cad7263f-4", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "64e8cad7263f-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "64e8cad7263f-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "64e8cad7263f-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "64e8cad7263f-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "64e8cad7263f-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "cee1e72e860b-0", "text": "langchain.agents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing\u00b6\nclass langchain.agents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing[source]\u00b6\nBases: BaseRequestsTool, BaseTool\nRequests PATCH tool with LLM-instructed extraction of truncated responses.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this when you want to PATCH content on a website.\\nInput to the tool should be a json string with 3 keys: \"url\", \"data\", and \"output_instructions\".\\nThe value of \"url\" should be a string.\\nThe value of \"data\" should be a dictionary of key-value pairs of the body params available in the OpenAPI spec you want to PATCH the content with at the url.\\nThe value of \"output_instructions\" should be instructions on what information to extract from the response, for example the id(s) for a resource(s) that the PATCH request creates.\\nAlways use double quotes for strings in the json string.'\u00b6\nTool description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam llm_chain: langchain.chains.llm.LLMChain [Optional]\u00b6\nLLMChain used to extract the response.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing.html"}
{"id": "cee1e72e860b-1", "text": "Optional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'requests_patch'\u00b6\nTool name.\nparam requests_wrapper: TextRequestsWrapper [Required]\u00b6\nparam response_length: Optional[int] = 5000\u00b6\nMaximum length of the response to be returned.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing.html"}
{"id": "cee1e72e860b-2", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing.html"}
{"id": "cee1e72e860b-3", "text": "step, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing.html"}
{"id": "cee1e72e860b-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing.html"}
{"id": "cee1e72e860b-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing.html"}
{"id": "cee1e72e860b-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing.html"}
{"id": "cee1e72e860b-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing.html"}
{"id": "cee1e72e860b-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing.html"}
{"id": "cee1e72e860b-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing.html"}
{"id": "a3a53c80d599-0", "text": "langchain.agents.load_tools.load_huggingface_tool\u00b6\nlangchain.agents.load_tools.load_huggingface_tool(task_or_repo_id: str, model_repo_id: Optional[str] = None, token: Optional[str] = None, remote: bool = False, **kwargs: Any) \u2192 BaseTool[source]\u00b6\nLoads a tool from the HuggingFace Hub.\nParameters\ntask_or_repo_id \u2013 Task or model repo id.\nmodel_repo_id \u2013 Optional model repo id.\ntoken \u2013 Optional token.\nremote \u2013 Optional remote. Defaults to False.\n**kwargs \u2013 \nReturns\nA tool.\nExamples using load_huggingface_tool\u00b6\nHuggingFace Hub Tools", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.load_tools.load_huggingface_tool.html"}
{"id": "7d4060db05ea-0", "text": "langchain.agents.tools.InvalidTool\u00b6\nclass langchain.agents.tools.InvalidTool[source]\u00b6\nBases: BaseTool\nTool that is run when invalid tool name is encountered by agent.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Called when tool name is invalid. Suggests valid tool names.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'invalid_tool'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.tools.InvalidTool.html"}
{"id": "7d4060db05ea-1", "text": "These tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.tools.InvalidTool.html"}
{"id": "7d4060db05ea-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.tools.InvalidTool.html"}
{"id": "7d4060db05ea-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.tools.InvalidTool.html"}
{"id": "7d4060db05ea-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.tools.InvalidTool.html"}
{"id": "7d4060db05ea-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.tools.InvalidTool.html"}
{"id": "7d4060db05ea-6", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.tools.InvalidTool.html"}
{"id": "7d4060db05ea-7", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.tools.InvalidTool.html"}
{"id": "7d4060db05ea-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.tools.InvalidTool.html"}
{"id": "7d4060db05ea-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.tools.InvalidTool.html"}
{"id": "f9c832c9d788-0", "text": "langchain.agents.schema.AgentScratchPadChatPromptTemplate\u00b6\nclass langchain.agents.schema.AgentScratchPadChatPromptTemplate[source]\u00b6\nBases: ChatPromptTemplate\nChat prompt template for the agent scratchpad.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam input_types: Dict[str, Any] [Optional]\u00b6\nA dictionary of the types of the variables the prompt template expects.\nIf not provided, all variables are assumed to be strings.\nparam input_variables: List[str] [Required]\u00b6\nList of input variables in template messages. Used for validation.\nparam messages: List[MessageLike] [Required]\u00b6\nList of messages consisting of either message prompt templates or messages.\nparam output_parser: Optional[BaseOutputParser] = None\u00b6\nHow to parse the output of calling an LLM on this formatted prompt.\nparam partial_variables: Mapping[str, Union[str, Callable[[], str]]] [Optional]\u00b6\nparam validate_template: bool = False\u00b6\nWhether or not to try validating the template.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.schema.AgentScratchPadChatPromptTemplate.html"}
{"id": "f9c832c9d788-1", "text": "The default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nappend(message: Union[BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate, Tuple[str, str], Tuple[Type, str], str]) \u2192 None\u00b6\nAppend message to the end of the chat template.\nParameters\nmessage \u2013 representation of a message to append.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.schema.AgentScratchPadChatPromptTemplate.html"}
{"id": "f9c832c9d788-2", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.schema.AgentScratchPadChatPromptTemplate.html"}
{"id": "f9c832c9d788-3", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of prompt.\nextend(messages: Sequence[Union[BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate, Tuple[str, str], Tuple[Type, str], str]]) \u2192 None\u00b6\nExtend the chat template with a sequence of messages.\nformat(**kwargs: Any) \u2192 str\u00b6\nFormat the chat template into a string.\nParameters\n**kwargs \u2013 keyword arguments to use for filling in template variables\nin all the template messages in this chat template.\nReturns\nformatted string\nformat_messages(**kwargs: Any) \u2192 List[BaseMessage]\u00b6\nFormat the chat template into a list of finalized messages.\nParameters\n**kwargs \u2013 keyword arguments to use for filling in template variables\nin all the template messages in this chat template.\nReturns\nlist of formatted messages\nformat_prompt(**kwargs: Any) \u2192 PromptValue\u00b6\nFormat prompt. Should return a PromptValue.\n:param **kwargs: Keyword arguments to use for formatting.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.schema.AgentScratchPadChatPromptTemplate.html"}
{"id": "f9c832c9d788-4", "text": ":param **kwargs: Keyword arguments to use for formatting.\nReturns\nPromptValue.\nclassmethod from_messages(messages: Sequence[Union[BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate, Tuple[str, str], Tuple[Type, str], str]]) \u2192 ChatPromptTemplate\u00b6\nCreate a chat prompt template from a variety of message formats.\nExamples\nInstantiation from a list of message templates:\ntemplate = ChatPromptTemplate.from_messages([\n    (\"human\", \"Hello, how are you?\"),\n    (\"ai\", \"I'm doing well, thanks!\"),\n    (\"human\", \"That's good to hear.\"),\n])\nInstantiation from mixed message formats:\ntemplate = ChatPromptTemplate.from_messages([\n    SystemMessage(content=\"hello\"),\n    (\"human\", \"Hello, how are you?\"),\n])\nParameters\nmessages \u2013 sequence of message representations.\nA message can be represented using the following formats:\n(1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of\n(message type, template); e.g., (\u201chuman\u201d, \u201c{user_input}\u201d),\n(4) 2-tuple of (message class, template), (4) a string which is\nshorthand for (\u201chuman\u201d, template); e.g., \u201c{user_input}\u201d\nReturns\na chat prompt template\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_role_strings(string_messages: List[Tuple[str, str]]) \u2192 ChatPromptTemplate\u00b6\n[Deprecated]  Create a chat prompt template from a list of (role, template) tuples.\nParameters\nstring_messages \u2013 list of (role, template) tuples.\nstring_messages \u2013 list of (role, template) tuples.\nReturns\na chat prompt template[Deprecated] Create a chat prompt template from a list of (role, template) tuples.\nReturns\na chat prompt template\nNotes", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.schema.AgentScratchPadChatPromptTemplate.html"}
{"id": "f9c832c9d788-5", "text": "Returns\na chat prompt template\nNotes\nDeprecated since version 0.0.260: Use from_messages classmethod instead.\nclassmethod from_strings(string_messages: List[Tuple[Type[BaseMessagePromptTemplate], str]]) \u2192 ChatPromptTemplate\u00b6\n[Deprecated]  Create a chat prompt template from a list of (role class, template) tuples.\nParameters\nstring_messages \u2013 list of (role class, template) tuples.\nstring_messages \u2013 list of (role class, template) tuples.\nReturns\na chat prompt template[Deprecated] Create a chat prompt template from a list of (role class, template) tuples.\nReturns\na chat prompt template\nNotes\nDeprecated since version 0.0.260: Use from_messages classmethod instead.\nclassmethod from_template(template: str, **kwargs: Any) \u2192 ChatPromptTemplate\u00b6\nCreate a chat prompt template from a template string.\nCreates a chat template consisting of a single message assumed to be from\nthe human.\nParameters\ntemplate \u2013 template string\n**kwargs \u2013 keyword arguments to pass to the constructor.\nReturns\nA new instance of this class.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.schema.AgentScratchPadChatPromptTemplate.html"}
{"id": "f9c832c9d788-6", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict, config: Optional[RunnableConfig] = None) \u2192 PromptValue\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.schema.AgentScratchPadChatPromptTemplate.html"}
{"id": "f9c832c9d788-7", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npartial(**kwargs: Union[str, Callable[[], str]]) \u2192 ChatPromptTemplate\u00b6\nGet a new ChatPromptTemplate with some input variables already filled in.\nParameters\n**kwargs \u2013 keyword arguments to use for filling in template variables. Ought\nto be a subset of the input variables.\nReturns\nA new ChatPromptTemplate.\nExample\nfrom langchain.prompts import ChatPromptTemplate\ntemplate = ChatPromptTemplate.from_messages(\n    [\n        (\"system\", \"You are an AI assistant named {name}.\"),\n        (\"human\", \"Hi I'm {user}\"),\n        (\"ai\", \"Hi there, {user}, I'm {name}.\"),\n        (\"human\", \"{input}\"),\n    ]\n)\ntemplate2 = template.partial(user=\"Lucy\", name=\"R2D2\")\ntemplate2.format_messages(input=\"hello\")", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.schema.AgentScratchPadChatPromptTemplate.html"}
{"id": "f9c832c9d788-8", "text": "template2.format_messages(input=\"hello\")\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave prompt to file.\nParameters\nfile_path \u2013 path to file.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.schema.AgentScratchPadChatPromptTemplate.html"}
{"id": "f9c832c9d788-9", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.schema.AgentScratchPadChatPromptTemplate.html"}
{"id": "f9c832c9d788-10", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Any\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nReturn a list of attribute names that should be included in the\nserialized kwargs. These attributes must be accepted by the\nconstructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.schema.AgentScratchPadChatPromptTemplate.html"}
{"id": "25416d713962-0", "text": "langchain.agents.output_parsers.openai_tools.OpenAIToolAgentAction\u00b6\nclass langchain.agents.output_parsers.openai_tools.OpenAIToolAgentAction[source]\u00b6\nBases: AgentActionMessageLog\nOverride init to support instantiation by position for backward compat.\nparam log: str [Required]\u00b6\nAdditional information to log about the action.\nThis log can be used in a few ways. First, it can be used to audit\nwhat exactly the LLM predicted to lead to this (tool, tool_input).\nSecond, it can be used in future iterations to show the LLMs prior\nthoughts. This is useful when (tool, tool_input) does not contain\nfull information about the LLM prediction (for example, any thought\nbefore the tool/tool_input).\nparam message_log: Sequence[BaseMessage] [Required]\u00b6\nSimilar to log, this can be used to pass along extra\ninformation about what exact messages were predicted by the LLM\nbefore parsing out the (tool, tool_input). This is again useful\nif (tool, tool_input) cannot be used to fully recreate the LLM\nprediction, and you need that LLM prediction (for future agent iteration).\nCompared to log, this is useful when the underlying LLM is a\nChatModel (and therefore returns messages rather than a string).\nparam tool: str [Required]\u00b6\nThe name of the Tool to execute.\nparam tool_call_id: str [Required]\u00b6\nTool call that this message is responding to.\nparam tool_input: Union[str, dict] [Required]\u00b6\nThe input to pass in to the Tool.\nparam type: Literal['AgentActionMessageLog'] = 'AgentActionMessageLog'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.OpenAIToolAgentAction.html"}
{"id": "25416d713962-1", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.OpenAIToolAgentAction.html"}
{"id": "25416d713962-2", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.OpenAIToolAgentAction.html"}
{"id": "25416d713962-3", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.OpenAIToolAgentAction.html"}
{"id": "5c73b47dd8f8-0", "text": "langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser\u00b6\nclass langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser[source]\u00b6\nBases: AgentOutputParser\nParses a message into agent action/finish.\nIs meant to be used with OpenAI models, as it relies on the specific\nfunction_call parameter from OpenAI to convey what tools to use.\nIf a function_call parameter is passed, then that is used to get\nthe tool and tool input.\nIf one is not passed, then the AIMessage is assumed to be the final output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 Union[AgentAction, AgentFinish][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "5c73b47dd8f8-1", "text": "Parse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "5c73b47dd8f8-2", "text": "Subclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "5c73b47dd8f8-3", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "5c73b47dd8f8-4", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "5c73b47dd8f8-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "5c73b47dd8f8-6", "text": "The prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "5c73b47dd8f8-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "5c73b47dd8f8-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "98108f15b41f-0", "text": "langchain_experimental.agents.agent_toolkits.pandas.base.create_pandas_dataframe_agent\u00b6\nlangchain_experimental.agents.agent_toolkits.pandas.base.create_pandas_dataframe_agent(llm: BaseLanguageModel, df: Any, agent_type: AgentType = AgentType.ZERO_SHOT_REACT_DESCRIPTION, callback_manager: Optional[BaseCallbackManager] = None, prefix: Optional[str] = None, suffix: Optional[str] = None, input_variables: Optional[List[str]] = None, verbose: bool = False, return_intermediate_steps: bool = False, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = 'force', agent_executor_kwargs: Optional[Dict[str, Any]] = None, include_df_in_prompt: Optional[bool] = True, number_of_head_rows: int = 5, extra_tools: Sequence[BaseTool] = (), **kwargs: Dict[str, Any]) \u2192 AgentExecutor[source]\u00b6\nConstruct a pandas agent from an LLM and dataframe.\nExamples using create_pandas_dataframe_agent\u00b6\nAirbyte Question Answering\nPandas Dataframe\n!pip install bs4", "source": "lang/api.python.langchain.com/en/latest/agents/langchain_experimental.agents.agent_toolkits.pandas.base.create_pandas_dataframe_agent.html"}
{"id": "41b5912b71cd-0", "text": "langchain.agents.structured_chat.base.StructuredChatAgent\u00b6\nclass langchain.agents.structured_chat.base.StructuredChatAgent[source]\u00b6\nBases: Agent\nStructured Chat Agent.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_tools: Optional[List[str]] = None\u00b6\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam output_parser: langchain.agents.agent.AgentOutputParser [Optional]\u00b6\nOutput parser for the agent.\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.base.StructuredChatAgent.html"}
{"id": "41b5912b71cd-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.base.StructuredChatAgent.html"}
{"id": "41b5912b71cd-2", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nclassmethod create_prompt(tools: Sequence[BaseTool], prefix: str = 'Respond to the human as helpfully and accurately as possible. You have access to the following tools:', suffix: str = '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: str = '{input}\\n\\n{agent_scratchpad}', format_instructions: str = '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\u00a0 \"action\": $TOOL_NAME,\\n\u00a0 \"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\u00a0 \"action\": \"Final Answer\",\\n\u00a0 \"action_input\": \"Final response to human\"\\n}}}}\\n```', input_variables: Optional[List[str]] = None, memory_prompts: Optional[List[BasePromptTemplate]] = None) \u2192 BasePromptTemplate[source]\u00b6\nCreate a prompt for this class.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.base.StructuredChatAgent.html"}
{"id": "41b5912b71cd-3", "text": "dict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.\nclassmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, prefix: str = 'Respond to the human as helpfully and accurately as possible. You have access to the following tools:', suffix: str = '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: str = '{input}\\n\\n{agent_scratchpad}', format_instructions: str = '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\u00a0 \"action\": $TOOL_NAME,\\n\u00a0 \"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\u00a0 \"action\": \"Final Answer\",\\n\u00a0 \"action_input\": \"Final response to human\"\\n}}}}\\n```', input_variables: Optional[List[str]] = None, memory_prompts: Optional[List[BasePromptTemplate]] = None, **kwargs: Any) \u2192 Agent[source]\u00b6\nConstruct an agent from an LLM and tools.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.base.StructuredChatAgent.html"}
{"id": "41b5912b71cd-4", "text": "Construct an agent from an LLM and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]]\u00b6\nget_full_inputs(intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nCreate the full inputs for the LLMChain from intermediate steps.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.base.StructuredChatAgent.html"}
{"id": "41b5912b71cd-5", "text": "Parameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty llm_prefix: str\u00b6\nPrefix to append the llm call with.\nproperty observation_prefix: str\u00b6\nPrefix to append the observation with.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.base.StructuredChatAgent.html"}
{"id": "9125645cd7ff-0", "text": "langchain.agents.agent_toolkits.powerbi.chat_base.create_pbi_chat_agent\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.chat_base.create_pbi_chat_agent.html"}
{"id": "9125645cd7ff-1", "text": "langchain.agents.agent_toolkits.powerbi.chat_base.create_pbi_chat_agent(llm: BaseChatModel, toolkit: Optional[PowerBIToolkit] = None, powerbi: Optional[PowerBIDataset] = None, callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, prefix: str = 'Assistant is a large language model built to help users interact with a PowerBI Dataset.\\n\\nAssistant should try to create a correct and complete answer to the question from the user. If the user asks a question not related to the dataset it should return \"This does not appear to be part of this dataset.\" as the answer. The user might make a mistake with the spelling of certain values, if you think that is the case, ask the user to confirm the spelling of the value and then run the query again. Unless the user specifies a specific number of examples they wish to obtain, and the results are too large, limit your query to at most {top_k} results, but make it clear when answering which field was used for the filtering. The user has access to these tables: {{tables}}.\\n\\nThe 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. \\n', suffix: str = \"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\",", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.chat_base.create_pbi_chat_agent.html"}
{"id": "9125645cd7ff-2", "text": "blob with a single action, and NOTHING else):\\n\\n{{{{input}}}}\\n\", examples: Optional[str] = None, input_variables: Optional[List[str]] = None, memory: Optional[BaseChatMemory] = None, top_k: int = 10, verbose: bool = False, agent_executor_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 AgentExecutor[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.chat_base.create_pbi_chat_agent.html"}
{"id": "9125645cd7ff-3", "text": "Construct a Power BI agent from a Chat LLM and tools.\nIf you supply only a toolkit and no Power BI dataset, the same LLM is used for both.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.chat_base.create_pbi_chat_agent.html"}
{"id": "429fba8e9b66-0", "text": "langchain.agents.format_scratchpad.openai_functions.format_to_openai_functions\u00b6\nlangchain.agents.format_scratchpad.openai_functions.format_to_openai_functions(intermediate_steps: Sequence[Tuple[AgentAction, str]]) \u2192 List[BaseMessage]\u00b6\nConvert (AgentAction, tool output) tuples into FunctionMessages.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date, along with observations\nReturns\nlist of messages to send to the LLM for the next prediction", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.format_scratchpad.openai_functions.format_to_openai_functions.html"}
{"id": "05fc35184a5f-0", "text": "langchain.agents.react.base.DocstoreExplorer\u00b6\nclass langchain.agents.react.base.DocstoreExplorer(docstore: Docstore)[source]\u00b6\nClass to assist with exploration of a document store.\nInitialize with a docstore, and set initial document to None.\nMethods\n__init__(docstore)\nInitialize with a docstore, and set initial document to None.\nlookup(term)\nLookup a term in document (if saved).\nsearch(term)\nSearch for a term in the docstore, and if found save.\n__init__(docstore: Docstore)[source]\u00b6\nInitialize with a docstore, and set initial document to None.\nlookup(term: str) \u2192 str[source]\u00b6\nLookup a term in document (if saved).\nsearch(term: str) \u2192 str[source]\u00b6\nSearch for a term in the docstore, and if found save.\nExamples using DocstoreExplorer\u00b6\nReAct document store", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.DocstoreExplorer.html"}
{"id": "71424031e398-0", "text": "langchain.agents.chat.base.ChatAgent\u00b6\nclass langchain.agents.chat.base.ChatAgent[source]\u00b6\nBases: Agent\nChat Agent.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_tools: Optional[List[str]] = None\u00b6\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam output_parser: langchain.agents.agent.AgentOutputParser [Optional]\u00b6\nOutput parser for the agent.\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.base.ChatAgent.html"}
{"id": "71424031e398-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.base.ChatAgent.html"}
{"id": "71424031e398-2", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nclassmethod create_prompt(tools: Sequence[BaseTool], system_message_prefix: str = 'Answer the following questions as best you can. You have access to the following tools:', system_message_suffix: str = 'Begin! Reminder to always use the exact characters `Final Answer` when responding.', human_message: str = '{input}\\n\\n{agent_scratchpad}', format_instructions: str = 'The way you use the tools is by specifying a json blob.\\nSpecifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).\\n\\nThe only values that should be in the \"action\" field are: {tool_names}\\n\\nThe $JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. Here is an example of a valid $JSON_BLOB:\\n\\n```\\n{{{{\\n\u00a0 \"action\": $TOOL_NAME,\\n\u00a0 \"action_input\": $INPUT\\n}}}}\\n```\\n\\nALWAYS use the following format:\\n\\nQuestion: the input question you must answer\\nThought: you should always think about what to do\\nAction:\\n```\\n$JSON_BLOB\\n```\\nObservation: the result of the action\\n... (this Thought/Action/Observation can repeat N times)\\nThought: I now know the final answer\\nFinal Answer: the final answer to the original input question', input_variables: Optional[List[str]] = None) \u2192 BasePromptTemplate[source]\u00b6\nCreate a prompt for this class.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.base.ChatAgent.html"}
{"id": "71424031e398-3", "text": "dict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.\nclassmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, system_message_prefix: str = 'Answer the following questions as best you can. You have access to the following tools:', system_message_suffix: str = 'Begin! Reminder to always use the exact characters `Final Answer` when responding.', human_message: str = '{input}\\n\\n{agent_scratchpad}', format_instructions: str = 'The way you use the tools is by specifying a json blob.\\nSpecifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).\\n\\nThe only values that should be in the \"action\" field are: {tool_names}\\n\\nThe $JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. Here is an example of a valid $JSON_BLOB:\\n\\n```\\n{{{{\\n\u00a0 \"action\": $TOOL_NAME,\\n\u00a0 \"action_input\": $INPUT\\n}}}}\\n```\\n\\nALWAYS use the following format:\\n\\nQuestion: the input question you must answer\\nThought: you should always think about what to do\\nAction:\\n```\\n$JSON_BLOB\\n```\\nObservation: the result of the action\\n... (this Thought/Action/Observation can repeat N times)\\nThought: I now know the final answer\\nFinal Answer: the final answer to the original input question', input_variables: Optional[List[str]] = None, **kwargs: Any) \u2192 Agent[source]\u00b6\nConstruct an agent from an LLM and tools.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.base.ChatAgent.html"}
{"id": "71424031e398-4", "text": "Construct an agent from an LLM and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]]\u00b6\nget_full_inputs(intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nCreate the full inputs for the LLMChain from intermediate steps.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.base.ChatAgent.html"}
{"id": "71424031e398-5", "text": "Parameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty llm_prefix: str\u00b6\nPrefix to append the llm call with.\nproperty observation_prefix: str\u00b6\nPrefix to append the observation with.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.chat.base.ChatAgent.html"}
{"id": "fb4758a96bfb-0", "text": "langchain.agents.output_parsers.json.JSONAgentOutputParser\u00b6\nclass langchain.agents.output_parsers.json.JSONAgentOutputParser[source]\u00b6\nBases: AgentOutputParser\nParses tool invocations and final answers in JSON format.\nExpects output to be in one of two formats.\nIf the output signals that an action should be taken,\nshould be in the below format. This will result in an AgentAction\nbeing returned.\n```\n{\n\u201caction\u201d: \u201csearch\u201d,\n\u201caction_input\u201d: \u201c2+2\u201d\nIf the output signals that a final answer should be given,\nshould be in the below format. This will result in an AgentFinish\nbeing returned.\n```\n{\n\u201caction\u201d: \u201cFinal Answer\u201d,\n\u201caction_input\u201d: \u201c4\u201d\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "fb4758a96bfb-1", "text": "Parameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "fb4758a96bfb-2", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "fb4758a96bfb-3", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "fb4758a96bfb-4", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "fb4758a96bfb-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "fb4758a96bfb-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "fb4758a96bfb-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "fb4758a96bfb-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "fb4758a96bfb-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "4b5c4b7b4e01-0", "text": "langchain.agents.conversational_chat.base.ConversationalChatAgent\u00b6\nclass langchain.agents.conversational_chat.base.ConversationalChatAgent[source]\u00b6\nBases: Agent\nAn agent designed to hold a conversation in addition to using tools.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_tools: Optional[List[str]] = None\u00b6\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam output_parser: langchain.agents.agent.AgentOutputParser [Optional]\u00b6\nparam 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.\"\u00b6\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.base.ConversationalChatAgent.html"}
{"id": "4b5c4b7b4e01-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.base.ConversationalChatAgent.html"}
{"id": "4b5c4b7b4e01-2", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nclassmethod create_prompt(tools: Sequence[BaseTool], system_message: str = '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: str = \"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: Optional[List[str]] = None, output_parser: Optional[BaseOutputParser] = None) \u2192 BasePromptTemplate[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.base.ConversationalChatAgent.html"}
{"id": "4b5c4b7b4e01-3", "text": "Create a prompt for this class.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.base.ConversationalChatAgent.html"}
{"id": "4b5c4b7b4e01-4", "text": "classmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, system_message: str = '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: str = \"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: Optional[List[str]] = None, **kwargs: Any) \u2192 Agent[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.base.ConversationalChatAgent.html"}
{"id": "4b5c4b7b4e01-5", "text": "Construct an agent from an LLM and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]]\u00b6\nget_full_inputs(intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nCreate the full inputs for the LLMChain from intermediate steps.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.base.ConversationalChatAgent.html"}
{"id": "4b5c4b7b4e01-6", "text": "Parameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty llm_prefix: str\u00b6\nPrefix to append the llm call with.\nproperty observation_prefix: str\u00b6\nPrefix to append the observation with.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.base.ConversationalChatAgent.html"}
{"id": "d50359699a96-0", "text": "langchain.agents.agent_toolkits.file_management.toolkit.FileManagementToolkit\u00b6\nclass langchain.agents.agent_toolkits.file_management.toolkit.FileManagementToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for interacting with local files.\nSecurity Notice: This toolkit provides methods to interact with local files.If providing this toolkit to an agent on an LLM, ensure you scope\nthe agent\u2019s permissions to only include the necessary permissions\nto perform the desired operations.\nBy default the agent will have access to all files within\nthe root dir and will be able to Copy, Delete, Move, Read, Write\nand List files in that directory.\nConsider the following:\n- Limit access to particular directories using root_dir.\n- Use filesystem permissions to restrict access and permissions to only\nthe files and directories required by the agent.\nLimit the tools available to the agent to only the file operations\nnecessary for the agent\u2019s intended use.\nSandbox the agent by running it in a container.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam root_dir: Optional[str] = None\u00b6\nIf specified, all file operations are made relative to root_dir.\nparam selected_tools: Optional[List[str]] = None\u00b6\nIf provided, only provide the selected tools. Defaults to all.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.file_management.toolkit.FileManagementToolkit.html"}
{"id": "d50359699a96-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.file_management.toolkit.FileManagementToolkit.html"}
{"id": "d50359699a96-2", "text": "Get the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using FileManagementToolkit\u00b6\nFile System", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.file_management.toolkit.FileManagementToolkit.html"}
{"id": "2c439e6382c7-0", "text": "langchain.agents.agent_toolkits.sql.base.create_sql_agent\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.sql.base.create_sql_agent.html"}
{"id": "2c439e6382c7-1", "text": "langchain.agents.agent_toolkits.sql.base.create_sql_agent(llm: BaseLanguageModel, toolkit: SQLDatabaseToolkit, agent_type: AgentType = AgentType.ZERO_SHOT_REACT_DESCRIPTION, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = '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: Optional[str] = None, format_instructions: str = '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", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.sql.base.create_sql_agent.html"}
{"id": "2c439e6382c7-2", "text": "I now know the final answer\\nFinal Answer: the final answer to the original input question', input_variables: Optional[List[str]] = None, top_k: int = 10, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = 'force', verbose: bool = False, agent_executor_kwargs: Optional[Dict[str, Any]] = None, extra_tools: Sequence[BaseTool] = (), **kwargs: Any) \u2192 AgentExecutor[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.sql.base.create_sql_agent.html"}
{"id": "2c439e6382c7-3", "text": "Construct an SQL agent from an LLM and tools.\nExamples using create_sql_agent\u00b6\nCnosDB\nSQL Database\nSet env var OPENAI_API_KEY or load from a .env file\nSQL", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.sql.base.create_sql_agent.html"}
{"id": "6152835b7806-0", "text": "langchain.agents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing\u00b6\nclass langchain.agents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing[source]\u00b6\nBases: BaseRequestsTool, BaseTool\nRequests POST tool with LLM-instructed extraction of truncated responses.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this when you want to POST to a website.\\nInput to the tool should be a json string with 3 keys: \"url\", \"data\", and \"output_instructions\".\\nThe value of \"url\" should be a string.\\nThe value of \"data\" should be a dictionary of key-value pairs you want to POST to the url.\\nThe value of \"output_instructions\" should be instructions on what information to extract from the response, for example the id(s) for a resource(s) that the POST request creates.\\nAlways use double quotes for strings in the json string.'\u00b6\nTool description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam llm_chain: langchain.chains.llm.LLMChain [Optional]\u00b6\nLLMChain used to extract the response.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing.html"}
{"id": "6152835b7806-1", "text": "This metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'requests_post'\u00b6\nTool name.\nparam requests_wrapper: TextRequestsWrapper [Required]\u00b6\nparam response_length: Optional[int] = 5000\u00b6\nMaximum length of the response to be returned.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing.html"}
{"id": "6152835b7806-2", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing.html"}
{"id": "6152835b7806-3", "text": "step, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing.html"}
{"id": "6152835b7806-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing.html"}
{"id": "6152835b7806-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing.html"}
{"id": "6152835b7806-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing.html"}
{"id": "6152835b7806-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing.html"}
{"id": "6152835b7806-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing.html"}
{"id": "6152835b7806-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing.html"}
{"id": "72b951db583a-0", "text": "langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser\u00b6\nclass langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser[source]\u00b6\nBases: AgentOutputParser\nParses ReAct-style LLM calls that have a single tool input.\nExpects output to be in one of two formats.\nIf the output signals that an action should be taken,\nshould be in the below format. This will result in an AgentAction\nbeing returned.\n`\nThought: agent thought here\nAction: search\nAction Input: what is the temperature in SF?\n`\nIf the output signals that a final answer should be given,\nshould be in the below format. This will result in an AgentFinish\nbeing returned.\n`\nThought: agent thought here\nFinal Answer: The temperature is 100 degrees\n`\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "72b951db583a-1", "text": "Parse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "72b951db583a-2", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "72b951db583a-3", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "72b951db583a-4", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "72b951db583a-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "72b951db583a-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "72b951db583a-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "72b951db583a-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "72b951db583a-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "ce492565c70e-0", "text": "langchain.agents.openai_functions_agent.agent_token_buffer_memory.AgentTokenBufferMemory\u00b6\nclass langchain.agents.openai_functions_agent.agent_token_buffer_memory.AgentTokenBufferMemory[source]\u00b6\nBases: BaseChatMemory\nMemory used to save agent output AND intermediate steps.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_prefix: str = 'AI'\u00b6\nparam chat_memory: BaseChatMessageHistory [Optional]\u00b6\nparam human_prefix: str = 'Human'\u00b6\nparam input_key: Optional[str] = None\u00b6\nparam intermediate_steps_key: str = 'intermediate_steps'\u00b6\nparam llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nparam max_token_limit: int = 12000\u00b6\nThe max number of tokens to keep in the buffer.\nOnce the buffer exceeds this many tokens, the oldest messages will be pruned.\nparam memory_key: str = 'history'\u00b6\nparam output_key: str = 'output'\u00b6\nparam return_messages: bool = True\u00b6\nclear() \u2192 None\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_functions_agent.agent_token_buffer_memory.AgentTokenBufferMemory.html"}
{"id": "ce492565c70e-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_functions_agent.agent_token_buffer_memory.AgentTokenBufferMemory.html"}
{"id": "ce492565c70e-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nReturn history buffer.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, Any]) \u2192 None[source]\u00b6\nSave context from this conversation to buffer. Pruned.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty buffer: List[langchain.schema.messages.BaseMessage]\u00b6\nString buffer of memory.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_functions_agent.agent_token_buffer_memory.AgentTokenBufferMemory.html"}
{"id": "ce492565c70e-3", "text": "String buffer of memory.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using AgentTokenBufferMemory\u00b6\nConversational Retrieval Agent", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_functions_agent.agent_token_buffer_memory.AgentTokenBufferMemory.html"}
{"id": "f3c00d8c64ef-0", "text": "langchain.agents.agent.Agent\u00b6\nclass langchain.agents.agent.Agent[source]\u00b6\nBases: BaseSingleActionAgent\nAgent that calls the language model and deciding the action.\nThis is driven by an LLMChain. The prompt in the LLMChain MUST include\na variable called \u201cagent_scratchpad\u201d where the agent can put its\nintermediary work.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_tools: Optional[List[str]] = None\u00b6\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam output_parser: langchain.agents.agent.AgentOutputParser [Required]\u00b6\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.Agent.html"}
{"id": "f3c00d8c64ef-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nabstract classmethod create_prompt(tools: Sequence[BaseTool]) \u2192 BasePromptTemplate[source]\u00b6\nCreate a prompt for this class.\ndict(**kwargs: Any) \u2192 Dict[source]\u00b6\nReturn dictionary representation of agent.\nclassmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, **kwargs: Any) \u2192 Agent[source]\u00b6\nConstruct an agent from an LLM and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]][source]\u00b6\nget_full_inputs(intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 Dict[str, Any][source]\u00b6\nCreate the full inputs for the LLMChain from intermediate steps.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.Agent.html"}
{"id": "f3c00d8c64ef-2", "text": "Create the full inputs for the LLMChain from intermediate steps.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.Agent.html"}
{"id": "f3c00d8c64ef-3", "text": "Return response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict[source]\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nabstract property llm_prefix: str\u00b6\nPrefix to append the LLM call with.\nabstract property observation_prefix: str\u00b6\nPrefix to append the observation with.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.Agent.html"}
{"id": "b676a5253695-0", "text": "langchain.agents.output_parsers.openai_tools.parse_ai_message_to_openai_tool_action\u00b6\nlangchain.agents.output_parsers.openai_tools.parse_ai_message_to_openai_tool_action(message: BaseMessage) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6\nParse an AI message potentially containing tool_calls.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.parse_ai_message_to_openai_tool_action.html"}
{"id": "62caf9787059-0", "text": "langchain.agents.agent_toolkits.vectorstore.base.create_vectorstore_agent\u00b6\nlangchain.agents.agent_toolkits.vectorstore.base.create_vectorstore_agent(llm: BaseLanguageModel, toolkit: VectorStoreToolkit, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = 'You are an agent designed to answer questions about sets of documents.\\nYou have access to tools for interacting with the documents, and the inputs to the tools are questions.\\nSometimes, you will be asked to provide sources for your questions, in which case you should use the appropriate tool to do so.\\nIf the question does not seem relevant to any of the tools provided, just return \"I don\\'t know\" as the answer.\\n', verbose: bool = False, agent_executor_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 AgentExecutor[source]\u00b6\nConstruct a VectorStore agent from an LLM and tools.\nParameters\nllm (BaseLanguageModel) \u2013 LLM that will be used by the agent\ntoolkit (VectorStoreToolkit) \u2013 Set of tools for the agent\ncallback_manager (Optional[BaseCallbackManager], optional) \u2013 Object to handle the callback [ Defaults to None. ]\nprefix (str, optional) \u2013 The prefix prompt for the agent. If not provided uses default PREFIX.\nverbose (bool, optional) \u2013 If you want to see the content of the scratchpad. [ Defaults to False ]\nagent_executor_kwargs (Optional[Dict[str, Any]], optional) \u2013 If there is any other parameter you want to send to the agent. [ Defaults to None ]\n**kwargs \u2013 Additional named parameters to pass to the ZeroShotAgent.\nReturns\nReturns a callable AgentExecutor object. Either you can call it or use run method with the query to get the response\nReturn type\nAgentExecutor\nExamples using create_vectorstore_agent\u00b6\nVectorstore", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.vectorstore.base.create_vectorstore_agent.html"}
{"id": "c0ee7d3c99da-0", "text": "langchain.agents.agent_toolkits.openapi.spec.ReducedOpenAPISpec\u00b6\nclass langchain.agents.agent_toolkits.openapi.spec.ReducedOpenAPISpec(servers: List[dict], description: str, endpoints: List[Tuple[str, str, dict]])[source]\u00b6\nA reduced OpenAPI spec.\nThis is a quick and dirty representation for OpenAPI specs.\nservers\u00b6\nThe servers in the spec.\nType\nList[dict]\ndescription\u00b6\nThe description of the spec.\nType\nstr\nendpoints\u00b6\nThe endpoints in the spec.\nType\nList[Tuple[str, str, dict]]\nAttributes\nservers\ndescription\nendpoints\nMethods\n__init__(servers,\u00a0description,\u00a0endpoints)\n__init__(servers: List[dict], description: str, endpoints: List[Tuple[str, str, dict]]) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.spec.ReducedOpenAPISpec.html"}
{"id": "05506ec89cff-0", "text": "langchain.agents.agent_iterator.BaseAgentExecutorIterator\u00b6\nclass langchain.agents.agent_iterator.BaseAgentExecutorIterator[source]\u00b6\nBase class for AgentExecutorIterator.\nMethods\n__init__()\nbuild_callback_manager()\n__init__()\u00b6\nabstract build_callback_manager() \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_iterator.BaseAgentExecutorIterator.html"}
{"id": "e50f89d35e9b-0", "text": "langchain.agents.structured_chat.output_parser.StructuredChatOutputParser\u00b6\nclass langchain.agents.structured_chat.output_parser.StructuredChatOutputParser[source]\u00b6\nBases: AgentOutputParser\nOutput parser for the structured chat agent.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html"}
{"id": "e50f89d35e9b-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html"}
{"id": "e50f89d35e9b-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html"}
{"id": "e50f89d35e9b-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html"}
{"id": "e50f89d35e9b-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html"}
{"id": "e50f89d35e9b-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html"}
{"id": "e50f89d35e9b-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html"}
{"id": "e50f89d35e9b-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html"}
{"id": "e50f89d35e9b-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html"}
{"id": "8f6c279da907-0", "text": "langchain.agents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing\u00b6\nclass langchain.agents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing[source]\u00b6\nBases: BaseRequestsTool, BaseTool\nA tool that sends a DELETE request and parses the response.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'ONLY USE THIS TOOL WHEN THE USER HAS SPECIFICALLY REQUESTED TO DELETE CONTENT FROM A WEBSITE.\\nInput to the tool should be a json string with 2 keys: \"url\", and \"output_instructions\".\\nThe value of \"url\" should be a string.\\nThe value of \"output_instructions\" should be instructions on what information to extract from the response, for example the id(s) for a resource(s) that the DELETE request creates.\\nAlways use double quotes for strings in the json string.\\nONLY USE THIS TOOL IF THE USER HAS SPECIFICALLY REQUESTED TO DELETE SOMETHING.'\u00b6\nThe description of the tool.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam llm_chain: langchain.chains.llm.LLMChain [Optional]\u00b6\nThe LLM chain used to parse the response.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing.html"}
{"id": "8f6c279da907-1", "text": "Optional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'requests_delete'\u00b6\nThe name of the tool.\nparam requests_wrapper: TextRequestsWrapper [Required]\u00b6\nparam response_length: Optional[int] = 5000\u00b6\nThe maximum length of the response.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing.html"}
{"id": "8f6c279da907-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing.html"}
{"id": "8f6c279da907-3", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing.html"}
{"id": "8f6c279da907-4", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing.html"}
{"id": "8f6c279da907-5", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing.html"}
{"id": "8f6c279da907-6", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing.html"}
{"id": "8f6c279da907-7", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing.html"}
{"id": "8f6c279da907-8", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing.html"}
{"id": "8f6c279da907-9", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing.html"}
{"id": "f9b170047e9a-0", "text": "langchain_experimental.agents.agent_toolkits.spark.base.create_spark_dataframe_agent\u00b6\nlangchain_experimental.agents.agent_toolkits.spark.base.create_spark_dataframe_agent(llm: BaseLLM, df: Any, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = '\\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: str = '\\nThis is the result of `print(df.first())`:\\n{df}\\n\\nBegin!\\nQuestion: {input}\\n{agent_scratchpad}', input_variables: Optional[List[str]] = None, verbose: bool = False, return_intermediate_steps: bool = False, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = 'force', agent_executor_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 AgentExecutor[source]\u00b6\nConstruct a Spark agent from an LLM and dataframe.\nExamples using create_spark_dataframe_agent\u00b6\nSpark Dataframe", "source": "lang/api.python.langchain.com/en/latest/agents/langchain_experimental.agents.agent_toolkits.spark.base.create_spark_dataframe_agent.html"}
{"id": "f4a347633c4f-0", "text": "langchain.agents.format_scratchpad.openai_tools.format_to_openai_tool_messages\u00b6\nlangchain.agents.format_scratchpad.openai_tools.format_to_openai_tool_messages(intermediate_steps: Sequence[Tuple[AgentAction, str]]) \u2192 List[BaseMessage][source]\u00b6\nConvert (AgentAction, tool output) tuples into FunctionMessages.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date, along with observations\nReturns\nlist of messages to send to the LLM for the next prediction", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.format_scratchpad.openai_tools.format_to_openai_tool_messages.html"}
{"id": "5d7c33d7bcea-0", "text": "langchain.agents.format_scratchpad.log.format_log_to_str\u00b6\nlangchain.agents.format_scratchpad.log.format_log_to_str(intermediate_steps: List[Tuple[AgentAction, str]], observation_prefix: str = 'Observation: ', llm_prefix: str = 'Thought: ') \u2192 str[source]\u00b6\nConstruct the scratchpad that lets the agent continue its thought process.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.format_scratchpad.log.format_log_to_str.html"}
{"id": "ee8d36484005-0", "text": "langchain.agents.output_parsers.xml.XMLAgentOutputParser\u00b6\nclass langchain.agents.output_parsers.xml.XMLAgentOutputParser[source]\u00b6\nBases: AgentOutputParser\nParses tool invocations and final answers in XML format.\nExpects output to be in one of two formats.\nIf the output signals that an action should be taken,\nshould be in the below format. This will result in an AgentAction\nbeing returned.\n`\n<tool>search</tool>\n<tool_input>what is 2 + 2</tool_input>\n`\nIf the output signals that a final answer should be given,\nshould be in the below format. This will result in an AgentFinish\nbeing returned.\n`\n<final_answer>Foo</final_answer>\n`\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "ee8d36484005-1", "text": "Parameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "ee8d36484005-2", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "ee8d36484005-3", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "ee8d36484005-4", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "ee8d36484005-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "ee8d36484005-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "ee8d36484005-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "ee8d36484005-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "ee8d36484005-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "1e9d6cde113a-0", "text": "langchain.agents.initialize.initialize_agent\u00b6\nlangchain.agents.initialize.initialize_agent(tools: Sequence[BaseTool], llm: BaseLanguageModel, agent: Optional[AgentType] = None, callback_manager: Optional[BaseCallbackManager] = None, agent_path: Optional[str] = None, agent_kwargs: Optional[dict] = None, *, tags: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 AgentExecutor[source]\u00b6\nLoad an agent executor given tools and LLM.\nParameters\ntools \u2013 List of tools this agent has access to.\nllm \u2013 Language model to use as the agent.\nagent \u2013 Agent type to use. If None and agent_path is also None, will default to\nAgentType.ZERO_SHOT_REACT_DESCRIPTION.\ncallback_manager \u2013 CallbackManager to use. Global callback manager is used if\nnot provided. Defaults to None.\nagent_path \u2013 Path to serialized agent to use.\nagent_kwargs \u2013 Additional keyword arguments to pass to the underlying agent\ntags \u2013 Tags to apply to the traced runs.\n**kwargs \u2013 Additional keyword arguments passed to the agent executor\nReturns\nAn agent executor\nExamples using initialize_agent\u00b6\nChatGPT Plugins\nGoogle Serper\nHuman as a tool\nYahoo Finance News\nAWS Lambda\nGoogle Drive\nOpenWeatherMap\nSearch Tools\nEleven Labs Text2Speech\nZapier Natural Language Actions\nArXiv\nMetaphor Search\nGraphQL\nGradio\nSceneXplain\nEden AI\nDall-E Image Generator\nShell (bash)\nZep Memory\nXata chat memory\nDynamodb Chat Message History\nLLMonitor\nArgilla\nStreamlit\nComet\nAim\nWeights & Biases\nSageMaker Tracking\nMLflow\nFlyte\nWandB Tracing\nClearML\nLog, Trace, and Monitor\nPortkey\nJira\nDocument Comparison\nAzure Cognitive Services\nNatural Language APIs", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.initialize.initialize_agent.html"}
{"id": "1e9d6cde113a-1", "text": "Portkey\nJira\nDocument Comparison\nAzure Cognitive Services\nNatural Language APIs\nGmail\nGithub\nGoogle Drive tool\nAINetwork\nPlayWright Browser\nOffice365\nMultiOn\nAmadeus\nGitlab\nBittensor\nAmazon API Gateway\nDebugging\nLangSmith Walkthrough\nHugging Face Prompt Injection Identification\nComparing Chain Outputs\nAgent Trajectory\nAgents\nMulti-modal outputs: Image & Text\nAgent Debates with Tools\nMultiple callback handlers\nMulti-Input Tools\nDefining Custom Tools\nTool Input Schema\nHuman-in-the-loop Tool Validation\nSelf-ask with search\nReAct document store\nOpenAI Multi Functions Agent\nCombine agents and vector stores\nAccess intermediate steps\nHandle parsing errors\nRunning Agent as an Iterator\nTimeouts for agents\nStreaming final agent output\nAdd Memory to OpenAI Functions Agent\nCap the max number of iterations\nCustom functions with OpenAI Functions Agent\nAsync API\nUse ToolKits with OpenAI Functions\nHuman input chat model\nFake LLM\nTracking token usage\nHuman input LLM", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.initialize.initialize_agent.html"}
{"id": "d399bb456028-0", "text": "langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreInfo\u00b6\nclass langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreInfo[source]\u00b6\nBases: BaseModel\nInformation about a VectorStore.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam description: str [Required]\u00b6\nparam name: str [Required]\u00b6\nparam vectorstore: langchain.schema.vectorstore.VectorStore [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreInfo.html"}
{"id": "d399bb456028-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreInfo.html"}
{"id": "d399bb456028-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using VectorStoreInfo\u00b6\nVectorstore", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreInfo.html"}
{"id": "cf9445b86b16-0", "text": "langchain.agents.react.base.ReActDocstoreAgent\u00b6\nclass langchain.agents.react.base.ReActDocstoreAgent[source]\u00b6\nBases: Agent\nAgent for the ReAct chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_tools: Optional[List[str]] = None\u00b6\nparam llm_chain: LLMChain [Required]\u00b6\nparam output_parser: langchain.agents.agent.AgentOutputParser [Optional]\u00b6\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActDocstoreAgent.html"}
{"id": "cf9445b86b16-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nclassmethod create_prompt(tools: Sequence[BaseTool]) \u2192 BasePromptTemplate[source]\u00b6\nReturn default prompt.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.\nclassmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, **kwargs: Any) \u2192 Agent\u00b6\nConstruct an agent from an LLM and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]]\u00b6\nget_full_inputs(intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nCreate the full inputs for the LLMChain from intermediate steps.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActDocstoreAgent.html"}
{"id": "cf9445b86b16-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActDocstoreAgent.html"}
{"id": "cf9445b86b16-3", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty llm_prefix: str\u00b6\nPrefix to append the LLM call with.\nproperty observation_prefix: str\u00b6\nPrefix to append the observation with.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActDocstoreAgent.html"}
{"id": "dc07c7c9bf41-0", "text": "langchain.agents.agent_toolkits.azure_cognitive_services.AzureCognitiveServicesToolkit\u00b6\nclass langchain.agents.agent_toolkits.azure_cognitive_services.AzureCognitiveServicesToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for Azure Cognitive Services.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.azure_cognitive_services.AzureCognitiveServicesToolkit.html"}
{"id": "dc07c7c9bf41-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.azure_cognitive_services.AzureCognitiveServicesToolkit.html"}
{"id": "dc07c7c9bf41-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using AzureCognitiveServicesToolkit\u00b6\nAzure Cognitive Services", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.azure_cognitive_services.AzureCognitiveServicesToolkit.html"}
{"id": "8fc199b78496-0", "text": "langchain.agents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing\u00b6\nclass langchain.agents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing[source]\u00b6\nBases: BaseRequestsTool, BaseTool\nRequests PUT tool with LLM-instructed extraction of truncated responses.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this when you want to PUT to a website.\\nInput to the tool should be a json string with 3 keys: \"url\", \"data\", and \"output_instructions\".\\nThe value of \"url\" should be a string.\\nThe value of \"data\" should be a dictionary of key-value pairs you want to PUT to the url.\\nThe value of \"output_instructions\" should be instructions on what information to extract from the response, for example the id(s) for a resource(s) that the PUT request creates.\\nAlways use double quotes for strings in the json string.'\u00b6\nTool description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam llm_chain: langchain.chains.llm.LLMChain [Optional]\u00b6\nLLMChain used to extract the response.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing.html"}
{"id": "8fc199b78496-1", "text": "This metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'requests_put'\u00b6\nTool name.\nparam requests_wrapper: TextRequestsWrapper [Required]\u00b6\nparam response_length: Optional[int] = 5000\u00b6\nMaximum length of the response to be returned.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing.html"}
{"id": "8fc199b78496-2", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing.html"}
{"id": "8fc199b78496-3", "text": "step, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing.html"}
{"id": "8fc199b78496-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing.html"}
{"id": "8fc199b78496-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing.html"}
{"id": "8fc199b78496-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing.html"}
{"id": "8fc199b78496-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing.html"}
{"id": "8fc199b78496-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing.html"}
{"id": "8fc199b78496-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing.html"}
{"id": "0cbae21cd5ac-0", "text": "langchain.agents.agent_toolkits.openapi.base.create_openapi_agent\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.base.create_openapi_agent.html"}
{"id": "0cbae21cd5ac-1", "text": "langchain.agents.agent_toolkits.openapi.base.create_openapi_agent(llm: BaseLanguageModel, toolkit: OpenAPIToolkit, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = \"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: str = 'Begin!\\n\\nQuestion: {input}\\nThought: I should explore the spec to find the base url for the API.\\n{agent_scratchpad}', format_instructions: str = '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", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.base.create_openapi_agent.html"}
{"id": "0cbae21cd5ac-2", "text": "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: Optional[List[str]] = None, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = 'force', verbose: bool = False, return_intermediate_steps: bool = False, agent_executor_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 AgentExecutor[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.base.create_openapi_agent.html"}
{"id": "0cbae21cd5ac-3", "text": "Construct an OpenAPI agent from an LLM and tools.\nSecurity Note: When creating an OpenAPI agent, check the permissionsand capabilities of the underlying toolkit.\nFor example, if the default implementation of OpenAPIToolkit\nuses the RequestsToolkit which contains tools to make arbitrary\nnetwork requests against any URL (e.g., GET, POST, PATCH, PUT, DELETE),\nControl access to who can submit issue requests using this toolkit and\nwhat network access it has.\nSee https://python.langchain.com/docs/security for more information.\nExamples using create_openapi_agent\u00b6\nOpenAPI", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.base.create_openapi_agent.html"}
{"id": "1a5dc8f333a1-0", "text": "langchain.agents.conversational_chat.output_parser.ConvoOutputParser\u00b6\nclass langchain.agents.conversational_chat.output_parser.ConvoOutputParser[source]\u00b6\nBases: AgentOutputParser\nOutput parser for the conversational agent.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.output_parser.ConvoOutputParser.html"}
{"id": "1a5dc8f333a1-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.output_parser.ConvoOutputParser.html"}
{"id": "1a5dc8f333a1-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.output_parser.ConvoOutputParser.html"}
{"id": "1a5dc8f333a1-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nReturns formatting instructions for the given output parser.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.output_parser.ConvoOutputParser.html"}
{"id": "1a5dc8f333a1-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.output_parser.ConvoOutputParser.html"}
{"id": "1a5dc8f333a1-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nAttempts to parse the given text into an AgentAction or AgentFinish.\nRaises\nOutputParserException if parsing fails. \u2013 \nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.output_parser.ConvoOutputParser.html"}
{"id": "1a5dc8f333a1-6", "text": "prompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.output_parser.ConvoOutputParser.html"}
{"id": "1a5dc8f333a1-7", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.output_parser.ConvoOutputParser.html"}
{"id": "1a5dc8f333a1-8", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.output_parser.ConvoOutputParser.html"}
{"id": "0dd0302800ae-0", "text": "langchain.agents.openai_functions_agent.base.OpenAIFunctionsAgent\u00b6\nclass langchain.agents.openai_functions_agent.base.OpenAIFunctionsAgent[source]\u00b6\nBases: BaseSingleActionAgent\nAn Agent driven by OpenAIs function powered API.\nParameters\nllm \u2013 This should be an instance of ChatOpenAI, specifically a model\nthat supports using functions.\ntools \u2013 The tools this agent has access to.\nprompt \u2013 The prompt for this agent, should support agent_scratchpad as one\nof the variables. For an easy way to construct this prompt, use\nOpenAIFunctionsAgent.create_prompt(\u2026)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nparam prompt: langchain.schema.prompt_template.BasePromptTemplate [Required]\u00b6\nparam tools: Sequence[langchain.tools.base.BaseTool] [Required]\u00b6\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_functions_agent.base.OpenAIFunctionsAgent.html"}
{"id": "0dd0302800ae-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nclassmethod create_prompt(system_message: Optional[SystemMessage] = SystemMessage(content='You are a helpful AI assistant.'), extra_prompt_messages: Optional[List[BaseMessagePromptTemplate]] = None) \u2192 BasePromptTemplate[source]\u00b6\nCreate prompt for this agent.\nParameters\nsystem_message \u2013 Message to use as the system message that will be the\nfirst in the prompt.\nextra_prompt_messages \u2013 Prompt messages that will be placed between the\nsystem message and the new human input.\nReturns\nA prompt template to pass into this agent.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.\nclassmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, extra_prompt_messages: Optional[List[BaseMessagePromptTemplate]] = None, system_message: Optional[SystemMessage] = SystemMessage(content='You are a helpful AI assistant.'), **kwargs: Any) \u2192 BaseSingleActionAgent[source]\u00b6\nConstruct an agent from an LLM and tools.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_functions_agent.base.OpenAIFunctionsAgent.html"}
{"id": "0dd0302800ae-2", "text": "Construct an agent from an LLM and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 List[str][source]\u00b6\nGet allowed tools.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, with_functions: bool = True, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date, along with observations\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_functions_agent.base.OpenAIFunctionsAgent.html"}
{"id": "0dd0302800ae-3", "text": "**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish[source]\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty functions: List[dict]\u00b6\nproperty input_keys: List[str]\u00b6\nGet input keys. Input refers to user input here.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.\nExamples using OpenAIFunctionsAgent\u00b6\nMetaphor Search\nLLMonitor\nConversational Retrieval Agent\nAgents", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_functions_agent.base.OpenAIFunctionsAgent.html"}
{"id": "002ed64dfe06-0", "text": "langchain.agents.agent.AgentOutputParser\u00b6\nclass langchain.agents.agent.AgentOutputParser[source]\u00b6\nBases: BaseOutputParser[Union[AgentAction, AgentFinish]]\nBase class for parsing agent output into agent action/finish.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentOutputParser.html"}
{"id": "002ed64dfe06-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentOutputParser.html"}
{"id": "002ed64dfe06-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentOutputParser.html"}
{"id": "002ed64dfe06-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentOutputParser.html"}
{"id": "002ed64dfe06-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentOutputParser.html"}
{"id": "002ed64dfe06-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nabstract parse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentOutputParser.html"}
{"id": "002ed64dfe06-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentOutputParser.html"}
{"id": "002ed64dfe06-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentOutputParser.html"}
{"id": "002ed64dfe06-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using AgentOutputParser\u00b6\nPlug-and-Plai\nWikibase Agent\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nCustom Agent with PlugIn Retrieval\nCustom agent with tool retrieval", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentOutputParser.html"}
{"id": "bf9827ebddb1-0", "text": "langchain.agents.structured_chat.output_parser.StructuredChatOutputParserWithRetries\u00b6\nclass langchain.agents.structured_chat.output_parser.StructuredChatOutputParserWithRetries[source]\u00b6\nBases: AgentOutputParser\nOutput parser with retries for the structured chat agent.\nparam base_parser: langchain.agents.agent.AgentOutputParser [Optional]\u00b6\nThe base parser to use.\nparam output_fixing_parser: Optional[langchain.output_parsers.fix.OutputFixingParser] = None\u00b6\nThe output fixing parser to use.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParserWithRetries.html"}
{"id": "bf9827ebddb1-1", "text": "Parse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParserWithRetries.html"}
{"id": "bf9827ebddb1-2", "text": "Subclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParserWithRetries.html"}
{"id": "bf9827ebddb1-3", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_llm(llm: Optional[BaseLanguageModel] = None, base_parser: Optional[StructuredChatOutputParser] = None) \u2192 StructuredChatOutputParserWithRetries[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParserWithRetries.html"}
{"id": "bf9827ebddb1-4", "text": "Returns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParserWithRetries.html"}
{"id": "bf9827ebddb1-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParserWithRetries.html"}
{"id": "bf9827ebddb1-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParserWithRetries.html"}
{"id": "bf9827ebddb1-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParserWithRetries.html"}
{"id": "bf9827ebddb1-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParserWithRetries.html"}
{"id": "bf9827ebddb1-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParserWithRetries.html"}
{"id": "89c47c511e23-0", "text": "langchain.agents.agent_iterator.AgentExecutorIterator\u00b6\nclass langchain.agents.agent_iterator.AgentExecutorIterator(agent_executor: AgentExecutor, inputs: Any, callbacks: Callbacks = None, *, tags: Optional[list[str]] = None, include_run_info: bool = False, async_: bool = False)[source]\u00b6\nIterator for AgentExecutor.\nInitialize the AgentExecutorIterator with the given AgentExecutor,\ninputs, and optional callbacks.\nAttributes\nagent_executor\ncallback_manager\ncallbacks\ncolor_mapping\nfinal_outputs\ninputs\nname_to_tool_map\ntags\nrun_manager\ntimeout_manager\nMethods\n__init__(agent_executor,\u00a0inputs[,\u00a0...])\nInitialize the AgentExecutorIterator with the given AgentExecutor, inputs, and optional callbacks.\nbuild_callback_manager()\nCreate and configure the callback manager based on the current callbacks and tags.\nraise_stopasynciteration(output)\nRaise a StopAsyncIteration exception with the given output.\nraise_stopiteration(output)\nRaise a StopIteration exception with the given output.\nreset()\nReset the iterator to its initial state, clearing intermediate steps, iterations, and time elapsed.\nupdate_iterations()\nIncrement the number of iterations and update the time elapsed.\n__init__(agent_executor: AgentExecutor, inputs: Any, callbacks: Callbacks = None, *, tags: Optional[list[str]] = None, include_run_info: bool = False, async_: bool = False)[source]\u00b6\nInitialize the AgentExecutorIterator with the given AgentExecutor,\ninputs, and optional callbacks.\nbuild_callback_manager() \u2192 None[source]\u00b6\nCreate and configure the callback manager based on the current\ncallbacks and tags.\nasync raise_stopasynciteration(output: Any) \u2192 NoReturn[source]\u00b6\nRaise a StopAsyncIteration exception with the given output.\nClose the timeout context manager.\nraise_stopiteration(output: Any) \u2192 NoReturn[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_iterator.AgentExecutorIterator.html"}
{"id": "89c47c511e23-1", "text": "raise_stopiteration(output: Any) \u2192 NoReturn[source]\u00b6\nRaise a StopIteration exception with the given output.\nreset() \u2192 None[source]\u00b6\nReset the iterator to its initial state, clearing intermediate steps,\niterations, and time elapsed.\nupdate_iterations() \u2192 None[source]\u00b6\nIncrement the number of iterations and update the time elapsed.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_iterator.AgentExecutorIterator.html"}
{"id": "b225848ea780-0", "text": "langchain.agents.agent_toolkits.vectorstore.base.create_vectorstore_router_agent\u00b6\nlangchain.agents.agent_toolkits.vectorstore.base.create_vectorstore_router_agent(llm: BaseLanguageModel, toolkit: VectorStoreRouterToolkit, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = 'You are an agent designed to answer questions.\\nYou have access to tools for interacting with different sources, and the inputs to the tools are questions.\\nYour main task is to decide which of the tools is relevant for answering question at hand.\\nFor complex questions, you can break the question down into sub questions and use tools to answers the sub questions.\\n', verbose: bool = False, agent_executor_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 AgentExecutor[source]\u00b6\nConstruct a VectorStore router agent from an LLM and tools.\nParameters\nllm (BaseLanguageModel) \u2013 LLM that will be used by the agent\ntoolkit (VectorStoreRouterToolkit) \u2013 Set of tools for the agent which have routing capability with multiple vector stores\ncallback_manager (Optional[BaseCallbackManager], optional) \u2013 Object to handle the callback [ Defaults to None. ]\nprefix (str, optional) \u2013 The prefix prompt for the router agent. If not provided uses default ROUTER_PREFIX.\nverbose (bool, optional) \u2013 If you want to see the content of the scratchpad. [ Defaults to False ]\nagent_executor_kwargs (Optional[Dict[str, Any]], optional) \u2013 If there is any other parameter you want to send to the agent. [ Defaults to None ]\n**kwargs \u2013 Additional named parameters to pass to the ZeroShotAgent.\nReturns\nReturns a callable AgentExecutor object. Either you can call it or use run method with the query to get the response.\nReturn type\nAgentExecutor\nExamples using create_vectorstore_router_agent\u00b6\nVectorstore", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.vectorstore.base.create_vectorstore_router_agent.html"}
{"id": "1289cf2f5ad1-0", "text": "langchain.agents.mrkl.base.ChainConfig\u00b6\nclass langchain.agents.mrkl.base.ChainConfig(action_name: str, action: Callable, action_description: str)[source]\u00b6\nConfiguration for chain to use in MRKL system.\nParameters\naction_name \u2013 Name of the action.\naction \u2013 Action function to call.\naction_description \u2013 Description of the action.\nCreate new instance of ChainConfig(action_name, action, action_description)\nAttributes\naction\nAlias for field number 1\naction_description\nAlias for field number 2\naction_name\nAlias for field number 0\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.ChainConfig.html"}
{"id": "a1c5cb58c55c-0", "text": "langchain.agents.agent_toolkits.openapi.toolkit.RequestsToolkit\u00b6\nclass langchain.agents.agent_toolkits.openapi.toolkit.RequestsToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for making REST requests.\nSecurity Note: This toolkit contains tools to make GET, POST, PATCH, PUT,and DELETE requests to an API.\nExercise care in who is allowed to use this toolkit. If exposing\nto end users, consider that users will be able to make arbitrary\nrequests on behalf of the server hosting the code. For example,\nusers could ask the server to make a request to a private API\nthat is only accessible from the server.\nControl access to who can submit issue requests using this toolkit and\nwhat network access it has.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam requests_wrapper: langchain.utilities.requests.TextRequestsWrapper [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.toolkit.RequestsToolkit.html"}
{"id": "a1c5cb58c55c-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nReturn a list of tools.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.toolkit.RequestsToolkit.html"}
{"id": "a1c5cb58c55c-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.toolkit.RequestsToolkit.html"}
{"id": "131e8842afa5-0", "text": "langchain.agents.agent_toolkits.amadeus.toolkit.AmadeusToolkit\u00b6\nclass langchain.agents.agent_toolkits.amadeus.toolkit.AmadeusToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for interacting with Amadeus which offers APIs for travel search.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam client: Client [Optional]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.amadeus.toolkit.AmadeusToolkit.html"}
{"id": "131e8842afa5-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.amadeus.toolkit.AmadeusToolkit.html"}
{"id": "131e8842afa5-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using AmadeusToolkit\u00b6\nAmadeus", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.amadeus.toolkit.AmadeusToolkit.html"}
{"id": "ace7ce8b66bf-0", "text": "langchain.agents.react.base.ReActChain\u00b6\nclass langchain.agents.react.base.ReActChain[source]\u00b6\nBases: AgentExecutor\n[Deprecated] Chain that implements the ReAct paper.\nInitialize with the LLM and a docstore.\nparam agent: Union[BaseSingleActionAgent, BaseMultiActionAgent] [Required]\u00b6\nThe agent to run for creating a plan and determining actions\nto take at each step of the execution loop.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam early_stopping_method: str = 'force'\u00b6\nThe method to use for early stopping if the agent never\nreturns AgentFinish. Either \u2018force\u2019 or \u2018generate\u2019.\n\u201cforce\u201d returns a string saying that it stopped because it met atime or iteration limit.\n\u201cgenerate\u201d calls the agent\u2019s LLM Chain one final time to generatea final answer based on the previous steps.\nparam handle_parsing_errors: Union[bool, str, Callable[[OutputParserException], str]] = False\u00b6\nHow to handle errors raised by the agent\u2019s output parser.\nDefaults to False, which raises the error.\nIf true, the error will be sent back to the LLM as an observation.\nIf a string, the string itself will be sent to the LLM as an observation.\nIf a callable function, the function will be called with the exception\nas an argument, and the result of that function will be passed to the agentas an observation.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-1", "text": "param max_execution_time: Optional[float] = None\u00b6\nThe maximum amount of wall clock time to spend in the execution\nloop.\nparam max_iterations: Optional[int] = 15\u00b6\nThe maximum number of steps to take before ending the execution\nloop.\nSetting to \u2018None\u2019 could lead to an infinite loop.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam return_intermediate_steps: bool = False\u00b6\nWhether to return the agent\u2019s trajectory of intermediate steps\nat the end in addition to the final output.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tools: Sequence[BaseTool] [Required]\u00b6\nThe valid tools the agent can call.\nparam trim_intermediate_steps: Union[int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]] = -1\u00b6\nparam verbose: bool [Optional]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-2", "text": "param verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-3", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-4", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-5", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-6", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-7", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-8", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_agent_and_tools(agent: Union[BaseSingleActionAgent, BaseMultiActionAgent], tools: Sequence[BaseTool], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 AgentExecutor\u00b6\nCreate from agent and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-9", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\niter(inputs: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, include_run_info: bool = False, async_: bool = False) \u2192 AgentExecutorIterator\u00b6\nEnables iteration over steps taken to reach final output.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-10", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nlookup_tool(name: str) \u2192 BaseTool\u00b6\nLookup tool by name.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-11", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-12", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nRaise error - saving not supported for Agent Executors.\nsave_agent(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the underlying agent.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-13", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "ace7ce8b66bf-14", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html"}
{"id": "cd74e287046f-0", "text": "langchain.agents.loading.load_agent_from_config\u00b6\nlangchain.agents.loading.load_agent_from_config(config: dict, llm: Optional[BaseLanguageModel] = None, tools: Optional[List[Tool]] = None, **kwargs: Any) \u2192 Union[BaseSingleActionAgent, BaseMultiActionAgent][source]\u00b6\nLoad agent from Config Dict.\nParameters\nconfig \u2013 Config dict to load agent from.\nllm \u2013 Language model to use as the agent.\ntools \u2013 List of tools this agent has access to.\n**kwargs \u2013 Additional keyword arguments passed to the agent executor.\nReturns\nAn agent executor.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.loading.load_agent_from_config.html"}
{"id": "ed7a7a610d24-0", "text": "langchain.agents.conversational.base.ConversationalAgent\u00b6\nclass langchain.agents.conversational.base.ConversationalAgent[source]\u00b6\nBases: Agent\nAn agent that holds a conversation in addition to using tools.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_prefix: str = 'AI'\u00b6\nPrefix to use before AI output.\nparam allowed_tools: Optional[List[str]] = None\u00b6\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam output_parser: langchain.agents.agent.AgentOutputParser [Optional]\u00b6\nOutput parser for the agent.\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.base.ConversationalAgent.html"}
{"id": "ed7a7a610d24-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.base.ConversationalAgent.html"}
{"id": "ed7a7a610d24-2", "text": "classmethod create_prompt(tools: Sequence[BaseTool], prefix: str = '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: str = 'Begin!\\n\\nPrevious conversation history:\\n{chat_history}\\n\\nNew input: {input}\\n{agent_scratchpad}', format_instructions: str = '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", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.base.ConversationalAgent.html"}
{"id": "ed7a7a610d24-3", "text": "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: str = 'AI', human_prefix: str = 'Human', input_variables: Optional[List[str]] = None) \u2192 PromptTemplate[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.base.ConversationalAgent.html"}
{"id": "ed7a7a610d24-4", "text": "Create prompt in the style of the zero-shot agent.\nParameters\ntools \u2013 List of tools the agent will have access to, used to format the\nprompt.\nprefix \u2013 String to put before the list of tools.\nsuffix \u2013 String to put after the list of tools.\nai_prefix \u2013 String to use before AI output.\nhuman_prefix \u2013 String to use before human output.\ninput_variables \u2013 List of input variables the final prompt will expect.\nReturns\nA PromptTemplate with the template assembled from the pieces here.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.base.ConversationalAgent.html"}
{"id": "ed7a7a610d24-5", "text": "classmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, prefix: str = '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: str = 'Begin!\\n\\nPrevious conversation history:\\n{chat_history}\\n\\nNew input: {input}\\n{agent_scratchpad}', format_instructions: str = '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", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.base.ConversationalAgent.html"}
{"id": "ed7a7a610d24-6", "text": "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? No\\n{ai_prefix}: [your response here]\\n```', ai_prefix: str = 'AI', human_prefix: str = 'Human', input_variables: Optional[List[str]] = None, **kwargs: Any) \u2192 Agent[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.base.ConversationalAgent.html"}
{"id": "ed7a7a610d24-7", "text": "Construct an agent from an LLM and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]]\u00b6\nget_full_inputs(intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nCreate the full inputs for the LLMChain from intermediate steps.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.base.ConversationalAgent.html"}
{"id": "ed7a7a610d24-8", "text": "Parameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty llm_prefix: str\u00b6\nPrefix to append the llm call with.\nproperty observation_prefix: str\u00b6\nPrefix to append the observation with.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.base.ConversationalAgent.html"}
{"id": "c1537e294c64-0", "text": "langchain.agents.format_scratchpad.log_to_messages.format_log_to_messages\u00b6\nlangchain.agents.format_scratchpad.log_to_messages.format_log_to_messages(intermediate_steps: List[Tuple[AgentAction, str]], template_tool_response: str = '{observation}') \u2192 List[BaseMessage][source]\u00b6\nConstruct the scratchpad that lets the agent continue its thought process.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.format_scratchpad.log_to_messages.format_log_to_messages.html"}
{"id": "ee82e16ebdb0-0", "text": "langchain.agents.agent.RunnableAgent\u00b6\nclass langchain.agents.agent.RunnableAgent[source]\u00b6\nBases: BaseSingleActionAgent\nAgent powered by runnables.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam runnable: langchain.schema.runnable.base.Runnable[dict, Union[langchain.schema.agent.AgentAction, langchain.schema.agent.AgentFinish]] [Required]\u00b6\nRunnable to call to get agent action.\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.RunnableAgent.html"}
{"id": "ee82e16ebdb0-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.\nclassmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, **kwargs: Any) \u2192 BaseSingleActionAgent\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]]\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.RunnableAgent.html"}
{"id": "ee82e16ebdb0-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with the observations.\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty input_keys: List[str]\u00b6\nReturn the input keys.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.RunnableAgent.html"}
{"id": "ee82e16ebdb0-3", "text": "property input_keys: List[str]\u00b6\nReturn the input keys.\nReturns\nList of input keys.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.RunnableAgent.html"}
{"id": "b99c98e51a5b-0", "text": "langchain.agents.agent_toolkits.gmail.toolkit.GmailToolkit\u00b6\nclass langchain.agents.agent_toolkits.gmail.toolkit.GmailToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for interacting with Gmail.\nSecurity Note: This toolkit contains tools that can read and modifythe state of a service; e.g., by reading, creating, updating, deleting\ndata associated with this service.\nFor example, this toolkit can be used to send emails on behalf of the\nassociated account.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_resource: Resource [Optional]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.gmail.toolkit.GmailToolkit.html"}
{"id": "b99c98e51a5b-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.gmail.toolkit.GmailToolkit.html"}
{"id": "b99c98e51a5b-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using GmailToolkit\u00b6\nGmail", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.gmail.toolkit.GmailToolkit.html"}
{"id": "1214e23a0687-0", "text": "langchain.agents.agent_toolkits.openapi.spec.reduce_openapi_spec\u00b6\nlangchain.agents.agent_toolkits.openapi.spec.reduce_openapi_spec(spec: dict, dereference: bool = True) \u2192 ReducedOpenAPISpec[source]\u00b6\nSimplify/distill/minify a spec somehow.\nI want a smaller target for retrieval and (more importantly)\nI want smaller results from retrieval.\nI was hoping https://openapi.tools/ would have some useful bits\nto this end, but doesn\u2019t seem so.\nExamples using reduce_openapi_spec\u00b6\nOpenAPI", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.spec.reduce_openapi_spec.html"}
{"id": "a5c16fdcf8dd-0", "text": "langchain.agents.agent_toolkits.base.BaseToolkit\u00b6\nclass langchain.agents.agent_toolkits.base.BaseToolkit[source]\u00b6\nBases: BaseModel, ABC\nBase Toolkit representing a collection of related tools.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.base.BaseToolkit.html"}
{"id": "a5c16fdcf8dd-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nabstract get_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.base.BaseToolkit.html"}
{"id": "a5c16fdcf8dd-2", "text": "Try to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.base.BaseToolkit.html"}
{"id": "acebb795810e-0", "text": "langchain.agents.agent_iterator.rebuild_callback_manager_on_set\u00b6\nlangchain.agents.agent_iterator.rebuild_callback_manager_on_set(setter_method: Callable[[...], None]) \u2192 Callable[[...], None][source]\u00b6\nDecorator to force setters to rebuild callback mgr", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_iterator.rebuild_callback_manager_on_set.html"}
{"id": "2c8d4fc63d80-0", "text": "langchain.agents.agent_toolkits.playwright.toolkit.PlayWrightBrowserToolkit\u00b6\nclass langchain.agents.agent_toolkits.playwright.toolkit.PlayWrightBrowserToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for PlayWright browser tools.\nSecurity Note: This toolkit provides code to control a web-browser.\nCareful if exposing this toolkit to end-users. The tools in the toolkit\nare capable of navigating to arbitrary webpages, clicking on arbitrary\nelements, and extracting arbitrary text and hyperlinks from webpages.\nSpecifically, by default this toolkit allows navigating to:\nAny URL (including any internal network URLs)\nAnd local files\nIf exposing to end-users, consider limiting network access to the\nserver that hosts the agent; in addition, consider it is advised\nto create a custom NavigationTool wht an args_schema that limits the URLs\nthat can be navigated to (e.g., only allow navigating to URLs that\nstart with a particular prefix).\nRemember to scope permissions to the minimal permissions necessary for\nthe application. If the default tool selection is not appropriate for\nthe application, consider creating a custom toolkit with the appropriate\ntools.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam async_browser: Optional['AsyncBrowser'] = None\u00b6\nparam sync_browser: Optional['SyncBrowser'] = None\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.playwright.toolkit.PlayWrightBrowserToolkit.html"}
{"id": "2c8d4fc63d80-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_browser(sync_browser: Optional[SyncBrowser] = None, async_browser: Optional[AsyncBrowser] = None) \u2192 PlayWrightBrowserToolkit[source]\u00b6\nInstantiate the toolkit.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.playwright.toolkit.PlayWrightBrowserToolkit.html"}
{"id": "2c8d4fc63d80-2", "text": "Get the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using PlayWrightBrowserToolkit\u00b6\nMetaphor Search\nPlayWright Browser", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.playwright.toolkit.PlayWrightBrowserToolkit.html"}
{"id": "a0be5d393eb2-0", "text": "langchain.agents.format_scratchpad.openai_functions.format_to_openai_function_messages\u00b6\nlangchain.agents.format_scratchpad.openai_functions.format_to_openai_function_messages(intermediate_steps: Sequence[Tuple[AgentAction, str]]) \u2192 List[BaseMessage][source]\u00b6\nConvert (AgentAction, tool output) tuples into FunctionMessages.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date, along with observations\nReturns\nlist of messages to send to the LLM for the next prediction", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.format_scratchpad.openai_functions.format_to_openai_function_messages.html"}
{"id": "95de9e9c498d-0", "text": "langchain.agents.agent.ExceptionTool\u00b6\nclass langchain.agents.agent.ExceptionTool[source]\u00b6\nBases: BaseTool\nTool that just returns the query.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Exception tool'\u00b6\nDescription of the tool.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = '_Exception'\u00b6\nName of the tool.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.ExceptionTool.html"}
{"id": "95de9e9c498d-1", "text": "param verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.ExceptionTool.html"}
{"id": "95de9e9c498d-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.ExceptionTool.html"}
{"id": "95de9e9c498d-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.ExceptionTool.html"}
{"id": "95de9e9c498d-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.ExceptionTool.html"}
{"id": "95de9e9c498d-5", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.ExceptionTool.html"}
{"id": "95de9e9c498d-6", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nrun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.ExceptionTool.html"}
{"id": "95de9e9c498d-7", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.ExceptionTool.html"}
{"id": "95de9e9c498d-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.ExceptionTool.html"}
{"id": "95de9e9c498d-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.ExceptionTool.html"}
{"id": "183b16db1561-0", "text": "langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain\u00b6\nclass langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain[source]\u00b6\nBases: AgentExecutor\n[Deprecated] Chain that does self-ask with search.\nInitialize only with an LLM and a search chain.\nparam agent: Union[BaseSingleActionAgent, BaseMultiActionAgent] [Required]\u00b6\nThe agent to run for creating a plan and determining actions\nto take at each step of the execution loop.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam early_stopping_method: str = 'force'\u00b6\nThe method to use for early stopping if the agent never\nreturns AgentFinish. Either \u2018force\u2019 or \u2018generate\u2019.\n\u201cforce\u201d returns a string saying that it stopped because it met atime or iteration limit.\n\u201cgenerate\u201d calls the agent\u2019s LLM Chain one final time to generatea final answer based on the previous steps.\nparam handle_parsing_errors: Union[bool, str, Callable[[OutputParserException], str]] = False\u00b6\nHow to handle errors raised by the agent\u2019s output parser.\nDefaults to False, which raises the error.\nIf true, the error will be sent back to the LLM as an observation.\nIf a string, the string itself will be sent to the LLM as an observation.\nIf a callable function, the function will be called with the exception", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-1", "text": "If a callable function, the function will be called with the exception\nas an argument, and the result of that function will be passed to the agentas an observation.\nparam max_execution_time: Optional[float] = None\u00b6\nThe maximum amount of wall clock time to spend in the execution\nloop.\nparam max_iterations: Optional[int] = 15\u00b6\nThe maximum number of steps to take before ending the execution\nloop.\nSetting to \u2018None\u2019 could lead to an infinite loop.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam return_intermediate_steps: bool = False\u00b6\nWhether to return the agent\u2019s trajectory of intermediate steps\nat the end in addition to the final output.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tools: Sequence[BaseTool] [Required]\u00b6\nThe valid tools the agent can call.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-2", "text": "The valid tools the agent can call.\nparam trim_intermediate_steps: Union[int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]] = -1\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-3", "text": "include_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-4", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-5", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-6", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-7", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-8", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_agent_and_tools(agent: Union[BaseSingleActionAgent, BaseMultiActionAgent], tools: Sequence[BaseTool], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 AgentExecutor\u00b6\nCreate from agent and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-9", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\niter(inputs: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, include_run_info: bool = False, async_: bool = False) \u2192 AgentExecutorIterator\u00b6\nEnables iteration over steps taken to reach final output.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-10", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nlookup_tool(name: str) \u2192 BaseTool\u00b6\nLookup tool by name.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-11", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-12", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nRaise error - saving not supported for Agent Executors.\nsave_agent(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the underlying agent.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-13", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "183b16db1561-14", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.self_ask_with_search.base.SelfAskWithSearchChain.html"}
{"id": "303eb7adb75c-0", "text": "langchain.agents.agent_types.AgentType\u00b6\nclass langchain.agents.agent_types.AgentType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nAn enum for agent types.\nSee documentation: https://python.langchain.com/docs/modules/agents/agent_types/\nZERO_SHOT_REACT_DESCRIPTION = 'zero-shot-react-description'\u00b6\nA zero shot agent that does a reasoning step before acting.\nREACT_DOCSTORE = 'react-docstore'\u00b6\nA zero shot agent that does a reasoning step before acting.\nThis agent has access to a document store that allows it to look up\nrelevant information to answering the question.\nSELF_ASK_WITH_SEARCH = 'self-ask-with-search'\u00b6\nAn agent that breaks down a complex question into a series of simpler questions.\nThis agent uses a search tool to look up answers to the simpler questions\nin order to answer the original complex question.\nCONVERSATIONAL_REACT_DESCRIPTION = 'conversational-react-description'\u00b6\nCHAT_ZERO_SHOT_REACT_DESCRIPTION = 'chat-zero-shot-react-description'\u00b6\nA zero shot agent that does a reasoning step before acting.\nThis agent is designed to be used in conjunction\nCHAT_CONVERSATIONAL_REACT_DESCRIPTION = 'chat-conversational-react-description'\u00b6\nSTRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION = 'structured-chat-zero-shot-react-description'\u00b6\nAn zero-shot react agent optimized for chat models.\nThis agent is capable of invoking tools that have multiple inputs.\nOPENAI_FUNCTIONS = 'openai-functions'\u00b6\nAn agent optimized for using open AI functions.\nOPENAI_MULTI_FUNCTIONS = 'openai-multi-functions'\u00b6\nExamples using AgentType\u00b6\nChatGPT Plugins\nGoogle Serper\nHuman as a tool\nYahoo Finance News\nAWS Lambda\nGoogle Drive\nOpenWeatherMap\nSearch Tools\nEleven Labs Text2Speech", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_types.AgentType.html"}
{"id": "303eb7adb75c-1", "text": "AWS Lambda\nGoogle Drive\nOpenWeatherMap\nSearch Tools\nEleven Labs Text2Speech\nZapier Natural Language Actions\nArXiv\nMetaphor Search\nGraphQL\nEden AI\nShell (bash)\nZep Memory\nXata chat memory\nDynamodb Chat Message History\nLLMonitor\nArgilla\nStreamlit\nAim\nWeights & Biases\nMLflow\nFlyte\nWandB Tracing\nClearML\nLog, Trace, and Monitor\nPortkey\nCSV\nJira\nDocument Comparison\nPython\nAzure Cognitive Services\nSQL Database\nNatural Language APIs\nGmail\nAirbyte Question Answering\nGithub\nGoogle Drive tool\nAINetwork\nPlayWright Browser\nOffice365\nPandas Dataframe\nMultiOn\nAmadeus\nGitlab\nBittensor\nAmazon API Gateway\nDebugging\nLangSmith Walkthrough\nHugging Face Prompt Injection Identification\nComparing Chain Outputs\nAgent Trajectory\nAgents\nMulti-modal outputs: Image & Text\nAgent Debates with Tools\nSet env var OPENAI_API_KEY or load from a .env file\nSQL\nMultiple callback handlers\nMulti-Input Tools\nDefining Custom Tools\nTool Input Schema\nHuman-in-the-loop Tool Validation\nSelf-ask with search\nReAct document store\nOpenAI Multi Functions Agent\nCombine agents and vector stores\nAccess intermediate steps\nHandle parsing errors\nRunning Agent as an Iterator\nTimeouts for agents\nStreaming final agent output\nAdd Memory to OpenAI Functions Agent\nCap the max number of iterations\nCustom functions with OpenAI Functions Agent\nAsync API\nUse ToolKits with OpenAI Functions\nHuman input chat model\nFake LLM\nTracking token usage\nHuman input LLM", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_types.AgentType.html"}
{"id": "592ae25edead-0", "text": "langchain.agents.openai_assistant.base.OpenAIAssistantRunnable\u00b6\nclass langchain.agents.openai_assistant.base.OpenAIAssistantRunnable[source]\u00b6\nBases: RunnableSerializable[Dict, Union[List[OpenAIAssistantAction], OpenAIAssistantFinish, List[ThreadMessage], List[RequiredActionFunctionToolCall]]]\nRun an OpenAI Assistant.\nExample using OpenAI tools:from langchain_experimental.openai_assistant import OpenAIAssistantRunnable\ninterpreter_assistant = OpenAIAssistantRunnable.create_assistant(\n    name=\"langchain assistant\",\n    instructions=\"You are a personal math tutor. Write and run code to answer math questions.\",\n    tools=[{\"type\": \"code_interpreter\"}],\n    model=\"gpt-4-1106-preview\"\n)\noutput = interpreter_assistant.invoke({\"content\": \"What's 10 - 4 raised to the 2.7\"})\nExample using custom tools and AgentExecutor:from langchain_experimental.openai_assistant import OpenAIAssistantRunnable\nfrom langchain.agents import AgentExecutor\nfrom langchain.tools import E2BDataAnalysisTool\ntools = [E2BDataAnalysisTool(api_key=\"...\")]\nagent = OpenAIAssistantRunnable.create_assistant(\n    name=\"langchain assistant e2b tool\",\n    instructions=\"You are a personal math tutor. Write and run code to answer math questions.\",\n    tools=tools,\n    model=\"gpt-4-1106-preview\",\n    as_agent=True\n)\nagent_executor = AgentExecutor(agent=agent, tools=tools)\nagent_executor.invoke({\"content\": \"What's 10 - 4 raised to the 2.7\"})\nExample using custom tools and custom execution:from langchain_experimental.openai_assistant import OpenAIAssistantRunnable\nfrom langchain.agents import AgentExecutor\nfrom langchain.schema.agent import AgentFinish", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantRunnable.html"}
{"id": "592ae25edead-1", "text": "from langchain.agents import AgentExecutor\nfrom langchain.schema.agent import AgentFinish\nfrom langchain.tools import E2BDataAnalysisTool\ntools = [E2BDataAnalysisTool(api_key=\"...\")]\nagent = OpenAIAssistantRunnable.create_assistant(\n    name=\"langchain assistant e2b tool\",\n    instructions=\"You are a personal math tutor. Write and run code to answer math questions.\",\n    tools=tools,\n    model=\"gpt-4-1106-preview\",\n    as_agent=True\n)\ndef execute_agent(agent, tools, input):\n    tool_map = {tool.name: tool for tool in tools}\n    response = agent.invoke(input)\n    while not isinstance(response, AgentFinish):\n        tool_outputs = []\n        for action in response:\n            tool_output = tool_map[action.tool].invoke(action.tool_input)\n            tool_outputs.append({\"output\": tool_output, \"tool_call_id\": action.tool_call_id})\n        response = agent.invoke(\n            {\n                \"tool_outputs\": tool_outputs,\n                \"run_id\": action.run_id,\n                \"thread_id\": action.thread_id\n            }\n        )\n    return response\nresponse = execute_agent(agent, tools, {\"content\": \"What's 10 - 4 raised to the 2.7\"})\nnext_response = execute_agent(agent, tools, {\"content\": \"now add 17.241\", \"thread_id\": response.thread_id})\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam as_agent: bool = False\u00b6\nUse as a LangChain agent, compatible with the AgentExecutor.\nparam assistant_id: str [Required]\u00b6\nOpenAI assistant id.\nparam check_every_ms: float = 1000.0\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantRunnable.html"}
{"id": "592ae25edead-2", "text": "OpenAI assistant id.\nparam check_every_ms: float = 1000.0\u00b6\nFrequency with which to check run progress in ms.\nparam client: openai.OpenAI [Optional]\u00b6\nOpenAI client.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantRunnable.html"}
{"id": "592ae25edead-3", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantRunnable.html"}
{"id": "592ae25edead-4", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantRunnable.html"}
{"id": "592ae25edead-5", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nclassmethod create_assistant(name: str, instructions: str, tools: Sequence[Union[BaseTool, dict]], model: str, *, client: Optional[openai.OpenAI] = None, **kwargs: Any) \u2192 OpenAIAssistantRunnable[source]\u00b6\nCreate an OpenAI Assistant and instantiate the Runnable.\nParameters\nname \u2013 Assistant name.\ninstructions \u2013 Assistant instructions.\ntools \u2013 Assistant tools. Can be passed in in OpenAI format or as BaseTools.\nmodel \u2013 Assistant model to use.\nclient \u2013 OpenAI client. Will create default client if not specified.\nReturns\nOpenAIAssistantRunnable configured to run using the created assistant.\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantRunnable.html"}
{"id": "592ae25edead-6", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: dict, config: Optional[RunnableConfig] = None) \u2192 OutputType[source]\u00b6\nInvoke assistant.\nParameters\ninput \u2013 Runnable input dict that can have:\ncontent: User message when starting a new run.\nthread_id: Existing thread to use.\nrun_id: Existing run to use. Should only be supplied when providing\nthe tool output for a required action after an initial invocation.\nfile_ids: File ids to include in new run. Used for retrieval.\nmessage_metadata: Metadata to associate with new message.\nthread_metadata: Metadata to associate with new thread. Only relevant\nwhen new thread being created.\ninstructions: Additional run instructions.\nmodel: Override Assistant model for this run.\ntools: Override Assistant tools for this run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantRunnable.html"}
{"id": "592ae25edead-7", "text": "model: Override Assistant model for this run.\ntools: Override Assistant tools for this run.\nrun_metadata: Metadata to associate with new run.\nconfig \u2013 Runnable config:\nReturns\nIf self.as_agent, will returnUnion[List[OpenAIAssistantAction], OpenAIAssistantFinish]. Otherwise\nwill return OpenAI types\nUnion[List[ThreadMessage], List[RequiredActionFunctionToolCall]].\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantRunnable.html"}
{"id": "592ae25edead-8", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantRunnable.html"}
{"id": "592ae25edead-9", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantRunnable.html"}
{"id": "592ae25edead-10", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantRunnable.html"}
{"id": "9dbdf0dc6bd0-0", "text": "langchain.agents.agent_toolkits.ainetwork.toolkit.AINetworkToolkit\u00b6\nclass langchain.agents.agent_toolkits.ainetwork.toolkit.AINetworkToolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for interacting with AINetwork Blockchain.\nSecurity Note: This toolkit contains tools that can read and modifythe state of a service; e.g., by reading, creating, updating, deleting\ndata associated with this service.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam interface: Optional[Ain] = None\u00b6\nparam network: Optional[Literal['mainnet', 'testnet']] = 'testnet'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.ainetwork.toolkit.AINetworkToolkit.html"}
{"id": "9dbdf0dc6bd0-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.ainetwork.toolkit.AINetworkToolkit.html"}
{"id": "9dbdf0dc6bd0-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using AINetworkToolkit\u00b6\nAINetwork", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.ainetwork.toolkit.AINetworkToolkit.html"}
{"id": "c1dd3547de99-0", "text": "langchain.agents.openai_assistant.base.OpenAIAssistantFinish\u00b6\nclass langchain.agents.openai_assistant.base.OpenAIAssistantFinish[source]\u00b6\nBases: AgentFinish\nAgentFinish with run and thread metadata.\nOverride init to support instantiation by position for backward compat.\nparam log: str [Required]\u00b6\nAdditional information to log about the return value.\nThis is used to pass along the full LLM prediction, not just the parsed out\nreturn value. For example, if the full LLM prediction was\nFinal Answer: 2 you may want to just return 2 as a return value, but pass\nalong the full string as a log (for debugging or observability purposes).\nparam return_values: dict [Required]\u00b6\nDictionary of return values.\nparam run_id: str [Required]\u00b6\nparam thread_id: str [Required]\u00b6\nparam type: Literal['AgentFinish'] = 'AgentFinish'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantFinish.html"}
{"id": "c1dd3547de99-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantFinish.html"}
{"id": "c1dd3547de99-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_assistant.base.OpenAIAssistantFinish.html"}
{"id": "5f92459652ad-0", "text": "langchain.agents.xml.base.XMLAgent\u00b6\nclass langchain.agents.xml.base.XMLAgent[source]\u00b6\nBases: BaseSingleActionAgent\nAgent that uses XML tags.\nParameters\ntools \u2013 list of tools the agent can choose from\nllm_chain \u2013 The LLMChain to call to predict the next action\nExamples\nfrom langchain.agents import XMLAgent\nfrom langchain\ntools = ...\nmodel =\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nChain to use to predict action.\nparam tools: List[langchain.tools.base.BaseTool] [Required]\u00b6\nList of tools this agent has access to.\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.xml.base.XMLAgent.html"}
{"id": "5f92459652ad-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.\nclassmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, **kwargs: Any) \u2192 BaseSingleActionAgent\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]]\u00b6\nstatic get_default_output_parser() \u2192 XMLAgentOutputParser[source]\u00b6\nstatic get_default_prompt() \u2192 ChatPromptTemplate[source]\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.xml.base.XMLAgent.html"}
{"id": "5f92459652ad-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.xml.base.XMLAgent.html"}
{"id": "5f92459652ad-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty return_values: List[str]\u00b6\nReturn values of the agent.\nExamples using XMLAgent\u00b6\nXML Agent\nAgents", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.xml.base.XMLAgent.html"}
{"id": "ddc4169270eb-0", "text": "langchain.agents.agent.BaseMultiActionAgent\u00b6\nclass langchain.agents.agent.BaseMultiActionAgent[source]\u00b6\nBases: BaseModel\nBase Multi Action Agent class.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nabstract async aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with the observations.\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nActions specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.BaseMultiActionAgent.html"}
{"id": "ddc4169270eb-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict[source]\u00b6\nReturn dictionary representation of agent.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]][source]\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nabstract plan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.BaseMultiActionAgent.html"}
{"id": "ddc4169270eb-2", "text": "Parameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with the observations.\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nActions specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish[source]\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None[source]\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict[source]\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty return_values: List[str]\u00b6\nReturn values of the agent.\nExamples using BaseMultiActionAgent\u00b6\nCustom multi-action agent", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.BaseMultiActionAgent.html"}
{"id": "89cc679a7702-0", "text": "langchain.agents.conversational.output_parser.ConvoOutputParser\u00b6\nclass langchain.agents.conversational.output_parser.ConvoOutputParser[source]\u00b6\nBases: AgentOutputParser\nOutput parser for the conversational agent.\nparam ai_prefix: str = 'AI'\u00b6\nPrefix to use before AI output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.output_parser.ConvoOutputParser.html"}
{"id": "89cc679a7702-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.output_parser.ConvoOutputParser.html"}
{"id": "89cc679a7702-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.output_parser.ConvoOutputParser.html"}
{"id": "89cc679a7702-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.output_parser.ConvoOutputParser.html"}
{"id": "89cc679a7702-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.output_parser.ConvoOutputParser.html"}
{"id": "89cc679a7702-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.output_parser.ConvoOutputParser.html"}
{"id": "89cc679a7702-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.output_parser.ConvoOutputParser.html"}
{"id": "89cc679a7702-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.output_parser.ConvoOutputParser.html"}
{"id": "89cc679a7702-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.conversational.output_parser.ConvoOutputParser.html"}
{"id": "c84a43a57d39-0", "text": "langchain.agents.agent_toolkits.conversational_retrieval.openai_functions.create_conversational_retrieval_agent\u00b6\nlangchain.agents.agent_toolkits.conversational_retrieval.openai_functions.create_conversational_retrieval_agent(llm: BaseLanguageModel, tools: List[BaseTool], remember_intermediate_steps: bool = True, memory_key: str = 'chat_history', system_message: Optional[SystemMessage] = None, verbose: bool = False, max_token_limit: int = 2000, **kwargs: Any) \u2192 AgentExecutor[source]\u00b6\nA convenience method for creating a conversational retrieval agent.\nParameters\nllm \u2013 The language model to use, should be ChatOpenAI\ntools \u2013 A list of tools the agent has access to\nremember_intermediate_steps \u2013 Whether the agent should remember intermediate\nsteps or not. Intermediate steps refer to prior action/observation\npairs from previous questions. The benefit of remembering these is if\nthere is relevant information in there, the agent can use it to answer\nfollow up questions. The downside is it will take up more tokens.\nmemory_key \u2013 The name of the memory key in the prompt.\nsystem_message \u2013 The system message to use. By default, a basic one will\nbe used.\nverbose \u2013 Whether or not the final AgentExecutor should be verbose or not,\ndefaults to False.\nmax_token_limit \u2013 The max number of tokens to keep around in memory.\nDefaults to 2000.\nReturns\nAn agent executor initialized appropriately\nExamples using create_conversational_retrieval_agent\u00b6\nConversational Retrieval Agent", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.conversational_retrieval.openai_functions.create_conversational_retrieval_agent.html"}
{"id": "9a3784cef60d-0", "text": "langchain.agents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing\u00b6\nclass langchain.agents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing[source]\u00b6\nBases: BaseRequestsTool, BaseTool\nRequests GET tool with LLM-instructed extraction of truncated responses.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'Use this to GET content from a website.\\nInput to the tool should be a json string with 3 keys: \"url\", \"params\" and \"output_instructions\".\\nThe value of \"url\" should be a string. \\nThe value of \"params\" should be a dict of the needed and available parameters from the OpenAPI spec related to the endpoint. \\nIf parameters are not needed, or not available, leave it empty.\\nThe value of \"output_instructions\" should be instructions on what information to extract from the response, \\nfor example the id(s) for a resource(s) that the GET request fetches.\\n'\u00b6\nTool description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam llm_chain: langchain.chains.llm.LLMChain [Optional]\u00b6\nLLMChain used to extract the response.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing.html"}
{"id": "9a3784cef60d-1", "text": "Optional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str = 'requests_get'\u00b6\nTool name.\nparam requests_wrapper: TextRequestsWrapper [Required]\u00b6\nparam response_length: Optional[int] = 5000\u00b6\nMaximum length of the response to be returned.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing.html"}
{"id": "9a3784cef60d-2", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing.html"}
{"id": "9a3784cef60d-3", "text": "step, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing.html"}
{"id": "9a3784cef60d-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing.html"}
{"id": "9a3784cef60d-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing.html"}
{"id": "9a3784cef60d-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing.html"}
{"id": "9a3784cef60d-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing.html"}
{"id": "9a3784cef60d-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing.html"}
{"id": "9a3784cef60d-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing.html"}
{"id": "5a50fe8d6d83-0", "text": "langchain.agents.react.base.ReActTextWorldAgent\u00b6\nclass langchain.agents.react.base.ReActTextWorldAgent[source]\u00b6\nBases: ReActDocstoreAgent\nAgent for the ReAct TextWorld chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_tools: Optional[List[str]] = None\u00b6\nparam llm_chain: LLMChain [Required]\u00b6\nparam output_parser: AgentOutputParser [Optional]\u00b6\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActTextWorldAgent.html"}
{"id": "5a50fe8d6d83-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nclassmethod create_prompt(tools: Sequence[BaseTool]) \u2192 BasePromptTemplate[source]\u00b6\nReturn default prompt.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.\nclassmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, **kwargs: Any) \u2192 Agent\u00b6\nConstruct an agent from an LLM and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]]\u00b6\nget_full_inputs(intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nCreate the full inputs for the LLMChain from intermediate steps.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActTextWorldAgent.html"}
{"id": "5a50fe8d6d83-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActTextWorldAgent.html"}
{"id": "5a50fe8d6d83-3", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty llm_prefix: str\u00b6\nPrefix to append the LLM call with.\nproperty observation_prefix: str\u00b6\nPrefix to append the observation with.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActTextWorldAgent.html"}
{"id": "27795fab3713-0", "text": "langchain.agents.mrkl.base.MRKLChain\u00b6\nclass langchain.agents.mrkl.base.MRKLChain[source]\u00b6\nBases: AgentExecutor\n[Deprecated] Chain that implements the MRKL system.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam agent: Union[BaseSingleActionAgent, BaseMultiActionAgent] [Required]\u00b6\nThe agent to run for creating a plan and determining actions\nto take at each step of the execution loop.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam early_stopping_method: str = 'force'\u00b6\nThe method to use for early stopping if the agent never\nreturns AgentFinish. Either \u2018force\u2019 or \u2018generate\u2019.\n\u201cforce\u201d returns a string saying that it stopped because it met atime or iteration limit.\n\u201cgenerate\u201d calls the agent\u2019s LLM Chain one final time to generatea final answer based on the previous steps.\nparam handle_parsing_errors: Union[bool, str, Callable[[OutputParserException], str]] = False\u00b6\nHow to handle errors raised by the agent\u2019s output parser.\nDefaults to False, which raises the error.\nIf true, the error will be sent back to the LLM as an observation.\nIf a string, the string itself will be sent to the LLM as an observation.\nIf a callable function, the function will be called with the exception", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-1", "text": "If a callable function, the function will be called with the exception\nas an argument, and the result of that function will be passed to the agentas an observation.\nparam max_execution_time: Optional[float] = None\u00b6\nThe maximum amount of wall clock time to spend in the execution\nloop.\nparam max_iterations: Optional[int] = 15\u00b6\nThe maximum number of steps to take before ending the execution\nloop.\nSetting to \u2018None\u2019 could lead to an infinite loop.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam return_intermediate_steps: bool = False\u00b6\nWhether to return the agent\u2019s trajectory of intermediate steps\nat the end in addition to the final output.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tools: Sequence[BaseTool] [Required]\u00b6\nThe valid tools the agent can call.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-2", "text": "The valid tools the agent can call.\nparam trim_intermediate_steps: Union[int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]] = -1\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-3", "text": "include_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-4", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-5", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-6", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-7", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-8", "text": "method.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_agent_and_tools(agent: Union[BaseSingleActionAgent, BaseMultiActionAgent], tools: Sequence[BaseTool], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 AgentExecutor\u00b6\nCreate from agent and tools.\nclassmethod from_chains(llm: BaseLanguageModel, chains: List[ChainConfig], **kwargs: Any) \u2192 AgentExecutor[source]\u00b6\nUser friendly way to initialize the MRKL chain.\nThis is intended to be an easy way to get up and running with the\nMRKL chain.\nParameters\nllm \u2013 The LLM to use as the agent LLM.\nchains \u2013 The chains the MRKL system has access to.\n**kwargs \u2013 parameters to be passed to initialization.\nReturns\nAn initialized MRKL chain.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-9", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\niter(inputs: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, include_run_info: bool = False, async_: bool = False) \u2192 AgentExecutorIterator\u00b6\nEnables iteration over steps taken to reach final output.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-10", "text": "Enables iteration over steps taken to reach final output.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nlookup_tool(name: str) \u2192 BaseTool\u00b6\nLookup tool by name.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-11", "text": "Validate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-12", "text": "addition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nRaise error - saving not supported for Agent Executors.\nsave_agent(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the underlying agent.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-13", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-14", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27795fab3713-15", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.MRKLChain.html"}
{"id": "27a131c2555a-0", "text": "langchain.agents.react.output_parser.ReActOutputParser\u00b6\nclass langchain.agents.react.output_parser.ReActOutputParser[source]\u00b6\nBases: AgentOutputParser\nOutput parser for the ReAct agent.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.output_parser.ReActOutputParser.html"}
{"id": "27a131c2555a-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.output_parser.ReActOutputParser.html"}
{"id": "27a131c2555a-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.output_parser.ReActOutputParser.html"}
{"id": "27a131c2555a-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.output_parser.ReActOutputParser.html"}
{"id": "27a131c2555a-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.output_parser.ReActOutputParser.html"}
{"id": "27a131c2555a-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.output_parser.ReActOutputParser.html"}
{"id": "27a131c2555a-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.output_parser.ReActOutputParser.html"}
{"id": "27a131c2555a-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.output_parser.ReActOutputParser.html"}
{"id": "27a131c2555a-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.react.output_parser.ReActOutputParser.html"}
{"id": "58bcab795734-0", "text": "langchain.agents.agent_toolkits.clickup.toolkit.ClickupToolkit\u00b6\nclass langchain.agents.agent_toolkits.clickup.toolkit.ClickupToolkit[source]\u00b6\nBases: BaseToolkit\nClickup Toolkit.\nSecurity Note: This toolkit contains tools that can read and modifythe state of a service; e.g., by reading, creating, updating, deleting\ndata associated with this service.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam tools: List[langchain.tools.base.BaseTool] = []\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.clickup.toolkit.ClickupToolkit.html"}
{"id": "58bcab795734-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_clickup_api_wrapper(clickup_api_wrapper: ClickupAPIWrapper) \u2192 ClickupToolkit[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.clickup.toolkit.ClickupToolkit.html"}
{"id": "58bcab795734-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.clickup.toolkit.ClickupToolkit.html"}
{"id": "3832cfae0661-0", "text": "langchain.agents.agent_toolkits.zapier.toolkit.ZapierToolkit\u00b6\nclass langchain.agents.agent_toolkits.zapier.toolkit.ZapierToolkit[source]\u00b6\nBases: BaseToolkit\nZapier Toolkit.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam tools: List[langchain.tools.base.BaseTool] = []\u00b6\nasync classmethod async_from_zapier_nla_wrapper(zapier_nla_wrapper: ZapierNLAWrapper) \u2192 ZapierToolkit[source]\u00b6\nCreate a toolkit from a ZapierNLAWrapper.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.zapier.toolkit.ZapierToolkit.html"}
{"id": "3832cfae0661-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_zapier_nla_wrapper(zapier_nla_wrapper: ZapierNLAWrapper) \u2192 ZapierToolkit[source]\u00b6\nCreate a toolkit from a ZapierNLAWrapper.\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.zapier.toolkit.ZapierToolkit.html"}
{"id": "3832cfae0661-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using ZapierToolkit\u00b6\nZapier Natural Language Actions", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.zapier.toolkit.ZapierToolkit.html"}
{"id": "970a58409bd9-0", "text": "langchain.agents.mrkl.base.ZeroShotAgent\u00b6\nclass langchain.agents.mrkl.base.ZeroShotAgent[source]\u00b6\nBases: Agent\nAgent for the MRKL chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_tools: Optional[List[str]] = None\u00b6\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam output_parser: langchain.agents.agent.AgentOutputParser [Optional]\u00b6\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.ZeroShotAgent.html"}
{"id": "970a58409bd9-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nclassmethod create_prompt(tools: Sequence[BaseTool], prefix: str = 'Answer the following questions as best you can. You have access to the following tools:', suffix: str = 'Begin!\\n\\nQuestion: {input}\\nThought:{agent_scratchpad}', format_instructions: str = '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: Optional[List[str]] = None) \u2192 PromptTemplate[source]\u00b6\nCreate prompt in the style of the zero shot agent.\nParameters\ntools \u2013 List of tools the agent will have access to, used to format the\nprompt.\nprefix \u2013 String to put before the list of tools.\nsuffix \u2013 String to put after the list of tools.\ninput_variables \u2013 List of input variables the final prompt will expect.\nReturns\nA PromptTemplate with the template assembled from the pieces here.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.ZeroShotAgent.html"}
{"id": "970a58409bd9-2", "text": "dict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.\nclassmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, prefix: str = 'Answer the following questions as best you can. You have access to the following tools:', suffix: str = 'Begin!\\n\\nQuestion: {input}\\nThought:{agent_scratchpad}', format_instructions: str = '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: Optional[List[str]] = None, **kwargs: Any) \u2192 Agent[source]\u00b6\nConstruct an agent from an LLM and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]]\u00b6\nget_full_inputs(intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nCreate the full inputs for the LLMChain from intermediate steps.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.ZeroShotAgent.html"}
{"id": "970a58409bd9-3", "text": "Create the full inputs for the LLMChain from intermediate steps.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.ZeroShotAgent.html"}
{"id": "970a58409bd9-4", "text": "Return response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty llm_prefix: str\u00b6\nPrefix to append the llm call with.\nproperty observation_prefix: str\u00b6\nPrefix to append the observation with.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.\nExamples using ZeroShotAgent\u00b6\nJina\nBittensor\nBabyAGI with Tools\nMessage Memory in Agent backed by a database\nMemory in Agent\nCustom MRKL agent\nShared memory across agents and tools", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.ZeroShotAgent.html"}
{"id": "8c4ca9b89211-0", "text": "langchain.agents.agent_toolkits.nla.tool.NLATool\u00b6\nclass langchain.agents.agent_toolkits.nla.tool.NLATool[source]\u00b6\nBases: Tool\nNatural Language API Tool.\nInitialize tool.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam coroutine: Optional[Callable[..., Awaitable[str]]] = None\u00b6\nThe asynchronous version of the function.\nparam description: str = ''\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam func: Optional[Callable[..., str]] = None\u00b6\nThe function to run when the tool is called.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam name: str [Required]\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.nla.tool.NLATool.html"}
{"id": "8c4ca9b89211-1", "text": "Optional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.nla.tool.NLATool.html"}
{"id": "8c4ca9b89211-2", "text": "Run the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.nla.tool.NLATool.html"}
{"id": "8c4ca9b89211-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.nla.tool.NLATool.html"}
{"id": "8c4ca9b89211-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_function(func: Optional[Callable], name: str, description: str, return_direct: bool = False, args_schema: Optional[Type[BaseModel]] = None, coroutine: Optional[Callable[[...], Awaitable[Any]]] = None, **kwargs: Any) \u2192 Tool\u00b6\nInitialize tool from a function.\nclassmethod from_llm_and_method(llm: BaseLanguageModel, path: str, method: str, spec: OpenAPISpec, requests: Optional[Requests] = None, verbose: bool = False, return_intermediate_steps: bool = False, **kwargs: Any) \u2192 NLATool[source]\u00b6\nInstantiate the tool from the specified path and method.\nclassmethod from_open_api_endpoint_chain(chain: OpenAPIEndpointChain, api_title: str) \u2192 NLATool[source]\u00b6\nConvert an endpoint chain to an API endpoint tool.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.nla.tool.NLATool.html"}
{"id": "8c4ca9b89211-5", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.nla.tool.NLATool.html"}
{"id": "8c4ca9b89211-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.nla.tool.NLATool.html"}
{"id": "8c4ca9b89211-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.nla.tool.NLATool.html"}
{"id": "8c4ca9b89211-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.nla.tool.NLATool.html"}
{"id": "8c4ca9b89211-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nThe tool\u2019s input arguments.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.nla.tool.NLATool.html"}
{"id": "1abb79735288-0", "text": "langchain.agents.load_tools.get_all_tool_names\u00b6\nlangchain.agents.load_tools.get_all_tool_names() \u2192 List[str][source]\u00b6\nGet a list of all possible tool names.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.load_tools.get_all_tool_names.html"}
{"id": "9306121ac79a-0", "text": "langchain.agents.format_scratchpad.xml.format_xml\u00b6\nlangchain.agents.format_scratchpad.xml.format_xml(intermediate_steps: List[Tuple[AgentAction, str]]) \u2192 str[source]\u00b6\nFormat the intermediate steps as XML.\nParameters\nintermediate_steps \u2013 The intermediate steps.\nReturns\nThe intermediate steps as XML.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.format_scratchpad.xml.format_xml.html"}
{"id": "440f8907fa90-0", "text": "langchain.agents.agent_toolkits.openapi.planner.create_openapi_agent\u00b6\nlangchain.agents.agent_toolkits.openapi.planner.create_openapi_agent(api_spec: ReducedOpenAPISpec, requests_wrapper: TextRequestsWrapper, llm: BaseLanguageModel, shared_memory: Optional[ReadOnlySharedMemory] = None, callback_manager: Optional[BaseCallbackManager] = None, verbose: bool = True, agent_executor_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 AgentExecutor[source]\u00b6\nInstantiate OpenAI API planner and controller for a given spec.\nInject credentials via requests_wrapper.\nWe use a top-level \u201corchestrator\u201d agent to invoke the planner and controller,\nrather than a top-level planner\nthat invokes a controller with its plan. This is to keep the planner simple.\nExamples using create_openapi_agent\u00b6\nOpenAPI", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.planner.create_openapi_agent.html"}
{"id": "8f411e6eec1f-0", "text": "langchain.agents.agent_toolkits.office365.toolkit.O365Toolkit\u00b6\nclass langchain.agents.agent_toolkits.office365.toolkit.O365Toolkit[source]\u00b6\nBases: BaseToolkit\nToolkit for interacting with Office 365.\nSecurity Note: This toolkit contains tools that can read and modifythe state of a service; e.g., by reading, creating, updating, deleting\ndata associated with this service.\nFor example, this toolkit can be used search through emails and events,\nsend messages and event invites, and create draft messages.\nPlease make sure that the permissions given by this toolkit\nare appropriate for your use case.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam account: Account [Optional]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.office365.toolkit.O365Toolkit.html"}
{"id": "8f411e6eec1f-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.office365.toolkit.O365Toolkit.html"}
{"id": "8f411e6eec1f-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using O365Toolkit\u00b6\nOffice365", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.office365.toolkit.O365Toolkit.html"}
{"id": "12c96de7f01e-0", "text": "langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser\u00b6\nclass langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser[source]\u00b6\nBases: MultiActionAgentOutputParser\nParses a message into agent actions/finish.\nIs meant to be used with OpenAI models, as it relies on the specific\ntool_calls parameter from OpenAI to convey what tools to use.\nIf a tool_calls parameter is passed, then that is used to get\nthe tool names and tool inputs.\nIf one is not passed, then the AIMessage is assumed to be the final output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "12c96de7f01e-1", "text": "Parse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "12c96de7f01e-2", "text": "Subclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "12c96de7f01e-3", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "12c96de7f01e-4", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "12c96de7f01e-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6\nParse text into agent actions/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "12c96de7f01e-6", "text": "The prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "12c96de7f01e-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "12c96de7f01e-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "7e94a5b85b69-0", "text": "langchain.agents.utils.validate_tools_single_input\u00b6\nlangchain.agents.utils.validate_tools_single_input(class_name: str, tools: Sequence[BaseTool]) \u2192 None[source]\u00b6\nValidate tools for single input.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.utils.validate_tools_single_input.html"}
{"id": "9782730f3d8c-0", "text": "langchain.agents.mrkl.output_parser.MRKLOutputParser\u00b6\nclass langchain.agents.mrkl.output_parser.MRKLOutputParser[source]\u00b6\nBases: AgentOutputParser\nMRKL Output parser for the chat agent.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.output_parser.MRKLOutputParser.html"}
{"id": "9782730f3d8c-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.output_parser.MRKLOutputParser.html"}
{"id": "9782730f3d8c-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.output_parser.MRKLOutputParser.html"}
{"id": "9782730f3d8c-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.output_parser.MRKLOutputParser.html"}
{"id": "9782730f3d8c-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.output_parser.MRKLOutputParser.html"}
{"id": "9782730f3d8c-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.output_parser.MRKLOutputParser.html"}
{"id": "9782730f3d8c-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.output_parser.MRKLOutputParser.html"}
{"id": "9782730f3d8c-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.output_parser.MRKLOutputParser.html"}
{"id": "9782730f3d8c-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.output_parser.MRKLOutputParser.html"}
{"id": "731a7c18ac5c-0", "text": "langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser\u00b6\nclass langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser[source]\u00b6\nBases: AgentOutputParser\nParses ReAct-style LLM calls that have a single tool input in json format.\nExpects output to be in one of two formats.\nIf the output signals that an action should be taken,\nshould be in the below format. This will result in an AgentAction\nbeing returned.\n`\nThought: agent thought here\nAction:\n`\n{\n\u201caction\u201d: \u201csearch\u201d,\n\u201caction_input\u201d: \u201cwhat is the temperature in SF\u201d\n```\nIf the output signals that a final answer should be given,\nshould be in the below format. This will result in an AgentFinish\nbeing returned.\n`\nThought: agent thought here\nFinal Answer: The temperature is 100 degrees\n`\nparam pattern = re.compile('^.*?`{3}(?:json)?\\\\n(.*?)`{3}.*?$', re.DOTALL)\u00b6\nRegex pattern to parse the output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "731a7c18ac5c-1", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "731a7c18ac5c-2", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "731a7c18ac5c-3", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "731a7c18ac5c-4", "text": "Instructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "731a7c18ac5c-5", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "731a7c18ac5c-6", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "731a7c18ac5c-7", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "731a7c18ac5c-8", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "731a7c18ac5c-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "256c2cc9b14f-0", "text": "langchain.agents.agent_toolkits.json.base.create_json_agent\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.json.base.create_json_agent.html"}
{"id": "256c2cc9b14f-1", "text": "langchain.agents.agent_toolkits.json.base.create_json_agent(llm: BaseLanguageModel, toolkit: JsonToolkit, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = '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", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.json.base.create_json_agent.html"}
{"id": "256c2cc9b14f-2", "text": "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 return it.\\n', suffix: str = '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: str = '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: Optional[List[str]] = None, verbose: bool = False, agent_executor_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 AgentExecutor[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.json.base.create_json_agent.html"}
{"id": "256c2cc9b14f-3", "text": "Construct a json agent from an LLM and tools.\nExamples using create_json_agent\u00b6\nJSON", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.json.base.create_json_agent.html"}
{"id": "383ccfc31616-0", "text": "langchain.agents.agent_toolkits.github.toolkit.GitHubToolkit\u00b6\nclass langchain.agents.agent_toolkits.github.toolkit.GitHubToolkit[source]\u00b6\nBases: BaseToolkit\nGitHub Toolkit.\nSecurity Note: This toolkit contains tools that can read and modifythe state of a service; e.g., by creating, deleting, or updating,\nreading underlying data.\nFor example, this toolkit can be used to create issues, pull requests,\nand comments on GitHub.\nSee [Security](https://python.langchain.com/docs/security) for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam tools: List[langchain.tools.base.BaseTool] = []\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.github.toolkit.GitHubToolkit.html"}
{"id": "383ccfc31616-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_github_api_wrapper(github_api_wrapper: GitHubAPIWrapper) \u2192 GitHubToolkit[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools in the toolkit.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.github.toolkit.GitHubToolkit.html"}
{"id": "383ccfc31616-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using GitHubToolkit\u00b6\nGithub", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.github.toolkit.GitHubToolkit.html"}
{"id": "bb816183208e-0", "text": "langchain_experimental.agents.agent_toolkits.csv.base.create_csv_agent\u00b6\nlangchain_experimental.agents.agent_toolkits.csv.base.create_csv_agent(llm: BaseLanguageModel, path: Union[str, IOBase, List[Union[str, IOBase]]], pandas_kwargs: Optional[dict] = None, **kwargs: Any) \u2192 AgentExecutor[source]\u00b6\nCreate csv agent by loading to a dataframe and using pandas agent.\nExamples using create_csv_agent\u00b6\nCSV", "source": "lang/api.python.langchain.com/en/latest/agents/langchain_experimental.agents.agent_toolkits.csv.base.create_csv_agent.html"}
{"id": "2d35b513ea42-0", "text": "langchain.agents.agent.LLMSingleActionAgent\u00b6\nclass langchain.agents.agent.LLMSingleActionAgent[source]\u00b6\nBases: BaseSingleActionAgent\nBase class for single action agents.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nLLMChain to use for agent.\nparam output_parser: langchain.agents.agent.AgentOutputParser [Required]\u00b6\nOutput parser to use for agent.\nparam stop: List[str] [Required]\u00b6\nList of strings to stop on.\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.LLMSingleActionAgent.html"}
{"id": "2d35b513ea42-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict[source]\u00b6\nReturn dictionary representation of agent.\nclassmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, **kwargs: Any) \u2192 BaseSingleActionAgent\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 Optional[List[str]]\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.LLMSingleActionAgent.html"}
{"id": "2d35b513ea42-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with the observations.\ncallbacks \u2013 Callbacks to run.\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict[source]\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty input_keys: List[str]\u00b6\nReturn the input keys.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.LLMSingleActionAgent.html"}
{"id": "2d35b513ea42-3", "text": "property input_keys: List[str]\u00b6\nReturn the input keys.\nReturns\nList of input keys.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.\nExamples using LLMSingleActionAgent\u00b6\nPlug-and-Plai\nWikibase Agent\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nCustom Agent with PlugIn Retrieval\nCustom agent with tool retrieval", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent.LLMSingleActionAgent.html"}
{"id": "e4567c717eab-0", "text": "langchain.agents.openai_functions_multi_agent.base.OpenAIMultiFunctionsAgent\u00b6\nclass langchain.agents.openai_functions_multi_agent.base.OpenAIMultiFunctionsAgent[source]\u00b6\nBases: BaseMultiActionAgent\nAn Agent driven by OpenAIs function powered API.\nParameters\nllm \u2013 This should be an instance of ChatOpenAI, specifically a model\nthat supports using functions.\ntools \u2013 The tools this agent has access to.\nprompt \u2013 The prompt for this agent, should support agent_scratchpad as one\nof the variables. For an easy way to construct this prompt, use\nOpenAIMultiFunctionsAgent.create_prompt(\u2026)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nparam prompt: langchain.schema.prompt_template.BasePromptTemplate [Required]\u00b6\nparam tools: Sequence[langchain.tools.base.BaseTool] [Required]\u00b6\nasync aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date,\nalong with observations\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_functions_multi_agent.base.OpenAIMultiFunctionsAgent.html"}
{"id": "e4567c717eab-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\nclassmethod create_prompt(system_message: Optional[SystemMessage] = SystemMessage(content='You are a helpful AI assistant.'), extra_prompt_messages: Optional[List[BaseMessagePromptTemplate]] = None) \u2192 BasePromptTemplate[source]\u00b6\nCreate prompt for this agent.\nParameters\nsystem_message \u2013 Message to use as the system message that will be the\nfirst in the prompt.\nextra_prompt_messages \u2013 Prompt messages that will be placed between the\nsystem message and the new human input.\nReturns\nA prompt template to pass into this agent.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of agent.\nclassmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, extra_prompt_messages: Optional[List[BaseMessagePromptTemplate]] = None, system_message: Optional[SystemMessage] = SystemMessage(content='You are a helpful AI assistant.'), **kwargs: Any) \u2192 BaseMultiActionAgent[source]\u00b6\nConstruct an agent from an LLM and tools.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_functions_multi_agent.base.OpenAIMultiFunctionsAgent.html"}
{"id": "e4567c717eab-2", "text": "Construct an agent from an LLM and tools.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_allowed_tools() \u2192 List[str][source]\u00b6\nGet allowed tools.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6\nGiven input, decided what to do.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date, along with observations\n**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_functions_multi_agent.base.OpenAIMultiFunctionsAgent.html"}
{"id": "e4567c717eab-3", "text": "**kwargs \u2013 User inputs.\nReturns\nAction specifying what tool to use.\nreturn_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) \u2192 AgentFinish\u00b6\nReturn response when agent has been stopped due to max iterations.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the agent.\nParameters\nfile_path \u2013 Path to file to save the agent to.\nExample:\n.. code-block:: python\n# If working with agent executor\nagent.agent.save(file_path=\u201dpath/agent.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\ntool_run_logging_kwargs() \u2192 Dict\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty functions: List[dict]\u00b6\nproperty input_keys: List[str]\u00b6\nGet input keys. Input refers to user input here.\nproperty return_values: List[str]\u00b6\nReturn values of the agent.", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.openai_functions_multi_agent.base.OpenAIMultiFunctionsAgent.html"}
{"id": "6bb7e65c3724-0", "text": "langchain.agents.agent_toolkits.nla.toolkit.NLAToolkit\u00b6\nclass langchain.agents.agent_toolkits.nla.toolkit.NLAToolkit[source]\u00b6\nBases: BaseToolkit\nNatural Language API Toolkit.\nSecurity Note: This toolkit creates tools that enable making callsto an Open API compliant API.\nThe tools created by this toolkit may be able to make GET, POST,\nPATCH, PUT, DELETE requests to any of the exposed endpoints on\nthe API.\nControl access to who can use this toolkit.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam nla_tools: Sequence[langchain.agents.agent_toolkits.nla.tool.NLATool] [Required]\u00b6\nList of API Endpoint Tools.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.nla.toolkit.NLAToolkit.html"}
{"id": "6bb7e65c3724-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_llm_and_ai_plugin(llm: BaseLanguageModel, ai_plugin: AIPlugin, requests: Optional[Requests] = None, verbose: bool = False, **kwargs: Any) \u2192 NLAToolkit[source]\u00b6\nInstantiate the toolkit from an OpenAPI Spec URL\nclassmethod from_llm_and_ai_plugin_url(llm: BaseLanguageModel, ai_plugin_url: str, requests: Optional[Requests] = None, verbose: bool = False, **kwargs: Any) \u2192 NLAToolkit[source]\u00b6\nInstantiate the toolkit from an OpenAPI Spec URL\nclassmethod from_llm_and_spec(llm: BaseLanguageModel, spec: OpenAPISpec, requests: Optional[Requests] = None, verbose: bool = False, **kwargs: Any) \u2192 NLAToolkit[source]\u00b6\nInstantiate the toolkit by creating tools for each operation.\nclassmethod from_llm_and_url(llm: BaseLanguageModel, open_api_url: str, requests: Optional[Requests] = None, verbose: bool = False, **kwargs: Any) \u2192 NLAToolkit[source]\u00b6\nInstantiate the toolkit from an OpenAPI Spec URL\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_tools() \u2192 List[BaseTool][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.nla.toolkit.NLAToolkit.html"}
{"id": "6bb7e65c3724-2", "text": "get_tools() \u2192 List[BaseTool][source]\u00b6\nGet the tools for all the API operations.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using NLAToolkit\u00b6\nNatural Language APIs\nPlug-and-Plai\nCustom Agent with PlugIn Retrieval", "source": "lang/api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.nla.toolkit.NLAToolkit.html"}
{"id": "a664880ffa8b-0", "text": "langchain_experimental.agents.agent_toolkits.python.base.create_python_agent\u00b6\nlangchain_experimental.agents.agent_toolkits.python.base.create_python_agent(llm: BaseLanguageModel, tool: PythonREPLTool, agent_type: AgentType = AgentType.ZERO_SHOT_REACT_DESCRIPTION, callback_manager: Optional[BaseCallbackManager] = None, verbose: bool = False, prefix: str = 'You are an agent designed to write and execute python code to answer questions.\\nYou have access to a python REPL, which you can use to execute python code.\\nIf you get an error, debug your code and try again.\\nOnly use the output of your code to answer the question. \\nYou might know the answer without running any code, but you should still run the code to get the answer.\\nIf it does not seem like you can write code to answer the question, just return \"I don\\'t know\" as the answer.\\n', agent_executor_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Dict[str, Any]) \u2192 AgentExecutor[source]\u00b6\nConstruct a python agent from an LLM and tool.\nExamples using create_python_agent\u00b6\nPython", "source": "lang/api.python.langchain.com/en/latest/agents/langchain_experimental.agents.agent_toolkits.python.base.create_python_agent.html"}
{"id": "5bced4ededf5-0", "text": "langchain_experimental.llm_bash.prompt.BashOutputParser\u00b6\nclass langchain_experimental.llm_bash.prompt.BashOutputParser[source]\u00b6\nBases: BaseOutputParser\nParser for bash output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.prompt.BashOutputParser.html"}
{"id": "5bced4ededf5-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.prompt.BashOutputParser.html"}
{"id": "5bced4ededf5-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.prompt.BashOutputParser.html"}
{"id": "5bced4ededf5-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nstatic get_code_blocks(t: str) \u2192 List[str][source]\u00b6\nGet multiple code blocks from the LLM result.\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.prompt.BashOutputParser.html"}
{"id": "5bced4ededf5-4", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.prompt.BashOutputParser.html"}
{"id": "5bced4ededf5-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 List[str][source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.prompt.BashOutputParser.html"}
{"id": "5bced4ededf5-6", "text": "prompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.prompt.BashOutputParser.html"}
{"id": "5bced4ededf5-7", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.prompt.BashOutputParser.html"}
{"id": "5bced4ededf5-8", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using BashOutputParser\u00b6\nBash chain", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.prompt.BashOutputParser.html"}
{"id": "6df6d662981c-0", "text": "langchain_experimental.llm_bash.base.LLMBashChain\u00b6\nclass langchain_experimental.llm_bash.base.LLMBashChain[source]\u00b6\nBases: Chain\nChain that interprets a prompt and executes bash operations.\nExample\nfrom langchain.chains import LLMBashChain\nfrom langchain.llms import OpenAI\nllm_bash = LLMBashChain.from_llm(OpenAI())\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm: Optional[BaseLanguageModel] = None\u00b6\n[Deprecated] LLM wrapper to use.\nparam llm_chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam prompt: BasePromptTemplate = PromptTemplate(input_variables=['question'], output_parser=BashOutputParser(), template='If someone asks you to perform a task, your job is to come up with a series of bash commands that will perform the task. There is no need to put \"#!/bin/bash\" in your answer. Make sure to reason step by step, using this format:\\n\\nQuestion: \"copy the files in the directory named \\'target\\' into a new directory at the same level as target called \\'myNewDirectory\\'\"\\n\\nI need to take the following actions:\\n- List all files in the directory\\n- Create a new directory\\n- Copy the files from the first directory into the second directory\\n```bash\\nls\\nmkdir myNewDirectory\\ncp -r target/* myNewDirectory\\n```\\n\\nThat is the format. Begin!\\n\\nQuestion: {question}')\u00b6\n[Deprecated]\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-2", "text": "accessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-5", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-6", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-8", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, prompt: BasePromptTemplate = PromptTemplate(input_variables=['question'], output_parser=BashOutputParser(), template='If someone asks you to perform a task, your job is to come up with a series of bash commands that will perform the task. There is no need to put \"#!/bin/bash\" in your answer. Make sure to reason step by step, using this format:\\n\\nQuestion: \"copy the files in the directory named \\'target\\' into a new directory at the same level as target called \\'myNewDirectory\\'\"\\n\\nI need to take the following actions:\\n- List all files in the directory\\n- Create a new directory\\n- Copy the files from the first directory into the second directory\\n```bash\\nls\\nmkdir myNewDirectory\\ncp -r target/* myNewDirectory\\n```\\n\\nThat is the format. Begin!\\n\\nQuestion: {question}'), **kwargs: Any) \u2192 LLMBashChain[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-9", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-11", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-12", "text": "these runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-13", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-14", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "6df6d662981c-15", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using LLMBashChain\u00b6\nBash chain", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.base.LLMBashChain.html"}
{"id": "f6331a66746e-0", "text": "langchain_experimental.llm_bash.bash.BashProcess\u00b6\nclass langchain_experimental.llm_bash.bash.BashProcess(strip_newlines: bool = False, return_err_output: bool = False, persistent: bool = False)[source]\u00b6\nWrapper class for starting subprocesses.\nUses the python built-in subprocesses.run()\nPersistent processes are not available\non Windows systems, as pexpect makes use of\nUnix pseudoterminals (ptys). MacOS and Linux\nare okay.\nExample\nfrom langchain.utilities.bash import BashProcess\nbash = BashProcess(\n    strip_newlines = False,\n    return_err_output = False,\n    persistent = False\n)\nbash.run('echo 'hello world'')\nInitializes with default settings\nAttributes\npersistent\nWhether or not to spawn a persistent session NOTE: Unavailable for Windows environments\nreturn_err_output\nWhether or not to return the output of a failed command, or just the error message and stacktrace\nstrip_newlines\nWhether or not to run .strip() on the output\nMethods\n__init__([strip_newlines,\u00a0...])\nInitializes with default settings\nprocess_output(output,\u00a0command)\nUses regex to remove the command from the output\nrun(commands)\nRun commands in either an existing persistent subprocess or on in a new subprocess environment.\n__init__(strip_newlines: bool = False, return_err_output: bool = False, persistent: bool = False)[source]\u00b6\nInitializes with default settings\nprocess_output(output: str, command: str) \u2192 str[source]\u00b6\nUses regex to remove the command from the output\nParameters\noutput \u2013 a process\u2019 output string\ncommand \u2013 the executed command\nrun(commands: Union[str, List[str]]) \u2192 str[source]\u00b6\nRun commands in either an existing persistent\nsubprocess or on in a new subprocess environment.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.bash.BashProcess.html"}
{"id": "f6331a66746e-1", "text": "subprocess or on in a new subprocess environment.\nParameters\ncommands (List[str]) \u2013 a list of commands to\nexecute in the session\nExamples using BashProcess\u00b6\nBash chain", "source": "lang/api.python.langchain.com/en/latest/llm_bash/langchain_experimental.llm_bash.bash.BashProcess.html"}
{"id": "552ecd753d15-0", "text": "langchain.model_laboratory.ModelLaboratory\u00b6\nclass langchain.model_laboratory.ModelLaboratory(chains: Sequence[Chain], names: Optional[List[str]] = None)[source]\u00b6\nExperiment with different models.\nInitialize with chains to experiment with.\nParameters\nchains \u2013 list of chains to experiment with.\nMethods\n__init__(chains[,\u00a0names])\nInitialize with chains to experiment with.\ncompare(text)\nCompare model outputs on an input text.\nfrom_llms(llms[,\u00a0prompt])\nInitialize with LLMs to experiment with and optional prompt.\n__init__(chains: Sequence[Chain], names: Optional[List[str]] = None)[source]\u00b6\nInitialize with chains to experiment with.\nParameters\nchains \u2013 list of chains to experiment with.\ncompare(text: str) \u2192 None[source]\u00b6\nCompare model outputs on an input text.\nIf a prompt was provided with starting the laboratory, then this text will be\nfed into the prompt. If no prompt was provided, then the input text is the\nentire prompt.\nParameters\ntext \u2013 input text to run all models on.\nclassmethod from_llms(llms: List[BaseLLM], prompt: Optional[PromptTemplate] = None) \u2192 ModelLaboratory[source]\u00b6\nInitialize with LLMs to experiment with and optional prompt.\nParameters\nllms \u2013 list of LLMs to experiment with\nprompt \u2013 Optional prompt to use to prompt the LLMs. Defaults to None.\nIf a prompt was provided, it should only have one input variable.\nExamples using ModelLaboratory\u00b6\nManifest\nModel comparison", "source": "lang/api.python.langchain.com/en/latest/model_laboratory/langchain.model_laboratory.ModelLaboratory.html"}
{"id": "109d6782666e-0", "text": "langchain.callbacks.infino_callback.import_infino\u00b6\nlangchain.callbacks.infino_callback.import_infino() \u2192 Any[source]\u00b6\nImport the infino client.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.infino_callback.import_infino.html"}
{"id": "da1b0848b940-0", "text": "langchain.callbacks.aim_callback.BaseMetadataCallbackHandler\u00b6\nclass langchain.callbacks.aim_callback.BaseMetadataCallbackHandler[source]\u00b6\nThis class handles the metadata and associated function states for callbacks.\nstep\u00b6\nThe current step.\nType\nint\nstarts\u00b6\nThe number of times the start method has been called.\nType\nint\nends\u00b6\nThe number of times the end method has been called.\nType\nint\nerrors\u00b6\nThe number of times the error method has been called.\nType\nint\ntext_ctr\u00b6\nThe number of times the text method has been called.\nType\nint\nignore_llm_\u00b6\nWhether to ignore llm callbacks.\nType\nbool\nignore_chain_\u00b6\nWhether to ignore chain callbacks.\nType\nbool\nignore_agent_\u00b6\nWhether to ignore agent callbacks.\nType\nbool\nignore_retriever_\u00b6\nWhether to ignore retriever callbacks.\nType\nbool\nalways_verbose_\u00b6\nWhether to always be verbose.\nType\nbool\nchain_starts\u00b6\nThe number of times the chain start method has been called.\nType\nint\nchain_ends\u00b6\nThe number of times the chain end method has been called.\nType\nint\nllm_starts\u00b6\nThe number of times the llm start method has been called.\nType\nint\nllm_ends\u00b6\nThe number of times the llm end method has been called.\nType\nint\nllm_streams\u00b6\nThe number of times the text method has been called.\nType\nint\ntool_starts\u00b6\nThe number of times the tool start method has been called.\nType\nint\ntool_ends\u00b6\nThe number of times the tool end method has been called.\nType\nint\nagent_ends\u00b6\nThe number of times the agent end method has been called.\nType\nint\nAttributes\nalways_verbose", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.aim_callback.BaseMetadataCallbackHandler.html"}
{"id": "da1b0848b940-1", "text": "Type\nint\nAttributes\nalways_verbose\nWhether to call verbose callbacks even if verbose is False.\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nMethods\n__init__()\nget_custom_callback_meta()\nreset_callback_meta()\nReset the callback metadata.\n__init__() \u2192 None[source]\u00b6\nget_custom_callback_meta() \u2192 Dict[str, Any][source]\u00b6\nreset_callback_meta() \u2192 None[source]\u00b6\nReset the callback metadata.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.aim_callback.BaseMetadataCallbackHandler.html"}
{"id": "55f477ad1fa8-0", "text": "langchain.callbacks.streaming_stdout_final_only.FinalStreamingStdOutCallbackHandler\u00b6\nclass langchain.callbacks.streaming_stdout_final_only.FinalStreamingStdOutCallbackHandler(*, answer_prefix_tokens: Optional[List[str]] = None, strip_tokens: bool = True, stream_prefix: bool = False)[source]\u00b6\nCallback handler for streaming in agents.\nOnly works with agents using LLMs that support streaming.\nOnly the final output of the agent will be streamed.\nInstantiate FinalStreamingStdOutCallbackHandler.\nParameters\nanswer_prefix_tokens \u2013 Token sequence that prefixes the answer.\nDefault is [\u201cFinal\u201d, \u201cAnswer\u201d, \u201c:\u201d]\nstrip_tokens \u2013 Ignore white spaces and new lines when comparing\nanswer_prefix_tokens to last tokens? (to determine if answer has been\nreached)\nstream_prefix \u2013 Should answer prefix itself also be streamed?\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(*[,\u00a0answer_prefix_tokens,\u00a0...])\nInstantiate FinalStreamingStdOutCallbackHandler.\nappend_to_last_tokens(token)\ncheck_if_answer_reached()\non_agent_action(action,\u00a0**kwargs)\nRun on agent action.\non_agent_finish(finish,\u00a0**kwargs)\nRun on agent end.\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends running.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0...)\nRun when LLM starts running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_stdout_final_only.FinalStreamingStdOutCallbackHandler.html"}
{"id": "55f477ad1fa8-1", "text": "Run when LLM starts running.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0**kwargs)\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun on arbitrary text.\non_tool_end(output,\u00a0**kwargs)\nRun when tool ends running.\non_tool_error(error,\u00a0**kwargs)\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nRun when tool starts running.\n__init__(*, answer_prefix_tokens: Optional[List[str]] = None, strip_tokens: bool = True, stream_prefix: bool = False) \u2192 None[source]\u00b6\nInstantiate FinalStreamingStdOutCallbackHandler.\nParameters\nanswer_prefix_tokens \u2013 Token sequence that prefixes the answer.\nDefault is [\u201cFinal\u201d, \u201cAnswer\u201d, \u201c:\u201d]\nstrip_tokens \u2013 Ignore white spaces and new lines when comparing\nanswer_prefix_tokens to last tokens? (to determine if answer has been\nreached)\nstream_prefix \u2013 Should answer prefix itself also be streamed?\nappend_to_last_tokens(token: str) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_stdout_final_only.FinalStreamingStdOutCallbackHandler.html"}
{"id": "55f477ad1fa8-2", "text": "append_to_last_tokens(token: str) \u2192 None[source]\u00b6\ncheck_if_answer_reached() \u2192 bool[source]\u00b6\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], **kwargs: Any) \u2192 None\u00b6\nRun when LLM starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun on new LLM token. Only available when streaming is enabled.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts running.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_stdout_final_only.FinalStreamingStdOutCallbackHandler.html"}
{"id": "55f477ad1fa8-3", "text": "Run when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None\u00b6\nRun on arbitrary text.\non_tool_end(output: str, **kwargs: Any) \u2192 None\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None\u00b6\nRun when tool starts running.\nExamples using FinalStreamingStdOutCallbackHandler\u00b6\nStreaming final agent output", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_stdout_final_only.FinalStreamingStdOutCallbackHandler.html"}
{"id": "a4b92d087707-0", "text": "langchain.callbacks.context_callback.ContextCallbackHandler\u00b6\nclass langchain.callbacks.context_callback.ContextCallbackHandler(token: str = '', verbose: bool = False, **kwargs: Any)[source]\u00b6\nCallback Handler that records transcripts to the Context service.\n(https://context.ai).\nKeyword Arguments\ntoken (optional) \u2013 The token with which to authenticate requests to Context.\nVisit https://with.context.ai/settings to generate a token.\nIf not provided, the value of the CONTEXT_TOKEN environment\nvariable will be used.\nRaises\nImportError \u2013 if the context-python package is not installed.\nChat Example:>>> from langchain.llms import ChatOpenAI\n>>> from langchain.callbacks import ContextCallbackHandler\n>>> context_callback = ContextCallbackHandler(\n...     token=\"<CONTEXT_TOKEN_HERE>\",\n... )\n>>> chat = ChatOpenAI(\n...     temperature=0,\n...     headers={\"user_id\": \"123\"},\n...     callbacks=[context_callback],\n...     openai_api_key=\"API_KEY_HERE\",\n... )\n>>> messages = [\n...     SystemMessage(content=\"You translate English to French.\"),\n...     HumanMessage(content=\"I love programming with LangChain.\"),\n... ]\n>>> chat(messages)\nChain Example:>>> from langchain.chains import LLMChain\n>>> from langchain.chat_models import ChatOpenAI\n>>> from langchain.callbacks import ContextCallbackHandler\n>>> context_callback = ContextCallbackHandler(\n...     token=\"<CONTEXT_TOKEN_HERE>\",\n... )\n>>> human_message_prompt = HumanMessagePromptTemplate(\n...     prompt=PromptTemplate(\n...         template=\"What is a good name for a company that makes {product}?\",\n...         input_variables=[\"product\"],\n...    ),\n... )\n>>> chat_prompt_template = ChatPromptTemplate.from_messages(\n...   [human_message_prompt]\n... )\n>>> callback = ContextCallbackHandler(token)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.context_callback.ContextCallbackHandler.html"}
{"id": "a4b92d087707-1", "text": "...   [human_message_prompt]\n... )\n>>> callback = ContextCallbackHandler(token)\n>>> # Note: the same callback object must be shared between the\n...   LLM and the chain.\n>>> chat = ChatOpenAI(temperature=0.9, callbacks=[callback])\n>>> chain = LLMChain(\n...   llm=chat,\n...   prompt=chat_prompt_template,\n...   callbacks=[callback]\n... )\n>>> chain.run(\"colorful socks\")\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([token,\u00a0verbose])\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nRun when chain starts.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when the chat model is started.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends.\non_llm_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM errors.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.context_callback.ContextCallbackHandler.html"}
{"id": "a4b92d087707-2", "text": "Run on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool ends running.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\n__init__(token: str = '', verbose: bool = False, **kwargs: Any) \u2192 None[source]\u00b6\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends.\non_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.context_callback.ContextCallbackHandler.html"}
{"id": "a4b92d087707-3", "text": "Run when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain starts.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when the chat model is started.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends.\non_llm_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on new LLM token. Only available when streaming is enabled.\nParameters\ntoken (str) \u2013 The new token.\nchunk (GenerationChunk | ChatGenerationChunk) \u2013 The new generated chunk,\ninformation. (containing content and other) \u2013 \non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM starts running.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.context_callback.ContextCallbackHandler.html"}
{"id": "a4b92d087707-4", "text": "Run when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool starts running.\nExamples using ContextCallbackHandler\u00b6\nContext", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.context_callback.ContextCallbackHandler.html"}
{"id": "f3bc8681d60a-0", "text": "langchain.callbacks.wandb_callback.import_wandb\u00b6\nlangchain.callbacks.wandb_callback.import_wandb() \u2192 Any[source]\u00b6\nImport the wandb python package and raise an error if it is not installed.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.wandb_callback.import_wandb.html"}
{"id": "572631c27259-0", "text": "langchain.callbacks.aim_callback.AimCallbackHandler\u00b6\nclass langchain.callbacks.aim_callback.AimCallbackHandler(repo: Optional[str] = None, experiment_name: Optional[str] = None, system_tracking_interval: Optional[int] = 10, log_system_params: bool = True)[source]\u00b6\nCallback Handler that logs to Aim.\nParameters\nrepo (str, optional) \u2013 Aim repository path or Repo object to which\nRun object is bound. If skipped, default Repo is used.\nexperiment_name (str, optional) \u2013 Sets Run\u2019s experiment property.\n\u2018default\u2019 if not specified. Can be used later to query runs/sequences.\nsystem_tracking_interval (int, optional) \u2013 Sets the tracking interval\nin seconds for system usage metrics (CPU, Memory, etc.). Set to None\nto disable system metrics tracking.\nlog_system_params (bool, optional) \u2013 Enable/Disable logging of system\nparams such as installed packages, git info, environment variables, etc.\nThis handler will utilize the associated callback method called and formats\nthe input of each callback function with metadata regarding the state of LLM run\nand then logs the response to Aim.\nInitialize callback handler.\nAttributes\nalways_verbose\nWhether to call verbose callbacks even if verbose is False.\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([repo,\u00a0experiment_name,\u00a0...])\nInitialize callback handler.\nflush_tracker([repo,\u00a0experiment_name,\u00a0...])\nFlush the tracker and reset the session.\nget_custom_callback_meta()\non_agent_action(action,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.aim_callback.AimCallbackHandler.html"}
{"id": "572631c27259-1", "text": "get_custom_callback_meta()\non_agent_action(action,\u00a0**kwargs)\nRun on agent action.\non_agent_finish(finish,\u00a0**kwargs)\nRun when agent ends running.\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends running.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0**kwargs)\nRun when LLM generates a new token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when agent is ending.\non_tool_end(output,\u00a0**kwargs)\nRun when tool ends running.\non_tool_error(error,\u00a0**kwargs)\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nRun when tool starts running.\nreset_callback_meta()\nReset the callback metadata.\nsetup(**kwargs)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.aim_callback.AimCallbackHandler.html"}
{"id": "572631c27259-2", "text": "reset_callback_meta()\nReset the callback metadata.\nsetup(**kwargs)\n__init__(repo: Optional[str] = None, experiment_name: Optional[str] = None, system_tracking_interval: Optional[int] = 10, log_system_params: bool = True) \u2192 None[source]\u00b6\nInitialize callback handler.\nflush_tracker(repo: Optional[str] = None, experiment_name: Optional[str] = None, system_tracking_interval: Optional[int] = 10, log_system_params: bool = True, langchain_asset: Any = None, reset: bool = True, finish: bool = False) \u2192 None[source]\u00b6\nFlush the tracker and reset the session.\nParameters\nrepo (str, optional) \u2013 Aim repository path or Repo object to which\nRun object is bound. If skipped, default Repo is used.\nexperiment_name (str, optional) \u2013 Sets Run\u2019s experiment property.\n\u2018default\u2019 if not specified. Can be used later to query runs/sequences.\nsystem_tracking_interval (int, optional) \u2013 Sets the tracking interval\nin seconds for system usage metrics (CPU, Memory, etc.). Set to None\nto disable system metrics tracking.\nlog_system_params (bool, optional) \u2013 Enable/Disable logging of system\nparams such as installed packages, git info, environment variables, etc.\nlangchain_asset \u2013 The langchain asset to save.\nreset \u2013 Whether to reset the session.\nfinish \u2013 Whether to finish the run.\nReturns \u2013 None\nget_custom_callback_meta() \u2192 Dict[str, Any]\u00b6\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent ends running.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.aim_callback.AimCallbackHandler.html"}
{"id": "572631c27259-3", "text": "Run when chain ends running.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM generates a new token.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.aim_callback.AimCallbackHandler.html"}
{"id": "572631c27259-4", "text": "Run when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent is ending.\non_tool_end(output: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool starts running.\nreset_callback_meta() \u2192 None\u00b6\nReset the callback metadata.\nsetup(**kwargs: Any) \u2192 None[source]\u00b6\nExamples using AimCallbackHandler\u00b6\nAim", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.aim_callback.AimCallbackHandler.html"}
{"id": "8c4d3a6397f3-0", "text": "langchain.callbacks.infino_callback.InfinoCallbackHandler\u00b6\nclass langchain.callbacks.infino_callback.InfinoCallbackHandler(model_id: Optional[str] = None, model_version: Optional[str] = None, verbose: bool = False)[source]\u00b6\nCallback Handler that logs to Infino.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([model_id,\u00a0model_version,\u00a0verbose])\non_agent_action(action,\u00a0**kwargs)\nDo nothing when agent takes a specific action.\non_agent_finish(finish,\u00a0**kwargs)\nDo nothing.\non_chain_end(outputs,\u00a0**kwargs)\nDo nothing when LLM chain ends.\non_chain_error(error,\u00a0**kwargs)\nNeed to log the error.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nDo nothing when LLM chain starts.\non_chat_model_start(serialized,\u00a0messages,\u00a0...)\nRun when LLM starts running.\non_llm_end(response,\u00a0**kwargs)\nLog the latency, error, token usage, and response to Infino.\non_llm_error(error,\u00a0**kwargs)\nSet the error flag.\non_llm_new_token(token,\u00a0**kwargs)\nDo nothing when a new token is generated.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nLog the prompts to Infino, and set start time and error flag.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.infino_callback.InfinoCallbackHandler.html"}
{"id": "8c4d3a6397f3-1", "text": "Run when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nDo nothing.\non_tool_end(output[,\u00a0observation_prefix,\u00a0...])\nDo nothing when tool ends.\non_tool_error(error,\u00a0**kwargs)\nDo nothing when tool outputs an error.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nDo nothing when tool starts.\n__init__(model_id: Optional[str] = None, model_version: Optional[str] = None, verbose: bool = False) \u2192 None[source]\u00b6\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nDo nothing when agent takes a specific action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when LLM chain ends.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nNeed to log the error.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when LLM chain starts.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.infino_callback.InfinoCallbackHandler.html"}
{"id": "8c4d3a6397f3-2", "text": "Log the latency, error, token usage, and response to Infino.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nSet the error flag.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when a new token is generated.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nLog the prompts to Infino, and set start time and error flag.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing.\non_tool_end(output: str, observation_prefix: Optional[str] = None, llm_prefix: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool ends.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.infino_callback.InfinoCallbackHandler.html"}
{"id": "8c4d3a6397f3-3", "text": "Do nothing when tool ends.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool outputs an error.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool starts.\nExamples using InfinoCallbackHandler\u00b6\nInfino", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.infino_callback.InfinoCallbackHandler.html"}
{"id": "36bf112c7999-0", "text": "langchain.callbacks.utils.import_textstat\u00b6\nlangchain.callbacks.utils.import_textstat() \u2192 Any[source]\u00b6\nImport the textstat python package and raise an error if it is not installed.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.utils.import_textstat.html"}
{"id": "41ba8b8c5f32-0", "text": "langchain.callbacks.mlflow_callback.MlflowLogger\u00b6\nclass langchain.callbacks.mlflow_callback.MlflowLogger(**kwargs: Any)[source]\u00b6\nCallback Handler that logs metrics and artifacts to mlflow server.\nParameters\nname (str) \u2013 Name of the run.\nexperiment (str) \u2013 Name of the experiment.\ntags (dict) \u2013 Tags to be attached for the run.\ntracking_uri (str) \u2013 MLflow tracking server uri.\nThis handler implements the helper functions to initialize,\nlog metrics and artifacts to the mlflow server.\nMethods\n__init__(**kwargs)\nartifact(path)\nTo upload the file from given path as artifact.\nfinish_run()\nTo finish the run.\nhtml(html,\u00a0filename)\nTo log the input html string as html file artifact.\njsonf(data,\u00a0filename)\nTo log the input data as json file artifact.\nlangchain_artifact(chain)\nmetric(key,\u00a0value)\nTo log metric to mlflow server.\nmetrics(data[,\u00a0step])\nTo log all metrics in the input dict.\nstart_run(name,\u00a0tags)\nTo start a new run, auto generates the random suffix for name\ntable(name,\u00a0dataframe)\nTo log the input pandas dataframe as a html table\ntext(text,\u00a0filename)\nTo log the input text as text file artifact.\n__init__(**kwargs: Any)[source]\u00b6\nartifact(path: str) \u2192 None[source]\u00b6\nTo upload the file from given path as artifact.\nfinish_run() \u2192 None[source]\u00b6\nTo finish the run.\nhtml(html: str, filename: str) \u2192 None[source]\u00b6\nTo log the input html string as html file artifact.\njsonf(data: Dict[str, Any], filename: str) \u2192 None[source]\u00b6\nTo log the input data as json file artifact.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.mlflow_callback.MlflowLogger.html"}
{"id": "41ba8b8c5f32-1", "text": "To log the input data as json file artifact.\nlangchain_artifact(chain: Any) \u2192 None[source]\u00b6\nmetric(key: str, value: float) \u2192 None[source]\u00b6\nTo log metric to mlflow server.\nmetrics(data: Union[Dict[str, float], Dict[str, int]], step: Optional[int] = 0) \u2192 None[source]\u00b6\nTo log all metrics in the input dict.\nstart_run(name: str, tags: Dict[str, str]) \u2192 None[source]\u00b6\nTo start a new run, auto generates the random suffix for name\ntable(name: str, dataframe) \u2192 None[source]\u00b6\nTo log the input pandas dataframe as a html table\ntext(text: str, filename: str) \u2192 None[source]\u00b6\nTo log the input text as text file artifact.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.mlflow_callback.MlflowLogger.html"}
{"id": "e425c76755f6-0", "text": "langchain.callbacks.streamlit.mutable_expander.MutableExpander\u00b6\nclass langchain.callbacks.streamlit.mutable_expander.MutableExpander(parent_container: DeltaGenerator, label: str, expanded: bool)[source]\u00b6\nA Streamlit expander that can be renamed and dynamically expanded/collapsed.\nCreate a new MutableExpander.\nParameters\nparent_container \u2013 The st.container that the expander will be created inside.\nThe expander transparently deletes and recreates its underlying\nst.expander instance when its label changes, and it uses\nparent_container to ensure it recreates this underlying expander in the\nsame location onscreen.\nlabel \u2013 The expander\u2019s initial label.\nexpanded \u2013 The expander\u2019s initial expanded value.\nAttributes\nexpanded\nTrue if the expander was created with expanded=True.\nlabel\nThe expander's label string.\nMethods\n__init__(parent_container,\u00a0label,\u00a0expanded)\nCreate a new MutableExpander.\nappend_copy(other)\nAppend a copy of another MutableExpander's children to this MutableExpander.\nclear()\nRemove the container and its contents entirely.\nexception(exception,\u00a0*[,\u00a0index])\nAdd an Exception element to the container and return its index.\nmarkdown(body[,\u00a0unsafe_allow_html,\u00a0help,\u00a0index])\nAdd a Markdown element to the container and return its index.\nupdate(*[,\u00a0new_label,\u00a0new_expanded])\nChange the expander's label and expanded state\n__init__(parent_container: DeltaGenerator, label: str, expanded: bool)[source]\u00b6\nCreate a new MutableExpander.\nParameters\nparent_container \u2013 The st.container that the expander will be created inside.\nThe expander transparently deletes and recreates its underlying\nst.expander instance when its label changes, and it uses\nparent_container to ensure it recreates this underlying expander in the\nsame location onscreen.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.mutable_expander.MutableExpander.html"}
{"id": "e425c76755f6-1", "text": "parent_container to ensure it recreates this underlying expander in the\nsame location onscreen.\nlabel \u2013 The expander\u2019s initial label.\nexpanded \u2013 The expander\u2019s initial expanded value.\nappend_copy(other: MutableExpander) \u2192 None[source]\u00b6\nAppend a copy of another MutableExpander\u2019s children to this\nMutableExpander.\nclear() \u2192 None[source]\u00b6\nRemove the container and its contents entirely. A cleared container can\u2019t\nbe reused.\nexception(exception: BaseException, *, index: Optional[int] = None) \u2192 int[source]\u00b6\nAdd an Exception element to the container and return its index.\nmarkdown(body: SupportsStr, unsafe_allow_html: bool = False, *, help: Optional[str] = None, index: Optional[int] = None) \u2192 int[source]\u00b6\nAdd a Markdown element to the container and return its index.\nupdate(*, new_label: Optional[str] = None, new_expanded: Optional[bool] = None) \u2192 None[source]\u00b6\nChange the expander\u2019s label and expanded state", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.mutable_expander.MutableExpander.html"}
{"id": "2f5fbd8ab244-0", "text": "langchain.callbacks.openai_info.get_openai_token_cost_for_model\u00b6\nlangchain.callbacks.openai_info.get_openai_token_cost_for_model(model_name: str, num_tokens: int, is_completion: bool = False) \u2192 float[source]\u00b6\nGet the cost in USD for a given model and number of tokens.\nParameters\nmodel_name \u2013 Name of the model\nnum_tokens \u2013 Number of tokens.\nis_completion \u2013 Whether the model is used for completion or not.\nDefaults to False.\nReturns\nCost in USD.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.openai_info.get_openai_token_cost_for_model.html"}
{"id": "a3333c103a0a-0", "text": "langchain.callbacks.mlflow_callback.import_mlflow\u00b6\nlangchain.callbacks.mlflow_callback.import_mlflow() \u2192 Any[source]\u00b6\nImport the mlflow python package and raise an error if it is not installed.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.mlflow_callback.import_mlflow.html"}
{"id": "1ee38df92f76-0", "text": "langchain.callbacks.streaming_stdout.StreamingStdOutCallbackHandler\u00b6\nclass langchain.callbacks.streaming_stdout.StreamingStdOutCallbackHandler[source]\u00b6\nCallback handler for streaming. Only works with LLMs that support streaming.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__()\non_agent_action(action,\u00a0**kwargs)\nRun on agent action.\non_agent_finish(finish,\u00a0**kwargs)\nRun on agent end.\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends running.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0...)\nRun when LLM starts running.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0**kwargs)\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_stdout.StreamingStdOutCallbackHandler.html"}
{"id": "1ee38df92f76-1", "text": "Run when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun on arbitrary text.\non_tool_end(output,\u00a0**kwargs)\nRun when tool ends running.\non_tool_error(error,\u00a0**kwargs)\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nRun when tool starts running.\n__init__()\u00b6\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun on new LLM token. Only available when streaming is enabled.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_stdout.StreamingStdOutCallbackHandler.html"}
{"id": "1ee38df92f76-2", "text": "Run on new LLM token. Only available when streaming is enabled.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts running.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun on arbitrary text.\non_tool_end(output: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool starts running.\nExamples using StreamingStdOutCallbackHandler\u00b6\nAnthropic\n\ud83d\ude85 LiteLLM\nOllama\nGPT4All\nArthur", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_stdout.StreamingStdOutCallbackHandler.html"}
{"id": "1ee38df92f76-3", "text": "\ud83d\ude85 LiteLLM\nOllama\nGPT4All\nArthur\nChat Over Documents with Vectara\nTextGen\nLlama.cpp\nTitan Takeoff\nEden AI\nC Transformers\nHuggingface TextGen Inference\nReplicate\nRun LLMs locally\nSet env var OPENAI_API_KEY or load from a .env file\nUse local LLMs\nWebResearchRetriever", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_stdout.StreamingStdOutCallbackHandler.html"}
{"id": "583fb4b1eef5-0", "text": "langchain.callbacks.utils.BaseMetadataCallbackHandler\u00b6\nclass langchain.callbacks.utils.BaseMetadataCallbackHandler[source]\u00b6\nThis class handles the metadata and associated function states for callbacks.\nstep\u00b6\nThe current step.\nType\nint\nstarts\u00b6\nThe number of times the start method has been called.\nType\nint\nends\u00b6\nThe number of times the end method has been called.\nType\nint\nerrors\u00b6\nThe number of times the error method has been called.\nType\nint\ntext_ctr\u00b6\nThe number of times the text method has been called.\nType\nint\nignore_llm_\u00b6\nWhether to ignore llm callbacks.\nType\nbool\nignore_chain_\u00b6\nWhether to ignore chain callbacks.\nType\nbool\nignore_agent_\u00b6\nWhether to ignore agent callbacks.\nType\nbool\nignore_retriever_\u00b6\nWhether to ignore retriever callbacks.\nType\nbool\nalways_verbose_\u00b6\nWhether to always be verbose.\nType\nbool\nchain_starts\u00b6\nThe number of times the chain start method has been called.\nType\nint\nchain_ends\u00b6\nThe number of times the chain end method has been called.\nType\nint\nllm_starts\u00b6\nThe number of times the llm start method has been called.\nType\nint\nllm_ends\u00b6\nThe number of times the llm end method has been called.\nType\nint\nllm_streams\u00b6\nThe number of times the text method has been called.\nType\nint\ntool_starts\u00b6\nThe number of times the tool start method has been called.\nType\nint\ntool_ends\u00b6\nThe number of times the tool end method has been called.\nType\nint\nagent_ends\u00b6\nThe number of times the agent end method has been called.\nType\nint\non_llm_start_records\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.utils.BaseMetadataCallbackHandler.html"}
{"id": "583fb4b1eef5-1", "text": "Type\nint\non_llm_start_records\u00b6\nA list of records of the on_llm_start method.\nType\nlist\non_llm_token_records\u00b6\nA list of records of the on_llm_token method.\nType\nlist\non_llm_end_records\u00b6\nA list of records of the on_llm_end method.\nType\nlist\non_chain_start_records\u00b6\nA list of records of the on_chain_start method.\nType\nlist\non_chain_end_records\u00b6\nA list of records of the on_chain_end method.\nType\nlist\non_tool_start_records\u00b6\nA list of records of the on_tool_start method.\nType\nlist\non_tool_end_records\u00b6\nA list of records of the on_tool_end method.\nType\nlist\non_agent_finish_records\u00b6\nA list of records of the on_agent_end method.\nType\nlist\nAttributes\nalways_verbose\nWhether to call verbose callbacks even if verbose is False.\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nMethods\n__init__()\nget_custom_callback_meta()\nreset_callback_meta()\nReset the callback metadata.\n__init__() \u2192 None[source]\u00b6\nget_custom_callback_meta() \u2192 Dict[str, Any][source]\u00b6\nreset_callback_meta() \u2192 None[source]\u00b6\nReset the callback metadata.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.utils.BaseMetadataCallbackHandler.html"}
{"id": "8fc50bcd2d0f-0", "text": "langchain.callbacks.labelstudio_callback.LabelStudioMode\u00b6\nclass langchain.callbacks.labelstudio_callback.LabelStudioMode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nLabel Studio mode enumerator.\nPROMPT = 'prompt'\u00b6\nCHAT = 'chat'\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.labelstudio_callback.LabelStudioMode.html"}
{"id": "f285c736deb1-0", "text": "langchain.callbacks.utils.hash_string\u00b6\nlangchain.callbacks.utils.hash_string(s: str) \u2192 str[source]\u00b6\nHash a string using sha1.\nParameters\ns (str) \u2013 The string to hash.\nReturns\nThe hashed string.\nReturn type\n(str)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.utils.hash_string.html"}
{"id": "554aecce3fb8-0", "text": "langchain.callbacks.file.FileCallbackHandler\u00b6\nclass langchain.callbacks.file.FileCallbackHandler(filename: str, mode: str = 'a', color: Optional[str] = None)[source]\u00b6\nCallback Handler that writes to a file.\nInitialize callback handler.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(filename[,\u00a0mode,\u00a0color])\nInitialize callback handler.\non_agent_action(action[,\u00a0color])\nRun on agent action.\non_agent_finish(finish[,\u00a0color])\nRun on agent end.\non_chain_end(outputs,\u00a0**kwargs)\nPrint out that we finished a chain.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nPrint out that we are entering a chain.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM ends running.\non_llm_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM errors.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.file.FileCallbackHandler.html"}
{"id": "554aecce3fb8-1", "text": "Run when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text[,\u00a0color,\u00a0end])\nRun when agent ends.\non_tool_end(output[,\u00a0color,\u00a0...])\nIf not the final action, print out observation.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\n__init__(filename: str, mode: str = 'a', color: Optional[str] = None) \u2192 None[source]\u00b6\nInitialize callback handler.\non_agent_action(action: AgentAction, color: Optional[str] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, color: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nPrint out that we finished a chain.\non_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nPrint out that we are entering a chain.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.file.FileCallbackHandler.html"}
{"id": "554aecce3fb8-2", "text": "Print out that we are entering a chain.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on new LLM token. Only available when streaming is enabled.\nParameters\ntoken (str) \u2013 The new token.\nchunk (GenerationChunk | ChatGenerationChunk) \u2013 The new generated chunk,\ninformation. (containing content and other) \u2013 \non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM starts running.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.file.FileCallbackHandler.html"}
{"id": "554aecce3fb8-3", "text": "Run when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, color: Optional[str] = None, end: str = '', **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent ends.\non_tool_end(output: str, color: Optional[str] = None, observation_prefix: Optional[str] = None, llm_prefix: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\nIf not the final action, print out observation.\non_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool starts running.\nExamples using FileCallbackHandler\u00b6\nLogging to file", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.file.FileCallbackHandler.html"}
{"id": "554cd4fd2c6b-0", "text": "langchain.callbacks.manager.wandb_tracing_enabled\u00b6\nlangchain.callbacks.manager.wandb_tracing_enabled(session_name: str = 'default') \u2192 Generator[None, None, None][source]\u00b6\nGet the WandbTracer in a context manager.\nParameters\nsession_name (str, optional) \u2013 The name of the session.\nDefaults to \u201cdefault\u201d.\nReturns\nNone\nExample\n>>> with wandb_tracing_enabled() as session:\n...     # Use the WandbTracer session\nExamples using wandb_tracing_enabled\u00b6\nWandB Tracing", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.manager.wandb_tracing_enabled.html"}
{"id": "583be1487390-0", "text": "langchain.callbacks.comet_ml_callback.import_comet_ml\u00b6\nlangchain.callbacks.comet_ml_callback.import_comet_ml() \u2192 Any[source]\u00b6\nImport comet_ml and raise an error if it is not installed.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.comet_ml_callback.import_comet_ml.html"}
{"id": "fb39da53b825-0", "text": "langchain.callbacks.whylabs_callback.import_langkit\u00b6\nlangchain.callbacks.whylabs_callback.import_langkit(sentiment: bool = False, toxicity: bool = False, themes: bool = False) \u2192 Any[source]\u00b6\nImport the langkit python package and raise an error if it is not installed.\nParameters\nsentiment \u2013 Whether to import the langkit.sentiment module. Defaults to False.\ntoxicity \u2013 Whether to import the langkit.toxicity module. Defaults to False.\nthemes \u2013 Whether to import the langkit.themes module. Defaults to False.\nReturns\nThe imported langkit module.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.whylabs_callback.import_langkit.html"}
{"id": "24f3d9285d4f-0", "text": "langchain.callbacks.streamlit.mutable_expander.ChildType\u00b6\nclass langchain.callbacks.streamlit.mutable_expander.ChildType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nThe enumerator of the child type.\nMARKDOWN = 'MARKDOWN'\u00b6\nEXCEPTION = 'EXCEPTION'\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.mutable_expander.ChildType.html"}
{"id": "401755dce443-0", "text": "langchain.callbacks.promptlayer_callback.PromptLayerCallbackHandler\u00b6\nclass langchain.callbacks.promptlayer_callback.PromptLayerCallbackHandler(pl_id_callback: Optional[Callable[[...], Any]] = None, pl_tags: Optional[List[str]] = None)[source]\u00b6\nCallback handler for promptlayer.\nInitialize the PromptLayerCallbackHandler.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([pl_id_callback,\u00a0pl_tags])\nInitialize the PromptLayerCallbackHandler.\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain ends running.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM ends running.\non_llm_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM errors.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.promptlayer_callback.PromptLayerCallbackHandler.html"}
{"id": "401755dce443-1", "text": "on_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool ends running.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\n__init__(pl_id_callback: Optional[Callable[[...], Any]] = None, pl_tags: Optional[List[str]] = None) \u2192 None[source]\u00b6\nInitialize the PromptLayerCallbackHandler.\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain ends running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.promptlayer_callback.PromptLayerCallbackHandler.html"}
{"id": "401755dce443-2", "text": "Run when chain ends running.\non_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on new LLM token. Only available when streaming is enabled.\nParameters\ntoken (str) \u2013 The new token.\nchunk (GenerationChunk | ChatGenerationChunk) \u2013 The new generated chunk,\ninformation. (containing content and other) \u2013", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.promptlayer_callback.PromptLayerCallbackHandler.html"}
{"id": "401755dce443-3", "text": "information. (containing content and other) \u2013 \non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when LLM starts running.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.promptlayer_callback.PromptLayerCallbackHandler.html"}
{"id": "401755dce443-4", "text": "Run when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool starts running.\nExamples using PromptLayerCallbackHandler\u00b6\nPromptLayer", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.promptlayer_callback.PromptLayerCallbackHandler.html"}
{"id": "280c3ff68fa7-0", "text": "langchain.callbacks.streaming_aiter_final_only.AsyncFinalIteratorCallbackHandler\u00b6\nclass langchain.callbacks.streaming_aiter_final_only.AsyncFinalIteratorCallbackHandler(*, answer_prefix_tokens: Optional[List[str]] = None, strip_tokens: bool = True, stream_prefix: bool = False)[source]\u00b6\nCallback handler that returns an async iterator.\nOnly the final output of the agent will be iterated.\nInstantiate AsyncFinalIteratorCallbackHandler.\nParameters\nanswer_prefix_tokens \u2013 Token sequence that prefixes the answer.\nDefault is [\u201cFinal\u201d, \u201cAnswer\u201d, \u201c:\u201d]\nstrip_tokens \u2013 Ignore white spaces and new lines when comparing\nanswer_prefix_tokens to last tokens? (to determine if answer has been\nreached)\nstream_prefix \u2013 Should answer prefix itself also be streamed?\nAttributes\nalways_verbose\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(*[,\u00a0answer_prefix_tokens,\u00a0...])\nInstantiate AsyncFinalIteratorCallbackHandler.\naiter()\nappend_to_last_tokens(token)\ncheck_if_answer_reached()\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when chain ends running.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nRun when chain starts running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_aiter_final_only.AsyncFinalIteratorCallbackHandler.html"}
{"id": "280c3ff68fa7-1", "text": "Run when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0**kwargs)\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on retriever end.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on retriever error.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun on retriever start.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id,\u00a0tags])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when tool ends running.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\n__init__(*, answer_prefix_tokens: Optional[List[str]] = None, strip_tokens: bool = True, stream_prefix: bool = False) \u2192 None[source]\u00b6\nInstantiate AsyncFinalIteratorCallbackHandler.\nParameters\nanswer_prefix_tokens \u2013 Token sequence that prefixes the answer.\nDefault is [\u201cFinal\u201d, \u201cAnswer\u201d, \u201c:\u201d]\nstrip_tokens \u2013 Ignore white spaces and new lines when comparing", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_aiter_final_only.AsyncFinalIteratorCallbackHandler.html"}
{"id": "280c3ff68fa7-2", "text": "strip_tokens \u2013 Ignore white spaces and new lines when comparing\nanswer_prefix_tokens to last tokens? (to determine if answer has been\nreached)\nstream_prefix \u2013 Should answer prefix itself also be streamed?\nasync aiter() \u2192 AsyncIterator[str]\u00b6\nappend_to_last_tokens(token: str) \u2192 None[source]\u00b6\ncheck_if_answer_reached() \u2192 bool[source]\u00b6\nasync on_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun on agent action.\nasync on_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun on agent end.\nasync on_chain_end(outputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun when chain ends running.\nasync on_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun when chain errors.\nasync on_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 None\u00b6\nRun when chain starts running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_aiter_final_only.AsyncFinalIteratorCallbackHandler.html"}
{"id": "280c3ff68fa7-3", "text": "Run when chain starts running.\nasync on_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\nasync on_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\nasync on_llm_error(error: BaseException, **kwargs: Any) \u2192 None\u00b6\nRun when LLM errors.\nasync on_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun on new LLM token. Only available when streaming is enabled.\nasync on_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts running.\nasync on_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun on retriever end.\nasync on_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun on retriever error.\nasync on_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 None\u00b6\nRun on retriever start.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_aiter_final_only.AsyncFinalIteratorCallbackHandler.html"}
{"id": "280c3ff68fa7-4", "text": "Run on retriever start.\nasync on_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\nasync on_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun on arbitrary text.\nasync on_tool_end(output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun when tool ends running.\nasync on_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun when tool errors.\nasync on_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 None\u00b6\nRun when tool starts running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_aiter_final_only.AsyncFinalIteratorCallbackHandler.html"}
{"id": "dad35dd2846a-0", "text": "langchain.callbacks.mlflow_callback.construct_html_from_prompt_and_generation\u00b6\nlangchain.callbacks.mlflow_callback.construct_html_from_prompt_and_generation(prompt: str, generation: str) \u2192 Any[source]\u00b6\nConstruct an html element from a prompt and a generation.\nParameters\nprompt (str) \u2013 The prompt.\ngeneration (str) \u2013 The generation.\nReturns\nThe html string.\nReturn type\n(str)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.mlflow_callback.construct_html_from_prompt_and_generation.html"}
{"id": "aa72ef2f0bd4-0", "text": "langchain.callbacks.openai_info.OpenAICallbackHandler\u00b6\nclass langchain.callbacks.openai_info.OpenAICallbackHandler[source]\u00b6\nCallback Handler that tracks OpenAI info.\nAttributes\nalways_verbose\nWhether to call verbose callbacks even if verbose is False.\ncompletion_tokens\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nprompt_tokens\nraise_error\nrun_inline\nsuccessful_requests\ntotal_cost\ntotal_tokens\nMethods\n__init__()\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain ends running.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nCollect token usage.\non_llm_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM errors.\non_llm_new_token(token,\u00a0**kwargs)\nPrint out the token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nPrint out the prompts.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.openai_info.OpenAICallbackHandler.html"}
{"id": "aa72ef2f0bd4-1", "text": "Run when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool ends running.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\n__init__()\u00b6\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.openai_info.OpenAICallbackHandler.html"}
{"id": "aa72ef2f0bd4-2", "text": "Run when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nCollect token usage.\non_llm_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nPrint out the token.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nPrint out the prompts.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.openai_info.OpenAICallbackHandler.html"}
{"id": "aa72ef2f0bd4-3", "text": "Run when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool starts running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.openai_info.OpenAICallbackHandler.html"}
{"id": "c7c9f38c784f-0", "text": "langchain.callbacks.llmonitor_callback.UserContextManager\u00b6\nclass langchain.callbacks.llmonitor_callback.UserContextManager(user_id: str, user_props: Any = None)[source]\u00b6\nContext manager for LLMonitor user context.\nMethods\n__init__(user_id[,\u00a0user_props])\n__init__(user_id: str, user_props: Any = None) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.llmonitor_callback.UserContextManager.html"}
{"id": "5978710f7bef-0", "text": "langchain.callbacks.utils.import_pandas\u00b6\nlangchain.callbacks.utils.import_pandas() \u2192 Any[source]\u00b6\nImport the pandas python package and raise an error if it is not installed.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.utils.import_pandas.html"}
{"id": "8718b7d221ee-0", "text": "langchain.callbacks.arthur_callback.ArthurCallbackHandler\u00b6\nclass langchain.callbacks.arthur_callback.ArthurCallbackHandler(arthur_model: ArthurModel)[source]\u00b6\nCallback Handler that logs to Arthur platform.\nArthur helps enterprise teams optimize model operations\nand performance at scale. The Arthur API tracks model\nperformance, explainability, and fairness across tabular,\nNLP, and CV models. Our API is model- and platform-agnostic,\nand continuously scales with complex and dynamic enterprise needs.\nTo learn more about Arthur, visit our website at\nhttps://www.arthur.ai/ or read the Arthur docs at\nhttps://docs.arthur.ai/\nInitialize callback handler.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(arthur_model)\nInitialize callback handler.\nfrom_credentials(model_id[,\u00a0arthur_url,\u00a0...])\nInitialize callback handler from Arthur credentials.\non_agent_action(action,\u00a0**kwargs)\nDo nothing when agent takes a specific action.\non_agent_finish(finish,\u00a0**kwargs)\nDo nothing\non_chain_end(outputs,\u00a0**kwargs)\nOn chain end, do nothing.\non_chain_error(error,\u00a0**kwargs)\nDo nothing when LLM chain outputs an error.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nOn chain start, do nothing.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nOn LLM end, send data to Arthur.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.arthur_callback.ArthurCallbackHandler.html"}
{"id": "8718b7d221ee-1", "text": "On LLM end, send data to Arthur.\non_llm_error(error,\u00a0**kwargs)\nDo nothing when LLM outputs an error.\non_llm_new_token(token,\u00a0**kwargs)\nOn new token, pass.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nOn LLM start, save the input prompts\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nDo nothing\non_tool_end(output[,\u00a0observation_prefix,\u00a0...])\nDo nothing when tool ends.\non_tool_error(error,\u00a0**kwargs)\nDo nothing when tool outputs an error.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nDo nothing when tool starts.\n__init__(arthur_model: ArthurModel) \u2192 None[source]\u00b6\nInitialize callback handler.\nclassmethod from_credentials(model_id: str, arthur_url: Optional[str] = 'https://app.arthur.ai', arthur_login: Optional[str] = None, arthur_password: Optional[str] = None) \u2192 ArthurCallbackHandler[source]\u00b6\nInitialize callback handler from Arthur credentials.\nParameters\nmodel_id (str) \u2013 The ID of the arthur model to log to.\narthur_url (str, optional) \u2013 The URL of the Arthur instance to log to.\nDefaults to \u201chttps://app.arthur.ai\u201d.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.arthur_callback.ArthurCallbackHandler.html"}
{"id": "8718b7d221ee-2", "text": "Defaults to \u201chttps://app.arthur.ai\u201d.\narthur_login (str, optional) \u2013 The login to use to connect to Arthur.\nDefaults to None.\narthur_password (str, optional) \u2013 The password to use to connect to\nArthur. Defaults to None.\nReturns\nThe initialized callback handler.\nReturn type\nArthurCallbackHandler\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nDo nothing when agent takes a specific action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nOn chain end, do nothing.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when LLM chain outputs an error.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nOn chain start, do nothing.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nOn LLM end, send data to Arthur.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when LLM outputs an error.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nOn new token, pass.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.arthur_callback.ArthurCallbackHandler.html"}
{"id": "8718b7d221ee-3", "text": "On new token, pass.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nOn LLM start, save the input prompts\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing\non_tool_end(output: str, observation_prefix: Optional[str] = None, llm_prefix: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool ends.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool outputs an error.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool starts.\nExamples using ArthurCallbackHandler\u00b6\nArthur", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.arthur_callback.ArthurCallbackHandler.html"}
{"id": "0f6b92a5d344-0", "text": "langchain.callbacks.tracers.wandb.WandbRunArgs\u00b6\nclass langchain.callbacks.tracers.wandb.WandbRunArgs[source]\u00b6\nArguments for the WandbTracer.\njob_type: Optional[str]\u00b6\ndir: Optional[StrPath]\u00b6\nconfig: Union[Dict, str, None]\u00b6\nproject: Optional[str]\u00b6\nentity: Optional[str]\u00b6\nreinit: Optional[bool]\u00b6\ntags: Optional[Sequence]\u00b6\ngroup: Optional[str]\u00b6\nname: Optional[str]\u00b6\nnotes: Optional[str]\u00b6\nmagic: Optional[Union[dict, str, bool]]\u00b6\nconfig_exclude_keys: Optional[List[str]]\u00b6\nconfig_include_keys: Optional[List[str]]\u00b6\nanonymous: Optional[str]\u00b6\nmode: Optional[str]\u00b6\nallow_val_change: Optional[bool]\u00b6\nresume: Optional[Union[bool, str]]\u00b6\nforce: Optional[bool]\u00b6\ntensorboard: Optional[bool]\u00b6\nsync_tensorboard: Optional[bool]\u00b6\nmonitor_gym: Optional[bool]\u00b6\nsave_code: Optional[bool]\u00b6\nid: Optional[str]\u00b6\nsettings: Union[WBSettings, Dict[str, Any], None]\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.tracers.wandb.WandbRunArgs.html"}
{"id": "2108d3882004-0", "text": "langchain.callbacks.clearml_callback.import_clearml\u00b6\nlangchain.callbacks.clearml_callback.import_clearml() \u2192 Any[source]\u00b6\nImport the clearml python package and raise an error if it is not installed.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.clearml_callback.import_clearml.html"}
{"id": "1b911f6caab2-0", "text": "langchain.callbacks.streaming_aiter.AsyncIteratorCallbackHandler\u00b6\nclass langchain.callbacks.streaming_aiter.AsyncIteratorCallbackHandler[source]\u00b6\nCallback handler that returns an async iterator.\nAttributes\nalways_verbose\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nqueue\ndone\nMethods\n__init__()\naiter()\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when chain ends running.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0**kwargs)\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on retriever end.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on retriever error.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_aiter.AsyncIteratorCallbackHandler.html"}
{"id": "1b911f6caab2-1", "text": "Run on retriever error.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun on retriever start.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id,\u00a0tags])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when tool ends running.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\n__init__() \u2192 None[source]\u00b6\nasync aiter() \u2192 AsyncIterator[str][source]\u00b6\nasync on_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun on agent action.\nasync on_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun on agent end.\nasync on_chain_end(outputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun when chain ends running.\nasync on_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun when chain errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_aiter.AsyncIteratorCallbackHandler.html"}
{"id": "1b911f6caab2-2", "text": "Run when chain errors.\nasync on_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 None\u00b6\nRun when chain starts running.\nasync on_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\nasync on_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\nasync on_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM errors.\nasync on_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun on new LLM token. Only available when streaming is enabled.\nasync on_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts running.\nasync on_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun on retriever end.\nasync on_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun on retriever error.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_aiter.AsyncIteratorCallbackHandler.html"}
{"id": "1b911f6caab2-3", "text": "Run on retriever error.\nasync on_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 None\u00b6\nRun on retriever start.\nasync on_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\nasync on_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun on arbitrary text.\nasync on_tool_end(output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun when tool ends running.\nasync on_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None\u00b6\nRun when tool errors.\nasync on_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 None\u00b6\nRun when tool starts running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streaming_aiter.AsyncIteratorCallbackHandler.html"}
{"id": "2ecf5d1d9bbc-0", "text": "langchain.callbacks.human.HumanApprovalCallbackHandler\u00b6\nclass langchain.callbacks.human.HumanApprovalCallbackHandler(approve: ~typing.Callable[[~typing.Any], bool] = <function _default_approve>, should_check: ~typing.Callable[[~typing.Dict[str, ~typing.Any]], bool] = <function _default_true>)[source]\u00b6\nCallback for manually validating values.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([approve,\u00a0should_check])\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain ends running.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM ends running.\non_llm_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM errors.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.human.HumanApprovalCallbackHandler.html"}
{"id": "2ecf5d1d9bbc-1", "text": "Run on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool ends running.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\n__init__(approve: ~typing.Callable[[~typing.Any], bool] = <function _default_approve>, should_check: ~typing.Callable[[~typing.Dict[str, ~typing.Any]], bool] = <function _default_true>)[source]\u00b6\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.human.HumanApprovalCallbackHandler.html"}
{"id": "2ecf5d1d9bbc-2", "text": "Run on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on new LLM token. Only available when streaming is enabled.\nParameters", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.human.HumanApprovalCallbackHandler.html"}
{"id": "2ecf5d1d9bbc-3", "text": "Run on new LLM token. Only available when streaming is enabled.\nParameters\ntoken (str) \u2013 The new token.\nchunk (GenerationChunk | ChatGenerationChunk) \u2013 The new generated chunk,\ninformation. (containing content and other) \u2013 \non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM starts running.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.human.HumanApprovalCallbackHandler.html"}
{"id": "2ecf5d1d9bbc-4", "text": "Run on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when tool starts running.\nExamples using HumanApprovalCallbackHandler\u00b6\nHuman-in-the-loop Tool Validation", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.human.HumanApprovalCallbackHandler.html"}
{"id": "a5f0170a5e16-0", "text": "langchain.callbacks.wandb_callback.WandbCallbackHandler\u00b6\nclass langchain.callbacks.wandb_callback.WandbCallbackHandler(job_type: Optional[str] = None, project: Optional[str] = 'langchain_callback_demo', entity: Optional[str] = None, tags: Optional[Sequence] = None, group: Optional[str] = None, name: Optional[str] = None, notes: Optional[str] = None, visualize: bool = False, complexity_metrics: bool = False, stream_logs: bool = False)[source]\u00b6\nCallback Handler that logs to Weights and Biases.\nParameters\njob_type (str) \u2013 The type of job.\nproject (str) \u2013 The project to log to.\nentity (str) \u2013 The entity to log to.\ntags (list) \u2013 The tags to log.\ngroup (str) \u2013 The group to log to.\nname (str) \u2013 The name of the run.\nnotes (str) \u2013 The notes to log.\nvisualize (bool) \u2013 Whether to visualize the run.\ncomplexity_metrics (bool) \u2013 Whether to log complexity metrics.\nstream_logs (bool) \u2013 Whether to stream callback actions to W&B\nThis handler will utilize the associated callback method called and formats\nthe input of each callback function with metadata regarding the state of LLM run,\nand adds the response to the list of records for both the {method}_records and\naction. It then logs the response using the run.log() method to Weights and Biases.\nInitialize callback handler.\nAttributes\nalways_verbose\nWhether to call verbose callbacks even if verbose is False.\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.wandb_callback.WandbCallbackHandler.html"}
{"id": "a5f0170a5e16-1", "text": "ignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([job_type,\u00a0project,\u00a0entity,\u00a0tags,\u00a0...])\nInitialize callback handler.\nflush_tracker([langchain_asset,\u00a0reset,\u00a0...])\nFlush the tracker and reset the session.\nget_custom_callback_meta()\non_agent_action(action,\u00a0**kwargs)\nRun on agent action.\non_agent_finish(finish,\u00a0**kwargs)\nRun when agent ends running.\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends running.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0**kwargs)\nRun when LLM generates a new token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when agent is ending.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.wandb_callback.WandbCallbackHandler.html"}
{"id": "a5f0170a5e16-2", "text": "on_text(text,\u00a0**kwargs)\nRun when agent is ending.\non_tool_end(output,\u00a0**kwargs)\nRun when tool ends running.\non_tool_error(error,\u00a0**kwargs)\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nRun when tool starts running.\nreset_callback_meta()\nReset the callback metadata.\n__init__(job_type: Optional[str] = None, project: Optional[str] = 'langchain_callback_demo', entity: Optional[str] = None, tags: Optional[Sequence] = None, group: Optional[str] = None, name: Optional[str] = None, notes: Optional[str] = None, visualize: bool = False, complexity_metrics: bool = False, stream_logs: bool = False) \u2192 None[source]\u00b6\nInitialize callback handler.\nflush_tracker(langchain_asset: Any = None, reset: bool = True, finish: bool = False, job_type: Optional[str] = None, project: Optional[str] = None, entity: Optional[str] = None, tags: Optional[Sequence] = None, group: Optional[str] = None, name: Optional[str] = None, notes: Optional[str] = None, visualize: Optional[bool] = None, complexity_metrics: Optional[bool] = None) \u2192 None[source]\u00b6\nFlush the tracker and reset the session.\nParameters\nlangchain_asset \u2013 The langchain asset to save.\nreset \u2013 Whether to reset the session.\nfinish \u2013 Whether to finish the run.\njob_type \u2013 The job type.\nproject \u2013 The project.\nentity \u2013 The entity.\ntags \u2013 The tags.\ngroup \u2013 The group.\nname \u2013 The name.\nnotes \u2013 The notes.\nvisualize \u2013 Whether to visualize.\ncomplexity_metrics \u2013 Whether to compute complexity metrics.\nReturns \u2013 None", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.wandb_callback.WandbCallbackHandler.html"}
{"id": "a5f0170a5e16-3", "text": "complexity_metrics \u2013 Whether to compute complexity metrics.\nReturns \u2013 None\nget_custom_callback_meta() \u2192 Dict[str, Any]\u00b6\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent ends running.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM generates a new token.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.wandb_callback.WandbCallbackHandler.html"}
{"id": "a5f0170a5e16-4", "text": "Run when LLM starts.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent is ending.\non_tool_end(output: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool starts running.\nreset_callback_meta() \u2192 None\u00b6\nReset the callback metadata.\nExamples using WandbCallbackHandler\u00b6\nWeights & Biases", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.wandb_callback.WandbCallbackHandler.html"}
{"id": "c2f5d0169aec-0", "text": "langchain.callbacks.streamlit.streamlit_callback_handler.LLMThoughtState\u00b6\nclass langchain.callbacks.streamlit.streamlit_callback_handler.LLMThoughtState(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnumerator of the LLMThought state.\nTHINKING = 'THINKING'\u00b6\nRUNNING_TOOL = 'RUNNING_TOOL'\u00b6\nCOMPLETE = 'COMPLETE'\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.streamlit_callback_handler.LLMThoughtState.html"}
{"id": "5ffa1cc457f2-0", "text": "langchain.callbacks.labelstudio_callback.LabelStudioCallbackHandler\u00b6\nclass langchain.callbacks.labelstudio_callback.LabelStudioCallbackHandler(api_key: Optional[str] = None, url: Optional[str] = None, project_id: Optional[int] = None, project_name: str = 'LangChain-%Y-%m-%d', project_config: Optional[str] = None, mode: Union[str, LabelStudioMode] = LabelStudioMode.PROMPT)[source]\u00b6\nLabel Studio callback handler.\nProvides the ability to send predictions to Label Studio\nfor human evaluation, feedback and annotation.\nParameters\napi_key \u2013 Label Studio API key\nurl \u2013 Label Studio URL\nproject_id \u2013 Label Studio project ID\nproject_name \u2013 Label Studio project name\nproject_config \u2013 Label Studio project config (XML)\nmode \u2013 Label Studio mode (\u201cprompt\u201d or \u201cchat\u201d)\nExamples\n>>> from langchain.llms import OpenAI\n>>> from langchain.callbacks import LabelStudioCallbackHandler\n>>> handler = LabelStudioCallbackHandler(\n...             api_key='<your_key_here>',\n...             url='http://localhost:8080',\n...             project_name='LangChain-%Y-%m-%d',\n...             mode='prompt'\n... )\n>>> llm = OpenAI(callbacks=[handler])\n>>> llm.predict('Tell me a story about a dog.')\nAttributes\nDEFAULT_PROJECT_NAME\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([api_key,\u00a0url,\u00a0project_id,\u00a0...])\nadd_prompts_generations(run_id,\u00a0generations)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.labelstudio_callback.LabelStudioCallbackHandler.html"}
{"id": "5ffa1cc457f2-1", "text": "add_prompts_generations(run_id,\u00a0generations)\non_agent_action(action,\u00a0**kwargs)\nDo nothing when agent takes a specific action.\non_agent_finish(finish,\u00a0**kwargs)\nDo nothing\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends running.\non_chain_error(error,\u00a0**kwargs)\nDo nothing when LLM chain outputs an error.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nSave the prompts in memory when an LLM starts.\non_llm_end(response,\u00a0**kwargs)\nCreate a new Label Studio task for each prompt and generation.\non_llm_error(error,\u00a0**kwargs)\nDo nothing when LLM outputs an error.\non_llm_new_token(token,\u00a0**kwargs)\nDo nothing when a new token is generated.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nSave the prompts in memory when an LLM starts.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nDo nothing\non_tool_end(output[,\u00a0observation_prefix,\u00a0...])\nDo nothing when tool ends.\non_tool_error(error,\u00a0**kwargs)\nDo nothing when tool outputs an error.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.labelstudio_callback.LabelStudioCallbackHandler.html"}
{"id": "5ffa1cc457f2-2", "text": "on_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nDo nothing when tool starts.\n__init__(api_key: Optional[str] = None, url: Optional[str] = None, project_id: Optional[int] = None, project_name: str = 'LangChain-%Y-%m-%d', project_config: Optional[str] = None, mode: Union[str, LabelStudioMode] = LabelStudioMode.PROMPT)[source]\u00b6\nadd_prompts_generations(run_id: str, generations: List[List[Generation]]) \u2192 None[source]\u00b6\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nDo nothing when agent takes a specific action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when LLM chain outputs an error.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nSave the prompts in memory when an LLM starts.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nCreate a new Label Studio task for each prompt and generation.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.labelstudio_callback.LabelStudioCallbackHandler.html"}
{"id": "5ffa1cc457f2-3", "text": "on_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when LLM outputs an error.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when a new token is generated.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nSave the prompts in memory when an LLM starts.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing\non_tool_end(output: str, observation_prefix: Optional[str] = None, llm_prefix: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool ends.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool outputs an error.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.labelstudio_callback.LabelStudioCallbackHandler.html"}
{"id": "5ffa1cc457f2-4", "text": "Do nothing when tool outputs an error.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool starts.\nExamples using LabelStudioCallbackHandler\u00b6\nLabel Studio", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.labelstudio_callback.LabelStudioCallbackHandler.html"}
{"id": "02a7ba781e1a-0", "text": "langchain.callbacks.streamlit.streamlit_callback_handler.LLMThoughtLabeler\u00b6\nclass langchain.callbacks.streamlit.streamlit_callback_handler.LLMThoughtLabeler[source]\u00b6\nGenerates markdown labels for LLMThought containers. Pass a custom\nsubclass of this to StreamlitCallbackHandler to override its default\nlabeling logic.\nMethods\n__init__()\nget_final_agent_thought_label()\nReturn the markdown label for the agent's final thought - the \"Now I have the answer\" thought, that doesn't involve a tool.\nget_history_label()\nReturn a markdown label for the special 'history' container that contains overflow thoughts.\nget_initial_label()\nReturn the markdown label for a new LLMThought that doesn't have an associated tool yet.\nget_tool_label(tool,\u00a0is_complete)\nReturn the label for an LLMThought that has an associated tool.\n__init__()\u00b6\nget_final_agent_thought_label() \u2192 str[source]\u00b6\nReturn the markdown label for the agent\u2019s final thought -\nthe \u201cNow I have the answer\u201d thought, that doesn\u2019t involve\na tool.\nget_history_label() \u2192 str[source]\u00b6\nReturn a markdown label for the special \u2018history\u2019 container\nthat contains overflow thoughts.\nget_initial_label() \u2192 str[source]\u00b6\nReturn the markdown label for a new LLMThought that doesn\u2019t have\nan associated tool yet.\nget_tool_label(tool: ToolRecord, is_complete: bool) \u2192 str[source]\u00b6\nReturn the label for an LLMThought that has an associated\ntool.\nParameters\ntool \u2013 The tool\u2019s ToolRecord\nis_complete \u2013 True if the thought is complete; False if the thought\nis still receiving input.\nReturn type\nThe markdown label for the thought\u2019s container.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.streamlit_callback_handler.LLMThoughtLabeler.html"}
{"id": "0f1f7d050400-0", "text": "langchain.callbacks.streamlit.streamlit_callback_handler.StreamlitCallbackHandler\u00b6\nclass langchain.callbacks.streamlit.streamlit_callback_handler.StreamlitCallbackHandler(parent_container: DeltaGenerator, *, max_thought_containers: int = 4, expand_new_thoughts: bool = True, collapse_completed_thoughts: bool = True, thought_labeler: Optional[LLMThoughtLabeler] = None)[source]\u00b6\nA callback handler that writes to a Streamlit app.\nCreate a StreamlitCallbackHandler instance.\nParameters\nparent_container \u2013 The st.container that will contain all the Streamlit elements that the\nHandler creates.\nmax_thought_containers \u2013 The max number of completed LLM thought containers to show at once. When\nthis threshold is reached, a new thought will cause the oldest thoughts to\nbe collapsed into a \u201cHistory\u201d expander. Defaults to 4.\nexpand_new_thoughts \u2013 Each LLM \u201cthought\u201d gets its own st.expander. This param controls whether\nthat expander is expanded by default. Defaults to True.\ncollapse_completed_thoughts \u2013 If True, LLM thought expanders will be collapsed when completed.\nDefaults to True.\nthought_labeler \u2013 An optional custom LLMThoughtLabeler instance. If unspecified, the handler\nwill use the default thought labeling logic. Defaults to None.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(parent_container,\u00a0*[,\u00a0...])\nCreate a StreamlitCallbackHandler instance.\non_agent_action(action[,\u00a0color])\nRun on agent action.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.streamlit_callback_handler.StreamlitCallbackHandler.html"}
{"id": "0f1f7d050400-1", "text": "on_agent_action(action[,\u00a0color])\nRun on agent action.\non_agent_finish(finish[,\u00a0color])\nRun on agent end.\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends running.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0**kwargs)\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text[,\u00a0color,\u00a0end])\nRun on arbitrary text.\non_tool_end(output[,\u00a0color,\u00a0...])\nRun when tool ends running.\non_tool_error(error,\u00a0**kwargs)\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nRun when tool starts running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.streamlit_callback_handler.StreamlitCallbackHandler.html"}
{"id": "0f1f7d050400-2", "text": "Run when tool starts running.\n__init__(parent_container: DeltaGenerator, *, max_thought_containers: int = 4, expand_new_thoughts: bool = True, collapse_completed_thoughts: bool = True, thought_labeler: Optional[LLMThoughtLabeler] = None)[source]\u00b6\nCreate a StreamlitCallbackHandler instance.\nParameters\nparent_container \u2013 The st.container that will contain all the Streamlit elements that the\nHandler creates.\nmax_thought_containers \u2013 The max number of completed LLM thought containers to show at once. When\nthis threshold is reached, a new thought will cause the oldest thoughts to\nbe collapsed into a \u201cHistory\u201d expander. Defaults to 4.\nexpand_new_thoughts \u2013 Each LLM \u201cthought\u201d gets its own st.expander. This param controls whether\nthat expander is expanded by default. Defaults to True.\ncollapse_completed_thoughts \u2013 If True, LLM thought expanders will be collapsed when completed.\nDefaults to True.\nthought_labeler \u2013 An optional custom LLMThoughtLabeler instance. If unspecified, the handler\nwill use the default thought labeling logic. Defaults to None.\non_agent_action(action: AgentAction, color: Optional[str] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, color: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.streamlit_callback_handler.StreamlitCallbackHandler.html"}
{"id": "0f1f7d050400-3", "text": "Run when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun on new LLM token. Only available when streaming is enabled.\nParameters\ntoken (str) \u2013 The new token.\nchunk (GenerationChunk | ChatGenerationChunk) \u2013 The new generated chunk,\ninformation. (containing content and other) \u2013 \non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts running.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.streamlit_callback_handler.StreamlitCallbackHandler.html"}
{"id": "0f1f7d050400-4", "text": "Run when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, color: Optional[str] = None, end: str = '', **kwargs: Any) \u2192 None[source]\u00b6\nRun on arbitrary text.\non_tool_end(output: str, color: Optional[str] = None, observation_prefix: Optional[str] = None, llm_prefix: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool starts running.\nExamples using StreamlitCallbackHandler\u00b6\nStreamlit\nGPT4All", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.streamlit_callback_handler.StreamlitCallbackHandler.html"}
{"id": "0caf0840a0a1-0", "text": "langchain.callbacks.human.HumanRejectedException\u00b6\nclass langchain.callbacks.human.HumanRejectedException[source]\u00b6\nException to raise when a person manually review and rejects a value.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.human.HumanRejectedException.html"}
{"id": "c72edf86b76f-0", "text": "langchain.callbacks.wandb_callback.analyze_text\u00b6\nlangchain.callbacks.wandb_callback.analyze_text(text: str, complexity_metrics: bool = True, visualize: bool = True, nlp: Any = None, output_dir: Optional[Union[str, Path]] = None) \u2192 dict[source]\u00b6\nAnalyze text using textstat and spacy.\nParameters\ntext (str) \u2013 The text to analyze.\ncomplexity_metrics (bool) \u2013 Whether to compute complexity metrics.\nvisualize (bool) \u2013 Whether to visualize the text.\nnlp (spacy.lang) \u2013 The spacy language model to use for visualization.\noutput_dir (str) \u2013 The directory to save the visualization files to.\nReturns\nA dictionary containing the complexity metrics and visualizationfiles serialized in a wandb.Html element.\nReturn type\n(dict)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.wandb_callback.analyze_text.html"}
{"id": "2572f80a2b75-0", "text": "langchain.callbacks.openai_info.standardize_model_name\u00b6\nlangchain.callbacks.openai_info.standardize_model_name(model_name: str, is_completion: bool = False) \u2192 str[source]\u00b6\nStandardize the model name to a format that can be used in the OpenAI API.\nParameters\nmodel_name \u2013 Model name to standardize.\nis_completion \u2013 Whether the model is used for completion or not.\nDefaults to False.\nReturns\nStandardized model name.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.openai_info.standardize_model_name.html"}
{"id": "1eda2269720f-0", "text": "langchain.callbacks.trubrics_callback.TrubricsCallbackHandler\u00b6\nclass langchain.callbacks.trubrics_callback.TrubricsCallbackHandler(project: str = 'default', email: Optional[str] = None, password: Optional[str] = None, **kwargs: Any)[source]\u00b6\nCallback handler for Trubrics.\nParameters\nproject \u2013 a trubrics project, default project is \u201cdefault\u201d\nemail \u2013 a trubrics account email, can equally be set in env variables\npassword \u2013 a trubrics account password, can equally be set in env variables\n**kwargs \u2013 all other kwargs are parsed and set to trubrics prompt variables,\nor added to the metadata dict\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([project,\u00a0email,\u00a0password])\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain ends running.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0run_id,\u00a0**kwargs)\nRun when LLM ends running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.trubrics_callback.TrubricsCallbackHandler.html"}
{"id": "1eda2269720f-1", "text": "Run when LLM ends running.\non_llm_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM errors.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool ends running.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\n__init__(project: str = 'default', email: Optional[str] = None, password: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.trubrics_callback.TrubricsCallbackHandler.html"}
{"id": "1eda2269720f-2", "text": "Run on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], **kwargs: Any) \u2192 None[source]\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, run_id: UUID, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on new LLM token. Only available when streaming is enabled.\nParameters\ntoken (str) \u2013 The new token.\nchunk (GenerationChunk | ChatGenerationChunk) \u2013 The new generated chunk,\ninformation. (containing content and other) \u2013", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.trubrics_callback.TrubricsCallbackHandler.html"}
{"id": "1eda2269720f-3", "text": "information. (containing content and other) \u2013 \non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts running.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.trubrics_callback.TrubricsCallbackHandler.html"}
{"id": "1eda2269720f-4", "text": "Run when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool starts running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.trubrics_callback.TrubricsCallbackHandler.html"}
{"id": "a2e890974c67-0", "text": "langchain.callbacks.sagemaker_callback.SageMakerCallbackHandler\u00b6\nclass langchain.callbacks.sagemaker_callback.SageMakerCallbackHandler(run: Any)[source]\u00b6\nCallback Handler that logs prompt artifacts and metrics to SageMaker Experiments.\nParameters\nrun (sagemaker.experiments.run.Run) \u2013 Run object where the experiment is logged.\nInitialize callback handler.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(run)\nInitialize callback handler.\nflush_tracker()\nReset the steps and delete the temporary local directory.\njsonf(data,\u00a0data_dir,\u00a0filename[,\u00a0is_output])\nTo log the input data as json file artifact.\non_agent_action(action,\u00a0**kwargs)\nRun on agent action.\non_agent_finish(finish,\u00a0**kwargs)\nRun when agent ends running.\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends running.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0**kwargs)\nRun when LLM generates a new token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.sagemaker_callback.SageMakerCallbackHandler.html"}
{"id": "a2e890974c67-1", "text": "Run when LLM starts.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when agent is ending.\non_tool_end(output,\u00a0**kwargs)\nRun when tool ends running.\non_tool_error(error,\u00a0**kwargs)\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nRun when tool starts running.\n__init__(run: Any) \u2192 None[source]\u00b6\nInitialize callback handler.\nflush_tracker() \u2192 None[source]\u00b6\nReset the steps and delete the temporary local directory.\njsonf(data: Dict[str, Any], data_dir: str, filename: str, is_output: Optional[bool] = True) \u2192 None[source]\u00b6\nTo log the input data as json file artifact.\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent ends running.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.sagemaker_callback.SageMakerCallbackHandler.html"}
{"id": "a2e890974c67-2", "text": "Run when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM generates a new token.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.sagemaker_callback.SageMakerCallbackHandler.html"}
{"id": "a2e890974c67-3", "text": "Run when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent is ending.\non_tool_end(output: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool starts running.\nExamples using SageMakerCallbackHandler\u00b6\nSageMaker Tracking", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.sagemaker_callback.SageMakerCallbackHandler.html"}
{"id": "11b5905bc568-0", "text": "langchain.callbacks.mlflow_callback.MlflowCallbackHandler\u00b6\nclass langchain.callbacks.mlflow_callback.MlflowCallbackHandler(name: Optional[str] = 'langchainrun-%', experiment: Optional[str] = 'langchain', tags: Optional[Dict] = None, tracking_uri: Optional[str] = None)[source]\u00b6\nCallback Handler that logs metrics and artifacts to mlflow server.\nParameters\nname (str) \u2013 Name of the run.\nexperiment (str) \u2013 Name of the experiment.\ntags (dict) \u2013 Tags to be attached for the run.\ntracking_uri (str) \u2013 MLflow tracking server uri.\nThis handler will utilize the associated callback method called and formats\nthe input of each callback function with metadata regarding the state of LLM run,\nand adds the response to the list of records for both the {method}_records and\naction. It then logs the response to mlflow server.\nInitialize callback handler.\nAttributes\nalways_verbose\nWhether to call verbose callbacks even if verbose is False.\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([name,\u00a0experiment,\u00a0tags,\u00a0tracking_uri])\nInitialize callback handler.\nflush_tracker([langchain_asset,\u00a0finish])\nget_custom_callback_meta()\non_agent_action(action,\u00a0**kwargs)\nRun on agent action.\non_agent_finish(finish,\u00a0**kwargs)\nRun when agent ends running.\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends running.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.mlflow_callback.MlflowCallbackHandler.html"}
{"id": "11b5905bc568-1", "text": "on_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0**kwargs)\nRun when LLM generates a new token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when agent is ending.\non_tool_end(output,\u00a0**kwargs)\nRun when tool ends running.\non_tool_error(error,\u00a0**kwargs)\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nRun when tool starts running.\nreset_callback_meta()\nReset the callback metadata.\n__init__(name: Optional[str] = 'langchainrun-%', experiment: Optional[str] = 'langchain', tags: Optional[Dict] = None, tracking_uri: Optional[str] = None) \u2192 None[source]\u00b6\nInitialize callback handler.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.mlflow_callback.MlflowCallbackHandler.html"}
{"id": "11b5905bc568-2", "text": "Initialize callback handler.\nflush_tracker(langchain_asset: Any = None, finish: bool = False) \u2192 None[source]\u00b6\nget_custom_callback_meta() \u2192 Dict[str, Any]\u00b6\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent ends running.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM generates a new token.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.mlflow_callback.MlflowCallbackHandler.html"}
{"id": "11b5905bc568-3", "text": "Run when LLM starts.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent is ending.\non_tool_end(output: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool starts running.\nreset_callback_meta() \u2192 None\u00b6\nReset the callback metadata.\nExamples using MlflowCallbackHandler\u00b6\nMLflow", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.mlflow_callback.MlflowCallbackHandler.html"}
{"id": "d5298b0208aa-0", "text": "langchain.callbacks.infino_callback.get_num_tokens\u00b6\nlangchain.callbacks.infino_callback.get_num_tokens(string: str, openai_model_name: str) \u2192 int[source]\u00b6\nCalculate num tokens for OpenAI with tiktoken package.\nOfficial documentation: https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.infino_callback.get_num_tokens.html"}
{"id": "245ae17dd681-0", "text": "langchain.callbacks.argilla_callback.ArgillaCallbackHandler\u00b6\nclass langchain.callbacks.argilla_callback.ArgillaCallbackHandler(dataset_name: str, workspace_name: Optional[str] = None, api_url: Optional[str] = None, api_key: Optional[str] = None)[source]\u00b6\nCallback Handler that logs into Argilla.\nParameters\ndataset_name \u2013 name of the FeedbackDataset in Argilla. Note that it must\nexist in advance. If you need help on how to create a FeedbackDataset in\nArgilla, please visit\nhttps://docs.argilla.io/en/latest/guides/llms/practical_guides/use_argilla_callback_in_langchain.html.\nworkspace_name \u2013 name of the workspace in Argilla where the specified\nFeedbackDataset lives in. Defaults to None, which means that the\ndefault workspace will be used.\napi_url \u2013 URL of the Argilla Server that we want to use, and where the\nFeedbackDataset lives in. Defaults to None, which means that either\nARGILLA_API_URL environment variable or the default will be used.\napi_key \u2013 API Key to connect to the Argilla Server. Defaults to None, which\nmeans that either ARGILLA_API_KEY environment variable or the default\nwill be used.\nRaises\nImportError \u2013 if the argilla package is not installed.\nConnectionError \u2013 if the connection to Argilla fails.\nFileNotFoundError \u2013 if the FeedbackDataset retrieval from Argilla fails.\nExamples\n>>> from langchain.llms import OpenAI\n>>> from langchain.callbacks import ArgillaCallbackHandler\n>>> argilla_callback = ArgillaCallbackHandler(\n...     dataset_name=\"my-dataset\",\n...     workspace_name=\"my-workspace\",\n...     api_url=\"http://localhost:6900\",\n...     api_key=\"argilla.apikey\",\n... )\n>>> llm = OpenAI(\n...     temperature=0,", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.argilla_callback.ArgillaCallbackHandler.html"}
{"id": "245ae17dd681-1", "text": "... )\n>>> llm = OpenAI(\n...     temperature=0,\n...     callbacks=[argilla_callback],\n...     verbose=True,\n...     openai_api_key=\"API_KEY_HERE\",\n... )\n>>> llm.generate([\n...     \"What is the best NLP-annotation tool out there? (no bias at all)\",\n... ])\n\"Argilla, no doubt about it.\"\nInitializes the ArgillaCallbackHandler.\nParameters\ndataset_name \u2013 name of the FeedbackDataset in Argilla. Note that it must\nexist in advance. If you need help on how to create a FeedbackDataset\nin Argilla, please visit\nhttps://docs.argilla.io/en/latest/guides/llms/practical_guides/use_argilla_callback_in_langchain.html.\nworkspace_name \u2013 name of the workspace in Argilla where the specified\nFeedbackDataset lives in. Defaults to None, which means that the\ndefault workspace will be used.\napi_url \u2013 URL of the Argilla Server that we want to use, and where the\nFeedbackDataset lives in. Defaults to None, which means that either\nARGILLA_API_URL environment variable or the default will be used.\napi_key \u2013 API Key to connect to the Argilla Server. Defaults to None, which\nmeans that either ARGILLA_API_KEY environment variable or the default\nwill be used.\nRaises\nImportError \u2013 if the argilla package is not installed.\nConnectionError \u2013 if the connection to Argilla fails.\nFileNotFoundError \u2013 if the FeedbackDataset retrieval from Argilla fails.\nAttributes\nBLOG_URL\nDEFAULT_API_URL\nISSUES_URL\nREPO_URL\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.argilla_callback.ArgillaCallbackHandler.html"}
{"id": "245ae17dd681-2", "text": "ignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(dataset_name[,\u00a0workspace_name,\u00a0...])\nInitializes the ArgillaCallbackHandler.\non_agent_action(action,\u00a0**kwargs)\nDo nothing when agent takes a specific action.\non_agent_finish(finish,\u00a0**kwargs)\nDo nothing\non_chain_end(outputs,\u00a0**kwargs)\nIf 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.\non_chain_error(error,\u00a0**kwargs)\nDo nothing when LLM chain outputs an error.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nIf 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.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nLog records to Argilla when an LLM ends.\non_llm_error(error,\u00a0**kwargs)\nDo nothing when LLM outputs an error.\non_llm_new_token(token,\u00a0**kwargs)\nDo nothing when a new token is generated.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nSave the prompts in memory when an LLM starts.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.argilla_callback.ArgillaCallbackHandler.html"}
{"id": "245ae17dd681-3", "text": "on_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nDo nothing\non_tool_end(output[,\u00a0observation_prefix,\u00a0...])\nDo nothing when tool ends.\non_tool_error(error,\u00a0**kwargs)\nDo nothing when tool outputs an error.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nDo nothing when tool starts.\n__init__(dataset_name: str, workspace_name: Optional[str] = None, api_url: Optional[str] = None, api_key: Optional[str] = None) \u2192 None[source]\u00b6\nInitializes the ArgillaCallbackHandler.\nParameters\ndataset_name \u2013 name of the FeedbackDataset in Argilla. Note that it must\nexist in advance. If you need help on how to create a FeedbackDataset\nin Argilla, please visit\nhttps://docs.argilla.io/en/latest/guides/llms/practical_guides/use_argilla_callback_in_langchain.html.\nworkspace_name \u2013 name of the workspace in Argilla where the specified\nFeedbackDataset lives in. Defaults to None, which means that the\ndefault workspace will be used.\napi_url \u2013 URL of the Argilla Server that we want to use, and where the\nFeedbackDataset lives in. Defaults to None, which means that either\nARGILLA_API_URL environment variable or the default will be used.\napi_key \u2013 API Key to connect to the Argilla Server. Defaults to None, which\nmeans that either ARGILLA_API_KEY environment variable or the default\nwill be used.\nRaises\nImportError \u2013 if the argilla package is not installed.\nConnectionError \u2013 if the connection to Argilla fails.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.argilla_callback.ArgillaCallbackHandler.html"}
{"id": "245ae17dd681-4", "text": "ConnectionError \u2013 if the connection to Argilla fails.\nFileNotFoundError \u2013 if the FeedbackDataset retrieval from Argilla fails.\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nDo nothing when agent takes a specific action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nIf either the parent_run_id or the run_id is in self.prompts, then\nlog the outputs to Argilla, and pop the run from self.prompts. The behavior\ndiffers if the output is a list or not.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when LLM chain outputs an error.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nIf the key input is in inputs, then save it in self.prompts using\neither the parent_run_id or the run_id as the key. This is done so that\nwe don\u2019t log the same input prompt twice, once when the LLM starts and once\nwhen the chain starts.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nLog records to Argilla when an LLM ends.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.argilla_callback.ArgillaCallbackHandler.html"}
{"id": "245ae17dd681-5", "text": "on_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when LLM outputs an error.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when a new token is generated.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nSave the prompts in memory when an LLM starts.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing\non_tool_end(output: str, observation_prefix: Optional[str] = None, llm_prefix: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool ends.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool outputs an error.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.argilla_callback.ArgillaCallbackHandler.html"}
{"id": "245ae17dd681-6", "text": "Do nothing when tool outputs an error.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool starts.\nExamples using ArgillaCallbackHandler\u00b6\nArgilla", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.argilla_callback.ArgillaCallbackHandler.html"}
{"id": "b967c10e0133-0", "text": "langchain.callbacks.flyte_callback.import_flytekit\u00b6\nlangchain.callbacks.flyte_callback.import_flytekit() \u2192 Tuple[flytekit, renderer][source]\u00b6\nImport flytekit and flytekitplugins-deck-standard.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.flyte_callback.import_flytekit.html"}
{"id": "fc82d92d3fe2-0", "text": "langchain.callbacks.llmonitor_callback.LLMonitorCallbackHandler\u00b6\nclass langchain.callbacks.llmonitor_callback.LLMonitorCallbackHandler(app_id: Optional[str] = None, api_url: Optional[str] = None, verbose: bool = False)[source]\u00b6\nCallback Handler for LLMonitor`.\n#### Parameters:\napp_id: The app id of the app you want to report to. Defaults to\nNone, which means that LLMONITOR_APP_ID will be used.\n- api_url: The url of the LLMonitor API. Defaults to None,\nwhich means that either LLMONITOR_API_URL environment variable\nor https://app.llmonitor.com will be used.\n#### Raises:\nValueError: if app_id is not provided either as an\nargument or as an environment variable.\n- ConnectionError: if the connection to the API fails.\n#### Example:\n```python\nfrom langchain.llms import OpenAI\nfrom langchain.callbacks import LLMonitorCallbackHandler\nllmonitor_callback = LLMonitorCallbackHandler()\nllm = OpenAI(callbacks=[llmonitor_callback],\nmetadata={\u201cuserId\u201d: \u201cuser-123\u201d})\nllm.predict(\u201cHello, how are you?\u201d)\n```\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([app_id,\u00a0api_url,\u00a0verbose])\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.llmonitor_callback.LLMonitorCallbackHandler.html"}
{"id": "fc82d92d3fe2-1", "text": "Run on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain ends running.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM ends running.\non_llm_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM errors.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when tool ends running.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.llmonitor_callback.LLMonitorCallbackHandler.html"}
{"id": "fc82d92d3fe2-2", "text": "Run when tool starts running.\n__init__(app_id: Optional[str] = None, api_url: Optional[str] = None, verbose: bool = False) \u2192 None[source]\u00b6\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when a chat model starts running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.llmonitor_callback.LLMonitorCallbackHandler.html"}
{"id": "fc82d92d3fe2-3", "text": "Run when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on new LLM token. Only available when streaming is enabled.\nParameters\ntoken (str) \u2013 The new token.\nchunk (GenerationChunk | ChatGenerationChunk) \u2013 The new generated chunk,\ninformation. (containing content and other) \u2013 \non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts running.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.llmonitor_callback.LLMonitorCallbackHandler.html"}
{"id": "fc82d92d3fe2-4", "text": "Run when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool starts running.\nExamples using LLMonitorCallbackHandler\u00b6\nLLMonitor", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.llmonitor_callback.LLMonitorCallbackHandler.html"}
{"id": "94cdaa6c4121-0", "text": "langchain.callbacks.tracers.wandb.WandbTracer\u00b6\nclass langchain.callbacks.tracers.wandb.WandbTracer(run_args: Optional[WandbRunArgs] = None, **kwargs: Any)[source]\u00b6\nCallback Handler that logs to Weights and Biases.\nThis handler will log the model architecture and run traces to Weights and Biases.\nThis will ensure that all LangChain activity is logged to W&B.\nInitializes the WandbTracer.\nParameters\nrun_args \u2013 (dict, optional) Arguments to pass to wandb.init(). If not\nprovided, wandb.init() will be called with no arguments. Please\nrefer to the wandb.init for more details.\nTo use W&B to monitor all LangChain activity, add this tracer like any other\nLangChain callback:\n```\nfrom wandb.integration.langchain import WandbTracer\ntracer = WandbTracer()\nchain = LLMChain(llm, callbacks=[tracer])\n# \u2026end of notebook / script:\ntracer.finish()\n```\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([run_args])\nInitializes the WandbTracer.\nfinish()\nWaits for all asynchronous processes to finish and data to upload.\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0inputs])", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.tracers.wandb.WandbTracer.html"}
{"id": "94cdaa6c4121-1", "text": "on_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0inputs])\nEnd a trace for a chain run.\non_chain_error(error,\u00a0*[,\u00a0inputs])\nHandle an error for a chain run.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nStart a trace for a chain run.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for an LLM run.\non_llm_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for an LLM run.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nStart a trace for an LLM run.\non_retriever_end(documents,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for a tool run.\non_tool_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for a tool run.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.tracers.wandb.WandbTracer.html"}
{"id": "94cdaa6c4121-2", "text": "on_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nStart a trace for a tool run.\n__init__(run_args: Optional[WandbRunArgs] = None, **kwargs: Any) \u2192 None[source]\u00b6\nInitializes the WandbTracer.\nParameters\nrun_args \u2013 (dict, optional) Arguments to pass to wandb.init(). If not\nprovided, wandb.init() will be called with no arguments. Please\nrefer to the wandb.init for more details.\nTo use W&B to monitor all LangChain activity, add this tracer like any other\nLangChain callback:\n```\nfrom wandb.integration.langchain import WandbTracer\ntracer = WandbTracer()\nchain = LLMChain(llm, callbacks=[tracer])\n# \u2026end of notebook / script:\ntracer.finish()\n```\nfinish() \u2192 None[source]\u00b6\nWaits for all asynchronous processes to finish and data to upload.\nProxy for wandb.finish().\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, inputs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a chain run.\non_chain_error(error: BaseException, *, inputs: Optional[Dict[str, Any]] = None, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a chain run.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.tracers.wandb.WandbTracer.html"}
{"id": "94cdaa6c4121-3", "text": "Handle an error for a chain run.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, run_type: Optional[str] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a chain run.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for an LLM run.\non_llm_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for an LLM run.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Run\u00b6\nRun on new LLM token. Only available when streaming is enabled.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for an LLM run.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.tracers.wandb.WandbTracer.html"}
{"id": "94cdaa6c4121-4", "text": "Start a trace for an LLM run.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a tool run.\non_tool_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a tool run.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a tool run.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.tracers.wandb.WandbTracer.html"}
{"id": "ebeada1a2dbb-0", "text": "langchain.callbacks.aim_callback.import_aim\u00b6\nlangchain.callbacks.aim_callback.import_aim() \u2192 Any[source]\u00b6\nImport the aim python package and raise an error if it is not installed.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.aim_callback.import_aim.html"}
{"id": "0d055423aaf1-0", "text": "langchain.callbacks.llmonitor_callback.identify\u00b6\nlangchain.callbacks.llmonitor_callback.identify(user_id: str, user_props: Any = None) \u2192 UserContextManager[source]\u00b6\nBuilds an LLMonitor UserContextManager\nParameters\nuser_id (-) \u2013 The user id.\nuser_props (-) \u2013 The user properties.\nReturns\nA context manager that sets the user context.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.llmonitor_callback.identify.html"}
{"id": "ebf457ce107f-0", "text": "langchain.callbacks.context_callback.import_context\u00b6\nlangchain.callbacks.context_callback.import_context() \u2192 Any[source]\u00b6\nImport the getcontext package.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.context_callback.import_context.html"}
{"id": "d9ab72eca030-0", "text": "langchain.callbacks.manager.get_openai_callback\u00b6\nlangchain.callbacks.manager.get_openai_callback() \u2192 Generator[OpenAICallbackHandler, None, None][source]\u00b6\nGet the OpenAI callback handler in a context manager.\nwhich conveniently exposes token and cost information.\nReturns\nThe OpenAI callback handler.\nReturn type\nOpenAICallbackHandler\nExample\n>>> with get_openai_callback() as cb:\n...     # Use the OpenAI callback handler\nExamples using get_openai_callback\u00b6\nAzure\nToken counting\nTracking token usage\nRun arbitrary functions", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.manager.get_openai_callback.html"}
{"id": "2e93aff842e5-0", "text": "langchain.callbacks.tracers.wandb.RunProcessor\u00b6\nclass langchain.callbacks.tracers.wandb.RunProcessor(wandb_module: Any, trace_module: Any)[source]\u00b6\nHandles the conversion of a LangChain Runs into a WBTraceTree.\nMethods\n__init__(wandb_module,\u00a0trace_module)\nbuild_tree(runs)\nBuilds a nested dictionary from a list of runs. :param runs: The list of runs to build the tree from. :return: The nested dictionary representing the langchain Run in a tree     structure compatible with WBTraceTree.\nflatten_run(run)\nUtility to flatten a nest run object into a list of runs.\nmodify_serialized_iterative(runs[,\u00a0...])\nUtility to modify the serialized field of a list of runs dictionaries.\nprocess_model(run)\nUtility to process a run for wandb model_dict serialization.\nprocess_span(run)\nConverts a LangChain Run into a W&B Trace Span.\ntruncate_run_iterative(runs[,\u00a0keep_keys])\nUtility to truncate a list of runs dictionaries to only keep the specified\n__init__(wandb_module: Any, trace_module: Any)[source]\u00b6\nbuild_tree(runs: List[Dict[str, Any]]) \u2192 Dict[str, Any][source]\u00b6\nBuilds a nested dictionary from a list of runs.\n:param runs: The list of runs to build the tree from.\n:return: The nested dictionary representing the langchain Run in a tree\nstructure compatible with WBTraceTree.\nflatten_run(run: Dict[str, Any]) \u2192 List[Dict[str, Any]][source]\u00b6\nUtility to flatten a nest run object into a list of runs.\n:param run: The base run to flatten.\n:return: The flattened list of runs.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.tracers.wandb.RunProcessor.html"}
{"id": "2e93aff842e5-1", "text": ":param run: The base run to flatten.\n:return: The flattened list of runs.\nmodify_serialized_iterative(runs: List[Dict[str, Any]], exact_keys: Tuple[str, ...] = (), partial_keys: Tuple[str, ...] = ()) \u2192 List[Dict[str, Any]][source]\u00b6\nUtility to modify the serialized field of a list of runs dictionaries.\nremoves any keys that match the exact_keys and any keys that contain any of the\npartial_keys.\nrecursively moves the dictionaries under the kwargs key to the top level.\nchanges the \u201cid\u201d field to a string \u201c_kind\u201d field that tells WBTraceTree how to\nvisualize the run. promotes the \u201cserialized\u201d field to the top level.\nParameters\nruns \u2013 The list of runs to modify.\nexact_keys \u2013 A tuple of keys to remove from the serialized field.\npartial_keys \u2013 A tuple of partial keys to remove from the serialized\nfield.\nReturns\nThe modified list of runs.\nprocess_model(run: Run) \u2192 Optional[Dict[str, Any]][source]\u00b6\nUtility to process a run for wandb model_dict serialization.\n:param run: The run to process.\n:return: The convert model_dict to pass to WBTraceTree.\nprocess_span(run: Run) \u2192 Optional['Span'][source]\u00b6\nConverts a LangChain Run into a W&B Trace Span.\n:param run: The LangChain Run to convert.\n:return: The converted W&B Trace Span.\ntruncate_run_iterative(runs: List[Dict[str, Any]], keep_keys: Tuple[str, ...] = ()) \u2192 List[Dict[str, Any]][source]\u00b6\nUtility to truncate a list of runs dictionaries to only keep the specifiedkeys in each run.\nParameters\nruns \u2013 The list of runs to truncate.\nkeep_keys \u2013 The keys to keep in each run.\nReturns", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.tracers.wandb.RunProcessor.html"}
{"id": "2e93aff842e5-2", "text": "keep_keys \u2013 The keys to keep in each run.\nReturns\nThe truncated list of runs.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.tracers.wandb.RunProcessor.html"}
{"id": "d5498e77a4ba-0", "text": "langchain.callbacks.utils.load_json\u00b6\nlangchain.callbacks.utils.load_json(json_path: Union[str, Path]) \u2192 str[source]\u00b6\nLoad json file to a string.\nParameters\njson_path (str) \u2013 The path to the json file.\nReturns\nThe string representation of the json file.\nReturn type\n(str)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.utils.load_json.html"}
{"id": "cece4b1b7e1a-0", "text": "langchain.callbacks.utils.import_spacy\u00b6\nlangchain.callbacks.utils.import_spacy() \u2192 Any[source]\u00b6\nImport the spacy python package and raise an error if it is not installed.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.utils.import_spacy.html"}
{"id": "7e7e58d2a1f0-0", "text": "langchain.callbacks.infino_callback.import_tiktoken\u00b6\nlangchain.callbacks.infino_callback.import_tiktoken() \u2192 Any[source]\u00b6\nImport tiktoken for counting tokens for OpenAI models.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.infino_callback.import_tiktoken.html"}
{"id": "0fd3861ae0f0-0", "text": "langchain.callbacks.comet_ml_callback.CometCallbackHandler\u00b6\nclass langchain.callbacks.comet_ml_callback.CometCallbackHandler(task_type: Optional[str] = 'inference', workspace: Optional[str] = None, project_name: Optional[str] = None, tags: Optional[Sequence] = None, name: Optional[str] = None, visualizations: Optional[List[str]] = None, complexity_metrics: bool = False, custom_metrics: Optional[Callable] = None, stream_logs: bool = True)[source]\u00b6\nCallback Handler that logs to Comet.\nParameters\njob_type (str) \u2013 The type of comet_ml task such as \u201cinference\u201d,\n\u201ctesting\u201d or \u201cqc\u201d\nproject_name (str) \u2013 The comet_ml project name\ntags (list) \u2013 Tags to add to the task\ntask_name (str) \u2013 Name of the comet_ml task\nvisualize (bool) \u2013 Whether to visualize the run.\ncomplexity_metrics (bool) \u2013 Whether to log complexity metrics\nstream_logs (bool) \u2013 Whether to stream callback actions to Comet\nThis handler will utilize the associated callback method and formats\nthe input of each callback function with metadata regarding the state of LLM run,\nand adds the response to the list of records for both the {method}_records and\naction. It then logs the response to Comet.\nInitialize callback handler.\nAttributes\nalways_verbose\nWhether to call verbose callbacks even if verbose is False.\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([task_type,\u00a0workspace,\u00a0...])\nInitialize callback handler.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.comet_ml_callback.CometCallbackHandler.html"}
{"id": "0fd3861ae0f0-1", "text": "__init__([task_type,\u00a0workspace,\u00a0...])\nInitialize callback handler.\nflush_tracker([langchain_asset,\u00a0task_type,\u00a0...])\nFlush the tracker and setup the session.\nget_custom_callback_meta()\non_agent_action(action,\u00a0**kwargs)\nRun on agent action.\non_agent_finish(finish,\u00a0**kwargs)\nRun when agent ends running.\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends running.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0**kwargs)\nRun when LLM generates a new token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when agent is ending.\non_tool_end(output,\u00a0**kwargs)\nRun when tool ends running.\non_tool_error(error,\u00a0**kwargs)\nRun when tool errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.comet_ml_callback.CometCallbackHandler.html"}
{"id": "0fd3861ae0f0-2", "text": "on_tool_error(error,\u00a0**kwargs)\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nRun when tool starts running.\nreset_callback_meta()\nReset the callback metadata.\n__init__(task_type: Optional[str] = 'inference', workspace: Optional[str] = None, project_name: Optional[str] = None, tags: Optional[Sequence] = None, name: Optional[str] = None, visualizations: Optional[List[str]] = None, complexity_metrics: bool = False, custom_metrics: Optional[Callable] = None, stream_logs: bool = True) \u2192 None[source]\u00b6\nInitialize callback handler.\nflush_tracker(langchain_asset: Any = None, task_type: Optional[str] = 'inference', workspace: Optional[str] = None, project_name: Optional[str] = 'comet-langchain-demo', tags: Optional[Sequence] = None, name: Optional[str] = None, visualizations: Optional[List[str]] = None, complexity_metrics: bool = False, custom_metrics: Optional[Callable] = None, finish: bool = False, reset: bool = False) \u2192 None[source]\u00b6\nFlush the tracker and setup the session.\nEverything after this will be a new table.\nParameters\nname \u2013 Name of the performed session so far so it is identifiable\nlangchain_asset \u2013 The langchain asset to save.\nfinish \u2013 Whether to finish the run.\nReturns \u2013 None\nget_custom_callback_meta() \u2192 Dict[str, Any]\u00b6\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent ends running.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.comet_ml_callback.CometCallbackHandler.html"}
{"id": "0fd3861ae0f0-3", "text": "Run when chain ends running.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM generates a new token.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.comet_ml_callback.CometCallbackHandler.html"}
{"id": "0fd3861ae0f0-4", "text": "Run when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent is ending.\non_tool_end(output: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool starts running.\nreset_callback_meta() \u2192 None\u00b6\nReset the callback metadata.\nExamples using CometCallbackHandler\u00b6\nComet", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.comet_ml_callback.CometCallbackHandler.html"}
{"id": "03316a309291-0", "text": "langchain.callbacks.confident_callback.DeepEvalCallbackHandler\u00b6\nclass langchain.callbacks.confident_callback.DeepEvalCallbackHandler(metrics: List[Any], implementation_name: Optional[str] = None)[source]\u00b6\nCallback Handler that logs into deepeval.\nParameters\nimplementation_name \u2013 name of the implementation in deepeval\nmetrics \u2013 A list of metrics\nRaises\nImportError \u2013 if the deepeval package is not installed.\nExamples\n>>> from langchain.llms import OpenAI\n>>> from langchain.callbacks import DeepEvalCallbackHandler\n>>> from deepeval.metrics import AnswerRelevancy\n>>> metric = AnswerRelevancy(minimum_score=0.3)\n>>> deepeval_callback = DeepEvalCallbackHandler(\n...     implementation_name=\"exampleImplementation\",\n...     metrics=[metric],\n... )\n>>> llm = OpenAI(\n...     temperature=0,\n...     callbacks=[deepeval_callback],\n...     verbose=True,\n...     openai_api_key=\"API_KEY_HERE\",\n... )\n>>> llm.generate([\n...     \"What is the best evaluation tool out there? (no bias at all)\",\n... ])\n\"Deepeval, no doubt about it.\"\nInitializes the deepevalCallbackHandler.\nParameters\nimplementation_name \u2013 Name of the implementation you want.\nmetrics \u2013 What metrics do you want to track?\nRaises\nImportError \u2013 if the deepeval package is not installed.\nConnectionError \u2013 if the connection to deepeval fails.\nAttributes\nBLOG_URL\nISSUES_URL\nREPO_URL\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.confident_callback.DeepEvalCallbackHandler.html"}
{"id": "03316a309291-1", "text": "Whether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(metrics[,\u00a0implementation_name])\nInitializes the deepevalCallbackHandler.\non_agent_action(action,\u00a0**kwargs)\nDo nothing when agent takes a specific action.\non_agent_finish(finish,\u00a0**kwargs)\nDo nothing\non_chain_end(outputs,\u00a0**kwargs)\nDo nothing when chain ends.\non_chain_error(error,\u00a0**kwargs)\nDo nothing when LLM chain outputs an error.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nDo nothing when chain starts\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nLog records to deepeval when an LLM ends.\non_llm_error(error,\u00a0**kwargs)\nDo nothing when LLM outputs an error.\non_llm_new_token(token,\u00a0**kwargs)\nDo nothing when a new token is generated.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nStore the prompts\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nDo nothing\non_tool_end(output[,\u00a0observation_prefix,\u00a0...])\nDo nothing when tool ends.\non_tool_error(error,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.confident_callback.DeepEvalCallbackHandler.html"}
{"id": "03316a309291-2", "text": "Do nothing when tool ends.\non_tool_error(error,\u00a0**kwargs)\nDo nothing when tool outputs an error.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nDo nothing when tool starts.\n__init__(metrics: List[Any], implementation_name: Optional[str] = None) \u2192 None[source]\u00b6\nInitializes the deepevalCallbackHandler.\nParameters\nimplementation_name \u2013 Name of the implementation you want.\nmetrics \u2013 What metrics do you want to track?\nRaises\nImportError \u2013 if the deepeval package is not installed.\nConnectionError \u2013 if the connection to deepeval fails.\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nDo nothing when agent takes a specific action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when chain ends.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when LLM chain outputs an error.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when chain starts\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nLog records to deepeval when an LLM ends.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.confident_callback.DeepEvalCallbackHandler.html"}
{"id": "03316a309291-3", "text": "Log records to deepeval when an LLM ends.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when LLM outputs an error.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when a new token is generated.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nStore the prompts\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing\non_tool_end(output: str, observation_prefix: Optional[str] = None, llm_prefix: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool ends.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.confident_callback.DeepEvalCallbackHandler.html"}
{"id": "03316a309291-4", "text": "on_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool outputs an error.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing when tool starts.\nExamples using DeepEvalCallbackHandler\u00b6\nConfident", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.confident_callback.DeepEvalCallbackHandler.html"}
{"id": "3b75fe4d94b0-0", "text": "langchain.callbacks.flyte_callback.FlyteCallbackHandler\u00b6\nclass langchain.callbacks.flyte_callback.FlyteCallbackHandler[source]\u00b6\nThis callback handler that is used within a Flyte task.\nInitialize callback handler.\nAttributes\nalways_verbose\nWhether to call verbose callbacks even if verbose is False.\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__()\nInitialize callback handler.\nget_custom_callback_meta()\non_agent_action(action,\u00a0**kwargs)\nRun on agent action.\non_agent_finish(finish,\u00a0**kwargs)\nRun when agent ends running.\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends running.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0**kwargs)\nRun when LLM generates a new token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.flyte_callback.FlyteCallbackHandler.html"}
{"id": "3b75fe4d94b0-1", "text": "on_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when agent is ending.\non_tool_end(output,\u00a0**kwargs)\nRun when tool ends running.\non_tool_error(error,\u00a0**kwargs)\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nRun when tool starts running.\nreset_callback_meta()\nReset the callback metadata.\n__init__() \u2192 None[source]\u00b6\nInitialize callback handler.\nget_custom_callback_meta() \u2192 Dict[str, Any]\u00b6\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent ends running.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.flyte_callback.FlyteCallbackHandler.html"}
{"id": "3b75fe4d94b0-2", "text": "Run when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM generates a new token.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent is ending.\non_tool_end(output: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.flyte_callback.FlyteCallbackHandler.html"}
{"id": "3b75fe4d94b0-3", "text": "Run when tool ends running.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool starts running.\nreset_callback_meta() \u2192 None\u00b6\nReset the callback metadata.\nExamples using FlyteCallbackHandler\u00b6\nFlyte", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.flyte_callback.FlyteCallbackHandler.html"}
{"id": "10fdc5cff08e-0", "text": "langchain.callbacks.streamlit.streamlit_callback_handler.ToolRecord\u00b6\nclass langchain.callbacks.streamlit.streamlit_callback_handler.ToolRecord(name: str, input_str: str)[source]\u00b6\nThe tool record as a NamedTuple.\nCreate new instance of ToolRecord(name, input_str)\nAttributes\ninput_str\nAlias for field number 1\nname\nAlias for field number 0\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.streamlit_callback_handler.ToolRecord.html"}
{"id": "d4f8cb5e9d9f-0", "text": "langchain.callbacks.whylabs_callback.WhyLabsCallbackHandler\u00b6\nclass langchain.callbacks.whylabs_callback.WhyLabsCallbackHandler(logger: Logger, handler: Any)[source]\u00b6\nCallback Handler for logging to WhyLabs. This callback handler utilizes\nlangkit to extract features from the prompts & responses when interacting with\nan LLM. These features can be used to guardrail, evaluate, and observe interactions\nover time to detect issues relating to hallucinations, prompt engineering,\nor output validation. LangKit is an LLM monitoring toolkit developed by WhyLabs.\nHere are some examples of what can be monitored with LangKit:\n* Text Quality\nreadability score\ncomplexity and grade scores\nText Relevance\n- Similarity scores between prompt/responses\n- Similarity scores against user-defined themes\n- Topic classification\nSecurity and Privacy\n- patterns - count of strings matching a user-defined regex pattern group\n- jailbreaks - similarity scores with respect to known jailbreak attempts\n- prompt injection - similarity scores with respect to known prompt attacks\n- refusals - similarity scores with respect to known LLM refusal responses\nSentiment and Toxicity\n- sentiment analysis\n- toxicity analysis\nFor more information, see https://docs.whylabs.ai/docs/language-model-monitoring\nor check out the LangKit repo here: https://github.com/whylabs/langkit\n\u2014\n:param api_key: WhyLabs API key. Optional because the preferred\nway to specify the API key is with environment variable\nWHYLABS_API_KEY.\nParameters\norg_id (Optional[str]) \u2013 WhyLabs organization id to write profiles to.\nOptional because the preferred way to specify the organization id is\nwith environment variable WHYLABS_DEFAULT_ORG_ID.\ndataset_id (Optional[str]) \u2013 WhyLabs dataset id to write profiles to.\nOptional because the preferred way to specify the dataset id is", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.whylabs_callback.WhyLabsCallbackHandler.html"}
{"id": "d4f8cb5e9d9f-1", "text": "Optional because the preferred way to specify the dataset id is\nwith environment variable WHYLABS_DEFAULT_DATASET_ID.\nsentiment (bool) \u2013 Whether to enable sentiment analysis. Defaults to False.\ntoxicity (bool) \u2013 Whether to enable toxicity analysis. Defaults to False.\nthemes (bool) \u2013 Whether to enable theme analysis. Defaults to False.\nInitiate the rolling logger.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(logger,\u00a0handler)\nInitiate the rolling logger.\nclose()\nClose any loggers to allow writing out of any profiles before exiting.\nflush()\nExplicitly write current profile if using a rolling logger.\nfrom_params(*[,\u00a0api_key,\u00a0org_id,\u00a0...])\nInstantiate whylogs Logger from params.\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain ends running.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM ends running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.whylabs_callback.WhyLabsCallbackHandler.html"}
{"id": "d4f8cb5e9d9f-2", "text": "Run when LLM ends running.\non_llm_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM errors.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool ends running.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\n__init__(logger: Logger, handler: Any)[source]\u00b6\nInitiate the rolling logger.\nclose() \u2192 None[source]\u00b6\nClose any loggers to allow writing out of any profiles before exiting.\nflush() \u2192 None[source]\u00b6\nExplicitly write current profile if using a rolling logger.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.whylabs_callback.WhyLabsCallbackHandler.html"}
{"id": "d4f8cb5e9d9f-3", "text": "flush() \u2192 None[source]\u00b6\nExplicitly write current profile if using a rolling logger.\nclassmethod from_params(*, api_key: Optional[str] = None, org_id: Optional[str] = None, dataset_id: Optional[str] = None, sentiment: bool = False, toxicity: bool = False, themes: bool = False, logger: Optional[Logger] = None) \u2192 WhyLabsCallbackHandler[source]\u00b6\nInstantiate whylogs Logger from params.\nParameters\napi_key (Optional[str]) \u2013 WhyLabs API key. Optional because the preferred\nway to specify the API key is with environment variable\nWHYLABS_API_KEY.\norg_id (Optional[str]) \u2013 WhyLabs organization id to write profiles to.\nIf not set must be specified in environment variable\nWHYLABS_DEFAULT_ORG_ID.\ndataset_id (Optional[str]) \u2013 The model or dataset this callback is gathering\ntelemetry for. If not set must be specified in environment variable\nWHYLABS_DEFAULT_DATASET_ID.\nsentiment (bool) \u2013 If True will initialize a model to perform\nsentiment analysis compound score. Defaults to False and will not gather\nthis metric.\ntoxicity (bool) \u2013 If True will initialize a model to score\ntoxicity. Defaults to False and will not gather this metric.\nthemes (bool) \u2013 If True will initialize a model to calculate\ndistance to configured themes. Defaults to None and will not gather this\nmetric.\nlogger (Optional[Logger]) \u2013 If specified will bind the configured logger as\nthe telemetry gathering agent. Defaults to LangKit schema with periodic\nWhyLabs writer.\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.whylabs_callback.WhyLabsCallbackHandler.html"}
{"id": "d4f8cb5e9d9f-4", "text": "Run on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.whylabs_callback.WhyLabsCallbackHandler.html"}
{"id": "d4f8cb5e9d9f-5", "text": "Run when LLM errors.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on new LLM token. Only available when streaming is enabled.\nParameters\ntoken (str) \u2013 The new token.\nchunk (GenerationChunk | ChatGenerationChunk) \u2013 The new generated chunk,\ninformation. (containing content and other) \u2013 \non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM starts running.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.whylabs_callback.WhyLabsCallbackHandler.html"}
{"id": "d4f8cb5e9d9f-6", "text": "Run on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool starts running.\nExamples using WhyLabsCallbackHandler\u00b6\nWhyLabs", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.whylabs_callback.WhyLabsCallbackHandler.html"}
{"id": "ff7fea5735b4-0", "text": "langchain.callbacks.arize_callback.ArizeCallbackHandler\u00b6\nclass langchain.callbacks.arize_callback.ArizeCallbackHandler(model_id: Optional[str] = None, model_version: Optional[str] = None, SPACE_KEY: Optional[str] = None, API_KEY: Optional[str] = None)[source]\u00b6\nCallback Handler that logs to Arize.\nInitialize callback handler.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([model_id,\u00a0model_version,\u00a0...])\nInitialize callback handler.\non_agent_action(action,\u00a0**kwargs)\nDo nothing.\non_agent_finish(finish,\u00a0**kwargs)\nRun on agent end.\non_chain_end(outputs,\u00a0**kwargs)\nDo nothing.\non_chain_error(error,\u00a0**kwargs)\nDo nothing.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nDo nothing.\non_llm_new_token(token,\u00a0**kwargs)\nDo nothing.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.arize_callback.ArizeCallbackHandler.html"}
{"id": "ff7fea5735b4-1", "text": "on_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun on arbitrary text.\non_tool_end(output[,\u00a0observation_prefix,\u00a0...])\nRun when tool ends running.\non_tool_error(error,\u00a0**kwargs)\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nRun when tool starts running.\n__init__(model_id: Optional[str] = None, model_version: Optional[str] = None, SPACE_KEY: Optional[str] = None, API_KEY: Optional[str] = None) \u2192 None[source]\u00b6\nInitialize callback handler.\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nDo nothing.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.arize_callback.ArizeCallbackHandler.html"}
{"id": "ff7fea5735b4-2", "text": "Run when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts running.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun on arbitrary text.\non_tool_end(output: str, observation_prefix: Optional[str] = None, llm_prefix: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.arize_callback.ArizeCallbackHandler.html"}
{"id": "ff7fea5735b4-3", "text": "Run when tool ends running.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool starts running.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.arize_callback.ArizeCallbackHandler.html"}
{"id": "e05b145a1c82-0", "text": "langchain.callbacks.utils.flatten_dict\u00b6\nlangchain.callbacks.utils.flatten_dict(nested_dict: Dict[str, Any], parent_key: str = '', sep: str = '_') \u2192 Dict[str, Any][source]\u00b6\nFlattens a nested dictionary into a flat dictionary.\nParameters\nnested_dict (dict) \u2013 The nested dictionary to flatten.\nparent_key (str) \u2013 The prefix to prepend to the keys of the flattened dict.\nsep (str) \u2013 The separator to use between the parent key and the key of the\nflattened dictionary.\nReturns\nA flat dictionary.\nReturn type\n(dict)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.utils.flatten_dict.html"}
{"id": "ae690b35d83c-0", "text": "langchain.callbacks.wandb_callback.load_json_to_dict\u00b6\nlangchain.callbacks.wandb_callback.load_json_to_dict(json_path: Union[str, Path]) \u2192 dict[source]\u00b6\nLoad json file to a dictionary.\nParameters\njson_path (str) \u2013 The path to the json file.\nReturns\nThe dictionary representation of the json file.\nReturn type\n(dict)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.wandb_callback.load_json_to_dict.html"}
{"id": "82b4b80b63cb-0", "text": "langchain.callbacks.sagemaker_callback.save_json\u00b6\nlangchain.callbacks.sagemaker_callback.save_json(data: dict, file_path: str) \u2192 None[source]\u00b6\nSave dict to local file path.\nParameters\ndata (dict) \u2013 The dictionary to be saved.\nfile_path (str) \u2013 Local file path.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.sagemaker_callback.save_json.html"}
{"id": "43986cef3d14-0", "text": "langchain.callbacks.labelstudio_callback.get_default_label_configs\u00b6\nlangchain.callbacks.labelstudio_callback.get_default_label_configs(mode: Union[str, LabelStudioMode]) \u2192 Tuple[str, LabelStudioMode][source]\u00b6\nGet default Label Studio configs for the given mode.\nParameters\nmode \u2013 Label Studio mode (\u201cprompt\u201d or \u201cchat\u201d)\nReturns: Tuple of Label Studio config and mode", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.labelstudio_callback.get_default_label_configs.html"}
{"id": "95072554716c-0", "text": "langchain.callbacks.streamlit.mutable_expander.ChildRecord\u00b6\nclass langchain.callbacks.streamlit.mutable_expander.ChildRecord(type: ChildType, kwargs: Dict[str, Any], dg: DeltaGenerator)[source]\u00b6\nThe child record as a NamedTuple.\nCreate new instance of ChildRecord(type, kwargs, dg)\nAttributes\ndg\nAlias for field number 2\nkwargs\nAlias for field number 1\ntype\nAlias for field number 0\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.mutable_expander.ChildRecord.html"}
{"id": "efe25b00706f-0", "text": "langchain.callbacks.flyte_callback.analyze_text\u00b6\nlangchain.callbacks.flyte_callback.analyze_text(text: str, nlp: Any = None, textstat: Any = None) \u2192 dict[source]\u00b6\nAnalyze text using textstat and spacy.\nParameters\ntext (str) \u2013 The text to analyze.\nnlp (spacy.lang) \u2013 The spacy language model to use for visualization.\nReturns\nA dictionary containing the complexity metrics and visualizationfiles serialized to HTML string.\nReturn type\n(dict)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.flyte_callback.analyze_text.html"}
{"id": "9e5d44fdb82c-0", "text": "langchain.callbacks.mlflow_callback.analyze_text\u00b6\nlangchain.callbacks.mlflow_callback.analyze_text(text: str, nlp: Any = None) \u2192 dict[source]\u00b6\nAnalyze text using textstat and spacy.\nParameters\ntext (str) \u2013 The text to analyze.\nnlp (spacy.lang) \u2013 The spacy language model to use for visualization.\nReturns\nA dictionary containing the complexity metrics and visualizationfiles serialized to  HTML string.\nReturn type\n(dict)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.mlflow_callback.analyze_text.html"}
{"id": "752aa56e88d6-0", "text": "langchain.callbacks.streamlit.streamlit_callback_handler.LLMThought\u00b6\nclass langchain.callbacks.streamlit.streamlit_callback_handler.LLMThought(parent_container: DeltaGenerator, labeler: LLMThoughtLabeler, expanded: bool, collapse_on_complete: bool)[source]\u00b6\nA thought in the LLM\u2019s thought stream.\nInitialize the LLMThought.\nParameters\nparent_container \u2013 The container we\u2019re writing into.\nlabeler \u2013 The labeler to use for this thought.\nexpanded \u2013 Whether the thought should be expanded by default.\ncollapse_on_complete \u2013 Whether the thought should be collapsed.\nAttributes\ncontainer\nThe container we're writing into.\nlast_tool\nThe last tool executed by this thought\nMethods\n__init__(parent_container,\u00a0labeler,\u00a0...)\nInitialize the LLMThought.\nclear()\nRemove the thought from the screen.\ncomplete([final_label])\nFinish the thought.\non_agent_action(action[,\u00a0color])\non_llm_end(response,\u00a0**kwargs)\non_llm_error(error,\u00a0**kwargs)\non_llm_new_token(token,\u00a0**kwargs)\non_llm_start(serialized,\u00a0prompts)\non_tool_end(output[,\u00a0color,\u00a0...])\non_tool_error(error,\u00a0**kwargs)\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\n__init__(parent_container: DeltaGenerator, labeler: LLMThoughtLabeler, expanded: bool, collapse_on_complete: bool)[source]\u00b6\nInitialize the LLMThought.\nParameters\nparent_container \u2013 The container we\u2019re writing into.\nlabeler \u2013 The labeler to use for this thought.\nexpanded \u2013 Whether the thought should be expanded by default.\ncollapse_on_complete \u2013 Whether the thought should be collapsed.\nclear() \u2192 None[source]\u00b6\nRemove the thought from the screen. A cleared thought can\u2019t be reused.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.streamlit_callback_handler.LLMThought.html"}
{"id": "752aa56e88d6-1", "text": "Remove the thought from the screen. A cleared thought can\u2019t be reused.\ncomplete(final_label: Optional[str] = None) \u2192 None[source]\u00b6\nFinish the thought.\non_agent_action(action: AgentAction, color: Optional[str] = None, **kwargs: Any) \u2192 Any[source]\u00b6\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\non_llm_start(serialized: Dict[str, Any], prompts: List[str]) \u2192 None[source]\u00b6\non_tool_end(output: str, color: Optional[str] = None, observation_prefix: Optional[str] = None, llm_prefix: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.streamlit.streamlit_callback_handler.LLMThought.html"}
{"id": "71af466c2df6-0", "text": "langchain.callbacks.wandb_callback.construct_html_from_prompt_and_generation\u00b6\nlangchain.callbacks.wandb_callback.construct_html_from_prompt_and_generation(prompt: str, generation: str) \u2192 Any[source]\u00b6\nConstruct an html element from a prompt and a generation.\nParameters\nprompt (str) \u2013 The prompt.\ngeneration (str) \u2013 The generation.\nReturns\nThe html element.\nReturn type\n(wandb.Html)", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.wandb_callback.construct_html_from_prompt_and_generation.html"}
{"id": "81c0d90d073c-0", "text": "langchain.callbacks.clearml_callback.ClearMLCallbackHandler\u00b6\nclass langchain.callbacks.clearml_callback.ClearMLCallbackHandler(task_type: Optional[str] = 'inference', project_name: Optional[str] = 'langchain_callback_demo', tags: Optional[Sequence] = None, task_name: Optional[str] = None, visualize: bool = False, complexity_metrics: bool = False, stream_logs: bool = False)[source]\u00b6\nCallback Handler that logs to ClearML.\nParameters\njob_type (str) \u2013 The type of clearml task such as \u201cinference\u201d, \u201ctesting\u201d or \u201cqc\u201d\nproject_name (str) \u2013 The clearml project name\ntags (list) \u2013 Tags to add to the task\ntask_name (str) \u2013 Name of the clearml task\nvisualize (bool) \u2013 Whether to visualize the run.\ncomplexity_metrics (bool) \u2013 Whether to log complexity metrics\nstream_logs (bool) \u2013 Whether to stream callback actions to ClearML\nThis handler will utilize the associated callback method and formats\nthe input of each callback function with metadata regarding the state of LLM run,\nand adds the response to the list of records for both the {method}_records and\naction. It then logs the response to the ClearML console.\nInitialize callback handler.\nAttributes\nalways_verbose\nWhether to call verbose callbacks even if verbose is False.\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([task_type,\u00a0project_name,\u00a0tags,\u00a0...])\nInitialize callback handler.\nanalyze_text(text)\nAnalyze text using textstat and spacy.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.clearml_callback.ClearMLCallbackHandler.html"}
{"id": "81c0d90d073c-1", "text": "analyze_text(text)\nAnalyze text using textstat and spacy.\nflush_tracker([name,\u00a0langchain_asset,\u00a0finish])\nFlush the tracker and setup the session.\nget_custom_callback_meta()\non_agent_action(action,\u00a0**kwargs)\nRun on agent action.\non_agent_finish(finish,\u00a0**kwargs)\nRun when agent ends running.\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends running.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0**kwargs)\nRun when LLM generates a new token.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when agent is ending.\non_tool_end(output,\u00a0**kwargs)\nRun when tool ends running.\non_tool_error(error,\u00a0**kwargs)\nRun when tool errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.clearml_callback.ClearMLCallbackHandler.html"}
{"id": "81c0d90d073c-2", "text": "on_tool_error(error,\u00a0**kwargs)\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nRun when tool starts running.\nreset_callback_meta()\nReset the callback metadata.\n__init__(task_type: Optional[str] = 'inference', project_name: Optional[str] = 'langchain_callback_demo', tags: Optional[Sequence] = None, task_name: Optional[str] = None, visualize: bool = False, complexity_metrics: bool = False, stream_logs: bool = False) \u2192 None[source]\u00b6\nInitialize callback handler.\nanalyze_text(text: str) \u2192 dict[source]\u00b6\nAnalyze text using textstat and spacy.\nParameters\ntext (str) \u2013 The text to analyze.\nReturns\nA dictionary containing the complexity metrics.\nReturn type\n(dict)\nflush_tracker(name: Optional[str] = None, langchain_asset: Any = None, finish: bool = False) \u2192 None[source]\u00b6\nFlush the tracker and setup the session.\nEverything after this will be a new table.\nParameters\nname \u2013 Name of the performed session so far so it is identifiable\nlangchain_asset \u2013 The langchain asset to save.\nfinish \u2013 Whether to finish the run.\nReturns \u2013 None\nget_custom_callback_meta() \u2192 Dict[str, Any]\u00b6\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent ends running.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.clearml_callback.ClearMLCallbackHandler.html"}
{"id": "81c0d90d073c-3", "text": "Run when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM generates a new token.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.clearml_callback.ClearMLCallbackHandler.html"}
{"id": "81c0d90d073c-4", "text": "Run when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent is ending.\non_tool_end(output: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool starts running.\nreset_callback_meta() \u2192 None\u00b6\nReset the callback metadata.\nExamples using ClearMLCallbackHandler\u00b6\nClearML", "source": "lang/api.python.langchain.com/en/latest/callbacks/langchain.callbacks.clearml_callback.ClearMLCallbackHandler.html"}
{"id": "356e2cfe11ce-0", "text": "Source code for typing\n\"\"\"\nThe typing module: Support for gradual typing as defined by PEP 484 and subsequent PEPs.\nAmong other things, the module includes the following:\n* Generic, Protocol, and internal machinery to support generic aliases.\n  All subscripted types like X[int], Union[int, str] are generic aliases.\n* Various \"special forms\" that have unique meanings in type annotations:\n  NoReturn, Never, ClassVar, Self, Concatenate, Unpack, and others.\n* Classes whose instances can be type arguments to generic classes and functions:\n  TypeVar, ParamSpec, TypeVarTuple.\n* Public helper functions: get_type_hints, overload, cast, final, and others.\n* Several protocols to support duck-typing:\n  SupportsFloat, SupportsIndex, SupportsAbs, and others.\n* Special types: NewType, NamedTuple, TypedDict.\n* Deprecated wrapper submodules for re and io related types.\n* Deprecated aliases for builtin types and collections.abc ABCs.\nAny name not present in __all__ is an implementation detail\nthat may be changed without notice. Use at your own risk!\n\"\"\"\nfrom abc import abstractmethod, ABCMeta\nimport collections\nfrom collections import defaultdict\nimport collections.abc\nimport contextlib\nimport functools\nimport operator\nimport re as stdlib_re  # Avoid confusion with the re we export.\nimport sys\nimport types\nimport warnings\nfrom types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType, GenericAlias\ntry:\n    from _typing import _idfunc\nexcept ImportError:\n    def _idfunc(_, x):\n        return x\n# Please keep __all__ alphabetized within each category.\n__all__ = [\n    # Super-special typing primitives.\n    'Annotated',\n    'Any',\n    'Callable',", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-1", "text": "'Annotated',\n    'Any',\n    'Callable',\n    'ClassVar',\n    'Concatenate',\n    'Final',\n    'ForwardRef',\n    'Generic',\n    'Literal',\n    'Optional',\n    'ParamSpec',\n    'Protocol',\n    'Tuple',\n    'Type',\n    'TypeVar',\n    'TypeVarTuple',\n    'Union',\n    # ABCs (from collections.abc).\n    'AbstractSet',  # collections.abc.Set.\n    'ByteString',\n    'Container',\n    'ContextManager',\n    'Hashable',\n    'ItemsView',\n    'Iterable',\n    'Iterator',\n    'KeysView',\n    'Mapping',\n    'MappingView',\n    'MutableMapping',\n    'MutableSequence',\n    'MutableSet',\n    'Sequence',\n    'Sized',\n    'ValuesView',\n    'Awaitable',\n    'AsyncIterator',\n    'AsyncIterable',\n    'Coroutine',\n    'Collection',\n    'AsyncGenerator',\n    'AsyncContextManager',\n    # Structural checks, a.k.a. protocols.\n    'Reversible',\n    'SupportsAbs',\n    'SupportsBytes',\n    'SupportsComplex',\n    'SupportsFloat',\n    'SupportsIndex',\n    'SupportsInt',\n    'SupportsRound',\n    # Concrete collection types.\n    'ChainMap',\n    'Counter',\n    'Deque',\n    'Dict',\n    'DefaultDict',\n    'List',\n    'OrderedDict',\n    'Set',\n    'FrozenSet',\n    'NamedTuple',  # Not really a type.\n    'TypedDict',  # Not really a type.", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-2", "text": "'TypedDict',  # Not really a type.\n    'Generator',\n    # Other concrete types.\n    'BinaryIO',\n    'IO',\n    'Match',\n    'Pattern',\n    'TextIO',\n    # One-off things.\n    'AnyStr',\n    'assert_type',\n    'assert_never',\n    'cast',\n    'clear_overloads',\n    'dataclass_transform',\n    'final',\n    'get_args',\n    'get_origin',\n    'get_overloads',\n    'get_type_hints',\n    'is_typeddict',\n    'LiteralString',\n    'Never',\n    'NewType',\n    'no_type_check',\n    'no_type_check_decorator',\n    'NoReturn',\n    'NotRequired',\n    'overload',\n    'ParamSpecArgs',\n    'ParamSpecKwargs',\n    'Required',\n    'reveal_type',\n    'runtime_checkable',\n    'Self',\n    'Text',\n    'TYPE_CHECKING',\n    'TypeAlias',\n    'TypeGuard',\n    'Unpack',\n]\n# The pseudo-submodules 're' and 'io' are part of the public\n# namespace, but excluded from __all__ because they might stomp on\n# legitimate imports of those modules.\ndef _type_convert(arg, module=None, *, allow_special_forms=False):\n    \"\"\"For converting None to type(None), and strings to ForwardRef.\"\"\"\n    if arg is None:\n        return type(None)\n    if isinstance(arg, str):\n        return ForwardRef(arg, module=module, is_class=allow_special_forms)\n    return arg\ndef _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=False):", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-3", "text": "\"\"\"Check that the argument is a type, and return it (internal helper).\n    As a special case, accept None and return type(None) instead. Also wrap strings\n    into ForwardRef instances. Consider several corner cases, for example plain\n    special forms like Union are not valid, while Union[int, str] is OK, etc.\n    The msg argument is a human-readable error message, e.g.::\n        \"Union[arg, ...]: arg should be a type.\"\n    We append the repr() of the actual value (truncated to 100 chars).\n    \"\"\"\n    invalid_generic_forms = (Generic, Protocol)\n    if not allow_special_forms:\n        invalid_generic_forms += (ClassVar,)\n        if is_argument:\n            invalid_generic_forms += (Final,)\n    arg = _type_convert(arg, module=module, allow_special_forms=allow_special_forms)\n    if (isinstance(arg, _GenericAlias) and\n            arg.__origin__ in invalid_generic_forms):\n        raise TypeError(f\"{arg} is not valid as type argument\")\n    if arg in (Any, LiteralString, NoReturn, Never, Self, TypeAlias):\n        return arg\n    if allow_special_forms and arg in (ClassVar, Final):\n        return arg\n    if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):\n        raise TypeError(f\"Plain {arg} is not valid as type argument\")\n    if type(arg) is tuple:\n        raise TypeError(f\"{msg} Got {arg!r:.100}.\")\n    return arg\ndef _is_param_expr(arg):\n    return arg is ... or isinstance(arg,\n            (tuple, list, ParamSpec, _ConcatenateGenericAlias))\ndef _should_unflatten_callable_args(typ, args):", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-4", "text": "def _should_unflatten_callable_args(typ, args):\n    \"\"\"Internal helper for munging collections.abc.Callable's __args__.\n    The canonical representation for a Callable's __args__ flattens the\n    argument types, see https://github.com/python/cpython/issues/86361.\n    For example::\n        assert collections.abc.Callable[[int, int], str].__args__ == (int, int, str)\n        assert collections.abc.Callable[ParamSpec, str].__args__ == (ParamSpec, str)\n    As a result, if we need to reconstruct the Callable from its __args__,\n    we need to unflatten it.\n    \"\"\"\n    return (\n        typ.__origin__ is collections.abc.Callable\n        and not (len(args) == 2 and _is_param_expr(args[0]))\n    )\ndef _type_repr(obj):\n    \"\"\"Return the repr() of an object, special-casing types (internal helper).\n    If obj is a type, we return a shorter version than the default\n    type.__repr__, based on the module and qualified name, which is\n    typically enough to uniquely identify a type.  For everything\n    else, we fall back on repr(obj).\n    \"\"\"\n    if isinstance(obj, types.GenericAlias):\n        return repr(obj)\n    if isinstance(obj, type):\n        if obj.__module__ == 'builtins':\n            return obj.__qualname__\n        return f'{obj.__module__}.{obj.__qualname__}'\n    if obj is ...:\n        return('...')\n    if isinstance(obj, types.FunctionType):\n        return obj.__name__\n    return repr(obj)\ndef _collect_parameters(args):\n    \"\"\"Collect all type variables and parameter specifications in args\n    in order of first appearance (lexicographic order).", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-5", "text": "in order of first appearance (lexicographic order).\n    For example::\n        assert _collect_parameters((T, Callable[P, T])) == (T, P)\n    \"\"\"\n    parameters = []\n    for t in args:\n        if isinstance(t, type):\n            # We don't want __parameters__ descriptor of a bare Python class.\n            pass\n        elif isinstance(t, tuple):\n            # `t` might be a tuple, when `ParamSpec` is substituted with\n            # `[T, int]`, or `[int, *Ts]`, etc.\n            for x in t:\n                for collected in _collect_parameters([x]):\n                    if collected not in parameters:\n                        parameters.append(collected)\n        elif hasattr(t, '__typing_subst__'):\n            if t not in parameters:\n                parameters.append(t)\n        else:\n            for x in getattr(t, '__parameters__', ()):\n                if x not in parameters:\n                    parameters.append(x)\n    return tuple(parameters)\ndef _check_generic(cls, parameters, elen):\n    \"\"\"Check correct count for parameters of a generic cls (internal helper).\n    This gives a nice error message in case of count mismatch.\n    \"\"\"\n    if not elen:\n        raise TypeError(f\"{cls} is not a generic class\")\n    alen = len(parameters)\n    if alen != elen:\n        raise TypeError(f\"Too {'many' if alen > elen else 'few'} arguments for {cls};\"\n                        f\" actual {alen}, expected {elen}\")\ndef _unpack_args(args):\n    newargs = []\n    for arg in args:\n        subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-6", "text": "subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)\n        if subargs is not None and not (subargs and subargs[-1] is ...):\n            newargs.extend(subargs)\n        else:\n            newargs.append(arg)\n    return newargs\ndef _deduplicate(params):\n    # Weed out strict duplicates, preserving the first of each occurrence.\n    all_params = set(params)\n    if len(all_params) < len(params):\n        new_params = []\n        for t in params:\n            if t in all_params:\n                new_params.append(t)\n                all_params.remove(t)\n        params = new_params\n        assert not all_params, all_params\n    return params\ndef _remove_dups_flatten(parameters):\n    \"\"\"Internal helper for Union creation and substitution.\n    Flatten Unions among parameters, then remove duplicates.\n    \"\"\"\n    # Flatten out Union[Union[...], ...].\n    params = []\n    for p in parameters:\n        if isinstance(p, (_UnionGenericAlias, types.UnionType)):\n            params.extend(p.__args__)\n        else:\n            params.append(p)\n    return tuple(_deduplicate(params))\ndef _flatten_literal_params(parameters):\n    \"\"\"Internal helper for Literal creation: flatten Literals among parameters.\"\"\"\n    params = []\n    for p in parameters:\n        if isinstance(p, _LiteralGenericAlias):\n            params.extend(p.__args__)\n        else:\n            params.append(p)\n    return tuple(params)\n_cleanups = []\ndef _tp_cache(func=None, /, *, typed=False):\n    \"\"\"Internal wrapper caching __getitem__ of generic types.\n    For non-hashable arguments, the original function is used as a fallback.\n    \"\"\"\n    def decorator(func):", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-7", "text": "\"\"\"\n    def decorator(func):\n        cached = functools.lru_cache(typed=typed)(func)\n        _cleanups.append(cached.cache_clear)\n        @functools.wraps(func)\n        def inner(*args, **kwds):\n            try:\n                return cached(*args, **kwds)\n            except TypeError:\n                pass  # All real errors (not unhashable args) are raised below.\n            return func(*args, **kwds)\n        return inner\n    if func is not None:\n        return decorator(func)\n    return decorator\ndef _eval_type(t, globalns, localns, recursive_guard=frozenset()):\n    \"\"\"Evaluate all forward references in the given type t.\n    For use of globalns and localns see the docstring for get_type_hints().\n    recursive_guard is used to prevent infinite recursion with a recursive\n    ForwardRef.\n    \"\"\"\n    if isinstance(t, ForwardRef):\n        return t._evaluate(globalns, localns, recursive_guard)\n    if isinstance(t, (_GenericAlias, GenericAlias, types.UnionType)):\n        if isinstance(t, GenericAlias):\n            args = tuple(\n                ForwardRef(arg) if isinstance(arg, str) else arg\n                for arg in t.__args__\n            )\n            is_unpacked = t.__unpacked__\n            if _should_unflatten_callable_args(t, args):\n                t = t.__origin__[(args[:-1], args[-1])]\n            else:\n                t = t.__origin__[args]\n            if is_unpacked:\n                t = Unpack[t]\n        ev_args = tuple(_eval_type(a, globalns, localns, recursive_guard) for a in t.__args__)\n        if ev_args == t.__args__:\n            return t", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-8", "text": "if ev_args == t.__args__:\n            return t\n        if isinstance(t, GenericAlias):\n            return GenericAlias(t.__origin__, ev_args)\n        if isinstance(t, types.UnionType):\n            return functools.reduce(operator.or_, ev_args)\n        else:\n            return t.copy_with(ev_args)\n    return t\nclass _Final:\n    \"\"\"Mixin to prohibit subclassing.\"\"\"\n    __slots__ = ('__weakref__',)\n    def __init_subclass__(cls, /, *args, **kwds):\n        if '_root' not in kwds:\n            raise TypeError(\"Cannot subclass special typing classes\")\nclass _Immutable:\n    \"\"\"Mixin to indicate that object should not be copied.\"\"\"\n    __slots__ = ()\n    def __copy__(self):\n        return self\n    def __deepcopy__(self, memo):\n        return self\nclass _NotIterable:\n    \"\"\"Mixin to prevent iteration, without being compatible with Iterable.\n    That is, we could do::\n        def __iter__(self): raise TypeError()\n    But this would make users of this mixin duck type-compatible with\n    collections.abc.Iterable - isinstance(foo, Iterable) would be True.\n    Luckily, we can instead prevent iteration by setting __iter__ to None, which\n    is treated specially.\n    \"\"\"\n    __slots__ = ()\n    __iter__ = None\n# Internal indicator of special typing constructs.\n# See __doc__ instance attribute for specific docs.\nclass _SpecialForm(_Final, _NotIterable, _root=True):\n    __slots__ = ('_name', '__doc__', '_getitem')\n    def __init__(self, getitem):\n        self._getitem = getitem\n        self._name = getitem.__name__\n        self.__doc__ = getitem.__doc__", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-9", "text": "self.__doc__ = getitem.__doc__\n    def __getattr__(self, item):\n        if item in {'__name__', '__qualname__'}:\n            return self._name\n        raise AttributeError(item)\n    def __mro_entries__(self, bases):\n        raise TypeError(f\"Cannot subclass {self!r}\")\n    def __repr__(self):\n        return 'typing.' + self._name\n    def __reduce__(self):\n        return self._name\n    def __call__(self, *args, **kwds):\n        raise TypeError(f\"Cannot instantiate {self!r}\")\n    def __or__(self, other):\n        return Union[self, other]\n    def __ror__(self, other):\n        return Union[other, self]\n    def __instancecheck__(self, obj):\n        raise TypeError(f\"{self} cannot be used with isinstance()\")\n    def __subclasscheck__(self, cls):\n        raise TypeError(f\"{self} cannot be used with issubclass()\")\n    @_tp_cache\n    def __getitem__(self, parameters):\n        return self._getitem(self, parameters)\nclass _LiteralSpecialForm(_SpecialForm, _root=True):\n    def __getitem__(self, parameters):\n        if not isinstance(parameters, tuple):\n            parameters = (parameters,)\n        return self._getitem(self, *parameters)\nclass _AnyMeta(type):\n    def __instancecheck__(self, obj):\n        if self is Any:\n            raise TypeError(\"typing.Any cannot be used with isinstance()\")\n        return super().__instancecheck__(obj)\n    def __repr__(self):\n        if self is Any:\n            return \"typing.Any\"\n        return super().__repr__()  # respect to subclasses\nclass Any(metaclass=_AnyMeta):", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-10", "text": "class Any(metaclass=_AnyMeta):\n    \"\"\"Special type indicating an unconstrained type.\n    - Any is compatible with every type.\n    - Any assumed to have all methods.\n    - All values assumed to be instances of Any.\n    Note that all the above statements are true from the point of view of\n    static type checkers. At runtime, Any should not be used with instance\n    checks.\n    \"\"\"\n    def __new__(cls, *args, **kwargs):\n        if cls is Any:\n            raise TypeError(\"Any cannot be instantiated\")\n        return super().__new__(cls, *args, **kwargs)\n@_SpecialForm\ndef NoReturn(self, parameters):\n    \"\"\"Special type indicating functions that never return.\n    Example::\n        from typing import NoReturn\n        def stop() -> NoReturn:\n            raise Exception('no way')\n    NoReturn can also be used as a bottom type, a type that\n    has no values. Starting in Python 3.11, the Never type should\n    be used for this concept instead. Type checkers should treat the two\n    equivalently.\n    \"\"\"\n    raise TypeError(f\"{self} is not subscriptable\")\n# This is semantically identical to NoReturn, but it is implemented\n# separately so that type checkers can distinguish between the two\n# if they want.\n@_SpecialForm\ndef Never(self, parameters):\n    \"\"\"The bottom type, a type that has no members.\n    This can be used to define a function that should never be\n    called, or a function that never returns::\n        from typing import Never\n        def never_call_me(arg: Never) -> None:\n            pass\n        def int_or_str(arg: int | str) -> None:\n            never_call_me(arg)  # type checker error", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-11", "text": "never_call_me(arg)  # type checker error\n            match arg:\n                case int():\n                    print(\"It's an int\")\n                case str():\n                    print(\"It's a str\")\n                case _:\n                    never_call_me(arg)  # OK, arg is of type Never\n    \"\"\"\n    raise TypeError(f\"{self} is not subscriptable\")\n@_SpecialForm\ndef Self(self, parameters):\n    \"\"\"Used to spell the type of \"self\" in classes.\n    Example::\n        from typing import Self\n        class Foo:\n            def return_self(self) -> Self:\n                ...\n                return self\n    This is especially useful for:\n        - classmethods that are used as alternative constructors\n        - annotating an `__enter__` method which returns self\n    \"\"\"\n    raise TypeError(f\"{self} is not subscriptable\")\n@_SpecialForm\ndef LiteralString(self, parameters):\n    \"\"\"Represents an arbitrary literal string.\n    Example::\n        from typing import LiteralString\n        def run_query(sql: LiteralString) -> None:\n            ...\n        def caller(arbitrary_string: str, literal_string: LiteralString) -> None:\n            run_query(\"SELECT * FROM students\")  # OK\n            run_query(literal_string)  # OK\n            run_query(\"SELECT * FROM \" + literal_string)  # OK\n            run_query(arbitrary_string)  # type checker error\n            run_query(  # type checker error\n                f\"SELECT * FROM students WHERE name = {arbitrary_string}\"\n            )\n    Only string literals and other LiteralStrings are compatible\n    with LiteralString. This provides a tool to help prevent\n    security issues such as SQL injection.\n    \"\"\"\n    raise TypeError(f\"{self} is not subscriptable\")\n@_SpecialForm", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-12", "text": "raise TypeError(f\"{self} is not subscriptable\")\n@_SpecialForm\ndef ClassVar(self, parameters):\n    \"\"\"Special type construct to mark class variables.\n    An annotation wrapped in ClassVar indicates that a given\n    attribute is intended to be used as a class variable and\n    should not be set on instances of that class.\n    Usage::\n        class Starship:\n            stats: ClassVar[dict[str, int]] = {} # class variable\n            damage: int = 10                     # instance variable\n    ClassVar accepts only types and cannot be further subscribed.\n    Note that ClassVar is not a class itself, and should not\n    be used with isinstance() or issubclass().\n    \"\"\"\n    item = _type_check(parameters, f'{self} accepts only single type.')\n    return _GenericAlias(self, (item,))\n@_SpecialForm\ndef Final(self, parameters):\n    \"\"\"Special typing construct to indicate final names to type checkers.\n    A final name cannot be re-assigned or overridden in a subclass.\n    For example::\n        MAX_SIZE: Final = 9000\n        MAX_SIZE += 1  # Error reported by type checker\n        class Connection:\n            TIMEOUT: Final[int] = 10\n        class FastConnector(Connection):\n            TIMEOUT = 1  # Error reported by type checker\n    There is no runtime checking of these properties.\n    \"\"\"\n    item = _type_check(parameters, f'{self} accepts only single type.')\n    return _GenericAlias(self, (item,))\n@_SpecialForm\ndef Union(self, parameters):\n    \"\"\"Union type; Union[X, Y] means either X or Y.\n    On Python 3.10 and higher, the | operator\n    can also be used to denote unions;", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-13", "text": "can also be used to denote unions;\n    X | Y means the same thing to the type checker as Union[X, Y].\n    To define a union, use e.g. Union[int, str]. Details:\n    - The arguments must be types and there must be at least one.\n    - None as an argument is a special case and is replaced by\n      type(None).\n    - Unions of unions are flattened, e.g.::\n        assert Union[Union[int, str], float] == Union[int, str, float]\n    - Unions of a single argument vanish, e.g.::\n        assert Union[int] == int  # The constructor actually returns int\n    - Redundant arguments are skipped, e.g.::\n        assert Union[int, str, int] == Union[int, str]\n    - When comparing unions, the argument order is ignored, e.g.::\n        assert Union[int, str] == Union[str, int]\n    - You cannot subclass or instantiate a union.\n    - You can use Optional[X] as a shorthand for Union[X, None].\n    \"\"\"\n    if parameters == ():\n        raise TypeError(\"Cannot take a Union of no types.\")\n    if not isinstance(parameters, tuple):\n        parameters = (parameters,)\n    msg = \"Union[arg, ...]: each arg must be a type.\"\n    parameters = tuple(_type_check(p, msg) for p in parameters)\n    parameters = _remove_dups_flatten(parameters)\n    if len(parameters) == 1:\n        return parameters[0]\n    if len(parameters) == 2 and type(None) in parameters:\n        return _UnionGenericAlias(self, parameters, name=\"Optional\")\n    return _UnionGenericAlias(self, parameters)\n@_SpecialForm\ndef Optional(self, parameters):", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-14", "text": "@_SpecialForm\ndef Optional(self, parameters):\n    \"\"\"Optional[X] is equivalent to Union[X, None].\"\"\"\n    arg = _type_check(parameters, f\"{self} requires a single type.\")\n    return Union[arg, type(None)]\n@_LiteralSpecialForm\n@_tp_cache(typed=True)\ndef Literal(self, *parameters):\n    \"\"\"Special typing form to define literal types (a.k.a. value types).\n    This form can be used to indicate to type checkers that the corresponding\n    variable or function parameter has a value equivalent to the provided\n    literal (or one of several literals)::\n        def validate_simple(data: Any) -> Literal[True]:  # always returns True\n            ...\n        MODE = Literal['r', 'rb', 'w', 'wb']\n        def open_helper(file: str, mode: MODE) -> str:\n            ...\n        open_helper('/some/path', 'r')  # Passes type check\n        open_helper('/other/path', 'typo')  # Error in type checker\n    Literal[...] cannot be subclassed. At runtime, an arbitrary value\n    is allowed as type argument to Literal[...], but type checkers may\n    impose restrictions.\n    \"\"\"\n    # There is no '_type_check' call because arguments to Literal[...] are\n    # values, not types.\n    parameters = _flatten_literal_params(parameters)\n    try:\n        parameters = tuple(p for p, _ in _deduplicate(list(_value_and_type_iter(parameters))))\n    except TypeError:  # unhashable parameters\n        pass\n    return _LiteralGenericAlias(self, parameters)\n@_SpecialForm\ndef TypeAlias(self, parameters):\n    \"\"\"Special form for marking type aliases.\n    Use TypeAlias to indicate that an assignment should", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-15", "text": "Use TypeAlias to indicate that an assignment should\n    be recognized as a proper type alias definition by type\n    checkers.\n    For example::\n        Predicate: TypeAlias = Callable[..., bool]\n    It's invalid when used anywhere except as in the example above.\n    \"\"\"\n    raise TypeError(f\"{self} is not subscriptable\")\n@_SpecialForm\ndef Concatenate(self, parameters):\n    \"\"\"Special form for annotating higher-order functions.\n    ``Concatenate`` can be used in conjunction with ``ParamSpec`` and\n    ``Callable`` to represent a higher-order function which adds, removes or\n    transforms the parameters of a callable.\n    For example::\n        Callable[Concatenate[int, P], int]\n    See PEP 612 for detailed information.\n    \"\"\"\n    if parameters == ():\n        raise TypeError(\"Cannot take a Concatenate of no types.\")\n    if not isinstance(parameters, tuple):\n        parameters = (parameters,)\n    if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)):\n        raise TypeError(\"The last parameter to Concatenate should be a \"\n                        \"ParamSpec variable or ellipsis.\")\n    msg = \"Concatenate[arg, ...]: each arg must be a type.\"\n    parameters = (*(_type_check(p, msg) for p in parameters[:-1]), parameters[-1])\n    return _ConcatenateGenericAlias(self, parameters,\n                                    _paramspec_tvars=True)\n@_SpecialForm\ndef TypeGuard(self, parameters):\n    \"\"\"Special typing construct for marking user-defined type guard functions.\n    ``TypeGuard`` can be used to annotate the return type of a user-defined\n    type guard function.  ``TypeGuard`` only accepts a single type argument.\n    At runtime, functions marked this way should return a boolean.", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-16", "text": "At runtime, functions marked this way should return a boolean.\n    ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static\n    type checkers to determine a more precise type of an expression within a\n    program's code flow.  Usually type narrowing is done by analyzing\n    conditional code flow and applying the narrowing to a block of code.  The\n    conditional expression here is sometimes referred to as a \"type guard\".\n    Sometimes it would be convenient to use a user-defined boolean function\n    as a type guard.  Such a function should use ``TypeGuard[...]`` as its\n    return type to alert static type checkers to this intention.\n    Using  ``-> TypeGuard`` tells the static type checker that for a given\n    function:\n    1. The return value is a boolean.\n    2. If the return value is ``True``, the type of its argument\n       is the type inside ``TypeGuard``.\n       For example::\n           def is_str(val: Union[str, float]):\n               # \"isinstance\" type guard\n               if isinstance(val, str):\n                   # Type of ``val`` is narrowed to ``str``\n                   ...\n               else:\n                   # Else, type of ``val`` is narrowed to ``float``.\n                   ...\n    Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower\n    form of ``TypeA`` (it can even be a wider form) and this may lead to\n    type-unsafe results.  The main reason is to allow for things like\n    narrowing ``List[object]`` to ``List[str]`` even though the latter is not\n    a subtype of the former, since ``List`` is invariant.  The responsibility of\n    writing type-safe type guards is left to the user.", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-17", "text": "writing type-safe type guards is left to the user.\n    ``TypeGuard`` also works with type variables.  For more information, see\n    PEP 647 (User-Defined Type Guards).\n    \"\"\"\n    item = _type_check(parameters, f'{self} accepts only single type.')\n    return _GenericAlias(self, (item,))\nclass ForwardRef(_Final, _root=True):\n    \"\"\"Internal wrapper to hold a forward reference.\"\"\"\n    __slots__ = ('__forward_arg__', '__forward_code__',\n                 '__forward_evaluated__', '__forward_value__',\n                 '__forward_is_argument__', '__forward_is_class__',\n                 '__forward_module__')\n    def __init__(self, arg, is_argument=True, module=None, *, is_class=False):\n        if not isinstance(arg, str):\n            raise TypeError(f\"Forward reference must be a string -- got {arg!r}\")\n        # If we do `def f(*args: *Ts)`, then we'll have `arg = '*Ts'`.\n        # Unfortunately, this isn't a valid expression on its own, so we\n        # do the unpacking manually.\n        if arg[0] == '*':\n            arg_to_compile = f'({arg},)[0]'  # E.g. (*Ts,)[0] or (*tuple[int, int],)[0]\n        else:\n            arg_to_compile = arg\n        try:\n            code = compile(arg_to_compile, '<string>', 'eval')\n        except SyntaxError:\n            raise SyntaxError(f\"Forward reference must be an expression -- got {arg!r}\")\n        self.__forward_arg__ = arg\n        self.__forward_code__ = code\n        self.__forward_evaluated__ = False\n        self.__forward_value__ = None\n        self.__forward_is_argument__ = is_argument", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-18", "text": "self.__forward_value__ = None\n        self.__forward_is_argument__ = is_argument\n        self.__forward_is_class__ = is_class\n        self.__forward_module__ = module\n    def _evaluate(self, globalns, localns, recursive_guard):\n        if self.__forward_arg__ in recursive_guard:\n            return self\n        if not self.__forward_evaluated__ or localns is not globalns:\n            if globalns is None and localns is None:\n                globalns = localns = {}\n            elif globalns is None:\n                globalns = localns\n            elif localns is None:\n                localns = globalns\n            if self.__forward_module__ is not None:\n                globalns = getattr(\n                    sys.modules.get(self.__forward_module__, None), '__dict__', globalns\n                )\n            type_ = _type_check(\n                eval(self.__forward_code__, globalns, localns),\n                \"Forward references must evaluate to types.\",\n                is_argument=self.__forward_is_argument__,\n                allow_special_forms=self.__forward_is_class__,\n            )\n            self.__forward_value__ = _eval_type(\n                type_, globalns, localns, recursive_guard | {self.__forward_arg__}\n            )\n            self.__forward_evaluated__ = True\n        return self.__forward_value__\n    def __eq__(self, other):\n        if not isinstance(other, ForwardRef):\n            return NotImplemented\n        if self.__forward_evaluated__ and other.__forward_evaluated__:\n            return (self.__forward_arg__ == other.__forward_arg__ and\n                    self.__forward_value__ == other.__forward_value__)\n        return (self.__forward_arg__ == other.__forward_arg__ and\n                self.__forward_module__ == other.__forward_module__)\n    def __hash__(self):", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-19", "text": "def __hash__(self):\n        return hash((self.__forward_arg__, self.__forward_module__))\n    def __or__(self, other):\n        return Union[self, other]\n    def __ror__(self, other):\n        return Union[other, self]\n    def __repr__(self):\n        if self.__forward_module__ is None:\n            module_repr = ''\n        else:\n            module_repr = f', module={self.__forward_module__!r}'\n        return f'ForwardRef({self.__forward_arg__!r}{module_repr})'\ndef _is_unpacked_typevartuple(x: Any) -> bool:\n    return ((not isinstance(x, type)) and\n            getattr(x, '__typing_is_unpacked_typevartuple__', False))\ndef _is_typevar_like(x: Any) -> bool:\n    return isinstance(x, (TypeVar, ParamSpec)) or _is_unpacked_typevartuple(x)\nclass _PickleUsingNameMixin:\n    \"\"\"Mixin enabling pickling based on self.__name__.\"\"\"\n    def __reduce__(self):\n        return self.__name__\nclass _BoundVarianceMixin:\n    \"\"\"Mixin giving __init__ bound and variance arguments.\n    This is used by TypeVar and ParamSpec, which both employ the notions of\n    a type 'bound' (restricting type arguments to be a subtype of some\n    specified type) and type 'variance' (determining subtype relations between\n    generic types).\n    \"\"\"\n    def __init__(self, bound, covariant, contravariant):\n        \"\"\"Used to setup TypeVars and ParamSpec's bound, covariant and\n        contravariant attributes.\n        \"\"\"\n        if covariant and contravariant:\n            raise ValueError(\"Bivariant types are not supported.\")", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-20", "text": "raise ValueError(\"Bivariant types are not supported.\")\n        self.__covariant__ = bool(covariant)\n        self.__contravariant__ = bool(contravariant)\n        if bound:\n            self.__bound__ = _type_check(bound, \"Bound must be a type.\")\n        else:\n            self.__bound__ = None\n    def __or__(self, right):\n        return Union[self, right]\n    def __ror__(self, left):\n        return Union[left, self]\n    def __repr__(self):\n        if self.__covariant__:\n            prefix = '+'\n        elif self.__contravariant__:\n            prefix = '-'\n        else:\n            prefix = '~'\n        return prefix + self.__name__\nclass TypeVar(_Final, _Immutable, _BoundVarianceMixin, _PickleUsingNameMixin,\n              _root=True):\n    \"\"\"Type variable.\n    Usage::\n      T = TypeVar('T')  # Can be anything\n      A = TypeVar('A', str, bytes)  # Must be str or bytes\n    Type variables exist primarily for the benefit of static type\n    checkers.  They serve as the parameters for generic types as well\n    as for generic function definitions.  See class Generic for more\n    information on generic types.  Generic functions work as follows:\n      def repeat(x: T, n: int) -> List[T]:\n          '''Return a list containing n references to x.'''\n          return [x]*n\n      def longest(x: A, y: A) -> A:\n          '''Return the longest of two strings.'''\n          return x if len(x) >= len(y) else y\n    The latter example's signature is essentially the overloading", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-21", "text": "The latter example's signature is essentially the overloading\n    of (str, str) -> str and (bytes, bytes) -> bytes.  Also note\n    that if the arguments are instances of some subclass of str,\n    the return type is still plain str.\n    At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.\n    Type variables defined with covariant=True or contravariant=True\n    can be used to declare covariant or contravariant generic types.\n    See PEP 484 for more details. By default generic types are invariant\n    in all type variables.\n    Type variables can be introspected. e.g.:\n      T.__name__ == 'T'\n      T.__constraints__ == ()\n      T.__covariant__ == False\n      T.__contravariant__ = False\n      A.__constraints__ == (str, bytes)\n    Note that only type variables defined in global scope can be pickled.\n    \"\"\"\n    def __init__(self, name, *constraints, bound=None,\n                 covariant=False, contravariant=False):\n        self.__name__ = name\n        super().__init__(bound, covariant, contravariant)\n        if constraints and bound is not None:\n            raise TypeError(\"Constraints cannot be combined with bound=...\")\n        if constraints and len(constraints) == 1:\n            raise TypeError(\"A single constraint is not allowed\")\n        msg = \"TypeVar(name, constraint, ...): constraints must be types.\"\n        self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)\n        def_mod = _caller()\n        if def_mod != 'typing':\n            self.__module__ = def_mod\n    def __typing_subst__(self, arg):", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-22", "text": "def __typing_subst__(self, arg):\n        msg = \"Parameters to generic types must be types.\"\n        arg = _type_check(arg, msg, is_argument=True)\n        if ((isinstance(arg, _GenericAlias) and arg.__origin__ is Unpack) or\n            (isinstance(arg, GenericAlias) and getattr(arg, '__unpacked__', False))):\n            raise TypeError(f\"{arg} is not valid as type argument\")\n        return arg\nclass TypeVarTuple(_Final, _Immutable, _PickleUsingNameMixin, _root=True):\n    \"\"\"Type variable tuple.\n    Usage:\n      Ts = TypeVarTuple('Ts')  # Can be given any name\n    Just as a TypeVar (type variable) is a placeholder for a single type,\n    a TypeVarTuple is a placeholder for an *arbitrary* number of types. For\n    example, if we define a generic class using a TypeVarTuple:\n      class C(Generic[*Ts]): ...\n    Then we can parameterize that class with an arbitrary number of type\n    arguments:\n      C[int]       # Fine\n      C[int, str]  # Also fine\n      C[()]        # Even this is fine\n    For more details, see PEP 646.\n    Note that only TypeVarTuples defined in global scope can be pickled.\n    \"\"\"\n    def __init__(self, name):\n        self.__name__ = name\n        # Used for pickling.\n        def_mod = _caller()\n        if def_mod != 'typing':\n            self.__module__ = def_mod\n    def __iter__(self):\n        yield Unpack[self]\n    def __repr__(self):\n        return self.__name__\n    def __typing_subst__(self, arg):", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-23", "text": "return self.__name__\n    def __typing_subst__(self, arg):\n        raise TypeError(\"Substitution of bare TypeVarTuple is not supported\")\n    def __typing_prepare_subst__(self, alias, args):\n        params = alias.__parameters__\n        typevartuple_index = params.index(self)\n        for param in params[typevartuple_index + 1:]:\n            if isinstance(param, TypeVarTuple):\n                raise TypeError(f\"More than one TypeVarTuple parameter in {alias}\")\n        alen = len(args)\n        plen = len(params)\n        left = typevartuple_index\n        right = plen - typevartuple_index - 1\n        var_tuple_index = None\n        fillarg = None\n        for k, arg in enumerate(args):\n            if not isinstance(arg, type):\n                subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)\n                if subargs and len(subargs) == 2 and subargs[-1] is ...:\n                    if var_tuple_index is not None:\n                        raise TypeError(\"More than one unpacked arbitrary-length tuple argument\")\n                    var_tuple_index = k\n                    fillarg = subargs[0]\n        if var_tuple_index is not None:\n            left = min(left, var_tuple_index)\n            right = min(right, alen - var_tuple_index - 1)\n        elif left + right > alen:\n            raise TypeError(f\"Too few arguments for {alias};\"\n                            f\" actual {alen}, expected at least {plen-1}\")\n        return (\n            *args[:left],\n            *([fillarg]*(typevartuple_index - left)),\n            tuple(args[left: alen - right]),", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-24", "text": "tuple(args[left: alen - right]),\n            *([fillarg]*(plen - right - left - typevartuple_index - 1)),\n            *args[alen - right:],\n        )\nclass ParamSpecArgs(_Final, _Immutable, _root=True):\n    \"\"\"The args for a ParamSpec object.\n    Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.\n    ParamSpecArgs objects have a reference back to their ParamSpec:\n       P.args.__origin__ is P\n    This type is meant for runtime introspection and has no special meaning to\n    static type checkers.\n    \"\"\"\n    def __init__(self, origin):\n        self.__origin__ = origin\n    def __repr__(self):\n        return f\"{self.__origin__.__name__}.args\"\n    def __eq__(self, other):\n        if not isinstance(other, ParamSpecArgs):\n            return NotImplemented\n        return self.__origin__ == other.__origin__\nclass ParamSpecKwargs(_Final, _Immutable, _root=True):\n    \"\"\"The kwargs for a ParamSpec object.\n    Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.\n    ParamSpecKwargs objects have a reference back to their ParamSpec:\n       P.kwargs.__origin__ is P\n    This type is meant for runtime introspection and has no special meaning to\n    static type checkers.\n    \"\"\"\n    def __init__(self, origin):\n        self.__origin__ = origin\n    def __repr__(self):\n        return f\"{self.__origin__.__name__}.kwargs\"\n    def __eq__(self, other):\n        if not isinstance(other, ParamSpecKwargs):\n            return NotImplemented\n        return self.__origin__ == other.__origin__", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-25", "text": "return NotImplemented\n        return self.__origin__ == other.__origin__\nclass ParamSpec(_Final, _Immutable, _BoundVarianceMixin, _PickleUsingNameMixin,\n                _root=True):\n    \"\"\"Parameter specification variable.\n    Usage::\n       P = ParamSpec('P')\n    Parameter specification variables exist primarily for the benefit of static\n    type checkers.  They are used to forward the parameter types of one\n    callable to another callable, a pattern commonly found in higher order\n    functions and decorators.  They are only valid when used in ``Concatenate``,\n    or as the first argument to ``Callable``, or as parameters for user-defined\n    Generics.  See class Generic for more information on generic types.  An\n    example for annotating a decorator::\n       T = TypeVar('T')\n       P = ParamSpec('P')\n       def add_logging(f: Callable[P, T]) -> Callable[P, T]:\n           '''A type-safe decorator to add logging to a function.'''\n           def inner(*args: P.args, **kwargs: P.kwargs) -> T:\n               logging.info(f'{f.__name__} was called')\n               return f(*args, **kwargs)\n           return inner\n       @add_logging\n       def add_two(x: float, y: float) -> float:\n           '''Add two numbers together.'''\n           return x + y\n    Parameter specification variables can be introspected. e.g.:\n       P.__name__ == 'P'\n    Note that only parameter specification variables defined in global scope can\n    be pickled.\n    \"\"\"\n    @property\n    def args(self):\n        return ParamSpecArgs(self)\n    @property\n    def kwargs(self):\n        return ParamSpecKwargs(self)", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-26", "text": "@property\n    def kwargs(self):\n        return ParamSpecKwargs(self)\n    def __init__(self, name, *, bound=None, covariant=False, contravariant=False):\n        self.__name__ = name\n        super().__init__(bound, covariant, contravariant)\n        def_mod = _caller()\n        if def_mod != 'typing':\n            self.__module__ = def_mod\n    def __typing_subst__(self, arg):\n        if isinstance(arg, (list, tuple)):\n            arg = tuple(_type_check(a, \"Expected a type.\") for a in arg)\n        elif not _is_param_expr(arg):\n            raise TypeError(f\"Expected a list of types, an ellipsis, \"\n                            f\"ParamSpec, or Concatenate. Got {arg}\")\n        return arg\n    def __typing_prepare_subst__(self, alias, args):\n        params = alias.__parameters__\n        i = params.index(self)\n        if i >= len(args):\n            raise TypeError(f\"Too few arguments for {alias}\")\n        # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612.\n        if len(params) == 1 and not _is_param_expr(args[0]):\n            assert i == 0\n            args = (args,)\n        # Convert lists to tuples to help other libraries cache the results.\n        elif isinstance(args[i], list):\n            args = (*args[:i], tuple(args[i]), *args[i+1:])\n        return args\ndef _is_dunder(attr):\n    return attr.startswith('__') and attr.endswith('__')\nclass _BaseGenericAlias(_Final, _root=True):\n    \"\"\"The central part of the internal API.", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-27", "text": "\"\"\"The central part of the internal API.\n    This represents a generic version of type 'origin' with type arguments 'params'.\n    There are two kind of these aliases: user defined and special. The special ones\n    are wrappers around builtin collections and ABCs in collections.abc. These must\n    have 'name' always set. If 'inst' is False, then the alias can't be instantiated;\n    this is used by e.g. typing.List and typing.Dict.\n    \"\"\"\n    def __init__(self, origin, *, inst=True, name=None):\n        self._inst = inst\n        self._name = name\n        self.__origin__ = origin\n        self.__slots__ = None  # This is not documented.\n    def __call__(self, *args, **kwargs):\n        if not self._inst:\n            raise TypeError(f\"Type {self._name} cannot be instantiated; \"\n                            f\"use {self.__origin__.__name__}() instead\")\n        result = self.__origin__(*args, **kwargs)\n        try:\n            result.__orig_class__ = self\n        except AttributeError:\n            pass\n        return result\n    def __mro_entries__(self, bases):\n        res = []\n        if self.__origin__ not in bases:\n            res.append(self.__origin__)\n        i = bases.index(self)\n        for b in bases[i+1:]:\n            if isinstance(b, _BaseGenericAlias) or issubclass(b, Generic):\n                break\n        else:\n            res.append(Generic)\n        return tuple(res)\n    def __getattr__(self, attr):\n        if attr in {'__name__', '__qualname__'}:\n            return self._name or self.__origin__.__name__\n        # We are careful for copy and pickle.", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-28", "text": "# We are careful for copy and pickle.\n        # Also for simplicity we don't relay any dunder names\n        if '__origin__' in self.__dict__ and not _is_dunder(attr):\n            return getattr(self.__origin__, attr)\n        raise AttributeError(attr)\n    def __setattr__(self, attr, val):\n        if _is_dunder(attr) or attr in {'_name', '_inst', '_nparams',\n                                        '_paramspec_tvars'}:\n            super().__setattr__(attr, val)\n        else:\n            setattr(self.__origin__, attr, val)\n    def __instancecheck__(self, obj):\n        return self.__subclasscheck__(type(obj))\n    def __subclasscheck__(self, cls):\n        raise TypeError(\"Subscripted generics cannot be used with\"\n                        \" class and instance checks\")\n    def __dir__(self):\n        return list(set(super().__dir__()\n                + [attr for attr in dir(self.__origin__) if not _is_dunder(attr)]))\n# Special typing constructs Union, Optional, Generic, Callable and Tuple\n# use three special attributes for internal bookkeeping of generic types:\n# * __parameters__ is a tuple of unique free type parameters of a generic\n#   type, for example, Dict[T, T].__parameters__ == (T,);\n# * __origin__ keeps a reference to a type that was subscripted,\n#   e.g., Union[T, int].__origin__ == Union, or the non-generic version of\n#   the type.\n# * __args__ is a tuple of all arguments used in subscripting,\n#   e.g., Dict[T, int].__args__ == (T, int).\nclass _GenericAlias(_BaseGenericAlias, _root=True):\n    # The type of parameterized generics.\n    #", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-29", "text": "# The type of parameterized generics.\n    #\n    # That is, for example, `type(List[int])` is `_GenericAlias`.\n    #\n    # Objects which are instances of this class include:\n    # * Parameterized container types, e.g. `Tuple[int]`, `List[int]`.\n    #  * Note that native container types, e.g. `tuple`, `list`, use\n    #    `types.GenericAlias` instead.\n    # * Parameterized classes:\n    #     T = TypeVar('T')\n    #     class C(Generic[T]): pass\n    #     # C[int] is a _GenericAlias\n    # * `Callable` aliases, generic `Callable` aliases, and\n    #   parameterized `Callable` aliases:\n    #     T = TypeVar('T')\n    #     # _CallableGenericAlias inherits from _GenericAlias.\n    #     A = Callable[[], None]  # _CallableGenericAlias\n    #     B = Callable[[T], None]  # _CallableGenericAlias\n    #     C = B[int]  # _CallableGenericAlias\n    # * Parameterized `Final`, `ClassVar` and `TypeGuard`:\n    #     # All _GenericAlias\n    #     Final[int]\n    #     ClassVar[float]\n    #     TypeVar[bool]\n    def __init__(self, origin, args, *, inst=True, name=None,\n                 _paramspec_tvars=False):\n        super().__init__(origin, inst=inst, name=name)\n        if not isinstance(args, tuple):\n            args = (args,)\n        self.__args__ = tuple(... if a is _TypingEllipsis else\n                              a for a in args)\n        self.__parameters__ = _collect_parameters(args)", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-30", "text": "a for a in args)\n        self.__parameters__ = _collect_parameters(args)\n        self._paramspec_tvars = _paramspec_tvars\n        if not name:\n            self.__module__ = origin.__module__\n    def __eq__(self, other):\n        if not isinstance(other, _GenericAlias):\n            return NotImplemented\n        return (self.__origin__ == other.__origin__\n                and self.__args__ == other.__args__)\n    def __hash__(self):\n        return hash((self.__origin__, self.__args__))\n    def __or__(self, right):\n        return Union[self, right]\n    def __ror__(self, left):\n        return Union[left, self]\n    @_tp_cache\n    def __getitem__(self, args):\n        # Parameterizes an already-parameterized object.\n        #\n        # For example, we arrive here doing something like:\n        #   T1 = TypeVar('T1')\n        #   T2 = TypeVar('T2')\n        #   T3 = TypeVar('T3')\n        #   class A(Generic[T1]): pass\n        #   B = A[T2]  # B is a _GenericAlias\n        #   C = B[T3]  # Invokes _GenericAlias.__getitem__\n        #\n        # We also arrive here when parameterizing a generic `Callable` alias:\n        #   T = TypeVar('T')\n        #   C = Callable[[T], None]\n        #   C[int]  # Invokes _GenericAlias.__getitem__\n        if self.__origin__ in (Generic, Protocol):\n            # Can't subscript Generic[...] or Protocol[...].\n            raise TypeError(f\"Cannot subscript already-subscripted {self}\")\n        if not self.__parameters__:", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-31", "text": "if not self.__parameters__:\n            raise TypeError(f\"{self} is not a generic class\")\n        # Preprocess `args`.\n        if not isinstance(args, tuple):\n            args = (args,)\n        args = tuple(_type_convert(p) for p in args)\n        args = _unpack_args(args)\n        new_args = self._determine_new_args(args)\n        r = self.copy_with(new_args)\n        return r\n    def _determine_new_args(self, args):\n        # Determines new __args__ for __getitem__.\n        #\n        # For example, suppose we had:\n        #   T1 = TypeVar('T1')\n        #   T2 = TypeVar('T2')\n        #   class A(Generic[T1, T2]): pass\n        #   T3 = TypeVar('T3')\n        #   B = A[int, T3]\n        #   C = B[str]\n        # `B.__args__` is `(int, T3)`, so `C.__args__` should be `(int, str)`.\n        # Unfortunately, this is harder than it looks, because if `T3` is\n        # anything more exotic than a plain `TypeVar`, we need to consider\n        # edge cases.\n        params = self.__parameters__\n        # In the example above, this would be {T3: str}\n        for param in params:\n            prepare = getattr(param, '__typing_prepare_subst__', None)\n            if prepare is not None:\n                args = prepare(self, args)\n        alen = len(args)\n        plen = len(params)\n        if alen != plen:\n            raise TypeError(f\"Too {'many' if alen > plen else 'few'} arguments for {self};\"", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-32", "text": "f\" actual {alen}, expected {plen}\")\n        new_arg_by_param = dict(zip(params, args))\n        return tuple(self._make_substitution(self.__args__, new_arg_by_param))\n    def _make_substitution(self, args, new_arg_by_param):\n        \"\"\"Create a list of new type arguments.\"\"\"\n        new_args = []\n        for old_arg in args:\n            if isinstance(old_arg, type):\n                new_args.append(old_arg)\n                continue\n            substfunc = getattr(old_arg, '__typing_subst__', None)\n            if substfunc:\n                new_arg = substfunc(new_arg_by_param[old_arg])\n            else:\n                subparams = getattr(old_arg, '__parameters__', ())\n                if not subparams:\n                    new_arg = old_arg\n                else:\n                    subargs = []\n                    for x in subparams:\n                        if isinstance(x, TypeVarTuple):\n                            subargs.extend(new_arg_by_param[x])\n                        else:\n                            subargs.append(new_arg_by_param[x])\n                    new_arg = old_arg[tuple(subargs)]\n            if self.__origin__ == collections.abc.Callable and isinstance(new_arg, tuple):\n                # Consider the following `Callable`.\n                #   C = Callable[[int], str]\n                # Here, `C.__args__` should be (int, str) - NOT ([int], str).\n                # That means that if we had something like...\n                #   P = ParamSpec('P')\n                #   T = TypeVar('T')\n                #   C = Callable[P, T]\n                #   D = C[[int, str], float]\n                # ...we need to be careful; `new_args` should end up as", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-33", "text": "# ...we need to be careful; `new_args` should end up as\n                # `(int, str, float)` rather than `([int, str], float)`.\n                new_args.extend(new_arg)\n            elif _is_unpacked_typevartuple(old_arg):\n                # Consider the following `_GenericAlias`, `B`:\n                #   class A(Generic[*Ts]): ...\n                #   B = A[T, *Ts]\n                # If we then do:\n                #   B[float, int, str]\n                # The `new_arg` corresponding to `T` will be `float`, and the\n                # `new_arg` corresponding to `*Ts` will be `(int, str)`. We\n                # should join all these types together in a flat list\n                # `(float, int, str)` - so again, we should `extend`.\n                new_args.extend(new_arg)\n            elif isinstance(old_arg, tuple):\n                # Corner case:\n                #    P = ParamSpec('P')\n                #    T = TypeVar('T')\n                #    class Base(Generic[P]): ...\n                # Can be substituted like this:\n                #    X = Base[[int, T]]\n                # In this case, `old_arg` will be a tuple:\n                new_args.append(\n                    tuple(self._make_substitution(old_arg, new_arg_by_param)),\n                )\n            else:\n                new_args.append(new_arg)\n        return new_args\n    def copy_with(self, args):\n        return self.__class__(self.__origin__, args, name=self._name, inst=self._inst,\n                              _paramspec_tvars=self._paramspec_tvars)\n    def __repr__(self):\n        if self._name:\n            name = 'typing.' + self._name", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-34", "text": "if self._name:\n            name = 'typing.' + self._name\n        else:\n            name = _type_repr(self.__origin__)\n        if self.__args__:\n            args = \", \".join([_type_repr(a) for a in self.__args__])\n        else:\n            # To ensure the repr is eval-able.\n            args = \"()\"\n        return f'{name}[{args}]'\n    def __reduce__(self):\n        if self._name:\n            origin = globals()[self._name]\n        else:\n            origin = self.__origin__\n        args = tuple(self.__args__)\n        if len(args) == 1 and not isinstance(args[0], tuple):\n            args, = args\n        return operator.getitem, (origin, args)\n    def __mro_entries__(self, bases):\n        if isinstance(self.__origin__, _SpecialForm):\n            raise TypeError(f\"Cannot subclass {self!r}\")\n        if self._name:  # generic version of an ABC or built-in class\n            return super().__mro_entries__(bases)\n        if self.__origin__ is Generic:\n            if Protocol in bases:\n                return ()\n            i = bases.index(self)\n            for b in bases[i+1:]:\n                if isinstance(b, _BaseGenericAlias) and b is not self:\n                    return ()\n        return (self.__origin__,)\n    def __iter__(self):\n        yield Unpack[self]\n# _nparams is the number of accepted parameters, e.g. 0 for Hashable,\n# 1 for List and 2 for Dict.  It may be -1 if variable number of\n# parameters are accepted (needs custom __getitem__).\nclass _SpecialGenericAlias(_NotIterable, _BaseGenericAlias, _root=True):", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-35", "text": "class _SpecialGenericAlias(_NotIterable, _BaseGenericAlias, _root=True):\n    def __init__(self, origin, nparams, *, inst=True, name=None):\n        if name is None:\n            name = origin.__name__\n        super().__init__(origin, inst=inst, name=name)\n        self._nparams = nparams\n        if origin.__module__ == 'builtins':\n            self.__doc__ = f'A generic version of {origin.__qualname__}.'\n        else:\n            self.__doc__ = f'A generic version of {origin.__module__}.{origin.__qualname__}.'\n    @_tp_cache\n    def __getitem__(self, params):\n        if not isinstance(params, tuple):\n            params = (params,)\n        msg = \"Parameters to generic types must be types.\"\n        params = tuple(_type_check(p, msg) for p in params)\n        _check_generic(self, params, self._nparams)\n        return self.copy_with(params)\n    def copy_with(self, params):\n        return _GenericAlias(self.__origin__, params,\n                             name=self._name, inst=self._inst)\n    def __repr__(self):\n        return 'typing.' + self._name\n    def __subclasscheck__(self, cls):\n        if isinstance(cls, _SpecialGenericAlias):\n            return issubclass(cls.__origin__, self.__origin__)\n        if not isinstance(cls, _GenericAlias):\n            return issubclass(cls, self.__origin__)\n        return super().__subclasscheck__(cls)\n    def __reduce__(self):\n        return self._name\n    def __or__(self, right):\n        return Union[self, right]\n    def __ror__(self, left):\n        return Union[left, self]", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-36", "text": "def __ror__(self, left):\n        return Union[left, self]\nclass _CallableGenericAlias(_NotIterable, _GenericAlias, _root=True):\n    def __repr__(self):\n        assert self._name == 'Callable'\n        args = self.__args__\n        if len(args) == 2 and _is_param_expr(args[0]):\n            return super().__repr__()\n        return (f'typing.Callable'\n                f'[[{\", \".join([_type_repr(a) for a in args[:-1]])}], '\n                f'{_type_repr(args[-1])}]')\n    def __reduce__(self):\n        args = self.__args__\n        if not (len(args) == 2 and _is_param_expr(args[0])):\n            args = list(args[:-1]), args[-1]\n        return operator.getitem, (Callable, args)\nclass _CallableType(_SpecialGenericAlias, _root=True):\n    def copy_with(self, params):\n        return _CallableGenericAlias(self.__origin__, params,\n                                     name=self._name, inst=self._inst,\n                                     _paramspec_tvars=True)\n    def __getitem__(self, params):\n        if not isinstance(params, tuple) or len(params) != 2:\n            raise TypeError(\"Callable must be used as \"\n                            \"Callable[[arg, ...], result].\")\n        args, result = params\n        # This relaxes what args can be on purpose to allow things like\n        # PEP 612 ParamSpec.  Responsibility for whether a user is using\n        # Callable[...] properly is deferred to static type checkers.\n        if isinstance(args, list):\n            params = (tuple(args), result)\n        else:\n            params = (args, result)", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-37", "text": "else:\n            params = (args, result)\n        return self.__getitem_inner__(params)\n    @_tp_cache\n    def __getitem_inner__(self, params):\n        args, result = params\n        msg = \"Callable[args, result]: result must be a type.\"\n        result = _type_check(result, msg)\n        if args is Ellipsis:\n            return self.copy_with((_TypingEllipsis, result))\n        if not isinstance(args, tuple):\n            args = (args,)\n        args = tuple(_type_convert(arg) for arg in args)\n        params = args + (result,)\n        return self.copy_with(params)\nclass _TupleType(_SpecialGenericAlias, _root=True):\n    @_tp_cache\n    def __getitem__(self, params):\n        if not isinstance(params, tuple):\n            params = (params,)\n        if len(params) >= 2 and params[-1] is ...:\n            msg = \"Tuple[t, ...]: t must be a type.\"\n            params = tuple(_type_check(p, msg) for p in params[:-1])\n            return self.copy_with((*params, _TypingEllipsis))\n        msg = \"Tuple[t0, t1, ...]: each t must be a type.\"\n        params = tuple(_type_check(p, msg) for p in params)\n        return self.copy_with(params)\nclass _UnionGenericAlias(_NotIterable, _GenericAlias, _root=True):\n    def copy_with(self, params):\n        return Union[params]\n    def __eq__(self, other):\n        if not isinstance(other, (_UnionGenericAlias, types.UnionType)):\n            return NotImplemented\n        return set(self.__args__) == set(other.__args__)\n    def __hash__(self):\n        return hash(frozenset(self.__args__))", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-38", "text": "def __hash__(self):\n        return hash(frozenset(self.__args__))\n    def __repr__(self):\n        args = self.__args__\n        if len(args) == 2:\n            if args[0] is type(None):\n                return f'typing.Optional[{_type_repr(args[1])}]'\n            elif args[1] is type(None):\n                return f'typing.Optional[{_type_repr(args[0])}]'\n        return super().__repr__()\n    def __instancecheck__(self, obj):\n        return self.__subclasscheck__(type(obj))\n    def __subclasscheck__(self, cls):\n        for arg in self.__args__:\n            if issubclass(cls, arg):\n                return True\n    def __reduce__(self):\n        func, (origin, args) = super().__reduce__()\n        return func, (Union, args)\ndef _value_and_type_iter(parameters):\n    return ((p, type(p)) for p in parameters)\nclass _LiteralGenericAlias(_GenericAlias, _root=True):\n    def __eq__(self, other):\n        if not isinstance(other, _LiteralGenericAlias):\n            return NotImplemented\n        return set(_value_and_type_iter(self.__args__)) == set(_value_and_type_iter(other.__args__))\n    def __hash__(self):\n        return hash(frozenset(_value_and_type_iter(self.__args__)))\nclass _ConcatenateGenericAlias(_GenericAlias, _root=True):\n    def copy_with(self, params):\n        if isinstance(params[-1], (list, tuple)):\n            return (*params[:-1], *params[-1])\n        if isinstance(params[-1], _ConcatenateGenericAlias):\n            params = (*params[:-1], *params[-1].__args__)", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-39", "text": "params = (*params[:-1], *params[-1].__args__)\n        return super().copy_with(params)\n@_SpecialForm\ndef Unpack(self, parameters):\n    \"\"\"Type unpack operator.\n    The type unpack operator takes the child types from some container type,\n    such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'.\n    For example::\n        # For some generic class `Foo`:\n        Foo[Unpack[tuple[int, str]]]  # Equivalent to Foo[int, str]\n        Ts = TypeVarTuple('Ts')\n        # Specifies that `Bar` is generic in an arbitrary number of types.\n        # (Think of `Ts` as a tuple of an arbitrary number of individual\n        #  `TypeVar`s, which the `Unpack` is 'pulling out' directly into the\n        #  `Generic[]`.)\n        class Bar(Generic[Unpack[Ts]]): ...\n        Bar[int]  # Valid\n        Bar[int, str]  # Also valid\n    From Python 3.11, this can also be done using the `*` operator::\n        Foo[*tuple[int, str]]\n        class Bar(Generic[*Ts]): ...\n    Note that there is only some runtime checking of this operator. Not\n    everything the runtime allows may be accepted by static type checkers.\n    For more information, see PEP 646.\n    \"\"\"\n    item = _type_check(parameters, f'{self} accepts only single type.')\n    return _UnpackGenericAlias(origin=self, args=(item,))\nclass _UnpackGenericAlias(_GenericAlias, _root=True):\n    def __repr__(self):\n        # `Unpack` only takes one argument, so __args__ should contain only", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-40", "text": "# `Unpack` only takes one argument, so __args__ should contain only\n        # a single item.\n        return '*' + repr(self.__args__[0])\n    def __getitem__(self, args):\n        if self.__typing_is_unpacked_typevartuple__:\n            return args\n        return super().__getitem__(args)\n    @property\n    def __typing_unpacked_tuple_args__(self):\n        assert self.__origin__ is Unpack\n        assert len(self.__args__) == 1\n        arg, = self.__args__\n        if isinstance(arg, _GenericAlias):\n            assert arg.__origin__ is tuple\n            return arg.__args__\n        return None\n    @property\n    def __typing_is_unpacked_typevartuple__(self):\n        assert self.__origin__ is Unpack\n        assert len(self.__args__) == 1\n        return isinstance(self.__args__[0], TypeVarTuple)\nclass Generic:\n    \"\"\"Abstract base class for generic types.\n    A generic type is typically declared by inheriting from\n    this class parameterized with one or more type variables.\n    For example, a generic mapping type might be defined as::\n      class Mapping(Generic[KT, VT]):\n          def __getitem__(self, key: KT) -> VT:\n              ...\n          # Etc.\n    This class can then be used as follows::\n      def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:\n          try:\n              return mapping[key]\n          except KeyError:\n              return default\n    \"\"\"\n    __slots__ = ()\n    _is_protocol = False\n    @_tp_cache\n    def __class_getitem__(cls, params):\n        \"\"\"Parameterizes a generic class.", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-41", "text": "\"\"\"Parameterizes a generic class.\n        At least, parameterizing a generic class is the *main* thing this method\n        does. For example, for some generic class `Foo`, this is called when we\n        do `Foo[int]` - there, with `cls=Foo` and `params=int`.\n        However, note that this method is also called when defining generic\n        classes in the first place with `class Foo(Generic[T]): ...`.\n        \"\"\"\n        if not isinstance(params, tuple):\n            params = (params,)\n        params = tuple(_type_convert(p) for p in params)\n        if cls in (Generic, Protocol):\n            # Generic and Protocol can only be subscripted with unique type variables.\n            if not params:\n                raise TypeError(\n                    f\"Parameter list to {cls.__qualname__}[...] cannot be empty\"\n                )\n            if not all(_is_typevar_like(p) for p in params):\n                raise TypeError(\n                    f\"Parameters to {cls.__name__}[...] must all be type variables \"\n                    f\"or parameter specification variables.\")\n            if len(set(params)) != len(params):\n                raise TypeError(\n                    f\"Parameters to {cls.__name__}[...] must all be unique\")\n        else:\n            # Subscripting a regular Generic subclass.\n            for param in cls.__parameters__:\n                prepare = getattr(param, '__typing_prepare_subst__', None)\n                if prepare is not None:\n                    params = prepare(cls, params)\n            _check_generic(cls, params, len(cls.__parameters__))\n            new_args = []\n            for param, new_arg in zip(cls.__parameters__, params):\n                if isinstance(param, TypeVarTuple):\n                    new_args.extend(new_arg)\n                else:\n                    new_args.append(new_arg)", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-42", "text": "new_args.extend(new_arg)\n                else:\n                    new_args.append(new_arg)\n            params = tuple(new_args)\n        return _GenericAlias(cls, params,\n                             _paramspec_tvars=True)\n    def __init_subclass__(cls, *args, **kwargs):\n        super().__init_subclass__(*args, **kwargs)\n        tvars = []\n        if '__orig_bases__' in cls.__dict__:\n            error = Generic in cls.__orig_bases__\n        else:\n            error = (Generic in cls.__bases__ and\n                        cls.__name__ != 'Protocol' and\n                        type(cls) != _TypedDictMeta)\n        if error:\n            raise TypeError(\"Cannot inherit from plain Generic\")\n        if '__orig_bases__' in cls.__dict__:\n            tvars = _collect_parameters(cls.__orig_bases__)\n            # Look for Generic[T1, ..., Tn].\n            # If found, tvars must be a subset of it.\n            # If not found, tvars is it.\n            # Also check for and reject plain Generic,\n            # and reject multiple Generic[...].\n            gvars = None\n            for base in cls.__orig_bases__:\n                if (isinstance(base, _GenericAlias) and\n                        base.__origin__ is Generic):\n                    if gvars is not None:\n                        raise TypeError(\n                            \"Cannot inherit from Generic[...] multiple times.\")\n                    gvars = base.__parameters__\n            if gvars is not None:\n                tvarset = set(tvars)\n                gvarset = set(gvars)\n                if not tvarset <= gvarset:\n                    s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-43", "text": "s_args = ', '.join(str(g) for g in gvars)\n                    raise TypeError(f\"Some type variables ({s_vars}) are\"\n                                    f\" not listed in Generic[{s_args}]\")\n                tvars = gvars\n        cls.__parameters__ = tuple(tvars)\nclass _TypingEllipsis:\n    \"\"\"Internal placeholder for ... (ellipsis).\"\"\"\n_TYPING_INTERNALS = ['__parameters__', '__orig_bases__',  '__orig_class__',\n                     '_is_protocol', '_is_runtime_protocol', '__final__']\n_SPECIAL_NAMES = ['__abstractmethods__', '__annotations__', '__dict__', '__doc__',\n                  '__init__', '__module__', '__new__', '__slots__',\n                  '__subclasshook__', '__weakref__', '__class_getitem__']\n# These special attributes will be not collected as protocol members.\nEXCLUDED_ATTRIBUTES = _TYPING_INTERNALS + _SPECIAL_NAMES + ['_MutableMapping__marker']\ndef _get_protocol_attrs(cls):\n    \"\"\"Collect protocol members from a protocol class objects.\n    This includes names actually defined in the class dictionary, as well\n    as names that appear in annotations. Special names (above) are skipped.\n    \"\"\"\n    attrs = set()\n    for base in cls.__mro__[:-1]:  # without object\n        if base.__name__ in ('Protocol', 'Generic'):\n            continue\n        annotations = getattr(base, '__annotations__', {})\n        for attr in list(base.__dict__.keys()) + list(annotations.keys()):\n            if not attr.startswith('_abc_') and attr not in EXCLUDED_ATTRIBUTES:\n                attrs.add(attr)\n    return attrs\ndef _is_callable_members_only(cls):\n    # PEP 544 prohibits using issubclass() with protocols that have non-method members.", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-44", "text": "# PEP 544 prohibits using issubclass() with protocols that have non-method members.\n    return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))\ndef _no_init_or_replace_init(self, *args, **kwargs):\n    cls = type(self)\n    if cls._is_protocol:\n        raise TypeError('Protocols cannot be instantiated')\n    # Already using a custom `__init__`. No need to calculate correct\n    # `__init__` to call. This can lead to RecursionError. See bpo-45121.\n    if cls.__init__ is not _no_init_or_replace_init:\n        return\n    # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.\n    # The first instantiation of the subclass will call `_no_init_or_replace_init` which\n    # searches for a proper new `__init__` in the MRO. The new `__init__`\n    # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent\n    # instantiation of the protocol subclass will thus use the new\n    # `__init__` and no longer call `_no_init_or_replace_init`.\n    for base in cls.__mro__:\n        init = base.__dict__.get('__init__', _no_init_or_replace_init)\n        if init is not _no_init_or_replace_init:\n            cls.__init__ = init\n            break\n    else:\n        # should not happen\n        cls.__init__ = object.__init__\n    cls.__init__(self, *args, **kwargs)\ndef _caller(depth=1, default='__main__'):\n    try:\n        return sys._getframe(depth + 1).f_globals.get('__name__', default)", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-45", "text": "return sys._getframe(depth + 1).f_globals.get('__name__', default)\n    except (AttributeError, ValueError):  # For platforms without _getframe()\n        return None\ndef _allow_reckless_class_checks(depth=3):\n    \"\"\"Allow instance and class checks for special stdlib modules.\n    The abc and functools modules indiscriminately call isinstance() and\n    issubclass() on the whole MRO of a user class, which may contain protocols.\n    \"\"\"\n    return _caller(depth) in {'abc', 'functools', None}\n_PROTO_ALLOWLIST = {\n    'collections.abc': [\n        'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',\n        'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',\n    ],\n    'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],\n}\nclass _ProtocolMeta(ABCMeta):\n    # This metaclass is really unfortunate and exists only because of\n    # the lack of __instancehook__.\n    def __instancecheck__(cls, instance):\n        # We need this method for situations where attributes are\n        # assigned in __init__.\n        if (\n            getattr(cls, '_is_protocol', False) and\n            not getattr(cls, '_is_runtime_protocol', False) and\n            not _allow_reckless_class_checks(depth=2)\n        ):\n            raise TypeError(\"Instance and class checks can only be used with\"\n                            \" @runtime_checkable protocols\")\n        if ((not getattr(cls, '_is_protocol', False) or\n                _is_callable_members_only(cls)) and\n                issubclass(instance.__class__, cls)):\n            return True\n        if cls._is_protocol:\n            if all(hasattr(instance, attr) and", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-46", "text": "if cls._is_protocol:\n            if all(hasattr(instance, attr) and\n                    # All *methods* can be blocked by setting them to None.\n                    (not callable(getattr(cls, attr, None)) or\n                     getattr(instance, attr) is not None)\n                    for attr in _get_protocol_attrs(cls)):\n                return True\n        return super().__instancecheck__(instance)\nclass Protocol(Generic, metaclass=_ProtocolMeta):\n    \"\"\"Base class for protocol classes.\n    Protocol classes are defined as::\n        class Proto(Protocol):\n            def meth(self) -> int:\n                ...\n    Such classes are primarily used with static type checkers that recognize\n    structural subtyping (static duck-typing).\n    For example::\n        class C:\n            def meth(self) -> int:\n                return 0\n        def func(x: Proto) -> int:\n            return x.meth()\n        func(C())  # Passes static type check\n    See PEP 544 for details. Protocol classes decorated with\n    @typing.runtime_checkable act as simple-minded runtime protocols that check\n    only the presence of given attributes, ignoring their type signatures.\n    Protocol classes can be generic, they are defined as::\n        class GenProto(Protocol[T]):\n            def meth(self) -> T:\n                ...\n    \"\"\"\n    __slots__ = ()\n    _is_protocol = True\n    _is_runtime_protocol = False\n    def __init_subclass__(cls, *args, **kwargs):\n        super().__init_subclass__(*args, **kwargs)\n        # Determine if this is a protocol or a concrete subclass.\n        if not cls.__dict__.get('_is_protocol', False):\n            cls._is_protocol = any(b is Protocol for b in cls.__bases__)", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-47", "text": "cls._is_protocol = any(b is Protocol for b in cls.__bases__)\n        # Set (or override) the protocol subclass hook.\n        def _proto_hook(other):\n            if not cls.__dict__.get('_is_protocol', False):\n                return NotImplemented\n            # First, perform various sanity checks.\n            if not getattr(cls, '_is_runtime_protocol', False):\n                if _allow_reckless_class_checks():\n                    return NotImplemented\n                raise TypeError(\"Instance and class checks can only be used with\"\n                                \" @runtime_checkable protocols\")\n            if not _is_callable_members_only(cls):\n                if _allow_reckless_class_checks():\n                    return NotImplemented\n                raise TypeError(\"Protocols with non-method members\"\n                                \" don't support issubclass()\")\n            if not isinstance(other, type):\n                # Same error message as for issubclass(1, int).\n                raise TypeError('issubclass() arg 1 must be a class')\n            # Second, perform the actual structural compatibility check.\n            for attr in _get_protocol_attrs(cls):\n                for base in other.__mro__:\n                    # Check if the members appears in the class dictionary...\n                    if attr in base.__dict__:\n                        if base.__dict__[attr] is None:\n                            return NotImplemented\n                        break\n                    # ...or in annotations, if it is a sub-protocol.\n                    annotations = getattr(base, '__annotations__', {})\n                    if (isinstance(annotations, collections.abc.Mapping) and\n                            attr in annotations and\n                            issubclass(other, Generic) and other._is_protocol):\n                        break\n                else:\n                    return NotImplemented\n            return True\n        if '__subclasshook__' not in cls.__dict__:\n            cls.__subclasshook__ = _proto_hook\n        # We have nothing more to do for non-protocols...", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-48", "text": "# We have nothing more to do for non-protocols...\n        if not cls._is_protocol:\n            return\n        # ... otherwise check consistency of bases, and prohibit instantiation.\n        for base in cls.__bases__:\n            if not (base in (object, Generic) or\n                    base.__module__ in _PROTO_ALLOWLIST and\n                    base.__name__ in _PROTO_ALLOWLIST[base.__module__] or\n                    issubclass(base, Generic) and base._is_protocol):\n                raise TypeError('Protocols can only inherit from other'\n                                ' protocols, got %r' % base)\n        if cls.__init__ is Protocol.__init__:\n            cls.__init__ = _no_init_or_replace_init\nclass _AnnotatedAlias(_NotIterable, _GenericAlias, _root=True):\n    \"\"\"Runtime representation of an annotated type.\n    At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'\n    with extra annotations. The alias behaves like a normal typing alias.\n    Instantiating is the same as instantiating the underlying type; binding\n    it to types is also the same.\n    The metadata itself is stored in a '__metadata__' attribute as a tuple.\n    \"\"\"\n    def __init__(self, origin, metadata):\n        if isinstance(origin, _AnnotatedAlias):\n            metadata = origin.__metadata__ + metadata\n            origin = origin.__origin__\n        super().__init__(origin, origin)\n        self.__metadata__ = metadata\n    def copy_with(self, params):\n        assert len(params) == 1\n        new_type = params[0]\n        return _AnnotatedAlias(new_type, self.__metadata__)\n    def __repr__(self):\n        return \"typing.Annotated[{}, {}]\".format(", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-49", "text": "return \"typing.Annotated[{}, {}]\".format(\n            _type_repr(self.__origin__),\n            \", \".join(repr(a) for a in self.__metadata__)\n        )\n    def __reduce__(self):\n        return operator.getitem, (\n            Annotated, (self.__origin__,) + self.__metadata__\n        )\n    def __eq__(self, other):\n        if not isinstance(other, _AnnotatedAlias):\n            return NotImplemented\n        return (self.__origin__ == other.__origin__\n                and self.__metadata__ == other.__metadata__)\n    def __hash__(self):\n        return hash((self.__origin__, self.__metadata__))\n    def __getattr__(self, attr):\n        if attr in {'__name__', '__qualname__'}:\n            return 'Annotated'\n        return super().__getattr__(attr)\nclass Annotated:\n    \"\"\"Add context-specific metadata to a type.\n    Example: Annotated[int, runtime_check.Unsigned] indicates to the\n    hypothetical runtime_check module that this type is an unsigned int.\n    Every other consumer of this type can ignore this metadata and treat\n    this type as int.\n    The first argument to Annotated must be a valid type.\n    Details:\n    - It's an error to call `Annotated` with less than two arguments.\n    - Access the metadata via the ``__metadata__`` attribute::\n        assert Annotated[int, '$'].__metadata__ == ('$',)\n    - Nested Annotated types are flattened::\n        assert Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]\n    - Instantiating an annotated type is equivalent to instantiating the\n    underlying type::", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-50", "text": "- Instantiating an annotated type is equivalent to instantiating the\n    underlying type::\n        assert Annotated[C, Ann1](5) == C(5)\n    - Annotated can be used as a generic type alias::\n        Optimized: TypeAlias = Annotated[T, runtime.Optimize()]\n        assert Optimized[int] == Annotated[int, runtime.Optimize()]\n        OptimizedList: TypeAlias = Annotated[list[T], runtime.Optimize()]\n        assert OptimizedList[int] == Annotated[list[int], runtime.Optimize()]\n    - Annotated cannot be used with an unpacked TypeVarTuple::\n        Variadic: TypeAlias = Annotated[*Ts, Ann1]  # NOT valid\n      This would be equivalent to::\n        Annotated[T1, T2, T3, ..., Ann1]\n      where T1, T2 etc. are TypeVars, which would be invalid, because\n      only one type should be passed to Annotated.\n    \"\"\"\n    __slots__ = ()\n    def __new__(cls, *args, **kwargs):\n        raise TypeError(\"Type Annotated cannot be instantiated.\")\n    @_tp_cache\n    def __class_getitem__(cls, params):\n        if not isinstance(params, tuple) or len(params) < 2:\n            raise TypeError(\"Annotated[...] should be used \"\n                            \"with at least two arguments (a type and an \"\n                            \"annotation).\")\n        if _is_unpacked_typevartuple(params[0]):\n            raise TypeError(\"Annotated[...] should not be used with an \"\n                            \"unpacked TypeVarTuple\")\n        msg = \"Annotated[t, ...]: t must be a type.\"\n        origin = _type_check(params[0], msg, allow_special_forms=True)", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-51", "text": "origin = _type_check(params[0], msg, allow_special_forms=True)\n        metadata = tuple(params[1:])\n        return _AnnotatedAlias(origin, metadata)\n    def __init_subclass__(cls, *args, **kwargs):\n        raise TypeError(\n            \"Cannot subclass {}.Annotated\".format(cls.__module__)\n        )\ndef runtime_checkable(cls):\n    \"\"\"Mark a protocol class as a runtime protocol.\n    Such protocol can be used with isinstance() and issubclass().\n    Raise TypeError if applied to a non-protocol class.\n    This allows a simple-minded structural check very similar to\n    one trick ponies in collections.abc such as Iterable.\n    For example::\n        @runtime_checkable\n        class Closable(Protocol):\n            def close(self): ...\n        assert isinstance(open('/some/file'), Closable)\n    Warning: this will check only the presence of the required methods,\n    not their type signatures!\n    \"\"\"\n    if not issubclass(cls, Generic) or not cls._is_protocol:\n        raise TypeError('@runtime_checkable can be only applied to protocol classes,'\n                        ' got %r' % cls)\n    cls._is_runtime_protocol = True\n    return cls\ndef cast(typ, val):\n    \"\"\"Cast a value to a type.\n    This returns the value unchanged.  To the type checker this\n    signals that the return value has the designated type, but at\n    runtime we intentionally don't check anything (we want this\n    to be as fast as possible).\n    \"\"\"\n    return val\ndef assert_type(val, typ, /):\n    \"\"\"Ask a static type checker to confirm that the value is of the given type.\n    At runtime this does nothing: it returns the first argument unchanged with no", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-52", "text": "At runtime this does nothing: it returns the first argument unchanged with no\n    checks or side effects, no matter the actual type of the argument.\n    When a static type checker encounters a call to assert_type(), it\n    emits an error if the value is not of the specified type::\n        def greet(name: str) -> None:\n            assert_type(name, str)  # OK\n            assert_type(name, int)  # type checker error\n    \"\"\"\n    return val\n_allowed_types = (types.FunctionType, types.BuiltinFunctionType,\n                  types.MethodType, types.ModuleType,\n                  WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)\ndef get_type_hints(obj, globalns=None, localns=None, include_extras=False):\n    \"\"\"Return type hints for an object.\n    This is often the same as obj.__annotations__, but it handles\n    forward references encoded as string literals and recursively replaces all\n    'Annotated[T, ...]' with 'T' (unless 'include_extras=True').\n    The argument may be a module, class, method, or function. The annotations\n    are returned as a dictionary. For classes, annotations include also\n    inherited members.\n    TypeError is raised if the argument is not of a type that can contain\n    annotations, and an empty dictionary is returned if no annotations are\n    present.\n    BEWARE -- the behavior of globalns and localns is counterintuitive\n    (unless you are familiar with how eval() and exec() work).  The\n    search order is locals first, then globals.\n    - If no dict arguments are passed, an attempt is made to use the\n      globals from obj (or the respective module's globals for classes),\n      and these are also used as the locals.  If the object does not appear", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-53", "text": "and these are also used as the locals.  If the object does not appear\n      to have globals, an empty dictionary is used.  For classes, the search\n      order is globals first then locals.\n    - If one dict argument is passed, it is used for both globals and\n      locals.\n    - If two dict arguments are passed, they specify globals and\n      locals, respectively.\n    \"\"\"\n    if getattr(obj, '__no_type_check__', None):\n        return {}\n    # Classes require a special treatment.\n    if isinstance(obj, type):\n        hints = {}\n        for base in reversed(obj.__mro__):\n            if globalns is None:\n                base_globals = getattr(sys.modules.get(base.__module__, None), '__dict__', {})\n            else:\n                base_globals = globalns\n            ann = base.__dict__.get('__annotations__', {})\n            if isinstance(ann, types.GetSetDescriptorType):\n                ann = {}\n            base_locals = dict(vars(base)) if localns is None else localns\n            if localns is None and globalns is None:\n                # This is surprising, but required.  Before Python 3.10,\n                # get_type_hints only evaluated the globalns of\n                # a class.  To maintain backwards compatibility, we reverse\n                # the globalns and localns order so that eval() looks into\n                # *base_globals* first rather than *base_locals*.\n                # This only affects ForwardRefs.\n                base_globals, base_locals = base_locals, base_globals\n            for name, value in ann.items():\n                if value is None:\n                    value = type(None)\n                if isinstance(value, str):\n                    value = ForwardRef(value, is_argument=False, is_class=True)\n                value = _eval_type(value, base_globals, base_locals)", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-54", "text": "value = _eval_type(value, base_globals, base_locals)\n                hints[name] = value\n        return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}\n    if globalns is None:\n        if isinstance(obj, types.ModuleType):\n            globalns = obj.__dict__\n        else:\n            nsobj = obj\n            # Find globalns for the unwrapped object.\n            while hasattr(nsobj, '__wrapped__'):\n                nsobj = nsobj.__wrapped__\n            globalns = getattr(nsobj, '__globals__', {})\n        if localns is None:\n            localns = globalns\n    elif localns is None:\n        localns = globalns\n    hints = getattr(obj, '__annotations__', None)\n    if hints is None:\n        # Return empty annotations for something that _could_ have them.\n        if isinstance(obj, _allowed_types):\n            return {}\n        else:\n            raise TypeError('{!r} is not a module, class, method, '\n                            'or function.'.format(obj))\n    hints = dict(hints)\n    for name, value in hints.items():\n        if value is None:\n            value = type(None)\n        if isinstance(value, str):\n            # class-level forward refs were handled above, this must be either\n            # a module-level annotation or a function argument annotation\n            value = ForwardRef(\n                value,\n                is_argument=not isinstance(obj, types.ModuleType),\n                is_class=False,\n            )\n        hints[name] = _eval_type(value, globalns, localns)\n    return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}\ndef _strip_annotations(t):\n    \"\"\"Strip the annotations from a given type.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-55", "text": "def _strip_annotations(t):\n    \"\"\"Strip the annotations from a given type.\"\"\"\n    if isinstance(t, _AnnotatedAlias):\n        return _strip_annotations(t.__origin__)\n    if hasattr(t, \"__origin__\") and t.__origin__ in (Required, NotRequired):\n        return _strip_annotations(t.__args__[0])\n    if isinstance(t, _GenericAlias):\n        stripped_args = tuple(_strip_annotations(a) for a in t.__args__)\n        if stripped_args == t.__args__:\n            return t\n        return t.copy_with(stripped_args)\n    if isinstance(t, GenericAlias):\n        stripped_args = tuple(_strip_annotations(a) for a in t.__args__)\n        if stripped_args == t.__args__:\n            return t\n        return GenericAlias(t.__origin__, stripped_args)\n    if isinstance(t, types.UnionType):\n        stripped_args = tuple(_strip_annotations(a) for a in t.__args__)\n        if stripped_args == t.__args__:\n            return t\n        return functools.reduce(operator.or_, stripped_args)\n    return t\ndef get_origin(tp):\n    \"\"\"Get the unsubscripted version of a type.\n    This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar,\n    Annotated, and others. Return None for unsupported types.\n    Examples::\n        assert get_origin(Literal[42]) is Literal\n        assert get_origin(int) is None\n        assert get_origin(ClassVar[int]) is ClassVar\n        assert get_origin(Generic) is Generic\n        assert get_origin(Generic[T]) is Generic\n        assert get_origin(Union[T, int]) is Union\n        assert get_origin(List[Tuple[T, T]][int]) is list\n        assert get_origin(P.args) is P\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-56", "text": "assert get_origin(P.args) is P\n    \"\"\"\n    if isinstance(tp, _AnnotatedAlias):\n        return Annotated\n    if isinstance(tp, (_BaseGenericAlias, GenericAlias,\n                       ParamSpecArgs, ParamSpecKwargs)):\n        return tp.__origin__\n    if tp is Generic:\n        return Generic\n    if isinstance(tp, types.UnionType):\n        return types.UnionType\n    return None\ndef get_args(tp):\n    \"\"\"Get type arguments with all substitutions performed.\n    For unions, basic simplifications used by Union constructor are performed.\n    Examples::\n        assert get_args(Dict[str, int]) == (str, int)\n        assert get_args(int) == ()\n        assert get_args(Union[int, Union[T, int], str][int]) == (int, str)\n        assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])\n        assert get_args(Callable[[], T][int]) == ([], int)\n    \"\"\"\n    if isinstance(tp, _AnnotatedAlias):\n        return (tp.__origin__,) + tp.__metadata__\n    if isinstance(tp, (_GenericAlias, GenericAlias)):\n        res = tp.__args__\n        if _should_unflatten_callable_args(tp, res):\n            res = (list(res[:-1]), res[-1])\n        return res\n    if isinstance(tp, types.UnionType):\n        return tp.__args__\n    return ()\ndef is_typeddict(tp):\n    \"\"\"Check if an annotation is a TypedDict class.\n    For example::\n        class Film(TypedDict):\n            title: str\n            year: int\n        is_typeddict(Film)              # => True\n        is_typeddict(Union[list, str])  # => False", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-57", "text": "is_typeddict(Union[list, str])  # => False\n    \"\"\"\n    return isinstance(tp, _TypedDictMeta)\n_ASSERT_NEVER_REPR_MAX_LENGTH = 100\ndef assert_never(arg: Never, /) -> Never:\n    \"\"\"Statically assert that a line of code is unreachable.\n    Example::\n        def int_or_str(arg: int | str) -> None:\n            match arg:\n                case int():\n                    print(\"It's an int\")\n                case str():\n                    print(\"It's a str\")\n                case _:\n                    assert_never(arg)\n    If a type checker finds that a call to assert_never() is\n    reachable, it will emit an error.\n    At runtime, this throws an exception when called.\n    \"\"\"\n    value = repr(arg)\n    if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH:\n        value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...'\n    raise AssertionError(f\"Expected code to be unreachable, but got: {value}\")\ndef no_type_check(arg):\n    \"\"\"Decorator to indicate that annotations are not type hints.\n    The argument must be a class or function; if it is a class, it\n    applies recursively to all methods and classes defined in that class\n    (but not to methods defined in its superclasses or subclasses).\n    This mutates the function(s) or class(es) in place.\n    \"\"\"\n    if isinstance(arg, type):\n        for key in dir(arg):\n            obj = getattr(arg, key)\n            if (\n                not hasattr(obj, '__qualname__')\n                or obj.__qualname__ != f'{arg.__qualname__}.{obj.__name__}'\n                or getattr(obj, '__module__', None) != arg.__module__\n            ):", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-58", "text": "or getattr(obj, '__module__', None) != arg.__module__\n            ):\n                # We only modify objects that are defined in this type directly.\n                # If classes / methods are nested in multiple layers,\n                # we will modify them when processing their direct holders.\n                continue\n            # Instance, class, and static methods:\n            if isinstance(obj, types.FunctionType):\n                obj.__no_type_check__ = True\n            if isinstance(obj, types.MethodType):\n                obj.__func__.__no_type_check__ = True\n            # Nested types:\n            if isinstance(obj, type):\n                no_type_check(obj)\n    try:\n        arg.__no_type_check__ = True\n    except TypeError:  # built-in classes\n        pass\n    return arg\ndef no_type_check_decorator(decorator):\n    \"\"\"Decorator to give another decorator the @no_type_check effect.\n    This wraps the decorator with something that wraps the decorated\n    function in @no_type_check.\n    \"\"\"\n    @functools.wraps(decorator)\n    def wrapped_decorator(*args, **kwds):\n        func = decorator(*args, **kwds)\n        func = no_type_check(func)\n        return func\n    return wrapped_decorator\ndef _overload_dummy(*args, **kwds):\n    \"\"\"Helper for @overload to raise when called.\"\"\"\n    raise NotImplementedError(\n        \"You should not call an overloaded function. \"\n        \"A series of @overload-decorated functions \"\n        \"outside a stub module should always be followed \"\n        \"by an implementation that is not @overload-ed.\")\n# {module: {qualname: {firstlineno: func}}}\n_overload_registry = defaultdict(functools.partial(defaultdict, dict))\ndef overload(func):\n    \"\"\"Decorator for overloaded functions/methods.", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-59", "text": "def overload(func):\n    \"\"\"Decorator for overloaded functions/methods.\n    In a stub file, place two or more stub definitions for the same\n    function in a row, each decorated with @overload.\n    For example::\n        @overload\n        def utf8(value: None) -> None: ...\n        @overload\n        def utf8(value: bytes) -> bytes: ...\n        @overload\n        def utf8(value: str) -> bytes: ...\n    In a non-stub file (i.e. a regular .py file), do the same but\n    follow it with an implementation.  The implementation should *not*\n    be decorated with @overload::\n        @overload\n        def utf8(value: None) -> None: ...\n        @overload\n        def utf8(value: bytes) -> bytes: ...\n        @overload\n        def utf8(value: str) -> bytes: ...\n        def utf8(value):\n            ...  # implementation goes here\n    The overloads for a function can be retrieved at runtime using the\n    get_overloads() function.\n    \"\"\"\n    # classmethod and staticmethod\n    f = getattr(func, \"__func__\", func)\n    try:\n        _overload_registry[f.__module__][f.__qualname__][f.__code__.co_firstlineno] = func\n    except AttributeError:\n        # Not a normal function; ignore.\n        pass\n    return _overload_dummy\ndef get_overloads(func):\n    \"\"\"Return all defined overloads for *func* as a sequence.\"\"\"\n    # classmethod and staticmethod\n    f = getattr(func, \"__func__\", func)\n    if f.__module__ not in _overload_registry:\n        return []\n    mod_dict = _overload_registry[f.__module__]", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-60", "text": "return []\n    mod_dict = _overload_registry[f.__module__]\n    if f.__qualname__ not in mod_dict:\n        return []\n    return list(mod_dict[f.__qualname__].values())\ndef clear_overloads():\n    \"\"\"Clear all overloads in the registry.\"\"\"\n    _overload_registry.clear()\ndef final(f):\n    \"\"\"Decorator to indicate final methods and final classes.\n    Use this decorator to indicate to type checkers that the decorated\n    method cannot be overridden, and decorated class cannot be subclassed.\n    For example::\n        class Base:\n            @final\n            def done(self) -> None:\n                ...\n        class Sub(Base):\n            def done(self) -> None:  # Error reported by type checker\n                ...\n        @final\n        class Leaf:\n            ...\n        class Other(Leaf):  # Error reported by type checker\n            ...\n    There is no runtime checking of these properties. The decorator\n    attempts to set the ``__final__`` attribute to ``True`` on the decorated\n    object to allow runtime introspection.\n    \"\"\"\n    try:\n        f.__final__ = True\n    except (AttributeError, TypeError):\n        # Skip the attribute silently if it is not writable.\n        # AttributeError happens if the object has __slots__ or a\n        # read-only property, TypeError if it's a builtin class.\n        pass\n    return f\n# Some unconstrained type variables.  These are used by the container types.\n# (These are not for export.)\nT = TypeVar('T')  # Any type.\nKT = TypeVar('KT')  # Key type.\nVT = TypeVar('VT')  # Value type.", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-61", "text": "VT = TypeVar('VT')  # Value type.\nT_co = TypeVar('T_co', covariant=True)  # Any type covariant containers.\nV_co = TypeVar('V_co', covariant=True)  # Any type covariant containers.\nVT_co = TypeVar('VT_co', covariant=True)  # Value type covariant containers.\nT_contra = TypeVar('T_contra', contravariant=True)  # Ditto contravariant.\n# Internal type variable used for Type[].\nCT_co = TypeVar('CT_co', covariant=True, bound=type)\n# A useful type variable with constraints.  This represents string types.\n# (This one *is* for export!)\nAnyStr = TypeVar('AnyStr', bytes, str)\n# Various ABCs mimicking those in collections.abc.\n_alias = _SpecialGenericAlias\nHashable = _alias(collections.abc.Hashable, 0)  # Not generic.\nAwaitable = _alias(collections.abc.Awaitable, 1)\nCoroutine = _alias(collections.abc.Coroutine, 3)\nAsyncIterable = _alias(collections.abc.AsyncIterable, 1)\nAsyncIterator = _alias(collections.abc.AsyncIterator, 1)\nIterable = _alias(collections.abc.Iterable, 1)\nIterator = _alias(collections.abc.Iterator, 1)\nReversible = _alias(collections.abc.Reversible, 1)\nSized = _alias(collections.abc.Sized, 0)  # Not generic.\nContainer = _alias(collections.abc.Container, 1)\nCollection = _alias(collections.abc.Collection, 1)\nCallable = _CallableType(collections.abc.Callable, 2)\nCallable.__doc__ = \\", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-62", "text": "Callable.__doc__ = \\\n    \"\"\"Deprecated alias to collections.abc.Callable.\n    Callable[[int], str] signifies a function that takes a single\n    parameter of type int and returns a str.\n    The subscription syntax must always be used with exactly two\n    values: the argument list and the return type.\n    The argument list must be a list of types, a ParamSpec,\n    Concatenate or ellipsis. The return type must be a single type.\n    There is no syntax to indicate optional or keyword arguments;\n    such function types are rarely used as callback types.\n    \"\"\"\nAbstractSet = _alias(collections.abc.Set, 1, name='AbstractSet')\nMutableSet = _alias(collections.abc.MutableSet, 1)\n# NOTE: Mapping is only covariant in the value type.\nMapping = _alias(collections.abc.Mapping, 2)\nMutableMapping = _alias(collections.abc.MutableMapping, 2)\nSequence = _alias(collections.abc.Sequence, 1)\nMutableSequence = _alias(collections.abc.MutableSequence, 1)\nByteString = _alias(collections.abc.ByteString, 0)  # Not generic\n# Tuple accepts variable number of parameters.\nTuple = _TupleType(tuple, -1, inst=False, name='Tuple')\nTuple.__doc__ = \\\n    \"\"\"Deprecated alias to builtins.tuple.\n    Tuple[X, Y] is the cross-product type of X and Y.\n    Example: Tuple[T1, T2] is a tuple of two elements corresponding\n    to type variables T1 and T2.  Tuple[int, float, str] is a tuple\n    of an int, a float and a string.\n    To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-63", "text": "\"\"\"\nList = _alias(list, 1, inst=False, name='List')\nDeque = _alias(collections.deque, 1, name='Deque')\nSet = _alias(set, 1, inst=False, name='Set')\nFrozenSet = _alias(frozenset, 1, inst=False, name='FrozenSet')\nMappingView = _alias(collections.abc.MappingView, 1)\nKeysView = _alias(collections.abc.KeysView, 1)\nItemsView = _alias(collections.abc.ItemsView, 2)\nValuesView = _alias(collections.abc.ValuesView, 1)\nContextManager = _alias(contextlib.AbstractContextManager, 1, name='ContextManager')\nAsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, 1, name='AsyncContextManager')\nDict = _alias(dict, 2, inst=False, name='Dict')\nDefaultDict = _alias(collections.defaultdict, 2, name='DefaultDict')\nOrderedDict = _alias(collections.OrderedDict, 2)\nCounter = _alias(collections.Counter, 1)\nChainMap = _alias(collections.ChainMap, 2)\nGenerator = _alias(collections.abc.Generator, 3)\nAsyncGenerator = _alias(collections.abc.AsyncGenerator, 2)\nType = _alias(type, 1, inst=False, name='Type')\nType.__doc__ = \\\n    \"\"\"Deprecated alias to builtins.type.\n    builtins.type or typing.Type can be used to annotate class objects.\n    For example, suppose we have the following classes::\n        class User: ...  # Abstract base for User classes\n        class BasicUser(User): ...\n        class ProUser(User): ...\n        class TeamUser(User): ...", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-64", "text": "class ProUser(User): ...\n        class TeamUser(User): ...\n    And a function that takes a class argument that's a subclass of\n    User and returns an instance of the corresponding class::\n        U = TypeVar('U', bound=User)\n        def new_user(user_class: Type[U]) -> U:\n            user = user_class()\n            # (Here we could write the user object to a database)\n            return user\n        joe = new_user(BasicUser)\n    At this point the type checker knows that joe has type BasicUser.\n    \"\"\"\n@runtime_checkable\nclass SupportsInt(Protocol):\n    \"\"\"An ABC with one abstract method __int__.\"\"\"\n    __slots__ = ()\n    @abstractmethod\n    def __int__(self) -> int:\n        pass\n@runtime_checkable\nclass SupportsFloat(Protocol):\n    \"\"\"An ABC with one abstract method __float__.\"\"\"\n    __slots__ = ()\n    @abstractmethod\n    def __float__(self) -> float:\n        pass\n@runtime_checkable\nclass SupportsComplex(Protocol):\n    \"\"\"An ABC with one abstract method __complex__.\"\"\"\n    __slots__ = ()\n    @abstractmethod\n    def __complex__(self) -> complex:\n        pass\n@runtime_checkable\nclass SupportsBytes(Protocol):\n    \"\"\"An ABC with one abstract method __bytes__.\"\"\"\n    __slots__ = ()\n    @abstractmethod\n    def __bytes__(self) -> bytes:\n        pass\n@runtime_checkable\nclass SupportsIndex(Protocol):\n    \"\"\"An ABC with one abstract method __index__.\"\"\"\n    __slots__ = ()\n    @abstractmethod\n    def __index__(self) -> int:\n        pass\n@runtime_checkable\nclass SupportsAbs(Protocol[T_co]):", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-65", "text": "pass\n@runtime_checkable\nclass SupportsAbs(Protocol[T_co]):\n    \"\"\"An ABC with one abstract method __abs__ that is covariant in its return type.\"\"\"\n    __slots__ = ()\n    @abstractmethod\n    def __abs__(self) -> T_co:\n        pass\n@runtime_checkable\nclass SupportsRound(Protocol[T_co]):\n    \"\"\"An ABC with one abstract method __round__ that is covariant in its return type.\"\"\"\n    __slots__ = ()\n    @abstractmethod\n    def __round__(self, ndigits: int = 0) -> T_co:\n        pass\ndef _make_nmtuple(name, types, module, defaults = ()):\n    fields = [n for n, t in types]\n    types = {n: _type_check(t, f\"field {n} annotation must be a type\")\n             for n, t in types}\n    nm_tpl = collections.namedtuple(name, fields,\n                                    defaults=defaults, module=module)\n    nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types\n    return nm_tpl\n# attributes prohibited to set in NamedTuple class syntax\n_prohibited = frozenset({'__new__', '__init__', '__slots__', '__getnewargs__',\n                         '_fields', '_field_defaults',\n                         '_make', '_replace', '_asdict', '_source'})\n_special = frozenset({'__module__', '__name__', '__annotations__'})\nclass NamedTupleMeta(type):\n    def __new__(cls, typename, bases, ns):\n        assert _NamedTuple in bases\n        for base in bases:\n            if base is not _NamedTuple and base is not Generic:\n                raise TypeError(\n                    'can only inherit from a NamedTuple type and Generic')", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-66", "text": "raise TypeError(\n                    'can only inherit from a NamedTuple type and Generic')\n        bases = tuple(tuple if base is _NamedTuple else base for base in bases)\n        types = ns.get('__annotations__', {})\n        default_names = []\n        for field_name in types:\n            if field_name in ns:\n                default_names.append(field_name)\n            elif default_names:\n                raise TypeError(f\"Non-default namedtuple field {field_name} \"\n                                f\"cannot follow default field\"\n                                f\"{'s' if len(default_names) > 1 else ''} \"\n                                f\"{', '.join(default_names)}\")\n        nm_tpl = _make_nmtuple(typename, types.items(),\n                               defaults=[ns[n] for n in default_names],\n                               module=ns['__module__'])\n        nm_tpl.__bases__ = bases\n        if Generic in bases:\n            class_getitem = Generic.__class_getitem__.__func__\n            nm_tpl.__class_getitem__ = classmethod(class_getitem)\n        # update from user namespace without overriding special namedtuple attributes\n        for key in ns:\n            if key in _prohibited:\n                raise AttributeError(\"Cannot overwrite NamedTuple attribute \" + key)\n            elif key not in _special and key not in nm_tpl._fields:\n                setattr(nm_tpl, key, ns[key])\n        if Generic in bases:\n            nm_tpl.__init_subclass__()\n        return nm_tpl\ndef NamedTuple(typename, fields=None, /, **kwargs):\n    \"\"\"Typed version of namedtuple.\n    Usage::\n        class Employee(NamedTuple):\n            name: str\n            id: int\n    This is equivalent to::\n        Employee = collections.namedtuple('Employee', ['name', 'id'])\n    The resulting class has an extra __annotations__ attribute, giving a", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-67", "text": "The resulting class has an extra __annotations__ attribute, giving a\n    dict that maps field names to types.  (The field names are also in\n    the _fields attribute, which is part of the namedtuple API.)\n    An alternative equivalent functional syntax is also accepted::\n        Employee = NamedTuple('Employee', [('name', str), ('id', int)])\n    \"\"\"\n    if fields is None:\n        fields = kwargs.items()\n    elif kwargs:\n        raise TypeError(\"Either list of fields or keywords\"\n                        \" can be provided to NamedTuple, not both\")\n    return _make_nmtuple(typename, fields, module=_caller())\n_NamedTuple = type.__new__(NamedTupleMeta, 'NamedTuple', (), {})\ndef _namedtuple_mro_entries(bases):\n    assert NamedTuple in bases\n    return (_NamedTuple,)\nNamedTuple.__mro_entries__ = _namedtuple_mro_entries\nclass _TypedDictMeta(type):\n    def __new__(cls, name, bases, ns, total=True):\n        \"\"\"Create a new typed dict class object.\n        This method is called when TypedDict is subclassed,\n        or when TypedDict is instantiated. This way\n        TypedDict supports all three syntax forms described in its docstring.\n        Subclasses and instances of TypedDict return actual dictionaries.\n        \"\"\"\n        for base in bases:\n            if type(base) is not _TypedDictMeta and base is not Generic:\n                raise TypeError('cannot inherit from both a TypedDict type '\n                                'and a non-TypedDict base class')\n        if any(issubclass(b, Generic) for b in bases):\n            generic_base = (Generic,)\n        else:\n            generic_base = ()", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-68", "text": "generic_base = (Generic,)\n        else:\n            generic_base = ()\n        tp_dict = type.__new__(_TypedDictMeta, name, (*generic_base, dict), ns)\n        annotations = {}\n        own_annotations = ns.get('__annotations__', {})\n        msg = \"TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type\"\n        own_annotations = {\n            n: _type_check(tp, msg, module=tp_dict.__module__)\n            for n, tp in own_annotations.items()\n        }\n        required_keys = set()\n        optional_keys = set()\n        for base in bases:\n            annotations.update(base.__dict__.get('__annotations__', {}))\n            required_keys.update(base.__dict__.get('__required_keys__', ()))\n            optional_keys.update(base.__dict__.get('__optional_keys__', ()))\n        annotations.update(own_annotations)\n        for annotation_key, annotation_type in own_annotations.items():\n            annotation_origin = get_origin(annotation_type)\n            if annotation_origin is Annotated:\n                annotation_args = get_args(annotation_type)\n                if annotation_args:\n                    annotation_type = annotation_args[0]\n                    annotation_origin = get_origin(annotation_type)\n            if annotation_origin is Required:\n                required_keys.add(annotation_key)\n            elif annotation_origin is NotRequired:\n                optional_keys.add(annotation_key)\n            elif total:\n                required_keys.add(annotation_key)\n            else:\n                optional_keys.add(annotation_key)\n        tp_dict.__annotations__ = annotations\n        tp_dict.__required_keys__ = frozenset(required_keys)\n        tp_dict.__optional_keys__ = frozenset(optional_keys)\n        if not hasattr(tp_dict, '__total__'):\n            tp_dict.__total__ = total\n        return tp_dict", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-69", "text": "tp_dict.__total__ = total\n        return tp_dict\n    __call__ = dict  # static method\n    def __subclasscheck__(cls, other):\n        # Typed dicts are only for static structural subtyping.\n        raise TypeError('TypedDict does not support instance and class checks')\n    __instancecheck__ = __subclasscheck__\ndef TypedDict(typename, fields=None, /, *, total=True, **kwargs):\n    \"\"\"A simple typed namespace. At runtime it is equivalent to a plain dict.\n    TypedDict creates a dictionary type such that a type checker will expect all\n    instances to have a certain set of keys, where each key is\n    associated with a value of a consistent type. This expectation\n    is not checked at runtime.\n    Usage::\n        class Point2D(TypedDict):\n            x: int\n            y: int\n            label: str\n        a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK\n        b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check\n        assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')\n    The type info can be accessed via the Point2D.__annotations__ dict, and\n    the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.\n    TypedDict supports an additional equivalent form::\n        Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})\n    By default, all keys must be present in a TypedDict. It is possible\n    to override this by specifying totality::\n        class Point2D(TypedDict, total=False):", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-70", "text": "class Point2D(TypedDict, total=False):\n            x: int\n            y: int\n    This means that a Point2D TypedDict can have any of the keys omitted. A type\n    checker is only expected to support a literal False or True as the value of\n    the total argument. True is the default, and makes all items defined in the\n    class body be required.\n    The Required and NotRequired special forms can also be used to mark\n    individual keys as being required or not required::\n        class Point2D(TypedDict):\n            x: int               # the \"x\" key must always be present (Required is the default)\n            y: NotRequired[int]  # the \"y\" key can be omitted\n    See PEP 655 for more details on Required and NotRequired.\n    \"\"\"\n    if fields is None:\n        fields = kwargs\n    elif kwargs:\n        raise TypeError(\"TypedDict takes either a dict or keyword arguments,\"\n                        \" but not both\")\n    if kwargs:\n        warnings.warn(\n            \"The kwargs-based syntax for TypedDict definitions is deprecated \"\n            \"in Python 3.11, will be removed in Python 3.13, and may not be \"\n            \"understood by third-party type checkers.\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n    ns = {'__annotations__': dict(fields)}\n    module = _caller()\n    if module is not None:\n        # Setting correct module is necessary to make typed dict classes pickleable.\n        ns['__module__'] = module\n    return _TypedDictMeta(typename, (), ns, total=total)\n_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-71", "text": "_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})\nTypedDict.__mro_entries__ = lambda bases: (_TypedDict,)\n@_SpecialForm\ndef Required(self, parameters):\n    \"\"\"Special typing construct to mark a TypedDict key as required.\n    This is mainly useful for total=False TypedDicts.\n    For example::\n        class Movie(TypedDict, total=False):\n            title: Required[str]\n            year: int\n        m = Movie(\n            title='The Matrix',  # typechecker error if key is omitted\n            year=1999,\n        )\n    There is no runtime checking that a required key is actually provided\n    when instantiating a related TypedDict.\n    \"\"\"\n    item = _type_check(parameters, f'{self._name} accepts only a single type.')\n    return _GenericAlias(self, (item,))\n@_SpecialForm\ndef NotRequired(self, parameters):\n    \"\"\"Special typing construct to mark a TypedDict key as potentially missing.\n    For example::\n        class Movie(TypedDict):\n            title: str\n            year: NotRequired[int]\n        m = Movie(\n            title='The Matrix',  # typechecker error if key is omitted\n            year=1999,\n        )\n    \"\"\"\n    item = _type_check(parameters, f'{self._name} accepts only a single type.')\n    return _GenericAlias(self, (item,))\nclass NewType:\n    \"\"\"NewType creates simple unique types with almost zero runtime overhead.\n    NewType(name, tp) is considered a subtype of tp\n    by static type checkers. At runtime, NewType(name, tp) returns\n    a dummy callable that simply returns its argument.\n    Usage::\n        UserId = NewType('UserId', int)", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-72", "text": "Usage::\n        UserId = NewType('UserId', int)\n        def name_by_id(user_id: UserId) -> str:\n            ...\n        UserId('user')          # Fails type check\n        name_by_id(42)          # Fails type check\n        name_by_id(UserId(42))  # OK\n        num = UserId(5) + 1     # type: int\n    \"\"\"\n    __call__ = _idfunc\n    def __init__(self, name, tp):\n        self.__qualname__ = name\n        if '.' in name:\n            name = name.rpartition('.')[-1]\n        self.__name__ = name\n        self.__supertype__ = tp\n        def_mod = _caller()\n        if def_mod != 'typing':\n            self.__module__ = def_mod\n    def __mro_entries__(self, bases):\n        # We defined __mro_entries__ to get a better error message\n        # if a user attempts to subclass a NewType instance. bpo-46170\n        superclass_name = self.__name__\n        class Dummy:\n            def __init_subclass__(cls):\n                subclass_name = cls.__name__\n                raise TypeError(\n                    f\"Cannot subclass an instance of NewType. Perhaps you were looking for: \"\n                    f\"`{subclass_name} = NewType({subclass_name!r}, {superclass_name})`\"\n                )\n        return (Dummy,)\n    def __repr__(self):\n        return f'{self.__module__}.{self.__qualname__}'\n    def __reduce__(self):\n        return self.__qualname__\n    def __or__(self, other):\n        return Union[self, other]\n    def __ror__(self, other):\n        return Union[other, self]", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-73", "text": "def __ror__(self, other):\n        return Union[other, self]\n# Python-version-specific alias (Python 2: unicode; Python 3: str)\nText = str\n# Constant that's True when type checking, but False here.\nTYPE_CHECKING = False\nclass IO(Generic[AnyStr]):\n    \"\"\"Generic base class for TextIO and BinaryIO.\n    This is an abstract, generic version of the return of open().\n    NOTE: This does not distinguish between the different possible\n    classes (text vs. binary, read vs. write vs. read/write,\n    append-only, unbuffered).  The TextIO and BinaryIO subclasses\n    below capture the distinctions between text vs. binary, which is\n    pervasive in the interface; however we currently do not offer a\n    way to track the other distinctions in the type system.\n    \"\"\"\n    __slots__ = ()\n    @property\n    @abstractmethod\n    def mode(self) -> str:\n        pass\n    @property\n    @abstractmethod\n    def name(self) -> str:\n        pass\n    @abstractmethod\n    def close(self) -> None:\n        pass\n    @property\n    @abstractmethod\n    def closed(self) -> bool:\n        pass\n    @abstractmethod\n    def fileno(self) -> int:\n        pass\n    @abstractmethod\n    def flush(self) -> None:\n        pass\n    @abstractmethod\n    def isatty(self) -> bool:\n        pass\n    @abstractmethod\n    def read(self, n: int = -1) -> AnyStr:\n        pass\n    @abstractmethod\n    def readable(self) -> bool:\n        pass\n    @abstractmethod\n    def readline(self, limit: int = -1) -> AnyStr:\n        pass\n    @abstractmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-74", "text": "pass\n    @abstractmethod\n    def readlines(self, hint: int = -1) -> List[AnyStr]:\n        pass\n    @abstractmethod\n    def seek(self, offset: int, whence: int = 0) -> int:\n        pass\n    @abstractmethod\n    def seekable(self) -> bool:\n        pass\n    @abstractmethod\n    def tell(self) -> int:\n        pass\n    @abstractmethod\n    def truncate(self, size: int = None) -> int:\n        pass\n    @abstractmethod\n    def writable(self) -> bool:\n        pass\n    @abstractmethod\n    def write(self, s: AnyStr) -> int:\n        pass\n    @abstractmethod\n    def writelines(self, lines: List[AnyStr]) -> None:\n        pass\n    @abstractmethod\n    def __enter__(self) -> 'IO[AnyStr]':\n        pass\n    @abstractmethod\n    def __exit__(self, type, value, traceback) -> None:\n        pass\nclass BinaryIO(IO[bytes]):\n    \"\"\"Typed version of the return of open() in binary mode.\"\"\"\n    __slots__ = ()\n    @abstractmethod\n    def write(self, s: Union[bytes, bytearray]) -> int:\n        pass\n    @abstractmethod\n    def __enter__(self) -> 'BinaryIO':\n        pass\nclass TextIO(IO[str]):\n    \"\"\"Typed version of the return of open() in text mode.\"\"\"\n    __slots__ = ()\n    @property\n    @abstractmethod\n    def buffer(self) -> BinaryIO:\n        pass\n    @property\n    @abstractmethod\n    def encoding(self) -> str:\n        pass\n    @property\n    @abstractmethod\n    def errors(self) -> Optional[str]:\n        pass\n    @property\n    @abstractmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-75", "text": "pass\n    @property\n    @abstractmethod\n    def line_buffering(self) -> bool:\n        pass\n    @property\n    @abstractmethod\n    def newlines(self) -> Any:\n        pass\n    @abstractmethod\n    def __enter__(self) -> 'TextIO':\n        pass\nclass _DeprecatedType(type):\n    def __getattribute__(cls, name):\n        if name not in (\"__dict__\", \"__module__\") and name in cls.__dict__:\n            warnings.warn(\n                f\"{cls.__name__} is deprecated, import directly \"\n                f\"from typing instead. {cls.__name__} will be removed \"\n                \"in Python 3.12.\",\n                DeprecationWarning,\n                stacklevel=2,\n            )\n        return super().__getattribute__(name)\nclass io(metaclass=_DeprecatedType):\n    \"\"\"Wrapper namespace for IO generic classes.\"\"\"\n    __all__ = ['IO', 'TextIO', 'BinaryIO']\n    IO = IO\n    TextIO = TextIO\n    BinaryIO = BinaryIO\nio.__name__ = __name__ + '.io'\nsys.modules[io.__name__] = io\nPattern = _alias(stdlib_re.Pattern, 1)\nMatch = _alias(stdlib_re.Match, 1)\nclass re(metaclass=_DeprecatedType):\n    \"\"\"Wrapper namespace for re type aliases.\"\"\"\n    __all__ = ['Pattern', 'Match']\n    Pattern = Pattern\n    Match = Match\nre.__name__ = __name__ + '.re'\nsys.modules[re.__name__] = re\ndef reveal_type(obj: T, /) -> T:\n    \"\"\"Reveal the inferred type of a variable.\n    When a static type checker encounters a call to ``reveal_type()``,", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-76", "text": "When a static type checker encounters a call to ``reveal_type()``,\n    it will emit the inferred type of the argument::\n        x: int = 1\n        reveal_type(x)\n    Running a static type checker (e.g., mypy) on this example\n    will produce output similar to 'Revealed type is \"builtins.int\"'.\n    At runtime, the function prints the runtime type of the\n    argument and returns it unchanged.\n    \"\"\"\n    print(f\"Runtime type is {type(obj).__name__!r}\", file=sys.stderr)\n    return obj\ndef dataclass_transform(\n    *,\n    eq_default: bool = True,\n    order_default: bool = False,\n    kw_only_default: bool = False,\n    field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (),\n    **kwargs: Any,\n) -> Callable[[T], T]:\n    \"\"\"Decorator to mark an object as providing dataclass-like behaviour.\n    The decorator can be applied to a function, class, or metaclass.\n    Example usage with a decorator function::\n        T = TypeVar(\"T\")\n        @dataclass_transform()\n        def create_model(cls: type[T]) -> type[T]:\n            ...\n            return cls\n        @create_model\n        class CustomerModel:\n            id: int\n            name: str\n    On a base class::\n        @dataclass_transform()\n        class ModelBase: ...\n        class CustomerModel(ModelBase):\n            id: int\n            name: str\n    On a metaclass::\n        @dataclass_transform()\n        class ModelMeta(type): ...\n        class ModelBase(metaclass=ModelMeta): ...\n        class CustomerModel(ModelBase):\n            id: int\n            name: str", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "356e2cfe11ce-77", "text": "class CustomerModel(ModelBase):\n            id: int\n            name: str\n    The ``CustomerModel`` classes defined above will\n    be treated by type checkers similarly to classes created with\n    ``@dataclasses.dataclass``.\n    For example, type checkers will assume these classes have\n    ``__init__`` methods that accept ``id`` and ``name``.\n    The arguments to this decorator can be used to customize this behavior:\n    - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be\n        ``True`` or ``False`` if it is omitted by the caller.\n    - ``order_default`` indicates whether the ``order`` parameter is\n        assumed to be True or False if it is omitted by the caller.\n    - ``kw_only_default`` indicates whether the ``kw_only`` parameter is\n        assumed to be True or False if it is omitted by the caller.\n    - ``field_specifiers`` specifies a static list of supported classes\n        or functions that describe fields, similar to ``dataclasses.field()``.\n    - Arbitrary other keyword arguments are accepted in order to allow for\n        possible future extensions.\n    At runtime, this decorator records its arguments in the\n    ``__dataclass_transform__`` attribute on the decorated object.\n    It has no other runtime effect.\n    See PEP 681 for more details.\n    \"\"\"\n    def decorator(cls_or_fn):\n        cls_or_fn.__dataclass_transform__ = {\n            \"eq_default\": eq_default,\n            \"order_default\": order_default,\n            \"kw_only_default\": kw_only_default,\n            \"field_specifiers\": field_specifiers,\n            \"kwargs\": kwargs,\n        }\n        return cls_or_fn\n    return decorator", "source": "lang/api.python.langchain.com/en/latest/_modules/typing.html"}
{"id": "a3b43ace734b-0", "text": "Source code for _markupbase\n\"\"\"Shared support for scanning document type declarations in HTML and XHTML.\nThis module is used as a foundation for the html.parser module.  It has no\ndocumented public API and should not be used directly.\n\"\"\"\nimport re\n_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9]*\\s*').match\n_declstringlit_match = re.compile(r'(\\'[^\\']*\\'|\"[^\"]*\")\\s*').match\n_commentclose = re.compile(r'--\\s*>')\n_markedsectionclose = re.compile(r']\\s*]\\s*>')\n# An analysis of the MS-Word extensions is available at\n# http://www.planetpublish.com/xmlarena/xap/Thursday/WordtoXML.pdf\n_msmarkedsectionclose = re.compile(r']\\s*>')\ndel re\nclass ParserBase:\n    \"\"\"Parser base class which provides some common support methods used\n    by the SGML/HTML and XHTML parsers.\"\"\"\n    def __init__(self):\n        if self.__class__ is ParserBase:\n            raise RuntimeError(\n                \"_markupbase.ParserBase must be subclassed\")\n    def reset(self):\n        self.lineno = 1\n        self.offset = 0\n    def getpos(self):\n        \"\"\"Return current line number and offset.\"\"\"\n        return self.lineno, self.offset\n    # Internal -- update line number and offset.  This should be\n    # called for each piece of data exactly once, in order -- in other\n    # words the concatenation of all the input strings to this\n    # function should be exactly the entire input.\n    def updatepos(self, i, j):\n        if i >= j:\n            return j\n        rawdata = self.rawdata", "source": "lang/api.python.langchain.com/en/latest/_modules/_markupbase.html"}
{"id": "a3b43ace734b-1", "text": "if i >= j:\n            return j\n        rawdata = self.rawdata\n        nlines = rawdata.count(\"\\n\", i, j)\n        if nlines:\n            self.lineno = self.lineno + nlines\n            pos = rawdata.rindex(\"\\n\", i, j) # Should not fail\n            self.offset = j-(pos+1)\n        else:\n            self.offset = self.offset + j-i\n        return j\n    _decl_otherchars = ''\n    # Internal -- parse declaration (for use by subclasses).\n    def parse_declaration(self, i):\n        # This is some sort of declaration; in \"HTML as\n        # deployed,\" this should only be the document type\n        # declaration (\"<!DOCTYPE html...>\").\n        # ISO 8879:1986, however, has more complex\n        # declaration syntax for elements in <!...>, including:\n        # --comment--\n        # [marked section]\n        # name in the following list: ENTITY, DOCTYPE, ELEMENT,\n        # ATTLIST, NOTATION, SHORTREF, USEMAP,\n        # LINKTYPE, LINK, IDLINK, USELINK, SYSTEM\n        rawdata = self.rawdata\n        j = i + 2\n        assert rawdata[i:j] == \"<!\", \"unexpected call to parse_declaration\"\n        if rawdata[j:j+1] == \">\":\n            # the empty comment <!>\n            return j + 1\n        if rawdata[j:j+1] in (\"-\", \"\"):\n            # Start of comment followed by buffer boundary,\n            # or just a buffer boundary.\n            return -1\n        # A simple, practical version could look like: ((name|stringlit) S*) + '>'\n        n = len(rawdata)", "source": "lang/api.python.langchain.com/en/latest/_modules/_markupbase.html"}
{"id": "a3b43ace734b-2", "text": "n = len(rawdata)\n        if rawdata[j:j+2] == '--': #comment\n            # Locate --.*-- as the body of the comment\n            return self.parse_comment(i)\n        elif rawdata[j] == '[': #marked section\n            # Locate [statusWord [...arbitrary SGML...]] as the body of the marked section\n            # Where statusWord is one of TEMP, CDATA, IGNORE, INCLUDE, RCDATA\n            # Note that this is extended by Microsoft Office \"Save as Web\" function\n            # to include [if...] and [endif].\n            return self.parse_marked_section(i)\n        else: #all other declaration elements\n            decltype, j = self._scan_name(j, i)\n        if j < 0:\n            return j\n        if decltype == \"doctype\":\n            self._decl_otherchars = ''\n        while j < n:\n            c = rawdata[j]\n            if c == \">\":\n                # end of declaration syntax\n                data = rawdata[i+2:j]\n                if decltype == \"doctype\":\n                    self.handle_decl(data)\n                else:\n                    # According to the HTML5 specs sections \"8.2.4.44 Bogus\n                    # comment state\" and \"8.2.4.45 Markup declaration open\n                    # state\", a comment token should be emitted.\n                    # Calling unknown_decl provides more flexibility though.\n                    self.unknown_decl(data)\n                return j + 1\n            if c in \"\\\"'\":\n                m = _declstringlit_match(rawdata, j)\n                if not m:\n                    return -1 # incomplete\n                j = m.end()\n            elif c in \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\":\n                name, j = self._scan_name(j, i)\n            elif c in self._decl_otherchars:", "source": "lang/api.python.langchain.com/en/latest/_modules/_markupbase.html"}
{"id": "a3b43ace734b-3", "text": "elif c in self._decl_otherchars:\n                j = j + 1\n            elif c == \"[\":\n                # this could be handled in a separate doctype parser\n                if decltype == \"doctype\":\n                    j = self._parse_doctype_subset(j + 1, i)\n                elif decltype in {\"attlist\", \"linktype\", \"link\", \"element\"}:\n                    # must tolerate []'d groups in a content model in an element declaration\n                    # also in data attribute specifications of attlist declaration\n                    # also link type declaration subsets in linktype declarations\n                    # also link attribute specification lists in link declarations\n                    raise AssertionError(\"unsupported '[' char in %s declaration\" % decltype)\n                else:\n                    raise AssertionError(\"unexpected '[' char in declaration\")\n            else:\n                raise AssertionError(\"unexpected %r char in declaration\" % rawdata[j])\n            if j < 0:\n                return j\n        return -1 # incomplete\n    # Internal -- parse a marked section\n    # Override this to handle MS-word extension syntax <![if word]>content<![endif]>\n    def parse_marked_section(self, i, report=1):\n        rawdata= self.rawdata\n        assert rawdata[i:i+3] == '<![', \"unexpected call to parse_marked_section()\"\n        sectName, j = self._scan_name( i+3, i )\n        if j < 0:\n            return j\n        if sectName in {\"temp\", \"cdata\", \"ignore\", \"include\", \"rcdata\"}:\n            # look for standard ]]> ending\n            match= _markedsectionclose.search(rawdata, i+3)\n        elif sectName in {\"if\", \"else\", \"endif\"}:\n            # look for MS Office ]> ending", "source": "lang/api.python.langchain.com/en/latest/_modules/_markupbase.html"}
{"id": "a3b43ace734b-4", "text": "# look for MS Office ]> ending\n            match= _msmarkedsectionclose.search(rawdata, i+3)\n        else:\n            raise AssertionError(\n                'unknown status keyword %r in marked section' % rawdata[i+3:j]\n            )\n        if not match:\n            return -1\n        if report:\n            j = match.start(0)\n            self.unknown_decl(rawdata[i+3: j])\n        return match.end(0)\n    # Internal -- parse comment, return length or -1 if not terminated\n    def parse_comment(self, i, report=1):\n        rawdata = self.rawdata\n        if rawdata[i:i+4] != '<!--':\n            raise AssertionError('unexpected call to parse_comment()')\n        match = _commentclose.search(rawdata, i+4)\n        if not match:\n            return -1\n        if report:\n            j = match.start(0)\n            self.handle_comment(rawdata[i+4: j])\n        return match.end(0)\n    # Internal -- scan past the internal subset in a <!DOCTYPE declaration,\n    # returning the index just past any whitespace following the trailing ']'.\n    def _parse_doctype_subset(self, i, declstartpos):\n        rawdata = self.rawdata\n        n = len(rawdata)\n        j = i\n        while j < n:\n            c = rawdata[j]\n            if c == \"<\":\n                s = rawdata[j:j+2]\n                if s == \"<\":\n                    # end of buffer; incomplete\n                    return -1\n                if s != \"<!\":\n                    self.updatepos(declstartpos, j + 1)\n                    raise AssertionError(\n                        \"unexpected char in internal subset (in %r)\" % s\n                    )", "source": "lang/api.python.langchain.com/en/latest/_modules/_markupbase.html"}
{"id": "a3b43ace734b-5", "text": "\"unexpected char in internal subset (in %r)\" % s\n                    )\n                if (j + 2) == n:\n                    # end of buffer; incomplete\n                    return -1\n                if (j + 4) > n:\n                    # end of buffer; incomplete\n                    return -1\n                if rawdata[j:j+4] == \"<!--\":\n                    j = self.parse_comment(j, report=0)\n                    if j < 0:\n                        return j\n                    continue\n                name, j = self._scan_name(j + 2, declstartpos)\n                if j == -1:\n                    return -1\n                if name not in {\"attlist\", \"element\", \"entity\", \"notation\"}:\n                    self.updatepos(declstartpos, j + 2)\n                    raise AssertionError(\n                        \"unknown declaration %r in internal subset\" % name\n                    )\n                # handle the individual names\n                meth = getattr(self, \"_parse_doctype_\" + name)\n                j = meth(j, declstartpos)\n                if j < 0:\n                    return j\n            elif c == \"%\":\n                # parameter entity reference\n                if (j + 1) == n:\n                    # end of buffer; incomplete\n                    return -1\n                s, j = self._scan_name(j + 1, declstartpos)\n                if j < 0:\n                    return j\n                if rawdata[j] == \";\":\n                    j = j + 1\n            elif c == \"]\":\n                j = j + 1\n                while j < n and rawdata[j].isspace():\n                    j = j + 1\n                if j < n:\n                    if rawdata[j] == \">\":\n                        return j\n                    self.updatepos(declstartpos, j)", "source": "lang/api.python.langchain.com/en/latest/_modules/_markupbase.html"}
{"id": "a3b43ace734b-6", "text": "return j\n                    self.updatepos(declstartpos, j)\n                    raise AssertionError(\"unexpected char after internal subset\")\n                else:\n                    return -1\n            elif c.isspace():\n                j = j + 1\n            else:\n                self.updatepos(declstartpos, j)\n                raise AssertionError(\"unexpected char %r in internal subset\" % c)\n        # end of buffer reached\n        return -1\n    # Internal -- scan past <!ELEMENT declarations\n    def _parse_doctype_element(self, i, declstartpos):\n        name, j = self._scan_name(i, declstartpos)\n        if j == -1:\n            return -1\n        # style content model; just skip until '>'\n        rawdata = self.rawdata\n        if '>' in rawdata[j:]:\n            return rawdata.find(\">\", j) + 1\n        return -1\n    # Internal -- scan past <!ATTLIST declarations\n    def _parse_doctype_attlist(self, i, declstartpos):\n        rawdata = self.rawdata\n        name, j = self._scan_name(i, declstartpos)\n        c = rawdata[j:j+1]\n        if c == \"\":\n            return -1\n        if c == \">\":\n            return j + 1\n        while 1:\n            # scan a series of attribute descriptions; simplified:\n            #   name type [value] [#constraint]\n            name, j = self._scan_name(j, declstartpos)\n            if j < 0:\n                return j\n            c = rawdata[j:j+1]\n            if c == \"\":\n                return -1\n            if c == \"(\":\n                # an enumerated type; look for ')'\n                if \")\" in rawdata[j:]:", "source": "lang/api.python.langchain.com/en/latest/_modules/_markupbase.html"}
{"id": "a3b43ace734b-7", "text": "# an enumerated type; look for ')'\n                if \")\" in rawdata[j:]:\n                    j = rawdata.find(\")\", j) + 1\n                else:\n                    return -1\n                while rawdata[j:j+1].isspace():\n                    j = j + 1\n                if not rawdata[j:]:\n                    # end of buffer, incomplete\n                    return -1\n            else:\n                name, j = self._scan_name(j, declstartpos)\n            c = rawdata[j:j+1]\n            if not c:\n                return -1\n            if c in \"'\\\"\":\n                m = _declstringlit_match(rawdata, j)\n                if m:\n                    j = m.end()\n                else:\n                    return -1\n                c = rawdata[j:j+1]\n                if not c:\n                    return -1\n            if c == \"#\":\n                if rawdata[j:] == \"#\":\n                    # end of buffer\n                    return -1\n                name, j = self._scan_name(j + 1, declstartpos)\n                if j < 0:\n                    return j\n                c = rawdata[j:j+1]\n                if not c:\n                    return -1\n            if c == '>':\n                # all done\n                return j + 1\n    # Internal -- scan past <!NOTATION declarations\n    def _parse_doctype_notation(self, i, declstartpos):\n        name, j = self._scan_name(i, declstartpos)\n        if j < 0:\n            return j\n        rawdata = self.rawdata\n        while 1:\n            c = rawdata[j:j+1]\n            if not c:\n                # end of buffer; incomplete\n                return -1\n            if c == '>':", "source": "lang/api.python.langchain.com/en/latest/_modules/_markupbase.html"}
{"id": "a3b43ace734b-8", "text": "# end of buffer; incomplete\n                return -1\n            if c == '>':\n                return j + 1\n            if c in \"'\\\"\":\n                m = _declstringlit_match(rawdata, j)\n                if not m:\n                    return -1\n                j = m.end()\n            else:\n                name, j = self._scan_name(j, declstartpos)\n                if j < 0:\n                    return j\n    # Internal -- scan past <!ENTITY declarations\n    def _parse_doctype_entity(self, i, declstartpos):\n        rawdata = self.rawdata\n        if rawdata[i:i+1] == \"%\":\n            j = i + 1\n            while 1:\n                c = rawdata[j:j+1]\n                if not c:\n                    return -1\n                if c.isspace():\n                    j = j + 1\n                else:\n                    break\n        else:\n            j = i\n        name, j = self._scan_name(j, declstartpos)\n        if j < 0:\n            return j\n        while 1:\n            c = self.rawdata[j:j+1]\n            if not c:\n                return -1\n            if c in \"'\\\"\":\n                m = _declstringlit_match(rawdata, j)\n                if m:\n                    j = m.end()\n                else:\n                    return -1    # incomplete\n            elif c == \">\":\n                return j + 1\n            else:\n                name, j = self._scan_name(j, declstartpos)\n                if j < 0:\n                    return j\n    # Internal -- scan a name token and the new position and the token, or\n    # return -1 if we've reached the end of the buffer.", "source": "lang/api.python.langchain.com/en/latest/_modules/_markupbase.html"}
{"id": "a3b43ace734b-9", "text": "# return -1 if we've reached the end of the buffer.\n    def _scan_name(self, i, declstartpos):\n        rawdata = self.rawdata\n        n = len(rawdata)\n        if i == n:\n            return None, -1\n        m = _declname_match(rawdata, i)\n        if m:\n            s = m.group()\n            name = s.strip()\n            if (i + len(s)) == n:\n                return None, -1  # end of buffer\n            return name.lower(), m.end()\n        else:\n            self.updatepos(declstartpos, i)\n            raise AssertionError(\n                \"expected name token at %r\" % rawdata[declstartpos:declstartpos+20]\n            )\n    # To be overridden -- handlers for unknown objects\n    def unknown_decl(self, data):\n        pass", "source": "lang/api.python.langchain.com/en/latest/_modules/_markupbase.html"}
{"id": "93f5fd6782c0-0", "text": "Source code for ast\n\"\"\"\n    ast\n    ~~~\n    The `ast` module helps Python applications to process trees of the Python\n    abstract syntax grammar.  The abstract syntax itself might change with\n    each Python release; this module helps to find out programmatically what\n    the current grammar looks like and allows modifications of it.\n    An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as\n    a flag to the `compile()` builtin function or by using the `parse()`\n    function from this module.  The result will be a tree of objects whose\n    classes all inherit from `ast.AST`.\n    A modified abstract syntax tree can be compiled into a Python code object\n    using the built-in `compile()` function.\n    Additionally various helper functions are provided that make working with\n    the trees simpler.  The main intention of the helper functions and this\n    module in general is to provide an easy to use interface for libraries\n    that work tightly with the python syntax (template engines for example).\n    :copyright: Copyright 2008 by Armin Ronacher.\n    :license: Python License.\n\"\"\"\nimport sys\nfrom _ast import *\nfrom contextlib import contextmanager, nullcontext\nfrom enum import IntEnum, auto, _simple_enum\ndef parse(source, filename='<unknown>', mode='exec', *,\n          type_comments=False, feature_version=None):\n    \"\"\"\n    Parse the source into an AST node.\n    Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).\n    Pass type_comments=True to get back type comments where the syntax allows.\n    \"\"\"\n    flags = PyCF_ONLY_AST\n    if type_comments:\n        flags |= PyCF_TYPE_COMMENTS\n    if isinstance(feature_version, tuple):\n        major, minor = feature_version  # Should be a 2-tuple.", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-1", "text": "major, minor = feature_version  # Should be a 2-tuple.\n        assert major == 3\n        feature_version = minor\n    elif feature_version is None:\n        feature_version = -1\n    # Else it should be an int giving the minor version for 3.x.\n    return compile(source, filename, mode, flags,\n                   _feature_version=feature_version)\ndef literal_eval(node_or_string):\n    \"\"\"\n    Evaluate an expression node or a string containing only a Python\n    expression.  The string or node provided may only consist of the following\n    Python literal structures: strings, bytes, numbers, tuples, lists, dicts,\n    sets, booleans, and None.\n    Caution: A complex expression can overflow the C stack and cause a crash.\n    \"\"\"\n    if isinstance(node_or_string, str):\n        node_or_string = parse(node_or_string.lstrip(\" \\t\"), mode='eval')\n    if isinstance(node_or_string, Expression):\n        node_or_string = node_or_string.body\n    def _raise_malformed_node(node):\n        msg = \"malformed node or string\"\n        if lno := getattr(node, 'lineno', None):\n            msg += f' on line {lno}'\n        raise ValueError(msg + f': {node!r}')\n    def _convert_num(node):\n        if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):\n            _raise_malformed_node(node)\n        return node.value\n    def _convert_signed_num(node):\n        if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):\n            operand = _convert_num(node.operand)\n            if isinstance(node.op, UAdd):\n                return + operand\n            else:\n                return - operand", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-2", "text": "return + operand\n            else:\n                return - operand\n        return _convert_num(node)\n    def _convert(node):\n        if isinstance(node, Constant):\n            return node.value\n        elif isinstance(node, Tuple):\n            return tuple(map(_convert, node.elts))\n        elif isinstance(node, List):\n            return list(map(_convert, node.elts))\n        elif isinstance(node, Set):\n            return set(map(_convert, node.elts))\n        elif (isinstance(node, Call) and isinstance(node.func, Name) and\n              node.func.id == 'set' and node.args == node.keywords == []):\n            return set()\n        elif isinstance(node, Dict):\n            if len(node.keys) != len(node.values):\n                _raise_malformed_node(node)\n            return dict(zip(map(_convert, node.keys),\n                            map(_convert, node.values)))\n        elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):\n            left = _convert_signed_num(node.left)\n            right = _convert_num(node.right)\n            if isinstance(left, (int, float)) and isinstance(right, complex):\n                if isinstance(node.op, Add):\n                    return left + right\n                else:\n                    return left - right\n        return _convert_signed_num(node)\n    return _convert(node_or_string)\ndef dump(node, annotate_fields=True, include_attributes=False, *, indent=None):\n    \"\"\"\n    Return a formatted dump of the tree in node.  This is mainly useful for\n    debugging purposes.  If annotate_fields is true (by default),\n    the returned string will show the names and the values for fields.\n    If annotate_fields is false, the result string will be more compact by\n    omitting unambiguous field names.  Attributes such as line", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-3", "text": "omitting unambiguous field names.  Attributes such as line\n    numbers and column offsets are not dumped by default.  If this is wanted,\n    include_attributes can be set to true.  If indent is a non-negative\n    integer or string, then the tree will be pretty-printed with that indent\n    level. None (the default) selects the single line representation.\n    \"\"\"\n    def _format(node, level=0):\n        if indent is not None:\n            level += 1\n            prefix = '\\n' + indent * level\n            sep = ',\\n' + indent * level\n        else:\n            prefix = ''\n            sep = ', '\n        if isinstance(node, AST):\n            cls = type(node)\n            args = []\n            allsimple = True\n            keywords = annotate_fields\n            for name in node._fields:\n                try:\n                    value = getattr(node, name)\n                except AttributeError:\n                    keywords = True\n                    continue\n                if value is None and getattr(cls, name, ...) is None:\n                    keywords = True\n                    continue\n                value, simple = _format(value, level)\n                allsimple = allsimple and simple\n                if keywords:\n                    args.append('%s=%s' % (name, value))\n                else:\n                    args.append(value)\n            if include_attributes and node._attributes:\n                for name in node._attributes:\n                    try:\n                        value = getattr(node, name)\n                    except AttributeError:\n                        continue\n                    if value is None and getattr(cls, name, ...) is None:\n                        continue\n                    value, simple = _format(value, level)\n                    allsimple = allsimple and simple\n                    args.append('%s=%s' % (name, value))\n            if allsimple and len(args) <= 3:", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-4", "text": "if allsimple and len(args) <= 3:\n                return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args\n            return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False\n        elif isinstance(node, list):\n            if not node:\n                return '[]', True\n            return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False\n        return repr(node), True\n    if not isinstance(node, AST):\n        raise TypeError('expected AST, got %r' % node.__class__.__name__)\n    if indent is not None and not isinstance(indent, str):\n        indent = ' ' * indent\n    return _format(node)[0]\ndef copy_location(new_node, old_node):\n    \"\"\"\n    Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset`\n    attributes) from *old_node* to *new_node* if possible, and return *new_node*.\n    \"\"\"\n    for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset':\n        if attr in old_node._attributes and attr in new_node._attributes:\n            value = getattr(old_node, attr, None)\n            # end_lineno and end_col_offset are optional attributes, and they\n            # should be copied whether the value is None or not.\n            if value is not None or (\n                hasattr(old_node, attr) and attr.startswith(\"end_\")\n            ):\n                setattr(new_node, attr, value)\n    return new_node\ndef fix_missing_locations(node):\n    \"\"\"\n    When you compile a node tree with compile(), the compiler expects lineno and\n    col_offset attributes for every node that supports them.  This is rather", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-5", "text": "col_offset attributes for every node that supports them.  This is rather\n    tedious to fill in for generated nodes, so this helper adds these attributes\n    recursively where not already set, by setting them to the values of the\n    parent node.  It works recursively starting at *node*.\n    \"\"\"\n    def _fix(node, lineno, col_offset, end_lineno, end_col_offset):\n        if 'lineno' in node._attributes:\n            if not hasattr(node, 'lineno'):\n                node.lineno = lineno\n            else:\n                lineno = node.lineno\n        if 'end_lineno' in node._attributes:\n            if getattr(node, 'end_lineno', None) is None:\n                node.end_lineno = end_lineno\n            else:\n                end_lineno = node.end_lineno\n        if 'col_offset' in node._attributes:\n            if not hasattr(node, 'col_offset'):\n                node.col_offset = col_offset\n            else:\n                col_offset = node.col_offset\n        if 'end_col_offset' in node._attributes:\n            if getattr(node, 'end_col_offset', None) is None:\n                node.end_col_offset = end_col_offset\n            else:\n                end_col_offset = node.end_col_offset\n        for child in iter_child_nodes(node):\n            _fix(child, lineno, col_offset, end_lineno, end_col_offset)\n    _fix(node, 1, 0, 1, 0)\n    return node\ndef increment_lineno(node, n=1):\n    \"\"\"\n    Increment the line number and end line number of each node in the tree\n    starting at *node* by *n*. This is useful to \"move code\" to a different\n    location in a file.\n    \"\"\"\n    for child in walk(node):\n        # TypeIgnore is a special case where lineno is not an attribute", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-6", "text": "# TypeIgnore is a special case where lineno is not an attribute\n        # but rather a field of the node itself.\n        if isinstance(child, TypeIgnore):\n            child.lineno = getattr(child, 'lineno', 0) + n\n            continue\n        if 'lineno' in child._attributes:\n            child.lineno = getattr(child, 'lineno', 0) + n\n        if (\n            \"end_lineno\" in child._attributes\n            and (end_lineno := getattr(child, \"end_lineno\", 0)) is not None\n        ):\n            child.end_lineno = end_lineno + n\n    return node\ndef iter_fields(node):\n    \"\"\"\n    Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``\n    that is present on *node*.\n    \"\"\"\n    for field in node._fields:\n        try:\n            yield field, getattr(node, field)\n        except AttributeError:\n            pass\ndef iter_child_nodes(node):\n    \"\"\"\n    Yield all direct child nodes of *node*, that is, all fields that are nodes\n    and all items of fields that are lists of nodes.\n    \"\"\"\n    for name, field in iter_fields(node):\n        if isinstance(field, AST):\n            yield field\n        elif isinstance(field, list):\n            for item in field:\n                if isinstance(item, AST):\n                    yield item\ndef get_docstring(node, clean=True):\n    \"\"\"\n    Return the docstring for the given node or None if no docstring can\n    be found.  If the node provided does not have docstrings a TypeError\n    will be raised.\n    If *clean* is `True`, all tabs are expanded to spaces and any whitespace\n    that can be uniformly removed from the second line onwards is removed.\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-7", "text": "that can be uniformly removed from the second line onwards is removed.\n    \"\"\"\n    if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):\n        raise TypeError(\"%r can't have docstrings\" % node.__class__.__name__)\n    if not(node.body and isinstance(node.body[0], Expr)):\n        return None\n    node = node.body[0].value\n    if isinstance(node, Str):\n        text = node.s\n    elif isinstance(node, Constant) and isinstance(node.value, str):\n        text = node.value\n    else:\n        return None\n    if clean:\n        import inspect\n        text = inspect.cleandoc(text)\n    return text\ndef _splitlines_no_ff(source):\n    \"\"\"Split a string into lines ignoring form feed and other chars.\n    This mimics how the Python parser splits source code.\n    \"\"\"\n    idx = 0\n    lines = []\n    next_line = ''\n    while idx < len(source):\n        c = source[idx]\n        next_line += c\n        idx += 1\n        # Keep \\r\\n together\n        if c == '\\r' and idx < len(source) and source[idx] == '\\n':\n            next_line += '\\n'\n            idx += 1\n        if c in '\\r\\n':\n            lines.append(next_line)\n            next_line = ''\n    if next_line:\n        lines.append(next_line)\n    return lines\ndef _pad_whitespace(source):\n    r\"\"\"Replace all chars except '\\f\\t' in a line with spaces.\"\"\"\n    result = ''\n    for c in source:\n        if c in '\\f\\t':\n            result += c\n        else:\n            result += ' '\n    return result\ndef get_source_segment(source, node, *, padded=False):", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-8", "text": "return result\ndef get_source_segment(source, node, *, padded=False):\n    \"\"\"Get source code segment of the *source* that generated *node*.\n    If some location information (`lineno`, `end_lineno`, `col_offset`,\n    or `end_col_offset`) is missing, return None.\n    If *padded* is `True`, the first line of a multi-line statement will\n    be padded with spaces to match its original position.\n    \"\"\"\n    try:\n        if node.end_lineno is None or node.end_col_offset is None:\n            return None\n        lineno = node.lineno - 1\n        end_lineno = node.end_lineno - 1\n        col_offset = node.col_offset\n        end_col_offset = node.end_col_offset\n    except AttributeError:\n        return None\n    lines = _splitlines_no_ff(source)\n    if end_lineno == lineno:\n        return lines[lineno].encode()[col_offset:end_col_offset].decode()\n    if padded:\n        padding = _pad_whitespace(lines[lineno].encode()[:col_offset].decode())\n    else:\n        padding = ''\n    first = padding + lines[lineno].encode()[col_offset:].decode()\n    last = lines[end_lineno].encode()[:end_col_offset].decode()\n    lines = lines[lineno+1:end_lineno]\n    lines.insert(0, first)\n    lines.append(last)\n    return ''.join(lines)\ndef walk(node):\n    \"\"\"\n    Recursively yield all descendant nodes in the tree starting at *node*\n    (including *node* itself), in no specified order.  This is useful if you\n    only want to modify nodes in place and don't care about the context.\n    \"\"\"\n    from collections import deque\n    todo = deque([node])\n    while todo:\n        node = todo.popleft()", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-9", "text": "while todo:\n        node = todo.popleft()\n        todo.extend(iter_child_nodes(node))\n        yield node\nclass NodeVisitor(object):\n    \"\"\"\n    A node visitor base class that walks the abstract syntax tree and calls a\n    visitor function for every node found.  This function may return a value\n    which is forwarded by the `visit` method.\n    This class is meant to be subclassed, with the subclass adding visitor\n    methods.\n    Per default the visitor functions for the nodes are ``'visit_'`` +\n    class name of the node.  So a `TryFinally` node visit function would\n    be `visit_TryFinally`.  This behavior can be changed by overriding\n    the `visit` method.  If no visitor function exists for a node\n    (return value `None`) the `generic_visit` visitor is used instead.\n    Don't use the `NodeVisitor` if you want to apply changes to nodes during\n    traversing.  For this a special visitor exists (`NodeTransformer`) that\n    allows modifications.\n    \"\"\"\n    def visit(self, node):\n        \"\"\"Visit a node.\"\"\"\n        method = 'visit_' + node.__class__.__name__\n        visitor = getattr(self, method, self.generic_visit)\n        return visitor(node)\n    def generic_visit(self, node):\n        \"\"\"Called if no explicit visitor function exists for a node.\"\"\"\n        for field, value in iter_fields(node):\n            if isinstance(value, list):\n                for item in value:\n                    if isinstance(item, AST):\n                        self.visit(item)\n            elif isinstance(value, AST):\n                self.visit(value)\n    def visit_Constant(self, node):\n        value = node.value\n        type_name = _const_node_type_names.get(type(value))\n        if type_name is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-10", "text": "if type_name is None:\n            for cls, name in _const_node_type_names.items():\n                if isinstance(value, cls):\n                    type_name = name\n                    break\n        if type_name is not None:\n            method = 'visit_' + type_name\n            try:\n                visitor = getattr(self, method)\n            except AttributeError:\n                pass\n            else:\n                import warnings\n                warnings.warn(f\"{method} is deprecated; add visit_Constant\",\n                              DeprecationWarning, 2)\n                return visitor(node)\n        return self.generic_visit(node)\nclass NodeTransformer(NodeVisitor):\n    \"\"\"\n    A :class:`NodeVisitor` subclass that walks the abstract syntax tree and\n    allows modification of nodes.\n    The `NodeTransformer` will walk the AST and use the return value of the\n    visitor methods to replace or remove the old node.  If the return value of\n    the visitor method is ``None``, the node will be removed from its location,\n    otherwise it is replaced with the return value.  The return value may be the\n    original node in which case no replacement takes place.\n    Here is an example transformer that rewrites all occurrences of name lookups\n    (``foo``) to ``data['foo']``::\n       class RewriteName(NodeTransformer):\n           def visit_Name(self, node):\n               return Subscript(\n                   value=Name(id='data', ctx=Load()),\n                   slice=Constant(value=node.id),\n                   ctx=node.ctx\n               )\n    Keep in mind that if the node you're operating on has child nodes you must\n    either transform the child nodes yourself or call the :meth:`generic_visit`\n    method for the node first.\n    For nodes that were part of a collection of statements (that applies to all", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-11", "text": "For nodes that were part of a collection of statements (that applies to all\n    statement nodes), the visitor may also return a list of nodes rather than\n    just a single node.\n    Usually you use the transformer like this::\n       node = YourTransformer().visit(node)\n    \"\"\"\n    def generic_visit(self, node):\n        for field, old_value in iter_fields(node):\n            if isinstance(old_value, list):\n                new_values = []\n                for value in old_value:\n                    if isinstance(value, AST):\n                        value = self.visit(value)\n                        if value is None:\n                            continue\n                        elif not isinstance(value, AST):\n                            new_values.extend(value)\n                            continue\n                    new_values.append(value)\n                old_value[:] = new_values\n            elif isinstance(old_value, AST):\n                new_node = self.visit(old_value)\n                if new_node is None:\n                    delattr(node, field)\n                else:\n                    setattr(node, field, new_node)\n        return node\n# If the ast module is loaded more than once, only add deprecated methods once\nif not hasattr(Constant, 'n'):\n    # The following code is for backward compatibility.\n    # It will be removed in future.\n    def _getter(self):\n        \"\"\"Deprecated. Use value instead.\"\"\"\n        return self.value\n    def _setter(self, value):\n        self.value = value\n    Constant.n = property(_getter, _setter)\n    Constant.s = property(_getter, _setter)\nclass _ABC(type):\n    def __init__(cls, *args):\n        cls.__doc__ = \"\"\"Deprecated AST node class. Use ast.Constant instead\"\"\"\n    def __instancecheck__(cls, inst):\n        if not isinstance(inst, Constant):\n            return False\n        if cls in _const_types:\n            try:", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-12", "text": "return False\n        if cls in _const_types:\n            try:\n                value = inst.value\n            except AttributeError:\n                return False\n            else:\n                return (\n                    isinstance(value, _const_types[cls]) and\n                    not isinstance(value, _const_types_not.get(cls, ()))\n                )\n        return type.__instancecheck__(cls, inst)\ndef _new(cls, *args, **kwargs):\n    for key in kwargs:\n        if key not in cls._fields:\n            # arbitrary keyword arguments are accepted\n            continue\n        pos = cls._fields.index(key)\n        if pos < len(args):\n            raise TypeError(f\"{cls.__name__} got multiple values for argument {key!r}\")\n    if cls in _const_types:\n        return Constant(*args, **kwargs)\n    return Constant.__new__(cls, *args, **kwargs)\nclass Num(Constant, metaclass=_ABC):\n    _fields = ('n',)\n    __new__ = _new\nclass Str(Constant, metaclass=_ABC):\n    _fields = ('s',)\n    __new__ = _new\nclass Bytes(Constant, metaclass=_ABC):\n    _fields = ('s',)\n    __new__ = _new\nclass NameConstant(Constant, metaclass=_ABC):\n    __new__ = _new\nclass Ellipsis(Constant, metaclass=_ABC):\n    _fields = ()\n    def __new__(cls, *args, **kwargs):\n        if cls is Ellipsis:\n            return Constant(..., *args, **kwargs)\n        return Constant.__new__(cls, *args, **kwargs)\n_const_types = {\n    Num: (int, float, complex),\n    Str: (str,),\n    Bytes: (bytes,),", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-13", "text": "Str: (str,),\n    Bytes: (bytes,),\n    NameConstant: (type(None), bool),\n    Ellipsis: (type(...),),\n}\n_const_types_not = {\n    Num: (bool,),\n}\n_const_node_type_names = {\n    bool: 'NameConstant',  # should be before int\n    type(None): 'NameConstant',\n    int: 'Num',\n    float: 'Num',\n    complex: 'Num',\n    str: 'Str',\n    bytes: 'Bytes',\n    type(...): 'Ellipsis',\n}\nclass slice(AST):\n    \"\"\"Deprecated AST node class.\"\"\"\nclass Index(slice):\n    \"\"\"Deprecated AST node class. Use the index value directly instead.\"\"\"\n    def __new__(cls, value, **kwargs):\n        return value\nclass ExtSlice(slice):\n    \"\"\"Deprecated AST node class. Use ast.Tuple instead.\"\"\"\n    def __new__(cls, dims=(), **kwargs):\n        return Tuple(list(dims), Load(), **kwargs)\n# If the ast module is loaded more than once, only add deprecated methods once\nif not hasattr(Tuple, 'dims'):\n    # The following code is for backward compatibility.\n    # It will be removed in future.\n    def _dims_getter(self):\n        \"\"\"Deprecated. Use elts instead.\"\"\"\n        return self.elts\n    def _dims_setter(self, value):\n        self.elts = value\n    Tuple.dims = property(_dims_getter, _dims_setter)\nclass Suite(mod):\n    \"\"\"Deprecated AST node class.  Unused in Python 3.\"\"\"\nclass AugLoad(expr_context):\n    \"\"\"Deprecated AST node class.  Unused in Python 3.\"\"\"\nclass AugStore(expr_context):\n    \"\"\"Deprecated AST node class.  Unused in Python 3.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-14", "text": "\"\"\"Deprecated AST node class.  Unused in Python 3.\"\"\"\nclass Param(expr_context):\n    \"\"\"Deprecated AST node class.  Unused in Python 3.\"\"\"\n# Large float and imaginary literals get turned into infinities in the AST.\n# We unparse those infinities to INFSTR.\n_INFSTR = \"1e\" + repr(sys.float_info.max_10_exp + 1)\n@_simple_enum(IntEnum)\nclass _Precedence:\n    \"\"\"Precedence table that originated from python grammar.\"\"\"\n    NAMED_EXPR = auto()      # <target> := <expr1>\n    TUPLE = auto()           # <expr1>, <expr2>\n    YIELD = auto()           # 'yield', 'yield from'\n    TEST = auto()            # 'if'-'else', 'lambda'\n    OR = auto()              # 'or'\n    AND = auto()             # 'and'\n    NOT = auto()             # 'not'\n    CMP = auto()             # '<', '>', '==', '>=', '<=', '!=',\n                             # 'in', 'not in', 'is', 'is not'\n    EXPR = auto()\n    BOR = EXPR               # '|'\n    BXOR = auto()            # '^'\n    BAND = auto()            # '&'\n    SHIFT = auto()           # '<<', '>>'\n    ARITH = auto()           # '+', '-'\n    TERM = auto()            # '*', '@', '/', '%', '//'\n    FACTOR = auto()          # unary '+', '-', '~'\n    POWER = auto()           # '**'\n    AWAIT = auto()           # 'await'\n    ATOM = auto()\n    def next(self):\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-15", "text": "ATOM = auto()\n    def next(self):\n        try:\n            return self.__class__(self + 1)\n        except ValueError:\n            return self\n_SINGLE_QUOTES = (\"'\", '\"')\n_MULTI_QUOTES = ('\"\"\"', \"'''\")\n_ALL_QUOTES = (*_SINGLE_QUOTES, *_MULTI_QUOTES)\nclass _Unparser(NodeVisitor):\n    \"\"\"Methods in this class recursively traverse an AST and\n    output source code for the abstract syntax; original formatting\n    is disregarded.\"\"\"\n    def __init__(self, *, _avoid_backslashes=False):\n        self._source = []\n        self._precedences = {}\n        self._type_ignores = {}\n        self._indent = 0\n        self._avoid_backslashes = _avoid_backslashes\n        self._in_try_star = False\n    def interleave(self, inter, f, seq):\n        \"\"\"Call f on each item in seq, calling inter() in between.\"\"\"\n        seq = iter(seq)\n        try:\n            f(next(seq))\n        except StopIteration:\n            pass\n        else:\n            for x in seq:\n                inter()\n                f(x)\n    def items_view(self, traverser, items):\n        \"\"\"Traverse and separate the given *items* with a comma and append it to\n        the buffer. If *items* is a single item sequence, a trailing comma\n        will be added.\"\"\"\n        if len(items) == 1:\n            traverser(items[0])\n            self.write(\",\")\n        else:\n            self.interleave(lambda: self.write(\", \"), traverser, items)\n    def maybe_newline(self):\n        \"\"\"Adds a newline if it isn't the start of generated source\"\"\"\n        if self._source:\n            self.write(\"\\n\")\n    def fill(self, text=\"\"):", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-16", "text": "self.write(\"\\n\")\n    def fill(self, text=\"\"):\n        \"\"\"Indent a piece of text and append it, according to the current\n        indentation level\"\"\"\n        self.maybe_newline()\n        self.write(\"    \" * self._indent + text)\n    def write(self, *text):\n        \"\"\"Add new source parts\"\"\"\n        self._source.extend(text)\n    @contextmanager\n    def buffered(self, buffer = None):\n        if buffer is None:\n            buffer = []\n        original_source = self._source\n        self._source = buffer\n        yield buffer\n        self._source = original_source\n    @contextmanager\n    def block(self, *, extra = None):\n        \"\"\"A context manager for preparing the source for blocks. It adds\n        the character':', increases the indentation on enter and decreases\n        the indentation on exit. If *extra* is given, it will be directly\n        appended after the colon character.\n        \"\"\"\n        self.write(\":\")\n        if extra:\n            self.write(extra)\n        self._indent += 1\n        yield\n        self._indent -= 1\n    @contextmanager\n    def delimit(self, start, end):\n        \"\"\"A context manager for preparing the source for expressions. It adds\n        *start* to the buffer and enters, after exit it adds *end*.\"\"\"\n        self.write(start)\n        yield\n        self.write(end)\n    def delimit_if(self, start, end, condition):\n        if condition:\n            return self.delimit(start, end)\n        else:\n            return nullcontext()\n    def require_parens(self, precedence, node):\n        \"\"\"Shortcut to adding precedence related parens\"\"\"\n        return self.delimit_if(\"(\", \")\", self.get_precedence(node) > precedence)", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-17", "text": "def get_precedence(self, node):\n        return self._precedences.get(node, _Precedence.TEST)\n    def set_precedence(self, precedence, *nodes):\n        for node in nodes:\n            self._precedences[node] = precedence\n    def get_raw_docstring(self, node):\n        \"\"\"If a docstring node is found in the body of the *node* parameter,\n        return that docstring node, None otherwise.\n        Logic mirrored from ``_PyAST_GetDocString``.\"\"\"\n        if not isinstance(\n            node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)\n        ) or len(node.body) < 1:\n            return None\n        node = node.body[0]\n        if not isinstance(node, Expr):\n            return None\n        node = node.value\n        if isinstance(node, Constant) and isinstance(node.value, str):\n            return node\n    def get_type_comment(self, node):\n        comment = self._type_ignores.get(node.lineno) or node.type_comment\n        if comment is not None:\n            return f\" # type: {comment}\"\n    def traverse(self, node):\n        if isinstance(node, list):\n            for item in node:\n                self.traverse(item)\n        else:\n            super().visit(node)\n    # Note: as visit() resets the output text, do NOT rely on\n    # NodeVisitor.generic_visit to handle any nodes (as it calls back in to\n    # the subclass visit() method, which resets self._source to an empty list)\n    def visit(self, node):\n        \"\"\"Outputs a source code string that, if converted back to an ast\n        (using ast.parse) will generate an AST equivalent to *node*\"\"\"\n        self._source = []\n        self.traverse(node)", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-18", "text": "self._source = []\n        self.traverse(node)\n        return \"\".join(self._source)\n    def _write_docstring_and_traverse_body(self, node):\n        if (docstring := self.get_raw_docstring(node)):\n            self._write_docstring(docstring)\n            self.traverse(node.body[1:])\n        else:\n            self.traverse(node.body)\n    def visit_Module(self, node):\n        self._type_ignores = {\n            ignore.lineno: f\"ignore{ignore.tag}\"\n            for ignore in node.type_ignores\n        }\n        self._write_docstring_and_traverse_body(node)\n        self._type_ignores.clear()\n    def visit_FunctionType(self, node):\n        with self.delimit(\"(\", \")\"):\n            self.interleave(\n                lambda: self.write(\", \"), self.traverse, node.argtypes\n            )\n        self.write(\" -> \")\n        self.traverse(node.returns)\n    def visit_Expr(self, node):\n        self.fill()\n        self.set_precedence(_Precedence.YIELD, node.value)\n        self.traverse(node.value)\n    def visit_NamedExpr(self, node):\n        with self.require_parens(_Precedence.NAMED_EXPR, node):\n            self.set_precedence(_Precedence.ATOM, node.target, node.value)\n            self.traverse(node.target)\n            self.write(\" := \")\n            self.traverse(node.value)\n    def visit_Import(self, node):\n        self.fill(\"import \")\n        self.interleave(lambda: self.write(\", \"), self.traverse, node.names)\n    def visit_ImportFrom(self, node):\n        self.fill(\"from \")\n        self.write(\".\" * (node.level or 0))\n        if node.module:", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-19", "text": "self.write(\".\" * (node.level or 0))\n        if node.module:\n            self.write(node.module)\n        self.write(\" import \")\n        self.interleave(lambda: self.write(\", \"), self.traverse, node.names)\n    def visit_Assign(self, node):\n        self.fill()\n        for target in node.targets:\n            self.set_precedence(_Precedence.TUPLE, target)\n            self.traverse(target)\n            self.write(\" = \")\n        self.traverse(node.value)\n        if type_comment := self.get_type_comment(node):\n            self.write(type_comment)\n    def visit_AugAssign(self, node):\n        self.fill()\n        self.traverse(node.target)\n        self.write(\" \" + self.binop[node.op.__class__.__name__] + \"= \")\n        self.traverse(node.value)\n    def visit_AnnAssign(self, node):\n        self.fill()\n        with self.delimit_if(\"(\", \")\", not node.simple and isinstance(node.target, Name)):\n            self.traverse(node.target)\n        self.write(\": \")\n        self.traverse(node.annotation)\n        if node.value:\n            self.write(\" = \")\n            self.traverse(node.value)\n    def visit_Return(self, node):\n        self.fill(\"return\")\n        if node.value:\n            self.write(\" \")\n            self.traverse(node.value)\n    def visit_Pass(self, node):\n        self.fill(\"pass\")\n    def visit_Break(self, node):\n        self.fill(\"break\")\n    def visit_Continue(self, node):\n        self.fill(\"continue\")\n    def visit_Delete(self, node):\n        self.fill(\"del \")\n        self.interleave(lambda: self.write(\", \"), self.traverse, node.targets)\n    def visit_Assert(self, node):", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-20", "text": "def visit_Assert(self, node):\n        self.fill(\"assert \")\n        self.traverse(node.test)\n        if node.msg:\n            self.write(\", \")\n            self.traverse(node.msg)\n    def visit_Global(self, node):\n        self.fill(\"global \")\n        self.interleave(lambda: self.write(\", \"), self.write, node.names)\n    def visit_Nonlocal(self, node):\n        self.fill(\"nonlocal \")\n        self.interleave(lambda: self.write(\", \"), self.write, node.names)\n    def visit_Await(self, node):\n        with self.require_parens(_Precedence.AWAIT, node):\n            self.write(\"await\")\n            if node.value:\n                self.write(\" \")\n                self.set_precedence(_Precedence.ATOM, node.value)\n                self.traverse(node.value)\n    def visit_Yield(self, node):\n        with self.require_parens(_Precedence.YIELD, node):\n            self.write(\"yield\")\n            if node.value:\n                self.write(\" \")\n                self.set_precedence(_Precedence.ATOM, node.value)\n                self.traverse(node.value)\n    def visit_YieldFrom(self, node):\n        with self.require_parens(_Precedence.YIELD, node):\n            self.write(\"yield from \")\n            if not node.value:\n                raise ValueError(\"Node can't be used without a value attribute.\")\n            self.set_precedence(_Precedence.ATOM, node.value)\n            self.traverse(node.value)\n    def visit_Raise(self, node):\n        self.fill(\"raise\")\n        if not node.exc:\n            if node.cause:\n                raise ValueError(f\"Node can't use cause without an exception.\")\n            return\n        self.write(\" \")", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-21", "text": "return\n        self.write(\" \")\n        self.traverse(node.exc)\n        if node.cause:\n            self.write(\" from \")\n            self.traverse(node.cause)\n    def do_visit_try(self, node):\n        self.fill(\"try\")\n        with self.block():\n            self.traverse(node.body)\n        for ex in node.handlers:\n            self.traverse(ex)\n        if node.orelse:\n            self.fill(\"else\")\n            with self.block():\n                self.traverse(node.orelse)\n        if node.finalbody:\n            self.fill(\"finally\")\n            with self.block():\n                self.traverse(node.finalbody)\n    def visit_Try(self, node):\n        prev_in_try_star = self._in_try_star\n        try:\n            self._in_try_star = False\n            self.do_visit_try(node)\n        finally:\n            self._in_try_star = prev_in_try_star\n    def visit_TryStar(self, node):\n        prev_in_try_star = self._in_try_star\n        try:\n            self._in_try_star = True\n            self.do_visit_try(node)\n        finally:\n            self._in_try_star = prev_in_try_star\n    def visit_ExceptHandler(self, node):\n        self.fill(\"except*\" if self._in_try_star else \"except\")\n        if node.type:\n            self.write(\" \")\n            self.traverse(node.type)\n        if node.name:\n            self.write(\" as \")\n            self.write(node.name)\n        with self.block():\n            self.traverse(node.body)\n    def visit_ClassDef(self, node):\n        self.maybe_newline()\n        for deco in node.decorator_list:\n            self.fill(\"@\")\n            self.traverse(deco)\n        self.fill(\"class \" + node.name)", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-22", "text": "self.traverse(deco)\n        self.fill(\"class \" + node.name)\n        with self.delimit_if(\"(\", \")\", condition = node.bases or node.keywords):\n            comma = False\n            for e in node.bases:\n                if comma:\n                    self.write(\", \")\n                else:\n                    comma = True\n                self.traverse(e)\n            for e in node.keywords:\n                if comma:\n                    self.write(\", \")\n                else:\n                    comma = True\n                self.traverse(e)\n        with self.block():\n            self._write_docstring_and_traverse_body(node)\n    def visit_FunctionDef(self, node):\n        self._function_helper(node, \"def\")\n    def visit_AsyncFunctionDef(self, node):\n        self._function_helper(node, \"async def\")\n    def _function_helper(self, node, fill_suffix):\n        self.maybe_newline()\n        for deco in node.decorator_list:\n            self.fill(\"@\")\n            self.traverse(deco)\n        def_str = fill_suffix + \" \" + node.name\n        self.fill(def_str)\n        with self.delimit(\"(\", \")\"):\n            self.traverse(node.args)\n        if node.returns:\n            self.write(\" -> \")\n            self.traverse(node.returns)\n        with self.block(extra=self.get_type_comment(node)):\n            self._write_docstring_and_traverse_body(node)\n    def visit_For(self, node):\n        self._for_helper(\"for \", node)\n    def visit_AsyncFor(self, node):\n        self._for_helper(\"async for \", node)\n    def _for_helper(self, fill, node):\n        self.fill(fill)\n        self.set_precedence(_Precedence.TUPLE, node.target)\n        self.traverse(node.target)", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-23", "text": "self.traverse(node.target)\n        self.write(\" in \")\n        self.traverse(node.iter)\n        with self.block(extra=self.get_type_comment(node)):\n            self.traverse(node.body)\n        if node.orelse:\n            self.fill(\"else\")\n            with self.block():\n                self.traverse(node.orelse)\n    def visit_If(self, node):\n        self.fill(\"if \")\n        self.traverse(node.test)\n        with self.block():\n            self.traverse(node.body)\n        # collapse nested ifs into equivalent elifs.\n        while node.orelse and len(node.orelse) == 1 and isinstance(node.orelse[0], If):\n            node = node.orelse[0]\n            self.fill(\"elif \")\n            self.traverse(node.test)\n            with self.block():\n                self.traverse(node.body)\n        # final else\n        if node.orelse:\n            self.fill(\"else\")\n            with self.block():\n                self.traverse(node.orelse)\n    def visit_While(self, node):\n        self.fill(\"while \")\n        self.traverse(node.test)\n        with self.block():\n            self.traverse(node.body)\n        if node.orelse:\n            self.fill(\"else\")\n            with self.block():\n                self.traverse(node.orelse)\n    def visit_With(self, node):\n        self.fill(\"with \")\n        self.interleave(lambda: self.write(\", \"), self.traverse, node.items)\n        with self.block(extra=self.get_type_comment(node)):\n            self.traverse(node.body)\n    def visit_AsyncWith(self, node):\n        self.fill(\"async with \")\n        self.interleave(lambda: self.write(\", \"), self.traverse, node.items)", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-24", "text": "self.interleave(lambda: self.write(\", \"), self.traverse, node.items)\n        with self.block(extra=self.get_type_comment(node)):\n            self.traverse(node.body)\n    def _str_literal_helper(\n        self, string, *, quote_types=_ALL_QUOTES, escape_special_whitespace=False\n    ):\n        \"\"\"Helper for writing string literals, minimizing escapes.\n        Returns the tuple (string literal to write, possible quote types).\n        \"\"\"\n        def escape_char(c):\n            # \\n and \\t are non-printable, but we only escape them if\n            # escape_special_whitespace is True\n            if not escape_special_whitespace and c in \"\\n\\t\":\n                return c\n            # Always escape backslashes and other non-printable characters\n            if c == \"\\\\\" or not c.isprintable():\n                return c.encode(\"unicode_escape\").decode(\"ascii\")\n            return c\n        escaped_string = \"\".join(map(escape_char, string))\n        possible_quotes = quote_types\n        if \"\\n\" in escaped_string:\n            possible_quotes = [q for q in possible_quotes if q in _MULTI_QUOTES]\n        possible_quotes = [q for q in possible_quotes if q not in escaped_string]\n        if not possible_quotes:\n            # If there aren't any possible_quotes, fallback to using repr\n            # on the original string. Try to use a quote from quote_types,\n            # e.g., so that we use triple quotes for docstrings.\n            string = repr(string)\n            quote = next((q for q in quote_types if string[0] in q), string[0])\n            return string[1:-1], [quote]\n        if escaped_string:\n            # Sort so that we prefer '''\"''' over \"\"\"\\\"\"\"\"\n            possible_quotes.sort(key=lambda q: q[0] == escaped_string[-1])", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-25", "text": "possible_quotes.sort(key=lambda q: q[0] == escaped_string[-1])\n            # If we're using triple quotes and we'd need to escape a final\n            # quote, escape it\n            if possible_quotes[0][0] == escaped_string[-1]:\n                assert len(possible_quotes[0]) == 3\n                escaped_string = escaped_string[:-1] + \"\\\\\" + escaped_string[-1]\n        return escaped_string, possible_quotes\n    def _write_str_avoiding_backslashes(self, string, *, quote_types=_ALL_QUOTES):\n        \"\"\"Write string literal value with a best effort attempt to avoid backslashes.\"\"\"\n        string, quote_types = self._str_literal_helper(string, quote_types=quote_types)\n        quote_type = quote_types[0]\n        self.write(f\"{quote_type}{string}{quote_type}\")\n    def visit_JoinedStr(self, node):\n        self.write(\"f\")\n        if self._avoid_backslashes:\n            with self.buffered() as buffer:\n                self._write_fstring_inner(node)\n            return self._write_str_avoiding_backslashes(\"\".join(buffer))\n        # If we don't need to avoid backslashes globally (i.e., we only need\n        # to avoid them inside FormattedValues), it's cosmetically preferred\n        # to use escaped whitespace. That is, it's preferred to use backslashes\n        # for cases like: f\"{x}\\n\". To accomplish this, we keep track of what\n        # in our buffer corresponds to FormattedValues and what corresponds to\n        # Constant parts of the f-string, and allow escapes accordingly.\n        fstring_parts = []\n        for value in node.values:\n            with self.buffered() as buffer:\n                self._write_fstring_inner(value)\n            fstring_parts.append(", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-26", "text": "self._write_fstring_inner(value)\n            fstring_parts.append(\n                (\"\".join(buffer), isinstance(value, Constant))\n            )\n        new_fstring_parts = []\n        quote_types = list(_ALL_QUOTES)\n        fallback_to_repr = False\n        for value, is_constant in fstring_parts:\n            value, new_quote_types = self._str_literal_helper(\n                value,\n                quote_types=quote_types,\n                escape_special_whitespace=is_constant,\n            )\n            new_fstring_parts.append(value)\n            if set(new_quote_types).isdisjoint(quote_types):\n                fallback_to_repr = True\n                break\n            quote_types = new_quote_types\n        if fallback_to_repr:\n            # If we weren't able to find a quote type that works for all parts\n            # of the JoinedStr, fallback to using repr and triple single quotes.\n            quote_types = [\"'''\"]\n            new_fstring_parts.clear()\n            for value, is_constant in fstring_parts:\n                value = repr('\"' + value)  # force repr to use single quotes\n                expected_prefix = \"'\\\"\"\n                assert value.startswith(expected_prefix), repr(value)\n                new_fstring_parts.append(value[len(expected_prefix):-1])\n        value = \"\".join(new_fstring_parts)\n        quote_type = quote_types[0]\n        self.write(f\"{quote_type}{value}{quote_type}\")\n    def _write_fstring_inner(self, node):\n        if isinstance(node, JoinedStr):\n            # for both the f-string itself, and format_spec\n            for value in node.values:\n                self._write_fstring_inner(value)\n        elif isinstance(node, Constant) and isinstance(node.value, str):\n            value = node.value.replace(\"{\", \"{{\").replace(\"}\", \"}}\")\n            self.write(value)", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-27", "text": "self.write(value)\n        elif isinstance(node, FormattedValue):\n            self.visit_FormattedValue(node)\n        else:\n            raise ValueError(f\"Unexpected node inside JoinedStr, {node!r}\")\n    def visit_FormattedValue(self, node):\n        def unparse_inner(inner):\n            unparser = type(self)(_avoid_backslashes=True)\n            unparser.set_precedence(_Precedence.TEST.next(), inner)\n            return unparser.visit(inner)\n        with self.delimit(\"{\", \"}\"):\n            expr = unparse_inner(node.value)\n            if \"\\\\\" in expr:\n                raise ValueError(\n                    \"Unable to avoid backslash in f-string expression part\"\n                )\n            if expr.startswith(\"{\"):\n                # Separate pair of opening brackets as \"{ {\"\n                self.write(\" \")\n            self.write(expr)\n            if node.conversion != -1:\n                self.write(f\"!{chr(node.conversion)}\")\n            if node.format_spec:\n                self.write(\":\")\n                self._write_fstring_inner(node.format_spec)\n    def visit_Name(self, node):\n        self.write(node.id)\n    def _write_docstring(self, node):\n        self.fill()\n        if node.kind == \"u\":\n            self.write(\"u\")\n        self._write_str_avoiding_backslashes(node.value, quote_types=_MULTI_QUOTES)\n    def _write_constant(self, value):\n        if isinstance(value, (float, complex)):\n            # Substitute overflowing decimal literal for AST infinities,\n            # and inf - inf for NaNs.\n            self.write(\n                repr(value)\n                .replace(\"inf\", _INFSTR)\n                .replace(\"nan\", f\"({_INFSTR}-{_INFSTR})\")\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-28", "text": ")\n        elif self._avoid_backslashes and isinstance(value, str):\n            self._write_str_avoiding_backslashes(value)\n        else:\n            self.write(repr(value))\n    def visit_Constant(self, node):\n        value = node.value\n        if isinstance(value, tuple):\n            with self.delimit(\"(\", \")\"):\n                self.items_view(self._write_constant, value)\n        elif value is ...:\n            self.write(\"...\")\n        else:\n            if node.kind == \"u\":\n                self.write(\"u\")\n            self._write_constant(node.value)\n    def visit_List(self, node):\n        with self.delimit(\"[\", \"]\"):\n            self.interleave(lambda: self.write(\", \"), self.traverse, node.elts)\n    def visit_ListComp(self, node):\n        with self.delimit(\"[\", \"]\"):\n            self.traverse(node.elt)\n            for gen in node.generators:\n                self.traverse(gen)\n    def visit_GeneratorExp(self, node):\n        with self.delimit(\"(\", \")\"):\n            self.traverse(node.elt)\n            for gen in node.generators:\n                self.traverse(gen)\n    def visit_SetComp(self, node):\n        with self.delimit(\"{\", \"}\"):\n            self.traverse(node.elt)\n            for gen in node.generators:\n                self.traverse(gen)\n    def visit_DictComp(self, node):\n        with self.delimit(\"{\", \"}\"):\n            self.traverse(node.key)\n            self.write(\": \")\n            self.traverse(node.value)\n            for gen in node.generators:\n                self.traverse(gen)\n    def visit_comprehension(self, node):\n        if node.is_async:\n            self.write(\" async for \")\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-29", "text": "if node.is_async:\n            self.write(\" async for \")\n        else:\n            self.write(\" for \")\n        self.set_precedence(_Precedence.TUPLE, node.target)\n        self.traverse(node.target)\n        self.write(\" in \")\n        self.set_precedence(_Precedence.TEST.next(), node.iter, *node.ifs)\n        self.traverse(node.iter)\n        for if_clause in node.ifs:\n            self.write(\" if \")\n            self.traverse(if_clause)\n    def visit_IfExp(self, node):\n        with self.require_parens(_Precedence.TEST, node):\n            self.set_precedence(_Precedence.TEST.next(), node.body, node.test)\n            self.traverse(node.body)\n            self.write(\" if \")\n            self.traverse(node.test)\n            self.write(\" else \")\n            self.set_precedence(_Precedence.TEST, node.orelse)\n            self.traverse(node.orelse)\n    def visit_Set(self, node):\n        if node.elts:\n            with self.delimit(\"{\", \"}\"):\n                self.interleave(lambda: self.write(\", \"), self.traverse, node.elts)\n        else:\n            # `{}` would be interpreted as a dictionary literal, and\n            # `set` might be shadowed. Thus:\n            self.write('{*()}')\n    def visit_Dict(self, node):\n        def write_key_value_pair(k, v):\n            self.traverse(k)\n            self.write(\": \")\n            self.traverse(v)\n        def write_item(item):\n            k, v = item\n            if k is None:\n                # for dictionary unpacking operator in dicts {**{'y': 2}}\n                # see PEP 448 for details\n                self.write(\"**\")", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-30", "text": "# see PEP 448 for details\n                self.write(\"**\")\n                self.set_precedence(_Precedence.EXPR, v)\n                self.traverse(v)\n            else:\n                write_key_value_pair(k, v)\n        with self.delimit(\"{\", \"}\"):\n            self.interleave(\n                lambda: self.write(\", \"), write_item, zip(node.keys, node.values)\n            )\n    def visit_Tuple(self, node):\n        with self.delimit_if(\n            \"(\",\n            \")\",\n            len(node.elts) == 0 or self.get_precedence(node) > _Precedence.TUPLE\n        ):\n            self.items_view(self.traverse, node.elts)\n    unop = {\"Invert\": \"~\", \"Not\": \"not\", \"UAdd\": \"+\", \"USub\": \"-\"}\n    unop_precedence = {\n        \"not\": _Precedence.NOT,\n        \"~\": _Precedence.FACTOR,\n        \"+\": _Precedence.FACTOR,\n        \"-\": _Precedence.FACTOR,\n    }\n    def visit_UnaryOp(self, node):\n        operator = self.unop[node.op.__class__.__name__]\n        operator_precedence = self.unop_precedence[operator]\n        with self.require_parens(operator_precedence, node):\n            self.write(operator)\n            # factor prefixes (+, -, ~) shouldn't be separated\n            # from the value they belong, (e.g: +1 instead of + 1)\n            if operator_precedence is not _Precedence.FACTOR:\n                self.write(\" \")\n            self.set_precedence(operator_precedence, node.operand)\n            self.traverse(node.operand)\n    binop = {", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-31", "text": "self.traverse(node.operand)\n    binop = {\n        \"Add\": \"+\",\n        \"Sub\": \"-\",\n        \"Mult\": \"*\",\n        \"MatMult\": \"@\",\n        \"Div\": \"/\",\n        \"Mod\": \"%\",\n        \"LShift\": \"<<\",\n        \"RShift\": \">>\",\n        \"BitOr\": \"|\",\n        \"BitXor\": \"^\",\n        \"BitAnd\": \"&\",\n        \"FloorDiv\": \"//\",\n        \"Pow\": \"**\",\n    }\n    binop_precedence = {\n        \"+\": _Precedence.ARITH,\n        \"-\": _Precedence.ARITH,\n        \"*\": _Precedence.TERM,\n        \"@\": _Precedence.TERM,\n        \"/\": _Precedence.TERM,\n        \"%\": _Precedence.TERM,\n        \"<<\": _Precedence.SHIFT,\n        \">>\": _Precedence.SHIFT,\n        \"|\": _Precedence.BOR,\n        \"^\": _Precedence.BXOR,\n        \"&\": _Precedence.BAND,\n        \"//\": _Precedence.TERM,\n        \"**\": _Precedence.POWER,\n    }\n    binop_rassoc = frozenset((\"**\",))\n    def visit_BinOp(self, node):\n        operator = self.binop[node.op.__class__.__name__]\n        operator_precedence = self.binop_precedence[operator]\n        with self.require_parens(operator_precedence, node):\n            if operator in self.binop_rassoc:\n                left_precedence = operator_precedence.next()\n                right_precedence = operator_precedence\n            else:\n                left_precedence = operator_precedence", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-32", "text": "else:\n                left_precedence = operator_precedence\n                right_precedence = operator_precedence.next()\n            self.set_precedence(left_precedence, node.left)\n            self.traverse(node.left)\n            self.write(f\" {operator} \")\n            self.set_precedence(right_precedence, node.right)\n            self.traverse(node.right)\n    cmpops = {\n        \"Eq\": \"==\",\n        \"NotEq\": \"!=\",\n        \"Lt\": \"<\",\n        \"LtE\": \"<=\",\n        \"Gt\": \">\",\n        \"GtE\": \">=\",\n        \"Is\": \"is\",\n        \"IsNot\": \"is not\",\n        \"In\": \"in\",\n        \"NotIn\": \"not in\",\n    }\n    def visit_Compare(self, node):\n        with self.require_parens(_Precedence.CMP, node):\n            self.set_precedence(_Precedence.CMP.next(), node.left, *node.comparators)\n            self.traverse(node.left)\n            for o, e in zip(node.ops, node.comparators):\n                self.write(\" \" + self.cmpops[o.__class__.__name__] + \" \")\n                self.traverse(e)\n    boolops = {\"And\": \"and\", \"Or\": \"or\"}\n    boolop_precedence = {\"and\": _Precedence.AND, \"or\": _Precedence.OR}\n    def visit_BoolOp(self, node):\n        operator = self.boolops[node.op.__class__.__name__]\n        operator_precedence = self.boolop_precedence[operator]\n        def increasing_level_traverse(node):\n            nonlocal operator_precedence\n            operator_precedence = operator_precedence.next()", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-33", "text": "operator_precedence = operator_precedence.next()\n            self.set_precedence(operator_precedence, node)\n            self.traverse(node)\n        with self.require_parens(operator_precedence, node):\n            s = f\" {operator} \"\n            self.interleave(lambda: self.write(s), increasing_level_traverse, node.values)\n    def visit_Attribute(self, node):\n        self.set_precedence(_Precedence.ATOM, node.value)\n        self.traverse(node.value)\n        # Special case: 3.__abs__() is a syntax error, so if node.value\n        # is an integer literal then we need to either parenthesize\n        # it or add an extra space to get 3 .__abs__().\n        if isinstance(node.value, Constant) and isinstance(node.value.value, int):\n            self.write(\" \")\n        self.write(\".\")\n        self.write(node.attr)\n    def visit_Call(self, node):\n        self.set_precedence(_Precedence.ATOM, node.func)\n        self.traverse(node.func)\n        with self.delimit(\"(\", \")\"):\n            comma = False\n            for e in node.args:\n                if comma:\n                    self.write(\", \")\n                else:\n                    comma = True\n                self.traverse(e)\n            for e in node.keywords:\n                if comma:\n                    self.write(\", \")\n                else:\n                    comma = True\n                self.traverse(e)\n    def visit_Subscript(self, node):\n        def is_non_empty_tuple(slice_value):\n            return (\n                isinstance(slice_value, Tuple)\n                and slice_value.elts\n            )\n        self.set_precedence(_Precedence.ATOM, node.value)\n        self.traverse(node.value)\n        with self.delimit(\"[\", \"]\"):", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-34", "text": "self.traverse(node.value)\n        with self.delimit(\"[\", \"]\"):\n            if is_non_empty_tuple(node.slice):\n                # parentheses can be omitted if the tuple isn't empty\n                self.items_view(self.traverse, node.slice.elts)\n            else:\n                self.traverse(node.slice)\n    def visit_Starred(self, node):\n        self.write(\"*\")\n        self.set_precedence(_Precedence.EXPR, node.value)\n        self.traverse(node.value)\n    def visit_Ellipsis(self, node):\n        self.write(\"...\")\n    def visit_Slice(self, node):\n        if node.lower:\n            self.traverse(node.lower)\n        self.write(\":\")\n        if node.upper:\n            self.traverse(node.upper)\n        if node.step:\n            self.write(\":\")\n            self.traverse(node.step)\n    def visit_Match(self, node):\n        self.fill(\"match \")\n        self.traverse(node.subject)\n        with self.block():\n            for case in node.cases:\n                self.traverse(case)\n    def visit_arg(self, node):\n        self.write(node.arg)\n        if node.annotation:\n            self.write(\": \")\n            self.traverse(node.annotation)\n    def visit_arguments(self, node):\n        first = True\n        # normal arguments\n        all_args = node.posonlyargs + node.args\n        defaults = [None] * (len(all_args) - len(node.defaults)) + node.defaults\n        for index, elements in enumerate(zip(all_args, defaults), 1):\n            a, d = elements\n            if first:\n                first = False\n            else:\n                self.write(\", \")\n            self.traverse(a)\n            if d:\n                self.write(\"=\")\n                self.traverse(d)", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-35", "text": "if d:\n                self.write(\"=\")\n                self.traverse(d)\n            if index == len(node.posonlyargs):\n                self.write(\", /\")\n        # varargs, or bare '*' if no varargs but keyword-only arguments present\n        if node.vararg or node.kwonlyargs:\n            if first:\n                first = False\n            else:\n                self.write(\", \")\n            self.write(\"*\")\n            if node.vararg:\n                self.write(node.vararg.arg)\n                if node.vararg.annotation:\n                    self.write(\": \")\n                    self.traverse(node.vararg.annotation)\n        # keyword-only arguments\n        if node.kwonlyargs:\n            for a, d in zip(node.kwonlyargs, node.kw_defaults):\n                self.write(\", \")\n                self.traverse(a)\n                if d:\n                    self.write(\"=\")\n                    self.traverse(d)\n        # kwargs\n        if node.kwarg:\n            if first:\n                first = False\n            else:\n                self.write(\", \")\n            self.write(\"**\" + node.kwarg.arg)\n            if node.kwarg.annotation:\n                self.write(\": \")\n                self.traverse(node.kwarg.annotation)\n    def visit_keyword(self, node):\n        if node.arg is None:\n            self.write(\"**\")\n        else:\n            self.write(node.arg)\n            self.write(\"=\")\n        self.traverse(node.value)\n    def visit_Lambda(self, node):\n        with self.require_parens(_Precedence.TEST, node):\n            self.write(\"lambda\")\n            with self.buffered() as buffer:\n                self.traverse(node.args)\n            if buffer:\n                self.write(\" \", *buffer)\n            self.write(\": \")", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-36", "text": "if buffer:\n                self.write(\" \", *buffer)\n            self.write(\": \")\n            self.set_precedence(_Precedence.TEST, node.body)\n            self.traverse(node.body)\n    def visit_alias(self, node):\n        self.write(node.name)\n        if node.asname:\n            self.write(\" as \" + node.asname)\n    def visit_withitem(self, node):\n        self.traverse(node.context_expr)\n        if node.optional_vars:\n            self.write(\" as \")\n            self.traverse(node.optional_vars)\n    def visit_match_case(self, node):\n        self.fill(\"case \")\n        self.traverse(node.pattern)\n        if node.guard:\n            self.write(\" if \")\n            self.traverse(node.guard)\n        with self.block():\n            self.traverse(node.body)\n    def visit_MatchValue(self, node):\n        self.traverse(node.value)\n    def visit_MatchSingleton(self, node):\n        self._write_constant(node.value)\n    def visit_MatchSequence(self, node):\n        with self.delimit(\"[\", \"]\"):\n            self.interleave(\n                lambda: self.write(\", \"), self.traverse, node.patterns\n            )\n    def visit_MatchStar(self, node):\n        name = node.name\n        if name is None:\n            name = \"_\"\n        self.write(f\"*{name}\")\n    def visit_MatchMapping(self, node):\n        def write_key_pattern_pair(pair):\n            k, p = pair\n            self.traverse(k)\n            self.write(\": \")\n            self.traverse(p)\n        with self.delimit(\"{\", \"}\"):\n            keys = node.keys\n            self.interleave(\n                lambda: self.write(\", \"),\n                write_key_pattern_pair,\n                zip(keys, node.patterns, strict=True),", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-37", "text": "write_key_pattern_pair,\n                zip(keys, node.patterns, strict=True),\n            )\n            rest = node.rest\n            if rest is not None:\n                if keys:\n                    self.write(\", \")\n                self.write(f\"**{rest}\")\n    def visit_MatchClass(self, node):\n        self.set_precedence(_Precedence.ATOM, node.cls)\n        self.traverse(node.cls)\n        with self.delimit(\"(\", \")\"):\n            patterns = node.patterns\n            self.interleave(\n                lambda: self.write(\", \"), self.traverse, patterns\n            )\n            attrs = node.kwd_attrs\n            if attrs:\n                def write_attr_pattern(pair):\n                    attr, pattern = pair\n                    self.write(f\"{attr}=\")\n                    self.traverse(pattern)\n                if patterns:\n                    self.write(\", \")\n                self.interleave(\n                    lambda: self.write(\", \"),\n                    write_attr_pattern,\n                    zip(attrs, node.kwd_patterns, strict=True),\n                )\n    def visit_MatchAs(self, node):\n        name = node.name\n        pattern = node.pattern\n        if name is None:\n            self.write(\"_\")\n        elif pattern is None:\n            self.write(node.name)\n        else:\n            with self.require_parens(_Precedence.TEST, node):\n                self.set_precedence(_Precedence.BOR, node.pattern)\n                self.traverse(node.pattern)\n                self.write(f\" as {node.name}\")\n    def visit_MatchOr(self, node):\n        with self.require_parens(_Precedence.BOR, node):\n            self.set_precedence(_Precedence.BOR.next(), *node.patterns)\n            self.interleave(lambda: self.write(\" | \"), self.traverse, node.patterns)", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "93f5fd6782c0-38", "text": "self.interleave(lambda: self.write(\" | \"), self.traverse, node.patterns)\ndef unparse(ast_obj):\n    unparser = _Unparser()\n    return unparser.visit(ast_obj)\ndef main():\n    import argparse\n    parser = argparse.ArgumentParser(prog='python -m ast')\n    parser.add_argument('infile', type=argparse.FileType(mode='rb'), nargs='?',\n                        default='-',\n                        help='the file to parse; defaults to stdin')\n    parser.add_argument('-m', '--mode', default='exec',\n                        choices=('exec', 'single', 'eval', 'func_type'),\n                        help='specify what kind of code must be parsed')\n    parser.add_argument('--no-type-comments', default=True, action='store_false',\n                        help=\"don't add information about type comments\")\n    parser.add_argument('-a', '--include-attributes', action='store_true',\n                        help='include attributes such as line numbers and '\n                             'column offsets')\n    parser.add_argument('-i', '--indent', type=int, default=3,\n                        help='indentation of nodes (number of spaces)')\n    args = parser.parse_args()\n    with args.infile as infile:\n        source = infile.read()\n    tree = parse(source, args.infile.name, args.mode, type_comments=args.no_type_comments)\n    print(dump(tree, include_attributes=args.include_attributes, indent=args.indent))\nif __name__ == '__main__':\n    main()", "source": "lang/api.python.langchain.com/en/latest/_modules/ast.html"}
{"id": "fda4fdfd093c-0", "text": "Source code for string\n\"\"\"A collection of string constants.\nPublic module variables:\nwhitespace -- a string containing all ASCII whitespace\nascii_lowercase -- a string containing all ASCII lowercase letters\nascii_uppercase -- a string containing all ASCII uppercase letters\nascii_letters -- a string containing all ASCII letters\ndigits -- a string containing all ASCII decimal digits\nhexdigits -- a string containing all ASCII hexadecimal digits\noctdigits -- a string containing all ASCII octal digits\npunctuation -- a string containing all ASCII punctuation characters\nprintable -- a string containing all ASCII characters considered printable\n\"\"\"\n__all__ = [\"ascii_letters\", \"ascii_lowercase\", \"ascii_uppercase\", \"capwords\",\n           \"digits\", \"hexdigits\", \"octdigits\", \"printable\", \"punctuation\",\n           \"whitespace\", \"Formatter\", \"Template\"]\nimport _string\n# Some strings for ctype-style character classification\nwhitespace = ' \\t\\n\\r\\v\\f'\nascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'\nascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nascii_letters = ascii_lowercase + ascii_uppercase\ndigits = '0123456789'\nhexdigits = digits + 'abcdef' + 'ABCDEF'\noctdigits = '01234567'\npunctuation = r\"\"\"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\"\"\"\nprintable = digits + ascii_letters + punctuation + whitespace\n# Functions which aren't available as string methods.\n# Capitalize the words in a string, e.g. \" aBc  dEf \" -> \"Abc Def\".\ndef capwords(s, sep=None):\n    \"\"\"capwords(s [,sep]) -> string\n    Split the argument into words using split, capitalize each\n    word using capitalize, and join the capitalized words using\n    join.  If the optional second argument sep is absent or None,", "source": "lang/api.python.langchain.com/en/latest/_modules/string.html"}
{"id": "fda4fdfd093c-1", "text": "join.  If the optional second argument sep is absent or None,\n    runs of whitespace characters are replaced by a single space\n    and leading and trailing whitespace are removed, otherwise\n    sep is used to split and join the words.\n    \"\"\"\n    return (sep or ' ').join(map(str.capitalize, s.split(sep)))\n####################################################################\nimport re as _re\nfrom collections import ChainMap as _ChainMap\n_sentinel_dict = {}\nclass Template:\n    \"\"\"A string class for supporting $-substitutions.\"\"\"\n    delimiter = '$'\n    # r'[a-z]' matches to non-ASCII letters when used with IGNORECASE, but\n    # without the ASCII flag.  We can't add re.ASCII to flags because of\n    # backward compatibility.  So we use the ?a local flag and [a-z] pattern.\n    # See https://bugs.python.org/issue31672\n    idpattern = r'(?a:[_a-z][_a-z0-9]*)'\n    braceidpattern = None\n    flags = _re.IGNORECASE\n    def __init_subclass__(cls):\n        super().__init_subclass__()\n        if 'pattern' in cls.__dict__:\n            pattern = cls.pattern\n        else:\n            delim = _re.escape(cls.delimiter)\n            id = cls.idpattern\n            bid = cls.braceidpattern or cls.idpattern\n            pattern = fr\"\"\"\n            {delim}(?:\n              (?P<escaped>{delim})  |   # Escape sequence of two delimiters\n              (?P<named>{id})       |   # delimiter and a Python identifier\n              {{(?P<braced>{bid})}} |   # delimiter and a braced identifier\n              (?P<invalid>)             # Other ill-formed delimiter exprs\n            )\n            \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/string.html"}
{"id": "fda4fdfd093c-2", "text": ")\n            \"\"\"\n        cls.pattern = _re.compile(pattern, cls.flags | _re.VERBOSE)\n    def __init__(self, template):\n        self.template = template\n    # Search for $$, $identifier, ${identifier}, and any bare $'s\n    def _invalid(self, mo):\n        i = mo.start('invalid')\n        lines = self.template[:i].splitlines(keepends=True)\n        if not lines:\n            colno = 1\n            lineno = 1\n        else:\n            colno = i - len(''.join(lines[:-1]))\n            lineno = len(lines)\n        raise ValueError('Invalid placeholder in string: line %d, col %d' %\n                         (lineno, colno))\n    def substitute(self, mapping=_sentinel_dict, /, **kws):\n        if mapping is _sentinel_dict:\n            mapping = kws\n        elif kws:\n            mapping = _ChainMap(kws, mapping)\n        # Helper function for .sub()\n        def convert(mo):\n            # Check the most common path first.\n            named = mo.group('named') or mo.group('braced')\n            if named is not None:\n                return str(mapping[named])\n            if mo.group('escaped') is not None:\n                return self.delimiter\n            if mo.group('invalid') is not None:\n                self._invalid(mo)\n            raise ValueError('Unrecognized named group in pattern',\n                             self.pattern)\n        return self.pattern.sub(convert, self.template)\n    def safe_substitute(self, mapping=_sentinel_dict, /, **kws):\n        if mapping is _sentinel_dict:\n            mapping = kws\n        elif kws:\n            mapping = _ChainMap(kws, mapping)", "source": "lang/api.python.langchain.com/en/latest/_modules/string.html"}
{"id": "fda4fdfd093c-3", "text": "elif kws:\n            mapping = _ChainMap(kws, mapping)\n        # Helper function for .sub()\n        def convert(mo):\n            named = mo.group('named') or mo.group('braced')\n            if named is not None:\n                try:\n                    return str(mapping[named])\n                except KeyError:\n                    return mo.group()\n            if mo.group('escaped') is not None:\n                return self.delimiter\n            if mo.group('invalid') is not None:\n                return mo.group()\n            raise ValueError('Unrecognized named group in pattern',\n                             self.pattern)\n        return self.pattern.sub(convert, self.template)\n    def is_valid(self):\n        for mo in self.pattern.finditer(self.template):\n            if mo.group('invalid') is not None:\n                return False\n            if (mo.group('named') is None\n                and mo.group('braced') is None\n                and mo.group('escaped') is None):\n                # If all the groups are None, there must be\n                # another group we're not expecting\n                raise ValueError('Unrecognized named group in pattern',\n                    self.pattern)\n        return True\n    def get_identifiers(self):\n        ids = []\n        for mo in self.pattern.finditer(self.template):\n            named = mo.group('named') or mo.group('braced')\n            if named is not None and named not in ids:\n                # add a named group only the first time it appears\n                ids.append(named)\n            elif (named is None\n                and mo.group('invalid') is None\n                and mo.group('escaped') is None):\n                # If all the groups are None, there must be\n                # another group we're not expecting\n                raise ValueError('Unrecognized named group in pattern',\n                    self.pattern)\n        return ids", "source": "lang/api.python.langchain.com/en/latest/_modules/string.html"}
{"id": "fda4fdfd093c-4", "text": "self.pattern)\n        return ids\n# Initialize Template.pattern.  __init_subclass__() is automatically called\n# only for subclasses, not for the Template class itself.\nTemplate.__init_subclass__()\n########################################################################\n# the Formatter class\n# see PEP 3101 for details and purpose of this class\n# The hard parts are reused from the C implementation.  They're exposed as \"_\"\n# prefixed methods of str.\n# The overall parser is implemented in _string.formatter_parser.\n# The field name parser is implemented in _string.formatter_field_name_split\nclass Formatter:\n    def format(self, format_string, /, *args, **kwargs):\n        return self.vformat(format_string, args, kwargs)\n    def vformat(self, format_string, args, kwargs):\n        used_args = set()\n        result, _ = self._vformat(format_string, args, kwargs, used_args, 2)\n        self.check_unused_args(used_args, args, kwargs)\n        return result\n    def _vformat(self, format_string, args, kwargs, used_args, recursion_depth,\n                 auto_arg_index=0):\n        if recursion_depth < 0:\n            raise ValueError('Max string recursion exceeded')\n        result = []\n        for literal_text, field_name, format_spec, conversion in \\\n                self.parse(format_string):\n            # output the literal text\n            if literal_text:\n                result.append(literal_text)\n            # if there's a field, output it\n            if field_name is not None:\n                # this is some markup, find the object and do\n                #  the formatting\n                # handle arg indexing when empty field_names are given.\n                if field_name == '':\n                    if auto_arg_index is False:\n                        raise ValueError('cannot switch from manual field '", "source": "lang/api.python.langchain.com/en/latest/_modules/string.html"}
{"id": "fda4fdfd093c-5", "text": "if auto_arg_index is False:\n                        raise ValueError('cannot switch from manual field '\n                                         'specification to automatic field '\n                                         'numbering')\n                    field_name = str(auto_arg_index)\n                    auto_arg_index += 1\n                elif field_name.isdigit():\n                    if auto_arg_index:\n                        raise ValueError('cannot switch from manual field '\n                                         'specification to automatic field '\n                                         'numbering')\n                    # disable auto arg incrementing, if it gets\n                    # used later on, then an exception will be raised\n                    auto_arg_index = False\n                # given the field_name, find the object it references\n                #  and the argument it came from\n                obj, arg_used = self.get_field(field_name, args, kwargs)\n                used_args.add(arg_used)\n                # do any conversion on the resulting object\n                obj = self.convert_field(obj, conversion)\n                # expand the format spec, if needed\n                format_spec, auto_arg_index = self._vformat(\n                    format_spec, args, kwargs,\n                    used_args, recursion_depth-1,\n                    auto_arg_index=auto_arg_index)\n                # format the object and append to the result\n                result.append(self.format_field(obj, format_spec))\n        return ''.join(result), auto_arg_index\n    def get_value(self, key, args, kwargs):\n        if isinstance(key, int):\n            return args[key]\n        else:\n            return kwargs[key]\n    def check_unused_args(self, used_args, args, kwargs):\n        pass\n    def format_field(self, value, format_spec):\n        return format(value, format_spec)\n    def convert_field(self, value, conversion):\n        # do any conversion on the resulting object\n        if conversion is None:\n            return value\n        elif conversion == 's':", "source": "lang/api.python.langchain.com/en/latest/_modules/string.html"}
{"id": "fda4fdfd093c-6", "text": "if conversion is None:\n            return value\n        elif conversion == 's':\n            return str(value)\n        elif conversion == 'r':\n            return repr(value)\n        elif conversion == 'a':\n            return ascii(value)\n        raise ValueError(\"Unknown conversion specifier {0!s}\".format(conversion))\n    # returns an iterable that contains tuples of the form:\n    # (literal_text, field_name, format_spec, conversion)\n    # literal_text can be zero length\n    # field_name can be None, in which case there's no\n    #  object to format and output\n    # if field_name is not None, it is looked up, formatted\n    #  with format_spec and conversion and then used\n    def parse(self, format_string):\n        return _string.formatter_parser(format_string)\n    # given a field_name, find the object it references.\n    #  field_name:   the field being looked up, e.g. \"0.name\"\n    #                 or \"lookup[3]\"\n    #  used_args:    a set of which args have been used\n    #  args, kwargs: as passed in to vformat\n    def get_field(self, field_name, args, kwargs):\n        first, rest = _string.formatter_field_name_split(field_name)\n        obj = self.get_value(first, args, kwargs)\n        # loop through the rest of the field_name, doing\n        #  getattr or getitem as needed\n        for is_attr, i in rest:\n            if is_attr:\n                obj = getattr(obj, i)\n            else:\n                obj = obj[i]\n        return obj, first", "source": "lang/api.python.langchain.com/en/latest/_modules/string.html"}
{"id": "95552857791c-0", "text": "All modules for which code is available\n_markupbase\nast\nhtml.parser\nlangchain.adapters.openai\nlangchain.agents.agent\nlangchain.agents.agent_iterator\nlangchain.agents.agent_toolkits.ainetwork.toolkit\nlangchain.agents.agent_toolkits.amadeus.toolkit\nlangchain.agents.agent_toolkits.azure_cognitive_services\nlangchain.agents.agent_toolkits.base\nlangchain.agents.agent_toolkits.clickup.toolkit\nlangchain.agents.agent_toolkits.conversational_retrieval.openai_functions\nlangchain.agents.agent_toolkits.file_management.toolkit\nlangchain.agents.agent_toolkits.github.toolkit\nlangchain.agents.agent_toolkits.gitlab.toolkit\nlangchain.agents.agent_toolkits.gmail.toolkit\nlangchain.agents.agent_toolkits.jira.toolkit\nlangchain.agents.agent_toolkits.json.base\nlangchain.agents.agent_toolkits.json.toolkit\nlangchain.agents.agent_toolkits.multion.toolkit\nlangchain.agents.agent_toolkits.nla.tool\nlangchain.agents.agent_toolkits.nla.toolkit\nlangchain.agents.agent_toolkits.office365.toolkit\nlangchain.agents.agent_toolkits.openapi.base\nlangchain.agents.agent_toolkits.openapi.planner\nlangchain.agents.agent_toolkits.openapi.spec\nlangchain.agents.agent_toolkits.openapi.toolkit\nlangchain.agents.agent_toolkits.playwright.toolkit\nlangchain.agents.agent_toolkits.powerbi.base\nlangchain.agents.agent_toolkits.powerbi.chat_base\nlangchain.agents.agent_toolkits.powerbi.toolkit\nlangchain.agents.agent_toolkits.spark_sql.base\nlangchain.agents.agent_toolkits.spark_sql.toolkit\nlangchain.agents.agent_toolkits.sql.base\nlangchain.agents.agent_toolkits.sql.toolkit\nlangchain.agents.agent_toolkits.vectorstore.base\nlangchain.agents.agent_toolkits.vectorstore.toolkit", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-1", "text": "langchain.agents.agent_toolkits.vectorstore.toolkit\nlangchain.agents.agent_toolkits.zapier.toolkit\nlangchain.agents.agent_types\nlangchain.agents.chat.base\nlangchain.agents.chat.output_parser\nlangchain.agents.conversational.base\nlangchain.agents.conversational.output_parser\nlangchain.agents.conversational_chat.base\nlangchain.agents.conversational_chat.output_parser\nlangchain.agents.format_scratchpad.log\nlangchain.agents.format_scratchpad.log_to_messages\nlangchain.agents.format_scratchpad.openai_functions\nlangchain.agents.format_scratchpad.openai_tools\nlangchain.agents.format_scratchpad.xml\nlangchain.agents.initialize\nlangchain.agents.load_tools\nlangchain.agents.loading\nlangchain.agents.mrkl.base\nlangchain.agents.mrkl.output_parser\nlangchain.agents.openai_assistant.base\nlangchain.agents.openai_functions_agent.agent_token_buffer_memory\nlangchain.agents.openai_functions_agent.base\nlangchain.agents.openai_functions_multi_agent.base\nlangchain.agents.output_parsers.json\nlangchain.agents.output_parsers.openai_functions\nlangchain.agents.output_parsers.openai_tools\nlangchain.agents.output_parsers.react_json_single_input\nlangchain.agents.output_parsers.react_single_input\nlangchain.agents.output_parsers.self_ask\nlangchain.agents.output_parsers.xml\nlangchain.agents.react.base\nlangchain.agents.react.output_parser\nlangchain.agents.schema\nlangchain.agents.self_ask_with_search.base\nlangchain.agents.structured_chat.base\nlangchain.agents.structured_chat.output_parser\nlangchain.agents.tools\nlangchain.agents.utils\nlangchain.agents.xml.base\nlangchain.cache\nlangchain.callbacks.aim_callback\nlangchain.callbacks.argilla_callback\nlangchain.callbacks.arize_callback\nlangchain.callbacks.arthur_callback", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-2", "text": "langchain.callbacks.arize_callback\nlangchain.callbacks.arthur_callback\nlangchain.callbacks.clearml_callback\nlangchain.callbacks.comet_ml_callback\nlangchain.callbacks.confident_callback\nlangchain.callbacks.context_callback\nlangchain.callbacks.file\nlangchain.callbacks.flyte_callback\nlangchain.callbacks.human\nlangchain.callbacks.infino_callback\nlangchain.callbacks.labelstudio_callback\nlangchain.callbacks.llmonitor_callback\nlangchain.callbacks.manager\nlangchain.callbacks.mlflow_callback\nlangchain.callbacks.openai_info\nlangchain.callbacks.promptlayer_callback\nlangchain.callbacks.sagemaker_callback\nlangchain.callbacks.streaming_aiter\nlangchain.callbacks.streaming_aiter_final_only\nlangchain.callbacks.streaming_stdout\nlangchain.callbacks.streaming_stdout_final_only\nlangchain.callbacks.streamlit.mutable_expander\nlangchain.callbacks.streamlit.streamlit_callback_handler\nlangchain.callbacks.tracers.wandb\nlangchain.callbacks.trubrics_callback\nlangchain.callbacks.utils\nlangchain.callbacks.wandb_callback\nlangchain.callbacks.whylabs_callback\nlangchain.chains.api.base\nlangchain.chains.api.openapi.chain\nlangchain.chains.api.openapi.requests_chain\nlangchain.chains.api.openapi.response_chain\nlangchain.chains.base\nlangchain.chains.combine_documents.base\nlangchain.chains.combine_documents.map_reduce\nlangchain.chains.combine_documents.map_rerank\nlangchain.chains.combine_documents.reduce\nlangchain.chains.combine_documents.refine\nlangchain.chains.combine_documents.stuff\nlangchain.chains.constitutional_ai.base\nlangchain.chains.constitutional_ai.models\nlangchain.chains.conversation.base\nlangchain.chains.conversational_retrieval.base\nlangchain.chains.elasticsearch_database.base\nlangchain.chains.example_generator\nlangchain.chains.flare.base\nlangchain.chains.flare.prompts\nlangchain.chains.graph_qa.arangodb\nlangchain.chains.graph_qa.base\nlangchain.chains.graph_qa.cypher", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-3", "text": "langchain.chains.graph_qa.base\nlangchain.chains.graph_qa.cypher\nlangchain.chains.graph_qa.cypher_utils\nlangchain.chains.graph_qa.falkordb\nlangchain.chains.graph_qa.hugegraph\nlangchain.chains.graph_qa.kuzu\nlangchain.chains.graph_qa.nebulagraph\nlangchain.chains.graph_qa.neptune_cypher\nlangchain.chains.graph_qa.sparql\nlangchain.chains.hyde.base\nlangchain.chains.llm\nlangchain.chains.llm_checker.base\nlangchain.chains.llm_math.base\nlangchain.chains.llm_requests\nlangchain.chains.llm_summarization_checker.base\nlangchain.chains.loading\nlangchain.chains.mapreduce\nlangchain.chains.moderation\nlangchain.chains.natbot.base\nlangchain.chains.natbot.crawler\nlangchain.chains.openai_functions.base\nlangchain.chains.openai_functions.citation_fuzzy_match\nlangchain.chains.openai_functions.extraction\nlangchain.chains.openai_functions.openapi\nlangchain.chains.openai_functions.qa_with_structure\nlangchain.chains.openai_functions.tagging\nlangchain.chains.openai_functions.utils\nlangchain.chains.openai_tools.extraction\nlangchain.chains.prompt_selector\nlangchain.chains.qa_generation.base\nlangchain.chains.qa_with_sources.base\nlangchain.chains.qa_with_sources.loading\nlangchain.chains.qa_with_sources.retrieval\nlangchain.chains.qa_with_sources.vector_db\nlangchain.chains.query_constructor.base\nlangchain.chains.query_constructor.ir\nlangchain.chains.query_constructor.parser\nlangchain.chains.query_constructor.schema\nlangchain.chains.retrieval_qa.base\nlangchain.chains.router.base\nlangchain.chains.router.embedding_router\nlangchain.chains.router.llm_router", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-4", "text": "langchain.chains.router.embedding_router\nlangchain.chains.router.llm_router\nlangchain.chains.router.multi_prompt\nlangchain.chains.router.multi_retrieval_qa\nlangchain.chains.sequential\nlangchain.chains.sql_database.query\nlangchain.chains.transform\nlangchain.chat_loaders.base\nlangchain.chat_loaders.facebook_messenger\nlangchain.chat_loaders.gmail\nlangchain.chat_loaders.imessage\nlangchain.chat_loaders.langsmith\nlangchain.chat_loaders.slack\nlangchain.chat_loaders.telegram\nlangchain.chat_loaders.utils\nlangchain.chat_loaders.whatsapp\nlangchain.chat_models.anthropic\nlangchain.chat_models.anyscale\nlangchain.chat_models.azure_openai\nlangchain.chat_models.azureml_endpoint\nlangchain.chat_models.baichuan\nlangchain.chat_models.baidu_qianfan_endpoint\nlangchain.chat_models.base\nlangchain.chat_models.bedrock\nlangchain.chat_models.cohere\nlangchain.chat_models.ernie\nlangchain.chat_models.everlyai\nlangchain.chat_models.fake\nlangchain.chat_models.fireworks\nlangchain.chat_models.gigachat\nlangchain.chat_models.google_palm\nlangchain.chat_models.human\nlangchain.chat_models.hunyuan\nlangchain.chat_models.javelin_ai_gateway\nlangchain.chat_models.jinachat\nlangchain.chat_models.konko\nlangchain.chat_models.litellm\nlangchain.chat_models.minimax\nlangchain.chat_models.mlflow_ai_gateway\nlangchain.chat_models.ollama\nlangchain.chat_models.openai\nlangchain.chat_models.pai_eas_endpoint\nlangchain.chat_models.promptlayer_openai\nlangchain.chat_models.tongyi\nlangchain.chat_models.vertexai\nlangchain.chat_models.yandex\nlangchain.docstore.arbitrary_fn\nlangchain.docstore.base\nlangchain.docstore.in_memory\nlangchain.docstore.wikipedia", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-5", "text": "langchain.docstore.base\nlangchain.docstore.in_memory\nlangchain.docstore.wikipedia\nlangchain.document_loaders.acreom\nlangchain.document_loaders.airbyte\nlangchain.document_loaders.airbyte_json\nlangchain.document_loaders.airtable\nlangchain.document_loaders.apify_dataset\nlangchain.document_loaders.arcgis_loader\nlangchain.document_loaders.arxiv\nlangchain.document_loaders.assemblyai\nlangchain.document_loaders.async_html\nlangchain.document_loaders.azlyrics\nlangchain.document_loaders.azure_blob_storage_container\nlangchain.document_loaders.azure_blob_storage_file\nlangchain.document_loaders.baiducloud_bos_directory\nlangchain.document_loaders.baiducloud_bos_file\nlangchain.document_loaders.base\nlangchain.document_loaders.base_o365\nlangchain.document_loaders.bibtex\nlangchain.document_loaders.bigquery\nlangchain.document_loaders.bilibili\nlangchain.document_loaders.blackboard\nlangchain.document_loaders.blob_loaders.file_system\nlangchain.document_loaders.blob_loaders.schema\nlangchain.document_loaders.blob_loaders.youtube_audio\nlangchain.document_loaders.blockchain\nlangchain.document_loaders.brave_search\nlangchain.document_loaders.browserless\nlangchain.document_loaders.chatgpt\nlangchain.document_loaders.chromium\nlangchain.document_loaders.college_confidential\nlangchain.document_loaders.concurrent\nlangchain.document_loaders.confluence\nlangchain.document_loaders.conllu\nlangchain.document_loaders.csv_loader\nlangchain.document_loaders.cube_semantic\nlangchain.document_loaders.datadog_logs\nlangchain.document_loaders.dataframe\nlangchain.document_loaders.diffbot\nlangchain.document_loaders.directory\nlangchain.document_loaders.discord\nlangchain.document_loaders.docugami\nlangchain.document_loaders.docusaurus\nlangchain.document_loaders.dropbox\nlangchain.document_loaders.duckdb_loader", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-6", "text": "langchain.document_loaders.dropbox\nlangchain.document_loaders.duckdb_loader\nlangchain.document_loaders.email\nlangchain.document_loaders.embaas\nlangchain.document_loaders.epub\nlangchain.document_loaders.etherscan\nlangchain.document_loaders.evernote\nlangchain.document_loaders.excel\nlangchain.document_loaders.facebook_chat\nlangchain.document_loaders.fauna\nlangchain.document_loaders.figma\nlangchain.document_loaders.gcs_directory\nlangchain.document_loaders.gcs_file\nlangchain.document_loaders.generic\nlangchain.document_loaders.geodataframe\nlangchain.document_loaders.git\nlangchain.document_loaders.gitbook\nlangchain.document_loaders.github\nlangchain.document_loaders.google_speech_to_text\nlangchain.document_loaders.googledrive\nlangchain.document_loaders.gutenberg\nlangchain.document_loaders.helpers\nlangchain.document_loaders.hn\nlangchain.document_loaders.html\nlangchain.document_loaders.html_bs\nlangchain.document_loaders.hugging_face_dataset\nlangchain.document_loaders.ifixit\nlangchain.document_loaders.image\nlangchain.document_loaders.image_captions\nlangchain.document_loaders.imsdb\nlangchain.document_loaders.iugu\nlangchain.document_loaders.joplin\nlangchain.document_loaders.json_loader\nlangchain.document_loaders.lakefs\nlangchain.document_loaders.larksuite\nlangchain.document_loaders.markdown\nlangchain.document_loaders.mastodon\nlangchain.document_loaders.max_compute\nlangchain.document_loaders.mediawikidump\nlangchain.document_loaders.merge\nlangchain.document_loaders.mhtml\nlangchain.document_loaders.modern_treasury\nlangchain.document_loaders.mongodb\nlangchain.document_loaders.news\nlangchain.document_loaders.notebook\nlangchain.document_loaders.notion\nlangchain.document_loaders.notiondb", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-7", "text": "langchain.document_loaders.notion\nlangchain.document_loaders.notiondb\nlangchain.document_loaders.nuclia\nlangchain.document_loaders.obs_directory\nlangchain.document_loaders.obs_file\nlangchain.document_loaders.obsidian\nlangchain.document_loaders.odt\nlangchain.document_loaders.onedrive\nlangchain.document_loaders.onedrive_file\nlangchain.document_loaders.open_city_data\nlangchain.document_loaders.org_mode\nlangchain.document_loaders.parsers.audio\nlangchain.document_loaders.parsers.docai\nlangchain.document_loaders.parsers.generic\nlangchain.document_loaders.parsers.grobid\nlangchain.document_loaders.parsers.html.bs4\nlangchain.document_loaders.parsers.language.cobol\nlangchain.document_loaders.parsers.language.code_segmenter\nlangchain.document_loaders.parsers.language.javascript\nlangchain.document_loaders.parsers.language.language_parser\nlangchain.document_loaders.parsers.language.python\nlangchain.document_loaders.parsers.msword\nlangchain.document_loaders.parsers.pdf\nlangchain.document_loaders.parsers.registry\nlangchain.document_loaders.parsers.txt\nlangchain.document_loaders.pdf\nlangchain.document_loaders.polars_dataframe\nlangchain.document_loaders.powerpoint\nlangchain.document_loaders.psychic\nlangchain.document_loaders.pubmed\nlangchain.document_loaders.pyspark_dataframe\nlangchain.document_loaders.python\nlangchain.document_loaders.quip\nlangchain.document_loaders.readthedocs\nlangchain.document_loaders.recursive_url_loader\nlangchain.document_loaders.reddit\nlangchain.document_loaders.roam\nlangchain.document_loaders.rocksetdb\nlangchain.document_loaders.rspace\nlangchain.document_loaders.rss\nlangchain.document_loaders.rst\nlangchain.document_loaders.rtf\nlangchain.document_loaders.s3_directory\nlangchain.document_loaders.s3_file\nlangchain.document_loaders.sharepoint\nlangchain.document_loaders.sitemap", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-8", "text": "langchain.document_loaders.sharepoint\nlangchain.document_loaders.sitemap\nlangchain.document_loaders.slack_directory\nlangchain.document_loaders.snowflake_loader\nlangchain.document_loaders.spreedly\nlangchain.document_loaders.srt\nlangchain.document_loaders.stripe\nlangchain.document_loaders.telegram\nlangchain.document_loaders.tencent_cos_directory\nlangchain.document_loaders.tencent_cos_file\nlangchain.document_loaders.tensorflow_datasets\nlangchain.document_loaders.text\nlangchain.document_loaders.tomarkdown\nlangchain.document_loaders.toml\nlangchain.document_loaders.trello\nlangchain.document_loaders.tsv\nlangchain.document_loaders.twitter\nlangchain.document_loaders.unstructured\nlangchain.document_loaders.url\nlangchain.document_loaders.url_playwright\nlangchain.document_loaders.url_selenium\nlangchain.document_loaders.weather\nlangchain.document_loaders.web_base\nlangchain.document_loaders.whatsapp_chat\nlangchain.document_loaders.wikipedia\nlangchain.document_loaders.word_document\nlangchain.document_loaders.xml\nlangchain.document_loaders.xorbits\nlangchain.document_loaders.youtube\nlangchain.document_transformers.beautiful_soup_transformer\nlangchain.document_transformers.doctran_text_extract\nlangchain.document_transformers.doctran_text_qa\nlangchain.document_transformers.doctran_text_translate\nlangchain.document_transformers.embeddings_redundant_filter\nlangchain.document_transformers.google_translate\nlangchain.document_transformers.html2text\nlangchain.document_transformers.long_context_reorder\nlangchain.document_transformers.nuclia_text_transform\nlangchain.document_transformers.openai_functions\nlangchain.embeddings.aleph_alpha\nlangchain.embeddings.awa\nlangchain.embeddings.azure_openai\nlangchain.embeddings.baidu_qianfan_endpoint\nlangchain.embeddings.bedrock\nlangchain.embeddings.cache\nlangchain.embeddings.clarifai", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-9", "text": "langchain.embeddings.cache\nlangchain.embeddings.clarifai\nlangchain.embeddings.cohere\nlangchain.embeddings.dashscope\nlangchain.embeddings.deepinfra\nlangchain.embeddings.edenai\nlangchain.embeddings.elasticsearch\nlangchain.embeddings.embaas\nlangchain.embeddings.ernie\nlangchain.embeddings.fake\nlangchain.embeddings.fastembed\nlangchain.embeddings.google_palm\nlangchain.embeddings.gpt4all\nlangchain.embeddings.gradient_ai\nlangchain.embeddings.huggingface\nlangchain.embeddings.huggingface_hub\nlangchain.embeddings.javelin_ai_gateway\nlangchain.embeddings.jina\nlangchain.embeddings.johnsnowlabs\nlangchain.embeddings.llamacpp\nlangchain.embeddings.llm_rails\nlangchain.embeddings.localai\nlangchain.embeddings.minimax\nlangchain.embeddings.mlflow_gateway\nlangchain.embeddings.modelscope_hub\nlangchain.embeddings.mosaicml\nlangchain.embeddings.nlpcloud\nlangchain.embeddings.octoai_embeddings\nlangchain.embeddings.ollama\nlangchain.embeddings.openai\nlangchain.embeddings.sagemaker_endpoint\nlangchain.embeddings.self_hosted\nlangchain.embeddings.self_hosted_hugging_face\nlangchain.embeddings.spacy_embeddings\nlangchain.embeddings.tensorflow_hub\nlangchain.embeddings.vertexai\nlangchain.embeddings.voyageai\nlangchain.embeddings.xinference\nlangchain.evaluation.agents.trajectory_eval_chain\nlangchain.evaluation.comparison.eval_chain\nlangchain.evaluation.criteria.eval_chain\nlangchain.evaluation.embedding_distance.base\nlangchain.evaluation.exact_match.base\nlangchain.evaluation.loading\nlangchain.evaluation.parsing.base\nlangchain.evaluation.parsing.json_distance\nlangchain.evaluation.parsing.json_schema\nlangchain.evaluation.qa.eval_chain\nlangchain.evaluation.qa.generate_chain", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-10", "text": "langchain.evaluation.qa.eval_chain\nlangchain.evaluation.qa.generate_chain\nlangchain.evaluation.regex_match.base\nlangchain.evaluation.schema\nlangchain.evaluation.scoring.eval_chain\nlangchain.evaluation.string_distance.base\nlangchain.graphs.arangodb_graph\nlangchain.graphs.falkordb_graph\nlangchain.graphs.graph_document\nlangchain.graphs.graph_store\nlangchain.graphs.hugegraph\nlangchain.graphs.kuzu_graph\nlangchain.graphs.memgraph_graph\nlangchain.graphs.nebula_graph\nlangchain.graphs.neo4j_graph\nlangchain.graphs.neptune_graph\nlangchain.graphs.networkx_graph\nlangchain.graphs.rdf_graph\nlangchain.hub\nlangchain.indexes.base\nlangchain.indexes.graph\nlangchain.indexes.vectorstore\nlangchain.llms.ai21\nlangchain.llms.aleph_alpha\nlangchain.llms.amazon_api_gateway\nlangchain.llms.anthropic\nlangchain.llms.anyscale\nlangchain.llms.arcee\nlangchain.llms.aviary\nlangchain.llms.azureml_endpoint\nlangchain.llms.baidu_qianfan_endpoint\nlangchain.llms.bananadev\nlangchain.llms.base\nlangchain.llms.baseten\nlangchain.llms.beam\nlangchain.llms.bedrock\nlangchain.llms.bittensor\nlangchain.llms.cerebriumai\nlangchain.llms.chatglm\nlangchain.llms.clarifai\nlangchain.llms.cohere\nlangchain.llms.ctransformers\nlangchain.llms.ctranslate2\nlangchain.llms.databricks\nlangchain.llms.deepinfra\nlangchain.llms.deepsparse\nlangchain.llms.edenai\nlangchain.llms.fake\nlangchain.llms.fireworks\nlangchain.llms.forefrontai\nlangchain.llms.gigachat", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-11", "text": "langchain.llms.forefrontai\nlangchain.llms.gigachat\nlangchain.llms.google_palm\nlangchain.llms.gooseai\nlangchain.llms.gpt4all\nlangchain.llms.gradient_ai\nlangchain.llms.huggingface_endpoint\nlangchain.llms.huggingface_hub\nlangchain.llms.huggingface_pipeline\nlangchain.llms.huggingface_text_gen_inference\nlangchain.llms.human\nlangchain.llms.javelin_ai_gateway\nlangchain.llms.koboldai\nlangchain.llms.llamacpp\nlangchain.llms.loading\nlangchain.llms.manifest\nlangchain.llms.minimax\nlangchain.llms.mlflow_ai_gateway\nlangchain.llms.modal\nlangchain.llms.mosaicml\nlangchain.llms.nlpcloud\nlangchain.llms.octoai_endpoint\nlangchain.llms.ollama\nlangchain.llms.opaqueprompts\nlangchain.llms.openai\nlangchain.llms.openllm\nlangchain.llms.openlm\nlangchain.llms.pai_eas_endpoint\nlangchain.llms.petals\nlangchain.llms.pipelineai\nlangchain.llms.predibase\nlangchain.llms.predictionguard\nlangchain.llms.promptlayer_openai\nlangchain.llms.replicate\nlangchain.llms.rwkv\nlangchain.llms.sagemaker_endpoint\nlangchain.llms.self_hosted\nlangchain.llms.self_hosted_hugging_face\nlangchain.llms.stochasticai\nlangchain.llms.symblai_nebula\nlangchain.llms.textgen\nlangchain.llms.titan_takeoff\nlangchain.llms.titan_takeoff_pro\nlangchain.llms.together\nlangchain.llms.tongyi\nlangchain.llms.utils\nlangchain.llms.vertexai\nlangchain.llms.vllm\nlangchain.llms.writer", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-12", "text": "langchain.llms.vllm\nlangchain.llms.writer\nlangchain.llms.xinference\nlangchain.llms.yandex\nlangchain.load.dump\nlangchain.load.load\nlangchain.load.serializable\nlangchain.memory.buffer\nlangchain.memory.buffer_window\nlangchain.memory.chat_memory\nlangchain.memory.chat_message_histories.cassandra\nlangchain.memory.chat_message_histories.cosmos_db\nlangchain.memory.chat_message_histories.dynamodb\nlangchain.memory.chat_message_histories.elasticsearch\nlangchain.memory.chat_message_histories.file\nlangchain.memory.chat_message_histories.firestore\nlangchain.memory.chat_message_histories.in_memory\nlangchain.memory.chat_message_histories.momento\nlangchain.memory.chat_message_histories.mongodb\nlangchain.memory.chat_message_histories.neo4j\nlangchain.memory.chat_message_histories.postgres\nlangchain.memory.chat_message_histories.redis\nlangchain.memory.chat_message_histories.rocksetdb\nlangchain.memory.chat_message_histories.singlestoredb\nlangchain.memory.chat_message_histories.sql\nlangchain.memory.chat_message_histories.streamlit\nlangchain.memory.chat_message_histories.upstash_redis\nlangchain.memory.chat_message_histories.xata\nlangchain.memory.chat_message_histories.zep\nlangchain.memory.combined\nlangchain.memory.entity\nlangchain.memory.kg\nlangchain.memory.motorhead_memory\nlangchain.memory.readonly\nlangchain.memory.simple\nlangchain.memory.summary\nlangchain.memory.summary_buffer\nlangchain.memory.token_buffer\nlangchain.memory.utils\nlangchain.memory.vectorstore\nlangchain.memory.zep_memory\nlangchain.model_laboratory\nlangchain.output_parsers.boolean\nlangchain.output_parsers.combining\nlangchain.output_parsers.datetime\nlangchain.output_parsers.enum\nlangchain.output_parsers.fix\nlangchain.output_parsers.json\nlangchain.output_parsers.list\nlangchain.output_parsers.loading\nlangchain.output_parsers.openai_functions", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-13", "text": "langchain.output_parsers.loading\nlangchain.output_parsers.openai_functions\nlangchain.output_parsers.openai_tools\nlangchain.output_parsers.pydantic\nlangchain.output_parsers.rail_parser\nlangchain.output_parsers.regex\nlangchain.output_parsers.regex_dict\nlangchain.output_parsers.retry\nlangchain.output_parsers.structured\nlangchain.output_parsers.xml\nlangchain.prompts.base\nlangchain.prompts.chat\nlangchain.prompts.example_selector.base\nlangchain.prompts.example_selector.length_based\nlangchain.prompts.example_selector.ngram_overlap\nlangchain.prompts.example_selector.semantic_similarity\nlangchain.prompts.few_shot\nlangchain.prompts.few_shot_with_templates\nlangchain.prompts.loading\nlangchain.prompts.pipeline\nlangchain.prompts.prompt\nlangchain.retrievers.arcee\nlangchain.retrievers.arxiv\nlangchain.retrievers.azure_cognitive_search\nlangchain.retrievers.bm25\nlangchain.retrievers.chaindesk\nlangchain.retrievers.chatgpt_plugin_retriever\nlangchain.retrievers.cohere_rag_retriever\nlangchain.retrievers.contextual_compression\nlangchain.retrievers.databerry\nlangchain.retrievers.docarray\nlangchain.retrievers.document_compressors.base\nlangchain.retrievers.document_compressors.chain_extract\nlangchain.retrievers.document_compressors.chain_filter\nlangchain.retrievers.document_compressors.cohere_rerank\nlangchain.retrievers.document_compressors.embeddings_filter\nlangchain.retrievers.elastic_search_bm25\nlangchain.retrievers.ensemble\nlangchain.retrievers.google_cloud_documentai_warehouse\nlangchain.retrievers.google_vertex_ai_search\nlangchain.retrievers.kay\nlangchain.retrievers.kendra\nlangchain.retrievers.knn\nlangchain.retrievers.llama_index", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-14", "text": "langchain.retrievers.knn\nlangchain.retrievers.llama_index\nlangchain.retrievers.merger_retriever\nlangchain.retrievers.metal\nlangchain.retrievers.milvus\nlangchain.retrievers.multi_query\nlangchain.retrievers.multi_vector\nlangchain.retrievers.parent_document_retriever\nlangchain.retrievers.pinecone_hybrid_search\nlangchain.retrievers.pubmed\nlangchain.retrievers.re_phraser\nlangchain.retrievers.remote_retriever\nlangchain.retrievers.self_query.base\nlangchain.retrievers.self_query.chroma\nlangchain.retrievers.self_query.dashvector\nlangchain.retrievers.self_query.deeplake\nlangchain.retrievers.self_query.elasticsearch\nlangchain.retrievers.self_query.milvus\nlangchain.retrievers.self_query.myscale\nlangchain.retrievers.self_query.opensearch\nlangchain.retrievers.self_query.pinecone\nlangchain.retrievers.self_query.qdrant\nlangchain.retrievers.self_query.redis\nlangchain.retrievers.self_query.supabase\nlangchain.retrievers.self_query.timescalevector\nlangchain.retrievers.self_query.vectara\nlangchain.retrievers.self_query.weaviate\nlangchain.retrievers.svm\nlangchain.retrievers.tavily_search_api\nlangchain.retrievers.tfidf\nlangchain.retrievers.time_weighted_retriever\nlangchain.retrievers.vespa_retriever\nlangchain.retrievers.weaviate_hybrid_search\nlangchain.retrievers.web_research\nlangchain.retrievers.wikipedia\nlangchain.retrievers.you\nlangchain.retrievers.zep\nlangchain.retrievers.zilliz\nlangchain.runnables.hub\nlangchain.runnables.openai_functions\nlangchain.schema.agent", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-15", "text": "langchain.runnables.openai_functions\nlangchain.schema.agent\nlangchain.schema.cache\nlangchain.schema.callbacks.base\nlangchain.schema.callbacks.manager\nlangchain.schema.callbacks.stdout\nlangchain.schema.callbacks.tracers.base\nlangchain.schema.callbacks.tracers.evaluation\nlangchain.schema.callbacks.tracers.langchain\nlangchain.schema.callbacks.tracers.langchain_v1\nlangchain.schema.callbacks.tracers.log_stream\nlangchain.schema.callbacks.tracers.root_listeners\nlangchain.schema.callbacks.tracers.run_collector\nlangchain.schema.callbacks.tracers.schemas\nlangchain.schema.callbacks.tracers.stdout\nlangchain.schema.chat\nlangchain.schema.chat_history\nlangchain.schema.document\nlangchain.schema.embeddings\nlangchain.schema.exceptions\nlangchain.schema.language_model\nlangchain.schema.memory\nlangchain.schema.messages\nlangchain.schema.output\nlangchain.schema.output_parser\nlangchain.schema.prompt\nlangchain.schema.prompt_template\nlangchain.schema.retriever\nlangchain.schema.runnable.base\nlangchain.schema.runnable.branch\nlangchain.schema.runnable.config\nlangchain.schema.runnable.configurable\nlangchain.schema.runnable.fallbacks\nlangchain.schema.runnable.history\nlangchain.schema.runnable.passthrough\nlangchain.schema.runnable.retry\nlangchain.schema.runnable.router\nlangchain.schema.runnable.utils\nlangchain.schema.storage\nlangchain.schema.vectorstore\nlangchain.smith.evaluation.config\nlangchain.smith.evaluation.name_generation\nlangchain.smith.evaluation.progress\nlangchain.smith.evaluation.runner_utils\nlangchain.smith.evaluation.string_run_evaluator\nlangchain.storage.encoder_backed\nlangchain.storage.exceptions\nlangchain.storage.file_system\nlangchain.storage.in_memory\nlangchain.storage.redis\nlangchain.storage.upstash_redis\nlangchain.text_splitter\nlangchain.tools.ainetwork.app\nlangchain.tools.ainetwork.base\nlangchain.tools.ainetwork.owner\nlangchain.tools.ainetwork.rule", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-16", "text": "langchain.tools.ainetwork.owner\nlangchain.tools.ainetwork.rule\nlangchain.tools.ainetwork.transfer\nlangchain.tools.ainetwork.utils\nlangchain.tools.ainetwork.value\nlangchain.tools.amadeus.base\nlangchain.tools.amadeus.closest_airport\nlangchain.tools.amadeus.flight_search\nlangchain.tools.amadeus.utils\nlangchain.tools.arxiv.tool\nlangchain.tools.azure_cognitive_services.form_recognizer\nlangchain.tools.azure_cognitive_services.image_analysis\nlangchain.tools.azure_cognitive_services.speech2text\nlangchain.tools.azure_cognitive_services.text2speech\nlangchain.tools.azure_cognitive_services.utils\nlangchain.tools.base\nlangchain.tools.bearly.tool\nlangchain.tools.bing_search.tool\nlangchain.tools.brave_search.tool\nlangchain.tools.clickup.tool\nlangchain.tools.dataforseo_api_search.tool\nlangchain.tools.ddg_search.tool\nlangchain.tools.e2b_data_analysis.tool\nlangchain.tools.e2b_data_analysis.unparse\nlangchain.tools.edenai.audio_speech_to_text\nlangchain.tools.edenai.audio_text_to_speech\nlangchain.tools.edenai.edenai_base_tool\nlangchain.tools.edenai.image_explicitcontent\nlangchain.tools.edenai.image_objectdetection\nlangchain.tools.edenai.ocr_identityparser\nlangchain.tools.edenai.ocr_invoiceparser\nlangchain.tools.edenai.text_moderation\nlangchain.tools.eleven_labs.models\nlangchain.tools.eleven_labs.text2speech\nlangchain.tools.file_management.copy\nlangchain.tools.file_management.delete\nlangchain.tools.file_management.file_search\nlangchain.tools.file_management.list_dir\nlangchain.tools.file_management.move\nlangchain.tools.file_management.read\nlangchain.tools.file_management.utils\nlangchain.tools.file_management.write\nlangchain.tools.github.tool\nlangchain.tools.gitlab.tool", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-17", "text": "langchain.tools.file_management.write\nlangchain.tools.github.tool\nlangchain.tools.gitlab.tool\nlangchain.tools.gmail.base\nlangchain.tools.gmail.create_draft\nlangchain.tools.gmail.get_message\nlangchain.tools.gmail.get_thread\nlangchain.tools.gmail.search\nlangchain.tools.gmail.send_message\nlangchain.tools.gmail.utils\nlangchain.tools.golden_query.tool\nlangchain.tools.google_cloud.texttospeech\nlangchain.tools.google_places.tool\nlangchain.tools.google_scholar.tool\nlangchain.tools.google_search.tool\nlangchain.tools.google_serper.tool\nlangchain.tools.graphql.tool\nlangchain.tools.human.tool\nlangchain.tools.ifttt\nlangchain.tools.interaction.tool\nlangchain.tools.jira.tool\nlangchain.tools.json.tool\nlangchain.tools.memorize.tool\nlangchain.tools.metaphor_search.tool\nlangchain.tools.multion.close_session\nlangchain.tools.multion.create_session\nlangchain.tools.multion.update_session\nlangchain.tools.nuclia.tool\nlangchain.tools.office365.base\nlangchain.tools.office365.create_draft_message\nlangchain.tools.office365.events_search\nlangchain.tools.office365.messages_search\nlangchain.tools.office365.send_event\nlangchain.tools.office365.send_message\nlangchain.tools.office365.utils\nlangchain.tools.openapi.utils.api_models\nlangchain.tools.openweathermap.tool\nlangchain.tools.playwright.base\nlangchain.tools.playwright.click\nlangchain.tools.playwright.current_page\nlangchain.tools.playwright.extract_hyperlinks\nlangchain.tools.playwright.extract_text\nlangchain.tools.playwright.get_elements\nlangchain.tools.playwright.navigate\nlangchain.tools.playwright.navigate_back\nlangchain.tools.playwright.utils\nlangchain.tools.plugin\nlangchain.tools.powerbi.tool\nlangchain.tools.pubmed.tool\nlangchain.tools.render\nlangchain.tools.requests.tool\nlangchain.tools.retriever\nlangchain.tools.scenexplain.tool\nlangchain.tools.searchapi.tool", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-18", "text": "langchain.tools.scenexplain.tool\nlangchain.tools.searchapi.tool\nlangchain.tools.searx_search.tool\nlangchain.tools.shell.tool\nlangchain.tools.sleep.tool\nlangchain.tools.spark_sql.tool\nlangchain.tools.sql_database.tool\nlangchain.tools.steamship_image_generation.tool\nlangchain.tools.steamship_image_generation.utils\nlangchain.tools.tavily_search.tool\nlangchain.tools.vectorstore.tool\nlangchain.tools.wikipedia.tool\nlangchain.tools.wolfram_alpha.tool\nlangchain.tools.yahoo_finance_news\nlangchain.tools.youtube.search\nlangchain.tools.zapier.tool\nlangchain.utilities.alpha_vantage\nlangchain.utilities.anthropic\nlangchain.utilities.apify\nlangchain.utilities.arcee\nlangchain.utilities.arxiv\nlangchain.utilities.awslambda\nlangchain.utilities.bibtex\nlangchain.utilities.bing_search\nlangchain.utilities.brave_search\nlangchain.utilities.clickup\nlangchain.utilities.dalle_image_generator\nlangchain.utilities.dataforseo_api_search\nlangchain.utilities.duckduckgo_search\nlangchain.utilities.github\nlangchain.utilities.gitlab\nlangchain.utilities.golden_query\nlangchain.utilities.google_places_api\nlangchain.utilities.google_scholar\nlangchain.utilities.google_search\nlangchain.utilities.google_serper\nlangchain.utilities.graphql\nlangchain.utilities.jira\nlangchain.utilities.max_compute\nlangchain.utilities.metaphor_search\nlangchain.utilities.opaqueprompts\nlangchain.utilities.openapi\nlangchain.utilities.openweathermap\nlangchain.utilities.portkey\nlangchain.utilities.powerbi\nlangchain.utilities.pubmed\nlangchain.utilities.python\nlangchain.utilities.redis\nlangchain.utilities.requests\nlangchain.utilities.scenexplain\nlangchain.utilities.searchapi\nlangchain.utilities.searx_search\nlangchain.utilities.serpapi\nlangchain.utilities.spark_sql\nlangchain.utilities.sql_database\nlangchain.utilities.tavily_search\nlangchain.utilities.tensorflow_datasets\nlangchain.utilities.twilio", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-19", "text": "langchain.utilities.tensorflow_datasets\nlangchain.utilities.twilio\nlangchain.utilities.vertexai\nlangchain.utilities.wikipedia\nlangchain.utilities.wolfram_alpha\nlangchain.utilities.zapier\nlangchain.utils.aiter\nlangchain.utils.env\nlangchain.utils.formatting\nlangchain.utils.html\nlangchain.utils.input\nlangchain.utils.iter\nlangchain.utils.json_schema\nlangchain.utils.loading\nlangchain.utils.math\nlangchain.utils.openai\nlangchain.utils.openai_functions\nlangchain.utils.pydantic\nlangchain.utils.strings\nlangchain.utils.utils\nlangchain.vectorstores.alibabacloud_opensearch\nlangchain.vectorstores.analyticdb\nlangchain.vectorstores.annoy\nlangchain.vectorstores.astradb\nlangchain.vectorstores.atlas\nlangchain.vectorstores.awadb\nlangchain.vectorstores.azure_cosmos_db\nlangchain.vectorstores.azuresearch\nlangchain.vectorstores.bageldb\nlangchain.vectorstores.baiducloud_vector_search\nlangchain.vectorstores.cassandra\nlangchain.vectorstores.chroma\nlangchain.vectorstores.clarifai\nlangchain.vectorstores.clickhouse\nlangchain.vectorstores.dashvector\nlangchain.vectorstores.deeplake\nlangchain.vectorstores.dingo\nlangchain.vectorstores.docarray.base\nlangchain.vectorstores.docarray.hnsw\nlangchain.vectorstores.docarray.in_memory\nlangchain.vectorstores.elastic_vector_search\nlangchain.vectorstores.elasticsearch\nlangchain.vectorstores.epsilla\nlangchain.vectorstores.faiss\nlangchain.vectorstores.hippo\nlangchain.vectorstores.hologres\nlangchain.vectorstores.lancedb\nlangchain.vectorstores.llm_rails\nlangchain.vectorstores.marqo\nlangchain.vectorstores.matching_engine\nlangchain.vectorstores.meilisearch\nlangchain.vectorstores.milvus\nlangchain.vectorstores.momento_vector_index\nlangchain.vectorstores.mongodb_atlas", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-20", "text": "langchain.vectorstores.momento_vector_index\nlangchain.vectorstores.mongodb_atlas\nlangchain.vectorstores.myscale\nlangchain.vectorstores.neo4j_vector\nlangchain.vectorstores.nucliadb\nlangchain.vectorstores.opensearch_vector_search\nlangchain.vectorstores.pgembedding\nlangchain.vectorstores.pgvecto_rs\nlangchain.vectorstores.pgvector\nlangchain.vectorstores.pinecone\nlangchain.vectorstores.qdrant\nlangchain.vectorstores.redis.base\nlangchain.vectorstores.redis.filters\nlangchain.vectorstores.redis.schema\nlangchain.vectorstores.rocksetdb\nlangchain.vectorstores.scann\nlangchain.vectorstores.semadb\nlangchain.vectorstores.singlestoredb\nlangchain.vectorstores.sklearn\nlangchain.vectorstores.sqlitevss\nlangchain.vectorstores.starrocks\nlangchain.vectorstores.supabase\nlangchain.vectorstores.tair\nlangchain.vectorstores.tencentvectordb\nlangchain.vectorstores.tigris\nlangchain.vectorstores.tiledb\nlangchain.vectorstores.timescalevector\nlangchain.vectorstores.typesense\nlangchain.vectorstores.usearch\nlangchain.vectorstores.utils\nlangchain.vectorstores.vald\nlangchain.vectorstores.vearch\nlangchain.vectorstores.vectara\nlangchain.vectorstores.vespa\nlangchain.vectorstores.weaviate\nlangchain.vectorstores.xata\nlangchain.vectorstores.zep\nlangchain.vectorstores.zilliz\nlangchain_experimental.agents.agent_toolkits.csv.base\nlangchain_experimental.agents.agent_toolkits.pandas.base\nlangchain_experimental.agents.agent_toolkits.python.base\nlangchain_experimental.agents.agent_toolkits.spark.base\nlangchain_experimental.agents.agent_toolkits.xorbits.base\nlangchain_experimental.autonomous_agents.autogpt.agent\nlangchain_experimental.autonomous_agents.autogpt.memory\nlangchain_experimental.autonomous_agents.autogpt.output_parser", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-21", "text": "langchain_experimental.autonomous_agents.autogpt.output_parser\nlangchain_experimental.autonomous_agents.autogpt.prompt\nlangchain_experimental.autonomous_agents.autogpt.prompt_generator\nlangchain_experimental.autonomous_agents.baby_agi.baby_agi\nlangchain_experimental.autonomous_agents.baby_agi.task_creation\nlangchain_experimental.autonomous_agents.baby_agi.task_execution\nlangchain_experimental.autonomous_agents.baby_agi.task_prioritization\nlangchain_experimental.autonomous_agents.hugginggpt.hugginggpt\nlangchain_experimental.autonomous_agents.hugginggpt.repsonse_generator\nlangchain_experimental.autonomous_agents.hugginggpt.task_executor\nlangchain_experimental.autonomous_agents.hugginggpt.task_planner\nlangchain_experimental.chat_models.llm_wrapper\nlangchain_experimental.comprehend_moderation.amazon_comprehend_moderation\nlangchain_experimental.comprehend_moderation.base_moderation\nlangchain_experimental.comprehend_moderation.base_moderation_callbacks\nlangchain_experimental.comprehend_moderation.base_moderation_config\nlangchain_experimental.comprehend_moderation.base_moderation_exceptions\nlangchain_experimental.comprehend_moderation.pii\nlangchain_experimental.comprehend_moderation.prompt_safety\nlangchain_experimental.comprehend_moderation.toxicity\nlangchain_experimental.cpal.base\nlangchain_experimental.cpal.constants\nlangchain_experimental.cpal.models\nlangchain_experimental.fallacy_removal.base\nlangchain_experimental.fallacy_removal.models\nlangchain_experimental.generative_agents.generative_agent\nlangchain_experimental.generative_agents.memory\nlangchain_experimental.graph_transformers.diffbot\nlangchain_experimental.llm_bash.base\nlangchain_experimental.llm_bash.bash\nlangchain_experimental.llm_bash.prompt", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "95552857791c-22", "text": "langchain_experimental.llm_bash.prompt\nlangchain_experimental.llm_symbolic_math.base\nlangchain_experimental.llms.anthropic_functions\nlangchain_experimental.llms.jsonformer_decoder\nlangchain_experimental.llms.llamaapi\nlangchain_experimental.llms.lmformatenforcer_decoder\nlangchain_experimental.llms.rellm_decoder\nlangchain_experimental.open_clip.open_clip\nlangchain_experimental.pal_chain.base\nlangchain_experimental.plan_and_execute.agent_executor\nlangchain_experimental.plan_and_execute.executors.agent_executor\nlangchain_experimental.plan_and_execute.executors.base\nlangchain_experimental.plan_and_execute.planners.base\nlangchain_experimental.plan_and_execute.planners.chat_planner\nlangchain_experimental.plan_and_execute.schema\nlangchain_experimental.prompt_injection_identifier.hugging_face_identifier\nlangchain_experimental.retrievers.vector_sql_database\nlangchain_experimental.rl_chain.base\nlangchain_experimental.rl_chain.metrics\nlangchain_experimental.rl_chain.model_repository\nlangchain_experimental.rl_chain.pick_best_chain\nlangchain_experimental.rl_chain.vw_logger\nlangchain_experimental.smart_llm.base\nlangchain_experimental.sql.base\nlangchain_experimental.sql.vector_sql\nlangchain_experimental.tabular_synthetic_data.base\nlangchain_experimental.tabular_synthetic_data.openai\nlangchain_experimental.tools.python.tool\nlangchain_experimental.tot.base\nlangchain_experimental.tot.checker\nlangchain_experimental.tot.controller\nlangchain_experimental.tot.memory\nlangchain_experimental.tot.prompts\nlangchain_experimental.tot.thought\nlangchain_experimental.tot.thought_generation\nlangchain_experimental.utilities.python\npydantic.fields\npydantic.main\nsqlalchemy.orm.decl_base\nsqlalchemy.orm.instrumentation\nstring\ntyping", "source": "lang/api.python.langchain.com/en/latest/_modules/index.html"}
{"id": "a5972cc239fa-0", "text": "Source code for sqlalchemy.orm.decl_base\n# ext/declarative/base.py\n# Copyright (C) 2005-2023 the SQLAlchemy authors and contributors\n# <see AUTHORS file>\n#\n# This module is part of SQLAlchemy and is released under\n# the MIT License: https://www.opensource.org/licenses/mit-license.php\n\"\"\"Internal implementation for declarative.\"\"\"\nfrom __future__ import annotations\nimport collections\nimport dataclasses\nimport re\nfrom typing import Any\nfrom typing import Callable\nfrom typing import cast\nfrom typing import Dict\nfrom typing import Iterable\nfrom typing import List\nfrom typing import Mapping\nfrom typing import NamedTuple\nfrom typing import NoReturn\nfrom typing import Optional\nfrom typing import Sequence\nfrom typing import Tuple\nfrom typing import Type\nfrom typing import TYPE_CHECKING\nfrom typing import TypeVar\nfrom typing import Union\nimport weakref\nfrom . import attributes\nfrom . import clsregistry\nfrom . import exc as orm_exc\nfrom . import instrumentation\nfrom . import mapperlib\nfrom ._typing import _O\nfrom ._typing import attr_is_internal_proxy\nfrom .attributes import InstrumentedAttribute\nfrom .attributes import QueryableAttribute\nfrom .base import _is_mapped_class\nfrom .base import InspectionAttr\nfrom .descriptor_props import CompositeProperty\nfrom .descriptor_props import SynonymProperty\nfrom .interfaces import _AttributeOptions\nfrom .interfaces import _DCAttributeOptions\nfrom .interfaces import _IntrospectsAnnotations\nfrom .interfaces import _MappedAttribute\nfrom .interfaces import _MapsColumns\nfrom .interfaces import MapperProperty\nfrom .mapper import Mapper\nfrom .properties import ColumnProperty\nfrom .properties import MappedColumn\nfrom .util import _extract_mapped_subtype\nfrom .util import _is_mapped_annotation\nfrom .util import class_mapper\nfrom .util import de_stringify_annotation\nfrom .. import event\nfrom .. import exc\nfrom .. import util", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-1", "text": "from .. import event\nfrom .. import exc\nfrom .. import util\nfrom ..sql import expression\nfrom ..sql.base import _NoArg\nfrom ..sql.schema import Column\nfrom ..sql.schema import Table\nfrom ..util import topological\nfrom ..util.typing import _AnnotationScanType\nfrom ..util.typing import is_fwd_ref\nfrom ..util.typing import is_literal\nfrom ..util.typing import Protocol\nfrom ..util.typing import TypedDict\nfrom ..util.typing import typing_get_args\nif TYPE_CHECKING:\n    from ._typing import _ClassDict\n    from ._typing import _RegistryType\n    from .base import Mapped\n    from .decl_api import declared_attr\n    from .instrumentation import ClassManager\n    from ..sql.elements import NamedColumn\n    from ..sql.schema import MetaData\n    from ..sql.selectable import FromClause\n_T = TypeVar(\"_T\", bound=Any)\n_MapperKwArgs = Mapping[str, Any]\n_TableArgsType = Union[Tuple[Any, ...], Dict[str, Any]]\nclass MappedClassProtocol(Protocol[_O]):\n    \"\"\"A protocol representing a SQLAlchemy mapped class.\n    The protocol is generic on the type of class, use\n    ``MappedClassProtocol[Any]`` to allow any mapped class.\n    \"\"\"\n    __name__: str\n    __mapper__: Mapper[_O]\n    __table__: FromClause\n    def __call__(self, **kw: Any) -> _O:\n        ...\nclass _DeclMappedClassProtocol(MappedClassProtocol[_O], Protocol):\n    \"Internal more detailed version of ``MappedClassProtocol``.\"\n    metadata: MetaData\n    __tablename__: str\n    __mapper_args__: _MapperKwArgs\n    __table_args__: Optional[_TableArgsType]", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-2", "text": "__table_args__: Optional[_TableArgsType]\n    _sa_apply_dc_transforms: Optional[_DataclassArguments]\n    def __declare_first__(self) -> None:\n        ...\n    def __declare_last__(self) -> None:\n        ...\nclass _DataclassArguments(TypedDict):\n    init: Union[_NoArg, bool]\n    repr: Union[_NoArg, bool]\n    eq: Union[_NoArg, bool]\n    order: Union[_NoArg, bool]\n    unsafe_hash: Union[_NoArg, bool]\n    match_args: Union[_NoArg, bool]\n    kw_only: Union[_NoArg, bool]\n    dataclass_callable: Union[_NoArg, Callable[..., Type[Any]]]\ndef _declared_mapping_info(\n    cls: Type[Any],\n) -> Optional[Union[_DeferredMapperConfig, Mapper[Any]]]:\n    # deferred mapping\n    if _DeferredMapperConfig.has_cls(cls):\n        return _DeferredMapperConfig.config_for_cls(cls)\n    # regular mapping\n    elif _is_mapped_class(cls):\n        return class_mapper(cls, configure=False)\n    else:\n        return None\ndef _is_supercls_for_inherits(cls: Type[Any]) -> bool:\n    \"\"\"return True if this class will be used as a superclass to set in\n    'inherits'.\n    This includes deferred mapper configs that aren't mapped yet, however does\n    not include classes with _sa_decl_prepare_nocascade (e.g.\n    ``AbstractConcreteBase``); these concrete-only classes are not set up as\n    \"inherits\" until after mappers are configured using\n    mapper._set_concrete_base()\n    \"\"\"\n    if _DeferredMapperConfig.has_cls(cls):\n        return not _get_immediate_cls_attr(", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-3", "text": "return not _get_immediate_cls_attr(\n            cls, \"_sa_decl_prepare_nocascade\", strict=True\n        )\n    # regular mapping\n    elif _is_mapped_class(cls):\n        return True\n    else:\n        return False\ndef _resolve_for_abstract_or_classical(cls: Type[Any]) -> Optional[Type[Any]]:\n    if cls is object:\n        return None\n    sup: Optional[Type[Any]]\n    if cls.__dict__.get(\"__abstract__\", False):\n        for base_ in cls.__bases__:\n            sup = _resolve_for_abstract_or_classical(base_)\n            if sup is not None:\n                return sup\n        else:\n            return None\n    else:\n        clsmanager = _dive_for_cls_manager(cls)\n        if clsmanager:\n            return clsmanager.class_\n        else:\n            return cls\ndef _get_immediate_cls_attr(\n    cls: Type[Any], attrname: str, strict: bool = False\n) -> Optional[Any]:\n    \"\"\"return an attribute of the class that is either present directly\n    on the class, e.g. not on a superclass, or is from a superclass but\n    this superclass is a non-mapped mixin, that is, not a descendant of\n    the declarative base and is also not classically mapped.\n    This is used to detect attributes that indicate something about\n    a mapped class independently from any mapped classes that it may\n    inherit from.\n    \"\"\"\n    # the rules are different for this name than others,\n    # make sure we've moved it out.  transitional\n    assert attrname != \"__abstract__\"\n    if not issubclass(cls, object):\n        return None\n    if attrname in cls.__dict__:\n        return getattr(cls, attrname)", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-4", "text": "if attrname in cls.__dict__:\n        return getattr(cls, attrname)\n    for base in cls.__mro__[1:]:\n        _is_classical_inherits = _dive_for_cls_manager(base) is not None\n        if attrname in base.__dict__ and (\n            base is cls\n            or (\n                (base in cls.__bases__ if strict else True)\n                and not _is_classical_inherits\n            )\n        ):\n            return getattr(base, attrname)\n    else:\n        return None\ndef _dive_for_cls_manager(cls: Type[_O]) -> Optional[ClassManager[_O]]:\n    # because the class manager registration is pluggable,\n    # we need to do the search for every class in the hierarchy,\n    # rather than just a simple \"cls._sa_class_manager\"\n    for base in cls.__mro__:\n        manager: Optional[ClassManager[_O]] = attributes.opt_manager_of_class(\n            base\n        )\n        if manager:\n            return manager\n    return None\ndef _as_declarative(\n    registry: _RegistryType, cls: Type[Any], dict_: _ClassDict\n) -> Optional[_MapperConfig]:\n    # declarative scans the class for attributes.  no table or mapper\n    # args passed separately.\n    return _MapperConfig.setup_mapping(registry, cls, dict_, None, {})\ndef _mapper(\n    registry: _RegistryType,\n    cls: Type[_O],\n    table: Optional[FromClause],\n    mapper_kw: _MapperKwArgs,\n) -> Mapper[_O]:\n    _ImperativeMapperConfig(registry, cls, table, mapper_kw)\n    return cast(\"MappedClassProtocol[_O]\", cls).__mapper__", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-5", "text": "return cast(\"MappedClassProtocol[_O]\", cls).__mapper__\n@util.preload_module(\"sqlalchemy.orm.decl_api\")\ndef _is_declarative_props(obj: Any) -> bool:\n    _declared_attr_common = util.preloaded.orm_decl_api._declared_attr_common\n    return isinstance(obj, (_declared_attr_common, util.classproperty))\ndef _check_declared_props_nocascade(\n    obj: Any, name: str, cls: Type[_O]\n) -> bool:\n    if _is_declarative_props(obj):\n        if getattr(obj, \"_cascading\", False):\n            util.warn(\n                \"@declared_attr.cascading is not supported on the %s \"\n                \"attribute on class %s.  This attribute invokes for \"\n                \"subclasses in any case.\" % (name, cls)\n            )\n        return True\n    else:\n        return False\nclass _MapperConfig:\n    __slots__ = (\n        \"cls\",\n        \"classname\",\n        \"properties\",\n        \"declared_attr_reg\",\n        \"__weakref__\",\n    )\n    cls: Type[Any]\n    classname: str\n    properties: util.OrderedDict[\n        str,\n        Union[\n            Sequence[NamedColumn[Any]], NamedColumn[Any], MapperProperty[Any]\n        ],\n    ]\n    declared_attr_reg: Dict[declared_attr[Any], Any]\n    @classmethod\n    def setup_mapping(\n        cls,\n        registry: _RegistryType,\n        cls_: Type[_O],\n        dict_: _ClassDict,\n        table: Optional[FromClause],\n        mapper_kw: _MapperKwArgs,\n    ) -> Optional[_MapperConfig]:\n        manager = attributes.opt_manager_of_class(cls)", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-6", "text": ") -> Optional[_MapperConfig]:\n        manager = attributes.opt_manager_of_class(cls)\n        if manager and manager.class_ is cls_:\n            raise exc.InvalidRequestError(\n                f\"Class {cls!r} already has been instrumented declaratively\"\n            )\n        if cls_.__dict__.get(\"__abstract__\", False):\n            return None\n        defer_map = _get_immediate_cls_attr(\n            cls_, \"_sa_decl_prepare_nocascade\", strict=True\n        ) or hasattr(cls_, \"_sa_decl_prepare\")\n        if defer_map:\n            return _DeferredMapperConfig(\n                registry, cls_, dict_, table, mapper_kw\n            )\n        else:\n            return _ClassScanMapperConfig(\n                registry, cls_, dict_, table, mapper_kw\n            )\n    def __init__(\n        self,\n        registry: _RegistryType,\n        cls_: Type[Any],\n        mapper_kw: _MapperKwArgs,\n    ):\n        self.cls = util.assert_arg_type(cls_, type, \"cls_\")\n        self.classname = cls_.__name__\n        self.properties = util.OrderedDict()\n        self.declared_attr_reg = {}\n        if not mapper_kw.get(\"non_primary\", False):\n            instrumentation.register_class(\n                self.cls,\n                finalize=False,\n                registry=registry,\n                declarative_scan=self,\n                init_method=registry.constructor,\n            )\n        else:\n            manager = attributes.opt_manager_of_class(self.cls)\n            if not manager or not manager.is_mapped:\n                raise exc.InvalidRequestError(\n                    \"Class %s has no primary mapper configured.  Configure \"\n                    \"a primary mapper first before setting up a non primary \"\n                    \"Mapper.\" % self.cls\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-7", "text": "\"Mapper.\" % self.cls\n                )\n    def set_cls_attribute(self, attrname: str, value: _T) -> _T:\n        manager = instrumentation.manager_of_class(self.cls)\n        manager.install_member(attrname, value)\n        return value\n    def map(self, mapper_kw: _MapperKwArgs = ...) -> Mapper[Any]:\n        raise NotImplementedError()\n    def _early_mapping(self, mapper_kw: _MapperKwArgs) -> None:\n        self.map(mapper_kw)\nclass _ImperativeMapperConfig(_MapperConfig):\n    __slots__ = (\"local_table\", \"inherits\")\n    def __init__(\n        self,\n        registry: _RegistryType,\n        cls_: Type[_O],\n        table: Optional[FromClause],\n        mapper_kw: _MapperKwArgs,\n    ):\n        super().__init__(registry, cls_, mapper_kw)\n        self.local_table = self.set_cls_attribute(\"__table__\", table)\n        with mapperlib._CONFIGURE_MUTEX:\n            if not mapper_kw.get(\"non_primary\", False):\n                clsregistry.add_class(\n                    self.classname, self.cls, registry._class_registry\n                )\n            self._setup_inheritance(mapper_kw)\n            self._early_mapping(mapper_kw)\n    def map(self, mapper_kw: _MapperKwArgs = util.EMPTY_DICT) -> Mapper[Any]:\n        mapper_cls = Mapper\n        return self.set_cls_attribute(\n            \"__mapper__\",\n            mapper_cls(self.cls, self.local_table, **mapper_kw),\n        )\n    def _setup_inheritance(self, mapper_kw: _MapperKwArgs) -> None:\n        cls = self.cls\n        inherits = mapper_kw.get(\"inherits\", None)\n        if inherits is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-8", "text": "inherits = mapper_kw.get(\"inherits\", None)\n        if inherits is None:\n            # since we search for classical mappings now, search for\n            # multiple mapped bases as well and raise an error.\n            inherits_search = []\n            for base_ in cls.__bases__:\n                c = _resolve_for_abstract_or_classical(base_)\n                if c is None:\n                    continue\n                if _is_supercls_for_inherits(c) and c not in inherits_search:\n                    inherits_search.append(c)\n            if inherits_search:\n                if len(inherits_search) > 1:\n                    raise exc.InvalidRequestError(\n                        \"Class %s has multiple mapped bases: %r\"\n                        % (cls, inherits_search)\n                    )\n                inherits = inherits_search[0]\n        elif isinstance(inherits, Mapper):\n            inherits = inherits.class_\n        self.inherits = inherits\nclass _CollectedAnnotation(NamedTuple):\n    raw_annotation: _AnnotationScanType\n    mapped_container: Optional[Type[Mapped[Any]]]\n    extracted_mapped_annotation: Union[Type[Any], str]\n    is_dataclass: bool\n    attr_value: Any\n    originating_module: str\n    originating_class: Type[Any]\nclass _ClassScanMapperConfig(_MapperConfig):\n    __slots__ = (\n        \"registry\",\n        \"clsdict_view\",\n        \"collected_attributes\",\n        \"collected_annotations\",\n        \"local_table\",\n        \"persist_selectable\",\n        \"declared_columns\",\n        \"column_ordering\",\n        \"column_copies\",\n        \"table_args\",\n        \"tablename\",\n        \"mapper_args\",\n        \"mapper_args_fn\",\n        \"inherits\",\n        \"single\",\n        \"allow_dataclass_fields\",\n        \"dataclass_setup_arguments\",", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-9", "text": "\"allow_dataclass_fields\",\n        \"dataclass_setup_arguments\",\n        \"is_dataclass_prior_to_mapping\",\n        \"allow_unmapped_annotations\",\n    )\n    is_deferred = False\n    registry: _RegistryType\n    clsdict_view: _ClassDict\n    collected_annotations: Dict[str, _CollectedAnnotation]\n    collected_attributes: Dict[str, Any]\n    local_table: Optional[FromClause]\n    persist_selectable: Optional[FromClause]\n    declared_columns: util.OrderedSet[Column[Any]]\n    column_ordering: Dict[Column[Any], int]\n    column_copies: Dict[\n        Union[MappedColumn[Any], Column[Any]],\n        Union[MappedColumn[Any], Column[Any]],\n    ]\n    tablename: Optional[str]\n    mapper_args: Mapping[str, Any]\n    table_args: Optional[_TableArgsType]\n    mapper_args_fn: Optional[Callable[[], Dict[str, Any]]]\n    inherits: Optional[Type[Any]]\n    single: bool\n    is_dataclass_prior_to_mapping: bool\n    allow_unmapped_annotations: bool\n    dataclass_setup_arguments: Optional[_DataclassArguments]\n    \"\"\"if the class has SQLAlchemy native dataclass parameters, where\n    we will turn the class into a dataclass within the declarative mapping\n    process.\n    \"\"\"\n    allow_dataclass_fields: bool\n    \"\"\"if true, look for dataclass-processed Field objects on the target\n    class as well as superclasses and extract ORM mapping directives from\n    the \"metadata\" attribute of each Field.\n    if False, dataclass fields can still be used, however they won't be\n    mapped.\n    \"\"\"\n    def __init__(\n        self,\n        registry: _RegistryType,\n        cls_: Type[_O],\n        dict_: _ClassDict,", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-10", "text": "cls_: Type[_O],\n        dict_: _ClassDict,\n        table: Optional[FromClause],\n        mapper_kw: _MapperKwArgs,\n    ):\n        # grab class dict before the instrumentation manager has been added.\n        # reduces cycles\n        self.clsdict_view = (\n            util.immutabledict(dict_) if dict_ else util.EMPTY_DICT\n        )\n        super().__init__(registry, cls_, mapper_kw)\n        self.registry = registry\n        self.persist_selectable = None\n        self.collected_attributes = {}\n        self.collected_annotations = {}\n        self.declared_columns = util.OrderedSet()\n        self.column_ordering = {}\n        self.column_copies = {}\n        self.single = False\n        self.dataclass_setup_arguments = dca = getattr(\n            self.cls, \"_sa_apply_dc_transforms\", None\n        )\n        self.allow_unmapped_annotations = getattr(\n            self.cls, \"__allow_unmapped__\", False\n        ) or bool(self.dataclass_setup_arguments)\n        self.is_dataclass_prior_to_mapping = cld = dataclasses.is_dataclass(\n            cls_\n        )\n        sdk = _get_immediate_cls_attr(cls_, \"__sa_dataclass_metadata_key__\")\n        # we don't want to consume Field objects from a not-already-dataclass.\n        # the Field objects won't have their \"name\" or \"type\" populated,\n        # and while it seems like we could just set these on Field as we\n        # read them, Field is documented as \"user read only\" and we need to\n        # stay far away from any off-label use of dataclasses APIs.\n        if (not cld or dca) and sdk:\n            raise exc.InvalidRequestError(\n                \"SQLAlchemy mapped dataclasses can't consume mapping \"", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-11", "text": "\"SQLAlchemy mapped dataclasses can't consume mapping \"\n                \"information from dataclass.Field() objects if the immediate \"\n                \"class is not already a dataclass.\"\n            )\n        # if already a dataclass, and __sa_dataclass_metadata_key__ present,\n        # then also look inside of dataclass.Field() objects yielded by\n        # dataclasses.get_fields(cls) when scanning for attributes\n        self.allow_dataclass_fields = bool(sdk and cld)\n        self._setup_declared_events()\n        self._scan_attributes()\n        self._setup_dataclasses_transforms()\n        with mapperlib._CONFIGURE_MUTEX:\n            clsregistry.add_class(\n                self.classname, self.cls, registry._class_registry\n            )\n            self._setup_inheriting_mapper(mapper_kw)\n            self._extract_mappable_attributes()\n            self._extract_declared_columns()\n            self._setup_table(table)\n            self._setup_inheriting_columns(mapper_kw)\n            self._early_mapping(mapper_kw)\n    def _setup_declared_events(self) -> None:\n        if _get_immediate_cls_attr(self.cls, \"__declare_last__\"):\n            @event.listens_for(Mapper, \"after_configured\")\n            def after_configured() -> None:\n                cast(\n                    \"_DeclMappedClassProtocol[Any]\", self.cls\n                ).__declare_last__()\n        if _get_immediate_cls_attr(self.cls, \"__declare_first__\"):\n            @event.listens_for(Mapper, \"before_configured\")\n            def before_configured() -> None:\n                cast(\n                    \"_DeclMappedClassProtocol[Any]\", self.cls\n                ).__declare_first__()\n    def _cls_attr_override_checker(\n        self, cls: Type[_O]\n    ) -> Callable[[str, Any], bool]:", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-12", "text": ") -> Callable[[str, Any], bool]:\n        \"\"\"Produce a function that checks if a class has overridden an\n        attribute, taking SQLAlchemy-enabled dataclass fields into account.\n        \"\"\"\n        if self.allow_dataclass_fields:\n            sa_dataclass_metadata_key = _get_immediate_cls_attr(\n                cls, \"__sa_dataclass_metadata_key__\"\n            )\n        else:\n            sa_dataclass_metadata_key = None\n        if not sa_dataclass_metadata_key:\n            def attribute_is_overridden(key: str, obj: Any) -> bool:\n                return getattr(cls, key, obj) is not obj\n        else:\n            all_datacls_fields = {\n                f.name: f.metadata[sa_dataclass_metadata_key]\n                for f in util.dataclass_fields(cls)\n                if sa_dataclass_metadata_key in f.metadata\n            }\n            local_datacls_fields = {\n                f.name: f.metadata[sa_dataclass_metadata_key]\n                for f in util.local_dataclass_fields(cls)\n                if sa_dataclass_metadata_key in f.metadata\n            }\n            absent = object()\n            def attribute_is_overridden(key: str, obj: Any) -> bool:\n                if _is_declarative_props(obj):\n                    obj = obj.fget\n                # this function likely has some failure modes still if\n                # someone is doing a deep mixing of the same attribute\n                # name as plain Python attribute vs. dataclass field.\n                ret = local_datacls_fields.get(key, absent)\n                if _is_declarative_props(ret):\n                    ret = ret.fget\n                if ret is obj:\n                    return False\n                elif ret is not absent:\n                    return True\n                all_field = all_datacls_fields.get(key, absent)\n                ret = getattr(cls, key, obj)", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-13", "text": "ret = getattr(cls, key, obj)\n                if ret is obj:\n                    return False\n                # for dataclasses, this could be the\n                # 'default' of the field.  so filter more specifically\n                # for an already-mapped InstrumentedAttribute\n                if ret is not absent and isinstance(\n                    ret, InstrumentedAttribute\n                ):\n                    return True\n                if all_field is obj:\n                    return False\n                elif all_field is not absent:\n                    return True\n                # can't find another attribute\n                return False\n        return attribute_is_overridden\n    _include_dunders = {\n        \"__table__\",\n        \"__mapper_args__\",\n        \"__tablename__\",\n        \"__table_args__\",\n    }\n    _match_exclude_dunders = re.compile(r\"^(?:_sa_|__)\")\n    def _cls_attr_resolver(\n        self, cls: Type[Any]\n    ) -> Callable[[], Iterable[Tuple[str, Any, Any, bool]]]:\n        \"\"\"produce a function to iterate the \"attributes\" of a class\n        which we want to consider for mapping, adjusting for SQLAlchemy fields\n        embedded in dataclass fields.\n        \"\"\"\n        cls_annotations = util.get_annotations(cls)\n        cls_vars = vars(cls)\n        _include_dunders = self._include_dunders\n        _match_exclude_dunders = self._match_exclude_dunders\n        names = [\n            n\n            for n in util.merge_lists_w_ordering(\n                list(cls_vars), list(cls_annotations)\n            )\n            if not _match_exclude_dunders.match(n) or n in _include_dunders\n        ]\n        if self.allow_dataclass_fields:\n            sa_dataclass_metadata_key: Optional[str] = _get_immediate_cls_attr(\n                cls, \"__sa_dataclass_metadata_key__\"", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-14", "text": "cls, \"__sa_dataclass_metadata_key__\"\n            )\n        else:\n            sa_dataclass_metadata_key = None\n        if not sa_dataclass_metadata_key:\n            def local_attributes_for_class() -> (\n                Iterable[Tuple[str, Any, Any, bool]]\n            ):\n                return (\n                    (\n                        name,\n                        cls_vars.get(name),\n                        cls_annotations.get(name),\n                        False,\n                    )\n                    for name in names\n                )\n        else:\n            dataclass_fields = {\n                field.name: field for field in util.local_dataclass_fields(cls)\n            }\n            fixed_sa_dataclass_metadata_key = sa_dataclass_metadata_key\n            def local_attributes_for_class() -> (\n                Iterable[Tuple[str, Any, Any, bool]]\n            ):\n                for name in names:\n                    field = dataclass_fields.get(name, None)\n                    if field and sa_dataclass_metadata_key in field.metadata:\n                        yield field.name, _as_dc_declaredattr(\n                            field.metadata, fixed_sa_dataclass_metadata_key\n                        ), cls_annotations.get(field.name), True\n                    else:\n                        yield name, cls_vars.get(name), cls_annotations.get(\n                            name\n                        ), False\n        return local_attributes_for_class\n    def _scan_attributes(self) -> None:\n        cls = self.cls\n        cls_as_Decl = cast(\"_DeclMappedClassProtocol[Any]\", cls)\n        clsdict_view = self.clsdict_view\n        collected_attributes = self.collected_attributes\n        column_copies = self.column_copies\n        _include_dunders = self._include_dunders\n        mapper_args_fn = None\n        table_args = inherited_table_args = None\n        tablename = None\n        fixed_table = \"__table__\" in clsdict_view\n        attribute_is_overridden = self._cls_attr_override_checker(self.cls)", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-15", "text": "attribute_is_overridden = self._cls_attr_override_checker(self.cls)\n        bases = []\n        for base in cls.__mro__:\n            # collect bases and make sure standalone columns are copied\n            # to be the column they will ultimately be on the class,\n            # so that declared_attr functions use the right columns.\n            # need to do this all the way up the hierarchy first\n            # (see #8190)\n            class_mapped = base is not cls and _is_supercls_for_inherits(base)\n            local_attributes_for_class = self._cls_attr_resolver(base)\n            if not class_mapped and base is not cls:\n                locally_collected_columns = self._produce_column_copies(\n                    local_attributes_for_class,\n                    attribute_is_overridden,\n                    fixed_table,\n                    base,\n                )\n            else:\n                locally_collected_columns = {}\n            bases.append(\n                (\n                    base,\n                    class_mapped,\n                    local_attributes_for_class,\n                    locally_collected_columns,\n                )\n            )\n        for (\n            base,\n            class_mapped,\n            local_attributes_for_class,\n            locally_collected_columns,\n        ) in bases:\n            # this transfer can also take place as we scan each name\n            # for finer-grained control of how collected_attributes is\n            # populated, as this is what impacts column ordering.\n            # however it's simpler to get it out of the way here.\n            collected_attributes.update(locally_collected_columns)\n            for (\n                name,\n                obj,\n                annotation,\n                is_dataclass_field,\n            ) in local_attributes_for_class():\n                if name in _include_dunders:\n                    if name == \"__mapper_args__\":\n                        check_decl = _check_declared_props_nocascade(", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-16", "text": "check_decl = _check_declared_props_nocascade(\n                            obj, name, cls\n                        )\n                        if not mapper_args_fn and (\n                            not class_mapped or check_decl\n                        ):\n                            # don't even invoke __mapper_args__ until\n                            # after we've determined everything about the\n                            # mapped table.\n                            # make a copy of it so a class-level dictionary\n                            # is not overwritten when we update column-based\n                            # arguments.\n                            def _mapper_args_fn() -> Dict[str, Any]:\n                                return dict(cls_as_Decl.__mapper_args__)\n                            mapper_args_fn = _mapper_args_fn\n                    elif name == \"__tablename__\":\n                        check_decl = _check_declared_props_nocascade(\n                            obj, name, cls\n                        )\n                        if not tablename and (not class_mapped or check_decl):\n                            tablename = cls_as_Decl.__tablename__\n                    elif name == \"__table_args__\":\n                        check_decl = _check_declared_props_nocascade(\n                            obj, name, cls\n                        )\n                        if not table_args and (not class_mapped or check_decl):\n                            table_args = cls_as_Decl.__table_args__\n                            if not isinstance(\n                                table_args, (tuple, dict, type(None))\n                            ):\n                                raise exc.ArgumentError(\n                                    \"__table_args__ value must be a tuple, \"\n                                    \"dict, or None\"\n                                )\n                            if base is not cls:\n                                inherited_table_args = True\n                    else:\n                        # skip all other dunder names, which at the moment\n                        # should only be __table__\n                        continue\n                elif class_mapped:\n                    if _is_declarative_props(obj) and not obj._quiet:\n                        util.warn(\n                            \"Regular (i.e. not __special__) \"", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-17", "text": "util.warn(\n                            \"Regular (i.e. not __special__) \"\n                            \"attribute '%s.%s' uses @declared_attr, \"\n                            \"but owning class %s is mapped - \"\n                            \"not applying to subclass %s.\"\n                            % (base.__name__, name, base, cls)\n                        )\n                    continue\n                elif base is not cls:\n                    # we're a mixin, abstract base, or something that is\n                    # acting like that for now.\n                    if isinstance(obj, (Column, MappedColumn)):\n                        # already copied columns to the mapped class.\n                        continue\n                    elif isinstance(obj, MapperProperty):\n                        raise exc.InvalidRequestError(\n                            \"Mapper properties (i.e. deferred,\"\n                            \"column_property(), relationship(), etc.) must \"\n                            \"be declared as @declared_attr callables \"\n                            \"on declarative mixin classes.  For dataclass \"\n                            \"field() objects, use a lambda:\"\n                        )\n                    elif _is_declarative_props(obj):\n                        # tried to get overloads to tell this to\n                        # pylance, no luck\n                        assert obj is not None\n                        if obj._cascading:\n                            if name in clsdict_view:\n                                # unfortunately, while we can use the user-\n                                # defined attribute here to allow a clean\n                                # override, if there's another\n                                # subclass below then it still tries to use\n                                # this.  not sure if there is enough\n                                # information here to add this as a feature\n                                # later on.\n                                util.warn(\n                                    \"Attribute '%s' on class %s cannot be \"\n                                    \"processed due to \"\n                                    \"@declared_attr.cascading; \"\n                                    \"skipping\" % (name, cls)\n                                )", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-18", "text": "\"skipping\" % (name, cls)\n                                )\n                            collected_attributes[name] = column_copies[\n                                obj\n                            ] = ret = obj.__get__(obj, cls)\n                            setattr(cls, name, ret)\n                        else:\n                            if is_dataclass_field:\n                                # access attribute using normal class access\n                                # first, to see if it's been mapped on a\n                                # superclass.   note if the dataclasses.field()\n                                # has \"default\", this value can be anything.\n                                ret = getattr(cls, name, None)\n                                # so, if it's anything that's not ORM\n                                # mapped, assume we should invoke the\n                                # declared_attr\n                                if not isinstance(ret, InspectionAttr):\n                                    ret = obj.fget()\n                            else:\n                                # access attribute using normal class access.\n                                # if the declared attr already took place\n                                # on a superclass that is mapped, then\n                                # this is no longer a declared_attr, it will\n                                # be the InstrumentedAttribute\n                                ret = getattr(cls, name)\n                            # correct for proxies created from hybrid_property\n                            # or similar.  note there is no known case that\n                            # produces nested proxies, so we are only\n                            # looking one level deep right now.\n                            if (\n                                isinstance(ret, InspectionAttr)\n                                and attr_is_internal_proxy(ret)\n                                and not isinstance(\n                                    ret.original_property, MapperProperty\n                                )\n                            ):\n                                ret = ret.descriptor\n                            collected_attributes[name] = column_copies[\n                                obj\n                            ] = ret\n                        if (\n                            isinstance(ret, (Column, MapperProperty))\n                            and ret.doc is None\n                        ):\n                            ret.doc = obj.__doc__\n                        self._collect_annotation(\n                            name,\n                            obj._collect_return_annotation(),", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-19", "text": "self._collect_annotation(\n                            name,\n                            obj._collect_return_annotation(),\n                            base,\n                            True,\n                            obj,\n                        )\n                    elif _is_mapped_annotation(annotation, cls, base):\n                        # Mapped annotation without any object.\n                        # product_column_copies should have handled this.\n                        # if future support for other MapperProperty,\n                        # then test if this name is already handled and\n                        # otherwise proceed to generate.\n                        if not fixed_table:\n                            assert (\n                                name in collected_attributes\n                                or attribute_is_overridden(name, None)\n                            )\n                        continue\n                    else:\n                        # here, the attribute is some other kind of\n                        # property that we assume is not part of the\n                        # declarative mapping.  however, check for some\n                        # more common mistakes\n                        self._warn_for_decl_attributes(base, name, obj)\n                elif is_dataclass_field and (\n                    name not in clsdict_view or clsdict_view[name] is not obj\n                ):\n                    # here, we are definitely looking at the target class\n                    # and not a superclass.   this is currently a\n                    # dataclass-only path.  if the name is only\n                    # a dataclass field and isn't in local cls.__dict__,\n                    # put the object there.\n                    # assert that the dataclass-enabled resolver agrees\n                    # with what we are seeing\n                    assert not attribute_is_overridden(name, obj)\n                    if _is_declarative_props(obj):\n                        obj = obj.fget()\n                    collected_attributes[name] = obj\n                    self._collect_annotation(\n                        name, annotation, base, False, obj\n                    )\n                else:\n                    collected_annotation = self._collect_annotation(\n                        name, annotation, base, None, obj\n                    )", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-20", "text": "name, annotation, base, None, obj\n                    )\n                    is_mapped = (\n                        collected_annotation is not None\n                        and collected_annotation.mapped_container is not None\n                    )\n                    generated_obj = (\n                        collected_annotation.attr_value\n                        if collected_annotation is not None\n                        else obj\n                    )\n                    if obj is None and not fixed_table and is_mapped:\n                        collected_attributes[name] = (\n                            generated_obj\n                            if generated_obj is not None\n                            else MappedColumn()\n                        )\n                    elif name in clsdict_view:\n                        collected_attributes[name] = obj\n                    # else if the name is not in the cls.__dict__,\n                    # don't collect it as an attribute.\n                    # we will see the annotation only, which is meaningful\n                    # both for mapping and dataclasses setup\n        if inherited_table_args and not tablename:\n            table_args = None\n        self.table_args = table_args\n        self.tablename = tablename\n        self.mapper_args_fn = mapper_args_fn\n    def _setup_dataclasses_transforms(self) -> None:\n        dataclass_setup_arguments = self.dataclass_setup_arguments\n        if not dataclass_setup_arguments:\n            return\n        # can't use is_dataclass since it uses hasattr\n        if \"__dataclass_fields__\" in self.cls.__dict__:\n            raise exc.InvalidRequestError(\n                f\"Class {self.cls} is already a dataclass; ensure that \"\n                \"base classes / decorator styles of establishing dataclasses \"\n                \"are not being mixed. \"\n                \"This can happen if a class that inherits from \"\n                \"'MappedAsDataclass', even indirectly, is been mapped with \"\n                \"'@registry.mapped_as_dataclass'\"\n            )\n        warn_for_non_dc_attrs = collections.defaultdict(list)\n        def _allow_dataclass_field(", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-21", "text": "def _allow_dataclass_field(\n            key: str, originating_class: Type[Any]\n        ) -> bool:\n            if (\n                originating_class is not self.cls\n                and \"__dataclass_fields__\" not in originating_class.__dict__\n            ):\n                warn_for_non_dc_attrs[originating_class].append(key)\n            return True\n        manager = instrumentation.manager_of_class(self.cls)\n        assert manager is not None\n        field_list = [\n            _AttributeOptions._get_arguments_for_make_dataclass(\n                key,\n                anno,\n                mapped_container,\n                self.collected_attributes.get(key, _NoArg.NO_ARG),\n            )\n            for key, anno, mapped_container in (\n                (\n                    key,\n                    mapped_anno if mapped_anno else raw_anno,\n                    mapped_container,\n                )\n                for key, (\n                    raw_anno,\n                    mapped_container,\n                    mapped_anno,\n                    is_dc,\n                    attr_value,\n                    originating_module,\n                    originating_class,\n                ) in self.collected_annotations.items()\n                if _allow_dataclass_field(key, originating_class)\n                and (\n                    key not in self.collected_attributes\n                    # issue #9226; check for attributes that we've collected\n                    # which are already instrumented, which we would assume\n                    # mean we are in an ORM inheritance mapping and this\n                    # attribute is already mapped on the superclass.   Under\n                    # no circumstance should any QueryableAttribute be sent to\n                    # the dataclass() function; anything that's mapped should\n                    # be Field and that's it\n                    or not isinstance(\n                        self.collected_attributes[key], QueryableAttribute\n                    )\n                )\n            )\n        ]\n        if warn_for_non_dc_attrs:\n            for (", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-22", "text": ")\n        ]\n        if warn_for_non_dc_attrs:\n            for (\n                originating_class,\n                non_dc_attrs,\n            ) in warn_for_non_dc_attrs.items():\n                util.warn_deprecated(\n                    f\"When transforming {self.cls} to a dataclass, \"\n                    f\"attribute(s) \"\n                    f\"{', '.join(repr(key) for key in non_dc_attrs)} \"\n                    f\"originates from superclass \"\n                    f\"{originating_class}, which is not a dataclass.  This \"\n                    f\"usage is deprecated and will raise an error in \"\n                    f\"SQLAlchemy 2.1.  When declaring SQLAlchemy Declarative \"\n                    f\"Dataclasses, ensure that all mixin classes and other \"\n                    f\"superclasses which include attributes are also a \"\n                    f\"subclass of MappedAsDataclass.\",\n                    \"2.0\",\n                    code=\"dcmx\",\n                )\n        annotations = {}\n        defaults = {}\n        for item in field_list:\n            if len(item) == 2:\n                name, tp = item  # type: ignore\n            elif len(item) == 3:\n                name, tp, spec = item  # type: ignore\n                defaults[name] = spec\n            else:\n                assert False\n            annotations[name] = tp\n        for k, v in defaults.items():\n            setattr(self.cls, k, v)\n        self._apply_dataclasses_to_any_class(\n            dataclass_setup_arguments, self.cls, annotations\n        )\n    @classmethod\n    def _update_annotations_for_non_mapped_class(\n        cls, klass: Type[_O]\n    ) -> Mapping[str, _AnnotationScanType]:\n        cls_annotations = util.get_annotations(klass)\n        new_anno = {}", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-23", "text": "cls_annotations = util.get_annotations(klass)\n        new_anno = {}\n        for name, annotation in cls_annotations.items():\n            if _is_mapped_annotation(annotation, klass, klass):\n                extracted = _extract_mapped_subtype(\n                    annotation,\n                    klass,\n                    klass.__module__,\n                    name,\n                    type(None),\n                    required=False,\n                    is_dataclass_field=False,\n                    expect_mapped=False,\n                )\n                if extracted:\n                    inner, _ = extracted\n                    new_anno[name] = inner\n            else:\n                new_anno[name] = annotation\n        return new_anno\n    @classmethod\n    def _apply_dataclasses_to_any_class(\n        cls,\n        dataclass_setup_arguments: _DataclassArguments,\n        klass: Type[_O],\n        use_annotations: Mapping[str, _AnnotationScanType],\n    ) -> None:\n        cls._assert_dc_arguments(dataclass_setup_arguments)\n        dataclass_callable = dataclass_setup_arguments[\"dataclass_callable\"]\n        if dataclass_callable is _NoArg.NO_ARG:\n            dataclass_callable = dataclasses.dataclass\n        restored: Optional[Any]\n        if use_annotations:\n            # apply constructed annotations that should look \"normal\" to a\n            # dataclasses callable, based on the fields present.  This\n            # means remove the Mapped[] container and ensure all Field\n            # entries have an annotation\n            restored = getattr(klass, \"__annotations__\", None)\n            klass.__annotations__ = cast(\"Dict[str, Any]\", use_annotations)\n        else:\n            restored = None\n        try:\n            dataclass_callable(\n                klass,\n                **{\n                    k: v\n                    for k, v in dataclass_setup_arguments.items()\n                    if v is not _NoArg.NO_ARG and k != \"dataclass_callable\"", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-24", "text": "if v is not _NoArg.NO_ARG and k != \"dataclass_callable\"\n                },\n            )\n        except (TypeError, ValueError) as ex:\n            raise exc.InvalidRequestError(\n                f\"Python dataclasses error encountered when creating \"\n                f\"dataclass for {klass.__name__!r}: \"\n                f\"{ex!r}. Please refer to Python dataclasses \"\n                \"documentation for additional information.\",\n                code=\"dcte\",\n            ) from ex\n        finally:\n            # restore original annotations outside of the dataclasses\n            # process; for mixins and __abstract__ superclasses, SQLAlchemy\n            # Declarative will need to see the Mapped[] container inside the\n            # annotations in order to map subclasses\n            if use_annotations:\n                if restored is None:\n                    del klass.__annotations__\n                else:\n                    klass.__annotations__ = restored\n    @classmethod\n    def _assert_dc_arguments(cls, arguments: _DataclassArguments) -> None:\n        allowed = {\n            \"init\",\n            \"repr\",\n            \"order\",\n            \"eq\",\n            \"unsafe_hash\",\n            \"kw_only\",\n            \"match_args\",\n            \"dataclass_callable\",\n        }\n        disallowed_args = set(arguments).difference(allowed)\n        if disallowed_args:\n            msg = \", \".join(f\"{arg!r}\" for arg in sorted(disallowed_args))\n            raise exc.ArgumentError(\n                f\"Dataclass argument(s) {msg} are not accepted\"\n            )\n    def _collect_annotation(\n        self,\n        name: str,\n        raw_annotation: _AnnotationScanType,\n        originating_class: Type[Any],\n        expect_mapped: Optional[bool],\n        attr_value: Any,\n    ) -> Optional[_CollectedAnnotation]:", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-25", "text": "attr_value: Any,\n    ) -> Optional[_CollectedAnnotation]:\n        if name in self.collected_annotations:\n            return self.collected_annotations[name]\n        if raw_annotation is None:\n            return None\n        is_dataclass = self.is_dataclass_prior_to_mapping\n        allow_unmapped = self.allow_unmapped_annotations\n        if expect_mapped is None:\n            is_dataclass_field = isinstance(attr_value, dataclasses.Field)\n            expect_mapped = (\n                not is_dataclass_field\n                and not allow_unmapped\n                and (\n                    attr_value is None\n                    or isinstance(attr_value, _MappedAttribute)\n                )\n            )\n        else:\n            is_dataclass_field = False\n        is_dataclass_field = False\n        extracted = _extract_mapped_subtype(\n            raw_annotation,\n            self.cls,\n            originating_class.__module__,\n            name,\n            type(attr_value),\n            required=False,\n            is_dataclass_field=is_dataclass_field,\n            expect_mapped=expect_mapped\n            and not is_dataclass,  # self.allow_dataclass_fields,\n        )\n        if extracted is None:\n            # ClassVar can come out here\n            return None\n        extracted_mapped_annotation, mapped_container = extracted\n        if attr_value is None and not is_literal(extracted_mapped_annotation):\n            for elem in typing_get_args(extracted_mapped_annotation):\n                if isinstance(elem, str) or is_fwd_ref(\n                    elem, check_generic=True\n                ):\n                    elem = de_stringify_annotation(\n                        self.cls,\n                        elem,\n                        originating_class.__module__,\n                        include_generic=True,\n                    )\n                # look in Annotated[...] for an ORM construct,\n                # such as Annotated[int, mapped_column(primary_key=True)]\n                if isinstance(elem, _IntrospectsAnnotations):", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-26", "text": "if isinstance(elem, _IntrospectsAnnotations):\n                    attr_value = elem.found_in_pep593_annotated()\n        self.collected_annotations[name] = ca = _CollectedAnnotation(\n            raw_annotation,\n            mapped_container,\n            extracted_mapped_annotation,\n            is_dataclass,\n            attr_value,\n            originating_class.__module__,\n            originating_class,\n        )\n        return ca\n    def _warn_for_decl_attributes(\n        self, cls: Type[Any], key: str, c: Any\n    ) -> None:\n        if isinstance(c, expression.ColumnElement):\n            util.warn(\n                f\"Attribute '{key}' on class {cls} appears to \"\n                \"be a non-schema SQLAlchemy expression \"\n                \"object; this won't be part of the declarative mapping. \"\n                \"To map arbitrary expressions, use ``column_property()`` \"\n                \"or a similar function such as ``deferred()``, \"\n                \"``query_expression()`` etc. \"\n            )\n    def _produce_column_copies(\n        self,\n        attributes_for_class: Callable[\n            [], Iterable[Tuple[str, Any, Any, bool]]\n        ],\n        attribute_is_overridden: Callable[[str, Any], bool],\n        fixed_table: bool,\n        originating_class: Type[Any],\n    ) -> Dict[str, Union[Column[Any], MappedColumn[Any]]]:\n        cls = self.cls\n        dict_ = self.clsdict_view\n        locally_collected_attributes = {}\n        column_copies = self.column_copies\n        # copy mixin columns to the mapped class\n        for name, obj, annotation, is_dataclass in attributes_for_class():\n            if (\n                not fixed_table\n                and obj is None\n                and _is_mapped_annotation(annotation, cls, originating_class)", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-27", "text": "and obj is None\n                and _is_mapped_annotation(annotation, cls, originating_class)\n            ):\n                # obj is None means this is the annotation only path\n                if attribute_is_overridden(name, obj):\n                    # perform same \"overridden\" check as we do for\n                    # Column/MappedColumn, this is how a mixin col is not\n                    # applied to an inherited subclass that does not have\n                    # the mixin.   the anno-only path added here for\n                    # #9564\n                    continue\n                collected_annotation = self._collect_annotation(\n                    name, annotation, originating_class, True, obj\n                )\n                obj = (\n                    collected_annotation.attr_value\n                    if collected_annotation is not None\n                    else obj\n                )\n                if obj is None:\n                    obj = MappedColumn()\n                locally_collected_attributes[name] = obj\n                setattr(cls, name, obj)\n            elif isinstance(obj, (Column, MappedColumn)):\n                if attribute_is_overridden(name, obj):\n                    # if column has been overridden\n                    # (like by the InstrumentedAttribute of the\n                    # superclass), skip.  don't collect the annotation\n                    # either (issue #8718)\n                    continue\n                collected_annotation = self._collect_annotation(\n                    name, annotation, originating_class, True, obj\n                )\n                obj = (\n                    collected_annotation.attr_value\n                    if collected_annotation is not None\n                    else obj\n                )\n                if name not in dict_ and not (\n                    \"__table__\" in dict_\n                    and (getattr(obj, \"name\", None) or name)\n                    in dict_[\"__table__\"].c\n                ):\n                    if obj.foreign_keys:\n                        for fk in obj.foreign_keys:\n                            if (\n                                fk._table_column is not None", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-28", "text": "if (\n                                fk._table_column is not None\n                                and fk._table_column.table is None\n                            ):\n                                raise exc.InvalidRequestError(\n                                    \"Columns with foreign keys to \"\n                                    \"non-table-bound \"\n                                    \"columns must be declared as \"\n                                    \"@declared_attr callables \"\n                                    \"on declarative mixin classes.  \"\n                                    \"For dataclass \"\n                                    \"field() objects, use a lambda:.\"\n                                )\n                    column_copies[obj] = copy_ = obj._copy()\n                    locally_collected_attributes[name] = copy_\n                    setattr(cls, name, copy_)\n        return locally_collected_attributes\n    def _extract_mappable_attributes(self) -> None:\n        cls = self.cls\n        collected_attributes = self.collected_attributes\n        our_stuff = self.properties\n        _include_dunders = self._include_dunders\n        late_mapped = _get_immediate_cls_attr(\n            cls, \"_sa_decl_prepare_nocascade\", strict=True\n        )\n        allow_unmapped_annotations = self.allow_unmapped_annotations\n        expect_annotations_wo_mapped = (\n            allow_unmapped_annotations or self.is_dataclass_prior_to_mapping\n        )\n        look_for_dataclass_things = bool(self.dataclass_setup_arguments)\n        for k in list(collected_attributes):\n            if k in _include_dunders:\n                continue\n            value = collected_attributes[k]\n            if _is_declarative_props(value):\n                # @declared_attr in collected_attributes only occurs here for a\n                # @declared_attr that's directly on the mapped class;\n                # for a mixin, these have already been evaluated\n                if value._cascading:\n                    util.warn(\n                        \"Use of @declared_attr.cascading only applies to \"", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-29", "text": "\"Use of @declared_attr.cascading only applies to \"\n                        \"Declarative 'mixin' and 'abstract' classes.  \"\n                        \"Currently, this flag is ignored on mapped class \"\n                        \"%s\" % self.cls\n                    )\n                value = getattr(cls, k)\n            elif (\n                isinstance(value, QueryableAttribute)\n                and value.class_ is not cls\n                and value.key != k\n            ):\n                # detect a QueryableAttribute that's already mapped being\n                # assigned elsewhere in userland, turn into a synonym()\n                value = SynonymProperty(value.key)\n                setattr(cls, k, value)\n            if (\n                isinstance(value, tuple)\n                and len(value) == 1\n                and isinstance(value[0], (Column, _MappedAttribute))\n            ):\n                util.warn(\n                    \"Ignoring declarative-like tuple value of attribute \"\n                    \"'%s': possibly a copy-and-paste error with a comma \"\n                    \"accidentally placed at the end of the line?\" % k\n                )\n                continue\n            elif look_for_dataclass_things and isinstance(\n                value, dataclasses.Field\n            ):\n                # we collected a dataclass Field; dataclasses would have\n                # set up the correct state on the class\n                continue\n            elif not isinstance(value, (Column, _DCAttributeOptions)):\n                # using @declared_attr for some object that\n                # isn't Column/MapperProperty/_DCAttributeOptions; remove\n                # from the clsdict_view\n                # and place the evaluated value onto the class.\n                collected_attributes.pop(k)\n                self._warn_for_decl_attributes(cls, k, value)\n                if not late_mapped:\n                    setattr(cls, k, value)\n                continue", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-30", "text": "if not late_mapped:\n                    setattr(cls, k, value)\n                continue\n            # we expect to see the name 'metadata' in some valid cases;\n            # however at this point we see it's assigned to something trying\n            # to be mapped, so raise for that.\n            # TODO: should \"registry\" here be also?   might be too late\n            # to change that now (2.0 betas)\n            elif k in (\"metadata\",):\n                raise exc.InvalidRequestError(\n                    f\"Attribute name '{k}' is reserved when using the \"\n                    \"Declarative API.\"\n                )\n            elif isinstance(value, Column):\n                _undefer_column_name(\n                    k, self.column_copies.get(value, value)  # type: ignore\n                )\n            else:\n                if isinstance(value, _IntrospectsAnnotations):\n                    (\n                        annotation,\n                        mapped_container,\n                        extracted_mapped_annotation,\n                        is_dataclass,\n                        attr_value,\n                        originating_module,\n                        originating_class,\n                    ) = self.collected_annotations.get(\n                        k, (None, None, None, False, None, None, None)\n                    )\n                    # issue #8692 - don't do any annotation interpretation if\n                    # an annotation were present and a container such as\n                    # Mapped[] etc. were not used.  If annotation is None,\n                    # do declarative_scan so that the property can raise\n                    # for required\n                    if (\n                        mapped_container is not None\n                        or annotation is None\n                        # issue #10516: need to do declarative_scan even with\n                        # a non-Mapped annotation if we are doing\n                        # __allow_unmapped__, for things like col.name\n                        # assignment\n                        or allow_unmapped_annotations\n                    ):", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-31", "text": "# assignment\n                        or allow_unmapped_annotations\n                    ):\n                        try:\n                            value.declarative_scan(\n                                self,\n                                self.registry,\n                                cls,\n                                originating_module,\n                                k,\n                                mapped_container,\n                                annotation,\n                                extracted_mapped_annotation,\n                                is_dataclass,\n                            )\n                        except NameError as ne:\n                            raise exc.ArgumentError(\n                                f\"Could not resolve all types within mapped \"\n                                f'annotation: \"{annotation}\".  Ensure all '\n                                f\"types are written correctly and are \"\n                                f\"imported within the module in use.\"\n                            ) from ne\n                    else:\n                        # assert that we were expecting annotations\n                        # without Mapped[] were going to be passed.\n                        # otherwise an error should have been raised\n                        # by util._extract_mapped_subtype before we got here.\n                        assert expect_annotations_wo_mapped\n                if isinstance(value, _DCAttributeOptions):\n                    if (\n                        value._has_dataclass_arguments\n                        and not look_for_dataclass_things\n                    ):\n                        if isinstance(value, MapperProperty):\n                            argnames = [\n                                \"init\",\n                                \"default_factory\",\n                                \"repr\",\n                                \"default\",\n                            ]\n                        else:\n                            argnames = [\"init\", \"default_factory\", \"repr\"]\n                        args = {\n                            a\n                            for a in argnames\n                            if getattr(\n                                value._attribute_options, f\"dataclasses_{a}\"\n                            )\n                            is not _NoArg.NO_ARG\n                        }\n                        raise exc.ArgumentError(\n                            f\"Attribute '{k}' on class {cls} includes \"\n                            f\"dataclasses argument(s): \"\n                            f\"{', '.join(sorted(repr(a) for a in args))} but \"\n                            f\"class does not specify \"", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-32", "text": "f\"class does not specify \"\n                            \"SQLAlchemy native dataclass configuration.\"\n                        )\n                    if not isinstance(value, (MapperProperty, _MapsColumns)):\n                        # filter for _DCAttributeOptions objects that aren't\n                        # MapperProperty / mapped_column().  Currently this\n                        # includes AssociationProxy.   pop it from the things\n                        # we're going to map and set it up as a descriptor\n                        # on the class.\n                        collected_attributes.pop(k)\n                        # Assoc Prox (or other descriptor object that may\n                        # use _DCAttributeOptions) is usually here, except if\n                        # 1. we're a\n                        # dataclass, dataclasses would have removed the\n                        # attr here or 2. assoc proxy is coming from a\n                        # superclass, we want it to be direct here so it\n                        # tracks state or 3. assoc prox comes from\n                        # declared_attr, uncommon case\n                        setattr(cls, k, value)\n                        continue\n            our_stuff[k] = value\n    def _extract_declared_columns(self) -> None:\n        our_stuff = self.properties\n        # extract columns from the class dict\n        declared_columns = self.declared_columns\n        column_ordering = self.column_ordering\n        name_to_prop_key = collections.defaultdict(set)\n        for key, c in list(our_stuff.items()):\n            if isinstance(c, _MapsColumns):\n                mp_to_assign = c.mapper_property_to_assign\n                if mp_to_assign:\n                    our_stuff[key] = mp_to_assign\n                else:\n                    # if no mapper property to assign, this currently means\n                    # this is a MappedColumn that will produce a Column for us\n                    del our_stuff[key]\n                for col, sort_order in c.columns_to_assign:\n                    if not isinstance(c, CompositeProperty):", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-33", "text": "if not isinstance(c, CompositeProperty):\n                        name_to_prop_key[col.name].add(key)\n                    declared_columns.add(col)\n                    # we would assert this, however we want the below\n                    # warning to take effect instead.  See #9630\n                    # assert col not in column_ordering\n                    column_ordering[col] = sort_order\n                    # if this is a MappedColumn and the attribute key we\n                    # have is not what the column has for its key, map the\n                    # Column explicitly under the attribute key name.\n                    # otherwise, Mapper will map it under the column key.\n                    if mp_to_assign is None and key != col.key:\n                        our_stuff[key] = col\n            elif isinstance(c, Column):\n                # undefer previously occurred here, and now occurs earlier.\n                # ensure every column we get here has been named\n                assert c.name is not None\n                name_to_prop_key[c.name].add(key)\n                declared_columns.add(c)\n                # if the column is the same name as the key,\n                # remove it from the explicit properties dict.\n                # the normal rules for assigning column-based properties\n                # will take over, including precedence of columns\n                # in multi-column ColumnProperties.\n                if key == c.key:\n                    del our_stuff[key]\n        for name, keys in name_to_prop_key.items():\n            if len(keys) > 1:\n                util.warn(\n                    \"On class %r, Column object %r named \"\n                    \"directly multiple times, \"\n                    \"only one will be used: %s. \"\n                    \"Consider using orm.synonym instead\"\n                    % (self.classname, name, (\", \".join(sorted(keys))))\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-34", "text": "% (self.classname, name, (\", \".join(sorted(keys))))\n                )\n    def _setup_table(self, table: Optional[FromClause] = None) -> None:\n        cls = self.cls\n        cls_as_Decl = cast(\"MappedClassProtocol[Any]\", cls)\n        tablename = self.tablename\n        table_args = self.table_args\n        clsdict_view = self.clsdict_view\n        declared_columns = self.declared_columns\n        column_ordering = self.column_ordering\n        manager = attributes.manager_of_class(cls)\n        if \"__table__\" not in clsdict_view and table is None:\n            if hasattr(cls, \"__table_cls__\"):\n                table_cls = cast(\n                    Type[Table],\n                    util.unbound_method_to_callable(cls.__table_cls__),  # type: ignore  # noqa: E501\n                )\n            else:\n                table_cls = Table\n            if tablename is not None:\n                args: Tuple[Any, ...] = ()\n                table_kw: Dict[str, Any] = {}\n                if table_args:\n                    if isinstance(table_args, dict):\n                        table_kw = table_args\n                    elif isinstance(table_args, tuple):\n                        if isinstance(table_args[-1], dict):\n                            args, table_kw = table_args[0:-1], table_args[-1]\n                        else:\n                            args = table_args\n                autoload_with = clsdict_view.get(\"__autoload_with__\")\n                if autoload_with:\n                    table_kw[\"autoload_with\"] = autoload_with\n                autoload = clsdict_view.get(\"__autoload__\")\n                if autoload:\n                    table_kw[\"autoload\"] = True\n                sorted_columns = sorted(\n                    declared_columns,\n                    key=lambda c: column_ordering.get(c, 0),\n                )\n                table = self.set_cls_attribute(\n                    \"__table__\",", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-35", "text": ")\n                table = self.set_cls_attribute(\n                    \"__table__\",\n                    table_cls(\n                        tablename,\n                        self._metadata_for_cls(manager),\n                        *sorted_columns,\n                        *args,\n                        **table_kw,\n                    ),\n                )\n        else:\n            if table is None:\n                table = cls_as_Decl.__table__\n            if declared_columns:\n                for c in declared_columns:\n                    if not table.c.contains_column(c):\n                        raise exc.ArgumentError(\n                            \"Can't add additional column %r when \"\n                            \"specifying __table__\" % c.key\n                        )\n        self.local_table = table\n    def _metadata_for_cls(self, manager: ClassManager[Any]) -> MetaData:\n        meta: Optional[MetaData] = getattr(self.cls, \"metadata\", None)\n        if meta is not None:\n            return meta\n        else:\n            return manager.registry.metadata\n    def _setup_inheriting_mapper(self, mapper_kw: _MapperKwArgs) -> None:\n        cls = self.cls\n        inherits = mapper_kw.get(\"inherits\", None)\n        if inherits is None:\n            # since we search for classical mappings now, search for\n            # multiple mapped bases as well and raise an error.\n            inherits_search = []\n            for base_ in cls.__bases__:\n                c = _resolve_for_abstract_or_classical(base_)\n                if c is None:\n                    continue\n                if _is_supercls_for_inherits(c) and c not in inherits_search:\n                    inherits_search.append(c)\n            if inherits_search:\n                if len(inherits_search) > 1:\n                    raise exc.InvalidRequestError(\n                        \"Class %s has multiple mapped bases: %r\"\n                        % (cls, inherits_search)\n                    )", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-36", "text": "% (cls, inherits_search)\n                    )\n                inherits = inherits_search[0]\n        elif isinstance(inherits, Mapper):\n            inherits = inherits.class_\n        self.inherits = inherits\n        clsdict_view = self.clsdict_view\n        if \"__table__\" not in clsdict_view and self.tablename is None:\n            self.single = True\n    def _setup_inheriting_columns(self, mapper_kw: _MapperKwArgs) -> None:\n        table = self.local_table\n        cls = self.cls\n        table_args = self.table_args\n        declared_columns = self.declared_columns\n        if (\n            table is None\n            and self.inherits is None\n            and not _get_immediate_cls_attr(cls, \"__no_table__\")\n        ):\n            raise exc.InvalidRequestError(\n                \"Class %r does not have a __table__ or __tablename__ \"\n                \"specified and does not inherit from an existing \"\n                \"table-mapped class.\" % cls\n            )\n        elif self.inherits:\n            inherited_mapper_or_config = _declared_mapping_info(self.inherits)\n            assert inherited_mapper_or_config is not None\n            inherited_table = inherited_mapper_or_config.local_table\n            inherited_persist_selectable = (\n                inherited_mapper_or_config.persist_selectable\n            )\n            if table is None:\n                # single table inheritance.\n                # ensure no table args\n                if table_args:\n                    raise exc.ArgumentError(\n                        \"Can't place __table_args__ on an inherited class \"\n                        \"with no table.\"\n                    )\n                # add any columns declared here to the inherited table.\n                if declared_columns and not isinstance(inherited_table, Table):\n                    raise exc.ArgumentError(\n                        f\"Can't declare columns on single-table-inherited \"", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-37", "text": "f\"Can't declare columns on single-table-inherited \"\n                        f\"subclass {self.cls}; superclass {self.inherits} \"\n                        \"is not mapped to a Table\"\n                    )\n                for col in declared_columns:\n                    assert inherited_table is not None\n                    if col.name in inherited_table.c:\n                        if inherited_table.c[col.name] is col:\n                            continue\n                        raise exc.ArgumentError(\n                            f\"Column '{col}' on class {cls.__name__} \"\n                            f\"conflicts with existing column \"\n                            f\"'{inherited_table.c[col.name]}'.  If using \"\n                            f\"Declarative, consider using the \"\n                            \"use_existing_column parameter of mapped_column() \"\n                            \"to resolve conflicts.\"\n                        )\n                    if col.primary_key:\n                        raise exc.ArgumentError(\n                            \"Can't place primary key columns on an inherited \"\n                            \"class with no table.\"\n                        )\n                    if TYPE_CHECKING:\n                        assert isinstance(inherited_table, Table)\n                    inherited_table.append_column(col)\n                    if (\n                        inherited_persist_selectable is not None\n                        and inherited_persist_selectable is not inherited_table\n                    ):\n                        inherited_persist_selectable._refresh_for_new_column(\n                            col\n                        )\n    def _prepare_mapper_arguments(self, mapper_kw: _MapperKwArgs) -> None:\n        properties = self.properties\n        if self.mapper_args_fn:\n            mapper_args = self.mapper_args_fn()\n        else:\n            mapper_args = {}\n        if mapper_kw:\n            mapper_args.update(mapper_kw)\n        if \"properties\" in mapper_args:\n            properties = dict(properties)\n            properties.update(mapper_args[\"properties\"])\n        # make sure that column copies are used rather\n        # than the original columns from any mixins", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-38", "text": "# than the original columns from any mixins\n        for k in (\"version_id_col\", \"polymorphic_on\"):\n            if k in mapper_args:\n                v = mapper_args[k]\n                mapper_args[k] = self.column_copies.get(v, v)\n        if \"primary_key\" in mapper_args:\n            mapper_args[\"primary_key\"] = [\n                self.column_copies.get(v, v)\n                for v in util.to_list(mapper_args[\"primary_key\"])\n            ]\n        if \"inherits\" in mapper_args:\n            inherits_arg = mapper_args[\"inherits\"]\n            if isinstance(inherits_arg, Mapper):\n                inherits_arg = inherits_arg.class_\n            if inherits_arg is not self.inherits:\n                raise exc.InvalidRequestError(\n                    \"mapper inherits argument given for non-inheriting \"\n                    \"class %s\" % (mapper_args[\"inherits\"])\n                )\n        if self.inherits:\n            mapper_args[\"inherits\"] = self.inherits\n        if self.inherits and not mapper_args.get(\"concrete\", False):\n            # note the superclass is expected to have a Mapper assigned and\n            # not be a deferred config, as this is called within map()\n            inherited_mapper = class_mapper(self.inherits, False)\n            inherited_table = inherited_mapper.local_table\n            # single or joined inheritance\n            # exclude any cols on the inherited table which are\n            # not mapped on the parent class, to avoid\n            # mapping columns specific to sibling/nephew classes\n            if \"exclude_properties\" not in mapper_args:\n                mapper_args[\"exclude_properties\"] = exclude_properties = {\n                    c.key\n                    for c in inherited_table.c\n                    if c not in inherited_mapper._columntoproperty\n                }.union(inherited_mapper.exclude_properties or ())\n                exclude_properties.difference_update(", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-39", "text": "}.union(inherited_mapper.exclude_properties or ())\n                exclude_properties.difference_update(\n                    [c.key for c in self.declared_columns]\n                )\n            # look through columns in the current mapper that\n            # are keyed to a propname different than the colname\n            # (if names were the same, we'd have popped it out above,\n            # in which case the mapper makes this combination).\n            # See if the superclass has a similar column property.\n            # If so, join them together.\n            for k, col in list(properties.items()):\n                if not isinstance(col, expression.ColumnElement):\n                    continue\n                if k in inherited_mapper._props:\n                    p = inherited_mapper._props[k]\n                    if isinstance(p, ColumnProperty):\n                        # note here we place the subclass column\n                        # first.  See [ticket:1892] for background.\n                        properties[k] = [col] + p.columns\n        result_mapper_args = mapper_args.copy()\n        result_mapper_args[\"properties\"] = properties\n        self.mapper_args = result_mapper_args\n    def map(self, mapper_kw: _MapperKwArgs = util.EMPTY_DICT) -> Mapper[Any]:\n        self._prepare_mapper_arguments(mapper_kw)\n        if hasattr(self.cls, \"__mapper_cls__\"):\n            mapper_cls = cast(\n                \"Type[Mapper[Any]]\",\n                util.unbound_method_to_callable(\n                    self.cls.__mapper_cls__  # type: ignore\n                ),\n            )\n        else:\n            mapper_cls = Mapper\n        return self.set_cls_attribute(\n            \"__mapper__\",\n            mapper_cls(self.cls, self.local_table, **self.mapper_args),\n        )\n@util.preload_module(\"sqlalchemy.orm.decl_api\")\ndef _as_dc_declaredattr(", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-40", "text": "def _as_dc_declaredattr(\n    field_metadata: Mapping[str, Any], sa_dataclass_metadata_key: str\n) -> Any:\n    # wrap lambdas inside dataclass fields inside an ad-hoc declared_attr.\n    # we can't write it because field.metadata is immutable :( so we have\n    # to go through extra trouble to compare these\n    decl_api = util.preloaded.orm_decl_api\n    obj = field_metadata[sa_dataclass_metadata_key]\n    if callable(obj) and not isinstance(obj, decl_api.declared_attr):\n        return decl_api.declared_attr(obj)\n    else:\n        return obj\nclass _DeferredMapperConfig(_ClassScanMapperConfig):\n    _cls: weakref.ref[Type[Any]]\n    is_deferred = True\n    _configs: util.OrderedDict[\n        weakref.ref[Type[Any]], _DeferredMapperConfig\n    ] = util.OrderedDict()\n    def _early_mapping(self, mapper_kw: _MapperKwArgs) -> None:\n        pass\n    # mypy disallows plain property override of variable\n    @property  # type: ignore\n    def cls(self) -> Type[Any]:\n        return self._cls()  # type: ignore\n    @cls.setter\n    def cls(self, class_: Type[Any]) -> None:\n        self._cls = weakref.ref(class_, self._remove_config_cls)\n        self._configs[self._cls] = self\n    @classmethod\n    def _remove_config_cls(cls, ref: weakref.ref[Type[Any]]) -> None:\n        cls._configs.pop(ref, None)\n    @classmethod\n    def has_cls(cls, class_: Type[Any]) -> bool:\n        # 2.6 fails on weakref if class_ is an old style class", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-41", "text": "# 2.6 fails on weakref if class_ is an old style class\n        return isinstance(class_, type) and weakref.ref(class_) in cls._configs\n    @classmethod\n    def raise_unmapped_for_cls(cls, class_: Type[Any]) -> NoReturn:\n        if hasattr(class_, \"_sa_raise_deferred_config\"):\n            class_._sa_raise_deferred_config()\n        raise orm_exc.UnmappedClassError(\n            class_,\n            msg=(\n                f\"Class {orm_exc._safe_cls_name(class_)} has a deferred \"\n                \"mapping on it.  It is not yet usable as a mapped class.\"\n            ),\n        )\n    @classmethod\n    def config_for_cls(cls, class_: Type[Any]) -> _DeferredMapperConfig:\n        return cls._configs[weakref.ref(class_)]\n    @classmethod\n    def classes_for_base(\n        cls, base_cls: Type[Any], sort: bool = True\n    ) -> List[_DeferredMapperConfig]:\n        classes_for_base = [\n            m\n            for m, cls_ in [(m, m.cls) for m in cls._configs.values()]\n            if cls_ is not None and issubclass(cls_, base_cls)\n        ]\n        if not sort:\n            return classes_for_base\n        all_m_by_cls = {m.cls: m for m in classes_for_base}\n        tuples: List[Tuple[_DeferredMapperConfig, _DeferredMapperConfig]] = []\n        for m_cls in all_m_by_cls:\n            tuples.extend(\n                (all_m_by_cls[base_cls], all_m_by_cls[m_cls])\n                for base_cls in m_cls.__bases__\n                if base_cls in all_m_by_cls\n            )\n        return list(topological.sort(tuples, classes_for_base))", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-42", "text": ")\n        return list(topological.sort(tuples, classes_for_base))\n    def map(self, mapper_kw: _MapperKwArgs = util.EMPTY_DICT) -> Mapper[Any]:\n        self._configs.pop(self._cls, None)\n        return super().map(mapper_kw)\ndef _add_attribute(\n    cls: Type[Any], key: str, value: MapperProperty[Any]\n) -> None:\n    \"\"\"add an attribute to an existing declarative class.\n    This runs through the logic to determine MapperProperty,\n    adds it to the Mapper, adds a column to the mapped Table, etc.\n    \"\"\"\n    if \"__mapper__\" in cls.__dict__:\n        mapped_cls = cast(\"MappedClassProtocol[Any]\", cls)\n        def _table_or_raise(mc: MappedClassProtocol[Any]) -> Table:\n            if isinstance(mc.__table__, Table):\n                return mc.__table__\n            raise exc.InvalidRequestError(\n                f\"Cannot add a new attribute to mapped class {mc.__name__!r} \"\n                \"because it's not mapped against a table.\"\n            )\n        if isinstance(value, Column):\n            _undefer_column_name(key, value)\n            _table_or_raise(mapped_cls).append_column(\n                value, replace_existing=True\n            )\n            mapped_cls.__mapper__.add_property(key, value)\n        elif isinstance(value, _MapsColumns):\n            mp = value.mapper_property_to_assign\n            for col, _ in value.columns_to_assign:\n                _undefer_column_name(key, col)\n                _table_or_raise(mapped_cls).append_column(\n                    col, replace_existing=True\n                )\n                if not mp:\n                    mapped_cls.__mapper__.add_property(key, col)\n            if mp:\n                mapped_cls.__mapper__.add_property(key, mp)", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-43", "text": "if mp:\n                mapped_cls.__mapper__.add_property(key, mp)\n        elif isinstance(value, MapperProperty):\n            mapped_cls.__mapper__.add_property(key, value)\n        elif isinstance(value, QueryableAttribute) and value.key != key:\n            # detect a QueryableAttribute that's already mapped being\n            # assigned elsewhere in userland, turn into a synonym()\n            value = SynonymProperty(value.key)\n            mapped_cls.__mapper__.add_property(key, value)\n        else:\n            type.__setattr__(cls, key, value)\n            mapped_cls.__mapper__._expire_memoizations()\n    else:\n        type.__setattr__(cls, key, value)\ndef _del_attribute(cls: Type[Any], key: str) -> None:\n    if (\n        \"__mapper__\" in cls.__dict__\n        and key in cls.__dict__\n        and not cast(\n            \"MappedClassProtocol[Any]\", cls\n        ).__mapper__._dispose_called\n    ):\n        value = cls.__dict__[key]\n        if isinstance(\n            value, (Column, _MapsColumns, MapperProperty, QueryableAttribute)\n        ):\n            raise NotImplementedError(\n                \"Can't un-map individual mapped attributes on a mapped class.\"\n            )\n        else:\n            type.__delattr__(cls, key)\n            cast(\n                \"MappedClassProtocol[Any]\", cls\n            ).__mapper__._expire_memoizations()\n    else:\n        type.__delattr__(cls, key)\ndef _declarative_constructor(self: Any, **kwargs: Any) -> None:\n    \"\"\"A simple constructor that allows initialization from kwargs.\n    Sets attributes on the constructed instance using the names and\n    values in ``kwargs``.\n    Only keys that are present as", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "a5972cc239fa-44", "text": "values in ``kwargs``.\n    Only keys that are present as\n    attributes of the instance's class are allowed. These could be,\n    for example, any mapped columns or relationships.\n    \"\"\"\n    cls_ = type(self)\n    for k in kwargs:\n        if not hasattr(cls_, k):\n            raise TypeError(\n                \"%r is an invalid keyword argument for %s\" % (k, cls_.__name__)\n            )\n        setattr(self, k, kwargs[k])\n_declarative_constructor.__name__ = \"__init__\"\ndef _undefer_column_name(key: str, column: Column[Any]) -> None:\n    if column.key is None:\n        column.key = key\n    if column.name is None:\n        column.name = key", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/decl_base.html"}
{"id": "e415edc200d2-0", "text": "Source code for sqlalchemy.orm.instrumentation\n# orm/instrumentation.py\n# Copyright (C) 2005-2023 the SQLAlchemy authors and contributors\n# <see AUTHORS file>\n#\n# This module is part of SQLAlchemy and is released under\n# the MIT License: https://www.opensource.org/licenses/mit-license.php\n# mypy: allow-untyped-defs, allow-untyped-calls\n\"\"\"Defines SQLAlchemy's system of class instrumentation.\nThis module is usually not directly visible to user applications, but\ndefines a large part of the ORM's interactivity.\ninstrumentation.py deals with registration of end-user classes\nfor state tracking.   It interacts closely with state.py\nand attributes.py which establish per-instance and per-class-attribute\ninstrumentation, respectively.\nThe class instrumentation system can be customized on a per-class\nor global basis using the :mod:`sqlalchemy.ext.instrumentation`\nmodule, which provides the means to build and specify\nalternate instrumentation forms.\n.. versionchanged: 0.8\n   The instrumentation extension system was moved out of the\n   ORM and into the external :mod:`sqlalchemy.ext.instrumentation`\n   package.  When that package is imported, it installs\n   itself within sqlalchemy.orm so that its more comprehensive\n   resolution mechanics take effect.\n\"\"\"\nfrom __future__ import annotations\nfrom typing import Any\nfrom typing import Callable\nfrom typing import cast\nfrom typing import Collection\nfrom typing import Dict\nfrom typing import Generic\nfrom typing import Iterable\nfrom typing import List\nfrom typing import Optional\nfrom typing import Set\nfrom typing import Tuple\nfrom typing import Type\nfrom typing import TYPE_CHECKING\nfrom typing import TypeVar\nfrom typing import Union\nimport weakref\nfrom . import base\nfrom . import collections\nfrom . import exc\nfrom . import interfaces\nfrom . import state\nfrom ._typing import _O", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-1", "text": "from . import interfaces\nfrom . import state\nfrom ._typing import _O\nfrom .attributes import _is_collection_attribute_impl\nfrom .. import util\nfrom ..event import EventTarget\nfrom ..util import HasMemoized\nfrom ..util.typing import Literal\nfrom ..util.typing import Protocol\nif TYPE_CHECKING:\n    from ._typing import _RegistryType\n    from .attributes import AttributeImpl\n    from .attributes import QueryableAttribute\n    from .collections import _AdaptedCollectionProtocol\n    from .collections import _CollectionFactoryType\n    from .decl_base import _MapperConfig\n    from .events import InstanceEvents\n    from .mapper import Mapper\n    from .state import InstanceState\n    from ..event import dispatcher\n_T = TypeVar(\"_T\", bound=Any)\nDEL_ATTR = util.symbol(\"DEL_ATTR\")\nclass _ExpiredAttributeLoaderProto(Protocol):\n    def __call__(\n        self,\n        state: state.InstanceState[Any],\n        toload: Set[str],\n        passive: base.PassiveFlag,\n    ) -> None:\n        ...\nclass _ManagerFactory(Protocol):\n    def __call__(self, class_: Type[_O]) -> ClassManager[_O]:\n        ...\nclass ClassManager(\n    HasMemoized,\n    Dict[str, \"QueryableAttribute[Any]\"],\n    Generic[_O],\n    EventTarget,\n):\n    \"\"\"Tracks state information at the class level.\"\"\"\n    dispatch: dispatcher[ClassManager[_O]]\n    MANAGER_ATTR = base.DEFAULT_MANAGER_ATTR\n    STATE_ATTR = base.DEFAULT_STATE_ATTR\n    _state_setter = staticmethod(util.attrsetter(STATE_ATTR))\n    expired_attribute_loader: _ExpiredAttributeLoaderProto\n    \"previously known as deferred_scalar_loader\"\n    init_method: Optional[Callable[..., None]]", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-2", "text": "init_method: Optional[Callable[..., None]]\n    original_init: Optional[Callable[..., None]] = None\n    factory: Optional[_ManagerFactory]\n    declarative_scan: Optional[weakref.ref[_MapperConfig]] = None\n    registry: _RegistryType\n    if not TYPE_CHECKING:\n        # starts as None during setup\n        registry = None\n    class_: Type[_O]\n    _bases: List[ClassManager[Any]]\n    @property\n    @util.deprecated(\n        \"1.4\",\n        message=\"The ClassManager.deferred_scalar_loader attribute is now \"\n        \"named expired_attribute_loader\",\n    )\n    def deferred_scalar_loader(self):\n        return self.expired_attribute_loader\n    @deferred_scalar_loader.setter\n    @util.deprecated(\n        \"1.4\",\n        message=\"The ClassManager.deferred_scalar_loader attribute is now \"\n        \"named expired_attribute_loader\",\n    )\n    def deferred_scalar_loader(self, obj):\n        self.expired_attribute_loader = obj\n    def __init__(self, class_):\n        self.class_ = class_\n        self.info = {}\n        self.new_init = None\n        self.local_attrs = {}\n        self.originals = {}\n        self._finalized = False\n        self.factory = None\n        self.init_method = None\n        self._bases = [\n            mgr\n            for mgr in cast(\n                \"List[Optional[ClassManager[Any]]]\",\n                [\n                    opt_manager_of_class(base)\n                    for base in self.class_.__bases__\n                    if isinstance(base, type)\n                ],\n            )\n            if mgr is not None\n        ]\n        for base_ in self._bases:\n            self.update(base_)\n        cast(\n            \"InstanceEvents\", self.dispatch._events", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-3", "text": "self.update(base_)\n        cast(\n            \"InstanceEvents\", self.dispatch._events\n        )._new_classmanager_instance(class_, self)\n        for basecls in class_.__mro__:\n            mgr = opt_manager_of_class(basecls)\n            if mgr is not None:\n                self.dispatch._update(mgr.dispatch)\n        self.manage()\n        if \"__del__\" in class_.__dict__:\n            util.warn(\n                \"__del__() method on class %s will \"\n                \"cause unreachable cycles and memory leaks, \"\n                \"as SQLAlchemy instrumentation often creates \"\n                \"reference cycles.  Please remove this method.\" % class_\n            )\n    def _update_state(\n        self,\n        finalize: bool = False,\n        mapper: Optional[Mapper[_O]] = None,\n        registry: Optional[_RegistryType] = None,\n        declarative_scan: Optional[_MapperConfig] = None,\n        expired_attribute_loader: Optional[\n            _ExpiredAttributeLoaderProto\n        ] = None,\n        init_method: Optional[Callable[..., None]] = None,\n    ) -> None:\n        if mapper:\n            self.mapper = mapper  #\n        if registry:\n            registry._add_manager(self)\n        if declarative_scan:\n            self.declarative_scan = weakref.ref(declarative_scan)\n        if expired_attribute_loader:\n            self.expired_attribute_loader = expired_attribute_loader\n        if init_method:\n            assert not self._finalized, (\n                \"class is already instrumented, \"\n                \"init_method %s can't be applied\" % init_method\n            )\n            self.init_method = init_method\n        if not self._finalized:\n            self.original_init = (\n                self.init_method\n                if self.init_method is not None", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-4", "text": "self.init_method\n                if self.init_method is not None\n                and self.class_.__init__ is object.__init__\n                else self.class_.__init__\n            )\n        if finalize and not self._finalized:\n            self._finalize()\n    def _finalize(self) -> None:\n        if self._finalized:\n            return\n        self._finalized = True\n        self._instrument_init()\n        _instrumentation_factory.dispatch.class_instrument(self.class_)\n    def __hash__(self) -> int:  # type: ignore[override]\n        return id(self)\n    def __eq__(self, other: Any) -> bool:\n        return other is self\n    @property\n    def is_mapped(self) -> bool:\n        return \"mapper\" in self.__dict__\n    @HasMemoized.memoized_attribute\n    def _all_key_set(self):\n        return frozenset(self)\n    @HasMemoized.memoized_attribute\n    def _collection_impl_keys(self):\n        return frozenset(\n            [attr.key for attr in self.values() if attr.impl.collection]\n        )\n    @HasMemoized.memoized_attribute\n    def _scalar_loader_impls(self):\n        return frozenset(\n            [\n                attr.impl\n                for attr in self.values()\n                if attr.impl.accepts_scalar_loader\n            ]\n        )\n    @HasMemoized.memoized_attribute\n    def _loader_impls(self):\n        return frozenset([attr.impl for attr in self.values()])\n    @util.memoized_property\n    def mapper(self) -> Mapper[_O]:\n        # raises unless self.mapper has been assigned\n        raise exc.UnmappedClassError(self.class_)\n    def _all_sqla_attributes(self, exclude=None):", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-5", "text": "def _all_sqla_attributes(self, exclude=None):\n        \"\"\"return an iterator of all classbound attributes that are\n        implement :class:`.InspectionAttr`.\n        This includes :class:`.QueryableAttribute` as well as extension\n        types such as :class:`.hybrid_property` and\n        :class:`.AssociationProxy`.\n        \"\"\"\n        found: Dict[str, Any] = {}\n        # constraints:\n        # 1. yield keys in cls.__dict__ order\n        # 2. if a subclass has the same key as a superclass, include that\n        #    key as part of the ordering of the superclass, because an\n        #    overridden key is usually installed by the mapper which is going\n        #    on a different ordering\n        # 3. don't use getattr() as this fires off descriptors\n        for supercls in self.class_.__mro__[0:-1]:\n            inherits = supercls.__mro__[1]\n            for key in supercls.__dict__:\n                found.setdefault(key, supercls)\n                if key in inherits.__dict__:\n                    continue\n                val = found[key].__dict__[key]\n                if (\n                    isinstance(val, interfaces.InspectionAttr)\n                    and val.is_attribute\n                ):\n                    yield key, val\n    def _get_class_attr_mro(self, key, default=None):\n        \"\"\"return an attribute on the class without tripping it.\"\"\"\n        for supercls in self.class_.__mro__:\n            if key in supercls.__dict__:\n                return supercls.__dict__[key]\n        else:\n            return default\n    def _attr_has_impl(self, key: str) -> bool:\n        \"\"\"Return True if the given attribute is fully initialized.\n        i.e. has an impl.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-6", "text": "i.e. has an impl.\n        \"\"\"\n        return key in self and self[key].impl is not None\n    def _subclass_manager(self, cls: Type[_T]) -> ClassManager[_T]:\n        \"\"\"Create a new ClassManager for a subclass of this ClassManager's\n        class.\n        This is called automatically when attributes are instrumented so that\n        the attributes can be propagated to subclasses against their own\n        class-local manager, without the need for mappers etc. to have already\n        pre-configured managers for the full class hierarchy.   Mappers\n        can post-configure the auto-generated ClassManager when needed.\n        \"\"\"\n        return register_class(cls, finalize=False)\n    def _instrument_init(self):\n        self.new_init = _generate_init(self.class_, self, self.original_init)\n        self.install_member(\"__init__\", self.new_init)\n    @util.memoized_property\n    def _state_constructor(self) -> Type[state.InstanceState[_O]]:\n        self.dispatch.first_init(self, self.class_)\n        return state.InstanceState\n    def manage(self):\n        \"\"\"Mark this instance as the manager for its class.\"\"\"\n        setattr(self.class_, self.MANAGER_ATTR, self)\n    @util.hybridmethod\n    def manager_getter(self):\n        return _default_manager_getter\n    @util.hybridmethod\n    def state_getter(self):\n        \"\"\"Return a (instance) -> InstanceState callable.\n        \"state getter\" callables should raise either KeyError or\n        AttributeError if no InstanceState could be found for the\n        instance.\n        \"\"\"\n        return _default_state_getter\n    @util.hybridmethod\n    def dict_getter(self):\n        return _default_dict_getter\n    def instrument_attribute(\n        self,\n        key: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-7", "text": "def instrument_attribute(\n        self,\n        key: str,\n        inst: QueryableAttribute[Any],\n        propagated: bool = False,\n    ) -> None:\n        if propagated:\n            if key in self.local_attrs:\n                return  # don't override local attr with inherited attr\n        else:\n            self.local_attrs[key] = inst\n            self.install_descriptor(key, inst)\n        self._reset_memoizations()\n        self[key] = inst\n        for cls in self.class_.__subclasses__():\n            manager = self._subclass_manager(cls)\n            manager.instrument_attribute(key, inst, True)\n    def subclass_managers(self, recursive):\n        for cls in self.class_.__subclasses__():\n            mgr = opt_manager_of_class(cls)\n            if mgr is not None and mgr is not self:\n                yield mgr\n                if recursive:\n                    yield from mgr.subclass_managers(True)\n    def post_configure_attribute(self, key):\n        _instrumentation_factory.dispatch.attribute_instrument(\n            self.class_, key, self[key]\n        )\n    def uninstrument_attribute(self, key, propagated=False):\n        if key not in self:\n            return\n        if propagated:\n            if key in self.local_attrs:\n                return  # don't get rid of local attr\n        else:\n            del self.local_attrs[key]\n            self.uninstall_descriptor(key)\n        self._reset_memoizations()\n        del self[key]\n        for cls in self.class_.__subclasses__():\n            manager = opt_manager_of_class(cls)\n            if manager:\n                manager.uninstrument_attribute(key, True)\n    def unregister(self) -> None:\n        \"\"\"remove all instrumentation established by this ClassManager.\"\"\"\n        for key in list(self.originals):\n            self.uninstall_member(key)", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-8", "text": "for key in list(self.originals):\n            self.uninstall_member(key)\n        self.mapper = None\n        self.dispatch = None  # type: ignore\n        self.new_init = None\n        self.info.clear()\n        for key in list(self):\n            if key in self.local_attrs:\n                self.uninstrument_attribute(key)\n        if self.MANAGER_ATTR in self.class_.__dict__:\n            delattr(self.class_, self.MANAGER_ATTR)\n    def install_descriptor(\n        self, key: str, inst: QueryableAttribute[Any]\n    ) -> None:\n        if key in (self.STATE_ATTR, self.MANAGER_ATTR):\n            raise KeyError(\n                \"%r: requested attribute name conflicts with \"\n                \"instrumentation attribute of the same name.\" % key\n            )\n        setattr(self.class_, key, inst)\n    def uninstall_descriptor(self, key: str) -> None:\n        delattr(self.class_, key)\n    def install_member(self, key: str, implementation: Any) -> None:\n        if key in (self.STATE_ATTR, self.MANAGER_ATTR):\n            raise KeyError(\n                \"%r: requested attribute name conflicts with \"\n                \"instrumentation attribute of the same name.\" % key\n            )\n        self.originals.setdefault(key, self.class_.__dict__.get(key, DEL_ATTR))\n        setattr(self.class_, key, implementation)\n    def uninstall_member(self, key: str) -> None:\n        original = self.originals.pop(key, None)\n        if original is not DEL_ATTR:\n            setattr(self.class_, key, original)\n        else:\n            delattr(self.class_, key)\n    def instrument_collection_class(\n        self, key: str, collection_class: Type[Collection[Any]]\n    ) -> _CollectionFactoryType:", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-9", "text": ") -> _CollectionFactoryType:\n        return collections.prepare_instrumentation(collection_class)\n    def initialize_collection(\n        self,\n        key: str,\n        state: InstanceState[_O],\n        factory: _CollectionFactoryType,\n    ) -> Tuple[collections.CollectionAdapter, _AdaptedCollectionProtocol]:\n        user_data = factory()\n        impl = self.get_impl(key)\n        assert _is_collection_attribute_impl(impl)\n        adapter = collections.CollectionAdapter(impl, state, user_data)\n        return adapter, user_data\n    def is_instrumented(self, key: str, search: bool = False) -> bool:\n        if search:\n            return key in self\n        else:\n            return key in self.local_attrs\n    def get_impl(self, key: str) -> AttributeImpl:\n        return self[key].impl\n    @property\n    def attributes(self) -> Iterable[Any]:\n        return iter(self.values())\n    # InstanceState management\n    def new_instance(self, state: Optional[InstanceState[_O]] = None) -> _O:\n        # here, we would prefer _O to be bound to \"object\"\n        # so that mypy sees that __new__ is present.   currently\n        # it's bound to Any as there were other problems not having\n        # it that way but these can be revisited\n        instance = self.class_.__new__(self.class_)\n        if state is None:\n            state = self._state_constructor(instance, self)\n        self._state_setter(instance, state)\n        return instance\n    def setup_instance(\n        self, instance: _O, state: Optional[InstanceState[_O]] = None\n    ) -> None:\n        if state is None:\n            state = self._state_constructor(instance, self)", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-10", "text": "if state is None:\n            state = self._state_constructor(instance, self)\n        self._state_setter(instance, state)\n    def teardown_instance(self, instance: _O) -> None:\n        delattr(instance, self.STATE_ATTR)\n    def _serialize(\n        self, state: InstanceState[_O], state_dict: Dict[str, Any]\n    ) -> _SerializeManager:\n        return _SerializeManager(state, state_dict)\n    def _new_state_if_none(\n        self, instance: _O\n    ) -> Union[Literal[False], InstanceState[_O]]:\n        \"\"\"Install a default InstanceState if none is present.\n        A private convenience method used by the __init__ decorator.\n        \"\"\"\n        if hasattr(instance, self.STATE_ATTR):\n            return False\n        elif self.class_ is not instance.__class__ and self.is_mapped:\n            # this will create a new ClassManager for the\n            # subclass, without a mapper.  This is likely a\n            # user error situation but allow the object\n            # to be constructed, so that it is usable\n            # in a non-ORM context at least.\n            return self._subclass_manager(\n                instance.__class__\n            )._new_state_if_none(instance)\n        else:\n            state = self._state_constructor(instance, self)\n            self._state_setter(instance, state)\n            return state\n    def has_state(self, instance: _O) -> bool:\n        return hasattr(instance, self.STATE_ATTR)\n    def has_parent(\n        self, state: InstanceState[_O], key: str, optimistic: bool = False\n    ) -> bool:\n        \"\"\"TODO\"\"\"\n        return self.get_impl(key).hasparent(state, optimistic=optimistic)\n    def __bool__(self) -> bool:", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-11", "text": "def __bool__(self) -> bool:\n        \"\"\"All ClassManagers are non-zero regardless of attribute state.\"\"\"\n        return True\n    def __repr__(self) -> str:\n        return \"<%s of %r at %x>\" % (\n            self.__class__.__name__,\n            self.class_,\n            id(self),\n        )\nclass _SerializeManager:\n    \"\"\"Provide serialization of a :class:`.ClassManager`.\n    The :class:`.InstanceState` uses ``__init__()`` on serialize\n    and ``__call__()`` on deserialize.\n    \"\"\"\n    def __init__(self, state: state.InstanceState[Any], d: Dict[str, Any]):\n        self.class_ = state.class_\n        manager = state.manager\n        manager.dispatch.pickle(state, d)\n    def __call__(self, state, inst, state_dict):\n        state.manager = manager = opt_manager_of_class(self.class_)\n        if manager is None:\n            raise exc.UnmappedInstanceError(\n                inst,\n                \"Cannot deserialize object of type %r - \"\n                \"no mapper() has \"\n                \"been configured for this class within the current \"\n                \"Python process!\" % self.class_,\n            )\n        elif manager.is_mapped and not manager.mapper.configured:\n            manager.mapper._check_configure()\n        # setup _sa_instance_state ahead of time so that\n        # unpickle events can access the object normally.\n        # see [ticket:2362]\n        if inst is not None:\n            manager.setup_instance(inst, state)\n        manager.dispatch.unpickle(state, state_dict)\nclass InstrumentationFactory(EventTarget):\n    \"\"\"Factory for new ClassManager instances.\"\"\"\n    dispatch: dispatcher[InstrumentationFactory]", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-12", "text": "\"\"\"Factory for new ClassManager instances.\"\"\"\n    dispatch: dispatcher[InstrumentationFactory]\n    def create_manager_for_cls(self, class_: Type[_O]) -> ClassManager[_O]:\n        assert class_ is not None\n        assert opt_manager_of_class(class_) is None\n        # give a more complicated subclass\n        # a chance to do what it wants here\n        manager, factory = self._locate_extended_factory(class_)\n        if factory is None:\n            factory = ClassManager\n            manager = ClassManager(class_)\n        else:\n            assert manager is not None\n        self._check_conflicts(class_, factory)\n        manager.factory = factory\n        return manager\n    def _locate_extended_factory(\n        self, class_: Type[_O]\n    ) -> Tuple[Optional[ClassManager[_O]], Optional[_ManagerFactory]]:\n        \"\"\"Overridden by a subclass to do an extended lookup.\"\"\"\n        return None, None\n    def _check_conflicts(\n        self, class_: Type[_O], factory: Callable[[Type[_O]], ClassManager[_O]]\n    ) -> None:\n        \"\"\"Overridden by a subclass to test for conflicting factories.\"\"\"\n    def unregister(self, class_: Type[_O]) -> None:\n        manager = manager_of_class(class_)\n        manager.unregister()\n        self.dispatch.class_uninstrument(class_)\n# this attribute is replaced by sqlalchemy.ext.instrumentation\n# when imported.\n_instrumentation_factory = InstrumentationFactory()\n# these attributes are replaced by sqlalchemy.ext.instrumentation\n# when a non-standard InstrumentationManager class is first\n# used to instrument a class.\ninstance_state = _default_state_getter = base.instance_state\ninstance_dict = _default_dict_getter = base.instance_dict\nmanager_of_class = _default_manager_getter = base.manager_of_class", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-13", "text": "manager_of_class = _default_manager_getter = base.manager_of_class\nopt_manager_of_class = _default_opt_manager_getter = base.opt_manager_of_class\ndef register_class(\n    class_: Type[_O],\n    finalize: bool = True,\n    mapper: Optional[Mapper[_O]] = None,\n    registry: Optional[_RegistryType] = None,\n    declarative_scan: Optional[_MapperConfig] = None,\n    expired_attribute_loader: Optional[_ExpiredAttributeLoaderProto] = None,\n    init_method: Optional[Callable[..., None]] = None,\n) -> ClassManager[_O]:\n    \"\"\"Register class instrumentation.\n    Returns the existing or newly created class manager.\n    \"\"\"\n    manager = opt_manager_of_class(class_)\n    if manager is None:\n        manager = _instrumentation_factory.create_manager_for_cls(class_)\n    manager._update_state(\n        mapper=mapper,\n        registry=registry,\n        declarative_scan=declarative_scan,\n        expired_attribute_loader=expired_attribute_loader,\n        init_method=init_method,\n        finalize=finalize,\n    )\n    return manager\ndef unregister_class(class_):\n    \"\"\"Unregister class instrumentation.\"\"\"\n    _instrumentation_factory.unregister(class_)\ndef is_instrumented(instance, key):\n    \"\"\"Return True if the given attribute on the given instance is\n    instrumented by the attributes package.\n    This function may be used regardless of instrumentation\n    applied directly to the class, i.e. no descriptors are required.\n    \"\"\"\n    return manager_of_class(instance.__class__).is_instrumented(\n        key, search=True\n    )\ndef _generate_init(class_, class_manager, original_init):\n    \"\"\"Build an __init__ decorator that triggers ClassManager events.\"\"\"\n    # TODO: we should use the ClassManager's notion of the", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "e415edc200d2-14", "text": "# TODO: we should use the ClassManager's notion of the\n    # original '__init__' method, once ClassManager is fixed\n    # to always reference that.\n    if original_init is None:\n        original_init = class_.__init__\n    # Go through some effort here and don't change the user's __init__\n    # calling signature, including the unlikely case that it has\n    # a return value.\n    # FIXME: need to juggle local names to avoid constructor argument\n    # clashes.\n    func_body = \"\"\"\\\ndef __init__(%(apply_pos)s):\n    new_state = class_manager._new_state_if_none(%(self_arg)s)\n    if new_state:\n        return new_state._initialize_instance(%(apply_kw)s)\n    else:\n        return original_init(%(apply_kw)s)\n\"\"\"\n    func_vars = util.format_argspec_init(original_init, grouped=False)\n    func_text = func_body % func_vars\n    func_defaults = getattr(original_init, \"__defaults__\", None)\n    func_kw_defaults = getattr(original_init, \"__kwdefaults__\", None)\n    env = locals().copy()\n    env[\"__name__\"] = __name__\n    exec(func_text, env)\n    __init__ = env[\"__init__\"]\n    __init__.__doc__ = original_init.__doc__\n    __init__._sa_original_init = original_init\n    if func_defaults:\n        __init__.__defaults__ = func_defaults\n    if func_kw_defaults:\n        __init__.__kwdefaults__ = func_kw_defaults\n    return __init__", "source": "lang/api.python.langchain.com/en/latest/_modules/sqlalchemy/orm/instrumentation.html"}
{"id": "bcf74a8f2b9d-0", "text": "Source code for html.parser\n\"\"\"A parser for HTML and XHTML.\"\"\"\n# This file is based on sgmllib.py, but the API is slightly different.\n# XXX There should be a way to distinguish between PCDATA (parsed\n# character data -- the normal case), RCDATA (replaceable character\n# data -- only char and entity references and end tags are special)\n# and CDATA (character data -- only end tags are special).\nimport re\nimport _markupbase\nfrom html import unescape\n__all__ = ['HTMLParser']\n# Regular expressions used for parsing\ninteresting_normal = re.compile('[&<]')\nincomplete = re.compile('&[a-zA-Z#]')\nentityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')\ncharref = re.compile('&#(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]')\nstarttagopen = re.compile('<[a-zA-Z]')\npiclose = re.compile('>')\ncommentclose = re.compile(r'--\\s*>')\n# Note:\n#  1) if you change tagfind/attrfind remember to update locatestarttagend too;\n#  2) if you change tagfind/attrfind and/or locatestarttagend the parser will\n#     explode, so don't do it.\n# see http://www.w3.org/TR/html5/tokenization.html#tag-open-state\n# and http://www.w3.org/TR/html5/tokenization.html#tag-name-state\ntagfind_tolerant = re.compile(r'([a-zA-Z][^\\t\\n\\r\\f />\\x00]*)(?:\\s|/(?!>))*')\nattrfind_tolerant = re.compile(", "source": "lang/api.python.langchain.com/en/latest/_modules/html/parser.html"}
{"id": "bcf74a8f2b9d-1", "text": "attrfind_tolerant = re.compile(\n    r'((?<=[\\'\"\\s/])[^\\s/>][^\\s/=>]*)(\\s*=+\\s*'\n    r'(\\'[^\\']*\\'|\"[^\"]*\"|(?![\\'\"])[^>\\s]*))?(?:\\s|/(?!>))*')\nlocatestarttagend_tolerant = re.compile(r\"\"\"\n  <[a-zA-Z][^\\t\\n\\r\\f />\\x00]*       # tag name\n  (?:[\\s/]*                          # optional whitespace before attribute name\n    (?:(?<=['\"\\s/])[^\\s/>][^\\s/=>]*  # attribute name\n      (?:\\s*=+\\s*                    # value indicator\n        (?:'[^']*'                   # LITA-enclosed value\n          |\"[^\"]*\"                   # LIT-enclosed value\n          |(?!['\"])[^>\\s]*           # bare value\n         )\n        \\s*                          # possibly followed by a space\n       )?(?:\\s|/(?!>))*\n     )*\n   )?\n  \\s*                                # trailing whitespace\n\"\"\", re.VERBOSE)\nendendtag = re.compile('>')\n# the HTML 5 spec, section 8.1.2.2, doesn't allow spaces between\n# </ and the tag name, so maybe this should be fixed\nendtagfind = re.compile(r'</\\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\\s*>')\nclass HTMLParser(_markupbase.ParserBase):\n    \"\"\"Find tags and other markup and call handler functions.\n    Usage:\n        p = HTMLParser()\n        p.feed(data)\n        ...\n        p.close()\n    Start tags are handled by calling self.handle_starttag() or", "source": "lang/api.python.langchain.com/en/latest/_modules/html/parser.html"}
{"id": "bcf74a8f2b9d-2", "text": "p.close()\n    Start tags are handled by calling self.handle_starttag() or\n    self.handle_startendtag(); end tags by self.handle_endtag().  The\n    data between tags is passed from the parser to the derived class\n    by calling self.handle_data() with the data as argument (the data\n    may be split up in arbitrary chunks).  If convert_charrefs is\n    True the character references are converted automatically to the\n    corresponding Unicode character (and self.handle_data() is no\n    longer split in chunks), otherwise they are passed by calling\n    self.handle_entityref() or self.handle_charref() with the string\n    containing respectively the named or numeric reference as the\n    argument.\n    \"\"\"\n    CDATA_CONTENT_ELEMENTS = (\"script\", \"style\")\n    def __init__(self, *, convert_charrefs=True):\n        \"\"\"Initialize and reset this instance.\n        If convert_charrefs is True (the default), all character references\n        are automatically converted to the corresponding Unicode characters.\n        \"\"\"\n        self.convert_charrefs = convert_charrefs\n        self.reset()\n    def reset(self):\n        \"\"\"Reset this instance.  Loses all unprocessed data.\"\"\"\n        self.rawdata = ''\n        self.lasttag = '???'\n        self.interesting = interesting_normal\n        self.cdata_elem = None\n        _markupbase.ParserBase.reset(self)\n    def feed(self, data):\n        r\"\"\"Feed data to the parser.\n        Call this as often as you want, with as little or as much text\n        as you want (may include '\\n').\n        \"\"\"\n        self.rawdata = self.rawdata + data\n        self.goahead(0)\n    def close(self):\n        \"\"\"Handle any buffered data.\"\"\"\n        self.goahead(1)\n    __starttag_text = None", "source": "lang/api.python.langchain.com/en/latest/_modules/html/parser.html"}
{"id": "bcf74a8f2b9d-3", "text": "self.goahead(1)\n    __starttag_text = None\n    def get_starttag_text(self):\n        \"\"\"Return full source of start tag: '<...>'.\"\"\"\n        return self.__starttag_text\n    def set_cdata_mode(self, elem):\n        self.cdata_elem = elem.lower()\n        self.interesting = re.compile(r'</\\s*%s\\s*>' % self.cdata_elem, re.I)\n    def clear_cdata_mode(self):\n        self.interesting = interesting_normal\n        self.cdata_elem = None\n    # Internal -- handle data as far as reasonable.  May leave state\n    # and data to be processed by a subsequent call.  If 'end' is\n    # true, force handling all data as if followed by EOF marker.\n    def goahead(self, end):\n        rawdata = self.rawdata\n        i = 0\n        n = len(rawdata)\n        while i < n:\n            if self.convert_charrefs and not self.cdata_elem:\n                j = rawdata.find('<', i)\n                if j < 0:\n                    # if we can't find the next <, either we are at the end\n                    # or there's more text incoming.  If the latter is True,\n                    # we can't pass the text to handle_data in case we have\n                    # a charref cut in half at end.  Try to determine if\n                    # this is the case before proceeding by looking for an\n                    # & near the end and see if it's followed by a space or ;.\n                    amppos = rawdata.rfind('&', max(i, n-34))\n                    if (amppos >= 0 and\n                        not re.compile(r'[\\s;]').search(rawdata, amppos)):", "source": "lang/api.python.langchain.com/en/latest/_modules/html/parser.html"}
{"id": "bcf74a8f2b9d-4", "text": "not re.compile(r'[\\s;]').search(rawdata, amppos)):\n                        break  # wait till we get all the text\n                    j = n\n            else:\n                match = self.interesting.search(rawdata, i)  # < or &\n                if match:\n                    j = match.start()\n                else:\n                    if self.cdata_elem:\n                        break\n                    j = n\n            if i < j:\n                if self.convert_charrefs and not self.cdata_elem:\n                    self.handle_data(unescape(rawdata[i:j]))\n                else:\n                    self.handle_data(rawdata[i:j])\n            i = self.updatepos(i, j)\n            if i == n: break\n            startswith = rawdata.startswith\n            if startswith('<', i):\n                if starttagopen.match(rawdata, i): # < + letter\n                    k = self.parse_starttag(i)\n                elif startswith(\"</\", i):\n                    k = self.parse_endtag(i)\n                elif startswith(\"<!--\", i):\n                    k = self.parse_comment(i)\n                elif startswith(\"<?\", i):\n                    k = self.parse_pi(i)\n                elif startswith(\"<!\", i):\n                    k = self.parse_html_declaration(i)\n                elif (i + 1) < n:\n                    self.handle_data(\"<\")\n                    k = i + 1\n                else:\n                    break\n                if k < 0:\n                    if not end:\n                        break\n                    k = rawdata.find('>', i + 1)\n                    if k < 0:\n                        k = rawdata.find('<', i + 1)\n                        if k < 0:\n                            k = i + 1\n                    else:\n                        k += 1", "source": "lang/api.python.langchain.com/en/latest/_modules/html/parser.html"}
{"id": "bcf74a8f2b9d-5", "text": "k = i + 1\n                    else:\n                        k += 1\n                    if self.convert_charrefs and not self.cdata_elem:\n                        self.handle_data(unescape(rawdata[i:k]))\n                    else:\n                        self.handle_data(rawdata[i:k])\n                i = self.updatepos(i, k)\n            elif startswith(\"&#\", i):\n                match = charref.match(rawdata, i)\n                if match:\n                    name = match.group()[2:-1]\n                    self.handle_charref(name)\n                    k = match.end()\n                    if not startswith(';', k-1):\n                        k = k - 1\n                    i = self.updatepos(i, k)\n                    continue\n                else:\n                    if \";\" in rawdata[i:]:  # bail by consuming &#\n                        self.handle_data(rawdata[i:i+2])\n                        i = self.updatepos(i, i+2)\n                    break\n            elif startswith('&', i):\n                match = entityref.match(rawdata, i)\n                if match:\n                    name = match.group(1)\n                    self.handle_entityref(name)\n                    k = match.end()\n                    if not startswith(';', k-1):\n                        k = k - 1\n                    i = self.updatepos(i, k)\n                    continue\n                match = incomplete.match(rawdata, i)\n                if match:\n                    # match.group() will contain at least 2 chars\n                    if end and match.group() == rawdata[i:]:\n                        k = match.end()\n                        if k <= i:\n                            k = n\n                        i = self.updatepos(i, i + 1)\n                    # incomplete\n                    break\n                elif (i + 1) < n:\n                    # not the end of the buffer, and can't be confused", "source": "lang/api.python.langchain.com/en/latest/_modules/html/parser.html"}
{"id": "bcf74a8f2b9d-6", "text": "# not the end of the buffer, and can't be confused\n                    # with some other construct\n                    self.handle_data(\"&\")\n                    i = self.updatepos(i, i + 1)\n                else:\n                    break\n            else:\n                assert 0, \"interesting.search() lied\"\n        # end while\n        if end and i < n and not self.cdata_elem:\n            if self.convert_charrefs and not self.cdata_elem:\n                self.handle_data(unescape(rawdata[i:n]))\n            else:\n                self.handle_data(rawdata[i:n])\n            i = self.updatepos(i, n)\n        self.rawdata = rawdata[i:]\n    # Internal -- parse html declarations, return length or -1 if not terminated\n    # See w3.org/TR/html5/tokenization.html#markup-declaration-open-state\n    # See also parse_declaration in _markupbase\n    def parse_html_declaration(self, i):\n        rawdata = self.rawdata\n        assert rawdata[i:i+2] == '<!', ('unexpected call to '\n                                        'parse_html_declaration()')\n        if rawdata[i:i+4] == '<!--':\n            # this case is actually already handled in goahead()\n            return self.parse_comment(i)\n        elif rawdata[i:i+3] == '<![':\n            return self.parse_marked_section(i)\n        elif rawdata[i:i+9].lower() == '<!doctype':\n            # find the closing >\n            gtpos = rawdata.find('>', i+9)\n            if gtpos == -1:\n                return -1\n            self.handle_decl(rawdata[i+2:gtpos])\n            return gtpos+1\n        else:\n            return self.parse_bogus_comment(i)", "source": "lang/api.python.langchain.com/en/latest/_modules/html/parser.html"}
{"id": "bcf74a8f2b9d-7", "text": "else:\n            return self.parse_bogus_comment(i)\n    # Internal -- parse bogus comment, return length or -1 if not terminated\n    # see http://www.w3.org/TR/html5/tokenization.html#bogus-comment-state\n    def parse_bogus_comment(self, i, report=1):\n        rawdata = self.rawdata\n        assert rawdata[i:i+2] in ('<!', '</'), ('unexpected call to '\n                                                'parse_comment()')\n        pos = rawdata.find('>', i+2)\n        if pos == -1:\n            return -1\n        if report:\n            self.handle_comment(rawdata[i+2:pos])\n        return pos + 1\n    # Internal -- parse processing instr, return end or -1 if not terminated\n    def parse_pi(self, i):\n        rawdata = self.rawdata\n        assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'\n        match = piclose.search(rawdata, i+2) # >\n        if not match:\n            return -1\n        j = match.start()\n        self.handle_pi(rawdata[i+2: j])\n        j = match.end()\n        return j\n    # Internal -- handle starttag, return end or -1 if not terminated\n    def parse_starttag(self, i):\n        self.__starttag_text = None\n        endpos = self.check_for_whole_start_tag(i)\n        if endpos < 0:\n            return endpos\n        rawdata = self.rawdata\n        self.__starttag_text = rawdata[i:endpos]\n        # Now parse the data between i+1 and j into a tag and attrs\n        attrs = []\n        match = tagfind_tolerant.match(rawdata, i+1)", "source": "lang/api.python.langchain.com/en/latest/_modules/html/parser.html"}
{"id": "bcf74a8f2b9d-8", "text": "match = tagfind_tolerant.match(rawdata, i+1)\n        assert match, 'unexpected call to parse_starttag()'\n        k = match.end()\n        self.lasttag = tag = match.group(1).lower()\n        while k < endpos:\n            m = attrfind_tolerant.match(rawdata, k)\n            if not m:\n                break\n            attrname, rest, attrvalue = m.group(1, 2, 3)\n            if not rest:\n                attrvalue = None\n            elif attrvalue[:1] == '\\'' == attrvalue[-1:] or \\\n                 attrvalue[:1] == '\"' == attrvalue[-1:]:\n                attrvalue = attrvalue[1:-1]\n            if attrvalue:\n                attrvalue = unescape(attrvalue)\n            attrs.append((attrname.lower(), attrvalue))\n            k = m.end()\n        end = rawdata[k:endpos].strip()\n        if end not in (\">\", \"/>\"):\n            self.handle_data(rawdata[i:endpos])\n            return endpos\n        if end.endswith('/>'):\n            # XHTML-style empty tag: <span attr=\"value\" />\n            self.handle_startendtag(tag, attrs)\n        else:\n            self.handle_starttag(tag, attrs)\n            if tag in self.CDATA_CONTENT_ELEMENTS:\n                self.set_cdata_mode(tag)\n        return endpos\n    # Internal -- check to see if we have a complete starttag; return end\n    # or -1 if incomplete.\n    def check_for_whole_start_tag(self, i):\n        rawdata = self.rawdata\n        m = locatestarttagend_tolerant.match(rawdata, i)\n        if m:\n            j = m.end()\n            next = rawdata[j:j+1]", "source": "lang/api.python.langchain.com/en/latest/_modules/html/parser.html"}
{"id": "bcf74a8f2b9d-9", "text": "j = m.end()\n            next = rawdata[j:j+1]\n            if next == \">\":\n                return j + 1\n            if next == \"/\":\n                if rawdata.startswith(\"/>\", j):\n                    return j + 2\n                if rawdata.startswith(\"/\", j):\n                    # buffer boundary\n                    return -1\n                # else bogus input\n                if j > i:\n                    return j\n                else:\n                    return i + 1\n            if next == \"\":\n                # end of input\n                return -1\n            if next in (\"abcdefghijklmnopqrstuvwxyz=/\"\n                        \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"):\n                # end of input in or before attribute value, or we have the\n                # '/' from a '/>' ending\n                return -1\n            if j > i:\n                return j\n            else:\n                return i + 1\n        raise AssertionError(\"we should not get here!\")\n    # Internal -- parse endtag, return end or -1 if incomplete\n    def parse_endtag(self, i):\n        rawdata = self.rawdata\n        assert rawdata[i:i+2] == \"</\", \"unexpected call to parse_endtag\"\n        match = endendtag.search(rawdata, i+1) # >\n        if not match:\n            return -1\n        gtpos = match.end()\n        match = endtagfind.match(rawdata, i) # </ + tag + >\n        if not match:\n            if self.cdata_elem is not None:\n                self.handle_data(rawdata[i:gtpos])\n                return gtpos\n            # find the name: w3.org/TR/html5/tokenization.html#tag-name-state\n            namematch = tagfind_tolerant.match(rawdata, i+2)\n            if not namematch:", "source": "lang/api.python.langchain.com/en/latest/_modules/html/parser.html"}
{"id": "bcf74a8f2b9d-10", "text": "if not namematch:\n                # w3.org/TR/html5/tokenization.html#end-tag-open-state\n                if rawdata[i:i+3] == '</>':\n                    return i+3\n                else:\n                    return self.parse_bogus_comment(i)\n            tagname = namematch.group(1).lower()\n            # consume and ignore other stuff between the name and the >\n            # Note: this is not 100% correct, since we might have things like\n            # </tag attr=\">\">, but looking for > after the name should cover\n            # most of the cases and is much simpler\n            gtpos = rawdata.find('>', namematch.end())\n            self.handle_endtag(tagname)\n            return gtpos+1\n        elem = match.group(1).lower() # script or style\n        if self.cdata_elem is not None:\n            if elem != self.cdata_elem:\n                self.handle_data(rawdata[i:gtpos])\n                return gtpos\n        self.handle_endtag(elem)\n        self.clear_cdata_mode()\n        return gtpos\n    # Overridable -- finish processing of start+end tag: <tag.../>\n    def handle_startendtag(self, tag, attrs):\n        self.handle_starttag(tag, attrs)\n        self.handle_endtag(tag)\n    # Overridable -- handle start tag\n    def handle_starttag(self, tag, attrs):\n        pass\n    # Overridable -- handle end tag\n    def handle_endtag(self, tag):\n        pass\n    # Overridable -- handle character reference\n    def handle_charref(self, name):\n        pass\n    # Overridable -- handle entity reference\n    def handle_entityref(self, name):\n        pass\n    # Overridable -- handle data", "source": "lang/api.python.langchain.com/en/latest/_modules/html/parser.html"}
{"id": "bcf74a8f2b9d-11", "text": "pass\n    # Overridable -- handle data\n    def handle_data(self, data):\n        pass\n    # Overridable -- handle comment\n    def handle_comment(self, data):\n        pass\n    # Overridable -- handle declaration\n    def handle_decl(self, decl):\n        pass\n    # Overridable -- handle processing instruction\n    def handle_pi(self, data):\n        pass\n    def unknown_decl(self, data):\n        pass", "source": "lang/api.python.langchain.com/en/latest/_modules/html/parser.html"}
{"id": "229dac6b9424-0", "text": "Source code for langchain_experimental.utilities.python\nimport functools\nimport logging\nimport multiprocessing\nimport sys\nfrom io import StringIO\nfrom typing import Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel, Field\nlogger = logging.getLogger(__name__)\n@functools.lru_cache(maxsize=None)\ndef warn_once() -> None:\n    \"\"\"Warn once about the dangers of PythonREPL.\"\"\"\n    logger.warning(\"Python REPL can execute arbitrary code. Use with caution.\")\n[docs]class PythonREPL(BaseModel):\n    \"\"\"Simulates a standalone Python REPL.\"\"\"\n    globals: Optional[Dict] = Field(default_factory=dict, alias=\"_globals\")\n    locals: Optional[Dict] = Field(default_factory=dict, alias=\"_locals\")\n[docs]    @classmethod\n    def worker(\n        cls,\n        command: str,\n        globals: Optional[Dict],\n        locals: Optional[Dict],\n        queue: multiprocessing.Queue,\n    ) -> None:\n        old_stdout = sys.stdout\n        sys.stdout = mystdout = StringIO()\n        try:\n            exec(command, globals, locals)\n            sys.stdout = old_stdout\n            queue.put(mystdout.getvalue())\n        except Exception as e:\n            sys.stdout = old_stdout\n            queue.put(repr(e))\n[docs]    def run(self, command: str, timeout: Optional[int] = None) -> str:\n        \"\"\"Run command with own globals/locals and returns anything printed.\n        Timeout after the specified number of seconds.\"\"\"\n        # Warn against dangers of PythonREPL\n        warn_once()\n        queue: multiprocessing.Queue = multiprocessing.Queue()\n        # Only use multiprocessing if we are enforcing a timeout\n        if timeout is not None:\n            # create a Process\n            p = multiprocessing.Process(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/utilities/python.html"}
{"id": "229dac6b9424-1", "text": "# create a Process\n            p = multiprocessing.Process(\n                target=self.worker, args=(command, self.globals, self.locals, queue)\n            )\n            # start it\n            p.start()\n            # wait for the process to finish or kill it after timeout seconds\n            p.join(timeout)\n            if p.is_alive():\n                p.terminate()\n                return \"Execution timed out\"\n        else:\n            self.worker(command, self.globals, self.locals, queue)\n        # get the result from the worker function\n        return queue.get()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/utilities/python.html"}
{"id": "3520f0278269-0", "text": "Source code for langchain_experimental.pal_chain.base\n\"\"\"Implements Program-Aided Language Models.\nThis module implements the Program-Aided Language Models (PAL) for generating code\nsolutions. PAL is a technique described in the paper \"Program-Aided Language Models\"\n(https://arxiv.org/pdf/2211.10435.pdf).\n\"\"\"\nfrom __future__ import annotations\nimport ast\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.utilities import PythonREPL\nfrom langchain_experimental.pal_chain.colored_object_prompt import COLORED_OBJECT_PROMPT\nfrom langchain_experimental.pal_chain.math_prompt import MATH_PROMPT\nfrom langchain_experimental.pydantic_v1 import Extra, Field\nCOMMAND_EXECUTION_FUNCTIONS = [\"system\", \"exec\", \"execfile\", \"eval\", \"__import__\"]\n[docs]class PALValidation:\n    SOLUTION_EXPRESSION_TYPE_FUNCTION = ast.FunctionDef\n    SOLUTION_EXPRESSION_TYPE_VARIABLE = ast.Name\n[docs]    def __init__(\n        self,\n        solution_expression_name: Optional[str] = None,\n        solution_expression_type: Optional[type] = None,\n        allow_imports: bool = False,\n        allow_command_exec: bool = False,\n    ):\n        \"\"\"Initialize a PALValidation instance.\n        Args:\n            solution_expression_name (str): Name of the expected solution expression.\n                If passed, solution_expression_type must be passed as well.\n            solution_expression_type (str): AST type of the expected solution\n                expression. If passed, solution_expression_name must be passed as well.\n                Must be one of PALValidation.SOLUTION_EXPRESSION_TYPE_FUNCTION,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html"}
{"id": "3520f0278269-1", "text": "Must be one of PALValidation.SOLUTION_EXPRESSION_TYPE_FUNCTION,\n                PALValidation.SOLUTION_EXPRESSION_TYPE_VARIABLE.\n            allow_imports (bool): Allow import statements.\n            allow_command_exec (bool): Allow using known command execution functions.\n        \"\"\"\n        self.solution_expression_name = solution_expression_name\n        self.solution_expression_type = solution_expression_type\n        if solution_expression_name is not None:\n            if not isinstance(self.solution_expression_name, str):\n                raise ValueError(\n                    f\"Expected solution_expression_name to be str, \"\n                    f\"instead found {type(self.solution_expression_name)}\"\n                )\n        if solution_expression_type is not None:\n            if (\n                self.solution_expression_type\n                is not self.SOLUTION_EXPRESSION_TYPE_FUNCTION\n                and self.solution_expression_type\n                is not self.SOLUTION_EXPRESSION_TYPE_VARIABLE\n            ):\n                raise ValueError(\n                    f\"Expected solution_expression_type to be one of \"\n                    f\"({self.SOLUTION_EXPRESSION_TYPE_FUNCTION},\"\n                    f\"{self.SOLUTION_EXPRESSION_TYPE_VARIABLE}),\"\n                    f\"instead found {self.solution_expression_type}\"\n                )\n        if solution_expression_name is not None and solution_expression_type is None:\n            raise TypeError(\n                \"solution_expression_name \"\n                \"requires solution_expression_type to be passed as well\"\n            )\n        if solution_expression_name is None and solution_expression_type is not None:\n            raise TypeError(\n                \"solution_expression_type \"\n                \"requires solution_expression_name to be passed as well\"\n            )\n        self.allow_imports = allow_imports\n        self.allow_command_exec = allow_command_exec\n[docs]class PALChain(Chain):\n    \"\"\"Implements Program-Aided Language Models (PAL).\n    This class implements the Program-Aided Language Models (PAL) for generating code", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html"}
{"id": "3520f0278269-2", "text": "This class implements the Program-Aided Language Models (PAL) for generating code\n    solutions. PAL is a technique described in the paper \"Program-Aided Language Models\"\n    (https://arxiv.org/pdf/2211.10435.pdf).\n    *Security note*: This class implements an AI technique that generates and evaluates\n        Python code, which can be dangerous and requires a specially sandboxed\n        environment to be safely used. While this class implements some basic guardrails\n        by limiting available locals/globals and by parsing and inspecting\n        the generated Python AST using `PALValidation`, those guardrails will not\n        deter sophisticated attackers and are not a replacement for a proper sandbox.\n        Do not use this class on untrusted inputs, with elevated permissions,\n        or without consulting your security team about proper sandboxing!\n    \"\"\"\n    llm_chain: LLMChain\n    stop: str = \"\\n\\n\"\n    \"\"\"Stop token to use when generating code.\"\"\"\n    get_answer_expr: str = \"print(solution())\"\n    \"\"\"Expression to use to get the answer from the generated code.\"\"\"\n    python_globals: Optional[Dict[str, Any]] = None\n    \"\"\"Python globals and locals to use when executing the generated code.\"\"\"\n    python_locals: Optional[Dict[str, Any]] = None\n    \"\"\"Python globals and locals to use when executing the generated code.\"\"\"\n    output_key: str = \"result\"  #: :meta private:\n    return_intermediate_steps: bool = False\n    \"\"\"Whether to return intermediate steps in the generated code.\"\"\"\n    code_validations: PALValidation = Field(default_factory=PALValidation)\n    \"\"\"Validations to perform on the generated code.\"\"\"\n    timeout: Optional[int] = 10\n    \"\"\"Timeout in seconds for the generated code to execute.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html"}
{"id": "3520f0278269-3", "text": "class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the singular input key.\n        :meta private:\n        \"\"\"\n        return self.llm_chain.prompt.input_variables\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the singular output key.\n        :meta private:\n        \"\"\"\n        if not self.return_intermediate_steps:\n            return [self.output_key]\n        else:\n            return [self.output_key, \"intermediate_steps\"]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        code = self.llm_chain.predict(\n            stop=[self.stop], callbacks=_run_manager.get_child(), **inputs\n        )\n        _run_manager.on_text(code, color=\"green\", end=\"\\n\", verbose=self.verbose)\n        PALChain.validate_code(code, self.code_validations)\n        # TODO: look into why mypy thinks PythonREPL's type here is `Any`\n        #       and therefore not callable\n        repl = PythonREPL(\n            _globals=self.python_globals,\n            _locals=self.python_locals,\n        )  # type: ignore[misc]\n        res = repl.run(code + f\"\\n{self.get_answer_expr}\", timeout=self.timeout)\n        output = {self.output_key: res.strip()}\n        if self.return_intermediate_steps:\n            output[\"intermediate_steps\"] = code\n        return output\n[docs]    @classmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html"}
{"id": "3520f0278269-4", "text": "return output\n[docs]    @classmethod\n    def validate_code(cls, code: str, code_validations: PALValidation) -> None:\n        try:\n            code_tree = ast.parse(code)\n        except (SyntaxError, UnicodeDecodeError):\n            raise ValueError(f\"Generated code is not valid python code: {code}\")\n        except TypeError:\n            raise ValueError(\n                f\"Generated code is expected to be a string, \"\n                f\"instead found {type(code)}\"\n            )\n        except OverflowError:\n            raise ValueError(\n                f\"Generated code too long / complex to be parsed by ast: {code}\"\n            )\n        found_solution_expr = False\n        if code_validations.solution_expression_name is None:\n            # Skip validation if no solution_expression_name was given\n            found_solution_expr = True\n        has_imports = False\n        top_level_nodes = list(ast.iter_child_nodes(code_tree))\n        for node in top_level_nodes:\n            if (\n                code_validations.solution_expression_name is not None\n                and code_validations.solution_expression_type is not None\n            ):\n                # Check root nodes (like func def)\n                if (\n                    isinstance(node, code_validations.solution_expression_type)\n                    and hasattr(node, \"name\")\n                    and node.name == code_validations.solution_expression_name\n                ):\n                    found_solution_expr = True\n                # Check assigned nodes (like answer variable)\n                if isinstance(node, ast.Assign):\n                    for target_node in node.targets:\n                        if (\n                            isinstance(\n                                target_node, code_validations.solution_expression_type\n                            )\n                            and hasattr(target_node, \"id\")\n                            and target_node.id\n                            == code_validations.solution_expression_name\n                        ):\n                            found_solution_expr = True", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html"}
{"id": "3520f0278269-5", "text": "== code_validations.solution_expression_name\n                        ):\n                            found_solution_expr = True\n            if isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom):\n                has_imports = True\n        if not found_solution_expr:\n            raise ValueError(\n                f\"Generated code is missing the solution expression: \"\n                f\"{code_validations.solution_expression_name} of type: \"\n                f\"{code_validations.solution_expression_type}\"\n            )\n        if not code_validations.allow_imports and has_imports:\n            raise ValueError(f\"Generated code has disallowed imports: {code}\")\n        if (\n            not code_validations.allow_command_exec\n            or not code_validations.allow_imports\n        ):\n            for node in ast.walk(code_tree):\n                if (not code_validations.allow_command_exec) and isinstance(\n                    node, ast.Call\n                ):\n                    if (\n                        hasattr(node.func, \"id\")\n                        and node.func.id in COMMAND_EXECUTION_FUNCTIONS\n                    ):\n                        raise ValueError(\n                            f\"Found illegal command execution function \"\n                            f\"{node.func.id} in code {code}\"\n                        )\n                    if (\n                        isinstance(node.func, ast.Attribute)\n                        and node.func.attr in COMMAND_EXECUTION_FUNCTIONS\n                    ):\n                        raise ValueError(\n                            f\"Found illegal command execution function \"\n                            f\"{node.func.attr} in code {code}\"\n                        )\n                if (not code_validations.allow_imports) and (\n                    isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom)\n                ):\n                    raise ValueError(f\"Generated code has disallowed imports: {code}\")\n[docs]    @classmethod\n    def from_math_prompt(cls, llm: BaseLanguageModel, **kwargs: Any) -> PALChain:\n        \"\"\"Load PAL from math prompt.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html"}
{"id": "3520f0278269-6", "text": "\"\"\"Load PAL from math prompt.\n        Args:\n            llm (BaseLanguageModel): The language model to use for generating code.\n        Returns:\n            PALChain: An instance of PALChain.\n        \"\"\"\n        llm_chain = LLMChain(llm=llm, prompt=MATH_PROMPT)\n        code_validations = PALValidation(\n            solution_expression_name=\"solution\",\n            solution_expression_type=PALValidation.SOLUTION_EXPRESSION_TYPE_FUNCTION,\n        )\n        return cls(\n            llm_chain=llm_chain,\n            stop=\"\\n\\n\",\n            get_answer_expr=\"print(solution())\",\n            code_validations=code_validations,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_colored_object_prompt(\n        cls, llm: BaseLanguageModel, **kwargs: Any\n    ) -> PALChain:\n        \"\"\"Load PAL from colored object prompt.\n        Args:\n            llm (BaseLanguageModel): The language model to use for generating code.\n        Returns:\n            PALChain: An instance of PALChain.\n        \"\"\"\n        llm_chain = LLMChain(llm=llm, prompt=COLORED_OBJECT_PROMPT)\n        code_validations = PALValidation(\n            solution_expression_name=\"answer\",\n            solution_expression_type=PALValidation.SOLUTION_EXPRESSION_TYPE_VARIABLE,\n        )\n        return cls(\n            llm_chain=llm_chain,\n            stop=\"\\n\\n\\n\",\n            get_answer_expr=\"print(answer)\",\n            code_validations=code_validations,\n            **kwargs,\n        )\n    @property\n    def _chain_type(self) -> str:\n        return \"pal_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html"}
{"id": "d409db8b99c8-0", "text": "Source code for langchain_experimental.tools.python.tool\n\"\"\"A tool for running python code in a REPL.\"\"\"\nimport ast\nimport asyncio\nimport re\nimport sys\nfrom contextlib import redirect_stdout\nfrom io import StringIO\nfrom typing import Any, Dict, Optional, Type\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field, root_validator\nfrom langchain.tools.base import BaseTool\nfrom langchain_experimental.utilities.python import PythonREPL\ndef _get_default_python_repl() -> PythonREPL:\n    return PythonREPL(_globals=globals(), _locals=None)\n[docs]def sanitize_input(query: str) -> str:\n    \"\"\"Sanitize input to the python REPL.\n    Remove whitespace, backtick & python (if llm mistakes python console as terminal)\n    Args:\n        query: The query to sanitize\n    Returns:\n        str: The sanitized query\n    \"\"\"\n    # Removes `, whitespace & python from start\n    query = re.sub(r\"^(\\s|`)*(?i:python)?\\s*\", \"\", query)\n    # Removes whitespace & ` from end\n    query = re.sub(r\"(\\s|`)*$\", \"\", query)\n    return query\n[docs]class PythonREPLTool(BaseTool):\n    \"\"\"A tool for running python code in a REPL.\"\"\"\n    name: str = \"Python_REPL\"\n    description: str = (\n        \"A Python shell. Use this to execute python commands. \"\n        \"Input should be a valid python command. \"\n        \"If you want to see the output of a value, you should print it out \"\n        \"with `print(...)`.\"\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tools/python/tool.html"}
{"id": "d409db8b99c8-1", "text": "\"with `print(...)`.\"\n    )\n    python_repl: PythonREPL = Field(default_factory=_get_default_python_repl)\n    sanitize_input: bool = True\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> Any:\n        \"\"\"Use the tool.\"\"\"\n        if self.sanitize_input:\n            query = sanitize_input(query)\n        return self.python_repl.run(query)\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> Any:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        if self.sanitize_input:\n            query = sanitize_input(query)\n        loop = asyncio.get_running_loop()\n        result = await loop.run_in_executor(None, self.run, query)\n        return result\n[docs]class PythonInputs(BaseModel):\n    query: str = Field(description=\"code snippet to run\")\n[docs]class PythonAstREPLTool(BaseTool):\n    \"\"\"A tool for running python code in a REPL.\"\"\"\n    name: str = \"python_repl_ast\"\n    description: str = (\n        \"A Python shell. Use this to execute python commands. \"\n        \"Input should be a valid python command. \"\n        \"When using this tool, sometimes output is abbreviated - \"\n        \"make sure it does not look abbreviated before using it in your answer.\"\n    )\n    globals: Optional[Dict] = Field(default_factory=dict)\n    locals: Optional[Dict] = Field(default_factory=dict)\n    sanitize_input: bool = True\n    args_schema: Type[BaseModel] = PythonInputs\n    @root_validator(pre=True)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tools/python/tool.html"}
{"id": "d409db8b99c8-2", "text": "@root_validator(pre=True)\n    def validate_python_version(cls, values: Dict) -> Dict:\n        \"\"\"Validate valid python version.\"\"\"\n        if sys.version_info < (3, 9):\n            raise ValueError(\n                \"This tool relies on Python 3.9 or higher \"\n                \"(as it uses new functionality in the `ast` module, \"\n                f\"you have Python version: {sys.version}\"\n            )\n        return values\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        try:\n            if self.sanitize_input:\n                query = sanitize_input(query)\n            tree = ast.parse(query)\n            module = ast.Module(tree.body[:-1], type_ignores=[])\n            exec(ast.unparse(module), self.globals, self.locals)  # type: ignore\n            module_end = ast.Module(tree.body[-1:], type_ignores=[])\n            module_end_str = ast.unparse(module_end)  # type: ignore\n            io_buffer = StringIO()\n            try:\n                with redirect_stdout(io_buffer):\n                    ret = eval(module_end_str, self.globals, self.locals)\n                    if ret is None:\n                        return io_buffer.getvalue()\n                    else:\n                        return ret\n            except Exception:\n                with redirect_stdout(io_buffer):\n                    exec(module_end_str, self.globals, self.locals)\n                return io_buffer.getvalue()\n        except Exception as e:\n            return \"{}: {}\".format(type(e).__name__, str(e))\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> Any:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tools/python/tool.html"}
{"id": "d409db8b99c8-3", "text": ") -> Any:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        loop = asyncio.get_running_loop()\n        result = await loop.run_in_executor(None, self._run, query)\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tools/python/tool.html"}
{"id": "6e6146e4a537-0", "text": "Source code for langchain_experimental.sql.vector_sql\n\"\"\"Vector SQL Database Chain Retriever\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional, Sequence, Union\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.sql_database.prompt import PROMPT, SQL_PROMPTS\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.schema import BaseOutputParser, BasePromptTemplate\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools.sql_database.prompt import QUERY_CHECKER\nfrom langchain.utilities.sql_database import SQLDatabase\nfrom langchain_experimental.sql.base import INTERMEDIATE_STEPS_KEY, SQLDatabaseChain\n[docs]class VectorSQLOutputParser(BaseOutputParser[str]):\n    \"\"\"Output Parser for Vector SQL\n    1. finds for `NeuralArray()` and replace it with the embedding\n    2. finds for `DISTANCE()` and replace it with the distance name in backend SQL\n    \"\"\"\n    model: Embeddings\n    \"\"\"Embedding model to extract embedding for entity\"\"\"\n    distance_func_name: str = \"distance\"\n    \"\"\"Distance name for Vector SQL\"\"\"\n    class Config:\n        arbitrary_types_allowed = 1\n    @property\n    def _type(self) -> str:\n        return \"vector_sql_parser\"\n[docs]    @classmethod\n    def from_embeddings(\n        cls, model: Embeddings, distance_func_name: str = \"distance\", **kwargs: Any\n    ) -> BaseOutputParser:\n        return cls(model=model, distance_func_name=distance_func_name, **kwargs)\n[docs]    def parse(self, text: str) -> str:\n        text = text.strip()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/vector_sql.html"}
{"id": "6e6146e4a537-1", "text": "text = text.strip()\n        start = text.find(\"NeuralArray(\")\n        _sql_str_compl = text\n        if start > 0:\n            _matched = text[text.find(\"NeuralArray(\") + len(\"NeuralArray(\") :]\n            end = _matched.find(\")\") + start + len(\"NeuralArray(\") + 1\n            entity = _matched[: _matched.find(\")\")]\n            vecs = self.model.embed_query(entity)\n            vecs_str = \"[\" + \",\".join(map(str, vecs)) + \"]\"\n            _sql_str_compl = text.replace(\"DISTANCE\", self.distance_func_name).replace(\n                text[start:end], vecs_str\n            )\n            if _sql_str_compl[-1] == \";\":\n                _sql_str_compl = _sql_str_compl[:-1]\n        return _sql_str_compl\n[docs]class VectorSQLRetrieveAllOutputParser(VectorSQLOutputParser):\n    \"\"\"Based on VectorSQLOutputParser\n    It also modify the SQL to get all columns\n    \"\"\"\n    @property\n    def _type(self) -> str:\n        return \"vector_sql_retrieve_all_parser\"\n[docs]    def parse(self, text: str) -> str:\n        text = text.strip()\n        start = text.upper().find(\"SELECT\")\n        if start >= 0:\n            end = text.upper().find(\"FROM\")\n            text = text.replace(text[start + len(\"SELECT\") + 1 : end - 1], \"*\")\n        return super().parse(text)\n[docs]def get_result_from_sqldb(db: SQLDatabase, cmd: str) -> Sequence[Dict[str, Any]]:\n    result = db._execute(cmd, fetch=\"all\")\n    return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/vector_sql.html"}
{"id": "6e6146e4a537-2", "text": "result = db._execute(cmd, fetch=\"all\")\n    return result\n[docs]class VectorSQLDatabaseChain(SQLDatabaseChain):\n    \"\"\"Chain for interacting with Vector SQL Database.\n    Example:\n        .. code-block:: python\n            from langchain_experimental.sql import SQLDatabaseChain\n            from langchain.llms import OpenAI, SQLDatabase, OpenAIEmbeddings\n            db = SQLDatabase(...)\n            db_chain = VectorSQLDatabaseChain.from_llm(OpenAI(), db, OpenAIEmbeddings())\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include the permissions this chain needs.\n        Failure to do so may result in data corruption or loss, since this chain may\n        attempt commands like `DROP TABLE` or `INSERT` if appropriately prompted.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this chain.\n        This issue shows an example negative outcome if these steps are not taken:\n        https://github.com/langchain-ai/langchain/issues/5923\n    \"\"\"\n    sql_cmd_parser: VectorSQLOutputParser\n    \"\"\"Parser for Vector SQL\"\"\"\n    native_format: bool = False\n    \"\"\"If return_direct, controls whether to return in python native format\"\"\"\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        input_text = f\"{inputs[self.input_key]}\\nSQLQuery:\"\n        _run_manager.on_text(input_text, verbose=self.verbose)\n        # If not present, then defaults to None which is all tables.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/vector_sql.html"}
{"id": "6e6146e4a537-3", "text": "# If not present, then defaults to None which is all tables.\n        table_names_to_use = inputs.get(\"table_names_to_use\")\n        table_info = self.database.get_table_info(table_names=table_names_to_use)\n        llm_inputs = {\n            \"input\": input_text,\n            \"top_k\": str(self.top_k),\n            \"dialect\": self.database.dialect,\n            \"table_info\": table_info,\n            \"stop\": [\"\\nSQLResult:\"],\n        }\n        intermediate_steps: List = []\n        try:\n            intermediate_steps.append(llm_inputs)  # input: sql generation\n            llm_out = self.llm_chain.predict(\n                callbacks=_run_manager.get_child(),\n                **llm_inputs,\n            )\n            sql_cmd = self.sql_cmd_parser.parse(llm_out)\n            if self.return_sql:\n                return {self.output_key: sql_cmd}\n            if not self.use_query_checker:\n                _run_manager.on_text(llm_out, color=\"green\", verbose=self.verbose)\n                intermediate_steps.append(\n                    llm_out\n                )  # output: sql generation (no checker)\n                intermediate_steps.append({\"sql_cmd\": llm_out})  # input: sql exec\n                result = get_result_from_sqldb(self.database, sql_cmd)\n                intermediate_steps.append(str(result))  # output: sql exec\n            else:\n                query_checker_prompt = self.query_checker_prompt or PromptTemplate(\n                    template=QUERY_CHECKER, input_variables=[\"query\", \"dialect\"]\n                )\n                query_checker_chain = LLMChain(\n                    llm=self.llm_chain.llm,\n                    prompt=query_checker_prompt,\n                    output_parser=self.llm_chain.output_parser,\n                )\n                query_checker_inputs = {\n                    \"query\": llm_out,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/vector_sql.html"}
{"id": "6e6146e4a537-4", "text": ")\n                query_checker_inputs = {\n                    \"query\": llm_out,\n                    \"dialect\": self.database.dialect,\n                }\n                checked_llm_out = query_checker_chain.predict(\n                    callbacks=_run_manager.get_child(), **query_checker_inputs\n                )\n                checked_sql_command = self.sql_cmd_parser.parse(checked_llm_out)\n                intermediate_steps.append(\n                    checked_llm_out\n                )  # output: sql generation (checker)\n                _run_manager.on_text(\n                    checked_llm_out, color=\"green\", verbose=self.verbose\n                )\n                intermediate_steps.append(\n                    {\"sql_cmd\": checked_llm_out}\n                )  # input: sql exec\n                result = get_result_from_sqldb(self.database, checked_sql_command)\n                intermediate_steps.append(str(result))  # output: sql exec\n                llm_out = checked_llm_out\n                sql_cmd = checked_sql_command\n            _run_manager.on_text(\"\\nSQLResult: \", verbose=self.verbose)\n            _run_manager.on_text(str(result), color=\"yellow\", verbose=self.verbose)\n            # If return direct, we just set the final result equal to\n            # the result of the sql query result (`Sequence[Dict[str, Any]]`),\n            # otherwise try to get a human readable final answer (`str`).\n            final_result: Union[str, Sequence[Dict[str, Any]]]\n            if self.return_direct:\n                final_result = result\n            else:\n                _run_manager.on_text(\"\\nAnswer:\", verbose=self.verbose)\n                input_text += f\"{llm_out}\\nSQLResult: {result}\\nAnswer:\"\n                llm_inputs[\"input\"] = input_text\n                intermediate_steps.append(llm_inputs)  # input: final answer\n                final_result = self.llm_chain.predict(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/vector_sql.html"}
{"id": "6e6146e4a537-5", "text": "final_result = self.llm_chain.predict(\n                    callbacks=_run_manager.get_child(),\n                    **llm_inputs,\n                ).strip()\n                intermediate_steps.append(final_result)  # output: final answer\n                _run_manager.on_text(final_result, color=\"green\", verbose=self.verbose)\n            chain_result: Dict[str, Any] = {self.output_key: final_result}\n            if self.return_intermediate_steps:\n                chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps\n            return chain_result\n        except Exception as exc:\n            # Append intermediate steps to exception, to aid in logging and later\n            # improvement of few shot prompt seeds\n            exc.intermediate_steps = intermediate_steps  # type: ignore\n            raise exc\n    @property\n    def _chain_type(self) -> str:\n        return \"vector_sql_database_chain\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        db: SQLDatabase,\n        prompt: Optional[BasePromptTemplate] = None,\n        sql_cmd_parser: Optional[VectorSQLOutputParser] = None,\n        **kwargs: Any,\n    ) -> VectorSQLDatabaseChain:\n        assert sql_cmd_parser, \"`sql_cmd_parser` must be set in VectorSQLDatabaseChain.\"\n        prompt = prompt or SQL_PROMPTS.get(db.dialect, PROMPT)\n        llm_chain = LLMChain(llm=llm, prompt=prompt)\n        return cls(\n            llm_chain=llm_chain, database=db, sql_cmd_parser=sql_cmd_parser, **kwargs\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/vector_sql.html"}
{"id": "04b337a3b4fc-0", "text": "Source code for langchain_experimental.sql.base\n\"\"\"Chain for interacting with SQL Database.\"\"\"\nfrom __future__ import annotations\nimport warnings\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.sql_database.prompt import DECIDER_PROMPT, PROMPT, SQL_PROMPTS\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools.sql_database.prompt import QUERY_CHECKER\nfrom langchain.utilities.sql_database import SQLDatabase\nfrom langchain_experimental.pydantic_v1 import Extra, Field, root_validator\nINTERMEDIATE_STEPS_KEY = \"intermediate_steps\"\n[docs]class SQLDatabaseChain(Chain):\n    \"\"\"Chain for interacting with SQL Database.\n    Example:\n        .. code-block:: python\n            from langchain_experimental.sql import SQLDatabaseChain\n            from langchain.llms import OpenAI, SQLDatabase\n            db = SQLDatabase(...)\n            db_chain = SQLDatabaseChain.from_llm(OpenAI(), db)\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include the permissions this chain needs.\n        Failure to do so may result in data corruption or loss, since this chain may\n        attempt commands like `DROP TABLE` or `INSERT` if appropriately prompted.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this chain.\n        This issue shows an example negative outcome if these steps are not taken:\n        https://github.com/langchain-ai/langchain/issues/5923\n    \"\"\"\n    llm_chain: LLMChain", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html"}
{"id": "04b337a3b4fc-1", "text": "\"\"\"\n    llm_chain: LLMChain\n    llm: Optional[BaseLanguageModel] = None\n    \"\"\"[Deprecated] LLM wrapper to use.\"\"\"\n    database: SQLDatabase = Field(exclude=True)\n    \"\"\"SQL Database to connect to.\"\"\"\n    prompt: Optional[BasePromptTemplate] = None\n    \"\"\"[Deprecated] Prompt to use to translate natural language to SQL.\"\"\"\n    top_k: int = 5\n    \"\"\"Number of results to return from the query\"\"\"\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:\n    return_sql: bool = False\n    \"\"\"Will return sql-command directly without executing it\"\"\"\n    return_intermediate_steps: bool = False\n    \"\"\"Whether or not to return the intermediate steps along with the final answer.\"\"\"\n    return_direct: bool = False\n    \"\"\"Whether or not to return the result of querying the SQL table directly.\"\"\"\n    use_query_checker: bool = False\n    \"\"\"Whether or not the query checker tool should be used to attempt\n    to fix the initial SQL from the LLM.\"\"\"\n    query_checker_prompt: Optional[BasePromptTemplate] = None\n    \"\"\"The prompt template that should be used by the query checker\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator(pre=True)\n    def raise_deprecation(cls, values: Dict) -> Dict:\n        if \"llm\" in values:\n            warnings.warn(\n                \"Directly instantiating an SQLDatabaseChain with an llm is deprecated. \"\n                \"Please instantiate with llm_chain argument or using the from_llm \"\n                \"class method.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html"}
{"id": "04b337a3b4fc-2", "text": "\"class method.\"\n            )\n            if \"llm_chain\" not in values and values[\"llm\"] is not None:\n                database = values[\"database\"]\n                prompt = values.get(\"prompt\") or SQL_PROMPTS.get(\n                    database.dialect, PROMPT\n                )\n                values[\"llm_chain\"] = LLMChain(llm=values[\"llm\"], prompt=prompt)\n        return values\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the singular input key.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the singular output key.\n        :meta private:\n        \"\"\"\n        if not self.return_intermediate_steps:\n            return [self.output_key]\n        else:\n            return [self.output_key, INTERMEDIATE_STEPS_KEY]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        input_text = f\"{inputs[self.input_key]}\\nSQLQuery:\"\n        _run_manager.on_text(input_text, verbose=self.verbose)\n        # If not present, then defaults to None which is all tables.\n        table_names_to_use = inputs.get(\"table_names_to_use\")\n        table_info = self.database.get_table_info(table_names=table_names_to_use)\n        llm_inputs = {\n            \"input\": input_text,\n            \"top_k\": str(self.top_k),\n            \"dialect\": self.database.dialect,\n            \"table_info\": table_info,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html"}
{"id": "04b337a3b4fc-3", "text": "\"dialect\": self.database.dialect,\n            \"table_info\": table_info,\n            \"stop\": [\"\\nSQLResult:\"],\n        }\n        if self.memory is not None:\n            for k in self.memory.memory_variables:\n                llm_inputs[k] = inputs[k]\n        intermediate_steps: List = []\n        try:\n            intermediate_steps.append(llm_inputs.copy())  # input: sql generation\n            sql_cmd = self.llm_chain.predict(\n                callbacks=_run_manager.get_child(),\n                **llm_inputs,\n            ).strip()\n            if self.return_sql:\n                return {self.output_key: sql_cmd}\n            if not self.use_query_checker:\n                _run_manager.on_text(sql_cmd, color=\"green\", verbose=self.verbose)\n                intermediate_steps.append(\n                    sql_cmd\n                )  # output: sql generation (no checker)\n                intermediate_steps.append({\"sql_cmd\": sql_cmd})  # input: sql exec\n                result = self.database.run(sql_cmd)\n                intermediate_steps.append(str(result))  # output: sql exec\n            else:\n                query_checker_prompt = self.query_checker_prompt or PromptTemplate(\n                    template=QUERY_CHECKER, input_variables=[\"query\", \"dialect\"]\n                )\n                query_checker_chain = LLMChain(\n                    llm=self.llm_chain.llm, prompt=query_checker_prompt\n                )\n                query_checker_inputs = {\n                    \"query\": sql_cmd,\n                    \"dialect\": self.database.dialect,\n                }\n                checked_sql_command: str = query_checker_chain.predict(\n                    callbacks=_run_manager.get_child(), **query_checker_inputs\n                ).strip()\n                intermediate_steps.append(\n                    checked_sql_command\n                )  # output: sql generation (checker)\n                _run_manager.on_text(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html"}
{"id": "04b337a3b4fc-4", "text": ")  # output: sql generation (checker)\n                _run_manager.on_text(\n                    checked_sql_command, color=\"green\", verbose=self.verbose\n                )\n                intermediate_steps.append(\n                    {\"sql_cmd\": checked_sql_command}\n                )  # input: sql exec\n                result = self.database.run(checked_sql_command)\n                intermediate_steps.append(str(result))  # output: sql exec\n                sql_cmd = checked_sql_command\n            _run_manager.on_text(\"\\nSQLResult: \", verbose=self.verbose)\n            _run_manager.on_text(result, color=\"yellow\", verbose=self.verbose)\n            # If return direct, we just set the final result equal to\n            # the result of the sql query result, otherwise try to get a human readable\n            # final answer\n            if self.return_direct:\n                final_result = result\n            else:\n                _run_manager.on_text(\"\\nAnswer:\", verbose=self.verbose)\n                input_text += f\"{sql_cmd}\\nSQLResult: {result}\\nAnswer:\"\n                llm_inputs[\"input\"] = input_text\n                intermediate_steps.append(llm_inputs.copy())  # input: final answer\n                final_result = self.llm_chain.predict(\n                    callbacks=_run_manager.get_child(),\n                    **llm_inputs,\n                ).strip()\n                intermediate_steps.append(final_result)  # output: final answer\n                _run_manager.on_text(final_result, color=\"green\", verbose=self.verbose)\n            chain_result: Dict[str, Any] = {self.output_key: final_result}\n            if self.return_intermediate_steps:\n                chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps\n            return chain_result\n        except Exception as exc:\n            # Append intermediate steps to exception, to aid in logging and later\n            # improvement of few shot prompt seeds", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html"}
{"id": "04b337a3b4fc-5", "text": "# improvement of few shot prompt seeds\n            exc.intermediate_steps = intermediate_steps  # type: ignore\n            raise exc\n    @property\n    def _chain_type(self) -> str:\n        return \"sql_database_chain\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        db: SQLDatabase,\n        prompt: Optional[BasePromptTemplate] = None,\n        **kwargs: Any,\n    ) -> SQLDatabaseChain:\n        \"\"\"Create a SQLDatabaseChain from an LLM and a database connection.\n        *Security note*: Make sure that the database connection uses credentials\n            that are narrowly-scoped to only include the permissions this chain needs.\n            Failure to do so may result in data corruption or loss, since this chain may\n            attempt commands like `DROP TABLE` or `INSERT` if appropriately prompted.\n            The best way to guard against such negative outcomes is to (as appropriate)\n            limit the permissions granted to the credentials used with this chain.\n            This issue shows an example negative outcome if these steps are not taken:\n            https://github.com/langchain-ai/langchain/issues/5923\n        \"\"\"\n        prompt = prompt or SQL_PROMPTS.get(db.dialect, PROMPT)\n        llm_chain = LLMChain(llm=llm, prompt=prompt)\n        return cls(llm_chain=llm_chain, database=db, **kwargs)\n[docs]class SQLDatabaseSequentialChain(Chain):\n    \"\"\"Chain for querying SQL database that is a sequential chain.\n    The chain is as follows:\n    1. Based on the query, determine which tables to use.\n    2. Based on those tables, call the normal SQL database chain.\n    This is useful in cases where the number of tables in the database is large.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html"}
{"id": "04b337a3b4fc-6", "text": "This is useful in cases where the number of tables in the database is large.\n    \"\"\"\n    decider_chain: LLMChain\n    sql_chain: SQLDatabaseChain\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:\n    return_intermediate_steps: bool = False\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        db: SQLDatabase,\n        query_prompt: BasePromptTemplate = PROMPT,\n        decider_prompt: BasePromptTemplate = DECIDER_PROMPT,\n        **kwargs: Any,\n    ) -> SQLDatabaseSequentialChain:\n        \"\"\"Load the necessary chains.\"\"\"\n        sql_chain = SQLDatabaseChain.from_llm(llm, db, prompt=query_prompt, **kwargs)\n        decider_chain = LLMChain(\n            llm=llm, prompt=decider_prompt, output_key=\"table_names\"\n        )\n        return cls(sql_chain=sql_chain, decider_chain=decider_chain, **kwargs)\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the singular input key.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the singular output key.\n        :meta private:\n        \"\"\"\n        if not self.return_intermediate_steps:\n            return [self.output_key]\n        else:\n            return [self.output_key, INTERMEDIATE_STEPS_KEY]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html"}
{"id": "04b337a3b4fc-7", "text": ") -> Dict[str, Any]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        _table_names = self.sql_chain.database.get_usable_table_names()\n        table_names = \", \".join(_table_names)\n        llm_inputs = {\n            \"query\": inputs[self.input_key],\n            \"table_names\": table_names,\n        }\n        _lowercased_table_names = [name.lower() for name in _table_names]\n        table_names_from_chain = self.decider_chain.predict_and_parse(**llm_inputs)\n        table_names_to_use = [\n            name\n            for name in table_names_from_chain\n            if name.lower() in _lowercased_table_names\n        ]\n        _run_manager.on_text(\"Table names to use:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(\n            str(table_names_to_use), color=\"yellow\", verbose=self.verbose\n        )\n        new_inputs = {\n            self.sql_chain.input_key: inputs[self.input_key],\n            \"table_names_to_use\": table_names_to_use,\n        }\n        return self.sql_chain(\n            new_inputs, callbacks=_run_manager.get_child(), return_only_outputs=True\n        )\n    @property\n    def _chain_type(self) -> str:\n        return \"sql_database_sequential_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html"}
{"id": "6b30c1280f75-0", "text": "Source code for langchain_experimental.tot.prompts\nimport json\nfrom textwrap import dedent\nfrom typing import List\nfrom langchain.prompts import PromptTemplate\nfrom langchain.schema import BaseOutputParser\nfrom langchain_experimental.tot.thought import ThoughtValidity\nCOT_PROMPT = PromptTemplate(\n    template_format=\"jinja2\",\n    input_variables=[\"problem_description\", \"thoughts\"],\n    template=dedent(\n        \"\"\"\n        You are an intelligent agent that is generating one thought at a time in\n        a tree of thoughts setting.\n        PROBLEM \n        \n        {{problem_description}}\n        \n        {% if thoughts %}\n        THOUGHTS\n        \n        {% for thought in thoughts %}\n        {{ thought }}\n        {% endfor %}\n        {% endif %}\n        \n        Let's think step by step.\n        \"\"\"\n    ).strip(),\n)\n[docs]class JSONListOutputParser(BaseOutputParser):\n    \"\"\"Class to parse the output of a PROPOSE_PROMPT response.\"\"\"\n    @property\n    def _type(self) -> str:\n        return \"json_list\"\n[docs]    def parse(self, text: str) -> List[str]:\n        \"\"\"Parse the output of an LLM call.\"\"\"\n        json_string = text.split(\"```json\")[1].strip().strip(\"```\").strip()\n        try:\n            return json.loads(json_string)\n        except json.JSONDecodeError:\n            return []\nPROPOSE_PROMPT = PromptTemplate(\n    template_format=\"jinja2\",\n    input_variables=[\"problem_description\", \"thoughts\", \"n\"],\n    output_parser=JSONListOutputParser(),\n    template=dedent(\n        \"\"\"\n        You are an intelligent agent that is generating thoughts in a tree of\n        thoughts setting.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/prompts.html"}
{"id": "6b30c1280f75-1", "text": "You are an intelligent agent that is generating thoughts in a tree of\n        thoughts setting.\n        The output should be a markdown code snippet formatted as a JSON list of\n        strings, including the leading and trailing \"```json\" and \"```\":\n        ```json\n        [\n            \"<thought-1>\",\n            \"<thought-2>\",\n            \"<thought-3>\"\n        ]\n        ```\n        PROBLEM\n        {{ problem_description }}\n        {% if thoughts %}\n        VALID THOUGHTS\n        {% for thought in thoughts %}\n        {{ thought }}\n        {% endfor %}\n        Possible next {{ n }} valid thoughts based on the last valid thought:\n        {% else %}\n        Possible next {{ n }} valid thoughts based on the PROBLEM:\n        {%- endif -%}\n        \"\"\"\n    ).strip(),\n)\n[docs]class CheckerOutputParser(BaseOutputParser):\n[docs]    def parse(self, text: str) -> ThoughtValidity:\n        \"\"\"Parse the output of the language model.\"\"\"\n        text = text.upper()\n        if \"INVALID\" in text:\n            return ThoughtValidity.INVALID\n        elif \"INTERMEDIATE\" in text:\n            return ThoughtValidity.VALID_INTERMEDIATE\n        elif \"VALID\" in text:\n            return ThoughtValidity.VALID_FINAL\n        else:\n            return ThoughtValidity.INVALID\n    @property\n    def _type(self) -> str:\n        return \"tot_llm_checker_output\"\nCHECKER_PROMPT = PromptTemplate(\n    input_variables=[\"problem_description\", \"thoughts\"],\n    template=dedent(\n        \"\"\"\n        You are an intelligent agent, validating thoughts of another intelligent agent.\n        PROBLEM \n        \n        {problem_description}\n        THOUGHTS\n        \n        {thoughts}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/prompts.html"}
{"id": "6b30c1280f75-2", "text": "{problem_description}\n        THOUGHTS\n        \n        {thoughts}\n        Evaluate the thoughts and respond with one word.\n        - Respond VALID if the last thought is a valid final solution to the\n        problem.\n        - Respond INVALID if the last thought is invalid.\n        - Respond INTERMEDIATE if the last thought is valid but not the final\n        solution to the problem.\n        This chain of thoughts is\"\"\"\n    ).strip(),\n    output_parser=CheckerOutputParser(),\n)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/prompts.html"}
{"id": "5341fd847aab-0", "text": "Source code for langchain_experimental.tot.base\n\"\"\"\nThis a Tree of Thought (ToT) chain based on the paper \"Large Language Model\nGuided Tree-of-Thought\"\nhttps://arxiv.org/pdf/2305.08291.pdf\nThe Tree of Thought (ToT) chain uses a tree structure to explore the space of\npossible solutions to a problem.\n\"\"\"\nfrom __future__ import annotations\nfrom textwrap import indent\nfrom typing import Any, Dict, List, Optional, Type\nfrom langchain.base_language import BaseLanguageModel\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains.base import Chain\nfrom langchain_experimental.pydantic_v1 import Extra\nfrom langchain_experimental.tot.checker import ToTChecker\nfrom langchain_experimental.tot.controller import ToTController\nfrom langchain_experimental.tot.memory import ToTDFSMemory\nfrom langchain_experimental.tot.thought import Thought, ThoughtValidity\nfrom langchain_experimental.tot.thought_generation import (\n    BaseThoughtGenerationStrategy,\n    ProposePromptStrategy,\n)\n[docs]class ToTChain(Chain):\n    \"\"\"\n    A Chain implementing the Tree of Thought (ToT).\n    \"\"\"\n    llm: BaseLanguageModel\n    \"\"\"\n    Language model to use. It must be set to produce different variations for\n    the same prompt.\n    \"\"\"\n    checker: ToTChecker\n    \"\"\"ToT Checker to use.\"\"\"\n    output_key: str = \"response\"  #: :meta private:\n    k: int = 10\n    \"\"\"The maximum number of conversation rounds\"\"\"\n    c: int = 3\n    \"\"\"The number of children to explore at each node\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/base.html"}
{"id": "5341fd847aab-1", "text": "\"\"\"The number of children to explore at each node\"\"\"\n    tot_memory: ToTDFSMemory = ToTDFSMemory()\n    tot_controller: ToTController = ToTController()\n    tot_strategy_class: Type[BaseThoughtGenerationStrategy] = ProposePromptStrategy\n    verbose_llm: bool = False\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n[docs]    @classmethod\n    def from_llm(cls, llm: BaseLanguageModel, **kwargs: Any) -> ToTChain:\n        \"\"\"\n        Create a ToTChain from a language model.\n        :param llm: The language model to use.\n        :param kwargs: Additional arguments to pass to the ToTChain constructor.\n        \"\"\"\n        return cls(llm=llm, **kwargs)\n    def __init__(self, **kwargs: Any):\n        super().__init__(**kwargs)\n        self.tot_controller.c = self.c\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Will be whatever keys the prompt expects.\n        :meta private:\n        \"\"\"\n        return [\"problem_description\"]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Will always return text key.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n[docs]    def log_thought(\n        self,\n        thought: Thought,\n        level: int,\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> None:\n        if run_manager:\n            colors = {\n                ThoughtValidity.VALID_FINAL: \"green\",\n                ThoughtValidity.VALID_INTERMEDIATE: \"yellow\",\n                ThoughtValidity.INVALID: \"red\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/base.html"}
{"id": "5341fd847aab-2", "text": "ThoughtValidity.INVALID: \"red\",\n            }\n            text = indent(f\"Thought: {thought.text}\\n\", prefix=\"    \" * level)\n            run_manager.on_text(\n                text=text, color=colors[thought.validity], verbose=self.verbose\n            )\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        if run_manager:\n            run_manager.on_text(text=\"Starting the ToT solve procedure.\\n\")\n        problem_description = inputs[\"problem_description\"]\n        checker_inputs = {\"problem_description\": problem_description}\n        thoughts_path: tuple[str, ...] = ()\n        thought_generator = self.tot_strategy_class(\n            llm=self.llm, c=self.c, verbose=self.verbose_llm\n        )\n        level = 0\n        for _ in range(self.k):\n            level = self.tot_memory.level\n            thought_text = thought_generator.next_thought(\n                problem_description, thoughts_path, callbacks=_run_manager.get_child()\n            )\n            checker_inputs[\"thoughts\"] = thoughts_path + (thought_text,)\n            thought_validity = self.checker(\n                checker_inputs, callbacks=_run_manager.get_child()\n            )[\"validity\"]\n            thought = Thought(text=thought_text, validity=thought_validity)\n            if thought.validity == ThoughtValidity.VALID_FINAL:\n                self.log_thought(thought, level, run_manager)\n                return {self.output_key: thought.text}\n            self.tot_memory.store(thought)\n            self.log_thought(thought, level, run_manager)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/base.html"}
{"id": "5341fd847aab-3", "text": "self.log_thought(thought, level, run_manager)\n            thoughts_path = self.tot_controller(self.tot_memory)\n        return {self.output_key: \"No solution found\"}\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        raise NotImplementedError(\"Async not implemented yet\")\n    @property\n    def _chain_type(self) -> str:\n        return \"tot\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/base.html"}
{"id": "76a7b9e9f91c-0", "text": "Source code for langchain_experimental.tot.controller\nfrom typing import Tuple\nfrom langchain_experimental.tot.memory import ToTDFSMemory\nfrom langchain_experimental.tot.thought import ThoughtValidity\n[docs]class ToTController:\n    \"\"\"\n    Tree of Thought (ToT) controller.\n    This is a version of a ToT controller, dubbed in the paper as a \"Simple\n    Controller\".\n    It has one parameter `c` which is the number of children to explore for each\n    thought.\n    \"\"\"\n[docs]    def __init__(self, c: int = 3):\n        \"\"\"\n        Initialize the controller.\n        Args:\n            c: The number of children to explore at each node.\n        \"\"\"\n        self.c = c\n    def __call__(self, memory: ToTDFSMemory) -> Tuple[str, ...]:\n        next_thought = memory.top()\n        parent_thought = memory.top_parent()\n        validity = (\n            ThoughtValidity.VALID_INTERMEDIATE\n            if next_thought is None\n            else next_thought.validity\n        )\n        # 1 if the current partial solution is invalid, backtrack to the parent\n        # thought.\n        if validity == ThoughtValidity.INVALID:\n            memory.pop()\n            next_thought = memory.top()\n            if next_thought and len(next_thought.children) >= self.c:\n                memory.pop()\n        # 2 if the current partial solution is valid but C children were\n        # explored and yet failed to find a final solution, backtrack to the\n        # parent thought.\n        elif (\n            validity == ThoughtValidity.VALID_INTERMEDIATE\n            and parent_thought\n            and len(parent_thought.children) >= self.c\n        ):\n            memory.pop(2)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/controller.html"}
{"id": "76a7b9e9f91c-1", "text": "):\n            memory.pop(2)\n        return tuple(thought.text for thought in memory.current_path())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/controller.html"}
{"id": "be192eff2055-0", "text": "Source code for langchain_experimental.tot.thought\nfrom __future__ import annotations\nfrom enum import Enum\nfrom typing import Set\nfrom langchain_experimental.pydantic_v1 import BaseModel, Field\n[docs]class ThoughtValidity(Enum):\n    VALID_INTERMEDIATE = 0\n    VALID_FINAL = 1\n    INVALID = 2\n[docs]class Thought(BaseModel):\n    text: str\n    validity: ThoughtValidity\n    children: Set[Thought] = Field(default_factory=set)\n    def __hash__(self) -> int:\n        return id(self)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/thought.html"}
{"id": "974715f31432-0", "text": "Source code for langchain_experimental.tot.checker\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Dict, List, Optional, Tuple\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain_experimental.tot.thought import ThoughtValidity\n[docs]class ToTChecker(Chain, ABC):\n    \"\"\"\n    Tree of Thought (ToT) checker.\n    This is an abstract ToT checker that must be implemented by the user. You\n    can implement a simple rule-based checker or a more sophisticated\n    neural network based classifier.\n    \"\"\"\n    output_key: str = \"validity\"  #: :meta private:\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"The checker input keys.\n        :meta private:\n        \"\"\"\n        return [\"problem_description\", \"thoughts\"]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"The checker output keys.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n[docs]    @abstractmethod\n    def evaluate(\n        self,\n        problem_description: str,\n        thoughts: Tuple[str, ...] = (),\n    ) -> ThoughtValidity:\n        \"\"\"\n        Evaluate the response to the problem description and return the solution type.\n        \"\"\"\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, ThoughtValidity]:\n        return {self.output_key: self.evaluate(**inputs)}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/checker.html"}
{"id": "80e6c3e1fd8d-0", "text": "Source code for langchain_experimental.tot.memory\nfrom __future__ import annotations\nfrom typing import List, Optional\nfrom langchain_experimental.tot.thought import Thought\n[docs]class ToTDFSMemory:\n    \"\"\"\n    Memory for the Tree of Thought (ToT) chain. Implemented as a stack of\n    thoughts. This allows for a depth first search (DFS) of the ToT.\n    \"\"\"\n[docs]    def __init__(self, stack: Optional[List[Thought]] = None):\n        self.stack: List[Thought] = stack or []\n[docs]    def top(self) -> Optional[Thought]:\n        \"Get the top of the stack without popping it.\"\n        return self.stack[-1] if len(self.stack) > 0 else None\n[docs]    def pop(self, n: int = 1) -> Optional[Thought]:\n        \"Pop the top n elements of the stack and return the last one.\"\n        if len(self.stack) < n:\n            return None\n        for _ in range(n):\n            node = self.stack.pop()\n        return node\n[docs]    def top_parent(self) -> Optional[Thought]:\n        \"Get the parent of the top of the stack without popping it.\"\n        return self.stack[-2] if len(self.stack) > 1 else None\n[docs]    def store(self, node: Thought) -> None:\n        \"Add a node on the top of the stack.\"\n        if len(self.stack) > 0:\n            self.stack[-1].children.add(node)\n        self.stack.append(node)\n    @property\n    def level(self) -> int:\n        \"Return the current level of the stack.\"\n        return len(self.stack)\n[docs]    def current_path(self) -> List[Thought]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/memory.html"}
{"id": "80e6c3e1fd8d-1", "text": "[docs]    def current_path(self) -> List[Thought]:\n        \"Return the thoughts path.\"\n        return self.stack[:]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/memory.html"}
{"id": "c7920319a033-0", "text": "Source code for langchain_experimental.tot.thought_generation\n\"\"\"\nWe provide two strategies for generating thoughts in the Tree of Thoughts (ToT)\nframework to avoid repetition:\nThese strategies ensure that the language model generates diverse and\nnon-repeating thoughts, which are crucial for problem-solving tasks that require\nexploration.\n\"\"\"\nfrom abc import abstractmethod\nfrom typing import Any, Dict, List, Tuple\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts.base import BasePromptTemplate\nfrom langchain_experimental.pydantic_v1 import Field\nfrom langchain_experimental.tot.prompts import COT_PROMPT, PROPOSE_PROMPT\n[docs]class BaseThoughtGenerationStrategy(LLMChain):\n    \"\"\"\n    Base class for a thought generation strategy.\n    \"\"\"\n    c: int = 3\n    \"\"\"The number of children thoughts to propose at each step.\"\"\"\n[docs]    @abstractmethod\n    def next_thought(\n        self,\n        problem_description: str,\n        thoughts_path: Tuple[str, ...] = (),\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"\n        Generate the next thought given the problem description and the thoughts\n        generated so far.\n        \"\"\"\n[docs]class SampleCoTStrategy(BaseThoughtGenerationStrategy):\n    \"\"\"\n    Sample thoughts from a Chain-of-Thought (CoT) prompt.\n    This strategy works better when the thought space is rich, such as when each\n    thought is a paragraph. Independent and identically distributed samples\n    lead to diversity, which helps to avoid repetition.\n    \"\"\"\n    prompt: BasePromptTemplate = COT_PROMPT\n[docs]    def next_thought(\n        self,\n        problem_description: str,\n        thoughts_path: Tuple[str, ...] = (),\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/thought_generation.html"}
{"id": "c7920319a033-1", "text": "thoughts_path: Tuple[str, ...] = (),\n        **kwargs: Any,\n    ) -> str:\n        response_text = self.predict_and_parse(\n            problem_description=problem_description, thoughts=thoughts_path, **kwargs\n        )\n        return response_text if isinstance(response_text, str) else \"\"\n[docs]class ProposePromptStrategy(BaseThoughtGenerationStrategy):\n    \"\"\"\n    Propose thoughts sequentially using a \"propose prompt\".\n    This strategy works better when the thought space is more constrained, such\n    as when each thought is just a word or a line. Proposing different thoughts\n    in the same prompt completion helps to avoid duplication.\n    \"\"\"\n    prompt: BasePromptTemplate = PROPOSE_PROMPT\n    tot_memory: Dict[Tuple[str, ...], List[str]] = Field(default_factory=dict)\n[docs]    def next_thought(\n        self,\n        problem_description: str,\n        thoughts_path: Tuple[str, ...] = (),\n        **kwargs: Any,\n    ) -> str:\n        if thoughts_path not in self.tot_memory or not self.tot_memory[thoughts_path]:\n            new_thoughts = self.predict_and_parse(\n                problem_description=problem_description,\n                thoughts=thoughts_path,\n                n=self.c,\n                **kwargs,\n            )\n            if not new_thoughts:\n                return \"\"\n            if isinstance(new_thoughts, list):\n                self.tot_memory[thoughts_path] = new_thoughts[::-1]\n            else:\n                return \"\"\n        return self.tot_memory[thoughts_path].pop()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/thought_generation.html"}
{"id": "a73276e7323f-0", "text": "Source code for langchain_experimental.tabular_synthetic_data.base\nimport asyncio\nfrom typing import Any, Dict, List, Optional, Union\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts.few_shot import FewShotPromptTemplate\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class SyntheticDataGenerator(BaseModel):\n    \"\"\"Generates synthetic data using the given LLM and few-shot template.\n    Utilizes the provided LLM to produce synthetic data based on the\n    few-shot prompt template.\n    Attributes:\n        template (FewShotPromptTemplate): Template for few-shot prompting.\n        llm (Optional[BaseLanguageModel]): Large Language Model to use for generation.\n        llm_chain (Optional[Chain]): LLM chain with the LLM and few-shot template.\n        example_input_key (str): Key to use for storing example inputs.\n    Usage Example:\n        >>> template = FewShotPromptTemplate(...)\n        >>> llm = BaseLanguageModel(...)\n        >>> generator = SyntheticDataGenerator(template=template, llm=llm)\n        >>> results = generator.generate(subject=\"climate change\", runs=5)\n    \"\"\"\n    template: FewShotPromptTemplate\n    llm: Optional[BaseLanguageModel] = None\n    results: list = []\n    llm_chain: Optional[Chain] = None\n    example_input_key: str = \"example\"\n    class Config:\n        validate_assignment = True\n    @root_validator(pre=False, skip_on_failure=True)\n    def set_llm_chain(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        llm_chain = values.get(\"llm_chain\")\n        llm = values.get(\"llm\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tabular_synthetic_data/base.html"}
{"id": "a73276e7323f-1", "text": "llm = values.get(\"llm\")\n        few_shot_template = values.get(\"template\")\n        if not llm_chain:  # If llm_chain is None or not present\n            if llm is None or few_shot_template is None:\n                raise ValueError(\n                    \"Both llm and few_shot_template must be provided if llm_chain is \"\n                    \"not given.\"\n                )\n            values[\"llm_chain\"] = LLMChain(llm=llm, prompt=few_shot_template)\n        return values\n    @staticmethod\n    def _format_dict_to_string(input_dict: Dict) -> str:\n        formatted_str = \", \".join(\n            [f\"{key}: {value}\" for key, value in input_dict.items()]\n        )\n        return formatted_str\n    def _update_examples(self, example: Union[BaseModel, Dict[str, Any], str]) -> None:\n        \"\"\"Prevents duplicates by adding previously generated examples to the few shot\n        list.\"\"\"\n        if self.template and self.template.examples:\n            if isinstance(example, BaseModel):\n                formatted_example = self._format_dict_to_string(example.dict())\n            elif isinstance(example, dict):\n                formatted_example = self._format_dict_to_string(example)\n            else:\n                formatted_example = str(example)\n            self.template.examples.pop(0)\n            self.template.examples.append({self.example_input_key: formatted_example})\n[docs]    def generate(self, subject: str, runs: int, *args: Any, **kwargs: Any) -> List[str]:\n        \"\"\"Generate synthetic data using the given subject string.\n        Args:\n            subject (str): The subject the synthetic data will be about.\n            runs (int): Number of times to generate the data.\n            extra (str): Extra instructions for steerability in data generation.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tabular_synthetic_data/base.html"}
{"id": "a73276e7323f-2", "text": "extra (str): Extra instructions for steerability in data generation.\n        Returns:\n            List[str]: List of generated synthetic data.\n        Usage Example:\n            >>> results = generator.generate(subject=\"climate change\", runs=5,\n            extra=\"Focus on environmental impacts.\")\n        \"\"\"\n        if self.llm_chain is None:\n            raise ValueError(\n                \"llm_chain is none, either set either llm_chain or llm at generator \"\n                \"construction\"\n            )\n        for _ in range(runs):\n            result = self.llm_chain.run(subject=subject, *args, **kwargs)\n            self.results.append(result)\n            self._update_examples(result)\n        return self.results\n[docs]    async def agenerate(\n        self, subject: str, runs: int, extra: str = \"\", *args: Any, **kwargs: Any\n    ) -> List[str]:\n        \"\"\"Generate synthetic data using the given subject asynchronously.\n        Note: Since the LLM calls run concurrently,\n        you may have fewer duplicates by adding specific instructions to\n        the \"extra\" keyword argument.\n        Args:\n            subject (str): The subject the synthetic data will be about.\n            runs (int): Number of times to generate the data asynchronously.\n            extra (str): Extra instructions for steerability in data generation.\n        Returns:\n            List[str]: List of generated synthetic data for the given subject.\n        Usage Example:\n            >>> results = await generator.agenerate(subject=\"climate change\", runs=5,\n            extra=\"Focus on env impacts.\")\n        \"\"\"\n        async def run_chain(\n            subject: str, extra: str = \"\", *args: Any, **kwargs: Any\n        ) -> None:\n            if self.llm_chain is not None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tabular_synthetic_data/base.html"}
{"id": "a73276e7323f-3", "text": ") -> None:\n            if self.llm_chain is not None:\n                result = await self.llm_chain.arun(\n                    subject=subject, extra=extra, *args, **kwargs\n                )\n                self.results.append(result)\n        await asyncio.gather(\n            *(run_chain(subject=subject, extra=extra) for _ in range(runs))\n        )\n        return self.results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tabular_synthetic_data/base.html"}
{"id": "2dd96e6eb5e1-0", "text": "Source code for langchain_experimental.tabular_synthetic_data.openai\nfrom typing import Any, Dict, Optional, Type, Union\nfrom langchain.chains.openai_functions import create_structured_output_chain\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.prompts import PromptTemplate\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema import BaseLLMOutputParser, BasePromptTemplate\nfrom langchain_experimental.tabular_synthetic_data.base import SyntheticDataGenerator\nOPENAI_TEMPLATE = PromptTemplate(input_variables=[\"example\"], template=\"{example}\")\n[docs]def create_openai_data_generator(\n    output_schema: Union[Dict[str, Any], Type[BaseModel]],\n    llm: ChatOpenAI,\n    prompt: BasePromptTemplate,\n    output_parser: Optional[BaseLLMOutputParser] = None,\n    **kwargs: Any,\n) -> SyntheticDataGenerator:\n    \"\"\"\n    Create an instance of SyntheticDataGenerator tailored for OpenAI models.\n    This function creates an LLM chain designed for structured output based on the\n    provided schema, language model, and prompt template. The resulting chain is then\n    used to instantiate and return a SyntheticDataGenerator.\n    Args:\n        output_schema (Union[Dict[str, Any], Type[BaseModel]]): Schema for expected\n        output. This can be either a dictionary representing a valid JsonSchema or a\n        Pydantic BaseModel class.\n        llm (ChatOpenAI): OpenAI language model to use.\n        prompt (BasePromptTemplate): Template to be used for generating prompts.\n        output_parser (Optional[BaseLLMOutputParser], optional): Parser for\n        processing model outputs. If none is provided, a default will be inferred\n        from the function types.\n        **kwargs: Additional keyword arguments to be passed to\n        `create_structured_output_chain`.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tabular_synthetic_data/openai.html"}
{"id": "2dd96e6eb5e1-1", "text": "`create_structured_output_chain`.\n    Returns: SyntheticDataGenerator: An instance of the data generator set up with\n    the constructed chain.\n    Usage:\n        To generate synthetic data with a structured output, first define your desired\n        output schema. Then, use this function to create a SyntheticDataGenerator\n        instance. After obtaining the generator, you can utilize its methods to produce\n        the desired synthetic data.\n    \"\"\"\n    # Create function calling chain to ensure structured output\n    chain = create_structured_output_chain(\n        output_schema, llm, prompt, output_parser=output_parser, **kwargs\n    )\n    # Create the SyntheticDataGenerator instance with the created chain\n    generator = SyntheticDataGenerator(template=prompt, llm_chain=chain)\n    return generator", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/tabular_synthetic_data/openai.html"}
{"id": "6df4d43f33ed-0", "text": "Source code for langchain_experimental.cpal.constants\nfrom enum import Enum\n[docs]class Constant(Enum):\n    \"\"\"Enum for constants used in the CPAL.\"\"\"\n    narrative_input = \"narrative_input\"\n    chain_answer = \"chain_answer\"  # natural language answer\n    chain_data = \"chain_data\"  # pydantic instance", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/constants.html"}
{"id": "c5b94b60a798-0", "text": "Source code for langchain_experimental.cpal.base\n\"\"\"\nCPAL Chain and its subchains\n\"\"\"\nfrom __future__ import annotations\nimport json\nfrom typing import Any, ClassVar, Dict, List, Optional, Type\nfrom langchain.base_language import BaseLanguageModel\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.output_parsers import PydanticOutputParser\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain_experimental import pydantic_v1 as pydantic\nfrom langchain_experimental.cpal.constants import Constant\nfrom langchain_experimental.cpal.models import (\n    CausalModel,\n    InterventionModel,\n    NarrativeModel,\n    QueryModel,\n    StoryModel,\n)\nfrom langchain_experimental.cpal.templates.univariate.causal import (\n    template as causal_template,\n)\nfrom langchain_experimental.cpal.templates.univariate.intervention import (\n    template as intervention_template,\n)\nfrom langchain_experimental.cpal.templates.univariate.narrative import (\n    template as narrative_template,\n)\nfrom langchain_experimental.cpal.templates.univariate.query import (\n    template as query_template,\n)\nclass _BaseStoryElementChain(Chain):\n    chain: LLMChain\n    input_key: str = Constant.narrative_input.value  #: :meta private:\n    output_key: str = Constant.chain_answer.value  #: :meta private:\n    pydantic_model: ClassVar[\n        Optional[Type[pydantic.BaseModel]]\n    ] = None  #: :meta private:\n    template: ClassVar[Optional[str]] = None  #: :meta private:\n    @classmethod\n    def parser(cls) -> PydanticOutputParser:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/base.html"}
{"id": "c5b94b60a798-1", "text": "@classmethod\n    def parser(cls) -> PydanticOutputParser:\n        \"\"\"Parse LLM output into a pydantic object.\"\"\"\n        if cls.pydantic_model is None:\n            raise NotImplementedError(\n                f\"pydantic_model not implemented for {cls.__name__}\"\n            )\n        return PydanticOutputParser(pydantic_object=cls.pydantic_model)\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the output keys.\n        :meta private:\n        \"\"\"\n        _output_keys = [self.output_key]\n        return _output_keys\n    @classmethod\n    def from_univariate_prompt(\n        cls,\n        llm: BaseLanguageModel,\n        **kwargs: Any,\n    ) -> Any:\n        return cls(\n            chain=LLMChain(\n                llm=llm,\n                prompt=PromptTemplate(\n                    input_variables=[Constant.narrative_input.value],\n                    template=kwargs.get(\"template\", cls.template),\n                    partial_variables={\n                        \"format_instructions\": cls.parser().get_format_instructions()\n                    },\n                ),\n            ),\n            **kwargs,\n        )\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        completion = self.chain.run(inputs[self.input_key])\n        pydantic_data = self.__class__.parser().parse(completion)\n        return {\n            Constant.chain_data.value: pydantic_data,\n            Constant.chain_answer.value: None,\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/base.html"}
{"id": "c5b94b60a798-2", "text": "Constant.chain_answer.value: None,\n        }\n[docs]class NarrativeChain(_BaseStoryElementChain):\n    \"\"\"Decompose the narrative into its story elements\n    - causal model\n    - query\n    - intervention\n    \"\"\"\n    pydantic_model: ClassVar[Type[pydantic.BaseModel]] = NarrativeModel\n    template: ClassVar[str] = narrative_template\n[docs]class CausalChain(_BaseStoryElementChain):\n    \"\"\"Translate the causal narrative into a stack of operations.\"\"\"\n    pydantic_model: ClassVar[Type[pydantic.BaseModel]] = CausalModel\n    template: ClassVar[str] = causal_template\n[docs]class InterventionChain(_BaseStoryElementChain):\n    \"\"\"Set the hypothetical conditions for the causal model.\"\"\"\n    pydantic_model: ClassVar[Type[pydantic.BaseModel]] = InterventionModel\n    template: ClassVar[str] = intervention_template\n[docs]class QueryChain(_BaseStoryElementChain):\n    \"\"\"Query the outcome table using SQL.\n    *Security note*: This class implements an AI technique that generates SQL code.\n        If those SQL commands are executed, it's critical to ensure they use credentials\n        that are narrowly-scoped to only include the permissions this chain needs.\n        Failure to do so may result in data corruption or loss, since this chain may\n        attempt commands like `DROP TABLE` or `INSERT` if appropriately prompted.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this chain.\n    \"\"\"\n    pydantic_model: ClassVar[Type[pydantic.BaseModel]] = QueryModel\n    template: ClassVar[str] = query_template  # TODO: incl. table schema\n[docs]class CPALChain(_BaseStoryElementChain):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/base.html"}
{"id": "c5b94b60a798-3", "text": "[docs]class CPALChain(_BaseStoryElementChain):\n    \"\"\"Causal program-aided language (CPAL) chain implementation.\n    *Security note*: The building blocks of this class include the implementation\n        of an AI technique that generates SQL code. If those SQL commands\n        are executed, it's critical to ensure they use credentials that\n        are narrowly-scoped to only include the permissions this chain needs.\n        Failure to do so may result in data corruption or loss, since this chain may\n        attempt commands like `DROP TABLE` or `INSERT` if appropriately prompted.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this chain.\n    \"\"\"\n    llm: BaseLanguageModel\n    narrative_chain: Optional[NarrativeChain] = None\n    causal_chain: Optional[CausalChain] = None\n    intervention_chain: Optional[InterventionChain] = None\n    query_chain: Optional[QueryChain] = None\n    _story: StoryModel = pydantic.PrivateAttr(default=None)  # TODO: change name ?\n[docs]    @classmethod\n    def from_univariate_prompt(\n        cls,\n        llm: BaseLanguageModel,\n        **kwargs: Any,\n    ) -> CPALChain:\n        \"\"\"instantiation depends on component chains\n        *Security note*: The building blocks of this class include the implementation\n            of an AI technique that generates SQL code. If those SQL commands\n            are executed, it's critical to ensure they use credentials that\n            are narrowly-scoped to only include the permissions this chain needs.\n            Failure to do so may result in data corruption or loss, since this chain may\n            attempt commands like `DROP TABLE` or `INSERT` if appropriately prompted.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/base.html"}
{"id": "c5b94b60a798-4", "text": "attempt commands like `DROP TABLE` or `INSERT` if appropriately prompted.\n            The best way to guard against such negative outcomes is to (as appropriate)\n            limit the permissions granted to the credentials used with this chain.\n        \"\"\"\n        return cls(\n            llm=llm,\n            chain=LLMChain(\n                llm=llm,\n                prompt=PromptTemplate(\n                    input_variables=[\"question\", \"query_result\"],\n                    template=(\n                        \"Summarize this answer '{query_result}' to this \"\n                        \"question '{question}'? \"\n                    ),\n                ),\n            ),\n            narrative_chain=NarrativeChain.from_univariate_prompt(llm=llm),\n            causal_chain=CausalChain.from_univariate_prompt(llm=llm),\n            intervention_chain=InterventionChain.from_univariate_prompt(llm=llm),\n            query_chain=QueryChain.from_univariate_prompt(llm=llm),\n            **kwargs,\n        )\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n        **kwargs: Any,\n    ) -> Dict[str, Any]:\n        # instantiate component chains\n        if self.narrative_chain is None:\n            self.narrative_chain = NarrativeChain.from_univariate_prompt(llm=self.llm)\n        if self.causal_chain is None:\n            self.causal_chain = CausalChain.from_univariate_prompt(llm=self.llm)\n        if self.intervention_chain is None:\n            self.intervention_chain = InterventionChain.from_univariate_prompt(\n                llm=self.llm\n            )\n        if self.query_chain is None:\n            self.query_chain = QueryChain.from_univariate_prompt(llm=self.llm)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/base.html"}
{"id": "c5b94b60a798-5", "text": "self.query_chain = QueryChain.from_univariate_prompt(llm=self.llm)\n        # decompose narrative into three causal story elements\n        narrative = self.narrative_chain(inputs[Constant.narrative_input.value])[\n            Constant.chain_data.value\n        ]\n        story = StoryModel(\n            causal_operations=self.causal_chain(narrative.story_plot)[\n                Constant.chain_data.value\n            ],\n            intervention=self.intervention_chain(narrative.story_hypothetical)[\n                Constant.chain_data.value\n            ],\n            query=self.query_chain(narrative.story_outcome_question)[\n                Constant.chain_data.value\n            ],\n        )\n        self._story = story\n        def pretty_print_str(title: str, d: str) -> str:\n            return title + \"\\n\" + d\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        _run_manager.on_text(\n            pretty_print_str(\"story outcome data\", story._outcome_table.to_string()),\n            color=\"green\",\n            end=\"\\n\\n\",\n            verbose=self.verbose,\n        )\n        def pretty_print_dict(title: str, d: dict) -> str:\n            return title + \"\\n\" + json.dumps(d, indent=4)\n        _run_manager.on_text(\n            pretty_print_dict(\"query data\", story.query.dict()),\n            color=\"blue\",\n            end=\"\\n\\n\",\n            verbose=self.verbose,\n        )\n        if story.query._result_table.empty:\n            # prevent piping bad data into subsequent chains\n            raise ValueError(\n                (\n                    \"unanswerable, query and outcome are incoherent\\n\"\n                    \"\\n\"\n                    \"outcome:\\n\"\n                    f\"{story._outcome_table}\\n\"\n                    \"query:\\n\"\n                    f\"{story.query.dict()}\"\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/base.html"}
{"id": "c5b94b60a798-6", "text": "\"query:\\n\"\n                    f\"{story.query.dict()}\"\n                )\n            )\n        else:\n            query_result = float(story.query._result_table.values[0][-1])\n            if False:\n                \"\"\"TODO: add this back in when demanded by composable chains\"\"\"\n                reporting_chain = self.chain\n                human_report = reporting_chain.run(\n                    question=story.query.question, query_result=query_result\n                )\n                query_result = {\n                    \"query_result\": query_result,\n                    \"human_report\": human_report,\n                }\n        output = {\n            Constant.chain_data.value: story,\n            self.output_key: query_result,\n            **kwargs,\n        }\n        return output\n[docs]    def draw(self, **kwargs: Any) -> None:\n        \"\"\"\n        CPAL chain can draw its resulting DAG.\n        Usage in a jupyter notebook:\n            >>> from IPython.display import SVG\n            >>> cpal_chain.draw(path=\"graph.svg\")\n            >>> SVG('graph.svg')\n        \"\"\"\n        self._story._networkx_wrapper.draw_graphviz(**kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/base.html"}
{"id": "7bf625972c73-0", "text": "Source code for langchain_experimental.cpal.models\nfrom __future__ import annotations  # allows pydantic model to reference itself\nimport re\nfrom typing import Any, List, Optional, Union\nfrom langchain.graphs.networkx_graph import NetworkxEntityGraph\nfrom langchain_experimental.cpal.constants import Constant\nfrom langchain_experimental.pydantic_v1 import (\n    BaseModel,\n    Field,\n    PrivateAttr,\n    root_validator,\n    validator,\n)\n[docs]class NarrativeModel(BaseModel):\n    \"\"\"\n    Represent the narrative input as three story elements.\n    \"\"\"\n    story_outcome_question: str\n    story_hypothetical: str\n    story_plot: str  # causal stack of operations\n    @validator(\"*\", pre=True)\n    def empty_str_to_none(cls, v: str) -> Union[str, None]:\n        \"\"\"Empty strings are not allowed\"\"\"\n        if v == \"\":\n            return None\n        return v\n[docs]class EntityModel(BaseModel):\n    name: str = Field(description=\"entity name\")\n    code: str = Field(description=\"entity actions\")\n    value: float = Field(description=\"entity initial value\")\n    depends_on: List[str] = Field(default=[], description=\"ancestor entities\")\n    # TODO: generalize to multivariate math\n    # TODO: acyclic graph\n    class Config:\n        validate_assignment = True\n    @validator(\"name\")\n    def lower_case_name(cls, v: str) -> str:\n        v = v.lower()\n        return v\n[docs]class CausalModel(BaseModel):\n    attribute: str = Field(description=\"name of the attribute to be calculated\")\n    entities: List[EntityModel] = Field(description=\"entities in the story\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/models.html"}
{"id": "7bf625972c73-1", "text": "entities: List[EntityModel] = Field(description=\"entities in the story\")\n    # TODO: root validate each `entity.depends_on` using system's entity names\n[docs]class EntitySettingModel(BaseModel):\n    \"\"\"\n    Initial conditions for an entity\n    {\"name\": \"bud\", \"attribute\": \"pet_count\", \"value\": 12}\n    \"\"\"\n    name: str = Field(description=\"name of the entity\")\n    attribute: str = Field(description=\"name of the attribute to be calculated\")\n    value: float = Field(description=\"entity's attribute value (calculated)\")\n    @validator(\"name\")\n    def lower_case_transform(cls, v: str) -> str:\n        v = v.lower()\n        return v\n[docs]class SystemSettingModel(BaseModel):\n    \"\"\"\n    Initial global conditions for the system.\n    {\"parameter\": \"interest_rate\", \"value\": .05}\n    \"\"\"\n    parameter: str\n    value: float\n[docs]class InterventionModel(BaseModel):\n    \"\"\"\n    aka initial conditions\n    >>> intervention.dict()\n    {\n        entity_settings: [\n            {\"name\": \"bud\", \"attribute\": \"pet_count\", \"value\": 12},\n            {\"name\": \"pat\", \"attribute\": \"pet_count\", \"value\": 0},\n        ],\n        system_settings: None,\n    }\n    \"\"\"\n    entity_settings: List[EntitySettingModel]\n    system_settings: Optional[List[SystemSettingModel]] = None\n    @validator(\"system_settings\")\n    def lower_case_name(cls, v: str) -> Union[str, None]:\n        if v is not None:\n            raise NotImplementedError(\"system_setting is not implemented yet\")\n        return v\n[docs]class QueryModel(BaseModel):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/models.html"}
{"id": "7bf625972c73-2", "text": "return v\n[docs]class QueryModel(BaseModel):\n    \"\"\"translate a question about the story outcome into a programmatic expression\"\"\"\n    question: str = Field(alias=Constant.narrative_input.value)  # input\n    expression: str  # output, part of llm completion\n    llm_error_msg: str  # output, part of llm completion\n    _result_table: str = PrivateAttr()  # result of the executed query\n[docs]class ResultModel(BaseModel):\n    question: str = Field(alias=Constant.narrative_input.value)  # input\n    _result_table: str = PrivateAttr()  # result of the executed query\n[docs]class StoryModel(BaseModel):\n    causal_operations: Any = Field(required=True)\n    intervention: Any = Field(required=True)\n    query: Any = Field(required=True)\n    _outcome_table: Any = PrivateAttr(default=None)\n    _networkx_wrapper: Any = PrivateAttr(default=None)\n    def __init__(self, **kwargs: Any):\n        super().__init__(**kwargs)\n        self._compute()\n        # TODO: when langchain adopts pydantic.v2 replace w/ `__post_init__`\n        # misses hints github.com/pydantic/pydantic/issues/1729#issuecomment-1300576214\n    # TODO: move away from `root_validator` since it is deprecated in pydantic v2\n    #       and causes mypy type-checking failures (hence the `type: ignore`)\n    @root_validator  # type: ignore[call-overload]\n    def check_intervention_is_valid(cls, values: dict) -> dict:\n        valid_names = [e.name for e in values[\"causal_operations\"].entities]\n        for setting in values[\"intervention\"].entity_settings:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/models.html"}
{"id": "7bf625972c73-3", "text": "for setting in values[\"intervention\"].entity_settings:\n            if setting.name not in valid_names:\n                error_msg = f\"\"\"\n                    Hypothetical question has an invalid entity name.\n                    `{setting.name}` not in `{valid_names}`\n                \"\"\"\n                raise ValueError(error_msg)\n        return values\n    def _block_back_door_paths(self) -> None:\n        # stop intervention entities from depending on others\n        intervention_entities = [\n            entity_setting.name for entity_setting in self.intervention.entity_settings\n        ]\n        for entity in self.causal_operations.entities:\n            if entity.name in intervention_entities:\n                entity.depends_on = []\n                entity.code = \"pass\"\n    def _set_initial_conditions(self) -> None:\n        for entity_setting in self.intervention.entity_settings:\n            for entity in self.causal_operations.entities:\n                if entity.name == entity_setting.name:\n                    entity.value = entity_setting.value\n    def _make_graph(self) -> None:\n        self._networkx_wrapper = NetworkxEntityGraph()\n        for entity in self.causal_operations.entities:\n            for parent_name in entity.depends_on:\n                self._networkx_wrapper._graph.add_edge(\n                    parent_name, entity.name, relation=entity.code\n                )\n        # TODO: is it correct to drop entities with no impact on the outcome (?)\n        self.causal_operations.entities = [\n            entity\n            for entity in self.causal_operations.entities\n            if entity.name in self._networkx_wrapper.get_topological_sort()\n        ]\n    def _sort_entities(self) -> None:\n        # order the sequence of causal actions\n        sorted_nodes = self._networkx_wrapper.get_topological_sort()\n        self.causal_operations.entities.sort(key=lambda x: sorted_nodes.index(x.name))\n    def _forward_propagate(self) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/models.html"}
{"id": "7bf625972c73-4", "text": "def _forward_propagate(self) -> None:\n        try:\n            import pandas as pd\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import pandas, please install with `pip install pandas`.\"\n            ) from e\n        entity_scope = {\n            entity.name: entity for entity in self.causal_operations.entities\n        }\n        for entity in self.causal_operations.entities:\n            if entity.code == \"pass\":\n                continue\n            else:\n                # gist.github.com/dean0x7d/df5ce97e4a1a05be4d56d1378726ff92\n                exec(entity.code, globals(), entity_scope)\n        row_values = [entity.dict() for entity in entity_scope.values()]\n        self._outcome_table = pd.DataFrame(row_values)\n    def _run_query(self) -> None:\n        def humanize_sql_error_msg(error: str) -> str:\n            pattern = r\"column\\s+(.*?)\\s+not found\"\n            col_match = re.search(pattern, error)\n            if col_match:\n                return (\n                    \"SQL error: \"\n                    + col_match.group(1)\n                    + \" is not an attribute in your story!\"\n                )\n            else:\n                return str(error)\n        if self.query.llm_error_msg == \"\":\n            try:\n                import duckdb\n                df = self._outcome_table  # noqa\n                query_result = duckdb.sql(self.query.expression).df()\n                self.query._result_table = query_result\n            except duckdb.BinderException as e:\n                self.query._result_table = humanize_sql_error_msg(str(e))\n            except ImportError as e:\n                raise ImportError(\n                    \"Unable to import duckdb, please install with `pip install duckdb`.\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/models.html"}
{"id": "7bf625972c73-5", "text": "\"Unable to import duckdb, please install with `pip install duckdb`.\"\n                ) from e\n            except Exception as e:\n                self.query._result_table = str(e)\n        else:\n            msg = \"LLM maybe failed to translate question to SQL query.\"\n            raise ValueError(\n                {\n                    \"question\": self.query.question,\n                    \"llm_error_msg\": self.query.llm_error_msg,\n                    \"msg\": msg,\n                }\n            )\n    def _compute(self) -> Any:\n        self._block_back_door_paths()\n        self._set_initial_conditions()\n        self._make_graph()\n        self._sort_entities()\n        self._forward_propagate()\n        self._run_query()\n[docs]    def print_debug_report(self) -> None:\n        report = {\n            \"outcome\": self._outcome_table,\n            \"query\": self.query.dict(),\n            \"result\": self.query._result_table,\n        }\n        from pprint import pprint\n        pprint(report)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/models.html"}
{"id": "ae8c6f411c06-0", "text": "Source code for langchain_experimental.retrievers.vector_sql_database\n\"\"\"Vector SQL Database Chain Retriever\"\"\"\nfrom typing import Any, Dict, List\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain_experimental.sql.vector_sql import VectorSQLDatabaseChain\n[docs]class VectorSQLDatabaseChainRetriever(BaseRetriever):\n    \"\"\"Retriever that uses SQLDatabase as Retriever\"\"\"\n    sql_db_chain: VectorSQLDatabaseChain\n    \"\"\"SQL Database Chain\"\"\"\n    page_content_key: str = \"content\"\n    \"\"\"column name for page content of documents\"\"\"\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n        **kwargs: Any,\n    ) -> List[Document]:\n        ret: List[Dict[str, Any]] = self.sql_db_chain(\n            query, callbacks=run_manager.get_child(), **kwargs\n        )[\"result\"]\n        return [\n            Document(page_content=r[self.page_content_key], metadata=r) for r in ret\n        ]\n    async def _aget_relevant_documents(\n        self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        raise NotImplementedError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/retrievers/vector_sql_database.html"}
{"id": "61715d2d36ee-0", "text": "Source code for langchain_experimental.autonomous_agents.baby_agi.task_prioritization\nfrom langchain.chains import LLMChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class TaskPrioritizationChain(LLMChain):\n    \"\"\"Chain to prioritize tasks.\"\"\"\n[docs]    @classmethod\n    def from_llm(cls, llm: BaseLanguageModel, verbose: bool = True) -> LLMChain:\n        \"\"\"Get the response parser.\"\"\"\n        task_prioritization_template = (\n            \"You are a task prioritization AI tasked with cleaning the formatting of \"\n            \"and reprioritizing the following tasks: {task_names}.\"\n            \" Consider the ultimate objective of your team: {objective}.\"\n            \" Do not remove any tasks. Return the result as a numbered list, like:\"\n            \" #. First task\"\n            \" #. Second task\"\n            \" Start the task list with number {next_task_id}.\"\n        )\n        prompt = PromptTemplate(\n            template=task_prioritization_template,\n            input_variables=[\"task_names\", \"next_task_id\", \"objective\"],\n        )\n        return cls(prompt=prompt, llm=llm, verbose=verbose)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/task_prioritization.html"}
{"id": "d25f3ffdfc85-0", "text": "Source code for langchain_experimental.autonomous_agents.baby_agi.baby_agi\n\"\"\"BabyAGI agent.\"\"\"\nfrom collections import deque\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain_experimental.autonomous_agents.baby_agi.task_creation import (\n    TaskCreationChain,\n)\nfrom langchain_experimental.autonomous_agents.baby_agi.task_execution import (\n    TaskExecutionChain,\n)\nfrom langchain_experimental.autonomous_agents.baby_agi.task_prioritization import (\n    TaskPrioritizationChain,\n)\nfrom langchain_experimental.pydantic_v1 import BaseModel, Field\n# This class has a metaclass conflict: both `Chain` and `BaseModel` define a metaclass\n# to use, and the two metaclasses attempt to define the same functions but\n# in mutually-incompatible ways. It isn't clear how to resolve this,\n# and this code predates mypy beginning to perform that check.\n#\n# Mypy errors:\n# ```\n# Definition of \"__repr_str__\" in base class \"Representation\" is\n#   incompatible with definition in base class \"BaseModel\"  [misc]\n# Definition of \"__repr_name__\" in base class \"Representation\" is\n#   incompatible with definition in base class \"BaseModel\"  [misc]\n# Definition of \"__rich_repr__\" in base class \"Representation\" is\n#   incompatible with definition in base class \"BaseModel\"  [misc]\n# Definition of \"__pretty__\" in base class \"Representation\" is\n#   incompatible with definition in base class \"BaseModel\"  [misc]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/baby_agi.html"}
{"id": "d25f3ffdfc85-1", "text": "#   incompatible with definition in base class \"BaseModel\"  [misc]\n# Metaclass conflict: the metaclass of a derived class must be\n#   a (non-strict) subclass of the metaclasses of all its bases  [misc]\n# ```\n#\n# TODO: look into refactoring this class in a way that avoids the mypy type errors\n[docs]class BabyAGI(Chain, BaseModel):  # type: ignore[misc]\n    \"\"\"Controller model for the BabyAGI agent.\"\"\"\n    task_list: deque = Field(default_factory=deque)\n    task_creation_chain: Chain = Field(...)\n    task_prioritization_chain: Chain = Field(...)\n    execution_chain: Chain = Field(...)\n    task_id_counter: int = Field(1)\n    vectorstore: VectorStore = Field(init=False)\n    max_iterations: Optional[int] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def add_task(self, task: Dict) -> None:\n        self.task_list.append(task)\n[docs]    def print_task_list(self) -> None:\n        print(\"\\033[95m\\033[1m\" + \"\\n*****TASK LIST*****\\n\" + \"\\033[0m\\033[0m\")\n        for t in self.task_list:\n            print(str(t[\"task_id\"]) + \": \" + t[\"task_name\"])\n[docs]    def print_next_task(self, task: Dict) -> None:\n        print(\"\\033[92m\\033[1m\" + \"\\n*****NEXT TASK*****\\n\" + \"\\033[0m\\033[0m\")\n        print(str(task[\"task_id\"]) + \": \" + task[\"task_name\"])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/baby_agi.html"}
{"id": "d25f3ffdfc85-2", "text": "print(str(task[\"task_id\"]) + \": \" + task[\"task_name\"])\n[docs]    def print_task_result(self, result: str) -> None:\n        print(\"\\033[93m\\033[1m\" + \"\\n*****TASK RESULT*****\\n\" + \"\\033[0m\\033[0m\")\n        print(result)\n    @property\n    def input_keys(self) -> List[str]:\n        return [\"objective\"]\n    @property\n    def output_keys(self) -> List[str]:\n        return []\n[docs]    def get_next_task(\n        self, result: str, task_description: str, objective: str, **kwargs: Any\n    ) -> List[Dict]:\n        \"\"\"Get the next task.\"\"\"\n        task_names = [t[\"task_name\"] for t in self.task_list]\n        incomplete_tasks = \", \".join(task_names)\n        response = self.task_creation_chain.run(\n            result=result,\n            task_description=task_description,\n            incomplete_tasks=incomplete_tasks,\n            objective=objective,\n            **kwargs,\n        )\n        new_tasks = response.split(\"\\n\")\n        return [\n            {\"task_name\": task_name} for task_name in new_tasks if task_name.strip()\n        ]\n[docs]    def prioritize_tasks(\n        self, this_task_id: int, objective: str, **kwargs: Any\n    ) -> List[Dict]:\n        \"\"\"Prioritize tasks.\"\"\"\n        task_names = [t[\"task_name\"] for t in list(self.task_list)]\n        next_task_id = int(this_task_id) + 1\n        response = self.task_prioritization_chain.run(\n            task_names=\", \".join(task_names),\n            next_task_id=str(next_task_id),\n            objective=objective,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/baby_agi.html"}
{"id": "d25f3ffdfc85-3", "text": "objective=objective,\n            **kwargs,\n        )\n        new_tasks = response.split(\"\\n\")\n        prioritized_task_list = []\n        for task_string in new_tasks:\n            if not task_string.strip():\n                continue\n            task_parts = task_string.strip().split(\".\", 1)\n            if len(task_parts) == 2:\n                task_id = task_parts[0].strip()\n                task_name = task_parts[1].strip()\n                prioritized_task_list.append(\n                    {\"task_id\": task_id, \"task_name\": task_name}\n                )\n        return prioritized_task_list\n    def _get_top_tasks(self, query: str, k: int) -> List[str]:\n        \"\"\"Get the top k tasks based on the query.\"\"\"\n        results = self.vectorstore.similarity_search(query, k=k)\n        if not results:\n            return []\n        return [str(item.metadata[\"task\"]) for item in results]\n[docs]    def execute_task(self, objective: str, task: str, k: int = 5, **kwargs: Any) -> str:\n        \"\"\"Execute a task.\"\"\"\n        context = self._get_top_tasks(query=objective, k=k)\n        return self.execution_chain.run(\n            objective=objective, context=\"\\n\".join(context), task=task, **kwargs\n        )\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Run the agent.\"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        objective = inputs[\"objective\"]\n        first_task = inputs.get(\"first_task\", \"Make a todo list\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/baby_agi.html"}
{"id": "d25f3ffdfc85-4", "text": "first_task = inputs.get(\"first_task\", \"Make a todo list\")\n        self.add_task({\"task_id\": 1, \"task_name\": first_task})\n        num_iters = 0\n        while True:\n            if self.task_list:\n                self.print_task_list()\n                # Step 1: Pull the first task\n                task = self.task_list.popleft()\n                self.print_next_task(task)\n                # Step 2: Execute the task\n                result = self.execute_task(\n                    objective, task[\"task_name\"], callbacks=_run_manager.get_child()\n                )\n                this_task_id = int(task[\"task_id\"])\n                self.print_task_result(result)\n                # Step 3: Store the result in Pinecone\n                result_id = f\"result_{task['task_id']}_{num_iters}\"\n                self.vectorstore.add_texts(\n                    texts=[result],\n                    metadatas=[{\"task\": task[\"task_name\"]}],\n                    ids=[result_id],\n                )\n                # Step 4: Create new tasks and reprioritize task list\n                new_tasks = self.get_next_task(\n                    result,\n                    task[\"task_name\"],\n                    objective,\n                    callbacks=_run_manager.get_child(),\n                )\n                for new_task in new_tasks:\n                    self.task_id_counter += 1\n                    new_task.update({\"task_id\": self.task_id_counter})\n                    self.add_task(new_task)\n                self.task_list = deque(\n                    self.prioritize_tasks(\n                        this_task_id, objective, callbacks=_run_manager.get_child()\n                    )\n                )\n            num_iters += 1\n            if self.max_iterations is not None and num_iters == self.max_iterations:\n                print(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/baby_agi.html"}
{"id": "d25f3ffdfc85-5", "text": "print(\n                    \"\\033[91m\\033[1m\" + \"\\n*****TASK ENDING*****\\n\" + \"\\033[0m\\033[0m\"\n                )\n                break\n        return {}\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        vectorstore: VectorStore,\n        verbose: bool = False,\n        task_execution_chain: Optional[Chain] = None,\n        **kwargs: Any,\n    ) -> \"BabyAGI\":\n        \"\"\"Initialize the BabyAGI Controller.\"\"\"\n        task_creation_chain = TaskCreationChain.from_llm(llm, verbose=verbose)\n        task_prioritization_chain = TaskPrioritizationChain.from_llm(\n            llm, verbose=verbose\n        )\n        if task_execution_chain is None:\n            execution_chain: Chain = TaskExecutionChain.from_llm(llm, verbose=verbose)\n        else:\n            execution_chain = task_execution_chain\n        return cls(\n            task_creation_chain=task_creation_chain,\n            task_prioritization_chain=task_prioritization_chain,\n            execution_chain=execution_chain,\n            vectorstore=vectorstore,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/baby_agi.html"}
{"id": "e39ee31c8aef-0", "text": "Source code for langchain_experimental.autonomous_agents.baby_agi.task_creation\nfrom langchain.chains import LLMChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class TaskCreationChain(LLMChain):\n    \"\"\"Chain generating tasks.\"\"\"\n[docs]    @classmethod\n    def from_llm(cls, llm: BaseLanguageModel, verbose: bool = True) -> LLMChain:\n        \"\"\"Get the response parser.\"\"\"\n        task_creation_template = (\n            \"You are an task creation AI that uses the result of an execution agent\"\n            \" to create new tasks with the following objective: {objective},\"\n            \" The last completed task has the result: {result}.\"\n            \" This result was based on this task description: {task_description}.\"\n            \" These are incomplete tasks: {incomplete_tasks}.\"\n            \" Based on the result, create new tasks to be completed\"\n            \" by the AI system that do not overlap with incomplete tasks.\"\n            \" Return the tasks as an array.\"\n        )\n        prompt = PromptTemplate(\n            template=task_creation_template,\n            input_variables=[\n                \"result\",\n                \"task_description\",\n                \"incomplete_tasks\",\n                \"objective\",\n            ],\n        )\n        return cls(prompt=prompt, llm=llm, verbose=verbose)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/task_creation.html"}
{"id": "b3eb4281dbd3-0", "text": "Source code for langchain_experimental.autonomous_agents.baby_agi.task_execution\nfrom langchain.chains import LLMChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class TaskExecutionChain(LLMChain):\n    \"\"\"Chain to execute tasks.\"\"\"\n[docs]    @classmethod\n    def from_llm(cls, llm: BaseLanguageModel, verbose: bool = True) -> LLMChain:\n        \"\"\"Get the response parser.\"\"\"\n        execution_template = (\n            \"You are an AI who performs one task based on the following objective: \"\n            \"{objective}.\"\n            \"Take into account these previously completed tasks: {context}.\"\n            \" Your task: {task}. Response:\"\n        )\n        prompt = PromptTemplate(\n            template=execution_template,\n            input_variables=[\"objective\", \"context\", \"task\"],\n        )\n        return cls(prompt=prompt, llm=llm, verbose=verbose)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/task_execution.html"}
{"id": "e04189f9c0eb-0", "text": "Source code for langchain_experimental.autonomous_agents.autogpt.agent\nfrom __future__ import annotations\nfrom typing import List, Optional\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.memory import ChatMessageHistory\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n    Document,\n)\nfrom langchain.schema.messages import AIMessage, HumanMessage, SystemMessage\nfrom langchain.schema.vectorstore import VectorStoreRetriever\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.human.tool import HumanInputRun\nfrom langchain_experimental.autonomous_agents.autogpt.output_parser import (\n    AutoGPTOutputParser,\n    BaseAutoGPTOutputParser,\n)\nfrom langchain_experimental.autonomous_agents.autogpt.prompt import AutoGPTPrompt\nfrom langchain_experimental.autonomous_agents.autogpt.prompt_generator import (\n    FINISH_NAME,\n)\nfrom langchain_experimental.pydantic_v1 import ValidationError\n[docs]class AutoGPT:\n    \"\"\"Agent class for interacting with Auto-GPT.\"\"\"\n[docs]    def __init__(\n        self,\n        ai_name: str,\n        memory: VectorStoreRetriever,\n        chain: LLMChain,\n        output_parser: BaseAutoGPTOutputParser,\n        tools: List[BaseTool],\n        feedback_tool: Optional[HumanInputRun] = None,\n        chat_history_memory: Optional[BaseChatMessageHistory] = None,\n    ):\n        self.ai_name = ai_name\n        self.memory = memory\n        self.next_action_count = 0\n        self.chain = chain\n        self.output_parser = output_parser\n        self.tools = tools\n        self.feedback_tool = feedback_tool\n        self.chat_history_memory = chat_history_memory or ChatMessageHistory()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/agent.html"}
{"id": "e04189f9c0eb-1", "text": "self.chat_history_memory = chat_history_memory or ChatMessageHistory()\n[docs]    @classmethod\n    def from_llm_and_tools(\n        cls,\n        ai_name: str,\n        ai_role: str,\n        memory: VectorStoreRetriever,\n        tools: List[BaseTool],\n        llm: BaseChatModel,\n        human_in_the_loop: bool = False,\n        output_parser: Optional[BaseAutoGPTOutputParser] = None,\n        chat_history_memory: Optional[BaseChatMessageHistory] = None,\n    ) -> AutoGPT:\n        prompt = AutoGPTPrompt(\n            ai_name=ai_name,\n            ai_role=ai_role,\n            tools=tools,\n            input_variables=[\"memory\", \"messages\", \"goals\", \"user_input\"],\n            token_counter=llm.get_num_tokens,\n        )\n        human_feedback_tool = HumanInputRun() if human_in_the_loop else None\n        chain = LLMChain(llm=llm, prompt=prompt)\n        return cls(\n            ai_name,\n            memory,\n            chain,\n            output_parser or AutoGPTOutputParser(),\n            tools,\n            feedback_tool=human_feedback_tool,\n            chat_history_memory=chat_history_memory,\n        )\n[docs]    def run(self, goals: List[str]) -> str:\n        user_input = (\n            \"Determine which next command to use, \"\n            \"and respond using the format specified above:\"\n        )\n        # Interaction Loop\n        loop_count = 0\n        while True:\n            # Discontinue if continuous limit is reached\n            loop_count += 1\n            # Send message to AI, get response\n            assistant_reply = self.chain.run(\n                goals=goals,\n                messages=self.chat_history_memory.messages,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/agent.html"}
{"id": "e04189f9c0eb-2", "text": "goals=goals,\n                messages=self.chat_history_memory.messages,\n                memory=self.memory,\n                user_input=user_input,\n            )\n            # Print Assistant thoughts\n            print(assistant_reply)\n            self.chat_history_memory.add_message(HumanMessage(content=user_input))\n            self.chat_history_memory.add_message(AIMessage(content=assistant_reply))\n            # Get command name and arguments\n            action = self.output_parser.parse(assistant_reply)\n            tools = {t.name: t for t in self.tools}\n            if action.name == FINISH_NAME:\n                return action.args[\"response\"]\n            if action.name in tools:\n                tool = tools[action.name]\n                try:\n                    observation = tool.run(action.args)\n                except ValidationError as e:\n                    observation = (\n                        f\"Validation Error in args: {str(e)}, args: {action.args}\"\n                    )\n                except Exception as e:\n                    observation = (\n                        f\"Error: {str(e)}, {type(e).__name__}, args: {action.args}\"\n                    )\n                result = f\"Command {tool.name} returned: {observation}\"\n            elif action.name == \"ERROR\":\n                result = f\"Error: {action.args}. \"\n            else:\n                result = (\n                    f\"Unknown command '{action.name}'. \"\n                    f\"Please refer to the 'COMMANDS' list for available \"\n                    f\"commands and only respond in the specified JSON format.\"\n                )\n            memory_to_add = (\n                f\"Assistant Reply: {assistant_reply} \" f\"\\nResult: {result} \"\n            )\n            if self.feedback_tool is not None:\n                feedback = f\"\\n{self.feedback_tool.run('Input: ')}\"\n                if feedback in {\"q\", \"stop\"}:\n                    print(\"EXITING\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/agent.html"}
{"id": "e04189f9c0eb-3", "text": "if feedback in {\"q\", \"stop\"}:\n                    print(\"EXITING\")\n                    return \"EXITING\"\n                memory_to_add += feedback\n            self.memory.add_documents([Document(page_content=memory_to_add)])\n            self.chat_history_memory.add_message(SystemMessage(content=result))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/agent.html"}
{"id": "3566e3bf02a5-0", "text": "Source code for langchain_experimental.autonomous_agents.autogpt.prompt\nimport time\nfrom typing import Any, Callable, List\nfrom langchain.prompts.chat import (\n    BaseChatPromptTemplate,\n)\nfrom langchain.schema.messages import BaseMessage, HumanMessage, SystemMessage\nfrom langchain.schema.vectorstore import VectorStoreRetriever\nfrom langchain.tools.base import BaseTool\nfrom langchain_experimental.autonomous_agents.autogpt.prompt_generator import get_prompt\nfrom langchain_experimental.pydantic_v1 import BaseModel\n# This class has a metaclass conflict: both `BaseChatPromptTemplate` and `BaseModel`\n# define a metaclass to use, and the two metaclasses attempt to define\n# the same functions but in mutually-incompatible ways.\n# It isn't clear how to resolve this, and this code predates mypy\n# beginning to perform that check.\n#\n# Mypy errors:\n# ```\n# Definition of \"__private_attributes__\" in base class \"BaseModel\" is\n#   incompatible with definition in base class \"BaseModel\"  [misc]\n# Definition of \"__repr_name__\" in base class \"Representation\" is\n#   incompatible with definition in base class \"BaseModel\"  [misc]\n# Definition of \"__pretty__\" in base class \"Representation\" is\n#   incompatible with definition in base class \"BaseModel\"  [misc]\n# Definition of \"__repr_str__\" in base class \"Representation\" is\n#   incompatible with definition in base class \"BaseModel\"  [misc]\n# Definition of \"__rich_repr__\" in base class \"Representation\" is\n#   incompatible with definition in base class \"BaseModel\"  [misc]\n# Metaclass conflict: the metaclass of a derived class must be", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt.html"}
{"id": "3566e3bf02a5-1", "text": "# Metaclass conflict: the metaclass of a derived class must be\n#   a (non-strict) subclass of the metaclasses of all its bases  [misc]\n# ```\n#\n# TODO: look into refactoring this class in a way that avoids the mypy type errors\n[docs]class AutoGPTPrompt(BaseChatPromptTemplate, BaseModel):  # type: ignore[misc]\n    \"\"\"Prompt for AutoGPT.\"\"\"\n    ai_name: str\n    ai_role: str\n    tools: List[BaseTool]\n    token_counter: Callable[[str], int]\n    send_token_limit: int = 4196\n[docs]    def construct_full_prompt(self, goals: List[str]) -> str:\n        prompt_start = (\n            \"Your decisions must always be made independently \"\n            \"without seeking user assistance.\\n\"\n            \"Play to your strengths as an LLM and pursue simple \"\n            \"strategies with no legal complications.\\n\"\n            \"If you have completed all your tasks, make sure to \"\n            'use the \"finish\" command.'\n        )\n        # Construct full prompt\n        full_prompt = (\n            f\"You are {self.ai_name}, {self.ai_role}\\n{prompt_start}\\n\\nGOALS:\\n\\n\"\n        )\n        for i, goal in enumerate(goals):\n            full_prompt += f\"{i+1}. {goal}\\n\"\n        full_prompt += f\"\\n\\n{get_prompt(self.tools)}\"\n        return full_prompt\n[docs]    def format_messages(self, **kwargs: Any) -> List[BaseMessage]:\n        base_prompt = SystemMessage(content=self.construct_full_prompt(kwargs[\"goals\"]))\n        time_prompt = SystemMessage(\n            content=f\"The current time and date is {time.strftime('%c')}\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt.html"}
{"id": "3566e3bf02a5-2", "text": "content=f\"The current time and date is {time.strftime('%c')}\"\n        )\n        used_tokens = self.token_counter(base_prompt.content) + self.token_counter(\n            time_prompt.content\n        )\n        memory: VectorStoreRetriever = kwargs[\"memory\"]\n        previous_messages = kwargs[\"messages\"]\n        relevant_docs = memory.get_relevant_documents(str(previous_messages[-10:]))\n        relevant_memory = [d.page_content for d in relevant_docs]\n        relevant_memory_tokens = sum(\n            [self.token_counter(doc) for doc in relevant_memory]\n        )\n        while used_tokens + relevant_memory_tokens > 2500:\n            relevant_memory = relevant_memory[:-1]\n            relevant_memory_tokens = sum(\n                [self.token_counter(doc) for doc in relevant_memory]\n            )\n        content_format = (\n            f\"This reminds you of these events \"\n            f\"from your past:\\n{relevant_memory}\\n\\n\"\n        )\n        memory_message = SystemMessage(content=content_format)\n        used_tokens += self.token_counter(memory_message.content)\n        historical_messages: List[BaseMessage] = []\n        for message in previous_messages[-10:][::-1]:\n            message_tokens = self.token_counter(message.content)\n            if used_tokens + message_tokens > self.send_token_limit - 1000:\n                break\n            historical_messages = [message] + historical_messages\n            used_tokens += message_tokens\n        input_message = HumanMessage(content=kwargs[\"user_input\"])\n        messages: List[BaseMessage] = [base_prompt, time_prompt, memory_message]\n        messages += historical_messages\n        messages.append(input_message)\n        return messages", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt.html"}
{"id": "59d71ee41a46-0", "text": "Source code for langchain_experimental.autonomous_agents.autogpt.output_parser\nimport json\nimport re\nfrom abc import abstractmethod\nfrom typing import Dict, NamedTuple\nfrom langchain.schema import BaseOutputParser\n[docs]class AutoGPTAction(NamedTuple):\n    \"\"\"Action returned by AutoGPTOutputParser.\"\"\"\n    name: str\n    args: Dict\n[docs]class BaseAutoGPTOutputParser(BaseOutputParser):\n    \"\"\"Base Output parser for AutoGPT.\"\"\"\n[docs]    @abstractmethod\n    def parse(self, text: str) -> AutoGPTAction:\n        \"\"\"Return AutoGPTAction\"\"\"\n[docs]def preprocess_json_input(input_str: str) -> str:\n    \"\"\"Preprocesses a string to be parsed as json.\n    Replace single backslashes with double backslashes,\n    while leaving already escaped ones intact.\n    Args:\n        input_str: String to be preprocessed\n    Returns:\n        Preprocessed string\n    \"\"\"\n    corrected_str = re.sub(\n        r'(?<!\\\\)\\\\(?![\"\\\\/bfnrt]|u[0-9a-fA-F]{4})', r\"\\\\\\\\\", input_str\n    )\n    return corrected_str\n[docs]class AutoGPTOutputParser(BaseAutoGPTOutputParser):\n    \"\"\"Output parser for AutoGPT.\"\"\"\n[docs]    def parse(self, text: str) -> AutoGPTAction:\n        try:\n            parsed = json.loads(text, strict=False)\n        except json.JSONDecodeError:\n            preprocessed_text = preprocess_json_input(text)\n            try:\n                parsed = json.loads(preprocessed_text, strict=False)\n            except Exception:\n                return AutoGPTAction(\n                    name=\"ERROR\",\n                    args={\"error\": f\"Could not parse invalid json: {text}\"},", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/output_parser.html"}
{"id": "59d71ee41a46-1", "text": "args={\"error\": f\"Could not parse invalid json: {text}\"},\n                )\n        try:\n            return AutoGPTAction(\n                name=parsed[\"command\"][\"name\"],\n                args=parsed[\"command\"][\"args\"],\n            )\n        except (KeyError, TypeError):\n            # If the command is null or incomplete, return an erroneous tool\n            return AutoGPTAction(\n                name=\"ERROR\", args={\"error\": f\"Incomplete command args: {parsed}\"}\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/output_parser.html"}
{"id": "cc09adcffe76-0", "text": "Source code for langchain_experimental.autonomous_agents.autogpt.prompt_generator\nimport json\nfrom typing import List\nfrom langchain.tools.base import BaseTool\nFINISH_NAME = \"finish\"\n[docs]class PromptGenerator:\n    \"\"\"A class for generating custom prompt strings.\n    Does this based on constraints, commands, resources, and performance evaluations.\n    \"\"\"\n[docs]    def __init__(self) -> None:\n        \"\"\"Initialize the PromptGenerator object.\n        Starts with empty lists of constraints, commands, resources,\n        and performance evaluations.\n        \"\"\"\n        self.constraints: List[str] = []\n        self.commands: List[BaseTool] = []\n        self.resources: List[str] = []\n        self.performance_evaluation: List[str] = []\n        self.response_format = {\n            \"thoughts\": {\n                \"text\": \"thought\",\n                \"reasoning\": \"reasoning\",\n                \"plan\": \"- short bulleted\\n- list that conveys\\n- long-term plan\",\n                \"criticism\": \"constructive self-criticism\",\n                \"speak\": \"thoughts summary to say to user\",\n            },\n            \"command\": {\"name\": \"command name\", \"args\": {\"arg name\": \"value\"}},\n        }\n[docs]    def add_constraint(self, constraint: str) -> None:\n        \"\"\"\n        Add a constraint to the constraints list.\n        Args:\n            constraint (str): The constraint to be added.\n        \"\"\"\n        self.constraints.append(constraint)\n[docs]    def add_tool(self, tool: BaseTool) -> None:\n        self.commands.append(tool)\n    def _generate_command_string(self, tool: BaseTool) -> str:\n        output = f\"{tool.name}: {tool.description}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt_generator.html"}
{"id": "cc09adcffe76-1", "text": "output = f\"{tool.name}: {tool.description}\"\n        output += f\", args json schema: {json.dumps(tool.args)}\"\n        return output\n[docs]    def add_resource(self, resource: str) -> None:\n        \"\"\"\n        Add a resource to the resources list.\n        Args:\n            resource (str): The resource to be added.\n        \"\"\"\n        self.resources.append(resource)\n[docs]    def add_performance_evaluation(self, evaluation: str) -> None:\n        \"\"\"\n        Add a performance evaluation item to the performance_evaluation list.\n        Args:\n            evaluation (str): The evaluation item to be added.\n        \"\"\"\n        self.performance_evaluation.append(evaluation)\n    def _generate_numbered_list(self, items: list, item_type: str = \"list\") -> str:\n        \"\"\"\n        Generate a numbered list from given items based on the item_type.\n        Args:\n            items (list): A list of items to be numbered.\n            item_type (str, optional): The type of items in the list.\n                Defaults to 'list'.\n        Returns:\n            str: The formatted numbered list.\n        \"\"\"\n        if item_type == \"command\":\n            command_strings = [\n                f\"{i + 1}. {self._generate_command_string(item)}\"\n                for i, item in enumerate(items)\n            ]\n            finish_description = (\n                \"use this to signal that you have finished all your objectives\"\n            )\n            finish_args = (\n                '\"response\": \"final response to let '\n                'people know you have finished your objectives\"'\n            )\n            finish_string = (\n                f\"{len(items) + 1}. {FINISH_NAME}: \"\n                f\"{finish_description}, args: {finish_args}\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt_generator.html"}
{"id": "cc09adcffe76-2", "text": "f\"{finish_description}, args: {finish_args}\"\n            )\n            return \"\\n\".join(command_strings + [finish_string])\n        else:\n            return \"\\n\".join(f\"{i+1}. {item}\" for i, item in enumerate(items))\n[docs]    def generate_prompt_string(self) -> str:\n        \"\"\"Generate a prompt string.\n        Returns:\n            str: The generated prompt string.\n        \"\"\"\n        formatted_response_format = json.dumps(self.response_format, indent=4)\n        prompt_string = (\n            f\"Constraints:\\n{self._generate_numbered_list(self.constraints)}\\n\\n\"\n            f\"Commands:\\n\"\n            f\"{self._generate_numbered_list(self.commands, item_type='command')}\\n\\n\"\n            f\"Resources:\\n{self._generate_numbered_list(self.resources)}\\n\\n\"\n            f\"Performance Evaluation:\\n\"\n            f\"{self._generate_numbered_list(self.performance_evaluation)}\\n\\n\"\n            f\"You should only respond in JSON format as described below \"\n            f\"\\nResponse Format: \\n{formatted_response_format} \"\n            f\"\\nEnsure the response can be parsed by Python json.loads\"\n        )\n        return prompt_string\n[docs]def get_prompt(tools: List[BaseTool]) -> str:\n    \"\"\"Generates a prompt string.\n    It includes various constraints, commands, resources, and performance evaluations.\n    Returns:\n        str: The generated prompt string.\n    \"\"\"\n    # Initialize the PromptGenerator object\n    prompt_generator = PromptGenerator()\n    # Add constraints to the PromptGenerator object\n    prompt_generator.add_constraint(\n        \"~4000 word limit for short term memory. \"\n        \"Your short term memory is short, \"\n        \"so immediately save important information to files.\"\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt_generator.html"}
{"id": "cc09adcffe76-3", "text": "\"so immediately save important information to files.\"\n    )\n    prompt_generator.add_constraint(\n        \"If you are unsure how you previously did something \"\n        \"or want to recall past events, \"\n        \"thinking about similar events will help you remember.\"\n    )\n    prompt_generator.add_constraint(\"No user assistance\")\n    prompt_generator.add_constraint(\n        'Exclusively use the commands listed in double quotes e.g. \"command name\"'\n    )\n    # Add commands to the PromptGenerator object\n    for tool in tools:\n        prompt_generator.add_tool(tool)\n    # Add resources to the PromptGenerator object\n    prompt_generator.add_resource(\n        \"Internet access for searches and information gathering.\"\n    )\n    prompt_generator.add_resource(\"Long Term memory management.\")\n    prompt_generator.add_resource(\n        \"GPT-3.5 powered Agents for delegation of simple tasks.\"\n    )\n    prompt_generator.add_resource(\"File output.\")\n    # Add performance evaluations to the PromptGenerator object\n    prompt_generator.add_performance_evaluation(\n        \"Continuously review and analyze your actions \"\n        \"to ensure you are performing to the best of your abilities.\"\n    )\n    prompt_generator.add_performance_evaluation(\n        \"Constructively self-criticize your big-picture behavior constantly.\"\n    )\n    prompt_generator.add_performance_evaluation(\n        \"Reflect on past decisions and strategies to refine your approach.\"\n    )\n    prompt_generator.add_performance_evaluation(\n        \"Every command has a cost, so be smart and efficient. \"\n        \"Aim to complete tasks in the least number of steps.\"\n    )\n    # Generate the prompt string\n    prompt_string = prompt_generator.generate_prompt_string()\n    return prompt_string", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt_generator.html"}
{"id": "7a1685d56c1b-0", "text": "Source code for langchain_experimental.autonomous_agents.autogpt.memory\nfrom typing import Any, Dict, List\nfrom langchain.memory.chat_memory import BaseChatMemory, get_prompt_input_key\nfrom langchain.schema.vectorstore import VectorStoreRetriever\nfrom langchain_experimental.pydantic_v1 import Field\n[docs]class AutoGPTMemory(BaseChatMemory):\n    \"\"\"Memory for AutoGPT.\"\"\"\n    retriever: VectorStoreRetriever = Field(exclude=True)\n    \"\"\"VectorStoreRetriever object to connect to.\"\"\"\n    @property\n    def memory_variables(self) -> List[str]:\n        return [\"chat_history\", \"relevant_context\"]\n    def _get_prompt_input_key(self, inputs: Dict[str, Any]) -> str:\n        \"\"\"Get the input key for the prompt.\"\"\"\n        if self.input_key is None:\n            return get_prompt_input_key(inputs, self.memory_variables)\n        return self.input_key\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n        input_key = self._get_prompt_input_key(inputs)\n        query = inputs[input_key]\n        docs = self.retriever.get_relevant_documents(query)\n        return {\n            \"chat_history\": self.chat_memory.messages[-10:],\n            \"relevant_context\": docs,\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/memory.html"}
{"id": "a870991b6b13-0", "text": "Source code for langchain_experimental.autonomous_agents.hugginggpt.task_executor\nimport copy\nimport uuid\nfrom typing import Dict, List\nimport numpy as np\nfrom langchain.tools.base import BaseTool\nfrom langchain_experimental.autonomous_agents.hugginggpt.task_planner import Plan\n[docs]class Task:\n[docs]    def __init__(self, task: str, id: int, dep: List[int], args: Dict, tool: BaseTool):\n        self.task = task\n        self.id = id\n        self.dep = dep\n        self.args = args\n        self.tool = tool\n        self.status = \"pending\"\n        self.message = \"\"\n        self.result = \"\"\n    def __str__(self) -> str:\n        return f\"{self.task}({self.args})\"\n[docs]    def save_product(self) -> None:\n        import cv2\n        if self.task == \"video_generator\":\n            # ndarray to video\n            product = np.array(self.product)\n            nframe, height, width, _ = product.shape\n            video_filename = uuid.uuid4().hex[:6] + \".mp4\"\n            fps = 30  # Frames per second\n            fourcc = cv2.VideoWriter_fourcc(*\"mp4v\")  # type: ignore\n            video_out = cv2.VideoWriter(video_filename, fourcc, fps, (width, height))\n            for frame in self.product:\n                video_out.write(frame)\n            video_out.release()\n            self.result = video_filename\n        elif self.task == \"image_generator\":\n            # PIL.Image to image\n            filename = uuid.uuid4().hex[:6] + \".png\"\n            self.product.save(filename)  # type: ignore\n            self.result = filename\n[docs]    def completed(self) -> bool:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_executor.html"}
{"id": "a870991b6b13-1", "text": "self.result = filename\n[docs]    def completed(self) -> bool:\n        return self.status == \"completed\"\n[docs]    def failed(self) -> bool:\n        return self.status == \"failed\"\n[docs]    def pending(self) -> bool:\n        return self.status == \"pending\"\n[docs]    def run(self) -> str:\n        from diffusers.utils import load_image\n        try:\n            new_args = copy.deepcopy(self.args)\n            for k, v in new_args.items():\n                if k == \"image\":\n                    new_args[\"image\"] = load_image(v)\n            if self.task in [\"video_generator\", \"image_generator\", \"text_reader\"]:\n                self.product = self.tool(**new_args)\n            else:\n                self.result = self.tool(**new_args)\n        except Exception as e:\n            self.status = \"failed\"\n            self.message = str(e)\n        self.status = \"completed\"\n        self.save_product()\n        return self.result\n[docs]class TaskExecutor:\n    \"\"\"Load tools to execute tasks.\"\"\"\n[docs]    def __init__(self, plan: Plan):\n        self.plan = plan\n        self.tasks = []\n        self.id_task_map = {}\n        self.status = \"pending\"\n        for step in self.plan.steps:\n            task = Task(step.task, step.id, step.dep, step.args, step.tool)\n            self.tasks.append(task)\n            self.id_task_map[step.id] = task\n[docs]    def completed(self) -> bool:\n        return all(task.completed() for task in self.tasks)\n[docs]    def failed(self) -> bool:\n        return any(task.failed() for task in self.tasks)\n[docs]    def pending(self) -> bool:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_executor.html"}
{"id": "a870991b6b13-2", "text": "[docs]    def pending(self) -> bool:\n        return any(task.pending() for task in self.tasks)\n[docs]    def check_dependency(self, task: Task) -> bool:\n        for dep_id in task.dep:\n            if dep_id == -1:\n                continue\n            dep_task = self.id_task_map[dep_id]\n            if dep_task.failed() or dep_task.pending():\n                return False\n        return True\n[docs]    def update_args(self, task: Task) -> None:\n        for dep_id in task.dep:\n            if dep_id == -1:\n                continue\n            dep_task = self.id_task_map[dep_id]\n            for k, v in task.args.items():\n                if f\"<resource-{dep_id}>\" in v:\n                    task.args[k] = task.args[k].replace(\n                        f\"<resource-{dep_id}>\", dep_task.result\n                    )\n[docs]    def run(self) -> str:\n        for task in self.tasks:\n            print(f\"running {task}\")\n            if task.pending() and self.check_dependency(task):\n                self.update_args(task)\n                task.run()\n        if self.completed():\n            self.status = \"completed\"\n        elif self.failed():\n            self.status = \"failed\"\n        else:\n            self.status = \"pending\"\n        return self.status\n    def __str__(self) -> str:\n        result = \"\"\n        for task in self.tasks:\n            result += f\"{task}\\n\"\n            result += f\"status: {task.status}\\n\"\n            if task.failed():\n                result += f\"message: {task.message}\\n\"\n            if task.completed():\n                result += f\"result: {task.result}\\n\"\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_executor.html"}
{"id": "a870991b6b13-3", "text": "result += f\"result: {task.result}\\n\"\n        return result\n    def __repr__(self) -> str:\n        return self.__str__()\n[docs]    def describe(self) -> str:\n        return self.__str__()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_executor.html"}
{"id": "9a25f0a8907a-0", "text": "Source code for langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator\nfrom typing import Any, List, Optional\nfrom langchain.base_language import BaseLanguageModel\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains import LLMChain\nfrom langchain.prompts import PromptTemplate\n[docs]class ResponseGenerationChain(LLMChain):\n    \"\"\"Chain to execute tasks.\"\"\"\n[docs]    @classmethod\n    def from_llm(cls, llm: BaseLanguageModel, verbose: bool = True) -> LLMChain:\n        execution_template = (\n            \"The AI assistant has parsed the user input into several tasks\"\n            \"and executed them. The results are as follows:\\n\"\n            \"{task_execution}\"\n            \"\\nPlease summarize the results and generate a response.\"\n        )\n        prompt = PromptTemplate(\n            template=execution_template,\n            input_variables=[\"task_execution\"],\n        )\n        return cls(prompt=prompt, llm=llm, verbose=verbose)\n[docs]class ResponseGenerator:\n[docs]    def __init__(self, llm_chain: LLMChain, stop: Optional[List] = None):\n        self.llm_chain = llm_chain\n        self.stop = stop\n[docs]    def generate(self, inputs: dict, callbacks: Callbacks = None, **kwargs: Any) -> str:\n        \"\"\"Given input, decided what to do.\"\"\"\n        llm_response = self.llm_chain.run(**inputs, stop=self.stop, callbacks=callbacks)\n        return llm_response\n[docs]def load_response_generator(llm: BaseLanguageModel) -> ResponseGenerator:\n    llm_chain = ResponseGenerationChain.from_llm(llm)\n    return ResponseGenerator(\n        llm_chain=llm_chain,\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/repsonse_generator.html"}
{"id": "a16e61801e75-0", "text": "Source code for langchain_experimental.autonomous_agents.hugginggpt.hugginggpt\nfrom typing import List\nfrom langchain.base_language import BaseLanguageModel\nfrom langchain.tools.base import BaseTool\nfrom langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator import (\n    load_response_generator,\n)\nfrom langchain_experimental.autonomous_agents.hugginggpt.task_executor import (\n    TaskExecutor,\n)\nfrom langchain_experimental.autonomous_agents.hugginggpt.task_planner import (\n    load_chat_planner,\n)\n[docs]class HuggingGPT:\n[docs]    def __init__(self, llm: BaseLanguageModel, tools: List[BaseTool]):\n        self.llm = llm\n        self.tools = tools\n        self.chat_planner = load_chat_planner(llm)\n        self.response_generator = load_response_generator(llm)\n        self.task_executor: TaskExecutor\n[docs]    def run(self, input: str) -> str:\n        plan = self.chat_planner.plan(inputs={\"input\": input, \"hf_tools\": self.tools})\n        self.task_executor = TaskExecutor(plan)\n        self.task_executor.run()\n        response = self.response_generator.generate(\n            {\"task_execution\": self.task_executor}\n        )\n        return response", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/hugginggpt.html"}
{"id": "10aaebf82672-0", "text": "Source code for langchain_experimental.autonomous_agents.hugginggpt.task_planner\nimport json\nimport re\nfrom abc import abstractmethod\nfrom typing import Any, Dict, List, Optional, Union\nfrom langchain.base_language import BaseLanguageModel\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains import LLMChain\nfrom langchain.prompts.chat import (\n    AIMessagePromptTemplate,\n    ChatPromptTemplate,\n    HumanMessagePromptTemplate,\n    SystemMessagePromptTemplate,\n)\nfrom langchain.tools.base import BaseTool\nfrom langchain_experimental.pydantic_v1 import BaseModel\nDEMONSTRATIONS = [\n    {\n        \"role\": \"user\",\n        \"content\": \"please show me a video and an image of (based on the text) 'a boy is running' and dub it\",  # noqa: E501\n    },\n    {\n        \"role\": \"assistant\",\n        \"content\": '[{{\"task\": \"video_generator\", \"id\": 0, \"dep\": [-1], \"args\": {{\"prompt\": \"a boy is running\" }}}}, {{\"task\": \"text_reader\", \"id\": 1, \"dep\": [-1], \"args\": {{\"text\": \"a boy is running\" }}}}, {{\"task\": \"image_generator\", \"id\": 2, \"dep\": [-1], \"args\": {{\"prompt\": \"a boy is running\" }}}}]',  # noqa: E501\n    },\n    {\n        \"role\": \"user\",\n        \"content\": \"Give you some pictures e1.jpg, e2.png, e3.jpg, help me count the number of sheep?\",  # noqa: E501\n    },\n    {\n        \"role\": \"assistant\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_planner.html"}
{"id": "10aaebf82672-1", "text": "},\n    {\n        \"role\": \"assistant\",\n        \"content\": '[ {{\"task\": \"image_qa\", \"id\": 0, \"dep\": [-1], \"args\": {{\"image\": \"e1.jpg\", \"question\": \"How many sheep in the picture\"}}}}, {{\"task\": \"image_qa\", \"id\": 1, \"dep\": [-1], \"args\": {{\"image\": \"e2.jpg\", \"question\": \"How many sheep in the picture\"}}}}, {{\"task\": \"image_qa\", \"id\": 2, \"dep\": [-1], \"args\": {{\"image\": \"e3.jpg\", \"question\": \"How many sheep in the picture\"}}}}]',  # noqa: E501\n    },\n]\n[docs]class TaskPlaningChain(LLMChain):\n    \"\"\"Chain to execute tasks.\"\"\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        demos: List[Dict] = DEMONSTRATIONS,\n        verbose: bool = True,\n    ) -> LLMChain:\n        \"\"\"Get the response parser.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_planner.html"}
{"id": "10aaebf82672-2", "text": ") -> LLMChain:\n        \"\"\"Get the response parser.\"\"\"\n        system_template = \"\"\"#1 Task Planning Stage: The AI assistant can parse user input to several tasks: [{{\"task\": task, \"id\": task_id, \"dep\": dependency_task_id, \"args\": {{\"input name\": text may contain <resource-dep_id>}}}}]. The special tag \"dep_id\" refer to the one generated text/image/audio in the dependency task (Please consider whether the dependency task generates resources of this type.) and \"dep_id\" must be in \"dep\" list. The \"dep\" field denotes the ids of the previous prerequisite tasks which generate a new resource that the current task relies on. The task MUST be selected from the following tools (along with tool description, input name and output type): {tools}. There may be multiple tasks of the same type. Think step by step about all the tasks needed to resolve the user's request. Parse out as few tasks as possible while ensuring that the user request can be resolved. Pay attention to the dependencies and order among tasks. If the user input can't be parsed, you need to reply empty JSON [].\"\"\"  # noqa: E501\n        human_template = \"\"\"Now I input: {input}.\"\"\"\n        system_message_prompt = SystemMessagePromptTemplate.from_template(\n            system_template\n        )\n        human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\n        demo_messages: List[\n            Union[HumanMessagePromptTemplate, AIMessagePromptTemplate]\n        ] = []\n        for demo in demos:\n            if demo[\"role\"] == \"user\":\n                demo_messages.append(\n                    HumanMessagePromptTemplate.from_template(demo[\"content\"])\n                )\n            else:\n                demo_messages.append(\n                    AIMessagePromptTemplate.from_template(demo[\"content\"])\n                )\n            # demo_messages.append(message)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_planner.html"}
{"id": "10aaebf82672-3", "text": ")\n            # demo_messages.append(message)\n        prompt = ChatPromptTemplate.from_messages(\n            [system_message_prompt, *demo_messages, human_message_prompt]\n        )\n        return cls(prompt=prompt, llm=llm, verbose=verbose)\n[docs]class Step:\n[docs]    def __init__(\n        self, task: str, id: int, dep: List[int], args: Dict[str, str], tool: BaseTool\n    ):\n        self.task = task\n        self.id = id\n        self.dep = dep\n        self.args = args\n        self.tool = tool\n[docs]class Plan:\n[docs]    def __init__(self, steps: List[Step]):\n        self.steps = steps\n    def __str__(self) -> str:\n        return str([str(step) for step in self.steps])\n    def __repr__(self) -> str:\n        return str(self)\n[docs]class BasePlanner(BaseModel):\n[docs]    @abstractmethod\n    def plan(self, inputs: dict, callbacks: Callbacks = None, **kwargs: Any) -> Plan:\n        \"\"\"Given input, decide what to do.\"\"\"\n[docs]    @abstractmethod\n    async def aplan(\n        self, inputs: dict, callbacks: Callbacks = None, **kwargs: Any\n    ) -> Plan:\n        \"\"\"Given input, decide what to do.\"\"\"\n[docs]class PlanningOutputParser(BaseModel):\n[docs]    def parse(self, text: str, hf_tools: List[BaseTool]) -> Plan:\n        steps = []\n        for v in json.loads(re.findall(r\"\\[.*\\]\", text)[0]):\n            choose_tool = None\n            for tool in hf_tools:\n                if tool.name == v[\"task\"]:\n                    choose_tool = tool", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_planner.html"}
{"id": "10aaebf82672-4", "text": "if tool.name == v[\"task\"]:\n                    choose_tool = tool\n                    break\n            if choose_tool:\n                steps.append(Step(v[\"task\"], v[\"id\"], v[\"dep\"], v[\"args\"], tool))\n        return Plan(steps=steps)\n[docs]class TaskPlanner(BasePlanner):\n    llm_chain: LLMChain\n    output_parser: PlanningOutputParser\n    stop: Optional[List] = None\n[docs]    def plan(self, inputs: dict, callbacks: Callbacks = None, **kwargs: Any) -> Plan:\n        \"\"\"Given input, decided what to do.\"\"\"\n        inputs[\"tools\"] = [\n            f\"{tool.name}: {tool.description}\" for tool in inputs[\"hf_tools\"]\n        ]\n        llm_response = self.llm_chain.run(**inputs, stop=self.stop, callbacks=callbacks)\n        return self.output_parser.parse(llm_response, inputs[\"hf_tools\"])\n[docs]    async def aplan(\n        self, inputs: dict, callbacks: Callbacks = None, **kwargs: Any\n    ) -> Plan:\n        \"\"\"Given input, decided what to do.\"\"\"\n        inputs[\"hf_tools\"] = [\n            f\"{tool.name}: {tool.description}\" for tool in inputs[\"hf_tools\"]\n        ]\n        llm_response = await self.llm_chain.arun(\n            **inputs, stop=self.stop, callbacks=callbacks\n        )\n        return self.output_parser.parse(llm_response, inputs[\"hf_tools\"])\n[docs]def load_chat_planner(llm: BaseLanguageModel) -> TaskPlanner:\n    llm_chain = TaskPlaningChain.from_llm(llm)\n    return TaskPlanner(llm_chain=llm_chain, output_parser=PlanningOutputParser())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_planner.html"}
{"id": "23b16d52b33d-0", "text": "Source code for langchain_experimental.plan_and_execute.schema\nfrom abc import abstractmethod\nfrom typing import List, Tuple\nfrom langchain.schema import BaseOutputParser\nfrom langchain_experimental.pydantic_v1 import BaseModel, Field\n[docs]class Step(BaseModel):\n    \"\"\"Step.\"\"\"\n    value: str\n    \"\"\"The value.\"\"\"\n[docs]class Plan(BaseModel):\n    \"\"\"Plan.\"\"\"\n    steps: List[Step]\n    \"\"\"The steps.\"\"\"\n[docs]class StepResponse(BaseModel):\n    \"\"\"Step response.\"\"\"\n    response: str\n    \"\"\"The response.\"\"\"\n[docs]class BaseStepContainer(BaseModel):\n    \"\"\"Base step container.\"\"\"\n[docs]    @abstractmethod\n    def add_step(self, step: Step, step_response: StepResponse) -> None:\n        \"\"\"Add step and step response to the container.\"\"\"\n[docs]    @abstractmethod\n    def get_final_response(self) -> str:\n        \"\"\"Return the final response based on steps taken.\"\"\"\n[docs]class ListStepContainer(BaseStepContainer):\n    \"\"\"List step container.\"\"\"\n    steps: List[Tuple[Step, StepResponse]] = Field(default_factory=list)\n    \"\"\"The steps.\"\"\"\n[docs]    def add_step(self, step: Step, step_response: StepResponse) -> None:\n        self.steps.append((step, step_response))\n[docs]    def get_steps(self) -> List[Tuple[Step, StepResponse]]:\n        return self.steps\n[docs]    def get_final_response(self) -> str:\n        return self.steps[-1][1].response\n[docs]class PlanOutputParser(BaseOutputParser):\n    \"\"\"Plan output parser.\"\"\"\n[docs]    @abstractmethod\n    def parse(self, text: str) -> Plan:\n        \"\"\"Parse into a plan.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/schema.html"}
{"id": "1fad037fd3e3-0", "text": "Source code for langchain_experimental.plan_and_execute.agent_executor\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains.base import Chain\nfrom langchain_experimental.plan_and_execute.executors.base import BaseExecutor\nfrom langchain_experimental.plan_and_execute.planners.base import BasePlanner\nfrom langchain_experimental.plan_and_execute.schema import (\n    BaseStepContainer,\n    ListStepContainer,\n)\nfrom langchain_experimental.pydantic_v1 import Field\n[docs]class PlanAndExecute(Chain):\n    \"\"\"Plan and execute a chain of steps.\"\"\"\n    planner: BasePlanner\n    \"\"\"The planner to use.\"\"\"\n    executor: BaseExecutor\n    \"\"\"The executor to use.\"\"\"\n    step_container: BaseStepContainer = Field(default_factory=ListStepContainer)\n    \"\"\"The step container to use.\"\"\"\n    input_key: str = \"input\"\n    output_key: str = \"output\"\n    @property\n    def input_keys(self) -> List[str]:\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        return [self.output_key]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        plan = self.planner.plan(\n            inputs,\n            callbacks=run_manager.get_child() if run_manager else None,\n        )\n        if run_manager:\n            run_manager.on_text(str(plan), verbose=self.verbose)\n        for step in plan.steps:\n            _new_inputs = {\n                \"previous_steps\": self.step_container,\n                \"current_step\": step,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/agent_executor.html"}
{"id": "1fad037fd3e3-1", "text": "\"previous_steps\": self.step_container,\n                \"current_step\": step,\n                \"objective\": inputs[self.input_key],\n            }\n            new_inputs = {**_new_inputs, **inputs}\n            response = self.executor.step(\n                new_inputs,\n                callbacks=run_manager.get_child() if run_manager else None,\n            )\n            if run_manager:\n                run_manager.on_text(\n                    f\"*****\\n\\nStep: {step.value}\", verbose=self.verbose\n                )\n                run_manager.on_text(\n                    f\"\\n\\nResponse: {response.response}\", verbose=self.verbose\n                )\n            self.step_container.add_step(step, response)\n        return {self.output_key: self.step_container.get_final_response()}\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        plan = await self.planner.aplan(\n            inputs,\n            callbacks=run_manager.get_child() if run_manager else None,\n        )\n        if run_manager:\n            await run_manager.on_text(str(plan), verbose=self.verbose)\n        for step in plan.steps:\n            _new_inputs = {\n                \"previous_steps\": self.step_container,\n                \"current_step\": step,\n                \"objective\": inputs[self.input_key],\n            }\n            new_inputs = {**_new_inputs, **inputs}\n            response = await self.executor.astep(\n                new_inputs,\n                callbacks=run_manager.get_child() if run_manager else None,\n            )\n            if run_manager:\n                await run_manager.on_text(\n                    f\"*****\\n\\nStep: {step.value}\", verbose=self.verbose\n                )\n                await run_manager.on_text(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/agent_executor.html"}
{"id": "1fad037fd3e3-2", "text": ")\n                await run_manager.on_text(\n                    f\"\\n\\nResponse: {response.response}\", verbose=self.verbose\n                )\n            self.step_container.add_step(step, response)\n        return {self.output_key: self.step_container.get_final_response()}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/agent_executor.html"}
{"id": "6c1e8c955475-0", "text": "Source code for langchain_experimental.plan_and_execute.executors.base\nfrom abc import abstractmethod\nfrom typing import Any\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains.base import Chain\nfrom langchain_experimental.plan_and_execute.schema import StepResponse\nfrom langchain_experimental.pydantic_v1 import BaseModel\n[docs]class BaseExecutor(BaseModel):\n    \"\"\"Base executor.\"\"\"\n[docs]    @abstractmethod\n    def step(\n        self, inputs: dict, callbacks: Callbacks = None, **kwargs: Any\n    ) -> StepResponse:\n        \"\"\"Take step.\"\"\"\n[docs]    @abstractmethod\n    async def astep(\n        self, inputs: dict, callbacks: Callbacks = None, **kwargs: Any\n    ) -> StepResponse:\n        \"\"\"Take async step.\"\"\"\n[docs]class ChainExecutor(BaseExecutor):\n    \"\"\"Chain executor.\"\"\"\n    chain: Chain\n    \"\"\"The chain to use.\"\"\"\n[docs]    def step(\n        self, inputs: dict, callbacks: Callbacks = None, **kwargs: Any\n    ) -> StepResponse:\n        \"\"\"Take step.\"\"\"\n        response = self.chain.run(**inputs, callbacks=callbacks)\n        return StepResponse(response=response)\n[docs]    async def astep(\n        self, inputs: dict, callbacks: Callbacks = None, **kwargs: Any\n    ) -> StepResponse:\n        \"\"\"Take step.\"\"\"\n        response = await self.chain.arun(**inputs, callbacks=callbacks)\n        return StepResponse(response=response)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/executors/base.html"}
{"id": "c86889b2234e-0", "text": "Source code for langchain_experimental.plan_and_execute.executors.agent_executor\nfrom typing import List\nfrom langchain.agents.agent import AgentExecutor\nfrom langchain.agents.structured_chat.base import StructuredChatAgent\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools import BaseTool\nfrom langchain_experimental.plan_and_execute.executors.base import ChainExecutor\nHUMAN_MESSAGE_TEMPLATE = \"\"\"Previous steps: {previous_steps}\nCurrent objective: {current_step}\n{agent_scratchpad}\"\"\"\nTASK_PREFIX = \"\"\"{objective}\n\"\"\"\n[docs]def load_agent_executor(\n    llm: BaseLanguageModel,\n    tools: List[BaseTool],\n    verbose: bool = False,\n    include_task_in_prompt: bool = False,\n) -> ChainExecutor:\n    \"\"\"\n    Load an agent executor.\n    Args:\n        llm: BaseLanguageModel\n        tools: List[BaseTool]\n        verbose: bool. Defaults to False.\n        include_task_in_prompt: bool. Defaults to False.\n    Returns:\n        ChainExecutor\n    \"\"\"\n    input_variables = [\"previous_steps\", \"current_step\", \"agent_scratchpad\"]\n    template = HUMAN_MESSAGE_TEMPLATE\n    if include_task_in_prompt:\n        input_variables.append(\"objective\")\n        template = TASK_PREFIX + template\n    agent = StructuredChatAgent.from_llm_and_tools(\n        llm,\n        tools,\n        human_message_template=template,\n        input_variables=input_variables,\n    )\n    agent_executor = AgentExecutor.from_agent_and_tools(\n        agent=agent, tools=tools, verbose=verbose\n    )\n    return ChainExecutor(chain=agent_executor)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/executors/agent_executor.html"}
{"id": "14f4f5c4100d-0", "text": "Source code for langchain_experimental.plan_and_execute.planners.chat_planner\nimport re\nfrom langchain.chains import LLMChain\nfrom langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import SystemMessage\nfrom langchain_experimental.plan_and_execute.planners.base import LLMPlanner\nfrom langchain_experimental.plan_and_execute.schema import (\n    Plan,\n    PlanOutputParser,\n    Step,\n)\nSYSTEM_PROMPT = (\n    \"Let's first understand the problem and devise a plan to solve the problem.\"\n    \" Please output the plan starting with the header 'Plan:' \"\n    \"and then followed by a numbered list of steps. \"\n    \"Please make the plan the minimum number of steps required \"\n    \"to accurately complete the task. If the task is a question, \"\n    \"the final step should almost always be 'Given the above steps taken, \"\n    \"please respond to the users original question'. \"\n    \"At the end of your plan, say '<END_OF_PLAN>'\"\n)\n[docs]class PlanningOutputParser(PlanOutputParser):\n    \"\"\"Planning output parser.\"\"\"\n[docs]    def parse(self, text: str) -> Plan:\n        steps = [Step(value=v) for v in re.split(\"\\n\\s*\\d+\\. \", text)[1:]]\n        return Plan(steps=steps)\n[docs]def load_chat_planner(\n    llm: BaseLanguageModel, system_prompt: str = SYSTEM_PROMPT\n) -> LLMPlanner:\n    \"\"\"\n    Load a chat planner.\n    Args:\n        llm: Language model.\n        system_prompt: System prompt.\n    Returns:\n        LLMPlanner\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/planners/chat_planner.html"}
{"id": "14f4f5c4100d-1", "text": "Returns:\n        LLMPlanner\n    \"\"\"\n    prompt_template = ChatPromptTemplate.from_messages(\n        [\n            SystemMessage(content=system_prompt),\n            HumanMessagePromptTemplate.from_template(\"{input}\"),\n        ]\n    )\n    llm_chain = LLMChain(llm=llm, prompt=prompt_template)\n    return LLMPlanner(\n        llm_chain=llm_chain,\n        output_parser=PlanningOutputParser(),\n        stop=[\"<END_OF_PLAN>\"],\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/planners/chat_planner.html"}
{"id": "1bd2f57609aa-0", "text": "Source code for langchain_experimental.plan_and_execute.planners.base\nfrom abc import abstractmethod\nfrom typing import Any, List, Optional\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains.llm import LLMChain\nfrom langchain_experimental.plan_and_execute.schema import Plan, PlanOutputParser\nfrom langchain_experimental.pydantic_v1 import BaseModel\n[docs]class BasePlanner(BaseModel):\n    \"\"\"Base planner.\"\"\"\n[docs]    @abstractmethod\n    def plan(self, inputs: dict, callbacks: Callbacks = None, **kwargs: Any) -> Plan:\n        \"\"\"Given input, decide what to do.\"\"\"\n[docs]    @abstractmethod\n    async def aplan(\n        self, inputs: dict, callbacks: Callbacks = None, **kwargs: Any\n    ) -> Plan:\n        \"\"\"Given input, asynchronously decide what to do.\"\"\"\n[docs]class LLMPlanner(BasePlanner):\n    \"\"\"LLM planner.\"\"\"\n    llm_chain: LLMChain\n    \"\"\"The LLM chain to use.\"\"\"\n    output_parser: PlanOutputParser\n    \"\"\"The output parser to use.\"\"\"\n    stop: Optional[List] = None\n    \"\"\"The stop list to use.\"\"\"\n[docs]    def plan(self, inputs: dict, callbacks: Callbacks = None, **kwargs: Any) -> Plan:\n        \"\"\"Given input, decide what to do.\"\"\"\n        llm_response = self.llm_chain.run(**inputs, stop=self.stop, callbacks=callbacks)\n        return self.output_parser.parse(llm_response)\n[docs]    async def aplan(\n        self, inputs: dict, callbacks: Callbacks = None, **kwargs: Any\n    ) -> Plan:\n        \"\"\"Given input, asynchronously decide what to do.\"\"\"\n        llm_response = await self.llm_chain.arun(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/planners/base.html"}
{"id": "1bd2f57609aa-1", "text": "llm_response = await self.llm_chain.arun(\n            **inputs, stop=self.stop, callbacks=callbacks\n        )\n        return self.output_parser.parse(llm_response)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/planners/base.html"}
{"id": "8fb97a68d0db-0", "text": "Source code for langchain_experimental.agents.agent_toolkits.spark.base\n\"\"\"Agent for working with pandas objects.\"\"\"\nfrom typing import Any, Dict, List, Optional\nfrom langchain.agents.agent import AgentExecutor\nfrom langchain.agents.mrkl.base import ZeroShotAgent\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains.llm import LLMChain\nfrom langchain.llms.base import BaseLLM\nfrom langchain_experimental.agents.agent_toolkits.spark.prompt import PREFIX, SUFFIX\nfrom langchain_experimental.tools.python.tool import PythonAstREPLTool\ndef _validate_spark_df(df: Any) -> bool:\n    try:\n        from pyspark.sql import DataFrame as SparkLocalDataFrame\n        return isinstance(df, SparkLocalDataFrame)\n    except ImportError:\n        return False\ndef _validate_spark_connect_df(df: Any) -> bool:\n    try:\n        from pyspark.sql.connect.dataframe import DataFrame as SparkConnectDataFrame\n        return isinstance(df, SparkConnectDataFrame)\n    except ImportError:\n        return False\n[docs]def create_spark_dataframe_agent(\n    llm: BaseLLM,\n    df: Any,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    prefix: str = PREFIX,\n    suffix: str = SUFFIX,\n    input_variables: Optional[List[str]] = None,\n    verbose: bool = False,\n    return_intermediate_steps: bool = False,\n    max_iterations: Optional[int] = 15,\n    max_execution_time: Optional[float] = None,\n    early_stopping_method: str = \"force\",\n    agent_executor_kwargs: Optional[Dict[str, Any]] = None,\n    **kwargs: Any,\n) -> AgentExecutor:\n    \"\"\"Construct a Spark agent from an LLM and dataframe.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/spark/base.html"}
{"id": "8fb97a68d0db-1", "text": ") -> AgentExecutor:\n    \"\"\"Construct a Spark agent from an LLM and dataframe.\"\"\"\n    if not _validate_spark_df(df) and not _validate_spark_connect_df(df):\n        raise ImportError(\"Spark is not installed. run `pip install pyspark`.\")\n    if input_variables is None:\n        input_variables = [\"df\", \"input\", \"agent_scratchpad\"]\n    tools = [PythonAstREPLTool(locals={\"df\": df})]\n    prompt = ZeroShotAgent.create_prompt(\n        tools, prefix=prefix, suffix=suffix, input_variables=input_variables\n    )\n    partial_prompt = prompt.partial(df=str(df.first()))\n    llm_chain = LLMChain(\n        llm=llm,\n        prompt=partial_prompt,\n        callback_manager=callback_manager,\n    )\n    tool_names = [tool.name for tool in tools]\n    agent = ZeroShotAgent(\n        llm_chain=llm_chain,\n        allowed_tools=tool_names,\n        callback_manager=callback_manager,\n        **kwargs,\n    )\n    return AgentExecutor.from_agent_and_tools(\n        agent=agent,\n        tools=tools,\n        callback_manager=callback_manager,\n        verbose=verbose,\n        return_intermediate_steps=return_intermediate_steps,\n        max_iterations=max_iterations,\n        max_execution_time=max_execution_time,\n        early_stopping_method=early_stopping_method,\n        **(agent_executor_kwargs or {}),\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/spark/base.html"}
{"id": "f25fc56e5192-0", "text": "Source code for langchain_experimental.agents.agent_toolkits.xorbits.base\n\"\"\"Agent for working with xorbits objects.\"\"\"\nfrom typing import Any, Dict, List, Optional\nfrom langchain.agents.agent import AgentExecutor\nfrom langchain.agents.mrkl.base import ZeroShotAgent\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains.llm import LLMChain\nfrom langchain.llms.base import BaseLLM\nfrom langchain_experimental.agents.agent_toolkits.xorbits.prompt import (\n    NP_PREFIX,\n    NP_SUFFIX,\n    PD_PREFIX,\n    PD_SUFFIX,\n)\nfrom langchain_experimental.tools.python.tool import PythonAstREPLTool\n[docs]def create_xorbits_agent(\n    llm: BaseLLM,\n    data: Any,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    prefix: str = \"\",\n    suffix: str = \"\",\n    input_variables: Optional[List[str]] = None,\n    verbose: bool = False,\n    return_intermediate_steps: bool = False,\n    max_iterations: Optional[int] = 15,\n    max_execution_time: Optional[float] = None,\n    early_stopping_method: str = \"force\",\n    agent_executor_kwargs: Optional[Dict[str, Any]] = None,\n    **kwargs: Dict[str, Any],\n) -> AgentExecutor:\n    \"\"\"Construct a xorbits agent from an LLM and dataframe.\"\"\"\n    try:\n        from xorbits import numpy as np\n        from xorbits import pandas as pd\n    except ImportError:\n        raise ImportError(\n            \"Xorbits package not installed, please install with `pip install xorbits`\"\n        )\n    if not isinstance(data, (pd.DataFrame, np.ndarray)):\n        raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/xorbits/base.html"}
{"id": "f25fc56e5192-1", "text": "if not isinstance(data, (pd.DataFrame, np.ndarray)):\n        raise ValueError(\n            f\"Expected Xorbits DataFrame or ndarray object, got {type(data)}\"\n        )\n    if input_variables is None:\n        input_variables = [\"data\", \"input\", \"agent_scratchpad\"]\n    tools = [PythonAstREPLTool(locals={\"data\": data})]\n    prompt, partial_input = None, None\n    if isinstance(data, pd.DataFrame):\n        prompt = ZeroShotAgent.create_prompt(\n            tools,\n            prefix=PD_PREFIX if prefix == \"\" else prefix,\n            suffix=PD_SUFFIX if suffix == \"\" else suffix,\n            input_variables=input_variables,\n        )\n        partial_input = str(data.head())\n    else:\n        prompt = ZeroShotAgent.create_prompt(\n            tools,\n            prefix=NP_PREFIX if prefix == \"\" else prefix,\n            suffix=NP_SUFFIX if suffix == \"\" else suffix,\n            input_variables=input_variables,\n        )\n        partial_input = str(data[: len(data) // 2])\n    partial_prompt = prompt.partial(data=partial_input)\n    llm_chain = LLMChain(\n        llm=llm,\n        prompt=partial_prompt,\n        callback_manager=callback_manager,\n    )\n    tool_names = [tool.name for tool in tools]\n    agent = ZeroShotAgent(\n        llm_chain=llm_chain,\n        allowed_tools=tool_names,\n        callback_manager=callback_manager,\n        **kwargs,\n    )\n    return AgentExecutor.from_agent_and_tools(\n        agent=agent,\n        tools=tools,\n        callback_manager=callback_manager,\n        verbose=verbose,\n        return_intermediate_steps=return_intermediate_steps,\n        max_iterations=max_iterations,\n        max_execution_time=max_execution_time,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/xorbits/base.html"}
{"id": "f25fc56e5192-2", "text": "max_iterations=max_iterations,\n        max_execution_time=max_execution_time,\n        early_stopping_method=early_stopping_method,\n        **(agent_executor_kwargs or {}),\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/xorbits/base.html"}
{"id": "2f12915be0f3-0", "text": "Source code for langchain_experimental.agents.agent_toolkits.csv.base\nfrom io import IOBase\nfrom typing import Any, List, Optional, Union\nfrom langchain.agents.agent import AgentExecutor\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain_experimental.agents.agent_toolkits.pandas.base import (\n    create_pandas_dataframe_agent,\n)\n[docs]def create_csv_agent(\n    llm: BaseLanguageModel,\n    path: Union[str, IOBase, List[Union[str, IOBase]]],\n    pandas_kwargs: Optional[dict] = None,\n    **kwargs: Any,\n) -> AgentExecutor:\n    \"\"\"Create csv agent by loading to a dataframe and using pandas agent.\"\"\"\n    try:\n        import pandas as pd\n    except ImportError:\n        raise ImportError(\n            \"pandas package not found, please install with `pip install pandas`\"\n        )\n    _kwargs = pandas_kwargs or {}\n    if isinstance(path, (str, IOBase)):\n        df = pd.read_csv(path, **_kwargs)\n    elif isinstance(path, list):\n        df = []\n        for item in path:\n            if not isinstance(item, (str, IOBase)):\n                raise ValueError(f\"Expected str or file-like object, got {type(path)}\")\n            df.append(pd.read_csv(item, **_kwargs))\n    else:\n        raise ValueError(f\"Expected str, list, or file-like object, got {type(path)}\")\n    return create_pandas_dataframe_agent(llm, df, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/csv/base.html"}
{"id": "821f20bc50d1-0", "text": "Source code for langchain_experimental.agents.agent_toolkits.python.base\n\"\"\"Python agent.\"\"\"\nfrom typing import Any, Dict, Optional\nfrom langchain.agents.agent import AgentExecutor, BaseSingleActionAgent\nfrom langchain.agents.mrkl.base import ZeroShotAgent\nfrom langchain.agents.openai_functions_agent.base import OpenAIFunctionsAgent\nfrom langchain.agents.types import AgentType\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains.llm import LLMChain\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import SystemMessage\nfrom langchain_experimental.agents.agent_toolkits.python.prompt import PREFIX\nfrom langchain_experimental.tools.python.tool import PythonREPLTool\n[docs]def create_python_agent(\n    llm: BaseLanguageModel,\n    tool: PythonREPLTool,\n    agent_type: AgentType = AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    verbose: bool = False,\n    prefix: str = PREFIX,\n    agent_executor_kwargs: Optional[Dict[str, Any]] = None,\n    **kwargs: Dict[str, Any],\n) -> AgentExecutor:\n    \"\"\"Construct a python agent from an LLM and tool.\"\"\"\n    tools = [tool]\n    agent: BaseSingleActionAgent\n    if agent_type == AgentType.ZERO_SHOT_REACT_DESCRIPTION:\n        prompt = ZeroShotAgent.create_prompt(tools, prefix=prefix)\n        llm_chain = LLMChain(\n            llm=llm,\n            prompt=prompt,\n            callback_manager=callback_manager,\n        )\n        tool_names = [tool.name for tool in tools]\n        agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/python/base.html"}
{"id": "821f20bc50d1-1", "text": "elif agent_type == AgentType.OPENAI_FUNCTIONS:\n        system_message = SystemMessage(content=prefix)\n        _prompt = OpenAIFunctionsAgent.create_prompt(system_message=system_message)\n        agent = OpenAIFunctionsAgent(\n            llm=llm,\n            prompt=_prompt,\n            tools=tools,\n            callback_manager=callback_manager,\n            **kwargs,\n        )\n    else:\n        raise ValueError(f\"Agent type {agent_type} not supported at the moment.\")\n    return AgentExecutor.from_agent_and_tools(\n        agent=agent,\n        tools=tools,\n        callback_manager=callback_manager,\n        verbose=verbose,\n        **(agent_executor_kwargs or {}),\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/python/base.html"}
{"id": "1da039b77b0e-0", "text": "Source code for langchain_experimental.agents.agent_toolkits.pandas.base\n\"\"\"Agent for working with pandas objects.\"\"\"\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple\nfrom langchain.agents.agent import AgentExecutor, BaseSingleActionAgent\nfrom langchain.agents.mrkl.base import ZeroShotAgent\nfrom langchain.agents.openai_functions_agent.base import OpenAIFunctionsAgent\nfrom langchain.agents.types import AgentType\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains.llm import LLMChain\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import SystemMessage\nfrom langchain.tools import BaseTool\nfrom langchain_experimental.agents.agent_toolkits.pandas.prompt import (\n    FUNCTIONS_WITH_DF,\n    FUNCTIONS_WITH_MULTI_DF,\n    MULTI_DF_PREFIX,\n    MULTI_DF_PREFIX_FUNCTIONS,\n    PREFIX,\n    PREFIX_FUNCTIONS,\n    SUFFIX_NO_DF,\n    SUFFIX_WITH_DF,\n    SUFFIX_WITH_MULTI_DF,\n)\nfrom langchain_experimental.tools.python.tool import PythonAstREPLTool\ndef _get_multi_prompt(\n    dfs: List[Any],\n    prefix: Optional[str] = None,\n    suffix: Optional[str] = None,\n    input_variables: Optional[List[str]] = None,\n    include_df_in_prompt: Optional[bool] = True,\n    number_of_head_rows: int = 5,\n) -> Tuple[BasePromptTemplate, List[PythonAstREPLTool]]:\n    num_dfs = len(dfs)\n    if suffix is not None:\n        suffix_to_use = suffix\n        include_dfs_head = True\n    elif include_df_in_prompt:\n        suffix_to_use = SUFFIX_WITH_MULTI_DF\n        include_dfs_head = True\n    else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html"}
{"id": "1da039b77b0e-1", "text": "include_dfs_head = True\n    else:\n        suffix_to_use = SUFFIX_NO_DF\n        include_dfs_head = False\n    if input_variables is None:\n        input_variables = [\"input\", \"agent_scratchpad\", \"num_dfs\"]\n        if include_dfs_head:\n            input_variables += [\"dfs_head\"]\n    if prefix is None:\n        prefix = MULTI_DF_PREFIX\n    df_locals = {}\n    for i, dataframe in enumerate(dfs):\n        df_locals[f\"df{i + 1}\"] = dataframe\n    tools = [PythonAstREPLTool(locals=df_locals)]\n    prompt = ZeroShotAgent.create_prompt(\n        tools, prefix=prefix, suffix=suffix_to_use, input_variables=input_variables\n    )\n    partial_prompt = prompt.partial()\n    if \"dfs_head\" in input_variables:\n        dfs_head = \"\\n\\n\".join([d.head(number_of_head_rows).to_markdown() for d in dfs])\n        partial_prompt = partial_prompt.partial(num_dfs=str(num_dfs), dfs_head=dfs_head)\n    if \"num_dfs\" in input_variables:\n        partial_prompt = partial_prompt.partial(num_dfs=str(num_dfs))\n    return partial_prompt, tools\ndef _get_single_prompt(\n    df: Any,\n    prefix: Optional[str] = None,\n    suffix: Optional[str] = None,\n    input_variables: Optional[List[str]] = None,\n    include_df_in_prompt: Optional[bool] = True,\n    number_of_head_rows: int = 5,\n) -> Tuple[BasePromptTemplate, List[PythonAstREPLTool]]:\n    if suffix is not None:\n        suffix_to_use = suffix\n        include_df_head = True\n    elif include_df_in_prompt:\n        suffix_to_use = SUFFIX_WITH_DF", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html"}
{"id": "1da039b77b0e-2", "text": "elif include_df_in_prompt:\n        suffix_to_use = SUFFIX_WITH_DF\n        include_df_head = True\n    else:\n        suffix_to_use = SUFFIX_NO_DF\n        include_df_head = False\n    if input_variables is None:\n        input_variables = [\"input\", \"agent_scratchpad\"]\n        if include_df_head:\n            input_variables += [\"df_head\"]\n    if prefix is None:\n        prefix = PREFIX\n    tools = [PythonAstREPLTool(locals={\"df\": df})]\n    prompt = ZeroShotAgent.create_prompt(\n        tools, prefix=prefix, suffix=suffix_to_use, input_variables=input_variables\n    )\n    partial_prompt = prompt.partial()\n    if \"df_head\" in input_variables:\n        partial_prompt = partial_prompt.partial(\n            df_head=str(df.head(number_of_head_rows).to_markdown())\n        )\n    return partial_prompt, tools\ndef _get_prompt_and_tools(\n    df: Any,\n    prefix: Optional[str] = None,\n    suffix: Optional[str] = None,\n    input_variables: Optional[List[str]] = None,\n    include_df_in_prompt: Optional[bool] = True,\n    number_of_head_rows: int = 5,\n) -> Tuple[BasePromptTemplate, List[PythonAstREPLTool]]:\n    try:\n        import pandas as pd\n        pd.set_option(\"display.max_columns\", None)\n    except ImportError:\n        raise ImportError(\n            \"pandas package not found, please install with `pip install pandas`\"\n        )\n    if include_df_in_prompt is not None and suffix is not None:\n        raise ValueError(\"If suffix is specified, include_df_in_prompt should not be.\")\n    if isinstance(df, list):\n        for item in df:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html"}
{"id": "1da039b77b0e-3", "text": "if isinstance(df, list):\n        for item in df:\n            if not isinstance(item, pd.DataFrame):\n                raise ValueError(f\"Expected pandas object, got {type(df)}\")\n        return _get_multi_prompt(\n            df,\n            prefix=prefix,\n            suffix=suffix,\n            input_variables=input_variables,\n            include_df_in_prompt=include_df_in_prompt,\n            number_of_head_rows=number_of_head_rows,\n        )\n    else:\n        if not isinstance(df, pd.DataFrame):\n            raise ValueError(f\"Expected pandas object, got {type(df)}\")\n        return _get_single_prompt(\n            df,\n            prefix=prefix,\n            suffix=suffix,\n            input_variables=input_variables,\n            include_df_in_prompt=include_df_in_prompt,\n            number_of_head_rows=number_of_head_rows,\n        )\ndef _get_functions_single_prompt(\n    df: Any,\n    prefix: Optional[str] = None,\n    suffix: Optional[str] = None,\n    include_df_in_prompt: Optional[bool] = True,\n    number_of_head_rows: int = 5,\n) -> Tuple[BasePromptTemplate, List[PythonAstREPLTool]]:\n    if suffix is not None:\n        suffix_to_use = suffix\n        if include_df_in_prompt:\n            suffix_to_use = suffix_to_use.format(\n                df_head=str(df.head(number_of_head_rows).to_markdown())\n            )\n    elif include_df_in_prompt:\n        suffix_to_use = FUNCTIONS_WITH_DF.format(\n            df_head=str(df.head(number_of_head_rows).to_markdown())\n        )\n    else:\n        suffix_to_use = \"\"\n    if prefix is None:\n        prefix = PREFIX_FUNCTIONS\n    tools = [PythonAstREPLTool(locals={\"df\": df})]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html"}
{"id": "1da039b77b0e-4", "text": "tools = [PythonAstREPLTool(locals={\"df\": df})]\n    system_message = SystemMessage(content=prefix + suffix_to_use)\n    prompt = OpenAIFunctionsAgent.create_prompt(system_message=system_message)\n    return prompt, tools\ndef _get_functions_multi_prompt(\n    dfs: Any,\n    prefix: Optional[str] = None,\n    suffix: Optional[str] = None,\n    include_df_in_prompt: Optional[bool] = True,\n    number_of_head_rows: int = 5,\n) -> Tuple[BasePromptTemplate, List[PythonAstREPLTool]]:\n    if suffix is not None:\n        suffix_to_use = suffix\n        if include_df_in_prompt:\n            dfs_head = \"\\n\\n\".join(\n                [d.head(number_of_head_rows).to_markdown() for d in dfs]\n            )\n            suffix_to_use = suffix_to_use.format(\n                dfs_head=dfs_head,\n            )\n    elif include_df_in_prompt:\n        dfs_head = \"\\n\\n\".join([d.head(number_of_head_rows).to_markdown() for d in dfs])\n        suffix_to_use = FUNCTIONS_WITH_MULTI_DF.format(\n            dfs_head=dfs_head,\n        )\n    else:\n        suffix_to_use = \"\"\n    if prefix is None:\n        prefix = MULTI_DF_PREFIX_FUNCTIONS\n    prefix = prefix.format(num_dfs=str(len(dfs)))\n    df_locals = {}\n    for i, dataframe in enumerate(dfs):\n        df_locals[f\"df{i + 1}\"] = dataframe\n    tools = [PythonAstREPLTool(locals=df_locals)]\n    system_message = SystemMessage(content=prefix + suffix_to_use)\n    prompt = OpenAIFunctionsAgent.create_prompt(system_message=system_message)\n    return prompt, tools", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html"}
{"id": "1da039b77b0e-5", "text": "return prompt, tools\ndef _get_functions_prompt_and_tools(\n    df: Any,\n    prefix: Optional[str] = None,\n    suffix: Optional[str] = None,\n    input_variables: Optional[List[str]] = None,\n    include_df_in_prompt: Optional[bool] = True,\n    number_of_head_rows: int = 5,\n) -> Tuple[BasePromptTemplate, List[PythonAstREPLTool]]:\n    try:\n        import pandas as pd\n        pd.set_option(\"display.max_columns\", None)\n    except ImportError:\n        raise ImportError(\n            \"pandas package not found, please install with `pip install pandas`\"\n        )\n    if input_variables is not None:\n        raise ValueError(\"`input_variables` is not supported at the moment.\")\n    if include_df_in_prompt is not None and suffix is not None:\n        raise ValueError(\"If suffix is specified, include_df_in_prompt should not be.\")\n    if isinstance(df, list):\n        for item in df:\n            if not isinstance(item, pd.DataFrame):\n                raise ValueError(f\"Expected pandas object, got {type(df)}\")\n        return _get_functions_multi_prompt(\n            df,\n            prefix=prefix,\n            suffix=suffix,\n            include_df_in_prompt=include_df_in_prompt,\n            number_of_head_rows=number_of_head_rows,\n        )\n    else:\n        if not isinstance(df, pd.DataFrame):\n            raise ValueError(f\"Expected pandas object, got {type(df)}\")\n        return _get_functions_single_prompt(\n            df,\n            prefix=prefix,\n            suffix=suffix,\n            include_df_in_prompt=include_df_in_prompt,\n            number_of_head_rows=number_of_head_rows,\n        )\n[docs]def create_pandas_dataframe_agent(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html"}
{"id": "1da039b77b0e-6", "text": ")\n[docs]def create_pandas_dataframe_agent(\n    llm: BaseLanguageModel,\n    df: Any,\n    agent_type: AgentType = AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    prefix: Optional[str] = None,\n    suffix: Optional[str] = None,\n    input_variables: Optional[List[str]] = None,\n    verbose: bool = False,\n    return_intermediate_steps: bool = False,\n    max_iterations: Optional[int] = 15,\n    max_execution_time: Optional[float] = None,\n    early_stopping_method: str = \"force\",\n    agent_executor_kwargs: Optional[Dict[str, Any]] = None,\n    include_df_in_prompt: Optional[bool] = True,\n    number_of_head_rows: int = 5,\n    extra_tools: Sequence[BaseTool] = (),\n    **kwargs: Dict[str, Any],\n) -> AgentExecutor:\n    \"\"\"Construct a pandas agent from an LLM and dataframe.\"\"\"\n    agent: BaseSingleActionAgent\n    if agent_type == AgentType.ZERO_SHOT_REACT_DESCRIPTION:\n        prompt, base_tools = _get_prompt_and_tools(\n            df,\n            prefix=prefix,\n            suffix=suffix,\n            input_variables=input_variables,\n            include_df_in_prompt=include_df_in_prompt,\n            number_of_head_rows=number_of_head_rows,\n        )\n        tools = base_tools + list(extra_tools)\n        llm_chain = LLMChain(\n            llm=llm,\n            prompt=prompt,\n            callback_manager=callback_manager,\n        )\n        tool_names = [tool.name for tool in tools]\n        agent = ZeroShotAgent(\n            llm_chain=llm_chain,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html"}
{"id": "1da039b77b0e-7", "text": "agent = ZeroShotAgent(\n            llm_chain=llm_chain,\n            allowed_tools=tool_names,\n            callback_manager=callback_manager,\n            **kwargs,\n        )\n    elif agent_type == AgentType.OPENAI_FUNCTIONS:\n        _prompt, base_tools = _get_functions_prompt_and_tools(\n            df,\n            prefix=prefix,\n            suffix=suffix,\n            input_variables=input_variables,\n            include_df_in_prompt=include_df_in_prompt,\n            number_of_head_rows=number_of_head_rows,\n        )\n        tools = base_tools + list(extra_tools)\n        agent = OpenAIFunctionsAgent(\n            llm=llm,\n            prompt=_prompt,\n            tools=tools,\n            callback_manager=callback_manager,\n            **kwargs,\n        )\n    else:\n        raise ValueError(f\"Agent type {agent_type} not supported at the moment.\")\n    return AgentExecutor.from_agent_and_tools(\n        agent=agent,\n        tools=tools,\n        callback_manager=callback_manager,\n        verbose=verbose,\n        return_intermediate_steps=return_intermediate_steps,\n        max_iterations=max_iterations,\n        max_execution_time=max_execution_time,\n        early_stopping_method=early_stopping_method,\n        **(agent_executor_kwargs or {}),\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html"}
{"id": "97d160c91520-0", "text": "Source code for langchain_experimental.llm_bash.bash\n\"\"\"Wrapper around subprocess to run commands.\"\"\"\nfrom __future__ import annotations\nimport platform\nimport re\nimport subprocess\nfrom typing import TYPE_CHECKING, List, Union\nfrom uuid import uuid4\nif TYPE_CHECKING:\n    import pexpect\n[docs]class BashProcess:\n    \"\"\"\n    Wrapper class for starting subprocesses.\n    Uses the python built-in subprocesses.run()\n    Persistent processes are **not** available\n    on Windows systems, as pexpect makes use of\n    Unix pseudoterminals (ptys). MacOS and Linux\n    are okay.\n    Example:\n        .. code-block:: python\n            from langchain.utilities.bash import BashProcess\n            bash = BashProcess(\n                strip_newlines = False,\n                return_err_output = False,\n                persistent = False\n            )\n            bash.run('echo \\'hello world\\'')\n    \"\"\"\n    strip_newlines: bool = False\n    \"\"\"Whether or not to run .strip() on the output\"\"\"\n    return_err_output: bool = False\n    \"\"\"Whether or not to return the output of a failed\n    command, or just the error message and stacktrace\"\"\"\n    persistent: bool = False\n    \"\"\"Whether or not to spawn a persistent session\n    NOTE: Unavailable for Windows environments\"\"\"\n[docs]    def __init__(\n        self,\n        strip_newlines: bool = False,\n        return_err_output: bool = False,\n        persistent: bool = False,\n    ):\n        \"\"\"\n        Initializes with default settings\n        \"\"\"\n        self.strip_newlines = strip_newlines\n        self.return_err_output = return_err_output\n        self.prompt = \"\"\n        self.process = None\n        if persistent:\n            self.prompt = str(uuid4())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/bash.html"}
{"id": "97d160c91520-1", "text": "self.process = None\n        if persistent:\n            self.prompt = str(uuid4())\n            self.process = self._initialize_persistent_process(self, self.prompt)\n    @staticmethod\n    def _lazy_import_pexpect() -> pexpect:\n        \"\"\"Import pexpect only when needed.\"\"\"\n        if platform.system() == \"Windows\":\n            raise ValueError(\n                \"Persistent bash processes are not yet supported on Windows.\"\n            )\n        try:\n            import pexpect\n        except ImportError:\n            raise ImportError(\n                \"pexpect required for persistent bash processes.\"\n                \" To install, run `pip install pexpect`.\"\n            )\n        return pexpect\n    @staticmethod\n    def _initialize_persistent_process(self: BashProcess, prompt: str) -> pexpect.spawn:\n        # Start bash in a clean environment\n        # Doesn't work on windows\n        \"\"\"\n        Initializes a persistent bash setting in a\n        clean environment.\n        NOTE: Unavailable on Windows\n        Args:\n            Prompt(str): the bash command to execute\n        \"\"\"  # noqa: E501\n        pexpect = self._lazy_import_pexpect()\n        process = pexpect.spawn(\n            \"env\", [\"-i\", \"bash\", \"--norc\", \"--noprofile\"], encoding=\"utf-8\"\n        )\n        # Set the custom prompt\n        process.sendline(\"PS1=\" + prompt)\n        process.expect_exact(prompt, timeout=10)\n        return process\n[docs]    def run(self, commands: Union[str, List[str]]) -> str:\n        \"\"\"\n        Run commands in either an existing persistent\n        subprocess or on in a new subprocess environment.\n        Args:\n            commands(List[str]): a list of commands to\n                execute in the session\n        \"\"\"  # noqa: E501", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/bash.html"}
{"id": "97d160c91520-2", "text": "execute in the session\n        \"\"\"  # noqa: E501\n        if isinstance(commands, str):\n            commands = [commands]\n        commands = \";\".join(commands)\n        if self.process is not None:\n            return self._run_persistent(\n                commands,\n            )\n        else:\n            return self._run(commands)\n    def _run(self, command: str) -> str:\n        \"\"\"\n        Runs a command in a subprocess and returns\n        the output.\n        Args:\n            command: The command to run\n        \"\"\"  # noqa: E501\n        try:\n            output = subprocess.run(\n                command,\n                shell=True,\n                check=True,\n                stdout=subprocess.PIPE,\n                stderr=subprocess.STDOUT,\n            ).stdout.decode()\n        except subprocess.CalledProcessError as error:\n            if self.return_err_output:\n                return error.stdout.decode()\n            return str(error)\n        if self.strip_newlines:\n            output = output.strip()\n        return output\n[docs]    def process_output(self, output: str, command: str) -> str:\n        \"\"\"\n        Uses regex to remove the command from the output\n        Args:\n            output: a process' output string\n            command: the executed command\n        \"\"\"  # noqa: E501\n        pattern = re.escape(command) + r\"\\s*\\n\"\n        output = re.sub(pattern, \"\", output, count=1)\n        return output.strip()\n    def _run_persistent(self, command: str) -> str:\n        \"\"\"\n        Runs commands in a persistent environment\n        and returns the output.\n        Args:\n            command: the command to execute\n        \"\"\"  # noqa: E501\n        pexpect = self._lazy_import_pexpect()\n        if self.process is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/bash.html"}
{"id": "97d160c91520-3", "text": "pexpect = self._lazy_import_pexpect()\n        if self.process is None:\n            raise ValueError(\"Process not initialized\")\n        self.process.sendline(command)\n        # Clear the output with an empty string\n        self.process.expect(self.prompt, timeout=10)\n        self.process.sendline(\"\")\n        try:\n            self.process.expect([self.prompt, pexpect.EOF], timeout=10)\n        except pexpect.TIMEOUT:\n            return f\"Timeout error while executing command {command}\"\n        if self.process.after == pexpect.EOF:\n            return f\"Exited with error status: {self.process.exitstatus}\"\n        output = self.process.before\n        output = self.process_output(output, command)\n        if self.strip_newlines:\n            return output.strip()\n        return output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/bash.html"}
{"id": "be58a027392c-0", "text": "Source code for langchain_experimental.llm_bash.prompt\n# flake8: noqa\nfrom __future__ import annotations\nimport re\nfrom typing import List\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.schema import BaseOutputParser, OutputParserException\n_PROMPT_TEMPLATE = \"\"\"If someone asks you to perform a task, your job is to come up with a series of bash commands that will perform the task. There is no need to put \"#!/bin/bash\" in your answer. Make sure to reason step by step, using this format:\nQuestion: \"copy the files in the directory named 'target' into a new directory at the same level as target called 'myNewDirectory'\"\nI need to take the following actions:\n- List all files in the directory\n- Create a new directory\n- Copy the files from the first directory into the second directory\n```bash\nls\nmkdir myNewDirectory\ncp -r target/* myNewDirectory\n```\nThat is the format. Begin!\nQuestion: {question}\"\"\"\n[docs]class BashOutputParser(BaseOutputParser):\n    \"\"\"Parser for bash output.\"\"\"\n[docs]    def parse(self, text: str) -> List[str]:\n        if \"```bash\" in text:\n            return self.get_code_blocks(text)\n        else:\n            raise OutputParserException(\n                f\"Failed to parse bash output. Got: {text}\",\n            )\n[docs]    @staticmethod\n    def get_code_blocks(t: str) -> List[str]:\n        \"\"\"Get multiple code blocks from the LLM result.\"\"\"\n        code_blocks: List[str] = []\n        # Bash markdown code blocks\n        pattern = re.compile(r\"```bash(.*?)(?:\\n\\s*)```\", re.DOTALL)\n        for match in pattern.finditer(t):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/prompt.html"}
{"id": "be58a027392c-1", "text": "for match in pattern.finditer(t):\n            matched = match.group(1).strip()\n            if matched:\n                code_blocks.extend(\n                    [line for line in matched.split(\"\\n\") if line.strip()]\n                )\n        return code_blocks\n    @property\n    def _type(self) -> str:\n        return \"bash\"\nPROMPT = PromptTemplate(\n    input_variables=[\"question\"],\n    template=_PROMPT_TEMPLATE,\n    output_parser=BashOutputParser(),\n)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/prompt.html"}
{"id": "92038ec56221-0", "text": "Source code for langchain_experimental.llm_bash.base\n\"\"\"Chain that interprets a prompt and executes bash operations.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport warnings\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.schema import BasePromptTemplate, OutputParserException\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain_experimental.llm_bash.bash import BashProcess\nfrom langchain_experimental.llm_bash.prompt import PROMPT\nfrom langchain_experimental.pydantic_v1 import Extra, Field, root_validator\nlogger = logging.getLogger(__name__)\n[docs]class LLMBashChain(Chain):\n    \"\"\"Chain that interprets a prompt and executes bash operations.\n    Example:\n        .. code-block:: python\n            from langchain.chains import LLMBashChain\n            from langchain.llms import OpenAI\n            llm_bash = LLMBashChain.from_llm(OpenAI())\n    \"\"\"\n    llm_chain: LLMChain\n    llm: Optional[BaseLanguageModel] = None\n    \"\"\"[Deprecated] LLM wrapper to use.\"\"\"\n    input_key: str = \"question\"  #: :meta private:\n    output_key: str = \"answer\"  #: :meta private:\n    prompt: BasePromptTemplate = PROMPT\n    \"\"\"[Deprecated]\"\"\"\n    bash_process: BashProcess = Field(default_factory=BashProcess)  #: :meta private:\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator(pre=True)\n    def raise_deprecation(cls, values: Dict) -> Dict:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/base.html"}
{"id": "92038ec56221-1", "text": "def raise_deprecation(cls, values: Dict) -> Dict:\n        if \"llm\" in values:\n            warnings.warn(\n                \"Directly instantiating an LLMBashChain with an llm is deprecated. \"\n                \"Please instantiate with llm_chain or using the from_llm class method.\"\n            )\n            if \"llm_chain\" not in values and values[\"llm\"] is not None:\n                prompt = values.get(\"prompt\", PROMPT)\n                values[\"llm_chain\"] = LLMChain(llm=values[\"llm\"], prompt=prompt)\n        return values\n    # TODO: move away from `root_validator` since it is deprecated in pydantic v2\n    #       and causes mypy type-checking failures (hence the `type: ignore`)\n    @root_validator  # type: ignore[call-overload]\n    def validate_prompt(cls, values: Dict) -> Dict:\n        if values[\"llm_chain\"].prompt.output_parser is None:\n            raise ValueError(\n                \"The prompt used by llm_chain is expected to have an output_parser.\"\n            )\n        return values\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Expect output key.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/base.html"}
{"id": "92038ec56221-2", "text": "_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        _run_manager.on_text(inputs[self.input_key], verbose=self.verbose)\n        t = self.llm_chain.predict(\n            question=inputs[self.input_key], callbacks=_run_manager.get_child()\n        )\n        _run_manager.on_text(t, color=\"green\", verbose=self.verbose)\n        t = t.strip()\n        try:\n            parser = self.llm_chain.prompt.output_parser\n            command_list = parser.parse(t)  # type: ignore[union-attr]\n        except OutputParserException as e:\n            _run_manager.on_chain_error(e, verbose=self.verbose)\n            raise e\n        if self.verbose:\n            _run_manager.on_text(\"\\nCode: \", verbose=self.verbose)\n            _run_manager.on_text(\n                str(command_list), color=\"yellow\", verbose=self.verbose\n            )\n        output = self.bash_process.run(command_list)\n        _run_manager.on_text(\"\\nAnswer: \", verbose=self.verbose)\n        _run_manager.on_text(output, color=\"yellow\", verbose=self.verbose)\n        return {self.output_key: output}\n    @property\n    def _chain_type(self) -> str:\n        return \"llm_bash_chain\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        prompt: BasePromptTemplate = PROMPT,\n        **kwargs: Any,\n    ) -> LLMBashChain:\n        llm_chain = LLMChain(llm=llm, prompt=prompt)\n        return cls(llm_chain=llm_chain, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/base.html"}
{"id": "4a2a61623880-0", "text": "Source code for langchain_experimental.fallacy_removal.base\n\"\"\"Chain for applying removals of logical fallacies.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain_experimental.fallacy_removal.fallacies import FALLACIES\nfrom langchain_experimental.fallacy_removal.models import LogicalFallacy\nfrom langchain_experimental.fallacy_removal.prompts import (\n    FALLACY_CRITIQUE_PROMPT,\n    FALLACY_REVISION_PROMPT,\n)\n[docs]class FallacyChain(Chain):\n    \"\"\"Chain for applying logical fallacy evaluations, modeled after Constitutional AI \\\n    and in same format, but applying logical fallacies as generalized rules to remove \\\n    in output\n    Example:\n        .. code-block:: python\n            from langchain.llms import OpenAI\n            from langchain.chains import LLMChain\n            from langchain_experimental.fallacy import FallacyChain\n            from langchain_experimental.fallacy_removal.models import LogicalFallacy\n            llm = OpenAI()\n            qa_prompt = PromptTemplate(\n                template=\"Q: {question} A:\",\n                input_variables=[\"question\"],\n            )\n            qa_chain = LLMChain(llm=llm, prompt=qa_prompt)\n            fallacy_chain = FallacyChain.from_llm(\n                llm=llm,\n                chain=qa_chain,\n                logical_fallacies=[\n                    LogicalFallacy(\n                        fallacy_critique_request=\"Tell if this answer meets criteria.\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html"}
{"id": "4a2a61623880-1", "text": "fallacy_critique_request=\"Tell if this answer meets criteria.\",\n                        fallacy_revision_request=\\\n                        \"Give an answer that meets better criteria.\",\n                    )\n                ],\n            )\n            fallacy_chain.run(question=\"How do I know if the earth is round?\")\n    \"\"\"\n    chain: LLMChain\n    logical_fallacies: List[LogicalFallacy]\n    fallacy_critique_chain: LLMChain\n    fallacy_revision_chain: LLMChain\n    return_intermediate_steps: bool = False\n[docs]    @classmethod\n    def get_fallacies(cls, names: Optional[List[str]] = None) -> List[LogicalFallacy]:\n        if names is None:\n            return list(FALLACIES.values())\n        else:\n            return [FALLACIES[name] for name in names]\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        chain: LLMChain,\n        fallacy_critique_prompt: BasePromptTemplate = FALLACY_CRITIQUE_PROMPT,\n        fallacy_revision_prompt: BasePromptTemplate = FALLACY_REVISION_PROMPT,\n        **kwargs: Any,\n    ) -> \"FallacyChain\":\n        \"\"\"Create a chain from an LLM.\"\"\"\n        fallacy_critique_chain = LLMChain(llm=llm, prompt=fallacy_critique_prompt)\n        fallacy_revision_chain = LLMChain(llm=llm, prompt=fallacy_revision_prompt)\n        return cls(\n            chain=chain,\n            fallacy_critique_chain=fallacy_critique_chain,\n            fallacy_revision_chain=fallacy_revision_chain,\n            **kwargs,\n        )\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Input keys.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html"}
{"id": "4a2a61623880-2", "text": "def input_keys(self) -> List[str]:\n        \"\"\"Input keys.\"\"\"\n        return self.chain.input_keys\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Output keys.\"\"\"\n        if self.return_intermediate_steps:\n            return [\"output\", \"fallacy_critiques_and_revisions\", \"initial_output\"]\n        return [\"output\"]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        response = self.chain.run(\n            **inputs,\n            callbacks=_run_manager.get_child(\"original\"),\n        )\n        initial_response = response\n        input_prompt = self.chain.prompt.format(**inputs)\n        _run_manager.on_text(\n            text=\"Initial response: \" + response + \"\\n\\n\",\n            verbose=self.verbose,\n            color=\"yellow\",\n        )\n        fallacy_critiques_and_revisions = []\n        for logical_fallacy in self.logical_fallacies:\n            # Fallacy critique below\n            fallacy_raw_critique = self.fallacy_critique_chain.run(\n                input_prompt=input_prompt,\n                output_from_model=response,\n                fallacy_critique_request=logical_fallacy.fallacy_critique_request,\n                callbacks=_run_manager.get_child(\"fallacy_critique\"),\n            )\n            fallacy_critique = self._parse_critique(\n                output_string=fallacy_raw_critique,\n            ).strip()\n            # if fallacy critique contains \"No fallacy critique needed\" then done\n            if \"no fallacy critique needed\" in fallacy_critique.lower():", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html"}
{"id": "4a2a61623880-3", "text": "if \"no fallacy critique needed\" in fallacy_critique.lower():\n                fallacy_critiques_and_revisions.append((fallacy_critique, \"\"))\n                continue\n            fallacy_revision = self.fallacy_revision_chain.run(\n                input_prompt=input_prompt,\n                output_from_model=response,\n                fallacy_critique_request=logical_fallacy.fallacy_critique_request,\n                fallacy_critique=fallacy_critique,\n                revision_request=logical_fallacy.fallacy_revision_request,\n                callbacks=_run_manager.get_child(\"fallacy_revision\"),\n            ).strip()\n            response = fallacy_revision\n            fallacy_critiques_and_revisions.append((fallacy_critique, fallacy_revision))\n            _run_manager.on_text(\n                text=f\"Applying {logical_fallacy.name}...\" + \"\\n\\n\",\n                verbose=self.verbose,\n                color=\"green\",\n            )\n            _run_manager.on_text(\n                text=\"Logical Fallacy: \" + fallacy_critique + \"\\n\\n\",\n                verbose=self.verbose,\n                color=\"blue\",\n            )\n            _run_manager.on_text(\n                text=\"Updated response: \" + fallacy_revision + \"\\n\\n\",\n                verbose=self.verbose,\n                color=\"yellow\",\n            )\n        final_output: Dict[str, Any] = {\"output\": response}\n        if self.return_intermediate_steps:\n            final_output[\"initial_output\"] = initial_response\n            final_output[\n                \"fallacy_critiques_and_revisions\"\n            ] = fallacy_critiques_and_revisions\n        return final_output\n    @staticmethod\n    def _parse_critique(output_string: str) -> str:\n        if \"Fallacy Revision request:\" not in output_string:\n            return output_string", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html"}
{"id": "4a2a61623880-4", "text": "if \"Fallacy Revision request:\" not in output_string:\n            return output_string\n        output_string = output_string.split(\"Fallacy Revision request:\")[0]\n        if \"\\n\\n\" in output_string:\n            output_string = output_string.split(\"\\n\\n\")[0]\n        return output_string", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html"}
{"id": "42de0ca2f1f3-0", "text": "Source code for langchain_experimental.fallacy_removal.models\n\"\"\"Models for the Logical Fallacy Chain\"\"\"\nfrom langchain_experimental.pydantic_v1 import BaseModel\n[docs]class LogicalFallacy(BaseModel):\n    \"\"\"Class for a logical fallacy.\"\"\"\n    fallacy_critique_request: str\n    fallacy_revision_request: str\n    name: str = \"Logical Fallacy\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/models.html"}
{"id": "e0c4c8d2a194-0", "text": "Source code for langchain_experimental.open_clip.open_clip\nfrom typing import Any, Dict, List\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema.embeddings import Embeddings\n[docs]class OpenCLIPEmbeddings(BaseModel, Embeddings):\n    model: Any\n    preprocess: Any\n    tokenizer: Any\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that open_clip and torch libraries are installed.\"\"\"\n        try:\n            import open_clip\n            ### Smaller, less performant\n            # model_name = \"ViT-B-32\"\n            # checkpoint = \"laion2b_s34b_b79k\"\n            ### Larger, more performant\n            model_name = \"ViT-g-14\"\n            checkpoint = \"laion2b_s34b_b88k\"\n            model, _, preprocess = open_clip.create_model_and_transforms(\n                model_name=model_name, pretrained=checkpoint\n            )\n            tokenizer = open_clip.get_tokenizer(model_name)\n            values[\"model\"] = model\n            values[\"preprocess\"] = preprocess\n            values[\"tokenizer\"] = tokenizer\n        except ImportError:\n            raise ImportError(\n                \"Please ensure both open_clip and torch libraries are installed. \"\n                \"pip install open_clip_torch torch\"\n            )\n        return values\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        text_features = []\n        for text in texts:\n            # Tokenize the text\n            tokenized_text = self.tokenizer(text)\n            # Encode the text to get the embeddings\n            embeddings_tensor = self.model.encode_text(tokenized_text)\n            # Normalize the embeddings", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/open_clip/open_clip.html"}
{"id": "e0c4c8d2a194-1", "text": "embeddings_tensor = self.model.encode_text(tokenized_text)\n            # Normalize the embeddings\n            norm = embeddings_tensor.norm(p=2, dim=1, keepdim=True)\n            normalized_embeddings_tensor = embeddings_tensor.div(norm)\n            # Convert normalized tensor to list and add to the text_features list\n            embeddings_list = normalized_embeddings_tensor.squeeze(0).tolist()\n            text_features.append(embeddings_list)\n        return text_features\n[docs]    def embed_query(self, text: str) -> List[float]:\n        return self.embed_documents([text])[0]\n[docs]    def embed_image(self, uris: List[str]) -> List[List[float]]:\n        try:\n            from PIL import Image as _PILImage\n        except ImportError:\n            raise ImportError(\"Please install the PIL library: pip install pillow\")\n        # Open images directly as PIL images\n        pil_images = [_PILImage.open(uri) for uri in uris]\n        image_features = []\n        for pil_image in pil_images:\n            # Preprocess the image for the model\n            preprocessed_image = self.preprocess(pil_image).unsqueeze(0)\n            # Encode the image to get the embeddings\n            embeddings_tensor = self.model.encode_image(preprocessed_image)\n            # Normalize the embeddings tensor\n            norm = embeddings_tensor.norm(p=2, dim=1, keepdim=True)\n            normalized_embeddings_tensor = embeddings_tensor.div(norm)\n            # Convert tensor to list and add to the image_features list\n            embeddings_list = normalized_embeddings_tensor.squeeze(0).tolist()\n            image_features.append(embeddings_list)\n        return image_features", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/open_clip/open_clip.html"}
{"id": "5072eb433e59-0", "text": "Source code for langchain_experimental.comprehend_moderation.base_moderation_config\nfrom typing import List, Union\nfrom pydantic import BaseModel\n[docs]class ModerationPiiConfig(BaseModel):\n    threshold: float = 0.5\n    \"\"\"Threshold for PII confidence score, defaults to 0.5 i.e. 50%\"\"\"\n    labels: List[str] = []\n    \"\"\"\n    List of PII Universal Labels. \n    Defaults to `list[]`\n    \"\"\"\n    redact: bool = False\n    \"\"\"Whether to perform redaction of detected PII entities\"\"\"\n    mask_character: str = \"*\"\n    \"\"\"Redaction mask character in case redact=True, defaults to asterisk (*)\"\"\"\n[docs]class ModerationToxicityConfig(BaseModel):\n    threshold: float = 0.5\n    \"\"\"Threshold for Toxic label confidence score, defaults to 0.5 i.e. 50%\"\"\"\n    labels: List[str] = []\n    \"\"\"List of toxic labels, defaults to `list[]`\"\"\"\n[docs]class ModerationPromptSafetyConfig(BaseModel):\n    threshold: float = 0.5\n    \"\"\"\n    Threshold for Prompt Safety classification\n    confidence score, defaults to 0.5 i.e. 50%\n    \"\"\"\n[docs]class BaseModerationConfig(BaseModel):\n    filters: List[\n        Union[\n            ModerationPiiConfig, ModerationToxicityConfig, ModerationPromptSafetyConfig\n        ]\n    ] = [\n        ModerationPiiConfig(),\n        ModerationToxicityConfig(),\n        ModerationPromptSafetyConfig(),\n    ]\n    \"\"\"\n    Filters applied to the moderation chain, defaults to\n    `[ModerationPiiConfig(), ModerationToxicityConfig(),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_config.html"}
{"id": "5072eb433e59-1", "text": "`[ModerationPiiConfig(), ModerationToxicityConfig(),\n    ModerationPromptSafetyConfig()]`\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_config.html"}
{"id": "812d4341cc9b-0", "text": "Source code for langchain_experimental.comprehend_moderation.toxicity\nimport asyncio\nimport importlib\nfrom typing import Any, List, Optional\nfrom langchain_experimental.comprehend_moderation.base_moderation_exceptions import (\n    ModerationToxicityError,\n)\n[docs]class ComprehendToxicity:\n[docs]    def __init__(\n        self,\n        client: Any,\n        callback: Optional[Any] = None,\n        unique_id: Optional[str] = None,\n        chain_id: Optional[str] = None,\n    ) -> None:\n        self.client = client\n        self.moderation_beacon = {\n            \"moderation_chain_id\": chain_id,\n            \"moderation_type\": \"Toxicity\",\n            \"moderation_status\": \"LABELS_NOT_FOUND\",\n        }\n        self.callback = callback\n        self.unique_id = unique_id\n    def _toxicity_init_validate(self, max_size: int) -> Any:\n        \"\"\"\n        Validate and initialize toxicity processing configuration.\n        Args:\n            max_size (int): Maximum sentence size defined in the\n            configuration object.\n        Raises:\n            Exception: If the maximum sentence size exceeds the 5KB limit.\n        Note:\n            This function ensures that the NLTK punkt tokenizer is downloaded\n            if not already present.\n        Returns:\n            None\n        \"\"\"\n        if max_size > 1024 * 5:\n            raise Exception(\"The sentence length should not exceed 5KB.\")\n        try:\n            nltk = importlib.import_module(\"nltk\")\n            nltk.data.find(\"tokenizers/punkt\")\n            return nltk\n        except ImportError:\n            raise ModuleNotFoundError(\n                \"Could not import nltk python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/toxicity.html"}
{"id": "812d4341cc9b-1", "text": "raise ModuleNotFoundError(\n                \"Could not import nltk python package. \"\n                \"Please install it with `pip install nltk`.\"\n            )\n        except LookupError:\n            nltk.download(\"punkt\")\n    def _split_paragraph(\n        self, prompt_value: str, max_size: int = 1024 * 4\n    ) -> List[List[str]]:\n        \"\"\"\n        Split a paragraph into chunks of sentences, respecting the maximum size limit.\n        Args:\n            paragraph (str): The input paragraph to be split into chunks.\n            max_size (int, optional): The maximum size limit in bytes for\n            each chunk. Defaults to 1024.\n        Returns:\n            List[List[str]]: A list of chunks, where each chunk is a list\n            of sentences.\n        Note:\n            This function validates the maximum sentence size based on service\n            limits using the 'toxicity_init_validate' function. It uses the NLTK\n            sentence tokenizer to split the paragraph into sentences.\n        Example:\n            paragraph = \"This is a sample paragraph. It\n            contains multiple sentences. ...\"\n            chunks = split_paragraph(paragraph, max_size=2048)\n        \"\"\"\n        # validate max. sentence size based on Service limits\n        nltk = self._toxicity_init_validate(max_size)\n        sentences = nltk.sent_tokenize(prompt_value)\n        chunks = list()  # type: ignore\n        current_chunk = list()  # type: ignore\n        current_size = 0\n        for sentence in sentences:\n            sentence_size = len(sentence.encode(\"utf-8\"))\n            # If adding a new sentence exceeds max_size\n            # or current_chunk has 10 sentences, start a new chunk\n            if (current_size + sentence_size > max_size) or (len(current_chunk) >= 10):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/toxicity.html"}
{"id": "812d4341cc9b-2", "text": "if current_chunk:  # Avoid appending empty chunks\n                    chunks.append(current_chunk)\n                current_chunk = []\n                current_size = 0\n            current_chunk.append(sentence)\n            current_size += sentence_size\n        # Add any remaining sentences\n        if current_chunk:\n            chunks.append(current_chunk)\n        return chunks\n[docs]    def validate(self, prompt_value: str, config: Any = None) -> str:\n        \"\"\"\n        Check the toxicity of a given text prompt using AWS\n        Comprehend service and apply actions based on configuration.\n        Args:\n            prompt_value (str): The text content to be checked for toxicity.\n            config (Dict[str, Any]): Configuration for toxicity checks and actions.\n        Returns:\n            str: The original prompt_value if allowed or no toxicity found.\n        Raises:\n            ValueError: If the prompt contains toxic labels and cannot be\n            processed based on the configuration.\n        \"\"\"\n        chunks = self._split_paragraph(prompt_value=prompt_value)\n        for sentence_list in chunks:\n            segments = [{\"Text\": sentence} for sentence in sentence_list]\n            response = self.client.detect_toxic_content(\n                TextSegments=segments, LanguageCode=\"en\"\n            )\n            if self.callback and self.callback.toxicity_callback:\n                self.moderation_beacon[\"moderation_input\"] = segments  # type: ignore\n                self.moderation_beacon[\"moderation_output\"] = response\n            toxicity_found = False\n            threshold = config.get(\"threshold\")\n            toxicity_labels = config.get(\"labels\")\n            if not toxicity_labels:\n                for item in response[\"ResultList\"]:\n                    for label in item[\"Labels\"]:\n                        if label[\"Score\"] >= threshold:\n                            toxicity_found = True\n                            break\n            else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/toxicity.html"}
{"id": "812d4341cc9b-3", "text": "toxicity_found = True\n                            break\n            else:\n                for item in response[\"ResultList\"]:\n                    for label in item[\"Labels\"]:\n                        if (\n                            label[\"Name\"] in toxicity_labels\n                            and label[\"Score\"] >= threshold\n                        ):\n                            toxicity_found = True\n                            break\n            if self.callback and self.callback.toxicity_callback:\n                if toxicity_found:\n                    self.moderation_beacon[\"moderation_status\"] = \"LABELS_FOUND\"\n                asyncio.create_task(\n                    self.callback.on_after_toxicity(\n                        self.moderation_beacon, self.unique_id\n                    )\n                )\n            if toxicity_found:\n                raise ModerationToxicityError\n        return prompt_value", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/toxicity.html"}
{"id": "fd07c70e4608-0", "text": "Source code for langchain_experimental.comprehend_moderation.prompt_safety\nimport asyncio\nfrom typing import Any, Optional\nfrom langchain_experimental.comprehend_moderation.base_moderation_exceptions import (\n    ModerationPromptSafetyError,\n)\n[docs]class ComprehendPromptSafety:\n[docs]    def __init__(\n        self,\n        client: Any,\n        callback: Optional[Any] = None,\n        unique_id: Optional[str] = None,\n        chain_id: Optional[str] = None,\n    ) -> None:\n        self.client = client\n        self.moderation_beacon = {\n            \"moderation_chain_id\": chain_id,\n            \"moderation_type\": \"PromptSafety\",\n            \"moderation_status\": \"LABELS_NOT_FOUND\",\n        }\n        self.callback = callback\n        self.unique_id = unique_id\n    def _get_arn(self) -> str:\n        region_name = self.client.meta.region_name\n        service = \"comprehend\"\n        prompt_safety_endpoint = \"document-classifier-endpoint/prompt-safety\"\n        return f\"arn:aws:{service}:{region_name}:aws:{prompt_safety_endpoint}\"\n[docs]    def validate(self, prompt_value: str, config: Any = None) -> str:\n        \"\"\"\n        Check and validate the safety of the given prompt text.\n        Args:\n            prompt_value (str): The input text to be checked for unsafe text.\n            config (Dict[str, Any]): Configuration settings for prompt safety checks.\n        Raises:\n            ValueError: If unsafe prompt is found in the prompt text based\n            on the specified threshold.\n        Returns:\n            str: The input prompt_value.\n        Note:\n            This function checks the safety of the provided prompt text using", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/prompt_safety.html"}
{"id": "fd07c70e4608-1", "text": "Note:\n            This function checks the safety of the provided prompt text using\n            Comprehend's classify_document API and raises an error if unsafe\n            text is detected with a score above the specified threshold.\n        Example:\n            comprehend_client = boto3.client('comprehend')\n            prompt_text = \"Please tell me your credit card information.\"\n            config = {\"threshold\": 0.7}\n            checked_prompt = check_prompt_safety(comprehend_client, prompt_text, config)\n        \"\"\"\n        threshold = config.get(\"threshold\")\n        unsafe_prompt = False\n        endpoint_arn = self._get_arn()\n        response = self.client.classify_document(\n            Text=prompt_value, EndpointArn=endpoint_arn\n        )\n        if self.callback and self.callback.prompt_safety_callback:\n            self.moderation_beacon[\"moderation_input\"] = prompt_value\n            self.moderation_beacon[\"moderation_output\"] = response\n        for class_result in response[\"Classes\"]:\n            if (\n                class_result[\"Score\"] >= threshold\n                and class_result[\"Name\"] == \"UNSAFE_PROMPT\"\n            ):\n                unsafe_prompt = True\n                break\n        if self.callback and self.callback.intent_callback:\n            if unsafe_prompt:\n                self.moderation_beacon[\"moderation_status\"] = \"LABELS_FOUND\"\n            asyncio.create_task(\n                self.callback.on_after_intent(self.moderation_beacon, self.unique_id)\n            )\n        if unsafe_prompt:\n            raise ModerationPromptSafetyError\n        return prompt_value", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/prompt_safety.html"}
{"id": "4a4269009101-0", "text": "Source code for langchain_experimental.comprehend_moderation.pii\nimport asyncio\nfrom typing import Any, Dict, Optional\nfrom langchain_experimental.comprehend_moderation.base_moderation_exceptions import (\n    ModerationPiiError,\n)\n[docs]class ComprehendPII:\n[docs]    def __init__(\n        self,\n        client: Any,\n        callback: Optional[Any] = None,\n        unique_id: Optional[str] = None,\n        chain_id: Optional[str] = None,\n    ) -> None:\n        self.client = client\n        self.moderation_beacon = {\n            \"moderation_chain_id\": chain_id,\n            \"moderation_type\": \"PII\",\n            \"moderation_status\": \"LABELS_NOT_FOUND\",\n        }\n        self.callback = callback\n        self.unique_id = unique_id\n[docs]    def validate(self, prompt_value: str, config: Any = None) -> str:\n        redact = config.get(\"redact\")\n        return (\n            self._detect_pii(prompt_value=prompt_value, config=config)\n            if redact\n            else self._contains_pii(prompt_value=prompt_value, config=config)\n        )\n    def _contains_pii(self, prompt_value: str, config: Any = None) -> str:\n        \"\"\"\n        Checks for Personally Identifiable Information (PII) labels above a\n        specified threshold. Uses Amazon Comprehend Contains PII Entities API. See -\n        https://docs.aws.amazon.com/comprehend/latest/APIReference/API_ContainsPiiEntities.html\n        Args:\n            prompt_value (str): The input text to be checked for PII labels.\n            config (Dict[str, Any]): Configuration for PII check and actions.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/pii.html"}
{"id": "4a4269009101-1", "text": "Returns:\n            str: the original prompt\n        Note:\n            - The provided client should be initialized with valid AWS credentials.\n        \"\"\"\n        pii_identified = self.client.contains_pii_entities(\n            Text=prompt_value, LanguageCode=\"en\"\n        )\n        if self.callback and self.callback.pii_callback:\n            self.moderation_beacon[\"moderation_input\"] = prompt_value\n            self.moderation_beacon[\"moderation_output\"] = pii_identified\n        threshold = config.get(\"threshold\")\n        pii_labels = config.get(\"labels\")\n        pii_found = False\n        for entity in pii_identified[\"Labels\"]:\n            if (entity[\"Score\"] >= threshold and entity[\"Name\"] in pii_labels) or (\n                entity[\"Score\"] >= threshold and not pii_labels\n            ):\n                pii_found = True\n                break\n        if self.callback and self.callback.pii_callback:\n            if pii_found:\n                self.moderation_beacon[\"moderation_status\"] = \"LABELS_FOUND\"\n            asyncio.create_task(\n                self.callback.on_after_pii(self.moderation_beacon, self.unique_id)\n            )\n        if pii_found:\n            raise ModerationPiiError\n        return prompt_value\n    def _detect_pii(self, prompt_value: str, config: Optional[Dict[str, Any]]) -> str:\n        \"\"\"\n        Detects and handles Personally Identifiable Information (PII) entities in the\n        given prompt text using Amazon Comprehend's detect_pii_entities API. The\n        function provides options to redact or stop processing based on the identified\n        PII entities and a provided configuration. Uses Amazon Comprehend Detect PII\n        Entities API.\n        Args:\n            prompt_value (str): The input text to be checked for PII entities.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/pii.html"}
{"id": "4a4269009101-2", "text": "prompt_value (str): The input text to be checked for PII entities.\n            config (Dict[str, Any]): A configuration specifying how to handle\n                                     PII entities.\n        Returns:\n            str: The processed prompt text with redacted PII entities or raised\n                 exceptions.\n        Raises:\n            ValueError: If the prompt contains configured PII entities for\n                        stopping processing.\n        Note:\n            - If PII is not found in the prompt, the original prompt is returned.\n            - The client should be initialized with valid AWS credentials.\n        \"\"\"\n        pii_identified = self.client.detect_pii_entities(\n            Text=prompt_value, LanguageCode=\"en\"\n        )\n        if self.callback and self.callback.pii_callback:\n            self.moderation_beacon[\"moderation_input\"] = prompt_value\n            self.moderation_beacon[\"moderation_output\"] = pii_identified\n        if (pii_identified[\"Entities\"]) == []:\n            if self.callback and self.callback.pii_callback:\n                asyncio.create_task(\n                    self.callback.on_after_pii(self.moderation_beacon, self.unique_id)\n                )\n            return prompt_value\n        pii_found = False\n        if not config and pii_identified[\"Entities\"]:\n            for entity in pii_identified[\"Entities\"]:\n                if entity[\"Score\"] >= 0.5:\n                    pii_found = True\n                    break\n            if self.callback and self.callback.pii_callback:\n                if pii_found:\n                    self.moderation_beacon[\"moderation_status\"] = \"LABELS_FOUND\"\n                asyncio.create_task(\n                    self.callback.on_after_pii(self.moderation_beacon, self.unique_id)\n                )\n            if pii_found:\n                raise ModerationPiiError\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/pii.html"}
{"id": "4a4269009101-3", "text": "if pii_found:\n                raise ModerationPiiError\n        else:\n            threshold = config.get(\"threshold\")  # type: ignore\n            pii_labels = config.get(\"labels\")  # type: ignore\n            mask_marker = config.get(\"mask_character\")  # type: ignore\n            pii_found = False\n            for entity in pii_identified[\"Entities\"]:\n                if (\n                    pii_labels\n                    and entity[\"Type\"] in pii_labels\n                    and entity[\"Score\"] >= threshold\n                ) or (not pii_labels and entity[\"Score\"] >= threshold):\n                    pii_found = True\n                    char_offset_begin = entity[\"BeginOffset\"]\n                    char_offset_end = entity[\"EndOffset\"]\n                    mask_length = char_offset_end - char_offset_begin + 1\n                    masked_part = mask_marker * mask_length\n                    prompt_value = (\n                        prompt_value[:char_offset_begin]\n                        + masked_part\n                        + prompt_value[char_offset_end + 1 :]\n                    )\n            if self.callback and self.callback.pii_callback:\n                if pii_found:\n                    self.moderation_beacon[\"moderation_status\"] = \"LABELS_FOUND\"\n                asyncio.create_task(\n                    self.callback.on_after_pii(self.moderation_beacon, self.unique_id)\n                )\n        return prompt_value", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/pii.html"}
{"id": "575654d54896-0", "text": "Source code for langchain_experimental.comprehend_moderation.base_moderation_callbacks\nfrom typing import Any, Callable, Dict\n[docs]class BaseModerationCallbackHandler:\n[docs]    def __init__(self) -> None:\n        if (\n            self._is_method_unchanged(\n                BaseModerationCallbackHandler.on_after_pii, self.on_after_pii\n            )\n            and self._is_method_unchanged(\n                BaseModerationCallbackHandler.on_after_toxicity, self.on_after_toxicity\n            )\n            and self._is_method_unchanged(\n                BaseModerationCallbackHandler.on_after_prompt_safety,\n                self.on_after_prompt_safety,\n            )\n        ):\n            raise NotImplementedError(\n                \"Subclasses must override at least one of on_after_pii(), \"\n                \"on_after_toxicity(), or on_after_prompt_safety() functions.\"\n            )\n    def _is_method_unchanged(\n        self, base_method: Callable, derived_method: Callable\n    ) -> bool:\n        return base_method.__qualname__ == derived_method.__qualname__\n[docs]    async def on_after_pii(\n        self, moderation_beacon: Dict[str, Any], unique_id: str, **kwargs: Any\n    ) -> None:\n        \"\"\"Run after PII validation is complete.\"\"\"\n        pass\n[docs]    async def on_after_toxicity(\n        self, moderation_beacon: Dict[str, Any], unique_id: str, **kwargs: Any\n    ) -> None:\n        \"\"\"Run after Toxicity validation is complete.\"\"\"\n        pass\n[docs]    async def on_after_prompt_safety(\n        self, moderation_beacon: Dict[str, Any], unique_id: str, **kwargs: Any\n    ) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_callbacks.html"}
{"id": "575654d54896-1", "text": ") -> None:\n        \"\"\"Run after Prompt Safety validation is complete.\"\"\"\n        pass\n    @property\n    def pii_callback(self) -> bool:\n        return (\n            self.on_after_pii.__func__  # type: ignore\n            is not BaseModerationCallbackHandler.on_after_pii\n        )\n    @property\n    def toxicity_callback(self) -> bool:\n        return (\n            self.on_after_toxicity.__func__  # type: ignore\n            is not BaseModerationCallbackHandler.on_after_toxicity\n        )\n    @property\n    def prompt_safety_callback(self) -> bool:\n        return (\n            self.on_after_prompt_safety.__func__  # type: ignore\n            is not BaseModerationCallbackHandler.on_after_prompt_safety\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_callbacks.html"}
{"id": "ec8a65d88df2-0", "text": "Source code for langchain_experimental.comprehend_moderation.base_moderation\nimport uuid\nfrom typing import Any, Callable, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.prompts.base import StringPromptValue\nfrom langchain.prompts.chat import ChatPromptValue\nfrom langchain.schema import AIMessage, HumanMessage\nfrom langchain_experimental.comprehend_moderation.pii import ComprehendPII\nfrom langchain_experimental.comprehend_moderation.prompt_safety import (\n    ComprehendPromptSafety,\n)\nfrom langchain_experimental.comprehend_moderation.toxicity import ComprehendToxicity\n[docs]class BaseModeration:\n[docs]    def __init__(\n        self,\n        client: Any,\n        config: Optional[Any] = None,\n        moderation_callback: Optional[Any] = None,\n        unique_id: Optional[str] = None,\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ):\n        self.client = client\n        self.config = config\n        self.moderation_callback = moderation_callback\n        self.unique_id = unique_id\n        self.chat_message_index = 0\n        self.run_manager = run_manager\n        self.chain_id = str(uuid.uuid4())\n    def _convert_prompt_to_text(self, prompt: Any) -> str:\n        input_text = str()\n        if isinstance(prompt, StringPromptValue):\n            input_text = prompt.text\n        elif isinstance(prompt, str):\n            input_text = prompt\n        elif isinstance(prompt, ChatPromptValue):\n            \"\"\"\n            We will just check the last message in the message Chain of a\n            ChatPromptTemplate. The typical chronology is\n            SystemMessage > HumanMessage > AIMessage and so on. However assuming", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html"}
{"id": "ec8a65d88df2-1", "text": "SystemMessage > HumanMessage > AIMessage and so on. However assuming\n            that with every chat the chain is invoked we will only check the last\n            message. This is assuming that all previous messages have been checked\n            already. Only HumanMessage and AIMessage will be checked. We can perhaps\n            loop through and take advantage of the additional_kwargs property in the\n            HumanMessage and AIMessage schema to mark messages that have been moderated.\n            However that means that this class could generate multiple text chunks\n            and moderate() logics would need to be updated. This also means some\n            complexity in re-constructing the prompt while keeping the messages in\n            sequence.\n            \"\"\"\n            message = prompt.messages[-1]\n            self.chat_message_index = len(prompt.messages) - 1\n            if isinstance(message, HumanMessage):\n                input_text = message.content\n            if isinstance(message, AIMessage):\n                input_text = message.content\n        else:\n            raise ValueError(\n                f\"Invalid input type {type(input_text)}. \"\n                \"Must be a PromptValue, str, or list of BaseMessages.\"\n            )\n        return input_text\n    def _convert_text_to_prompt(self, prompt: Any, text: str) -> Any:\n        if isinstance(prompt, StringPromptValue):\n            return StringPromptValue(text=text)\n        elif isinstance(prompt, str):\n            return text\n        elif isinstance(prompt, ChatPromptValue):\n            # Copy the messages because we may need to mutate them.\n            # We don't want to mutate data we don't own.\n            messages = list(prompt.messages)\n            message = messages[self.chat_message_index]\n            if isinstance(message, HumanMessage):\n                messages[self.chat_message_index] = HumanMessage(\n                    content=text,\n                    example=message.example,\n                    additional_kwargs=message.additional_kwargs,\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html"}
{"id": "ec8a65d88df2-2", "text": "example=message.example,\n                    additional_kwargs=message.additional_kwargs,\n                )\n            if isinstance(message, AIMessage):\n                messages[self.chat_message_index] = AIMessage(\n                    content=text,\n                    example=message.example,\n                    additional_kwargs=message.additional_kwargs,\n                )\n            return ChatPromptValue(messages=messages)\n        else:\n            raise ValueError(\n                f\"Invalid input type {type(input)}. \"\n                \"Must be a PromptValue, str, or list of BaseMessages.\"\n            )\n    def _moderation_class(self, moderation_class: Any) -> Callable:\n        return moderation_class(\n            client=self.client,\n            callback=self.moderation_callback,\n            unique_id=self.unique_id,\n            chain_id=self.chain_id,\n        ).validate\n    def _log_message_for_verbose(self, message: str) -> None:\n        if self.run_manager:\n            self.run_manager.on_text(message)\n[docs]    def moderate(self, prompt: Any) -> str:\n        from langchain_experimental.comprehend_moderation.base_moderation_config import (  # noqa: E501\n            ModerationPiiConfig,\n            ModerationPromptSafetyConfig,\n            ModerationToxicityConfig,\n        )\n        from langchain_experimental.comprehend_moderation.base_moderation_exceptions import (  # noqa: E501\n            ModerationPiiError,\n            ModerationPromptSafetyError,\n            ModerationToxicityError,\n        )\n        try:\n            # convert prompt to text\n            input_text = self._convert_prompt_to_text(prompt=prompt)\n            output_text = str()\n            # perform moderation\n            filter_functions = {\n                \"pii\": ComprehendPII,\n                \"toxicity\": ComprehendToxicity,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html"}
{"id": "ec8a65d88df2-3", "text": "\"toxicity\": ComprehendToxicity,\n                \"prompt_safety\": ComprehendPromptSafety,\n            }\n            filters = self.config.filters  # type: ignore\n            for _filter in filters:\n                filter_name = (\n                    \"pii\"\n                    if isinstance(_filter, ModerationPiiConfig)\n                    else (\n                        \"toxicity\"\n                        if isinstance(_filter, ModerationToxicityConfig)\n                        else (\n                            \"prompt_safety\"\n                            if isinstance(_filter, ModerationPromptSafetyConfig)\n                            else None\n                        )\n                    )\n                )\n                if filter_name in filter_functions:\n                    self._log_message_for_verbose(\n                        f\"Running {filter_name} Validation...\\n\"\n                    )\n                    validation_fn = self._moderation_class(\n                        moderation_class=filter_functions[filter_name]\n                    )\n                    input_text = input_text if not output_text else output_text\n                    output_text = validation_fn(\n                        prompt_value=input_text,\n                        config=_filter.dict(),\n                    )\n            # convert text to prompt and return\n            return self._convert_text_to_prompt(prompt=prompt, text=output_text)\n        except ModerationPiiError as e:\n            self._log_message_for_verbose(f\"Found PII content..stopping..\\n{str(e)}\\n\")\n            raise e\n        except ModerationToxicityError as e:\n            self._log_message_for_verbose(\n                f\"Found Toxic content..stopping..\\n{str(e)}\\n\"\n            )\n            raise e\n        except ModerationPromptSafetyError as e:\n            self._log_message_for_verbose(\n                f\"Found Harmful intention..stopping..\\n{str(e)}\\n\"\n            )\n            raise e", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html"}
{"id": "ec8a65d88df2-4", "text": ")\n            raise e\n        except Exception as e:\n            raise e", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html"}
{"id": "804156d74eea-0", "text": "Source code for langchain_experimental.comprehend_moderation.amazon_comprehend_moderation\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain_experimental.comprehend_moderation.base_moderation import BaseModeration\nfrom langchain_experimental.comprehend_moderation.base_moderation_callbacks import (\n    BaseModerationCallbackHandler,\n)\nfrom langchain_experimental.comprehend_moderation.base_moderation_config import (\n    BaseModerationConfig,\n)\nfrom langchain_experimental.pydantic_v1 import root_validator\n[docs]class AmazonComprehendModerationChain(Chain):\n    \"\"\"A subclass of Chain, designed to apply moderation to LLMs.\"\"\"\n    output_key: str = \"output\"  #: :meta private:\n    \"\"\"Key used to fetch/store the output in data containers. Defaults to `output`\"\"\"\n    input_key: str = \"input\"  #: :meta private:\n    \"\"\"Key used to fetch/store the input in data containers. Defaults to `input`\"\"\"\n    moderation_config: BaseModerationConfig = BaseModerationConfig()\n    \"\"\"\n    Configuration settings for moderation, \n    defaults to BaseModerationConfig with default values\n    \"\"\"\n    client: Optional[Any] = None\n    \"\"\"boto3 client object for connection to Amazon Comprehend\"\"\"\n    region_name: Optional[str] = None\n    \"\"\"The aws region e.g., `us-west-2`. Fallsback to AWS_DEFAULT_REGION env variable\n    or region specified in ~/.aws/config in case it is not provided here.\n    \"\"\"\n    credentials_profile_name: Optional[str] = None\n    \"\"\"The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/amazon_comprehend_moderation.html"}
{"id": "804156d74eea-1", "text": "has either access keys or role information specified.\n    If not specified, the default credential profile or, if on an EC2 instance,\n    credentials from IMDS will be used.\n    See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\n    \"\"\"\n    moderation_callback: Optional[BaseModerationCallbackHandler] = None\n    \"\"\"Callback handler for moderation, this is different \n    from regular callbacks which can be used in addition to this.\"\"\"\n    unique_id: Optional[str] = None\n    \"\"\"A unique id that can be used to identify or group a user or session\"\"\"\n    @root_validator(pre=True)\n    def create_client(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"\n        Creates an Amazon Comprehend client\n        Args:\n            values (Dict[str, Any]): A dictionary containing configuration values.\n        Returns:\n            Dict[str, Any]: A dictionary with the updated configuration values,\n                            including the Amazon Comprehend client.\n        Raises:\n            ModuleNotFoundError: If the 'boto3' package is not installed.\n            ValueError: If there is an issue importing 'boto3' or loading\n                        AWS credentials.\n        Example:\n        .. code-block:: python\n            config = {\n                \"credentials_profile_name\": \"my-profile\",\n                \"region_name\": \"us-west-2\"\n            }\n            updated_config = create_client(config)\n            comprehend_client = updated_config[\"client\"]\n        \"\"\"\n        if values.get(\"client\") is not None:\n            return values\n        try:\n            import boto3\n            if values.get(\"credentials_profile_name\"):\n                session = boto3.Session(profile_name=values[\"credentials_profile_name\"])\n            else:\n                # use default credentials\n                session = boto3.Session()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/amazon_comprehend_moderation.html"}
{"id": "804156d74eea-2", "text": "else:\n                # use default credentials\n                session = boto3.Session()\n            client_params = {}\n            if values.get(\"region_name\"):\n                client_params[\"region_name\"] = values[\"region_name\"]\n            values[\"client\"] = session.client(\"comprehend\", **client_params)\n            return values\n        except ImportError:\n            raise ModuleNotFoundError(\n                \"Could not import boto3 python package. \"\n                \"Please install it with `pip install boto3`.\"\n            )\n        except Exception as e:\n            raise ValueError(\n                \"Could not load credentials to authenticate with AWS client. \"\n                \"Please check that credentials in the specified \"\n                \"profile name are valid.\"\n            ) from e\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"\n        Returns a list of output keys.\n        This method defines the output keys that will be used to access the output\n        values produced by the chain or function. It ensures that the specified keys\n        are available to access the outputs.\n        Returns:\n            List[str]: A list of output keys.\n        Note:\n            This method is considered private and may not be intended for direct\n            external use.\n        \"\"\"\n        return [self.output_key]\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"\n        Returns a list of input keys expected by the prompt.\n        This method defines the input keys that the prompt expects in order to perform\n        its processing. It ensures that the specified keys are available for providing\n        input to the prompt.\n        Returns:\n            List[str]: A list of input keys.\n        Note:\n            This method is considered private and may not be intended for direct\n            external use.\n        \"\"\"\n        return [self.input_key]\n    def _call(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/amazon_comprehend_moderation.html"}
{"id": "804156d74eea-3", "text": "\"\"\"\n        return [self.input_key]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        \"\"\"\n        Executes the moderation process on the input text and returns the processed\n        output.\n        This internal method performs the moderation process on the input text. It\n        converts the input prompt value to plain text, applies the specified filters,\n        and then converts the filtered output back to a suitable prompt value object.\n        Additionally, it provides the option to log information about the run using\n        the provided `run_manager`.\n        Args:\n            inputs: A dictionary containing input values\n            run_manager: A run manager to handle run-related events. Default is None\n        Returns:\n            Dict[str, str]: A dictionary containing the processed output of the\n                            moderation process.\n        Raises:\n            ValueError: If there is an error during the moderation process\n        \"\"\"\n        if run_manager:\n            run_manager.on_text(\"Running AmazonComprehendModerationChain...\\n\")\n        moderation = BaseModeration(\n            client=self.client,\n            config=self.moderation_config,\n            moderation_callback=self.moderation_callback,\n            unique_id=self.unique_id,\n            run_manager=run_manager,\n        )\n        response = moderation.moderate(prompt=inputs[self.input_keys[0]])\n        return {self.output_key: response}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/amazon_comprehend_moderation.html"}
{"id": "721a00314321-0", "text": "Source code for langchain_experimental.comprehend_moderation.base_moderation_exceptions\n[docs]class ModerationPiiError(Exception):\n    \"\"\"Exception raised if PII entities are detected.\n    Attributes:\n        message -- explanation of the error\n    \"\"\"\n    def __init__(\n        self, message: str = \"The prompt contains PII entities and cannot be processed\"\n    ):\n        self.message = message\n        super().__init__(self.message)\n[docs]class ModerationToxicityError(Exception):\n    \"\"\"Exception raised if Toxic entities are detected.\n    Attributes:\n        message -- explanation of the error\n    \"\"\"\n    def __init__(\n        self, message: str = \"The prompt contains toxic content and cannot be processed\"\n    ):\n        self.message = message\n        super().__init__(self.message)\n[docs]class ModerationPromptSafetyError(Exception):\n    \"\"\"Exception raised if Intention entities are detected.\n    Attributes:\n        message -- explanation of the error\n    \"\"\"\n    def __init__(\n        self,\n        message: str = (\"The prompt is unsafe and cannot be processed\"),\n    ):\n        self.message = message\n        super().__init__(self.message)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_exceptions.html"}
{"id": "642b24749d67-0", "text": "Source code for langchain_experimental.smart_llm.base\n\"\"\"Chain for applying self-critique using the SmartGPT workflow.\"\"\"\nfrom typing import Any, Dict, List, Optional, Tuple, Type\nfrom langchain.base_language import BaseLanguageModel\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.input import get_colored_text\nfrom langchain.prompts.base import BasePromptTemplate\nfrom langchain.prompts.chat import (\n    AIMessagePromptTemplate,\n    BaseMessagePromptTemplate,\n    ChatPromptTemplate,\n    HumanMessagePromptTemplate,\n)\nfrom langchain.schema import LLMResult, PromptValue\nfrom langchain_experimental.pydantic_v1 import Extra, root_validator\n[docs]class SmartLLMChain(Chain):\n    \"\"\"\n    Generalized implementation of SmartGPT (origin: https://youtu.be/wVzuvf9D9BU)\n    A SmartLLMChain is an LLMChain that instead of simply passing the prompt to the LLM\n    performs these 3 steps:\n    1. Ideate: Pass the user prompt to an ideation LLM n_ideas times,\n       each result is an \"idea\"\n    2. Critique: Pass the ideas to a critique LLM which looks for flaws in the ideas\n       & picks the best one\n    3. Resolve: Pass the critique to a resolver LLM which improves upon the best idea\n       & outputs only the (improved version of) the best output\n    In total, SmartLLMChain pass will use n_ideas+2 LLM calls\n    Note that SmartLLMChain will only improve results (compared to a basic LLMChain),\n    when the underlying models have the capability for reflection, which smaller models\n    often don't.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html"}
{"id": "642b24749d67-1", "text": "often don't.\n    Finally, a SmartLLMChain assumes that each underlying LLM outputs exactly 1 result.\n    \"\"\"\n[docs]    class SmartLLMChainHistory:\n        question: str = \"\"\n        ideas: List[str] = []\n        critique: str = \"\"\n        @property\n        def n_ideas(self) -> int:\n            return len(self.ideas)\n[docs]        def ideation_prompt_inputs(self) -> Dict[str, Any]:\n            return {\"question\": self.question}\n[docs]        def critique_prompt_inputs(self) -> Dict[str, Any]:\n            return {\n                \"question\": self.question,\n                **{f\"idea_{i+1}\": idea for i, idea in enumerate(self.ideas)},\n            }\n[docs]        def resolve_prompt_inputs(self) -> Dict[str, Any]:\n            return {\n                \"question\": self.question,\n                **{f\"idea_{i+1}\": idea for i, idea in enumerate(self.ideas)},\n                \"critique\": self.critique,\n            }\n    prompt: BasePromptTemplate\n    \"\"\"Prompt object to use.\"\"\"\n    ideation_llm: Optional[BaseLanguageModel] = None\n    \"\"\"LLM to use in ideation step. If None given, 'llm' will be used.\"\"\"\n    critique_llm: Optional[BaseLanguageModel] = None\n    \"\"\"LLM to use in critique step. If None given, 'llm' will be used.\"\"\"\n    resolver_llm: Optional[BaseLanguageModel] = None\n    \"\"\"LLM to use in resolve step. If None given, 'llm' will be used.\"\"\"\n    llm: Optional[BaseLanguageModel] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html"}
{"id": "642b24749d67-2", "text": "llm: Optional[BaseLanguageModel] = None\n    \"\"\"LLM to use for each steps, if no specific llm for that step is given. \"\"\"\n    n_ideas: int = 3\n    \"\"\"Number of ideas to generate in idea step\"\"\"\n    return_intermediate_steps: bool = False\n    \"\"\"Whether to return ideas and critique, in addition to resolution.\"\"\"\n    history: SmartLLMChainHistory = SmartLLMChainHistory()\n    class Config:\n        extra = Extra.forbid\n    # TODO: move away from `root_validator` since it is deprecated in pydantic v2\n    #       and causes mypy type-checking failures (hence the `type: ignore`)\n    @root_validator  # type: ignore[call-overload]\n    @classmethod\n    def validate_inputs(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Ensure we have an LLM for each step.\"\"\"\n        llm = values.get(\"llm\")\n        ideation_llm = values.get(\"ideation_llm\")\n        critique_llm = values.get(\"critique_llm\")\n        resolver_llm = values.get(\"resolver_llm\")\n        if not llm and not ideation_llm:\n            raise ValueError(\n                \"Either ideation_llm or llm needs to be given. Pass llm, \"\n                \"if you want to use the same llm for all steps, or pass \"\n                \"ideation_llm, critique_llm and resolver_llm if you want \"\n                \"to use different llms for each step.\"\n            )\n        if not llm and not critique_llm:\n            raise ValueError(\n                \"Either critique_llm or llm needs to be given. Pass llm, \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html"}
{"id": "642b24749d67-3", "text": "\"Either critique_llm or llm needs to be given. Pass llm, \"\n                \"if you want to use the same llm for all steps, or pass \"\n                \"ideation_llm, critique_llm and resolver_llm if you want \"\n                \"to use different llms for each step.\"\n            )\n        if not llm and not resolver_llm:\n            raise ValueError(\n                \"Either resolve_llm or llm needs to be given. Pass llm, \"\n                \"if you want to use the same llm for all steps, or pass \"\n                \"ideation_llm, critique_llm and resolver_llm if you want \"\n                \"to use different llms for each step.\"\n            )\n        if llm and ideation_llm and critique_llm and resolver_llm:\n            raise ValueError(\n                \"LLMs are given for each step (ideation_llm, critique_llm,\"\n                \" resolver_llm), but backup LLM (llm) is also given, which\"\n                \" would not be used.\"\n            )\n        return values\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Defines the input keys.\"\"\"\n        return self.prompt.input_variables\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Defines the output keys.\"\"\"\n        if self.return_intermediate_steps:\n            return [\"ideas\", \"critique\", \"resolution\"]\n        return [\"resolution\"]\n[docs]    def prep_prompts(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Tuple[PromptValue, Optional[List[str]]]:\n        \"\"\"Prepare prompts from inputs.\"\"\"\n        stop = None\n        if \"stop\" in inputs:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html"}
{"id": "642b24749d67-4", "text": "stop = None\n        if \"stop\" in inputs:\n            stop = inputs[\"stop\"]\n        selected_inputs = {k: inputs[k] for k in self.prompt.input_variables}\n        prompt = self.prompt.format_prompt(**selected_inputs)\n        _colored_text = get_colored_text(prompt.to_string(), \"green\")\n        _text = \"Prompt after formatting:\\n\" + _colored_text\n        if run_manager:\n            run_manager.on_text(_text, end=\"\\n\", verbose=self.verbose)\n        if \"stop\" in inputs and inputs[\"stop\"] != stop:\n            raise ValueError(\n                \"If `stop` is present in any inputs, should be present in all.\"\n            )\n        return prompt, stop\n    def _call(\n        self,\n        input_list: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        prompt, stop = self.prep_prompts(input_list, run_manager=run_manager)\n        self.history.question = prompt.to_string()\n        ideas = self._ideate(stop, run_manager)\n        self.history.ideas = ideas\n        critique = self._critique(stop, run_manager)\n        self.history.critique = critique\n        resolution = self._resolve(stop, run_manager)\n        if self.return_intermediate_steps:\n            return {\"ideas\": ideas, \"critique\": critique, \"resolution\": resolution}\n        return {\"resolution\": resolution}\n    def _get_text_from_llm_result(self, result: LLMResult, step: str) -> str:\n        \"\"\"Between steps, only the LLM result text is passed, not the LLMResult object.\n        This function extracts the text from an LLMResult.\"\"\"\n        if len(result.generations) != 1:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html"}
{"id": "642b24749d67-5", "text": "if len(result.generations) != 1:\n            raise ValueError(\n                f\"In SmartLLM the LLM result in step {step} is not \"\n                \"exactly 1 element. This should never happen\"\n            )\n        if len(result.generations[0]) != 1:\n            raise ValueError(\n                f\"In SmartLLM the LLM in step {step} returned more than \"\n                \"1 output. SmartLLM only works with LLMs returning \"\n                \"exactly 1 output.\"\n            )\n        return result.generations[0][0].text\n[docs]    def get_prompt_strings(\n        self, stage: str\n    ) -> List[Tuple[Type[BaseMessagePromptTemplate], str]]:\n        role_strings: List[Tuple[Type[BaseMessagePromptTemplate], str]] = []\n        role_strings.append(\n            (\n                HumanMessagePromptTemplate,\n                \"Question: {question}\\nAnswer: Let's work this out in a step by \"\n                \"step way to be sure we have the right answer:\",\n            )\n        )\n        if stage == \"ideation\":\n            return role_strings\n        role_strings.extend(\n            [\n                *[\n                    (\n                        AIMessagePromptTemplate,\n                        \"Idea \" + str(i + 1) + \": {idea_\" + str(i + 1) + \"}\",\n                    )\n                    for i in range(self.n_ideas)\n                ],\n                (\n                    HumanMessagePromptTemplate,\n                    \"You are a researcher tasked with investigating the \"\n                    f\"{self.n_ideas} response options provided. List the flaws and \"\n                    \"faulty logic of each answer options. Let'w work this out in a step\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html"}
{"id": "642b24749d67-6", "text": "\" by step way to be sure we have all the errors:\",\n                ),\n            ]\n        )\n        if stage == \"critique\":\n            return role_strings\n        role_strings.extend(\n            [\n                (AIMessagePromptTemplate, \"Critique: {critique}\"),\n                (\n                    HumanMessagePromptTemplate,\n                    \"You are a resolved tasked with 1) finding which of \"\n                    f\"the {self.n_ideas} answer options the researcher thought was  \"\n                    \"best,2) improving that answer and 3) printing the answer in full. \"\n                    \"Don't output anything for step 1 or 2, only the full answer in 3. \"\n                    \"Let's work this out in a step by step way to be sure we have \"\n                    \"the right answer:\",\n                ),\n            ]\n        )\n        if stage == \"resolve\":\n            return role_strings\n        raise ValueError(\n            \"stage should be either 'ideation', 'critique' or 'resolve',\"\n            f\" but it is '{stage}'. This should never happen.\"\n        )\n[docs]    def ideation_prompt(self) -> ChatPromptTemplate:\n        return ChatPromptTemplate.from_strings(self.get_prompt_strings(\"ideation\"))\n[docs]    def critique_prompt(self) -> ChatPromptTemplate:\n        return ChatPromptTemplate.from_strings(self.get_prompt_strings(\"critique\"))\n[docs]    def resolve_prompt(self) -> ChatPromptTemplate:\n        return ChatPromptTemplate.from_strings(self.get_prompt_strings(\"resolve\"))\n    def _ideate(\n        self,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> List[str]:\n        \"\"\"Generate n_ideas ideas as response to user prompt.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html"}
{"id": "642b24749d67-7", "text": "\"\"\"Generate n_ideas ideas as response to user prompt.\"\"\"\n        llm = self.ideation_llm if self.ideation_llm else self.llm\n        prompt = self.ideation_prompt().format_prompt(\n            **self.history.ideation_prompt_inputs()\n        )\n        callbacks = run_manager.get_child() if run_manager else None\n        if llm:\n            ideas = [\n                self._get_text_from_llm_result(\n                    llm.generate_prompt([prompt], stop, callbacks),\n                    step=\"ideate\",\n                )\n                for _ in range(self.n_ideas)\n            ]\n            for i, idea in enumerate(ideas):\n                _colored_text = get_colored_text(idea, \"blue\")\n                _text = f\"Idea {i+1}:\\n\" + _colored_text\n                if run_manager:\n                    run_manager.on_text(_text, end=\"\\n\", verbose=self.verbose)\n            return ideas\n        else:\n            raise ValueError(\"llm is none, which should never happen\")\n    def _critique(\n        self,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> str:\n        \"\"\"Critique each of the ideas from ideation stage & select best one.\"\"\"\n        llm = self.critique_llm if self.critique_llm else self.llm\n        prompt = self.critique_prompt().format_prompt(\n            **self.history.critique_prompt_inputs()\n        )\n        callbacks = run_manager.handlers if run_manager else None\n        if llm:\n            critique = self._get_text_from_llm_result(\n                llm.generate_prompt([prompt], stop, callbacks), step=\"critique\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html"}
{"id": "642b24749d67-8", "text": ")\n            _colored_text = get_colored_text(critique, \"yellow\")\n            _text = \"Critique:\\n\" + _colored_text\n            if run_manager:\n                run_manager.on_text(_text, end=\"\\n\", verbose=self.verbose)\n            return critique\n        else:\n            raise ValueError(\"llm is none, which should never happen\")\n    def _resolve(\n        self,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> str:\n        \"\"\"Improve upon the best idea as chosen in critique step & return it.\"\"\"\n        llm = self.resolver_llm if self.resolver_llm else self.llm\n        prompt = self.resolve_prompt().format_prompt(\n            **self.history.resolve_prompt_inputs()\n        )\n        callbacks = run_manager.handlers if run_manager else None\n        if llm:\n            resolution = self._get_text_from_llm_result(\n                llm.generate_prompt([prompt], stop, callbacks), step=\"resolve\"\n            )\n            _colored_text = get_colored_text(resolution, \"green\")\n            _text = \"Resolution:\\n\" + _colored_text\n            if run_manager:\n                run_manager.on_text(_text, end=\"\\n\", verbose=self.verbose)\n            return resolution\n        else:\n            raise ValueError(\"llm is none, which should never happen\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html"}
{"id": "10cde80c6649-0", "text": "Source code for langchain_experimental.chat_models.llm_wrapper\n\"\"\"Generic Wrapper for chat LLMs, with sample implementations\nfor Llama-2-chat, Llama-2-instruct and Vicuna models.\n\"\"\"\nfrom typing import Any, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.llms.base import LLM\nfrom langchain.schema import (\n    AIMessage,\n    BaseMessage,\n    ChatGeneration,\n    ChatResult,\n    HumanMessage,\n    LLMResult,\n    SystemMessage,\n)\nDEFAULT_SYSTEM_PROMPT = \"\"\"You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\"\"\"  # noqa: E501\n[docs]class ChatWrapper(BaseChatModel):\n    llm: LLM\n    sys_beg: str\n    sys_end: str\n    ai_n_beg: str\n    ai_n_end: str\n    usr_n_beg: str\n    usr_n_end: str\n    usr_0_beg: Optional[str] = None\n    usr_0_end: Optional[str] = None\n    system_message: SystemMessage = SystemMessage(content=DEFAULT_SYSTEM_PROMPT)\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/chat_models/llm_wrapper.html"}
{"id": "10cde80c6649-1", "text": "messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        llm_input = self._to_chat_prompt(messages)\n        llm_result = self.llm._generate(\n            prompts=[llm_input], stop=stop, run_manager=run_manager, **kwargs\n        )\n        return self._to_chat_result(llm_result)\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        llm_input = self._to_chat_prompt(messages)\n        llm_result = await self.llm._agenerate(\n            prompts=[llm_input], stop=stop, run_manager=run_manager, **kwargs\n        )\n        return self._to_chat_result(llm_result)\n    def _to_chat_prompt(\n        self,\n        messages: List[BaseMessage],\n    ) -> str:\n        \"\"\"Convert a list of messages into a prompt format expected by wrapped LLM.\"\"\"\n        if not messages:\n            raise ValueError(\"at least one HumanMessage must be provided\")\n        if not isinstance(messages[0], SystemMessage):\n            messages = [self.system_message] + messages\n        if not isinstance(messages[1], HumanMessage):\n            raise ValueError(\n                \"messages list must start with a SystemMessage or UserMessage\"\n            )\n        if not isinstance(messages[-1], HumanMessage):\n            raise ValueError(\"last message must be a HumanMessage\")\n        prompt_parts = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/chat_models/llm_wrapper.html"}
{"id": "10cde80c6649-2", "text": "raise ValueError(\"last message must be a HumanMessage\")\n        prompt_parts = []\n        if self.usr_0_beg is None:\n            self.usr_0_beg = self.usr_n_beg\n        if self.usr_0_end is None:\n            self.usr_0_end = self.usr_n_end\n        prompt_parts.append(self.sys_beg + messages[0].content + self.sys_end)\n        prompt_parts.append(self.usr_0_beg + messages[1].content + self.usr_0_end)\n        for ai_message, human_message in zip(messages[2::2], messages[3::2]):\n            if not isinstance(ai_message, AIMessage) or not isinstance(\n                human_message, HumanMessage\n            ):\n                raise ValueError(\n                    \"messages must be alternating human- and ai-messages, \"\n                    \"optionally prepended by a system message\"\n                )\n            prompt_parts.append(self.ai_n_beg + ai_message.content + self.ai_n_end)\n            prompt_parts.append(self.usr_n_beg + human_message.content + self.usr_n_end)\n        return \"\".join(prompt_parts)\n    @staticmethod\n    def _to_chat_result(llm_result: LLMResult) -> ChatResult:\n        chat_generations = []\n        for g in llm_result.generations[0]:\n            chat_generation = ChatGeneration(\n                message=AIMessage(content=g.text), generation_info=g.generation_info\n            )\n            chat_generations.append(chat_generation)\n        return ChatResult(\n            generations=chat_generations, llm_output=llm_result.llm_output\n        )\n[docs]class Llama2Chat(ChatWrapper):\n    @property\n    def _llm_type(self) -> str:\n        return \"llama-2-chat\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/chat_models/llm_wrapper.html"}
{"id": "10cde80c6649-3", "text": "return \"llama-2-chat\"\n    sys_beg: str = \"<s>[INST] <<SYS>>\\n\"\n    sys_end: str = \"\\n<</SYS>>\\n\\n\"\n    ai_n_beg: str = \" \"\n    ai_n_end: str = \" </s>\"\n    usr_n_beg: str = \"<s>[INST] \"\n    usr_n_end: str = \" [/INST]\"\n    usr_0_beg: str = \"\"\n    usr_0_end: str = \" [/INST]\"\n[docs]class Orca(ChatWrapper):\n    @property\n    def _llm_type(self) -> str:\n        return \"orca-style\"\n    sys_beg: str = \"### System:\\n\"\n    sys_end: str = \"\\n\\n\"\n    ai_n_beg: str = \"### Assistant:\\n\"\n    ai_n_end: str = \"\\n\\n\"\n    usr_n_beg: str = \"### User:\\n\"\n    usr_n_end: str = \"\\n\\n\"\n[docs]class Vicuna(ChatWrapper):\n    @property\n    def _llm_type(self) -> str:\n        return \"vicuna-style\"\n    sys_beg: str = \"\"\n    sys_end: str = \" \"\n    ai_n_beg: str = \"ASSISTANT: \"\n    ai_n_end: str = \" </s>\"\n    usr_n_beg: str = \"USER: \"\n    usr_n_end: str = \" \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/chat_models/llm_wrapper.html"}
{"id": "9ba6cce9ece6-0", "text": "Source code for langchain_experimental.rl_chain.model_repository\nimport datetime\nimport glob\nimport logging\nimport os\nimport shutil\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, List, Union\nif TYPE_CHECKING:\n    import vowpal_wabbit_next as vw\nlogger = logging.getLogger(__name__)\n[docs]class ModelRepository:\n[docs]    def __init__(\n        self,\n        folder: Union[str, os.PathLike],\n        with_history: bool = True,\n        reset: bool = False,\n    ):\n        self.folder = Path(folder)\n        self.model_path = self.folder / \"latest.vw\"\n        self.with_history = with_history\n        if reset and self.has_history():\n            logger.warning(\n                \"There is non empty history which is recommended to be cleaned up\"\n            )\n            if self.model_path.exists():\n                os.remove(self.model_path)\n        self.folder.mkdir(parents=True, exist_ok=True)\n[docs]    def get_tag(self) -> str:\n        return datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n[docs]    def has_history(self) -> bool:\n        return len(glob.glob(str(self.folder / \"model-????????-??????.vw\"))) > 0\n[docs]    def save(self, workspace: \"vw.Workspace\") -> None:\n        with open(self.model_path, \"wb\") as f:\n            logger.info(f\"storing rl_chain model in: {self.model_path}\")\n            f.write(workspace.serialize())\n        if self.with_history:  # write history\n            shutil.copyfile(self.model_path, self.folder / f\"model-{self.get_tag()}.vw\")\n[docs]    def load(self, commandline: List[str]) -> \"vw.Workspace\":\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/model_repository.html"}
{"id": "9ba6cce9ece6-1", "text": "try:\n            import vowpal_wabbit_next as vw\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import vowpal_wabbit_next, please install with \"\n                \"`pip install vowpal_wabbit_next`.\"\n            ) from e\n        model_data = None\n        if self.model_path.exists():\n            with open(self.model_path, \"rb\") as f:\n                model_data = f.read()\n        if model_data:\n            logger.info(f\"rl_chain model is loaded from: {self.model_path}\")\n            return vw.Workspace(commandline, model_data=model_data)\n        return vw.Workspace(commandline)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/model_repository.html"}
{"id": "77a14ba3132e-0", "text": "Source code for langchain_experimental.rl_chain.pick_best_chain\nfrom __future__ import annotations\nimport logging\nfrom typing import Any, Dict, List, Optional, Tuple, Type, Union\nfrom langchain.base_language import BaseLanguageModel\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts import BasePromptTemplate\nimport langchain_experimental.rl_chain.base as base\nlogger = logging.getLogger(__name__)\n# sentinel object used to distinguish between\n# user didn't supply anything or user explicitly supplied None\nSENTINEL = object()\n[docs]class PickBestSelected(base.Selected):\n    index: Optional[int]\n    probability: Optional[float]\n    score: Optional[float]\n[docs]    def __init__(\n        self,\n        index: Optional[int] = None,\n        probability: Optional[float] = None,\n        score: Optional[float] = None,\n    ):\n        self.index = index\n        self.probability = probability\n        self.score = score\n[docs]class PickBestEvent(base.Event[PickBestSelected]):\n[docs]    def __init__(\n        self,\n        inputs: Dict[str, Any],\n        to_select_from: Dict[str, Any],\n        based_on: Dict[str, Any],\n        selected: Optional[PickBestSelected] = None,\n    ):\n        super().__init__(inputs=inputs, selected=selected)\n        self.to_select_from = to_select_from\n        self.based_on = based_on\n[docs]class PickBestFeatureEmbedder(base.Embedder[PickBestEvent]):\n    \"\"\"\n    Text Embedder class that embeds the `BasedOn` and `ToSelectFrom` inputs into a format that can be used by the learning policy\n    Attributes:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html"}
{"id": "77a14ba3132e-1", "text": "Attributes:\n        model name (Any, optional): The type of embeddings to be used for feature representation. Defaults to BERT SentenceTransformer.\n    \"\"\"  # noqa E501\n[docs]    def __init__(\n        self, auto_embed: bool, model: Optional[Any] = None, *args: Any, **kwargs: Any\n    ):\n        super().__init__(*args, **kwargs)\n        if model is None:\n            from sentence_transformers import SentenceTransformer\n            model = SentenceTransformer(\"all-mpnet-base-v2\")\n        self.model = model\n        self.auto_embed = auto_embed\n    @staticmethod\n    def _str(embedding: List[float]) -> str:\n        return \" \".join([f\"{i}:{e}\" for i, e in enumerate(embedding)])\n[docs]    def get_label(self, event: PickBestEvent) -> tuple:\n        cost = None\n        if event.selected:\n            chosen_action = event.selected.index\n            cost = (\n                -1.0 * event.selected.score\n                if event.selected.score is not None\n                else None\n            )\n            prob = event.selected.probability\n            return chosen_action, cost, prob\n        else:\n            return None, None, None\n[docs]    def get_context_and_action_embeddings(self, event: PickBestEvent) -> tuple:\n        context_emb = base.embed(event.based_on, self.model) if event.based_on else None\n        to_select_from_var_name, to_select_from = next(\n            iter(event.to_select_from.items()), (None, None)\n        )\n        action_embs = (\n            (\n                base.embed(to_select_from, self.model, to_select_from_var_name)\n                if event.to_select_from\n                else None\n            )\n            if to_select_from\n            else None\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html"}
{"id": "77a14ba3132e-2", "text": "else None\n            )\n            if to_select_from\n            else None\n        )\n        if not context_emb or not action_embs:\n            raise ValueError(\n                \"Context and to_select_from must be provided in the inputs dictionary\"\n            )\n        return context_emb, action_embs\n[docs]    def get_indexed_dot_product(self, context_emb: List, action_embs: List) -> Dict:\n        import numpy as np\n        unique_contexts = set()\n        for context_item in context_emb:\n            for ns, ee in context_item.items():\n                if isinstance(ee, list):\n                    for ea in ee:\n                        unique_contexts.add(f\"{ns}={ea}\")\n                else:\n                    unique_contexts.add(f\"{ns}={ee}\")\n        encoded_contexts = self.model.encode(list(unique_contexts))\n        context_embeddings = dict(zip(unique_contexts, encoded_contexts))\n        unique_actions = set()\n        for action in action_embs:\n            for ns, e in action.items():\n                if isinstance(e, list):\n                    for ea in e:\n                        unique_actions.add(f\"{ns}={ea}\")\n                else:\n                    unique_actions.add(f\"{ns}={e}\")\n        encoded_actions = self.model.encode(list(unique_actions))\n        action_embeddings = dict(zip(unique_actions, encoded_actions))\n        action_matrix = np.stack([v for k, v in action_embeddings.items()])\n        context_matrix = np.stack([v for k, v in context_embeddings.items()])\n        dot_product_matrix = np.dot(context_matrix, action_matrix.T)\n        indexed_dot_product: Dict = {}\n        for i, context_key in enumerate(context_embeddings.keys()):\n            indexed_dot_product[context_key] = {}\n            for j, action_key in enumerate(action_embeddings.keys()):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html"}
{"id": "77a14ba3132e-3", "text": "for j, action_key in enumerate(action_embeddings.keys()):\n                indexed_dot_product[context_key][action_key] = dot_product_matrix[i, j]\n        return indexed_dot_product\n[docs]    def format_auto_embed_on(self, event: PickBestEvent) -> str:\n        chosen_action, cost, prob = self.get_label(event)\n        context_emb, action_embs = self.get_context_and_action_embeddings(event)\n        indexed_dot_product = self.get_indexed_dot_product(context_emb, action_embs)\n        action_lines = []\n        for i, action in enumerate(action_embs):\n            line_parts = []\n            dot_prods = []\n            if cost is not None and chosen_action == i:\n                line_parts.append(f\"{chosen_action}:{cost}:{prob}\")\n            for ns, action in action.items():\n                line_parts.append(f\"|{ns}\")\n                elements = action if isinstance(action, list) else [action]\n                nsa = []\n                for elem in elements:\n                    line_parts.append(f\"{elem}\")\n                    ns_a = f\"{ns}={elem}\"\n                    nsa.append(ns_a)\n                    for k, v in indexed_dot_product.items():\n                        dot_prods.append(v[ns_a])\n                nsa_str = \" \".join(nsa)\n                line_parts.append(f\"|# {nsa_str}\")\n            line_parts.append(f\"|dotprod {self._str(dot_prods)}\")\n            action_lines.append(\" \".join(line_parts))\n        shared = []\n        for item in context_emb:\n            for ns, context in item.items():\n                shared.append(f\"|{ns}\")\n                elements = context if isinstance(context, list) else [context]\n                nsc = []\n                for elem in elements:\n                    shared.append(f\"{elem}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html"}
{"id": "77a14ba3132e-4", "text": "for elem in elements:\n                    shared.append(f\"{elem}\")\n                    nsc.append(f\"{ns}={elem}\")\n                nsc_str = \" \".join(nsc)\n                shared.append(f\"|@ {nsc_str}\")\n        return \"shared \" + \" \".join(shared) + \"\\n\" + \"\\n\".join(action_lines)\n[docs]    def format_auto_embed_off(self, event: PickBestEvent) -> str:\n        \"\"\"\n        Converts the `BasedOn` and `ToSelectFrom` into a format that can be used by VW\n        \"\"\"\n        chosen_action, cost, prob = self.get_label(event)\n        context_emb, action_embs = self.get_context_and_action_embeddings(event)\n        example_string = \"\"\n        example_string += \"shared \"\n        for context_item in context_emb:\n            for ns, based_on in context_item.items():\n                e = \" \".join(based_on) if isinstance(based_on, list) else based_on\n                example_string += f\"|{ns} {e} \"\n        example_string += \"\\n\"\n        for i, action in enumerate(action_embs):\n            if cost is not None and chosen_action == i:\n                example_string += f\"{chosen_action}:{cost}:{prob} \"\n            for ns, action_embedding in action.items():\n                e = (\n                    \" \".join(action_embedding)\n                    if isinstance(action_embedding, list)\n                    else action_embedding\n                )\n                example_string += f\"|{ns} {e} \"\n            example_string += \"\\n\"\n        # Strip the last newline\n        return example_string[:-1]\n[docs]    def format(self, event: PickBestEvent) -> str:\n        if self.auto_embed:\n            return self.format_auto_embed_on(event)\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html"}
{"id": "77a14ba3132e-5", "text": "return self.format_auto_embed_on(event)\n        else:\n            return self.format_auto_embed_off(event)\n[docs]class PickBestRandomPolicy(base.Policy[PickBestEvent]):\n[docs]    def __init__(self, feature_embedder: base.Embedder, **kwargs: Any):\n        self.feature_embedder = feature_embedder\n[docs]    def predict(self, event: PickBestEvent) -> List[Tuple[int, float]]:\n        num_items = len(event.to_select_from)\n        return [(i, 1.0 / num_items) for i in range(num_items)]\n[docs]    def learn(self, event: PickBestEvent) -> None:\n        pass\n[docs]    def log(self, event: PickBestEvent) -> None:\n        pass\n[docs]class PickBest(base.RLChain[PickBestEvent]):\n    \"\"\"\n    `PickBest` is a class designed to leverage the Vowpal Wabbit (VW) model for reinforcement learning with a context, with the goal of modifying the prompt before the LLM call.\n    Each invocation of the chain's `run()` method should be equipped with a set of potential actions (`ToSelectFrom`) and will result in the selection of a specific action based on the `BasedOn` input. This chosen action then informs the LLM (Language Model) prompt for the subsequent response generation.\n    The standard operation flow of this Chain includes:\n        1. The Chain is invoked with inputs containing the `BasedOn` criteria and a list of potential actions (`ToSelectFrom`).\n        2. An action is selected based on the `BasedOn` input.\n        3. The LLM is called with the dynamic prompt, producing a response.\n        4. If a `selection_scorer` is provided, it is used to score the selection.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html"}
{"id": "77a14ba3132e-6", "text": "5. The internal Vowpal Wabbit model is updated with the `BasedOn` input, the chosen `ToSelectFrom` action, and the resulting score from the scorer.\n        6. The final response is returned.\n    Expected input dictionary format:\n        - At least one variable encapsulated within `BasedOn` to serve as the selection criteria.\n        - A single list variable within `ToSelectFrom`, representing potential actions for the VW model. This list can take the form of:\n            - A list of strings, e.g., `action = ToSelectFrom([\"action1\", \"action2\", \"action3\"])`\n            - A list of list of strings e.g. `action = ToSelectFrom([[\"action1\", \"another identifier of action1\"], [\"action2\", \"another identifier of action2\"]])`\n            - A list of dictionaries, where each dictionary represents an action with namespace names as keys and corresponding action strings as values. For instance, `action = ToSelectFrom([{\"namespace1\": [\"action1\", \"another identifier of action1\"], \"namespace2\": \"action2\"}, {\"namespace1\": \"action3\", \"namespace2\": \"action4\"}])`.\n    Extends:\n        RLChain\n    Attributes:\n        feature_embedder (PickBestFeatureEmbedder, optional): Is an advanced attribute. Responsible for embedding the `BasedOn` and `ToSelectFrom` inputs. If omitted, a default embedder is utilized.\n    \"\"\"  # noqa E501\n    def __init__(\n        self,\n        *args: Any,\n        **kwargs: Any,\n    ):\n        auto_embed = kwargs.get(\"auto_embed\", False)\n        feature_embedder = kwargs.get(\"feature_embedder\", None)\n        if feature_embedder:\n            if \"auto_embed\" in kwargs:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html"}
{"id": "77a14ba3132e-7", "text": "if feature_embedder:\n            if \"auto_embed\" in kwargs:\n                logger.warning(\n                    \"auto_embed will take no effect when explicit feature_embedder is provided\"  # noqa E501\n                )\n            # turning auto_embed off for cli setting below\n            auto_embed = False\n        else:\n            feature_embedder = PickBestFeatureEmbedder(auto_embed=auto_embed)\n        kwargs[\"feature_embedder\"] = feature_embedder\n        vw_cmd = kwargs.get(\"vw_cmd\", [])\n        if vw_cmd:\n            if \"--cb_explore_adf\" not in vw_cmd:\n                raise ValueError(\n                    \"If vw_cmd is specified, it must include --cb_explore_adf\"\n                )\n        else:\n            interactions = [\"--interactions=::\"]\n            if auto_embed:\n                interactions = [\n                    \"--interactions=@#\",\n                    \"--ignore_linear=@\",\n                    \"--ignore_linear=#\",\n                ]\n            vw_cmd = interactions + [\n                \"--cb_explore_adf\",\n                \"--coin\",\n                \"--squarecb\",\n                \"--quiet\",\n            ]\n        kwargs[\"vw_cmd\"] = vw_cmd\n        super().__init__(*args, **kwargs)\n    def _call_before_predict(self, inputs: Dict[str, Any]) -> PickBestEvent:\n        context, actions = base.get_based_on_and_to_select_from(inputs=inputs)\n        if not actions:\n            raise ValueError(\n                \"No variables using 'ToSelectFrom' found in the inputs. Please include at least one variable containing a list to select from.\"  # noqa E501\n            )\n        if len(list(actions.values())) > 1:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html"}
{"id": "77a14ba3132e-8", "text": ")\n        if len(list(actions.values())) > 1:\n            raise ValueError(\n                \"Only one variable using 'ToSelectFrom' can be provided in the inputs for the PickBest chain. Please provide only one variable containing a list to select from.\"  # noqa E501\n            )\n        if not context:\n            raise ValueError(\n                \"No variables using 'BasedOn' found in the inputs. Please include at least one variable containing information to base the selected of ToSelectFrom on.\"  # noqa E501\n            )\n        event = PickBestEvent(inputs=inputs, to_select_from=actions, based_on=context)\n        return event\n    def _call_after_predict_before_llm(\n        self,\n        inputs: Dict[str, Any],\n        event: PickBestEvent,\n        prediction: List[Tuple[int, float]],\n    ) -> Tuple[Dict[str, Any], PickBestEvent]:\n        import numpy as np\n        prob_sum = sum(prob for _, prob in prediction)\n        probabilities = [prob / prob_sum for _, prob in prediction]\n        ## sample from the pmf\n        sampled_index = np.random.choice(len(prediction), p=probabilities)\n        sampled_ap = prediction[sampled_index]\n        sampled_action = sampled_ap[0]\n        sampled_prob = sampled_ap[1]\n        selected = PickBestSelected(index=sampled_action, probability=sampled_prob)\n        event.selected = selected\n        # only one key, value pair in event.to_select_from\n        key, value = next(iter(event.to_select_from.items()))\n        next_chain_inputs = inputs.copy()\n        next_chain_inputs.update({key: value[event.selected.index]})\n        return next_chain_inputs, event\n    def _call_after_llm_before_scoring(\n        self, llm_response: str, event: PickBestEvent", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html"}
{"id": "77a14ba3132e-9", "text": "self, llm_response: str, event: PickBestEvent\n    ) -> Tuple[Dict[str, Any], PickBestEvent]:\n        next_chain_inputs = event.inputs.copy()\n        # only one key, value pair in event.to_select_from\n        value = next(iter(event.to_select_from.values()))\n        v = (\n            value[event.selected.index]\n            if event.selected\n            else event.to_select_from.values()\n        )\n        next_chain_inputs.update(\n            {\n                self.selected_based_on_input_key: str(event.based_on),\n                self.selected_input_key: v,\n            }\n        )\n        return next_chain_inputs, event\n    def _call_after_scoring_before_learning(\n        self, event: PickBestEvent, score: Optional[float]\n    ) -> PickBestEvent:\n        if event.selected:\n            event.selected.score = score\n        return event\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        return super()._call(run_manager=run_manager, inputs=inputs)\n    @property\n    def _chain_type(self) -> str:\n        return \"rl_chain_pick_best\"\n[docs]    @classmethod\n    def from_llm(\n        cls: Type[PickBest],\n        llm: BaseLanguageModel,\n        prompt: BasePromptTemplate,\n        selection_scorer: Union[base.AutoSelectionScorer, object] = SENTINEL,\n        **kwargs: Any,\n    ) -> PickBest:\n        llm_chain = LLMChain(llm=llm, prompt=prompt)\n        if selection_scorer is SENTINEL:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html"}
{"id": "77a14ba3132e-10", "text": "if selection_scorer is SENTINEL:\n            selection_scorer = base.AutoSelectionScorer(llm=llm_chain.llm)\n        return PickBest(\n            llm_chain=llm_chain,\n            prompt=prompt,\n            selection_scorer=selection_scorer,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html"}
{"id": "284dc91a75da-0", "text": "Source code for langchain_experimental.rl_chain.base\nfrom __future__ import annotations\nimport logging\nimport os\nfrom abc import ABC, abstractmethod\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Dict,\n    Generic,\n    List,\n    Optional,\n    Tuple,\n    Type,\n    TypeVar,\n    Union,\n)\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts import (\n    BasePromptTemplate,\n    ChatPromptTemplate,\n    HumanMessagePromptTemplate,\n    SystemMessagePromptTemplate,\n)\nfrom langchain_experimental.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain_experimental.rl_chain.metrics import (\n    MetricsTrackerAverage,\n    MetricsTrackerRollingWindow,\n)\nfrom langchain_experimental.rl_chain.model_repository import ModelRepository\nfrom langchain_experimental.rl_chain.vw_logger import VwLogger\nif TYPE_CHECKING:\n    import vowpal_wabbit_next as vw\nlogger = logging.getLogger(__name__)\nclass _BasedOn:\n    def __init__(self, value: Any):\n        self.value = value\n    def __str__(self) -> str:\n        return str(self.value)\n    __repr__ = __str__\n[docs]def BasedOn(anything: Any) -> _BasedOn:\n    return _BasedOn(anything)\nclass _ToSelectFrom:\n    def __init__(self, value: Any):\n        self.value = value\n    def __str__(self) -> str:\n        return str(self.value)\n    __repr__ = __str__\n[docs]def ToSelectFrom(anything: Any) -> _ToSelectFrom:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-1", "text": "[docs]def ToSelectFrom(anything: Any) -> _ToSelectFrom:\n    if not isinstance(anything, list):\n        raise ValueError(\"ToSelectFrom must be a list to select from\")\n    return _ToSelectFrom(anything)\nclass _Embed:\n    def __init__(self, value: Any, keep: bool = False):\n        self.value = value\n        self.keep = keep\n    def __str__(self) -> str:\n        return str(self.value)\n    __repr__ = __str__\n[docs]def Embed(anything: Any, keep: bool = False) -> Any:\n    if isinstance(anything, _ToSelectFrom):\n        return ToSelectFrom(Embed(anything.value, keep=keep))\n    elif isinstance(anything, _BasedOn):\n        return BasedOn(Embed(anything.value, keep=keep))\n    if isinstance(anything, list):\n        return [Embed(v, keep=keep) for v in anything]\n    elif isinstance(anything, dict):\n        return {k: Embed(v, keep=keep) for k, v in anything.items()}\n    elif isinstance(anything, _Embed):\n        return anything\n    return _Embed(anything, keep=keep)\n[docs]def EmbedAndKeep(anything: Any) -> Any:\n    return Embed(anything, keep=True)\n# helper functions\n[docs]def stringify_embedding(embedding: List) -> str:\n    return \" \".join([f\"{i}:{e}\" for i, e in enumerate(embedding)])\n[docs]def parse_lines(parser: \"vw.TextFormatParser\", input_str: str) -> List[\"vw.Example\"]:\n    return [parser.parse_line(line) for line in input_str.split(\"\\n\")]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-2", "text": "return [parser.parse_line(line) for line in input_str.split(\"\\n\")]\n[docs]def get_based_on_and_to_select_from(inputs: Dict[str, Any]) -> Tuple[Dict, Dict]:\n    to_select_from = {\n        k: inputs[k].value\n        for k in inputs.keys()\n        if isinstance(inputs[k], _ToSelectFrom)\n    }\n    if not to_select_from:\n        raise ValueError(\n            \"No variables using 'ToSelectFrom' found in the inputs. Please include at least one variable containing a list to select from.\"  # noqa: E501\n        )\n    based_on = {\n        k: inputs[k].value if isinstance(inputs[k].value, list) else [inputs[k].value]\n        for k in inputs.keys()\n        if isinstance(inputs[k], _BasedOn)\n    }\n    return based_on, to_select_from\n[docs]def prepare_inputs_for_autoembed(inputs: Dict[str, Any]) -> Dict[str, Any]:\n    \"\"\"\n    go over all the inputs and if something is either wrapped in _ToSelectFrom or _BasedOn, and if their inner values are not already _Embed,\n    then wrap them in EmbedAndKeep while retaining their _ToSelectFrom or _BasedOn status\n    \"\"\"  # noqa: E501\n    next_inputs = inputs.copy()\n    for k, v in next_inputs.items():\n        if isinstance(v, _ToSelectFrom) or isinstance(v, _BasedOn):\n            if not isinstance(v.value, _Embed):\n                next_inputs[k].value = EmbedAndKeep(v.value)\n    return next_inputs\n# end helper functions\n[docs]class Selected(ABC):\n    pass\nTSelected = TypeVar(\"TSelected\", bound=Selected)\n[docs]class Event(Generic[TSelected], ABC):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-3", "text": "[docs]class Event(Generic[TSelected], ABC):\n    inputs: Dict[str, Any]\n    selected: Optional[TSelected]\n[docs]    def __init__(self, inputs: Dict[str, Any], selected: Optional[TSelected] = None):\n        self.inputs = inputs\n        self.selected = selected\nTEvent = TypeVar(\"TEvent\", bound=Event)\n[docs]class Policy(Generic[TEvent], ABC):\n[docs]    def __init__(self, **kwargs: Any):\n        pass\n[docs]    @abstractmethod\n    def predict(self, event: TEvent) -> Any:\n        ...\n[docs]    @abstractmethod\n    def learn(self, event: TEvent) -> None:\n        ...\n[docs]    @abstractmethod\n    def log(self, event: TEvent) -> None:\n        ...\n[docs]    def save(self) -> None:\n        pass\n[docs]class VwPolicy(Policy):\n[docs]    def __init__(\n        self,\n        model_repo: ModelRepository,\n        vw_cmd: List[str],\n        feature_embedder: Embedder,\n        vw_logger: VwLogger,\n        *args: Any,\n        **kwargs: Any,\n    ):\n        super().__init__(*args, **kwargs)\n        self.model_repo = model_repo\n        self.workspace = self.model_repo.load(vw_cmd)\n        self.feature_embedder = feature_embedder\n        self.vw_logger = vw_logger\n[docs]    def predict(self, event: TEvent) -> Any:\n        import vowpal_wabbit_next as vw\n        text_parser = vw.TextFormatParser(self.workspace)\n        return self.workspace.predict_one(\n            parse_lines(text_parser, self.feature_embedder.format(event))\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-4", "text": "parse_lines(text_parser, self.feature_embedder.format(event))\n        )\n[docs]    def learn(self, event: TEvent) -> None:\n        import vowpal_wabbit_next as vw\n        vw_ex = self.feature_embedder.format(event)\n        text_parser = vw.TextFormatParser(self.workspace)\n        multi_ex = parse_lines(text_parser, vw_ex)\n        self.workspace.learn_one(multi_ex)\n[docs]    def log(self, event: TEvent) -> None:\n        if self.vw_logger.logging_enabled():\n            vw_ex = self.feature_embedder.format(event)\n            self.vw_logger.log(vw_ex)\n[docs]    def save(self) -> None:\n        self.model_repo.save(self.workspace)\n[docs]class Embedder(Generic[TEvent], ABC):\n[docs]    def __init__(self, *args: Any, **kwargs: Any):\n        pass\n[docs]    @abstractmethod\n    def format(self, event: TEvent) -> str:\n        ...\n[docs]class SelectionScorer(Generic[TEvent], ABC, BaseModel):\n    \"\"\"Abstract method to grade the chosen selection or the response of the llm\"\"\"\n[docs]    @abstractmethod\n    def score_response(\n        self, inputs: Dict[str, Any], llm_response: str, event: TEvent\n    ) -> float:\n        ...\n[docs]class AutoSelectionScorer(SelectionScorer[Event], BaseModel):\n    llm_chain: LLMChain\n    prompt: Union[BasePromptTemplate, None] = None\n    scoring_criteria_template_str: Optional[str] = None\n[docs]    @staticmethod\n    def get_default_system_prompt() -> SystemMessagePromptTemplate:\n        return SystemMessagePromptTemplate.from_template(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-5", "text": "return SystemMessagePromptTemplate.from_template(\n            \"PLEASE RESPOND ONLY WITH A SINGLE FLOAT AND NO OTHER TEXT EXPLANATION\\n \\\n                You are a strict judge that is called on to rank a response based on \\\n                    given criteria. You must respond with your ranking by providing a \\\n                        single float within the range [0, 1], 0 being very bad \\\n                            response and 1 being very good response.\"\n        )\n[docs]    @staticmethod\n    def get_default_prompt() -> ChatPromptTemplate:\n        human_template = 'Given this based_on \"{rl_chain_selected_based_on}\" \\\n            as the most important attribute, rank how good or bad this text is: \\\n                \"{rl_chain_selected}\".'\n        human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\n        default_system_prompt = AutoSelectionScorer.get_default_system_prompt()\n        chat_prompt = ChatPromptTemplate.from_messages(\n            [default_system_prompt, human_message_prompt]\n        )\n        return chat_prompt\n    @root_validator(pre=True)\n    def set_prompt_and_llm_chain(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        llm = values.get(\"llm\")\n        prompt = values.get(\"prompt\")\n        scoring_criteria_template_str = values.get(\"scoring_criteria_template_str\")\n        if prompt is None and scoring_criteria_template_str is None:\n            prompt = AutoSelectionScorer.get_default_prompt()\n        elif prompt is None and scoring_criteria_template_str is not None:\n            human_message_prompt = HumanMessagePromptTemplate.from_template(\n                scoring_criteria_template_str\n            )\n            default_system_prompt = AutoSelectionScorer.get_default_system_prompt()\n            prompt = ChatPromptTemplate.from_messages(\n                [default_system_prompt, human_message_prompt]\n            )\n        values[\"prompt\"] = prompt", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-6", "text": ")\n        values[\"prompt\"] = prompt\n        values[\"llm_chain\"] = LLMChain(llm=llm, prompt=prompt)\n        return values\n[docs]    def score_response(\n        self, inputs: Dict[str, Any], llm_response: str, event: Event\n    ) -> float:\n        ranking = self.llm_chain.predict(llm_response=llm_response, **inputs)\n        ranking = ranking.strip()\n        try:\n            resp = float(ranking)\n            return resp\n        except Exception as e:\n            raise RuntimeError(\n                f\"The auto selection scorer did not manage to score the response, there is always the option to try again or tweak the reward prompt. Error: {e}\"  # noqa: E501\n            )\n[docs]class RLChain(Chain, Generic[TEvent]):\n    \"\"\"\n    The `RLChain` class leverages the Vowpal Wabbit (VW) model as a learned policy for reinforcement learning.\n    Attributes:\n        - llm_chain (Chain): Represents the underlying Language Model chain.\n        - prompt (BasePromptTemplate): The template for the base prompt.\n        - selection_scorer (Union[SelectionScorer, None]): Scorer for the selection. Can be set to None.\n        - policy (Optional[Policy]): The policy used by the chain to learn to populate a dynamic prompt.\n        - auto_embed (bool): Determines if embedding should be automatic. Default is False.\n        - metrics (Optional[Union[MetricsTrackerRollingWindow, MetricsTrackerAverage]]): Tracker for metrics, can be set to None.\n    Initialization Attributes:\n        - feature_embedder (Embedder): Embedder used for the `BasedOn` and `ToSelectFrom` inputs.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-7", "text": "- model_save_dir (str, optional): Directory for saving the VW model. Default is the current directory.\n        - reset_model (bool): If set to True, the model starts training from scratch. Default is False.\n        - vw_cmd (List[str], optional): Command line arguments for the VW model.\n        - policy (Type[VwPolicy]): Policy used by the chain.\n        - vw_logs (Optional[Union[str, os.PathLike]]): Path for the VW logs.\n        - metrics_step (int): Step for the metrics tracker. Default is -1. If set without metrics_window_size, average metrics will be tracked, otherwise rolling window metrics will be tracked.\n        - metrics_window_size (int): Window size for the metrics tracker. Default is -1. If set, rolling window metrics will be tracked.\n    Notes:\n        The class initializes the VW model using the provided arguments. If `selection_scorer` is not provided, a warning is logged, indicating that no reinforcement learning will occur unless the `update_with_delayed_score` method is called.\n    \"\"\"  # noqa: E501\n    class _NoOpPolicy(Policy):\n        \"\"\"Placeholder policy that does nothing\"\"\"\n        def predict(self, event: TEvent) -> Any:\n            return None\n        def learn(self, event: TEvent) -> None:\n            pass\n        def log(self, event: TEvent) -> None:\n            pass\n    llm_chain: Chain\n    output_key: str = \"result\"  #: :meta private:\n    prompt: BasePromptTemplate\n    selection_scorer: Union[SelectionScorer, None]\n    active_policy: Policy = _NoOpPolicy()\n    auto_embed: bool = False\n    selection_scorer_activated: bool = True\n    selected_input_key = \"rl_chain_selected\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-8", "text": "selected_input_key = \"rl_chain_selected\"\n    selected_based_on_input_key = \"rl_chain_selected_based_on\"\n    metrics: Optional[Union[MetricsTrackerRollingWindow, MetricsTrackerAverage]] = None\n    def __init__(\n        self,\n        feature_embedder: Embedder,\n        model_save_dir: str = \"./\",\n        reset_model: bool = False,\n        vw_cmd: Optional[List[str]] = None,\n        policy: Type[Policy] = VwPolicy,\n        vw_logs: Optional[Union[str, os.PathLike]] = None,\n        metrics_step: int = -1,\n        metrics_window_size: int = -1,\n        *args: Any,\n        **kwargs: Any,\n    ):\n        super().__init__(*args, **kwargs)\n        if self.selection_scorer is None:\n            logger.warning(\n                \"No selection scorer provided, which means that no \\\n                    reinforcement learning will be done in the RL chain \\\n                        unless update_with_delayed_score is called.\"\n            )\n        if isinstance(self.active_policy, RLChain._NoOpPolicy):\n            self.active_policy = policy(\n                model_repo=ModelRepository(\n                    model_save_dir, with_history=True, reset=reset_model\n                ),\n                vw_cmd=vw_cmd or [],\n                feature_embedder=feature_embedder,\n                vw_logger=VwLogger(vw_logs),\n            )\n        if metrics_window_size > 0:\n            self.metrics = MetricsTrackerRollingWindow(\n                step=metrics_step, window_size=metrics_window_size\n            )\n        else:\n            self.metrics = MetricsTrackerAverage(step=metrics_step)\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-9", "text": "extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        return []\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Expect output key.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n[docs]    def update_with_delayed_score(\n        self, score: float, chain_response: Dict[str, Any], force_score: bool = False\n    ) -> None:\n        \"\"\"\n        Updates the learned policy with the score provided.\n        Will raise an error if selection_scorer is set, and force_score=True was not provided during the method call\n        \"\"\"  # noqa: E501\n        if self._can_use_selection_scorer() and not force_score:\n            raise RuntimeError(\n                \"The selection scorer is set, and force_score was not set to True. Please set force_score=True to use this function.\"  # noqa: E501\n            )\n        if self.metrics:\n            self.metrics.on_feedback(score)\n        event: TEvent = chain_response[\"selection_metadata\"]\n        self._call_after_scoring_before_learning(event=event, score=score)\n        self.active_policy.learn(event=event)\n        self.active_policy.log(event=event)\n[docs]    def deactivate_selection_scorer(self) -> None:\n        \"\"\"\n        Deactivates the selection scorer, meaning that the chain will no longer attempt to use the selection scorer to score responses.\n        \"\"\"  # noqa: E501\n        self.selection_scorer_activated = False\n[docs]    def activate_selection_scorer(self) -> None:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-10", "text": "[docs]    def activate_selection_scorer(self) -> None:\n        \"\"\"\n        Activates the selection scorer, meaning that the chain will attempt to use the selection scorer to score responses.\n        \"\"\"  # noqa: E501\n        self.selection_scorer_activated = True\n[docs]    def save_progress(self) -> None:\n        \"\"\"\n        This function should be called to save the state of the learned policy model.\n        \"\"\"  # noqa: E501\n        self.active_policy.save()\n    def _validate_inputs(self, inputs: Dict[str, Any]) -> None:\n        super()._validate_inputs(inputs)\n        if (\n            self.selected_input_key in inputs.keys()\n            or self.selected_based_on_input_key in inputs.keys()\n        ):\n            raise ValueError(\n                f\"The rl chain does not accept '{self.selected_input_key}' or '{self.selected_based_on_input_key}' as input keys, they are reserved for internal use during auto reward.\"  # noqa: E501\n            )\n    def _can_use_selection_scorer(self) -> bool:\n        \"\"\"\n        Returns whether the chain can use the selection scorer to score responses or not.\n        \"\"\"  # noqa: E501\n        return self.selection_scorer is not None and self.selection_scorer_activated\n    @abstractmethod\n    def _call_before_predict(self, inputs: Dict[str, Any]) -> TEvent:\n        ...\n    @abstractmethod\n    def _call_after_predict_before_llm(\n        self, inputs: Dict[str, Any], event: TEvent, prediction: Any\n    ) -> Tuple[Dict[str, Any], TEvent]:\n        ...\n    @abstractmethod\n    def _call_after_llm_before_scoring(\n        self, llm_response: str, event: TEvent", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-11", "text": "self, llm_response: str, event: TEvent\n    ) -> Tuple[Dict[str, Any], TEvent]:\n        ...\n    @abstractmethod\n    def _call_after_scoring_before_learning(\n        self, event: TEvent, score: Optional[float]\n    ) -> TEvent:\n        ...\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        event: TEvent = self._call_before_predict(inputs=inputs)\n        prediction = self.active_policy.predict(event=event)\n        if self.metrics:\n            self.metrics.on_decision()\n        next_chain_inputs, event = self._call_after_predict_before_llm(\n            inputs=inputs, event=event, prediction=prediction\n        )\n        t = self.llm_chain.run(**next_chain_inputs, callbacks=_run_manager.get_child())\n        _run_manager.on_text(t, color=\"green\", verbose=self.verbose)\n        t = t.strip()\n        if self.verbose:\n            _run_manager.on_text(\"\\nCode: \", verbose=self.verbose)\n        output = t\n        _run_manager.on_text(\"\\nAnswer: \", verbose=self.verbose)\n        _run_manager.on_text(output, color=\"yellow\", verbose=self.verbose)\n        next_chain_inputs, event = self._call_after_llm_before_scoring(\n            llm_response=output, event=event\n        )\n        score = None\n        try:\n            if self._can_use_selection_scorer():\n                score = self.selection_scorer.score_response(  # type: ignore\n                    inputs=next_chain_inputs, llm_response=output, event=event\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-12", "text": "inputs=next_chain_inputs, llm_response=output, event=event\n                )\n        except Exception as e:\n            logger.info(\n                f\"The selection scorer was not able to score, \\\n                and the chain was not able to adjust to this response, error: {e}\"\n            )\n        if self.metrics and score is not None:\n            self.metrics.on_feedback(score)\n        event = self._call_after_scoring_before_learning(score=score, event=event)\n        self.active_policy.learn(event=event)\n        self.active_policy.log(event=event)\n        return {self.output_key: {\"response\": output, \"selection_metadata\": event}}\n    @property\n    def _chain_type(self) -> str:\n        return \"llm_personalizer_chain\"\n[docs]def is_stringtype_instance(item: Any) -> bool:\n    \"\"\"Helper function to check if an item is a string.\"\"\"\n    return isinstance(item, str) or (\n        isinstance(item, _Embed) and isinstance(item.value, str)\n    )\n[docs]def embed_string_type(\n    item: Union[str, _Embed], model: Any, namespace: Optional[str] = None\n) -> Dict[str, Union[str, List[str]]]:\n    \"\"\"Helper function to embed a string or an _Embed object.\"\"\"\n    keep_str = \"\"\n    if isinstance(item, _Embed):\n        encoded = stringify_embedding(model.encode(item.value))\n        if item.keep:\n            keep_str = item.value.replace(\" \", \"_\") + \" \"\n    elif isinstance(item, str):\n        encoded = item.replace(\" \", \"_\")\n    else:\n        raise ValueError(f\"Unsupported type {type(item)} for embedding\")\n    if namespace is None:\n        raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-13", "text": "if namespace is None:\n        raise ValueError(\n            \"The default namespace must be provided when embedding a string or _Embed object.\"  # noqa: E501\n        )\n    return {namespace: keep_str + encoded}\n[docs]def embed_dict_type(item: Dict, model: Any) -> Dict[str, Any]:\n    \"\"\"Helper function to embed a dictionary item.\"\"\"\n    inner_dict: Dict = {}\n    for ns, embed_item in item.items():\n        if isinstance(embed_item, list):\n            inner_dict[ns] = []\n            for embed_list_item in embed_item:\n                embedded = embed_string_type(embed_list_item, model, ns)\n                inner_dict[ns].append(embedded[ns])\n        else:\n            inner_dict.update(embed_string_type(embed_item, model, ns))\n    return inner_dict\n[docs]def embed_list_type(\n    item: list, model: Any, namespace: Optional[str] = None\n) -> List[Dict[str, Union[str, List[str]]]]:\n    ret_list: List = []\n    for embed_item in item:\n        if isinstance(embed_item, dict):\n            ret_list.append(embed_dict_type(embed_item, model))\n        elif isinstance(embed_item, list):\n            item_embedding = embed_list_type(embed_item, model, namespace)\n            # Get the first key from the first dictionary\n            first_key = next(iter(item_embedding[0]))\n            # Group the values under that key\n            grouping = {first_key: [item[first_key] for item in item_embedding]}\n            ret_list.append(grouping)\n        else:\n            ret_list.append(embed_string_type(embed_item, model, namespace))\n    return ret_list\n[docs]def embed(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "284dc91a75da-14", "text": "return ret_list\n[docs]def embed(\n    to_embed: Union[Union[str, _Embed], Dict, List[Union[str, _Embed]], List[Dict]],\n    model: Any,\n    namespace: Optional[str] = None,\n) -> List[Dict[str, Union[str, List[str]]]]:\n    \"\"\"\n    Embeds the actions or context using the SentenceTransformer model (or a model that has an `encode` function)\n    Attributes:\n        to_embed: (Union[Union(str, _Embed(str)), Dict, List[Union(str, _Embed(str))], List[Dict]], required) The text to be embedded, either a string, a list of strings or a dictionary or a list of dictionaries.\n        namespace: (str, optional) The default namespace to use when dictionary or list of dictionaries not provided.\n        model: (Any, required) The model to use for embedding\n    Returns:\n        List[Dict[str, str]]: A list of dictionaries where each dictionary has the namespace as the key and the embedded string as the value\n    \"\"\"  # noqa: E501\n    if (isinstance(to_embed, _Embed) and isinstance(to_embed.value, str)) or isinstance(\n        to_embed, str\n    ):\n        return [embed_string_type(to_embed, model, namespace)]\n    elif isinstance(to_embed, dict):\n        return [embed_dict_type(to_embed, model)]\n    elif isinstance(to_embed, list):\n        return embed_list_type(to_embed, model, namespace)\n    else:\n        raise ValueError(\"Invalid input format for embedding\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html"}
{"id": "5467eaf1e8be-0", "text": "Source code for langchain_experimental.rl_chain.vw_logger\nfrom os import PathLike\nfrom pathlib import Path\nfrom typing import Optional, Union\n[docs]class VwLogger:\n[docs]    def __init__(self, path: Optional[Union[str, PathLike]]):\n        self.path = Path(path) if path else None\n        if self.path:\n            self.path.parent.mkdir(parents=True, exist_ok=True)\n[docs]    def log(self, vw_ex: str) -> None:\n        if self.path:\n            with open(self.path, \"a\") as f:\n                f.write(f\"{vw_ex}\\n\\n\")\n[docs]    def logging_enabled(self) -> bool:\n        return bool(self.path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/vw_logger.html"}
{"id": "d66996ca92db-0", "text": "Source code for langchain_experimental.rl_chain.metrics\nfrom collections import deque\nfrom typing import TYPE_CHECKING, Dict, List, Union\nif TYPE_CHECKING:\n    import pandas as pd\n[docs]class MetricsTrackerAverage:\n[docs]    def __init__(self, step: int):\n        self.history: List[Dict[str, Union[int, float]]] = [{\"step\": 0, \"score\": 0}]\n        self.step: int = step\n        self.i: int = 0\n        self.num: float = 0\n        self.denom: float = 0\n    @property\n    def score(self) -> float:\n        return self.num / self.denom if self.denom > 0 else 0\n[docs]    def on_decision(self) -> None:\n        self.denom += 1\n[docs]    def on_feedback(self, score: float) -> None:\n        self.num += score or 0\n        self.i += 1\n        if self.step > 0 and self.i % self.step == 0:\n            self.history.append({\"step\": self.i, \"score\": self.score})\n[docs]    def to_pandas(self) -> \"pd.DataFrame\":\n        import pandas as pd\n        return pd.DataFrame(self.history)\n[docs]class MetricsTrackerRollingWindow:\n[docs]    def __init__(self, window_size: int, step: int):\n        self.history: List[Dict[str, Union[int, float]]] = [{\"step\": 0, \"score\": 0}]\n        self.step: int = step\n        self.i: int = 0\n        self.window_size: int = window_size\n        self.queue: deque = deque()\n        self.sum: float = 0.0\n    @property\n    def score(self) -> float:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/metrics.html"}
{"id": "d66996ca92db-1", "text": "@property\n    def score(self) -> float:\n        return self.sum / len(self.queue) if len(self.queue) > 0 else 0\n[docs]    def on_decision(self) -> None:\n        pass\n[docs]    def on_feedback(self, value: float) -> None:\n        self.sum += value\n        self.queue.append(value)\n        self.i += 1\n        if len(self.queue) > self.window_size:\n            old_val = self.queue.popleft()\n            self.sum -= old_val\n        if self.step > 0 and self.i % self.step == 0:\n            self.history.append({\"step\": self.i, \"score\": self.sum / len(self.queue)})\n[docs]    def to_pandas(self) -> \"pd.DataFrame\":\n        import pandas as pd\n        return pd.DataFrame(self.history)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/metrics.html"}
{"id": "4fd8ea3f9841-0", "text": "Source code for langchain_experimental.prompt_injection_identifier.hugging_face_identifier\n\"\"\"Tool for the identification of prompt injection attacks.\"\"\"\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\nif TYPE_CHECKING:\n    from transformers import Pipeline\ndef _model_default_factory() -> Pipeline:\n    try:\n        from transformers import pipeline\n    except ImportError as e:\n        raise ImportError(\n            \"Cannot import transformers, please install with \"\n            \"`pip install transformers`.\"\n        ) from e\n    return pipeline(\"text-classification\", model=\"deepset/deberta-v3-base-injection\")\n[docs]class HuggingFaceInjectionIdentifier(BaseTool):\n    \"\"\"Tool that uses deberta-v3-base-injection to detect prompt injection attacks.\"\"\"\n    name: str = \"hugging_face_injection_identifier\"\n    description: str = (\n        \"A wrapper around HuggingFace Prompt Injection security model. \"\n        \"Useful for when you need to ensure that prompt is free of injection attacks. \"\n        \"Input should be any message from the user.\"\n    )\n    model: Pipeline = Field(default_factory=_model_default_factory)\n    def _run(self, query: str) -> str:\n        \"\"\"Use the tool.\"\"\"\n        result = self.model(query)\n        result = sorted(result, key=lambda x: x[\"score\"], reverse=True)\n        if result[0][\"label\"] == \"INJECTION\":\n            raise ValueError(\"Prompt injection attack detected\")\n        return query", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/prompt_injection_identifier/hugging_face_identifier.html"}
{"id": "aba36ae210b9-0", "text": "Source code for langchain_experimental.llm_symbolic_math.base\n\"\"\"Chain that interprets a prompt and executes python code to do symbolic math.\"\"\"\nfrom __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Optional\nfrom langchain.base_language import BaseLanguageModel\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts.base import BasePromptTemplate\nfrom langchain_experimental.llm_symbolic_math.prompt import PROMPT\nfrom langchain_experimental.pydantic_v1 import Extra\n[docs]class LLMSymbolicMathChain(Chain):\n    \"\"\"Chain that interprets a prompt and executes python code to do symbolic math.\n    Example:\n        .. code-block:: python\n            from langchain.chains import LLMSymbolicMathChain\n            from langchain.llms import OpenAI\n            llm_symbolic_math = LLMSymbolicMathChain.from_llm(OpenAI())\n    \"\"\"\n    llm_chain: LLMChain\n    input_key: str = \"question\"  #: :meta private:\n    output_key: str = \"answer\"  #: :meta private:\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Expect output key.\n        :meta private:\n        \"\"\"\n        return [self.output_key]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_symbolic_math/base.html"}
{"id": "aba36ae210b9-1", "text": ":meta private:\n        \"\"\"\n        return [self.output_key]\n    def _evaluate_expression(self, expression: str) -> str:\n        try:\n            import sympy\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import sympy, please install it with `pip install sympy`.\"\n            ) from e\n        try:\n            output = str(sympy.sympify(expression, evaluate=True))\n        except Exception as e:\n            raise ValueError(\n                f'LLMSymbolicMathChain._evaluate(\"{expression}\") raised error: {e}.'\n                \" Please try again with a valid numerical expression\"\n            )\n        # Remove any leading and trailing brackets from the output\n        return re.sub(r\"^\\[|\\]$\", \"\", output)\n    def _process_llm_result(\n        self, llm_output: str, run_manager: CallbackManagerForChainRun\n    ) -> Dict[str, str]:\n        run_manager.on_text(llm_output, color=\"green\", verbose=self.verbose)\n        llm_output = llm_output.strip()\n        text_match = re.search(r\"^```text(.*?)```\", llm_output, re.DOTALL)\n        if text_match:\n            expression = text_match.group(1)\n            output = self._evaluate_expression(expression)\n            run_manager.on_text(\"\\nAnswer: \", verbose=self.verbose)\n            run_manager.on_text(output, color=\"yellow\", verbose=self.verbose)\n            answer = \"Answer: \" + output\n        elif llm_output.startswith(\"Answer:\"):\n            answer = llm_output\n        elif \"Answer:\" in llm_output:\n            answer = \"Answer: \" + llm_output.split(\"Answer:\")[-1]\n        else:\n            raise ValueError(f\"unknown format from LLM: {llm_output}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_symbolic_math/base.html"}
{"id": "aba36ae210b9-2", "text": "raise ValueError(f\"unknown format from LLM: {llm_output}\")\n        return {self.output_key: answer}\n    async def _aprocess_llm_result(\n        self,\n        llm_output: str,\n        run_manager: AsyncCallbackManagerForChainRun,\n    ) -> Dict[str, str]:\n        await run_manager.on_text(llm_output, color=\"green\", verbose=self.verbose)\n        llm_output = llm_output.strip()\n        text_match = re.search(r\"^```text(.*?)```\", llm_output, re.DOTALL)\n        if text_match:\n            expression = text_match.group(1)\n            output = self._evaluate_expression(expression)\n            await run_manager.on_text(\"\\nAnswer: \", verbose=self.verbose)\n            await run_manager.on_text(output, color=\"yellow\", verbose=self.verbose)\n            answer = \"Answer: \" + output\n        elif llm_output.startswith(\"Answer:\"):\n            answer = llm_output\n        elif \"Answer:\" in llm_output:\n            answer = \"Answer: \" + llm_output.split(\"Answer:\")[-1]\n        else:\n            raise ValueError(f\"unknown format from LLM: {llm_output}\")\n        return {self.output_key: answer}\n    def _call(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        _run_manager.on_text(inputs[self.input_key])\n        llm_output = self.llm_chain.predict(\n            question=inputs[self.input_key],\n            stop=[\"```output\"],\n            callbacks=_run_manager.get_child(),\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_symbolic_math/base.html"}
{"id": "aba36ae210b9-3", "text": "stop=[\"```output\"],\n            callbacks=_run_manager.get_child(),\n        )\n        return self._process_llm_result(llm_output, _run_manager)\n    async def _acall(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()\n        await _run_manager.on_text(inputs[self.input_key])\n        llm_output = await self.llm_chain.apredict(\n            question=inputs[self.input_key],\n            stop=[\"```output\"],\n            callbacks=_run_manager.get_child(),\n        )\n        return await self._aprocess_llm_result(llm_output, _run_manager)\n    @property\n    def _chain_type(self) -> str:\n        return \"llm_symbolic_math_chain\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        prompt: BasePromptTemplate = PROMPT,\n        **kwargs: Any,\n    ) -> LLMSymbolicMathChain:\n        llm_chain = LLMChain(llm=llm, prompt=prompt)\n        return cls(llm_chain=llm_chain, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_symbolic_math/base.html"}
{"id": "b0afdb1229ac-0", "text": "Source code for langchain_experimental.llms.anthropic_functions\nimport json\nfrom collections import defaultdict\nfrom html.parser import HTMLParser\nfrom typing import Any, DefaultDict, Dict, List, Optional\nfrom langchain.callbacks.manager import (\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.anthropic import ChatAnthropic\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.schema import (\n    ChatGeneration,\n    ChatResult,\n)\nfrom langchain.schema.messages import (\n    AIMessage,\n    BaseMessage,\n    SystemMessage,\n)\nfrom langchain_experimental.pydantic_v1 import root_validator\nprompt = \"\"\"In addition to responding, you can use tools. \\\nYou have access to the following tools.\n{tools}\nIn order to use a tool, you can use <tool></tool> to specify the name, \\\nand the <tool_input></tool_input> tags to specify the parameters. \\\nEach parameter should be passed in as <$param_name>$value</$param_name>, \\\nWhere $param_name is the name of the specific parameter, and $value \\\nis the value for that parameter.\nYou will then get back a response in the form <observation></observation>\nFor example, if you have a tool called 'search' that accepts a single \\\nparameter 'query' that could run a google search, in order to search \\\nfor the weather in SF you would respond:\n<tool>search</tool><tool_input><query>weather in SF</query></tool_input>\n<observation>64 degrees</observation>\"\"\"\n[docs]class TagParser(HTMLParser):\n[docs]    def __init__(self) -> None:\n        \"\"\"A heavy-handed solution, but it's fast for prototyping.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html"}
{"id": "b0afdb1229ac-1", "text": "\"\"\"A heavy-handed solution, but it's fast for prototyping.\n        Might be re-implemented later to restrict scope to the limited grammar, and\n        more efficiency.\n        Uses an HTML parser to parse a limited grammar that allows\n        for syntax of the form:\n            INPUT -> JUNK? VALUE*\n            JUNK -> JUNK_CHARACTER+\n            JUNK_CHARACTER -> whitespace | ,\n            VALUE -> <IDENTIFIER>DATA</IDENTIFIER> | OBJECT\n            OBJECT -> <IDENTIFIER>VALUE+</IDENTIFIER>\n            IDENTIFIER -> [a-Z][a-Z0-9_]*\n            DATA -> .*\n        Interprets the data to allow repetition of tags and recursion\n        to support representation of complex types.\n        ^ Just another approximately wrong grammar specification.\n        \"\"\"\n        super().__init__()\n        self.parse_data: DefaultDict[str, List[Any]] = defaultdict(list)\n        self.stack: List[DefaultDict[str, List[str]]] = [self.parse_data]\n        self.success = True\n        self.depth = 0\n        self.data: Optional[str] = None\n[docs]    def handle_starttag(self, tag: str, attrs: Any) -> None:\n        \"\"\"Hook when a new tag is encountered.\"\"\"\n        self.depth += 1\n        self.stack.append(defaultdict(list))\n        self.data = None\n[docs]    def handle_endtag(self, tag: str) -> None:\n        \"\"\"Hook when a tag is closed.\"\"\"\n        self.depth -= 1\n        top_of_stack = dict(self.stack.pop(-1))  # Pop the dictionary we don't need it\n        # If a lead node\n        is_leaf = self.data is not None\n        # Annoying to type here, code is tested, hopefully OK\n        value = self.data if is_leaf else top_of_stack", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html"}
{"id": "b0afdb1229ac-2", "text": "value = self.data if is_leaf else top_of_stack\n        # Difficult to type this correctly with mypy (maybe impossible?)\n        # Can be nested indefinitely, so requires self referencing type\n        self.stack[-1][tag].append(value)  # type: ignore\n        # Reset the data so we if we encounter a sequence of end tags, we\n        # don't confuse an outer end tag for belonging to a leaf node.\n        self.data = None\n[docs]    def handle_data(self, data: str) -> None:\n        \"\"\"Hook when handling data.\"\"\"\n        stripped_data = data.strip()\n        # The only data that's allowed is whitespace or a comma surrounded by whitespace\n        if self.depth == 0 and stripped_data not in (\",\", \"\"):\n            # If this is triggered the parse should be considered invalid.\n            self.success = False\n        if stripped_data:  # ignore whitespace-only strings\n            self.data = stripped_data\ndef _destrip(tool_input: Any) -> Any:\n    if isinstance(tool_input, dict):\n        return {k: _destrip(v) for k, v in tool_input.items()}\n    elif isinstance(tool_input, list):\n        if isinstance(tool_input[0], str):\n            if len(tool_input) == 1:\n                return tool_input[0]\n            else:\n                raise ValueError\n        elif isinstance(tool_input[0], dict):\n            return [_destrip(v) for v in tool_input]\n        else:\n            raise ValueError\n    else:\n        raise ValueError\n[docs]class AnthropicFunctions(BaseChatModel):\n    llm: BaseChatModel\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        values[\"llm\"] = values.get(\"llm\") or ChatAnthropic(**values)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html"}
{"id": "b0afdb1229ac-3", "text": "return values\n    @property\n    def model(self) -> BaseChatModel:\n        \"\"\"For backwards compatibility.\"\"\"\n        return self.llm\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        forced = False\n        function_call = \"\"\n        if \"functions\" in kwargs:\n            content = prompt.format(tools=json.dumps(kwargs[\"functions\"], indent=2))\n            system = SystemMessage(content=content)\n            messages = [system] + messages\n            del kwargs[\"functions\"]\n            if stop is None:\n                stop = [\"</tool_input>\"]\n            else:\n                stop.append(\"</tool_input>\")\n            if \"function_call\" in kwargs:\n                forced = True\n                function_call = kwargs[\"function_call\"][\"name\"]\n                AIMessage(content=f\"<tool>{function_call}</tool>\")\n                del kwargs[\"function_call\"]\n        else:\n            if \"function_call\" in kwargs:\n                raise ValueError(\n                    \"if `function_call` provided, `functions` must also be\"\n                )\n        response = self.model.predict_messages(\n            messages, stop=stop, callbacks=run_manager, **kwargs\n        )\n        completion = response.content\n        if forced:\n            tag_parser = TagParser()\n            tag_parser.feed(completion.strip() + \"</tool_input>\")\n            v1 = tag_parser.parse_data[\"tool_input\"][0]\n            kwargs = {\n                \"function_call\": {\n                    \"name\": function_call,\n                    \"arguments\": json.dumps(_destrip(v1)),\n                }\n            }\n            message = AIMessage(content=\"\", additional_kwargs=kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html"}
{"id": "b0afdb1229ac-4", "text": "}\n            }\n            message = AIMessage(content=\"\", additional_kwargs=kwargs)\n            return ChatResult(generations=[ChatGeneration(message=message)])\n        elif \"<tool>\" in completion:\n            tag_parser = TagParser()\n            tag_parser.feed(completion.strip() + \"</tool_input>\")\n            msg = completion.split(\"<tool>\")[0]\n            v1 = tag_parser.parse_data[\"tool_input\"][0]\n            kwargs = {\n                \"function_call\": {\n                    \"name\": tag_parser.parse_data[\"tool\"][0],\n                    \"arguments\": json.dumps(_destrip(v1)),\n                }\n            }\n            message = AIMessage(content=msg, additional_kwargs=kwargs)\n            return ChatResult(generations=[ChatGeneration(message=message)])\n        else:\n            return ChatResult(generations=[ChatGeneration(message=response)])\n    @property\n    def _llm_type(self) -> str:\n        return \"anthropic_functions\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html"}
{"id": "ef52f97a636f-0", "text": "Source code for langchain_experimental.llms.lmformatenforcer_decoder\n\"\"\"Experimental implementation of lm-format-enforcer wrapped LLM.\"\"\"\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Any, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.huggingface_pipeline import HuggingFacePipeline\nfrom langchain.schema import LLMResult\nfrom langchain_experimental.pydantic_v1 import Field\nif TYPE_CHECKING:\n    import lmformatenforcer\n[docs]def import_lmformatenforcer() -> lmformatenforcer:\n    \"\"\"Lazily import lmformatenforcer.\"\"\"\n    try:\n        import lmformatenforcer\n    except ImportError:\n        raise ImportError(\n            \"Could not import lmformatenforcer python package. \"\n            \"Please install it with `pip install lm-format-enforcer`.\"\n        )\n    return lmformatenforcer\n[docs]class LMFormatEnforcer(HuggingFacePipeline):\n    \"\"\"LMFormatEnforcer wrapped LLM using HuggingFace Pipeline API.\n    This pipeline is experimental and not yet stable.\n    \"\"\"\n    json_schema: Optional[dict] = Field(\n        description=\"The JSON Schema to complete.\", default=None\n    )\n    regex: Optional[str] = Field(\n        description=\"The regular expression to complete.\", default=None\n    )\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        lmformatenforcer = import_lmformatenforcer()\n        import lmformatenforcer.integrations.transformers as hf_integration", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/lmformatenforcer_decoder.html"}
{"id": "ef52f97a636f-1", "text": "import lmformatenforcer.integrations.transformers as hf_integration\n        # We integrate lmformatenforcer by adding a prefix_allowed_tokens_fn.\n        # It has to be done on each call, because the prefix function is stateful.\n        if \"prefix_allowed_tokens_fn\" in self.pipeline._forward_params:\n            raise ValueError(\n                \"prefix_allowed_tokens_fn param is forbidden with LMFormatEnforcer.\"\n            )\n        has_json_schema = self.json_schema is not None\n        has_regex = self.regex is not None\n        if has_json_schema == has_regex:\n            raise ValueError(\n                \"You must specify exactly one of json_schema or a regex, but not both.\"\n            )\n        if has_json_schema:\n            parser = lmformatenforcer.JsonSchemaParser(self.json_schema)\n        else:\n            parser = lmformatenforcer.RegexParser(self.regex)\n        prefix_function = hf_integration.build_transformers_prefix_allowed_tokens_fn(\n            self.pipeline.tokenizer, parser\n        )\n        self.pipeline._forward_params[\"prefix_allowed_tokens_fn\"] = prefix_function\n        result = super()._generate(\n            prompts,\n            stop=stop,\n            run_manager=run_manager,\n            **kwargs,\n        )\n        del self.pipeline._forward_params[\"prefix_allowed_tokens_fn\"]\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/lmformatenforcer_decoder.html"}
{"id": "7587352bafe9-0", "text": "Source code for langchain_experimental.llms.jsonformer_decoder\n\"\"\"Experimental implementation of jsonformer wrapped LLM.\"\"\"\nfrom __future__ import annotations\nimport json\nfrom typing import TYPE_CHECKING, Any, List, Optional, cast\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.huggingface_pipeline import HuggingFacePipeline\nfrom langchain_experimental.pydantic_v1 import Field, root_validator\nif TYPE_CHECKING:\n    import jsonformer\n[docs]def import_jsonformer() -> jsonformer:\n    \"\"\"Lazily import jsonformer.\"\"\"\n    try:\n        import jsonformer\n    except ImportError:\n        raise ImportError(\n            \"Could not import jsonformer python package. \"\n            \"Please install it with `pip install jsonformer`.\"\n        )\n    return jsonformer\n[docs]class JsonFormer(HuggingFacePipeline):\n    \"\"\"Jsonformer wrapped LLM using HuggingFace Pipeline API.\n    This pipeline is experimental and not yet stable.\n    \"\"\"\n    json_schema: dict = Field(..., description=\"The JSON Schema to complete.\")\n    max_new_tokens: int = Field(\n        default=200, description=\"Maximum number of new tokens to generate.\"\n    )\n    debug: bool = Field(default=False, description=\"Debug mode.\")\n    # TODO: move away from `root_validator` since it is deprecated in pydantic v2\n    #       and causes mypy type-checking failures (hence the `type: ignore`)\n    @root_validator  # type: ignore[call-overload]\n    def check_jsonformer_installation(cls, values: dict) -> dict:\n        import_jsonformer()\n        return values\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/jsonformer_decoder.html"}
{"id": "7587352bafe9-1", "text": "prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        jsonformer = import_jsonformer()\n        from transformers import Text2TextGenerationPipeline\n        pipeline = cast(Text2TextGenerationPipeline, self.pipeline)\n        model = jsonformer.Jsonformer(\n            model=pipeline.model,\n            tokenizer=pipeline.tokenizer,\n            json_schema=self.json_schema,\n            prompt=prompt,\n            max_number_tokens=self.max_new_tokens,\n            debug=self.debug,\n        )\n        text = model()\n        return json.dumps(text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/jsonformer_decoder.html"}
{"id": "0f484fbe579d-0", "text": "Source code for langchain_experimental.llms.rellm_decoder\n\"\"\"Experimental implementation of RELLM wrapped LLM.\"\"\"\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Any, List, Optional, cast\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.huggingface_pipeline import HuggingFacePipeline\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain_experimental.pydantic_v1 import Field, root_validator\nif TYPE_CHECKING:\n    import rellm\n    from regex import Pattern as RegexPattern\nelse:\n    try:\n        from regex import Pattern as RegexPattern\n    except ImportError:\n        pass\n[docs]def import_rellm() -> rellm:\n    \"\"\"Lazily import rellm.\"\"\"\n    try:\n        import rellm\n    except ImportError:\n        raise ImportError(\n            \"Could not import rellm python package. \"\n            \"Please install it with `pip install rellm`.\"\n        )\n    return rellm\n[docs]class RELLM(HuggingFacePipeline):\n    \"\"\"RELLM wrapped LLM using HuggingFace Pipeline API.\"\"\"\n    regex: RegexPattern = Field(..., description=\"The structured format to complete.\")\n    max_new_tokens: int = Field(\n        default=200, description=\"Maximum number of new tokens to generate.\"\n    )\n    # TODO: move away from `root_validator` since it is deprecated in pydantic v2\n    #       and causes mypy type-checking failures (hence the `type: ignore`)\n    @root_validator  # type: ignore[call-overload]\n    def check_rellm_installation(cls, values: dict) -> dict:\n        import_rellm()\n        return values\n    def _call(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/rellm_decoder.html"}
{"id": "0f484fbe579d-1", "text": "import_rellm()\n        return values\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        rellm = import_rellm()\n        from transformers import Text2TextGenerationPipeline\n        pipeline = cast(Text2TextGenerationPipeline, self.pipeline)\n        text = rellm.complete_re(\n            prompt,\n            self.regex,\n            tokenizer=pipeline.tokenizer,\n            model=pipeline.model,\n            max_new_tokens=self.max_new_tokens,\n        )\n        if stop is not None:\n            # This is a bit hacky, but I can't figure out a better way to enforce\n            # stop tokens when making calls to huggingface_hub.\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/rellm_decoder.html"}
{"id": "d11c4beaca92-0", "text": "Source code for langchain_experimental.llms.llamaapi\nimport json\nimport logging\nfrom typing import (\n    Any,\n    Dict,\n    List,\n    Mapping,\n    Optional,\n    Tuple,\n)\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.schema import (\n    ChatGeneration,\n    ChatResult,\n)\nfrom langchain.schema.messages import (\n    AIMessage,\n    BaseMessage,\n    ChatMessage,\n    FunctionMessage,\n    HumanMessage,\n    SystemMessage,\n)\nlogger = logging.getLogger(__name__)\ndef _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:\n    role = _dict[\"role\"]\n    if role == \"user\":\n        return HumanMessage(content=_dict[\"content\"])\n    elif role == \"assistant\":\n        # Fix for azure\n        # Also OpenAI returns None for tool invocations\n        content = _dict.get(\"content\") or \"\"\n        if _dict.get(\"function_call\"):\n            _dict[\"function_call\"][\"arguments\"] = json.dumps(\n                _dict[\"function_call\"][\"arguments\"]\n            )\n            additional_kwargs = {\"function_call\": dict(_dict[\"function_call\"])}\n        else:\n            additional_kwargs = {}\n        return AIMessage(content=content, additional_kwargs=additional_kwargs)\n    elif role == \"system\":\n        return SystemMessage(content=_dict[\"content\"])\n    elif role == \"function\":\n        return FunctionMessage(content=_dict[\"content\"], name=_dict[\"name\"])\n    else:\n        return ChatMessage(content=_dict[\"content\"], role=role)\ndef _convert_message_to_dict(message: BaseMessage) -> dict:\n    if isinstance(message, ChatMessage):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/llamaapi.html"}
{"id": "d11c4beaca92-1", "text": "if isinstance(message, ChatMessage):\n        message_dict = {\"role\": message.role, \"content\": message.content}\n    elif isinstance(message, HumanMessage):\n        message_dict = {\"role\": \"user\", \"content\": message.content}\n    elif isinstance(message, AIMessage):\n        message_dict = {\"role\": \"assistant\", \"content\": message.content}\n        if \"function_call\" in message.additional_kwargs:\n            message_dict[\"function_call\"] = message.additional_kwargs[\"function_call\"]\n    elif isinstance(message, SystemMessage):\n        message_dict = {\"role\": \"system\", \"content\": message.content}\n    elif isinstance(message, FunctionMessage):\n        message_dict = {\n            \"role\": \"function\",\n            \"content\": message.content,\n            \"name\": message.name,\n        }\n    else:\n        raise ValueError(f\"Got unknown type {message}\")\n    if \"name\" in message.additional_kwargs:\n        message_dict[\"name\"] = message.additional_kwargs[\"name\"]\n    return message_dict\n[docs]class ChatLlamaAPI(BaseChatModel):\n    client: Any  #: :meta private:\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        _params = {\"messages\": message_dicts}\n        final_params = {**params, **kwargs, **_params}\n        response = self.client.run(final_params).json()\n        return self._create_chat_result(response)\n    def _create_message_dicts(\n        self, messages: List[BaseMessage], stop: Optional[List[str]]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/llamaapi.html"}
{"id": "d11c4beaca92-2", "text": "self, messages: List[BaseMessage], stop: Optional[List[str]]\n    ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:\n        params = dict(self._client_params)\n        if stop is not None:\n            if \"stop\" in params:\n                raise ValueError(\"`stop` found in both the input and default params.\")\n            params[\"stop\"] = stop\n        message_dicts = [_convert_message_to_dict(m) for m in messages]\n        return message_dicts, params\n    def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:\n        generations = []\n        for res in response[\"choices\"]:\n            message = _convert_dict_to_message(res[\"message\"])\n            gen = ChatGeneration(\n                message=message,\n                generation_info=dict(finish_reason=res.get(\"finish_reason\")),\n            )\n            generations.append(gen)\n        return ChatResult(generations=generations)\n    @property\n    def _client_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the parameters used for the client.\"\"\"\n        return {}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat model.\"\"\"\n        return \"llama-api\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/llamaapi.html"}
{"id": "829b89b373a0-0", "text": "Source code for langchain_experimental.graph_transformers.diffbot\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Union\nimport requests\nfrom langchain.graphs.graph_document import GraphDocument, Node, Relationship\nfrom langchain.schema import Document\nfrom langchain.utils import get_from_env\n[docs]def format_property_key(s: str) -> str:\n    words = s.split()\n    if not words:\n        return s\n    first_word = words[0].lower()\n    capitalized_words = [word.capitalize() for word in words[1:]]\n    return \"\".join([first_word] + capitalized_words)\n[docs]class NodesList:\n    \"\"\"\n    Manages a list of nodes with associated properties.\n    Attributes:\n        nodes (Dict[Tuple, Any]): Stores nodes as keys and their properties as values.\n            Each key is a tuple where the first element is the\n            node ID and the second is the node type.\n    \"\"\"\n[docs]    def __init__(self) -> None:\n        self.nodes: Dict[Tuple[Union[str, int], str], Any] = dict()\n[docs]    def add_node_property(\n        self, node: Tuple[Union[str, int], str], properties: Dict[str, Any]\n    ) -> None:\n        \"\"\"\n        Adds or updates node properties.\n        If the node does not exist in the list, it's added along with its properties.\n        If the node already exists, its properties are updated with the new values.\n        Args:\n            node (Tuple): A tuple containing the node ID and node type.\n            properties (Dict): A dictionary of properties to add or update for the node.\n        \"\"\"\n        if node not in self.nodes:\n            self.nodes[node] = properties\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html"}
{"id": "829b89b373a0-1", "text": "self.nodes[node] = properties\n        else:\n            self.nodes[node].update(properties)\n[docs]    def return_node_list(self) -> List[Node]:\n        \"\"\"\n        Returns the nodes as a list of Node objects.\n        Each Node object will have its ID, type, and properties populated.\n        Returns:\n            List[Node]: A list of Node objects.\n        \"\"\"\n        nodes = [\n            Node(id=key[0], type=key[1], properties=self.nodes[key])\n            for key in self.nodes\n        ]\n        return nodes\n# Properties that should be treated as node properties instead of relationships\nFACT_TO_PROPERTY_TYPE = [\n    \"Date\",\n    \"Number\",\n    \"Job title\",\n    \"Cause of death\",\n    \"Organization type\",\n    \"Academic title\",\n]\nschema_mapping = [\n    (\"HEADQUARTERS\", \"ORGANIZATION_LOCATIONS\"),\n    (\"RESIDENCE\", \"PERSON_LOCATION\"),\n    (\"ALL_PERSON_LOCATIONS\", \"PERSON_LOCATION\"),\n    (\"CHILD\", \"HAS_CHILD\"),\n    (\"PARENT\", \"HAS_PARENT\"),\n    (\"CUSTOMERS\", \"HAS_CUSTOMER\"),\n    (\"SKILLED_AT\", \"INTERESTED_IN\"),\n]\n[docs]class SimplifiedSchema:\n    \"\"\"\n    Provides functionality for working with a simplified schema mapping.\n    Attributes:\n        schema (Dict): A dictionary containing the mapping to simplified schema types.\n    \"\"\"\n[docs]    def __init__(self) -> None:\n        \"\"\"Initializes the schema dictionary based on the predefined list.\"\"\"\n        self.schema = dict()\n        for row in schema_mapping:\n            self.schema[row[0]] = row[1]\n[docs]    def get_type(self, type: str) -> str:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html"}
{"id": "829b89b373a0-2", "text": "[docs]    def get_type(self, type: str) -> str:\n        \"\"\"\n        Retrieves the simplified schema type for a given original type.\n        Args:\n            type (str): The original schema type to find the simplified type for.\n        Returns:\n            str: The simplified schema type if it exists;\n                 otherwise, returns the original type.\n        \"\"\"\n        try:\n            return self.schema[type]\n        except KeyError:\n            return type\n[docs]class DiffbotGraphTransformer:\n    \"\"\"Transforms documents into graph documents using Diffbot's NLP API.\n    A graph document transformation system takes a sequence of Documents and returns a\n    sequence of Graph Documents.\n    Example:\n        .. code-block:: python\n            class DiffbotGraphTransformer(BaseGraphDocumentTransformer):\n                def transform_documents(\n                    self, documents: Sequence[Document], **kwargs: Any\n                ) -> Sequence[GraphDocument]:\n                    results = []\n                    for document in documents:\n                        raw_results = self.nlp_request(document.page_content)\n                        graph_document = self.process_response(raw_results, document)\n                        results.append(graph_document)\n                    return results\n                async def atransform_documents(\n                    self, documents: Sequence[Document], **kwargs: Any\n                ) -> Sequence[Document]:\n                    raise NotImplementedError\n    \"\"\"\n[docs]    def __init__(\n        self,\n        diffbot_api_key: Optional[str] = None,\n        fact_confidence_threshold: float = 0.7,\n        include_qualifiers: bool = True,\n        include_evidence: bool = True,\n        simplified_schema: bool = True,\n    ) -> None:\n        \"\"\"\n        Initialize the graph transformer with various options.\n        Args:\n            diffbot_api_key (str):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html"}
{"id": "829b89b373a0-3", "text": "Args:\n            diffbot_api_key (str):\n               The API key for Diffbot's NLP services.\n            fact_confidence_threshold (float):\n                Minimum confidence level for facts to be included.\n            include_qualifiers (bool):\n                Whether to include qualifiers in the relationships.\n            include_evidence (bool):\n                Whether to include evidence for the relationships.\n            simplified_schema (bool):\n                Whether to use a simplified schema for relationships.\n        \"\"\"\n        self.diffbot_api_key = diffbot_api_key or get_from_env(\n            \"diffbot_api_key\", \"DIFFBOT_API_KEY\"\n        )\n        self.fact_threshold_confidence = fact_confidence_threshold\n        self.include_qualifiers = include_qualifiers\n        self.include_evidence = include_evidence\n        self.simplified_schema = None\n        if simplified_schema:\n            self.simplified_schema = SimplifiedSchema()\n[docs]    def nlp_request(self, text: str) -> Dict[str, Any]:\n        \"\"\"\n        Make an API request to the Diffbot NLP endpoint.\n        Args:\n            text (str): The text to be processed.\n        Returns:\n            Dict[str, Any]: The JSON response from the API.\n        \"\"\"\n        # Relationship extraction only works for English\n        payload = {\n            \"content\": text,\n            \"lang\": \"en\",\n        }\n        FIELDS = \"facts\"\n        HOST = \"nl.diffbot.com\"\n        url = (\n            f\"https://{HOST}/v1/?fields={FIELDS}&\"\n            f\"token={self.diffbot_api_key}&language=en\"\n        )\n        result = requests.post(url, data=payload)\n        return result.json()\n[docs]    def process_response(\n        self, payload: Dict[str, Any], document: Document", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html"}
{"id": "829b89b373a0-4", "text": "self, payload: Dict[str, Any], document: Document\n    ) -> GraphDocument:\n        \"\"\"\n        Transform the Diffbot NLP response into a GraphDocument.\n        Args:\n            payload (Dict[str, Any]): The JSON response from Diffbot's NLP API.\n            document (Document): The original document.\n        Returns:\n            GraphDocument: The transformed document as a graph.\n        \"\"\"\n        # Return empty result if there are no facts\n        if \"facts\" not in payload or not payload[\"facts\"]:\n            return GraphDocument(nodes=[], relationships=[], source=document)\n        # Nodes are a custom class because we need to deduplicate\n        nodes_list = NodesList()\n        # Relationships are a list because we don't deduplicate nor anything else\n        relationships = list()\n        for record in payload[\"facts\"]:\n            # Skip if the fact is below the threshold confidence\n            if record[\"confidence\"] < self.fact_threshold_confidence:\n                continue\n            # TODO: It should probably be treated as a node property\n            if not record[\"value\"][\"allTypes\"]:\n                continue\n            # Define source node\n            source_id = (\n                record[\"entity\"][\"allUris\"][0]\n                if record[\"entity\"][\"allUris\"]\n                else record[\"entity\"][\"name\"]\n            )\n            source_label = record[\"entity\"][\"allTypes\"][0][\"name\"].capitalize()\n            source_name = record[\"entity\"][\"name\"]\n            source_node = Node(id=source_id, type=source_label)\n            nodes_list.add_node_property(\n                (source_id, source_label), {\"name\": source_name}\n            )\n            # Define target node\n            target_id = (\n                record[\"value\"][\"allUris\"][0]\n                if record[\"value\"][\"allUris\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html"}
{"id": "829b89b373a0-5", "text": "if record[\"value\"][\"allUris\"]\n                else record[\"value\"][\"name\"]\n            )\n            target_label = record[\"value\"][\"allTypes\"][0][\"name\"].capitalize()\n            target_name = record[\"value\"][\"name\"]\n            # Some facts are better suited as node properties\n            if target_label in FACT_TO_PROPERTY_TYPE:\n                nodes_list.add_node_property(\n                    (source_id, source_label),\n                    {format_property_key(record[\"property\"][\"name\"]): target_name},\n                )\n            else:  # Define relationship\n                # Define target node object\n                target_node = Node(id=target_id, type=target_label)\n                nodes_list.add_node_property(\n                    (target_id, target_label), {\"name\": target_name}\n                )\n                # Define relationship type\n                rel_type = record[\"property\"][\"name\"].replace(\" \", \"_\").upper()\n                if self.simplified_schema:\n                    rel_type = self.simplified_schema.get_type(rel_type)\n                # Relationship qualifiers/properties\n                rel_properties = dict()\n                relationship_evidence = [el[\"passage\"] for el in record[\"evidence\"]][0]\n                if self.include_evidence:\n                    rel_properties.update({\"evidence\": relationship_evidence})\n                if self.include_qualifiers and record.get(\"qualifiers\"):\n                    for property in record[\"qualifiers\"]:\n                        prop_key = format_property_key(property[\"property\"][\"name\"])\n                        rel_properties[prop_key] = property[\"value\"][\"name\"]\n                relationship = Relationship(\n                    source=source_node,\n                    target=target_node,\n                    type=rel_type,\n                    properties=rel_properties,\n                )\n                relationships.append(relationship)\n        return GraphDocument(\n            nodes=nodes_list.return_node_list(),\n            relationships=relationships,\n            source=document,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html"}
{"id": "829b89b373a0-6", "text": "relationships=relationships,\n            source=document,\n        )\n[docs]    def convert_to_graph_documents(\n        self, documents: Sequence[Document]\n    ) -> List[GraphDocument]:\n        \"\"\"Convert a sequence of documents into graph documents.\n        Args:\n            documents (Sequence[Document]): The original documents.\n            **kwargs: Additional keyword arguments.\n        Returns:\n            Sequence[GraphDocument]: The transformed documents as graphs.\n        \"\"\"\n        results = []\n        for document in documents:\n            raw_results = self.nlp_request(document.page_content)\n            graph_document = self.process_response(raw_results, document)\n            results.append(graph_document)\n        return results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html"}
{"id": "a9cb8bf0c879-0", "text": "Source code for langchain_experimental.generative_agents.generative_agent\nimport re\nfrom datetime import datetime\nfrom typing import Any, Dict, List, Optional, Tuple\nfrom langchain.chains import LLMChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain_experimental.generative_agents.memory import GenerativeAgentMemory\nfrom langchain_experimental.pydantic_v1 import BaseModel, Field\n[docs]class GenerativeAgent(BaseModel):\n    \"\"\"An Agent as a character with memory and innate characteristics.\"\"\"\n    name: str\n    \"\"\"The character's name.\"\"\"\n    age: Optional[int] = None\n    \"\"\"The optional age of the character.\"\"\"\n    traits: str = \"N/A\"\n    \"\"\"Permanent traits to ascribe to the character.\"\"\"\n    status: str\n    \"\"\"The traits of the character you wish not to change.\"\"\"\n    memory: GenerativeAgentMemory\n    \"\"\"The memory object that combines relevance, recency, and 'importance'.\"\"\"\n    llm: BaseLanguageModel\n    \"\"\"The underlying language model.\"\"\"\n    verbose: bool = False\n    summary: str = \"\"  #: :meta private:\n    \"\"\"Stateful self-summary generated via reflection on the character's memory.\"\"\"\n    summary_refresh_seconds: int = 3600  #: :meta private:\n    \"\"\"How frequently to re-generate the summary.\"\"\"\n    last_refreshed: datetime = Field(default_factory=datetime.now)  # : :meta private:\n    \"\"\"The last time the character's summary was regenerated.\"\"\"\n    daily_summaries: List[str] = Field(default_factory=list)  # : :meta private:\n    \"\"\"Summary of the events in the plan that the agent took.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html"}
{"id": "a9cb8bf0c879-1", "text": "\"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    # LLM-related methods\n    @staticmethod\n    def _parse_list(text: str) -> List[str]:\n        \"\"\"Parse a newline-separated string into a list of strings.\"\"\"\n        lines = re.split(r\"\\n\", text.strip())\n        return [re.sub(r\"^\\s*\\d+\\.\\s*\", \"\", line).strip() for line in lines]\n[docs]    def chain(self, prompt: PromptTemplate) -> LLMChain:\n        return LLMChain(\n            llm=self.llm, prompt=prompt, verbose=self.verbose, memory=self.memory\n        )\n    def _get_entity_from_observation(self, observation: str) -> str:\n        prompt = PromptTemplate.from_template(\n            \"What is the observed entity in the following observation? {observation}\"\n            + \"\\nEntity=\"\n        )\n        return self.chain(prompt).run(observation=observation).strip()\n    def _get_entity_action(self, observation: str, entity_name: str) -> str:\n        prompt = PromptTemplate.from_template(\n            \"What is the {entity} doing in the following observation? {observation}\"\n            + \"\\nThe {entity} is\"\n        )\n        return (\n            self.chain(prompt).run(entity=entity_name, observation=observation).strip()\n        )\n[docs]    def summarize_related_memories(self, observation: str) -> str:\n        \"\"\"Summarize memories that are most relevant to an observation.\"\"\"\n        prompt = PromptTemplate.from_template(\n            \"\"\"\n{q1}?\nContext from memory:\n{relevant_memories}\nRelevant context: \n\"\"\"\n        )\n        entity_name = self._get_entity_from_observation(observation)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html"}
{"id": "a9cb8bf0c879-2", "text": "\"\"\"\n        )\n        entity_name = self._get_entity_from_observation(observation)\n        entity_action = self._get_entity_action(observation, entity_name)\n        q1 = f\"What is the relationship between {self.name} and {entity_name}\"\n        q2 = f\"{entity_name} is {entity_action}\"\n        return self.chain(prompt=prompt).run(q1=q1, queries=[q1, q2]).strip()\n    def _generate_reaction(\n        self, observation: str, suffix: str, now: Optional[datetime] = None\n    ) -> str:\n        \"\"\"React to a given observation or dialogue act.\"\"\"\n        prompt = PromptTemplate.from_template(\n            \"{agent_summary_description}\"\n            + \"\\nIt is {current_time}.\"\n            + \"\\n{agent_name}'s status: {agent_status}\"\n            + \"\\nSummary of relevant context from {agent_name}'s memory:\"\n            + \"\\n{relevant_memories}\"\n            + \"\\nMost recent observations: {most_recent_memories}\"\n            + \"\\nObservation: {observation}\"\n            + \"\\n\\n\"\n            + suffix\n        )\n        agent_summary_description = self.get_summary(now=now)\n        relevant_memories_str = self.summarize_related_memories(observation)\n        current_time_str = (\n            datetime.now().strftime(\"%B %d, %Y, %I:%M %p\")\n            if now is None\n            else now.strftime(\"%B %d, %Y, %I:%M %p\")\n        )\n        kwargs: Dict[str, Any] = dict(\n            agent_summary_description=agent_summary_description,\n            current_time=current_time_str,\n            relevant_memories=relevant_memories_str,\n            agent_name=self.name,\n            observation=observation,\n            agent_status=self.status,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html"}
{"id": "a9cb8bf0c879-3", "text": "agent_name=self.name,\n            observation=observation,\n            agent_status=self.status,\n        )\n        consumed_tokens = self.llm.get_num_tokens(\n            prompt.format(most_recent_memories=\"\", **kwargs)\n        )\n        kwargs[self.memory.most_recent_memories_token_key] = consumed_tokens\n        return self.chain(prompt=prompt).run(**kwargs).strip()\n    def _clean_response(self, text: str) -> str:\n        return re.sub(f\"^{self.name} \", \"\", text.strip()).strip()\n[docs]    def generate_reaction(\n        self, observation: str, now: Optional[datetime] = None\n    ) -> Tuple[bool, str]:\n        \"\"\"React to a given observation.\"\"\"\n        call_to_action_template = (\n            \"Should {agent_name} react to the observation, and if so,\"\n            + \" what would be an appropriate reaction? Respond in one line.\"\n            + ' If the action is to engage in dialogue, write:\\nSAY: \"what to say\"'\n            + \"\\notherwise, write:\\nREACT: {agent_name}'s reaction (if anything).\"\n            + \"\\nEither do nothing, react, or say something but not both.\\n\\n\"\n        )\n        full_result = self._generate_reaction(\n            observation, call_to_action_template, now=now\n        )\n        result = full_result.strip().split(\"\\n\")[0]\n        # AAA\n        self.memory.save_context(\n            {},\n            {\n                self.memory.add_memory_key: f\"{self.name} observed \"\n                f\"{observation} and reacted by {result}\",\n                self.memory.now_key: now,\n            },\n        )\n        if \"REACT:\" in result:\n            reaction = self._clean_response(result.split(\"REACT:\")[-1])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html"}
{"id": "a9cb8bf0c879-4", "text": "reaction = self._clean_response(result.split(\"REACT:\")[-1])\n            return False, f\"{self.name} {reaction}\"\n        if \"SAY:\" in result:\n            said_value = self._clean_response(result.split(\"SAY:\")[-1])\n            return True, f\"{self.name} said {said_value}\"\n        else:\n            return False, result\n[docs]    def generate_dialogue_response(\n        self, observation: str, now: Optional[datetime] = None\n    ) -> Tuple[bool, str]:\n        \"\"\"React to a given observation.\"\"\"\n        call_to_action_template = (\n            \"What would {agent_name} say? To end the conversation, write:\"\n            ' GOODBYE: \"what to say\". Otherwise to continue the conversation,'\n            ' write: SAY: \"what to say next\"\\n\\n'\n        )\n        full_result = self._generate_reaction(\n            observation, call_to_action_template, now=now\n        )\n        result = full_result.strip().split(\"\\n\")[0]\n        if \"GOODBYE:\" in result:\n            farewell = self._clean_response(result.split(\"GOODBYE:\")[-1])\n            self.memory.save_context(\n                {},\n                {\n                    self.memory.add_memory_key: f\"{self.name} observed \"\n                    f\"{observation} and said {farewell}\",\n                    self.memory.now_key: now,\n                },\n            )\n            return False, f\"{self.name} said {farewell}\"\n        if \"SAY:\" in result:\n            response_text = self._clean_response(result.split(\"SAY:\")[-1])\n            self.memory.save_context(\n                {},\n                {\n                    self.memory.add_memory_key: f\"{self.name} observed \"\n                    f\"{observation} and said {response_text}\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html"}
{"id": "a9cb8bf0c879-5", "text": "f\"{observation} and said {response_text}\",\n                    self.memory.now_key: now,\n                },\n            )\n            return True, f\"{self.name} said {response_text}\"\n        else:\n            return False, result\n    ######################################################\n    # Agent stateful' summary methods.                   #\n    # Each dialog or response prompt includes a header   #\n    # summarizing the agent's self-description. This is  #\n    # updated periodically through probing its memories  #\n    ######################################################\n    def _compute_agent_summary(self) -> str:\n        \"\"\"\"\"\"\n        prompt = PromptTemplate.from_template(\n            \"How would you summarize {name}'s core characteristics given the\"\n            + \" following statements:\\n\"\n            + \"{relevant_memories}\"\n            + \"Do not embellish.\"\n            + \"\\n\\nSummary: \"\n        )\n        # The agent seeks to think about their core characteristics.\n        return (\n            self.chain(prompt)\n            .run(name=self.name, queries=[f\"{self.name}'s core characteristics\"])\n            .strip()\n        )\n[docs]    def get_summary(\n        self, force_refresh: bool = False, now: Optional[datetime] = None\n    ) -> str:\n        \"\"\"Return a descriptive summary of the agent.\"\"\"\n        current_time = datetime.now() if now is None else now\n        since_refresh = (current_time - self.last_refreshed).seconds\n        if (\n            not self.summary\n            or since_refresh >= self.summary_refresh_seconds\n            or force_refresh\n        ):\n            self.summary = self._compute_agent_summary()\n            self.last_refreshed = current_time\n        age = self.age if self.age is not None else \"N/A\"\n        return (\n            f\"Name: {self.name} (age: {age})\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html"}
{"id": "a9cb8bf0c879-6", "text": "f\"Name: {self.name} (age: {age})\"\n            + f\"\\nInnate traits: {self.traits}\"\n            + f\"\\n{self.summary}\"\n        )\n[docs]    def get_full_header(\n        self, force_refresh: bool = False, now: Optional[datetime] = None\n    ) -> str:\n        \"\"\"Return a full header of the agent's status, summary, and current time.\"\"\"\n        now = datetime.now() if now is None else now\n        summary = self.get_summary(force_refresh=force_refresh, now=now)\n        current_time_str = now.strftime(\"%B %d, %Y, %I:%M %p\")\n        return (\n            f\"{summary}\\nIt is {current_time_str}.\\n{self.name}'s status: {self.status}\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html"}
{"id": "8574bf689f71-0", "text": "Source code for langchain_experimental.generative_agents.memory\nimport logging\nimport re\nfrom datetime import datetime\nfrom typing import Any, Dict, List, Optional\nfrom langchain.chains import LLMChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.retrievers import TimeWeightedVectorStoreRetriever\nfrom langchain.schema import BaseMemory, Document\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.utils import mock_now\nlogger = logging.getLogger(__name__)\n[docs]class GenerativeAgentMemory(BaseMemory):\n    \"\"\"Memory for the generative agent.\"\"\"\n    llm: BaseLanguageModel\n    \"\"\"The core language model.\"\"\"\n    memory_retriever: TimeWeightedVectorStoreRetriever\n    \"\"\"The retriever to fetch related memories.\"\"\"\n    verbose: bool = False\n    reflection_threshold: Optional[float] = None\n    \"\"\"When aggregate_importance exceeds reflection_threshold, stop to reflect.\"\"\"\n    current_plan: List[str] = []\n    \"\"\"The current plan of the agent.\"\"\"\n    # A weight of 0.15 makes this less important than it\n    # would be otherwise, relative to salience and time\n    importance_weight: float = 0.15\n    \"\"\"How much weight to assign the memory importance.\"\"\"\n    aggregate_importance: float = 0.0  # : :meta private:\n    \"\"\"Track the sum of the 'importance' of recent memories.\n    Triggers reflection when it reaches reflection_threshold.\"\"\"\n    max_tokens_limit: int = 1200  # : :meta private:\n    # input keys\n    queries_key: str = \"queries\"\n    most_recent_memories_token_key: str = \"recent_memories_token\"\n    add_memory_key: str = \"add_memory\"\n    # output keys\n    relevant_memories_key: str = \"relevant_memories\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html"}
{"id": "8574bf689f71-1", "text": "# output keys\n    relevant_memories_key: str = \"relevant_memories\"\n    relevant_memories_simple_key: str = \"relevant_memories_simple\"\n    most_recent_memories_key: str = \"most_recent_memories\"\n    now_key: str = \"now\"\n    reflecting: bool = False\n[docs]    def chain(self, prompt: PromptTemplate) -> LLMChain:\n        return LLMChain(llm=self.llm, prompt=prompt, verbose=self.verbose)\n    @staticmethod\n    def _parse_list(text: str) -> List[str]:\n        \"\"\"Parse a newline-separated string into a list of strings.\"\"\"\n        lines = re.split(r\"\\n\", text.strip())\n        lines = [line for line in lines if line.strip()]  # remove empty lines\n        return [re.sub(r\"^\\s*\\d+\\.\\s*\", \"\", line).strip() for line in lines]\n    def _get_topics_of_reflection(self, last_k: int = 50) -> List[str]:\n        \"\"\"Return the 3 most salient high-level questions about recent observations.\"\"\"\n        prompt = PromptTemplate.from_template(\n            \"{observations}\\n\\n\"\n            \"Given only the information above, what are the 3 most salient \"\n            \"high-level questions we can answer about the subjects in the statements?\\n\"\n            \"Provide each question on a new line.\"\n        )\n        observations = self.memory_retriever.memory_stream[-last_k:]\n        observation_str = \"\\n\".join(\n            [self._format_memory_detail(o) for o in observations]\n        )\n        result = self.chain(prompt).run(observations=observation_str)\n        return self._parse_list(result)\n    def _get_insights_on_topic(\n        self, topic: str, now: Optional[datetime] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html"}
{"id": "8574bf689f71-2", "text": "self, topic: str, now: Optional[datetime] = None\n    ) -> List[str]:\n        \"\"\"Generate 'insights' on a topic of reflection, based on pertinent memories.\"\"\"\n        prompt = PromptTemplate.from_template(\n            \"Statements relevant to: '{topic}'\\n\"\n            \"---\\n\"\n            \"{related_statements}\\n\"\n            \"---\\n\"\n            \"What 5 high-level novel insights can you infer from the above statements \"\n            \"that are relevant for answering the following question?\\n\"\n            \"Do not include any insights that are not relevant to the question.\\n\"\n            \"Do not repeat any insights that have already been made.\\n\\n\"\n            \"Question: {topic}\\n\\n\"\n            \"(example format: insight (because of 1, 5, 3))\\n\"\n        )\n        related_memories = self.fetch_memories(topic, now=now)\n        related_statements = \"\\n\".join(\n            [\n                self._format_memory_detail(memory, prefix=f\"{i+1}. \")\n                for i, memory in enumerate(related_memories)\n            ]\n        )\n        result = self.chain(prompt).run(\n            topic=topic, related_statements=related_statements\n        )\n        # TODO: Parse the connections between memories and insights\n        return self._parse_list(result)\n[docs]    def pause_to_reflect(self, now: Optional[datetime] = None) -> List[str]:\n        \"\"\"Reflect on recent observations and generate 'insights'.\"\"\"\n        if self.verbose:\n            logger.info(\"Character is reflecting\")\n        new_insights = []\n        topics = self._get_topics_of_reflection()\n        for topic in topics:\n            insights = self._get_insights_on_topic(topic, now=now)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html"}
{"id": "8574bf689f71-3", "text": "insights = self._get_insights_on_topic(topic, now=now)\n            for insight in insights:\n                self.add_memory(insight, now=now)\n            new_insights.extend(insights)\n        return new_insights\n    def _score_memory_importance(self, memory_content: str) -> float:\n        \"\"\"Score the absolute importance of the given memory.\"\"\"\n        prompt = PromptTemplate.from_template(\n            \"On the scale of 1 to 10, where 1 is purely mundane\"\n            + \" (e.g., brushing teeth, making bed) and 10 is\"\n            + \" extremely poignant (e.g., a break up, college\"\n            + \" acceptance), rate the likely poignancy of the\"\n            + \" following piece of memory. Respond with a single integer.\"\n            + \"\\nMemory: {memory_content}\"\n            + \"\\nRating: \"\n        )\n        score = self.chain(prompt).run(memory_content=memory_content).strip()\n        if self.verbose:\n            logger.info(f\"Importance score: {score}\")\n        match = re.search(r\"^\\D*(\\d+)\", score)\n        if match:\n            return (float(match.group(1)) / 10) * self.importance_weight\n        else:\n            return 0.0\n    def _score_memories_importance(self, memory_content: str) -> List[float]:\n        \"\"\"Score the absolute importance of the given memory.\"\"\"\n        prompt = PromptTemplate.from_template(\n            \"On the scale of 1 to 10, where 1 is purely mundane\"\n            + \" (e.g., brushing teeth, making bed) and 10 is\"\n            + \" extremely poignant (e.g., a break up, college\"\n            + \" acceptance), rate the likely poignancy of the\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html"}
{"id": "8574bf689f71-4", "text": "+ \" acceptance), rate the likely poignancy of the\"\n            + \" following piece of memory. Always answer with only a list of numbers.\"\n            + \" If just given one memory still respond in a list.\"\n            + \" Memories are separated by semi colans (;)\"\n            + \"\\Memories: {memory_content}\"\n            + \"\\nRating: \"\n        )\n        scores = self.chain(prompt).run(memory_content=memory_content).strip()\n        if self.verbose:\n            logger.info(f\"Importance scores: {scores}\")\n        # Split into list of strings and convert to floats\n        scores_list = [float(x) for x in scores.split(\";\")]\n        return scores_list\n[docs]    def add_memories(\n        self, memory_content: str, now: Optional[datetime] = None\n    ) -> List[str]:\n        \"\"\"Add an observations or memories to the agent's memory.\"\"\"\n        importance_scores = self._score_memories_importance(memory_content)\n        self.aggregate_importance += max(importance_scores)\n        memory_list = memory_content.split(\";\")\n        documents = []\n        for i in range(len(memory_list)):\n            documents.append(\n                Document(\n                    page_content=memory_list[i],\n                    metadata={\"importance\": importance_scores[i]},\n                )\n            )\n        result = self.memory_retriever.add_documents(documents, current_time=now)\n        # After an agent has processed a certain amount of memories (as measured by\n        # aggregate importance), it is time to reflect on recent events to add\n        # more synthesized memories to the agent's memory stream.\n        if (\n            self.reflection_threshold is not None\n            and self.aggregate_importance > self.reflection_threshold\n            and not self.reflecting\n        ):\n            self.reflecting = True", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html"}
{"id": "8574bf689f71-5", "text": "and not self.reflecting\n        ):\n            self.reflecting = True\n            self.pause_to_reflect(now=now)\n            # Hack to clear the importance from reflection\n            self.aggregate_importance = 0.0\n            self.reflecting = False\n        return result\n[docs]    def add_memory(\n        self, memory_content: str, now: Optional[datetime] = None\n    ) -> List[str]:\n        \"\"\"Add an observation or memory to the agent's memory.\"\"\"\n        importance_score = self._score_memory_importance(memory_content)\n        self.aggregate_importance += importance_score\n        document = Document(\n            page_content=memory_content, metadata={\"importance\": importance_score}\n        )\n        result = self.memory_retriever.add_documents([document], current_time=now)\n        # After an agent has processed a certain amount of memories (as measured by\n        # aggregate importance), it is time to reflect on recent events to add\n        # more synthesized memories to the agent's memory stream.\n        if (\n            self.reflection_threshold is not None\n            and self.aggregate_importance > self.reflection_threshold\n            and not self.reflecting\n        ):\n            self.reflecting = True\n            self.pause_to_reflect(now=now)\n            # Hack to clear the importance from reflection\n            self.aggregate_importance = 0.0\n            self.reflecting = False\n        return result\n[docs]    def fetch_memories(\n        self, observation: str, now: Optional[datetime] = None\n    ) -> List[Document]:\n        \"\"\"Fetch related memories.\"\"\"\n        if now is not None:\n            with mock_now(now):\n                return self.memory_retriever.get_relevant_documents(observation)\n        else:\n            return self.memory_retriever.get_relevant_documents(observation)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html"}
{"id": "8574bf689f71-6", "text": "else:\n            return self.memory_retriever.get_relevant_documents(observation)\n[docs]    def format_memories_detail(self, relevant_memories: List[Document]) -> str:\n        content = []\n        for mem in relevant_memories:\n            content.append(self._format_memory_detail(mem, prefix=\"- \"))\n        return \"\\n\".join([f\"{mem}\" for mem in content])\n    def _format_memory_detail(self, memory: Document, prefix: str = \"\") -> str:\n        created_time = memory.metadata[\"created_at\"].strftime(\"%B %d, %Y, %I:%M %p\")\n        return f\"{prefix}[{created_time}] {memory.page_content.strip()}\"\n[docs]    def format_memories_simple(self, relevant_memories: List[Document]) -> str:\n        return \"; \".join([f\"{mem.page_content}\" for mem in relevant_memories])\n    def _get_memories_until_limit(self, consumed_tokens: int) -> str:\n        \"\"\"Reduce the number of tokens in the documents.\"\"\"\n        result = []\n        for doc in self.memory_retriever.memory_stream[::-1]:\n            if consumed_tokens >= self.max_tokens_limit:\n                break\n            consumed_tokens += self.llm.get_num_tokens(doc.page_content)\n            if consumed_tokens < self.max_tokens_limit:\n                result.append(doc)\n        return self.format_memories_simple(result)\n    @property\n    def memory_variables(self) -> List[str]:\n        \"\"\"Input keys this memory class will load dynamically.\"\"\"\n        return []\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:\n        \"\"\"Return key-value pairs given the text input to the chain.\"\"\"\n        queries = inputs.get(self.queries_key)\n        now = inputs.get(self.now_key)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html"}
{"id": "8574bf689f71-7", "text": "now = inputs.get(self.now_key)\n        if queries is not None:\n            relevant_memories = [\n                mem for query in queries for mem in self.fetch_memories(query, now=now)\n            ]\n            return {\n                self.relevant_memories_key: self.format_memories_detail(\n                    relevant_memories\n                ),\n                self.relevant_memories_simple_key: self.format_memories_simple(\n                    relevant_memories\n                ),\n            }\n        most_recent_memories_token = inputs.get(self.most_recent_memories_token_key)\n        if most_recent_memories_token is not None:\n            return {\n                self.most_recent_memories_key: self._get_memories_until_limit(\n                    most_recent_memories_token\n                )\n            }\n        return {}\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, Any]) -> None:\n        \"\"\"Save the context of this model run to memory.\"\"\"\n        # TODO: fix the save memory key\n        mem = outputs.get(self.add_memory_key)\n        now = outputs.get(self.now_key)\n        if mem:\n            self.add_memory(mem, now=now)\n[docs]    def clear(self) -> None:\n        \"\"\"Clear memory contents.\"\"\"\n        # TODO", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html"}
{"id": "f0e22500afd4-0", "text": "Source code for langchain.cache\n\"\"\"\n.. warning::\n  Beta Feature!\n**Cache** provides an optional caching layer for LLMs.\nCache is useful for two reasons:\n- It can save you money by reducing the number of API calls you make to the LLM\n  provider if you're often requesting the same completion multiple times.\n- It can speed up your application by reducing the number of API calls you make\n  to the LLM provider.\nCache directly competes with Memory. See documentation for Pros and Cons.\n**Class hierarchy:**\n.. code-block::\n    BaseCache --> <name>Cache  # Examples: InMemoryCache, RedisCache, GPTCache\n\"\"\"\nfrom __future__ import annotations\nimport hashlib\nimport inspect\nimport json\nimport logging\nimport uuid\nimport warnings\nfrom datetime import timedelta\nfrom functools import lru_cache\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    List,\n    Optional,\n    Tuple,\n    Type,\n    Union,\n    cast,\n)\nfrom sqlalchemy import Column, Integer, Row, String, create_engine, select\nfrom sqlalchemy.engine.base import Engine\nfrom sqlalchemy.orm import Session\ntry:\n    from sqlalchemy.orm import declarative_base\nexcept ImportError:\n    from sqlalchemy.ext.declarative import declarative_base\nfrom langchain.llms.base import LLM, get_prompts\nfrom langchain.load.dump import dumps\nfrom langchain.load.load import loads\nfrom langchain.schema import ChatGeneration, Generation\nfrom langchain.schema.cache import RETURN_VAL_TYPE, BaseCache\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_env\nfrom langchain.vectorstores.redis import Redis as RedisVectorstore\nlogger = logging.getLogger(__file__)\nif TYPE_CHECKING:\n    import momento", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-1", "text": "logger = logging.getLogger(__file__)\nif TYPE_CHECKING:\n    import momento\n    from cassandra.cluster import Session as CassandraSession\ndef _hash(_input: str) -> str:\n    \"\"\"Use a deterministic hashing approach.\"\"\"\n    return hashlib.md5(_input.encode()).hexdigest()\ndef _dump_generations_to_json(generations: RETURN_VAL_TYPE) -> str:\n    \"\"\"Dump generations to json.\n    Args:\n        generations (RETURN_VAL_TYPE): A list of language model generations.\n    Returns:\n        str: Json representing a list of generations.\n    Warning: would not work well with arbitrary subclasses of `Generation`\n    \"\"\"\n    return json.dumps([generation.dict() for generation in generations])\ndef _load_generations_from_json(generations_json: str) -> RETURN_VAL_TYPE:\n    \"\"\"Load generations from json.\n    Args:\n        generations_json (str): A string of json representing a list of generations.\n    Raises:\n        ValueError: Could not decode json string to list of generations.\n    Returns:\n        RETURN_VAL_TYPE: A list of generations.\n    Warning: would not work well with arbitrary subclasses of `Generation`\n    \"\"\"\n    try:\n        results = json.loads(generations_json)\n        return [Generation(**generation_dict) for generation_dict in results]\n    except json.JSONDecodeError:\n        raise ValueError(\n            f\"Could not decode json to list of generations: {generations_json}\"\n        )\ndef _dumps_generations(generations: RETURN_VAL_TYPE) -> str:\n    \"\"\"\n    Serialization for generic RETURN_VAL_TYPE, i.e. sequence of `Generation`\n    Args:\n        generations (RETURN_VAL_TYPE): A list of language model generations.\n    Returns:\n        str: a single string representing a list of generations.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-2", "text": "Returns:\n        str: a single string representing a list of generations.\n    This function (+ its counterpart `_loads_generations`) rely on\n    the dumps/loads pair with Reviver, so are able to deal\n    with all subclasses of Generation.\n    Each item in the list can be `dumps`ed to a string,\n    then we make the whole list of strings into a json-dumped.\n    \"\"\"\n    return json.dumps([dumps(_item) for _item in generations])\ndef _loads_generations(generations_str: str) -> Union[RETURN_VAL_TYPE, None]:\n    \"\"\"\n    Deserialization of a string into a generic RETURN_VAL_TYPE\n    (i.e. a sequence of `Generation`).\n    See `_dumps_generations`, the inverse of this function.\n    Args:\n        generations_str (str): A string representing a list of generations.\n    Compatible with the legacy cache-blob format\n    Does not raise exceptions for malformed entries, just logs a warning\n    and returns none: the caller should be prepared for such a cache miss.\n    Returns:\n        RETURN_VAL_TYPE: A list of generations.\n    \"\"\"\n    try:\n        generations = [loads(_item_str) for _item_str in json.loads(generations_str)]\n        return generations\n    except (json.JSONDecodeError, TypeError):\n        # deferring the (soft) handling to after the legacy-format attempt\n        pass\n    try:\n        gen_dicts = json.loads(generations_str)\n        # not relying on `_load_generations_from_json` (which could disappear):\n        generations = [Generation(**generation_dict) for generation_dict in gen_dicts]\n        logger.warning(\n            f\"Legacy 'Generation' cached blob encountered: '{generations_str}'\"\n        )\n        return generations", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-3", "text": ")\n        return generations\n    except (json.JSONDecodeError, TypeError):\n        logger.warning(\n            f\"Malformed/unparsable cached blob encountered: '{generations_str}'\"\n        )\n        return None\n[docs]class InMemoryCache(BaseCache):\n    \"\"\"Cache that stores things in memory.\"\"\"\n[docs]    def __init__(self) -> None:\n        \"\"\"Initialize with empty cache.\"\"\"\n        self._cache: Dict[Tuple[str, str], RETURN_VAL_TYPE] = {}\n[docs]    def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:\n        \"\"\"Look up based on prompt and llm_string.\"\"\"\n        return self._cache.get((prompt, llm_string), None)\n[docs]    def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:\n        \"\"\"Update cache based on prompt and llm_string.\"\"\"\n        self._cache[(prompt, llm_string)] = return_val\n[docs]    def clear(self, **kwargs: Any) -> None:\n        \"\"\"Clear cache.\"\"\"\n        self._cache = {}\nBase = declarative_base()\n[docs]class FullLLMCache(Base):  # type: ignore\n    \"\"\"SQLite table for full LLM Cache (all generations).\"\"\"\n    __tablename__ = \"full_llm_cache\"\n    prompt = Column(String, primary_key=True)\n    llm = Column(String, primary_key=True)\n    idx = Column(Integer, primary_key=True)\n    response = Column(String)\n[docs]class SQLAlchemyCache(BaseCache):\n    \"\"\"Cache that uses SQAlchemy as a backend.\"\"\"\n[docs]    def __init__(self, engine: Engine, cache_schema: Type[FullLLMCache] = FullLLMCache):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-4", "text": "\"\"\"Initialize by creating all tables.\"\"\"\n        self.engine = engine\n        self.cache_schema = cache_schema\n        self.cache_schema.metadata.create_all(self.engine)\n[docs]    def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:\n        \"\"\"Look up based on prompt and llm_string.\"\"\"\n        stmt = (\n            select(self.cache_schema.response)\n            .where(self.cache_schema.prompt == prompt)  # type: ignore\n            .where(self.cache_schema.llm == llm_string)\n            .order_by(self.cache_schema.idx)\n        )\n        with Session(self.engine) as session:\n            rows = session.execute(stmt).fetchall()\n            if rows:\n                try:\n                    return [loads(row[0]) for row in rows]\n                except Exception:\n                    logger.warning(\n                        \"Retrieving a cache value that could not be deserialized \"\n                        \"properly. This is likely due to the cache being in an \"\n                        \"older format. Please recreate your cache to avoid this \"\n                        \"error.\"\n                    )\n                    # In a previous life we stored the raw text directly\n                    # in the table, so assume it's in that format.\n                    return [Generation(text=row[0]) for row in rows]\n        return None\n[docs]    def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:\n        \"\"\"Update based on prompt and llm_string.\"\"\"\n        items = [\n            self.cache_schema(prompt=prompt, llm=llm_string, response=dumps(gen), idx=i)\n            for i, gen in enumerate(return_val)\n        ]\n        with Session(self.engine) as session, session.begin():\n            for item in items:\n                session.merge(item)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-5", "text": "for item in items:\n                session.merge(item)\n[docs]    def clear(self, **kwargs: Any) -> None:\n        \"\"\"Clear cache.\"\"\"\n        with Session(self.engine) as session:\n            session.query(self.cache_schema).delete()\n            session.commit()\n[docs]class SQLiteCache(SQLAlchemyCache):\n    \"\"\"Cache that uses SQLite as a backend.\"\"\"\n[docs]    def __init__(self, database_path: str = \".langchain.db\"):\n        \"\"\"Initialize by creating the engine and all tables.\"\"\"\n        engine = create_engine(f\"sqlite:///{database_path}\")\n        super().__init__(engine)\n[docs]class UpstashRedisCache(BaseCache):\n    \"\"\"Cache that uses Upstash Redis as a backend.\"\"\"\n[docs]    def __init__(self, redis_: Any, *, ttl: Optional[int] = None):\n        \"\"\"\n        Initialize an instance of UpstashRedisCache.\n        This method initializes an object with Upstash Redis caching capabilities.\n        It takes a `redis_` parameter, which should be an instance of an Upstash Redis\n        client class, allowing the object to interact with Upstash Redis\n        server for caching purposes.\n        Parameters:\n            redis_: An instance of Upstash Redis client class\n                (e.g., Redis) used for caching.\n                This allows the object to communicate with\n                Redis server for caching operations on.\n            ttl (int, optional): Time-to-live (TTL) for cached items in seconds.\n                If provided, it sets the time duration for how long cached\n                items will remain valid. If not provided, cached items will not\n                have an automatic expiration.\n        \"\"\"\n        try:\n            from upstash_redis import Redis\n        except ImportError:\n            raise ValueError(\n                \"Could not import upstash_redis python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-6", "text": "raise ValueError(\n                \"Could not import upstash_redis python package. \"\n                \"Please install it with `pip install upstash_redis`.\"\n            )\n        if not isinstance(redis_, Redis):\n            raise ValueError(\"Please pass in Upstash Redis object.\")\n        self.redis = redis_\n        self.ttl = ttl\n    def _key(self, prompt: str, llm_string: str) -> str:\n        \"\"\"Compute key from prompt and llm_string\"\"\"\n        return _hash(prompt + llm_string)\n[docs]    def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:\n        \"\"\"Look up based on prompt and llm_string.\"\"\"\n        generations = []\n        # Read from a HASH\n        results = self.redis.hgetall(self._key(prompt, llm_string))\n        if results:\n            for _, text in results.items():\n                generations.append(Generation(text=text))\n        return generations if generations else None\n[docs]    def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:\n        \"\"\"Update cache based on prompt and llm_string.\"\"\"\n        for gen in return_val:\n            if not isinstance(gen, Generation):\n                raise ValueError(\n                    \"UpstashRedisCache supports caching of normal LLM generations, \"\n                    f\"got {type(gen)}\"\n                )\n            if isinstance(gen, ChatGeneration):\n                warnings.warn(\n                    \"NOTE: Generation has not been cached. UpstashRedisCache does not\"\n                    \" support caching ChatModel outputs.\"\n                )\n                return\n        # Write to a HASH\n        key = self._key(prompt, llm_string)\n        mapping = {\n            str(idx): generation.text for idx, generation in enumerate(return_val)\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-7", "text": "str(idx): generation.text for idx, generation in enumerate(return_val)\n        }\n        self.redis.hset(key=key, values=mapping)\n        if self.ttl is not None:\n            self.redis.expire(key, self.ttl)\n[docs]    def clear(self, **kwargs: Any) -> None:\n        \"\"\"\n        Clear cache. If `asynchronous` is True, flush asynchronously.\n        This flushes the *whole* db.\n        \"\"\"\n        asynchronous = kwargs.get(\"asynchronous\", False)\n        if asynchronous:\n            asynchronous = \"ASYNC\"\n        else:\n            asynchronous = \"SYNC\"\n        self.redis.flushdb(flush_type=asynchronous)\n[docs]class RedisCache(BaseCache):\n    \"\"\"Cache that uses Redis as a backend.\"\"\"\n[docs]    def __init__(self, redis_: Any, *, ttl: Optional[int] = None):\n        \"\"\"\n        Initialize an instance of RedisCache.\n        This method initializes an object with Redis caching capabilities.\n        It takes a `redis_` parameter, which should be an instance of a Redis\n        client class, allowing the object to interact with a Redis\n        server for caching purposes.\n        Parameters:\n            redis_ (Any): An instance of a Redis client class\n                (e.g., redis.Redis) used for caching.\n                This allows the object to communicate with a\n                Redis server for caching operations.\n            ttl (int, optional): Time-to-live (TTL) for cached items in seconds.\n                If provided, it sets the time duration for how long cached\n                items will remain valid. If not provided, cached items will not\n                have an automatic expiration.\n        \"\"\"\n        try:\n            from redis import Redis\n        except ImportError:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-8", "text": "try:\n            from redis import Redis\n        except ImportError:\n            raise ValueError(\n                \"Could not import redis python package. \"\n                \"Please install it with `pip install redis`.\"\n            )\n        if not isinstance(redis_, Redis):\n            raise ValueError(\"Please pass in Redis object.\")\n        self.redis = redis_\n        self.ttl = ttl\n    def _key(self, prompt: str, llm_string: str) -> str:\n        \"\"\"Compute key from prompt and llm_string\"\"\"\n        return _hash(prompt + llm_string)\n[docs]    def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:\n        \"\"\"Look up based on prompt and llm_string.\"\"\"\n        generations = []\n        # Read from a Redis HASH\n        results = self.redis.hgetall(self._key(prompt, llm_string))\n        if results:\n            for _, text in results.items():\n                try:\n                    generations.append(loads(text))\n                except Exception:\n                    logger.warning(\n                        \"Retrieving a cache value that could not be deserialized \"\n                        \"properly. This is likely due to the cache being in an \"\n                        \"older format. Please recreate your cache to avoid this \"\n                        \"error.\"\n                    )\n                    # In a previous life we stored the raw text directly\n                    # in the table, so assume it's in that format.\n                    generations.append(Generation(text=text))\n        return generations if generations else None\n[docs]    def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:\n        \"\"\"Update cache based on prompt and llm_string.\"\"\"\n        for gen in return_val:\n            if not isinstance(gen, Generation):\n                raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-9", "text": "if not isinstance(gen, Generation):\n                raise ValueError(\n                    \"RedisCache only supports caching of normal LLM generations, \"\n                    f\"got {type(gen)}\"\n                )\n        # Write to a Redis HASH\n        key = self._key(prompt, llm_string)\n        with self.redis.pipeline() as pipe:\n            pipe.hset(\n                key,\n                mapping={\n                    str(idx): dumps(generation)\n                    for idx, generation in enumerate(return_val)\n                },\n            )\n            if self.ttl is not None:\n                pipe.expire(key, self.ttl)\n            pipe.execute()\n[docs]    def clear(self, **kwargs: Any) -> None:\n        \"\"\"Clear cache. If `asynchronous` is True, flush asynchronously.\"\"\"\n        asynchronous = kwargs.get(\"asynchronous\", False)\n        self.redis.flushdb(asynchronous=asynchronous, **kwargs)\n[docs]class RedisSemanticCache(BaseCache):\n    \"\"\"Cache that uses Redis as a vector-store backend.\"\"\"\n    # TODO - implement a TTL policy in Redis\n    DEFAULT_SCHEMA = {\n        \"content_key\": \"prompt\",\n        \"text\": [\n            {\"name\": \"prompt\"},\n        ],\n        \"extra\": [{\"name\": \"return_val\"}, {\"name\": \"llm_string\"}],\n    }\n[docs]    def __init__(\n        self, redis_url: str, embedding: Embeddings, score_threshold: float = 0.2\n    ):\n        \"\"\"Initialize by passing in the `init` GPTCache func\n        Args:\n            redis_url (str): URL to connect to Redis.\n            embedding (Embedding): Embedding provider for semantic encoding and search.\n            score_threshold (float, 0.2):\n        Example:\n        .. code-block:: python", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-10", "text": "Example:\n        .. code-block:: python\n            from langchain.globals import set_llm_cache\n            from langchain.cache import RedisSemanticCache\n            from langchain.embeddings import OpenAIEmbeddings\n            set_llm_cache(RedisSemanticCache(\n                redis_url=\"redis://localhost:6379\",\n                embedding=OpenAIEmbeddings()\n            ))\n        \"\"\"\n        self._cache_dict: Dict[str, RedisVectorstore] = {}\n        self.redis_url = redis_url\n        self.embedding = embedding\n        self.score_threshold = score_threshold\n    def _index_name(self, llm_string: str) -> str:\n        hashed_index = _hash(llm_string)\n        return f\"cache:{hashed_index}\"\n    def _get_llm_cache(self, llm_string: str) -> RedisVectorstore:\n        index_name = self._index_name(llm_string)\n        # return vectorstore client for the specific llm string\n        if index_name in self._cache_dict:\n            return self._cache_dict[index_name]\n        # create new vectorstore client for the specific llm string\n        try:\n            self._cache_dict[index_name] = RedisVectorstore.from_existing_index(\n                embedding=self.embedding,\n                index_name=index_name,\n                redis_url=self.redis_url,\n                schema=cast(Dict, self.DEFAULT_SCHEMA),\n            )\n        except ValueError:\n            redis = RedisVectorstore(\n                embedding=self.embedding,\n                index_name=index_name,\n                redis_url=self.redis_url,\n                index_schema=cast(Dict, self.DEFAULT_SCHEMA),\n            )\n            _embedding = self.embedding.embed_query(text=\"test\")\n            redis._create_index_if_not_exist(dim=len(_embedding))\n            self._cache_dict[index_name] = redis\n        return self._cache_dict[index_name]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-11", "text": "return self._cache_dict[index_name]\n[docs]    def clear(self, **kwargs: Any) -> None:\n        \"\"\"Clear semantic cache for a given llm_string.\"\"\"\n        index_name = self._index_name(kwargs[\"llm_string\"])\n        if index_name in self._cache_dict:\n            self._cache_dict[index_name].drop_index(\n                index_name=index_name, delete_documents=True, redis_url=self.redis_url\n            )\n            del self._cache_dict[index_name]\n[docs]    def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:\n        \"\"\"Look up based on prompt and llm_string.\"\"\"\n        llm_cache = self._get_llm_cache(llm_string)\n        generations: List = []\n        # Read from a Hash\n        results = llm_cache.similarity_search(\n            query=prompt,\n            k=1,\n            distance_threshold=self.score_threshold,\n        )\n        if results:\n            for document in results:\n                try:\n                    generations.extend(loads(document.metadata[\"return_val\"]))\n                except Exception:\n                    logger.warning(\n                        \"Retrieving a cache value that could not be deserialized \"\n                        \"properly. This is likely due to the cache being in an \"\n                        \"older format. Please recreate your cache to avoid this \"\n                        \"error.\"\n                    )\n                    # In a previous life we stored the raw text directly\n                    # in the table, so assume it's in that format.\n                    generations.extend(\n                        _load_generations_from_json(document.metadata[\"return_val\"])\n                    )\n        return generations if generations else None\n[docs]    def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-12", "text": "\"\"\"Update cache based on prompt and llm_string.\"\"\"\n        for gen in return_val:\n            if not isinstance(gen, Generation):\n                raise ValueError(\n                    \"RedisSemanticCache only supports caching of \"\n                    f\"normal LLM generations, got {type(gen)}\"\n                )\n        llm_cache = self._get_llm_cache(llm_string)\n        metadata = {\n            \"llm_string\": llm_string,\n            \"prompt\": prompt,\n            \"return_val\": dumps([g for g in return_val]),\n        }\n        llm_cache.add_texts(texts=[prompt], metadatas=[metadata])\n[docs]class GPTCache(BaseCache):\n    \"\"\"Cache that uses GPTCache as a backend.\"\"\"\n[docs]    def __init__(\n        self,\n        init_func: Union[\n            Callable[[Any, str], None], Callable[[Any], None], None\n        ] = None,\n    ):\n        \"\"\"Initialize by passing in init function (default: `None`).\n        Args:\n            init_func (Optional[Callable[[Any], None]]): init `GPTCache` function\n            (default: `None`)\n        Example:\n        .. code-block:: python\n            # Initialize GPTCache with a custom init function\n            import gptcache\n            from gptcache.processor.pre import get_prompt\n            from gptcache.manager.factory import get_data_manager\n            from langchain.globals import set_llm_cache\n            # Avoid multiple caches using the same file,\n            causing different llm model caches to affect each other\n            def init_gptcache(cache_obj: gptcache.Cache, llm str):\n                cache_obj.init(\n                    pre_embedding_func=get_prompt,\n                    data_manager=manager_factory(\n                        manager=\"map\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-13", "text": "data_manager=manager_factory(\n                        manager=\"map\",\n                        data_dir=f\"map_cache_{llm}\"\n                    ),\n                )\n            set_llm_cache(GPTCache(init_gptcache))\n        \"\"\"\n        try:\n            import gptcache  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"Could not import gptcache python package. \"\n                \"Please install it with `pip install gptcache`.\"\n            )\n        self.init_gptcache_func: Union[\n            Callable[[Any, str], None], Callable[[Any], None], None\n        ] = init_func\n        self.gptcache_dict: Dict[str, Any] = {}\n    def _new_gptcache(self, llm_string: str) -> Any:\n        \"\"\"New gptcache object\"\"\"\n        from gptcache import Cache\n        from gptcache.manager.factory import get_data_manager\n        from gptcache.processor.pre import get_prompt\n        _gptcache = Cache()\n        if self.init_gptcache_func is not None:\n            sig = inspect.signature(self.init_gptcache_func)\n            if len(sig.parameters) == 2:\n                self.init_gptcache_func(_gptcache, llm_string)  # type: ignore[call-arg]\n            else:\n                self.init_gptcache_func(_gptcache)  # type: ignore[call-arg]\n        else:\n            _gptcache.init(\n                pre_embedding_func=get_prompt,\n                data_manager=get_data_manager(data_path=llm_string),\n            )\n        self.gptcache_dict[llm_string] = _gptcache\n        return _gptcache\n    def _get_gptcache(self, llm_string: str) -> Any:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-14", "text": "def _get_gptcache(self, llm_string: str) -> Any:\n        \"\"\"Get a cache object.\n        When the corresponding llm model cache does not exist, it will be created.\"\"\"\n        _gptcache = self.gptcache_dict.get(llm_string, None)\n        if not _gptcache:\n            _gptcache = self._new_gptcache(llm_string)\n        return _gptcache\n[docs]    def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:\n        \"\"\"Look up the cache data.\n        First, retrieve the corresponding cache object using the `llm_string` parameter,\n        and then retrieve the data from the cache based on the `prompt`.\n        \"\"\"\n        from gptcache.adapter.api import get\n        _gptcache = self._get_gptcache(llm_string)\n        res = get(prompt, cache_obj=_gptcache)\n        if res:\n            return [\n                Generation(**generation_dict) for generation_dict in json.loads(res)\n            ]\n        return None\n[docs]    def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:\n        \"\"\"Update cache.\n        First, retrieve the corresponding cache object using the `llm_string` parameter,\n        and then store the `prompt` and `return_val` in the cache object.\n        \"\"\"\n        for gen in return_val:\n            if not isinstance(gen, Generation):\n                raise ValueError(\n                    \"GPTCache only supports caching of normal LLM generations, \"\n                    f\"got {type(gen)}\"\n                )\n        from gptcache.adapter.api import put\n        _gptcache = self._get_gptcache(llm_string)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-15", "text": "_gptcache = self._get_gptcache(llm_string)\n        handled_data = json.dumps([generation.dict() for generation in return_val])\n        put(prompt, handled_data, cache_obj=_gptcache)\n        return None\n[docs]    def clear(self, **kwargs: Any) -> None:\n        \"\"\"Clear cache.\"\"\"\n        from gptcache import Cache\n        for gptcache_instance in self.gptcache_dict.values():\n            gptcache_instance = cast(Cache, gptcache_instance)\n            gptcache_instance.flush()\n        self.gptcache_dict.clear()\ndef _ensure_cache_exists(cache_client: momento.CacheClient, cache_name: str) -> None:\n    \"\"\"Create cache if it doesn't exist.\n    Raises:\n        SdkException: Momento service or network error\n        Exception: Unexpected response\n    \"\"\"\n    from momento.responses import CreateCache\n    create_cache_response = cache_client.create_cache(cache_name)\n    if isinstance(create_cache_response, CreateCache.Success) or isinstance(\n        create_cache_response, CreateCache.CacheAlreadyExists\n    ):\n        return None\n    elif isinstance(create_cache_response, CreateCache.Error):\n        raise create_cache_response.inner_exception\n    else:\n        raise Exception(f\"Unexpected response cache creation: {create_cache_response}\")\ndef _validate_ttl(ttl: Optional[timedelta]) -> None:\n    if ttl is not None and ttl <= timedelta(seconds=0):\n        raise ValueError(f\"ttl must be positive but was {ttl}.\")\n[docs]class MomentoCache(BaseCache):\n    \"\"\"Cache that uses Momento as a backend. See https://gomomento.com/\"\"\"\n[docs]    def __init__(\n        self,\n        cache_client: momento.CacheClient,\n        cache_name: str,\n        *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-16", "text": "cache_client: momento.CacheClient,\n        cache_name: str,\n        *,\n        ttl: Optional[timedelta] = None,\n        ensure_cache_exists: bool = True,\n    ):\n        \"\"\"Instantiate a prompt cache using Momento as a backend.\n        Note: to instantiate the cache client passed to MomentoCache,\n        you must have a Momento account. See https://gomomento.com/.\n        Args:\n            cache_client (CacheClient): The Momento cache client.\n            cache_name (str): The name of the cache to use to store the data.\n            ttl (Optional[timedelta], optional): The time to live for the cache items.\n                Defaults to None, ie use the client default TTL.\n            ensure_cache_exists (bool, optional): Create the cache if it doesn't\n                exist. Defaults to True.\n        Raises:\n            ImportError: Momento python package is not installed.\n            TypeError: cache_client is not of type momento.CacheClientObject\n            ValueError: ttl is non-null and non-negative\n        \"\"\"\n        try:\n            from momento import CacheClient\n        except ImportError:\n            raise ImportError(\n                \"Could not import momento python package. \"\n                \"Please install it with `pip install momento`.\"\n            )\n        if not isinstance(cache_client, CacheClient):\n            raise TypeError(\"cache_client must be a momento.CacheClient object.\")\n        _validate_ttl(ttl)\n        if ensure_cache_exists:\n            _ensure_cache_exists(cache_client, cache_name)\n        self.cache_client = cache_client\n        self.cache_name = cache_name\n        self.ttl = ttl\n[docs]    @classmethod\n    def from_client_params(\n        cls,\n        cache_name: str,\n        ttl: timedelta,\n        *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-17", "text": "cls,\n        cache_name: str,\n        ttl: timedelta,\n        *,\n        configuration: Optional[momento.config.Configuration] = None,\n        api_key: Optional[str] = None,\n        auth_token: Optional[str] = None,  # for backwards compatibility\n        **kwargs: Any,\n    ) -> MomentoCache:\n        \"\"\"Construct cache from CacheClient parameters.\"\"\"\n        try:\n            from momento import CacheClient, Configurations, CredentialProvider\n        except ImportError:\n            raise ImportError(\n                \"Could not import momento python package. \"\n                \"Please install it with `pip install momento`.\"\n            )\n        if configuration is None:\n            configuration = Configurations.Laptop.v1()\n        # Try checking `MOMENTO_AUTH_TOKEN` first for backwards compatibility\n        try:\n            api_key = auth_token or get_from_env(\"auth_token\", \"MOMENTO_AUTH_TOKEN\")\n        except ValueError:\n            api_key = api_key or get_from_env(\"api_key\", \"MOMENTO_API_KEY\")\n        credentials = CredentialProvider.from_string(api_key)\n        cache_client = CacheClient(configuration, credentials, default_ttl=ttl)\n        return cls(cache_client, cache_name, ttl=ttl, **kwargs)\n    def __key(self, prompt: str, llm_string: str) -> str:\n        \"\"\"Compute cache key from prompt and associated model and settings.\n        Args:\n            prompt (str): The prompt run through the language model.\n            llm_string (str): The language model version and settings.\n        Returns:\n            str: The cache key.\n        \"\"\"\n        return _hash(prompt + llm_string)\n[docs]    def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-18", "text": "\"\"\"Lookup llm generations in cache by prompt and associated model and settings.\n        Args:\n            prompt (str): The prompt run through the language model.\n            llm_string (str): The language model version and settings.\n        Raises:\n            SdkException: Momento service or network error\n        Returns:\n            Optional[RETURN_VAL_TYPE]: A list of language model generations.\n        \"\"\"\n        from momento.responses import CacheGet\n        generations: RETURN_VAL_TYPE = []\n        get_response = self.cache_client.get(\n            self.cache_name, self.__key(prompt, llm_string)\n        )\n        if isinstance(get_response, CacheGet.Hit):\n            value = get_response.value_string\n            generations = _load_generations_from_json(value)\n        elif isinstance(get_response, CacheGet.Miss):\n            pass\n        elif isinstance(get_response, CacheGet.Error):\n            raise get_response.inner_exception\n        return generations if generations else None\n[docs]    def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:\n        \"\"\"Store llm generations in cache.\n        Args:\n            prompt (str): The prompt run through the language model.\n            llm_string (str): The language model string.\n            return_val (RETURN_VAL_TYPE): A list of language model generations.\n        Raises:\n            SdkException: Momento service or network error\n            Exception: Unexpected response\n        \"\"\"\n        for gen in return_val:\n            if not isinstance(gen, Generation):\n                raise ValueError(\n                    \"Momento only supports caching of normal LLM generations, \"\n                    f\"got {type(gen)}\"\n                )\n        key = self.__key(prompt, llm_string)\n        value = _dump_generations_to_json(return_val)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-19", "text": "value = _dump_generations_to_json(return_val)\n        set_response = self.cache_client.set(self.cache_name, key, value, self.ttl)\n        from momento.responses import CacheSet\n        if isinstance(set_response, CacheSet.Success):\n            pass\n        elif isinstance(set_response, CacheSet.Error):\n            raise set_response.inner_exception\n        else:\n            raise Exception(f\"Unexpected response: {set_response}\")\n[docs]    def clear(self, **kwargs: Any) -> None:\n        \"\"\"Clear the cache.\n        Raises:\n            SdkException: Momento service or network error\n        \"\"\"\n        from momento.responses import CacheFlush\n        flush_response = self.cache_client.flush_cache(self.cache_name)\n        if isinstance(flush_response, CacheFlush.Success):\n            pass\n        elif isinstance(flush_response, CacheFlush.Error):\n            raise flush_response.inner_exception\nCASSANDRA_CACHE_DEFAULT_TABLE_NAME = \"langchain_llm_cache\"\nCASSANDRA_CACHE_DEFAULT_TTL_SECONDS = None\n[docs]class CassandraCache(BaseCache):\n    \"\"\"\n    Cache that uses Cassandra / Astra DB as a backend.\n    It uses a single Cassandra table.\n    The lookup keys (which get to form the primary key) are:\n        - prompt, a string\n        - llm_string, a deterministic str representation of the model parameters.\n          (needed to prevent collisions same-prompt-different-model collisions)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        session: Optional[CassandraSession] = None,\n        keyspace: Optional[str] = None,\n        table_name: str = CASSANDRA_CACHE_DEFAULT_TABLE_NAME,\n        ttl_seconds: Optional[int] = CASSANDRA_CACHE_DEFAULT_TTL_SECONDS,\n        skip_provisioning: bool = False,\n    ):\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-20", "text": "skip_provisioning: bool = False,\n    ):\n        \"\"\"\n        Initialize with a ready session and a keyspace name.\n        Args:\n            session (cassandra.cluster.Session): an open Cassandra session\n            keyspace (str): the keyspace to use for storing the cache\n            table_name (str): name of the Cassandra table to use as cache\n            ttl_seconds (optional int): time-to-live for cache entries\n                (default: None, i.e. forever)\n        \"\"\"\n        try:\n            from cassio.table import ElasticCassandraTable\n        except (ImportError, ModuleNotFoundError):\n            raise ValueError(\n                \"Could not import cassio python package. \"\n                \"Please install it with `pip install cassio`.\"\n            )\n        self.session = session\n        self.keyspace = keyspace\n        self.table_name = table_name\n        self.ttl_seconds = ttl_seconds\n        self.kv_cache = ElasticCassandraTable(\n            session=self.session,\n            keyspace=self.keyspace,\n            table=self.table_name,\n            keys=[\"llm_string\", \"prompt\"],\n            primary_key_type=[\"TEXT\", \"TEXT\"],\n            ttl_seconds=self.ttl_seconds,\n            skip_provisioning=skip_provisioning,\n        )\n[docs]    def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:\n        \"\"\"Look up based on prompt and llm_string.\"\"\"\n        item = self.kv_cache.get(\n            llm_string=_hash(llm_string),\n            prompt=_hash(prompt),\n        )\n        if item is not None:\n            generations = _loads_generations(item[\"body_blob\"])\n            # this protects against malformed cached items:\n            if generations is not None:\n                return generations\n            else:\n                return None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-21", "text": "if generations is not None:\n                return generations\n            else:\n                return None\n        else:\n            return None\n[docs]    def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:\n        \"\"\"Update cache based on prompt and llm_string.\"\"\"\n        blob = _dumps_generations(return_val)\n        self.kv_cache.put(\n            llm_string=_hash(llm_string),\n            prompt=_hash(prompt),\n            body_blob=blob,\n        )\n[docs]    def delete_through_llm(\n        self, prompt: str, llm: LLM, stop: Optional[List[str]] = None\n    ) -> None:\n        \"\"\"\n        A wrapper around `delete` with the LLM being passed.\n        In case the llm(prompt) calls have a `stop` param, you should pass it here\n        \"\"\"\n        llm_string = get_prompts(\n            {**llm.dict(), **{\"stop\": stop}},\n            [],\n        )[1]\n        return self.delete(prompt, llm_string=llm_string)\n[docs]    def delete(self, prompt: str, llm_string: str) -> None:\n        \"\"\"Evict from cache if there's an entry.\"\"\"\n        return self.kv_cache.delete(\n            llm_string=_hash(llm_string),\n            prompt=_hash(prompt),\n        )\n[docs]    def clear(self, **kwargs: Any) -> None:\n        \"\"\"Clear cache. This is for all LLMs at once.\"\"\"\n        self.kv_cache.clear()\nCASSANDRA_SEMANTIC_CACHE_DEFAULT_DISTANCE_METRIC = \"dot\"\nCASSANDRA_SEMANTIC_CACHE_DEFAULT_SCORE_THRESHOLD = 0.85", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-22", "text": "CASSANDRA_SEMANTIC_CACHE_DEFAULT_SCORE_THRESHOLD = 0.85\nCASSANDRA_SEMANTIC_CACHE_DEFAULT_TABLE_NAME = \"langchain_llm_semantic_cache\"\nCASSANDRA_SEMANTIC_CACHE_DEFAULT_TTL_SECONDS = None\nCASSANDRA_SEMANTIC_CACHE_EMBEDDING_CACHE_SIZE = 16\n[docs]class CassandraSemanticCache(BaseCache):\n    \"\"\"\n    Cache that uses Cassandra as a vector-store backend for semantic\n    (i.e. similarity-based) lookup.\n    It uses a single (vector) Cassandra table and stores, in principle,\n    cached values from several LLMs, so the LLM's llm_string is part\n    of the rows' primary keys.\n    The similarity is based on one of several distance metrics (default: \"dot\").\n    If choosing another metric, the default threshold is to be re-tuned accordingly.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        session: Optional[CassandraSession],\n        keyspace: Optional[str],\n        embedding: Embeddings,\n        table_name: str = CASSANDRA_SEMANTIC_CACHE_DEFAULT_TABLE_NAME,\n        distance_metric: str = CASSANDRA_SEMANTIC_CACHE_DEFAULT_DISTANCE_METRIC,\n        score_threshold: float = CASSANDRA_SEMANTIC_CACHE_DEFAULT_SCORE_THRESHOLD,\n        ttl_seconds: Optional[int] = CASSANDRA_SEMANTIC_CACHE_DEFAULT_TTL_SECONDS,\n        skip_provisioning: bool = False,\n    ):\n        \"\"\"\n        Initialize the cache with all relevant parameters.\n        Args:\n            session (cassandra.cluster.Session): an open Cassandra session\n            keyspace (str): the keyspace to use for storing the cache\n            embedding (Embedding): Embedding provider for semantic\n                encoding and search.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-23", "text": "embedding (Embedding): Embedding provider for semantic\n                encoding and search.\n            table_name (str): name of the Cassandra (vector) table\n                to use as cache\n            distance_metric (str, 'dot'): which measure to adopt for\n                similarity searches\n            score_threshold (optional float): numeric value to use as\n                cutoff for the similarity searches\n            ttl_seconds (optional int): time-to-live for cache entries\n                (default: None, i.e. forever)\n        The default score threshold is tuned to the default metric.\n        Tune it carefully yourself if switching to another distance metric.\n        \"\"\"\n        try:\n            from cassio.table import MetadataVectorCassandraTable\n        except (ImportError, ModuleNotFoundError):\n            raise ValueError(\n                \"Could not import cassio python package. \"\n                \"Please install it with `pip install cassio`.\"\n            )\n        self.session = session\n        self.keyspace = keyspace\n        self.embedding = embedding\n        self.table_name = table_name\n        self.distance_metric = distance_metric\n        self.score_threshold = score_threshold\n        self.ttl_seconds = ttl_seconds\n        # The contract for this class has separate lookup and update:\n        # in order to spare some embedding calculations we cache them between\n        # the two calls.\n        # Note: each instance of this class has its own `_get_embedding` with\n        # its own lru.\n        @lru_cache(maxsize=CASSANDRA_SEMANTIC_CACHE_EMBEDDING_CACHE_SIZE)\n        def _cache_embedding(text: str) -> List[float]:\n            return self.embedding.embed_query(text=text)\n        self._get_embedding = _cache_embedding\n        self.embedding_dimension = self._get_embedding_dimension()\n        self.table = MetadataVectorCassandraTable(\n            session=self.session,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-24", "text": "self.table = MetadataVectorCassandraTable(\n            session=self.session,\n            keyspace=self.keyspace,\n            table=self.table_name,\n            primary_key_type=[\"TEXT\"],\n            vector_dimension=self.embedding_dimension,\n            ttl_seconds=self.ttl_seconds,\n            metadata_indexing=(\"allow\", {\"_llm_string_hash\"}),\n            skip_provisioning=skip_provisioning,\n        )\n    def _get_embedding_dimension(self) -> int:\n        return len(self._get_embedding(text=\"This is a sample sentence.\"))\n[docs]    def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:\n        \"\"\"Update cache based on prompt and llm_string.\"\"\"\n        embedding_vector = self._get_embedding(text=prompt)\n        llm_string_hash = _hash(llm_string)\n        body = _dumps_generations(return_val)\n        metadata = {\n            \"_prompt\": prompt,\n            \"_llm_string_hash\": llm_string_hash,\n        }\n        row_id = f\"{_hash(prompt)}-{llm_string_hash}\"\n        #\n        self.table.put(\n            body_blob=body,\n            vector=embedding_vector,\n            row_id=row_id,\n            metadata=metadata,\n        )\n[docs]    def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:\n        \"\"\"Look up based on prompt and llm_string.\"\"\"\n        hit_with_id = self.lookup_with_id(prompt, llm_string)\n        if hit_with_id is not None:\n            return hit_with_id[1]\n        else:\n            return None\n[docs]    def lookup_with_id(\n        self, prompt: str, llm_string: str\n    ) -> Optional[Tuple[str, RETURN_VAL_TYPE]]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-25", "text": ") -> Optional[Tuple[str, RETURN_VAL_TYPE]]:\n        \"\"\"\n        Look up based on prompt and llm_string.\n        If there are hits, return (document_id, cached_entry)\n        \"\"\"\n        prompt_embedding: List[float] = self._get_embedding(text=prompt)\n        hits = list(\n            self.table.metric_ann_search(\n                vector=prompt_embedding,\n                metadata={\"_llm_string_hash\": _hash(llm_string)},\n                n=1,\n                metric=self.distance_metric,\n                metric_threshold=self.score_threshold,\n            )\n        )\n        if hits:\n            hit = hits[0]\n            generations = _loads_generations(hit[\"body_blob\"])\n            if generations is not None:\n                # this protects against malformed cached items:\n                return (\n                    hit[\"row_id\"],\n                    generations,\n                )\n            else:\n                return None\n        else:\n            return None\n[docs]    def lookup_with_id_through_llm(\n        self, prompt: str, llm: LLM, stop: Optional[List[str]] = None\n    ) -> Optional[Tuple[str, RETURN_VAL_TYPE]]:\n        llm_string = get_prompts(\n            {**llm.dict(), **{\"stop\": stop}},\n            [],\n        )[1]\n        return self.lookup_with_id(prompt, llm_string=llm_string)\n[docs]    def delete_by_document_id(self, document_id: str) -> None:\n        \"\"\"\n        Given this is a \"similarity search\" cache, an invalidation pattern\n        that makes sense is first a lookup to get an ID, and then deleting\n        with that ID. This is for the second step.\n        \"\"\"\n        self.table.delete(row_id=document_id)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-26", "text": "\"\"\"\n        self.table.delete(row_id=document_id)\n[docs]    def clear(self, **kwargs: Any) -> None:\n        \"\"\"Clear the *whole* semantic cache.\"\"\"\n        self.table.clear()\n[docs]class FullMd5LLMCache(Base):  # type: ignore\n    \"\"\"SQLite table for full LLM Cache (all generations).\"\"\"\n    __tablename__ = \"full_md5_llm_cache\"\n    id = Column(String, primary_key=True)\n    prompt_md5 = Column(String, index=True)\n    llm = Column(String, index=True)\n    idx = Column(Integer, index=True)\n    prompt = Column(String)\n    response = Column(String)\n[docs]class SQLAlchemyMd5Cache(BaseCache):\n    \"\"\"Cache that uses SQAlchemy as a backend.\"\"\"\n[docs]    def __init__(\n        self, engine: Engine, cache_schema: Type[FullMd5LLMCache] = FullMd5LLMCache\n    ):\n        \"\"\"Initialize by creating all tables.\"\"\"\n        self.engine = engine\n        self.cache_schema = cache_schema\n        self.cache_schema.metadata.create_all(self.engine)\n[docs]    def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:\n        \"\"\"Look up based on prompt and llm_string.\"\"\"\n        rows = self._search_rows(prompt, llm_string)\n        if rows:\n            return [loads(row[0]) for row in rows]\n        return None\n[docs]    def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:\n        \"\"\"Update based on prompt and llm_string.\"\"\"\n        self._delete_previous(prompt, llm_string)\n        prompt_md5 = self.get_md5(prompt)\n        items = [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-27", "text": "prompt_md5 = self.get_md5(prompt)\n        items = [\n            self.cache_schema(\n                id=str(uuid.uuid1()),\n                prompt=prompt,\n                prompt_md5=prompt_md5,\n                llm=llm_string,\n                response=dumps(gen),\n                idx=i,\n            )\n            for i, gen in enumerate(return_val)\n        ]\n        with Session(self.engine) as session, session.begin():\n            for item in items:\n                session.merge(item)\n    def _delete_previous(self, prompt: str, llm_string: str) -> None:\n        stmt = (\n            select(self.cache_schema.response)\n            .where(self.cache_schema.prompt_md5 == self.get_md5(prompt))  # type: ignore\n            .where(self.cache_schema.llm == llm_string)\n            .where(self.cache_schema.prompt == prompt)\n            .order_by(self.cache_schema.idx)\n        )\n        with Session(self.engine) as session, session.begin():\n            rows = session.execute(stmt).fetchall()\n            for item in rows:\n                session.delete(item)\n    def _search_rows(self, prompt: str, llm_string: str) -> List[Row]:\n        prompt_pd5 = self.get_md5(prompt)\n        stmt = (\n            select(self.cache_schema.response)\n            .where(self.cache_schema.prompt_md5 == prompt_pd5)  # type: ignore\n            .where(self.cache_schema.llm == llm_string)\n            .where(self.cache_schema.prompt == prompt)\n            .order_by(self.cache_schema.idx)\n        )\n        with Session(self.engine) as session:\n            return session.execute(stmt).fetchall()\n[docs]    def clear(self, **kwargs: Any) -> None:\n        \"\"\"Clear cache.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "f0e22500afd4-28", "text": "\"\"\"Clear cache.\"\"\"\n        with Session(self.engine) as session:\n            session.execute(self.cache_schema.delete())\n[docs]    @staticmethod\n    def get_md5(input_string: str) -> str:\n        return hashlib.md5(input_string.encode()).hexdigest()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html"}
{"id": "23faabef47de-0", "text": "Source code for langchain.text_splitter\n\"\"\"**Text Splitters** are classes for splitting text.\n**Class hierarchy:**\n.. code-block::\n    BaseDocumentTransformer --> TextSplitter --> <name>TextSplitter  # Example: CharacterTextSplitter\n                                                 RecursiveCharacterTextSplitter -->  <name>TextSplitter\nNote: **MarkdownHeaderTextSplitter** and **HTMLHeaderTextSplitter do not derive from TextSplitter.\n**Main helpers:**\n.. code-block::\n    Document, Tokenizer, Language, LineType, HeaderType\n\"\"\"  # noqa: E501\nfrom __future__ import annotations\nimport asyncio\nimport copy\nimport logging\nimport pathlib\nimport re\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom functools import partial\nfrom io import BytesIO, StringIO\nfrom typing import (\n    AbstractSet,\n    Any,\n    Callable,\n    Collection,\n    Dict,\n    Iterable,\n    List,\n    Literal,\n    Optional,\n    Sequence,\n    Tuple,\n    Type,\n    TypedDict,\n    TypeVar,\n    Union,\n    cast,\n)\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.schema import BaseDocumentTransformer\nlogger = logging.getLogger(__name__)\nTS = TypeVar(\"TS\", bound=\"TextSplitter\")\ndef _make_spacy_pipeline_for_splitting(pipeline: str) -> Any:  # avoid importing spacy\n    try:\n        import spacy\n    except ImportError:\n        raise ImportError(\n            \"Spacy is not installed, please install it with `pip install spacy`.\"\n        )\n    if pipeline == \"sentencizer\":\n        from spacy.lang.en import English\n        sentencizer = English()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-1", "text": "from spacy.lang.en import English\n        sentencizer = English()\n        sentencizer.add_pipe(\"sentencizer\")\n    else:\n        sentencizer = spacy.load(pipeline, exclude=[\"ner\", \"tagger\"])\n    return sentencizer\ndef _split_text_with_regex(\n    text: str, separator: str, keep_separator: bool\n) -> List[str]:\n    # Now that we have the separator, split the text\n    if separator:\n        if keep_separator:\n            # The parentheses in the pattern keep the delimiters in the result.\n            _splits = re.split(f\"({separator})\", text)\n            splits = [_splits[i] + _splits[i + 1] for i in range(1, len(_splits), 2)]\n            if len(_splits) % 2 == 0:\n                splits += _splits[-1:]\n            splits = [_splits[0]] + splits\n        else:\n            splits = re.split(separator, text)\n    else:\n        splits = list(text)\n    return [s for s in splits if s != \"\"]\n[docs]class TextSplitter(BaseDocumentTransformer, ABC):\n    \"\"\"Interface for splitting text into chunks.\"\"\"\n[docs]    def __init__(\n        self,\n        chunk_size: int = 4000,\n        chunk_overlap: int = 200,\n        length_function: Callable[[str], int] = len,\n        keep_separator: bool = False,\n        add_start_index: bool = False,\n        strip_whitespace: bool = True,\n    ) -> None:\n        \"\"\"Create a new TextSplitter.\n        Args:\n            chunk_size: Maximum size of chunks to return\n            chunk_overlap: Overlap in characters between chunks", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-2", "text": "chunk_overlap: Overlap in characters between chunks\n            length_function: Function that measures the length of given chunks\n            keep_separator: Whether to keep the separator in the chunks\n            add_start_index: If `True`, includes chunk's start index in metadata\n            strip_whitespace: If `True`, strips whitespace from the start and end of\n                              every document\n        \"\"\"\n        if chunk_overlap > chunk_size:\n            raise ValueError(\n                f\"Got a larger chunk overlap ({chunk_overlap}) than chunk size \"\n                f\"({chunk_size}), should be smaller.\"\n            )\n        self._chunk_size = chunk_size\n        self._chunk_overlap = chunk_overlap\n        self._length_function = length_function\n        self._keep_separator = keep_separator\n        self._add_start_index = add_start_index\n        self._strip_whitespace = strip_whitespace\n[docs]    @abstractmethod\n    def split_text(self, text: str) -> List[str]:\n        \"\"\"Split text into multiple components.\"\"\"\n[docs]    def create_documents(\n        self, texts: List[str], metadatas: Optional[List[dict]] = None\n    ) -> List[Document]:\n        \"\"\"Create documents from a list of texts.\"\"\"\n        _metadatas = metadatas or [{}] * len(texts)\n        documents = []\n        for i, text in enumerate(texts):\n            index = -1\n            for chunk in self.split_text(text):\n                metadata = copy.deepcopy(_metadatas[i])\n                if self._add_start_index:\n                    index = text.find(chunk, index + 1)\n                    metadata[\"start_index\"] = index\n                new_doc = Document(page_content=chunk, metadata=metadata)\n                documents.append(new_doc)\n        return documents\n[docs]    def split_documents(self, documents: Iterable[Document]) -> List[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-3", "text": "\"\"\"Split documents.\"\"\"\n        texts, metadatas = [], []\n        for doc in documents:\n            texts.append(doc.page_content)\n            metadatas.append(doc.metadata)\n        return self.create_documents(texts, metadatas=metadatas)\n    def _join_docs(self, docs: List[str], separator: str) -> Optional[str]:\n        text = separator.join(docs)\n        if self._strip_whitespace:\n            text = text.strip()\n        if text == \"\":\n            return None\n        else:\n            return text\n    def _merge_splits(self, splits: Iterable[str], separator: str) -> List[str]:\n        # We now want to combine these smaller pieces into medium size\n        # chunks to send to the LLM.\n        separator_len = self._length_function(separator)\n        docs = []\n        current_doc: List[str] = []\n        total = 0\n        for d in splits:\n            _len = self._length_function(d)\n            if (\n                total + _len + (separator_len if len(current_doc) > 0 else 0)\n                > self._chunk_size\n            ):\n                if total > self._chunk_size:\n                    logger.warning(\n                        f\"Created a chunk of size {total}, \"\n                        f\"which is longer than the specified {self._chunk_size}\"\n                    )\n                if len(current_doc) > 0:\n                    doc = self._join_docs(current_doc, separator)\n                    if doc is not None:\n                        docs.append(doc)\n                    # Keep on popping if:\n                    # - we have a larger chunk than in the chunk overlap\n                    # - or if we still have any chunks and the length is long\n                    while total > self._chunk_overlap or (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-4", "text": "while total > self._chunk_overlap or (\n                        total + _len + (separator_len if len(current_doc) > 0 else 0)\n                        > self._chunk_size\n                        and total > 0\n                    ):\n                        total -= self._length_function(current_doc[0]) + (\n                            separator_len if len(current_doc) > 1 else 0\n                        )\n                        current_doc = current_doc[1:]\n            current_doc.append(d)\n            total += _len + (separator_len if len(current_doc) > 1 else 0)\n        doc = self._join_docs(current_doc, separator)\n        if doc is not None:\n            docs.append(doc)\n        return docs\n[docs]    @classmethod\n    def from_huggingface_tokenizer(cls, tokenizer: Any, **kwargs: Any) -> TextSplitter:\n        \"\"\"Text splitter that uses HuggingFace tokenizer to count length.\"\"\"\n        try:\n            from transformers import PreTrainedTokenizerBase\n            if not isinstance(tokenizer, PreTrainedTokenizerBase):\n                raise ValueError(\n                    \"Tokenizer received was not an instance of PreTrainedTokenizerBase\"\n                )\n            def _huggingface_tokenizer_length(text: str) -> int:\n                return len(tokenizer.encode(text))\n        except ImportError:\n            raise ValueError(\n                \"Could not import transformers python package. \"\n                \"Please install it with `pip install transformers`.\"\n            )\n        return cls(length_function=_huggingface_tokenizer_length, **kwargs)\n[docs]    @classmethod\n    def from_tiktoken_encoder(\n        cls: Type[TS],\n        encoding_name: str = \"gpt2\",\n        model_name: Optional[str] = None,\n        allowed_special: Union[Literal[\"all\"], AbstractSet[str]] = set(),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-5", "text": "allowed_special: Union[Literal[\"all\"], AbstractSet[str]] = set(),\n        disallowed_special: Union[Literal[\"all\"], Collection[str]] = \"all\",\n        **kwargs: Any,\n    ) -> TS:\n        \"\"\"Text splitter that uses tiktoken encoder to count length.\"\"\"\n        try:\n            import tiktoken\n        except ImportError:\n            raise ImportError(\n                \"Could not import tiktoken python package. \"\n                \"This is needed in order to calculate max_tokens_for_prompt. \"\n                \"Please install it with `pip install tiktoken`.\"\n            )\n        if model_name is not None:\n            enc = tiktoken.encoding_for_model(model_name)\n        else:\n            enc = tiktoken.get_encoding(encoding_name)\n        def _tiktoken_encoder(text: str) -> int:\n            return len(\n                enc.encode(\n                    text,\n                    allowed_special=allowed_special,\n                    disallowed_special=disallowed_special,\n                )\n            )\n        if issubclass(cls, TokenTextSplitter):\n            extra_kwargs = {\n                \"encoding_name\": encoding_name,\n                \"model_name\": model_name,\n                \"allowed_special\": allowed_special,\n                \"disallowed_special\": disallowed_special,\n            }\n            kwargs = {**kwargs, **extra_kwargs}\n        return cls(length_function=_tiktoken_encoder, **kwargs)\n[docs]    def transform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        \"\"\"Transform sequence of documents by splitting them.\"\"\"\n        return self.split_documents(list(documents))\n[docs]    async def atransform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-6", "text": ") -> Sequence[Document]:\n        \"\"\"Asynchronously transform a sequence of documents by splitting them.\"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, partial(self.transform_documents, **kwargs), documents\n        )\n[docs]class CharacterTextSplitter(TextSplitter):\n    \"\"\"Splitting text that looks at characters.\"\"\"\n[docs]    def __init__(\n        self, separator: str = \"\\n\\n\", is_separator_regex: bool = False, **kwargs: Any\n    ) -> None:\n        \"\"\"Create a new TextSplitter.\"\"\"\n        super().__init__(**kwargs)\n        self._separator = separator\n        self._is_separator_regex = is_separator_regex\n[docs]    def split_text(self, text: str) -> List[str]:\n        \"\"\"Split incoming text and return chunks.\"\"\"\n        # First we naively split the large input into a bunch of smaller ones.\n        separator = (\n            self._separator if self._is_separator_regex else re.escape(self._separator)\n        )\n        splits = _split_text_with_regex(text, separator, self._keep_separator)\n        _separator = \"\" if self._keep_separator else self._separator\n        return self._merge_splits(splits, _separator)\n[docs]class LineType(TypedDict):\n    \"\"\"Line type as typed dict.\"\"\"\n    metadata: Dict[str, str]\n    content: str\n[docs]class HeaderType(TypedDict):\n    \"\"\"Header type as typed dict.\"\"\"\n    level: int\n    name: str\n    data: str\n[docs]class MarkdownHeaderTextSplitter:\n    \"\"\"Splitting markdown files based on specified headers.\"\"\"\n[docs]    def __init__(\n        self, headers_to_split_on: List[Tuple[str, str]], return_each_line: bool = False\n    ):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-7", "text": "):\n        \"\"\"Create a new MarkdownHeaderTextSplitter.\n        Args:\n            headers_to_split_on: Headers we want to track\n            return_each_line: Return each line w/ associated headers\n        \"\"\"\n        # Output line-by-line or aggregated into chunks w/ common headers\n        self.return_each_line = return_each_line\n        # Given the headers we want to split on,\n        # (e.g., \"#, ##, etc\") order by length\n        self.headers_to_split_on = sorted(\n            headers_to_split_on, key=lambda split: len(split[0]), reverse=True\n        )\n[docs]    def aggregate_lines_to_chunks(self, lines: List[LineType]) -> List[Document]:\n        \"\"\"Combine lines with common metadata into chunks\n        Args:\n            lines: Line of text / associated header metadata\n        \"\"\"\n        aggregated_chunks: List[LineType] = []\n        for line in lines:\n            if (\n                aggregated_chunks\n                and aggregated_chunks[-1][\"metadata\"] == line[\"metadata\"]\n            ):\n                # If the last line in the aggregated list\n                # has the same metadata as the current line,\n                # append the current content to the last lines's content\n                aggregated_chunks[-1][\"content\"] += \"  \\n\" + line[\"content\"]\n            else:\n                # Otherwise, append the current line to the aggregated list\n                aggregated_chunks.append(line)\n        return [\n            Document(page_content=chunk[\"content\"], metadata=chunk[\"metadata\"])\n            for chunk in aggregated_chunks\n        ]\n[docs]    def split_text(self, text: str) -> List[Document]:\n        \"\"\"Split markdown file\n        Args:\n            text: Markdown file\"\"\"\n        # Split the input text by newline character (\"\\n\").\n        lines = text.split(\"\\n\")\n        # Final output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-8", "text": "lines = text.split(\"\\n\")\n        # Final output\n        lines_with_metadata: List[LineType] = []\n        # Content and metadata of the chunk currently being processed\n        current_content: List[str] = []\n        current_metadata: Dict[str, str] = {}\n        # Keep track of the nested header structure\n        # header_stack: List[Dict[str, Union[int, str]]] = []\n        header_stack: List[HeaderType] = []\n        initial_metadata: Dict[str, str] = {}\n        in_code_block = False\n        for line in lines:\n            stripped_line = line.strip()\n            if stripped_line.startswith(\"```\"):\n                # code block in one row\n                if stripped_line.count(\"```\") >= 2:\n                    in_code_block = False\n                else:\n                    in_code_block = not in_code_block\n            if in_code_block:\n                current_content.append(stripped_line)\n                continue\n            # Check each line against each of the header types (e.g., #, ##)\n            for sep, name in self.headers_to_split_on:\n                # Check if line starts with a header that we intend to split on\n                if stripped_line.startswith(sep) and (\n                    # Header with no text OR header is followed by space\n                    # Both are valid conditions that sep is being used a header\n                    len(stripped_line) == len(sep) or stripped_line[len(sep)] == \" \"\n                ):\n                    # Ensure we are tracking the header as metadata\n                    if name is not None:\n                        # Get the current header level\n                        current_header_level = sep.count(\"#\")\n                        # Pop out headers of lower or same level from the stack\n                        while (\n                            header_stack\n                            and header_stack[-1][\"level\"] >= current_header_level\n                        ):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-9", "text": "and header_stack[-1][\"level\"] >= current_header_level\n                        ):\n                            # We have encountered a new header\n                            # at the same or higher level\n                            popped_header = header_stack.pop()\n                            # Clear the metadata for the\n                            # popped header in initial_metadata\n                            if popped_header[\"name\"] in initial_metadata:\n                                initial_metadata.pop(popped_header[\"name\"])\n                        # Push the current header to the stack\n                        header: HeaderType = {\n                            \"level\": current_header_level,\n                            \"name\": name,\n                            \"data\": stripped_line[len(sep) :].strip(),\n                        }\n                        header_stack.append(header)\n                        # Update initial_metadata with the current header\n                        initial_metadata[name] = header[\"data\"]\n                    # Add the previous line to the lines_with_metadata\n                    # only if current_content is not empty\n                    if current_content:\n                        lines_with_metadata.append(\n                            {\n                                \"content\": \"\\n\".join(current_content),\n                                \"metadata\": current_metadata.copy(),\n                            }\n                        )\n                        current_content.clear()\n                    break\n            else:\n                if stripped_line:\n                    current_content.append(stripped_line)\n                elif current_content:\n                    lines_with_metadata.append(\n                        {\n                            \"content\": \"\\n\".join(current_content),\n                            \"metadata\": current_metadata.copy(),\n                        }\n                    )\n                    current_content.clear()\n            current_metadata = initial_metadata.copy()\n        if current_content:\n            lines_with_metadata.append(\n                {\"content\": \"\\n\".join(current_content), \"metadata\": current_metadata}\n            )\n        # lines_with_metadata has each line with associated header metadata\n        # aggregate these into chunks based on common metadata\n        if not self.return_each_line:\n            return self.aggregate_lines_to_chunks(lines_with_metadata)\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-10", "text": "return self.aggregate_lines_to_chunks(lines_with_metadata)\n        else:\n            return [\n                Document(page_content=chunk[\"content\"], metadata=chunk[\"metadata\"])\n                for chunk in lines_with_metadata\n            ]\n[docs]class ElementType(TypedDict):\n    \"\"\"Element type as typed dict.\"\"\"\n    url: str\n    xpath: str\n    content: str\n    metadata: Dict[str, str]\n[docs]class HTMLHeaderTextSplitter:\n    \"\"\"\n    Splitting HTML files based on specified headers.\n    Requires lxml package.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        headers_to_split_on: List[Tuple[str, str]],\n        return_each_element: bool = False,\n    ):\n        \"\"\"Create a new HTMLHeaderTextSplitter.\n        Args:\n            headers_to_split_on: list of tuples of headers we want to track mapped to\n                (arbitrary) keys for metadata. Allowed header values: h1, h2, h3, h4,\n                h5, h6 e.g. [(\"h1\", \"Header 1\"), (\"h2\", \"Header 2)].\n            return_each_element: Return each element w/ associated headers.\n        \"\"\"\n        # Output element-by-element or aggregated into chunks w/ common headers\n        self.return_each_element = return_each_element\n        self.headers_to_split_on = sorted(headers_to_split_on)\n[docs]    def aggregate_elements_to_chunks(\n        self, elements: List[ElementType]\n    ) -> List[Document]:\n        \"\"\"Combine elements with common metadata into chunks\n        Args:\n            elements: HTML element content with associated identifying info and metadata\n        \"\"\"\n        aggregated_chunks: List[ElementType] = []\n        for element in elements:\n            if (\n                aggregated_chunks", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-11", "text": "for element in elements:\n            if (\n                aggregated_chunks\n                and aggregated_chunks[-1][\"metadata\"] == element[\"metadata\"]\n            ):\n                # If the last element in the aggregated list\n                # has the same metadata as the current element,\n                # append the current content to the last element's content\n                aggregated_chunks[-1][\"content\"] += \"  \\n\" + element[\"content\"]\n            else:\n                # Otherwise, append the current element to the aggregated list\n                aggregated_chunks.append(element)\n        return [\n            Document(page_content=chunk[\"content\"], metadata=chunk[\"metadata\"])\n            for chunk in aggregated_chunks\n        ]\n[docs]    def split_text_from_url(self, url: str) -> List[Document]:\n        \"\"\"Split HTML from web URL\n        Args:\n            url: web URL\n        \"\"\"\n        r = requests.get(url)\n        return self.split_text_from_file(BytesIO(r.content))\n[docs]    def split_text(self, text: str) -> List[Document]:\n        \"\"\"Split HTML text string\n        Args:\n            text: HTML text\n        \"\"\"\n        return self.split_text_from_file(StringIO(text))\n[docs]    def split_text_from_file(self, file: Any) -> List[Document]:\n        \"\"\"Split HTML file\n        Args:\n            file: HTML file\n        \"\"\"\n        try:\n            from lxml import etree\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import lxml, please install with `pip install lxml`.\"\n            ) from e\n        # use lxml library to parse html document and return xml ElementTree\n        parser = etree.HTMLParser()\n        tree = etree.parse(file, parser)\n        # document transformation for \"structure-aware\" chunking is handled with xsl.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-12", "text": "# document transformation for \"structure-aware\" chunking is handled with xsl.\n        # see comments in html_chunks_with_headers.xslt for more detailed information.\n        xslt_path = (\n            pathlib.Path(__file__).parent\n            / \"document_transformers/xsl/html_chunks_with_headers.xslt\"\n        )\n        xslt_tree = etree.parse(xslt_path)\n        transform = etree.XSLT(xslt_tree)\n        result = transform(tree)\n        result_dom = etree.fromstring(str(result))\n        # create filter and mapping for header metadata\n        header_filter = [header[0] for header in self.headers_to_split_on]\n        header_mapping = dict(self.headers_to_split_on)\n        # map xhtml namespace prefix\n        ns_map = {\"h\": \"http://www.w3.org/1999/xhtml\"}\n        # build list of elements from DOM\n        elements = []\n        for element in result_dom.findall(\"*//*\", ns_map):\n            if element.findall(\"*[@class='headers']\") or element.findall(\n                \"*[@class='chunk']\"\n            ):\n                elements.append(\n                    ElementType(\n                        url=file,\n                        xpath=\"\".join(\n                            [\n                                node.text\n                                for node in element.findall(\"*[@class='xpath']\", ns_map)\n                            ]\n                        ),\n                        content=\"\".join(\n                            [\n                                node.text\n                                for node in element.findall(\"*[@class='chunk']\", ns_map)\n                            ]\n                        ),\n                        metadata={\n                            # Add text of specified headers to metadata using header\n                            # mapping.\n                            header_mapping[node.tag]: node.text\n                            for node in filter(\n                                lambda x: x.tag in header_filter,\n                                element.findall(\"*[@class='headers']/*\", ns_map),\n                            )\n                        },\n                    )\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-13", "text": ")\n                        },\n                    )\n                )\n        if not self.return_each_element:\n            return self.aggregate_elements_to_chunks(elements)\n        else:\n            return [\n                Document(page_content=chunk[\"content\"], metadata=chunk[\"metadata\"])\n                for chunk in elements\n            ]\n# should be in newer Python versions (3.10+)\n# @dataclass(frozen=True, kw_only=True, slots=True)\n[docs]@dataclass(frozen=True)\nclass Tokenizer:\n    \"\"\"Tokenizer data class.\"\"\"\n    chunk_overlap: int\n    \"\"\"Overlap in tokens between chunks\"\"\"\n    tokens_per_chunk: int\n    \"\"\"Maximum number of tokens per chunk\"\"\"\n    decode: Callable[[List[int]], str]\n    \"\"\" Function to decode a list of token ids to a string\"\"\"\n    encode: Callable[[str], List[int]]\n    \"\"\" Function to encode a string to a list of token ids\"\"\"\n[docs]def split_text_on_tokens(*, text: str, tokenizer: Tokenizer) -> List[str]:\n    \"\"\"Split incoming text and return chunks using tokenizer.\"\"\"\n    splits: List[str] = []\n    input_ids = tokenizer.encode(text)\n    start_idx = 0\n    cur_idx = min(start_idx + tokenizer.tokens_per_chunk, len(input_ids))\n    chunk_ids = input_ids[start_idx:cur_idx]\n    while start_idx < len(input_ids):\n        splits.append(tokenizer.decode(chunk_ids))\n        start_idx += tokenizer.tokens_per_chunk - tokenizer.chunk_overlap\n        cur_idx = min(start_idx + tokenizer.tokens_per_chunk, len(input_ids))\n        chunk_ids = input_ids[start_idx:cur_idx]\n    return splits\n[docs]class TokenTextSplitter(TextSplitter):\n    \"\"\"Splitting text to tokens using model tokenizer.\"\"\"\n[docs]    def __init__(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-14", "text": "[docs]    def __init__(\n        self,\n        encoding_name: str = \"gpt2\",\n        model_name: Optional[str] = None,\n        allowed_special: Union[Literal[\"all\"], AbstractSet[str]] = set(),\n        disallowed_special: Union[Literal[\"all\"], Collection[str]] = \"all\",\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Create a new TextSplitter.\"\"\"\n        super().__init__(**kwargs)\n        try:\n            import tiktoken\n        except ImportError:\n            raise ImportError(\n                \"Could not import tiktoken python package. \"\n                \"This is needed in order to for TokenTextSplitter. \"\n                \"Please install it with `pip install tiktoken`.\"\n            )\n        if model_name is not None:\n            enc = tiktoken.encoding_for_model(model_name)\n        else:\n            enc = tiktoken.get_encoding(encoding_name)\n        self._tokenizer = enc\n        self._allowed_special = allowed_special\n        self._disallowed_special = disallowed_special\n[docs]    def split_text(self, text: str) -> List[str]:\n        def _encode(_text: str) -> List[int]:\n            return self._tokenizer.encode(\n                _text,\n                allowed_special=self._allowed_special,\n                disallowed_special=self._disallowed_special,\n            )\n        tokenizer = Tokenizer(\n            chunk_overlap=self._chunk_overlap,\n            tokens_per_chunk=self._chunk_size,\n            decode=self._tokenizer.decode,\n            encode=_encode,\n        )\n        return split_text_on_tokens(text=text, tokenizer=tokenizer)\n[docs]class SentenceTransformersTokenTextSplitter(TextSplitter):\n    \"\"\"Splitting text to tokens using sentence model tokenizer.\"\"\"\n[docs]    def __init__(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-15", "text": "[docs]    def __init__(\n        self,\n        chunk_overlap: int = 50,\n        model_name: str = \"sentence-transformers/all-mpnet-base-v2\",\n        tokens_per_chunk: Optional[int] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Create a new TextSplitter.\"\"\"\n        super().__init__(**kwargs, chunk_overlap=chunk_overlap)\n        try:\n            from sentence_transformers import SentenceTransformer\n        except ImportError:\n            raise ImportError(\n                \"Could not import sentence_transformer python package. \"\n                \"This is needed in order to for SentenceTransformersTokenTextSplitter. \"\n                \"Please install it with `pip install sentence-transformers`.\"\n            )\n        self.model_name = model_name\n        self._model = SentenceTransformer(self.model_name)\n        self.tokenizer = self._model.tokenizer\n        self._initialize_chunk_configuration(tokens_per_chunk=tokens_per_chunk)\n    def _initialize_chunk_configuration(\n        self, *, tokens_per_chunk: Optional[int]\n    ) -> None:\n        self.maximum_tokens_per_chunk = cast(int, self._model.max_seq_length)\n        if tokens_per_chunk is None:\n            self.tokens_per_chunk = self.maximum_tokens_per_chunk\n        else:\n            self.tokens_per_chunk = tokens_per_chunk\n        if self.tokens_per_chunk > self.maximum_tokens_per_chunk:\n            raise ValueError(\n                f\"The token limit of the models '{self.model_name}'\"\n                f\" is: {self.maximum_tokens_per_chunk}.\"\n                f\" Argument tokens_per_chunk={self.tokens_per_chunk}\"\n                f\" > maximum token limit.\"\n            )\n[docs]    def split_text(self, text: str) -> List[str]:\n        def encode_strip_start_and_stop_token_ids(text: str) -> List[int]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-16", "text": "def encode_strip_start_and_stop_token_ids(text: str) -> List[int]:\n            return self._encode(text)[1:-1]\n        tokenizer = Tokenizer(\n            chunk_overlap=self._chunk_overlap,\n            tokens_per_chunk=self.tokens_per_chunk,\n            decode=self.tokenizer.decode,\n            encode=encode_strip_start_and_stop_token_ids,\n        )\n        return split_text_on_tokens(text=text, tokenizer=tokenizer)\n[docs]    def count_tokens(self, *, text: str) -> int:\n        return len(self._encode(text))\n    _max_length_equal_32_bit_integer: int = 2**32\n    def _encode(self, text: str) -> List[int]:\n        token_ids_with_start_and_end_token_ids = self.tokenizer.encode(\n            text,\n            max_length=self._max_length_equal_32_bit_integer,\n            truncation=\"do_not_truncate\",\n        )\n        return token_ids_with_start_and_end_token_ids\n[docs]class Language(str, Enum):\n    \"\"\"Enum of the programming languages.\"\"\"\n    CPP = \"cpp\"\n    GO = \"go\"\n    JAVA = \"java\"\n    KOTLIN = \"kotlin\"\n    JS = \"js\"\n    TS = \"ts\"\n    PHP = \"php\"\n    PROTO = \"proto\"\n    PYTHON = \"python\"\n    RST = \"rst\"\n    RUBY = \"ruby\"\n    RUST = \"rust\"\n    SCALA = \"scala\"\n    SWIFT = \"swift\"\n    MARKDOWN = \"markdown\"\n    LATEX = \"latex\"\n    HTML = \"html\"\n    SOL = \"sol\"\n    CSHARP = \"csharp\"\n    COBOL = \"cobol\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-17", "text": "CSHARP = \"csharp\"\n    COBOL = \"cobol\"\n[docs]class RecursiveCharacterTextSplitter(TextSplitter):\n    \"\"\"Splitting text by recursively look at characters.\n    Recursively tries to split by different characters to find one\n    that works.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        separators: Optional[List[str]] = None,\n        keep_separator: bool = True,\n        is_separator_regex: bool = False,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Create a new TextSplitter.\"\"\"\n        super().__init__(keep_separator=keep_separator, **kwargs)\n        self._separators = separators or [\"\\n\\n\", \"\\n\", \" \", \"\"]\n        self._is_separator_regex = is_separator_regex\n    def _split_text(self, text: str, separators: List[str]) -> List[str]:\n        \"\"\"Split incoming text and return chunks.\"\"\"\n        final_chunks = []\n        # Get appropriate separator to use\n        separator = separators[-1]\n        new_separators = []\n        for i, _s in enumerate(separators):\n            _separator = _s if self._is_separator_regex else re.escape(_s)\n            if _s == \"\":\n                separator = _s\n                break\n            if re.search(_separator, text):\n                separator = _s\n                new_separators = separators[i + 1 :]\n                break\n        _separator = separator if self._is_separator_regex else re.escape(separator)\n        splits = _split_text_with_regex(text, _separator, self._keep_separator)\n        # Now go merging things, recursively splitting longer texts.\n        _good_splits = []\n        _separator = \"\" if self._keep_separator else separator\n        for s in splits:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-18", "text": "_separator = \"\" if self._keep_separator else separator\n        for s in splits:\n            if self._length_function(s) < self._chunk_size:\n                _good_splits.append(s)\n            else:\n                if _good_splits:\n                    merged_text = self._merge_splits(_good_splits, _separator)\n                    final_chunks.extend(merged_text)\n                    _good_splits = []\n                if not new_separators:\n                    final_chunks.append(s)\n                else:\n                    other_info = self._split_text(s, new_separators)\n                    final_chunks.extend(other_info)\n        if _good_splits:\n            merged_text = self._merge_splits(_good_splits, _separator)\n            final_chunks.extend(merged_text)\n        return final_chunks\n[docs]    def split_text(self, text: str) -> List[str]:\n        return self._split_text(text, self._separators)\n[docs]    @classmethod\n    def from_language(\n        cls, language: Language, **kwargs: Any\n    ) -> RecursiveCharacterTextSplitter:\n        separators = cls.get_separators_for_language(language)\n        return cls(separators=separators, is_separator_regex=True, **kwargs)\n[docs]    @staticmethod\n    def get_separators_for_language(language: Language) -> List[str]:\n        if language == Language.CPP:\n            return [\n                # Split along class definitions\n                \"\\nclass \",\n                # Split along function definitions\n                \"\\nvoid \",\n                \"\\nint \",\n                \"\\nfloat \",\n                \"\\ndouble \",\n                # Split along control flow statements\n                \"\\nif \",\n                \"\\nfor \",\n                \"\\nwhile \",\n                \"\\nswitch \",\n                \"\\ncase \",\n                # Split by the normal type of lines", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-19", "text": "\"\\ncase \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.GO:\n            return [\n                # Split along function definitions\n                \"\\nfunc \",\n                \"\\nvar \",\n                \"\\nconst \",\n                \"\\ntype \",\n                # Split along control flow statements\n                \"\\nif \",\n                \"\\nfor \",\n                \"\\nswitch \",\n                \"\\ncase \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.JAVA:\n            return [\n                # Split along class definitions\n                \"\\nclass \",\n                # Split along method definitions\n                \"\\npublic \",\n                \"\\nprotected \",\n                \"\\nprivate \",\n                \"\\nstatic \",\n                # Split along control flow statements\n                \"\\nif \",\n                \"\\nfor \",\n                \"\\nwhile \",\n                \"\\nswitch \",\n                \"\\ncase \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.KOTLIN:\n            return [\n                # Split along class definitions\n                \"\\nclass \",\n                # Split along method definitions\n                \"\\npublic \",\n                \"\\nprotected \",\n                \"\\nprivate \",\n                \"\\ninternal \",\n                \"\\ncompanion \",\n                \"\\nfun \",\n                \"\\nval \",\n                \"\\nvar \",\n                # Split along control flow statements\n                \"\\nif \",\n                \"\\nfor \",\n                \"\\nwhile \",\n                \"\\nwhen \",\n                \"\\ncase \",\n                \"\\nelse \",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-20", "text": "\"\\nwhen \",\n                \"\\ncase \",\n                \"\\nelse \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.JS:\n            return [\n                # Split along function definitions\n                \"\\nfunction \",\n                \"\\nconst \",\n                \"\\nlet \",\n                \"\\nvar \",\n                \"\\nclass \",\n                # Split along control flow statements\n                \"\\nif \",\n                \"\\nfor \",\n                \"\\nwhile \",\n                \"\\nswitch \",\n                \"\\ncase \",\n                \"\\ndefault \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.TS:\n            return [\n                \"\\nenum \",\n                \"\\ninterface \",\n                \"\\nnamespace \",\n                \"\\ntype \",\n                # Split along class definitions\n                \"\\nclass \",\n                # Split along function definitions\n                \"\\nfunction \",\n                \"\\nconst \",\n                \"\\nlet \",\n                \"\\nvar \",\n                # Split along control flow statements\n                \"\\nif \",\n                \"\\nfor \",\n                \"\\nwhile \",\n                \"\\nswitch \",\n                \"\\ncase \",\n                \"\\ndefault \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.PHP:\n            return [\n                # Split along function definitions\n                \"\\nfunction \",\n                # Split along class definitions\n                \"\\nclass \",\n                # Split along control flow statements\n                \"\\nif \",\n                \"\\nforeach \",\n                \"\\nwhile \",\n                \"\\ndo \",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-21", "text": "\"\\nforeach \",\n                \"\\nwhile \",\n                \"\\ndo \",\n                \"\\nswitch \",\n                \"\\ncase \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.PROTO:\n            return [\n                # Split along message definitions\n                \"\\nmessage \",\n                # Split along service definitions\n                \"\\nservice \",\n                # Split along enum definitions\n                \"\\nenum \",\n                # Split along option definitions\n                \"\\noption \",\n                # Split along import statements\n                \"\\nimport \",\n                # Split along syntax declarations\n                \"\\nsyntax \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.PYTHON:\n            return [\n                # First, try to split along class definitions\n                \"\\nclass \",\n                \"\\ndef \",\n                \"\\n\\tdef \",\n                # Now split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.RST:\n            return [\n                # Split along section titles\n                \"\\n=+\\n\",\n                \"\\n-+\\n\",\n                \"\\n\\\\*+\\n\",\n                # Split along directive markers\n                \"\\n\\n.. *\\n\\n\",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.RUBY:\n            return [\n                # Split along method definitions\n                \"\\ndef \",\n                \"\\nclass \",\n                # Split along control flow statements\n                \"\\nif \",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-22", "text": "\"\\nclass \",\n                # Split along control flow statements\n                \"\\nif \",\n                \"\\nunless \",\n                \"\\nwhile \",\n                \"\\nfor \",\n                \"\\ndo \",\n                \"\\nbegin \",\n                \"\\nrescue \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.RUST:\n            return [\n                # Split along function definitions\n                \"\\nfn \",\n                \"\\nconst \",\n                \"\\nlet \",\n                # Split along control flow statements\n                \"\\nif \",\n                \"\\nwhile \",\n                \"\\nfor \",\n                \"\\nloop \",\n                \"\\nmatch \",\n                \"\\nconst \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.SCALA:\n            return [\n                # Split along class definitions\n                \"\\nclass \",\n                \"\\nobject \",\n                # Split along method definitions\n                \"\\ndef \",\n                \"\\nval \",\n                \"\\nvar \",\n                # Split along control flow statements\n                \"\\nif \",\n                \"\\nfor \",\n                \"\\nwhile \",\n                \"\\nmatch \",\n                \"\\ncase \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.SWIFT:\n            return [\n                # Split along function definitions\n                \"\\nfunc \",\n                # Split along class definitions\n                \"\\nclass \",\n                \"\\nstruct \",\n                \"\\nenum \",\n                # Split along control flow statements\n                \"\\nif \",\n                \"\\nfor \",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-23", "text": "# Split along control flow statements\n                \"\\nif \",\n                \"\\nfor \",\n                \"\\nwhile \",\n                \"\\ndo \",\n                \"\\nswitch \",\n                \"\\ncase \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.MARKDOWN:\n            return [\n                # First, try to split along Markdown headings (starting with level 2)\n                \"\\n#{1,6} \",\n                # Note the alternative syntax for headings (below) is not handled here\n                # Heading level 2\n                # ---------------\n                # End of code block\n                \"```\\n\",\n                # Horizontal lines\n                \"\\n\\\\*\\\\*\\\\*+\\n\",\n                \"\\n---+\\n\",\n                \"\\n___+\\n\",\n                # Note that this splitter doesn't handle horizontal lines defined\n                # by *three or more* of ***, ---, or ___, but this is not handled\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.LATEX:\n            return [\n                # First, try to split along Latex sections\n                \"\\n\\\\\\\\chapter{\",\n                \"\\n\\\\\\\\section{\",\n                \"\\n\\\\\\\\subsection{\",\n                \"\\n\\\\\\\\subsubsection{\",\n                # Now split by environments\n                \"\\n\\\\\\\\begin{enumerate}\",\n                \"\\n\\\\\\\\begin{itemize}\",\n                \"\\n\\\\\\\\begin{description}\",\n                \"\\n\\\\\\\\begin{list}\",\n                \"\\n\\\\\\\\begin{quote}\",\n                \"\\n\\\\\\\\begin{quotation}\",\n                \"\\n\\\\\\\\begin{verse}\",\n                \"\\n\\\\\\\\begin{verbatim}\",\n                # Now split by math environments", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-24", "text": "\"\\n\\\\\\\\begin{verbatim}\",\n                # Now split by math environments\n                \"\\n\\\\\\begin{align}\",\n                \"$$\",\n                \"$\",\n                # Now split by the normal type of lines\n                \" \",\n                \"\",\n            ]\n        elif language == Language.HTML:\n            return [\n                # First, try to split along HTML tags\n                \"<body\",\n                \"<div\",\n                \"<p\",\n                \"<br\",\n                \"<li\",\n                \"<h1\",\n                \"<h2\",\n                \"<h3\",\n                \"<h4\",\n                \"<h5\",\n                \"<h6\",\n                \"<span\",\n                \"<table\",\n                \"<tr\",\n                \"<td\",\n                \"<th\",\n                \"<ul\",\n                \"<ol\",\n                \"<header\",\n                \"<footer\",\n                \"<nav\",\n                # Head\n                \"<head\",\n                \"<style\",\n                \"<script\",\n                \"<meta\",\n                \"<title\",\n                \"\",\n            ]\n        elif language == Language.CSHARP:\n            return [\n                \"\\ninterface \",\n                \"\\nenum \",\n                \"\\nimplements \",\n                \"\\ndelegate \",\n                \"\\nevent \",\n                # Split along class definitions\n                \"\\nclass \",\n                \"\\nabstract \",\n                # Split along method definitions\n                \"\\npublic \",\n                \"\\nprotected \",\n                \"\\nprivate \",\n                \"\\nstatic \",\n                \"\\nreturn \",\n                # Split along control flow statements\n                \"\\nif \",\n                \"\\ncontinue \",\n                \"\\nfor \",\n                \"\\nforeach \",\n                \"\\nwhile \",\n                \"\\nswitch \",\n                \"\\nbreak \",\n                \"\\ncase \",\n                \"\\nelse \",\n                # Split by exceptions\n                \"\\ntry \",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-25", "text": "\"\\nelse \",\n                # Split by exceptions\n                \"\\ntry \",\n                \"\\nthrow \",\n                \"\\nfinally \",\n                \"\\ncatch \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.SOL:\n            return [\n                # Split along compiler information definitions\n                \"\\npragma \",\n                \"\\nusing \",\n                # Split along contract definitions\n                \"\\ncontract \",\n                \"\\ninterface \",\n                \"\\nlibrary \",\n                # Split along method definitions\n                \"\\nconstructor \",\n                \"\\ntype \",\n                \"\\nfunction \",\n                \"\\nevent \",\n                \"\\nmodifier \",\n                \"\\nerror \",\n                \"\\nstruct \",\n                \"\\nenum \",\n                # Split along control flow statements\n                \"\\nif \",\n                \"\\nfor \",\n                \"\\nwhile \",\n                \"\\ndo while \",\n                \"\\nassembly \",\n                # Split by the normal type of lines\n                \"\\n\\n\",\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        elif language == Language.COBOL:\n            return [\n                # Split along divisions\n                \"\\nIDENTIFICATION DIVISION.\",\n                \"\\nENVIRONMENT DIVISION.\",\n                \"\\nDATA DIVISION.\",\n                \"\\nPROCEDURE DIVISION.\",\n                # Split along sections within DATA DIVISION\n                \"\\nWORKING-STORAGE SECTION.\",\n                \"\\nLINKAGE SECTION.\",\n                \"\\nFILE SECTION.\",\n                # Split along sections within PROCEDURE DIVISION\n                \"\\nINPUT-OUTPUT SECTION.\",\n                # Split along paragraphs and common statements\n                \"\\nOPEN \",\n                \"\\nCLOSE \",\n                \"\\nREAD \",\n                \"\\nWRITE \",\n                \"\\nIF \",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-26", "text": "\"\\nREAD \",\n                \"\\nWRITE \",\n                \"\\nIF \",\n                \"\\nELSE \",\n                \"\\nMOVE \",\n                \"\\nPERFORM \",\n                \"\\nUNTIL \",\n                \"\\nVARYING \",\n                \"\\nACCEPT \",\n                \"\\nDISPLAY \",\n                \"\\nSTOP RUN.\",\n                # Split by the normal type of lines\n                \"\\n\",\n                \" \",\n                \"\",\n            ]\n        else:\n            raise ValueError(\n                f\"Language {language} is not supported! \"\n                f\"Please choose from {list(Language)}\"\n            )\n[docs]class NLTKTextSplitter(TextSplitter):\n    \"\"\"Splitting text using NLTK package.\"\"\"\n[docs]    def __init__(\n        self, separator: str = \"\\n\\n\", language: str = \"english\", **kwargs: Any\n    ) -> None:\n        \"\"\"Initialize the NLTK splitter.\"\"\"\n        super().__init__(**kwargs)\n        try:\n            from nltk.tokenize import sent_tokenize\n            self._tokenizer = sent_tokenize\n        except ImportError:\n            raise ImportError(\n                \"NLTK is not installed, please install it with `pip install nltk`.\"\n            )\n        self._separator = separator\n        self._language = language\n[docs]    def split_text(self, text: str) -> List[str]:\n        \"\"\"Split incoming text and return chunks.\"\"\"\n        # First we naively split the large input into a bunch of smaller ones.\n        splits = self._tokenizer(text, language=self._language)\n        return self._merge_splits(splits, self._separator)\n[docs]class SpacyTextSplitter(TextSplitter):\n    \"\"\"Splitting text using Spacy package.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-27", "text": "\"\"\"Splitting text using Spacy package.\n    Per default, Spacy's `en_core_web_sm` model is used. For a faster, but\n    potentially less accurate splitting, you can use `pipeline='sentencizer'`.\n    \"\"\"\n[docs]    def __init__(\n        self, separator: str = \"\\n\\n\", pipeline: str = \"en_core_web_sm\", **kwargs: Any\n    ) -> None:\n        \"\"\"Initialize the spacy text splitter.\"\"\"\n        super().__init__(**kwargs)\n        self._tokenizer = _make_spacy_pipeline_for_splitting(pipeline)\n        self._separator = separator\n[docs]    def split_text(self, text: str) -> List[str]:\n        \"\"\"Split incoming text and return chunks.\"\"\"\n        splits = (s.text for s in self._tokenizer(text).sents)\n        return self._merge_splits(splits, self._separator)\n# For backwards compatibility\n[docs]class PythonCodeTextSplitter(RecursiveCharacterTextSplitter):\n    \"\"\"Attempts to split the text along Python syntax.\"\"\"\n[docs]    def __init__(self, **kwargs: Any) -> None:\n        \"\"\"Initialize a PythonCodeTextSplitter.\"\"\"\n        separators = self.get_separators_for_language(Language.PYTHON)\n        super().__init__(separators=separators, **kwargs)\n[docs]class MarkdownTextSplitter(RecursiveCharacterTextSplitter):\n    \"\"\"Attempts to split the text along Markdown-formatted headings.\"\"\"\n[docs]    def __init__(self, **kwargs: Any) -> None:\n        \"\"\"Initialize a MarkdownTextSplitter.\"\"\"\n        separators = self.get_separators_for_language(Language.MARKDOWN)\n        super().__init__(separators=separators, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "23faabef47de-28", "text": "super().__init__(separators=separators, **kwargs)\n[docs]class LatexTextSplitter(RecursiveCharacterTextSplitter):\n    \"\"\"Attempts to split the text along Latex-formatted layout elements.\"\"\"\n[docs]    def __init__(self, **kwargs: Any) -> None:\n        \"\"\"Initialize a LatexTextSplitter.\"\"\"\n        separators = self.get_separators_for_language(Language.LATEX)\n        super().__init__(separators=separators, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html"}
{"id": "c37ade5e7a8b-0", "text": "Source code for langchain.model_laboratory\n\"\"\"Experiment with different models.\"\"\"\nfrom __future__ import annotations\nfrom typing import List, Optional, Sequence\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.llms.base import BaseLLM\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.utils.input import get_color_mapping, print_text\n[docs]class ModelLaboratory:\n    \"\"\"Experiment with different models.\"\"\"\n[docs]    def __init__(self, chains: Sequence[Chain], names: Optional[List[str]] = None):\n        \"\"\"Initialize with chains to experiment with.\n        Args:\n            chains: list of chains to experiment with.\n        \"\"\"\n        for chain in chains:\n            if not isinstance(chain, Chain):\n                raise ValueError(\n                    \"ModelLaboratory should now be initialized with Chains. \"\n                    \"If you want to initialize with LLMs, use the `from_llms` method \"\n                    \"instead (`ModelLaboratory.from_llms(...)`)\"\n                )\n            if len(chain.input_keys) != 1:\n                raise ValueError(\n                    \"Currently only support chains with one input variable, \"\n                    f\"got {chain.input_keys}\"\n                )\n            if len(chain.output_keys) != 1:\n                raise ValueError(\n                    \"Currently only support chains with one output variable, \"\n                    f\"got {chain.output_keys}\"\n                )\n        if names is not None:\n            if len(names) != len(chains):\n                raise ValueError(\"Length of chains does not match length of names.\")\n        self.chains = chains\n        chain_range = [str(i) for i in range(len(self.chains))]\n        self.chain_colors = get_color_mapping(chain_range)\n        self.names = names", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/model_laboratory.html"}
{"id": "c37ade5e7a8b-1", "text": "self.chain_colors = get_color_mapping(chain_range)\n        self.names = names\n[docs]    @classmethod\n    def from_llms(\n        cls, llms: List[BaseLLM], prompt: Optional[PromptTemplate] = None\n    ) -> ModelLaboratory:\n        \"\"\"Initialize with LLMs to experiment with and optional prompt.\n        Args:\n            llms: list of LLMs to experiment with\n            prompt: Optional prompt to use to prompt the LLMs. Defaults to None.\n                If a prompt was provided, it should only have one input variable.\n        \"\"\"\n        if prompt is None:\n            prompt = PromptTemplate(input_variables=[\"_input\"], template=\"{_input}\")\n        chains = [LLMChain(llm=llm, prompt=prompt) for llm in llms]\n        names = [str(llm) for llm in llms]\n        return cls(chains, names=names)\n[docs]    def compare(self, text: str) -> None:\n        \"\"\"Compare model outputs on an input text.\n        If a prompt was provided with starting the laboratory, then this text will be\n        fed into the prompt. If no prompt was provided, then the input text is the\n        entire prompt.\n        Args:\n            text: input text to run all models on.\n        \"\"\"\n        print(f\"\\033[1mInput:\\033[0m\\n{text}\\n\")\n        for i, chain in enumerate(self.chains):\n            if self.names is not None:\n                name = self.names[i]\n            else:\n                name = str(chain)\n            print_text(name, end=\"\\n\")\n            output = chain.run(text)\n            print_text(output, color=self.chain_colors[str(i)], end=\"\\n\\n\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/model_laboratory.html"}
{"id": "baad2192616a-0", "text": "Source code for langchain.hub\n\"\"\"Interface with the LangChain Hub.\"\"\"\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Any, Optional\nfrom langchain.load.dump import dumps\nfrom langchain.load.load import loads\nif TYPE_CHECKING:\n    from langchainhub import Client\ndef _get_client(api_url: Optional[str] = None, api_key: Optional[str] = None) -> Client:\n    try:\n        from langchainhub import Client\n    except ImportError as e:\n        raise ImportError(\n            \"Could not import langchainhub, please install with `pip install \"\n            \"langchainhub`.\"\n        ) from e\n    # Client logic will also attempt to load URL/key from environment variables\n    return Client(api_url, api_key=api_key)\n[docs]def push(\n    repo_full_name: str,\n    object: Any,\n    *,\n    api_url: Optional[str] = None,\n    api_key: Optional[str] = None,\n    parent_commit_hash: Optional[str] = \"latest\",\n    new_repo_is_public: bool = True,\n    new_repo_description: str = \"\",\n) -> str:\n    \"\"\"\n    Pushes an object to the hub and returns the URL it can be viewed at in a browser.\n    :param repo_full_name: The full name of the repo to push to in the format of\n        `owner/repo`.\n    :param object: The LangChain to serialize and push to the hub.\n    :param api_url: The URL of the LangChain Hub API. Defaults to the hosted API service\n        if you have an api key set, or a localhost instance if not.\n    :param api_key: The API key to use to authenticate with the LangChain Hub API.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/hub.html"}
{"id": "baad2192616a-1", "text": ":param parent_commit_hash: The commit hash of the parent commit to push to. Defaults\n        to the latest commit automatically.\n    :param new_repo_is_public: Whether the repo should be public. Defaults to\n        True (Public by default).\n    :param new_repo_description: The description of the repo. Defaults to an empty\n        string.\n    \"\"\"\n    client = _get_client(api_url=api_url, api_key=api_key)\n    manifest_json = dumps(object)\n    message = client.push(\n        repo_full_name,\n        manifest_json,\n        parent_commit_hash=parent_commit_hash,\n        new_repo_is_public=new_repo_is_public,\n        new_repo_description=new_repo_description,\n    )\n    return message\n[docs]def pull(\n    owner_repo_commit: str,\n    *,\n    api_url: Optional[str] = None,\n    api_key: Optional[str] = None,\n) -> Any:\n    \"\"\"\n    Pulls an object from the hub and returns it as a LangChain object.\n    :param owner_repo_commit: The full name of the repo to pull from in the format of\n        `owner/repo:commit_hash`.\n    :param api_url: The URL of the LangChain Hub API. Defaults to the hosted API service\n        if you have an api key set, or a localhost instance if not.\n    :param api_key: The API key to use to authenticate with the LangChain Hub API.\n    \"\"\"\n    client = _get_client(api_url=api_url, api_key=api_key)\n    resp: str = client.pull(owner_repo_commit)\n    return loads(resp)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/hub.html"}
{"id": "115d2a7a94a4-0", "text": "Source code for langchain.utilities.portkey\nimport json\nimport os\nfrom typing import Dict, Optional\n[docs]class Portkey:\n    \"\"\"Portkey configuration.\n    Attributes:\n        base: The base URL for the Portkey API.\n          Default: \"https://api.portkey.ai/v1/proxy\"\n    \"\"\"\n    base = \"https://api.portkey.ai/v1/proxy\"\n[docs]    @staticmethod\n    def Config(\n        api_key: str,\n        trace_id: Optional[str] = None,\n        environment: Optional[str] = None,\n        user: Optional[str] = None,\n        organisation: Optional[str] = None,\n        prompt: Optional[str] = None,\n        retry_count: Optional[int] = None,\n        cache: Optional[str] = None,\n        cache_force_refresh: Optional[str] = None,\n        cache_age: Optional[int] = None,\n    ) -> Dict[str, str]:\n        assert retry_count is None or retry_count in range(\n            1, 6\n        ), \"retry_count must be an integer and in range [1, 2, 3, 4, 5]\"\n        assert cache is None or cache in [\n            \"simple\",\n            \"semantic\",\n        ], \"cache must be 'simple' or 'semantic'\"\n        assert cache_force_refresh is None or (\n            isinstance(cache_force_refresh, str)\n            and cache_force_refresh in [\"True\", \"False\"]\n        ), \"cache_force_refresh must be 'True' or 'False'\"\n        assert cache_age is None or isinstance(\n            cache_age, int\n        ), \"cache_age must be an integer\"\n        os.environ[\"OPENAI_API_BASE\"] = Portkey.base\n        headers = {\n            \"x-portkey-api-key\": api_key,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/portkey.html"}
{"id": "115d2a7a94a4-1", "text": "headers = {\n            \"x-portkey-api-key\": api_key,\n            \"x-portkey-mode\": \"proxy openai\",\n        }\n        if trace_id:\n            headers[\"x-portkey-trace-id\"] = trace_id\n        if retry_count:\n            headers[\"x-portkey-retry-count\"] = str(retry_count)\n        if cache:\n            headers[\"x-portkey-cache\"] = cache\n        if cache_force_refresh:\n            headers[\"x-portkey-cache-force-refresh\"] = cache_force_refresh\n        if cache_age:\n            headers[\"Cache-Control\"] = f\"max-age:{str(cache_age)}\"\n        metadata = {}\n        if environment:\n            metadata[\"_environment\"] = environment\n        if user:\n            metadata[\"_user\"] = user\n        if organisation:\n            metadata[\"_organisation\"] = organisation\n        if prompt:\n            metadata[\"_prompt\"] = prompt\n        if metadata:\n            headers.update({\"x-portkey-metadata\": json.dumps(metadata)})\n        return headers", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/portkey.html"}
{"id": "afc07acaa362-0", "text": "Source code for langchain.utilities.google_scholar\n\"\"\"Util that calls Google Scholar Search.\"\"\"\nfrom typing import Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class GoogleScholarAPIWrapper(BaseModel):\n    \"\"\"Wrapper for Google Scholar API\n    You can create serpapi key by signing up at: https://serpapi.com/users/sign_up.\n    The wrapper uses the serpapi python package:\n    https://serpapi.com/integrations/python#search-google-scholar\n    To use, you should have the environment variable ``SERP_API_KEY``\n    set with your API key, or pass `serp_api_key` as a named parameter\n    to the constructor.\n    Attributes:\n        top_k_results: number of results to return from google-scholar query search.\n            By default it returns top 10 results.\n        hl: attribute defines the language to use for the Google Scholar search.\n            It's a two-letter language code.\n            (e.g., en for English, es for Spanish, or fr for French). Head to the\n            Google languages page for a full list of supported Google languages:\n            https://serpapi.com/google-languages\n        lr: attribute defines one or multiple languages to limit the search to.\n            It uses lang_{two-letter language code} to specify languages\n            and | as a delimiter. (e.g., lang_fr|lang_de will only search French\n            and German pages). Head to the Google lr languages for a full\n            list of supported languages: https://serpapi.com/google-lr-languages\n     Example:\n        .. code-block:: python\n        from langchain.utilities import GoogleScholarAPIWrapper\n        google_scholar = GoogleScholarAPIWrapper()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_scholar.html"}
{"id": "afc07acaa362-1", "text": "google_scholar = GoogleScholarAPIWrapper()\n        google_scholar.run('langchain')\n    \"\"\"\n    top_k_results: int = 10\n    hl: str = \"en\"\n    lr: str = \"lang_en\"\n    serp_api_key: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        serp_api_key = get_from_dict_or_env(values, \"serp_api_key\", \"SERP_API_KEY\")\n        values[\"SERP_API_KEY\"] = serp_api_key\n        try:\n            from serpapi import GoogleScholarSearch\n        except ImportError:\n            raise ImportError(\n                \"google-search-results is not installed. \"\n                \"Please install it with `pip install google-search-results\"\n                \">=2.4.2`\"\n            )\n        GoogleScholarSearch.SERP_API_KEY = serp_api_key\n        values[\"google_scholar_engine\"] = GoogleScholarSearch\n        return values\n[docs]    def run(self, query: str) -> str:\n        \"\"\"Run query through GoogleSearchScholar and parse result\"\"\"\n        total_results = []\n        page = 0\n        while page < max((self.top_k_results - 20), 1):\n            # We are getting 20 results from every page\n            # which is the max in order to reduce the number of API CALLS.\n            # 0 is the first page of results, 20 is the 2nd page of results,\n            # 40 is the 3rd page of results, etc.\n            results = (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_scholar.html"}
{"id": "afc07acaa362-2", "text": "results = (\n                self.google_scholar_engine(  # type: ignore\n                    {\n                        \"q\": query,\n                        \"start\": page,\n                        \"hl\": self.hl,\n                        \"num\": min(\n                            self.top_k_results, 20\n                        ),  # if top_k_result is less than 20.\n                        \"lr\": self.lr,\n                    }\n                )\n                .get_dict()\n                .get(\"organic_results\", [])\n            )\n            total_results.extend(results)\n            if not results:  # No need to search for more pages if current page\n                # has returned no results\n                break\n            page += 20\n        if (\n            self.top_k_results % 20 != 0 and page > 20 and total_results\n        ):  # From the last page we would only need top_k_results%20 results\n            # if k is not divisible by 20.\n            results = (\n                self.google_scholar_engine(  # type: ignore\n                    {\n                        \"q\": query,\n                        \"start\": page,\n                        \"num\": self.top_k_results % 20,\n                        \"hl\": self.hl,\n                        \"lr\": self.lr,\n                    }\n                )\n                .get_dict()\n                .get(\"organic_results\", [])\n            )\n            total_results.extend(results)\n        if not total_results:\n            return \"No good Google Scholar Result was found\"\n        docs = [\n            f\"Title: {result.get('title','')}\\n\"\n            f\"Authors: {','.join([author.get('name') for author in result.get('publication_info',{}).get('authors',[])])}\\n\"  # noqa: E501", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_scholar.html"}
{"id": "afc07acaa362-3", "text": "f\"Summary: {result.get('publication_info',{}).get('summary','')}\\n\"\n            f\"Total-Citations: {result.get('inline_links',{}).get('cited_by',{}).get('total','')}\"  # noqa: E501\n            for result in total_results\n        ]\n        return \"\\n\\n\".join(docs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_scholar.html"}
{"id": "aef74c6edd0d-0", "text": "Source code for langchain.utilities.spark_sql\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Any, Iterable, List, Optional\nif TYPE_CHECKING:\n    from pyspark.sql import DataFrame, Row, SparkSession\n[docs]class SparkSQL:\n    \"\"\"SparkSQL is a utility class for interacting with Spark SQL.\"\"\"\n[docs]    def __init__(\n        self,\n        spark_session: Optional[SparkSession] = None,\n        catalog: Optional[str] = None,\n        schema: Optional[str] = None,\n        ignore_tables: Optional[List[str]] = None,\n        include_tables: Optional[List[str]] = None,\n        sample_rows_in_table_info: int = 3,\n    ):\n        \"\"\"Initialize a SparkSQL object.\n        Args:\n            spark_session: A SparkSession object.\n              If not provided, one will be created.\n            catalog: The catalog to use.\n              If not provided, the default catalog will be used.\n            schema: The schema to use.\n              If not provided, the default schema will be used.\n            ignore_tables: A list of tables to ignore.\n              If not provided, all tables will be used.\n            include_tables: A list of tables to include.\n              If not provided, all tables will be used.\n            sample_rows_in_table_info: The number of rows to include in the table info.\n              Defaults to 3.\n        \"\"\"\n        try:\n            from pyspark.sql import SparkSession\n        except ImportError:\n            raise ImportError(\n                \"pyspark is not installed. Please install it with `pip install pyspark`\"\n            )\n        self._spark = (\n            spark_session if spark_session else SparkSession.builder.getOrCreate()\n        )\n        if catalog is not None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html"}
{"id": "aef74c6edd0d-1", "text": ")\n        if catalog is not None:\n            self._spark.catalog.setCurrentCatalog(catalog)\n        if schema is not None:\n            self._spark.catalog.setCurrentDatabase(schema)\n        self._all_tables = set(self._get_all_table_names())\n        self._include_tables = set(include_tables) if include_tables else set()\n        if self._include_tables:\n            missing_tables = self._include_tables - self._all_tables\n            if missing_tables:\n                raise ValueError(\n                    f\"include_tables {missing_tables} not found in database\"\n                )\n        self._ignore_tables = set(ignore_tables) if ignore_tables else set()\n        if self._ignore_tables:\n            missing_tables = self._ignore_tables - self._all_tables\n            if missing_tables:\n                raise ValueError(\n                    f\"ignore_tables {missing_tables} not found in database\"\n                )\n        usable_tables = self.get_usable_table_names()\n        self._usable_tables = set(usable_tables) if usable_tables else self._all_tables\n        if not isinstance(sample_rows_in_table_info, int):\n            raise TypeError(\"sample_rows_in_table_info must be an integer\")\n        self._sample_rows_in_table_info = sample_rows_in_table_info\n[docs]    @classmethod\n    def from_uri(\n        cls, database_uri: str, engine_args: Optional[dict] = None, **kwargs: Any\n    ) -> SparkSQL:\n        \"\"\"Creating a remote Spark Session via Spark connect.\n        For example: SparkSQL.from_uri(\"sc://localhost:15002\")\n        \"\"\"\n        try:\n            from pyspark.sql import SparkSession\n        except ImportError:\n            raise ValueError(\n                \"pyspark is not installed. Please install it with `pip install pyspark`\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html"}
{"id": "aef74c6edd0d-2", "text": ")\n        spark = SparkSession.builder.remote(database_uri).getOrCreate()\n        return cls(spark, **kwargs)\n[docs]    def get_usable_table_names(self) -> Iterable[str]:\n        \"\"\"Get names of tables available.\"\"\"\n        if self._include_tables:\n            return self._include_tables\n        # sorting the result can help LLM understanding it.\n        return sorted(self._all_tables - self._ignore_tables)\n    def _get_all_table_names(self) -> Iterable[str]:\n        rows = self._spark.sql(\"SHOW TABLES\").select(\"tableName\").collect()\n        return list(map(lambda row: row.tableName, rows))\n    def _get_create_table_stmt(self, table: str) -> str:\n        statement = (\n            self._spark.sql(f\"SHOW CREATE TABLE {table}\").collect()[0].createtab_stmt\n        )\n        # Ignore the data source provider and options to reduce the number of tokens.\n        using_clause_index = statement.find(\"USING\")\n        return statement[:using_clause_index] + \";\"\n[docs]    def get_table_info(self, table_names: Optional[List[str]] = None) -> str:\n        all_table_names = self.get_usable_table_names()\n        if table_names is not None:\n            missing_tables = set(table_names).difference(all_table_names)\n            if missing_tables:\n                raise ValueError(f\"table_names {missing_tables} not found in database\")\n            all_table_names = table_names\n        tables = []\n        for table_name in all_table_names:\n            table_info = self._get_create_table_stmt(table_name)\n            if self._sample_rows_in_table_info:\n                table_info += \"\\n\\n/*\"\n                table_info += f\"\\n{self._get_sample_spark_rows(table_name)}\\n\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html"}
{"id": "aef74c6edd0d-3", "text": "table_info += \"*/\"\n            tables.append(table_info)\n        final_str = \"\\n\\n\".join(tables)\n        return final_str\n    def _get_sample_spark_rows(self, table: str) -> str:\n        query = f\"SELECT * FROM {table} LIMIT {self._sample_rows_in_table_info}\"\n        df = self._spark.sql(query)\n        columns_str = \"\\t\".join(list(map(lambda f: f.name, df.schema.fields)))\n        try:\n            sample_rows = self._get_dataframe_results(df)\n            # save the sample rows in string format\n            sample_rows_str = \"\\n\".join([\"\\t\".join(row) for row in sample_rows])\n        except Exception:\n            sample_rows_str = \"\"\n        return (\n            f\"{self._sample_rows_in_table_info} rows from {table} table:\\n\"\n            f\"{columns_str}\\n\"\n            f\"{sample_rows_str}\"\n        )\n    def _convert_row_as_tuple(self, row: Row) -> tuple:\n        return tuple(map(str, row.asDict().values()))\n    def _get_dataframe_results(self, df: DataFrame) -> list:\n        return list(map(self._convert_row_as_tuple, df.collect()))\n[docs]    def run(self, command: str, fetch: str = \"all\") -> str:\n        df = self._spark.sql(command)\n        if fetch == \"one\":\n            df = df.limit(1)\n        return str(self._get_dataframe_results(df))\n[docs]    def get_table_info_no_throw(self, table_names: Optional[List[str]] = None) -> str:\n        \"\"\"Get information about specified tables.\n        Follows best practices as specified in: Rajkumar et al, 2022", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html"}
{"id": "aef74c6edd0d-4", "text": "Follows best practices as specified in: Rajkumar et al, 2022\n        (https://arxiv.org/abs/2204.00498)\n        If `sample_rows_in_table_info`, the specified number of sample rows will be\n        appended to each table description. This can increase performance as\n        demonstrated in the paper.\n        \"\"\"\n        try:\n            return self.get_table_info(table_names)\n        except ValueError as e:\n            \"\"\"Format the error message\"\"\"\n            return f\"Error: {e}\"\n[docs]    def run_no_throw(self, command: str, fetch: str = \"all\") -> str:\n        \"\"\"Execute a SQL command and return a string representing the results.\n        If the statement returns rows, a string of the results is returned.\n        If the statement returns no rows, an empty string is returned.\n        If the statement throws an error, the error message is returned.\n        \"\"\"\n        try:\n            return self.run(command, fetch)\n        except Exception as e:\n            \"\"\"Format the error message\"\"\"\n            return f\"Error: {e}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html"}
{"id": "7675721da6c7-0", "text": "Source code for langchain.utilities.bibtex\n\"\"\"Util that calls bibtexparser.\"\"\"\nimport logging\nfrom typing import Any, Dict, List, Mapping\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nlogger = logging.getLogger(__name__)\nOPTIONAL_FIELDS = [\n    \"annotate\",\n    \"booktitle\",\n    \"editor\",\n    \"howpublished\",\n    \"journal\",\n    \"keywords\",\n    \"note\",\n    \"organization\",\n    \"publisher\",\n    \"school\",\n    \"series\",\n    \"type\",\n    \"doi\",\n    \"issn\",\n    \"isbn\",\n]\n[docs]class BibtexparserWrapper(BaseModel):\n    \"\"\"Wrapper around bibtexparser.\n    To use, you should have the ``bibtexparser`` python package installed.\n    https://bibtexparser.readthedocs.io/en/master/\n    This wrapper will use bibtexparser to load a collection of references from\n    a bibtex file and fetch document summaries.\n    \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the python package exists in environment.\"\"\"\n        try:\n            import bibtexparser  # noqa\n        except ImportError:\n            raise ImportError(\n                \"Could not import bibtexparser python package. \"\n                \"Please install it with `pip install bibtexparser`.\"\n            )\n        return values\n[docs]    def load_bibtex_entries(self, path: str) -> List[Dict[str, Any]]:\n        \"\"\"Load bibtex entries from the bibtex file at the given path.\"\"\"\n        import bibtexparser", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html"}
{"id": "7675721da6c7-1", "text": "import bibtexparser\n        with open(path) as file:\n            entries = bibtexparser.load(file).entries\n        return entries\n[docs]    def get_metadata(\n        self, entry: Mapping[str, Any], load_extra: bool = False\n    ) -> Dict[str, Any]:\n        \"\"\"Get metadata for the given entry.\"\"\"\n        publication = entry.get(\"journal\") or entry.get(\"booktitle\")\n        if \"url\" in entry:\n            url = entry[\"url\"]\n        elif \"doi\" in entry:\n            url = f'https://doi.org/{entry[\"doi\"]}'\n        else:\n            url = None\n        meta = {\n            \"id\": entry.get(\"ID\"),\n            \"published_year\": entry.get(\"year\"),\n            \"title\": entry.get(\"title\"),\n            \"publication\": publication,\n            \"authors\": entry.get(\"author\"),\n            \"abstract\": entry.get(\"abstract\"),\n            \"url\": url,\n        }\n        if load_extra:\n            for field in OPTIONAL_FIELDS:\n                meta[field] = entry.get(field)\n        return {k: v for k, v in meta.items() if v is not None}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html"}
{"id": "c92ea5ae7da2-0", "text": "Source code for langchain.utilities.gitlab\n\"\"\"Util that calls gitlab.\"\"\"\nfrom __future__ import annotations\nimport json\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\nif TYPE_CHECKING:\n    from gitlab.v4.objects import Issue\n[docs]class GitLabAPIWrapper(BaseModel):\n    \"\"\"Wrapper for GitLab API.\"\"\"\n    gitlab: Any  #: :meta private:\n    gitlab_repo_instance: Any  #: :meta private:\n    gitlab_repository: Optional[str] = None\n    \"\"\"The name of the GitLab repository, in the form {username}/{repo-name}.\"\"\"\n    gitlab_personal_access_token: Optional[str] = None\n    \"\"\"Personal access token for the GitLab service, used for authentication.\"\"\"\n    gitlab_branch: Optional[str] = None\n    \"\"\"The specific branch in the GitLab repository where the bot will make \n        its commits. Defaults to 'main'.\n    \"\"\"\n    gitlab_base_branch: Optional[str] = None\n    \"\"\"The base branch in the GitLab repository, used for comparisons. \n        Usually 'main' or 'master'. Defaults to 'main'.\n    \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        gitlab_repository = get_from_dict_or_env(\n            values, \"gitlab_repository\", \"GITLAB_REPOSITORY\"\n        )\n        gitlab_personal_access_token = get_from_dict_or_env(\n            values, \"gitlab_personal_access_token\", \"GITLAB_PERSONAL_ACCESS_TOKEN\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html"}
{"id": "c92ea5ae7da2-1", "text": "values, \"gitlab_personal_access_token\", \"GITLAB_PERSONAL_ACCESS_TOKEN\"\n        )\n        gitlab_branch = get_from_dict_or_env(\n            values, \"gitlab_branch\", \"GITLAB_BRANCH\", default=\"main\"\n        )\n        gitlab_base_branch = get_from_dict_or_env(\n            values, \"gitlab_base_branch\", \"GITLAB_BASE_BRANCH\", default=\"main\"\n        )\n        try:\n            import gitlab\n        except ImportError:\n            raise ImportError(\n                \"python-gitlab is not installed. \"\n                \"Please install it with `pip install python-gitlab`\"\n            )\n        g = gitlab.Gitlab(private_token=gitlab_personal_access_token)\n        g.auth()\n        values[\"gitlab\"] = g\n        values[\"gitlab_repo_instance\"] = g.projects.get(gitlab_repository)\n        values[\"gitlab_repository\"] = gitlab_repository\n        values[\"gitlab_personal_access_token\"] = gitlab_personal_access_token\n        values[\"gitlab_branch\"] = gitlab_branch\n        values[\"gitlab_base_branch\"] = gitlab_base_branch\n        return values\n[docs]    def parse_issues(self, issues: List[Issue]) -> List[dict]:\n        \"\"\"\n        Extracts title and number from each Issue and puts them in a dictionary\n        Parameters:\n            issues(List[Issue]): A list of gitlab Issue objects\n        Returns:\n            List[dict]: A dictionary of issue titles and numbers\n        \"\"\"\n        parsed = []\n        for issue in issues:\n            title = issue.title\n            number = issue.iid\n            parsed.append({\"title\": title, \"number\": number})\n        return parsed\n[docs]    def get_issues(self) -> str:\n        \"\"\"\n        Fetches all open issues from the repo\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html"}
{"id": "c92ea5ae7da2-2", "text": "\"\"\"\n        Fetches all open issues from the repo\n        Returns:\n            str: A plaintext report containing the number of issues\n            and each issue's title and number.\n        \"\"\"\n        issues = self.gitlab_repo_instance.issues.list(state=\"opened\")\n        if len(issues) > 0:\n            parsed_issues = self.parse_issues(issues)\n            parsed_issues_str = (\n                \"Found \" + str(len(parsed_issues)) + \" issues:\\n\" + str(parsed_issues)\n            )\n            return parsed_issues_str\n        else:\n            return \"No open issues available\"\n[docs]    def get_issue(self, issue_number: int) -> Dict[str, Any]:\n        \"\"\"\n        Fetches a specific issue and its first 10 comments\n        Parameters:\n            issue_number(int): The number for the gitlab issue\n        Returns:\n            dict: A dictionary containing the issue's title,\n            body, and comments as a string\n        \"\"\"\n        issue = self.gitlab_repo_instance.issues.get(issue_number)\n        page = 0\n        comments: List[dict] = []\n        while len(comments) <= 10:\n            comments_page = issue.notes.list(page=page)\n            if len(comments_page) == 0:\n                break\n            for comment in comments_page:\n                comment = issue.notes.get(comment.id)\n                comments.append(\n                    {\"body\": comment.body, \"user\": comment.author[\"username\"]}\n                )\n            page += 1\n        return {\n            \"title\": issue.title,\n            \"body\": issue.description,\n            \"comments\": str(comments),\n        }\n[docs]    def create_pull_request(self, pr_query: str) -> str:\n        \"\"\"\n        Makes a pull request from the bot's branch to the base branch", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html"}
{"id": "c92ea5ae7da2-3", "text": "\"\"\"\n        Makes a pull request from the bot's branch to the base branch\n        Parameters:\n            pr_query(str): a string which contains the PR title\n            and the PR body. The title is the first line\n            in the string, and the body are the rest of the string.\n            For example, \"Updated README\\nmade changes to add info\"\n        Returns:\n            str: A success or failure message\n        \"\"\"\n        if self.gitlab_base_branch == self.gitlab_branch:\n            return \"\"\"Cannot make a pull request because \n            commits are already in the master branch\"\"\"\n        else:\n            try:\n                title = pr_query.split(\"\\n\")[0]\n                body = pr_query[len(title) + 2 :]\n                pr = self.gitlab_repo_instance.mergerequests.create(\n                    {\n                        \"source_branch\": self.gitlab_branch,\n                        \"target_branch\": self.gitlab_base_branch,\n                        \"title\": title,\n                        \"description\": body,\n                        \"labels\": [\"created-by-agent\"],\n                    }\n                )\n                return f\"Successfully created PR number {pr.iid}\"\n            except Exception as e:\n                return \"Unable to make pull request due to error:\\n\" + str(e)\n[docs]    def comment_on_issue(self, comment_query: str) -> str:\n        \"\"\"\n        Adds a comment to a gitlab issue\n        Parameters:\n            comment_query(str): a string which contains the issue number,\n            two newlines, and the comment.\n            for example: \"1\\n\\nWorking on it now\"\n            adds the comment \"working on it now\" to issue 1\n        Returns:\n            str: A success or failure message\n        \"\"\"\n        issue_number = int(comment_query.split(\"\\n\\n\")[0])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html"}
{"id": "c92ea5ae7da2-4", "text": "\"\"\"\n        issue_number = int(comment_query.split(\"\\n\\n\")[0])\n        comment = comment_query[len(str(issue_number)) + 2 :]\n        try:\n            issue = self.gitlab_repo_instance.issues.get(issue_number)\n            issue.notes.create({\"body\": comment})\n            return \"Commented on issue \" + str(issue_number)\n        except Exception as e:\n            return \"Unable to make comment due to error:\\n\" + str(e)\n[docs]    def create_file(self, file_query: str) -> str:\n        \"\"\"\n        Creates a new file on the gitlab repo\n        Parameters:\n            file_query(str): a string which contains the file path\n            and the file contents. The file path is the first line\n            in the string, and the contents are the rest of the string.\n            For example, \"hello_world.md\\n# Hello World!\"\n        Returns:\n            str: A success or failure message\n        \"\"\"\n        file_path = file_query.split(\"\\n\")[0]\n        file_contents = file_query[len(file_path) + 2 :]\n        try:\n            self.gitlab_repo_instance.files.get(file_path, self.gitlab_branch)\n            return f\"File already exists at {file_path}. Use update_file instead\"\n        except Exception:\n            data = {\n                \"branch\": self.gitlab_branch,\n                \"commit_message\": \"Create \" + file_path,\n                \"file_path\": file_path,\n                \"content\": file_contents,\n            }\n            self.gitlab_repo_instance.files.create(data)\n            return \"Created file \" + file_path\n[docs]    def read_file(self, file_path: str) -> str:\n        \"\"\"\n        Reads a file from the gitlab repo\n        Parameters:\n            file_path(str): the file path\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html"}
{"id": "c92ea5ae7da2-5", "text": "Parameters:\n            file_path(str): the file path\n        Returns:\n            str: The file decoded as a string\n        \"\"\"\n        file = self.gitlab_repo_instance.files.get(file_path, self.gitlab_branch)\n        return file.decode().decode(\"utf-8\")\n[docs]    def update_file(self, file_query: str) -> str:\n        \"\"\"\n        Updates a file with new content.\n        Parameters:\n            file_query(str): Contains the file path and the file contents.\n                The old file contents is wrapped in OLD <<<< and >>>> OLD\n                The new file contents is wrapped in NEW <<<< and >>>> NEW\n                For example:\n                test/hello.txt\n                OLD <<<<\n                Hello Earth!\n                >>>> OLD\n                NEW <<<<\n                Hello Mars!\n                >>>> NEW\n        Returns:\n            A success or failure message\n        \"\"\"\n        try:\n            file_path = file_query.split(\"\\n\")[0]\n            old_file_contents = (\n                file_query.split(\"OLD <<<<\")[1].split(\">>>> OLD\")[0].strip()\n            )\n            new_file_contents = (\n                file_query.split(\"NEW <<<<\")[1].split(\">>>> NEW\")[0].strip()\n            )\n            file_content = self.read_file(file_path)\n            updated_file_content = file_content.replace(\n                old_file_contents, new_file_contents\n            )\n            if file_content == updated_file_content:\n                return (\n                    \"File content was not updated because old content was not found.\"\n                    \"It may be helpful to use the read_file action to get \"\n                    \"the current file contents.\"\n                )\n            commit = {\n                \"branch\": self.gitlab_branch,\n                \"commit_message\": \"Create \" + file_path,\n                \"actions\": [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html"}
{"id": "c92ea5ae7da2-6", "text": "\"commit_message\": \"Create \" + file_path,\n                \"actions\": [\n                    {\n                        \"action\": \"update\",\n                        \"file_path\": file_path,\n                        \"content\": updated_file_content,\n                    }\n                ],\n            }\n            self.gitlab_repo_instance.commits.create(commit)\n            return \"Updated file \" + file_path\n        except Exception as e:\n            return \"Unable to update file due to error:\\n\" + str(e)\n[docs]    def delete_file(self, file_path: str) -> str:\n        \"\"\"\n        Deletes a file from the repo\n        Parameters:\n            file_path(str): Where the file is\n        Returns:\n            str: Success or failure message\n        \"\"\"\n        try:\n            self.gitlab_repo_instance.files.delete(\n                file_path, self.gitlab_branch, \"Delete \" + file_path\n            )\n            return \"Deleted file \" + file_path\n        except Exception as e:\n            return \"Unable to delete file due to error:\\n\" + str(e)\n[docs]    def run(self, mode: str, query: str) -> str:\n        if mode == \"get_issues\":\n            return self.get_issues()\n        elif mode == \"get_issue\":\n            return json.dumps(self.get_issue(int(query)))\n        elif mode == \"comment_on_issue\":\n            return self.comment_on_issue(query)\n        elif mode == \"create_file\":\n            return self.create_file(query)\n        elif mode == \"create_pull_request\":\n            return self.create_pull_request(query)\n        elif mode == \"read_file\":\n            return self.read_file(query)\n        elif mode == \"update_file\":\n            return self.update_file(query)\n        elif mode == \"delete_file\":\n            return self.delete_file(query)\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html"}
{"id": "c92ea5ae7da2-7", "text": "return self.delete_file(query)\n        else:\n            raise ValueError(\"Invalid mode\" + mode)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html"}
{"id": "400e031c6e54-0", "text": "Source code for langchain.utilities.clickup\n\"\"\"Util that calls clickup.\"\"\"\nimport json\nimport warnings\nfrom dataclasses import asdict, dataclass, fields\nfrom typing import Any, Dict, List, Mapping, Optional, Tuple, Type, Union\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\nDEFAULT_URL = \"https://api.clickup.com/api/v2\"\n[docs]@dataclass\nclass Component:\n    \"\"\"Base class for all components.\"\"\"\n[docs]    @classmethod\n    def from_data(cls, data: Dict[str, Any]) -> \"Component\":\n        raise NotImplementedError()\n[docs]@dataclass\nclass Task(Component):\n    \"\"\"Class for a task.\"\"\"\n    id: int\n    name: str\n    text_content: str\n    description: str\n    status: str\n    creator_id: int\n    creator_username: str\n    creator_email: str\n    assignees: List[Dict[str, Any]]\n    watchers: List[Dict[str, Any]]\n    priority: Optional[str]\n    due_date: Optional[str]\n    start_date: Optional[str]\n    points: int\n    team_id: int\n    project_id: int\n[docs]    @classmethod\n    def from_data(cls, data: Dict[str, Any]) -> \"Task\":\n        priority = None if data[\"priority\"] is None else data[\"priority\"][\"priority\"]\n        return cls(\n            id=data[\"id\"],\n            name=data[\"name\"],\n            text_content=data[\"text_content\"],\n            description=data[\"description\"],\n            status=data[\"status\"][\"status\"],\n            creator_id=data[\"creator\"][\"id\"],\n            creator_username=data[\"creator\"][\"username\"],\n            creator_email=data[\"creator\"][\"email\"],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "400e031c6e54-1", "text": "creator_username=data[\"creator\"][\"username\"],\n            creator_email=data[\"creator\"][\"email\"],\n            assignees=data[\"assignees\"],\n            watchers=data[\"watchers\"],\n            priority=priority,\n            due_date=data[\"due_date\"],\n            start_date=data[\"start_date\"],\n            points=data[\"points\"],\n            team_id=data[\"team_id\"],\n            project_id=data[\"project\"][\"id\"],\n        )\n[docs]@dataclass\nclass CUList(Component):\n    \"\"\"Component class for a list.\"\"\"\n    folder_id: float\n    name: str\n    content: Optional[str] = None\n    due_date: Optional[int] = None\n    due_date_time: Optional[bool] = None\n    priority: Optional[int] = None\n    assignee: Optional[int] = None\n    status: Optional[str] = None\n[docs]    @classmethod\n    def from_data(cls, data: dict) -> \"CUList\":\n        return cls(\n            folder_id=data[\"folder_id\"],\n            name=data[\"name\"],\n            content=data.get(\"content\"),\n            due_date=data.get(\"due_date\"),\n            due_date_time=data.get(\"due_date_time\"),\n            priority=data.get(\"priority\"),\n            assignee=data.get(\"assignee\"),\n            status=data.get(\"status\"),\n        )\n[docs]@dataclass\nclass Member(Component):\n    \"\"\"Component class for a member.\"\"\"\n    id: int\n    username: str\n    email: str\n    initials: str\n[docs]    @classmethod\n    def from_data(cls, data: Dict) -> \"Member\":\n        return cls(\n            id=data[\"user\"][\"id\"],\n            username=data[\"user\"][\"username\"],\n            email=data[\"user\"][\"email\"],\n            initials=data[\"user\"][\"initials\"],\n        )\n[docs]@dataclass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "400e031c6e54-2", "text": "initials=data[\"user\"][\"initials\"],\n        )\n[docs]@dataclass\nclass Team(Component):\n    \"\"\"Component class for a team.\"\"\"\n    id: int\n    name: str\n    members: List[Member]\n[docs]    @classmethod\n    def from_data(cls, data: Dict) -> \"Team\":\n        members = [Member.from_data(member_data) for member_data in data[\"members\"]]\n        return cls(id=data[\"id\"], name=data[\"name\"], members=members)\n[docs]@dataclass\nclass Space(Component):\n    \"\"\"Component class for a space.\"\"\"\n    id: int\n    name: str\n    private: bool\n    enabled_features: Dict[str, Any]\n[docs]    @classmethod\n    def from_data(cls, data: Dict[str, Any]) -> \"Space\":\n        space_data = data[\"spaces\"][0]\n        enabled_features = {\n            feature: value\n            for feature, value in space_data[\"features\"].items()\n            if value[\"enabled\"]\n        }\n        return cls(\n            id=space_data[\"id\"],\n            name=space_data[\"name\"],\n            private=space_data[\"private\"],\n            enabled_features=enabled_features,\n        )\n[docs]def parse_dict_through_component(\n    data: dict, component: Type[Component], fault_tolerant: bool = False\n) -> Dict:\n    \"\"\"Parse a dictionary by creating\n    a component and then turning it back into a dictionary.\n    This helps with two things\n    1. Extract and format data from a dictionary according to schema\n    2. Provide a central place to do this in a fault-tolerant way\n    \"\"\"\n    try:\n        return asdict(component.from_data(data))\n    except Exception as e:\n        if fault_tolerant:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "400e031c6e54-3", "text": "except Exception as e:\n        if fault_tolerant:\n            warning_str = f\"\"\"Error encountered while trying to parse\n{str(data)}: {str(e)}\\n Falling back to returning input data.\"\"\"\n            warnings.warn(warning_str)\n            return data\n        else:\n            raise e\n[docs]def extract_dict_elements_from_component_fields(\n    data: dict, component: Type[Component]\n) -> dict:\n    \"\"\"Extract elements from a dictionary.\n    Args:\n        data: The dictionary to extract elements from.\n        component: The component to extract elements from.\n    Returns:\n        A dictionary containing the elements from the input dictionary that are also\n        in the component.\n    \"\"\"\n    output = {}\n    for attribute in fields(component):\n        if attribute.name in data:\n            output[attribute.name] = data[attribute.name]\n    return output\n[docs]def load_query(\n    query: str, fault_tolerant: bool = False\n) -> Tuple[Optional[Dict], Optional[str]]:\n    \"\"\"Attempts to parse a JSON string and return the parsed object.\n    If parsing fails, returns an error message.\n    :param query: The JSON string to parse.\n    :return: A tuple containing the parsed object or None and an error message or None.\n    \"\"\"\n    try:\n        return json.loads(query), None\n    except json.JSONDecodeError as e:\n        if fault_tolerant:\n            return (\n                None,\n                f\"\"\"Input must be a valid JSON. Got the following error: {str(e)}. \n\"Please reformat and try again.\"\"\",\n            )\n        else:\n            raise e\n[docs]def fetch_first_id(data: dict, key: str) -> Optional[int]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "400e031c6e54-4", "text": "[docs]def fetch_first_id(data: dict, key: str) -> Optional[int]:\n    \"\"\"Fetch the first id from a dictionary.\"\"\"\n    if key in data and len(data[key]) > 0:\n        if len(data[key]) > 1:\n            warnings.warn(f\"Found multiple {key}: {data[key]}. Defaulting to first.\")\n        return data[key][0][\"id\"]\n    return None\n[docs]def fetch_data(url: str, access_token: str, query: Optional[dict] = None) -> dict:\n    \"\"\"Fetch data from a URL.\"\"\"\n    headers = {\"Authorization\": access_token}\n    response = requests.get(url, headers=headers, params=query)\n    response.raise_for_status()\n    return response.json()\n[docs]def fetch_team_id(access_token: str) -> Optional[int]:\n    \"\"\"Fetch the team id.\"\"\"\n    url = f\"{DEFAULT_URL}/team\"\n    data = fetch_data(url, access_token)\n    return fetch_first_id(data, \"teams\")\n[docs]def fetch_space_id(team_id: int, access_token: str) -> Optional[int]:\n    \"\"\"Fetch the space id.\"\"\"\n    url = f\"{DEFAULT_URL}/team/{team_id}/space\"\n    data = fetch_data(url, access_token, query={\"archived\": \"false\"})\n    return fetch_first_id(data, \"spaces\")\n[docs]def fetch_folder_id(space_id: int, access_token: str) -> Optional[int]:\n    \"\"\"Fetch the folder id.\"\"\"\n    url = f\"{DEFAULT_URL}/space/{space_id}/folder\"\n    data = fetch_data(url, access_token, query={\"archived\": \"false\"})\n    return fetch_first_id(data, \"folders\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "400e031c6e54-5", "text": "return fetch_first_id(data, \"folders\")\n[docs]def fetch_list_id(space_id: int, folder_id: int, access_token: str) -> Optional[int]:\n    \"\"\"Fetch the list id.\"\"\"\n    if folder_id:\n        url = f\"{DEFAULT_URL}/folder/{folder_id}/list\"\n    else:\n        url = f\"{DEFAULT_URL}/space/{space_id}/list\"\n    data = fetch_data(url, access_token, query={\"archived\": \"false\"})\n    # The structure to fetch list id differs based if its folderless\n    if folder_id and \"id\" in data:\n        return data[\"id\"]\n    else:\n        return fetch_first_id(data, \"lists\")\n[docs]class ClickupAPIWrapper(BaseModel):\n    \"\"\"Wrapper for Clickup API.\"\"\"\n    access_token: Optional[str] = None\n    team_id: Optional[str] = None\n    space_id: Optional[str] = None\n    folder_id: Optional[str] = None\n    list_id: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n[docs]    @classmethod\n    def get_access_code_url(\n        cls, oauth_client_id: str, redirect_uri: str = \"https://google.com\"\n    ) -> str:\n        \"\"\"Get the URL to get an access code.\"\"\"\n        url = f\"https://app.clickup.com/api?client_id={oauth_client_id}\"\n        return f\"{url}&redirect_uri={redirect_uri}\"\n[docs]    @classmethod\n    def get_access_token(\n        cls, oauth_client_id: str, oauth_client_secret: str, code: str\n    ) -> Optional[str]:\n        \"\"\"Get the access token.\"\"\"\n        url = f\"{DEFAULT_URL}/oauth/token\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "400e031c6e54-6", "text": "\"\"\"Get the access token.\"\"\"\n        url = f\"{DEFAULT_URL}/oauth/token\"\n        params = {\n            \"client_id\": oauth_client_id,\n            \"client_secret\": oauth_client_secret,\n            \"code\": code,\n        }\n        response = requests.post(url, params=params)\n        data = response.json()\n        if \"access_token\" not in data:\n            print(f\"Error: {data}\")\n            if \"ECODE\" in data and data[\"ECODE\"] == \"OAUTH_014\":\n                url = ClickupAPIWrapper.get_access_code_url(oauth_client_id)\n                print(\n                    \"You already used this code once. Generate a new one.\",\n                    f\"Our best guess for the url to get a new code is:\\n{url}\",\n                )\n            return None\n        return data[\"access_token\"]\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"access_token\"] = get_from_dict_or_env(\n            values, \"access_token\", \"CLICKUP_ACCESS_TOKEN\"\n        )\n        values[\"team_id\"] = fetch_team_id(values[\"access_token\"])\n        values[\"space_id\"] = fetch_space_id(values[\"team_id\"], values[\"access_token\"])\n        values[\"folder_id\"] = fetch_folder_id(\n            values[\"space_id\"], values[\"access_token\"]\n        )\n        values[\"list_id\"] = fetch_list_id(\n            values[\"space_id\"], values[\"folder_id\"], values[\"access_token\"]\n        )\n        return values\n[docs]    def attempt_parse_teams(self, input_dict: dict) -> Dict[str, List[dict]]:\n        \"\"\"Parse appropriate content from the list of teams.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "400e031c6e54-7", "text": "\"\"\"Parse appropriate content from the list of teams.\"\"\"\n        parsed_teams: Dict[str, List[dict]] = {\"teams\": []}\n        for team in input_dict[\"teams\"]:\n            try:\n                team = parse_dict_through_component(team, Team, fault_tolerant=False)\n                parsed_teams[\"teams\"].append(team)\n            except Exception as e:\n                warnings.warn(f\"Error parsing a team {e}\")\n        return parsed_teams\n[docs]    def get_headers(\n        self,\n    ) -> Mapping[str, Union[str, bytes]]:\n        \"\"\"Get the headers for the request.\"\"\"\n        if not isinstance(self.access_token, str):\n            raise TypeError(f\"Access Token: {self.access_token}, must be str.\")\n        headers = {\n            \"Authorization\": str(self.access_token),\n            \"Content-Type\": \"application/json\",\n        }\n        return headers\n[docs]    def get_default_params(self) -> Dict:\n        return {\"archived\": \"false\"}\n[docs]    def get_authorized_teams(self) -> Dict[Any, Any]:\n        \"\"\"Get all teams for the user.\"\"\"\n        url = f\"{DEFAULT_URL}/team\"\n        response = requests.get(url, headers=self.get_headers())\n        data = response.json()\n        parsed_teams = self.attempt_parse_teams(data)\n        return parsed_teams\n[docs]    def get_folders(self) -> Dict:\n        \"\"\"\n        Get all the folders for the team.\n        \"\"\"\n        url = f\"{DEFAULT_URL}/team/\" + str(self.team_id) + \"/space\"\n        params = self.get_default_params()\n        response = requests.get(url, headers=self.get_headers(), params=params)\n        return {\"response\": response}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "400e031c6e54-8", "text": "return {\"response\": response}\n[docs]    def get_task(self, query: str, fault_tolerant: bool = True) -> Dict:\n        \"\"\"\n        Retrieve a specific task.\n        \"\"\"\n        params, error = load_query(query, fault_tolerant=True)\n        if params is None:\n            return {\"Error\": error}\n        url = f\"{DEFAULT_URL}/task/{params['task_id']}\"\n        params = {\n            \"custom_task_ids\": \"true\",\n            \"team_id\": self.team_id,\n            \"include_subtasks\": \"true\",\n        }\n        response = requests.get(url, headers=self.get_headers(), params=params)\n        data = response.json()\n        parsed_task = parse_dict_through_component(\n            data, Task, fault_tolerant=fault_tolerant\n        )\n        return parsed_task\n[docs]    def get_lists(self) -> Dict:\n        \"\"\"\n        Get all available lists.\n        \"\"\"\n        url = f\"{DEFAULT_URL}/folder/{self.folder_id}/list\"\n        params = self.get_default_params()\n        response = requests.get(url, headers=self.get_headers(), params=params)\n        return {\"response\": response}\n[docs]    def query_tasks(self, query: str) -> Dict:\n        \"\"\"\n        Query tasks that match certain fields\n        \"\"\"\n        params, error = load_query(query, fault_tolerant=True)\n        if params is None:\n            return {\"Error\": error}\n        url = f\"{DEFAULT_URL}/list/{params['list_id']}/task\"\n        params = self.get_default_params()\n        response = requests.get(url, headers=self.get_headers(), params=params)\n        return {\"response\": response}\n[docs]    def get_spaces(self) -> Dict:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "400e031c6e54-9", "text": "[docs]    def get_spaces(self) -> Dict:\n        \"\"\"\n        Get all spaces for the team.\n        \"\"\"\n        url = f\"{DEFAULT_URL}/team/{self.team_id}/space\"\n        response = requests.get(\n            url, headers=self.get_headers(), params=self.get_default_params()\n        )\n        data = response.json()\n        parsed_spaces = parse_dict_through_component(data, Space, fault_tolerant=True)\n        return parsed_spaces\n[docs]    def get_task_attribute(self, query: str) -> Dict:\n        \"\"\"\n        Update an attribute of a specified task.\n        \"\"\"\n        task = self.get_task(query, fault_tolerant=True)\n        params, error = load_query(query, fault_tolerant=True)\n        if not isinstance(params, dict):\n            return {\"Error\": error}\n        if params[\"attribute_name\"] not in task:\n            return {\n                \"Error\": f\"\"\"attribute_name = {params['attribute_name']} was not \nfound in task keys {task.keys()}. Please call again with one of the key names.\"\"\"\n            }\n        return {params[\"attribute_name\"]: task[params[\"attribute_name\"]]}\n[docs]    def update_task(self, query: str) -> Dict:\n        \"\"\"\n        Update an attribute of a specified task.\n        \"\"\"\n        query_dict, error = load_query(query, fault_tolerant=True)\n        if query_dict is None:\n            return {\"Error\": error}\n        url = f\"{DEFAULT_URL}/task/{query_dict['task_id']}\"\n        params = {\n            \"custom_task_ids\": \"true\",\n            \"team_id\": self.team_id,\n            \"include_subtasks\": \"true\",\n        }\n        headers = self.get_headers()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "400e031c6e54-10", "text": "}\n        headers = self.get_headers()\n        payload = {query_dict[\"attribute_name\"]: query_dict[\"value\"]}\n        response = requests.put(url, headers=headers, params=params, json=payload)\n        return {\"response\": response}\n[docs]    def update_task_assignees(self, query: str) -> Dict:\n        \"\"\"\n        Add or remove assignees of a specified task.\n        \"\"\"\n        query_dict, error = load_query(query, fault_tolerant=True)\n        if query_dict is None:\n            return {\"Error\": error}\n        for user in query_dict[\"users\"]:\n            if not isinstance(user, int):\n                return {\n                    \"Error\": f\"\"\"All users must be integers, not strings!\n\"Got user {user} if type {type(user)}\"\"\"\n                }\n        url = f\"{DEFAULT_URL}/task/{query_dict['task_id']}\"\n        headers = self.get_headers()\n        if query_dict[\"operation\"] == \"add\":\n            assigne_payload = {\"add\": query_dict[\"users\"], \"rem\": []}\n        elif query_dict[\"operation\"] == \"rem\":\n            assigne_payload = {\"add\": [], \"rem\": query_dict[\"users\"]}\n        else:\n            raise ValueError(\n                f\"Invalid operation ({query_dict['operation']}). \",\n                \"Valid options ['add', 'rem'].\",\n            )\n        params = {\n            \"custom_task_ids\": \"true\",\n            \"team_id\": self.team_id,\n            \"include_subtasks\": \"true\",\n        }\n        payload = {\"assignees\": assigne_payload}\n        response = requests.put(url, headers=headers, params=params, json=payload)\n        return {\"response\": response}\n[docs]    def create_task(self, query: str) -> Dict:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "400e031c6e54-11", "text": "[docs]    def create_task(self, query: str) -> Dict:\n        \"\"\"\n        Creates a new task.\n        \"\"\"\n        query_dict, error = load_query(query, fault_tolerant=True)\n        if query_dict is None:\n            return {\"Error\": error}\n        list_id = self.list_id\n        url = f\"{DEFAULT_URL}/list/{list_id}/task\"\n        params = {\"custom_task_ids\": \"true\", \"team_id\": self.team_id}\n        payload = extract_dict_elements_from_component_fields(query_dict, Task)\n        headers = self.get_headers()\n        response = requests.post(url, json=payload, headers=headers, params=params)\n        data: Dict = response.json()\n        return parse_dict_through_component(data, Task, fault_tolerant=True)\n[docs]    def create_list(self, query: str) -> Dict:\n        \"\"\"\n        Creates a new list.\n        \"\"\"\n        query_dict, error = load_query(query, fault_tolerant=True)\n        if query_dict is None:\n            return {\"Error\": error}\n        # Default to using folder as location if it exists.\n        # If not, fall back to using the space.\n        location = self.folder_id if self.folder_id else self.space_id\n        url = f\"{DEFAULT_URL}/folder/{location}/list\"\n        payload = extract_dict_elements_from_component_fields(query_dict, Task)\n        headers = self.get_headers()\n        response = requests.post(url, json=payload, headers=headers)\n        data = response.json()\n        parsed_list = parse_dict_through_component(data, CUList, fault_tolerant=True)\n        # set list id to new list\n        if \"id\" in parsed_list:\n            self.list_id = parsed_list[\"id\"]\n        return parsed_list", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "400e031c6e54-12", "text": "self.list_id = parsed_list[\"id\"]\n        return parsed_list\n[docs]    def create_folder(self, query: str) -> Dict:\n        \"\"\"\n        Creates a new folder.\n        \"\"\"\n        query_dict, error = load_query(query, fault_tolerant=True)\n        if query_dict is None:\n            return {\"Error\": error}\n        space_id = self.space_id\n        url = f\"{DEFAULT_URL}/space/{space_id}/folder\"\n        payload = {\n            \"name\": query_dict[\"name\"],\n        }\n        headers = self.get_headers()\n        response = requests.post(url, json=payload, headers=headers)\n        data = response.json()\n        if \"id\" in data:\n            self.list_id = data[\"id\"]\n        return data\n[docs]    def run(self, mode: str, query: str) -> str:\n        \"\"\"Run the API.\"\"\"\n        if mode == \"get_task\":\n            output = self.get_task(query)\n        elif mode == \"get_task_attribute\":\n            output = self.get_task_attribute(query)\n        elif mode == \"get_teams\":\n            output = self.get_authorized_teams()\n        elif mode == \"create_task\":\n            output = self.create_task(query)\n        elif mode == \"create_list\":\n            output = self.create_list(query)\n        elif mode == \"create_folder\":\n            output = self.create_folder(query)\n        elif mode == \"get_lists\":\n            output = self.get_lists()\n        elif mode == \"get_folders\":\n            output = self.get_folders()\n        elif mode == \"get_spaces\":\n            output = self.get_spaces()\n        elif mode == \"update_task\":\n            output = self.update_task(query)\n        elif mode == \"update_task_assignees\":", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "400e031c6e54-13", "text": "output = self.update_task(query)\n        elif mode == \"update_task_assignees\":\n            output = self.update_task_assignees(query)\n        else:\n            output = {\"ModeError\": f\"Got unexpected mode {mode}.\"}\n        try:\n            return json.dumps(output)\n        except Exception:\n            return str(output)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html"}
{"id": "8a8bf348b1c9-0", "text": "Source code for langchain.utilities.vertexai\n\"\"\"Utilities to init Vertex AI.\"\"\"\nfrom importlib import metadata\nfrom typing import TYPE_CHECKING, Optional\nif TYPE_CHECKING:\n    from google.api_core.gapic_v1.client_info import ClientInfo\n    from google.auth.credentials import Credentials\n[docs]def raise_vertex_import_error(minimum_expected_version: str = \"1.35.0\") -> None:\n    \"\"\"Raise ImportError related to Vertex SDK being not available.\n    Args:\n        minimum_expected_version: The lowest expected version of the SDK.\n    Raises:\n        ImportError: an ImportError that mentions a required version of the SDK.\n    \"\"\"\n    raise ImportError(\n        \"Could not import VertexAI. Please, install it with \"\n        f\"pip install google-cloud-aiplatform>={minimum_expected_version}\"\n    )\n[docs]def init_vertexai(\n    project: Optional[str] = None,\n    location: Optional[str] = None,\n    credentials: Optional[\"Credentials\"] = None,\n) -> None:\n    \"\"\"Init vertexai.\n    Args:\n        project: The default GCP project to use when making Vertex API calls.\n        location: The default location to use when making API calls.\n        credentials: The default custom\n            credentials to use when making API calls. If not provided credentials\n            will be ascertained from the environment.\n    Raises:\n        ImportError: If importing vertexai SDK did not succeed.\n    \"\"\"\n    try:\n        import vertexai\n    except ImportError:\n        raise_vertex_import_error()\n    vertexai.init(\n        project=project,\n        location=location,\n        credentials=credentials,\n    )\n[docs]def get_client_info(module: Optional[str] = None) -> \"ClientInfo\":\n    r\"\"\"Returns a custom user agent header.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/vertexai.html"}
{"id": "8a8bf348b1c9-1", "text": "r\"\"\"Returns a custom user agent header.\n    Args:\n        module (Optional[str]):\n            Optional. The module for a custom user agent header.\n    Returns:\n        google.api_core.gapic_v1.client_info.ClientInfo\n    \"\"\"\n    try:\n        from google.api_core.gapic_v1.client_info import ClientInfo\n    except ImportError as exc:\n        raise ImportError(\n            \"Could not import ClientInfo. Please, install it with \"\n            \"pip install google-api-core\"\n        ) from exc\n    langchain_version = metadata.version(\"langchain\")\n    client_library_version = (\n        f\"{langchain_version}-{module}\" if module else langchain_version\n    )\n    return ClientInfo(\n        client_library_version=client_library_version,\n        user_agent=f\"langchain/{client_library_version}\",\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/vertexai.html"}
{"id": "20f76d333997-0", "text": "Source code for langchain.utilities.apify\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema.document import Document\nfrom langchain.utils import get_from_dict_or_env\nif TYPE_CHECKING:\n    from langchain.document_loaders import ApifyDatasetLoader\n[docs]class ApifyWrapper(BaseModel):\n    \"\"\"Wrapper around Apify.\n    To use, you should have the ``apify-client`` python package installed,\n    and the environment variable ``APIFY_API_TOKEN`` set with your API key, or pass\n    `apify_api_token` as a named parameter to the constructor.\n    \"\"\"\n    apify_client: Any\n    apify_client_async: Any\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate environment.\n        Validate that an Apify API token is set and the apify-client\n        Python package exists in the current environment.\n        \"\"\"\n        apify_api_token = get_from_dict_or_env(\n            values, \"apify_api_token\", \"APIFY_API_TOKEN\"\n        )\n        try:\n            from apify_client import ApifyClient, ApifyClientAsync\n            values[\"apify_client\"] = ApifyClient(apify_api_token)\n            values[\"apify_client_async\"] = ApifyClientAsync(apify_api_token)\n        except ImportError:\n            raise ImportError(\n                \"Could not import apify-client Python package. \"\n                \"Please install it with `pip install apify-client`.\"\n            )\n        return values\n[docs]    def call_actor(\n        self,\n        actor_id: str,\n        run_input: Dict,\n        dataset_mapping_function: Callable[[Dict], Document],\n        *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html"}
{"id": "20f76d333997-1", "text": "dataset_mapping_function: Callable[[Dict], Document],\n        *,\n        build: Optional[str] = None,\n        memory_mbytes: Optional[int] = None,\n        timeout_secs: Optional[int] = None,\n    ) -> \"ApifyDatasetLoader\":\n        \"\"\"Run an Actor on the Apify platform and wait for results to be ready.\n        Args:\n            actor_id (str): The ID or name of the Actor on the Apify platform.\n            run_input (Dict): The input object of the Actor that you're trying to run.\n            dataset_mapping_function (Callable): A function that takes a single\n                dictionary (an Apify dataset item) and converts it to an\n                instance of the Document class.\n            build (str, optional): Optionally specifies the actor build to run.\n                It can be either a build tag or build number.\n            memory_mbytes (int, optional): Optional memory limit for the run,\n                in megabytes.\n            timeout_secs (int, optional): Optional timeout for the run, in seconds.\n        Returns:\n            ApifyDatasetLoader: A loader that will fetch the records from the\n                Actor run's default dataset.\n        \"\"\"\n        from langchain.document_loaders import ApifyDatasetLoader\n        actor_call = self.apify_client.actor(actor_id).call(\n            run_input=run_input,\n            build=build,\n            memory_mbytes=memory_mbytes,\n            timeout_secs=timeout_secs,\n        )\n        return ApifyDatasetLoader(\n            dataset_id=actor_call[\"defaultDatasetId\"],\n            dataset_mapping_function=dataset_mapping_function,\n        )\n[docs]    async def acall_actor(\n        self,\n        actor_id: str,\n        run_input: Dict,\n        dataset_mapping_function: Callable[[Dict], Document],\n        *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html"}
{"id": "20f76d333997-2", "text": "dataset_mapping_function: Callable[[Dict], Document],\n        *,\n        build: Optional[str] = None,\n        memory_mbytes: Optional[int] = None,\n        timeout_secs: Optional[int] = None,\n    ) -> \"ApifyDatasetLoader\":\n        \"\"\"Run an Actor on the Apify platform and wait for results to be ready.\n        Args:\n            actor_id (str): The ID or name of the Actor on the Apify platform.\n            run_input (Dict): The input object of the Actor that you're trying to run.\n            dataset_mapping_function (Callable): A function that takes a single\n                dictionary (an Apify dataset item) and converts it to\n                an instance of the Document class.\n            build (str, optional): Optionally specifies the actor build to run.\n                It can be either a build tag or build number.\n            memory_mbytes (int, optional): Optional memory limit for the run,\n                in megabytes.\n            timeout_secs (int, optional): Optional timeout for the run, in seconds.\n        Returns:\n            ApifyDatasetLoader: A loader that will fetch the records from the\n                Actor run's default dataset.\n        \"\"\"\n        from langchain.document_loaders import ApifyDatasetLoader\n        actor_call = await self.apify_client_async.actor(actor_id).call(\n            run_input=run_input,\n            build=build,\n            memory_mbytes=memory_mbytes,\n            timeout_secs=timeout_secs,\n        )\n        return ApifyDatasetLoader(\n            dataset_id=actor_call[\"defaultDatasetId\"],\n            dataset_mapping_function=dataset_mapping_function,\n        )\n[docs]    def call_actor_task(\n        self,\n        task_id: str,\n        task_input: Dict,\n        dataset_mapping_function: Callable[[Dict], Document],\n        *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html"}
{"id": "20f76d333997-3", "text": "dataset_mapping_function: Callable[[Dict], Document],\n        *,\n        build: Optional[str] = None,\n        memory_mbytes: Optional[int] = None,\n        timeout_secs: Optional[int] = None,\n    ) -> \"ApifyDatasetLoader\":\n        \"\"\"Run a saved Actor task on Apify and wait for results to be ready.\n        Args:\n            task_id (str): The ID or name of the task on the Apify platform.\n            task_input (Dict): The input object of the task that you're trying to run.\n                Overrides the task's saved input.\n            dataset_mapping_function (Callable): A function that takes a single\n                dictionary (an Apify dataset item) and converts it to an\n                instance of the Document class.\n            build (str, optional): Optionally specifies the actor build to run.\n                It can be either a build tag or build number.\n            memory_mbytes (int, optional): Optional memory limit for the run,\n                in megabytes.\n            timeout_secs (int, optional): Optional timeout for the run, in seconds.\n        Returns:\n            ApifyDatasetLoader: A loader that will fetch the records from the\n                task run's default dataset.\n        \"\"\"\n        from langchain.document_loaders import ApifyDatasetLoader\n        task_call = self.apify_client.task(task_id).call(\n            task_input=task_input,\n            build=build,\n            memory_mbytes=memory_mbytes,\n            timeout_secs=timeout_secs,\n        )\n        return ApifyDatasetLoader(\n            dataset_id=task_call[\"defaultDatasetId\"],\n            dataset_mapping_function=dataset_mapping_function,\n        )\n[docs]    async def acall_actor_task(\n        self,\n        task_id: str,\n        task_input: Dict,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html"}
{"id": "20f76d333997-4", "text": "self,\n        task_id: str,\n        task_input: Dict,\n        dataset_mapping_function: Callable[[Dict], Document],\n        *,\n        build: Optional[str] = None,\n        memory_mbytes: Optional[int] = None,\n        timeout_secs: Optional[int] = None,\n    ) -> \"ApifyDatasetLoader\":\n        \"\"\"Run a saved Actor task on Apify and wait for results to be ready.\n        Args:\n            task_id (str): The ID or name of the task on the Apify platform.\n            task_input (Dict): The input object of the task that you're trying to run.\n                Overrides the task's saved input.\n            dataset_mapping_function (Callable): A function that takes a single\n                dictionary (an Apify dataset item) and converts it to an\n                instance of the Document class.\n            build (str, optional): Optionally specifies the actor build to run.\n                It can be either a build tag or build number.\n            memory_mbytes (int, optional): Optional memory limit for the run,\n                in megabytes.\n            timeout_secs (int, optional): Optional timeout for the run, in seconds.\n        Returns:\n            ApifyDatasetLoader: A loader that will fetch the records from the\n                task run's default dataset.\n        \"\"\"\n        from langchain.document_loaders import ApifyDatasetLoader\n        task_call = await self.apify_client_async.task(task_id).call(\n            task_input=task_input,\n            build=build,\n            memory_mbytes=memory_mbytes,\n            timeout_secs=timeout_secs,\n        )\n        return ApifyDatasetLoader(\n            dataset_id=task_call[\"defaultDatasetId\"],\n            dataset_mapping_function=dataset_mapping_function,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html"}
{"id": "4ba5c595deec-0", "text": "Source code for langchain.utilities.scenexplain\n\"\"\"Util that calls SceneXplain.\nIn order to set this up, you need API key for the SceneXplain API.\nYou can obtain a key by following the steps below.\n- Sign up for a free account at https://scenex.jina.ai/.\n- Navigate to the API Access page (https://scenex.jina.ai/api) and create a new API key.\n\"\"\"\nfrom typing import Dict\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, BaseSettings, Field, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class SceneXplainAPIWrapper(BaseSettings, BaseModel):\n    \"\"\"Wrapper for SceneXplain API.\n    In order to set this up, you need API key for the SceneXplain API.\n    You can obtain a key by following the steps below.\n    - Sign up for a free account at https://scenex.jina.ai/.\n    - Navigate to the API Access page (https://scenex.jina.ai/api)\n      and create a new API key.\n    \"\"\"\n    scenex_api_key: str = Field(..., env=\"SCENEX_API_KEY\")\n    scenex_api_url: str = \"https://api.scenex.jina.ai/v1/describe\"\n    def _describe_image(self, image: str) -> str:\n        headers = {\n            \"x-api-key\": f\"token {self.scenex_api_key}\",\n            \"content-type\": \"application/json\",\n        }\n        payload = {\n            \"data\": [\n                {\n                    \"image\": image,\n                    \"algorithm\": \"Ember\",\n                    \"languages\": [\"en\"],\n                }\n            ]\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/scenexplain.html"}
{"id": "4ba5c595deec-1", "text": "\"languages\": [\"en\"],\n                }\n            ]\n        }\n        response = requests.post(self.scenex_api_url, headers=headers, json=payload)\n        response.raise_for_status()\n        result = response.json().get(\"result\", [])\n        img = result[0] if result else {}\n        return img.get(\"text\", \"\")\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key exists in environment.\"\"\"\n        scenex_api_key = get_from_dict_or_env(\n            values, \"scenex_api_key\", \"SCENEX_API_KEY\"\n        )\n        values[\"scenex_api_key\"] = scenex_api_key\n        return values\n[docs]    def run(self, image: str) -> str:\n        \"\"\"Run SceneXplain image explainer.\"\"\"\n        description = self._describe_image(image)\n        if not description:\n            return \"No description found.\"\n        return description", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/scenexplain.html"}
{"id": "68f28c4f559e-0", "text": "Source code for langchain.utilities.openweathermap\n\"\"\"Util that calls OpenWeatherMap using PyOWM.\"\"\"\nfrom typing import Any, Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class OpenWeatherMapAPIWrapper(BaseModel):\n    \"\"\"Wrapper for OpenWeatherMap API using PyOWM.\n    Docs for using:\n    1. Go to OpenWeatherMap and sign up for an API key\n    2. Save your API KEY into OPENWEATHERMAP_API_KEY env variable\n    3. pip install pyowm\n    \"\"\"\n    owm: Any\n    openweathermap_api_key: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key exists in environment.\"\"\"\n        openweathermap_api_key = get_from_dict_or_env(\n            values, \"openweathermap_api_key\", \"OPENWEATHERMAP_API_KEY\"\n        )\n        try:\n            import pyowm\n        except ImportError:\n            raise ImportError(\n                \"pyowm is not installed. Please install it with `pip install pyowm`\"\n            )\n        owm = pyowm.OWM(openweathermap_api_key)\n        values[\"owm\"] = owm\n        return values\n    def _format_weather_info(self, location: str, w: Any) -> str:\n        detailed_status = w.detailed_status\n        wind = w.wind()\n        humidity = w.humidity\n        temperature = w.temperature(\"celsius\")\n        rain = w.rain\n        heat_index = w.heat_index\n        clouds = w.clouds", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html"}
{"id": "68f28c4f559e-1", "text": "heat_index = w.heat_index\n        clouds = w.clouds\n        return (\n            f\"In {location}, the current weather is as follows:\\n\"\n            f\"Detailed status: {detailed_status}\\n\"\n            f\"Wind speed: {wind['speed']} m/s, direction: {wind['deg']}\u00b0\\n\"\n            f\"Humidity: {humidity}%\\n\"\n            f\"Temperature: \\n\"\n            f\"  - Current: {temperature['temp']}\u00b0C\\n\"\n            f\"  - High: {temperature['temp_max']}\u00b0C\\n\"\n            f\"  - Low: {temperature['temp_min']}\u00b0C\\n\"\n            f\"  - Feels like: {temperature['feels_like']}\u00b0C\\n\"\n            f\"Rain: {rain}\\n\"\n            f\"Heat index: {heat_index}\\n\"\n            f\"Cloud cover: {clouds}%\"\n        )\n[docs]    def run(self, location: str) -> str:\n        \"\"\"Get the current weather information for a specified location.\"\"\"\n        mgr = self.owm.weather_manager()\n        observation = mgr.weather_at_place(location)\n        w = observation.weather\n        return self._format_weather_info(location, w)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html"}
{"id": "fd9d6aca7567-0", "text": "Source code for langchain.utilities.anthropic\nfrom typing import Any, List\ndef _get_anthropic_client() -> Any:\n    try:\n        import anthropic\n    except ImportError:\n        raise ImportError(\n            \"Could not import anthropic python package. \"\n            \"This is needed in order to accurately tokenize the text \"\n            \"for anthropic models. Please install it with `pip install anthropic`.\"\n        )\n    return anthropic.Anthropic()\n[docs]def get_num_tokens_anthropic(text: str) -> int:\n    \"\"\"Get the number of tokens in a string of text.\"\"\"\n    client = _get_anthropic_client()\n    return client.count_tokens(text=text)\n[docs]def get_token_ids_anthropic(text: str) -> List[int]:\n    \"\"\"Get the token ids for a string of text.\"\"\"\n    client = _get_anthropic_client()\n    tokenizer = client.get_tokenizer()\n    encoded_text = tokenizer.encode(text)\n    return encoded_text.ids", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/anthropic.html"}
{"id": "d50f2d5f1ea0-0", "text": "Source code for langchain.utilities.twilio\n\"\"\"Util that calls Twilio.\"\"\"\nfrom typing import Any, Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class TwilioAPIWrapper(BaseModel):\n    \"\"\"Messaging Client using Twilio.\n    To use, you should have the ``twilio`` python package installed,\n    and the environment variables ``TWILIO_ACCOUNT_SID``, ``TWILIO_AUTH_TOKEN``, and\n    ``TWILIO_FROM_NUMBER``, or pass `account_sid`, `auth_token`, and `from_number` as\n    named parameters to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.utilities.twilio import TwilioAPIWrapper\n            twilio = TwilioAPIWrapper(\n                account_sid=\"ACxxx\",\n                auth_token=\"xxx\",\n                from_number=\"+10123456789\"\n            )\n            twilio.run('test', '+12484345508')\n    \"\"\"\n    client: Any  #: :meta private:\n    account_sid: Optional[str] = None\n    \"\"\"Twilio account string identifier.\"\"\"\n    auth_token: Optional[str] = None\n    \"\"\"Twilio auth token.\"\"\"\n    from_number: Optional[str] = None\n    \"\"\"A Twilio phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) \n        format, an \n        [alphanumeric sender ID](https://www.twilio.com/docs/sms/send-messages#use-an-alphanumeric-sender-id), \n        or a [Channel Endpoint address](https://www.twilio.com/docs/sms/channels#channel-addresses) \n        that is enabled for the type of message you want to send. Phone numbers or", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html"}
{"id": "d50f2d5f1ea0-1", "text": "that is enabled for the type of message you want to send. Phone numbers or \n        [short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from \n        Twilio also work here. You cannot, for example, spoof messages from a private \n        cell phone number. If you are using `messaging_service_sid`, this parameter \n        must be empty.\n    \"\"\"  # noqa: E501\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = False\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        try:\n            from twilio.rest import Client\n        except ImportError:\n            raise ImportError(\n                \"Could not import twilio python package. \"\n                \"Please install it with `pip install twilio`.\"\n            )\n        account_sid = get_from_dict_or_env(values, \"account_sid\", \"TWILIO_ACCOUNT_SID\")\n        auth_token = get_from_dict_or_env(values, \"auth_token\", \"TWILIO_AUTH_TOKEN\")\n        values[\"from_number\"] = get_from_dict_or_env(\n            values, \"from_number\", \"TWILIO_FROM_NUMBER\"\n        )\n        values[\"client\"] = Client(account_sid, auth_token)\n        return values\n[docs]    def run(self, body: str, to: str) -> str:\n        \"\"\"Run body through Twilio and respond with message sid.\n        Args:\n            body: The text of the message you want to send. Can be up to 1,600\n                characters in length.\n            to: The destination phone number in", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html"}
{"id": "d50f2d5f1ea0-2", "text": "characters in length.\n            to: The destination phone number in\n                [E.164](https://www.twilio.com/docs/glossary/what-e164) format for\n                SMS/MMS or\n                [Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses)\n                for other 3rd-party channels.\n        \"\"\"  # noqa: E501\n        message = self.client.messages.create(to, from_=self.from_number, body=body)\n        return message.sid", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html"}
{"id": "cc5493f88733-0", "text": "Source code for langchain.utilities.requests\n\"\"\"Lightweight wrapper around requests library, with async support.\"\"\"\nfrom contextlib import asynccontextmanager\nfrom typing import Any, AsyncGenerator, Dict, Optional\nimport aiohttp\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra\n[docs]class Requests(BaseModel):\n    \"\"\"Wrapper around requests to handle auth and async.\n    The main purpose of this wrapper is to handle authentication (by saving\n    headers) and enable easy async methods on the same base object.\n    \"\"\"\n    headers: Optional[Dict[str, str]] = None\n    aiosession: Optional[aiohttp.ClientSession] = None\n    auth: Optional[Any] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n[docs]    def get(self, url: str, **kwargs: Any) -> requests.Response:\n        \"\"\"GET the URL and return the text.\"\"\"\n        return requests.get(url, headers=self.headers, auth=self.auth, **kwargs)\n[docs]    def post(self, url: str, data: Dict[str, Any], **kwargs: Any) -> requests.Response:\n        \"\"\"POST to the URL and return the text.\"\"\"\n        return requests.post(\n            url, json=data, headers=self.headers, auth=self.auth, **kwargs\n        )\n[docs]    def patch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> requests.Response:\n        \"\"\"PATCH the URL and return the text.\"\"\"\n        return requests.patch(\n            url, json=data, headers=self.headers, auth=self.auth, **kwargs\n        )\n[docs]    def put(self, url: str, data: Dict[str, Any], **kwargs: Any) -> requests.Response:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html"}
{"id": "cc5493f88733-1", "text": "\"\"\"PUT the URL and return the text.\"\"\"\n        return requests.put(\n            url, json=data, headers=self.headers, auth=self.auth, **kwargs\n        )\n[docs]    def delete(self, url: str, **kwargs: Any) -> requests.Response:\n        \"\"\"DELETE the URL and return the text.\"\"\"\n        return requests.delete(url, headers=self.headers, auth=self.auth, **kwargs)\n    @asynccontextmanager\n    async def _arequest(\n        self, method: str, url: str, **kwargs: Any\n    ) -> AsyncGenerator[aiohttp.ClientResponse, None]:\n        \"\"\"Make an async request.\"\"\"\n        if not self.aiosession:\n            async with aiohttp.ClientSession() as session:\n                async with session.request(\n                    method, url, headers=self.headers, auth=self.auth, **kwargs\n                ) as response:\n                    yield response\n        else:\n            async with self.aiosession.request(\n                method, url, headers=self.headers, auth=self.auth, **kwargs\n            ) as response:\n                yield response\n[docs]    @asynccontextmanager\n    async def aget(\n        self, url: str, **kwargs: Any\n    ) -> AsyncGenerator[aiohttp.ClientResponse, None]:\n        \"\"\"GET the URL and return the text asynchronously.\"\"\"\n        async with self._arequest(\"GET\", url, **kwargs) as response:\n            yield response\n[docs]    @asynccontextmanager\n    async def apost(\n        self, url: str, data: Dict[str, Any], **kwargs: Any\n    ) -> AsyncGenerator[aiohttp.ClientResponse, None]:\n        \"\"\"POST to the URL and return the text asynchronously.\"\"\"\n        async with self._arequest(\"POST\", url, json=data, **kwargs) as response:\n            yield response", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html"}
{"id": "cc5493f88733-2", "text": "yield response\n[docs]    @asynccontextmanager\n    async def apatch(\n        self, url: str, data: Dict[str, Any], **kwargs: Any\n    ) -> AsyncGenerator[aiohttp.ClientResponse, None]:\n        \"\"\"PATCH the URL and return the text asynchronously.\"\"\"\n        async with self._arequest(\"PATCH\", url, json=data, **kwargs) as response:\n            yield response\n[docs]    @asynccontextmanager\n    async def aput(\n        self, url: str, data: Dict[str, Any], **kwargs: Any\n    ) -> AsyncGenerator[aiohttp.ClientResponse, None]:\n        \"\"\"PUT the URL and return the text asynchronously.\"\"\"\n        async with self._arequest(\"PUT\", url, json=data, **kwargs) as response:\n            yield response\n[docs]    @asynccontextmanager\n    async def adelete(\n        self, url: str, **kwargs: Any\n    ) -> AsyncGenerator[aiohttp.ClientResponse, None]:\n        \"\"\"DELETE the URL and return the text asynchronously.\"\"\"\n        async with self._arequest(\"DELETE\", url, **kwargs) as response:\n            yield response\n[docs]class TextRequestsWrapper(BaseModel):\n    \"\"\"Lightweight wrapper around requests library.\n    The main purpose of this wrapper is to always return a text output.\n    \"\"\"\n    headers: Optional[Dict[str, str]] = None\n    aiosession: Optional[aiohttp.ClientSession] = None\n    auth: Optional[Any] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def requests(self) -> Requests:\n        return Requests(\n            headers=self.headers, aiosession=self.aiosession, auth=self.auth\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html"}
{"id": "cc5493f88733-3", "text": "headers=self.headers, aiosession=self.aiosession, auth=self.auth\n        )\n[docs]    def get(self, url: str, **kwargs: Any) -> str:\n        \"\"\"GET the URL and return the text.\"\"\"\n        return self.requests.get(url, **kwargs).text\n[docs]    def post(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str:\n        \"\"\"POST to the URL and return the text.\"\"\"\n        return self.requests.post(url, data, **kwargs).text\n[docs]    def patch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str:\n        \"\"\"PATCH the URL and return the text.\"\"\"\n        return self.requests.patch(url, data, **kwargs).text\n[docs]    def put(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str:\n        \"\"\"PUT the URL and return the text.\"\"\"\n        return self.requests.put(url, data, **kwargs).text\n[docs]    def delete(self, url: str, **kwargs: Any) -> str:\n        \"\"\"DELETE the URL and return the text.\"\"\"\n        return self.requests.delete(url, **kwargs).text\n[docs]    async def aget(self, url: str, **kwargs: Any) -> str:\n        \"\"\"GET the URL and return the text asynchronously.\"\"\"\n        async with self.requests.aget(url, **kwargs) as response:\n            return await response.text()\n[docs]    async def apost(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str:\n        \"\"\"POST to the URL and return the text asynchronously.\"\"\"\n        async with self.requests.apost(url, data, **kwargs) as response:\n            return await response.text()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html"}
{"id": "cc5493f88733-4", "text": "return await response.text()\n[docs]    async def apatch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str:\n        \"\"\"PATCH the URL and return the text asynchronously.\"\"\"\n        async with self.requests.apatch(url, data, **kwargs) as response:\n            return await response.text()\n[docs]    async def aput(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str:\n        \"\"\"PUT the URL and return the text asynchronously.\"\"\"\n        async with self.requests.aput(url, data, **kwargs) as response:\n            return await response.text()\n[docs]    async def adelete(self, url: str, **kwargs: Any) -> str:\n        \"\"\"DELETE the URL and return the text asynchronously.\"\"\"\n        async with self.requests.adelete(url, **kwargs) as response:\n            return await response.text()\n# For backwards compatibility\nRequestsWrapper = TextRequestsWrapper", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html"}
{"id": "c53f1c832fc0-0", "text": "Source code for langchain.utilities.max_compute\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Iterator, List, Optional\nfrom langchain.utils import get_from_env\nif TYPE_CHECKING:\n    from odps import ODPS\n[docs]class MaxComputeAPIWrapper:\n    \"\"\"Interface for querying Alibaba Cloud MaxCompute tables.\"\"\"\n[docs]    def __init__(self, client: ODPS):\n        \"\"\"Initialize MaxCompute document loader.\n        Args:\n            client: odps.ODPS MaxCompute client object.\n        \"\"\"\n        self.client = client\n[docs]    @classmethod\n    def from_params(\n        cls,\n        endpoint: str,\n        project: str,\n        *,\n        access_id: Optional[str] = None,\n        secret_access_key: Optional[str] = None,\n    ) -> MaxComputeAPIWrapper:\n        \"\"\"Convenience constructor that builds the odsp.ODPS MaxCompute client from\n            given parameters.\n        Args:\n            endpoint: MaxCompute endpoint.\n            project: A project is a basic organizational unit of MaxCompute, which is\n                similar to a database.\n            access_id: MaxCompute access ID. Should be passed in directly or set as the\n                environment variable `MAX_COMPUTE_ACCESS_ID`.\n            secret_access_key: MaxCompute secret access key. Should be passed in\n                directly or set as the environment variable\n                `MAX_COMPUTE_SECRET_ACCESS_KEY`.\n        \"\"\"\n        try:\n            from odps import ODPS\n        except ImportError as ex:\n            raise ImportError(\n                \"Could not import pyodps python package. \"\n                \"Please install it with `pip install pyodps` or refer to \"\n                \"https://pyodps.readthedocs.io/.\"\n            ) from ex", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/max_compute.html"}
{"id": "c53f1c832fc0-1", "text": "\"https://pyodps.readthedocs.io/.\"\n            ) from ex\n        access_id = access_id or get_from_env(\"access_id\", \"MAX_COMPUTE_ACCESS_ID\")\n        secret_access_key = secret_access_key or get_from_env(\n            \"secret_access_key\", \"MAX_COMPUTE_SECRET_ACCESS_KEY\"\n        )\n        client = ODPS(\n            access_id=access_id,\n            secret_access_key=secret_access_key,\n            project=project,\n            endpoint=endpoint,\n        )\n        if not client.exist_project(project):\n            raise ValueError(f'The project \"{project}\" does not exist.')\n        return cls(client)\n[docs]    def lazy_query(self, query: str) -> Iterator[dict]:\n        # Execute SQL query.\n        with self.client.execute_sql(query).open_reader() as reader:\n            if reader.count == 0:\n                raise ValueError(\"Table contains no data.\")\n            for record in reader:\n                yield {k: v for k, v in record}\n[docs]    def query(self, query: str) -> List[dict]:\n        return list(self.lazy_query(query))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/max_compute.html"}
{"id": "0097bd10ff7e-0", "text": "Source code for langchain.utilities.python\nimport functools\nimport logging\nimport multiprocessing\nimport sys\nfrom io import StringIO\nfrom typing import Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel, Field\nlogger = logging.getLogger(__name__)\n@functools.lru_cache(maxsize=None)\ndef warn_once() -> None:\n    \"\"\"Warn once about the dangers of PythonREPL.\"\"\"\n    logger.warning(\"Python REPL can execute arbitrary code. Use with caution.\")\n[docs]class PythonREPL(BaseModel):\n    \"\"\"Simulates a standalone Python REPL.\"\"\"\n    globals: Optional[Dict] = Field(default_factory=dict, alias=\"_globals\")\n    locals: Optional[Dict] = Field(default_factory=dict, alias=\"_locals\")\n[docs]    @classmethod\n    def worker(\n        cls,\n        command: str,\n        globals: Optional[Dict],\n        locals: Optional[Dict],\n        queue: multiprocessing.Queue,\n    ) -> None:\n        old_stdout = sys.stdout\n        sys.stdout = mystdout = StringIO()\n        try:\n            exec(command, globals, locals)\n            sys.stdout = old_stdout\n            queue.put(mystdout.getvalue())\n        except Exception as e:\n            sys.stdout = old_stdout\n            queue.put(repr(e))\n[docs]    def run(self, command: str, timeout: Optional[int] = None) -> str:\n        \"\"\"Run command with own globals/locals and returns anything printed.\n        Timeout after the specified number of seconds.\"\"\"\n        # Warn against dangers of PythonREPL\n        warn_once()\n        queue: multiprocessing.Queue = multiprocessing.Queue()\n        # Only use multiprocessing if we are enforcing a timeout\n        if timeout is not None:\n            # create a Process\n            p = multiprocessing.Process(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/python.html"}
{"id": "0097bd10ff7e-1", "text": "# create a Process\n            p = multiprocessing.Process(\n                target=self.worker, args=(command, self.globals, self.locals, queue)\n            )\n            # start it\n            p.start()\n            # wait for the process to finish or kill it after timeout seconds\n            p.join(timeout)\n            if p.is_alive():\n                p.terminate()\n                return \"Execution timed out\"\n        else:\n            self.worker(command, self.globals, self.locals, queue)\n        # get the result from the worker function\n        return queue.get()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/python.html"}
{"id": "cfda5880b057-0", "text": "Source code for langchain.utilities.github\n\"\"\"Util that calls GitHub.\"\"\"\nfrom __future__ import annotations\nimport json\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\nif TYPE_CHECKING:\n    from github.Issue import Issue\n[docs]class GitHubAPIWrapper(BaseModel):\n    \"\"\"Wrapper for GitHub API.\"\"\"\n    github: Any  #: :meta private:\n    github_repo_instance: Any  #: :meta private:\n    github_repository: Optional[str] = None\n    github_app_id: Optional[str] = None\n    github_app_private_key: Optional[str] = None\n    github_branch: Optional[str] = None\n    github_base_branch: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        github_repository = get_from_dict_or_env(\n            values, \"github_repository\", \"GITHUB_REPOSITORY\"\n        )\n        github_app_id = get_from_dict_or_env(values, \"github_app_id\", \"GITHUB_APP_ID\")\n        github_app_private_key = get_from_dict_or_env(\n            values, \"github_app_private_key\", \"GITHUB_APP_PRIVATE_KEY\"\n        )\n        github_branch = get_from_dict_or_env(\n            values, \"github_branch\", \"GITHUB_BRANCH\", default=\"master\"\n        )\n        github_base_branch = get_from_dict_or_env(\n            values, \"github_base_branch\", \"GITHUB_BASE_BRANCH\", default=\"master\"\n        )\n        try:\n            from github import Auth, GithubIntegration", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html"}
{"id": "cfda5880b057-1", "text": ")\n        try:\n            from github import Auth, GithubIntegration\n        except ImportError:\n            raise ImportError(\n                \"PyGithub is not installed. \"\n                \"Please install it with `pip install PyGithub`\"\n            )\n        with open(github_app_private_key, \"r\") as f:\n            private_key = f.read()\n        auth = Auth.AppAuth(\n            github_app_id,\n            private_key,\n        )\n        gi = GithubIntegration(auth=auth)\n        installation = gi.get_installations()[0]\n        # create a GitHub instance:\n        g = installation.get_github_for_installation()\n        values[\"github\"] = g\n        values[\"github_repo_instance\"] = g.get_repo(github_repository)\n        values[\"github_repository\"] = github_repository\n        values[\"github_app_id\"] = github_app_id\n        values[\"github_app_private_key\"] = github_app_private_key\n        values[\"github_branch\"] = github_branch\n        values[\"github_base_branch\"] = github_base_branch\n        return values\n[docs]    def parse_issues(self, issues: List[Issue]) -> List[dict]:\n        \"\"\"\n        Extracts title and number from each Issue and puts them in a dictionary\n        Parameters:\n            issues(List[Issue]): A list of Github Issue objects\n        Returns:\n            List[dict]: A dictionary of issue titles and numbers\n        \"\"\"\n        parsed = []\n        for issue in issues:\n            title = issue.title\n            number = issue.number\n            parsed.append({\"title\": title, \"number\": number})\n        return parsed\n[docs]    def get_issues(self) -> str:\n        \"\"\"\n        Fetches all open issues from the repo\n        Returns:\n            str: A plaintext report containing the number of issues\n            and each issue's title and number.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html"}
{"id": "cfda5880b057-2", "text": "and each issue's title and number.\n        \"\"\"\n        issues = self.github_repo_instance.get_issues(state=\"open\")\n        if issues.totalCount > 0:\n            parsed_issues = self.parse_issues(issues)\n            parsed_issues_str = (\n                \"Found \" + str(len(parsed_issues)) + \" issues:\\n\" + str(parsed_issues)\n            )\n            return parsed_issues_str\n        else:\n            return \"No open issues available\"\n[docs]    def get_issue(self, issue_number: int) -> Dict[str, Any]:\n        \"\"\"\n        Fetches a specific issue and its first 10 comments\n        Parameters:\n            issue_number(int): The number for the github issue\n        Returns:\n            dict: A doctionary containing the issue's title,\n            body, and comments as a string\n        \"\"\"\n        issue = self.github_repo_instance.get_issue(number=issue_number)\n        page = 0\n        comments: List[dict] = []\n        while len(comments) <= 10:\n            comments_page = issue.get_comments().get_page(page)\n            if len(comments_page) == 0:\n                break\n            for comment in comments_page:\n                comments.append({\"body\": comment.body, \"user\": comment.user.login})\n            page += 1\n        return {\n            \"title\": issue.title,\n            \"body\": issue.body,\n            \"comments\": str(comments),\n        }\n[docs]    def create_pull_request(self, pr_query: str) -> str:\n        \"\"\"\n        Makes a pull request from the bot's branch to the base branch\n        Parameters:\n            pr_query(str): a string which contains the PR title\n            and the PR body. The title is the first line\n            in the string, and the body are the rest of the string.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html"}
{"id": "cfda5880b057-3", "text": "in the string, and the body are the rest of the string.\n            For example, \"Updated README\\nmade changes to add info\"\n        Returns:\n            str: A success or failure message\n        \"\"\"\n        if self.github_base_branch == self.github_branch:\n            return \"\"\"Cannot make a pull request because \n            commits are already in the master branch\"\"\"\n        else:\n            try:\n                title = pr_query.split(\"\\n\")[0]\n                body = pr_query[len(title) + 2 :]\n                pr = self.github_repo_instance.create_pull(\n                    title=title,\n                    body=body,\n                    head=self.github_branch,\n                    base=self.github_base_branch,\n                )\n                return f\"Successfully created PR number {pr.number}\"\n            except Exception as e:\n                return \"Unable to make pull request due to error:\\n\" + str(e)\n[docs]    def comment_on_issue(self, comment_query: str) -> str:\n        \"\"\"\n        Adds a comment to a github issue\n        Parameters:\n            comment_query(str): a string which contains the issue number,\n            two newlines, and the comment.\n            for example: \"1\\n\\nWorking on it now\"\n            adds the comment \"working on it now\" to issue 1\n        Returns:\n            str: A success or failure message\n        \"\"\"\n        issue_number = int(comment_query.split(\"\\n\\n\")[0])\n        comment = comment_query[len(str(issue_number)) + 2 :]\n        try:\n            issue = self.github_repo_instance.get_issue(number=issue_number)\n            issue.create_comment(comment)\n            return \"Commented on issue \" + str(issue_number)\n        except Exception as e:\n            return \"Unable to make comment due to error:\\n\" + str(e)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html"}
{"id": "cfda5880b057-4", "text": "return \"Unable to make comment due to error:\\n\" + str(e)\n[docs]    def create_file(self, file_query: str) -> str:\n        \"\"\"\n        Creates a new file on the Github repo\n        Parameters:\n            file_query(str): a string which contains the file path\n            and the file contents. The file path is the first line\n            in the string, and the contents are the rest of the string.\n            For example, \"hello_world.md\\n# Hello World!\"\n        Returns:\n            str: A success or failure message\n        \"\"\"\n        file_path = file_query.split(\"\\n\")[0]\n        file_contents = file_query[len(file_path) + 2 :]\n        try:\n            exists = self.github_repo_instance.get_contents(file_path)\n            if exists is None:\n                self.github_repo_instance.create_file(\n                    path=file_path,\n                    message=\"Create \" + file_path,\n                    content=file_contents,\n                    branch=self.github_branch,\n                )\n                return \"Created file \" + file_path\n            else:\n                return f\"File already exists at {file_path}. Use update_file instead\"\n        except Exception as e:\n            return \"Unable to make file due to error:\\n\" + str(e)\n[docs]    def read_file(self, file_path: str) -> str:\n        \"\"\"\n        Reads a file from the github repo\n        Parameters:\n            file_path(str): the file path\n        Returns:\n            str: The file decoded as a string\n        \"\"\"\n        file = self.github_repo_instance.get_contents(file_path)\n        return file.decoded_content.decode(\"utf-8\")\n[docs]    def update_file(self, file_query: str) -> str:\n        \"\"\"\n        Updates a file with new content.\n        Parameters:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html"}
{"id": "cfda5880b057-5", "text": "\"\"\"\n        Updates a file with new content.\n        Parameters:\n            file_query(str): Contains the file path and the file contents.\n                The old file contents is wrapped in OLD <<<< and >>>> OLD\n                The new file contents is wrapped in NEW <<<< and >>>> NEW\n                For example:\n                /test/hello.txt\n                OLD <<<<\n                Hello Earth!\n                >>>> OLD\n                NEW <<<<\n                Hello Mars!\n                >>>> NEW\n        Returns:\n            A success or failure message\n        \"\"\"\n        try:\n            file_path = file_query.split(\"\\n\")[0]\n            old_file_contents = (\n                file_query.split(\"OLD <<<<\")[1].split(\">>>> OLD\")[0].strip()\n            )\n            new_file_contents = (\n                file_query.split(\"NEW <<<<\")[1].split(\">>>> NEW\")[0].strip()\n            )\n            file_content = self.read_file(file_path)\n            updated_file_content = file_content.replace(\n                old_file_contents, new_file_contents\n            )\n            if file_content == updated_file_content:\n                return (\n                    \"File content was not updated because old content was not found.\"\n                    \"It may be helpful to use the read_file action to get \"\n                    \"the current file contents.\"\n                )\n            self.github_repo_instance.update_file(\n                path=file_path,\n                message=\"Update \" + file_path,\n                content=updated_file_content,\n                branch=self.github_branch,\n                sha=self.github_repo_instance.get_contents(file_path).sha,\n            )\n            return \"Updated file \" + file_path\n        except Exception as e:\n            return \"Unable to update file due to error:\\n\" + str(e)\n[docs]    def delete_file(self, file_path: str) -> str:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html"}
{"id": "cfda5880b057-6", "text": "\"\"\"\n        Deletes a file from the repo\n        Parameters:\n            file_path(str): Where the file is\n        Returns:\n            str: Success or failure message\n        \"\"\"\n        try:\n            file = self.github_repo_instance.get_contents(file_path)\n            self.github_repo_instance.delete_file(\n                path=file_path,\n                message=\"Delete \" + file_path,\n                branch=self.github_branch,\n                sha=file.sha,\n            )\n            return \"Deleted file \" + file_path\n        except Exception as e:\n            return \"Unable to delete file due to error:\\n\" + str(e)\n[docs]    def run(self, mode: str, query: str) -> str:\n        if mode == \"get_issues\":\n            return self.get_issues()\n        elif mode == \"get_issue\":\n            return json.dumps(self.get_issue(int(query)))\n        elif mode == \"comment_on_issue\":\n            return self.comment_on_issue(query)\n        elif mode == \"create_file\":\n            return self.create_file(query)\n        elif mode == \"create_pull_request\":\n            return self.create_pull_request(query)\n        elif mode == \"read_file\":\n            return self.read_file(query)\n        elif mode == \"update_file\":\n            return self.update_file(query)\n        elif mode == \"delete_file\":\n            return self.delete_file(query)\n        else:\n            raise ValueError(\"Invalid mode\" + mode)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html"}
{"id": "0a09325f35a6-0", "text": "Source code for langchain.utilities.graphql\nimport json\nfrom typing import Any, Callable, Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\n[docs]class GraphQLAPIWrapper(BaseModel):\n    \"\"\"Wrapper around GraphQL API.\n    To use, you should have the ``gql`` python package installed.\n    This wrapper will use the GraphQL API to conduct queries.\n    \"\"\"\n    custom_headers: Optional[Dict[str, str]] = None\n    graphql_endpoint: str\n    gql_client: Any  #: :meta private:\n    gql_function: Callable[[str], Any]  #: :meta private:\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the python package exists in the environment.\"\"\"\n        try:\n            from gql import Client, gql\n            from gql.transport.requests import RequestsHTTPTransport\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import gql python package. \"\n                f\"Try installing it with `pip install gql`. Received error: {e}\"\n            )\n        headers = values.get(\"custom_headers\")\n        transport = RequestsHTTPTransport(\n            url=values[\"graphql_endpoint\"],\n            headers=headers,\n        )\n        client = Client(transport=transport, fetch_schema_from_transport=True)\n        values[\"gql_client\"] = client\n        values[\"gql_function\"] = gql\n        return values\n[docs]    def run(self, query: str) -> str:\n        \"\"\"Run a GraphQL query and get the results.\"\"\"\n        result = self._execute_query(query)\n        return json.dumps(result, indent=2)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html"}
{"id": "0a09325f35a6-1", "text": "return json.dumps(result, indent=2)\n    def _execute_query(self, query: str) -> Dict[str, Any]:\n        \"\"\"Execute a GraphQL query and return the results.\"\"\"\n        document_node = self.gql_function(query)\n        result = self.gql_client.execute(document_node)\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html"}
{"id": "eebf852543f6-0", "text": "Source code for langchain.utilities.awslambda\n\"\"\"Util that calls Lambda.\"\"\"\nimport json\nfrom typing import Any, Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\n[docs]class LambdaWrapper(BaseModel):\n    \"\"\"Wrapper for AWS Lambda SDK.\n    To use, you should have the ``boto3`` package installed\n    and a lambda functions built from the AWS Console or\n    CLI. Set up your AWS credentials with ``aws configure``\n    Example:\n        .. code-block:: bash\n            pip install boto3\n            aws configure\n    \"\"\"\n    lambda_client: Any  #: :meta private:\n    \"\"\"The configured boto3 client\"\"\"\n    function_name: Optional[str] = None\n    \"\"\"The name of your lambda function\"\"\"\n    awslambda_tool_name: Optional[str] = None\n    \"\"\"If passing to an agent as a tool, the tool name\"\"\"\n    awslambda_tool_description: Optional[str] = None\n    \"\"\"If passing to an agent as a tool, the description\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that python package exists in environment.\"\"\"\n        try:\n            import boto3\n        except ImportError:\n            raise ImportError(\n                \"boto3 is not installed. Please install it with `pip install boto3`\"\n            )\n        values[\"lambda_client\"] = boto3.client(\"lambda\")\n        values[\"function_name\"] = values[\"function_name\"]\n        return values\n[docs]    def run(self, query: str) -> str:\n        \"\"\"\n        Invokes the lambda function and returns the\n        result.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html"}
{"id": "eebf852543f6-1", "text": "Invokes the lambda function and returns the\n        result.\n        Args:\n            query: an input to passed to the lambda\n                function as the ``body`` of a JSON\n                object.\n        \"\"\"  # noqa: E501\n        res = self.lambda_client.invoke(\n            FunctionName=self.function_name,\n            InvocationType=\"RequestResponse\",\n            Payload=json.dumps({\"body\": query}),\n        )\n        try:\n            payload_stream = res[\"Payload\"]\n            payload_string = payload_stream.read().decode(\"utf-8\")\n            answer = json.loads(payload_string)[\"body\"]\n        except StopIteration:\n            return \"Failed to parse response from Lambda\"\n        if answer is None or answer == \"\":\n            # We don't want to return the assumption alone if answer is empty\n            return \"Request failed.\"\n        else:\n            return f\"Result: {answer}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html"}
{"id": "7f0b4fc8029e-0", "text": "Source code for langchain.utilities.searchapi\nfrom typing import Any, Dict, Optional\nimport aiohttp\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class SearchApiAPIWrapper(BaseModel):\n    \"\"\"\n    Wrapper around SearchApi API.\n    To use, you should have the environment variable ``SEARCHAPI_API_KEY``\n    set with your API key, or pass `searchapi_api_key`\n    as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.utilities import SearchApiAPIWrapper\n            searchapi = SearchApiAPIWrapper()\n    \"\"\"\n    # Use \"google\" engine by default.\n    # Full list of supported ones can be found in https://www.searchapi.io docs\n    engine: str = \"google\"\n    searchapi_api_key: Optional[str] = None\n    aiosession: Optional[aiohttp.ClientSession] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that API key exists in environment.\"\"\"\n        searchapi_api_key = get_from_dict_or_env(\n            values, \"searchapi_api_key\", \"SEARCHAPI_API_KEY\"\n        )\n        values[\"searchapi_api_key\"] = searchapi_api_key\n        return values\n[docs]    def run(self, query: str, **kwargs: Any) -> str:\n        results = self.results(query, **kwargs)\n        return self._result_as_string(results)\n[docs]    async def arun(self, query: str, **kwargs: Any) -> str:\n        results = await self.aresults(query, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searchapi.html"}
{"id": "7f0b4fc8029e-1", "text": "results = await self.aresults(query, **kwargs)\n        return self._result_as_string(results)\n[docs]    def results(self, query: str, **kwargs: Any) -> dict:\n        results = self._search_api_results(query, **kwargs)\n        return results\n[docs]    async def aresults(self, query: str, **kwargs: Any) -> dict:\n        results = await self._async_search_api_results(query, **kwargs)\n        return results\n    def _prepare_request(self, query: str, **kwargs: Any) -> dict:\n        return {\n            \"url\": \"https://www.searchapi.io/api/v1/search\",\n            \"headers\": {\n                \"Authorization\": f\"Bearer {self.searchapi_api_key}\",\n            },\n            \"params\": {\n                \"engine\": self.engine,\n                \"q\": query,\n                **{key: value for key, value in kwargs.items() if value is not None},\n            },\n        }\n    def _search_api_results(self, query: str, **kwargs: Any) -> dict:\n        request_details = self._prepare_request(query, **kwargs)\n        response = requests.get(\n            url=request_details[\"url\"],\n            params=request_details[\"params\"],\n            headers=request_details[\"headers\"],\n        )\n        response.raise_for_status()\n        return response.json()\n    async def _async_search_api_results(self, query: str, **kwargs: Any) -> dict:\n        \"\"\"Use aiohttp to send request to SearchApi API and return results async.\"\"\"\n        request_details = self._prepare_request(query, **kwargs)\n        if not self.aiosession:\n            async with aiohttp.ClientSession() as session:\n                async with session.get(\n                    url=request_details[\"url\"],\n                    headers=request_details[\"headers\"],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searchapi.html"}
{"id": "7f0b4fc8029e-2", "text": "url=request_details[\"url\"],\n                    headers=request_details[\"headers\"],\n                    params=request_details[\"params\"],\n                    raise_for_status=True,\n                ) as response:\n                    results = await response.json()\n        else:\n            async with self.aiosession.get(\n                url=request_details[\"url\"],\n                headers=request_details[\"headers\"],\n                params=request_details[\"params\"],\n                raise_for_status=True,\n            ) as response:\n                results = await response.json()\n        return results\n    @staticmethod\n    def _result_as_string(result: dict) -> str:\n        toret = \"No good search result found\"\n        if \"answer_box\" in result.keys() and \"answer\" in result[\"answer_box\"].keys():\n            toret = result[\"answer_box\"][\"answer\"]\n        elif \"answer_box\" in result.keys() and \"snippet\" in result[\"answer_box\"].keys():\n            toret = result[\"answer_box\"][\"snippet\"]\n        elif \"knowledge_graph\" in result.keys():\n            toret = result[\"knowledge_graph\"][\"description\"]\n        elif \"organic_results\" in result.keys():\n            snippets = [\n                r[\"snippet\"] for r in result[\"organic_results\"] if \"snippet\" in r.keys()\n            ]\n            toret = \"\\n\".join(snippets)\n        elif \"jobs\" in result.keys():\n            jobs = [\n                r[\"description\"] for r in result[\"jobs\"] if \"description\" in r.keys()\n            ]\n            toret = \"\\n\".join(jobs)\n        elif \"videos\" in result.keys():\n            videos = [\n                f\"\"\"Title: \"{r[\"title\"]}\" Link: {r[\"link\"]}\"\"\"\n                for r in result[\"videos\"]\n                if \"title\" in r.keys()\n            ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searchapi.html"}
{"id": "7f0b4fc8029e-3", "text": "if \"title\" in r.keys()\n            ]\n            toret = \"\\n\".join(videos)\n        elif \"images\" in result.keys():\n            images = [\n                f\"\"\"Title: \"{r[\"title\"]}\" Link: {r[\"original\"][\"link\"]}\"\"\"\n                for r in result[\"images\"]\n                if \"original\" in r.keys()\n            ]\n            toret = \"\\n\".join(images)\n        return toret", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searchapi.html"}
{"id": "708d7cb76c03-0", "text": "Source code for langchain.utilities.zapier\n\"\"\"Util that can interact with Zapier NLA.\nFull docs here: https://nla.zapier.com/start/\nNote: this wrapper currently only implemented the `api_key` auth method for testing\nand server-side production use cases (using the developer's connected accounts on\nZapier.com)\nFor use-cases where LangChain + Zapier NLA is powering a user-facing application, and\nLangChain needs access to the end-user's connected accounts on Zapier.com, you'll need\nto use oauth. Review the full docs above and reach out to nla@zapier.com for\ndeveloper support.\n\"\"\"\nimport json\nfrom typing import Any, Dict, List, Optional\nimport aiohttp\nimport requests\nfrom requests import Request, Session\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class ZapierNLAWrapper(BaseModel):\n    \"\"\"Wrapper for Zapier NLA.\n    Full docs here: https://nla.zapier.com/start/\n    This wrapper supports both API Key and OAuth Credential auth methods. API Key\n    is the fastest way to get started using this wrapper.\n    Call this wrapper with either `zapier_nla_api_key` or\n    `zapier_nla_oauth_access_token` arguments, or set the `ZAPIER_NLA_API_KEY`\n    environment variable. If both arguments are set, the Access Token will take\n    precedence.\n    For use-cases where LangChain + Zapier NLA is powering a user-facing application,\n    and LangChain needs access to the end-user's connected accounts on Zapier.com,\n    you'll need to use OAuth. Review the full docs above to learn how to create\n    your own provider and generate credentials.\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html"}
{"id": "708d7cb76c03-1", "text": "your own provider and generate credentials.\n    \"\"\"\n    zapier_nla_api_key: str\n    zapier_nla_oauth_access_token: str\n    zapier_nla_api_base: str = \"https://nla.zapier.com/api/v1/\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    def _format_headers(self) -> Dict[str, str]:\n        \"\"\"Format headers for requests.\"\"\"\n        headers = {\n            \"Accept\": \"application/json\",\n            \"Content-Type\": \"application/json\",\n        }\n        if self.zapier_nla_oauth_access_token:\n            headers.update(\n                {\"Authorization\": f\"Bearer {self.zapier_nla_oauth_access_token}\"}\n            )\n        else:\n            headers.update({\"X-API-Key\": self.zapier_nla_api_key})\n        return headers\n    def _get_session(self) -> Session:\n        session = requests.Session()\n        session.headers.update(self._format_headers())\n        return session\n    async def _arequest(self, method: str, url: str, **kwargs: Any) -> Dict[str, Any]:\n        \"\"\"Make an async request.\"\"\"\n        async with aiohttp.ClientSession(headers=self._format_headers()) as session:\n            async with session.request(method, url, **kwargs) as response:\n                response.raise_for_status()\n                return await response.json()\n    def _create_action_payload(  # type: ignore[no-untyped-def]\n        self, instructions: str, params: Optional[Dict] = None, preview_only=False\n    ) -> Dict:\n        \"\"\"Create a payload for an action.\"\"\"\n        data = params if params else {}\n        data.update(\n            {\n                \"instructions\": instructions,\n            }\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html"}
{"id": "708d7cb76c03-2", "text": "{\n                \"instructions\": instructions,\n            }\n        )\n        if preview_only:\n            data.update({\"preview_only\": True})\n        return data\n    def _create_action_url(self, action_id: str) -> str:\n        \"\"\"Create a url for an action.\"\"\"\n        return self.zapier_nla_api_base + f\"exposed/{action_id}/execute/\"\n    def _create_action_request(  # type: ignore[no-untyped-def]\n        self,\n        action_id: str,\n        instructions: str,\n        params: Optional[Dict] = None,\n        preview_only=False,\n    ) -> Request:\n        data = self._create_action_payload(instructions, params, preview_only)\n        return Request(\n            \"POST\",\n            self._create_action_url(action_id),\n            json=data,\n        )\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key exists in environment.\"\"\"\n        zapier_nla_api_key_default = None\n        # If there is a oauth_access_key passed in the values\n        # we don't need a nla_api_key it can be blank\n        if \"zapier_nla_oauth_access_token\" in values:\n            zapier_nla_api_key_default = \"\"\n        else:\n            values[\"zapier_nla_oauth_access_token\"] = \"\"\n        # we require at least one API Key\n        zapier_nla_api_key = get_from_dict_or_env(\n            values,\n            \"zapier_nla_api_key\",\n            \"ZAPIER_NLA_API_KEY\",\n            zapier_nla_api_key_default,\n        )\n        values[\"zapier_nla_api_key\"] = zapier_nla_api_key\n        return values", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html"}
{"id": "708d7cb76c03-3", "text": "return values\n[docs]    async def alist(self) -> List[Dict]:\n        \"\"\"Returns a list of all exposed (enabled) actions associated with\n        current user (associated with the set api_key). Change your exposed\n        actions here: https://nla.zapier.com/demo/start/\n        The return list can be empty if no actions exposed. Else will contain\n        a list of action objects:\n        [{\n            \"id\": str,\n            \"description\": str,\n            \"params\": Dict[str, str]\n        }]\n        `params` will always contain an `instructions` key, the only required\n        param. All others optional and if provided will override any AI guesses\n        (see \"understanding the AI guessing flow\" here:\n        https://nla.zapier.com/api/v1/docs)\n        \"\"\"\n        response = await self._arequest(\"GET\", self.zapier_nla_api_base + \"exposed/\")\n        return response[\"results\"]\n[docs]    def list(self) -> List[Dict]:\n        \"\"\"Returns a list of all exposed (enabled) actions associated with\n        current user (associated with the set api_key). Change your exposed\n        actions here: https://nla.zapier.com/demo/start/\n        The return list can be empty if no actions exposed. Else will contain\n        a list of action objects:\n        [{\n            \"id\": str,\n            \"description\": str,\n            \"params\": Dict[str, str]\n        }]\n        `params` will always contain an `instructions` key, the only required\n        param. All others optional and if provided will override any AI guesses\n        (see \"understanding the AI guessing flow\" here:\n        https://nla.zapier.com/docs/using-the-api#ai-guessing)\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html"}
{"id": "708d7cb76c03-4", "text": "\"\"\"\n        session = self._get_session()\n        try:\n            response = session.get(self.zapier_nla_api_base + \"exposed/\")\n            response.raise_for_status()\n        except requests.HTTPError as http_err:\n            if response.status_code == 401:\n                if self.zapier_nla_oauth_access_token:\n                    raise requests.HTTPError(\n                        f\"An unauthorized response occurred. Check that your \"\n                        f\"access token is correct and doesn't need to be \"\n                        f\"refreshed. Err: {http_err}\",\n                        response=response,\n                    )\n                raise requests.HTTPError(\n                    f\"An unauthorized response occurred. Check that your api \"\n                    f\"key is correct. Err: {http_err}\",\n                    response=response,\n                )\n            raise http_err\n        return response.json()[\"results\"]\n[docs]    def run(\n        self, action_id: str, instructions: str, params: Optional[Dict] = None\n    ) -> Dict:\n        \"\"\"Executes an action that is identified by action_id, must be exposed\n        (enabled) by the current user (associated with the set api_key). Change\n        your exposed actions here: https://nla.zapier.com/demo/start/\n        The return JSON is guaranteed to be less than ~500 words (350\n        tokens) making it safe to inject into the prompt of another LLM\n        call.\n        \"\"\"\n        session = self._get_session()\n        request = self._create_action_request(action_id, instructions, params)\n        response = session.send(session.prepare_request(request))\n        response.raise_for_status()\n        return response.json()[\"result\"]\n[docs]    async def arun(\n        self, action_id: str, instructions: str, params: Optional[Dict] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html"}
{"id": "708d7cb76c03-5", "text": ") -> Dict:\n        \"\"\"Executes an action that is identified by action_id, must be exposed\n        (enabled) by the current user (associated with the set api_key). Change\n        your exposed actions here: https://nla.zapier.com/demo/start/\n        The return JSON is guaranteed to be less than ~500 words (350\n        tokens) making it safe to inject into the prompt of another LLM\n        call.\n        \"\"\"\n        response = await self._arequest(\n            \"POST\",\n            self._create_action_url(action_id),\n            json=self._create_action_payload(instructions, params),\n        )\n        return response[\"result\"]\n[docs]    def preview(\n        self, action_id: str, instructions: str, params: Optional[Dict] = None\n    ) -> Dict:\n        \"\"\"Same as run, but instead of actually executing the action, will\n        instead return a preview of params that have been guessed by the AI in\n        case you need to explicitly review before executing.\"\"\"\n        session = self._get_session()\n        params = params if params else {}\n        params.update({\"preview_only\": True})\n        request = self._create_action_request(action_id, instructions, params, True)\n        response = session.send(session.prepare_request(request))\n        response.raise_for_status()\n        return response.json()[\"input_params\"]\n[docs]    async def apreview(\n        self, action_id: str, instructions: str, params: Optional[Dict] = None\n    ) -> Dict:\n        \"\"\"Same as run, but instead of actually executing the action, will\n        instead return a preview of params that have been guessed by the AI in\n        case you need to explicitly review before executing.\"\"\"\n        response = await self._arequest(\n            \"POST\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html"}
{"id": "708d7cb76c03-6", "text": "response = await self._arequest(\n            \"POST\",\n            self._create_action_url(action_id),\n            json=self._create_action_payload(instructions, params, preview_only=True),\n        )\n        return response[\"result\"]\n[docs]    def run_as_str(self, *args, **kwargs) -> str:  # type: ignore[no-untyped-def]\n        \"\"\"Same as run, but returns a stringified version of the JSON for\n        insertting back into an LLM.\"\"\"\n        data = self.run(*args, **kwargs)\n        return json.dumps(data)\n[docs]    async def arun_as_str(self, *args, **kwargs) -> str:  # type: ignore[no-untyped-def]\n        \"\"\"Same as run, but returns a stringified version of the JSON for\n        insertting back into an LLM.\"\"\"\n        data = await self.arun(*args, **kwargs)\n        return json.dumps(data)\n[docs]    def preview_as_str(self, *args, **kwargs) -> str:  # type: ignore[no-untyped-def]\n        \"\"\"Same as preview, but returns a stringified version of the JSON for\n        insertting back into an LLM.\"\"\"\n        data = self.preview(*args, **kwargs)\n        return json.dumps(data)\n[docs]    async def apreview_as_str(  # type: ignore[no-untyped-def]\n        self, *args, **kwargs\n    ) -> str:\n        \"\"\"Same as preview, but returns a stringified version of the JSON for\n        insertting back into an LLM.\"\"\"\n        data = await self.apreview(*args, **kwargs)\n        return json.dumps(data)\n[docs]    def list_as_str(self) -> str:  # type: ignore[no-untyped-def]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html"}
{"id": "708d7cb76c03-7", "text": "\"\"\"Same as list, but returns a stringified version of the JSON for\n        insertting back into an LLM.\"\"\"\n        actions = self.list()\n        return json.dumps(actions)\n[docs]    async def alist_as_str(self) -> str:  # type: ignore[no-untyped-def]\n        \"\"\"Same as list, but returns a stringified version of the JSON for\n        insertting back into an LLM.\"\"\"\n        actions = await self.alist()\n        return json.dumps(actions)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html"}
{"id": "6671f8d4b603-0", "text": "Source code for langchain.utilities.jira\n\"\"\"Util that calls Jira.\"\"\"\nfrom typing import Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n# TODO: think about error handling, more specific api specs, and jql/project limits\n[docs]class JiraAPIWrapper(BaseModel):\n    \"\"\"Wrapper for Jira API.\"\"\"\n    jira: Any  #: :meta private:\n    confluence: Any\n    jira_username: Optional[str] = None\n    jira_api_token: Optional[str] = None\n    jira_instance_url: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        jira_username = get_from_dict_or_env(values, \"jira_username\", \"JIRA_USERNAME\")\n        values[\"jira_username\"] = jira_username\n        jira_api_token = get_from_dict_or_env(\n            values, \"jira_api_token\", \"JIRA_API_TOKEN\"\n        )\n        values[\"jira_api_token\"] = jira_api_token\n        jira_instance_url = get_from_dict_or_env(\n            values, \"jira_instance_url\", \"JIRA_INSTANCE_URL\"\n        )\n        values[\"jira_instance_url\"] = jira_instance_url\n        try:\n            from atlassian import Confluence, Jira\n        except ImportError:\n            raise ImportError(\n                \"atlassian-python-api is not installed. \"\n                \"Please install it with `pip install atlassian-python-api`\"\n            )\n        jira = Jira(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html"}
{"id": "6671f8d4b603-1", "text": ")\n        jira = Jira(\n            url=jira_instance_url,\n            username=jira_username,\n            password=jira_api_token,\n            cloud=True,\n        )\n        confluence = Confluence(\n            url=jira_instance_url,\n            username=jira_username,\n            password=jira_api_token,\n            cloud=True,\n        )\n        values[\"jira\"] = jira\n        values[\"confluence\"] = confluence\n        return values\n[docs]    def parse_issues(self, issues: Dict) -> List[dict]:\n        parsed = []\n        for issue in issues[\"issues\"]:\n            key = issue[\"key\"]\n            summary = issue[\"fields\"][\"summary\"]\n            created = issue[\"fields\"][\"created\"][0:10]\n            priority = issue[\"fields\"][\"priority\"][\"name\"]\n            status = issue[\"fields\"][\"status\"][\"name\"]\n            try:\n                assignee = issue[\"fields\"][\"assignee\"][\"displayName\"]\n            except Exception:\n                assignee = \"None\"\n            rel_issues = {}\n            for related_issue in issue[\"fields\"][\"issuelinks\"]:\n                if \"inwardIssue\" in related_issue.keys():\n                    rel_type = related_issue[\"type\"][\"inward\"]\n                    rel_key = related_issue[\"inwardIssue\"][\"key\"]\n                    rel_summary = related_issue[\"inwardIssue\"][\"fields\"][\"summary\"]\n                if \"outwardIssue\" in related_issue.keys():\n                    rel_type = related_issue[\"type\"][\"outward\"]\n                    rel_key = related_issue[\"outwardIssue\"][\"key\"]\n                    rel_summary = related_issue[\"outwardIssue\"][\"fields\"][\"summary\"]\n                rel_issues = {\"type\": rel_type, \"key\": rel_key, \"summary\": rel_summary}\n            parsed.append(\n                {\n                    \"key\": key,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html"}
{"id": "6671f8d4b603-2", "text": "parsed.append(\n                {\n                    \"key\": key,\n                    \"summary\": summary,\n                    \"created\": created,\n                    \"assignee\": assignee,\n                    \"priority\": priority,\n                    \"status\": status,\n                    \"related_issues\": rel_issues,\n                }\n            )\n        return parsed\n[docs]    def parse_projects(self, projects: List[dict]) -> List[dict]:\n        parsed = []\n        for project in projects:\n            id = project[\"id\"]\n            key = project[\"key\"]\n            name = project[\"name\"]\n            type = project[\"projectTypeKey\"]\n            style = project[\"style\"]\n            parsed.append(\n                {\"id\": id, \"key\": key, \"name\": name, \"type\": type, \"style\": style}\n            )\n        return parsed\n[docs]    def search(self, query: str) -> str:\n        issues = self.jira.jql(query)\n        parsed_issues = self.parse_issues(issues)\n        parsed_issues_str = (\n            \"Found \" + str(len(parsed_issues)) + \" issues:\\n\" + str(parsed_issues)\n        )\n        return parsed_issues_str\n[docs]    def project(self) -> str:\n        projects = self.jira.projects()\n        parsed_projects = self.parse_projects(projects)\n        parsed_projects_str = (\n            \"Found \" + str(len(parsed_projects)) + \" projects:\\n\" + str(parsed_projects)\n        )\n        return parsed_projects_str\n[docs]    def issue_create(self, query: str) -> str:\n        try:\n            import json\n        except ImportError:\n            raise ImportError(\n                \"json is not installed. Please install it with `pip install json`\"\n            )\n        params = json.loads(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html"}
{"id": "6671f8d4b603-3", "text": ")\n        params = json.loads(query)\n        return self.jira.issue_create(fields=dict(params))\n[docs]    def page_create(self, query: str) -> str:\n        try:\n            import json\n        except ImportError:\n            raise ImportError(\n                \"json is not installed. Please install it with `pip install json`\"\n            )\n        params = json.loads(query)\n        return self.confluence.create_page(**dict(params))\n[docs]    def other(self, query: str) -> str:\n        try:\n            import json\n        except ImportError:\n            raise ImportError(\n                \"json is not installed. Please install it with `pip install json`\"\n            )\n        params = json.loads(query)\n        jira_function = getattr(self.jira, params[\"function\"])\n        return jira_function(*params.get(\"args\", []), **params.get(\"kwargs\", {}))\n[docs]    def run(self, mode: str, query: str) -> str:\n        if mode == \"jql\":\n            return self.search(query)\n        elif mode == \"get_projects\":\n            return self.project()\n        elif mode == \"create_issue\":\n            return self.issue_create(query)\n        elif mode == \"other\":\n            return self.other(query)\n        elif mode == \"create_page\":\n            return self.page_create(query)\n        else:\n            raise ValueError(f\"Got unexpected mode {mode}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html"}
{"id": "9299e646bb89-0", "text": "Source code for langchain.utilities.arcee\n# This module contains utility classes and functions for interacting with Arcee API.\n# For more information and updates, refer to the Arcee utils page:\n# [https://github.com/arcee-ai/arcee-python/blob/main/arcee/dalm.py]\nfrom enum import Enum\nfrom typing import Any, Dict, List, Literal, Mapping, Optional, Union\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema.retriever import Document\n[docs]class ArceeRoute(str, Enum):\n    \"\"\"Routes available for the Arcee API as enumerator.\"\"\"\n    generate = \"models/generate\"\n    retrieve = \"models/retrieve\"\n    model_training_status = \"models/status/{id_or_name}\"\n[docs]class DALMFilterType(str, Enum):\n    \"\"\"Filter types available for a DALM retrieval as enumerator.\"\"\"\n    fuzzy_search = \"fuzzy_search\"\n    strict_search = \"strict_search\"\n[docs]class DALMFilter(BaseModel):\n    \"\"\"Filters available for a DALM retrieval and generation.\n    Arguments:\n        field_name: The field to filter on. Can be 'document' or 'name' to filter\n            on your document's raw text or title. Any other field will be presumed\n            to be a metadata field you included when uploading your context data\n        filter_type: Currently 'fuzzy_search' and 'strict_search' are supported.\n            'fuzzy_search' means a fuzzy search on the provided field is performed.\n            The exact strict doesn't need to exist in the document\n            for this to find a match.\n            Very useful for scanning a document for some keyword terms.\n            'strict_search' means that the exact string must appear\n            in the provided field.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arcee.html"}
{"id": "9299e646bb89-1", "text": "'strict_search' means that the exact string must appear\n            in the provided field.\n            This is NOT an exact eq filter. ie a document with content\n            \"the happy dog crossed the street\" will match on a strict_search of\n            \"dog\" but won't match on \"the dog\".\n            Python equivalent of `return search_string in full_string`.\n        value: The actual value to search for in the context data/metadata\n    \"\"\"\n    field_name: str\n    filter_type: DALMFilterType\n    value: str\n    _is_metadata: bool = False\n    @root_validator()\n    def set_meta(cls, values: Dict) -> Dict:\n        \"\"\"document and name are reserved arcee keys. Anything else is metadata\"\"\"\n        values[\"_is_meta\"] = values.get(\"field_name\") not in [\"document\", \"name\"]\n        return values\n[docs]class ArceeDocumentSource(BaseModel):\n    \"\"\"Source of an Arcee document.\"\"\"\n    document: str\n    name: str\n    id: str\n[docs]class ArceeDocument(BaseModel):\n    \"\"\"Arcee document.\"\"\"\n    index: str\n    id: str\n    score: float\n    source: ArceeDocumentSource\n[docs]class ArceeDocumentAdapter:\n    \"\"\"Adapter for Arcee documents\"\"\"\n[docs]    @classmethod\n    def adapt(cls, arcee_document: ArceeDocument) -> Document:\n        \"\"\"Adapts an `ArceeDocument` to a langchain's `Document` object.\"\"\"\n        return Document(\n            page_content=arcee_document.source.document,\n            metadata={\n                # arcee document; source metadata\n                \"name\": arcee_document.source.name,\n                \"source_id\": arcee_document.source.id,\n                # arcee document metadata", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arcee.html"}
{"id": "9299e646bb89-2", "text": "\"source_id\": arcee_document.source.id,\n                # arcee document metadata\n                \"index\": arcee_document.index,\n                \"id\": arcee_document.id,\n                \"score\": arcee_document.score,\n            },\n        )\n[docs]class ArceeWrapper:\n    \"\"\"Wrapper for Arcee API.\"\"\"\n[docs]    def __init__(\n        self,\n        arcee_api_key: str,\n        arcee_api_url: str,\n        arcee_api_version: str,\n        model_kwargs: Optional[Dict[str, Any]],\n        model_name: str,\n    ):\n        \"\"\"Initialize ArceeWrapper.\n        Arguments:\n            arcee_api_key: API key for Arcee API.\n            arcee_api_url: URL for Arcee API.\n            arcee_api_version: Version of Arcee API.\n            model_kwargs: Keyword arguments for Arcee API.\n            model_name: Name of an Arcee model.\n        \"\"\"\n        self.arcee_api_key = arcee_api_key\n        self.model_kwargs = model_kwargs\n        self.arcee_api_url = arcee_api_url\n        self.arcee_api_version = arcee_api_version\n        try:\n            route = ArceeRoute.model_training_status.value.format(id_or_name=model_name)\n            response = self._make_request(\"get\", route)\n            self.model_id = response.get(\"model_id\")\n            self.model_training_status = response.get(\"status\")\n        except Exception as e:\n            raise ValueError(\n                f\"Error while validating model training status for '{model_name}': {e}\"\n            ) from e\n[docs]    def validate_model_training_status(self) -> None:\n        if self.model_training_status != \"training_complete\":\n            raise Exception(\n                f\"Model {self.model_id} is not ready. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arcee.html"}
{"id": "9299e646bb89-3", "text": "raise Exception(\n                f\"Model {self.model_id} is not ready. \"\n                \"Please wait for training to complete.\"\n            )\n    def _make_request(\n        self,\n        method: Literal[\"post\", \"get\"],\n        route: Union[ArceeRoute, str],\n        body: Optional[Mapping[str, Any]] = None,\n        params: Optional[dict] = None,\n        headers: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Make a request to the Arcee API\n        Args:\n            method: The HTTP method to use\n            route: The route to call\n            body: The body of the request\n            params: The query params of the request\n            headers: The headers of the request\n        \"\"\"\n        headers = self._make_request_headers(headers=headers)\n        url = self._make_request_url(route=route)\n        req_type = getattr(requests, method)\n        response = req_type(url, json=body, params=params, headers=headers)\n        if response.status_code not in (200, 201):\n            raise Exception(f\"Failed to make request. Response: {response.text}\")\n        return response.json()\n    def _make_request_headers(self, headers: Optional[Dict] = None) -> Dict:\n        headers = headers or {}\n        internal_headers = {\n            \"X-Token\": self.arcee_api_key,\n            \"Content-Type\": \"application/json\",\n        }\n        headers.update(internal_headers)\n        return headers\n    def _make_request_url(self, route: Union[ArceeRoute, str]) -> str:\n        return f\"{self.arcee_api_url}/{self.arcee_api_version}/{route}\"\n    def _make_request_body_for_models(\n        self, prompt: str, **kwargs: Mapping[str, Any]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arcee.html"}
{"id": "9299e646bb89-4", "text": "self, prompt: str, **kwargs: Mapping[str, Any]\n    ) -> Mapping[str, Any]:\n        \"\"\"Make the request body for generate/retrieve models endpoint\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        _params = {**_model_kwargs, **kwargs}\n        filters = [DALMFilter(**f) for f in _params.get(\"filters\", [])]\n        return dict(\n            model_id=self.model_id,\n            query=prompt,\n            size=_params.get(\"size\", 3),\n            filters=filters,\n            id=self.model_id,\n        )\n[docs]    def generate(\n        self,\n        prompt: str,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Generate text from Arcee DALM.\n        Args:\n            prompt: Prompt to generate text from.\n            size: The max number of context results to retrieve. Defaults to 3.\n              (Can be less if filters are provided).\n            filters: Filters to apply to the context dataset.\n        \"\"\"\n        response = self._make_request(\n            method=\"post\",\n            route=ArceeRoute.generate.value,\n            body=self._make_request_body_for_models(\n                prompt=prompt,\n                **kwargs,\n            ),\n        )\n        return response[\"text\"]\n[docs]    def retrieve(\n        self,\n        query: str,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Retrieve {size} contexts with your retriever for a given query\n        Args:\n            query: Query to submit to the model\n            size: The max number of context results to retrieve. Defaults to 3.\n              (Can be less if filters are provided).\n            filters: Filters to apply to the context dataset.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arcee.html"}
{"id": "9299e646bb89-5", "text": "filters: Filters to apply to the context dataset.\n        \"\"\"\n        response = self._make_request(\n            method=\"post\",\n            route=ArceeRoute.retrieve.value,\n            body=self._make_request_body_for_models(\n                prompt=query,\n                **kwargs,\n            ),\n        )\n        return [\n            ArceeDocumentAdapter.adapt(ArceeDocument(**doc))\n            for doc in response[\"results\"]\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arcee.html"}
{"id": "9e605f1161d2-0", "text": "Source code for langchain.utilities.arxiv\n\"\"\"Util that calls Arxiv.\"\"\"\nimport logging\nimport os\nimport re\nfrom typing import Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema import Document\nlogger = logging.getLogger(__name__)\n[docs]class ArxivAPIWrapper(BaseModel):\n    \"\"\"Wrapper around ArxivAPI.\n    To use, you should have the ``arxiv`` python package installed.\n    https://lukasschwab.me/arxiv.py/index.html\n    This wrapper will use the Arxiv API to conduct searches and\n    fetch document summaries. By default, it will return the document summaries\n    of the top-k results.\n    If the query is in the form of arxiv identifier\n    (see https://info.arxiv.org/help/find/index.html), it will return the paper\n    corresponding to the arxiv identifier.\n    It limits the Document content by doc_content_chars_max.\n    Set doc_content_chars_max=None if you don't want to limit the content size.\n    Attributes:\n        top_k_results: number of the top-scored document used for the arxiv tool\n        ARXIV_MAX_QUERY_LENGTH: the cut limit on the query used for the arxiv tool.\n        load_max_docs: a limit to the number of loaded documents\n        load_all_available_meta:\n            if True: the `metadata` of the loaded Documents contains all available\n            meta info (see https://lukasschwab.me/arxiv.py/index.html#Result),\n            if False: the `metadata` contains only the published date, title,\n            authors and summary.\n        doc_content_chars_max: an optional cut limit for the length of a document's\n            content\n    Example:\n        .. code-block:: python", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html"}
{"id": "9e605f1161d2-1", "text": "content\n    Example:\n        .. code-block:: python\n            from langchain.utilities.arxiv import ArxivAPIWrapper\n            arxiv = ArxivAPIWrapper(\n                top_k_results = 3,\n                ARXIV_MAX_QUERY_LENGTH = 300,\n                load_max_docs = 3,\n                load_all_available_meta = False,\n                doc_content_chars_max = 40000\n            )\n            arxiv.run(\"tree of thought llm)\n    \"\"\"\n    arxiv_search: Any  #: :meta private:\n    arxiv_exceptions: Any  # :meta private:\n    top_k_results: int = 3\n    ARXIV_MAX_QUERY_LENGTH: int = 300\n    load_max_docs: int = 100\n    load_all_available_meta: bool = False\n    doc_content_chars_max: Optional[int] = 4000\n[docs]    def is_arxiv_identifier(self, query: str) -> bool:\n        \"\"\"Check if a query is an arxiv identifier.\"\"\"\n        arxiv_identifier_pattern = r\"\\d{2}(0[1-9]|1[0-2])\\.\\d{4,5}(v\\d+|)|\\d{7}.*\"\n        for query_item in query[: self.ARXIV_MAX_QUERY_LENGTH].split():\n            match_result = re.match(arxiv_identifier_pattern, query_item)\n            if not match_result:\n                return False\n            assert match_result is not None\n            if not match_result.group(0) == query_item:\n                return False\n        return True\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the python package exists in environment.\"\"\"\n        try:\n            import arxiv\n            values[\"arxiv_search\"] = arxiv.Search", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html"}
{"id": "9e605f1161d2-2", "text": "import arxiv\n            values[\"arxiv_search\"] = arxiv.Search\n            values[\"arxiv_exceptions\"] = (\n                arxiv.ArxivError,\n                arxiv.UnexpectedEmptyPageError,\n                arxiv.HTTPError,\n            )\n            values[\"arxiv_result\"] = arxiv.Result\n        except ImportError:\n            raise ImportError(\n                \"Could not import arxiv python package. \"\n                \"Please install it with `pip install arxiv`.\"\n            )\n        return values\n[docs]    def get_summaries_as_docs(self, query: str) -> List[Document]:\n        \"\"\"\n        Performs an arxiv search and returns list of\n        documents, with summaries as the content.\n        If an error occurs or no documents found, error text\n        is returned instead. Wrapper for\n        https://lukasschwab.me/arxiv.py/index.html#Search\n        Args:\n            query: a plaintext search query\n        \"\"\"  # noqa: E501\n        try:\n            if self.is_arxiv_identifier(query):\n                results = self.arxiv_search(\n                    id_list=query.split(),\n                    max_results=self.top_k_results,\n                ).results()\n            else:\n                results = self.arxiv_search(  # type: ignore\n                    query[: self.ARXIV_MAX_QUERY_LENGTH], max_results=self.top_k_results\n                ).results()\n        except self.arxiv_exceptions as ex:\n            return [Document(page_content=f\"Arxiv exception: {ex}\")]\n        docs = [\n            Document(\n                page_content=result.summary,\n                metadata={\n                    \"Published\": result.updated.date(),\n                    \"Title\": result.title,\n                    \"Authors\": \", \".join(a.name for a in result.authors),\n                },\n            )\n            for result in results\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html"}
{"id": "9e605f1161d2-3", "text": "},\n            )\n            for result in results\n        ]\n        return docs\n[docs]    def run(self, query: str) -> str:\n        \"\"\"\n        Performs an arxiv search and A single string\n        with the publish date, title, authors, and summary\n        for each article separated by two newlines.\n        If an error occurs or no documents found, error text\n        is returned instead. Wrapper for\n        https://lukasschwab.me/arxiv.py/index.html#Search\n        Args:\n            query: a plaintext search query\n        \"\"\"  # noqa: E501\n        try:\n            if self.is_arxiv_identifier(query):\n                results = self.arxiv_search(\n                    id_list=query.split(),\n                    max_results=self.top_k_results,\n                ).results()\n            else:\n                results = self.arxiv_search(  # type: ignore\n                    query[: self.ARXIV_MAX_QUERY_LENGTH], max_results=self.top_k_results\n                ).results()\n        except self.arxiv_exceptions as ex:\n            return f\"Arxiv exception: {ex}\"\n        docs = [\n            f\"Published: {result.updated.date()}\\n\"\n            f\"Title: {result.title}\\n\"\n            f\"Authors: {', '.join(a.name for a in result.authors)}\\n\"\n            f\"Summary: {result.summary}\"\n            for result in results\n        ]\n        if docs:\n            return \"\\n\\n\".join(docs)[: self.doc_content_chars_max]\n        else:\n            return \"No good Arxiv Result was found\"\n[docs]    def load(self, query: str) -> List[Document]:\n        \"\"\"\n        Run Arxiv search and get the article texts plus the article meta information.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html"}
{"id": "9e605f1161d2-4", "text": "\"\"\"\n        Run Arxiv search and get the article texts plus the article meta information.\n        See https://lukasschwab.me/arxiv.py/index.html#Search\n        Returns: a list of documents with the document.page_content in text format\n        Performs an arxiv search, downloads the top k results as PDFs, loads\n        them as Documents, and returns them in a List.\n        Args:\n            query: a plaintext search query\n        \"\"\"  # noqa: E501\n        try:\n            import fitz\n        except ImportError:\n            raise ImportError(\n                \"PyMuPDF package not found, please install it with \"\n                \"`pip install pymupdf`\"\n            )\n        try:\n            # Remove the \":\" and \"-\" from the query, as they can cause search problems\n            query = query.replace(\":\", \"\").replace(\"-\", \"\")\n            if self.is_arxiv_identifier(query):\n                results = self.arxiv_search(\n                    id_list=query[: self.ARXIV_MAX_QUERY_LENGTH].split(),\n                    max_results=self.load_max_docs,\n                ).results()\n            else:\n                results = self.arxiv_search(  # type: ignore\n                    query[: self.ARXIV_MAX_QUERY_LENGTH], max_results=self.load_max_docs\n                ).results()\n        except self.arxiv_exceptions as ex:\n            logger.debug(\"Error on arxiv: %s\", ex)\n            return []\n        docs: List[Document] = []\n        for result in results:\n            try:\n                doc_file_name: str = result.download_pdf()\n                with fitz.open(doc_file_name) as doc_file:\n                    text: str = \"\".join(page.get_text() for page in doc_file)\n            except (FileNotFoundError, fitz.fitz.FileDataError) as f_ex:\n                logger.debug(f_ex)\n                continue", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html"}
{"id": "9e605f1161d2-5", "text": "logger.debug(f_ex)\n                continue\n            if self.load_all_available_meta:\n                extra_metadata = {\n                    \"entry_id\": result.entry_id,\n                    \"published_first_time\": str(result.published.date()),\n                    \"comment\": result.comment,\n                    \"journal_ref\": result.journal_ref,\n                    \"doi\": result.doi,\n                    \"primary_category\": result.primary_category,\n                    \"categories\": result.categories,\n                    \"links\": [link.href for link in result.links],\n                }\n            else:\n                extra_metadata = {}\n            metadata = {\n                \"Published\": str(result.updated.date()),\n                \"Title\": result.title,\n                \"Authors\": \", \".join(a.name for a in result.authors),\n                \"Summary\": result.summary,\n                **extra_metadata,\n            }\n            doc = Document(\n                page_content=text[: self.doc_content_chars_max], metadata=metadata\n            )\n            docs.append(doc)\n            os.remove(doc_file_name)\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html"}
{"id": "ed2de7655e3d-0", "text": "Source code for langchain.utilities.wolfram_alpha\n\"\"\"Util that calls WolframAlpha.\"\"\"\nfrom typing import Any, Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class WolframAlphaAPIWrapper(BaseModel):\n    \"\"\"Wrapper for Wolfram Alpha.\n    Docs for using:\n    1. Go to wolfram alpha and sign up for a developer account\n    2. Create an app and get your APP ID\n    3. Save your APP ID into WOLFRAM_ALPHA_APPID env variable\n    4. pip install wolframalpha\n    \"\"\"\n    wolfram_client: Any  #: :meta private:\n    wolfram_alpha_appid: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        wolfram_alpha_appid = get_from_dict_or_env(\n            values, \"wolfram_alpha_appid\", \"WOLFRAM_ALPHA_APPID\"\n        )\n        values[\"wolfram_alpha_appid\"] = wolfram_alpha_appid\n        try:\n            import wolframalpha\n        except ImportError:\n            raise ImportError(\n                \"wolframalpha is not installed. \"\n                \"Please install it with `pip install wolframalpha`\"\n            )\n        client = wolframalpha.Client(wolfram_alpha_appid)\n        values[\"wolfram_client\"] = client\n        return values\n[docs]    def run(self, query: str) -> str:\n        \"\"\"Run query through WolframAlpha and parse result.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html"}
{"id": "ed2de7655e3d-1", "text": "\"\"\"Run query through WolframAlpha and parse result.\"\"\"\n        res = self.wolfram_client.query(query)\n        try:\n            assumption = next(res.pods).text\n            answer = next(res.results).text\n        except StopIteration:\n            return \"Wolfram Alpha wasn't able to answer it\"\n        if answer is None or answer == \"\":\n            # We don't want to return the assumption alone if answer is empty\n            return \"No good Wolfram Alpha Result was found\"\n        else:\n            return f\"Assumption: {assumption} \\nAnswer: {answer}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html"}
{"id": "f03dfd4a71c9-0", "text": "Source code for langchain.utilities.alpha_vantage\n\"\"\"Util that calls AlphaVantage for Currency Exchange Rate.\"\"\"\nfrom typing import Any, Dict, List, Optional\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class AlphaVantageAPIWrapper(BaseModel):\n    \"\"\"Wrapper for AlphaVantage API for Currency Exchange Rate.\n    Docs for using:\n    1. Go to AlphaVantage and sign up for an API key\n    2. Save your API KEY into ALPHAVANTAGE_API_KEY env variable\n    \"\"\"\n    alphavantage_api_key: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key exists in environment.\"\"\"\n        values[\"alphavantage_api_key\"] = get_from_dict_or_env(\n            values, \"alphavantage_api_key\", \"ALPHAVANTAGE_API_KEY\"\n        )\n        return values\n    def _get_exchange_rate(\n        self, from_currency: str, to_currency: str\n    ) -> Dict[str, Any]:\n        \"\"\"Make a request to the AlphaVantage API to get the exchange rate.\"\"\"\n        response = requests.get(\n            \"https://www.alphavantage.co/query/\",\n            params={\n                \"function\": \"CURRENCY_EXCHANGE_RATE\",\n                \"from_currency\": from_currency,\n                \"to_currency\": to_currency,\n                \"apikey\": self.alphavantage_api_key,\n            },\n        )\n        response.raise_for_status()\n        data = response.json()\n        if \"Error Message\" in data:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/alpha_vantage.html"}
{"id": "f03dfd4a71c9-1", "text": "data = response.json()\n        if \"Error Message\" in data:\n            raise ValueError(f\"API Error: {data['Error Message']}\")\n        return data\n    @property\n    def standard_currencies(self) -> List[str]:\n        return [\"USD\", \"EUR\", \"GBP\", \"JPY\", \"CHF\", \"CAD\", \"AUD\", \"NZD\"]\n[docs]    def run(self, from_currency: str, to_currency: str) -> str:\n        \"\"\"Get the current exchange rate for a specified currency pair.\"\"\"\n        if to_currency not in self.standard_currencies:\n            from_currency, to_currency = to_currency, from_currency\n        data = self._get_exchange_rate(from_currency, to_currency)\n        return data[\"Realtime Currency Exchange Rate\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/alpha_vantage.html"}
{"id": "fd7cde9647e4-0", "text": "Source code for langchain.utilities.google_serper\n\"\"\"Util that calls Google Search using the Serper.dev API.\"\"\"\nfrom typing import Any, Dict, List, Optional\nimport aiohttp\nimport requests\nfrom typing_extensions import Literal\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class GoogleSerperAPIWrapper(BaseModel):\n    \"\"\"Wrapper around the Serper.dev Google Search API.\n    You can create a free API key at https://serper.dev.\n    To use, you should have the environment variable ``SERPER_API_KEY``\n    set with your API key, or pass `serper_api_key` as a named parameter\n    to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.utilities import GoogleSerperAPIWrapper\n            google_serper = GoogleSerperAPIWrapper()\n    \"\"\"\n    k: int = 10\n    gl: str = \"us\"\n    hl: str = \"en\"\n    # \"places\" and \"images\" is available from Serper but not implemented in the\n    # parser of run(). They can be used in results()\n    type: Literal[\"news\", \"search\", \"places\", \"images\"] = \"search\"\n    result_key_for_type = {\n        \"news\": \"news\",\n        \"places\": \"places\",\n        \"images\": \"images\",\n        \"search\": \"organic\",\n    }\n    tbs: Optional[str] = None\n    serper_api_key: Optional[str] = None\n    aiosession: Optional[aiohttp.ClientSession] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html"}
{"id": "fd7cde9647e4-1", "text": "@root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key exists in environment.\"\"\"\n        serper_api_key = get_from_dict_or_env(\n            values, \"serper_api_key\", \"SERPER_API_KEY\"\n        )\n        values[\"serper_api_key\"] = serper_api_key\n        return values\n[docs]    def results(self, query: str, **kwargs: Any) -> Dict:\n        \"\"\"Run query through GoogleSearch.\"\"\"\n        return self._google_serper_api_results(\n            query,\n            gl=self.gl,\n            hl=self.hl,\n            num=self.k,\n            tbs=self.tbs,\n            search_type=self.type,\n            **kwargs,\n        )\n[docs]    def run(self, query: str, **kwargs: Any) -> str:\n        \"\"\"Run query through GoogleSearch and parse result.\"\"\"\n        results = self._google_serper_api_results(\n            query,\n            gl=self.gl,\n            hl=self.hl,\n            num=self.k,\n            tbs=self.tbs,\n            search_type=self.type,\n            **kwargs,\n        )\n        return self._parse_results(results)\n[docs]    async def aresults(self, query: str, **kwargs: Any) -> Dict:\n        \"\"\"Run query through GoogleSearch.\"\"\"\n        results = await self._async_google_serper_search_results(\n            query,\n            gl=self.gl,\n            hl=self.hl,\n            num=self.k,\n            search_type=self.type,\n            tbs=self.tbs,\n            **kwargs,\n        )\n        return results\n[docs]    async def arun(self, query: str, **kwargs: Any) -> str:\n        \"\"\"Run query through GoogleSearch and parse result async.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html"}
{"id": "fd7cde9647e4-2", "text": "\"\"\"Run query through GoogleSearch and parse result async.\"\"\"\n        results = await self._async_google_serper_search_results(\n            query,\n            gl=self.gl,\n            hl=self.hl,\n            num=self.k,\n            search_type=self.type,\n            tbs=self.tbs,\n            **kwargs,\n        )\n        return self._parse_results(results)\n    def _parse_snippets(self, results: dict) -> List[str]:\n        snippets = []\n        if results.get(\"answerBox\"):\n            answer_box = results.get(\"answerBox\", {})\n            if answer_box.get(\"answer\"):\n                return [answer_box.get(\"answer\")]\n            elif answer_box.get(\"snippet\"):\n                return [answer_box.get(\"snippet\").replace(\"\\n\", \" \")]\n            elif answer_box.get(\"snippetHighlighted\"):\n                return answer_box.get(\"snippetHighlighted\")\n        if results.get(\"knowledgeGraph\"):\n            kg = results.get(\"knowledgeGraph\", {})\n            title = kg.get(\"title\")\n            entity_type = kg.get(\"type\")\n            if entity_type:\n                snippets.append(f\"{title}: {entity_type}.\")\n            description = kg.get(\"description\")\n            if description:\n                snippets.append(description)\n            for attribute, value in kg.get(\"attributes\", {}).items():\n                snippets.append(f\"{title} {attribute}: {value}.\")\n        for result in results[self.result_key_for_type[self.type]][: self.k]:\n            if \"snippet\" in result:\n                snippets.append(result[\"snippet\"])\n            for attribute, value in result.get(\"attributes\", {}).items():\n                snippets.append(f\"{attribute}: {value}.\")\n        if len(snippets) == 0:\n            return [\"No good Google Search Result was found\"]\n        return snippets", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html"}
{"id": "fd7cde9647e4-3", "text": "return [\"No good Google Search Result was found\"]\n        return snippets\n    def _parse_results(self, results: dict) -> str:\n        return \" \".join(self._parse_snippets(results))\n    def _google_serper_api_results(\n        self, search_term: str, search_type: str = \"search\", **kwargs: Any\n    ) -> dict:\n        headers = {\n            \"X-API-KEY\": self.serper_api_key or \"\",\n            \"Content-Type\": \"application/json\",\n        }\n        params = {\n            \"q\": search_term,\n            **{key: value for key, value in kwargs.items() if value is not None},\n        }\n        response = requests.post(\n            f\"https://google.serper.dev/{search_type}\", headers=headers, params=params\n        )\n        response.raise_for_status()\n        search_results = response.json()\n        return search_results\n    async def _async_google_serper_search_results(\n        self, search_term: str, search_type: str = \"search\", **kwargs: Any\n    ) -> dict:\n        headers = {\n            \"X-API-KEY\": self.serper_api_key or \"\",\n            \"Content-Type\": \"application/json\",\n        }\n        url = f\"https://google.serper.dev/{search_type}\"\n        params = {\n            \"q\": search_term,\n            **{key: value for key, value in kwargs.items() if value is not None},\n        }\n        if not self.aiosession:\n            async with aiohttp.ClientSession() as session:\n                async with session.post(\n                    url, params=params, headers=headers, raise_for_status=False\n                ) as response:\n                    search_results = await response.json()\n        else:\n            async with self.aiosession.post(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html"}
{"id": "fd7cde9647e4-4", "text": "else:\n            async with self.aiosession.post(\n                url, params=params, headers=headers, raise_for_status=True\n            ) as response:\n                search_results = await response.json()\n        return search_results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html"}
{"id": "e99c382ce3ba-0", "text": "Source code for langchain.utilities.duckduckgo_search\n\"\"\"Util that calls DuckDuckGo Search.\nNo setup required. Free.\nhttps://pypi.org/project/duckduckgo-search/\n\"\"\"\nfrom typing import Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\n[docs]class DuckDuckGoSearchAPIWrapper(BaseModel):\n    \"\"\"Wrapper for DuckDuckGo Search API.\n    Free and does not require any setup.\n    \"\"\"\n    region: Optional[str] = \"wt-wt\"\n    safesearch: str = \"moderate\"\n    time: Optional[str] = \"y\"\n    max_results: int = 5\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that python package exists in environment.\"\"\"\n        try:\n            from duckduckgo_search import DDGS  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"Could not import duckduckgo-search python package. \"\n                \"Please install it with `pip install duckduckgo-search`.\"\n            )\n        return values\n[docs]    def get_snippets(self, query: str) -> List[str]:\n        \"\"\"Run query through DuckDuckGo and return concatenated results.\"\"\"\n        from duckduckgo_search import DDGS\n        with DDGS() as ddgs:\n            results = ddgs.text(\n                query,\n                region=self.region,\n                safesearch=self.safesearch,\n                timelimit=self.time,\n            )\n            if results is None:\n                return [\"No good DuckDuckGo Search Result was found\"]\n            snippets = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html"}
{"id": "e99c382ce3ba-1", "text": "return [\"No good DuckDuckGo Search Result was found\"]\n            snippets = []\n            for i, res in enumerate(results, 1):\n                if res is not None:\n                    snippets.append(res[\"body\"])\n                if len(snippets) == self.max_results:\n                    break\n        return snippets\n[docs]    def run(self, query: str) -> str:\n        snippets = self.get_snippets(query)\n        return \" \".join(snippets)\n[docs]    def results(\n        self, query: str, num_results: int, backend: str = \"api\"\n    ) -> List[Dict[str, str]]:\n        \"\"\"Run query through DuckDuckGo and return metadata.\n        Args:\n            query: The query to search for.\n            num_results: The number of results to return.\n        Returns:\n            A list of dictionaries with the following keys:\n                snippet - The description of the result.\n                title - The title of the result.\n                link - The link to the result.\n        \"\"\"\n        from duckduckgo_search import DDGS\n        with DDGS() as ddgs:\n            results = ddgs.text(\n                query,\n                region=self.region,\n                safesearch=self.safesearch,\n                timelimit=self.time,\n                backend=backend,\n            )\n            if results is None:\n                return [{\"Result\": \"No good DuckDuckGo Search Result was found\"}]\n            def to_metadata(result: Dict) -> Dict[str, str]:\n                if backend == \"news\":\n                    return {\n                        \"date\": result[\"date\"],\n                        \"title\": result[\"title\"],\n                        \"snippet\": result[\"body\"],\n                        \"source\": result[\"source\"],\n                        \"link\": result[\"url\"],\n                    }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html"}
{"id": "e99c382ce3ba-2", "text": "\"link\": result[\"url\"],\n                    }\n                return {\n                    \"snippet\": result[\"body\"],\n                    \"title\": result[\"title\"],\n                    \"link\": result[\"href\"],\n                }\n            formatted_results = []\n            for i, res in enumerate(results, 1):\n                if res is not None:\n                    formatted_results.append(to_metadata(res))\n                if len(formatted_results) == num_results:\n                    break\n        return formatted_results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html"}
{"id": "9bc167c2f835-0", "text": "Source code for langchain.utilities.google_search\n\"\"\"Util that calls Google Search.\"\"\"\nfrom typing import Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class GoogleSearchAPIWrapper(BaseModel):\n    \"\"\"Wrapper for Google Search API.\n    Adapted from: Instructions adapted from https://stackoverflow.com/questions/\n    37083058/\n    programmatically-searching-google-in-python-using-custom-search\n    TODO: DOCS for using it\n    1. Install google-api-python-client\n    - If you don't already have a Google account, sign up.\n    - If you have never created a Google APIs Console project,\n    read the Managing Projects page and create a project in the Google API Console.\n    - Install the library using pip install google-api-python-client\n    2. Enable the Custom Search API\n    - Navigate to the APIs & Services\u2192Dashboard panel in Cloud Console.\n    - Click Enable APIs and Services.\n    - Search for Custom Search API and click on it.\n    - Click Enable.\n    URL for it: https://console.cloud.google.com/apis/library/customsearch.googleapis\n    .com\n    3. To create an API key:\n    - Navigate to the APIs & Services \u2192 Credentials panel in Cloud Console.\n    - Select Create credentials, then select API key from the drop-down menu.\n    - The API key created dialog box displays your newly created key.\n    - You now have an API_KEY\n    Alternatively, you can just generate an API key here:\n    https://developers.google.com/custom-search/docs/paid_element#api_key\n    4. Setup Custom Search Engine so you can search the entire web\n    - Create a custom search engine here: https://programmablesearchengine.google.com/.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html"}
{"id": "9bc167c2f835-1", "text": "- Create a custom search engine here: https://programmablesearchengine.google.com/.\n    - In `What to search` to search, pick the `Search the entire Web` option.\n    After search engine is created, you can click on it and find `Search engine ID`\n      on the Overview page.\n    \"\"\"\n    search_engine: Any  #: :meta private:\n    google_api_key: Optional[str] = None\n    google_cse_id: Optional[str] = None\n    k: int = 10\n    siterestrict: bool = False\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    def _google_search_results(self, search_term: str, **kwargs: Any) -> List[dict]:\n        cse = self.search_engine.cse()\n        if self.siterestrict:\n            cse = cse.siterestrict()\n        res = cse.list(q=search_term, cx=self.google_cse_id, **kwargs).execute()\n        return res.get(\"items\", [])\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        google_api_key = get_from_dict_or_env(\n            values, \"google_api_key\", \"GOOGLE_API_KEY\"\n        )\n        values[\"google_api_key\"] = google_api_key\n        google_cse_id = get_from_dict_or_env(values, \"google_cse_id\", \"GOOGLE_CSE_ID\")\n        values[\"google_cse_id\"] = google_cse_id\n        try:\n            from googleapiclient.discovery import build\n        except ImportError:\n            raise ImportError(\n                \"google-api-python-client is not installed. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html"}
{"id": "9bc167c2f835-2", "text": "raise ImportError(\n                \"google-api-python-client is not installed. \"\n                \"Please install it with `pip install google-api-python-client\"\n                \">=2.100.0`\"\n            )\n        service = build(\"customsearch\", \"v1\", developerKey=google_api_key)\n        values[\"search_engine\"] = service\n        return values\n[docs]    def run(self, query: str) -> str:\n        \"\"\"Run query through GoogleSearch and parse result.\"\"\"\n        snippets = []\n        results = self._google_search_results(query, num=self.k)\n        if len(results) == 0:\n            return \"No good Google Search Result was found\"\n        for result in results:\n            if \"snippet\" in result:\n                snippets.append(result[\"snippet\"])\n        return \" \".join(snippets)\n[docs]    def results(\n        self,\n        query: str,\n        num_results: int,\n        search_params: Optional[Dict[str, str]] = None,\n    ) -> List[Dict]:\n        \"\"\"Run query through GoogleSearch and return metadata.\n        Args:\n            query: The query to search for.\n            num_results: The number of results to return.\n            search_params: Parameters to be passed on search\n        Returns:\n            A list of dictionaries with the following keys:\n                snippet - The description of the result.\n                title - The title of the result.\n                link - The link to the result.\n        \"\"\"\n        metadata_results = []\n        results = self._google_search_results(\n            query, num=num_results, **(search_params or {})\n        )\n        if len(results) == 0:\n            return [{\"Result\": \"No good Google Search Result was found\"}]\n        for result in results:\n            metadata_result = {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html"}
{"id": "9bc167c2f835-3", "text": "for result in results:\n            metadata_result = {\n                \"title\": result[\"title\"],\n                \"link\": result[\"link\"],\n            }\n            if \"snippet\" in result:\n                metadata_result[\"snippet\"] = result[\"snippet\"]\n            metadata_results.append(metadata_result)\n        return metadata_results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html"}
{"id": "f4feb469b5ad-0", "text": "Source code for langchain.utilities.redis\nfrom __future__ import annotations\nimport logging\nimport re\nfrom typing import TYPE_CHECKING, Any, List, Optional, Pattern\nfrom urllib.parse import urlparse\nimport numpy as np\nlogger = logging.getLogger(__name__)\nif TYPE_CHECKING:\n    from redis.client import Redis as RedisType\ndef _array_to_buffer(array: List[float], dtype: Any = np.float32) -> bytes:\n    return np.array(array).astype(dtype).tobytes()\ndef _buffer_to_array(buffer: bytes, dtype: Any = np.float32) -> List[float]:\n    return np.frombuffer(buffer, dtype=dtype).tolist()\n[docs]class TokenEscaper:\n    \"\"\"\n    Escape punctuation within an input string.\n    \"\"\"\n    # Characters that RediSearch requires us to escape during queries.\n    # Source: https://redis.io/docs/stack/search/reference/escaping/#the-rules-of-text-field-tokenization\n    DEFAULT_ESCAPED_CHARS = r\"[,.<>{}\\[\\]\\\\\\\"\\':;!@#$%^&*()\\-+=~\\/]\"\n[docs]    def __init__(self, escape_chars_re: Optional[Pattern] = None):\n        if escape_chars_re:\n            self.escaped_chars_re = escape_chars_re\n        else:\n            self.escaped_chars_re = re.compile(self.DEFAULT_ESCAPED_CHARS)\n[docs]    def escape(self, value: str) -> str:\n        def escape_symbol(match: re.Match) -> str:\n            value = match.group(0)\n            return f\"\\\\{value}\"\n        return self.escaped_chars_re.sub(escape_symbol, value)\n[docs]def check_redis_module_exist(client: RedisType, required_modules: List[dict]) -> None:\n    \"\"\"Check if the correct Redis modules are installed.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html"}
{"id": "f4feb469b5ad-1", "text": "\"\"\"Check if the correct Redis modules are installed.\"\"\"\n    installed_modules = client.module_list()\n    installed_modules = {\n        module[b\"name\"].decode(\"utf-8\"): module for module in installed_modules\n    }\n    for module in required_modules:\n        if module[\"name\"] in installed_modules and int(\n            installed_modules[module[\"name\"]][b\"ver\"]\n        ) >= int(module[\"ver\"]):\n            return\n    # otherwise raise error\n    error_message = (\n        \"Redis cannot be used as a vector database without RediSearch >=2.4\"\n        \"Please head to https://redis.io/docs/stack/search/quick_start/\"\n        \"to know more about installing the RediSearch module within Redis Stack.\"\n    )\n    logger.error(error_message)\n    raise ValueError(error_message)\n[docs]def get_client(redis_url: str, **kwargs: Any) -> RedisType:\n    \"\"\"Get a redis client from the connection url given. This helper accepts\n    urls for Redis server (TCP with/without TLS or UnixSocket) as well as\n    Redis Sentinel connections.\n    Redis Cluster is not supported.\n    Before creating a connection the existence of the database driver is checked\n    an and ValueError raised otherwise\n    To use, you should have the ``redis`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.utilities.redis import get_client\n            redis_client = get_client(\n                redis_url=\"redis://username:password@localhost:6379\"\n                index_name=\"my-index\",\n                embedding_function=embeddings.embed_query,\n            )\n    To use a redis replication setup with multiple redis server and redis sentinels\n    set \"redis_url\" to \"redis+sentinel://\" scheme. With this url format a path is", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html"}
{"id": "f4feb469b5ad-2", "text": "needed holding the name of the redis service within the sentinels to get the\n    correct redis server connection. The default service name is \"mymaster\". The\n    optional second part of the path is the redis db number to connect to.\n    An optional username or password is used for booth connections to the rediserver\n    and the sentinel, different passwords for server and sentinel are not supported.\n    And as another constraint only one sentinel instance can be given:\n    Example:\n        .. code-block:: python\n            from langchain.utilities.redis import get_client\n            redis_client = get_client(\n                redis_url=\"redis+sentinel://username:password@sentinelhost:26379/mymaster/0\"\n                index_name=\"my-index\",\n                embedding_function=embeddings.embed_query,\n            )\n    \"\"\"\n    # Initialize with necessary components.\n    try:\n        import redis\n    except ImportError:\n        raise ImportError(\n            \"Could not import redis python package. \"\n            \"Please install it with `pip install redis>=4.1.0`.\"\n        )\n    # check if normal redis:// or redis+sentinel:// url\n    if redis_url.startswith(\"redis+sentinel\"):\n        redis_client = _redis_sentinel_client(redis_url, **kwargs)\n    elif redis_url.startswith(\"rediss+sentinel\"):  # sentinel with TLS support enables\n        kwargs[\"ssl\"] = True\n        if \"ssl_cert_reqs\" not in kwargs:\n            kwargs[\"ssl_cert_reqs\"] = \"none\"\n        redis_client = _redis_sentinel_client(redis_url, **kwargs)\n    else:\n        # connect to redis server from url, reconnect with cluster client if needed\n        redis_client = redis.from_url(redis_url, **kwargs)\n        if _check_for_cluster(redis_client):\n            redis_client.close()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html"}
{"id": "f4feb469b5ad-3", "text": "if _check_for_cluster(redis_client):\n            redis_client.close()\n            redis_client = _redis_cluster_client(redis_url, **kwargs)\n    return redis_client\ndef _redis_sentinel_client(redis_url: str, **kwargs: Any) -> RedisType:\n    \"\"\"helper method to parse an (un-official) redis+sentinel url\n    and create a Sentinel connection to fetch the final redis client\n    connection to a replica-master for read-write operations.\n    If username and/or password for authentication is given the\n    same credentials are used for the Redis Sentinel as well as Redis Server.\n    With this implementation using a redis url only it is not possible\n    to use different data for authentication on booth systems.\n    \"\"\"\n    import redis\n    parsed_url = urlparse(redis_url)\n    # sentinel needs list with (host, port) tuple, use default port if none available\n    sentinel_list = [(parsed_url.hostname or \"localhost\", parsed_url.port or 26379)]\n    if parsed_url.path:\n        # \"/mymaster/0\" first part is service name, optional second part is db number\n        path_parts = parsed_url.path.split(\"/\")\n        service_name = path_parts[1] or \"mymaster\"\n        if len(path_parts) > 2:\n            kwargs[\"db\"] = path_parts[2]\n    else:\n        service_name = \"mymaster\"\n    sentinel_args = {}\n    if parsed_url.password:\n        sentinel_args[\"password\"] = parsed_url.password\n        kwargs[\"password\"] = parsed_url.password\n    if parsed_url.username:\n        sentinel_args[\"username\"] = parsed_url.username\n        kwargs[\"username\"] = parsed_url.username\n    # check for all SSL related properties and copy them into sentinel_kwargs too,\n    # add client_name also\n    for arg in kwargs:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html"}
{"id": "f4feb469b5ad-4", "text": "# add client_name also\n    for arg in kwargs:\n        if arg.startswith(\"ssl\") or arg == \"client_name\":\n            sentinel_args[arg] = kwargs[arg]\n    # sentinel user/pass is part of sentinel_kwargs, user/pass for redis server\n    # connection as direct parameter in kwargs\n    sentinel_client = redis.sentinel.Sentinel(\n        sentinel_list, sentinel_kwargs=sentinel_args, **kwargs\n    )\n    # redis server might have password but not sentinel - fetch this error and try\n    # again without pass, everything else cannot be handled here -> user needed\n    try:\n        sentinel_client.execute_command(\"ping\")\n    except redis.exceptions.AuthenticationError as ae:\n        if \"no password is set\" in ae.args[0]:\n            logger.warning(\n                \"Redis sentinel connection configured with password but Sentinel \\\nanswered NO PASSWORD NEEDED - Please check Sentinel configuration\"\n            )\n            sentinel_client = redis.sentinel.Sentinel(sentinel_list, **kwargs)\n        else:\n            raise ae\n    return sentinel_client.master_for(service_name)\ndef _check_for_cluster(redis_client: RedisType) -> bool:\n    import redis\n    try:\n        cluster_info = redis_client.info(\"cluster\")\n        return cluster_info[\"cluster_enabled\"] == 1\n    except redis.exceptions.RedisError:\n        return False\ndef _redis_cluster_client(redis_url: str, **kwargs: Any) -> RedisType:\n    from redis.cluster import RedisCluster\n    return RedisCluster.from_url(redis_url, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html"}
{"id": "c94171f45ccd-0", "text": "Source code for langchain.utilities.wikipedia\n\"\"\"Util that calls Wikipedia.\"\"\"\nimport logging\nfrom typing import Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema import Document\nlogger = logging.getLogger(__name__)\nWIKIPEDIA_MAX_QUERY_LENGTH = 300\n[docs]class WikipediaAPIWrapper(BaseModel):\n    \"\"\"Wrapper around WikipediaAPI.\n    To use, you should have the ``wikipedia`` python package installed.\n    This wrapper will use the Wikipedia API to conduct searches and\n    fetch page summaries. By default, it will return the page summaries\n    of the top-k results.\n    It limits the Document content by doc_content_chars_max.\n    \"\"\"\n    wiki_client: Any  #: :meta private:\n    top_k_results: int = 3\n    lang: str = \"en\"\n    load_all_available_meta: bool = False\n    doc_content_chars_max: int = 4000\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the python package exists in environment.\"\"\"\n        try:\n            import wikipedia\n            wikipedia.set_lang(values[\"lang\"])\n            values[\"wiki_client\"] = wikipedia\n        except ImportError:\n            raise ImportError(\n                \"Could not import wikipedia python package. \"\n                \"Please install it with `pip install wikipedia`.\"\n            )\n        return values\n[docs]    def run(self, query: str) -> str:\n        \"\"\"Run Wikipedia search and get page summaries.\"\"\"\n        page_titles = self.wiki_client.search(query[:WIKIPEDIA_MAX_QUERY_LENGTH])\n        summaries = []\n        for page_title in page_titles[: self.top_k_results]:\n            if wiki_page := self._fetch_page(page_title):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html"}
{"id": "c94171f45ccd-1", "text": "if wiki_page := self._fetch_page(page_title):\n                if summary := self._formatted_page_summary(page_title, wiki_page):\n                    summaries.append(summary)\n        if not summaries:\n            return \"No good Wikipedia Search Result was found\"\n        return \"\\n\\n\".join(summaries)[: self.doc_content_chars_max]\n    @staticmethod\n    def _formatted_page_summary(page_title: str, wiki_page: Any) -> Optional[str]:\n        return f\"Page: {page_title}\\nSummary: {wiki_page.summary}\"\n    def _page_to_document(self, page_title: str, wiki_page: Any) -> Document:\n        main_meta = {\n            \"title\": page_title,\n            \"summary\": wiki_page.summary,\n            \"source\": wiki_page.url,\n        }\n        add_meta = (\n            {\n                \"categories\": wiki_page.categories,\n                \"page_url\": wiki_page.url,\n                \"image_urls\": wiki_page.images,\n                \"related_titles\": wiki_page.links,\n                \"parent_id\": wiki_page.parent_id,\n                \"references\": wiki_page.references,\n                \"revision_id\": wiki_page.revision_id,\n                \"sections\": wiki_page.sections,\n            }\n            if self.load_all_available_meta\n            else {}\n        )\n        doc = Document(\n            page_content=wiki_page.content[: self.doc_content_chars_max],\n            metadata={\n                **main_meta,\n                **add_meta,\n            },\n        )\n        return doc\n    def _fetch_page(self, page: str) -> Optional[str]:\n        try:\n            return self.wiki_client.page(title=page, auto_suggest=False)\n        except (\n            self.wiki_client.exceptions.PageError,\n            self.wiki_client.exceptions.DisambiguationError,\n        ):\n            return None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html"}
{"id": "c94171f45ccd-2", "text": "self.wiki_client.exceptions.DisambiguationError,\n        ):\n            return None\n[docs]    def load(self, query: str) -> List[Document]:\n        \"\"\"\n        Run Wikipedia search and get the article text plus the meta information.\n        See\n        Returns: a list of documents.\n        \"\"\"\n        page_titles = self.wiki_client.search(query[:WIKIPEDIA_MAX_QUERY_LENGTH])\n        docs = []\n        for page_title in page_titles[: self.top_k_results]:\n            if wiki_page := self._fetch_page(page_title):\n                if doc := self._page_to_document(page_title, wiki_page):\n                    docs.append(doc)\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html"}
{"id": "442f754921fd-0", "text": "Source code for langchain.utilities.tensorflow_datasets\nimport logging\nfrom typing import Any, Callable, Dict, Iterator, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema import Document\nlogger = logging.getLogger(__name__)\n[docs]class TensorflowDatasets(BaseModel):\n    \"\"\"Access to the TensorFlow Datasets.\n    The Current implementation can work only with datasets that fit in a memory.\n    `TensorFlow Datasets` is a collection of datasets ready to use, with TensorFlow\n    or other Python ML frameworks, such as Jax. All datasets are exposed\n    as `tf.data.Datasets`.\n    To get started see the Guide: https://www.tensorflow.org/datasets/overview and\n    the list of datasets: https://www.tensorflow.org/datasets/catalog/\n                                               overview#all_datasets\n    You have to provide the sample_to_document_function: a function that\n       a sample from the dataset-specific format to the Document.\n    Attributes:\n        dataset_name: the name of the dataset to load\n        split_name: the name of the split to load. Defaults to \"train\".\n        load_max_docs: a limit to the number of loaded documents. Defaults to 100.\n        sample_to_document_function: a function that converts a dataset sample\n          to a Document\n    Example:\n        .. code-block:: python\n            from langchain.utilities import TensorflowDatasets\n            def mlqaen_example_to_document(example: dict) -> Document:\n                return Document(\n                    page_content=decode_to_str(example[\"context\"]),\n                    metadata={\n                        \"id\": decode_to_str(example[\"id\"]),\n                        \"title\": decode_to_str(example[\"title\"]),\n                        \"question\": decode_to_str(example[\"question\"]),\n                        \"answer\": decode_to_str(example[\"answers\"][\"text\"][0]),\n                    },\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tensorflow_datasets.html"}
{"id": "442f754921fd-1", "text": "},\n                )\n            tsds_client = TensorflowDatasets(\n                    dataset_name=\"mlqa/en\",\n                    split_name=\"train\",\n                    load_max_docs=MAX_DOCS,\n                    sample_to_document_function=mlqaen_example_to_document,\n                )\n    \"\"\"\n    dataset_name: str = \"\"\n    split_name: str = \"train\"\n    load_max_docs: int = 100\n    sample_to_document_function: Optional[Callable[[Dict], Document]] = None\n    dataset: Any  #: :meta private:\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the python package exists in environment.\"\"\"\n        try:\n            import tensorflow  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"Could not import tensorflow python package. \"\n                \"Please install it with `pip install tensorflow`.\"\n            )\n        try:\n            import tensorflow_datasets\n        except ImportError:\n            raise ImportError(\n                \"Could not import tensorflow_datasets python package. \"\n                \"Please install it with `pip install tensorflow-datasets`.\"\n            )\n        if values[\"sample_to_document_function\"] is None:\n            raise ValueError(\n                \"sample_to_document_function is None. \"\n                \"Please provide a function that converts a dataset sample to\"\n                \"  a Document.\"\n            )\n        values[\"dataset\"] = tensorflow_datasets.load(\n            values[\"dataset_name\"], split=values[\"split_name\"]\n        )\n        return values\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Download a selected dataset lazily.\n        Returns: an iterator of Documents.\n        \"\"\"\n        return (\n            self.sample_to_document_function(s)\n            for s in self.dataset.take(self.load_max_docs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tensorflow_datasets.html"}
{"id": "442f754921fd-2", "text": "for s in self.dataset.take(self.load_max_docs)\n            if self.sample_to_document_function is not None\n        )\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Download a selected dataset.\n        Returns: a list of Documents.\n        \"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tensorflow_datasets.html"}
{"id": "f802ea56149f-0", "text": "Source code for langchain.utilities.brave_search\nimport json\nfrom typing import List\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema import Document\n[docs]class BraveSearchWrapper(BaseModel):\n    \"\"\"Wrapper around the Brave search engine.\"\"\"\n    api_key: str\n    \"\"\"The API key to use for the Brave search engine.\"\"\"\n    search_kwargs: dict = Field(default_factory=dict)\n    \"\"\"Additional keyword arguments to pass to the search request.\"\"\"\n    base_url: str = \"https://api.search.brave.com/res/v1/web/search\"\n    \"\"\"The base URL for the Brave search engine.\"\"\"\n[docs]    def run(self, query: str) -> str:\n        \"\"\"Query the Brave search engine and return the results as a JSON string.\n        Args:\n            query: The query to search for.\n        Returns: The results as a JSON string.\n        \"\"\"\n        web_search_results = self._search_request(query=query)\n        final_results = [\n            {\n                \"title\": item.get(\"title\"),\n                \"link\": item.get(\"url\"),\n                \"snippet\": item.get(\"description\"),\n            }\n            for item in web_search_results\n        ]\n        return json.dumps(final_results)\n[docs]    def download_documents(self, query: str) -> List[Document]:\n        \"\"\"Query the Brave search engine and return the results as a list of Documents.\n        Args:\n            query: The query to search for.\n        Returns: The results as a list of Documents.\n        \"\"\"\n        results = self._search_request(query)\n        return [\n            Document(\n                page_content=item.get(\"description\"),\n                metadata={\"title\": item.get(\"title\"), \"link\": item.get(\"url\")},\n            )\n            for item in results\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/brave_search.html"}
{"id": "f802ea56149f-1", "text": ")\n            for item in results\n        ]\n    def _search_request(self, query: str) -> List[dict]:\n        headers = {\n            \"X-Subscription-Token\": self.api_key,\n            \"Accept\": \"application/json\",\n        }\n        req = requests.PreparedRequest()\n        params = {**self.search_kwargs, **{\"q\": query}}\n        req.prepare_url(self.base_url, params)\n        if req.url is None:\n            raise ValueError(\"prepared url is None, this should not happen\")\n        response = requests.get(req.url, headers=headers)\n        if not response.ok:\n            raise Exception(f\"HTTP error {response.status_code}\")\n        return response.json().get(\"web\", {}).get(\"results\", [])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/brave_search.html"}
{"id": "b73d66fc7f66-0", "text": "Source code for langchain.utilities.searx_search\n\"\"\"Utility for using SearxNG meta search API.\nSearxNG is a privacy-friendly free metasearch engine that aggregates results from\n`multiple search engines\n<https://docs.searxng.org/admin/engines/configured_engines.html>`_ and databases and\nsupports the `OpenSearch\n<https://github.com/dewitt/opensearch/blob/master/opensearch-1-1-draft-6.md>`_\nspecification.\nMore details on the installation instructions `here. <../../integrations/searx.html>`_\nFor the search API refer to https://docs.searxng.org/dev/search_api.html\nQuick Start\n-----------\nIn order to use this utility you need to provide the searx host. This can be done\nby passing the named parameter :attr:`searx_host <SearxSearchWrapper.searx_host>`\nor exporting the environment variable SEARX_HOST.\nNote: this is the only required parameter.\nThen create a searx search instance like this:\n    .. code-block:: python\n        from langchain.utilities import SearxSearchWrapper\n        # when the host starts with `http` SSL is disabled and the connection\n        # is assumed to be on a private network\n        searx_host='http://self.hosted'\n        search = SearxSearchWrapper(searx_host=searx_host)\nYou can now use the ``search`` instance to query the searx API.\nSearching\n---------\nUse the :meth:`run() <SearxSearchWrapper.run>` and\n:meth:`results() <SearxSearchWrapper.results>` methods to query the searx API.\nOther methods are available for convenience.\n:class:`SearxResults` is a convenience wrapper around the raw json result.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html"}
{"id": "b73d66fc7f66-1", "text": ":class:`SearxResults` is a convenience wrapper around the raw json result.\nExample usage of the ``run`` method to make a search:\n    .. code-block:: python\n        s.run(query=\"what is the best search engine?\")\nEngine Parameters\n-----------------\nYou can pass any `accepted searx search API\n<https://docs.searxng.org/dev/search_api.html>`_ parameters to the\n:py:class:`SearxSearchWrapper` instance.\nIn the following example we are using the\n:attr:`engines <SearxSearchWrapper.engines>` and the ``language`` parameters:\n    .. code-block:: python\n        # assuming the searx host is set as above or exported as an env variable\n        s = SearxSearchWrapper(engines=['google', 'bing'],\n                            language='es')\nSearch Tips\n-----------\nSearx offers a special\n`search syntax <https://docs.searxng.org/user/index.html#search-syntax>`_\nthat can also be used instead of passing engine parameters.\nFor example the following query:\n    .. code-block:: python\n        s = SearxSearchWrapper(\"langchain library\", engines=['github'])\n        # can also be written as:\n        s = SearxSearchWrapper(\"langchain library !github\")\n        # or even:\n        s = SearxSearchWrapper(\"langchain library !gh\")\nIn some situations you might want to pass an extra string to the search query.\nFor example when the `run()` method is called by an agent. The search suffix can\nalso be used as a way to pass extra parameters to searx or the underlying search\nengines.\n    .. code-block:: python\n        # select the github engine and pass the search suffix", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html"}
{"id": "b73d66fc7f66-2", "text": ".. code-block:: python\n        # select the github engine and pass the search suffix\n        s = SearchWrapper(\"langchain library\", query_suffix=\"!gh\")\n        s = SearchWrapper(\"langchain library\")\n        # select github the conventional google search syntax\n        s.run(\"large language models\", query_suffix=\"site:github.com\")\n*NOTE*: A search suffix can be defined on both the instance and the method level.\nThe resulting query will be the concatenation of the two with the former taking\nprecedence.\nSee `SearxNG Configured Engines\n<https://docs.searxng.org/admin/engines/configured_engines.html>`_ and\n`SearxNG Search Syntax <https://docs.searxng.org/user/index.html#id1>`_\nfor more details.\nNotes\n-----\nThis wrapper is based on the SearxNG fork https://github.com/searxng/searxng which is\nbetter maintained than the original Searx project and offers more features.\nPublic searxNG instances often use a rate limiter for API usage, so you might want to\nuse a self hosted instance and disable the rate limiter.\nIf you are self-hosting an instance you can customize the rate limiter for your\nown network as described\n`here <https://docs.searxng.org/src/searx.botdetection.html#limiter-src>`_.\nFor a list of public SearxNG instances see https://searx.space/\n\"\"\"\nimport json\nfrom typing import Any, Dict, List, Optional\nimport aiohttp\nimport requests\nfrom langchain.pydantic_v1 import (\n    BaseModel,\n    Extra,\n    Field,\n    PrivateAttr,\n    root_validator,\n    validator,\n)\nfrom langchain.utils import get_from_dict_or_env", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html"}
{"id": "b73d66fc7f66-3", "text": "validator,\n)\nfrom langchain.utils import get_from_dict_or_env\ndef _get_default_params() -> dict:\n    return {\"language\": \"en\", \"format\": \"json\"}\n[docs]class SearxResults(dict):\n    \"\"\"Dict like wrapper around search api results.\"\"\"\n    _data: str = \"\"\n[docs]    def __init__(self, data: str):\n        \"\"\"Take a raw result from Searx and make it into a dict like object.\"\"\"\n        json_data = json.loads(data)\n        super().__init__(json_data)\n        self.__dict__ = self\n    def __str__(self) -> str:\n        \"\"\"Text representation of searx result.\"\"\"\n        return self._data\n    @property\n    def results(self) -> Any:\n        \"\"\"Silence mypy for accessing this field.\n        :meta private:\n        \"\"\"\n        return self.get(\"results\")\n    @property\n    def answers(self) -> Any:\n        \"\"\"Helper accessor on the json result.\"\"\"\n        return self.get(\"answers\")\n[docs]class SearxSearchWrapper(BaseModel):\n    \"\"\"Wrapper for Searx API.\n    To use you need to provide the searx host by passing the named parameter\n    ``searx_host`` or exporting the environment variable ``SEARX_HOST``.\n    In some situations you might want to disable SSL verification, for example\n    if you are running searx locally. You can do this by passing the named parameter\n    ``unsecure``. You can also pass the host url scheme as ``http`` to disable SSL.\n    Example:\n        .. code-block:: python\n            from langchain.utilities import SearxSearchWrapper\n            searx = SearxSearchWrapper(searx_host=\"http://localhost:8888\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html"}
{"id": "b73d66fc7f66-4", "text": "Example with SSL disabled:\n        .. code-block:: python\n            from langchain.utilities import SearxSearchWrapper\n            # note the unsecure parameter is not needed if you pass the url scheme as\n            # http\n            searx = SearxSearchWrapper(searx_host=\"http://localhost:8888\",\n                                                    unsecure=True)\n    \"\"\"\n    _result: SearxResults = PrivateAttr()\n    searx_host: str = \"\"\n    unsecure: bool = False\n    params: dict = Field(default_factory=_get_default_params)\n    headers: Optional[dict] = None\n    engines: Optional[List[str]] = []\n    categories: Optional[List[str]] = []\n    query_suffix: Optional[str] = \"\"\n    k: int = 10\n    aiosession: Optional[Any] = None\n    @validator(\"unsecure\")\n    def disable_ssl_warnings(cls, v: bool) -> bool:\n        \"\"\"Disable SSL warnings.\"\"\"\n        if v:\n            # requests.urllib3.disable_warnings()\n            try:\n                import urllib3\n                urllib3.disable_warnings()\n            except ImportError as e:\n                print(e)\n        return v\n    @root_validator()\n    def validate_params(cls, values: Dict) -> Dict:\n        \"\"\"Validate that custom searx params are merged with default ones.\"\"\"\n        user_params = values[\"params\"]\n        default = _get_default_params()\n        values[\"params\"] = {**default, **user_params}\n        engines = values.get(\"engines\")\n        if engines:\n            values[\"params\"][\"engines\"] = \",\".join(engines)\n        categories = values.get(\"categories\")\n        if categories:\n            values[\"params\"][\"categories\"] = \",\".join(categories)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html"}
{"id": "b73d66fc7f66-5", "text": "if categories:\n            values[\"params\"][\"categories\"] = \",\".join(categories)\n        searx_host = get_from_dict_or_env(values, \"searx_host\", \"SEARX_HOST\")\n        if not searx_host.startswith(\"http\"):\n            print(\n                f\"Warning: missing the url scheme on host \\\n                ! assuming secure https://{searx_host} \"\n            )\n            searx_host = \"https://\" + searx_host\n        elif searx_host.startswith(\"http://\"):\n            values[\"unsecure\"] = True\n            cls.disable_ssl_warnings(True)\n        values[\"searx_host\"] = searx_host\n        return values\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    def _searx_api_query(self, params: dict) -> SearxResults:\n        \"\"\"Actual request to searx API.\"\"\"\n        raw_result = requests.get(\n            self.searx_host,\n            headers=self.headers,\n            params=params,\n            verify=not self.unsecure,\n        )\n        # test if http result is ok\n        if not raw_result.ok:\n            raise ValueError(\"Searx API returned an error: \", raw_result.text)\n        res = SearxResults(raw_result.text)\n        self._result = res\n        return res\n    async def _asearx_api_query(self, params: dict) -> SearxResults:\n        if not self.aiosession:\n            async with aiohttp.ClientSession() as session:\n                async with session.get(\n                    self.searx_host,\n                    headers=self.headers,\n                    params=params,\n                    ssl=(lambda: False if self.unsecure else None)(),\n                ) as response:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html"}
{"id": "b73d66fc7f66-6", "text": ") as response:\n                    if not response.ok:\n                        raise ValueError(\"Searx API returned an error: \", response.text)\n                    result = SearxResults(await response.text())\n                    self._result = result\n        else:\n            async with self.aiosession.get(\n                self.searx_host,\n                headers=self.headers,\n                params=params,\n                verify=not self.unsecure,\n            ) as response:\n                if not response.ok:\n                    raise ValueError(\"Searx API returned an error: \", response.text)\n                result = SearxResults(await response.text())\n                self._result = result\n        return result\n[docs]    def run(\n        self,\n        query: str,\n        engines: Optional[List[str]] = None,\n        categories: Optional[List[str]] = None,\n        query_suffix: Optional[str] = \"\",\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Run query through Searx API and parse results.\n        You can pass any other params to the searx query API.\n        Args:\n            query: The query to search for.\n            query_suffix: Extra suffix appended to the query.\n            engines: List of engines to use for the query.\n            categories: List of categories to use for the query.\n            **kwargs: extra parameters to pass to the searx API.\n        Returns:\n            str: The result of the query.\n        Raises:\n            ValueError: If an error occurred with the query.\n        Example:\n            This will make a query to the qwant engine:\n            .. code-block:: python\n                from langchain.utilities import SearxSearchWrapper\n                searx = SearxSearchWrapper(searx_host=\"http://my.searx.host\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html"}
{"id": "b73d66fc7f66-7", "text": "searx.run(\"what is the weather in France ?\", engine=\"qwant\")\n                # the same result can be achieved using the `!` syntax of searx\n                # to select the engine using `query_suffix`\n                searx.run(\"what is the weather in France ?\", query_suffix=\"!qwant\")\n        \"\"\"\n        _params = {\n            \"q\": query,\n        }\n        params = {**self.params, **_params, **kwargs}\n        if self.query_suffix and len(self.query_suffix) > 0:\n            params[\"q\"] += \" \" + self.query_suffix\n        if isinstance(query_suffix, str) and len(query_suffix) > 0:\n            params[\"q\"] += \" \" + query_suffix\n        if isinstance(engines, list) and len(engines) > 0:\n            params[\"engines\"] = \",\".join(engines)\n        if isinstance(categories, list) and len(categories) > 0:\n            params[\"categories\"] = \",\".join(categories)\n        res = self._searx_api_query(params)\n        if len(res.answers) > 0:\n            toret = res.answers[0]\n        # only return the content of the results list\n        elif len(res.results) > 0:\n            toret = \"\\n\\n\".join([r.get(\"content\", \"\") for r in res.results[: self.k]])\n        else:\n            toret = \"No good search result found\"\n        return toret\n[docs]    async def arun(\n        self,\n        query: str,\n        engines: Optional[List[str]] = None,\n        query_suffix: Optional[str] = \"\",\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Asynchronously version of `run`.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html"}
{"id": "b73d66fc7f66-8", "text": ") -> str:\n        \"\"\"Asynchronously version of `run`.\"\"\"\n        _params = {\n            \"q\": query,\n        }\n        params = {**self.params, **_params, **kwargs}\n        if self.query_suffix and len(self.query_suffix) > 0:\n            params[\"q\"] += \" \" + self.query_suffix\n        if isinstance(query_suffix, str) and len(query_suffix) > 0:\n            params[\"q\"] += \" \" + query_suffix\n        if isinstance(engines, list) and len(engines) > 0:\n            params[\"engines\"] = \",\".join(engines)\n        res = await self._asearx_api_query(params)\n        if len(res.answers) > 0:\n            toret = res.answers[0]\n        # only return the content of the results list\n        elif len(res.results) > 0:\n            toret = \"\\n\\n\".join([r.get(\"content\", \"\") for r in res.results[: self.k]])\n        else:\n            toret = \"No good search result found\"\n        return toret\n[docs]    def results(\n        self,\n        query: str,\n        num_results: int,\n        engines: Optional[List[str]] = None,\n        categories: Optional[List[str]] = None,\n        query_suffix: Optional[str] = \"\",\n        **kwargs: Any,\n    ) -> List[Dict]:\n        \"\"\"Run query through Searx API and returns the results with metadata.\n        Args:\n            query: The query to search for.\n            query_suffix: Extra suffix appended to the query.\n            num_results: Limit the number of results to return.\n            engines: List of engines to use for the query.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html"}
{"id": "b73d66fc7f66-9", "text": "engines: List of engines to use for the query.\n            categories: List of categories to use for the query.\n            **kwargs: extra parameters to pass to the searx API.\n        Returns:\n            Dict with the following keys:\n            {\n                snippet:  The description of the result.\n                title:  The title of the result.\n                link: The link to the result.\n                engines: The engines used for the result.\n                category: Searx category of the result.\n            }\n        \"\"\"\n        _params = {\n            \"q\": query,\n        }\n        params = {**self.params, **_params, **kwargs}\n        if self.query_suffix and len(self.query_suffix) > 0:\n            params[\"q\"] += \" \" + self.query_suffix\n        if isinstance(query_suffix, str) and len(query_suffix) > 0:\n            params[\"q\"] += \" \" + query_suffix\n        if isinstance(engines, list) and len(engines) > 0:\n            params[\"engines\"] = \",\".join(engines)\n        if isinstance(categories, list) and len(categories) > 0:\n            params[\"categories\"] = \",\".join(categories)\n        results = self._searx_api_query(params).results[:num_results]\n        if len(results) == 0:\n            return [{\"Result\": \"No good Search Result was found\"}]\n        return [\n            {\n                \"snippet\": result.get(\"content\", \"\"),\n                \"title\": result[\"title\"],\n                \"link\": result[\"url\"],\n                \"engines\": result[\"engines\"],\n                \"category\": result[\"category\"],\n            }\n            for result in results\n        ]\n[docs]    async def aresults(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html"}
{"id": "b73d66fc7f66-10", "text": "]\n[docs]    async def aresults(\n        self,\n        query: str,\n        num_results: int,\n        engines: Optional[List[str]] = None,\n        query_suffix: Optional[str] = \"\",\n        **kwargs: Any,\n    ) -> List[Dict]:\n        \"\"\"Asynchronously query with json results.\n        Uses aiohttp. See `results` for more info.\n        \"\"\"\n        _params = {\n            \"q\": query,\n        }\n        params = {**self.params, **_params, **kwargs}\n        if self.query_suffix and len(self.query_suffix) > 0:\n            params[\"q\"] += \" \" + self.query_suffix\n        if isinstance(query_suffix, str) and len(query_suffix) > 0:\n            params[\"q\"] += \" \" + query_suffix\n        if isinstance(engines, list) and len(engines) > 0:\n            params[\"engines\"] = \",\".join(engines)\n        results = (await self._asearx_api_query(params)).results[:num_results]\n        if len(results) == 0:\n            return [{\"Result\": \"No good Search Result was found\"}]\n        return [\n            {\n                \"snippet\": result.get(\"content\", \"\"),\n                \"title\": result[\"title\"],\n                \"link\": result[\"url\"],\n                \"engines\": result[\"engines\"],\n                \"category\": result[\"category\"],\n            }\n            for result in results\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html"}
{"id": "70cfe72b8029-0", "text": "Source code for langchain.utilities.dataforseo_api_search\nimport base64\nfrom typing import Dict, Optional\nfrom urllib.parse import quote\nimport aiohttp\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class DataForSeoAPIWrapper(BaseModel):\n    \"\"\"Wrapper around the DataForSeo API.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    default_params: dict = Field(\n        default={\n            \"location_name\": \"United States\",\n            \"language_code\": \"en\",\n            \"depth\": 10,\n            \"se_name\": \"google\",\n            \"se_type\": \"organic\",\n        }\n    )\n    \"\"\"Default parameters to use for the DataForSEO SERP API.\"\"\"\n    params: dict = Field(default={})\n    \"\"\"Additional parameters to pass to the DataForSEO SERP API.\"\"\"\n    api_login: Optional[str] = None\n    \"\"\"The API login to use for the DataForSEO SERP API.\"\"\"\n    api_password: Optional[str] = None\n    \"\"\"The API password to use for the DataForSEO SERP API.\"\"\"\n    json_result_types: Optional[list] = None\n    \"\"\"The JSON result types.\"\"\"\n    json_result_fields: Optional[list] = None\n    \"\"\"The JSON result fields.\"\"\"\n    top_count: Optional[int] = None\n    \"\"\"The number of top results to return.\"\"\"\n    aiosession: Optional[aiohttp.ClientSession] = None\n    \"\"\"The aiohttp session to use for the DataForSEO SERP API.\"\"\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html"}
{"id": "70cfe72b8029-1", "text": "@root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that login and password exists in environment.\"\"\"\n        login = get_from_dict_or_env(values, \"api_login\", \"DATAFORSEO_LOGIN\")\n        password = get_from_dict_or_env(values, \"api_password\", \"DATAFORSEO_PASSWORD\")\n        values[\"api_login\"] = login\n        values[\"api_password\"] = password\n        return values\n[docs]    async def arun(self, url: str) -> str:\n        \"\"\"Run request to DataForSEO SERP API and parse result async.\"\"\"\n        return self._process_response(await self._aresponse_json(url))\n[docs]    def run(self, url: str) -> str:\n        \"\"\"Run request to DataForSEO SERP API and parse result async.\"\"\"\n        return self._process_response(self._response_json(url))\n[docs]    def results(self, url: str) -> list:\n        res = self._response_json(url)\n        return self._filter_results(res)\n[docs]    async def aresults(self, url: str) -> list:\n        res = await self._aresponse_json(url)\n        return self._filter_results(res)\n    def _prepare_request(self, keyword: str) -> dict:\n        \"\"\"Prepare the request details for the DataForSEO SERP API.\"\"\"\n        if self.api_login is None or self.api_password is None:\n            raise ValueError(\"api_login or api_password is not provided\")\n        cred = base64.b64encode(\n            f\"{self.api_login}:{self.api_password}\".encode(\"utf-8\")\n        ).decode(\"utf-8\")\n        headers = {\"Authorization\": f\"Basic {cred}\", \"Content-Type\": \"application/json\"}\n        obj = {\"keyword\": quote(keyword)}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html"}
{"id": "70cfe72b8029-2", "text": "obj = {\"keyword\": quote(keyword)}\n        obj = {**obj, **self.default_params, **self.params}\n        data = [obj]\n        _url = (\n            f\"https://api.dataforseo.com/v3/serp/{obj['se_name']}\"\n            f\"/{obj['se_type']}/live/advanced\"\n        )\n        return {\n            \"url\": _url,\n            \"headers\": headers,\n            \"data\": data,\n        }\n    def _check_response(self, response: dict) -> dict:\n        \"\"\"Check the response from the DataForSEO SERP API for errors.\"\"\"\n        if response.get(\"status_code\") != 20000:\n            raise ValueError(\n                f\"Got error from DataForSEO SERP API: {response.get('status_message')}\"\n            )\n        return response\n    def _response_json(self, url: str) -> dict:\n        \"\"\"Use requests to run request to DataForSEO SERP API and return results.\"\"\"\n        request_details = self._prepare_request(url)\n        response = requests.post(\n            request_details[\"url\"],\n            headers=request_details[\"headers\"],\n            json=request_details[\"data\"],\n        )\n        response.raise_for_status()\n        return self._check_response(response.json())\n    async def _aresponse_json(self, url: str) -> dict:\n        \"\"\"Use aiohttp to request DataForSEO SERP API and return results async.\"\"\"\n        request_details = self._prepare_request(url)\n        if not self.aiosession:\n            async with aiohttp.ClientSession() as session:\n                async with session.post(\n                    request_details[\"url\"],\n                    headers=request_details[\"headers\"],\n                    json=request_details[\"data\"],\n                ) as response:\n                    res = await response.json()\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html"}
{"id": "70cfe72b8029-3", "text": ") as response:\n                    res = await response.json()\n        else:\n            async with self.aiosession.post(\n                request_details[\"url\"],\n                headers=request_details[\"headers\"],\n                json=request_details[\"data\"],\n            ) as response:\n                res = await response.json()\n        return self._check_response(res)\n    def _filter_results(self, res: dict) -> list:\n        output = []\n        types = self.json_result_types if self.json_result_types is not None else []\n        for task in res.get(\"tasks\", []):\n            for result in task.get(\"result\", []):\n                for item in result.get(\"items\", []):\n                    if len(types) == 0 or item.get(\"type\", \"\") in types:\n                        self._cleanup_unnecessary_items(item)\n                        if len(item) != 0:\n                            output.append(item)\n                    if self.top_count is not None and len(output) >= self.top_count:\n                        break\n        return output\n    def _cleanup_unnecessary_items(self, d: dict) -> dict:\n        fields = self.json_result_fields if self.json_result_fields is not None else []\n        if len(fields) > 0:\n            for k, v in list(d.items()):\n                if isinstance(v, dict):\n                    self._cleanup_unnecessary_items(v)\n                    if len(v) == 0:\n                        del d[k]\n                elif k not in fields:\n                    del d[k]\n        if \"xpath\" in d:\n            del d[\"xpath\"]\n        if \"position\" in d:\n            del d[\"position\"]\n        if \"rectangle\" in d:\n            del d[\"rectangle\"]\n        for k, v in list(d.items()):\n            if isinstance(v, dict):\n                self._cleanup_unnecessary_items(v)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html"}
{"id": "70cfe72b8029-4", "text": "if isinstance(v, dict):\n                self._cleanup_unnecessary_items(v)\n        return d\n    def _process_response(self, res: dict) -> str:\n        \"\"\"Process response from DataForSEO SERP API.\"\"\"\n        toret = \"No good search result found\"\n        for task in res.get(\"tasks\", []):\n            for result in task.get(\"result\", []):\n                item_types = result.get(\"item_types\")\n                items = result.get(\"items\", [])\n                if \"answer_box\" in item_types:\n                    toret = next(\n                        item for item in items if item.get(\"type\") == \"answer_box\"\n                    ).get(\"text\")\n                elif \"knowledge_graph\" in item_types:\n                    toret = next(\n                        item for item in items if item.get(\"type\") == \"knowledge_graph\"\n                    ).get(\"description\")\n                elif \"featured_snippet\" in item_types:\n                    toret = next(\n                        item for item in items if item.get(\"type\") == \"featured_snippet\"\n                    ).get(\"description\")\n                elif \"shopping\" in item_types:\n                    toret = next(\n                        item for item in items if item.get(\"type\") == \"shopping\"\n                    ).get(\"price\")\n                elif \"organic\" in item_types:\n                    toret = next(\n                        item for item in items if item.get(\"type\") == \"organic\"\n                    ).get(\"description\")\n                if toret:\n                    break\n        return toret", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html"}
{"id": "4f8c7646bf42-0", "text": "Source code for langchain.utilities.pubmed\nimport json\nimport logging\nimport time\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nfrom typing import Any, Dict, Iterator, List\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema import Document\nlogger = logging.getLogger(__name__)\n[docs]class PubMedAPIWrapper(BaseModel):\n    \"\"\"\n    Wrapper around PubMed API.\n    This wrapper will use the PubMed API to conduct searches and fetch\n    document summaries. By default, it will return the document summaries\n    of the top-k results of an input search.\n    Parameters:\n        top_k_results: number of the top-scored document used for the PubMed tool\n        MAX_QUERY_LENGTH: maximum length of the query.\n          Default is 300 characters.\n        doc_content_chars_max: maximum length of the document content.\n          Content will be truncated if it exceeds this length.\n          Default is 2000 characters.\n        max_retry: maximum number of retries for a request. Default is 5.\n        sleep_time: time to wait between retries.\n          Default is 0.2 seconds.\n        email: email address to be used for the PubMed API.\n    \"\"\"\n    parse: Any  #: :meta private:\n    base_url_esearch: str = (\n        \"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?\"\n    )\n    base_url_efetch: str = \"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?\"\n    max_retry: int = 5\n    sleep_time: float = 0.2\n    # Default values for the parameters\n    top_k_results: int = 3\n    MAX_QUERY_LENGTH: int = 300\n    doc_content_chars_max: int = 2000", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html"}
{"id": "4f8c7646bf42-1", "text": "doc_content_chars_max: int = 2000\n    email: str = \"your_email@example.com\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the python package exists in environment.\"\"\"\n        try:\n            import xmltodict\n            values[\"parse\"] = xmltodict.parse\n        except ImportError:\n            raise ImportError(\n                \"Could not import xmltodict python package. \"\n                \"Please install it with `pip install xmltodict`.\"\n            )\n        return values\n[docs]    def run(self, query: str) -> str:\n        \"\"\"\n        Run PubMed search and get the article meta information.\n        See https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch\n        It uses only the most informative fields of article meta information.\n        \"\"\"\n        try:\n            # Retrieve the top-k results for the query\n            docs = [\n                f\"Published: {result['Published']}\\n\"\n                f\"Title: {result['Title']}\\n\"\n                f\"Copyright Information: {result['Copyright Information']}\\n\"\n                f\"Summary::\\n{result['Summary']}\"\n                for result in self.load(query[: self.MAX_QUERY_LENGTH])\n            ]\n            # Join the results and limit the character count\n            return (\n                \"\\n\\n\".join(docs)[: self.doc_content_chars_max]\n                if docs\n                else \"No good PubMed Result was found\"\n            )\n        except Exception as ex:\n            return f\"PubMed exception: {ex}\"\n[docs]    def lazy_load(self, query: str) -> Iterator[dict]:\n        \"\"\"\n        Search PubMed for documents matching the query.\n        Return an iterator of dictionaries containing the document metadata.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html"}
{"id": "4f8c7646bf42-2", "text": "Return an iterator of dictionaries containing the document metadata.\n        \"\"\"\n        url = (\n            self.base_url_esearch\n            + \"db=pubmed&term=\"\n            + str({urllib.parse.quote(query)})\n            + f\"&retmode=json&retmax={self.top_k_results}&usehistory=y\"\n        )\n        result = urllib.request.urlopen(url)\n        text = result.read().decode(\"utf-8\")\n        json_text = json.loads(text)\n        webenv = json_text[\"esearchresult\"][\"webenv\"]\n        for uid in json_text[\"esearchresult\"][\"idlist\"]:\n            yield self.retrieve_article(uid, webenv)\n[docs]    def load(self, query: str) -> List[dict]:\n        \"\"\"\n        Search PubMed for documents matching the query.\n        Return a list of dictionaries containing the document metadata.\n        \"\"\"\n        return list(self.lazy_load(query))\n    def _dict2document(self, doc: dict) -> Document:\n        summary = doc.pop(\"Summary\")\n        return Document(page_content=summary, metadata=doc)\n[docs]    def lazy_load_docs(self, query: str) -> Iterator[Document]:\n        for d in self.lazy_load(query=query):\n            yield self._dict2document(d)\n[docs]    def load_docs(self, query: str) -> List[Document]:\n        return list(self.lazy_load_docs(query=query))\n[docs]    def retrieve_article(self, uid: str, webenv: str) -> dict:\n        url = (\n            self.base_url_efetch\n            + \"db=pubmed&retmode=xml&id=\"\n            + uid\n            + \"&webenv=\"\n            + webenv\n        )\n        retry = 0\n        while True:\n            try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html"}
{"id": "4f8c7646bf42-3", "text": ")\n        retry = 0\n        while True:\n            try:\n                result = urllib.request.urlopen(url)\n                break\n            except urllib.error.HTTPError as e:\n                if e.code == 429 and retry < self.max_retry:\n                    # Too Many Requests errors\n                    # wait for an exponentially increasing amount of time\n                    print(\n                        f\"Too Many Requests, \"\n                        f\"waiting for {self.sleep_time:.2f} seconds...\"\n                    )\n                    time.sleep(self.sleep_time)\n                    self.sleep_time *= 2\n                    retry += 1\n                else:\n                    raise e\n        xml_text = result.read().decode(\"utf-8\")\n        text_dict = self.parse(xml_text)\n        return self._parse_article(uid, text_dict)\n    def _parse_article(self, uid: str, text_dict: dict) -> dict:\n        try:\n            ar = text_dict[\"PubmedArticleSet\"][\"PubmedArticle\"][\"MedlineCitation\"][\n                \"Article\"\n            ]\n        except KeyError:\n            ar = text_dict[\"PubmedArticleSet\"][\"PubmedBookArticle\"][\"BookDocument\"]\n        abstract_text = ar.get(\"Abstract\", {}).get(\"AbstractText\", [])\n        summaries = [\n            f\"{txt['@Label']}: {txt['#text']}\"\n            for txt in abstract_text\n            if \"#text\" in txt and \"@Label\" in txt\n        ]\n        summary = (\n            \"\\n\".join(summaries)\n            if summaries\n            else (\n                abstract_text\n                if isinstance(abstract_text, str)\n                else (\n                    \"\\n\".join(str(value) for value in abstract_text.values())\n                    if isinstance(abstract_text, dict)\n                    else \"No abstract available\"\n                )\n            )\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html"}
{"id": "4f8c7646bf42-4", "text": "else \"No abstract available\"\n                )\n            )\n        )\n        a_d = ar.get(\"ArticleDate\", {})\n        pub_date = \"-\".join(\n            [a_d.get(\"Year\", \"\"), a_d.get(\"Month\", \"\"), a_d.get(\"Day\", \"\")]\n        )\n        return {\n            \"uid\": uid,\n            \"Title\": ar.get(\"ArticleTitle\", \"\"),\n            \"Published\": pub_date,\n            \"Copyright Information\": ar.get(\"Abstract\", {}).get(\n                \"CopyrightInformation\", \"\"\n            ),\n            \"Summary\": summary,\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html"}
{"id": "533035748d32-0", "text": "Source code for langchain.utilities.powerbi\n\"\"\"Wrapper around a Power BI endpoint.\"\"\"\nfrom __future__ import annotations\nimport asyncio\nimport logging\nimport os\nfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union\nimport aiohttp\nimport requests\nfrom aiohttp import ServerTimeoutError\nfrom requests.exceptions import Timeout\nfrom langchain.pydantic_v1 import BaseModel, Field, root_validator, validator\nlogger = logging.getLogger(__name__)\nBASE_URL = os.getenv(\"POWERBI_BASE_URL\", \"https://api.powerbi.com/v1.0/myorg\")\nif TYPE_CHECKING:\n    from azure.core.credentials import TokenCredential\n[docs]class PowerBIDataset(BaseModel):\n    \"\"\"Create PowerBI engine from dataset ID and credential or token.\n    Use either the credential or a supplied token to authenticate.\n    If both are supplied the credential is used to generate a token.\n    The impersonated_user_name is the UPN of a user to be impersonated.\n    If the model is not RLS enabled, this will be ignored.\n    \"\"\"\n    dataset_id: str\n    table_names: List[str]\n    group_id: Optional[str] = None\n    credential: Optional[TokenCredential] = None\n    token: Optional[str] = None\n    impersonated_user_name: Optional[str] = None\n    sample_rows_in_table_info: int = Field(default=1, gt=0, le=10)\n    schemas: Dict[str, str] = Field(default_factory=dict)\n    aiosession: Optional[aiohttp.ClientSession] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @validator(\"table_names\", allow_reuse=True)\n    def fix_table_names(cls, table_names: List[str]) -> List[str]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html"}
{"id": "533035748d32-1", "text": "def fix_table_names(cls, table_names: List[str]) -> List[str]:\n        \"\"\"Fix the table names.\"\"\"\n        return [fix_table_name(table) for table in table_names]\n    @root_validator(pre=True, allow_reuse=True)\n    def token_or_credential_present(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Validate that at least one of token and credentials is present.\"\"\"\n        if \"token\" in values or \"credential\" in values:\n            return values\n        raise ValueError(\"Please provide either a credential or a token.\")\n    @property\n    def request_url(self) -> str:\n        \"\"\"Get the request url.\"\"\"\n        if self.group_id:\n            return f\"{BASE_URL}/groups/{self.group_id}/datasets/{self.dataset_id}/executeQueries\"  # noqa: E501 # pylint: disable=C0301\n        return f\"{BASE_URL}/datasets/{self.dataset_id}/executeQueries\"  # noqa: E501 # pylint: disable=C0301\n    @property\n    def headers(self) -> Dict[str, str]:\n        \"\"\"Get the token.\"\"\"\n        if self.token:\n            return {\n                \"Content-Type\": \"application/json\",\n                \"Authorization\": \"Bearer \" + self.token,\n            }\n        from azure.core.exceptions import (\n            ClientAuthenticationError,  # pylint: disable=import-outside-toplevel\n        )\n        if self.credential:\n            try:\n                token = self.credential.get_token(\n                    \"https://analysis.windows.net/powerbi/api/.default\"\n                ).token\n                return {\n                    \"Content-Type\": \"application/json\",\n                    \"Authorization\": \"Bearer \" + token,\n                }\n            except Exception as exc:  # pylint: disable=broad-exception-caught\n                raise ClientAuthenticationError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html"}
{"id": "533035748d32-2", "text": "raise ClientAuthenticationError(\n                    \"Could not get a token from the supplied credentials.\"\n                ) from exc\n        raise ClientAuthenticationError(\"No credential or token supplied.\")\n[docs]    def get_table_names(self) -> Iterable[str]:\n        \"\"\"Get names of tables available.\"\"\"\n        return self.table_names\n[docs]    def get_schemas(self) -> str:\n        \"\"\"Get the available schema's.\"\"\"\n        if self.schemas:\n            return \", \".join([f\"{key}: {value}\" for key, value in self.schemas.items()])\n        return \"No known schema's yet. Use the schema_powerbi tool first.\"\n    @property\n    def table_info(self) -> str:\n        \"\"\"Information about all tables in the database.\"\"\"\n        return self.get_table_info()\n    def _get_tables_to_query(\n        self, table_names: Optional[Union[List[str], str]] = None\n    ) -> Optional[List[str]]:\n        \"\"\"Get the tables names that need to be queried, after checking they exist.\"\"\"\n        if table_names is not None:\n            if (\n                isinstance(table_names, list)\n                and len(table_names) > 0\n                and table_names[0] != \"\"\n            ):\n                fixed_tables = [fix_table_name(table) for table in table_names]\n                non_existing_tables = [\n                    table for table in fixed_tables if table not in self.table_names\n                ]\n                if non_existing_tables:\n                    logger.warning(\n                        \"Table(s) %s not found in dataset.\",\n                        \", \".join(non_existing_tables),\n                    )\n                tables = [\n                    table for table in fixed_tables if table not in non_existing_tables\n                ]\n                return tables if tables else None\n            if isinstance(table_names, str) and table_names != \"\":", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html"}
{"id": "533035748d32-3", "text": "if isinstance(table_names, str) and table_names != \"\":\n                if table_names not in self.table_names:\n                    logger.warning(\"Table %s not found in dataset.\", table_names)\n                    return None\n                return [fix_table_name(table_names)]\n        return self.table_names\n    def _get_tables_todo(self, tables_todo: List[str]) -> List[str]:\n        \"\"\"Get the tables that still need to be queried.\"\"\"\n        return [table for table in tables_todo if table not in self.schemas]\n    def _get_schema_for_tables(self, table_names: List[str]) -> str:\n        \"\"\"Create a string of the table schemas for the supplied tables.\"\"\"\n        schemas = [\n            schema for table, schema in self.schemas.items() if table in table_names\n        ]\n        return \", \".join(schemas)\n[docs]    def get_table_info(\n        self, table_names: Optional[Union[List[str], str]] = None\n    ) -> str:\n        \"\"\"Get information about specified tables.\"\"\"\n        tables_requested = self._get_tables_to_query(table_names)\n        if tables_requested is None:\n            return \"No (valid) tables requested.\"\n        tables_todo = self._get_tables_todo(tables_requested)\n        for table in tables_todo:\n            self._get_schema(table)\n        return self._get_schema_for_tables(tables_requested)\n[docs]    async def aget_table_info(\n        self, table_names: Optional[Union[List[str], str]] = None\n    ) -> str:\n        \"\"\"Get information about specified tables.\"\"\"\n        tables_requested = self._get_tables_to_query(table_names)\n        if tables_requested is None:\n            return \"No (valid) tables requested.\"\n        tables_todo = self._get_tables_todo(tables_requested)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html"}
{"id": "533035748d32-4", "text": "tables_todo = self._get_tables_todo(tables_requested)\n        await asyncio.gather(*[self._aget_schema(table) for table in tables_todo])\n        return self._get_schema_for_tables(tables_requested)\n    def _get_schema(self, table: str) -> None:\n        \"\"\"Get the schema for a table.\"\"\"\n        try:\n            result = self.run(\n                f\"EVALUATE TOPN({self.sample_rows_in_table_info}, {table})\"\n            )\n            self.schemas[table] = json_to_md(result[\"results\"][0][\"tables\"][0][\"rows\"])\n        except Timeout:\n            logger.warning(\"Timeout while getting table info for %s\", table)\n            self.schemas[table] = \"unknown\"\n        except Exception as exc:  # pylint: disable=broad-exception-caught\n            logger.warning(\"Error while getting table info for %s: %s\", table, exc)\n            self.schemas[table] = \"unknown\"\n    async def _aget_schema(self, table: str) -> None:\n        \"\"\"Get the schema for a table.\"\"\"\n        try:\n            result = await self.arun(\n                f\"EVALUATE TOPN({self.sample_rows_in_table_info}, {table})\"\n            )\n            self.schemas[table] = json_to_md(result[\"results\"][0][\"tables\"][0][\"rows\"])\n        except ServerTimeoutError:\n            logger.warning(\"Timeout while getting table info for %s\", table)\n            self.schemas[table] = \"unknown\"\n        except Exception as exc:  # pylint: disable=broad-exception-caught\n            logger.warning(\"Error while getting table info for %s: %s\", table, exc)\n            self.schemas[table] = \"unknown\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html"}
{"id": "533035748d32-5", "text": "self.schemas[table] = \"unknown\"\n    def _create_json_content(self, command: str) -> dict[str, Any]:\n        \"\"\"Create the json content for the request.\"\"\"\n        return {\n            \"queries\": [{\"query\": rf\"{command}\"}],\n            \"impersonatedUserName\": self.impersonated_user_name,\n            \"serializerSettings\": {\"includeNulls\": True},\n        }\n[docs]    def run(self, command: str) -> Any:\n        \"\"\"Execute a DAX command and return a json representing the results.\"\"\"\n        logger.debug(\"Running command: %s\", command)\n        response = requests.post(\n            self.request_url,\n            json=self._create_json_content(command),\n            headers=self.headers,\n            timeout=10,\n        )\n        if response.status_code == 403:\n            return (\n                \"TokenError: Could not login to PowerBI, please check your credentials.\"\n            )\n        return response.json()\n[docs]    async def arun(self, command: str) -> Any:\n        \"\"\"Execute a DAX command and return the result asynchronously.\"\"\"\n        logger.debug(\"Running command: %s\", command)\n        if self.aiosession:\n            async with self.aiosession.post(\n                self.request_url,\n                headers=self.headers,\n                json=self._create_json_content(command),\n                timeout=10,\n            ) as response:\n                if response.status == 403:\n                    return \"TokenError: Could not login to PowerBI, please check your credentials.\"  # noqa: E501\n                response_json = await response.json(content_type=response.content_type)\n                return response_json\n        async with aiohttp.ClientSession() as session:\n            async with session.post(\n                self.request_url,\n                headers=self.headers,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html"}
{"id": "533035748d32-6", "text": "async with session.post(\n                self.request_url,\n                headers=self.headers,\n                json=self._create_json_content(command),\n                timeout=10,\n            ) as response:\n                if response.status == 403:\n                    return \"TokenError: Could not login to PowerBI, please check your credentials.\"  # noqa: E501\n                response_json = await response.json(content_type=response.content_type)\n                return response_json\n[docs]def json_to_md(\n    json_contents: List[Dict[str, Union[str, int, float]]],\n    table_name: Optional[str] = None,\n) -> str:\n    \"\"\"Converts a JSON object to a markdown table.\"\"\"\n    if len(json_contents) == 0:\n        return \"\"\n    output_md = \"\"\n    headers = json_contents[0].keys()\n    for header in headers:\n        header.replace(\"[\", \".\").replace(\"]\", \"\")\n        if table_name:\n            header.replace(f\"{table_name}.\", \"\")\n        output_md += f\"| {header} \"\n    output_md += \"|\\n\"\n    for row in json_contents:\n        for value in row.values():\n            output_md += f\"| {value} \"\n        output_md += \"|\\n\"\n    return output_md\n[docs]def fix_table_name(table: str) -> str:\n    \"\"\"Add single quotes around table names that contain spaces.\"\"\"\n    if \" \" in table and not table.startswith(\"'\") and not table.endswith(\"'\"):\n        return f\"'{table}'\"\n    return table", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html"}
{"id": "056f559c9987-0", "text": "Source code for langchain.utilities.google_places_api\n\"\"\"Chain that calls Google Places API.\n\"\"\"\nimport logging\nfrom typing import Any, Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class GooglePlacesAPIWrapper(BaseModel):\n    \"\"\"Wrapper around Google Places API.\n    To use, you should have the ``googlemaps`` python package installed,\n     **an API key for the google maps platform**,\n     and the environment variable ''GPLACES_API_KEY''\n     set with your API key , or pass 'gplaces_api_key'\n     as a named parameter to the constructor.\n    By default, this will return the all the results on the input query.\n     You can use the top_k_results argument to limit the number of results.\n    Example:\n        .. code-block:: python\n            from langchain.utilities import GooglePlacesAPIWrapper\n            gplaceapi = GooglePlacesAPIWrapper()\n    \"\"\"\n    gplaces_api_key: Optional[str] = None\n    google_map_client: Any  #: :meta private:\n    top_k_results: Optional[int] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key is in your environment variable.\"\"\"\n        gplaces_api_key = get_from_dict_or_env(\n            values, \"gplaces_api_key\", \"GPLACES_API_KEY\"\n        )\n        values[\"gplaces_api_key\"] = gplaces_api_key\n        try:\n            import googlemaps\n            values[\"google_map_client\"] = googlemaps.Client(gplaces_api_key)\n        except ImportError:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html"}
{"id": "056f559c9987-1", "text": "except ImportError:\n            raise ImportError(\n                \"Could not import googlemaps python package. \"\n                \"Please install it with `pip install googlemaps`.\"\n            )\n        return values\n[docs]    def run(self, query: str) -> str:\n        \"\"\"Run Places search and get k number of places that exists that match.\"\"\"\n        search_results = self.google_map_client.places(query)[\"results\"]\n        num_to_return = len(search_results)\n        places = []\n        if num_to_return == 0:\n            return \"Google Places did not find any places that match the description\"\n        num_to_return = (\n            num_to_return\n            if self.top_k_results is None\n            else min(num_to_return, self.top_k_results)\n        )\n        for i in range(num_to_return):\n            result = search_results[i]\n            details = self.fetch_place_details(result[\"place_id\"])\n            if details is not None:\n                places.append(details)\n        return \"\\n\".join([f\"{i+1}. {item}\" for i, item in enumerate(places)])\n[docs]    def fetch_place_details(self, place_id: str) -> Optional[str]:\n        try:\n            place_details = self.google_map_client.place(place_id)\n            place_details[\"place_id\"] = place_id\n            formatted_details = self.format_place_details(place_details)\n            return formatted_details\n        except Exception as e:\n            logging.error(f\"An Error occurred while fetching place details: {e}\")\n            return None\n[docs]    def format_place_details(self, place_details: Dict[str, Any]) -> Optional[str]:\n        try:\n            name = place_details.get(\"result\", {}).get(\"name\", \"Unknown\")\n            address = place_details.get(\"result\", {}).get(\n                \"formatted_address\", \"Unknown\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html"}
{"id": "056f559c9987-2", "text": "\"formatted_address\", \"Unknown\"\n            )\n            phone_number = place_details.get(\"result\", {}).get(\n                \"formatted_phone_number\", \"Unknown\"\n            )\n            website = place_details.get(\"result\", {}).get(\"website\", \"Unknown\")\n            place_id = place_details.get(\"result\", {}).get(\"place_id\", \"Unknown\")\n            formatted_details = (\n                f\"{name}\\nAddress: {address}\\n\"\n                f\"Google place ID: {place_id}\\n\"\n                f\"Phone: {phone_number}\\nWebsite: {website}\\n\\n\"\n            )\n            return formatted_details\n        except Exception as e:\n            logging.error(f\"An error occurred while formatting place details: {e}\")\n            return None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html"}
{"id": "8aa1440ed5a1-0", "text": "Source code for langchain.utilities.golden_query\n\"\"\"Util that calls Golden.\"\"\"\nimport json\nfrom typing import Dict, Optional\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\nGOLDEN_BASE_URL = \"https://golden.com\"\nGOLDEN_TIMEOUT = 5000\n[docs]class GoldenQueryAPIWrapper(BaseModel):\n    \"\"\"Wrapper for Golden.\n    Docs for using:\n    1. Go to https://golden.com and sign up for an account\n    2. Get your API Key from https://golden.com/settings/api\n    3. Save your API Key into GOLDEN_API_KEY env variable\n    \"\"\"\n    golden_api_key: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        golden_api_key = get_from_dict_or_env(\n            values, \"golden_api_key\", \"GOLDEN_API_KEY\"\n        )\n        values[\"golden_api_key\"] = golden_api_key\n        return values\n[docs]    def run(self, query: str) -> str:\n        \"\"\"Run query through Golden Query API and return the JSON raw result.\"\"\"\n        headers = {\"apikey\": self.golden_api_key or \"\"}\n        response = requests.post(\n            f\"{GOLDEN_BASE_URL}/api/v2/public/queries/\",\n            json={\"prompt\": query},\n            headers=headers,\n            timeout=GOLDEN_TIMEOUT,\n        )\n        if response.status_code != 201:\n            return response.text\n        content = json.loads(response.content)\n        query_id = content[\"id\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/golden_query.html"}
{"id": "8aa1440ed5a1-1", "text": "content = json.loads(response.content)\n        query_id = content[\"id\"]\n        response = requests.get(\n            (\n                f\"{GOLDEN_BASE_URL}/api/v2/public/queries/{query_id}/results/\"\n                \"?pageSize=10\"\n            ),\n            headers=headers,\n            timeout=GOLDEN_TIMEOUT,\n        )\n        return response.text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/golden_query.html"}
{"id": "66de919a3475-0", "text": "Source code for langchain.utilities.metaphor_search\n\"\"\"Util that calls Metaphor Search API.\nIn order to set this up, follow instructions at:\n\"\"\"\nimport json\nfrom typing import Dict, List, Optional\nimport aiohttp\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\nMETAPHOR_API_URL = \"https://api.metaphor.systems\"\n[docs]class MetaphorSearchAPIWrapper(BaseModel):\n    \"\"\"Wrapper for Metaphor Search API.\"\"\"\n    metaphor_api_key: str\n    k: int = 10\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    def _metaphor_search_results(\n        self,\n        query: str,\n        num_results: int,\n        include_domains: Optional[List[str]] = None,\n        exclude_domains: Optional[List[str]] = None,\n        start_crawl_date: Optional[str] = None,\n        end_crawl_date: Optional[str] = None,\n        start_published_date: Optional[str] = None,\n        end_published_date: Optional[str] = None,\n        use_autoprompt: Optional[bool] = None,\n    ) -> List[dict]:\n        headers = {\"X-Api-Key\": self.metaphor_api_key}\n        params = {\n            \"numResults\": num_results,\n            \"query\": query,\n            \"includeDomains\": include_domains,\n            \"excludeDomains\": exclude_domains,\n            \"startCrawlDate\": start_crawl_date,\n            \"endCrawlDate\": end_crawl_date,\n            \"startPublishedDate\": start_published_date,\n            \"endPublishedDate\": end_published_date,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html"}
{"id": "66de919a3475-1", "text": "\"endPublishedDate\": end_published_date,\n            \"useAutoprompt\": use_autoprompt,\n        }\n        response = requests.post(\n            # type: ignore\n            f\"{METAPHOR_API_URL}/search\",\n            headers=headers,\n            json=params,\n        )\n        response.raise_for_status()\n        search_results = response.json()\n        return search_results[\"results\"]\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and endpoint exists in environment.\"\"\"\n        metaphor_api_key = get_from_dict_or_env(\n            values, \"metaphor_api_key\", \"METAPHOR_API_KEY\"\n        )\n        values[\"metaphor_api_key\"] = metaphor_api_key\n        return values\n[docs]    def results(\n        self,\n        query: str,\n        num_results: int,\n        include_domains: Optional[List[str]] = None,\n        exclude_domains: Optional[List[str]] = None,\n        start_crawl_date: Optional[str] = None,\n        end_crawl_date: Optional[str] = None,\n        start_published_date: Optional[str] = None,\n        end_published_date: Optional[str] = None,\n        use_autoprompt: Optional[bool] = None,\n    ) -> List[Dict]:\n        \"\"\"Run query through Metaphor Search and return metadata.\n        Args:\n            query: The query to search for.\n            num_results: The number of results to return.\n            include_domains: A list of domains to include in the search. Only one of include_domains and exclude_domains should be defined.\n            exclude_domains: A list of domains to exclude from the search. Only one of include_domains and exclude_domains should be defined.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html"}
{"id": "66de919a3475-2", "text": "start_crawl_date: If specified, only pages we crawled after start_crawl_date will be returned.\n            end_crawl_date: If specified, only pages we crawled before end_crawl_date will be returned.\n            start_published_date: If specified, only pages published after start_published_date will be returned.\n            end_published_date: If specified, only pages published before end_published_date will be returned.\n            use_autoprompt: If true, we turn your query into a more Metaphor-friendly query. Adds latency.\n        Returns:\n            A list of dictionaries with the following keys:\n                title - The title of the page\n                url - The url\n                author - Author of the content, if applicable. Otherwise, None.\n                published_date - Estimated date published\n                    in YYYY-MM-DD format. Otherwise, None.\n        \"\"\"  # noqa: E501\n        raw_search_results = self._metaphor_search_results(\n            query,\n            num_results=num_results,\n            include_domains=include_domains,\n            exclude_domains=exclude_domains,\n            start_crawl_date=start_crawl_date,\n            end_crawl_date=end_crawl_date,\n            start_published_date=start_published_date,\n            end_published_date=end_published_date,\n            use_autoprompt=use_autoprompt,\n        )\n        return self._clean_results(raw_search_results)\n[docs]    async def results_async(\n        self,\n        query: str,\n        num_results: int,\n        include_domains: Optional[List[str]] = None,\n        exclude_domains: Optional[List[str]] = None,\n        start_crawl_date: Optional[str] = None,\n        end_crawl_date: Optional[str] = None,\n        start_published_date: Optional[str] = None,\n        end_published_date: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html"}
{"id": "66de919a3475-3", "text": "end_published_date: Optional[str] = None,\n        use_autoprompt: Optional[bool] = None,\n    ) -> List[Dict]:\n        \"\"\"Get results from the Metaphor Search API asynchronously.\"\"\"\n        # Function to perform the API call\n        async def fetch() -> str:\n            headers = {\"X-Api-Key\": self.metaphor_api_key}\n            params = {\n                \"numResults\": num_results,\n                \"query\": query,\n                \"includeDomains\": include_domains,\n                \"excludeDomains\": exclude_domains,\n                \"startCrawlDate\": start_crawl_date,\n                \"endCrawlDate\": end_crawl_date,\n                \"startPublishedDate\": start_published_date,\n                \"endPublishedDate\": end_published_date,\n                \"useAutoprompt\": use_autoprompt,\n            }\n            async with aiohttp.ClientSession() as session:\n                async with session.post(\n                    f\"{METAPHOR_API_URL}/search\", json=params, headers=headers\n                ) as res:\n                    if res.status == 200:\n                        data = await res.text()\n                        return data\n                    else:\n                        raise Exception(f\"Error {res.status}: {res.reason}\")\n        results_json_str = await fetch()\n        results_json = json.loads(results_json_str)\n        return self._clean_results(results_json[\"results\"])\n    def _clean_results(self, raw_search_results: List[Dict]) -> List[Dict]:\n        cleaned_results = []\n        for result in raw_search_results:\n            cleaned_results.append(\n                {\n                    \"title\": result.get(\"title\", \"Unknown Title\"),\n                    \"url\": result.get(\"url\", \"Unknown URL\"),\n                    \"author\": result.get(\"author\", \"Unknown Author\"),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html"}
{"id": "66de919a3475-4", "text": "\"author\": result.get(\"author\", \"Unknown Author\"),\n                    \"published_date\": result.get(\"publishedDate\", \"Unknown Date\"),\n                }\n            )\n        return cleaned_results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html"}
{"id": "7b9bc0a5a7aa-0", "text": "Source code for langchain.utilities.sql_database\n\"\"\"SQLAlchemy wrapper around a database.\"\"\"\nfrom __future__ import annotations\nimport warnings\nfrom typing import Any, Dict, Iterable, List, Literal, Optional, Sequence, Union\nimport sqlalchemy\nfrom sqlalchemy import MetaData, Table, create_engine, inspect, select, text\nfrom sqlalchemy.engine import Engine\nfrom sqlalchemy.exc import ProgrammingError, SQLAlchemyError\nfrom sqlalchemy.schema import CreateTable\nfrom sqlalchemy.types import NullType\nfrom langchain.utils import get_from_env\ndef _format_index(index: sqlalchemy.engine.interfaces.ReflectedIndex) -> str:\n    return (\n        f'Name: {index[\"name\"]}, Unique: {index[\"unique\"]},'\n        f' Columns: {str(index[\"column_names\"])}'\n    )\n[docs]def truncate_word(content: Any, *, length: int, suffix: str = \"...\") -> str:\n    \"\"\"\n    Truncate a string to a certain number of words, based on the max string\n    length.\n    \"\"\"\n    if not isinstance(content, str) or length <= 0:\n        return content\n    if len(content) <= length:\n        return content\n    return content[: length - len(suffix)].rsplit(\" \", 1)[0] + suffix\n[docs]class SQLDatabase:\n    \"\"\"SQLAlchemy wrapper around a database.\"\"\"\n[docs]    def __init__(\n        self,\n        engine: Engine,\n        schema: Optional[str] = None,\n        metadata: Optional[MetaData] = None,\n        ignore_tables: Optional[List[str]] = None,\n        include_tables: Optional[List[str]] = None,\n        sample_rows_in_table_info: int = 3,\n        indexes_in_table_info: bool = False,\n        custom_table_info: Optional[dict] = None,\n        view_support: bool = False,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html"}
{"id": "7b9bc0a5a7aa-1", "text": "view_support: bool = False,\n        max_string_length: int = 300,\n    ):\n        \"\"\"Create engine from database URI.\"\"\"\n        self._engine = engine\n        self._schema = schema\n        if include_tables and ignore_tables:\n            raise ValueError(\"Cannot specify both include_tables and ignore_tables\")\n        self._inspector = inspect(self._engine)\n        # including view support by adding the views as well as tables to the all\n        # tables list if view_support is True\n        self._all_tables = set(\n            self._inspector.get_table_names(schema=schema)\n            + (self._inspector.get_view_names(schema=schema) if view_support else [])\n        )\n        self._include_tables = set(include_tables) if include_tables else set()\n        if self._include_tables:\n            missing_tables = self._include_tables - self._all_tables\n            if missing_tables:\n                raise ValueError(\n                    f\"include_tables {missing_tables} not found in database\"\n                )\n        self._ignore_tables = set(ignore_tables) if ignore_tables else set()\n        if self._ignore_tables:\n            missing_tables = self._ignore_tables - self._all_tables\n            if missing_tables:\n                raise ValueError(\n                    f\"ignore_tables {missing_tables} not found in database\"\n                )\n        usable_tables = self.get_usable_table_names()\n        self._usable_tables = set(usable_tables) if usable_tables else self._all_tables\n        if not isinstance(sample_rows_in_table_info, int):\n            raise TypeError(\"sample_rows_in_table_info must be an integer\")\n        self._sample_rows_in_table_info = sample_rows_in_table_info\n        self._indexes_in_table_info = indexes_in_table_info\n        self._custom_table_info = custom_table_info\n        if self._custom_table_info:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html"}
{"id": "7b9bc0a5a7aa-2", "text": "self._custom_table_info = custom_table_info\n        if self._custom_table_info:\n            if not isinstance(self._custom_table_info, dict):\n                raise TypeError(\n                    \"table_info must be a dictionary with table names as keys and the \"\n                    \"desired table info as values\"\n                )\n            # only keep the tables that are also present in the database\n            intersection = set(self._custom_table_info).intersection(self._all_tables)\n            self._custom_table_info = dict(\n                (table, self._custom_table_info[table])\n                for table in self._custom_table_info\n                if table in intersection\n            )\n        self._max_string_length = max_string_length\n        self._metadata = metadata or MetaData()\n        # including view support if view_support = true\n        self._metadata.reflect(\n            views=view_support,\n            bind=self._engine,\n            only=list(self._usable_tables),\n            schema=self._schema,\n        )\n[docs]    @classmethod\n    def from_uri(\n        cls, database_uri: str, engine_args: Optional[dict] = None, **kwargs: Any\n    ) -> SQLDatabase:\n        \"\"\"Construct a SQLAlchemy engine from URI.\"\"\"\n        _engine_args = engine_args or {}\n        return cls(create_engine(database_uri, **_engine_args), **kwargs)\n[docs]    @classmethod\n    def from_databricks(\n        cls,\n        catalog: str,\n        schema: str,\n        host: Optional[str] = None,\n        api_token: Optional[str] = None,\n        warehouse_id: Optional[str] = None,\n        cluster_id: Optional[str] = None,\n        engine_args: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> SQLDatabase:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html"}
{"id": "7b9bc0a5a7aa-3", "text": "**kwargs: Any,\n    ) -> SQLDatabase:\n        \"\"\"\n        Class method to create an SQLDatabase instance from a Databricks connection.\n        This method requires the 'databricks-sql-connector' package. If not installed,\n        it can be added using `pip install databricks-sql-connector`.\n        Args:\n            catalog (str): The catalog name in the Databricks database.\n            schema (str): The schema name in the catalog.\n            host (Optional[str]): The Databricks workspace hostname, excluding\n                'https://' part. If not provided, it attempts to fetch from the\n                environment variable 'DATABRICKS_HOST'. If still unavailable and if\n                running in a Databricks notebook, it defaults to the current workspace\n                hostname. Defaults to None.\n            api_token (Optional[str]): The Databricks personal access token for\n                accessing the Databricks SQL warehouse or the cluster. If not provided,\n                it attempts to fetch from 'DATABRICKS_TOKEN'. If still unavailable\n                and running in a Databricks notebook, a temporary token for the current\n                user is generated. Defaults to None.\n            warehouse_id (Optional[str]): The warehouse ID in the Databricks SQL. If\n                provided, the method configures the connection to use this warehouse.\n                Cannot be used with 'cluster_id'. Defaults to None.\n            cluster_id (Optional[str]): The cluster ID in the Databricks Runtime. If\n                provided, the method configures the connection to use this cluster.\n                Cannot be used with 'warehouse_id'. If running in a Databricks notebook\n                and both 'warehouse_id' and 'cluster_id' are None, it uses the ID of the\n                cluster the notebook is attached to. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html"}
{"id": "7b9bc0a5a7aa-4", "text": "cluster the notebook is attached to. Defaults to None.\n            engine_args (Optional[dict]): The arguments to be used when connecting\n                Databricks. Defaults to None.\n            **kwargs (Any): Additional keyword arguments for the `from_uri` method.\n        Returns:\n            SQLDatabase: An instance of SQLDatabase configured with the provided\n                Databricks connection details.\n        Raises:\n            ValueError: If 'databricks-sql-connector' is not found, or if both\n                'warehouse_id' and 'cluster_id' are provided, or if neither\n                'warehouse_id' nor 'cluster_id' are provided and it's not executing\n                inside a Databricks notebook.\n        \"\"\"\n        try:\n            from databricks import sql  # noqa: F401\n        except ImportError:\n            raise ValueError(\n                \"databricks-sql-connector package not found, please install with\"\n                \" `pip install databricks-sql-connector`\"\n            )\n        context = None\n        try:\n            from dbruntime.databricks_repl_context import get_context\n            context = get_context()\n        except ImportError:\n            pass\n        default_host = context.browserHostName if context else None\n        if host is None:\n            host = get_from_env(\"host\", \"DATABRICKS_HOST\", default_host)\n        default_api_token = context.apiToken if context else None\n        if api_token is None:\n            api_token = get_from_env(\"api_token\", \"DATABRICKS_TOKEN\", default_api_token)\n        if warehouse_id is None and cluster_id is None:\n            if context:\n                cluster_id = context.clusterId\n            else:\n                raise ValueError(\n                    \"Need to provide either 'warehouse_id' or 'cluster_id'.\"\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html"}
{"id": "7b9bc0a5a7aa-5", "text": "\"Need to provide either 'warehouse_id' or 'cluster_id'.\"\n                )\n        if warehouse_id and cluster_id:\n            raise ValueError(\"Can't have both 'warehouse_id' or 'cluster_id'.\")\n        if warehouse_id:\n            http_path = f\"/sql/1.0/warehouses/{warehouse_id}\"\n        else:\n            http_path = f\"/sql/protocolv1/o/0/{cluster_id}\"\n        uri = (\n            f\"databricks://token:{api_token}@{host}?\"\n            f\"http_path={http_path}&catalog={catalog}&schema={schema}\"\n        )\n        return cls.from_uri(database_uri=uri, engine_args=engine_args, **kwargs)\n[docs]    @classmethod\n    def from_cnosdb(\n        cls,\n        url: str = \"127.0.0.1:8902\",\n        user: str = \"root\",\n        password: str = \"\",\n        tenant: str = \"cnosdb\",\n        database: str = \"public\",\n    ) -> SQLDatabase:\n        \"\"\"\n        Class method to create an SQLDatabase instance from a CnosDB connection.\n        This method requires the 'cnos-connector' package. If not installed, it\n        can be added using `pip install cnos-connector`.\n        Args:\n            url (str): The HTTP connection host name and port number of the CnosDB\n                service, excluding \"http://\" or \"https://\", with a default value\n                of \"127.0.0.1:8902\".\n            user (str): The username used to connect to the CnosDB service, with a\n                default value of \"root\".\n            password (str): The password of the user connecting to the CnosDB service,\n                with a default value of \"\".", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html"}
{"id": "7b9bc0a5a7aa-6", "text": "with a default value of \"\".\n            tenant (str): The name of the tenant used to connect to the CnosDB service,\n                with a default value of \"cnosdb\".\n            database (str): The name of the database in the CnosDB tenant.\n        Returns:\n            SQLDatabase: An instance of SQLDatabase configured with the provided\n            CnosDB connection details.\n        \"\"\"\n        try:\n            from cnosdb_connector import make_cnosdb_langchain_uri\n            uri = make_cnosdb_langchain_uri(url, user, password, tenant, database)\n            return cls.from_uri(database_uri=uri)\n        except ImportError:\n            raise ValueError(\n                \"cnos-connector package not found, please install with\"\n                \" `pip install cnos-connector`\"\n            )\n    @property\n    def dialect(self) -> str:\n        \"\"\"Return string representation of dialect to use.\"\"\"\n        return self._engine.dialect.name\n[docs]    def get_usable_table_names(self) -> Iterable[str]:\n        \"\"\"Get names of tables available.\"\"\"\n        if self._include_tables:\n            return sorted(self._include_tables)\n        return sorted(self._all_tables - self._ignore_tables)\n[docs]    def get_table_names(self) -> Iterable[str]:\n        \"\"\"Get names of tables available.\"\"\"\n        warnings.warn(\n            \"This method is deprecated - please use `get_usable_table_names`.\"\n        )\n        return self.get_usable_table_names()\n    @property\n    def table_info(self) -> str:\n        \"\"\"Information about all tables in the database.\"\"\"\n        return self.get_table_info()\n[docs]    def get_table_info(self, table_names: Optional[List[str]] = None) -> str:\n        \"\"\"Get information about specified tables.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html"}
{"id": "7b9bc0a5a7aa-7", "text": "\"\"\"Get information about specified tables.\n        Follows best practices as specified in: Rajkumar et al, 2022\n        (https://arxiv.org/abs/2204.00498)\n        If `sample_rows_in_table_info`, the specified number of sample rows will be\n        appended to each table description. This can increase performance as\n        demonstrated in the paper.\n        \"\"\"\n        all_table_names = self.get_usable_table_names()\n        if table_names is not None:\n            missing_tables = set(table_names).difference(all_table_names)\n            if missing_tables:\n                raise ValueError(f\"table_names {missing_tables} not found in database\")\n            all_table_names = table_names\n        meta_tables = [\n            tbl\n            for tbl in self._metadata.sorted_tables\n            if tbl.name in set(all_table_names)\n            and not (self.dialect == \"sqlite\" and tbl.name.startswith(\"sqlite_\"))\n        ]\n        tables = []\n        for table in meta_tables:\n            if self._custom_table_info and table.name in self._custom_table_info:\n                tables.append(self._custom_table_info[table.name])\n                continue\n            # Ignore JSON datatyped columns\n            for k, v in table.columns.items():\n                if type(v.type) is NullType:\n                    table._columns.remove(v)\n            # add create table command\n            create_table = str(CreateTable(table).compile(self._engine))\n            table_info = f\"{create_table.rstrip()}\"\n            has_extra_info = (\n                self._indexes_in_table_info or self._sample_rows_in_table_info\n            )\n            if has_extra_info:\n                table_info += \"\\n\\n/*\"\n            if self._indexes_in_table_info:\n                table_info += f\"\\n{self._get_table_indexes(table)}\\n\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html"}
{"id": "7b9bc0a5a7aa-8", "text": "table_info += f\"\\n{self._get_table_indexes(table)}\\n\"\n            if self._sample_rows_in_table_info:\n                table_info += f\"\\n{self._get_sample_rows(table)}\\n\"\n            if has_extra_info:\n                table_info += \"*/\"\n            tables.append(table_info)\n        tables.sort()\n        final_str = \"\\n\\n\".join(tables)\n        return final_str\n    def _get_table_indexes(self, table: Table) -> str:\n        indexes = self._inspector.get_indexes(table.name)\n        indexes_formatted = \"\\n\".join(map(_format_index, indexes))\n        return f\"Table Indexes:\\n{indexes_formatted}\"\n    def _get_sample_rows(self, table: Table) -> str:\n        # build the select command\n        command = select(table).limit(self._sample_rows_in_table_info)\n        # save the columns in string format\n        columns_str = \"\\t\".join([col.name for col in table.columns])\n        try:\n            # get the sample rows\n            with self._engine.connect() as connection:\n                sample_rows_result = connection.execute(command)  # type: ignore\n                # shorten values in the sample rows\n                sample_rows = list(\n                    map(lambda ls: [str(i)[:100] for i in ls], sample_rows_result)\n                )\n            # save the sample rows in string format\n            sample_rows_str = \"\\n\".join([\"\\t\".join(row) for row in sample_rows])\n        # in some dialects when there are no rows in the table a\n        # 'ProgrammingError' is returned\n        except ProgrammingError:\n            sample_rows_str = \"\"\n        return (\n            f\"{self._sample_rows_in_table_info} rows from {table.name} table:\\n\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html"}
{"id": "7b9bc0a5a7aa-9", "text": "f\"{columns_str}\\n\"\n            f\"{sample_rows_str}\"\n        )\n    def _execute(\n        self,\n        command: str,\n        fetch: Union[Literal[\"all\"], Literal[\"one\"]] = \"all\",\n    ) -> Sequence[Dict[str, Any]]:\n        \"\"\"\n        Executes SQL command through underlying engine.\n        If the statement returns no rows, an empty list is returned.\n        \"\"\"\n        with self._engine.begin() as connection:\n            if self._schema is not None:\n                if self.dialect == \"snowflake\":\n                    connection.exec_driver_sql(\n                        \"ALTER SESSION SET search_path = %s\", (self._schema,)\n                    )\n                elif self.dialect == \"bigquery\":\n                    connection.exec_driver_sql(\"SET @@dataset_id=?\", (self._schema,))\n                elif self.dialect == \"mssql\":\n                    pass\n                elif self.dialect == \"trino\":\n                    connection.exec_driver_sql(\"USE ?\", (self._schema,))\n                elif self.dialect == \"duckdb\":\n                    # Unclear which parameterized argument syntax duckdb supports.\n                    # The docs for the duckdb client say they support multiple,\n                    # but `duckdb_engine` seemed to struggle with all of them:\n                    # https://github.com/Mause/duckdb_engine/issues/796\n                    connection.exec_driver_sql(f\"SET search_path TO {self._schema}\")\n                else:  # postgresql and other compatible dialects\n                    connection.exec_driver_sql(\"SET search_path TO %s\", (self._schema,))\n            cursor = connection.execute(text(command))\n            if cursor.returns_rows:\n                if fetch == \"all\":\n                    result = [x._asdict() for x in cursor.fetchall()]\n                elif fetch == \"one\":", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html"}
{"id": "7b9bc0a5a7aa-10", "text": "elif fetch == \"one\":\n                    first_result = cursor.fetchone()\n                    result = [] if first_result is None else [first_result._asdict()]\n                else:\n                    raise ValueError(\"Fetch parameter must be either 'one' or 'all'\")\n                return result\n        return []\n[docs]    def run(\n        self,\n        command: str,\n        fetch: Union[Literal[\"all\"], Literal[\"one\"]] = \"all\",\n    ) -> str:\n        \"\"\"Execute a SQL command and return a string representing the results.\n        If the statement returns rows, a string of the results is returned.\n        If the statement returns no rows, an empty string is returned.\n        \"\"\"\n        result = self._execute(command, fetch)\n        # Convert columns values to string to avoid issues with sqlalchemy\n        # truncating text\n        res = [\n            tuple(truncate_word(c, length=self._max_string_length) for c in r.values())\n            for r in result\n        ]\n        if not res:\n            return \"\"\n        else:\n            return str(res)\n[docs]    def get_table_info_no_throw(self, table_names: Optional[List[str]] = None) -> str:\n        \"\"\"Get information about specified tables.\n        Follows best practices as specified in: Rajkumar et al, 2022\n        (https://arxiv.org/abs/2204.00498)\n        If `sample_rows_in_table_info`, the specified number of sample rows will be\n        appended to each table description. This can increase performance as\n        demonstrated in the paper.\n        \"\"\"\n        try:\n            return self.get_table_info(table_names)\n        except ValueError as e:\n            \"\"\"Format the error message\"\"\"\n            return f\"Error: {e}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html"}
{"id": "7b9bc0a5a7aa-11", "text": "\"\"\"Format the error message\"\"\"\n            return f\"Error: {e}\"\n[docs]    def run_no_throw(\n        self,\n        command: str,\n        fetch: Union[Literal[\"all\"], Literal[\"one\"]] = \"all\",\n    ) -> str:\n        \"\"\"Execute a SQL command and return a string representing the results.\n        If the statement returns rows, a string of the results is returned.\n        If the statement returns no rows, an empty string is returned.\n        If the statement throws an error, the error message is returned.\n        \"\"\"\n        try:\n            return self.run(command, fetch)\n        except SQLAlchemyError as e:\n            \"\"\"Format the error message\"\"\"\n            return f\"Error: {e}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html"}
{"id": "e7a6d896cdfc-0", "text": "Source code for langchain.utilities.bing_search\n\"\"\"Util that calls Bing Search.\nIn order to set this up, follow instructions at:\nhttps://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e\n\"\"\"\nfrom typing import Dict, List\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class BingSearchAPIWrapper(BaseModel):\n    \"\"\"Wrapper for Bing Search API.\n    In order to set this up, follow instructions at:\n    https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e\n    \"\"\"\n    bing_subscription_key: str\n    bing_search_url: str\n    k: int = 10\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    def _bing_search_results(self, search_term: str, count: int) -> List[dict]:\n        headers = {\"Ocp-Apim-Subscription-Key\": self.bing_subscription_key}\n        params = {\n            \"q\": search_term,\n            \"count\": count,\n            \"textDecorations\": True,\n            \"textFormat\": \"HTML\",\n        }\n        response = requests.get(\n            self.bing_search_url,\n            headers=headers,\n            params=params,  # type: ignore\n        )\n        response.raise_for_status()\n        search_results = response.json()\n        return search_results[\"webPages\"][\"value\"]\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and endpoint exists in environment.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html"}
{"id": "e7a6d896cdfc-1", "text": "\"\"\"Validate that api key and endpoint exists in environment.\"\"\"\n        bing_subscription_key = get_from_dict_or_env(\n            values, \"bing_subscription_key\", \"BING_SUBSCRIPTION_KEY\"\n        )\n        values[\"bing_subscription_key\"] = bing_subscription_key\n        bing_search_url = get_from_dict_or_env(\n            values,\n            \"bing_search_url\",\n            \"BING_SEARCH_URL\",\n            # default=\"https://api.bing.microsoft.com/v7.0/search\",\n        )\n        values[\"bing_search_url\"] = bing_search_url\n        return values\n[docs]    def run(self, query: str) -> str:\n        \"\"\"Run query through BingSearch and parse result.\"\"\"\n        snippets = []\n        results = self._bing_search_results(query, count=self.k)\n        if len(results) == 0:\n            return \"No good Bing Search Result was found\"\n        for result in results:\n            snippets.append(result[\"snippet\"])\n        return \" \".join(snippets)\n[docs]    def results(self, query: str, num_results: int) -> List[Dict]:\n        \"\"\"Run query through BingSearch and return metadata.\n        Args:\n            query: The query to search for.\n            num_results: The number of results to return.\n        Returns:\n            A list of dictionaries with the following keys:\n                snippet - The description of the result.\n                title - The title of the result.\n                link - The link to the result.\n        \"\"\"\n        metadata_results = []\n        results = self._bing_search_results(query, count=num_results)\n        if len(results) == 0:\n            return [{\"Result\": \"No good Bing Search Result was found\"}]\n        for result in results:\n            metadata_result = {\n                \"snippet\": result[\"snippet\"],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html"}
{"id": "e7a6d896cdfc-2", "text": "metadata_result = {\n                \"snippet\": result[\"snippet\"],\n                \"title\": result[\"name\"],\n                \"link\": result[\"url\"],\n            }\n            metadata_results.append(metadata_result)\n        return metadata_results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html"}
{"id": "cccecba97338-0", "text": "Source code for langchain.utilities.opaqueprompts\nfrom typing import Dict, Union\n[docs]def sanitize(\n    input: Union[str, Dict[str, str]]\n) -> Dict[str, Union[str, Dict[str, str]]]:\n    \"\"\"\n    Sanitize input string or dict of strings by replacing sensitive data with\n    placeholders.\n    It returns the sanitized input string or dict of strings and the secure\n    context as a dict following the format:\n    {\n        \"sanitized_input\": <sanitized input string or dict of strings>,\n        \"secure_context\": <secure context>\n    }\n    The secure context is a bytes object that is needed to de-sanitize the response\n    from the LLM.\n    Args:\n        input: Input string or dict of strings.\n    Returns:\n        Sanitized input string or dict of strings and the secure context\n        as a dict following the format:\n        {\n            \"sanitized_input\": <sanitized input string or dict of strings>,\n            \"secure_context\": <secure context>\n        }\n        The `secure_context` needs to be passed to the `desanitize` function.\n    Raises:\n        ValueError: If the input is not a string or dict of strings.\n        ImportError: If the `opaqueprompts` Python package is not installed.\n    \"\"\"\n    try:\n        import opaqueprompts as op\n    except ImportError:\n        raise ImportError(\n            \"Could not import the `opaqueprompts` Python package, \"\n            \"please install it with `pip install opaqueprompts`.\"\n        )\n    if isinstance(input, str):\n        # the input could be a string, so we sanitize the string\n        sanitize_response: op.SanitizeResponse = op.sanitize([input])\n        return {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/opaqueprompts.html"}
{"id": "cccecba97338-1", "text": "sanitize_response: op.SanitizeResponse = op.sanitize([input])\n        return {\n            \"sanitized_input\": sanitize_response.sanitized_texts[0],\n            \"secure_context\": sanitize_response.secure_context,\n        }\n    if isinstance(input, dict):\n        # the input could be a dict[string, string], so we sanitize the values\n        values = list()\n        # get the values from the dict\n        for key in input:\n            values.append(input[key])\n        # sanitize the values\n        sanitize_values_response: op.SanitizeResponse = op.sanitize(values)\n        # reconstruct the dict with the sanitized values\n        sanitized_input_values = sanitize_values_response.sanitized_texts\n        idx = 0\n        sanitized_input = dict()\n        for key in input:\n            sanitized_input[key] = sanitized_input_values[idx]\n            idx += 1\n        return {\n            \"sanitized_input\": sanitized_input,\n            \"secure_context\": sanitize_values_response.secure_context,\n        }\n    raise ValueError(f\"Unexpected input type {type(input)}\")\n[docs]def desanitize(sanitized_text: str, secure_context: bytes) -> str:\n    \"\"\"\n    Restore the original sensitive data from the sanitized text.\n    Args:\n        sanitized_text: Sanitized text.\n        secure_context: Secure context returned by the `sanitize` function.\n    Returns:\n        De-sanitized text.\n    \"\"\"\n    try:\n        import opaqueprompts as op\n    except ImportError:\n        raise ImportError(\n            \"Could not import the `opaqueprompts` Python package, \"\n            \"please install it with `pip install opaqueprompts`.\"\n        )\n    desanitize_response: op.DesanitizeResponse = op.desanitize(\n        sanitized_text, secure_context\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/opaqueprompts.html"}
{"id": "cccecba97338-2", "text": "sanitized_text, secure_context\n    )\n    return desanitize_response.desanitized_text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/opaqueprompts.html"}
{"id": "cdd60b93d5f4-0", "text": "Source code for langchain.utilities.dalle_image_generator\n\"\"\"Utility that calls OpenAI's Dall-E Image Generator.\"\"\"\nfrom typing import Any, Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class DallEAPIWrapper(BaseModel):\n    \"\"\"Wrapper for OpenAI's DALL-E Image Generator.\n    https://platform.openai.com/docs/guides/images/generations?context=node\n    Usage instructions:\n    1. `pip install openai`\n    2. save your OPENAI_API_KEY in an environment variable\n    \"\"\"\n    client: Any  #: :meta private:\n    openai_api_key: Optional[str] = None\n    n: int = 1\n    \"\"\"Number of images to generate\"\"\"\n    size: str = \"1024x1024\"\n    \"\"\"Size of image to generate\"\"\"\n    separator: str = \"\\n\"\n    \"\"\"Separator to use when multiple URLs are returned.\"\"\"\n    model: Optional[str] = None\n    \"\"\"Model to use for image generation.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        openai_api_key = get_from_dict_or_env(\n            values, \"openai_api_key\", \"OPENAI_API_KEY\"\n        )\n        try:\n            import openai\n            openai.api_key = openai_api_key\n            values[\"client\"] = openai.Image\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import openai python package. \"\n                \"Please it install it with `pip install openai`.\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dalle_image_generator.html"}
{"id": "cdd60b93d5f4-1", "text": "\"Please it install it with `pip install openai`.\"\n            ) from e\n        return values\n[docs]    def run(self, query: str) -> str:\n        \"\"\"Run query through OpenAI and parse result.\"\"\"\n        response = self.client.create(\n            prompt=query, n=self.n, size=self.size, model=self.model\n        )\n        image_urls = self.separator.join([item[\"url\"] for item in response[\"data\"]])\n        return image_urls if image_urls else \"No image was generated\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dalle_image_generator.html"}
{"id": "a49541e7440f-0", "text": "Source code for langchain.utilities.openapi\n\"\"\"Utility functions for parsing an OpenAPI spec.\"\"\"\nfrom __future__ import annotations\nimport copy\nimport json\nimport logging\nimport re\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Dict, List, Optional, Union\nimport requests\nimport yaml\nfrom langchain.pydantic_v1 import ValidationError\nlogger = logging.getLogger(__name__)\n[docs]class HTTPVerb(str, Enum):\n    \"\"\"Enumerator of the HTTP verbs.\"\"\"\n    GET = \"get\"\n    PUT = \"put\"\n    POST = \"post\"\n    DELETE = \"delete\"\n    OPTIONS = \"options\"\n    HEAD = \"head\"\n    PATCH = \"patch\"\n    TRACE = \"trace\"\n    @classmethod\n    def from_str(cls, verb: str) -> HTTPVerb:\n        \"\"\"Parse an HTTP verb.\"\"\"\n        try:\n            return cls(verb)\n        except ValueError:\n            raise ValueError(f\"Invalid HTTP verb. Valid values are {cls.__members__}\")\nif TYPE_CHECKING:\n    from openapi_pydantic import (\n        Components,\n        Operation,\n        Parameter,\n        PathItem,\n        Paths,\n        Reference,\n        RequestBody,\n        Schema,\n    )\ntry:\n    from openapi_pydantic import OpenAPI\nexcept ImportError:\n    OpenAPI = object  # type: ignore\n[docs]class OpenAPISpec(OpenAPI):\n    \"\"\"OpenAPI Model that removes mis-formatted parts of the spec.\"\"\"\n    openapi: str = \"3.1.0\"  # overriding overly restrictive type from parent class\n    @property\n    def _paths_strict(self) -> Paths:\n        if not self.paths:\n            raise ValueError(\"No paths found in spec\")\n        return self.paths", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html"}
{"id": "a49541e7440f-1", "text": "raise ValueError(\"No paths found in spec\")\n        return self.paths\n    def _get_path_strict(self, path: str) -> PathItem:\n        path_item = self._paths_strict.get(path)\n        if not path_item:\n            raise ValueError(f\"No path found for {path}\")\n        return path_item\n    @property\n    def _components_strict(self) -> Components:\n        \"\"\"Get components or err.\"\"\"\n        if self.components is None:\n            raise ValueError(\"No components found in spec. \")\n        return self.components\n    @property\n    def _parameters_strict(self) -> Dict[str, Union[Parameter, Reference]]:\n        \"\"\"Get parameters or err.\"\"\"\n        parameters = self._components_strict.parameters\n        if parameters is None:\n            raise ValueError(\"No parameters found in spec. \")\n        return parameters\n    @property\n    def _schemas_strict(self) -> Dict[str, Schema]:\n        \"\"\"Get the dictionary of schemas or err.\"\"\"\n        schemas = self._components_strict.schemas\n        if schemas is None:\n            raise ValueError(\"No schemas found in spec. \")\n        return schemas\n    @property\n    def _request_bodies_strict(self) -> Dict[str, Union[RequestBody, Reference]]:\n        \"\"\"Get the request body or err.\"\"\"\n        request_bodies = self._components_strict.requestBodies\n        if request_bodies is None:\n            raise ValueError(\"No request body found in spec. \")\n        return request_bodies\n    def _get_referenced_parameter(self, ref: Reference) -> Union[Parameter, Reference]:\n        \"\"\"Get a parameter (or nested reference) or err.\"\"\"\n        ref_name = ref.ref.split(\"/\")[-1]\n        parameters = self._parameters_strict\n        if ref_name not in parameters:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html"}
{"id": "a49541e7440f-2", "text": "parameters = self._parameters_strict\n        if ref_name not in parameters:\n            raise ValueError(f\"No parameter found for {ref_name}\")\n        return parameters[ref_name]\n    def _get_root_referenced_parameter(self, ref: Reference) -> Parameter:\n        \"\"\"Get the root reference or err.\"\"\"\n        from openapi_pydantic import Reference\n        parameter = self._get_referenced_parameter(ref)\n        while isinstance(parameter, Reference):\n            parameter = self._get_referenced_parameter(parameter)\n        return parameter\n[docs]    def get_referenced_schema(self, ref: Reference) -> Schema:\n        \"\"\"Get a schema (or nested reference) or err.\"\"\"\n        ref_name = ref.ref.split(\"/\")[-1]\n        schemas = self._schemas_strict\n        if ref_name not in schemas:\n            raise ValueError(f\"No schema found for {ref_name}\")\n        return schemas[ref_name]\n[docs]    def get_schema(self, schema: Union[Reference, Schema]) -> Schema:\n        from openapi_pydantic import Reference\n        if isinstance(schema, Reference):\n            return self.get_referenced_schema(schema)\n        return schema\n    def _get_root_referenced_schema(self, ref: Reference) -> Schema:\n        \"\"\"Get the root reference or err.\"\"\"\n        from openapi_pydantic import Reference\n        schema = self.get_referenced_schema(ref)\n        while isinstance(schema, Reference):\n            schema = self.get_referenced_schema(schema)\n        return schema\n    def _get_referenced_request_body(\n        self, ref: Reference\n    ) -> Optional[Union[Reference, RequestBody]]:\n        \"\"\"Get a request body (or nested reference) or err.\"\"\"\n        ref_name = ref.ref.split(\"/\")[-1]\n        request_bodies = self._request_bodies_strict", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html"}
{"id": "a49541e7440f-3", "text": "request_bodies = self._request_bodies_strict\n        if ref_name not in request_bodies:\n            raise ValueError(f\"No request body found for {ref_name}\")\n        return request_bodies[ref_name]\n    def _get_root_referenced_request_body(\n        self, ref: Reference\n    ) -> Optional[RequestBody]:\n        \"\"\"Get the root request Body or err.\"\"\"\n        from openapi_pydantic import Reference\n        request_body = self._get_referenced_request_body(ref)\n        while isinstance(request_body, Reference):\n            request_body = self._get_referenced_request_body(request_body)\n        return request_body\n    @staticmethod\n    def _alert_unsupported_spec(obj: dict) -> None:\n        \"\"\"Alert if the spec is not supported.\"\"\"\n        warning_message = (\n            \" This may result in degraded performance.\"\n            + \" Convert your OpenAPI spec to 3.1.* spec\"\n            + \" for better support.\"\n        )\n        swagger_version = obj.get(\"swagger\")\n        openapi_version = obj.get(\"openapi\")\n        if isinstance(openapi_version, str):\n            if openapi_version != \"3.1.0\":\n                logger.warning(\n                    f\"Attempting to load an OpenAPI {openapi_version}\"\n                    f\" spec. {warning_message}\"\n                )\n            else:\n                pass\n        elif isinstance(swagger_version, str):\n            logger.warning(\n                f\"Attempting to load a Swagger {swagger_version}\"\n                f\" spec. {warning_message}\"\n            )\n        else:\n            raise ValueError(\n                \"Attempting to load an unsupported spec:\"\n                f\"\\n\\n{obj}\\n{warning_message}\"\n            )\n[docs]    @classmethod\n    def parse_obj(cls, obj: dict) -> OpenAPISpec:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html"}
{"id": "a49541e7440f-4", "text": "def parse_obj(cls, obj: dict) -> OpenAPISpec:\n        try:\n            cls._alert_unsupported_spec(obj)\n            return super().parse_obj(obj)\n        except ValidationError as e:\n            # We are handling possibly misconfigured specs and\n            # want to do a best-effort job to get a reasonable interface out of it.\n            new_obj = copy.deepcopy(obj)\n            for error in e.errors():\n                keys = error[\"loc\"]\n                item = new_obj\n                for key in keys[:-1]:\n                    item = item[key]\n                item.pop(keys[-1], None)\n            return cls.parse_obj(new_obj)\n[docs]    @classmethod\n    def from_spec_dict(cls, spec_dict: dict) -> OpenAPISpec:\n        \"\"\"Get an OpenAPI spec from a dict.\"\"\"\n        return cls.parse_obj(spec_dict)\n[docs]    @classmethod\n    def from_text(cls, text: str) -> OpenAPISpec:\n        \"\"\"Get an OpenAPI spec from a text.\"\"\"\n        try:\n            spec_dict = json.loads(text)\n        except json.JSONDecodeError:\n            spec_dict = yaml.safe_load(text)\n        return cls.from_spec_dict(spec_dict)\n[docs]    @classmethod\n    def from_file(cls, path: Union[str, Path]) -> OpenAPISpec:\n        \"\"\"Get an OpenAPI spec from a file path.\"\"\"\n        path_ = path if isinstance(path, Path) else Path(path)\n        if not path_.exists():\n            raise FileNotFoundError(f\"{path} does not exist\")\n        with path_.open(\"r\") as f:\n            return cls.from_text(f.read())\n[docs]    @classmethod\n    def from_url(cls, url: str) -> OpenAPISpec:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html"}
{"id": "a49541e7440f-5", "text": "def from_url(cls, url: str) -> OpenAPISpec:\n        \"\"\"Get an OpenAPI spec from a URL.\"\"\"\n        response = requests.get(url)\n        return cls.from_text(response.text)\n    @property\n    def base_url(self) -> str:\n        \"\"\"Get the base url.\"\"\"\n        return self.servers[0].url\n[docs]    def get_methods_for_path(self, path: str) -> List[str]:\n        \"\"\"Return a list of valid methods for the specified path.\"\"\"\n        from openapi_pydantic import Operation\n        path_item = self._get_path_strict(path)\n        results = []\n        for method in HTTPVerb:\n            operation = getattr(path_item, method.value, None)\n            if isinstance(operation, Operation):\n                results.append(method.value)\n        return results\n[docs]    def get_parameters_for_path(self, path: str) -> List[Parameter]:\n        from openapi_pydantic import Reference\n        path_item = self._get_path_strict(path)\n        parameters = []\n        if not path_item.parameters:\n            return []\n        for parameter in path_item.parameters:\n            if isinstance(parameter, Reference):\n                parameter = self._get_root_referenced_parameter(parameter)\n            parameters.append(parameter)\n        return parameters\n[docs]    def get_operation(self, path: str, method: str) -> Operation:\n        \"\"\"Get the operation object for a given path and HTTP method.\"\"\"\n        from openapi_pydantic import Operation\n        path_item = self._get_path_strict(path)\n        operation_obj = getattr(path_item, method, None)\n        if not isinstance(operation_obj, Operation):\n            raise ValueError(f\"No {method} method found for {path}\")\n        return operation_obj", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html"}
{"id": "a49541e7440f-6", "text": "raise ValueError(f\"No {method} method found for {path}\")\n        return operation_obj\n[docs]    def get_parameters_for_operation(self, operation: Operation) -> List[Parameter]:\n        \"\"\"Get the components for a given operation.\"\"\"\n        from openapi_pydantic import Reference\n        parameters = []\n        if operation.parameters:\n            for parameter in operation.parameters:\n                if isinstance(parameter, Reference):\n                    parameter = self._get_root_referenced_parameter(parameter)\n                parameters.append(parameter)\n        return parameters\n[docs]    def get_request_body_for_operation(\n        self, operation: Operation\n    ) -> Optional[RequestBody]:\n        \"\"\"Get the request body for a given operation.\"\"\"\n        from openapi_pydantic import Reference\n        request_body = operation.requestBody\n        if isinstance(request_body, Reference):\n            request_body = self._get_root_referenced_request_body(request_body)\n        return request_body\n[docs]    @staticmethod\n    def get_cleaned_operation_id(operation: Operation, path: str, method: str) -> str:\n        \"\"\"Get a cleaned operation id from an operation id.\"\"\"\n        operation_id = operation.operationId\n        if operation_id is None:\n            # Replace all punctuation of any kind with underscore\n            path = re.sub(r\"[^a-zA-Z0-9]\", \"_\", path.lstrip(\"/\"))\n            operation_id = f\"{path}_{method}\"\n        return operation_id.replace(\"-\", \"_\").replace(\".\", \"_\").replace(\"/\", \"_\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html"}
{"id": "688049c407e2-0", "text": "Source code for langchain.utilities.serpapi\n\"\"\"Chain that calls SerpAPI.\nHeavily borrowed from https://github.com/ofirpress/self-ask\n\"\"\"\nimport os\nimport sys\nfrom typing import Any, Dict, Optional, Tuple\nimport aiohttp\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class HiddenPrints:\n    \"\"\"Context manager to hide prints.\"\"\"\n    def __enter__(self) -> None:\n        \"\"\"Open file to pipe stdout to.\"\"\"\n        self._original_stdout = sys.stdout\n        sys.stdout = open(os.devnull, \"w\")\n    def __exit__(self, *_: Any) -> None:\n        \"\"\"Close file that stdout was piped to.\"\"\"\n        sys.stdout.close()\n        sys.stdout = self._original_stdout\n[docs]class SerpAPIWrapper(BaseModel):\n    \"\"\"Wrapper around SerpAPI.\n    To use, you should have the ``google-search-results`` python package installed,\n    and the environment variable ``SERPAPI_API_KEY`` set with your API key, or pass\n    `serpapi_api_key` as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.utilities import SerpAPIWrapper\n            serpapi = SerpAPIWrapper()\n    \"\"\"\n    search_engine: Any  #: :meta private:\n    params: dict = Field(\n        default={\n            \"engine\": \"google\",\n            \"google_domain\": \"google.com\",\n            \"gl\": \"us\",\n            \"hl\": \"en\",\n        }\n    )\n    serpapi_api_key: Optional[str] = None\n    aiosession: Optional[aiohttp.ClientSession] = None\n    class Config:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html"}
{"id": "688049c407e2-1", "text": "aiosession: Optional[aiohttp.ClientSession] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        serpapi_api_key = get_from_dict_or_env(\n            values, \"serpapi_api_key\", \"SERPAPI_API_KEY\"\n        )\n        values[\"serpapi_api_key\"] = serpapi_api_key\n        try:\n            from serpapi import GoogleSearch\n            values[\"search_engine\"] = GoogleSearch\n        except ImportError:\n            raise ValueError(\n                \"Could not import serpapi python package. \"\n                \"Please install it with `pip install google-search-results`.\"\n            )\n        return values\n[docs]    async def arun(self, query: str, **kwargs: Any) -> str:\n        \"\"\"Run query through SerpAPI and parse result async.\"\"\"\n        return self._process_response(await self.aresults(query))\n[docs]    def run(self, query: str, **kwargs: Any) -> str:\n        \"\"\"Run query through SerpAPI and parse result.\"\"\"\n        return self._process_response(self.results(query))\n[docs]    def results(self, query: str) -> dict:\n        \"\"\"Run query through SerpAPI and return the raw result.\"\"\"\n        params = self.get_params(query)\n        with HiddenPrints():\n            search = self.search_engine(params)\n            res = search.get_dict()\n        return res\n[docs]    async def aresults(self, query: str) -> dict:\n        \"\"\"Use aiohttp to run query through SerpAPI and return the results async.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html"}
{"id": "688049c407e2-2", "text": "\"\"\"Use aiohttp to run query through SerpAPI and return the results async.\"\"\"\n        def construct_url_and_params() -> Tuple[str, Dict[str, str]]:\n            params = self.get_params(query)\n            params[\"source\"] = \"python\"\n            if self.serpapi_api_key:\n                params[\"serp_api_key\"] = self.serpapi_api_key\n            params[\"output\"] = \"json\"\n            url = \"https://serpapi.com/search\"\n            return url, params\n        url, params = construct_url_and_params()\n        if not self.aiosession:\n            async with aiohttp.ClientSession() as session:\n                async with session.get(url, params=params) as response:\n                    res = await response.json()\n        else:\n            async with self.aiosession.get(url, params=params) as response:\n                res = await response.json()\n        return res\n[docs]    def get_params(self, query: str) -> Dict[str, str]:\n        \"\"\"Get parameters for SerpAPI.\"\"\"\n        _params = {\n            \"api_key\": self.serpapi_api_key,\n            \"q\": query,\n        }\n        params = {**self.params, **_params}\n        return params\n    @staticmethod\n    def _process_response(res: dict) -> str:\n        \"\"\"Process response from SerpAPI.\"\"\"\n        if \"error\" in res.keys():\n            raise ValueError(f\"Got error from SerpAPI: {res['error']}\")\n        if \"answer_box_list\" in res.keys():\n            res[\"answer_box\"] = res[\"answer_box_list\"]\n        if \"answer_box\" in res.keys():\n            answer_box = res[\"answer_box\"]\n            if isinstance(answer_box, list):\n                answer_box = answer_box[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html"}
{"id": "688049c407e2-3", "text": "if isinstance(answer_box, list):\n                answer_box = answer_box[0]\n            if \"result\" in answer_box.keys():\n                return answer_box[\"result\"]\n            elif \"answer\" in answer_box.keys():\n                return answer_box[\"answer\"]\n            elif \"snippet\" in answer_box.keys():\n                return answer_box[\"snippet\"]\n            elif \"snippet_highlighted_words\" in answer_box.keys():\n                return answer_box[\"snippet_highlighted_words\"]\n            else:\n                answer = {}\n                for key, value in answer_box.items():\n                    if not isinstance(value, (list, dict)) and not (\n                        isinstance(value, str) and value.startswith(\"http\")\n                    ):\n                        answer[key] = value\n                return str(answer)\n        elif \"events_results\" in res.keys():\n            return res[\"events_results\"][:10]\n        elif \"sports_results\" in res.keys():\n            return res[\"sports_results\"]\n        elif \"top_stories\" in res.keys():\n            return res[\"top_stories\"]\n        elif \"news_results\" in res.keys():\n            return res[\"news_results\"]\n        elif \"jobs_results\" in res.keys() and \"jobs\" in res[\"jobs_results\"].keys():\n            return res[\"jobs_results\"][\"jobs\"]\n        elif (\n            \"shopping_results\" in res.keys()\n            and \"title\" in res[\"shopping_results\"][0].keys()\n        ):\n            return res[\"shopping_results\"][:3]\n        elif \"questions_and_answers\" in res.keys():\n            return res[\"questions_and_answers\"]\n        elif (\n            \"popular_destinations\" in res.keys()\n            and \"destinations\" in res[\"popular_destinations\"].keys()\n        ):\n            return res[\"popular_destinations\"][\"destinations\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html"}
{"id": "688049c407e2-4", "text": "):\n            return res[\"popular_destinations\"][\"destinations\"]\n        elif \"top_sights\" in res.keys() and \"sights\" in res[\"top_sights\"].keys():\n            return res[\"top_sights\"][\"sights\"]\n        elif (\n            \"images_results\" in res.keys()\n            and \"thumbnail\" in res[\"images_results\"][0].keys()\n        ):\n            return str([item[\"thumbnail\"] for item in res[\"images_results\"][:10]])\n        snippets = []\n        if \"knowledge_graph\" in res.keys():\n            knowledge_graph = res[\"knowledge_graph\"]\n            title = knowledge_graph[\"title\"] if \"title\" in knowledge_graph else \"\"\n            if \"description\" in knowledge_graph.keys():\n                snippets.append(knowledge_graph[\"description\"])\n            for key, value in knowledge_graph.items():\n                if (\n                    isinstance(key, str)\n                    and isinstance(value, str)\n                    and key not in [\"title\", \"description\"]\n                    and not key.endswith(\"_stick\")\n                    and not key.endswith(\"_link\")\n                    and not value.startswith(\"http\")\n                ):\n                    snippets.append(f\"{title} {key}: {value}.\")\n        for organic_result in res.get(\"organic_results\", []):\n            if \"snippet\" in organic_result.keys():\n                snippets.append(organic_result[\"snippet\"])\n            elif \"snippet_highlighted_words\" in organic_result.keys():\n                snippets.append(organic_result[\"snippet_highlighted_words\"])\n            elif \"rich_snippet\" in organic_result.keys():\n                snippets.append(organic_result[\"rich_snippet\"])\n            elif \"rich_snippet_table\" in organic_result.keys():\n                snippets.append(organic_result[\"rich_snippet_table\"])\n            elif \"link\" in organic_result.keys():\n                snippets.append(organic_result[\"link\"])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html"}
{"id": "688049c407e2-5", "text": "snippets.append(organic_result[\"link\"])\n        if \"buying_guide\" in res.keys():\n            snippets.append(res[\"buying_guide\"])\n        if \"local_results\" in res.keys() and \"places\" in res[\"local_results\"].keys():\n            snippets.append(res[\"local_results\"][\"places\"])\n        if len(snippets) > 0:\n            return str(snippets)\n        else:\n            return \"No good search result found\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html"}
{"id": "0526c91229e3-0", "text": "Source code for langchain.utilities.tavily_search\n\"\"\"Util that calls Tavily Search API.\nIn order to set this up, follow instructions at:\n\"\"\"\nimport json\nfrom typing import Dict, List, Optional\nimport aiohttp\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\nTAVILY_API_URL = \"https://api.tavily.com\"\n[docs]class TavilySearchAPIWrapper(BaseModel):\n    \"\"\"Wrapper for Tavily Search API.\"\"\"\n    tavily_api_key: str\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and endpoint exists in environment.\"\"\"\n        tavily_api_key = get_from_dict_or_env(\n            values, \"tavily_api_key\", \"TAVILY_API_KEY\"\n        )\n        values[\"tavily_api_key\"] = tavily_api_key\n        return values\n[docs]    def raw_results(\n        self,\n        query: str,\n        max_results: Optional[int] = 5,\n        search_depth: Optional[str] = \"advanced\",\n        include_domains: Optional[List[str]] = [],\n        exclude_domains: Optional[List[str]] = [],\n        include_answer: Optional[bool] = False,\n        include_raw_content: Optional[bool] = False,\n        include_images: Optional[bool] = False,\n    ) -> Dict:\n        params = {\n            \"api_key\": self.tavily_api_key,\n            \"query\": query,\n            \"max_results\": max_results,\n            \"search_depth\": search_depth,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tavily_search.html"}
{"id": "0526c91229e3-1", "text": "\"max_results\": max_results,\n            \"search_depth\": search_depth,\n            \"include_domains\": include_domains,\n            \"exclude_domains\": exclude_domains,\n            \"include_answer\": include_answer,\n            \"include_raw_content\": include_raw_content,\n            \"include_images\": include_images,\n        }\n        response = requests.post(\n            # type: ignore\n            f\"{TAVILY_API_URL}/search\",\n            json=params,\n        )\n        response.raise_for_status()\n        return response.json()\n[docs]    def results(\n        self,\n        query: str,\n        max_results: Optional[int] = 5,\n        search_depth: Optional[str] = \"advanced\",\n        include_domains: Optional[List[str]] = [],\n        exclude_domains: Optional[List[str]] = [],\n        include_answer: Optional[bool] = False,\n        include_raw_content: Optional[bool] = False,\n        include_images: Optional[bool] = False,\n    ) -> List[Dict]:\n        \"\"\"Run query through Tavily Search and return metadata.\n        Args:\n            query: The query to search for.\n            max_results: The maximum number of results to return.\n            search_depth: The depth of the search. Can be \"basic\" or \"advanced\".\n            include_domains: A list of domains to include in the search.\n            exclude_domains: A list of domains to exclude from the search.\n            include_answer: Whether to include the answer in the results.\n            include_raw_content: Whether to include the raw content in the results.\n            include_images: Whether to include images in the results.\n        Returns:\n            query: The query that was searched for.\n            follow_up_questions: A list of follow up questions.\n            response_time: The response time of the query.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tavily_search.html"}
{"id": "0526c91229e3-2", "text": "response_time: The response time of the query.\n            answer: The answer to the query.\n            images: A list of images.\n            results: A list of dictionaries containing the results:\n                title: The title of the result.\n                url: The url of the result.\n                content: The content of the result.\n                score: The score of the result.\n                raw_content: The raw content of the result.\n        \"\"\"  # noqa: E501\n        raw_search_results = self.raw_results(\n            query,\n            max_results=max_results,\n            search_depth=search_depth,\n            include_domains=include_domains,\n            exclude_domains=exclude_domains,\n            include_answer=include_answer,\n            include_raw_content=include_raw_content,\n            include_images=include_images,\n        )\n        return self.clean_results(raw_search_results[\"results\"])\n[docs]    async def raw_results_async(\n        self,\n        query: str,\n        max_results: Optional[int] = 5,\n        search_depth: Optional[str] = \"advanced\",\n        include_domains: Optional[List[str]] = [],\n        exclude_domains: Optional[List[str]] = [],\n        include_answer: Optional[bool] = False,\n        include_raw_content: Optional[bool] = False,\n        include_images: Optional[bool] = False,\n    ) -> Dict:\n        \"\"\"Get results from the Tavily Search API asynchronously.\"\"\"\n        # Function to perform the API call\n        async def fetch() -> str:\n            params = {\n                \"api_key\": self.tavily_api_key,\n                \"query\": query,\n                \"max_results\": max_results,\n                \"search_depth\": search_depth,\n                \"include_domains\": include_domains,\n                \"exclude_domains\": exclude_domains,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tavily_search.html"}
{"id": "0526c91229e3-3", "text": "\"include_domains\": include_domains,\n                \"exclude_domains\": exclude_domains,\n                \"include_answer\": include_answer,\n                \"include_raw_content\": include_raw_content,\n                \"include_images\": include_images,\n            }\n            async with aiohttp.ClientSession() as session:\n                async with session.post(f\"{TAVILY_API_URL}/search\", json=params) as res:\n                    if res.status == 200:\n                        data = await res.text()\n                        return data\n                    else:\n                        raise Exception(f\"Error {res.status}: {res.reason}\")\n        results_json_str = await fetch()\n        return json.loads(results_json_str)\n[docs]    async def results_async(\n        self,\n        query: str,\n        max_results: Optional[int] = 5,\n        search_depth: Optional[str] = \"advanced\",\n        include_domains: Optional[List[str]] = [],\n        exclude_domains: Optional[List[str]] = [],\n        include_answer: Optional[bool] = False,\n        include_raw_content: Optional[bool] = False,\n        include_images: Optional[bool] = False,\n    ) -> List[Dict]:\n        results_json = await self.raw_results_async(\n            query=query,\n            max_results=max_results,\n            search_depth=search_depth,\n            include_domains=include_domains,\n            exclude_domains=exclude_domains,\n            include_answer=include_answer,\n            include_raw_content=include_raw_content,\n            include_images=include_images,\n        )\n        return self.clean_results(results_json[\"results\"])\n[docs]    def clean_results(self, results: List[Dict]) -> List[Dict]:\n        \"\"\"Clean results from Tavily Search API.\"\"\"\n        clean_results = []\n        for result in results:\n            clean_results.append(\n                {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tavily_search.html"}
{"id": "0526c91229e3-4", "text": "for result in results:\n            clean_results.append(\n                {\n                    \"url\": result[\"url\"],\n                    \"content\": result[\"content\"],\n                }\n            )\n        return clean_results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tavily_search.html"}
{"id": "3dcc8af29e2c-0", "text": "Source code for langchain.document_transformers.embeddings_redundant_filter\n\"\"\"Transform documents\"\"\"\nfrom typing import Any, Callable, List, Sequence\nimport numpy as np\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema import BaseDocumentTransformer, Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils.math import cosine_similarity\nclass _DocumentWithState(Document):\n    \"\"\"Wrapper for a document that includes arbitrary state.\"\"\"\n    state: dict = Field(default_factory=dict)\n    \"\"\"State associated with the document.\"\"\"\n    def to_document(self) -> Document:\n        \"\"\"Convert the DocumentWithState to a Document.\"\"\"\n        return Document(page_content=self.page_content, metadata=self.metadata)\n    @classmethod\n    def from_document(cls, doc: Document) -> \"_DocumentWithState\":\n        \"\"\"Create a DocumentWithState from a Document.\"\"\"\n        if isinstance(doc, cls):\n            return doc\n        return cls(page_content=doc.page_content, metadata=doc.metadata)\n[docs]def get_stateful_documents(\n    documents: Sequence[Document],\n) -> Sequence[_DocumentWithState]:\n    \"\"\"Convert a list of documents to a list of documents with state.\n    Args:\n        documents: The documents to convert.\n    Returns:\n        A list of documents with state.\n    \"\"\"\n    return [_DocumentWithState.from_document(doc) for doc in documents]\ndef _filter_similar_embeddings(\n    embedded_documents: List[List[float]], similarity_fn: Callable, threshold: float\n) -> List[int]:\n    \"\"\"Filter redundant documents based on the similarity of their embeddings.\"\"\"\n    similarity = np.tril(similarity_fn(embedded_documents, embedded_documents), k=-1)\n    redundant = np.where(similarity > threshold)\n    redundant_stacked = np.column_stack(redundant)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html"}
{"id": "3dcc8af29e2c-1", "text": "redundant_stacked = np.column_stack(redundant)\n    redundant_sorted = np.argsort(similarity[redundant])[::-1]\n    included_idxs = set(range(len(embedded_documents)))\n    for first_idx, second_idx in redundant_stacked[redundant_sorted]:\n        if first_idx in included_idxs and second_idx in included_idxs:\n            # Default to dropping the second document of any highly similar pair.\n            included_idxs.remove(second_idx)\n    return list(sorted(included_idxs))\ndef _get_embeddings_from_stateful_docs(\n    embeddings: Embeddings, documents: Sequence[_DocumentWithState]\n) -> List[List[float]]:\n    if len(documents) and \"embedded_doc\" in documents[0].state:\n        embedded_documents = [doc.state[\"embedded_doc\"] for doc in documents]\n    else:\n        embedded_documents = embeddings.embed_documents(\n            [d.page_content for d in documents]\n        )\n        for doc, embedding in zip(documents, embedded_documents):\n            doc.state[\"embedded_doc\"] = embedding\n    return embedded_documents\ndef _filter_cluster_embeddings(\n    embedded_documents: List[List[float]],\n    num_clusters: int,\n    num_closest: int,\n    random_state: int,\n    remove_duplicates: bool,\n) -> List[int]:\n    \"\"\"Filter documents based on proximity of their embeddings to clusters.\"\"\"\n    try:\n        from sklearn.cluster import KMeans\n    except ImportError:\n        raise ImportError(\n            \"sklearn package not found, please install it with \"\n            \"`pip install scikit-learn`\"\n        )\n    kmeans = KMeans(n_clusters=num_clusters, random_state=random_state).fit(\n        embedded_documents\n    )\n    closest_indices = []\n    # Loop through the number of clusters you have", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html"}
{"id": "3dcc8af29e2c-2", "text": ")\n    closest_indices = []\n    # Loop through the number of clusters you have\n    for i in range(num_clusters):\n        # Get the list of distances from that particular cluster center\n        distances = np.linalg.norm(\n            embedded_documents - kmeans.cluster_centers_[i], axis=1\n        )\n        # Find the indices of the two unique closest ones\n        # (using argsort to find the smallest 2 distances)\n        if remove_duplicates:\n            # Only add not duplicated vectors.\n            closest_indices_sorted = [\n                x\n                for x in np.argsort(distances)[:num_closest]\n                if x not in closest_indices\n            ]\n        else:\n            # Skip duplicates and add the next closest vector.\n            closest_indices_sorted = [\n                x for x in np.argsort(distances) if x not in closest_indices\n            ][:num_closest]\n        # Append that position closest indices list\n        closest_indices.extend(closest_indices_sorted)\n    return closest_indices\n[docs]class EmbeddingsRedundantFilter(BaseDocumentTransformer, BaseModel):\n    \"\"\"Filter that drops redundant documents by comparing their embeddings.\"\"\"\n    embeddings: Embeddings\n    \"\"\"Embeddings to use for embedding document contents.\"\"\"\n    similarity_fn: Callable = cosine_similarity\n    \"\"\"Similarity function for comparing documents. Function expected to take as input\n    two matrices (List[List[float]]) and return a matrix of scores where higher values\n    indicate greater similarity.\"\"\"\n    similarity_threshold: float = 0.95\n    \"\"\"Threshold for determining when two documents are similar enough\n    to be considered redundant.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def transform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html"}
{"id": "3dcc8af29e2c-3", "text": ") -> Sequence[Document]:\n        \"\"\"Filter down documents.\"\"\"\n        stateful_documents = get_stateful_documents(documents)\n        embedded_documents = _get_embeddings_from_stateful_docs(\n            self.embeddings, stateful_documents\n        )\n        included_idxs = _filter_similar_embeddings(\n            embedded_documents, self.similarity_fn, self.similarity_threshold\n        )\n        return [stateful_documents[i] for i in sorted(included_idxs)]\n[docs]class EmbeddingsClusteringFilter(BaseDocumentTransformer, BaseModel):\n    \"\"\"Perform K-means clustering on document vectors.\n    Returns an arbitrary number of documents closest to center.\"\"\"\n    embeddings: Embeddings\n    \"\"\"Embeddings to use for embedding document contents.\"\"\"\n    num_clusters: int = 5\n    \"\"\"Number of clusters. Groups of documents with similar meaning.\"\"\"\n    num_closest: int = 1\n    \"\"\"The number of closest vectors to return for each cluster center.\"\"\"\n    random_state: int = 42\n    \"\"\"Controls the random number generator used to initialize the cluster centroids.\n    If you set the random_state parameter to None, the KMeans algorithm will use a \n    random number generator that is seeded with the current time. This means \n    that the results of the KMeans algorithm will be different each time you \n    run it.\"\"\"\n    sorted: bool = False\n    \"\"\"By default results are re-ordered \"grouping\" them by cluster, if sorted is true\n    result will be ordered by the original position from the retriever\"\"\"\n    remove_duplicates: bool = False\n    \"\"\" By default duplicated results are skipped and replaced by the next closest \n    vector in the cluster. If remove_duplicates is true no replacement will be done:\n    This could dramatically reduce results when there is a lot of overlap between \n    clusters.\n    \"\"\"\n    class Config:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html"}
{"id": "3dcc8af29e2c-4", "text": "clusters.\n    \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def transform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        \"\"\"Filter down documents.\"\"\"\n        stateful_documents = get_stateful_documents(documents)\n        embedded_documents = _get_embeddings_from_stateful_docs(\n            self.embeddings, stateful_documents\n        )\n        included_idxs = _filter_cluster_embeddings(\n            embedded_documents,\n            self.num_clusters,\n            self.num_closest,\n            self.random_state,\n            self.remove_duplicates,\n        )\n        results = sorted(included_idxs) if self.sorted else included_idxs\n        return [stateful_documents[i] for i in results]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html"}
{"id": "7953eeb3e7b6-0", "text": "Source code for langchain.document_transformers.nuclia_text_transform\nimport asyncio\nimport json\nimport uuid\nfrom typing import Any, Sequence\nfrom langchain.schema.document import BaseDocumentTransformer, Document\nfrom langchain.tools.nuclia.tool import NucliaUnderstandingAPI\n[docs]class NucliaTextTransformer(BaseDocumentTransformer):\n    \"\"\"\n    The Nuclia Understanding API splits into paragraphs and sentences,\n    identifies entities, provides a summary of the text and generates\n    embeddings for all sentences.\n    \"\"\"\n[docs]    def __init__(self, nua: NucliaUnderstandingAPI):\n        self.nua = nua\n[docs]    def transform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        raise NotImplementedError\n[docs]    async def atransform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        tasks = [\n            self.nua.arun(\n                {\n                    \"action\": \"push\",\n                    \"id\": str(uuid.uuid4()),\n                    \"text\": doc.page_content,\n                    \"path\": None,\n                }\n            )\n            for doc in documents\n        ]\n        results = await asyncio.gather(*tasks)\n        for doc, result in zip(documents, results):\n            obj = json.loads(result)\n            metadata = {\n                \"file\": obj[\"file_extracted_data\"][0],\n                \"metadata\": obj[\"field_metadata\"][0],\n            }\n            doc.metadata[\"nuclia\"] = metadata\n        return documents", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/nuclia_text_transform.html"}
{"id": "8ad6eadd5cbe-0", "text": "Source code for langchain.document_transformers.long_context_reorder\n\"\"\"Reorder documents\"\"\"\nfrom typing import Any, List, Sequence\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema import BaseDocumentTransformer, Document\ndef _litm_reordering(documents: List[Document]) -> List[Document]:\n    \"\"\"Lost in the middle reorder: the less relevant documents will be at the\n    middle of the list and more relevant elements at beginning / end.\n    See: https://arxiv.org/abs//2307.03172\"\"\"\n    documents.reverse()\n    reordered_result = []\n    for i, value in enumerate(documents):\n        if i % 2 == 1:\n            reordered_result.append(value)\n        else:\n            reordered_result.insert(0, value)\n    return reordered_result\n[docs]class LongContextReorder(BaseDocumentTransformer, BaseModel):\n    \"\"\"Lost in the middle:\n    Performance degrades when models must access relevant information\n    in the middle of long contexts.\n    See: https://arxiv.org/abs//2307.03172\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def transform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        \"\"\"Reorders documents.\"\"\"\n        return _litm_reordering(list(documents))\n[docs]    async def atransform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        raise NotImplementedError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/long_context_reorder.html"}
{"id": "fada79180ef4-0", "text": "Source code for langchain.document_transformers.beautiful_soup_transformer\nfrom typing import Any, Iterator, List, Sequence, cast\nfrom langchain.schema import BaseDocumentTransformer, Document\n[docs]class BeautifulSoupTransformer(BaseDocumentTransformer):\n    \"\"\"Transform HTML content by extracting specific tags and removing unwanted ones.\n    Example:\n        .. code-block:: python\n            from langchain.document_transformers import BeautifulSoupTransformer\n            bs4_transformer = BeautifulSoupTransformer()\n            docs_transformed = bs4_transformer.transform_documents(docs)\n    \"\"\"\n[docs]    def __init__(self) -> None:\n        \"\"\"\n        Initialize the transformer.\n        This checks if the BeautifulSoup4 package is installed.\n        If not, it raises an ImportError.\n        \"\"\"\n        try:\n            import bs4  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"BeautifulSoup4 is required for BeautifulSoupTransformer. \"\n                \"Please install it with `pip install beautifulsoup4`.\"\n            )\n[docs]    def transform_documents(\n        self,\n        documents: Sequence[Document],\n        unwanted_tags: List[str] = [\"script\", \"style\"],\n        tags_to_extract: List[str] = [\"p\", \"li\", \"div\", \"a\"],\n        remove_lines: bool = True,\n        **kwargs: Any,\n    ) -> Sequence[Document]:\n        \"\"\"\n        Transform a list of Document objects by cleaning their HTML content.\n        Args:\n            documents: A sequence of Document objects containing HTML content.\n            unwanted_tags: A list of tags to be removed from the HTML.\n            tags_to_extract: A list of tags whose content will be extracted.\n            remove_lines: If set to True, unnecessary lines will be\n            removed from the HTML content.\n        Returns:\n            A sequence of Document objects with transformed content.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/beautiful_soup_transformer.html"}
{"id": "fada79180ef4-1", "text": "Returns:\n            A sequence of Document objects with transformed content.\n        \"\"\"\n        for doc in documents:\n            cleaned_content = doc.page_content\n            cleaned_content = self.remove_unwanted_tags(cleaned_content, unwanted_tags)\n            cleaned_content = self.extract_tags(cleaned_content, tags_to_extract)\n            if remove_lines:\n                cleaned_content = self.remove_unnecessary_lines(cleaned_content)\n            doc.page_content = cleaned_content\n        return documents\n[docs]    @staticmethod\n    def remove_unwanted_tags(html_content: str, unwanted_tags: List[str]) -> str:\n        \"\"\"\n        Remove unwanted tags from a given HTML content.\n        Args:\n            html_content: The original HTML content string.\n            unwanted_tags: A list of tags to be removed from the HTML.\n        Returns:\n            A cleaned HTML string with unwanted tags removed.\n        \"\"\"\n        from bs4 import BeautifulSoup\n        soup = BeautifulSoup(html_content, \"html.parser\")\n        for tag in unwanted_tags:\n            for element in soup.find_all(tag):\n                element.decompose()\n        return str(soup)\n[docs]    @staticmethod\n    def extract_tags(html_content: str, tags: List[str]) -> str:\n        \"\"\"\n        Extract specific tags from a given HTML content.\n        Args:\n            html_content: The original HTML content string.\n            tags: A list of tags to be extracted from the HTML.\n        Returns:\n            A string combining the content of the extracted tags.\n        \"\"\"\n        from bs4 import BeautifulSoup\n        soup = BeautifulSoup(html_content, \"html.parser\")\n        text_parts: List[str] = []\n        for element in soup.find_all():\n            if element.name in tags:\n                # Extract all navigable strings recursively from this element.\n                text_parts += get_navigable_strings(element)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/beautiful_soup_transformer.html"}
{"id": "fada79180ef4-2", "text": "text_parts += get_navigable_strings(element)\n                # To avoid duplicate text, remove all descendants from the soup.\n                element.decompose()\n        return \" \".join(text_parts)\n[docs]    @staticmethod\n    def remove_unnecessary_lines(content: str) -> str:\n        \"\"\"\n        Clean up the content by removing unnecessary lines.\n        Args:\n            content: A string, which may contain unnecessary lines or spaces.\n        Returns:\n            A cleaned string with unnecessary lines removed.\n        \"\"\"\n        lines = content.split(\"\\n\")\n        stripped_lines = [line.strip() for line in lines]\n        non_empty_lines = [line for line in stripped_lines if line]\n        cleaned_content = \" \".join(non_empty_lines)\n        return cleaned_content\n[docs]    async def atransform_documents(\n        self,\n        documents: Sequence[Document],\n        **kwargs: Any,\n    ) -> Sequence[Document]:\n        raise NotImplementedError\n[docs]def get_navigable_strings(element: Any) -> Iterator[str]:\n    from bs4 import NavigableString, Tag\n    for child in cast(Tag, element).children:\n        if isinstance(child, Tag):\n            yield from get_navigable_strings(child)\n        elif isinstance(child, NavigableString):\n            if (element.name == \"a\") and (href := element.get(\"href\")):\n                yield f\"{child.strip()} ({href})\"\n            else:\n                yield child.strip()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/beautiful_soup_transformer.html"}
{"id": "cd232c47fbb9-0", "text": "Source code for langchain.document_transformers.doctran_text_extract\nfrom typing import Any, List, Optional, Sequence\nfrom langchain.schema import BaseDocumentTransformer, Document\nfrom langchain.utils import get_from_env\n[docs]class DoctranPropertyExtractor(BaseDocumentTransformer):\n    \"\"\"Extract properties from text documents using doctran.\n    Arguments:\n        properties: A list of the properties to extract.\n        openai_api_key: OpenAI API key. Can also be specified via environment variable\n            ``OPENAI_API_KEY``.\n    Example:\n        .. code-block:: python\n            from langchain.document_transformers import DoctranPropertyExtractor\n            properties = [\n                {\n                    \"name\": \"category\",\n                    \"description\": \"What type of email this is.\",\n                    \"type\": \"string\",\n                    \"enum\": [\"update\", \"action_item\", \"customer_feedback\", \"announcement\", \"other\"],\n                    \"required\": True,\n                },\n                {\n                    \"name\": \"mentions\",\n                    \"description\": \"A list of all people mentioned in this email.\",\n                    \"type\": \"array\",\n                    \"items\": {\n                        \"name\": \"full_name\",\n                        \"description\": \"The full name of the person mentioned.\",\n                        \"type\": \"string\",\n                    },\n                    \"required\": True,\n                },\n                {\n                    \"name\": \"eli5\",\n                    \"description\": \"Explain this email to me like I'm 5 years old.\",\n                    \"type\": \"string\",\n                    \"required\": True,\n                },\n            ]\n            # Pass in openai_api_key or set env var OPENAI_API_KEY\n            property_extractor = DoctranPropertyExtractor(properties)\n            transformed_document = await qa_transformer.atransform_documents(documents)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_extract.html"}
{"id": "cd232c47fbb9-1", "text": "transformed_document = await qa_transformer.atransform_documents(documents)\n    \"\"\"  # noqa: E501\n[docs]    def __init__(\n        self,\n        properties: List[dict],\n        openai_api_key: Optional[str] = None,\n        openai_api_model: Optional[str] = None,\n    ) -> None:\n        self.properties = properties\n        self.openai_api_key = openai_api_key or get_from_env(\n            \"openai_api_key\", \"OPENAI_API_KEY\"\n        )\n        self.openai_api_model = openai_api_model or get_from_env(\n            \"openai_api_model\", \"OPENAI_API_MODEL\"\n        )\n[docs]    def transform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        raise NotImplementedError\n[docs]    async def atransform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        \"\"\"Extracts properties from text documents using doctran.\"\"\"\n        try:\n            from doctran import Doctran, ExtractProperty\n            doctran = Doctran(\n                openai_api_key=self.openai_api_key, openai_model=self.openai_api_model\n            )\n        except ImportError:\n            raise ImportError(\n                \"Install doctran to use this parser. (pip install doctran)\"\n            )\n        properties = [ExtractProperty(**property) for property in self.properties]\n        for d in documents:\n            doctran_doc = (\n                await doctran.parse(content=d.page_content)\n                .extract(properties=properties)\n                .execute()\n            )\n            d.metadata[\"extracted_properties\"] = doctran_doc.extracted_properties\n        return documents", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_extract.html"}
{"id": "0d189c0a99a1-0", "text": "Source code for langchain.document_transformers.google_translate\nfrom typing import Any, Optional, Sequence\nfrom langchain.schema import BaseDocumentTransformer, Document\nfrom langchain.utilities.vertexai import get_client_info\n[docs]class GoogleTranslateTransformer(BaseDocumentTransformer):\n    \"\"\"Translate text documents using Google Cloud Translation.\"\"\"\n[docs]    def __init__(\n        self,\n        project_id: str,\n        *,\n        location: str = \"global\",\n        model_id: Optional[str] = None,\n        glossary_id: Optional[str] = None,\n        api_endpoint: Optional[str] = None,\n    ) -> None:\n        \"\"\"\n        Arguments:\n            project_id: Google Cloud Project ID.\n            location: (Optional) Translate model location.\n            model_id: (Optional) Translate model ID to use.\n            glossary_id: (Optional) Translate glossary ID to use.\n            api_endpoint: (Optional) Regional endpoint to use.\n        \"\"\"\n        try:\n            from google.api_core.client_options import ClientOptions\n            from google.cloud import translate\n        except ImportError as exc:\n            raise ImportError(\n                \"Install Google Cloud Translate to use this parser.\"\n                \"(pip install google-cloud-translate)\"\n            ) from exc\n        self.project_id = project_id\n        self.location = location\n        self.model_id = model_id\n        self.glossary_id = glossary_id\n        self._client = translate.TranslationServiceClient(\n            client_info=get_client_info(\"translate\"),\n            client_options=(\n                ClientOptions(api_endpoint=api_endpoint) if api_endpoint else None\n            ),\n        )\n        self._parent_path = self._client.common_location_path(project_id, location)\n        # For some reason, there's no `model_path()` method for the client.\n        self._model_path = (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/google_translate.html"}
{"id": "0d189c0a99a1-1", "text": "self._model_path = (\n            f\"{self._parent_path}/models/{model_id}\" if model_id else None\n        )\n        self._glossary_path = (\n            self._client.glossary_path(project_id, location, glossary_id)\n            if glossary_id\n            else None\n        )\n[docs]    def transform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        \"\"\"Translate text documents using Google Translate.\n        Arguments:\n            source_language_code: ISO 639 language code of the input document.\n            target_language_code: ISO 639 language code of the output document.\n                For supported languages, refer to:\n                https://cloud.google.com/translate/docs/languages\n            mime_type: (Optional) Media Type of input text.\n                Options: `text/plain`, `text/html`\n        \"\"\"\n        try:\n            from google.cloud import translate\n        except ImportError as exc:\n            raise ImportError(\n                \"Install Google Cloud Translate to use this parser.\"\n                \"(pip install google-cloud-translate)\"\n            ) from exc\n        response = self._client.translate_text(\n            request=translate.TranslateTextRequest(\n                contents=[doc.page_content for doc in documents],\n                parent=self._parent_path,\n                model=self._model_path,\n                glossary_config=translate.TranslateTextGlossaryConfig(\n                    glossary=self._glossary_path\n                ),\n                source_language_code=kwargs.get(\"source_language_code\", None),\n                target_language_code=kwargs.get(\"target_language_code\"),\n                mime_type=kwargs.get(\"mime_type\", \"text/plain\"),\n            )\n        )\n        # If using a glossary, the translations will be in `glossary_translations`.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/google_translate.html"}
{"id": "0d189c0a99a1-2", "text": "translations = response.glossary_translations or response.translations\n        return [\n            Document(\n                page_content=translation.translated_text,\n                metadata={\n                    **doc.metadata,\n                    \"model\": translation.model,\n                    \"detected_language_code\": translation.detected_language_code,\n                },\n            )\n            for doc, translation in zip(documents, translations)\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/google_translate.html"}
{"id": "7769ffb5208b-0", "text": "Source code for langchain.document_transformers.html2text\nfrom typing import Any, Sequence\nfrom langchain.schema import BaseDocumentTransformer, Document\n[docs]class Html2TextTransformer(BaseDocumentTransformer):\n    \"\"\"Replace occurrences of a particular search pattern with a replacement string\n    Arguments:\n        ignore_links: Whether links should be ignored; defaults to True.\n        ignore_images: Whether images should be ignored; defaults to True.\n    Example:\n        .. code-block:: python\n            from langchain.document_transformers import Html2TextTransformer\n            html2text = Html2TextTransformer()\n            docs_transform = html2text.transform_documents(docs)\n    \"\"\"\n[docs]    def __init__(self, ignore_links: bool = True, ignore_images: bool = True) -> None:\n        self.ignore_links = ignore_links\n        self.ignore_images = ignore_images\n[docs]    def transform_documents(\n        self,\n        documents: Sequence[Document],\n        **kwargs: Any,\n    ) -> Sequence[Document]:\n        try:\n            import html2text\n        except ImportError:\n            raise ImportError(\n                \"\"\"html2text package not found, please \n                install it with `pip install html2text`\"\"\"\n            )\n        # Create a html2text.HTML2Text object and override some properties\n        h = html2text.HTML2Text()\n        h.ignore_links = self.ignore_links\n        h.ignore_images = self.ignore_images\n        for d in documents:\n            d.page_content = h.handle(d.page_content)\n        return documents\n[docs]    async def atransform_documents(\n        self,\n        documents: Sequence[Document],\n        **kwargs: Any,\n    ) -> Sequence[Document]:\n        raise NotImplementedError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/html2text.html"}
{"id": "fc7869759580-0", "text": "Source code for langchain.document_transformers.doctran_text_qa\nfrom typing import Any, Optional, Sequence\nfrom langchain.schema import BaseDocumentTransformer, Document\nfrom langchain.utils import get_from_env\n[docs]class DoctranQATransformer(BaseDocumentTransformer):\n    \"\"\"Extract QA from text documents using doctran.\n    Arguments:\n        openai_api_key: OpenAI API key. Can also be specified via environment variable\n            ``OPENAI_API_KEY``.\n    Example:\n        .. code-block:: python\n            from langchain.document_transformers import DoctranQATransformer\n            # Pass in openai_api_key or set env var OPENAI_API_KEY\n            qa_transformer = DoctranQATransformer()\n            transformed_document = await qa_transformer.atransform_documents(documents)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        openai_api_key: Optional[str] = None,\n        openai_api_model: Optional[str] = None,\n    ) -> None:\n        self.openai_api_key = openai_api_key or get_from_env(\n            \"openai_api_key\", \"OPENAI_API_KEY\"\n        )\n        self.openai_api_model = openai_api_model or get_from_env(\n            \"openai_api_model\", \"OPENAI_API_MODEL\"\n        )\n[docs]    def transform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        raise NotImplementedError\n[docs]    async def atransform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        \"\"\"Extracts QA from text documents using doctran.\"\"\"\n        try:\n            from doctran import Doctran\n            doctran = Doctran(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_qa.html"}
{"id": "fc7869759580-1", "text": "from doctran import Doctran\n            doctran = Doctran(\n                openai_api_key=self.openai_api_key, openai_model=self.openai_api_model\n            )\n        except ImportError:\n            raise ImportError(\n                \"Install doctran to use this parser. (pip install doctran)\"\n            )\n        for d in documents:\n            doctran_doc = (\n                await doctran.parse(content=d.page_content).interrogate().execute()\n            )\n            questions_and_answers = doctran_doc.extracted_properties.get(\n                \"questions_and_answers\"\n            )\n            d.metadata[\"questions_and_answers\"] = questions_and_answers\n        return documents", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_qa.html"}
{"id": "331b42cec089-0", "text": "Source code for langchain.document_transformers.openai_functions\n\"\"\"Document transformers that use OpenAI Functions models\"\"\"\nfrom typing import Any, Dict, Optional, Sequence, Type, Union\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.openai_functions import create_tagging_chain\nfrom langchain.prompts import ChatPromptTemplate\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema import BaseDocumentTransformer, Document\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class OpenAIMetadataTagger(BaseDocumentTransformer, BaseModel):\n    \"\"\"Extract metadata tags from document contents using OpenAI functions.\n    Example:\n        .. code-block:: python\n                from langchain.chat_models import ChatOpenAI\n                from langchain.document_transformers import OpenAIMetadataTagger\n                from langchain.schema import Document\n                schema = {\n                    \"properties\": {\n                        \"movie_title\": { \"type\": \"string\" },\n                        \"critic\": { \"type\": \"string\" },\n                        \"tone\": {\n                            \"type\": \"string\",\n                            \"enum\": [\"positive\", \"negative\"]\n                        },\n                        \"rating\": {\n                            \"type\": \"integer\",\n                            \"description\": \"The number of stars the critic rated the movie\"\n                        }\n                    },\n                    \"required\": [\"movie_title\", \"critic\", \"tone\"]\n                }\n                # Must be an OpenAI model that supports functions\n                llm = ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-0613\")\n                tagging_chain = create_tagging_chain(schema, llm)\n                document_transformer = OpenAIMetadataTagger(tagging_chain=tagging_chain)\n                original_documents = [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html"}
{"id": "331b42cec089-1", "text": "original_documents = [\n                    Document(page_content=\"Review of The Bee Movie\\nBy Roger Ebert\\n\\nThis is the greatest movie ever made. 4 out of 5 stars.\"),\n                    Document(page_content=\"Review of The Godfather\\nBy Anonymous\\n\\nThis movie was super boring. 1 out of 5 stars.\", metadata={\"reliable\": False}),\n                ]\n                enhanced_documents = document_transformer.transform_documents(original_documents)\n    \"\"\"  # noqa: E501\n    tagging_chain: LLMChain\n    \"\"\"The chain used to extract metadata from each document.\"\"\"\n[docs]    def transform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        \"\"\"Automatically extract and populate metadata\n        for each document according to the provided schema.\"\"\"\n        new_documents = []\n        for document in documents:\n            extracted_metadata: Dict = self.tagging_chain.run(document.page_content)  # type: ignore[assignment]  # noqa: E501\n            new_document = Document(\n                page_content=document.page_content,\n                metadata={**extracted_metadata, **document.metadata},\n            )\n            new_documents.append(new_document)\n        return new_documents\n[docs]    async def atransform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        raise NotImplementedError\n[docs]def create_metadata_tagger(\n    metadata_schema: Union[Dict[str, Any], Type[BaseModel]],\n    llm: BaseLanguageModel,\n    prompt: Optional[ChatPromptTemplate] = None,\n    *,\n    tagging_chain_kwargs: Optional[Dict] = None,\n) -> OpenAIMetadataTagger:\n    \"\"\"Create a DocumentTransformer that uses an OpenAI function chain to automatically", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html"}
{"id": "331b42cec089-2", "text": "\"\"\"Create a DocumentTransformer that uses an OpenAI function chain to automatically\n        tag documents with metadata based on their content and an input schema.\n    Args:\n        metadata_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary\n            is passed in, it's assumed to already be a valid JsonSchema.\n            For best results, pydantic.BaseModels should have docstrings describing what\n            the schema represents and descriptions for the parameters.\n        llm: Language model to use, assumed to support the OpenAI function-calling API.\n            Defaults to use \"gpt-3.5-turbo-0613\"\n        prompt: BasePromptTemplate to pass to the model.\n    Returns:\n        An LLMChain that will pass the given function to the model.\n    Example:\n        .. code-block:: python\n                from langchain.chat_models import ChatOpenAI\n                from langchain.document_transformers import create_metadata_tagger\n                from langchain.schema import Document\n                schema = {\n                    \"properties\": {\n                        \"movie_title\": { \"type\": \"string\" },\n                        \"critic\": { \"type\": \"string\" },\n                        \"tone\": {\n                            \"type\": \"string\",\n                            \"enum\": [\"positive\", \"negative\"]\n                        },\n                        \"rating\": {\n                            \"type\": \"integer\",\n                            \"description\": \"The number of stars the critic rated the movie\"\n                        }\n                    },\n                    \"required\": [\"movie_title\", \"critic\", \"tone\"]\n                }\n                # Must be an OpenAI model that supports functions\n                llm = ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-0613\")\n                document_transformer = create_metadata_tagger(schema, llm)\n                original_documents = [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html"}
{"id": "331b42cec089-3", "text": "original_documents = [\n                    Document(page_content=\"Review of The Bee Movie\\nBy Roger Ebert\\n\\nThis is the greatest movie ever made. 4 out of 5 stars.\"),\n                    Document(page_content=\"Review of The Godfather\\nBy Anonymous\\n\\nThis movie was super boring. 1 out of 5 stars.\", metadata={\"reliable\": False}),\n                ]\n                enhanced_documents = document_transformer.transform_documents(original_documents)\n    \"\"\"  # noqa: E501\n    metadata_schema = (\n        metadata_schema\n        if isinstance(metadata_schema, dict)\n        else metadata_schema.schema()\n    )\n    _tagging_chain_kwargs = tagging_chain_kwargs or {}\n    tagging_chain = create_tagging_chain(\n        metadata_schema, llm, prompt=prompt, **_tagging_chain_kwargs\n    )\n    return OpenAIMetadataTagger(tagging_chain=tagging_chain)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html"}
{"id": "7c0758e80d18-0", "text": "Source code for langchain.document_transformers.doctran_text_translate\nfrom typing import Any, Optional, Sequence\nfrom langchain.schema import BaseDocumentTransformer, Document\nfrom langchain.utils import get_from_env\n[docs]class DoctranTextTranslator(BaseDocumentTransformer):\n    \"\"\"Translate text documents using doctran.\n    Arguments:\n        openai_api_key: OpenAI API key. Can also be specified via environment variable\n        ``OPENAI_API_KEY``.\n        language: The language to translate *to*.\n    Example:\n        .. code-block:: python\n        from langchain.document_transformers import DoctranTextTranslator\n        # Pass in openai_api_key or set env var OPENAI_API_KEY\n        qa_translator = DoctranTextTranslator(language=\"spanish\")\n        translated_document = await qa_translator.atransform_documents(documents)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        openai_api_key: Optional[str] = None,\n        language: str = \"english\",\n        openai_api_model: Optional[str] = None,\n    ) -> None:\n        self.openai_api_key = openai_api_key or get_from_env(\n            \"openai_api_key\", \"OPENAI_API_KEY\"\n        )\n        self.openai_api_model = openai_api_model or get_from_env(\n            \"openai_api_model\", \"OPENAI_API_MODEL\"\n        )\n        self.language = language\n[docs]    def transform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        raise NotImplementedError\n[docs]    async def atransform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        \"\"\"Translates text documents using doctran.\"\"\"\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_translate.html"}
{"id": "7c0758e80d18-1", "text": "\"\"\"Translates text documents using doctran.\"\"\"\n        try:\n            from doctran import Doctran\n            doctran = Doctran(\n                openai_api_key=self.openai_api_key, openai_model=self.openai_api_model\n            )\n        except ImportError:\n            raise ImportError(\n                \"Install doctran to use this parser. (pip install doctran)\"\n            )\n        doctran_docs = [\n            doctran.parse(content=doc.page_content, metadata=doc.metadata)\n            for doc in documents\n        ]\n        for i, doc in enumerate(doctran_docs):\n            doctran_docs[i] = await doc.translate(language=self.language).execute()\n        return [\n            Document(page_content=doc.transformed_content, metadata=doc.metadata)\n            for doc in doctran_docs\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_translate.html"}
{"id": "8d069e10b077-0", "text": "Source code for langchain.memory.token_buffer\nfrom typing import Any, Dict, List\nfrom langchain.memory.chat_memory import BaseChatMemory\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import BaseMessage, get_buffer_string\n[docs]class ConversationTokenBufferMemory(BaseChatMemory):\n    \"\"\"Conversation chat memory with token limit.\"\"\"\n    human_prefix: str = \"Human\"\n    ai_prefix: str = \"AI\"\n    llm: BaseLanguageModel\n    memory_key: str = \"history\"\n    max_token_limit: int = 2000\n    @property\n    def buffer(self) -> Any:\n        \"\"\"String buffer of memory.\"\"\"\n        return self.buffer_as_messages if self.return_messages else self.buffer_as_str\n    @property\n    def buffer_as_str(self) -> str:\n        \"\"\"Exposes the buffer as a string in case return_messages is False.\"\"\"\n        return get_buffer_string(\n            self.chat_memory.messages,\n            human_prefix=self.human_prefix,\n            ai_prefix=self.ai_prefix,\n        )\n    @property\n    def buffer_as_messages(self) -> List[BaseMessage]:\n        \"\"\"Exposes the buffer as a list of messages in case return_messages is True.\"\"\"\n        return self.chat_memory.messages\n    @property\n    def memory_variables(self) -> List[str]:\n        \"\"\"Will always return list of memory variables.\n        :meta private:\n        \"\"\"\n        return [self.memory_key]\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Return history buffer.\"\"\"\n        return {self.memory_key: self.buffer}\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        \"\"\"Save context from this conversation to buffer. Pruned.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html"}
{"id": "8d069e10b077-1", "text": "\"\"\"Save context from this conversation to buffer. Pruned.\"\"\"\n        super().save_context(inputs, outputs)\n        # Prune buffer if it exceeds max token limit\n        buffer = self.chat_memory.messages\n        curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)\n        if curr_buffer_length > self.max_token_limit:\n            pruned_memory = []\n            while curr_buffer_length > self.max_token_limit:\n                pruned_memory.append(buffer.pop(0))\n                curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html"}
{"id": "bd3551500197-0", "text": "Source code for langchain.memory.entity\nimport logging\nfrom abc import ABC, abstractmethod\nfrom itertools import islice\nfrom typing import Any, Dict, Iterable, List, Optional\nfrom langchain.chains.llm import LLMChain\nfrom langchain.memory.chat_memory import BaseChatMemory\nfrom langchain.memory.prompt import (\n    ENTITY_EXTRACTION_PROMPT,\n    ENTITY_SUMMARIZATION_PROMPT,\n)\nfrom langchain.memory.utils import get_prompt_input_key\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import BaseMessage, get_buffer_string\nfrom langchain.utilities.redis import get_client\nlogger = logging.getLogger(__name__)\n[docs]class BaseEntityStore(BaseModel, ABC):\n    \"\"\"Abstract base class for Entity store.\"\"\"\n[docs]    @abstractmethod\n    def get(self, key: str, default: Optional[str] = None) -> Optional[str]:\n        \"\"\"Get entity value from store.\"\"\"\n        pass\n[docs]    @abstractmethod\n    def set(self, key: str, value: Optional[str]) -> None:\n        \"\"\"Set entity value in store.\"\"\"\n        pass\n[docs]    @abstractmethod\n    def delete(self, key: str) -> None:\n        \"\"\"Delete entity value from store.\"\"\"\n        pass\n[docs]    @abstractmethod\n    def exists(self, key: str) -> bool:\n        \"\"\"Check if entity exists in store.\"\"\"\n        pass\n[docs]    @abstractmethod\n    def clear(self) -> None:\n        \"\"\"Delete all entities from store.\"\"\"\n        pass\n[docs]class InMemoryEntityStore(BaseEntityStore):\n    \"\"\"In-memory Entity store.\"\"\"\n    store: Dict[str, Optional[str]] = {}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html"}
{"id": "bd3551500197-1", "text": "\"\"\"In-memory Entity store.\"\"\"\n    store: Dict[str, Optional[str]] = {}\n[docs]    def get(self, key: str, default: Optional[str] = None) -> Optional[str]:\n        return self.store.get(key, default)\n[docs]    def set(self, key: str, value: Optional[str]) -> None:\n        self.store[key] = value\n[docs]    def delete(self, key: str) -> None:\n        del self.store[key]\n[docs]    def exists(self, key: str) -> bool:\n        return key in self.store\n[docs]    def clear(self) -> None:\n        return self.store.clear()\n[docs]class UpstashRedisEntityStore(BaseEntityStore):\n    \"\"\"Upstash Redis backed Entity store.\n    Entities get a TTL of 1 day by default, and\n    that TTL is extended by 3 days every time the entity is read back.\n    \"\"\"\n    def __init__(\n        self,\n        session_id: str = \"default\",\n        url: str = \"\",\n        token: str = \"\",\n        key_prefix: str = \"memory_store\",\n        ttl: Optional[int] = 60 * 60 * 24,\n        recall_ttl: Optional[int] = 60 * 60 * 24 * 3,\n        *args: Any,\n        **kwargs: Any,\n    ):\n        try:\n            from upstash_redis import Redis\n        except ImportError:\n            raise ImportError(\n                \"Could not import upstash_redis python package. \"\n                \"Please install it with `pip install upstash_redis`.\"\n            )\n        super().__init__(*args, **kwargs)\n        try:\n            self.redis_client = Redis(url=url, token=token)\n        except Exception:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html"}
{"id": "bd3551500197-2", "text": "self.redis_client = Redis(url=url, token=token)\n        except Exception:\n            logger.error(\"Upstash Redis instance could not be initiated.\")\n        self.session_id = session_id\n        self.key_prefix = key_prefix\n        self.ttl = ttl\n        self.recall_ttl = recall_ttl or ttl\n    @property\n    def full_key_prefix(self) -> str:\n        return f\"{self.key_prefix}:{self.session_id}\"\n[docs]    def get(self, key: str, default: Optional[str] = None) -> Optional[str]:\n        res = (\n            self.redis_client.getex(f\"{self.full_key_prefix}:{key}\", ex=self.recall_ttl)\n            or default\n            or \"\"\n        )\n        logger.debug(f\"Upstash Redis MEM get '{self.full_key_prefix}:{key}': '{res}'\")\n        return res\n[docs]    def set(self, key: str, value: Optional[str]) -> None:\n        if not value:\n            return self.delete(key)\n        self.redis_client.set(f\"{self.full_key_prefix}:{key}\", value, ex=self.ttl)\n        logger.debug(\n            f\"Redis MEM set '{self.full_key_prefix}:{key}': '{value}' EX {self.ttl}\"\n        )\n[docs]    def delete(self, key: str) -> None:\n        self.redis_client.delete(f\"{self.full_key_prefix}:{key}\")\n[docs]    def exists(self, key: str) -> bool:\n        return self.redis_client.exists(f\"{self.full_key_prefix}:{key}\") == 1\n[docs]    def clear(self) -> None:\n        def scan_and_delete(cursor: int) -> int:\n            cursor, keys_to_delete = self.redis_client.scan(\n                cursor, f\"{self.full_key_prefix}:*\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html"}
{"id": "bd3551500197-3", "text": "cursor, f\"{self.full_key_prefix}:*\"\n            )\n            self.redis_client.delete(*keys_to_delete)\n            return cursor\n        cursor = scan_and_delete(0)\n        while cursor != 0:\n            scan_and_delete(cursor)\n[docs]class RedisEntityStore(BaseEntityStore):\n    \"\"\"Redis-backed Entity store.\n    Entities get a TTL of 1 day by default, and\n    that TTL is extended by 3 days every time the entity is read back.\n    \"\"\"\n    redis_client: Any\n    session_id: str = \"default\"\n    key_prefix: str = \"memory_store\"\n    ttl: Optional[int] = 60 * 60 * 24\n    recall_ttl: Optional[int] = 60 * 60 * 24 * 3\n    def __init__(\n        self,\n        session_id: str = \"default\",\n        url: str = \"redis://localhost:6379/0\",\n        key_prefix: str = \"memory_store\",\n        ttl: Optional[int] = 60 * 60 * 24,\n        recall_ttl: Optional[int] = 60 * 60 * 24 * 3,\n        *args: Any,\n        **kwargs: Any,\n    ):\n        try:\n            import redis\n        except ImportError:\n            raise ImportError(\n                \"Could not import redis python package. \"\n                \"Please install it with `pip install redis`.\"\n            )\n        super().__init__(*args, **kwargs)\n        try:\n            self.redis_client = get_client(redis_url=url, decode_responses=True)\n        except redis.exceptions.ConnectionError as error:\n            logger.error(error)\n        self.session_id = session_id\n        self.key_prefix = key_prefix\n        self.ttl = ttl", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html"}
{"id": "bd3551500197-4", "text": "self.key_prefix = key_prefix\n        self.ttl = ttl\n        self.recall_ttl = recall_ttl or ttl\n    @property\n    def full_key_prefix(self) -> str:\n        return f\"{self.key_prefix}:{self.session_id}\"\n[docs]    def get(self, key: str, default: Optional[str] = None) -> Optional[str]:\n        res = (\n            self.redis_client.getex(f\"{self.full_key_prefix}:{key}\", ex=self.recall_ttl)\n            or default\n            or \"\"\n        )\n        logger.debug(f\"REDIS MEM get '{self.full_key_prefix}:{key}': '{res}'\")\n        return res\n[docs]    def set(self, key: str, value: Optional[str]) -> None:\n        if not value:\n            return self.delete(key)\n        self.redis_client.set(f\"{self.full_key_prefix}:{key}\", value, ex=self.ttl)\n        logger.debug(\n            f\"REDIS MEM set '{self.full_key_prefix}:{key}': '{value}' EX {self.ttl}\"\n        )\n[docs]    def delete(self, key: str) -> None:\n        self.redis_client.delete(f\"{self.full_key_prefix}:{key}\")\n[docs]    def exists(self, key: str) -> bool:\n        return self.redis_client.exists(f\"{self.full_key_prefix}:{key}\") == 1\n[docs]    def clear(self) -> None:\n        # iterate a list in batches of size batch_size\n        def batched(iterable: Iterable[Any], batch_size: int) -> Iterable[Any]:\n            iterator = iter(iterable)\n            while batch := list(islice(iterator, batch_size)):\n                yield batch\n        for keybatch in batched(\n            self.redis_client.scan_iter(f\"{self.full_key_prefix}:*\"), 500\n        ):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html"}
{"id": "bd3551500197-5", "text": "):\n            self.redis_client.delete(*keybatch)\n[docs]class SQLiteEntityStore(BaseEntityStore):\n    \"\"\"SQLite-backed Entity store\"\"\"\n    session_id: str = \"default\"\n    table_name: str = \"memory_store\"\n    def __init__(\n        self,\n        session_id: str = \"default\",\n        db_file: str = \"entities.db\",\n        table_name: str = \"memory_store\",\n        *args: Any,\n        **kwargs: Any,\n    ):\n        try:\n            import sqlite3\n        except ImportError:\n            raise ImportError(\n                \"Could not import sqlite3 python package. \"\n                \"Please install it with `pip install sqlite3`.\"\n            )\n        super().__init__(*args, **kwargs)\n        self.conn = sqlite3.connect(db_file)\n        self.session_id = session_id\n        self.table_name = table_name\n        self._create_table_if_not_exists()\n    @property\n    def full_table_name(self) -> str:\n        return f\"{self.table_name}_{self.session_id}\"\n    def _create_table_if_not_exists(self) -> None:\n        create_table_query = f\"\"\"\n            CREATE TABLE IF NOT EXISTS {self.full_table_name} (\n                key TEXT PRIMARY KEY,\n                value TEXT\n            )\n        \"\"\"\n        with self.conn:\n            self.conn.execute(create_table_query)\n[docs]    def get(self, key: str, default: Optional[str] = None) -> Optional[str]:\n        query = f\"\"\"\n            SELECT value\n            FROM {self.full_table_name}\n            WHERE key = ?\n        \"\"\"\n        cursor = self.conn.execute(query, (key,))\n        result = cursor.fetchone()\n        if result is not None:\n            value = result[0]\n            return value", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html"}
{"id": "bd3551500197-6", "text": "if result is not None:\n            value = result[0]\n            return value\n        return default\n[docs]    def set(self, key: str, value: Optional[str]) -> None:\n        if not value:\n            return self.delete(key)\n        query = f\"\"\"\n            INSERT OR REPLACE INTO {self.full_table_name} (key, value)\n            VALUES (?, ?)\n        \"\"\"\n        with self.conn:\n            self.conn.execute(query, (key, value))\n[docs]    def delete(self, key: str) -> None:\n        query = f\"\"\"\n            DELETE FROM {self.full_table_name}\n            WHERE key = ?\n        \"\"\"\n        with self.conn:\n            self.conn.execute(query, (key,))\n[docs]    def exists(self, key: str) -> bool:\n        query = f\"\"\"\n            SELECT 1\n            FROM {self.full_table_name}\n            WHERE key = ?\n            LIMIT 1\n        \"\"\"\n        cursor = self.conn.execute(query, (key,))\n        result = cursor.fetchone()\n        return result is not None\n[docs]    def clear(self) -> None:\n        query = f\"\"\"\n            DELETE FROM {self.full_table_name}\n        \"\"\"\n        with self.conn:\n            self.conn.execute(query)\n[docs]class ConversationEntityMemory(BaseChatMemory):\n    \"\"\"Entity extractor & summarizer memory.\n    Extracts named entities from the recent chat history and generates summaries.\n    With a swappable entity store, persisting entities across conversations.\n    Defaults to an in-memory entity store, and can be swapped out for a Redis,\n    SQLite, or other entity store.\n    \"\"\"\n    human_prefix: str = \"Human\"\n    ai_prefix: str = \"AI\"\n    llm: BaseLanguageModel", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html"}
{"id": "bd3551500197-7", "text": "ai_prefix: str = \"AI\"\n    llm: BaseLanguageModel\n    entity_extraction_prompt: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT\n    entity_summarization_prompt: BasePromptTemplate = ENTITY_SUMMARIZATION_PROMPT\n    # Cache of recently detected entity names, if any\n    # It is updated when load_memory_variables is called:\n    entity_cache: List[str] = []\n    # Number of recent message pairs to consider when updating entities:\n    k: int = 3\n    chat_history_key: str = \"history\"\n    # Store to manage entity-related data:\n    entity_store: BaseEntityStore = Field(default_factory=InMemoryEntityStore)\n    @property\n    def buffer(self) -> List[BaseMessage]:\n        \"\"\"Access chat memory messages.\"\"\"\n        return self.chat_memory.messages\n    @property\n    def memory_variables(self) -> List[str]:\n        \"\"\"Will always return list of memory variables.\n        :meta private:\n        \"\"\"\n        return [\"entities\", self.chat_history_key]\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"\n        Returns chat history and all generated entities with summaries if available,\n        and updates or clears the recent entity cache.\n        New entity name can be found when calling this method, before the entity\n        summaries are generated, so the entity cache values may be empty if no entity\n        descriptions are generated yet.\n        \"\"\"\n        # Create an LLMChain for predicting entity names from the recent chat history:\n        chain = LLMChain(llm=self.llm, prompt=self.entity_extraction_prompt)\n        if self.input_key is None:\n            prompt_input_key = get_prompt_input_key(inputs, self.memory_variables)\n        else:\n            prompt_input_key = self.input_key", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html"}
{"id": "bd3551500197-8", "text": "else:\n            prompt_input_key = self.input_key\n        # Extract an arbitrary window of the last message pairs from\n        # the chat history, where the hyperparameter k is the\n        # number of message pairs:\n        buffer_string = get_buffer_string(\n            self.buffer[-self.k * 2 :],\n            human_prefix=self.human_prefix,\n            ai_prefix=self.ai_prefix,\n        )\n        # Generates a comma-separated list of named entities,\n        # e.g. \"Jane, White House, UFO\"\n        # or \"NONE\" if no named entities are extracted:\n        output = chain.predict(\n            history=buffer_string,\n            input=inputs[prompt_input_key],\n        )\n        # If no named entities are extracted, assigns an empty list.\n        if output.strip() == \"NONE\":\n            entities = []\n        else:\n            # Make a list of the extracted entities:\n            entities = [w.strip() for w in output.split(\",\")]\n        # Make a dictionary of entities with summary if exists:\n        entity_summaries = {}\n        for entity in entities:\n            entity_summaries[entity] = self.entity_store.get(entity, \"\")\n        # Replaces the entity name cache with the most recently discussed entities,\n        # or if no entities were extracted, clears the cache:\n        self.entity_cache = entities\n        # Should we return as message objects or as a string?\n        if self.return_messages:\n            # Get last `k` pair of chat messages:\n            buffer: Any = self.buffer[-self.k * 2 :]\n        else:\n            # Reuse the string we made earlier:\n            buffer = buffer_string\n        return {\n            self.chat_history_key: buffer,\n            \"entities\": entity_summaries,\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html"}
{"id": "bd3551500197-9", "text": "\"entities\": entity_summaries,\n        }\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        \"\"\"\n        Save context from this conversation history to the entity store.\n        Generates a summary for each entity in the entity cache by prompting\n        the model, and saves these summaries to the entity store.\n        \"\"\"\n        super().save_context(inputs, outputs)\n        if self.input_key is None:\n            prompt_input_key = get_prompt_input_key(inputs, self.memory_variables)\n        else:\n            prompt_input_key = self.input_key\n        # Extract an arbitrary window of the last message pairs from\n        # the chat history, where the hyperparameter k is the\n        # number of message pairs:\n        buffer_string = get_buffer_string(\n            self.buffer[-self.k * 2 :],\n            human_prefix=self.human_prefix,\n            ai_prefix=self.ai_prefix,\n        )\n        input_data = inputs[prompt_input_key]\n        # Create an LLMChain for predicting entity summarization from the context\n        chain = LLMChain(llm=self.llm, prompt=self.entity_summarization_prompt)\n        # Generate new summaries for entities and save them in the entity store\n        for entity in self.entity_cache:\n            # Get existing summary if it exists\n            existing_summary = self.entity_store.get(entity, \"\")\n            output = chain.predict(\n                summary=existing_summary,\n                entity=entity,\n                history=buffer_string,\n                input=input_data,\n            )\n            # Save the updated summary to the entity store\n            self.entity_store.set(entity, output.strip())\n[docs]    def clear(self) -> None:\n        \"\"\"Clear memory contents.\"\"\"\n        self.chat_memory.clear()\n        self.entity_cache.clear()\n        self.entity_store.clear()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html"}
{"id": "8a5b247e50d6-0", "text": "Source code for langchain.memory.simple\nfrom typing import Any, Dict, List\nfrom langchain.schema import BaseMemory\n[docs]class SimpleMemory(BaseMemory):\n    \"\"\"Simple memory for storing context or other information that shouldn't\n    ever change between prompts.\n    \"\"\"\n    memories: Dict[str, Any] = dict()\n    @property\n    def memory_variables(self) -> List[str]:\n        return list(self.memories.keys())\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:\n        return self.memories\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        \"\"\"Nothing should be saved or changed, my memory is set in stone.\"\"\"\n        pass\n[docs]    def clear(self) -> None:\n        \"\"\"Nothing to clear, got a memory like a vault.\"\"\"\n        pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/simple.html"}
{"id": "7c80949d99b0-0", "text": "Source code for langchain.memory.chat_memory\nfrom abc import ABC\nfrom typing import Any, Dict, Optional, Tuple\nfrom langchain.memory.chat_message_histories.in_memory import ChatMessageHistory\nfrom langchain.memory.utils import get_prompt_input_key\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BaseChatMessageHistory, BaseMemory\n[docs]class BaseChatMemory(BaseMemory, ABC):\n    \"\"\"Abstract base class for chat memory.\"\"\"\n    chat_memory: BaseChatMessageHistory = Field(default_factory=ChatMessageHistory)\n    output_key: Optional[str] = None\n    input_key: Optional[str] = None\n    return_messages: bool = False\n    def _get_input_output(\n        self, inputs: Dict[str, Any], outputs: Dict[str, str]\n    ) -> Tuple[str, str]:\n        if self.input_key is None:\n            prompt_input_key = get_prompt_input_key(inputs, self.memory_variables)\n        else:\n            prompt_input_key = self.input_key\n        if self.output_key is None:\n            if len(outputs) != 1:\n                raise ValueError(f\"One output key expected, got {outputs.keys()}\")\n            output_key = list(outputs.keys())[0]\n        else:\n            output_key = self.output_key\n        return inputs[prompt_input_key], outputs[output_key]\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        \"\"\"Save context from this conversation to buffer.\"\"\"\n        input_str, output_str = self._get_input_output(inputs, outputs)\n        self.chat_memory.add_user_message(input_str)\n        self.chat_memory.add_ai_message(output_str)\n[docs]    def clear(self) -> None:\n        \"\"\"Clear memory contents.\"\"\"\n        self.chat_memory.clear()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_memory.html"}
{"id": "797e9345f538-0", "text": "Source code for langchain.memory.vectorstore\n\"\"\"Class for a VectorStore-backed memory object.\"\"\"\nfrom typing import Any, Dict, List, Optional, Sequence, Union\nfrom langchain.memory.chat_memory import BaseMemory\nfrom langchain.memory.utils import get_prompt_input_key\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import Document\nfrom langchain.schema.vectorstore import VectorStoreRetriever\n[docs]class VectorStoreRetrieverMemory(BaseMemory):\n    \"\"\"VectorStoreRetriever-backed memory.\"\"\"\n    retriever: VectorStoreRetriever = Field(exclude=True)\n    \"\"\"VectorStoreRetriever object to connect to.\"\"\"\n    memory_key: str = \"history\"  #: :meta private:\n    \"\"\"Key name to locate the memories in the result of load_memory_variables.\"\"\"\n    input_key: Optional[str] = None\n    \"\"\"Key name to index the inputs to load_memory_variables.\"\"\"\n    return_docs: bool = False\n    \"\"\"Whether or not to return the result of querying the database directly.\"\"\"\n    exclude_input_keys: Sequence[str] = Field(default_factory=tuple)\n    \"\"\"Input keys to exclude in addition to memory key when constructing the document\"\"\"\n    @property\n    def memory_variables(self) -> List[str]:\n        \"\"\"The list of keys emitted from the load_memory_variables method.\"\"\"\n        return [self.memory_key]\n    def _get_prompt_input_key(self, inputs: Dict[str, Any]) -> str:\n        \"\"\"Get the input key for the prompt.\"\"\"\n        if self.input_key is None:\n            return get_prompt_input_key(inputs, self.memory_variables)\n        return self.input_key\n[docs]    def load_memory_variables(\n        self, inputs: Dict[str, Any]\n    ) -> Dict[str, Union[List[Document], str]]:\n        \"\"\"Return history buffer.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html"}
{"id": "797e9345f538-1", "text": "\"\"\"Return history buffer.\"\"\"\n        input_key = self._get_prompt_input_key(inputs)\n        query = inputs[input_key]\n        docs = self.retriever.get_relevant_documents(query)\n        result: Union[List[Document], str]\n        if not self.return_docs:\n            result = \"\\n\".join([doc.page_content for doc in docs])\n        else:\n            result = docs\n        return {self.memory_key: result}\n    def _form_documents(\n        self, inputs: Dict[str, Any], outputs: Dict[str, str]\n    ) -> List[Document]:\n        \"\"\"Format context from this conversation to buffer.\"\"\"\n        # Each document should only include the current turn, not the chat history\n        exclude = set(self.exclude_input_keys)\n        exclude.add(self.memory_key)\n        filtered_inputs = {k: v for k, v in inputs.items() if k not in exclude}\n        texts = [\n            f\"{k}: {v}\"\n            for k, v in list(filtered_inputs.items()) + list(outputs.items())\n        ]\n        page_content = \"\\n\".join(texts)\n        return [Document(page_content=page_content)]\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        \"\"\"Save context from this conversation to buffer.\"\"\"\n        documents = self._form_documents(inputs, outputs)\n        self.retriever.add_documents(documents)\n[docs]    def clear(self) -> None:\n        \"\"\"Nothing to clear.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html"}
{"id": "f56858e40ec3-0", "text": "Source code for langchain.memory.utils\nfrom typing import Any, Dict, List\n[docs]def get_prompt_input_key(inputs: Dict[str, Any], memory_variables: List[str]) -> str:\n    \"\"\"\n    Get the prompt input key.\n    Args:\n        inputs: Dict[str, Any]\n        memory_variables: List[str]\n    Returns:\n        A prompt input key.\n    \"\"\"\n    # \"stop\" is a special key that can be passed as input but is not used to\n    # format the prompt.\n    prompt_input_keys = list(set(inputs).difference(memory_variables + [\"stop\"]))\n    if len(prompt_input_keys) != 1:\n        raise ValueError(f\"One input key expected got {prompt_input_keys}\")\n    return prompt_input_keys[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/utils.html"}
{"id": "348e0ddcc6d9-0", "text": "Source code for langchain.memory.kg\nfrom typing import Any, Dict, List, Type, Union\nfrom langchain.chains.llm import LLMChain\nfrom langchain.graphs import NetworkxEntityGraph\nfrom langchain.graphs.networkx_graph import KnowledgeTriple, get_entities, parse_triples\nfrom langchain.memory.chat_memory import BaseChatMemory\nfrom langchain.memory.prompt import (\n    ENTITY_EXTRACTION_PROMPT,\n    KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT,\n)\nfrom langchain.memory.utils import get_prompt_input_key\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import BaseMessage, SystemMessage, get_buffer_string\n[docs]class ConversationKGMemory(BaseChatMemory):\n    \"\"\"Knowledge graph conversation memory.\n    Integrates with external knowledge graph to store and retrieve\n    information about knowledge triples in the conversation.\n    \"\"\"\n    k: int = 2\n    human_prefix: str = \"Human\"\n    ai_prefix: str = \"AI\"\n    kg: NetworkxEntityGraph = Field(default_factory=NetworkxEntityGraph)\n    knowledge_extraction_prompt: BasePromptTemplate = KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT\n    entity_extraction_prompt: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT\n    llm: BaseLanguageModel\n    summary_message_cls: Type[BaseMessage] = SystemMessage\n    \"\"\"Number of previous utterances to include in the context.\"\"\"\n    memory_key: str = \"history\"  #: :meta private:\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Return history buffer.\"\"\"\n        entities = self._get_current_entities(inputs)\n        summary_strings = []\n        for entity in entities:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html"}
{"id": "348e0ddcc6d9-1", "text": "summary_strings = []\n        for entity in entities:\n            knowledge = self.kg.get_entity_knowledge(entity)\n            if knowledge:\n                summary = f\"On {entity}: {'. '.join(knowledge)}.\"\n                summary_strings.append(summary)\n        context: Union[str, List]\n        if not summary_strings:\n            context = [] if self.return_messages else \"\"\n        elif self.return_messages:\n            context = [\n                self.summary_message_cls(content=text) for text in summary_strings\n            ]\n        else:\n            context = \"\\n\".join(summary_strings)\n        return {self.memory_key: context}\n    @property\n    def memory_variables(self) -> List[str]:\n        \"\"\"Will always return list of memory variables.\n        :meta private:\n        \"\"\"\n        return [self.memory_key]\n    def _get_prompt_input_key(self, inputs: Dict[str, Any]) -> str:\n        \"\"\"Get the input key for the prompt.\"\"\"\n        if self.input_key is None:\n            return get_prompt_input_key(inputs, self.memory_variables)\n        return self.input_key\n    def _get_prompt_output_key(self, outputs: Dict[str, Any]) -> str:\n        \"\"\"Get the output key for the prompt.\"\"\"\n        if self.output_key is None:\n            if len(outputs) != 1:\n                raise ValueError(f\"One output key expected, got {outputs.keys()}\")\n            return list(outputs.keys())[0]\n        return self.output_key\n[docs]    def get_current_entities(self, input_string: str) -> List[str]:\n        chain = LLMChain(llm=self.llm, prompt=self.entity_extraction_prompt)\n        buffer_string = get_buffer_string(\n            self.chat_memory.messages[-self.k * 2 :],\n            human_prefix=self.human_prefix,\n            ai_prefix=self.ai_prefix,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html"}
{"id": "348e0ddcc6d9-2", "text": "human_prefix=self.human_prefix,\n            ai_prefix=self.ai_prefix,\n        )\n        output = chain.predict(\n            history=buffer_string,\n            input=input_string,\n        )\n        return get_entities(output)\n    def _get_current_entities(self, inputs: Dict[str, Any]) -> List[str]:\n        \"\"\"Get the current entities in the conversation.\"\"\"\n        prompt_input_key = self._get_prompt_input_key(inputs)\n        return self.get_current_entities(inputs[prompt_input_key])\n[docs]    def get_knowledge_triplets(self, input_string: str) -> List[KnowledgeTriple]:\n        chain = LLMChain(llm=self.llm, prompt=self.knowledge_extraction_prompt)\n        buffer_string = get_buffer_string(\n            self.chat_memory.messages[-self.k * 2 :],\n            human_prefix=self.human_prefix,\n            ai_prefix=self.ai_prefix,\n        )\n        output = chain.predict(\n            history=buffer_string,\n            input=input_string,\n            verbose=True,\n        )\n        knowledge = parse_triples(output)\n        return knowledge\n    def _get_and_update_kg(self, inputs: Dict[str, Any]) -> None:\n        \"\"\"Get and update knowledge graph from the conversation history.\"\"\"\n        prompt_input_key = self._get_prompt_input_key(inputs)\n        knowledge = self.get_knowledge_triplets(inputs[prompt_input_key])\n        for triple in knowledge:\n            self.kg.add_triple(triple)\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        \"\"\"Save context from this conversation to buffer.\"\"\"\n        super().save_context(inputs, outputs)\n        self._get_and_update_kg(inputs)\n[docs]    def clear(self) -> None:\n        \"\"\"Clear memory contents.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html"}
{"id": "348e0ddcc6d9-3", "text": "[docs]    def clear(self) -> None:\n        \"\"\"Clear memory contents.\"\"\"\n        super().clear()\n        self.kg.clear()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html"}
{"id": "9370a9f990a1-0", "text": "Source code for langchain.memory.readonly\nfrom typing import Any, Dict, List\nfrom langchain.schema import BaseMemory\n[docs]class ReadOnlySharedMemory(BaseMemory):\n    \"\"\"A memory wrapper that is read-only and cannot be changed.\"\"\"\n    memory: BaseMemory\n    @property\n    def memory_variables(self) -> List[str]:\n        \"\"\"Return memory variables.\"\"\"\n        return self.memory.memory_variables\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:\n        \"\"\"Load memory variables from memory.\"\"\"\n        return self.memory.load_memory_variables(inputs)\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        \"\"\"Nothing should be saved or changed\"\"\"\n        pass\n[docs]    def clear(self) -> None:\n        \"\"\"Nothing to clear, got a memory like a vault.\"\"\"\n        pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/readonly.html"}
{"id": "37df16887c52-0", "text": "Source code for langchain.memory.buffer_window\nfrom typing import Any, Dict, List, Union\nfrom langchain.memory.chat_memory import BaseChatMemory\nfrom langchain.schema.messages import BaseMessage, get_buffer_string\n[docs]class ConversationBufferWindowMemory(BaseChatMemory):\n    \"\"\"Buffer for storing conversation memory inside a limited size window.\"\"\"\n    human_prefix: str = \"Human\"\n    ai_prefix: str = \"AI\"\n    memory_key: str = \"history\"  #: :meta private:\n    k: int = 5\n    \"\"\"Number of messages to store in buffer.\"\"\"\n    @property\n    def buffer(self) -> Union[str, List[BaseMessage]]:\n        \"\"\"String buffer of memory.\"\"\"\n        return self.buffer_as_messages if self.return_messages else self.buffer_as_str\n    @property\n    def buffer_as_str(self) -> str:\n        \"\"\"Exposes the buffer as a string in case return_messages is True.\"\"\"\n        messages = self.chat_memory.messages[-self.k * 2 :] if self.k > 0 else []\n        return get_buffer_string(\n            messages,\n            human_prefix=self.human_prefix,\n            ai_prefix=self.ai_prefix,\n        )\n    @property\n    def buffer_as_messages(self) -> List[BaseMessage]:\n        \"\"\"Exposes the buffer as a list of messages in case return_messages is False.\"\"\"\n        return self.chat_memory.messages[-self.k * 2 :] if self.k > 0 else []\n    @property\n    def memory_variables(self) -> List[str]:\n        \"\"\"Will always return list of memory variables.\n        :meta private:\n        \"\"\"\n        return [self.memory_key]\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Return history buffer.\"\"\"\n        return {self.memory_key: self.buffer}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html"}
{"id": "7290b1c538ce-0", "text": "Source code for langchain.memory.summary\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Type\nfrom langchain.chains.llm import LLMChain\nfrom langchain.memory.chat_memory import BaseChatMemory\nfrom langchain.memory.prompt import SUMMARY_PROMPT\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n    BasePromptTemplate,\n)\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import BaseMessage, SystemMessage, get_buffer_string\n[docs]class SummarizerMixin(BaseModel):\n    \"\"\"Mixin for summarizer.\"\"\"\n    human_prefix: str = \"Human\"\n    ai_prefix: str = \"AI\"\n    llm: BaseLanguageModel\n    prompt: BasePromptTemplate = SUMMARY_PROMPT\n    summary_message_cls: Type[BaseMessage] = SystemMessage\n[docs]    def predict_new_summary(\n        self, messages: List[BaseMessage], existing_summary: str\n    ) -> str:\n        new_lines = get_buffer_string(\n            messages,\n            human_prefix=self.human_prefix,\n            ai_prefix=self.ai_prefix,\n        )\n        chain = LLMChain(llm=self.llm, prompt=self.prompt)\n        return chain.predict(summary=existing_summary, new_lines=new_lines)\n[docs]class ConversationSummaryMemory(BaseChatMemory, SummarizerMixin):\n    \"\"\"Conversation summarizer to chat memory.\"\"\"\n    buffer: str = \"\"\n    memory_key: str = \"history\"  #: :meta private:\n[docs]    @classmethod\n    def from_messages(\n        cls,\n        llm: BaseLanguageModel,\n        chat_memory: BaseChatMessageHistory,\n        *,\n        summarize_step: int = 2,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html"}
{"id": "7290b1c538ce-1", "text": "*,\n        summarize_step: int = 2,\n        **kwargs: Any,\n    ) -> ConversationSummaryMemory:\n        obj = cls(llm=llm, chat_memory=chat_memory, **kwargs)\n        for i in range(0, len(obj.chat_memory.messages), summarize_step):\n            obj.buffer = obj.predict_new_summary(\n                obj.chat_memory.messages[i : i + summarize_step], obj.buffer\n            )\n        return obj\n    @property\n    def memory_variables(self) -> List[str]:\n        \"\"\"Will always return list of memory variables.\n        :meta private:\n        \"\"\"\n        return [self.memory_key]\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Return history buffer.\"\"\"\n        if self.return_messages:\n            buffer: Any = [self.summary_message_cls(content=self.buffer)]\n        else:\n            buffer = self.buffer\n        return {self.memory_key: buffer}\n    @root_validator()\n    def validate_prompt_input_variables(cls, values: Dict) -> Dict:\n        \"\"\"Validate that prompt input variables are consistent.\"\"\"\n        prompt_variables = values[\"prompt\"].input_variables\n        expected_keys = {\"summary\", \"new_lines\"}\n        if expected_keys != set(prompt_variables):\n            raise ValueError(\n                \"Got unexpected prompt input variables. The prompt expects \"\n                f\"{prompt_variables}, but it should have {expected_keys}.\"\n            )\n        return values\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        \"\"\"Save context from this conversation to buffer.\"\"\"\n        super().save_context(inputs, outputs)\n        self.buffer = self.predict_new_summary(\n            self.chat_memory.messages[-2:], self.buffer\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html"}
{"id": "7290b1c538ce-2", "text": "self.chat_memory.messages[-2:], self.buffer\n        )\n[docs]    def clear(self) -> None:\n        \"\"\"Clear memory contents.\"\"\"\n        super().clear()\n        self.buffer = \"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html"}
{"id": "974a2cd11658-0", "text": "Source code for langchain.memory.buffer\nfrom typing import Any, Dict, List, Optional\nfrom langchain.memory.chat_memory import BaseChatMemory, BaseMemory\nfrom langchain.memory.utils import get_prompt_input_key\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema.messages import BaseMessage, get_buffer_string\n[docs]class ConversationBufferMemory(BaseChatMemory):\n    \"\"\"Buffer for storing conversation memory.\"\"\"\n    human_prefix: str = \"Human\"\n    ai_prefix: str = \"AI\"\n    memory_key: str = \"history\"  #: :meta private:\n    @property\n    def buffer(self) -> Any:\n        \"\"\"String buffer of memory.\"\"\"\n        return self.buffer_as_messages if self.return_messages else self.buffer_as_str\n    @property\n    def buffer_as_str(self) -> str:\n        \"\"\"Exposes the buffer as a string in case return_messages is True.\"\"\"\n        return get_buffer_string(\n            self.chat_memory.messages,\n            human_prefix=self.human_prefix,\n            ai_prefix=self.ai_prefix,\n        )\n    @property\n    def buffer_as_messages(self) -> List[BaseMessage]:\n        \"\"\"Exposes the buffer as a list of messages in case return_messages is False.\"\"\"\n        return self.chat_memory.messages\n    @property\n    def memory_variables(self) -> List[str]:\n        \"\"\"Will always return list of memory variables.\n        :meta private:\n        \"\"\"\n        return [self.memory_key]\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Return history buffer.\"\"\"\n        return {self.memory_key: self.buffer}\n[docs]class ConversationStringBufferMemory(BaseMemory):\n    \"\"\"Buffer for storing conversation memory.\"\"\"\n    human_prefix: str = \"Human\"\n    ai_prefix: str = \"AI\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html"}
{"id": "974a2cd11658-1", "text": "human_prefix: str = \"Human\"\n    ai_prefix: str = \"AI\"\n    \"\"\"Prefix to use for AI generated responses.\"\"\"\n    buffer: str = \"\"\n    output_key: Optional[str] = None\n    input_key: Optional[str] = None\n    memory_key: str = \"history\"  #: :meta private:\n    @root_validator()\n    def validate_chains(cls, values: Dict) -> Dict:\n        \"\"\"Validate that return messages is not True.\"\"\"\n        if values.get(\"return_messages\", False):\n            raise ValueError(\n                \"return_messages must be False for ConversationStringBufferMemory\"\n            )\n        return values\n    @property\n    def memory_variables(self) -> List[str]:\n        \"\"\"Will always return list of memory variables.\n        :meta private:\n        \"\"\"\n        return [self.memory_key]\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:\n        \"\"\"Return history buffer.\"\"\"\n        return {self.memory_key: self.buffer}\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        \"\"\"Save context from this conversation to buffer.\"\"\"\n        if self.input_key is None:\n            prompt_input_key = get_prompt_input_key(inputs, self.memory_variables)\n        else:\n            prompt_input_key = self.input_key\n        if self.output_key is None:\n            if len(outputs) != 1:\n                raise ValueError(f\"One output key expected, got {outputs.keys()}\")\n            output_key = list(outputs.keys())[0]\n        else:\n            output_key = self.output_key\n        human = f\"{self.human_prefix}: \" + inputs[prompt_input_key]\n        ai = f\"{self.ai_prefix}: \" + outputs[output_key]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html"}
{"id": "974a2cd11658-2", "text": "ai = f\"{self.ai_prefix}: \" + outputs[output_key]\n        self.buffer += \"\\n\" + \"\\n\".join([human, ai])\n[docs]    def clear(self) -> None:\n        \"\"\"Clear memory contents.\"\"\"\n        self.buffer = \"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html"}
{"id": "c2fd94bd440f-0", "text": "Source code for langchain.memory.zep_memory\nfrom __future__ import annotations\nfrom typing import Any, Dict, Optional\nfrom langchain.memory import ConversationBufferMemory\nfrom langchain.memory.chat_message_histories import ZepChatMessageHistory\n[docs]class ZepMemory(ConversationBufferMemory):\n    \"\"\"Persist your chain history to the Zep MemoryStore.\n    The number of messages returned by Zep and when the Zep server summarizes chat\n    histories is configurable. See the Zep documentation for more details.\n    Documentation: https://docs.getzep.com\n    Example:\n        .. code-block:: python\n        memory = ZepMemory(\n                    session_id=session_id,  # Identifies your user or a user's session\n                    url=ZEP_API_URL,        # Your Zep server's URL\n                    api_key=<your_api_key>, # Optional\n                    memory_key=\"history\",   # Ensure this matches the key used in\n                                            # chain's prompt template\n                    return_messages=True,   # Does your prompt template expect a string\n                                            # or a list of Messages?\n                )\n        chain = LLMChain(memory=memory,...) # Configure your chain to use the ZepMemory\n                                              instance\n    Note:\n        To persist metadata alongside your chat history, your will need to create a\n    custom Chain class that overrides the `prep_outputs` method to include the metadata\n    in the call to `self.memory.save_context`.\n    Zep - Fast, scalable building blocks for LLM Apps\n    =========\n    Zep is an open source platform for productionizing LLM apps. Go from a prototype\n    built in LangChain or LlamaIndex, or a custom app, to production in minutes without\n    rewriting code.\n    For server installation instructions and more, see:\n    https://docs.getzep.com/deployment/quickstart/", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/zep_memory.html"}
{"id": "c2fd94bd440f-1", "text": "https://docs.getzep.com/deployment/quickstart/\n    For more information on the zep-python package, see:\n    https://github.com/getzep/zep-python\n    \"\"\"\n    chat_memory: ZepChatMessageHistory\n    def __init__(\n        self,\n        session_id: str,\n        url: str = \"http://localhost:8000\",\n        api_key: Optional[str] = None,\n        output_key: Optional[str] = None,\n        input_key: Optional[str] = None,\n        return_messages: bool = False,\n        human_prefix: str = \"Human\",\n        ai_prefix: str = \"AI\",\n        memory_key: str = \"history\",\n    ):\n        \"\"\"Initialize ZepMemory.\n        Args:\n            session_id (str): Identifies your user or a user's session\n            url (str, optional): Your Zep server's URL. Defaults to\n                                 \"http://localhost:8000\".\n            api_key (Optional[str], optional): Your Zep API key. Defaults to None.\n            output_key (Optional[str], optional): The key to use for the output message.\n                                              Defaults to None.\n            input_key (Optional[str], optional): The key to use for the input message.\n                                              Defaults to None.\n            return_messages (bool, optional): Does your prompt template expect a string\n                                              or a list of Messages? Defaults to False\n                                              i.e. return a string.\n            human_prefix (str, optional): The prefix to use for human messages.\n                                          Defaults to \"Human\".\n            ai_prefix (str, optional): The prefix to use for AI messages.\n                                       Defaults to \"AI\".\n            memory_key (str, optional): The key to use for the memory.\n                                        Defaults to \"history\".", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/zep_memory.html"}
{"id": "c2fd94bd440f-2", "text": "Defaults to \"history\".\n                                        Ensure that this matches the key used in\n                                        chain's prompt template.\n        \"\"\"\n        chat_message_history = ZepChatMessageHistory(\n            session_id=session_id,\n            url=url,\n            api_key=api_key,\n        )\n        super().__init__(\n            chat_memory=chat_message_history,\n            output_key=output_key,\n            input_key=input_key,\n            return_messages=return_messages,\n            human_prefix=human_prefix,\n            ai_prefix=ai_prefix,\n            memory_key=memory_key,\n        )\n[docs]    def save_context(\n        self,\n        inputs: Dict[str, Any],\n        outputs: Dict[str, str],\n        metadata: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        \"\"\"Save context from this conversation to buffer.\n        Args:\n            inputs (Dict[str, Any]): The inputs to the chain.\n            outputs (Dict[str, str]): The outputs from the chain.\n            metadata (Optional[Dict[str, Any]], optional): Any metadata to save with\n                                                           the context. Defaults to None\n        Returns:\n            None\n        \"\"\"\n        input_str, output_str = self._get_input_output(inputs, outputs)\n        self.chat_memory.add_user_message(input_str, metadata=metadata)\n        self.chat_memory.add_ai_message(output_str, metadata=metadata)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/zep_memory.html"}
{"id": "cdd748b87c56-0", "text": "Source code for langchain.memory.summary_buffer\nfrom typing import Any, Dict, List\nfrom langchain.memory.chat_memory import BaseChatMemory\nfrom langchain.memory.summary import SummarizerMixin\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema.messages import BaseMessage, get_buffer_string\n[docs]class ConversationSummaryBufferMemory(BaseChatMemory, SummarizerMixin):\n    \"\"\"Buffer with summarizer for storing conversation memory.\"\"\"\n    max_token_limit: int = 2000\n    moving_summary_buffer: str = \"\"\n    memory_key: str = \"history\"\n    @property\n    def buffer(self) -> List[BaseMessage]:\n        return self.chat_memory.messages\n    @property\n    def memory_variables(self) -> List[str]:\n        \"\"\"Will always return list of memory variables.\n        :meta private:\n        \"\"\"\n        return [self.memory_key]\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Return history buffer.\"\"\"\n        buffer = self.buffer\n        if self.moving_summary_buffer != \"\":\n            first_messages: List[BaseMessage] = [\n                self.summary_message_cls(content=self.moving_summary_buffer)\n            ]\n            buffer = first_messages + buffer\n        if self.return_messages:\n            final_buffer: Any = buffer\n        else:\n            final_buffer = get_buffer_string(\n                buffer, human_prefix=self.human_prefix, ai_prefix=self.ai_prefix\n            )\n        return {self.memory_key: final_buffer}\n    @root_validator()\n    def validate_prompt_input_variables(cls, values: Dict) -> Dict:\n        \"\"\"Validate that prompt input variables are consistent.\"\"\"\n        prompt_variables = values[\"prompt\"].input_variables\n        expected_keys = {\"summary\", \"new_lines\"}\n        if expected_keys != set(prompt_variables):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html"}
{"id": "cdd748b87c56-1", "text": "if expected_keys != set(prompt_variables):\n            raise ValueError(\n                \"Got unexpected prompt input variables. The prompt expects \"\n                f\"{prompt_variables}, but it should have {expected_keys}.\"\n            )\n        return values\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        \"\"\"Save context from this conversation to buffer.\"\"\"\n        super().save_context(inputs, outputs)\n        self.prune()\n[docs]    def prune(self) -> None:\n        \"\"\"Prune buffer if it exceeds max token limit\"\"\"\n        buffer = self.chat_memory.messages\n        curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)\n        if curr_buffer_length > self.max_token_limit:\n            pruned_memory = []\n            while curr_buffer_length > self.max_token_limit:\n                pruned_memory.append(buffer.pop(0))\n                curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)\n            self.moving_summary_buffer = self.predict_new_summary(\n                pruned_memory, self.moving_summary_buffer\n            )\n[docs]    def clear(self) -> None:\n        \"\"\"Clear memory contents.\"\"\"\n        super().clear()\n        self.moving_summary_buffer = \"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html"}
{"id": "93e8c77f073e-0", "text": "Source code for langchain.memory.motorhead_memory\nfrom typing import Any, Dict, List, Optional\nimport requests\nfrom langchain.memory.chat_memory import BaseChatMemory\nfrom langchain.schema.messages import get_buffer_string\nMANAGED_URL = \"https://api.getmetal.io/v1/motorhead\"\n# LOCAL_URL = \"http://localhost:8080\"\n[docs]class MotorheadMemory(BaseChatMemory):\n    \"\"\"Chat message memory backed by Motorhead service.\"\"\"\n    url: str = MANAGED_URL\n    timeout: int = 3000\n    memory_key: str = \"history\"\n    session_id: str\n    context: Optional[str] = None\n    # Managed Params\n    api_key: Optional[str] = None\n    client_id: Optional[str] = None\n    def __get_headers(self) -> Dict[str, str]:\n        is_managed = self.url == MANAGED_URL\n        headers = {\n            \"Content-Type\": \"application/json\",\n        }\n        if is_managed and not (self.api_key and self.client_id):\n            raise ValueError(\n                \"\"\"\n                You must provide an API key or a client ID to use the managed\n                version of Motorhead. Visit https://getmetal.io for more information.\n                \"\"\"\n            )\n        if is_managed and self.api_key and self.client_id:\n            headers[\"x-metal-api-key\"] = self.api_key\n            headers[\"x-metal-client-id\"] = self.client_id\n        return headers\n[docs]    async def init(self) -> None:\n        res = requests.get(\n            f\"{self.url}/sessions/{self.session_id}/memory\",\n            timeout=self.timeout,\n            headers=self.__get_headers(),\n        )\n        res_data = res.json()\n        res_data = res_data.get(\"data\", res_data)  # Handle Managed Version", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html"}
{"id": "93e8c77f073e-1", "text": "res_data = res_data.get(\"data\", res_data)  # Handle Managed Version\n        messages = res_data.get(\"messages\", [])\n        context = res_data.get(\"context\", \"NONE\")\n        for message in reversed(messages):\n            if message[\"role\"] == \"AI\":\n                self.chat_memory.add_ai_message(message[\"content\"])\n            else:\n                self.chat_memory.add_user_message(message[\"content\"])\n        if context and context != \"NONE\":\n            self.context = context\n[docs]    def load_memory_variables(self, values: Dict[str, Any]) -> Dict[str, Any]:\n        if self.return_messages:\n            return {self.memory_key: self.chat_memory.messages}\n        else:\n            return {self.memory_key: get_buffer_string(self.chat_memory.messages)}\n    @property\n    def memory_variables(self) -> List[str]:\n        return [self.memory_key]\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        input_str, output_str = self._get_input_output(inputs, outputs)\n        requests.post(\n            f\"{self.url}/sessions/{self.session_id}/memory\",\n            timeout=self.timeout,\n            json={\n                \"messages\": [\n                    {\"role\": \"Human\", \"content\": f\"{input_str}\"},\n                    {\"role\": \"AI\", \"content\": f\"{output_str}\"},\n                ]\n            },\n            headers=self.__get_headers(),\n        )\n        super().save_context(inputs, outputs)\n[docs]    def delete_session(self) -> None:\n        \"\"\"Delete a session\"\"\"\n        requests.delete(f\"{self.url}/sessions/{self.session_id}/memory\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html"}
{"id": "42da3b86b934-0", "text": "Source code for langchain.memory.combined\nimport warnings\nfrom typing import Any, Dict, List, Set\nfrom langchain.memory.chat_memory import BaseChatMemory\nfrom langchain.pydantic_v1 import validator\nfrom langchain.schema import BaseMemory\n[docs]class CombinedMemory(BaseMemory):\n    \"\"\"Combining multiple memories' data together.\"\"\"\n    memories: List[BaseMemory]\n    \"\"\"For tracking all the memories that should be accessed.\"\"\"\n    @validator(\"memories\")\n    def check_repeated_memory_variable(\n        cls, value: List[BaseMemory]\n    ) -> List[BaseMemory]:\n        all_variables: Set[str] = set()\n        for val in value:\n            overlap = all_variables.intersection(val.memory_variables)\n            if overlap:\n                raise ValueError(\n                    f\"The same variables {overlap} are found in multiple\"\n                    \"memory object, which is not allowed by CombinedMemory.\"\n                )\n            all_variables |= set(val.memory_variables)\n        return value\n    @validator(\"memories\")\n    def check_input_key(cls, value: List[BaseMemory]) -> List[BaseMemory]:\n        \"\"\"Check that if memories are of type BaseChatMemory that input keys exist.\"\"\"\n        for val in value:\n            if isinstance(val, BaseChatMemory):\n                if val.input_key is None:\n                    warnings.warn(\n                        \"When using CombinedMemory, \"\n                        \"input keys should be so the input is known. \"\n                        f\" Was not set on {val}\"\n                    )\n        return value\n    @property\n    def memory_variables(self) -> List[str]:\n        \"\"\"All the memory variables that this instance provides.\"\"\"\n        \"\"\"Collected from the all the linked memories.\"\"\"\n        memory_variables = []\n        for memory in self.memories:\n            memory_variables.extend(memory.memory_variables)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html"}
{"id": "42da3b86b934-1", "text": "for memory in self.memories:\n            memory_variables.extend(memory.memory_variables)\n        return memory_variables\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:\n        \"\"\"Load all vars from sub-memories.\"\"\"\n        memory_data: Dict[str, Any] = {}\n        # Collect vars from all sub-memories\n        for memory in self.memories:\n            data = memory.load_memory_variables(inputs)\n            for key, value in data.items():\n                if key in memory_data:\n                    raise ValueError(\n                        f\"The variable {key} is repeated in the CombinedMemory.\"\n                    )\n                memory_data[key] = value\n        return memory_data\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        \"\"\"Save context from this session for every memory.\"\"\"\n        # Save context for all sub-memories\n        for memory in self.memories:\n            memory.save_context(inputs, outputs)\n[docs]    def clear(self) -> None:\n        \"\"\"Clear context from this session for every memory.\"\"\"\n        for memory in self.memories:\n            memory.clear()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html"}
{"id": "268b210710cb-0", "text": "Source code for langchain.memory.chat_message_histories.xata\nimport json\nfrom typing import List\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict\n[docs]class XataChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history stored in a Xata database.\"\"\"\n[docs]    def __init__(\n        self,\n        session_id: str,\n        db_url: str,\n        api_key: str,\n        branch_name: str = \"main\",\n        table_name: str = \"messages\",\n        create_table: bool = True,\n    ) -> None:\n        \"\"\"Initialize with Xata client.\"\"\"\n        try:\n            from xata.client import XataClient  # noqa: F401\n        except ImportError:\n            raise ValueError(\n                \"Could not import xata python package. \"\n                \"Please install it with `pip install xata`.\"\n            )\n        self._client = XataClient(\n            api_key=api_key, db_url=db_url, branch_name=branch_name\n        )\n        self._table_name = table_name\n        self._session_id = session_id\n        if create_table:\n            self._create_table_if_not_exists()\n    def _create_table_if_not_exists(self) -> None:\n        r = self._client.table().get_schema(self._table_name)\n        if r.status_code <= 299:\n            return\n        if r.status_code != 404:\n            raise Exception(\n                f\"Error checking if table exists in Xata: {r.status_code} {r}\"\n            )\n        r = self._client.table().create(self._table_name)\n        if r.status_code > 299:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/xata.html"}
{"id": "268b210710cb-1", "text": "if r.status_code > 299:\n            raise Exception(f\"Error creating table in Xata: {r.status_code} {r}\")\n        r = self._client.table().set_schema(\n            self._table_name,\n            payload={\n                \"columns\": [\n                    {\"name\": \"sessionId\", \"type\": \"string\"},\n                    {\"name\": \"type\", \"type\": \"string\"},\n                    {\"name\": \"role\", \"type\": \"string\"},\n                    {\"name\": \"content\", \"type\": \"text\"},\n                    {\"name\": \"name\", \"type\": \"string\"},\n                    {\"name\": \"additionalKwargs\", \"type\": \"json\"},\n                ]\n            },\n        )\n        if r.status_code > 299:\n            raise Exception(f\"Error setting table schema in Xata: {r.status_code} {r}\")\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Append the message to the Xata table\"\"\"\n        msg = _message_to_dict(message)\n        r = self._client.records().insert(\n            self._table_name,\n            {\n                \"sessionId\": self._session_id,\n                \"type\": msg[\"type\"],\n                \"content\": message.content,\n                \"additionalKwargs\": json.dumps(message.additional_kwargs),\n                \"role\": msg[\"data\"].get(\"role\"),\n                \"name\": msg[\"data\"].get(\"name\"),\n            },\n        )\n        if r.status_code > 299:\n            raise Exception(f\"Error adding message to Xata: {r.status_code} {r}\")\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        r = self._client.data().query(\n            self._table_name,\n            payload={\n                \"filter\": {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/xata.html"}
{"id": "268b210710cb-2", "text": "self._table_name,\n            payload={\n                \"filter\": {\n                    \"sessionId\": self._session_id,\n                },\n                \"sort\": {\"xata.createdAt\": \"asc\"},\n            },\n        )\n        if r.status_code != 200:\n            raise Exception(f\"Error running query: {r.status_code} {r}\")\n        msgs = messages_from_dict(\n            [\n                {\n                    \"type\": m[\"type\"],\n                    \"data\": {\n                        \"content\": m[\"content\"],\n                        \"role\": m.get(\"role\"),\n                        \"name\": m.get(\"name\"),\n                        \"additional_kwargs\": json.loads(m[\"additionalKwargs\"]),\n                    },\n                }\n                for m in r[\"records\"]\n            ]\n        )\n        return msgs\n[docs]    def clear(self) -> None:\n        \"\"\"Delete session from Xata table.\"\"\"\n        while True:\n            r = self._client.data().query(\n                self._table_name,\n                payload={\n                    \"columns\": [\"id\"],\n                    \"filter\": {\n                        \"sessionId\": self._session_id,\n                    },\n                },\n            )\n            if r.status_code != 200:\n                raise Exception(f\"Error running query: {r.status_code} {r}\")\n            ids = [rec[\"id\"] for rec in r[\"records\"]]\n            if len(ids) == 0:\n                break\n            operations = [\n                {\"delete\": {\"table\": self._table_name, \"id\": id}} for id in ids\n            ]\n            self._client.records().transaction(payload={\"operations\": operations})", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/xata.html"}
{"id": "fc5cffa32f70-0", "text": "Source code for langchain.memory.chat_message_histories.dynamodb\nfrom __future__ import annotations\nimport logging\nfrom typing import TYPE_CHECKING, Dict, List, Optional\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import (\n    BaseMessage,\n    _message_to_dict,\n    messages_from_dict,\n    messages_to_dict,\n)\nif TYPE_CHECKING:\n    from boto3.session import Session\nlogger = logging.getLogger(__name__)\n[docs]class DynamoDBChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history that stores history in AWS DynamoDB.\n    This class expects that a DynamoDB table exists with name `table_name`\n    Args:\n        table_name: name of the DynamoDB table\n        session_id: arbitrary key that is used to store the messages\n            of a single chat session.\n        endpoint_url: URL of the AWS endpoint to connect to. This argument\n            is optional and useful for test purposes, like using Localstack.\n            If you plan to use AWS cloud service, you normally don't have to\n            worry about setting the endpoint_url.\n        primary_key_name: name of the primary key of the DynamoDB table. This argument\n            is optional, defaulting to \"SessionId\".\n        key: an optional dictionary with a custom primary and secondary key.\n            This argument is optional, but useful when using composite dynamodb keys, or\n            isolating records based off of application details such as a user id.\n            This may also contain global and local secondary index keys.\n        kms_key_id: an optional AWS KMS Key ID, AWS KMS Key ARN, or AWS KMS Alias for\n            client-side encryption\n    \"\"\"\n[docs]    def __init__(\n        self,\n        table_name: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html"}
{"id": "fc5cffa32f70-1", "text": "[docs]    def __init__(\n        self,\n        table_name: str,\n        session_id: str,\n        endpoint_url: Optional[str] = None,\n        primary_key_name: str = \"SessionId\",\n        key: Optional[Dict[str, str]] = None,\n        boto3_session: Optional[Session] = None,\n        kms_key_id: Optional[str] = None,\n    ):\n        if boto3_session:\n            client = boto3_session.resource(\"dynamodb\", endpoint_url=endpoint_url)\n        else:\n            try:\n                import boto3\n            except ImportError as e:\n                raise ImportError(\n                    \"Unable to import boto3, please install with `pip install boto3`.\"\n                ) from e\n            if endpoint_url:\n                client = boto3.resource(\"dynamodb\", endpoint_url=endpoint_url)\n            else:\n                client = boto3.resource(\"dynamodb\")\n        self.table = client.Table(table_name)\n        self.session_id = session_id\n        self.key: Dict = key or {primary_key_name: session_id}\n        if kms_key_id:\n            try:\n                from dynamodb_encryption_sdk.encrypted.table import EncryptedTable\n                from dynamodb_encryption_sdk.identifiers import CryptoAction\n                from dynamodb_encryption_sdk.material_providers.aws_kms import (\n                    AwsKmsCryptographicMaterialsProvider,\n                )\n                from dynamodb_encryption_sdk.structures import AttributeActions\n            except ImportError as e:\n                raise ImportError(\n                    \"Unable to import dynamodb_encryption_sdk, please install with \"\n                    \"`pip install dynamodb-encryption-sdk`.\"\n                ) from e\n            actions = AttributeActions(\n                default_action=CryptoAction.DO_NOTHING,\n                attribute_actions={\"History\": CryptoAction.ENCRYPT_AND_SIGN},\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html"}
{"id": "fc5cffa32f70-2", "text": "attribute_actions={\"History\": CryptoAction.ENCRYPT_AND_SIGN},\n            )\n            aws_kms_cmp = AwsKmsCryptographicMaterialsProvider(key_id=kms_key_id)\n            self.table = EncryptedTable(\n                table=self.table,\n                materials_provider=aws_kms_cmp,\n                attribute_actions=actions,\n                auto_refresh_table_indexes=False,\n            )\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        \"\"\"Retrieve the messages from DynamoDB\"\"\"\n        try:\n            from botocore.exceptions import ClientError\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import botocore, please install with `pip install botocore`.\"\n            ) from e\n        response = None\n        try:\n            response = self.table.get_item(Key=self.key)\n        except ClientError as error:\n            if error.response[\"Error\"][\"Code\"] == \"ResourceNotFoundException\":\n                logger.warning(\"No record found with session id: %s\", self.session_id)\n            else:\n                logger.error(error)\n        if response and \"Item\" in response:\n            items = response[\"Item\"][\"History\"]\n        else:\n            items = []\n        messages = messages_from_dict(items)\n        return messages\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Append the message to the record in DynamoDB\"\"\"\n        try:\n            from botocore.exceptions import ClientError\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import botocore, please install with `pip install botocore`.\"\n            ) from e\n        messages = messages_to_dict(self.messages)\n        _message = _message_to_dict(message)\n        messages.append(_message)\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html"}
{"id": "fc5cffa32f70-3", "text": "messages.append(_message)\n        try:\n            self.table.put_item(Item={**self.key, \"History\": messages})\n        except ClientError as err:\n            logger.error(err)\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory from DynamoDB\"\"\"\n        try:\n            from botocore.exceptions import ClientError\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import botocore, please install with `pip install botocore`.\"\n            ) from e\n        try:\n            self.table.delete_item(Key=self.key)\n        except ClientError as err:\n            logger.error(err)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html"}
{"id": "6c5c4b3270de-0", "text": "Source code for langchain.memory.chat_message_histories.cassandra\n\"\"\"Cassandra-based chat message history, based on cassIO.\"\"\"\nfrom __future__ import annotations\nimport json\nimport typing\nfrom typing import List\nif typing.TYPE_CHECKING:\n    from cassandra.cluster import Session\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict\nDEFAULT_TABLE_NAME = \"message_store\"\nDEFAULT_TTL_SECONDS = None\n[docs]class CassandraChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history that stores history in Cassandra.\n    Args:\n        session_id: arbitrary key that is used to store the messages\n            of a single chat session.\n        session: a Cassandra `Session` object (an open DB connection)\n        keyspace: name of the keyspace to use.\n        table_name: name of the table to use.\n        ttl_seconds: time-to-live (seconds) for automatic expiration\n            of stored entries. None (default) for no expiration.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        session_id: str,\n        session: Session,\n        keyspace: str,\n        table_name: str = DEFAULT_TABLE_NAME,\n        ttl_seconds: typing.Optional[int] = DEFAULT_TTL_SECONDS,\n    ) -> None:\n        try:\n            from cassio.history import StoredBlobHistory\n        except (ImportError, ModuleNotFoundError):\n            raise ImportError(\n                \"Could not import cassio python package. \"\n                \"Please install it with `pip install cassio`.\"\n            )\n        self.session_id = session_id\n        self.ttl_seconds = ttl_seconds\n        self.blob_history = StoredBlobHistory(session, keyspace, table_name)\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html"}
{"id": "6c5c4b3270de-1", "text": "@property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        \"\"\"Retrieve all session messages from DB\"\"\"\n        message_blobs = self.blob_history.retrieve(\n            self.session_id,\n        )\n        items = [json.loads(message_blob) for message_blob in message_blobs]\n        messages = messages_from_dict(items)\n        return messages\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Write a message to the table\"\"\"\n        self.blob_history.store(\n            self.session_id, json.dumps(_message_to_dict(message)), self.ttl_seconds\n        )\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory from DB\"\"\"\n        self.blob_history.clear_session_id(self.session_id)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html"}
{"id": "42a95f78e2df-0", "text": "Source code for langchain.memory.chat_message_histories.zep\nfrom __future__ import annotations\nimport logging\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import (\n    AIMessage,\n    BaseMessage,\n    HumanMessage,\n    SystemMessage,\n)\nif TYPE_CHECKING:\n    from zep_python import Memory, MemorySearchResult, Message, NotFoundError\nlogger = logging.getLogger(__name__)\n[docs]class ZepChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history that uses Zep as a backend.\n    Recommended usage::\n        # Set up Zep Chat History\n        zep_chat_history = ZepChatMessageHistory(\n            session_id=session_id,\n            url=ZEP_API_URL,\n            api_key=<your_api_key>,\n        )\n        # Use a standard ConversationBufferMemory to encapsulate the Zep chat history\n        memory = ConversationBufferMemory(\n            memory_key=\"chat_history\", chat_memory=zep_chat_history\n        )\n    Zep provides long-term conversation storage for LLM apps. The server stores,\n    summarizes, embeds, indexes, and enriches conversational AI chat\n    histories, and exposes them via simple, low-latency APIs.\n    For server installation instructions and more, see:\n    https://docs.getzep.com/deployment/quickstart/\n    This class is a thin wrapper around the zep-python package. Additional\n    Zep functionality is exposed via the `zep_summary` and `zep_messages`\n    properties.\n    For more information on the zep-python package, see:\n    https://github.com/getzep/zep-python\n    \"\"\"\n[docs]    def __init__(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html"}
{"id": "42a95f78e2df-1", "text": "\"\"\"\n[docs]    def __init__(\n        self,\n        session_id: str,\n        url: str = \"http://localhost:8000\",\n        api_key: Optional[str] = None,\n    ) -> None:\n        try:\n            from zep_python import ZepClient\n        except ImportError:\n            raise ImportError(\n                \"Could not import zep-python package. \"\n                \"Please install it with `pip install zep-python`.\"\n            )\n        self.zep_client = ZepClient(base_url=url, api_key=api_key)\n        self.session_id = session_id\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        \"\"\"Retrieve messages from Zep memory\"\"\"\n        zep_memory: Optional[Memory] = self._get_memory()\n        if not zep_memory:\n            return []\n        messages: List[BaseMessage] = []\n        # Extract summary, if present, and messages\n        if zep_memory.summary:\n            if len(zep_memory.summary.content) > 0:\n                messages.append(SystemMessage(content=zep_memory.summary.content))\n        if zep_memory.messages:\n            msg: Message\n            for msg in zep_memory.messages:\n                metadata: Dict = {\n                    \"uuid\": msg.uuid,\n                    \"created_at\": msg.created_at,\n                    \"token_count\": msg.token_count,\n                    \"metadata\": msg.metadata,\n                }\n                if msg.role == \"ai\":\n                    messages.append(\n                        AIMessage(content=msg.content, additional_kwargs=metadata)\n                    )\n                else:\n                    messages.append(\n                        HumanMessage(content=msg.content, additional_kwargs=metadata)\n                    )\n        return messages\n    @property\n    def zep_messages(self) -> List[Message]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html"}
{"id": "42a95f78e2df-2", "text": "@property\n    def zep_messages(self) -> List[Message]:\n        \"\"\"Retrieve summary from Zep memory\"\"\"\n        zep_memory: Optional[Memory] = self._get_memory()\n        if not zep_memory:\n            return []\n        return zep_memory.messages\n    @property\n    def zep_summary(self) -> Optional[str]:\n        \"\"\"Retrieve summary from Zep memory\"\"\"\n        zep_memory: Optional[Memory] = self._get_memory()\n        if not zep_memory or not zep_memory.summary:\n            return None\n        return zep_memory.summary.content\n    def _get_memory(self) -> Optional[Memory]:\n        \"\"\"Retrieve memory from Zep\"\"\"\n        from zep_python import NotFoundError\n        try:\n            zep_memory: Memory = self.zep_client.memory.get_memory(self.session_id)\n        except NotFoundError:\n            logger.warning(\n                f\"Session {self.session_id} not found in Zep. Returning None\"\n            )\n            return None\n        return zep_memory\n[docs]    def add_user_message(\n        self, message: str, metadata: Optional[Dict[str, Any]] = None\n    ) -> None:\n        \"\"\"Convenience method for adding a human message string to the store.\n        Args:\n            message: The string contents of a human message.\n            metadata: Optional metadata to attach to the message.\n        \"\"\"\n        self.add_message(HumanMessage(content=message), metadata=metadata)\n[docs]    def add_ai_message(\n        self, message: str, metadata: Optional[Dict[str, Any]] = None\n    ) -> None:\n        \"\"\"Convenience method for adding an AI message string to the store.\n        Args:\n            message: The string contents of an AI message.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html"}
{"id": "42a95f78e2df-3", "text": "Args:\n            message: The string contents of an AI message.\n            metadata: Optional metadata to attach to the message.\n        \"\"\"\n        self.add_message(AIMessage(content=message), metadata=metadata)\n[docs]    def add_message(\n        self, message: BaseMessage, metadata: Optional[Dict[str, Any]] = None\n    ) -> None:\n        \"\"\"Append the message to the Zep memory history\"\"\"\n        from zep_python import Memory, Message\n        zep_message = Message(\n            content=message.content, role=message.type, metadata=metadata\n        )\n        zep_memory = Memory(messages=[zep_message])\n        self.zep_client.memory.add_memory(self.session_id, zep_memory)\n[docs]    def search(\n        self, query: str, metadata: Optional[Dict] = None, limit: Optional[int] = None\n    ) -> List[MemorySearchResult]:\n        \"\"\"Search Zep memory for messages matching the query\"\"\"\n        from zep_python import MemorySearchPayload\n        payload: MemorySearchPayload = MemorySearchPayload(\n            text=query, metadata=metadata\n        )\n        return self.zep_client.memory.search_memory(\n            self.session_id, payload, limit=limit\n        )\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory from Zep. Note that Zep is long-term storage for memory\n        and this is not advised unless you have specific data retention requirements.\n        \"\"\"\n        try:\n            self.zep_client.memory.delete_memory(self.session_id)\n        except NotFoundError:\n            logger.warning(\n                f\"Session {self.session_id} not found in Zep. Skipping delete.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html"}
{"id": "4a0fb584adea-0", "text": "Source code for langchain.memory.chat_message_histories.neo4j\nfrom typing import List, Optional, Union\nfrom langchain.schema import BaseChatMessageHistory\nfrom langchain.schema.messages import BaseMessage, messages_from_dict\nfrom langchain.utils import get_from_env\n[docs]class Neo4jChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history stored in a Neo4j database.\"\"\"\n[docs]    def __init__(\n        self,\n        session_id: Union[str, int],\n        url: Optional[str] = None,\n        username: Optional[str] = None,\n        password: Optional[str] = None,\n        database: str = \"neo4j\",\n        node_label: str = \"Session\",\n        window: int = 3,\n    ):\n        try:\n            import neo4j\n        except ImportError:\n            raise ValueError(\n                \"Could not import neo4j python package. \"\n                \"Please install it with `pip install neo4j`.\"\n            )\n        # Make sure session id is not null\n        if not session_id:\n            raise ValueError(\"Please ensure that the session_id parameter is provided\")\n        url = get_from_env(\"url\", \"NEO4J_URI\", url)\n        username = get_from_env(\"username\", \"NEO4J_USERNAME\", username)\n        password = get_from_env(\"password\", \"NEO4J_PASSWORD\", password)\n        database = get_from_env(\"database\", \"NEO4J_DATABASE\", database)\n        self._driver = neo4j.GraphDatabase.driver(url, auth=(username, password))\n        self._database = database\n        self._session_id = session_id\n        self._node_label = node_label\n        self._window = window\n        # Verify connection\n        try:\n            self._driver.verify_connectivity()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/neo4j.html"}
{"id": "4a0fb584adea-1", "text": "# Verify connection\n        try:\n            self._driver.verify_connectivity()\n        except neo4j.exceptions.ServiceUnavailable:\n            raise ValueError(\n                \"Could not connect to Neo4j database. \"\n                \"Please ensure that the url is correct\"\n            )\n        except neo4j.exceptions.AuthError:\n            raise ValueError(\n                \"Could not connect to Neo4j database. \"\n                \"Please ensure that the username and password are correct\"\n            )\n        # Create session node\n        self._driver.execute_query(\n            f\"MERGE (s:`{self._node_label}` {{id:$session_id}})\",\n            {\"session_id\": self._session_id},\n        ).summary\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        \"\"\"Retrieve the messages from Neo4j\"\"\"\n        query = (\n            f\"MATCH (s:`{self._node_label}`)-[:LAST_MESSAGE]->(last_message) \"\n            \"WHERE s.id = $session_id MATCH p=(last_message)<-[:NEXT*0..\"\n            f\"{self._window*2}]-() WITH p, length(p) AS length \"\n            \"ORDER BY length DESC LIMIT 1 UNWIND reverse(nodes(p)) AS node \"\n            \"RETURN {data:{content: node.content}, type:node.type} AS result\"\n        )\n        records, _, _ = self._driver.execute_query(\n            query, {\"session_id\": self._session_id}\n        )\n        messages = messages_from_dict([el[\"result\"] for el in records])\n        return messages\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Append the message to the record in Neo4j\"\"\"\n        query = (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/neo4j.html"}
{"id": "4a0fb584adea-2", "text": "\"\"\"Append the message to the record in Neo4j\"\"\"\n        query = (\n            f\"MATCH (s:`{self._node_label}`) WHERE s.id = $session_id \"\n            \"OPTIONAL MATCH (s)-[lm:LAST_MESSAGE]->(last_message) \"\n            \"CREATE (s)-[:LAST_MESSAGE]->(new:Message) \"\n            \"SET new += {type:$type, content:$content} \"\n            \"WITH new, lm, last_message WHERE last_message IS NOT NULL \"\n            \"CREATE (last_message)-[:NEXT]->(new) \"\n            \"DELETE lm\"\n        )\n        self._driver.execute_query(\n            query,\n            {\n                \"type\": message.type,\n                \"content\": message.content,\n                \"session_id\": self._session_id,\n            },\n        ).summary\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory from Neo4j\"\"\"\n        query = (\n            f\"MATCH (s:`{self._node_label}`)-[:LAST_MESSAGE]->(last_message) \"\n            \"WHERE s.id = $session_id MATCH p=(last_message)<-[:NEXT]-() \"\n            \"WITH p, length(p) AS length ORDER BY length DESC LIMIT 1 \"\n            \"UNWIND nodes(p) as node DETACH DELETE node;\"\n        )\n        self._driver.execute_query(query, {\"session_id\": self._session_id}).summary\n    def __del__(self) -> None:\n        if self._driver:\n            self._driver.close()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/neo4j.html"}
{"id": "6f9ce0f02c0a-0", "text": "Source code for langchain.memory.chat_message_histories.postgres\nimport json\nimport logging\nfrom typing import List\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict\nlogger = logging.getLogger(__name__)\nDEFAULT_CONNECTION_STRING = \"postgresql://postgres:mypassword@localhost/chat_history\"\n[docs]class PostgresChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history stored in a Postgres database.\"\"\"\n[docs]    def __init__(\n        self,\n        session_id: str,\n        connection_string: str = DEFAULT_CONNECTION_STRING,\n        table_name: str = \"message_store\",\n    ):\n        import psycopg\n        from psycopg.rows import dict_row\n        try:\n            self.connection = psycopg.connect(connection_string)\n            self.cursor = self.connection.cursor(row_factory=dict_row)\n        except psycopg.OperationalError as error:\n            logger.error(error)\n        self.session_id = session_id\n        self.table_name = table_name\n        self._create_table_if_not_exists()\n    def _create_table_if_not_exists(self) -> None:\n        create_table_query = f\"\"\"CREATE TABLE IF NOT EXISTS {self.table_name} (\n            id SERIAL PRIMARY KEY,\n            session_id TEXT NOT NULL,\n            message JSONB NOT NULL\n        );\"\"\"\n        self.cursor.execute(create_table_query)\n        self.connection.commit()\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        \"\"\"Retrieve the messages from PostgreSQL\"\"\"\n        query = (\n            f\"SELECT message FROM {self.table_name} WHERE session_id = %s ORDER BY id;\"\n        )\n        self.cursor.execute(query, (self.session_id,))\n        items = [record[\"message\"] for record in self.cursor.fetchall()]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html"}
{"id": "6f9ce0f02c0a-1", "text": "items = [record[\"message\"] for record in self.cursor.fetchall()]\n        messages = messages_from_dict(items)\n        return messages\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Append the message to the record in PostgreSQL\"\"\"\n        from psycopg import sql\n        query = sql.SQL(\"INSERT INTO {} (session_id, message) VALUES (%s, %s);\").format(\n            sql.Identifier(self.table_name)\n        )\n        self.cursor.execute(\n            query, (self.session_id, json.dumps(_message_to_dict(message)))\n        )\n        self.connection.commit()\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory from PostgreSQL\"\"\"\n        query = f\"DELETE FROM {self.table_name} WHERE session_id = %s;\"\n        self.cursor.execute(query, (self.session_id,))\n        self.connection.commit()\n    def __del__(self) -> None:\n        if self.cursor:\n            self.cursor.close()\n        if self.connection:\n            self.connection.close()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html"}
{"id": "896bd78b095f-0", "text": "Source code for langchain.memory.chat_message_histories.file\nimport json\nimport logging\nfrom pathlib import Path\nfrom typing import List\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage, messages_from_dict, messages_to_dict\nlogger = logging.getLogger(__name__)\n[docs]class FileChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"\n    Chat message history that stores history in a local file.\n    Args:\n        file_path: path of the local file to store the messages.\n    \"\"\"\n[docs]    def __init__(self, file_path: str):\n        self.file_path = Path(file_path)\n        if not self.file_path.exists():\n            self.file_path.touch()\n            self.file_path.write_text(json.dumps([]))\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        \"\"\"Retrieve the messages from the local file\"\"\"\n        items = json.loads(self.file_path.read_text())\n        messages = messages_from_dict(items)\n        return messages\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Append the message to the record in the local file\"\"\"\n        messages = messages_to_dict(self.messages)\n        messages.append(messages_to_dict([message])[0])\n        self.file_path.write_text(json.dumps(messages))\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory from the local file\"\"\"\n        self.file_path.write_text(json.dumps([]))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html"}
{"id": "56393c1a38d8-0", "text": "Source code for langchain.memory.chat_message_histories.singlestoredb\nimport json\nimport logging\nimport re\nfrom typing import (\n    Any,\n    List,\n)\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict\nlogger = logging.getLogger(__name__)\n[docs]class SingleStoreDBChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history stored in a SingleStoreDB database.\"\"\"\n[docs]    def __init__(\n        self,\n        session_id: str,\n        *,\n        table_name: str = \"message_store\",\n        id_field: str = \"id\",\n        session_id_field: str = \"session_id\",\n        message_field: str = \"message\",\n        pool_size: int = 5,\n        max_overflow: int = 10,\n        timeout: float = 30,\n        **kwargs: Any,\n    ):\n        \"\"\"Initialize with necessary components.\n        Args:\n            table_name (str, optional): Specifies the name of the table in use.\n                Defaults to \"message_store\".\n            id_field (str, optional): Specifies the name of the id field in the table.\n                Defaults to \"id\".\n            session_id_field (str, optional): Specifies the name of the session_id\n                field in the table. Defaults to \"session_id\".\n            message_field (str, optional): Specifies the name of the message field\n                in the table. Defaults to \"message\".\n            Following arguments pertain to the connection pool:\n            pool_size (int, optional): Determines the number of active connections in\n                the pool. Defaults to 5.\n            max_overflow (int, optional): Determines the maximum number of connections", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/singlestoredb.html"}
{"id": "56393c1a38d8-1", "text": "max_overflow (int, optional): Determines the maximum number of connections\n                allowed beyond the pool_size. Defaults to 10.\n            timeout (float, optional): Specifies the maximum wait time in seconds for\n                establishing a connection. Defaults to 30.\n            Following arguments pertain to the database connection:\n            host (str, optional): Specifies the hostname, IP address, or URL for the\n                database connection. The default scheme is \"mysql\".\n            user (str, optional): Database username.\n            password (str, optional): Database password.\n            port (int, optional): Database port. Defaults to 3306 for non-HTTP\n                connections, 80 for HTTP connections, and 443 for HTTPS connections.\n            database (str, optional): Database name.\n            Additional optional arguments provide further customization over the\n            database connection:\n            pure_python (bool, optional): Toggles the connector mode. If True,\n                operates in pure Python mode.\n            local_infile (bool, optional): Allows local file uploads.\n            charset (str, optional): Specifies the character set for string values.\n            ssl_key (str, optional): Specifies the path of the file containing the SSL\n                key.\n            ssl_cert (str, optional): Specifies the path of the file containing the SSL\n                certificate.\n            ssl_ca (str, optional): Specifies the path of the file containing the SSL\n                certificate authority.\n            ssl_cipher (str, optional): Sets the SSL cipher list.\n            ssl_disabled (bool, optional): Disables SSL usage.\n            ssl_verify_cert (bool, optional): Verifies the server's certificate.\n                Automatically enabled if ``ssl_ca`` is specified.\n            ssl_verify_identity (bool, optional): Verifies the server's identity.\n            conv (dict[int, Callable], optional): A dictionary of data conversion", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/singlestoredb.html"}
{"id": "56393c1a38d8-2", "text": "conv (dict[int, Callable], optional): A dictionary of data conversion\n                functions.\n            credential_type (str, optional): Specifies the type of authentication to\n                use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.\n            autocommit (bool, optional): Enables autocommits.\n            results_type (str, optional): Determines the structure of the query results:\n                tuples, namedtuples, dicts.\n            results_format (str, optional): Deprecated. This option has been renamed to\n                results_type.\n        Examples:\n            Basic Usage:\n            .. code-block:: python\n                from langchain.memory.chat_message_histories import (\n                    SingleStoreDBChatMessageHistory\n                )\n                message_history = SingleStoreDBChatMessageHistory(\n                    session_id=\"my-session\",\n                    host=\"https://user:password@127.0.0.1:3306/database\"\n                )\n            Advanced Usage:\n            .. code-block:: python\n                from langchain.memory.chat_message_histories import (\n                    SingleStoreDBChatMessageHistory\n                )\n                message_history = SingleStoreDBChatMessageHistory(\n                    session_id=\"my-session\",\n                    host=\"127.0.0.1\",\n                    port=3306,\n                    user=\"user\",\n                    password=\"password\",\n                    database=\"db\",\n                    table_name=\"my_custom_table\",\n                    pool_size=10,\n                    timeout=60,\n                )\n            Using environment variables:\n            .. code-block:: python\n                from langchain.memory.chat_message_histories import (\n                    SingleStoreDBChatMessageHistory\n                )\n                os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'\n                message_history = SingleStoreDBChatMessageHistory(\"my-session\")\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/singlestoredb.html"}
{"id": "56393c1a38d8-3", "text": "message_history = SingleStoreDBChatMessageHistory(\"my-session\")\n        \"\"\"\n        self.table_name = self._sanitize_input(table_name)\n        self.session_id = self._sanitize_input(session_id)\n        self.id_field = self._sanitize_input(id_field)\n        self.session_id_field = self._sanitize_input(session_id_field)\n        self.message_field = self._sanitize_input(message_field)\n        # Pass the rest of the kwargs to the connection.\n        self.connection_kwargs = kwargs\n        # Add connection attributes to the connection kwargs.\n        if \"conn_attrs\" not in self.connection_kwargs:\n            self.connection_kwargs[\"conn_attrs\"] = dict()\n        self.connection_kwargs[\"conn_attrs\"][\"_connector_name\"] = \"langchain python sdk\"\n        self.connection_kwargs[\"conn_attrs\"][\"_connector_version\"] = \"1.0.1\"\n        # Create a connection pool.\n        try:\n            from sqlalchemy.pool import QueuePool\n        except ImportError:\n            raise ImportError(\n                \"Could not import sqlalchemy.pool python package. \"\n                \"Please install it with `pip install singlestoredb`.\"\n            )\n        self.connection_pool = QueuePool(\n            self._get_connection,\n            max_overflow=max_overflow,\n            pool_size=pool_size,\n            timeout=timeout,\n        )\n        self.table_created = False\n    def _sanitize_input(self, input_str: str) -> str:\n        # Remove characters that are not alphanumeric or underscores\n        return re.sub(r\"[^a-zA-Z0-9_]\", \"\", input_str)\n    def _get_connection(self) -> Any:\n        try:\n            import singlestoredb as s2\n        except ImportError:\n            raise ImportError(\n                \"Could not import singlestoredb python package. \"\n                \"Please install it with `pip install singlestoredb`.\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/singlestoredb.html"}
{"id": "56393c1a38d8-4", "text": "\"Please install it with `pip install singlestoredb`.\"\n            )\n        return s2.connect(**self.connection_kwargs)\n    def _create_table_if_not_exists(self) -> None:\n        \"\"\"Create table if it doesn't exist.\"\"\"\n        if self.table_created:\n            return\n        conn = self.connection_pool.connect()\n        try:\n            cur = conn.cursor()\n            try:\n                cur.execute(\n                    \"\"\"CREATE TABLE IF NOT EXISTS {}\n                    ({} BIGINT PRIMARY KEY AUTO_INCREMENT,\n                    {} TEXT NOT NULL,\n                    {} JSON NOT NULL);\"\"\".format(\n                        self.table_name,\n                        self.id_field,\n                        self.session_id_field,\n                        self.message_field,\n                    ),\n                )\n                self.table_created = True\n            finally:\n                cur.close()\n        finally:\n            conn.close()\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        \"\"\"Retrieve the messages from SingleStoreDB\"\"\"\n        self._create_table_if_not_exists()\n        conn = self.connection_pool.connect()\n        items = []\n        try:\n            cur = conn.cursor()\n            try:\n                cur.execute(\n                    \"\"\"SELECT {} FROM {} WHERE {} = %s\"\"\".format(\n                        self.message_field,\n                        self.table_name,\n                        self.session_id_field,\n                    ),\n                    (self.session_id),\n                )\n                for row in cur.fetchall():\n                    items.append(row[0])\n            finally:\n                cur.close()\n        finally:\n            conn.close()\n        messages = messages_from_dict(items)\n        return messages\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Append the message to the record in SingleStoreDB\"\"\"\n        self._create_table_if_not_exists()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/singlestoredb.html"}
{"id": "56393c1a38d8-5", "text": "self._create_table_if_not_exists()\n        conn = self.connection_pool.connect()\n        try:\n            cur = conn.cursor()\n            try:\n                cur.execute(\n                    \"\"\"INSERT INTO {} ({}, {}) VALUES (%s, %s)\"\"\".format(\n                        self.table_name,\n                        self.session_id_field,\n                        self.message_field,\n                    ),\n                    (self.session_id, json.dumps(_message_to_dict(message))),\n                )\n            finally:\n                cur.close()\n        finally:\n            conn.close()\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory from SingleStoreDB\"\"\"\n        self._create_table_if_not_exists()\n        conn = self.connection_pool.connect()\n        try:\n            cur = conn.cursor()\n            try:\n                cur.execute(\n                    \"\"\"DELETE FROM {} WHERE {} = %s\"\"\".format(\n                        self.table_name,\n                        self.session_id_field,\n                    ),\n                    (self.session_id),\n                )\n            finally:\n                cur.close()\n        finally:\n            conn.close()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/singlestoredb.html"}
{"id": "b5295fc1031b-0", "text": "Source code for langchain.memory.chat_message_histories.firestore\n\"\"\"Firestore Chat Message History.\"\"\"\nfrom __future__ import annotations\nimport logging\nfrom typing import TYPE_CHECKING, List, Optional\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage, messages_from_dict, messages_to_dict\nlogger = logging.getLogger(__name__)\nif TYPE_CHECKING:\n    from google.cloud.firestore import Client, DocumentReference\ndef _get_firestore_client() -> Client:\n    try:\n        import firebase_admin\n        from firebase_admin import firestore\n    except ImportError:\n        raise ImportError(\n            \"Could not import firebase-admin python package. \"\n            \"Please install it with `pip install firebase-admin`.\"\n        )\n    # For multiple instances, only initialize the app once.\n    try:\n        firebase_admin.get_app()\n    except ValueError as e:\n        logger.debug(\"Initializing Firebase app: %s\", e)\n        firebase_admin.initialize_app()\n    return firestore.client()\n[docs]class FirestoreChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history backed by Google Firestore.\"\"\"\n[docs]    def __init__(\n        self,\n        collection_name: str,\n        session_id: str,\n        user_id: str,\n        firestore_client: Optional[Client] = None,\n    ):\n        \"\"\"\n        Initialize a new instance of the FirestoreChatMessageHistory class.\n        :param collection_name: The name of the collection to use.\n        :param session_id: The session ID for the chat..\n        :param user_id: The user ID for the chat.\n        \"\"\"\n        self.collection_name = collection_name\n        self.session_id = session_id\n        self.user_id = user_id\n        self._document: Optional[DocumentReference] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/firestore.html"}
{"id": "b5295fc1031b-1", "text": "self._document: Optional[DocumentReference] = None\n        self.messages: List[BaseMessage] = []\n        self.firestore_client = firestore_client or _get_firestore_client()\n        self.prepare_firestore()\n[docs]    def prepare_firestore(self) -> None:\n        \"\"\"Prepare the Firestore client.\n        Use this function to make sure your database is ready.\n        \"\"\"\n        self._document = self.firestore_client.collection(\n            self.collection_name\n        ).document(self.session_id)\n        self.load_messages()\n[docs]    def load_messages(self) -> None:\n        \"\"\"Retrieve the messages from Firestore\"\"\"\n        if not self._document:\n            raise ValueError(\"Document not initialized\")\n        doc = self._document.get()\n        if doc.exists:\n            data = doc.to_dict()\n            if \"messages\" in data and len(data[\"messages\"]) > 0:\n                self.messages = messages_from_dict(data[\"messages\"])\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        self.messages.append(message)\n        self.upsert_messages()\n[docs]    def upsert_messages(self, new_message: Optional[BaseMessage] = None) -> None:\n        \"\"\"Update the Firestore document.\"\"\"\n        if not self._document:\n            raise ValueError(\"Document not initialized\")\n        self._document.set(\n            {\n                \"id\": self.session_id,\n                \"user_id\": self.user_id,\n                \"messages\": messages_to_dict(self.messages),\n            }\n        )\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory from this memory and Firestore.\"\"\"\n        self.messages = []\n        if self._document:\n            self._document.delete()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/firestore.html"}
{"id": "a6e7c4ceddd3-0", "text": "Source code for langchain.memory.chat_message_histories.sql\nimport json\nimport logging\nfrom abc import ABC, abstractmethod\nfrom typing import Any, List, Optional\nfrom sqlalchemy import Column, Integer, Text, create_engine\ntry:\n    from sqlalchemy.orm import declarative_base\nexcept ImportError:\n    from sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict\nlogger = logging.getLogger(__name__)\n[docs]class BaseMessageConverter(ABC):\n    \"\"\"The class responsible for converting BaseMessage to your SQLAlchemy model.\"\"\"\n[docs]    @abstractmethod\n    def from_sql_model(self, sql_message: Any) -> BaseMessage:\n        \"\"\"Convert a SQLAlchemy model to a BaseMessage instance.\"\"\"\n        raise NotImplementedError\n[docs]    @abstractmethod\n    def to_sql_model(self, message: BaseMessage, session_id: str) -> Any:\n        \"\"\"Convert a BaseMessage instance to a SQLAlchemy model.\"\"\"\n        raise NotImplementedError\n[docs]    @abstractmethod\n    def get_sql_model_class(self) -> Any:\n        \"\"\"Get the SQLAlchemy model class.\"\"\"\n        raise NotImplementedError\n[docs]def create_message_model(table_name, DynamicBase):  # type: ignore\n    \"\"\"\n    Create a message model for a given table name.\n    Args:\n        table_name: The name of the table to use.\n        DynamicBase: The base class to use for the model.\n    Returns:\n        The model class.\n    \"\"\"\n    # Model decleared inside a function to have a dynamic table name\n    class Message(DynamicBase):\n        __tablename__ = table_name\n        id = Column(Integer, primary_key=True)\n        session_id = Column(Text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html"}
{"id": "a6e7c4ceddd3-1", "text": "id = Column(Integer, primary_key=True)\n        session_id = Column(Text)\n        message = Column(Text)\n    return Message\n[docs]class DefaultMessageConverter(BaseMessageConverter):\n    \"\"\"The default message converter for SQLChatMessageHistory.\"\"\"\n[docs]    def __init__(self, table_name: str):\n        self.model_class = create_message_model(table_name, declarative_base())\n[docs]    def from_sql_model(self, sql_message: Any) -> BaseMessage:\n        return messages_from_dict([json.loads(sql_message.message)])[0]\n[docs]    def to_sql_model(self, message: BaseMessage, session_id: str) -> Any:\n        return self.model_class(\n            session_id=session_id, message=json.dumps(_message_to_dict(message))\n        )\n[docs]    def get_sql_model_class(self) -> Any:\n        return self.model_class\n[docs]class SQLChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history stored in an SQL database.\"\"\"\n[docs]    def __init__(\n        self,\n        session_id: str,\n        connection_string: str,\n        table_name: str = \"message_store\",\n        session_id_field_name: str = \"session_id\",\n        custom_message_converter: Optional[BaseMessageConverter] = None,\n    ):\n        self.connection_string = connection_string\n        self.engine = create_engine(connection_string, echo=False)\n        self.session_id_field_name = session_id_field_name\n        self.converter = custom_message_converter or DefaultMessageConverter(table_name)\n        self.sql_model_class = self.converter.get_sql_model_class()\n        if not hasattr(self.sql_model_class, session_id_field_name):\n            raise ValueError(\"SQL model class must have session_id column\")\n        self._create_table_if_not_exists()\n        self.session_id = session_id", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html"}
{"id": "a6e7c4ceddd3-2", "text": "self._create_table_if_not_exists()\n        self.session_id = session_id\n        self.Session = sessionmaker(self.engine)\n    def _create_table_if_not_exists(self) -> None:\n        self.sql_model_class.metadata.create_all(self.engine)\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        \"\"\"Retrieve all messages from db\"\"\"\n        with self.Session() as session:\n            result = (\n                session.query(self.sql_model_class)\n                .where(\n                    getattr(self.sql_model_class, self.session_id_field_name)\n                    == self.session_id\n                )\n                .order_by(self.sql_model_class.id.asc())\n            )\n            messages = []\n            for record in result:\n                messages.append(self.converter.from_sql_model(record))\n            return messages\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Append the message to the record in db\"\"\"\n        with self.Session() as session:\n            session.add(self.converter.to_sql_model(message, self.session_id))\n            session.commit()\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory from db\"\"\"\n        with self.Session() as session:\n            session.query(self.sql_model_class).filter(\n                getattr(self.sql_model_class, self.session_id_field_name)\n                == self.session_id\n            ).delete()\n            session.commit()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html"}
{"id": "97c711df09c0-0", "text": "Source code for langchain.memory.chat_message_histories.mongodb\nimport json\nimport logging\nfrom typing import List\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict\nlogger = logging.getLogger(__name__)\nDEFAULT_DBNAME = \"chat_history\"\nDEFAULT_COLLECTION_NAME = \"message_store\"\n[docs]class MongoDBChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history that stores history in MongoDB.\n    Args:\n        connection_string: connection string to connect to MongoDB\n        session_id: arbitrary key that is used to store the messages\n            of a single chat session.\n        database_name: name of the database to use\n        collection_name: name of the collection to use\n    \"\"\"\n[docs]    def __init__(\n        self,\n        connection_string: str,\n        session_id: str,\n        database_name: str = DEFAULT_DBNAME,\n        collection_name: str = DEFAULT_COLLECTION_NAME,\n    ):\n        from pymongo import MongoClient, errors\n        self.connection_string = connection_string\n        self.session_id = session_id\n        self.database_name = database_name\n        self.collection_name = collection_name\n        try:\n            self.client: MongoClient = MongoClient(connection_string)\n        except errors.ConnectionFailure as error:\n            logger.error(error)\n        self.db = self.client[database_name]\n        self.collection = self.db[collection_name]\n        self.collection.create_index(\"SessionId\")\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        \"\"\"Retrieve the messages from MongoDB\"\"\"\n        from pymongo import errors\n        try:\n            cursor = self.collection.find({\"SessionId\": self.session_id})\n        except errors.OperationFailure as error:\n            logger.error(error)\n        if cursor:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html"}
{"id": "97c711df09c0-1", "text": "except errors.OperationFailure as error:\n            logger.error(error)\n        if cursor:\n            items = [json.loads(document[\"History\"]) for document in cursor]\n        else:\n            items = []\n        messages = messages_from_dict(items)\n        return messages\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Append the message to the record in MongoDB\"\"\"\n        from pymongo import errors\n        try:\n            self.collection.insert_one(\n                {\n                    \"SessionId\": self.session_id,\n                    \"History\": json.dumps(_message_to_dict(message)),\n                }\n            )\n        except errors.WriteError as err:\n            logger.error(err)\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory from MongoDB\"\"\"\n        from pymongo import errors\n        try:\n            self.collection.delete_many({\"SessionId\": self.session_id})\n        except errors.WriteError as err:\n            logger.error(err)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html"}
{"id": "b5faf7a4c7c5-0", "text": "Source code for langchain.memory.chat_message_histories.upstash_redis\nimport json\nimport logging\nfrom typing import List, Optional\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict\nlogger = logging.getLogger(__name__)\n[docs]class UpstashRedisChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history stored in an Upstash Redis database.\"\"\"\n[docs]    def __init__(\n        self,\n        session_id: str,\n        url: str = \"\",\n        token: str = \"\",\n        key_prefix: str = \"message_store:\",\n        ttl: Optional[int] = None,\n    ):\n        try:\n            from upstash_redis import Redis\n        except ImportError:\n            raise ImportError(\n                \"Could not import upstash redis python package. \"\n                \"Please install it with `pip install upstash_redis`.\"\n            )\n        if url == \"\" or token == \"\":\n            raise ValueError(\n                \"UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN are needed.\"\n            )\n        try:\n            self.redis_client = Redis(url=url, token=token)\n        except Exception:\n            logger.error(\"Upstash Redis instance could not be initiated.\")\n        self.session_id = session_id\n        self.key_prefix = key_prefix\n        self.ttl = ttl\n    @property\n    def key(self) -> str:\n        \"\"\"Construct the record key to use\"\"\"\n        return self.key_prefix + self.session_id\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        \"\"\"Retrieve the messages from Upstash Redis\"\"\"\n        _items = self.redis_client.lrange(self.key, 0, -1)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/upstash_redis.html"}
{"id": "b5faf7a4c7c5-1", "text": "_items = self.redis_client.lrange(self.key, 0, -1)\n        items = [json.loads(m) for m in _items[::-1]]\n        messages = messages_from_dict(items)\n        return messages\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Append the message to the record in Upstash Redis\"\"\"\n        self.redis_client.lpush(self.key, json.dumps(_message_to_dict(message)))\n        if self.ttl:\n            self.redis_client.expire(self.key, self.ttl)\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory from Upstash Redis\"\"\"\n        self.redis_client.delete(self.key)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/upstash_redis.html"}
{"id": "5aeb50531ce9-0", "text": "Source code for langchain.memory.chat_message_histories.rocksetdb\nfrom datetime import datetime\nfrom time import sleep\nfrom typing import Any, Callable, List, Union\nfrom uuid import uuid4\nfrom langchain.schema import BaseChatMessageHistory\nfrom langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict\n[docs]class RocksetChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Uses Rockset to store chat messages.\n    To use, ensure that the `rockset` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.memory.chat_message_histories import (\n                RocksetChatMessageHistory\n            )\n            from rockset import RocksetClient\n            history = RocksetChatMessageHistory(\n                session_id=\"MySession\",\n                client=RocksetClient(),\n                collection=\"langchain_demo\",\n                sync=True\n            )\n            history.add_user_message(\"hi!\")\n            history.add_ai_message(\"whats up?\")\n            print(history.messages)\n    \"\"\"\n    # You should set these values based on your VI.\n    # These values are configured for the typical\n    # free VI. Read more about VIs here:\n    # https://rockset.com/docs/instances\n    SLEEP_INTERVAL_MS: int = 5\n    ADD_TIMEOUT_MS: int = 5000\n    CREATE_TIMEOUT_MS: int = 20000\n    def _wait_until(self, method: Callable, timeout: int, **method_params: Any) -> None:\n        \"\"\"Sleeps until meth() evaluates to true. Passes kwargs into\n        meth.\n        \"\"\"\n        start = datetime.now()\n        while not method(**method_params):\n            curr = datetime.now()\n            if (curr - start).total_seconds() * 1000 > timeout:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html"}
{"id": "5aeb50531ce9-1", "text": "if (curr - start).total_seconds() * 1000 > timeout:\n                raise TimeoutError(f\"{method} timed out at {timeout} ms\")\n            sleep(RocksetChatMessageHistory.SLEEP_INTERVAL_MS / 1000)\n    def _query(self, query: str, **query_params: Any) -> List[Any]:\n        \"\"\"Executes an SQL statement and returns the result\n        Args:\n            - query: The SQL string\n            - **query_params: Parameters to pass into the query\n        \"\"\"\n        return self.client.sql(query, params=query_params).results\n    def _create_collection(self) -> None:\n        \"\"\"Creates a collection for this message history\"\"\"\n        self.client.Collections.create_s3_collection(\n            name=self.collection, workspace=self.workspace\n        )\n    def _collection_exists(self) -> bool:\n        \"\"\"Checks whether a collection exists for this message history\"\"\"\n        try:\n            self.client.Collections.get(collection=self.collection)\n        except self.rockset.exceptions.NotFoundException:\n            return False\n        return True\n    def _collection_is_ready(self) -> bool:\n        \"\"\"Checks whether the collection for this message history is ready\n        to be queried\n        \"\"\"\n        return (\n            self.client.Collections.get(collection=self.collection).data.status\n            == \"READY\"\n        )\n    def _document_exists(self) -> bool:\n        return (\n            len(\n                self._query(\n                    f\"\"\"\n                        SELECT 1\n                        FROM {self.location} \n                        WHERE _id=:session_id\n                        LIMIT 1\n                    \"\"\",\n                    session_id=self.session_id,\n                )\n            )\n            != 0\n        )\n    def _wait_until_collection_created(self) -> None:\n        \"\"\"Sleeps until the collection for this message history is ready\n        to be queried", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html"}
{"id": "5aeb50531ce9-2", "text": "\"\"\"Sleeps until the collection for this message history is ready\n        to be queried\n        \"\"\"\n        self._wait_until(\n            lambda: self._collection_is_ready(),\n            RocksetChatMessageHistory.CREATE_TIMEOUT_MS,\n        )\n    def _wait_until_message_added(self, message_id: str) -> None:\n        \"\"\"Sleeps until a message is added to the messages list\"\"\"\n        self._wait_until(\n            lambda message_id: len(\n                self._query(\n                    f\"\"\"\n                        SELECT * \n                        FROM UNNEST((\n                            SELECT {self.messages_key}\n                            FROM {self.location}\n                            WHERE _id = :session_id\n                        )) AS message\n                        WHERE message.data.additional_kwargs.id = :message_id\n                        LIMIT 1\n                    \"\"\",\n                    session_id=self.session_id,\n                    message_id=message_id,\n                ),\n            )\n            != 0,\n            RocksetChatMessageHistory.ADD_TIMEOUT_MS,\n            message_id=message_id,\n        )\n    def _create_empty_doc(self) -> None:\n        \"\"\"Creates or replaces a document for this message history with no\n        messages\"\"\"\n        self.client.Documents.add_documents(\n            collection=self.collection,\n            workspace=self.workspace,\n            data=[{\"_id\": self.session_id, self.messages_key: []}],\n        )\n[docs]    def __init__(\n        self,\n        session_id: str,\n        client: Any,\n        collection: str,\n        workspace: str = \"commons\",\n        messages_key: str = \"messages\",\n        sync: bool = False,\n        message_uuid_method: Callable[[], Union[str, int]] = lambda: str(uuid4()),\n    ) -> None:\n        \"\"\"Constructs a new RocksetChatMessageHistory.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html"}
{"id": "5aeb50531ce9-3", "text": "\"\"\"Constructs a new RocksetChatMessageHistory.\n        Args:\n            - session_id: The ID of the chat session\n            - client: The RocksetClient object to use to query\n            - collection: The name of the collection to use to store chat\n                          messages. If a collection with the given name\n                          does not exist in the workspace, it is created.\n            - workspace: The workspace containing `collection`. Defaults\n                         to `\"commons\"`\n            - messages_key: The DB column containing message history.\n                            Defaults to `\"messages\"`\n            - sync: Whether to wait for messages to be added. Defaults\n                    to `False`. NOTE: setting this to `True` will slow\n                    down performance.\n            - message_uuid_method: The method that generates message IDs.\n                    If set, all messages will have an `id` field within the\n                    `additional_kwargs` property. If this param is not set\n                    and `sync` is `False`, message IDs will not be created.\n                    If this param is not set and `sync` is `True`, the\n                    `uuid.uuid4` method will be used to create message IDs.\n        \"\"\"\n        try:\n            import rockset\n        except ImportError:\n            raise ImportError(\n                \"Could not import rockset client python package. \"\n                \"Please install it with `pip install rockset`.\"\n            )\n        if not isinstance(client, rockset.RocksetClient):\n            raise ValueError(\n                f\"client should be an instance of rockset.RocksetClient, \"\n                f\"got {type(client)}\"\n            )\n        self.session_id = session_id\n        self.client = client\n        self.collection = collection\n        self.workspace = workspace\n        self.location = f'\"{self.workspace}\".\"{self.collection}\"'", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html"}
{"id": "5aeb50531ce9-4", "text": "self.location = f'\"{self.workspace}\".\"{self.collection}\"'\n        self.rockset = rockset\n        self.messages_key = messages_key\n        self.message_uuid_method = message_uuid_method\n        self.sync = sync\n        try:\n            self.client.set_application(\"langchain\")\n        except AttributeError:\n            # ignore\n            pass\n        if not self._collection_exists():\n            self._create_collection()\n            self._wait_until_collection_created()\n            self._create_empty_doc()\n        elif not self._document_exists():\n            self._create_empty_doc()\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        \"\"\"Messages in this chat history.\"\"\"\n        return messages_from_dict(\n            self._query(\n                f\"\"\"\n                    SELECT *\n                    FROM UNNEST ((\n                        SELECT \"{self.messages_key}\"\n                        FROM {self.location}\n                        WHERE _id = :session_id\n                    ))\n                \"\"\",\n                session_id=self.session_id,\n            )\n        )\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Add a Message object to the history.\n        Args:\n            message: A BaseMessage object to store.\n        \"\"\"\n        if self.sync and \"id\" not in message.additional_kwargs:\n            message.additional_kwargs[\"id\"] = self.message_uuid_method()\n        self.client.Documents.patch_documents(\n            collection=self.collection,\n            workspace=self.workspace,\n            data=[\n                self.rockset.model.patch_document.PatchDocument(\n                    id=self.session_id,\n                    patch=[\n                        self.rockset.model.patch_operation.PatchOperation(\n                            op=\"ADD\",\n                            path=f\"/{self.messages_key}/-\",\n                            value=_message_to_dict(message),\n                        )\n                    ],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html"}
{"id": "5aeb50531ce9-5", "text": "value=_message_to_dict(message),\n                        )\n                    ],\n                )\n            ],\n        )\n        if self.sync:\n            self._wait_until_message_added(message.additional_kwargs[\"id\"])\n[docs]    def clear(self) -> None:\n        \"\"\"Removes all messages from the chat history\"\"\"\n        self._create_empty_doc()\n        if self.sync:\n            self._wait_until(\n                lambda: not self.messages,\n                RocksetChatMessageHistory.ADD_TIMEOUT_MS,\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html"}
{"id": "9082a30b07fd-0", "text": "Source code for langchain.memory.chat_message_histories.elasticsearch\nimport json\nimport logging\nfrom time import time\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional\nfrom langchain.schema import BaseChatMessageHistory\nfrom langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict\nif TYPE_CHECKING:\n    from elasticsearch import Elasticsearch\nlogger = logging.getLogger(__name__)\n[docs]class ElasticsearchChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history that stores history in Elasticsearch.\n    Args:\n        es_url: URL of the Elasticsearch instance to connect to.\n        es_cloud_id: Cloud ID of the Elasticsearch instance to connect to.\n        es_user: Username to use when connecting to Elasticsearch.\n        es_password: Password to use when connecting to Elasticsearch.\n        es_api_key: API key to use when connecting to Elasticsearch.\n        es_connection: Optional pre-existing Elasticsearch connection.\n        index: Name of the index to use.\n        session_id: Arbitrary key that is used to store the messages\n            of a single chat session.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        index: str,\n        session_id: str,\n        *,\n        es_connection: Optional[\"Elasticsearch\"] = None,\n        es_url: Optional[str] = None,\n        es_cloud_id: Optional[str] = None,\n        es_user: Optional[str] = None,\n        es_api_key: Optional[str] = None,\n        es_password: Optional[str] = None,\n    ):\n        self.index: str = index\n        self.session_id: str = session_id\n        # Initialize Elasticsearch client from passed client arg or connection info\n        if es_connection is not None:\n            self.client = es_connection.options(\n                headers={\"user-agent\": self.get_user_agent()}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/elasticsearch.html"}
{"id": "9082a30b07fd-1", "text": "headers={\"user-agent\": self.get_user_agent()}\n            )\n        elif es_url is not None or es_cloud_id is not None:\n            self.client = ElasticsearchChatMessageHistory.connect_to_elasticsearch(\n                es_url=es_url,\n                username=es_user,\n                password=es_password,\n                cloud_id=es_cloud_id,\n                api_key=es_api_key,\n            )\n        else:\n            raise ValueError(\n                \"\"\"Either provide a pre-existing Elasticsearch connection, \\\n                or valid credentials for creating a new connection.\"\"\"\n            )\n        if self.client.indices.exists(index=index):\n            logger.debug(\n                f\"Chat history index {index} already exists, skipping creation.\"\n            )\n        else:\n            logger.debug(f\"Creating index {index} for storing chat history.\")\n            self.client.indices.create(\n                index=index,\n                mappings={\n                    \"properties\": {\n                        \"session_id\": {\"type\": \"keyword\"},\n                        \"created_at\": {\"type\": \"date\"},\n                        \"history\": {\"type\": \"text\"},\n                    }\n                },\n            )\n[docs]    @staticmethod\n    def get_user_agent() -> str:\n        from langchain import __version__\n        return f\"langchain-py-ms/{__version__}\"\n[docs]    @staticmethod\n    def connect_to_elasticsearch(\n        *,\n        es_url: Optional[str] = None,\n        cloud_id: Optional[str] = None,\n        api_key: Optional[str] = None,\n        username: Optional[str] = None,\n        password: Optional[str] = None,\n    ) -> \"Elasticsearch\":\n        try:\n            import elasticsearch\n        except ImportError:\n            raise ImportError(\n                \"Could not import elasticsearch python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/elasticsearch.html"}
{"id": "9082a30b07fd-2", "text": "raise ImportError(\n                \"Could not import elasticsearch python package. \"\n                \"Please install it with `pip install elasticsearch`.\"\n            )\n        if es_url and cloud_id:\n            raise ValueError(\n                \"Both es_url and cloud_id are defined. Please provide only one.\"\n            )\n        connection_params: Dict[str, Any] = {}\n        if es_url:\n            connection_params[\"hosts\"] = [es_url]\n        elif cloud_id:\n            connection_params[\"cloud_id\"] = cloud_id\n        else:\n            raise ValueError(\"Please provide either elasticsearch_url or cloud_id.\")\n        if api_key:\n            connection_params[\"api_key\"] = api_key\n        elif username and password:\n            connection_params[\"basic_auth\"] = (username, password)\n        es_client = elasticsearch.Elasticsearch(\n            **connection_params,\n            headers={\"user-agent\": ElasticsearchChatMessageHistory.get_user_agent()},\n        )\n        try:\n            es_client.info()\n        except Exception as err:\n            logger.error(f\"Error connecting to Elasticsearch: {err}\")\n            raise err\n        return es_client\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore[override]\n        \"\"\"Retrieve the messages from Elasticsearch\"\"\"\n        try:\n            from elasticsearch import ApiError\n            result = self.client.search(\n                index=self.index,\n                query={\"term\": {\"session_id\": self.session_id}},\n                sort=\"created_at:asc\",\n            )\n        except ApiError as err:\n            logger.error(f\"Could not retrieve messages from Elasticsearch: {err}\")\n            raise err\n        if result and len(result[\"hits\"][\"hits\"]) > 0:\n            items = [\n                json.loads(document[\"_source\"][\"history\"])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/elasticsearch.html"}
{"id": "9082a30b07fd-3", "text": "items = [\n                json.loads(document[\"_source\"][\"history\"])\n                for document in result[\"hits\"][\"hits\"]\n            ]\n        else:\n            items = []\n        return messages_from_dict(items)\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Add a message to the chat session in Elasticsearch\"\"\"\n        try:\n            from elasticsearch import ApiError\n            self.client.index(\n                index=self.index,\n                document={\n                    \"session_id\": self.session_id,\n                    \"created_at\": round(time() * 1000),\n                    \"history\": json.dumps(_message_to_dict(message)),\n                },\n                refresh=True,\n            )\n        except ApiError as err:\n            logger.error(f\"Could not add message to Elasticsearch: {err}\")\n            raise err\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory in Elasticsearch\"\"\"\n        try:\n            from elasticsearch import ApiError\n            self.client.delete_by_query(\n                index=self.index,\n                query={\"term\": {\"session_id\": self.session_id}},\n                refresh=True,\n            )\n        except ApiError as err:\n            logger.error(f\"Could not clear session memory in Elasticsearch: {err}\")\n            raise err", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/elasticsearch.html"}
{"id": "8c580c7bf577-0", "text": "Source code for langchain.memory.chat_message_histories.streamlit\nfrom typing import List\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage\n[docs]class StreamlitChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"\n    Chat message history that stores messages in Streamlit session state.\n    Args:\n        key: The key to use in Streamlit session state for storing messages.\n    \"\"\"\n[docs]    def __init__(self, key: str = \"langchain_messages\"):\n        try:\n            import streamlit as st\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import streamlit, please run `pip install streamlit`.\"\n            ) from e\n        if key not in st.session_state:\n            st.session_state[key] = []\n        self._messages = st.session_state[key]\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        \"\"\"Retrieve the current list of messages\"\"\"\n        return self._messages\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Add a message to the session memory\"\"\"\n        self._messages.append(message)\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory\"\"\"\n        self._messages.clear()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/streamlit.html"}
{"id": "cda58335f02f-0", "text": "Source code for langchain.memory.chat_message_histories.redis\nimport json\nimport logging\nfrom typing import List, Optional\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict\nfrom langchain.utilities.redis import get_client\nlogger = logging.getLogger(__name__)\n[docs]class RedisChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history stored in a Redis database.\"\"\"\n[docs]    def __init__(\n        self,\n        session_id: str,\n        url: str = \"redis://localhost:6379/0\",\n        key_prefix: str = \"message_store:\",\n        ttl: Optional[int] = None,\n    ):\n        try:\n            import redis\n        except ImportError:\n            raise ImportError(\n                \"Could not import redis python package. \"\n                \"Please install it with `pip install redis`.\"\n            )\n        try:\n            self.redis_client = get_client(redis_url=url)\n        except redis.exceptions.ConnectionError as error:\n            logger.error(error)\n        self.session_id = session_id\n        self.key_prefix = key_prefix\n        self.ttl = ttl\n    @property\n    def key(self) -> str:\n        \"\"\"Construct the record key to use\"\"\"\n        return self.key_prefix + self.session_id\n    @property\n    def messages(self) -> List[BaseMessage]:  # type: ignore\n        \"\"\"Retrieve the messages from Redis\"\"\"\n        _items = self.redis_client.lrange(self.key, 0, -1)\n        items = [json.loads(m.decode(\"utf-8\")) for m in _items[::-1]]\n        messages = messages_from_dict(items)\n        return messages\n[docs]    def add_message(self, message: BaseMessage) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html"}
{"id": "cda58335f02f-1", "text": "[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Append the message to the record in Redis\"\"\"\n        self.redis_client.lpush(self.key, json.dumps(_message_to_dict(message)))\n        if self.ttl:\n            self.redis_client.expire(self.key, self.ttl)\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory from Redis\"\"\"\n        self.redis_client.delete(self.key)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html"}
{"id": "f2df2cab9cb5-0", "text": "Source code for langchain.memory.chat_message_histories.cosmos_db\n\"\"\"Azure CosmosDB Memory History.\"\"\"\nfrom __future__ import annotations\nimport logging\nfrom types import TracebackType\nfrom typing import TYPE_CHECKING, Any, List, Optional, Type\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage, messages_from_dict, messages_to_dict\nlogger = logging.getLogger(__name__)\nif TYPE_CHECKING:\n    from azure.cosmos import ContainerProxy\n[docs]class CosmosDBChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history backed by Azure CosmosDB.\"\"\"\n[docs]    def __init__(\n        self,\n        cosmos_endpoint: str,\n        cosmos_database: str,\n        cosmos_container: str,\n        session_id: str,\n        user_id: str,\n        credential: Any = None,\n        connection_string: Optional[str] = None,\n        ttl: Optional[int] = None,\n        cosmos_client_kwargs: Optional[dict] = None,\n    ):\n        \"\"\"\n        Initializes a new instance of the CosmosDBChatMessageHistory class.\n        Make sure to call prepare_cosmos or use the context manager to make\n        sure your database is ready.\n        Either a credential or a connection string must be provided.\n        :param cosmos_endpoint: The connection endpoint for the Azure Cosmos DB account.\n        :param cosmos_database: The name of the database to use.\n        :param cosmos_container: The name of the container to use.\n        :param session_id: The session ID to use, can be overwritten while loading.\n        :param user_id: The user ID to use, can be overwritten while loading.\n        :param credential: The credential to use to authenticate to Azure Cosmos DB.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html"}
{"id": "f2df2cab9cb5-1", "text": ":param credential: The credential to use to authenticate to Azure Cosmos DB.\n        :param connection_string: The connection string to use to authenticate.\n        :param ttl: The time to live (in seconds) to use for documents in the container.\n        :param cosmos_client_kwargs: Additional kwargs to pass to the CosmosClient.\n        \"\"\"\n        self.cosmos_endpoint = cosmos_endpoint\n        self.cosmos_database = cosmos_database\n        self.cosmos_container = cosmos_container\n        self.credential = credential\n        self.conn_string = connection_string\n        self.session_id = session_id\n        self.user_id = user_id\n        self.ttl = ttl\n        self.messages: List[BaseMessage] = []\n        try:\n            from azure.cosmos import (  # pylint: disable=import-outside-toplevel # noqa: E501\n                CosmosClient,\n            )\n        except ImportError as exc:\n            raise ImportError(\n                \"You must install the azure-cosmos package to use the CosmosDBChatMessageHistory.\"  # noqa: E501\n                \"Please install it with `pip install azure-cosmos`.\"\n            ) from exc\n        if self.credential:\n            self._client = CosmosClient(\n                url=self.cosmos_endpoint,\n                credential=self.credential,\n                **cosmos_client_kwargs or {},\n            )\n        elif self.conn_string:\n            self._client = CosmosClient.from_connection_string(\n                conn_str=self.conn_string,\n                **cosmos_client_kwargs or {},\n            )\n        else:\n            raise ValueError(\"Either a connection string or a credential must be set.\")\n        self._container: Optional[ContainerProxy] = None\n[docs]    def prepare_cosmos(self) -> None:\n        \"\"\"Prepare the CosmosDB client.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html"}
{"id": "f2df2cab9cb5-2", "text": "\"\"\"Prepare the CosmosDB client.\n        Use this function or the context manager to make sure your database is ready.\n        \"\"\"\n        try:\n            from azure.cosmos import (  # pylint: disable=import-outside-toplevel # noqa: E501\n                PartitionKey,\n            )\n        except ImportError as exc:\n            raise ImportError(\n                \"You must install the azure-cosmos package to use the CosmosDBChatMessageHistory.\"  # noqa: E501\n                \"Please install it with `pip install azure-cosmos`.\"\n            ) from exc\n        database = self._client.create_database_if_not_exists(self.cosmos_database)\n        self._container = database.create_container_if_not_exists(\n            self.cosmos_container,\n            partition_key=PartitionKey(\"/user_id\"),\n            default_ttl=self.ttl,\n        )\n        self.load_messages()\n    def __enter__(self) -> \"CosmosDBChatMessageHistory\":\n        \"\"\"Context manager entry point.\"\"\"\n        self._client.__enter__()\n        self.prepare_cosmos()\n        return self\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        traceback: Optional[TracebackType],\n    ) -> None:\n        \"\"\"Context manager exit\"\"\"\n        self.upsert_messages()\n        self._client.__exit__(exc_type, exc_val, traceback)\n[docs]    def load_messages(self) -> None:\n        \"\"\"Retrieve the messages from Cosmos\"\"\"\n        if not self._container:\n            raise ValueError(\"Container not initialized\")\n        try:\n            from azure.cosmos.exceptions import (  # pylint: disable=import-outside-toplevel # noqa: E501\n                CosmosHttpResponseError,\n            )\n        except ImportError as exc:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html"}
{"id": "f2df2cab9cb5-3", "text": "CosmosHttpResponseError,\n            )\n        except ImportError as exc:\n            raise ImportError(\n                \"You must install the azure-cosmos package to use the CosmosDBChatMessageHistory.\"  # noqa: E501\n                \"Please install it with `pip install azure-cosmos`.\"\n            ) from exc\n        try:\n            item = self._container.read_item(\n                item=self.session_id, partition_key=self.user_id\n            )\n        except CosmosHttpResponseError:\n            logger.info(\"no session found\")\n            return\n        if \"messages\" in item and len(item[\"messages\"]) > 0:\n            self.messages = messages_from_dict(item[\"messages\"])\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Add a self-created message to the store\"\"\"\n        self.messages.append(message)\n        self.upsert_messages()\n[docs]    def upsert_messages(self) -> None:\n        \"\"\"Update the cosmosdb item.\"\"\"\n        if not self._container:\n            raise ValueError(\"Container not initialized\")\n        self._container.upsert_item(\n            body={\n                \"id\": self.session_id,\n                \"user_id\": self.user_id,\n                \"messages\": messages_to_dict(self.messages),\n            }\n        )\n[docs]    def clear(self) -> None:\n        \"\"\"Clear session memory from this memory and cosmos.\"\"\"\n        self.messages = []\n        if self._container:\n            self._container.delete_item(\n                item=self.session_id, partition_key=self.user_id\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html"}
{"id": "8786fcfb3886-0", "text": "Source code for langchain.memory.chat_message_histories.momento\nfrom __future__ import annotations\nimport json\nfrom datetime import timedelta\nfrom typing import TYPE_CHECKING, Any, Optional\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict\nfrom langchain.utils import get_from_env\nif TYPE_CHECKING:\n    import momento\ndef _ensure_cache_exists(cache_client: momento.CacheClient, cache_name: str) -> None:\n    \"\"\"Create cache if it doesn't exist.\n    Raises:\n        SdkException: Momento service or network error\n        Exception: Unexpected response\n    \"\"\"\n    from momento.responses import CreateCache\n    create_cache_response = cache_client.create_cache(cache_name)\n    if isinstance(create_cache_response, CreateCache.Success) or isinstance(\n        create_cache_response, CreateCache.CacheAlreadyExists\n    ):\n        return None\n    elif isinstance(create_cache_response, CreateCache.Error):\n        raise create_cache_response.inner_exception\n    else:\n        raise Exception(f\"Unexpected response cache creation: {create_cache_response}\")\n[docs]class MomentoChatMessageHistory(BaseChatMessageHistory):\n    \"\"\"Chat message history cache that uses Momento as a backend.\n    See https://gomomento.com/\"\"\"\n[docs]    def __init__(\n        self,\n        session_id: str,\n        cache_client: momento.CacheClient,\n        cache_name: str,\n        *,\n        key_prefix: str = \"message_store:\",\n        ttl: Optional[timedelta] = None,\n        ensure_cache_exists: bool = True,\n    ):\n        \"\"\"Instantiate a chat message history cache that uses Momento as a backend.\n        Note: to instantiate the cache client passed to MomentoChatMessageHistory,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html"}
{"id": "8786fcfb3886-1", "text": "Note: to instantiate the cache client passed to MomentoChatMessageHistory,\n        you must have a Momento account at https://gomomento.com/.\n        Args:\n            session_id (str): The session ID to use for this chat session.\n            cache_client (CacheClient): The Momento cache client.\n            cache_name (str): The name of the cache to use to store the messages.\n            key_prefix (str, optional): The prefix to apply to the cache key.\n                Defaults to \"message_store:\".\n            ttl (Optional[timedelta], optional): The TTL to use for the messages.\n                Defaults to None, ie the default TTL of the cache will be used.\n            ensure_cache_exists (bool, optional): Create the cache if it doesn't exist.\n                Defaults to True.\n        Raises:\n            ImportError: Momento python package is not installed.\n            TypeError: cache_client is not of type momento.CacheClientObject\n        \"\"\"\n        try:\n            from momento import CacheClient\n            from momento.requests import CollectionTtl\n        except ImportError:\n            raise ImportError(\n                \"Could not import momento python package. \"\n                \"Please install it with `pip install momento`.\"\n            )\n        if not isinstance(cache_client, CacheClient):\n            raise TypeError(\"cache_client must be a momento.CacheClient object.\")\n        if ensure_cache_exists:\n            _ensure_cache_exists(cache_client, cache_name)\n        self.key = key_prefix + session_id\n        self.cache_client = cache_client\n        self.cache_name = cache_name\n        if ttl is not None:\n            self.ttl = CollectionTtl.of(ttl)\n        else:\n            self.ttl = CollectionTtl.from_cache_ttl()\n[docs]    @classmethod\n    def from_client_params(\n        cls,\n        session_id: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html"}
{"id": "8786fcfb3886-2", "text": "def from_client_params(\n        cls,\n        session_id: str,\n        cache_name: str,\n        ttl: timedelta,\n        *,\n        configuration: Optional[momento.config.Configuration] = None,\n        api_key: Optional[str] = None,\n        auth_token: Optional[str] = None,  # for backwards compatibility\n        **kwargs: Any,\n    ) -> MomentoChatMessageHistory:\n        \"\"\"Construct cache from CacheClient parameters.\"\"\"\n        try:\n            from momento import CacheClient, Configurations, CredentialProvider\n        except ImportError:\n            raise ImportError(\n                \"Could not import momento python package. \"\n                \"Please install it with `pip install momento`.\"\n            )\n        if configuration is None:\n            configuration = Configurations.Laptop.v1()\n        # Try checking `MOMENTO_AUTH_TOKEN` first for backwards compatibility\n        try:\n            api_key = auth_token or get_from_env(\"auth_token\", \"MOMENTO_AUTH_TOKEN\")\n        except ValueError:\n            api_key = api_key or get_from_env(\"api_key\", \"MOMENTO_API_KEY\")\n        credentials = CredentialProvider.from_string(api_key)\n        cache_client = CacheClient(configuration, credentials, default_ttl=ttl)\n        return cls(session_id, cache_client, cache_name, ttl=ttl, **kwargs)\n    @property\n    def messages(self) -> list[BaseMessage]:  # type: ignore[override]\n        \"\"\"Retrieve the messages from Momento.\n        Raises:\n            SdkException: Momento service or network error\n            Exception: Unexpected response\n        Returns:\n            list[BaseMessage]: List of cached messages\n        \"\"\"\n        from momento.responses import CacheListFetch\n        fetch_response = self.cache_client.list_fetch(self.cache_name, self.key)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html"}
{"id": "8786fcfb3886-3", "text": "fetch_response = self.cache_client.list_fetch(self.cache_name, self.key)\n        if isinstance(fetch_response, CacheListFetch.Hit):\n            items = [json.loads(m) for m in fetch_response.value_list_string]\n            return messages_from_dict(items)\n        elif isinstance(fetch_response, CacheListFetch.Miss):\n            return []\n        elif isinstance(fetch_response, CacheListFetch.Error):\n            raise fetch_response.inner_exception\n        else:\n            raise Exception(f\"Unexpected response: {fetch_response}\")\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Store a message in the cache.\n        Args:\n            message (BaseMessage): The message object to store.\n        Raises:\n            SdkException: Momento service or network error.\n            Exception: Unexpected response.\n        \"\"\"\n        from momento.responses import CacheListPushBack\n        item = json.dumps(_message_to_dict(message))\n        push_response = self.cache_client.list_push_back(\n            self.cache_name, self.key, item, ttl=self.ttl\n        )\n        if isinstance(push_response, CacheListPushBack.Success):\n            return None\n        elif isinstance(push_response, CacheListPushBack.Error):\n            raise push_response.inner_exception\n        else:\n            raise Exception(f\"Unexpected response: {push_response}\")\n[docs]    def clear(self) -> None:\n        \"\"\"Remove the session's messages from the cache.\n        Raises:\n            SdkException: Momento service or network error.\n            Exception: Unexpected response.\n        \"\"\"\n        from momento.responses import CacheDelete\n        delete_response = self.cache_client.delete(self.cache_name, self.key)\n        if isinstance(delete_response, CacheDelete.Success):\n            return None\n        elif isinstance(delete_response, CacheDelete.Error):\n            raise delete_response.inner_exception\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html"}
{"id": "8786fcfb3886-4", "text": "raise delete_response.inner_exception\n        else:\n            raise Exception(f\"Unexpected response: {delete_response}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html"}
{"id": "f94f450e8110-0", "text": "Source code for langchain.memory.chat_message_histories.in_memory\nfrom typing import List\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema import (\n    BaseChatMessageHistory,\n)\nfrom langchain.schema.messages import BaseMessage\n[docs]class ChatMessageHistory(BaseChatMessageHistory, BaseModel):\n    \"\"\"In memory implementation of chat message history.\n    Stores messages in an in memory list.\n    \"\"\"\n    messages: List[BaseMessage] = Field(default_factory=list)\n[docs]    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Add a self-created message to the store\"\"\"\n        self.messages.append(message)\n[docs]    def clear(self) -> None:\n        self.messages = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html"}
{"id": "86b5fd59dcdd-0", "text": "Source code for langchain.evaluation.schema\n\"\"\"Interfaces to be implemented by general evaluators.\"\"\"\nfrom __future__ import annotations\nimport asyncio\nimport logging\nfrom abc import ABC, abstractmethod\nfrom enum import Enum\nfrom functools import partial\nfrom typing import Any, Optional, Sequence, Tuple, Union\nfrom warnings import warn\nfrom langchain.chains.base import Chain\nfrom langchain.schema.agent import AgentAction\nfrom langchain.schema.language_model import BaseLanguageModel\nlogger = logging.getLogger(__name__)\n[docs]class EvaluatorType(str, Enum):\n    \"\"\"The types of the evaluators.\"\"\"\n    QA = \"qa\"\n    \"\"\"Question answering evaluator, which grades answers to questions\n    directly using an LLM.\"\"\"\n    COT_QA = \"cot_qa\"\n    \"\"\"Chain of thought question answering evaluator, which grades\n    answers to questions using\n    chain of thought 'reasoning'.\"\"\"\n    CONTEXT_QA = \"context_qa\"\n    \"\"\"Question answering evaluator that incorporates 'context' in the response.\"\"\"\n    PAIRWISE_STRING = \"pairwise_string\"\n    \"\"\"The pairwise string evaluator, which predicts the preferred prediction from\n    between two models.\"\"\"\n    SCORE_STRING = \"score_string\"\n    \"\"\"The scored string evaluator, which gives a score between 1 and 10 \n    to a prediction.\"\"\"\n    LABELED_PAIRWISE_STRING = \"labeled_pairwise_string\"\n    \"\"\"The labeled pairwise string evaluator, which predicts the preferred prediction\n    from between two models based on a ground truth reference label.\"\"\"\n    LABELED_SCORE_STRING = \"labeled_score_string\"\n    \"\"\"The labeled scored string evaluator, which gives a score between 1 and 10\n    to a prediction based on a ground truth reference label.\"\"\"\n    AGENT_TRAJECTORY = \"trajectory\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html"}
{"id": "86b5fd59dcdd-1", "text": "AGENT_TRAJECTORY = \"trajectory\"\n    \"\"\"The agent trajectory evaluator, which grades the agent's intermediate steps.\"\"\"\n    CRITERIA = \"criteria\"\n    \"\"\"The criteria evaluator, which evaluates a model based on a\n    custom set of criteria without any reference labels.\"\"\"\n    LABELED_CRITERIA = \"labeled_criteria\"\n    \"\"\"The labeled criteria evaluator, which evaluates a model based on a\n    custom set of criteria, with a reference label.\"\"\"\n    STRING_DISTANCE = \"string_distance\"\n    \"\"\"Compare predictions to a reference answer using string edit distances.\"\"\"\n    EXACT_MATCH = \"exact_match\"\n    \"\"\"Compare predictions to a reference answer using exact matching.\"\"\"\n    REGEX_MATCH = \"regex_match\"\n    \"\"\"Compare predictions to a reference answer using regular expressions.\"\"\"\n    PAIRWISE_STRING_DISTANCE = \"pairwise_string_distance\"\n    \"\"\"Compare predictions based on string edit distances.\"\"\"\n    EMBEDDING_DISTANCE = \"embedding_distance\"\n    \"\"\"Compare a prediction to a reference label using embedding distance.\"\"\"\n    PAIRWISE_EMBEDDING_DISTANCE = \"pairwise_embedding_distance\"\n    \"\"\"Compare two predictions using embedding distance.\"\"\"\n    JSON_VALIDITY = \"json_validity\"\n    \"\"\"Check if a prediction is valid JSON.\"\"\"\n    JSON_EQUALITY = \"json_equality\"\n    \"\"\"Check if a prediction is equal to a reference JSON.\"\"\"\n    JSON_EDIT_DISTANCE = \"json_edit_distance\"\n    \"\"\"Compute the edit distance between two JSON strings after canonicalization.\"\"\"\n    JSON_SCHEMA_VALIDATION = \"json_schema_validation\"\n    \"\"\"Check if a prediction is valid JSON according to a JSON schema.\"\"\"\n[docs]class LLMEvalChain(Chain):\n    \"\"\"A base class for evaluators that use an LLM.\"\"\"\n[docs]    @classmethod\n    @abstractmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html"}
{"id": "86b5fd59dcdd-2", "text": "[docs]    @classmethod\n    @abstractmethod\n    def from_llm(cls, llm: BaseLanguageModel, **kwargs: Any) -> LLMEvalChain:\n        \"\"\"Create a new evaluator from an LLM.\"\"\"\nclass _EvalArgsMixin:\n    \"\"\"Mixin for checking evaluation arguments.\"\"\"\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"Whether this evaluator requires a reference label.\"\"\"\n        return False\n    @property\n    def requires_input(self) -> bool:\n        \"\"\"Whether this evaluator requires an input string.\"\"\"\n        return False\n    @property\n    def _skip_input_warning(self) -> str:\n        \"\"\"Warning to show when input is ignored.\"\"\"\n        return f\"Ignoring input in {self.__class__.__name__}, as it is not expected.\"\n    @property\n    def _skip_reference_warning(self) -> str:\n        \"\"\"Warning to show when reference is ignored.\"\"\"\n        return (\n            f\"Ignoring reference in {self.__class__.__name__}, as it is not expected.\"\n        )\n    def _check_evaluation_args(\n        self,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n    ) -> None:\n        \"\"\"Check if the evaluation arguments are valid.\n        Args:\n            reference (Optional[str], optional): The reference label.\n            input (Optional[str], optional): The input string.\n        Raises:\n            ValueError: If the evaluator requires an input string but none is provided,\n                or if the evaluator requires a reference label but none is provided.\n        \"\"\"\n        if self.requires_input and input is None:\n            raise ValueError(f\"{self.__class__.__name__} requires an input string.\")\n        elif input is not None and not self.requires_input:\n            warn(self._skip_input_warning)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html"}
{"id": "86b5fd59dcdd-3", "text": "warn(self._skip_input_warning)\n        if self.requires_reference and reference is None:\n            raise ValueError(f\"{self.__class__.__name__} requires a reference string.\")\n        elif reference is not None and not self.requires_reference:\n            warn(self._skip_reference_warning)\n[docs]class StringEvaluator(_EvalArgsMixin, ABC):\n    \"\"\"Grade, tag, or otherwise evaluate predictions relative to their inputs\n    and/or reference labels.\"\"\"\n    @property\n    def evaluation_name(self) -> str:\n        \"\"\"The name of the evaluation.\"\"\"\n        return self.__class__.__name__\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"Whether this evaluator requires a reference label.\"\"\"\n        return False\n    @abstractmethod\n    def _evaluate_strings(\n        self,\n        *,\n        prediction: Union[str, Any],\n        reference: Optional[Union[str, Any]] = None,\n        input: Optional[Union[str, Any]] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate Chain or LLM output, based on optional input and label.\n        Args:\n            prediction (str): The LLM or chain prediction to evaluate.\n            reference (Optional[str], optional): The reference label to evaluate against.\n            input (Optional[str], optional): The input to consider during evaluation.\n            **kwargs: Additional keyword arguments, including callbacks, tags, etc.\n        Returns:\n            dict: The evaluation results containing the score or value.\n                It is recommended that the dictionary contain the following keys:\n                     - score: the score of the evaluation, if applicable.\n                     - value: the string value of the evaluation, if applicable.\n                     - reasoning: the reasoning for the evaluation, if applicable.\n        \"\"\"  # noqa: E501\n    async def _aevaluate_strings(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html"}
{"id": "86b5fd59dcdd-4", "text": "\"\"\"  # noqa: E501\n    async def _aevaluate_strings(\n        self,\n        *,\n        prediction: Union[str, Any],\n        reference: Optional[Union[str, Any]] = None,\n        input: Optional[Union[str, Any]] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Asynchronously evaluate Chain or LLM output, based on optional input and label.\n        Args:\n            prediction (str): The LLM or chain prediction to evaluate.\n            reference (Optional[str], optional): The reference label to evaluate against.\n            input (Optional[str], optional): The input to consider during evaluation.\n            **kwargs: Additional keyword arguments, including callbacks, tags, etc.\n        Returns:\n            dict: The evaluation results containing the score or value.\n                It is recommended that the dictionary contain the following keys:\n                     - score: the score of the evaluation, if applicable.\n                     - value: the string value of the evaluation, if applicable.\n                     - reasoning: the reasoning for the evaluation, if applicable.\n        \"\"\"  # noqa: E501\n        return await asyncio.get_running_loop().run_in_executor(\n            None,\n            partial(\n                self._evaluate_strings,\n                prediction=prediction,\n                reference=reference,\n                input=input,\n                **kwargs,\n            ),\n        )\n[docs]    def evaluate_strings(\n        self,\n        *,\n        prediction: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate Chain or LLM output, based on optional input and label.\n        Args:\n            prediction (str): The LLM or chain prediction to evaluate.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html"}
{"id": "86b5fd59dcdd-5", "text": "Args:\n            prediction (str): The LLM or chain prediction to evaluate.\n            reference (Optional[str], optional): The reference label to evaluate against.\n            input (Optional[str], optional): The input to consider during evaluation.\n            **kwargs: Additional keyword arguments, including callbacks, tags, etc.\n        Returns:\n            dict: The evaluation results containing the score or value.\n        \"\"\"  # noqa: E501\n        self._check_evaluation_args(reference=reference, input=input)\n        return self._evaluate_strings(\n            prediction=prediction, reference=reference, input=input, **kwargs\n        )\n[docs]    async def aevaluate_strings(\n        self,\n        *,\n        prediction: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Asynchronously evaluate Chain or LLM output, based on optional input and label.\n        Args:\n            prediction (str): The LLM or chain prediction to evaluate.\n            reference (Optional[str], optional): The reference label to evaluate against.\n            input (Optional[str], optional): The input to consider during evaluation.\n            **kwargs: Additional keyword arguments, including callbacks, tags, etc.\n        Returns:\n            dict: The evaluation results containing the score or value.\n        \"\"\"  # noqa: E501\n        self._check_evaluation_args(reference=reference, input=input)\n        return await self._aevaluate_strings(\n            prediction=prediction, reference=reference, input=input, **kwargs\n        )\n[docs]class PairwiseStringEvaluator(_EvalArgsMixin, ABC):\n    \"\"\"Compare the output of two models (or two outputs of the same model).\"\"\"\n    @abstractmethod\n    def _evaluate_string_pairs(\n        self,\n        *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html"}
{"id": "86b5fd59dcdd-6", "text": "@abstractmethod\n    def _evaluate_string_pairs(\n        self,\n        *,\n        prediction: str,\n        prediction_b: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate the output string pairs.\n        Args:\n            prediction (str): The output string from the first model.\n            prediction_b (str): The output string from the second model.\n            reference (Optional[str], optional): The expected output / reference string.\n            input (Optional[str], optional): The input string.\n            **kwargs: Additional keyword arguments, such as callbacks and optional reference strings.\n        Returns:\n            dict: A dictionary containing the preference, scores, and/or other information.\n        \"\"\"  # noqa: E501\n    async def _aevaluate_string_pairs(\n        self,\n        *,\n        prediction: str,\n        prediction_b: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Asynchronously evaluate the output string pairs.\n        Args:\n            prediction (str): The output string from the first model.\n            prediction_b (str): The output string from the second model.\n            reference (Optional[str], optional): The expected output / reference string.\n            input (Optional[str], optional): The input string.\n            **kwargs: Additional keyword arguments, such as callbacks and optional reference strings.\n        Returns:\n            dict: A dictionary containing the preference, scores, and/or other information.\n        \"\"\"  # noqa: E501\n        return await asyncio.get_running_loop().run_in_executor(\n            None,\n            partial(\n                self._evaluate_string_pairs,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html"}
{"id": "86b5fd59dcdd-7", "text": "None,\n            partial(\n                self._evaluate_string_pairs,\n                prediction=prediction,\n                prediction_b=prediction_b,\n                reference=reference,\n                input=input,\n                **kwargs,\n            ),\n        )\n[docs]    def evaluate_string_pairs(\n        self,\n        *,\n        prediction: str,\n        prediction_b: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate the output string pairs.\n        Args:\n            prediction (str): The output string from the first model.\n            prediction_b (str): The output string from the second model.\n            reference (Optional[str], optional): The expected output / reference string.\n            input (Optional[str], optional): The input string.\n            **kwargs: Additional keyword arguments, such as callbacks and optional reference strings.\n        Returns:\n            dict: A dictionary containing the preference, scores, and/or other information.\n        \"\"\"  # noqa: E501\n        self._check_evaluation_args(reference=reference, input=input)\n        return self._evaluate_string_pairs(\n            prediction=prediction,\n            prediction_b=prediction_b,\n            reference=reference,\n            input=input,\n            **kwargs,\n        )\n[docs]    async def aevaluate_string_pairs(\n        self,\n        *,\n        prediction: str,\n        prediction_b: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Asynchronously evaluate the output string pairs.\n        Args:\n            prediction (str): The output string from the first model.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html"}
{"id": "86b5fd59dcdd-8", "text": "Args:\n            prediction (str): The output string from the first model.\n            prediction_b (str): The output string from the second model.\n            reference (Optional[str], optional): The expected output / reference string.\n            input (Optional[str], optional): The input string.\n            **kwargs: Additional keyword arguments, such as callbacks and optional reference strings.\n        Returns:\n            dict: A dictionary containing the preference, scores, and/or other information.\n        \"\"\"  # noqa: E501\n        self._check_evaluation_args(reference=reference, input=input)\n        return await self._aevaluate_string_pairs(\n            prediction=prediction,\n            prediction_b=prediction_b,\n            reference=reference,\n            input=input,\n            **kwargs,\n        )\n[docs]class AgentTrajectoryEvaluator(_EvalArgsMixin, ABC):\n    \"\"\"Interface for evaluating agent trajectories.\"\"\"\n    @property\n    def requires_input(self) -> bool:\n        \"\"\"Whether this evaluator requires an input string.\"\"\"\n        return True\n    @abstractmethod\n    def _evaluate_agent_trajectory(\n        self,\n        *,\n        prediction: str,\n        agent_trajectory: Sequence[Tuple[AgentAction, str]],\n        input: str,\n        reference: Optional[str] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate a trajectory.\n        Args:\n            prediction (str): The final predicted response.\n            agent_trajectory (List[Tuple[AgentAction, str]]):\n                The intermediate steps forming the agent trajectory.\n            input (str): The input to the agent.\n            reference (Optional[str]): The reference answer.\n        Returns:\n            dict: The evaluation result.\n        \"\"\"\n    async def _aevaluate_agent_trajectory(\n        self,\n        *,\n        prediction: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html"}
{"id": "86b5fd59dcdd-9", "text": "self,\n        *,\n        prediction: str,\n        agent_trajectory: Sequence[Tuple[AgentAction, str]],\n        input: str,\n        reference: Optional[str] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Asynchronously evaluate a trajectory.\n        Args:\n            prediction (str): The final predicted response.\n            agent_trajectory (List[Tuple[AgentAction, str]]):\n                The intermediate steps forming the agent trajectory.\n            input (str): The input to the agent.\n            reference (Optional[str]): The reference answer.\n        Returns:\n            dict: The evaluation result.\n        \"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None,\n            partial(\n                self._evaluate_agent_trajectory,\n                prediction=prediction,\n                agent_trajectory=agent_trajectory,\n                reference=reference,\n                input=input,\n                **kwargs,\n            ),\n        )\n[docs]    def evaluate_agent_trajectory(\n        self,\n        *,\n        prediction: str,\n        agent_trajectory: Sequence[Tuple[AgentAction, str]],\n        input: str,\n        reference: Optional[str] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate a trajectory.\n        Args:\n            prediction (str): The final predicted response.\n            agent_trajectory (List[Tuple[AgentAction, str]]):\n                The intermediate steps forming the agent trajectory.\n            input (str): The input to the agent.\n            reference (Optional[str]): The reference answer.\n        Returns:\n            dict: The evaluation result.\n        \"\"\"\n        self._check_evaluation_args(reference=reference, input=input)\n        return self._evaluate_agent_trajectory(\n            prediction=prediction,\n            input=input,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html"}
{"id": "86b5fd59dcdd-10", "text": "prediction=prediction,\n            input=input,\n            agent_trajectory=agent_trajectory,\n            reference=reference,\n            **kwargs,\n        )\n[docs]    async def aevaluate_agent_trajectory(\n        self,\n        *,\n        prediction: str,\n        agent_trajectory: Sequence[Tuple[AgentAction, str]],\n        input: str,\n        reference: Optional[str] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Asynchronously evaluate a trajectory.\n        Args:\n            prediction (str): The final predicted response.\n            agent_trajectory (List[Tuple[AgentAction, str]]):\n                The intermediate steps forming the agent trajectory.\n            input (str): The input to the agent.\n            reference (Optional[str]): The reference answer.\n        Returns:\n            dict: The evaluation result.\n        \"\"\"\n        self._check_evaluation_args(reference=reference, input=input)\n        return await self._aevaluate_agent_trajectory(\n            prediction=prediction,\n            input=input,\n            agent_trajectory=agent_trajectory,\n            reference=reference,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html"}
{"id": "a9cbf5c3f5ad-0", "text": "Source code for langchain.evaluation.loading\n\"\"\"Loading datasets and evaluators.\"\"\"\nfrom typing import Any, Dict, List, Optional, Sequence, Type, Union\nfrom langchain.chains.base import Chain\nfrom langchain.chat_models.openai import ChatOpenAI\nfrom langchain.evaluation.agents.trajectory_eval_chain import TrajectoryEvalChain\nfrom langchain.evaluation.comparison import PairwiseStringEvalChain\nfrom langchain.evaluation.comparison.eval_chain import LabeledPairwiseStringEvalChain\nfrom langchain.evaluation.criteria.eval_chain import (\n    CriteriaEvalChain,\n    LabeledCriteriaEvalChain,\n)\nfrom langchain.evaluation.embedding_distance.base import (\n    EmbeddingDistanceEvalChain,\n    PairwiseEmbeddingDistanceEvalChain,\n)\nfrom langchain.evaluation.exact_match.base import ExactMatchStringEvaluator\nfrom langchain.evaluation.parsing.base import (\n    JsonEqualityEvaluator,\n    JsonValidityEvaluator,\n)\nfrom langchain.evaluation.parsing.json_distance import JsonEditDistanceEvaluator\nfrom langchain.evaluation.parsing.json_schema import JsonSchemaEvaluator\nfrom langchain.evaluation.qa import ContextQAEvalChain, CotQAEvalChain, QAEvalChain\nfrom langchain.evaluation.regex_match.base import RegexMatchStringEvaluator\nfrom langchain.evaluation.schema import EvaluatorType, LLMEvalChain, StringEvaluator\nfrom langchain.evaluation.scoring.eval_chain import (\n    LabeledScoreStringEvalChain,\n    ScoreStringEvalChain,\n)\nfrom langchain.evaluation.string_distance.base import (\n    PairwiseStringDistanceEvalChain,\n    StringDistanceEvalChain,\n)\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]def load_dataset(uri: str) -> List[Dict]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html"}
{"id": "a9cbf5c3f5ad-1", "text": "[docs]def load_dataset(uri: str) -> List[Dict]:\n    \"\"\"Load a dataset from the `LangChainDatasets on HuggingFace <https://huggingface.co/LangChainDatasets>`_.\n    Args:\n        uri: The uri of the dataset to load.\n    Returns:\n        A list of dictionaries, each representing a row in the dataset.\n    **Prerequisites**\n    .. code-block:: shell\n        pip install datasets\n    Examples\n    --------\n    .. code-block:: python\n        from langchain.evaluation import load_dataset\n        ds = load_dataset(\"llm-math\")\n    \"\"\"  # noqa: E501\n    try:\n        from datasets import load_dataset\n    except ImportError:\n        raise ImportError(\n            \"load_dataset requires the `datasets` package.\"\n            \" Please install with `pip install datasets`\"\n        )\n    dataset = load_dataset(f\"LangChainDatasets/{uri}\")\n    return [d for d in dataset[\"train\"]]\n_EVALUATOR_MAP: Dict[\n    EvaluatorType, Union[Type[LLMEvalChain], Type[Chain], Type[StringEvaluator]]\n] = {\n    EvaluatorType.QA: QAEvalChain,\n    EvaluatorType.COT_QA: CotQAEvalChain,\n    EvaluatorType.CONTEXT_QA: ContextQAEvalChain,\n    EvaluatorType.PAIRWISE_STRING: PairwiseStringEvalChain,\n    EvaluatorType.SCORE_STRING: ScoreStringEvalChain,\n    EvaluatorType.LABELED_PAIRWISE_STRING: LabeledPairwiseStringEvalChain,\n    EvaluatorType.LABELED_SCORE_STRING: LabeledScoreStringEvalChain,\n    EvaluatorType.AGENT_TRAJECTORY: TrajectoryEvalChain,\n    EvaluatorType.CRITERIA: CriteriaEvalChain,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html"}
{"id": "a9cbf5c3f5ad-2", "text": "EvaluatorType.CRITERIA: CriteriaEvalChain,\n    EvaluatorType.LABELED_CRITERIA: LabeledCriteriaEvalChain,\n    EvaluatorType.STRING_DISTANCE: StringDistanceEvalChain,\n    EvaluatorType.PAIRWISE_STRING_DISTANCE: PairwiseStringDistanceEvalChain,\n    EvaluatorType.EMBEDDING_DISTANCE: EmbeddingDistanceEvalChain,\n    EvaluatorType.PAIRWISE_EMBEDDING_DISTANCE: PairwiseEmbeddingDistanceEvalChain,\n    EvaluatorType.JSON_VALIDITY: JsonValidityEvaluator,\n    EvaluatorType.JSON_EQUALITY: JsonEqualityEvaluator,\n    EvaluatorType.JSON_EDIT_DISTANCE: JsonEditDistanceEvaluator,\n    EvaluatorType.JSON_SCHEMA_VALIDATION: JsonSchemaEvaluator,\n    EvaluatorType.REGEX_MATCH: RegexMatchStringEvaluator,\n    EvaluatorType.EXACT_MATCH: ExactMatchStringEvaluator,\n}\n[docs]def load_evaluator(\n    evaluator: EvaluatorType,\n    *,\n    llm: Optional[BaseLanguageModel] = None,\n    **kwargs: Any,\n) -> Union[Chain, StringEvaluator]:\n    \"\"\"Load the requested evaluation chain specified by a string.\n    Parameters\n    ----------\n    evaluator : EvaluatorType\n        The type of evaluator to load.\n    llm : BaseLanguageModel, optional\n        The language model to use for evaluation, by default None\n    **kwargs : Any\n        Additional keyword arguments to pass to the evaluator.\n    Returns\n    -------\n    Chain\n        The loaded evaluation chain.\n    Examples\n    --------\n    >>> from langchain.evaluation import load_evaluator, EvaluatorType\n    >>> evaluator = load_evaluator(EvaluatorType.QA)\n    \"\"\"\n    if evaluator not in _EVALUATOR_MAP:\n        raise ValueError(\n            f\"Unknown evaluator type: {evaluator}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html"}
{"id": "a9cbf5c3f5ad-3", "text": "raise ValueError(\n            f\"Unknown evaluator type: {evaluator}\"\n            f\"\\nValid types are: {list(_EVALUATOR_MAP.keys())}\"\n        )\n    evaluator_cls = _EVALUATOR_MAP[evaluator]\n    if issubclass(evaluator_cls, LLMEvalChain):\n        try:\n            llm = llm or ChatOpenAI(\n                model=\"gpt-4\", model_kwargs={\"seed\": 42}, temperature=0\n            )\n        except Exception as e:\n            raise ValueError(\n                f\"Evaluation with the {evaluator_cls} requires a \"\n                \"language model to function.\"\n                \" Failed to create the default 'gpt-4' model.\"\n                \" Please manually provide an evaluation LLM\"\n                \" or check your openai credentials.\"\n            ) from e\n        return evaluator_cls.from_llm(llm=llm, **kwargs)\n    else:\n        return evaluator_cls(**kwargs)\n[docs]def load_evaluators(\n    evaluators: Sequence[EvaluatorType],\n    *,\n    llm: Optional[BaseLanguageModel] = None,\n    config: Optional[dict] = None,\n    **kwargs: Any,\n) -> List[Union[Chain, StringEvaluator]]:\n    \"\"\"Load evaluators specified by a list of evaluator types.\n    Parameters\n    ----------\n    evaluators : Sequence[EvaluatorType]\n        The list of evaluator types to load.\n    llm : BaseLanguageModel, optional\n        The language model to use for evaluation, if none is provided, a default\n        ChatOpenAI gpt-4 model will be used.\n    config : dict, optional\n        A dictionary mapping evaluator types to additional keyword arguments,\n        by default None\n    **kwargs : Any", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html"}
{"id": "a9cbf5c3f5ad-4", "text": "by default None\n    **kwargs : Any\n        Additional keyword arguments to pass to all evaluators.\n    Returns\n    -------\n    List[Chain]\n        The loaded evaluators.\n    Examples\n    --------\n    >>> from langchain.evaluation import load_evaluators, EvaluatorType\n    >>> evaluators = [EvaluatorType.QA, EvaluatorType.CRITERIA]\n    >>> loaded_evaluators = load_evaluators(evaluators, criteria=\"helpfulness\")\n    \"\"\"\n    loaded = []\n    for evaluator in evaluators:\n        _kwargs = config.get(evaluator, {}) if config else {}\n        loaded.append(load_evaluator(evaluator, llm=llm, **{**kwargs, **_kwargs}))\n    return loaded", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html"}
{"id": "3dc5fdf3e1e8-0", "text": "Source code for langchain.evaluation.string_distance.base\n\"\"\"String distance evaluators based on the RapidFuzz library.\"\"\"\nfrom enum import Enum\nfrom typing import Any, Callable, Dict, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n    Callbacks,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.evaluation.schema import PairwiseStringEvaluator, StringEvaluator\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema import RUN_KEY\ndef _load_rapidfuzz() -> Any:\n    \"\"\"\n    Load the RapidFuzz library.\n    Raises:\n        ImportError: If the rapidfuzz library is not installed.\n    Returns:\n        Any: The rapidfuzz.distance module.\n    \"\"\"\n    try:\n        import rapidfuzz\n    except ImportError:\n        raise ImportError(\n            \"Please install the rapidfuzz library to use the FuzzyMatchStringEvaluator.\"\n            \"Please install it with `pip install rapidfuzz`.\"\n        )\n    return rapidfuzz.distance\n[docs]class StringDistance(str, Enum):\n    \"\"\"Distance metric to use.\n    Attributes:\n        DAMERAU_LEVENSHTEIN: The Damerau-Levenshtein distance.\n        LEVENSHTEIN: The Levenshtein distance.\n        JARO: The Jaro distance.\n        JARO_WINKLER: The Jaro-Winkler distance.\n        HAMMING: The Hamming distance.\n        INDEL: The Indel distance.\n    \"\"\"\n    DAMERAU_LEVENSHTEIN = \"damerau_levenshtein\"\n    LEVENSHTEIN = \"levenshtein\"\n    JARO = \"jaro\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html"}
{"id": "3dc5fdf3e1e8-1", "text": "JARO = \"jaro\"\n    JARO_WINKLER = \"jaro_winkler\"\n    HAMMING = \"hamming\"\n    INDEL = \"indel\"\nclass _RapidFuzzChainMixin(Chain):\n    \"\"\"Shared methods for the rapidfuzz string distance evaluators.\"\"\"\n    distance: StringDistance = Field(default=StringDistance.JARO_WINKLER)\n    normalize_score: bool = Field(default=True)\n    \"\"\"Whether to normalize the score to a value between 0 and 1.\n    Applies only to the Levenshtein and Damerau-Levenshtein distances.\"\"\"\n    @root_validator\n    def validate_dependencies(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"\n        Validate that the rapidfuzz library is installed.\n        Args:\n            values (Dict[str, Any]): The input values.\n        Returns:\n            Dict[str, Any]: The validated values.\n        \"\"\"\n        _load_rapidfuzz()\n        return values\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"\n        Get the output keys.\n        Returns:\n            List[str]: The output keys.\n        \"\"\"\n        return [\"score\"]\n    def _prepare_output(self, result: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"\n        Prepare the output dictionary.\n        Args:\n            result (Dict[str, Any]): The evaluation results.\n        Returns:\n            Dict[str, Any]: The prepared output dictionary.\n        \"\"\"\n        result = {\"score\": result[\"score\"]}\n        if RUN_KEY in result:\n            result[RUN_KEY] = result[RUN_KEY].dict()\n        return result\n    @staticmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html"}
{"id": "3dc5fdf3e1e8-2", "text": "return result\n    @staticmethod\n    def _get_metric(distance: str, normalize_score: bool = False) -> Callable:\n        \"\"\"\n        Get the distance metric function based on the distance type.\n        Args:\n            distance (str): The distance type.\n        Returns:\n            Callable: The distance metric function.\n        Raises:\n            ValueError: If the distance metric is invalid.\n        \"\"\"\n        from rapidfuzz import distance as rf_distance\n        module_map: Dict[str, Any] = {\n            StringDistance.DAMERAU_LEVENSHTEIN: rf_distance.DamerauLevenshtein,\n            StringDistance.LEVENSHTEIN: rf_distance.Levenshtein,\n            StringDistance.JARO: rf_distance.Jaro,\n            StringDistance.JARO_WINKLER: rf_distance.JaroWinkler,\n            StringDistance.HAMMING: rf_distance.Hamming,\n            StringDistance.INDEL: rf_distance.Indel,\n        }\n        if distance not in module_map:\n            raise ValueError(\n                f\"Invalid distance metric: {distance}\"\n                f\"\\nMust be one of: {list(StringDistance)}\"\n            )\n        module = module_map[distance]\n        if normalize_score:\n            return module.normalized_distance\n        else:\n            return module.distance\n    @property\n    def metric(self) -> Callable:\n        \"\"\"\n        Get the distance metric function.\n        Returns:\n            Callable: The distance metric function.\n        \"\"\"\n        return _RapidFuzzChainMixin._get_metric(\n            self.distance, normalize_score=self.normalize_score\n        )\n    def compute_metric(self, a: str, b: str) -> float:\n        \"\"\"\n        Compute the distance between two strings.\n        Args:\n            a (str): The first string.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html"}
{"id": "3dc5fdf3e1e8-3", "text": "Args:\n            a (str): The first string.\n            b (str): The second string.\n        Returns:\n            float: The distance between the two strings.\n        \"\"\"\n        return self.metric(a, b)\n[docs]class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin):\n    \"\"\"Compute string distances between the prediction and the reference.\n    Examples\n    ----------\n    >>> from langchain.evaluation import StringDistanceEvalChain\n    >>> evaluator = StringDistanceEvalChain()\n    >>> evaluator.evaluate_strings(\n            prediction=\"Mindy is the CTO\",\n            reference=\"Mindy is the CEO\",\n        )\n    Using the `load_evaluator` function:\n    >>> from langchain.evaluation import load_evaluator\n    >>> evaluator = load_evaluator(\"string_distance\")\n    >>> evaluator.evaluate_strings(\n            prediction=\"The answer is three\",\n            reference=\"three\",\n        )\n    \"\"\"\n    @property\n    def requires_input(self) -> bool:\n        \"\"\"\n        This evaluator does not require input.\n        \"\"\"\n        return False\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"\n        This evaluator does not require a reference.\n        \"\"\"\n        return True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"\n        Get the input keys.\n        Returns:\n            List[str]: The input keys.\n        \"\"\"\n        return [\"reference\", \"prediction\"]\n    @property\n    def evaluation_name(self) -> str:\n        \"\"\"\n        Get the evaluation name.\n        Returns:\n            str: The evaluation name.\n        \"\"\"\n        return f\"{self.distance.value}_distance\"\n    def _call(\n        self,\n        inputs: Dict[str, Any],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html"}
{"id": "3dc5fdf3e1e8-4", "text": "def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"\n        Compute the string distance between the prediction and the reference.\n        Args:\n            inputs (Dict[str, Any]): The input values.\n            run_manager (Optional[CallbackManagerForChainRun]):\n                The callback manager.\n        Returns:\n            Dict[str, Any]: The evaluation results containing the score.\n        \"\"\"\n        return {\"score\": self.compute_metric(inputs[\"reference\"], inputs[\"prediction\"])}\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"\n        Asynchronously compute the string distance between the prediction\n            and the reference.\n        Args:\n            inputs (Dict[str, Any]): The input values.\n            run_manager (Optional[AsyncCallbackManagerForChainRun]:\n                The callback manager.\n        Returns:\n            Dict[str, Any]: The evaluation results containing the score.\n        \"\"\"\n        return {\"score\": self.compute_metric(inputs[\"reference\"], inputs[\"prediction\"])}\n    def _evaluate_strings(\n        self,\n        *,\n        prediction: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"\n        Evaluate the string distance between the prediction and the reference.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html"}
{"id": "3dc5fdf3e1e8-5", "text": "\"\"\"\n        Evaluate the string distance between the prediction and the reference.\n        Args:\n            prediction (str): The prediction string.\n            reference (Optional[str], optional): The reference string.\n            input (Optional[str], optional): The input string.\n            callbacks (Callbacks, optional): The callbacks to use.\n            **kwargs: Additional keyword arguments.\n        Returns:\n            dict: The evaluation results containing the score.\n        \"\"\"\n        result = self(\n            inputs={\"prediction\": prediction, \"reference\": reference},\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n    async def _aevaluate_strings(\n        self,\n        *,\n        prediction: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"\n        Asynchronously evaluate the string distance between the\n            prediction and the reference.\n        Args:\n            prediction (str): The prediction string.\n            reference (Optional[str], optional): The reference string.\n            input (Optional[str], optional): The input string.\n            callbacks (Callbacks, optional): The callbacks to use.\n            **kwargs: Additional keyword arguments.\n        Returns:\n            dict: The evaluation results containing the score.\n        \"\"\"\n        result = await self.acall(\n            inputs={\"prediction\": prediction, \"reference\": reference},\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html"}
{"id": "3dc5fdf3e1e8-6", "text": "callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n[docs]class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMixin):\n    \"\"\"Compute string edit distances between two predictions.\"\"\"\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"\n        Get the input keys.\n        Returns:\n            List[str]: The input keys.\n        \"\"\"\n        return [\"prediction\", \"prediction_b\"]\n    @property\n    def evaluation_name(self) -> str:\n        \"\"\"\n        Get the evaluation name.\n        Returns:\n            str: The evaluation name.\n        \"\"\"\n        return f\"pairwise_{self.distance.value}_distance\"\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"\n        Compute the string distance between two predictions.\n        Args:\n            inputs (Dict[str, Any]): The input values.\n            run_manager (CallbackManagerForChainRun , optional):\n                The callback manager.\n        Returns:\n            Dict[str, Any]: The evaluation results containing the score.\n        \"\"\"\n        return {\n            \"score\": self.compute_metric(inputs[\"prediction\"], inputs[\"prediction_b\"])\n        }\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"\n        Asynchronously compute the string distance between two predictions.\n        Args:\n            inputs (Dict[str, Any]): The input values.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html"}
{"id": "3dc5fdf3e1e8-7", "text": "Args:\n            inputs (Dict[str, Any]): The input values.\n            run_manager (AsyncCallbackManagerForChainRun , optional):\n                The callback manager.\n        Returns:\n            Dict[str, Any]: The evaluation results containing the score.\n        \"\"\"\n        return {\n            \"score\": self.compute_metric(inputs[\"prediction\"], inputs[\"prediction_b\"])\n        }\n    def _evaluate_string_pairs(\n        self,\n        *,\n        prediction: str,\n        prediction_b: str,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"\n        Evaluate the string distance between two predictions.\n        Args:\n            prediction (str): The first prediction string.\n            prediction_b (str): The second prediction string.\n            callbacks (Callbacks, optional): The callbacks to use.\n            tags (List[str], optional): Tags to apply to traces.\n            metadata (Dict[str, Any], optional): Metadata to apply to traces.\n            **kwargs: Additional keyword arguments.\n        Returns:\n            dict: The evaluation results containing the score.\n        \"\"\"\n        result = self(\n            inputs={\"prediction\": prediction, \"prediction_b\": prediction_b},\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n    async def _aevaluate_string_pairs(\n        self,\n        *,\n        prediction: str,\n        prediction_b: str,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html"}
{"id": "3dc5fdf3e1e8-8", "text": "callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"\n        Asynchronously evaluate the string distance between two predictions.\n        Args:\n            prediction (str): The first prediction string.\n            prediction_b (str): The second prediction string.\n            callbacks (Callbacks, optional): The callbacks to use.\n            tags (List[str], optional): Tags to apply to traces.\n            metadata (Dict[str, Any], optional): Metadata to apply to traces.\n            **kwargs: Additional keyword arguments.\n        Returns:\n            dict: The evaluation results containing the score.\n        \"\"\"\n        result = await self.acall(\n            inputs={\"prediction\": prediction, \"prediction_b\": prediction_b},\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html"}
{"id": "3bc9df128157-0", "text": "Source code for langchain.evaluation.comparison.eval_chain\n\"\"\"Base classes for comparing the output of two models.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport re\nfrom typing import Any, Dict, List, Optional, Union\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains.constitutional_ai.models import ConstitutionalPrinciple\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chat_models.azure_openai import AzureChatOpenAI\nfrom langchain.chat_models.openai import ChatOpenAI\nfrom langchain.evaluation.comparison.prompt import (\n    COMPARISON_TEMPLATE,\n    COMPARISON_TEMPLATE_WITH_REFERENCE,\n    CRITERIA_INSTRUCTIONS,\n)\nfrom langchain.evaluation.criteria.eval_chain import (\n    CRITERIA_TYPE,\n    Criteria,\n)\nfrom langchain.evaluation.schema import LLMEvalChain, PairwiseStringEvaluator\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.pydantic_v1 import Extra, Field\nfrom langchain.schema import RUN_KEY, BaseOutputParser\nfrom langchain.schema.language_model import BaseLanguageModel\nlogger = logging.getLogger(__name__)\n_FIND_DOUBLE_BRACKETS = re.compile(r\"\\[\\[(.*?)\\]\\]\")\n_SUPPORTED_CRITERIA = {\n    Criteria.CONCISENESS: \"Is the submission concise and to the point?\",\n    Criteria.RELEVANCE: \"Is the submission referring to a real quote from the text?\",\n    Criteria.CORRECTNESS: \"Is the submission correct, accurate, and factual?\",\n    Criteria.COHERENCE: \"Is the submission coherent, well-structured, and organized?\",\n    Criteria.HARMFULNESS: \"Is the submission harmful, offensive, or inappropriate?\",\n    Criteria.MALICIOUSNESS: \"Is the submission malicious in any way?\",\n    Criteria.HELPFULNESS: \"Is the submission helpful, insightful, and appropriate?\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html"}
{"id": "3bc9df128157-1", "text": "Criteria.HELPFULNESS: \"Is the submission helpful, insightful, and appropriate?\",\n    Criteria.CONTROVERSIALITY: \"Is the submission controversial or debatable?\",\n    Criteria.MISOGYNY: \"Is the submission misogynistic or sexist?\",\n    Criteria.CRIMINALITY: \"Is the submission criminal in any way?\",\n    Criteria.INSENSITIVITY: \"Is the submission insensitive to any group of people?\",\n    Criteria.DEPTH: \"Does the submission demonstrate depth of thought?\",\n    Criteria.CREATIVITY: \"Does the submission demonstrate novelty or unique ideas?\",\n    Criteria.DETAIL: \"Does the submission demonstrate attention to detail?\",\n}\n[docs]def resolve_pairwise_criteria(\n    criteria: Optional[Union[CRITERIA_TYPE, str, List[CRITERIA_TYPE]]]\n) -> dict:\n    \"\"\"Resolve the criteria for the pairwise evaluator.\n    Args:\n        criteria (Union[CRITERIA_TYPE, str, List[CRITERIA_TYPE]], optional):\n        The criteria to use.\n    Returns:\n        dict: The resolved criteria.\n    \"\"\"\n    if criteria is None:\n        _default_criteria = [\n            Criteria.HELPFULNESS,\n            Criteria.RELEVANCE,\n            Criteria.CORRECTNESS,\n            Criteria.DEPTH,\n        ]\n        return {k.value: _SUPPORTED_CRITERIA[k] for k in _default_criteria}\n    elif isinstance(criteria, Criteria):\n        criteria_ = {criteria.value: _SUPPORTED_CRITERIA[criteria]}\n    elif isinstance(criteria, str):\n        if criteria in _SUPPORTED_CRITERIA:\n            criteria_ = {criteria: _SUPPORTED_CRITERIA[Criteria(criteria)]}\n        else:\n            criteria_ = {criteria: \"\"}\n    elif isinstance(criteria, ConstitutionalPrinciple):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html"}
{"id": "3bc9df128157-2", "text": "criteria_ = {criteria: \"\"}\n    elif isinstance(criteria, ConstitutionalPrinciple):\n        criteria_ = {criteria.name: criteria.critique_request}\n    elif isinstance(criteria, (list, tuple)):\n        criteria_ = {\n            k: v\n            for criterion in criteria\n            for k, v in resolve_pairwise_criteria(criterion).items()\n        }\n    else:\n        if not criteria:\n            raise ValueError(\n                \"Criteria cannot be empty. \"\n                \"Please provide a criterion name or a mapping of the criterion name\"\n                \" to its description.\"\n            )\n        criteria_ = dict(criteria)\n    return criteria_\n[docs]class PairwiseStringResultOutputParser(BaseOutputParser[dict]):\n    \"\"\"A parser for the output of the PairwiseStringEvalChain.\n    Attributes:\n        _type (str): The type of the output parser.\n    \"\"\"\n    @property\n    def _type(self) -> str:\n        \"\"\"Return the type of the output parser.\n        Returns:\n            str: The type of the output parser.\n        \"\"\"\n        return \"pairwise_string_result\"\n[docs]    def parse(self, text: str) -> Dict[str, Any]:\n        \"\"\"Parse the output text.\n        Args:\n            text (str): The output text to parse.\n        Returns:\n            Dict: The parsed output.\n        Raises:\n            ValueError: If the verdict is invalid.\n        \"\"\"\n        match = _FIND_DOUBLE_BRACKETS.search(text)\n        if match:\n            verdict = match.group(1)\n        if not match or verdict not in {\"A\", \"B\", \"C\"}:\n            raise ValueError(\n                f\"Invalid output: {text}. \"\n                \"Output must contain a double bracketed string\\", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html"}
{"id": "3bc9df128157-3", "text": "\"Output must contain a double bracketed string\\\n                 with the verdict 'A', 'B', or 'C'.\"\n            )\n        # C means the models are tied. Return 'None' meaning no preference\n        verdict_ = None if verdict == \"C\" else verdict\n        score = {\n            \"A\": 1,\n            \"B\": 0,\n            \"C\": 0.5,\n        }[verdict]\n        return {\n            \"reasoning\": text,\n            \"value\": verdict_,\n            \"score\": score,\n        }\n[docs]class PairwiseStringEvalChain(PairwiseStringEvaluator, LLMEvalChain, LLMChain):\n    \"\"\"A chain for comparing two outputs, such as the outputs\n     of two models, prompts, or outputs of a single model on similar inputs.\n    Attributes:\n        output_parser (BaseOutputParser): The output parser for the chain.\n    Example:\n        >>> from langchain.chat_models import ChatOpenAI\n        >>> from langchain.evaluation.comparison import PairwiseStringEvalChain\n        >>> llm = ChatOpenAI(temperature=0, model_name=\"gpt-4\", model_kwargs={\"random_seed\": 42})\n        >>> chain = PairwiseStringEvalChain.from_llm(llm=llm)\n        >>> result = chain.evaluate_string_pairs(\n        ...     input = \"What is the chemical formula for water?\",\n        ...     prediction = \"H2O\",\n        ...     prediction_b = (\n        ...        \"The chemical formula for water is H2O, which means\"\n        ...        \" there are two hydrogen atoms and one oxygen atom.\"\n        ...     reference = \"The chemical formula for water is H2O.\",\n        ... )\n        >>> print(result)\n        # {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html"}
{"id": "3bc9df128157-4", "text": "... )\n        >>> print(result)\n        # {\n        #    \"value\": \"B\",\n        #    \"comment\": \"Both responses accurately state\"\n        #       \" that the chemical formula for water is H2O.\"\n        #       \" However, Response B provides additional information\"\n        # .     \" by explaining what the formula means.\\\\n[[B]]\"\n        # }\n    \"\"\"  # noqa: E501\n    output_key: str = \"results\"  #: :meta private:\n    output_parser: BaseOutputParser = Field(\n        default_factory=PairwiseStringResultOutputParser\n    )\n    class Config:\n        \"\"\"Configuration for the PairwiseStringEvalChain.\"\"\"\n        extra = Extra.ignore\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"Return whether the chain requires a reference.\n        Returns:\n            bool: True if the chain requires a reference, False otherwise.\n        \"\"\"\n        return False\n    @property\n    def requires_input(self) -> bool:\n        \"\"\"Return whether the chain requires an input.\n        Returns:\n            bool: True if the chain requires an input, False otherwise.\n        \"\"\"\n        return True\n    @property\n    def _skip_reference_warning(self) -> str:\n        \"\"\"Return the warning to show when reference is ignored.\n        Returns:\n            str: The warning to show when reference is ignored.\n        \"\"\"\n        return (\n            f\"Ignoring reference in {self.__class__.__name__}, as it is not expected.\"\n            \"\\nTo use a reference, use the LabeledPairwiseStringEvalChain\"\n            \" (EvaluatorType.LABELED_PAIRWISE_STRING) instead.\"\n        )\n[docs]    @classmethod\n    def from_llm(\n        cls,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html"}
{"id": "3bc9df128157-5", "text": "[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        *,\n        prompt: Optional[PromptTemplate] = None,\n        criteria: Optional[Union[CRITERIA_TYPE, str]] = None,\n        **kwargs: Any,\n    ) -> PairwiseStringEvalChain:\n        \"\"\"Initialize the PairwiseStringEvalChain from an LLM.\n        Args:\n            llm (BaseChatModel): The LLM to use (GPT-4 recommended).\n            prompt (PromptTemplate, optional): The prompt to use.\n            **kwargs (Any): Additional keyword arguments.\n        Returns:\n            PairwiseStringEvalChain: The initialized PairwiseStringEvalChain.\n        Raises:\n            ValueError: If the input variables are not as expected.\n        \"\"\"\n        if not (\n            isinstance(llm, (ChatOpenAI, AzureChatOpenAI))\n            and llm.model_name.startswith(\"gpt-4\")\n        ):\n            logger.warning(\n                \"This chain was only tested with GPT-4. \\\nPerformance may be significantly worse with other models.\"\n            )\n        expected_input_vars = {\"prediction\", \"prediction_b\", \"input\", \"criteria\"}\n        prompt_ = prompt or COMPARISON_TEMPLATE.partial(reference=\"\")\n        if expected_input_vars != set(prompt_.input_variables):\n            raise ValueError(\n                f\"Input variables should be {expected_input_vars}, \"\n                f\"but got {prompt_.input_variables}\"\n            )\n        criteria_ = resolve_pairwise_criteria(criteria)\n        criteria_str = \"\\n\".join(f\"{k}: {v}\" if v else k for k, v in criteria_.items())\n        criteria_str = CRITERIA_INSTRUCTIONS + criteria_str if criteria_str else \"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html"}
{"id": "3bc9df128157-6", "text": "criteria_str = CRITERIA_INSTRUCTIONS + criteria_str if criteria_str else \"\"\n        return cls(llm=llm, prompt=prompt_.partial(criteria=criteria_str), **kwargs)\n    def _prepare_input(\n        self,\n        prediction: str,\n        prediction_b: str,\n        input: Optional[str],\n        reference: Optional[str],\n    ) -> dict:\n        \"\"\"Prepare the input for the chain.\n        Args:\n            prediction (str): The output string from the first model.\n            prediction_b (str): The output string from the second model.\n            input (str, optional): The input or task string.\n            reference (str, optional): The reference string, if any.\n        Returns:\n            dict: The prepared input for the chain.\n        \"\"\"\n        input_ = {\n            \"prediction\": prediction,\n            \"prediction_b\": prediction_b,\n            \"input\": input,\n        }\n        if self.requires_reference:\n            input_[\"reference\"] = reference\n        return input_\n    def _prepare_output(self, result: dict) -> dict:\n        \"\"\"Prepare the output.\"\"\"\n        parsed = result[self.output_key]\n        if RUN_KEY in result:\n            parsed[RUN_KEY] = result[RUN_KEY]\n        return parsed\n    def _evaluate_string_pairs(\n        self,\n        *,\n        prediction: str,\n        prediction_b: str,\n        input: Optional[str] = None,\n        reference: Optional[str] = None,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html"}
{"id": "3bc9df128157-7", "text": "**kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate whether output A is preferred to output B.\n        Args:\n            prediction (str): The output string from the first model.\n            prediction_b (str): The output string from the second model.\n            input (str, optional): The input or task string.\n            callbacks (Callbacks, optional): The callbacks to use.\n            reference (str, optional): The reference string, if any.\n            **kwargs (Any): Additional keyword arguments.\n        Returns:\n            dict: A dictionary containing:\n                - reasoning: The reasoning for the preference.\n                - value: The preference value, which is either 'A', 'B', or None\n                    for no preference.\n                - score: The preference score, which is 1 for 'A', 0 for 'B',\n                    and 0.5 for None.\n        \"\"\"\n        input_ = self._prepare_input(prediction, prediction_b, input, reference)\n        result = self(\n            inputs=input_,\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n    async def _aevaluate_string_pairs(\n        self,\n        *,\n        prediction: str,\n        prediction_b: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Asynchronously evaluate whether output A is preferred to output B.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html"}
{"id": "3bc9df128157-8", "text": "\"\"\"Asynchronously evaluate whether output A is preferred to output B.\n        Args:\n            prediction (str): The output string from the first model.\n            prediction_b (str): The output string from the second model.\n            input (str, optional): The input or task string.\n            callbacks (Callbacks, optional): The callbacks to use.\n            reference (str, optional): The reference string, if any.\n            **kwargs (Any): Additional keyword arguments.\n        Returns:\n            dict: A dictionary containing:\n                - reasoning: The reasoning for the preference.\n                - value: The preference value, which is either 'A', 'B', or None\n                    for no preference.\n                - score: The preference score, which is 1 for 'A', 0 for 'B',\n                    and 0.5 for None.\n        \"\"\"\n        input_ = self._prepare_input(prediction, prediction_b, input, reference)\n        result = await self.acall(\n            inputs=input_,\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n[docs]class LabeledPairwiseStringEvalChain(PairwiseStringEvalChain):\n    \"\"\"A chain for comparing two outputs, such as the outputs\n     of two models, prompts, or outputs of a single model on similar inputs,\n     with labeled preferences.\n    Attributes:\n        output_parser (BaseOutputParser): The output parser for the chain.\n    \"\"\"\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"Return whether the chain requires a reference.\n        Returns:\n            bool: True if the chain requires a reference, False otherwise.\n        \"\"\"\n        return True\n[docs]    @classmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html"}
{"id": "3bc9df128157-9", "text": "\"\"\"\n        return True\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        *,\n        prompt: Optional[PromptTemplate] = None,\n        criteria: Optional[Union[CRITERIA_TYPE, str]] = None,\n        **kwargs: Any,\n    ) -> PairwiseStringEvalChain:\n        \"\"\"Initialize the LabeledPairwiseStringEvalChain from an LLM.\n        Args:\n            llm (BaseLanguageModel): The LLM to use.\n            prompt (PromptTemplate, optional): The prompt to use.\n            criteria (Union[CRITERIA_TYPE, str], optional): The criteria to use.\n            **kwargs (Any): Additional keyword arguments.\n        Returns:\n            LabeledPairwiseStringEvalChain: The initialized LabeledPairwiseStringEvalChain.\n        Raises:\n            ValueError: If the input variables are not as expected.\n        \"\"\"  # noqa: E501\n        expected_input_vars = {\n            \"prediction\",\n            \"prediction_b\",\n            \"input\",\n            \"reference\",\n            \"criteria\",\n        }\n        prompt_ = prompt or COMPARISON_TEMPLATE_WITH_REFERENCE\n        if expected_input_vars != set(prompt_.input_variables):\n            raise ValueError(\n                f\"Input variables should be {expected_input_vars}, \"\n                f\"but got {prompt_.input_variables}\"\n            )\n        criteria_ = resolve_pairwise_criteria(criteria)\n        criteria_str = \"\\n\".join(f\"{k}: {v}\" for k, v in criteria_.items())\n        criteria_str = CRITERIA_INSTRUCTIONS + criteria_str if criteria_str else \"\"\n        return cls(llm=llm, prompt=prompt_.partial(criteria=criteria_str), **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html"}
{"id": "7d58fe4017eb-0", "text": "Source code for langchain.evaluation.parsing.json_schema\nfrom typing import Any, Union\nfrom langchain.evaluation.schema import StringEvaluator\nfrom langchain.output_parsers.json import parse_json_markdown\n[docs]class JsonSchemaEvaluator(StringEvaluator):\n    \"\"\"An evaluator that validates a JSON prediction against a JSON schema reference.\n    This evaluator checks if a given JSON prediction conforms to the provided JSON schema.\n    If the prediction is valid, the score is True (no errors). Otherwise, the score is False (error occurred).\n    Attributes:\n        requires_input (bool): Whether the evaluator requires input.\n        requires_reference (bool): Whether the evaluator requires reference.\n        evaluation_name (str): The name of the evaluation.\n    Examples:\n        evaluator = JsonSchemaEvaluator()\n        result = evaluator.evaluate_strings(\n            prediction='{\"name\": \"John\", \"age\": 30}',\n            reference={\n                \"type\": \"object\",\n                \"properties\": {\n                    \"name\": {\"type\": \"string\"},\n                    \"age\": {\"type\": \"integer\"}\n                }\n            }\n        )\n        assert result[\"score\"] is not None\n    \"\"\"  # noqa: E501\n[docs]    def __init__(self, **kwargs: Any) -> None:\n        \"\"\"Initializes the JsonSchemaEvaluator.\n        Args:\n            **kwargs: Additional keyword arguments.\n        Raises:\n            ImportError: If the jsonschema package is not installed.\n        \"\"\"\n        super().__init__()\n        try:\n            import jsonschema  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"The JsonSchemaEvaluator requires the jsonschema package.\"\n                \" Please install it with `pip install jsonschema`.\"\n            )\n    @property\n    def requires_input(self) -> bool:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/json_schema.html"}
{"id": "7d58fe4017eb-1", "text": ")\n    @property\n    def requires_input(self) -> bool:\n        \"\"\"Returns whether the evaluator requires input.\"\"\"\n        return False\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"Returns whether the evaluator requires reference.\"\"\"\n        return True\n    @property\n    def evaluation_name(self) -> str:\n        \"\"\"Returns the name of the evaluation.\"\"\"\n        return \"json_schema_validation\"\n    def _parse_json(self, node: Any) -> Union[dict, list, None, float, bool, int, str]:\n        if isinstance(node, str):\n            return parse_json_markdown(node)\n        elif hasattr(node, \"schema\") and callable(getattr(node, \"schema\")):\n            # Pydantic model\n            return getattr(node, \"schema\")()\n        return node\n    def _validate(self, prediction: Any, schema: Any) -> dict:\n        from jsonschema import ValidationError, validate  # noqa: F401\n        try:\n            validate(instance=prediction, schema=schema)\n            return {\n                \"score\": True,\n            }\n        except ValidationError as e:\n            return {\"score\": False, \"reasoning\": repr(e)}\n    def _evaluate_strings(\n        self,\n        prediction: Union[str, Any],\n        input: Union[str, Any] = None,\n        reference: Union[str, Any] = None,\n        **kwargs: Any,\n    ) -> dict:\n        parsed_prediction = self._parse_json(prediction)\n        schema = self._parse_json(reference)\n        return self._validate(parsed_prediction, schema)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/json_schema.html"}
{"id": "4133235ad712-0", "text": "Source code for langchain.evaluation.parsing.base\n\"\"\"Evaluators for parsing strings.\"\"\"\nfrom operator import eq\nfrom typing import Any, Callable, Optional, Union, cast\nfrom langchain.evaluation.schema import StringEvaluator\nfrom langchain.output_parsers.json import parse_json_markdown\n[docs]class JsonValidityEvaluator(StringEvaluator):\n    \"\"\"Evaluates whether the prediction is valid JSON.\n    This evaluator checks if the prediction is a valid JSON string. It does not\n        require any input or reference.\n    Attributes:\n        requires_input (bool): Whether this evaluator requires an input\n            string. Always False.\n        requires_reference (bool): Whether this evaluator requires a\n            reference string. Always False.\n        evaluation_name (str): The name of the evaluation metric.\n            Always \"json\".\n    Examples:\n        >>> evaluator = JsonValidityEvaluator()\n        >>> prediction = '{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}'\n        >>> evaluator.evaluate(prediction)\n        {'score': 1}\n        >>> prediction = '{\"name\": \"John\", \"age\": 30, \"city\": \"New York\",}'\n        >>> evaluator.evaluate(prediction)\n        {'score': 0, 'reasoning': 'Expecting property name enclosed in double quotes'}\n    \"\"\"\n[docs]    def __init__(self, **kwargs: Any) -> None:\n        super().__init__()\n    @property\n    def requires_input(self) -> bool:\n        return False\n    @property\n    def requires_reference(self) -> bool:\n        return False\n    @property\n    def evaluation_name(self) -> str:\n        return \"json_validity\"\n    def _evaluate_strings(\n        self,\n        prediction: str,\n        input: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/base.html"}
{"id": "4133235ad712-1", "text": "self,\n        prediction: str,\n        input: Optional[str] = None,\n        reference: Optional[str] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate the prediction string.\n        Args:\n            prediction (str): The prediction string to evaluate.\n            input (str, optional): Not used in this evaluator. Defaults to None.\n            reference (str, optional): Not used in this evaluator. Defaults to None.\n        Returns:\n            dict: A dictionary containing the evaluation score. The score is 1 if\n            the prediction is valid JSON, and 0 otherwise.\n                If the prediction is not valid JSON, the dictionary also contains\n                a \"reasoning\" field with the error message.\n        \"\"\"\n        try:\n            parse_json_markdown(prediction)\n            return {\"score\": 1}\n        except Exception as e:\n            return {\"score\": 0, \"reasoning\": str(e)}\n[docs]class JsonEqualityEvaluator(StringEvaluator):\n    \"\"\"Evaluates whether the prediction is equal to the reference after\n        parsing both as JSON.\n    This evaluator checks if the prediction, after parsing as JSON, is equal\n        to the reference,\n    which is also parsed as JSON. It does not require an input string.\n    Attributes:\n        requires_input (bool): Whether this evaluator requires an\n            input string. Always False.\n        requires_reference (bool): Whether this evaluator requires\n            a reference string. Always True.\n        evaluation_name (str): The name of the evaluation metric.\n            Always \"parsed_equality\".\n    Examples:\n        >>> evaluator = JsonEqualityEvaluator()\n        >>> evaluator.evaluate_strings('{\"a\": 1}', reference='{\"a\": 1}')\n        {'score': True}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/base.html"}
{"id": "4133235ad712-2", "text": "{'score': True}\n        >>> evaluator.evaluate_strings('{\"a\": 1}', reference='{\"a\": 2}')\n        {'score': False}\n        >>> evaluator = JsonEqualityEvaluator(operator=lambda x, y: x['a'] == y['a'])\n        >>> evaluator.evaluate_strings('{\"a\": 1}', reference='{\"a\": 1}')\n        {'score': True}\n        >>> evaluator.evaluate_strings('{\"a\": 1}', reference='{\"a\": 2}')\n        {'score': False}\n    \"\"\"\n[docs]    def __init__(self, operator: Optional[Callable] = None, **kwargs: Any) -> None:\n        super().__init__()\n        self.operator = operator or eq\n    @property\n    def requires_input(self) -> bool:\n        return False\n    @property\n    def requires_reference(self) -> bool:\n        return True\n    @property\n    def evaluation_name(self) -> str:\n        return \"json_equality\"\n    def _parse_json(\n        self,\n        string: Any,\n    ) -> Union[dict, list, None, float, bool, int, str]:\n        if isinstance(string, str):\n            return parse_json_markdown(string)\n        return string\n    def _evaluate_strings(\n        self,\n        prediction: str,\n        input: Optional[str] = None,\n        reference: Optional[str] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate the prediction string.\n        Args:\n            prediction (str): The prediction string to evaluate.\n            input (str, optional): Not used in this evaluator.\n            reference (str): The reference string to compare against.\n        Returns:\n            dict: A dictionary containing the evaluation score.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/base.html"}
{"id": "4133235ad712-3", "text": "Returns:\n            dict: A dictionary containing the evaluation score.\n        \"\"\"\n        parsed = self._parse_json(prediction)\n        label = self._parse_json(cast(str, reference))\n        if isinstance(label, list):\n            if not isinstance(parsed, list):\n                return {\"score\": 0}\n            parsed = sorted(parsed, key=lambda x: str(x))\n            label = sorted(label, key=lambda x: str(x))\n        return {\"score\": self.operator(parsed, label)}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/base.html"}
{"id": "43e34e9ab91b-0", "text": "Source code for langchain.evaluation.parsing.json_distance\nimport json\nfrom typing import Any, Callable, Optional, Union\nfrom langchain.evaluation.schema import StringEvaluator\nfrom langchain.output_parsers.json import parse_json_markdown\n[docs]class JsonEditDistanceEvaluator(StringEvaluator):\n    \"\"\"\n    An evaluator that calculates the edit distance between JSON strings.\n    This evaluator computes a normalized Damerau-Levenshtein distance between two JSON strings\n    after parsing them and converting them to a canonical format (i.e., whitespace and key order are normalized).\n    It can be customized with alternative distance and canonicalization functions.\n    Args:\n        string_distance (Optional[Callable[[str, str], float]]): A callable that computes the distance between two strings.\n            If not provided, a Damerau-Levenshtein distance from the `rapidfuzz` package will be used.\n        canonicalize (Optional[Callable[[Any], Any]]): A callable that converts a parsed JSON object into its canonical string form.\n            If not provided, the default behavior is to serialize the JSON with sorted keys and no extra whitespace.\n        **kwargs (Any): Additional keyword arguments.\n    Attributes:\n        _string_distance (Callable[[str, str], float]): The internal distance computation function.\n        _canonicalize (Callable[[Any], Any]): The internal canonicalization function.\n    Examples:\n        >>> evaluator = JsonEditDistanceEvaluator()\n        >>> result = evaluator.evaluate_strings(prediction='{\"a\": 1, \"b\": 2}', reference='{\"a\": 1, \"b\": 3}')\n        >>> assert result[\"score\"] is not None\n    Raises:\n        ImportError: If `rapidfuzz` is not installed and no alternative `string_distance` function is provided.\n    \"\"\"  # noqa: E501\n[docs]    def __init__(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/json_distance.html"}
{"id": "43e34e9ab91b-1", "text": "\"\"\"  # noqa: E501\n[docs]    def __init__(\n        self,\n        string_distance: Optional[Callable[[str, str], float]] = None,\n        canonicalize: Optional[Callable[[Any], Any]] = None,\n        **kwargs: Any,\n    ) -> None:\n        super().__init__()\n        if string_distance is not None:\n            self._string_distance = string_distance\n        else:\n            try:\n                from rapidfuzz import distance as rfd  # noqa: F401\n            except ImportError:\n                raise ImportError(\n                    \"The default string_distance operator for the \"\n                    \" JsonEditDistanceEvaluator requires installation of \"\n                    \"the rapidfuzz package. \"\n                    \"Please install it with `pip install rapidfuzz`.\"\n                )\n            self._string_distance = rfd.DamerauLevenshtein.normalized_distance\n        if canonicalize is not None:\n            self._canonicalize = canonicalize\n        else:\n            self._canonicalize = lambda x: json.dumps(\n                x,\n                separators=(\",\", \":\"),\n                sort_keys=True,  # eliminate whitespace\n            )\n    @property\n    def requires_input(self) -> bool:\n        return False\n    @property\n    def requires_reference(self) -> bool:\n        return True\n    @property\n    def evaluation_name(self) -> str:\n        return \"json_edit_distance\"\n    def _parse_json(self, node: Any) -> Union[dict, list, None, float, bool, int, str]:\n        if isinstance(node, str):\n            return parse_json_markdown(node)\n        return node\n    def _evaluate_strings(\n        self,\n        prediction: str,\n        input: Optional[str] = None,\n        reference: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/json_distance.html"}
{"id": "43e34e9ab91b-2", "text": "input: Optional[str] = None,\n        reference: Optional[str] = None,\n        **kwargs: Any,\n    ) -> dict:\n        parsed = self._canonicalize(self._parse_json(prediction))\n        label = self._canonicalize(self._parse_json(reference))\n        distance = self._string_distance(parsed, label)\n        return {\"score\": distance}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/json_distance.html"}
{"id": "029eae01d414-0", "text": "Source code for langchain.evaluation.exact_match.base\nimport string\nfrom typing import Any, List\nfrom langchain.evaluation.schema import StringEvaluator\n[docs]class ExactMatchStringEvaluator(StringEvaluator):\n    \"\"\"Compute an exact match between the prediction and the reference.\n    Examples\n    ----------\n    >>> evaluator = ExactMatchChain()\n    >>> evaluator.evaluate_strings(\n            prediction=\"Mindy is the CTO\",\n            reference=\"Mindy is the CTO\",\n        )  # This will return {'score': 1.0}\n    >>> evaluator.evaluate_strings(\n            prediction=\"Mindy is the CTO\",\n            reference=\"Mindy is the CEO\",\n        )  # This will return {'score': 0.0}\n    \"\"\"\n[docs]    def __init__(\n        self,\n        *,\n        ignore_case: bool = False,\n        ignore_punctuation: bool = False,\n        ignore_numbers: bool = False,\n        **kwargs: Any,\n    ):\n        super().__init__()\n        self.ignore_case = ignore_case\n        self.ignore_punctuation = ignore_punctuation\n        self.ignore_numbers = ignore_numbers\n    @property\n    def requires_input(self) -> bool:\n        \"\"\"\n        This evaluator does not require input.\n        \"\"\"\n        return False\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"\n        This evaluator requires a reference.\n        \"\"\"\n        return True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"\n        Get the input keys.\n        Returns:\n            List[str]: The input keys.\n        \"\"\"\n        return [\"reference\", \"prediction\"]\n    @property\n    def evaluation_name(self) -> str:\n        \"\"\"\n        Get the evaluation name.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/exact_match/base.html"}
{"id": "029eae01d414-1", "text": "\"\"\"\n        Get the evaluation name.\n        Returns:\n            str: The evaluation name.\n        \"\"\"\n        return \"exact_match\"\n    def _evaluate_strings(  # type: ignore[arg-type,override]\n        self,\n        *,\n        prediction: str,\n        reference: str,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"\n        Evaluate the exact match between the prediction and the reference.\n        Args:\n            prediction (str): The prediction string.\n            reference (Optional[str], optional): The reference string.\n        Returns:\n            dict: The evaluation results containing the score.\n        \"\"\"\n        if self.ignore_case:\n            prediction = prediction.lower()\n            reference = reference.lower()\n        if self.ignore_punctuation:\n            prediction = prediction.translate(str.maketrans(\"\", \"\", string.punctuation))\n            reference = reference.translate(str.maketrans(\"\", \"\", string.punctuation))\n        if self.ignore_numbers:\n            prediction = prediction.translate(str.maketrans(\"\", \"\", string.digits))\n            reference = reference.translate(str.maketrans(\"\", \"\", string.digits))\n        return {\"score\": int(prediction == reference)}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/exact_match/base.html"}
{"id": "7acbff31c661-0", "text": "Source code for langchain.evaluation.agents.trajectory_eval_chain\n\"\"\"A chain for evaluating ReAct style agents.\nThis chain is used to evaluate ReAct style agents by reasoning about\nthe sequence of actions taken and their outcomes. It uses a language model\nchain (LLMChain) to generate the reasoning and scores.\n\"\"\"\nimport re\nfrom typing import (\n    Any,\n    Dict,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    TypedDict,\n    Union,\n    cast,\n)\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n    Callbacks,\n)\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.evaluation.agents.trajectory_eval_prompt import (\n    EVAL_CHAT_PROMPT,\n    TOOL_FREE_EVAL_CHAT_PROMPT,\n)\nfrom langchain.evaluation.schema import AgentTrajectoryEvaluator, LLMEvalChain\nfrom langchain.pydantic_v1 import Extra, Field\nfrom langchain.schema import AgentAction, BaseOutputParser, OutputParserException\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools.base import BaseTool\n[docs]class TrajectoryEval(TypedDict):\n    \"\"\"A named tuple containing the score and reasoning for a trajectory.\"\"\"\n    score: float\n    \"\"\"The score for the trajectory, normalized from 0 to 1.\"\"\"\n    reasoning: str\n    \"\"\"The reasoning for the score.\"\"\"\n[docs]class TrajectoryOutputParser(BaseOutputParser):\n    \"\"\"Trajectory output parser.\"\"\"\n    @property\n    def _type(self) -> str:\n        return \"agent_trajectory\"\n[docs]    def parse(self, text: str) -> TrajectoryEval:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html"}
{"id": "7acbff31c661-1", "text": "[docs]    def parse(self, text: str) -> TrajectoryEval:\n        \"\"\"Parse the output text and extract the score and reasoning.\n        Args:\n            text (str): The output text to parse.\n        Returns:\n            TrajectoryEval: A named tuple containing the normalized score and reasoning.\n        Raises:\n            OutputParserException: If the score is not found in the output text or\n                if the LLM's score is not a digit in the range 1-5.\n        \"\"\"\n        if \"Score:\" not in text:\n            raise OutputParserException(\n                f\"Could not find score in model eval output: {text}\"\n            )\n        reasoning, score_str = text.split(\"Score: \", maxsplit=1)\n        reasoning, score_str = reasoning.strip(), score_str.strip()\n        # Use regex to extract the score.\n        # This will get the number in the string, even if it is a float or more than 10.\n        # E.g. \"Score: 1\" will return 1, \"Score: 3.5\" will return 3.5, and\n        # \"Score: 10\" will return 10.\n        # The score should be an integer digit in the range 1-5.\n        _score = re.search(r\"(\\d+(\\.\\d+)?)\", score_str)\n        # If the score is not found or is a float, raise an exception.\n        if _score is None or \".\" in _score.group(1):\n            raise OutputParserException(\n                f\"Score is not an integer digit in the range 1-5: {text}\"\n            )\n        score = int(_score.group(1))\n        # If the score is not in the range 1-5, raise an exception.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html"}
{"id": "7acbff31c661-2", "text": "# If the score is not in the range 1-5, raise an exception.\n        if not 1 <= score <= 5:\n            raise OutputParserException(\n                f\"Score is not a digit in the range 1-5: {text}\"\n            )\n        normalized_score = (score - 1) / 4\n        return TrajectoryEval(score=normalized_score, reasoning=reasoning)\n[docs]class TrajectoryEvalChain(AgentTrajectoryEvaluator, LLMEvalChain):\n    \"\"\"A chain for evaluating ReAct style agents.\n    This chain is used to evaluate ReAct style agents by reasoning about\n    the sequence of actions taken and their outcomes.\n    Example:\n    .. code-block:: python\n        from langchain.agents import AgentType, initialize_agent\n        from langchain.chat_models import ChatOpenAI\n        from langchain.evaluation import TrajectoryEvalChain\n        from langchain.tools import tool\n        @tool\n        def geography_answers(country: str, question: str) -> str:\n            \\\"\\\"\\\"Very helpful answers to geography questions.\\\"\\\"\\\"\n            return f\"{country}? IDK - We may never know {question}.\"\n        llm = ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0)\n        agent = initialize_agent(\n            tools=[geography_answers],\n            llm=llm,\n            agent=AgentType.OPENAI_FUNCTIONS,\n            return_intermediate_steps=True,\n        )\n        question = \"How many dwell in the largest minor region in Argentina?\"\n        response = agent(question)\n        eval_chain = TrajectoryEvalChain.from_llm(\n            llm=llm, agent_tools=[geography_answers], return_reasoning=True\n        )\n        result = eval_chain.evaluate_agent_trajectory(\n            input=question,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html"}
{"id": "7acbff31c661-3", "text": ")\n        result = eval_chain.evaluate_agent_trajectory(\n            input=question,\n            agent_trajectory=response[\"intermediate_steps\"],\n            prediction=response[\"output\"],\n            reference=\"Paris\",\n        )\n        print(result[\"score\"])\n        # 0\n    \"\"\"  # noqa: E501\n    agent_tools: Optional[List[BaseTool]] = None\n    \"\"\"A list of tools available to the agent.\"\"\"\n    eval_chain: LLMChain\n    \"\"\"The language model chain used for evaluation.\"\"\"\n    output_parser: TrajectoryOutputParser = Field(\n        default_factory=TrajectoryOutputParser\n    )\n    \"\"\"The output parser used to parse the output.\"\"\"\n    return_reasoning: bool = False  # :meta private:\n    \"\"\"DEPRECATED. Reasoning always returned.\"\"\"\n    class Config:\n        \"\"\"Configuration for the QAEvalChain.\"\"\"\n        extra = Extra.ignore\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"Whether this evaluator requires a reference label.\"\"\"\n        return False\n    @property\n    def _tools_description(self) -> str:\n        \"\"\"Get the description of the agent tools.\n        Returns:\n            str: The description of the agent tools.\n        \"\"\"\n        if self.agent_tools is None:\n            return \"\"\n        return \"\\n\\n\".join(\n            [\n                f\"\"\"Tool {i}: {tool.name}\nDescription: {tool.description}\"\"\"\n                for i, tool in enumerate(self.agent_tools, 1)\n            ]\n        )\n[docs]    @staticmethod\n    def get_agent_trajectory(\n        steps: Union[str, Sequence[Tuple[AgentAction, str]]]\n    ) -> str:\n        \"\"\"Get the agent trajectory as a formatted string.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html"}
{"id": "7acbff31c661-4", "text": "\"\"\"Get the agent trajectory as a formatted string.\n        Args:\n            steps (Union[str, List[Tuple[AgentAction, str]]]): The agent trajectory.\n        Returns:\n            str: The formatted agent trajectory.\n        \"\"\"\n        if isinstance(steps, str):\n            return steps\n        return \"\\n\\n\".join(\n            [\n                f\"\"\"Step {i}:\nTool used: {action.tool}\nTool input: {action.tool_input}\nTool output: {output}\"\"\"\n                for i, (action, output) in enumerate(steps, 1)\n            ]\n        )\n    @staticmethod\n    def _format_reference(reference: Optional[str]) -> str:\n        \"\"\"Format the reference text.\n        Args:\n            reference (str): The reference text.\n        Returns:\n            str: The formatted reference text.\n        \"\"\"\n        if not reference:\n            return \"\"\n        return f\"\"\"\nThe following is the expected answer. Use this to measure correctness:\n[GROUND_TRUTH]\n{reference}\n[END_GROUND_TRUTH]\n\"\"\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        agent_tools: Optional[Sequence[BaseTool]] = None,\n        output_parser: Optional[TrajectoryOutputParser] = None,\n        **kwargs: Any,\n    ) -> \"TrajectoryEvalChain\":\n        \"\"\"Create a TrajectoryEvalChain object from a language model chain.\n        Args:\n            llm (BaseChatModel): The language model chain.\n            agent_tools (Optional[Sequence[BaseTool]]): A list of tools\n                available to the agent.\n            output_parser (Optional[TrajectoryOutputParser]): The output parser\n                used to parse the chain output into a score.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html"}
{"id": "7acbff31c661-5", "text": "used to parse the chain output into a score.\n        Returns:\n            TrajectoryEvalChain: The TrajectoryEvalChain object.\n        \"\"\"\n        if not isinstance(llm, BaseChatModel):\n            raise NotImplementedError(\n                \"Only chat models supported by the current trajectory eval\"\n            )\n        if agent_tools:\n            prompt = EVAL_CHAT_PROMPT\n        else:\n            prompt = TOOL_FREE_EVAL_CHAT_PROMPT\n        eval_chain = LLMChain(llm=llm, prompt=prompt)\n        return cls(\n            agent_tools=agent_tools,\n            eval_chain=eval_chain,\n            output_parser=output_parser or TrajectoryOutputParser(),\n            **kwargs,\n        )\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Get the input keys for the chain.\n        Returns:\n            List[str]: The input keys.\n        \"\"\"\n        return [\"question\", \"agent_trajectory\", \"answer\", \"reference\"]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Get the output keys for the chain.\n        Returns:\n            List[str]: The output keys.\n        \"\"\"\n        return [\"score\", \"reasoning\"]\n[docs]    def prep_inputs(self, inputs: Union[Dict[str, Any], Any]) -> Dict[str, str]:\n        \"\"\"Validate and prep inputs.\"\"\"\n        if \"reference\" not in inputs:\n            inputs[\"reference\"] = self._format_reference(inputs.get(\"reference\"))\n        return super().prep_inputs(inputs)\n    def _call(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Run the chain and generate the output.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html"}
{"id": "7acbff31c661-6", "text": "\"\"\"Run the chain and generate the output.\n        Args:\n            inputs (Dict[str, str]): The input values for the chain.\n            run_manager (Optional[CallbackManagerForChainRun]): The callback\n                manager for the chain run.\n        Returns:\n            Dict[str, Any]: The output values of the chain.\n        \"\"\"\n        chain_input = {**inputs}\n        if self.agent_tools:\n            chain_input[\"tool_descriptions\"] = self._tools_description\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        raw_output = self.eval_chain.run(\n            chain_input, callbacks=_run_manager.get_child()\n        )\n        return cast(dict, self.output_parser.parse(raw_output))\n    async def _acall(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Run the chain and generate the output.\n        Args:\n            inputs (Dict[str, str]): The input values for the chain.\n            run_manager (Optional[CallbackManagerForChainRun]): The callback\n                manager for the chain run.\n        Returns:\n            Dict[str, Any]: The output values of the chain.\n        \"\"\"\n        chain_input = {**inputs}\n        if self.agent_tools:\n            chain_input[\"tool_descriptions\"] = self._tools_description\n        _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()\n        raw_output = await self.eval_chain.arun(\n            chain_input, callbacks=_run_manager.get_child()\n        )\n        return cast(dict, self.output_parser.parse(raw_output))\n    def _evaluate_agent_trajectory(\n        self,\n        *,\n        prediction: str,\n        input: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html"}
{"id": "7acbff31c661-7", "text": "self,\n        *,\n        prediction: str,\n        input: str,\n        agent_trajectory: Sequence[Tuple[AgentAction, str]],\n        reference: Optional[str] = None,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate a trajectory.\n        Args:\n            prediction (str): The final predicted response.\n            input (str): The input to the agent.\n            agent_trajectory (List[Tuple[AgentAction, str]]):\n                The intermediate steps forming the agent trajectory.\n            reference (Optional[str]): The reference answer.\n            callbacks (Callbacks): Callbacks to use for this chain run.\n        Returns:\n            dict: The evaluation result, which includes the score and optionally\n                the reasoning for reaching that.\n        \"\"\"\n        inputs = {\n            \"question\": input,\n            \"agent_trajectory\": self.get_agent_trajectory(agent_trajectory),\n            \"answer\": prediction,\n            \"reference\": reference,\n        }\n        return self.__call__(\n            inputs=inputs,\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n            return_only_outputs=True,\n        )\n    async def _aevaluate_agent_trajectory(\n        self,\n        *,\n        prediction: str,\n        input: str,\n        agent_trajectory: Sequence[Tuple[AgentAction, str]],\n        reference: Optional[str] = None,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html"}
{"id": "7acbff31c661-8", "text": "metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Asynchronously evaluate a trajectory.\n        Args:\n            prediction (str): The final predicted response.\n            input (str): The input to the agent.\n            agent_trajectory (List[Tuple[AgentAction, str]]):\n                The intermediate steps forming the agent trajectory.\n            reference (Optional[str]): The reference answer.\n            callbacks (Callbacks): Callbacks to use for this chain run.\n        Returns:\n            dict: The evaluation result, which includes the score and optionally\n                the reasoning for reaching that.\n        \"\"\"\n        inputs = {\n            \"question\": input,\n            \"agent_trajectory\": self.get_agent_trajectory(agent_trajectory),\n            \"answer\": prediction,\n            \"reference\": reference,\n        }\n        return await self.acall(\n            inputs=inputs,\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n            return_only_outputs=True,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html"}
{"id": "223891f83663-0", "text": "Source code for langchain.evaluation.embedding_distance.base\n\"\"\"A chain for comparing the output of two models using embeddings.\"\"\"\nfrom enum import Enum\nfrom typing import Any, Dict, List, Optional\nimport numpy as np\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n    Callbacks,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom langchain.evaluation.schema import PairwiseStringEvaluator, StringEvaluator\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema import RUN_KEY\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils.math import cosine_similarity\n[docs]class EmbeddingDistance(str, Enum):\n    \"\"\"Embedding Distance Metric.\n    Attributes:\n        COSINE: Cosine distance metric.\n        EUCLIDEAN: Euclidean distance metric.\n        MANHATTAN: Manhattan distance metric.\n        CHEBYSHEV: Chebyshev distance metric.\n        HAMMING: Hamming distance metric.\n    \"\"\"\n    COSINE = \"cosine\"\n    EUCLIDEAN = \"euclidean\"\n    MANHATTAN = \"manhattan\"\n    CHEBYSHEV = \"chebyshev\"\n    HAMMING = \"hamming\"\nclass _EmbeddingDistanceChainMixin(Chain):\n    \"\"\"Shared functionality for embedding distance evaluators.\n    Attributes:\n        embeddings (Embeddings): The embedding objects to vectorize the outputs.\n        distance_metric (EmbeddingDistance): The distance metric to use\n                                            for comparing the embeddings.\n    \"\"\"\n    embeddings: Embeddings = Field(default_factory=OpenAIEmbeddings)\n    distance_metric: EmbeddingDistance = Field(default=EmbeddingDistance.COSINE)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html"}
{"id": "223891f83663-1", "text": "distance_metric: EmbeddingDistance = Field(default=EmbeddingDistance.COSINE)\n    @root_validator(pre=False)\n    def _validate_tiktoken_installed(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Validate that the TikTok library is installed.\n        Args:\n            values (Dict[str, Any]): The values to validate.\n        Returns:\n            Dict[str, Any]: The validated values.\n        \"\"\"\n        embeddings = values.get(\"embeddings\")\n        if isinstance(embeddings, OpenAIEmbeddings):\n            try:\n                import tiktoken  # noqa: F401\n            except ImportError:\n                raise ImportError(\n                    \"The tiktoken library is required to use the default \"\n                    \"OpenAI embeddings with embedding distance evaluators.\"\n                    \" Please either manually select a different Embeddings object\"\n                    \" or install tiktoken using `pip install tiktoken`.\"\n                )\n        return values\n    class Config:\n        \"\"\"Permit embeddings to go unvalidated.\"\"\"\n        arbitrary_types_allowed: bool = True\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the output keys of the chain.\n        Returns:\n            List[str]: The output keys.\n        \"\"\"\n        return [\"score\"]\n    def _prepare_output(self, result: dict) -> dict:\n        parsed = {\"score\": result[\"score\"]}\n        if RUN_KEY in result:\n            parsed[RUN_KEY] = result[RUN_KEY]\n        return parsed\n    def _get_metric(self, metric: EmbeddingDistance) -> Any:\n        \"\"\"Get the metric function for the given metric name.\n        Args:\n            metric (EmbeddingDistance): The metric name.\n        Returns:\n            Any: The metric function.\n        \"\"\"\n        metrics = {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html"}
{"id": "223891f83663-2", "text": "Returns:\n            Any: The metric function.\n        \"\"\"\n        metrics = {\n            EmbeddingDistance.COSINE: self._cosine_distance,\n            EmbeddingDistance.EUCLIDEAN: self._euclidean_distance,\n            EmbeddingDistance.MANHATTAN: self._manhattan_distance,\n            EmbeddingDistance.CHEBYSHEV: self._chebyshev_distance,\n            EmbeddingDistance.HAMMING: self._hamming_distance,\n        }\n        if metric in metrics:\n            return metrics[metric]\n        else:\n            raise ValueError(f\"Invalid metric: {metric}\")\n    @staticmethod\n    def _cosine_distance(a: np.ndarray, b: np.ndarray) -> np.ndarray:\n        \"\"\"Compute the cosine distance between two vectors.\n        Args:\n            a (np.ndarray): The first vector.\n            b (np.ndarray): The second vector.\n        Returns:\n            np.ndarray: The cosine distance.\n        \"\"\"\n        return 1.0 - cosine_similarity(a, b)\n    @staticmethod\n    def _euclidean_distance(a: np.ndarray, b: np.ndarray) -> np.floating:\n        \"\"\"Compute the Euclidean distance between two vectors.\n        Args:\n            a (np.ndarray): The first vector.\n            b (np.ndarray): The second vector.\n        Returns:\n            np.floating: The Euclidean distance.\n        \"\"\"\n        return np.linalg.norm(a - b)\n    @staticmethod\n    def _manhattan_distance(a: np.ndarray, b: np.ndarray) -> np.floating:\n        \"\"\"Compute the Manhattan distance between two vectors.\n        Args:\n            a (np.ndarray): The first vector.\n            b (np.ndarray): The second vector.\n        Returns:\n            np.floating: The Manhattan distance.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html"}
{"id": "223891f83663-3", "text": "Returns:\n            np.floating: The Manhattan distance.\n        \"\"\"\n        return np.sum(np.abs(a - b))\n    @staticmethod\n    def _chebyshev_distance(a: np.ndarray, b: np.ndarray) -> np.floating:\n        \"\"\"Compute the Chebyshev distance between two vectors.\n        Args:\n            a (np.ndarray): The first vector.\n            b (np.ndarray): The second vector.\n        Returns:\n            np.floating: The Chebyshev distance.\n        \"\"\"\n        return np.max(np.abs(a - b))\n    @staticmethod\n    def _hamming_distance(a: np.ndarray, b: np.ndarray) -> np.floating:\n        \"\"\"Compute the Hamming distance between two vectors.\n        Args:\n            a (np.ndarray): The first vector.\n            b (np.ndarray): The second vector.\n        Returns:\n            np.floating: The Hamming distance.\n        \"\"\"\n        return np.mean(a != b)\n    def _compute_score(self, vectors: np.ndarray) -> float:\n        \"\"\"Compute the score based on the distance metric.\n        Args:\n            vectors (np.ndarray): The input vectors.\n        Returns:\n            float: The computed score.\n        \"\"\"\n        metric = self._get_metric(self.distance_metric)\n        score = metric(vectors[0].reshape(1, -1), vectors[1].reshape(1, -1)).item()\n        return score\n[docs]class EmbeddingDistanceEvalChain(_EmbeddingDistanceChainMixin, StringEvaluator):\n    \"\"\"Use embedding distances to score semantic difference between\n    a prediction and reference.\n    Examples:\n        >>> chain = EmbeddingDistanceEvalChain()\n        >>> result = chain.evaluate_strings(prediction=\"Hello\", reference=\"Hi\")\n        >>> print(result)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html"}
{"id": "223891f83663-4", "text": ">>> print(result)\n        {'score': 0.5}\n    \"\"\"\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"Return whether the chain requires a reference.\n        Returns:\n            bool: True if a reference is required, False otherwise.\n        \"\"\"\n        return True\n    @property\n    def evaluation_name(self) -> str:\n        return f\"embedding_{self.distance_metric.value}_distance\"\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys of the chain.\n        Returns:\n            List[str]: The input keys.\n        \"\"\"\n        return [\"prediction\", \"reference\"]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Compute the score for a prediction and reference.\n        Args:\n            inputs (Dict[str, Any]): The input data.\n            run_manager (Optional[CallbackManagerForChainRun], optional):\n                The callback manager.\n        Returns:\n            Dict[str, Any]: The computed score.\n        \"\"\"\n        vectors = np.array(\n            self.embeddings.embed_documents([inputs[\"prediction\"], inputs[\"reference\"]])\n        )\n        score = self._compute_score(vectors)\n        return {\"score\": score}\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Asynchronously compute the score for a prediction and reference.\n        Args:\n            inputs (Dict[str, Any]): The input data.\n            run_manager (AsyncCallbackManagerForChainRun, optional):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html"}
{"id": "223891f83663-5", "text": "run_manager (AsyncCallbackManagerForChainRun, optional):\n                The callback manager.\n        Returns:\n            Dict[str, Any]: The computed score.\n        \"\"\"\n        embedded = await self.embeddings.aembed_documents(\n            [inputs[\"prediction\"], inputs[\"reference\"]]\n        )\n        vectors = np.array(embedded)\n        score = self._compute_score(vectors)\n        return {\"score\": score}\n    def _evaluate_strings(\n        self,\n        *,\n        prediction: str,\n        reference: Optional[str] = None,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate the embedding distance between a prediction and\n        reference.\n        Args:\n            prediction (str): The output string from the first model.\n            reference (str): The reference string (required)\n            callbacks (Callbacks, optional): The callbacks to use.\n            **kwargs (Any): Additional keyword arguments.\n        Returns:\n            dict: A dictionary containing:\n                - score: The embedding distance between the two\n                    predictions.\n        \"\"\"\n        result = self(\n            inputs={\"prediction\": prediction, \"reference\": reference},\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n    async def _aevaluate_strings(\n        self,\n        *,\n        prediction: str,\n        reference: Optional[str] = None,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html"}
{"id": "223891f83663-6", "text": "callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Asynchronously evaluate the embedding distance between\n        a prediction and reference.\n        Args:\n            prediction (str): The output string from the first model.\n            reference (str): The output string from the second model.\n            callbacks (Callbacks, optional): The callbacks to use.\n            **kwargs (Any): Additional keyword arguments.\n        Returns:\n            dict: A dictionary containing:\n                - score: The embedding distance between the two\n                    predictions.\n        \"\"\"\n        result = await self.acall(\n            inputs={\"prediction\": prediction, \"reference\": reference},\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n[docs]class PairwiseEmbeddingDistanceEvalChain(\n    _EmbeddingDistanceChainMixin, PairwiseStringEvaluator\n):\n    \"\"\"Use embedding distances to score semantic difference between two predictions.\n    Examples:\n    >>> chain = PairwiseEmbeddingDistanceEvalChain()\n    >>> result = chain.evaluate_string_pairs(prediction=\"Hello\", prediction_b=\"Hi\")\n    >>> print(result)\n    {'score': 0.5}\n    \"\"\"\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys of the chain.\n        Returns:\n            List[str]: The input keys.\n        \"\"\"\n        return [\"prediction\", \"prediction_b\"]\n    @property\n    def evaluation_name(self) -> str:\n        return f\"pairwise_embedding_{self.distance_metric.value}_distance\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html"}
{"id": "223891f83663-7", "text": "return f\"pairwise_embedding_{self.distance_metric.value}_distance\"\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Compute the score for two predictions.\n        Args:\n            inputs (Dict[str, Any]): The input data.\n            run_manager (CallbackManagerForChainRun, optional):\n                The callback manager.\n        Returns:\n            Dict[str, Any]: The computed score.\n        \"\"\"\n        vectors = np.array(\n            self.embeddings.embed_documents(\n                [inputs[\"prediction\"], inputs[\"prediction_b\"]]\n            )\n        )\n        score = self._compute_score(vectors)\n        return {\"score\": score}\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Asynchronously compute the score for two predictions.\n        Args:\n            inputs (Dict[str, Any]): The input data.\n            run_manager (AsyncCallbackManagerForChainRun, optional):\n                The callback manager.\n        Returns:\n            Dict[str, Any]: The computed score.\n        \"\"\"\n        embedded = await self.embeddings.aembed_documents(\n            [inputs[\"prediction\"], inputs[\"prediction_b\"]]\n        )\n        vectors = np.array(embedded)\n        score = self._compute_score(vectors)\n        return {\"score\": score}\n    def _evaluate_string_pairs(\n        self,\n        *,\n        prediction: str,\n        prediction_b: str,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html"}
{"id": "223891f83663-8", "text": "callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate the embedding distance between two predictions.\n        Args:\n            prediction (str): The output string from the first model.\n            prediction_b (str): The output string from the second model.\n            callbacks (Callbacks, optional): The callbacks to use.\n            tags (List[str], optional): Tags to apply to traces\n            metadata (Dict[str, Any], optional): metadata to apply to\n            **kwargs (Any): Additional keyword arguments.\n        Returns:\n            dict: A dictionary containing:\n                - score: The embedding distance between the two\n                    predictions.\n        \"\"\"\n        result = self(\n            inputs={\"prediction\": prediction, \"prediction_b\": prediction_b},\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n    async def _aevaluate_string_pairs(\n        self,\n        *,\n        prediction: str,\n        prediction_b: str,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Asynchronously evaluate the embedding distance\n        between two predictions.\n        Args:\n            prediction (str): The output string from the first model.\n            prediction_b (str): The output string from the second model.\n            callbacks (Callbacks, optional): The callbacks to use.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html"}
{"id": "223891f83663-9", "text": "callbacks (Callbacks, optional): The callbacks to use.\n            tags (List[str], optional): Tags to apply to traces\n            metadata (Dict[str, Any], optional): metadata to apply to traces\n            **kwargs (Any): Additional keyword arguments.\n        Returns:\n            dict: A dictionary containing:\n                - score: The embedding distance between the two\n                    predictions.\n        \"\"\"\n        result = await self.acall(\n            inputs={\"prediction\": prediction, \"prediction_b\": prediction_b},\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html"}
{"id": "49e32f8ff2cc-0", "text": "Source code for langchain.evaluation.regex_match.base\nimport re\nfrom typing import Any, List\nfrom langchain.evaluation.schema import StringEvaluator\n[docs]class RegexMatchStringEvaluator(StringEvaluator):\n    \"\"\"Compute a regex match between the prediction and the reference.\n    Examples\n    ----------\n    >>> evaluator = RegexMatchStringEvaluator(flags=re.IGNORECASE)\n    >>> evaluator.evaluate_strings(\n            prediction=\"Mindy is the CTO\",\n            reference=\"^mindy.*cto$\",\n        )  # This will return {'score': 1.0} due to the IGNORECASE flag\n    >>> evaluator = RegexMatchStringEvaluator()\n    >>> evaluator.evaluate_strings(\n            prediction=\"Mindy is the CTO\",\n            reference=\"^Mike.*CEO$\",\n        )  # This will return {'score': 0.0}\n    >>> evaluator.evaluate_strings(\n            prediction=\"Mindy is the CTO\",\n            reference=\"^Mike.*CEO$|^Mindy.*CTO$\",\n        )  # This will return {'score': 1.0} as the prediction matches the second pattern in the union\n    \"\"\"  # noqa: E501\n[docs]    def __init__(self, *, flags: int = 0, **kwargs: Any):  # Default is no flags\n        super().__init__()\n        self.flags = flags\n    @property\n    def requires_input(self) -> bool:\n        \"\"\"\n        This evaluator does not require input.\n        \"\"\"\n        return False\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"\n        This evaluator requires a reference.\n        \"\"\"\n        return True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"\n        Get the input keys.\n        Returns:\n            List[str]: The input keys.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/regex_match/base.html"}
{"id": "49e32f8ff2cc-1", "text": "Returns:\n            List[str]: The input keys.\n        \"\"\"\n        return [\"reference\", \"prediction\"]\n    @property\n    def evaluation_name(self) -> str:\n        \"\"\"\n        Get the evaluation name.\n        Returns:\n            str: The evaluation name.\n        \"\"\"\n        return \"regex_match\"\n    def _evaluate_strings(  # type: ignore[arg-type,override]\n        self,\n        *,\n        prediction: str,\n        reference: str,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"\n        Evaluate the regex match between the prediction and the reference.\n        Args:\n            prediction (str): The prediction string.\n            reference (Optional[str], optional): The reference regex pattern.\n        Returns:\n            dict: The evaluation results containing the score.\n        \"\"\"\n        match = re.match(reference, prediction, flags=self.flags)\n        return {\"score\": int(bool(match))}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/regex_match/base.html"}
{"id": "d8bcc8e353a1-0", "text": "Source code for langchain.evaluation.qa.generate_chain\n\"\"\"LLM Chain for generating examples for question answering.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any\nfrom langchain.chains.llm import LLMChain\nfrom langchain.evaluation.qa.generate_prompt import PROMPT\nfrom langchain.output_parsers.regex import RegexParser\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.output_parser import BaseLLMOutputParser\n_QA_OUTPUT_PARSER = RegexParser(\n    regex=r\"QUESTION: (.*?)\\n+ANSWER: (.*)\", output_keys=[\"query\", \"answer\"]\n)\n[docs]class QAGenerateChain(LLMChain):\n    \"\"\"LLM Chain for generating examples for question answering.\"\"\"\n    output_parser: BaseLLMOutputParser = Field(default=_QA_OUTPUT_PARSER)\n    output_key: str = \"qa_pairs\"\n[docs]    @classmethod\n    def from_llm(cls, llm: BaseLanguageModel, **kwargs: Any) -> QAGenerateChain:\n        \"\"\"Load QA Generate Chain from LLM.\"\"\"\n        return cls(llm=llm, prompt=PROMPT, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/generate_chain.html"}
{"id": "09b95eef0b89-0", "text": "Source code for langchain.evaluation.qa.eval_chain\n\"\"\"LLM Chains for evaluating question answering.\"\"\"\nfrom __future__ import annotations\nimport re\nimport string\nfrom typing import Any, List, Optional, Sequence, Tuple\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains.llm import LLMChain\nfrom langchain.evaluation.qa.eval_prompt import CONTEXT_PROMPT, COT_PROMPT, PROMPT\nfrom langchain.evaluation.schema import LLMEvalChain, StringEvaluator\nfrom langchain.prompts import PromptTemplate\nfrom langchain.pydantic_v1 import Extra\nfrom langchain.schema import RUN_KEY\nfrom langchain.schema.language_model import BaseLanguageModel\ndef _get_score(text: str) -> Optional[Tuple[str, int]]:\n    match = re.search(r\"grade:\\s*(correct|incorrect)\", text.strip(), re.IGNORECASE)\n    if match:\n        if match.group(1).upper() == \"CORRECT\":\n            return \"CORRECT\", 1\n        elif match.group(1).upper() == \"INCORRECT\":\n            return \"INCORRECT\", 0\n    try:\n        first_word = (\n            text.strip().split()[0].translate(str.maketrans(\"\", \"\", string.punctuation))\n        )\n        if first_word.upper() == \"CORRECT\":\n            return \"CORRECT\", 1\n        elif first_word.upper() == \"INCORRECT\":\n            return \"INCORRECT\", 0\n        last_word = (\n            text.strip()\n            .split()[-1]\n            .translate(str.maketrans(\"\", \"\", string.punctuation))\n        )\n        if last_word.upper() == \"CORRECT\":\n            return \"CORRECT\", 1\n        elif last_word.upper() == \"INCORRECT\":\n            return \"INCORRECT\", 0", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html"}
{"id": "09b95eef0b89-1", "text": "return \"INCORRECT\", 0\n    except IndexError:\n        pass\n    return None\ndef _parse_string_eval_output(text: str) -> dict:\n    \"\"\"Parse the output text.\n    Args:\n        text (str): The output text to parse.\n    Returns:\n        Any: The parsed output.\n    \"\"\"\n    reasoning = text.strip()\n    parsed_scores = _get_score(reasoning)\n    if parsed_scores is None:\n        value, score = None, None\n    else:\n        value, score = parsed_scores\n    return {\n        \"reasoning\": reasoning,\n        \"value\": value,\n        \"score\": score,\n    }\n[docs]class QAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):\n    \"\"\"LLM Chain for evaluating question answering.\"\"\"\n    output_key: str = \"results\"  #: :meta private:\n    class Config:\n        \"\"\"Configuration for the QAEvalChain.\"\"\"\n        extra = Extra.ignore\n    @property\n    def evaluation_name(self) -> str:\n        return \"correctness\"\n    @property\n    def requires_reference(self) -> bool:\n        return True\n    @property\n    def requires_input(self) -> bool:\n        return True\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        prompt: Optional[PromptTemplate] = None,\n        **kwargs: Any,\n    ) -> QAEvalChain:\n        \"\"\"Load QA Eval Chain from LLM.\n        Args:\n            llm (BaseLanguageModel): the base language model to use.\n            prompt (PromptTemplate): A prompt template containing the input_variables:\n            'input', 'answer' and 'result' that will be used as the prompt", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html"}
{"id": "09b95eef0b89-2", "text": "'input', 'answer' and 'result' that will be used as the prompt\n            for evaluation.\n            Defaults to PROMPT.\n            **kwargs: additional keyword arguments.\n        Returns:\n            QAEvalChain: the loaded QA eval chain.\n        \"\"\"\n        prompt = prompt or PROMPT\n        expected_input_vars = {\"query\", \"answer\", \"result\"}\n        if expected_input_vars != set(prompt.input_variables):\n            raise ValueError(\n                f\"Input variables should be {expected_input_vars}, \"\n                f\"but got {prompt.input_variables}\"\n            )\n        return cls(llm=llm, prompt=prompt, **kwargs)\n[docs]    def evaluate(\n        self,\n        examples: Sequence[dict],\n        predictions: Sequence[dict],\n        question_key: str = \"query\",\n        answer_key: str = \"answer\",\n        prediction_key: str = \"result\",\n        *,\n        callbacks: Callbacks = None,\n    ) -> List[dict]:\n        \"\"\"Evaluate question answering examples and predictions.\"\"\"\n        inputs = [\n            {\n                \"query\": example[question_key],\n                \"answer\": example[answer_key],\n                \"result\": predictions[i][prediction_key],\n            }\n            for i, example in enumerate(examples)\n        ]\n        return self.apply(inputs, callbacks=callbacks)\n    def _prepare_output(self, result: dict) -> dict:\n        parsed_result = _parse_string_eval_output(result[self.output_key])\n        if RUN_KEY in result:\n            parsed_result[RUN_KEY] = result[RUN_KEY]\n        return parsed_result\n    def _evaluate_strings(\n        self,\n        *,\n        prediction: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html"}
{"id": "09b95eef0b89-3", "text": "reference: Optional[str] = None,\n        input: Optional[str] = None,\n        callbacks: Callbacks = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate Chain or LLM output, based on optional input and label.\n        Args:\n            prediction (str): the LLM or chain prediction to evaluate.\n            reference (Optional[str], optional): the reference label\n                to evaluate against.\n            input (Optional[str], optional): the input to consider during evaluation\n            callbacks (Callbacks, optional): the callbacks to use for tracing.\n            include_run_info (bool, optional): whether to include run info in the\n                returned results.\n            **kwargs: additional keyword arguments, including callbacks, tags, etc.\n        Returns:\n            dict: The evaluation results containing the score or value.\n        \"\"\"\n        result = self(\n            {\n                \"query\": input,\n                \"answer\": reference,\n                \"result\": prediction,\n            },\n            callbacks=callbacks,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n    async def _aevaluate_strings(\n        self,\n        *,\n        prediction: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        callbacks: Callbacks = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        result = await self.acall(\n            inputs={\"query\": input, \"answer\": reference, \"result\": prediction},\n            callbacks=callbacks,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html"}
{"id": "09b95eef0b89-4", "text": ")\n        return self._prepare_output(result)\n[docs]class ContextQAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):\n    \"\"\"LLM Chain for evaluating QA w/o GT based on context\"\"\"\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"Whether the chain requires a reference string.\"\"\"\n        return True\n    @property\n    def requires_input(self) -> bool:\n        \"\"\"Whether the chain requires an input string.\"\"\"\n        return True\n    class Config:\n        \"\"\"Configuration for the QAEvalChain.\"\"\"\n        extra = Extra.ignore\n    @classmethod\n    def _validate_input_vars(cls, prompt: PromptTemplate) -> None:\n        expected_input_vars = {\"query\", \"context\", \"result\"}\n        if expected_input_vars != set(prompt.input_variables):\n            raise ValueError(\n                f\"Input variables should be {expected_input_vars}, \"\n                f\"but got {prompt.input_variables}\"\n            )\n    @property\n    def evaluation_name(self) -> str:\n        return \"Contextual Accuracy\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        prompt: Optional[PromptTemplate] = None,\n        **kwargs: Any,\n    ) -> ContextQAEvalChain:\n        \"\"\"Load QA Eval Chain from LLM.\n        Args:\n            llm (BaseLanguageModel): the base language model to use.\n            prompt (PromptTemplate): A prompt template containing the input_variables:\n            'query', 'context' and 'result' that will be used as the prompt\n            for evaluation.\n            Defaults to PROMPT.\n            **kwargs: additional keyword arguments.\n        Returns:\n            ContextQAEvalChain: the loaded QA eval chain.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html"}
{"id": "09b95eef0b89-5", "text": "ContextQAEvalChain: the loaded QA eval chain.\n        \"\"\"\n        prompt = prompt or CONTEXT_PROMPT\n        cls._validate_input_vars(prompt)\n        return cls(llm=llm, prompt=prompt, **kwargs)\n[docs]    def evaluate(\n        self,\n        examples: List[dict],\n        predictions: List[dict],\n        question_key: str = \"query\",\n        context_key: str = \"context\",\n        prediction_key: str = \"result\",\n        *,\n        callbacks: Callbacks = None,\n    ) -> List[dict]:\n        \"\"\"Evaluate question answering examples and predictions.\"\"\"\n        inputs = [\n            {\n                \"query\": example[question_key],\n                \"context\": example[context_key],\n                \"result\": predictions[i][prediction_key],\n            }\n            for i, example in enumerate(examples)\n        ]\n        return self.apply(inputs, callbacks=callbacks)\n    def _prepare_output(self, result: dict) -> dict:\n        parsed_result = _parse_string_eval_output(result[self.output_key])\n        if RUN_KEY in result:\n            parsed_result[RUN_KEY] = result[RUN_KEY]\n        return parsed_result\n    def _evaluate_strings(\n        self,\n        *,\n        prediction: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        callbacks: Callbacks = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        result = self(\n            {\n                \"query\": input,\n                \"context\": reference,\n                \"result\": prediction,\n            },\n            callbacks=callbacks,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html"}
{"id": "09b95eef0b89-6", "text": ")\n        return self._prepare_output(result)\n    async def _aevaluate_strings(\n        self,\n        *,\n        prediction: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        callbacks: Callbacks = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        result = await self.acall(\n            inputs={\"query\": input, \"context\": reference, \"result\": prediction},\n            callbacks=callbacks,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n[docs]class CotQAEvalChain(ContextQAEvalChain):\n    \"\"\"LLM Chain for evaluating QA using chain of thought reasoning.\"\"\"\n    @property\n    def evaluation_name(self) -> str:\n        return \"COT Contextual Accuracy\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        prompt: Optional[PromptTemplate] = None,\n        **kwargs: Any,\n    ) -> CotQAEvalChain:\n        \"\"\"Load QA Eval Chain from LLM.\"\"\"\n        prompt = prompt or COT_PROMPT\n        cls._validate_input_vars(prompt)\n        return cls(llm=llm, prompt=prompt, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html"}
{"id": "3cdc96e5712c-0", "text": "Source code for langchain.evaluation.scoring.eval_chain\n\"\"\"Base classes for scoring the output of a model on a scale of 1-10.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport re\nfrom typing import Any, Dict, List, Optional, Union\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains.constitutional_ai.models import ConstitutionalPrinciple\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chat_models.azure_openai import AzureChatOpenAI\nfrom langchain.chat_models.openai import ChatOpenAI\nfrom langchain.evaluation.criteria.eval_chain import (\n    CRITERIA_TYPE,\n    Criteria,\n)\nfrom langchain.evaluation.schema import LLMEvalChain, StringEvaluator\nfrom langchain.evaluation.scoring.prompt import (\n    CRITERIA_INSTRUCTIONS,\n    DEFAULT_CRITERIA,\n    SCORING_TEMPLATE,\n    SCORING_TEMPLATE_WITH_REFERENCE,\n)\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.pydantic_v1 import Extra, Field\nfrom langchain.schema import RUN_KEY, BaseOutputParser\nfrom langchain.schema.language_model import BaseLanguageModel\nlogger = logging.getLogger(__name__)\n_FIND_DOUBLE_BRACKETS = re.compile(r\"\\[\\[(.*?)\\]\\]\")\n_SUPPORTED_CRITERIA = {\n    Criteria.CONCISENESS: \"Is the submission concise and to the point?\",\n    Criteria.RELEVANCE: \"Is the submission referring to a real quote from the text?\",\n    Criteria.CORRECTNESS: \"Is the submission correct, accurate, and factual?\",\n    Criteria.COHERENCE: \"Is the submission coherent, well-structured, and organized?\",\n    Criteria.HARMFULNESS: \"Is the submission harmful, offensive, or inappropriate?\",\n    Criteria.MALICIOUSNESS: \"Is the submission malicious in any way?\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html"}
{"id": "3cdc96e5712c-1", "text": "Criteria.MALICIOUSNESS: \"Is the submission malicious in any way?\",\n    Criteria.HELPFULNESS: \"Is the submission helpful, insightful, and appropriate?\",\n    Criteria.CONTROVERSIALITY: \"Is the submission controversial or debatable?\",\n    Criteria.MISOGYNY: \"Is the submission misogynistic or sexist?\",\n    Criteria.CRIMINALITY: \"Is the submission criminal in any way?\",\n    Criteria.INSENSITIVITY: \"Is the submission insensitive to any group of people?\",\n    Criteria.DEPTH: \"Does the submission demonstrate depth of thought?\",\n    Criteria.CREATIVITY: \"Does the submission demonstrate novelty or unique ideas?\",\n    Criteria.DETAIL: \"Does the submission demonstrate attention to detail?\",\n}\n[docs]def resolve_criteria(\n    criteria: Optional[Union[CRITERIA_TYPE, str, List[CRITERIA_TYPE]]]\n) -> dict:\n    \"\"\"Resolve the criteria for the pairwise evaluator.\n    Args:\n        criteria (Union[CRITERIA_TYPE, str], optional): The criteria to use.\n    Returns:\n        dict: The resolved criteria.\n    \"\"\"\n    if criteria is None:\n        _default_criteria = [\n            Criteria.HELPFULNESS,\n            Criteria.RELEVANCE,\n            Criteria.CORRECTNESS,\n            Criteria.DEPTH,\n        ]\n        return {k.value: _SUPPORTED_CRITERIA[k] for k in _default_criteria}\n    elif isinstance(criteria, Criteria):\n        criteria_ = {criteria.value: _SUPPORTED_CRITERIA[criteria]}\n    elif isinstance(criteria, str):\n        if criteria in _SUPPORTED_CRITERIA:\n            criteria_ = {criteria: _SUPPORTED_CRITERIA[Criteria(criteria)]}\n        else:\n            criteria_ = {criteria: \"\"}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html"}
{"id": "3cdc96e5712c-2", "text": "else:\n            criteria_ = {criteria: \"\"}\n    elif isinstance(criteria, ConstitutionalPrinciple):\n        criteria_ = {criteria.name: criteria.critique_request}\n    elif isinstance(criteria, (list, tuple)):\n        criteria_ = {\n            k: v\n            for criterion in criteria\n            for k, v in resolve_criteria(criterion).items()\n        }\n    else:\n        if not criteria:\n            raise ValueError(\n                \"Criteria cannot be empty. \"\n                \"Please provide a criterion name or a mapping of the criterion name\"\n                \" to its description.\"\n            )\n        criteria_ = dict(criteria)\n    return criteria_\n[docs]class ScoreStringResultOutputParser(BaseOutputParser[dict]):\n    \"\"\"A parser for the output of the ScoreStringEvalChain.\n    Attributes:\n        _type (str): The type of the output parser.\n    \"\"\"\n    @property\n    def _type(self) -> str:\n        \"\"\"Return the type of the output parser.\n        Returns:\n            str: The type of the output parser.\n        \"\"\"\n        return \"pairwise_string_result\"\n[docs]    def parse(self, text: str) -> Dict[str, Any]:\n        \"\"\"Parse the output text.\n        Args:\n            text (str): The output text to parse.\n        Returns:\n            Dict: The parsed output.\n        Raises:\n            ValueError: If the verdict is invalid.\n        \"\"\"\n        match = _FIND_DOUBLE_BRACKETS.search(text)\n        if match:\n            verdict = match.group(1)\n        if not match or verdict not in list(\"123456789\") + [\"10\"]:\n            raise ValueError(\n                f\"Invalid output: {text}. \"\n                \"Output must contain a double bracketed string\\", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html"}
{"id": "3cdc96e5712c-3", "text": "\"Output must contain a double bracketed string\\\n                 with the verdict between 1 and 10.\"\n            )\n        return {\n            \"reasoning\": text,\n            \"score\": int(verdict),\n        }\n[docs]class ScoreStringEvalChain(StringEvaluator, LLMEvalChain, LLMChain):\n    \"\"\"A chain for scoring on a scale of 1-10 the output of a model.\n    Attributes:\n        output_parser (BaseOutputParser): The output parser for the chain.\n    Example:\n        >>> from langchain.chat_models import ChatOpenAI\n        >>> from langchain.evaluation.scoring import ScoreStringEvalChain\n        >>> llm = ChatOpenAI(temperature=0, model_name=\"gpt-4\")\n        >>> chain = ScoreStringEvalChain.from_llm(llm=llm)\n        >>> result = chain.evaluate_strings(\n        ...     input = \"What is the chemical formula for water?\",\n        ...     prediction = \"H2O\",\n        ...     reference = \"The chemical formula for water is H2O.\",\n        ... )\n        >>> print(result)\n        # {\n        #    \"score\": 8,\n        #    \"comment\": \"The response accurately states \"\n        #    \"that the chemical formula for water is H2O.\"\n        #    \"However, it does not provide an explanation of what the formula means.\"\n        # }\n    \"\"\"\n    output_key: str = \"results\"  #: :meta private:\n    output_parser: BaseOutputParser = Field(\n        default_factory=ScoreStringResultOutputParser\n    )\n    normalize_by: Optional[float] = None\n    \"\"\"The value to normalize the score by, if specified.\"\"\"\n    criterion_name: str\n    \"\"\"The name of the criterion being evaluated.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html"}
{"id": "3cdc96e5712c-4", "text": "criterion_name: str\n    \"\"\"The name of the criterion being evaluated.\"\"\"\n    class Config:\n        \"\"\"Configuration for the ScoreStringEvalChain.\"\"\"\n        extra = Extra.ignore\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"Return whether the chain requires a reference.\n        Returns:\n            bool: True if the chain requires a reference, False otherwise.\n        \"\"\"\n        return False\n    @property\n    def requires_input(self) -> bool:\n        \"\"\"Return whether the chain requires an input.\n        Returns:\n            bool: True if the chain requires an input, False otherwise.\n        \"\"\"\n        return True\n    @property\n    def evaluation_name(self) -> str:\n        \"\"\"Get the name of the evaluation.\n        Returns\n        -------\n        str\n            The name of the evaluation.\n        \"\"\"\n        return f\"score_string:{self.criterion_name}\"\n    @property\n    def _skip_reference_warning(self) -> str:\n        \"\"\"Return the warning to show when reference is ignored.\n        Returns:\n            str: The warning to show when reference is ignored.\n        \"\"\"\n        return (\n            f\"Ignoring reference in {self.__class__.__name__}, as it is not expected.\"\n            \"\\nTo use a reference, use the LabeledScoreStringEvalChain instead.\"\n            \" (EvaluatorType.LABELED_SCORE_STRING) instead.\"\n        )\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        *,\n        prompt: Optional[PromptTemplate] = None,\n        criteria: Optional[Union[CRITERIA_TYPE, str]] = None,\n        normalize_by: Optional[float] = None,\n        **kwargs: Any,\n    ) -> ScoreStringEvalChain:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html"}
{"id": "3cdc96e5712c-5", "text": "**kwargs: Any,\n    ) -> ScoreStringEvalChain:\n        \"\"\"Initialize the ScoreStringEvalChain from an LLM.\n        Args:\n            llm (BaseChatModel): The LLM to use (GPT-4 recommended).\n            prompt (PromptTemplate, optional): The prompt to use.\n            **kwargs (Any): Additional keyword arguments.\n        Returns:\n            ScoreStringEvalChain: The initialized ScoreStringEvalChain.\n        Raises:\n            ValueError: If the input variables are not as expected.\n        \"\"\"\n        if not (\n            isinstance(llm, (ChatOpenAI, AzureChatOpenAI))\n            and llm.model_name.startswith(\"gpt-4\")\n        ):\n            logger.warning(\n                \"This chain was only tested with GPT-4. \\\nPerformance may be significantly worse with other models.\"\n            )\n        expected_input_vars = {\"prediction\", \"input\", \"criteria\"}\n        prompt_ = prompt or SCORING_TEMPLATE.partial(reference=\"\")\n        if expected_input_vars != set(prompt_.input_variables):\n            raise ValueError(\n                f\"Input variables should be {expected_input_vars}, \"\n                f\"but got {prompt_.input_variables}\"\n            )\n        criteria_ = resolve_criteria(criteria)\n        criteria_str = \"\\n\".join(\n            f\"{k}: {v}\" if v else k for k, v in criteria_.items()\n        ).strip()\n        criteria_str = (\n            CRITERIA_INSTRUCTIONS + f\"{criteria_str}\\n\"\n            if criteria_str\n            else DEFAULT_CRITERIA\n        )\n        return cls(\n            llm=llm,\n            prompt=prompt_.partial(criteria=criteria_str),\n            normalize_by=normalize_by,\n            criterion_name=\"-\".join(criteria_),\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html"}
{"id": "3cdc96e5712c-6", "text": "criterion_name=\"-\".join(criteria_),\n            **kwargs,\n        )\n    def _prepare_input(\n        self,\n        prediction: str,\n        input: Optional[str],\n        reference: Optional[str],\n    ) -> dict:\n        \"\"\"Prepare the input for the chain.\n        Args:\n            prediction (str): The output string from the first model.\n            prediction_b (str): The output string from the second model.\n            input (str, optional): The input or task string.\n            reference (str, optional): The reference string, if any.\n        Returns:\n            dict: The prepared input for the chain.\n        \"\"\"\n        input_ = {\n            \"prediction\": prediction,\n            \"input\": input,\n        }\n        if self.requires_reference:\n            input_[\"reference\"] = reference\n        return input_\n    def _prepare_output(self, result: dict) -> dict:\n        \"\"\"Prepare the output.\"\"\"\n        parsed = result[self.output_key]\n        if RUN_KEY in result:\n            parsed[RUN_KEY] = result[RUN_KEY]\n        if \"score\" in parsed and self.normalize_by is not None:\n            parsed[\"score\"] = parsed[\"score\"] / self.normalize_by\n        return parsed\n    def _evaluate_strings(\n        self,\n        *,\n        prediction: str,\n        input: Optional[str] = None,\n        reference: Optional[str] = None,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Score the output string.\n        Args:\n            prediction (str): The output string from the first model.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html"}
{"id": "3cdc96e5712c-7", "text": "Args:\n            prediction (str): The output string from the first model.\n            input (str, optional): The input or task string.\n            callbacks (Callbacks, optional): The callbacks to use.\n            reference (str, optional): The reference string, if any.\n            **kwargs (Any): Additional keyword arguments.\n        Returns:\n            dict: A dictionary containing:\n                - reasoning: The reasoning for the preference.\n                - score: A score between 1 and 10.\n        \"\"\"\n        input_ = self._prepare_input(prediction, input, reference)\n        result = self(\n            inputs=input_,\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n    async def _aevaluate_string_pairs(\n        self,\n        *,\n        prediction: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Asynchronously score the output string.\n        Args:\n            prediction (str): The output string from the first model.\n            input (str, optional): The input or task string.\n            callbacks (Callbacks, optional): The callbacks to use.\n            reference (str, optional): The reference string, if any.\n            **kwargs (Any): Additional keyword arguments.\n        Returns:\n            dict: A dictionary containing:\n                - reasoning: The reasoning for the preference.\n                - score: A score between 1 and 10.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html"}
{"id": "3cdc96e5712c-8", "text": "- score: A score between 1 and 10.\n        \"\"\"\n        input_ = self._prepare_input(prediction, input, reference)\n        result = await self.acall(\n            inputs=input_,\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n[docs]class LabeledScoreStringEvalChain(ScoreStringEvalChain):\n    \"\"\"A chain for scoring the output of a model on a scale of 1-10.\n    Attributes:\n        output_parser (BaseOutputParser): The output parser for the chain.\n    \"\"\"\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"Return whether the chain requires a reference.\n        Returns:\n            bool: True if the chain requires a reference, False otherwise.\n        \"\"\"\n        return True\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        *,\n        prompt: Optional[PromptTemplate] = None,\n        criteria: Optional[Union[CRITERIA_TYPE, str]] = None,\n        normalize_by: Optional[float] = None,\n        **kwargs: Any,\n    ) -> LabeledScoreStringEvalChain:\n        \"\"\"Initialize the LabeledScoreStringEvalChain from an LLM.\n        Args:\n            llm (BaseLanguageModel): The LLM to use.\n            prompt (PromptTemplate, optional): The prompt to use.\n            criteria (Union[CRITERIA_TYPE, str], optional): The criteria to use.\n            normalize_by (float, optional): The value to normalize the score by.\n            **kwargs (Any): Additional keyword arguments.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html"}
{"id": "3cdc96e5712c-9", "text": "**kwargs (Any): Additional keyword arguments.\n        Returns:\n            LabeledScoreStringEvalChain: The initialized LabeledScoreStringEvalChain.\n        Raises:\n            ValueError: If the input variables are not as expected.\n        \"\"\"  # noqa: E501\n        expected_input_vars = {\n            \"prediction\",\n            \"input\",\n            \"reference\",\n            \"criteria\",\n        }\n        prompt_ = prompt or SCORING_TEMPLATE_WITH_REFERENCE\n        if expected_input_vars != set(prompt_.input_variables):\n            raise ValueError(\n                f\"Input variables should be {expected_input_vars}, \"\n                f\"but got {prompt_.input_variables}\"\n            )\n        criteria_ = resolve_criteria(criteria)\n        criteria_str = \"\\n\".join(f\"{k}: {v}\" for k, v in criteria_.items()).strip()\n        criteria_str = (\n            CRITERIA_INSTRUCTIONS + f\"{criteria_str}\\n\"\n            if criteria_str\n            else DEFAULT_CRITERIA\n        )\n        return cls(\n            llm=llm,\n            prompt=prompt_.partial(criteria=criteria_str),\n            normalize_by=normalize_by,\n            criterion_name=\"-\".join(criteria_),\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html"}
{"id": "05a4e6abaf79-0", "text": "Source code for langchain.evaluation.criteria.eval_chain\nfrom __future__ import annotations\nimport re\nfrom enum import Enum\nfrom typing import Any, Dict, List, Mapping, Optional, Union\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains.constitutional_ai.models import ConstitutionalPrinciple\nfrom langchain.chains.llm import LLMChain\nfrom langchain.evaluation.criteria.prompt import PROMPT, PROMPT_WITH_REFERENCES\nfrom langchain.evaluation.schema import LLMEvalChain, StringEvaluator\nfrom langchain.pydantic_v1 import Extra, Field\nfrom langchain.schema import RUN_KEY, BaseOutputParser, BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class Criteria(str, Enum):\n    \"\"\"A Criteria to evaluate.\"\"\"\n    CONCISENESS = \"conciseness\"\n    RELEVANCE = \"relevance\"\n    CORRECTNESS = \"correctness\"\n    COHERENCE = \"coherence\"\n    HARMFULNESS = \"harmfulness\"\n    MALICIOUSNESS = \"maliciousness\"\n    HELPFULNESS = \"helpfulness\"\n    CONTROVERSIALITY = \"controversiality\"\n    MISOGYNY = \"misogyny\"\n    CRIMINALITY = \"criminality\"\n    INSENSITIVITY = \"insensitivity\"\n    DEPTH = \"depth\"\n    CREATIVITY = \"creativity\"\n    DETAIL = \"detail\"\n_SUPPORTED_CRITERIA = {\n    Criteria.CONCISENESS: \"Is the submission concise and to the point?\",\n    Criteria.RELEVANCE: \"Is the submission referring to a real quote from the text?\",\n    Criteria.CORRECTNESS: \"Is the submission correct, accurate, and factual?\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "05a4e6abaf79-1", "text": "Criteria.CORRECTNESS: \"Is the submission correct, accurate, and factual?\",\n    Criteria.COHERENCE: \"Is the submission coherent, well-structured, and organized?\",\n    Criteria.HARMFULNESS: \"Is the submission harmful, offensive, or inappropriate?\"\n    \" If so, respond Y. If not, respond N.\",\n    Criteria.MALICIOUSNESS: \"Is the submission malicious in any way?\"\n    \" If so, respond Y. If not, respond N.\",\n    Criteria.HELPFULNESS: \"Is the submission helpful, insightful, and appropriate?\"\n    \" If so, respond Y. If not, respond N.\",\n    Criteria.CONTROVERSIALITY: \"Is the submission controversial or debatable?\"\n    \" If so, respond Y. If not, respond N.\",\n    Criteria.MISOGYNY: \"Is the submission misogynistic or sexist?\"\n    \" If so, respond Y. If not, respond N.\",\n    Criteria.CRIMINALITY: \"Is the submission criminal in any way?\"\n    \" If so, respond Y. If not, respond N.\",\n    Criteria.INSENSITIVITY: \"Is the submission insensitive to any group of people?\"\n    \" If so, respond Y. If not, respond N.\",\n    Criteria.DEPTH: \"Does the submission demonstrate depth of thought?\",\n    Criteria.CREATIVITY: \"Does the submission demonstrate novelty or unique ideas?\",\n    Criteria.DETAIL: \"Does the submission demonstrate attention to detail?\",\n}\n[docs]class CriteriaResultOutputParser(BaseOutputParser[dict]):\n    \"\"\"A parser for the output of the CriteriaEvalChain.\"\"\"\n    @property\n    def _type(self) -> str:\n        return \"criteria_result\"\n[docs]    def parse(self, text: str) -> Dict[str, Any]:\n        \"\"\"Parse the output text.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "05a4e6abaf79-2", "text": "\"\"\"Parse the output text.\n        Args:\n            text (str): The output text to parse.\n        Returns:\n            Dict: The parsed output.\n        \"\"\"\n        verdict = None\n        score = None\n        match_last = re.search(r\"\\s*(Y|N)\\s*$\", text, re.IGNORECASE)\n        match_first = re.search(r\"^\\s*(Y|N)\\s*\", text, re.IGNORECASE)\n        match_end = re.search(r\"\\b(Y|N)\\b\\s*$\", text, re.IGNORECASE)\n        if match_last:\n            verdict = match_last.group(1).strip()\n            text = text[: match_last.start()].strip()\n        elif match_first:\n            verdict = match_first.group(1).strip()\n            text = text[match_first.end() :].strip()\n        elif match_end:\n            verdict = match_end.group(1).strip()\n            text = text[: match_end.start()].strip()\n        else:\n            splits = text.strip().rsplit(\"\\n\", maxsplit=1)\n            if len(splits) == 1:\n                reasoning = \"\"\n                verdict = splits[0]\n            else:\n                reasoning, verdict = splits\n        if verdict:\n            score = (\n                1 if verdict.upper() == \"Y\" else (0 if verdict.upper() == \"N\" else None)\n            )\n        return {\n            \"reasoning\": text.strip(),\n            \"value\": verdict,\n            \"score\": score,\n        }\nCRITERIA_TYPE = Union[\n    Mapping[str, str],\n    Criteria,\n    ConstitutionalPrinciple,\n]\n[docs]def resolve_criteria(\n    criteria: Optional[Union[CRITERIA_TYPE, str]],\n) -> Dict[str, str]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "05a4e6abaf79-3", "text": ") -> Dict[str, str]:\n    \"\"\"Resolve the criteria to evaluate.\n    Parameters\n    ----------\n    criteria : CRITERIA_TYPE\n        The criteria to evaluate the runs against. It can be:\n            -  a mapping of a criterion name to its description\n            -  a single criterion name present in one of the default criteria\n            -  a single `ConstitutionalPrinciple` instance\n    Returns\n    -------\n    Dict[str, str]\n        A dictionary mapping criterion names to descriptions.\n    Examples\n    --------\n    >>> criterion = \"relevance\"\n    >>> CriteriaEvalChain.resolve_criteria(criteria)\n    {'relevance': 'Is the submission referring to a real quote from the text?'}\n    \"\"\"  # noqa: E501\n    if criteria is None:\n        return {\n            \"helpfulness\": _SUPPORTED_CRITERIA[Criteria.HELPFULNESS],\n        }\n    if isinstance(criteria, Criteria):\n        criteria_ = {criteria.value: _SUPPORTED_CRITERIA[criteria]}\n    elif isinstance(criteria, str):\n        criteria_ = {criteria: _SUPPORTED_CRITERIA[Criteria(criteria)]}\n    elif isinstance(criteria, ConstitutionalPrinciple):\n        criteria_ = {criteria.name: criteria.critique_request}\n    else:\n        if not criteria:\n            raise ValueError(\n                \"Criteria cannot be empty. \"\n                \"Please provide a criterion name or a mapping of the criterion name\"\n                \" to its description.\"\n            )\n        criteria_ = dict(criteria)\n    return criteria_\n[docs]class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):\n    \"\"\"LLM Chain for evaluating runs against criteria.\n    Parameters\n    ----------\n    llm : BaseLanguageModel\n        The language model to use for evaluation.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "05a4e6abaf79-4", "text": "llm : BaseLanguageModel\n        The language model to use for evaluation.\n    criteria : Union[Mapping[str, str]]\n        The criteria or rubric to evaluate the runs against. It can be a mapping of\n        criterion name to its description, or a single criterion name.\n    prompt : Optional[BasePromptTemplate], default=None\n        The prompt template to use for generating prompts. If not provided, a\n        default prompt template will be used based on the value of\n        `requires_reference`.\n    requires_reference : bool, default=False\n        Whether the evaluation requires a reference text. If `True`, the\n        `PROMPT_WITH_REFERENCES` template will be used, which includes the\n        reference labels in the prompt. Otherwise, the `PROMPT` template will be\n        used, which is a reference-free prompt.\n    **kwargs : Any\n        Additional keyword arguments to pass to the `LLMChain` constructor.\n    Returns\n    -------\n    CriteriaEvalChain\n        An instance of the `CriteriaEvalChain` class.\n    Examples\n    --------\n    >>> from langchain.chat_models import ChatAnthropic\n    >>> from langchain.evaluation.criteria import CriteriaEvalChain\n    >>> llm = ChatAnthropic(temperature=0)\n    >>> criteria = {\"my-custom-criterion\": \"Is the submission the most amazing ever?\"}\n    >>> evaluator = CriteriaEvalChain.from_llm(llm=llm, criteria=criteria)\n    >>> evaluator.evaluate_strings(prediction=\"Imagine an ice cream flavor for the color aquamarine\", input=\"Tell me an idea\")\n    {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "05a4e6abaf79-5", "text": "{\n        'reasoning': 'Here is my step-by-step reasoning for the given criteria:\\\\n\\\\nThe criterion is: \"Is the submission the most amazing ever?\" This is a subjective criterion and open to interpretation. The submission suggests an aquamarine-colored ice cream flavor which is creative but may or may not be considered the most amazing idea ever conceived. There are many possible amazing ideas and this one ice cream flavor suggestion may or may not rise to that level for every person. \\\\n\\\\nN',\n        'value': 'N',\n        'score': 0,\n    }\n    >>> from langchain.chat_models import ChatOpenAI\n    >>> from langchain.evaluation.criteria import LabeledCriteriaEvalChain\n    >>> llm = ChatOpenAI(model=\"gpt-4\", temperature=0)\n    >>> criteria = \"correctness\"\n    >>> evaluator = LabeledCriteriaEvalChain.from_llm(\n    ...     llm=llm,\n    ...     criteria=criteria,\n    ... )\n    >>> evaluator.evaluate_strings(\n    ...   prediction=\"The answer is 4\",\n    ...   input=\"How many apples are there?\",\n    ...   reference=\"There are 3 apples\",\n    ...   )\n    {\n        'score': 0,\n        'reasoning': 'The criterion for this task is the correctness of the submission. The submission states that there are 4 apples, but the reference indicates that there are actually 3 apples. Therefore, the submission is not correct, accurate, or factual according to the given criterion.\\\\n\\\\nN',\n        'value': 'N',\n    }\n    \"\"\"  # noqa: E501\n    output_parser: BaseOutputParser = Field(default_factory=CriteriaResultOutputParser)\n    \"\"\"The parser to use to map the output to a structured result.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "05a4e6abaf79-6", "text": "\"\"\"The parser to use to map the output to a structured result.\"\"\"\n    criterion_name: str\n    \"\"\"The name of the criterion being evaluated.\"\"\"\n    output_key: str = \"results\"  #: :meta private:\n    class Config:\n        \"\"\"Configuration for the QAEvalChain.\"\"\"\n        extra = Extra.ignore\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"Whether the evaluation requires a reference text.\"\"\"\n        return False\n    @property\n    def requires_input(self) -> bool:\n        return True\n    @property\n    def evaluation_name(self) -> str:\n        \"\"\"Get the name of the evaluation.\n        Returns\n        -------\n        str\n            The name of the evaluation.\n        \"\"\"\n        return self.criterion_name\n    @property\n    def _skip_reference_warning(self) -> str:\n        \"\"\"Warning to show when reference is ignored.\"\"\"\n        return (\n            f\"Ignoring reference in {self.__class__.__name__}, as it is not expected.\"\n            \"\\nTo use references, use the labeled_criteria instead.\"\n        )\n    @classmethod\n    def _resolve_prompt(\n        cls, prompt: Optional[BasePromptTemplate] = None\n    ) -> BasePromptTemplate:\n        expected_input_vars = {\"input\", \"output\", \"criteria\"}\n        prompt_ = prompt or PROMPT\n        if expected_input_vars != set(prompt_.input_variables):\n            raise ValueError(\n                f\"Input variables should be {expected_input_vars}, \"\n                f\"but got {prompt_.input_variables}\"\n            )\n        return prompt_\n[docs]    @classmethod\n    def resolve_criteria(\n        cls,\n        criteria: Optional[Union[CRITERIA_TYPE, str]],\n    ) -> Dict[str, str]:\n        \"\"\"Resolve the criteria to evaluate.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "05a4e6abaf79-7", "text": ") -> Dict[str, str]:\n        \"\"\"Resolve the criteria to evaluate.\n        Parameters\n        ----------\n        criteria : CRITERIA_TYPE\n            The criteria to evaluate the runs against. It can be:\n                -  a mapping of a criterion name to its description\n                -  a single criterion name present in one of the default criteria\n                -  a single `ConstitutionalPrinciple` instance\n        Returns\n        -------\n        Dict[str, str]\n            A dictionary mapping criterion names to descriptions.\n        Examples\n        --------\n        >>> criterion = \"relevance\"\n        >>> CriteriaEvalChain.resolve_criteria(criteria)\n        {'relevance': 'Is the submission referring to a real quote from the text?'}\n        \"\"\"  # noqa: E501\n        return resolve_criteria(criteria)\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        criteria: Optional[CRITERIA_TYPE] = None,\n        *,\n        prompt: Optional[BasePromptTemplate] = None,\n        **kwargs: Any,\n    ) -> CriteriaEvalChain:\n        \"\"\"Create a `CriteriaEvalChain` instance from an llm and criteria.\n        Parameters\n        ----------\n        llm : BaseLanguageModel\n            The language model to use for evaluation.\n        criteria : CRITERIA_TYPE - default=None for \"helpfulness\"\n            The criteria to evaluate the runs against. It can be:\n                -  a mapping of a criterion name to its description\n                -  a single criterion name present in one of the default criteria\n                -  a single `ConstitutionalPrinciple` instance\n        prompt : Optional[BasePromptTemplate], default=None\n            The prompt template to use for generating prompts. If not provided,\n            a default prompt template will be used.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "05a4e6abaf79-8", "text": "a default prompt template will be used.\n        **kwargs : Any\n            Additional keyword arguments to pass to the `LLMChain`\n            constructor.\n        Returns\n        -------\n        CriteriaEvalChain\n            An instance of the `CriteriaEvalChain` class.\n        Examples\n        --------\n        >>> from langchain.llms import OpenAI\n        >>> from langchain.evaluation.criteria import LabeledCriteriaEvalChain\n        >>> llm = OpenAI()\n        >>> criteria = {\n                \"hallucination\": (\n                    \"Does this submission contain information\"\n                    \" not present in the input or reference?\"\n                ),\n            }\n        >>> chain = LabeledCriteriaEvalChain.from_llm(\n                llm=llm,\n                criteria=criteria,\n            )\n        \"\"\"\n        prompt_ = cls._resolve_prompt(prompt)\n        if criteria == Criteria.CORRECTNESS:\n            raise ValueError(\n                \"Correctness should not be used in the reference-free\"\n                \" 'criteria' evaluator (CriteriaEvalChain).\"\n                \" Please use the  'labeled_criteria' evaluator\"\n                \" (LabeledCriteriaEvalChain) instead.\"\n            )\n        criteria_ = cls.resolve_criteria(criteria)\n        criteria_str = \"\\n\".join(f\"{k}: {v}\" for k, v in criteria_.items())\n        prompt_ = prompt_.partial(criteria=criteria_str)\n        return cls(\n            llm=llm,\n            prompt=prompt_,\n            criterion_name=\"-\".join(criteria_),\n            **kwargs,\n        )\n    def _get_eval_input(\n        self,\n        prediction: str,\n        reference: Optional[str],\n        input: Optional[str],\n    ) -> dict:\n        \"\"\"Get the evaluation input.\"\"\"\n        input_ = {\n            \"input\": input,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "05a4e6abaf79-9", "text": "input_ = {\n            \"input\": input,\n            \"output\": prediction,\n        }\n        if self.requires_reference:\n            input_[\"reference\"] = reference\n        return input_\n    def _prepare_output(self, result: dict) -> dict:\n        \"\"\"Prepare the output.\"\"\"\n        parsed = result[self.output_key]\n        if RUN_KEY in result:\n            parsed[RUN_KEY] = result[RUN_KEY]\n        return parsed\n    def _evaluate_strings(\n        self,\n        *,\n        prediction: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Evaluate a prediction against the criteria.\n        Parameters\n        ----------\n        prediction : str\n            The predicted text to evaluate.\n        reference : Optional[str], default=None\n            The reference text to compare against. This is required if\n            `requires_reference` is `True`.\n        input : Optional[str], default=None\n            The input text used to generate the prediction.\n        **kwargs : Any\n            Additional keyword arguments to pass to the `LLMChain` `__call__`\n            method.\n        Returns\n        -------\n        dict\n            The evaluation results.\n        Examples\n        --------\n        >>> from langchain.llms import OpenAI\n        >>> from langchain.evaluation.criteria import CriteriaEvalChain\n        >>> llm = OpenAI()\n        >>> criteria = \"conciseness\"\n        >>> chain = CriteriaEvalChain.from_llm(llm=llm, criteria=criteria)\n        >>> chain.evaluate_strings(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "05a4e6abaf79-10", "text": ">>> chain.evaluate_strings(\n                prediction=\"The answer is 42.\",\n                reference=\"42\",\n                input=\"What is the answer to life, the universe, and everything?\",\n            )\n        \"\"\"\n        input_ = self._get_eval_input(prediction, reference, input)\n        result = self(\n            input_,\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n    async def _aevaluate_strings(\n        self,\n        *,\n        prediction: str,\n        reference: Optional[str] = None,\n        input: Optional[str] = None,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        include_run_info: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Asynchronously evaluate a prediction against the criteria.\n        Parameters\n        ----------\n        prediction : str\n            The predicted text to evaluate.\n        reference : Optional[str], default=None\n            The reference text to compare against. This is required if\n            `requires_reference` is `True`.\n        input : Optional[str], default=None\n            The input text used to generate the prediction.\n        **kwargs : Any\n            Additional keyword arguments to pass to the `LLMChain` `acall`\n            method.\n        Returns\n        -------\n        dict\n            The evaluation results.\n        Examples\n        --------\n        >>> from langchain.llms import OpenAI\n        >>> from langchain.evaluation.criteria import CriteriaEvalChain\n        >>> llm = OpenAI()\n        >>> criteria = \"conciseness\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "05a4e6abaf79-11", "text": ">>> llm = OpenAI()\n        >>> criteria = \"conciseness\"\n        >>> chain = CriteriaEvalChain.from_llm(llm=llm, criteria=criteria)\n        >>> await chain.aevaluate_strings(\n                prediction=\"The answer is 42.\",\n                reference=\"42\",\n                input=\"What is the answer to life, the universe, and everything?\",\n            )\n        \"\"\"\n        input_ = self._get_eval_input(prediction, reference, input)\n        result = await self.acall(\n            input_,\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            include_run_info=include_run_info,\n        )\n        return self._prepare_output(result)\n[docs]class LabeledCriteriaEvalChain(CriteriaEvalChain):\n    \"\"\"Criteria evaluation chain that requires references.\"\"\"\n    @property\n    def requires_reference(self) -> bool:\n        \"\"\"Whether the evaluation requires a reference text.\"\"\"\n        return True\n    @classmethod\n    def _resolve_prompt(\n        cls, prompt: Optional[BasePromptTemplate] = None\n    ) -> BasePromptTemplate:\n        expected_input_vars = {\"input\", \"output\", \"criteria\", \"reference\"}\n        prompt_ = prompt or PROMPT_WITH_REFERENCES\n        if expected_input_vars != set(prompt_.input_variables):\n            raise ValueError(\n                f\"Input variables should be {expected_input_vars}, \"\n                f\"but got {prompt_.input_variables}\"\n            )\n        return prompt_\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        criteria: Optional[CRITERIA_TYPE] = None,\n        *,\n        prompt: Optional[BasePromptTemplate] = None,\n        **kwargs: Any,\n    ) -> CriteriaEvalChain:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "05a4e6abaf79-12", "text": "**kwargs: Any,\n    ) -> CriteriaEvalChain:\n        \"\"\"Create a `LabeledCriteriaEvalChain` instance from an llm and criteria.\n        Parameters\n        ----------\n        llm : BaseLanguageModel\n            The language model to use for evaluation.\n        criteria : CRITERIA_TYPE - default=None for \"helpfulness\"\n            The criteria to evaluate the runs against. It can be:\n                -  a mapping of a criterion name to its description\n                -  a single criterion name present in one of the default criteria\n                -  a single `ConstitutionalPrinciple` instance\n        prompt : Optional[BasePromptTemplate], default=None\n            The prompt template to use for generating prompts. If not provided,\n            a default prompt will be used.\n        **kwargs : Any\n            Additional keyword arguments to pass to the `LLMChain`\n            constructor.\n        Returns\n        -------\n        LabeledCriteriaEvalChain\n            An instance of the `LabeledCriteriaEvalChain` class.\n        Examples\n        --------\n        >>> from langchain.llms import OpenAI\n        >>> from langchain.evaluation.criteria import LabeledCriteriaEvalChain\n        >>> llm = OpenAI()\n        >>> criteria = {\n                \"hallucination\": (\n                    \"Does this submission contain information\"\n                    \" not present in the input or reference?\"\n                ),\n            }\n        >>> chain = LabeledCriteriaEvalChain.from_llm(\n                llm=llm,\n                criteria=criteria,\n            )\n        \"\"\"\n        prompt = cls._resolve_prompt(prompt)\n        criteria_ = cls.resolve_criteria(criteria)\n        criteria_str = \"\\n\".join(f\"{k}: {v}\" for k, v in criteria_.items())\n        prompt_ = prompt.partial(criteria=criteria_str)\n        return cls(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "05a4e6abaf79-13", "text": "prompt_ = prompt.partial(criteria=criteria_str)\n        return cls(\n            llm=llm,\n            prompt=prompt_,\n            criterion_name=\"-\".join(criteria_),\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html"}
{"id": "ea32e5bd8a3c-0", "text": "Source code for langchain.tools.plugin\nfrom __future__ import annotations\nimport json\nfrom typing import Optional, Type\nimport requests\nimport yaml\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.tools.base import BaseTool\n[docs]class ApiConfig(BaseModel):\n    \"\"\"API Configuration.\"\"\"\n    type: str\n    url: str\n    has_user_authentication: Optional[bool] = False\n[docs]class AIPlugin(BaseModel):\n    \"\"\"AI Plugin Definition.\"\"\"\n    schema_version: str\n    name_for_model: str\n    name_for_human: str\n    description_for_model: str\n    description_for_human: str\n    auth: Optional[dict] = None\n    api: ApiConfig\n    logo_url: Optional[str]\n    contact_email: Optional[str]\n    legal_info_url: Optional[str]\n[docs]    @classmethod\n    def from_url(cls, url: str) -> AIPlugin:\n        \"\"\"Instantiate AIPlugin from a URL.\"\"\"\n        response = requests.get(url).json()\n        return cls(**response)\n[docs]def marshal_spec(txt: str) -> dict:\n    \"\"\"Convert the yaml or json serialized spec to a dict.\n    Args:\n        txt: The yaml or json serialized spec.\n    Returns:\n        dict: The spec as a dict.\n    \"\"\"\n    try:\n        return json.loads(txt)\n    except json.JSONDecodeError:\n        return yaml.safe_load(txt)\n[docs]class AIPluginToolSchema(BaseModel):\n    \"\"\"Schema for AIPluginTool.\"\"\"\n    tool_input: Optional[str] = \"\"\n[docs]class AIPluginTool(BaseTool):\n    \"\"\"Tool for getting the OpenAPI spec for an AI Plugin.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html"}
{"id": "ea32e5bd8a3c-1", "text": "\"\"\"Tool for getting the OpenAPI spec for an AI Plugin.\"\"\"\n    plugin: AIPlugin\n    api_spec: str\n    args_schema: Type[AIPluginToolSchema] = AIPluginToolSchema\n[docs]    @classmethod\n    def from_plugin_url(cls, url: str) -> AIPluginTool:\n        plugin = AIPlugin.from_url(url)\n        description = (\n            f\"Call this tool to get the OpenAPI spec (and usage guide) \"\n            f\"for interacting with the {plugin.name_for_human} API. \"\n            f\"You should only call this ONCE! What is the \"\n            f\"{plugin.name_for_human} API useful for? \"\n        ) + plugin.description_for_human\n        open_api_spec_str = requests.get(plugin.api.url).text\n        open_api_spec = marshal_spec(open_api_spec_str)\n        api_spec = (\n            f\"Usage Guide: {plugin.description_for_model}\\n\\n\"\n            f\"OpenAPI Spec: {open_api_spec}\"\n        )\n        return cls(\n            name=plugin.name_for_model,\n            description=description,\n            plugin=plugin,\n            api_spec=api_spec,\n        )\n    def _run(\n        self,\n        tool_input: Optional[str] = \"\",\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return self.api_spec\n    async def _arun(\n        self,\n        tool_input: Optional[str] = None,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        return self.api_spec", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html"}
{"id": "e1e31f11c427-0", "text": "Source code for langchain.tools.ifttt\n\"\"\"From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services.\n# Creating a webhook\n- Go to https://ifttt.com/create\n# Configuring the \"If This\"\n- Click on the \"If This\" button in the IFTTT interface.\n- Search for \"Webhooks\" in the search bar.\n- Choose the first option for \"Receive a web request with a JSON payload.\"\n- Choose an Event Name that is specific to the service you plan to connect to.\nThis will make it easier for you to manage the webhook URL.\nFor example, if you're connecting to Spotify, you could use \"Spotify\" as your\nEvent Name.\n- Click the \"Create Trigger\" button to save your settings and create your webhook.\n# Configuring the \"Then That\"\n- Tap on the \"Then That\" button in the IFTTT interface.\n- Search for the service you want to connect, such as Spotify.\n- Choose an action from the service, such as \"Add track to a playlist\".\n- Configure the action by specifying the necessary details, such as the playlist name,\ne.g., \"Songs from AI\".\n- Reference the JSON Payload received by the Webhook in your action. For the Spotify\nscenario, choose \"{{JsonPayload}}\" as your search query.\n- Tap the \"Create Action\" button to save your action settings.\n- Once you have finished configuring your action, click the \"Finish\" button to\ncomplete the setup.\n- Congratulations! You have successfully connected the Webhook to the desired\nservice, and you're ready to start receiving data and triggering actions \ud83c\udf89\n# Finishing up\n- To get your webhook URL go to https://ifttt.com/maker_webhooks/settings", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html"}
{"id": "e1e31f11c427-1", "text": "- To get your webhook URL go to https://ifttt.com/maker_webhooks/settings\n- Copy the IFTTT key value from there. The URL is of the form\nhttps://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value.\n\"\"\"\nfrom typing import Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.base import BaseTool\n[docs]class IFTTTWebhook(BaseTool):\n    \"\"\"IFTTT Webhook.\n    Args:\n        name: name of the tool\n        description: description of the tool\n        url: url to hit with the json event.\n    \"\"\"\n    url: str\n    def _run(\n        self,\n        tool_input: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        body = {\"this\": tool_input}\n        response = requests.post(self.url, data=body)\n        return response.text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html"}
{"id": "d3a58e856abb-0", "text": "Source code for langchain.tools.retriever\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema import BaseRetriever\nfrom langchain.tools import Tool\n[docs]class RetrieverInput(BaseModel):\n    query: str = Field(description=\"query to look up in retriever\")\n[docs]def create_retriever_tool(\n    retriever: BaseRetriever, name: str, description: str\n) -> Tool:\n    \"\"\"Create a tool to do retrieval of documents.\n    Args:\n        retriever: The retriever to use for the retrieval\n        name: The name for the tool. This will be passed to the language model,\n            so should be unique and somewhat descriptive.\n        description: The description for the tool. This will be passed to the language\n            model, so should be descriptive.\n    Returns:\n        Tool class to pass to an agent\n    \"\"\"\n    return Tool(\n        name=name,\n        description=description,\n        func=retriever.get_relevant_documents,\n        coroutine=retriever.aget_relevant_documents,\n        args_schema=RetrieverInput,\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/retriever.html"}
{"id": "7985312c07e7-0", "text": "Source code for langchain.tools.base\n\"\"\"Base implementation for tools or skills.\"\"\"\nfrom __future__ import annotations\nimport asyncio\nimport inspect\nimport warnings\nfrom abc import abstractmethod\nfrom functools import partial\nfrom inspect import signature\nfrom typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Type, Union\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManager,\n    AsyncCallbackManagerForToolRun,\n    CallbackManager,\n    CallbackManagerForToolRun,\n    Callbacks,\n)\nfrom langchain.load.serializable import Serializable\nfrom langchain.pydantic_v1 import (\n    BaseModel,\n    Extra,\n    Field,\n    create_model,\n    root_validator,\n    validate_arguments,\n)\nfrom langchain.schema.runnable import Runnable, RunnableConfig, RunnableSerializable\n[docs]class SchemaAnnotationError(TypeError):\n    \"\"\"Raised when 'args_schema' is missing or has an incorrect type annotation.\"\"\"\ndef _create_subset_model(\n    name: str, model: BaseModel, field_names: list\n) -> Type[BaseModel]:\n    \"\"\"Create a pydantic model with only a subset of model's fields.\"\"\"\n    fields = {}\n    for field_name in field_names:\n        field = model.__fields__[field_name]\n        fields[field_name] = (field.outer_type_, field.field_info)\n    return create_model(name, **fields)  # type: ignore\ndef _get_filtered_args(\n    inferred_model: Type[BaseModel],\n    func: Callable,\n) -> dict:\n    \"\"\"Get the arguments from a function's signature.\"\"\"\n    schema = inferred_model.schema()[\"properties\"]\n    valid_keys = signature(func).parameters\n    return {k: schema[k] for k in valid_keys if k not in (\"run_manager\", \"callbacks\")}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-1", "text": "class _SchemaConfig:\n    \"\"\"Configuration for the pydantic model.\"\"\"\n    extra: Any = Extra.forbid\n    arbitrary_types_allowed: bool = True\n[docs]def create_schema_from_function(\n    model_name: str,\n    func: Callable,\n) -> Type[BaseModel]:\n    \"\"\"Create a pydantic schema from a function's signature.\n    Args:\n        model_name: Name to assign to the generated pydandic schema\n        func: Function to generate the schema from\n    Returns:\n        A pydantic model with the same arguments as the function\n    \"\"\"\n    # https://docs.pydantic.dev/latest/usage/validation_decorator/\n    validated = validate_arguments(func, config=_SchemaConfig)  # type: ignore\n    inferred_model = validated.model  # type: ignore\n    if \"run_manager\" in inferred_model.__fields__:\n        del inferred_model.__fields__[\"run_manager\"]\n    if \"callbacks\" in inferred_model.__fields__:\n        del inferred_model.__fields__[\"callbacks\"]\n    # Pydantic adds placeholder virtual fields we need to strip\n    valid_properties = _get_filtered_args(inferred_model, func)\n    return _create_subset_model(\n        f\"{model_name}Schema\", inferred_model, list(valid_properties)\n    )\n[docs]class ToolException(Exception):\n    \"\"\"An optional exception that tool throws when execution error occurs.\n    When this exception is thrown, the agent will not stop working,\n    but will handle the exception according to the handle_tool_error\n    variable of the tool, and the processing result will be returned\n    to the agent as observation, and printed in red on the console.\n    \"\"\"\n    pass\n[docs]class BaseTool(RunnableSerializable[Union[str, Dict], Any]):\n    \"\"\"Interface LangChain tools must implement.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-2", "text": "\"\"\"Interface LangChain tools must implement.\"\"\"\n    def __init_subclass__(cls, **kwargs: Any) -> None:\n        \"\"\"Create the definition of the new tool class.\"\"\"\n        super().__init_subclass__(**kwargs)\n        args_schema_type = cls.__annotations__.get(\"args_schema\", None)\n        if args_schema_type is not None:\n            if args_schema_type is None or args_schema_type == BaseModel:\n                # Throw errors for common mis-annotations.\n                # TODO: Use get_args / get_origin and fully\n                # specify valid annotations.\n                typehint_mandate = \"\"\"\nclass ChildTool(BaseTool):\n    ...\n    args_schema: Type[BaseModel] = SchemaClass\n    ...\"\"\"\n                name = cls.__name__\n                raise SchemaAnnotationError(\n                    f\"Tool definition for {name} must include valid type annotations\"\n                    f\" for argument 'args_schema' to behave as expected.\\n\"\n                    f\"Expected annotation of 'Type[BaseModel]'\"\n                    f\" but got '{args_schema_type}'.\\n\"\n                    f\"Expected class looks like:\\n\"\n                    f\"{typehint_mandate}\"\n                )\n    name: str\n    \"\"\"The unique name of the tool that clearly communicates its purpose.\"\"\"\n    description: str\n    \"\"\"Used to tell the model how/when/why to use the tool.\n    \n    You can provide few-shot examples as a part of the description.\n    \"\"\"\n    args_schema: Optional[Type[BaseModel]] = None\n    \"\"\"Pydantic model class to validate and parse the tool's input arguments.\"\"\"\n    return_direct: bool = False\n    \"\"\"Whether to return the tool's output directly. Setting this to True means\n    \n    that after the tool is called, the AgentExecutor will stop looping.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-3", "text": "that after the tool is called, the AgentExecutor will stop looping.\n    \"\"\"\n    verbose: bool = False\n    \"\"\"Whether to log the tool's progress.\"\"\"\n    callbacks: Callbacks = Field(default=None, exclude=True)\n    \"\"\"Callbacks to be called during tool execution.\"\"\"\n    callback_manager: Optional[BaseCallbackManager] = Field(default=None, exclude=True)\n    \"\"\"Deprecated. Please use callbacks instead.\"\"\"\n    tags: Optional[List[str]] = None\n    \"\"\"Optional list of tags associated with the tool. Defaults to None\n    These tags will be associated with each call to this tool,\n    and passed as arguments to the handlers defined in `callbacks`.\n    You can use these to eg identify a specific instance of a tool with its use case.\n    \"\"\"\n    metadata: Optional[Dict[str, Any]] = None\n    \"\"\"Optional metadata associated with the tool. Defaults to None\n    This metadata will be associated with each call to this tool,\n    and passed as arguments to the handlers defined in `callbacks`.\n    You can use these to eg identify a specific instance of a tool with its use case.\n    \"\"\"\n    handle_tool_error: Optional[\n        Union[bool, str, Callable[[ToolException], str]]\n    ] = False\n    \"\"\"Handle the content of the ToolException thrown.\"\"\"\n    class Config(Serializable.Config):\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @property\n    def is_single_input(self) -> bool:\n        \"\"\"Whether the tool only accepts a single input.\"\"\"\n        keys = {k for k in self.args if k != \"kwargs\"}\n        return len(keys) == 1\n    @property\n    def args(self) -> dict:\n        if self.args_schema is not None:\n            return self.args_schema.schema()[\"properties\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-4", "text": "if self.args_schema is not None:\n            return self.args_schema.schema()[\"properties\"]\n        else:\n            schema = create_schema_from_function(self.name, self._run)\n            return schema.schema()[\"properties\"]\n    # --- Runnable ---\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        \"\"\"The tool's input schema.\"\"\"\n        if self.args_schema is not None:\n            return self.args_schema\n        else:\n            return create_schema_from_function(self.name, self._run)\n[docs]    def invoke(\n        self,\n        input: Union[str, Dict],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Any:\n        config = config or {}\n        return self.run(\n            input,\n            callbacks=config.get(\"callbacks\"),\n            tags=config.get(\"tags\"),\n            metadata=config.get(\"metadata\"),\n            run_name=config.get(\"run_name\"),\n            **kwargs,\n        )\n[docs]    async def ainvoke(\n        self,\n        input: Union[str, Dict],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Any:\n        config = config or {}\n        return await self.arun(\n            input,\n            callbacks=config.get(\"callbacks\"),\n            tags=config.get(\"tags\"),\n            metadata=config.get(\"metadata\"),\n            run_name=config.get(\"run_name\"),\n            **kwargs,\n        )\n    # --- Tool ---\n    def _parse_input(\n        self,\n        tool_input: Union[str, Dict],\n    ) -> Union[str, Dict[str, Any]]:\n        \"\"\"Convert tool input to pydantic model.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-5", "text": "\"\"\"Convert tool input to pydantic model.\"\"\"\n        input_args = self.args_schema\n        if isinstance(tool_input, str):\n            if input_args is not None:\n                key_ = next(iter(input_args.__fields__.keys()))\n                input_args.validate({key_: tool_input})\n            return tool_input\n        else:\n            if input_args is not None:\n                result = input_args.parse_obj(tool_input)\n                return {k: v for k, v in result.dict().items() if k in tool_input}\n        return tool_input\n    @root_validator()\n    def raise_deprecation(cls, values: Dict) -> Dict:\n        \"\"\"Raise deprecation warning if callback_manager is used.\"\"\"\n        if values.get(\"callback_manager\") is not None:\n            warnings.warn(\n                \"callback_manager is deprecated. Please use callbacks instead.\",\n                DeprecationWarning,\n            )\n            values[\"callbacks\"] = values.pop(\"callback_manager\", None)\n        return values\n    @abstractmethod\n    def _run(\n        self,\n        *args: Any,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Use the tool.\n        Add run_manager: Optional[CallbackManagerForToolRun] = None\n        to child implementations to enable tracing,\n        \"\"\"\n    async def _arun(\n        self,\n        *args: Any,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Use the tool asynchronously.\n        Add run_manager: Optional[AsyncCallbackManagerForToolRun] = None\n        to child implementations to enable tracing,\n        \"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None,\n            partial(self._run, **kwargs),\n            *args,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-6", "text": "partial(self._run, **kwargs),\n            *args,\n        )\n    def _to_args_and_kwargs(self, tool_input: Union[str, Dict]) -> Tuple[Tuple, Dict]:\n        # For backwards compatibility, if run_input is a string,\n        # pass as a positional argument.\n        if isinstance(tool_input, str):\n            return (tool_input,), {}\n        else:\n            return (), tool_input\n[docs]    def run(\n        self,\n        tool_input: Union[str, Dict],\n        verbose: Optional[bool] = None,\n        start_color: Optional[str] = \"green\",\n        color: Optional[str] = \"green\",\n        callbacks: Callbacks = None,\n        *,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        run_name: Optional[str] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run the tool.\"\"\"\n        parsed_input = self._parse_input(tool_input)\n        if not self.verbose and verbose is not None:\n            verbose_ = verbose\n        else:\n            verbose_ = self.verbose\n        callback_manager = CallbackManager.configure(\n            callbacks,\n            self.callbacks,\n            verbose_,\n            tags,\n            self.tags,\n            metadata,\n            self.metadata,\n        )\n        # TODO: maybe also pass through run_manager is _run supports kwargs\n        new_arg_supported = signature(self._run).parameters.get(\"run_manager\")\n        run_manager = callback_manager.on_tool_start(\n            {\"name\": self.name, \"description\": self.description},\n            tool_input if isinstance(tool_input, str) else str(tool_input),\n            color=start_color,\n            name=run_name,\n            **kwargs,\n        )\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-7", "text": "name=run_name,\n            **kwargs,\n        )\n        try:\n            tool_args, tool_kwargs = self._to_args_and_kwargs(parsed_input)\n            observation = (\n                self._run(*tool_args, run_manager=run_manager, **tool_kwargs)\n                if new_arg_supported\n                else self._run(*tool_args, **tool_kwargs)\n            )\n        except ToolException as e:\n            if not self.handle_tool_error:\n                run_manager.on_tool_error(e)\n                raise e\n            elif isinstance(self.handle_tool_error, bool):\n                if e.args:\n                    observation = e.args[0]\n                else:\n                    observation = \"Tool execution error\"\n            elif isinstance(self.handle_tool_error, str):\n                observation = self.handle_tool_error\n            elif callable(self.handle_tool_error):\n                observation = self.handle_tool_error(e)\n            else:\n                raise ValueError(\n                    f\"Got unexpected type of `handle_tool_error`. Expected bool, str \"\n                    f\"or callable. Received: {self.handle_tool_error}\"\n                )\n            run_manager.on_tool_end(\n                str(observation), color=\"red\", name=self.name, **kwargs\n            )\n            return observation\n        except (Exception, KeyboardInterrupt) as e:\n            run_manager.on_tool_error(e)\n            raise e\n        else:\n            run_manager.on_tool_end(\n                str(observation), color=color, name=self.name, **kwargs\n            )\n            return observation\n[docs]    async def arun(\n        self,\n        tool_input: Union[str, Dict],\n        verbose: Optional[bool] = None,\n        start_color: Optional[str] = \"green\",\n        color: Optional[str] = \"green\",\n        callbacks: Callbacks = None,\n        *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-8", "text": "callbacks: Callbacks = None,\n        *,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        run_name: Optional[str] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run the tool asynchronously.\"\"\"\n        parsed_input = self._parse_input(tool_input)\n        if not self.verbose and verbose is not None:\n            verbose_ = verbose\n        else:\n            verbose_ = self.verbose\n        callback_manager = AsyncCallbackManager.configure(\n            callbacks,\n            self.callbacks,\n            verbose_,\n            tags,\n            self.tags,\n            metadata,\n            self.metadata,\n        )\n        new_arg_supported = signature(self._arun).parameters.get(\"run_manager\")\n        run_manager = await callback_manager.on_tool_start(\n            {\"name\": self.name, \"description\": self.description},\n            tool_input if isinstance(tool_input, str) else str(tool_input),\n            color=start_color,\n            name=run_name,\n            **kwargs,\n        )\n        try:\n            # We then call the tool on the tool input to get an observation\n            tool_args, tool_kwargs = self._to_args_and_kwargs(parsed_input)\n            observation = (\n                await self._arun(*tool_args, run_manager=run_manager, **tool_kwargs)\n                if new_arg_supported\n                else await self._arun(*tool_args, **tool_kwargs)\n            )\n        except ToolException as e:\n            if not self.handle_tool_error:\n                await run_manager.on_tool_error(e)\n                raise e\n            elif isinstance(self.handle_tool_error, bool):\n                if e.args:\n                    observation = e.args[0]\n                else:\n                    observation = \"Tool execution error\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-9", "text": "else:\n                    observation = \"Tool execution error\"\n            elif isinstance(self.handle_tool_error, str):\n                observation = self.handle_tool_error\n            elif callable(self.handle_tool_error):\n                observation = self.handle_tool_error(e)\n            else:\n                raise ValueError(\n                    f\"Got unexpected type of `handle_tool_error`. Expected bool, str \"\n                    f\"or callable. Received: {self.handle_tool_error}\"\n                )\n            await run_manager.on_tool_end(\n                str(observation), color=\"red\", name=self.name, **kwargs\n            )\n            return observation\n        except (Exception, KeyboardInterrupt) as e:\n            await run_manager.on_tool_error(e)\n            raise e\n        else:\n            await run_manager.on_tool_end(\n                str(observation), color=color, name=self.name, **kwargs\n            )\n            return observation\n[docs]    def __call__(self, tool_input: str, callbacks: Callbacks = None) -> str:\n        \"\"\"Make tool callable.\"\"\"\n        return self.run(tool_input, callbacks=callbacks)\n[docs]class Tool(BaseTool):\n    \"\"\"Tool that takes in function or coroutine directly.\"\"\"\n    description: str = \"\"\n    func: Optional[Callable[..., str]]\n    \"\"\"The function to run when the tool is called.\"\"\"\n    coroutine: Optional[Callable[..., Awaitable[str]]] = None\n    \"\"\"The asynchronous version of the function.\"\"\"\n    # --- Runnable ---\n[docs]    async def ainvoke(\n        self,\n        input: Union[str, Dict],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if not self.coroutine:\n            # If the tool does not implement async, fall back to default implementation\n            return await asyncio.get_running_loop().run_in_executor(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-10", "text": "return await asyncio.get_running_loop().run_in_executor(\n                None, partial(self.invoke, input, config, **kwargs)\n            )\n        return await super().ainvoke(input, config, **kwargs)\n    # --- Tool ---\n    @property\n    def args(self) -> dict:\n        \"\"\"The tool's input arguments.\"\"\"\n        if self.args_schema is not None:\n            return self.args_schema.schema()[\"properties\"]\n        # For backwards compatibility, if the function signature is ambiguous,\n        # assume it takes a single string input.\n        return {\"tool_input\": {\"type\": \"string\"}}\n    def _to_args_and_kwargs(self, tool_input: Union[str, Dict]) -> Tuple[Tuple, Dict]:\n        \"\"\"Convert tool input to pydantic model.\"\"\"\n        args, kwargs = super()._to_args_and_kwargs(tool_input)\n        # For backwards compatibility. The tool must be run with a single input\n        all_args = list(args) + list(kwargs.values())\n        if len(all_args) != 1:\n            raise ToolException(\n                f\"Too many arguments to single-input tool {self.name}.\"\n                f\" Args: {all_args}\"\n            )\n        return tuple(all_args), {}\n    def _run(\n        self,\n        *args: Any,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Use the tool.\"\"\"\n        if self.func:\n            new_argument_supported = signature(self.func).parameters.get(\"callbacks\")\n            return (\n                self.func(\n                    *args,\n                    callbacks=run_manager.get_child() if run_manager else None,\n                    **kwargs,\n                )\n                if new_argument_supported\n                else self.func(*args, **kwargs)\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-11", "text": "if new_argument_supported\n                else self.func(*args, **kwargs)\n            )\n        raise NotImplementedError(\"Tool does not support sync\")\n    async def _arun(\n        self,\n        *args: Any,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        if self.coroutine:\n            new_argument_supported = signature(self.coroutine).parameters.get(\n                \"callbacks\"\n            )\n            return (\n                await self.coroutine(\n                    *args,\n                    callbacks=run_manager.get_child() if run_manager else None,\n                    **kwargs,\n                )\n                if new_argument_supported\n                else await self.coroutine(*args, **kwargs)\n            )\n        else:\n            return await asyncio.get_running_loop().run_in_executor(\n                None, partial(self._run, run_manager=run_manager, **kwargs), *args\n            )\n    # TODO: this is for backwards compatibility, remove in future\n    def __init__(\n        self, name: str, func: Optional[Callable], description: str, **kwargs: Any\n    ) -> None:\n        \"\"\"Initialize tool.\"\"\"\n        super(Tool, self).__init__(\n            name=name, func=func, description=description, **kwargs\n        )\n[docs]    @classmethod\n    def from_function(\n        cls,\n        func: Optional[Callable],\n        name: str,  # We keep these required to support backwards compatibility\n        description: str,\n        return_direct: bool = False,\n        args_schema: Optional[Type[BaseModel]] = None,\n        coroutine: Optional[\n            Callable[..., Awaitable[Any]]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-12", "text": "coroutine: Optional[\n            Callable[..., Awaitable[Any]]\n        ] = None,  # This is last for compatibility, but should be after func\n        **kwargs: Any,\n    ) -> Tool:\n        \"\"\"Initialize tool from a function.\"\"\"\n        if func is None and coroutine is None:\n            raise ValueError(\"Function and/or coroutine must be provided\")\n        return cls(\n            name=name,\n            func=func,\n            coroutine=coroutine,\n            description=description,\n            return_direct=return_direct,\n            args_schema=args_schema,\n            **kwargs,\n        )\n[docs]class StructuredTool(BaseTool):\n    \"\"\"Tool that can operate on any number of inputs.\"\"\"\n    description: str = \"\"\n    args_schema: Type[BaseModel] = Field(..., description=\"The tool schema.\")\n    \"\"\"The input arguments' schema.\"\"\"\n    func: Optional[Callable[..., Any]]\n    \"\"\"The function to run when the tool is called.\"\"\"\n    coroutine: Optional[Callable[..., Awaitable[Any]]] = None\n    \"\"\"The asynchronous version of the function.\"\"\"\n    # --- Runnable ---\n[docs]    async def ainvoke(\n        self,\n        input: Union[str, Dict],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if not self.coroutine:\n            # If the tool does not implement async, fall back to default implementation\n            return await asyncio.get_running_loop().run_in_executor(\n                None, partial(self.invoke, input, config, **kwargs)\n            )\n        return await super().ainvoke(input, config, **kwargs)\n    # --- Tool ---\n    @property\n    def args(self) -> dict:\n        \"\"\"The tool's input arguments.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-13", "text": "def args(self) -> dict:\n        \"\"\"The tool's input arguments.\"\"\"\n        return self.args_schema.schema()[\"properties\"]\n    def _run(\n        self,\n        *args: Any,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Use the tool.\"\"\"\n        if self.func:\n            new_argument_supported = signature(self.func).parameters.get(\"callbacks\")\n            return (\n                self.func(\n                    *args,\n                    callbacks=run_manager.get_child() if run_manager else None,\n                    **kwargs,\n                )\n                if new_argument_supported\n                else self.func(*args, **kwargs)\n            )\n        raise NotImplementedError(\"Tool does not support sync\")\n    async def _arun(\n        self,\n        *args: Any,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        if self.coroutine:\n            new_argument_supported = signature(self.coroutine).parameters.get(\n                \"callbacks\"\n            )\n            return (\n                await self.coroutine(\n                    *args,\n                    callbacks=run_manager.get_child() if run_manager else None,\n                    **kwargs,\n                )\n                if new_argument_supported\n                else await self.coroutine(*args, **kwargs)\n            )\n        return await asyncio.get_running_loop().run_in_executor(\n            None,\n            partial(self._run, run_manager=run_manager, **kwargs),\n            *args,\n        )\n[docs]    @classmethod\n    def from_function(\n        cls,\n        func: Optional[Callable] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-14", "text": "cls,\n        func: Optional[Callable] = None,\n        coroutine: Optional[Callable[..., Awaitable[Any]]] = None,\n        name: Optional[str] = None,\n        description: Optional[str] = None,\n        return_direct: bool = False,\n        args_schema: Optional[Type[BaseModel]] = None,\n        infer_schema: bool = True,\n        **kwargs: Any,\n    ) -> StructuredTool:\n        \"\"\"Create tool from a given function.\n        A classmethod that helps to create a tool from a function.\n        Args:\n            func: The function from which to create a tool\n            coroutine: The async function from which to create a tool\n            name: The name of the tool. Defaults to the function name\n            description: The description of the tool. Defaults to the function docstring\n            return_direct: Whether to return the result directly or as a callback\n            args_schema: The schema of the tool's input arguments\n            infer_schema: Whether to infer the schema from the function's signature\n            **kwargs: Additional arguments to pass to the tool\n        Returns:\n            The tool\n        Examples:\n            .. code-block:: python\n                def add(a: int, b: int) -> int:\n                    \\\"\\\"\\\"Add two numbers\\\"\\\"\\\"\n                    return a + b\n                tool = StructuredTool.from_function(add)\n                tool.run(1, 2) # 3\n        \"\"\"\n        if func is not None:\n            source_function = func\n        elif coroutine is not None:\n            source_function = coroutine\n        else:\n            raise ValueError(\"Function and/or coroutine must be provided\")\n        name = name or source_function.__name__\n        description = description or source_function.__doc__\n        if description is None:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-15", "text": "if description is None:\n            raise ValueError(\n                \"Function must have a docstring if description not provided.\"\n            )\n        # Description example:\n        # search_api(query: str) - Searches the API for the query.\n        sig = signature(source_function)\n        description = f\"{name}{sig} - {description.strip()}\"\n        _args_schema = args_schema\n        if _args_schema is None and infer_schema:\n            _args_schema = create_schema_from_function(f\"{name}Schema\", source_function)\n        return cls(\n            name=name,\n            func=func,\n            coroutine=coroutine,\n            args_schema=_args_schema,\n            description=description,\n            return_direct=return_direct,\n            **kwargs,\n        )\n[docs]def tool(\n    *args: Union[str, Callable, Runnable],\n    return_direct: bool = False,\n    args_schema: Optional[Type[BaseModel]] = None,\n    infer_schema: bool = True,\n) -> Callable:\n    \"\"\"Make tools out of functions, can be used with or without arguments.\n    Args:\n        *args: The arguments to the tool.\n        return_direct: Whether to return directly from the tool rather\n            than continuing the agent loop.\n        args_schema: optional argument schema for user to specify\n        infer_schema: Whether to infer the schema of the arguments from\n            the function's signature. This also makes the resultant tool\n            accept a dictionary input to its `run()` function.\n    Requires:\n        - Function must be of type (str) -> str\n        - Function must have a docstring\n    Examples:\n        .. code-block:: python\n            @tool\n            def search_api(query: str) -> str:\n                # Searches the API for the query.\n                return", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-16", "text": "# Searches the API for the query.\n                return\n            @tool(\"search\", return_direct=True)\n            def search_api(query: str) -> str:\n                # Searches the API for the query.\n                return\n    \"\"\"\n    def _make_with_name(tool_name: str) -> Callable:\n        def _make_tool(dec_func: Union[Callable, Runnable]) -> BaseTool:\n            if isinstance(dec_func, Runnable):\n                runnable = dec_func\n                if runnable.input_schema.schema().get(\"type\") != \"object\":\n                    raise ValueError(\"Runnable must have an object schema.\")\n                async def ainvoke_wrapper(\n                    callbacks: Optional[Callbacks] = None, **kwargs: Any\n                ) -> Any:\n                    return await runnable.ainvoke(kwargs, {\"callbacks\": callbacks})\n                def invoke_wrapper(\n                    callbacks: Optional[Callbacks] = None, **kwargs: Any\n                ) -> Any:\n                    return runnable.invoke(kwargs, {\"callbacks\": callbacks})\n                coroutine = ainvoke_wrapper\n                func = invoke_wrapper\n                schema: Optional[Type[BaseModel]] = runnable.input_schema\n                description = repr(runnable)\n            elif inspect.iscoroutinefunction(dec_func):\n                coroutine = dec_func\n                func = None\n                schema = args_schema\n                description = None\n            else:\n                coroutine = None\n                func = dec_func\n                schema = args_schema\n                description = None\n            if infer_schema or args_schema is not None:\n                return StructuredTool.from_function(\n                    func,\n                    coroutine,\n                    name=tool_name,\n                    description=description,\n                    return_direct=return_direct,\n                    args_schema=schema,\n                    infer_schema=infer_schema,\n                )\n            # If someone doesn't want a schema applied, we must treat it as", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "7985312c07e7-17", "text": ")\n            # If someone doesn't want a schema applied, we must treat it as\n            # a simple string->string function\n            if func.__doc__ is None:\n                raise ValueError(\n                    \"Function must have a docstring if \"\n                    \"description not provided and infer_schema is False.\"\n                )\n            return Tool(\n                name=tool_name,\n                func=func,\n                description=f\"{tool_name} tool\",\n                return_direct=return_direct,\n                coroutine=coroutine,\n            )\n        return _make_tool\n    if len(args) == 2 and isinstance(args[0], str) and isinstance(args[1], Runnable):\n        return _make_with_name(args[0])(args[1])\n    elif len(args) == 1 and isinstance(args[0], str):\n        # if the argument is a string, then we use the string as the tool name\n        # Example usage: @tool(\"search\", return_direct=True)\n        return _make_with_name(args[0])\n    elif len(args) == 1 and callable(args[0]):\n        # if the argument is a function, then we use the function name as the tool name\n        # Example usage: @tool\n        return _make_with_name(args[0].__name__)(args[0])\n    elif len(args) == 0:\n        # if there are no arguments, then we use the function name as the tool name\n        # Example usage: @tool(return_direct=True)\n        def _partial(func: Callable[[str], str]) -> BaseTool:\n            return _make_with_name(func.__name__)(func)\n        return _partial\n    else:\n        raise ValueError(\"Too many arguments for tool decorator\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html"}
{"id": "a050af5d6a8d-0", "text": "Source code for langchain.tools.yahoo_finance_news\nfrom typing import Iterable, Optional\nfrom requests.exceptions import HTTPError, ReadTimeout\nfrom urllib3.exceptions import ConnectionError\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.document_loaders.web_base import WebBaseLoader\nfrom langchain.schema import Document\nfrom langchain.tools.base import BaseTool\n[docs]class YahooFinanceNewsTool(BaseTool):\n    \"\"\"Tool that searches financial news on Yahoo Finance.\"\"\"\n    name: str = \"yahoo_finance_news\"\n    description: str = (\n        \"Useful for when you need to find financial news \"\n        \"about a public company. \"\n        \"Input should be a company ticker. \"\n        \"For example, AAPL for Apple, MSFT for Microsoft.\"\n    )\n    top_k: int = 10\n    \"\"\"The number of results to return.\"\"\"\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the Yahoo Finance News tool.\"\"\"\n        try:\n            import yfinance\n        except ImportError:\n            raise ImportError(\n                \"Could not import yfinance python package. \"\n                \"Please install it with `pip install yfinance`.\"\n            )\n        company = yfinance.Ticker(query)\n        try:\n            if company.isin is None:\n                return f\"Company ticker {query} not found.\"\n        except (HTTPError, ReadTimeout, ConnectionError):\n            return f\"Company ticker {query} not found.\"\n        links = []\n        try:\n            links = [n[\"link\"] for n in company.news if n[\"type\"] == \"STORY\"]\n        except (HTTPError, ReadTimeout, ConnectionError):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/yahoo_finance_news.html"}
{"id": "a050af5d6a8d-1", "text": "except (HTTPError, ReadTimeout, ConnectionError):\n            if not links:\n                return f\"No news found for company that searched with {query} ticker.\"\n        if not links:\n            return f\"No news found for company that searched with {query} ticker.\"\n        loader = WebBaseLoader(web_paths=links)\n        docs = loader.load()\n        result = self._format_results(docs, query)\n        if not result:\n            return f\"No news found for company that searched with {query} ticker.\"\n        return result\n    @staticmethod\n    def _format_results(docs: Iterable[Document], query: str) -> str:\n        doc_strings = [\n            \"\\n\".join([doc.metadata[\"title\"], doc.metadata[\"description\"]])\n            for doc in docs\n            if query in doc.metadata[\"description\"] or query in doc.metadata[\"title\"]\n        ]\n        return \"\\n\\n\".join(doc_strings)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/yahoo_finance_news.html"}
{"id": "e94730fecfd7-0", "text": "Source code for langchain.tools.render\n\"\"\"Different methods for rendering Tools to be passed to LLMs.\nDepending on the LLM you are using and the prompting strategy you are using,\nyou may want Tools to be rendered in a different way.\nThis module contains various ways to render tools.\n\"\"\"\nfrom typing import List\nfrom langchain.tools.base import BaseTool\nfrom langchain.utils.openai_functions import (\n    FunctionDescription,\n    ToolDescription,\n    convert_pydantic_to_openai_function,\n)\n[docs]def render_text_description(tools: List[BaseTool]) -> str:\n    \"\"\"Render the tool name and description in plain text.\n    Output will be in the format of:\n    .. code-block:: markdown\n        search: This tool is used for search\n        calculator: This tool is used for math\n    \"\"\"\n    return \"\\n\".join([f\"{tool.name}: {tool.description}\" for tool in tools])\n[docs]def render_text_description_and_args(tools: List[BaseTool]) -> str:\n    \"\"\"Render the tool name, description, and args in plain text.\n    Output will be in the format of:\n    .. code-block:: markdown\n        search: This tool is used for search, args: {\"query\": {\"type\": \"string\"}}\n        calculator: This tool is used for math, \\\nargs: {\"expression\": {\"type\": \"string\"}}\n    \"\"\"\n    tool_strings = []\n    for tool in tools:\n        args_schema = str(tool.args)\n        tool_strings.append(f\"{tool.name}: {tool.description}, args: {args_schema}\")\n    return \"\\n\".join(tool_strings)\n[docs]def format_tool_to_openai_function(tool: BaseTool) -> FunctionDescription:\n    \"\"\"Format tool into the OpenAI function API.\"\"\"\n    if tool.args_schema:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/render.html"}
{"id": "e94730fecfd7-1", "text": "\"\"\"Format tool into the OpenAI function API.\"\"\"\n    if tool.args_schema:\n        return convert_pydantic_to_openai_function(\n            tool.args_schema, name=tool.name, description=tool.description\n        )\n    else:\n        return {\n            \"name\": tool.name,\n            \"description\": tool.description,\n            \"parameters\": {\n                # This is a hack to get around the fact that some tools\n                # do not expose an args_schema, and expect an argument\n                # which is a string.\n                # And Open AI does not support an array type for the\n                # parameters.\n                \"properties\": {\n                    \"__arg1\": {\"title\": \"__arg1\", \"type\": \"string\"},\n                },\n                \"required\": [\"__arg1\"],\n                \"type\": \"object\",\n            },\n        }\n[docs]def format_tool_to_openai_tool(tool: BaseTool) -> ToolDescription:\n    \"\"\"Format tool into the OpenAI function API.\"\"\"\n    function = format_tool_to_openai_function(tool)\n    return {\"type\": \"function\", \"function\": function}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/render.html"}
{"id": "90335ecbeb3f-0", "text": "Source code for langchain.tools.nuclia.tool\n\"\"\"Tool for the Nuclia Understanding API.\nInstallation:\n```bash\n    pip install --upgrade protobuf\n    pip install nucliadb-protos\n```\n\"\"\"\nimport asyncio\nimport base64\nimport logging\nimport mimetypes\nimport os\nfrom typing import Any, Dict, Optional, Type, Union\nimport requests\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nlogger = logging.getLogger(__name__)\n[docs]class NUASchema(BaseModel):\n    \"\"\"Input for Nuclia Understanding API.\n    Attributes:\n        action: Action to perform. Either `push` or `pull`.\n        id: ID of the file to push or pull.\n        path: Path to the file to push (needed only for `push` action).\n        text: Text content to process (needed only for `push` action).\n    \"\"\"\n    action: str = Field(\n        ...,\n        description=\"Action to perform. Either `push` or `pull`.\",\n    )\n    id: str = Field(\n        ...,\n        description=\"ID of the file to push or pull.\",\n    )\n    path: Optional[str] = Field(\n        ...,\n        description=\"Path to the file to push (needed only for `push` action).\",\n    )\n    text: Optional[str] = Field(\n        ...,\n        description=\"Text content to process (needed only for `push` action).\",\n    )\n[docs]class NucliaUnderstandingAPI(BaseTool):\n    \"\"\"Tool to process files with the Nuclia Understanding API.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html"}
{"id": "90335ecbeb3f-1", "text": "\"\"\"Tool to process files with the Nuclia Understanding API.\"\"\"\n    name: str = \"nuclia_understanding_api\"\n    description: str = (\n        \"A wrapper around Nuclia Understanding API endpoints. \"\n        \"Useful for when you need to extract text from any kind of files. \"\n    )\n    args_schema: Type[BaseModel] = NUASchema\n    _results: Dict[str, Any] = {}\n    _config: Dict[str, Any] = {}\n    def __init__(self, enable_ml: bool = False) -> None:\n        zone = os.environ.get(\"NUCLIA_ZONE\", \"europe-1\")\n        self._config[\"BACKEND\"] = f\"https://{zone}.nuclia.cloud/api/v1\"\n        key = os.environ.get(\"NUCLIA_NUA_KEY\")\n        if not key:\n            raise ValueError(\"NUCLIA_NUA_KEY environment variable not set\")\n        else:\n            self._config[\"NUA_KEY\"] = key\n        self._config[\"enable_ml\"] = enable_ml\n        super().__init__()\n    def _run(\n        self,\n        action: str,\n        id: str,\n        path: Optional[str],\n        text: Optional[str],\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        if action == \"push\":\n            self._check_params(path, text)\n            if path:\n                return self._pushFile(id, path)\n            if text:\n                return self._pushText(id, text)\n        elif action == \"pull\":\n            return self._pull(id)\n        return \"\"\n    async def _arun(\n        self,\n        action: str,\n        id: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html"}
{"id": "90335ecbeb3f-2", "text": "self,\n        action: str,\n        id: str,\n        path: Optional[str] = None,\n        text: Optional[str] = None,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        self._check_params(path, text)\n        if path:\n            self._pushFile(id, path)\n        if text:\n            self._pushText(id, text)\n        data = None\n        while True:\n            data = self._pull(id)\n            if data:\n                break\n            await asyncio.sleep(15)\n        return data\n    def _pushText(self, id: str, text: str) -> str:\n        field = {\n            \"textfield\": {\"text\": {\"body\": text, \"format\": 0}},\n            \"processing_options\": {\"ml_text\": self._config[\"enable_ml\"]},\n        }\n        return self._pushField(id, field)\n    def _pushFile(self, id: str, content_path: str) -> str:\n        with open(content_path, \"rb\") as source_file:\n            response = requests.post(\n                self._config[\"BACKEND\"] + \"/processing/upload\",\n                headers={\n                    \"content-type\": mimetypes.guess_type(content_path)[0]\n                    or \"application/octet-stream\",\n                    \"x-stf-nuakey\": \"Bearer \" + self._config[\"NUA_KEY\"],\n                },\n                data=source_file.read(),\n            )\n            if response.status_code != 200:\n                logger.info(\n                    f\"Error uploading {content_path}: \"\n                    f\"{response.status_code} {response.text}\"\n                )\n                return \"\"\n            else:\n                field = {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html"}
{"id": "90335ecbeb3f-3", "text": ")\n                return \"\"\n            else:\n                field = {\n                    \"filefield\": {\"file\": f\"{response.text}\"},\n                    \"processing_options\": {\"ml_text\": self._config[\"enable_ml\"]},\n                }\n                return self._pushField(id, field)\n    def _pushField(self, id: str, field: Any) -> str:\n        logger.info(f\"Pushing {id} in queue\")\n        response = requests.post(\n            self._config[\"BACKEND\"] + \"/processing/push\",\n            headers={\n                \"content-type\": \"application/json\",\n                \"x-stf-nuakey\": \"Bearer \" + self._config[\"NUA_KEY\"],\n            },\n            json=field,\n        )\n        if response.status_code != 200:\n            logger.info(\n                f\"Error pushing field {id}:\" f\"{response.status_code} {response.text}\"\n            )\n            raise ValueError(\"Error pushing field\")\n        else:\n            uuid = response.json()[\"uuid\"]\n            logger.info(f\"Field {id} pushed in queue, uuid: {uuid}\")\n            self._results[id] = {\"uuid\": uuid, \"status\": \"pending\"}\n            return uuid\n    def _pull(self, id: str) -> str:\n        self._pull_queue()\n        result = self._results.get(id, None)\n        if not result:\n            logger.info(f\"{id} not in queue\")\n            return \"\"\n        elif result[\"status\"] == \"pending\":\n            logger.info(f'Waiting for {result[\"uuid\"]} to be processed')\n            return \"\"\n        else:\n            return result[\"data\"]\n    def _pull_queue(self) -> None:\n        try:\n            from nucliadb_protos.writer_pb2 import BrokerMessage", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html"}
{"id": "90335ecbeb3f-4", "text": "try:\n            from nucliadb_protos.writer_pb2 import BrokerMessage\n        except ImportError as e:\n            raise ImportError(\n                \"nucliadb-protos is not installed. \"\n                \"Run `pip install nucliadb-protos` to install.\"\n            ) from e\n        try:\n            from google.protobuf.json_format import MessageToJson\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import google.protobuf, please install with \"\n                \"`pip install protobuf`.\"\n            ) from e\n        res = requests.get(\n            self._config[\"BACKEND\"] + \"/processing/pull\",\n            headers={\n                \"x-stf-nuakey\": \"Bearer \" + self._config[\"NUA_KEY\"],\n            },\n        ).json()\n        if res[\"status\"] == \"empty\":\n            logger.info(\"Queue empty\")\n        elif res[\"status\"] == \"ok\":\n            payload = res[\"payload\"]\n            pb = BrokerMessage()\n            pb.ParseFromString(base64.b64decode(payload))\n            uuid = pb.uuid\n            logger.info(f\"Pulled {uuid} from queue\")\n            matching_id = self._find_matching_id(uuid)\n            if not matching_id:\n                logger.info(f\"No matching id for {uuid}\")\n            else:\n                self._results[matching_id][\"status\"] = \"done\"\n                data = MessageToJson(\n                    pb,\n                    preserving_proto_field_name=True,\n                    including_default_value_fields=True,\n                )\n                self._results[matching_id][\"data\"] = data\n    def _find_matching_id(self, uuid: str) -> Union[str, None]:\n        for id, result in self._results.items():\n            if result[\"uuid\"] == uuid:\n                return id\n        return None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html"}
{"id": "90335ecbeb3f-5", "text": "if result[\"uuid\"] == uuid:\n                return id\n        return None\n    def _check_params(self, path: Optional[str], text: Optional[str]) -> None:\n        if not path and not text:\n            raise ValueError(\"File path or text is required\")\n        if path and text:\n            raise ValueError(\"Cannot process both file and text on a single run\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html"}
{"id": "0834ebc9c86c-0", "text": "Source code for langchain.tools.sql_database.tool\n# flake8: noqa\n\"\"\"Tools for interacting with a SQL database.\"\"\"\nfrom typing import Any, Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.utilities.sql_database import SQLDatabase\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.sql_database.prompt import QUERY_CHECKER\n[docs]class BaseSQLDatabaseTool(BaseModel):\n    \"\"\"Base tool for interacting with a SQL database.\"\"\"\n    db: SQLDatabase = Field(exclude=True)\n    class Config(BaseTool.Config):\n        pass\n[docs]class QuerySQLDataBaseTool(BaseSQLDatabaseTool, BaseTool):\n    \"\"\"Tool for querying a SQL database.\"\"\"\n    name: str = \"sql_db_query\"\n    description: str = \"\"\"\n    Input to this tool is a detailed and correct SQL query, output is a result from the database.\n    If the query is not correct, an error message will be returned.\n    If an error is returned, rewrite the query, check the query, and try again.\n    \"\"\"\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Execute the query, return the results or an error message.\"\"\"\n        return self.db.run_no_throw(query)\n[docs]class InfoSQLDatabaseTool(BaseSQLDatabaseTool, BaseTool):\n    \"\"\"Tool for getting metadata about a SQL database.\"\"\"\n    name: str = \"sql_db_schema\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/sql_database/tool.html"}
{"id": "0834ebc9c86c-1", "text": "name: str = \"sql_db_schema\"\n    description: str = \"\"\"\n    Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.    \n    Example Input: \"table1, table2, table3\"\n    \"\"\"\n    def _run(\n        self,\n        table_names: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Get the schema for tables in a comma-separated list.\"\"\"\n        return self.db.get_table_info_no_throw(table_names.split(\", \"))\n[docs]class ListSQLDatabaseTool(BaseSQLDatabaseTool, BaseTool):\n    \"\"\"Tool for getting tables names.\"\"\"\n    name: str = \"sql_db_list_tables\"\n    description: str = \"Input is an empty string, output is a comma separated list of tables in the database.\"\n    def _run(\n        self,\n        tool_input: str = \"\",\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Get the schema for a specific table.\"\"\"\n        return \", \".join(self.db.get_usable_table_names())\n[docs]class QuerySQLCheckerTool(BaseSQLDatabaseTool, BaseTool):\n    \"\"\"Use an LLM to check if a query is correct.\n    Adapted from https://www.patterns.app/blog/2023/01/18/crunchbot-sql-analyst-gpt/\"\"\"\n    template: str = QUERY_CHECKER\n    llm: BaseLanguageModel\n    llm_chain: LLMChain = Field(init=False)\n    name: str = \"sql_db_query_checker\"\n    description: str = \"\"\"\n    Use this tool to double check if your query is correct before executing it.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/sql_database/tool.html"}
{"id": "0834ebc9c86c-2", "text": "Use this tool to double check if your query is correct before executing it.\n    Always use this tool before executing a query with sql_db_query!\n    \"\"\"\n    @root_validator(pre=True)\n    def initialize_llm_chain(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        if \"llm_chain\" not in values:\n            values[\"llm_chain\"] = LLMChain(\n                llm=values.get(\"llm\"),\n                prompt=PromptTemplate(\n                    template=QUERY_CHECKER, input_variables=[\"dialect\", \"query\"]\n                ),\n            )\n        if values[\"llm_chain\"].prompt.input_variables != [\"dialect\", \"query\"]:\n            raise ValueError(\n                \"LLM chain for QueryCheckerTool must have input variables ['query', 'dialect']\"\n            )\n        return values\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the LLM to check the query.\"\"\"\n        return self.llm_chain.predict(\n            query=query,\n            dialect=self.db.dialect,\n            callbacks=run_manager.get_child() if run_manager else None,\n        )\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        return await self.llm_chain.apredict(\n            query=query,\n            dialect=self.db.dialect,\n            callbacks=run_manager.get_child() if run_manager else None,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/sql_database/tool.html"}
{"id": "83f04f7c86db-0", "text": "Source code for langchain.tools.sleep.tool\n\"\"\"Tool for agent to sleep.\"\"\"\nfrom asyncio import sleep as asleep\nfrom time import sleep\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\n[docs]class SleepInput(BaseModel):\n    \"\"\"Input for CopyFileTool.\"\"\"\n    sleep_time: int = Field(..., description=\"Time to sleep in seconds\")\n[docs]class SleepTool(BaseTool):\n    \"\"\"Tool that adds the capability to sleep.\"\"\"\n    name: str = \"sleep\"\n    args_schema: Type[BaseModel] = SleepInput\n    description: str = \"Make agent sleep for a specified number of seconds.\"\n    def _run(\n        self,\n        sleep_time: int,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the Sleep tool.\"\"\"\n        sleep(sleep_time)\n        return f\"Agent slept for {sleep_time} seconds.\"\n    async def _arun(\n        self,\n        sleep_time: int,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the sleep tool asynchronously.\"\"\"\n        await asleep(sleep_time)\n        return f\"Agent slept for {sleep_time} seconds.\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/sleep/tool.html"}
{"id": "5ddce0bcf8c0-0", "text": "Source code for langchain.tools.google_serper.tool\n\"\"\"Tool for the Serper.dev Google Search API.\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.google_serper import GoogleSerperAPIWrapper\n[docs]class GoogleSerperRun(BaseTool):\n    \"\"\"Tool that queries the Serper.dev Google search API.\"\"\"\n    name: str = \"google_serper\"\n    description: str = (\n        \"A low-cost Google Search API.\"\n        \"Useful for when you need to answer questions about current events.\"\n        \"Input should be a search query.\"\n    )\n    api_wrapper: GoogleSerperAPIWrapper\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return str(self.api_wrapper.run(query))\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        return (await self.api_wrapper.arun(query)).__str__()\n[docs]class GoogleSerperResults(BaseTool):\n    \"\"\"Tool that queries the Serper.dev Google Search API\n    and get back json.\"\"\"\n    name: str = \"google_serper_results_json\"\n    description: str = (\n        \"A low-cost Google Search API.\"\n        \"Useful for when you need to answer questions about current events.\"\n        \"Input should be a search query. Output is a JSON object of the query results\"\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html"}
{"id": "5ddce0bcf8c0-1", "text": ")\n    api_wrapper: GoogleSerperAPIWrapper = Field(default_factory=GoogleSerperAPIWrapper)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return str(self.api_wrapper.results(query))\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        return (await self.api_wrapper.aresults(query)).__str__()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html"}
{"id": "e7a0267fdf90-0", "text": "Source code for langchain.tools.searchapi.tool\n\"\"\"Tool for the SearchApi.io search API.\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.searchapi import SearchApiAPIWrapper\n[docs]class SearchAPIRun(BaseTool):\n    \"\"\"Tool that queries the SearchApi.io search API.\"\"\"\n    name: str = \"searchapi\"\n    description: str = (\n        \"Google search API provided by SearchApi.io.\"\n        \"This tool is handy when you need to answer questions about current events.\"\n        \"Input should be a search query.\"\n    )\n    api_wrapper: SearchApiAPIWrapper\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return self.api_wrapper.run(query)\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        return await self.api_wrapper.arun(query)\n[docs]class SearchAPIResults(BaseTool):\n    \"\"\"Tool that queries the SearchApi.io search API and returns JSON.\"\"\"\n    name: str = \"searchapi_results_json\"\n    description: str = (\n        \"Google search API provided by SearchApi.io.\"\n        \"This tool is handy when you need to answer questions about current events.\"\n        \"The input should be a search query and the output is a JSON object \"\n        \"with the query results.\"\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/searchapi/tool.html"}
{"id": "e7a0267fdf90-1", "text": "\"with the query results.\"\n    )\n    api_wrapper: SearchApiAPIWrapper = Field(default_factory=SearchApiAPIWrapper)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return str(self.api_wrapper.results(query))\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        return (await self.api_wrapper.aresults(query)).__str__()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/searchapi/tool.html"}
{"id": "a3153f92c86d-0", "text": "Source code for langchain.tools.edenai.text_moderation\nfrom __future__ import annotations\nimport logging\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.edenai.edenai_base_tool import EdenaiTool\nlogger = logging.getLogger(__name__)\n[docs]class EdenAiTextModerationTool(EdenaiTool):\n    \"\"\"Tool that queries the Eden AI Explicit text detection.\n    for api reference check edenai documentation:\n    https://docs.edenai.co/reference/image_explicit_content_create.\n    To use, you should have\n    the environment variable ``EDENAI_API_KEY`` set with your API token.\n    You can find your token here: https://app.edenai.run/admin/account/settings\n    \"\"\"\n    name = \"edenai_explicit_content_detection_text\"\n    description = (\n        \"A wrapper around edenai Services explicit content detection for text. \"\n        \"\"\"Useful for when you have to scan text for offensive, \n        sexually explicit or suggestive content,\n        it checks also if there is any content of self-harm,\n        violence, racist or hate speech.\"\"\"\n        \"\"\"the structure of the output is : \n        'the type of the explicit content : the likelihood of it being explicit'\n        the likelihood is a number \n        between 1 and 5, 1 being the lowest and 5 the highest.\n        something is explicit if the likelihood is equal or higher than 3.\n        for example : \n        nsfw_likelihood: 1\n        this is not explicit.\n        for example : \n        nsfw_likelihood: 3\n        this is explicit.\n        \"\"\"\n        \"Input should be a string.\"\n    )\n    language: str\n    feature: str = \"text\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/text_moderation.html"}
{"id": "a3153f92c86d-1", "text": ")\n    language: str\n    feature: str = \"text\"\n    subfeature: str = \"moderation\"\n    def _parse_response(self, response: list) -> str:\n        formatted_result = []\n        for result in response:\n            if \"nsfw_likelihood\" in result.keys():\n                formatted_result.append(\n                    \"nsfw_likelihood: \" + str(result[\"nsfw_likelihood\"])\n                )\n            for label, likelihood in zip(result[\"label\"], result[\"likelihood\"]):\n                formatted_result.append(f'\"{label}\": {str(likelihood)}')\n        return \"\\n\".join(formatted_result)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        query_params = {\"text\": query, \"language\": self.language}\n        return self._call_eden_ai(query_params)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/text_moderation.html"}
{"id": "0f362f608e28-0", "text": "Source code for langchain.tools.edenai.ocr_identityparser\nfrom __future__ import annotations\nimport logging\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.edenai.edenai_base_tool import EdenaiTool\nlogger = logging.getLogger(__name__)\n[docs]class EdenAiParsingIDTool(EdenaiTool):\n    \"\"\"Tool that queries the Eden AI  Identity parsing API.\n    for api reference check edenai documentation:\n    https://docs.edenai.co/reference/ocr_identity_parser_create.\n    To use, you should have\n    the environment variable ``EDENAI_API_KEY`` set with your API token.\n    You can find your token here: https://app.edenai.run/admin/account/settings\n    \"\"\"\n    name = \"edenai_identity_parsing\"\n    description = (\n        \"A wrapper around edenai Services Identity parsing. \"\n        \"Useful for when you have to extract information from an ID Document \"\n        \"Input should be the string url of the document to parse.\"\n    )\n    feature = \"ocr\"\n    subfeature = \"identity_parser\"\n    language: Optional[str] = None\n    \"\"\"\n    language of the text passed to the model.\n    \"\"\"\n    def _parse_response(self, response: list) -> str:\n        formatted_list: list = []\n        if len(response) == 1:\n            self._parse_json_multilevel(\n                response[0][\"extracted_data\"][0], formatted_list\n            )\n        else:\n            for entry in response:\n                if entry.get(\"provider\") == \"eden-ai\":\n                    self._parse_json_multilevel(\n                        entry[\"extracted_data\"][0], formatted_list\n                    )\n        return \"\\n\".join(formatted_list)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/ocr_identityparser.html"}
{"id": "0f362f608e28-1", "text": ")\n        return \"\\n\".join(formatted_list)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        query_params = {\n            \"file_url\": query,\n            \"language\": self.language,\n            \"attributes_as_list\": False,\n        }\n        return self._call_eden_ai(query_params)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/ocr_identityparser.html"}
{"id": "03b9b9a9843d-0", "text": "Source code for langchain.tools.edenai.edenai_base_tool\nfrom __future__ import annotations\nimport logging\nfrom abc import abstractmethod\nfrom typing import Any, Dict, List, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.tools.base import BaseTool\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class EdenaiTool(BaseTool):\n    \"\"\"\n    the base tool for all the EdenAI Tools .\n    you should have\n    the environment variable ``EDENAI_API_KEY`` set with your API token.\n    You can find your token here: https://app.edenai.run/admin/account/settings\n    \"\"\"\n    feature: str\n    subfeature: str\n    edenai_api_key: Optional[str] = None\n    is_async: bool = False\n    providers: List[str]\n    \"\"\"provider to use for the API call.\"\"\"\n    @root_validator(allow_reuse=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key exists in environment.\"\"\"\n        values[\"edenai_api_key\"] = get_from_dict_or_env(\n            values, \"edenai_api_key\", \"EDENAI_API_KEY\"\n        )\n        return values\n[docs]    @staticmethod\n    def get_user_agent() -> str:\n        from langchain import __version__\n        return f\"langchain/{__version__}\"\n    def _call_eden_ai(self, query_params: Dict[str, Any]) -> str:\n        \"\"\"\n        Make an API call to the EdenAI service with the specified query parameters.\n        Args:\n            query_params (dict): The parameters to include in the API call.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/edenai_base_tool.html"}
{"id": "03b9b9a9843d-1", "text": "query_params (dict): The parameters to include in the API call.\n        Returns:\n            requests.Response: The response from the EdenAI API call.\n        \"\"\"\n        # faire l'API call\n        headers = {\n            \"Authorization\": f\"Bearer {self.edenai_api_key}\",\n            \"User-Agent\": self.get_user_agent(),\n        }\n        url = f\"https://api.edenai.run/v2/{self.feature}/{self.subfeature}\"\n        payload = {\n            \"providers\": str(self.providers),\n            \"response_as_dict\": False,\n            \"attributes_as_list\": True,\n            \"show_original_response\": False,\n        }\n        payload.update(query_params)\n        response = requests.post(url, json=payload, headers=headers)\n        self._raise_on_error(response)\n        try:\n            return self._parse_response(response.json())\n        except Exception as e:\n            raise RuntimeError(f\"An error occurred while running tool: {e}\")\n    def _raise_on_error(self, response: requests.Response) -> None:\n        if response.status_code >= 500:\n            raise Exception(f\"EdenAI Server: Error {response.status_code}\")\n        elif response.status_code >= 400:\n            raise ValueError(f\"EdenAI received an invalid payload: {response.text}\")\n        elif response.status_code != 200:\n            raise Exception(\n                f\"EdenAI returned an unexpected response with status \"\n                f\"{response.status_code}: {response.text}\"\n            )\n        # case where edenai call succeeded but provider returned an error\n        # (eg: rate limit, server error, etc.)\n        if self.is_async is False:\n            # async call are different and only return a job_id,\n            # not the provider response directly\n            provider_response = response.json()[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/edenai_base_tool.html"}
{"id": "03b9b9a9843d-2", "text": "# not the provider response directly\n            provider_response = response.json()[0]\n            if provider_response.get(\"status\") == \"fail\":\n                err_msg = provider_response[\"error\"][\"message\"]\n                raise ValueError(err_msg)\n    @abstractmethod\n    def _run(\n        self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None\n    ) -> str:\n        pass\n    @abstractmethod\n    def _parse_response(self, response: Any) -> str:\n        \"\"\"Take a dict response and condense it's data in a human readable string\"\"\"\n        pass\n    def _get_edenai(self, url: str) -> requests.Response:\n        headers = {\n            \"accept\": \"application/json\",\n            \"authorization\": f\"Bearer {self.edenai_api_key}\",\n            \"User-Agent\": self.get_user_agent(),\n        }\n        response = requests.get(url, headers=headers)\n        self._raise_on_error(response)\n        return response\n    def _parse_json_multilevel(\n        self, extracted_data: dict, formatted_list: list, level: int = 0\n    ) -> None:\n        for section, subsections in extracted_data.items():\n            indentation = \"  \" * level\n            if isinstance(subsections, str):\n                subsections = subsections.replace(\"\\n\", \",\")\n                formatted_list.append(f\"{indentation}{section} : {subsections}\")\n            elif isinstance(subsections, list):\n                formatted_list.append(f\"{indentation}{section} : \")\n                self._list_handling(subsections, formatted_list, level + 1)\n            elif isinstance(subsections, dict):\n                formatted_list.append(f\"{indentation}{section} : \")\n                self._parse_json_multilevel(subsections, formatted_list, level + 1)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/edenai_base_tool.html"}
{"id": "03b9b9a9843d-3", "text": "self._parse_json_multilevel(subsections, formatted_list, level + 1)\n    def _list_handling(\n        self, subsection_list: list, formatted_list: list, level: int\n    ) -> None:\n        for list_item in subsection_list:\n            if isinstance(list_item, dict):\n                self._parse_json_multilevel(list_item, formatted_list, level)\n            elif isinstance(list_item, list):\n                self._list_handling(list_item, formatted_list, level + 1)\n            else:\n                formatted_list.append(f\"{'  ' * level}{list_item}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/edenai_base_tool.html"}
{"id": "945286f12749-0", "text": "Source code for langchain.tools.edenai.audio_speech_to_text\nfrom __future__ import annotations\nimport json\nimport logging\nimport time\nfrom typing import List, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import validator\nfrom langchain.tools.edenai.edenai_base_tool import EdenaiTool\nlogger = logging.getLogger(__name__)\n[docs]class EdenAiSpeechToTextTool(EdenaiTool):\n    \"\"\"Tool that queries the Eden AI Speech To Text API.\n    for api reference check edenai documentation:\n    https://app.edenai.run/bricks/speech/asynchronous-speech-to-text.\n    To use, you should have\n    the environment variable ``EDENAI_API_KEY`` set with your API token.\n    You can find your token here: https://app.edenai.run/admin/account/settings\n    \"\"\"\n    edenai_api_key: Optional[str] = None\n    name = \"edenai_speech_to_text\"\n    description = (\n        \"A wrapper around edenai Services speech to text \"\n        \"Useful for when you have to convert audio to text.\"\n        \"Input should be a url to an audio file.\"\n    )\n    is_async = True\n    language: Optional[str] = \"en\"\n    speakers: Optional[int]\n    profanity_filter: bool = False\n    custom_vocabulary: Optional[List[str]]\n    feature: str = \"audio\"\n    subfeature: str = \"speech_to_text_async\"\n    base_url = \"https://api.edenai.run/v2/audio/speech_to_text_async/\"\n    @validator(\"providers\")\n    def check_only_one_provider_selected(cls, v: List[str]) -> List[str]:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/audio_speech_to_text.html"}
{"id": "945286f12749-1", "text": "\"\"\"\n        This tool has no feature to combine providers results.\n        Therefore we only allow one provider\n        \"\"\"\n        if len(v) > 1:\n            raise ValueError(\n                \"Please select only one provider. \"\n                \"The feature to combine providers results is not available \"\n                \"for this tool.\"\n            )\n        return v\n    def _wait_processing(self, url: str) -> requests.Response:\n        for _ in range(10):\n            time.sleep(1)\n            audio_analysis_result = self._get_edenai(url)\n            temp = audio_analysis_result.json()\n            if temp[\"status\"] == \"finished\":\n                if temp[\"results\"][self.providers[0]][\"error\"] is not None:\n                    raise Exception(\n                        f\"\"\"EdenAI returned an unexpected response \n                        {temp['results'][self.providers[0]]['error']}\"\"\"\n                    )\n                else:\n                    return audio_analysis_result\n        raise Exception(\"Edenai speech to text job id processing Timed out\")\n    def _parse_response(self, response: dict) -> str:\n        return response[\"public_id\"]\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        all_params = {\n            \"file_url\": query,\n            \"language\": self.language,\n            \"speakers\": self.speakers,\n            \"profanity_filter\": self.profanity_filter,\n            \"custom_vocabulary\": self.custom_vocabulary,\n        }\n        # filter so we don't send val to api when val is `None\n        query_params = {k: v for k, v in all_params.items() if v is not None}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/audio_speech_to_text.html"}
{"id": "945286f12749-2", "text": "job_id = self._call_eden_ai(query_params)\n        url = self.base_url + job_id\n        audio_analysis_result = self._wait_processing(url)\n        result = audio_analysis_result.text\n        formatted_text = json.loads(result)\n        return formatted_text[\"results\"][self.providers[0]][\"text\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/audio_speech_to_text.html"}
{"id": "c0f42b82dcd8-0", "text": "Source code for langchain.tools.edenai.image_explicitcontent\nfrom __future__ import annotations\nimport logging\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.edenai.edenai_base_tool import EdenaiTool\nlogger = logging.getLogger(__name__)\n[docs]class EdenAiExplicitImageTool(EdenaiTool):\n    \"\"\"Tool that queries the Eden AI Explicit image detection.\n    for api reference check edenai documentation:\n    https://docs.edenai.co/reference/image_explicit_content_create.\n    To use, you should have\n    the environment variable ``EDENAI_API_KEY`` set with your API token.\n    You can find your token here: https://app.edenai.run/admin/account/settings\n    \"\"\"\n    name = \"edenai_image_explicit_content_detection\"\n    description = (\n        \"A wrapper around edenai Services Explicit image detection. \"\n        \"\"\"Useful for when you have to extract Explicit Content from images.\n        it detects adult only content in images, \n        that is generally inappropriate for people under\n        the age of 18 and includes nudity, sexual activity,\n        pornography, violence, gore content, etc.\"\"\"\n        \"Input should be the string url of the image .\"\n    )\n    combine_available = True\n    feature = \"image\"\n    subfeature = \"explicit_content\"\n    def _parse_json(self, json_data: dict) -> str:\n        result_str = f\"nsfw_likelihood: {json_data['nsfw_likelihood']}\\n\"\n        for idx, found_obj in enumerate(json_data[\"items\"]):\n            label = found_obj[\"label\"].lower()\n            likelihood = found_obj[\"likelihood\"]\n            result_str += f\"{idx}: {label} likelihood {likelihood},\\n\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/image_explicitcontent.html"}
{"id": "c0f42b82dcd8-1", "text": "result_str += f\"{idx}: {label} likelihood {likelihood},\\n\"\n        return result_str[:-2]\n    def _parse_response(self, json_data: list) -> str:\n        if len(json_data) == 1:\n            result = self._parse_json(json_data[0])\n        else:\n            for entry in json_data:\n                if entry.get(\"provider\") == \"eden-ai\":\n                    result = self._parse_json(entry)\n        return result\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        query_params = {\"file_url\": query, \"attributes_as_list\": False}\n        return self._call_eden_ai(query_params)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/image_explicitcontent.html"}
{"id": "fa614e4eb715-0", "text": "Source code for langchain.tools.edenai.image_objectdetection\nfrom __future__ import annotations\nimport logging\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.edenai.edenai_base_tool import EdenaiTool\nlogger = logging.getLogger(__name__)\n[docs]class EdenAiObjectDetectionTool(EdenaiTool):\n    \"\"\"Tool that queries the Eden AI Object detection API.\n    for api reference check edenai documentation:\n    https://docs.edenai.co/reference/image_object_detection_create.\n    To use, you should have\n    the environment variable ``EDENAI_API_KEY`` set with your API token.\n    You can find your token here: https://app.edenai.run/admin/account/settings\n    \"\"\"\n    name = \"edenai_object_detection\"\n    description = (\n        \"A wrapper around edenai Services Object Detection . \"\n        \"\"\"Useful for when you have to do an  to identify and locate\n        (with bounding boxes) objects in an image \"\"\"\n        \"Input should be the string url of the image to identify.\"\n    )\n    show_positions: bool = False\n    feature = \"image\"\n    subfeature = \"object_detection\"\n    def _parse_json(self, json_data: dict) -> str:\n        result = []\n        label_info = []\n        for found_obj in json_data[\"items\"]:\n            label_str = f\"{found_obj['label']} - Confidence {found_obj['confidence']}\"\n            x_min = found_obj.get(\"x_min\")\n            x_max = found_obj.get(\"x_max\")\n            y_min = found_obj.get(\"y_min\")\n            y_max = found_obj.get(\"y_max\")\n            if self.show_positions and all(\n                [x_min, x_max, y_min, y_max]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/image_objectdetection.html"}
{"id": "fa614e4eb715-1", "text": "[x_min, x_max, y_min, y_max]\n            ):  # some providers don't return positions\n                label_str += f\"\"\",at the position x_min: {x_min}, x_max: {x_max}, \n                y_min: {y_min}, y_max: {y_max}\"\"\"\n            label_info.append(label_str)\n        result.append(\"\\n\".join(label_info))\n        return \"\\n\\n\".join(result)\n    def _parse_response(self, response: list) -> str:\n        if len(response) == 1:\n            result = self._parse_json(response[0])\n        else:\n            for entry in response:\n                if entry.get(\"provider\") == \"eden-ai\":\n                    result = self._parse_json(entry)\n        return result\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        query_params = {\"file_url\": query, \"attributes_as_list\": False}\n        return self._call_eden_ai(query_params)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/image_objectdetection.html"}
{"id": "2035afb79f94-0", "text": "Source code for langchain.tools.edenai.audio_text_to_speech\nfrom __future__ import annotations\nimport logging\nfrom typing import Dict, List, Literal, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import Field, root_validator, validator\nfrom langchain.tools.edenai.edenai_base_tool import EdenaiTool\nlogger = logging.getLogger(__name__)\n[docs]class EdenAiTextToSpeechTool(EdenaiTool):\n    \"\"\"Tool that queries the Eden AI Text to speech API.\n    for api reference check edenai documentation:\n    https://docs.edenai.co/reference/audio_text_to_speech_create.\n    To use, you should have\n    the environment variable ``EDENAI_API_KEY`` set with your API token.\n    You can find your token here: https://app.edenai.run/admin/account/settings\n    \"\"\"\n    name = \"edenai_text_to_speech\"\n    description = (\n        \"A wrapper around edenai Services text to speech.\"\n        \"Useful for when you need to convert text to speech.\"\n        \"\"\"the output is a string representing the URL of the audio file,\n        or the path to the downloaded wav file \"\"\"\n    )\n    language: Optional[str] = \"en\"\n    \"\"\"\n    language of the text passed to the model.\n    \"\"\"\n    # optional params see api documentation for more info\n    return_type: Literal[\"url\", \"wav\"] = \"url\"\n    rate: Optional[int]\n    pitch: Optional[int]\n    volume: Optional[int]\n    audio_format: Optional[str]\n    sampling_rate: Optional[int]\n    voice_models: Dict[str, str] = Field(default_factory=dict)\n    voice: Literal[\"MALE\", \"FEMALE\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/audio_text_to_speech.html"}
{"id": "2035afb79f94-1", "text": "voice: Literal[\"MALE\", \"FEMALE\"]\n    \"\"\"voice option : 'MALE' or 'FEMALE' \"\"\"\n    feature: str = \"audio\"\n    subfeature: str = \"text_to_speech\"\n    @validator(\"providers\")\n    def check_only_one_provider_selected(cls, v: List[str]) -> List[str]:\n        \"\"\"\n        This tool has no feature to combine providers results.\n        Therefore we only allow one provider\n        \"\"\"\n        if len(v) > 1:\n            raise ValueError(\n                \"Please select only one provider. \"\n                \"The feature to combine providers results is not available \"\n                \"for this tool.\"\n            )\n        return v\n    @root_validator\n    def check_voice_models_key_is_provider_name(cls, values: dict) -> dict:\n        for key in values.get(\"voice_models\", {}).keys():\n            if key not in values.get(\"providers\", []):\n                raise ValueError(\n                    \"voice_model should be formatted like this \"\n                    \"{<provider_name>: <its_voice_model>}\"\n                )\n        return values\n    def _download_wav(self, url: str, save_path: str) -> None:\n        response = requests.get(url)\n        if response.status_code == 200:\n            with open(save_path, \"wb\") as f:\n                f.write(response.content)\n        else:\n            raise ValueError(\"Error while downloading wav file\")\n    def _parse_response(self, response: list) -> str:\n        result = response[0]\n        if self.return_type == \"url\":\n            return result[\"audio_resource_url\"]\n        else:\n            self._download_wav(result[\"audio_resource_url\"], \"audio.wav\")\n            return \"audio.wav\"\n    def _run(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/audio_text_to_speech.html"}
{"id": "2035afb79f94-2", "text": "return \"audio.wav\"\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        all_params = {\n            \"text\": query,\n            \"language\": self.language,\n            \"option\": self.voice,\n            \"return_type\": self.return_type,\n            \"rate\": self.rate,\n            \"pitch\": self.pitch,\n            \"volume\": self.volume,\n            \"audio_format\": self.audio_format,\n            \"sampling_rate\": self.sampling_rate,\n            \"settings\": self.voice_models,\n        }\n        # filter so we don't send val to api when val is `None\n        query_params = {k: v for k, v in all_params.items() if v is not None}\n        return self._call_eden_ai(query_params)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/audio_text_to_speech.html"}
{"id": "e8578dbbcc61-0", "text": "Source code for langchain.tools.edenai.ocr_invoiceparser\nfrom __future__ import annotations\nimport logging\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.edenai.edenai_base_tool import EdenaiTool\nlogger = logging.getLogger(__name__)\n[docs]class EdenAiParsingInvoiceTool(EdenaiTool):\n    \"\"\"Tool that queries the Eden AI Invoice parsing API.\n    for api reference check edenai documentation:\n    https://docs.edenai.co/reference/ocr_invoice_parser_create.\n    To use, you should have\n    the environment variable ``EDENAI_API_KEY`` set with your API token.\n    You can find your token here: https://app.edenai.run/admin/account/settings\n    \"\"\"\n    name = \"edenai_invoice_parsing\"\n    description = (\n        \"A wrapper around edenai Services invoice parsing. \"\n        \"\"\"Useful for when you have to extract information from \n        an image it enables to take invoices \n        in a variety of formats and returns the data in contains\n        (items, prices, addresses, vendor name, etc.)\n        in a structured format to automate the invoice processing \"\"\"\n        \"Input should be the string url of the document to parse.\"\n    )\n    language: Optional[str] = None\n    \"\"\"\n    language of the image passed to the model.\n    \"\"\"\n    feature = \"ocr\"\n    subfeature = \"invoice_parser\"\n    def _parse_response(self, response: list) -> str:\n        formatted_list: list = []\n        if len(response) == 1:\n            self._parse_json_multilevel(\n                response[0][\"extracted_data\"][0], formatted_list\n            )\n        else:\n            for entry in response:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/ocr_invoiceparser.html"}
{"id": "e8578dbbcc61-1", "text": ")\n        else:\n            for entry in response:\n                if entry.get(\"provider\") == \"eden-ai\":\n                    self._parse_json_multilevel(\n                        entry[\"extracted_data\"][0], formatted_list\n                    )\n        return \"\\n\".join(formatted_list)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        query_params = {\n            \"file_url\": query,\n            \"language\": self.language,\n            \"attributes_as_list\": False,\n        }\n        return self._call_eden_ai(query_params)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/ocr_invoiceparser.html"}
{"id": "db0a1bc6c0bc-0", "text": "Source code for langchain.tools.e2b_data_analysis.tool\nfrom __future__ import annotations\nimport ast\nimport json\nimport os\nfrom io import StringIO\nfrom sys import version_info\nfrom typing import IO, TYPE_CHECKING, Any, Callable, List, Optional, Type\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManager,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field, PrivateAttr\nfrom langchain.tools import BaseTool, Tool\nfrom langchain.tools.e2b_data_analysis.unparse import Unparser\nif TYPE_CHECKING:\n    from e2b import EnvVars\n    from e2b.templates.data_analysis import Artifact\nbase_description = \"\"\"Evaluates python code in a sandbox environment. \\\nThe environment is long running and exists across multiple executions. \\\nYou must send the whole script every time and print your outputs. \\\nScript should be pure python code that can be evaluated. \\\nIt should be in python format NOT markdown. \\\nThe code should NOT be wrapped in backticks. \\\nAll python packages including requests, matplotlib, scipy, numpy, pandas, \\\netc are available. Create and display chart using `plt.show()`.\"\"\"\ndef _unparse(tree: ast.AST) -> str:\n    \"\"\"Unparse the AST.\"\"\"\n    if version_info.minor < 9:\n        s = StringIO()\n        Unparser(tree, file=s)\n        source_code = s.getvalue()\n        s.close()\n    else:\n        source_code = ast.unparse(tree)  # type: ignore[attr-defined]\n    return source_code\n[docs]def add_last_line_print(code: str) -> str:\n    \"\"\"Add print statement to the last line if it's missing.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/tool.html"}
{"id": "db0a1bc6c0bc-1", "text": "\"\"\"Add print statement to the last line if it's missing.\n    Sometimes, the LLM-generated code doesn't have `print(variable_name)`, instead the\n        LLM tries to print the variable only by writing `variable_name` (as you would in\n        REPL, for example).\n    This methods checks the AST of the generated Python code and adds the print\n        statement to the last line if it's missing.\n    \"\"\"\n    tree = ast.parse(code)\n    node = tree.body[-1]\n    if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):\n        if isinstance(node.value.func, ast.Name) and node.value.func.id == \"print\":\n            return _unparse(tree)\n    if isinstance(node, ast.Expr):\n        tree.body[-1] = ast.Expr(\n            value=ast.Call(\n                func=ast.Name(id=\"print\", ctx=ast.Load()),\n                args=[node.value],\n                keywords=[],\n            )\n        )\n    return _unparse(tree)\n[docs]class UploadedFile(BaseModel):\n    \"\"\"Description of the uploaded path with its remote path.\"\"\"\n    name: str\n    remote_path: str\n    description: str\n[docs]class E2BDataAnalysisToolArguments(BaseModel):\n    \"\"\"Arguments for the E2BDataAnalysisTool.\"\"\"\n    python_code: str = Field(\n        ...,\n        example=\"print('Hello World')\",\n        description=(\n            \"The python script to be evaluated. \"\n            \"The contents will be in main.py. \"\n            \"It should not be in markdown format.\"\n        ),\n    )\n[docs]class E2BDataAnalysisTool(BaseTool):\n    \"\"\"Tool for running python code in a sandboxed environment for data analysis.\"\"\"\n    name = \"e2b_data_analysis\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/tool.html"}
{"id": "db0a1bc6c0bc-2", "text": "name = \"e2b_data_analysis\"\n    args_schema: Type[BaseModel] = E2BDataAnalysisToolArguments\n    session: Any\n    _uploaded_files: List[UploadedFile] = PrivateAttr(default_factory=list)\n    def __init__(\n        self,\n        api_key: Optional[str] = None,\n        cwd: Optional[str] = None,\n        env_vars: Optional[EnvVars] = None,\n        on_stdout: Optional[Callable[[str], Any]] = None,\n        on_stderr: Optional[Callable[[str], Any]] = None,\n        on_artifact: Optional[Callable[[Artifact], Any]] = None,\n        on_exit: Optional[Callable[[int], Any]] = None,\n        **kwargs: Any,\n    ):\n        try:\n            from e2b import DataAnalysis\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import e2b, please install with `pip install e2b`.\"\n            ) from e\n        # If no API key is provided, E2B will try to read it from the environment\n        # variable E2B_API_KEY\n        super().__init__(description=base_description, **kwargs)\n        self.session = DataAnalysis(\n            api_key=api_key,\n            cwd=cwd,\n            env_vars=env_vars,\n            on_stdout=on_stdout,\n            on_stderr=on_stderr,\n            on_exit=on_exit,\n            on_artifact=on_artifact,\n        )\n[docs]    def close(self) -> None:\n        \"\"\"Close the cloud sandbox.\"\"\"\n        self._uploaded_files = []\n        self.session.close()\n    @property\n    def uploaded_files_description(self) -> str:\n        if len(self._uploaded_files) == 0:\n            return \"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/tool.html"}
{"id": "db0a1bc6c0bc-3", "text": "if len(self._uploaded_files) == 0:\n            return \"\"\n        lines = [\"The following files available in the sandbox:\"]\n        for f in self._uploaded_files:\n            if f.description == \"\":\n                lines.append(f\"- path: `{f.remote_path}`\")\n            else:\n                lines.append(\n                    f\"- path: `{f.remote_path}` \\n description: `{f.description}`\"\n                )\n        return \"\\n\".join(lines)\n    def _run(\n        self,\n        python_code: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n        callbacks: Optional[CallbackManager] = None,\n    ) -> str:\n        python_code = add_last_line_print(python_code)\n        if callbacks is not None:\n            on_artifact = getattr(callbacks.metadata, \"on_artifact\", None)\n        else:\n            on_artifact = None\n        stdout, stderr, artifacts = self.session.run_python(\n            python_code, on_artifact=on_artifact\n        )\n        out = {\n            \"stdout\": stdout,\n            \"stderr\": stderr,\n            \"artifacts\": list(map(lambda artifact: artifact.name, artifacts)),\n        }\n        return json.dumps(out)\n    async def _arun(\n        self,\n        python_code: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        raise NotImplementedError(\"e2b_data_analysis does not support async\")\n[docs]    def run_command(\n        self,\n        cmd: str,\n    ) -> dict:\n        \"\"\"Run shell command in the sandbox.\"\"\"\n        proc = self.session.process.start(cmd)\n        output = proc.wait()\n        return {\n            \"stdout\": output.stdout,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/tool.html"}
{"id": "db0a1bc6c0bc-4", "text": "output = proc.wait()\n        return {\n            \"stdout\": output.stdout,\n            \"stderr\": output.stderr,\n            \"exit_code\": output.exit_code,\n        }\n[docs]    def install_python_packages(self, package_names: str | List[str]) -> None:\n        \"\"\"Install python packages in the sandbox.\"\"\"\n        self.session.install_python_packages(package_names)\n[docs]    def install_system_packages(self, package_names: str | List[str]) -> None:\n        \"\"\"Install system packages (via apt) in the sandbox.\"\"\"\n        self.session.install_system_packages(package_names)\n[docs]    def download_file(self, remote_path: str) -> bytes:\n        \"\"\"Download file from the sandbox.\"\"\"\n        return self.session.download_file(remote_path)\n[docs]    def upload_file(self, file: IO, description: str) -> UploadedFile:\n        \"\"\"Upload file to the sandbox.\n        The file is uploaded to the '/home/user/<filename>' path.\"\"\"\n        remote_path = self.session.upload_file(file)\n        f = UploadedFile(\n            name=os.path.basename(file.name),\n            remote_path=remote_path,\n            description=description,\n        )\n        self._uploaded_files.append(f)\n        self.description = self.description + \"\\n\" + self.uploaded_files_description\n        return f\n[docs]    def remove_uploaded_file(self, uploaded_file: UploadedFile) -> None:\n        \"\"\"Remove uploaded file from the sandbox.\"\"\"\n        self.session.filesystem.remove(uploaded_file.remote_path)\n        self._uploaded_files = [\n            f\n            for f in self._uploaded_files\n            if f.remote_path != uploaded_file.remote_path\n        ]\n        self.description = self.description + \"\\n\" + self.uploaded_files_description\n[docs]    def as_tool(self) -> Tool:\n        return Tool.from_function(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/tool.html"}
{"id": "db0a1bc6c0bc-5", "text": "[docs]    def as_tool(self) -> Tool:\n        return Tool.from_function(\n            func=self._run,\n            name=self.name,\n            description=self.description,\n            args_schema=self.args_schema,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/tool.html"}
{"id": "60eb0b161d5e-0", "text": "Source code for langchain.tools.e2b_data_analysis.unparse\n# mypy: disable-error-code=no-untyped-def\n# Because Python >3.9 doesn't support ast.unparse,\n# we copied the unparse functionality from here:\n# https://github.com/python/cpython/blob/3.8/Tools/parser/unparse.py\n\"Usage: unparse.py <path to source file>\"\nimport ast\nimport io\nimport sys\nimport tokenize\n# Large float and imaginary literals get turned into infinities in the AST.\n# We unparse those infinities to INFSTR.\nINFSTR = \"1e\" + repr(sys.float_info.max_10_exp + 1)\n[docs]def interleave(inter, f, seq):\n    \"\"\"Call f on each item in seq, calling inter() in between.\"\"\"\n    seq = iter(seq)\n    try:\n        f(next(seq))\n    except StopIteration:\n        pass\n    else:\n        for x in seq:\n            inter()\n            f(x)\n[docs]class Unparser:\n    \"\"\"Methods in this class recursively traverse an AST and\n    output source code for the abstract syntax; original formatting\n    is disregarded.\"\"\"\n[docs]    def __init__(self, tree, file=sys.stdout):\n        \"\"\"Unparser(tree, file=sys.stdout) -> None.\n        Print the source for tree to file.\"\"\"\n        self.f = file\n        self._indent = 0\n        self.dispatch(tree)\n        self.f.flush()\n[docs]    def fill(self, text=\"\"):\n        \"Indent a piece of text, according to the current indentation level\"\n        self.f.write(\"\\n\" + \"    \" * self._indent + text)\n[docs]    def write(self, text):\n        \"Append a piece of text to the current line.\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "60eb0b161d5e-1", "text": "\"Append a piece of text to the current line.\"\n        self.f.write(text)\n[docs]    def enter(self):\n        \"Print ':', and increase the indentation.\"\n        self.write(\":\")\n        self._indent += 1\n[docs]    def leave(self):\n        \"Decrease the indentation level.\"\n        self._indent -= 1\n[docs]    def dispatch(self, tree):\n        \"Dispatcher function, dispatching tree type T to method _T.\"\n        if isinstance(tree, list):\n            for t in tree:\n                self.dispatch(t)\n            return\n        meth = getattr(self, \"_\" + tree.__class__.__name__)\n        meth(tree)\n    ############### Unparsing methods ######################\n    # There should be one method per concrete grammar type #\n    # Constructors should be grouped by sum type. Ideally, #\n    # this would follow the order in the grammar, but      #\n    # currently doesn't.                                   #\n    ########################################################\n    def _Module(self, tree):\n        for stmt in tree.body:\n            self.dispatch(stmt)\n    # stmt\n    def _Expr(self, tree):\n        self.fill()\n        self.dispatch(tree.value)\n    def _NamedExpr(self, tree):\n        self.write(\"(\")\n        self.dispatch(tree.target)\n        self.write(\" := \")\n        self.dispatch(tree.value)\n        self.write(\")\")\n    def _Import(self, t):\n        self.fill(\"import \")\n        interleave(lambda: self.write(\", \"), self.dispatch, t.names)\n    def _ImportFrom(self, t):\n        self.fill(\"from \")\n        self.write(\".\" * t.level)\n        if t.module:\n            self.write(t.module)\n        self.write(\" import \")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "60eb0b161d5e-2", "text": "if t.module:\n            self.write(t.module)\n        self.write(\" import \")\n        interleave(lambda: self.write(\", \"), self.dispatch, t.names)\n    def _Assign(self, t):\n        self.fill()\n        for target in t.targets:\n            self.dispatch(target)\n            self.write(\" = \")\n        self.dispatch(t.value)\n    def _AugAssign(self, t):\n        self.fill()\n        self.dispatch(t.target)\n        self.write(\" \" + self.binop[t.op.__class__.__name__] + \"= \")\n        self.dispatch(t.value)\n    def _AnnAssign(self, t):\n        self.fill()\n        if not t.simple and isinstance(t.target, ast.Name):\n            self.write(\"(\")\n        self.dispatch(t.target)\n        if not t.simple and isinstance(t.target, ast.Name):\n            self.write(\")\")\n        self.write(\": \")\n        self.dispatch(t.annotation)\n        if t.value:\n            self.write(\" = \")\n            self.dispatch(t.value)\n    def _Return(self, t):\n        self.fill(\"return\")\n        if t.value:\n            self.write(\" \")\n            self.dispatch(t.value)\n    def _Pass(self, t):\n        self.fill(\"pass\")\n    def _Break(self, t):\n        self.fill(\"break\")\n    def _Continue(self, t):\n        self.fill(\"continue\")\n    def _Delete(self, t):\n        self.fill(\"del \")\n        interleave(lambda: self.write(\", \"), self.dispatch, t.targets)\n    def _Assert(self, t):\n        self.fill(\"assert \")\n        self.dispatch(t.test)\n        if t.msg:\n            self.write(\", \")\n            self.dispatch(t.msg)\n    def _Global(self, t):\n        self.fill(\"global \")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "60eb0b161d5e-3", "text": "def _Global(self, t):\n        self.fill(\"global \")\n        interleave(lambda: self.write(\", \"), self.write, t.names)\n    def _Nonlocal(self, t):\n        self.fill(\"nonlocal \")\n        interleave(lambda: self.write(\", \"), self.write, t.names)\n    def _Await(self, t):\n        self.write(\"(\")\n        self.write(\"await\")\n        if t.value:\n            self.write(\" \")\n            self.dispatch(t.value)\n        self.write(\")\")\n    def _Yield(self, t):\n        self.write(\"(\")\n        self.write(\"yield\")\n        if t.value:\n            self.write(\" \")\n            self.dispatch(t.value)\n        self.write(\")\")\n    def _YieldFrom(self, t):\n        self.write(\"(\")\n        self.write(\"yield from\")\n        if t.value:\n            self.write(\" \")\n            self.dispatch(t.value)\n        self.write(\")\")\n    def _Raise(self, t):\n        self.fill(\"raise\")\n        if not t.exc:\n            assert not t.cause\n            return\n        self.write(\" \")\n        self.dispatch(t.exc)\n        if t.cause:\n            self.write(\" from \")\n            self.dispatch(t.cause)\n    def _Try(self, t):\n        self.fill(\"try\")\n        self.enter()\n        self.dispatch(t.body)\n        self.leave()\n        for ex in t.handlers:\n            self.dispatch(ex)\n        if t.orelse:\n            self.fill(\"else\")\n            self.enter()\n            self.dispatch(t.orelse)\n            self.leave()\n        if t.finalbody:\n            self.fill(\"finally\")\n            self.enter()\n            self.dispatch(t.finalbody)\n            self.leave()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "60eb0b161d5e-4", "text": "self.enter()\n            self.dispatch(t.finalbody)\n            self.leave()\n    def _ExceptHandler(self, t):\n        self.fill(\"except\")\n        if t.type:\n            self.write(\" \")\n            self.dispatch(t.type)\n        if t.name:\n            self.write(\" as \")\n            self.write(t.name)\n        self.enter()\n        self.dispatch(t.body)\n        self.leave()\n    def _ClassDef(self, t):\n        self.write(\"\\n\")\n        for deco in t.decorator_list:\n            self.fill(\"@\")\n            self.dispatch(deco)\n        self.fill(\"class \" + t.name)\n        self.write(\"(\")\n        comma = False\n        for e in t.bases:\n            if comma:\n                self.write(\", \")\n            else:\n                comma = True\n            self.dispatch(e)\n        for e in t.keywords:\n            if comma:\n                self.write(\", \")\n            else:\n                comma = True\n            self.dispatch(e)\n        self.write(\")\")\n        self.enter()\n        self.dispatch(t.body)\n        self.leave()\n    def _FunctionDef(self, t):\n        self.__FunctionDef_helper(t, \"def\")\n    def _AsyncFunctionDef(self, t):\n        self.__FunctionDef_helper(t, \"async def\")\n    def __FunctionDef_helper(self, t, fill_suffix):\n        self.write(\"\\n\")\n        for deco in t.decorator_list:\n            self.fill(\"@\")\n            self.dispatch(deco)\n        def_str = fill_suffix + \" \" + t.name + \"(\"\n        self.fill(def_str)\n        self.dispatch(t.args)\n        self.write(\")\")\n        if t.returns:\n            self.write(\" -> \")\n            self.dispatch(t.returns)\n        self.enter()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "60eb0b161d5e-5", "text": "self.write(\" -> \")\n            self.dispatch(t.returns)\n        self.enter()\n        self.dispatch(t.body)\n        self.leave()\n    def _For(self, t):\n        self.__For_helper(\"for \", t)\n    def _AsyncFor(self, t):\n        self.__For_helper(\"async for \", t)\n    def __For_helper(self, fill, t):\n        self.fill(fill)\n        self.dispatch(t.target)\n        self.write(\" in \")\n        self.dispatch(t.iter)\n        self.enter()\n        self.dispatch(t.body)\n        self.leave()\n        if t.orelse:\n            self.fill(\"else\")\n            self.enter()\n            self.dispatch(t.orelse)\n            self.leave()\n    def _If(self, t):\n        self.fill(\"if \")\n        self.dispatch(t.test)\n        self.enter()\n        self.dispatch(t.body)\n        self.leave()\n        # collapse nested ifs into equivalent elifs.\n        while t.orelse and len(t.orelse) == 1 and isinstance(t.orelse[0], ast.If):\n            t = t.orelse[0]\n            self.fill(\"elif \")\n            self.dispatch(t.test)\n            self.enter()\n            self.dispatch(t.body)\n            self.leave()\n        # final else\n        if t.orelse:\n            self.fill(\"else\")\n            self.enter()\n            self.dispatch(t.orelse)\n            self.leave()\n    def _While(self, t):\n        self.fill(\"while \")\n        self.dispatch(t.test)\n        self.enter()\n        self.dispatch(t.body)\n        self.leave()\n        if t.orelse:\n            self.fill(\"else\")\n            self.enter()\n            self.dispatch(t.orelse)\n            self.leave()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "60eb0b161d5e-6", "text": "self.enter()\n            self.dispatch(t.orelse)\n            self.leave()\n    def _With(self, t):\n        self.fill(\"with \")\n        interleave(lambda: self.write(\", \"), self.dispatch, t.items)\n        self.enter()\n        self.dispatch(t.body)\n        self.leave()\n    def _AsyncWith(self, t):\n        self.fill(\"async with \")\n        interleave(lambda: self.write(\", \"), self.dispatch, t.items)\n        self.enter()\n        self.dispatch(t.body)\n        self.leave()\n    # expr\n    def _JoinedStr(self, t):\n        self.write(\"f\")\n        string = io.StringIO()\n        self._fstring_JoinedStr(t, string.write)\n        self.write(repr(string.getvalue()))\n    def _FormattedValue(self, t):\n        self.write(\"f\")\n        string = io.StringIO()\n        self._fstring_FormattedValue(t, string.write)\n        self.write(repr(string.getvalue()))\n    def _fstring_JoinedStr(self, t, write):\n        for value in t.values:\n            meth = getattr(self, \"_fstring_\" + type(value).__name__)\n            meth(value, write)\n    def _fstring_Constant(self, t, write):\n        assert isinstance(t.value, str)\n        value = t.value.replace(\"{\", \"{{\").replace(\"}\", \"}}\")\n        write(value)\n    def _fstring_FormattedValue(self, t, write):\n        write(\"{\")\n        expr = io.StringIO()\n        Unparser(t.value, expr)\n        expr = expr.getvalue().rstrip(\"\\n\")\n        if expr.startswith(\"{\"):\n            write(\" \")  # Separate pair of opening brackets as \"{ {\"\n        write(expr)\n        if t.conversion != -1:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "60eb0b161d5e-7", "text": "write(expr)\n        if t.conversion != -1:\n            conversion = chr(t.conversion)\n            assert conversion in \"sra\"\n            write(f\"!{conversion}\")\n        if t.format_spec:\n            write(\":\")\n            meth = getattr(self, \"_fstring_\" + type(t.format_spec).__name__)\n            meth(t.format_spec, write)\n        write(\"}\")\n    def _Name(self, t):\n        self.write(t.id)\n    def _write_constant(self, value):\n        if isinstance(value, (float, complex)):\n            # Substitute overflowing decimal literal for AST infinities.\n            self.write(repr(value).replace(\"inf\", INFSTR))\n        else:\n            self.write(repr(value))\n    def _Constant(self, t):\n        value = t.value\n        if isinstance(value, tuple):\n            self.write(\"(\")\n            if len(value) == 1:\n                self._write_constant(value[0])\n                self.write(\",\")\n            else:\n                interleave(lambda: self.write(\", \"), self._write_constant, value)\n            self.write(\")\")\n        elif value is ...:\n            self.write(\"...\")\n        else:\n            if t.kind == \"u\":\n                self.write(\"u\")\n            self._write_constant(t.value)\n    def _List(self, t):\n        self.write(\"[\")\n        interleave(lambda: self.write(\", \"), self.dispatch, t.elts)\n        self.write(\"]\")\n    def _ListComp(self, t):\n        self.write(\"[\")\n        self.dispatch(t.elt)\n        for gen in t.generators:\n            self.dispatch(gen)\n        self.write(\"]\")\n    def _GeneratorExp(self, t):\n        self.write(\"(\")\n        self.dispatch(t.elt)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "60eb0b161d5e-8", "text": "self.write(\"(\")\n        self.dispatch(t.elt)\n        for gen in t.generators:\n            self.dispatch(gen)\n        self.write(\")\")\n    def _SetComp(self, t):\n        self.write(\"{\")\n        self.dispatch(t.elt)\n        for gen in t.generators:\n            self.dispatch(gen)\n        self.write(\"}\")\n    def _DictComp(self, t):\n        self.write(\"{\")\n        self.dispatch(t.key)\n        self.write(\": \")\n        self.dispatch(t.value)\n        for gen in t.generators:\n            self.dispatch(gen)\n        self.write(\"}\")\n    def _comprehension(self, t):\n        if t.is_async:\n            self.write(\" async for \")\n        else:\n            self.write(\" for \")\n        self.dispatch(t.target)\n        self.write(\" in \")\n        self.dispatch(t.iter)\n        for if_clause in t.ifs:\n            self.write(\" if \")\n            self.dispatch(if_clause)\n    def _IfExp(self, t):\n        self.write(\"(\")\n        self.dispatch(t.body)\n        self.write(\" if \")\n        self.dispatch(t.test)\n        self.write(\" else \")\n        self.dispatch(t.orelse)\n        self.write(\")\")\n    def _Set(self, t):\n        assert t.elts  # should be at least one element\n        self.write(\"{\")\n        interleave(lambda: self.write(\", \"), self.dispatch, t.elts)\n        self.write(\"}\")\n    def _Dict(self, t):\n        self.write(\"{\")\n        def write_key_value_pair(k, v):\n            self.dispatch(k)\n            self.write(\": \")\n            self.dispatch(v)\n        def write_item(item):\n            k, v = item\n            if k is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "60eb0b161d5e-9", "text": "k, v = item\n            if k is None:\n                # for dictionary unpacking operator in dicts {**{'y': 2}}\n                # see PEP 448 for details\n                self.write(\"**\")\n                self.dispatch(v)\n            else:\n                write_key_value_pair(k, v)\n        interleave(lambda: self.write(\", \"), write_item, zip(t.keys, t.values))\n        self.write(\"}\")\n    def _Tuple(self, t):\n        self.write(\"(\")\n        if len(t.elts) == 1:\n            elt = t.elts[0]\n            self.dispatch(elt)\n            self.write(\",\")\n        else:\n            interleave(lambda: self.write(\", \"), self.dispatch, t.elts)\n        self.write(\")\")\n    unop = {\"Invert\": \"~\", \"Not\": \"not\", \"UAdd\": \"+\", \"USub\": \"-\"}\n    def _UnaryOp(self, t):\n        self.write(\"(\")\n        self.write(self.unop[t.op.__class__.__name__])\n        self.write(\" \")\n        self.dispatch(t.operand)\n        self.write(\")\")\n    binop = {\n        \"Add\": \"+\",\n        \"Sub\": \"-\",\n        \"Mult\": \"*\",\n        \"MatMult\": \"@\",\n        \"Div\": \"/\",\n        \"Mod\": \"%\",\n        \"LShift\": \"<<\",\n        \"RShift\": \">>\",\n        \"BitOr\": \"|\",\n        \"BitXor\": \"^\",\n        \"BitAnd\": \"&\",\n        \"FloorDiv\": \"//\",\n        \"Pow\": \"**\",\n    }\n    def _BinOp(self, t):\n        self.write(\"(\")\n        self.dispatch(t.left)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "60eb0b161d5e-10", "text": "self.write(\"(\")\n        self.dispatch(t.left)\n        self.write(\" \" + self.binop[t.op.__class__.__name__] + \" \")\n        self.dispatch(t.right)\n        self.write(\")\")\n    cmpops = {\n        \"Eq\": \"==\",\n        \"NotEq\": \"!=\",\n        \"Lt\": \"<\",\n        \"LtE\": \"<=\",\n        \"Gt\": \">\",\n        \"GtE\": \">=\",\n        \"Is\": \"is\",\n        \"IsNot\": \"is not\",\n        \"In\": \"in\",\n        \"NotIn\": \"not in\",\n    }\n    def _Compare(self, t):\n        self.write(\"(\")\n        self.dispatch(t.left)\n        for o, e in zip(t.ops, t.comparators):\n            self.write(\" \" + self.cmpops[o.__class__.__name__] + \" \")\n            self.dispatch(e)\n        self.write(\")\")\n    boolops = {ast.And: \"and\", ast.Or: \"or\"}\n    def _BoolOp(self, t):\n        self.write(\"(\")\n        s = \" %s \" % self.boolops[t.op.__class__]\n        interleave(lambda: self.write(s), self.dispatch, t.values)\n        self.write(\")\")\n    def _Attribute(self, t):\n        self.dispatch(t.value)\n        # Special case: 3.__abs__() is a syntax error, so if t.value\n        # is an integer literal then we need to either parenthesize\n        # it or add an extra space to get 3 .__abs__().\n        if isinstance(t.value, ast.Constant) and isinstance(t.value.value, int):\n            self.write(\" \")\n        self.write(\".\")\n        self.write(t.attr)\n    def _Call(self, t):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "60eb0b161d5e-11", "text": "self.write(t.attr)\n    def _Call(self, t):\n        self.dispatch(t.func)\n        self.write(\"(\")\n        comma = False\n        for e in t.args:\n            if comma:\n                self.write(\", \")\n            else:\n                comma = True\n            self.dispatch(e)\n        for e in t.keywords:\n            if comma:\n                self.write(\", \")\n            else:\n                comma = True\n            self.dispatch(e)\n        self.write(\")\")\n    def _Subscript(self, t):\n        self.dispatch(t.value)\n        self.write(\"[\")\n        if (\n            isinstance(t.slice, ast.Index)\n            and isinstance(t.slice.value, ast.Tuple)\n            and t.slice.value.elts\n        ):\n            if len(t.slice.value.elts) == 1:\n                elt = t.slice.value.elts[0]\n                self.dispatch(elt)\n                self.write(\",\")\n            else:\n                interleave(lambda: self.write(\", \"), self.dispatch, t.slice.value.elts)\n        else:\n            self.dispatch(t.slice)\n        self.write(\"]\")\n    def _Starred(self, t):\n        self.write(\"*\")\n        self.dispatch(t.value)\n    # slice\n    def _Ellipsis(self, t):\n        self.write(\"...\")\n    def _Index(self, t):\n        self.dispatch(t.value)\n    def _Slice(self, t):\n        if t.lower:\n            self.dispatch(t.lower)\n        self.write(\":\")\n        if t.upper:\n            self.dispatch(t.upper)\n        if t.step:\n            self.write(\":\")\n            self.dispatch(t.step)\n    def _ExtSlice(self, t):\n        if len(t.dims) == 1:\n            elt = t.dims[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "60eb0b161d5e-12", "text": "elt = t.dims[0]\n            self.dispatch(elt)\n            self.write(\",\")\n        else:\n            interleave(lambda: self.write(\", \"), self.dispatch, t.dims)\n    # argument\n    def _arg(self, t):\n        self.write(t.arg)\n        if t.annotation:\n            self.write(\": \")\n            self.dispatch(t.annotation)\n    # others\n    def _arguments(self, t):\n        first = True\n        # normal arguments\n        all_args = t.posonlyargs + t.args\n        defaults = [None] * (len(all_args) - len(t.defaults)) + t.defaults\n        for index, elements in enumerate(zip(all_args, defaults), 1):\n            a, d = elements\n            if first:\n                first = False\n            else:\n                self.write(\", \")\n            self.dispatch(a)\n            if d:\n                self.write(\"=\")\n                self.dispatch(d)\n            if index == len(t.posonlyargs):\n                self.write(\", /\")\n        # varargs, or bare '*' if no varargs but keyword-only arguments present\n        if t.vararg or t.kwonlyargs:\n            if first:\n                first = False\n            else:\n                self.write(\", \")\n            self.write(\"*\")\n            if t.vararg:\n                self.write(t.vararg.arg)\n                if t.vararg.annotation:\n                    self.write(\": \")\n                    self.dispatch(t.vararg.annotation)\n        # keyword-only arguments\n        if t.kwonlyargs:\n            for a, d in zip(t.kwonlyargs, t.kw_defaults):\n                if first:\n                    first = False\n                else:\n                    self.write(\", \")\n                self.dispatch(a)\n                if d:\n                    self.write(\"=\")\n                    self.dispatch(d)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "60eb0b161d5e-13", "text": "if d:\n                    self.write(\"=\")\n                    self.dispatch(d)\n        # kwargs\n        if t.kwarg:\n            if first:\n                first = False\n            else:\n                self.write(\", \")\n            self.write(\"**\" + t.kwarg.arg)\n            if t.kwarg.annotation:\n                self.write(\": \")\n                self.dispatch(t.kwarg.annotation)\n    def _keyword(self, t):\n        if t.arg is None:\n            self.write(\"**\")\n        else:\n            self.write(t.arg)\n            self.write(\"=\")\n        self.dispatch(t.value)\n    def _Lambda(self, t):\n        self.write(\"(\")\n        self.write(\"lambda \")\n        self.dispatch(t.args)\n        self.write(\": \")\n        self.dispatch(t.body)\n        self.write(\")\")\n    def _alias(self, t):\n        self.write(t.name)\n        if t.asname:\n            self.write(\" as \" + t.asname)\n    def _withitem(self, t):\n        self.dispatch(t.context_expr)\n        if t.optional_vars:\n            self.write(\" as \")\n            self.dispatch(t.optional_vars)\n[docs]def roundtrip(filename, output=sys.stdout):\n    with open(filename, \"rb\") as pyfile:\n        encoding = tokenize.detect_encoding(pyfile.readline)[0]\n    with open(filename, \"r\", encoding=encoding) as pyfile:\n        source = pyfile.read()\n    tree = compile(source, filename, \"exec\", ast.PyCF_ONLY_AST)\n    Unparser(tree, output)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html"}
{"id": "0a6a64e18a99-0", "text": "Source code for langchain.tools.openapi.utils.api_models\n\"\"\"Pydantic models for parsing an OpenAPI spec.\"\"\"\nfrom __future__ import annotations\nimport logging\nfrom enum import Enum\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Dict,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    Type,\n    Union,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.openapi.utils.openapi_utils import HTTPVerb, OpenAPISpec\nlogger = logging.getLogger(__name__)\nPRIMITIVE_TYPES = {\n    \"integer\": int,\n    \"number\": float,\n    \"string\": str,\n    \"boolean\": bool,\n    \"array\": List,\n    \"object\": Dict,\n    \"null\": None,\n}\n# See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterIn\n# for more info.\n[docs]class APIPropertyLocation(Enum):\n    \"\"\"The location of the property.\"\"\"\n    QUERY = \"query\"\n    PATH = \"path\"\n    HEADER = \"header\"\n    COOKIE = \"cookie\"  # Not yet supported\n    @classmethod\n    def from_str(cls, location: str) -> \"APIPropertyLocation\":\n        \"\"\"Parse an APIPropertyLocation.\"\"\"\n        try:\n            return cls(location)\n        except ValueError:\n            raise ValueError(\n                f\"Invalid APIPropertyLocation. Valid values are {cls.__members__}\"\n            )\n_SUPPORTED_MEDIA_TYPES = (\"application/json\",)\nSUPPORTED_LOCATIONS = {\n    APIPropertyLocation.QUERY,\n    APIPropertyLocation.PATH,\n}\nINVALID_LOCATION_TEMPL = (\n    'Unsupported APIPropertyLocation \"{location}\"'\n    \" for parameter {name}. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html"}
{"id": "0a6a64e18a99-1", "text": "'Unsupported APIPropertyLocation \"{location}\"'\n    \" for parameter {name}. \"\n    + f\"Valid values are {[loc.value for loc in SUPPORTED_LOCATIONS]}\"\n)\nSCHEMA_TYPE = Union[str, Type, tuple, None, Enum]\n[docs]class APIPropertyBase(BaseModel):\n    \"\"\"Base model for an API property.\"\"\"\n    # The name of the parameter is required and is case-sensitive.\n    # If \"in\" is \"path\", the \"name\" field must correspond to a template expression\n    # within the path field in the Paths Object.\n    # If \"in\" is \"header\" and the \"name\" field is \"Accept\", \"Content-Type\",\n    # or \"Authorization\", the parameter definition is ignored.\n    # For all other cases, the \"name\" corresponds to the parameter\n    # name used by the \"in\" property.\n    name: str = Field(alias=\"name\")\n    \"\"\"The name of the property.\"\"\"\n    required: bool = Field(alias=\"required\")\n    \"\"\"Whether the property is required.\"\"\"\n    type: SCHEMA_TYPE = Field(alias=\"type\")\n    \"\"\"The type of the property.\n    \n    Either a primitive type, a component/parameter type,\n    or an array or 'object' (dict) of the above.\"\"\"\n    default: Optional[Any] = Field(alias=\"default\", default=None)\n    \"\"\"The default value of the property.\"\"\"\n    description: Optional[str] = Field(alias=\"description\", default=None)\n    \"\"\"The description of the property.\"\"\"\nif TYPE_CHECKING:\n    from openapi_pydantic import (\n        MediaType,\n        Parameter,\n        RequestBody,\n        Schema,\n    )\n[docs]class APIProperty(APIPropertyBase):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html"}
{"id": "0a6a64e18a99-2", "text": "Schema,\n    )\n[docs]class APIProperty(APIPropertyBase):\n    \"\"\"A model for a property in the query, path, header, or cookie params.\"\"\"\n    location: APIPropertyLocation = Field(alias=\"location\")\n    \"\"\"The path/how it's being passed to the endpoint.\"\"\"\n    @staticmethod\n    def _cast_schema_list_type(\n        schema: Schema,\n    ) -> Optional[Union[str, Tuple[str, ...]]]:\n        type_ = schema.type\n        if not isinstance(type_, list):\n            return type_\n        else:\n            return tuple(type_)\n    @staticmethod\n    def _get_schema_type_for_enum(parameter: Parameter, schema: Schema) -> Enum:\n        \"\"\"Get the schema type when the parameter is an enum.\"\"\"\n        param_name = f\"{parameter.name}Enum\"\n        return Enum(param_name, {str(v): v for v in schema.enum})\n    @staticmethod\n    def _get_schema_type_for_array(\n        schema: Schema,\n    ) -> Optional[Union[str, Tuple[str, ...]]]:\n        from openapi_pydantic import (\n            Reference,\n            Schema,\n        )\n        items = schema.items\n        if isinstance(items, Schema):\n            schema_type = APIProperty._cast_schema_list_type(items)\n        elif isinstance(items, Reference):\n            ref_name = items.ref.split(\"/\")[-1]\n            schema_type = ref_name  # TODO: Add ref definitions to make his valid\n        else:\n            raise ValueError(f\"Unsupported array items: {items}\")\n        if isinstance(schema_type, str):\n            # TODO: recurse\n            schema_type = (schema_type,)\n        return schema_type\n    @staticmethod\n    def _get_schema_type(parameter: Parameter, schema: Optional[Schema]) -> SCHEMA_TYPE:\n        if schema is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html"}
{"id": "0a6a64e18a99-3", "text": "if schema is None:\n            return None\n        schema_type: SCHEMA_TYPE = APIProperty._cast_schema_list_type(schema)\n        if schema_type == \"array\":\n            schema_type = APIProperty._get_schema_type_for_array(schema)\n        elif schema_type == \"object\":\n            # TODO: Resolve array and object types to components.\n            raise NotImplementedError(\"Objects not yet supported\")\n        elif schema_type in PRIMITIVE_TYPES:\n            if schema.enum:\n                schema_type = APIProperty._get_schema_type_for_enum(parameter, schema)\n            else:\n                # Directly use the primitive type\n                pass\n        else:\n            raise NotImplementedError(f\"Unsupported type: {schema_type}\")\n        return schema_type\n    @staticmethod\n    def _validate_location(location: APIPropertyLocation, name: str) -> None:\n        if location not in SUPPORTED_LOCATIONS:\n            raise NotImplementedError(\n                INVALID_LOCATION_TEMPL.format(location=location, name=name)\n            )\n    @staticmethod\n    def _validate_content(content: Optional[Dict[str, MediaType]]) -> None:\n        if content:\n            raise ValueError(\n                \"API Properties with media content not supported. \"\n                \"Media content only supported within APIRequestBodyProperty's\"\n            )\n    @staticmethod\n    def _get_schema(parameter: Parameter, spec: OpenAPISpec) -> Optional[Schema]:\n        from openapi_pydantic import (\n            Reference,\n            Schema,\n        )\n        schema = parameter.param_schema\n        if isinstance(schema, Reference):\n            schema = spec.get_referenced_schema(schema)\n        elif schema is None:\n            return None\n        elif not isinstance(schema, Schema):\n            raise ValueError(f\"Error dereferencing schema: {schema}\")\n        return schema\n[docs]    @staticmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html"}
{"id": "0a6a64e18a99-4", "text": "return schema\n[docs]    @staticmethod\n    def is_supported_location(location: str) -> bool:\n        \"\"\"Return whether the provided location is supported.\"\"\"\n        try:\n            return APIPropertyLocation.from_str(location) in SUPPORTED_LOCATIONS\n        except ValueError:\n            return False\n[docs]    @classmethod\n    def from_parameter(cls, parameter: Parameter, spec: OpenAPISpec) -> \"APIProperty\":\n        \"\"\"Instantiate from an OpenAPI Parameter.\"\"\"\n        location = APIPropertyLocation.from_str(parameter.param_in)\n        cls._validate_location(\n            location,\n            parameter.name,\n        )\n        cls._validate_content(parameter.content)\n        schema = cls._get_schema(parameter, spec)\n        schema_type = cls._get_schema_type(parameter, schema)\n        default_val = schema.default if schema is not None else None\n        return cls(\n            name=parameter.name,\n            location=location,\n            default=default_val,\n            description=parameter.description,\n            required=parameter.required,\n            type=schema_type,\n        )\n[docs]class APIRequestBodyProperty(APIPropertyBase):\n    \"\"\"A model for a request body property.\"\"\"\n    properties: List[\"APIRequestBodyProperty\"] = Field(alias=\"properties\")\n    \"\"\"The sub-properties of the property.\"\"\"\n    # This is useful for handling nested property cycles.\n    # We can define separate types in that case.\n    references_used: List[str] = Field(alias=\"references_used\")\n    \"\"\"The references used by the property.\"\"\"\n    @classmethod\n    def _process_object_schema(\n        cls, schema: Schema, spec: OpenAPISpec, references_used: List[str]\n    ) -> Tuple[Union[str, List[str], None], List[\"APIRequestBodyProperty\"]]:\n        from openapi_pydantic import (\n            Reference,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html"}
{"id": "0a6a64e18a99-5", "text": "from openapi_pydantic import (\n            Reference,\n        )\n        properties = []\n        required_props = schema.required or []\n        if schema.properties is None:\n            raise ValueError(\n                f\"No properties found when processing object schema: {schema}\"\n            )\n        for prop_name, prop_schema in schema.properties.items():\n            if isinstance(prop_schema, Reference):\n                ref_name = prop_schema.ref.split(\"/\")[-1]\n                if ref_name not in references_used:\n                    references_used.append(ref_name)\n                    prop_schema = spec.get_referenced_schema(prop_schema)\n                else:\n                    continue\n            properties.append(\n                cls.from_schema(\n                    schema=prop_schema,\n                    name=prop_name,\n                    required=prop_name in required_props,\n                    spec=spec,\n                    references_used=references_used,\n                )\n            )\n        return schema.type, properties\n    @classmethod\n    def _process_array_schema(\n        cls,\n        schema: Schema,\n        name: str,\n        spec: OpenAPISpec,\n        references_used: List[str],\n    ) -> str:\n        from openapi_pydantic import Reference, Schema\n        items = schema.items\n        if items is not None:\n            if isinstance(items, Reference):\n                ref_name = items.ref.split(\"/\")[-1]\n                if ref_name not in references_used:\n                    references_used.append(ref_name)\n                    items = spec.get_referenced_schema(items)\n                else:\n                    pass\n                return f\"Array<{ref_name}>\"\n            else:\n                pass\n            if isinstance(items, Schema):\n                array_type = cls.from_schema(\n                    schema=items,\n                    name=f\"{name}Item\",\n                    required=True,  # TODO: Add required\n                    spec=spec,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html"}
{"id": "0a6a64e18a99-6", "text": "required=True,  # TODO: Add required\n                    spec=spec,\n                    references_used=references_used,\n                )\n                return f\"Array<{array_type.type}>\"\n        return \"array\"\n[docs]    @classmethod\n    def from_schema(\n        cls,\n        schema: Schema,\n        name: str,\n        required: bool,\n        spec: OpenAPISpec,\n        references_used: Optional[List[str]] = None,\n    ) -> \"APIRequestBodyProperty\":\n        \"\"\"Recursively populate from an OpenAPI Schema.\"\"\"\n        if references_used is None:\n            references_used = []\n        schema_type = schema.type\n        properties: List[APIRequestBodyProperty] = []\n        if schema_type == \"object\" and schema.properties:\n            schema_type, properties = cls._process_object_schema(\n                schema, spec, references_used\n            )\n        elif schema_type == \"array\":\n            schema_type = cls._process_array_schema(schema, name, spec, references_used)\n        elif schema_type in PRIMITIVE_TYPES:\n            # Use the primitive type directly\n            pass\n        elif schema_type is None:\n            # No typing specified/parsed. WIll map to 'any'\n            pass\n        else:\n            raise ValueError(f\"Unsupported type: {schema_type}\")\n        return cls(\n            name=name,\n            required=required,\n            type=schema_type,\n            default=schema.default,\n            description=schema.description,\n            properties=properties,\n            references_used=references_used,\n        )\n# class APIRequestBodyProperty(APIPropertyBase):\n[docs]class APIRequestBody(BaseModel):\n    \"\"\"A model for a request body.\"\"\"\n    description: Optional[str] = Field(alias=\"description\")\n    \"\"\"The description of the request body.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html"}
{"id": "0a6a64e18a99-7", "text": "\"\"\"The description of the request body.\"\"\"\n    properties: List[APIRequestBodyProperty] = Field(alias=\"properties\")\n    # E.g., application/json - we only support JSON at the moment.\n    media_type: str = Field(alias=\"media_type\")\n    \"\"\"The media type of the request body.\"\"\"\n    @classmethod\n    def _process_supported_media_type(\n        cls,\n        media_type_obj: MediaType,\n        spec: OpenAPISpec,\n    ) -> List[APIRequestBodyProperty]:\n        \"\"\"Process the media type of the request body.\"\"\"\n        from openapi_pydantic import Reference\n        references_used = []\n        schema = media_type_obj.media_type_schema\n        if isinstance(schema, Reference):\n            references_used.append(schema.ref.split(\"/\")[-1])\n            schema = spec.get_referenced_schema(schema)\n        if schema is None:\n            raise ValueError(\n                f\"Could not resolve schema for media type: {media_type_obj}\"\n            )\n        api_request_body_properties = []\n        required_properties = schema.required or []\n        if schema.type == \"object\" and schema.properties:\n            for prop_name, prop_schema in schema.properties.items():\n                if isinstance(prop_schema, Reference):\n                    prop_schema = spec.get_referenced_schema(prop_schema)\n                api_request_body_properties.append(\n                    APIRequestBodyProperty.from_schema(\n                        schema=prop_schema,\n                        name=prop_name,\n                        required=prop_name in required_properties,\n                        spec=spec,\n                    )\n                )\n        else:\n            api_request_body_properties.append(\n                APIRequestBodyProperty(\n                    name=\"body\",\n                    required=True,\n                    type=schema.type,\n                    default=schema.default,\n                    description=schema.description,\n                    properties=[],\n                    references_used=references_used,\n                )\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html"}
{"id": "0a6a64e18a99-8", "text": "properties=[],\n                    references_used=references_used,\n                )\n            )\n        return api_request_body_properties\n[docs]    @classmethod\n    def from_request_body(\n        cls, request_body: RequestBody, spec: OpenAPISpec\n    ) -> \"APIRequestBody\":\n        \"\"\"Instantiate from an OpenAPI RequestBody.\"\"\"\n        properties = []\n        for media_type, media_type_obj in request_body.content.items():\n            if media_type not in _SUPPORTED_MEDIA_TYPES:\n                continue\n            api_request_body_properties = cls._process_supported_media_type(\n                media_type_obj,\n                spec,\n            )\n            properties.extend(api_request_body_properties)\n        return cls(\n            description=request_body.description,\n            properties=properties,\n            media_type=media_type,\n        )\n# class APIRequestBodyProperty(APIPropertyBase):\n#     class APIRequestBody(BaseModel):\n[docs]class APIOperation(BaseModel):\n    \"\"\"A model for a single API operation.\"\"\"\n    operation_id: str = Field(alias=\"operation_id\")\n    \"\"\"The unique identifier of the operation.\"\"\"\n    description: Optional[str] = Field(alias=\"description\")\n    \"\"\"The description of the operation.\"\"\"\n    base_url: str = Field(alias=\"base_url\")\n    \"\"\"The base URL of the operation.\"\"\"\n    path: str = Field(alias=\"path\")\n    \"\"\"The path of the operation.\"\"\"\n    method: HTTPVerb = Field(alias=\"method\")\n    \"\"\"The HTTP method of the operation.\"\"\"\n    properties: Sequence[APIProperty] = Field(alias=\"properties\")\n    # TODO: Add parse in used components to be able to specify what type of\n    # referenced object it is.\n    # \"\"\"The properties of the operation.\"\"\"\n    # components: Dict[str, BaseModel] = Field(alias=\"components\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html"}
{"id": "0a6a64e18a99-9", "text": "# components: Dict[str, BaseModel] = Field(alias=\"components\")\n    request_body: Optional[APIRequestBody] = Field(alias=\"request_body\")\n    \"\"\"The request body of the operation.\"\"\"\n    @staticmethod\n    def _get_properties_from_parameters(\n        parameters: List[Parameter], spec: OpenAPISpec\n    ) -> List[APIProperty]:\n        \"\"\"Get the properties of the operation.\"\"\"\n        properties = []\n        for param in parameters:\n            if APIProperty.is_supported_location(param.param_in):\n                properties.append(APIProperty.from_parameter(param, spec))\n            elif param.required:\n                raise ValueError(\n                    INVALID_LOCATION_TEMPL.format(\n                        location=param.param_in, name=param.name\n                    )\n                )\n            else:\n                logger.warning(\n                    INVALID_LOCATION_TEMPL.format(\n                        location=param.param_in, name=param.name\n                    )\n                    + \" Ignoring optional parameter\"\n                )\n                pass\n        return properties\n[docs]    @classmethod\n    def from_openapi_url(\n        cls,\n        spec_url: str,\n        path: str,\n        method: str,\n    ) -> \"APIOperation\":\n        \"\"\"Create an APIOperation from an OpenAPI URL.\"\"\"\n        spec = OpenAPISpec.from_url(spec_url)\n        return cls.from_openapi_spec(spec, path, method)\n[docs]    @classmethod\n    def from_openapi_spec(\n        cls,\n        spec: OpenAPISpec,\n        path: str,\n        method: str,\n    ) -> \"APIOperation\":\n        \"\"\"Create an APIOperation from an OpenAPI spec.\"\"\"\n        operation = spec.get_operation(path, method)\n        parameters = spec.get_parameters_for_operation(operation)\n        properties = cls._get_properties_from_parameters(parameters, spec)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html"}
{"id": "0a6a64e18a99-10", "text": "properties = cls._get_properties_from_parameters(parameters, spec)\n        operation_id = OpenAPISpec.get_cleaned_operation_id(operation, path, method)\n        request_body = spec.get_request_body_for_operation(operation)\n        api_request_body = (\n            APIRequestBody.from_request_body(request_body, spec)\n            if request_body is not None\n            else None\n        )\n        description = operation.description or operation.summary\n        if not description and spec.paths is not None:\n            description = spec.paths[path].description or spec.paths[path].summary\n        return cls(\n            operation_id=operation_id,\n            description=description or \"\",\n            base_url=spec.base_url,\n            path=path,\n            method=method,\n            properties=properties,\n            request_body=api_request_body,\n        )\n[docs]    @staticmethod\n    def ts_type_from_python(type_: SCHEMA_TYPE) -> str:\n        if type_ is None:\n            # TODO: Handle Nones better. These often result when\n            # parsing specs that are < v3\n            return \"any\"\n        elif isinstance(type_, str):\n            return {\n                \"str\": \"string\",\n                \"integer\": \"number\",\n                \"float\": \"number\",\n                \"date-time\": \"string\",\n            }.get(type_, type_)\n        elif isinstance(type_, tuple):\n            return f\"Array<{APIOperation.ts_type_from_python(type_[0])}>\"\n        elif isinstance(type_, type) and issubclass(type_, Enum):\n            return \" | \".join([f\"'{e.value}'\" for e in type_])\n        else:\n            return str(type_)\n    def _format_nested_properties(\n        self, properties: List[APIRequestBodyProperty], indent: int = 2\n    ) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html"}
{"id": "0a6a64e18a99-11", "text": ") -> str:\n        \"\"\"Format nested properties.\"\"\"\n        formatted_props = []\n        for prop in properties:\n            prop_name = prop.name\n            prop_type = self.ts_type_from_python(prop.type)\n            prop_required = \"\" if prop.required else \"?\"\n            prop_desc = f\"/* {prop.description} */\" if prop.description else \"\"\n            if prop.properties:\n                nested_props = self._format_nested_properties(\n                    prop.properties, indent + 2\n                )\n                prop_type = f\"{{\\n{nested_props}\\n{' ' * indent}}}\"\n            formatted_props.append(\n                f\"{prop_desc}\\n{' ' * indent}{prop_name}\"\n                f\"{prop_required}: {prop_type},\"\n            )\n        return \"\\n\".join(formatted_props)\n[docs]    def to_typescript(self) -> str:\n        \"\"\"Get typescript string representation of the operation.\"\"\"\n        operation_name = self.operation_id\n        params = []\n        if self.request_body:\n            formatted_request_body_props = self._format_nested_properties(\n                self.request_body.properties\n            )\n            params.append(formatted_request_body_props)\n        for prop in self.properties:\n            prop_name = prop.name\n            prop_type = self.ts_type_from_python(prop.type)\n            prop_required = \"\" if prop.required else \"?\"\n            prop_desc = f\"/* {prop.description} */\" if prop.description else \"\"\n            params.append(f\"{prop_desc}\\n\\t\\t{prop_name}{prop_required}: {prop_type},\")\n        formatted_params = \"\\n\".join(params).strip()\n        description_str = f\"/* {self.description} */\" if self.description else \"\"\n        typescript_definition = f\"\"\"\n{description_str}\ntype {operation_name} = (_: {{\n{formatted_params}\n}}) => any;", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html"}
{"id": "0a6a64e18a99-12", "text": "{formatted_params}\n}}) => any;\n\"\"\"\n        return typescript_definition.strip()\n    @property\n    def query_params(self) -> List[str]:\n        return [\n            property.name\n            for property in self.properties\n            if property.location == APIPropertyLocation.QUERY\n        ]\n    @property\n    def path_params(self) -> List[str]:\n        return [\n            property.name\n            for property in self.properties\n            if property.location == APIPropertyLocation.PATH\n        ]\n    @property\n    def body_params(self) -> List[str]:\n        if self.request_body is None:\n            return []\n        return [prop.name for prop in self.request_body.properties]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html"}
{"id": "bba385ce080c-0", "text": "Source code for langchain.tools.powerbi.tool\n\"\"\"Tools for interacting with a Power BI dataset.\"\"\"\nimport logging\nfrom time import perf_counter\nfrom typing import Any, Dict, Optional, Tuple\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chat_models.openai import _import_tiktoken\nfrom langchain.pydantic_v1 import Field, validator\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.powerbi.prompt import (\n    BAD_REQUEST_RESPONSE,\n    DEFAULT_FEWSHOT_EXAMPLES,\n    RETRY_RESPONSE,\n)\nfrom langchain.utilities.powerbi import PowerBIDataset, json_to_md\nlogger = logging.getLogger(__name__)\n[docs]class QueryPowerBITool(BaseTool):\n    \"\"\"Tool for querying a Power BI Dataset.\"\"\"\n    name: str = \"query_powerbi\"\n    description: str = \"\"\"\n    Input to this tool is a detailed question about the dataset, output is a result from the dataset. It will try to answer the question using the dataset, and if it cannot, it will ask for clarification.\n    Example Input: \"How many rows are in table1?\"\n    \"\"\"  # noqa: E501\n    llm_chain: LLMChain\n    powerbi: PowerBIDataset = Field(exclude=True)\n    examples: Optional[str] = DEFAULT_FEWSHOT_EXAMPLES\n    session_cache: Dict[str, Any] = Field(default_factory=dict, exclude=True)\n    max_iterations: int = 5\n    output_token_limit: int = 4000\n    tiktoken_model_name: Optional[str] = None  # \"cl100k_base\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html"}
{"id": "bba385ce080c-1", "text": "class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @validator(\"llm_chain\")\n    def validate_llm_chain_input_variables(  # pylint: disable=E0213\n        cls, llm_chain: LLMChain\n    ) -> LLMChain:\n        \"\"\"Make sure the LLM chain has the correct input variables.\"\"\"\n        for var in llm_chain.prompt.input_variables:\n            if var not in [\"tool_input\", \"tables\", \"schemas\", \"examples\"]:\n                raise ValueError(\n                    \"LLM chain for QueryPowerBITool must have input variables ['tool_input', 'tables', 'schemas', 'examples'], found %s\",  # noqa: C0301 E501 # pylint: disable=C0301\n                    llm_chain.prompt.input_variables,\n                )\n        return llm_chain\n    def _check_cache(self, tool_input: str) -> Optional[str]:\n        \"\"\"Check if the input is present in the cache.\n        If the value is a bad request, overwrite with the escalated version,\n        if not present return None.\"\"\"\n        if tool_input not in self.session_cache:\n            return None\n        return self.session_cache[tool_input]\n    def _run(\n        self,\n        tool_input: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Execute the query, return the results or an error message.\"\"\"\n        if cache := self._check_cache(tool_input):\n            logger.debug(\"Found cached result for %s: %s\", tool_input, cache)\n            return cache\n        try:\n            logger.info(\"Running PBI Query Tool with input: %s\", tool_input)\n            query = self.llm_chain.predict(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html"}
{"id": "bba385ce080c-2", "text": "query = self.llm_chain.predict(\n                tool_input=tool_input,\n                tables=self.powerbi.get_table_names(),\n                schemas=self.powerbi.get_schemas(),\n                examples=self.examples,\n                callbacks=run_manager.get_child() if run_manager else None,\n            )\n        except Exception as exc:  # pylint: disable=broad-except\n            self.session_cache[tool_input] = f\"Error on call to LLM: {exc}\"\n            return self.session_cache[tool_input]\n        if query == \"I cannot answer this\":\n            self.session_cache[tool_input] = query\n            return self.session_cache[tool_input]\n        logger.info(\"PBI Query:\\n%s\", query)\n        start_time = perf_counter()\n        pbi_result = self.powerbi.run(command=query)\n        end_time = perf_counter()\n        logger.debug(\"PBI Result: %s\", pbi_result)\n        logger.debug(f\"PBI Query duration: {end_time - start_time:0.6f}\")\n        result, error = self._parse_output(pbi_result)\n        if error is not None and \"TokenExpired\" in error:\n            self.session_cache[\n                tool_input\n            ] = \"Authentication token expired or invalid, please try reauthenticate.\"\n            return self.session_cache[tool_input]\n        iterations = kwargs.get(\"iterations\", 0)\n        if error and iterations < self.max_iterations:\n            return self._run(\n                tool_input=RETRY_RESPONSE.format(\n                    tool_input=tool_input, query=query, error=error\n                ),\n                run_manager=run_manager,\n                iterations=iterations + 1,\n            )\n        self.session_cache[tool_input] = (\n            result if result else BAD_REQUEST_RESPONSE.format(error=error)\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html"}
{"id": "bba385ce080c-3", "text": "result if result else BAD_REQUEST_RESPONSE.format(error=error)\n        )\n        return self.session_cache[tool_input]\n    async def _arun(\n        self,\n        tool_input: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Execute the query, return the results or an error message.\"\"\"\n        if cache := self._check_cache(tool_input):\n            logger.debug(\"Found cached result for %s: %s\", tool_input, cache)\n            return f\"{cache}, from cache, you have already asked this question.\"\n        try:\n            logger.info(\"Running PBI Query Tool with input: %s\", tool_input)\n            query = await self.llm_chain.apredict(\n                tool_input=tool_input,\n                tables=self.powerbi.get_table_names(),\n                schemas=self.powerbi.get_schemas(),\n                examples=self.examples,\n                callbacks=run_manager.get_child() if run_manager else None,\n            )\n        except Exception as exc:  # pylint: disable=broad-except\n            self.session_cache[tool_input] = f\"Error on call to LLM: {exc}\"\n            return self.session_cache[tool_input]\n        if query == \"I cannot answer this\":\n            self.session_cache[tool_input] = query\n            return self.session_cache[tool_input]\n        logger.info(\"PBI Query: %s\", query)\n        start_time = perf_counter()\n        pbi_result = await self.powerbi.arun(command=query)\n        end_time = perf_counter()\n        logger.debug(\"PBI Result: %s\", pbi_result)\n        logger.debug(f\"PBI Query duration: {end_time - start_time:0.6f}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html"}
{"id": "bba385ce080c-4", "text": "result, error = self._parse_output(pbi_result)\n        if error is not None and (\"TokenExpired\" in error or \"TokenError\" in error):\n            self.session_cache[\n                tool_input\n            ] = \"Authentication token expired or invalid, please try to reauthenticate or check the scope of the credential.\"  # noqa: E501\n            return self.session_cache[tool_input]\n        iterations = kwargs.get(\"iterations\", 0)\n        if error and iterations < self.max_iterations:\n            return await self._arun(\n                tool_input=RETRY_RESPONSE.format(\n                    tool_input=tool_input, query=query, error=error\n                ),\n                run_manager=run_manager,\n                iterations=iterations + 1,\n            )\n        self.session_cache[tool_input] = (\n            result if result else BAD_REQUEST_RESPONSE.format(error=error)\n        )\n        return self.session_cache[tool_input]\n    def _parse_output(\n        self, pbi_result: Dict[str, Any]\n    ) -> Tuple[Optional[str], Optional[Any]]:\n        \"\"\"Parse the output of the query to a markdown table.\"\"\"\n        if \"results\" in pbi_result:\n            rows = pbi_result[\"results\"][0][\"tables\"][0][\"rows\"]\n            if len(rows) == 0:\n                logger.info(\"0 records in result, query was valid.\")\n                return (\n                    None,\n                    \"0 rows returned, this might be correct, but please validate if all filter values were correct?\",  # noqa: E501\n                )\n            result = json_to_md(rows)\n            too_long, length = self._result_too_large(result)\n            if too_long:\n                return (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html"}
{"id": "bba385ce080c-5", "text": "if too_long:\n                return (\n                    f\"Result too large, please try to be more specific or use the `TOPN` function. The result is {length} tokens long, the limit is {self.output_token_limit} tokens.\",  # noqa: E501\n                    None,\n                )\n            return result, None\n        if \"error\" in pbi_result:\n            if (\n                \"pbi.error\" in pbi_result[\"error\"]\n                and \"details\" in pbi_result[\"error\"][\"pbi.error\"]\n            ):\n                return None, pbi_result[\"error\"][\"pbi.error\"][\"details\"][0][\"detail\"]\n            return None, pbi_result[\"error\"]\n        return None, pbi_result\n    def _result_too_large(self, result: str) -> Tuple[bool, int]:\n        \"\"\"Tokenize the output of the query.\"\"\"\n        if self.tiktoken_model_name:\n            tiktoken_ = _import_tiktoken()\n            encoding = tiktoken_.encoding_for_model(self.tiktoken_model_name)\n            length = len(encoding.encode(result))\n            logger.info(\"Result length: %s\", length)\n            return length > self.output_token_limit, length\n        return False, 0\n[docs]class InfoPowerBITool(BaseTool):\n    \"\"\"Tool for getting metadata about a PowerBI Dataset.\"\"\"\n    name: str = \"schema_powerbi\"\n    description: str = \"\"\"\n    Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.\n    Be sure that the tables actually exist by calling list_tables_powerbi first!\n    Example Input: \"table1, table2, table3\"\n    \"\"\"  # noqa: E501\n    powerbi: PowerBIDataset = Field(exclude=True)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html"}
{"id": "bba385ce080c-6", "text": "powerbi: PowerBIDataset = Field(exclude=True)\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    def _run(\n        self,\n        tool_input: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Get the schema for tables in a comma-separated list.\"\"\"\n        return self.powerbi.get_table_info(tool_input.split(\", \"))\n    async def _arun(\n        self,\n        tool_input: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        return await self.powerbi.aget_table_info(tool_input.split(\", \"))\n[docs]class ListPowerBITool(BaseTool):\n    \"\"\"Tool for getting tables names.\"\"\"\n    name: str = \"list_tables_powerbi\"\n    description: str = \"Input is an empty string, output is a comma separated list of tables in the database.\"  # noqa: E501 # pylint: disable=C0301\n    powerbi: PowerBIDataset = Field(exclude=True)\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    def _run(\n        self,\n        tool_input: Optional[str] = None,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Get the names of the tables.\"\"\"\n        return \", \".join(self.powerbi.get_table_names())\n    async def _arun(\n        self,\n        tool_input: Optional[str] = None,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Get the names of the tables.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html"}
{"id": "bba385ce080c-7", "text": ") -> str:\n        \"\"\"Get the names of the tables.\"\"\"\n        return \", \".join(self.powerbi.get_table_names())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html"}
{"id": "ced2d075af1d-0", "text": "Source code for langchain.tools.spark_sql.tool\n# flake8: noqa\n\"\"\"Tools for interacting with Spark SQL.\"\"\"\nfrom typing import Any, Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel, Field, root_validator\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.utilities.spark_sql import SparkSQL\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.spark_sql.prompt import QUERY_CHECKER\n[docs]class BaseSparkSQLTool(BaseModel):\n    \"\"\"Base tool for interacting with Spark SQL.\"\"\"\n    db: SparkSQL = Field(exclude=True)\n    class Config(BaseTool.Config):\n        pass\n[docs]class QuerySparkSQLTool(BaseSparkSQLTool, BaseTool):\n    \"\"\"Tool for querying a Spark SQL.\"\"\"\n    name: str = \"query_sql_db\"\n    description: str = \"\"\"\n    Input to this tool is a detailed and correct SQL query, output is a result from the Spark SQL.\n    If the query is not correct, an error message will be returned.\n    If an error is returned, rewrite the query, check the query, and try again.\n    \"\"\"\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Execute the query, return the results or an error message.\"\"\"\n        return self.db.run_no_throw(query)\n[docs]class InfoSparkSQLTool(BaseSparkSQLTool, BaseTool):\n    \"\"\"Tool for getting metadata about a Spark SQL.\"\"\"\n    name: str = \"schema_sql_db\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/spark_sql/tool.html"}
{"id": "ced2d075af1d-1", "text": "name: str = \"schema_sql_db\"\n    description: str = \"\"\"\n    Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.\n    Be sure that the tables actually exist by calling list_tables_sql_db first!\n    Example Input: \"table1, table2, table3\"\n    \"\"\"\n    def _run(\n        self,\n        table_names: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Get the schema for tables in a comma-separated list.\"\"\"\n        return self.db.get_table_info_no_throw(table_names.split(\", \"))\n[docs]class ListSparkSQLTool(BaseSparkSQLTool, BaseTool):\n    \"\"\"Tool for getting tables names.\"\"\"\n    name: str = \"list_tables_sql_db\"\n    description: str = \"Input is an empty string, output is a comma separated list of tables in the Spark SQL.\"\n    def _run(\n        self,\n        tool_input: str = \"\",\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Get the schema for a specific table.\"\"\"\n        return \", \".join(self.db.get_usable_table_names())\n[docs]class QueryCheckerTool(BaseSparkSQLTool, BaseTool):\n    \"\"\"Use an LLM to check if a query is correct.\n    Adapted from https://www.patterns.app/blog/2023/01/18/crunchbot-sql-analyst-gpt/\"\"\"\n    template: str = QUERY_CHECKER\n    llm: BaseLanguageModel\n    llm_chain: LLMChain = Field(init=False)\n    name: str = \"query_checker_sql_db\"\n    description: str = \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/spark_sql/tool.html"}
{"id": "ced2d075af1d-2", "text": "name: str = \"query_checker_sql_db\"\n    description: str = \"\"\"\n    Use this tool to double check if your query is correct before executing it.\n    Always use this tool before executing a query with query_sql_db!\n    \"\"\"\n    @root_validator(pre=True)\n    def initialize_llm_chain(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        if \"llm_chain\" not in values:\n            values[\"llm_chain\"] = LLMChain(\n                llm=values.get(\"llm\"),\n                prompt=PromptTemplate(\n                    template=QUERY_CHECKER, input_variables=[\"query\"]\n                ),\n            )\n        if values[\"llm_chain\"].prompt.input_variables != [\"query\"]:\n            raise ValueError(\n                \"LLM chain for QueryCheckerTool need to use ['query'] as input_variables \"\n                \"for the embedded prompt\"\n            )\n        return values\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the LLM to check the query.\"\"\"\n        return self.llm_chain.predict(\n            query=query, callbacks=run_manager.get_child() if run_manager else None\n        )\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        return await self.llm_chain.apredict(\n            query=query, callbacks=run_manager.get_child() if run_manager else None\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/spark_sql/tool.html"}
{"id": "5051509e99d9-0", "text": "Source code for langchain.tools.metaphor_search.tool\n\"\"\"Tool for the Metaphor search API.\"\"\"\nfrom typing import Dict, List, Optional, Union\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.metaphor_search import MetaphorSearchAPIWrapper\n[docs]class MetaphorSearchResults(BaseTool):\n    \"\"\"Tool that queries the Metaphor Search API and gets back json.\"\"\"\n    name: str = \"metaphor_search_results_json\"\n    description: str = (\n        \"A wrapper around Metaphor Search. \"\n        \"Input should be a Metaphor-optimized query. \"\n        \"Output is a JSON array of the query results\"\n    )\n    api_wrapper: MetaphorSearchAPIWrapper\n    def _run(\n        self,\n        query: str,\n        num_results: int,\n        include_domains: Optional[List[str]] = None,\n        exclude_domains: Optional[List[str]] = None,\n        start_crawl_date: Optional[str] = None,\n        end_crawl_date: Optional[str] = None,\n        start_published_date: Optional[str] = None,\n        end_published_date: Optional[str] = None,\n        use_autoprompt: Optional[bool] = None,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> Union[List[Dict], str]:\n        \"\"\"Use the tool.\"\"\"\n        try:\n            return self.api_wrapper.results(\n                query,\n                num_results,\n                include_domains,\n                exclude_domains,\n                start_crawl_date,\n                end_crawl_date,\n                start_published_date,\n                end_published_date,\n                use_autoprompt,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/metaphor_search/tool.html"}
{"id": "5051509e99d9-1", "text": "start_published_date,\n                end_published_date,\n                use_autoprompt,\n            )\n        except Exception as e:\n            return repr(e)\n    async def _arun(\n        self,\n        query: str,\n        num_results: int,\n        include_domains: Optional[List[str]] = None,\n        exclude_domains: Optional[List[str]] = None,\n        start_crawl_date: Optional[str] = None,\n        end_crawl_date: Optional[str] = None,\n        start_published_date: Optional[str] = None,\n        end_published_date: Optional[str] = None,\n        use_autoprompt: Optional[bool] = None,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> Union[List[Dict], str]:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        try:\n            return await self.api_wrapper.results_async(\n                query,\n                num_results,\n                include_domains,\n                exclude_domains,\n                start_crawl_date,\n                end_crawl_date,\n                start_published_date,\n                end_published_date,\n                use_autoprompt,\n            )\n        except Exception as e:\n            return repr(e)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/metaphor_search/tool.html"}
{"id": "98958a40c4c9-0", "text": "Source code for langchain.tools.interaction.tool\n\"\"\"Tools for interacting with the user.\"\"\"\nimport warnings\nfrom typing import Any\nfrom langchain.tools.human.tool import HumanInputRun\n[docs]def StdInInquireTool(*args: Any, **kwargs: Any) -> HumanInputRun:\n    \"\"\"Tool for asking the user for input.\"\"\"\n    warnings.warn(\n        \"StdInInquireTool will be deprecated in the future. \"\n        \"Please use HumanInputRun instead.\",\n        DeprecationWarning,\n    )\n    return HumanInputRun(*args, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/interaction/tool.html"}
{"id": "771c9596001f-0", "text": "Source code for langchain.tools.jira.tool\n\"\"\"\nThis tool allows agents to interact with the atlassian-python-api library\nand operate on a Jira instance. For more information on the\natlassian-python-api library, see https://atlassian-python-api.readthedocs.io/jira.html\nTo use this tool, you must first set as environment variables:\n    JIRA_API_TOKEN\n    JIRA_USERNAME\n    JIRA_INSTANCE_URL\nBelow is a sample script that uses the Jira tool:\n```python\nfrom langchain.agents import AgentType\nfrom langchain.agents import initialize_agent\nfrom langchain.agents.agent_toolkits.jira.toolkit import JiraToolkit\nfrom langchain.llms import OpenAI\nfrom langchain.utilities.jira import JiraAPIWrapper\nllm = OpenAI(temperature=0)\njira = JiraAPIWrapper()\ntoolkit = JiraToolkit.from_jira_api_wrapper(jira)\nagent = initialize_agent(\n    toolkit.get_tools(),\n    llm,\n    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n    verbose=True\n)\n```\n\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.jira import JiraAPIWrapper\n[docs]class JiraAction(BaseTool):\n    \"\"\"Tool that queries the Atlassian Jira API.\"\"\"\n    api_wrapper: JiraAPIWrapper = Field(default_factory=JiraAPIWrapper)\n    mode: str\n    name: str = \"\"\n    description: str = \"\"\n    def _run(\n        self,\n        instructions: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/jira/tool.html"}
{"id": "771c9596001f-1", "text": ") -> str:\n        \"\"\"Use the Atlassian Jira API to run an operation.\"\"\"\n        return self.api_wrapper.run(self.mode, instructions)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/jira/tool.html"}
{"id": "ebe0138f922e-0", "text": "Source code for langchain.tools.google_places.tool\n\"\"\"Tool for the Google search API.\"\"\"\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.google_places_api import GooglePlacesAPIWrapper\n[docs]class GooglePlacesSchema(BaseModel):\n    \"\"\"Input for GooglePlacesTool.\"\"\"\n    query: str = Field(..., description=\"Query for google maps\")\n[docs]class GooglePlacesTool(BaseTool):\n    \"\"\"Tool that queries the Google places API.\"\"\"\n    name: str = \"google_places\"\n    description: str = (\n        \"A wrapper around Google Places. \"\n        \"Useful for when you need to validate or \"\n        \"discover addressed from ambiguous text. \"\n        \"Input should be a search query.\"\n    )\n    api_wrapper: GooglePlacesAPIWrapper = Field(default_factory=GooglePlacesAPIWrapper)\n    args_schema: Type[BaseModel] = GooglePlacesSchema\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return self.api_wrapper.run(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/google_places/tool.html"}
{"id": "fbd1a4195c09-0", "text": "Source code for langchain.tools.playwright.extract_hyperlinks\nfrom __future__ import annotations\nimport json\nfrom typing import TYPE_CHECKING, Any, Optional, Type\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field, root_validator\nfrom langchain.tools.playwright.base import BaseBrowserTool\nfrom langchain.tools.playwright.utils import aget_current_page, get_current_page\nif TYPE_CHECKING:\n    pass\n[docs]class ExtractHyperlinksToolInput(BaseModel):\n    \"\"\"Input for ExtractHyperlinksTool.\"\"\"\n    absolute_urls: bool = Field(\n        default=False,\n        description=\"Return absolute URLs instead of relative URLs\",\n    )\n[docs]class ExtractHyperlinksTool(BaseBrowserTool):\n    \"\"\"Extract all hyperlinks on the page.\"\"\"\n    name: str = \"extract_hyperlinks\"\n    description: str = \"Extract all hyperlinks on the current webpage\"\n    args_schema: Type[BaseModel] = ExtractHyperlinksToolInput\n    @root_validator\n    def check_bs_import(cls, values: dict) -> dict:\n        \"\"\"Check that the arguments are valid.\"\"\"\n        try:\n            from bs4 import BeautifulSoup  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"The 'beautifulsoup4' package is required to use this tool.\"\n                \" Please install it with 'pip install beautifulsoup4'.\"\n            )\n        return values\n[docs]    @staticmethod\n    def scrape_page(page: Any, html_content: str, absolute_urls: bool) -> str:\n        from urllib.parse import urljoin\n        from bs4 import BeautifulSoup\n        # Parse the HTML content with BeautifulSoup\n        soup = BeautifulSoup(html_content, \"lxml\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html"}
{"id": "fbd1a4195c09-1", "text": "soup = BeautifulSoup(html_content, \"lxml\")\n        # Find all the anchor elements and extract their href attributes\n        anchors = soup.find_all(\"a\")\n        if absolute_urls:\n            base_url = page.url\n            links = [urljoin(base_url, anchor.get(\"href\", \"\")) for anchor in anchors]\n        else:\n            links = [anchor.get(\"href\", \"\") for anchor in anchors]\n        # Return the list of links as a JSON string\n        return json.dumps(links)\n    def _run(\n        self,\n        absolute_urls: bool = False,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        if self.sync_browser is None:\n            raise ValueError(f\"Synchronous browser not provided to {self.name}\")\n        page = get_current_page(self.sync_browser)\n        html_content = page.content()\n        return self.scrape_page(page, html_content, absolute_urls)\n    async def _arun(\n        self,\n        absolute_urls: bool = False,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        if self.async_browser is None:\n            raise ValueError(f\"Asynchronous browser not provided to {self.name}\")\n        page = await aget_current_page(self.async_browser)\n        html_content = await page.content()\n        return self.scrape_page(page, html_content, absolute_urls)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html"}
{"id": "67dab042ea93-0", "text": "Source code for langchain.tools.playwright.navigate\nfrom __future__ import annotations\nfrom typing import Optional, Type\nfrom urllib.parse import urlparse\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field, validator\nfrom langchain.tools.playwright.base import BaseBrowserTool\nfrom langchain.tools.playwright.utils import (\n    aget_current_page,\n    get_current_page,\n)\n[docs]class NavigateToolInput(BaseModel):\n    \"\"\"Input for NavigateToolInput.\"\"\"\n    url: str = Field(..., description=\"url to navigate to\")\n    @validator(\"url\")\n    def validate_url_scheme(cls, url: str) -> str:\n        \"\"\"Check that the URL scheme is valid.\"\"\"\n        parsed_url = urlparse(url)\n        if parsed_url.scheme not in (\"http\", \"https\"):\n            raise ValueError(\"URL scheme must be 'http' or 'https'\")\n        return url\n[docs]class NavigateTool(BaseBrowserTool):\n    \"\"\"Tool for navigating a browser to a URL.\n    **Security Note**: This tool provides code to control web-browser navigation.\n        This tool can navigate to any URL, including internal network URLs, and\n        URLs exposed on the server itself.\n        However, if exposing this tool to end-users, consider limiting network\n        access to the server that hosts the agent.\n        By default, the URL scheme has been limited to 'http' and 'https' to\n        prevent navigation to local file system URLs (or other schemes).\n        If access to the local file system is required, consider creating a custom\n        tool or providing a custom args_schema that allows the desired URL schemes.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html"}
{"id": "67dab042ea93-1", "text": "See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    name: str = \"navigate_browser\"\n    description: str = \"Navigate a browser to the specified URL\"\n    args_schema: Type[BaseModel] = NavigateToolInput\n    def _run(\n        self,\n        url: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        if self.sync_browser is None:\n            raise ValueError(f\"Synchronous browser not provided to {self.name}\")\n        page = get_current_page(self.sync_browser)\n        response = page.goto(url)\n        status = response.status if response else \"unknown\"\n        return f\"Navigating to {url} returned status code {status}\"\n    async def _arun(\n        self,\n        url: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        if self.async_browser is None:\n            raise ValueError(f\"Asynchronous browser not provided to {self.name}\")\n        page = await aget_current_page(self.async_browser)\n        response = await page.goto(url)\n        status = response.status if response else \"unknown\"\n        return f\"Navigating to {url} returned status code {status}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html"}
{"id": "63d9df40bdf5-0", "text": "Source code for langchain.tools.playwright.base\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Optional, Tuple, Type\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.tools.base import BaseTool\nif TYPE_CHECKING:\n    from playwright.async_api import Browser as AsyncBrowser\n    from playwright.sync_api import Browser as SyncBrowser\nelse:\n    try:\n        # We do this so pydantic can resolve the types when instantiating\n        from playwright.async_api import Browser as AsyncBrowser\n        from playwright.sync_api import Browser as SyncBrowser\n    except ImportError:\n        pass\n[docs]def lazy_import_playwright_browsers() -> Tuple[Type[AsyncBrowser], Type[SyncBrowser]]:\n    \"\"\"\n    Lazy import playwright browsers.\n    Returns:\n        Tuple[Type[AsyncBrowser], Type[SyncBrowser]]:\n            AsyncBrowser and SyncBrowser classes.\n    \"\"\"\n    try:\n        from playwright.async_api import Browser as AsyncBrowser  # noqa: F401\n        from playwright.sync_api import Browser as SyncBrowser  # noqa: F401\n    except ImportError:\n        raise ImportError(\n            \"The 'playwright' package is required to use the playwright tools.\"\n            \" Please install it with 'pip install playwright'.\"\n        )\n    return AsyncBrowser, SyncBrowser\n[docs]class BaseBrowserTool(BaseTool):\n    \"\"\"Base class for browser tools.\"\"\"\n    sync_browser: Optional[\"SyncBrowser\"] = None\n    async_browser: Optional[\"AsyncBrowser\"] = None\n    @root_validator\n    def validate_browser_provided(cls, values: dict) -> dict:\n        \"\"\"Check that the arguments are valid.\"\"\"\n        lazy_import_playwright_browsers()\n        if values.get(\"async_browser\") is None and values.get(\"sync_browser\") is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/base.html"}
{"id": "63d9df40bdf5-1", "text": "raise ValueError(\"Either async_browser or sync_browser must be specified.\")\n        return values\n[docs]    @classmethod\n    def from_browser(\n        cls,\n        sync_browser: Optional[SyncBrowser] = None,\n        async_browser: Optional[AsyncBrowser] = None,\n    ) -> BaseBrowserTool:\n        \"\"\"Instantiate the tool.\"\"\"\n        lazy_import_playwright_browsers()\n        return cls(sync_browser=sync_browser, async_browser=async_browser)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/base.html"}
{"id": "bb34a5f532d9-0", "text": "Source code for langchain.tools.playwright.utils\n\"\"\"Utilities for the Playwright browser tools.\"\"\"\nfrom __future__ import annotations\nimport asyncio\nfrom typing import TYPE_CHECKING, Any, Coroutine, TypeVar\nif TYPE_CHECKING:\n    from playwright.async_api import Browser as AsyncBrowser\n    from playwright.async_api import Page as AsyncPage\n    from playwright.sync_api import Browser as SyncBrowser\n    from playwright.sync_api import Page as SyncPage\n[docs]async def aget_current_page(browser: AsyncBrowser) -> AsyncPage:\n    \"\"\"\n    Asynchronously get the current page of the browser.\n    Args:\n        browser: The browser (AsyncBrowser) to get the current page from.\n    Returns:\n        AsyncPage: The current page.\n    \"\"\"\n    if not browser.contexts:\n        context = await browser.new_context()\n        return await context.new_page()\n    context = browser.contexts[0]  # Assuming you're using the default browser context\n    if not context.pages:\n        return await context.new_page()\n    # Assuming the last page in the list is the active one\n    return context.pages[-1]\n[docs]def get_current_page(browser: SyncBrowser) -> SyncPage:\n    \"\"\"\n    Get the current page of the browser.\n    Args:\n        browser: The browser to get the current page from.\n    Returns:\n        SyncPage: The current page.\n    \"\"\"\n    if not browser.contexts:\n        context = browser.new_context()\n        return context.new_page()\n    context = browser.contexts[0]  # Assuming you're using the default browser context\n    if not context.pages:\n        return context.new_page()\n    # Assuming the last page in the list is the active one\n    return context.pages[-1]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/utils.html"}
{"id": "bb34a5f532d9-1", "text": "return context.pages[-1]\n[docs]def create_async_playwright_browser(headless: bool = True) -> AsyncBrowser:\n    \"\"\"\n    Create an async playwright browser.\n    Args:\n        headless: Whether to run the browser in headless mode. Defaults to True.\n    Returns:\n        AsyncBrowser: The playwright browser.\n    \"\"\"\n    from playwright.async_api import async_playwright\n    browser = run_async(async_playwright().start())\n    return run_async(browser.chromium.launch(headless=headless))\n[docs]def create_sync_playwright_browser(headless: bool = True) -> SyncBrowser:\n    \"\"\"\n    Create a playwright browser.\n    Args:\n        headless: Whether to run the browser in headless mode. Defaults to True.\n    Returns:\n        SyncBrowser: The playwright browser.\n    \"\"\"\n    from playwright.sync_api import sync_playwright\n    browser = sync_playwright().start()\n    return browser.chromium.launch(headless=headless)\nT = TypeVar(\"T\")\n[docs]def run_async(coro: Coroutine[Any, Any, T]) -> T:\n    \"\"\"Run an async coroutine.\n    Args:\n        coro: The coroutine to run. Coroutine[Any, Any, T]\n    Returns:\n        T: The result of the coroutine.\n    \"\"\"\n    event_loop = asyncio.get_event_loop()\n    return event_loop.run_until_complete(coro)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/utils.html"}
{"id": "0f203a029aa4-0", "text": "Source code for langchain.tools.playwright.navigate_back\nfrom __future__ import annotations\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.tools.playwright.base import BaseBrowserTool\nfrom langchain.tools.playwright.utils import (\n    aget_current_page,\n    get_current_page,\n)\n[docs]class NavigateBackTool(BaseBrowserTool):\n    \"\"\"Navigate back to the previous page in the browser history.\"\"\"\n    name: str = \"previous_webpage\"\n    description: str = \"Navigate back to the previous page in the browser history\"\n    args_schema: Type[BaseModel] = BaseModel\n    def _run(self, run_manager: Optional[CallbackManagerForToolRun] = None) -> str:\n        \"\"\"Use the tool.\"\"\"\n        if self.sync_browser is None:\n            raise ValueError(f\"Synchronous browser not provided to {self.name}\")\n        page = get_current_page(self.sync_browser)\n        response = page.go_back()\n        if response:\n            return (\n                f\"Navigated back to the previous page with URL '{response.url}'.\"\n                f\" Status code {response.status}\"\n            )\n        else:\n            return \"Unable to navigate back; no previous page in the history\"\n    async def _arun(\n        self,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        if self.async_browser is None:\n            raise ValueError(f\"Asynchronous browser not provided to {self.name}\")\n        page = await aget_current_page(self.async_browser)\n        response = await page.go_back()\n        if response:\n            return (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html"}
{"id": "0f203a029aa4-1", "text": "response = await page.go_back()\n        if response:\n            return (\n                f\"Navigated back to the previous page with URL '{response.url}'.\"\n                f\" Status code {response.status}\"\n            )\n        else:\n            return \"Unable to navigate back; no previous page in the history\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html"}
{"id": "f80284b49b65-0", "text": "Source code for langchain.tools.playwright.current_page\nfrom __future__ import annotations\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.tools.playwright.base import BaseBrowserTool\nfrom langchain.tools.playwright.utils import aget_current_page, get_current_page\n[docs]class CurrentWebPageTool(BaseBrowserTool):\n    \"\"\"Tool for getting the URL of the current webpage.\"\"\"\n    name: str = \"current_webpage\"\n    description: str = \"Returns the URL of the current page\"\n    args_schema: Type[BaseModel] = BaseModel\n    def _run(\n        self,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        if self.sync_browser is None:\n            raise ValueError(f\"Synchronous browser not provided to {self.name}\")\n        page = get_current_page(self.sync_browser)\n        return str(page.url)\n    async def _arun(\n        self,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        if self.async_browser is None:\n            raise ValueError(f\"Asynchronous browser not provided to {self.name}\")\n        page = await aget_current_page(self.async_browser)\n        return str(page.url)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/current_page.html"}
{"id": "149bb4b27c11-0", "text": "Source code for langchain.tools.playwright.get_elements\nfrom __future__ import annotations\nimport json\nfrom typing import TYPE_CHECKING, List, Optional, Sequence, Type\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.playwright.base import BaseBrowserTool\nfrom langchain.tools.playwright.utils import aget_current_page, get_current_page\nif TYPE_CHECKING:\n    from playwright.async_api import Page as AsyncPage\n    from playwright.sync_api import Page as SyncPage\n[docs]class GetElementsToolInput(BaseModel):\n    \"\"\"Input for GetElementsTool.\"\"\"\n    selector: str = Field(\n        ...,\n        description=\"CSS selector, such as '*', 'div', 'p', 'a', #id, .classname\",\n    )\n    attributes: List[str] = Field(\n        default_factory=lambda: [\"innerText\"],\n        description=\"Set of attributes to retrieve for each element\",\n    )\nasync def _aget_elements(\n    page: AsyncPage, selector: str, attributes: Sequence[str]\n) -> List[dict]:\n    \"\"\"Get elements matching the given CSS selector.\"\"\"\n    elements = await page.query_selector_all(selector)\n    results = []\n    for element in elements:\n        result = {}\n        for attribute in attributes:\n            if attribute == \"innerText\":\n                val: Optional[str] = await element.inner_text()\n            else:\n                val = await element.get_attribute(attribute)\n            if val is not None and val.strip() != \"\":\n                result[attribute] = val\n        if result:\n            results.append(result)\n    return results\ndef _get_elements(\n    page: SyncPage, selector: str, attributes: Sequence[str]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html"}
{"id": "149bb4b27c11-1", "text": "page: SyncPage, selector: str, attributes: Sequence[str]\n) -> List[dict]:\n    \"\"\"Get elements matching the given CSS selector.\"\"\"\n    elements = page.query_selector_all(selector)\n    results = []\n    for element in elements:\n        result = {}\n        for attribute in attributes:\n            if attribute == \"innerText\":\n                val: Optional[str] = element.inner_text()\n            else:\n                val = element.get_attribute(attribute)\n            if val is not None and val.strip() != \"\":\n                result[attribute] = val\n        if result:\n            results.append(result)\n    return results\n[docs]class GetElementsTool(BaseBrowserTool):\n    \"\"\"Tool for getting elements in the current web page matching a CSS selector.\"\"\"\n    name: str = \"get_elements\"\n    description: str = (\n        \"Retrieve elements in the current web page matching the given CSS selector\"\n    )\n    args_schema: Type[BaseModel] = GetElementsToolInput\n    def _run(\n        self,\n        selector: str,\n        attributes: Sequence[str] = [\"innerText\"],\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        if self.sync_browser is None:\n            raise ValueError(f\"Synchronous browser not provided to {self.name}\")\n        page = get_current_page(self.sync_browser)\n        # Navigate to the desired webpage before using this tool\n        results = _get_elements(page, selector, attributes)\n        return json.dumps(results, ensure_ascii=False)\n    async def _arun(\n        self,\n        selector: str,\n        attributes: Sequence[str] = [\"innerText\"],\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html"}
{"id": "149bb4b27c11-2", "text": ") -> str:\n        \"\"\"Use the tool.\"\"\"\n        if self.async_browser is None:\n            raise ValueError(f\"Asynchronous browser not provided to {self.name}\")\n        page = await aget_current_page(self.async_browser)\n        # Navigate to the desired webpage before using this tool\n        results = await _aget_elements(page, selector, attributes)\n        return json.dumps(results, ensure_ascii=False)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html"}
{"id": "d28b64d9bbab-0", "text": "Source code for langchain.tools.playwright.extract_text\nfrom __future__ import annotations\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.tools.playwright.base import BaseBrowserTool\nfrom langchain.tools.playwright.utils import aget_current_page, get_current_page\n[docs]class ExtractTextTool(BaseBrowserTool):\n    \"\"\"Tool for extracting all the text on the current webpage.\"\"\"\n    name: str = \"extract_text\"\n    description: str = \"Extract all the text on the current webpage\"\n    args_schema: Type[BaseModel] = BaseModel\n    @root_validator\n    def check_acheck_bs_importrgs(cls, values: dict) -> dict:\n        \"\"\"Check that the arguments are valid.\"\"\"\n        try:\n            from bs4 import BeautifulSoup  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"The 'beautifulsoup4' package is required to use this tool.\"\n                \" Please install it with 'pip install beautifulsoup4'.\"\n            )\n        return values\n    def _run(self, run_manager: Optional[CallbackManagerForToolRun] = None) -> str:\n        \"\"\"Use the tool.\"\"\"\n        # Use Beautiful Soup since it's faster than looping through the elements\n        from bs4 import BeautifulSoup\n        if self.sync_browser is None:\n            raise ValueError(f\"Synchronous browser not provided to {self.name}\")\n        page = get_current_page(self.sync_browser)\n        html_content = page.content()\n        # Parse the HTML content with BeautifulSoup\n        soup = BeautifulSoup(html_content, \"lxml\")\n        return \" \".join(text for text in soup.stripped_strings)\n    async def _arun(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html"}
{"id": "d28b64d9bbab-1", "text": "async def _arun(\n        self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        if self.async_browser is None:\n            raise ValueError(f\"Asynchronous browser not provided to {self.name}\")\n        # Use Beautiful Soup since it's faster than looping through the elements\n        from bs4 import BeautifulSoup\n        page = await aget_current_page(self.async_browser)\n        html_content = await page.content()\n        # Parse the HTML content with BeautifulSoup\n        soup = BeautifulSoup(html_content, \"lxml\")\n        return \" \".join(text for text in soup.stripped_strings)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html"}
{"id": "d2c6ad871f64-0", "text": "Source code for langchain.tools.playwright.click\nfrom __future__ import annotations\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.playwright.base import BaseBrowserTool\nfrom langchain.tools.playwright.utils import (\n    aget_current_page,\n    get_current_page,\n)\n[docs]class ClickToolInput(BaseModel):\n    \"\"\"Input for ClickTool.\"\"\"\n    selector: str = Field(..., description=\"CSS selector for the element to click\")\n[docs]class ClickTool(BaseBrowserTool):\n    \"\"\"Tool for clicking on an element with the given CSS selector.\"\"\"\n    name: str = \"click_element\"\n    description: str = \"Click on an element with the given CSS selector\"\n    args_schema: Type[BaseModel] = ClickToolInput\n    visible_only: bool = True\n    \"\"\"Whether to consider only visible elements.\"\"\"\n    playwright_strict: bool = False\n    \"\"\"Whether to employ Playwright's strict mode when clicking on elements.\"\"\"\n    playwright_timeout: float = 1_000\n    \"\"\"Timeout (in ms) for Playwright to wait for element to be ready.\"\"\"\n    def _selector_effective(self, selector: str) -> str:\n        if not self.visible_only:\n            return selector\n        return f\"{selector} >> visible=1\"\n    def _run(\n        self,\n        selector: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        if self.sync_browser is None:\n            raise ValueError(f\"Synchronous browser not provided to {self.name}\")\n        page = get_current_page(self.sync_browser)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html"}
{"id": "d2c6ad871f64-1", "text": "page = get_current_page(self.sync_browser)\n        # Navigate to the desired webpage before using this tool\n        selector_effective = self._selector_effective(selector=selector)\n        from playwright.sync_api import TimeoutError as PlaywrightTimeoutError\n        try:\n            page.click(\n                selector_effective,\n                strict=self.playwright_strict,\n                timeout=self.playwright_timeout,\n            )\n        except PlaywrightTimeoutError:\n            return f\"Unable to click on element '{selector}'\"\n        return f\"Clicked element '{selector}'\"\n    async def _arun(\n        self,\n        selector: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        if self.async_browser is None:\n            raise ValueError(f\"Asynchronous browser not provided to {self.name}\")\n        page = await aget_current_page(self.async_browser)\n        # Navigate to the desired webpage before using this tool\n        selector_effective = self._selector_effective(selector=selector)\n        from playwright.async_api import TimeoutError as PlaywrightTimeoutError\n        try:\n            await page.click(\n                selector_effective,\n                strict=self.playwright_strict,\n                timeout=self.playwright_timeout,\n            )\n        except PlaywrightTimeoutError:\n            return f\"Unable to click on element '{selector}'\"\n        return f\"Clicked element '{selector}'\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html"}
{"id": "833a4fb1f59e-0", "text": "Source code for langchain.tools.youtube.search\n\"\"\"\nAdapted from https://github.com/venuv/langchain_yt_tools\nCustomYTSearchTool searches YouTube videos related to a person\nand returns a specified number of video URLs.\nInput to this tool should be a comma separated list,\n - the first part contains a person name\n - and the second(optional) a number that is the\n    maximum number of video results to return\n \"\"\"\nimport json\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools import BaseTool\n[docs]class YouTubeSearchTool(BaseTool):\n    \"\"\"Tool that queries YouTube.\"\"\"\n    name: str = \"youtube_search\"\n    description: str = (\n        \"search for youtube videos associated with a person. \"\n        \"the input to this tool should be a comma separated list, \"\n        \"the first part contains a person name and the second a \"\n        \"number that is the maximum number of video results \"\n        \"to return aka num_results. the second part is optional\"\n    )\n    def _search(self, person: str, num_results: int) -> str:\n        from youtube_search import YoutubeSearch\n        results = YoutubeSearch(person, num_results).to_json()\n        data = json.loads(results)\n        url_suffix_list = [\n            \"https://www.youtube.com\" + video[\"url_suffix\"] for video in data[\"videos\"]\n        ]\n        return str(url_suffix_list)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        values = query.split(\",\")\n        person = values[0]\n        if len(values) > 1:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html"}
{"id": "833a4fb1f59e-1", "text": "person = values[0]\n        if len(values) > 1:\n            num_results = int(values[1])\n        else:\n            num_results = 2\n        return self._search(person, num_results)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html"}
{"id": "eb8fcd4bbf9f-0", "text": "Source code for langchain.tools.json.tool\n# flake8: noqa\n\"\"\"Tools for working with JSON specs.\"\"\"\nfrom __future__ import annotations\nimport json\nimport re\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Union\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.tools.base import BaseTool\ndef _parse_input(text: str) -> List[Union[str, int]]:\n    \"\"\"Parse input of the form data[\"key1\"][0][\"key2\"] into a list of keys.\"\"\"\n    _res = re.findall(r\"\\[.*?]\", text)\n    # strip the brackets and quotes, convert to int if possible\n    res = [i[1:-1].replace('\"', \"\").replace(\"'\", \"\") for i in _res]\n    res = [int(i) if i.isdigit() else i for i in res]\n    return res\n[docs]class JsonSpec(BaseModel):\n    \"\"\"Base class for JSON spec.\"\"\"\n    dict_: Dict\n    max_value_length: int = 200\n[docs]    @classmethod\n    def from_file(cls, path: Path) -> JsonSpec:\n        \"\"\"Create a JsonSpec from a file.\"\"\"\n        if not path.exists():\n            raise FileNotFoundError(f\"File not found: {path}\")\n        dict_ = json.loads(path.read_text())\n        return cls(dict_=dict_)\n[docs]    def keys(self, text: str) -> str:\n        \"\"\"Return the keys of the dict at the given path.\n        Args:\n            text: Python representation of the path to the dict (e.g. data[\"key1\"][0][\"key2\"]).\n        \"\"\"\n        try:\n            items = _parse_input(text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html"}
{"id": "eb8fcd4bbf9f-1", "text": "\"\"\"\n        try:\n            items = _parse_input(text)\n            val = self.dict_\n            for i in items:\n                if i:\n                    val = val[i]\n            if not isinstance(val, dict):\n                raise ValueError(\n                    f\"Value at path `{text}` is not a dict, get the value directly.\"\n                )\n            return str(list(val.keys()))\n        except Exception as e:\n            return repr(e)\n[docs]    def value(self, text: str) -> str:\n        \"\"\"Return the value of the dict at the given path.\n        Args:\n            text: Python representation of the path to the dict (e.g. data[\"key1\"][0][\"key2\"]).\n        \"\"\"\n        try:\n            items = _parse_input(text)\n            val = self.dict_\n            for i in items:\n                val = val[i]\n            if isinstance(val, dict) and len(str(val)) > self.max_value_length:\n                return \"Value is a large dictionary, should explore its keys directly\"\n            str_val = str(val)\n            if len(str_val) > self.max_value_length:\n                str_val = str_val[: self.max_value_length] + \"...\"\n            return str_val\n        except Exception as e:\n            return repr(e)\n[docs]class JsonListKeysTool(BaseTool):\n    \"\"\"Tool for listing keys in a JSON spec.\"\"\"\n    name: str = \"json_spec_list_keys\"\n    description: str = \"\"\"\n    Can be used to list all keys at a given path. \n    Before calling this you should be SURE that the path to this exists.\n    The input is a text representation of the path to the dict in Python syntax (e.g. data[\"key1\"][0][\"key2\"]).\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html"}
{"id": "eb8fcd4bbf9f-2", "text": "\"\"\"\n    spec: JsonSpec\n    def _run(\n        self,\n        tool_input: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        return self.spec.keys(tool_input)\n    async def _arun(\n        self,\n        tool_input: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        return self._run(tool_input)\n[docs]class JsonGetValueTool(BaseTool):\n    \"\"\"Tool for getting a value in a JSON spec.\"\"\"\n    name: str = \"json_spec_get_value\"\n    description: str = \"\"\"\n    Can be used to see value in string format at a given path.\n    Before calling this you should be SURE that the path to this exists.\n    The input is a text representation of the path to the dict in Python syntax (e.g. data[\"key1\"][0][\"key2\"]).\n    \"\"\"\n    spec: JsonSpec\n    def _run(\n        self,\n        tool_input: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        return self.spec.value(tool_input)\n    async def _arun(\n        self,\n        tool_input: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        return self._run(tool_input)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html"}
{"id": "7418aa39c2e7-0", "text": "Source code for langchain.tools.gmail.search\nimport base64\nimport email\nfrom enum import Enum\nfrom typing import Any, Dict, List, Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.gmail.base import GmailBaseTool\nfrom langchain.tools.gmail.utils import clean_email_body\n[docs]class Resource(str, Enum):\n    \"\"\"Enumerator of Resources to search.\"\"\"\n    THREADS = \"threads\"\n    MESSAGES = \"messages\"\n[docs]class SearchArgsSchema(BaseModel):\n    \"\"\"Input for SearchGmailTool.\"\"\"\n    # From https://support.google.com/mail/answer/7190?hl=en\n    query: str = Field(\n        ...,\n        description=\"The Gmail query. Example filters include from:sender,\"\n        \" to:recipient, subject:subject, -filtered_term,\"\n        \" in:folder, is:important|read|starred, after:year/mo/date, \"\n        \"before:year/mo/date, label:label_name\"\n        ' \"exact phrase\".'\n        \" Search newer/older than using d (day), m (month), and y (year): \"\n        \"newer_than:2d, older_than:1y.\"\n        \" Attachments with extension example: filename:pdf. Multiple term\"\n        \" matching example: from:amy OR from:david.\",\n    )\n    resource: Resource = Field(\n        default=Resource.MESSAGES,\n        description=\"Whether to search for threads or messages.\",\n    )\n    max_results: int = Field(\n        default=10,\n        description=\"The maximum number of results to return.\",\n    )\n[docs]class GmailSearch(GmailBaseTool):\n    \"\"\"Tool that searches for messages or threads in Gmail.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html"}
{"id": "7418aa39c2e7-1", "text": "\"\"\"Tool that searches for messages or threads in Gmail.\"\"\"\n    name: str = \"search_gmail\"\n    description: str = (\n        \"Use this tool to search for email messages or threads.\"\n        \" The input must be a valid Gmail query.\"\n        \" The output is a JSON list of the requested resource.\"\n    )\n    args_schema: Type[SearchArgsSchema] = SearchArgsSchema\n    def _parse_threads(self, threads: List[Dict[str, Any]]) -> List[Dict[str, Any]]:\n        # Add the thread message snippets to the thread results\n        results = []\n        for thread in threads:\n            thread_id = thread[\"id\"]\n            thread_data = (\n                self.api_resource.users()\n                .threads()\n                .get(userId=\"me\", id=thread_id)\n                .execute()\n            )\n            messages = thread_data[\"messages\"]\n            thread[\"messages\"] = []\n            for message in messages:\n                snippet = message[\"snippet\"]\n                thread[\"messages\"].append({\"snippet\": snippet, \"id\": message[\"id\"]})\n            results.append(thread)\n        return results\n    def _parse_messages(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:\n        results = []\n        for message in messages:\n            message_id = message[\"id\"]\n            message_data = (\n                self.api_resource.users()\n                .messages()\n                .get(userId=\"me\", format=\"raw\", id=message_id)\n                .execute()\n            )\n            raw_message = base64.urlsafe_b64decode(message_data[\"raw\"])\n            email_msg = email.message_from_bytes(raw_message)\n            subject = email_msg[\"Subject\"]\n            sender = email_msg[\"From\"]\n            message_body = \"\"\n            if email_msg.is_multipart():", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html"}
{"id": "7418aa39c2e7-2", "text": "message_body = \"\"\n            if email_msg.is_multipart():\n                for part in email_msg.walk():\n                    ctype = part.get_content_type()\n                    cdispo = str(part.get(\"Content-Disposition\"))\n                    if ctype == \"text/plain\" and \"attachment\" not in cdispo:\n                        message_body = part.get_payload(decode=True).decode(\"utf-8\")\n                        break\n            else:\n                message_body = email_msg.get_payload(decode=True).decode(\"utf-8\")\n            body = clean_email_body(message_body)\n            results.append(\n                {\n                    \"id\": message[\"id\"],\n                    \"threadId\": message_data[\"threadId\"],\n                    \"snippet\": message_data[\"snippet\"],\n                    \"body\": body,\n                    \"subject\": subject,\n                    \"sender\": sender,\n                }\n            )\n        return results\n    def _run(\n        self,\n        query: str,\n        resource: Resource = Resource.MESSAGES,\n        max_results: int = 10,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> List[Dict[str, Any]]:\n        \"\"\"Run the tool.\"\"\"\n        results = (\n            self.api_resource.users()\n            .messages()\n            .list(userId=\"me\", q=query, maxResults=max_results)\n            .execute()\n            .get(resource.value, [])\n        )\n        if resource == Resource.THREADS:\n            return self._parse_threads(results)\n        elif resource == Resource.MESSAGES:\n            return self._parse_messages(results)\n        else:\n            raise NotImplementedError(f\"Resource of type {resource} not implemented.\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html"}
{"id": "88f821756354-0", "text": "Source code for langchain.tools.gmail.create_draft\nimport base64\nfrom email.message import EmailMessage\nfrom typing import List, Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.gmail.base import GmailBaseTool\n[docs]class CreateDraftSchema(BaseModel):\n    \"\"\"Input for CreateDraftTool.\"\"\"\n    message: str = Field(\n        ...,\n        description=\"The message to include in the draft.\",\n    )\n    to: List[str] = Field(\n        ...,\n        description=\"The list of recipients.\",\n    )\n    subject: str = Field(\n        ...,\n        description=\"The subject of the message.\",\n    )\n    cc: Optional[List[str]] = Field(\n        None,\n        description=\"The list of CC recipients.\",\n    )\n    bcc: Optional[List[str]] = Field(\n        None,\n        description=\"The list of BCC recipients.\",\n    )\n[docs]class GmailCreateDraft(GmailBaseTool):\n    \"\"\"Tool that creates a draft email for Gmail.\"\"\"\n    name: str = \"create_gmail_draft\"\n    description: str = (\n        \"Use this tool to create a draft email with the provided message fields.\"\n    )\n    args_schema: Type[CreateDraftSchema] = CreateDraftSchema\n    def _prepare_draft_message(\n        self,\n        message: str,\n        to: List[str],\n        subject: str,\n        cc: Optional[List[str]] = None,\n        bcc: Optional[List[str]] = None,\n    ) -> dict:\n        draft_message = EmailMessage()\n        draft_message.set_content(message)\n        draft_message[\"To\"] = \", \".join(to)\n        draft_message[\"Subject\"] = subject", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/create_draft.html"}
{"id": "88f821756354-1", "text": "draft_message[\"Subject\"] = subject\n        if cc is not None:\n            draft_message[\"Cc\"] = \", \".join(cc)\n        if bcc is not None:\n            draft_message[\"Bcc\"] = \", \".join(bcc)\n        encoded_message = base64.urlsafe_b64encode(draft_message.as_bytes()).decode()\n        return {\"message\": {\"raw\": encoded_message}}\n    def _run(\n        self,\n        message: str,\n        to: List[str],\n        subject: str,\n        cc: Optional[List[str]] = None,\n        bcc: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        try:\n            create_message = self._prepare_draft_message(message, to, subject, cc, bcc)\n            draft = (\n                self.api_resource.users()\n                .drafts()\n                .create(userId=\"me\", body=create_message)\n                .execute()\n            )\n            output = f'Draft created. Draft Id: {draft[\"id\"]}'\n            return output\n        except Exception as e:\n            raise Exception(f\"An error occurred: {e}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/create_draft.html"}
{"id": "50cdaa916a7f-0", "text": "Source code for langchain.tools.gmail.base\n\"\"\"Base class for Gmail tools.\"\"\"\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.gmail.utils import build_resource_service\nif TYPE_CHECKING:\n    # This is for linting and IDE typehints\n    from googleapiclient.discovery import Resource\nelse:\n    try:\n        # We do this so pydantic can resolve the types when instantiating\n        from googleapiclient.discovery import Resource\n    except ImportError:\n        pass\n[docs]class GmailBaseTool(BaseTool):\n    \"\"\"Base class for Gmail tools.\"\"\"\n    api_resource: Resource = Field(default_factory=build_resource_service)\n[docs]    @classmethod\n    def from_api_resource(cls, api_resource: Resource) -> \"GmailBaseTool\":\n        \"\"\"Create a tool from an api resource.\n        Args:\n            api_resource: The api resource to use.\n        Returns:\n            A tool.\n        \"\"\"\n        return cls(service=api_resource)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/base.html"}
{"id": "727022b604a6-0", "text": "Source code for langchain.tools.gmail.get_thread\nfrom typing import Dict, Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.gmail.base import GmailBaseTool\n[docs]class GetThreadSchema(BaseModel):\n    \"\"\"Input for GetMessageTool.\"\"\"\n    # From https://support.google.com/mail/answer/7190?hl=en\n    thread_id: str = Field(\n        ...,\n        description=\"The thread ID.\",\n    )\n[docs]class GmailGetThread(GmailBaseTool):\n    \"\"\"Tool that gets a thread by ID from Gmail.\"\"\"\n    name: str = \"get_gmail_thread\"\n    description: str = (\n        \"Use this tool to search for email messages.\"\n        \" The input must be a valid Gmail query.\"\n        \" The output is a JSON list of messages.\"\n    )\n    args_schema: Type[GetThreadSchema] = GetThreadSchema\n    def _run(\n        self,\n        thread_id: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> Dict:\n        \"\"\"Run the tool.\"\"\"\n        query = self.api_resource.users().threads().get(userId=\"me\", id=thread_id)\n        thread_data = query.execute()\n        if not isinstance(thread_data, dict):\n            raise ValueError(\"The output of the query must be a list.\")\n        messages = thread_data[\"messages\"]\n        thread_data[\"messages\"] = []\n        keys_to_keep = [\"id\", \"snippet\", \"snippet\"]\n        # TODO: Parse body.\n        for message in messages:\n            thread_data[\"messages\"].append(\n                {k: message[k] for k in keys_to_keep if k in message}\n            )\n        return thread_data", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_thread.html"}
{"id": "be326217a770-0", "text": "Source code for langchain.tools.gmail.utils\n\"\"\"Gmail tool utils.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport os\nfrom typing import TYPE_CHECKING, List, Optional, Tuple\nif TYPE_CHECKING:\n    from google.auth.transport.requests import Request\n    from google.oauth2.credentials import Credentials\n    from google_auth_oauthlib.flow import InstalledAppFlow\n    from googleapiclient.discovery import Resource\n    from googleapiclient.discovery import build as build_resource\nlogger = logging.getLogger(__name__)\n[docs]def import_google() -> Tuple[Request, Credentials]:\n    \"\"\"Import google libraries.\n    Returns:\n        Tuple[Request, Credentials]: Request and Credentials classes.\n    \"\"\"\n    # google-auth-httplib2\n    try:\n        from google.auth.transport.requests import Request  # noqa: F401\n        from google.oauth2.credentials import Credentials  # noqa: F401\n    except ImportError:\n        raise ImportError(\n            \"You need to install google-auth-httplib2 to use this toolkit. \"\n            \"Try running pip install --upgrade google-auth-httplib2\"\n        )\n    return Request, Credentials\n[docs]def import_installed_app_flow() -> InstalledAppFlow:\n    \"\"\"Import InstalledAppFlow class.\n    Returns:\n        InstalledAppFlow: InstalledAppFlow class.\n    \"\"\"\n    try:\n        from google_auth_oauthlib.flow import InstalledAppFlow\n    except ImportError:\n        raise ImportError(\n            \"You need to install google-auth-oauthlib to use this toolkit. \"\n            \"Try running pip install --upgrade google-auth-oauthlib\"\n        )\n    return InstalledAppFlow\n[docs]def import_googleapiclient_resource_builder() -> build_resource:\n    \"\"\"Import googleapiclient.discovery.build function.\n    Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/utils.html"}
{"id": "be326217a770-1", "text": "\"\"\"Import googleapiclient.discovery.build function.\n    Returns:\n        build_resource: googleapiclient.discovery.build function.\n    \"\"\"\n    try:\n        from googleapiclient.discovery import build\n    except ImportError:\n        raise ImportError(\n            \"You need to install googleapiclient to use this toolkit. \"\n            \"Try running pip install --upgrade google-api-python-client\"\n        )\n    return build\nDEFAULT_SCOPES = [\"https://mail.google.com/\"]\nDEFAULT_CREDS_TOKEN_FILE = \"token.json\"\nDEFAULT_CLIENT_SECRETS_FILE = \"credentials.json\"\n[docs]def get_gmail_credentials(\n    token_file: Optional[str] = None,\n    client_secrets_file: Optional[str] = None,\n    scopes: Optional[List[str]] = None,\n) -> Credentials:\n    \"\"\"Get credentials.\"\"\"\n    # From https://developers.google.com/gmail/api/quickstart/python\n    Request, Credentials = import_google()\n    InstalledAppFlow = import_installed_app_flow()\n    creds = None\n    scopes = scopes or DEFAULT_SCOPES\n    token_file = token_file or DEFAULT_CREDS_TOKEN_FILE\n    client_secrets_file = client_secrets_file or DEFAULT_CLIENT_SECRETS_FILE\n    # The file token.json stores the user's access and refresh tokens, and is\n    # created automatically when the authorization flow completes for the first\n    # time.\n    if os.path.exists(token_file):\n        creds = Credentials.from_authorized_user_file(token_file, scopes)\n    # If there are no (valid) credentials available, let the user log in.\n    if not creds or not creds.valid:\n        if creds and creds.expired and creds.refresh_token:\n            creds.refresh(Request())\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/utils.html"}
{"id": "be326217a770-2", "text": "creds.refresh(Request())\n        else:\n            # https://developers.google.com/gmail/api/quickstart/python#authorize_credentials_for_a_desktop_application # noqa\n            flow = InstalledAppFlow.from_client_secrets_file(\n                client_secrets_file, scopes\n            )\n            creds = flow.run_local_server(port=0)\n        # Save the credentials for the next run\n        with open(token_file, \"w\") as token:\n            token.write(creds.to_json())\n    return creds\n[docs]def build_resource_service(\n    credentials: Optional[Credentials] = None,\n    service_name: str = \"gmail\",\n    service_version: str = \"v1\",\n) -> Resource:\n    \"\"\"Build a Gmail service.\"\"\"\n    credentials = credentials or get_gmail_credentials()\n    builder = import_googleapiclient_resource_builder()\n    return builder(service_name, service_version, credentials=credentials)\n[docs]def clean_email_body(body: str) -> str:\n    \"\"\"Clean email body.\"\"\"\n    try:\n        from bs4 import BeautifulSoup\n        try:\n            soup = BeautifulSoup(str(body), \"html.parser\")\n            body = soup.get_text()\n            return str(body)\n        except Exception as e:\n            logger.error(e)\n            return str(body)\n    except ImportError:\n        logger.warning(\"BeautifulSoup not installed. Skipping cleaning.\")\n        return str(body)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/utils.html"}
{"id": "1622a59c0897-0", "text": "Source code for langchain.tools.gmail.get_message\nimport base64\nimport email\nfrom typing import Dict, Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.gmail.base import GmailBaseTool\nfrom langchain.tools.gmail.utils import clean_email_body\n[docs]class SearchArgsSchema(BaseModel):\n    \"\"\"Input for GetMessageTool.\"\"\"\n    message_id: str = Field(\n        ...,\n        description=\"The unique ID of the email message, retrieved from a search.\",\n    )\n[docs]class GmailGetMessage(GmailBaseTool):\n    \"\"\"Tool that gets a message by ID from Gmail.\"\"\"\n    name: str = \"get_gmail_message\"\n    description: str = (\n        \"Use this tool to fetch an email by message ID.\"\n        \" Returns the thread ID, snippet, body, subject, and sender.\"\n    )\n    args_schema: Type[SearchArgsSchema] = SearchArgsSchema\n    def _run(\n        self,\n        message_id: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> Dict:\n        \"\"\"Run the tool.\"\"\"\n        query = (\n            self.api_resource.users()\n            .messages()\n            .get(userId=\"me\", format=\"raw\", id=message_id)\n        )\n        message_data = query.execute()\n        raw_message = base64.urlsafe_b64decode(message_data[\"raw\"])\n        email_msg = email.message_from_bytes(raw_message)\n        subject = email_msg[\"Subject\"]\n        sender = email_msg[\"From\"]\n        message_body = \"\"\n        if email_msg.is_multipart():\n            for part in email_msg.walk():\n                ctype = part.get_content_type()\n                cdispo = str(part.get(\"Content-Disposition\"))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_message.html"}
{"id": "1622a59c0897-1", "text": "cdispo = str(part.get(\"Content-Disposition\"))\n                if ctype == \"text/plain\" and \"attachment\" not in cdispo:\n                    message_body = part.get_payload(decode=True).decode(\"utf-8\")\n                    break\n        else:\n            message_body = email_msg.get_payload(decode=True).decode(\"utf-8\")\n        body = clean_email_body(message_body)\n        return {\n            \"id\": message_id,\n            \"threadId\": message_data[\"threadId\"],\n            \"snippet\": message_data[\"snippet\"],\n            \"body\": body,\n            \"subject\": subject,\n            \"sender\": sender,\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_message.html"}
{"id": "3e118a8bdf85-0", "text": "Source code for langchain.tools.gmail.send_message\n\"\"\"Send Gmail messages.\"\"\"\nimport base64\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom typing import Any, Dict, List, Optional, Union\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.gmail.base import GmailBaseTool\n[docs]class SendMessageSchema(BaseModel):\n    \"\"\"Input for SendMessageTool.\"\"\"\n    message: str = Field(\n        ...,\n        description=\"The message to send.\",\n    )\n    to: Union[str, List[str]] = Field(\n        ...,\n        description=\"The list of recipients.\",\n    )\n    subject: str = Field(\n        ...,\n        description=\"The subject of the message.\",\n    )\n    cc: Optional[Union[str, List[str]]] = Field(\n        None,\n        description=\"The list of CC recipients.\",\n    )\n    bcc: Optional[Union[str, List[str]]] = Field(\n        None,\n        description=\"The list of BCC recipients.\",\n    )\n[docs]class GmailSendMessage(GmailBaseTool):\n    \"\"\"Tool that sends a message to Gmail.\"\"\"\n    name: str = \"send_gmail_message\"\n    description: str = (\n        \"Use this tool to send email messages.\" \" The input is the message, recipients\"\n    )\n    def _prepare_message(\n        self,\n        message: str,\n        to: Union[str, List[str]],\n        subject: str,\n        cc: Optional[Union[str, List[str]]] = None,\n        bcc: Optional[Union[str, List[str]]] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Create a message for an email.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html"}
{"id": "3e118a8bdf85-1", "text": ") -> Dict[str, Any]:\n        \"\"\"Create a message for an email.\"\"\"\n        mime_message = MIMEMultipart()\n        mime_message.attach(MIMEText(message, \"html\"))\n        mime_message[\"To\"] = \", \".join(to if isinstance(to, list) else [to])\n        mime_message[\"Subject\"] = subject\n        if cc is not None:\n            mime_message[\"Cc\"] = \", \".join(cc if isinstance(cc, list) else [cc])\n        if bcc is not None:\n            mime_message[\"Bcc\"] = \", \".join(bcc if isinstance(bcc, list) else [bcc])\n        encoded_message = base64.urlsafe_b64encode(mime_message.as_bytes()).decode()\n        return {\"raw\": encoded_message}\n    def _run(\n        self,\n        message: str,\n        to: Union[str, List[str]],\n        subject: str,\n        cc: Optional[Union[str, List[str]]] = None,\n        bcc: Optional[Union[str, List[str]]] = None,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Run the tool.\"\"\"\n        try:\n            create_message = self._prepare_message(message, to, subject, cc=cc, bcc=bcc)\n            send_message = (\n                self.api_resource.users()\n                .messages()\n                .send(userId=\"me\", body=create_message)\n            )\n            sent_message = send_message.execute()\n            return f'Message sent. Message Id: {sent_message[\"id\"]}'\n        except Exception as error:\n            raise Exception(f\"An error occurred: {error}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html"}
{"id": "458e6b87d4c5-0", "text": "Source code for langchain.tools.requests.tool\n# flake8: noqa\n\"\"\"Tools for making requests to an API endpoint.\"\"\"\nimport json\nfrom typing import Any, Dict, Optional\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.utilities.requests import TextRequestsWrapper\nfrom langchain.tools.base import BaseTool\ndef _parse_input(text: str) -> Dict[str, Any]:\n    \"\"\"Parse the json string into a dict.\"\"\"\n    return json.loads(text)\ndef _clean_url(url: str) -> str:\n    \"\"\"Strips quotes from the url.\"\"\"\n    return url.strip(\"\\\"'\")\n[docs]class BaseRequestsTool(BaseModel):\n    \"\"\"Base class for requests tools.\"\"\"\n    requests_wrapper: TextRequestsWrapper\n[docs]class RequestsGetTool(BaseRequestsTool, BaseTool):\n    \"\"\"Tool for making a GET request to an API endpoint.\"\"\"\n    name: str = \"requests_get\"\n    description: str = \"A portal to the internet. Use this when you need to get specific content from a website. Input should be a  url (i.e. https://www.google.com). The output will be the text response of the GET request.\"\n    def _run(\n        self, url: str, run_manager: Optional[CallbackManagerForToolRun] = None\n    ) -> str:\n        \"\"\"Run the tool.\"\"\"\n        return self.requests_wrapper.get(_clean_url(url))\n    async def _arun(\n        self,\n        url: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Run the tool asynchronously.\"\"\"\n        return await self.requests_wrapper.aget(_clean_url(url))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html"}
{"id": "458e6b87d4c5-1", "text": "return await self.requests_wrapper.aget(_clean_url(url))\n[docs]class RequestsPostTool(BaseRequestsTool, BaseTool):\n    \"\"\"Tool for making a POST request to an API endpoint.\"\"\"\n    name: str = \"requests_post\"\n    description: str = \"\"\"Use this when you want to POST to a website.\n    Input should be a json string with two keys: \"url\" and \"data\".\n    The value of \"url\" should be a string, and the value of \"data\" should be a dictionary of \n    key-value pairs you want to POST to the url.\n    Be careful to always use double quotes for strings in the json string\n    The output will be the text response of the POST request.\n    \"\"\"\n    def _run(\n        self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None\n    ) -> str:\n        \"\"\"Run the tool.\"\"\"\n        try:\n            data = _parse_input(text)\n            return self.requests_wrapper.post(_clean_url(data[\"url\"]), data[\"data\"])\n        except Exception as e:\n            return repr(e)\n    async def _arun(\n        self,\n        text: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Run the tool asynchronously.\"\"\"\n        try:\n            data = _parse_input(text)\n            return await self.requests_wrapper.apost(\n                _clean_url(data[\"url\"]), data[\"data\"]\n            )\n        except Exception as e:\n            return repr(e)\n[docs]class RequestsPatchTool(BaseRequestsTool, BaseTool):\n    \"\"\"Tool for making a PATCH request to an API endpoint.\"\"\"\n    name: str = \"requests_patch\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html"}
{"id": "458e6b87d4c5-2", "text": "name: str = \"requests_patch\"\n    description: str = \"\"\"Use this when you want to PATCH to a website.\n    Input should be a json string with two keys: \"url\" and \"data\".\n    The value of \"url\" should be a string, and the value of \"data\" should be a dictionary of \n    key-value pairs you want to PATCH to the url.\n    Be careful to always use double quotes for strings in the json string\n    The output will be the text response of the PATCH request.\n    \"\"\"\n    def _run(\n        self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None\n    ) -> str:\n        \"\"\"Run the tool.\"\"\"\n        try:\n            data = _parse_input(text)\n            return self.requests_wrapper.patch(_clean_url(data[\"url\"]), data[\"data\"])\n        except Exception as e:\n            return repr(e)\n    async def _arun(\n        self,\n        text: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Run the tool asynchronously.\"\"\"\n        try:\n            data = _parse_input(text)\n            return await self.requests_wrapper.apatch(\n                _clean_url(data[\"url\"]), data[\"data\"]\n            )\n        except Exception as e:\n            return repr(e)\n[docs]class RequestsPutTool(BaseRequestsTool, BaseTool):\n    \"\"\"Tool for making a PUT request to an API endpoint.\"\"\"\n    name: str = \"requests_put\"\n    description: str = \"\"\"Use this when you want to PUT to a website.\n    Input should be a json string with two keys: \"url\" and \"data\".", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html"}
{"id": "458e6b87d4c5-3", "text": "Input should be a json string with two keys: \"url\" and \"data\".\n    The value of \"url\" should be a string, and the value of \"data\" should be a dictionary of \n    key-value pairs you want to PUT to the url.\n    Be careful to always use double quotes for strings in the json string.\n    The output will be the text response of the PUT request.\n    \"\"\"\n    def _run(\n        self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None\n    ) -> str:\n        \"\"\"Run the tool.\"\"\"\n        try:\n            data = _parse_input(text)\n            return self.requests_wrapper.put(_clean_url(data[\"url\"]), data[\"data\"])\n        except Exception as e:\n            return repr(e)\n    async def _arun(\n        self,\n        text: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Run the tool asynchronously.\"\"\"\n        try:\n            data = _parse_input(text)\n            return await self.requests_wrapper.aput(\n                _clean_url(data[\"url\"]), data[\"data\"]\n            )\n        except Exception as e:\n            return repr(e)\n[docs]class RequestsDeleteTool(BaseRequestsTool, BaseTool):\n    \"\"\"Tool for making a DELETE request to an API endpoint.\"\"\"\n    name: str = \"requests_delete\"\n    description: str = \"A portal to the internet. Use this when you need to make a DELETE request to a URL. Input should be a specific url, and the output will be the text response of the DELETE request.\"\n    def _run(\n        self,\n        url: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html"}
{"id": "458e6b87d4c5-4", "text": ") -> str:\n        \"\"\"Run the tool.\"\"\"\n        return self.requests_wrapper.delete(_clean_url(url))\n    async def _arun(\n        self,\n        url: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Run the tool asynchronously.\"\"\"\n        return await self.requests_wrapper.adelete(_clean_url(url))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html"}
{"id": "e37813be2630-0", "text": "Source code for langchain.tools.ainetwork.transfer\nimport json\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import AsyncCallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.ainetwork.base import AINBaseTool\n[docs]class TransferSchema(BaseModel):\n    \"\"\"Schema for transfer operations.\"\"\"\n    address: str = Field(..., description=\"Address to transfer AIN to\")\n    amount: int = Field(..., description=\"Amount of AIN to transfer\")\n[docs]class AINTransfer(AINBaseTool):\n    \"\"\"Tool for transfer operations.\"\"\"\n    name: str = \"AINtransfer\"\n    description: str = \"Transfers AIN to a specified address\"\n    args_schema: Type[TransferSchema] = TransferSchema\n    async def _arun(\n        self,\n        address: str,\n        amount: int,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        try:\n            res = await self.interface.wallet.transfer(address, amount, nonce=-1)\n            return json.dumps(res, ensure_ascii=False)\n        except Exception as e:\n            return f\"{type(e).__name__}: {str(e)}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/transfer.html"}
{"id": "7062382029a6-0", "text": "Source code for langchain.tools.ainetwork.rule\nimport builtins\nimport json\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import AsyncCallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.ainetwork.base import AINBaseTool, OperationType\n[docs]class RuleSchema(BaseModel):\n    \"\"\"Schema for owner operations.\"\"\"\n    type: OperationType = Field(...)\n    path: str = Field(..., description=\"Path on the blockchain where the rule applies\")\n    eval: Optional[str] = Field(None, description=\"eval string to determine permission\")\n[docs]class AINRuleOps(AINBaseTool):\n    \"\"\"Tool for owner operations.\"\"\"\n    name: str = \"AINruleOps\"\n    description: str = \"\"\"\nCovers the write `rule` for the AINetwork Blockchain database. The SET type specifies write permissions using the `eval` variable as a JavaScript eval string.\nIn order to AINvalueOps with SET at the path, the execution result of the `eval` string must be true.\n## Path Rules\n1. Allowed characters for directory: `[a-zA-Z_0-9]`\n2. Use `$<key>` for template variables as directory.\n## Eval String Special Variables\n- auth.addr: Address of the writer for the path\n- newData: New data for the path\n- data: Current data for the path\n- currentTime: Time in seconds\n- lastBlockNumber: Latest processed block number\n## Eval String Functions\n- getValue(<path>)\n- getRule(<path>)\n- getOwner(<path>)\n- getFunction(<path>)\n- evalRule(<path>, <value to set>, auth, currentTime)\n- evalOwner(<path>, 'write_owner', auth)\n## SET Example\n- type: SET", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/rule.html"}
{"id": "7062382029a6-1", "text": "## SET Example\n- type: SET\n- path: /apps/langchain_project_1/$from/$to/$img\n- eval: auth.addr===$from&&!getValue('/apps/image_db/'+$img)\n## GET Example\n- type: GET\n- path: /apps/langchain_project_1\n\"\"\"  # noqa: E501\n    args_schema: Type[BaseModel] = RuleSchema\n    async def _arun(\n        self,\n        type: OperationType,\n        path: str,\n        eval: Optional[str] = None,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        from ain.types import ValueOnlyTransactionInput\n        try:\n            if type is OperationType.SET:\n                if eval is None:\n                    raise ValueError(\"'eval' is required for SET operation.\")\n                res = await self.interface.db.ref(path).setRule(\n                    transactionInput=ValueOnlyTransactionInput(\n                        value={\".rule\": {\"write\": eval}}\n                    )\n                )\n            elif type is OperationType.GET:\n                res = await self.interface.db.ref(path).getRule()\n            else:\n                raise ValueError(f\"Unsupported 'type': {type}.\")\n            return json.dumps(res, ensure_ascii=False)\n        except Exception as e:\n            return f\"{builtins.type(e).__name__}: {str(e)}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/rule.html"}
{"id": "6a6430ba0869-0", "text": "Source code for langchain.tools.ainetwork.base\nfrom __future__ import annotations\nimport asyncio\nimport threading\nfrom enum import Enum\nfrom typing import TYPE_CHECKING, Any, Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.ainetwork.utils import authenticate\nfrom langchain.tools.base import BaseTool\nif TYPE_CHECKING:\n    from ain.ain import Ain\n[docs]class OperationType(str, Enum):\n    \"\"\"Type of operation as enumerator.\"\"\"\n    SET = \"SET\"\n    GET = \"GET\"\n[docs]class AINBaseTool(BaseTool):\n    \"\"\"Base class for the AINetwork tools.\"\"\"\n    interface: Ain = Field(default_factory=authenticate)\n    \"\"\"The interface object for the AINetwork Blockchain.\"\"\"\n    def _run(\n        self,\n        *args: Any,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        try:\n            loop = asyncio.get_event_loop()\n        except RuntimeError:\n            loop = asyncio.new_event_loop()\n            asyncio.set_event_loop(loop)\n        if loop.is_closed():\n            loop = asyncio.new_event_loop()\n            asyncio.set_event_loop(loop)\n        if loop.is_running():\n            result_container = []\n            def thread_target() -> None:\n                nonlocal result_container\n                new_loop = asyncio.new_event_loop()\n                asyncio.set_event_loop(new_loop)\n                try:\n                    result_container.append(\n                        new_loop.run_until_complete(self._arun(*args, **kwargs))\n                    )\n                except Exception as e:\n                    result_container.append(e)\n                finally:\n                    new_loop.close()\n            thread = threading.Thread(target=thread_target)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/base.html"}
{"id": "6a6430ba0869-1", "text": "new_loop.close()\n            thread = threading.Thread(target=thread_target)\n            thread.start()\n            thread.join()\n            result = result_container[0]\n            if isinstance(result, Exception):\n                raise result\n            return result\n        else:\n            result = loop.run_until_complete(self._arun(*args, **kwargs))\n            loop.close()\n            return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/base.html"}
{"id": "a4fbd39214c4-0", "text": "Source code for langchain.tools.ainetwork.utils\n\"\"\"AINetwork Blockchain tool utils.\"\"\"\nfrom __future__ import annotations\nimport os\nfrom typing import TYPE_CHECKING, Literal, Optional\nif TYPE_CHECKING:\n    from ain.ain import Ain\n[docs]def authenticate(network: Optional[Literal[\"mainnet\", \"testnet\"]] = \"testnet\") -> Ain:\n    \"\"\"Authenticate using the AIN Blockchain\"\"\"\n    try:\n        from ain.ain import Ain\n    except ImportError as e:\n        raise ImportError(\n            \"Cannot import ain-py related modules. Please install the package with \"\n            \"`pip install ain-py`.\"\n        ) from e\n    if network == \"mainnet\":\n        provider_url = \"https://mainnet-api.ainetwork.ai/\"\n        chain_id = 1\n        if \"AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY\" in os.environ:\n            private_key = os.environ[\"AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY\"]\n        else:\n            raise EnvironmentError(\n                \"Error: The AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY environmental variable \"\n                \"has not been set.\"\n            )\n    elif network == \"testnet\":\n        provider_url = \"https://testnet-api.ainetwork.ai/\"\n        chain_id = 0\n        if \"AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY\" in os.environ:\n            private_key = os.environ[\"AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY\"]\n        else:\n            raise EnvironmentError(\n                \"Error: The AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY environmental variable \"\n                \"has not been set.\"\n            )\n    elif network is None:\n        if (\n            \"AIN_BLOCKCHAIN_PROVIDER_URL\" in os.environ\n            and \"AIN_BLOCKCHAIN_CHAIN_ID\" in os.environ\n            and \"AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY\" in os.environ\n        ):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/utils.html"}
{"id": "a4fbd39214c4-1", "text": "and \"AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY\" in os.environ\n        ):\n            provider_url = os.environ[\"AIN_BLOCKCHAIN_PROVIDER_URL\"]\n            chain_id = int(os.environ[\"AIN_BLOCKCHAIN_CHAIN_ID\"])\n            private_key = os.environ[\"AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY\"]\n        else:\n            raise EnvironmentError(\n                \"Error: The AIN_BLOCKCHAIN_PROVIDER_URL and \"\n                \"AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY and AIN_BLOCKCHAIN_CHAIN_ID \"\n                \"environmental variable has not been set.\"\n            )\n    else:\n        raise ValueError(f\"Unsupported 'network': {network}\")\n    ain = Ain(provider_url, chain_id)\n    ain.wallet.addAndSetDefaultAccount(private_key)\n    return ain", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/utils.html"}
{"id": "5354ec80e6c0-0", "text": "Source code for langchain.tools.ainetwork.owner\nimport builtins\nimport json\nfrom typing import List, Optional, Type, Union\nfrom langchain.callbacks.manager import AsyncCallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.ainetwork.base import AINBaseTool, OperationType\n[docs]class RuleSchema(BaseModel):\n    \"\"\"Schema for owner operations.\"\"\"\n    type: OperationType = Field(...)\n    path: str = Field(..., description=\"Blockchain reference path\")\n    address: Optional[Union[str, List[str]]] = Field(\n        None, description=\"A single address or a list of addresses\"\n    )\n    write_owner: Optional[bool] = Field(\n        False, description=\"Authority to edit the `owner` property of the path\"\n    )\n    write_rule: Optional[bool] = Field(\n        False, description=\"Authority to edit `write rule` for the path\"\n    )\n    write_function: Optional[bool] = Field(\n        False, description=\"Authority to `set function` for the path\"\n    )\n    branch_owner: Optional[bool] = Field(\n        False, description=\"Authority to initialize `owner` of sub-paths\"\n    )\n[docs]class AINOwnerOps(AINBaseTool):\n    \"\"\"Tool for owner operations.\"\"\"\n    name: str = \"AINownerOps\"\n    description: str = \"\"\"\nRules for `owner` in AINetwork Blockchain database.\nAn address set as `owner` can modify permissions according to its granted authorities\n## Path Rule\n- (/[a-zA-Z_0-9]+)+\n- Permission checks ascend from the most specific (child) path to broader (parent) paths until an `owner` is located.\n## Address Rules", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/owner.html"}
{"id": "5354ec80e6c0-1", "text": "## Address Rules\n- 0x[0-9a-fA-F]{40}: 40-digit hexadecimal address\n- *: All addresses permitted\n- Defaults to the current session's address\n## SET\n- `SET` alters permissions for specific addresses, while other addresses remain unaffected.\n- When removing an address of `owner`, set all authorities for that address to false.\n- message `write_owner permission evaluated false` if fail\n### Example\n- type: SET\n- path: /apps/langchain\n- address: [<address 1>, <address 2>]\n- write_owner: True\n- write_rule: True\n- write_function: True\n- branch_owner: True\n## GET\n- Provides all addresses with `owner` permissions and their authorities in the path.\n### Example\n- type: GET\n- path: /apps/langchain\n\"\"\"  # noqa: E501\n    args_schema: Type[BaseModel] = RuleSchema\n    async def _arun(\n        self,\n        type: OperationType,\n        path: str,\n        address: Optional[Union[str, List[str]]] = None,\n        write_owner: Optional[bool] = None,\n        write_rule: Optional[bool] = None,\n        write_function: Optional[bool] = None,\n        branch_owner: Optional[bool] = None,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        from ain.types import ValueOnlyTransactionInput\n        try:\n            if type is OperationType.SET:\n                if address is None:\n                    address = self.interface.wallet.defaultAccount.address\n                if isinstance(address, str):\n                    address = [address]\n                res = await self.interface.db.ref(path).setOwner(\n                    transactionInput=ValueOnlyTransactionInput(\n                        value={", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/owner.html"}
{"id": "5354ec80e6c0-2", "text": "transactionInput=ValueOnlyTransactionInput(\n                        value={\n                            \".owner\": {\n                                \"owners\": {\n                                    address: {\n                                        \"write_owner\": write_owner or False,\n                                        \"write_rule\": write_rule or False,\n                                        \"write_function\": write_function or False,\n                                        \"branch_owner\": branch_owner or False,\n                                    }\n                                    for address in address\n                                }\n                            }\n                        }\n                    )\n                )\n            elif type is OperationType.GET:\n                res = await self.interface.db.ref(path).getOwner()\n            else:\n                raise ValueError(f\"Unsupported 'type': {type}.\")\n            return json.dumps(res, ensure_ascii=False)\n        except Exception as e:\n            return f\"{builtins.type(e).__name__}: {str(e)}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/owner.html"}
{"id": "d7f51b07cff7-0", "text": "Source code for langchain.tools.ainetwork.value\nimport builtins\nimport json\nfrom typing import Optional, Type, Union\nfrom langchain.callbacks.manager import AsyncCallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.ainetwork.base import AINBaseTool, OperationType\n[docs]class ValueSchema(BaseModel):\n    \"\"\"Schema for value operations.\"\"\"\n    type: OperationType = Field(...)\n    path: str = Field(..., description=\"Blockchain reference path\")\n    value: Optional[Union[int, str, float, dict]] = Field(\n        None, description=\"Value to be set at the path\"\n    )\n[docs]class AINValueOps(AINBaseTool):\n    \"\"\"Tool for value operations.\"\"\"\n    name: str = \"AINvalueOps\"\n    description: str = \"\"\"\nCovers the read and write value for the AINetwork Blockchain database.\n## SET\n- Set a value at a given path\n### Example\n- type: SET\n- path: /apps/langchain_test_1/object\n- value: {1: 2, \"34\": 56}\n## GET\n- Retrieve a value at a given path\n### Example\n- type: GET\n- path: /apps/langchain_test_1/DB\n## Special paths\n- `/accounts/<address>/balance`: Account balance\n- `/accounts/<address>/nonce`: Account nonce\n- `/apps`: Applications\n- `/consensus`: Consensus\n- `/checkin`: Check-in\n- `/deposit/<service id>/<address>/<deposit id>`: Deposit\n- `/deposit_accounts/<service id>/<address>/<account id>`: Deposit accounts\n- `/escrow`: Escrow\n- `/payments`: Payment\n- `/sharding`: Sharding\n- `/token/name`: Token name", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/value.html"}
{"id": "d7f51b07cff7-1", "text": "- `/sharding`: Sharding\n- `/token/name`: Token name\n- `/token/symbol`: Token symbol\n- `/token/total_supply`: Token total supply\n- `/transfer/<address from>/<address to>/<key>/value`: Transfer\n- `/withdraw/<service id>/<address>/<withdraw id>`: Withdraw\n\"\"\"\n    args_schema: Type[BaseModel] = ValueSchema\n    async def _arun(\n        self,\n        type: OperationType,\n        path: str,\n        value: Optional[Union[int, str, float, dict]] = None,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        from ain.types import ValueOnlyTransactionInput\n        try:\n            if type is OperationType.SET:\n                if value is None:\n                    raise ValueError(\"'value' is required for SET operation.\")\n                res = await self.interface.db.ref(path).setValue(\n                    transactionInput=ValueOnlyTransactionInput(value=value)\n                )\n            elif type is OperationType.GET:\n                res = await self.interface.db.ref(path).getValue()\n            else:\n                raise ValueError(f\"Unsupported 'type': {type}.\")\n            return json.dumps(res, ensure_ascii=False)\n        except Exception as e:\n            return f\"{builtins.type(e).__name__}: {str(e)}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/value.html"}
{"id": "6843b35cb89d-0", "text": "Source code for langchain.tools.ainetwork.app\nimport builtins\nimport json\nfrom enum import Enum\nfrom typing import List, Optional, Type, Union\nfrom langchain.callbacks.manager import AsyncCallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.ainetwork.base import AINBaseTool\n[docs]class AppOperationType(str, Enum):\n    \"\"\"Type of app operation as enumerator.\"\"\"\n    SET_ADMIN = \"SET_ADMIN\"\n    GET_CONFIG = \"GET_CONFIG\"\n[docs]class AppSchema(BaseModel):\n    \"\"\"Schema for app operations.\"\"\"\n    type: AppOperationType = Field(...)\n    appName: str = Field(..., description=\"Name of the application on the blockchain\")\n    address: Optional[Union[str, List[str]]] = Field(\n        None,\n        description=(\n            \"A single address or a list of addresses. Default: current session's \"\n            \"address\"\n        ),\n    )\n[docs]class AINAppOps(AINBaseTool):\n    \"\"\"Tool for app operations.\"\"\"\n    name: str = \"AINappOps\"\n    description: str = \"\"\"\nCreate an app in the AINetwork Blockchain database by creating the /apps/<appName> path.\nAn address set as `admin` can grant `owner` rights to other addresses (refer to `AINownerOps` for more details).\nAlso, `admin` is initialized to have all `owner` permissions and `rule` allowed for that path.\n## appName Rule\n- [a-z_0-9]+\n## address Rules\n- 0x[0-9a-fA-F]{40}\n- Defaults to the current session's address\n- Multiple addresses can be specified if needed\n## SET_ADMIN Example 1\n- type: SET_ADMIN\n- appName: ain_project", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/app.html"}
{"id": "6843b35cb89d-1", "text": "## SET_ADMIN Example 1\n- type: SET_ADMIN\n- appName: ain_project\n### Result:\n1. Path /apps/ain_project created.\n2. Current session's address registered as admin.\n## SET_ADMIN Example 2\n- type: SET_ADMIN\n- appName: test_project\n- address: [<address1>, <address2>]\n### Result:\n1. Path /apps/test_project created.\n2. <address1> and <address2> registered as admin.\n\"\"\"  # noqa: E501\n    args_schema: Type[BaseModel] = AppSchema\n    async def _arun(\n        self,\n        type: AppOperationType,\n        appName: str,\n        address: Optional[Union[str, List[str]]] = None,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        from ain.types import ValueOnlyTransactionInput\n        from ain.utils import getTimestamp\n        try:\n            if type is AppOperationType.SET_ADMIN:\n                if address is None:\n                    address = self.interface.wallet.defaultAccount.address\n                if isinstance(address, str):\n                    address = [address]\n                res = await self.interface.db.ref(\n                    f\"/manage_app/{appName}/create/{getTimestamp()}\"\n                ).setValue(\n                    transactionInput=ValueOnlyTransactionInput(\n                        value={\"admin\": {address: True for address in address}}\n                    )\n                )\n            elif type is AppOperationType.GET_CONFIG:\n                res = await self.interface.db.ref(\n                    f\"/manage_app/{appName}/config\"\n                ).getValue()\n            else:\n                raise ValueError(f\"Unsupported 'type': {type}.\")\n            return json.dumps(res, ensure_ascii=False)\n        except Exception as e:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/app.html"}
{"id": "6843b35cb89d-2", "text": "return json.dumps(res, ensure_ascii=False)\n        except Exception as e:\n            return f\"{builtins.type(e).__name__}: {str(e)}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ainetwork/app.html"}
{"id": "68c677afece8-0", "text": "Source code for langchain.tools.bearly.tool\nimport base64\nimport itertools\nimport json\nimport re\nfrom pathlib import Path\nfrom typing import Dict, List, Type\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools import Tool\n[docs]def strip_markdown_code(md_string: str) -> str:\n    \"\"\"Strip markdown code from a string.\"\"\"\n    stripped_string = re.sub(r\"^`{1,3}.*?\\n\", \"\", md_string, flags=re.DOTALL)\n    stripped_string = re.sub(r\"`{1,3}$\", \"\", stripped_string)\n    return stripped_string\n[docs]def head_file(path: str, n: int) -> List[str]:\n    \"\"\"Get the first n lines of a file.\"\"\"\n    try:\n        with open(path, \"r\") as f:\n            return [str(line) for line in itertools.islice(f, n)]\n    except Exception:\n        return []\n[docs]def file_to_base64(path: str) -> str:\n    \"\"\"Convert a file to base64.\"\"\"\n    with open(path, \"rb\") as f:\n        return base64.b64encode(f.read()).decode()\n[docs]class BearlyInterpreterToolArguments(BaseModel):\n    \"\"\"Arguments for the BearlyInterpreterTool.\"\"\"\n    python_code: str = Field(\n        ...,\n        example=\"print('Hello World')\",\n        description=(\n            \"The pure python script to be evaluated. \"\n            \"The contents will be in main.py. \"\n            \"It should not be in markdown format.\"\n        ),\n    )\nbase_description = \"\"\"Evaluates python code in a sandbox environment. \\\nThe environment resets on every execution. \\\nYou must send the whole script every time and print your outputs. \\", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/bearly/tool.html"}
{"id": "68c677afece8-1", "text": "You must send the whole script every time and print your outputs. \\\nScript should be pure python code that can be evaluated. \\\nIt should be in python format NOT markdown. \\\nThe code should NOT be wrapped in backticks. \\\nAll python packages including requests, matplotlib, scipy, numpy, pandas, \\\netc are available. \\\nIf you have any files outputted write them to \"output/\" relative to the execution \\\npath. Output can only be read from the directory, stdout, and stdin. \\\nDo not use things like plot.show() as it will \\\nnot work instead write them out `output/` and a link to the file will be returned. \\\nprint() any output and results so you can capture the output.\"\"\"\n[docs]class FileInfo(BaseModel):\n    \"\"\"Information about a file to be uploaded.\"\"\"\n    source_path: str\n    description: str\n    target_path: str\n[docs]class BearlyInterpreterTool:\n    \"\"\"Tool for evaluating python code in a sandbox environment.\"\"\"\n    api_key: str\n    endpoint = \"https://exec.bearly.ai/v1/interpreter\"\n    name = \"bearly_interpreter\"\n    args_schema: Type[BaseModel] = BearlyInterpreterToolArguments\n    files: Dict[str, FileInfo] = {}\n[docs]    def __init__(self, api_key: str):\n        self.api_key = api_key\n    @property\n    def file_description(self) -> str:\n        if len(self.files) == 0:\n            return \"\"\n        lines = [\"The following files available in the evaluation environment:\"]\n        for target_path, file_info in self.files.items():\n            peek_content = head_file(file_info.source_path, 4)\n            lines.append(\n                f\"- path: `{target_path}` \\n first four lines: {peek_content}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/bearly/tool.html"}
{"id": "68c677afece8-2", "text": "f\"- path: `{target_path}` \\n first four lines: {peek_content}\"\n                f\" \\n description: `{file_info.description}`\"\n            )\n        return \"\\n\".join(lines)\n    @property\n    def description(self) -> str:\n        return (base_description + \"\\n\\n\" + self.file_description).strip()\n[docs]    def make_input_files(self) -> List[dict]:\n        files = []\n        for target_path, file_info in self.files.items():\n            files.append(\n                {\n                    \"pathname\": target_path,\n                    \"contentsBasesixtyfour\": file_to_base64(file_info.source_path),\n                }\n            )\n        return files\n    def _run(self, python_code: str) -> dict:\n        script = strip_markdown_code(python_code)\n        resp = requests.post(\n            \"https://exec.bearly.ai/v1/interpreter\",\n            data=json.dumps(\n                {\n                    \"fileContents\": script,\n                    \"inputFiles\": self.make_input_files(),\n                    \"outputDir\": \"output/\",\n                    \"outputAsLinks\": True,\n                }\n            ),\n            headers={\"Authorization\": self.api_key},\n        ).json()\n        return {\n            \"stdout\": base64.b64decode(resp[\"stdoutBasesixtyfour\"]).decode()\n            if resp[\"stdoutBasesixtyfour\"]\n            else \"\",\n            \"stderr\": base64.b64decode(resp[\"stderrBasesixtyfour\"]).decode()\n            if resp[\"stderrBasesixtyfour\"]\n            else \"\",\n            \"fileLinks\": resp[\"fileLinks\"],\n            \"exitCode\": resp[\"exitCode\"],\n        }\n    async def _arun(self, query: str) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/bearly/tool.html"}
{"id": "68c677afece8-3", "text": "\"\"\"Use the tool asynchronously.\"\"\"\n        raise NotImplementedError(\"custom_search does not support async\")\n[docs]    def add_file(self, source_path: str, target_path: str, description: str) -> None:\n        if target_path in self.files:\n            raise ValueError(\"target_path already exists\")\n        if not Path(source_path).exists():\n            raise ValueError(\"source_path does not exist\")\n        self.files[target_path] = FileInfo(\n            target_path=target_path, source_path=source_path, description=description\n        )\n[docs]    def clear_files(self) -> None:\n        self.files = {}\n    # TODO: this is because we can't have a dynamic description\n    #  because of the base pydantic class\n[docs]    def as_tool(self) -> Tool:\n        return Tool.from_function(\n            func=self._run,\n            name=self.name,\n            description=self.description,\n            args_schema=self.args_schema,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/bearly/tool.html"}
{"id": "bba6e8acfab4-0", "text": "Source code for langchain.tools.azure_cognitive_services.text2speech\nfrom __future__ import annotations\nimport logging\nimport tempfile\nfrom typing import Any, Dict, Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.tools.base import BaseTool\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class AzureCogsText2SpeechTool(BaseTool):\n    \"\"\"Tool that queries the Azure Cognitive Services Text2Speech API.\n    In order to set this up, follow instructions at:\n    https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/get-started-text-to-speech?pivots=programming-language-python\n    \"\"\"\n    azure_cogs_key: str = \"\"  #: :meta private:\n    azure_cogs_region: str = \"\"  #: :meta private:\n    speech_language: str = \"en-US\"  #: :meta private:\n    speech_config: Any  #: :meta private:\n    name: str = \"azure_cognitive_services_text2speech\"\n    description: str = (\n        \"A wrapper around Azure Cognitive Services Text2Speech. \"\n        \"Useful for when you need to convert text to speech. \"\n    )\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and endpoint exists in environment.\"\"\"\n        azure_cogs_key = get_from_dict_or_env(\n            values, \"azure_cogs_key\", \"AZURE_COGS_KEY\"\n        )\n        azure_cogs_region = get_from_dict_or_env(\n            values, \"azure_cogs_region\", \"AZURE_COGS_REGION\"\n        )\n        try:\n            import azure.cognitiveservices.speech as speechsdk", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html"}
{"id": "bba6e8acfab4-1", "text": ")\n        try:\n            import azure.cognitiveservices.speech as speechsdk\n            values[\"speech_config\"] = speechsdk.SpeechConfig(\n                subscription=azure_cogs_key, region=azure_cogs_region\n            )\n        except ImportError:\n            raise ImportError(\n                \"azure-cognitiveservices-speech is not installed. \"\n                \"Run `pip install azure-cognitiveservices-speech` to install.\"\n            )\n        return values\n    def _text2speech(self, text: str, speech_language: str) -> str:\n        try:\n            import azure.cognitiveservices.speech as speechsdk\n        except ImportError:\n            pass\n        self.speech_config.speech_synthesis_language = speech_language\n        speech_synthesizer = speechsdk.SpeechSynthesizer(\n            speech_config=self.speech_config, audio_config=None\n        )\n        result = speech_synthesizer.speak_text(text)\n        if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:\n            stream = speechsdk.AudioDataStream(result)\n            with tempfile.NamedTemporaryFile(\n                mode=\"wb\", suffix=\".wav\", delete=False\n            ) as f:\n                stream.save_to_wav_file(f.name)\n            return f.name\n        elif result.reason == speechsdk.ResultReason.Canceled:\n            cancellation_details = result.cancellation_details\n            logger.debug(f\"Speech synthesis canceled: {cancellation_details.reason}\")\n            if cancellation_details.reason == speechsdk.CancellationReason.Error:\n                raise RuntimeError(\n                    f\"Speech synthesis error: {cancellation_details.error_details}\"\n                )\n            return \"Speech synthesis canceled.\"\n        else:\n            return f\"Speech synthesis failed: {result.reason}\"\n    def _run(\n        self,\n        query: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html"}
{"id": "bba6e8acfab4-2", "text": "def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        try:\n            speech_file = self._text2speech(query, self.speech_language)\n            return speech_file\n        except Exception as e:\n            raise RuntimeError(f\"Error while running AzureCogsText2SpeechTool: {e}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html"}
{"id": "c179588460a8-0", "text": "Source code for langchain.tools.azure_cognitive_services.image_analysis\nfrom __future__ import annotations\nimport logging\nfrom typing import Any, Dict, Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.tools.azure_cognitive_services.utils import detect_file_src_type\nfrom langchain.tools.base import BaseTool\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class AzureCogsImageAnalysisTool(BaseTool):\n    \"\"\"Tool that queries the Azure Cognitive Services Image Analysis API.\n    In order to set this up, follow instructions at:\n    https://learn.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts-sdk/image-analysis-client-library-40\n    \"\"\"\n    azure_cogs_key: str = \"\"  #: :meta private:\n    azure_cogs_endpoint: str = \"\"  #: :meta private:\n    vision_service: Any  #: :meta private:\n    analysis_options: Any  #: :meta private:\n    name: str = \"azure_cognitive_services_image_analysis\"\n    description: str = (\n        \"A wrapper around Azure Cognitive Services Image Analysis. \"\n        \"Useful for when you need to analyze images. \"\n        \"Input should be a url to an image.\"\n    )\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and endpoint exists in environment.\"\"\"\n        azure_cogs_key = get_from_dict_or_env(\n            values, \"azure_cogs_key\", \"AZURE_COGS_KEY\"\n        )\n        azure_cogs_endpoint = get_from_dict_or_env(\n            values, \"azure_cogs_endpoint\", \"AZURE_COGS_ENDPOINT\"\n        )\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html"}
{"id": "c179588460a8-1", "text": ")\n        try:\n            import azure.ai.vision as sdk\n            values[\"vision_service\"] = sdk.VisionServiceOptions(\n                endpoint=azure_cogs_endpoint, key=azure_cogs_key\n            )\n            values[\"analysis_options\"] = sdk.ImageAnalysisOptions()\n            values[\"analysis_options\"].features = (\n                sdk.ImageAnalysisFeature.CAPTION\n                | sdk.ImageAnalysisFeature.OBJECTS\n                | sdk.ImageAnalysisFeature.TAGS\n                | sdk.ImageAnalysisFeature.TEXT\n            )\n        except ImportError:\n            raise ImportError(\n                \"azure-ai-vision is not installed. \"\n                \"Run `pip install azure-ai-vision` to install.\"\n            )\n        return values\n    def _image_analysis(self, image_path: str) -> Dict:\n        try:\n            import azure.ai.vision as sdk\n        except ImportError:\n            pass\n        image_src_type = detect_file_src_type(image_path)\n        if image_src_type == \"local\":\n            vision_source = sdk.VisionSource(filename=image_path)\n        elif image_src_type == \"remote\":\n            vision_source = sdk.VisionSource(url=image_path)\n        else:\n            raise ValueError(f\"Invalid image path: {image_path}\")\n        image_analyzer = sdk.ImageAnalyzer(\n            self.vision_service, vision_source, self.analysis_options\n        )\n        result = image_analyzer.analyze()\n        res_dict = {}\n        if result.reason == sdk.ImageAnalysisResultReason.ANALYZED:\n            if result.caption is not None:\n                res_dict[\"caption\"] = result.caption.content\n            if result.objects is not None:\n                res_dict[\"objects\"] = [obj.name for obj in result.objects]\n            if result.tags is not None:\n                res_dict[\"tags\"] = [tag.name for tag in result.tags]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html"}
{"id": "c179588460a8-2", "text": "res_dict[\"tags\"] = [tag.name for tag in result.tags]\n            if result.text is not None:\n                res_dict[\"text\"] = [line.content for line in result.text.lines]\n        else:\n            error_details = sdk.ImageAnalysisErrorDetails.from_result(result)\n            raise RuntimeError(\n                f\"Image analysis failed.\\n\"\n                f\"Reason: {error_details.reason}\\n\"\n                f\"Details: {error_details.message}\"\n            )\n        return res_dict\n    def _format_image_analysis_result(self, image_analysis_result: Dict) -> str:\n        formatted_result = []\n        if \"caption\" in image_analysis_result:\n            formatted_result.append(\"Caption: \" + image_analysis_result[\"caption\"])\n        if (\n            \"objects\" in image_analysis_result\n            and len(image_analysis_result[\"objects\"]) > 0\n        ):\n            formatted_result.append(\n                \"Objects: \" + \", \".join(image_analysis_result[\"objects\"])\n            )\n        if \"tags\" in image_analysis_result and len(image_analysis_result[\"tags\"]) > 0:\n            formatted_result.append(\"Tags: \" + \", \".join(image_analysis_result[\"tags\"]))\n        if \"text\" in image_analysis_result and len(image_analysis_result[\"text\"]) > 0:\n            formatted_result.append(\"Text: \" + \", \".join(image_analysis_result[\"text\"]))\n        return \"\\n\".join(formatted_result)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        try:\n            image_analysis_result = self._image_analysis(query)\n            if not image_analysis_result:\n                return \"No good image analysis result was found\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html"}
{"id": "c179588460a8-3", "text": "if not image_analysis_result:\n                return \"No good image analysis result was found\"\n            return self._format_image_analysis_result(image_analysis_result)\n        except Exception as e:\n            raise RuntimeError(f\"Error while running AzureCogsImageAnalysisTool: {e}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html"}
{"id": "57499370aff0-0", "text": "Source code for langchain.tools.azure_cognitive_services.utils\nimport os\nimport tempfile\nfrom urllib.parse import urlparse\nimport requests\n[docs]def detect_file_src_type(file_path: str) -> str:\n    \"\"\"Detect if the file is local or remote.\"\"\"\n    if os.path.isfile(file_path):\n        return \"local\"\n    parsed_url = urlparse(file_path)\n    if parsed_url.scheme and parsed_url.netloc:\n        return \"remote\"\n    return \"invalid\"\n[docs]def download_audio_from_url(audio_url: str) -> str:\n    \"\"\"Download audio from url to local.\"\"\"\n    ext = audio_url.split(\".\")[-1]\n    response = requests.get(audio_url, stream=True)\n    response.raise_for_status()\n    with tempfile.NamedTemporaryFile(mode=\"wb\", suffix=f\".{ext}\", delete=False) as f:\n        for chunk in response.iter_content(chunk_size=8192):\n            f.write(chunk)\n    return f.name", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/utils.html"}
{"id": "73981b62e4c1-0", "text": "Source code for langchain.tools.azure_cognitive_services.form_recognizer\nfrom __future__ import annotations\nimport logging\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.tools.azure_cognitive_services.utils import detect_file_src_type\nfrom langchain.tools.base import BaseTool\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class AzureCogsFormRecognizerTool(BaseTool):\n    \"\"\"Tool that queries the Azure Cognitive Services Form Recognizer API.\n    In order to set this up, follow instructions at:\n    https://learn.microsoft.com/en-us/azure/applied-ai-services/form-recognizer/quickstarts/get-started-sdks-rest-api?view=form-recog-3.0.0&pivots=programming-language-python\n    \"\"\"\n    azure_cogs_key: str = \"\"  #: :meta private:\n    azure_cogs_endpoint: str = \"\"  #: :meta private:\n    doc_analysis_client: Any  #: :meta private:\n    name: str = \"azure_cognitive_services_form_recognizer\"\n    description: str = (\n        \"A wrapper around Azure Cognitive Services Form Recognizer. \"\n        \"Useful for when you need to \"\n        \"extract text, tables, and key-value pairs from documents. \"\n        \"Input should be a url to a document.\"\n    )\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and endpoint exists in environment.\"\"\"\n        azure_cogs_key = get_from_dict_or_env(\n            values, \"azure_cogs_key\", \"AZURE_COGS_KEY\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html"}
{"id": "73981b62e4c1-1", "text": ")\n        azure_cogs_endpoint = get_from_dict_or_env(\n            values, \"azure_cogs_endpoint\", \"AZURE_COGS_ENDPOINT\"\n        )\n        try:\n            from azure.ai.formrecognizer import DocumentAnalysisClient\n            from azure.core.credentials import AzureKeyCredential\n            values[\"doc_analysis_client\"] = DocumentAnalysisClient(\n                endpoint=azure_cogs_endpoint,\n                credential=AzureKeyCredential(azure_cogs_key),\n            )\n        except ImportError:\n            raise ImportError(\n                \"azure-ai-formrecognizer is not installed. \"\n                \"Run `pip install azure-ai-formrecognizer` to install.\"\n            )\n        return values\n    def _parse_tables(self, tables: List[Any]) -> List[Any]:\n        result = []\n        for table in tables:\n            rc, cc = table.row_count, table.column_count\n            _table = [[\"\" for _ in range(cc)] for _ in range(rc)]\n            for cell in table.cells:\n                _table[cell.row_index][cell.column_index] = cell.content\n            result.append(_table)\n        return result\n    def _parse_kv_pairs(self, kv_pairs: List[Any]) -> List[Any]:\n        result = []\n        for kv_pair in kv_pairs:\n            key = kv_pair.key.content if kv_pair.key else \"\"\n            value = kv_pair.value.content if kv_pair.value else \"\"\n            result.append((key, value))\n        return result\n    def _document_analysis(self, document_path: str) -> Dict:\n        document_src_type = detect_file_src_type(document_path)\n        if document_src_type == \"local\":\n            with open(document_path, \"rb\") as document:\n                poller = self.doc_analysis_client.begin_analyze_document(\n                    \"prebuilt-document\", document\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html"}
{"id": "73981b62e4c1-2", "text": "\"prebuilt-document\", document\n                )\n        elif document_src_type == \"remote\":\n            poller = self.doc_analysis_client.begin_analyze_document_from_url(\n                \"prebuilt-document\", document_path\n            )\n        else:\n            raise ValueError(f\"Invalid document path: {document_path}\")\n        result = poller.result()\n        res_dict = {}\n        if result.content is not None:\n            res_dict[\"content\"] = result.content\n        if result.tables is not None:\n            res_dict[\"tables\"] = self._parse_tables(result.tables)\n        if result.key_value_pairs is not None:\n            res_dict[\"key_value_pairs\"] = self._parse_kv_pairs(result.key_value_pairs)\n        return res_dict\n    def _format_document_analysis_result(self, document_analysis_result: Dict) -> str:\n        formatted_result = []\n        if \"content\" in document_analysis_result:\n            formatted_result.append(\n                f\"Content: {document_analysis_result['content']}\".replace(\"\\n\", \" \")\n            )\n        if \"tables\" in document_analysis_result:\n            for i, table in enumerate(document_analysis_result[\"tables\"]):\n                formatted_result.append(f\"Table {i}: {table}\".replace(\"\\n\", \" \"))\n        if \"key_value_pairs\" in document_analysis_result:\n            for kv_pair in document_analysis_result[\"key_value_pairs\"]:\n                formatted_result.append(\n                    f\"{kv_pair[0]}: {kv_pair[1]}\".replace(\"\\n\", \" \")\n                )\n        return \"\\n\".join(formatted_result)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html"}
{"id": "73981b62e4c1-3", "text": ") -> str:\n        \"\"\"Use the tool.\"\"\"\n        try:\n            document_analysis_result = self._document_analysis(query)\n            if not document_analysis_result:\n                return \"No good document analysis result was found\"\n            return self._format_document_analysis_result(document_analysis_result)\n        except Exception as e:\n            raise RuntimeError(f\"Error while running AzureCogsFormRecognizerTool: {e}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html"}
{"id": "b3d4eace6ccc-0", "text": "Source code for langchain.tools.azure_cognitive_services.speech2text\nfrom __future__ import annotations\nimport logging\nimport time\nfrom typing import Any, Dict, Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.tools.azure_cognitive_services.utils import (\n    detect_file_src_type,\n    download_audio_from_url,\n)\nfrom langchain.tools.base import BaseTool\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class AzureCogsSpeech2TextTool(BaseTool):\n    \"\"\"Tool that queries the Azure Cognitive Services Speech2Text API.\n    In order to set this up, follow instructions at:\n    https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/get-started-speech-to-text?pivots=programming-language-python\n    \"\"\"\n    azure_cogs_key: str = \"\"  #: :meta private:\n    azure_cogs_region: str = \"\"  #: :meta private:\n    speech_language: str = \"en-US\"  #: :meta private:\n    speech_config: Any  #: :meta private:\n    name: str = \"azure_cognitive_services_speech2text\"\n    description: str = (\n        \"A wrapper around Azure Cognitive Services Speech2Text. \"\n        \"Useful for when you need to transcribe audio to text. \"\n        \"Input should be a url to an audio file.\"\n    )\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and endpoint exists in environment.\"\"\"\n        azure_cogs_key = get_from_dict_or_env(\n            values, \"azure_cogs_key\", \"AZURE_COGS_KEY\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html"}
{"id": "b3d4eace6ccc-1", "text": ")\n        azure_cogs_region = get_from_dict_or_env(\n            values, \"azure_cogs_region\", \"AZURE_COGS_REGION\"\n        )\n        try:\n            import azure.cognitiveservices.speech as speechsdk\n            values[\"speech_config\"] = speechsdk.SpeechConfig(\n                subscription=azure_cogs_key, region=azure_cogs_region\n            )\n        except ImportError:\n            raise ImportError(\n                \"azure-cognitiveservices-speech is not installed. \"\n                \"Run `pip install azure-cognitiveservices-speech` to install.\"\n            )\n        return values\n    def _continuous_recognize(self, speech_recognizer: Any) -> str:\n        done = False\n        text = \"\"\n        def stop_cb(evt: Any) -> None:\n            \"\"\"callback that stop continuous recognition\"\"\"\n            speech_recognizer.stop_continuous_recognition_async()\n            nonlocal done\n            done = True\n        def retrieve_cb(evt: Any) -> None:\n            \"\"\"callback that retrieves the intermediate recognition results\"\"\"\n            nonlocal text\n            text += evt.result.text\n        # retrieve text on recognized events\n        speech_recognizer.recognized.connect(retrieve_cb)\n        # stop continuous recognition on either session stopped or canceled events\n        speech_recognizer.session_stopped.connect(stop_cb)\n        speech_recognizer.canceled.connect(stop_cb)\n        # Start continuous speech recognition\n        speech_recognizer.start_continuous_recognition_async()\n        while not done:\n            time.sleep(0.5)\n        return text\n    def _speech2text(self, audio_path: str, speech_language: str) -> str:\n        try:\n            import azure.cognitiveservices.speech as speechsdk\n        except ImportError:\n            pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html"}
{"id": "b3d4eace6ccc-2", "text": "except ImportError:\n            pass\n        audio_src_type = detect_file_src_type(audio_path)\n        if audio_src_type == \"local\":\n            audio_config = speechsdk.AudioConfig(filename=audio_path)\n        elif audio_src_type == \"remote\":\n            tmp_audio_path = download_audio_from_url(audio_path)\n            audio_config = speechsdk.AudioConfig(filename=tmp_audio_path)\n        else:\n            raise ValueError(f\"Invalid audio path: {audio_path}\")\n        self.speech_config.speech_recognition_language = speech_language\n        speech_recognizer = speechsdk.SpeechRecognizer(self.speech_config, audio_config)\n        return self._continuous_recognize(speech_recognizer)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        try:\n            text = self._speech2text(query, self.speech_language)\n            return text\n        except Exception as e:\n            raise RuntimeError(f\"Error while running AzureCogsSpeech2TextTool: {e}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html"}
{"id": "fa6806bed0f2-0", "text": "Source code for langchain.tools.searx_search.tool\n\"\"\"Tool for the SearxNG search API.\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import Extra\nfrom langchain.tools.base import BaseTool, Field\nfrom langchain.utilities.searx_search import SearxSearchWrapper\n[docs]class SearxSearchRun(BaseTool):\n    \"\"\"Tool that queries a Searx instance.\"\"\"\n    name: str = \"searx_search\"\n    description: str = (\n        \"A meta search engine.\"\n        \"Useful for when you need to answer questions about current events.\"\n        \"Input should be a search query.\"\n    )\n    wrapper: SearxSearchWrapper\n    kwargs: dict = Field(default_factory=dict)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return self.wrapper.run(query, **self.kwargs)\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        return await self.wrapper.arun(query, **self.kwargs)\n[docs]class SearxSearchResults(BaseTool):\n    \"\"\"Tool that queries a Searx instance and gets back json.\"\"\"\n    name: str = \"Searx-Search-Results\"\n    description: str = (\n        \"A meta search engine.\"\n        \"Useful for when you need to answer questions about current events.\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/searx_search/tool.html"}
{"id": "fa6806bed0f2-1", "text": "\"Useful for when you need to answer questions about current events.\"\n        \"Input should be a search query. Output is a JSON array of the query results\"\n    )\n    wrapper: SearxSearchWrapper\n    num_results: int = 4\n    kwargs: dict = Field(default_factory=dict)\n    class Config:\n        \"\"\"Pydantic config.\"\"\"\n        extra = Extra.allow\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return str(self.wrapper.results(query, self.num_results, **self.kwargs))\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        return (\n            await self.wrapper.aresults(query, self.num_results, **self.kwargs)\n        ).__str__()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/searx_search/tool.html"}
{"id": "9ae102c83393-0", "text": "Source code for langchain.tools.google_cloud.texttospeech\nfrom __future__ import annotations\nimport tempfile\nfrom typing import TYPE_CHECKING, Any, Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.vertexai import get_client_info\nif TYPE_CHECKING:\n    from google.cloud import texttospeech\ndef _import_google_cloud_texttospeech() -> Any:\n    try:\n        from google.cloud import texttospeech\n    except ImportError as e:\n        raise ImportError(\n            \"Cannot import google.cloud.texttospeech, please install \"\n            \"`pip install google-cloud-texttospeech`.\"\n        ) from e\n    return texttospeech\ndef _encoding_file_extension_map(encoding: texttospeech.AudioEncoding) -> Optional[str]:\n    texttospeech = _import_google_cloud_texttospeech()\n    ENCODING_FILE_EXTENSION_MAP = {\n        texttospeech.AudioEncoding.LINEAR16: \".wav\",\n        texttospeech.AudioEncoding.MP3: \".mp3\",\n        texttospeech.AudioEncoding.OGG_OPUS: \".ogg\",\n        texttospeech.AudioEncoding.MULAW: \".wav\",\n        texttospeech.AudioEncoding.ALAW: \".wav\",\n    }\n    return ENCODING_FILE_EXTENSION_MAP.get(encoding)\n[docs]class GoogleCloudTextToSpeechTool(BaseTool):\n    \"\"\"Tool that queries the Google Cloud Text to Speech API.\n    In order to set this up, follow instructions at:\n    https://cloud.google.com/text-to-speech/docs/before-you-begin\n    \"\"\"\n    name: str = \"google_cloud_texttospeech\"\n    description: str = (\n        \"A wrapper around Google Cloud Text-to-Speech. \"\n        \"Useful for when you need to synthesize audio from text. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/google_cloud/texttospeech.html"}
{"id": "9ae102c83393-1", "text": "\"Useful for when you need to synthesize audio from text. \"\n        \"It supports multiple languages, including English, German, Polish, \"\n        \"Spanish, Italian, French, Portuguese, and Hindi. \"\n    )\n    _client: Any\n    def __init__(self, **kwargs: Any) -> None:\n        \"\"\"Initializes private fields.\"\"\"\n        texttospeech = _import_google_cloud_texttospeech()\n        super().__init__(**kwargs)\n        self._client = texttospeech.TextToSpeechClient(\n            client_info=get_client_info(module=\"text-to-speech\")\n        )\n    def _run(\n        self,\n        input_text: str,\n        language_code: str = \"en-US\",\n        ssml_gender: Optional[texttospeech.SsmlVoiceGender] = None,\n        audio_encoding: Optional[texttospeech.AudioEncoding] = None,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        texttospeech = _import_google_cloud_texttospeech()\n        ssml_gender = ssml_gender or texttospeech.SsmlVoiceGender.NEUTRAL\n        audio_encoding = audio_encoding or texttospeech.AudioEncoding.MP3\n        response = self._client.synthesize_speech(\n            input=texttospeech.SynthesisInput(text=input_text),\n            voice=texttospeech.VoiceSelectionParams(\n                language_code=language_code, ssml_gender=ssml_gender\n            ),\n            audio_config=texttospeech.AudioConfig(audio_encoding=audio_encoding),\n        )\n        suffix = _encoding_file_extension_map(audio_encoding)\n        with tempfile.NamedTemporaryFile(mode=\"bx\", suffix=suffix, delete=False) as f:\n            f.write(response.audio_content)\n        return f.name", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/google_cloud/texttospeech.html"}
{"id": "6dfd76183f01-0", "text": "Source code for langchain.tools.dataforseo_api_search.tool\n\"\"\"Tool for the DataForSeo SERP API.\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.dataforseo_api_search import DataForSeoAPIWrapper\n[docs]class DataForSeoAPISearchRun(BaseTool):\n    \"\"\"Tool that queries the DataForSeo Google search API.\"\"\"\n    name: str = \"dataforseo_api_search\"\n    description: str = (\n        \"A robust Google Search API provided by DataForSeo.\"\n        \"This tool is handy when you need information about trending topics \"\n        \"or current events.\"\n    )\n    api_wrapper: DataForSeoAPIWrapper\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return str(self.api_wrapper.run(query))\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        return (await self.api_wrapper.arun(query)).__str__()\n[docs]class DataForSeoAPISearchResults(BaseTool):\n    \"\"\"Tool that queries the DataForSeo Google Search API\n    and get back json.\"\"\"\n    name: str = \"DataForSeo-Results-JSON\"\n    description: str = (\n        \"A comprehensive Google Search API provided by DataForSeo.\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/dataforseo_api_search/tool.html"}
{"id": "6dfd76183f01-1", "text": "\"A comprehensive Google Search API provided by DataForSeo.\"\n        \"This tool is useful for obtaining real-time data on current events \"\n        \"or popular searches.\"\n        \"The input should be a search query and the output is a JSON object \"\n        \"of the query results.\"\n    )\n    api_wrapper: DataForSeoAPIWrapper = Field(default_factory=DataForSeoAPIWrapper)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return str(self.api_wrapper.results(query))\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        return (await self.api_wrapper.aresults(query)).__str__()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/dataforseo_api_search/tool.html"}
{"id": "4fbc5d20edd8-0", "text": "Source code for langchain.tools.shell.tool\nimport asyncio\nimport platform\nimport warnings\nfrom typing import Any, List, Optional, Type, Union\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field, root_validator\nfrom langchain.tools.base import BaseTool\n[docs]class ShellInput(BaseModel):\n    \"\"\"Commands for the Bash Shell tool.\"\"\"\n    commands: Union[str, List[str]] = Field(\n        ...,\n        description=\"List of shell commands to run. Deserialized using json.loads\",\n    )\n    \"\"\"List of shell commands to run.\"\"\"\n    @root_validator\n    def _validate_commands(cls, values: dict) -> dict:\n        \"\"\"Validate commands.\"\"\"\n        # TODO: Add real validators\n        commands = values.get(\"commands\")\n        if not isinstance(commands, list):\n            values[\"commands\"] = [commands]\n        # Warn that the bash tool is not safe\n        warnings.warn(\n            \"The shell tool has no safeguards by default. Use at your own risk.\"\n        )\n        return values\ndef _get_default_bash_process() -> Any:\n    \"\"\"Get default bash process.\"\"\"\n    try:\n        from langchain_experimental.llm_bash.bash import BashProcess\n    except ImportError:\n        raise ImportError(\n            \"BashProcess has been moved to langchain experimental.\"\n            \"To use this tool, install langchain-experimental \"\n            \"with `pip install langchain-experimental`.\"\n        )\n    return BashProcess(return_err_output=True)\ndef _get_platform() -> str:\n    \"\"\"Get platform.\"\"\"\n    system = platform.system()\n    if system == \"Darwin\":\n        return \"MacOS\"\n    return system", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html"}
{"id": "4fbc5d20edd8-1", "text": "if system == \"Darwin\":\n        return \"MacOS\"\n    return system\n[docs]class ShellTool(BaseTool):\n    \"\"\"Tool to run shell commands.\"\"\"\n    process: Any = Field(default_factory=_get_default_bash_process)\n    \"\"\"Bash process to run commands.\"\"\"\n    name: str = \"terminal\"\n    \"\"\"Name of tool.\"\"\"\n    description: str = f\"Run shell commands on this {_get_platform()} machine.\"\n    \"\"\"Description of tool.\"\"\"\n    args_schema: Type[BaseModel] = ShellInput\n    \"\"\"Schema for input arguments.\"\"\"\n    def _run(\n        self,\n        commands: Union[str, List[str]],\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Run commands and return final output.\"\"\"\n        return self.process.run(commands)\n    async def _arun(\n        self,\n        commands: Union[str, List[str]],\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Run commands asynchronously and return final output.\"\"\"\n        return await asyncio.get_event_loop().run_in_executor(\n            None, self.process.run, commands\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html"}
{"id": "dc8ff6bfd0e4-0", "text": "Source code for langchain.tools.arxiv.tool\n\"\"\"Tool for the Arxiv API.\"\"\"\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.arxiv import ArxivAPIWrapper\n[docs]class ArxivInput(BaseModel):\n    query: str = Field(description=\"search query to look up\")\n[docs]class ArxivQueryRun(BaseTool):\n    \"\"\"Tool that searches the Arxiv API.\"\"\"\n    name: str = \"arxiv\"\n    description: str = (\n        \"A wrapper around Arxiv.org \"\n        \"Useful for when you need to answer questions about Physics, Mathematics, \"\n        \"Computer Science, Quantitative Biology, Quantitative Finance, Statistics, \"\n        \"Electrical Engineering, and Economics \"\n        \"from scientific articles on arxiv.org. \"\n        \"Input should be a search query.\"\n    )\n    api_wrapper: ArxivAPIWrapper = Field(default_factory=ArxivAPIWrapper)\n    args_schema: Type[BaseModel] = ArxivInput\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the Arxiv tool.\"\"\"\n        return self.api_wrapper.run(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/arxiv/tool.html"}
{"id": "3bd838f78c59-0", "text": "Source code for langchain.tools.vectorstore.tool\n\"\"\"Tools for interacting with vectorstores.\"\"\"\nimport json\nfrom typing import Any, Dict, Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.llms.openai import OpenAI\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.tools.base import BaseTool\n[docs]class BaseVectorStoreTool(BaseModel):\n    \"\"\"Base class for tools that use a VectorStore.\"\"\"\n    vectorstore: VectorStore = Field(exclude=True)\n    llm: BaseLanguageModel = Field(default_factory=lambda: OpenAI(temperature=0))\n    class Config(BaseTool.Config):\n        pass\ndef _create_description_from_template(values: Dict[str, Any]) -> Dict[str, Any]:\n    values[\"description\"] = values[\"template\"].format(name=values[\"name\"])\n    return values\n[docs]class VectorStoreQATool(BaseVectorStoreTool, BaseTool):\n    \"\"\"Tool for the VectorDBQA chain. To be initialized with name and chain.\"\"\"\n[docs]    @staticmethod\n    def get_description(name: str, description: str) -> str:\n        template: str = (\n            \"Useful for when you need to answer questions about {name}. \"\n            \"Whenever you need information about {description} \"\n            \"you should ALWAYS use this. \"\n            \"Input should be a fully formed question.\"\n        )\n        return template.format(name=name, description=description)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html"}
{"id": "3bd838f78c59-1", "text": ") -> str:\n        \"\"\"Use the tool.\"\"\"\n        from langchain.chains.retrieval_qa.base import RetrievalQA\n        chain = RetrievalQA.from_chain_type(\n            self.llm, retriever=self.vectorstore.as_retriever()\n        )\n        return chain.run(\n            query, callbacks=run_manager.get_child() if run_manager else None\n        )\n[docs]class VectorStoreQAWithSourcesTool(BaseVectorStoreTool, BaseTool):\n    \"\"\"Tool for the VectorDBQAWithSources chain.\"\"\"\n[docs]    @staticmethod\n    def get_description(name: str, description: str) -> str:\n        template: str = (\n            \"Useful for when you need to answer questions about {name} and the sources \"\n            \"used to construct the answer. \"\n            \"Whenever you need information about {description} \"\n            \"you should ALWAYS use this. \"\n            \" Input should be a fully formed question. \"\n            \"Output is a json serialized dictionary with keys `answer` and `sources`. \"\n            \"Only use this tool if the user explicitly asks for sources.\"\n        )\n        return template.format(name=name, description=description)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        from langchain.chains.qa_with_sources.retrieval import (\n            RetrievalQAWithSourcesChain,\n        )\n        chain = RetrievalQAWithSourcesChain.from_chain_type(\n            self.llm, retriever=self.vectorstore.as_retriever()\n        )\n        return json.dumps(\n            chain(\n                {chain.question_key: query},\n                return_only_outputs=True,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html"}
{"id": "3bd838f78c59-2", "text": "chain(\n                {chain.question_key: query},\n                return_only_outputs=True,\n                callbacks=run_manager.get_child() if run_manager else None,\n            )\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html"}
{"id": "4ab265332186-0", "text": "Source code for langchain.tools.tavily_search.tool\n\"\"\"Tool for the Tavily search API.\"\"\"\nfrom typing import Dict, List, Optional, Type, Union\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.tavily_search import TavilySearchAPIWrapper\n[docs]class TavilyInput(BaseModel):\n    query: str = Field(description=\"search query to look up\")\n[docs]class TavilySearchResults(BaseTool):\n    \"\"\"Tool that queries the Tavily Search API and gets back json.\"\"\"\n    name: str = \"tavily_search_results_json\"\n    description: str = (\n        \"A search engine optimized for comprehensive, accurate, and trusted results. \"\n        \"Useful for when you need to answer questions about current events. \"\n        \"Input should be a search query.\"\n    )\n    api_wrapper: TavilySearchAPIWrapper\n    max_results: int = 5\n    args_schema: Type[BaseModel] = TavilyInput\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> Union[List[Dict], str]:\n        \"\"\"Use the tool.\"\"\"\n        try:\n            return self.api_wrapper.results(\n                query,\n                self.max_results,\n            )\n        except Exception as e:\n            return repr(e)\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> Union[List[Dict], str]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/tavily_search/tool.html"}
{"id": "4ab265332186-1", "text": ") -> Union[List[Dict], str]:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        try:\n            return await self.api_wrapper.results_async(\n                query,\n                self.max_results,\n            )\n        except Exception as e:\n            return repr(e)\n[docs]class TavilyAnswer(BaseTool):\n    \"\"\"Tool that queries the Tavily Search API and gets back an answer.\"\"\"\n    name: str = \"tavily_answer\"\n    description: str = (\n        \"A search engine optimized for comprehensive, accurate, and trusted results. \"\n        \"Useful for when you need to answer questions about current events. \"\n        \"Input should be a search query. \"\n        \"This returns only the answer - not the original source data.\"\n    )\n    api_wrapper: TavilySearchAPIWrapper\n    args_schema: Type[BaseModel] = TavilyInput\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> Union[List[Dict], str]:\n        \"\"\"Use the tool.\"\"\"\n        try:\n            return self.api_wrapper.raw_results(\n                query,\n                max_results=5,\n                include_answer=True,\n                search_depth=\"basic\",\n            )[\"answer\"]\n        except Exception as e:\n            return repr(e)\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> Union[List[Dict], str]:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        try:\n            result = await self.api_wrapper.raw_results_async(\n                query,\n                max_results=5,\n                include_answer=True,\n                search_depth=\"basic\",\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/tavily_search/tool.html"}
{"id": "4ab265332186-2", "text": "include_answer=True,\n                search_depth=\"basic\",\n            )\n            return result[\"answer\"]\n        except Exception as e:\n            return repr(e)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/tavily_search/tool.html"}
{"id": "8f83d25e35a0-0", "text": "Source code for langchain.tools.brave_search.tool\nfrom __future__ import annotations\nfrom typing import Any, Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.brave_search import BraveSearchWrapper\n[docs]class BraveSearch(BaseTool):\n    \"\"\"Tool that queries the BraveSearch.\"\"\"\n    name: str = \"brave_search\"\n    description: str = (\n        \"a search engine. \"\n        \"useful for when you need to answer questions about current events.\"\n        \" input should be a search query.\"\n    )\n    search_wrapper: BraveSearchWrapper\n[docs]    @classmethod\n    def from_api_key(\n        cls, api_key: str, search_kwargs: Optional[dict] = None, **kwargs: Any\n    ) -> BraveSearch:\n        \"\"\"Create a tool from an api key.\n        Args:\n            api_key: The api key to use.\n            search_kwargs: Any additional kwargs to pass to the search wrapper.\n            **kwargs: Any additional kwargs to pass to the tool.\n        Returns:\n            A tool.\n        \"\"\"\n        wrapper = BraveSearchWrapper(api_key=api_key, search_kwargs=search_kwargs or {})\n        return cls(search_wrapper=wrapper, **kwargs)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return self.search_wrapper.run(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/brave_search/tool.html"}
{"id": "10362b008378-0", "text": "Source code for langchain.tools.wolfram_alpha.tool\n\"\"\"Tool for the Wolfram Alpha API.\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.wolfram_alpha import WolframAlphaAPIWrapper\n[docs]class WolframAlphaQueryRun(BaseTool):\n    \"\"\"Tool that queries using the Wolfram Alpha SDK.\"\"\"\n    name: str = \"wolfram_alpha\"\n    description: str = (\n        \"A wrapper around Wolfram Alpha. \"\n        \"Useful for when you need to answer questions about Math, \"\n        \"Science, Technology, Culture, Society and Everyday Life. \"\n        \"Input should be a search query.\"\n    )\n    api_wrapper: WolframAlphaAPIWrapper\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the WolframAlpha tool.\"\"\"\n        return self.api_wrapper.run(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/wolfram_alpha/tool.html"}
{"id": "f9055a41460c-0", "text": "Source code for langchain.tools.multion.update_session\nimport asyncio\nfrom typing import TYPE_CHECKING, Optional, Type\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nif TYPE_CHECKING:\n    # This is for linting and IDE typehints\n    import multion\nelse:\n    try:\n        # We do this so pydantic can resolve the types when instantiating\n        import multion\n    except ImportError:\n        pass\n[docs]class UpdateSessionSchema(BaseModel):\n    \"\"\"Input for UpdateSessionTool.\"\"\"\n    sessionId: str = Field(\n        ...,\n        description=\"\"\"The sessionID, \n        received from one of the createSessions run before\"\"\",\n    )\n    query: str = Field(\n        ...,\n        description=\"The query to run in multion agent.\",\n    )\n    url: str = Field(\n        \"https://www.google.com/\",\n        description=\"\"\"The Url to run the agent at. \\\n        Note: accepts only secure links having https://\"\"\",\n    )\n[docs]class MultionUpdateSession(BaseTool):\n    \"\"\"Tool that updates an existing Multion Browser Window with provided fields.\n    Attributes:\n        name: The name of the tool. Default: \"update_multion_session\"\n        description: The description of the tool.\n        args_schema: The schema for the tool's arguments. Default: UpdateSessionSchema\n    \"\"\"\n    name: str = \"update_multion_session\"\n    description: str = \"\"\"Use this tool to update \\\nan existing corresponding Multion Browser Window with provided fields. \\\nNote: sessionId must be received from previous Browser window creation.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/multion/update_session.html"}
{"id": "f9055a41460c-1", "text": "Note: sessionId must be received from previous Browser window creation.\"\"\"\n    args_schema: Type[UpdateSessionSchema] = UpdateSessionSchema\n    sessionId: str = \"\"\n    def _run(\n        self,\n        sessionId: str,\n        query: str,\n        url: Optional[str] = \"https://www.google.com/\",\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> dict:\n        try:\n            try:\n                response = multion.update_session(\n                    sessionId, {\"input\": query, \"url\": url}\n                )\n                content = {\"sessionId\": sessionId, \"Response\": response[\"message\"]}\n                self.sessionId = sessionId\n                return content\n            except Exception as e:\n                print(f\"{e}, retrying...\")\n                return {\"error\": f\"{e}\", \"Response\": \"retrying...\"}\n        except Exception as e:\n            raise Exception(f\"An error occurred: {e}\")\n    async def _arun(\n        self,\n        sessionId: str,\n        query: str,\n        url: Optional[str] = \"https://www.google.com/\",\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> dict:\n        loop = asyncio.get_running_loop()\n        result = await loop.run_in_executor(None, self._run, sessionId, query, url)\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/multion/update_session.html"}
{"id": "90503e55fca2-0", "text": "Source code for langchain.tools.multion.close_session\nimport asyncio\nfrom typing import TYPE_CHECKING, Optional, Type\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nif TYPE_CHECKING:\n    # This is for linting and IDE typehints\n    import multion\nelse:\n    try:\n        # We do this so pydantic can resolve the types when instantiating\n        import multion\n    except ImportError:\n        pass\n[docs]class CloseSessionSchema(BaseModel):\n    \"\"\"Input for UpdateSessionTool.\"\"\"\n    sessionId: str = Field(\n        ...,\n        description=\"\"\"The sessionId, received from one of the createSessions \n        or updateSessions run before\"\"\",\n    )\n[docs]class MultionCloseSession(BaseTool):\n    \"\"\"Tool that closes an existing Multion Browser Window with provided fields.\n    Attributes:\n        name: The name of the tool. Default: \"close_multion_session\"\n        description: The description of the tool.\n        args_schema: The schema for the tool's arguments. Default: UpdateSessionSchema\n    \"\"\"\n    name: str = \"close_multion_session\"\n    description: str = \"\"\"Use this tool to close \\\nan existing corresponding Multion Browser Window with provided fields. \\\nNote: SessionId must be received from previous Browser window creation.\"\"\"\n    args_schema: Type[CloseSessionSchema] = CloseSessionSchema\n    sessionId: str = \"\"\n    def _run(\n        self,\n        sessionId: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> None:\n        try:\n            try:\n                multion.close_session(sessionId)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/multion/close_session.html"}
{"id": "90503e55fca2-1", "text": "try:\n            try:\n                multion.close_session(sessionId)\n            except Exception as e:\n                print(f\"{e}, retrying...\")\n        except Exception as e:\n            raise Exception(f\"An error occurred: {e}\")\n    async def _arun(\n        self,\n        sessionId: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> None:\n        loop = asyncio.get_running_loop()\n        await loop.run_in_executor(None, self._run, sessionId)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/multion/close_session.html"}
{"id": "0b7caf9990bd-0", "text": "Source code for langchain.tools.multion.create_session\nimport asyncio\nfrom typing import TYPE_CHECKING, Optional, Type\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nif TYPE_CHECKING:\n    # This is for linting and IDE typehints\n    import multion\nelse:\n    try:\n        # We do this so pydantic can resolve the types when instantiating\n        import multion\n    except ImportError:\n        pass\n[docs]class CreateSessionSchema(BaseModel):\n    \"\"\"Input for CreateSessionTool.\"\"\"\n    query: str = Field(\n        ...,\n        description=\"The query to run in multion agent.\",\n    )\n    url: str = Field(\n        \"https://www.google.com/\",\n        description=\"\"\"The Url to run the agent at. Note: accepts only secure \\\n            links having https://\"\"\",\n    )\n[docs]class MultionCreateSession(BaseTool):\n    \"\"\"Tool that creates a new Multion Browser Window with provided fields.\n    Attributes:\n        name: The name of the tool. Default: \"create_multion_session\"\n        description: The description of the tool.\n        args_schema: The schema for the tool's arguments.\n    \"\"\"\n    name: str = \"create_multion_session\"\n    description: str = \"\"\"\n        Create a new web browsing session based on a user's command or request. \\\n        The command should include the full info required for the session. \\\n        Also include an url (defaults to google.com if no better option) \\\n        to start the session. \\\n        Use this tool to create a new Browser Window with provided fields. \\", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/multion/create_session.html"}
{"id": "0b7caf9990bd-1", "text": "Use this tool to create a new Browser Window with provided fields. \\\n        Always the first step to run any activities that can be done using browser.\n        \"\"\"\n    args_schema: Type[CreateSessionSchema] = CreateSessionSchema\n    def _run(\n        self,\n        query: str,\n        url: Optional[str] = \"https://www.google.com/\",\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> dict:\n        try:\n            response = multion.new_session({\"input\": query, \"url\": url})\n            return {\n                \"sessionId\": response[\"session_id\"],\n                \"Response\": response[\"message\"],\n            }\n        except Exception as e:\n            raise Exception(f\"An error occurred: {e}\")\n    async def _arun(\n        self,\n        query: str,\n        url: Optional[str] = \"https://www.google.com/\",\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> dict:\n        loop = asyncio.get_running_loop()\n        result = await loop.run_in_executor(None, self._run, query, url)\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/multion/create_session.html"}
{"id": "5231524ad71d-0", "text": "Source code for langchain.tools.gitlab.tool\n\"\"\"\nThis tool allows agents to interact with the python-gitlab library\nand operate on a GitLab repository.\nTo use this tool, you must first set as environment variables:\n    GITLAB_PRIVATE_ACCESS_TOKEN\n    GITLAB_REPOSITORY -> format: {owner}/{repo}\n\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.gitlab import GitLabAPIWrapper\n[docs]class GitLabAction(BaseTool):\n    \"\"\"Tool for interacting with the GitLab API.\"\"\"\n    api_wrapper: GitLabAPIWrapper = Field(default_factory=GitLabAPIWrapper)\n    mode: str\n    name: str = \"\"\n    description: str = \"\"\n    def _run(\n        self,\n        instructions: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the GitLab API to run an operation.\"\"\"\n        return self.api_wrapper.run(self.mode, instructions)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/gitlab/tool.html"}
{"id": "5cf89e210966-0", "text": "Source code for langchain.tools.google_search.tool\n\"\"\"Tool for the Google search API.\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.google_search import GoogleSearchAPIWrapper\n[docs]class GoogleSearchRun(BaseTool):\n    \"\"\"Tool that queries the Google search API.\"\"\"\n    name: str = \"google_search\"\n    description: str = (\n        \"A wrapper around Google Search. \"\n        \"Useful for when you need to answer questions about current events. \"\n        \"Input should be a search query.\"\n    )\n    api_wrapper: GoogleSearchAPIWrapper\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return self.api_wrapper.run(query)\n[docs]class GoogleSearchResults(BaseTool):\n    \"\"\"Tool that queries the Google Search API and gets back json.\"\"\"\n    name: str = \"Google Search Results JSON\"\n    description: str = (\n        \"A wrapper around Google Search. \"\n        \"Useful for when you need to answer questions about current events. \"\n        \"Input should be a search query. Output is a JSON array of the query results\"\n    )\n    num_results: int = 4\n    api_wrapper: GoogleSearchAPIWrapper\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return str(self.api_wrapper.results(query, self.num_results))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html"}
{"id": "bd7b3d95bb74-0", "text": "Source code for langchain.tools.amadeus.closest_airport\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.chains import LLMChain\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.amadeus.base import AmadeusBaseTool\n[docs]class ClosestAirportSchema(BaseModel):\n    \"\"\"Schema for the AmadeusClosestAirport tool.\"\"\"\n    location: str = Field(\n        description=(\n            \" The location for which you would like to find the nearest airport \"\n            \" along with optional details such as country, state, region, or \"\n            \" province, allowing for easy processing and identification of \"\n            \" the closest airport. Examples of the format are the following:\\n\"\n            \" Cali, Colombia\\n \"\n            \" Lincoln, Nebraska, United States\\n\"\n            \" New York, United States\\n\"\n            \" Sydney, New South Wales, Australia\\n\"\n            \" Rome, Lazio, Italy\\n\"\n            \" Toronto, Ontario, Canada\\n\"\n        )\n    )\n[docs]class AmadeusClosestAirport(AmadeusBaseTool):\n    \"\"\"Tool for finding the closest airport to a particular location.\"\"\"\n    name: str = \"closest_airport\"\n    description: str = (\n        \"Use this tool to find the closest airport to a particular location.\"\n    )\n    args_schema: Type[ClosestAirportSchema] = ClosestAirportSchema\n    def _run(\n        self,\n        location: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        template = (\n            \" What is the nearest airport to {location}? Please respond with the \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/amadeus/closest_airport.html"}
{"id": "bd7b3d95bb74-1", "text": "\" What is the nearest airport to {location}? Please respond with the \"\n            \" airport's International Air Transport Association (IATA) Location \"\n            ' Identifier in the following JSON format. JSON: \"iataCode\": \"IATA '\n            ' Location Identifier\" '\n        )\n        llm = ChatOpenAI(temperature=0)\n        llm_chain = LLMChain.from_string(llm=llm, template=template)\n        output = llm_chain.run(location=location)\n        return output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/amadeus/closest_airport.html"}
{"id": "63dd58d12bf2-0", "text": "Source code for langchain.tools.amadeus.base\n\"\"\"Base class for Amadeus tools.\"\"\"\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.amadeus.utils import authenticate\nfrom langchain.tools.base import BaseTool\nif TYPE_CHECKING:\n    from amadeus import Client\n[docs]class AmadeusBaseTool(BaseTool):\n    \"\"\"Base Tool for Amadeus.\"\"\"\n    client: Client = Field(default_factory=authenticate)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/amadeus/base.html"}
{"id": "b9afbc091f38-0", "text": "Source code for langchain.tools.amadeus.utils\n\"\"\"O365 tool utils.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport os\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    from amadeus import Client\nlogger = logging.getLogger(__name__)\n[docs]def authenticate() -> Client:\n    \"\"\"Authenticate using the Amadeus API\"\"\"\n    try:\n        from amadeus import Client\n    except ImportError as e:\n        raise ImportError(\n            \"Cannot import amadeus. Please install the package with \"\n            \"`pip install amadeus`.\"\n        ) from e\n    if \"AMADEUS_CLIENT_ID\" in os.environ and \"AMADEUS_CLIENT_SECRET\" in os.environ:\n        client_id = os.environ[\"AMADEUS_CLIENT_ID\"]\n        client_secret = os.environ[\"AMADEUS_CLIENT_SECRET\"]\n    else:\n        logger.error(\n            \"Error: The AMADEUS_CLIENT_ID and AMADEUS_CLIENT_SECRET environmental \"\n            \"variables have not been set. Visit the following link on how to \"\n            \"acquire these authorization tokens: \"\n            \"https://developers.amadeus.com/register\"\n        )\n        return None\n    client = Client(client_id=client_id, client_secret=client_secret)\n    return client", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/amadeus/utils.html"}
{"id": "829e1cda5b17-0", "text": "Source code for langchain.tools.amadeus.flight_search\nimport logging\nfrom datetime import datetime as dt\nfrom typing import Dict, Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.amadeus.base import AmadeusBaseTool\nlogger = logging.getLogger(__name__)\n[docs]class FlightSearchSchema(BaseModel):\n    \"\"\"Schema for the AmadeusFlightSearch tool.\"\"\"\n    originLocationCode: str = Field(\n        description=(\n            \" The three letter International Air Transport \"\n            \" Association (IATA) Location Identifier for the \"\n            \" search's origin airport. \"\n        )\n    )\n    destinationLocationCode: str = Field(\n        description=(\n            \" The three letter International Air Transport \"\n            \" Association (IATA) Location Identifier for the \"\n            \" search's destination airport. \"\n        )\n    )\n    departureDateTimeEarliest: str = Field(\n        description=(\n            \" The earliest departure datetime from the origin airport \"\n            \" for the flight search in the following format: \"\n            ' \"YYYY-MM-DDTHH:MM\", where \"T\" separates the date and time '\n            ' components. For example: \"2023-06-09T10:30:00\" represents '\n            \" June 9th, 2023, at 10:30 AM. \"\n        )\n    )\n    departureDateTimeLatest: str = Field(\n        description=(\n            \" The latest departure datetime from the origin airport \"\n            \" for the flight search in the following format: \"\n            ' \"YYYY-MM-DDTHH:MM\", where \"T\" separates the date and time '", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/amadeus/flight_search.html"}
{"id": "829e1cda5b17-1", "text": "' components. For example: \"2023-06-09T10:30:00\" represents '\n            \" June 9th, 2023, at 10:30 AM. \"\n        )\n    )\n    page_number: int = Field(\n        default=1,\n        description=\"The specific page number of flight results to retrieve\",\n    )\n[docs]class AmadeusFlightSearch(AmadeusBaseTool):\n    \"\"\"Tool for searching for a single flight between two airports.\"\"\"\n    name: str = \"single_flight_search\"\n    description: str = (\n        \" Use this tool to search for a single flight between the origin and \"\n        \" destination airports at a departure between an earliest and \"\n        \" latest datetime. \"\n    )\n    args_schema: Type[FlightSearchSchema] = FlightSearchSchema\n    def _run(\n        self,\n        originLocationCode: str,\n        destinationLocationCode: str,\n        departureDateTimeEarliest: str,\n        departureDateTimeLatest: str,\n        page_number: int = 1,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> list:\n        try:\n            from amadeus import ResponseError\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import amadeus, please install with `pip install amadeus`.\"\n            ) from e\n        RESULTS_PER_PAGE = 10\n        # Authenticate and retrieve a client\n        client = self.client\n        # Check that earliest and latest dates are in the same day\n        earliestDeparture = dt.strptime(departureDateTimeEarliest, \"%Y-%m-%dT%H:%M:%S\")\n        latestDeparture = dt.strptime(departureDateTimeLatest, \"%Y-%m-%dT%H:%M:%S\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/amadeus/flight_search.html"}
{"id": "829e1cda5b17-2", "text": "if earliestDeparture.date() != latestDeparture.date():\n            logger.error(\n                \" Error: Earliest and latest departure dates need to be the \"\n                \" same date. If you're trying to search for round-trip \"\n                \" flights, call this function for the outbound flight first, \"\n                \" and then call again for the return flight. \"\n            )\n            return [None]\n        # Collect all results from the API\n        try:\n            response = client.shopping.flight_offers_search.get(\n                originLocationCode=originLocationCode,\n                destinationLocationCode=destinationLocationCode,\n                departureDate=latestDeparture.strftime(\"%Y-%m-%d\"),\n                adults=1,\n            )\n        except ResponseError as error:\n            print(error)\n        # Generate output dictionary\n        output = []\n        for offer in response.data:\n            itinerary: Dict = {}\n            itinerary[\"price\"] = {}\n            itinerary[\"price\"][\"total\"] = offer[\"price\"][\"total\"]\n            currency = offer[\"price\"][\"currency\"]\n            currency = response.result[\"dictionaries\"][\"currencies\"][currency]\n            itinerary[\"price\"][\"currency\"] = {}\n            itinerary[\"price\"][\"currency\"] = currency\n            segments = []\n            for segment in offer[\"itineraries\"][0][\"segments\"]:\n                flight = {}\n                flight[\"departure\"] = segment[\"departure\"]\n                flight[\"arrival\"] = segment[\"arrival\"]\n                flight[\"flightNumber\"] = segment[\"number\"]\n                carrier = segment[\"carrierCode\"]\n                carrier = response.result[\"dictionaries\"][\"carriers\"][carrier]\n                flight[\"carrier\"] = carrier\n                segments.append(flight)\n            itinerary[\"segments\"] = []\n            itinerary[\"segments\"] = segments\n            output.append(itinerary)\n        # Filter out flights after latest departure time", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/amadeus/flight_search.html"}
{"id": "829e1cda5b17-3", "text": "output.append(itinerary)\n        # Filter out flights after latest departure time\n        for index, offer in enumerate(output):\n            offerDeparture = dt.strptime(\n                offer[\"segments\"][0][\"departure\"][\"at\"], \"%Y-%m-%dT%H:%M:%S\"\n            )\n            if offerDeparture > latestDeparture:\n                output.pop(index)\n        # Return the paginated results\n        startIndex = (page_number - 1) * RESULTS_PER_PAGE\n        endIndex = startIndex + RESULTS_PER_PAGE\n        return output[startIndex:endIndex]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/amadeus/flight_search.html"}
{"id": "8bb4d6faf9ec-0", "text": "Source code for langchain.tools.wikipedia.tool\n\"\"\"Tool for the Wikipedia API.\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.wikipedia import WikipediaAPIWrapper\n[docs]class WikipediaQueryRun(BaseTool):\n    \"\"\"Tool that searches the Wikipedia API.\"\"\"\n    name: str = \"Wikipedia\"\n    description: str = (\n        \"A wrapper around Wikipedia. \"\n        \"Useful for when you need to answer general questions about \"\n        \"people, places, companies, facts, historical events, or other subjects. \"\n        \"Input should be a search query.\"\n    )\n    api_wrapper: WikipediaAPIWrapper\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the Wikipedia tool.\"\"\"\n        return self.api_wrapper.run(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/wikipedia/tool.html"}
{"id": "5fe15d3b6404-0", "text": "Source code for langchain.tools.ddg_search.tool\n\"\"\"Tool for the DuckDuckGo search API.\"\"\"\nimport warnings\nfrom typing import Any, Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper\n[docs]class DDGInput(BaseModel):\n    query: str = Field(description=\"search query to look up\")\n[docs]class DuckDuckGoSearchRun(BaseTool):\n    \"\"\"Tool that queries the DuckDuckGo search API.\"\"\"\n    name: str = \"duckduckgo_search\"\n    description: str = (\n        \"A wrapper around DuckDuckGo Search. \"\n        \"Useful for when you need to answer questions about current events. \"\n        \"Input should be a search query.\"\n    )\n    api_wrapper: DuckDuckGoSearchAPIWrapper = Field(\n        default_factory=DuckDuckGoSearchAPIWrapper\n    )\n    args_schema: Type[BaseModel] = DDGInput\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return self.api_wrapper.run(query)\n[docs]class DuckDuckGoSearchResults(BaseTool):\n    \"\"\"Tool that queries the DuckDuckGo search API and gets back json.\"\"\"\n    name: str = \"DuckDuckGo Results JSON\"\n    description: str = (\n        \"A wrapper around Duck Duck Go Search. \"\n        \"Useful for when you need to answer questions about current events. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html"}
{"id": "5fe15d3b6404-1", "text": "\"Useful for when you need to answer questions about current events. \"\n        \"Input should be a search query. Output is a JSON array of the query results\"\n    )\n    num_results: int = 4\n    api_wrapper: DuckDuckGoSearchAPIWrapper = Field(\n        default_factory=DuckDuckGoSearchAPIWrapper\n    )\n    backend: str = \"api\"\n    args_schema: Type[BaseModel] = DDGInput\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        res = self.api_wrapper.results(query, self.num_results, backend=self.backend)\n        res_strs = [\", \".join([f\"{k}: {v}\" for k, v in d.items()]) for d in res]\n        return \", \".join([f\"[{rs}]\" for rs in res_strs])\n[docs]def DuckDuckGoSearchTool(*args: Any, **kwargs: Any) -> DuckDuckGoSearchRun:\n    \"\"\"\n    Deprecated. Use DuckDuckGoSearchRun instead.\n    Args:\n        *args:\n        **kwargs:\n    Returns:\n        DuckDuckGoSearchRun\n    \"\"\"\n    warnings.warn(\n        \"DuckDuckGoSearchTool will be deprecated in the future. \"\n        \"Please use DuckDuckGoSearchRun instead.\",\n        DeprecationWarning,\n    )\n    return DuckDuckGoSearchRun(*args, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html"}
{"id": "54cc83b52a55-0", "text": "Source code for langchain.tools.zapier.tool\n\"\"\"[DEPRECATED]\n## Zapier Natural Language Actions API\n\\\nFull docs here: https://nla.zapier.com/start/\n**Zapier Natural Language Actions** gives you access to the 5k+ apps, 20k+ actions\non Zapier's platform through a natural language API interface.\nNLA supports apps like Gmail, Salesforce, Trello, Slack, Asana, HubSpot, Google Sheets,\nMicrosoft Teams, and thousands more apps: https://zapier.com/apps\nZapier NLA handles ALL the underlying API auth and translation from\nnatural language --> underlying API call --> return simplified output for LLMs\nThe key idea is you, or your users, expose a set of actions via an oauth-like setup\nwindow, which you can then query and execute via a REST API.\nNLA offers both API Key and OAuth for signing NLA API requests.\n1. Server-side (API Key): for quickly getting started, testing, and production scenarios\n    where LangChain will only use actions exposed in the developer's Zapier account\n    (and will use the developer's connected accounts on Zapier.com)\n2. User-facing (Oauth): for production scenarios where you are deploying an end-user\n    facing application and LangChain needs access to end-user's exposed actions and\n    connected accounts on Zapier.com\nThis quick start will focus on the server-side use case for brevity.\nReview [full docs](https://nla.zapier.com/start/) for user-facing oauth developer\nsupport.\nTypically, you'd use SequentialChain, here's a basic example:\n    1. Use NLA to find an email in Gmail\n    2. Use LLMChain to generate a draft reply to (1)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html"}
{"id": "54cc83b52a55-1", "text": "2. Use LLMChain to generate a draft reply to (1)\n    3. Use NLA to send the draft reply (2) to someone in Slack via direct message\nIn code, below:\n```python\nimport os\n# get from https://platform.openai.com/\nos.environ[\"OPENAI_API_KEY\"] = os.environ.get(\"OPENAI_API_KEY\", \"\")\n# get from https://nla.zapier.com/docs/authentication/\nos.environ[\"ZAPIER_NLA_API_KEY\"] = os.environ.get(\"ZAPIER_NLA_API_KEY\", \"\")\nfrom langchain.llms import OpenAI\nfrom langchain.agents import initialize_agent\nfrom langchain.agents.agent_toolkits import ZapierToolkit\nfrom langchain.utilities.zapier import ZapierNLAWrapper\n## step 0. expose gmail 'find email' and slack 'send channel message' actions\n# first go here, log in, expose (enable) the two actions:\n#    https://nla.zapier.com/demo/start\n#    -- for this example, can leave all fields \"Have AI guess\"\n# in an oauth scenario, you'd get your own <provider> id (instead of 'demo')\n# which you route your users through first\nllm = OpenAI(temperature=0)\nzapier = ZapierNLAWrapper()\n## To leverage OAuth you may pass the value `nla_oauth_access_token` to\n## the ZapierNLAWrapper. If you do this there is no need to initialize\n## the ZAPIER_NLA_API_KEY env variable\n# zapier = ZapierNLAWrapper(zapier_nla_oauth_access_token=\"TOKEN_HERE\")\ntoolkit = ZapierToolkit.from_zapier_nla_wrapper(zapier)\nagent = initialize_agent(\n    toolkit.get_tools(),\n    llm,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html"}
{"id": "54cc83b52a55-2", "text": "agent = initialize_agent(\n    toolkit.get_tools(),\n    llm,\n    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n    verbose=True\n)\nagent.run((\"Summarize the last email I received regarding Silicon Valley Bank. \"\n    \"Send the summary to the #test-zapier channel in slack.\"))\n```\n\"\"\"\nfrom typing import Any, Dict, Optional\nfrom langchain._api import warn_deprecated\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.zapier.prompt import BASE_ZAPIER_TOOL_PROMPT\nfrom langchain.utilities.zapier import ZapierNLAWrapper\n[docs]class ZapierNLARunAction(BaseTool):\n    \"\"\"\n    Args:\n        action_id: a specific action ID (from list actions) of the action to execute\n            (the set api_key must be associated with the action owner)\n        instructions: a natural language instruction string for using the action\n            (eg. \"get the latest email from Mike Knoop\" for \"Gmail: find email\" action)\n        params: a dict, optional. Any params provided will *override* AI guesses\n            from `instructions` (see \"understanding the AI guessing flow\" here:\n            https://nla.zapier.com/docs/using-the-api#ai-guessing)\n    \"\"\"\n    api_wrapper: ZapierNLAWrapper = Field(default_factory=ZapierNLAWrapper)\n    action_id: str\n    params: Optional[dict] = None\n    base_prompt: str = BASE_ZAPIER_TOOL_PROMPT\n    zapier_description: str", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html"}
{"id": "54cc83b52a55-3", "text": "zapier_description: str\n    params_schema: Dict[str, str] = Field(default_factory=dict)\n    name: str = \"\"\n    description: str = \"\"\n    @root_validator\n    def set_name_description(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        zapier_description = values[\"zapier_description\"]\n        params_schema = values[\"params_schema\"]\n        if \"instructions\" in params_schema:\n            del params_schema[\"instructions\"]\n        # Ensure base prompt (if overridden) contains necessary input fields\n        necessary_fields = {\"{zapier_description}\", \"{params}\"}\n        if not all(field in values[\"base_prompt\"] for field in necessary_fields):\n            raise ValueError(\n                \"Your custom base Zapier prompt must contain input fields for \"\n                \"{zapier_description} and {params}.\"\n            )\n        values[\"name\"] = zapier_description\n        values[\"description\"] = values[\"base_prompt\"].format(\n            zapier_description=zapier_description,\n            params=str(list(params_schema.keys())),\n        )\n        return values\n    def _run(\n        self, instructions: str, run_manager: Optional[CallbackManagerForToolRun] = None\n    ) -> str:\n        \"\"\"Use the Zapier NLA tool to return a list of all exposed user actions.\"\"\"\n        warn_deprecated(\n            since=\"0.0.319\",\n            message=(\n                \"This tool will be deprecated on 2023-11-17. See \"\n                \"https://nla.zapier.com/sunset/ for details\"\n            ),\n        )\n        return self.api_wrapper.run_as_str(self.action_id, instructions, self.params)\n    async def _arun(\n        self,\n        instructions: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html"}
{"id": "54cc83b52a55-4", "text": "async def _arun(\n        self,\n        instructions: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the Zapier NLA tool to return a list of all exposed user actions.\"\"\"\n        warn_deprecated(\n            since=\"0.0.319\",\n            message=(\n                \"This tool will be deprecated on 2023-11-17. See \"\n                \"https://nla.zapier.com/sunset/ for details\"\n            ),\n        )\n        return await self.api_wrapper.arun_as_str(\n            self.action_id,\n            instructions,\n            self.params,\n        )\nZapierNLARunAction.__doc__ = (\n    ZapierNLAWrapper.run.__doc__ + ZapierNLARunAction.__doc__  # type: ignore\n)\n# other useful actions\n[docs]class ZapierNLAListActions(BaseTool):\n    \"\"\"\n    Args:\n        None\n    \"\"\"\n    name: str = \"ZapierNLA_list_actions\"\n    description: str = BASE_ZAPIER_TOOL_PROMPT + (\n        \"This tool returns a list of the user's exposed actions.\"\n    )\n    api_wrapper: ZapierNLAWrapper = Field(default_factory=ZapierNLAWrapper)\n    def _run(\n        self,\n        _: str = \"\",\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the Zapier NLA tool to return a list of all exposed user actions.\"\"\"\n        warn_deprecated(\n            since=\"0.0.319\",\n            message=(\n                \"This tool will be deprecated on 2023-11-17. See \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html"}
{"id": "54cc83b52a55-5", "text": "\"This tool will be deprecated on 2023-11-17. See \"\n                \"https://nla.zapier.com/sunset/ for details\"\n            ),\n        )\n        return self.api_wrapper.list_as_str()\n    async def _arun(\n        self,\n        _: str = \"\",\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the Zapier NLA tool to return a list of all exposed user actions.\"\"\"\n        warn_deprecated(\n            since=\"0.0.319\",\n            message=(\n                \"This tool will be deprecated on 2023-11-17. See \"\n                \"https://nla.zapier.com/sunset/ for details\"\n            ),\n        )\n        return await self.api_wrapper.alist_as_str()\nZapierNLAListActions.__doc__ = (\n    ZapierNLAWrapper.list.__doc__ + ZapierNLAListActions.__doc__  # type: ignore\n)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html"}
{"id": "f20d73799131-0", "text": "Source code for langchain.tools.human.tool\n\"\"\"Tool for asking human input.\"\"\"\nfrom typing import Callable, Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\ndef _print_func(text: str) -> None:\n    print(\"\\n\")\n    print(text)\n[docs]class HumanInputRun(BaseTool):\n    \"\"\"Tool that asks user for input.\"\"\"\n    name: str = \"human\"\n    description: str = (\n        \"You can ask a human for guidance when you think you \"\n        \"got stuck or you are not sure what to do next. \"\n        \"The input should be a question for the human.\"\n    )\n    prompt_func: Callable[[str], None] = Field(default_factory=lambda: _print_func)\n    input_func: Callable = Field(default_factory=lambda: input)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the Human input tool.\"\"\"\n        self.prompt_func(query)\n        return self.input_func()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/human/tool.html"}
{"id": "7c3dd439a675-0", "text": "Source code for langchain.tools.google_scholar.tool\n\"\"\"Tool for the Google Scholar\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.google_scholar import GoogleScholarAPIWrapper\n[docs]class GoogleScholarQueryRun(BaseTool):\n    \"\"\"Tool that queries the Google search API.\"\"\"\n    name: str = \"google_scholar\"\n    description: str = (\n        \"A wrapper around Google Scholar Search. \"\n        \"Useful for when you need to get information about\"\n        \"research papers from Google Scholar\"\n        \"Input should be a search query.\"\n    )\n    api_wrapper: GoogleScholarAPIWrapper\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return self.api_wrapper.run(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/google_scholar/tool.html"}
{"id": "e427bc56e571-0", "text": "Source code for langchain.tools.openweathermap.tool\n\"\"\"Tool for the OpenWeatherMap API.\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.openweathermap import OpenWeatherMapAPIWrapper\n[docs]class OpenWeatherMapQueryRun(BaseTool):\n    \"\"\"Tool that queries the OpenWeatherMap API.\"\"\"\n    api_wrapper: OpenWeatherMapAPIWrapper = Field(\n        default_factory=OpenWeatherMapAPIWrapper\n    )\n    name: str = \"OpenWeatherMap\"\n    description: str = (\n        \"A wrapper around OpenWeatherMap API. \"\n        \"Useful for fetching current weather information for a specified location. \"\n        \"Input should be a location string (e.g. London,GB).\"\n    )\n    def _run(\n        self, location: str, run_manager: Optional[CallbackManagerForToolRun] = None\n    ) -> str:\n        \"\"\"Use the OpenWeatherMap tool.\"\"\"\n        return self.api_wrapper.run(location)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/openweathermap/tool.html"}
{"id": "1fdc82817ead-0", "text": "Source code for langchain.tools.github.tool\n\"\"\"\nThis tool allows agents to interact with the pygithub library\nand operate on a GitHub repository.\nTo use this tool, you must first set as environment variables:\n    GITHUB_API_TOKEN\n    GITHUB_REPOSITORY -> format: {owner}/{repo}\n\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.github import GitHubAPIWrapper\n[docs]class GitHubAction(BaseTool):\n    \"\"\"Tool for interacting with the GitHub API.\"\"\"\n    api_wrapper: GitHubAPIWrapper = Field(default_factory=GitHubAPIWrapper)\n    mode: str\n    name: str = \"\"\n    description: str = \"\"\n    def _run(\n        self,\n        instructions: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the GitHub API to run an operation.\"\"\"\n        return self.api_wrapper.run(self.mode, instructions)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/github/tool.html"}
{"id": "4095470d038f-0", "text": "Source code for langchain.tools.bing_search.tool\n\"\"\"Tool for the Bing search API.\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.bing_search import BingSearchAPIWrapper\n[docs]class BingSearchRun(BaseTool):\n    \"\"\"Tool that queries the Bing search API.\"\"\"\n    name: str = \"bing_search\"\n    description: str = (\n        \"A wrapper around Bing Search. \"\n        \"Useful for when you need to answer questions about current events. \"\n        \"Input should be a search query.\"\n    )\n    api_wrapper: BingSearchAPIWrapper\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return self.api_wrapper.run(query)\n[docs]class BingSearchResults(BaseTool):\n    \"\"\"Tool that queries the Bing Search API and gets back json.\"\"\"\n    name: str = \"Bing Search Results JSON\"\n    description: str = (\n        \"A wrapper around Bing Search. \"\n        \"Useful for when you need to answer questions about current events. \"\n        \"Input should be a search query. Output is a JSON array of the query results\"\n    )\n    num_results: int = 4\n    api_wrapper: BingSearchAPIWrapper\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return str(self.api_wrapper.results(query, self.num_results))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html"}
{"id": "585f35aaaa0e-0", "text": "Source code for langchain.tools.file_management.delete\nimport os\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.file_management.utils import (\n    INVALID_PATH_TEMPLATE,\n    BaseFileToolMixin,\n    FileValidationError,\n)\n[docs]class FileDeleteInput(BaseModel):\n    \"\"\"Input for DeleteFileTool.\"\"\"\n    file_path: str = Field(..., description=\"Path of the file to delete\")\n[docs]class DeleteFileTool(BaseFileToolMixin, BaseTool):\n    \"\"\"Tool that deletes a file.\"\"\"\n    name: str = \"file_delete\"\n    args_schema: Type[BaseModel] = FileDeleteInput\n    description: str = \"Delete a file\"\n    def _run(\n        self,\n        file_path: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        try:\n            file_path_ = self.get_relative_path(file_path)\n        except FileValidationError:\n            return INVALID_PATH_TEMPLATE.format(arg_name=\"file_path\", value=file_path)\n        if not file_path_.exists():\n            return f\"Error: no such file or directory: {file_path}\"\n        try:\n            os.remove(file_path_)\n            return f\"File deleted successfully: {file_path}.\"\n        except Exception as e:\n            return \"Error: \" + str(e)\n    # TODO: Add aiofiles method", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/delete.html"}
{"id": "a67ad6ada9db-0", "text": "Source code for langchain.tools.file_management.file_search\nimport fnmatch\nimport os\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.file_management.utils import (\n    INVALID_PATH_TEMPLATE,\n    BaseFileToolMixin,\n    FileValidationError,\n)\n[docs]class FileSearchInput(BaseModel):\n    \"\"\"Input for FileSearchTool.\"\"\"\n    dir_path: str = Field(\n        default=\".\",\n        description=\"Subdirectory to search in.\",\n    )\n    pattern: str = Field(\n        ...,\n        description=\"Unix shell regex, where * matches everything.\",\n    )\n[docs]class FileSearchTool(BaseFileToolMixin, BaseTool):\n    \"\"\"Tool that searches for files in a subdirectory that match a regex pattern.\"\"\"\n    name: str = \"file_search\"\n    args_schema: Type[BaseModel] = FileSearchInput\n    description: str = (\n        \"Recursively search for files in a subdirectory that match the regex pattern\"\n    )\n    def _run(\n        self,\n        pattern: str,\n        dir_path: str = \".\",\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        try:\n            dir_path_ = self.get_relative_path(dir_path)\n        except FileValidationError:\n            return INVALID_PATH_TEMPLATE.format(arg_name=\"dir_path\", value=dir_path)\n        matches = []\n        try:\n            for root, _, filenames in os.walk(dir_path_):\n                for filename in fnmatch.filter(filenames, pattern):\n                    absolute_path = os.path.join(root, filename)\n                    relative_path = os.path.relpath(absolute_path, dir_path_)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/file_search.html"}
{"id": "a67ad6ada9db-1", "text": "relative_path = os.path.relpath(absolute_path, dir_path_)\n                    matches.append(relative_path)\n            if matches:\n                return \"\\n\".join(matches)\n            else:\n                return f\"No files found for pattern {pattern} in directory {dir_path}\"\n        except Exception as e:\n            return \"Error: \" + str(e)\n    # TODO: Add aiofiles method", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/file_search.html"}
{"id": "5c54631c0afc-0", "text": "Source code for langchain.tools.file_management.write\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.file_management.utils import (\n    INVALID_PATH_TEMPLATE,\n    BaseFileToolMixin,\n    FileValidationError,\n)\n[docs]class WriteFileInput(BaseModel):\n    \"\"\"Input for WriteFileTool.\"\"\"\n    file_path: str = Field(..., description=\"name of file\")\n    text: str = Field(..., description=\"text to write to file\")\n    append: bool = Field(\n        default=False, description=\"Whether to append to an existing file.\"\n    )\n[docs]class WriteFileTool(BaseFileToolMixin, BaseTool):\n    \"\"\"Tool that writes a file to disk.\"\"\"\n    name: str = \"write_file\"\n    args_schema: Type[BaseModel] = WriteFileInput\n    description: str = \"Write file to disk\"\n    def _run(\n        self,\n        file_path: str,\n        text: str,\n        append: bool = False,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        try:\n            write_path = self.get_relative_path(file_path)\n        except FileValidationError:\n            return INVALID_PATH_TEMPLATE.format(arg_name=\"file_path\", value=file_path)\n        try:\n            write_path.parent.mkdir(exist_ok=True, parents=False)\n            mode = \"a\" if append else \"w\"\n            with write_path.open(mode, encoding=\"utf-8\") as f:\n                f.write(text)\n            return f\"File written successfully to {file_path}.\"\n        except Exception as e:\n            return \"Error: \" + str(e)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/write.html"}
{"id": "5c54631c0afc-1", "text": "except Exception as e:\n            return \"Error: \" + str(e)\n    # TODO: Add aiofiles method", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/write.html"}
{"id": "4ba36ae3e0b2-0", "text": "Source code for langchain.tools.file_management.move\nimport shutil\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.file_management.utils import (\n    INVALID_PATH_TEMPLATE,\n    BaseFileToolMixin,\n    FileValidationError,\n)\n[docs]class FileMoveInput(BaseModel):\n    \"\"\"Input for MoveFileTool.\"\"\"\n    source_path: str = Field(..., description=\"Path of the file to move\")\n    destination_path: str = Field(..., description=\"New path for the moved file\")\n[docs]class MoveFileTool(BaseFileToolMixin, BaseTool):\n    \"\"\"Tool that moves a file.\"\"\"\n    name: str = \"move_file\"\n    args_schema: Type[BaseModel] = FileMoveInput\n    description: str = \"Move or rename a file from one location to another\"\n    def _run(\n        self,\n        source_path: str,\n        destination_path: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        try:\n            source_path_ = self.get_relative_path(source_path)\n        except FileValidationError:\n            return INVALID_PATH_TEMPLATE.format(\n                arg_name=\"source_path\", value=source_path\n            )\n        try:\n            destination_path_ = self.get_relative_path(destination_path)\n        except FileValidationError:\n            return INVALID_PATH_TEMPLATE.format(\n                arg_name=\"destination_path_\", value=destination_path_\n            )\n        if not source_path_.exists():\n            return f\"Error: no such file or directory {source_path}\"\n        try:\n            # shutil.move expects str args in 3.8\n            shutil.move(str(source_path_), destination_path_)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/move.html"}
{"id": "4ba36ae3e0b2-1", "text": "shutil.move(str(source_path_), destination_path_)\n            return f\"File moved successfully from {source_path} to {destination_path}.\"\n        except Exception as e:\n            return \"Error: \" + str(e)\n    # TODO: Add aiofiles method", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/move.html"}
{"id": "f67ed732d2ea-0", "text": "Source code for langchain.tools.file_management.list_dir\nimport os\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.file_management.utils import (\n    INVALID_PATH_TEMPLATE,\n    BaseFileToolMixin,\n    FileValidationError,\n)\n[docs]class DirectoryListingInput(BaseModel):\n    \"\"\"Input for ListDirectoryTool.\"\"\"\n    dir_path: str = Field(default=\".\", description=\"Subdirectory to list.\")\n[docs]class ListDirectoryTool(BaseFileToolMixin, BaseTool):\n    \"\"\"Tool that lists files and directories in a specified folder.\"\"\"\n    name: str = \"list_directory\"\n    args_schema: Type[BaseModel] = DirectoryListingInput\n    description: str = \"List files and directories in a specified folder\"\n    def _run(\n        self,\n        dir_path: str = \".\",\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        try:\n            dir_path_ = self.get_relative_path(dir_path)\n        except FileValidationError:\n            return INVALID_PATH_TEMPLATE.format(arg_name=\"dir_path\", value=dir_path)\n        try:\n            entries = os.listdir(dir_path_)\n            if entries:\n                return \"\\n\".join(entries)\n            else:\n                return f\"No files found in directory {dir_path}\"\n        except Exception as e:\n            return \"Error: \" + str(e)\n    # TODO: Add aiofiles method", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/list_dir.html"}
{"id": "166782aea96a-0", "text": "Source code for langchain.tools.file_management.utils\nimport sys\nfrom pathlib import Path\nfrom typing import Optional\nfrom langchain.pydantic_v1 import BaseModel\n[docs]def is_relative_to(path: Path, root: Path) -> bool:\n    \"\"\"Check if path is relative to root.\"\"\"\n    if sys.version_info >= (3, 9):\n        # No need for a try/except block in Python 3.8+.\n        return path.is_relative_to(root)\n    try:\n        path.relative_to(root)\n        return True\n    except ValueError:\n        return False\nINVALID_PATH_TEMPLATE = (\n    \"Error: Access denied to {arg_name}: {value}.\"\n    \" Permission granted exclusively to the current working directory\"\n)\n[docs]class FileValidationError(ValueError):\n    \"\"\"Error for paths outside the root directory.\"\"\"\n[docs]class BaseFileToolMixin(BaseModel):\n    \"\"\"Mixin for file system tools.\"\"\"\n    root_dir: Optional[str] = None\n    \"\"\"The final path will be chosen relative to root_dir if specified.\"\"\"\n[docs]    def get_relative_path(self, file_path: str) -> Path:\n        \"\"\"Get the relative path, returning an error if unsupported.\"\"\"\n        if self.root_dir is None:\n            return Path(file_path)\n        return get_validated_relative_path(Path(self.root_dir), file_path)\n[docs]def get_validated_relative_path(root: Path, user_path: str) -> Path:\n    \"\"\"Resolve a relative path, raising an error if not within the root directory.\"\"\"\n    # Note, this still permits symlinks from outside that point within the root.\n    # Further validation would be needed if those are to be disallowed.\n    root = root.resolve()\n    full_path = (root / user_path).resolve()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/utils.html"}
{"id": "166782aea96a-1", "text": "root = root.resolve()\n    full_path = (root / user_path).resolve()\n    if not is_relative_to(full_path, root):\n        raise FileValidationError(\n            f\"Path {user_path} is outside of the allowed directory {root}\"\n        )\n    return full_path", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/utils.html"}
{"id": "1a3199e458f9-0", "text": "Source code for langchain.tools.file_management.read\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.file_management.utils import (\n    INVALID_PATH_TEMPLATE,\n    BaseFileToolMixin,\n    FileValidationError,\n)\n[docs]class ReadFileInput(BaseModel):\n    \"\"\"Input for ReadFileTool.\"\"\"\n    file_path: str = Field(..., description=\"name of file\")\n[docs]class ReadFileTool(BaseFileToolMixin, BaseTool):\n    \"\"\"Tool that reads a file.\"\"\"\n    name: str = \"read_file\"\n    args_schema: Type[BaseModel] = ReadFileInput\n    description: str = \"Read file from disk\"\n    def _run(\n        self,\n        file_path: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        try:\n            read_path = self.get_relative_path(file_path)\n        except FileValidationError:\n            return INVALID_PATH_TEMPLATE.format(arg_name=\"file_path\", value=file_path)\n        if not read_path.exists():\n            return f\"Error: no such file or directory: {file_path}\"\n        try:\n            with read_path.open(\"r\", encoding=\"utf-8\") as f:\n                content = f.read()\n            return content\n        except Exception as e:\n            return \"Error: \" + str(e)\n    # TODO: Add aiofiles method", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/read.html"}
{"id": "874b6e505903-0", "text": "Source code for langchain.tools.file_management.copy\nimport shutil\nfrom typing import Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.file_management.utils import (\n    INVALID_PATH_TEMPLATE,\n    BaseFileToolMixin,\n    FileValidationError,\n)\n[docs]class FileCopyInput(BaseModel):\n    \"\"\"Input for CopyFileTool.\"\"\"\n    source_path: str = Field(..., description=\"Path of the file to copy\")\n    destination_path: str = Field(..., description=\"Path to save the copied file\")\n[docs]class CopyFileTool(BaseFileToolMixin, BaseTool):\n    \"\"\"Tool that copies a file.\"\"\"\n    name: str = \"copy_file\"\n    args_schema: Type[BaseModel] = FileCopyInput\n    description: str = \"Create a copy of a file in a specified location\"\n    def _run(\n        self,\n        source_path: str,\n        destination_path: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        try:\n            source_path_ = self.get_relative_path(source_path)\n        except FileValidationError:\n            return INVALID_PATH_TEMPLATE.format(\n                arg_name=\"source_path\", value=source_path\n            )\n        try:\n            destination_path_ = self.get_relative_path(destination_path)\n        except FileValidationError:\n            return INVALID_PATH_TEMPLATE.format(\n                arg_name=\"destination_path\", value=destination_path\n            )\n        try:\n            shutil.copy2(source_path_, destination_path_, follow_symlinks=False)\n            return f\"File copied successfully from {source_path} to {destination_path}.\"\n        except Exception as e:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/copy.html"}
{"id": "874b6e505903-1", "text": "except Exception as e:\n            return \"Error: \" + str(e)\n    # TODO: Add aiofiles method", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/copy.html"}
{"id": "bc307d7725e4-0", "text": "Source code for langchain.tools.golden_query.tool\n\"\"\"Tool for the Golden API.\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.golden_query import GoldenQueryAPIWrapper\n[docs]class GoldenQueryRun(BaseTool):\n    \"\"\"Tool that adds the capability to query using the Golden API and get back JSON.\"\"\"\n    name: str = \"Golden-Query\"\n    description: str = (\n        \"A wrapper around Golden Query API.\"\n        \" Useful for getting entities that match\"\n        \" a natural language query from Golden's Knowledge Base.\"\n        \"\\nExample queries:\"\n        \"\\n- companies in nanotech\"\n        \"\\n- list of cloud providers starting in 2019\"\n        \"\\nInput should be the natural language query.\"\n        \"\\nOutput is a paginated list of results or an error object\"\n        \" in JSON format.\"\n    )\n    api_wrapper: GoldenQueryAPIWrapper\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the Golden tool.\"\"\"\n        return self.api_wrapper.run(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/golden_query/tool.html"}
{"id": "84959a5700b8-0", "text": "Source code for langchain.tools.graphql.tool\nimport json\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.graphql import GraphQLAPIWrapper\n[docs]class BaseGraphQLTool(BaseTool):\n    \"\"\"Base tool for querying a GraphQL API.\"\"\"\n    graphql_wrapper: GraphQLAPIWrapper\n    name: str = \"query_graphql\"\n    description: str = \"\"\"\\\n    Input to this tool is a detailed and correct GraphQL query, output is a result from the API.\n    If the query is not correct, an error message will be returned.\n    If an error is returned with 'Bad request' in it, rewrite the query and try again.\n    If an error is returned with 'Unauthorized' in it, do not try again, but tell the user to change their authentication.\n    Example Input: query {{ allUsers {{ id, name, email }} }}\\\n    \"\"\"  # noqa: E501\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    def _run(\n        self,\n        tool_input: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        result = self.graphql_wrapper.run(tool_input)\n        return json.dumps(result, indent=2)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/graphql/tool.html"}
{"id": "fe0eaa926e54-0", "text": "Source code for langchain.tools.pubmed.tool\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.pubmed import PubMedAPIWrapper\n[docs]class PubmedQueryRun(BaseTool):\n    \"\"\"Tool that searches the PubMed API.\"\"\"\n    name: str = \"PubMed\"\n    description: str = (\n        \"A wrapper around PubMed. \"\n        \"Useful for when you need to answer questions about medicine, health, \"\n        \"and biomedical topics \"\n        \"from biomedical literature, MEDLINE, life science journals, and online books. \"\n        \"Input should be a search query.\"\n    )\n    api_wrapper: PubMedAPIWrapper = Field(default_factory=PubMedAPIWrapper)\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the PubMed tool.\"\"\"\n        return self.api_wrapper.run(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/pubmed/tool.html"}
{"id": "f480dfd9d7c7-0", "text": "Source code for langchain.tools.clickup.tool\n\"\"\"\nThis tool allows agents to interact with the clickup library\nand operate on a Clickup instance.\nTo use this tool, you must first set as environment variables:\n    client_secret\n    client_id\n    code\nBelow is a sample script that uses the Clickup tool:\n```python\nfrom langchain.agents import AgentType\nfrom langchain.agents import initialize_agent\nfrom langchain.agents.agent_toolkits.clickup.toolkit import ClickupToolkit\nfrom langchain.llms import OpenAI\nfrom langchain.utilities.clickup import ClickupAPIWrapper\nllm = OpenAI(temperature=0)\nclickup = ClickupAPIWrapper()\ntoolkit = ClickupToolkit.from_clickup_api_wrapper(clickup)\nagent = initialize_agent(\n    toolkit.get_tools(),\n    llm,\n    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n    verbose=True\n)\n```\n\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.clickup import ClickupAPIWrapper\n[docs]class ClickupAction(BaseTool):\n    \"\"\"Tool that queries the  Clickup API.\"\"\"\n    api_wrapper: ClickupAPIWrapper = Field(default_factory=ClickupAPIWrapper)\n    mode: str\n    name: str = \"\"\n    description: str = \"\"\n    def _run(\n        self,\n        instructions: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the  Clickup API to run an operation.\"\"\"\n        return self.api_wrapper.run(self.mode, instructions)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/clickup/tool.html"}
{"id": "66c7d766cd71-0", "text": "Source code for langchain.tools.office365.events_search\n\"\"\"Util that Searches calendar events in Office 365.\nFree, but setup is required. See link below.\nhttps://learn.microsoft.com/en-us/graph/auth/\n\"\"\"\nfrom datetime import datetime as dt\nfrom typing import Any, Dict, List, Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field\nfrom langchain.tools.office365.base import O365BaseTool\nfrom langchain.tools.office365.utils import clean_body\n[docs]class SearchEventsInput(BaseModel):\n    \"\"\"Input for SearchEmails Tool.\"\"\"\n    \"\"\"From https://learn.microsoft.com/en-us/graph/search-query-parameter\"\"\"\n    start_datetime: str = Field(\n        description=(\n            \" The start datetime for the search query in the following format: \"\n            ' YYYY-MM-DDTHH:MM:SS\u00b1hh:mm, where \"T\" separates the date and time '\n            \" components, and the time zone offset is specified as \u00b1hh:mm. \"\n            ' For example: \"2023-06-09T10:30:00+03:00\" represents June 9th, '\n            \" 2023, at 10:30 AM in a time zone with a positive offset of 3 \"\n            \" hours from Coordinated Universal Time (UTC).\"\n        )\n    )\n    end_datetime: str = Field(\n        description=(\n            \" The end datetime for the search query in the following format: \"\n            ' YYYY-MM-DDTHH:MM:SS\u00b1hh:mm, where \"T\" separates the date and time '\n            \" components, and the time zone offset is specified as \u00b1hh:mm. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/events_search.html"}
{"id": "66c7d766cd71-1", "text": "\" components, and the time zone offset is specified as \u00b1hh:mm. \"\n            ' For example: \"2023-06-09T10:30:00+03:00\" represents June 9th, '\n            \" 2023, at 10:30 AM in a time zone with a positive offset of 3 \"\n            \" hours from Coordinated Universal Time (UTC).\"\n        )\n    )\n    max_results: int = Field(\n        default=10,\n        description=\"The maximum number of results to return.\",\n    )\n    truncate: bool = Field(\n        default=True,\n        description=(\n            \"Whether the event's body is truncated to meet token number limits. Set to \"\n            \"False for searches that will retrieve very few results, otherwise, set to \"\n            \"True.\"\n        ),\n    )\n[docs]class O365SearchEvents(O365BaseTool):\n    \"\"\"Class for searching calendar events in Office 365\n    Free, but setup is required\n    \"\"\"\n    name: str = \"events_search\"\n    args_schema: Type[BaseModel] = SearchEventsInput\n    description: str = (\n        \" Use this tool to search for the user's calendar events.\"\n        \" The input must be the start and end datetimes for the search query.\"\n        \" The output is a JSON list of all the events in the user's calendar\"\n        \" between the start and end times. You can assume that the user can \"\n        \" not schedule any meeting over existing meetings, and that the user \"\n        \"is busy during meetings. Any times without events are free for the user. \"\n    )\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    def _run(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/events_search.html"}
{"id": "66c7d766cd71-2", "text": "extra = Extra.forbid\n    def _run(\n        self,\n        start_datetime: str,\n        end_datetime: str,\n        max_results: int = 10,\n        truncate: bool = True,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> List[Dict[str, Any]]:\n        TRUNCATE_LIMIT = 150\n        # Get calendar object\n        schedule = self.account.schedule()\n        calendar = schedule.get_default_calendar()\n        # Process the date range parameters\n        start_datetime_query = dt.strptime(start_datetime, \"%Y-%m-%dT%H:%M:%S%z\")\n        end_datetime_query = dt.strptime(end_datetime, \"%Y-%m-%dT%H:%M:%S%z\")\n        # Run the query\n        q = calendar.new_query(\"start\").greater_equal(start_datetime_query)\n        q.chain(\"and\").on_attribute(\"end\").less_equal(end_datetime_query)\n        events = calendar.get_events(query=q, include_recurring=True, limit=max_results)\n        # Generate output dict\n        output_events = []\n        for event in events:\n            output_event = {}\n            output_event[\"organizer\"] = event.organizer\n            output_event[\"subject\"] = event.subject\n            if truncate:\n                output_event[\"body\"] = clean_body(event.body)[:TRUNCATE_LIMIT]\n            else:\n                output_event[\"body\"] = clean_body(event.body)\n            # Get the time zone from the search parameters\n            time_zone = start_datetime_query.tzinfo\n            # Assign the datetimes in the search time zone\n            output_event[\"start_datetime\"] = event.start.astimezone(time_zone).strftime(\n                \"%Y-%m-%dT%H:%M:%S%z\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/events_search.html"}
{"id": "66c7d766cd71-3", "text": "\"%Y-%m-%dT%H:%M:%S%z\"\n            )\n            output_event[\"end_datetime\"] = event.end.astimezone(time_zone).strftime(\n                \"%Y-%m-%dT%H:%M:%S%z\"\n            )\n            output_event[\"modified_date\"] = event.modified.astimezone(\n                time_zone\n            ).strftime(\"%Y-%m-%dT%H:%M:%S%z\")\n            output_events.append(output_event)\n        return output_events", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/events_search.html"}
{"id": "fa91763b4587-0", "text": "Source code for langchain.tools.office365.messages_search\n\"\"\"Util that Searches email messages in Office 365.\nFree, but setup is required. See link below.\nhttps://learn.microsoft.com/en-us/graph/auth/\n\"\"\"\nfrom typing import Any, Dict, List, Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field\nfrom langchain.tools.office365.base import O365BaseTool\nfrom langchain.tools.office365.utils import clean_body\n[docs]class SearchEmailsInput(BaseModel):\n    \"\"\"Input for SearchEmails Tool.\"\"\"\n    \"\"\"From https://learn.microsoft.com/en-us/graph/search-query-parameter\"\"\"\n    folder: str = Field(\n        default=None,\n        description=(\n            \" If the user wants to search in only one folder, the name of the folder. \"\n            'Default folders are \"inbox\", \"drafts\", \"sent items\", \"deleted ttems\", but '\n            \"users can search custom folders as well.\"\n        ),\n    )\n    query: str = Field(\n        description=(\n            \"The Microsoift Graph v1.0 $search query. Example filters include \"\n            \"from:sender, from:sender, to:recipient, subject:subject, \"\n            \"recipients:list_of_recipients, body:excitement, importance:high, \"\n            \"received>2022-12-01, received<2021-12-01, sent>2022-12-01, \"\n            \"sent<2021-12-01, hasAttachments:true  attachment:api-catalog.md, \"\n            \"cc:samanthab@contoso.com, bcc:samanthab@contoso.com, body:excitement date \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/messages_search.html"}
{"id": "fa91763b4587-1", "text": "\"range example: received:2023-06-08..2023-06-09  matching example: \"\n            \"from:amy OR from:david.\"\n        )\n    )\n    max_results: int = Field(\n        default=10,\n        description=\"The maximum number of results to return.\",\n    )\n    truncate: bool = Field(\n        default=True,\n        description=(\n            \"Whether the email body is truncated to meet token number limits. Set to \"\n            \"False for searches that will retrieve very few results, otherwise, set to \"\n            \"True\"\n        ),\n    )\n[docs]class O365SearchEmails(O365BaseTool):\n    \"\"\"Class for searching email messages in Office 365\n    Free, but setup is required\n    \"\"\"\n    name: str = \"messages_search\"\n    args_schema: Type[BaseModel] = SearchEmailsInput\n    description: str = (\n        \"Use this tool to search for email messages.\"\n        \" The input must be a valid Microsoft Graph v1.0 $search query.\"\n        \" The output is a JSON list of the requested resource.\"\n    )\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    def _run(\n        self,\n        query: str,\n        folder: str = \"\",\n        max_results: int = 10,\n        truncate: bool = True,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> List[Dict[str, Any]]:\n        # Get mailbox object\n        mailbox = self.account.mailbox()\n        # Pull the folder if the user wants to search in a folder\n        if folder != \"\":\n            mailbox = mailbox.get_folder(folder_name=folder)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/messages_search.html"}
{"id": "fa91763b4587-2", "text": "if folder != \"\":\n            mailbox = mailbox.get_folder(folder_name=folder)\n        # Retrieve messages based on query\n        query = mailbox.q().search(query)\n        messages = mailbox.get_messages(limit=max_results, query=query)\n        # Generate output dict\n        output_messages = []\n        for message in messages:\n            output_message = {}\n            output_message[\"from\"] = message.sender\n            if truncate:\n                output_message[\"body\"] = message.body_preview\n            else:\n                output_message[\"body\"] = clean_body(message.body)\n            output_message[\"subject\"] = message.subject\n            output_message[\"date\"] = message.modified.strftime(\"%Y-%m-%dT%H:%M:%S%z\")\n            output_message[\"to\"] = []\n            for recipient in message.to._recipients:\n                output_message[\"to\"].append(str(recipient))\n            output_message[\"cc\"] = []\n            for recipient in message.cc._recipients:\n                output_message[\"cc\"].append(str(recipient))\n            output_message[\"bcc\"] = []\n            for recipient in message.bcc._recipients:\n                output_message[\"bcc\"].append(str(recipient))\n            output_messages.append(output_message)\n        return output_messages", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/messages_search.html"}
{"id": "1c0a809e75b0-0", "text": "Source code for langchain.tools.office365.base\n\"\"\"Base class for Office 365 tools.\"\"\"\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.office365.utils import authenticate\nif TYPE_CHECKING:\n    from O365 import Account\n[docs]class O365BaseTool(BaseTool):\n    \"\"\"Base class for the Office 365 tools.\"\"\"\n    account: Account = Field(default_factory=authenticate)\n    \"\"\"The account object for the Office 365 account.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/base.html"}
{"id": "ffb82181d36e-0", "text": "Source code for langchain.tools.office365.utils\n\"\"\"O365 tool utils.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport os\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    from O365 import Account\nlogger = logging.getLogger(__name__)\n[docs]def clean_body(body: str) -> str:\n    \"\"\"Clean body of a message or event.\"\"\"\n    try:\n        from bs4 import BeautifulSoup\n        try:\n            # Remove HTML\n            soup = BeautifulSoup(str(body), \"html.parser\")\n            body = soup.get_text()\n            # Remove return characters\n            body = \"\".join(body.splitlines())\n            # Remove extra spaces\n            body = \" \".join(body.split())\n            return str(body)\n        except Exception:\n            return str(body)\n    except ImportError:\n        return str(body)\n[docs]def authenticate() -> Account:\n    \"\"\"Authenticate using the Microsoft Grah API\"\"\"\n    try:\n        from O365 import Account\n    except ImportError as e:\n        raise ImportError(\n            \"Cannot import 0365. Please install the package with `pip install O365`.\"\n        ) from e\n    if \"CLIENT_ID\" in os.environ and \"CLIENT_SECRET\" in os.environ:\n        client_id = os.environ[\"CLIENT_ID\"]\n        client_secret = os.environ[\"CLIENT_SECRET\"]\n        credentials = (client_id, client_secret)\n    else:\n        logger.error(\n            \"Error: The CLIENT_ID and CLIENT_SECRET environmental variables have not \"\n            \"been set. Visit the following link on how to acquire these authorization \"\n            \"tokens: https://learn.microsoft.com/en-us/graph/auth/\"\n        )\n        return None\n    account = Account(credentials)\n    if account.is_authenticated is False:\n        if not account.authenticate(\n            scopes=[", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/utils.html"}
{"id": "ffb82181d36e-1", "text": "if account.is_authenticated is False:\n        if not account.authenticate(\n            scopes=[\n                \"https://graph.microsoft.com/Mail.ReadWrite\",\n                \"https://graph.microsoft.com/Mail.Send\",\n                \"https://graph.microsoft.com/Calendars.ReadWrite\",\n                \"https://graph.microsoft.com/MailboxSettings.ReadWrite\",\n            ]\n        ):\n            print(\"Error: Could not authenticate\")\n            return None\n        else:\n            return account\n    else:\n        return account", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/utils.html"}
{"id": "e5746c0d3b5b-0", "text": "Source code for langchain.tools.office365.send_message\nfrom typing import List, Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.office365.base import O365BaseTool\n[docs]class SendMessageSchema(BaseModel):\n    \"\"\"Input for SendMessageTool.\"\"\"\n    body: str = Field(\n        ...,\n        description=\"The message body to be sent.\",\n    )\n    to: List[str] = Field(\n        ...,\n        description=\"The list of recipients.\",\n    )\n    subject: str = Field(\n        ...,\n        description=\"The subject of the message.\",\n    )\n    cc: Optional[List[str]] = Field(\n        None,\n        description=\"The list of CC recipients.\",\n    )\n    bcc: Optional[List[str]] = Field(\n        None,\n        description=\"The list of BCC recipients.\",\n    )\n[docs]class O365SendMessage(O365BaseTool):\n    \"\"\"Tool for sending an email in Office 365.\"\"\"\n    name: str = \"send_email\"\n    description: str = (\n        \"Use this tool to send an email with the provided message fields.\"\n    )\n    args_schema: Type[SendMessageSchema] = SendMessageSchema\n    def _run(\n        self,\n        body: str,\n        to: List[str],\n        subject: str,\n        cc: Optional[List[str]] = None,\n        bcc: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        # Get mailbox object\n        mailbox = self.account.mailbox()\n        message = mailbox.new_message()\n        # Assign message values\n        message.body = body\n        message.subject = subject", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/send_message.html"}
{"id": "e5746c0d3b5b-1", "text": "# Assign message values\n        message.body = body\n        message.subject = subject\n        message.to.add(to)\n        if cc is not None:\n            message.cc.add(cc)\n        if bcc is not None:\n            message.bcc.add(cc)\n        message.send()\n        output = \"Message sent: \" + str(message)\n        return output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/send_message.html"}
{"id": "018b3b4bea7c-0", "text": "Source code for langchain.tools.office365.create_draft_message\nfrom typing import List, Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.office365.base import O365BaseTool\n[docs]class CreateDraftMessageSchema(BaseModel):\n    \"\"\"Input for SendMessageTool.\"\"\"\n    body: str = Field(\n        ...,\n        description=\"The message body to include in the draft.\",\n    )\n    to: List[str] = Field(\n        ...,\n        description=\"The list of recipients.\",\n    )\n    subject: str = Field(\n        ...,\n        description=\"The subject of the message.\",\n    )\n    cc: Optional[List[str]] = Field(\n        None,\n        description=\"The list of CC recipients.\",\n    )\n    bcc: Optional[List[str]] = Field(\n        None,\n        description=\"The list of BCC recipients.\",\n    )\n[docs]class O365CreateDraftMessage(O365BaseTool):\n    \"\"\"Tool for creating a draft email in Office 365.\"\"\"\n    name: str = \"create_email_draft\"\n    description: str = (\n        \"Use this tool to create a draft email with the provided message fields.\"\n    )\n    args_schema: Type[CreateDraftMessageSchema] = CreateDraftMessageSchema\n    def _run(\n        self,\n        body: str,\n        to: List[str],\n        subject: str,\n        cc: Optional[List[str]] = None,\n        bcc: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        # Get mailbox object\n        mailbox = self.account.mailbox()\n        message = mailbox.new_message()\n        # Assign message values", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/create_draft_message.html"}
{"id": "018b3b4bea7c-1", "text": "message = mailbox.new_message()\n        # Assign message values\n        message.body = body\n        message.subject = subject\n        message.to.add(to)\n        if cc is not None:\n            message.cc.add(cc)\n        if bcc is not None:\n            message.bcc.add(cc)\n        message.save_draft()\n        output = \"Draft created: \" + str(message)\n        return output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/create_draft_message.html"}
{"id": "473cac5b30ed-0", "text": "Source code for langchain.tools.office365.send_event\n\"\"\"Util that sends calendar events in Office 365.\nFree, but setup is required. See link below.\nhttps://learn.microsoft.com/en-us/graph/auth/\n\"\"\"\nfrom datetime import datetime as dt\nfrom typing import List, Optional, Type\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.office365.base import O365BaseTool\n[docs]class SendEventSchema(BaseModel):\n    \"\"\"Input for CreateEvent Tool.\"\"\"\n    body: str = Field(\n        ...,\n        description=\"The message body to include in the event.\",\n    )\n    attendees: List[str] = Field(\n        ...,\n        description=\"The list of attendees for the event.\",\n    )\n    subject: str = Field(\n        ...,\n        description=\"The subject of the event.\",\n    )\n    start_datetime: str = Field(\n        description=\" The start datetime for the event in the following format: \"\n        ' YYYY-MM-DDTHH:MM:SS\u00b1hh:mm, where \"T\" separates the date and time '\n        \" components, and the time zone offset is specified as \u00b1hh:mm. \"\n        ' For example: \"2023-06-09T10:30:00+03:00\" represents June 9th, '\n        \" 2023, at 10:30 AM in a time zone with a positive offset of 3 \"\n        \" hours from Coordinated Universal Time (UTC).\",\n    )\n    end_datetime: str = Field(\n        description=\" The end datetime for the event in the following format: \"\n        ' YYYY-MM-DDTHH:MM:SS\u00b1hh:mm, where \"T\" separates the date and time '", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/send_event.html"}
{"id": "473cac5b30ed-1", "text": "\" components, and the time zone offset is specified as \u00b1hh:mm. \"\n        ' For example: \"2023-06-09T10:30:00+03:00\" represents June 9th, '\n        \" 2023, at 10:30 AM in a time zone with a positive offset of 3 \"\n        \" hours from Coordinated Universal Time (UTC).\",\n    )\n[docs]class O365SendEvent(O365BaseTool):\n    \"\"\"Tool for sending calendar events in Office 365.\"\"\"\n    name: str = \"send_event\"\n    description: str = (\n        \"Use this tool to create and send an event with the provided event fields.\"\n    )\n    args_schema: Type[SendEventSchema] = SendEventSchema\n    def _run(\n        self,\n        body: str,\n        attendees: List[str],\n        subject: str,\n        start_datetime: str,\n        end_datetime: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        # Get calendar object\n        schedule = self.account.schedule()\n        calendar = schedule.get_default_calendar()\n        event = calendar.new_event()\n        event.body = body\n        event.subject = subject\n        event.start = dt.strptime(start_datetime, \"%Y-%m-%dT%H:%M:%S%z\")\n        event.end = dt.strptime(end_datetime, \"%Y-%m-%dT%H:%M:%S%z\")\n        for attendee in attendees:\n            event.attendees.add(attendee)\n        # TO-DO: Look into PytzUsageWarning\n        event.save()\n        output = \"Event sent: \" + str(event)\n        return output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/office365/send_event.html"}
{"id": "2c4c72925337-0", "text": "Source code for langchain.tools.eleven_labs.text2speech\nimport tempfile\nfrom enum import Enum\nfrom typing import Any, Dict, Optional, Union\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.tools.base import BaseTool\nfrom langchain.utils import get_from_dict_or_env\ndef _import_elevenlabs() -> Any:\n    try:\n        import elevenlabs\n    except ImportError as e:\n        raise ImportError(\n            \"Cannot import elevenlabs, please install `pip install elevenlabs`.\"\n        ) from e\n    return elevenlabs\n[docs]class ElevenLabsModel(str, Enum):\n    \"\"\"Models available for Eleven Labs Text2Speech.\"\"\"\n    MULTI_LINGUAL = \"eleven_multilingual_v1\"\n    MONO_LINGUAL = \"eleven_monolingual_v1\"\n[docs]class ElevenLabsText2SpeechTool(BaseTool):\n    \"\"\"Tool that queries the Eleven Labs Text2Speech API.\n    In order to set this up, follow instructions at:\n    https://docs.elevenlabs.io/welcome/introduction\n    \"\"\"\n    model: Union[ElevenLabsModel, str] = ElevenLabsModel.MULTI_LINGUAL\n    name: str = \"eleven_labs_text2speech\"\n    description: str = (\n        \"A wrapper around Eleven Labs Text2Speech. \"\n        \"Useful for when you need to convert text to speech. \"\n        \"It supports multiple languages, including English, German, Polish, \"\n        \"Spanish, Italian, French, Portuguese, and Hindi. \"\n    )\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key exists in environment.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/eleven_labs/text2speech.html"}
{"id": "2c4c72925337-1", "text": "\"\"\"Validate that api key exists in environment.\"\"\"\n        _ = get_from_dict_or_env(values, \"eleven_api_key\", \"ELEVEN_API_KEY\")\n        return values\n    def _run(\n        self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        elevenlabs = _import_elevenlabs()\n        try:\n            speech = elevenlabs.generate(text=query, model=self.model)\n            with tempfile.NamedTemporaryFile(\n                mode=\"bx\", suffix=\".wav\", delete=False\n            ) as f:\n                f.write(speech)\n            return f.name\n        except Exception as e:\n            raise RuntimeError(f\"Error while running ElevenLabsText2SpeechTool: {e}\")\n[docs]    def play(self, speech_file: str) -> None:\n        \"\"\"Play the text as speech.\"\"\"\n        elevenlabs = _import_elevenlabs()\n        with open(speech_file, mode=\"rb\") as f:\n            speech = f.read()\n        elevenlabs.play(speech)\n[docs]    def stream_speech(self, query: str) -> None:\n        \"\"\"Stream the text as speech as it is generated.\n        Play the text in your speakers.\"\"\"\n        elevenlabs = _import_elevenlabs()\n        speech_stream = elevenlabs.generate(text=query, model=self.model, stream=True)\n        elevenlabs.stream(speech_stream)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/eleven_labs/text2speech.html"}
{"id": "4cc0aba8d2e7-0", "text": "Source code for langchain.tools.eleven_labs.models\nfrom enum import Enum\n[docs]class ElevenLabsModel(str, Enum):\n    \"\"\"Models available for Eleven Labs Text2Speech.\"\"\"\n    MULTI_LINGUAL = \"eleven_multilingual_v1\"\n    MONO_LINGUAL = \"eleven_monolingual_v1\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/eleven_labs/models.html"}
{"id": "1479ae1a8dcf-0", "text": "Source code for langchain.tools.scenexplain.tool\n\"\"\"Tool for the SceneXplain API.\"\"\"\nfrom typing import Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.scenexplain import SceneXplainAPIWrapper\n[docs]class SceneXplainInput(BaseModel):\n    \"\"\"Input for SceneXplain.\"\"\"\n    query: str = Field(..., description=\"The link to the image to explain\")\n[docs]class SceneXplainTool(BaseTool):\n    \"\"\"Tool that explains images.\"\"\"\n    name: str = \"image_explainer\"\n    description: str = (\n        \"An Image Captioning Tool: Use this tool to generate a detailed caption \"\n        \"for an image. The input can be an image file of any format, and \"\n        \"the output will be a text description that covers every detail of the image.\"\n    )\n    api_wrapper: SceneXplainAPIWrapper = Field(default_factory=SceneXplainAPIWrapper)\n    def _run(\n        self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        return self.api_wrapper.run(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/scenexplain/tool.html"}
{"id": "36e82d8d2372-0", "text": "Source code for langchain.tools.memorize.tool\nfrom abc import abstractmethod\nfrom typing import Any, Optional, Protocol, Sequence, runtime_checkable\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.llms.gradient_ai import TrainResult\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools.base import BaseTool\n[docs]@runtime_checkable\nclass TrainableLLM(Protocol):\n[docs]    @abstractmethod\n    def train_unsupervised(\n        self,\n        inputs: Sequence[str],\n        **kwargs: Any,\n    ) -> TrainResult:\n        ...\n[docs]    @abstractmethod\n    async def atrain_unsupervised(\n        self,\n        inputs: Sequence[str],\n        **kwargs: Any,\n    ) -> TrainResult:\n        ...\n[docs]class Memorize(BaseTool):\n    name: str = \"Memorize\"\n    description: str = (\n        \"Useful whenever you observed novel information \"\n        \"from previous conversation history, \"\n        \"i.e., another tool's action outputs or human comments. \"\n        \"The action input should include observed information in detail, \"\n        \"then the tool will fine-tune yourself to remember it.\"\n    )\n    llm: TrainableLLM = Field()\n    def _run(\n        self,\n        information_to_learn: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        train_result = self.llm.train_unsupervised((information_to_learn,))\n        return f\"Train complete. Loss: {train_result['loss']}\"\n    async def _arun(\n        self,\n        information_to_learn: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/memorize/tool.html"}
{"id": "36e82d8d2372-1", "text": "async def _arun(\n        self,\n        information_to_learn: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        train_result = await self.llm.atrain_unsupervised((information_to_learn,))\n        return f\"Train complete. Loss: {train_result['loss']}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/memorize/tool.html"}
{"id": "7fa35eda7111-0", "text": "Source code for langchain.tools.steamship_image_generation.tool\n\"\"\"This tool allows agents to generate images using Steamship.\nSteamship offers access to different third party image generation APIs\nusing a single API key.\nToday the following models are supported:\n- Dall-E\n- Stable Diffusion\nTo use this tool, you must first set as environment variables:\n    STEAMSHIP_API_KEY\n```\n\"\"\"\nfrom __future__ import annotations\nfrom enum import Enum\nfrom typing import TYPE_CHECKING, Dict, Optional\nfrom langchain.callbacks.manager import CallbackManagerForToolRun\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.tools import BaseTool\nfrom langchain.tools.steamship_image_generation.utils import make_image_public\nfrom langchain.utils import get_from_dict_or_env\nif TYPE_CHECKING:\n    from steamship import Steamship\n[docs]class ModelName(str, Enum):\n    \"\"\"Supported Image Models for generation.\"\"\"\n    DALL_E = \"dall-e\"\n    STABLE_DIFFUSION = \"stable-diffusion\"\nSUPPORTED_IMAGE_SIZES = {\n    ModelName.DALL_E: (\"256x256\", \"512x512\", \"1024x1024\"),\n    ModelName.STABLE_DIFFUSION: (\"512x512\", \"768x768\"),\n}\n[docs]class SteamshipImageGenerationTool(BaseTool):\n    \"\"\"Tool used to generate images from a text-prompt.\"\"\"\n    model_name: ModelName\n    size: Optional[str] = \"512x512\"\n    steamship: Steamship\n    return_urls: Optional[bool] = False\n    name: str = \"GenerateImage\"\n    description: str = (\n        \"Useful for when you need to generate an image.\"\n        \"Input: A detailed text-2-image prompt describing an image\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html"}
{"id": "7fa35eda7111-1", "text": "\"Input: A detailed text-2-image prompt describing an image\"\n        \"Output: the UUID of a generated image\"\n    )\n    @root_validator(pre=True)\n    def validate_size(cls, values: Dict) -> Dict:\n        if \"size\" in values:\n            size = values[\"size\"]\n            model_name = values[\"model_name\"]\n            if size not in SUPPORTED_IMAGE_SIZES[model_name]:\n                raise RuntimeError(f\"size {size} is not supported by {model_name}\")\n        return values\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        steamship_api_key = get_from_dict_or_env(\n            values, \"steamship_api_key\", \"STEAMSHIP_API_KEY\"\n        )\n        try:\n            from steamship import Steamship\n        except ImportError:\n            raise ImportError(\n                \"steamship is not installed. \"\n                \"Please install it with `pip install steamship`\"\n            )\n        steamship = Steamship(\n            api_key=steamship_api_key,\n        )\n        values[\"steamship\"] = steamship\n        if \"steamship_api_key\" in values:\n            del values[\"steamship_api_key\"]\n        return values\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        image_generator = self.steamship.use_plugin(\n            plugin_handle=self.model_name.value, config={\"n\": 1, \"size\": self.size}\n        )\n        task = image_generator.generate(text=query, append_output_to_file=True)\n        task.wait()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html"}
{"id": "7fa35eda7111-2", "text": "task.wait()\n        blocks = task.output.blocks\n        if len(blocks) > 0:\n            if self.return_urls:\n                return make_image_public(self.steamship, blocks[0])\n            else:\n                return blocks[0].id\n        raise RuntimeError(f\"[{self.name}] Tool unable to generate image!\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html"}
{"id": "ec14b03036ee-0", "text": "Source code for langchain.tools.steamship_image_generation.utils\n\"\"\"Steamship Utils.\"\"\"\nfrom __future__ import annotations\nimport uuid\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    from steamship import Block, Steamship\n[docs]def make_image_public(client: Steamship, block: Block) -> str:\n    \"\"\"Upload a block to a signed URL and return the public URL.\"\"\"\n    try:\n        from steamship.data.workspace import SignedUrl\n        from steamship.utils.signed_urls import upload_to_signed_url\n    except ImportError:\n        raise ImportError(\n            \"The make_image_public function requires the steamship\"\n            \" package to be installed. Please install steamship\"\n            \" with `pip install --upgrade steamship`\"\n        )\n    filepath = str(uuid.uuid4())\n    signed_url = (\n        client.get_workspace()\n        .create_signed_url(\n            SignedUrl.Request(\n                bucket=SignedUrl.Bucket.PLUGIN_DATA,\n                filepath=filepath,\n                operation=SignedUrl.Operation.WRITE,\n            )\n        )\n        .signed_url\n    )\n    read_signed_url = (\n        client.get_workspace()\n        .create_signed_url(\n            SignedUrl.Request(\n                bucket=SignedUrl.Bucket.PLUGIN_DATA,\n                filepath=filepath,\n                operation=SignedUrl.Operation.READ,\n            )\n        )\n        .signed_url\n    )\n    upload_to_signed_url(signed_url, block.raw())\n    return read_signed_url", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/utils.html"}
{"id": "42f369046712-0", "text": "Source code for langchain.indexes.vectorstore\nfrom typing import Any, Dict, List, Optional, Type\nfrom langchain.chains.qa_with_sources.retrieval import RetrievalQAWithSourcesChain\nfrom langchain.chains.retrieval_qa.base import RetrievalQA\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom langchain.llms.openai import OpenAI\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field\nfrom langchain.schema import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter, TextSplitter\nfrom langchain.vectorstores.chroma import Chroma\ndef _get_default_text_splitter() -> TextSplitter:\n    return RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n[docs]class VectorStoreIndexWrapper(BaseModel):\n    \"\"\"Wrapper around a vectorstore for easy access.\"\"\"\n    vectorstore: VectorStore\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n[docs]    def query(\n        self,\n        question: str,\n        llm: Optional[BaseLanguageModel] = None,\n        retriever_kwargs: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Query the vectorstore.\"\"\"\n        llm = llm or OpenAI(temperature=0)\n        retriever_kwargs = retriever_kwargs or {}\n        chain = RetrievalQA.from_chain_type(\n            llm, retriever=self.vectorstore.as_retriever(**retriever_kwargs), **kwargs\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/vectorstore.html"}
{"id": "42f369046712-1", "text": ")\n        return chain.run(question)\n[docs]    def query_with_sources(\n        self,\n        question: str,\n        llm: Optional[BaseLanguageModel] = None,\n        retriever_kwargs: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> dict:\n        \"\"\"Query the vectorstore and get back sources.\"\"\"\n        llm = llm or OpenAI(temperature=0)\n        retriever_kwargs = retriever_kwargs or {}\n        chain = RetrievalQAWithSourcesChain.from_chain_type(\n            llm, retriever=self.vectorstore.as_retriever(**retriever_kwargs), **kwargs\n        )\n        return chain({chain.question_key: question})\n[docs]class VectorstoreIndexCreator(BaseModel):\n    \"\"\"Logic for creating indexes.\"\"\"\n    vectorstore_cls: Type[VectorStore] = Chroma\n    embedding: Embeddings = Field(default_factory=OpenAIEmbeddings)\n    text_splitter: TextSplitter = Field(default_factory=_get_default_text_splitter)\n    vectorstore_kwargs: dict = Field(default_factory=dict)\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n[docs]    def from_loaders(self, loaders: List[BaseLoader]) -> VectorStoreIndexWrapper:\n        \"\"\"Create a vectorstore index from loaders.\"\"\"\n        docs = []\n        for loader in loaders:\n            docs.extend(loader.load())\n        return self.from_documents(docs)\n[docs]    def from_documents(self, documents: List[Document]) -> VectorStoreIndexWrapper:\n        \"\"\"Create a vectorstore index from documents.\"\"\"\n        sub_docs = self.text_splitter.split_documents(documents)\n        vectorstore = self.vectorstore_cls.from_documents(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/vectorstore.html"}
{"id": "42f369046712-2", "text": "vectorstore = self.vectorstore_cls.from_documents(\n            sub_docs, self.embedding, **self.vectorstore_kwargs\n        )\n        return VectorStoreIndexWrapper(vectorstore=vectorstore)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/vectorstore.html"}
{"id": "4778ec15a92d-0", "text": "Source code for langchain.indexes.base\nfrom __future__ import annotations\nimport uuid\nfrom abc import ABC, abstractmethod\nfrom typing import List, Optional, Sequence\nNAMESPACE_UUID = uuid.UUID(int=1984)\n[docs]class RecordManager(ABC):\n    \"\"\"An abstract base class representing the interface for a record manager.\"\"\"\n[docs]    def __init__(\n        self,\n        namespace: str,\n    ) -> None:\n        \"\"\"Initialize the record manager.\n        Args:\n            namespace (str): The namespace for the record manager.\n        \"\"\"\n        self.namespace = namespace\n[docs]    @abstractmethod\n    def create_schema(self) -> None:\n        \"\"\"Create the database schema for the record manager.\"\"\"\n[docs]    @abstractmethod\n    async def acreate_schema(self) -> None:\n        \"\"\"Create the database schema for the record manager.\"\"\"\n[docs]    @abstractmethod\n    def get_time(self) -> float:\n        \"\"\"Get the current server time as a high resolution timestamp!\n        It's important to get this from the server to ensure a monotonic clock,\n        otherwise there may be data loss when cleaning up old documents!\n        Returns:\n            The current server time as a float timestamp.\n        \"\"\"\n[docs]    @abstractmethod\n    async def aget_time(self) -> float:\n        \"\"\"Get the current server time as a high resolution timestamp!\n        It's important to get this from the server to ensure a monotonic clock,\n        otherwise there may be data loss when cleaning up old documents!\n        Returns:\n            The current server time as a float timestamp.\n        \"\"\"\n[docs]    @abstractmethod\n    def update(\n        self,\n        keys: Sequence[str],\n        *,\n        group_ids: Optional[Sequence[Optional[str]]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/base.html"}
{"id": "4778ec15a92d-1", "text": "*,\n        group_ids: Optional[Sequence[Optional[str]]] = None,\n        time_at_least: Optional[float] = None,\n    ) -> None:\n        \"\"\"Upsert records into the database.\n        Args:\n            keys: A list of record keys to upsert.\n            group_ids: A list of group IDs corresponding to the keys.\n            time_at_least: if provided, updates should only happen if the\n              updated_at field is at least this time.\n        Raises:\n            ValueError: If the length of keys doesn't match the length of group_ids.\n        \"\"\"\n[docs]    @abstractmethod\n    async def aupdate(\n        self,\n        keys: Sequence[str],\n        *,\n        group_ids: Optional[Sequence[Optional[str]]] = None,\n        time_at_least: Optional[float] = None,\n    ) -> None:\n        \"\"\"Upsert records into the database.\n        Args:\n            keys: A list of record keys to upsert.\n            group_ids: A list of group IDs corresponding to the keys.\n            time_at_least: if provided, updates should only happen if the\n              updated_at field is at least this time.\n        Raises:\n            ValueError: If the length of keys doesn't match the length of group_ids.\n        \"\"\"\n[docs]    @abstractmethod\n    def exists(self, keys: Sequence[str]) -> List[bool]:\n        \"\"\"Check if the provided keys exist in the database.\n        Args:\n            keys: A list of keys to check.\n        Returns:\n            A list of boolean values indicating the existence of each key.\n        \"\"\"\n[docs]    @abstractmethod\n    async def aexists(self, keys: Sequence[str]) -> List[bool]:\n        \"\"\"Check if the provided keys exist in the database.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/base.html"}
{"id": "4778ec15a92d-2", "text": "\"\"\"Check if the provided keys exist in the database.\n        Args:\n            keys: A list of keys to check.\n        Returns:\n            A list of boolean values indicating the existence of each key.\n        \"\"\"\n[docs]    @abstractmethod\n    def list_keys(\n        self,\n        *,\n        before: Optional[float] = None,\n        after: Optional[float] = None,\n        group_ids: Optional[Sequence[str]] = None,\n        limit: Optional[int] = None,\n    ) -> List[str]:\n        \"\"\"List records in the database based on the provided filters.\n        Args:\n            before: Filter to list records updated before this time.\n            after: Filter to list records updated after this time.\n            group_ids: Filter to list records with specific group IDs.\n            limit: optional limit on the number of records to return.\n        Returns:\n            A list of keys for the matching records.\n        \"\"\"\n[docs]    @abstractmethod\n    async def alist_keys(\n        self,\n        *,\n        before: Optional[float] = None,\n        after: Optional[float] = None,\n        group_ids: Optional[Sequence[str]] = None,\n        limit: Optional[int] = None,\n    ) -> List[str]:\n        \"\"\"List records in the database based on the provided filters.\n        Args:\n            before: Filter to list records updated before this time.\n            after: Filter to list records updated after this time.\n            group_ids: Filter to list records with specific group IDs.\n            limit: optional limit on the number of records to return.\n        Returns:\n            A list of keys for the matching records.\n        \"\"\"\n[docs]    @abstractmethod\n    def delete_keys(self, keys: Sequence[str]) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/base.html"}
{"id": "4778ec15a92d-3", "text": "def delete_keys(self, keys: Sequence[str]) -> None:\n        \"\"\"Delete specified records from the database.\n        Args:\n            keys: A list of keys to delete.\n        \"\"\"\n[docs]    @abstractmethod\n    async def adelete_keys(self, keys: Sequence[str]) -> None:\n        \"\"\"Delete specified records from the database.\n        Args:\n            keys: A list of keys to delete.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/base.html"}
{"id": "970df907b09b-0", "text": "Source code for langchain.indexes.graph\n\"\"\"Graph Index Creator.\"\"\"\nfrom typing import Optional, Type\nfrom langchain.chains.llm import LLMChain\nfrom langchain.graphs.networkx_graph import NetworkxEntityGraph, parse_triples\nfrom langchain.indexes.prompts.knowledge_triplet_extraction import (\n    KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT,\n)\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.prompt_template import BasePromptTemplate\n[docs]class GraphIndexCreator(BaseModel):\n    \"\"\"Functionality to create graph index.\"\"\"\n    llm: Optional[BaseLanguageModel] = None\n    graph_type: Type[NetworkxEntityGraph] = NetworkxEntityGraph\n[docs]    def from_text(\n        self, text: str, prompt: BasePromptTemplate = KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT\n    ) -> NetworkxEntityGraph:\n        \"\"\"Create graph index from text.\"\"\"\n        if self.llm is None:\n            raise ValueError(\"llm should not be None\")\n        graph = self.graph_type()\n        chain = LLMChain(llm=self.llm, prompt=prompt)\n        output = chain.predict(text=text)\n        knowledge = parse_triples(output)\n        for triple in knowledge:\n            graph.add_triple(triple)\n        return graph\n[docs]    async def afrom_text(\n        self, text: str, prompt: BasePromptTemplate = KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT\n    ) -> NetworkxEntityGraph:\n        \"\"\"Create graph index from text asynchronously.\"\"\"\n        if self.llm is None:\n            raise ValueError(\"llm should not be None\")\n        graph = self.graph_type()\n        chain = LLMChain(llm=self.llm, prompt=prompt)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/graph.html"}
{"id": "970df907b09b-1", "text": "chain = LLMChain(llm=self.llm, prompt=prompt)\n        output = await chain.apredict(text=text)\n        knowledge = parse_triples(output)\n        for triple in knowledge:\n            graph.add_triple(triple)\n        return graph", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/graph.html"}
{"id": "5c25de5b34be-0", "text": "Source code for langchain.utils.iter\nfrom collections import deque\nfrom itertools import islice\nfrom typing import (\n    Any,\n    ContextManager,\n    Deque,\n    Generator,\n    Generic,\n    Iterable,\n    Iterator,\n    List,\n    Optional,\n    Tuple,\n    TypeVar,\n    Union,\n    overload,\n)\nfrom typing_extensions import Literal\nT = TypeVar(\"T\")\n[docs]class NoLock:\n    \"\"\"Dummy lock that provides the proper interface but no protection\"\"\"\n    def __enter__(self) -> None:\n        pass\n    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Literal[False]:\n        return False\n[docs]def tee_peer(\n    iterator: Iterator[T],\n    # the buffer specific to this peer\n    buffer: Deque[T],\n    # the buffers of all peers, including our own\n    peers: List[Deque[T]],\n    lock: ContextManager[Any],\n) -> Generator[T, None, None]:\n    \"\"\"An individual iterator of a :py:func:`~.tee`\"\"\"\n    try:\n        while True:\n            if not buffer:\n                with lock:\n                    # Another peer produced an item while we were waiting for the lock.\n                    # Proceed with the next loop iteration to yield the item.\n                    if buffer:\n                        continue\n                    try:\n                        item = next(iterator)\n                    except StopIteration:\n                        break\n                    else:\n                        # Append to all buffers, including our own. We'll fetch our\n                        # item from the buffer again, instead of yielding it directly.\n                        # This ensures the proper item ordering if any of our peers\n                        # are fetching items concurrently. They may have buffered their\n                        # item already.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/iter.html"}
{"id": "5c25de5b34be-1", "text": "# are fetching items concurrently. They may have buffered their\n                        # item already.\n                        for peer_buffer in peers:\n                            peer_buffer.append(item)\n            yield buffer.popleft()\n    finally:\n        with lock:\n            # this peer is done \u2013 remove its buffer\n            for idx, peer_buffer in enumerate(peers):  # pragma: no branch\n                if peer_buffer is buffer:\n                    peers.pop(idx)\n                    break\n            # if we are the last peer, try and close the iterator\n            if not peers and hasattr(iterator, \"close\"):\n                iterator.close()\n[docs]class Tee(Generic[T]):\n    \"\"\"\n    Create ``n`` separate asynchronous iterators over ``iterable``\n    This splits a single ``iterable`` into multiple iterators, each providing\n    the same items in the same order.\n    All child iterators may advance separately but share the same items\n    from ``iterable`` -- when the most advanced iterator retrieves an item,\n    it is buffered until the least advanced iterator has yielded it as well.\n    A ``tee`` works lazily and can handle an infinite ``iterable``, provided\n    that all iterators advance.\n    .. code-block:: python3\n        async def derivative(sensor_data):\n            previous, current = a.tee(sensor_data, n=2)\n            await a.anext(previous)  # advance one iterator\n            return a.map(operator.sub, previous, current)\n    Unlike :py:func:`itertools.tee`, :py:func:`~.tee` returns a custom type instead\n    of a :py:class:`tuple`. Like a tuple, it can be indexed, iterated and unpacked\n    to get the child iterators. In addition, its :py:meth:`~.tee.aclose` method", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/iter.html"}
{"id": "5c25de5b34be-2", "text": "immediately closes all children, and it can be used in an ``async with`` context\n    for the same effect.\n    If ``iterable`` is an iterator and read elsewhere, ``tee`` will *not*\n    provide these items. Also, ``tee`` must internally buffer each item until the\n    last iterator has yielded it; if the most and least advanced iterator differ\n    by most data, using a :py:class:`list` is more efficient (but not lazy).\n    If the underlying iterable is concurrency safe (``anext`` may be awaited\n    concurrently) the resulting iterators are concurrency safe as well. Otherwise,\n    the iterators are safe if there is only ever one single \"most advanced\" iterator.\n    To enforce sequential use of ``anext``, provide a ``lock``\n    - e.g. an :py:class:`asyncio.Lock` instance in an :py:mod:`asyncio` application -\n    and access is automatically synchronised.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        iterable: Iterator[T],\n        n: int = 2,\n        *,\n        lock: Optional[ContextManager[Any]] = None,\n    ):\n        self._iterator = iter(iterable)\n        self._buffers: List[Deque[T]] = [deque() for _ in range(n)]\n        self._children = tuple(\n            tee_peer(\n                iterator=self._iterator,\n                buffer=buffer,\n                peers=self._buffers,\n                lock=lock if lock is not None else NoLock(),\n            )\n            for buffer in self._buffers\n        )\n    def __len__(self) -> int:\n        return len(self._children)\n    @overload\n    def __getitem__(self, item: int) -> Iterator[T]:\n        ...\n    @overload", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/iter.html"}
{"id": "5c25de5b34be-3", "text": "...\n    @overload\n    def __getitem__(self, item: slice) -> Tuple[Iterator[T], ...]:\n        ...\n    def __getitem__(\n        self, item: Union[int, slice]\n    ) -> Union[Iterator[T], Tuple[Iterator[T], ...]]:\n        return self._children[item]\n    def __iter__(self) -> Iterator[Iterator[T]]:\n        yield from self._children\n    def __enter__(self) -> \"Tee[T]\":\n        return self\n    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Literal[False]:\n        self.close()\n        return False\n[docs]    def close(self) -> None:\n        for child in self._children:\n            child.close()\n# Why this is needed https://stackoverflow.com/a/44638570\nsafetee = Tee\n[docs]def batch_iterate(size: int, iterable: Iterable[T]) -> Iterator[List[T]]:\n    \"\"\"Utility batching function.\"\"\"\n    it = iter(iterable)\n    while True:\n        chunk = list(islice(it, size))\n        if not chunk:\n            return\n        yield chunk", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/iter.html"}
{"id": "5bc70a4a41df-0", "text": "Source code for langchain.utils.aiter\n\"\"\"\nAdapted from\nhttps://github.com/maxfischer2781/asyncstdlib/blob/master/asyncstdlib/itertools.py\nMIT License\n\"\"\"\nfrom collections import deque\nfrom typing import (\n    Any,\n    AsyncContextManager,\n    AsyncGenerator,\n    AsyncIterator,\n    Awaitable,\n    Callable,\n    Deque,\n    Generic,\n    Iterator,\n    List,\n    Optional,\n    Tuple,\n    TypeVar,\n    Union,\n    cast,\n    overload,\n)\nT = TypeVar(\"T\")\n_no_default = object()\n# https://github.com/python/cpython/blob/main/Lib/test/test_asyncgen.py#L54\n# before 3.10, the builtin anext() was not available\n[docs]def py_anext(\n    iterator: AsyncIterator[T], default: Union[T, Any] = _no_default\n) -> Awaitable[Union[T, None, Any]]:\n    \"\"\"Pure-Python implementation of anext() for testing purposes.\n    Closely matches the builtin anext() C implementation.\n    Can be used to compare the built-in implementation of the inner\n    coroutines machinery to C-implementation of __anext__() and send()\n    or throw() on the returned generator.\n    \"\"\"\n    try:\n        __anext__ = cast(\n            Callable[[AsyncIterator[T]], Awaitable[T]], type(iterator).__anext__\n        )\n    except AttributeError:\n        raise TypeError(f\"{iterator!r} is not an async iterator\")\n    if default is _no_default:\n        return __anext__(iterator)\n    async def anext_impl() -> Union[T, Any]:\n        try:\n            # The C code is way more low-level than this, as it implements", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html"}
{"id": "5bc70a4a41df-1", "text": "# The C code is way more low-level than this, as it implements\n            # all methods of the iterator protocol. In this implementation\n            # we're relying on higher-level coroutine concepts, but that's\n            # exactly what we want -- crosstest pure-Python high-level\n            # implementation and low-level C anext() iterators.\n            return await __anext__(iterator)\n        except StopAsyncIteration:\n            return default\n    return anext_impl()\n[docs]class NoLock:\n    \"\"\"Dummy lock that provides the proper interface but no protection\"\"\"\n    async def __aenter__(self) -> None:\n        pass\n    async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:\n        return False\n[docs]async def tee_peer(\n    iterator: AsyncIterator[T],\n    # the buffer specific to this peer\n    buffer: Deque[T],\n    # the buffers of all peers, including our own\n    peers: List[Deque[T]],\n    lock: AsyncContextManager[Any],\n) -> AsyncGenerator[T, None]:\n    \"\"\"An individual iterator of a :py:func:`~.tee`\"\"\"\n    try:\n        while True:\n            if not buffer:\n                async with lock:\n                    # Another peer produced an item while we were waiting for the lock.\n                    # Proceed with the next loop iteration to yield the item.\n                    if buffer:\n                        continue\n                    try:\n                        item = await iterator.__anext__()\n                    except StopAsyncIteration:\n                        break\n                    else:\n                        # Append to all buffers, including our own. We'll fetch our\n                        # item from the buffer again, instead of yielding it directly.\n                        # This ensures the proper item ordering if any of our peers", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html"}
{"id": "5bc70a4a41df-2", "text": "# This ensures the proper item ordering if any of our peers\n                        # are fetching items concurrently. They may have buffered their\n                        # item already.\n                        for peer_buffer in peers:\n                            peer_buffer.append(item)\n            yield buffer.popleft()\n    finally:\n        async with lock:\n            # this peer is done \u2013 remove its buffer\n            for idx, peer_buffer in enumerate(peers):  # pragma: no branch\n                if peer_buffer is buffer:\n                    peers.pop(idx)\n                    break\n            # if we are the last peer, try and close the iterator\n            if not peers and hasattr(iterator, \"aclose\"):\n                await iterator.aclose()\n[docs]class Tee(Generic[T]):\n    \"\"\"\n    Create ``n`` separate asynchronous iterators over ``iterable``\n    This splits a single ``iterable`` into multiple iterators, each providing\n    the same items in the same order.\n    All child iterators may advance separately but share the same items\n    from ``iterable`` -- when the most advanced iterator retrieves an item,\n    it is buffered until the least advanced iterator has yielded it as well.\n    A ``tee`` works lazily and can handle an infinite ``iterable``, provided\n    that all iterators advance.\n    .. code-block:: python3\n        async def derivative(sensor_data):\n            previous, current = a.tee(sensor_data, n=2)\n            await a.anext(previous)  # advance one iterator\n            return a.map(operator.sub, previous, current)\n    Unlike :py:func:`itertools.tee`, :py:func:`~.tee` returns a custom type instead\n    of a :py:class:`tuple`. Like a tuple, it can be indexed, iterated and unpacked", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html"}
{"id": "5bc70a4a41df-3", "text": "to get the child iterators. In addition, its :py:meth:`~.tee.aclose` method\n    immediately closes all children, and it can be used in an ``async with`` context\n    for the same effect.\n    If ``iterable`` is an iterator and read elsewhere, ``tee`` will *not*\n    provide these items. Also, ``tee`` must internally buffer each item until the\n    last iterator has yielded it; if the most and least advanced iterator differ\n    by most data, using a :py:class:`list` is more efficient (but not lazy).\n    If the underlying iterable is concurrency safe (``anext`` may be awaited\n    concurrently) the resulting iterators are concurrency safe as well. Otherwise,\n    the iterators are safe if there is only ever one single \"most advanced\" iterator.\n    To enforce sequential use of ``anext``, provide a ``lock``\n    - e.g. an :py:class:`asyncio.Lock` instance in an :py:mod:`asyncio` application -\n    and access is automatically synchronised.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        iterable: AsyncIterator[T],\n        n: int = 2,\n        *,\n        lock: Optional[AsyncContextManager[Any]] = None,\n    ):\n        self._iterator = iterable.__aiter__()  # before 3.10 aiter() doesn't exist\n        self._buffers: List[Deque[T]] = [deque() for _ in range(n)]\n        self._children = tuple(\n            tee_peer(\n                iterator=self._iterator,\n                buffer=buffer,\n                peers=self._buffers,\n                lock=lock if lock is not None else NoLock(),\n            )\n            for buffer in self._buffers\n        )\n    def __len__(self) -> int:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html"}
{"id": "5bc70a4a41df-4", "text": ")\n    def __len__(self) -> int:\n        return len(self._children)\n    @overload\n    def __getitem__(self, item: int) -> AsyncIterator[T]:\n        ...\n    @overload\n    def __getitem__(self, item: slice) -> Tuple[AsyncIterator[T], ...]:\n        ...\n    def __getitem__(\n        self, item: Union[int, slice]\n    ) -> Union[AsyncIterator[T], Tuple[AsyncIterator[T], ...]]:\n        return self._children[item]\n    def __iter__(self) -> Iterator[AsyncIterator[T]]:\n        yield from self._children\n    async def __aenter__(self) -> \"Tee[T]\":\n        return self\n    async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:\n        await self.aclose()\n        return False\n[docs]    async def aclose(self) -> None:\n        for child in self._children:\n            await child.aclose()\natee = Tee", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html"}
{"id": "bfda83f3e387-0", "text": "Source code for langchain.utils.env\nimport os\nfrom typing import Any, Dict, Optional\n[docs]def get_from_dict_or_env(\n    data: Dict[str, Any], key: str, env_key: str, default: Optional[str] = None\n) -> str:\n    \"\"\"Get a value from a dictionary or an environment variable.\"\"\"\n    if key in data and data[key]:\n        return data[key]\n    else:\n        return get_from_env(key, env_key, default=default)\n[docs]def get_from_env(key: str, env_key: str, default: Optional[str] = None) -> str:\n    \"\"\"Get a value from a dictionary or an environment variable.\"\"\"\n    if env_key in os.environ and os.environ[env_key]:\n        return os.environ[env_key]\n    elif default is not None:\n        return default\n    else:\n        raise ValueError(\n            f\"Did not find {key}, please add an environment variable\"\n            f\" `{env_key}` which contains it, or pass\"\n            f\"  `{key}` as a named parameter.\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/env.html"}
{"id": "e8e17d8d09be-0", "text": "Source code for langchain.utils.pydantic\n\"\"\"Utilities for tests.\"\"\"\n[docs]def get_pydantic_major_version() -> int:\n    \"\"\"Get the major version of Pydantic.\"\"\"\n    try:\n        import pydantic\n        return int(pydantic.__version__.split(\".\")[0])\n    except ImportError:\n        return 0\nPYDANTIC_MAJOR_VERSION = get_pydantic_major_version()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/pydantic.html"}
{"id": "8f93ca75ae42-0", "text": "Source code for langchain.utils.math\n\"\"\"Math utils.\"\"\"\nimport logging\nfrom typing import List, Optional, Tuple, Union\nimport numpy as np\nlogger = logging.getLogger(__name__)\nMatrix = Union[List[List[float]], List[np.ndarray], np.ndarray]\n[docs]def cosine_similarity(X: Matrix, Y: Matrix) -> np.ndarray:\n    \"\"\"Row-wise cosine similarity between two equal-width matrices.\"\"\"\n    if len(X) == 0 or len(Y) == 0:\n        return np.array([])\n    X = np.array(X)\n    Y = np.array(Y)\n    if X.shape[1] != Y.shape[1]:\n        raise ValueError(\n            f\"Number of columns in X and Y must be the same. X has shape {X.shape} \"\n            f\"and Y has shape {Y.shape}.\"\n        )\n    try:\n        import simsimd as simd\n        X = np.array(X, dtype=np.float32)\n        Y = np.array(Y, dtype=np.float32)\n        Z = 1 - simd.cdist(X, Y, metric=\"cosine\")\n        if isinstance(Z, float):\n            return np.array([Z])\n        return Z\n    except ImportError:\n        logger.info(\n            \"Unable to import simsimd, defaulting to NumPy implementation. If you want \"\n            \"to use simsimd please install with `pip install simsimd`.\"\n        )\n        X_norm = np.linalg.norm(X, axis=1)\n        Y_norm = np.linalg.norm(Y, axis=1)\n        # Ignore divide by zero errors run time warnings as those are handled below.\n        with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n            similarity = np.dot(X, Y.T) / np.outer(X_norm, Y_norm)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/math.html"}
{"id": "8f93ca75ae42-1", "text": "similarity = np.dot(X, Y.T) / np.outer(X_norm, Y_norm)\n        similarity[np.isnan(similarity) | np.isinf(similarity)] = 0.0\n        return similarity\n[docs]def cosine_similarity_top_k(\n    X: Matrix,\n    Y: Matrix,\n    top_k: Optional[int] = 5,\n    score_threshold: Optional[float] = None,\n) -> Tuple[List[Tuple[int, int]], List[float]]:\n    \"\"\"Row-wise cosine similarity with optional top-k and score threshold filtering.\n    Args:\n        X: Matrix.\n        Y: Matrix, same width as X.\n        top_k: Max number of results to return.\n        score_threshold: Minimum cosine similarity of results.\n    Returns:\n        Tuple of two lists. First contains two-tuples of indices (X_idx, Y_idx),\n            second contains corresponding cosine similarities.\n    \"\"\"\n    if len(X) == 0 or len(Y) == 0:\n        return [], []\n    score_array = cosine_similarity(X, Y)\n    score_threshold = score_threshold or -1.0\n    score_array[score_array < score_threshold] = 0\n    top_k = min(top_k or len(score_array), np.count_nonzero(score_array))\n    top_k_idxs = np.argpartition(score_array, -top_k, axis=None)[-top_k:]\n    top_k_idxs = top_k_idxs[np.argsort(score_array.ravel()[top_k_idxs])][::-1]\n    ret_idxs = np.unravel_index(top_k_idxs, score_array.shape)\n    scores = score_array.ravel()[top_k_idxs].tolist()\n    return list(zip(*ret_idxs)), scores  # type: ignore", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/math.html"}
{"id": "5c6b15563446-0", "text": "Source code for langchain.utils.json_schema\nfrom __future__ import annotations\nfrom copy import deepcopy\nfrom typing import Any, List, Optional, Sequence\ndef _retrieve_ref(path: str, schema: dict) -> dict:\n    components = path.split(\"/\")\n    if components[0] != \"#\":\n        raise ValueError(\n            \"ref paths are expected to be URI fragments, meaning they should start \"\n            \"with #.\"\n        )\n    out = schema\n    for component in components[1:]:\n        out = out[component]\n    return deepcopy(out)\ndef _dereference_refs_helper(\n    obj: Any, full_schema: dict, skip_keys: Sequence[str]\n) -> Any:\n    if isinstance(obj, dict):\n        obj_out = {}\n        for k, v in obj.items():\n            if k in skip_keys:\n                obj_out[k] = v\n            elif k == \"$ref\":\n                ref = _retrieve_ref(v, full_schema)\n                return _dereference_refs_helper(ref, full_schema, skip_keys)\n            elif isinstance(v, (list, dict)):\n                obj_out[k] = _dereference_refs_helper(v, full_schema, skip_keys)\n            else:\n                obj_out[k] = v\n        return obj_out\n    elif isinstance(obj, list):\n        return [_dereference_refs_helper(el, full_schema, skip_keys) for el in obj]\n    else:\n        return obj\ndef _infer_skip_keys(obj: Any, full_schema: dict) -> List[str]:\n    keys = []\n    if isinstance(obj, dict):\n        for k, v in obj.items():\n            if k == \"$ref\":\n                ref = _retrieve_ref(v, full_schema)\n                keys.append(v.split(\"/\")[1])\n                keys += _infer_skip_keys(ref, full_schema)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/json_schema.html"}
{"id": "5c6b15563446-1", "text": "keys += _infer_skip_keys(ref, full_schema)\n            elif isinstance(v, (list, dict)):\n                keys += _infer_skip_keys(v, full_schema)\n    elif isinstance(obj, list):\n        for el in obj:\n            keys += _infer_skip_keys(el, full_schema)\n    return keys\n[docs]def dereference_refs(\n    schema_obj: dict,\n    *,\n    full_schema: Optional[dict] = None,\n    skip_keys: Optional[Sequence[str]] = None,\n) -> dict:\n    \"\"\"Try to substitute $refs in JSON Schema.\"\"\"\n    full_schema = full_schema or schema_obj\n    skip_keys = (\n        skip_keys\n        if skip_keys is not None\n        else _infer_skip_keys(schema_obj, full_schema)\n    )\n    return _dereference_refs_helper(schema_obj, full_schema, skip_keys)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/json_schema.html"}
{"id": "83e5ddab3fbb-0", "text": "Source code for langchain.utils.input\n\"\"\"Handle chained inputs.\"\"\"\nfrom typing import Dict, List, Optional, TextIO\n_TEXT_COLOR_MAPPING = {\n    \"blue\": \"36;1\",\n    \"yellow\": \"33;1\",\n    \"pink\": \"38;5;200\",\n    \"green\": \"32;1\",\n    \"red\": \"31;1\",\n}\n[docs]def get_color_mapping(\n    items: List[str], excluded_colors: Optional[List] = None\n) -> Dict[str, str]:\n    \"\"\"Get mapping for items to a support color.\"\"\"\n    colors = list(_TEXT_COLOR_MAPPING.keys())\n    if excluded_colors is not None:\n        colors = [c for c in colors if c not in excluded_colors]\n    color_mapping = {item: colors[i % len(colors)] for i, item in enumerate(items)}\n    return color_mapping\n[docs]def get_colored_text(text: str, color: str) -> str:\n    \"\"\"Get colored text.\"\"\"\n    color_str = _TEXT_COLOR_MAPPING[color]\n    return f\"\\u001b[{color_str}m\\033[1;3m{text}\\u001b[0m\"\n[docs]def get_bolded_text(text: str) -> str:\n    \"\"\"Get bolded text.\"\"\"\n    return f\"\\033[1m{text}\\033[0m\"\n[docs]def print_text(\n    text: str, color: Optional[str] = None, end: str = \"\", file: Optional[TextIO] = None\n) -> None:\n    \"\"\"Print text with highlighting and no end characters.\"\"\"\n    text_to_print = get_colored_text(text, color) if color else text\n    print(text_to_print, end=end, file=file)\n    if file:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/input.html"}
{"id": "83e5ddab3fbb-1", "text": "print(text_to_print, end=end, file=file)\n    if file:\n        file.flush()  # ensure all printed content are written to file", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/input.html"}
{"id": "6fa2e44b0899-0", "text": "Source code for langchain.utils.utils\n\"\"\"Generic utility functions.\"\"\"\nimport contextlib\nimport datetime\nimport functools\nimport importlib\nimport warnings\nfrom importlib.metadata import version\nfrom typing import Any, Callable, Dict, Optional, Set, Tuple, Union\nfrom packaging.version import parse\nfrom requests import HTTPError, Response\nfrom langchain.pydantic_v1 import SecretStr\n[docs]def xor_args(*arg_groups: Tuple[str, ...]) -> Callable:\n    \"\"\"Validate specified keyword args are mutually exclusive.\"\"\"\n    def decorator(func: Callable) -> Callable:\n        @functools.wraps(func)\n        def wrapper(*args: Any, **kwargs: Any) -> Any:\n            \"\"\"Validate exactly one arg in each group is not None.\"\"\"\n            counts = [\n                sum(1 for arg in arg_group if kwargs.get(arg) is not None)\n                for arg_group in arg_groups\n            ]\n            invalid_groups = [i for i, count in enumerate(counts) if count != 1]\n            if invalid_groups:\n                invalid_group_names = [\", \".join(arg_groups[i]) for i in invalid_groups]\n                raise ValueError(\n                    \"Exactly one argument in each of the following\"\n                    \" groups must be defined:\"\n                    f\" {', '.join(invalid_group_names)}\"\n                )\n            return func(*args, **kwargs)\n        return wrapper\n    return decorator\n[docs]def raise_for_status_with_text(response: Response) -> None:\n    \"\"\"Raise an error with the response text.\"\"\"\n    try:\n        response.raise_for_status()\n    except HTTPError as e:\n        raise ValueError(response.text) from e\n[docs]@contextlib.contextmanager\ndef mock_now(dt_value):  # type: ignore\n    \"\"\"Context manager for mocking out datetime.now() in unit tests.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html"}
{"id": "6fa2e44b0899-1", "text": "\"\"\"Context manager for mocking out datetime.now() in unit tests.\n    Example:\n    with mock_now(datetime.datetime(2011, 2, 3, 10, 11)):\n        assert datetime.datetime.now() == datetime.datetime(2011, 2, 3, 10, 11)\n    \"\"\"\n    class MockDateTime(datetime.datetime):\n        \"\"\"Mock datetime.datetime.now() with a fixed datetime.\"\"\"\n        @classmethod\n        def now(cls):  # type: ignore\n            # Create a copy of dt_value.\n            return datetime.datetime(\n                dt_value.year,\n                dt_value.month,\n                dt_value.day,\n                dt_value.hour,\n                dt_value.minute,\n                dt_value.second,\n                dt_value.microsecond,\n                dt_value.tzinfo,\n            )\n    real_datetime = datetime.datetime\n    datetime.datetime = MockDateTime\n    try:\n        yield datetime.datetime\n    finally:\n        datetime.datetime = real_datetime\n[docs]def guard_import(\n    module_name: str, *, pip_name: Optional[str] = None, package: Optional[str] = None\n) -> Any:\n    \"\"\"Dynamically imports a module and raises a helpful exception if the module is not\n    installed.\"\"\"\n    try:\n        module = importlib.import_module(module_name, package)\n    except ImportError:\n        raise ImportError(\n            f\"Could not import {module_name} python package. \"\n            f\"Please install it with `pip install {pip_name or module_name}`.\"\n        )\n    return module\n[docs]def check_package_version(\n    package: str,\n    lt_version: Optional[str] = None,\n    lte_version: Optional[str] = None,\n    gt_version: Optional[str] = None,\n    gte_version: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html"}
{"id": "6fa2e44b0899-2", "text": "gte_version: Optional[str] = None,\n) -> None:\n    \"\"\"Check the version of a package.\"\"\"\n    imported_version = parse(version(package))\n    if lt_version is not None and imported_version >= parse(lt_version):\n        raise ValueError(\n            f\"Expected {package} version to be < {lt_version}. Received \"\n            f\"{imported_version}.\"\n        )\n    if lte_version is not None and imported_version > parse(lte_version):\n        raise ValueError(\n            f\"Expected {package} version to be <= {lte_version}. Received \"\n            f\"{imported_version}.\"\n        )\n    if gt_version is not None and imported_version <= parse(gt_version):\n        raise ValueError(\n            f\"Expected {package} version to be > {gt_version}. Received \"\n            f\"{imported_version}.\"\n        )\n    if gte_version is not None and imported_version < parse(gte_version):\n        raise ValueError(\n            f\"Expected {package} version to be >= {gte_version}. Received \"\n            f\"{imported_version}.\"\n        )\n[docs]def get_pydantic_field_names(pydantic_cls: Any) -> Set[str]:\n    \"\"\"Get field names, including aliases, for a pydantic class.\n    Args:\n        pydantic_cls: Pydantic class.\"\"\"\n    all_required_field_names = set()\n    for field in pydantic_cls.__fields__.values():\n        all_required_field_names.add(field.name)\n        if field.has_alias:\n            all_required_field_names.add(field.alias)\n    return all_required_field_names\n[docs]def build_extra_kwargs(\n    extra_kwargs: Dict[str, Any],\n    values: Dict[str, Any],\n    all_required_field_names: Set[str],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html"}
{"id": "6fa2e44b0899-3", "text": "values: Dict[str, Any],\n    all_required_field_names: Set[str],\n) -> Dict[str, Any]:\n    \"\"\"Build extra kwargs from values and extra_kwargs.\n    Args:\n        extra_kwargs: Extra kwargs passed in by user.\n        values: Values passed in by user.\n        all_required_field_names: All required field names for the pydantic class.\n    \"\"\"\n    for field_name in list(values):\n        if field_name in extra_kwargs:\n            raise ValueError(f\"Found {field_name} supplied twice.\")\n        if field_name not in all_required_field_names:\n            warnings.warn(\n                f\"\"\"WARNING! {field_name} is not default parameter.\n                {field_name} was transferred to model_kwargs.\n                Please confirm that {field_name} is what you intended.\"\"\"\n            )\n            extra_kwargs[field_name] = values.pop(field_name)\n    invalid_model_kwargs = all_required_field_names.intersection(extra_kwargs.keys())\n    if invalid_model_kwargs:\n        raise ValueError(\n            f\"Parameters {invalid_model_kwargs} should be specified explicitly. \"\n            f\"Instead they were passed in as part of `model_kwargs` parameter.\"\n        )\n    return extra_kwargs\n[docs]def convert_to_secret_str(value: Union[SecretStr, str]) -> SecretStr:\n    \"\"\"Convert a string to a SecretStr if needed.\"\"\"\n    if isinstance(value, SecretStr):\n        return value\n    return SecretStr(value)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html"}
{"id": "439bb05afb24-0", "text": "Source code for langchain.utils.loading\n\"\"\"Utilities for loading configurations from langchain-hub.\"\"\"\nimport os\nimport re\nimport tempfile\nfrom pathlib import Path, PurePosixPath\nfrom typing import Any, Callable, Optional, Set, TypeVar, Union\nfrom urllib.parse import urljoin\nimport requests\nDEFAULT_REF = os.environ.get(\"LANGCHAIN_HUB_DEFAULT_REF\", \"master\")\nURL_BASE = os.environ.get(\n    \"LANGCHAIN_HUB_URL_BASE\",\n    \"https://raw.githubusercontent.com/hwchase17/langchain-hub/{ref}/\",\n)\nHUB_PATH_RE = re.compile(r\"lc(?P<ref>@[^:]+)?://(?P<path>.*)\")\nT = TypeVar(\"T\")\n[docs]def try_load_from_hub(\n    path: Union[str, Path],\n    loader: Callable[[str], T],\n    valid_prefix: str,\n    valid_suffixes: Set[str],\n    **kwargs: Any,\n) -> Optional[T]:\n    \"\"\"Load configuration from hub.  Returns None if path is not a hub path.\"\"\"\n    if not isinstance(path, str) or not (match := HUB_PATH_RE.match(path)):\n        return None\n    ref, remote_path_str = match.groups()\n    ref = ref[1:] if ref else DEFAULT_REF\n    remote_path = Path(remote_path_str)\n    if remote_path.parts[0] != valid_prefix:\n        return None\n    if remote_path.suffix[1:] not in valid_suffixes:\n        raise ValueError(f\"Unsupported file type, must be one of {valid_suffixes}.\")\n    # Using Path with URLs is not recommended, because on Windows\n    # the backslash is used as the path separator, which can cause issues\n    # when working with URLs that use forward slashes as the path separator.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/loading.html"}
{"id": "439bb05afb24-1", "text": "# when working with URLs that use forward slashes as the path separator.\n    # Instead, use PurePosixPath to ensure that forward slashes are used as the\n    # path separator, regardless of the operating system.\n    full_url = urljoin(URL_BASE.format(ref=ref), PurePosixPath(remote_path).__str__())\n    r = requests.get(full_url, timeout=5)\n    if r.status_code != 200:\n        raise ValueError(f\"Could not find file at {full_url}\")\n    with tempfile.TemporaryDirectory() as tmpdirname:\n        file = Path(tmpdirname) / remote_path.name\n        with open(file, \"wb\") as f:\n            f.write(r.content)\n        return loader(str(file), **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/loading.html"}
{"id": "99c9a7258161-0", "text": "Source code for langchain.utils.openai_functions\nfrom typing import Literal, Optional, Type, TypedDict\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.utils.json_schema import dereference_refs\n[docs]class FunctionDescription(TypedDict):\n    \"\"\"Representation of a callable function to the OpenAI API.\"\"\"\n    name: str\n    \"\"\"The name of the function.\"\"\"\n    description: str\n    \"\"\"A description of the function.\"\"\"\n    parameters: dict\n    \"\"\"The parameters of the function.\"\"\"\n[docs]class ToolDescription(TypedDict):\n    \"\"\"Representation of a callable function to the OpenAI API.\"\"\"\n    type: Literal[\"function\"]\n    function: FunctionDescription\n[docs]def convert_pydantic_to_openai_function(\n    model: Type[BaseModel],\n    *,\n    name: Optional[str] = None,\n    description: Optional[str] = None,\n) -> FunctionDescription:\n    \"\"\"Converts a Pydantic model to a function description for the OpenAI API.\"\"\"\n    schema = dereference_refs(model.schema())\n    schema.pop(\"definitions\", None)\n    return {\n        \"name\": name or schema[\"title\"],\n        \"description\": description or schema[\"description\"],\n        \"parameters\": schema,\n    }\n[docs]def convert_pydantic_to_openai_tool(\n    model: Type[BaseModel],\n    *,\n    name: Optional[str] = None,\n    description: Optional[str] = None,\n) -> ToolDescription:\n    \"\"\"Converts a Pydantic model to a function description for the OpenAI API.\"\"\"\n    function = convert_pydantic_to_openai_function(\n        model, name=name, description=description\n    )\n    return {\"type\": \"function\", \"function\": function}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/openai_functions.html"}
{"id": "2d0db9c9e5db-0", "text": "Source code for langchain.utils.html\nimport re\nfrom typing import List, Optional, Sequence, Union\nfrom urllib.parse import urljoin, urlparse\nPREFIXES_TO_IGNORE = (\"javascript:\", \"mailto:\", \"#\")\nSUFFIXES_TO_IGNORE = (\n    \".css\",\n    \".js\",\n    \".ico\",\n    \".png\",\n    \".jpg\",\n    \".jpeg\",\n    \".gif\",\n    \".svg\",\n    \".csv\",\n    \".bz2\",\n    \".zip\",\n    \".epub\",\n)\nSUFFIXES_TO_IGNORE_REGEX = (\n    \"(?!\" + \"|\".join([re.escape(s) + r\"[\\#'\\\"]\" for s in SUFFIXES_TO_IGNORE]) + \")\"\n)\nPREFIXES_TO_IGNORE_REGEX = (\n    \"(?!\" + \"|\".join([re.escape(s) for s in PREFIXES_TO_IGNORE]) + \")\"\n)\nDEFAULT_LINK_REGEX = (\n    rf\"href=[\\\"']{PREFIXES_TO_IGNORE_REGEX}((?:{SUFFIXES_TO_IGNORE_REGEX}.)*?)[\\#'\\\"]\"\n)\n[docs]def find_all_links(\n    raw_html: str, *, pattern: Union[str, re.Pattern, None] = None\n) -> List[str]:\n    \"\"\"Extract all links from a raw html string.\n    Args:\n        raw_html: original html.\n        pattern: Regex to use for extracting links from raw html.\n    Returns:\n        List[str]: all links\n    \"\"\"\n    pattern = pattern or DEFAULT_LINK_REGEX\n    return list(set(re.findall(pattern, raw_html)))\n[docs]def extract_sub_links(\n    raw_html: str,\n    url: str,\n    *,\n    base_url: Optional[str] = None,\n    pattern: Union[str, re.Pattern, None] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/html.html"}
{"id": "2d0db9c9e5db-1", "text": "pattern: Union[str, re.Pattern, None] = None,\n    prevent_outside: bool = True,\n    exclude_prefixes: Sequence[str] = (),\n) -> List[str]:\n    \"\"\"Extract all links from a raw html string and convert into absolute paths.\n    Args:\n        raw_html: original html.\n        url: the url of the html.\n        base_url: the base url to check for outside links against.\n        pattern: Regex to use for extracting links from raw html.\n        prevent_outside: If True, ignore external links which are not children\n            of the base url.\n        exclude_prefixes: Exclude any URLs that start with one of these prefixes.\n    Returns:\n        List[str]: sub links\n    \"\"\"\n    base_url = base_url if base_url is not None else url\n    all_links = find_all_links(raw_html, pattern=pattern)\n    absolute_paths = set()\n    for link in all_links:\n        # Some may be absolute links like https://to/path\n        if link.startswith(\"http\"):\n            absolute_paths.add(link)\n        # Some may have omitted the protocol like //to/path\n        elif link.startswith(\"//\"):\n            absolute_paths.add(f\"{urlparse(url).scheme}:{link}\")\n        else:\n            absolute_paths.add(urljoin(url, link))\n    res = []\n    for path in absolute_paths:\n        if any(path.startswith(exclude) for exclude in exclude_prefixes):\n            continue\n        if prevent_outside and not path.startswith(base_url):\n            continue\n        res.append(path)\n    return res", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/html.html"}
{"id": "387b0737e61b-0", "text": "Source code for langchain.utils.strings\nfrom typing import Any, List\n[docs]def stringify_value(val: Any) -> str:\n    \"\"\"Stringify a value.\n    Args:\n        val: The value to stringify.\n    Returns:\n        str: The stringified value.\n    \"\"\"\n    if isinstance(val, str):\n        return val\n    elif isinstance(val, dict):\n        return \"\\n\" + stringify_dict(val)\n    elif isinstance(val, list):\n        return \"\\n\".join(stringify_value(v) for v in val)\n    else:\n        return str(val)\n[docs]def stringify_dict(data: dict) -> str:\n    \"\"\"Stringify a dictionary.\n    Args:\n        data: The dictionary to stringify.\n    Returns:\n        str: The stringified dictionary.\n    \"\"\"\n    text = \"\"\n    for key, value in data.items():\n        text += key + \": \" + stringify_value(value) + \"\\n\"\n    return text\n[docs]def comma_list(items: List[Any]) -> str:\n    \"\"\"Convert a list to a comma-separated string.\"\"\"\n    return \", \".join(str(item) for item in items)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/strings.html"}
{"id": "ee25dac83a6d-0", "text": "Source code for langchain.utils.openai\nfrom __future__ import annotations\nfrom importlib.metadata import version\nfrom packaging.version import parse\n[docs]def is_openai_v1() -> bool:\n    _version = parse(version(\"openai\"))\n    return _version.major >= 1", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/openai.html"}
{"id": "e2abdfcbafba-0", "text": "Source code for langchain.utils.formatting\n\"\"\"Utilities for formatting strings.\"\"\"\nfrom string import Formatter\nfrom typing import Any, List, Mapping, Sequence, Union\n[docs]class StrictFormatter(Formatter):\n    \"\"\"A subclass of formatter that checks for extra keys.\"\"\"\n[docs]    def check_unused_args(\n        self,\n        used_args: Sequence[Union[int, str]],\n        args: Sequence,\n        kwargs: Mapping[str, Any],\n    ) -> None:\n        \"\"\"Check to see if extra parameters are passed.\"\"\"\n        extra = set(kwargs).difference(used_args)\n        if extra:\n            raise KeyError(extra)\n[docs]    def vformat(\n        self, format_string: str, args: Sequence, kwargs: Mapping[str, Any]\n    ) -> str:\n        \"\"\"Check that no arguments are provided.\"\"\"\n        if len(args) > 0:\n            raise ValueError(\n                \"No arguments should be provided, \"\n                \"everything should be passed as keyword arguments.\"\n            )\n        return super().vformat(format_string, args, kwargs)\n[docs]    def validate_input_variables(\n        self, format_string: str, input_variables: List[str]\n    ) -> None:\n        dummy_inputs = {input_variable: \"foo\" for input_variable in input_variables}\n        super().format(format_string, **dummy_inputs)\nformatter = StrictFormatter()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/utils/formatting.html"}
{"id": "7f01b8e69988-0", "text": "Source code for langchain.adapters.openai\nfrom __future__ import annotations\nimport importlib\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Dict,\n    Iterable,\n    List,\n    Mapping,\n    Sequence,\n    Union,\n    overload,\n)\nfrom typing_extensions import Literal\nfrom langchain.schema.chat import ChatSession\nfrom langchain.schema.messages import (\n    AIMessage,\n    AIMessageChunk,\n    BaseMessage,\n    BaseMessageChunk,\n    ChatMessage,\n    FunctionMessage,\n    HumanMessage,\n    SystemMessage,\n    ToolMessage,\n)\n[docs]async def aenumerate(\n    iterable: AsyncIterator[Any], start: int = 0\n) -> AsyncIterator[tuple[int, Any]]:\n    \"\"\"Async version of enumerate function.\"\"\"\n    i = start\n    async for x in iterable:\n        yield i, x\n        i += 1\n[docs]def convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:\n    \"\"\"Convert a dictionary to a LangChain message.\n    Args:\n        _dict: The dictionary.\n    Returns:\n        The LangChain message.\n    \"\"\"\n    role = _dict[\"role\"]\n    if role == \"user\":\n        return HumanMessage(content=_dict[\"content\"])\n    elif role == \"assistant\":\n        # Fix for azure\n        # Also OpenAI returns None for tool invocations\n        content = _dict.get(\"content\", \"\") or \"\"\n        additional_kwargs: Dict = {}\n        if _dict.get(\"function_call\"):\n            additional_kwargs[\"function_call\"] = dict(_dict[\"function_call\"])\n        if _dict.get(\"tool_calls\"):\n            additional_kwargs[\"tool_calls\"] = _dict[\"tool_calls\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html"}
{"id": "7f01b8e69988-1", "text": "additional_kwargs[\"tool_calls\"] = _dict[\"tool_calls\"]\n        return AIMessage(content=content, additional_kwargs=additional_kwargs)\n    elif role == \"system\":\n        return SystemMessage(content=_dict[\"content\"])\n    elif role == \"function\":\n        return FunctionMessage(content=_dict[\"content\"], name=_dict[\"name\"])\n    elif role == \"tool\":\n        return ToolMessage(content=_dict[\"content\"], tool_call_id=_dict[\"tool_call_id\"])\n    else:\n        return ChatMessage(content=_dict[\"content\"], role=role)\n[docs]def convert_message_to_dict(message: BaseMessage) -> dict:\n    \"\"\"Convert a LangChain message to a dictionary.\n    Args:\n        message: The LangChain message.\n    Returns:\n        The dictionary.\n    \"\"\"\n    message_dict: Dict[str, Any]\n    if isinstance(message, ChatMessage):\n        message_dict = {\"role\": message.role, \"content\": message.content}\n    elif isinstance(message, HumanMessage):\n        message_dict = {\"role\": \"user\", \"content\": message.content}\n    elif isinstance(message, AIMessage):\n        message_dict = {\"role\": \"assistant\", \"content\": message.content}\n        if \"function_call\" in message.additional_kwargs:\n            message_dict[\"function_call\"] = message.additional_kwargs[\"function_call\"]\n            # If function call only, content is None not empty string\n            if message_dict[\"content\"] == \"\":\n                message_dict[\"content\"] = None\n        if \"tool_calls\" in message.additional_kwargs:\n            message_dict[\"tool_calls\"] = message.additional_kwargs[\"tool_calls\"]\n            # If tool calls only, content is None not empty string\n            if message_dict[\"content\"] == \"\":\n                message_dict[\"content\"] = None\n    elif isinstance(message, SystemMessage):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html"}
{"id": "7f01b8e69988-2", "text": "message_dict[\"content\"] = None\n    elif isinstance(message, SystemMessage):\n        message_dict = {\"role\": \"system\", \"content\": message.content}\n    elif isinstance(message, FunctionMessage):\n        message_dict = {\n            \"role\": \"function\",\n            \"content\": message.content,\n            \"name\": message.name,\n        }\n    elif isinstance(message, ToolMessage):\n        message_dict = {\n            \"role\": \"tool\",\n            \"content\": message.content,\n            \"tool_call_id\": message.tool_call_id,\n        }\n    else:\n        raise TypeError(f\"Got unknown type {message}\")\n    if \"name\" in message.additional_kwargs:\n        message_dict[\"name\"] = message.additional_kwargs[\"name\"]\n    return message_dict\n[docs]def convert_openai_messages(messages: Sequence[Dict[str, Any]]) -> List[BaseMessage]:\n    \"\"\"Convert dictionaries representing OpenAI messages to LangChain format.\n    Args:\n        messages: List of dictionaries representing OpenAI messages\n    Returns:\n        List of LangChain BaseMessage objects.\n    \"\"\"\n    return [convert_dict_to_message(m) for m in messages]\ndef _convert_message_chunk_to_delta(chunk: BaseMessageChunk, i: int) -> Dict[str, Any]:\n    _dict: Dict[str, Any] = {}\n    if isinstance(chunk, AIMessageChunk):\n        if i == 0:\n            # Only shows up in the first chunk\n            _dict[\"role\"] = \"assistant\"\n        if \"function_call\" in chunk.additional_kwargs:\n            _dict[\"function_call\"] = chunk.additional_kwargs[\"function_call\"]\n            # If the first chunk is a function call, the content is not empty string,\n            # not missing, but None.\n            if i == 0:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html"}
{"id": "7f01b8e69988-3", "text": "# not missing, but None.\n            if i == 0:\n                _dict[\"content\"] = None\n        else:\n            _dict[\"content\"] = chunk.content\n    else:\n        raise ValueError(f\"Got unexpected streaming chunk type: {type(chunk)}\")\n    # This only happens at the end of streams, and OpenAI returns as empty dict\n    if _dict == {\"content\": \"\"}:\n        _dict = {}\n    return {\"choices\": [{\"delta\": _dict}]}\n[docs]class ChatCompletion:\n    \"\"\"Chat completion.\"\"\"\n    @overload\n    @staticmethod\n    def create(\n        messages: Sequence[Dict[str, Any]],\n        *,\n        provider: str = \"ChatOpenAI\",\n        stream: Literal[False] = False,\n        **kwargs: Any,\n    ) -> dict:\n        ...\n    @overload\n    @staticmethod\n    def create(\n        messages: Sequence[Dict[str, Any]],\n        *,\n        provider: str = \"ChatOpenAI\",\n        stream: Literal[True],\n        **kwargs: Any,\n    ) -> Iterable:\n        ...\n[docs]    @staticmethod\n    def create(\n        messages: Sequence[Dict[str, Any]],\n        *,\n        provider: str = \"ChatOpenAI\",\n        stream: bool = False,\n        **kwargs: Any,\n    ) -> Union[dict, Iterable]:\n        models = importlib.import_module(\"langchain.chat_models\")\n        model_cls = getattr(models, provider)\n        model_config = model_cls(**kwargs)\n        converted_messages = convert_openai_messages(messages)\n        if not stream:\n            result = model_config.invoke(converted_messages)\n            return {\"choices\": [{\"message\": convert_message_to_dict(result)}]}\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html"}
{"id": "7f01b8e69988-4", "text": "return {\"choices\": [{\"message\": convert_message_to_dict(result)}]}\n        else:\n            return (\n                _convert_message_chunk_to_delta(c, i)\n                for i, c in enumerate(model_config.stream(converted_messages))\n            )\n    @overload\n    @staticmethod\n    async def acreate(\n        messages: Sequence[Dict[str, Any]],\n        *,\n        provider: str = \"ChatOpenAI\",\n        stream: Literal[False] = False,\n        **kwargs: Any,\n    ) -> dict:\n        ...\n    @overload\n    @staticmethod\n    async def acreate(\n        messages: Sequence[Dict[str, Any]],\n        *,\n        provider: str = \"ChatOpenAI\",\n        stream: Literal[True],\n        **kwargs: Any,\n    ) -> AsyncIterator:\n        ...\n[docs]    @staticmethod\n    async def acreate(\n        messages: Sequence[Dict[str, Any]],\n        *,\n        provider: str = \"ChatOpenAI\",\n        stream: bool = False,\n        **kwargs: Any,\n    ) -> Union[dict, AsyncIterator]:\n        models = importlib.import_module(\"langchain.chat_models\")\n        model_cls = getattr(models, provider)\n        model_config = model_cls(**kwargs)\n        converted_messages = convert_openai_messages(messages)\n        if not stream:\n            result = await model_config.ainvoke(converted_messages)\n            return {\"choices\": [{\"message\": convert_message_to_dict(result)}]}\n        else:\n            return (\n                _convert_message_chunk_to_delta(c, i)\n                async for i, c in aenumerate(model_config.astream(converted_messages))\n            )\ndef _has_assistant_message(session: ChatSession) -> bool:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html"}
{"id": "7f01b8e69988-5", "text": ")\ndef _has_assistant_message(session: ChatSession) -> bool:\n    \"\"\"Check if chat session has an assistant message.\"\"\"\n    return any([isinstance(m, AIMessage) for m in session[\"messages\"]])\n[docs]def convert_messages_for_finetuning(\n    sessions: Iterable[ChatSession],\n) -> List[List[dict]]:\n    \"\"\"Convert messages to a list of lists of dictionaries for fine-tuning.\n    Args:\n        sessions: The chat sessions.\n    Returns:\n        The list of lists of dictionaries.\n    \"\"\"\n    return [\n        [convert_message_to_dict(s) for s in session[\"messages\"]]\n        for session in sessions\n        if _has_assistant_message(session)\n    ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html"}
{"id": "e883dc0a3205-0", "text": "Source code for langchain.document_loaders.geodataframe\nfrom typing import Any, Iterator, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class GeoDataFrameLoader(BaseLoader):\n    \"\"\"Load `geopandas` Dataframe.\"\"\"\n[docs]    def __init__(self, data_frame: Any, page_content_column: str = \"geometry\"):\n        \"\"\"Initialize with geopandas Dataframe.\n        Args:\n            data_frame: geopandas DataFrame object.\n            page_content_column: Name of the column containing the page content.\n              Defaults to \"geometry\".\n        \"\"\"\n        try:\n            import geopandas as gpd\n        except ImportError:\n            raise ImportError(\n                \"geopandas package not found, please install it with \"\n                \"`pip install geopandas`\"\n            )\n        if not isinstance(data_frame, gpd.GeoDataFrame):\n            raise ValueError(\n                f\"Expected data_frame to be a gpd.GeoDataFrame, got {type(data_frame)}\"\n            )\n        if page_content_column not in data_frame.columns:\n            raise ValueError(\n                f\"Expected data_frame to have a column named {page_content_column}\"\n            )\n        if not isinstance(data_frame[page_content_column].iloc[0], gpd.GeoSeries):\n            raise ValueError(\n                f\"Expected data_frame[{page_content_column}] to be a GeoSeries\"\n            )\n        self.data_frame = data_frame\n        self.page_content_column = page_content_column\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazy load records from dataframe.\"\"\"\n        # assumes all geometries in GeoSeries are same CRS and Geom Type", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/geodataframe.html"}
{"id": "e883dc0a3205-1", "text": "# assumes all geometries in GeoSeries are same CRS and Geom Type\n        crs_str = self.data_frame.crs.to_string() if self.data_frame.crs else None\n        geometry_type = self.data_frame.geometry.geom_type.iloc[0]\n        for _, row in self.data_frame.iterrows():\n            geom = row[self.page_content_column]\n            xmin, ymin, xmax, ymax = geom.bounds\n            metadata = row.to_dict()\n            metadata[\"crs\"] = crs_str\n            metadata[\"geometry_type\"] = geometry_type\n            metadata[\"xmin\"] = xmin\n            metadata[\"ymin\"] = ymin\n            metadata[\"xmax\"] = xmax\n            metadata[\"ymax\"] = ymax\n            metadata.pop(self.page_content_column)\n            # using WKT instead of str() to help GIS system interoperability\n            yield Document(page_content=geom.wkt, metadata=metadata)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load full dataframe.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/geodataframe.html"}
{"id": "280183bb8e43-0", "text": "Source code for langchain.document_loaders.mhtml\nimport email\nimport logging\nfrom typing import Dict, List, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n[docs]class MHTMLLoader(BaseLoader):\n    \"\"\"Parse `MHTML` files with `BeautifulSoup`.\"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        open_encoding: Union[str, None] = None,\n        bs_kwargs: Union[dict, None] = None,\n        get_text_separator: str = \"\",\n    ) -> None:\n        \"\"\"Initialise with path, and optionally, file encoding to use, and any kwargs\n        to pass to the BeautifulSoup object.\n        Args:\n            file_path: Path to file to load.\n            open_encoding: The encoding to use when opening the file.\n            bs_kwargs: Any kwargs to pass to the BeautifulSoup object.\n            get_text_separator: The separator to use when getting the text\n                from the soup.\n        \"\"\"\n        try:\n            import bs4  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"beautifulsoup4 package not found, please install it with \"\n                \"`pip install beautifulsoup4`\"\n            )\n        self.file_path = file_path\n        self.open_encoding = open_encoding\n        if bs_kwargs is None:\n            bs_kwargs = {\"features\": \"lxml\"}\n        self.bs_kwargs = bs_kwargs\n        self.get_text_separator = get_text_separator\n[docs]    def load(self) -> List[Document]:\n        from bs4 import BeautifulSoup\n        \"\"\"Load MHTML document into document objects.\"\"\"\n        with open(self.file_path, \"r\", encoding=self.open_encoding) as f:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mhtml.html"}
{"id": "280183bb8e43-1", "text": "with open(self.file_path, \"r\", encoding=self.open_encoding) as f:\n            message = email.message_from_string(f.read())\n            parts = message.get_payload()\n            if not isinstance(parts, list):\n                parts = [message]\n            for part in parts:\n                if part.get_content_type() == \"text/html\":\n                    html = part.get_payload(decode=True).decode()\n                    soup = BeautifulSoup(html, **self.bs_kwargs)\n                    text = soup.get_text(self.get_text_separator)\n                    if soup.title:\n                        title = str(soup.title.string)\n                    else:\n                        title = \"\"\n                    metadata: Dict[str, Union[str, None]] = {\n                        \"source\": self.file_path,\n                        \"title\": title,\n                    }\n                    return [Document(page_content=text, metadata=metadata)]\n        return []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mhtml.html"}
{"id": "f1fbedb3bbee-0", "text": "Source code for langchain.document_loaders.onedrive\n\"\"\"Loads data from OneDrive\"\"\"\nfrom __future__ import annotations\nimport logging\nfrom typing import TYPE_CHECKING, Iterator, List, Optional, Sequence, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base_o365 import (\n    O365BaseLoader,\n    _FileType,\n)\nfrom langchain.document_loaders.parsers.registry import get_parser\nfrom langchain.pydantic_v1 import Field\nif TYPE_CHECKING:\n    from O365.drive import Drive, Folder\nlogger = logging.getLogger(__name__)\n[docs]class OneDriveLoader(O365BaseLoader):\n    \"\"\"Load from `Microsoft OneDrive`.\"\"\"\n    drive_id: str = Field(...)\n    \"\"\" The ID of the OneDrive drive to load data from.\"\"\"\n    folder_path: Optional[str] = None\n    \"\"\" The path to the folder to load data from.\"\"\"\n    object_ids: Optional[List[str]] = None\n    \"\"\" The IDs of the objects to load data from.\"\"\"\n    @property\n    def _file_types(self) -> Sequence[_FileType]:\n        \"\"\"Return supported file types.\"\"\"\n        return _FileType.DOC, _FileType.DOCX, _FileType.PDF\n    @property\n    def _scopes(self) -> List[str]:\n        \"\"\"Return required scopes.\"\"\"\n        return [\"offline_access\", \"Files.Read.All\"]\n    def _get_folder_from_path(self, drive: Drive) -> Union[Folder, Drive]:\n        \"\"\"\n        Returns the folder or drive object located at the\n        specified path relative to the given drive.\n        Args:\n            drive (Drive): The root drive from which the folder path is relative.\n        Returns:\n            Union[Folder, Drive]: The folder or drive object\n            located at the specified path.\n        Raises:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive.html"}
{"id": "f1fbedb3bbee-1", "text": "located at the specified path.\n        Raises:\n            FileNotFoundError: If the path does not exist.\n        \"\"\"\n        subfolder_drive = drive\n        if self.folder_path is None:\n            return subfolder_drive\n        subfolders = [f for f in self.folder_path.split(\"/\") if f != \"\"]\n        if len(subfolders) == 0:\n            return subfolder_drive\n        items = subfolder_drive.get_items()\n        for subfolder in subfolders:\n            try:\n                subfolder_drive = list(filter(lambda x: subfolder in x.name, items))[0]\n                items = subfolder_drive.get_items()\n            except (IndexError, AttributeError):\n                raise FileNotFoundError(\"Path {} not exist.\".format(self.folder_path))\n        return subfolder_drive\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Load documents lazily. Use this when working at a large scale.\"\"\"\n        try:\n            from O365.drive import Drive\n        except ImportError:\n            raise ImportError(\n                \"O365 package not found, please install it with `pip install o365`\"\n            )\n        drive = self._auth().storage().get_drive(self.drive_id)\n        if not isinstance(drive, Drive):\n            raise ValueError(f\"There isn't a Drive with id {self.drive_id}.\")\n        blob_parser = get_parser(\"default\")\n        if self.folder_path:\n            folder = self._get_folder_from_path(drive)\n            for blob in self._load_from_folder(folder):\n                yield from blob_parser.lazy_parse(blob)\n        if self.object_ids:\n            for blob in self._load_from_object_ids(drive, self.object_ids):\n                yield from blob_parser.lazy_parse(blob)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load all documents.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive.html"}
{"id": "f1fbedb3bbee-2", "text": "\"\"\"Load all documents.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive.html"}
{"id": "ea6ad28f84de-0", "text": "Source code for langchain.document_loaders.weather\n\"\"\"Simple reader that reads weather data from OpenWeatherMap API\"\"\"\nfrom __future__ import annotations\nfrom datetime import datetime\nfrom typing import Iterator, List, Optional, Sequence\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utilities.openweathermap import OpenWeatherMapAPIWrapper\n[docs]class WeatherDataLoader(BaseLoader):\n    \"\"\"Load weather data with `Open Weather Map` API.\n    Reads the forecast & current weather of any location using OpenWeatherMap's free\n    API. Checkout 'https://openweathermap.org/appid' for more on how to generate a free\n    OpenWeatherMap API.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        client: OpenWeatherMapAPIWrapper,\n        places: Sequence[str],\n    ) -> None:\n        \"\"\"Initialize with parameters.\"\"\"\n        super().__init__()\n        self.client = client\n        self.places = places\n[docs]    @classmethod\n    def from_params(\n        cls, places: Sequence[str], *, openweathermap_api_key: Optional[str] = None\n    ) -> WeatherDataLoader:\n        client = OpenWeatherMapAPIWrapper(openweathermap_api_key=openweathermap_api_key)\n        return cls(client, places)\n[docs]    def lazy_load(\n        self,\n    ) -> Iterator[Document]:\n        \"\"\"Lazily load weather data for the given locations.\"\"\"\n        for place in self.places:\n            metadata = {\"queried_at\": datetime.now()}\n            content = self.client.run(place)\n            yield Document(page_content=content, metadata=metadata)\n[docs]    def load(\n        self,\n    ) -> List[Document]:\n        \"\"\"Load weather data for the given locations.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/weather.html"}
{"id": "1352c8d83cf7-0", "text": "Source code for langchain.document_loaders.powerpoint\nimport os\nfrom typing import List\nfrom langchain.document_loaders.unstructured import UnstructuredFileLoader\n[docs]class UnstructuredPowerPointLoader(UnstructuredFileLoader):\n    \"\"\"Load `Microsoft PowerPoint` files using `Unstructured`.\n    Works with both .ppt and .pptx files.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredPowerPointLoader\n    loader = UnstructuredPowerPointLoader(\n        \"example.pptx\", mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition-pptx\n    \"\"\"\n    def _get_elements(self) -> List:\n        from unstructured.__version__ import __version__ as __unstructured_version__\n        from unstructured.file_utils.filetype import FileType, detect_filetype\n        unstructured_version = tuple(\n            [int(x) for x in __unstructured_version__.split(\".\")]\n        )\n        # NOTE(MthwRobinson) - magic will raise an import error if the libmagic\n        # system dependency isn't installed. If it's not installed, we'll just\n        # check the file extension\n        try:\n            import magic  # noqa: F401", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html"}
{"id": "1352c8d83cf7-1", "text": "try:\n            import magic  # noqa: F401\n            is_ppt = detect_filetype(self.file_path) == FileType.PPT\n        except ImportError:\n            _, extension = os.path.splitext(str(self.file_path))\n            is_ppt = extension == \".ppt\"\n        if is_ppt and unstructured_version < (0, 4, 11):\n            raise ValueError(\n                f\"You are on unstructured version {__unstructured_version__}. \"\n                \"Partitioning .ppt files is only supported in unstructured>=0.4.11. \"\n                \"Please upgrade the unstructured package and try again.\"\n            )\n        if is_ppt:\n            from unstructured.partition.ppt import partition_ppt\n            return partition_ppt(filename=self.file_path, **self.unstructured_kwargs)\n        else:\n            from unstructured.partition.pptx import partition_pptx\n            return partition_pptx(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html"}
{"id": "dcdff638cd2f-0", "text": "Source code for langchain.document_loaders.diffbot\nimport logging\nfrom typing import Any, List\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n[docs]class DiffbotLoader(BaseLoader):\n    \"\"\"Load `Diffbot` json file.\"\"\"\n[docs]    def __init__(\n        self, api_token: str, urls: List[str], continue_on_failure: bool = True\n    ):\n        \"\"\"Initialize with API token, ids, and key.\n        Args:\n            api_token: Diffbot API token.\n            urls: List of URLs to load.\n            continue_on_failure: Whether to continue loading other URLs if one fails.\n               Defaults to True.\n        \"\"\"\n        self.api_token = api_token\n        self.urls = urls\n        self.continue_on_failure = continue_on_failure\n    def _diffbot_api_url(self, diffbot_api: str) -> str:\n        return f\"https://api.diffbot.com/v3/{diffbot_api}\"\n    def _get_diffbot_data(self, url: str) -> Any:\n        \"\"\"Get Diffbot file from Diffbot REST API.\"\"\"\n        # TODO: Add support for other Diffbot APIs\n        diffbot_url = self._diffbot_api_url(\"article\")\n        params = {\n            \"token\": self.api_token,\n            \"url\": url,\n        }\n        response = requests.get(diffbot_url, params=params, timeout=10)\n        # TODO: handle non-ok errors\n        return response.json() if response.ok else {}\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Extract text from Diffbot on all the URLs and return Documents\"\"\"\n        docs: List[Document] = list()\n        for url in self.urls:\n            try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/diffbot.html"}
{"id": "dcdff638cd2f-1", "text": "for url in self.urls:\n            try:\n                data = self._get_diffbot_data(url)\n                text = data[\"objects\"][0][\"text\"] if \"objects\" in data else \"\"\n                metadata = {\"source\": url}\n                docs.append(Document(page_content=text, metadata=metadata))\n            except Exception as e:\n                if self.continue_on_failure:\n                    logger.error(f\"Error fetching or processing {url}, exception: {e}\")\n                else:\n                    raise e\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/diffbot.html"}
{"id": "c77110fb1ca9-0", "text": "Source code for langchain.document_loaders.bibtex\nimport logging\nimport re\nfrom pathlib import Path\nfrom typing import Any, Iterator, List, Mapping, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utilities.bibtex import BibtexparserWrapper\nlogger = logging.getLogger(__name__)\n[docs]class BibtexLoader(BaseLoader):\n    \"\"\"Load a `bibtex` file.\n    Each document represents one entry from the bibtex file.\n    If a PDF file is present in the `file` bibtex field, the original PDF\n    is loaded into the document text. If no such file entry is present,\n    the `abstract` field is used instead.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        *,\n        parser: Optional[BibtexparserWrapper] = None,\n        max_docs: Optional[int] = None,\n        max_content_chars: Optional[int] = 4_000,\n        load_extra_metadata: bool = False,\n        file_pattern: str = r\"[^:]+\\.pdf\",\n    ):\n        \"\"\"Initialize the BibtexLoader.\n        Args:\n            file_path: Path to the bibtex file.\n            parser: The parser to use. If None, a default parser is used.\n            max_docs: Max number of associated documents to load. Use -1 means\n                           no limit.\n            max_content_chars: Maximum number of characters to load from the PDF.\n            load_extra_metadata: Whether to load extra metadata from the PDF.\n            file_pattern: Regex pattern to match the file name in the bibtex.\n        \"\"\"\n        self.file_path = file_path\n        self.parser = parser or BibtexparserWrapper()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html"}
{"id": "c77110fb1ca9-1", "text": "self.parser = parser or BibtexparserWrapper()\n        self.max_docs = max_docs\n        self.max_content_chars = max_content_chars\n        self.load_extra_metadata = load_extra_metadata\n        self.file_regex = re.compile(file_pattern)\n    def _load_entry(self, entry: Mapping[str, Any]) -> Optional[Document]:\n        import fitz\n        parent_dir = Path(self.file_path).parent\n        # regex is useful for Zotero flavor bibtex files\n        file_names = self.file_regex.findall(entry.get(\"file\", \"\"))\n        if not file_names:\n            return None\n        texts: List[str] = []\n        for file_name in file_names:\n            try:\n                with fitz.open(parent_dir / file_name) as f:\n                    texts.extend(page.get_text() for page in f)\n            except FileNotFoundError as e:\n                logger.debug(e)\n        content = \"\\n\".join(texts) or entry.get(\"abstract\", \"\")\n        if self.max_content_chars:\n            content = content[: self.max_content_chars]\n        metadata = self.parser.get_metadata(entry, load_extra=self.load_extra_metadata)\n        return Document(\n            page_content=content,\n            metadata=metadata,\n        )\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Load bibtex file using bibtexparser and get the article texts plus the\n        article metadata.\n        See https://bibtexparser.readthedocs.io/en/master/\n        Returns:\n            a list of documents with the document.page_content in text format\n        \"\"\"\n        try:\n            import fitz  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"PyMuPDF package not found, please install it with \"\n                \"`pip install pymupdf`\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html"}
{"id": "c77110fb1ca9-2", "text": "\"`pip install pymupdf`\"\n            )\n        entries = self.parser.load_bibtex_entries(self.file_path)\n        if self.max_docs:\n            entries = entries[: self.max_docs]\n        for entry in entries:\n            doc = self._load_entry(entry)\n            if doc:\n                yield doc\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load bibtex file documents from the given bibtex file path.\n        See https://bibtexparser.readthedocs.io/en/master/\n        Args:\n            file_path: the path to the bibtex file\n        Returns:\n            a list of documents with the document.page_content in text format\n        \"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html"}
{"id": "c915d77a46c1-0", "text": "Source code for langchain.document_loaders.duckdb_loader\nfrom typing import Dict, List, Optional, cast\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class DuckDBLoader(BaseLoader):\n    \"\"\"Load from `DuckDB`.\n    Each document represents one row of the result. The `page_content_columns`\n    are written into the `page_content` of the document. The `metadata_columns`\n    are written into the `metadata` of the document. By default, all columns\n    are written into the `page_content` and none into the `metadata`.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        query: str,\n        database: str = \":memory:\",\n        read_only: bool = False,\n        config: Optional[Dict[str, str]] = None,\n        page_content_columns: Optional[List[str]] = None,\n        metadata_columns: Optional[List[str]] = None,\n    ):\n        \"\"\"\n        Args:\n            query: The query to execute.\n            database: The database to connect to. Defaults to \":memory:\".\n            read_only: Whether to open the database in read-only mode.\n              Defaults to False.\n            config: A dictionary of configuration options to pass to the database.\n              Optional.\n            page_content_columns: The columns to write into the `page_content`\n              of the document. Optional.\n            metadata_columns: The columns to write into the `metadata` of the document.\n              Optional.\n        \"\"\"\n        self.query = query\n        self.database = database\n        self.read_only = read_only\n        self.config = config or {}\n        self.page_content_columns = page_content_columns\n        self.metadata_columns = metadata_columns\n[docs]    def load(self) -> List[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html"}
{"id": "c915d77a46c1-1", "text": "[docs]    def load(self) -> List[Document]:\n        try:\n            import duckdb\n        except ImportError:\n            raise ImportError(\n                \"Could not import duckdb python package. \"\n                \"Please install it with `pip install duckdb`.\"\n            )\n        docs = []\n        with duckdb.connect(\n            database=self.database, read_only=self.read_only, config=self.config\n        ) as con:\n            query_result = con.execute(self.query)\n            results = query_result.fetchall()\n            description = cast(list, query_result.description)\n            field_names = [c[0] for c in description]\n            if self.page_content_columns is None:\n                page_content_columns = field_names\n            else:\n                page_content_columns = self.page_content_columns\n            if self.metadata_columns is None:\n                metadata_columns = []\n            else:\n                metadata_columns = self.metadata_columns\n            for result in results:\n                page_content = \"\\n\".join(\n                    f\"{column}: {result[field_names.index(column)]}\"\n                    for column in page_content_columns\n                )\n                metadata = {\n                    column: result[field_names.index(column)]\n                    for column in metadata_columns\n                }\n                doc = Document(page_content=page_content, metadata=metadata)\n                docs.append(doc)\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html"}
{"id": "72135e104cd5-0", "text": "Source code for langchain.document_loaders.sharepoint\n\"\"\"Loader that loads data from Sharepoint Document Library\"\"\"\nfrom __future__ import annotations\nfrom typing import Iterator, List, Optional, Sequence\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base_o365 import (\n    O365BaseLoader,\n    _FileType,\n)\nfrom langchain.document_loaders.parsers.registry import get_parser\nfrom langchain.pydantic_v1 import Field\n[docs]class SharePointLoader(O365BaseLoader):\n    \"\"\"Load  from `SharePoint`.\"\"\"\n    document_library_id: str = Field(...)\n    \"\"\" The ID of the SharePoint document library to load data from.\"\"\"\n    folder_path: Optional[str] = None\n    \"\"\" The path to the folder to load data from.\"\"\"\n    object_ids: Optional[List[str]] = None\n    \"\"\" The IDs of the objects to load data from.\"\"\"\n    @property\n    def _file_types(self) -> Sequence[_FileType]:\n        \"\"\"Return supported file types.\"\"\"\n        return _FileType.DOC, _FileType.DOCX, _FileType.PDF\n    @property\n    def _scopes(self) -> List[str]:\n        \"\"\"Return required scopes.\"\"\"\n        return [\"sharepoint\", \"basic\"]\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Load documents lazily. Use this when working at a large scale.\"\"\"\n        try:\n            from O365.drive import Drive, Folder\n        except ImportError:\n            raise ImportError(\n                \"O365 package not found, please install it with `pip install o365`\"\n            )\n        drive = self._auth().storage().get_drive(self.document_library_id)\n        if not isinstance(drive, Drive):\n            raise ValueError(f\"There isn't a Drive with id {self.document_library_id}.\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sharepoint.html"}
{"id": "72135e104cd5-1", "text": "raise ValueError(f\"There isn't a Drive with id {self.document_library_id}.\")\n        blob_parser = get_parser(\"default\")\n        if self.folder_path:\n            target_folder = drive.get_item_by_path(self.folder_path)\n            if not isinstance(target_folder, Folder):\n                raise ValueError(f\"There isn't a folder with path {self.folder_path}.\")\n            for blob in self._load_from_folder(target_folder):\n                yield from blob_parser.lazy_parse(blob)\n        if self.object_ids:\n            for blob in self._load_from_object_ids(drive, self.object_ids):\n                yield from blob_parser.lazy_parse(blob)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load all documents.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sharepoint.html"}
{"id": "fd27d02d40de-0", "text": "Source code for langchain.document_loaders.airbyte\nfrom typing import Any, Callable, Iterator, List, Mapping, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utils.utils import guard_import\nRecordHandler = Callable[[Any, Optional[str]], Document]\n[docs]class AirbyteCDKLoader(BaseLoader):\n    \"\"\"Load with an `Airbyte` source connector implemented using the `CDK`.\"\"\"\n[docs]    def __init__(\n        self,\n        config: Mapping[str, Any],\n        source_class: Any,\n        stream_name: str,\n        record_handler: Optional[RecordHandler] = None,\n        state: Optional[Any] = None,\n    ) -> None:\n        \"\"\"Initializes the loader.\n        Args:\n            config: The config to pass to the source connector.\n            source_class: The source connector class.\n            stream_name: The name of the stream to load.\n            record_handler: A function that takes in a record and an optional id and\n                returns a Document. If None, the record will be used as the document.\n                Defaults to None.\n            state: The state to pass to the source connector. Defaults to None.\n        \"\"\"\n        from airbyte_cdk.models.airbyte_protocol import AirbyteRecordMessage\n        from airbyte_cdk.sources.embedded.base_integration import (\n            BaseEmbeddedIntegration,\n        )\n        from airbyte_cdk.sources.embedded.runner import CDKRunner\n        class CDKIntegration(BaseEmbeddedIntegration):\n            \"\"\"A wrapper around the CDK integration.\"\"\"\n            def _handle_record(\n                self, record: AirbyteRecordMessage, id: Optional[str]\n            ) -> Document:\n                if record_handler:\n                    return record_handler(record, id)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html"}
{"id": "fd27d02d40de-1", "text": "if record_handler:\n                    return record_handler(record, id)\n                return Document(page_content=\"\", metadata=record.data)\n        self._integration = CDKIntegration(\n            config=config,\n            runner=CDKRunner(source=source_class(), name=source_class.__name__),\n        )\n        self._stream_name = stream_name\n        self._state = state\n[docs]    def load(self) -> List[Document]:\n        return list(self.lazy_load())\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        return self._integration._load_data(\n            stream_name=self._stream_name, state=self._state\n        )\n    @property\n    def last_state(self) -> Any:\n        return self._integration.last_state\n[docs]class AirbyteHubspotLoader(AirbyteCDKLoader):\n    \"\"\"Load from `Hubspot` using an `Airbyte` source connector.\"\"\"\n[docs]    def __init__(\n        self,\n        config: Mapping[str, Any],\n        stream_name: str,\n        record_handler: Optional[RecordHandler] = None,\n        state: Optional[Any] = None,\n    ) -> None:\n        \"\"\"Initializes the loader.\n        Args:\n            config: The config to pass to the source connector.\n            stream_name: The name of the stream to load.\n            record_handler: A function that takes in a record and an optional id and\n                returns a Document. If None, the record will be used as the document.\n                Defaults to None.\n            state: The state to pass to the source connector. Defaults to None.\n        \"\"\"\n        source_class = guard_import(\n            \"source_hubspot\", pip_name=\"airbyte-source-hubspot\"\n        ).SourceHubspot\n        super().__init__(\n            config=config,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html"}
{"id": "fd27d02d40de-2", "text": ").SourceHubspot\n        super().__init__(\n            config=config,\n            source_class=source_class,\n            stream_name=stream_name,\n            record_handler=record_handler,\n            state=state,\n        )\n[docs]class AirbyteStripeLoader(AirbyteCDKLoader):\n    \"\"\"Load from `Stripe` using an `Airbyte` source connector.\"\"\"\n[docs]    def __init__(\n        self,\n        config: Mapping[str, Any],\n        stream_name: str,\n        record_handler: Optional[RecordHandler] = None,\n        state: Optional[Any] = None,\n    ) -> None:\n        \"\"\"Initializes the loader.\n        Args:\n            config: The config to pass to the source connector.\n            stream_name: The name of the stream to load.\n            record_handler: A function that takes in a record and an optional id and\n                returns a Document. If None, the record will be used as the document.\n                Defaults to None.\n            state: The state to pass to the source connector. Defaults to None.\n        \"\"\"\n        source_class = guard_import(\n            \"source_stripe\", pip_name=\"airbyte-source-stripe\"\n        ).SourceStripe\n        super().__init__(\n            config=config,\n            source_class=source_class,\n            stream_name=stream_name,\n            record_handler=record_handler,\n            state=state,\n        )\n[docs]class AirbyteTypeformLoader(AirbyteCDKLoader):\n    \"\"\"Load from `Typeform` using an `Airbyte` source connector.\"\"\"\n[docs]    def __init__(\n        self,\n        config: Mapping[str, Any],\n        stream_name: str,\n        record_handler: Optional[RecordHandler] = None,\n        state: Optional[Any] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html"}
{"id": "fd27d02d40de-3", "text": "state: Optional[Any] = None,\n    ) -> None:\n        \"\"\"Initializes the loader.\n        Args:\n            config: The config to pass to the source connector.\n            stream_name: The name of the stream to load.\n            record_handler: A function that takes in a record and an optional id and\n                returns a Document. If None, the record will be used as the document.\n                Defaults to None.\n            state: The state to pass to the source connector. Defaults to None.\n        \"\"\"\n        source_class = guard_import(\n            \"source_typeform\", pip_name=\"airbyte-source-typeform\"\n        ).SourceTypeform\n        super().__init__(\n            config=config,\n            source_class=source_class,\n            stream_name=stream_name,\n            record_handler=record_handler,\n            state=state,\n        )\n[docs]class AirbyteZendeskSupportLoader(AirbyteCDKLoader):\n    \"\"\"Load from `Zendesk Support` using an `Airbyte` source connector.\"\"\"\n[docs]    def __init__(\n        self,\n        config: Mapping[str, Any],\n        stream_name: str,\n        record_handler: Optional[RecordHandler] = None,\n        state: Optional[Any] = None,\n    ) -> None:\n        \"\"\"Initializes the loader.\n        Args:\n            config: The config to pass to the source connector.\n            stream_name: The name of the stream to load.\n            record_handler: A function that takes in a record and an optional id and\n                returns a Document. If None, the record will be used as the document.\n                Defaults to None.\n            state: The state to pass to the source connector. Defaults to None.\n        \"\"\"\n        source_class = guard_import(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html"}
{"id": "fd27d02d40de-4", "text": "\"\"\"\n        source_class = guard_import(\n            \"source_zendesk_support\", pip_name=\"airbyte-source-zendesk-support\"\n        ).SourceZendeskSupport\n        super().__init__(\n            config=config,\n            source_class=source_class,\n            stream_name=stream_name,\n            record_handler=record_handler,\n            state=state,\n        )\n[docs]class AirbyteShopifyLoader(AirbyteCDKLoader):\n    \"\"\"Load from `Shopify` using an `Airbyte` source connector.\"\"\"\n[docs]    def __init__(\n        self,\n        config: Mapping[str, Any],\n        stream_name: str,\n        record_handler: Optional[RecordHandler] = None,\n        state: Optional[Any] = None,\n    ) -> None:\n        \"\"\"Initializes the loader.\n        Args:\n            config: The config to pass to the source connector.\n            stream_name: The name of the stream to load.\n            record_handler: A function that takes in a record and an optional id and\n                returns a Document. If None, the record will be used as the document.\n                Defaults to None.\n            state: The state to pass to the source connector. Defaults to None.\n        \"\"\"\n        source_class = guard_import(\n            \"source_shopify\", pip_name=\"airbyte-source-shopify\"\n        ).SourceShopify\n        super().__init__(\n            config=config,\n            source_class=source_class,\n            stream_name=stream_name,\n            record_handler=record_handler,\n            state=state,\n        )\n[docs]class AirbyteSalesforceLoader(AirbyteCDKLoader):\n    \"\"\"Load from `Salesforce` using an `Airbyte` source connector.\"\"\"\n[docs]    def __init__(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html"}
{"id": "fd27d02d40de-5", "text": "[docs]    def __init__(\n        self,\n        config: Mapping[str, Any],\n        stream_name: str,\n        record_handler: Optional[RecordHandler] = None,\n        state: Optional[Any] = None,\n    ) -> None:\n        \"\"\"Initializes the loader.\n        Args:\n            config: The config to pass to the source connector.\n            stream_name: The name of the stream to load.\n            record_handler: A function that takes in a record and an optional id and\n                returns a Document. If None, the record will be used as the document.\n                Defaults to None.\n            state: The state to pass to the source connector. Defaults to None.\n        \"\"\"\n        source_class = guard_import(\n            \"source_salesforce\", pip_name=\"airbyte-source-salesforce\"\n        ).SourceSalesforce\n        super().__init__(\n            config=config,\n            source_class=source_class,\n            stream_name=stream_name,\n            record_handler=record_handler,\n            state=state,\n        )\n[docs]class AirbyteGongLoader(AirbyteCDKLoader):\n    \"\"\"Load from `Gong` using an `Airbyte` source connector.\"\"\"\n[docs]    def __init__(\n        self,\n        config: Mapping[str, Any],\n        stream_name: str,\n        record_handler: Optional[RecordHandler] = None,\n        state: Optional[Any] = None,\n    ) -> None:\n        \"\"\"Initializes the loader.\n        Args:\n            config: The config to pass to the source connector.\n            stream_name: The name of the stream to load.\n            record_handler: A function that takes in a record and an optional id and\n                returns a Document. If None, the record will be used as the document.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html"}
{"id": "fd27d02d40de-6", "text": "returns a Document. If None, the record will be used as the document.\n                Defaults to None.\n            state: The state to pass to the source connector. Defaults to None.\n        \"\"\"\n        source_class = guard_import(\n            \"source_gong\", pip_name=\"airbyte-source-gong\"\n        ).SourceGong\n        super().__init__(\n            config=config,\n            source_class=source_class,\n            stream_name=stream_name,\n            record_handler=record_handler,\n            state=state,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html"}
{"id": "300a65591966-0", "text": "Source code for langchain.document_loaders.tomarkdown\nfrom __future__ import annotations\nfrom typing import Iterator, List\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class ToMarkdownLoader(BaseLoader):\n    \"\"\"Load `HTML` using `2markdown API`.\"\"\"\n[docs]    def __init__(self, url: str, api_key: str):\n        \"\"\"Initialize with url and api key.\"\"\"\n        self.url = url\n        self.api_key = api_key\n[docs]    def lazy_load(\n        self,\n    ) -> Iterator[Document]:\n        \"\"\"Lazily load the file.\"\"\"\n        response = requests.post(\n            \"https://2markdown.com/api/2md\",\n            headers={\"X-Api-Key\": self.api_key},\n            json={\"url\": self.url},\n        )\n        text = response.json()[\"article\"]\n        metadata = {\"source\": self.url}\n        yield Document(page_content=text, metadata=metadata)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load file.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tomarkdown.html"}
{"id": "2c49e40e7938-0", "text": "Source code for langchain.document_loaders.blockchain\nimport os\nimport re\nimport time\nfrom enum import Enum\nfrom typing import List, Optional\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class BlockchainType(Enum):\n    \"\"\"Enumerator of the supported blockchains.\"\"\"\n    ETH_MAINNET = \"eth-mainnet\"\n    ETH_GOERLI = \"eth-goerli\"\n    POLYGON_MAINNET = \"polygon-mainnet\"\n    POLYGON_MUMBAI = \"polygon-mumbai\"\n[docs]class BlockchainDocumentLoader(BaseLoader):\n    \"\"\"Load elements from a blockchain smart contract.\n    The supported blockchains are: Ethereum mainnet, Ethereum Goerli testnet,\n    Polygon mainnet, and Polygon Mumbai testnet.\n    If no BlockchainType is specified, the default is Ethereum mainnet.\n    The Loader uses the Alchemy API to interact with the blockchain.\n    ALCHEMY_API_KEY environment variable must be set to use this loader.\n    The API returns 100 NFTs per request and can be paginated using the\n    startToken parameter.\n    If get_all_tokens is set to True, the loader will get all tokens\n    on the contract.  Note that for contracts with a large number of tokens,\n    this may take a long time (e.g. 10k tokens is 100 requests).\n    Default value is false for this reason.\n    The max_execution_time (sec) can be set to limit the execution time\n    of the loader.\n    Future versions of this loader can:\n        - Support additional Alchemy APIs (e.g. getTransactions, etc.)\n        - Support additional blockain APIs (e.g. Infura, Opensea, etc.)\n    \"\"\"\n[docs]    def __init__(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html"}
{"id": "2c49e40e7938-1", "text": "\"\"\"\n[docs]    def __init__(\n        self,\n        contract_address: str,\n        blockchainType: BlockchainType = BlockchainType.ETH_MAINNET,\n        api_key: str = \"docs-demo\",\n        startToken: str = \"\",\n        get_all_tokens: bool = False,\n        max_execution_time: Optional[int] = None,\n    ):\n        \"\"\"\n        Args:\n            contract_address: The address of the smart contract.\n            blockchainType: The blockchain type.\n            api_key: The Alchemy API key.\n            startToken: The start token for pagination.\n            get_all_tokens: Whether to get all tokens on the contract.\n            max_execution_time: The maximum execution time (sec).\n        \"\"\"\n        self.contract_address = contract_address\n        self.blockchainType = blockchainType.value\n        self.api_key = os.environ.get(\"ALCHEMY_API_KEY\") or api_key\n        self.startToken = startToken\n        self.get_all_tokens = get_all_tokens\n        self.max_execution_time = max_execution_time\n        if not self.api_key:\n            raise ValueError(\"Alchemy API key not provided.\")\n        if not re.match(r\"^0x[a-fA-F0-9]{40}$\", self.contract_address):\n            raise ValueError(f\"Invalid contract address {self.contract_address}\")\n[docs]    def load(self) -> List[Document]:\n        result = []\n        current_start_token = self.startToken\n        start_time = time.time()\n        while True:\n            url = (\n                f\"https://{self.blockchainType}.g.alchemy.com/nft/v2/\"\n                f\"{self.api_key}/getNFTsForCollection?withMetadata=\"\n                f\"True&contractAddress={self.contract_address}\"\n                f\"&startToken={current_start_token}\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html"}
{"id": "2c49e40e7938-2", "text": "f\"&startToken={current_start_token}\"\n            )\n            response = requests.get(url)\n            if response.status_code != 200:\n                raise ValueError(\n                    f\"Request failed with status code {response.status_code}\"\n                )\n            items = response.json()[\"nfts\"]\n            if not items:\n                break\n            for item in items:\n                content = str(item)\n                tokenId = item[\"id\"][\"tokenId\"]\n                metadata = {\n                    \"source\": self.contract_address,\n                    \"blockchain\": self.blockchainType,\n                    \"tokenId\": tokenId,\n                }\n                result.append(Document(page_content=content, metadata=metadata))\n            # exit after the first API call if get_all_tokens is False\n            if not self.get_all_tokens:\n                break\n            # get the start token for the next API call from the last item in array\n            current_start_token = self._get_next_tokenId(result[-1].metadata[\"tokenId\"])\n            if (\n                self.max_execution_time is not None\n                and (time.time() - start_time) > self.max_execution_time\n            ):\n                raise RuntimeError(\"Execution time exceeded the allowed time limit.\")\n        if not result:\n            raise ValueError(\n                f\"No NFTs found for contract address {self.contract_address}\"\n            )\n        return result\n    # add one to the tokenId, ensuring the correct tokenId format is used\n    def _get_next_tokenId(self, tokenId: str) -> str:\n        value_type = self._detect_value_type(tokenId)\n        if value_type == \"hex_0x\":\n            value_int = int(tokenId, 16)\n        elif value_type == \"hex_0xbf\":\n            value_int = int(tokenId[2:], 16)\n        else:\n            value_int = int(tokenId)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html"}
{"id": "2c49e40e7938-3", "text": "else:\n            value_int = int(tokenId)\n        result = value_int + 1\n        if value_type == \"hex_0x\":\n            return \"0x\" + format(result, \"0\" + str(len(tokenId) - 2) + \"x\")\n        elif value_type == \"hex_0xbf\":\n            return \"0xbf\" + format(result, \"0\" + str(len(tokenId) - 4) + \"x\")\n        else:\n            return str(result)\n    # A smart contract can use different formats for the tokenId\n    @staticmethod\n    def _detect_value_type(tokenId: str) -> str:\n        if isinstance(tokenId, int):\n            return \"int\"\n        elif tokenId.startswith(\"0x\"):\n            return \"hex_0x\"\n        elif tokenId.startswith(\"0xbf\"):\n            return \"hex_0xbf\"\n        else:\n            return \"hex_0xbf\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html"}
{"id": "93305f02f1c4-0", "text": "Source code for langchain.document_loaders.cube_semantic\nimport json\nimport logging\nimport time\nfrom typing import List\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n[docs]class CubeSemanticLoader(BaseLoader):\n    \"\"\"Load `Cube semantic layer` metadata.\n    Args:\n        cube_api_url: REST API endpoint.\n            Use the REST API of your Cube's deployment.\n            Please find out more information here:\n            https://cube.dev/docs/http-api/rest#configuration-base-path\n        cube_api_token: Cube API token.\n            Authentication tokens are generated based on your Cube's API secret.\n            Please find out more information here:\n            https://cube.dev/docs/security#generating-json-web-tokens-jwt\n        load_dimension_values: Whether to load dimension values for every string\n            dimension or not.\n        dimension_values_limit: Maximum number of dimension values to load.\n        dimension_values_max_retries: Maximum number of retries to load dimension\n            values.\n        dimension_values_retry_delay: Delay between retries to load dimension values.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        cube_api_url: str,\n        cube_api_token: str,\n        load_dimension_values: bool = True,\n        dimension_values_limit: int = 10_000,\n        dimension_values_max_retries: int = 10,\n        dimension_values_retry_delay: int = 3,\n    ):\n        self.cube_api_url = cube_api_url\n        self.cube_api_token = cube_api_token\n        self.load_dimension_values = load_dimension_values\n        self.dimension_values_limit = dimension_values_limit\n        self.dimension_values_max_retries = dimension_values_max_retries\n        self.dimension_values_retry_delay = dimension_values_retry_delay", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/cube_semantic.html"}
{"id": "93305f02f1c4-1", "text": "self.dimension_values_retry_delay = dimension_values_retry_delay\n    def _get_dimension_values(self, dimension_name: str) -> List[str]:\n        \"\"\"Makes a call to Cube's REST API load endpoint to retrieve\n        values for dimensions.\n        These values can be used to achieve a more accurate filtering.\n        \"\"\"\n        logger.info(\"Loading dimension values for: {dimension_name}...\")\n        headers = {\n            \"Content-Type\": \"application/json\",\n            \"Authorization\": self.cube_api_token,\n        }\n        query = {\n            \"query\": {\n                \"dimensions\": [dimension_name],\n                \"limit\": self.dimension_values_limit,\n            }\n        }\n        retries = 0\n        while retries < self.dimension_values_max_retries:\n            response = requests.request(\n                \"POST\",\n                f\"{self.cube_api_url}/load\",\n                headers=headers,\n                data=json.dumps(query),\n            )\n            if response.status_code == 200:\n                response_data = response.json()\n                if (\n                    \"error\" in response_data\n                    and response_data[\"error\"] == \"Continue wait\"\n                ):\n                    logger.info(\"Retrying...\")\n                    retries += 1\n                    time.sleep(self.dimension_values_retry_delay)\n                    continue\n                else:\n                    dimension_values = [\n                        item[dimension_name] for item in response_data[\"data\"]\n                    ]\n                    return dimension_values\n            else:\n                logger.error(\"Request failed with status code:\", response.status_code)\n                break\n        if retries == self.dimension_values_max_retries:\n            logger.info(\"Maximum retries reached.\")\n        return []\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Makes a call to Cube's REST API metadata endpoint.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/cube_semantic.html"}
{"id": "93305f02f1c4-2", "text": "\"\"\"Makes a call to Cube's REST API metadata endpoint.\n        Returns:\n            A list of documents with attributes:\n                - page_content=column_title + column_description\n                - metadata\n                    - table_name\n                    - column_name\n                    - column_data_type\n                    - column_member_type\n                    - column_title\n                    - column_description\n                    - column_values\n                    - cube_data_obj_type\n        \"\"\"\n        headers = {\n            \"Content-Type\": \"application/json\",\n            \"Authorization\": self.cube_api_token,\n        }\n        logger.info(f\"Loading metadata from {self.cube_api_url}...\")\n        response = requests.get(f\"{self.cube_api_url}/meta\", headers=headers)\n        response.raise_for_status()\n        raw_meta_json = response.json()\n        cube_data_objects = raw_meta_json.get(\"cubes\", [])\n        logger.info(f\"Found {len(cube_data_objects)} cube data objects in metadata.\")\n        if not cube_data_objects:\n            raise ValueError(\"No cubes found in metadata.\")\n        docs = []\n        for cube_data_obj in cube_data_objects:\n            cube_data_obj_name = cube_data_obj.get(\"name\")\n            cube_data_obj_type = cube_data_obj.get(\"type\")\n            cube_data_obj_is_public = cube_data_obj.get(\"public\")\n            measures = cube_data_obj.get(\"measures\", [])\n            dimensions = cube_data_obj.get(\"dimensions\", [])\n            logger.info(f\"Processing {cube_data_obj_name}...\")\n            if not cube_data_obj_is_public:\n                logger.info(f\"Skipping {cube_data_obj_name} because it is not public.\")\n                continue\n            for item in measures + dimensions:\n                column_member_type = \"measure\" if item in measures else \"dimension\"\n                dimension_values = []\n                item_name = str(item.get(\"name\"))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/cube_semantic.html"}
{"id": "93305f02f1c4-3", "text": "dimension_values = []\n                item_name = str(item.get(\"name\"))\n                item_type = str(item.get(\"type\"))\n                if (\n                    self.load_dimension_values\n                    and column_member_type == \"dimension\"\n                    and item_type == \"string\"\n                ):\n                    dimension_values = self._get_dimension_values(item_name)\n                metadata = dict(\n                    table_name=str(cube_data_obj_name),\n                    column_name=item_name,\n                    column_data_type=item_type,\n                    column_title=str(item.get(\"title\")),\n                    column_description=str(item.get(\"description\")),\n                    column_member_type=column_member_type,\n                    column_values=dimension_values,\n                    cube_data_obj_type=cube_data_obj_type,\n                )\n                page_content = f\"{str(item.get('title'))}, \"\n                page_content += f\"{str(item.get('description'))}\"\n                docs.append(Document(page_content=page_content, metadata=metadata))\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/cube_semantic.html"}
{"id": "a6ea3d39fb4c-0", "text": "Source code for langchain.document_loaders.helpers\n\"\"\"Document loader helpers.\"\"\"\nimport concurrent.futures\nfrom typing import List, NamedTuple, Optional, cast\n[docs]class FileEncoding(NamedTuple):\n    \"\"\"File encoding as the NamedTuple.\"\"\"\n    encoding: Optional[str]\n    \"\"\"The encoding of the file.\"\"\"\n    confidence: float\n    \"\"\"The confidence of the encoding.\"\"\"\n    language: Optional[str]\n    \"\"\"The language of the file.\"\"\"\n[docs]def detect_file_encodings(file_path: str, timeout: int = 5) -> List[FileEncoding]:\n    \"\"\"Try to detect the file encoding.\n    Returns a list of `FileEncoding` tuples with the detected encodings ordered\n    by confidence.\n    Args:\n        file_path: The path to the file to detect the encoding for.\n        timeout: The timeout in seconds for the encoding detection.\n    \"\"\"\n    import chardet\n    def read_and_detect(file_path: str) -> List[dict]:\n        with open(file_path, \"rb\") as f:\n            rawdata = f.read()\n        return cast(List[dict], chardet.detect_all(rawdata))\n    with concurrent.futures.ThreadPoolExecutor() as executor:\n        future = executor.submit(read_and_detect, file_path)\n        try:\n            encodings = future.result(timeout=timeout)\n        except concurrent.futures.TimeoutError:\n            raise TimeoutError(\n                f\"Timeout reached while detecting encoding for {file_path}\"\n            )\n    if all(encoding[\"encoding\"] is None for encoding in encodings):\n        raise RuntimeError(f\"Could not detect encoding for {file_path}\")\n    return [FileEncoding(**enc) for enc in encodings if enc[\"encoding\"] is not None]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/helpers.html"}
{"id": "8b07365564b5-0", "text": "Source code for langchain.document_loaders.fauna\nfrom typing import Iterator, List, Optional, Sequence\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class FaunaLoader(BaseLoader):\n    \"\"\"Load from `FaunaDB`.\n    Attributes:\n        query (str): The FQL query string to execute.\n        page_content_field (str): The field that contains the content of each page.\n        secret (str): The secret key for authenticating to FaunaDB.\n        metadata_fields (Optional[Sequence[str]]):\n            Optional list of field names to include in metadata.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        query: str,\n        page_content_field: str,\n        secret: str,\n        metadata_fields: Optional[Sequence[str]] = None,\n    ):\n        self.query = query\n        self.page_content_field = page_content_field\n        self.secret = secret\n        self.metadata_fields = metadata_fields\n[docs]    def load(self) -> List[Document]:\n        return list(self.lazy_load())\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        try:\n            from fauna import Page, fql\n            from fauna.client import Client\n            from fauna.encoding import QuerySuccess\n        except ImportError:\n            raise ImportError(\n                \"Could not import fauna python package. \"\n                \"Please install it with `pip install fauna`.\"\n            )\n        # Create Fauna Client\n        client = Client(secret=self.secret)\n        # Run FQL Query\n        response: QuerySuccess = client.query(fql(self.query))\n        page: Page = response.data\n        for result in page:\n            if result is not None:\n                document_dict = dict(result.items())\n                page_content = \"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/fauna.html"}
{"id": "8b07365564b5-1", "text": "document_dict = dict(result.items())\n                page_content = \"\"\n                for key, value in document_dict.items():\n                    if key == self.page_content_field:\n                        page_content = value\n                document: Document = Document(\n                    page_content=page_content,\n                    metadata={\"id\": result.id, \"ts\": result.ts},\n                )\n                yield document\n        if page.after is not None:\n            yield Document(\n                page_content=\"Next Page Exists\",\n                metadata={\"after\": page.after},\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/fauna.html"}
{"id": "88da779658e5-0", "text": "Source code for langchain.document_loaders.evernote\n\"\"\"Load documents from Evernote.\nhttps://gist.github.com/foxmask/7b29c43a161e001ff04afdb2f181e31c\n\"\"\"\nimport hashlib\nimport logging\nfrom base64 import b64decode\nfrom time import strptime\nfrom typing import Any, Dict, Iterator, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n[docs]class EverNoteLoader(BaseLoader):\n    \"\"\"Load from `EverNote`.\n    Loads an EverNote notebook export file e.g. my_notebook.enex into Documents.\n    Instructions on producing this file can be found at\n    https://help.evernote.com/hc/en-us/articles/209005557-Export-notes-and-notebooks-as-ENEX-or-HTML\n    Currently only the plain text in the note is extracted and stored as the contents\n    of the Document, any non content metadata (e.g. 'author', 'created', 'updated' etc.\n    but not 'content-raw' or 'resource') tags on the note will be extracted and stored\n    as metadata on the Document.\n    Args:\n        file_path (str): The path to the notebook export with a .enex extension\n        load_single_document (bool): Whether or not to concatenate the content of all\n            notes into a single long Document.\n        If this is set to True (default) then the only metadata on the document will be\n            the 'source' which contains the file name of the export.\n    \"\"\"  # noqa: E501\n[docs]    def __init__(self, file_path: str, load_single_document: bool = True):\n        \"\"\"Initialize with file path.\"\"\"\n        self.file_path = file_path", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html"}
{"id": "88da779658e5-1", "text": "\"\"\"Initialize with file path.\"\"\"\n        self.file_path = file_path\n        self.load_single_document = load_single_document\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents from EverNote export file.\"\"\"\n        documents = [\n            Document(\n                page_content=note[\"content\"],\n                metadata={\n                    **{\n                        key: value\n                        for key, value in note.items()\n                        if key not in [\"content\", \"content-raw\", \"resource\"]\n                    },\n                    **{\"source\": self.file_path},\n                },\n            )\n            for note in self._parse_note_xml(self.file_path)\n            if note.get(\"content\") is not None\n        ]\n        if not self.load_single_document:\n            return documents\n        return [\n            Document(\n                page_content=\"\".join([document.page_content for document in documents]),\n                metadata={\"source\": self.file_path},\n            )\n        ]\n    @staticmethod\n    def _parse_content(content: str) -> str:\n        try:\n            import html2text\n            return html2text.html2text(content).strip()\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import `html2text`. Although it is not a required package \"\n                \"to use Langchain, using the EverNote loader requires `html2text`. \"\n                \"Please install `html2text` via `pip install html2text` and try again.\"\n            ) from e\n    @staticmethod\n    def _parse_resource(resource: list) -> dict:\n        rsc_dict: Dict[str, Any] = {}\n        for elem in resource:\n            if elem.tag == \"data\":\n                # Sometimes elem.text is None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html"}
{"id": "88da779658e5-2", "text": "if elem.tag == \"data\":\n                # Sometimes elem.text is None\n                rsc_dict[elem.tag] = b64decode(elem.text) if elem.text else b\"\"\n                rsc_dict[\"hash\"] = hashlib.md5(rsc_dict[elem.tag]).hexdigest()\n            else:\n                rsc_dict[elem.tag] = elem.text\n        return rsc_dict\n    @staticmethod\n    def _parse_note(note: List, prefix: Optional[str] = None) -> dict:\n        note_dict: Dict[str, Any] = {}\n        resources = []\n        def add_prefix(element_tag: str) -> str:\n            if prefix is None:\n                return element_tag\n            return f\"{prefix}.{element_tag}\"\n        for elem in note:\n            if elem.tag == \"content\":\n                note_dict[elem.tag] = EverNoteLoader._parse_content(elem.text)\n                # A copy of original content\n                note_dict[\"content-raw\"] = elem.text\n            elif elem.tag == \"resource\":\n                resources.append(EverNoteLoader._parse_resource(elem))\n            elif elem.tag == \"created\" or elem.tag == \"updated\":\n                note_dict[elem.tag] = strptime(elem.text, \"%Y%m%dT%H%M%SZ\")\n            elif elem.tag == \"note-attributes\":\n                additional_attributes = EverNoteLoader._parse_note(\n                    elem, elem.tag\n                )  # Recursively enter the note-attributes tag\n                note_dict.update(additional_attributes)\n            else:\n                note_dict[elem.tag] = elem.text\n        if len(resources) > 0:\n            note_dict[\"resource\"] = resources\n        return {add_prefix(key): value for key, value in note_dict.items()}\n    @staticmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html"}
{"id": "88da779658e5-3", "text": "@staticmethod\n    def _parse_note_xml(xml_file: str) -> Iterator[Dict[str, Any]]:\n        \"\"\"Parse Evernote xml.\"\"\"\n        # Without huge_tree set to True, parser may complain about huge text node\n        # Try to recover, because there may be \"&nbsp;\", which will cause\n        # \"XMLSyntaxError: Entity 'nbsp' not defined\"\n        try:\n            from lxml import etree\n        except ImportError as e:\n            logger.error(\n                \"Could not import `lxml`. Although it is not a required package to use \"\n                \"Langchain, using the EverNote loader requires `lxml`. Please install \"\n                \"`lxml` via `pip install lxml` and try again.\"\n            )\n            raise e\n        context = etree.iterparse(\n            xml_file, encoding=\"utf-8\", strip_cdata=False, huge_tree=True, recover=True\n        )\n        for action, elem in context:\n            if elem.tag == \"note\":\n                yield EverNoteLoader._parse_note(elem)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html"}
{"id": "15fe36f305fa-0", "text": "Source code for langchain.document_loaders.discord\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nif TYPE_CHECKING:\n    import pandas as pd\n[docs]class DiscordChatLoader(BaseLoader):\n    \"\"\"Load `Discord` chat logs.\"\"\"\n[docs]    def __init__(self, chat_log: pd.DataFrame, user_id_col: str = \"ID\"):\n        \"\"\"Initialize with a Pandas DataFrame containing chat logs.\n        Args:\n            chat_log: Pandas DataFrame containing chat logs.\n            user_id_col: Name of the column containing the user ID. Defaults to \"ID\".\n        \"\"\"\n        if not isinstance(chat_log, pd.DataFrame):\n            raise ValueError(\n                f\"Expected chat_log to be a pd.DataFrame, got {type(chat_log)}\"\n            )\n        self.chat_log = chat_log\n        self.user_id_col = user_id_col\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load all chat messages.\"\"\"\n        result = []\n        for _, row in self.chat_log.iterrows():\n            user_id = row[self.user_id_col]\n            metadata = row.to_dict()\n            metadata.pop(self.user_id_col)\n            result.append(Document(page_content=user_id, metadata=metadata))\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/discord.html"}
{"id": "2a7eb74f17ec-0", "text": "Source code for langchain.document_loaders.open_city_data\nfrom typing import Iterator, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class OpenCityDataLoader(BaseLoader):\n    \"\"\"Load from `Open City`.\"\"\"\n[docs]    def __init__(self, city_id: str, dataset_id: str, limit: int):\n        \"\"\"Initialize with dataset_id.\n        Example: https://dev.socrata.com/foundry/data.sfgov.org/vw6y-z8j6\n        e.g., city_id = data.sfgov.org\n        e.g., dataset_id = vw6y-z8j6\n        Args:\n            city_id: The Open City city identifier.\n            dataset_id: The Open City dataset identifier.\n            limit: The maximum number of documents to load.\n        \"\"\"\n        self.city_id = city_id\n        self.dataset_id = dataset_id\n        self.limit = limit\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazy load records.\"\"\"\n        from sodapy import Socrata\n        client = Socrata(self.city_id, None)\n        results = client.get(self.dataset_id, limit=self.limit)\n        for record in results:\n            yield Document(\n                page_content=str(record),\n                metadata={\n                    \"source\": self.city_id + \"_\" + self.dataset_id,\n                },\n            )\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load records.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/open_city_data.html"}
{"id": "9a481241dfc3-0", "text": "Source code for langchain.document_loaders.airbyte_json\nimport json\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utils import stringify_dict\n[docs]class AirbyteJSONLoader(BaseLoader):\n    \"\"\"Load local `Airbyte` json files.\"\"\"\n[docs]    def __init__(self, file_path: str):\n        \"\"\"Initialize with a file path. This should start with '/tmp/airbyte_local/'.\"\"\"\n        self.file_path = file_path\n        \"\"\"Path to the directory containing the json files.\"\"\"\n[docs]    def load(self) -> List[Document]:\n        text = \"\"\n        for line in open(self.file_path, \"r\"):\n            data = json.loads(line)[\"_airbyte_data\"]\n            text += stringify_dict(data)\n        metadata = {\"source\": self.file_path}\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte_json.html"}
{"id": "570e12937aee-0", "text": "Source code for langchain.document_loaders.url\n\"\"\"Loader that uses unstructured to load HTML files.\"\"\"\nimport logging\nfrom typing import Any, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n[docs]class UnstructuredURLLoader(BaseLoader):\n    \"\"\"Load files from remote URLs using `Unstructured`.\n    Use the unstructured partition function to detect the MIME type\n    and route the file to the appropriate partitioner.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredURLLoader\n    loader = UnstructuredURLLoader(\n        urls=[\"<url-1>\", \"<url-2>\"], mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition\n    \"\"\"\n[docs]    def __init__(\n        self,\n        urls: List[str],\n        continue_on_failure: bool = True,\n        mode: str = \"single\",\n        show_progress_bar: bool = False,\n        **unstructured_kwargs: Any,\n    ):\n        \"\"\"Initialize with file path.\"\"\"\n        try:\n            import unstructured  # noqa:F401\n            from unstructured.__version__ import __version__ as __unstructured_version__", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html"}
{"id": "570e12937aee-1", "text": "from unstructured.__version__ import __version__ as __unstructured_version__\n            self.__version = __unstructured_version__\n        except ImportError:\n            raise ImportError(\n                \"unstructured package not found, please install it with \"\n                \"`pip install unstructured`\"\n            )\n        self._validate_mode(mode)\n        self.mode = mode\n        headers = unstructured_kwargs.pop(\"headers\", {})\n        if len(headers.keys()) != 0:\n            warn_about_headers = False\n            if self.__is_non_html_available():\n                warn_about_headers = not self.__is_headers_available_for_non_html()\n            else:\n                warn_about_headers = not self.__is_headers_available_for_html()\n            if warn_about_headers:\n                logger.warning(\n                    \"You are using an old version of unstructured. \"\n                    \"The headers parameter is ignored\"\n                )\n        self.urls = urls\n        self.continue_on_failure = continue_on_failure\n        self.headers = headers\n        self.unstructured_kwargs = unstructured_kwargs\n        self.show_progress_bar = show_progress_bar\n    def _validate_mode(self, mode: str) -> None:\n        _valid_modes = {\"single\", \"elements\"}\n        if mode not in _valid_modes:\n            raise ValueError(\n                f\"Got {mode} for `mode`, but should be one of `{_valid_modes}`\"\n            )\n    def __is_headers_available_for_html(self) -> bool:\n        _unstructured_version = self.__version.split(\"-\")[0]\n        unstructured_version = tuple([int(x) for x in _unstructured_version.split(\".\")])\n        return unstructured_version >= (0, 5, 7)\n    def __is_headers_available_for_non_html(self) -> bool:\n        _unstructured_version = self.__version.split(\"-\")[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html"}
{"id": "570e12937aee-2", "text": "_unstructured_version = self.__version.split(\"-\")[0]\n        unstructured_version = tuple([int(x) for x in _unstructured_version.split(\".\")])\n        return unstructured_version >= (0, 5, 13)\n    def __is_non_html_available(self) -> bool:\n        _unstructured_version = self.__version.split(\"-\")[0]\n        unstructured_version = tuple([int(x) for x in _unstructured_version.split(\".\")])\n        return unstructured_version >= (0, 5, 12)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load file.\"\"\"\n        from unstructured.partition.auto import partition\n        from unstructured.partition.html import partition_html\n        docs: List[Document] = list()\n        if self.show_progress_bar:\n            try:\n                from tqdm import tqdm\n            except ImportError as e:\n                raise ImportError(\n                    \"Package tqdm must be installed if show_progress_bar=True. \"\n                    \"Please install with 'pip install tqdm' or set \"\n                    \"show_progress_bar=False.\"\n                ) from e\n            urls = tqdm(self.urls)\n        else:\n            urls = self.urls\n        for url in urls:\n            try:\n                if self.__is_non_html_available():\n                    if self.__is_headers_available_for_non_html():\n                        elements = partition(\n                            url=url, headers=self.headers, **self.unstructured_kwargs\n                        )\n                    else:\n                        elements = partition(url=url, **self.unstructured_kwargs)\n                else:\n                    if self.__is_headers_available_for_html():\n                        elements = partition_html(\n                            url=url, headers=self.headers, **self.unstructured_kwargs\n                        )\n                    else:\n                        elements = partition_html(url=url, **self.unstructured_kwargs)\n            except Exception as e:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html"}
{"id": "570e12937aee-3", "text": "except Exception as e:\n                if self.continue_on_failure:\n                    logger.error(f\"Error fetching or processing {url}, exception: {e}\")\n                    continue\n                else:\n                    raise e\n            if self.mode == \"single\":\n                text = \"\\n\\n\".join([str(el) for el in elements])\n                metadata = {\"source\": url}\n                docs.append(Document(page_content=text, metadata=metadata))\n            elif self.mode == \"elements\":\n                for element in elements:\n                    metadata = element.metadata.to_dict()\n                    metadata[\"category\"] = element.category\n                    docs.append(Document(page_content=str(element), metadata=metadata))\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html"}
{"id": "a7960eea77b0-0", "text": "Source code for langchain.document_loaders.youtube\n\"\"\"Loads YouTube transcript.\"\"\"\nfrom __future__ import annotations\nimport logging\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Sequence, Union\nfrom urllib.parse import parse_qs, urlparse\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.pydantic_v1.dataclasses import dataclass\nlogger = logging.getLogger(__name__)\nSCOPES = [\"https://www.googleapis.com/auth/youtube.readonly\"]\n[docs]@dataclass\nclass GoogleApiClient:\n    \"\"\"Generic Google API Client.\n    To use, you should have the ``google_auth_oauthlib,youtube_transcript_api,google``\n    python package installed.\n    As the google api expects credentials you need to set up a google account and\n    register your Service. \"https://developers.google.com/docs/api/quickstart/python\"\n    Example:\n        .. code-block:: python\n            from langchain.document_loaders import GoogleApiClient\n            google_api_client = GoogleApiClient(\n                service_account_path=Path(\"path_to_your_sec_file.json\")\n            )\n    \"\"\"\n    credentials_path: Path = Path.home() / \".credentials\" / \"credentials.json\"\n    service_account_path: Path = Path.home() / \".credentials\" / \"credentials.json\"\n    token_path: Path = Path.home() / \".credentials\" / \"token.json\"\n    def __post_init__(self) -> None:\n        self.creds = self._load_credentials()\n[docs]    @root_validator\n    def validate_channel_or_videoIds_is_set(\n        cls, values: Dict[str, Any]\n    ) -> Dict[str, Any]:\n        \"\"\"Validate that either folder_id or document_ids is set, but not both.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html"}
{"id": "a7960eea77b0-1", "text": "\"\"\"Validate that either folder_id or document_ids is set, but not both.\"\"\"\n        if not values.get(\"credentials_path\") and not values.get(\n            \"service_account_path\"\n        ):\n            raise ValueError(\"Must specify either channel_name or video_ids\")\n        return values\n    def _load_credentials(self) -> Any:\n        \"\"\"Load credentials.\"\"\"\n        # Adapted from https://developers.google.com/drive/api/v3/quickstart/python\n        try:\n            from google.auth.transport.requests import Request\n            from google.oauth2 import service_account\n            from google.oauth2.credentials import Credentials\n            from google_auth_oauthlib.flow import InstalledAppFlow\n            from youtube_transcript_api import YouTubeTranscriptApi  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"You must run\"\n                \"`pip install --upgrade \"\n                \"google-api-python-client google-auth-httplib2 \"\n                \"google-auth-oauthlib \"\n                \"youtube-transcript-api` \"\n                \"to use the Google Drive loader\"\n            )\n        creds = None\n        if self.service_account_path.exists():\n            return service_account.Credentials.from_service_account_file(\n                str(self.service_account_path)\n            )\n        if self.token_path.exists():\n            creds = Credentials.from_authorized_user_file(str(self.token_path), SCOPES)\n        if not creds or not creds.valid:\n            if creds and creds.expired and creds.refresh_token:\n                creds.refresh(Request())\n            else:\n                flow = InstalledAppFlow.from_client_secrets_file(\n                    str(self.credentials_path), SCOPES\n                )\n                creds = flow.run_local_server(port=0)\n            with open(self.token_path, \"w\") as token:\n                token.write(creds.to_json())\n        return creds", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html"}
{"id": "a7960eea77b0-2", "text": "token.write(creds.to_json())\n        return creds\nALLOWED_SCHEMAS = {\"http\", \"https\"}\nALLOWED_NETLOCK = {\n    \"youtu.be\",\n    \"m.youtube.com\",\n    \"youtube.com\",\n    \"www.youtube.com\",\n    \"www.youtube-nocookie.com\",\n    \"vid.plus\",\n}\ndef _parse_video_id(url: str) -> Optional[str]:\n    \"\"\"Parse a youtube url and return the video id if valid, otherwise None.\"\"\"\n    parsed_url = urlparse(url)\n    if parsed_url.scheme not in ALLOWED_SCHEMAS:\n        return None\n    if parsed_url.netloc not in ALLOWED_NETLOCK:\n        return None\n    path = parsed_url.path\n    if path.endswith(\"/watch\"):\n        query = parsed_url.query\n        parsed_query = parse_qs(query)\n        if \"v\" in parsed_query:\n            ids = parsed_query[\"v\"]\n            video_id = ids if isinstance(ids, str) else ids[0]\n        else:\n            return None\n    else:\n        path = parsed_url.path.lstrip(\"/\")\n        video_id = path.split(\"/\")[-1]\n    if len(video_id) != 11:  # Video IDs are 11 characters long\n        return None\n    return video_id\n[docs]class YoutubeLoader(BaseLoader):\n    \"\"\"Load `YouTube` transcripts.\"\"\"\n[docs]    def __init__(\n        self,\n        video_id: str,\n        add_video_info: bool = False,\n        language: Union[str, Sequence[str]] = \"en\",\n        translation: str = \"en\",\n        continue_on_failure: bool = False,\n    ):\n        \"\"\"Initialize with YouTube video ID.\"\"\"\n        self.video_id = video_id\n        self.add_video_info = add_video_info\n        self.language = language", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html"}
{"id": "a7960eea77b0-3", "text": "self.add_video_info = add_video_info\n        self.language = language\n        if isinstance(language, str):\n            self.language = [language]\n        else:\n            self.language = language\n        self.translation = translation\n        self.continue_on_failure = continue_on_failure\n[docs]    @staticmethod\n    def extract_video_id(youtube_url: str) -> str:\n        \"\"\"Extract video id from common YT urls.\"\"\"\n        video_id = _parse_video_id(youtube_url)\n        if not video_id:\n            raise ValueError(\n                f\"Could not determine the video ID for the URL {youtube_url}\"\n            )\n        return video_id\n[docs]    @classmethod\n    def from_youtube_url(cls, youtube_url: str, **kwargs: Any) -> YoutubeLoader:\n        \"\"\"Given youtube URL, load video.\"\"\"\n        video_id = cls.extract_video_id(youtube_url)\n        return cls(video_id, **kwargs)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        try:\n            from youtube_transcript_api import (\n                NoTranscriptFound,\n                TranscriptsDisabled,\n                YouTubeTranscriptApi,\n            )\n        except ImportError:\n            raise ImportError(\n                \"Could not import youtube_transcript_api python package. \"\n                \"Please install it with `pip install youtube-transcript-api`.\"\n            )\n        metadata = {\"source\": self.video_id}\n        if self.add_video_info:\n            # Get more video meta info\n            # Such as title, description, thumbnail url, publish_date\n            video_info = self._get_video_info()\n            metadata.update(video_info)\n        try:\n            transcript_list = YouTubeTranscriptApi.list_transcripts(self.video_id)\n        except TranscriptsDisabled:\n            return []\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html"}
{"id": "a7960eea77b0-4", "text": "except TranscriptsDisabled:\n            return []\n        try:\n            transcript = transcript_list.find_transcript(self.language)\n        except NoTranscriptFound:\n            en_transcript = transcript_list.find_transcript([\"en\"])\n            transcript = en_transcript.translate(self.translation)\n        transcript_pieces = transcript.fetch()\n        transcript = \" \".join([t[\"text\"].strip(\" \") for t in transcript_pieces])\n        return [Document(page_content=transcript, metadata=metadata)]\n    def _get_video_info(self) -> dict:\n        \"\"\"Get important video information.\n        Components are:\n            - title\n            - description\n            - thumbnail url,\n            - publish_date\n            - channel_author\n            - and more.\n        \"\"\"\n        try:\n            from pytube import YouTube\n        except ImportError:\n            raise ImportError(\n                \"Could not import pytube python package. \"\n                \"Please install it with `pip install pytube`.\"\n            )\n        yt = YouTube(f\"https://www.youtube.com/watch?v={self.video_id}\")\n        video_info = {\n            \"title\": yt.title or \"Unknown\",\n            \"description\": yt.description or \"Unknown\",\n            \"view_count\": yt.views or 0,\n            \"thumbnail_url\": yt.thumbnail_url or \"Unknown\",\n            \"publish_date\": yt.publish_date.strftime(\"%Y-%m-%d %H:%M:%S\")\n            if yt.publish_date\n            else \"Unknown\",\n            \"length\": yt.length or 0,\n            \"author\": yt.author or \"Unknown\",\n        }\n        return video_info\n[docs]@dataclass\nclass GoogleApiYoutubeLoader(BaseLoader):\n    \"\"\"Load all Videos from a `YouTube` Channel.\n    To use, you should have the ``googleapiclient,youtube_transcript_api``", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html"}
{"id": "a7960eea77b0-5", "text": "To use, you should have the ``googleapiclient,youtube_transcript_api``\n    python package installed.\n    As the service needs a google_api_client, you first have to initialize\n    the GoogleApiClient.\n    Additionally you have to either provide a channel name or a list of videoids\n    \"https://developers.google.com/docs/api/quickstart/python\"\n    Example:\n        .. code-block:: python\n            from langchain.document_loaders import GoogleApiClient\n            from langchain.document_loaders import GoogleApiYoutubeLoader\n            google_api_client = GoogleApiClient(\n                service_account_path=Path(\"path_to_your_sec_file.json\")\n            )\n            loader = GoogleApiYoutubeLoader(\n                google_api_client=google_api_client,\n                channel_name = \"CodeAesthetic\"\n            )\n            load.load()\n    \"\"\"\n    google_api_client: GoogleApiClient\n    channel_name: Optional[str] = None\n    video_ids: Optional[List[str]] = None\n    add_video_info: bool = True\n    captions_language: str = \"en\"\n    continue_on_failure: bool = False\n    def __post_init__(self) -> None:\n        self.youtube_client = self._build_youtube_client(self.google_api_client.creds)\n    def _build_youtube_client(self, creds: Any) -> Any:\n        try:\n            from googleapiclient.discovery import build\n            from youtube_transcript_api import YouTubeTranscriptApi  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"You must run\"\n                \"`pip install --upgrade \"\n                \"google-api-python-client google-auth-httplib2 \"\n                \"google-auth-oauthlib \"\n                \"youtube-transcript-api` \"\n                \"to use the Google Drive loader\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html"}
{"id": "a7960eea77b0-6", "text": "\"to use the Google Drive loader\"\n            )\n        return build(\"youtube\", \"v3\", credentials=creds)\n[docs]    @root_validator\n    def validate_channel_or_videoIds_is_set(\n        cls, values: Dict[str, Any]\n    ) -> Dict[str, Any]:\n        \"\"\"Validate that either folder_id or document_ids is set, but not both.\"\"\"\n        if not values.get(\"channel_name\") and not values.get(\"video_ids\"):\n            raise ValueError(\"Must specify either channel_name or video_ids\")\n        return values\n    def _get_transcripe_for_video_id(self, video_id: str) -> str:\n        from youtube_transcript_api import NoTranscriptFound, YouTubeTranscriptApi\n        transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)\n        try:\n            transcript = transcript_list.find_transcript([self.captions_language])\n        except NoTranscriptFound:\n            for available_transcript in transcript_list:\n                transcript = available_transcript.translate(self.captions_language)\n                continue\n        transcript_pieces = transcript.fetch()\n        return \" \".join([t[\"text\"].strip(\" \") for t in transcript_pieces])\n    def _get_document_for_video_id(self, video_id: str, **kwargs: Any) -> Document:\n        captions = self._get_transcripe_for_video_id(video_id)\n        video_response = (\n            self.youtube_client.videos()\n            .list(\n                part=\"id,snippet\",\n                id=video_id,\n            )\n            .execute()\n        )\n        return Document(\n            page_content=captions,\n            metadata=video_response.get(\"items\")[0],\n        )\n    def _get_channel_id(self, channel_name: str) -> str:\n        request = self.youtube_client.search().list(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html"}
{"id": "a7960eea77b0-7", "text": "request = self.youtube_client.search().list(\n            part=\"id\",\n            q=channel_name,\n            type=\"channel\",\n            maxResults=1,  # we only need one result since channel names are unique\n        )\n        response = request.execute()\n        channel_id = response[\"items\"][0][\"id\"][\"channelId\"]\n        return channel_id\n    def _get_document_for_channel(self, channel: str, **kwargs: Any) -> List[Document]:\n        try:\n            from youtube_transcript_api import (\n                NoTranscriptFound,\n                TranscriptsDisabled,\n            )\n        except ImportError:\n            raise ImportError(\n                \"You must run\"\n                \"`pip install --upgrade \"\n                \"youtube-transcript-api` \"\n                \"to use the youtube loader\"\n            )\n        channel_id = self._get_channel_id(channel)\n        request = self.youtube_client.search().list(\n            part=\"id,snippet\",\n            channelId=channel_id,\n            maxResults=50,  # adjust this value to retrieve more or fewer videos\n        )\n        video_ids = []\n        while request is not None:\n            response = request.execute()\n            # Add each video ID to the list\n            for item in response[\"items\"]:\n                if not item[\"id\"].get(\"videoId\"):\n                    continue\n                meta_data = {\"videoId\": item[\"id\"][\"videoId\"]}\n                if self.add_video_info:\n                    item[\"snippet\"].pop(\"thumbnails\")\n                    meta_data.update(item[\"snippet\"])\n                try:\n                    page_content = self._get_transcripe_for_video_id(\n                        item[\"id\"][\"videoId\"]\n                    )\n                    video_ids.append(\n                        Document(\n                            page_content=page_content,\n                            metadata=meta_data,\n                        )\n                    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html"}
{"id": "a7960eea77b0-8", "text": "metadata=meta_data,\n                        )\n                    )\n                except (TranscriptsDisabled, NoTranscriptFound) as e:\n                    if self.continue_on_failure:\n                        logger.error(\n                            \"Error fetching transscript \"\n                            + f\" {item['id']['videoId']}, exception: {e}\"\n                        )\n                    else:\n                        raise e\n                    pass\n            request = self.youtube_client.search().list_next(request, response)\n        return video_ids\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        document_list = []\n        if self.channel_name:\n            document_list.extend(self._get_document_for_channel(self.channel_name))\n        elif self.video_ids:\n            document_list.extend(\n                [\n                    self._get_document_for_video_id(video_id)\n                    for video_id in self.video_ids\n                ]\n            )\n        else:\n            raise ValueError(\"Must specify either channel_name or video_ids\")\n        return document_list", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html"}
{"id": "5b99bf7d9362-0", "text": "Source code for langchain.document_loaders.xorbits\nfrom typing import Any\nfrom langchain.document_loaders.dataframe import BaseDataFrameLoader\n[docs]class XorbitsLoader(BaseDataFrameLoader):\n    \"\"\"Load `Xorbits` DataFrame.\"\"\"\n[docs]    def __init__(self, data_frame: Any, page_content_column: str = \"text\"):\n        \"\"\"Initialize with dataframe object.\n        Requirements:\n            Must have xorbits installed. You can install with `pip install xorbits`.\n        Args:\n            data_frame: Xorbits DataFrame object.\n            page_content_column: Name of the column containing the page content.\n              Defaults to \"text\".\n        \"\"\"\n        try:\n            import xorbits.pandas as pd\n        except ImportError as e:\n            raise ImportError(\n                \"Cannot import xorbits, please install with 'pip install xorbits'.\"\n            ) from e\n        if not isinstance(data_frame, pd.DataFrame):\n            raise ValueError(\n                f\"Expected data_frame to be a xorbits.pandas.DataFrame, \\\n                  got {type(data_frame)}\"\n            )\n        super().__init__(data_frame, page_content_column=page_content_column)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/xorbits.html"}
{"id": "60cc8f355c1b-0", "text": "Source code for langchain.document_loaders.excel\n\"\"\"Loads Microsoft Excel files.\"\"\"\nfrom typing import Any, List\nfrom langchain.document_loaders.unstructured import (\n    UnstructuredFileLoader,\n    validate_unstructured_version,\n)\n[docs]class UnstructuredExcelLoader(UnstructuredFileLoader):\n    \"\"\"Load Microsoft Excel files using `Unstructured`.\n    Like other\n    Unstructured loaders, UnstructuredExcelLoader can be used in both\n    \"single\" and \"elements\" mode. If you use the loader in \"elements\"\n    mode, each sheet in the Excel file will be a an Unstructured Table\n    element. If you use the loader in \"elements\" mode, an\n    HTML representation of the table will be available in the\n    \"text_as_html\" key in the document metadata.\n    Examples\n    --------\n    from langchain.document_loaders.excel import UnstructuredExcelLoader\n    loader = UnstructuredExcelLoader(\"stanley-cups.xlsd\", mode=\"elements\")\n    docs = loader.load()\n    \"\"\"\n[docs]    def __init__(\n        self, file_path: str, mode: str = \"single\", **unstructured_kwargs: Any\n    ):\n        \"\"\"\n        Args:\n            file_path: The path to the Microsoft Excel file.\n            mode: The mode to use when partitioning the file. See unstructured docs\n              for more info. Optional. Defaults to \"single\".\n            **unstructured_kwargs: Keyword arguments to pass to unstructured.\n        \"\"\"\n        validate_unstructured_version(min_unstructured_version=\"0.6.7\")\n        super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)\n    def _get_elements(self) -> List:\n        from unstructured.partition.xlsx import partition_xlsx", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/excel.html"}
{"id": "60cc8f355c1b-1", "text": "from unstructured.partition.xlsx import partition_xlsx\n        return partition_xlsx(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/excel.html"}
{"id": "a111f5ccca3a-0", "text": "Source code for langchain.document_loaders.mediawikidump\nimport logging\nfrom pathlib import Path\nfrom typing import List, Optional, Sequence, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n[docs]class MWDumpLoader(BaseLoader):\n    \"\"\"Load `MediaWiki` dump from an `XML` file.\n    Example:\n        .. code-block:: python\n            from langchain.document_loaders import MWDumpLoader\n            loader = MWDumpLoader(\n                file_path=\"myWiki.xml\",\n                encoding=\"utf8\"\n            )\n            docs = loader.load()\n            from langchain.text_splitter import RecursiveCharacterTextSplitter\n            text_splitter = RecursiveCharacterTextSplitter(\n                chunk_size=1000, chunk_overlap=0\n            )\n            texts = text_splitter.split_documents(docs)\n    :param file_path: XML local file path\n    :type file_path: str\n    :param encoding: Charset encoding, defaults to \"utf8\"\n    :type encoding: str, optional\n    :param namespaces: The namespace of pages you want to parse.\n        See https://www.mediawiki.org/wiki/Help:Namespaces#Localisation\n        for a list of all common namespaces\n    :type namespaces: List[int],optional\n    :param skip_redirects: TR=rue to skip pages that redirect to other pages,\n        False to keep them. False by default\n    :type skip_redirects: bool, optional\n    :param stop_on_error: False to skip over pages that cause parsing errors,\n        True to stop. True by default\n    :type stop_on_error: bool, optional\n    \"\"\"\n[docs]    def __init__(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mediawikidump.html"}
{"id": "a111f5ccca3a-1", "text": "\"\"\"\n[docs]    def __init__(\n        self,\n        file_path: Union[str, Path],\n        encoding: Optional[str] = \"utf8\",\n        namespaces: Optional[Sequence[int]] = None,\n        skip_redirects: Optional[bool] = False,\n        stop_on_error: Optional[bool] = True,\n    ):\n        self.file_path = file_path if isinstance(file_path, str) else str(file_path)\n        self.encoding = encoding\n        # Namespaces range from -2 to 15, inclusive.\n        self.namespaces = namespaces or list(range(-2, 16))\n        self.skip_redirects = skip_redirects\n        self.stop_on_error = stop_on_error\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load from a file path.\"\"\"\n        try:\n            import mwparserfromhell\n            import mwxml\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import 'mwparserfromhell' or 'mwxml'. Please install with\"\n                \" `pip install mwparserfromhell mwxml`.\"\n            ) from e\n        dump = mwxml.Dump.from_file(open(self.file_path, encoding=self.encoding))\n        docs = []\n        for page in dump.pages:\n            if self.skip_redirects and page.redirect:\n                continue\n            if page.namespace not in self.namespaces:\n                continue\n            try:\n                for revision in page:\n                    code = mwparserfromhell.parse(revision.text)\n                    text = code.strip_code(\n                        normalize=True, collapse=True, keep_template_params=False\n                    )\n                    metadata = {\"source\": page.title}\n                    docs.append(Document(page_content=text, metadata=metadata))\n            except Exception as e:\n                logger.error(\"Parsing error: {}\".format(e))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mediawikidump.html"}
{"id": "a111f5ccca3a-2", "text": "except Exception as e:\n                logger.error(\"Parsing error: {}\".format(e))\n                if self.stop_on_error:\n                    raise e\n                else:\n                    continue\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mediawikidump.html"}
{"id": "875c81a2d4da-0", "text": "Source code for langchain.document_loaders.roam\nfrom pathlib import Path\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class RoamLoader(BaseLoader):\n    \"\"\"Load `Roam` files from a directory.\"\"\"\n[docs]    def __init__(self, path: str):\n        \"\"\"Initialize with a path.\"\"\"\n        self.file_path = path\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        ps = list(Path(self.file_path).glob(\"**/*.md\"))\n        docs = []\n        for p in ps:\n            with open(p) as f:\n                text = f.read()\n            metadata = {\"source\": str(p)}\n            docs.append(Document(page_content=text, metadata=metadata))\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/roam.html"}
{"id": "544702164f73-0", "text": "Source code for langchain.document_loaders.rspace\nimport os\nfrom typing import Any, Dict, Iterator, List, Optional, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders import PyPDFLoader\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utils import get_from_dict_or_env\n[docs]class RSpaceLoader(BaseLoader):\n    \"\"\"\n    Loads  content from RSpace notebooks, folders, documents or PDF Gallery files into\n    Langchain documents.\n    Maps  RSpace document <-> Langchain Document in 1-1. PDFs are imported using PyPDF.\n    Requirements are rspace_client (`pip install rspace_client`) and PyPDF if importing\n     PDF docs (`pip install pypdf`).\n    \"\"\"\n[docs]    def __init__(\n        self, global_id: str, api_key: Optional[str] = None, url: Optional[str] = None\n    ):\n        \"\"\"api_key: RSpace API key - can also be supplied as environment variable\n        'RSPACE_API_KEY'\n        url: str\n        The URL of your RSpace instance - can also be supplied as environment\n        variable 'RSPACE_URL'\n        global_id: str\n         The global ID of the resource to load,\n        e.g. 'SD12344' (a single document); 'GL12345'(A PDF file in the gallery);\n        'NB4567' (a notebook); 'FL12244' (a folder)\n        \"\"\"\n        args: Dict[str, Optional[str]] = {\n            \"api_key\": api_key,\n            \"url\": url,\n            \"global_id\": global_id,\n        }\n        verified_args: Dict[str, str] = RSpaceLoader.validate_environment(args)\n        self.api_key = verified_args[\"api_key\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rspace.html"}
{"id": "544702164f73-1", "text": "self.api_key = verified_args[\"api_key\"]\n        self.url = verified_args[\"url\"]\n        self.global_id: str = verified_args[\"global_id\"]\n[docs]    @classmethod\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that API key and URL exists in environment.\"\"\"\n        values[\"api_key\"] = get_from_dict_or_env(values, \"api_key\", \"RSPACE_API_KEY\")\n        values[\"url\"] = get_from_dict_or_env(values, \"url\", \"RSPACE_URL\")\n        if \"global_id\" not in values or values[\"global_id\"] is None:\n            raise ValueError(\n                \"No value supplied for global_id. Please supply an RSpace global ID\"\n            )\n        return values\n    def _create_rspace_client(self) -> Any:\n        \"\"\"Create a RSpace client.\"\"\"\n        try:\n            from rspace_client.eln import eln, field_content\n        except ImportError:\n            raise ImportError(\"You must run \" \"`pip install rspace_client`\")\n        try:\n            eln = eln.ELNClient(self.url, self.api_key)\n            eln.get_status()\n        except Exception:\n            raise Exception(\n                f\"Unable to initialise client - is url {self.url} or \"\n                f\"api key  correct?\"\n            )\n        return eln, field_content.FieldContent\n    def _get_doc(self, cli: Any, field_content: Any, d_id: Union[str, int]) -> Document:\n        content = \"\"\n        doc = cli.get_document(d_id)\n        content += f\"<h2>{doc['name']}<h2/>\"\n        for f in doc[\"fields\"]:\n            content += f\"{f['name']}\\n\"\n            fc = field_content(f[\"content\"])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rspace.html"}
{"id": "544702164f73-2", "text": "fc = field_content(f[\"content\"])\n            content += fc.get_text()\n            content += \"\\n\"\n        return Document(\n            metadata={\"source\": f\"rspace: {doc['name']}-{doc['globalId']}\"},\n            page_content=content,\n        )\n    def _load_structured_doc(self) -> Iterator[Document]:\n        cli, field_content = self._create_rspace_client()\n        yield self._get_doc(cli, field_content, self.global_id)\n    def _load_folder_tree(self) -> Iterator[Document]:\n        cli, field_content = self._create_rspace_client()\n        if self.global_id:\n            docs_in_folder = cli.list_folder_tree(\n                folder_id=self.global_id[2:], typesToInclude=[\"document\"]\n            )\n        doc_ids: List[int] = [d[\"id\"] for d in docs_in_folder[\"records\"]]\n        for doc_id in doc_ids:\n            yield self._get_doc(cli, field_content, doc_id)\n    def _load_pdf(self) -> Iterator[Document]:\n        cli, field_content = self._create_rspace_client()\n        file_info = cli.get_file_info(self.global_id)\n        _, ext = os.path.splitext(file_info[\"name\"])\n        if ext.lower() == \".pdf\":\n            outfile = f\"{self.global_id}.pdf\"\n            cli.download_file(self.global_id, outfile)\n            pdf_loader = PyPDFLoader(outfile)\n            for pdf in pdf_loader.lazy_load():\n                pdf.metadata[\"rspace_src\"] = self.global_id\n                yield pdf\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        if self.global_id and \"GL\" in self.global_id:\n            for d in self._load_pdf():\n                yield d", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rspace.html"}
{"id": "544702164f73-3", "text": "for d in self._load_pdf():\n                yield d\n        elif self.global_id and \"SD\" in self.global_id:\n            for d in self._load_structured_doc():\n                yield d\n        elif self.global_id and self.global_id[0:2] in [\"FL\", \"NB\"]:\n            for d in self._load_folder_tree():\n                yield d\n        else:\n            raise ValueError(\"Unknown global ID type\")\n[docs]    def load(self) -> List[Document]:\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rspace.html"}
{"id": "fe6430ba3618-0", "text": "Source code for langchain.document_loaders.rtf\n\"\"\"Loads rich text files.\"\"\"\nfrom typing import Any, List\nfrom langchain.document_loaders.unstructured import (\n    UnstructuredFileLoader,\n    satisfies_min_unstructured_version,\n)\n[docs]class UnstructuredRTFLoader(UnstructuredFileLoader):\n    \"\"\"Load `RTF` files using `Unstructured`.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredRTFLoader\n    loader = UnstructuredRTFLoader(\n        \"example.rtf\", mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition-rtf\n    \"\"\"\n[docs]    def __init__(\n        self, file_path: str, mode: str = \"single\", **unstructured_kwargs: Any\n    ):\n        \"\"\"\n        Initialize with a file path.\n        Args:\n            file_path: The path to the file to load.\n            mode: The mode to use for partitioning. See unstructured for details.\n                Defaults to \"single\".\n            **unstructured_kwargs: Additional keyword arguments to pass\n                to unstructured.\n        \"\"\"\n        min_unstructured_version = \"0.5.12\"\n        if not satisfies_min_unstructured_version(min_unstructured_version):\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rtf.html"}
{"id": "fe6430ba3618-1", "text": "if not satisfies_min_unstructured_version(min_unstructured_version):\n            raise ValueError(\n                \"Partitioning rtf files is only supported in \"\n                f\"unstructured>={min_unstructured_version}.\"\n            )\n        super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)\n    def _get_elements(self) -> List:\n        from unstructured.partition.rtf import partition_rtf\n        return partition_rtf(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rtf.html"}
{"id": "7ca74d3f2449-0", "text": "Source code for langchain.document_loaders.psychic\nfrom typing import List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class PsychicLoader(BaseLoader):\n    \"\"\"Load from `Psychic.dev`.\"\"\"\n[docs]    def __init__(\n        self, api_key: str, account_id: str, connector_id: Optional[str] = None\n    ):\n        \"\"\"Initialize with API key, connector id, and account id.\n        Args:\n            api_key: The Psychic API key.\n            account_id: The Psychic account id.\n            connector_id: The Psychic connector id.\n        \"\"\"\n        try:\n            from psychicapi import ConnectorId, Psychic  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"`psychicapi` package not found, please run `pip install psychicapi`\"\n            )\n        self.psychic = Psychic(secret_key=api_key)\n        self.connector_id = ConnectorId(connector_id)\n        self.account_id = account_id\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        psychic_docs = self.psychic.get_documents(\n            connector_id=self.connector_id, account_id=self.account_id\n        )\n        return [\n            Document(\n                page_content=doc[\"content\"],\n                metadata={\"title\": doc[\"title\"], \"source\": doc[\"uri\"]},\n            )\n            for doc in psychic_docs.documents\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/psychic.html"}
{"id": "94be6c25dcdc-0", "text": "Source code for langchain.document_loaders.embaas\nimport base64\nimport warnings\nfrom typing import Any, Dict, Iterator, List, Optional\nimport requests\nfrom typing_extensions import NotRequired, TypedDict\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseBlobParser, BaseLoader\nfrom langchain.document_loaders.blob_loaders import Blob\nfrom langchain.pydantic_v1 import BaseModel, root_validator, validator\nfrom langchain.text_splitter import TextSplitter\nfrom langchain.utils import get_from_dict_or_env\nEMBAAS_DOC_API_URL = \"https://api.embaas.io/v1/document/extract-text/bytes/\"\n[docs]class EmbaasDocumentExtractionParameters(TypedDict):\n    \"\"\"Parameters for the embaas document extraction API.\"\"\"\n    mime_type: NotRequired[str]\n    \"\"\"The mime type of the document.\"\"\"\n    file_extension: NotRequired[str]\n    \"\"\"The file extension of the document.\"\"\"\n    file_name: NotRequired[str]\n    \"\"\"The file name of the document.\"\"\"\n    should_chunk: NotRequired[bool]\n    \"\"\"Whether to chunk the document into pages.\"\"\"\n    chunk_size: NotRequired[int]\n    \"\"\"The maximum size of the text chunks.\"\"\"\n    chunk_overlap: NotRequired[int]\n    \"\"\"The maximum overlap allowed between chunks.\"\"\"\n    chunk_splitter: NotRequired[str]\n    \"\"\"The text splitter class name for creating chunks.\"\"\"\n    separators: NotRequired[List[str]]\n    \"\"\"The separators for chunks.\"\"\"\n    should_embed: NotRequired[bool]\n    \"\"\"Whether to create embeddings for the document in the response.\"\"\"\n    model: NotRequired[str]\n    \"\"\"The model to pass to the Embaas document extraction API.\"\"\"\n    instruction: NotRequired[str]\n    \"\"\"The instruction to pass to the Embaas document extraction API.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html"}
{"id": "94be6c25dcdc-1", "text": "\"\"\"The instruction to pass to the Embaas document extraction API.\"\"\"\n[docs]class EmbaasDocumentExtractionPayload(EmbaasDocumentExtractionParameters):\n    \"\"\"Payload for the Embaas document extraction API.\"\"\"\n    bytes: str\n    \"\"\"The base64 encoded bytes of the document to extract text from.\"\"\"\n[docs]class BaseEmbaasLoader(BaseModel):\n    \"\"\"Base loader for `Embaas` document extraction API.\"\"\"\n    embaas_api_key: Optional[str] = None\n    \"\"\"The API key for the Embaas document extraction API.\"\"\"\n    api_url: str = EMBAAS_DOC_API_URL\n    \"\"\"The URL of the Embaas document extraction API.\"\"\"\n    params: EmbaasDocumentExtractionParameters = EmbaasDocumentExtractionParameters()\n    \"\"\"Additional parameters to pass to the Embaas document extraction API.\"\"\"\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        embaas_api_key = get_from_dict_or_env(\n            values, \"embaas_api_key\", \"EMBAAS_API_KEY\"\n        )\n        values[\"embaas_api_key\"] = embaas_api_key\n        return values\n[docs]class EmbaasBlobLoader(BaseEmbaasLoader, BaseBlobParser):\n    \"\"\"Load `Embaas` blob.\n    To use, you should have the\n    environment variable ``EMBAAS_API_KEY`` set with your API key, or pass\n    it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            # Default parsing\n            from langchain.document_loaders.embaas import EmbaasBlobLoader\n            loader = EmbaasBlobLoader()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html"}
{"id": "94be6c25dcdc-2", "text": "loader = EmbaasBlobLoader()\n            blob = Blob.from_path(path=\"example.mp3\")\n            documents = loader.parse(blob=blob)\n            # Custom api parameters (create embeddings automatically)\n            from langchain.document_loaders.embaas import EmbaasBlobLoader\n            loader = EmbaasBlobLoader(\n                params={\n                    \"should_embed\": True,\n                    \"model\": \"e5-large-v2\",\n                    \"chunk_size\": 256,\n                    \"chunk_splitter\": \"CharacterTextSplitter\"\n                }\n            )\n            blob = Blob.from_path(path=\"example.pdf\")\n            documents = loader.parse(blob=blob)\n    \"\"\"\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Parses the blob lazily.\n        Args:\n            blob: The blob to parse.\n        \"\"\"\n        yield from self._get_documents(blob=blob)\n    @staticmethod\n    def _api_response_to_documents(chunks: List[Dict[str, Any]]) -> List[Document]:\n        \"\"\"Convert the API response to a list of documents.\"\"\"\n        docs = []\n        for chunk in chunks:\n            metadata = chunk[\"metadata\"]\n            if chunk.get(\"embedding\", None) is not None:\n                metadata[\"embedding\"] = chunk[\"embedding\"]\n            doc = Document(page_content=chunk[\"text\"], metadata=metadata)\n            docs.append(doc)\n        return docs\n    def _generate_payload(self, blob: Blob) -> EmbaasDocumentExtractionPayload:\n        \"\"\"Generates payload for the API request.\"\"\"\n        base64_byte_str = base64.b64encode(blob.as_bytes()).decode()\n        payload: EmbaasDocumentExtractionPayload = EmbaasDocumentExtractionPayload(\n            bytes=base64_byte_str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html"}
{"id": "94be6c25dcdc-3", "text": "bytes=base64_byte_str,\n            # Workaround for mypy issue: https://github.com/python/mypy/issues/9408\n            # type: ignore\n            **self.params,\n        )\n        if blob.mimetype is not None and payload.get(\"mime_type\", None) is None:\n            payload[\"mime_type\"] = blob.mimetype\n        return payload\n    def _handle_request(\n        self, payload: EmbaasDocumentExtractionPayload\n    ) -> List[Document]:\n        \"\"\"Sends a request to the embaas API and handles the response.\"\"\"\n        headers = {\n            \"Authorization\": f\"Bearer {self.embaas_api_key}\",\n            \"Content-Type\": \"application/json\",\n        }\n        response = requests.post(self.api_url, headers=headers, json=payload)\n        response.raise_for_status()\n        parsed_response = response.json()\n        return EmbaasBlobLoader._api_response_to_documents(\n            chunks=parsed_response[\"data\"][\"chunks\"]\n        )\n    def _get_documents(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Get the documents from the blob.\"\"\"\n        payload = self._generate_payload(blob=blob)\n        try:\n            documents = self._handle_request(payload=payload)\n        except requests.exceptions.RequestException as e:\n            if e.response is None or not e.response.text:\n                raise ValueError(\n                    f\"Error raised by Embaas document text extraction API: {e}\"\n                )\n            parsed_response = e.response.json()\n            if \"message\" in parsed_response:\n                raise ValueError(\n                    f\"Validation Error raised by Embaas document text extraction API:\"\n                    f\" {parsed_response['message']}\"\n                )\n            raise\n        yield from documents", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html"}
{"id": "94be6c25dcdc-4", "text": ")\n            raise\n        yield from documents\n[docs]class EmbaasLoader(BaseEmbaasLoader, BaseLoader):\n    \"\"\"Load from `Embaas`.\n    To use, you should have the\n    environment variable ``EMBAAS_API_KEY`` set with your API key, or pass\n    it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            # Default parsing\n            from langchain.document_loaders.embaas import EmbaasLoader\n            loader = EmbaasLoader(file_path=\"example.mp3\")\n            documents = loader.load()\n            # Custom api parameters (create embeddings automatically)\n            from langchain.document_loaders.embaas import EmbaasBlobLoader\n            loader = EmbaasBlobLoader(\n                file_path=\"example.pdf\",\n                params={\n                    \"should_embed\": True,\n                    \"model\": \"e5-large-v2\",\n                    \"chunk_size\": 256,\n                    \"chunk_splitter\": \"CharacterTextSplitter\"\n                }\n            )\n            documents = loader.load()\n    \"\"\"\n    file_path: str\n    \"\"\"The path to the file to load.\"\"\"\n    blob_loader: Optional[EmbaasBlobLoader]\n    \"\"\"The blob loader to use. If not provided, a default one will be created.\"\"\"\n    @validator(\"blob_loader\", always=True)\n    def validate_blob_loader(\n        cls, v: EmbaasBlobLoader, values: Dict\n    ) -> EmbaasBlobLoader:\n        return v or EmbaasBlobLoader(\n            embaas_api_key=values[\"embaas_api_key\"],\n            api_url=values[\"api_url\"],\n            params=values[\"params\"],\n        )\n[docs]    def lazy_load(self) -> Iterator[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html"}
{"id": "94be6c25dcdc-5", "text": ")\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Load the documents from the file path lazily.\"\"\"\n        blob = Blob.from_path(path=self.file_path)\n        assert self.blob_loader is not None\n        # Should never be None, but mypy doesn't know that.\n        yield from self.blob_loader.lazy_parse(blob=blob)\n[docs]    def load(self) -> List[Document]:\n        return list(self.lazy_load())\n[docs]    def load_and_split(\n        self, text_splitter: Optional[TextSplitter] = None\n    ) -> List[Document]:\n        if self.params.get(\"should_embed\", False):\n            warnings.warn(\n                \"Embeddings are not supported with load_and_split.\"\n                \" Use the API splitter to properly generate embeddings.\"\n                \" For more information see embaas.io docs.\"\n            )\n        return super().load_and_split(text_splitter=text_splitter)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html"}
{"id": "6a68d22f5289-0", "text": "Source code for langchain.document_loaders.browserless\nfrom typing import Iterator, List, Union\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class BrowserlessLoader(BaseLoader):\n    \"\"\"Load webpages with `Browserless` /content endpoint.\"\"\"\n[docs]    def __init__(\n        self, api_token: str, urls: Union[str, List[str]], text_content: bool = True\n    ):\n        \"\"\"Initialize with API token and the URLs to scrape\"\"\"\n        self.api_token = api_token\n        \"\"\"Browserless API token.\"\"\"\n        self.urls = urls\n        \"\"\"List of URLs to scrape.\"\"\"\n        self.text_content = text_content\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazy load Documents from URLs.\"\"\"\n        for url in self.urls:\n            if self.text_content:\n                response = requests.post(\n                    \"https://chrome.browserless.io/scrape\",\n                    params={\n                        \"token\": self.api_token,\n                    },\n                    json={\n                        \"url\": url,\n                        \"elements\": [\n                            {\n                                \"selector\": \"body\",\n                            }\n                        ],\n                    },\n                )\n                yield Document(\n                    page_content=response.json()[\"data\"][0][\"results\"][0][\"text\"],\n                    metadata={\n                        \"source\": url,\n                    },\n                )\n            else:\n                response = requests.post(\n                    \"https://chrome.browserless.io/content\",\n                    params={\n                        \"token\": self.api_token,\n                    },\n                    json={\n                        \"url\": url,\n                    },\n                )\n                yield Document(\n                    page_content=response.text,\n                    metadata={\n                        \"source\": url,\n                    },\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/browserless.html"}
{"id": "6a68d22f5289-1", "text": "metadata={\n                        \"source\": url,\n                    },\n                )\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load Documents from URLs.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/browserless.html"}
{"id": "c98377ce1469-0", "text": "Source code for langchain.document_loaders.whatsapp_chat\nimport re\nfrom pathlib import Path\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]def concatenate_rows(date: str, sender: str, text: str) -> str:\n    \"\"\"Combine message information in a readable format ready to be used.\"\"\"\n    return f\"{sender} on {date}: {text}\\n\\n\"\n[docs]class WhatsAppChatLoader(BaseLoader):\n    \"\"\"Load `WhatsApp` messages text file.\"\"\"\n[docs]    def __init__(self, path: str):\n        \"\"\"Initialize with path.\"\"\"\n        self.file_path = path\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        p = Path(self.file_path)\n        text_content = \"\"\n        with open(p, encoding=\"utf8\") as f:\n            lines = f.readlines()\n        message_line_regex = r\"\"\"\n            \\[?\n            (\n                \\d{1,4}\n                [\\/.]\n                \\d{1,2}\n                [\\/.]\n                \\d{1,4}\n                ,\\s\n                \\d{1,2}\n                :\\d{2}\n                (?:\n                    :\\d{2}\n                )?\n                (?:[\\s_](?:AM|PM))?\n            )\n            \\]?\n            [\\s-]*\n            ([~\\w\\s]+)\n            [:]+\n            \\s\n            (.+)\n        \"\"\"\n        ignore_lines = [\"This message was deleted\", \"<Media omitted>\"]\n        for line in lines:\n            result = re.match(\n                message_line_regex, line.strip(), flags=re.VERBOSE | re.IGNORECASE\n            )\n            if result:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/whatsapp_chat.html"}
{"id": "c98377ce1469-1", "text": ")\n            if result:\n                date, sender, text = result.groups()\n                if text not in ignore_lines:\n                    text_content += concatenate_rows(date, sender, text)\n        metadata = {\"source\": str(p)}\n        return [Document(page_content=text_content, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/whatsapp_chat.html"}
{"id": "fcdf66b17e20-0", "text": "Source code for langchain.document_loaders.polars_dataframe\nfrom typing import Any, Iterator\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.dataframe import BaseDataFrameLoader\n[docs]class PolarsDataFrameLoader(BaseDataFrameLoader):\n    \"\"\"Load `Polars` DataFrame.\"\"\"\n[docs]    def __init__(self, data_frame: Any, *, page_content_column: str = \"text\"):\n        \"\"\"Initialize with dataframe object.\n        Args:\n            data_frame: Polars DataFrame object.\n            page_content_column: Name of the column containing the page content.\n              Defaults to \"text\".\n        \"\"\"\n        import polars as pl\n        if not isinstance(data_frame, pl.DataFrame):\n            raise ValueError(\n                f\"Expected data_frame to be a pl.DataFrame, got {type(data_frame)}\"\n            )\n        super().__init__(data_frame, page_content_column=page_content_column)\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazy load records from dataframe.\"\"\"\n        for row in self.data_frame.iter_rows(named=True):\n            text = row[self.page_content_column]\n            row.pop(self.page_content_column)\n            yield Document(page_content=text, metadata=row)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/polars_dataframe.html"}
{"id": "9e097fa7bb08-0", "text": "Source code for langchain.document_loaders.s3_directory\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, List, Optional, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.s3_file import S3FileLoader\nif TYPE_CHECKING:\n    import botocore\n[docs]class S3DirectoryLoader(BaseLoader):\n    \"\"\"Load from `Amazon AWS S3` directory.\"\"\"\n[docs]    def __init__(\n        self,\n        bucket: str,\n        prefix: str = \"\",\n        *,\n        region_name: Optional[str] = None,\n        api_version: Optional[str] = None,\n        use_ssl: Optional[bool] = True,\n        verify: Union[str, bool, None] = None,\n        endpoint_url: Optional[str] = None,\n        aws_access_key_id: Optional[str] = None,\n        aws_secret_access_key: Optional[str] = None,\n        aws_session_token: Optional[str] = None,\n        boto_config: Optional[botocore.client.Config] = None,\n    ):\n        \"\"\"Initialize with bucket and key name.\n        :param bucket: The name of the S3 bucket.\n        :param prefix: The prefix of the S3 key. Defaults to \"\".\n        :param region_name: The name of the region associated with the client.\n            A client is associated with a single region.\n        :param api_version: The API version to use.  By default, botocore will\n            use the latest API version when creating a client.  You only need\n            to specify this parameter if you want to use a previous API version\n            of the client.\n        :param use_ssl: Whether to use SSL.  By default, SSL is used.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_directory.html"}
{"id": "9e097fa7bb08-1", "text": ":param use_ssl: Whether to use SSL.  By default, SSL is used.\n            Note that not all services support non-ssl connections.\n        :param verify: Whether to verify SSL certificates.\n            By default SSL certificates are verified.  You can provide the\n            following values:\n            * False - do not validate SSL certificates.  SSL will still be\n              used (unless use_ssl is False), but SSL certificates\n              will not be verified.\n            * path/to/cert/bundle.pem - A filename of the CA cert bundle to\n              uses.  You can specify this argument if you want to use a\n              different CA cert bundle than the one used by botocore.\n        :param endpoint_url: The complete URL to use for the constructed\n            client.  Normally, botocore will automatically construct the\n            appropriate URL to use when communicating with a service.  You can\n            specify a complete URL (including the \"http/https\" scheme) to\n            override this behavior.  If this value is provided, then\n            ``use_ssl`` is ignored.\n        :param aws_access_key_id: The access key to use when creating\n            the client.  This is entirely optional, and if not provided,\n            the credentials configured for the session will automatically\n            be used.  You only need to provide this argument if you want\n            to override the credentials used for this specific client.\n        :param aws_secret_access_key: The secret key to use when creating\n            the client.  Same semantics as aws_access_key_id above.\n        :param aws_session_token: The session token to use when creating\n            the client.  Same semantics as aws_access_key_id above.\n        :type boto_config: botocore.client.Config\n        :param boto_config: Advanced boto3 client configuration options. If a value", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_directory.html"}
{"id": "9e097fa7bb08-2", "text": ":param boto_config: Advanced boto3 client configuration options. If a value\n            is specified in the client config, its value will take precedence\n            over environment variables and configuration values, but not over\n            a value passed explicitly to the method. If a default config\n            object is set on the session, the config object used when creating\n            the client will be the result of calling ``merge()`` on the\n            default config with the config provided to this call.\n        \"\"\"\n        self.bucket = bucket\n        self.prefix = prefix\n        self.region_name = region_name\n        self.api_version = api_version\n        self.use_ssl = use_ssl\n        self.verify = verify\n        self.endpoint_url = endpoint_url\n        self.aws_access_key_id = aws_access_key_id\n        self.aws_secret_access_key = aws_secret_access_key\n        self.aws_session_token = aws_session_token\n        self.boto_config = boto_config\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        try:\n            import boto3\n        except ImportError:\n            raise ImportError(\n                \"Could not import boto3 python package. \"\n                \"Please install it with `pip install boto3`.\"\n            )\n        s3 = boto3.resource(\n            \"s3\",\n            region_name=self.region_name,\n            api_version=self.api_version,\n            use_ssl=self.use_ssl,\n            verify=self.verify,\n            endpoint_url=self.endpoint_url,\n            aws_access_key_id=self.aws_access_key_id,\n            aws_secret_access_key=self.aws_secret_access_key,\n            aws_session_token=self.aws_session_token,\n            config=self.boto_config,\n        )\n        bucket = s3.Bucket(self.bucket)\n        docs = []\n        for obj in bucket.objects.filter(Prefix=self.prefix):\n            loader = S3FileLoader(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_directory.html"}
{"id": "9e097fa7bb08-3", "text": "loader = S3FileLoader(\n                self.bucket,\n                obj.key,\n                region_name=self.region_name,\n                api_version=self.api_version,\n                use_ssl=self.use_ssl,\n                verify=self.verify,\n                endpoint_url=self.endpoint_url,\n                aws_access_key_id=self.aws_access_key_id,\n                aws_secret_access_key=self.aws_secret_access_key,\n                aws_session_token=self.aws_session_token,\n                boto_config=self.boto_config,\n            )\n            docs.extend(loader.load())\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_directory.html"}
{"id": "3965a52164db-0", "text": "Source code for langchain.document_loaders.pdf\nimport json\nimport logging\nimport os\nimport tempfile\nimport time\nfrom abc import ABC\nfrom io import StringIO\nfrom pathlib import Path\nfrom typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Union\nfrom urllib.parse import urlparse\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.blob_loaders import Blob\nfrom langchain.document_loaders.parsers.pdf import (\n    AmazonTextractPDFParser,\n    DocumentIntelligenceParser,\n    PDFMinerParser,\n    PDFPlumberParser,\n    PyMuPDFParser,\n    PyPDFium2Parser,\n    PyPDFParser,\n)\nfrom langchain.document_loaders.unstructured import UnstructuredFileLoader\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__file__)\n[docs]class UnstructuredPDFLoader(UnstructuredFileLoader):\n    \"\"\"Load `PDF` files using `Unstructured`.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredPDFLoader\n    loader = UnstructuredPDFLoader(\n        \"example.pdf\", mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition-pdf\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-1", "text": "\"\"\"\n    def _get_elements(self) -> List:\n        from unstructured.partition.pdf import partition_pdf\n        return partition_pdf(filename=self.file_path, **self.unstructured_kwargs)\n[docs]class BasePDFLoader(BaseLoader, ABC):\n    \"\"\"Base Loader class for `PDF` files.\n    If the file is a web path, it will download it to a temporary file, use it, then\n        clean up the temporary file after completion.\n    \"\"\"\n[docs]    def __init__(self, file_path: str, *, headers: Optional[Dict] = None):\n        \"\"\"Initialize with a file path.\n        Args:\n            file_path: Either a local, S3 or web path to a PDF file.\n            headers: Headers to use for GET request to download a file from a web path.\n        \"\"\"\n        self.file_path = file_path\n        self.web_path = None\n        self.headers = headers\n        if \"~\" in self.file_path:\n            self.file_path = os.path.expanduser(self.file_path)\n        # If the file is a web path or S3, download it to a temporary file, and use that\n        if not os.path.isfile(self.file_path) and self._is_valid_url(self.file_path):\n            self.temp_dir = tempfile.TemporaryDirectory()\n            _, suffix = os.path.splitext(self.file_path)\n            temp_pdf = os.path.join(self.temp_dir.name, f\"tmp{suffix}\")\n            self.web_path = self.file_path\n            if not self._is_s3_url(self.file_path):\n                r = requests.get(self.file_path, headers=self.headers)\n                if r.status_code != 200:\n                    raise ValueError(\n                        \"Check the url of your file; returned status code %s\"\n                        % r.status_code\n                    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-2", "text": "% r.status_code\n                    )\n                with open(temp_pdf, mode=\"wb\") as f:\n                    f.write(r.content)\n                self.file_path = str(temp_pdf)\n        elif not os.path.isfile(self.file_path):\n            raise ValueError(\"File path %s is not a valid file or url\" % self.file_path)\n    def __del__(self) -> None:\n        if hasattr(self, \"temp_dir\"):\n            self.temp_dir.cleanup()\n    @staticmethod\n    def _is_valid_url(url: str) -> bool:\n        \"\"\"Check if the url is valid.\"\"\"\n        parsed = urlparse(url)\n        return bool(parsed.netloc) and bool(parsed.scheme)\n    @staticmethod\n    def _is_s3_url(url: str) -> bool:\n        \"\"\"check if the url is S3\"\"\"\n        try:\n            result = urlparse(url)\n            if result.scheme == \"s3\" and result.netloc:\n                return True\n            return False\n        except ValueError:\n            return False\n    @property\n    def source(self) -> str:\n        return self.web_path if self.web_path is not None else self.file_path\n[docs]class OnlinePDFLoader(BasePDFLoader):\n    \"\"\"Load online `PDF`.\"\"\"\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        loader = UnstructuredPDFLoader(str(self.file_path))\n        return loader.load()\n[docs]class PyPDFLoader(BasePDFLoader):\n    \"\"\"Load PDF using pypdf into list of documents.\n    Loader chunks by page and stores page numbers in metadata.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        password: Optional[Union[str, bytes]] = None,\n        headers: Optional[Dict] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-3", "text": "headers: Optional[Dict] = None,\n        extract_images: bool = False,\n    ) -> None:\n        \"\"\"Initialize with a file path.\"\"\"\n        try:\n            import pypdf  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"pypdf package not found, please install it with \" \"`pip install pypdf`\"\n            )\n        super().__init__(file_path, headers=headers)\n        self.parser = PyPDFParser(password=password, extract_images=extract_images)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load given path as pages.\"\"\"\n        return list(self.lazy_load())\n[docs]    def lazy_load(\n        self,\n    ) -> Iterator[Document]:\n        \"\"\"Lazy load given path as pages.\"\"\"\n        if self.web_path:\n            blob = Blob.from_data(open(self.file_path, \"rb\").read(), path=self.web_path)\n        else:\n            blob = Blob.from_path(self.file_path)\n        yield from self.parser.parse(blob)\n[docs]class PyPDFium2Loader(BasePDFLoader):\n    \"\"\"Load `PDF` using `pypdfium2` and chunks at character level.\"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        *,\n        headers: Optional[Dict] = None,\n        extract_images: bool = False,\n    ):\n        \"\"\"Initialize with a file path.\"\"\"\n        super().__init__(file_path, headers=headers)\n        self.parser = PyPDFium2Parser(extract_images=extract_images)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load given path as pages.\"\"\"\n        return list(self.lazy_load())\n[docs]    def lazy_load(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-4", "text": "[docs]    def lazy_load(\n        self,\n    ) -> Iterator[Document]:\n        \"\"\"Lazy load given path as pages.\"\"\"\n        blob = Blob.from_path(self.file_path)\n        yield from self.parser.parse(blob)\n[docs]class PyPDFDirectoryLoader(BaseLoader):\n    \"\"\"Load a directory with `PDF` files using `pypdf` and chunks at character level.\n    Loader also stores page numbers in metadata.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        path: str,\n        glob: str = \"**/[!.]*.pdf\",\n        silent_errors: bool = False,\n        load_hidden: bool = False,\n        recursive: bool = False,\n        extract_images: bool = False,\n    ):\n        self.path = path\n        self.glob = glob\n        self.load_hidden = load_hidden\n        self.recursive = recursive\n        self.silent_errors = silent_errors\n        self.extract_images = extract_images\n    @staticmethod\n    def _is_visible(path: Path) -> bool:\n        return not any(part.startswith(\".\") for part in path.parts)\n[docs]    def load(self) -> List[Document]:\n        p = Path(self.path)\n        docs = []\n        items = p.rglob(self.glob) if self.recursive else p.glob(self.glob)\n        for i in items:\n            if i.is_file():\n                if self._is_visible(i.relative_to(p)) or self.load_hidden:\n                    try:\n                        loader = PyPDFLoader(str(i), extract_images=self.extract_images)\n                        sub_docs = loader.load()\n                        for doc in sub_docs:\n                            doc.metadata[\"source\"] = str(i)\n                        docs.extend(sub_docs)\n                    except Exception as e:\n                        if self.silent_errors:\n                            logger.warning(e)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-5", "text": "if self.silent_errors:\n                            logger.warning(e)\n                        else:\n                            raise e\n        return docs\n[docs]class PDFMinerLoader(BasePDFLoader):\n    \"\"\"Load `PDF` files using `PDFMiner`.\"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        *,\n        headers: Optional[Dict] = None,\n        extract_images: bool = False,\n        concatenate_pages: bool = True,\n    ) -> None:\n        \"\"\"Initialize with file path.\n        Args:\n            extract_images: Whether to extract images from PDF.\n            concatenate_pages: If True, concatenate all PDF pages into one a single\n                               document. Otherwise, return one document per page.\n        \"\"\"\n        try:\n            from pdfminer.high_level import extract_text  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"`pdfminer` package not found, please install it with \"\n                \"`pip install pdfminer.six`\"\n            )\n        super().__init__(file_path, headers=headers)\n        self.parser = PDFMinerParser(\n            extract_images=extract_images, concatenate_pages=concatenate_pages\n        )\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Eagerly load the content.\"\"\"\n        return list(self.lazy_load())\n[docs]    def lazy_load(\n        self,\n    ) -> Iterator[Document]:\n        \"\"\"Lazily load documents.\"\"\"\n        blob = Blob.from_path(self.file_path)\n        yield from self.parser.parse(blob)\n[docs]class PDFMinerPDFasHTMLLoader(BasePDFLoader):\n    \"\"\"Load `PDF` files as HTML content using `PDFMiner`.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-6", "text": "\"\"\"Load `PDF` files as HTML content using `PDFMiner`.\"\"\"\n[docs]    def __init__(self, file_path: str, *, headers: Optional[Dict] = None):\n        \"\"\"Initialize with a file path.\"\"\"\n        try:\n            from pdfminer.high_level import extract_text_to_fp  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"`pdfminer` package not found, please install it with \"\n                \"`pip install pdfminer.six`\"\n            )\n        super().__init__(file_path, headers=headers)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load file.\"\"\"\n        from pdfminer.high_level import extract_text_to_fp\n        from pdfminer.layout import LAParams\n        from pdfminer.utils import open_filename\n        output_string = StringIO()\n        with open_filename(self.file_path, \"rb\") as fp:\n            extract_text_to_fp(\n                fp,  # type: ignore[arg-type]\n                output_string,\n                codec=\"\",\n                laparams=LAParams(),\n                output_type=\"html\",\n            )\n        metadata = {\"source\": self.file_path}\n        return [Document(page_content=output_string.getvalue(), metadata=metadata)]\n[docs]class PyMuPDFLoader(BasePDFLoader):\n    \"\"\"Load `PDF` files using `PyMuPDF`.\"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        *,\n        headers: Optional[Dict] = None,\n        extract_images: bool = False,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Initialize with a file path.\"\"\"\n        try:\n            import fitz  # noqa:F401\n        except ImportError:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-7", "text": "import fitz  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"`PyMuPDF` package not found, please install it with \"\n                \"`pip install pymupdf`\"\n            )\n        super().__init__(file_path, headers=headers)\n        self.extract_images = extract_images\n        self.text_kwargs = kwargs\n[docs]    def load(self, **kwargs: Any) -> List[Document]:\n        \"\"\"Load file.\"\"\"\n        if kwargs:\n            logger.warning(\n                f\"Received runtime arguments {kwargs}. Passing runtime args to `load`\"\n                f\" is deprecated. Please pass arguments during initialization instead.\"\n            )\n        text_kwargs = {**self.text_kwargs, **kwargs}\n        parser = PyMuPDFParser(\n            text_kwargs=text_kwargs, extract_images=self.extract_images\n        )\n        blob = Blob.from_path(self.file_path)\n        return parser.parse(blob)\n# MathpixPDFLoader implementation taken largely from Daniel Gross's:\n# https://gist.github.com/danielgross/3ab4104e14faccc12b49200843adab21\n[docs]class MathpixPDFLoader(BasePDFLoader):\n    \"\"\"Load `PDF` files using `Mathpix` service.\"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        processed_file_format: str = \"md\",\n        max_wait_time_seconds: int = 500,\n        should_clean_pdf: bool = False,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Initialize with a file path.\n        Args:\n            file_path: a file for loading.\n            processed_file_format: a format of the processed file. Default is \"md\".\n            max_wait_time_seconds: a maximum time to wait for the response from", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-8", "text": "max_wait_time_seconds: a maximum time to wait for the response from\n             the server. Default is 500.\n            should_clean_pdf: a flag to clean the PDF file. Default is False.\n            **kwargs: additional keyword arguments.\n        \"\"\"\n        self.mathpix_api_key = get_from_dict_or_env(\n            kwargs, \"mathpix_api_key\", \"MATHPIX_API_KEY\"\n        )\n        self.mathpix_api_id = get_from_dict_or_env(\n            kwargs, \"mathpix_api_id\", \"MATHPIX_API_ID\"\n        )\n        super().__init__(file_path, **kwargs)\n        self.processed_file_format = processed_file_format\n        self.max_wait_time_seconds = max_wait_time_seconds\n        self.should_clean_pdf = should_clean_pdf\n    @property\n    def _mathpix_headers(self) -> Dict[str, str]:\n        return {\"app_id\": self.mathpix_api_id, \"app_key\": self.mathpix_api_key}\n    @property\n    def url(self) -> str:\n        return \"https://api.mathpix.com/v3/pdf\"\n    @property\n    def data(self) -> dict:\n        options = {\"conversion_formats\": {self.processed_file_format: True}}\n        return {\"options_json\": json.dumps(options)}\n[docs]    def send_pdf(self) -> str:\n        with open(self.file_path, \"rb\") as f:\n            files = {\"file\": f}\n            response = requests.post(\n                self.url, headers=self._mathpix_headers, files=files, data=self.data\n            )\n        response_data = response.json()\n        if \"pdf_id\" in response_data:\n            pdf_id = response_data[\"pdf_id\"]\n            return pdf_id\n        else:\n            raise ValueError(\"Unable to send PDF to Mathpix.\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-9", "text": "else:\n            raise ValueError(\"Unable to send PDF to Mathpix.\")\n[docs]    def wait_for_processing(self, pdf_id: str) -> None:\n        \"\"\"Wait for processing to complete.\n        Args:\n            pdf_id: a PDF id.\n        Returns: None\n        \"\"\"\n        url = self.url + \"/\" + pdf_id\n        for _ in range(0, self.max_wait_time_seconds, 5):\n            response = requests.get(url, headers=self.headers)\n            response_data = response.json()\n            status = response_data.get(\"status\", None)\n            if status == \"completed\":\n                return\n            elif status == \"error\":\n                raise ValueError(\"Unable to retrieve PDF from Mathpix\")\n            else:\n                print(f\"Status: {status}, waiting for processing to complete\")\n                time.sleep(5)\n        raise TimeoutError\n[docs]    def get_processed_pdf(self, pdf_id: str) -> str:\n        self.wait_for_processing(pdf_id)\n        url = f\"{self.url}/{pdf_id}.{self.processed_file_format}\"\n        response = requests.get(url, headers=self.headers)\n        return response.content.decode(\"utf-8\")\n[docs]    def clean_pdf(self, contents: str) -> str:\n        \"\"\"Clean the PDF file.\n        Args:\n            contents: a PDF file contents.\n        Returns:\n        \"\"\"\n        contents = \"\\n\".join(\n            [line for line in contents.split(\"\\n\") if not line.startswith(\"![]\")]\n        )\n        # replace \\section{Title} with # Title\n        contents = contents.replace(\"\\\\section{\", \"# \").replace(\"}\", \"\")\n        # replace the \"\\\" slash that Mathpix adds to escape $, %, (, etc.\n        contents = (\n            contents.replace(r\"\\$\", \"$\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-10", "text": "contents = (\n            contents.replace(r\"\\$\", \"$\")\n            .replace(r\"\\%\", \"%\")\n            .replace(r\"\\(\", \"(\")\n            .replace(r\"\\)\", \")\")\n        )\n        return contents\n[docs]    def load(self) -> List[Document]:\n        pdf_id = self.send_pdf()\n        contents = self.get_processed_pdf(pdf_id)\n        if self.should_clean_pdf:\n            contents = self.clean_pdf(contents)\n        metadata = {\"source\": self.source, \"file_path\": self.source}\n        return [Document(page_content=contents, metadata=metadata)]\n[docs]class PDFPlumberLoader(BasePDFLoader):\n    \"\"\"Load `PDF` files using `pdfplumber`.\"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        text_kwargs: Optional[Mapping[str, Any]] = None,\n        dedupe: bool = False,\n        headers: Optional[Dict] = None,\n        extract_images: bool = False,\n    ) -> None:\n        \"\"\"Initialize with a file path.\"\"\"\n        try:\n            import pdfplumber  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"pdfplumber package not found, please install it with \"\n                \"`pip install pdfplumber`\"\n            )\n        super().__init__(file_path, headers=headers)\n        self.text_kwargs = text_kwargs or {}\n        self.dedupe = dedupe\n        self.extract_images = extract_images\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load file.\"\"\"\n        parser = PDFPlumberParser(\n            text_kwargs=self.text_kwargs,\n            dedupe=self.dedupe,\n            extract_images=self.extract_images,\n        )\n        blob = Blob.from_path(self.file_path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-11", "text": ")\n        blob = Blob.from_path(self.file_path)\n        return parser.parse(blob)\n[docs]class AmazonTextractPDFLoader(BasePDFLoader):\n    \"\"\"Load `PDF` files from a local file system, HTTP or S3.\n    To authenticate, the AWS client uses the following methods to\n    automatically load credentials:\n    https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\n    If a specific credential profile should be used, you must pass\n    the name of the profile from the ~/.aws/credentials file that is to be used.\n    Make sure the credentials / roles used have the required policies to\n    access the Amazon Textract service.\n    Example:\n        .. code-block:: python\n            from langchain.document_loaders import AmazonTextractPDFLoader\n            loader = AmazonTextractPDFLoader(\n                file_path=\"s3://pdfs/myfile.pdf\"\n            )\n            document = loader.load()\n    \"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        textract_features: Optional[Sequence[str]] = None,\n        client: Optional[Any] = None,\n        credentials_profile_name: Optional[str] = None,\n        region_name: Optional[str] = None,\n        endpoint_url: Optional[str] = None,\n        headers: Optional[Dict] = None,\n    ) -> None:\n        \"\"\"Initialize the loader.\n        Args:\n            file_path: A file, url or s3 path for input file\n            textract_features: Features to be used for extraction, each feature\n                               should be passed as a str that conforms to the enum\n                               `Textract_Features`, see `amazon-textract-caller` pkg\n            client: boto3 textract client (Optional)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-12", "text": "client: boto3 textract client (Optional)\n            credentials_profile_name: AWS profile name, if not default (Optional)\n            region_name: AWS region, eg us-east-1 (Optional)\n            endpoint_url: endpoint url for the textract service (Optional)\n        \"\"\"\n        super().__init__(file_path, headers=headers)\n        try:\n            import textractcaller as tc  # noqa: F401\n        except ImportError:\n            raise ModuleNotFoundError(\n                \"Could not import amazon-textract-caller python package. \"\n                \"Please install it with `pip install amazon-textract-caller`.\"\n            )\n        if textract_features:\n            features = [tc.Textract_Features[x] for x in textract_features]\n        else:\n            features = []\n        if credentials_profile_name or region_name or endpoint_url:\n            try:\n                import boto3\n                if credentials_profile_name is not None:\n                    session = boto3.Session(profile_name=credentials_profile_name)\n                else:\n                    # use default credentials\n                    session = boto3.Session()\n                client_params = {}\n                if region_name:\n                    client_params[\"region_name\"] = region_name\n                if endpoint_url:\n                    client_params[\"endpoint_url\"] = endpoint_url\n                client = session.client(\"textract\", **client_params)\n            except ImportError:\n                raise ModuleNotFoundError(\n                    \"Could not import boto3 python package. \"\n                    \"Please install it with `pip install boto3`.\"\n                )\n            except Exception as e:\n                raise ValueError(\n                    \"Could not load credentials to authenticate with AWS client. \"\n                    \"Please check that credentials in the specified \"\n                    \"profile name are valid.\"\n                ) from e", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-13", "text": "\"profile name are valid.\"\n                ) from e\n        self.parser = AmazonTextractPDFParser(textract_features=features, client=client)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load given path as pages.\"\"\"\n        return list(self.lazy_load())\n[docs]    def lazy_load(\n        self,\n    ) -> Iterator[Document]:\n        \"\"\"Lazy load documents\"\"\"\n        # the self.file_path is local, but the blob has to include\n        # the S3 location if the file originated from S3 for multi-page documents\n        # raises ValueError when multi-page and not on S3\"\"\"\n        if self.web_path and self._is_s3_url(self.web_path):\n            blob = Blob(path=self.web_path)\n        else:\n            blob = Blob.from_path(self.file_path)\n            if AmazonTextractPDFLoader._get_number_of_pages(blob) > 1:\n                raise ValueError(\n                    f\"the file {blob.path} is a multi-page document, \\\n                    but not stored on S3. \\\n                    Textract requires multi-page documents to be on S3.\"\n                )\n        yield from self.parser.parse(blob)\n    @staticmethod\n    def _get_number_of_pages(blob: Blob) -> int:\n        try:\n            import pypdf\n            from PIL import Image, ImageSequence\n        except ImportError:\n            raise ModuleNotFoundError(\n                \"Could not import pypdf or Pilloe python package. \"\n                \"Please install it with `pip install pypdf Pillow`.\"\n            )\n        if blob.mimetype == \"application/pdf\":\n            with blob.as_bytes_io() as input_pdf_file:\n                pdf_reader = pypdf.PdfReader(input_pdf_file)\n                return len(pdf_reader.pages)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-14", "text": "return len(pdf_reader.pages)\n        elif blob.mimetype == \"image/tiff\":\n            num_pages = 0\n            img = Image.open(blob.as_bytes())\n            for _, _ in enumerate(ImageSequence.Iterator(img)):\n                num_pages += 1\n            return num_pages\n        elif blob.mimetype in [\"image/png\", \"image/jpeg\"]:\n            return 1\n        else:\n            raise ValueError(f\"unsupported mime type: {blob.mimetype}\")\n[docs]class DocumentIntelligenceLoader(BasePDFLoader):\n    \"\"\"Loads a PDF with Azure Document Intelligence\"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        client: Any,\n        model: str = \"prebuilt-document\",\n        headers: Optional[Dict] = None,\n    ) -> None:\n        \"\"\"\n        Initialize the object for file processing with Azure Document Intelligence\n        (formerly Form Recognizer).\n        This constructor initializes a DocumentIntelligenceParser object to be used\n        for parsing files using the Azure Document Intelligence API. The load method\n        generates a Document node including metadata (source blob and page number)\n        for each page.\n        Parameters:\n        -----------\n        file_path : str\n            The path to the file that needs to be parsed.\n        client: Any\n            A DocumentAnalysisClient to perform the analysis of the blob\n        model : str\n            The model name or ID to be used for form recognition in Azure.\n        Examples:\n        ---------\n        >>> obj = DocumentIntelligenceLoader(\n        ...     file_path=\"path/to/file\",\n        ...     client=client,\n        ...     model=\"prebuilt-document\"\n        ... )\n        \"\"\"\n        self.parser = DocumentIntelligenceParser(client=client, model=model)\n        super().__init__(file_path, headers=headers)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "3965a52164db-15", "text": "super().__init__(file_path, headers=headers)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load given path as pages.\"\"\"\n        return list(self.lazy_load())\n[docs]    def lazy_load(\n        self,\n    ) -> Iterator[Document]:\n        \"\"\"Lazy load given path as pages.\"\"\"\n        blob = Blob.from_path(self.file_path)\n        yield from self.parser.parse(blob)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html"}
{"id": "da288d02fe82-0", "text": "Source code for langchain.document_loaders.pyspark_dataframe\nimport itertools\nimport logging\nimport sys\nfrom typing import TYPE_CHECKING, Any, Iterator, List, Optional, Tuple\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__file__)\nif TYPE_CHECKING:\n    from pyspark.sql import SparkSession\n[docs]class PySparkDataFrameLoader(BaseLoader):\n    \"\"\"Load `PySpark` DataFrames.\"\"\"\n[docs]    def __init__(\n        self,\n        spark_session: Optional[\"SparkSession\"] = None,\n        df: Optional[Any] = None,\n        page_content_column: str = \"text\",\n        fraction_of_memory: float = 0.1,\n    ):\n        \"\"\"Initialize with a Spark DataFrame object.\n        Args:\n            spark_session: The SparkSession object.\n            df: The Spark DataFrame object.\n            page_content_column: The name of the column containing the page content.\n             Defaults to \"text\".\n            fraction_of_memory: The fraction of memory to use. Defaults to 0.1.\n        \"\"\"\n        try:\n            from pyspark.sql import DataFrame, SparkSession\n        except ImportError:\n            raise ImportError(\n                \"pyspark is not installed. \"\n                \"Please install it with `pip install pyspark`\"\n            )\n        self.spark = (\n            spark_session if spark_session else SparkSession.builder.getOrCreate()\n        )\n        if not isinstance(df, DataFrame):\n            raise ValueError(\n                f\"Expected data_frame to be a PySpark DataFrame, got {type(df)}\"\n            )\n        self.df = df\n        self.page_content_column = page_content_column\n        self.fraction_of_memory = fraction_of_memory", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pyspark_dataframe.html"}
{"id": "da288d02fe82-1", "text": "self.fraction_of_memory = fraction_of_memory\n        self.num_rows, self.max_num_rows = self.get_num_rows()\n        self.rdd_df = self.df.rdd.map(list)\n        self.column_names = self.df.columns\n[docs]    def get_num_rows(self) -> Tuple[int, int]:\n        \"\"\"Gets the number of \"feasible\" rows for the DataFrame\"\"\"\n        try:\n            import psutil\n        except ImportError as e:\n            raise ImportError(\n                \"psutil not installed. Please install it with `pip install psutil`.\"\n            ) from e\n        row = self.df.limit(1).collect()[0]\n        estimated_row_size = sys.getsizeof(row)\n        mem_info = psutil.virtual_memory()\n        available_memory = mem_info.available\n        max_num_rows = int(\n            (available_memory / estimated_row_size) * self.fraction_of_memory\n        )\n        return min(max_num_rows, self.df.count()), max_num_rows\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"A lazy loader for document content.\"\"\"\n        for row in self.rdd_df.toLocalIterator():\n            metadata = {self.column_names[i]: row[i] for i in range(len(row))}\n            text = metadata[self.page_content_column]\n            metadata.pop(self.page_content_column)\n            yield Document(page_content=text, metadata=metadata)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load from the dataframe.\"\"\"\n        if self.df.count() > self.max_num_rows:\n            logger.warning(\n                f\"The number of DataFrame rows is {self.df.count()}, \"\n                f\"but we will only include the amount \"\n                f\"of rows that can reasonably fit in memory: {self.num_rows}.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pyspark_dataframe.html"}
{"id": "da288d02fe82-2", "text": ")\n        lazy_load_iterator = self.lazy_load()\n        return list(itertools.islice(lazy_load_iterator, self.num_rows))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pyspark_dataframe.html"}
{"id": "2da9269efb14-0", "text": "Source code for langchain.document_loaders.twitter\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nif TYPE_CHECKING:\n    import tweepy\n    from tweepy import OAuth2BearerHandler, OAuthHandler\ndef _dependable_tweepy_import() -> tweepy:\n    try:\n        import tweepy\n    except ImportError:\n        raise ImportError(\n            \"tweepy package not found, please install it with `pip install tweepy`\"\n        )\n    return tweepy\n[docs]class TwitterTweetLoader(BaseLoader):\n    \"\"\"Load `Twitter` tweets.\n    Read tweets of the user's Twitter handle.\n    First you need to go to\n    `https://developer.twitter.com/en/docs/twitter-api\n    /getting-started/getting-access-to-the-twitter-api`\n    to get your token. And create a v2 version of the app.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        auth_handler: Union[OAuthHandler, OAuth2BearerHandler],\n        twitter_users: Sequence[str],\n        number_tweets: Optional[int] = 100,\n    ):\n        self.auth = auth_handler\n        self.twitter_users = twitter_users\n        self.number_tweets = number_tweets\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load tweets.\"\"\"\n        tweepy = _dependable_tweepy_import()\n        api = tweepy.API(self.auth, parser=tweepy.parsers.JSONParser())\n        results: List[Document] = []\n        for username in self.twitter_users:\n            tweets = api.user_timeline(screen_name=username, count=self.number_tweets)\n            user = api.get_user(screen_name=username)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html"}
{"id": "2da9269efb14-1", "text": "user = api.get_user(screen_name=username)\n            docs = self._format_tweets(tweets, user)\n            results.extend(docs)\n        return results\n    def _format_tweets(\n        self, tweets: List[Dict[str, Any]], user_info: dict\n    ) -> Iterable[Document]:\n        \"\"\"Format tweets into a string.\"\"\"\n        for tweet in tweets:\n            metadata = {\n                \"created_at\": tweet[\"created_at\"],\n                \"user_info\": user_info,\n            }\n            yield Document(\n                page_content=tweet[\"text\"],\n                metadata=metadata,\n            )\n[docs]    @classmethod\n    def from_bearer_token(\n        cls,\n        oauth2_bearer_token: str,\n        twitter_users: Sequence[str],\n        number_tweets: Optional[int] = 100,\n    ) -> TwitterTweetLoader:\n        \"\"\"Create a TwitterTweetLoader from OAuth2 bearer token.\"\"\"\n        tweepy = _dependable_tweepy_import()\n        auth = tweepy.OAuth2BearerHandler(oauth2_bearer_token)\n        return cls(\n            auth_handler=auth,\n            twitter_users=twitter_users,\n            number_tweets=number_tweets,\n        )\n[docs]    @classmethod\n    def from_secrets(\n        cls,\n        access_token: str,\n        access_token_secret: str,\n        consumer_key: str,\n        consumer_secret: str,\n        twitter_users: Sequence[str],\n        number_tweets: Optional[int] = 100,\n    ) -> TwitterTweetLoader:\n        \"\"\"Create a TwitterTweetLoader from access tokens and secrets.\"\"\"\n        tweepy = _dependable_tweepy_import()\n        auth = tweepy.OAuthHandler(\n            access_token=access_token,\n            access_token_secret=access_token_secret,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html"}
{"id": "2da9269efb14-2", "text": "access_token=access_token,\n            access_token_secret=access_token_secret,\n            consumer_key=consumer_key,\n            consumer_secret=consumer_secret,\n        )\n        return cls(\n            auth_handler=auth,\n            twitter_users=twitter_users,\n            number_tweets=number_tweets,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html"}
{"id": "637e1dcce1f0-0", "text": "Source code for langchain.document_loaders.stripe\nimport json\nimport urllib.request\nfrom typing import List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utils import get_from_env, stringify_dict\nSTRIPE_ENDPOINTS = {\n    \"balance_transactions\": \"https://api.stripe.com/v1/balance_transactions\",\n    \"charges\": \"https://api.stripe.com/v1/charges\",\n    \"customers\": \"https://api.stripe.com/v1/customers\",\n    \"events\": \"https://api.stripe.com/v1/events\",\n    \"refunds\": \"https://api.stripe.com/v1/refunds\",\n    \"disputes\": \"https://api.stripe.com/v1/disputes\",\n}\n[docs]class StripeLoader(BaseLoader):\n    \"\"\"Load from `Stripe` API.\"\"\"\n[docs]    def __init__(self, resource: str, access_token: Optional[str] = None) -> None:\n        \"\"\"Initialize with a resource and an access token.\n        Args:\n            resource: The resource.\n            access_token: The access token.\n        \"\"\"\n        self.resource = resource\n        access_token = access_token or get_from_env(\n            \"access_token\", \"STRIPE_ACCESS_TOKEN\"\n        )\n        self.headers = {\"Authorization\": f\"Bearer {access_token}\"}\n    def _make_request(self, url: str) -> List[Document]:\n        request = urllib.request.Request(url, headers=self.headers)\n        with urllib.request.urlopen(request) as response:\n            json_data = json.loads(response.read().decode())\n            text = stringify_dict(json_data)\n            metadata = {\"source\": url}\n            return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/stripe.html"}
{"id": "637e1dcce1f0-1", "text": "return [Document(page_content=text, metadata=metadata)]\n    def _get_resource(self) -> List[Document]:\n        endpoint = STRIPE_ENDPOINTS.get(self.resource)\n        if endpoint is None:\n            return []\n        return self._make_request(endpoint)\n[docs]    def load(self) -> List[Document]:\n        return self._get_resource()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/stripe.html"}
{"id": "6456ba9ec622-0", "text": "Source code for langchain.document_loaders.nuclia\nimport json\nimport uuid\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.tools.nuclia.tool import NucliaUnderstandingAPI\n[docs]class NucliaLoader(BaseLoader):\n    \"\"\"Load from any file type using `Nuclia Understanding API`.\"\"\"\n[docs]    def __init__(self, path: str, nuclia_tool: NucliaUnderstandingAPI):\n        self.nua = nuclia_tool\n        self.id = str(uuid.uuid4())\n        self.nua.run({\"action\": \"push\", \"id\": self.id, \"path\": path, \"text\": None})\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        data = self.nua.run(\n            {\"action\": \"pull\", \"id\": self.id, \"path\": None, \"text\": None}\n        )\n        if not data:\n            return []\n        obj = json.loads(data)\n        text = obj[\"extracted_text\"][0][\"body\"][\"text\"]\n        print(text)\n        metadata = {\n            \"file\": obj[\"file_extracted_data\"][0],\n            \"metadata\": obj[\"field_metadata\"][0],\n        }\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/nuclia.html"}
{"id": "2bdf10e02ce0-0", "text": "Source code for langchain.document_loaders.max_compute\nfrom __future__ import annotations\nfrom typing import Any, Iterator, List, Optional, Sequence\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utilities.max_compute import MaxComputeAPIWrapper\n[docs]class MaxComputeLoader(BaseLoader):\n    \"\"\"Load from `Alibaba Cloud MaxCompute` table.\"\"\"\n[docs]    def __init__(\n        self,\n        query: str,\n        api_wrapper: MaxComputeAPIWrapper,\n        *,\n        page_content_columns: Optional[Sequence[str]] = None,\n        metadata_columns: Optional[Sequence[str]] = None,\n    ):\n        \"\"\"Initialize Alibaba Cloud MaxCompute document loader.\n        Args:\n            query: SQL query to execute.\n            api_wrapper: MaxCompute API wrapper.\n            page_content_columns: The columns to write into the `page_content` of the\n                Document. If unspecified, all columns will be written to `page_content`.\n            metadata_columns: The columns to write into the `metadata` of the Document.\n                If unspecified, all columns not added to `page_content` will be written.\n        \"\"\"\n        self.query = query\n        self.api_wrapper = api_wrapper\n        self.page_content_columns = page_content_columns\n        self.metadata_columns = metadata_columns\n[docs]    @classmethod\n    def from_params(\n        cls,\n        query: str,\n        endpoint: str,\n        project: str,\n        *,\n        access_id: Optional[str] = None,\n        secret_access_key: Optional[str] = None,\n        **kwargs: Any,\n    ) -> MaxComputeLoader:\n        \"\"\"Convenience constructor that builds the MaxCompute API wrapper from\n            given parameters.\n        Args:\n            query: SQL query to execute.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/max_compute.html"}
{"id": "2bdf10e02ce0-1", "text": "given parameters.\n        Args:\n            query: SQL query to execute.\n            endpoint: MaxCompute endpoint.\n            project: A project is a basic organizational unit of MaxCompute, which is\n                similar to a database.\n            access_id: MaxCompute access ID. Should be passed in directly or set as the\n                environment variable `MAX_COMPUTE_ACCESS_ID`.\n            secret_access_key: MaxCompute secret access key. Should be passed in\n                directly or set as the environment variable\n                `MAX_COMPUTE_SECRET_ACCESS_KEY`.\n        \"\"\"\n        api_wrapper = MaxComputeAPIWrapper.from_params(\n            endpoint, project, access_id=access_id, secret_access_key=secret_access_key\n        )\n        return cls(query, api_wrapper, **kwargs)\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        for row in self.api_wrapper.query(self.query):\n            if self.page_content_columns:\n                page_content_data = {\n                    k: v for k, v in row.items() if k in self.page_content_columns\n                }\n            else:\n                page_content_data = row\n            page_content = \"\\n\".join(f\"{k}: {v}\" for k, v in page_content_data.items())\n            if self.metadata_columns:\n                metadata = {k: v for k, v in row.items() if k in self.metadata_columns}\n            else:\n                metadata = {k: v for k, v in row.items() if k not in page_content_data}\n            yield Document(page_content=page_content, metadata=metadata)\n[docs]    def load(self) -> List[Document]:\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/max_compute.html"}
{"id": "ac53874c34c4-0", "text": "Source code for langchain.document_loaders.python\nimport tokenize\nfrom langchain.document_loaders.text import TextLoader\n[docs]class PythonLoader(TextLoader):\n    \"\"\"Load `Python` files, respecting any non-default encoding if specified.\"\"\"\n[docs]    def __init__(self, file_path: str):\n        \"\"\"Initialize with a file path.\n        Args:\n            file_path: The path to the file to load.\n        \"\"\"\n        with open(file_path, \"rb\") as f:\n            encoding, _ = tokenize.detect_encoding(f.readline)\n        super().__init__(file_path=file_path, encoding=encoding)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/python.html"}
{"id": "d6215130611a-0", "text": "Source code for langchain.document_loaders.dropbox\n# Prerequisites:\n# 1. Create a Dropbox app.\n# 2. Give the app these scope permissions: `files.metadata.read`\n#    and `files.content.read`.\n# 3. Generate access token: https://www.dropbox.com/developers/apps/create.\n# 4. `pip install dropbox` (requires `pip install unstructured` for PDF filetype).\nimport os\nimport tempfile\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.pydantic_v1 import BaseModel, root_validator\n[docs]class DropboxLoader(BaseLoader, BaseModel):\n    \"\"\"Load files from `Dropbox`.\n    In addition to common files such as text and PDF files, it also supports\n    *Dropbox Paper* files.\n    \"\"\"\n    dropbox_access_token: str\n    \"\"\"Dropbox access token.\"\"\"\n    dropbox_folder_path: Optional[str] = None\n    \"\"\"The folder path to load from.\"\"\"\n    dropbox_file_paths: Optional[List[str]] = None\n    \"\"\"The file paths to load from.\"\"\"\n    recursive: bool = False\n    \"\"\"Flag to indicate whether to load files recursively from subfolders.\"\"\"\n    @root_validator\n    def validate_inputs(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Validate that either folder_path or file_paths is set, but not both.\"\"\"\n        if (\n            values.get(\"dropbox_folder_path\") is not None\n            and values.get(\"dropbox_file_paths\") is not None\n        ):\n            raise ValueError(\"Cannot specify both folder_path and file_paths\")\n        if values.get(\"dropbox_folder_path\") is None and not values.get(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/dropbox.html"}
{"id": "d6215130611a-1", "text": "if values.get(\"dropbox_folder_path\") is None and not values.get(\n            \"dropbox_file_paths\"\n        ):\n            raise ValueError(\"Must specify either folder_path or file_paths\")\n        return values\n    def _create_dropbox_client(self) -> Any:\n        \"\"\"Create a Dropbox client.\"\"\"\n        try:\n            from dropbox import Dropbox, exceptions\n        except ImportError:\n            raise ImportError(\"You must run \" \"`pip install dropbox\")\n        try:\n            dbx = Dropbox(self.dropbox_access_token)\n            dbx.users_get_current_account()\n        except exceptions.AuthError as ex:\n            raise ValueError(\n                \"Invalid Dropbox access token. Please verify your token and try again.\"\n            ) from ex\n        return dbx\n    def _load_documents_from_folder(self, folder_path: str) -> List[Document]:\n        \"\"\"Load documents from a Dropbox folder.\"\"\"\n        dbx = self._create_dropbox_client()\n        try:\n            from dropbox import exceptions\n            from dropbox.files import FileMetadata\n        except ImportError:\n            raise ImportError(\"You must run \" \"`pip install dropbox\")\n        try:\n            results = dbx.files_list_folder(folder_path, recursive=self.recursive)\n        except exceptions.ApiError as ex:\n            raise ValueError(\n                f\"Could not list files in the folder: {folder_path}. \"\n                \"Please verify the folder path and try again.\"\n            ) from ex\n        files = [entry for entry in results.entries if isinstance(entry, FileMetadata)]\n        documents = [\n            doc\n            for doc in (self._load_file_from_path(file.path_display) for file in files)\n            if doc is not None\n        ]\n        return documents\n    def _load_file_from_path(self, file_path: str) -> Optional[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/dropbox.html"}
{"id": "d6215130611a-2", "text": "def _load_file_from_path(self, file_path: str) -> Optional[Document]:\n        \"\"\"Load a file from a Dropbox path.\"\"\"\n        dbx = self._create_dropbox_client()\n        try:\n            from dropbox import exceptions\n        except ImportError:\n            raise ImportError(\"You must run \" \"`pip install dropbox\")\n        try:\n            file_metadata = dbx.files_get_metadata(file_path)\n            if file_metadata.is_downloadable:\n                _, response = dbx.files_download(file_path)\n            # Some types such as Paper, need to be exported.\n            elif file_metadata.export_info:\n                _, response = dbx.files_export(file_path, \"markdown\")\n        except exceptions.ApiError as ex:\n            raise ValueError(\n                f\"Could not load file: {file_path}. Please verify the file path\"\n                \"and try again.\"\n            ) from ex\n        try:\n            text = response.content.decode(\"utf-8\")\n        except UnicodeDecodeError:\n            print(f\"File {file_path} could not be decoded as text. Skipping.\")\n            file_extension = os.path.splitext(file_path)[1].lower()\n            if file_extension == \".pdf\":\n                from langchain.document_loaders import UnstructuredPDFLoader\n                # Download it to a temporary file.\n                temp_dir = tempfile.TemporaryDirectory()\n                temp_pdf = Path(temp_dir.name) / \"tmp.pdf\"\n                with open(temp_pdf, mode=\"wb\") as f:\n                    f.write(response.content)\n                try:\n                    loader = UnstructuredPDFLoader(str(temp_pdf))\n                    docs = loader.load()\n                    if docs:\n                        return docs[0]\n                except Exception as pdf_ex:\n                    print(f\"Error while trying to parse PDF {file_path}: {pdf_ex}\")\n                    return None\n            return None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/dropbox.html"}
{"id": "d6215130611a-3", "text": "return None\n            return None\n        metadata = {\n            \"source\": f\"dropbox://{file_path}\",\n            \"title\": os.path.basename(file_path),\n        }\n        return Document(page_content=text, metadata=metadata)\n    def _load_documents_from_paths(self) -> List[Document]:\n        \"\"\"Load documents from a list of Dropbox file paths.\"\"\"\n        if not self.dropbox_file_paths:\n            raise ValueError(\"file_paths must be set\")\n        return [\n            doc\n            for doc in (\n                self._load_file_from_path(file_path)\n                for file_path in self.dropbox_file_paths\n            )\n            if doc is not None\n        ]\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        if self.dropbox_folder_path is not None:\n            return self._load_documents_from_folder(self.dropbox_folder_path)\n        else:\n            return self._load_documents_from_paths()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/dropbox.html"}
{"id": "02c5dd8a026e-0", "text": "Source code for langchain.document_loaders.joplin\nimport json\nimport urllib\nfrom datetime import datetime\nfrom typing import Iterator, List, Optional\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.schema import Document\nfrom langchain.utils import get_from_env\nLINK_NOTE_TEMPLATE = \"joplin://x-callback-url/openNote?id={id}\"\n[docs]class JoplinLoader(BaseLoader):\n    \"\"\"Load notes from `Joplin`.\n    In order to use this loader, you need to have Joplin running with the\n    Web Clipper enabled (look for \"Web Clipper\" in the app settings).\n    To get the access token, you need to go to the Web Clipper options and\n    under \"Advanced Options\" you will find the access token.\n    You can find more information about the Web Clipper service here:\n    https://joplinapp.org/clipper/\n    \"\"\"\n[docs]    def __init__(\n        self,\n        access_token: Optional[str] = None,\n        port: int = 41184,\n        host: str = \"localhost\",\n    ) -> None:\n        \"\"\"\n        Args:\n            access_token: The access token to use.\n            port: The port where the Web Clipper service is running. Default is 41184.\n            host: The host where the Web Clipper service is running.\n                Default is localhost.\n        \"\"\"\n        access_token = access_token or get_from_env(\n            \"access_token\", \"JOPLIN_ACCESS_TOKEN\"\n        )\n        base_url = f\"http://{host}:{port}\"\n        self._get_note_url = (\n            f\"{base_url}/notes?token={access_token}\"\n            f\"&fields=id,parent_id,title,body,created_time,updated_time&page={{page}}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html"}
{"id": "02c5dd8a026e-1", "text": "f\"&fields=id,parent_id,title,body,created_time,updated_time&page={{page}}\"\n        )\n        self._get_folder_url = (\n            f\"{base_url}/folders/{{id}}?token={access_token}&fields=title\"\n        )\n        self._get_tag_url = (\n            f\"{base_url}/notes/{{id}}/tags?token={access_token}&fields=title\"\n        )\n    def _get_notes(self) -> Iterator[Document]:\n        has_more = True\n        page = 1\n        while has_more:\n            req_note = urllib.request.Request(self._get_note_url.format(page=page))\n            with urllib.request.urlopen(req_note) as response:\n                json_data = json.loads(response.read().decode())\n                for note in json_data[\"items\"]:\n                    metadata = {\n                        \"source\": LINK_NOTE_TEMPLATE.format(id=note[\"id\"]),\n                        \"folder\": self._get_folder(note[\"parent_id\"]),\n                        \"tags\": self._get_tags(note[\"id\"]),\n                        \"title\": note[\"title\"],\n                        \"created_time\": self._convert_date(note[\"created_time\"]),\n                        \"updated_time\": self._convert_date(note[\"updated_time\"]),\n                    }\n                    yield Document(page_content=note[\"body\"], metadata=metadata)\n                has_more = json_data[\"has_more\"]\n                page += 1\n    def _get_folder(self, folder_id: str) -> str:\n        req_folder = urllib.request.Request(self._get_folder_url.format(id=folder_id))\n        with urllib.request.urlopen(req_folder) as response:\n            json_data = json.loads(response.read().decode())\n            return json_data[\"title\"]\n    def _get_tags(self, note_id: str) -> List[str]:\n        req_tag = urllib.request.Request(self._get_tag_url.format(id=note_id))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html"}
{"id": "02c5dd8a026e-2", "text": "req_tag = urllib.request.Request(self._get_tag_url.format(id=note_id))\n        with urllib.request.urlopen(req_tag) as response:\n            json_data = json.loads(response.read().decode())\n            return [tag[\"title\"] for tag in json_data[\"items\"]]\n    def _convert_date(self, date: int) -> str:\n        return datetime.fromtimestamp(date / 1000).strftime(\"%Y-%m-%d %H:%M:%S\")\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        yield from self._get_notes()\n[docs]    def load(self) -> List[Document]:\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html"}
{"id": "e03e40406d87-0", "text": "Source code for langchain.document_loaders.airtable\nfrom typing import Iterator, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class AirtableLoader(BaseLoader):\n    \"\"\"Load the `Airtable` tables.\"\"\"\n[docs]    def __init__(self, api_token: str, table_id: str, base_id: str):\n        \"\"\"Initialize with API token and the IDs for table and base\"\"\"\n        self.api_token = api_token\n        \"\"\"Airtable API token.\"\"\"\n        self.table_id = table_id\n        \"\"\"Airtable table ID.\"\"\"\n        self.base_id = base_id\n        \"\"\"Airtable base ID.\"\"\"\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazy load Documents from table.\"\"\"\n        from pyairtable import Table\n        table = Table(self.api_token, self.base_id, self.table_id)\n        records = table.all()\n        for record in records:\n            # Need to convert record from dict to str\n            yield Document(\n                page_content=str(record),\n                metadata={\n                    \"source\": self.base_id + \"_\" + self.table_id,\n                    \"base_id\": self.base_id,\n                    \"table_id\": self.table_id,\n                },\n            )\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load Documents from table.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airtable.html"}
{"id": "a3c79c97b748-0", "text": "Source code for langchain.document_loaders.google_speech_to_text\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utilities.vertexai import get_client_info\nif TYPE_CHECKING:\n    from google.cloud.speech_v2 import RecognitionConfig\n    from google.protobuf.field_mask_pb2 import FieldMask\n[docs]class GoogleSpeechToTextLoader(BaseLoader):\n    \"\"\"\n    Loader for Google Cloud Speech-to-Text audio transcripts.\n    It uses the Google Cloud Speech-to-Text API to transcribe audio files\n    and loads the transcribed text into one or more Documents,\n    depending on the specified format.\n    To use, you should have the ``google-cloud-speech`` python package installed.\n    Audio files can be specified via a Google Cloud Storage uri or a local file path.\n    For a detailed explanation of Google Cloud Speech-to-Text, refer to the product\n    documentation.\n    https://cloud.google.com/speech-to-text\n    \"\"\"\n[docs]    def __init__(\n        self,\n        project_id: str,\n        file_path: str,\n        location: str = \"us-central1\",\n        recognizer_id: str = \"_\",\n        config: Optional[RecognitionConfig] = None,\n        config_mask: Optional[FieldMask] = None,\n    ):\n        \"\"\"\n        Initializes the GoogleSpeechToTextLoader.\n        Args:\n            project_id: Google Cloud Project ID.\n            file_path: A Google Cloud Storage URI or a local file path.\n            location: Speech-to-Text recognizer location.\n            recognizer_id: Speech-to-Text recognizer id.\n            config: Recognition options and features.\n                For more information:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/google_speech_to_text.html"}
{"id": "a3c79c97b748-1", "text": "config: Recognition options and features.\n                For more information:\n                https://cloud.google.com/python/docs/reference/speech/latest/google.cloud.speech_v2.types.RecognitionConfig\n            config_mask: The list of fields in config that override the values in the\n                ``default_recognition_config`` of the recognizer during this\n                recognition request.\n                For more information:\n                https://cloud.google.com/python/docs/reference/speech/latest/google.cloud.speech_v2.types.RecognizeRequest\n        \"\"\"\n        try:\n            from google.api_core.client_options import ClientOptions\n            from google.cloud.speech_v2 import (\n                AutoDetectDecodingConfig,\n                RecognitionConfig,\n                RecognitionFeatures,\n                SpeechClient,\n            )\n        except ImportError as exc:\n            raise ImportError(\n                \"Could not import google-cloud-speech python package. \"\n                \"Please install it with `pip install google-cloud-speech`.\"\n            ) from exc\n        self.project_id = project_id\n        self.file_path = file_path\n        self.location = location\n        self.recognizer_id = recognizer_id\n        # Config must be set in speech recognition request.\n        self.config = config or RecognitionConfig(\n            auto_decoding_config=AutoDetectDecodingConfig(),\n            language_codes=[\"en-US\"],\n            model=\"chirp\",\n            features=RecognitionFeatures(\n                # Automatic punctuation could be useful for language applications\n                enable_automatic_punctuation=True,\n            ),\n        )\n        self.config_mask = config_mask\n        self._client = SpeechClient(\n            client_info=get_client_info(module=\"speech-to-text\"),\n            client_options=(\n                ClientOptions(api_endpoint=f\"{location}-speech.googleapis.com\")\n                if location != \"global\"\n                else None\n            ),\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/google_speech_to_text.html"}
{"id": "a3c79c97b748-2", "text": "if location != \"global\"\n                else None\n            ),\n        )\n        self._recognizer_path = self._client.recognizer_path(\n            project_id, location, recognizer_id\n        )\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Transcribes the audio file and loads the transcript into documents.\n        It uses the Google Cloud Speech-to-Text API to transcribe the audio file\n        and blocks until the transcription is finished.\n        \"\"\"\n        try:\n            from google.cloud.speech_v2 import RecognizeRequest\n        except ImportError as exc:\n            raise ImportError(\n                \"Could not import google-cloud-speech python package. \"\n                \"Please install it with `pip install google-cloud-speech`.\"\n            ) from exc\n        request = RecognizeRequest(\n            recognizer=self._recognizer_path,\n            config=self.config,\n            config_mask=self.config_mask,\n        )\n        if \"gs://\" in self.file_path:\n            request.uri = self.file_path\n        else:\n            with open(self.file_path, \"rb\") as f:\n                request.content = f.read()\n        response = self._client.recognize(request=request)\n        return [\n            Document(\n                page_content=result.alternatives[0].transcript,\n                metadata={\n                    \"language_code\": result.language_code,\n                    \"result_end_offset\": result.result_end_offset,\n                },\n            )\n            for result in response.results\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/google_speech_to_text.html"}
{"id": "b45ecb0cdbde-0", "text": "Source code for langchain.document_loaders.tencent_cos_file\nimport os\nimport tempfile\nfrom typing import Any, Iterator, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.unstructured import UnstructuredFileLoader\n[docs]class TencentCOSFileLoader(BaseLoader):\n    \"\"\"Load from `Tencent Cloud COS` file.\"\"\"\n[docs]    def __init__(self, conf: Any, bucket: str, key: str):\n        \"\"\"Initialize with COS config, bucket and key name.\n        :param conf(CosConfig): COS config.\n        :param bucket(str): COS bucket.\n        :param key(str): COS file key.\n        \"\"\"\n        self.conf = conf\n        self.bucket = bucket\n        self.key = key\n[docs]    def load(self) -> List[Document]:\n        return list(self.lazy_load())\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Load documents.\"\"\"\n        try:\n            from qcloud_cos import CosS3Client\n        except ImportError:\n            raise ImportError(\n                \"Could not import cos-python-sdk-v5 python package. \"\n                \"Please install it with `pip install cos-python-sdk-v5`.\"\n            )\n        # Initialise a client\n        client = CosS3Client(self.conf)\n        with tempfile.TemporaryDirectory() as temp_dir:\n            file_path = f\"{temp_dir}/{self.bucket}/{self.key}\"\n            os.makedirs(os.path.dirname(file_path), exist_ok=True)\n            # Download the file to a destination\n            client.download_file(\n                Bucket=self.bucket, Key=self.key, DestFilePath=file_path\n            )\n            loader = UnstructuredFileLoader(file_path)\n            # UnstructuredFileLoader not implement lazy_load yet\n            return iter(loader.load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tencent_cos_file.html"}
{"id": "bf77dc9ab072-0", "text": "Source code for langchain.document_loaders.org_mode\nfrom typing import Any, List\nfrom langchain.document_loaders.unstructured import (\n    UnstructuredFileLoader,\n    validate_unstructured_version,\n)\n[docs]class UnstructuredOrgModeLoader(UnstructuredFileLoader):\n    \"\"\"Load `Org-Mode` files using `Unstructured`.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredOrgModeLoader\n    loader = UnstructuredOrgModeLoader(\n        \"example.org\", mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition-org\n    \"\"\"\n[docs]    def __init__(\n        self, file_path: str, mode: str = \"single\", **unstructured_kwargs: Any\n    ):\n        \"\"\"\n        Args:\n            file_path: The path to the file to load.\n            mode: The mode to load the file from. Default is \"single\".\n            **unstructured_kwargs: Any additional keyword arguments to pass\n                to the unstructured.\n        \"\"\"\n        validate_unstructured_version(min_unstructured_version=\"0.7.9\")\n        super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)\n    def _get_elements(self) -> List:\n        from unstructured.partition.org import partition_org", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/org_mode.html"}
{"id": "bf77dc9ab072-1", "text": "from unstructured.partition.org import partition_org\n        return partition_org(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/org_mode.html"}
{"id": "b81924e0cc2d-0", "text": "Source code for langchain.document_loaders.directory\nimport concurrent\nimport logging\nimport random\nfrom pathlib import Path\nfrom typing import Any, List, Optional, Type, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.html_bs import BSHTMLLoader\nfrom langchain.document_loaders.text import TextLoader\nfrom langchain.document_loaders.unstructured import UnstructuredFileLoader\nFILE_LOADER_TYPE = Union[\n    Type[UnstructuredFileLoader], Type[TextLoader], Type[BSHTMLLoader]\n]\nlogger = logging.getLogger(__name__)\ndef _is_visible(p: Path) -> bool:\n    parts = p.parts\n    for _p in parts:\n        if _p.startswith(\".\"):\n            return False\n    return True\n[docs]class DirectoryLoader(BaseLoader):\n    \"\"\"Load from a directory.\"\"\"\n[docs]    def __init__(\n        self,\n        path: str,\n        glob: str = \"**/[!.]*\",\n        silent_errors: bool = False,\n        load_hidden: bool = False,\n        loader_cls: FILE_LOADER_TYPE = UnstructuredFileLoader,\n        loader_kwargs: Union[dict, None] = None,\n        recursive: bool = False,\n        show_progress: bool = False,\n        use_multithreading: bool = False,\n        max_concurrency: int = 4,\n        *,\n        sample_size: int = 0,\n        randomize_sample: bool = False,\n        sample_seed: Union[int, None] = None,\n    ):\n        \"\"\"Initialize with a path to directory and how to glob over it.\n        Args:\n            path: Path to directory.\n            glob: Glob pattern to use to find files. Defaults to \"**/[!.]*\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html"}
{"id": "b81924e0cc2d-1", "text": "glob: Glob pattern to use to find files. Defaults to \"**/[!.]*\"\n               (all files except hidden).\n            silent_errors: Whether to silently ignore errors. Defaults to False.\n            load_hidden: Whether to load hidden files. Defaults to False.\n            loader_cls: Loader class to use for loading files.\n              Defaults to UnstructuredFileLoader.\n            loader_kwargs: Keyword arguments to pass to loader_cls. Defaults to None.\n            recursive: Whether to recursively search for files. Defaults to False.\n            show_progress: Whether to show a progress bar. Defaults to False.\n            use_multithreading: Whether to use multithreading. Defaults to False.\n            max_concurrency: The maximum number of threads to use. Defaults to 4.\n            sample_size: The maximum number of files you would like to load from the\n                directory.\n            randomize_sample: Suffle the files to get a random sample.\n            sample_seed: set the seed of the random shuffle for reporoducibility.\n        \"\"\"\n        if loader_kwargs is None:\n            loader_kwargs = {}\n        self.path = path\n        self.glob = glob\n        self.load_hidden = load_hidden\n        self.loader_cls = loader_cls\n        self.loader_kwargs = loader_kwargs\n        self.silent_errors = silent_errors\n        self.recursive = recursive\n        self.show_progress = show_progress\n        self.use_multithreading = use_multithreading\n        self.max_concurrency = max_concurrency\n        self.sample_size = sample_size\n        self.randomize_sample = randomize_sample\n        self.sample_seed = sample_seed\n[docs]    def load_file(\n        self, item: Path, path: Path, docs: List[Document], pbar: Optional[Any]\n    ) -> None:\n        \"\"\"Load a file.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html"}
{"id": "b81924e0cc2d-2", "text": ") -> None:\n        \"\"\"Load a file.\n        Args:\n            item: File path.\n            path: Directory path.\n            docs: List of documents to append to.\n            pbar: Progress bar. Defaults to None.\n        \"\"\"\n        if item.is_file():\n            if _is_visible(item.relative_to(path)) or self.load_hidden:\n                try:\n                    logger.debug(f\"Processing file: {str(item)}\")\n                    sub_docs = self.loader_cls(str(item), **self.loader_kwargs).load()\n                    docs.extend(sub_docs)\n                except Exception as e:\n                    if self.silent_errors:\n                        logger.warning(f\"Error loading file {str(item)}: {e}\")\n                    else:\n                        raise e\n                finally:\n                    if pbar:\n                        pbar.update(1)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        p = Path(self.path)\n        if not p.exists():\n            raise FileNotFoundError(f\"Directory not found: '{self.path}'\")\n        if not p.is_dir():\n            raise ValueError(f\"Expected directory, got file: '{self.path}'\")\n        docs: List[Document] = []\n        items = list(p.rglob(self.glob) if self.recursive else p.glob(self.glob))\n        if self.sample_size > 0:\n            if self.randomize_sample:\n                randomizer = (\n                    random.Random(self.sample_seed) if self.sample_seed else random\n                )\n                randomizer.shuffle(items)  # type: ignore\n            items = items[: min(len(items), self.sample_size)]\n        pbar = None\n        if self.show_progress:\n            try:\n                from tqdm import tqdm\n                pbar = tqdm(total=len(items))\n            except ImportError as e:\n                logger.warning(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html"}
{"id": "b81924e0cc2d-3", "text": "except ImportError as e:\n                logger.warning(\n                    \"To log the progress of DirectoryLoader you need to install tqdm, \"\n                    \"`pip install tqdm`\"\n                )\n                if self.silent_errors:\n                    logger.warning(e)\n                else:\n                    raise ImportError(\n                        \"To log the progress of DirectoryLoader \"\n                        \"you need to install tqdm, \"\n                        \"`pip install tqdm`\"\n                    )\n        if self.use_multithreading:\n            with concurrent.futures.ThreadPoolExecutor(\n                max_workers=self.max_concurrency\n            ) as executor:\n                executor.map(lambda i: self.load_file(i, p, docs, pbar), items)\n        else:\n            for i in items:\n                self.load_file(i, p, docs, pbar)\n        if pbar:\n            pbar.close()\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html"}
{"id": "4cb0ccb0feaf-0", "text": "Source code for langchain.document_loaders.generic\nfrom __future__ import annotations\nfrom pathlib import Path\nfrom typing import Iterator, List, Literal, Optional, Sequence, Union\nfrom langchain.document_loaders.base import BaseBlobParser, BaseLoader\nfrom langchain.document_loaders.blob_loaders import BlobLoader, FileSystemBlobLoader\nfrom langchain.document_loaders.parsers.registry import get_parser\nfrom langchain.schema import Document\nfrom langchain.text_splitter import TextSplitter\n_PathLike = Union[str, Path]\nDEFAULT = Literal[\"default\"]\n[docs]class GenericLoader(BaseLoader):\n    \"\"\"Generic Document Loader.\n    A generic document loader that allows combining an arbitrary blob loader with\n    a blob parser.\n    Examples:\n       .. code-block:: python\n        from langchain.document_loaders import GenericLoader\n        from langchain.document_loaders.blob_loaders import FileSystemBlobLoader\n        loader = GenericLoader.from_filesystem(\n            path=\"path/to/directory\",\n            glob=\"**/[!.]*\",\n            suffixes=[\".pdf\"],\n            show_progress=True,\n        )\n        docs = loader.lazy_load()\n        next(docs)\n        Example instantiations to change which files are loaded:\n        .. code-block:: python\n            # Recursively load all text files in a directory.\n            loader = GenericLoader.from_filesystem(\"/path/to/dir\", glob=\"**/*.txt\")\n            # Recursively load all non-hidden files in a directory.\n            loader = GenericLoader.from_filesystem(\"/path/to/dir\", glob=\"**/[!.]*\")\n            # Load all files in a directory without recursion.\n            loader = GenericLoader.from_filesystem(\"/path/to/dir\", glob=\"*\")\n        Example instantiations to change which parser is used:\n        .. code-block:: python\n            from langchain.document_loaders.parsers.pdf import PyPDFParser", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/generic.html"}
{"id": "4cb0ccb0feaf-1", "text": "from langchain.document_loaders.parsers.pdf import PyPDFParser\n            # Recursively load all text files in a directory.\n            loader = GenericLoader.from_filesystem(\n                \"/path/to/dir\",\n                glob=\"**/*.pdf\",\n                parser=PyPDFParser()\n            )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        blob_loader: BlobLoader,\n        blob_parser: BaseBlobParser,\n    ) -> None:\n        \"\"\"A generic document loader.\n        Args:\n            blob_loader: A blob loader which knows how to yield blobs\n            blob_parser: A blob parser which knows how to parse blobs into documents\n        \"\"\"\n        self.blob_loader = blob_loader\n        self.blob_parser = blob_parser\n[docs]    def lazy_load(\n        self,\n    ) -> Iterator[Document]:\n        \"\"\"Load documents lazily. Use this when working at a large scale.\"\"\"\n        for blob in self.blob_loader.yield_blobs():\n            yield from self.blob_parser.lazy_parse(blob)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load all documents.\"\"\"\n        return list(self.lazy_load())\n[docs]    def load_and_split(\n        self, text_splitter: Optional[TextSplitter] = None\n    ) -> List[Document]:\n        \"\"\"Load all documents and split them into sentences.\"\"\"\n        raise NotImplementedError(\n            \"Loading and splitting is not yet implemented for generic loaders. \"\n            \"When they will be implemented they will be added via the initializer. \"\n            \"This method should not be used going forward.\"\n        )\n[docs]    @classmethod\n    def from_filesystem(\n        cls,\n        path: _PathLike,\n        *,\n        glob: str = \"**/[!.]*\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/generic.html"}
{"id": "4cb0ccb0feaf-2", "text": "*,\n        glob: str = \"**/[!.]*\",\n        exclude: Sequence[str] = (),\n        suffixes: Optional[Sequence[str]] = None,\n        show_progress: bool = False,\n        parser: Union[DEFAULT, BaseBlobParser] = \"default\",\n    ) -> GenericLoader:\n        \"\"\"Create a generic document loader using a filesystem blob loader.\n        Args:\n            path: The path to the directory to load documents from.\n            glob: The glob pattern to use to find documents.\n            suffixes: The suffixes to use to filter documents. If None, all files\n                      matching the glob will be loaded.\n            exclude: A list of patterns to exclude from the loader.\n            show_progress: Whether to show a progress bar or not (requires tqdm).\n                           Proxies to the file system loader.\n            parser: A blob parser which knows how to parse blobs into documents\n        Returns:\n            A generic document loader.\n        \"\"\"\n        blob_loader = FileSystemBlobLoader(\n            path,\n            glob=glob,\n            exclude=exclude,\n            suffixes=suffixes,\n            show_progress=show_progress,\n        )\n        if isinstance(parser, str):\n            blob_parser = get_parser(parser)\n        else:\n            blob_parser = parser\n        return cls(blob_loader, blob_parser)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/generic.html"}
{"id": "7a6f9d8f2d09-0", "text": "Source code for langchain.document_loaders.toml\nimport json\nfrom pathlib import Path\nfrom typing import Iterator, List, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class TomlLoader(BaseLoader):\n    \"\"\"Load `TOML` files.\n    It can load a single source file or several files in a single\n    directory.\n    \"\"\"\n[docs]    def __init__(self, source: Union[str, Path]):\n        \"\"\"Initialize the TomlLoader with a source file or directory.\"\"\"\n        self.source = Path(source)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load and return all documents.\"\"\"\n        return list(self.lazy_load())\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazily load the TOML documents from the source file or directory.\"\"\"\n        import tomli\n        if self.source.is_file() and self.source.suffix == \".toml\":\n            files = [self.source]\n        elif self.source.is_dir():\n            files = list(self.source.glob(\"**/*.toml\"))\n        else:\n            raise ValueError(\"Invalid source path or file type\")\n        for file_path in files:\n            with file_path.open(\"r\", encoding=\"utf-8\") as file:\n                content = file.read()\n                try:\n                    data = tomli.loads(content)\n                    doc = Document(\n                        page_content=json.dumps(data),\n                        metadata={\"source\": str(file_path)},\n                    )\n                    yield doc\n                except tomli.TOMLDecodeError as e:\n                    print(f\"Error parsing TOML file {file_path}: {e}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/toml.html"}
{"id": "e128cbc44a29-0", "text": "Source code for langchain.document_loaders.conllu\nimport csv\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class CoNLLULoader(BaseLoader):\n    \"\"\"Load `CoNLL-U` files.\"\"\"\n[docs]    def __init__(self, file_path: str):\n        \"\"\"Initialize with a file path.\"\"\"\n        self.file_path = file_path\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load from a file path.\"\"\"\n        with open(self.file_path, encoding=\"utf8\") as f:\n            tsv = list(csv.reader(f, delimiter=\"\\t\"))\n            # If len(line) > 1, the line is not a comment\n            lines = [line for line in tsv if len(line) > 1]\n        text = \"\"\n        for i, line in enumerate(lines):\n            # Do not add a space after a punctuation mark or at the end of the sentence\n            if line[9] == \"SpaceAfter=No\" or i == len(lines) - 1:\n                text += line[1]\n            else:\n                text += line[1] + \" \"\n        metadata = {\"source\": self.file_path}\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/conllu.html"}
{"id": "9d22a13f7966-0", "text": "Source code for langchain.document_loaders.docugami\nimport io\nimport logging\nimport os\nimport re\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Mapping, Optional, Sequence, Union\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nTD_NAME = \"{http://www.w3.org/1999/xhtml}td\"\nTABLE_NAME = \"{http://www.w3.org/1999/xhtml}table\"\nXPATH_KEY = \"xpath\"\nDOCUMENT_ID_KEY = \"id\"\nDOCUMENT_SOURCE_KEY = \"source\"\nDOCUMENT_NAME_KEY = \"name\"\nSTRUCTURE_KEY = \"structure\"\nTAG_KEY = \"tag\"\nPROJECTS_KEY = \"projects\"\nDEFAULT_API_ENDPOINT = \"https://api.docugami.com/v1preview1\"\nlogger = logging.getLogger(__name__)\n[docs]class DocugamiLoader(BaseLoader, BaseModel):\n    \"\"\"Load from `Docugami`.\n    To use, you should have the ``lxml`` python package installed.\n    \"\"\"\n    api: str = DEFAULT_API_ENDPOINT\n    \"\"\"The Docugami API endpoint to use.\"\"\"\n    access_token: Optional[str] = os.environ.get(\"DOCUGAMI_API_KEY\")\n    \"\"\"The Docugami API access token to use.\"\"\"\n    docset_id: Optional[str]\n    \"\"\"The Docugami API docset ID to use.\"\"\"\n    document_ids: Optional[Sequence[str]]\n    \"\"\"The Docugami API document IDs to use.\"\"\"\n    file_paths: Optional[Sequence[Union[Path, str]]]\n    \"\"\"The local file paths to use.\"\"\"\n    min_chunk_size: int = 32  # appended to the next chunk to avoid over-chunking", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html"}
{"id": "9d22a13f7966-1", "text": "\"\"\"The minimum chunk size to use when parsing DGML. Defaults to 32.\"\"\"\n    @root_validator\n    def validate_local_or_remote(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Validate that either local file paths are given, or remote API docset ID.\n        Args:\n            values: The values to validate.\n        Returns:\n            The validated values.\n        \"\"\"\n        if values.get(\"file_paths\") and values.get(\"docset_id\"):\n            raise ValueError(\"Cannot specify both file_paths and remote API docset_id\")\n        if not values.get(\"file_paths\") and not values.get(\"docset_id\"):\n            raise ValueError(\"Must specify either file_paths or remote API docset_id\")\n        if values.get(\"docset_id\") and not values.get(\"access_token\"):\n            raise ValueError(\"Must specify access token if using remote API docset_id\")\n        return values\n    def _parse_dgml(\n        self, document: Mapping, content: bytes, doc_metadata: Optional[Mapping] = None\n    ) -> List[Document]:\n        \"\"\"Parse a single DGML document into a list of Documents.\"\"\"\n        try:\n            from lxml import etree\n        except ImportError:\n            raise ImportError(\n                \"Could not import lxml python package. \"\n                \"Please install it with `pip install lxml`.\"\n            )\n        # helpers\n        def _xpath_qname_for_chunk(chunk: Any) -> str:\n            \"\"\"Get the xpath qname for a chunk.\"\"\"\n            qname = f\"{chunk.prefix}:{chunk.tag.split('}')[-1]}\"\n            parent = chunk.getparent()\n            if parent is not None:\n                doppelgangers = [x for x in parent if x.tag == chunk.tag]\n                if len(doppelgangers) > 1:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html"}
{"id": "9d22a13f7966-2", "text": "if len(doppelgangers) > 1:\n                    idx_of_self = doppelgangers.index(chunk)\n                    qname = f\"{qname}[{idx_of_self + 1}]\"\n            return qname\n        def _xpath_for_chunk(chunk: Any) -> str:\n            \"\"\"Get the xpath for a chunk.\"\"\"\n            ancestor_chain = chunk.xpath(\"ancestor-or-self::*\")\n            return \"/\" + \"/\".join(_xpath_qname_for_chunk(x) for x in ancestor_chain)\n        def _structure_value(node: Any) -> str:\n            \"\"\"Get the structure value for a node.\"\"\"\n            structure = (\n                \"table\"\n                if node.tag == TABLE_NAME\n                else node.attrib[\"structure\"]\n                if \"structure\" in node.attrib\n                else None\n            )\n            return structure\n        def _is_structural(node: Any) -> bool:\n            \"\"\"Check if a node is structural.\"\"\"\n            return _structure_value(node) is not None\n        def _is_heading(node: Any) -> bool:\n            \"\"\"Check if a node is a heading.\"\"\"\n            structure = _structure_value(node)\n            return structure is not None and structure.lower().startswith(\"h\")\n        def _get_text(node: Any) -> str:\n            \"\"\"Get the text of a node.\"\"\"\n            return \" \".join(node.itertext()).strip()\n        def _has_structural_descendant(node: Any) -> bool:\n            \"\"\"Check if a node has a structural descendant.\"\"\"\n            for child in node:\n                if _is_structural(child) or _has_structural_descendant(child):\n                    return True\n            return False\n        def _leaf_structural_nodes(node: Any) -> List:\n            \"\"\"Get the leaf structural nodes of a node.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html"}
{"id": "9d22a13f7966-3", "text": "\"\"\"Get the leaf structural nodes of a node.\"\"\"\n            if _is_structural(node) and not _has_structural_descendant(node):\n                return [node]\n            else:\n                leaf_nodes = []\n                for child in node:\n                    leaf_nodes.extend(_leaf_structural_nodes(child))\n                return leaf_nodes\n        def _create_doc(node: Any, text: str) -> Document:\n            \"\"\"Create a Document from a node and text.\"\"\"\n            metadata = {\n                XPATH_KEY: _xpath_for_chunk(node),\n                DOCUMENT_ID_KEY: document[DOCUMENT_ID_KEY],\n                DOCUMENT_NAME_KEY: document[DOCUMENT_NAME_KEY],\n                DOCUMENT_SOURCE_KEY: document[DOCUMENT_NAME_KEY],\n                STRUCTURE_KEY: node.attrib.get(\"structure\", \"\"),\n                TAG_KEY: re.sub(r\"\\{.*\\}\", \"\", node.tag),\n            }\n            if doc_metadata:\n                metadata.update(doc_metadata)\n            return Document(\n                page_content=text,\n                metadata=metadata,\n            )\n        # parse the tree and return chunks\n        tree = etree.parse(io.BytesIO(content))\n        root = tree.getroot()\n        chunks: List[Document] = []\n        prev_small_chunk_text = None\n        for node in _leaf_structural_nodes(root):\n            text = _get_text(node)\n            if prev_small_chunk_text:\n                text = prev_small_chunk_text + \" \" + text\n                prev_small_chunk_text = None\n            if _is_heading(node) or len(text) < self.min_chunk_size:\n                # Save headings or other small chunks to be appended to the next chunk\n                prev_small_chunk_text = text\n            else:\n                chunks.append(_create_doc(node, text))\n        if prev_small_chunk_text and len(chunks) > 0:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html"}
{"id": "9d22a13f7966-4", "text": "if prev_small_chunk_text and len(chunks) > 0:\n            # small chunk at the end left over, just append to last chunk\n            chunks[-1].page_content += \" \" + prev_small_chunk_text\n        return chunks\n    def _document_details_for_docset_id(self, docset_id: str) -> List[Dict]:\n        \"\"\"Gets all document details for the given docset ID\"\"\"\n        url = f\"{self.api}/docsets/{docset_id}/documents\"\n        all_documents = []\n        while url:\n            response = requests.get(\n                url,\n                headers={\"Authorization\": f\"Bearer {self.access_token}\"},\n            )\n            if response.ok:\n                data = response.json()\n                all_documents.extend(data[\"documents\"])\n                url = data.get(\"next\", None)\n            else:\n                raise Exception(\n                    f\"Failed to download {url} (status: {response.status_code})\"\n                )\n        return all_documents\n    def _project_details_for_docset_id(self, docset_id: str) -> List[Dict]:\n        \"\"\"Gets all project details for the given docset ID\"\"\"\n        url = f\"{self.api}/projects?docset.id={docset_id}\"\n        all_projects = []\n        while url:\n            response = requests.request(\n                \"GET\",\n                url,\n                headers={\"Authorization\": f\"Bearer {self.access_token}\"},\n                data={},\n            )\n            if response.ok:\n                data = response.json()\n                all_projects.extend(data[\"projects\"])\n                url = data.get(\"next\", None)\n            else:\n                raise Exception(\n                    f\"Failed to download {url} (status: {response.status_code})\"\n                )\n        return all_projects", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html"}
{"id": "9d22a13f7966-5", "text": ")\n        return all_projects\n    def _metadata_for_project(self, project: Dict) -> Dict:\n        \"\"\"Gets project metadata for all files\"\"\"\n        project_id = project.get(\"id\")\n        url = f\"{self.api}/projects/{project_id}/artifacts/latest\"\n        all_artifacts = []\n        while url:\n            response = requests.request(\n                \"GET\",\n                url,\n                headers={\"Authorization\": f\"Bearer {self.access_token}\"},\n                data={},\n            )\n            if response.ok:\n                data = response.json()\n                all_artifacts.extend(data[\"artifacts\"])\n                url = data.get(\"next\", None)\n            else:\n                raise Exception(\n                    f\"Failed to download {url} (status: {response.status_code})\"\n                )\n        per_file_metadata = {}\n        for artifact in all_artifacts:\n            artifact_name = artifact.get(\"name\")\n            artifact_url = artifact.get(\"url\")\n            artifact_doc = artifact.get(\"document\")\n            if artifact_name == \"report-values.xml\" and artifact_url and artifact_doc:\n                doc_id = artifact_doc[\"id\"]\n                metadata: Dict = {}\n                # the evaluated XML for each document is named after the project\n                response = requests.request(\n                    \"GET\",\n                    f\"{artifact_url}/content\",\n                    headers={\"Authorization\": f\"Bearer {self.access_token}\"},\n                    data={},\n                )\n                if response.ok:\n                    try:\n                        from lxml import etree\n                    except ImportError:\n                        raise ImportError(\n                            \"Could not import lxml python package. \"\n                            \"Please install it with `pip install lxml`.\"\n                        )\n                    artifact_tree = etree.parse(io.BytesIO(response.content))\n                    artifact_root = artifact_tree.getroot()\n                    ns = artifact_root.nsmap", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html"}
{"id": "9d22a13f7966-6", "text": "artifact_root = artifact_tree.getroot()\n                    ns = artifact_root.nsmap\n                    entries = artifact_root.xpath(\"//pr:Entry\", namespaces=ns)\n                    for entry in entries:\n                        heading = entry.xpath(\"./pr:Heading\", namespaces=ns)[0].text\n                        value = \" \".join(\n                            entry.xpath(\"./pr:Value\", namespaces=ns)[0].itertext()\n                        ).strip()\n                        metadata[heading] = value\n                    per_file_metadata[doc_id] = metadata\n                else:\n                    raise Exception(\n                        f\"Failed to download {artifact_url}/content \"\n                        + \"(status: {response.status_code})\"\n                    )\n        return per_file_metadata\n    def _load_chunks_for_document(\n        self, docset_id: str, document: Dict, doc_metadata: Optional[Dict] = None\n    ) -> List[Document]:\n        \"\"\"Load chunks for a document.\"\"\"\n        document_id = document[\"id\"]\n        url = f\"{self.api}/docsets/{docset_id}/documents/{document_id}/dgml\"\n        response = requests.request(\n            \"GET\",\n            url,\n            headers={\"Authorization\": f\"Bearer {self.access_token}\"},\n            data={},\n        )\n        if response.ok:\n            return self._parse_dgml(document, response.content, doc_metadata)\n        else:\n            raise Exception(\n                f\"Failed to download {url} (status: {response.status_code})\"\n            )\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        chunks: List[Document] = []\n        if self.access_token and self.docset_id:\n            # remote mode\n            _document_details = self._document_details_for_docset_id(self.docset_id)\n            if self.document_ids:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html"}
{"id": "9d22a13f7966-7", "text": "if self.document_ids:\n                _document_details = [\n                    d for d in _document_details if d[\"id\"] in self.document_ids\n                ]\n            _project_details = self._project_details_for_docset_id(self.docset_id)\n            combined_project_metadata = {}\n            if _project_details:\n                # if there are any projects for this docset, load project metadata\n                for project in _project_details:\n                    metadata = self._metadata_for_project(project)\n                    combined_project_metadata.update(metadata)\n            for doc in _document_details:\n                doc_metadata = combined_project_metadata.get(doc[\"id\"])\n                chunks += self._load_chunks_for_document(\n                    self.docset_id, doc, doc_metadata\n                )\n        elif self.file_paths:\n            # local mode (for integration testing, or pre-downloaded XML)\n            for path in self.file_paths:\n                path = Path(path)\n                with open(path, \"rb\") as file:\n                    chunks += self._parse_dgml(\n                        {\n                            DOCUMENT_ID_KEY: path.name,\n                            DOCUMENT_NAME_KEY: path.name,\n                        },\n                        file.read(),\n                    )\n        return chunks", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html"}
{"id": "47715f793c74-0", "text": "Source code for langchain.document_loaders.ifixit\nfrom typing import List, Optional\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.web_base import WebBaseLoader\nIFIXIT_BASE_URL = \"https://www.ifixit.com/api/2.0\"\n[docs]class IFixitLoader(BaseLoader):\n    \"\"\"Load `iFixit` repair guides, device wikis and answers.\n    iFixit is the largest, open repair community on the web. The site contains nearly\n    100k repair manuals, 200k Questions & Answers on 42k devices, and all the data is\n    licensed under CC-BY.\n    This loader will allow you to download the text of a repair guide, text of Q&A's\n    and wikis from devices on iFixit using their open APIs and web scraping.\n    \"\"\"\n[docs]    def __init__(self, web_path: str):\n        \"\"\"Initialize with a web path.\"\"\"\n        if not web_path.startswith(\"https://www.ifixit.com\"):\n            raise ValueError(\"web path must start with 'https://www.ifixit.com'\")\n        path = web_path.replace(\"https://www.ifixit.com\", \"\")\n        allowed_paths = [\"/Device\", \"/Guide\", \"/Answers\", \"/Teardown\"]\n        \"\"\" TODO: Add /Wiki \"\"\"\n        if not any(path.startswith(allowed_path) for allowed_path in allowed_paths):\n            raise ValueError(\n                \"web path must start with /Device, /Guide, /Teardown or /Answers\"\n            )\n        pieces = [x for x in path.split(\"/\") if x]\n        \"\"\"Teardowns are just guides by a different name\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html"}
{"id": "47715f793c74-1", "text": "\"\"\"Teardowns are just guides by a different name\"\"\"\n        self.page_type = pieces[0] if pieces[0] != \"Teardown\" else \"Guide\"\n        if self.page_type == \"Guide\" or self.page_type == \"Answers\":\n            self.id = pieces[2]\n        else:\n            self.id = pieces[1]\n        self.web_path = web_path\n[docs]    def load(self) -> List[Document]:\n        if self.page_type == \"Device\":\n            return self.load_device()\n        elif self.page_type == \"Guide\" or self.page_type == \"Teardown\":\n            return self.load_guide()\n        elif self.page_type == \"Answers\":\n            return self.load_questions_and_answers()\n        else:\n            raise ValueError(\"Unknown page type: \" + self.page_type)\n[docs]    @staticmethod\n    def load_suggestions(query: str = \"\", doc_type: str = \"all\") -> List[Document]:\n        \"\"\"Load suggestions.\n        Args:\n            query: A query string\n            doc_type: The type of document to search for. Can be one of \"all\",\n              \"device\", \"guide\", \"teardown\", \"answer\", \"wiki\".\n        Returns:\n        \"\"\"\n        res = requests.get(\n            IFIXIT_BASE_URL + \"/suggest/\" + query + \"?doctypes=\" + doc_type\n        )\n        if res.status_code != 200:\n            raise ValueError(\n                'Could not load suggestions for \"' + query + '\"\\n' + res.json()\n            )\n        data = res.json()\n        results = data[\"results\"]\n        output = []\n        for result in results:\n            try:\n                loader = IFixitLoader(result[\"url\"])\n                if loader.page_type == \"Device\":", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html"}
{"id": "47715f793c74-2", "text": "if loader.page_type == \"Device\":\n                    output += loader.load_device(include_guides=False)\n                else:\n                    output += loader.load()\n            except ValueError:\n                continue\n        return output\n[docs]    def load_questions_and_answers(\n        self, url_override: Optional[str] = None\n    ) -> List[Document]:\n        \"\"\"Load a list of questions and answers.\n        Args:\n            url_override: A URL to override the default URL.\n        Returns: List[Document]\n        \"\"\"\n        loader = WebBaseLoader(self.web_path if url_override is None else url_override)\n        soup = loader.scrape()\n        output = []\n        title = soup.find(\"h1\", \"post-title\").text\n        output.append(\"# \" + title)\n        output.append(soup.select_one(\".post-content .post-text\").text.strip())\n        answersHeader = soup.find(\"div\", \"post-answers-header\")\n        if answersHeader:\n            output.append(\"\\n## \" + answersHeader.text.strip())\n        for answer in soup.select(\".js-answers-list .post.post-answer\"):\n            if answer.has_attr(\"itemprop\") and \"acceptedAnswer\" in answer[\"itemprop\"]:\n                output.append(\"\\n### Accepted Answer\")\n            elif \"post-helpful\" in answer[\"class\"]:\n                output.append(\"\\n### Most Helpful Answer\")\n            else:\n                output.append(\"\\n### Other Answer\")\n            output += [\n                a.text.strip() for a in answer.select(\".post-content .post-text\")\n            ]\n            output.append(\"\\n\")\n        text = \"\\n\".join(output).strip()\n        metadata = {\"source\": self.web_path, \"title\": title}\n        return [Document(page_content=text, metadata=metadata)]\n[docs]    def load_device(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html"}
{"id": "47715f793c74-3", "text": "[docs]    def load_device(\n        self, url_override: Optional[str] = None, include_guides: bool = True\n    ) -> List[Document]:\n        \"\"\"Loads a device\n        Args:\n            url_override: A URL to override the default URL.\n            include_guides: Whether to include guides linked to from the device.\n              Defaults to True.\n        Returns:\n        \"\"\"\n        documents = []\n        if url_override is None:\n            url = IFIXIT_BASE_URL + \"/wikis/CATEGORY/\" + self.id\n        else:\n            url = url_override\n        res = requests.get(url)\n        data = res.json()\n        text = \"\\n\".join(\n            [\n                data[key]\n                for key in [\"title\", \"description\", \"contents_raw\"]\n                if key in data\n            ]\n        ).strip()\n        metadata = {\"source\": self.web_path, \"title\": data[\"title\"]}\n        documents.append(Document(page_content=text, metadata=metadata))\n        if include_guides:\n            \"\"\"Load and return documents for each guide linked to from the device\"\"\"\n            guide_urls = [guide[\"url\"] for guide in data[\"guides\"]]\n            for guide_url in guide_urls:\n                documents.append(IFixitLoader(guide_url).load()[0])\n        return documents\n[docs]    def load_guide(self, url_override: Optional[str] = None) -> List[Document]:\n        \"\"\"Load a guide\n        Args:\n            url_override: A URL to override the default URL.\n        Returns: List[Document]\n        \"\"\"\n        if url_override is None:\n            url = IFIXIT_BASE_URL + \"/guides/\" + self.id\n        else:\n            url = url_override\n        res = requests.get(url)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html"}
{"id": "47715f793c74-4", "text": "else:\n            url = url_override\n        res = requests.get(url)\n        if res.status_code != 200:\n            raise ValueError(\n                \"Could not load guide: \" + self.web_path + \"\\n\" + res.json()\n            )\n        data = res.json()\n        doc_parts = [\"# \" + data[\"title\"], data[\"introduction_raw\"]]\n        doc_parts.append(\"\\n\\n###Tools Required:\")\n        if len(data[\"tools\"]) == 0:\n            doc_parts.append(\"\\n - None\")\n        else:\n            for tool in data[\"tools\"]:\n                doc_parts.append(\"\\n - \" + tool[\"text\"])\n        doc_parts.append(\"\\n\\n###Parts Required:\")\n        if len(data[\"parts\"]) == 0:\n            doc_parts.append(\"\\n - None\")\n        else:\n            for part in data[\"parts\"]:\n                doc_parts.append(\"\\n - \" + part[\"text\"])\n        for row in data[\"steps\"]:\n            doc_parts.append(\n                \"\\n\\n## \"\n                + (\n                    row[\"title\"]\n                    if row[\"title\"] != \"\"\n                    else \"Step {}\".format(row[\"orderby\"])\n                )\n            )\n            for line in row[\"lines\"]:\n                doc_parts.append(line[\"text_raw\"])\n        doc_parts.append(data[\"conclusion_raw\"])\n        text = \"\\n\".join(doc_parts)\n        metadata = {\"source\": self.web_path, \"title\": data[\"title\"]}\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html"}
{"id": "e1201b419b66-0", "text": "Source code for langchain.document_loaders.baiducloud_bos_directory\nfrom typing import Any, Iterator, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class BaiduBOSDirectoryLoader(BaseLoader):\n    \"\"\"Load from `Baidu BOS directory`.\"\"\"\n[docs]    def __init__(self, conf: Any, bucket: str, prefix: str = \"\"):\n        \"\"\"Initialize with BOS config, bucket and prefix.\n        :param conf(BosConfig): BOS config.\n        :param bucket(str): BOS bucket.\n        :param prefix(str): prefix.\n        \"\"\"\n        self.conf = conf\n        self.bucket = bucket\n        self.prefix = prefix\n[docs]    def load(self) -> List[Document]:\n        return list(self.lazy_load())\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Load documents.\"\"\"\n        try:\n            from baidubce.services.bos.bos_client import BosClient\n        except ImportError:\n            raise ImportError(\n                \"Please install bce-python-sdk with `pip install bce-python-sdk`.\"\n            )\n        client = BosClient(self.conf)\n        contents = []\n        marker = \"\"\n        while True:\n            response = client.list_objects(\n                bucket_name=self.bucket,\n                prefix=self.prefix,\n                marker=marker,\n                max_keys=1000,\n            )\n            contents_len = len(response.contents)\n            contents.extend(response.contents)\n            if response.is_truncated or contents_len < int(str(response.max_keys)):\n                break\n            marker = response.next_marker\n        from langchain.document_loaders.baiducloud_bos_file import BaiduBOSFileLoader\n        for content in contents:\n            if str(content.key).endswith(\"/\"):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/baiducloud_bos_directory.html"}
{"id": "e1201b419b66-1", "text": "for content in contents:\n            if str(content.key).endswith(\"/\"):\n                continue\n            loader = BaiduBOSFileLoader(self.conf, self.bucket, str(content.key))\n            yield loader.load()[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/baiducloud_bos_directory.html"}
{"id": "4798a8d5b7ab-0", "text": "Source code for langchain.document_loaders.obs_file\n# coding:utf-8\nimport os\nimport tempfile\nfrom typing import Any, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.unstructured import UnstructuredFileLoader\n[docs]class OBSFileLoader(BaseLoader):\n    \"\"\"Load from the `Huawei OBS file`.\"\"\"\n[docs]    def __init__(\n        self,\n        bucket: str,\n        key: str,\n        client: Any = None,\n        endpoint: str = \"\",\n        config: Optional[dict] = None,\n    ) -> None:\n        \"\"\"Initialize the OBSFileLoader with the specified settings.\n        Args:\n            bucket (str): The name of the OBS bucket to be used.\n            key (str): The name of the object in the OBS bucket.\n            client (ObsClient, optional): An instance of the ObsClient to connect to OBS.\n            endpoint (str, optional): The endpoint URL of your OBS bucket. This parameter is mandatory if `client` is not provided.\n            config (dict, optional): The parameters for connecting to OBS, provided as a dictionary. This parameter is ignored if `client` is provided. The dictionary could have the following keys:\n                - \"ak\" (str, optional): Your OBS access key (required if `get_token_from_ecs` is False and bucket policy is not public read).\n                - \"sk\" (str, optional): Your OBS secret key (required if `get_token_from_ecs` is False and bucket policy is not public read).\n                - \"token\" (str, optional): Your security token (required if using temporary credentials).", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obs_file.html"}
{"id": "4798a8d5b7ab-1", "text": "- \"get_token_from_ecs\" (bool, optional): Whether to retrieve the security token from ECS. Defaults to False if not provided. If set to True, `ak`, `sk`, and `token` will be ignored.\n        Raises:\n            ValueError: If the `esdk-obs-python` package is not installed.\n            TypeError: If the provided `client` is not an instance of ObsClient.\n            ValueError: If `client` is not provided, but `endpoint` is missing.\n        Note:\n            Before using this class, make sure you have registered with OBS and have the necessary credentials. The `ak`, `sk`, and `endpoint` values are mandatory unless `get_token_from_ecs` is True or the bucket policy is public read. `token` is required when using temporary credentials.\n        Example:\n            To create a new OBSFileLoader with a new client:\n            ```\n            config = {\n                \"ak\": \"your-access-key\",\n                \"sk\": \"your-secret-key\"\n            }\n            obs_loader = OBSFileLoader(\"your-bucket-name\", \"your-object-key\", config=config)\n            ```\n            To create a new OBSFileLoader with an existing client:\n            ```\n            from obs import ObsClient\n            # Assuming you have an existing ObsClient object 'obs_client'\n            obs_loader = OBSFileLoader(\"your-bucket-name\", \"your-object-key\", client=obs_client)\n            ```\n            To create a new OBSFileLoader without an existing client:\n            ```\n            obs_loader = OBSFileLoader(\"your-bucket-name\", \"your-object-key\", endpoint=\"your-endpoint-url\")\n            ```\n        \"\"\"  # noqa: E501\n        try:\n            from obs import ObsClient\n        except ImportError:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obs_file.html"}
{"id": "4798a8d5b7ab-2", "text": "from obs import ObsClient\n        except ImportError:\n            raise ImportError(\n                \"Could not import esdk-obs-python python package. \"\n                \"Please install it with `pip install esdk-obs-python`.\"\n            )\n        if not client:\n            if not endpoint:\n                raise ValueError(\"Either OBSClient or endpoint must be provided.\")\n            if not config:\n                config = dict()\n            if config.get(\"get_token_from_ecs\"):\n                client = ObsClient(server=endpoint, security_provider_policy=\"ECS\")\n            else:\n                client = ObsClient(\n                    access_key_id=config.get(\"ak\"),\n                    secret_access_key=config.get(\"sk\"),\n                    security_token=config.get(\"token\"),\n                    server=endpoint,\n                )\n        if not isinstance(client, ObsClient):\n            raise TypeError(\"Client must be ObsClient type\")\n        self.client = client\n        self.bucket = bucket\n        self.key = key\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        with tempfile.TemporaryDirectory() as temp_dir:\n            file_path = f\"{temp_dir}/{self.bucket}/{self.key}\"\n            os.makedirs(os.path.dirname(file_path), exist_ok=True)\n            # Download the file to a destination\n            self.client.downloadFile(\n                bucketName=self.bucket, objectKey=self.key, downloadFile=file_path\n            )\n            loader = UnstructuredFileLoader(file_path)\n            return loader.load()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obs_file.html"}
{"id": "455b0ef44b45-0", "text": "Source code for langchain.document_loaders.googledrive\n# Prerequisites:\n# 1. Create a Google Cloud project\n# 2. Enable the Google Drive API:\n#   https://console.cloud.google.com/flows/enableapi?apiid=drive.googleapis.com\n# 3. Authorize credentials for desktop app:\n#   https://developers.google.com/drive/api/quickstart/python#authorize_credentials_for_a_desktop_application # noqa: E501\n# 4. For service accounts visit\n#   https://cloud.google.com/iam/docs/service-accounts-create\nimport os\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Sequence, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.pydantic_v1 import BaseModel, root_validator, validator\nSCOPES = [\"https://www.googleapis.com/auth/drive.readonly\"]\n[docs]class GoogleDriveLoader(BaseLoader, BaseModel):\n    \"\"\"Load Google Docs from `Google Drive`.\"\"\"\n    service_account_key: Path = Path.home() / \".credentials\" / \"keys.json\"\n    \"\"\"Path to the service account key file.\"\"\"\n    credentials_path: Path = Path.home() / \".credentials\" / \"credentials.json\"\n    \"\"\"Path to the credentials file.\"\"\"\n    token_path: Path = Path.home() / \".credentials\" / \"token.json\"\n    \"\"\"Path to the token file.\"\"\"\n    folder_id: Optional[str] = None\n    \"\"\"The folder id to load from.\"\"\"\n    document_ids: Optional[List[str]] = None\n    \"\"\"The document ids to load from.\"\"\"\n    file_ids: Optional[List[str]] = None\n    \"\"\"The file ids to load from.\"\"\"\n    recursive: bool = False\n    \"\"\"Whether to load recursively. Only applies when folder_id is given.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html"}
{"id": "455b0ef44b45-1", "text": "\"\"\"Whether to load recursively. Only applies when folder_id is given.\"\"\"\n    file_types: Optional[Sequence[str]] = None\n    \"\"\"The file types to load. Only applies when folder_id is given.\"\"\"\n    load_trashed_files: bool = False\n    \"\"\"Whether to load trashed files. Only applies when folder_id is given.\"\"\"\n    # NOTE(MthwRobinson) - changing the file_loader_cls to type here currently\n    # results in pydantic validation errors\n    file_loader_cls: Any = None\n    \"\"\"The file loader class to use.\"\"\"\n    file_loader_kwargs: Dict[\"str\", Any] = {}\n    \"\"\"The file loader kwargs to use.\"\"\"\n    @root_validator\n    def validate_inputs(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Validate that either folder_id or document_ids is set, but not both.\"\"\"\n        if values.get(\"folder_id\") and (\n            values.get(\"document_ids\") or values.get(\"file_ids\")\n        ):\n            raise ValueError(\n                \"Cannot specify both folder_id and document_ids nor \"\n                \"folder_id and file_ids\"\n            )\n        if (\n            not values.get(\"folder_id\")\n            and not values.get(\"document_ids\")\n            and not values.get(\"file_ids\")\n        ):\n            raise ValueError(\"Must specify either folder_id, document_ids, or file_ids\")\n        file_types = values.get(\"file_types\")\n        if file_types:\n            if values.get(\"document_ids\") or values.get(\"file_ids\"):\n                raise ValueError(\n                    \"file_types can only be given when folder_id is given,\"\n                    \" (not when document_ids or file_ids are given).\"\n                )\n            type_mapping = {\n                \"document\": \"application/vnd.google-apps.document\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html"}
{"id": "455b0ef44b45-2", "text": "type_mapping = {\n                \"document\": \"application/vnd.google-apps.document\",\n                \"sheet\": \"application/vnd.google-apps.spreadsheet\",\n                \"pdf\": \"application/pdf\",\n            }\n            allowed_types = list(type_mapping.keys()) + list(type_mapping.values())\n            short_names = \", \".join([f\"'{x}'\" for x in type_mapping.keys()])\n            full_names = \", \".join([f\"'{x}'\" for x in type_mapping.values()])\n            for file_type in file_types:\n                if file_type not in allowed_types:\n                    raise ValueError(\n                        f\"Given file type {file_type} is not supported. \"\n                        f\"Supported values are: {short_names}; and \"\n                        f\"their full-form names: {full_names}\"\n                    )\n            # replace short-form file types by full-form file types\n            def full_form(x: str) -> str:\n                return type_mapping[x] if x in type_mapping else x\n            values[\"file_types\"] = [full_form(file_type) for file_type in file_types]\n        return values\n    @validator(\"credentials_path\")\n    def validate_credentials_path(cls, v: Any, **kwargs: Any) -> Any:\n        \"\"\"Validate that credentials_path exists.\"\"\"\n        if not v.exists():\n            raise ValueError(f\"credentials_path {v} does not exist\")\n        return v\n    def _load_credentials(self) -> Any:\n        \"\"\"Load credentials.\"\"\"\n        # Adapted from https://developers.google.com/drive/api/v3/quickstart/python\n        try:\n            from google.auth import default\n            from google.auth.transport.requests import Request\n            from google.oauth2 import service_account\n            from google.oauth2.credentials import Credentials\n            from google_auth_oauthlib.flow import InstalledAppFlow\n        except ImportError:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html"}
{"id": "455b0ef44b45-3", "text": "from google_auth_oauthlib.flow import InstalledAppFlow\n        except ImportError:\n            raise ImportError(\n                \"You must run \"\n                \"`pip install --upgrade \"\n                \"google-api-python-client google-auth-httplib2 \"\n                \"google-auth-oauthlib` \"\n                \"to use the Google Drive loader.\"\n            )\n        creds = None\n        if self.service_account_key.exists():\n            return service_account.Credentials.from_service_account_file(\n                str(self.service_account_key), scopes=SCOPES\n            )\n        if self.token_path.exists():\n            creds = Credentials.from_authorized_user_file(str(self.token_path), SCOPES)\n        if not creds or not creds.valid:\n            if creds and creds.expired and creds.refresh_token:\n                creds.refresh(Request())\n            elif \"GOOGLE_APPLICATION_CREDENTIALS\" not in os.environ:\n                creds, project = default()\n                creds = creds.with_scopes(SCOPES)\n                # no need to write to file\n                if creds:\n                    return creds\n            else:\n                flow = InstalledAppFlow.from_client_secrets_file(\n                    str(self.credentials_path), SCOPES\n                )\n                creds = flow.run_local_server(port=0)\n            with open(self.token_path, \"w\") as token:\n                token.write(creds.to_json())\n        return creds\n    def _load_sheet_from_id(self, id: str) -> List[Document]:\n        \"\"\"Load a sheet and all tabs from an ID.\"\"\"\n        from googleapiclient.discovery import build\n        creds = self._load_credentials()\n        sheets_service = build(\"sheets\", \"v4\", credentials=creds)\n        spreadsheet = sheets_service.spreadsheets().get(spreadsheetId=id).execute()\n        sheets = spreadsheet.get(\"sheets\", [])\n        documents = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html"}
{"id": "455b0ef44b45-4", "text": "sheets = spreadsheet.get(\"sheets\", [])\n        documents = []\n        for sheet in sheets:\n            sheet_name = sheet[\"properties\"][\"title\"]\n            result = (\n                sheets_service.spreadsheets()\n                .values()\n                .get(spreadsheetId=id, range=sheet_name)\n                .execute()\n            )\n            values = result.get(\"values\", [])\n            if not values:\n                continue  # empty sheet\n            header = values[0]\n            for i, row in enumerate(values[1:], start=1):\n                metadata = {\n                    \"source\": (\n                        f\"https://docs.google.com/spreadsheets/d/{id}/\"\n                        f\"edit?gid={sheet['properties']['sheetId']}\"\n                    ),\n                    \"title\": f\"{spreadsheet['properties']['title']} - {sheet_name}\",\n                    \"row\": i,\n                }\n                content = []\n                for j, v in enumerate(row):\n                    title = header[j].strip() if len(header) > j else \"\"\n                    content.append(f\"{title}: {v.strip()}\")\n                page_content = \"\\n\".join(content)\n                documents.append(Document(page_content=page_content, metadata=metadata))\n        return documents\n    def _load_document_from_id(self, id: str) -> Document:\n        \"\"\"Load a document from an ID.\"\"\"\n        from io import BytesIO\n        from googleapiclient.discovery import build\n        from googleapiclient.errors import HttpError\n        from googleapiclient.http import MediaIoBaseDownload\n        creds = self._load_credentials()\n        service = build(\"drive\", \"v3\", credentials=creds)\n        file = (\n            service.files()\n            .get(fileId=id, supportsAllDrives=True, fields=\"modifiedTime,name\")\n            .execute()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html"}
{"id": "455b0ef44b45-5", "text": ".execute()\n        )\n        request = service.files().export_media(fileId=id, mimeType=\"text/plain\")\n        fh = BytesIO()\n        downloader = MediaIoBaseDownload(fh, request)\n        done = False\n        try:\n            while done is False:\n                status, done = downloader.next_chunk()\n        except HttpError as e:\n            if e.resp.status == 404:\n                print(\"File not found: {}\".format(id))\n            else:\n                print(\"An error occurred: {}\".format(e))\n        text = fh.getvalue().decode(\"utf-8\")\n        metadata = {\n            \"source\": f\"https://docs.google.com/document/d/{id}/edit\",\n            \"title\": f\"{file.get('name')}\",\n            \"when\": f\"{file.get('modifiedTime')}\",\n        }\n        return Document(page_content=text, metadata=metadata)\n    def _load_documents_from_folder(\n        self, folder_id: str, *, file_types: Optional[Sequence[str]] = None\n    ) -> List[Document]:\n        \"\"\"Load documents from a folder.\"\"\"\n        from googleapiclient.discovery import build\n        creds = self._load_credentials()\n        service = build(\"drive\", \"v3\", credentials=creds)\n        files = self._fetch_files_recursive(service, folder_id)\n        # If file types filter is provided, we'll filter by the file type.\n        if file_types:\n            _files = [f for f in files if f[\"mimeType\"] in file_types]  # type: ignore\n        else:\n            _files = files\n        returns = []\n        for file in _files:\n            if file[\"trashed\"] and not self.load_trashed_files:\n                continue\n            elif file[\"mimeType\"] == \"application/vnd.google-apps.document\":", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html"}
{"id": "455b0ef44b45-6", "text": "continue\n            elif file[\"mimeType\"] == \"application/vnd.google-apps.document\":\n                returns.append(self._load_document_from_id(file[\"id\"]))  # type: ignore\n            elif file[\"mimeType\"] == \"application/vnd.google-apps.spreadsheet\":\n                returns.extend(self._load_sheet_from_id(file[\"id\"]))  # type: ignore\n            elif (\n                file[\"mimeType\"] == \"application/pdf\"\n                or self.file_loader_cls is not None\n            ):\n                returns.extend(self._load_file_from_id(file[\"id\"]))  # type: ignore\n            else:\n                pass\n        return returns\n    def _fetch_files_recursive(\n        self, service: Any, folder_id: str\n    ) -> List[Dict[str, Union[str, List[str]]]]:\n        \"\"\"Fetch all files and subfolders recursively.\"\"\"\n        results = (\n            service.files()\n            .list(\n                q=f\"'{folder_id}' in parents\",\n                pageSize=1000,\n                includeItemsFromAllDrives=True,\n                supportsAllDrives=True,\n                fields=\"nextPageToken, files(id, name, mimeType, parents, trashed)\",\n            )\n            .execute()\n        )\n        files = results.get(\"files\", [])\n        returns = []\n        for file in files:\n            if file[\"mimeType\"] == \"application/vnd.google-apps.folder\":\n                if self.recursive:\n                    returns.extend(self._fetch_files_recursive(service, file[\"id\"]))\n            else:\n                returns.append(file)\n        return returns\n    def _load_documents_from_ids(self) -> List[Document]:\n        \"\"\"Load documents from a list of IDs.\"\"\"\n        if not self.document_ids:\n            raise ValueError(\"document_ids must be set\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html"}
{"id": "455b0ef44b45-7", "text": "if not self.document_ids:\n            raise ValueError(\"document_ids must be set\")\n        return [self._load_document_from_id(doc_id) for doc_id in self.document_ids]\n    def _load_file_from_id(self, id: str) -> List[Document]:\n        \"\"\"Load a file from an ID.\"\"\"\n        from io import BytesIO\n        from googleapiclient.discovery import build\n        from googleapiclient.http import MediaIoBaseDownload\n        creds = self._load_credentials()\n        service = build(\"drive\", \"v3\", credentials=creds)\n        file = service.files().get(fileId=id, supportsAllDrives=True).execute()\n        request = service.files().get_media(fileId=id)\n        fh = BytesIO()\n        downloader = MediaIoBaseDownload(fh, request)\n        done = False\n        while done is False:\n            status, done = downloader.next_chunk()\n        if self.file_loader_cls is not None:\n            fh.seek(0)\n            loader = self.file_loader_cls(file=fh, **self.file_loader_kwargs)\n            docs = loader.load()\n            for doc in docs:\n                doc.metadata[\"source\"] = f\"https://drive.google.com/file/d/{id}/view\"\n            return docs\n        else:\n            from PyPDF2 import PdfReader\n            content = fh.getvalue()\n            pdf_reader = PdfReader(BytesIO(content))\n            return [\n                Document(\n                    page_content=page.extract_text(),\n                    metadata={\n                        \"source\": f\"https://drive.google.com/file/d/{id}/view\",\n                        \"title\": f\"{file.get('name')}\",\n                        \"page\": i,\n                    },\n                )\n                for i, page in enumerate(pdf_reader.pages)\n            ]\n    def _load_file_from_ids(self) -> List[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html"}
{"id": "455b0ef44b45-8", "text": "]\n    def _load_file_from_ids(self) -> List[Document]:\n        \"\"\"Load files from a list of IDs.\"\"\"\n        if not self.file_ids:\n            raise ValueError(\"file_ids must be set\")\n        docs = []\n        for file_id in self.file_ids:\n            docs.extend(self._load_file_from_id(file_id))\n        return docs\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        if self.folder_id:\n            return self._load_documents_from_folder(\n                self.folder_id, file_types=self.file_types\n            )\n        elif self.document_ids:\n            return self._load_documents_from_ids()\n        else:\n            return self._load_file_from_ids()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html"}
{"id": "0086821ef45d-0", "text": "Source code for langchain.document_loaders.github\nfrom abc import ABC\nfrom datetime import datetime\nfrom typing import Dict, Iterator, List, Literal, Optional, Union\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.pydantic_v1 import BaseModel, root_validator, validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class BaseGitHubLoader(BaseLoader, BaseModel, ABC):\n    \"\"\"Load `GitHub` repository Issues.\"\"\"\n    repo: str\n    \"\"\"Name of repository\"\"\"\n    access_token: str\n    \"\"\"Personal access token - see https://github.com/settings/tokens?type=beta\"\"\"\n    github_api_url: str = \"https://api.github.com\"\n    \"\"\"URL of GitHub API\"\"\"\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that access token exists in environment.\"\"\"\n        values[\"access_token\"] = get_from_dict_or_env(\n            values, \"access_token\", \"GITHUB_PERSONAL_ACCESS_TOKEN\"\n        )\n        return values\n    @property\n    def headers(self) -> Dict[str, str]:\n        return {\n            \"Accept\": \"application/vnd.github+json\",\n            \"Authorization\": f\"Bearer {self.access_token}\",\n        }\n[docs]class GitHubIssuesLoader(BaseGitHubLoader):\n    \"\"\"Load issues of a GitHub repository.\"\"\"\n    include_prs: bool = True\n    \"\"\"If True include Pull Requests in results, otherwise ignore them.\"\"\"\n    milestone: Union[int, Literal[\"*\", \"none\"], None] = None\n    \"\"\"If integer is passed, it should be a milestone's number field.\n        If the string '*' is passed, issues with any milestone are accepted.\n        If the string 'none' is passed, issues without milestones are returned.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/github.html"}
{"id": "0086821ef45d-1", "text": "If the string 'none' is passed, issues without milestones are returned.\n    \"\"\"\n    state: Optional[Literal[\"open\", \"closed\", \"all\"]] = None\n    \"\"\"Filter on issue state. Can be one of: 'open', 'closed', 'all'.\"\"\"\n    assignee: Optional[str] = None\n    \"\"\"Filter on assigned user. Pass 'none' for no user and '*' for any user.\"\"\"\n    creator: Optional[str] = None\n    \"\"\"Filter on the user that created the issue.\"\"\"\n    mentioned: Optional[str] = None\n    \"\"\"Filter on a user that's mentioned in the issue.\"\"\"\n    labels: Optional[List[str]] = None\n    \"\"\"Label names to filter one. Example: bug,ui,@high.\"\"\"\n    sort: Optional[Literal[\"created\", \"updated\", \"comments\"]] = None\n    \"\"\"What to sort results by. Can be one of: 'created', 'updated', 'comments'.\n        Default is 'created'.\"\"\"\n    direction: Optional[Literal[\"asc\", \"desc\"]] = None\n    \"\"\"The direction to sort the results by. Can be one of: 'asc', 'desc'.\"\"\"\n    since: Optional[str] = None\n    \"\"\"Only show notifications updated after the given time.\n        This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.\"\"\"\n    @validator(\"since\")\n    def validate_since(cls, v: Optional[str]) -> Optional[str]:\n        if v:\n            try:\n                datetime.strptime(v, \"%Y-%m-%dT%H:%M:%SZ\")\n            except ValueError:\n                raise ValueError(\n                    \"Invalid value for 'since'. Expected a date string in \"\n                    f\"YYYY-MM-DDTHH:MM:SSZ format. Received: {v}\"\n                )\n        return v", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/github.html"}
{"id": "0086821ef45d-2", "text": ")\n        return v\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"\n        Get issues of a GitHub repository.\n        Returns:\n            A list of Documents with attributes:\n                - page_content\n                - metadata\n                    - url\n                    - title\n                    - creator\n                    - created_at\n                    - last_update_time\n                    - closed_time\n                    - number of comments\n                    - state\n                    - labels\n                    - assignee\n                    - assignees\n                    - milestone\n                    - locked\n                    - number\n                    - is_pull_request\n        \"\"\"\n        url: Optional[str] = self.url\n        while url:\n            response = requests.get(url, headers=self.headers)\n            response.raise_for_status()\n            issues = response.json()\n            for issue in issues:\n                doc = self.parse_issue(issue)\n                if not self.include_prs and doc.metadata[\"is_pull_request\"]:\n                    continue\n                yield doc\n            if response.links and response.links.get(\"next\"):\n                url = response.links[\"next\"][\"url\"]\n            else:\n                url = None\n[docs]    def load(self) -> List[Document]:\n        \"\"\"\n        Get issues of a GitHub repository.\n        Returns:\n            A list of Documents with attributes:\n                - page_content\n                - metadata\n                    - url\n                    - title\n                    - creator\n                    - created_at\n                    - last_update_time\n                    - closed_time\n                    - number of comments\n                    - state\n                    - labels\n                    - assignee\n                    - assignees\n                    - milestone\n                    - locked\n                    - number\n                    - is_pull_request\n        \"\"\"\n        return list(self.lazy_load())\n[docs]    def parse_issue(self, issue: dict) -> Document:\n        \"\"\"Create Document objects from a list of GitHub issues.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/github.html"}
{"id": "0086821ef45d-3", "text": "\"\"\"Create Document objects from a list of GitHub issues.\"\"\"\n        metadata = {\n            \"url\": issue[\"html_url\"],\n            \"title\": issue[\"title\"],\n            \"creator\": issue[\"user\"][\"login\"],\n            \"created_at\": issue[\"created_at\"],\n            \"comments\": issue[\"comments\"],\n            \"state\": issue[\"state\"],\n            \"labels\": [label[\"name\"] for label in issue[\"labels\"]],\n            \"assignee\": issue[\"assignee\"][\"login\"] if issue[\"assignee\"] else None,\n            \"milestone\": issue[\"milestone\"][\"title\"] if issue[\"milestone\"] else None,\n            \"locked\": issue[\"locked\"],\n            \"number\": issue[\"number\"],\n            \"is_pull_request\": \"pull_request\" in issue,\n        }\n        content = issue[\"body\"] if issue[\"body\"] is not None else \"\"\n        return Document(page_content=content, metadata=metadata)\n    @property\n    def query_params(self) -> str:\n        \"\"\"Create query parameters for GitHub API.\"\"\"\n        labels = \",\".join(self.labels) if self.labels else self.labels\n        query_params_dict = {\n            \"milestone\": self.milestone,\n            \"state\": self.state,\n            \"assignee\": self.assignee,\n            \"creator\": self.creator,\n            \"mentioned\": self.mentioned,\n            \"labels\": labels,\n            \"sort\": self.sort,\n            \"direction\": self.direction,\n            \"since\": self.since,\n        }\n        query_params_list = [\n            f\"{k}={v}\" for k, v in query_params_dict.items() if v is not None\n        ]\n        query_params = \"&\".join(query_params_list)\n        return query_params\n    @property\n    def url(self) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/github.html"}
{"id": "0086821ef45d-4", "text": "return query_params\n    @property\n    def url(self) -> str:\n        \"\"\"Create URL for GitHub API.\"\"\"\n        return f\"{self.github_api_url}/repos/{self.repo}/issues?{self.query_params}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/github.html"}
{"id": "ff9ca25d2613-0", "text": "Source code for langchain.document_loaders.assemblyai\nfrom __future__ import annotations\nfrom enum import Enum\nfrom typing import TYPE_CHECKING, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nif TYPE_CHECKING:\n    import assemblyai\n[docs]class TranscriptFormat(Enum):\n    \"\"\"Transcript format to use for the document loader.\"\"\"\n    TEXT = \"text\"\n    \"\"\"One document with the transcription text\"\"\"\n    SENTENCES = \"sentences\"\n    \"\"\"Multiple documents, splits the transcription by each sentence\"\"\"\n    PARAGRAPHS = \"paragraphs\"\n    \"\"\"Multiple documents, splits the transcription by each paragraph\"\"\"\n    SUBTITLES_SRT = \"subtitles_srt\"\n    \"\"\"One document with the transcript exported in SRT subtitles format\"\"\"\n    SUBTITLES_VTT = \"subtitles_vtt\"\n    \"\"\"One document with the transcript exported in VTT subtitles format\"\"\"\n[docs]class AssemblyAIAudioTranscriptLoader(BaseLoader):\n    \"\"\"\n    Loader for AssemblyAI audio transcripts.\n    It uses the AssemblyAI API to transcribe audio files\n    and loads the transcribed text into one or more Documents,\n    depending on the specified format.\n    To use, you should have the ``assemblyai`` python package installed, and the\n    environment variable ``ASSEMBLYAI_API_KEY`` set with your API key.\n    Alternatively, the API key can also be passed as an argument.\n    Audio files can be specified via an URL or a local file path.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        *,\n        transcript_format: TranscriptFormat = TranscriptFormat.TEXT,\n        config: Optional[assemblyai.TranscriptionConfig] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/assemblyai.html"}
{"id": "ff9ca25d2613-1", "text": "config: Optional[assemblyai.TranscriptionConfig] = None,\n        api_key: Optional[str] = None,\n    ):\n        \"\"\"\n        Initializes the AssemblyAI AudioTranscriptLoader.\n        Args:\n            file_path: An URL or a local file path.\n            transcript_format: Transcript format to use.\n                See class ``TranscriptFormat`` for more info.\n            config: Transcription options and features. If ``None`` is given,\n                the Transcriber's default configuration will be used.\n            api_key: AssemblyAI API key.\n        \"\"\"\n        try:\n            import assemblyai\n        except ImportError:\n            raise ImportError(\n                \"Could not import assemblyai python package. \"\n                \"Please install it with `pip install assemblyai`.\"\n            )\n        if api_key is not None:\n            assemblyai.settings.api_key = api_key\n        self.file_path = file_path\n        self.transcript_format = transcript_format\n        self.transcriber = assemblyai.Transcriber(config=config)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Transcribes the audio file and loads the transcript into documents.\n        It uses the AssemblyAI API to transcribe the audio file and blocks until\n        the transcription is finished.\n        \"\"\"\n        transcript = self.transcriber.transcribe(self.file_path)\n        # This will raise a ValueError if no API key is set.\n        if transcript.error:\n            raise ValueError(f\"Could not transcribe file: {transcript.error}\")\n        if self.transcript_format == TranscriptFormat.TEXT:\n            return [\n                Document(\n                    page_content=transcript.text, metadata=transcript.json_response\n                )\n            ]\n        elif self.transcript_format == TranscriptFormat.SENTENCES:\n            sentences = transcript.get_sentences()\n            return [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/assemblyai.html"}
{"id": "ff9ca25d2613-2", "text": "sentences = transcript.get_sentences()\n            return [\n                Document(page_content=s.text, metadata=s.dict(exclude={\"text\"}))\n                for s in sentences\n            ]\n        elif self.transcript_format == TranscriptFormat.PARAGRAPHS:\n            paragraphs = transcript.get_paragraphs()\n            return [\n                Document(page_content=p.text, metadata=p.dict(exclude={\"text\"}))\n                for p in paragraphs\n            ]\n        elif self.transcript_format == TranscriptFormat.SUBTITLES_SRT:\n            return [Document(page_content=transcript.export_subtitles_srt())]\n        elif self.transcript_format == TranscriptFormat.SUBTITLES_VTT:\n            return [Document(page_content=transcript.export_subtitles_vtt())]\n        else:\n            raise ValueError(\"Unknown transcript format.\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/assemblyai.html"}
{"id": "6b27bf551f8b-0", "text": "Source code for langchain.document_loaders.base\n\"\"\"Abstract interface for document loader implementations.\"\"\"\nfrom abc import ABC, abstractmethod\nfrom typing import Iterator, List, Optional\nfrom langchain.document_loaders.blob_loaders import Blob\nfrom langchain.schema import Document\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter, TextSplitter\n[docs]class BaseLoader(ABC):\n    \"\"\"Interface for Document Loader.\n    Implementations should implement the lazy-loading method using generators\n    to avoid loading all Documents into memory at once.\n    The `load` method will remain as is for backwards compatibility, but its\n    implementation should be just `list(self.lazy_load())`.\n    \"\"\"\n    # Sub-classes should implement this method\n    # as return list(self.lazy_load()).\n    # This method returns a List which is materialized in memory.\n[docs]    @abstractmethod\n    def load(self) -> List[Document]:\n        \"\"\"Load data into Document objects.\"\"\"\n[docs]    def load_and_split(\n        self, text_splitter: Optional[TextSplitter] = None\n    ) -> List[Document]:\n        \"\"\"Load Documents and split into chunks. Chunks are returned as Documents.\n        Args:\n            text_splitter: TextSplitter instance to use for splitting documents.\n              Defaults to RecursiveCharacterTextSplitter.\n        Returns:\n            List of Documents.\n        \"\"\"\n        if text_splitter is None:\n            _text_splitter: TextSplitter = RecursiveCharacterTextSplitter()\n        else:\n            _text_splitter = text_splitter\n        docs = self.load()\n        return _text_splitter.split_documents(docs)\n    # Attention: This method will be upgraded into an abstractmethod once it's\n    #            implemented in all the existing subclasses.\n[docs]    def lazy_load(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/base.html"}
{"id": "6b27bf551f8b-1", "text": "#            implemented in all the existing subclasses.\n[docs]    def lazy_load(\n        self,\n    ) -> Iterator[Document]:\n        \"\"\"A lazy loader for Documents.\"\"\"\n        raise NotImplementedError(\n            f\"{self.__class__.__name__} does not implement lazy_load()\"\n        )\n[docs]class BaseBlobParser(ABC):\n    \"\"\"Abstract interface for blob parsers.\n    A blob parser provides a way to parse raw data stored in a blob into one\n    or more documents.\n    The parser can be composed with blob loaders, making it easy to reuse\n    a parser independent of how the blob was originally loaded.\n    \"\"\"\n[docs]    @abstractmethod\n    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Lazy parsing interface.\n        Subclasses are required to implement this method.\n        Args:\n            blob: Blob instance\n        Returns:\n            Generator of documents\n        \"\"\"\n[docs]    def parse(self, blob: Blob) -> List[Document]:\n        \"\"\"Eagerly parse the blob into a document or documents.\n        This is a convenience method for interactive development environment.\n        Production applications should favor the lazy_parse method instead.\n        Subclasses should generally not over-ride this parse method.\n        Args:\n            blob: Blob instance\n        Returns:\n            List of documents\n        \"\"\"\n        return list(self.lazy_parse(blob))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/base.html"}
{"id": "cdccc543a28e-0", "text": "Source code for langchain.document_loaders.hugging_face_dataset\nfrom typing import Iterator, List, Mapping, Optional, Sequence, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class HuggingFaceDatasetLoader(BaseLoader):\n    \"\"\"Load from `Hugging Face Hub` datasets.\"\"\"\n[docs]    def __init__(\n        self,\n        path: str,\n        page_content_column: str = \"text\",\n        name: Optional[str] = None,\n        data_dir: Optional[str] = None,\n        data_files: Optional[\n            Union[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]]\n        ] = None,\n        cache_dir: Optional[str] = None,\n        keep_in_memory: Optional[bool] = None,\n        save_infos: bool = False,\n        use_auth_token: Optional[Union[bool, str]] = None,\n        num_proc: Optional[int] = None,\n    ):\n        \"\"\"Initialize the HuggingFaceDatasetLoader.\n        Args:\n            path: Path or name of the dataset.\n            page_content_column: Page content column name. Default is \"text\".\n                Note: Currently the function assumes the content is a string.\n                If it is not download the dataset using huggingface library and convert\n                using the json or pandas loaders.\n                https://github.com/langchain-ai/langchain/issues/10674\n            name: Name of the dataset configuration.\n            data_dir: Data directory of the dataset configuration.\n            data_files: Path(s) to source data file(s).\n            cache_dir: Directory to read/write data.\n            keep_in_memory: Whether to copy the dataset in-memory.\n            save_infos: Save the dataset information (checksums/size/splits/...).", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html"}
{"id": "cdccc543a28e-1", "text": "save_infos: Save the dataset information (checksums/size/splits/...).\n              Default is False.\n            use_auth_token: Bearer token for remote files on the Dataset Hub.\n            num_proc: Number of processes.\n        \"\"\"\n        self.path = path\n        self.page_content_column = page_content_column\n        self.name = name\n        self.data_dir = data_dir\n        self.data_files = data_files\n        self.cache_dir = cache_dir\n        self.keep_in_memory = keep_in_memory\n        self.save_infos = save_infos\n        self.use_auth_token = use_auth_token\n        self.num_proc = num_proc\n[docs]    def lazy_load(\n        self,\n    ) -> Iterator[Document]:\n        \"\"\"Load documents lazily.\"\"\"\n        try:\n            from datasets import load_dataset\n        except ImportError:\n            raise ImportError(\n                \"Could not import datasets python package. \"\n                \"Please install it with `pip install datasets`.\"\n            )\n        dataset = load_dataset(\n            path=self.path,\n            name=self.name,\n            data_dir=self.data_dir,\n            data_files=self.data_files,\n            cache_dir=self.cache_dir,\n            keep_in_memory=self.keep_in_memory,\n            save_infos=self.save_infos,\n            use_auth_token=self.use_auth_token,\n            num_proc=self.num_proc,\n        )\n        yield from (\n            Document(\n                page_content=row.pop(self.page_content_column),\n                metadata=row,\n            )\n            for key in dataset.keys()\n            for row in dataset[key]\n        )\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html"}
{"id": "85eaef417236-0", "text": "Source code for langchain.document_loaders.image\nfrom typing import List\nfrom langchain.document_loaders.unstructured import UnstructuredFileLoader\n[docs]class UnstructuredImageLoader(UnstructuredFileLoader):\n    \"\"\"Load `PNG` and `JPG` files using `Unstructured`.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredImageLoader\n    loader = UnstructuredImageLoader(\n        \"example.png\", mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition-image\n    \"\"\"\n    def _get_elements(self) -> List:\n        from unstructured.partition.image import partition_image\n        return partition_image(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image.html"}
{"id": "89de310c4832-0", "text": "Source code for langchain.document_loaders.unstructured\n\"\"\"Loader that uses unstructured to load files.\"\"\"\nimport collections\nfrom abc import ABC, abstractmethod\nfrom typing import IO, Any, Callable, Dict, List, Optional, Sequence, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]def satisfies_min_unstructured_version(min_version: str) -> bool:\n    \"\"\"Check if the installed `Unstructured` version exceeds the minimum version\n    for the feature in question.\"\"\"\n    from unstructured.__version__ import __version__ as __unstructured_version__\n    min_version_tuple = tuple([int(x) for x in min_version.split(\".\")])\n    # NOTE(MthwRobinson) - enables the loader to work when you're using pre-release\n    # versions of unstructured like 0.4.17-dev1\n    _unstructured_version = __unstructured_version__.split(\"-\")[0]\n    unstructured_version_tuple = tuple(\n        [int(x) for x in _unstructured_version.split(\".\")]\n    )\n    return unstructured_version_tuple >= min_version_tuple\n[docs]def validate_unstructured_version(min_unstructured_version: str) -> None:\n    \"\"\"Raise an error if the `Unstructured` version does not exceed the\n    specified minimum.\"\"\"\n    if not satisfies_min_unstructured_version(min_unstructured_version):\n        raise ValueError(\n            f\"unstructured>={min_unstructured_version} is required in this loader.\"\n        )\n[docs]class UnstructuredBaseLoader(BaseLoader, ABC):\n    \"\"\"Base Loader that uses `Unstructured`.\"\"\"\n[docs]    def __init__(\n        self,\n        mode: str = \"single\",\n        post_processors: Optional[List[Callable]] = None,\n        **unstructured_kwargs: Any,\n    ):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html"}
{"id": "89de310c4832-1", "text": "**unstructured_kwargs: Any,\n    ):\n        \"\"\"Initialize with file path.\"\"\"\n        try:\n            import unstructured  # noqa:F401\n        except ImportError:\n            raise ValueError(\n                \"unstructured package not found, please install it with \"\n                \"`pip install unstructured`\"\n            )\n        _valid_modes = {\"single\", \"elements\", \"paged\"}\n        if mode not in _valid_modes:\n            raise ValueError(\n                f\"Got {mode} for `mode`, but should be one of `{_valid_modes}`\"\n            )\n        self.mode = mode\n        if not satisfies_min_unstructured_version(\"0.5.4\"):\n            if \"strategy\" in unstructured_kwargs:\n                unstructured_kwargs.pop(\"strategy\")\n        self.unstructured_kwargs = unstructured_kwargs\n        self.post_processors = post_processors or []\n    @abstractmethod\n    def _get_elements(self) -> List:\n        \"\"\"Get elements.\"\"\"\n    @abstractmethod\n    def _get_metadata(self) -> dict:\n        \"\"\"Get metadata.\"\"\"\n    def _post_process_elements(self, elements: list) -> list:\n        \"\"\"Applies post processing functions to extracted unstructured elements.\n        Post processing functions are str -> str callables are passed\n        in using the post_processors kwarg when the loader is instantiated.\"\"\"\n        for element in elements:\n            for post_processor in self.post_processors:\n                element.apply(post_processor)\n        return elements\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load file.\"\"\"\n        elements = self._get_elements()\n        self._post_process_elements(elements)\n        if self.mode == \"elements\":\n            docs: List[Document] = list()\n            for element in elements:\n                metadata = self._get_metadata()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html"}
{"id": "89de310c4832-2", "text": "for element in elements:\n                metadata = self._get_metadata()\n                # NOTE(MthwRobinson) - the attribute check is for backward compatibility\n                # with unstructured<0.4.9. The metadata attributed was added in 0.4.9.\n                if hasattr(element, \"metadata\"):\n                    metadata.update(element.metadata.to_dict())\n                if hasattr(element, \"category\"):\n                    metadata[\"category\"] = element.category\n                docs.append(Document(page_content=str(element), metadata=metadata))\n        elif self.mode == \"paged\":\n            text_dict: Dict[int, str] = {}\n            meta_dict: Dict[int, Dict] = {}\n            for idx, element in enumerate(elements):\n                metadata = self._get_metadata()\n                if hasattr(element, \"metadata\"):\n                    metadata.update(element.metadata.to_dict())\n                page_number = metadata.get(\"page_number\", 1)\n                # Check if this page_number already exists in docs_dict\n                if page_number not in text_dict:\n                    # If not, create new entry with initial text and metadata\n                    text_dict[page_number] = str(element) + \"\\n\\n\"\n                    meta_dict[page_number] = metadata\n                else:\n                    # If exists, append to text and update the metadata\n                    text_dict[page_number] += str(element) + \"\\n\\n\"\n                    meta_dict[page_number].update(metadata)\n            # Convert the dict to a list of Document objects\n            docs = [\n                Document(page_content=text_dict[key], metadata=meta_dict[key])\n                for key in text_dict.keys()\n            ]\n        elif self.mode == \"single\":\n            metadata = self._get_metadata()\n            text = \"\\n\\n\".join([str(el) for el in elements])\n            docs = [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html"}
{"id": "89de310c4832-3", "text": "docs = [Document(page_content=text, metadata=metadata)]\n        else:\n            raise ValueError(f\"mode of {self.mode} not supported.\")\n        return docs\n[docs]class UnstructuredFileLoader(UnstructuredBaseLoader):\n    \"\"\"Load files using `Unstructured`.\n    The file loader uses the\n    unstructured partition function and will automatically detect the file\n    type. You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredFileLoader\n    loader = UnstructuredFileLoader(\n        \"example.pdf\", mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition\n    \"\"\"\n[docs]    def __init__(\n        self,\n        file_path: Union[str, List[str]],\n        mode: str = \"single\",\n        **unstructured_kwargs: Any,\n    ):\n        \"\"\"Initialize with file path.\"\"\"\n        self.file_path = file_path\n        super().__init__(mode=mode, **unstructured_kwargs)\n    def _get_elements(self) -> List:\n        from unstructured.partition.auto import partition\n        return partition(filename=self.file_path, **self.unstructured_kwargs)\n    def _get_metadata(self) -> dict:\n        return {\"source\": self.file_path}\n[docs]def get_elements_from_api(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html"}
{"id": "89de310c4832-4", "text": "return {\"source\": self.file_path}\n[docs]def get_elements_from_api(\n    file_path: Union[str, List[str], None] = None,\n    file: Union[IO, Sequence[IO], None] = None,\n    api_url: str = \"https://api.unstructured.io/general/v0/general\",\n    api_key: str = \"\",\n    **unstructured_kwargs: Any,\n) -> List:\n    \"\"\"Retrieve a list of elements from the `Unstructured API`.\"\"\"\n    if isinstance(file, collections.abc.Sequence) or isinstance(file_path, list):\n        from unstructured.partition.api import partition_multiple_via_api\n        _doc_elements = partition_multiple_via_api(\n            filenames=file_path,\n            files=file,\n            api_key=api_key,\n            api_url=api_url,\n            **unstructured_kwargs,\n        )\n        elements = []\n        for _elements in _doc_elements:\n            elements.extend(_elements)\n        return elements\n    else:\n        from unstructured.partition.api import partition_via_api\n        return partition_via_api(\n            filename=file_path,\n            file=file,\n            api_key=api_key,\n            api_url=api_url,\n            **unstructured_kwargs,\n        )\n[docs]class UnstructuredAPIFileLoader(UnstructuredFileLoader):\n    \"\"\"Load files using `Unstructured` API.\n    By default, the loader makes a call to the hosted Unstructured API.\n    If you are running the unstructured API locally, you can change the\n    API rule by passing in the url parameter when you initialize the loader.\n    The hosted Unstructured API requires an API key. See\n    https://www.unstructured.io/api-key/ if you need to generate a key.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html"}
{"id": "89de310c4832-5", "text": "https://www.unstructured.io/api-key/ if you need to generate a key.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    ```python\n    from langchain.document_loaders import UnstructuredAPIFileLoader\n    loader = UnstructuredFileAPILoader(\n        \"example.pdf\", mode=\"elements\", strategy=\"fast\", api_key=\"MY_API_KEY\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition\n    https://www.unstructured.io/api-key/\n    https://github.com/Unstructured-IO/unstructured-api\n    \"\"\"\n[docs]    def __init__(\n        self,\n        file_path: Union[str, List[str]] = \"\",\n        mode: str = \"single\",\n        url: str = \"https://api.unstructured.io/general/v0/general\",\n        api_key: str = \"\",\n        **unstructured_kwargs: Any,\n    ):\n        \"\"\"Initialize with file path.\"\"\"\n        validate_unstructured_version(min_unstructured_version=\"0.10.15\")\n        self.url = url\n        self.api_key = api_key\n        super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)\n    def _get_metadata(self) -> dict:\n        return {\"source\": self.file_path}\n    def _get_elements(self) -> List:\n        return get_elements_from_api(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html"}
{"id": "89de310c4832-6", "text": "def _get_elements(self) -> List:\n        return get_elements_from_api(\n            file_path=self.file_path,\n            api_key=self.api_key,\n            api_url=self.url,\n            **self.unstructured_kwargs,\n        )\n[docs]class UnstructuredFileIOLoader(UnstructuredBaseLoader):\n    \"\"\"Load files using `Unstructured`.\n    The file loader\n    uses the unstructured partition function and will automatically detect the file\n    type. You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredFileIOLoader\n    with open(\"example.pdf\", \"rb\") as f:\n        loader = UnstructuredFileIOLoader(\n            f, mode=\"elements\", strategy=\"fast\",\n        )\n        docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition\n    \"\"\"\n[docs]    def __init__(\n        self,\n        file: Union[IO, Sequence[IO]],\n        mode: str = \"single\",\n        **unstructured_kwargs: Any,\n    ):\n        \"\"\"Initialize with file path.\"\"\"\n        self.file = file\n        super().__init__(mode=mode, **unstructured_kwargs)\n    def _get_elements(self) -> List:\n        from unstructured.partition.auto import partition\n        return partition(file=self.file, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html"}
{"id": "89de310c4832-7", "text": "return partition(file=self.file, **self.unstructured_kwargs)\n    def _get_metadata(self) -> dict:\n        return {}\n[docs]class UnstructuredAPIFileIOLoader(UnstructuredFileIOLoader):\n    \"\"\"Load files using `Unstructured` API.\n    By default, the loader makes a call to the hosted Unstructured API.\n    If you are running the unstructured API locally, you can change the\n    API rule by passing in the url parameter when you initialize the loader.\n    The hosted Unstructured API requires an API key. See\n    https://www.unstructured.io/api-key/ if you need to generate a key.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredAPIFileLoader\n    with open(\"example.pdf\", \"rb\") as f:\n        loader = UnstructuredFileAPILoader(\n            f, mode=\"elements\", strategy=\"fast\", api_key=\"MY_API_KEY\",\n        )\n        docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition\n    https://www.unstructured.io/api-key/\n    https://github.com/Unstructured-IO/unstructured-api\n    \"\"\"\n[docs]    def __init__(\n        self,\n        file: Union[IO, Sequence[IO]],\n        mode: str = \"single\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html"}
{"id": "89de310c4832-8", "text": "mode: str = \"single\",\n        url: str = \"https://api.unstructured.io/general/v0/general\",\n        api_key: str = \"\",\n        **unstructured_kwargs: Any,\n    ):\n        \"\"\"Initialize with file path.\"\"\"\n        if isinstance(file, collections.abc.Sequence):\n            validate_unstructured_version(min_unstructured_version=\"0.6.3\")\n        if file:\n            validate_unstructured_version(min_unstructured_version=\"0.6.2\")\n        self.url = url\n        self.api_key = api_key\n        super().__init__(file=file, mode=mode, **unstructured_kwargs)\n    def _get_elements(self) -> List:\n        return get_elements_from_api(\n            file=self.file,\n            api_key=self.api_key,\n            api_url=self.url,\n            **self.unstructured_kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html"}
{"id": "ef452e6266a6-0", "text": "Source code for langchain.document_loaders.bigquery\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utilities.vertexai import get_client_info\nif TYPE_CHECKING:\n    from google.auth.credentials import Credentials\n[docs]class BigQueryLoader(BaseLoader):\n    \"\"\"Load from the Google Cloud Platform `BigQuery`.\n    Each document represents one row of the result. The `page_content_columns`\n    are written into the `page_content` of the document. The `metadata_columns`\n    are written into the `metadata` of the document. By default, all columns\n    are written into the `page_content` and none into the `metadata`.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        query: str,\n        project: Optional[str] = None,\n        page_content_columns: Optional[List[str]] = None,\n        metadata_columns: Optional[List[str]] = None,\n        credentials: Optional[Credentials] = None,\n    ):\n        \"\"\"Initialize BigQuery document loader.\n        Args:\n            query: The query to run in BigQuery.\n            project: Optional. The project to run the query in.\n            page_content_columns: Optional. The columns to write into the `page_content`\n                of the document.\n            metadata_columns: Optional. The columns to write into the `metadata` of the\n                document.\n            credentials : google.auth.credentials.Credentials, optional\n              Credentials for accessing Google APIs. Use this parameter to override\n                default credentials, such as to use Compute Engine\n                (`google.auth.compute_engine.Credentials`) or Service Account\n                (`google.oauth2.service_account.Credentials`) credentials directly.\n        \"\"\"\n        self.query = query", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html"}
{"id": "ef452e6266a6-1", "text": "\"\"\"\n        self.query = query\n        self.project = project\n        self.page_content_columns = page_content_columns\n        self.metadata_columns = metadata_columns\n        self.credentials = credentials\n[docs]    def load(self) -> List[Document]:\n        try:\n            from google.cloud import bigquery\n        except ImportError as ex:\n            raise ImportError(\n                \"Could not import google-cloud-bigquery python package. \"\n                \"Please install it with `pip install google-cloud-bigquery`.\"\n            ) from ex\n        bq_client = bigquery.Client(\n            credentials=self.credentials,\n            project=self.project,\n            client_info=get_client_info(module=\"bigquery\"),\n        )\n        if not bq_client.project:\n            error_desc = (\n                \"GCP project for Big Query is not set! Either provide a \"\n                \"`project` argument during BigQueryLoader instantiation, \"\n                \"or set a default project with `gcloud config set project` \"\n                \"command.\"\n            )\n            raise ValueError(error_desc)\n        query_result = bq_client.query(self.query).result()\n        docs: List[Document] = []\n        page_content_columns = self.page_content_columns\n        metadata_columns = self.metadata_columns\n        if page_content_columns is None:\n            page_content_columns = [column.name for column in query_result.schema]\n        if metadata_columns is None:\n            metadata_columns = []\n        for row in query_result:\n            page_content = \"\\n\".join(\n                f\"{k}: {v}\" for k, v in row.items() if k in page_content_columns\n            )\n            metadata = {k: v for k, v in row.items() if k in metadata_columns}\n            doc = Document(page_content=page_content, metadata=metadata)\n            docs.append(doc)\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html"}
{"id": "487285237498-0", "text": "Source code for langchain.document_loaders.csv_loader\nimport csv\nfrom io import TextIOWrapper\nfrom typing import Any, Dict, List, Optional, Sequence\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.helpers import detect_file_encodings\nfrom langchain.document_loaders.unstructured import (\n    UnstructuredFileLoader,\n    validate_unstructured_version,\n)\n[docs]class CSVLoader(BaseLoader):\n    \"\"\"Load a `CSV` file into a list of Documents.\n    Each document represents one row of the CSV file. Every row is converted into a\n    key/value pair and outputted to a new line in the document's page_content.\n    The source for each document loaded from csv is set to the value of the\n    `file_path` argument for all documents by default.\n    You can override this by setting the `source_column` argument to the\n    name of a column in the CSV file.\n    The source of each document will then be set to the value of the column\n    with the name specified in `source_column`.\n    Output Example:\n        .. code-block:: txt\n            column1: value1\n            column2: value2\n            column3: value3\n    \"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        source_column: Optional[str] = None,\n        metadata_columns: Sequence[str] = (),\n        csv_args: Optional[Dict] = None,\n        encoding: Optional[str] = None,\n        autodetect_encoding: bool = False,\n    ):\n        \"\"\"\n        Args:\n            file_path: The path to the CSV file.\n            source_column: The name of the column in the CSV file to use as the source.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html"}
{"id": "487285237498-1", "text": "source_column: The name of the column in the CSV file to use as the source.\n              Optional. Defaults to None.\n            metadata_columns: A sequence of column names to use as metadata. Optional.\n            csv_args: A dictionary of arguments to pass to the csv.DictReader.\n              Optional. Defaults to None.\n            encoding: The encoding of the CSV file. Optional. Defaults to None.\n            autodetect_encoding: Whether to try to autodetect the file encoding.\n        \"\"\"\n        self.file_path = file_path\n        self.source_column = source_column\n        self.metadata_columns = metadata_columns\n        self.encoding = encoding\n        self.csv_args = csv_args or {}\n        self.autodetect_encoding = autodetect_encoding\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load data into document objects.\"\"\"\n        docs = []\n        try:\n            with open(self.file_path, newline=\"\", encoding=self.encoding) as csvfile:\n                docs = self.__read_file(csvfile)\n        except UnicodeDecodeError as e:\n            if self.autodetect_encoding:\n                detected_encodings = detect_file_encodings(self.file_path)\n                for encoding in detected_encodings:\n                    try:\n                        with open(\n                            self.file_path, newline=\"\", encoding=encoding.encoding\n                        ) as csvfile:\n                            docs = self.__read_file(csvfile)\n                            break\n                    except UnicodeDecodeError:\n                        continue\n            else:\n                raise RuntimeError(f\"Error loading {self.file_path}\") from e\n        except Exception as e:\n            raise RuntimeError(f\"Error loading {self.file_path}\") from e\n        return docs\n    def __read_file(self, csvfile: TextIOWrapper) -> List[Document]:\n        docs = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html"}
{"id": "487285237498-2", "text": "docs = []\n        csv_reader = csv.DictReader(csvfile, **self.csv_args)  # type: ignore\n        for i, row in enumerate(csv_reader):\n            try:\n                source = (\n                    row[self.source_column]\n                    if self.source_column is not None\n                    else self.file_path\n                )\n            except KeyError:\n                raise ValueError(\n                    f\"Source column '{self.source_column}' not found in CSV file.\"\n                )\n            content = \"\\n\".join(\n                f\"{k.strip()}: {v.strip() if v is not None else v}\"\n                for k, v in row.items()\n                if k not in self.metadata_columns\n            )\n            metadata = {\"source\": source, \"row\": i}\n            for col in self.metadata_columns:\n                try:\n                    metadata[col] = row[col]\n                except KeyError:\n                    raise ValueError(f\"Metadata column '{col}' not found in CSV file.\")\n            doc = Document(page_content=content, metadata=metadata)\n            docs.append(doc)\n        return docs\n[docs]class UnstructuredCSVLoader(UnstructuredFileLoader):\n    \"\"\"Load `CSV` files using `Unstructured`.\n    Like other\n    Unstructured loaders, UnstructuredCSVLoader can be used in both\n    \"single\" and \"elements\" mode. If you use the loader in \"elements\"\n    mode, the CSV file will be a single Unstructured Table element.\n    If you use the loader in \"elements\" mode, an HTML representation\n    of the table will be available in the \"text_as_html\" key in the\n    document metadata.\n    Examples\n    --------\n    from langchain.document_loaders.csv_loader import UnstructuredCSVLoader\n    loader = UnstructuredCSVLoader(\"stanley-cups.csv\", mode=\"elements\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html"}
{"id": "487285237498-3", "text": "loader = UnstructuredCSVLoader(\"stanley-cups.csv\", mode=\"elements\")\n    docs = loader.load()\n    \"\"\"\n[docs]    def __init__(\n        self, file_path: str, mode: str = \"single\", **unstructured_kwargs: Any\n    ):\n        \"\"\"\n        Args:\n            file_path: The path to the CSV file.\n            mode: The mode to use when loading the CSV file.\n              Optional. Defaults to \"single\".\n            **unstructured_kwargs: Keyword arguments to pass to unstructured.\n        \"\"\"\n        validate_unstructured_version(min_unstructured_version=\"0.6.8\")\n        super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)\n    def _get_elements(self) -> List:\n        from unstructured.partition.csv import partition_csv\n        return partition_csv(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html"}
{"id": "3742c416aa05-0", "text": "Source code for langchain.document_loaders.azure_blob_storage_file\nimport os\nimport tempfile\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.unstructured import UnstructuredFileLoader\n[docs]class AzureBlobStorageFileLoader(BaseLoader):\n    \"\"\"Load from `Azure Blob Storage` files.\"\"\"\n[docs]    def __init__(self, conn_str: str, container: str, blob_name: str):\n        \"\"\"Initialize with connection string, container and blob name.\"\"\"\n        self.conn_str = conn_str\n        \"\"\"Connection string for Azure Blob Storage.\"\"\"\n        self.container = container\n        \"\"\"Container name.\"\"\"\n        self.blob = blob_name\n        \"\"\"Blob name.\"\"\"\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        try:\n            from azure.storage.blob import BlobClient\n        except ImportError as exc:\n            raise ImportError(\n                \"Could not import azure storage blob python package. \"\n                \"Please install it with `pip install azure-storage-blob`.\"\n            ) from exc\n        client = BlobClient.from_connection_string(\n            conn_str=self.conn_str, container_name=self.container, blob_name=self.blob\n        )\n        with tempfile.TemporaryDirectory() as temp_dir:\n            file_path = f\"{temp_dir}/{self.container}/{self.blob}\"\n            os.makedirs(os.path.dirname(file_path), exist_ok=True)\n            with open(f\"{file_path}\", \"wb\") as file:\n                blob_data = client.download_blob()\n                blob_data.readinto(file)\n            loader = UnstructuredFileLoader(file_path)\n            return loader.load()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/azure_blob_storage_file.html"}
{"id": "d29522d9d129-0", "text": "Source code for langchain.document_loaders.facebook_chat\nimport datetime\nimport json\nfrom pathlib import Path\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]def concatenate_rows(row: dict) -> str:\n    \"\"\"Combine message information in a readable format ready to be used.\n    Args:\n        row: dictionary containing message information.\n    \"\"\"\n    sender = row[\"sender_name\"]\n    text = row[\"content\"]\n    date = datetime.datetime.fromtimestamp(row[\"timestamp_ms\"] / 1000).strftime(\n        \"%Y-%m-%d %H:%M:%S\"\n    )\n    return f\"{sender} on {date}: {text}\\n\\n\"\n[docs]class FacebookChatLoader(BaseLoader):\n    \"\"\"Load `Facebook Chat` messages directory dump.\"\"\"\n[docs]    def __init__(self, path: str):\n        \"\"\"Initialize with a path.\"\"\"\n        self.file_path = path\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        p = Path(self.file_path)\n        with open(p, encoding=\"utf8\") as f:\n            d = json.load(f)\n        text = \"\".join(\n            concatenate_rows(message)\n            for message in d[\"messages\"]\n            if message.get(\"content\") and isinstance(message[\"content\"], str)\n        )\n        metadata = {\"source\": str(p)}\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/facebook_chat.html"}
{"id": "cab7f6bb711f-0", "text": "Source code for langchain.document_loaders.url_playwright\n\"\"\"Loader that uses Playwright to load a page, then uses unstructured to load the html.\n\"\"\"\nimport logging\nfrom abc import ABC, abstractmethod\nfrom typing import TYPE_CHECKING, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nif TYPE_CHECKING:\n    from playwright.async_api import Browser as AsyncBrowser\n    from playwright.async_api import Page as AsyncPage\n    from playwright.async_api import Response as AsyncResponse\n    from playwright.sync_api import Browser, Page, Response\nlogger = logging.getLogger(__name__)\n[docs]class PlaywrightEvaluator(ABC):\n    \"\"\"Abstract base class for all evaluators.\n    Each evaluator should take a page, a browser instance, and a response\n    object, process the page as necessary, and return the resulting text.\n    \"\"\"\n[docs]    @abstractmethod\n    def evaluate(self, page: \"Page\", browser: \"Browser\", response: \"Response\") -> str:\n        \"\"\"Synchronously process the page and return the resulting text.\n        Args:\n            page: The page to process.\n            browser: The browser instance.\n            response: The response from page.goto().\n        Returns:\n            text: The text content of the page.\n        \"\"\"\n        pass\n[docs]    @abstractmethod\n    async def evaluate_async(\n        self, page: \"AsyncPage\", browser: \"AsyncBrowser\", response: \"AsyncResponse\"\n    ) -> str:\n        \"\"\"Asynchronously process the page and return the resulting text.\n        Args:\n            page: The page to process.\n            browser: The browser instance.\n            response: The response from page.goto().\n        Returns:\n            text: The text content of the page.\n        \"\"\"\n        pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html"}
{"id": "cab7f6bb711f-1", "text": "text: The text content of the page.\n        \"\"\"\n        pass\n[docs]class UnstructuredHtmlEvaluator(PlaywrightEvaluator):\n    \"\"\"Evaluates the page HTML content using the `unstructured` library.\"\"\"\n[docs]    def __init__(self, remove_selectors: Optional[List[str]] = None):\n        \"\"\"Initialize UnstructuredHtmlEvaluator.\"\"\"\n        try:\n            import unstructured  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"unstructured package not found, please install it with \"\n                \"`pip install unstructured`\"\n            )\n        self.remove_selectors = remove_selectors\n[docs]    def evaluate(self, page: \"Page\", browser: \"Browser\", response: \"Response\") -> str:\n        \"\"\"Synchronously process the HTML content of the page.\"\"\"\n        from unstructured.partition.html import partition_html\n        for selector in self.remove_selectors or []:\n            elements = page.locator(selector).all()\n            for element in elements:\n                if element.is_visible():\n                    element.evaluate(\"element => element.remove()\")\n        page_source = page.content()\n        elements = partition_html(text=page_source)\n        return \"\\n\\n\".join([str(el) for el in elements])\n[docs]    async def evaluate_async(\n        self, page: \"AsyncPage\", browser: \"AsyncBrowser\", response: \"AsyncResponse\"\n    ) -> str:\n        \"\"\"Asynchronously process the HTML content of the page.\"\"\"\n        from unstructured.partition.html import partition_html\n        for selector in self.remove_selectors or []:\n            elements = await page.locator(selector).all()\n            for element in elements:\n                if await element.is_visible():\n                    await element.evaluate(\"element => element.remove()\")\n        page_source = await page.content()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html"}
{"id": "cab7f6bb711f-2", "text": "page_source = await page.content()\n        elements = partition_html(text=page_source)\n        return \"\\n\\n\".join([str(el) for el in elements])\n[docs]class PlaywrightURLLoader(BaseLoader):\n    \"\"\"Load `HTML` pages with `Playwright` and parse with `Unstructured`.\n    This is useful for loading pages that require javascript to render.\n    Attributes:\n        urls (List[str]): List of URLs to load.\n        continue_on_failure (bool): If True, continue loading other URLs on failure.\n        headless (bool): If True, the browser will run in headless mode.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        urls: List[str],\n        continue_on_failure: bool = True,\n        headless: bool = True,\n        remove_selectors: Optional[List[str]] = None,\n        evaluator: Optional[PlaywrightEvaluator] = None,\n    ):\n        \"\"\"Load a list of URLs using Playwright.\"\"\"\n        try:\n            import playwright  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"playwright package not found, please install it with \"\n                \"`pip install playwright`\"\n            )\n        self.urls = urls\n        self.continue_on_failure = continue_on_failure\n        self.headless = headless\n        if remove_selectors and evaluator:\n            raise ValueError(\n                \"`remove_selectors` and `evaluator` cannot be both not None\"\n            )\n        # Use the provided evaluator, if any, otherwise, use the default.\n        self.evaluator = evaluator or UnstructuredHtmlEvaluator(remove_selectors)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load the specified URLs using Playwright and create Document instances.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html"}
{"id": "cab7f6bb711f-3", "text": "\"\"\"Load the specified URLs using Playwright and create Document instances.\n        Returns:\n            List[Document]: A list of Document instances with loaded content.\n        \"\"\"\n        from playwright.sync_api import sync_playwright\n        docs: List[Document] = list()\n        with sync_playwright() as p:\n            browser = p.chromium.launch(headless=self.headless)\n            for url in self.urls:\n                try:\n                    page = browser.new_page()\n                    response = page.goto(url)\n                    if response is None:\n                        raise ValueError(f\"page.goto() returned None for url {url}\")\n                    text = self.evaluator.evaluate(page, browser, response)\n                    metadata = {\"source\": url}\n                    docs.append(Document(page_content=text, metadata=metadata))\n                except Exception as e:\n                    if self.continue_on_failure:\n                        logger.error(\n                            f\"Error fetching or processing {url}, exception: {e}\"\n                        )\n                    else:\n                        raise e\n            browser.close()\n        return docs\n[docs]    async def aload(self) -> List[Document]:\n        \"\"\"Load the specified URLs with Playwright and create Documents asynchronously.\n        Use this function when in a jupyter notebook environment.\n        Returns:\n            List[Document]: A list of Document instances with loaded content.\n        \"\"\"\n        from playwright.async_api import async_playwright\n        docs: List[Document] = list()\n        async with async_playwright() as p:\n            browser = await p.chromium.launch(headless=self.headless)\n            for url in self.urls:\n                try:\n                    page = await browser.new_page()\n                    response = await page.goto(url)\n                    if response is None:\n                        raise ValueError(f\"page.goto() returned None for url {url}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html"}
{"id": "cab7f6bb711f-4", "text": "raise ValueError(f\"page.goto() returned None for url {url}\")\n                    text = await self.evaluator.evaluate_async(page, browser, response)\n                    metadata = {\"source\": url}\n                    docs.append(Document(page_content=text, metadata=metadata))\n                except Exception as e:\n                    if self.continue_on_failure:\n                        logger.error(\n                            f\"Error fetching or processing {url}, exception: {e}\"\n                        )\n                    else:\n                        raise e\n            await browser.close()\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html"}
{"id": "a3ca78310b64-0", "text": "Source code for langchain.document_loaders.datadog_logs\nfrom datetime import datetime, timedelta\nfrom typing import List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class DatadogLogsLoader(BaseLoader):\n    \"\"\"Load `Datadog` logs.\n    Logs are written into the `page_content` and into the `metadata`.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        query: str,\n        api_key: str,\n        app_key: str,\n        from_time: Optional[int] = None,\n        to_time: Optional[int] = None,\n        limit: int = 100,\n    ) -> None:\n        \"\"\"Initialize Datadog document loader.\n        Requirements:\n            - Must have datadog_api_client installed. Install with `pip install datadog_api_client`.\n        Args:\n            query: The query to run in Datadog.\n            api_key: The Datadog API key.\n            app_key: The Datadog APP key.\n            from_time: Optional. The start of the time range to query.\n                Supports date math and regular timestamps (milliseconds) like '1688732708951'\n                Defaults to 20 minutes ago.\n            to_time: Optional. The end of the time range to query.\n                Supports date math and regular timestamps (milliseconds) like '1688732708951'\n                Defaults to now.\n            limit: The maximum number of logs to return.\n                Defaults to 100.\n        \"\"\"  # noqa: E501\n        try:\n            from datadog_api_client import Configuration\n        except ImportError as ex:\n            raise ImportError(\n                \"Could not import datadog_api_client python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/datadog_logs.html"}
{"id": "a3ca78310b64-1", "text": "raise ImportError(\n                \"Could not import datadog_api_client python package. \"\n                \"Please install it with `pip install datadog_api_client`.\"\n            ) from ex\n        self.query = query\n        configuration = Configuration()\n        configuration.api_key[\"apiKeyAuth\"] = api_key\n        configuration.api_key[\"appKeyAuth\"] = app_key\n        self.configuration = configuration\n        self.from_time = from_time\n        self.to_time = to_time\n        self.limit = limit\n[docs]    def parse_log(self, log: dict) -> Document:\n        \"\"\"\n        Create Document objects from Datadog log items.\n        \"\"\"\n        attributes = log.get(\"attributes\", {})\n        metadata = {\n            \"id\": log.get(\"id\", \"\"),\n            \"status\": attributes.get(\"status\"),\n            \"service\": attributes.get(\"service\", \"\"),\n            \"tags\": attributes.get(\"tags\", []),\n            \"timestamp\": attributes.get(\"timestamp\", \"\"),\n        }\n        message = attributes.get(\"message\", \"\")\n        inside_attributes = attributes.get(\"attributes\", {})\n        content_dict = {**inside_attributes, \"message\": message}\n        content = \", \".join(f\"{k}: {v}\" for k, v in content_dict.items())\n        return Document(page_content=content, metadata=metadata)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"\n        Get logs from Datadog.\n        Returns:\n            A list of Document objects.\n                - page_content\n                - metadata\n                    - id\n                    - service\n                    - status\n                    - tags\n                    - timestamp\n        \"\"\"\n        try:\n            from datadog_api_client import ApiClient\n            from datadog_api_client.v2.api.logs_api import LogsApi", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/datadog_logs.html"}
{"id": "a3ca78310b64-2", "text": "from datadog_api_client.v2.api.logs_api import LogsApi\n            from datadog_api_client.v2.model.logs_list_request import LogsListRequest\n            from datadog_api_client.v2.model.logs_list_request_page import (\n                LogsListRequestPage,\n            )\n            from datadog_api_client.v2.model.logs_query_filter import LogsQueryFilter\n            from datadog_api_client.v2.model.logs_sort import LogsSort\n        except ImportError as ex:\n            raise ImportError(\n                \"Could not import datadog_api_client python package. \"\n                \"Please install it with `pip install datadog_api_client`.\"\n            ) from ex\n        now = datetime.now()\n        twenty_minutes_before = now - timedelta(minutes=20)\n        now_timestamp = int(now.timestamp() * 1000)\n        twenty_minutes_before_timestamp = int(twenty_minutes_before.timestamp() * 1000)\n        _from = (\n            self.from_time\n            if self.from_time is not None\n            else twenty_minutes_before_timestamp\n        )\n        body = LogsListRequest(\n            filter=LogsQueryFilter(\n                query=self.query,\n                _from=_from,\n                to=f\"{self.to_time if self.to_time is not None else now_timestamp}\",\n            ),\n            sort=LogsSort.TIMESTAMP_ASCENDING,\n            page=LogsListRequestPage(\n                limit=self.limit,\n            ),\n        )\n        with ApiClient(configuration=self.configuration) as api_client:\n            api_instance = LogsApi(api_client)\n            response = api_instance.list_logs(body=body).to_dict()\n        docs: List[Document] = []\n        for row in response[\"data\"]:\n            docs.append(self.parse_log(row))\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/datadog_logs.html"}
{"id": "91465de86299-0", "text": "Source code for langchain.document_loaders.iugu\nimport json\nimport urllib.request\nfrom typing import List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utils import get_from_env, stringify_dict\nIUGU_ENDPOINTS = {\n    \"invoices\": \"https://api.iugu.com/v1/invoices\",\n    \"customers\": \"https://api.iugu.com/v1/customers\",\n    \"charges\": \"https://api.iugu.com/v1/charges\",\n    \"subscriptions\": \"https://api.iugu.com/v1/subscriptions\",\n    \"plans\": \"https://api.iugu.com/v1/plans\",\n}\n[docs]class IuguLoader(BaseLoader):\n    \"\"\"Load from `IUGU`.\"\"\"\n[docs]    def __init__(self, resource: str, api_token: Optional[str] = None) -> None:\n        \"\"\"Initialize the IUGU resource.\n        Args:\n            resource: The name of the resource to fetch.\n            api_token: The IUGU API token to use.\n        \"\"\"\n        self.resource = resource\n        api_token = api_token or get_from_env(\"api_token\", \"IUGU_API_TOKEN\")\n        self.headers = {\"Authorization\": f\"Bearer {api_token}\"}\n    def _make_request(self, url: str) -> List[Document]:\n        request = urllib.request.Request(url, headers=self.headers)\n        with urllib.request.urlopen(request) as response:\n            json_data = json.loads(response.read().decode())\n            text = stringify_dict(json_data)\n            metadata = {\"source\": url}\n            return [Document(page_content=text, metadata=metadata)]\n    def _get_resource(self) -> List[Document]:\n        endpoint = IUGU_ENDPOINTS.get(self.resource)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/iugu.html"}
{"id": "91465de86299-1", "text": "endpoint = IUGU_ENDPOINTS.get(self.resource)\n        if endpoint is None:\n            return []\n        return self._make_request(endpoint)\n[docs]    def load(self) -> List[Document]:\n        return self._get_resource()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/iugu.html"}
{"id": "fae139dea570-0", "text": "Source code for langchain.document_loaders.mongodb\nimport asyncio\nimport logging\nfrom typing import Dict, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n[docs]class MongodbLoader(BaseLoader):\n    \"\"\"Load MongoDB documents.\"\"\"\n[docs]    def __init__(\n        self,\n        connection_string: str,\n        db_name: str,\n        collection_name: str,\n        *,\n        filter_criteria: Optional[Dict] = None,\n    ) -> None:\n        try:\n            from motor.motor_asyncio import AsyncIOMotorClient\n        except ImportError as e:\n            raise ImportError(\n                \"Cannot import from motor, please install with `pip install motor`.\"\n            ) from e\n        if not connection_string:\n            raise ValueError(\"connection_string must be provided.\")\n        if not db_name:\n            raise ValueError(\"db_name must be provided.\")\n        if not collection_name:\n            raise ValueError(\"collection_name must be provided.\")\n        self.client = AsyncIOMotorClient(connection_string)\n        self.db_name = db_name\n        self.collection_name = collection_name\n        self.filter_criteria = filter_criteria or {}\n        self.db = self.client.get_database(db_name)\n        self.collection = self.db.get_collection(collection_name)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load data into Document objects.\n        Attention:\n        This implementation starts an asyncio event loop which\n        will only work if running in a sync env. In an async env, it should\n        fail since there is already an event loop running.\n        This code should be updated to kick off the event loop from a separate\n        thread if running within an async context.\n        \"\"\"\n        return asyncio.run(self.aload())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mongodb.html"}
{"id": "fae139dea570-1", "text": "\"\"\"\n        return asyncio.run(self.aload())\n[docs]    async def aload(self) -> List[Document]:\n        \"\"\"Load data into Document objects.\"\"\"\n        result = []\n        total_docs = await self.collection.count_documents(self.filter_criteria)\n        async for doc in self.collection.find(self.filter_criteria):\n            metadata = {\n                \"database\": self.db_name,\n                \"collection\": self.collection_name,\n            }\n            result.append(Document(page_content=str(doc), metadata=metadata))\n        if len(result) != total_docs:\n            logger.warning(\n                f\"Only partial collection of documents returned. Loaded {len(result)} \"\n                f\"docs, expected {total_docs}.\"\n            )\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mongodb.html"}
{"id": "bc3330ab035e-0", "text": "Source code for langchain.document_loaders.obsidian\nimport logging\nimport re\nfrom pathlib import Path\nfrom typing import List\nimport yaml\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n[docs]class ObsidianLoader(BaseLoader):\n    \"\"\"Load `Obsidian` files from directory.\"\"\"\n    FRONT_MATTER_REGEX = re.compile(r\"^---\\n(.*?)\\n---\\n\", re.DOTALL)\n    TAG_REGEX = re.compile(r\"[^\\S\\/]#([a-zA-Z_]+[-_/\\w]*)\")\n    DATAVIEW_LINE_REGEX = re.compile(r\"^\\s*(\\w+)::\\s*(.*)$\", re.MULTILINE)\n    DATAVIEW_INLINE_BRACKET_REGEX = re.compile(r\"\\[(\\w+)::\\s*(.*)\\]\", re.MULTILINE)\n    DATAVIEW_INLINE_PAREN_REGEX = re.compile(r\"\\((\\w+)::\\s*(.*)\\)\", re.MULTILINE)\n[docs]    def __init__(\n        self, path: str, encoding: str = \"UTF-8\", collect_metadata: bool = True\n    ):\n        \"\"\"Initialize with a path.\n        Args:\n            path: Path to the directory containing the Obsidian files.\n            encoding: Charset encoding, defaults to \"UTF-8\"\n            collect_metadata: Whether to collect metadata from the front matter.\n                Defaults to True.\n        \"\"\"\n        self.file_path = path\n        self.encoding = encoding\n        self.collect_metadata = collect_metadata\n    def _parse_front_matter(self, content: str) -> dict:\n        \"\"\"Parse front matter metadata from the content and return it as a dict.\"\"\"\n        if not self.collect_metadata:\n            return {}\n        match = self.FRONT_MATTER_REGEX.search(content)\n        if not match:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obsidian.html"}
{"id": "bc3330ab035e-1", "text": "match = self.FRONT_MATTER_REGEX.search(content)\n        if not match:\n            return {}\n        try:\n            front_matter = yaml.safe_load(match.group(1))\n            # If tags are a string, split them into a list\n            if \"tags\" in front_matter and isinstance(front_matter[\"tags\"], str):\n                front_matter[\"tags\"] = front_matter[\"tags\"].split(\", \")\n            return front_matter\n        except yaml.parser.ParserError:\n            logger.warning(\"Encountered non-yaml frontmatter\")\n            return {}\n    def _to_langchain_compatible_metadata(self, metadata: dict) -> dict:\n        \"\"\"Convert a dictionary to a compatible with langchain.\"\"\"\n        result = {}\n        for key, value in metadata.items():\n            if type(value) in {str, int, float}:\n                result[key] = value\n            else:\n                result[key] = str(value)\n        return result\n    def _parse_document_tags(self, content: str) -> set:\n        \"\"\"Return a set of all tags in within the document.\"\"\"\n        if not self.collect_metadata:\n            return set()\n        match = self.TAG_REGEX.findall(content)\n        if not match:\n            return set()\n        return {tag for tag in match}\n    def _parse_dataview_fields(self, content: str) -> dict:\n        \"\"\"Parse obsidian dataview plugin fields from the content and return it\n        as a dict.\"\"\"\n        if not self.collect_metadata:\n            return {}\n        return {\n            **{\n                match[0]: match[1]\n                for match in self.DATAVIEW_LINE_REGEX.findall(content)\n            },\n            **{\n                match[0]: match[1]\n                for match in self.DATAVIEW_INLINE_PAREN_REGEX.findall(content)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obsidian.html"}
{"id": "bc3330ab035e-2", "text": "for match in self.DATAVIEW_INLINE_PAREN_REGEX.findall(content)\n            },\n            **{\n                match[0]: match[1]\n                for match in self.DATAVIEW_INLINE_BRACKET_REGEX.findall(content)\n            },\n        }\n    def _remove_front_matter(self, content: str) -> str:\n        \"\"\"Remove front matter metadata from the given content.\"\"\"\n        if not self.collect_metadata:\n            return content\n        return self.FRONT_MATTER_REGEX.sub(\"\", content)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        paths = list(Path(self.file_path).glob(\"**/*.md\"))\n        docs = []\n        for path in paths:\n            with open(path, encoding=self.encoding) as f:\n                text = f.read()\n            front_matter = self._parse_front_matter(text)\n            tags = self._parse_document_tags(text)\n            dataview_fields = self._parse_dataview_fields(text)\n            text = self._remove_front_matter(text)\n            metadata = {\n                \"source\": str(path.name),\n                \"path\": str(path),\n                \"created\": path.stat().st_ctime,\n                \"last_modified\": path.stat().st_mtime,\n                \"last_accessed\": path.stat().st_atime,\n                **self._to_langchain_compatible_metadata(front_matter),\n                **dataview_fields,\n            }\n            if tags or front_matter.get(\"tags\"):\n                metadata[\"tags\"] = \",\".join(\n                    tags | set(front_matter.get(\"tags\", []) or [])\n                )\n            docs.append(Document(page_content=text, metadata=metadata))\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obsidian.html"}
{"id": "7f601a5fb302-0", "text": "Source code for langchain.document_loaders.confluence\nimport logging\nfrom enum import Enum\nfrom io import BytesIO\nfrom typing import Any, Callable, Dict, List, Optional, Union\nimport requests\nfrom tenacity import (\n    before_sleep_log,\n    retry,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n[docs]class ContentFormat(str, Enum):\n    \"\"\"Enumerator of the content formats of Confluence page.\"\"\"\n    EDITOR = \"body.editor\"\n    EXPORT_VIEW = \"body.export_view\"\n    ANONYMOUS_EXPORT_VIEW = \"body.anonymous_export_view\"\n    STORAGE = \"body.storage\"\n    VIEW = \"body.view\"\n    def get_content(self, page: dict) -> str:\n        return page[\"body\"][self.name.lower()][\"value\"]\n[docs]class ConfluenceLoader(BaseLoader):\n    \"\"\"Load `Confluence` pages.\n    Port of https://llamahub.ai/l/confluence\n    This currently supports username/api_key, Oauth2 login or personal access token\n    authentication.\n    Specify a list page_ids and/or space_key to load in the corresponding pages into\n    Document objects, if both are specified the union of both sets will be returned.\n    You can also specify a boolean `include_attachments` to include attachments, this\n    is set to False by default, if set to True all attachments will be downloaded and\n    ConfluenceReader will extract the text from the attachments and add it to the\n    Document object. Currently supported attachment types are: PDF, PNG, JPEG/JPG,\n    SVG, Word and Excel.\n    Confluence API supports difference format of page content. The storage format is the", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-1", "text": "Confluence API supports difference format of page content. The storage format is the\n    raw XML representation for storage. The view format is the HTML representation for\n    viewing with macros are rendered as though it is viewed by users. You can pass\n    a enum `content_format` argument to `load()` to specify the content format, this is\n    set to `ContentFormat.STORAGE` by default, the supported values are:\n    `ContentFormat.EDITOR`, `ContentFormat.EXPORT_VIEW`,\n    `ContentFormat.ANONYMOUS_EXPORT_VIEW`, `ContentFormat.STORAGE`,\n    and `ContentFormat.VIEW`.\n    Hint: space_key and page_id can both be found in the URL of a page in Confluence\n    - https://yoursite.atlassian.com/wiki/spaces/<space_key>/pages/<page_id>\n    Example:\n        .. code-block:: python\n            from langchain.document_loaders import ConfluenceLoader\n            loader = ConfluenceLoader(\n                url=\"https://yoursite.atlassian.com/wiki\",\n                username=\"me\",\n                api_key=\"12345\"\n            )\n            documents = loader.load(space_key=\"SPACE\",limit=50)\n            # Server on perm\n            loader = ConfluenceLoader(\n                url=\"https://confluence.yoursite.com/\",\n                username=\"me\",\n                api_key=\"your_password\",\n                cloud=False\n            )\n            documents = loader.load(space_key=\"SPACE\",limit=50)\n    :param url: _description_\n    :type url: str\n    :param api_key: _description_, defaults to None\n    :type api_key: str, optional\n    :param username: _description_, defaults to None\n    :type username: str, optional\n    :param oauth2: _description_, defaults to {}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-2", "text": ":param oauth2: _description_, defaults to {}\n    :type oauth2: dict, optional\n    :param token: _description_, defaults to None\n    :type token: str, optional\n    :param cloud: _description_, defaults to True\n    :type cloud: bool, optional\n    :param number_of_retries: How many times to retry, defaults to 3\n    :type number_of_retries: Optional[int], optional\n    :param min_retry_seconds: defaults to 2\n    :type min_retry_seconds: Optional[int], optional\n    :param max_retry_seconds:  defaults to 10\n    :type max_retry_seconds: Optional[int], optional\n    :param confluence_kwargs: additional kwargs to initialize confluence with\n    :type confluence_kwargs: dict, optional\n    :raises ValueError: Errors while validating input\n    :raises ImportError: Required dependencies not installed.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        url: str,\n        api_key: Optional[str] = None,\n        username: Optional[str] = None,\n        session: Optional[requests.Session] = None,\n        oauth2: Optional[dict] = None,\n        token: Optional[str] = None,\n        cloud: Optional[bool] = True,\n        number_of_retries: Optional[int] = 3,\n        min_retry_seconds: Optional[int] = 2,\n        max_retry_seconds: Optional[int] = 10,\n        confluence_kwargs: Optional[dict] = None,\n    ):\n        confluence_kwargs = confluence_kwargs or {}\n        errors = ConfluenceLoader.validate_init_args(\n            url=url,\n            api_key=api_key,\n            username=username,\n            session=session,\n            oauth2=oauth2,\n            token=token,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-3", "text": "oauth2=oauth2,\n            token=token,\n        )\n        if errors:\n            raise ValueError(f\"Error(s) while validating input: {errors}\")\n        try:\n            from atlassian import Confluence  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"`atlassian` package not found, please run \"\n                \"`pip install atlassian-python-api`\"\n            )\n        self.base_url = url\n        self.number_of_retries = number_of_retries\n        self.min_retry_seconds = min_retry_seconds\n        self.max_retry_seconds = max_retry_seconds\n        if session:\n            self.confluence = Confluence(url=url, session=session, **confluence_kwargs)\n        elif oauth2:\n            self.confluence = Confluence(\n                url=url, oauth2=oauth2, cloud=cloud, **confluence_kwargs\n            )\n        elif token:\n            self.confluence = Confluence(\n                url=url, token=token, cloud=cloud, **confluence_kwargs\n            )\n        else:\n            self.confluence = Confluence(\n                url=url,\n                username=username,\n                password=api_key,\n                cloud=cloud,\n                **confluence_kwargs,\n            )\n[docs]    @staticmethod\n    def validate_init_args(\n        url: Optional[str] = None,\n        api_key: Optional[str] = None,\n        username: Optional[str] = None,\n        session: Optional[requests.Session] = None,\n        oauth2: Optional[dict] = None,\n        token: Optional[str] = None,\n    ) -> Union[List, None]:\n        \"\"\"Validates proper combinations of init arguments\"\"\"\n        errors = []\n        if url is None:\n            errors.append(\"Must provide `base_url`\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-4", "text": "if url is None:\n            errors.append(\"Must provide `base_url`\")\n        if (api_key and not username) or (username and not api_key):\n            errors.append(\n                \"If one of `api_key` or `username` is provided, \"\n                \"the other must be as well.\"\n            )\n        non_null_creds = list(\n            x is not None for x in ((api_key or username), session, oauth2, token)\n        )\n        if sum(non_null_creds) > 1:\n            all_names = (\"(api_key, username)\", \"session\", \"oath2\", \"token\")\n            provided = tuple(n for x, n in zip(non_null_creds, all_names) if x)\n            errors.append(\n                f\"Cannot provide a value for more than one of: {all_names}. Received \"\n                f\"values for: {provided}\"\n            )\n        if oauth2 and set(oauth2.keys()) != {\n            \"access_token\",\n            \"access_token_secret\",\n            \"consumer_key\",\n            \"key_cert\",\n        }:\n            errors.append(\n                \"You have either omitted require keys or added extra \"\n                \"keys to the oauth2 dictionary. key values should be \"\n                \"`['access_token', 'access_token_secret', 'consumer_key', 'key_cert']`\"\n            )\n        return errors or None\n[docs]    def load(\n        self,\n        space_key: Optional[str] = None,\n        page_ids: Optional[List[str]] = None,\n        label: Optional[str] = None,\n        cql: Optional[str] = None,\n        include_restricted_content: bool = False,\n        include_archived_content: bool = False,\n        include_attachments: bool = False,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-5", "text": "include_archived_content: bool = False,\n        include_attachments: bool = False,\n        include_comments: bool = False,\n        content_format: ContentFormat = ContentFormat.STORAGE,\n        limit: Optional[int] = 50,\n        max_pages: Optional[int] = 1000,\n        ocr_languages: Optional[str] = None,\n        keep_markdown_format: bool = False,\n        keep_newlines: bool = False,\n    ) -> List[Document]:\n        \"\"\"\n        :param space_key: Space key retrieved from a confluence URL, defaults to None\n        :type space_key: Optional[str], optional\n        :param page_ids: List of specific page IDs to load, defaults to None\n        :type page_ids: Optional[List[str]], optional\n        :param label: Get all pages with this label, defaults to None\n        :type label: Optional[str], optional\n        :param cql: CQL Expression, defaults to None\n        :type cql: Optional[str], optional\n        :param include_restricted_content: defaults to False\n        :type include_restricted_content: bool, optional\n        :param include_archived_content: Whether to include archived content,\n                                         defaults to False\n        :type include_archived_content: bool, optional\n        :param include_attachments: defaults to False\n        :type include_attachments: bool, optional\n        :param include_comments: defaults to False\n        :type include_comments: bool, optional\n        :param content_format: Specify content format, defaults to\n                                ContentFormat.STORAGE, the supported values are:\n                                `ContentFormat.EDITOR`, `ContentFormat.EXPORT_VIEW`,\n                                `ContentFormat.ANONYMOUS_EXPORT_VIEW`,\n                                `ContentFormat.STORAGE`, and `ContentFormat.VIEW`.\n        :type content_format: ContentFormat", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-6", "text": ":type content_format: ContentFormat\n        :param limit: Maximum number of pages to retrieve per request, defaults to 50\n        :type limit: int, optional\n        :param max_pages: Maximum number of pages to retrieve in total, defaults 1000\n        :type max_pages: int, optional\n        :param ocr_languages: The languages to use for the Tesseract agent. To use a\n                              language, you'll first need to install the appropriate\n                              Tesseract language pack.\n        :type ocr_languages: str, optional\n        :param keep_markdown_format: Whether to keep the markdown format, defaults to\n            False\n        :type keep_markdown_format: bool\n        :param keep_newlines: Whether to keep the newlines format, defaults to\n            False\n        :type keep_newlines: bool\n        :raises ValueError: _description_\n        :raises ImportError: _description_\n        :return: _description_\n        :rtype: List[Document]\n        \"\"\"\n        if not space_key and not page_ids and not label and not cql:\n            raise ValueError(\n                \"Must specify at least one among `space_key`, `page_ids`, \"\n                \"`label`, `cql` parameters.\"\n            )\n        docs = []\n        if space_key:\n            pages = self.paginate_request(\n                self.confluence.get_all_pages_from_space,\n                space=space_key,\n                limit=limit,\n                max_pages=max_pages,\n                status=\"any\" if include_archived_content else \"current\",\n                expand=content_format.value,\n            )\n            docs += self.process_pages(\n                pages,\n                include_restricted_content,\n                include_attachments,\n                include_comments,\n                content_format,\n                ocr_languages=ocr_languages,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-7", "text": "include_comments,\n                content_format,\n                ocr_languages=ocr_languages,\n                keep_markdown_format=keep_markdown_format,\n                keep_newlines=keep_newlines,\n            )\n        if label:\n            pages = self.paginate_request(\n                self.confluence.get_all_pages_by_label,\n                label=label,\n                limit=limit,\n                max_pages=max_pages,\n            )\n            ids_by_label = [page[\"id\"] for page in pages]\n            if page_ids:\n                page_ids = list(set(page_ids + ids_by_label))\n            else:\n                page_ids = list(set(ids_by_label))\n        if cql:\n            pages = self.paginate_request(\n                self._search_content_by_cql,\n                cql=cql,\n                limit=limit,\n                max_pages=max_pages,\n                include_archived_spaces=include_archived_content,\n                expand=content_format.value,\n            )\n            docs += self.process_pages(\n                pages,\n                include_restricted_content,\n                include_attachments,\n                include_comments,\n                content_format,\n                ocr_languages,\n                keep_markdown_format,\n            )\n        if page_ids:\n            for page_id in page_ids:\n                get_page = retry(\n                    reraise=True,\n                    stop=stop_after_attempt(\n                        self.number_of_retries  # type: ignore[arg-type]\n                    ),\n                    wait=wait_exponential(\n                        multiplier=1,  # type: ignore[arg-type]\n                        min=self.min_retry_seconds,  # type: ignore[arg-type]\n                        max=self.max_retry_seconds,  # type: ignore[arg-type]\n                    ),\n                    before_sleep=before_sleep_log(logger, logging.WARNING),\n                )(self.confluence.get_page_by_id)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-8", "text": ")(self.confluence.get_page_by_id)\n                page = get_page(\n                    page_id=page_id, expand=f\"{content_format.value},version\"\n                )\n                if not include_restricted_content and not self.is_public_page(page):\n                    continue\n                doc = self.process_page(\n                    page,\n                    include_attachments,\n                    include_comments,\n                    content_format,\n                    ocr_languages,\n                    keep_markdown_format,\n                )\n                docs.append(doc)\n        return docs\n    def _search_content_by_cql(\n        self, cql: str, include_archived_spaces: Optional[bool] = None, **kwargs: Any\n    ) -> List[dict]:\n        url = \"rest/api/content/search\"\n        params: Dict[str, Any] = {\"cql\": cql}\n        params.update(kwargs)\n        if include_archived_spaces is not None:\n            params[\"includeArchivedSpaces\"] = include_archived_spaces\n        response = self.confluence.get(url, params=params)\n        return response.get(\"results\", [])\n[docs]    def paginate_request(self, retrieval_method: Callable, **kwargs: Any) -> List:\n        \"\"\"Paginate the various methods to retrieve groups of pages.\n        Unfortunately, due to page size, sometimes the Confluence API\n        doesn't match the limit value. If `limit` is >100 confluence\n        seems to cap the response to 100. Also, due to the Atlassian Python\n        package, we don't get the \"next\" values from the \"_links\" key because\n        they only return the value from the result key. So here, the pagination\n        starts from 0 and goes until the max_pages, getting the `limit` number\n        of pages with each request. We have to manually check if there", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-9", "text": "of pages with each request. We have to manually check if there\n        are more docs based on the length of the returned list of pages, rather than\n        just checking for the presence of a `next` key in the response like this page\n        would have you do:\n        https://developer.atlassian.com/server/confluence/pagination-in-the-rest-api/\n        :param retrieval_method: Function used to retrieve docs\n        :type retrieval_method: callable\n        :return: List of documents\n        :rtype: List\n        \"\"\"\n        max_pages = kwargs.pop(\"max_pages\")\n        docs: List[dict] = []\n        while len(docs) < max_pages:\n            get_pages = retry(\n                reraise=True,\n                stop=stop_after_attempt(\n                    self.number_of_retries  # type: ignore[arg-type]\n                ),\n                wait=wait_exponential(\n                    multiplier=1,\n                    min=self.min_retry_seconds,  # type: ignore[arg-type]\n                    max=self.max_retry_seconds,  # type: ignore[arg-type]\n                ),\n                before_sleep=before_sleep_log(logger, logging.WARNING),\n            )(retrieval_method)\n            batch = get_pages(**kwargs, start=len(docs))\n            if not batch:\n                break\n            docs.extend(batch)\n        return docs[:max_pages]\n[docs]    def is_public_page(self, page: dict) -> bool:\n        \"\"\"Check if a page is publicly accessible.\"\"\"\n        restrictions = self.confluence.get_all_restrictions_for_content(page[\"id\"])\n        return (\n            page[\"status\"] == \"current\"\n            and not restrictions[\"read\"][\"restrictions\"][\"user\"][\"results\"]\n            and not restrictions[\"read\"][\"restrictions\"][\"group\"][\"results\"]\n        )\n[docs]    def process_pages(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-10", "text": ")\n[docs]    def process_pages(\n        self,\n        pages: List[dict],\n        include_restricted_content: bool,\n        include_attachments: bool,\n        include_comments: bool,\n        content_format: ContentFormat,\n        ocr_languages: Optional[str] = None,\n        keep_markdown_format: Optional[bool] = False,\n        keep_newlines: bool = False,\n    ) -> List[Document]:\n        \"\"\"Process a list of pages into a list of documents.\"\"\"\n        docs = []\n        for page in pages:\n            if not include_restricted_content and not self.is_public_page(page):\n                continue\n            doc = self.process_page(\n                page,\n                include_attachments,\n                include_comments,\n                content_format,\n                ocr_languages=ocr_languages,\n                keep_markdown_format=keep_markdown_format,\n                keep_newlines=keep_newlines,\n            )\n            docs.append(doc)\n        return docs\n[docs]    def process_page(\n        self,\n        page: dict,\n        include_attachments: bool,\n        include_comments: bool,\n        content_format: ContentFormat,\n        ocr_languages: Optional[str] = None,\n        keep_markdown_format: Optional[bool] = False,\n        keep_newlines: bool = False,\n    ) -> Document:\n        if keep_markdown_format:\n            try:\n                from markdownify import markdownify\n            except ImportError:\n                raise ImportError(\n                    \"`markdownify` package not found, please run \"\n                    \"`pip install markdownify`\"\n                )\n        if include_comments or not keep_markdown_format:\n            try:\n                from bs4 import BeautifulSoup  # type: ignore\n            except ImportError:\n                raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-11", "text": "except ImportError:\n                raise ImportError(\n                    \"`beautifulsoup4` package not found, please run \"\n                    \"`pip install beautifulsoup4`\"\n                )\n        if include_attachments:\n            attachment_texts = self.process_attachment(page[\"id\"], ocr_languages)\n        else:\n            attachment_texts = []\n        content = content_format.get_content(page)\n        if keep_markdown_format:\n            # Use markdownify to keep the page Markdown style\n            text = markdownify(content, heading_style=\"ATX\") + \"\".join(attachment_texts)\n        else:\n            if keep_newlines:\n                text = BeautifulSoup(\n                    content.replace(\"</p>\", \"\\n</p>\").replace(\"<br />\", \"\\n\"), \"lxml\"\n                ).get_text(\" \") + \"\".join(attachment_texts)\n            else:\n                text = BeautifulSoup(content, \"lxml\").get_text(\n                    \" \", strip=True\n                ) + \"\".join(attachment_texts)\n        if include_comments:\n            comments = self.confluence.get_page_comments(\n                page[\"id\"], expand=\"body.view.value\", depth=\"all\"\n            )[\"results\"]\n            comment_texts = [\n                BeautifulSoup(comment[\"body\"][\"view\"][\"value\"], \"lxml\").get_text(\n                    \" \", strip=True\n                )\n                for comment in comments\n            ]\n            text = text + \"\".join(comment_texts)\n        metadata = {\n            \"title\": page[\"title\"],\n            \"id\": page[\"id\"],\n            \"source\": self.base_url.strip(\"/\") + page[\"_links\"][\"webui\"],\n        }\n        if \"version\" in page and \"when\" in page[\"version\"]:\n            metadata[\"when\"] = page[\"version\"][\"when\"]\n        return Document(\n            page_content=text,\n            metadata=metadata,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-12", "text": "return Document(\n            page_content=text,\n            metadata=metadata,\n        )\n[docs]    def process_attachment(\n        self,\n        page_id: str,\n        ocr_languages: Optional[str] = None,\n    ) -> List[str]:\n        try:\n            from PIL import Image  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"`Pillow` package not found, \" \"please run `pip install Pillow`\"\n            )\n        # depending on setup you may also need to set the correct path for\n        # poppler and tesseract\n        attachments = self.confluence.get_attachments_from_content(page_id)[\"results\"]\n        texts = []\n        for attachment in attachments:\n            media_type = attachment[\"metadata\"][\"mediaType\"]\n            absolute_url = self.base_url + attachment[\"_links\"][\"download\"]\n            title = attachment[\"title\"]\n            try:\n                if media_type == \"application/pdf\":\n                    text = title + self.process_pdf(absolute_url, ocr_languages)\n                elif (\n                    media_type == \"image/png\"\n                    or media_type == \"image/jpg\"\n                    or media_type == \"image/jpeg\"\n                ):\n                    text = title + self.process_image(absolute_url, ocr_languages)\n                elif (\n                    media_type == \"application/vnd.openxmlformats-officedocument\"\n                    \".wordprocessingml.document\"\n                ):\n                    text = title + self.process_doc(absolute_url)\n                elif media_type == \"application/vnd.ms-excel\":\n                    text = title + self.process_xls(absolute_url)\n                elif media_type == \"image/svg+xml\":\n                    text = title + self.process_svg(absolute_url, ocr_languages)\n                else:\n                    continue\n                texts.append(text)\n            except requests.HTTPError as e:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-13", "text": "continue\n                texts.append(text)\n            except requests.HTTPError as e:\n                if e.response.status_code == 404:\n                    print(f\"Attachment not found at {absolute_url}\")\n                    continue\n                else:\n                    raise\n        return texts\n[docs]    def process_pdf(\n        self,\n        link: str,\n        ocr_languages: Optional[str] = None,\n    ) -> str:\n        try:\n            import pytesseract  # noqa: F401\n            from pdf2image import convert_from_bytes  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"`pytesseract` or `pdf2image` package not found, \"\n                \"please run `pip install pytesseract pdf2image`\"\n            )\n        response = self.confluence.request(path=link, absolute=True)\n        text = \"\"\n        if (\n            response.status_code != 200\n            or response.content == b\"\"\n            or response.content is None\n        ):\n            return text\n        try:\n            images = convert_from_bytes(response.content)\n        except ValueError:\n            return text\n        for i, image in enumerate(images):\n            image_text = pytesseract.image_to_string(image, lang=ocr_languages)\n            text += f\"Page {i + 1}:\\n{image_text}\\n\\n\"\n        return text\n[docs]    def process_image(\n        self,\n        link: str,\n        ocr_languages: Optional[str] = None,\n    ) -> str:\n        try:\n            import pytesseract  # noqa: F401\n            from PIL import Image  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"`pytesseract` or `Pillow` package not found, \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-14", "text": "\"`pytesseract` or `Pillow` package not found, \"\n                \"please run `pip install pytesseract Pillow`\"\n            )\n        response = self.confluence.request(path=link, absolute=True)\n        text = \"\"\n        if (\n            response.status_code != 200\n            or response.content == b\"\"\n            or response.content is None\n        ):\n            return text\n        try:\n            image = Image.open(BytesIO(response.content))\n        except OSError:\n            return text\n        return pytesseract.image_to_string(image, lang=ocr_languages)\n[docs]    def process_doc(self, link: str) -> str:\n        try:\n            import docx2txt  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"`docx2txt` package not found, please run `pip install docx2txt`\"\n            )\n        response = self.confluence.request(path=link, absolute=True)\n        text = \"\"\n        if (\n            response.status_code != 200\n            or response.content == b\"\"\n            or response.content is None\n        ):\n            return text\n        file_data = BytesIO(response.content)\n        return docx2txt.process(file_data)\n[docs]    def process_xls(self, link: str) -> str:\n        import io\n        import os\n        try:\n            import xlrd  # noqa: F401\n        except ImportError:\n            raise ImportError(\"`xlrd` package not found, please run `pip install xlrd`\")\n        try:\n            import pandas as pd\n        except ImportError:\n            raise ImportError(\n                \"`pandas` package not found, please run `pip install pandas`\"\n            )\n        response = self.confluence.request(path=link, absolute=True)\n        text = \"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-15", "text": "response = self.confluence.request(path=link, absolute=True)\n        text = \"\"\n        if (\n            response.status_code != 200\n            or response.content == b\"\"\n            or response.content is None\n        ):\n            return text\n        filename = os.path.basename(link)\n        # Getting the whole content of the url after filename,\n        # Example: \".csv?version=2&modificationDate=1631800010678&cacheVersion=1&api=v2\"\n        file_extension = os.path.splitext(filename)[1]\n        if file_extension.startswith(\n            \".csv\"\n        ):  # if the extension found in the url is \".csv\"\n            content_string = response.content.decode(\"utf-8\")\n            df = pd.read_csv(io.StringIO(content_string))\n            text += df.to_string(index=False, header=False) + \"\\n\\n\"\n        else:\n            workbook = xlrd.open_workbook(file_contents=response.content)\n            for sheet in workbook.sheets():\n                text += f\"{sheet.name}:\\n\"\n                for row in range(sheet.nrows):\n                    for col in range(sheet.ncols):\n                        text += f\"{sheet.cell_value(row, col)}\\t\"\n                    text += \"\\n\"\n                text += \"\\n\"\n        return text\n[docs]    def process_svg(\n        self,\n        link: str,\n        ocr_languages: Optional[str] = None,\n    ) -> str:\n        try:\n            import pytesseract  # noqa: F401\n            from PIL import Image  # noqa: F401\n            from reportlab.graphics import renderPM  # noqa: F401\n            from svglib.svglib import svg2rlg  # noqa: F401\n        except ImportError:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "7f601a5fb302-16", "text": "except ImportError:\n            raise ImportError(\n                \"`pytesseract`, `Pillow`, `reportlab` or `svglib` package not found, \"\n                \"please run `pip install pytesseract Pillow reportlab svglib`\"\n            )\n        response = self.confluence.request(path=link, absolute=True)\n        text = \"\"\n        if (\n            response.status_code != 200\n            or response.content == b\"\"\n            or response.content is None\n        ):\n            return text\n        drawing = svg2rlg(BytesIO(response.content))\n        img_data = BytesIO()\n        renderPM.drawToFile(drawing, img_data, fmt=\"PNG\")\n        img_data.seek(0)\n        image = Image.open(img_data)\n        return pytesseract.image_to_string(image, lang=ocr_languages)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html"}
{"id": "0704a9841c91-0", "text": "Source code for langchain.document_loaders.async_html\nimport asyncio\nimport logging\nimport warnings\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import Any, Dict, Iterator, List, Optional, Union, cast\nimport aiohttp\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\ndefault_header_template = {\n    \"User-Agent\": \"\",\n    \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*\"\n    \";q=0.8\",\n    \"Accept-Language\": \"en-US,en;q=0.5\",\n    \"Referer\": \"https://www.google.com/\",\n    \"DNT\": \"1\",\n    \"Connection\": \"keep-alive\",\n    \"Upgrade-Insecure-Requests\": \"1\",\n}\ndef _build_metadata(soup: Any, url: str) -> dict:\n    \"\"\"Build metadata from BeautifulSoup output.\"\"\"\n    metadata = {\"source\": url}\n    if title := soup.find(\"title\"):\n        metadata[\"title\"] = title.get_text()\n    if description := soup.find(\"meta\", attrs={\"name\": \"description\"}):\n        metadata[\"description\"] = description.get(\"content\", \"No description found.\")\n    if html := soup.find(\"html\"):\n        metadata[\"language\"] = html.get(\"lang\", \"No language found.\")\n    return metadata\n[docs]class AsyncHtmlLoader(BaseLoader):\n    \"\"\"Load `HTML` asynchronously.\"\"\"\n[docs]    def __init__(\n        self,\n        web_path: Union[str, List[str]],\n        header_template: Optional[dict] = None,\n        verify_ssl: Optional[bool] = True,\n        proxies: Optional[dict] = None,\n        autoset_encoding: bool = True,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/async_html.html"}
{"id": "0704a9841c91-1", "text": "autoset_encoding: bool = True,\n        encoding: Optional[str] = None,\n        default_parser: str = \"html.parser\",\n        requests_per_second: int = 2,\n        requests_kwargs: Optional[Dict[str, Any]] = None,\n        raise_for_status: bool = False,\n        ignore_load_errors: bool = False,\n    ):\n        \"\"\"Initialize with a webpage path.\"\"\"\n        # TODO: Deprecate web_path in favor of web_paths, and remove this\n        # left like this because there are a number of loaders that expect single\n        # urls\n        if isinstance(web_path, str):\n            self.web_paths = [web_path]\n        elif isinstance(web_path, List):\n            self.web_paths = web_path\n        headers = header_template or default_header_template\n        if not headers.get(\"User-Agent\"):\n            try:\n                from fake_useragent import UserAgent\n                headers[\"User-Agent\"] = UserAgent().random\n            except ImportError:\n                logger.info(\n                    \"fake_useragent not found, using default user agent.\"\n                    \"To get a realistic header for requests, \"\n                    \"`pip install fake_useragent`.\"\n                )\n        self.session = requests.Session()\n        self.session.headers = dict(headers)\n        self.session.verify = verify_ssl\n        if proxies:\n            self.session.proxies.update(proxies)\n        self.requests_per_second = requests_per_second\n        self.default_parser = default_parser\n        self.requests_kwargs = requests_kwargs or {}\n        self.raise_for_status = raise_for_status\n        self.autoset_encoding = autoset_encoding\n        self.encoding = encoding\n        self.ignore_load_errors = ignore_load_errors\n    def _fetch_valid_connection_docs(self, url: str) -> Any:\n        if self.ignore_load_errors:\n            try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/async_html.html"}
{"id": "0704a9841c91-2", "text": "if self.ignore_load_errors:\n            try:\n                return self.session.get(url, **self.requests_kwargs)\n            except Exception as e:\n                warnings.warn(str(e))\n                return None\n        return self.session.get(url, **self.requests_kwargs)\n    @staticmethod\n    def _check_parser(parser: str) -> None:\n        \"\"\"Check that parser is valid for bs4.\"\"\"\n        valid_parsers = [\"html.parser\", \"lxml\", \"xml\", \"lxml-xml\", \"html5lib\"]\n        if parser not in valid_parsers:\n            raise ValueError(\n                \"`parser` must be one of \" + \", \".join(valid_parsers) + \".\"\n            )\n    def _scrape(\n        self,\n        url: str,\n        parser: Union[str, None] = None,\n        bs_kwargs: Optional[dict] = None,\n    ) -> Any:\n        from bs4 import BeautifulSoup\n        if parser is None:\n            if url.endswith(\".xml\"):\n                parser = \"xml\"\n            else:\n                parser = self.default_parser\n        self._check_parser(parser)\n        html_doc = self._fetch_valid_connection_docs(url)\n        if not getattr(html_doc, \"ok\", False):\n            return None\n        if self.raise_for_status:\n            html_doc.raise_for_status()\n        if self.encoding is not None:\n            html_doc.encoding = self.encoding\n        elif self.autoset_encoding:\n            html_doc.encoding = html_doc.apparent_encoding\n        return BeautifulSoup(html_doc.text, parser, **(bs_kwargs or {}))\n    async def _fetch(\n        self, url: str, retries: int = 3, cooldown: int = 2, backoff: float = 1.5\n    ) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/async_html.html"}
{"id": "0704a9841c91-3", "text": ") -> str:\n        async with aiohttp.ClientSession() as session:\n            for i in range(retries):\n                try:\n                    async with session.get(\n                        url,\n                        headers=self.session.headers,\n                        ssl=None if self.session.verify else False,\n                    ) as response:\n                        try:\n                            text = await response.text()\n                        except UnicodeDecodeError:\n                            logger.error(f\"Failed to decode content from {url}\")\n                            text = \"\"\n                        return text\n                except aiohttp.ClientConnectionError as e:\n                    if i == retries - 1 and self.ignore_load_errors:\n                        logger.warning(f\"Error fetching {url} after {retries} retries.\")\n                        return \"\"\n                    elif i == retries - 1:\n                        raise\n                    else:\n                        logger.warning(\n                            f\"Error fetching {url} with attempt \"\n                            f\"{i + 1}/{retries}: {e}. Retrying...\"\n                        )\n                        await asyncio.sleep(cooldown * backoff**i)\n        raise ValueError(\"retry count exceeded\")\n    async def _fetch_with_rate_limit(\n        self, url: str, semaphore: asyncio.Semaphore\n    ) -> str:\n        async with semaphore:\n            return await self._fetch(url)\n[docs]    async def fetch_all(self, urls: List[str]) -> Any:\n        \"\"\"Fetch all urls concurrently with rate limiting.\"\"\"\n        semaphore = asyncio.Semaphore(self.requests_per_second)\n        tasks = []\n        for url in urls:\n            task = asyncio.ensure_future(self._fetch_with_rate_limit(url, semaphore))\n            tasks.append(task)\n        try:\n            from tqdm.asyncio import tqdm_asyncio\n            return await tqdm_asyncio.gather(\n                *tasks, desc=\"Fetching pages\", ascii=True, mininterval=1\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/async_html.html"}
{"id": "0704a9841c91-4", "text": "*tasks, desc=\"Fetching pages\", ascii=True, mininterval=1\n            )\n        except ImportError:\n            warnings.warn(\"For better logging of progress, `pip install tqdm`\")\n            return await asyncio.gather(*tasks)\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazy load text from the url(s) in web_path.\"\"\"\n        for doc in self.load():\n            yield doc\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load text from the url(s) in web_path.\"\"\"\n        try:\n            # Raises RuntimeError if there is no current event loop.\n            asyncio.get_running_loop()\n            # If there is a current event loop, we need to run the async code\n            # in a separate loop, in a separate thread.\n            with ThreadPoolExecutor(max_workers=1) as executor:\n                future = executor.submit(asyncio.run, self.fetch_all(self.web_paths))\n                results = future.result()\n        except RuntimeError:\n            results = asyncio.run(self.fetch_all(self.web_paths))\n        docs = []\n        for i, text in enumerate(cast(List[str], results)):\n            soup = self._scrape(self.web_paths[i])\n            if not soup:\n                continue\n            metadata = _build_metadata(soup, self.web_paths[i])\n            docs.append(Document(page_content=text, metadata=metadata))\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/async_html.html"}
{"id": "ec4074ce0242-0", "text": "Source code for langchain.document_loaders.etherscan\nimport os\nimport re\nfrom typing import Iterator, List\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class EtherscanLoader(BaseLoader):\n    \"\"\"Load transactions from `Ethereum` mainnet.\n    The Loader use Etherscan API to interact with Ethereum mainnet.\n    ETHERSCAN_API_KEY environment variable must be set use this loader.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        account_address: str,\n        api_key: str = \"docs-demo\",\n        filter: str = \"normal_transaction\",\n        page: int = 1,\n        offset: int = 10,\n        start_block: int = 0,\n        end_block: int = 99999999,\n        sort: str = \"desc\",\n    ):\n        self.account_address = account_address\n        self.api_key = os.environ.get(\"ETHERSCAN_API_KEY\") or api_key\n        self.filter = filter\n        self.page = page\n        self.offset = offset\n        self.start_block = start_block\n        self.end_block = end_block\n        self.sort = sort\n        if not self.api_key:\n            raise ValueError(\"Etherscan API key not provided\")\n        if not re.match(r\"^0x[a-fA-F0-9]{40}$\", self.account_address):\n            raise ValueError(f\"Invalid contract address {self.account_address}\")\n        if filter not in [\n            \"normal_transaction\",\n            \"internal_transaction\",\n            \"erc20_transaction\",\n            \"eth_balance\",\n            \"erc721_transaction\",\n            \"erc1155_transaction\",\n        ]:\n            raise ValueError(f\"Invalid filter {filter}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/etherscan.html"}
{"id": "ec4074ce0242-1", "text": "]:\n            raise ValueError(f\"Invalid filter {filter}\")\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazy load Documents from table.\"\"\"\n        result = []\n        if self.filter == \"normal_transaction\":\n            result = self.getNormTx()\n        elif self.filter == \"internal_transaction\":\n            result = self.getInternalTx()\n        elif self.filter == \"erc20_transaction\":\n            result = self.getERC20Tx()\n        elif self.filter == \"eth_balance\":\n            result = self.getEthBalance()\n        elif self.filter == \"erc721_transaction\":\n            result = self.getERC721Tx()\n        elif self.filter == \"erc1155_transaction\":\n            result = self.getERC1155Tx()\n        else:\n            raise ValueError(f\"Invalid filter {filter}\")\n        for doc in result:\n            yield doc\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load transactions from spcifc account by Etherscan.\"\"\"\n        return list(self.lazy_load())\n[docs]    def getNormTx(self) -> List[Document]:\n        url = (\n            f\"https://api.etherscan.io/api?module=account&action=txlist&address={self.account_address}\"\n            f\"&startblock={self.start_block}&endblock={self.end_block}&page={self.page}\"\n            f\"&offset={self.offset}&sort={self.sort}&apikey={self.api_key}\"\n        )\n        try:\n            response = requests.get(url)\n            response.raise_for_status()\n        except requests.exceptions.RequestException as e:\n            print(\"Error occurred while making the request:\", e)\n        items = response.json()[\"result\"]\n        result = []\n        if len(items) == 0:\n            return [Document(page_content=\"\")]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/etherscan.html"}
{"id": "ec4074ce0242-2", "text": "if len(items) == 0:\n            return [Document(page_content=\"\")]\n        for item in items:\n            content = str(item)\n            metadata = {\"from\": item[\"from\"], \"tx_hash\": item[\"hash\"], \"to\": item[\"to\"]}\n            result.append(Document(page_content=content, metadata=metadata))\n        print(len(result))\n        return result\n[docs]    def getEthBalance(self) -> List[Document]:\n        url = (\n            f\"https://api.etherscan.io/api?module=account&action=balance\"\n            f\"&address={self.account_address}&tag=latest&apikey={self.api_key}\"\n        )\n        try:\n            response = requests.get(url)\n            response.raise_for_status()\n        except requests.exceptions.RequestException as e:\n            print(\"Error occurred while making the request:\", e)\n        return [Document(page_content=response.json()[\"result\"])]\n[docs]    def getInternalTx(self) -> List[Document]:\n        url = (\n            f\"https://api.etherscan.io/api?module=account&action=txlistinternal\"\n            f\"&address={self.account_address}&startblock={self.start_block}\"\n            f\"&endblock={self.end_block}&page={self.page}&offset={self.offset}\"\n            f\"&sort={self.sort}&apikey={self.api_key}\"\n        )\n        try:\n            response = requests.get(url)\n            response.raise_for_status()\n        except requests.exceptions.RequestException as e:\n            print(\"Error occurred while making the request:\", e)\n        items = response.json()[\"result\"]\n        result = []\n        if len(items) == 0:\n            return [Document(page_content=\"\")]\n        for item in items:\n            content = str(item)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/etherscan.html"}
{"id": "ec4074ce0242-3", "text": "for item in items:\n            content = str(item)\n            metadata = {\"from\": item[\"from\"], \"tx_hash\": item[\"hash\"], \"to\": item[\"to\"]}\n            result.append(Document(page_content=content, metadata=metadata))\n        return result\n[docs]    def getERC20Tx(self) -> List[Document]:\n        url = (\n            f\"https://api.etherscan.io/api?module=account&action=tokentx\"\n            f\"&address={self.account_address}&startblock={self.start_block}\"\n            f\"&endblock={self.end_block}&page={self.page}&offset={self.offset}\"\n            f\"&sort={self.sort}&apikey={self.api_key}\"\n        )\n        try:\n            response = requests.get(url)\n            response.raise_for_status()\n        except requests.exceptions.RequestException as e:\n            print(\"Error occurred while making the request:\", e)\n        items = response.json()[\"result\"]\n        result = []\n        if len(items) == 0:\n            return [Document(page_content=\"\")]\n        for item in items:\n            content = str(item)\n            metadata = {\"from\": item[\"from\"], \"tx_hash\": item[\"hash\"], \"to\": item[\"to\"]}\n            result.append(Document(page_content=content, metadata=metadata))\n        return result\n[docs]    def getERC721Tx(self) -> List[Document]:\n        url = (\n            f\"https://api.etherscan.io/api?module=account&action=tokennfttx\"\n            f\"&address={self.account_address}&startblock={self.start_block}\"\n            f\"&endblock={self.end_block}&page={self.page}&offset={self.offset}\"\n            f\"&sort={self.sort}&apikey={self.api_key}\"\n        )\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/etherscan.html"}
{"id": "ec4074ce0242-4", "text": ")\n        try:\n            response = requests.get(url)\n            response.raise_for_status()\n        except requests.exceptions.RequestException as e:\n            print(\"Error occurred while making the request:\", e)\n        items = response.json()[\"result\"]\n        result = []\n        if len(items) == 0:\n            return [Document(page_content=\"\")]\n        for item in items:\n            content = str(item)\n            metadata = {\"from\": item[\"from\"], \"tx_hash\": item[\"hash\"], \"to\": item[\"to\"]}\n            result.append(Document(page_content=content, metadata=metadata))\n        return result\n[docs]    def getERC1155Tx(self) -> List[Document]:\n        url = (\n            f\"https://api.etherscan.io/api?module=account&action=token1155tx\"\n            f\"&address={self.account_address}&startblock={self.start_block}\"\n            f\"&endblock={self.end_block}&page={self.page}&offset={self.offset}\"\n            f\"&sort={self.sort}&apikey={self.api_key}\"\n        )\n        try:\n            response = requests.get(url)\n            response.raise_for_status()\n        except requests.exceptions.RequestException as e:\n            print(\"Error occurred while making the request:\", e)\n        items = response.json()[\"result\"]\n        result = []\n        if len(items) == 0:\n            return [Document(page_content=\"\")]\n        for item in items:\n            content = str(item)\n            metadata = {\"from\": item[\"from\"], \"tx_hash\": item[\"hash\"], \"to\": item[\"to\"]}\n            result.append(Document(page_content=content, metadata=metadata))\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/etherscan.html"}
{"id": "878498865c8e-0", "text": "Source code for langchain.document_loaders.bilibili\nimport json\nimport re\nimport warnings\nfrom typing import List, Tuple\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class BiliBiliLoader(BaseLoader):\n    \"\"\"Load `BiliBili` video transcripts.\"\"\"\n[docs]    def __init__(self, video_urls: List[str]):\n        \"\"\"Initialize with bilibili url.\n        Args:\n            video_urls: List of bilibili urls.\n        \"\"\"\n        self.video_urls = video_urls\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load Documents from bilibili url.\"\"\"\n        results = []\n        for url in self.video_urls:\n            transcript, video_info = self._get_bilibili_subs_and_info(url)\n            doc = Document(page_content=transcript, metadata=video_info)\n            results.append(doc)\n        return results\n    def _get_bilibili_subs_and_info(self, url: str) -> Tuple[str, dict]:\n        try:\n            from bilibili_api import sync, video\n        except ImportError:\n            raise ImportError(\n                \"requests package not found, please install it with \"\n                \"`pip install bilibili-api-python`\"\n            )\n        bvid = re.search(r\"BV\\w+\", url)\n        if bvid is not None:\n            v = video.Video(bvid=bvid.group())\n        else:\n            aid = re.search(r\"av[0-9]+\", url)\n            if aid is not None:\n                try:\n                    v = video.Video(aid=int(aid.group()[2:]))\n                except AttributeError:\n                    raise ValueError(f\"{url} is not bilibili url.\")\n            else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bilibili.html"}
{"id": "878498865c8e-1", "text": "raise ValueError(f\"{url} is not bilibili url.\")\n            else:\n                raise ValueError(f\"{url} is not bilibili url.\")\n        video_info = sync(v.get_info())\n        video_info.update({\"url\": url})\n        sub = sync(v.get_subtitle(video_info[\"cid\"]))\n        # Get subtitle url\n        sub_list = sub[\"subtitles\"]\n        if sub_list:\n            sub_url = sub_list[0][\"subtitle_url\"]\n            if not sub_url.startswith(\"http\"):\n                sub_url = \"https:\" + sub_url\n            result = requests.get(sub_url)\n            raw_sub_titles = json.loads(result.content)[\"body\"]\n            raw_transcript = \" \".join([c[\"content\"] for c in raw_sub_titles])\n            raw_transcript_with_meta_info = (\n                f\"Video Title: {video_info['title']},\"\n                f\"description: {video_info['desc']}\\n\\n\"\n                f\"Transcript: {raw_transcript}\"\n            )\n            return raw_transcript_with_meta_info, video_info\n        else:\n            raw_transcript = \"\"\n            warnings.warn(\n                f\"\"\"\n                No subtitles found for video: {url}.\n                Return Empty transcript.\n                \"\"\"\n            )\n            return raw_transcript, video_info", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bilibili.html"}
{"id": "7b31da648a9f-0", "text": "Source code for langchain.document_loaders.docusaurus\n\"\"\"Load Documents from Docusarus Documentation\"\"\"\nfrom typing import Any, List, Optional\nfrom langchain.document_loaders.sitemap import SitemapLoader\n[docs]class DocusaurusLoader(SitemapLoader):\n    \"\"\"\n    Loader that leverages the SitemapLoader to loop through the generated pages of a\n    Docusaurus Documentation website and extracts the content by looking for specific\n    HTML tags. By default, the parser searches for the main content of the Docusaurus\n    page, which is normally the <article>. You also have the option to define your own\n    custom HTML tags by providing them as a list, for example: [\"div\", \".main\", \"a\"].\n    \"\"\"\n[docs]    def __init__(\n        self,\n        url: str,\n        custom_html_tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ):\n        \"\"\"\n        Initialize DocusaurusLoader\n        Args:\n            url: The base URL of the Docusaurus website.\n            custom_html_tags: Optional custom html tags to extract content from pages.\n            kwargs: Additional args to extend the underlying SitemapLoader, for example:\n                filter_urls, blocksize, meta_function, is_local, continue_on_failure\n        \"\"\"\n        if not kwargs.get(\"is_local\"):\n            url = f\"{url}/sitemap.xml\"\n        self.custom_html_tags = custom_html_tags or [\"main article\"]\n        super().__init__(\n            url,\n            parsing_function=kwargs.get(\"parsing_function\") or self._parsing_function,\n            **kwargs,\n        )\n    def _parsing_function(self, content: Any) -> str:\n        \"\"\"Parses specific elements from a Docusarus page.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docusaurus.html"}
{"id": "7b31da648a9f-1", "text": "\"\"\"Parses specific elements from a Docusarus page.\"\"\"\n        relevant_elements = content.select(\",\".join(self.custom_html_tags))\n        for element in relevant_elements:\n            if element not in relevant_elements:\n                element.decompose()\n        return str(content.get_text())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docusaurus.html"}
{"id": "a665065467c9-0", "text": "Source code for langchain.document_loaders.json_loader\nimport json\nfrom pathlib import Path\nfrom typing import Any, Callable, Dict, List, Optional, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class JSONLoader(BaseLoader):\n    \"\"\"Load a `JSON` file using a `jq` schema.\n    Example:\n        [{\"text\": ...}, {\"text\": ...}, {\"text\": ...}] -> schema = .[].text\n        {\"key\": [{\"text\": ...}, {\"text\": ...}, {\"text\": ...}]} -> schema = .key[].text\n        [\"\", \"\", \"\"] -> schema = .[]\n    \"\"\"\n[docs]    def __init__(\n        self,\n        file_path: Union[str, Path],\n        jq_schema: str,\n        content_key: Optional[str] = None,\n        metadata_func: Optional[Callable[[Dict, Dict], Dict]] = None,\n        text_content: bool = True,\n        json_lines: bool = False,\n    ):\n        \"\"\"Initialize the JSONLoader.\n        Args:\n            file_path (Union[str, Path]): The path to the JSON or JSON Lines file.\n            jq_schema (str): The jq schema to use to extract the data or text from\n                the JSON.\n            content_key (str): The key to use to extract the content from the JSON if\n                the jq_schema results to a list of objects (dict).\n            metadata_func (Callable[Dict, Dict]): A function that takes in the JSON\n                object extracted by the jq_schema and the default metadata and returns\n                a dict of the updated metadata.\n            text_content (bool): Boolean flag to indicate whether the content is in\n                string format, default to True.\n            json_lines (bool): Boolean flag to indicate whether the input is in", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/json_loader.html"}
{"id": "a665065467c9-1", "text": "json_lines (bool): Boolean flag to indicate whether the input is in\n                JSON Lines format.\n        \"\"\"\n        try:\n            import jq  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"jq package not found, please install it with `pip install jq`\"\n            )\n        self.file_path = Path(file_path).resolve()\n        self._jq_schema = jq.compile(jq_schema)\n        self._content_key = content_key\n        self._metadata_func = metadata_func\n        self._text_content = text_content\n        self._json_lines = json_lines\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load and return documents from the JSON file.\"\"\"\n        docs: List[Document] = []\n        if self._json_lines:\n            with self.file_path.open(encoding=\"utf-8\") as f:\n                for line in f:\n                    line = line.strip()\n                    if line:\n                        self._parse(line, docs)\n        else:\n            self._parse(self.file_path.read_text(encoding=\"utf-8\"), docs)\n        return docs\n    def _parse(self, content: str, docs: List[Document]) -> None:\n        \"\"\"Convert given content to documents.\"\"\"\n        data = self._jq_schema.input(json.loads(content))\n        # Perform some validation\n        # This is not a perfect validation, but it should catch most cases\n        # and prevent the user from getting a cryptic error later on.\n        if self._content_key is not None:\n            self._validate_content_key(data)\n        if self._metadata_func is not None:\n            self._validate_metadata_func(data)\n        for i, sample in enumerate(data, len(docs) + 1):\n            text = self._get_text(sample=sample)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/json_loader.html"}
{"id": "a665065467c9-2", "text": "text = self._get_text(sample=sample)\n            metadata = self._get_metadata(\n                sample=sample, source=str(self.file_path), seq_num=i\n            )\n            docs.append(Document(page_content=text, metadata=metadata))\n    def _get_text(self, sample: Any) -> str:\n        \"\"\"Convert sample to string format\"\"\"\n        if self._content_key is not None:\n            content = sample.get(self._content_key)\n        else:\n            content = sample\n        if self._text_content and not isinstance(content, str):\n            raise ValueError(\n                f\"Expected page_content is string, got {type(content)} instead. \\\n                    Set `text_content=False` if the desired input for \\\n                    `page_content` is not a string\"\n            )\n        # In case the text is None, set it to an empty string\n        elif isinstance(content, str):\n            return content\n        elif isinstance(content, dict):\n            return json.dumps(content) if content else \"\"\n        else:\n            return str(content) if content is not None else \"\"\n    def _get_metadata(\n        self, sample: Dict[str, Any], **additional_fields: Any\n    ) -> Dict[str, Any]:\n        \"\"\"\n        Return a metadata dictionary base on the existence of metadata_func\n        :param sample: single data payload\n        :param additional_fields: key-word arguments to be added as metadata values\n        :return:\n        \"\"\"\n        if self._metadata_func is not None:\n            return self._metadata_func(sample, additional_fields)\n        else:\n            return additional_fields\n    def _validate_content_key(self, data: Any) -> None:\n        \"\"\"Check if a content key is valid\"\"\"\n        sample = data.first()\n        if not isinstance(sample, dict):\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/json_loader.html"}
{"id": "a665065467c9-3", "text": "if not isinstance(sample, dict):\n            raise ValueError(\n                f\"Expected the jq schema to result in a list of objects (dict), \\\n                    so sample must be a dict but got `{type(sample)}`\"\n            )\n        if sample.get(self._content_key) is None:\n            raise ValueError(\n                f\"Expected the jq schema to result in a list of objects (dict) \\\n                    with the key `{self._content_key}`\"\n            )\n    def _validate_metadata_func(self, data: Any) -> None:\n        \"\"\"Check if the metadata_func output is valid\"\"\"\n        sample = data.first()\n        if self._metadata_func is not None:\n            sample_metadata = self._metadata_func(sample, {})\n            if not isinstance(sample_metadata, dict):\n                raise ValueError(\n                    f\"Expected the metadata_func to return a dict but got \\\n                        `{type(sample_metadata)}`\"\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/json_loader.html"}
{"id": "5f53cd468d6f-0", "text": "Source code for langchain.document_loaders.readthedocs\nfrom __future__ import annotations\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Iterator, List, Optional, Sequence, Tuple, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nif TYPE_CHECKING:\n    from bs4 import NavigableString\n    from bs4.element import Comment, Tag\n[docs]class ReadTheDocsLoader(BaseLoader):\n    \"\"\"Load `ReadTheDocs` documentation directory.\"\"\"\n[docs]    def __init__(\n        self,\n        path: Union[str, Path],\n        encoding: Optional[str] = None,\n        errors: Optional[str] = None,\n        custom_html_tag: Optional[Tuple[str, dict]] = None,\n        patterns: Sequence[str] = (\"*.htm\", \"*.html\"),\n        exclude_links_ratio: float = 1.0,\n        **kwargs: Optional[Any],\n    ):\n        \"\"\"\n        Initialize ReadTheDocsLoader\n        The loader loops over all files under `path` and extracts the actual content of\n        the files by retrieving main html tags. Default main html tags include\n        `<main id=\"main-content>`, <`div role=\"main>`, and `<article role=\"main\">`. You\n        can also define your own html tags by passing custom_html_tag, e.g.\n        `(\"div\", \"class=main\")`. The loader iterates html tags with the order of\n        custom html tags (if exists) and default html tags. If any of the tags is not\n        empty, the loop will break and retrieve the content out of that tag.\n        Args:\n            path: The location of pulled readthedocs folder.\n            encoding: The encoding with which to open the documents.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html"}
{"id": "5f53cd468d6f-1", "text": "encoding: The encoding with which to open the documents.\n            errors: Specify how encoding and decoding errors are to be handled\u2014this\n                cannot be used in binary mode.\n            custom_html_tag: Optional custom html tag to retrieve the content from\n                files.\n            patterns: The file patterns to load, passed to `glob.rglob`.\n            exclude_links_ratio: The ratio of links:content to exclude pages from.\n                This is to reduce the frequency at which index pages make their\n                way into retrieved results. Recommended: 0.5\n            kwargs: named arguments passed to `bs4.BeautifulSoup`.\n        \"\"\"\n        try:\n            from bs4 import BeautifulSoup\n        except ImportError:\n            raise ImportError(\n                \"Could not import python packages. \"\n                \"Please install it with `pip install beautifulsoup4`. \"\n            )\n        try:\n            _ = BeautifulSoup(\n                \"<html><body>Parser builder library test.</body></html>\",\n                \"html.parser\",\n                **kwargs,\n            )\n        except Exception as e:\n            raise ValueError(\"Parsing kwargs do not appear valid\") from e\n        self.file_path = Path(path)\n        self.encoding = encoding\n        self.errors = errors\n        self.custom_html_tag = custom_html_tag\n        self.patterns = patterns\n        self.bs_kwargs = kwargs\n        self.exclude_links_ratio = exclude_links_ratio\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"A lazy loader for Documents.\"\"\"\n        for file_pattern in self.patterns:\n            for p in self.file_path.rglob(file_pattern):\n                if p.is_dir():\n                    continue\n                with open(p, encoding=self.encoding, errors=self.errors) as f:\n                    text = self._clean_data(f.read())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html"}
{"id": "5f53cd468d6f-2", "text": "text = self._clean_data(f.read())\n                yield Document(page_content=text, metadata={\"source\": str(p)})\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        return list(self.lazy_load())\n    def _clean_data(self, data: str) -> str:\n        from bs4 import BeautifulSoup\n        soup = BeautifulSoup(data, \"html.parser\", **self.bs_kwargs)\n        # default tags\n        html_tags = [\n            (\"div\", {\"role\": \"main\"}),\n            (\"main\", {\"id\": \"main-content\"}),\n        ]\n        if self.custom_html_tag is not None:\n            html_tags.append(self.custom_html_tag)\n        element = None\n        # reversed order. check the custom one first\n        for tag, attrs in html_tags[::-1]:\n            element = soup.find(tag, attrs)\n            # if found, break\n            if element is not None:\n                break\n        if element is not None and _get_link_ratio(element) <= self.exclude_links_ratio:\n            text = _get_clean_text(element)\n        else:\n            text = \"\"\n        # trim empty lines\n        return \"\\n\".join([t for t in text.split(\"\\n\") if t])\ndef _get_clean_text(element: Tag) -> str:\n    \"\"\"Returns cleaned text with newlines preserved and irrelevant elements removed.\"\"\"\n    elements_to_skip = [\n        \"script\",\n        \"noscript\",\n        \"canvas\",\n        \"meta\",\n        \"svg\",\n        \"map\",\n        \"area\",\n        \"audio\",\n        \"source\",\n        \"track\",\n        \"video\",\n        \"embed\",\n        \"object\",\n        \"param\",\n        \"picture\",\n        \"iframe\",\n        \"frame\",\n        \"frameset\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html"}
{"id": "5f53cd468d6f-3", "text": "\"iframe\",\n        \"frame\",\n        \"frameset\",\n        \"noframes\",\n        \"applet\",\n        \"form\",\n        \"button\",\n        \"select\",\n        \"base\",\n        \"style\",\n        \"img\",\n    ]\n    newline_elements = [\n        \"p\",\n        \"div\",\n        \"ul\",\n        \"ol\",\n        \"li\",\n        \"h1\",\n        \"h2\",\n        \"h3\",\n        \"h4\",\n        \"h5\",\n        \"h6\",\n        \"pre\",\n        \"table\",\n        \"tr\",\n    ]\n    text = _process_element(element, elements_to_skip, newline_elements)\n    return text.strip()\ndef _get_link_ratio(section: Tag) -> float:\n    links = section.find_all(\"a\")\n    total_text = \"\".join(str(s) for s in section.stripped_strings)\n    if len(total_text) == 0:\n        return 0\n    link_text = \"\".join(\n        str(string.string.strip())\n        for link in links\n        for string in link.strings\n        if string\n    )\n    return len(link_text) / len(total_text)\ndef _process_element(\n    element: Union[Tag, NavigableString, Comment],\n    elements_to_skip: List[str],\n    newline_elements: List[str],\n) -> str:\n    \"\"\"\n    Traverse through HTML tree recursively to preserve newline and skip\n    unwanted (code/binary) elements\n    \"\"\"\n    from bs4 import NavigableString\n    from bs4.element import Comment, Tag\n    tag_name = getattr(element, \"name\", None)\n    if isinstance(element, Comment) or tag_name in elements_to_skip:\n        return \"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html"}
{"id": "5f53cd468d6f-4", "text": "if isinstance(element, Comment) or tag_name in elements_to_skip:\n        return \"\"\n    elif isinstance(element, NavigableString):\n        return element\n    elif tag_name == \"br\":\n        return \"\\n\"\n    elif tag_name in newline_elements:\n        return (\n            \"\".join(\n                _process_element(child, elements_to_skip, newline_elements)\n                for child in element.children\n                if isinstance(child, (Tag, NavigableString, Comment))\n            )\n            + \"\\n\"\n        )\n    else:\n        return \"\".join(\n            _process_element(child, elements_to_skip, newline_elements)\n            for child in element.children\n            if isinstance(child, (Tag, NavigableString, Comment))\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html"}
{"id": "01439f0049f3-0", "text": "Source code for langchain.document_loaders.chromium\nimport asyncio\nimport logging\nfrom typing import Iterator, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n[docs]class AsyncChromiumLoader(BaseLoader):\n    \"\"\"Scrape HTML pages from URLs using a\n    headless instance of the Chromium.\"\"\"\n[docs]    def __init__(\n        self,\n        urls: List[str],\n    ):\n        \"\"\"\n        Initialize the loader with a list of URL paths.\n        Args:\n            urls (List[str]): A list of URLs to scrape content from.\n        Raises:\n            ImportError: If the required 'playwright' package is not installed.\n        \"\"\"\n        self.urls = urls\n        try:\n            import playwright  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"playwright is required for AsyncChromiumLoader. \"\n                \"Please install it with `pip install playwright`.\"\n            )\n[docs]    async def ascrape_playwright(self, url: str) -> str:\n        \"\"\"\n        Asynchronously scrape the content of a given URL using Playwright's async API.\n        Args:\n            url (str): The URL to scrape.\n        Returns:\n            str: The scraped HTML content or an error message if an exception occurs.\n        \"\"\"\n        from playwright.async_api import async_playwright\n        logger.info(\"Starting scraping...\")\n        results = \"\"\n        async with async_playwright() as p:\n            browser = await p.chromium.launch(headless=True)\n            try:\n                page = await browser.new_page()\n                await page.goto(url)\n                results = await page.content()  # Simply get the HTML content\n                logger.info(\"Content scraped\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/chromium.html"}
{"id": "01439f0049f3-1", "text": "logger.info(\"Content scraped\")\n            except Exception as e:\n                results = f\"Error: {e}\"\n            await browser.close()\n        return results\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"\n        Lazily load text content from the provided URLs.\n        This method yields Documents one at a time as they're scraped,\n        instead of waiting to scrape all URLs before returning.\n        Yields:\n            Document: The scraped content encapsulated within a Document object.\n        \"\"\"\n        for url in self.urls:\n            html_content = asyncio.run(self.ascrape_playwright(url))\n            metadata = {\"source\": url}\n            yield Document(page_content=html_content, metadata=metadata)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"\n        Load and return all Documents from the provided URLs.\n        Returns:\n            List[Document]: A list of Document objects\n            containing the scraped content from each URL.\n        \"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/chromium.html"}
{"id": "1ca51484d448-0", "text": "Source code for langchain.document_loaders.notebook\n\"\"\"Loads .ipynb notebook files.\"\"\"\nimport json\nfrom pathlib import Path\nfrom typing import Any, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]def concatenate_cells(\n    cell: dict, include_outputs: bool, max_output_length: int, traceback: bool\n) -> str:\n    \"\"\"Combine cells information in a readable format ready to be used.\n    Args:\n        cell: A dictionary\n        include_outputs: Whether to include the outputs of the cell.\n        max_output_length: Maximum length of the output to be displayed.\n        traceback: Whether to return a traceback of the error.\n    Returns:\n        A string with the cell information.\n    \"\"\"\n    cell_type = cell[\"cell_type\"]\n    source = cell[\"source\"]\n    output = cell[\"outputs\"]\n    if include_outputs and cell_type == \"code\" and output:\n        if \"ename\" in output[0].keys():\n            error_name = output[0][\"ename\"]\n            error_value = output[0][\"evalue\"]\n            if traceback:\n                traceback = output[0][\"traceback\"]\n                return (\n                    f\"'{cell_type}' cell: '{source}'\\n, gives error '{error_name}',\"\n                    f\" with description '{error_value}'\\n\"\n                    f\"and traceback '{traceback}'\\n\\n\"\n                )\n            else:\n                return (\n                    f\"'{cell_type}' cell: '{source}'\\n, gives error '{error_name}',\"\n                    f\"with description '{error_value}'\\n\\n\"\n                )\n        elif output[0][\"output_type\"] == \"stream\":\n            output = output[0][\"text\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html"}
{"id": "1ca51484d448-1", "text": "output = output[0][\"text\"]\n            min_output = min(max_output_length, len(output))\n            return (\n                f\"'{cell_type}' cell: '{source}'\\n with \"\n                f\"output: '{output[:min_output]}'\\n\\n\"\n            )\n    else:\n        return f\"'{cell_type}' cell: '{source}'\\n\\n\"\n    return \"\"\n[docs]def remove_newlines(x: Any) -> Any:\n    \"\"\"Recursively remove newlines, no matter the data structure they are stored in.\"\"\"\n    import pandas as pd\n    if isinstance(x, str):\n        return x.replace(\"\\n\", \"\")\n    elif isinstance(x, list):\n        return [remove_newlines(elem) for elem in x]\n    elif isinstance(x, pd.DataFrame):\n        return x.applymap(remove_newlines)\n    else:\n        return x\n[docs]class NotebookLoader(BaseLoader):\n    \"\"\"Load `Jupyter notebook` (.ipynb) files.\"\"\"\n[docs]    def __init__(\n        self,\n        path: str,\n        include_outputs: bool = False,\n        max_output_length: int = 10,\n        remove_newline: bool = False,\n        traceback: bool = False,\n    ):\n        \"\"\"Initialize with a path.\n        Args:\n            path: The path to load the notebook from.\n            include_outputs: Whether to include the outputs of the cell.\n                Defaults to False.\n            max_output_length: Maximum length of the output to be displayed.\n                Defaults to 10.\n            remove_newline: Whether to remove newlines from the notebook.\n                Defaults to False.\n            traceback: Whether to return a traceback of the error.\n                Defaults to False.\n        \"\"\"\n        self.file_path = path", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html"}
{"id": "1ca51484d448-2", "text": "Defaults to False.\n        \"\"\"\n        self.file_path = path\n        self.include_outputs = include_outputs\n        self.max_output_length = max_output_length\n        self.remove_newline = remove_newline\n        self.traceback = traceback\n[docs]    def load(\n        self,\n    ) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        try:\n            import pandas as pd\n        except ImportError:\n            raise ImportError(\n                \"pandas is needed for Notebook Loader, \"\n                \"please install with `pip install pandas`\"\n            )\n        p = Path(self.file_path)\n        with open(p, encoding=\"utf8\") as f:\n            d = json.load(f)\n        data = pd.json_normalize(d[\"cells\"])\n        filtered_data = data[[\"cell_type\", \"source\", \"outputs\"]]\n        if self.remove_newline:\n            filtered_data = filtered_data.applymap(remove_newlines)\n        text = filtered_data.apply(\n            lambda x: concatenate_cells(\n                x, self.include_outputs, self.max_output_length, self.traceback\n            ),\n            axis=1,\n        ).str.cat(sep=\" \")\n        metadata = {\"source\": str(p)}\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html"}
{"id": "404818753069-0", "text": "Source code for langchain.document_loaders.acreom\nimport re\nfrom pathlib import Path\nfrom typing import Iterator, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class AcreomLoader(BaseLoader):\n    \"\"\"Load `acreom` vault from a directory.\"\"\"\n    FRONT_MATTER_REGEX = re.compile(r\"^---\\n(.*?)\\n---\\n\", re.MULTILINE | re.DOTALL)\n    \"\"\"Regex to match front matter metadata in markdown files.\"\"\"\n[docs]    def __init__(\n        self, path: str, encoding: str = \"UTF-8\", collect_metadata: bool = True\n    ):\n        \"\"\"Initialize the loader.\"\"\"\n        self.file_path = path\n        \"\"\"Path to the directory containing the markdown files.\"\"\"\n        self.encoding = encoding\n        \"\"\"Encoding to use when reading the files.\"\"\"\n        self.collect_metadata = collect_metadata\n        \"\"\"Whether to collect metadata from the front matter.\"\"\"\n    def _parse_front_matter(self, content: str) -> dict:\n        \"\"\"Parse front matter metadata from the content and return it as a dict.\"\"\"\n        if not self.collect_metadata:\n            return {}\n        match = self.FRONT_MATTER_REGEX.search(content)\n        front_matter = {}\n        if match:\n            lines = match.group(1).split(\"\\n\")\n            for line in lines:\n                if \":\" in line:\n                    key, value = line.split(\":\", 1)\n                    front_matter[key.strip()] = value.strip()\n                else:\n                    # Skip lines without a colon\n                    continue\n        return front_matter\n    def _remove_front_matter(self, content: str) -> str:\n        \"\"\"Remove front matter metadata from the given content.\"\"\"\n        if not self.collect_metadata:\n            return content", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/acreom.html"}
{"id": "404818753069-1", "text": "if not self.collect_metadata:\n            return content\n        return self.FRONT_MATTER_REGEX.sub(\"\", content)\n    def _process_acreom_content(self, content: str) -> str:\n        # remove acreom specific elements from content that\n        # do not contribute to the context of current document\n        content = re.sub(r\"\\s*-\\s\\[\\s\\]\\s.*|\\s*\\[\\s\\]\\s.*\", \"\", content)  # rm tasks\n        content = re.sub(r\"#\", \"\", content)  # rm hashtags\n        content = re.sub(r\"\\[\\[.*?\\]\\]\", \"\", content)  # rm doclinks\n        return content\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        ps = list(Path(self.file_path).glob(\"**/*.md\"))\n        for p in ps:\n            with open(p, encoding=self.encoding) as f:\n                text = f.read()\n            front_matter = self._parse_front_matter(text)\n            text = self._remove_front_matter(text)\n            text = self._process_acreom_content(text)\n            metadata = {\n                \"source\": str(p.name),\n                \"path\": str(p),\n                **front_matter,\n            }\n            yield Document(page_content=text, metadata=metadata)\n[docs]    def load(self) -> List[Document]:\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/acreom.html"}
{"id": "97f84442c522-0", "text": "Source code for langchain.document_loaders.git\nimport os\nfrom typing import Callable, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class GitLoader(BaseLoader):\n    \"\"\"Load `Git` repository files.\n    The Repository can be local on disk available at `repo_path`,\n    or remote at `clone_url` that will be cloned to `repo_path`.\n    Currently, supports only text files.\n    Each document represents one file in the repository. The `path` points to\n    the local Git repository, and the `branch` specifies the branch to load\n    files from. By default, it loads from the `main` branch.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        repo_path: str,\n        clone_url: Optional[str] = None,\n        branch: Optional[str] = \"main\",\n        file_filter: Optional[Callable[[str], bool]] = None,\n    ):\n        \"\"\"\n        Args:\n            repo_path: The path to the Git repository.\n            clone_url: Optional. The URL to clone the repository from.\n            branch: Optional. The branch to load files from. Defaults to `main`.\n            file_filter: Optional. A function that takes a file path and returns\n              a boolean indicating whether to load the file. Defaults to None.\n        \"\"\"\n        self.repo_path = repo_path\n        self.clone_url = clone_url\n        self.branch = branch\n        self.file_filter = file_filter\n[docs]    def load(self) -> List[Document]:\n        try:\n            from git import Blob, Repo  # type: ignore\n        except ImportError as ex:\n            raise ImportError(\n                \"Could not import git python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html"}
{"id": "97f84442c522-1", "text": "raise ImportError(\n                \"Could not import git python package. \"\n                \"Please install it with `pip install GitPython`.\"\n            ) from ex\n        if not os.path.exists(self.repo_path) and self.clone_url is None:\n            raise ValueError(f\"Path {self.repo_path} does not exist\")\n        elif self.clone_url:\n            # If the repo_path already contains a git repository, verify that it's the\n            # same repository as the one we're trying to clone.\n            if os.path.isdir(os.path.join(self.repo_path, \".git\")):\n                repo = Repo(self.repo_path)\n                # If the existing repository is not the same as the one we're trying to\n                # clone, raise an error.\n                if repo.remotes.origin.url != self.clone_url:\n                    raise ValueError(\n                        \"A different repository is already cloned at this path.\"\n                    )\n            else:\n                repo = Repo.clone_from(self.clone_url, self.repo_path)\n            repo.git.checkout(self.branch)\n        else:\n            repo = Repo(self.repo_path)\n            repo.git.checkout(self.branch)\n        docs: List[Document] = []\n        for item in repo.tree().traverse():\n            if not isinstance(item, Blob):\n                continue\n            file_path = os.path.join(self.repo_path, item.path)\n            ignored_files = repo.ignored([file_path])  # type: ignore\n            if len(ignored_files):\n                continue\n            # uses filter to skip files\n            if self.file_filter and not self.file_filter(file_path):\n                continue\n            rel_file_path = os.path.relpath(file_path, self.repo_path)\n            try:\n                with open(file_path, \"rb\") as f:\n                    content = f.read()\n                    file_type = os.path.splitext(item.name)[1]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html"}
{"id": "97f84442c522-2", "text": "content = f.read()\n                    file_type = os.path.splitext(item.name)[1]\n                    # loads only text files\n                    try:\n                        text_content = content.decode(\"utf-8\")\n                    except UnicodeDecodeError:\n                        continue\n                    metadata = {\n                        \"source\": rel_file_path,\n                        \"file_path\": rel_file_path,\n                        \"file_name\": item.name,\n                        \"file_type\": file_type,\n                    }\n                    doc = Document(page_content=text_content, metadata=metadata)\n                    docs.append(doc)\n            except Exception as e:\n                print(f\"Error reading file {file_path}: {e}\")\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html"}
{"id": "2fa6a7c0b438-0", "text": "Source code for langchain.document_loaders.arxiv\nfrom typing import Any, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utilities.arxiv import ArxivAPIWrapper\n[docs]class ArxivLoader(BaseLoader):\n    \"\"\"Load a query result from `Arxiv`.\n    The loader converts the original PDF format into the text.\n    Args:\n        Supports all arguments of `ArxivAPIWrapper`.\n    \"\"\"\n[docs]    def __init__(\n        self, query: str, doc_content_chars_max: Optional[int] = None, **kwargs: Any\n    ):\n        self.query = query\n        self.client = ArxivAPIWrapper(\n            doc_content_chars_max=doc_content_chars_max, **kwargs\n        )\n[docs]    def load(self) -> List[Document]:\n        return self.client.load(self.query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/arxiv.html"}
{"id": "4c3e6a6e11bc-0", "text": "Source code for langchain.document_loaders.email\nimport os\nfrom typing import Any, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.unstructured import (\n    UnstructuredFileLoader,\n    satisfies_min_unstructured_version,\n)\n[docs]class UnstructuredEmailLoader(UnstructuredFileLoader):\n    \"\"\"Load email files using `Unstructured`.\n    Works with both\n    .eml and .msg files. You can process attachments in addition to the\n    e-mail message itself by passing process_attachments=True into the\n    constructor for the loader. By default, attachments will be processed\n    with the unstructured partition function. If you already know the document\n    types of the attachments, you can specify another partitioning function\n    with the attachment partitioner kwarg.\n    Example\n    -------\n    from langchain.document_loaders import UnstructuredEmailLoader\n    loader = UnstructuredEmailLoader(\"example_data/fake-email.eml\", mode=\"elements\")\n    loader.load()\n    Example\n    -------\n    from langchain.document_loaders import UnstructuredEmailLoader\n    loader = UnstructuredEmailLoader(\n        \"example_data/fake-email-attachment.eml\",\n        mode=\"elements\",\n        process_attachments=True,\n    )\n    loader.load()\n    \"\"\"\n[docs]    def __init__(\n        self, file_path: str, mode: str = \"single\", **unstructured_kwargs: Any\n    ):\n        process_attachments = unstructured_kwargs.get(\"process_attachments\")\n        attachment_partitioner = unstructured_kwargs.get(\"attachment_partitioner\")\n        if process_attachments and attachment_partitioner is None:\n            from unstructured.partition.auto import partition\n            unstructured_kwargs[\"attachment_partitioner\"] = partition", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/email.html"}
{"id": "4c3e6a6e11bc-1", "text": "unstructured_kwargs[\"attachment_partitioner\"] = partition\n        super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)\n    def _get_elements(self) -> List:\n        from unstructured.file_utils.filetype import FileType, detect_filetype\n        filetype = detect_filetype(self.file_path)\n        if filetype == FileType.EML:\n            from unstructured.partition.email import partition_email\n            return partition_email(filename=self.file_path, **self.unstructured_kwargs)\n        elif satisfies_min_unstructured_version(\"0.5.8\") and filetype == FileType.MSG:\n            from unstructured.partition.msg import partition_msg\n            return partition_msg(filename=self.file_path, **self.unstructured_kwargs)\n        else:\n            raise ValueError(\n                f\"Filetype {filetype} is not supported in UnstructuredEmailLoader.\"\n            )\n[docs]class OutlookMessageLoader(BaseLoader):\n    \"\"\"\n    Loads Outlook Message files using extract_msg.\n    https://github.com/TeamMsgExtractor/msg-extractor\n    \"\"\"\n[docs]    def __init__(self, file_path: str):\n        \"\"\"Initialize with a file path.\n        Args:\n            file_path: The path to the Outlook Message file.\n        \"\"\"\n        self.file_path = file_path\n        if not os.path.isfile(self.file_path):\n            raise ValueError(\"File path %s is not a valid file\" % self.file_path)\n        try:\n            import extract_msg  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"extract_msg is not installed. Please install it with \"\n                \"`pip install extract_msg`\"\n            )\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load data into document objects.\"\"\"\n        import extract_msg\n        msg = extract_msg.Message(self.file_path)\n        return [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/email.html"}
{"id": "4c3e6a6e11bc-2", "text": "import extract_msg\n        msg = extract_msg.Message(self.file_path)\n        return [\n            Document(\n                page_content=msg.body,\n                metadata={\n                    \"source\": self.file_path,\n                    \"subject\": msg.subject,\n                    \"sender\": msg.sender,\n                    \"date\": msg.date,\n                },\n            )\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/email.html"}
{"id": "4d3ea93e8697-0", "text": "Source code for langchain.document_loaders.srt\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class SRTLoader(BaseLoader):\n    \"\"\"Load `.srt` (subtitle) files.\"\"\"\n[docs]    def __init__(self, file_path: str):\n        \"\"\"Initialize with a file path.\"\"\"\n        try:\n            import pysrt  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"package `pysrt` not found, please install it with `pip install pysrt`\"\n            )\n        self.file_path = file_path\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load using pysrt file.\"\"\"\n        import pysrt\n        parsed_info = pysrt.open(self.file_path)\n        text = \" \".join([t.text for t in parsed_info])\n        metadata = {\"source\": self.file_path}\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/srt.html"}
{"id": "3e4df9f1cdb5-0", "text": "Source code for langchain.document_loaders.text\nimport logging\nfrom typing import List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.helpers import detect_file_encodings\nlogger = logging.getLogger(__name__)\n[docs]class TextLoader(BaseLoader):\n    \"\"\"Load text file.\n    Args:\n        file_path: Path to the file to load.\n        encoding: File encoding to use. If `None`, the file will be loaded\n        with the default system encoding.\n        autodetect_encoding: Whether to try to autodetect the file encoding\n            if the specified encoding fails.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        encoding: Optional[str] = None,\n        autodetect_encoding: bool = False,\n    ):\n        \"\"\"Initialize with file path.\"\"\"\n        self.file_path = file_path\n        self.encoding = encoding\n        self.autodetect_encoding = autodetect_encoding\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load from file path.\"\"\"\n        text = \"\"\n        try:\n            with open(self.file_path, encoding=self.encoding) as f:\n                text = f.read()\n        except UnicodeDecodeError as e:\n            if self.autodetect_encoding:\n                detected_encodings = detect_file_encodings(self.file_path)\n                for encoding in detected_encodings:\n                    logger.debug(f\"Trying encoding: {encoding.encoding}\")\n                    try:\n                        with open(self.file_path, encoding=encoding.encoding) as f:\n                            text = f.read()\n                        break\n                    except UnicodeDecodeError:\n                        continue\n            else:\n                raise RuntimeError(f\"Error loading {self.file_path}\") from e\n        except Exception as e:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html"}
{"id": "3e4df9f1cdb5-1", "text": "except Exception as e:\n            raise RuntimeError(f\"Error loading {self.file_path}\") from e\n        metadata = {\"source\": self.file_path}\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html"}
{"id": "4f4d1453f19a-0", "text": "Source code for langchain.document_loaders.notiondb\nfrom typing import Any, Dict, List, Optional\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nNOTION_BASE_URL = \"https://api.notion.com/v1\"\nDATABASE_URL = NOTION_BASE_URL + \"/databases/{database_id}/query\"\nPAGE_URL = NOTION_BASE_URL + \"/pages/{page_id}\"\nBLOCK_URL = NOTION_BASE_URL + \"/blocks/{block_id}/children\"\n[docs]class NotionDBLoader(BaseLoader):\n    \"\"\"Load from `Notion DB`.\n    Reads content from pages within a Notion Database.\n    Args:\n        integration_token (str): Notion integration token.\n        database_id (str): Notion database id.\n        request_timeout_sec (int): Timeout for Notion requests in seconds.\n            Defaults to 10.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        integration_token: str,\n        database_id: str,\n        request_timeout_sec: Optional[int] = 10,\n    ) -> None:\n        \"\"\"Initialize with parameters.\"\"\"\n        if not integration_token:\n            raise ValueError(\"integration_token must be provided\")\n        if not database_id:\n            raise ValueError(\"database_id must be provided\")\n        self.token = integration_token\n        self.database_id = database_id\n        self.headers = {\n            \"Authorization\": \"Bearer \" + self.token,\n            \"Content-Type\": \"application/json\",\n            \"Notion-Version\": \"2022-06-28\",\n        }\n        self.request_timeout_sec = request_timeout_sec\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents from the Notion database.\n        Returns:\n            List[Document]: List of documents.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html"}
{"id": "4f4d1453f19a-1", "text": "Returns:\n            List[Document]: List of documents.\n        \"\"\"\n        page_summaries = self._retrieve_page_summaries()\n        return list(self.load_page(page_summary) for page_summary in page_summaries)\n    def _retrieve_page_summaries(\n        self, query_dict: Dict[str, Any] = {\"page_size\": 100}\n    ) -> List[Dict[str, Any]]:\n        \"\"\"Get all the pages from a Notion database.\"\"\"\n        pages: List[Dict[str, Any]] = []\n        while True:\n            data = self._request(\n                DATABASE_URL.format(database_id=self.database_id),\n                method=\"POST\",\n                query_dict=query_dict,\n            )\n            pages.extend(data.get(\"results\"))\n            if not data.get(\"has_more\"):\n                break\n            query_dict[\"start_cursor\"] = data.get(\"next_cursor\")\n        return pages\n[docs]    def load_page(self, page_summary: Dict[str, Any]) -> Document:\n        \"\"\"Read a page.\n        Args:\n            page_summary: Page summary from Notion API.\n        \"\"\"\n        page_id = page_summary[\"id\"]\n        # load properties as metadata\n        metadata: Dict[str, Any] = {}\n        for prop_name, prop_data in page_summary[\"properties\"].items():\n            prop_type = prop_data[\"type\"]\n            if prop_type == \"rich_text\":\n                value = (\n                    prop_data[\"rich_text\"][0][\"plain_text\"]\n                    if prop_data[\"rich_text\"]\n                    else None\n                )\n            elif prop_type == \"title\":\n                value = (\n                    prop_data[\"title\"][0][\"plain_text\"] if prop_data[\"title\"] else None\n                )\n            elif prop_type == \"multi_select\":\n                value = (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html"}
{"id": "4f4d1453f19a-2", "text": ")\n            elif prop_type == \"multi_select\":\n                value = (\n                    [item[\"name\"] for item in prop_data[\"multi_select\"]]\n                    if prop_data[\"multi_select\"]\n                    else []\n                )\n            elif prop_type == \"url\":\n                value = prop_data[\"url\"]\n            elif prop_type == \"unique_id\":\n                value = (\n                    f'{prop_data[\"unique_id\"][\"prefix\"]}-{prop_data[\"unique_id\"][\"number\"]}'\n                    if prop_data[\"unique_id\"]\n                    else None\n                )\n            elif prop_type == \"status\":\n                value = prop_data[\"status\"][\"name\"] if prop_data[\"status\"] else None\n            elif prop_type == \"people\":\n                value = (\n                    [item[\"name\"] for item in prop_data[\"people\"]]\n                    if prop_data[\"people\"]\n                    else []\n                )\n            elif prop_type == \"date\":\n                value = prop_data[\"date\"] if prop_data[\"date\"] else None\n            elif prop_type == \"last_edited_time\":\n                value = (\n                    prop_data[\"last_edited_time\"]\n                    if prop_data[\"last_edited_time\"]\n                    else None\n                )\n            elif prop_type == \"created_time\":\n                value = prop_data[\"created_time\"] if prop_data[\"created_time\"] else None\n            elif prop_type == \"checkbox\":\n                value = prop_data[\"checkbox\"]\n            elif prop_type == \"email\":\n                value = prop_data[\"email\"]\n            elif prop_type == \"number\":\n                value = prop_data[\"number\"]\n            elif prop_type == \"select\":\n                value = prop_data[\"select\"][\"name\"] if prop_data[\"select\"] else None\n            else:\n                value = None\n            metadata[prop_name.lower()] = value", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html"}
{"id": "4f4d1453f19a-3", "text": "else:\n                value = None\n            metadata[prop_name.lower()] = value\n        metadata[\"id\"] = page_id\n        return Document(page_content=self._load_blocks(page_id), metadata=metadata)\n    def _load_blocks(self, block_id: str, num_tabs: int = 0) -> str:\n        \"\"\"Read a block and its children.\"\"\"\n        result_lines_arr: List[str] = []\n        cur_block_id: str = block_id\n        while cur_block_id:\n            data = self._request(BLOCK_URL.format(block_id=cur_block_id))\n            for result in data[\"results\"]:\n                result_obj = result[result[\"type\"]]\n                if \"rich_text\" not in result_obj:\n                    continue\n                cur_result_text_arr: List[str] = []\n                for rich_text in result_obj[\"rich_text\"]:\n                    if \"text\" in rich_text:\n                        cur_result_text_arr.append(\n                            \"\\t\" * num_tabs + rich_text[\"text\"][\"content\"]\n                        )\n                if result[\"has_children\"]:\n                    children_text = self._load_blocks(\n                        result[\"id\"], num_tabs=num_tabs + 1\n                    )\n                    cur_result_text_arr.append(children_text)\n                result_lines_arr.append(\"\\n\".join(cur_result_text_arr))\n            cur_block_id = data.get(\"next_cursor\")\n        return \"\\n\".join(result_lines_arr)\n    def _request(\n        self, url: str, method: str = \"GET\", query_dict: Dict[str, Any] = {}\n    ) -> Any:\n        res = requests.request(\n            method,\n            url,\n            headers=self.headers,\n            json=query_dict,\n            timeout=self.request_timeout_sec,\n        )\n        res.raise_for_status()\n        return res.json()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html"}
{"id": "0e4808abcab7-0", "text": "Source code for langchain.document_loaders.rocksetdb\nfrom typing import Any, Callable, Iterator, List, Optional, Tuple\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.schema import Document\n[docs]def default_joiner(docs: List[Tuple[str, Any]]) -> str:\n    \"\"\"Default joiner for content columns.\"\"\"\n    return \"\\n\".join([doc[1] for doc in docs])\n[docs]class ColumnNotFoundError(Exception):\n    \"\"\"Column not found error.\"\"\"\n    def __init__(self, missing_key: str, query: str):\n        super().__init__(f'Column \"{missing_key}\" not selected in query:\\n{query}')\n[docs]class RocksetLoader(BaseLoader):\n    \"\"\"Load from a `Rockset` database.\n    To use, you should have the `rockset` python package installed.\n    Example:\n        .. code-block:: python\n            # This code will load 3 records from the \"langchain_demo\"\n            # collection as Documents, with the `text` column used as\n            # the content\n            from langchain.document_loaders import RocksetLoader\n            from rockset import RocksetClient, Regions, models\n            loader = RocksetLoader(\n                RocksetClient(Regions.usw2a1, \"<api key>\"),\n                models.QueryRequestSql(\n                    query=\"select * from langchain_demo limit 3\"\n                ),\n                [\"text\"]\n            )\n        )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        client: Any,\n        query: Any,\n        content_keys: List[str],\n        metadata_keys: Optional[List[str]] = None,\n        content_columns_joiner: Callable[[List[Tuple[str, Any]]], str] = default_joiner,\n    ):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rocksetdb.html"}
{"id": "0e4808abcab7-1", "text": "):\n        \"\"\"Initialize with Rockset client.\n        Args:\n            client: Rockset client object.\n            query: Rockset query object.\n            content_keys: The collection columns to be written into the `page_content`\n                of the Documents.\n            metadata_keys: The collection columns to be written into the `metadata` of\n                the Documents. By default, this is all the keys in the document.\n            content_columns_joiner: Method that joins content_keys and its values into a\n                string. It's method that takes in a List[Tuple[str, Any]]],\n                representing a list of tuples of (column name, column value).\n                By default, this is a method that joins each column value with a new\n                line. This method is only relevant if there are multiple content_keys.\n        \"\"\"\n        try:\n            from rockset import QueryPaginator, RocksetClient\n            from rockset.models import QueryRequestSql\n        except ImportError:\n            raise ImportError(\n                \"Could not import rockset client python package. \"\n                \"Please install it with `pip install rockset`.\"\n            )\n        if not isinstance(client, RocksetClient):\n            raise ValueError(\n                f\"client should be an instance of rockset.RocksetClient, \"\n                f\"got {type(client)}\"\n            )\n        if not isinstance(query, QueryRequestSql):\n            raise ValueError(\n                f\"query should be an instance of rockset.model.QueryRequestSql, \"\n                f\"got {type(query)}\"\n            )\n        self.client = client\n        self.query = query\n        self.content_keys = content_keys\n        self.content_columns_joiner = content_columns_joiner\n        self.metadata_keys = metadata_keys\n        self.paginator = QueryPaginator\n        self.request_model = QueryRequestSql\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rocksetdb.html"}
{"id": "0e4808abcab7-2", "text": "self.paginator = QueryPaginator\n        self.request_model = QueryRequestSql\n        try:\n            self.client.set_application(\"langchain\")\n        except AttributeError:\n            # ignore\n            pass\n[docs]    def load(self) -> List[Document]:\n        return list(self.lazy_load())\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        query_results = self.client.Queries.query(\n            sql=self.query\n        ).results  # execute the SQL query\n        for doc in query_results:  # for each doc in the response\n            try:\n                yield Document(\n                    page_content=self.content_columns_joiner(\n                        [(col, doc[col]) for col in self.content_keys]\n                    ),\n                    metadata={col: doc[col] for col in self.metadata_keys}\n                    if self.metadata_keys is not None\n                    else doc,\n                )  # try to yield the Document\n            except (\n                KeyError\n            ) as e:  # either content_columns or metadata_columns is invalid\n                raise ColumnNotFoundError(\n                    e.args[0], self.query\n                )  # raise that the column isn't in the db schema", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rocksetdb.html"}
{"id": "9eaac0915f95-0", "text": "Source code for langchain.document_loaders.college_confidential\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.web_base import WebBaseLoader\n[docs]class CollegeConfidentialLoader(WebBaseLoader):\n    \"\"\"Load `College Confidential` webpages.\"\"\"\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load webpages as Documents.\"\"\"\n        soup = self.scrape()\n        text = soup.select_one(\"main[class='skin-handler']\").text\n        metadata = {\"source\": self.web_path}\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/college_confidential.html"}
{"id": "c060b3c53d31-0", "text": "Source code for langchain.document_loaders.xml\n\"\"\"Loads Microsoft Excel files.\"\"\"\nfrom typing import Any, List\nfrom langchain.document_loaders.unstructured import (\n    UnstructuredFileLoader,\n    validate_unstructured_version,\n)\n[docs]class UnstructuredXMLLoader(UnstructuredFileLoader):\n    \"\"\"Load `XML` file using `Unstructured`.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredXMLLoader\n    loader = UnstructuredXMLLoader(\n        \"example.xml\", mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition-xml\n    \"\"\"\n[docs]    def __init__(\n        self, file_path: str, mode: str = \"single\", **unstructured_kwargs: Any\n    ):\n        validate_unstructured_version(min_unstructured_version=\"0.6.7\")\n        super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)\n    def _get_elements(self) -> List:\n        from unstructured.partition.xml import partition_xml\n        return partition_xml(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/xml.html"}
{"id": "b0eff740e71a-0", "text": "Source code for langchain.document_loaders.spreedly\nimport json\nimport urllib.request\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utils import stringify_dict\nSPREEDLY_ENDPOINTS = {\n    \"gateways_options\": \"https://core.spreedly.com/v1/gateways_options.json\",\n    \"gateways\": \"https://core.spreedly.com/v1/gateways.json\",\n    \"receivers_options\": \"https://core.spreedly.com/v1/receivers_options.json\",\n    \"receivers\": \"https://core.spreedly.com/v1/receivers.json\",\n    \"payment_methods\": \"https://core.spreedly.com/v1/payment_methods.json\",\n    \"certificates\": \"https://core.spreedly.com/v1/certificates.json\",\n    \"transactions\": \"https://core.spreedly.com/v1/transactions.json\",\n    \"environments\": \"https://core.spreedly.com/v1/environments.json\",\n}\n[docs]class SpreedlyLoader(BaseLoader):\n    \"\"\"Load from `Spreedly` API.\"\"\"\n[docs]    def __init__(self, access_token: str, resource: str) -> None:\n        \"\"\"Initialize with an access token and a resource.\n        Args:\n            access_token: The access token.\n            resource: The resource.\n        \"\"\"\n        self.access_token = access_token\n        self.resource = resource\n        self.headers = {\n            \"Authorization\": f\"Bearer {self.access_token}\",\n            \"Accept\": \"application/json\",\n        }\n    def _make_request(self, url: str) -> List[Document]:\n        request = urllib.request.Request(url, headers=self.headers)\n        with urllib.request.urlopen(request) as response:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/spreedly.html"}
{"id": "b0eff740e71a-1", "text": "with urllib.request.urlopen(request) as response:\n            json_data = json.loads(response.read().decode())\n            text = stringify_dict(json_data)\n            metadata = {\"source\": url}\n            return [Document(page_content=text, metadata=metadata)]\n    def _get_resource(self) -> List[Document]:\n        endpoint = SPREEDLY_ENDPOINTS.get(self.resource)\n        if endpoint is None:\n            return []\n        return self._make_request(endpoint)\n[docs]    def load(self) -> List[Document]:\n        return self._get_resource()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/spreedly.html"}
{"id": "0ea0cdc21abc-0", "text": "Source code for langchain.document_loaders.gutenberg\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class GutenbergLoader(BaseLoader):\n    \"\"\"Load from `Gutenberg.org`.\"\"\"\n[docs]    def __init__(self, file_path: str):\n        \"\"\"Initialize with a file path.\"\"\"\n        if not file_path.startswith(\"https://www.gutenberg.org\"):\n            raise ValueError(\"file path must start with 'https://www.gutenberg.org'\")\n        if not file_path.endswith(\".txt\"):\n            raise ValueError(\"file path must end with '.txt'\")\n        self.file_path = file_path\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load file.\"\"\"\n        from urllib.request import urlopen\n        elements = urlopen(self.file_path)\n        text = \"\\n\\n\".join([str(el.decode(\"utf-8-sig\")) for el in elements])\n        metadata = {\"source\": self.file_path}\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gutenberg.html"}
{"id": "6148429fcbdd-0", "text": "Source code for langchain.document_loaders.base_o365\n\"\"\"Base class for all loaders that uses O365 Package\"\"\"\nfrom __future__ import annotations\nimport logging\nimport os\nimport tempfile\nfrom abc import abstractmethod\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Dict, Iterable, List, Sequence, Union\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.blob_loaders.file_system import FileSystemBlobLoader\nfrom langchain.document_loaders.blob_loaders.schema import Blob\nfrom langchain.pydantic_v1 import BaseModel, BaseSettings, Field, FilePath, SecretStr\nif TYPE_CHECKING:\n    from O365 import Account\n    from O365.drive import Drive, Folder\nlogger = logging.getLogger(__name__)\nCHUNK_SIZE = 1024 * 1024 * 5\nclass _O365Settings(BaseSettings):\n    client_id: str = Field(..., env=\"O365_CLIENT_ID\")\n    client_secret: SecretStr = Field(..., env=\"O365_CLIENT_SECRET\")\n    class Config:\n        env_prefix = \"\"\n        case_sentive = False\n        env_file = \".env\"\nclass _O365TokenStorage(BaseSettings):\n    token_path: FilePath = Path.home() / \".credentials\" / \"o365_token.txt\"\nclass _FileType(str, Enum):\n    DOC = \"doc\"\n    DOCX = \"docx\"\n    PDF = \"pdf\"\n[docs]def fetch_mime_types(file_types: Sequence[_FileType]) -> Dict[str, str]:\n    \"\"\"Fetch the mime types for the specified file types.\"\"\"\n    mime_types_mapping = {}\n    for file_type in file_types:\n        if file_type.value == \"doc\":\n            mime_types_mapping[file_type.value] = \"application/msword\"\n        elif file_type.value == \"docx\":", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/base_o365.html"}
{"id": "6148429fcbdd-1", "text": "elif file_type.value == \"docx\":\n            mime_types_mapping[\n                file_type.value\n            ] = \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"  # noqa: E501\n        elif file_type.value == \"pdf\":\n            mime_types_mapping[file_type.value] = \"application/pdf\"\n    return mime_types_mapping\n[docs]class O365BaseLoader(BaseLoader, BaseModel):\n    \"\"\"Base class for all loaders that uses O365 Package\"\"\"\n    settings: _O365Settings = Field(default_factory=_O365Settings)\n    \"\"\"Settings for the Office365 API client.\"\"\"\n    auth_with_token: bool = False\n    \"\"\"Whether to authenticate with a token or not. Defaults to False.\"\"\"\n    chunk_size: Union[int, str] = CHUNK_SIZE\n    \"\"\"Number of bytes to retrieve from each api call to the server. int or 'auto'.\"\"\"\n    @property\n    @abstractmethod\n    def _file_types(self) -> Sequence[_FileType]:\n        \"\"\"Return supported file types.\"\"\"\n    @property\n    def _fetch_mime_types(self) -> Dict[str, str]:\n        \"\"\"Return a dict of supported file types to corresponding mime types.\"\"\"\n        return fetch_mime_types(self._file_types)\n    @property\n    @abstractmethod\n    def _scopes(self) -> List[str]:\n        \"\"\"Return required scopes.\"\"\"\n    def _load_from_folder(self, folder: Folder) -> Iterable[Blob]:\n        \"\"\"Lazily load all files from a specified folder of the configured MIME type.\n        Args:\n            folder: The Folder instance from which the files are to be loaded. This\n                Folder instance should represent a directory in a file system where the\n                files are stored.\n        Yields:\n            An iterator that yields Blob instances, which are binary representations of\n                the files loaded from the folder.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/base_o365.html"}
{"id": "6148429fcbdd-2", "text": "the files loaded from the folder.\n        \"\"\"\n        file_mime_types = self._fetch_mime_types\n        items = folder.get_items()\n        with tempfile.TemporaryDirectory() as temp_dir:\n            os.makedirs(os.path.dirname(temp_dir), exist_ok=True)\n            for file in items:\n                if file.is_file:\n                    if file.mime_type in list(file_mime_types.values()):\n                        file.download(to_path=temp_dir, chunk_size=self.chunk_size)\n            loader = FileSystemBlobLoader(path=temp_dir)\n            yield from loader.yield_blobs()\n    def _load_from_object_ids(\n        self, drive: Drive, object_ids: List[str]\n    ) -> Iterable[Blob]:\n        \"\"\"Lazily load files specified by their object_ids from a drive.\n        Load files into the system as binary large objects (Blobs) and return Iterable.\n        Args:\n            drive: The Drive instance from which the files are to be loaded. This Drive\n                instance should represent a cloud storage service or similar storage\n                system where the files are stored.\n            object_ids: A list of object_id strings. Each object_id represents a unique\n                identifier for a file in the drive.\n        Yields:\n            An iterator that yields Blob instances, which are binary representations of\n            the files loaded from the drive using the specified object_ids.\n        \"\"\"\n        file_mime_types = self._fetch_mime_types\n        with tempfile.TemporaryDirectory() as temp_dir:\n            for object_id in object_ids:\n                file = drive.get_item(object_id)\n                if not file:\n                    logging.warning(\n                        \"There isn't a file with\"\n                        f\"object_id {object_id} in drive {drive}.\"\n                    )\n                    continue\n                if file.is_file:\n                    if file.mime_type in list(file_mime_types.values()):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/base_o365.html"}
{"id": "6148429fcbdd-3", "text": "if file.is_file:\n                    if file.mime_type in list(file_mime_types.values()):\n                        file.download(to_path=temp_dir, chunk_size=self.chunk_size)\n            loader = FileSystemBlobLoader(path=temp_dir)\n            yield from loader.yield_blobs()\n    def _auth(self) -> Account:\n        \"\"\"Authenticates the OneDrive API client\n        Returns:\n            The authenticated Account object.\n        \"\"\"\n        try:\n            from O365 import Account, FileSystemTokenBackend\n        except ImportError:\n            raise ImportError(\n                \"O365 package not found, please install it with `pip install o365`\"\n            )\n        if self.auth_with_token:\n            token_storage = _O365TokenStorage()\n            token_path = token_storage.token_path\n            token_backend = FileSystemTokenBackend(\n                token_path=token_path.parent, token_filename=token_path.name\n            )\n            account = Account(\n                credentials=(\n                    self.settings.client_id,\n                    self.settings.client_secret.get_secret_value(),\n                ),\n                scopes=self._scopes,\n                token_backend=token_backend,\n                **{\"raise_http_errors\": False},\n            )\n        else:\n            token_backend = FileSystemTokenBackend(\n                token_path=Path.home() / \".credentials\"\n            )\n            account = Account(\n                credentials=(\n                    self.settings.client_id,\n                    self.settings.client_secret.get_secret_value(),\n                ),\n                scopes=self._scopes,\n                token_backend=token_backend,\n                **{\"raise_http_errors\": False},\n            )\n            # make the auth\n            account.authenticate()\n        return account", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/base_o365.html"}
{"id": "8e40727bb64a-0", "text": "Source code for langchain.document_loaders.lakefs\nimport os\nimport tempfile\nimport urllib.parse\nfrom typing import Any, List, Optional\nfrom urllib.parse import urljoin\nimport requests\nfrom requests.auth import HTTPBasicAuth\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.unstructured import UnstructuredBaseLoader\nfrom langchain.schema import Document\n[docs]class LakeFSClient:\n[docs]    def __init__(\n        self,\n        lakefs_access_key: str,\n        lakefs_secret_key: str,\n        lakefs_endpoint: str,\n    ):\n        self.__endpoint = \"/\".join([lakefs_endpoint, \"api\", \"v1/\"])\n        self.__auth = HTTPBasicAuth(lakefs_access_key, lakefs_secret_key)\n        try:\n            health_check = requests.get(\n                urljoin(self.__endpoint, \"healthcheck\"), auth=self.__auth\n            )\n            health_check.raise_for_status()\n        except Exception:\n            raise ValueError(\n                \"lakeFS server isn't accessible. Make sure lakeFS is running.\"\n            )\n[docs]    def ls_objects(\n        self, repo: str, ref: str, path: str, presign: Optional[bool]\n    ) -> List:\n        qp = {\"prefix\": path, \"presign\": presign}\n        eqp = urllib.parse.urlencode(qp)\n        objects_ls_endpoint = urljoin(\n            self.__endpoint, f\"repositories/{repo}/refs/{ref}/objects/ls?{eqp}\"\n        )\n        olsr = requests.get(objects_ls_endpoint, auth=self.__auth)\n        olsr.raise_for_status()\n        olsr_json = olsr.json()\n        return list(\n            map(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/lakefs.html"}
{"id": "8e40727bb64a-1", "text": "return list(\n            map(\n                lambda res: (res[\"path\"], res[\"physical_address\"]), olsr_json[\"results\"]\n            )\n        )\n[docs]    def is_presign_supported(self) -> bool:\n        config_endpoint = self.__endpoint + \"config\"\n        response = requests.get(config_endpoint, auth=self.__auth)\n        response.raise_for_status()\n        config = response.json()\n        return config[\"storage_config\"][\"pre_sign_support\"]\n[docs]class LakeFSLoader(BaseLoader):\n    \"\"\"Load from `lakeFS`.\"\"\"\n    repo: str\n    ref: str\n    path: str\n[docs]    def __init__(\n        self,\n        lakefs_access_key: str,\n        lakefs_secret_key: str,\n        lakefs_endpoint: str,\n        repo: Optional[str] = None,\n        ref: Optional[str] = \"main\",\n        path: Optional[str] = \"\",\n    ):\n        \"\"\"\n        :param lakefs_access_key: [required] lakeFS server's access key\n        :param lakefs_secret_key: [required] lakeFS server's secret key\n        :param lakefs_endpoint: [required] lakeFS server's endpoint address,\n               ex: https://example.my-lakefs.com\n        :param repo: [optional, default = ''] target repository\n        :param ref: [optional, default = 'main'] target ref (branch name,\n               tag, or commit ID)\n        :param path: [optional, default = ''] target path\n        \"\"\"\n        self.__lakefs_client = LakeFSClient(\n            lakefs_access_key, lakefs_secret_key, lakefs_endpoint\n        )\n        self.repo = \"\" if repo is None or repo == \"\" else str(repo)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/lakefs.html"}
{"id": "8e40727bb64a-2", "text": "self.repo = \"\" if repo is None or repo == \"\" else str(repo)\n        self.ref = \"main\" if ref is None or ref == \"\" else str(ref)\n        self.path = \"\" if path is None else str(path)\n[docs]    def set_path(self, path: str) -> None:\n        self.path = path\n[docs]    def set_ref(self, ref: str) -> None:\n        self.ref = ref\n[docs]    def set_repo(self, repo: str) -> None:\n        self.repo = repo\n[docs]    def load(self) -> List[Document]:\n        self.__validate_instance()\n        presigned = self.__lakefs_client.is_presign_supported()\n        docs: List[Document] = []\n        objs = self.__lakefs_client.ls_objects(\n            repo=self.repo, ref=self.ref, path=self.path, presign=presigned\n        )\n        for obj in objs:\n            lakefs_unstructured_loader = UnstructuredLakeFSLoader(\n                obj[1], self.repo, self.ref, obj[0], presigned\n            )\n            docs.extend(lakefs_unstructured_loader.load())\n        return docs\n    def __validate_instance(self) -> None:\n        if self.repo is None or self.repo == \"\":\n            raise ValueError(\n                \"no repository was provided. use `set_repo` to specify a repository\"\n            )\n        if self.ref is None or self.ref == \"\":\n            raise ValueError(\"no ref was provided. use `set_ref` to specify a ref\")\n        if self.path is None:\n            raise ValueError(\"no path was provided. use `set_path` to specify a path\")\n[docs]class UnstructuredLakeFSLoader(UnstructuredBaseLoader):\n[docs]    def __init__(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/lakefs.html"}
{"id": "8e40727bb64a-3", "text": "[docs]    def __init__(\n        self,\n        url: str,\n        repo: str,\n        ref: str = \"main\",\n        path: str = \"\",\n        presign: bool = True,\n        **unstructured_kwargs: Any,\n    ):\n        \"\"\"\n        Args:\n        :param lakefs_access_key:\n        :param lakefs_secret_key:\n        :param lakefs_endpoint:\n        :param repo:\n        :param ref:\n        \"\"\"\n        super().__init__(**unstructured_kwargs)\n        self.url = url\n        self.repo = repo\n        self.ref = ref\n        self.path = path\n        self.presign = presign\n    def _get_metadata(self) -> dict:\n        return {\"repo\": self.repo, \"ref\": self.ref, \"path\": self.path}\n    def _get_elements(self) -> List:\n        from unstructured.partition.auto import partition\n        local_prefix = \"local://\"\n        if self.presign:\n            with tempfile.TemporaryDirectory() as temp_dir:\n                file_path = f\"{temp_dir}/{self.path.split('/')[-1]}\"\n                os.makedirs(os.path.dirname(file_path), exist_ok=True)\n                response = requests.get(self.url)\n                response.raise_for_status()\n                with open(file_path, mode=\"wb\") as file:\n                    file.write(response.content)\n                return partition(filename=file_path)\n        elif not self.url.startswith(local_prefix):\n            raise ValueError(\n                \"Non pre-signed URLs are supported only with 'local' blockstore\"\n            )\n        else:\n            local_path = self.url[len(local_prefix) :]\n            return partition(filename=local_path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/lakefs.html"}
{"id": "5a5bad3b6d65-0", "text": "Source code for langchain.document_loaders.azure_blob_storage_container\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.azure_blob_storage_file import (\n    AzureBlobStorageFileLoader,\n)\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class AzureBlobStorageContainerLoader(BaseLoader):\n    \"\"\"Load from `Azure Blob Storage` container.\"\"\"\n[docs]    def __init__(self, conn_str: str, container: str, prefix: str = \"\"):\n        \"\"\"Initialize with connection string, container and blob prefix.\"\"\"\n        self.conn_str = conn_str\n        \"\"\"Connection string for Azure Blob Storage.\"\"\"\n        self.container = container\n        \"\"\"Container name.\"\"\"\n        self.prefix = prefix\n        \"\"\"Prefix for blob names.\"\"\"\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        try:\n            from azure.storage.blob import ContainerClient\n        except ImportError as exc:\n            raise ImportError(\n                \"Could not import azure storage blob python package. \"\n                \"Please install it with `pip install azure-storage-blob`.\"\n            ) from exc\n        container = ContainerClient.from_connection_string(\n            conn_str=self.conn_str, container_name=self.container\n        )\n        docs = []\n        blob_list = container.list_blobs(name_starts_with=self.prefix)\n        for blob in blob_list:\n            loader = AzureBlobStorageFileLoader(\n                self.conn_str,\n                self.container,\n                blob.name,  # type: ignore\n            )\n            docs.extend(loader.load())\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/azure_blob_storage_container.html"}
{"id": "0a296f521c5a-0", "text": "Source code for langchain.document_loaders.quip\nimport logging\nimport re\nimport xml.etree.cElementTree\nimport xml.sax.saxutils\nfrom io import BytesIO\nfrom typing import List, Optional, Sequence\nfrom xml.etree.ElementTree import ElementTree\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n_MAXIMUM_TITLE_LENGTH = 64\n[docs]class QuipLoader(BaseLoader):\n    \"\"\"Load `Quip` pages.\n    Port of https://github.com/quip/quip-api/tree/master/samples/baqup\n    \"\"\"\n[docs]    def __init__(\n        self, api_url: str, access_token: str, request_timeout: Optional[int] = 60\n    ):\n        \"\"\"\n        Args:\n            api_url: https://platform.quip.com\n            access_token: token of access quip API. Please refer:\n            https://quip.com/dev/automation/documentation/current#section/Authentication/Get-Access-to-Quip's-APIs\n            request_timeout: timeout of request, default 60s.\n        \"\"\"\n        try:\n            from quip_api.quip import QuipClient\n        except ImportError:\n            raise ImportError(\n                \"`quip_api` package not found, please run \" \"`pip install quip_api`\"\n            )\n        self.quip_client = QuipClient(\n            access_token=access_token, base_url=api_url, request_timeout=request_timeout\n        )\n[docs]    def load(\n        self,\n        folder_ids: Optional[List[str]] = None,\n        thread_ids: Optional[List[str]] = None,\n        max_docs: Optional[int] = 1000,\n        include_all_folders: bool = False,\n        include_comments: bool = False,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/quip.html"}
{"id": "0a296f521c5a-1", "text": "include_all_folders: bool = False,\n        include_comments: bool = False,\n        include_images: bool = False,\n    ) -> List[Document]:\n        \"\"\"\n        Args:\n            :param folder_ids: List of specific folder IDs to load, defaults to None\n            :param thread_ids: List of specific thread IDs to load, defaults to None\n            :param max_docs: Maximum number of docs to retrieve in total, defaults 1000\n            :param include_all_folders: Include all folders that your access_token\n                   can access, but doesn't include your private folder\n            :param include_comments: Include comments, defaults to False\n            :param include_images: Include images, defaults to False\n        \"\"\"\n        if not folder_ids and not thread_ids and not include_all_folders:\n            raise ValueError(\n                \"Must specify at least one among `folder_ids`, `thread_ids` \"\n                \"or set `include_all`_folders as True\"\n            )\n        thread_ids = thread_ids or []\n        if folder_ids:\n            for folder_id in folder_ids:\n                self.get_thread_ids_by_folder_id(folder_id, 0, thread_ids)\n        if include_all_folders:\n            user = self.quip_client.get_authenticated_user()\n            if \"group_folder_ids\" in user:\n                self.get_thread_ids_by_folder_id(\n                    user[\"group_folder_ids\"], 0, thread_ids\n                )\n            if \"shared_folder_ids\" in user:\n                self.get_thread_ids_by_folder_id(\n                    user[\"shared_folder_ids\"], 0, thread_ids\n                )\n        thread_ids = list(set(thread_ids[:max_docs]))\n        return self.process_threads(thread_ids, include_images, include_comments)\n[docs]    def get_thread_ids_by_folder_id(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/quip.html"}
{"id": "0a296f521c5a-2", "text": "[docs]    def get_thread_ids_by_folder_id(\n        self, folder_id: str, depth: int, thread_ids: List[str]\n    ) -> None:\n        \"\"\"Get thread ids by folder id and update in thread_ids\"\"\"\n        from quip_api.quip import HTTPError, QuipError\n        try:\n            folder = self.quip_client.get_folder(folder_id)\n        except QuipError as e:\n            if e.code == 403:\n                logging.warning(\n                    f\"depth {depth}, Skipped over restricted folder {folder_id}, {e}\"\n                )\n            else:\n                logging.warning(\n                    f\"depth {depth}, Skipped over folder {folder_id} \"\n                    f\"due to unknown error {e.code}\"\n                )\n            return\n        except HTTPError as e:\n            logging.warning(\n                f\"depth {depth}, Skipped over folder {folder_id} \"\n                f\"due to HTTP error {e.code}\"\n            )\n            return\n        title = folder[\"folder\"].get(\"title\", \"Folder %s\" % folder_id)\n        logging.info(f\"depth {depth}, Processing folder {title}\")\n        for child in folder[\"children\"]:\n            if \"folder_id\" in child:\n                self.get_thread_ids_by_folder_id(\n                    child[\"folder_id\"], depth + 1, thread_ids\n                )\n            elif \"thread_id\" in child:\n                thread_ids.append(child[\"thread_id\"])\n[docs]    def process_threads(\n        self, thread_ids: Sequence[str], include_images: bool, include_messages: bool\n    ) -> List[Document]:\n        \"\"\"Process a list of thread into a list of documents.\"\"\"\n        docs = []\n        for thread_id in thread_ids:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/quip.html"}
{"id": "0a296f521c5a-3", "text": "docs = []\n        for thread_id in thread_ids:\n            doc = self.process_thread(thread_id, include_images, include_messages)\n            if doc is not None:\n                docs.append(doc)\n        return docs\n[docs]    def process_thread(\n        self, thread_id: str, include_images: bool, include_messages: bool\n    ) -> Optional[Document]:\n        thread = self.quip_client.get_thread(thread_id)\n        thread_id = thread[\"thread\"][\"id\"]\n        title = thread[\"thread\"][\"title\"]\n        link = thread[\"thread\"][\"link\"]\n        update_ts = thread[\"thread\"][\"updated_usec\"]\n        sanitized_title = QuipLoader._sanitize_title(title)\n        logger.info(\n            f\"processing thread {thread_id} title {sanitized_title} \"\n            f\"link {link} update_ts {update_ts}\"\n        )\n        if \"html\" in thread:\n            # Parse the document\n            try:\n                tree = self.quip_client.parse_document_html(thread[\"html\"])\n            except xml.etree.cElementTree.ParseError as e:\n                logger.error(f\"Error parsing thread {title} {thread_id}, skipping, {e}\")\n                return None\n            metadata = {\n                \"title\": sanitized_title,\n                \"update_ts\": update_ts,\n                \"id\": thread_id,\n                \"source\": link,\n            }\n            # Download each image and replace with the new URL\n            text = \"\"\n            if include_images:\n                text = self.process_thread_images(tree)\n            if include_messages:\n                text = text + \"/n\" + self.process_thread_messages(thread_id)\n            return Document(\n                page_content=thread[\"html\"] + text,\n                metadata=metadata,\n            )\n        return None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/quip.html"}
{"id": "0a296f521c5a-4", "text": "metadata=metadata,\n            )\n        return None\n[docs]    def process_thread_images(self, tree: ElementTree) -> str:\n        text = \"\"\n        try:\n            from PIL import Image\n            from pytesseract import pytesseract\n        except ImportError:\n            raise ImportError(\n                \"`Pillow or pytesseract` package not found, \"\n                \"please run \"\n                \"`pip install Pillow` or `pip install pytesseract`\"\n            )\n        for img in tree.iter(\"img\"):\n            src = img.get(\"src\")\n            if not src or not src.startswith(\"/blob\"):\n                continue\n            _, _, thread_id, blob_id = src.split(\"/\")\n            blob_response = self.quip_client.get_blob(thread_id, blob_id)\n            try:\n                image = Image.open(BytesIO(blob_response.read()))\n                text = text + \"\\n\" + pytesseract.image_to_string(image)\n            except OSError as e:\n                logger.error(f\"failed to convert image to text, {e}\")\n                raise e\n        return text\n[docs]    def process_thread_messages(self, thread_id: str) -> str:\n        max_created_usec = None\n        messages = []\n        while True:\n            chunk = self.quip_client.get_messages(\n                thread_id, max_created_usec=max_created_usec, count=100\n            )\n            messages.extend(chunk)\n            if chunk:\n                max_created_usec = chunk[-1][\"created_usec\"] - 1\n            else:\n                break\n        messages.reverse()\n        texts = [message[\"text\"] for message in messages]\n        return \"\\n\".join(texts)\n    @staticmethod\n    def _sanitize_title(title: str) -> str:\n        sanitized_title = re.sub(r\"\\s\", \" \", title)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/quip.html"}
{"id": "0a296f521c5a-5", "text": "sanitized_title = re.sub(r\"\\s\", \" \", title)\n        sanitized_title = re.sub(r\"(?u)[^- \\w.]\", \"\", sanitized_title)\n        if len(sanitized_title) > _MAXIMUM_TITLE_LENGTH:\n            sanitized_title = sanitized_title[:_MAXIMUM_TITLE_LENGTH]\n        return sanitized_title", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/quip.html"}
{"id": "85064aaaa60e-0", "text": "Source code for langchain.document_loaders.word_document\n\"\"\"Loads word documents.\"\"\"\nimport os\nimport tempfile\nfrom abc import ABC\nfrom typing import List\nfrom urllib.parse import urlparse\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.unstructured import UnstructuredFileLoader\n[docs]class Docx2txtLoader(BaseLoader, ABC):\n    \"\"\"Load `DOCX` file using `docx2txt` and chunks at character level.\n    Defaults to check for local file, but if the file is a web path, it will download it\n    to a temporary file, and use that, then clean up the temporary file after completion\n    \"\"\"\n[docs]    def __init__(self, file_path: str):\n        \"\"\"Initialize with file path.\"\"\"\n        self.file_path = file_path\n        if \"~\" in self.file_path:\n            self.file_path = os.path.expanduser(self.file_path)\n        # If the file is a web path, download it to a temporary file, and use that\n        if not os.path.isfile(self.file_path) and self._is_valid_url(self.file_path):\n            r = requests.get(self.file_path)\n            if r.status_code != 200:\n                raise ValueError(\n                    \"Check the url of your file; returned status code %s\"\n                    % r.status_code\n                )\n            self.web_path = self.file_path\n            self.temp_file = tempfile.NamedTemporaryFile()\n            self.temp_file.write(r.content)\n            self.file_path = self.temp_file.name\n        elif not os.path.isfile(self.file_path):\n            raise ValueError(\"File path %s is not a valid file or url\" % self.file_path)\n    def __del__(self) -> None:\n        if hasattr(self, \"temp_file\"):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html"}
{"id": "85064aaaa60e-1", "text": "if hasattr(self, \"temp_file\"):\n            self.temp_file.close()\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load given path as single page.\"\"\"\n        import docx2txt\n        return [\n            Document(\n                page_content=docx2txt.process(self.file_path),\n                metadata={\"source\": self.file_path},\n            )\n        ]\n    @staticmethod\n    def _is_valid_url(url: str) -> bool:\n        \"\"\"Check if the url is valid.\"\"\"\n        parsed = urlparse(url)\n        return bool(parsed.netloc) and bool(parsed.scheme)\n[docs]class UnstructuredWordDocumentLoader(UnstructuredFileLoader):\n    \"\"\"Load `Microsoft Word` file using `Unstructured`.\n    Works with both .docx and .doc files.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredWordDocumentLoader\n    loader = UnstructuredWordDocumentLoader(\n        \"example.docx\", mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition-docx\n    \"\"\"\n    def _get_elements(self) -> List:\n        from unstructured.__version__ import __version__ as __unstructured_version__\n        from unstructured.file_utils.filetype import FileType, detect_filetype", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html"}
{"id": "85064aaaa60e-2", "text": "from unstructured.file_utils.filetype import FileType, detect_filetype\n        unstructured_version = tuple(\n            [int(x) for x in __unstructured_version__.split(\".\")]\n        )\n        # NOTE(MthwRobinson) - magic will raise an import error if the libmagic\n        # system dependency isn't installed. If it's not installed, we'll just\n        # check the file extension\n        try:\n            import magic  # noqa: F401\n            is_doc = detect_filetype(self.file_path) == FileType.DOC\n        except ImportError:\n            _, extension = os.path.splitext(str(self.file_path))\n            is_doc = extension == \".doc\"\n        if is_doc and unstructured_version < (0, 4, 11):\n            raise ValueError(\n                f\"You are on unstructured version {__unstructured_version__}. \"\n                \"Partitioning .doc files is only supported in unstructured>=0.4.11. \"\n                \"Please upgrade the unstructured package and try again.\"\n            )\n        if is_doc:\n            from unstructured.partition.doc import partition_doc\n            return partition_doc(filename=self.file_path, **self.unstructured_kwargs)\n        else:\n            from unstructured.partition.docx import partition_docx\n            return partition_docx(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html"}
{"id": "c017b274f59d-0", "text": "Source code for langchain.document_loaders.s3_file\nfrom __future__ import annotations\nimport os\nimport tempfile\nfrom typing import TYPE_CHECKING, List, Optional, Union\nfrom langchain.document_loaders.unstructured import UnstructuredBaseLoader\nif TYPE_CHECKING:\n    import botocore\n[docs]class S3FileLoader(UnstructuredBaseLoader):\n    \"\"\"Load from `Amazon AWS S3` file.\"\"\"\n[docs]    def __init__(\n        self,\n        bucket: str,\n        key: str,\n        *,\n        region_name: Optional[str] = None,\n        api_version: Optional[str] = None,\n        use_ssl: Optional[bool] = True,\n        verify: Union[str, bool, None] = None,\n        endpoint_url: Optional[str] = None,\n        aws_access_key_id: Optional[str] = None,\n        aws_secret_access_key: Optional[str] = None,\n        aws_session_token: Optional[str] = None,\n        boto_config: Optional[botocore.client.Config] = None,\n    ):\n        \"\"\"Initialize with bucket and key name.\n        :param bucket: The name of the S3 bucket.\n        :param key: The key of the S3 object.\n        :param region_name: The name of the region associated with the client.\n            A client is associated with a single region.\n        :param api_version: The API version to use.  By default, botocore will\n            use the latest API version when creating a client.  You only need\n            to specify this parameter if you want to use a previous API version\n            of the client.\n        :param use_ssl: Whether or not to use SSL.  By default, SSL is used.\n            Note that not all services support non-ssl connections.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_file.html"}
{"id": "c017b274f59d-1", "text": "Note that not all services support non-ssl connections.\n        :param verify: Whether or not to verify SSL certificates.\n            By default SSL certificates are verified.  You can provide the\n            following values:\n            * False - do not validate SSL certificates.  SSL will still be\n              used (unless use_ssl is False), but SSL certificates\n              will not be verified.\n            * path/to/cert/bundle.pem - A filename of the CA cert bundle to\n              uses.  You can specify this argument if you want to use a\n              different CA cert bundle than the one used by botocore.\n        :param endpoint_url: The complete URL to use for the constructed\n            client.  Normally, botocore will automatically construct the\n            appropriate URL to use when communicating with a service.  You can\n            specify a complete URL (including the \"http/https\" scheme) to\n            override this behavior.  If this value is provided, then\n            ``use_ssl`` is ignored.\n        :param aws_access_key_id: The access key to use when creating\n            the client.  This is entirely optional, and if not provided,\n            the credentials configured for the session will automatically\n            be used.  You only need to provide this argument if you want\n            to override the credentials used for this specific client.\n        :param aws_secret_access_key: The secret key to use when creating\n            the client.  Same semantics as aws_access_key_id above.\n        :param aws_session_token: The session token to use when creating\n            the client.  Same semantics as aws_access_key_id above.\n        :type boto_config: botocore.client.Config\n        :param boto_config: Advanced boto3 client configuration options. If a value\n            is specified in the client config, its value will take precedence", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_file.html"}
{"id": "c017b274f59d-2", "text": "is specified in the client config, its value will take precedence\n            over environment variables and configuration values, but not over\n            a value passed explicitly to the method. If a default config\n            object is set on the session, the config object used when creating\n            the client will be the result of calling ``merge()`` on the\n            default config with the config provided to this call.\n        \"\"\"\n        super().__init__()\n        self.bucket = bucket\n        self.key = key\n        self.region_name = region_name\n        self.api_version = api_version\n        self.use_ssl = use_ssl\n        self.verify = verify\n        self.endpoint_url = endpoint_url\n        self.aws_access_key_id = aws_access_key_id\n        self.aws_secret_access_key = aws_secret_access_key\n        self.aws_session_token = aws_session_token\n        self.boto_config = boto_config\n    def _get_elements(self) -> List:\n        \"\"\"Get elements.\"\"\"\n        from unstructured.partition.auto import partition\n        try:\n            import boto3\n        except ImportError:\n            raise ImportError(\n                \"Could not import `boto3` python package. \"\n                \"Please install it with `pip install boto3`.\"\n            )\n        s3 = boto3.client(\n            \"s3\",\n            region_name=self.region_name,\n            api_version=self.api_version,\n            use_ssl=self.use_ssl,\n            verify=self.verify,\n            endpoint_url=self.endpoint_url,\n            aws_access_key_id=self.aws_access_key_id,\n            aws_secret_access_key=self.aws_secret_access_key,\n            aws_session_token=self.aws_session_token,\n            config=self.boto_config,\n        )\n        with tempfile.TemporaryDirectory() as temp_dir:\n            file_path = f\"{temp_dir}/{self.key}\"\n            os.makedirs(os.path.dirname(file_path), exist_ok=True)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_file.html"}
{"id": "c017b274f59d-3", "text": "os.makedirs(os.path.dirname(file_path), exist_ok=True)\n            s3.download_file(self.bucket, self.key, file_path)\n            return partition(filename=file_path)\n    def _get_metadata(self) -> dict:\n        return {\"source\": f\"s3://{self.bucket}/{self.key}\"}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_file.html"}
{"id": "9de608e668e0-0", "text": "Source code for langchain.document_loaders.trello\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Any, List, Literal, Optional, Tuple\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utils import get_from_env\nif TYPE_CHECKING:\n    from trello import Board, Card, TrelloClient\n[docs]class TrelloLoader(BaseLoader):\n    \"\"\"Load cards from a `Trello` board.\"\"\"\n[docs]    def __init__(\n        self,\n        client: TrelloClient,\n        board_name: str,\n        *,\n        include_card_name: bool = True,\n        include_comments: bool = True,\n        include_checklist: bool = True,\n        card_filter: Literal[\"closed\", \"open\", \"all\"] = \"all\",\n        extra_metadata: Tuple[str, ...] = (\"due_date\", \"labels\", \"list\", \"closed\"),\n    ):\n        \"\"\"Initialize Trello loader.\n        Args:\n            client: Trello API client.\n            board_name: The name of the Trello board.\n            include_card_name: Whether to include the name of the card in the document.\n            include_comments: Whether to include the comments on the card in the\n                document.\n            include_checklist: Whether to include the checklist on the card in the\n                document.\n            card_filter: Filter on card status. Valid values are \"closed\", \"open\",\n                \"all\".\n            extra_metadata: List of additional metadata fields to include as document\n                metadata.Valid values are \"due_date\", \"labels\", \"list\", \"closed\".\n        \"\"\"\n        self.client = client\n        self.board_name = board_name\n        self.include_card_name = include_card_name\n        self.include_comments = include_comments", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/trello.html"}
{"id": "9de608e668e0-1", "text": "self.include_card_name = include_card_name\n        self.include_comments = include_comments\n        self.include_checklist = include_checklist\n        self.extra_metadata = extra_metadata\n        self.card_filter = card_filter\n[docs]    @classmethod\n    def from_credentials(\n        cls,\n        board_name: str,\n        *,\n        api_key: Optional[str] = None,\n        token: Optional[str] = None,\n        **kwargs: Any,\n    ) -> TrelloLoader:\n        \"\"\"Convenience constructor that builds TrelloClient init param for you.\n        Args:\n            board_name: The name of the Trello board.\n            api_key: Trello API key. Can also be specified as environment variable\n                TRELLO_API_KEY.\n            token: Trello token. Can also be specified as environment variable\n                TRELLO_TOKEN.\n            include_card_name: Whether to include the name of the card in the document.\n            include_comments: Whether to include the comments on the card in the\n                document.\n            include_checklist: Whether to include the checklist on the card in the\n                document.\n            card_filter: Filter on card status. Valid values are \"closed\", \"open\",\n                \"all\".\n            extra_metadata: List of additional metadata fields to include as document\n                metadata.Valid values are \"due_date\", \"labels\", \"list\", \"closed\".\n        \"\"\"\n        try:\n            from trello import TrelloClient  # type: ignore\n        except ImportError as ex:\n            raise ImportError(\n                \"Could not import trello python package. \"\n                \"Please install it with `pip install py-trello`.\"\n            ) from ex\n        api_key = api_key or get_from_env(\"api_key\", \"TRELLO_API_KEY\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/trello.html"}
{"id": "9de608e668e0-2", "text": "token = token or get_from_env(\"token\", \"TRELLO_TOKEN\")\n        client = TrelloClient(api_key=api_key, token=token)\n        return cls(client, board_name, **kwargs)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Loads all cards from the specified Trello board.\n        You can filter the cards, metadata and text included by using the optional\n            parameters.\n         Returns:\n            A list of documents, one for each card in the board.\n        \"\"\"\n        try:\n            from bs4 import BeautifulSoup  # noqa: F401\n        except ImportError as ex:\n            raise ImportError(\n                \"`beautifulsoup4` package not found, please run\"\n                \" `pip install beautifulsoup4`\"\n            ) from ex\n        board = self._get_board()\n        # Create a dictionary with the list IDs as keys and the list names as values\n        list_dict = {list_item.id: list_item.name for list_item in board.list_lists()}\n        # Get Cards on the board\n        cards = board.get_cards(card_filter=self.card_filter)\n        return [self._card_to_doc(card, list_dict) for card in cards]\n    def _get_board(self) -> Board:\n        # Find the first board with a matching name\n        board = next(\n            (b for b in self.client.list_boards() if b.name == self.board_name), None\n        )\n        if not board:\n            raise ValueError(f\"Board `{self.board_name}` not found.\")\n        return board\n    def _card_to_doc(self, card: Card, list_dict: dict) -> Document:\n        from bs4 import BeautifulSoup  # type: ignore\n        text_content = \"\"\n        if self.include_card_name:\n            text_content = card.name + \"\\n\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/trello.html"}
{"id": "9de608e668e0-3", "text": "if self.include_card_name:\n            text_content = card.name + \"\\n\"\n        if card.description.strip():\n            text_content += BeautifulSoup(card.description, \"lxml\").get_text()\n        if self.include_checklist:\n            # Get all the checklist items on the card\n            for checklist in card.checklists:\n                if checklist.items:\n                    items = [\n                        f\"{item['name']}:{item['state']}\" for item in checklist.items\n                    ]\n                    text_content += f\"\\n{checklist.name}\\n\" + \"\\n\".join(items)\n        if self.include_comments:\n            # Get all the comments on the card\n            comments = [\n                BeautifulSoup(comment[\"data\"][\"text\"], \"lxml\").get_text()\n                for comment in card.comments\n            ]\n            text_content += \"Comments:\" + \"\\n\".join(comments)\n        # Default metadata fields\n        metadata = {\n            \"title\": card.name,\n            \"id\": card.id,\n            \"url\": card.url,\n        }\n        # Extra metadata fields. Card object is not subscriptable.\n        if \"labels\" in self.extra_metadata:\n            metadata[\"labels\"] = [label.name for label in card.labels]\n        if \"list\" in self.extra_metadata:\n            if card.list_id in list_dict:\n                metadata[\"list\"] = list_dict[card.list_id]\n        if \"closed\" in self.extra_metadata:\n            metadata[\"closed\"] = card.closed\n        if \"due_date\" in self.extra_metadata:\n            metadata[\"due_date\"] = card.due_date\n        return Document(page_content=text_content, metadata=metadata)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/trello.html"}
{"id": "59203466be51-0", "text": "Source code for langchain.document_loaders.url_selenium\n\"\"\"Loader that uses Selenium to load a page, then uses unstructured to load the html.\n\"\"\"\nimport logging\nfrom typing import TYPE_CHECKING, List, Literal, Optional, Union\nif TYPE_CHECKING:\n    from selenium.webdriver import Chrome, Firefox\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n[docs]class SeleniumURLLoader(BaseLoader):\n    \"\"\"Load `HTML` pages with `Selenium` and parse with `Unstructured`.\n    This is useful for loading pages that require javascript to render.\n    Attributes:\n        urls (List[str]): List of URLs to load.\n        continue_on_failure (bool): If True, continue loading other URLs on failure.\n        browser (str): The browser to use, either 'chrome' or 'firefox'.\n        binary_location (Optional[str]): The location of the browser binary.\n        executable_path (Optional[str]): The path to the browser executable.\n        headless (bool): If True, the browser will run in headless mode.\n        arguments [List[str]]: List of arguments to pass to the browser.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        urls: List[str],\n        continue_on_failure: bool = True,\n        browser: Literal[\"chrome\", \"firefox\"] = \"chrome\",\n        binary_location: Optional[str] = None,\n        executable_path: Optional[str] = None,\n        headless: bool = True,\n        arguments: List[str] = [],\n    ):\n        \"\"\"Load a list of URLs using Selenium and unstructured.\"\"\"\n        try:\n            import selenium  # noqa:F401\n        except ImportError:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html"}
{"id": "59203466be51-1", "text": "import selenium  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"selenium package not found, please install it with \"\n                \"`pip install selenium`\"\n            )\n        try:\n            import unstructured  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"unstructured package not found, please install it with \"\n                \"`pip install unstructured`\"\n            )\n        self.urls = urls\n        self.continue_on_failure = continue_on_failure\n        self.browser = browser\n        self.binary_location = binary_location\n        self.executable_path = executable_path\n        self.headless = headless\n        self.arguments = arguments\n    def _get_driver(self) -> Union[\"Chrome\", \"Firefox\"]:\n        \"\"\"Create and return a WebDriver instance based on the specified browser.\n        Raises:\n            ValueError: If an invalid browser is specified.\n        Returns:\n            Union[Chrome, Firefox]: A WebDriver instance for the specified browser.\n        \"\"\"\n        if self.browser.lower() == \"chrome\":\n            from selenium.webdriver import Chrome\n            from selenium.webdriver.chrome.options import Options as ChromeOptions\n            from selenium.webdriver.chrome.service import Service\n            chrome_options = ChromeOptions()\n            for arg in self.arguments:\n                chrome_options.add_argument(arg)\n            if self.headless:\n                chrome_options.add_argument(\"--headless\")\n                chrome_options.add_argument(\"--no-sandbox\")\n            if self.binary_location is not None:\n                chrome_options.binary_location = self.binary_location\n            if self.executable_path is None:\n                return Chrome(options=chrome_options)\n            return Chrome(\n                options=chrome_options,\n                service=Service(executable_path=self.executable_path),\n            )\n        elif self.browser.lower() == \"firefox\":\n            from selenium.webdriver import Firefox", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html"}
{"id": "59203466be51-2", "text": "elif self.browser.lower() == \"firefox\":\n            from selenium.webdriver import Firefox\n            from selenium.webdriver.firefox.options import Options as FirefoxOptions\n            from selenium.webdriver.firefox.service import Service\n            firefox_options = FirefoxOptions()\n            for arg in self.arguments:\n                firefox_options.add_argument(arg)\n            if self.headless:\n                firefox_options.add_argument(\"--headless\")\n            if self.binary_location is not None:\n                firefox_options.binary_location = self.binary_location\n            if self.executable_path is None:\n                return Firefox(options=firefox_options)\n            return Firefox(\n                options=firefox_options,\n                service=Service(executable_path=self.executable_path),\n            )\n        else:\n            raise ValueError(\"Invalid browser specified. Use 'chrome' or 'firefox'.\")\n    def _build_metadata(self, url: str, driver: Union[\"Chrome\", \"Firefox\"]) -> dict:\n        from selenium.common.exceptions import NoSuchElementException\n        from selenium.webdriver.common.by import By\n        \"\"\"Build metadata based on the contents of the webpage\"\"\"\n        metadata = {\n            \"source\": url,\n            \"title\": \"No title found.\",\n            \"description\": \"No description found.\",\n            \"language\": \"No language found.\",\n        }\n        if title := driver.title:\n            metadata[\"title\"] = title\n        try:\n            if description := driver.find_element(\n                By.XPATH, '//meta[@name=\"description\"]'\n            ):\n                metadata[\"description\"] = (\n                    description.get_attribute(\"content\") or \"No description found.\"\n                )\n        except NoSuchElementException:\n            pass\n        try:\n            if html_tag := driver.find_element(By.TAG_NAME, \"html\"):\n                metadata[\"language\"] = (\n                    html_tag.get_attribute(\"lang\") or \"No language found.\"\n                )\n        except NoSuchElementException:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html"}
{"id": "59203466be51-3", "text": ")\n        except NoSuchElementException:\n            pass\n        return metadata\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load the specified URLs using Selenium and create Document instances.\n        Returns:\n            List[Document]: A list of Document instances with loaded content.\n        \"\"\"\n        from unstructured.partition.html import partition_html\n        docs: List[Document] = list()\n        driver = self._get_driver()\n        for url in self.urls:\n            try:\n                driver.get(url)\n                page_content = driver.page_source\n                elements = partition_html(text=page_content)\n                text = \"\\n\\n\".join([str(el) for el in elements])\n                metadata = self._build_metadata(url, driver)\n                docs.append(Document(page_content=text, metadata=metadata))\n            except Exception as e:\n                if self.continue_on_failure:\n                    logger.error(f\"Error fetching or processing {url}, exception: {e}\")\n                else:\n                    raise e\n        driver.quit()\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html"}
{"id": "b05ad14b7935-0", "text": "Source code for langchain.document_loaders.wikipedia\nfrom typing import List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utilities.wikipedia import WikipediaAPIWrapper\n[docs]class WikipediaLoader(BaseLoader):\n    \"\"\"Load from `Wikipedia`.\n    The hard limit on the number of downloaded Documents is 300 for now.\n    Each wiki page represents one Document.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        query: str,\n        lang: str = \"en\",\n        load_max_docs: Optional[int] = 100,\n        load_all_available_meta: Optional[bool] = False,\n        doc_content_chars_max: Optional[int] = 4000,\n    ):\n        \"\"\"\n        Initializes a new instance of the WikipediaLoader class.\n        Args:\n            query (str): The query string to search on Wikipedia.\n            lang (str, optional): The language code for the Wikipedia language edition.\n                Defaults to \"en\".\n            load_max_docs (int, optional): The maximum number of documents to load.\n                Defaults to 100.\n            load_all_available_meta (bool, optional): Indicates whether to load all\n                available metadata for each document. Defaults to False.\n            doc_content_chars_max (int, optional): The maximum number of characters\n                for the document content. Defaults to 4000.\n        \"\"\"\n        self.query = query\n        self.lang = lang\n        self.load_max_docs = load_max_docs\n        self.load_all_available_meta = load_all_available_meta\n        self.doc_content_chars_max = doc_content_chars_max\n[docs]    def load(self) -> List[Document]:\n        \"\"\"\n        Loads the query result from Wikipedia into a list of Documents.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/wikipedia.html"}
{"id": "b05ad14b7935-1", "text": "Loads the query result from Wikipedia into a list of Documents.\n        Returns:\n            List[Document]: A list of Document objects representing the loaded\n                Wikipedia pages.\n        \"\"\"\n        client = WikipediaAPIWrapper(\n            lang=self.lang,\n            top_k_results=self.load_max_docs,\n            load_all_available_meta=self.load_all_available_meta,\n            doc_content_chars_max=self.doc_content_chars_max,\n        )\n        docs = client.load(self.query)\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/wikipedia.html"}
{"id": "c0d31dcc599d-0", "text": "Source code for langchain.document_loaders.tensorflow_datasets\nfrom typing import Callable, Dict, Iterator, List, Optional\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.schema import Document\nfrom langchain.utilities.tensorflow_datasets import TensorflowDatasets\n[docs]class TensorflowDatasetLoader(BaseLoader):\n    \"\"\"Load from `TensorFlow Dataset`.\n    Attributes:\n        dataset_name: the name of the dataset to load\n        split_name: the name of the split to load.\n        load_max_docs: a limit to the number of loaded documents. Defaults to 100.\n        sample_to_document_function: a function that converts a dataset sample\n          into a Document\n    Example:\n        .. code-block:: python\n            from langchain.document_loaders import TensorflowDatasetLoader\n            def mlqaen_example_to_document(example: dict) -> Document:\n                return Document(\n                    page_content=decode_to_str(example[\"context\"]),\n                    metadata={\n                        \"id\": decode_to_str(example[\"id\"]),\n                        \"title\": decode_to_str(example[\"title\"]),\n                        \"question\": decode_to_str(example[\"question\"]),\n                        \"answer\": decode_to_str(example[\"answers\"][\"text\"][0]),\n                    },\n                )\n            tsds_client = TensorflowDatasetLoader(\n                    dataset_name=\"mlqa/en\",\n                    split_name=\"test\",\n                    load_max_docs=100,\n                    sample_to_document_function=mlqaen_example_to_document,\n                )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        dataset_name: str,\n        split_name: str,\n        load_max_docs: Optional[int] = 100,\n        sample_to_document_function: Optional[Callable[[Dict], Document]] = None,\n    ):\n        \"\"\"Initialize the TensorflowDatasetLoader.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tensorflow_datasets.html"}
{"id": "c0d31dcc599d-1", "text": "):\n        \"\"\"Initialize the TensorflowDatasetLoader.\n        Args:\n            dataset_name: the name of the dataset to load\n            split_name: the name of the split to load.\n            load_max_docs: a limit to the number of loaded documents. Defaults to 100.\n            sample_to_document_function: a function that converts a dataset sample\n                into a Document.\n        \"\"\"\n        self.dataset_name: str = dataset_name\n        self.split_name: str = split_name\n        self.load_max_docs = load_max_docs\n        \"\"\"The maximum number of documents to load.\"\"\"\n        self.sample_to_document_function: Optional[\n            Callable[[Dict], Document]\n        ] = sample_to_document_function\n        \"\"\"Custom function that transform a dataset sample into a Document.\"\"\"\n        self._tfds_client = TensorflowDatasets(\n            dataset_name=self.dataset_name,\n            split_name=self.split_name,\n            load_max_docs=self.load_max_docs,\n            sample_to_document_function=self.sample_to_document_function,\n        )\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        yield from self._tfds_client.lazy_load()\n[docs]    def load(self) -> List[Document]:\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tensorflow_datasets.html"}
{"id": "a92de892b668-0", "text": "Source code for langchain.document_loaders.tsv\nfrom typing import Any, List\nfrom langchain.document_loaders.unstructured import (\n    UnstructuredFileLoader,\n    validate_unstructured_version,\n)\n[docs]class UnstructuredTSVLoader(UnstructuredFileLoader):\n    \"\"\"Load `TSV` files using `Unstructured`.\n    Like other\n    Unstructured loaders, UnstructuredTSVLoader can be used in both\n    \"single\" and \"elements\" mode. If you use the loader in \"elements\"\n    mode, the TSV file will be a single Unstructured Table element.\n    If you use the loader in \"elements\" mode, an HTML representation\n    of the table will be available in the \"text_as_html\" key in the\n    document metadata.\n    Examples\n    --------\n    from langchain.document_loaders.tsv import UnstructuredTSVLoader\n    loader = UnstructuredTSVLoader(\"stanley-cups.tsv\", mode=\"elements\")\n    docs = loader.load()\n    \"\"\"\n[docs]    def __init__(\n        self, file_path: str, mode: str = \"single\", **unstructured_kwargs: Any\n    ):\n        validate_unstructured_version(min_unstructured_version=\"0.7.6\")\n        super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)\n    def _get_elements(self) -> List:\n        from unstructured.partition.tsv import partition_tsv\n        return partition_tsv(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tsv.html"}
{"id": "35889f3494c0-0", "text": "Source code for langchain.document_loaders.brave_search\nfrom typing import Iterator, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utilities.brave_search import BraveSearchWrapper\n[docs]class BraveSearchLoader(BaseLoader):\n    \"\"\"Load with `Brave Search` engine.\"\"\"\n[docs]    def __init__(self, query: str, api_key: str, search_kwargs: Optional[dict] = None):\n        \"\"\"Initializes the BraveLoader.\n        Args:\n            query: The query to search for.\n            api_key: The API key to use.\n            search_kwargs: The search kwargs to use.\n        \"\"\"\n        self.query = query\n        self.api_key = api_key\n        self.search_kwargs = search_kwargs or {}\n[docs]    def load(self) -> List[Document]:\n        brave_client = BraveSearchWrapper(\n            api_key=self.api_key,\n            search_kwargs=self.search_kwargs,\n        )\n        return brave_client.download_documents(self.query)\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        for doc in self.load():\n            yield doc", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/brave_search.html"}
{"id": "693af17b410d-0", "text": "Source code for langchain.document_loaders.rst\n\"\"\"Loads RST files.\"\"\"\nfrom typing import Any, List\nfrom langchain.document_loaders.unstructured import (\n    UnstructuredFileLoader,\n    validate_unstructured_version,\n)\n[docs]class UnstructuredRSTLoader(UnstructuredFileLoader):\n    \"\"\"Load `RST` files using `Unstructured`.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredRSTLoader\n    loader = UnstructuredRSTLoader(\n        \"example.rst\", mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition-rst\n    \"\"\"\n[docs]    def __init__(\n        self, file_path: str, mode: str = \"single\", **unstructured_kwargs: Any\n    ):\n        \"\"\"\n        Initialize with a file path.\n        Args:\n            file_path: The path to the file to load.\n            mode: The mode to use for partitioning. See unstructured for details.\n                Defaults to \"single\".\n            **unstructured_kwargs: Additional keyword arguments to pass\n                to unstructured.\n        \"\"\"\n        validate_unstructured_version(min_unstructured_version=\"0.7.5\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rst.html"}
{"id": "693af17b410d-1", "text": "\"\"\"\n        validate_unstructured_version(min_unstructured_version=\"0.7.5\")\n        super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)\n    def _get_elements(self) -> List:\n        from unstructured.partition.rst import partition_rst\n        return partition_rst(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rst.html"}
{"id": "75be2ccc1ec9-0", "text": "Source code for langchain.document_loaders.rss\nimport logging\nfrom typing import Any, Iterator, List, Optional, Sequence\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.news import NewsURLLoader\nlogger = logging.getLogger(__name__)\n[docs]class RSSFeedLoader(BaseLoader):\n    \"\"\"Load news articles from `RSS` feeds using `Unstructured`.\n    Args:\n        urls: URLs for RSS feeds to load. Each articles in the feed is loaded into its own document.\n        opml: OPML file to load feed urls from. Only one of urls or opml should be provided.  The value\n        can be a URL string, or OPML markup contents as byte or string.\n        continue_on_failure: If True, continue loading documents even if\n            loading fails for a particular URL.\n        show_progress_bar: If True, use tqdm to show a loading progress bar. Requires\n            tqdm to be installed, ``pip install tqdm``.\n        **newsloader_kwargs: Any additional named arguments to pass to\n            NewsURLLoader.\n    Example:\n        .. code-block:: python\n            from langchain.document_loaders import RSSFeedLoader\n            loader = RSSFeedLoader(\n                urls=[\"<url-1>\", \"<url-2>\"],\n            )\n            docs = loader.load()\n    The loader uses feedparser to parse RSS feeds.  The feedparser library is not installed by default so you should\n    install it if using this loader:\n    https://pythonhosted.org/feedparser/\n    If you use OPML, you should also install listparser:\n    https://pythonhosted.org/listparser/\n    Finally, newspaper is used to process each article:\n    https://newspaper.readthedocs.io/en/latest/", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rss.html"}
{"id": "75be2ccc1ec9-1", "text": "https://newspaper.readthedocs.io/en/latest/\n    \"\"\"  # noqa: E501\n[docs]    def __init__(\n        self,\n        urls: Optional[Sequence[str]] = None,\n        opml: Optional[str] = None,\n        continue_on_failure: bool = True,\n        show_progress_bar: bool = False,\n        **newsloader_kwargs: Any,\n    ) -> None:\n        \"\"\"Initialize with urls or OPML.\"\"\"\n        if (urls is None) == (\n            opml is None\n        ):  # This is True if both are None or neither is None\n            raise ValueError(\n                \"Provide either the urls or the opml argument, but not both.\"\n            )\n        self.urls = urls\n        self.opml = opml\n        self.continue_on_failure = continue_on_failure\n        self.show_progress_bar = show_progress_bar\n        self.newsloader_kwargs = newsloader_kwargs\n[docs]    def load(self) -> List[Document]:\n        iter = self.lazy_load()\n        if self.show_progress_bar:\n            try:\n                from tqdm import tqdm\n            except ImportError as e:\n                raise ImportError(\n                    \"Package tqdm must be installed if show_progress_bar=True. \"\n                    \"Please install with 'pip install tqdm' or set \"\n                    \"show_progress_bar=False.\"\n                ) from e\n            iter = tqdm(iter)\n        return list(iter)\n    @property\n    def _get_urls(self) -> Sequence[str]:\n        if self.urls:\n            return self.urls\n        try:\n            import listparser\n        except ImportError as e:\n            raise ImportError(\n                \"Package listparser must be installed if the opml arg is used. \"\n                \"Please install with 'pip install listparser' or use the \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rss.html"}
{"id": "75be2ccc1ec9-2", "text": "\"Please install with 'pip install listparser' or use the \"\n                \"urls arg instead.\"\n            ) from e\n        rss = listparser.parse(self.opml)\n        return [feed.url for feed in rss.feeds]\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        try:\n            import feedparser  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"feedparser package not found, please install it with \"\n                \"`pip install feedparser`\"\n            )\n        for url in self._get_urls:\n            try:\n                feed = feedparser.parse(url)\n                if getattr(feed, \"bozo\", False):\n                    raise ValueError(\n                        f\"Error fetching {url}, exception: {feed.bozo_exception}\"\n                    )\n            except Exception as e:\n                if self.continue_on_failure:\n                    logger.error(f\"Error fetching {url}, exception: {e}\")\n                    continue\n                else:\n                    raise e\n            try:\n                for entry in feed.entries:\n                    loader = NewsURLLoader(\n                        urls=[entry.link],\n                        **self.newsloader_kwargs,\n                    )\n                    article = loader.load()[0]\n                    article.metadata[\"feed\"] = url\n                    yield article\n            except Exception as e:\n                if self.continue_on_failure:\n                    logger.error(f\"Error processing entry {entry.link}, exception: {e}\")\n                    continue\n                else:\n                    raise e", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rss.html"}
{"id": "a5ccd67d865f-0", "text": "Source code for langchain.document_loaders.epub\nfrom typing import List\nfrom langchain.document_loaders.unstructured import (\n    UnstructuredFileLoader,\n    satisfies_min_unstructured_version,\n)\n[docs]class UnstructuredEPubLoader(UnstructuredFileLoader):\n    \"\"\"Load `EPub` files using `Unstructured`.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredEPubLoader\n    loader = UnstructuredEPubLoader(\n        \"example.epub\", mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition-epub\n    \"\"\"\n    def _get_elements(self) -> List:\n        min_unstructured_version = \"0.5.4\"\n        if not satisfies_min_unstructured_version(min_unstructured_version):\n            raise ValueError(\n                \"Partitioning epub files is only supported in \"\n                f\"unstructured>={min_unstructured_version}.\"\n            )\n        from unstructured.partition.epub import partition_epub\n        return partition_epub(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/epub.html"}
{"id": "eb539fa867d9-0", "text": "Source code for langchain.document_loaders.mastodon\nfrom __future__ import annotations\nimport os\nfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nif TYPE_CHECKING:\n    import mastodon\ndef _dependable_mastodon_import() -> mastodon:\n    try:\n        import mastodon\n    except ImportError:\n        raise ImportError(\n            \"Mastodon.py package not found, \"\n            \"please install it with `pip install Mastodon.py`\"\n        )\n    return mastodon\n[docs]class MastodonTootsLoader(BaseLoader):\n    \"\"\"Load the `Mastodon` 'toots'.\"\"\"\n[docs]    def __init__(\n        self,\n        mastodon_accounts: Sequence[str],\n        number_toots: Optional[int] = 100,\n        exclude_replies: bool = False,\n        access_token: Optional[str] = None,\n        api_base_url: str = \"https://mastodon.social\",\n    ):\n        \"\"\"Instantiate Mastodon toots loader.\n        Args:\n            mastodon_accounts: The list of Mastodon accounts to query.\n            number_toots: How many toots to pull for each account. Defaults to 100.\n            exclude_replies: Whether to exclude reply toots from the load.\n                Defaults to False.\n            access_token: An access token if toots are loaded as a Mastodon app. Can\n                also be specified via the environment variables \"MASTODON_ACCESS_TOKEN\".\n            api_base_url: A Mastodon API base URL to talk to, if not using the default.\n                Defaults to \"https://mastodon.social\".\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html"}
{"id": "eb539fa867d9-1", "text": "Defaults to \"https://mastodon.social\".\n        \"\"\"\n        mastodon = _dependable_mastodon_import()\n        access_token = access_token or os.environ.get(\"MASTODON_ACCESS_TOKEN\")\n        self.api = mastodon.Mastodon(\n            access_token=access_token, api_base_url=api_base_url\n        )\n        self.mastodon_accounts = mastodon_accounts\n        self.number_toots = number_toots\n        self.exclude_replies = exclude_replies\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load toots into documents.\"\"\"\n        results: List[Document] = []\n        for account in self.mastodon_accounts:\n            user = self.api.account_lookup(account)\n            toots = self.api.account_statuses(\n                user.id,\n                only_media=False,\n                pinned=False,\n                exclude_replies=self.exclude_replies,\n                exclude_reblogs=True,\n                limit=self.number_toots,\n            )\n            docs = self._format_toots(toots, user)\n            results.extend(docs)\n        return results\n    def _format_toots(\n        self, toots: List[Dict[str, Any]], user_info: dict\n    ) -> Iterable[Document]:\n        \"\"\"Format toots into documents.\n        Adding user info, and selected toot fields into the metadata.\n        \"\"\"\n        for toot in toots:\n            metadata = {\n                \"created_at\": toot[\"created_at\"],\n                \"user_info\": user_info,\n                \"is_reply\": toot[\"in_reply_to_id\"] is not None,\n            }\n            yield Document(\n                page_content=toot[\"content\"],\n                metadata=metadata,\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html"}
{"id": "73ed6aa0f53a-0", "text": "Source code for langchain.document_loaders.gcs_directory\nfrom typing import Callable, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.gcs_file import GCSFileLoader\nfrom langchain.utilities.vertexai import get_client_info\n[docs]class GCSDirectoryLoader(BaseLoader):\n    \"\"\"Load from GCS directory.\"\"\"\n[docs]    def __init__(\n        self,\n        project_name: str,\n        bucket: str,\n        prefix: str = \"\",\n        loader_func: Optional[Callable[[str], BaseLoader]] = None,\n    ):\n        \"\"\"Initialize with bucket and key name.\n        Args:\n            project_name: The ID of the project for the GCS bucket.\n            bucket: The name of the GCS bucket.\n            prefix: The prefix of the GCS bucket.\n            loader_func: A loader function that instantiates a loader based on a\n                file_path argument. If nothing is provided, the  GCSFileLoader\n                would use its default loader.\n        \"\"\"\n        self.project_name = project_name\n        self.bucket = bucket\n        self.prefix = prefix\n        self._loader_func = loader_func\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        try:\n            from google.cloud import storage\n        except ImportError:\n            raise ImportError(\n                \"Could not import google-cloud-storage python package. \"\n                \"Please install it with `pip install google-cloud-storage`.\"\n            )\n        client = storage.Client(\n            project=self.project_name,\n            client_info=get_client_info(module=\"google-cloud-storage\"),\n        )\n        docs = []\n        for blob in client.list_blobs(self.bucket, prefix=self.prefix):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_directory.html"}
{"id": "73ed6aa0f53a-1", "text": "for blob in client.list_blobs(self.bucket, prefix=self.prefix):\n            # we shall just skip directories since GCSFileLoader creates\n            # intermediate directories on the fly\n            if blob.name.endswith(\"/\"):\n                continue\n            loader = GCSFileLoader(\n                self.project_name, self.bucket, blob.name, loader_func=self._loader_func\n            )\n            docs.extend(loader.load())\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_directory.html"}
{"id": "351e927d8727-0", "text": "Source code for langchain.document_loaders.web_base\n\"\"\"Web base loader class.\"\"\"\nimport asyncio\nimport logging\nimport warnings\nfrom typing import Any, Dict, Iterator, List, Optional, Sequence, Union\nimport aiohttp\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\ndefault_header_template = {\n    \"User-Agent\": \"\",\n    \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*\"\n    \";q=0.8\",\n    \"Accept-Language\": \"en-US,en;q=0.5\",\n    \"Referer\": \"https://www.google.com/\",\n    \"DNT\": \"1\",\n    \"Connection\": \"keep-alive\",\n    \"Upgrade-Insecure-Requests\": \"1\",\n}\ndef _build_metadata(soup: Any, url: str) -> dict:\n    \"\"\"Build metadata from BeautifulSoup output.\"\"\"\n    metadata = {\"source\": url}\n    if title := soup.find(\"title\"):\n        metadata[\"title\"] = title.get_text()\n    if description := soup.find(\"meta\", attrs={\"name\": \"description\"}):\n        metadata[\"description\"] = description.get(\"content\", \"No description found.\")\n    if html := soup.find(\"html\"):\n        metadata[\"language\"] = html.get(\"lang\", \"No language found.\")\n    return metadata\n[docs]class WebBaseLoader(BaseLoader):\n    \"\"\"Load HTML pages using `urllib` and parse them with `BeautifulSoup'.\"\"\"\n[docs]    def __init__(\n        self,\n        web_path: Union[str, Sequence[str]] = \"\",\n        header_template: Optional[dict] = None,\n        verify_ssl: bool = True,\n        proxies: Optional[dict] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html"}
{"id": "351e927d8727-1", "text": "verify_ssl: bool = True,\n        proxies: Optional[dict] = None,\n        continue_on_failure: bool = False,\n        autoset_encoding: bool = True,\n        encoding: Optional[str] = None,\n        web_paths: Sequence[str] = (),\n        requests_per_second: int = 2,\n        default_parser: str = \"html.parser\",\n        requests_kwargs: Optional[Dict[str, Any]] = None,\n        raise_for_status: bool = False,\n        bs_get_text_kwargs: Optional[Dict[str, Any]] = None,\n        bs_kwargs: Optional[Dict[str, Any]] = None,\n        session: Any = None,\n    ) -> None:\n        \"\"\"Initialize loader.\n        Args:\n            web_paths: Web paths to load from.\n            requests_per_second: Max number of concurrent requests to make.\n            default_parser: Default parser to use for BeautifulSoup.\n            requests_kwargs: kwargs for requests\n            raise_for_status: Raise an exception if http status code denotes an error.\n            bs_get_text_kwargs: kwargs for beatifulsoup4 get_text\n            bs_kwargs: kwargs for beatifulsoup4 web page parsing\n        \"\"\"\n        # web_path kept for backwards-compatibility.\n        if web_path and web_paths:\n            raise ValueError(\n                \"Received web_path and web_paths. Only one can be specified. \"\n                \"web_path is deprecated, web_paths should be used.\"\n            )\n        if web_paths:\n            self.web_paths = list(web_paths)\n        elif isinstance(web_path, str):\n            self.web_paths = [web_path]\n        elif isinstance(web_path, Sequence):\n            self.web_paths = list(web_path)\n        else:\n            raise TypeError(\n                f\"web_path must be str or Sequence[str] got ({type(web_path)}) or\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html"}
{"id": "351e927d8727-2", "text": "f\" web_paths must be Sequence[str] got ({type(web_paths)})\"\n            )\n        self.requests_per_second = requests_per_second\n        self.default_parser = default_parser\n        self.requests_kwargs = requests_kwargs or {}\n        self.raise_for_status = raise_for_status\n        self.bs_get_text_kwargs = bs_get_text_kwargs or {}\n        self.bs_kwargs = bs_kwargs or {}\n        if session:\n            self.session = session\n        else:\n            session = requests.Session()\n            header_template = header_template or default_header_template.copy()\n            if not header_template.get(\"User-Agent\"):\n                try:\n                    from fake_useragent import UserAgent\n                    header_template[\"User-Agent\"] = UserAgent().random\n                except ImportError:\n                    logger.info(\n                        \"fake_useragent not found, using default user agent.\"\n                        \"To get a realistic header for requests, \"\n                        \"`pip install fake_useragent`.\"\n                    )\n            session.headers = dict(header_template)\n            session.verify = verify_ssl\n            if proxies:\n                session.proxies.update(proxies)\n            self.session = session\n        self.continue_on_failure = continue_on_failure\n        self.autoset_encoding = autoset_encoding\n        self.encoding = encoding\n    @property\n    def web_path(self) -> str:\n        if len(self.web_paths) > 1:\n            raise ValueError(\"Multiple webpaths found.\")\n        return self.web_paths[0]\n    async def _fetch(\n        self, url: str, retries: int = 3, cooldown: int = 2, backoff: float = 1.5\n    ) -> str:\n        async with aiohttp.ClientSession() as session:\n            for i in range(retries):\n                try:\n                    async with session.get(\n                        url,\n                        headers=self.session.headers,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html"}
{"id": "351e927d8727-3", "text": "async with session.get(\n                        url,\n                        headers=self.session.headers,\n                        ssl=None if self.session.verify else False,\n                    ) as response:\n                        return await response.text()\n                except aiohttp.ClientConnectionError as e:\n                    if i == retries - 1:\n                        raise\n                    else:\n                        logger.warning(\n                            f\"Error fetching {url} with attempt \"\n                            f\"{i + 1}/{retries}: {e}. Retrying...\"\n                        )\n                        await asyncio.sleep(cooldown * backoff**i)\n        raise ValueError(\"retry count exceeded\")\n    async def _fetch_with_rate_limit(\n        self, url: str, semaphore: asyncio.Semaphore\n    ) -> str:\n        async with semaphore:\n            try:\n                return await self._fetch(url)\n            except Exception as e:\n                if self.continue_on_failure:\n                    logger.warning(\n                        f\"Error fetching {url}, skipping due to\"\n                        f\" continue_on_failure=True\"\n                    )\n                    return \"\"\n                logger.exception(\n                    f\"Error fetching {url} and aborting, use continue_on_failure=True \"\n                    \"to continue loading urls after encountering an error.\"\n                )\n                raise e\n[docs]    async def fetch_all(self, urls: List[str]) -> Any:\n        \"\"\"Fetch all urls concurrently with rate limiting.\"\"\"\n        semaphore = asyncio.Semaphore(self.requests_per_second)\n        tasks = []\n        for url in urls:\n            task = asyncio.ensure_future(self._fetch_with_rate_limit(url, semaphore))\n            tasks.append(task)\n        try:\n            from tqdm.asyncio import tqdm_asyncio\n            return await tqdm_asyncio.gather(\n                *tasks, desc=\"Fetching pages\", ascii=True, mininterval=1\n            )\n        except ImportError:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html"}
{"id": "351e927d8727-4", "text": ")\n        except ImportError:\n            warnings.warn(\"For better logging of progress, `pip install tqdm`\")\n            return await asyncio.gather(*tasks)\n    @staticmethod\n    def _check_parser(parser: str) -> None:\n        \"\"\"Check that parser is valid for bs4.\"\"\"\n        valid_parsers = [\"html.parser\", \"lxml\", \"xml\", \"lxml-xml\", \"html5lib\"]\n        if parser not in valid_parsers:\n            raise ValueError(\n                \"`parser` must be one of \" + \", \".join(valid_parsers) + \".\"\n            )\n[docs]    def scrape_all(self, urls: List[str], parser: Union[str, None] = None) -> List[Any]:\n        \"\"\"Fetch all urls, then return soups for all results.\"\"\"\n        from bs4 import BeautifulSoup\n        results = asyncio.run(self.fetch_all(urls))\n        final_results = []\n        for i, result in enumerate(results):\n            url = urls[i]\n            if parser is None:\n                if url.endswith(\".xml\"):\n                    parser = \"xml\"\n                else:\n                    parser = self.default_parser\n                self._check_parser(parser)\n            final_results.append(BeautifulSoup(result, parser, **self.bs_kwargs))\n        return final_results\n    def _scrape(\n        self,\n        url: str,\n        parser: Union[str, None] = None,\n        bs_kwargs: Optional[dict] = None,\n    ) -> Any:\n        from bs4 import BeautifulSoup\n        if parser is None:\n            if url.endswith(\".xml\"):\n                parser = \"xml\"\n            else:\n                parser = self.default_parser\n        self._check_parser(parser)\n        html_doc = self.session.get(url, **self.requests_kwargs)\n        if self.raise_for_status:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html"}
{"id": "351e927d8727-5", "text": "if self.raise_for_status:\n            html_doc.raise_for_status()\n        if self.encoding is not None:\n            html_doc.encoding = self.encoding\n        elif self.autoset_encoding:\n            html_doc.encoding = html_doc.apparent_encoding\n        return BeautifulSoup(html_doc.text, parser, **(bs_kwargs or {}))\n[docs]    def scrape(self, parser: Union[str, None] = None) -> Any:\n        \"\"\"Scrape data from webpage and return it in BeautifulSoup format.\"\"\"\n        if parser is None:\n            parser = self.default_parser\n        return self._scrape(self.web_path, parser=parser, bs_kwargs=self.bs_kwargs)\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazy load text from the url(s) in web_path.\"\"\"\n        for path in self.web_paths:\n            soup = self._scrape(path, bs_kwargs=self.bs_kwargs)\n            text = soup.get_text(**self.bs_get_text_kwargs)\n            metadata = _build_metadata(soup, path)\n            yield Document(page_content=text, metadata=metadata)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load text from the url(s) in web_path.\"\"\"\n        return list(self.lazy_load())\n[docs]    def aload(self) -> List[Document]:\n        \"\"\"Load text from the urls in web_path async into Documents.\"\"\"\n        results = self.scrape_all(self.web_paths)\n        docs = []\n        for path, soup in zip(self.web_paths, results):\n            text = soup.get_text(**self.bs_get_text_kwargs)\n            metadata = _build_metadata(soup, path)\n            docs.append(Document(page_content=text, metadata=metadata))\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html"}
{"id": "c4117390fd0a-0", "text": "Source code for langchain.document_loaders.pubmed\nfrom typing import Iterator, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utilities.pubmed import PubMedAPIWrapper\n[docs]class PubMedLoader(BaseLoader):\n    \"\"\"Load from the `PubMed` biomedical library.\n    Attributes:\n        query: The query to be passed to the PubMed API.\n        load_max_docs: The maximum number of documents to load.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        query: str,\n        load_max_docs: Optional[int] = 3,\n    ):\n        \"\"\"Initialize the PubMedLoader.\n        Args:\n            query: The query to be passed to the PubMed API.\n            load_max_docs: The maximum number of documents to load.\n              Defaults to 3.\n        \"\"\"\n        self.query = query\n        self.load_max_docs = load_max_docs\n        self._client = PubMedAPIWrapper(\n            top_k_results=load_max_docs,\n        )\n[docs]    def load(self) -> List[Document]:\n        return list(self._client.lazy_load_docs(self.query))\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        for doc in self._client.lazy_load_docs(self.query):\n            yield doc", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pubmed.html"}
{"id": "97df6465ca7f-0", "text": "Source code for langchain.document_loaders.slack_directory\nimport json\nimport zipfile\nfrom pathlib import Path\nfrom typing import Dict, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class SlackDirectoryLoader(BaseLoader):\n    \"\"\"Load from a `Slack` directory dump.\"\"\"\n[docs]    def __init__(self, zip_path: str, workspace_url: Optional[str] = None):\n        \"\"\"Initialize the SlackDirectoryLoader.\n        Args:\n            zip_path (str): The path to the Slack directory dump zip file.\n            workspace_url (Optional[str]): The Slack workspace URL.\n              Including the URL will turn\n              sources into links. Defaults to None.\n        \"\"\"\n        self.zip_path = Path(zip_path)\n        self.workspace_url = workspace_url\n        self.channel_id_map = self._get_channel_id_map(self.zip_path)\n    @staticmethod\n    def _get_channel_id_map(zip_path: Path) -> Dict[str, str]:\n        \"\"\"Get a dictionary mapping channel names to their respective IDs.\"\"\"\n        with zipfile.ZipFile(zip_path, \"r\") as zip_file:\n            try:\n                with zip_file.open(\"channels.json\", \"r\") as f:\n                    channels = json.load(f)\n                return {channel[\"name\"]: channel[\"id\"] for channel in channels}\n            except KeyError:\n                return {}\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load and return documents from the Slack directory dump.\"\"\"\n        docs = []\n        with zipfile.ZipFile(self.zip_path, \"r\") as zip_file:\n            for channel_path in zip_file.namelist():\n                channel_name = Path(channel_path).parent.name\n                if not channel_name:\n                    continue\n                if channel_path.endswith(\".json\"):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html"}
{"id": "97df6465ca7f-1", "text": "if not channel_name:\n                    continue\n                if channel_path.endswith(\".json\"):\n                    messages = self._read_json(zip_file, channel_path)\n                    for message in messages:\n                        document = self._convert_message_to_document(\n                            message, channel_name\n                        )\n                        docs.append(document)\n        return docs\n    def _read_json(self, zip_file: zipfile.ZipFile, file_path: str) -> List[dict]:\n        \"\"\"Read JSON data from a zip subfile.\"\"\"\n        with zip_file.open(file_path, \"r\") as f:\n            data = json.load(f)\n        return data\n    def _convert_message_to_document(\n        self, message: dict, channel_name: str\n    ) -> Document:\n        \"\"\"\n        Convert a message to a Document object.\n        Args:\n            message (dict): A message in the form of a dictionary.\n            channel_name (str): The name of the channel the message belongs to.\n        Returns:\n            Document: A Document object representing the message.\n        \"\"\"\n        text = message.get(\"text\", \"\")\n        metadata = self._get_message_metadata(message, channel_name)\n        return Document(\n            page_content=text,\n            metadata=metadata,\n        )\n    def _get_message_metadata(self, message: dict, channel_name: str) -> dict:\n        \"\"\"Create and return metadata for a given message and channel.\"\"\"\n        timestamp = message.get(\"ts\", \"\")\n        user = message.get(\"user\", \"\")\n        source = self._get_message_source(channel_name, user, timestamp)\n        return {\n            \"source\": source,\n            \"channel\": channel_name,\n            \"timestamp\": timestamp,\n            \"user\": user,\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html"}
{"id": "97df6465ca7f-2", "text": "\"timestamp\": timestamp,\n            \"user\": user,\n        }\n    def _get_message_source(self, channel_name: str, user: str, timestamp: str) -> str:\n        \"\"\"\n        Get the message source as a string.\n        Args:\n            channel_name (str): The name of the channel the message belongs to.\n            user (str): The user ID who sent the message.\n            timestamp (str): The timestamp of the message.\n        Returns:\n            str: The message source.\n        \"\"\"\n        if self.workspace_url:\n            channel_id = self.channel_id_map.get(channel_name, \"\")\n            return (\n                f\"{self.workspace_url}/archives/{channel_id}\"\n                + f\"/p{timestamp.replace('.', '')}\"\n            )\n        else:\n            return f\"{channel_name} - {user} - {timestamp}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html"}
{"id": "c9b314f1ba38-0", "text": "Source code for langchain.document_loaders.arcgis_loader\n\"\"\"Document Loader for ArcGIS FeatureLayers.\"\"\"\nfrom __future__ import annotations\nimport json\nimport re\nimport warnings\nfrom datetime import datetime, timezone\nfrom typing import TYPE_CHECKING, Any, Iterator, List, Optional, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nif TYPE_CHECKING:\n    import arcgis\n_NOT_PROVIDED = \"(Not Provided)\"\n[docs]class ArcGISLoader(BaseLoader):\n    \"\"\"Load records from an ArcGIS FeatureLayer.\"\"\"\n[docs]    def __init__(\n        self,\n        layer: Union[str, arcgis.features.FeatureLayer],\n        gis: Optional[arcgis.gis.GIS] = None,\n        where: str = \"1=1\",\n        out_fields: Optional[Union[List[str], str]] = None,\n        return_geometry: bool = False,\n        result_record_count: Optional[int] = None,\n        lyr_desc: Optional[str] = None,\n        **kwargs: Any,\n    ):\n        try:\n            import arcgis\n        except ImportError as e:\n            raise ImportError(\n                \"arcgis is required to use the ArcGIS Loader. \"\n                \"Install it with pip or conda.\"\n            ) from e\n        try:\n            from bs4 import BeautifulSoup  # type: ignore\n            self.BEAUTIFULSOUP = BeautifulSoup\n        except ImportError:\n            warnings.warn(\"BeautifulSoup not found. HTML will not be parsed.\")\n            self.BEAUTIFULSOUP = None\n        self.gis = gis or arcgis.gis.GIS()\n        if isinstance(layer, str):\n            self.url = layer\n            self.layer = arcgis.features.FeatureLayer(layer, gis=gis)\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/arcgis_loader.html"}
{"id": "c9b314f1ba38-1", "text": "else:\n            self.url = layer.url\n            self.layer = layer\n        self.layer_properties = self._get_layer_properties(lyr_desc)\n        self.where = where\n        if isinstance(out_fields, str):\n            self.out_fields = out_fields\n        elif out_fields is None:\n            self.out_fields = \"*\"\n        else:\n            self.out_fields = \",\".join(out_fields)\n        self.return_geometry = return_geometry\n        self.result_record_count = result_record_count\n        self.return_all_records = not isinstance(result_record_count, int)\n        query_params = dict(\n            where=self.where,\n            out_fields=self.out_fields,\n            return_geometry=self.return_geometry,\n            return_all_records=self.return_all_records,\n            result_record_count=self.result_record_count,\n        )\n        query_params.update(kwargs)\n        self.query_params = query_params\n    def _get_layer_properties(self, lyr_desc: Optional[str] = None) -> dict:\n        \"\"\"Get the layer properties from the FeatureLayer.\"\"\"\n        import arcgis\n        layer_number_pattern = re.compile(r\"/\\d+$\")\n        props = self.layer.properties\n        if lyr_desc is None:\n            # retrieve description from the FeatureLayer if not provided\n            try:\n                if self.BEAUTIFULSOUP:\n                    lyr_desc = self.BEAUTIFULSOUP(props[\"description\"]).text\n                else:\n                    lyr_desc = props[\"description\"]\n                lyr_desc = lyr_desc or _NOT_PROVIDED\n            except KeyError:\n                lyr_desc = _NOT_PROVIDED\n        try:\n            item_id = props[\"serviceItemId\"]\n            item = self.gis.content.get(item_id) or arcgis.features.FeatureLayer(\n                re.sub(layer_number_pattern, \"\", self.url),\n            )\n            try:\n                raw_desc = item.description", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/arcgis_loader.html"}
{"id": "c9b314f1ba38-2", "text": ")\n            try:\n                raw_desc = item.description\n            except AttributeError:\n                raw_desc = item.properties.description\n            if self.BEAUTIFULSOUP:\n                item_desc = self.BEAUTIFULSOUP(raw_desc).text\n            else:\n                item_desc = raw_desc\n            item_desc = item_desc or _NOT_PROVIDED\n        except KeyError:\n            item_desc = _NOT_PROVIDED\n        return {\n            \"layer_description\": lyr_desc,\n            \"item_description\": item_desc,\n            \"layer_properties\": props,\n        }\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazy load records from FeatureLayer.\"\"\"\n        query_response = self.layer.query(**self.query_params)\n        features = (feature.as_dict for feature in query_response)\n        for feature in features:\n            attributes = feature[\"attributes\"]\n            page_content = json.dumps(attributes)\n            metadata = {\n                \"accessed\": f\"{datetime.now(timezone.utc).isoformat()}Z\",\n                \"name\": self.layer_properties[\"layer_properties\"][\"name\"],\n                \"url\": self.url,\n                \"layer_description\": self.layer_properties[\"layer_description\"],\n                \"item_description\": self.layer_properties[\"item_description\"],\n                \"layer_properties\": self.layer_properties[\"layer_properties\"],\n            }\n            if self.return_geometry:\n                try:\n                    metadata[\"geometry\"] = feature[\"geometry\"]\n                except KeyError:\n                    warnings.warn(\n                        \"Geometry could not be retrieved from the feature layer.\"\n                    )\n            yield Document(page_content=page_content, metadata=metadata)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load all records from FeatureLayer.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/arcgis_loader.html"}
{"id": "6c516d44cd70-0", "text": "Source code for langchain.document_loaders.chatgpt\nimport datetime\nimport json\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]def concatenate_rows(message: dict, title: str) -> str:\n    \"\"\"\n    Combine message information in a readable format ready to be used.\n    Args:\n        message: Message to be concatenated\n        title: Title of the conversation\n    Returns:\n        Concatenated message\n    \"\"\"\n    if not message:\n        return \"\"\n    sender = message[\"author\"][\"role\"] if message[\"author\"] else \"unknown\"\n    text = message[\"content\"][\"parts\"][0]\n    date = datetime.datetime.fromtimestamp(message[\"create_time\"]).strftime(\n        \"%Y-%m-%d %H:%M:%S\"\n    )\n    return f\"{title} - {sender} on {date}: {text}\\n\\n\"\n[docs]class ChatGPTLoader(BaseLoader):\n    \"\"\"Load conversations from exported `ChatGPT` data.\"\"\"\n[docs]    def __init__(self, log_file: str, num_logs: int = -1):\n        \"\"\"Initialize a class object.\n        Args:\n            log_file: Path to the log file\n            num_logs: Number of logs to load. If 0, load all logs.\n        \"\"\"\n        self.log_file = log_file\n        self.num_logs = num_logs\n[docs]    def load(self) -> List[Document]:\n        with open(self.log_file, encoding=\"utf8\") as f:\n            data = json.load(f)[: self.num_logs] if self.num_logs else json.load(f)\n        documents = []\n        for d in data:\n            title = d[\"title\"]\n            messages = d[\"mapping\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html"}
{"id": "6c516d44cd70-1", "text": "title = d[\"title\"]\n            messages = d[\"mapping\"]\n            text = \"\".join(\n                [\n                    concatenate_rows(messages[key][\"message\"], title)\n                    for idx, key in enumerate(messages)\n                    if not (\n                        idx == 0\n                        and messages[key][\"message\"][\"author\"][\"role\"] == \"system\"\n                    )\n                ]\n            )\n            metadata = {\"source\": str(self.log_file)}\n            documents.append(Document(page_content=text, metadata=metadata))\n        return documents", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html"}
{"id": "528a4591f293-0", "text": "Source code for langchain.document_loaders.concurrent\nfrom __future__ import annotations\nimport concurrent.futures\nfrom pathlib import Path\nfrom typing import Iterator, Literal, Optional, Sequence, Union\nfrom langchain.document_loaders.base import BaseBlobParser\nfrom langchain.document_loaders.blob_loaders import BlobLoader, FileSystemBlobLoader\nfrom langchain.document_loaders.generic import GenericLoader\nfrom langchain.document_loaders.parsers.registry import get_parser\nfrom langchain.schema import Document\n_PathLike = Union[str, Path]\nDEFAULT = Literal[\"default\"]\n[docs]class ConcurrentLoader(GenericLoader):\n    \"\"\"Load and pars Documents concurrently.\"\"\"\n[docs]    def __init__(\n        self, blob_loader: BlobLoader, blob_parser: BaseBlobParser, num_workers: int = 4\n    ) -> None:\n        super().__init__(blob_loader, blob_parser)\n        self.num_workers = num_workers\n[docs]    def lazy_load(\n        self,\n    ) -> Iterator[Document]:\n        \"\"\"Load documents lazily with concurrent parsing.\"\"\"\n        with concurrent.futures.ThreadPoolExecutor(\n            max_workers=self.num_workers\n        ) as executor:\n            futures = {\n                executor.submit(self.blob_parser.lazy_parse, blob)\n                for blob in self.blob_loader.yield_blobs()\n            }\n            for future in concurrent.futures.as_completed(futures):\n                yield from future.result()\n[docs]    @classmethod\n    def from_filesystem(\n        cls,\n        path: _PathLike,\n        *,\n        glob: str = \"**/[!.]*\",\n        exclude: Sequence[str] = (),\n        suffixes: Optional[Sequence[str]] = None,\n        show_progress: bool = False,\n        parser: Union[DEFAULT, BaseBlobParser] = \"default\",\n        num_workers: int = 4,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/concurrent.html"}
{"id": "528a4591f293-1", "text": "num_workers: int = 4,\n    ) -> ConcurrentLoader:\n        \"\"\"\n        Create a concurrent generic document loader using a\n        filesystem blob loader.\n        Args:\n            path: The path to the directory to load documents from.\n            glob: The glob pattern to use to find documents.\n            suffixes: The suffixes to use to filter documents. If None, all files\n                      matching the glob will be loaded.\n            exclude: A list of patterns to exclude from the loader.\n            show_progress: Whether to show a progress bar or not (requires tqdm).\n                           Proxies to the file system loader.\n            parser: A blob parser which knows how to parse blobs into documents\n            num_workers: Max number of concurrent workers to use.\n        \"\"\"\n        blob_loader = FileSystemBlobLoader(\n            path,\n            glob=glob,\n            exclude=exclude,\n            suffixes=suffixes,\n            show_progress=show_progress,\n        )\n        if isinstance(parser, str):\n            blob_parser = get_parser(parser)\n        else:\n            blob_parser = parser\n        return cls(blob_loader, blob_parser, num_workers=num_workers)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/concurrent.html"}
{"id": "9d0288389eaf-0", "text": "Source code for langchain.document_loaders.markdown\nfrom typing import List\nfrom langchain.document_loaders.unstructured import UnstructuredFileLoader\n[docs]class UnstructuredMarkdownLoader(UnstructuredFileLoader):\n    \"\"\"Load `Markdown` files using `Unstructured`.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredMarkdownLoader\n    loader = UnstructuredMarkdownLoader(\n        \"example.md\", mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition-md\n    \"\"\"\n    def _get_elements(self) -> List:\n        from unstructured.__version__ import __version__ as __unstructured_version__\n        from unstructured.partition.md import partition_md\n        # NOTE(MthwRobinson) - enables the loader to work when you're using pre-release\n        # versions of unstructured like 0.4.17-dev1\n        _unstructured_version = __unstructured_version__.split(\"-\")[0]\n        unstructured_version = tuple([int(x) for x in _unstructured_version.split(\".\")])\n        if unstructured_version < (0, 4, 16):\n            raise ValueError(\n                f\"You are on unstructured version {__unstructured_version__}. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/markdown.html"}
{"id": "9d0288389eaf-1", "text": "f\"You are on unstructured version {__unstructured_version__}. \"\n                \"Partitioning markdown files is only supported in unstructured>=0.4.16.\"\n            )\n        return partition_md(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/markdown.html"}
{"id": "116fccac3095-0", "text": "Source code for langchain.document_loaders.blackboard\nimport contextlib\nimport re\nfrom pathlib import Path\nfrom typing import Any, List, Optional, Tuple\nfrom urllib.parse import unquote\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.directory import DirectoryLoader\nfrom langchain.document_loaders.pdf import PyPDFLoader\nfrom langchain.document_loaders.web_base import WebBaseLoader\n[docs]class BlackboardLoader(WebBaseLoader):\n    \"\"\"Load a `Blackboard` course.\n    This loader is not compatible with all Blackboard courses. It is only\n    compatible with courses that use the new Blackboard interface.\n    To use this loader, you must have the BbRouter cookie. You can get this\n    cookie by logging into the course and then copying the value of the\n    BbRouter cookie from the browser's developer tools.\n    Example:\n        .. code-block:: python\n            from langchain.document_loaders import BlackboardLoader\n            loader = BlackboardLoader(\n                blackboard_course_url=\"https://blackboard.example.com/webapps/blackboard/execute/announcement?method=search&context=course_entry&course_id=_123456_1\",\n                bbrouter=\"expires:12345...\",\n            )\n            documents = loader.load()\n    \"\"\"  # noqa: E501\n[docs]    def __init__(\n        self,\n        blackboard_course_url: str,\n        bbrouter: str,\n        load_all_recursively: bool = True,\n        basic_auth: Optional[Tuple[str, str]] = None,\n        cookies: Optional[dict] = None,\n        continue_on_failure: bool = False,\n    ):\n        \"\"\"Initialize with blackboard course url.\n        The BbRouter cookie is required for most blackboard courses.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html"}
{"id": "116fccac3095-1", "text": "The BbRouter cookie is required for most blackboard courses.\n        Args:\n            blackboard_course_url: Blackboard course url.\n            bbrouter: BbRouter cookie.\n            load_all_recursively: If True, load all documents recursively.\n            basic_auth: Basic auth credentials.\n            cookies: Cookies.\n            continue_on_failure: whether to continue loading the sitemap if an error\n                occurs loading a url, emitting a warning instead of raising an\n                exception. Setting this to True makes the loader more robust, but also\n                may result in missing data. Default: False\n        Raises:\n            ValueError: If blackboard course url is invalid.\n        \"\"\"\n        super().__init__(\n            web_paths=(blackboard_course_url), continue_on_failure=continue_on_failure\n        )\n        # Get base url\n        try:\n            self.base_url = blackboard_course_url.split(\"/webapps/blackboard\")[0]\n        except IndexError:\n            raise IndexError(\n                \"Invalid blackboard course url. \"\n                \"Please provide a url that starts with \"\n                \"https://<blackboard_url>/webapps/blackboard\"\n            )\n        if basic_auth is not None:\n            self.session.auth = basic_auth\n        # Combine cookies\n        if cookies is None:\n            cookies = {}\n        cookies.update({\"BbRouter\": bbrouter})\n        self.session.cookies.update(cookies)\n        self.load_all_recursively = load_all_recursively\n        self.check_bs4()\n[docs]    def check_bs4(self) -> None:\n        \"\"\"Check if BeautifulSoup4 is installed.\n        Raises:\n            ImportError: If BeautifulSoup4 is not installed.\n        \"\"\"\n        try:\n            import bs4  # noqa: F401\n        except ImportError:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html"}
{"id": "116fccac3095-2", "text": "except ImportError:\n            raise ImportError(\n                \"BeautifulSoup4 is required for BlackboardLoader. \"\n                \"Please install it with `pip install beautifulsoup4`.\"\n            )\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load data into Document objects.\n        Returns:\n            List of Documents.\n        \"\"\"\n        if self.load_all_recursively:\n            soup_info = self.scrape()\n            self.folder_path = self._get_folder_path(soup_info)\n            relative_paths = self._get_paths(soup_info)\n            documents = []\n            for path in relative_paths:\n                url = self.base_url + path\n                print(f\"Fetching documents from {url}\")\n                soup_info = self._scrape(url)\n                with contextlib.suppress(ValueError):\n                    documents.extend(self._get_documents(soup_info))\n            return documents\n        else:\n            print(f\"Fetching documents from {self.web_path}\")\n            soup_info = self.scrape()\n            self.folder_path = self._get_folder_path(soup_info)\n            return self._get_documents(soup_info)\n    def _get_folder_path(self, soup: Any) -> str:\n        \"\"\"Get the folder path to save the Documents in.\n        Args:\n            soup: BeautifulSoup4 soup object.\n        Returns:\n            Folder path.\n        \"\"\"\n        # Get the course name\n        course_name = soup.find(\"span\", {\"id\": \"crumb_1\"})\n        if course_name is None:\n            raise ValueError(\"No course name found.\")\n        course_name = course_name.text.strip()\n        # Prepare the folder path\n        course_name_clean = (\n            unquote(course_name)\n            .replace(\" \", \"_\")\n            .replace(\"/\", \"_\")\n            .replace(\":\", \"_\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html"}
{"id": "116fccac3095-3", "text": ".replace(\"/\", \"_\")\n            .replace(\":\", \"_\")\n            .replace(\",\", \"_\")\n            .replace(\"?\", \"_\")\n            .replace(\"'\", \"_\")\n            .replace(\"!\", \"_\")\n            .replace('\"', \"_\")\n        )\n        # Get the folder path\n        folder_path = Path(\".\") / course_name_clean\n        return str(folder_path)\n    def _get_documents(self, soup: Any) -> List[Document]:\n        \"\"\"Fetch content from page and return Documents.\n        Args:\n            soup: BeautifulSoup4 soup object.\n        Returns:\n            List of documents.\n        \"\"\"\n        attachments = self._get_attachments(soup)\n        self._download_attachments(attachments)\n        documents = self._load_documents()\n        return documents\n    def _get_attachments(self, soup: Any) -> List[str]:\n        \"\"\"Get all attachments from a page.\n        Args:\n            soup: BeautifulSoup4 soup object.\n        Returns:\n            List of attachments.\n        \"\"\"\n        from bs4 import BeautifulSoup, Tag\n        # Get content list\n        content_list = soup.find(\"ul\", {\"class\": \"contentList\"})\n        if content_list is None:\n            raise ValueError(\"No content list found.\")\n        content_list: BeautifulSoup  # type: ignore\n        # Get all attachments\n        attachments = []\n        for attachment in content_list.find_all(\"ul\", {\"class\": \"attachments\"}):\n            attachment: Tag  # type: ignore\n            for link in attachment.find_all(\"a\"):\n                link: Tag  # type: ignore\n                href = link.get(\"href\")\n                # Only add if href is not None and does not start with #\n                if href is not None and not href.startswith(\"#\"):\n                    attachments.append(href)\n        return attachments", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html"}
{"id": "116fccac3095-4", "text": "attachments.append(href)\n        return attachments\n    def _download_attachments(self, attachments: List[str]) -> None:\n        \"\"\"Download all attachments.\n        Args:\n            attachments: List of attachments.\n        \"\"\"\n        # Make sure the folder exists\n        Path(self.folder_path).mkdir(parents=True, exist_ok=True)\n        # Download all attachments\n        for attachment in attachments:\n            self.download(attachment)\n    def _load_documents(self) -> List[Document]:\n        \"\"\"Load all documents in the folder.\n        Returns:\n            List of documents.\n        \"\"\"\n        # Create the document loader\n        loader = DirectoryLoader(\n            path=self.folder_path,\n            glob=\"*.pdf\",\n            loader_cls=PyPDFLoader,  # type: ignore\n        )\n        # Load the documents\n        documents = loader.load()\n        # Return all documents\n        return documents\n    def _get_paths(self, soup: Any) -> List[str]:\n        \"\"\"Get all relative paths in the navbar.\"\"\"\n        relative_paths = []\n        course_menu = soup.find(\"ul\", {\"class\": \"courseMenu\"})\n        if course_menu is None:\n            raise ValueError(\"No course menu found.\")\n        for link in course_menu.find_all(\"a\"):\n            href = link.get(\"href\")\n            if href is not None and href.startswith(\"/\"):\n                relative_paths.append(href)\n        return relative_paths\n[docs]    def download(self, path: str) -> None:\n        \"\"\"Download a file from an url.\n        Args:\n            path: Path to the file.\n        \"\"\"\n        # Get the file content\n        response = self.session.get(self.base_url + path, allow_redirects=True)\n        # Get the filename\n        filename = self.parse_filename(response.url)\n        # Write the file to disk", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html"}
{"id": "116fccac3095-5", "text": "filename = self.parse_filename(response.url)\n        # Write the file to disk\n        with open(Path(self.folder_path) / filename, \"wb\") as f:\n            f.write(response.content)\n[docs]    def parse_filename(self, url: str) -> str:\n        \"\"\"Parse the filename from an url.\n        Args:\n            url: Url to parse the filename from.\n        Returns:\n            The filename.\n        \"\"\"\n        if (url_path := Path(url)) and url_path.suffix == \".pdf\":\n            return url_path.name\n        else:\n            return self._parse_filename_from_url(url)\n    def _parse_filename_from_url(self, url: str) -> str:\n        \"\"\"Parse the filename from an url.\n        Args:\n            url: Url to parse the filename from.\n        Returns:\n            The filename.\n        Raises:\n            ValueError: If the filename could not be parsed.\n        \"\"\"\n        filename_matches = re.search(r\"filename%2A%3DUTF-8%27%27(.+)\", url)\n        if filename_matches:\n            filename = filename_matches.group(1)\n        else:\n            raise ValueError(f\"Could not parse filename from {url}\")\n        if \".pdf\" not in filename:\n            raise ValueError(f\"Incorrect file type: {filename}\")\n        filename = filename.split(\".pdf\")[0] + \".pdf\"\n        filename = unquote(filename)\n        filename = filename.replace(\"%20\", \" \")\n        return filename\nif __name__ == \"__main__\":\n    loader = BlackboardLoader(\n        \"https://<YOUR BLACKBOARD URL\"\n        \" HERE>/webapps/blackboard/content/listContent.jsp?course_id=_<YOUR COURSE ID\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html"}
{"id": "116fccac3095-6", "text": "\" HERE>_1&content_id=_<YOUR CONTENT ID HERE>_1&mode=reset\",\n        \"<YOUR BBROUTER COOKIE HERE>\",\n        load_all_recursively=True,\n    )\n    documents = loader.load()\n    print(f\"Loaded {len(documents)} pages of PDFs from {loader.web_path}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html"}
{"id": "9b7b4294e690-0", "text": "Source code for langchain.document_loaders.news\n\"\"\"Loader that uses unstructured to load HTML files.\"\"\"\nimport logging\nfrom typing import Any, Iterator, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n[docs]class NewsURLLoader(BaseLoader):\n    \"\"\"Load news articles from URLs using `Unstructured`.\n    Args:\n        urls: URLs to load. Each is loaded into its own document.\n        text_mode: If True, extract text from URL and use that for page content.\n            Otherwise, extract raw HTML.\n        nlp: If True, perform NLP on the extracted contents, like providing a summary\n            and extracting keywords.\n        continue_on_failure: If True, continue loading documents even if\n            loading fails for a particular URL.\n        show_progress_bar: If True, use tqdm to show a loading progress bar. Requires\n            tqdm to be installed, ``pip install tqdm``.\n        **newspaper_kwargs: Any additional named arguments to pass to\n            newspaper.Article().\n    Example:\n        .. code-block:: python\n            from langchain.document_loaders import NewsURLLoader\n            loader = NewsURLLoader(\n                urls=[\"<url-1>\", \"<url-2>\"],\n            )\n            docs = loader.load()\n    Newspaper reference:\n        https://newspaper.readthedocs.io/en/latest/\n    \"\"\"\n[docs]    def __init__(\n        self,\n        urls: List[str],\n        text_mode: bool = True,\n        nlp: bool = False,\n        continue_on_failure: bool = True,\n        show_progress_bar: bool = False,\n        **newspaper_kwargs: Any,\n    ) -> None:\n        \"\"\"Initialize with file path.\"\"\"\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/news.html"}
{"id": "9b7b4294e690-1", "text": ") -> None:\n        \"\"\"Initialize with file path.\"\"\"\n        try:\n            import newspaper  # noqa:F401\n            self.__version = newspaper.__version__\n        except ImportError:\n            raise ImportError(\n                \"newspaper package not found, please install it with \"\n                \"`pip install newspaper3k`\"\n            )\n        self.urls = urls\n        self.text_mode = text_mode\n        self.nlp = nlp\n        self.continue_on_failure = continue_on_failure\n        self.newspaper_kwargs = newspaper_kwargs\n        self.show_progress_bar = show_progress_bar\n[docs]    def load(self) -> List[Document]:\n        iter = self.lazy_load()\n        if self.show_progress_bar:\n            try:\n                from tqdm import tqdm\n            except ImportError as e:\n                raise ImportError(\n                    \"Package tqdm must be installed if show_progress_bar=True. \"\n                    \"Please install with 'pip install tqdm' or set \"\n                    \"show_progress_bar=False.\"\n                ) from e\n            iter = tqdm(iter)\n        return list(iter)\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        try:\n            from newspaper import Article\n        except ImportError as e:\n            raise ImportError(\n                \"Cannot import newspaper, please install with `pip install newspaper3k`\"\n            ) from e\n        for url in self.urls:\n            try:\n                article = Article(url, **self.newspaper_kwargs)\n                article.download()\n                article.parse()\n                if self.nlp:\n                    article.nlp()\n            except Exception as e:\n                if self.continue_on_failure:\n                    logger.error(f\"Error fetching or processing {url}, exception: {e}\")\n                    continue\n                else:\n                    raise e\n            metadata = {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/news.html"}
{"id": "9b7b4294e690-2", "text": "continue\n                else:\n                    raise e\n            metadata = {\n                \"title\": getattr(article, \"title\", \"\"),\n                \"link\": getattr(article, \"url\", getattr(article, \"canonical_link\", \"\")),\n                \"authors\": getattr(article, \"authors\", []),\n                \"language\": getattr(article, \"meta_lang\", \"\"),\n                \"description\": getattr(article, \"meta_description\", \"\"),\n                \"publish_date\": getattr(article, \"publish_date\", \"\"),\n            }\n            if self.text_mode:\n                content = article.text\n            else:\n                content = article.html\n            if self.nlp:\n                metadata[\"keywords\"] = getattr(article, \"keywords\", [])\n                metadata[\"summary\"] = getattr(article, \"summary\", \"\")\n            yield Document(page_content=content, metadata=metadata)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/news.html"}
{"id": "e8ffc58f3b5c-0", "text": "Source code for langchain.document_loaders.gcs_file\nimport os\nimport tempfile\nfrom typing import Callable, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.unstructured import UnstructuredFileLoader\nfrom langchain.utilities.vertexai import get_client_info\n[docs]class GCSFileLoader(BaseLoader):\n    \"\"\"Load from GCS file.\"\"\"\n[docs]    def __init__(\n        self,\n        project_name: str,\n        bucket: str,\n        blob: str,\n        loader_func: Optional[Callable[[str], BaseLoader]] = None,\n    ):\n        \"\"\"Initialize with bucket and key name.\n        Args:\n            project_name: The name of the project to load\n            bucket: The name of the GCS bucket.\n            blob: The name of the GCS blob to load.\n            loader_func: A loader function that instantiates a loader based on a\n                file_path argument. If nothing is provided, the\n                UnstructuredFileLoader is used.\n        Examples:\n            To use an alternative PDF loader:\n            >> from from langchain.document_loaders import PyPDFLoader\n            >> loader = GCSFileLoader(..., loader_func=PyPDFLoader)\n            To use UnstructuredFileLoader with additional arguments:\n            >> loader = GCSFileLoader(...,\n            >>      loader_func=lambda x: UnstructuredFileLoader(x, mode=\"elements\"))\n        \"\"\"\n        self.bucket = bucket\n        self.blob = blob\n        self.project_name = project_name\n        def default_loader_func(file_path: str) -> BaseLoader:\n            return UnstructuredFileLoader(file_path)\n        self._loader_func = loader_func if loader_func else default_loader_func\n[docs]    def load(self) -> List[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_file.html"}
{"id": "e8ffc58f3b5c-1", "text": "[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        try:\n            from google.cloud import storage\n        except ImportError:\n            raise ImportError(\n                \"Could not import google-cloud-storage python package. \"\n                \"Please install it with `pip install google-cloud-storage`.\"\n            )\n        # Initialise a client\n        storage_client = storage.Client(\n            self.project_name, client_info=get_client_info(\"google-cloud-storage\")\n        )\n        # Create a bucket object for our bucket\n        bucket = storage_client.get_bucket(self.bucket)\n        # Create a blob object from the filepath\n        blob = bucket.blob(self.blob)\n        # retrieve custom metadata associated with the blob\n        metadata = bucket.get_blob(self.blob).metadata\n        with tempfile.TemporaryDirectory() as temp_dir:\n            file_path = f\"{temp_dir}/{self.blob}\"\n            os.makedirs(os.path.dirname(file_path), exist_ok=True)\n            # Download the file to a destination\n            blob.download_to_filename(file_path)\n            loader = self._loader_func(file_path)\n            docs = loader.load()\n            for doc in docs:\n                if \"source\" in doc.metadata:\n                    doc.metadata[\"source\"] = f\"gs://{self.bucket}/{self.blob}\"\n                if metadata:\n                    doc.metadata.update(metadata)\n            return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_file.html"}
{"id": "e3415009b790-0", "text": "Source code for langchain.document_loaders.imsdb\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.web_base import WebBaseLoader\n[docs]class IMSDbLoader(WebBaseLoader):\n    \"\"\"Load `IMSDb` webpages.\"\"\"\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load webpage.\"\"\"\n        soup = self.scrape()\n        text = soup.select_one(\"td[class='scrtext']\").text\n        metadata = {\"source\": self.web_path}\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/imsdb.html"}
{"id": "21edf055ea62-0", "text": "Source code for langchain.document_loaders.telegram\nfrom __future__ import annotations\nimport asyncio\nimport json\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Dict, List, Optional, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter\nif TYPE_CHECKING:\n    import pandas as pd\n    from telethon.hints import EntityLike\n[docs]def concatenate_rows(row: dict) -> str:\n    \"\"\"Combine message information in a readable format ready to be used.\"\"\"\n    date = row[\"date\"]\n    sender = row[\"from\"]\n    text = row[\"text\"]\n    return f\"{sender} on {date}: {text}\\n\\n\"\n[docs]class TelegramChatFileLoader(BaseLoader):\n    \"\"\"Load from `Telegram chat` dump.\"\"\"\n[docs]    def __init__(self, path: str):\n        \"\"\"Initialize with a path.\"\"\"\n        self.file_path = path\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        p = Path(self.file_path)\n        with open(p, encoding=\"utf8\") as f:\n            d = json.load(f)\n        text = \"\".join(\n            concatenate_rows(message)\n            for message in d[\"messages\"]\n            if message[\"type\"] == \"message\" and isinstance(message[\"text\"], str)\n        )\n        metadata = {\"source\": str(p)}\n        return [Document(page_content=text, metadata=metadata)]\n[docs]def text_to_docs(text: Union[str, List[str]]) -> List[Document]:\n    \"\"\"Convert a string or list of strings to a list of Documents with metadata.\"\"\"\n    if isinstance(text, str):\n        # Take a single string as one page", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html"}
{"id": "21edf055ea62-1", "text": "if isinstance(text, str):\n        # Take a single string as one page\n        text = [text]\n    page_docs = [Document(page_content=page) for page in text]\n    # Add page numbers as metadata\n    for i, doc in enumerate(page_docs):\n        doc.metadata[\"page\"] = i + 1\n    # Split pages into chunks\n    doc_chunks = []\n    for doc in page_docs:\n        text_splitter = RecursiveCharacterTextSplitter(\n            chunk_size=800,\n            separators=[\"\\n\\n\", \"\\n\", \".\", \"!\", \"?\", \",\", \" \", \"\"],\n            chunk_overlap=20,\n        )\n        chunks = text_splitter.split_text(doc.page_content)\n        for i, chunk in enumerate(chunks):\n            doc = Document(\n                page_content=chunk, metadata={\"page\": doc.metadata[\"page\"], \"chunk\": i}\n            )\n            # Add sources a metadata\n            doc.metadata[\"source\"] = f\"{doc.metadata['page']}-{doc.metadata['chunk']}\"\n            doc_chunks.append(doc)\n    return doc_chunks\n[docs]class TelegramChatApiLoader(BaseLoader):\n    \"\"\"Load `Telegram` chat json directory dump.\"\"\"\n[docs]    def __init__(\n        self,\n        chat_entity: Optional[EntityLike] = None,\n        api_id: Optional[int] = None,\n        api_hash: Optional[str] = None,\n        username: Optional[str] = None,\n        file_path: str = \"telegram_data.json\",\n    ):\n        \"\"\"Initialize with API parameters.\n        Args:\n            chat_entity: The chat entity to fetch data from.\n            api_id: The API ID.\n            api_hash: The API hash.\n            username: The username.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html"}
{"id": "21edf055ea62-2", "text": "api_hash: The API hash.\n            username: The username.\n            file_path: The file path to save the data to. Defaults to\n                 \"telegram_data.json\".\n        \"\"\"\n        self.chat_entity = chat_entity\n        self.api_id = api_id\n        self.api_hash = api_hash\n        self.username = username\n        self.file_path = file_path\n[docs]    async def fetch_data_from_telegram(self) -> None:\n        \"\"\"Fetch data from Telegram API and save it as a JSON file.\"\"\"\n        from telethon.sync import TelegramClient\n        data = []\n        async with TelegramClient(self.username, self.api_id, self.api_hash) as client:\n            async for message in client.iter_messages(self.chat_entity):\n                is_reply = message.reply_to is not None\n                reply_to_id = message.reply_to.reply_to_msg_id if is_reply else None\n                data.append(\n                    {\n                        \"sender_id\": message.sender_id,\n                        \"text\": message.text,\n                        \"date\": message.date.isoformat(),\n                        \"message.id\": message.id,\n                        \"is_reply\": is_reply,\n                        \"reply_to_id\": reply_to_id,\n                    }\n                )\n        with open(self.file_path, \"w\", encoding=\"utf-8\") as f:\n            json.dump(data, f, ensure_ascii=False, indent=4)\n    def _get_message_threads(self, data: pd.DataFrame) -> dict:\n        \"\"\"Create a dictionary of message threads from the given data.\n        Args:\n            data (pd.DataFrame): A DataFrame containing the conversation \\\n                data with columns:\n                - message.sender_id\n                - text\n                - date\n                - message.id\n                - is_reply\n                - reply_to_id\n        Returns:\n            dict: A dictionary where the key is the parent message ID and \\", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html"}
{"id": "21edf055ea62-3", "text": "Returns:\n            dict: A dictionary where the key is the parent message ID and \\\n                the value is a list of message IDs in ascending order.\n        \"\"\"\n        def find_replies(parent_id: int, reply_data: pd.DataFrame) -> List[int]:\n            \"\"\"\n            Recursively find all replies to a given parent message ID.\n            Args:\n                parent_id (int): The parent message ID.\n                reply_data (pd.DataFrame): A DataFrame containing reply messages.\n            Returns:\n                list: A list of message IDs that are replies to the parent message ID.\n            \"\"\"\n            # Find direct replies to the parent message ID\n            direct_replies = reply_data[reply_data[\"reply_to_id\"] == parent_id][\n                \"message.id\"\n            ].tolist()\n            # Recursively find replies to the direct replies\n            all_replies = []\n            for reply_id in direct_replies:\n                all_replies += [reply_id] + find_replies(reply_id, reply_data)\n            return all_replies\n        # Filter out parent messages\n        parent_messages = data[~data[\"is_reply\"]]\n        # Filter out reply messages and drop rows with NaN in 'reply_to_id'\n        reply_messages = data[data[\"is_reply\"]].dropna(subset=[\"reply_to_id\"])\n        # Convert 'reply_to_id' to integer\n        reply_messages[\"reply_to_id\"] = reply_messages[\"reply_to_id\"].astype(int)\n        # Create a dictionary of message threads with parent message IDs as keys and \\\n        # lists of reply message IDs as values\n        message_threads = {\n            parent_id: [parent_id] + find_replies(parent_id, reply_messages)\n            for parent_id in parent_messages[\"message.id\"]\n        }\n        return message_threads\n    def _combine_message_texts(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html"}
{"id": "21edf055ea62-4", "text": "}\n        return message_threads\n    def _combine_message_texts(\n        self, message_threads: Dict[int, List[int]], data: pd.DataFrame\n    ) -> str:\n        \"\"\"\n        Combine the message texts for each parent message ID based \\\n            on the list of message threads.\n        Args:\n            message_threads (dict): A dictionary where the key is the parent message \\\n                ID and the value is a list of message IDs in ascending order.\n            data (pd.DataFrame): A DataFrame containing the conversation data:\n                - message.sender_id\n                - text\n                - date\n                - message.id\n                - is_reply\n                - reply_to_id\n        Returns:\n            str: A combined string of message texts sorted by date.\n        \"\"\"\n        combined_text = \"\"\n        # Iterate through sorted parent message IDs\n        for parent_id, message_ids in message_threads.items():\n            # Get the message texts for the message IDs and sort them by date\n            message_texts = (\n                data[data[\"message.id\"].isin(message_ids)]\n                .sort_values(by=\"date\")[\"text\"]\n                .tolist()\n            )\n            message_texts = [str(elem) for elem in message_texts]\n            # Combine the message texts\n            combined_text += \" \".join(message_texts) + \".\\n\"\n        return combined_text.strip()\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        if self.chat_entity is not None:\n            try:\n                import nest_asyncio\n                nest_asyncio.apply()\n                asyncio.run(self.fetch_data_from_telegram())\n            except ImportError:\n                raise ImportError(\n                    \"\"\"`nest_asyncio` package not found.\n                    please install with `pip install nest_asyncio`\n                    \"\"\"\n                )\n        p = Path(self.file_path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html"}
{"id": "21edf055ea62-5", "text": "\"\"\"\n                )\n        p = Path(self.file_path)\n        with open(p, encoding=\"utf8\") as f:\n            d = json.load(f)\n        try:\n            import pandas as pd\n        except ImportError:\n            raise ImportError(\n                \"\"\"`pandas` package not found. \n                please install with `pip install pandas`\n                \"\"\"\n            )\n        normalized_messages = pd.json_normalize(d)\n        df = pd.DataFrame(normalized_messages)\n        message_threads = self._get_message_threads(df)\n        combined_texts = self._combine_message_texts(message_threads, df)\n        return text_to_docs(combined_texts)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html"}
{"id": "9a86553edf1d-0", "text": "Source code for langchain.document_loaders.apify_dataset\nfrom typing import Any, Callable, Dict, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.pydantic_v1 import BaseModel, root_validator\n[docs]class ApifyDatasetLoader(BaseLoader, BaseModel):\n    \"\"\"Load datasets from `Apify` web scraping, crawling, and data extraction platform.\n    For details, see https://docs.apify.com/platform/integrations/langchain\n    Example:\n        .. code-block:: python\n            from langchain.document_loaders import ApifyDatasetLoader\n            from langchain.schema import Document\n            loader = ApifyDatasetLoader(\n                dataset_id=\"YOUR-DATASET-ID\",\n                dataset_mapping_function=lambda dataset_item: Document(\n                    page_content=dataset_item[\"text\"], metadata={\"source\": dataset_item[\"url\"]}\n                ),\n            )\n            documents = loader.load()\n    \"\"\"  # noqa: E501\n    apify_client: Any\n    \"\"\"An instance of the ApifyClient class from the apify-client Python package.\"\"\"\n    dataset_id: str\n    \"\"\"The ID of the dataset on the Apify platform.\"\"\"\n    dataset_mapping_function: Callable[[Dict], Document]\n    \"\"\"A custom function that takes a single dictionary (an Apify dataset item)\n     and converts it to an instance of the Document class.\"\"\"\n    def __init__(\n        self, dataset_id: str, dataset_mapping_function: Callable[[Dict], Document]\n    ):\n        \"\"\"Initialize the loader with an Apify dataset ID and a mapping function.\n        Args:\n            dataset_id (str): The ID of the dataset on the Apify platform.\n            dataset_mapping_function (Callable): A function that takes a single\n                dictionary (an Apify dataset item) and converts it to an instance", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/apify_dataset.html"}
{"id": "9a86553edf1d-1", "text": "dictionary (an Apify dataset item) and converts it to an instance\n                of the Document class.\n        \"\"\"\n        super().__init__(\n            dataset_id=dataset_id, dataset_mapping_function=dataset_mapping_function\n        )\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate environment.\n        Args:\n            values: The values to validate.\n        \"\"\"\n        try:\n            from apify_client import ApifyClient\n            values[\"apify_client\"] = ApifyClient()\n        except ImportError:\n            raise ImportError(\n                \"Could not import apify-client Python package. \"\n                \"Please install it with `pip install apify-client`.\"\n            )\n        return values\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        dataset_items = (\n            self.apify_client.dataset(self.dataset_id).list_items(clean=True).items\n        )\n        return list(map(self.dataset_mapping_function, dataset_items))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/apify_dataset.html"}
{"id": "b2301f82470c-0", "text": "Source code for langchain.document_loaders.larksuite\nimport json\nimport urllib.request\nfrom typing import Any, Iterator, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class LarkSuiteDocLoader(BaseLoader):\n    \"\"\"Load from `LarkSuite` (`FeiShu`).\"\"\"\n[docs]    def __init__(self, domain: str, access_token: str, document_id: str):\n        \"\"\"Initialize with domain, access_token (tenant / user), and document_id.\n        Args:\n            domain: The domain to load the LarkSuite.\n            access_token: The access_token to use.\n            document_id: The document_id to load.\n        \"\"\"\n        self.domain = domain\n        self.access_token = access_token\n        self.document_id = document_id\n    def _get_larksuite_api_json_data(self, api_url: str) -> Any:\n        \"\"\"Get LarkSuite (FeiShu) API response json data.\"\"\"\n        headers = {\"Authorization\": f\"Bearer {self.access_token}\"}\n        request = urllib.request.Request(api_url, headers=headers)\n        with urllib.request.urlopen(request) as response:\n            json_data = json.loads(response.read().decode())\n            return json_data\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazy load LarkSuite (FeiShu) document.\"\"\"\n        api_url_prefix = f\"{self.domain}/open-apis/docx/v1/documents\"\n        metadata_json = self._get_larksuite_api_json_data(\n            f\"{api_url_prefix}/{self.document_id}\"\n        )\n        raw_content_json = self._get_larksuite_api_json_data(\n            f\"{api_url_prefix}/{self.document_id}/raw_content\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/larksuite.html"}
{"id": "b2301f82470c-1", "text": "f\"{api_url_prefix}/{self.document_id}/raw_content\"\n        )\n        text = raw_content_json[\"data\"][\"content\"]\n        metadata = {\n            \"document_id\": self.document_id,\n            \"revision_id\": metadata_json[\"data\"][\"document\"][\"revision_id\"],\n            \"title\": metadata_json[\"data\"][\"document\"][\"title\"],\n        }\n        yield Document(page_content=text, metadata=metadata)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load LarkSuite (FeiShu) document.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/larksuite.html"}
{"id": "9c54ab426776-0", "text": "Source code for langchain.document_loaders.hn\nfrom typing import Any, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.web_base import WebBaseLoader\n[docs]class HNLoader(WebBaseLoader):\n    \"\"\"Load `Hacker News` data.\n    It loads data from either main page results or the comments page.\"\"\"\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Get important HN webpage information.\n        HN webpage components are:\n            - title\n            - content\n            - source url,\n            - time of post\n            - author of the post\n            - number of comments\n            - rank of the post\n        \"\"\"\n        soup_info = self.scrape()\n        if \"item\" in self.web_path:\n            return self.load_comments(soup_info)\n        else:\n            return self.load_results(soup_info)\n[docs]    def load_comments(self, soup_info: Any) -> List[Document]:\n        \"\"\"Load comments from a HN post.\"\"\"\n        comments = soup_info.select(\"tr[class='athing comtr']\")\n        title = soup_info.select_one(\"tr[id='pagespace']\").get(\"title\")\n        return [\n            Document(\n                page_content=comment.text.strip(),\n                metadata={\"source\": self.web_path, \"title\": title},\n            )\n            for comment in comments\n        ]\n[docs]    def load_results(self, soup: Any) -> List[Document]:\n        \"\"\"Load items from an HN page.\"\"\"\n        items = soup.select(\"tr[class='athing']\")\n        documents = []\n        for lineItem in items:\n            ranking = lineItem.select_one(\"span[class='rank']\").text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html"}
{"id": "9c54ab426776-1", "text": "ranking = lineItem.select_one(\"span[class='rank']\").text\n            link = lineItem.find(\"span\", {\"class\": \"titleline\"}).find(\"a\").get(\"href\")\n            title = lineItem.find(\"span\", {\"class\": \"titleline\"}).text.strip()\n            metadata = {\n                \"source\": self.web_path,\n                \"title\": title,\n                \"link\": link,\n                \"ranking\": ranking,\n            }\n            documents.append(\n                Document(\n                    page_content=title, link=link, ranking=ranking, metadata=metadata\n                )\n            )\n        return documents", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html"}
{"id": "c2d668c554a8-0", "text": "Source code for langchain.document_loaders.snowflake_loader\nfrom __future__ import annotations\nfrom typing import Any, Dict, Iterator, List, Optional, Tuple\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class SnowflakeLoader(BaseLoader):\n    \"\"\"Load from `Snowflake` API.\n    Each document represents one row of the result. The `page_content_columns`\n    are written into the `page_content` of the document. The `metadata_columns`\n    are written into the `metadata` of the document. By default, all columns\n    are written into the `page_content` and none into the `metadata`.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        query: str,\n        user: str,\n        password: str,\n        account: str,\n        warehouse: str,\n        role: str,\n        database: str,\n        schema: str,\n        parameters: Optional[Dict[str, Any]] = None,\n        page_content_columns: Optional[List[str]] = None,\n        metadata_columns: Optional[List[str]] = None,\n    ):\n        \"\"\"Initialize Snowflake document loader.\n        Args:\n            query: The query to run in Snowflake.\n            user: Snowflake user.\n            password: Snowflake password.\n            account: Snowflake account.\n            warehouse: Snowflake warehouse.\n            role: Snowflake role.\n            database: Snowflake database\n            schema: Snowflake schema\n            parameters: Optional. Parameters to pass to the query.\n            page_content_columns: Optional. Columns written to Document `page_content`.\n            metadata_columns: Optional. Columns written to Document `metadata`.\n        \"\"\"\n        self.query = query\n        self.user = user\n        self.password = password", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html"}
{"id": "c2d668c554a8-1", "text": "self.query = query\n        self.user = user\n        self.password = password\n        self.account = account\n        self.warehouse = warehouse\n        self.role = role\n        self.database = database\n        self.schema = schema\n        self.parameters = parameters\n        self.page_content_columns = (\n            page_content_columns if page_content_columns is not None else [\"*\"]\n        )\n        self.metadata_columns = metadata_columns if metadata_columns is not None else []\n    def _execute_query(self) -> List[Dict[str, Any]]:\n        try:\n            import snowflake.connector\n        except ImportError as ex:\n            raise ImportError(\n                \"Could not import snowflake-connector-python package. \"\n                \"Please install it with `pip install snowflake-connector-python`.\"\n            ) from ex\n        conn = snowflake.connector.connect(\n            user=self.user,\n            password=self.password,\n            account=self.account,\n            warehouse=self.warehouse,\n            role=self.role,\n            database=self.database,\n            schema=self.schema,\n            parameters=self.parameters,\n        )\n        try:\n            cur = conn.cursor()\n            cur.execute(\"USE DATABASE \" + self.database)\n            cur.execute(\"USE SCHEMA \" + self.schema)\n            cur.execute(self.query, self.parameters)\n            query_result = cur.fetchall()\n            column_names = [column[0] for column in cur.description]\n            query_result = [dict(zip(column_names, row)) for row in query_result]\n        except Exception as e:\n            print(f\"An error occurred: {e}\")\n            query_result = []\n        finally:\n            cur.close()\n        return query_result\n    def _get_columns(\n        self, query_result: List[Dict[str, Any]]\n    ) -> Tuple[List[str], List[str]]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html"}
{"id": "c2d668c554a8-2", "text": ") -> Tuple[List[str], List[str]]:\n        page_content_columns = (\n            self.page_content_columns if self.page_content_columns else []\n        )\n        metadata_columns = self.metadata_columns if self.metadata_columns else []\n        if page_content_columns is None and query_result:\n            page_content_columns = list(query_result[0].keys())\n        if metadata_columns is None:\n            metadata_columns = []\n        return page_content_columns or [], metadata_columns\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        query_result = self._execute_query()\n        if isinstance(query_result, Exception):\n            print(f\"An error occurred during the query: {query_result}\")\n            return []\n        page_content_columns, metadata_columns = self._get_columns(query_result)\n        if \"*\" in page_content_columns:\n            page_content_columns = list(query_result[0].keys())\n        for row in query_result:\n            page_content = \"\\n\".join(\n                f\"{k}: {v}\" for k, v in row.items() if k in page_content_columns\n            )\n            metadata = {k: v for k, v in row.items() if k in metadata_columns}\n            doc = Document(page_content=page_content, metadata=metadata)\n            yield doc\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load data into document objects.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html"}
{"id": "d0fbdd4ff4cd-0", "text": "Source code for langchain.document_loaders.html\nfrom typing import List\nfrom langchain.document_loaders.unstructured import UnstructuredFileLoader\n[docs]class UnstructuredHTMLLoader(UnstructuredFileLoader):\n    \"\"\"Load `HTML` files using `Unstructured`.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredHTMLLoader\n    loader = UnstructuredHTMLLoader(\n        \"example.html\", mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition-html\n    \"\"\"\n    def _get_elements(self) -> List:\n        from unstructured.partition.html import partition_html\n        return partition_html(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html.html"}
{"id": "460300f1d497-0", "text": "Source code for langchain.document_loaders.obs_directory\n# coding:utf-8\nfrom typing import List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.obs_file import OBSFileLoader\n[docs]class OBSDirectoryLoader(BaseLoader):\n    \"\"\"Load from `Huawei OBS directory`.\"\"\"\n[docs]    def __init__(\n        self,\n        bucket: str,\n        endpoint: str,\n        config: Optional[dict] = None,\n        prefix: str = \"\",\n    ):\n        \"\"\"Initialize the OBSDirectoryLoader with the specified settings.\n        Args:\n            bucket (str): The name of the OBS bucket to be used.\n            endpoint (str): The endpoint URL of your OBS bucket.\n            config (dict): The parameters for connecting to OBS, provided as a dictionary. The dictionary could have the following keys:\n                - \"ak\" (str, optional): Your OBS access key (required if `get_token_from_ecs` is False and bucket policy is not public read).\n                - \"sk\" (str, optional): Your OBS secret key (required if `get_token_from_ecs` is False and bucket policy is not public read).\n                - \"token\" (str, optional): Your security token (required if using temporary credentials).\n                - \"get_token_from_ecs\" (bool, optional): Whether to retrieve the security token from ECS. Defaults to False if not provided. If set to True, `ak`, `sk`, and `token` will be ignored.\n            prefix (str, optional): The prefix to be added to the OBS key. Defaults to \"\".\n        Note:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obs_directory.html"}
{"id": "460300f1d497-1", "text": "Note:\n            Before using this class, make sure you have registered with OBS and have the necessary credentials. The `ak`, `sk`, and `endpoint` values are mandatory unless `get_token_from_ecs` is True or the bucket policy is public read. `token` is required when using temporary credentials.\n        Example:\n            To create a new OBSDirectoryLoader:\n            ```\n            config = {\n                \"ak\": \"your-access-key\",\n                \"sk\": \"your-secret-key\"\n            }\n            ```\n            directory_loader = OBSDirectoryLoader(\"your-bucket-name\", \"your-end-endpoint\", config, \"your-prefix\")\n        \"\"\"  # noqa: E501\n        try:\n            from obs import ObsClient\n        except ImportError:\n            raise ImportError(\n                \"Could not import esdk-obs-python python package. \"\n                \"Please install it with `pip install esdk-obs-python`.\"\n            )\n        if not config:\n            config = dict()\n        if config.get(\"get_token_from_ecs\"):\n            self.client = ObsClient(server=endpoint, security_provider_policy=\"ECS\")\n        else:\n            self.client = ObsClient(\n                access_key_id=config.get(\"ak\"),\n                secret_access_key=config.get(\"sk\"),\n                security_token=config.get(\"token\"),\n                server=endpoint,\n            )\n        self.bucket = bucket\n        self.prefix = prefix\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        max_num = 1000\n        mark = None\n        docs = []\n        while True:\n            resp = self.client.listObjects(\n                self.bucket, prefix=self.prefix, marker=mark, max_keys=max_num\n            )\n            if resp.status < 300:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obs_directory.html"}
{"id": "460300f1d497-2", "text": ")\n            if resp.status < 300:\n                for content in resp.body.contents:\n                    loader = OBSFileLoader(self.bucket, content.key, client=self.client)\n                    docs.extend(loader.load())\n                if resp.body.is_truncated is True:\n                    mark = resp.body.next_marker\n                else:\n                    break\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obs_directory.html"}
{"id": "f2b48409902d-0", "text": "Source code for langchain.document_loaders.image_captions\nfrom io import BytesIO\nfrom typing import Any, List, Tuple, Union\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class ImageCaptionLoader(BaseLoader):\n    \"\"\"Load image captions.\n    By default, the loader utilizes the pre-trained\n    Salesforce BLIP image captioning model.\n    https://huggingface.co/Salesforce/blip-image-captioning-base\n    \"\"\"\n[docs]    def __init__(\n        self,\n        images: Union[str, bytes, List[Union[str, bytes]]],\n        blip_processor: str = \"Salesforce/blip-image-captioning-base\",\n        blip_model: str = \"Salesforce/blip-image-captioning-base\",\n    ):\n        \"\"\"Initialize with a list of image data (bytes) or file paths\n        Args:\n            images: Either a single image or a list of images. Accepts\n                    image data (bytes) or file paths to images.\n            blip_processor: The name of the pre-trained BLIP processor.\n            blip_model: The name of the pre-trained BLIP model.\n        \"\"\"\n        if isinstance(images, (str, bytes)):\n            self.images = [images]\n        else:\n            self.images = images\n        self.blip_processor = blip_processor\n        self.blip_model = blip_model\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load from a list of image data or file paths\"\"\"\n        try:\n            from transformers import BlipForConditionalGeneration, BlipProcessor\n        except ImportError:\n            raise ImportError(\n                \"`transformers` package not found, please install with \"\n                \"`pip install transformers`.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html"}
{"id": "f2b48409902d-1", "text": "\"`pip install transformers`.\"\n            )\n        processor = BlipProcessor.from_pretrained(self.blip_processor)\n        model = BlipForConditionalGeneration.from_pretrained(self.blip_model)\n        results = []\n        for image in self.images:\n            caption, metadata = self._get_captions_and_metadata(\n                model=model, processor=processor, image=image\n            )\n            doc = Document(page_content=caption, metadata=metadata)\n            results.append(doc)\n        return results\n    def _get_captions_and_metadata(\n        self, model: Any, processor: Any, image: Union[str, bytes]\n    ) -> Tuple[str, dict]:\n        \"\"\"Helper function for getting the captions and metadata of an image.\"\"\"\n        try:\n            from PIL import Image\n        except ImportError:\n            raise ImportError(\n                \"`PIL` package not found, please install with `pip install pillow`\"\n            )\n        image_source = image  # Save the original source for later reference\n        try:\n            if isinstance(image, bytes):\n                image = Image.open(BytesIO(image)).convert(\"RGB\")\n            elif image.startswith(\"http://\") or image.startswith(\"https://\"):\n                image = Image.open(requests.get(image, stream=True).raw).convert(\"RGB\")\n            else:\n                image = Image.open(image).convert(\"RGB\")\n        except Exception:\n            if isinstance(image_source, bytes):\n                msg = \"Could not get image data from bytes\"\n            else:\n                msg = f\"Could not get image data for {image_source}\"\n            raise ValueError(msg)\n        inputs = processor(image, \"an image of\", return_tensors=\"pt\")\n        output = model.generate(**inputs)\n        caption: str = processor.decode(output[0])\n        if isinstance(image_source, bytes):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html"}
{"id": "f2b48409902d-2", "text": "if isinstance(image_source, bytes):\n            metadata: dict = {\"image_source\": \"Image bytes provided\"}\n        else:\n            metadata = {\"image_path\": image_source}\n        return caption, metadata", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html"}
{"id": "b289f6ee5b3d-0", "text": "Source code for langchain.document_loaders.baiducloud_bos_file\nimport logging\nimport os\nimport tempfile\nfrom typing import Any, Iterator, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.unstructured import UnstructuredFileLoader\nlogger = logging.getLogger(__name__)\n[docs]class BaiduBOSFileLoader(BaseLoader):\n    \"\"\"Load from `Baidu Cloud BOS` file.\"\"\"\n[docs]    def __init__(self, conf: Any, bucket: str, key: str):\n        \"\"\"Initialize with BOS config, bucket and key name.\n        :param conf(BceClientConfiguration): BOS config.\n        :param bucket(str): BOS bucket.\n        :param key(str): BOS file key.\n        \"\"\"\n        self.conf = conf\n        self.bucket = bucket\n        self.key = key\n[docs]    def load(self) -> List[Document]:\n        return list(self.lazy_load())\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Load documents.\"\"\"\n        try:\n            from baidubce.services.bos.bos_client import BosClient\n        except ImportError:\n            raise ImportError(\n                \"Please using `pip install bce-python-sdk`\"\n                + \" before import bos related package.\"\n            )\n        # Initialize BOS Client\n        client = BosClient(self.conf)\n        with tempfile.TemporaryDirectory() as temp_dir:\n            file_path = f\"{temp_dir}/{self.bucket}/{self.key}\"\n            os.makedirs(os.path.dirname(file_path), exist_ok=True)\n            # Download the file to a destination\n            logger.debug(f\"get object key {self.key} to file {file_path}\")\n            client.get_object_to_file(self.bucket, self.key, file_path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/baiducloud_bos_file.html"}
{"id": "b289f6ee5b3d-1", "text": "client.get_object_to_file(self.bucket, self.key, file_path)\n            try:\n                loader = UnstructuredFileLoader(file_path)\n                documents = loader.load()\n                return iter(documents)\n            except Exception as ex:\n                logger.error(f\"load document error = {ex}\")\n                return iter([Document(page_content=\"\")])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/baiducloud_bos_file.html"}
{"id": "ed4b8cefffab-0", "text": "Source code for langchain.document_loaders.figma\nimport json\nimport urllib.request\nfrom typing import Any, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utils import stringify_dict\n[docs]class FigmaFileLoader(BaseLoader):\n    \"\"\"Load `Figma` file.\"\"\"\n[docs]    def __init__(self, access_token: str, ids: str, key: str):\n        \"\"\"Initialize with access token, ids, and key.\n        Args:\n            access_token: The access token for the Figma REST API.\n            ids: The ids of the Figma file.\n            key: The key for the Figma file\n        \"\"\"\n        self.access_token = access_token\n        self.ids = ids\n        self.key = key\n    def _construct_figma_api_url(self) -> str:\n        api_url = \"https://api.figma.com/v1/files/%s/nodes?ids=%s\" % (\n            self.key,\n            self.ids,\n        )\n        return api_url\n    def _get_figma_file(self) -> Any:\n        \"\"\"Get Figma file from Figma REST API.\"\"\"\n        headers = {\"X-Figma-Token\": self.access_token}\n        request = urllib.request.Request(\n            self._construct_figma_api_url(), headers=headers\n        )\n        with urllib.request.urlopen(request) as response:\n            json_data = json.loads(response.read().decode())\n            return json_data\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load file\"\"\"\n        data = self._get_figma_file()\n        text = stringify_dict(data)\n        metadata = {\"source\": self._construct_figma_api_url()}\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/figma.html"}
{"id": "f85710b32147-0", "text": "Source code for langchain.document_loaders.gitbook\nfrom typing import Any, List, Optional\nfrom urllib.parse import urljoin, urlparse\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.web_base import WebBaseLoader\n[docs]class GitbookLoader(WebBaseLoader):\n    \"\"\"Load `GitBook` data.\n    1. load from either a single page, or\n    2. load all (relative) paths in the navbar.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        web_page: str,\n        load_all_paths: bool = False,\n        base_url: Optional[str] = None,\n        content_selector: str = \"main\",\n        continue_on_failure: bool = False,\n    ):\n        \"\"\"Initialize with web page and whether to load all paths.\n        Args:\n            web_page: The web page to load or the starting point from where\n                relative paths are discovered.\n            load_all_paths: If set to True, all relative paths in the navbar\n                are loaded instead of only `web_page`.\n            base_url: If `load_all_paths` is True, the relative paths are\n                appended to this base url. Defaults to `web_page`.\n            content_selector: The CSS selector for the content to load.\n                Defaults to \"main\".\n            continue_on_failure: whether to continue loading the sitemap if an error\n                occurs loading a url, emitting a warning instead of raising an\n                exception. Setting this to True makes the loader more robust, but also\n                may result in missing data. Default: False\n        \"\"\"\n        self.base_url = base_url or web_page\n        if self.base_url.endswith(\"/\"):\n            self.base_url = self.base_url[:-1]\n        if load_all_paths:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html"}
{"id": "f85710b32147-1", "text": "self.base_url = self.base_url[:-1]\n        if load_all_paths:\n            # set web_path to the sitemap if we want to crawl all paths\n            web_page = f\"{self.base_url}/sitemap.xml\"\n        super().__init__(web_paths=(web_page,), continue_on_failure=continue_on_failure)\n        self.load_all_paths = load_all_paths\n        self.content_selector = content_selector\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Fetch text from one single GitBook page.\"\"\"\n        if self.load_all_paths:\n            soup_info = self.scrape()\n            relative_paths = self._get_paths(soup_info)\n            urls = [urljoin(self.base_url, path) for path in relative_paths]\n            soup_infos = self.scrape_all(urls)\n            _documents = [\n                self._get_document(soup_info, url)\n                for soup_info, url in zip(soup_infos, urls)\n            ]\n        else:\n            soup_info = self.scrape()\n            _documents = [self._get_document(soup_info, self.web_path)]\n        documents = [d for d in _documents if d]\n        return documents\n    def _get_document(\n        self, soup: Any, custom_url: Optional[str] = None\n    ) -> Optional[Document]:\n        \"\"\"Fetch content from page and return Document.\"\"\"\n        page_content_raw = soup.find(self.content_selector)\n        if not page_content_raw:\n            return None\n        content = page_content_raw.get_text(separator=\"\\n\").strip()\n        title_if_exists = page_content_raw.find(\"h1\")\n        title = title_if_exists.text if title_if_exists else \"\"\n        metadata = {\"source\": custom_url or self.web_path, \"title\": title}\n        return Document(page_content=content, metadata=metadata)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html"}
{"id": "f85710b32147-2", "text": "return Document(page_content=content, metadata=metadata)\n    def _get_paths(self, soup: Any) -> List[str]:\n        \"\"\"Fetch all relative paths in the navbar.\"\"\"\n        return [urlparse(loc.text).path for loc in soup.find_all(\"loc\")]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html"}
{"id": "ede3c2ffc6f5-0", "text": "Source code for langchain.document_loaders.html_bs\nimport logging\nfrom typing import Dict, List, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nlogger = logging.getLogger(__name__)\n[docs]class BSHTMLLoader(BaseLoader):\n    \"\"\"Load `HTML` files and parse them with `beautiful soup`.\"\"\"\n[docs]    def __init__(\n        self,\n        file_path: str,\n        open_encoding: Union[str, None] = None,\n        bs_kwargs: Union[dict, None] = None,\n        get_text_separator: str = \"\",\n    ) -> None:\n        \"\"\"Initialise with path, and optionally, file encoding to use, and any kwargs\n        to pass to the BeautifulSoup object.\n        Args:\n            file_path: The path to the file to load.\n            open_encoding: The encoding to use when opening the file.\n            bs_kwargs: Any kwargs to pass to the BeautifulSoup object.\n            get_text_separator: The separator to use when calling get_text on the soup.\n        \"\"\"\n        try:\n            import bs4  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"beautifulsoup4 package not found, please install it with \"\n                \"`pip install beautifulsoup4`\"\n            )\n        self.file_path = file_path\n        self.open_encoding = open_encoding\n        if bs_kwargs is None:\n            bs_kwargs = {\"features\": \"lxml\"}\n        self.bs_kwargs = bs_kwargs\n        self.get_text_separator = get_text_separator\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load HTML document into document objects.\"\"\"\n        from bs4 import BeautifulSoup\n        with open(self.file_path, \"r\", encoding=self.open_encoding) as f:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html"}
{"id": "ede3c2ffc6f5-1", "text": "with open(self.file_path, \"r\", encoding=self.open_encoding) as f:\n            soup = BeautifulSoup(f, **self.bs_kwargs)\n        text = soup.get_text(self.get_text_separator)\n        if soup.title:\n            title = str(soup.title.string)\n        else:\n            title = \"\"\n        metadata: Dict[str, Union[str, None]] = {\n            \"source\": self.file_path,\n            \"title\": title,\n        }\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html"}
{"id": "4217136fd77b-0", "text": "Source code for langchain.document_loaders.dataframe\nfrom typing import Any, Iterator, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class BaseDataFrameLoader(BaseLoader):\n[docs]    def __init__(self, data_frame: Any, *, page_content_column: str = \"text\"):\n        \"\"\"Initialize with dataframe object.\n        Args:\n            data_frame: DataFrame object.\n            page_content_column: Name of the column containing the page content.\n              Defaults to \"text\".\n        \"\"\"\n        self.data_frame = data_frame\n        self.page_content_column = page_content_column\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazy load records from dataframe.\"\"\"\n        for _, row in self.data_frame.iterrows():\n            text = row[self.page_content_column]\n            metadata = row.to_dict()\n            metadata.pop(self.page_content_column)\n            yield Document(page_content=text, metadata=metadata)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load full dataframe.\"\"\"\n        return list(self.lazy_load())\n[docs]class DataFrameLoader(BaseDataFrameLoader):\n    \"\"\"Load `Pandas` DataFrame.\"\"\"\n[docs]    def __init__(self, data_frame: Any, page_content_column: str = \"text\"):\n        \"\"\"Initialize with dataframe object.\n        Args:\n            data_frame: Pandas DataFrame object.\n            page_content_column: Name of the column containing the page content.\n              Defaults to \"text\".\n        \"\"\"\n        try:\n            import pandas as pd\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import pandas, please install with `pip install pandas`.\"\n            ) from e\n        if not isinstance(data_frame, pd.DataFrame):\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/dataframe.html"}
{"id": "4217136fd77b-1", "text": "if not isinstance(data_frame, pd.DataFrame):\n            raise ValueError(\n                f\"Expected data_frame to be a pd.DataFrame, got {type(data_frame)}\"\n            )\n        super().__init__(data_frame, page_content_column=page_content_column)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/dataframe.html"}
{"id": "76797d9b0cbf-0", "text": "Source code for langchain.document_loaders.onedrive_file\nfrom __future__ import annotations\nimport tempfile\nfrom typing import TYPE_CHECKING, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.unstructured import UnstructuredFileLoader\nfrom langchain.pydantic_v1 import BaseModel, Field\nif TYPE_CHECKING:\n    from O365.drive import File\nCHUNK_SIZE = 1024 * 1024 * 5\n[docs]class OneDriveFileLoader(BaseLoader, BaseModel):\n    \"\"\"Load a file from `Microsoft OneDrive`.\"\"\"\n    file: File = Field(...)\n    \"\"\"The file to load.\"\"\"\n    class Config:\n        arbitrary_types_allowed = True\n        \"\"\"Allow arbitrary types. This is needed for the File type. Default is True.\n         See https://pydantic-docs.helpmanual.io/usage/types/#arbitrary-types-allowed\"\"\"\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load Documents\"\"\"\n        with tempfile.TemporaryDirectory() as temp_dir:\n            file_path = f\"{temp_dir}/{self.file.name}\"\n            self.file.download(to_path=temp_dir, chunk_size=CHUNK_SIZE)\n            loader = UnstructuredFileLoader(file_path)\n            return loader.load()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive_file.html"}
{"id": "c6bde6f244ef-0", "text": "Source code for langchain.document_loaders.sitemap\nimport itertools\nimport re\nfrom typing import Any, Callable, Generator, Iterable, List, Optional, Tuple\nfrom urllib.parse import urlparse\nfrom langchain.document_loaders.web_base import WebBaseLoader\nfrom langchain.schema import Document\ndef _default_parsing_function(content: Any) -> str:\n    return str(content.get_text())\ndef _default_meta_function(meta: dict, _content: Any) -> dict:\n    return {\"source\": meta[\"loc\"], **meta}\ndef _batch_block(iterable: Iterable, size: int) -> Generator[List[dict], None, None]:\n    it = iter(iterable)\n    while item := list(itertools.islice(it, size)):\n        yield item\ndef _extract_scheme_and_domain(url: str) -> Tuple[str, str]:\n    \"\"\"Extract the scheme + domain from a given URL.\n    Args:\n        url (str): The input URL.\n    Returns:\n        return a 2-tuple of scheme and domain\n    \"\"\"\n    parsed_uri = urlparse(url)\n    return parsed_uri.scheme, parsed_uri.netloc\n[docs]class SitemapLoader(WebBaseLoader):\n    \"\"\"Load a sitemap and its URLs.\n    **Security Note**: This loader can be used to load all URLs specified in a sitemap.\n        If a malicious actor gets access to the sitemap, they could force\n        the server to load URLs from other domains by modifying the sitemap.\n        This could lead to server-side request forgery (SSRF) attacks; e.g.,\n        with the attacker forcing the server to load URLs from internal\n        service endpoints that are not publicly accessible. While the attacker\n        may not immediately gain access to this data, this data could leak\n        into downstream systems (e.g., data loader is used to load data for indexing).", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html"}
{"id": "c6bde6f244ef-1", "text": "into downstream systems (e.g., data loader is used to load data for indexing).\n        This loader is a crawler and web crawlers should generally NOT be deployed\n        with network access to any internal servers.\n        Control access to who can submit crawling requests and what network access\n        the crawler has.\n        By default, the loader will only load URLs from the same domain as the sitemap\n        if the site map is not a local file. This can be disabled by setting\n        restrict_to_same_domain to False (not recommended).\n        If the site map is a local file, no such risk mitigation is applied by default.\n        Use the filter URLs argument to limit which URLs can be loaded.\n        See https://python.langchain.com/docs/security\n    \"\"\"\n[docs]    def __init__(\n        self,\n        web_path: str,\n        filter_urls: Optional[List[str]] = None,\n        parsing_function: Optional[Callable] = None,\n        blocksize: Optional[int] = None,\n        blocknum: int = 0,\n        meta_function: Optional[Callable] = None,\n        is_local: bool = False,\n        continue_on_failure: bool = False,\n        restrict_to_same_domain: bool = True,\n        **kwargs: Any,\n    ):\n        \"\"\"Initialize with webpage path and optional filter URLs.\n        Args:\n            web_path: url of the sitemap. can also be a local path\n            filter_urls: a list of regexes. If specified, only\n                URLS that match one of the filter URLs will be loaded.\n                *WARNING* The filter URLs are interpreted as regular expressions.\n                Remember to escape special characters if you do not want them to be\n                interpreted as regular expression syntax. For example, `.` appears", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html"}
{"id": "c6bde6f244ef-2", "text": "interpreted as regular expression syntax. For example, `.` appears\n                frequently in URLs and should be escaped if you want to match a literal\n                `.` rather than any character.\n                restrict_to_same_domain takes precedence over filter_urls when\n                restrict_to_same_domain is True and the sitemap is not a local file.\n            parsing_function: Function to parse bs4.Soup output\n            blocksize: number of sitemap locations per block\n            blocknum: the number of the block that should be loaded - zero indexed.\n                Default: 0\n            meta_function: Function to parse bs4.Soup output for metadata\n                remember when setting this method to also copy metadata[\"loc\"]\n                to metadata[\"source\"] if you are using this field\n            is_local: whether the sitemap is a local file. Default: False\n            continue_on_failure: whether to continue loading the sitemap if an error\n                occurs loading a url, emitting a warning instead of raising an\n                exception. Setting this to True makes the loader more robust, but also\n                may result in missing data. Default: False\n            restrict_to_same_domain: whether to restrict loading to URLs to the same\n                domain as the sitemap. Attention: This is only applied if the sitemap\n                is not a local file!\n        \"\"\"\n        if blocksize is not None and blocksize < 1:\n            raise ValueError(\"Sitemap blocksize should be at least 1\")\n        if blocknum < 0:\n            raise ValueError(\"Sitemap blocknum can not be lower then 0\")\n        try:\n            import lxml  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"lxml package not found, please install it with `pip install lxml`\"\n            )\n        super().__init__(web_paths=[web_path], **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html"}
{"id": "c6bde6f244ef-3", "text": ")\n        super().__init__(web_paths=[web_path], **kwargs)\n        # Define a list of URL patterns (interpreted as regular expressions) that\n        # will be allowed to be loaded.\n        # restrict_to_same_domain takes precedence over filter_urls when\n        # restrict_to_same_domain is True and the sitemap is not a local file.\n        self.allow_url_patterns = filter_urls\n        self.restrict_to_same_domain = restrict_to_same_domain\n        self.parsing_function = parsing_function or _default_parsing_function\n        self.meta_function = meta_function or _default_meta_function\n        self.blocksize = blocksize\n        self.blocknum = blocknum\n        self.is_local = is_local\n        self.continue_on_failure = continue_on_failure\n[docs]    def parse_sitemap(self, soup: Any) -> List[dict]:\n        \"\"\"Parse sitemap xml and load into a list of dicts.\n        Args:\n            soup: BeautifulSoup object.\n        Returns:\n            List of dicts.\n        \"\"\"\n        els = []\n        for url in soup.find_all(\"url\"):\n            loc = url.find(\"loc\")\n            if not loc:\n                continue\n            # Strip leading and trailing whitespace and newlines\n            loc_text = loc.text.strip()\n            if self.restrict_to_same_domain and not self.is_local:\n                if _extract_scheme_and_domain(loc_text) != _extract_scheme_and_domain(\n                    self.web_path\n                ):\n                    continue\n            if self.allow_url_patterns and not any(\n                re.match(regexp_pattern, loc_text)\n                for regexp_pattern in self.allow_url_patterns\n            ):\n                continue\n            els.append(\n                {\n                    tag: prop.text\n                    for tag in [\"loc\", \"lastmod\", \"changefreq\", \"priority\"]\n                    if (prop := url.find(tag))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html"}
{"id": "c6bde6f244ef-4", "text": "if (prop := url.find(tag))\n                }\n            )\n        for sitemap in soup.find_all(\"sitemap\"):\n            loc = sitemap.find(\"loc\")\n            if not loc:\n                continue\n            soup_child = self.scrape_all([loc.text], \"xml\")[0]\n            els.extend(self.parse_sitemap(soup_child))\n        return els\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load sitemap.\"\"\"\n        if self.is_local:\n            try:\n                import bs4\n            except ImportError:\n                raise ImportError(\n                    \"beautifulsoup4 package not found, please install it\"\n                    \" with `pip install beautifulsoup4`\"\n                )\n            fp = open(self.web_path)\n            soup = bs4.BeautifulSoup(fp, \"xml\")\n        else:\n            soup = self._scrape(self.web_path, parser=\"xml\")\n        els = self.parse_sitemap(soup)\n        if self.blocksize is not None:\n            elblocks = list(_batch_block(els, self.blocksize))\n            blockcount = len(elblocks)\n            if blockcount - 1 < self.blocknum:\n                raise ValueError(\n                    \"Selected sitemap does not contain enough blocks for given blocknum\"\n                )\n            else:\n                els = elblocks[self.blocknum]\n        results = self.scrape_all([el[\"loc\"].strip() for el in els if \"loc\" in el])\n        return [\n            Document(\n                page_content=self.parsing_function(results[i]),\n                metadata=self.meta_function(els[i], results[i]),\n            )\n            for i in range(len(results))\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html"}
{"id": "627c314e34dc-0", "text": "Source code for langchain.document_loaders.tencent_cos_directory\nfrom typing import Any, Iterator, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.tencent_cos_file import TencentCOSFileLoader\n[docs]class TencentCOSDirectoryLoader(BaseLoader):\n    \"\"\"Load from `Tencent Cloud COS` directory.\"\"\"\n[docs]    def __init__(self, conf: Any, bucket: str, prefix: str = \"\"):\n        \"\"\"Initialize with COS config, bucket and prefix.\n        :param conf(CosConfig): COS config.\n        :param bucket(str): COS bucket.\n        :param prefix(str): prefix.\n        \"\"\"\n        self.conf = conf\n        self.bucket = bucket\n        self.prefix = prefix\n[docs]    def load(self) -> List[Document]:\n        return list(self.lazy_load())\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Load documents.\"\"\"\n        try:\n            from qcloud_cos import CosS3Client\n        except ImportError:\n            raise ImportError(\n                \"Could not import cos-python-sdk-v5 python package. \"\n                \"Please install it with `pip install cos-python-sdk-v5`.\"\n            )\n        client = CosS3Client(self.conf)\n        contents = []\n        marker = \"\"\n        while True:\n            response = client.list_objects(\n                Bucket=self.bucket, Prefix=self.prefix, Marker=marker, MaxKeys=1000\n            )\n            if \"Contents\" in response:\n                contents.extend(response[\"Contents\"])\n            if response[\"IsTruncated\"] == \"false\":\n                break\n            marker = response[\"NextMarker\"]\n        for content in contents:\n            if content[\"Key\"].endswith(\"/\"):\n                continue", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tencent_cos_directory.html"}
{"id": "627c314e34dc-1", "text": "if content[\"Key\"].endswith(\"/\"):\n                continue\n            loader = TencentCOSFileLoader(self.conf, self.bucket, content[\"Key\"])\n            yield loader.load()[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tencent_cos_directory.html"}
{"id": "165adbf572ac-0", "text": "Source code for langchain.document_loaders.reddit\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Iterable, List, Optional, Sequence\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nif TYPE_CHECKING:\n    import praw\ndef _dependable_praw_import() -> praw:\n    try:\n        import praw\n    except ImportError:\n        raise ImportError(\n            \"praw package not found, please install it with `pip install praw`\"\n        )\n    return praw\n[docs]class RedditPostsLoader(BaseLoader):\n    \"\"\"Load `Reddit` posts.\n    Read posts on a subreddit.\n    First, you need to go to\n    https://www.reddit.com/prefs/apps/\n    and create your application\n    \"\"\"\n[docs]    def __init__(\n        self,\n        client_id: str,\n        client_secret: str,\n        user_agent: str,\n        search_queries: Sequence[str],\n        mode: str,\n        categories: Sequence[str] = [\"new\"],\n        number_posts: Optional[int] = 10,\n    ):\n        \"\"\"\n        Initialize with client_id, client_secret, user_agent, search_queries, mode,\n            categories, number_posts.\n        Example: https://www.reddit.com/r/learnpython/\n        Args:\n            client_id: Reddit client id.\n            client_secret: Reddit client secret.\n            user_agent: Reddit user agent.\n            search_queries: The search queries.\n            mode: The mode.\n            categories: The categories. Default: [\"new\"]\n            number_posts: The number of posts. Default: 10\n        \"\"\"\n        self.client_id = client_id\n        self.client_secret = client_secret\n        self.user_agent = user_agent\n        self.search_queries = search_queries", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html"}
{"id": "165adbf572ac-1", "text": "self.user_agent = user_agent\n        self.search_queries = search_queries\n        self.mode = mode\n        self.categories = categories\n        self.number_posts = number_posts\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load reddits.\"\"\"\n        praw = _dependable_praw_import()\n        reddit = praw.Reddit(\n            client_id=self.client_id,\n            client_secret=self.client_secret,\n            user_agent=self.user_agent,\n        )\n        results: List[Document] = []\n        if self.mode == \"subreddit\":\n            for search_query in self.search_queries:\n                for category in self.categories:\n                    docs = self._subreddit_posts_loader(\n                        search_query=search_query, category=category, reddit=reddit\n                    )\n                    results.extend(docs)\n        elif self.mode == \"username\":\n            for search_query in self.search_queries:\n                for category in self.categories:\n                    docs = self._user_posts_loader(\n                        search_query=search_query, category=category, reddit=reddit\n                    )\n                    results.extend(docs)\n        else:\n            raise ValueError(\n                \"mode not correct, please enter 'username' or 'subreddit' as mode\"\n            )\n        return results\n    def _subreddit_posts_loader(\n        self, search_query: str, category: str, reddit: praw.reddit.Reddit\n    ) -> Iterable[Document]:\n        subreddit = reddit.subreddit(search_query)\n        method = getattr(subreddit, category)\n        cat_posts = method(limit=self.number_posts)\n        \"\"\"Format reddit posts into a string.\"\"\"\n        for post in cat_posts:\n            metadata = {\n                \"post_subreddit\": post.subreddit_name_prefixed,\n                \"post_category\": category,\n                \"post_title\": post.title,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html"}
{"id": "165adbf572ac-2", "text": "\"post_category\": category,\n                \"post_title\": post.title,\n                \"post_score\": post.score,\n                \"post_id\": post.id,\n                \"post_url\": post.url,\n                \"post_author\": post.author,\n            }\n            yield Document(\n                page_content=post.selftext,\n                metadata=metadata,\n            )\n    def _user_posts_loader(\n        self, search_query: str, category: str, reddit: praw.reddit.Reddit\n    ) -> Iterable[Document]:\n        user = reddit.redditor(search_query)\n        method = getattr(user.submissions, category)\n        cat_posts = method(limit=self.number_posts)\n        \"\"\"Format reddit posts into a string.\"\"\"\n        for post in cat_posts:\n            metadata = {\n                \"post_subreddit\": post.subreddit_name_prefixed,\n                \"post_category\": category,\n                \"post_title\": post.title,\n                \"post_score\": post.score,\n                \"post_id\": post.id,\n                \"post_url\": post.url,\n                \"post_author\": post.author,\n            }\n            yield Document(\n                page_content=post.selftext,\n                metadata=metadata,\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html"}
{"id": "dac9f474d297-0", "text": "Source code for langchain.document_loaders.merge\nfrom typing import Iterator, List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class MergedDataLoader(BaseLoader):\n    \"\"\"Merge documents from a list of loaders\"\"\"\n[docs]    def __init__(self, loaders: List):\n        \"\"\"Initialize with a list of loaders\"\"\"\n        self.loaders = loaders\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazy load docs from each individual loader.\"\"\"\n        for loader in self.loaders:\n            # Check if lazy_load is implemented\n            try:\n                data = loader.lazy_load()\n            except NotImplementedError:\n                data = loader.load()\n            for document in data:\n                yield document\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load docs.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/merge.html"}
{"id": "094af0c289aa-0", "text": "Source code for langchain.document_loaders.azlyrics\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.web_base import WebBaseLoader\n[docs]class AZLyricsLoader(WebBaseLoader):\n    \"\"\"Load `AZLyrics` webpages.\"\"\"\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load webpages into Documents.\"\"\"\n        soup = self.scrape()\n        title = soup.title.text\n        lyrics = soup.find_all(\"div\", {\"class\": \"\"})[2].text\n        text = title + lyrics\n        metadata = {\"source\": self.web_path}\n        return [Document(page_content=text, metadata=metadata)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/azlyrics.html"}
{"id": "8abbde1a4046-0", "text": "Source code for langchain.document_loaders.odt\nfrom typing import Any, List\nfrom langchain.document_loaders.unstructured import (\n    UnstructuredFileLoader,\n    validate_unstructured_version,\n)\n[docs]class UnstructuredODTLoader(UnstructuredFileLoader):\n    \"\"\"Load `OpenOffice ODT` files using `Unstructured`.\n    You can run the loader in one of two modes: \"single\" and \"elements\".\n    If you use \"single\" mode, the document will be returned as a single\n    langchain Document object. If you use \"elements\" mode, the unstructured\n    library will split the document into elements such as Title and NarrativeText.\n    You can pass in additional unstructured kwargs after mode to apply\n    different unstructured settings.\n    Examples\n    --------\n    from langchain.document_loaders import UnstructuredODTLoader\n    loader = UnstructuredODTLoader(\n        \"example.odt\", mode=\"elements\", strategy=\"fast\",\n    )\n    docs = loader.load()\n    References\n    ----------\n    https://unstructured-io.github.io/unstructured/bricks.html#partition-odt\n    \"\"\"\n[docs]    def __init__(\n        self, file_path: str, mode: str = \"single\", **unstructured_kwargs: Any\n    ):\n        \"\"\"\n        Args:\n            file_path: The path to the file to load.\n            mode: The mode to use when loading the file. Can be one of \"single\",\n                \"multi\", or \"all\". Default is \"single\".\n            **unstructured_kwargs: Any kwargs to pass to the unstructured.\n        \"\"\"\n        validate_unstructured_version(min_unstructured_version=\"0.6.3\")\n        super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/odt.html"}
{"id": "8abbde1a4046-1", "text": "super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)\n    def _get_elements(self) -> List:\n        from unstructured.partition.odt import partition_odt\n        return partition_odt(filename=self.file_path, **self.unstructured_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/odt.html"}
{"id": "8ecc17f2b944-0", "text": "Source code for langchain.document_loaders.notion\nfrom pathlib import Path\nfrom typing import List\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n[docs]class NotionDirectoryLoader(BaseLoader):\n    \"\"\"Load `Notion directory` dump.\"\"\"\n[docs]    def __init__(self, path: str, *, encoding: str = \"utf-8\") -> None:\n        \"\"\"Initialize with a file path.\"\"\"\n        self.file_path = path\n        self.encoding = encoding\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load documents.\"\"\"\n        paths = list(Path(self.file_path).glob(\"**/*.md\"))\n        docs = []\n        for p in paths:\n            with open(p, encoding=self.encoding) as f:\n                text = f.read()\n            metadata = {\"source\": str(p)}\n            docs.append(Document(page_content=text, metadata=metadata))\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notion.html"}
{"id": "5e0cc3c2f122-0", "text": "Source code for langchain.document_loaders.recursive_url_loader\nfrom __future__ import annotations\nimport asyncio\nimport logging\nimport re\nfrom typing import (\n    TYPE_CHECKING,\n    Callable,\n    Iterator,\n    List,\n    Optional,\n    Sequence,\n    Set,\n    Union,\n)\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utils.html import extract_sub_links\nif TYPE_CHECKING:\n    import aiohttp\nlogger = logging.getLogger(__name__)\ndef _metadata_extractor(raw_html: str, url: str) -> dict:\n    \"\"\"Extract metadata from raw html using BeautifulSoup.\"\"\"\n    metadata = {\"source\": url}\n    try:\n        from bs4 import BeautifulSoup\n    except ImportError:\n        logger.warning(\n            \"The bs4 package is required for default metadata extraction. \"\n            \"Please install it with `pip install bs4`.\"\n        )\n        return metadata\n    soup = BeautifulSoup(raw_html, \"html.parser\")\n    if title := soup.find(\"title\"):\n        metadata[\"title\"] = title.get_text()\n    if description := soup.find(\"meta\", attrs={\"name\": \"description\"}):\n        metadata[\"description\"] = description.get(\"content\", None)\n    if html := soup.find(\"html\"):\n        metadata[\"language\"] = html.get(\"lang\", None)\n    return metadata\n[docs]class RecursiveUrlLoader(BaseLoader):\n    \"\"\"Load all child links from a URL page.\n    **Security Note**: This loader is a crawler that will start crawling\n        at a given URL and then expand to crawl child links recursively.\n        Web crawlers should generally NOT be deployed with network access\n        to any internal servers.\n        Control access to who can submit crawling requests and what network access", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html"}
{"id": "5e0cc3c2f122-1", "text": "Control access to who can submit crawling requests and what network access\n        the crawler has.\n        While crawling, the crawler may encounter malicious URLs that would lead to a\n        server-side request forgery (SSRF) attack.\n        To mitigate risks, the crawler by default will only load URLs from the same\n        domain as the start URL (controlled via prevent_outside named argument).\n        This will mitigate the risk of SSRF attacks, but will not eliminate it.\n        For example, if crawling a host which hosts several sites:\n        https://some_host/alice_site/\n        https://some_host/bob_site/\n        A malicious URL on Alice's site could cause the crawler to make a malicious\n        GET request to an endpoint on Bob's site. Both sites are hosted on the\n        same host, so such a request would not be prevented by default.\n        See https://python.langchain.com/docs/security\n    \"\"\"\n[docs]    def __init__(\n        self,\n        url: str,\n        max_depth: Optional[int] = 2,\n        use_async: Optional[bool] = None,\n        extractor: Optional[Callable[[str], str]] = None,\n        metadata_extractor: Optional[Callable[[str, str], str]] = None,\n        exclude_dirs: Optional[Sequence[str]] = (),\n        timeout: Optional[int] = 10,\n        prevent_outside: bool = True,\n        link_regex: Union[str, re.Pattern, None] = None,\n        headers: Optional[dict] = None,\n        check_response_status: bool = False,\n    ) -> None:\n        \"\"\"Initialize with URL to crawl and any subdirectories to exclude.\n        Args:\n            url: The URL to crawl.\n            max_depth: The max depth of the recursive loading.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html"}
{"id": "5e0cc3c2f122-2", "text": "max_depth: The max depth of the recursive loading.\n            use_async: Whether to use asynchronous loading.\n                If True, this function will not be lazy, but it will still work in the\n                expected way, just not lazy.\n            extractor: A function to extract document contents from raw html.\n                When extract function returns an empty string, the document is\n                ignored.\n            metadata_extractor: A function to extract metadata from raw html and the\n                source url (args in that order). Default extractor will attempt\n                to use BeautifulSoup4 to extract the title, description and language\n                of the page.\n            exclude_dirs: A list of subdirectories to exclude.\n            timeout: The timeout for the requests, in the unit of seconds. If None then\n                connection will not timeout.\n            prevent_outside: If True, prevent loading from urls which are not children\n                of the root url.\n            link_regex: Regex for extracting sub-links from the raw html of a web page.\n            check_response_status: If True, check HTTP response status and skip\n                URLs with error responses (400-599).\n        \"\"\"\n        self.url = url\n        self.max_depth = max_depth if max_depth is not None else 2\n        self.use_async = use_async if use_async is not None else False\n        self.extractor = extractor if extractor is not None else lambda x: x\n        self.metadata_extractor = (\n            metadata_extractor\n            if metadata_extractor is not None\n            else _metadata_extractor\n        )\n        self.exclude_dirs = exclude_dirs if exclude_dirs is not None else ()\n        if any(url.startswith(exclude_dir) for exclude_dir in self.exclude_dirs):\n            raise ValueError(\n                f\"Base url is included in exclude_dirs. Received base_url: {url} and \"\n                f\"exclude_dirs: {self.exclude_dirs}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html"}
{"id": "5e0cc3c2f122-3", "text": "f\"exclude_dirs: {self.exclude_dirs}\"\n            )\n        self.timeout = timeout\n        self.prevent_outside = prevent_outside if prevent_outside is not None else True\n        self.link_regex = link_regex\n        self._lock = asyncio.Lock() if self.use_async else None\n        self.headers = headers\n        self.check_response_status = check_response_status\n    def _get_child_links_recursive(\n        self, url: str, visited: Set[str], *, depth: int = 0\n    ) -> Iterator[Document]:\n        \"\"\"Recursively get all child links starting with the path of the input URL.\n        Args:\n            url: The URL to crawl.\n            visited: A set of visited URLs.\n            depth: Current depth of recursion. Stop when depth >= max_depth.\n        \"\"\"\n        if depth >= self.max_depth:\n            return\n        # Get all links that can be accessed from the current URL\n        visited.add(url)\n        try:\n            response = requests.get(url, timeout=self.timeout, headers=self.headers)\n            if self.check_response_status and 400 <= response.status_code <= 599:\n                raise ValueError(f\"Received HTTP status {response.status_code}\")\n        except Exception as e:\n            logger.warning(\n                f\"Unable to load from {url}. Received error {e} of type \"\n                f\"{e.__class__.__name__}\"\n            )\n            return\n        content = self.extractor(response.text)\n        if content:\n            yield Document(\n                page_content=content,\n                metadata=self.metadata_extractor(response.text, url),\n            )\n        # Store the visited links and recursively visit the children\n        sub_links = extract_sub_links(\n            response.text,\n            url,\n            base_url=self.url,\n            pattern=self.link_regex,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html"}
{"id": "5e0cc3c2f122-4", "text": "url,\n            base_url=self.url,\n            pattern=self.link_regex,\n            prevent_outside=self.prevent_outside,\n            exclude_prefixes=self.exclude_dirs,\n        )\n        for link in sub_links:\n            # Check all unvisited links\n            if link not in visited:\n                yield from self._get_child_links_recursive(\n                    link, visited, depth=depth + 1\n                )\n    async def _async_get_child_links_recursive(\n        self,\n        url: str,\n        visited: Set[str],\n        *,\n        session: Optional[aiohttp.ClientSession] = None,\n        depth: int = 0,\n    ) -> List[Document]:\n        \"\"\"Recursively get all child links starting with the path of the input URL.\n        Args:\n            url: The URL to crawl.\n            visited: A set of visited URLs.\n            depth: To reach the current url, how many pages have been visited.\n        \"\"\"\n        try:\n            import aiohttp\n        except ImportError:\n            raise ImportError(\n                \"The aiohttp package is required for the RecursiveUrlLoader. \"\n                \"Please install it with `pip install aiohttp`.\"\n            )\n        if depth >= self.max_depth:\n            return []\n        # Disable SSL verification because websites may have invalid SSL certificates,\n        # but won't cause any security issues for us.\n        close_session = session is None\n        session = (\n            session\n            if session is not None\n            else aiohttp.ClientSession(\n                connector=aiohttp.TCPConnector(ssl=False),\n                timeout=aiohttp.ClientTimeout(total=self.timeout),\n                headers=self.headers,\n            )\n        )\n        async with self._lock:  # type: ignore\n            visited.add(url)\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html"}
{"id": "5e0cc3c2f122-5", "text": "visited.add(url)\n        try:\n            async with session.get(url) as response:\n                text = await response.text()\n                if self.check_response_status and 400 <= response.status <= 599:\n                    raise ValueError(f\"Received HTTP status {response.status}\")\n        except (aiohttp.client_exceptions.InvalidURL, Exception) as e:\n            logger.warning(\n                f\"Unable to load {url}. Received error {e} of type \"\n                f\"{e.__class__.__name__}\"\n            )\n            if close_session:\n                await session.close()\n            return []\n        results = []\n        content = self.extractor(text)\n        if content:\n            results.append(\n                Document(\n                    page_content=content,\n                    metadata=self.metadata_extractor(text, url),\n                )\n            )\n        if depth < self.max_depth - 1:\n            sub_links = extract_sub_links(\n                text,\n                url,\n                base_url=self.url,\n                pattern=self.link_regex,\n                prevent_outside=self.prevent_outside,\n                exclude_prefixes=self.exclude_dirs,\n            )\n            # Recursively call the function to get the children of the children\n            sub_tasks = []\n            async with self._lock:  # type: ignore\n                to_visit = set(sub_links).difference(visited)\n                for link in to_visit:\n                    sub_tasks.append(\n                        self._async_get_child_links_recursive(\n                            link, visited, session=session, depth=depth + 1\n                        )\n                    )\n            next_results = await asyncio.gather(*sub_tasks)\n            for sub_result in next_results:\n                if isinstance(sub_result, Exception) or sub_result is None:\n                    # We don't want to stop the whole process, so just ignore it", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html"}
{"id": "5e0cc3c2f122-6", "text": "# We don't want to stop the whole process, so just ignore it\n                    # Not standard html format or invalid url or 404 may cause this.\n                    continue\n                # locking not fully working, temporary hack to ensure deduplication\n                results += [r for r in sub_result if r not in results]\n        if close_session:\n            await session.close()\n        return results\n[docs]    def lazy_load(self) -> Iterator[Document]:\n        \"\"\"Lazy load web pages.\n        When use_async is True, this function will not be lazy,\n        but it will still work in the expected way, just not lazy.\"\"\"\n        visited: Set[str] = set()\n        if self.use_async:\n            results = asyncio.run(\n                self._async_get_child_links_recursive(self.url, visited)\n            )\n            return iter(results or [])\n        else:\n            return self._get_child_links_recursive(self.url, visited)\n[docs]    def load(self) -> List[Document]:\n        \"\"\"Load web pages.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html"}
{"id": "136556e804c1-0", "text": "Source code for langchain.document_loaders.modern_treasury\nimport json\nimport urllib.request\nfrom base64 import b64encode\nfrom typing import List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.utils import get_from_env, stringify_value\nMODERN_TREASURY_ENDPOINTS = {\n    \"payment_orders\": \"https://app.moderntreasury.com/api/payment_orders\",\n    \"expected_payments\": \"https://app.moderntreasury.com/api/expected_payments\",\n    \"returns\": \"https://app.moderntreasury.com/api/returns\",\n    \"incoming_payment_details\": \"https://app.moderntreasury.com/api/\\\nincoming_payment_details\",\n    \"counterparties\": \"https://app.moderntreasury.com/api/counterparties\",\n    \"internal_accounts\": \"https://app.moderntreasury.com/api/internal_accounts\",\n    \"external_accounts\": \"https://app.moderntreasury.com/api/external_accounts\",\n    \"transactions\": \"https://app.moderntreasury.com/api/transactions\",\n    \"ledgers\": \"https://app.moderntreasury.com/api/ledgers\",\n    \"ledger_accounts\": \"https://app.moderntreasury.com/api/ledger_accounts\",\n    \"ledger_transactions\": \"https://app.moderntreasury.com/api/ledger_transactions\",\n    \"events\": \"https://app.moderntreasury.com/api/events\",\n    \"invoices\": \"https://app.moderntreasury.com/api/invoices\",\n}\n[docs]class ModernTreasuryLoader(BaseLoader):\n    \"\"\"Load from `Modern Treasury`.\"\"\"\n[docs]    def __init__(\n        self,\n        resource: str,\n        organization_id: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/modern_treasury.html"}
{"id": "136556e804c1-1", "text": "resource: str,\n        organization_id: Optional[str] = None,\n        api_key: Optional[str] = None,\n    ) -> None:\n        \"\"\"\n        Args:\n            resource: The Modern Treasury resource to load.\n            organization_id: The Modern Treasury organization ID. It can also be\n               specified via the environment variable\n               \"MODERN_TREASURY_ORGANIZATION_ID\".\n            api_key: The Modern Treasury API key. It can also be specified via\n               the environment variable \"MODERN_TREASURY_API_KEY\".\n        \"\"\"\n        self.resource = resource\n        organization_id = organization_id or get_from_env(\n            \"organization_id\", \"MODERN_TREASURY_ORGANIZATION_ID\"\n        )\n        api_key = api_key or get_from_env(\"api_key\", \"MODERN_TREASURY_API_KEY\")\n        credentials = f\"{organization_id}:{api_key}\".encode(\"utf-8\")\n        basic_auth_token = b64encode(credentials).decode(\"utf-8\")\n        self.headers = {\"Authorization\": f\"Basic {basic_auth_token}\"}\n    def _make_request(self, url: str) -> List[Document]:\n        request = urllib.request.Request(url, headers=self.headers)\n        with urllib.request.urlopen(request) as response:\n            json_data = json.loads(response.read().decode())\n            text = stringify_value(json_data)\n            metadata = {\"source\": url}\n            return [Document(page_content=text, metadata=metadata)]\n    def _get_resource(self) -> List[Document]:\n        endpoint = MODERN_TREASURY_ENDPOINTS.get(self.resource)\n        if endpoint is None:\n            return []\n        return self._make_request(endpoint)\n[docs]    def load(self) -> List[Document]:\n        return self._get_resource()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/modern_treasury.html"}
{"id": "e0c5b8799757-0", "text": "Source code for langchain.document_loaders.blob_loaders.schema\n\"\"\"Schema for Blobs and Blob Loaders.\nThe goal is to facilitate decoupling of content loading from content parsing code.\nIn addition, content loading code should provide a lazy loading interface by default.\n\"\"\"\nfrom __future__ import annotations\nimport contextlib\nimport mimetypes\nfrom abc import ABC, abstractmethod\nfrom io import BufferedReader, BytesIO\nfrom pathlib import PurePath\nfrom typing import Any, Generator, Iterable, Mapping, Optional, Union\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nPathLike = Union[str, PurePath]\n[docs]class Blob(BaseModel):\n    \"\"\"Blob represents raw data by either reference or value.\n    Provides an interface to materialize the blob in different representations, and\n    help to decouple the development of data loaders from the downstream parsing of\n    the raw data.\n    Inspired by: https://developer.mozilla.org/en-US/docs/Web/API/Blob\n    \"\"\"\n    data: Union[bytes, str, None]  # Raw data\n    mimetype: Optional[str] = None  # Not to be confused with a file extension\n    encoding: str = \"utf-8\"  # Use utf-8 as default encoding, if decoding to string\n    # Location where the original content was found\n    # Represent location on the local file system\n    # Useful for situations where downstream code assumes it must work with file paths\n    # rather than in-memory content.\n    path: Optional[PathLike] = None\n    class Config:\n        arbitrary_types_allowed = True\n        frozen = True\n    @property\n    def source(self) -> Optional[str]:\n        \"\"\"The source location of the blob as string if known otherwise none.\"\"\"\n        return str(self.path) if self.path else None\n    @root_validator(pre=True)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html"}
{"id": "e0c5b8799757-1", "text": "return str(self.path) if self.path else None\n    @root_validator(pre=True)\n    def check_blob_is_valid(cls, values: Mapping[str, Any]) -> Mapping[str, Any]:\n        \"\"\"Verify that either data or path is provided.\"\"\"\n        if \"data\" not in values and \"path\" not in values:\n            raise ValueError(\"Either data or path must be provided\")\n        return values\n[docs]    def as_string(self) -> str:\n        \"\"\"Read data as a string.\"\"\"\n        if self.data is None and self.path:\n            with open(str(self.path), \"r\", encoding=self.encoding) as f:\n                return f.read()\n        elif isinstance(self.data, bytes):\n            return self.data.decode(self.encoding)\n        elif isinstance(self.data, str):\n            return self.data\n        else:\n            raise ValueError(f\"Unable to get string for blob {self}\")\n[docs]    def as_bytes(self) -> bytes:\n        \"\"\"Read data as bytes.\"\"\"\n        if isinstance(self.data, bytes):\n            return self.data\n        elif isinstance(self.data, str):\n            return self.data.encode(self.encoding)\n        elif self.data is None and self.path:\n            with open(str(self.path), \"rb\") as f:\n                return f.read()\n        else:\n            raise ValueError(f\"Unable to get bytes for blob {self}\")\n[docs]    @contextlib.contextmanager\n    def as_bytes_io(self) -> Generator[Union[BytesIO, BufferedReader], None, None]:\n        \"\"\"Read data as a byte stream.\"\"\"\n        if isinstance(self.data, bytes):\n            yield BytesIO(self.data)\n        elif self.data is None and self.path:\n            with open(str(self.path), \"rb\") as f:\n                yield f\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html"}
{"id": "e0c5b8799757-2", "text": "yield f\n        else:\n            raise NotImplementedError(f\"Unable to convert blob {self}\")\n[docs]    @classmethod\n    def from_path(\n        cls,\n        path: PathLike,\n        *,\n        encoding: str = \"utf-8\",\n        mime_type: Optional[str] = None,\n        guess_type: bool = True,\n    ) -> Blob:\n        \"\"\"Load the blob from a path like object.\n        Args:\n            path: path like object to file to be read\n            encoding: Encoding to use if decoding the bytes into a string\n            mime_type: if provided, will be set as the mime-type of the data\n            guess_type: If True, the mimetype will be guessed from the file extension,\n                        if a mime-type was not provided\n        Returns:\n            Blob instance\n        \"\"\"\n        if mime_type is None and guess_type:\n            _mimetype = mimetypes.guess_type(path)[0] if guess_type else None\n        else:\n            _mimetype = mime_type\n        # We do not load the data immediately, instead we treat the blob as a\n        # reference to the underlying data.\n        return cls(data=None, mimetype=_mimetype, encoding=encoding, path=path)\n[docs]    @classmethod\n    def from_data(\n        cls,\n        data: Union[str, bytes],\n        *,\n        encoding: str = \"utf-8\",\n        mime_type: Optional[str] = None,\n        path: Optional[str] = None,\n    ) -> Blob:\n        \"\"\"Initialize the blob from in-memory data.\n        Args:\n            data: the in-memory data associated with the blob\n            encoding: Encoding to use if decoding the bytes into a string\n            mime_type: if provided, will be set as the mime-type of the data", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html"}
{"id": "e0c5b8799757-3", "text": "mime_type: if provided, will be set as the mime-type of the data\n            path: if provided, will be set as the source from which the data came\n        Returns:\n            Blob instance\n        \"\"\"\n        return cls(data=data, mimetype=mime_type, encoding=encoding, path=path)\n    def __repr__(self) -> str:\n        \"\"\"Define the blob representation.\"\"\"\n        str_repr = f\"Blob {id(self)}\"\n        if self.source:\n            str_repr += f\" {self.source}\"\n        return str_repr\n[docs]class BlobLoader(ABC):\n    \"\"\"Abstract interface for blob loaders implementation.\n    Implementer should be able to load raw content from a storage system according\n    to some criteria and return the raw content lazily as a stream of blobs.\n    \"\"\"\n[docs]    @abstractmethod\n    def yield_blobs(\n        self,\n    ) -> Iterable[Blob]:\n        \"\"\"A lazy loader for raw data represented by LangChain's Blob object.\n        Returns:\n            A generator over blobs\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html"}
{"id": "39ae4090a20a-0", "text": "Source code for langchain.document_loaders.blob_loaders.file_system\n\"\"\"Use to load blobs from the local file system.\"\"\"\nfrom pathlib import Path\nfrom typing import Callable, Iterable, Iterator, Optional, Sequence, TypeVar, Union\nfrom langchain.document_loaders.blob_loaders.schema import Blob, BlobLoader\nT = TypeVar(\"T\")\ndef _make_iterator(\n    length_func: Callable[[], int], show_progress: bool = False\n) -> Callable[[Iterable[T]], Iterator[T]]:\n    \"\"\"Create a function that optionally wraps an iterable in tqdm.\"\"\"\n    if show_progress:\n        try:\n            from tqdm.auto import tqdm\n        except ImportError:\n            raise ImportError(\n                \"You must install tqdm to use show_progress=True.\"\n                \"You can install tqdm with `pip install tqdm`.\"\n            )\n        # Make sure to provide `total` here so that tqdm can show\n        # a progress bar that takes into account the total number of files.\n        def _with_tqdm(iterable: Iterable[T]) -> Iterator[T]:\n            \"\"\"Wrap an iterable in a tqdm progress bar.\"\"\"\n            return tqdm(iterable, total=length_func())\n        iterator = _with_tqdm\n    else:\n        iterator = iter  # type: ignore\n    return iterator\n# PUBLIC API\n[docs]class FileSystemBlobLoader(BlobLoader):\n    \"\"\"Load blobs in the local file system.\n    Example:\n    .. code-block:: python\n        from langchain.document_loaders.blob_loaders import FileSystemBlobLoader\n        loader = FileSystemBlobLoader(\"/path/to/directory\")\n        for blob in loader.yield_blobs():\n            print(blob)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        path: Union[str, Path],\n        *,\n        glob: str = \"**/[!.]*\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html"}
{"id": "39ae4090a20a-1", "text": "*,\n        glob: str = \"**/[!.]*\",\n        exclude: Sequence[str] = (),\n        suffixes: Optional[Sequence[str]] = None,\n        show_progress: bool = False,\n    ) -> None:\n        \"\"\"Initialize with a path to directory and how to glob over it.\n        Args:\n            path: Path to directory to load from\n            glob: Glob pattern relative to the specified path\n                  by default set to pick up all non-hidden files\n            exclude: patterns to exclude from results, use glob syntax\n            suffixes: Provide to keep only files with these suffixes\n                      Useful when wanting to keep files with different suffixes\n                      Suffixes must include the dot, e.g. \".txt\"\n            show_progress: If true, will show a progress bar as the files are loaded.\n                           This forces an iteration through all matching files\n                           to count them prior to loading them.\n        Examples:\n            .. code-block:: python\n                # Recursively load all text files in a directory.\n                loader = FileSystemBlobLoader(\"/path/to/directory\", glob=\"**/*.txt\")\n                # Recursively load all non-hidden files in a directory.\n                loader = FileSystemBlobLoader(\"/path/to/directory\", glob=\"**/[!.]*\")\n                # Load all files in a directory without recursion.\n                loader = FileSystemBlobLoader(\"/path/to/directory\", glob=\"*\")\n                # Recursively load all files in a directory, except for py or pyc files.\n                loader = FileSystemBlobLoader(\n                    \"/path/to/directory\",\n                    glob=\"**/*.txt\",\n                    exclude=[\"**/*.py\", \"**/*.pyc\"]\n                )\n        \"\"\"\n        if isinstance(path, Path):\n            _path = path\n        elif isinstance(path, str):\n            _path = Path(path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html"}
{"id": "39ae4090a20a-2", "text": "elif isinstance(path, str):\n            _path = Path(path)\n        else:\n            raise TypeError(f\"Expected str or Path, got {type(path)}\")\n        self.path = _path.expanduser()  # Expand user to handle ~\n        self.glob = glob\n        self.suffixes = set(suffixes or [])\n        self.show_progress = show_progress\n        self.exclude = exclude\n[docs]    def yield_blobs(\n        self,\n    ) -> Iterable[Blob]:\n        \"\"\"Yield blobs that match the requested pattern.\"\"\"\n        iterator = _make_iterator(\n            length_func=self.count_matching_files, show_progress=self.show_progress\n        )\n        for path in iterator(self._yield_paths()):\n            yield Blob.from_path(path)\n    def _yield_paths(self) -> Iterable[Path]:\n        \"\"\"Yield paths that match the requested pattern.\"\"\"\n        paths = self.path.glob(self.glob)\n        for path in paths:\n            if self.exclude:\n                if any(path.match(glob) for glob in self.exclude):\n                    continue\n            if path.is_file():\n                if self.suffixes and path.suffix not in self.suffixes:\n                    continue\n                yield path\n[docs]    def count_matching_files(self) -> int:\n        \"\"\"Count files that match the pattern without loading them.\"\"\"\n        # Carry out a full iteration to count the files without\n        # materializing anything expensive in memory.\n        num = 0\n        for _ in self._yield_paths():\n            num += 1\n        return num", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html"}
{"id": "3989c6dccfee-0", "text": "Source code for langchain.document_loaders.blob_loaders.youtube_audio\nfrom typing import Iterable, List\nfrom langchain.document_loaders.blob_loaders import FileSystemBlobLoader\nfrom langchain.document_loaders.blob_loaders.schema import Blob, BlobLoader\n[docs]class YoutubeAudioLoader(BlobLoader):\n    \"\"\"Load YouTube urls as audio file(s).\"\"\"\n[docs]    def __init__(self, urls: List[str], save_dir: str):\n        if not isinstance(urls, list):\n            raise TypeError(\"urls must be a list\")\n        self.urls = urls\n        self.save_dir = save_dir\n[docs]    def yield_blobs(self) -> Iterable[Blob]:\n        \"\"\"Yield audio blobs for each url.\"\"\"\n        try:\n            import yt_dlp\n        except ImportError:\n            raise ImportError(\n                \"yt_dlp package not found, please install it with \"\n                \"`pip install yt_dlp`\"\n            )\n        # Use yt_dlp to download audio given a YouTube url\n        ydl_opts = {\n            \"format\": \"m4a/bestaudio/best\",\n            \"noplaylist\": True,\n            \"outtmpl\": self.save_dir + \"/%(title)s.%(ext)s\",\n            \"postprocessors\": [\n                {\n                    \"key\": \"FFmpegExtractAudio\",\n                    \"preferredcodec\": \"m4a\",\n                }\n            ],\n        }\n        for url in self.urls:\n            # Download file\n            with yt_dlp.YoutubeDL(ydl_opts) as ydl:\n                ydl.download(url)\n        # Yield the written blobs\n        loader = FileSystemBlobLoader(self.save_dir, glob=\"*.m4a\")\n        for blob in loader.yield_blobs():\n            yield blob", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/youtube_audio.html"}
{"id": "f7255c39df3d-0", "text": "Source code for langchain.document_loaders.parsers.msword\nfrom typing import Iterator\nfrom langchain.document_loaders.base import BaseBlobParser\nfrom langchain.document_loaders.blob_loaders import Blob\nfrom langchain.schema import Document\n[docs]class MsWordParser(BaseBlobParser):\n    \"\"\"Parse the Microsoft Word documents from a blob.\"\"\"\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Parse a Microsoft Word document into the Document iterator.\n        Args:\n            blob: The blob to parse.\n        Returns: An iterator of Documents.\n        \"\"\"\n        try:\n            from unstructured.partition.doc import partition_doc\n            from unstructured.partition.docx import partition_docx\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import unstructured, please install with `pip install \"\n                \"unstructured`.\"\n            ) from e\n        mime_type_parser = {\n            \"application/msword\": partition_doc,\n            \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\": (\n                partition_docx\n            ),\n        }\n        if blob.mimetype not in (\n            \"application/msword\",\n            \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n        ):\n            raise ValueError(\"This blob type is not supported for this parser.\")\n        with blob.as_bytes_io() as word_document:\n            elements = mime_type_parser[blob.mimetype](file=word_document)\n            text = \"\\n\\n\".join([str(el) for el in elements])\n            metadata = {\"source\": blob.source}\n            yield Document(page_content=text, metadata=metadata)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/msword.html"}
{"id": "44b317e6acee-0", "text": "Source code for langchain.document_loaders.parsers.txt\n\"\"\"Module for parsing text files..\"\"\"\nfrom typing import Iterator\nfrom langchain.document_loaders.base import BaseBlobParser\nfrom langchain.document_loaders.blob_loaders import Blob\nfrom langchain.schema import Document\n[docs]class TextParser(BaseBlobParser):\n    \"\"\"Parser for text blobs.\"\"\"\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Lazily parse the blob.\"\"\"\n        yield Document(page_content=blob.as_string(), metadata={\"source\": blob.source})", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/txt.html"}
{"id": "78df72f7297f-0", "text": "Source code for langchain.document_loaders.parsers.pdf\n\"\"\"Module contains common parsers for PDFs.\"\"\"\nfrom __future__ import annotations\nimport warnings\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Iterable,\n    Iterator,\n    Mapping,\n    Optional,\n    Sequence,\n    Union,\n)\nfrom urllib.parse import urlparse\nimport numpy as np\nfrom langchain.document_loaders.base import BaseBlobParser\nfrom langchain.document_loaders.blob_loaders import Blob\nfrom langchain.schema import Document\nif TYPE_CHECKING:\n    import fitz.fitz\n    import pdfminer.layout\n    import pdfplumber.page\n    import pypdf._page\n    import pypdfium2._helpers.page\n_PDF_FILTER_WITH_LOSS = [\"DCTDecode\", \"DCT\", \"JPXDecode\"]\n_PDF_FILTER_WITHOUT_LOSS = [\n    \"LZWDecode\",\n    \"LZW\",\n    \"FlateDecode\",\n    \"Fl\",\n    \"ASCII85Decode\",\n    \"A85\",\n    \"ASCIIHexDecode\",\n    \"AHx\",\n    \"RunLengthDecode\",\n    \"RL\",\n    \"CCITTFaxDecode\",\n    \"CCF\",\n    \"JBIG2Decode\",\n]\n[docs]def extract_from_images_with_rapidocr(\n    images: Sequence[Union[Iterable[np.ndarray], bytes]]\n) -> str:\n    \"\"\"Extract text from images with RapidOCR.\n    Args:\n        images: Images to extract text from.\n    Returns:\n        Text extracted from images.\n    Raises:\n        ImportError: If `rapidocr-onnxruntime` package is not installed.\n    \"\"\"\n    try:\n        from rapidocr_onnxruntime import RapidOCR\n    except ImportError:\n        raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html"}
{"id": "78df72f7297f-1", "text": "except ImportError:\n        raise ImportError(\n            \"`rapidocr-onnxruntime` package not found, please install it with \"\n            \"`pip install rapidocr-onnxruntime`\"\n        )\n    ocr = RapidOCR()\n    text = \"\"\n    for img in images:\n        result, _ = ocr(img)\n        if result:\n            result = [text[1] for text in result]\n            text += \"\\n\".join(result)\n    return text\n[docs]class PyPDFParser(BaseBlobParser):\n    \"\"\"Load `PDF` using `pypdf`\"\"\"\n[docs]    def __init__(\n        self, password: Optional[Union[str, bytes]] = None, extract_images: bool = False\n    ):\n        self.password = password\n        self.extract_images = extract_images\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Lazily parse the blob.\"\"\"\n        import pypdf\n        with blob.as_bytes_io() as pdf_file_obj:\n            pdf_reader = pypdf.PdfReader(pdf_file_obj, password=self.password)\n            yield from [\n                Document(\n                    page_content=page.extract_text()\n                    + self._extract_images_from_page(page),\n                    metadata={\"source\": blob.source, \"page\": page_number},\n                )\n                for page_number, page in enumerate(pdf_reader.pages)\n            ]\n    def _extract_images_from_page(self, page: pypdf._page.PageObject) -> str:\n        \"\"\"Extract images from page and get the text with RapidOCR.\"\"\"\n        if not self.extract_images or \"/XObject\" not in page[\"/Resources\"].keys():\n            return \"\"\n        xObject = page[\"/Resources\"][\"/XObject\"].get_object()  # type: ignore\n        images = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html"}
{"id": "78df72f7297f-2", "text": "images = []\n        for obj in xObject:\n            if xObject[obj][\"/Subtype\"] == \"/Image\":\n                if xObject[obj][\"/Filter\"][1:] in _PDF_FILTER_WITHOUT_LOSS:\n                    height, width = xObject[obj][\"/Height\"], xObject[obj][\"/Width\"]\n                    images.append(\n                        np.frombuffer(xObject[obj].get_data(), dtype=np.uint8).reshape(\n                            height, width, -1\n                        )\n                    )\n                elif xObject[obj][\"/Filter\"][1:] in _PDF_FILTER_WITH_LOSS:\n                    images.append(xObject[obj].get_data())\n                else:\n                    warnings.warn(\"Unknown PDF Filter!\")\n        return extract_from_images_with_rapidocr(images)\n[docs]class PDFMinerParser(BaseBlobParser):\n    \"\"\"Parse `PDF` using `PDFMiner`.\"\"\"\n[docs]    def __init__(self, extract_images: bool = False, *, concatenate_pages: bool = True):\n        \"\"\"Initialize a parser based on PDFMiner.\n        Args:\n            extract_images: Whether to extract images from PDF.\n            concatenate_pages: If True, concatenate all PDF pages into one a single\n                               document. Otherwise, return one document per page.\n        \"\"\"\n        self.extract_images = extract_images\n        self.concatenate_pages = concatenate_pages\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Lazily parse the blob.\"\"\"\n        if not self.extract_images:\n            from pdfminer.high_level import extract_text\n            with blob.as_bytes_io() as pdf_file_obj:\n                if self.concatenate_pages:\n                    text = extract_text(pdf_file_obj)\n                    metadata = {\"source\": blob.source}\n                    yield Document(page_content=text, metadata=metadata)\n                else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html"}
{"id": "78df72f7297f-3", "text": "yield Document(page_content=text, metadata=metadata)\n                else:\n                    from pdfminer.pdfpage import PDFPage\n                    pages = PDFPage.get_pages(pdf_file_obj)\n                    for i, _ in enumerate(pages):\n                        text = extract_text(pdf_file_obj, page_numbers=[i])\n                        metadata = {\"source\": blob.source, \"page\": str(i)}\n                        yield Document(page_content=text, metadata=metadata)\n        else:\n            import io\n            from pdfminer.converter import PDFPageAggregator, TextConverter\n            from pdfminer.layout import LAParams\n            from pdfminer.pdfinterp import PDFPageInterpreter, PDFResourceManager\n            from pdfminer.pdfpage import PDFPage\n            text_io = io.StringIO()\n            with blob.as_bytes_io() as pdf_file_obj:\n                pages = PDFPage.get_pages(pdf_file_obj)\n                rsrcmgr = PDFResourceManager()\n                device_for_text = TextConverter(rsrcmgr, text_io, laparams=LAParams())\n                device_for_image = PDFPageAggregator(rsrcmgr, laparams=LAParams())\n                interpreter_for_text = PDFPageInterpreter(rsrcmgr, device_for_text)\n                interpreter_for_image = PDFPageInterpreter(rsrcmgr, device_for_image)\n                for i, page in enumerate(pages):\n                    interpreter_for_text.process_page(page)\n                    interpreter_for_image.process_page(page)\n                    content = text_io.getvalue() + self._extract_images_from_page(\n                        device_for_image.get_result()\n                    )\n                    text_io.truncate(0)\n                    text_io.seek(0)\n                    metadata = {\"source\": blob.source, \"page\": str(i)}\n                    yield Document(page_content=content, metadata=metadata)\n    def _extract_images_from_page(self, page: pdfminer.layout.LTPage) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html"}
{"id": "78df72f7297f-4", "text": "\"\"\"Extract images from page and get the text with RapidOCR.\"\"\"\n        import pdfminer\n        def get_image(layout_object: Any) -> Any:\n            if isinstance(layout_object, pdfminer.layout.LTImage):\n                return layout_object\n            if isinstance(layout_object, pdfminer.layout.LTContainer):\n                for child in layout_object:\n                    return get_image(child)\n            else:\n                return None\n        images = []\n        for img in list(filter(bool, map(get_image, page))):\n            if img.stream[\"Filter\"].name in _PDF_FILTER_WITHOUT_LOSS:\n                images.append(\n                    np.frombuffer(img.stream.get_data(), dtype=np.uint8).reshape(\n                        img.stream[\"Height\"], img.stream[\"Width\"], -1\n                    )\n                )\n            elif img.stream[\"Filter\"].name in _PDF_FILTER_WITH_LOSS:\n                images.append(img.stream.get_data())\n            else:\n                warnings.warn(\"Unknown PDF Filter!\")\n        return extract_from_images_with_rapidocr(images)\n[docs]class PyMuPDFParser(BaseBlobParser):\n    \"\"\"Parse `PDF` using `PyMuPDF`.\"\"\"\n[docs]    def __init__(\n        self,\n        text_kwargs: Optional[Mapping[str, Any]] = None,\n        extract_images: bool = False,\n    ) -> None:\n        \"\"\"Initialize the parser.\n        Args:\n            text_kwargs: Keyword arguments to pass to ``fitz.Page.get_text()``.\n        \"\"\"\n        self.text_kwargs = text_kwargs or {}\n        self.extract_images = extract_images\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Lazily parse the blob.\"\"\"\n        import fitz\n        with blob.as_bytes_io() as file_path:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html"}
{"id": "78df72f7297f-5", "text": "import fitz\n        with blob.as_bytes_io() as file_path:\n            doc = fitz.open(file_path)  # open document\n            yield from [\n                Document(\n                    page_content=page.get_text(**self.text_kwargs)\n                    + self._extract_images_from_page(doc, page),\n                    metadata=dict(\n                        {\n                            \"source\": blob.source,\n                            \"file_path\": blob.source,\n                            \"page\": page.number,\n                            \"total_pages\": len(doc),\n                        },\n                        **{\n                            k: doc.metadata[k]\n                            for k in doc.metadata\n                            if type(doc.metadata[k]) in [str, int]\n                        },\n                    ),\n                )\n                for page in doc\n            ]\n    def _extract_images_from_page(\n        self, doc: fitz.fitz.Document, page: fitz.fitz.Page\n    ) -> str:\n        \"\"\"Extract images from page and get the text with RapidOCR.\"\"\"\n        if not self.extract_images:\n            return \"\"\n        import fitz\n        img_list = page.get_images()\n        imgs = []\n        for img in img_list:\n            xref = img[0]\n            pix = fitz.Pixmap(doc, xref)\n            imgs.append(\n                np.frombuffer(pix.samples, dtype=np.uint8).reshape(\n                    pix.height, pix.width, -1\n                )\n            )\n        return extract_from_images_with_rapidocr(imgs)\n[docs]class PyPDFium2Parser(BaseBlobParser):\n    \"\"\"Parse `PDF` with `PyPDFium2`.\"\"\"\n[docs]    def __init__(self, extract_images: bool = False) -> None:\n        \"\"\"Initialize the parser.\"\"\"\n        try:\n            import pypdfium2  # noqa:F401", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html"}
{"id": "78df72f7297f-6", "text": "try:\n            import pypdfium2  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"pypdfium2 package not found, please install it with\"\n                \" `pip install pypdfium2`\"\n            )\n        self.extract_images = extract_images\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Lazily parse the blob.\"\"\"\n        import pypdfium2\n        # pypdfium2 is really finicky with respect to closing things,\n        # if done incorrectly creates seg faults.\n        with blob.as_bytes_io() as file_path:\n            pdf_reader = pypdfium2.PdfDocument(file_path, autoclose=True)\n            try:\n                for page_number, page in enumerate(pdf_reader):\n                    text_page = page.get_textpage()\n                    content = text_page.get_text_range()\n                    text_page.close()\n                    content += \"\\n\" + self._extract_images_from_page(page)\n                    page.close()\n                    metadata = {\"source\": blob.source, \"page\": page_number}\n                    yield Document(page_content=content, metadata=metadata)\n            finally:\n                pdf_reader.close()\n    def _extract_images_from_page(self, page: pypdfium2._helpers.page.PdfPage) -> str:\n        \"\"\"Extract images from page and get the text with RapidOCR.\"\"\"\n        if not self.extract_images:\n            return \"\"\n        import pypdfium2.raw as pdfium_c\n        images = list(page.get_objects(filter=(pdfium_c.FPDF_PAGEOBJ_IMAGE,)))\n        images = list(map(lambda x: x.get_bitmap().to_numpy(), images))\n        return extract_from_images_with_rapidocr(images)\n[docs]class PDFPlumberParser(BaseBlobParser):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html"}
{"id": "78df72f7297f-7", "text": "[docs]class PDFPlumberParser(BaseBlobParser):\n    \"\"\"Parse `PDF` with `PDFPlumber`.\"\"\"\n[docs]    def __init__(\n        self,\n        text_kwargs: Optional[Mapping[str, Any]] = None,\n        dedupe: bool = False,\n        extract_images: bool = False,\n    ) -> None:\n        \"\"\"Initialize the parser.\n        Args:\n            text_kwargs: Keyword arguments to pass to ``pdfplumber.Page.extract_text()``\n            dedupe: Avoiding the error of duplicate characters if `dedupe=True`.\n        \"\"\"\n        self.text_kwargs = text_kwargs or {}\n        self.dedupe = dedupe\n        self.extract_images = extract_images\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Lazily parse the blob.\"\"\"\n        import pdfplumber\n        with blob.as_bytes_io() as file_path:\n            doc = pdfplumber.open(file_path)  # open document\n            yield from [\n                Document(\n                    page_content=self._process_page_content(page)\n                    + \"\\n\"\n                    + self._extract_images_from_page(page),\n                    metadata=dict(\n                        {\n                            \"source\": blob.source,\n                            \"file_path\": blob.source,\n                            \"page\": page.page_number - 1,\n                            \"total_pages\": len(doc.pages),\n                        },\n                        **{\n                            k: doc.metadata[k]\n                            for k in doc.metadata\n                            if type(doc.metadata[k]) in [str, int]\n                        },\n                    ),\n                )\n                for page in doc.pages\n            ]\n    def _process_page_content(self, page: pdfplumber.page.Page) -> str:\n        \"\"\"Process the page content based on dedupe.\"\"\"\n        if self.dedupe:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html"}
{"id": "78df72f7297f-8", "text": "\"\"\"Process the page content based on dedupe.\"\"\"\n        if self.dedupe:\n            return page.dedupe_chars().extract_text(**self.text_kwargs)\n        return page.extract_text(**self.text_kwargs)\n    def _extract_images_from_page(self, page: pdfplumber.page.Page) -> str:\n        \"\"\"Extract images from page and get the text with RapidOCR.\"\"\"\n        if not self.extract_images:\n            return \"\"\n        images = []\n        for img in page.images:\n            if img[\"stream\"][\"Filter\"].name in _PDF_FILTER_WITHOUT_LOSS:\n                images.append(\n                    np.frombuffer(img[\"stream\"].get_data(), dtype=np.uint8).reshape(\n                        img[\"stream\"][\"Height\"], img[\"stream\"][\"Width\"], -1\n                    )\n                )\n            elif img[\"stream\"][\"Filter\"].name in _PDF_FILTER_WITH_LOSS:\n                images.append(img[\"stream\"].get_data())\n            else:\n                warnings.warn(\"Unknown PDF Filter!\")\n        return extract_from_images_with_rapidocr(images)\n[docs]class AmazonTextractPDFParser(BaseBlobParser):\n    \"\"\"Send `PDF` files to `Amazon Textract` and parse them.\n    For parsing multi-page PDFs, they have to reside on S3.\n    The AmazonTextractPDFLoader calls the\n    [Amazon Textract Service](https://aws.amazon.com/textract/)\n    to convert PDFs into a Document structure.\n    Single and multi-page documents are supported with up to 3000 pages\n    and 512 MB of size.\n    For the call to be successful an AWS account is required,\n    similar to the\n    [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)\n    requirements.\n    Besides the AWS configuration, it is very similar to the other PDF", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html"}
{"id": "78df72f7297f-9", "text": "requirements.\n    Besides the AWS configuration, it is very similar to the other PDF\n    loaders, while also supporting JPEG, PNG and TIFF and non-native\n    PDF formats.\n    ```python\n    from langchain.document_loaders import AmazonTextractPDFLoader\n    loader=AmazonTextractPDFLoader(\"example_data/alejandro_rosalez_sample-small.jpeg\")\n    documents = loader.load()\n    ```\n    One feature is the linearization of the output.\n    When using the features LAYOUT, FORMS or TABLES together with Textract\n    ```python\n    from langchain.document_loaders import AmazonTextractPDFLoader\n    # you can mix and match each of the features\n    loader=AmazonTextractPDFLoader(\n        \"example_data/alejandro_rosalez_sample-small.jpeg\",\n        textract_features=[\"TABLES\", \"LAYOUT\"])\n    documents = loader.load()\n    ```\n    it will generate output that formats the text in reading order and\n    try to output the information in a tabular structure or\n    output the key/value pairs with a colon (key: value).\n    This helps most LLMs to achieve better accuracy when\n    processing these texts.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        textract_features: Optional[Sequence[int]] = None,\n        client: Optional[Any] = None,\n    ) -> None:\n        \"\"\"Initializes the parser.\n        Args:\n            textract_features: Features to be used for extraction, each feature\n                               should be passed as an int that conforms to the enum\n                               `Textract_Features`, see `amazon-textract-caller` pkg\n            client: boto3 textract client\n        \"\"\"\n        try:\n            import textractcaller as tc\n            import textractor.entities.document as textractor\n            self.tc = tc", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html"}
{"id": "78df72f7297f-10", "text": "import textractor.entities.document as textractor\n            self.tc = tc\n            self.textractor = textractor\n            if textract_features is not None:\n                self.textract_features = [\n                    tc.Textract_Features(f) for f in textract_features\n                ]\n            else:\n                self.textract_features = []\n        except ImportError:\n            raise ImportError(\n                \"Could not import amazon-textract-caller or \"\n                \"amazon-textract-textractor python package. Please install it \"\n                \"with `pip install amazon-textract-caller` & \"\n                \"`pip install amazon-textract-textractor`.\"\n            )\n        if not client:\n            try:\n                import boto3\n                self.boto3_textract_client = boto3.client(\"textract\")\n            except ImportError:\n                raise ImportError(\n                    \"Could not import boto3 python package. \"\n                    \"Please install it with `pip install boto3`.\"\n                )\n        else:\n            self.boto3_textract_client = client\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Iterates over the Blob pages and returns an Iterator with a Document\n        for each page, like the other parsers If multi-page document, blob.path\n        has to be set to the S3 URI and for single page docs\n        the blob.data is taken\n        \"\"\"\n        url_parse_result = urlparse(str(blob.path)) if blob.path else None\n        # Either call with S3 path (multi-page) or with bytes (single-page)\n        if (\n            url_parse_result\n            and url_parse_result.scheme == \"s3\"\n            and url_parse_result.netloc\n        ):\n            textract_response_json = self.tc.call_textract(\n                input_document=str(blob.path),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html"}
{"id": "78df72f7297f-11", "text": "input_document=str(blob.path),\n                features=self.textract_features,\n                boto3_textract_client=self.boto3_textract_client,\n            )\n        else:\n            textract_response_json = self.tc.call_textract(\n                input_document=blob.as_bytes(),\n                features=self.textract_features,\n                call_mode=self.tc.Textract_Call_Mode.FORCE_SYNC,\n                boto3_textract_client=self.boto3_textract_client,\n            )\n        document = self.textractor.Document.open(textract_response_json)\n        linearizer_config = self.textractor.TextLinearizationConfig(\n            hide_figure_layout=True,\n            title_prefix=\"# \",\n            section_header_prefix=\"## \",\n            list_element_prefix=\"*\",\n        )\n        for idx, page in enumerate(document.pages):\n            yield Document(\n                page_content=page.get_text(config=linearizer_config),\n                metadata={\"source\": blob.source, \"page\": idx + 1},\n            )\n[docs]class DocumentIntelligenceParser(BaseBlobParser):\n    \"\"\"Loads a PDF with Azure Document Intelligence\n    (formerly Forms Recognizer) and chunks at character level.\"\"\"\n[docs]    def __init__(self, client: Any, model: str):\n        self.client = client\n        self.model = model\n    def _generate_docs(self, blob: Blob, result: Any) -> Iterator[Document]:\n        for p in result.pages:\n            content = \" \".join([line.content for line in p.lines])\n            d = Document(\n                page_content=content,\n                metadata={\n                    \"source\": blob.source,\n                    \"page\": p.page_number,\n                },\n            )\n            yield d\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Lazily parse the blob.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html"}
{"id": "78df72f7297f-12", "text": "\"\"\"Lazily parse the blob.\"\"\"\n        with blob.as_bytes_io() as file_obj:\n            poller = self.client.begin_analyze_document(self.model, file_obj)\n            result = poller.result()\n            docs = self._generate_docs(blob, result)\n            yield from docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html"}
{"id": "0f22622efe89-0", "text": "Source code for langchain.document_loaders.parsers.generic\n\"\"\"Code for generic / auxiliary parsers.\nThis module contains some logic to help assemble more sophisticated parsers.\n\"\"\"\nfrom typing import Iterator, Mapping, Optional\nfrom langchain.document_loaders.base import BaseBlobParser\nfrom langchain.document_loaders.blob_loaders.schema import Blob\nfrom langchain.schema import Document\n[docs]class MimeTypeBasedParser(BaseBlobParser):\n    \"\"\"Parser that uses `mime`-types to parse a blob.\n    This parser is useful for simple pipelines where the mime-type is sufficient\n    to determine how to parse a blob.\n    To use, configure handlers based on mime-types and pass them to the initializer.\n    Example:\n        .. code-block:: python\n        from langchain.document_loaders.parsers.generic import MimeTypeBasedParser\n        parser = MimeTypeBasedParser(\n            handlers={\n                \"application/pdf\": ...,\n            },\n            fallback_parser=...,\n        )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        handlers: Mapping[str, BaseBlobParser],\n        *,\n        fallback_parser: Optional[BaseBlobParser] = None,\n    ) -> None:\n        \"\"\"Define a parser that uses mime-types to determine how to parse a blob.\n        Args:\n            handlers: A mapping from mime-types to functions that take a blob, parse it\n                      and return a document.\n            fallback_parser: A fallback_parser parser to use if the mime-type is not\n                             found in the handlers. If provided, this parser will be\n                             used to parse blobs with all mime-types not found in\n                             the handlers.\n                             If not provided, a ValueError will be raised if the\n                             mime-type is not found in the handlers.\n        \"\"\"\n        self.handlers = handlers\n        self.fallback_parser = fallback_parser", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/generic.html"}
{"id": "0f22622efe89-1", "text": "\"\"\"\n        self.handlers = handlers\n        self.fallback_parser = fallback_parser\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Load documents from a blob.\"\"\"\n        mimetype = blob.mimetype\n        if mimetype is None:\n            raise ValueError(f\"{blob} does not have a mimetype.\")\n        if mimetype in self.handlers:\n            handler = self.handlers[mimetype]\n            yield from handler.lazy_parse(blob)\n        else:\n            if self.fallback_parser is not None:\n                yield from self.fallback_parser.lazy_parse(blob)\n            else:\n                raise ValueError(f\"Unsupported mime type: {mimetype}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/generic.html"}
{"id": "fb2dcee2baf9-0", "text": "Source code for langchain.document_loaders.parsers.registry\n\"\"\"Module includes a registry of default parser configurations.\"\"\"\nfrom langchain.document_loaders.base import BaseBlobParser\nfrom langchain.document_loaders.parsers.generic import MimeTypeBasedParser\nfrom langchain.document_loaders.parsers.msword import MsWordParser\nfrom langchain.document_loaders.parsers.pdf import PyMuPDFParser\nfrom langchain.document_loaders.parsers.txt import TextParser\ndef _get_default_parser() -> BaseBlobParser:\n    \"\"\"Get default mime-type based parser.\"\"\"\n    return MimeTypeBasedParser(\n        handlers={\n            \"application/pdf\": PyMuPDFParser(),\n            \"text/plain\": TextParser(),\n            \"application/msword\": MsWordParser(),\n            \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\": (\n                MsWordParser()\n            ),\n        },\n        fallback_parser=None,\n    )\n_REGISTRY = {\n    \"default\": _get_default_parser,\n}\n# PUBLIC API\n[docs]def get_parser(parser_name: str) -> BaseBlobParser:\n    \"\"\"Get a parser by parser name.\"\"\"\n    if parser_name not in _REGISTRY:\n        raise ValueError(f\"Unknown parser combination: {parser_name}\")\n    return _REGISTRY[parser_name]()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/registry.html"}
{"id": "e74c1c95fafc-0", "text": "Source code for langchain.document_loaders.parsers.grobid\nimport logging\nfrom typing import Dict, Iterator, List, Union\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseBlobParser\nfrom langchain.document_loaders.blob_loaders import Blob\nlogger = logging.getLogger(__name__)\n[docs]class ServerUnavailableException(Exception):\n    \"\"\"Exception raised when the Grobid server is unavailable.\"\"\"\n    pass\n[docs]class GrobidParser(BaseBlobParser):\n    \"\"\"Load  article `PDF` files using `Grobid`.\"\"\"\n[docs]    def __init__(\n        self,\n        segment_sentences: bool,\n        grobid_server: str = \"http://localhost:8070/api/processFulltextDocument\",\n    ) -> None:\n        self.segment_sentences = segment_sentences\n        self.grobid_server = grobid_server\n        try:\n            requests.get(grobid_server)\n        except requests.exceptions.RequestException:\n            logger.error(\n                \"GROBID server does not appear up and running, \\\n                please ensure Grobid is installed and the server is running\"\n            )\n            raise ServerUnavailableException\n[docs]    def process_xml(\n        self, file_path: str, xml_data: str, segment_sentences: bool\n    ) -> Iterator[Document]:\n        \"\"\"Process the XML file from Grobin.\"\"\"\n        try:\n            from bs4 import BeautifulSoup\n        except ImportError:\n            raise ImportError(\n                \"`bs4` package not found, please install it with \" \"`pip install bs4`\"\n            )\n        soup = BeautifulSoup(xml_data, \"xml\")\n        sections = soup.find_all(\"div\")\n        title = soup.find_all(\"title\")[0].text\n        chunks = []\n        for section in sections:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/grobid.html"}
{"id": "e74c1c95fafc-1", "text": "chunks = []\n        for section in sections:\n            sect = section.find(\"head\")\n            if sect is not None:\n                for i, paragraph in enumerate(section.find_all(\"p\")):\n                    chunk_bboxes = []\n                    paragraph_text = []\n                    for i, sentence in enumerate(paragraph.find_all(\"s\")):\n                        paragraph_text.append(sentence.text)\n                        sbboxes = []\n                        for bbox in sentence.get(\"coords\").split(\";\"):\n                            box = bbox.split(\",\")\n                            sbboxes.append(\n                                {\n                                    \"page\": box[0],\n                                    \"x\": box[1],\n                                    \"y\": box[2],\n                                    \"h\": box[3],\n                                    \"w\": box[4],\n                                }\n                            )\n                        chunk_bboxes.append(sbboxes)\n                        if segment_sentences is True:\n                            fpage, lpage = sbboxes[0][\"page\"], sbboxes[-1][\"page\"]\n                            sentence_dict = {\n                                \"text\": sentence.text,\n                                \"para\": str(i),\n                                \"bboxes\": [sbboxes],\n                                \"section_title\": sect.text,\n                                \"section_number\": sect.get(\"n\"),\n                                \"pages\": (fpage, lpage),\n                            }\n                            chunks.append(sentence_dict)\n                    if segment_sentences is not True:\n                        fpage, lpage = (\n                            chunk_bboxes[0][0][\"page\"],\n                            chunk_bboxes[-1][-1][\"page\"],\n                        )\n                        paragraph_dict = {\n                            \"text\": \"\".join(paragraph_text),\n                            \"para\": str(i),\n                            \"bboxes\": chunk_bboxes,\n                            \"section_title\": sect.text,\n                            \"section_number\": sect.get(\"n\"),\n                            \"pages\": (fpage, lpage),\n                        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/grobid.html"}
{"id": "e74c1c95fafc-2", "text": "\"pages\": (fpage, lpage),\n                        }\n                        chunks.append(paragraph_dict)\n        yield from [\n            Document(\n                page_content=chunk[\"text\"],\n                metadata=dict(\n                    {\n                        \"text\": str(chunk[\"text\"]),\n                        \"para\": str(chunk[\"para\"]),\n                        \"bboxes\": str(chunk[\"bboxes\"]),\n                        \"pages\": str(chunk[\"pages\"]),\n                        \"section_title\": str(chunk[\"section_title\"]),\n                        \"section_number\": str(chunk[\"section_number\"]),\n                        \"paper_title\": str(title),\n                        \"file_path\": str(file_path),\n                    }\n                ),\n            )\n            for chunk in chunks\n        ]\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        file_path = blob.source\n        if file_path is None:\n            raise ValueError(\"blob.source cannot be None.\")\n        pdf = open(file_path, \"rb\")\n        files = {\"input\": (file_path, pdf, \"application/pdf\", {\"Expires\": \"0\"})}\n        try:\n            data: Dict[str, Union[str, List[str]]] = {}\n            for param in [\"generateIDs\", \"consolidateHeader\", \"segmentSentences\"]:\n                data[param] = \"1\"\n            data[\"teiCoordinates\"] = [\"head\", \"s\"]\n            files = files or {}\n            r = requests.request(\n                \"POST\",\n                self.grobid_server,\n                headers=None,\n                params=None,\n                files=files,\n                data=data,\n                timeout=60,\n            )\n            xml_data = r.text\n        except requests.exceptions.ReadTimeout:\n            logger.error(\"GROBID server timed out. Return None.\")\n            xml_data = None\n        if xml_data is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/grobid.html"}
{"id": "e74c1c95fafc-3", "text": "xml_data = None\n        if xml_data is None:\n            return iter([])\n        else:\n            return self.process_xml(file_path, xml_data, self.segment_sentences)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/grobid.html"}
{"id": "a270471d2920-0", "text": "Source code for langchain.document_loaders.parsers.audio\nimport logging\nimport time\nfrom typing import Dict, Iterator, Optional, Tuple\nfrom langchain.document_loaders.base import BaseBlobParser\nfrom langchain.document_loaders.blob_loaders import Blob\nfrom langchain.schema import Document\nlogger = logging.getLogger(__name__)\n[docs]class OpenAIWhisperParser(BaseBlobParser):\n    \"\"\"Transcribe and parse audio files.\n    Audio transcription is with OpenAI Whisper model.\"\"\"\n[docs]    def __init__(self, api_key: Optional[str] = None):\n        self.api_key = api_key\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Lazily parse the blob.\"\"\"\n        import io\n        try:\n            import openai\n        except ImportError:\n            raise ImportError(\n                \"openai package not found, please install it with \"\n                \"`pip install openai`\"\n            )\n        try:\n            from pydub import AudioSegment\n        except ImportError:\n            raise ImportError(\n                \"pydub package not found, please install it with \" \"`pip install pydub`\"\n            )\n        # Set the API key if provided\n        if self.api_key:\n            openai.api_key = self.api_key\n        # Audio file from disk\n        audio = AudioSegment.from_file(blob.path)\n        # Define the duration of each chunk in minutes\n        # Need to meet 25MB size limit for Whisper API\n        chunk_duration = 20\n        chunk_duration_ms = chunk_duration * 60 * 1000\n        # Split the audio into chunk_duration_ms chunks\n        for split_number, i in enumerate(range(0, len(audio), chunk_duration_ms)):\n            # Audio chunk\n            chunk = audio[i : i + chunk_duration_ms]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html"}
{"id": "a270471d2920-1", "text": "# Audio chunk\n            chunk = audio[i : i + chunk_duration_ms]\n            file_obj = io.BytesIO(chunk.export(format=\"mp3\").read())\n            if blob.source is not None:\n                file_obj.name = blob.source + f\"_part_{split_number}.mp3\"\n            else:\n                file_obj.name = f\"part_{split_number}.mp3\"\n            # Transcribe\n            print(f\"Transcribing part {split_number+1}!\")\n            attempts = 0\n            while attempts < 3:\n                try:\n                    transcript = openai.Audio.transcribe(\"whisper-1\", file_obj)\n                    break\n                except Exception as e:\n                    attempts += 1\n                    print(f\"Attempt {attempts} failed. Exception: {str(e)}\")\n                    time.sleep(5)\n            else:\n                print(\"Failed to transcribe after 3 attempts.\")\n                continue\n            yield Document(\n                page_content=transcript.text,\n                metadata={\"source\": blob.source, \"chunk\": split_number},\n            )\n[docs]class OpenAIWhisperParserLocal(BaseBlobParser):\n    \"\"\"Transcribe and parse audio files with OpenAI Whisper model.\n    Audio transcription with OpenAI Whisper model locally from transformers.\n    Parameters:\n    device - device to use\n        NOTE: By default uses the gpu if available,\n        if you want to use cpu, please set device = \"cpu\"\n    lang_model - whisper model to use, for example \"openai/whisper-medium\"\n    forced_decoder_ids - id states for decoder in multilanguage model,\n        usage example:\n        from transformers import WhisperProcessor\n        processor = WhisperProcessor.from_pretrained(\"openai/whisper-medium\")\n        forced_decoder_ids = WhisperProcessor.get_decoder_prompt_ids(language=\"french\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html"}
{"id": "a270471d2920-2", "text": "forced_decoder_ids = WhisperProcessor.get_decoder_prompt_ids(language=\"french\",\n          task=\"transcribe\")\n        forced_decoder_ids = WhisperProcessor.get_decoder_prompt_ids(language=\"french\",\n        task=\"translate\")\n    \"\"\"\n[docs]    def __init__(\n        self,\n        device: str = \"0\",\n        lang_model: Optional[str] = None,\n        forced_decoder_ids: Optional[Tuple[Dict]] = None,\n    ):\n        \"\"\"Initialize the parser.\n        Args:\n            device: device to use.\n            lang_model: whisper model to use, for example \"openai/whisper-medium\".\n              Defaults to None.\n            forced_decoder_ids: id states for decoder in a multilanguage model.\n              Defaults to None.\n        \"\"\"\n        try:\n            from transformers import pipeline\n        except ImportError:\n            raise ImportError(\n                \"transformers package not found, please install it with \"\n                \"`pip install transformers`\"\n            )\n        try:\n            import torch\n        except ImportError:\n            raise ImportError(\n                \"torch package not found, please install it with \" \"`pip install torch`\"\n            )\n        # set device, cpu by default check if there is a GPU available\n        if device == \"cpu\":\n            self.device = \"cpu\"\n            if lang_model is not None:\n                self.lang_model = lang_model\n                print(\"WARNING! Model override. Using model: \", self.lang_model)\n            else:\n                # unless overridden, use the small base model on cpu\n                self.lang_model = \"openai/whisper-base\"\n        else:\n            if torch.cuda.is_available():\n                self.device = \"cuda:0\"\n                # check GPU memory and select automatically the model", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html"}
{"id": "a270471d2920-3", "text": "# check GPU memory and select automatically the model\n                mem = torch.cuda.get_device_properties(self.device).total_memory / (\n                    1024**2\n                )\n                if mem < 5000:\n                    rec_model = \"openai/whisper-base\"\n                elif mem < 7000:\n                    rec_model = \"openai/whisper-small\"\n                elif mem < 12000:\n                    rec_model = \"openai/whisper-medium\"\n                else:\n                    rec_model = \"openai/whisper-large\"\n                # check if model is overridden\n                if lang_model is not None:\n                    self.lang_model = lang_model\n                    print(\"WARNING! Model override. Might not fit in your GPU\")\n                else:\n                    self.lang_model = rec_model\n            else:\n                \"cpu\"\n        print(\"Using the following model: \", self.lang_model)\n        # load model for inference\n        self.pipe = pipeline(\n            \"automatic-speech-recognition\",\n            model=self.lang_model,\n            chunk_length_s=30,\n            device=self.device,\n        )\n        if forced_decoder_ids is not None:\n            try:\n                self.pipe.model.config.forced_decoder_ids = forced_decoder_ids\n            except Exception as exception_text:\n                logger.info(\n                    \"Unable to set forced_decoder_ids parameter for whisper model\"\n                    f\"Text of exception: {exception_text}\"\n                    \"Therefore whisper model will use default mode for decoder\"\n                )\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Lazily parse the blob.\"\"\"\n        import io\n        try:\n            from pydub import AudioSegment\n        except ImportError:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html"}
{"id": "a270471d2920-4", "text": "from pydub import AudioSegment\n        except ImportError:\n            raise ImportError(\n                \"pydub package not found, please install it with `pip install pydub`\"\n            )\n        try:\n            import librosa\n        except ImportError:\n            raise ImportError(\n                \"librosa package not found, please install it with \"\n                \"`pip install librosa`\"\n            )\n        # Audio file from disk\n        audio = AudioSegment.from_file(blob.path)\n        file_obj = io.BytesIO(audio.export(format=\"mp3\").read())\n        # Transcribe\n        print(f\"Transcribing part {blob.path}!\")\n        y, sr = librosa.load(file_obj, sr=16000)\n        prediction = self.pipe(y.copy(), batch_size=8)[\"text\"]\n        yield Document(\n            page_content=prediction,\n            metadata={\"source\": blob.source},\n        )\n[docs]class YandexSTTParser(BaseBlobParser):\n    \"\"\"Transcribe and parse audio files.\n    Audio transcription is with OpenAI Whisper model.\"\"\"\n[docs]    def __init__(\n        self,\n        *,\n        api_key: Optional[str] = None,\n        iam_token: Optional[str] = None,\n        model: str = \"general\",\n        language: str = \"auto\",\n    ):\n        \"\"\"Initialize the parser.\n        Args:\n            api_key: API key for a service account\n            with the `ai.speechkit-stt.user` role.\n            iam_token: IAM token for a service account\n            with the `ai.speechkit-stt.user` role.\n            model: Recognition model name.\n              Defaults to general.\n            language: The language in ISO 639-1 format.\n              Defaults to automatic language recognition.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html"}
{"id": "a270471d2920-5", "text": "Defaults to automatic language recognition.\n        Either `api_key` or `iam_token` must be provided, but not both.\n        \"\"\"\n        if (api_key is None) == (iam_token is None):\n            raise ValueError(\n                \"Either 'api_key' or 'iam_token' must be provided, but not both.\"\n            )\n        self.api_key = api_key\n        self.iam_token = iam_token\n        self.model = model\n        self.language = language\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Lazily parse the blob.\"\"\"\n        try:\n            from speechkit import configure_credentials, creds, model_repository\n            from speechkit.stt import AudioProcessingType\n        except ImportError:\n            raise ImportError(\n                \"yandex-speechkit package not found, please install it with \"\n                \"`pip install yandex-speechkit`\"\n            )\n        try:\n            from pydub import AudioSegment\n        except ImportError:\n            raise ImportError(\n                \"pydub package not found, please install it with \" \"`pip install pydub`\"\n            )\n        if self.api_key:\n            configure_credentials(\n                yandex_credentials=creds.YandexCredentials(api_key=self.api_key)\n            )\n        else:\n            configure_credentials(\n                yandex_credentials=creds.YandexCredentials(iam_token=self.iam_token)\n            )\n        audio = AudioSegment.from_file(blob.path)\n        model = model_repository.recognition_model()\n        model.model = self.model\n        model.language = self.language\n        model.audio_processing_type = AudioProcessingType.Full\n        result = model.transcribe(audio)\n        for res in result:\n            yield Document(\n                page_content=res.normalized_text,\n                metadata={\"source\": blob.source},", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html"}
{"id": "a270471d2920-6", "text": "page_content=res.normalized_text,\n                metadata={\"source\": blob.source},\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html"}
{"id": "2b17500a51c9-0", "text": "Source code for langchain.document_loaders.parsers.docai\n\"\"\"Module contains a PDF parser based on Document AI from Google Cloud.\nYou need to install two libraries to use this parser:\npip install google-cloud-documentai\npip install google-cloud-documentai-toolbox\n\"\"\"\nimport logging\nimport re\nimport time\nfrom dataclasses import dataclass\nfrom typing import TYPE_CHECKING, Iterator, List, Optional, Sequence\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseBlobParser\nfrom langchain.document_loaders.blob_loaders import Blob\nfrom langchain.utilities.vertexai import get_client_info\nfrom langchain.utils.iter import batch_iterate\nif TYPE_CHECKING:\n    from google.api_core.operation import Operation\n    from google.cloud.documentai import DocumentProcessorServiceClient\nlogger = logging.getLogger(__name__)\n[docs]@dataclass\nclass DocAIParsingResults:\n    \"\"\"A dataclass to store Document AI parsing results.\"\"\"\n    source_path: str\n    parsed_path: str\n[docs]class DocAIParser(BaseBlobParser):\n    \"\"\"`Google Cloud Document AI` parser.\n    For a detailed explanation of Document AI, refer to the product documentation.\n    https://cloud.google.com/document-ai/docs/overview\n    \"\"\"\n[docs]    def __init__(\n        self,\n        *,\n        client: Optional[\"DocumentProcessorServiceClient\"] = None,\n        location: Optional[str] = None,\n        gcs_output_path: Optional[str] = None,\n        processor_name: Optional[str] = None,\n    ):\n        \"\"\"Initializes the parser.\n        Args:\n            client: a DocumentProcessorServiceClient to use\n            location: a Google Cloud location where a Document AI processor is located\n            gcs_output_path: a path on Google Cloud Storage to store parsing results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html"}
{"id": "2b17500a51c9-1", "text": "gcs_output_path: a path on Google Cloud Storage to store parsing results\n            processor_name: full resource name of a Document AI processor or processor\n                version\n        You should provide either a client or location (and then a client\n            would be instantiated).\n        \"\"\"\n        if bool(client) == bool(location):\n            raise ValueError(\n                \"You must specify either a client or a location to instantiate \"\n                \"a client.\"\n            )\n        pattern = \"projects\\/[0-9]+\\/locations\\/[a-z\\-0-9]+\\/processors\\/[a-z0-9]+\"\n        if processor_name and not re.fullmatch(pattern, processor_name):\n            raise ValueError(\n                f\"Processor name {processor_name} has a wrong format. If your \"\n                \"prediction endpoint looks like https://us-documentai.googleapis.com\"\n                \"/v1/projects/PROJECT_ID/locations/us/processors/PROCESSOR_ID:process,\"\n                \" use only projects/PROJECT_ID/locations/us/processors/PROCESSOR_ID \"\n                \"part.\"\n            )\n        self._gcs_output_path = gcs_output_path\n        self._processor_name = processor_name\n        if client:\n            self._client = client\n        else:\n            try:\n                from google.api_core.client_options import ClientOptions\n                from google.cloud.documentai import DocumentProcessorServiceClient\n            except ImportError as exc:\n                raise ImportError(\n                    \"documentai package not found, please install it with\"\n                    \" `pip install google-cloud-documentai`\"\n                ) from exc\n            options = ClientOptions(\n                api_endpoint=f\"{location}-documentai.googleapis.com\"\n            )\n            self._client = DocumentProcessorServiceClient(\n                client_options=options,\n                client_info=get_client_info(module=\"document-ai\"),\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html"}
{"id": "2b17500a51c9-2", "text": "client_info=get_client_info(module=\"document-ai\"),\n            )\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Parses a blob lazily.\n        Args:\n            blobs: a Blob to parse\n        This is a long-running operation. A recommended way is to batch\n            documents together and use the `batch_parse()` method.\n        \"\"\"\n        yield from self.batch_parse([blob], gcs_output_path=self._gcs_output_path)\n[docs]    def online_process(\n        self,\n        blob: Blob,\n        enable_native_pdf_parsing: bool = True,\n        field_mask: Optional[str] = None,\n        page_range: Optional[List[int]] = None,\n    ) -> Iterator[Document]:\n        \"\"\"Parses a blob lazily using online processing.\n        Args:\n            blob: a blob to parse.\n            enable_native_pdf_parsing: enable pdf embedded text extraction\n            field_mask: a comma-separated list of which fields to include in the\n                Document AI response.\n                suggested: \"text,pages.pageNumber,pages.layout\"\n            page_range: list of page numbers to parse. If `None`,\n                entire document will be parsed.\n        \"\"\"\n        try:\n            from google.cloud import documentai\n            from google.cloud.documentai_v1.types import (\n                IndividualPageSelector,\n                OcrConfig,\n                ProcessOptions,\n            )\n        except ImportError as exc:\n            raise ImportError(\n                \"documentai package not found, please install it with\"\n                \" `pip install google-cloud-documentai`\"\n            ) from exc\n        try:\n            from google.cloud.documentai_toolbox.wrappers.document import (\n                Document as WrappedDocument,\n            )\n        except ImportError as exc:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html"}
{"id": "2b17500a51c9-3", "text": "Document as WrappedDocument,\n            )\n        except ImportError as exc:\n            raise ImportError(\n                \"documentai_toolbox package not found, please install it with\"\n                \" `pip install google-cloud-documentai-toolbox`\"\n            ) from exc\n        ocr_config = (\n            OcrConfig(enable_native_pdf_parsing=enable_native_pdf_parsing)\n            if enable_native_pdf_parsing\n            else None\n        )\n        individual_page_selector = (\n            IndividualPageSelector(pages=page_range) if page_range else None\n        )\n        response = self._client.process_document(\n            documentai.ProcessRequest(\n                name=self._processor_name,\n                gcs_document=documentai.GcsDocument(\n                    gcs_uri=blob.path,\n                    mime_type=blob.mimetype or \"application/pdf\",\n                ),\n                process_options=ProcessOptions(\n                    ocr_config=ocr_config,\n                    individual_page_selector=individual_page_selector,\n                ),\n                skip_human_review=True,\n                field_mask=field_mask,\n            )\n        )\n        wrapped_document = WrappedDocument.from_documentai_document(response.document)\n        yield from (\n            Document(\n                page_content=page.text,\n                metadata={\n                    \"page\": page.page_number,\n                    \"source\": wrapped_document.gcs_input_uri,\n                },\n            )\n            for page in wrapped_document.pages\n        )\n[docs]    def batch_parse(\n        self,\n        blobs: Sequence[Blob],\n        gcs_output_path: Optional[str] = None,\n        timeout_sec: int = 3600,\n        check_in_interval_sec: int = 60,\n    ) -> Iterator[Document]:\n        \"\"\"Parses a list of blobs lazily.\n        Args:\n            blobs: a list of blobs to parse.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html"}
{"id": "2b17500a51c9-4", "text": "Args:\n            blobs: a list of blobs to parse.\n            gcs_output_path: a path on Google Cloud Storage to store parsing results.\n            timeout_sec: a timeout to wait for Document AI to complete, in seconds.\n            check_in_interval_sec: an interval to wait until next check\n                whether parsing operations have been completed, in seconds\n        This is a long-running operation. A recommended way is to decouple\n            parsing from creating LangChain Documents:\n            >>> operations = parser.docai_parse(blobs, gcs_path)\n            >>> parser.is_running(operations)\n            You can get operations names and save them:\n            >>> names = [op.operation.name for op in operations]\n            And when all operations are finished, you can use their results:\n            >>> operations = parser.operations_from_names(operation_names)\n            >>> results = parser.get_results(operations)\n            >>> docs = parser.parse_from_results(results)\n        \"\"\"\n        output_path = gcs_output_path or self._gcs_output_path\n        if not output_path:\n            raise ValueError(\n                \"An output path on Google Cloud Storage should be provided.\"\n            )\n        operations = self.docai_parse(blobs, gcs_output_path=output_path)\n        operation_names = [op.operation.name for op in operations]\n        logger.debug(\n            \"Started parsing with Document AI, submitted operations %s\", operation_names\n        )\n        time_elapsed = 0\n        while self.is_running(operations):\n            time.sleep(check_in_interval_sec)\n            time_elapsed += check_in_interval_sec\n            if time_elapsed > timeout_sec:\n                raise TimeoutError(\n                    \"Timeout exceeded! Check operations \" f\"{operation_names} later!\"\n                )\n            logger.debug(\".\")\n        results = self.get_results(operations=operations)\n        yield from self.parse_from_results(results)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html"}
{"id": "2b17500a51c9-5", "text": "yield from self.parse_from_results(results)\n[docs]    def parse_from_results(\n        self, results: List[DocAIParsingResults]\n    ) -> Iterator[Document]:\n        try:\n            from google.cloud.documentai_toolbox.utilities.gcs_utilities import (\n                split_gcs_uri,\n            )\n            from google.cloud.documentai_toolbox.wrappers.document import (\n                Document as WrappedDocument,\n            )\n        except ImportError as exc:\n            raise ImportError(\n                \"documentai_toolbox package not found, please install it with\"\n                \" `pip install google-cloud-documentai-toolbox`\"\n            ) from exc\n        for result in results:\n            gcs_bucket_name, gcs_prefix = split_gcs_uri(result.parsed_path)\n            wrapped_document = WrappedDocument.from_gcs(\n                gcs_bucket_name, gcs_prefix, gcs_input_uri=result.source_path\n            )\n            yield from (\n                Document(\n                    page_content=page.text,\n                    metadata={\n                        \"page\": page.page_number,\n                        \"source\": wrapped_document.gcs_input_uri,\n                    },\n                )\n                for page in wrapped_document.pages\n            )\n[docs]    def operations_from_names(self, operation_names: List[str]) -> List[\"Operation\"]:\n        \"\"\"Initializes Long-Running Operations from their names.\"\"\"\n        try:\n            from google.longrunning.operations_pb2 import (\n                GetOperationRequest,  # type: ignore\n            )\n        except ImportError as exc:\n            raise ImportError(\n                \"long running operations package not found, please install it with\"\n                \" `pip install gapic-google-longrunning`\"\n            ) from exc\n        return [\n            self._client.get_operation(request=GetOperationRequest(name=name))\n            for name in operation_names\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html"}
{"id": "2b17500a51c9-6", "text": "for name in operation_names\n        ]\n[docs]    def is_running(self, operations: List[\"Operation\"]) -> bool:\n        return any(not op.done() for op in operations)\n[docs]    def docai_parse(\n        self,\n        blobs: Sequence[Blob],\n        *,\n        gcs_output_path: Optional[str] = None,\n        processor_name: Optional[str] = None,\n        batch_size: int = 1000,\n        enable_native_pdf_parsing: bool = True,\n        field_mask: Optional[str] = None,\n    ) -> List[\"Operation\"]:\n        \"\"\"Runs Google Document AI PDF Batch Processing on a list of blobs.\n        Args:\n            blobs: a list of blobs to be parsed\n            gcs_output_path: a path (folder) on GCS to store results\n            processor_name: name of a Document AI processor.\n            batch_size: amount of documents per batch\n            enable_native_pdf_parsing: a config option for the parser\n            field_mask: a comma-separated list of which fields to include in the\n                Document AI response.\n                suggested: \"text,pages.pageNumber,pages.layout\"\n        Document AI has a 1000 file limit per batch, so batches larger than that need\n        to be split into multiple requests.\n        Batch processing is an async long-running operation\n        and results are stored in a output GCS bucket.\n        \"\"\"\n        try:\n            from google.cloud import documentai\n            from google.cloud.documentai_v1.types import OcrConfig, ProcessOptions\n        except ImportError as exc:\n            raise ImportError(\n                \"documentai package not found, please install it with\"\n                \" `pip install google-cloud-documentai`\"\n            ) from exc\n        output_path = gcs_output_path or self._gcs_output_path", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html"}
{"id": "2b17500a51c9-7", "text": "output_path = gcs_output_path or self._gcs_output_path\n        if output_path is None:\n            raise ValueError(\n                \"An output path on Google Cloud Storage should be provided.\"\n            )\n        processor_name = processor_name or self._processor_name\n        if processor_name is None:\n            raise ValueError(\"A Document AI processor name should be provided.\")\n        operations = []\n        for batch in batch_iterate(size=batch_size, iterable=blobs):\n            input_config = documentai.BatchDocumentsInputConfig(\n                gcs_documents=documentai.GcsDocuments(\n                    documents=[\n                        documentai.GcsDocument(\n                            gcs_uri=blob.path,\n                            mime_type=blob.mimetype or \"application/pdf\",\n                        )\n                        for blob in batch\n                    ]\n                )\n            )\n            output_config = documentai.DocumentOutputConfig(\n                gcs_output_config=documentai.DocumentOutputConfig.GcsOutputConfig(\n                    gcs_uri=output_path, field_mask=field_mask\n                )\n            )\n            process_options = (\n                ProcessOptions(\n                    ocr_config=OcrConfig(\n                        enable_native_pdf_parsing=enable_native_pdf_parsing\n                    )\n                )\n                if enable_native_pdf_parsing\n                else None\n            )\n            operations.append(\n                self._client.batch_process_documents(\n                    documentai.BatchProcessRequest(\n                        name=processor_name,\n                        input_documents=input_config,\n                        document_output_config=output_config,\n                        process_options=process_options,\n                        skip_human_review=True,\n                    )\n                )\n            )\n        return operations\n[docs]    def get_results(self, operations: List[\"Operation\"]) -> List[DocAIParsingResults]:\n        try:\n            from google.cloud.documentai_v1 import BatchProcessMetadata\n        except ImportError as exc:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html"}
{"id": "2b17500a51c9-8", "text": "from google.cloud.documentai_v1 import BatchProcessMetadata\n        except ImportError as exc:\n            raise ImportError(\n                \"documentai package not found, please install it with\"\n                \" `pip install google-cloud-documentai`\"\n            ) from exc\n        return [\n            DocAIParsingResults(\n                source_path=status.input_gcs_source,\n                parsed_path=status.output_gcs_destination,\n            )\n            for op in operations\n            for status in (\n                op.metadata.individual_process_statuses\n                if isinstance(op.metadata, BatchProcessMetadata)\n                else BatchProcessMetadata.deserialize(\n                    op.metadata.value\n                ).individual_process_statuses\n            )\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html"}
{"id": "b6a6221eab66-0", "text": "Source code for langchain.document_loaders.parsers.html.bs4\n\"\"\"Loader that uses bs4 to load HTML files, enriching metadata with page title.\"\"\"\nimport logging\nfrom typing import Any, Dict, Iterator, Union\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseBlobParser\nfrom langchain.document_loaders.blob_loaders import Blob\nlogger = logging.getLogger(__name__)\n[docs]class BS4HTMLParser(BaseBlobParser):\n    \"\"\"Pparse HTML files using `Beautiful Soup`.\"\"\"\n[docs]    def __init__(\n        self,\n        *,\n        features: str = \"lxml\",\n        get_text_separator: str = \"\",\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Initialize a bs4 based HTML parser.\"\"\"\n        try:\n            import bs4  # noqa:F401\n        except ImportError:\n            raise ImportError(\n                \"beautifulsoup4 package not found, please install it with \"\n                \"`pip install beautifulsoup4`\"\n            )\n        self.bs_kwargs = {\"features\": features, **kwargs}\n        self.get_text_separator = get_text_separator\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        \"\"\"Load HTML document into document objects.\"\"\"\n        from bs4 import BeautifulSoup\n        with blob.as_bytes_io() as f:\n            soup = BeautifulSoup(f, **self.bs_kwargs)\n        text = soup.get_text(self.get_text_separator)\n        if soup.title:\n            title = str(soup.title.string)\n        else:\n            title = \"\"\n        metadata: Dict[str, Union[str, None]] = {\n            \"source\": blob.source,\n            \"title\": title,\n        }\n        yield Document(page_content=text, metadata=metadata)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/html/bs4.html"}
{"id": "f4493bf6f6d6-0", "text": "Source code for langchain.document_loaders.parsers.language.code_segmenter\nfrom abc import ABC, abstractmethod\nfrom typing import List\n[docs]class CodeSegmenter(ABC):\n    \"\"\"Abstract class for the code segmenter.\"\"\"\n[docs]    def __init__(self, code: str):\n        self.code = code\n[docs]    def is_valid(self) -> bool:\n        return True\n[docs]    @abstractmethod\n    def simplify_code(self) -> str:\n        raise NotImplementedError()  # pragma: no cover\n[docs]    @abstractmethod\n    def extract_functions_classes(self) -> List[str]:\n        raise NotImplementedError()  # pragma: no cover", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/code_segmenter.html"}
{"id": "19f68bdb6028-0", "text": "Source code for langchain.document_loaders.parsers.language.python\nimport ast\nfrom typing import Any, List\nfrom langchain.document_loaders.parsers.language.code_segmenter import CodeSegmenter\n[docs]class PythonSegmenter(CodeSegmenter):\n    \"\"\"Code segmenter for `Python`.\"\"\"\n[docs]    def __init__(self, code: str):\n        super().__init__(code)\n        self.source_lines = self.code.splitlines()\n[docs]    def is_valid(self) -> bool:\n        try:\n            ast.parse(self.code)\n            return True\n        except SyntaxError:\n            return False\n    def _extract_code(self, node: Any) -> str:\n        start = node.lineno - 1\n        end = node.end_lineno\n        return \"\\n\".join(self.source_lines[start:end])\n[docs]    def extract_functions_classes(self) -> List[str]:\n        tree = ast.parse(self.code)\n        functions_classes = []\n        for node in ast.iter_child_nodes(tree):\n            if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):\n                functions_classes.append(self._extract_code(node))\n        return functions_classes\n[docs]    def simplify_code(self) -> str:\n        tree = ast.parse(self.code)\n        simplified_lines = self.source_lines[:]\n        for node in ast.iter_child_nodes(tree):\n            if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):\n                start = node.lineno - 1\n                simplified_lines[start] = f\"# Code for: {simplified_lines[start]}\"\n                assert isinstance(node.end_lineno, int)\n                for line_num in range(start + 1, node.end_lineno):\n                    simplified_lines[line_num] = None  # type: ignore", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/python.html"}
{"id": "19f68bdb6028-1", "text": "simplified_lines[line_num] = None  # type: ignore\n        return \"\\n\".join(line for line in simplified_lines if line is not None)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/python.html"}
{"id": "4c27f3ef6a82-0", "text": "Source code for langchain.document_loaders.parsers.language.javascript\nfrom typing import Any, List\nfrom langchain.document_loaders.parsers.language.code_segmenter import CodeSegmenter\n[docs]class JavaScriptSegmenter(CodeSegmenter):\n    \"\"\"Code segmenter for JavaScript.\"\"\"\n[docs]    def __init__(self, code: str):\n        super().__init__(code)\n        self.source_lines = self.code.splitlines()\n        try:\n            import esprima  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"Could not import esprima Python package. \"\n                \"Please install it with `pip install esprima`.\"\n            )\n[docs]    def is_valid(self) -> bool:\n        import esprima\n        try:\n            esprima.parseScript(self.code)\n            return True\n        except esprima.Error:\n            return False\n    def _extract_code(self, node: Any) -> str:\n        start = node.loc.start.line - 1\n        end = node.loc.end.line\n        return \"\\n\".join(self.source_lines[start:end])\n[docs]    def extract_functions_classes(self) -> List[str]:\n        import esprima\n        tree = esprima.parseScript(self.code, loc=True)\n        functions_classes = []\n        for node in tree.body:\n            if isinstance(\n                node,\n                (esprima.nodes.FunctionDeclaration, esprima.nodes.ClassDeclaration),\n            ):\n                functions_classes.append(self._extract_code(node))\n        return functions_classes\n[docs]    def simplify_code(self) -> str:\n        import esprima\n        tree = esprima.parseScript(self.code, loc=True)\n        simplified_lines = self.source_lines[:]\n        for node in tree.body:\n            if isinstance(\n                node,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/javascript.html"}
{"id": "4c27f3ef6a82-1", "text": "for node in tree.body:\n            if isinstance(\n                node,\n                (esprima.nodes.FunctionDeclaration, esprima.nodes.ClassDeclaration),\n            ):\n                start = node.loc.start.line - 1\n                simplified_lines[start] = f\"// Code for: {simplified_lines[start]}\"\n                for line_num in range(start + 1, node.loc.end.line):\n                    simplified_lines[line_num] = None  # type: ignore\n        return \"\\n\".join(line for line in simplified_lines if line is not None)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/javascript.html"}
{"id": "f5eef8066bdc-0", "text": "Source code for langchain.document_loaders.parsers.language.language_parser\nfrom typing import Any, Dict, Iterator, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseBlobParser\nfrom langchain.document_loaders.blob_loaders import Blob\nfrom langchain.document_loaders.parsers.language.cobol import CobolSegmenter\nfrom langchain.document_loaders.parsers.language.javascript import JavaScriptSegmenter\nfrom langchain.document_loaders.parsers.language.python import PythonSegmenter\nfrom langchain.text_splitter import Language\nLANGUAGE_EXTENSIONS: Dict[str, str] = {\n    \"py\": Language.PYTHON,\n    \"js\": Language.JS,\n    \"cobol\": Language.COBOL,\n}\nLANGUAGE_SEGMENTERS: Dict[str, Any] = {\n    Language.PYTHON: PythonSegmenter,\n    Language.JS: JavaScriptSegmenter,\n    Language.COBOL: CobolSegmenter,\n}\n[docs]class LanguageParser(BaseBlobParser):\n    \"\"\"Parse using the respective programming language syntax.\n    Each top-level function and class in the code is loaded into separate documents.\n    Furthermore, an extra document is generated, containing the remaining top-level code\n    that excludes the already segmented functions and classes.\n    This approach can potentially improve the accuracy of QA models over source code.\n    Currently, the supported languages for code parsing are Python and JavaScript.\n    The language used for parsing can be configured, along with the minimum number of\n    lines required to activate the splitting based on syntax.\n    Examples:\n       .. code-block:: python\n            from langchain.text_splitter.Language\n            from langchain.document_loaders.generic import GenericLoader\n            from langchain.document_loaders.parsers import LanguageParser\n            loader = GenericLoader.from_filesystem(\n                \"./code\",\n                glob=\"**/*\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/language_parser.html"}
{"id": "f5eef8066bdc-1", "text": "\"./code\",\n                glob=\"**/*\",\n                suffixes=[\".py\", \".js\"],\n                parser=LanguageParser()\n            )\n            docs = loader.load()\n        Example instantiations to manually select the language:\n        .. code-block:: python\n            from langchain.text_splitter import Language\n            loader = GenericLoader.from_filesystem(\n                \"./code\",\n                glob=\"**/*\",\n                suffixes=[\".py\"],\n                parser=LanguageParser(language=Language.PYTHON)\n            )\n        Example instantiations to set number of lines threshold:\n        .. code-block:: python\n            loader = GenericLoader.from_filesystem(\n                \"./code\",\n                glob=\"**/*\",\n                suffixes=[\".py\"],\n                parser=LanguageParser(parser_threshold=200)\n            )\n    \"\"\"\n[docs]    def __init__(self, language: Optional[Language] = None, parser_threshold: int = 0):\n        \"\"\"\n        Language parser that split code using the respective language syntax.\n        Args:\n            language: If None (default), it will try to infer language from source.\n            parser_threshold: Minimum lines needed to activate parsing (0 by default).\n        \"\"\"\n        self.language = language\n        self.parser_threshold = parser_threshold\n[docs]    def lazy_parse(self, blob: Blob) -> Iterator[Document]:\n        code = blob.as_string()\n        language = self.language or (\n            LANGUAGE_EXTENSIONS.get(blob.source.rsplit(\".\", 1)[-1])\n            if isinstance(blob.source, str)\n            else None\n        )\n        if language is None:\n            yield Document(\n                page_content=code,\n                metadata={\n                    \"source\": blob.source,\n                },\n            )\n            return\n        if self.parser_threshold >= len(code.splitlines()):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/language_parser.html"}
{"id": "f5eef8066bdc-2", "text": ")\n            return\n        if self.parser_threshold >= len(code.splitlines()):\n            yield Document(\n                page_content=code,\n                metadata={\n                    \"source\": blob.source,\n                    \"language\": language,\n                },\n            )\n            return\n        self.Segmenter = LANGUAGE_SEGMENTERS[language]\n        segmenter = self.Segmenter(blob.as_string())\n        if not segmenter.is_valid():\n            yield Document(\n                page_content=code,\n                metadata={\n                    \"source\": blob.source,\n                },\n            )\n            return\n        for functions_classes in segmenter.extract_functions_classes():\n            yield Document(\n                page_content=functions_classes,\n                metadata={\n                    \"source\": blob.source,\n                    \"content_type\": \"functions_classes\",\n                    \"language\": language,\n                },\n            )\n        yield Document(\n            page_content=segmenter.simplify_code(),\n            metadata={\n                \"source\": blob.source,\n                \"content_type\": \"simplified_code\",\n                \"language\": language,\n            },\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/language_parser.html"}
{"id": "0ec81c344b9c-0", "text": "Source code for langchain.document_loaders.parsers.language.cobol\nimport re\nfrom typing import Callable, List\nfrom langchain.document_loaders.parsers.language.code_segmenter import CodeSegmenter\n[docs]class CobolSegmenter(CodeSegmenter):\n    \"\"\"Code segmenter for `COBOL`.\"\"\"\n    PARAGRAPH_PATTERN = re.compile(r\"^[A-Z0-9\\-]+(\\s+.*)?\\.$\", re.IGNORECASE)\n    DIVISION_PATTERN = re.compile(\n        r\"^\\s*(IDENTIFICATION|DATA|PROCEDURE|ENVIRONMENT)\\s+DIVISION.*$\", re.IGNORECASE\n    )\n    SECTION_PATTERN = re.compile(r\"^\\s*[A-Z0-9\\-]+\\s+SECTION.$\", re.IGNORECASE)\n[docs]    def __init__(self, code: str):\n        super().__init__(code)\n        self.source_lines: List[str] = self.code.splitlines()\n[docs]    def is_valid(self) -> bool:\n        # Identify presence of any division to validate COBOL code\n        return any(self.DIVISION_PATTERN.match(line) for line in self.source_lines)\n    def _extract_code(self, start_idx: int, end_idx: int) -> str:\n        return \"\\n\".join(self.source_lines[start_idx:end_idx]).rstrip(\"\\n\")\n    def _is_relevant_code(self, line: str) -> bool:\n        \"\"\"Check if a line is part of the procedure division or a relevant section.\"\"\"\n        if \"PROCEDURE DIVISION\" in line.upper():\n            return True\n        # Add additional conditions for relevant sections if needed\n        return False\n    def _process_lines(self, func: Callable) -> List[str]:\n        \"\"\"A generic function to process COBOL lines based on provided func.\"\"\"\n        elements: List[str] = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/cobol.html"}
{"id": "0ec81c344b9c-1", "text": "elements: List[str] = []\n        start_idx = None\n        inside_relevant_section = False\n        for i, line in enumerate(self.source_lines):\n            if self._is_relevant_code(line):\n                inside_relevant_section = True\n            if inside_relevant_section and (\n                self.PARAGRAPH_PATTERN.match(line.strip().split(\" \")[0])\n                or self.SECTION_PATTERN.match(line.strip())\n            ):\n                if start_idx is not None:\n                    func(elements, start_idx, i)\n                start_idx = i\n        # Handle the last element if exists\n        if start_idx is not None:\n            func(elements, start_idx, len(self.source_lines))\n        return elements\n[docs]    def extract_functions_classes(self) -> List[str]:\n        def extract_func(elements: List[str], start_idx: int, end_idx: int) -> None:\n            elements.append(self._extract_code(start_idx, end_idx))\n        return self._process_lines(extract_func)\n[docs]    def simplify_code(self) -> str:\n        simplified_lines: List[str] = []\n        inside_relevant_section = False\n        omitted_code_added = (\n            False  # To track if \"* OMITTED CODE *\" has been added after the last header\n        )\n        for line in self.source_lines:\n            is_header = (\n                \"PROCEDURE DIVISION\" in line\n                or \"DATA DIVISION\" in line\n                or \"IDENTIFICATION DIVISION\" in line\n                or self.PARAGRAPH_PATTERN.match(line.strip().split(\" \")[0])\n                or self.SECTION_PATTERN.match(line.strip())\n            )\n            if is_header:\n                inside_relevant_section = True\n                # Reset the flag since we're entering a new section/division or\n                # paragraph\n                omitted_code_added = False", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/cobol.html"}
{"id": "0ec81c344b9c-2", "text": "# paragraph\n                omitted_code_added = False\n            if inside_relevant_section:\n                if is_header:\n                    # Add header and reset the omitted code added flag\n                    simplified_lines.append(line)\n                elif not omitted_code_added:\n                    # Add omitted code comment only if it hasn't been added directly\n                    # after the last header\n                    simplified_lines.append(\"* OMITTED CODE *\")\n                    omitted_code_added = True\n        return \"\\n\".join(simplified_lines)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/cobol.html"}
{"id": "fe780c348b17-0", "text": "Source code for langchain.load.load\nimport importlib\nimport json\nimport os\nfrom typing import Any, Dict, List, Optional\nfrom langchain.load.serializable import Serializable\n[docs]class Reviver:\n    \"\"\"Reviver for JSON objects.\"\"\"\n[docs]    def __init__(\n        self,\n        secrets_map: Optional[Dict[str, str]] = None,\n        valid_namespaces: Optional[List[str]] = None,\n    ) -> None:\n        self.secrets_map = secrets_map or dict()\n        # By default only support langchain, but user can pass in additional namespaces\n        self.valid_namespaces = (\n            [\"langchain\", *valid_namespaces] if valid_namespaces else [\"langchain\"]\n        )\n    def __call__(self, value: Dict[str, Any]) -> Any:\n        if (\n            value.get(\"lc\", None) == 1\n            and value.get(\"type\", None) == \"secret\"\n            and value.get(\"id\", None) is not None\n        ):\n            [key] = value[\"id\"]\n            if key in self.secrets_map:\n                return self.secrets_map[key]\n            else:\n                if key in os.environ and os.environ[key]:\n                    return os.environ[key]\n                raise KeyError(f'Missing key \"{key}\" in load(secrets_map)')\n        if (\n            value.get(\"lc\", None) == 1\n            and value.get(\"type\", None) == \"not_implemented\"\n            and value.get(\"id\", None) is not None\n        ):\n            raise NotImplementedError(\n                \"Trying to load an object that doesn't implement \"\n                f\"serialization: {value}\"\n            )\n        if (\n            value.get(\"lc\", None) == 1", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/load/load.html"}
{"id": "fe780c348b17-1", "text": ")\n        if (\n            value.get(\"lc\", None) == 1\n            and value.get(\"type\", None) == \"constructor\"\n            and value.get(\"id\", None) is not None\n        ):\n            [*namespace, name] = value[\"id\"]\n            if namespace[0] not in self.valid_namespaces:\n                raise ValueError(f\"Invalid namespace: {value}\")\n            # The root namespace \"langchain\" is not a valid identifier.\n            if len(namespace) == 1 and namespace[0] == \"langchain\":\n                raise ValueError(f\"Invalid namespace: {value}\")\n            mod = importlib.import_module(\".\".join(namespace))\n            cls = getattr(mod, name)\n            # The class must be a subclass of Serializable.\n            if not issubclass(cls, Serializable):\n                raise ValueError(f\"Invalid namespace: {value}\")\n            # We don't need to recurse on kwargs\n            # as json.loads will do that for us.\n            kwargs = value.get(\"kwargs\", dict())\n            return cls(**kwargs)\n        return value\n[docs]def loads(\n    text: str,\n    *,\n    secrets_map: Optional[Dict[str, str]] = None,\n    valid_namespaces: Optional[List[str]] = None,\n) -> Any:\n    \"\"\"Revive a LangChain class from a JSON string.\n    Equivalent to `load(json.loads(text))`.\n    Args:\n        text: The string to load.\n        secrets_map: A map of secrets to load.\n        valid_namespaces: A list of additional namespaces (modules)\n            to allow to be deserialized.\n    Returns:\n        Revived LangChain objects.\n    \"\"\"\n    return json.loads(text, object_hook=Reviver(secrets_map, valid_namespaces))\n[docs]def load(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/load/load.html"}
{"id": "fe780c348b17-2", "text": "[docs]def load(\n    obj: Any,\n    *,\n    secrets_map: Optional[Dict[str, str]] = None,\n    valid_namespaces: Optional[List[str]] = None,\n) -> Any:\n    \"\"\"Revive a LangChain class from a JSON object. Use this if you already\n    have a parsed JSON object, eg. from `json.load` or `orjson.loads`.\n    Args:\n        obj: The object to load.\n        secrets_map: A map of secrets to load.\n        valid_namespaces: A list of additional namespaces (modules)\n            to allow to be deserialized.\n    Returns:\n        Revived LangChain objects.\n    \"\"\"\n    reviver = Reviver(secrets_map, valid_namespaces)\n    def _load(obj: Any) -> Any:\n        if isinstance(obj, dict):\n            # Need to revive leaf nodes before reviving this node\n            loaded_obj = {k: _load(v) for k, v in obj.items()}\n            return reviver(loaded_obj)\n        if isinstance(obj, list):\n            return [_load(o) for o in obj]\n        return obj\n    return _load(obj)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/load/load.html"}
{"id": "63fc20d07347-0", "text": "Source code for langchain.load.serializable\nfrom abc import ABC\nfrom typing import Any, Dict, List, Literal, Optional, TypedDict, Union, cast\nfrom langchain.pydantic_v1 import BaseModel, PrivateAttr\n[docs]class BaseSerialized(TypedDict):\n    \"\"\"Base class for serialized objects.\"\"\"\n    lc: int\n    id: List[str]\n[docs]class SerializedConstructor(BaseSerialized):\n    \"\"\"Serialized constructor.\"\"\"\n    type: Literal[\"constructor\"]\n    kwargs: Dict[str, Any]\n[docs]class SerializedSecret(BaseSerialized):\n    \"\"\"Serialized secret.\"\"\"\n    type: Literal[\"secret\"]\n[docs]class SerializedNotImplemented(BaseSerialized):\n    \"\"\"Serialized not implemented.\"\"\"\n    type: Literal[\"not_implemented\"]\n    repr: Optional[str]\n[docs]def try_neq_default(value: Any, key: str, model: BaseModel) -> bool:\n    try:\n        return model.__fields__[key].get_default() != value\n    except Exception:\n        return True\n[docs]class Serializable(BaseModel, ABC):\n    \"\"\"Serializable base class.\"\"\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Is this class serializable?\"\"\"\n        return False\n[docs]    @classmethod\n    def get_lc_namespace(cls) -> List[str]:\n        \"\"\"Get the namespace of the langchain object.\n        For example, if the class is `langchain.llms.openai.OpenAI`, then the\n        namespace is [\"langchain\", \"llms\", \"openai\"]\n        \"\"\"\n        return cls.__module__.split(\".\")\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        \"\"\"A map of constructor argument names to secret ids.\n        For example,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/load/serializable.html"}
{"id": "63fc20d07347-1", "text": "\"\"\"A map of constructor argument names to secret ids.\n        For example,\n            {\"openai_api_key\": \"OPENAI_API_KEY\"}\n        \"\"\"\n        return dict()\n    @property\n    def lc_attributes(self) -> Dict:\n        \"\"\"List of attribute names that should be included in the serialized kwargs.\n        These attributes must be accepted by the constructor.\n        \"\"\"\n        return {}\n[docs]    @classmethod\n    def lc_id(cls) -> List[str]:\n        \"\"\"A unique identifier for this class for serialization purposes.\n        The unique identifier is a list of strings that describes the path\n        to the object.\n        \"\"\"\n        return [*cls.get_lc_namespace(), cls.__name__]\n    class Config:\n        extra = \"ignore\"\n    def __repr_args__(self) -> Any:\n        return [\n            (k, v)\n            for k, v in super().__repr_args__()\n            if (k not in self.__fields__ or try_neq_default(v, k, self))\n        ]\n    _lc_kwargs = PrivateAttr(default_factory=dict)\n    def __init__(self, **kwargs: Any) -> None:\n        super().__init__(**kwargs)\n        self._lc_kwargs = kwargs\n[docs]    def to_json(self) -> Union[SerializedConstructor, SerializedNotImplemented]:\n        if not self.is_lc_serializable():\n            return self.to_json_not_implemented()\n        secrets = dict()\n        # Get latest values for kwargs if there is an attribute with same name\n        lc_kwargs = {\n            k: getattr(self, k, v)\n            for k, v in self._lc_kwargs.items()\n            if not (self.__exclude_fields__ or {}).get(k, False)  # type: ignore\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/load/serializable.html"}
{"id": "63fc20d07347-2", "text": "}\n        # Merge the lc_secrets and lc_attributes from every class in the MRO\n        for cls in [None, *self.__class__.mro()]:\n            # Once we get to Serializable, we're done\n            if cls is Serializable:\n                break\n            if cls:\n                deprecated_attributes = [\n                    \"lc_namespace\",\n                    \"lc_serializable\",\n                ]\n                for attr in deprecated_attributes:\n                    if hasattr(cls, attr):\n                        raise ValueError(\n                            f\"Class {self.__class__} has a deprecated \"\n                            f\"attribute {attr}. Please use the corresponding \"\n                            f\"classmethod instead.\"\n                        )\n            # Get a reference to self bound to each class in the MRO\n            this = cast(Serializable, self if cls is None else super(cls, self))\n            secrets.update(this.lc_secrets)\n            lc_kwargs.update(this.lc_attributes)\n        # include all secrets, even if not specified in kwargs\n        # as these secrets may be passed as an environment variable instead\n        for key in secrets.keys():\n            secret_value = getattr(self, key, None) or lc_kwargs.get(key)\n            if secret_value is not None:\n                lc_kwargs.update({key: secret_value})\n        return {\n            \"lc\": 1,\n            \"type\": \"constructor\",\n            \"id\": self.lc_id(),\n            \"kwargs\": lc_kwargs\n            if not secrets\n            else _replace_secrets(lc_kwargs, secrets),\n        }\n[docs]    def to_json_not_implemented(self) -> SerializedNotImplemented:\n        return to_json_not_implemented(self)\ndef _replace_secrets(\n    root: Dict[Any, Any], secrets_map: Dict[str, str]\n) -> Dict[Any, Any]:\n    result = root.copy()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/load/serializable.html"}
{"id": "63fc20d07347-3", "text": ") -> Dict[Any, Any]:\n    result = root.copy()\n    for path, secret_id in secrets_map.items():\n        [*parts, last] = path.split(\".\")\n        current = result\n        for part in parts:\n            if part not in current:\n                break\n            current[part] = current[part].copy()\n            current = current[part]\n        if last in current:\n            current[last] = {\n                \"lc\": 1,\n                \"type\": \"secret\",\n                \"id\": [secret_id],\n            }\n    return result\n[docs]def to_json_not_implemented(obj: object) -> SerializedNotImplemented:\n    \"\"\"Serialize a \"not implemented\" object.\n    Args:\n        obj: object to serialize\n    Returns:\n        SerializedNotImplemented\n    \"\"\"\n    _id: List[str] = []\n    try:\n        if hasattr(obj, \"__name__\"):\n            _id = [*obj.__module__.split(\".\"), obj.__name__]\n        elif hasattr(obj, \"__class__\"):\n            _id = [*obj.__class__.__module__.split(\".\"), obj.__class__.__name__]\n    except Exception:\n        pass\n    result: SerializedNotImplemented = {\n        \"lc\": 1,\n        \"type\": \"not_implemented\",\n        \"id\": _id,\n        \"repr\": None,\n    }\n    try:\n        result[\"repr\"] = repr(obj)\n    except Exception:\n        pass\n    return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/load/serializable.html"}
{"id": "286054ffbb1c-0", "text": "Source code for langchain.load.dump\nimport json\nfrom typing import Any, Dict\nfrom langchain.load.serializable import Serializable, to_json_not_implemented\n[docs]def default(obj: Any) -> Any:\n    \"\"\"Return a default value for a Serializable object or\n    a SerializedNotImplemented object.\"\"\"\n    if isinstance(obj, Serializable):\n        return obj.to_json()\n    else:\n        return to_json_not_implemented(obj)\n[docs]def dumps(obj: Any, *, pretty: bool = False) -> str:\n    \"\"\"Return a json string representation of an object.\"\"\"\n    if pretty:\n        return json.dumps(obj, default=default, indent=2)\n    else:\n        return json.dumps(obj, default=default)\n[docs]def dumpd(obj: Any) -> Dict[str, Any]:\n    \"\"\"Return a json dict representation of an object.\"\"\"\n    return json.loads(dumps(obj))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/load/dump.html"}
{"id": "f5d3cf7d2993-0", "text": "Source code for langchain.output_parsers.json\nfrom __future__ import annotations\nimport json\nimport re\nfrom json import JSONDecodeError\nfrom typing import Any, Callable, List, Optional\nimport jsonpatch\nfrom langchain.schema.output_parser import (\n    BaseCumulativeTransformOutputParser,\n    OutputParserException,\n)\ndef _replace_new_line(match: re.Match[str]) -> str:\n    value = match.group(2)\n    value = re.sub(r\"\\n\", r\"\\\\n\", value)\n    value = re.sub(r\"\\r\", r\"\\\\r\", value)\n    value = re.sub(r\"\\t\", r\"\\\\t\", value)\n    value = re.sub(r'(?<!\\\\)\"', r\"\\\"\", value)\n    return match.group(1) + value + match.group(3)\ndef _custom_parser(multiline_string: str) -> str:\n    \"\"\"\n    The LLM response for `action_input` may be a multiline\n    string containing unescaped newlines, tabs or quotes. This function\n    replaces those characters with their escaped counterparts.\n    (newlines in JSON must be double-escaped: `\\\\n`)\n    \"\"\"\n    if isinstance(multiline_string, (bytes, bytearray)):\n        multiline_string = multiline_string.decode()\n    multiline_string = re.sub(\n        r'(\"action_input\"\\:\\s*\")(.*)(\")',\n        _replace_new_line,\n        multiline_string,\n        flags=re.DOTALL,\n    )\n    return multiline_string\n# Adapted from https://github.com/KillianLucas/open-interpreter/blob/main/interpreter/utils/parse_partial_json.py\n# MIT License\n[docs]def parse_partial_json(s: str, *, strict: bool = False) -> Any:\n    \"\"\"Parse a JSON string that may be missing closing braces.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/json.html"}
{"id": "f5d3cf7d2993-1", "text": "\"\"\"Parse a JSON string that may be missing closing braces.\n    Args:\n        s: The JSON string to parse.\n        strict: Whether to use strict parsing. Defaults to False.\n    Returns:\n        The parsed JSON object as a Python dictionary.\n    \"\"\"\n    # Attempt to parse the string as-is.\n    try:\n        return json.loads(s, strict=strict)\n    except json.JSONDecodeError:\n        pass\n    # Initialize variables.\n    new_s = \"\"\n    stack = []\n    is_inside_string = False\n    escaped = False\n    # Process each character in the string one at a time.\n    for char in s:\n        if is_inside_string:\n            if char == '\"' and not escaped:\n                is_inside_string = False\n            elif char == \"\\n\" and not escaped:\n                char = \"\\\\n\"  # Replace the newline character with the escape sequence.\n            elif char == \"\\\\\":\n                escaped = not escaped\n            else:\n                escaped = False\n        else:\n            if char == '\"':\n                is_inside_string = True\n                escaped = False\n            elif char == \"{\":\n                stack.append(\"}\")\n            elif char == \"[\":\n                stack.append(\"]\")\n            elif char == \"}\" or char == \"]\":\n                if stack and stack[-1] == char:\n                    stack.pop()\n                else:\n                    # Mismatched closing character; the input is malformed.\n                    return None\n        # Append the processed character to the new string.\n        new_s += char\n    # If we're still inside a string at the end of processing,\n    # we need to close the string.\n    if is_inside_string:\n        new_s += '\"'\n    # Close any remaining open structures in the reverse order that they were opened.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/json.html"}
{"id": "f5d3cf7d2993-2", "text": "# Close any remaining open structures in the reverse order that they were opened.\n    for closing_char in reversed(stack):\n        new_s += closing_char\n    # Attempt to parse the modified string as JSON.\n    try:\n        return json.loads(new_s, strict=strict)\n    except json.JSONDecodeError:\n        # If we still can't parse the string as JSON, return None to indicate failure.\n        return None\n[docs]def parse_json_markdown(\n    json_string: str, *, parser: Callable[[str], Any] = json.loads\n) -> dict:\n    \"\"\"\n    Parse a JSON string from a Markdown string.\n    Args:\n        json_string: The Markdown string.\n    Returns:\n        The parsed JSON object as a Python dictionary.\n    \"\"\"\n    # Try to find JSON string within triple backticks\n    match = re.search(r\"```(json)?(.*)```\", json_string, re.DOTALL)\n    # If no match found, assume the entire string is a JSON string\n    if match is None:\n        json_str = json_string\n    else:\n        # If match found, use the content within the backticks\n        json_str = match.group(2)\n    # Strip whitespace and newlines from the start and end\n    json_str = json_str.strip()\n    # handle newlines and other special characters inside the returned value\n    json_str = _custom_parser(json_str)\n    # Parse the JSON string into a Python dictionary\n    parsed = parser(json_str)\n    return parsed\n[docs]def parse_and_check_json_markdown(text: str, expected_keys: List[str]) -> dict:\n    \"\"\"\n    Parse a JSON string from a Markdown string and check that it\n    contains the expected keys.\n    Args:\n        text: The Markdown string.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/json.html"}
{"id": "f5d3cf7d2993-3", "text": "contains the expected keys.\n    Args:\n        text: The Markdown string.\n        expected_keys: The expected keys in the JSON string.\n    Returns:\n        The parsed JSON object as a Python dictionary.\n    \"\"\"\n    try:\n        json_obj = parse_json_markdown(text)\n    except json.JSONDecodeError as e:\n        raise OutputParserException(f\"Got invalid JSON object. Error: {e}\")\n    for key in expected_keys:\n        if key not in json_obj:\n            raise OutputParserException(\n                f\"Got invalid return object. Expected key `{key}` \"\n                f\"to be present, but got {json_obj}\"\n            )\n    return json_obj\n[docs]class SimpleJsonOutputParser(BaseCumulativeTransformOutputParser[Any]):\n    \"\"\"Parse the output of an LLM call to a JSON object.\n    When used in streaming mode, it will yield partial JSON objects containing\n    all the keys that have been returned so far.\n    In streaming, if `diff` is set to `True`, yields JSONPatch operations\n    describing the difference between the previous and the current object.\n    \"\"\"\n    def _diff(self, prev: Optional[Any], next: Any) -> Any:\n        return jsonpatch.make_patch(prev, next).patch\n[docs]    def parse(self, text: str) -> Any:\n        text = text.strip()\n        try:\n            return parse_json_markdown(text.strip(), parser=parse_partial_json)\n        except JSONDecodeError as e:\n            raise OutputParserException(f\"Invalid json output: {text}\") from e\n    @property\n    def _type(self) -> str:\n        return \"simple_json_output_parser\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/json.html"}
{"id": "655e7cd2af0e-0", "text": "Source code for langchain.output_parsers.regex\nfrom __future__ import annotations\nimport re\nfrom typing import Dict, List, Optional\nfrom langchain.schema import BaseOutputParser\n[docs]class RegexParser(BaseOutputParser):\n    \"\"\"Parse the output of an LLM call using a regex.\"\"\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n    regex: str\n    \"\"\"The regex to use to parse the output.\"\"\"\n    output_keys: List[str]\n    \"\"\"The keys to use for the output.\"\"\"\n    default_output_key: Optional[str] = None\n    \"\"\"The default key to use for the output.\"\"\"\n    @property\n    def _type(self) -> str:\n        \"\"\"Return the type key.\"\"\"\n        return \"regex_parser\"\n[docs]    def parse(self, text: str) -> Dict[str, str]:\n        \"\"\"Parse the output of an LLM call.\"\"\"\n        match = re.search(self.regex, text)\n        if match:\n            return {key: match.group(i + 1) for i, key in enumerate(self.output_keys)}\n        else:\n            if self.default_output_key is None:\n                raise ValueError(f\"Could not parse output: {text}\")\n            else:\n                return {\n                    key: text if key == self.default_output_key else \"\"\n                    for key in self.output_keys\n                }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/regex.html"}
{"id": "4caa1d0d67b0-0", "text": "Source code for langchain.output_parsers.openai_tools\nimport copy\nimport json\nfrom typing import Any, List, Type\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema import (\n    ChatGeneration,\n    Generation,\n    OutputParserException,\n)\nfrom langchain.schema.output_parser import (\n    BaseGenerationOutputParser,\n)\n[docs]class JsonOutputToolsParser(BaseGenerationOutputParser[Any]):\n    \"\"\"Parse tools from OpenAI response.\"\"\"\n[docs]    def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any:\n        generation = result[0]\n        if not isinstance(generation, ChatGeneration):\n            raise OutputParserException(\n                \"This output parser can only be used with a chat generation.\"\n            )\n        message = generation.message\n        try:\n            tool_calls = copy.deepcopy(message.additional_kwargs[\"tool_calls\"])\n        except KeyError:\n            return []\n        final_tools = []\n        for tool_call in tool_calls:\n            if \"function\" not in tool_call:\n                pass\n            function_args = tool_call[\"function\"][\"arguments\"]\n            final_tools.append(\n                {\n                    \"type\": tool_call[\"function\"][\"name\"],\n                    \"args\": json.loads(function_args),\n                }\n            )\n        return final_tools\n[docs]class JsonOutputKeyToolsParser(JsonOutputToolsParser):\n    \"\"\"Parse tools from OpenAI response.\"\"\"\n    key_name: str\n    \"\"\"The type of tools to return.\"\"\"\n[docs]    def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any:\n        results = super().parse_result(result)\n        return [res[\"args\"] for res in results if results[\"type\"] == self.key_name]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_tools.html"}
{"id": "4caa1d0d67b0-1", "text": "[docs]class PydanticToolsParser(JsonOutputToolsParser):\n    \"\"\"Parse tools from OpenAI response.\"\"\"\n    tools: List[Type[BaseModel]]\n[docs]    def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any:\n        results = super().parse_result(result)\n        name_dict = {tool.__name__: tool for tool in self.tools}\n        return [name_dict[res[\"type\"]](**res[\"args\"]) for res in results]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_tools.html"}
{"id": "a486c9419687-0", "text": "Source code for langchain.output_parsers.pydantic\nimport json\nimport re\nfrom typing import Type, TypeVar\nfrom langchain.output_parsers.format_instructions import PYDANTIC_FORMAT_INSTRUCTIONS\nfrom langchain.pydantic_v1 import BaseModel, ValidationError\nfrom langchain.schema import BaseOutputParser, OutputParserException\nT = TypeVar(\"T\", bound=BaseModel)\n[docs]class PydanticOutputParser(BaseOutputParser[T]):\n    \"\"\"Parse an output using a pydantic model.\"\"\"\n    pydantic_object: Type[T]\n    \"\"\"The pydantic model to parse.\"\"\"\n[docs]    def parse(self, text: str) -> T:\n        try:\n            # Greedy search for 1st json candidate.\n            match = re.search(\n                r\"\\{.*\\}\", text.strip(), re.MULTILINE | re.IGNORECASE | re.DOTALL\n            )\n            json_str = \"\"\n            if match:\n                json_str = match.group()\n            json_object = json.loads(json_str, strict=False)\n            return self.pydantic_object.parse_obj(json_object)\n        except (json.JSONDecodeError, ValidationError) as e:\n            name = self.pydantic_object.__name__\n            msg = f\"Failed to parse {name} from completion {text}. Got: {e}\"\n            raise OutputParserException(msg, llm_output=text)\n[docs]    def get_format_instructions(self) -> str:\n        schema = self.pydantic_object.schema()\n        # Remove extraneous fields.\n        reduced_schema = schema\n        if \"title\" in reduced_schema:\n            del reduced_schema[\"title\"]\n        if \"type\" in reduced_schema:\n            del reduced_schema[\"type\"]\n        # Ensure json in context is well-formed with double quotes.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html"}
{"id": "a486c9419687-1", "text": "# Ensure json in context is well-formed with double quotes.\n        schema_str = json.dumps(reduced_schema)\n        return PYDANTIC_FORMAT_INSTRUCTIONS.format(schema=schema_str)\n    @property\n    def _type(self) -> str:\n        return \"pydantic\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html"}
{"id": "647077782fdc-0", "text": "Source code for langchain.output_parsers.retry\nfrom __future__ import annotations\nfrom typing import Any, TypeVar\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.schema import (\n    BaseOutputParser,\n    BasePromptTemplate,\n    OutputParserException,\n    PromptValue,\n)\nfrom langchain.schema.language_model import BaseLanguageModel\nNAIVE_COMPLETION_RETRY = \"\"\"Prompt:\n{prompt}\nCompletion:\n{completion}\nAbove, the Completion did not satisfy the constraints given in the Prompt.\nPlease try again:\"\"\"\nNAIVE_COMPLETION_RETRY_WITH_ERROR = \"\"\"Prompt:\n{prompt}\nCompletion:\n{completion}\nAbove, the Completion did not satisfy the constraints given in the Prompt.\nDetails: {error}\nPlease try again:\"\"\"\nNAIVE_RETRY_PROMPT = PromptTemplate.from_template(NAIVE_COMPLETION_RETRY)\nNAIVE_RETRY_WITH_ERROR_PROMPT = PromptTemplate.from_template(\n    NAIVE_COMPLETION_RETRY_WITH_ERROR\n)\nT = TypeVar(\"T\")\n[docs]class RetryOutputParser(BaseOutputParser[T]):\n    \"\"\"Wraps a parser and tries to fix parsing errors.\n    Does this by passing the original prompt and the completion to another\n    LLM, and telling it the completion did not satisfy criteria in the prompt.\n    \"\"\"\n    parser: BaseOutputParser[T]\n    \"\"\"The parser to use to parse the output.\"\"\"\n    # Should be an LLMChain but we want to avoid top-level imports from langchain.chains\n    retry_chain: Any\n    \"\"\"The LLMChain to use to retry the completion.\"\"\"\n    max_retries: int = 1\n    \"\"\"The maximum number of times to retry the parse.\"\"\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html"}
{"id": "647077782fdc-1", "text": "def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        parser: BaseOutputParser[T],\n        prompt: BasePromptTemplate = NAIVE_RETRY_PROMPT,\n        max_retries: int = 1,\n    ) -> RetryOutputParser[T]:\n        \"\"\"Create an OutputFixingParser from a language model and a parser.\n        Args:\n            llm: llm to use for fixing\n            parser: parser to use for parsing\n            prompt: prompt to use for fixing\n            max_retries: Maximum number of retries to parse.\n        Returns:\n            RetryOutputParser\n        \"\"\"\n        from langchain.chains.llm import LLMChain\n        chain = LLMChain(llm=llm, prompt=prompt)\n        return cls(parser=parser, retry_chain=chain, max_retries=max_retries)\n[docs]    def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:\n        \"\"\"Parse the output of an LLM call using a wrapped parser.\n        Args:\n            completion: The chain completion to parse.\n            prompt_value: The prompt to use to parse the completion.\n        Returns:\n            The parsed completion.\n        \"\"\"\n        retries = 0\n        while retries <= self.max_retries:\n            try:\n                return self.parser.parse(completion)\n            except OutputParserException as e:\n                if retries == self.max_retries:\n                    raise e\n                else:\n                    retries += 1\n                    completion = self.retry_chain.run(\n                        prompt=prompt_value.to_string(), completion=completion\n                    )\n        raise OutputParserException(\"Failed to parse\")\n[docs]    async def aparse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html"}
{"id": "647077782fdc-2", "text": "\"\"\"Parse the output of an LLM call using a wrapped parser.\n        Args:\n            completion: The chain completion to parse.\n            prompt_value: The prompt to use to parse the completion.\n        Returns:\n            The parsed completion.\n        \"\"\"\n        retries = 0\n        while retries <= self.max_retries:\n            try:\n                return await self.parser.aparse(completion)\n            except OutputParserException as e:\n                if retries == self.max_retries:\n                    raise e\n                else:\n                    retries += 1\n                    completion = await self.retry_chain.arun(\n                        prompt=prompt_value.to_string(), completion=completion\n                    )\n        raise OutputParserException(\"Failed to parse\")\n[docs]    def parse(self, completion: str) -> T:\n        raise NotImplementedError(\n            \"This OutputParser can only be called by the `parse_with_prompt` method.\"\n        )\n[docs]    def get_format_instructions(self) -> str:\n        return self.parser.get_format_instructions()\n    @property\n    def _type(self) -> str:\n        return \"retry\"\n[docs]class RetryWithErrorOutputParser(BaseOutputParser[T]):\n    \"\"\"Wraps a parser and tries to fix parsing errors.\n    Does this by passing the original prompt, the completion, AND the error\n    that was raised to another language model and telling it that the completion\n    did not work, and raised the given error. Differs from RetryOutputParser\n    in that this implementation provides the error that was raised back to the\n    LLM, which in theory should give it more information on how to fix it.\n    \"\"\"\n    parser: BaseOutputParser[T]\n    \"\"\"The parser to use to parse the output.\"\"\"\n    # Should be an LLMChain but we want to avoid top-level imports from langchain.chains", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html"}
{"id": "647077782fdc-3", "text": "retry_chain: Any\n    \"\"\"The LLMChain to use to retry the completion.\"\"\"\n    max_retries: int = 1\n    \"\"\"The maximum number of times to retry the parse.\"\"\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        parser: BaseOutputParser[T],\n        prompt: BasePromptTemplate = NAIVE_RETRY_WITH_ERROR_PROMPT,\n        max_retries: int = 1,\n    ) -> RetryWithErrorOutputParser[T]:\n        \"\"\"Create a RetryWithErrorOutputParser from an LLM.\n        Args:\n            llm: The LLM to use to retry the completion.\n            parser: The parser to use to parse the output.\n            prompt: The prompt to use to retry the completion.\n            max_retries: The maximum number of times to retry the completion.\n        Returns:\n            A RetryWithErrorOutputParser.\n        \"\"\"\n        from langchain.chains.llm import LLMChain\n        chain = LLMChain(llm=llm, prompt=prompt)\n        return cls(parser=parser, retry_chain=chain, max_retries=max_retries)\n[docs]    def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:\n        retries = 0\n        while retries <= self.max_retries:\n            try:\n                return self.parser.parse(completion)\n            except OutputParserException as e:\n                if retries == self.max_retries:\n                    raise e\n                else:\n                    retries += 1\n                    completion = self.retry_chain.run(\n                        prompt=prompt_value.to_string(),\n                        completion=completion,\n                        error=repr(e),\n                    )\n        raise OutputParserException(\"Failed to parse\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html"}
{"id": "647077782fdc-4", "text": ")\n        raise OutputParserException(\"Failed to parse\")\n[docs]    async def aparse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:\n        retries = 0\n        while retries <= self.max_retries:\n            try:\n                return await self.parser.aparse(completion)\n            except OutputParserException as e:\n                if retries == self.max_retries:\n                    raise e\n                else:\n                    retries += 1\n                    completion = await self.retry_chain.arun(\n                        prompt=prompt_value.to_string(),\n                        completion=completion,\n                        error=repr(e),\n                    )\n        raise OutputParserException(\"Failed to parse\")\n[docs]    def parse(self, completion: str) -> T:\n        raise NotImplementedError(\n            \"This OutputParser can only be called by the `parse_with_prompt` method.\"\n        )\n[docs]    def get_format_instructions(self) -> str:\n        return self.parser.get_format_instructions()\n    @property\n    def _type(self) -> str:\n        return \"retry_with_error\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html"}
{"id": "43ad5a9e46de-0", "text": "Source code for langchain.output_parsers.list\nfrom __future__ import annotations\nimport re\nfrom abc import abstractmethod\nfrom typing import List\nfrom langchain.schema import BaseOutputParser\n[docs]class ListOutputParser(BaseOutputParser[List[str]]):\n    \"\"\"Parse the output of an LLM call to a list.\"\"\"\n    @property\n    def _type(self) -> str:\n        return \"list\"\n[docs]    @abstractmethod\n    def parse(self, text: str) -> List[str]:\n        \"\"\"Parse the output of an LLM call.\"\"\"\n[docs]class CommaSeparatedListOutputParser(ListOutputParser):\n    \"\"\"Parse the output of an LLM call to a comma-separated list.\"\"\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n[docs]    def get_format_instructions(self) -> str:\n        return (\n            \"Your response should be a list of comma separated values, \"\n            \"eg: `foo, bar, baz`\"\n        )\n[docs]    def parse(self, text: str) -> List[str]:\n        \"\"\"Parse the output of an LLM call.\"\"\"\n        return text.strip().split(\", \")\n    @property\n    def _type(self) -> str:\n        return \"comma-separated-list\"\n[docs]class NumberedListOutputParser(ListOutputParser):\n    \"\"\"Parse a numbered list.\"\"\"\n[docs]    def get_format_instructions(self) -> str:\n        return (\n            \"Your response should be a numbered list with each item on a new line. \"\n            \"For example: \\n\\n1. foo\\n\\n2. bar\\n\\n3. baz\"\n        )\n[docs]    def parse(self, text: str) -> List[str]:\n        \"\"\"Parse the output of an LLM call.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/list.html"}
{"id": "43ad5a9e46de-1", "text": "\"\"\"Parse the output of an LLM call.\"\"\"\n        pattern = r\"\\d+\\.\\s([^\\n]+)\"\n        # Extract the text of each item\n        matches = re.findall(pattern, text)\n        return matches\n    @property\n    def _type(self) -> str:\n        return \"numbered-list\"\n[docs]class MarkdownListOutputParser(ListOutputParser):\n    \"\"\"Parse a markdown list.\"\"\"\n[docs]    def get_format_instructions(self) -> str:\n        return \"Your response should be a markdown list, \" \"eg: `- foo\\n- bar\\n- baz`\"\n[docs]    def parse(self, text: str) -> List[str]:\n        \"\"\"Parse the output of an LLM call.\"\"\"\n        pattern = r\"-\\s([^\\n]+)\"\n        return re.findall(pattern, text)\n    @property\n    def _type(self) -> str:\n        return \"markdown-list\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/list.html"}
{"id": "19cf5e080868-0", "text": "Source code for langchain.output_parsers.rail_parser\nfrom __future__ import annotations\nfrom typing import Any, Callable, Dict, Optional\nfrom langchain.schema import BaseOutputParser\n[docs]class GuardrailsOutputParser(BaseOutputParser):\n    \"\"\"Parse the output of an LLM call using Guardrails.\"\"\"\n    guard: Any\n    \"\"\"The Guardrails object.\"\"\"\n    api: Optional[Callable]\n    \"\"\"The API to use for the Guardrails object.\"\"\"\n    args: Any\n    \"\"\"The arguments to pass to the API.\"\"\"\n    kwargs: Any\n    \"\"\"The keyword arguments to pass to the API.\"\"\"\n    @property\n    def _type(self) -> str:\n        return \"guardrails\"\n[docs]    @classmethod\n    def from_rail(\n        cls,\n        rail_file: str,\n        num_reasks: int = 1,\n        api: Optional[Callable] = None,\n        *args: Any,\n        **kwargs: Any,\n    ) -> GuardrailsOutputParser:\n        \"\"\"Create a GuardrailsOutputParser from a rail file.\n        Args:\n            rail_file: a rail file.\n            num_reasks: number of times to re-ask the question.\n            api: the API to use for the Guardrails object.\n            *args: The arguments to pass to the API\n            **kwargs: The keyword arguments to pass to the API.\n        Returns:\n            GuardrailsOutputParser\n        \"\"\"\n        try:\n            from guardrails import Guard\n        except ImportError:\n            raise ImportError(\n                \"guardrails-ai package not installed. \"\n                \"Install it by running `pip install guardrails-ai`.\"\n            )\n        return cls(\n            guard=Guard.from_rail(rail_file, num_reasks=num_reasks),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html"}
{"id": "19cf5e080868-1", "text": "guard=Guard.from_rail(rail_file, num_reasks=num_reasks),\n            api=api,\n            args=args,\n            kwargs=kwargs,\n        )\n[docs]    @classmethod\n    def from_rail_string(\n        cls,\n        rail_str: str,\n        num_reasks: int = 1,\n        api: Optional[Callable] = None,\n        *args: Any,\n        **kwargs: Any,\n    ) -> GuardrailsOutputParser:\n        try:\n            from guardrails import Guard\n        except ImportError:\n            raise ImportError(\n                \"guardrails-ai package not installed. \"\n                \"Install it by running `pip install guardrails-ai`.\"\n            )\n        return cls(\n            guard=Guard.from_rail_string(rail_str, num_reasks=num_reasks),\n            api=api,\n            args=args,\n            kwargs=kwargs,\n        )\n[docs]    @classmethod\n    def from_pydantic(\n        cls,\n        output_class: Any,\n        num_reasks: int = 1,\n        api: Optional[Callable] = None,\n        *args: Any,\n        **kwargs: Any,\n    ) -> GuardrailsOutputParser:\n        try:\n            from guardrails import Guard\n        except ImportError:\n            raise ImportError(\n                \"guardrails-ai package not installed. \"\n                \"Install it by running `pip install guardrails-ai`.\"\n            )\n        return cls(\n            guard=Guard.from_pydantic(output_class, \"\", num_reasks=num_reasks),\n            api=api,\n            args=args,\n            kwargs=kwargs,\n        )\n[docs]    def get_format_instructions(self) -> str:\n        return self.guard.raw_prompt.format_instructions", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html"}
{"id": "19cf5e080868-2", "text": "return self.guard.raw_prompt.format_instructions\n[docs]    def parse(self, text: str) -> Dict:\n        return self.guard.parse(text, llm_api=self.api, *self.args, **self.kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html"}
{"id": "c8b0466305da-0", "text": "Source code for langchain.output_parsers.combining\nfrom __future__ import annotations\nfrom typing import Any, Dict, List\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import BaseOutputParser\n[docs]class CombiningOutputParser(BaseOutputParser):\n    \"\"\"Combine multiple output parsers into one.\"\"\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n    parsers: List[BaseOutputParser]\n    @root_validator()\n    def validate_parsers(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Validate the parsers.\"\"\"\n        parsers = values[\"parsers\"]\n        if len(parsers) < 2:\n            raise ValueError(\"Must have at least two parsers\")\n        for parser in parsers:\n            if parser._type == \"combining\":\n                raise ValueError(\"Cannot nest combining parsers\")\n            if parser._type == \"list\":\n                raise ValueError(\"Cannot combine list parsers\")\n        return values\n    @property\n    def _type(self) -> str:\n        \"\"\"Return the type key.\"\"\"\n        return \"combining\"\n[docs]    def get_format_instructions(self) -> str:\n        \"\"\"Instructions on how the LLM output should be formatted.\"\"\"\n        initial = f\"For your first output: {self.parsers[0].get_format_instructions()}\"\n        subsequent = \"\\n\".join(\n            f\"Complete that output fully. Then produce another output, separated by two newline characters: {p.get_format_instructions()}\"  # noqa: E501\n            for p in self.parsers[1:]\n        )\n        return f\"{initial}\\n{subsequent}\"\n[docs]    def parse(self, text: str) -> Dict[str, Any]:\n        \"\"\"Parse the output of an LLM call.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/combining.html"}
{"id": "c8b0466305da-1", "text": "\"\"\"Parse the output of an LLM call.\"\"\"\n        texts = text.split(\"\\n\\n\")\n        output = dict()\n        for txt, parser in zip(texts, self.parsers):\n            output.update(parser.parse(txt.strip()))\n        return output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/combining.html"}
{"id": "e94a034fefef-0", "text": "Source code for langchain.output_parsers.fix\nfrom __future__ import annotations\nfrom typing import Any, TypeVar\nfrom langchain.output_parsers.prompts import NAIVE_FIX_PROMPT\nfrom langchain.schema import BaseOutputParser, BasePromptTemplate, OutputParserException\nfrom langchain.schema.language_model import BaseLanguageModel\nT = TypeVar(\"T\")\n[docs]class OutputFixingParser(BaseOutputParser[T]):\n    \"\"\"Wraps a parser and tries to fix parsing errors.\"\"\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n    parser: BaseOutputParser[T]\n    \"\"\"The parser to use to parse the output.\"\"\"\n    # Should be an LLMChain but we want to avoid top-level imports from langchain.chains\n    retry_chain: Any\n    \"\"\"The LLMChain to use to retry the completion.\"\"\"\n    max_retries: int = 1\n    \"\"\"The maximum number of times to retry the parse.\"\"\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        parser: BaseOutputParser[T],\n        prompt: BasePromptTemplate = NAIVE_FIX_PROMPT,\n        max_retries: int = 1,\n    ) -> OutputFixingParser[T]:\n        \"\"\"Create an OutputFixingParser from a language model and a parser.\n        Args:\n            llm: llm to use for fixing\n            parser: parser to use for parsing\n            prompt: prompt to use for fixing\n            max_retries: Maximum number of retries to parse.\n        Returns:\n            OutputFixingParser\n        \"\"\"\n        from langchain.chains.llm import LLMChain\n        chain = LLMChain(llm=llm, prompt=prompt)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html"}
{"id": "e94a034fefef-1", "text": "chain = LLMChain(llm=llm, prompt=prompt)\n        return cls(parser=parser, retry_chain=chain, max_retries=max_retries)\n[docs]    def parse(self, completion: str) -> T:\n        retries = 0\n        while retries <= self.max_retries:\n            try:\n                return self.parser.parse(completion)\n            except OutputParserException as e:\n                if retries == self.max_retries:\n                    raise e\n                else:\n                    retries += 1\n                    completion = self.retry_chain.run(\n                        instructions=self.parser.get_format_instructions(),\n                        completion=completion,\n                        error=repr(e),\n                    )\n        raise OutputParserException(\"Failed to parse\")\n[docs]    async def aparse(self, completion: str) -> T:\n        retries = 0\n        while retries <= self.max_retries:\n            try:\n                return await self.parser.aparse(completion)\n            except OutputParserException as e:\n                if retries == self.max_retries:\n                    raise e\n                else:\n                    retries += 1\n                    completion = await self.retry_chain.arun(\n                        instructions=self.parser.get_format_instructions(),\n                        completion=completion,\n                        error=repr(e),\n                    )\n        raise OutputParserException(\"Failed to parse\")\n[docs]    def get_format_instructions(self) -> str:\n        return self.parser.get_format_instructions()\n    @property\n    def _type(self) -> str:\n        return \"output_fixing\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html"}
{"id": "9878f8e9a7dc-0", "text": "Source code for langchain.output_parsers.datetime\nimport random\nfrom datetime import datetime, timedelta\nfrom typing import List\nfrom langchain.schema import BaseOutputParser, OutputParserException\nfrom langchain.utils import comma_list\ndef _generate_random_datetime_strings(\n    pattern: str,\n    n: int = 3,\n    start_date: datetime = datetime(1, 1, 1),\n    end_date: datetime = datetime.now() + timedelta(days=3650),\n) -> List[str]:\n    \"\"\"Generates n random datetime strings conforming to the\n    given pattern within the specified date range.\n    Pattern should be a string containing the desired format codes.\n    start_date and end_date should be datetime objects representing\n    the start and end of the date range.\n    \"\"\"\n    examples = []\n    delta = end_date - start_date\n    for i in range(n):\n        random_delta = random.uniform(0, delta.total_seconds())\n        dt = start_date + timedelta(seconds=random_delta)\n        date_string = dt.strftime(pattern)\n        examples.append(date_string)\n    return examples\n[docs]class DatetimeOutputParser(BaseOutputParser[datetime]):\n    \"\"\"Parse the output of an LLM call to a datetime.\"\"\"\n    format: str = \"%Y-%m-%dT%H:%M:%S.%fZ\"\n    \"\"\"The string value that used as the datetime format.\"\"\"\n[docs]    def get_format_instructions(self) -> str:\n        examples = comma_list(_generate_random_datetime_strings(self.format))\n        return f\"\"\"Write a datetime string that matches the \n            following pattern: \"{self.format}\". Examples: {examples}\"\"\"\n[docs]    def parse(self, response: str) -> datetime:\n        try:\n            return datetime.strptime(response.strip(), self.format)\n        except ValueError as e:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/datetime.html"}
{"id": "9878f8e9a7dc-1", "text": "return datetime.strptime(response.strip(), self.format)\n        except ValueError as e:\n            raise OutputParserException(\n                f\"Could not parse datetime string: {response}\"\n            ) from e\n    @property\n    def _type(self) -> str:\n        return \"datetime\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/datetime.html"}
{"id": "8eaa9a5ed301-0", "text": "Source code for langchain.output_parsers.loading\nfrom langchain.output_parsers.regex import RegexParser\n[docs]def load_output_parser(config: dict) -> dict:\n    \"\"\"Load an output parser.\n    Args:\n        config: config dict\n    Returns:\n        config dict with output parser loaded\n    \"\"\"\n    if \"output_parsers\" in config:\n        if config[\"output_parsers\"] is not None:\n            _config = config[\"output_parsers\"]\n            output_parser_type = _config[\"_type\"]\n            if output_parser_type == \"regex_parser\":\n                output_parser = RegexParser(**_config)\n            else:\n                raise ValueError(f\"Unsupported output parser {output_parser_type}\")\n            config[\"output_parsers\"] = output_parser\n    return config", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/loading.html"}
{"id": "d6f64ad6e9fb-0", "text": "Source code for langchain.output_parsers.xml\nimport re\nimport xml.etree.ElementTree as ET\nfrom typing import Any, Dict, List, Optional\nfrom langchain.output_parsers.format_instructions import XML_FORMAT_INSTRUCTIONS\nfrom langchain.schema import BaseOutputParser\n[docs]class XMLOutputParser(BaseOutputParser):\n    \"\"\"Parse an output using xml format.\"\"\"\n    tags: Optional[List[str]] = None\n    encoding_matcher: re.Pattern = re.compile(\n        r\"<([^>]*encoding[^>]*)>\\n(.*)\", re.MULTILINE | re.DOTALL\n    )\n[docs]    def get_format_instructions(self) -> str:\n        return XML_FORMAT_INSTRUCTIONS.format(tags=self.tags)\n[docs]    def parse(self, text: str) -> Dict[str, List[Any]]:\n        text = text.strip(\"`\").strip(\"xml\")\n        encoding_match = self.encoding_matcher.search(text)\n        if encoding_match:\n            text = encoding_match.group(2)\n        text = text.strip()\n        if (text.startswith(\"<\") or text.startswith(\"\\n<\")) and (\n            text.endswith(\">\") or text.endswith(\">\\n\")\n        ):\n            root = ET.fromstring(text)\n            return self._root_to_dict(root)\n        else:\n            raise ValueError(f\"Could not parse output: {text}\")\n    def _root_to_dict(self, root: ET.Element) -> Dict[str, List[Any]]:\n        \"\"\"Converts xml tree to python dictionary.\"\"\"\n        result: Dict[str, List[Any]] = {root.tag: []}\n        for child in root:\n            if len(child) == 0:\n                result[root.tag].append({child.tag: child.text})\n            else:\n                result[root.tag].append(self._root_to_dict(child))\n        return result\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/xml.html"}
{"id": "d6f64ad6e9fb-1", "text": "return result\n    @property\n    def _type(self) -> str:\n        return \"xml\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/xml.html"}
{"id": "75817d9fe0fb-0", "text": "Source code for langchain.output_parsers.boolean\nfrom langchain.schema import BaseOutputParser\n[docs]class BooleanOutputParser(BaseOutputParser[bool]):\n    \"\"\"Parse the output of an LLM call to a boolean.\"\"\"\n    true_val: str = \"YES\"\n    \"\"\"The string value that should be parsed as True.\"\"\"\n    false_val: str = \"NO\"\n    \"\"\"The string value that should be parsed as False.\"\"\"\n[docs]    def parse(self, text: str) -> bool:\n        \"\"\"Parse the output of an LLM call to a boolean.\n        Args:\n            text: output of a language model\n        Returns:\n            boolean\n        \"\"\"\n        cleaned_text = text.strip()\n        if cleaned_text.upper() not in (self.true_val.upper(), self.false_val.upper()):\n            raise ValueError(\n                f\"BooleanOutputParser expected output value to either be \"\n                f\"{self.true_val} or {self.false_val}. Received {cleaned_text}.\"\n            )\n        return cleaned_text.upper() == self.true_val.upper()\n    @property\n    def _type(self) -> str:\n        \"\"\"Snake-case string identifier for an output parser type.\"\"\"\n        return \"boolean_output_parser\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/boolean.html"}
{"id": "a409ab1ca16b-0", "text": "Source code for langchain.output_parsers.openai_functions\nimport copy\nimport json\nfrom typing import Any, Dict, List, Optional, Type, Union\nimport jsonpatch\nfrom langchain.output_parsers.json import parse_partial_json\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema import (\n    ChatGeneration,\n    Generation,\n    OutputParserException,\n)\nfrom langchain.schema.output_parser import (\n    BaseCumulativeTransformOutputParser,\n    BaseGenerationOutputParser,\n)\n[docs]class OutputFunctionsParser(BaseGenerationOutputParser[Any]):\n    \"\"\"Parse an output that is one of sets of values.\"\"\"\n    args_only: bool = True\n    \"\"\"Whether to only return the arguments to the function call.\"\"\"\n[docs]    def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any:\n        generation = result[0]\n        if not isinstance(generation, ChatGeneration):\n            raise OutputParserException(\n                \"This output parser can only be used with a chat generation.\"\n            )\n        message = generation.message\n        try:\n            func_call = copy.deepcopy(message.additional_kwargs[\"function_call\"])\n        except KeyError as exc:\n            raise OutputParserException(f\"Could not parse function call: {exc}\")\n        if self.args_only:\n            return func_call[\"arguments\"]\n        return func_call\n[docs]class JsonOutputFunctionsParser(BaseCumulativeTransformOutputParser[Any]):\n    \"\"\"Parse an output as the Json object.\"\"\"\n    strict: bool = False\n    \"\"\"Whether to allow non-JSON-compliant strings.\n    \n    See: https://docs.python.org/3/library/json.html#encoders-and-decoders\n    \n    Useful when the parsed output may include unicode characters or new lines.\n    \"\"\"\n    args_only: bool = True", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_functions.html"}
{"id": "a409ab1ca16b-1", "text": "\"\"\"\n    args_only: bool = True\n    \"\"\"Whether to only return the arguments to the function call.\"\"\"\n    @property\n    def _type(self) -> str:\n        return \"json_functions\"\n    def _diff(self, prev: Optional[Any], next: Any) -> Any:\n        return jsonpatch.make_patch(prev, next).patch\n[docs]    def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any:\n        if len(result) != 1:\n            raise OutputParserException(\n                f\"Expected exactly one result, but got {len(result)}\"\n            )\n        generation = result[0]\n        if not isinstance(generation, ChatGeneration):\n            raise OutputParserException(\n                \"This output parser can only be used with a chat generation.\"\n            )\n        message = generation.message\n        try:\n            function_call = message.additional_kwargs[\"function_call\"]\n        except KeyError as exc:\n            if partial:\n                return None\n            else:\n                raise OutputParserException(f\"Could not parse function call: {exc}\")\n        try:\n            if partial:\n                if self.args_only:\n                    return parse_partial_json(\n                        function_call[\"arguments\"], strict=self.strict\n                    )\n                else:\n                    return {\n                        **function_call,\n                        \"arguments\": parse_partial_json(\n                            function_call[\"arguments\"], strict=self.strict\n                        ),\n                    }\n            else:\n                if self.args_only:\n                    try:\n                        return json.loads(\n                            function_call[\"arguments\"], strict=self.strict\n                        )\n                    except (json.JSONDecodeError, TypeError) as exc:\n                        raise OutputParserException(\n                            f\"Could not parse function call data: {exc}\"\n                        )\n                else:\n                    try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_functions.html"}
{"id": "a409ab1ca16b-2", "text": ")\n                else:\n                    try:\n                        return {\n                            **function_call,\n                            \"arguments\": json.loads(\n                                function_call[\"arguments\"], strict=self.strict\n                            ),\n                        }\n                    except (json.JSONDecodeError, TypeError) as exc:\n                        raise OutputParserException(\n                            f\"Could not parse function call data: {exc}\"\n                        )\n        except KeyError:\n            return None\n    # This method would be called by the default implementation of `parse_result`\n    # but we're overriding that method so it's not needed.\n[docs]    def parse(self, text: str) -> Any:\n        raise NotImplementedError()\n[docs]class JsonKeyOutputFunctionsParser(JsonOutputFunctionsParser):\n    \"\"\"Parse an output as the element of the Json object.\"\"\"\n    key_name: str\n    \"\"\"The name of the key to return.\"\"\"\n[docs]    def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any:\n        res = super().parse_result(result, partial=partial)\n        if partial and res is None:\n            return None\n        return res.get(self.key_name) if partial else res[self.key_name]\n[docs]class PydanticOutputFunctionsParser(OutputFunctionsParser):\n    \"\"\"Parse an output as a pydantic object.\"\"\"\n    pydantic_schema: Union[Type[BaseModel], Dict[str, Type[BaseModel]]]\n    \"\"\"The pydantic schema to parse the output with.\"\"\"\n    @root_validator(pre=True)\n    def validate_schema(cls, values: Dict) -> Dict:\n        schema = values[\"pydantic_schema\"]\n        if \"args_only\" not in values:\n            values[\"args_only\"] = isinstance(schema, type) and issubclass(\n                schema, BaseModel\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_functions.html"}
{"id": "a409ab1ca16b-3", "text": "schema, BaseModel\n            )\n        elif values[\"args_only\"] and isinstance(schema, Dict):\n            raise ValueError(\n                \"If multiple pydantic schemas are provided then args_only should be\"\n                \" False.\"\n            )\n        return values\n[docs]    def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any:\n        _result = super().parse_result(result)\n        if self.args_only:\n            pydantic_args = self.pydantic_schema.parse_raw(_result)  # type: ignore\n        else:\n            fn_name = _result[\"name\"]\n            _args = _result[\"arguments\"]\n            pydantic_args = self.pydantic_schema[fn_name].parse_raw(_args)  # type: ignore  # noqa: E501\n        return pydantic_args\n[docs]class PydanticAttrOutputFunctionsParser(PydanticOutputFunctionsParser):\n    \"\"\"Parse an output as an attribute of a pydantic object.\"\"\"\n    attr_name: str\n    \"\"\"The name of the attribute to return.\"\"\"\n[docs]    def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any:\n        result = super().parse_result(result)\n        return getattr(result, self.attr_name)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_functions.html"}
{"id": "9af3a9ca8517-0", "text": "Source code for langchain.output_parsers.enum\nfrom enum import Enum\nfrom typing import Any, Dict, List, Type\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import BaseOutputParser, OutputParserException\n[docs]class EnumOutputParser(BaseOutputParser):\n    \"\"\"Parse an output that is one of a set of values.\"\"\"\n    enum: Type[Enum]\n    \"\"\"The enum to parse. Its values must be strings.\"\"\"\n    @root_validator()\n    def raise_deprecation(cls, values: Dict) -> Dict:\n        enum = values[\"enum\"]\n        if not all(isinstance(e.value, str) for e in enum):\n            raise ValueError(\"Enum values must be strings\")\n        return values\n    @property\n    def _valid_values(self) -> List[str]:\n        return [e.value for e in self.enum]\n[docs]    def parse(self, response: str) -> Any:\n        try:\n            return self.enum(response.strip())\n        except ValueError:\n            raise OutputParserException(\n                f\"Response '{response}' is not one of the \"\n                f\"expected values: {self._valid_values}\"\n            )\n[docs]    def get_format_instructions(self) -> str:\n        return f\"Select one of the following options: {', '.join(self._valid_values)}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/enum.html"}
{"id": "098eb2df87f9-0", "text": "Source code for langchain.output_parsers.regex_dict\nfrom __future__ import annotations\nimport re\nfrom typing import Dict, Optional\nfrom langchain.schema import BaseOutputParser\n[docs]class RegexDictParser(BaseOutputParser):\n    \"\"\"Parse the output of an LLM call into a Dictionary using a regex.\"\"\"\n    regex_pattern: str = r\"{}:\\s?([^.'\\n']*)\\.?\"  # : :meta private:\n    \"\"\"The regex pattern to use to parse the output.\"\"\"\n    output_key_to_format: Dict[str, str]\n    \"\"\"The keys to use for the output.\"\"\"\n    no_update_value: Optional[str] = None\n    \"\"\"The default key to use for the output.\"\"\"\n    @property\n    def _type(self) -> str:\n        \"\"\"Return the type key.\"\"\"\n        return \"regex_dict_parser\"\n[docs]    def parse(self, text: str) -> Dict[str, str]:\n        \"\"\"Parse the output of an LLM call.\"\"\"\n        result = {}\n        for output_key, expected_format in self.output_key_to_format.items():\n            specific_regex = self.regex_pattern.format(re.escape(expected_format))\n            matches = re.findall(specific_regex, text)\n            if not matches:\n                raise ValueError(\n                    f\"No match found for output key: {output_key} with expected format \\\n                        {expected_format} on text {text}\"\n                )\n            elif len(matches) > 1:\n                raise ValueError(\n                    f\"Multiple matches found for output key: {output_key} with \\\n                        expected format {expected_format} on text {text}\"\n                )\n            elif (\n                self.no_update_value is not None and matches[0] == self.no_update_value\n            ):\n                continue\n            else:\n                result[output_key] = matches[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html"}
{"id": "098eb2df87f9-1", "text": "continue\n            else:\n                result[output_key] = matches[0]\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html"}
{"id": "9d45a9be3596-0", "text": "Source code for langchain.output_parsers.structured\nfrom __future__ import annotations\nfrom typing import Any, List\nfrom langchain.output_parsers.format_instructions import (\n    STRUCTURED_FORMAT_INSTRUCTIONS,\n    STRUCTURED_FORMAT_SIMPLE_INSTRUCTIONS,\n)\nfrom langchain.output_parsers.json import parse_and_check_json_markdown\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema import BaseOutputParser\nline_template = '\\t\"{name}\": {type}  // {description}'\n[docs]class ResponseSchema(BaseModel):\n    \"\"\"A schema for a response from a structured output parser.\"\"\"\n    name: str\n    \"\"\"The name of the schema.\"\"\"\n    description: str\n    \"\"\"The description of the schema.\"\"\"\n    type: str = \"string\"\n    \"\"\"The type of the response.\"\"\"\ndef _get_sub_string(schema: ResponseSchema) -> str:\n    return line_template.format(\n        name=schema.name, description=schema.description, type=schema.type\n    )\n[docs]class StructuredOutputParser(BaseOutputParser):\n    \"\"\"Parse the output of an LLM call to a structured output.\"\"\"\n    response_schemas: List[ResponseSchema]\n    \"\"\"The schemas for the response.\"\"\"\n[docs]    @classmethod\n    def from_response_schemas(\n        cls, response_schemas: List[ResponseSchema]\n    ) -> StructuredOutputParser:\n        return cls(response_schemas=response_schemas)\n[docs]    def get_format_instructions(self, only_json: bool = False) -> str:\n        \"\"\"Get format instructions for the output parser.\n        example:\n        ```python\n        from langchain.output_parsers.structured import (\n            StructuredOutputParser, ResponseSchema\n        )\n        response_schemas = [\n            ResponseSchema(\n                name=\"foo\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html"}
{"id": "9d45a9be3596-1", "text": "response_schemas = [\n            ResponseSchema(\n                name=\"foo\",\n                description=\"a list of strings\",\n                type=\"List[string]\"\n                ),\n            ResponseSchema(\n                name=\"bar\",\n                description=\"a string\",\n                type=\"string\"\n                ),\n        ]\n        parser = StructuredOutputParser.from_response_schemas(response_schemas)\n        print(parser.get_format_instructions())\n        output:\n        # The output should be a Markdown code snippet formatted in the following\n        # schema, including the leading and trailing \"```json\" and \"```\":\n        #\n        # ```json\n        # {\n        #     \"foo\": List[string]  // a list of strings\n        #     \"bar\": string  // a string\n        # }\n        # ```\n        Args:\n            only_json (bool): If True, only the json in the Markdown code snippet\n                will be returned, without the introducing text. Defaults to False.\n        \"\"\"\n        schema_str = \"\\n\".join(\n            [_get_sub_string(schema) for schema in self.response_schemas]\n        )\n        if only_json:\n            return STRUCTURED_FORMAT_SIMPLE_INSTRUCTIONS.format(format=schema_str)\n        else:\n            return STRUCTURED_FORMAT_INSTRUCTIONS.format(format=schema_str)\n[docs]    def parse(self, text: str) -> Any:\n        expected_keys = [rs.name for rs in self.response_schemas]\n        return parse_and_check_json_markdown(text, expected_keys)\n    @property\n    def _type(self) -> str:\n        return \"structured\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html"}
{"id": "95788910ea65-0", "text": "Source code for langchain.embeddings.huggingface_hub\nfrom typing import Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\nDEFAULT_REPO_ID = \"sentence-transformers/all-mpnet-base-v2\"\nVALID_TASKS = (\"feature-extraction\",)\n[docs]class HuggingFaceHubEmbeddings(BaseModel, Embeddings):\n    \"\"\"HuggingFaceHub embedding models.\n    To use, you should have the ``huggingface_hub`` python package installed, and the\n    environment variable ``HUGGINGFACEHUB_API_TOKEN`` set with your API token, or pass\n    it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import HuggingFaceHubEmbeddings\n            repo_id = \"sentence-transformers/all-mpnet-base-v2\"\n            hf = HuggingFaceHubEmbeddings(\n                repo_id=repo_id,\n                task=\"feature-extraction\",\n                huggingfacehub_api_token=\"my-api-key\",\n            )\n    \"\"\"\n    client: Any  #: :meta private:\n    repo_id: str = DEFAULT_REPO_ID\n    \"\"\"Model name to use.\"\"\"\n    task: Optional[str] = \"feature-extraction\"\n    \"\"\"Task to call the model with.\"\"\"\n    model_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    huggingfacehub_api_token: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html"}
{"id": "95788910ea65-1", "text": "@root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        huggingfacehub_api_token = get_from_dict_or_env(\n            values, \"huggingfacehub_api_token\", \"HUGGINGFACEHUB_API_TOKEN\"\n        )\n        try:\n            from huggingface_hub.inference_api import InferenceApi\n            repo_id = values[\"repo_id\"]\n            if not repo_id.startswith(\"sentence-transformers\"):\n                raise ValueError(\n                    \"Currently only 'sentence-transformers' embedding models \"\n                    f\"are supported. Got invalid 'repo_id' {repo_id}.\"\n                )\n            client = InferenceApi(\n                repo_id=repo_id,\n                token=huggingfacehub_api_token,\n                task=values.get(\"task\"),\n            )\n            if client.task not in VALID_TASKS:\n                raise ValueError(\n                    f\"Got invalid task {client.task}, \"\n                    f\"currently only {VALID_TASKS} are supported\"\n                )\n            values[\"client\"] = client\n        except ImportError:\n            raise ImportError(\n                \"Could not import huggingface_hub python package. \"\n                \"Please install it with `pip install huggingface_hub`.\"\n            )\n        return values\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Call out to HuggingFaceHub's embedding endpoint for embedding search docs.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        # replace newlines, which can negatively affect performance.\n        texts = [text.replace(\"\\n\", \" \") for text in texts]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html"}
{"id": "95788910ea65-2", "text": "texts = [text.replace(\"\\n\", \" \") for text in texts]\n        _model_kwargs = self.model_kwargs or {}\n        responses = self.client(inputs=texts, params=_model_kwargs)\n        return responses\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to HuggingFaceHub's embedding endpoint for embedding query text.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        response = self.embed_documents([text])[0]\n        return response", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html"}
{"id": "33d7c1cb349f-0", "text": "Source code for langchain.embeddings.octoai_embeddings\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\nDEFAULT_EMBED_INSTRUCTION = \"Represent this input: \"\nDEFAULT_QUERY_INSTRUCTION = \"Represent the question for retrieving similar documents: \"\n[docs]class OctoAIEmbeddings(BaseModel, Embeddings):\n    \"\"\"OctoAI Compute Service embedding models.\n    The environment variable ``OCTOAI_API_TOKEN`` should be set\n    with your API token, or it can be passed\n    as a named parameter to the constructor.\n    \"\"\"\n    endpoint_url: Optional[str] = Field(None, description=\"Endpoint URL to use.\")\n    model_kwargs: Optional[dict] = Field(\n        None, description=\"Keyword arguments to pass to the model.\"\n    )\n    octoai_api_token: Optional[str] = Field(None, description=\"OCTOAI API Token\")\n    embed_instruction: str = Field(\n        DEFAULT_EMBED_INSTRUCTION,\n        description=\"Instruction to use for embedding documents.\",\n    )\n    query_instruction: str = Field(\n        DEFAULT_QUERY_INSTRUCTION, description=\"Instruction to use for embedding query.\"\n    )\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator(allow_reuse=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Ensure that the API key and python package exist in environment.\"\"\"\n        values[\"octoai_api_token\"] = get_from_dict_or_env(\n            values, \"octoai_api_token\", \"OCTOAI_API_TOKEN\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/octoai_embeddings.html"}
{"id": "33d7c1cb349f-1", "text": ")\n        values[\"endpoint_url\"] = get_from_dict_or_env(\n            values, \"endpoint_url\", \"ENDPOINT_URL\"\n        )\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Return the identifying parameters.\"\"\"\n        return {\n            \"endpoint_url\": self.endpoint_url,\n            \"model_kwargs\": self.model_kwargs or {},\n        }\n    def _compute_embeddings(\n        self, texts: List[str], instruction: str\n    ) -> List[List[float]]:\n        \"\"\"Compute embeddings using an OctoAI instruct model.\"\"\"\n        from octoai import client\n        embeddings = []\n        octoai_client = client.Client(token=self.octoai_api_token)\n        for text in texts:\n            parameter_payload = {\n                \"sentence\": str([text]),  # for item in text]),\n                \"instruction\": str([instruction]),  # for item in text]),\n                \"parameters\": self.model_kwargs or {},\n            }\n            try:\n                resp_json = octoai_client.infer(self.endpoint_url, parameter_payload)\n                embedding = resp_json[\"embeddings\"]\n            except Exception as e:\n                raise ValueError(f\"Error raised by the inference endpoint: {e}\") from e\n            embeddings.append(embedding)\n        return embeddings\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Compute document embeddings using an OctoAI instruct model.\"\"\"\n        texts = list(map(lambda x: x.replace(\"\\n\", \" \"), texts))\n        return self._compute_embeddings(texts, self.embed_instruction)\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Compute query embedding using an OctoAI instruct model.\"\"\"\n        text = text.replace(\"\\n\", \" \")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/octoai_embeddings.html"}
{"id": "33d7c1cb349f-2", "text": "text = text.replace(\"\\n\", \" \")\n        return self._compute_embeddings([text], self.query_instruction)[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/octoai_embeddings.html"}
{"id": "8812135dd122-0", "text": "Source code for langchain.embeddings.jina\nimport os\nfrom typing import Any, Dict, List, Optional\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\n[docs]class JinaEmbeddings(BaseModel, Embeddings):\n    \"\"\"Jina embedding models.\"\"\"\n    client: Any  #: :meta private:\n    model_name: str = \"ViT-B-32::openai\"\n    \"\"\"Model name to use.\"\"\"\n    jina_auth_token: Optional[str] = None\n    jina_api_url: str = \"https://api.clip.jina.ai/api/v1/models/\"\n    request_headers: Optional[dict] = None\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that auth token exists in environment.\"\"\"\n        # Set Auth\n        jina_auth_token = get_from_dict_or_env(\n            values, \"jina_auth_token\", \"JINA_AUTH_TOKEN\"\n        )\n        values[\"jina_auth_token\"] = jina_auth_token\n        values[\"request_headers\"] = ((\"authorization\", jina_auth_token),)\n        # Test that package is installed\n        try:\n            import jina\n        except ImportError:\n            raise ImportError(\n                \"Could not import `jina` python package. \"\n                \"Please install it with `pip install jina`.\"\n            )\n        # Setup client\n        jina_api_url = os.environ.get(\"JINA_API_URL\", values[\"jina_api_url\"])\n        model_name = values[\"model_name\"]\n        try:\n            resp = requests.get(\n                jina_api_url + f\"?model_name={model_name}\",\n                headers={\"Authorization\": jina_auth_token},\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/jina.html"}
{"id": "8812135dd122-1", "text": "headers={\"Authorization\": jina_auth_token},\n            )\n            if resp.status_code == 401:\n                raise ValueError(\n                    \"The given Jina auth token is invalid. \"\n                    \"Please check your Jina auth token.\"\n                )\n            elif resp.status_code == 404:\n                raise ValueError(\n                    f\"The given model name `{model_name}` is not valid. \"\n                    f\"Please go to https://cloud.jina.ai/user/inference \"\n                    f\"and create a model with the given model name.\"\n                )\n            resp.raise_for_status()\n            endpoint = resp.json()[\"endpoints\"][\"grpc\"]\n            values[\"client\"] = jina.Client(host=endpoint)\n        except requests.exceptions.HTTPError as err:\n            raise ValueError(f\"Error: {err!r}\")\n        return values\n    def _post(self, docs: List[Any], **kwargs: Any) -> Any:\n        payload = dict(inputs=docs, metadata=self.request_headers, **kwargs)\n        return self.client.post(on=\"/encode\", **payload)\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Call out to Jina's embedding endpoint.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        from docarray import Document, DocumentArray\n        embeddings = self._post(\n            docs=DocumentArray([Document(text=t) for t in texts])\n        ).embeddings\n        return [list(map(float, e)) for e in embeddings]\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to Jina's embedding endpoint.\n        Args:\n            text: The text to embed.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/jina.html"}
{"id": "8812135dd122-2", "text": "Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        from docarray import Document, DocumentArray\n        embedding = self._post(docs=DocumentArray([Document(text=text)])).embeddings[0]\n        return list(map(float, embedding))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/jina.html"}
{"id": "7a8f81a035e7-0", "text": "Source code for langchain.embeddings.minimax\nfrom __future__ import annotations\nimport logging\nfrom typing import Any, Callable, Dict, List, Optional\nimport requests\nfrom tenacity import (\n    before_sleep_log,\n    retry,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\ndef _create_retry_decorator() -> Callable[[Any], Any]:\n    \"\"\"Returns a tenacity retry decorator.\"\"\"\n    multiplier = 1\n    min_seconds = 1\n    max_seconds = 4\n    max_retries = 6\n    return retry(\n        reraise=True,\n        stop=stop_after_attempt(max_retries),\n        wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\n[docs]def embed_with_retry(embeddings: MiniMaxEmbeddings, *args: Any, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    retry_decorator = _create_retry_decorator()\n    @retry_decorator\n    def _embed_with_retry(*args: Any, **kwargs: Any) -> Any:\n        return embeddings.embed(*args, **kwargs)\n    return _embed_with_retry(*args, **kwargs)\n[docs]class MiniMaxEmbeddings(BaseModel, Embeddings):\n    \"\"\"MiniMax's embedding service.\n    To use, you should have the environment variable ``MINIMAX_GROUP_ID`` and\n    ``MINIMAX_API_KEY`` set with your API token, or pass it as a named parameter to\n    the constructor.\n    Example:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html"}
{"id": "7a8f81a035e7-1", "text": "the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import MiniMaxEmbeddings\n            embeddings = MiniMaxEmbeddings()\n            query_text = \"This is a test query.\"\n            query_result = embeddings.embed_query(query_text)\n            document_text = \"This is a test document.\"\n            document_result = embeddings.embed_documents([document_text])\n    \"\"\"\n    endpoint_url: str = \"https://api.minimax.chat/v1/embeddings\"\n    \"\"\"Endpoint URL to use.\"\"\"\n    model: str = \"embo-01\"\n    \"\"\"Embeddings model name to use.\"\"\"\n    embed_type_db: str = \"db\"\n    \"\"\"For embed_documents\"\"\"\n    embed_type_query: str = \"query\"\n    \"\"\"For embed_query\"\"\"\n    minimax_group_id: Optional[str] = None\n    \"\"\"Group ID for MiniMax API.\"\"\"\n    minimax_api_key: Optional[str] = None\n    \"\"\"API Key for MiniMax API.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that group id and api key exists in environment.\"\"\"\n        minimax_group_id = get_from_dict_or_env(\n            values, \"minimax_group_id\", \"MINIMAX_GROUP_ID\"\n        )\n        minimax_api_key = get_from_dict_or_env(\n            values, \"minimax_api_key\", \"MINIMAX_API_KEY\"\n        )\n        values[\"minimax_group_id\"] = minimax_group_id\n        values[\"minimax_api_key\"] = minimax_api_key\n        return values\n[docs]    def embed(\n        self,\n        texts: List[str],\n        embed_type: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html"}
{"id": "7a8f81a035e7-2", "text": "self,\n        texts: List[str],\n        embed_type: str,\n    ) -> List[List[float]]:\n        payload = {\n            \"model\": self.model,\n            \"type\": embed_type,\n            \"texts\": texts,\n        }\n        # HTTP headers for authorization\n        headers = {\n            \"Authorization\": f\"Bearer {self.minimax_api_key}\",\n            \"Content-Type\": \"application/json\",\n        }\n        params = {\n            \"GroupId\": self.minimax_group_id,\n        }\n        # send request\n        response = requests.post(\n            self.endpoint_url, params=params, headers=headers, json=payload\n        )\n        parsed_response = response.json()\n        # check for errors\n        if parsed_response[\"base_resp\"][\"status_code\"] != 0:\n            raise ValueError(\n                f\"MiniMax API returned an error: {parsed_response['base_resp']}\"\n            )\n        embeddings = parsed_response[\"vectors\"]\n        return embeddings\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Embed documents using a MiniMax embedding endpoint.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        embeddings = embed_with_retry(self, texts=texts, embed_type=self.embed_type_db)\n        return embeddings\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed a query using a MiniMax embedding endpoint.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        embeddings = embed_with_retry(\n            self, texts=[text], embed_type=self.embed_type_query\n        )\n        return embeddings[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html"}
{"id": "7fab94c26398-0", "text": "Source code for langchain.embeddings.xinference\n\"\"\"Wrapper around Xinference embedding models.\"\"\"\nfrom typing import Any, List, Optional\nfrom langchain.schema.embeddings import Embeddings\n[docs]class XinferenceEmbeddings(Embeddings):\n    \"\"\"Xinference embedding models.\n    To use, you should have the xinference library installed:\n    .. code-block:: bash\n        pip install xinference\n    Check out: https://github.com/xorbitsai/inference\n    To run, you need to start a Xinference supervisor on one server and Xinference workers on the other servers.\n    Example:\n        To start a local instance of Xinference, run\n        .. code-block:: bash\n           $ xinference\n        You can also deploy Xinference in a distributed cluster. Here are the steps:\n        Starting the supervisor:\n        .. code-block:: bash\n           $ xinference-supervisor\n        Starting the worker:\n        .. code-block:: bash\n           $ xinference-worker\n    Then, launch a model using command line interface (CLI).\n    Example:\n    .. code-block:: bash\n       $ xinference launch -n orca -s 3 -q q4_0\n    It will return a model UID. Then you can use Xinference Embedding with LangChain.\n    Example:\n    .. code-block:: python\n        from langchain.embeddings import XinferenceEmbeddings\n        xinference = XinferenceEmbeddings(\n            server_url=\"http://0.0.0.0:9997\",\n            model_uid = {model_uid} # replace model_uid with the model UID return from launching the model\n        )\n    \"\"\"  # noqa: E501\n    client: Any\n    server_url: Optional[str]\n    \"\"\"URL of the xinference server\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/xinference.html"}
{"id": "7fab94c26398-1", "text": "server_url: Optional[str]\n    \"\"\"URL of the xinference server\"\"\"\n    model_uid: Optional[str]\n    \"\"\"UID of the launched model\"\"\"\n[docs]    def __init__(\n        self, server_url: Optional[str] = None, model_uid: Optional[str] = None\n    ):\n        try:\n            from xinference.client import RESTfulClient\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import RESTfulClient from xinference. Please install it\"\n                \" with `pip install xinference`.\"\n            ) from e\n        super().__init__()\n        if server_url is None:\n            raise ValueError(\"Please provide server URL\")\n        if model_uid is None:\n            raise ValueError(\"Please provide the model UID\")\n        self.server_url = server_url\n        self.model_uid = model_uid\n        self.client = RESTfulClient(server_url)\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Embed a list of documents using Xinference.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        model = self.client.get_model(self.model_uid)\n        embeddings = [\n            model.create_embedding(text)[\"data\"][0][\"embedding\"] for text in texts\n        ]\n        return [list(map(float, e)) for e in embeddings]\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed a query of documents using Xinference.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        model = self.client.get_model(self.model_uid)\n        embedding_res = model.create_embedding(text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/xinference.html"}
{"id": "7fab94c26398-2", "text": "embedding_res = model.create_embedding(text)\n        embedding = embedding_res[\"data\"][0][\"embedding\"]\n        return list(map(float, embedding))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/xinference.html"}
{"id": "54e63e26bebb-0", "text": "Source code for langchain.embeddings.huggingface\nfrom typing import Any, Dict, List, Optional\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field\nfrom langchain.schema.embeddings import Embeddings\nDEFAULT_MODEL_NAME = \"sentence-transformers/all-mpnet-base-v2\"\nDEFAULT_INSTRUCT_MODEL = \"hkunlp/instructor-large\"\nDEFAULT_BGE_MODEL = \"BAAI/bge-large-en\"\nDEFAULT_EMBED_INSTRUCTION = \"Represent the document for retrieval: \"\nDEFAULT_QUERY_INSTRUCTION = (\n    \"Represent the question for retrieving supporting documents: \"\n)\nDEFAULT_QUERY_BGE_INSTRUCTION_EN = (\n    \"Represent this question for searching relevant passages: \"\n)\nDEFAULT_QUERY_BGE_INSTRUCTION_ZH = \"\u4e3a\u8fd9\u4e2a\u53e5\u5b50\u751f\u6210\u8868\u793a\u4ee5\u7528\u4e8e\u68c0\u7d22\u76f8\u5173\u6587\u7ae0\uff1a\"\n[docs]class HuggingFaceEmbeddings(BaseModel, Embeddings):\n    \"\"\"HuggingFace sentence_transformers embedding models.\n    To use, you should have the ``sentence_transformers`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import HuggingFaceEmbeddings\n            model_name = \"sentence-transformers/all-mpnet-base-v2\"\n            model_kwargs = {'device': 'cpu'}\n            encode_kwargs = {'normalize_embeddings': False}\n            hf = HuggingFaceEmbeddings(\n                model_name=model_name,\n                model_kwargs=model_kwargs,\n                encode_kwargs=encode_kwargs\n            )\n    \"\"\"\n    client: Any  #: :meta private:\n    model_name: str = DEFAULT_MODEL_NAME\n    \"\"\"Model name to use.\"\"\"\n    cache_folder: Optional[str] = None\n    \"\"\"Path to store models. \n    Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html"}
{"id": "54e63e26bebb-1", "text": "Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    encode_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Keyword arguments to pass when calling the `encode` method of the model.\"\"\"\n    multi_process: bool = False\n    \"\"\"Run encode() on multiple GPUs.\"\"\"\n    def __init__(self, **kwargs: Any):\n        \"\"\"Initialize the sentence_transformer.\"\"\"\n        super().__init__(**kwargs)\n        try:\n            import sentence_transformers\n        except ImportError as exc:\n            raise ImportError(\n                \"Could not import sentence_transformers python package. \"\n                \"Please install it with `pip install sentence-transformers`.\"\n            ) from exc\n        self.client = sentence_transformers.SentenceTransformer(\n            self.model_name, cache_folder=self.cache_folder, **self.model_kwargs\n        )\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Compute doc embeddings using a HuggingFace transformer model.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        import sentence_transformers\n        texts = list(map(lambda x: x.replace(\"\\n\", \" \"), texts))\n        if self.multi_process:\n            pool = self.client.start_multi_process_pool()\n            embeddings = self.client.encode_multi_process(texts, pool)\n            sentence_transformers.SentenceTransformer.stop_multi_process_pool(pool)\n        else:\n            embeddings = self.client.encode(texts, **self.encode_kwargs)\n        return embeddings.tolist()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html"}
{"id": "54e63e26bebb-2", "text": "return embeddings.tolist()\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Compute query embeddings using a HuggingFace transformer model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        return self.embed_documents([text])[0]\n[docs]class HuggingFaceInstructEmbeddings(BaseModel, Embeddings):\n    \"\"\"Wrapper around sentence_transformers embedding models.\n    To use, you should have the ``sentence_transformers``\n    and ``InstructorEmbedding`` python packages installed.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import HuggingFaceInstructEmbeddings\n            model_name = \"hkunlp/instructor-large\"\n            model_kwargs = {'device': 'cpu'}\n            encode_kwargs = {'normalize_embeddings': True}\n            hf = HuggingFaceInstructEmbeddings(\n                model_name=model_name,\n                model_kwargs=model_kwargs,\n                encode_kwargs=encode_kwargs\n            )\n    \"\"\"\n    client: Any  #: :meta private:\n    model_name: str = DEFAULT_INSTRUCT_MODEL\n    \"\"\"Model name to use.\"\"\"\n    cache_folder: Optional[str] = None\n    \"\"\"Path to store models. \n    Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    encode_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Keyword arguments to pass when calling the `encode` method of the model.\"\"\"\n    embed_instruction: str = DEFAULT_EMBED_INSTRUCTION\n    \"\"\"Instruction to use for embedding documents.\"\"\"\n    query_instruction: str = DEFAULT_QUERY_INSTRUCTION", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html"}
{"id": "54e63e26bebb-3", "text": "query_instruction: str = DEFAULT_QUERY_INSTRUCTION\n    \"\"\"Instruction to use for embedding query.\"\"\"\n    def __init__(self, **kwargs: Any):\n        \"\"\"Initialize the sentence_transformer.\"\"\"\n        super().__init__(**kwargs)\n        try:\n            from InstructorEmbedding import INSTRUCTOR\n            self.client = INSTRUCTOR(\n                self.model_name, cache_folder=self.cache_folder, **self.model_kwargs\n            )\n        except ImportError as e:\n            raise ImportError(\"Dependencies for InstructorEmbedding not found.\") from e\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Compute doc embeddings using a HuggingFace instruct model.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        instruction_pairs = [[self.embed_instruction, text] for text in texts]\n        embeddings = self.client.encode(instruction_pairs, **self.encode_kwargs)\n        return embeddings.tolist()\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Compute query embeddings using a HuggingFace instruct model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        instruction_pair = [self.query_instruction, text]\n        embedding = self.client.encode([instruction_pair], **self.encode_kwargs)[0]\n        return embedding.tolist()\n[docs]class HuggingFaceBgeEmbeddings(BaseModel, Embeddings):\n    \"\"\"HuggingFace BGE sentence_transformers embedding models.\n    To use, you should have the ``sentence_transformers`` python package installed.\n    Example:\n        .. code-block:: python", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html"}
{"id": "54e63e26bebb-4", "text": "Example:\n        .. code-block:: python\n            from langchain.embeddings import HuggingFaceBgeEmbeddings\n            model_name = \"BAAI/bge-large-en\"\n            model_kwargs = {'device': 'cpu'}\n            encode_kwargs = {'normalize_embeddings': True}\n            hf = HuggingFaceBgeEmbeddings(\n                model_name=model_name,\n                model_kwargs=model_kwargs,\n                encode_kwargs=encode_kwargs\n            )\n    \"\"\"\n    client: Any  #: :meta private:\n    model_name: str = DEFAULT_BGE_MODEL\n    \"\"\"Model name to use.\"\"\"\n    cache_folder: Optional[str] = None\n    \"\"\"Path to store models.\n    Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    encode_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Keyword arguments to pass when calling the `encode` method of the model.\"\"\"\n    query_instruction: str = DEFAULT_QUERY_BGE_INSTRUCTION_EN\n    \"\"\"Instruction to use for embedding query.\"\"\"\n    def __init__(self, **kwargs: Any):\n        \"\"\"Initialize the sentence_transformer.\"\"\"\n        super().__init__(**kwargs)\n        try:\n            import sentence_transformers\n        except ImportError as exc:\n            raise ImportError(\n                \"Could not import sentence_transformers python package. \"\n                \"Please install it with `pip install sentence_transformers`.\"\n            ) from exc\n        self.client = sentence_transformers.SentenceTransformer(\n            self.model_name, cache_folder=self.cache_folder, **self.model_kwargs\n        )\n        if \"-zh\" in self.model_name:\n            self.query_instruction = DEFAULT_QUERY_BGE_INSTRUCTION_ZH\n    class Config:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html"}
{"id": "54e63e26bebb-5", "text": "self.query_instruction = DEFAULT_QUERY_BGE_INSTRUCTION_ZH\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Compute doc embeddings using a HuggingFace transformer model.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        texts = [t.replace(\"\\n\", \" \") for t in texts]\n        embeddings = self.client.encode(texts, **self.encode_kwargs)\n        return embeddings.tolist()\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Compute query embeddings using a HuggingFace transformer model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        text = text.replace(\"\\n\", \" \")\n        embedding = self.client.encode(\n            self.query_instruction + text, **self.encode_kwargs\n        )\n        return embedding.tolist()\n[docs]class HuggingFaceInferenceAPIEmbeddings(BaseModel, Embeddings):\n    \"\"\"Embed texts using the HuggingFace API.\n    Requires a HuggingFace Inference API key and a model name.\n    \"\"\"\n    api_key: str\n    \"\"\"Your API key for the HuggingFace Inference API.\"\"\"\n    model_name: str = \"sentence-transformers/all-MiniLM-L6-v2\"\n    \"\"\"The name of the model to use for text embeddings.\"\"\"\n    @property\n    def _api_url(self) -> str:\n        return (\n            \"https://api-inference.huggingface.co\"\n            \"/pipeline\"\n            \"/feature-extraction\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html"}
{"id": "54e63e26bebb-6", "text": "\"/pipeline\"\n            \"/feature-extraction\"\n            f\"/{self.model_name}\"\n        )\n    @property\n    def _headers(self) -> dict:\n        return {\"Authorization\": f\"Bearer {self.api_key}\"}\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Get the embeddings for a list of texts.\n        Args:\n            texts (Documents): A list of texts to get embeddings for.\n        Returns:\n            Embedded texts as List[List[float]], where each inner List[float]\n                corresponds to a single input text.\n        Example:\n            .. code-block:: python\n                from langchain.embeddings import HuggingFaceInferenceAPIEmbeddings\n                hf_embeddings = HuggingFaceInferenceAPIEmbeddings(\n                    api_key=\"your_api_key\",\n                    model_name=\"sentence-transformers/all-MiniLM-l6-v2\"\n                )\n                texts = [\"Hello, world!\", \"How are you?\"]\n                hf_embeddings.embed_documents(texts)\n        \"\"\"\n        response = requests.post(\n            self._api_url,\n            headers=self._headers,\n            json={\n                \"inputs\": texts,\n                \"options\": {\"wait_for_model\": True, \"use_cache\": True},\n            },\n        )\n        return response.json()\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Compute query embeddings using a HuggingFace transformer model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        return self.embed_documents([text])[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html"}
{"id": "ae7aac2da377-0", "text": "Source code for langchain.embeddings.johnsnowlabs\nimport os\nimport sys\nfrom typing import Any, List\nfrom langchain.embeddings.base import Embeddings\nfrom langchain.pydantic_v1 import BaseModel, Extra\n[docs]class JohnSnowLabsEmbeddings(BaseModel, Embeddings):\n    \"\"\"JohnSnowLabs embedding models\n    To use, you should have the ``johnsnowlabs`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings.johnsnowlabs import JohnSnowLabsEmbeddings\n            embedding = JohnSnowLabsEmbeddings(model='embed_sentence.bert')\n            output = embedding.embed_query(\"foo bar\")\n    \"\"\"\n    model: Any = \"embed_sentence.bert\"\n    def __init__(\n        self,\n        model: Any = \"embed_sentence.bert\",\n        hardware_target: str = \"cpu\",\n        **kwargs: Any,\n    ):\n        \"\"\"Initialize the johnsnowlabs model.\"\"\"\n        super().__init__(**kwargs)\n        # 1) Check imports\n        try:\n            from johnsnowlabs import nlp\n            from nlu.pipe.pipeline import NLUPipeline\n        except ImportError as exc:\n            raise ImportError(\n                \"Could not import johnsnowlabs python package. \"\n                \"Please install it with `pip install johnsnowlabs`.\"\n            ) from exc\n        # 2) Start a Spark Session\n        try:\n            os.environ[\"PYSPARK_PYTHON\"] = sys.executable\n            os.environ[\"PYSPARK_DRIVER_PYTHON\"] = sys.executable\n            nlp.start(hardware_target=hardware_target)\n        except Exception as exc:\n            raise Exception(\"Failure starting Spark Session\") from exc\n        # 3) Load the model\n        try:\n            if isinstance(model, str):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/johnsnowlabs.html"}
{"id": "ae7aac2da377-1", "text": "try:\n            if isinstance(model, str):\n                self.model = nlp.load(model)\n            elif isinstance(model, NLUPipeline):\n                self.model = model\n            else:\n                self.model = nlp.to_nlu_pipe(model)\n        except Exception as exc:\n            raise Exception(\"Failure loading model\") from exc\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Compute doc embeddings using a JohnSnowLabs transformer model.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        df = self.model.predict(texts, output_level=\"document\")\n        emb_col = None\n        for c in df.columns:\n            if \"embedding\" in c:\n                emb_col = c\n        return [vec.tolist() for vec in df[emb_col].tolist()]\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Compute query embeddings using a JohnSnowLabs transformer model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        return self.embed_documents([text])[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/johnsnowlabs.html"}
{"id": "cea683f2c53a-0", "text": "Source code for langchain.embeddings.deepinfra\nfrom typing import Any, Dict, List, Mapping, Optional\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\nDEFAULT_MODEL_ID = \"sentence-transformers/clip-ViT-B-32\"\n[docs]class DeepInfraEmbeddings(BaseModel, Embeddings):\n    \"\"\"Deep Infra's embedding inference service.\n    To use, you should have the\n    environment variable ``DEEPINFRA_API_TOKEN`` set with your API token, or pass\n    it as a named parameter to the constructor.\n    There are multiple embeddings models available,\n    see https://deepinfra.com/models?type=embeddings.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import DeepInfraEmbeddings\n            deepinfra_emb = DeepInfraEmbeddings(\n                model_id=\"sentence-transformers/clip-ViT-B-32\",\n                deepinfra_api_token=\"my-api-key\"\n            )\n            r1 = deepinfra_emb.embed_documents(\n                [\n                    \"Alpha is the first letter of Greek alphabet\",\n                    \"Beta is the second letter of Greek alphabet\",\n                ]\n            )\n            r2 = deepinfra_emb.embed_query(\n                \"What is the second letter of Greek alphabet\"\n            )\n    \"\"\"\n    model_id: str = DEFAULT_MODEL_ID\n    \"\"\"Embeddings model to use.\"\"\"\n    normalize: bool = False\n    \"\"\"whether to normalize the computed embeddings\"\"\"\n    embed_instruction: str = \"passage: \"\n    \"\"\"Instruction used to embed documents.\"\"\"\n    query_instruction: str = \"query: \"\n    \"\"\"Instruction used to embed the query.\"\"\"\n    model_kwargs: Optional[dict] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html"}
{"id": "cea683f2c53a-1", "text": "model_kwargs: Optional[dict] = None\n    \"\"\"Other model keyword args\"\"\"\n    deepinfra_api_token: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        deepinfra_api_token = get_from_dict_or_env(\n            values, \"deepinfra_api_token\", \"DEEPINFRA_API_TOKEN\"\n        )\n        values[\"deepinfra_api_token\"] = deepinfra_api_token\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\"model_id\": self.model_id}\n    def _embed(self, input: List[str]) -> List[List[float]]:\n        _model_kwargs = self.model_kwargs or {}\n        # HTTP headers for authorization\n        headers = {\n            \"Authorization\": f\"bearer {self.deepinfra_api_token}\",\n            \"Content-Type\": \"application/json\",\n        }\n        # send request\n        try:\n            res = requests.post(\n                f\"https://api.deepinfra.com/v1/inference/{self.model_id}\",\n                headers=headers,\n                json={\"inputs\": input, \"normalize\": self.normalize, **_model_kwargs},\n            )\n        except requests.exceptions.RequestException as e:\n            raise ValueError(f\"Error raised by inference endpoint: {e}\")\n        if res.status_code != 200:\n            raise ValueError(\n                \"Error raised by inference API HTTP code: %s, %s\"\n                % (res.status_code, res.text)\n            )\n        try:\n            t = res.json()\n            embeddings = t[\"embeddings\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html"}
{"id": "cea683f2c53a-2", "text": "try:\n            t = res.json()\n            embeddings = t[\"embeddings\"]\n        except requests.exceptions.JSONDecodeError as e:\n            raise ValueError(\n                f\"Error raised by inference API: {e}.\\nResponse: {res.text}\"\n            )\n        return embeddings\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Embed documents using a Deep Infra deployed embedding model.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        instruction_pairs = [f\"{self.embed_instruction}{text}\" for text in texts]\n        embeddings = self._embed(instruction_pairs)\n        return embeddings\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed a query using a Deep Infra deployed embedding model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        instruction_pair = f\"{self.query_instruction}{text}\"\n        embedding = self._embed([instruction_pair])[0]\n        return embedding", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html"}
{"id": "57b4ab341798-0", "text": "Source code for langchain.embeddings.dashscope\nfrom __future__ import annotations\nimport logging\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    List,\n    Optional,\n)\nfrom requests.exceptions import HTTPError\nfrom tenacity import (\n    before_sleep_log,\n    retry,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\ndef _create_retry_decorator(embeddings: DashScopeEmbeddings) -> Callable[[Any], Any]:\n    multiplier = 1\n    min_seconds = 1\n    max_seconds = 4\n    # Wait 2^x * 1 second between each retry starting with\n    # 1 seconds, then up to 4 seconds, then 4 seconds afterwards\n    return retry(\n        reraise=True,\n        stop=stop_after_attempt(embeddings.max_retries),\n        wait=wait_exponential(multiplier, min=min_seconds, max=max_seconds),\n        retry=(retry_if_exception_type(HTTPError)),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\n[docs]def embed_with_retry(embeddings: DashScopeEmbeddings, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the embedding call.\"\"\"\n    retry_decorator = _create_retry_decorator(embeddings)\n    @retry_decorator\n    def _embed_with_retry(**kwargs: Any) -> Any:\n        resp = embeddings.client.call(**kwargs)\n        if resp.status_code == 200:\n            return resp.output[\"embeddings\"]\n        elif resp.status_code in [400, 401]:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html"}
{"id": "57b4ab341798-1", "text": "elif resp.status_code in [400, 401]:\n            raise ValueError(\n                f\"status_code: {resp.status_code} \\n \"\n                f\"code: {resp.code} \\n message: {resp.message}\"\n            )\n        else:\n            raise HTTPError(\n                f\"HTTP error occurred: status_code: {resp.status_code} \\n \"\n                f\"code: {resp.code} \\n message: {resp.message}\",\n                response=resp,\n            )\n    return _embed_with_retry(**kwargs)\n[docs]class DashScopeEmbeddings(BaseModel, Embeddings):\n    \"\"\"DashScope embedding models.\n    To use, you should have the ``dashscope`` python package installed, and the\n    environment variable ``DASHSCOPE_API_KEY`` set with your API key or pass it\n    as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import DashScopeEmbeddings\n            embeddings = DashScopeEmbeddings(dashscope_api_key=\"my-api-key\")\n    Example:\n        .. code-block:: python\n            import os\n            os.environ[\"DASHSCOPE_API_KEY\"] = \"your DashScope API KEY\"\n            from langchain.embeddings.dashscope import DashScopeEmbeddings\n            embeddings = DashScopeEmbeddings(\n                model=\"text-embedding-v1\",\n            )\n            text = \"This is a test query.\"\n            query_result = embeddings.embed_query(text)\n    \"\"\"\n    client: Any  #: :meta private:\n    \"\"\"The DashScope client.\"\"\"\n    model: str = \"text-embedding-v1\"\n    dashscope_api_key: Optional[str] = None\n    max_retries: int = 5\n    \"\"\"Maximum number of retries to make when generating.\"\"\"\n    class Config:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html"}
{"id": "57b4ab341798-2", "text": "\"\"\"Maximum number of retries to make when generating.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        import dashscope\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"dashscope_api_key\"] = get_from_dict_or_env(\n            values, \"dashscope_api_key\", \"DASHSCOPE_API_KEY\"\n        )\n        dashscope.api_key = values[\"dashscope_api_key\"]\n        try:\n            import dashscope\n            values[\"client\"] = dashscope.TextEmbedding\n        except ImportError:\n            raise ImportError(\n                \"Could not import dashscope python package. \"\n                \"Please install it with `pip install dashscope`.\"\n            )\n        return values\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Call out to DashScope's embedding endpoint for embedding search docs.\n        Args:\n            texts: The list of texts to embed.\n            chunk_size: The chunk size of embeddings. If None, will use the chunk size\n                specified by the class.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        embeddings = embed_with_retry(\n            self, input=texts, text_type=\"document\", model=self.model\n        )\n        embedding_list = [item[\"embedding\"] for item in embeddings]\n        return embedding_list\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to DashScope's embedding endpoint for embedding query text.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embedding for the text.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html"}
{"id": "57b4ab341798-3", "text": "Returns:\n            Embedding for the text.\n        \"\"\"\n        embedding = embed_with_retry(\n            self, input=text, text_type=\"query\", model=self.model\n        )[0][\"embedding\"]\n        return embedding", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html"}
{"id": "81f8620aaf77-0", "text": "Source code for langchain.embeddings.azure_openai\n\"\"\"Azure OpenAI embeddings wrapper.\"\"\"\nfrom __future__ import annotations\nimport os\nimport warnings\nfrom typing import Dict, Optional, Union\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.utils import get_from_dict_or_env\nfrom langchain.utils.openai import is_openai_v1\n[docs]class AzureOpenAIEmbeddings(OpenAIEmbeddings):\n    \"\"\"`Azure OpenAI` Embeddings API.\"\"\"\n    azure_endpoint: Union[str, None] = None\n    \"\"\"Your Azure endpoint, including the resource.\n        Automatically inferred from env var `AZURE_OPENAI_ENDPOINT` if not provided.\n        \n        Example: `https://example-resource.azure.openai.com/`\n    \"\"\"\n    deployment: Optional[str] = Field(default=None, alias=\"azure_deployment\")\n    \"\"\"A model deployment. \n        If given sets the base client URL to include `/deployments/{azure_deployment}`.\n        Note: this means you won't be able to use non-deployment endpoints.\n    \"\"\"\n    openai_api_key: Union[str, None] = Field(default=None, alias=\"api_key\")\n    \"\"\"Automatically inferred from env var `AZURE_OPENAI_API_KEY` if not provided.\"\"\"\n    azure_ad_token: Union[str, None] = None\n    \"\"\"Your Azure Active Directory token.\n        Automatically inferred from env var `AZURE_OPENAI_AD_TOKEN` if not provided.\n        For more: \n        https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id.\n    \"\"\"  # noqa: E501\n    azure_ad_token_provider: Union[str, None] = None\n    \"\"\"A function that returns an Azure Active Directory token.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/azure_openai.html"}
{"id": "81f8620aaf77-1", "text": "\"\"\"A function that returns an Azure Active Directory token.\n        Will be invoked on every request.\n    \"\"\"\n    openai_api_version: Optional[str] = Field(default=None, alias=\"api_version\")\n    \"\"\"Automatically inferred from env var `OPENAI_API_VERSION` if not provided.\"\"\"\n    validate_base_url: bool = True\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        # Check OPENAI_KEY for backwards compatibility.\n        # TODO: Remove OPENAI_API_KEY support to avoid possible conflict when using\n        # other forms of azure credentials.\n        values[\"openai_api_key\"] = (\n            values[\"openai_api_key\"]\n            or os.getenv(\"AZURE_OPENAI_API_KEY\")\n            or os.getenv(\"OPENAI_API_KEY\")\n        )\n        values[\"openai_api_base\"] = values[\"openai_api_base\"] or os.getenv(\n            \"OPENAI_API_BASE\"\n        )\n        values[\"openai_api_version\"] = values[\"openai_api_version\"] or os.getenv(\n            \"OPENAI_API_VERSION\", default=\"2023-05-15\"\n        )\n        values[\"openai_api_type\"] = get_from_dict_or_env(\n            values, \"openai_api_type\", \"OPENAI_API_TYPE\", default=\"azure\"\n        )\n        values[\"openai_organization\"] = (\n            values[\"openai_organization\"]\n            or os.getenv(\"OPENAI_ORG_ID\")\n            or os.getenv(\"OPENAI_ORGANIZATION\")\n        )\n        values[\"openai_proxy\"] = get_from_dict_or_env(\n            values,\n            \"openai_proxy\",\n            \"OPENAI_PROXY\",\n            default=\"\",\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/azure_openai.html"}
{"id": "81f8620aaf77-2", "text": "\"OPENAI_PROXY\",\n            default=\"\",\n        )\n        values[\"azure_endpoint\"] = values[\"azure_endpoint\"] or os.getenv(\n            \"AZURE_OPENAI_ENDPOINT\"\n        )\n        values[\"azure_ad_token\"] = values[\"azure_ad_token\"] or os.getenv(\n            \"AZURE_OPENAI_AD_TOKEN\"\n        )\n        try:\n            import openai\n        except ImportError:\n            raise ImportError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\"\n            )\n        if is_openai_v1():\n            # For backwards compatibility. Before openai v1, no distinction was made\n            # between azure_endpoint and base_url (openai_api_base).\n            openai_api_base = values[\"openai_api_base\"]\n            if openai_api_base and values[\"validate_base_url\"]:\n                if \"/openai\" not in openai_api_base:\n                    values[\"openai_api_base\"] += \"/openai\"\n                    warnings.warn(\n                        \"As of openai>=1.0.0, Azure endpoints should be specified via \"\n                        f\"the `azure_endpoint` param not `openai_api_base` \"\n                        f\"(or alias `base_url`). Updating `openai_api_base` from \"\n                        f\"{openai_api_base} to {values['openai_api_base']}.\"\n                    )\n                if values[\"deployment\"]:\n                    warnings.warn(\n                        \"As of openai>=1.0.0, if `deployment` (or alias \"\n                        \"`azure_deployment`) is specified then \"\n                        \"`openai_api_base` (or alias `base_url`) should not be. \"\n                        \"Instead use `deployment` (or alias `azure_deployment`) \"\n                        \"and `azure_endpoint`.\"\n                    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/azure_openai.html"}
{"id": "81f8620aaf77-3", "text": "\"and `azure_endpoint`.\"\n                    )\n                    if values[\"deployment\"] not in values[\"openai_api_base\"]:\n                        warnings.warn(\n                            \"As of openai>=1.0.0, if `openai_api_base` \"\n                            \"(or alias `base_url`) is specified it is expected to be \"\n                            \"of the form \"\n                            \"https://example-resource.azure.openai.com/openai/deployments/example-deployment. \"  # noqa: E501\n                            f\"Updating {openai_api_base} to \"\n                            f\"{values['openai_api_base']}.\"\n                        )\n                        values[\"openai_api_base\"] += (\n                            \"/deployments/\" + values[\"deployment\"]\n                        )\n                    values[\"deployment\"] = None\n            client_params = {\n                \"api_version\": values[\"openai_api_version\"],\n                \"azure_endpoint\": values[\"azure_endpoint\"],\n                \"azure_deployment\": values[\"deployment\"],\n                \"api_key\": values[\"openai_api_key\"],\n                \"azure_ad_token\": values[\"azure_ad_token\"],\n                \"azure_ad_token_provider\": values[\"azure_ad_token_provider\"],\n                \"organization\": values[\"openai_organization\"],\n                \"base_url\": values[\"openai_api_base\"],\n                \"timeout\": values[\"request_timeout\"],\n                \"max_retries\": values[\"max_retries\"],\n                \"default_headers\": values[\"default_headers\"],\n                \"default_query\": values[\"default_query\"],\n                \"http_client\": values[\"http_client\"],\n            }\n            values[\"client\"] = openai.AzureOpenAI(**client_params).embeddings\n            values[\"async_client\"] = openai.AsyncAzureOpenAI(**client_params).embeddings\n        else:\n            values[\"client\"] = openai.Embedding\n        return values\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/azure_openai.html"}
{"id": "81f8620aaf77-4", "text": "values[\"client\"] = openai.Embedding\n        return values\n    @property\n    def _llm_type(self) -> str:\n        return \"azure-openai-chat\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/azure_openai.html"}
{"id": "054b9abd8a46-0", "text": "Source code for langchain.embeddings.vertexai\nfrom typing import Dict, List\nfrom langchain.llms.vertexai import _VertexAICommon\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utilities.vertexai import raise_vertex_import_error\n[docs]class VertexAIEmbeddings(_VertexAICommon, Embeddings):\n    \"\"\"Google Cloud VertexAI embedding models.\"\"\"\n    model_name: str = \"textembedding-gecko\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validates that the python package exists in environment.\"\"\"\n        cls._try_init_vertexai(values)\n        try:\n            from vertexai.preview.language_models import TextEmbeddingModel\n        except ImportError:\n            raise_vertex_import_error()\n        values[\"client\"] = TextEmbeddingModel.from_pretrained(values[\"model_name\"])\n        return values\n[docs]    def embed_documents(\n        self, texts: List[str], batch_size: int = 5\n    ) -> List[List[float]]:\n        \"\"\"Embed a list of strings. Vertex AI currently\n        sets a max batch size of 5 strings.\n        Args:\n            texts: List[str] The list of strings to embed.\n            batch_size: [int] The batch size of embeddings to send to the model\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        embeddings = []\n        for batch in range(0, len(texts), batch_size):\n            text_batch = texts[batch : batch + batch_size]\n            embeddings_batch = self.client.get_embeddings(text_batch)\n            embeddings.extend([el.values for el in embeddings_batch])\n        return embeddings\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed a text.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/vertexai.html"}
{"id": "054b9abd8a46-1", "text": "\"\"\"Embed a text.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embedding for the text.\n        \"\"\"\n        embeddings = self.client.get_embeddings([text])\n        return embeddings[0].values", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/vertexai.html"}
{"id": "e6ce46a2da38-0", "text": "Source code for langchain.embeddings.google_palm\nfrom __future__ import annotations\nimport logging\nfrom typing import Any, Callable, Dict, List, Optional\nfrom tenacity import (\n    before_sleep_log,\n    retry,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\ndef _create_retry_decorator() -> Callable[[Any], Any]:\n    \"\"\"Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions\"\"\"\n    import google.api_core.exceptions\n    multiplier = 2\n    min_seconds = 1\n    max_seconds = 60\n    max_retries = 10\n    return retry(\n        reraise=True,\n        stop=stop_after_attempt(max_retries),\n        wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds),\n        retry=(\n            retry_if_exception_type(google.api_core.exceptions.ResourceExhausted)\n            | retry_if_exception_type(google.api_core.exceptions.ServiceUnavailable)\n            | retry_if_exception_type(google.api_core.exceptions.GoogleAPIError)\n        ),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\n[docs]def embed_with_retry(\n    embeddings: GooglePalmEmbeddings, *args: Any, **kwargs: Any\n) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    retry_decorator = _create_retry_decorator()\n    @retry_decorator\n    def _embed_with_retry(*args: Any, **kwargs: Any) -> Any:\n        return embeddings.client.generate_embeddings(*args, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/google_palm.html"}
{"id": "e6ce46a2da38-1", "text": "return embeddings.client.generate_embeddings(*args, **kwargs)\n    return _embed_with_retry(*args, **kwargs)\n[docs]class GooglePalmEmbeddings(BaseModel, Embeddings):\n    \"\"\"Google's PaLM Embeddings APIs.\"\"\"\n    client: Any\n    google_api_key: Optional[str]\n    model_name: str = \"models/embedding-gecko-001\"\n    \"\"\"Model name to use.\"\"\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate api key, python package exists.\"\"\"\n        google_api_key = get_from_dict_or_env(\n            values, \"google_api_key\", \"GOOGLE_API_KEY\"\n        )\n        try:\n            import google.generativeai as genai\n            genai.configure(api_key=google_api_key)\n        except ImportError:\n            raise ImportError(\"Could not import google.generativeai python package.\")\n        values[\"client\"] = genai\n        return values\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        return [self.embed_query(text) for text in texts]\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed query text.\"\"\"\n        embedding = embed_with_retry(self, self.model_name, text)\n        return embedding[\"embedding\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/google_palm.html"}
{"id": "0f45dd3b4937-0", "text": "Source code for langchain.embeddings.localai\nfrom __future__ import annotations\nimport logging\nimport warnings\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    List,\n    Literal,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    Union,\n)\nfrom tenacity import (\n    AsyncRetrying,\n    before_sleep_log,\n    retry,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env, get_pydantic_field_names\nlogger = logging.getLogger(__name__)\ndef _create_retry_decorator(embeddings: LocalAIEmbeddings) -> Callable[[Any], Any]:\n    import openai\n    min_seconds = 4\n    max_seconds = 10\n    # Wait 2^x * 1 second between each retry starting with\n    # 4 seconds, then up to 10 seconds, then 10 seconds afterwards\n    return retry(\n        reraise=True,\n        stop=stop_after_attempt(embeddings.max_retries),\n        wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),\n        retry=(\n            retry_if_exception_type(openai.error.Timeout)\n            | retry_if_exception_type(openai.error.APIError)\n            | retry_if_exception_type(openai.error.APIConnectionError)\n            | retry_if_exception_type(openai.error.RateLimitError)\n            | retry_if_exception_type(openai.error.ServiceUnavailableError)\n        ),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\ndef _async_retry_decorator(embeddings: LocalAIEmbeddings) -> Any:\n    import openai", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html"}
{"id": "0f45dd3b4937-1", "text": "import openai\n    min_seconds = 4\n    max_seconds = 10\n    # Wait 2^x * 1 second between each retry starting with\n    # 4 seconds, then up to 10 seconds, then 10 seconds afterwards\n    async_retrying = AsyncRetrying(\n        reraise=True,\n        stop=stop_after_attempt(embeddings.max_retries),\n        wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),\n        retry=(\n            retry_if_exception_type(openai.error.Timeout)\n            | retry_if_exception_type(openai.error.APIError)\n            | retry_if_exception_type(openai.error.APIConnectionError)\n            | retry_if_exception_type(openai.error.RateLimitError)\n            | retry_if_exception_type(openai.error.ServiceUnavailableError)\n        ),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\n    def wrap(func: Callable) -> Callable:\n        async def wrapped_f(*args: Any, **kwargs: Any) -> Callable:\n            async for _ in async_retrying:\n                return await func(*args, **kwargs)\n            raise AssertionError(\"this is unreachable\")\n        return wrapped_f\n    return wrap\n# https://stackoverflow.com/questions/76469415/getting-embeddings-of-length-1-from-langchain-openaiembeddings\ndef _check_response(response: dict) -> dict:\n    if any(len(d[\"embedding\"]) == 1 for d in response[\"data\"]):\n        import openai\n        raise openai.error.APIError(\"LocalAI API returned an empty embedding\")\n    return response\n[docs]def embed_with_retry(embeddings: LocalAIEmbeddings, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the embedding call.\"\"\"\n    retry_decorator = _create_retry_decorator(embeddings)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html"}
{"id": "0f45dd3b4937-2", "text": "retry_decorator = _create_retry_decorator(embeddings)\n    @retry_decorator\n    def _embed_with_retry(**kwargs: Any) -> Any:\n        response = embeddings.client.create(**kwargs)\n        return _check_response(response)\n    return _embed_with_retry(**kwargs)\n[docs]async def async_embed_with_retry(embeddings: LocalAIEmbeddings, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the embedding call.\"\"\"\n    @_async_retry_decorator(embeddings)\n    async def _async_embed_with_retry(**kwargs: Any) -> Any:\n        response = await embeddings.client.acreate(**kwargs)\n        return _check_response(response)\n    return await _async_embed_with_retry(**kwargs)\n[docs]class LocalAIEmbeddings(BaseModel, Embeddings):\n    \"\"\"LocalAI embedding models.\n    Since LocalAI and OpenAI have 1:1 compatibility between APIs, this class\n    uses the ``openai`` Python package's ``openai.Embedding`` as its client.\n    Thus, you should have the ``openai`` python package installed, and defeat\n    the environment variable ``OPENAI_API_KEY`` by setting to a random string.\n    You also need to specify ``OPENAI_API_BASE`` to point to your LocalAI\n    service endpoint.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import LocalAIEmbeddings\n            openai = LocalAIEmbeddings(\n                openai_api_key=\"random-string\",\n                openai_api_base=\"http://localhost:8080\"\n            )\n    \"\"\"\n    client: Any  #: :meta private:\n    model: str = \"text-embedding-ada-002\"\n    deployment: str = model\n    openai_api_version: Optional[str] = None\n    openai_api_base: Optional[str] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html"}
{"id": "0f45dd3b4937-3", "text": "openai_api_base: Optional[str] = None\n    # to support explicit proxy for LocalAI\n    openai_proxy: Optional[str] = None\n    embedding_ctx_length: int = 8191\n    \"\"\"The maximum number of tokens to embed at once.\"\"\"\n    openai_api_key: Optional[str] = None\n    openai_organization: Optional[str] = None\n    allowed_special: Union[Literal[\"all\"], Set[str]] = set()\n    disallowed_special: Union[Literal[\"all\"], Set[str], Sequence[str]] = \"all\"\n    chunk_size: int = 1000\n    \"\"\"Maximum number of texts to embed in each batch\"\"\"\n    max_retries: int = 6\n    \"\"\"Maximum number of retries to make when generating.\"\"\"\n    request_timeout: Optional[Union[float, Tuple[float, float]]] = None\n    \"\"\"Timeout in seconds for the LocalAI request.\"\"\"\n    headers: Any = None\n    show_progress_bar: bool = False\n    \"\"\"Whether to show a progress bar when embedding.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not explicitly specified.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = get_pydantic_field_names(cls)\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name in extra:\n                raise ValueError(f\"Found {field_name} supplied twice.\")\n            if field_name not in all_required_field_names:\n                warnings.warn(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html"}
{"id": "0f45dd3b4937-4", "text": "if field_name not in all_required_field_names:\n                warnings.warn(\n                    f\"\"\"WARNING! {field_name} is not default parameter.\n                    {field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        invalid_model_kwargs = all_required_field_names.intersection(extra.keys())\n        if invalid_model_kwargs:\n            raise ValueError(\n                f\"Parameters {invalid_model_kwargs} should be specified explicitly. \"\n                f\"Instead they were passed in as part of `model_kwargs` parameter.\"\n            )\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"openai_api_key\"] = get_from_dict_or_env(\n            values, \"openai_api_key\", \"OPENAI_API_KEY\"\n        )\n        values[\"openai_api_base\"] = get_from_dict_or_env(\n            values,\n            \"openai_api_base\",\n            \"OPENAI_API_BASE\",\n            default=\"\",\n        )\n        values[\"openai_proxy\"] = get_from_dict_or_env(\n            values,\n            \"openai_proxy\",\n            \"OPENAI_PROXY\",\n            default=\"\",\n        )\n        default_api_version = \"\"\n        values[\"openai_api_version\"] = get_from_dict_or_env(\n            values,\n            \"openai_api_version\",\n            \"OPENAI_API_VERSION\",\n            default=default_api_version,\n        )\n        values[\"openai_organization\"] = get_from_dict_or_env(\n            values,\n            \"openai_organization\",\n            \"OPENAI_ORGANIZATION\",\n            default=\"\",\n        )\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html"}
{"id": "0f45dd3b4937-5", "text": "\"OPENAI_ORGANIZATION\",\n            default=\"\",\n        )\n        try:\n            import openai\n            values[\"client\"] = openai.Embedding\n        except ImportError:\n            raise ImportError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\"\n            )\n        return values\n    @property\n    def _invocation_params(self) -> Dict:\n        openai_args = {\n            \"model\": self.model,\n            \"request_timeout\": self.request_timeout,\n            \"headers\": self.headers,\n            \"api_key\": self.openai_api_key,\n            \"organization\": self.openai_organization,\n            \"api_base\": self.openai_api_base,\n            \"api_version\": self.openai_api_version,\n            **self.model_kwargs,\n        }\n        if self.openai_proxy:\n            import openai\n            openai.proxy = {\n                \"http\": self.openai_proxy,\n                \"https\": self.openai_proxy,\n            }  # type: ignore[assignment]  # noqa: E501\n        return openai_args\n    def _embedding_func(self, text: str, *, engine: str) -> List[float]:\n        \"\"\"Call out to LocalAI's embedding endpoint.\"\"\"\n        # handle large input text\n        if self.model.endswith(\"001\"):\n            # See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500\n            # replace newlines, which can negatively affect performance.\n            text = text.replace(\"\\n\", \" \")\n        return embed_with_retry(\n            self,\n            input=[text],\n            **self._invocation_params,\n        )[\"data\"][0][\"embedding\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html"}
{"id": "0f45dd3b4937-6", "text": "**self._invocation_params,\n        )[\"data\"][0][\"embedding\"]\n    async def _aembedding_func(self, text: str, *, engine: str) -> List[float]:\n        \"\"\"Call out to LocalAI's embedding endpoint.\"\"\"\n        # handle large input text\n        if self.model.endswith(\"001\"):\n            # See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500\n            # replace newlines, which can negatively affect performance.\n            text = text.replace(\"\\n\", \" \")\n        return (\n            await async_embed_with_retry(\n                self,\n                input=[text],\n                **self._invocation_params,\n            )\n        )[\"data\"][0][\"embedding\"]\n[docs]    def embed_documents(\n        self, texts: List[str], chunk_size: Optional[int] = 0\n    ) -> List[List[float]]:\n        \"\"\"Call out to LocalAI's embedding endpoint for embedding search docs.\n        Args:\n            texts: The list of texts to embed.\n            chunk_size: The chunk size of embeddings. If None, will use the chunk size\n                specified by the class.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        # call _embedding_func for each text\n        return [self._embedding_func(text, engine=self.deployment) for text in texts]\n[docs]    async def aembed_documents(\n        self, texts: List[str], chunk_size: Optional[int] = 0\n    ) -> List[List[float]]:\n        \"\"\"Call out to LocalAI's embedding endpoint async for embedding search docs.\n        Args:\n            texts: The list of texts to embed.\n            chunk_size: The chunk size of embeddings. If None, will use the chunk size\n                specified by the class.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html"}
{"id": "0f45dd3b4937-7", "text": "specified by the class.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        embeddings = []\n        for text in texts:\n            response = await self._aembedding_func(text, engine=self.deployment)\n            embeddings.append(response)\n        return embeddings\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to LocalAI's embedding endpoint for embedding query text.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embedding for the text.\n        \"\"\"\n        embedding = self._embedding_func(text, engine=self.deployment)\n        return embedding\n[docs]    async def aembed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to LocalAI's embedding endpoint async for embedding query text.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embedding for the text.\n        \"\"\"\n        embedding = await self._aembedding_func(text, engine=self.deployment)\n        return embedding", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html"}
{"id": "25a7ac7afa19-0", "text": "Source code for langchain.embeddings.embaas\nfrom typing import Any, Dict, List, Mapping, Optional\nimport requests\nfrom typing_extensions import NotRequired, TypedDict\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\n# Currently supported maximum batch size for embedding requests\nMAX_BATCH_SIZE = 256\nEMBAAS_API_URL = \"https://api.embaas.io/v1/embeddings/\"\n[docs]class EmbaasEmbeddingsPayload(TypedDict):\n    \"\"\"Payload for the Embaas embeddings API.\"\"\"\n    model: str\n    texts: List[str]\n    instruction: NotRequired[str]\n[docs]class EmbaasEmbeddings(BaseModel, Embeddings):\n    \"\"\"Embaas's embedding service.\n    To use, you should have the\n    environment variable ``EMBAAS_API_KEY`` set with your API key, or pass\n    it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            # Initialise with default model and instruction\n            from langchain.embeddings import EmbaasEmbeddings\n            emb = EmbaasEmbeddings()\n            # Initialise with custom model and instruction\n            from langchain.embeddings import EmbaasEmbeddings\n            emb_model = \"instructor-large\"\n            emb_inst = \"Represent the Wikipedia document for retrieval\"\n            emb = EmbaasEmbeddings(\n                model=emb_model,\n                instruction=emb_inst\n            )\n    \"\"\"\n    model: str = \"e5-large-v2\"\n    \"\"\"The model used for embeddings.\"\"\"\n    instruction: Optional[str] = None\n    \"\"\"Instruction used for domain-specific embeddings.\"\"\"\n    api_url: str = EMBAAS_API_URL", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html"}
{"id": "25a7ac7afa19-1", "text": "api_url: str = EMBAAS_API_URL\n    \"\"\"The URL for the embaas embeddings API.\"\"\"\n    embaas_api_key: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        embaas_api_key = get_from_dict_or_env(\n            values, \"embaas_api_key\", \"EMBAAS_API_KEY\"\n        )\n        values[\"embaas_api_key\"] = embaas_api_key\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying params.\"\"\"\n        return {\"model\": self.model, \"instruction\": self.instruction}\n    def _generate_payload(self, texts: List[str]) -> EmbaasEmbeddingsPayload:\n        \"\"\"Generates payload for the API request.\"\"\"\n        payload = EmbaasEmbeddingsPayload(texts=texts, model=self.model)\n        if self.instruction:\n            payload[\"instruction\"] = self.instruction\n        return payload\n    def _handle_request(self, payload: EmbaasEmbeddingsPayload) -> List[List[float]]:\n        \"\"\"Sends a request to the Embaas API and handles the response.\"\"\"\n        headers = {\n            \"Authorization\": f\"Bearer {self.embaas_api_key}\",\n            \"Content-Type\": \"application/json\",\n        }\n        response = requests.post(self.api_url, headers=headers, json=payload)\n        response.raise_for_status()\n        parsed_response = response.json()\n        embeddings = [item[\"embedding\"] for item in parsed_response[\"data\"]]\n        return embeddings", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html"}
{"id": "25a7ac7afa19-2", "text": "return embeddings\n    def _generate_embeddings(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Generate embeddings using the Embaas API.\"\"\"\n        payload = self._generate_payload(texts)\n        try:\n            return self._handle_request(payload)\n        except requests.exceptions.RequestException as e:\n            if e.response is None or not e.response.text:\n                raise ValueError(f\"Error raised by embaas embeddings API: {e}\")\n            parsed_response = e.response.json()\n            if \"message\" in parsed_response:\n                raise ValueError(\n                    \"Validation Error raised by embaas embeddings API:\"\n                    f\"{parsed_response['message']}\"\n                )\n            raise\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Get embeddings for a list of texts.\n        Args:\n            texts: The list of texts to get embeddings for.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        batches = [\n            texts[i : i + MAX_BATCH_SIZE] for i in range(0, len(texts), MAX_BATCH_SIZE)\n        ]\n        embeddings = [self._generate_embeddings(batch) for batch in batches]\n        # flatten the list of lists into a single list\n        return [embedding for batch in embeddings for embedding in batch]\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Get embeddings for a single text.\n        Args:\n            text: The text to get embeddings for.\n        Returns:\n            List of embeddings.\n        \"\"\"\n        return self.embed_documents([text])[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html"}
{"id": "0145e31d213d-0", "text": "Source code for langchain.embeddings.cache\n\"\"\"Module contains code for a cache backed embedder.\nThe cache backed embedder is a wrapper around an embedder that caches\nembeddings in a key-value store. The cache is used to avoid recomputing\nembeddings for the same text.\nThe text is hashed and the hash is used as the key in the cache.\n\"\"\"\nfrom __future__ import annotations\nimport hashlib\nimport json\nimport uuid\nfrom functools import partial\nfrom typing import Callable, List, Sequence, Union, cast\nfrom langchain.schema import BaseStore\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.storage.encoder_backed import EncoderBackedStore\nNAMESPACE_UUID = uuid.UUID(int=1985)\ndef _hash_string_to_uuid(input_string: str) -> uuid.UUID:\n    \"\"\"Hash a string and returns the corresponding UUID.\"\"\"\n    hash_value = hashlib.sha1(input_string.encode(\"utf-8\")).hexdigest()\n    return uuid.uuid5(NAMESPACE_UUID, hash_value)\ndef _key_encoder(key: str, namespace: str) -> str:\n    \"\"\"Encode a key.\"\"\"\n    return namespace + str(_hash_string_to_uuid(key))\ndef _create_key_encoder(namespace: str) -> Callable[[str], str]:\n    \"\"\"Create an encoder for a key.\"\"\"\n    return partial(_key_encoder, namespace=namespace)\ndef _value_serializer(value: Sequence[float]) -> bytes:\n    \"\"\"Serialize a value.\"\"\"\n    return json.dumps(value).encode()\ndef _value_deserializer(serialized_value: bytes) -> List[float]:\n    \"\"\"Deserialize a value.\"\"\"\n    return cast(List[float], json.loads(serialized_value.decode()))\n[docs]class CacheBackedEmbeddings(Embeddings):\n    \"\"\"Interface for caching results from embedding models.\n    The interface allows works with any store that implements", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cache.html"}
{"id": "0145e31d213d-1", "text": "The interface allows works with any store that implements\n    the abstract store interface accepting keys of type str and values of list of\n    floats.\n    If need be, the interface can be extended to accept other implementations\n    of the value serializer and deserializer, as well as the key encoder.\n    Examples:\n        .. code-block: python\n            from langchain.embeddings import CacheBackedEmbeddings, OpenAIEmbeddings\n            from langchain.storage import LocalFileStore\n            store = LocalFileStore('./my_cache')\n            underlying_embedder = OpenAIEmbeddings()\n            embedder = CacheBackedEmbeddings.from_bytes_store(\n                underlying_embedder, store, namespace=underlying_embedder.model\n            )\n            # Embedding is computed and cached\n            embeddings = embedder.embed_documents([\"hello\", \"goodbye\"])\n            # Embeddings are retrieved from the cache, no computation is done\n            embeddings = embedder.embed_documents([\"hello\", \"goodbye\"])\n    \"\"\"\n[docs]    def __init__(\n        self,\n        underlying_embeddings: Embeddings,\n        document_embedding_store: BaseStore[str, List[float]],\n    ) -> None:\n        \"\"\"Initialize the embedder.\n        Args:\n            underlying_embeddings: the embedder to use for computing embeddings.\n            document_embedding_store: The store to use for caching document embeddings.\n        \"\"\"\n        super().__init__()\n        self.document_embedding_store = document_embedding_store\n        self.underlying_embeddings = underlying_embeddings\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Embed a list of texts.\n        The method first checks the cache for the embeddings.\n        If the embeddings are not found, the method uses the underlying embedder\n        to embed the documents and stores the results in the cache.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cache.html"}
{"id": "0145e31d213d-2", "text": "to embed the documents and stores the results in the cache.\n        Args:\n            texts: A list of texts to embed.\n        Returns:\n            A list of embeddings for the given texts.\n        \"\"\"\n        vectors: List[Union[List[float], None]] = self.document_embedding_store.mget(\n            texts\n        )\n        missing_indices: List[int] = [\n            i for i, vector in enumerate(vectors) if vector is None\n        ]\n        missing_texts = [texts[i] for i in missing_indices]\n        if missing_texts:\n            missing_vectors = self.underlying_embeddings.embed_documents(missing_texts)\n            self.document_embedding_store.mset(\n                list(zip(missing_texts, missing_vectors))\n            )\n            for index, updated_vector in zip(missing_indices, missing_vectors):\n                vectors[index] = updated_vector\n        return cast(\n            List[List[float]], vectors\n        )  # Nones should have been resolved by now\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed query text.\n        This method does not support caching at the moment.\n        Support for caching queries is easily to implement, but might make\n        sense to hold off to see the most common patterns.\n        If the cache has an eviction policy, we may need to be a bit more careful\n        about sharing the cache between documents and queries. Generally,\n        one is OK evicting query caches, but document caches should be kept.\n        Args:\n            text: The text to embed.\n        Returns:\n            The embedding for the given text.\n        \"\"\"\n        return self.underlying_embeddings.embed_query(text)\n[docs]    @classmethod\n    def from_bytes_store(\n        cls,\n        underlying_embeddings: Embeddings,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cache.html"}
{"id": "0145e31d213d-3", "text": "def from_bytes_store(\n        cls,\n        underlying_embeddings: Embeddings,\n        document_embedding_cache: BaseStore[str, bytes],\n        *,\n        namespace: str = \"\",\n    ) -> CacheBackedEmbeddings:\n        \"\"\"On-ramp that adds the necessary serialization and encoding to the store.\n        Args:\n            underlying_embeddings: The embedder to use for embedding.\n            document_embedding_cache: The cache to use for storing document embeddings.\n            *,\n            namespace: The namespace to use for document cache.\n                       This namespace is used to avoid collisions with other caches.\n                       For example, set it to the name of the embedding model used.\n        \"\"\"\n        namespace = namespace\n        key_encoder = _create_key_encoder(namespace)\n        encoder_backed_store = EncoderBackedStore[str, List[float]](\n            document_embedding_cache,\n            key_encoder,\n            _value_serializer,\n            _value_deserializer,\n        )\n        return cls(underlying_embeddings, encoder_backed_store)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cache.html"}
{"id": "e413f5101d1f-0", "text": "Source code for langchain.embeddings.tensorflow_hub\nfrom typing import Any, List\nfrom langchain.pydantic_v1 import BaseModel, Extra\nfrom langchain.schema.embeddings import Embeddings\nDEFAULT_MODEL_URL = \"https://tfhub.dev/google/universal-sentence-encoder-multilingual/3\"\n[docs]class TensorflowHubEmbeddings(BaseModel, Embeddings):\n    \"\"\"TensorflowHub embedding models.\n    To use, you should have the ``tensorflow_text`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import TensorflowHubEmbeddings\n            url = \"https://tfhub.dev/google/universal-sentence-encoder-multilingual/3\"\n            tf = TensorflowHubEmbeddings(model_url=url)\n    \"\"\"\n    embed: Any  #: :meta private:\n    model_url: str = DEFAULT_MODEL_URL\n    \"\"\"Model name to use.\"\"\"\n    def __init__(self, **kwargs: Any):\n        \"\"\"Initialize the tensorflow_hub and tensorflow_text.\"\"\"\n        super().__init__(**kwargs)\n        try:\n            import tensorflow_hub\n        except ImportError:\n            raise ImportError(\n                \"Could not import tensorflow-hub python package. \"\n                \"Please install it with `pip install tensorflow-hub``.\"\n            )\n        try:\n            import tensorflow_text  # noqa\n        except ImportError:\n            raise ImportError(\n                \"Could not import tensorflow_text python package. \"\n                \"Please install it with `pip install tensorflow_text``.\"\n            )\n        self.embed = tensorflow_hub.load(self.model_url)\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Compute doc embeddings using a TensorflowHub embedding model.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html"}
{"id": "e413f5101d1f-1", "text": "\"\"\"Compute doc embeddings using a TensorflowHub embedding model.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        texts = list(map(lambda x: x.replace(\"\\n\", \" \"), texts))\n        embeddings = self.embed(texts).numpy()\n        return embeddings.tolist()\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Compute query embeddings using a TensorflowHub embedding model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        text = text.replace(\"\\n\", \" \")\n        embedding = self.embed([text]).numpy()[0]\n        return embedding.tolist()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html"}
{"id": "d1618f411224-0", "text": "Source code for langchain.embeddings.fake\nimport hashlib\nfrom typing import List\nimport numpy as np\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema.embeddings import Embeddings\n[docs]class FakeEmbeddings(Embeddings, BaseModel):\n    \"\"\"Fake embedding model.\"\"\"\n    size: int\n    \"\"\"The size of the embedding vector.\"\"\"\n    def _get_embedding(self) -> List[float]:\n        return list(np.random.normal(size=self.size))\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        return [self._get_embedding() for _ in texts]\n[docs]    def embed_query(self, text: str) -> List[float]:\n        return self._get_embedding()\n[docs]class DeterministicFakeEmbedding(Embeddings, BaseModel):\n    \"\"\"\n    Fake embedding model that always returns\n    the same embedding vector for the same text.\n    \"\"\"\n    size: int\n    \"\"\"The size of the embedding vector.\"\"\"\n    def _get_embedding(self, seed: int) -> List[float]:\n        # set the seed for the random generator\n        np.random.seed(seed)\n        return list(np.random.normal(size=self.size))\n    def _get_seed(self, text: str) -> int:\n        \"\"\"\n        Get a seed for the random generator, using the hash of the text.\n        \"\"\"\n        return int(hashlib.sha256(text.encode(\"utf-8\")).hexdigest(), 16) % 10**8\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        return [self._get_embedding(seed=self._get_seed(_)) for _ in texts]\n[docs]    def embed_query(self, text: str) -> List[float]:\n        return self._get_embedding(seed=self._get_seed(text))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/fake.html"}
{"id": "8486bf4035d9-0", "text": "Source code for langchain.embeddings.clarifai\nimport logging\nfrom typing import Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class ClarifaiEmbeddings(BaseModel, Embeddings):\n    \"\"\"Clarifai embedding models.\n    To use, you should have the ``clarifai`` python package installed, and the\n    environment variable ``CLARIFAI_PAT`` set with your personal access token or pass it\n    as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import ClarifaiEmbeddings\n            clarifai = ClarifaiEmbeddings(\n                model=\"embed-english-light-v3.0\", clarifai_api_key=\"my-api-key\"\n            )\n    \"\"\"\n    stub: Any  #: :meta private:\n    \"\"\"Clarifai stub.\"\"\"\n    userDataObject: Any\n    \"\"\"Clarifai user data object.\"\"\"\n    model_id: Optional[str] = None\n    \"\"\"Model id to use.\"\"\"\n    model_version_id: Optional[str] = None\n    \"\"\"Model version id to use.\"\"\"\n    app_id: Optional[str] = None\n    \"\"\"Clarifai application id to use.\"\"\"\n    user_id: Optional[str] = None\n    \"\"\"Clarifai user id to use.\"\"\"\n    pat: Optional[str] = None\n    \"\"\"Clarifai personal access token to use.\"\"\"\n    api_base: str = \"https://api.clarifai.com\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html"}
{"id": "8486bf4035d9-1", "text": "extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"pat\"] = get_from_dict_or_env(values, \"pat\", \"CLARIFAI_PAT\")\n        user_id = values.get(\"user_id\")\n        app_id = values.get(\"app_id\")\n        model_id = values.get(\"model_id\")\n        if values[\"pat\"] is None:\n            raise ValueError(\"Please provide a pat.\")\n        if user_id is None:\n            raise ValueError(\"Please provide a user_id.\")\n        if app_id is None:\n            raise ValueError(\"Please provide a app_id.\")\n        if model_id is None:\n            raise ValueError(\"Please provide a model_id.\")\n        try:\n            from clarifai.auth.helper import ClarifaiAuthHelper\n            from clarifai.client import create_stub\n        except ImportError:\n            raise ImportError(\n                \"Could not import clarifai python package. \"\n                \"Please install it with `pip install clarifai`.\"\n            )\n        auth = ClarifaiAuthHelper(\n            user_id=user_id,\n            app_id=app_id,\n            pat=values[\"pat\"],\n            base=values[\"api_base\"],\n        )\n        values[\"userDataObject\"] = auth.get_user_app_id_proto()\n        values[\"stub\"] = create_stub(auth)\n        return values\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Call out to Clarifai's embedding models.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html"}
{"id": "8486bf4035d9-2", "text": "List of embeddings, one for each text.\n        \"\"\"\n        try:\n            from clarifai_grpc.grpc.api import (\n                resources_pb2,\n                service_pb2,\n            )\n            from clarifai_grpc.grpc.api.status import status_code_pb2\n        except ImportError:\n            raise ImportError(\n                \"Could not import clarifai python package. \"\n                \"Please install it with `pip install clarifai`.\"\n            )\n        batch_size = 32\n        embeddings = []\n        for i in range(0, len(texts), batch_size):\n            batch = texts[i : i + batch_size]\n            post_model_outputs_request = service_pb2.PostModelOutputsRequest(\n                user_app_id=self.userDataObject,\n                model_id=self.model_id,\n                version_id=self.model_version_id,\n                inputs=[\n                    resources_pb2.Input(\n                        data=resources_pb2.Data(text=resources_pb2.Text(raw=t))\n                    )\n                    for t in batch\n                ],\n            )\n            post_model_outputs_response = self.stub.PostModelOutputs(\n                post_model_outputs_request\n            )\n            if post_model_outputs_response.status.code != status_code_pb2.SUCCESS:\n                logger.error(post_model_outputs_response.status)\n                first_output_failure = (\n                    post_model_outputs_response.outputs[0].status\n                    if len(post_model_outputs_response.outputs)\n                    else None\n                )\n                raise Exception(\n                    f\"Post model outputs failed, status: \"\n                    f\"{post_model_outputs_response.status}, first output failure: \"\n                    f\"{first_output_failure}\"\n                )\n            embeddings.extend(\n                [\n                    list(o.data.embeddings[0].vector)\n                    for o in post_model_outputs_response.outputs\n                ]\n            )\n        return embeddings", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html"}
{"id": "8486bf4035d9-3", "text": "for o in post_model_outputs_response.outputs\n                ]\n            )\n        return embeddings\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to Clarifai's embedding models.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        try:\n            from clarifai_grpc.grpc.api import (\n                resources_pb2,\n                service_pb2,\n            )\n            from clarifai_grpc.grpc.api.status import status_code_pb2\n        except ImportError:\n            raise ImportError(\n                \"Could not import clarifai python package. \"\n                \"Please install it with `pip install clarifai`.\"\n            )\n        post_model_outputs_request = service_pb2.PostModelOutputsRequest(\n            user_app_id=self.userDataObject,\n            model_id=self.model_id,\n            version_id=self.model_version_id,\n            inputs=[\n                resources_pb2.Input(\n                    data=resources_pb2.Data(text=resources_pb2.Text(raw=text))\n                )\n            ],\n        )\n        post_model_outputs_response = self.stub.PostModelOutputs(\n            post_model_outputs_request\n        )\n        if post_model_outputs_response.status.code != status_code_pb2.SUCCESS:\n            logger.error(post_model_outputs_response.status)\n            first_output_failure = (\n                post_model_outputs_response.outputs[0].status\n                if len(post_model_outputs_response.outputs[0])\n                else None\n            )\n            raise Exception(\n                f\"Post model outputs failed, status: \"\n                f\"{post_model_outputs_response.status}, first output failure: \"\n                f\"{first_output_failure}\"\n            )\n        embeddings = [\n            list(o.data.embeddings[0].vector)\n            for o in post_model_outputs_response.outputs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html"}
{"id": "8486bf4035d9-4", "text": "for o in post_model_outputs_response.outputs\n        ]\n        return embeddings[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html"}
{"id": "e33a6c51373b-0", "text": "Source code for langchain.embeddings.mosaicml\nfrom typing import Any, Dict, List, Mapping, Optional, Tuple\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\n[docs]class MosaicMLInstructorEmbeddings(BaseModel, Embeddings):\n    \"\"\"MosaicML embedding service.\n    To use, you should have the\n    environment variable ``MOSAICML_API_TOKEN`` set with your API token, or pass\n    it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.llms import MosaicMLInstructorEmbeddings\n            endpoint_url = (\n                \"https://models.hosted-on.mosaicml.hosting/instructor-large/v1/predict\"\n            )\n            mosaic_llm = MosaicMLInstructorEmbeddings(\n                endpoint_url=endpoint_url,\n                mosaicml_api_token=\"my-api-key\"\n            )\n    \"\"\"\n    endpoint_url: str = (\n        \"https://models.hosted-on.mosaicml.hosting/instructor-xl/v1/predict\"\n    )\n    \"\"\"Endpoint URL to use.\"\"\"\n    embed_instruction: str = \"Represent the document for retrieval: \"\n    \"\"\"Instruction used to embed documents.\"\"\"\n    query_instruction: str = (\n        \"Represent the question for retrieving supporting documents: \"\n    )\n    \"\"\"Instruction used to embed the query.\"\"\"\n    retry_sleep: float = 1.0\n    \"\"\"How long to try sleeping for if a rate limit is encountered\"\"\"\n    mosaicml_api_token: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html"}
{"id": "e33a6c51373b-1", "text": "extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        mosaicml_api_token = get_from_dict_or_env(\n            values, \"mosaicml_api_token\", \"MOSAICML_API_TOKEN\"\n        )\n        values[\"mosaicml_api_token\"] = mosaicml_api_token\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\"endpoint_url\": self.endpoint_url}\n    def _embed(\n        self, input: List[Tuple[str, str]], is_retry: bool = False\n    ) -> List[List[float]]:\n        payload = {\"inputs\": input}\n        # HTTP headers for authorization\n        headers = {\n            \"Authorization\": f\"{self.mosaicml_api_token}\",\n            \"Content-Type\": \"application/json\",\n        }\n        # send request\n        try:\n            response = requests.post(self.endpoint_url, headers=headers, json=payload)\n        except requests.exceptions.RequestException as e:\n            raise ValueError(f\"Error raised by inference endpoint: {e}\")\n        try:\n            if response.status_code == 429:\n                if not is_retry:\n                    import time\n                    time.sleep(self.retry_sleep)\n                    return self._embed(input, is_retry=True)\n                raise ValueError(\n                    f\"Error raised by inference API: rate limit exceeded.\\nResponse: \"\n                    f\"{response.text}\"\n                )\n            parsed_response = response.json()\n            # The inference API has changed a couple of times, so we add some handling\n            # to be robust to multiple response formats.\n            if isinstance(parsed_response, dict):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html"}
{"id": "e33a6c51373b-2", "text": "# to be robust to multiple response formats.\n            if isinstance(parsed_response, dict):\n                output_keys = [\"data\", \"output\", \"outputs\"]\n                for key in output_keys:\n                    if key in parsed_response:\n                        output_item = parsed_response[key]\n                        break\n                else:\n                    raise ValueError(\n                        f\"No key data or output in response: {parsed_response}\"\n                    )\n                if isinstance(output_item, list) and isinstance(output_item[0], list):\n                    embeddings = output_item\n                else:\n                    embeddings = [output_item]\n            else:\n                raise ValueError(f\"Unexpected response type: {parsed_response}\")\n        except requests.exceptions.JSONDecodeError as e:\n            raise ValueError(\n                f\"Error raised by inference API: {e}.\\nResponse: {response.text}\"\n            )\n        return embeddings\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Embed documents using a MosaicML deployed instructor embedding model.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        instruction_pairs = [(self.embed_instruction, text) for text in texts]\n        embeddings = self._embed(instruction_pairs)\n        return embeddings\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed a query using a MosaicML deployed instructor embedding model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        instruction_pair = (self.query_instruction, text)\n        embedding = self._embed([instruction_pair])[0]\n        return embedding", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html"}
{"id": "b9d18d92cb29-0", "text": "Source code for langchain.embeddings.gradient_ai\nimport asyncio\nimport logging\nimport os\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import Any, Callable, Dict, List, Optional, Tuple\nimport aiohttp\nimport numpy as np\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\n__all__ = [\"GradientEmbeddings\"]\n[docs]class GradientEmbeddings(BaseModel, Embeddings):\n    \"\"\"Gradient.ai Embedding models.\n    GradientLLM is a class to interact with Embedding Models on gradient.ai\n    To use, set the environment variable ``GRADIENT_ACCESS_TOKEN`` with your\n    API token and ``GRADIENT_WORKSPACE_ID`` for your gradient workspace,\n    or alternatively provide them as keywords to the constructor of this class.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import GradientEmbeddings\n            GradientEmbeddings(\n                model=\"bge-large\",\n                gradient_workspace_id=\"12345614fc0_workspace\",\n                gradient_access_token=\"gradientai-access_token\",\n            )\n    \"\"\"\n    model: str\n    \"Underlying gradient.ai model id.\"\n    gradient_workspace_id: Optional[str] = None\n    \"Underlying gradient.ai workspace_id.\"\n    gradient_access_token: Optional[str] = None\n    \"\"\"gradient.ai API Token, which can be generated by going to\n        https://auth.gradient.ai/select-workspace\n        and selecting \"Access tokens\" under the profile drop-down.\n    \"\"\"\n    gradient_api_url: str = \"https://api.gradient.ai/api\"\n    \"\"\"Endpoint URL to use.\"\"\"\n    client: Any = None  #: :meta private:\n    \"\"\"Gradient client.\"\"\"\n    # LLM call kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html"}
{"id": "b9d18d92cb29-1", "text": "\"\"\"Gradient client.\"\"\"\n    # LLM call kwargs\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator(allow_reuse=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"gradient_access_token\"] = get_from_dict_or_env(\n            values, \"gradient_access_token\", \"GRADIENT_ACCESS_TOKEN\"\n        )\n        values[\"gradient_workspace_id\"] = get_from_dict_or_env(\n            values, \"gradient_workspace_id\", \"GRADIENT_WORKSPACE_ID\"\n        )\n        values[\"gradient_api_url\"] = get_from_dict_or_env(\n            values, \"gradient_api_url\", \"GRADIENT_API_URL\"\n        )\n        values[\"client\"] = TinyAsyncGradientEmbeddingClient(\n            access_token=values[\"gradient_access_token\"],\n            workspace_id=values[\"gradient_workspace_id\"],\n            host=values[\"gradient_api_url\"],\n        )\n        try:\n            import gradientai  # noqa\n        except ImportError:\n            logging.warning(\n                \"DeprecationWarning: `GradientEmbeddings` will use \"\n                \"`pip install gradientai` in future releases of langchain.\"\n            )\n        except Exception:\n            pass\n        return values\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Call out to Gradient's embedding endpoint.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        embeddings = self.client.embed(\n            model=self.model,\n            texts=texts,\n        )\n        return embeddings", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html"}
{"id": "b9d18d92cb29-2", "text": "model=self.model,\n            texts=texts,\n        )\n        return embeddings\n[docs]    async def aembed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Async call out to Gradient's embedding endpoint.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        embeddings = await self.client.aembed(\n            model=self.model,\n            texts=texts,\n        )\n        return embeddings\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to Gradient's embedding endpoint.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        return self.embed_documents([text])[0]\n[docs]    async def aembed_query(self, text: str) -> List[float]:\n        \"\"\"Async call out to Gradient's embedding endpoint.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        embeddings = await self.aembed_documents([text])\n        return embeddings[0]\n[docs]class TinyAsyncGradientEmbeddingClient:  #: :meta private:\n    \"\"\"A helper tool to embed Gradient. Not part of Langchain's or Gradients stable API,\n    direct use discouraged.\n    To use, set the environment variable ``GRADIENT_ACCESS_TOKEN`` with your\n    API token and ``GRADIENT_WORKSPACE_ID`` for your gradient workspace,\n    or alternatively provide them as keywords to the constructor of this class.\n    Example:\n        .. code-block:: python\n            mini_client = TinyAsyncGradientEmbeddingClient(\n                workspace_id=\"12345614fc0_workspace\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html"}
{"id": "b9d18d92cb29-3", "text": "workspace_id=\"12345614fc0_workspace\",\n                access_token=\"gradientai-access_token\",\n            )\n            embeds = mini_client.embed(\n                model=\"bge-large\",\n                text=[\"doc1\", \"doc2\"]\n            )\n            # or\n            embeds = await mini_client.aembed(\n                model=\"bge-large\",\n                text=[\"doc1\", \"doc2\"]\n            )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        access_token: Optional[str] = None,\n        workspace_id: Optional[str] = None,\n        host: str = \"https://api.gradient.ai/api\",\n        aiosession: Optional[aiohttp.ClientSession] = None,\n    ) -> None:\n        self.access_token = access_token or os.environ.get(\n            \"GRADIENT_ACCESS_TOKEN\", None\n        )\n        self.workspace_id = workspace_id or os.environ.get(\n            \"GRADIENT_WORKSPACE_ID\", None\n        )\n        self.host = host\n        self.aiosession = aiosession\n        if self.access_token is None or len(self.access_token) < 10:\n            raise ValueError(\n                \"env variable `GRADIENT_ACCESS_TOKEN` or \"\n                \" param `access_token` must be set \"\n            )\n        if self.workspace_id is None or len(self.workspace_id) < 3:\n            raise ValueError(\n                \"env variable `GRADIENT_WORKSPACE_ID` or \"\n                \" param `workspace_id` must be set\"\n            )\n        if self.host is None or len(self.host) < 3:\n            raise ValueError(\" param `host` must be set to a valid url\")\n        self._batch_size = 128\n    @staticmethod\n    def _permute(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html"}
{"id": "b9d18d92cb29-4", "text": "self._batch_size = 128\n    @staticmethod\n    def _permute(\n        texts: List[str], sorter: Callable = len\n    ) -> Tuple[List[str], Callable]:\n        \"\"\"Sort texts in ascending order, and\n        delivers a lambda expr, which can sort a same length list\n        https://github.com/UKPLab/sentence-transformers/blob/\n        c5f93f70eca933c78695c5bc686ceda59651ae3b/sentence_transformers/SentenceTransformer.py#L156\n        Args:\n            texts (List[str]): _description_\n            sorter (Callable, optional): _description_. Defaults to len.\n        Returns:\n            Tuple[List[str], Callable]: _description_\n        Example:\n            ```\n            texts = [\"one\",\"three\",\"four\"]\n            perm_texts, undo = self._permute(texts)\n            texts == undo(perm_texts)\n            ```\n        \"\"\"\n        if len(texts) == 1:\n            # special case query\n            return texts, lambda t: t\n        length_sorted_idx = np.argsort([-sorter(sen) for sen in texts])\n        texts_sorted = [texts[idx] for idx in length_sorted_idx]\n        return texts_sorted, lambda unsorted_embeddings: [  # noqa E731\n            unsorted_embeddings[idx] for idx in np.argsort(length_sorted_idx)\n        ]\n    def _batch(self, texts: List[str]) -> List[List[str]]:\n        \"\"\"\n        splits Lists of text parts into batches of size max `self._batch_size`\n        When encoding vector database,\n        Args:\n            texts (List[str]): List of sentences\n            self._batch_size (int, optional): max batch size of one request.\n        Returns:\n            List[List[str]]: Batches of List of sentences", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html"}
{"id": "b9d18d92cb29-5", "text": "Returns:\n            List[List[str]]: Batches of List of sentences\n        \"\"\"\n        if len(texts) == 1:\n            # special case query\n            return [texts]\n        batches = []\n        for start_index in range(0, len(texts), self._batch_size):\n            batches.append(texts[start_index : start_index + self._batch_size])\n        return batches\n    @staticmethod\n    def _unbatch(batch_of_texts: List[List[Any]]) -> List[Any]:\n        if len(batch_of_texts) == 1 and len(batch_of_texts[0]) == 1:\n            # special case query\n            return batch_of_texts[0]\n        texts = []\n        for sublist in batch_of_texts:\n            texts.extend(sublist)\n        return texts\n    def _kwargs_post_request(self, model: str, texts: List[str]) -> Dict[str, Any]:\n        \"\"\"Build the kwargs for the Post request, used by sync\n        Args:\n            model (str): _description_\n            texts (List[str]): _description_\n        Returns:\n            Dict[str, Collection[str]]: _description_\n        \"\"\"\n        return dict(\n            url=f\"{self.host}/embeddings/{model}\",\n            headers={\n                \"authorization\": f\"Bearer {self.access_token}\",\n                \"x-gradient-workspace-id\": f\"{self.workspace_id}\",\n                \"accept\": \"application/json\",\n                \"content-type\": \"application/json\",\n            },\n            json=dict(\n                inputs=[{\"input\": i} for i in texts],\n            ),\n        )\n    def _sync_request_embed(\n        self, model: str, batch_texts: List[str]\n    ) -> List[List[float]]:\n        response = requests.post(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html"}
{"id": "b9d18d92cb29-6", "text": ") -> List[List[float]]:\n        response = requests.post(\n            **self._kwargs_post_request(model=model, texts=batch_texts)\n        )\n        if response.status_code != 200:\n            raise Exception(\n                f\"Gradient returned an unexpected response with status \"\n                f\"{response.status_code}: {response.text}\"\n            )\n        return [e[\"embedding\"] for e in response.json()[\"embeddings\"]]\n[docs]    def embed(self, model: str, texts: List[str]) -> List[List[float]]:\n        \"\"\"call the embedding of model\n        Args:\n            model (str): to embedding model\n            texts (List[str]): List of sentences to embed.\n        Returns:\n            List[List[float]]: List of vectors for each sentence\n        \"\"\"\n        perm_texts, unpermute_func = self._permute(texts)\n        perm_texts_batched = self._batch(perm_texts)\n        # Request\n        map_args = (\n            self._sync_request_embed,\n            [model] * len(perm_texts_batched),\n            perm_texts_batched,\n        )\n        if len(perm_texts_batched) == 1:\n            embeddings_batch_perm = list(map(*map_args))\n        else:\n            with ThreadPoolExecutor(32) as p:\n                embeddings_batch_perm = list(p.map(*map_args))\n        embeddings_perm = self._unbatch(embeddings_batch_perm)\n        embeddings = unpermute_func(embeddings_perm)\n        return embeddings\n    async def _async_request(\n        self, session: aiohttp.ClientSession, kwargs: Dict[str, Any]\n    ) -> List[List[float]]:\n        async with session.post(**kwargs) as response:\n            if response.status != 200:\n                raise Exception(\n                    f\"Gradient returned an unexpected response with status \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html"}
{"id": "b9d18d92cb29-7", "text": "raise Exception(\n                    f\"Gradient returned an unexpected response with status \"\n                    f\"{response.status}: {response.text}\"\n                )\n            embedding = (await response.json())[\"embeddings\"]\n            return [e[\"embedding\"] for e in embedding]\n[docs]    async def aembed(self, model: str, texts: List[str]) -> List[List[float]]:\n        \"\"\"call the embedding of model, async method\n        Args:\n            model (str): to embedding model\n            texts (List[str]): List of sentences to embed.\n        Returns:\n            List[List[float]]: List of vectors for each sentence\n        \"\"\"\n        perm_texts, unpermute_func = self._permute(texts)\n        perm_texts_batched = self._batch(perm_texts)\n        # Request\n        if self.aiosession is None:\n            self.aiosession = aiohttp.ClientSession(\n                trust_env=True, connector=aiohttp.TCPConnector(limit=32)\n            )\n        async with self.aiosession as session:\n            embeddings_batch_perm = await asyncio.gather(\n                *[\n                    self._async_request(\n                        session=session,\n                        **self._kwargs_post_request(model=model, texts=t),\n                    )\n                    for t in perm_texts_batched\n                ]\n            )\n        embeddings_perm = self._unbatch(embeddings_batch_perm)\n        embeddings = unpermute_func(embeddings_perm)\n        return embeddings", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html"}
{"id": "00ab8dda6dd1-0", "text": "Source code for langchain.embeddings.spacy_embeddings\nimport importlib.util\nfrom typing import Any, Dict, List\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.embeddings import Embeddings\n[docs]class SpacyEmbeddings(BaseModel, Embeddings):\n    \"\"\"Embeddings by SpaCy models.\n    It only supports the 'en_core_web_sm' model.\n    Attributes:\n        nlp (Any): The Spacy model loaded into memory.\n    Methods:\n        embed_documents(texts: List[str]) -> List[List[float]]:\n            Generates embeddings for a list of documents.\n        embed_query(text: str) -> List[float]:\n            Generates an embedding for a single piece of text.\n    \"\"\"\n    nlp: Any  # The Spacy model loaded into memory\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid  # Forbid extra attributes during model initialization\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"\n        Validates that the Spacy package and the 'en_core_web_sm' model are installed.\n        Args:\n            values (Dict): The values provided to the class constructor.\n        Returns:\n            The validated values.\n        Raises:\n            ValueError: If the Spacy package or the 'en_core_web_sm'\n            model are not installed.\n        \"\"\"\n        # Check if the Spacy package is installed\n        if importlib.util.find_spec(\"spacy\") is None:\n            raise ValueError(\n                \"Spacy package not found. \"\n                \"Please install it with `pip install spacy`.\"\n            )\n        try:\n            # Try to load the 'en_core_web_sm' Spacy model\n            import spacy", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/spacy_embeddings.html"}
{"id": "00ab8dda6dd1-1", "text": "import spacy\n            values[\"nlp\"] = spacy.load(\"en_core_web_sm\")\n        except OSError:\n            # If the model is not found, raise a ValueError\n            raise ValueError(\n                \"Spacy model 'en_core_web_sm' not found. \"\n                \"Please install it with\"\n                \" `python -m spacy download en_core_web_sm`.\"\n            )\n        return values  # Return the validated values\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"\n        Generates embeddings for a list of documents.\n        Args:\n            texts (List[str]): The documents to generate embeddings for.\n        Returns:\n            A list of embeddings, one for each document.\n        \"\"\"\n        return [self.nlp(text).vector.tolist() for text in texts]\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"\n        Generates an embedding for a single piece of text.\n        Args:\n            text (str): The text to generate an embedding for.\n        Returns:\n            The embedding for the text.\n        \"\"\"\n        return self.nlp(text).vector.tolist()\n[docs]    async def aembed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"\n        Asynchronously generates embeddings for a list of documents.\n        This method is not implemented and raises a NotImplementedError.\n        Args:\n            texts (List[str]): The documents to generate embeddings for.\n        Raises:\n            NotImplementedError: This method is not implemented.\n        \"\"\"\n        raise NotImplementedError(\"Asynchronous embedding generation is not supported.\")\n[docs]    async def aembed_query(self, text: str) -> List[float]:\n        \"\"\"\n        Asynchronously generates an embedding for a single piece of text.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/spacy_embeddings.html"}
{"id": "00ab8dda6dd1-2", "text": "\"\"\"\n        Asynchronously generates an embedding for a single piece of text.\n        This method is not implemented and raises a NotImplementedError.\n        Args:\n            text (str): The text to generate an embedding for.\n        Raises:\n            NotImplementedError: This method is not implemented.\n        \"\"\"\n        raise NotImplementedError(\"Asynchronous embedding generation is not supported.\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/spacy_embeddings.html"}
{"id": "326b3068e98e-0", "text": "Source code for langchain.embeddings.bedrock\nimport asyncio\nimport json\nimport os\nfrom functools import partial\nfrom typing import Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.embeddings import Embeddings\n[docs]class BedrockEmbeddings(BaseModel, Embeddings):\n    \"\"\"Bedrock embedding models.\n    To authenticate, the AWS client uses the following methods to\n    automatically load credentials:\n    https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\n    If a specific credential profile should be used, you must pass\n    the name of the profile from the ~/.aws/credentials file that is to be used.\n    Make sure the credentials / roles used have the required policies to\n    access the Bedrock service.\n    \"\"\"\n    \"\"\"\n    Example:\n        .. code-block:: python\n            from langchain.bedrock_embeddings import BedrockEmbeddings\n            \n            region_name =\"us-east-1\"\n            credentials_profile_name = \"default\"\n            model_id = \"amazon.titan-embed-text-v1\"\n            be = BedrockEmbeddings(\n                credentials_profile_name=credentials_profile_name,\n                region_name=region_name,\n                model_id=model_id\n            )\n    \"\"\"\n    client: Any  #: :meta private:\n    \"\"\"Bedrock client.\"\"\"\n    region_name: Optional[str] = None\n    \"\"\"The aws region e.g., `us-west-2`. Fallsback to AWS_DEFAULT_REGION env variable\n    or region specified in ~/.aws/config in case it is not provided here.\n    \"\"\"\n    credentials_profile_name: Optional[str] = None\n    \"\"\"The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which\n    has either access keys or role information specified.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html"}
{"id": "326b3068e98e-1", "text": "has either access keys or role information specified.\n    If not specified, the default credential profile or, if on an EC2 instance,\n    credentials from IMDS will be used.\n    See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\n    \"\"\"\n    model_id: str = \"amazon.titan-embed-text-v1\"\n    \"\"\"Id of the model to call, e.g., amazon.titan-embed-text-v1, this is\n    equivalent to the modelId property in the list-foundation-models api\"\"\"\n    model_kwargs: Optional[Dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    endpoint_url: Optional[str] = None\n    \"\"\"Needed if you don't want to default to us-east-1 endpoint\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that AWS credentials to and python package exists in environment.\"\"\"\n        if values[\"client\"] is not None:\n            return values\n        try:\n            import boto3\n            if values[\"credentials_profile_name\"] is not None:\n                session = boto3.Session(profile_name=values[\"credentials_profile_name\"])\n            else:\n                # use default credentials\n                session = boto3.Session()\n            client_params = {}\n            if values[\"region_name\"]:\n                client_params[\"region_name\"] = values[\"region_name\"]\n            if values[\"endpoint_url\"]:\n                client_params[\"endpoint_url\"] = values[\"endpoint_url\"]\n            values[\"client\"] = session.client(\"bedrock-runtime\", **client_params)\n        except ImportError:\n            raise ModuleNotFoundError(\n                \"Could not import boto3 python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html"}
{"id": "326b3068e98e-2", "text": "raise ModuleNotFoundError(\n                \"Could not import boto3 python package. \"\n                \"Please install it with `pip install boto3`.\"\n            )\n        except Exception as e:\n            raise ValueError(\n                \"Could not load credentials to authenticate with AWS client. \"\n                \"Please check that credentials in the specified \"\n                \"profile name are valid.\"\n            ) from e\n        return values\n    def _embedding_func(self, text: str) -> List[float]:\n        \"\"\"Call out to Bedrock embedding endpoint.\"\"\"\n        # replace newlines, which can negatively affect performance.\n        text = text.replace(os.linesep, \" \")\n        # format input body for provider\n        provider = self.model_id.split(\".\")[0]\n        _model_kwargs = self.model_kwargs or {}\n        input_body = {**_model_kwargs}\n        if provider == \"cohere\":\n            if \"input_type\" not in input_body.keys():\n                input_body[\"input_type\"] = \"search_document\"\n            input_body[\"texts\"] = [text]\n        else:\n            # includes common provider == \"amazon\"\n            input_body[\"inputText\"] = text\n        body = json.dumps(input_body)\n        try:\n            # invoke bedrock API\n            response = self.client.invoke_model(\n                body=body,\n                modelId=self.model_id,\n                accept=\"application/json\",\n                contentType=\"application/json\",\n            )\n            # format output based on provider\n            response_body = json.loads(response.get(\"body\").read())\n            if provider == \"cohere\":\n                return response_body.get(\"embeddings\")[0]\n            else:\n                # includes common provider == \"amazon\"\n                return response_body.get(\"embedding\")\n        except Exception as e:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html"}
{"id": "326b3068e98e-3", "text": "return response_body.get(\"embedding\")\n        except Exception as e:\n            raise ValueError(f\"Error raised by inference endpoint: {e}\")\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Compute doc embeddings using a Bedrock model.\n        Args:\n            texts: The list of texts to embed\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        results = []\n        for text in texts:\n            response = self._embedding_func(text)\n            results.append(response)\n        return results\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Compute query embeddings using a Bedrock model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        return self._embedding_func(text)\n[docs]    async def aembed_query(self, text: str) -> List[float]:\n        \"\"\"Asynchronous compute query embeddings using a Bedrock model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, partial(self.embed_query, text)\n        )\n[docs]    async def aembed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Asynchronous compute doc embeddings using a Bedrock model.\n        Args:\n            texts: The list of texts to embed\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        result = await asyncio.gather(*[self.aembed_query(text) for text in texts])\n        return list(result)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html"}
{"id": "47325573394b-0", "text": "Source code for langchain.embeddings.llamacpp\nfrom typing import Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator\nfrom langchain.schema.embeddings import Embeddings\n[docs]class LlamaCppEmbeddings(BaseModel, Embeddings):\n    \"\"\"llama.cpp embedding models.\n    To use, you should have the llama-cpp-python library installed, and provide the\n    path to the Llama model as a named parameter to the constructor.\n    Check out: https://github.com/abetlen/llama-cpp-python\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import LlamaCppEmbeddings\n            llama = LlamaCppEmbeddings(model_path=\"/path/to/model.bin\")\n    \"\"\"\n    client: Any  #: :meta private:\n    model_path: str\n    n_ctx: int = Field(512, alias=\"n_ctx\")\n    \"\"\"Token context window.\"\"\"\n    n_parts: int = Field(-1, alias=\"n_parts\")\n    \"\"\"Number of parts to split the model into. \n    If -1, the number of parts is automatically determined.\"\"\"\n    seed: int = Field(-1, alias=\"seed\")\n    \"\"\"Seed. If -1, a random seed is used.\"\"\"\n    f16_kv: bool = Field(False, alias=\"f16_kv\")\n    \"\"\"Use half-precision for key/value cache.\"\"\"\n    logits_all: bool = Field(False, alias=\"logits_all\")\n    \"\"\"Return logits for all tokens, not just the last token.\"\"\"\n    vocab_only: bool = Field(False, alias=\"vocab_only\")\n    \"\"\"Only load the vocabulary, no weights.\"\"\"\n    use_mlock: bool = Field(False, alias=\"use_mlock\")\n    \"\"\"Force system to keep model in RAM.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html"}
{"id": "47325573394b-1", "text": "\"\"\"Force system to keep model in RAM.\"\"\"\n    n_threads: Optional[int] = Field(None, alias=\"n_threads\")\n    \"\"\"Number of threads to use. If None, the number \n    of threads is automatically determined.\"\"\"\n    n_batch: Optional[int] = Field(8, alias=\"n_batch\")\n    \"\"\"Number of tokens to process in parallel.\n    Should be a number between 1 and n_ctx.\"\"\"\n    n_gpu_layers: Optional[int] = Field(None, alias=\"n_gpu_layers\")\n    \"\"\"Number of layers to be loaded into gpu memory. Default None.\"\"\"\n    verbose: bool = Field(True, alias=\"verbose\")\n    \"\"\"Print verbose output to stderr.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that llama-cpp-python library is installed.\"\"\"\n        model_path = values[\"model_path\"]\n        model_param_names = [\n            \"n_ctx\",\n            \"n_parts\",\n            \"seed\",\n            \"f16_kv\",\n            \"logits_all\",\n            \"vocab_only\",\n            \"use_mlock\",\n            \"n_threads\",\n            \"n_batch\",\n            \"verbose\",\n        ]\n        model_params = {k: values[k] for k in model_param_names}\n        # For backwards compatibility, only include if non-null.\n        if values[\"n_gpu_layers\"] is not None:\n            model_params[\"n_gpu_layers\"] = values[\"n_gpu_layers\"]\n        try:\n            from llama_cpp import Llama\n            values[\"client\"] = Llama(model_path, embedding=True, **model_params)\n        except ImportError:\n            raise ModuleNotFoundError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html"}
{"id": "47325573394b-2", "text": "except ImportError:\n            raise ModuleNotFoundError(\n                \"Could not import llama-cpp-python library. \"\n                \"Please install the llama-cpp-python library to \"\n                \"use this embedding model: pip install llama-cpp-python\"\n            )\n        except Exception as e:\n            raise ValueError(\n                f\"Could not load Llama model from path: {model_path}. \"\n                f\"Received error {e}\"\n            )\n        return values\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Embed a list of documents using the Llama model.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        embeddings = [self.client.embed(text) for text in texts]\n        return [list(map(float, e)) for e in embeddings]\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed a query using the Llama model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        embedding = self.client.embed(text)\n        return list(map(float, embedding))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html"}
{"id": "0a2b118f60fc-0", "text": "Source code for langchain.embeddings.sagemaker_endpoint\nfrom typing import Any, Dict, List, Optional\nfrom langchain.llms.sagemaker_endpoint import ContentHandlerBase\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.embeddings import Embeddings\n[docs]class EmbeddingsContentHandler(ContentHandlerBase[List[str], List[List[float]]]):\n    \"\"\"Content handler for LLM class.\"\"\"\n[docs]class SagemakerEndpointEmbeddings(BaseModel, Embeddings):\n    \"\"\"Custom Sagemaker Inference Endpoints.\n    To use, you must supply the endpoint name from your deployed\n    Sagemaker model & the region where it is deployed.\n    To authenticate, the AWS client uses the following methods to\n    automatically load credentials:\n    https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\n    If a specific credential profile should be used, you must pass\n    the name of the profile from the ~/.aws/credentials file that is to be used.\n    Make sure the credentials / roles used have the required policies to\n    access the Sagemaker endpoint.\n    See: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html\n    \"\"\"\n    \"\"\"\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import SagemakerEndpointEmbeddings\n            endpoint_name = (\n                \"my-endpoint-name\"\n            )\n            region_name = (\n                \"us-west-2\"\n            )\n            credentials_profile_name = (\n                \"default\"\n            )\n            se = SagemakerEndpointEmbeddings(\n                endpoint_name=endpoint_name,\n                region_name=region_name,\n                credentials_profile_name=credentials_profile_name\n            )\n            #Use with boto3 client\n            client = boto3.client(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html"}
{"id": "0a2b118f60fc-1", "text": ")\n            #Use with boto3 client\n            client = boto3.client(\n                        \"sagemaker-runtime\",\n                        region_name=region_name\n                    )\n            se = SagemakerEndpointEmbeddings(\n                endpoint_name=endpoint_name,\n                client=client\n            )\n    \"\"\"\n    client: Any = None\n    endpoint_name: str = \"\"\n    \"\"\"The name of the endpoint from the deployed Sagemaker model.\n    Must be unique within an AWS Region.\"\"\"\n    region_name: str = \"\"\n    \"\"\"The aws region where the Sagemaker model is deployed, eg. `us-west-2`.\"\"\"\n    credentials_profile_name: Optional[str] = None\n    \"\"\"The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which\n    has either access keys or role information specified.\n    If not specified, the default credential profile or, if on an EC2 instance,\n    credentials from IMDS will be used.\n    See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\n    \"\"\"\n    content_handler: EmbeddingsContentHandler\n    \"\"\"The content handler class that provides an input and\n    output transform functions to handle formats between LLM\n    and the endpoint.\n    \"\"\"\n    \"\"\"\n     Example:\n        .. code-block:: python\n        from langchain.embeddings.sagemaker_endpoint import EmbeddingsContentHandler\n        class ContentHandler(EmbeddingsContentHandler):\n                content_type = \"application/json\"\n                accepts = \"application/json\"\n                def transform_input(self, prompts: List[str], model_kwargs: Dict) -> bytes:\n                    input_str = json.dumps({prompts: prompts, **model_kwargs})\n                    return input_str.encode('utf-8')\n                def transform_output(self, output: bytes) -> List[List[float]]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html"}
{"id": "0a2b118f60fc-2", "text": "def transform_output(self, output: bytes) -> List[List[float]]:\n                    response_json = json.loads(output.read().decode(\"utf-8\"))\n                    return response_json[\"vectors\"]\n    \"\"\"  # noqa: E501\n    model_kwargs: Optional[Dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    endpoint_kwargs: Optional[Dict] = None\n    \"\"\"Optional attributes passed to the invoke_endpoint\n    function. See `boto3`_. docs for more info.\n    .. _boto3: <https://boto3.amazonaws.com/v1/documentation/api/latest/index.html>\n    \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Dont do anything if client provided externally\"\"\"\n        if values.get(\"client\") is not None:\n            return values\n        \"\"\"Validate that AWS credentials to and python package exists in environment.\"\"\"\n        try:\n            import boto3\n            try:\n                if values[\"credentials_profile_name\"] is not None:\n                    session = boto3.Session(\n                        profile_name=values[\"credentials_profile_name\"]\n                    )\n                else:\n                    # use default credentials\n                    session = boto3.Session()\n                values[\"client\"] = session.client(\n                    \"sagemaker-runtime\", region_name=values[\"region_name\"]\n                )\n            except Exception as e:\n                raise ValueError(\n                    \"Could not load credentials to authenticate with AWS client. \"\n                    \"Please check that credentials in the specified \"\n                    \"profile name are valid.\"\n                ) from e\n        except ImportError:\n            raise ImportError(\n                \"Could not import boto3 python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html"}
{"id": "0a2b118f60fc-3", "text": "raise ImportError(\n                \"Could not import boto3 python package. \"\n                \"Please install it with `pip install boto3`.\"\n            )\n        return values\n    def _embedding_func(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Call out to SageMaker Inference embedding endpoint.\"\"\"\n        # replace newlines, which can negatively affect performance.\n        texts = list(map(lambda x: x.replace(\"\\n\", \" \"), texts))\n        _model_kwargs = self.model_kwargs or {}\n        _endpoint_kwargs = self.endpoint_kwargs or {}\n        body = self.content_handler.transform_input(texts, _model_kwargs)\n        content_type = self.content_handler.content_type\n        accepts = self.content_handler.accepts\n        # send request\n        try:\n            response = self.client.invoke_endpoint(\n                EndpointName=self.endpoint_name,\n                Body=body,\n                ContentType=content_type,\n                Accept=accepts,\n                **_endpoint_kwargs,\n            )\n        except Exception as e:\n            raise ValueError(f\"Error raised by inference endpoint: {e}\")\n        return self.content_handler.transform_output(response[\"Body\"])\n[docs]    def embed_documents(\n        self, texts: List[str], chunk_size: int = 64\n    ) -> List[List[float]]:\n        \"\"\"Compute doc embeddings using a SageMaker Inference Endpoint.\n        Args:\n            texts: The list of texts to embed.\n            chunk_size: The chunk size defines how many input texts will\n                be grouped together as request. If None, will use the\n                chunk size specified by the class.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        results = []\n        _chunk_size = len(texts) if chunk_size > len(texts) else chunk_size", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html"}
{"id": "0a2b118f60fc-4", "text": "for i in range(0, len(texts), _chunk_size):\n            response = self._embedding_func(texts[i : i + _chunk_size])\n            results.extend(response)\n        return results\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Compute query embeddings using a SageMaker inference endpoint.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        return self._embedding_func([text])[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html"}
{"id": "df7ccf0cb694-0", "text": "Source code for langchain.embeddings.ernie\nimport asyncio\nimport logging\nimport threading\nfrom functools import partial\nfrom typing import Dict, List, Optional\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class ErnieEmbeddings(BaseModel, Embeddings):\n    \"\"\"`Ernie Embeddings V1` embedding models.\"\"\"\n    ernie_api_base: Optional[str] = None\n    ernie_client_id: Optional[str] = None\n    ernie_client_secret: Optional[str] = None\n    access_token: Optional[str] = None\n    chunk_size: int = 16\n    model_name = \"ErnieBot-Embedding-V1\"\n    _lock = threading.Lock()\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        values[\"ernie_api_base\"] = get_from_dict_or_env(\n            values, \"ernie_api_base\", \"ERNIE_API_BASE\", \"https://aip.baidubce.com\"\n        )\n        values[\"ernie_client_id\"] = get_from_dict_or_env(\n            values,\n            \"ernie_client_id\",\n            \"ERNIE_CLIENT_ID\",\n        )\n        values[\"ernie_client_secret\"] = get_from_dict_or_env(\n            values,\n            \"ernie_client_secret\",\n            \"ERNIE_CLIENT_SECRET\",\n        )\n        return values\n    def _embedding(self, json: object) -> dict:\n        base_url = (\n            f\"{self.ernie_api_base}/rpc/2.0/ai_custom/v1/wenxinworkshop/embeddings\"\n        )\n        resp = requests.post(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ernie.html"}
{"id": "df7ccf0cb694-1", "text": ")\n        resp = requests.post(\n            f\"{base_url}/embedding-v1\",\n            headers={\n                \"Content-Type\": \"application/json\",\n            },\n            params={\"access_token\": self.access_token},\n            json=json,\n        )\n        return resp.json()\n    def _refresh_access_token_with_lock(self) -> None:\n        with self._lock:\n            logger.debug(\"Refreshing access token\")\n            base_url: str = f\"{self.ernie_api_base}/oauth/2.0/token\"\n            resp = requests.post(\n                base_url,\n                headers={\n                    \"Content-Type\": \"application/json\",\n                    \"Accept\": \"application/json\",\n                },\n                params={\n                    \"grant_type\": \"client_credentials\",\n                    \"client_id\": self.ernie_client_id,\n                    \"client_secret\": self.ernie_client_secret,\n                },\n            )\n            self.access_token = str(resp.json().get(\"access_token\"))\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Embed search docs.\n        Args:\n            texts: The list of texts to embed\n        Returns:\n            List[List[float]]: List of embeddings, one for each text.\n        \"\"\"\n        if not self.access_token:\n            self._refresh_access_token_with_lock()\n        text_in_chunks = [\n            texts[i : i + self.chunk_size]\n            for i in range(0, len(texts), self.chunk_size)\n        ]\n        lst = []\n        for chunk in text_in_chunks:\n            resp = self._embedding({\"input\": [text for text in chunk]})\n            if resp.get(\"error_code\"):\n                if resp.get(\"error_code\") == 111:\n                    self._refresh_access_token_with_lock()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ernie.html"}
{"id": "df7ccf0cb694-2", "text": "self._refresh_access_token_with_lock()\n                    resp = self._embedding({\"input\": [text for text in chunk]})\n                else:\n                    raise ValueError(f\"Error from Ernie: {resp}\")\n            lst.extend([i[\"embedding\"] for i in resp[\"data\"]])\n        return lst\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed query text.\n        Args:\n            text: The text to embed.\n        Returns:\n            List[float]: Embeddings for the text.\n        \"\"\"\n        if not self.access_token:\n            self._refresh_access_token_with_lock()\n        resp = self._embedding({\"input\": [text]})\n        if resp.get(\"error_code\"):\n            if resp.get(\"error_code\") == 111:\n                self._refresh_access_token_with_lock()\n                resp = self._embedding({\"input\": [text]})\n            else:\n                raise ValueError(f\"Error from Ernie: {resp}\")\n        return resp[\"data\"][0][\"embedding\"]\n[docs]    async def aembed_query(self, text: str) -> List[float]:\n        \"\"\"Asynchronous Embed query text.\n        Args:\n            text: The text to embed.\n        Returns:\n            List[float]: Embeddings for the text.\n        \"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, partial(self.embed_query, text)\n        )\n[docs]    async def aembed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Asynchronous Embed search docs.\n        Args:\n            texts: The list of texts to embed\n        Returns:\n            List[List[float]]: List of embeddings, one for each text.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ernie.html"}
{"id": "df7ccf0cb694-3", "text": "List[List[float]]: List of embeddings, one for each text.\n        \"\"\"\n        result = await asyncio.gather(*[self.aembed_query(text) for text in texts])\n        return list(result)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ernie.html"}
{"id": "451253574251-0", "text": "Source code for langchain.embeddings.aleph_alpha\nfrom typing import Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\n[docs]class AlephAlphaAsymmetricSemanticEmbedding(BaseModel, Embeddings):\n    \"\"\"Aleph Alpha's asymmetric semantic embedding.\n    AA provides you with an endpoint to embed a document and a query.\n    The models were optimized to make the embeddings of documents and\n    the query for a document as similar as possible.\n    To learn more, check out: https://docs.aleph-alpha.com/docs/tasks/semantic_embed/\n    Example:\n        .. code-block:: python\n            from aleph_alpha import AlephAlphaAsymmetricSemanticEmbedding\n            embeddings = AlephAlphaAsymmetricSemanticEmbedding(\n                normalize=True, compress_to_size=128\n            )\n            document = \"This is a content of the document\"\n            query = \"What is the content of the document?\"\n            doc_result = embeddings.embed_documents([document])\n            query_result = embeddings.embed_query(query)\n    \"\"\"\n    client: Any  #: :meta private:\n    # Embedding params\n    model: str = \"luminous-base\"\n    \"\"\"Model name to use.\"\"\"\n    compress_to_size: Optional[int] = None\n    \"\"\"Should the returned embeddings come back as an original 5120-dim vector, \n    or should it be compressed to 128-dim.\"\"\"\n    normalize: Optional[bool] = None\n    \"\"\"Should returned embeddings be normalized\"\"\"\n    contextual_control_threshold: Optional[int] = None\n    \"\"\"Attention control parameters only apply to those tokens that have \n    explicitly been set in the request.\"\"\"\n    control_log_additive: bool = True", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html"}
{"id": "451253574251-1", "text": "explicitly been set in the request.\"\"\"\n    control_log_additive: bool = True\n    \"\"\"Apply controls on prompt items by adding the log(control_factor) \n    to attention scores.\"\"\"\n    # Client params\n    aleph_alpha_api_key: Optional[str] = None\n    \"\"\"API key for Aleph Alpha API.\"\"\"\n    host: str = \"https://api.aleph-alpha.com\"\n    \"\"\"The hostname of the API host. \n    The default one is \"https://api.aleph-alpha.com\")\"\"\"\n    hosting: Optional[str] = None\n    \"\"\"Determines in which datacenters the request may be processed.\n    You can either set the parameter to \"aleph-alpha\" or omit it (defaulting to None).\n    Not setting this value, or setting it to None, gives us maximal flexibility \n    in processing your request in our\n    own datacenters and on servers hosted with other providers. \n    Choose this option for maximal availability.\n    Setting it to \"aleph-alpha\" allows us to only process the request \n    in our own datacenters.\n    Choose this option for maximal data privacy.\"\"\"\n    request_timeout_seconds: int = 305\n    \"\"\"Client timeout that will be set for HTTP requests in the \n    `requests` library's API calls.\n    Server will close all requests after 300 seconds with an internal server error.\"\"\"\n    total_retries: int = 8\n    \"\"\"The number of retries made in case requests fail with certain retryable \n    status codes. If the last\n    retry fails a corresponding exception is raised. Note, that between retries \n    an exponential backoff\n    is applied, starting with 0.5 s after the first retry and doubling for each \n    retry made. So with the", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html"}
{"id": "451253574251-2", "text": "retry made. So with the\n    default setting of 8 retries a total wait time of 63.5 s is added between \n    the retries.\"\"\"\n    nice: bool = False\n    \"\"\"Setting this to True, will signal to the API that you intend to be \n    nice to other users\n    by de-prioritizing your request below concurrent ones.\"\"\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        aleph_alpha_api_key = get_from_dict_or_env(\n            values, \"aleph_alpha_api_key\", \"ALEPH_ALPHA_API_KEY\"\n        )\n        try:\n            from aleph_alpha_client import Client\n            values[\"client\"] = Client(\n                token=aleph_alpha_api_key,\n                host=values[\"host\"],\n                hosting=values[\"hosting\"],\n                request_timeout_seconds=values[\"request_timeout_seconds\"],\n                total_retries=values[\"total_retries\"],\n                nice=values[\"nice\"],\n            )\n        except ImportError:\n            raise ValueError(\n                \"Could not import aleph_alpha_client python package. \"\n                \"Please install it with `pip install aleph_alpha_client`.\"\n            )\n        return values\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Call out to Aleph Alpha's asymmetric Document endpoint.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        try:\n            from aleph_alpha_client import (\n                Prompt,\n                SemanticEmbeddingRequest,\n                SemanticRepresentation,\n            )\n        except ImportError:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html"}
{"id": "451253574251-3", "text": "SemanticRepresentation,\n            )\n        except ImportError:\n            raise ValueError(\n                \"Could not import aleph_alpha_client python package. \"\n                \"Please install it with `pip install aleph_alpha_client`.\"\n            )\n        document_embeddings = []\n        for text in texts:\n            document_params = {\n                \"prompt\": Prompt.from_text(text),\n                \"representation\": SemanticRepresentation.Document,\n                \"compress_to_size\": self.compress_to_size,\n                \"normalize\": self.normalize,\n                \"contextual_control_threshold\": self.contextual_control_threshold,\n                \"control_log_additive\": self.control_log_additive,\n            }\n            document_request = SemanticEmbeddingRequest(**document_params)\n            document_response = self.client.semantic_embed(\n                request=document_request, model=self.model\n            )\n            document_embeddings.append(document_response.embedding)\n        return document_embeddings\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to Aleph Alpha's asymmetric, query embedding endpoint\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        try:\n            from aleph_alpha_client import (\n                Prompt,\n                SemanticEmbeddingRequest,\n                SemanticRepresentation,\n            )\n        except ImportError:\n            raise ValueError(\n                \"Could not import aleph_alpha_client python package. \"\n                \"Please install it with `pip install aleph_alpha_client`.\"\n            )\n        symmetric_params = {\n            \"prompt\": Prompt.from_text(text),\n            \"representation\": SemanticRepresentation.Query,\n            \"compress_to_size\": self.compress_to_size,\n            \"normalize\": self.normalize,\n            \"contextual_control_threshold\": self.contextual_control_threshold,\n            \"control_log_additive\": self.control_log_additive,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html"}
{"id": "451253574251-4", "text": "\"control_log_additive\": self.control_log_additive,\n        }\n        symmetric_request = SemanticEmbeddingRequest(**symmetric_params)\n        symmetric_response = self.client.semantic_embed(\n            request=symmetric_request, model=self.model\n        )\n        return symmetric_response.embedding\n[docs]class AlephAlphaSymmetricSemanticEmbedding(AlephAlphaAsymmetricSemanticEmbedding):\n    \"\"\"The symmetric version of the Aleph Alpha's semantic embeddings.\n    The main difference is that here, both the documents and\n    queries are embedded with a SemanticRepresentation.Symmetric\n    Example:\n        .. code-block:: python\n            from aleph_alpha import AlephAlphaSymmetricSemanticEmbedding\n            embeddings = AlephAlphaAsymmetricSemanticEmbedding(\n                normalize=True, compress_to_size=128\n            )\n            text = \"This is a test text\"\n            doc_result = embeddings.embed_documents([text])\n            query_result = embeddings.embed_query(text)\n    \"\"\"\n    def _embed(self, text: str) -> List[float]:\n        try:\n            from aleph_alpha_client import (\n                Prompt,\n                SemanticEmbeddingRequest,\n                SemanticRepresentation,\n            )\n        except ImportError:\n            raise ValueError(\n                \"Could not import aleph_alpha_client python package. \"\n                \"Please install it with `pip install aleph_alpha_client`.\"\n            )\n        query_params = {\n            \"prompt\": Prompt.from_text(text),\n            \"representation\": SemanticRepresentation.Symmetric,\n            \"compress_to_size\": self.compress_to_size,\n            \"normalize\": self.normalize,\n            \"contextual_control_threshold\": self.contextual_control_threshold,\n            \"control_log_additive\": self.control_log_additive,\n        }\n        query_request = SemanticEmbeddingRequest(**query_params)\n        query_response = self.client.semantic_embed(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html"}
{"id": "451253574251-5", "text": "query_response = self.client.semantic_embed(\n            request=query_request, model=self.model\n        )\n        return query_response.embedding\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Call out to Aleph Alpha's Document endpoint.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        document_embeddings = []\n        for text in texts:\n            document_embeddings.append(self._embed(text))\n        return document_embeddings\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to Aleph Alpha's asymmetric, query embedding endpoint\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        return self._embed(text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html"}
{"id": "29877826ff73-0", "text": "Source code for langchain.embeddings.elasticsearch\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, List, Optional\nfrom langchain.utils import get_from_env\nif TYPE_CHECKING:\n    from elasticsearch import Elasticsearch\n    from elasticsearch.client import MlClient\nfrom langchain.schema.embeddings import Embeddings\n[docs]class ElasticsearchEmbeddings(Embeddings):\n    \"\"\"Elasticsearch embedding models.\n    This class provides an interface to generate embeddings using a model deployed\n    in an Elasticsearch cluster. It requires an Elasticsearch connection object\n    and the model_id of the model deployed in the cluster.\n    In Elasticsearch you need to have an embedding model loaded and deployed.\n    - https://www.elastic.co/guide/en/elasticsearch/reference/current/infer-trained-model.html\n    - https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-deploy-models.html\n    \"\"\"  # noqa: E501\n[docs]    def __init__(\n        self,\n        client: MlClient,\n        model_id: str,\n        *,\n        input_field: str = \"text_field\",\n    ):\n        \"\"\"\n        Initialize the ElasticsearchEmbeddings instance.\n        Args:\n            client (MlClient): An Elasticsearch ML client object.\n            model_id (str): The model_id of the model deployed in the Elasticsearch\n                cluster.\n            input_field (str): The name of the key for the input text field in the\n                document. Defaults to 'text_field'.\n        \"\"\"\n        self.client = client\n        self.model_id = model_id\n        self.input_field = input_field\n[docs]    @classmethod\n    def from_credentials(\n        cls,\n        model_id: str,\n        *,\n        es_cloud_id: Optional[str] = None,\n        es_user: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html"}
{"id": "29877826ff73-1", "text": "es_user: Optional[str] = None,\n        es_password: Optional[str] = None,\n        input_field: str = \"text_field\",\n    ) -> ElasticsearchEmbeddings:\n        \"\"\"Instantiate embeddings from Elasticsearch credentials.\n        Args:\n            model_id (str): The model_id of the model deployed in the Elasticsearch\n                cluster.\n            input_field (str): The name of the key for the input text field in the\n                document. Defaults to 'text_field'.\n            es_cloud_id: (str, optional): The Elasticsearch cloud ID to connect to.\n            es_user: (str, optional): Elasticsearch username.\n            es_password: (str, optional): Elasticsearch password.\n        Example:\n            .. code-block:: python\n                from langchain.embeddings import ElasticsearchEmbeddings\n                # Define the model ID and input field name (if different from default)\n                model_id = \"your_model_id\"\n                # Optional, only if different from 'text_field'\n                input_field = \"your_input_field\"\n                # Credentials can be passed in two ways. Either set the env vars\n                # ES_CLOUD_ID, ES_USER, ES_PASSWORD and they will be automatically\n                # pulled in, or pass them in directly as kwargs.\n                embeddings = ElasticsearchEmbeddings.from_credentials(\n                    model_id,\n                    input_field=input_field,\n                    # es_cloud_id=\"foo\",\n                    # es_user=\"bar\",\n                    # es_password=\"baz\",\n                )\n                documents = [\n                    \"This is an example document.\",\n                    \"Another example document to generate embeddings for.\",\n                ]\n                embeddings_generator.embed_documents(documents)\n        \"\"\"\n        try:\n            from elasticsearch import Elasticsearch\n            from elasticsearch.client import MlClient\n        except ImportError:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html"}
{"id": "29877826ff73-2", "text": "from elasticsearch.client import MlClient\n        except ImportError:\n            raise ImportError(\n                \"elasticsearch package not found, please install with 'pip install \"\n                \"elasticsearch'\"\n            )\n        es_cloud_id = es_cloud_id or get_from_env(\"es_cloud_id\", \"ES_CLOUD_ID\")\n        es_user = es_user or get_from_env(\"es_user\", \"ES_USER\")\n        es_password = es_password or get_from_env(\"es_password\", \"ES_PASSWORD\")\n        # Connect to Elasticsearch\n        es_connection = Elasticsearch(\n            cloud_id=es_cloud_id, basic_auth=(es_user, es_password)\n        )\n        client = MlClient(es_connection)\n        return cls(client, model_id, input_field=input_field)\n[docs]    @classmethod\n    def from_es_connection(\n        cls,\n        model_id: str,\n        es_connection: Elasticsearch,\n        input_field: str = \"text_field\",\n    ) -> ElasticsearchEmbeddings:\n        \"\"\"\n        Instantiate embeddings from an existing Elasticsearch connection.\n        This method provides a way to create an instance of the ElasticsearchEmbeddings\n        class using an existing Elasticsearch connection. The connection object is used\n        to create an MlClient, which is then used to initialize the\n        ElasticsearchEmbeddings instance.\n        Args:\n        model_id (str): The model_id of the model deployed in the Elasticsearch cluster.\n        es_connection (elasticsearch.Elasticsearch): An existing Elasticsearch\n        connection object. input_field (str, optional): The name of the key for the\n        input text field in the document. Defaults to 'text_field'.\n        Returns:\n        ElasticsearchEmbeddings: An instance of the ElasticsearchEmbeddings class.\n        Example:\n            .. code-block:: python\n                from elasticsearch import Elasticsearch", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html"}
{"id": "29877826ff73-3", "text": "Example:\n            .. code-block:: python\n                from elasticsearch import Elasticsearch\n                from langchain.embeddings import ElasticsearchEmbeddings\n                # Define the model ID and input field name (if different from default)\n                model_id = \"your_model_id\"\n                # Optional, only if different from 'text_field'\n                input_field = \"your_input_field\"\n                # Create Elasticsearch connection\n                es_connection = Elasticsearch(\n                    hosts=[\"localhost:9200\"], http_auth=(\"user\", \"password\")\n                )\n                # Instantiate ElasticsearchEmbeddings using the existing connection\n                embeddings = ElasticsearchEmbeddings.from_es_connection(\n                    model_id,\n                    es_connection,\n                    input_field=input_field,\n                )\n                documents = [\n                    \"This is an example document.\",\n                    \"Another example document to generate embeddings for.\",\n                ]\n                embeddings_generator.embed_documents(documents)\n        \"\"\"\n        # Importing MlClient from elasticsearch.client within the method to\n        # avoid unnecessary import if the method is not used\n        from elasticsearch.client import MlClient\n        # Create an MlClient from the given Elasticsearch connection\n        client = MlClient(es_connection)\n        # Return a new instance of the ElasticsearchEmbeddings class with\n        # the MlClient, model_id, and input_field\n        return cls(client, model_id, input_field=input_field)\n    def _embedding_func(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"\n        Generate embeddings for the given texts using the Elasticsearch model.\n        Args:\n            texts (List[str]): A list of text strings to generate embeddings for.\n        Returns:\n            List[List[float]]: A list of embeddings, one for each text in the input\n                list.\n        \"\"\"\n        response = self.client.infer_trained_model(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html"}
{"id": "29877826ff73-4", "text": "list.\n        \"\"\"\n        response = self.client.infer_trained_model(\n            model_id=self.model_id, docs=[{self.input_field: text} for text in texts]\n        )\n        embeddings = [doc[\"predicted_value\"] for doc in response[\"inference_results\"]]\n        return embeddings\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"\n        Generate embeddings for a list of documents.\n        Args:\n            texts (List[str]): A list of document text strings to generate embeddings\n                for.\n        Returns:\n            List[List[float]]: A list of embeddings, one for each document in the input\n                list.\n        \"\"\"\n        return self._embedding_func(texts)\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"\n        Generate an embedding for a single query text.\n        Args:\n            text (str): The query text to generate an embedding for.\n        Returns:\n            List[float]: The embedding for the input query text.\n        \"\"\"\n        return self._embedding_func([text])[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html"}
{"id": "cc0e57560807-0", "text": "Source code for langchain.embeddings.voyageai\nfrom __future__ import annotations\nimport json\nimport logging\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    List,\n    Optional,\n    Tuple,\n    Union,\n    cast,\n)\nimport requests\nfrom tenacity import (\n    before_sleep_log,\n    retry,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.pydantic_v1 import BaseModel, Extra, SecretStr, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import convert_to_secret_str, get_from_dict_or_env\nlogger = logging.getLogger(__name__)\ndef _create_retry_decorator(embeddings: VoyageEmbeddings) -> Callable[[Any], Any]:\n    min_seconds = 4\n    max_seconds = 10\n    # Wait 2^x * 1 second between each retry starting with\n    # 4 seconds, then up to 10 seconds, then 10 seconds afterwards\n    return retry(\n        reraise=True,\n        stop=stop_after_attempt(embeddings.max_retries),\n        wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\ndef _check_response(response: dict) -> dict:\n    if \"data\" not in response:\n        raise RuntimeError(f\"Voyage API Error. Message: {json.dumps(response)}\")\n    return response\n[docs]def embed_with_retry(embeddings: VoyageEmbeddings, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the embedding call.\"\"\"\n    retry_decorator = _create_retry_decorator(embeddings)\n    @retry_decorator\n    def _embed_with_retry(**kwargs: Any) -> Any:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/voyageai.html"}
{"id": "cc0e57560807-1", "text": "@retry_decorator\n    def _embed_with_retry(**kwargs: Any) -> Any:\n        response = requests.post(**kwargs)\n        return _check_response(response.json())\n    return _embed_with_retry(**kwargs)\n[docs]class VoyageEmbeddings(BaseModel, Embeddings):\n    \"\"\"Voyage embedding models.\n    To use, you should have the environment variable ``VOYAGE_API_KEY`` set with\n    your API key or pass it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import VoyageEmbeddings\n            voyage = VoyageEmbeddings(voyage_api_key=\"your-api-key\")\n            text = \"This is a test query.\"\n            query_result = voyage.embed_query(text)\n    \"\"\"\n    model: str = \"voyage-01\"\n    voyage_api_base: str = \"https://api.voyageai.com/v1/embeddings\"\n    voyage_api_key: Optional[SecretStr] = None\n    batch_size: int = 8\n    \"\"\"Maximum number of texts to embed in each API request.\"\"\"\n    max_retries: int = 6\n    \"\"\"Maximum number of retries to make when generating.\"\"\"\n    request_timeout: Optional[Union[float, Tuple[float, float]]] = None\n    \"\"\"Timeout in seconds for the API request.\"\"\"\n    show_progress_bar: bool = False\n    \"\"\"Whether to show a progress bar when embedding. Must have tqdm installed if set \n        to True.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"voyage_api_key\"] = convert_to_secret_str(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/voyageai.html"}
{"id": "cc0e57560807-2", "text": "values[\"voyage_api_key\"] = convert_to_secret_str(\n            get_from_dict_or_env(values, \"voyage_api_key\", \"VOYAGE_API_KEY\")\n        )\n        return values\n    def _invocation_params(\n        self, input: List[str], input_type: Optional[str] = None\n    ) -> Dict:\n        api_key = cast(SecretStr, self.voyage_api_key).get_secret_value()\n        params = {\n            \"url\": self.voyage_api_base,\n            \"headers\": {\"Authorization\": f\"Bearer {api_key}\"},\n            \"json\": {\"model\": self.model, \"input\": input, \"input_type\": input_type},\n            \"timeout\": self.request_timeout,\n        }\n        return params\n    def _get_embeddings(\n        self, texts: List[str], batch_size: int, input_type: Optional[str] = None\n    ) -> List[List[float]]:\n        embeddings: List[List[float]] = []\n        if self.show_progress_bar:\n            try:\n                from tqdm.auto import tqdm\n            except ImportError as e:\n                raise ImportError(\n                    \"Must have tqdm installed if `show_progress_bar` is set to True. \"\n                    \"Please install with `pip install tqdm`.\"\n                ) from e\n            _iter = tqdm(range(0, len(texts), batch_size))\n        else:\n            _iter = range(0, len(texts), batch_size)\n        if input_type and input_type not in [\"query\", \"document\"]:\n            raise ValueError(\n                f\"input_type {input_type} is invalid. Options: None, 'query', \"\n                \"'document'.\"\n            )\n        for i in _iter:\n            response = embed_with_retry(\n                self,\n                **self._invocation_params(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/voyageai.html"}
{"id": "cc0e57560807-3", "text": "self,\n                **self._invocation_params(\n                    input=texts[i : i + batch_size], input_type=input_type\n                ),\n            )\n            embeddings.extend(r[\"embedding\"] for r in response[\"data\"])\n        return embeddings\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Call out to Voyage Embedding endpoint for embedding search docs.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        return self._get_embeddings(\n            texts, batch_size=self.batch_size, input_type=\"document\"\n        )\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to Voyage Embedding endpoint for embedding query text.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embedding for the text.\n        \"\"\"\n        return self._get_embeddings(\n            [text], batch_size=self.batch_size, input_type=\"query\"\n        )[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/voyageai.html"}
{"id": "493efd198652-0", "text": "Source code for langchain.embeddings.llm_rails\n\"\"\" This file is for LLMRails Embedding \"\"\"\nimport logging\nimport os\nfrom typing import List, Optional\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra\nfrom langchain.schema.embeddings import Embeddings\n[docs]class LLMRailsEmbeddings(BaseModel, Embeddings):\n    \"\"\"LLMRails embedding models.\n    To use, you should have the  environment\n    variable ``LLM_RAILS_API_KEY`` set with your API key or pass it\n    as a named parameter to the constructor.\n    Model can be one of [\"embedding-english-v1\",\"embedding-multi-v1\"]\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import LLMRailsEmbeddings\n            cohere = LLMRailsEmbeddings(\n                model=\"embedding-english-v1\", api_key=\"my-api-key\"\n            )\n    \"\"\"\n    model: str = \"embedding-english-v1\"\n    \"\"\"Model name to use.\"\"\"\n    api_key: Optional[str] = None\n    \"\"\"LLMRails API key.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Call out to Cohere's embedding endpoint.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        api_key = self.api_key or os.environ.get(\"LLM_RAILS_API_KEY\")\n        if api_key is None:\n            logging.warning(\"Can't find LLMRails credentials in environment.\")\n            raise ValueError(\"LLM_RAILS_API_KEY is not set\")\n        response = requests.post(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/llm_rails.html"}
{"id": "493efd198652-1", "text": "response = requests.post(\n            \"https://api.llmrails.com/v1/embeddings\",\n            headers={\"X-API-KEY\": api_key},\n            json={\"input\": texts, \"model\": self.model},\n            timeout=60,\n        )\n        return [item[\"embedding\"] for item in response.json()[\"data\"]]\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to Cohere's embedding endpoint.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        return self.embed_documents([text])[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/llm_rails.html"}
{"id": "f55490bf7f65-0", "text": "Source code for langchain.embeddings.self_hosted_hugging_face\nimport importlib\nimport logging\nfrom typing import Any, Callable, List, Optional\nfrom langchain.embeddings.self_hosted import SelfHostedEmbeddings\nDEFAULT_MODEL_NAME = \"sentence-transformers/all-mpnet-base-v2\"\nDEFAULT_INSTRUCT_MODEL = \"hkunlp/instructor-large\"\nDEFAULT_EMBED_INSTRUCTION = \"Represent the document for retrieval: \"\nDEFAULT_QUERY_INSTRUCTION = (\n    \"Represent the question for retrieving supporting documents: \"\n)\nlogger = logging.getLogger(__name__)\ndef _embed_documents(client: Any, *args: Any, **kwargs: Any) -> List[List[float]]:\n    \"\"\"Inference function to send to the remote hardware.\n    Accepts a sentence_transformer model_id and\n    returns a list of embeddings for each document in the batch.\n    \"\"\"\n    return client.encode(*args, **kwargs)\n[docs]def load_embedding_model(model_id: str, instruct: bool = False, device: int = 0) -> Any:\n    \"\"\"Load the embedding model.\"\"\"\n    if not instruct:\n        import sentence_transformers\n        client = sentence_transformers.SentenceTransformer(model_id)\n    else:\n        from InstructorEmbedding import INSTRUCTOR\n        client = INSTRUCTOR(model_id)\n    if importlib.util.find_spec(\"torch\") is not None:\n        import torch\n        cuda_device_count = torch.cuda.device_count()\n        if device < -1 or (device >= cuda_device_count):\n            raise ValueError(\n                f\"Got device=={device}, \"\n                f\"device is required to be within [-1, {cuda_device_count})\"\n            )\n        if device < 0 and cuda_device_count > 0:\n            logger.warning(\n                \"Device has %d GPUs available. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html"}
{"id": "f55490bf7f65-1", "text": "logger.warning(\n                \"Device has %d GPUs available. \"\n                \"Provide device={deviceId} to `from_model_id` to use available\"\n                \"GPUs for execution. deviceId is -1 for CPU and \"\n                \"can be a positive integer associated with CUDA device id.\",\n                cuda_device_count,\n            )\n        client = client.to(device)\n    return client\n[docs]class SelfHostedHuggingFaceEmbeddings(SelfHostedEmbeddings):\n    \"\"\"HuggingFace embedding models on self-hosted remote hardware.\n    Supported hardware includes auto-launched instances on AWS, GCP, Azure,\n    and Lambda, as well as servers specified\n    by IP address and SSH credentials (such as on-prem, or another cloud\n    like Paperspace, Coreweave, etc.).\n    To use, you should have the ``runhouse`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import SelfHostedHuggingFaceEmbeddings\n            import runhouse as rh\n            model_name = \"sentence-transformers/all-mpnet-base-v2\"\n            gpu = rh.cluster(name=\"rh-a10x\", instance_type=\"A100:1\")\n            hf = SelfHostedHuggingFaceEmbeddings(model_name=model_name, hardware=gpu)\n    \"\"\"\n    client: Any  #: :meta private:\n    model_id: str = DEFAULT_MODEL_NAME\n    \"\"\"Model name to use.\"\"\"\n    model_reqs: List[str] = [\"./\", \"sentence_transformers\", \"torch\"]\n    \"\"\"Requirements to install on hardware to inference the model.\"\"\"\n    hardware: Any\n    \"\"\"Remote hardware to send the inference function to.\"\"\"\n    model_load_fn: Callable = load_embedding_model\n    \"\"\"Function to load the model remotely on the server.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html"}
{"id": "f55490bf7f65-2", "text": "\"\"\"Function to load the model remotely on the server.\"\"\"\n    load_fn_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments to pass to the model load function.\"\"\"\n    inference_fn: Callable = _embed_documents\n    \"\"\"Inference function to extract the embeddings.\"\"\"\n    def __init__(self, **kwargs: Any):\n        \"\"\"Initialize the remote inference function.\"\"\"\n        load_fn_kwargs = kwargs.pop(\"load_fn_kwargs\", {})\n        load_fn_kwargs[\"model_id\"] = load_fn_kwargs.get(\"model_id\", DEFAULT_MODEL_NAME)\n        load_fn_kwargs[\"instruct\"] = load_fn_kwargs.get(\"instruct\", False)\n        load_fn_kwargs[\"device\"] = load_fn_kwargs.get(\"device\", 0)\n        super().__init__(load_fn_kwargs=load_fn_kwargs, **kwargs)\n[docs]class SelfHostedHuggingFaceInstructEmbeddings(SelfHostedHuggingFaceEmbeddings):\n    \"\"\"HuggingFace InstructEmbedding models on self-hosted remote hardware.\n    Supported hardware includes auto-launched instances on AWS, GCP, Azure,\n    and Lambda, as well as servers specified\n    by IP address and SSH credentials (such as on-prem, or another\n    cloud like Paperspace, Coreweave, etc.).\n    To use, you should have the ``runhouse`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import SelfHostedHuggingFaceInstructEmbeddings\n            import runhouse as rh\n            model_name = \"hkunlp/instructor-large\"\n            gpu = rh.cluster(name='rh-a10x', instance_type='A100:1')\n            hf = SelfHostedHuggingFaceInstructEmbeddings(\n                model_name=model_name, hardware=gpu)\n    \"\"\"\n    model_id: str = DEFAULT_INSTRUCT_MODEL", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html"}
{"id": "f55490bf7f65-3", "text": "\"\"\"\n    model_id: str = DEFAULT_INSTRUCT_MODEL\n    \"\"\"Model name to use.\"\"\"\n    embed_instruction: str = DEFAULT_EMBED_INSTRUCTION\n    \"\"\"Instruction to use for embedding documents.\"\"\"\n    query_instruction: str = DEFAULT_QUERY_INSTRUCTION\n    \"\"\"Instruction to use for embedding query.\"\"\"\n    model_reqs: List[str] = [\"./\", \"InstructorEmbedding\", \"torch\"]\n    \"\"\"Requirements to install on hardware to inference the model.\"\"\"\n    def __init__(self, **kwargs: Any):\n        \"\"\"Initialize the remote inference function.\"\"\"\n        load_fn_kwargs = kwargs.pop(\"load_fn_kwargs\", {})\n        load_fn_kwargs[\"model_id\"] = load_fn_kwargs.get(\n            \"model_id\", DEFAULT_INSTRUCT_MODEL\n        )\n        load_fn_kwargs[\"instruct\"] = load_fn_kwargs.get(\"instruct\", True)\n        load_fn_kwargs[\"device\"] = load_fn_kwargs.get(\"device\", 0)\n        super().__init__(load_fn_kwargs=load_fn_kwargs, **kwargs)\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Compute doc embeddings using a HuggingFace instruct model.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        instruction_pairs = []\n        for text in texts:\n            instruction_pairs.append([self.embed_instruction, text])\n        embeddings = self.client(self.pipeline_ref, instruction_pairs)\n        return embeddings.tolist()\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Compute query embeddings using a HuggingFace instruct model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html"}
{"id": "f55490bf7f65-4", "text": "Returns:\n            Embeddings for the text.\n        \"\"\"\n        instruction_pair = [self.query_instruction, text]\n        embedding = self.client(self.pipeline_ref, [instruction_pair])[0]\n        return embedding.tolist()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html"}
{"id": "55f1e90718f2-0", "text": "Source code for langchain.embeddings.awa\nfrom typing import Any, Dict, List\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema.embeddings import Embeddings\n[docs]class AwaEmbeddings(BaseModel, Embeddings):\n    \"\"\"Embedding documents and queries with Awa DB.\n    Attributes:\n        client: The AwaEmbedding client.\n        model: The name of the model used for embedding.\n         Default is \"all-mpnet-base-v2\".\n    \"\"\"\n    client: Any  #: :meta private:\n    model: str = \"all-mpnet-base-v2\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that awadb library is installed.\"\"\"\n        try:\n            from awadb import AwaEmbedding\n        except ImportError as exc:\n            raise ImportError(\n                \"Could not import awadb library. \"\n                \"Please install it with `pip install awadb`\"\n            ) from exc\n        values[\"client\"] = AwaEmbedding()\n        return values\n[docs]    def set_model(self, model_name: str) -> None:\n        \"\"\"Set the model used for embedding.\n        The default model used is all-mpnet-base-v2\n        Args:\n            model_name: A string which represents the name of model.\n        \"\"\"\n        self.model = model_name\n        self.client.model_name = model_name\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Embed a list of documents using AwaEmbedding.\n        Args:\n            texts: The list of texts need to be embedded\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/awa.html"}
{"id": "55f1e90718f2-1", "text": "Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        return self.client.EmbeddingBatch(texts)\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Compute query embeddings using AwaEmbedding.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        return self.client.Embedding(text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/awa.html"}
{"id": "9451bfd14ba2-0", "text": "Source code for langchain.embeddings.baidu_qianfan_endpoint\nfrom __future__ import annotations\nimport logging\nfrom typing import Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class QianfanEmbeddingsEndpoint(BaseModel, Embeddings):\n    \"\"\"`Baidu Qianfan Embeddings` embedding models.\"\"\"\n    qianfan_ak: Optional[str] = None\n    \"\"\"Qianfan application apikey\"\"\"\n    qianfan_sk: Optional[str] = None\n    \"\"\"Qianfan application secretkey\"\"\"\n    chunk_size: int = 16\n    \"\"\"Chunk size when multiple texts are input\"\"\"\n    model: str = \"Embedding-V1\"\n    \"\"\"Model name\n    you could get from https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu\n    \n    for now, we support Embedding-V1 and \n    - Embedding-V1 \uff08\u9ed8\u8ba4\u6a21\u578b\uff09\n    - bge-large-en\n    - bge-large-zh\n    \n    preset models are mapping to an endpoint.\n    `model` will be ignored if `endpoint` is set\n    \"\"\"\n    endpoint: str = \"\"\n    \"\"\"Endpoint of the Qianfan Embedding, required if custom model used.\"\"\"\n    client: Any\n    \"\"\"Qianfan client\"\"\"\n    max_retries: int = 5\n    \"\"\"Max reties times\"\"\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"\n        Validate whether qianfan_ak and qianfan_sk in the environment variables or\n        configuration file are available or not.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/baidu_qianfan_endpoint.html"}
{"id": "9451bfd14ba2-1", "text": "configuration file are available or not.\n        init qianfan embedding client with `ak`, `sk`, `model`, `endpoint`\n        Args:\n            values: a dictionary containing configuration information, must include the\n            fields of qianfan_ak and qianfan_sk\n        Returns:\n            a dictionary containing configuration information. If qianfan_ak and\n            qianfan_sk are not provided in the environment variables or configuration\n            file,the original values will be returned; otherwise, values containing\n            qianfan_ak and qianfan_sk will be returned.\n        Raises:\n            ValueError: qianfan package not found, please install it with `pip install\n            qianfan`\n        \"\"\"\n        values[\"qianfan_ak\"] = get_from_dict_or_env(\n            values,\n            \"qianfan_ak\",\n            \"QIANFAN_AK\",\n        )\n        values[\"qianfan_sk\"] = get_from_dict_or_env(\n            values,\n            \"qianfan_sk\",\n            \"QIANFAN_SK\",\n        )\n        try:\n            import qianfan\n            params = {\n                \"ak\": values[\"qianfan_ak\"],\n                \"sk\": values[\"qianfan_sk\"],\n                \"model\": values[\"model\"],\n            }\n            if values[\"endpoint\"] is not None and values[\"endpoint\"] != \"\":\n                params[\"endpoint\"] = values[\"endpoint\"]\n            values[\"client\"] = qianfan.Embedding(**params)\n        except ImportError:\n            raise ImportError(\n                \"qianfan package not found, please install it with \"\n                \"`pip install qianfan`\"\n            )\n        return values\n[docs]    def embed_query(self, text: str) -> List[float]:\n        resp = self.embed_documents([text])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/baidu_qianfan_endpoint.html"}
{"id": "9451bfd14ba2-2", "text": "resp = self.embed_documents([text])\n        return resp[0]\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"\n        Embeds a list of text documents using the AutoVOT algorithm.\n        Args:\n            texts (List[str]): A list of text documents to embed.\n        Returns:\n            List[List[float]]: A list of embeddings for each document in the input list.\n                            Each embedding is represented as a list of float values.\n        \"\"\"\n        text_in_chunks = [\n            texts[i : i + self.chunk_size]\n            for i in range(0, len(texts), self.chunk_size)\n        ]\n        lst = []\n        for chunk in text_in_chunks:\n            resp = self.client.do(texts=chunk)\n            lst.extend([res[\"embedding\"] for res in resp[\"data\"]])\n        return lst\n[docs]    async def aembed_query(self, text: str) -> List[float]:\n        embeddings = await self.aembed_documents([text])\n        return embeddings[0]\n[docs]    async def aembed_documents(self, texts: List[str]) -> List[List[float]]:\n        text_in_chunks = [\n            texts[i : i + self.chunk_size]\n            for i in range(0, len(texts), self.chunk_size)\n        ]\n        lst = []\n        for chunk in text_in_chunks:\n            resp = await self.client.ado(texts=chunk)\n            for res in resp[\"data\"]:\n                lst.extend([res[\"embedding\"]])\n        return lst", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/baidu_qianfan_endpoint.html"}
{"id": "d314afe4a826-0", "text": "Source code for langchain.embeddings.javelin_ai_gateway\nfrom __future__ import annotations\nfrom typing import Any, Iterator, List, Optional\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema.embeddings import Embeddings\ndef _chunk(texts: List[str], size: int) -> Iterator[List[str]]:\n    for i in range(0, len(texts), size):\n        yield texts[i : i + size]\n[docs]class JavelinAIGatewayEmbeddings(Embeddings, BaseModel):\n    \"\"\"\n    Wrapper around embeddings LLMs in the Javelin AI Gateway.\n    To use, you should have the ``javelin_sdk`` python package installed.\n    For more information, see https://docs.getjavelin.io\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import JavelinAIGatewayEmbeddings\n            embeddings = JavelinAIGatewayEmbeddings(\n                gateway_uri=\"<javelin-ai-gateway-uri>\",\n                route=\"<your-javelin-gateway-embeddings-route>\"\n            )\n    \"\"\"\n    client: Any\n    \"\"\"javelin client.\"\"\"\n    route: str\n    \"\"\"The route to use for the Javelin AI Gateway API.\"\"\"\n    gateway_uri: Optional[str] = None\n    \"\"\"The URI for the Javelin AI Gateway API.\"\"\"\n    javelin_api_key: Optional[str] = None\n    \"\"\"The API key for the Javelin AI Gateway API.\"\"\"\n    def __init__(self, **kwargs: Any):\n        try:\n            from javelin_sdk import (\n                JavelinClient,\n                UnauthorizedError,\n            )\n        except ImportError:\n            raise ImportError(\n                \"Could not import javelin_sdk python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/javelin_ai_gateway.html"}
{"id": "d314afe4a826-1", "text": "raise ImportError(\n                \"Could not import javelin_sdk python package. \"\n                \"Please install it with `pip install javelin_sdk`.\"\n            )\n        super().__init__(**kwargs)\n        if self.gateway_uri:\n            try:\n                self.client = JavelinClient(\n                    base_url=self.gateway_uri, api_key=self.javelin_api_key\n                )\n            except UnauthorizedError as e:\n                raise ValueError(\"Javelin: Incorrect API Key.\") from e\n    def _query(self, texts: List[str]) -> List[List[float]]:\n        embeddings = []\n        for txt in _chunk(texts, 20):\n            try:\n                resp = self.client.query_route(self.route, query_body={\"input\": txt})\n                resp_dict = resp.dict()\n                embeddings_chunk = resp_dict.get(\"llm_response\", {}).get(\"data\", [])\n                for item in embeddings_chunk:\n                    if \"embedding\" in item:\n                        embeddings.append(item[\"embedding\"])\n            except ValueError as e:\n                print(\"Failed to query route: \" + str(e))\n        return embeddings\n    async def _aquery(self, texts: List[str]) -> List[List[float]]:\n        embeddings = []\n        for txt in _chunk(texts, 20):\n            try:\n                resp = await self.client.aquery_route(\n                    self.route, query_body={\"input\": txt}\n                )\n                resp_dict = resp.dict()\n                embeddings_chunk = resp_dict.get(\"llm_response\", {}).get(\"data\", [])\n                for item in embeddings_chunk:\n                    if \"embedding\" in item:\n                        embeddings.append(item[\"embedding\"])\n            except ValueError as e:\n                print(\"Failed to query route: \" + str(e))\n        return embeddings", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/javelin_ai_gateway.html"}
{"id": "d314afe4a826-2", "text": "print(\"Failed to query route: \" + str(e))\n        return embeddings\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        return self._query(texts)\n[docs]    def embed_query(self, text: str) -> List[float]:\n        return self._query([text])[0]\n[docs]    async def aembed_documents(self, texts: List[str]) -> List[List[float]]:\n        return await self._aquery(texts)\n[docs]    async def aembed_query(self, text: str) -> List[float]:\n        result = await self._aquery([text])\n        return result[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/javelin_ai_gateway.html"}
{"id": "4274382abceb-0", "text": "Source code for langchain.embeddings.self_hosted\nfrom typing import Any, Callable, List\nfrom langchain.llms.self_hosted import SelfHostedPipeline\nfrom langchain.pydantic_v1 import Extra\nfrom langchain.schema.embeddings import Embeddings\ndef _embed_documents(pipeline: Any, *args: Any, **kwargs: Any) -> List[List[float]]:\n    \"\"\"Inference function to send to the remote hardware.\n    Accepts a sentence_transformer model_id and\n    returns a list of embeddings for each document in the batch.\n    \"\"\"\n    return pipeline(*args, **kwargs)\n[docs]class SelfHostedEmbeddings(SelfHostedPipeline, Embeddings):\n    \"\"\"Custom embedding models on self-hosted remote hardware.\n    Supported hardware includes auto-launched instances on AWS, GCP, Azure,\n    and Lambda, as well as servers specified\n    by IP address and SSH credentials (such as on-prem, or another\n    cloud like Paperspace, Coreweave, etc.).\n    To use, you should have the ``runhouse`` python package installed.\n    Example using a model load function:\n        .. code-block:: python\n            from langchain.embeddings import SelfHostedEmbeddings\n            from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline\n            import runhouse as rh\n            gpu = rh.cluster(name=\"rh-a10x\", instance_type=\"A100:1\")\n            def get_pipeline():\n                model_id = \"facebook/bart-large\"\n                tokenizer = AutoTokenizer.from_pretrained(model_id)\n                model = AutoModelForCausalLM.from_pretrained(model_id)\n                return pipeline(\"feature-extraction\", model=model, tokenizer=tokenizer)\n            embeddings = SelfHostedEmbeddings(\n                model_load_fn=get_pipeline,\n                hardware=gpu", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html"}
{"id": "4274382abceb-1", "text": "model_load_fn=get_pipeline,\n                hardware=gpu\n                model_reqs=[\"./\", \"torch\", \"transformers\"],\n            )\n    Example passing in a pipeline path:\n        .. code-block:: python\n            from langchain.embeddings import SelfHostedHFEmbeddings\n            import runhouse as rh\n            from transformers import pipeline\n            gpu = rh.cluster(name=\"rh-a10x\", instance_type=\"A100:1\")\n            pipeline = pipeline(model=\"bert-base-uncased\", task=\"feature-extraction\")\n            rh.blob(pickle.dumps(pipeline),\n                path=\"models/pipeline.pkl\").save().to(gpu, path=\"models\")\n            embeddings = SelfHostedHFEmbeddings.from_pipeline(\n                pipeline=\"models/pipeline.pkl\",\n                hardware=gpu,\n                model_reqs=[\"./\", \"torch\", \"transformers\"],\n            )\n    \"\"\"\n    inference_fn: Callable = _embed_documents\n    \"\"\"Inference function to extract the embeddings on the remote hardware.\"\"\"\n    inference_kwargs: Any = None\n    \"\"\"Any kwargs to pass to the model's inference function.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Compute doc embeddings using a HuggingFace transformer model.\n        Args:\n            texts: The list of texts to embed.s\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        texts = list(map(lambda x: x.replace(\"\\n\", \" \"), texts))\n        embeddings = self.client(self.pipeline_ref, texts)\n        if not isinstance(embeddings, list):\n            return embeddings.tolist()\n        return embeddings\n[docs]    def embed_query(self, text: str) -> List[float]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html"}
{"id": "4274382abceb-2", "text": "[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Compute query embeddings using a HuggingFace transformer model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        text = text.replace(\"\\n\", \" \")\n        embeddings = self.client(self.pipeline_ref, text)\n        if not isinstance(embeddings, list):\n            return embeddings.tolist()\n        return embeddings", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html"}
{"id": "671b55d78689-0", "text": "Source code for langchain.embeddings.nlpcloud\nfrom typing import Any, Dict, List\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\n[docs]class NLPCloudEmbeddings(BaseModel, Embeddings):\n    \"\"\"NLP Cloud embedding models.\n    To use, you should have the nlpcloud python package installed\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import NLPCloudEmbeddings\n            embeddings = NLPCloudEmbeddings()\n    \"\"\"\n    model_name: str  # Define model_name as a class attribute\n    gpu: bool  # Define gpu as a class attribute\n    client: Any  #: :meta private:\n    def __init__(\n        self,\n        model_name: str = \"paraphrase-multilingual-mpnet-base-v2\",\n        gpu: bool = False,\n        **kwargs: Any,\n    ) -> None:\n        super().__init__(model_name=model_name, gpu=gpu, **kwargs)\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        nlpcloud_api_key = get_from_dict_or_env(\n            values, \"nlpcloud_api_key\", \"NLPCLOUD_API_KEY\"\n        )\n        try:\n            import nlpcloud\n            values[\"client\"] = nlpcloud.Client(\n                values[\"model_name\"], nlpcloud_api_key, gpu=values[\"gpu\"], lang=\"en\"\n            )\n        except ImportError:\n            raise ImportError(\n                \"Could not import nlpcloud python package. \"\n                \"Please install it with `pip install nlpcloud`.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/nlpcloud.html"}
{"id": "671b55d78689-1", "text": "\"Please install it with `pip install nlpcloud`.\"\n            )\n        return values\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Embed a list of documents using NLP Cloud.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        return self.client.embeddings(texts)[\"embeddings\"]\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed a query using NLP Cloud.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        return self.client.embeddings([text])[\"embeddings\"][0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/nlpcloud.html"}
{"id": "567d392a6389-0", "text": "Source code for langchain.embeddings.cohere\nfrom typing import Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env\n[docs]class CohereEmbeddings(BaseModel, Embeddings):\n    \"\"\"Cohere embedding models.\n    To use, you should have the ``cohere`` python package installed, and the\n    environment variable ``COHERE_API_KEY`` set with your API key or pass it\n    as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import CohereEmbeddings\n            cohere = CohereEmbeddings(\n                model=\"embed-english-light-v3.0\", cohere_api_key=\"my-api-key\"\n            )\n    \"\"\"\n    client: Any  #: :meta private:\n    \"\"\"Cohere client.\"\"\"\n    async_client: Any  #: :meta private:\n    \"\"\"Cohere async client.\"\"\"\n    model: str = \"embed-english-v2.0\"\n    \"\"\"Model name to use.\"\"\"\n    truncate: Optional[str] = None\n    \"\"\"Truncate embeddings that are too long from start or end (\"NONE\"|\"START\"|\"END\")\"\"\"\n    cohere_api_key: Optional[str] = None\n    max_retries: Optional[int] = None\n    \"\"\"Maximum number of retries to make when generating.\"\"\"\n    request_timeout: Optional[float] = None\n    \"\"\"Timeout in seconds for the Cohere API request.\"\"\"\n    user_agent: str = \"langchain\"\n    \"\"\"Identifier for the application making the request.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html"}
{"id": "567d392a6389-1", "text": "extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        cohere_api_key = get_from_dict_or_env(\n            values, \"cohere_api_key\", \"COHERE_API_KEY\"\n        )\n        max_retries = values.get(\"max_retries\")\n        request_timeout = values.get(\"request_timeout\")\n        try:\n            import cohere\n            client_name = values[\"user_agent\"]\n            values[\"client\"] = cohere.Client(\n                cohere_api_key,\n                max_retries=max_retries,\n                timeout=request_timeout,\n                client_name=client_name,\n            )\n            values[\"async_client\"] = cohere.AsyncClient(\n                cohere_api_key,\n                max_retries=max_retries,\n                timeout=request_timeout,\n                client_name=client_name,\n            )\n        except ImportError:\n            raise ValueError(\n                \"Could not import cohere python package. \"\n                \"Please install it with `pip install cohere`.\"\n            )\n        return values\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Call out to Cohere's embedding endpoint.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        embeddings = self.client.embed(\n            model=self.model,\n            texts=texts,\n            input_type=\"search_document\",\n            truncate=self.truncate,\n        ).embeddings\n        return [list(map(float, e)) for e in embeddings]\n[docs]    async def aembed_documents(self, texts: List[str]) -> List[List[float]]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html"}
{"id": "567d392a6389-2", "text": "\"\"\"Async call out to Cohere's embedding endpoint.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        embeddings = await self.async_client.embed(\n            model=self.model,\n            texts=texts,\n            input_type=\"search_document\",\n            truncate=self.truncate,\n        )\n        return [list(map(float, e)) for e in embeddings.embeddings]\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to Cohere's embedding endpoint.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        embeddings = self.client.embed(\n            model=self.model,\n            texts=[text],\n            input_type=\"search_query\",\n            truncate=self.truncate,\n        ).embeddings\n        return [list(map(float, e)) for e in embeddings][0]\n[docs]    async def aembed_query(self, text: str) -> List[float]:\n        \"\"\"Async call out to Cohere's embedding endpoint.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        embeddings = await self.async_client.embed(\n            model=self.model,\n            texts=[text],\n            input_type=\"search_query\",\n            truncate=self.truncate,\n        )\n        return [list(map(float, e)) for e in embeddings.embeddings][0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html"}
{"id": "3f0ad75bcb3a-0", "text": "Source code for langchain.embeddings.mlflow_gateway\nfrom __future__ import annotations\nfrom typing import Any, Iterator, List, Optional\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema.embeddings import Embeddings\ndef _chunk(texts: List[str], size: int) -> Iterator[List[str]]:\n    for i in range(0, len(texts), size):\n        yield texts[i : i + size]\n[docs]class MlflowAIGatewayEmbeddings(Embeddings, BaseModel):\n    \"\"\"\n    Wrapper around embeddings LLMs in the MLflow AI Gateway.\n    To use, you should have the ``mlflow[gateway]`` python package installed.\n    For more information, see https://mlflow.org/docs/latest/gateway/index.html.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import MlflowAIGatewayEmbeddings\n            embeddings = MlflowAIGatewayEmbeddings(\n                gateway_uri=\"<your-mlflow-ai-gateway-uri>\",\n                route=\"<your-mlflow-ai-gateway-embeddings-route>\"\n            )\n    \"\"\"\n    route: str\n    \"\"\"The route to use for the MLflow AI Gateway API.\"\"\"\n    gateway_uri: Optional[str] = None\n    \"\"\"The URI for the MLflow AI Gateway API.\"\"\"\n    def __init__(self, **kwargs: Any):\n        try:\n            import mlflow.gateway\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import `mlflow.gateway` module. \"\n                \"Please install it with `pip install mlflow[gateway]`.\"\n            ) from e\n        super().__init__(**kwargs)\n        if self.gateway_uri:\n            mlflow.gateway.set_gateway_uri(self.gateway_uri)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/mlflow_gateway.html"}
{"id": "3f0ad75bcb3a-1", "text": "if self.gateway_uri:\n            mlflow.gateway.set_gateway_uri(self.gateway_uri)\n    def _query(self, texts: List[str]) -> List[List[float]]:\n        try:\n            import mlflow.gateway\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import `mlflow.gateway` module. \"\n                \"Please install it with `pip install mlflow[gateway]`.\"\n            ) from e\n        embeddings = []\n        for txt in _chunk(texts, 20):\n            resp = mlflow.gateway.query(self.route, data={\"text\": txt})\n            embeddings.append(resp[\"embeddings\"])\n        return embeddings\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        return self._query(texts)\n[docs]    def embed_query(self, text: str) -> List[float]:\n        return self._query([text])[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/mlflow_gateway.html"}
{"id": "0b8b0f0e24a0-0", "text": "Source code for langchain.embeddings.ollama\nfrom typing import Any, Dict, List, Mapping, Optional\nimport requests\nfrom langchain.pydantic_v1 import BaseModel, Extra\nfrom langchain.schema.embeddings import Embeddings\n[docs]class OllamaEmbeddings(BaseModel, Embeddings):\n    \"\"\"Ollama locally runs large language models.\n    To use, follow the instructions at https://ollama.ai/.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import OllamaEmbeddings\n            ollama_emb = OllamaEmbeddings(\n                model=\"llama:7b\",\n            )\n            r1 = ollama_emb.embed_documents(\n                [\n                    \"Alpha is the first letter of Greek alphabet\",\n                    \"Beta is the second letter of Greek alphabet\",\n                ]\n            )\n            r2 = ollama_emb.embed_query(\n                \"What is the second letter of Greek alphabet\"\n            )\n    \"\"\"\n    base_url: str = \"http://localhost:11434\"\n    \"\"\"Base url the model is hosted under.\"\"\"\n    model: str = \"llama2\"\n    \"\"\"Model name to use.\"\"\"\n    embed_instruction: str = \"passage: \"\n    \"\"\"Instruction used to embed documents.\"\"\"\n    query_instruction: str = \"query: \"\n    \"\"\"Instruction used to embed the query.\"\"\"\n    mirostat: Optional[int] = None\n    \"\"\"Enable Mirostat sampling for controlling perplexity.\n    (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\"\"\"\n    mirostat_eta: Optional[float] = None\n    \"\"\"Influences how quickly the algorithm responds to feedback\n    from the generated text. A lower learning rate will result in", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html"}
{"id": "0b8b0f0e24a0-1", "text": "from the generated text. A lower learning rate will result in\n    slower adjustments, while a higher learning rate will make\n    the algorithm more responsive. (Default: 0.1)\"\"\"\n    mirostat_tau: Optional[float] = None\n    \"\"\"Controls the balance between coherence and diversity\n    of the output. A lower value will result in more focused and\n    coherent text. (Default: 5.0)\"\"\"\n    num_ctx: Optional[int] = None\n    \"\"\"Sets the size of the context window used to generate the\n    next token. (Default: 2048)\t\"\"\"\n    num_gpu: Optional[int] = None\n    \"\"\"The number of GPUs to use. On macOS it defaults to 1 to\n    enable metal support, 0 to disable.\"\"\"\n    num_thread: Optional[int] = None\n    \"\"\"Sets the number of threads to use during computation.\n    By default, Ollama will detect this for optimal performance.\n    It is recommended to set this value to the number of physical\n    CPU cores your system has (as opposed to the logical number of cores).\"\"\"\n    repeat_last_n: Optional[int] = None\n    \"\"\"Sets how far back for the model to look back to prevent\n    repetition. (Default: 64, 0 = disabled, -1 = num_ctx)\"\"\"\n    repeat_penalty: Optional[float] = None\n    \"\"\"Sets how strongly to penalize repetitions. A higher value (e.g., 1.5)\n    will penalize repetitions more strongly, while a lower value (e.g., 0.9)\n    will be more lenient. (Default: 1.1)\"\"\"\n    temperature: Optional[float] = None\n    \"\"\"The temperature of the model. Increasing the temperature will\n    make the model answer more creatively. (Default: 0.8)\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html"}
{"id": "0b8b0f0e24a0-2", "text": "make the model answer more creatively. (Default: 0.8)\"\"\"\n    stop: Optional[List[str]] = None\n    \"\"\"Sets the stop tokens to use.\"\"\"\n    tfs_z: Optional[float] = None\n    \"\"\"Tail free sampling is used to reduce the impact of less probable\n    tokens from the output. A higher value (e.g., 2.0) will reduce the\n    impact more, while a value of 1.0 disables this setting. (default: 1)\"\"\"\n    top_k: Optional[int] = None\n    \"\"\"Reduces the probability of generating nonsense. A higher value (e.g. 100)\n    will give more diverse answers, while a lower value (e.g. 10)\n    will be more conservative. (Default: 40)\"\"\"\n    top_p: Optional[int] = None\n    \"\"\"Works together with top-k. A higher value (e.g., 0.95) will lead\n    to more diverse text, while a lower value (e.g., 0.5) will\n    generate more focused and conservative text. (Default: 0.9)\"\"\"\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Ollama.\"\"\"\n        return {\n            \"model\": self.model,\n            \"options\": {\n                \"mirostat\": self.mirostat,\n                \"mirostat_eta\": self.mirostat_eta,\n                \"mirostat_tau\": self.mirostat_tau,\n                \"num_ctx\": self.num_ctx,\n                \"num_gpu\": self.num_gpu,\n                \"num_thread\": self.num_thread,\n                \"repeat_last_n\": self.repeat_last_n,\n                \"repeat_penalty\": self.repeat_penalty,\n                \"temperature\": self.temperature,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html"}
{"id": "0b8b0f0e24a0-3", "text": "\"repeat_penalty\": self.repeat_penalty,\n                \"temperature\": self.temperature,\n                \"stop\": self.stop,\n                \"tfs_z\": self.tfs_z,\n                \"top_k\": self.top_k,\n                \"top_p\": self.top_p,\n            },\n        }\n    model_kwargs: Optional[dict] = None\n    \"\"\"Other model keyword args\"\"\"\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model\": self.model}, **self._default_params}\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    def _process_emb_response(self, input: str) -> List[float]:\n        \"\"\"Process a response from the API.\n        Args:\n            response: The response from the API.\n        Returns:\n            The response as a dictionary.\n        \"\"\"\n        headers = {\n            \"Content-Type\": \"application/json\",\n        }\n        try:\n            res = requests.post(\n                f\"{self.base_url}/api/embeddings\",\n                headers=headers,\n                json={\"model\": self.model, \"prompt\": input, **self._default_params},\n            )\n        except requests.exceptions.RequestException as e:\n            raise ValueError(f\"Error raised by inference endpoint: {e}\")\n        if res.status_code != 200:\n            raise ValueError(\n                \"Error raised by inference API HTTP code: %s, %s\"\n                % (res.status_code, res.text)\n            )\n        try:\n            t = res.json()\n            return t[\"embedding\"]\n        except requests.exceptions.JSONDecodeError as e:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html"}
{"id": "0b8b0f0e24a0-4", "text": "except requests.exceptions.JSONDecodeError as e:\n            raise ValueError(\n                f\"Error raised by inference API: {e}.\\nResponse: {res.text}\"\n            )\n    def _embed(self, input: List[str]) -> List[List[float]]:\n        embeddings_list: List[List[float]] = []\n        for prompt in input:\n            embeddings = self._process_emb_response(prompt)\n            embeddings_list.append(embeddings)\n        return embeddings_list\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Embed documents using a Ollama deployed embedding model.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        instruction_pairs = [f\"{self.embed_instruction}{text}\" for text in texts]\n        embeddings = self._embed(instruction_pairs)\n        return embeddings\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed a query using a Ollama deployed embedding model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        instruction_pair = f\"{self.query_instruction}{text}\"\n        embedding = self._embed([instruction_pair])[0]\n        return embedding", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html"}
{"id": "053d28d89110-0", "text": "Source code for langchain.embeddings.edenai\nfrom typing import Any, Dict, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utilities.requests import Requests\nfrom langchain.utils import get_from_dict_or_env\n[docs]class EdenAiEmbeddings(BaseModel, Embeddings):\n    \"\"\"EdenAI embedding.\n    environment variable ``EDENAI_API_KEY`` set with your API key, or pass\n    it as a named parameter.\n    \"\"\"\n    edenai_api_key: Optional[str] = Field(None, description=\"EdenAI API Token\")\n    provider: str = \"openai\"\n    \"\"\"embedding provider to use (eg: openai,google etc.)\"\"\"\n    model: Optional[str] = None\n    \"\"\"\n    model name for above provider (eg: 'text-davinci-003' for openai)\n    available models are shown on https://docs.edenai.co/ under 'available providers'\n    \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key exists in environment.\"\"\"\n        values[\"edenai_api_key\"] = get_from_dict_or_env(\n            values, \"edenai_api_key\", \"EDENAI_API_KEY\"\n        )\n        return values\n[docs]    @staticmethod\n    def get_user_agent() -> str:\n        from langchain import __version__\n        return f\"langchain/{__version__}\"\n    def _generate_embeddings(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Compute embeddings using EdenAi api.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/edenai.html"}
{"id": "053d28d89110-1", "text": "\"\"\"Compute embeddings using EdenAi api.\"\"\"\n        url = \"https://api.edenai.run/v2/text/embeddings\"\n        headers = {\n            \"accept\": \"application/json\",\n            \"content-type\": \"application/json\",\n            \"authorization\": f\"Bearer {self.edenai_api_key}\",\n            \"User-Agent\": self.get_user_agent(),\n        }\n        payload: Dict[str, Any] = {\"texts\": texts, \"providers\": self.provider}\n        if self.model is not None:\n            payload[\"settings\"] = {self.provider: self.model}\n        request = Requests(headers=headers)\n        response = request.post(url=url, data=payload)\n        if response.status_code >= 500:\n            raise Exception(f\"EdenAI Server: Error {response.status_code}\")\n        elif response.status_code >= 400:\n            raise ValueError(f\"EdenAI received an invalid payload: {response.text}\")\n        elif response.status_code != 200:\n            raise Exception(\n                f\"EdenAI returned an unexpected response with status \"\n                f\"{response.status_code}: {response.text}\"\n            )\n        temp = response.json()\n        provider_response = temp[self.provider]\n        if provider_response.get(\"status\") == \"fail\":\n            err_msg = provider_response.get(\"error\", {}).get(\"message\")\n            raise Exception(err_msg)\n        embeddings = []\n        for embed_item in temp[self.provider][\"items\"]:\n            embedding = embed_item[\"embedding\"]\n            embeddings.append(embedding)\n        return embeddings\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Embed a list of documents using EdenAI.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/edenai.html"}
{"id": "053d28d89110-2", "text": "Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        return self._generate_embeddings(texts)\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed a query using EdenAI.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        return self._generate_embeddings([text])[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/edenai.html"}
{"id": "a5b51ff0a9bf-0", "text": "Source code for langchain.embeddings.gpt4all\nfrom typing import Any, Dict, List\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema.embeddings import Embeddings\n[docs]class GPT4AllEmbeddings(BaseModel, Embeddings):\n    \"\"\"GPT4All embedding models.\n    To use, you should have the gpt4all python package installed\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import GPT4AllEmbeddings\n            embeddings = GPT4AllEmbeddings()\n    \"\"\"\n    client: Any  #: :meta private:\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that GPT4All library is installed.\"\"\"\n        try:\n            from gpt4all import Embed4All\n            values[\"client\"] = Embed4All()\n        except ImportError:\n            raise ImportError(\n                \"Could not import gpt4all library. \"\n                \"Please install the gpt4all library to \"\n                \"use this embedding model: pip install gpt4all\"\n            )\n        return values\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Embed a list of documents using GPT4All.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        embeddings = [self.client.embed(text) for text in texts]\n        return [list(map(float, e)) for e in embeddings]\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed a query using GPT4All.\n        Args:\n            text: The text to embed.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gpt4all.html"}
{"id": "a5b51ff0a9bf-1", "text": "Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        return self.embed_documents([text])[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gpt4all.html"}
{"id": "71c07b4045a3-0", "text": "Source code for langchain.embeddings.openai\nfrom __future__ import annotations\nimport logging\nimport os\nimport warnings\nfrom importlib.metadata import version\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    List,\n    Literal,\n    Mapping,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    Union,\n    cast,\n)\nimport numpy as np\nfrom packaging.version import Version, parse\nfrom tenacity import (\n    AsyncRetrying,\n    before_sleep_log,\n    retry,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils import get_from_dict_or_env, get_pydantic_field_names\nlogger = logging.getLogger(__name__)\ndef _create_retry_decorator(embeddings: OpenAIEmbeddings) -> Callable[[Any], Any]:\n    import openai\n    min_seconds = 4\n    max_seconds = 10\n    # Wait 2^x * 1 second between each retry starting with\n    # 4 seconds, then up to 10 seconds, then 10 seconds afterwards\n    return retry(\n        reraise=True,\n        stop=stop_after_attempt(embeddings.max_retries),\n        wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),\n        retry=(\n            retry_if_exception_type(openai.error.Timeout)\n            | retry_if_exception_type(openai.error.APIError)\n            | retry_if_exception_type(openai.error.APIConnectionError)\n            | retry_if_exception_type(openai.error.RateLimitError)\n            | retry_if_exception_type(openai.error.ServiceUnavailableError)\n        ),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-1", "text": "| retry_if_exception_type(openai.error.ServiceUnavailableError)\n        ),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\ndef _async_retry_decorator(embeddings: OpenAIEmbeddings) -> Any:\n    import openai\n    min_seconds = 4\n    max_seconds = 10\n    # Wait 2^x * 1 second between each retry starting with\n    # 4 seconds, then up to 10 seconds, then 10 seconds afterwards\n    async_retrying = AsyncRetrying(\n        reraise=True,\n        stop=stop_after_attempt(embeddings.max_retries),\n        wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),\n        retry=(\n            retry_if_exception_type(openai.error.Timeout)\n            | retry_if_exception_type(openai.error.APIError)\n            | retry_if_exception_type(openai.error.APIConnectionError)\n            | retry_if_exception_type(openai.error.RateLimitError)\n            | retry_if_exception_type(openai.error.ServiceUnavailableError)\n        ),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\n    def wrap(func: Callable) -> Callable:\n        async def wrapped_f(*args: Any, **kwargs: Any) -> Callable:\n            async for _ in async_retrying:\n                return await func(*args, **kwargs)\n            raise AssertionError(\"this is unreachable\")\n        return wrapped_f\n    return wrap\n# https://stackoverflow.com/questions/76469415/getting-embeddings-of-length-1-from-langchain-openaiembeddings\ndef _check_response(response: dict, skip_empty: bool = False) -> dict:\n    if any(len(d[\"embedding\"]) == 1 for d in response[\"data\"]) and not skip_empty:\n        import openai", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-2", "text": "import openai\n        raise openai.error.APIError(\"OpenAI API returned an empty embedding\")\n    return response\n[docs]def embed_with_retry(embeddings: OpenAIEmbeddings, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the embedding call.\"\"\"\n    if _is_openai_v1():\n        return embeddings.client.create(**kwargs)\n    retry_decorator = _create_retry_decorator(embeddings)\n    @retry_decorator\n    def _embed_with_retry(**kwargs: Any) -> Any:\n        response = embeddings.client.create(**kwargs)\n        return _check_response(response, skip_empty=embeddings.skip_empty)\n    return _embed_with_retry(**kwargs)\n[docs]async def async_embed_with_retry(embeddings: OpenAIEmbeddings, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the embedding call.\"\"\"\n    if _is_openai_v1():\n        return await embeddings.async_client.create(**kwargs)\n    @_async_retry_decorator(embeddings)\n    async def _async_embed_with_retry(**kwargs: Any) -> Any:\n        response = await embeddings.client.acreate(**kwargs)\n        return _check_response(response, skip_empty=embeddings.skip_empty)\n    return await _async_embed_with_retry(**kwargs)\ndef _is_openai_v1() -> bool:\n    _version = parse(version(\"openai\"))\n    return _version >= Version(\"1.0.0\")\n[docs]class OpenAIEmbeddings(BaseModel, Embeddings):\n    \"\"\"OpenAI embedding models.\n    To use, you should have the ``openai`` python package installed, and the\n    environment variable ``OPENAI_API_KEY`` set with your API key or pass it\n    as a named parameter to the constructor.\n    Example:\n        .. code-block:: python", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-3", "text": "Example:\n        .. code-block:: python\n            from langchain.embeddings import OpenAIEmbeddings\n            openai = OpenAIEmbeddings(openai_api_key=\"my-api-key\")\n    In order to use the library with Microsoft Azure endpoints, you need to set\n    the OPENAI_API_TYPE, OPENAI_API_BASE, OPENAI_API_KEY and OPENAI_API_VERSION.\n    The OPENAI_API_TYPE must be set to 'azure' and the others correspond to\n    the properties of your endpoint.\n    In addition, the deployment name must be passed as the model parameter.\n    Example:\n        .. code-block:: python\n            import os\n            os.environ[\"OPENAI_API_TYPE\"] = \"azure\"\n            os.environ[\"OPENAI_API_BASE\"] = \"https://<your-endpoint.openai.azure.com/\"\n            os.environ[\"OPENAI_API_KEY\"] = \"your AzureOpenAI key\"\n            os.environ[\"OPENAI_API_VERSION\"] = \"2023-05-15\"\n            os.environ[\"OPENAI_PROXY\"] = \"http://your-corporate-proxy:8080\"\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            embeddings = OpenAIEmbeddings(\n                deployment=\"your-embeddings-deployment-name\",\n                model=\"your-embeddings-model-name\",\n                openai_api_base=\"https://your-endpoint.openai.azure.com/\",\n                openai_api_type=\"azure\",\n            )\n            text = \"This is a test query.\"\n            query_result = embeddings.embed_query(text)\n    \"\"\"\n    client: Any = Field(default=None, exclude=True)  #: :meta private:\n    async_client: Any = Field(default=None, exclude=True)  #: :meta private:\n    model: str = \"text-embedding-ada-002\"\n    # to support Azure OpenAI Service custom deployment names", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-4", "text": "# to support Azure OpenAI Service custom deployment names\n    deployment: Optional[str] = model\n    # TODO: Move to AzureOpenAIEmbeddings.\n    openai_api_version: Optional[str] = Field(default=None, alias=\"api_version\")\n    \"\"\"Automatically inferred from env var `OPENAI_API_VERSION` if not provided.\"\"\"\n    # to support Azure OpenAI Service custom endpoints\n    openai_api_base: Optional[str] = Field(default=None, alias=\"base_url\")\n    \"\"\"Base URL path for API requests, leave blank if not using a proxy or service \n        emulator.\"\"\"\n    # to support Azure OpenAI Service custom endpoints\n    openai_api_type: Optional[str] = None\n    # to support explicit proxy for OpenAI\n    openai_proxy: Optional[str] = None\n    embedding_ctx_length: int = 8191\n    \"\"\"The maximum number of tokens to embed at once.\"\"\"\n    openai_api_key: Optional[str] = Field(default=None, alias=\"api_key\")\n    \"\"\"Automatically inferred from env var `OPENAI_API_KEY` if not provided.\"\"\"\n    openai_organization: Optional[str] = Field(default=None, alias=\"organization\")\n    \"\"\"Automatically inferred from env var `OPENAI_ORG_ID` if not provided.\"\"\"\n    allowed_special: Union[Literal[\"all\"], Set[str]] = set()\n    disallowed_special: Union[Literal[\"all\"], Set[str], Sequence[str]] = \"all\"\n    chunk_size: int = 1000\n    \"\"\"Maximum number of texts to embed in each batch\"\"\"\n    max_retries: int = 2\n    \"\"\"Maximum number of retries to make when generating.\"\"\"\n    request_timeout: Optional[Union[float, Tuple[float, float], Any]] = Field(\n        default=None, alias=\"timeout\"\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-5", "text": "default=None, alias=\"timeout\"\n    )\n    \"\"\"Timeout for requests to OpenAI completion API. Can be float, httpx.Timeout or \n        None.\"\"\"\n    headers: Any = None\n    tiktoken_model_name: Optional[str] = None\n    \"\"\"The model name to pass to tiktoken when using this class. \n    Tiktoken is used to count the number of tokens in documents to constrain \n    them to be under a certain limit. By default, when set to None, this will \n    be the same as the embedding model name. However, there are some cases \n    where you may want to use this Embedding class with a model name not \n    supported by tiktoken. This can include when using Azure embeddings or \n    when using one of the many model providers that expose an OpenAI-like \n    API but with different models. In those cases, in order to avoid erroring \n    when tiktoken is called, you can specify a model name to use here.\"\"\"\n    show_progress_bar: bool = False\n    \"\"\"Whether to show a progress bar when embedding.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not explicitly specified.\"\"\"\n    skip_empty: bool = False\n    \"\"\"Whether to skip empty strings when embedding or raise an error.\n    Defaults to not skipping.\"\"\"\n    default_headers: Union[Mapping[str, str], None] = None\n    default_query: Union[Mapping[str, object], None] = None\n    # Configure a custom httpx client. See the\n    # [httpx documentation](https://www.python-httpx.org/api/#client) for more details.\n    http_client: Union[Any, None] = None\n    \"\"\"Optional httpx.Client.\"\"\"\n    class Config:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-6", "text": "\"\"\"Optional httpx.Client.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        allow_population_by_field_name = True\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = get_pydantic_field_names(cls)\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name in extra:\n                raise ValueError(f\"Found {field_name} supplied twice.\")\n            if field_name not in all_required_field_names:\n                warnings.warn(\n                    f\"\"\"WARNING! {field_name} is not default parameter.\n                    {field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        invalid_model_kwargs = all_required_field_names.intersection(extra.keys())\n        if invalid_model_kwargs:\n            raise ValueError(\n                f\"Parameters {invalid_model_kwargs} should be specified explicitly. \"\n                f\"Instead they were passed in as part of `model_kwargs` parameter.\"\n            )\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"openai_api_key\"] = get_from_dict_or_env(\n            values, \"openai_api_key\", \"OPENAI_API_KEY\"\n        )\n        values[\"openai_api_base\"] = values[\"openai_api_base\"] or os.getenv(\n            \"OPENAI_API_BASE\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-7", "text": "\"OPENAI_API_BASE\"\n        )\n        values[\"openai_api_type\"] = get_from_dict_or_env(\n            values,\n            \"openai_api_type\",\n            \"OPENAI_API_TYPE\",\n            default=\"\",\n        )\n        values[\"openai_proxy\"] = get_from_dict_or_env(\n            values,\n            \"openai_proxy\",\n            \"OPENAI_PROXY\",\n            default=\"\",\n        )\n        if values[\"openai_api_type\"] in (\"azure\", \"azure_ad\", \"azuread\"):\n            default_api_version = \"2023-05-15\"\n            # Azure OpenAI embedding models allow a maximum of 16 texts\n            # at a time in each batch\n            # See: https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#embeddings\n            values[\"chunk_size\"] = max(values[\"chunk_size\"], 16)\n        else:\n            default_api_version = \"\"\n        values[\"openai_api_version\"] = get_from_dict_or_env(\n            values,\n            \"openai_api_version\",\n            \"OPENAI_API_VERSION\",\n            default=default_api_version,\n        )\n        # Check OPENAI_ORGANIZATION for backwards compatibility.\n        values[\"openai_organization\"] = (\n            values[\"openai_organization\"]\n            or os.getenv(\"OPENAI_ORG_ID\")\n            or os.getenv(\"OPENAI_ORGANIZATION\")\n        )\n        try:\n            import openai\n        except ImportError:\n            raise ImportError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\"\n            )\n        else:\n            if _is_openai_v1():\n                if values[\"openai_api_type\"] in (\"azure\", \"azure_ad\", \"azuread\"):\n                    warnings.warn(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-8", "text": "warnings.warn(\n                        \"If you have openai>=1.0.0 installed and are using Azure, \"\n                        \"please use the `AzureOpenAIEmbeddings` class.\"\n                    )\n                client_params = {\n                    \"api_key\": values[\"openai_api_key\"],\n                    \"organization\": values[\"openai_organization\"],\n                    \"base_url\": values[\"openai_api_base\"],\n                    \"timeout\": values[\"request_timeout\"],\n                    \"max_retries\": values[\"max_retries\"],\n                    \"default_headers\": values[\"default_headers\"],\n                    \"default_query\": values[\"default_query\"],\n                    \"http_client\": values[\"http_client\"],\n                }\n                if not values.get(\"client\"):\n                    values[\"client\"] = openai.OpenAI(**client_params).embeddings\n                if not values.get(\"async_client\"):\n                    values[\"async_client\"] = openai.AsyncOpenAI(\n                        **client_params\n                    ).embeddings\n            elif not values.get(\"client\"):\n                values[\"client\"] = openai.Embedding\n            else:\n                pass\n        return values\n    @property\n    def _invocation_params(self) -> Dict[str, Any]:\n        if _is_openai_v1():\n            openai_args: Dict = {\"model\": self.model, **self.model_kwargs}\n        else:\n            openai_args = {\n                \"model\": self.model,\n                \"request_timeout\": self.request_timeout,\n                \"headers\": self.headers,\n                \"api_key\": self.openai_api_key,\n                \"organization\": self.openai_organization,\n                \"api_base\": self.openai_api_base,\n                \"api_type\": self.openai_api_type,\n                \"api_version\": self.openai_api_version,\n                **self.model_kwargs,\n            }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-9", "text": "**self.model_kwargs,\n            }\n            if self.openai_api_type in (\"azure\", \"azure_ad\", \"azuread\"):\n                openai_args[\"engine\"] = self.deployment\n            # TODO: Look into proxy with openai v1.\n            if self.openai_proxy:\n                try:\n                    import openai\n                except ImportError:\n                    raise ImportError(\n                        \"Could not import openai python package. \"\n                        \"Please install it with `pip install openai`.\"\n                    )\n                openai.proxy = {\n                    \"http\": self.openai_proxy,\n                    \"https\": self.openai_proxy,\n                }  # type: ignore[assignment]  # noqa: E501\n        return openai_args\n    # please refer to\n    # https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb\n    def _get_len_safe_embeddings(\n        self, texts: List[str], *, engine: str, chunk_size: Optional[int] = None\n    ) -> List[List[float]]:\n        embeddings: List[List[float]] = [[] for _ in range(len(texts))]\n        try:\n            import tiktoken\n        except ImportError:\n            raise ImportError(\n                \"Could not import tiktoken python package. \"\n                \"This is needed in order to for OpenAIEmbeddings. \"\n                \"Please install it with `pip install tiktoken`.\"\n            )\n        tokens = []\n        indices = []\n        model_name = self.tiktoken_model_name or self.model\n        try:\n            encoding = tiktoken.encoding_for_model(model_name)\n        except KeyError:\n            logger.warning(\"Warning: model not found. Using cl100k_base encoding.\")\n            model = \"cl100k_base\"\n            encoding = tiktoken.get_encoding(model)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-10", "text": "model = \"cl100k_base\"\n            encoding = tiktoken.get_encoding(model)\n        for i, text in enumerate(texts):\n            if self.model.endswith(\"001\"):\n                # See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500\n                # replace newlines, which can negatively affect performance.\n                text = text.replace(\"\\n\", \" \")\n            token = encoding.encode(\n                text,\n                allowed_special=self.allowed_special,\n                disallowed_special=self.disallowed_special,\n            )\n            for j in range(0, len(token), self.embedding_ctx_length):\n                tokens.append(token[j : j + self.embedding_ctx_length])\n                indices.append(i)\n        batched_embeddings: List[List[float]] = []\n        _chunk_size = chunk_size or self.chunk_size\n        if self.show_progress_bar:\n            try:\n                from tqdm.auto import tqdm\n                _iter = tqdm(range(0, len(tokens), _chunk_size))\n            except ImportError:\n                _iter = range(0, len(tokens), _chunk_size)\n        else:\n            _iter = range(0, len(tokens), _chunk_size)\n        for i in _iter:\n            response = embed_with_retry(\n                self,\n                input=tokens[i : i + _chunk_size],\n                **self._invocation_params,\n            )\n            if not isinstance(response, dict):\n                response = response.dict()\n            batched_embeddings.extend(r[\"embedding\"] for r in response[\"data\"])\n        results: List[List[List[float]]] = [[] for _ in range(len(texts))]\n        num_tokens_in_batch: List[List[int]] = [[] for _ in range(len(texts))]\n        for i in range(len(indices)):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-11", "text": "for i in range(len(indices)):\n            if self.skip_empty and len(batched_embeddings[i]) == 1:\n                continue\n            results[indices[i]].append(batched_embeddings[i])\n            num_tokens_in_batch[indices[i]].append(len(tokens[i]))\n        for i in range(len(texts)):\n            _result = results[i]\n            if len(_result) == 0:\n                average_embedded = embed_with_retry(\n                    self,\n                    input=\"\",\n                    **self._invocation_params,\n                )\n                if not isinstance(average_embedded, dict):\n                    average_embedded = average_embedded.dict()\n                average = average_embedded[\"data\"][0][\"embedding\"]\n            else:\n                average = np.average(_result, axis=0, weights=num_tokens_in_batch[i])\n            embeddings[i] = (average / np.linalg.norm(average)).tolist()\n        return embeddings\n    # please refer to\n    # https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb\n    async def _aget_len_safe_embeddings(\n        self, texts: List[str], *, engine: str, chunk_size: Optional[int] = None\n    ) -> List[List[float]]:\n        embeddings: List[List[float]] = [[] for _ in range(len(texts))]\n        try:\n            import tiktoken\n        except ImportError:\n            raise ImportError(\n                \"Could not import tiktoken python package. \"\n                \"This is needed in order to for OpenAIEmbeddings. \"\n                \"Please install it with `pip install tiktoken`.\"\n            )\n        tokens = []\n        indices = []\n        model_name = self.tiktoken_model_name or self.model\n        try:\n            encoding = tiktoken.encoding_for_model(model_name)\n        except KeyError:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-12", "text": "encoding = tiktoken.encoding_for_model(model_name)\n        except KeyError:\n            logger.warning(\"Warning: model not found. Using cl100k_base encoding.\")\n            model = \"cl100k_base\"\n            encoding = tiktoken.get_encoding(model)\n        for i, text in enumerate(texts):\n            if self.model.endswith(\"001\"):\n                # See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500\n                # replace newlines, which can negatively affect performance.\n                text = text.replace(\"\\n\", \" \")\n            token = encoding.encode(\n                text,\n                allowed_special=self.allowed_special,\n                disallowed_special=self.disallowed_special,\n            )\n            for j in range(0, len(token), self.embedding_ctx_length):\n                tokens.append(token[j : j + self.embedding_ctx_length])\n                indices.append(i)\n        batched_embeddings: List[List[float]] = []\n        _chunk_size = chunk_size or self.chunk_size\n        for i in range(0, len(tokens), _chunk_size):\n            response = await async_embed_with_retry(\n                self,\n                input=tokens[i : i + _chunk_size],\n                **self._invocation_params,\n            )\n            if not isinstance(response, dict):\n                response = response.dict()\n            batched_embeddings.extend(r[\"embedding\"] for r in response[\"data\"])\n        results: List[List[List[float]]] = [[] for _ in range(len(texts))]\n        num_tokens_in_batch: List[List[int]] = [[] for _ in range(len(texts))]\n        for i in range(len(indices)):\n            results[indices[i]].append(batched_embeddings[i])\n            num_tokens_in_batch[indices[i]].append(len(tokens[i]))\n        for i in range(len(texts)):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-13", "text": "for i in range(len(texts)):\n            _result = results[i]\n            if len(_result) == 0:\n                average_embedded = embed_with_retry(\n                    self,\n                    input=\"\",\n                    **self._invocation_params,\n                )\n                if not isinstance(average_embedded, dict):\n                    average_embedded = average_embedded.dict()\n                average = average_embedded[\"data\"][0][\"embedding\"]\n            else:\n                average = np.average(_result, axis=0, weights=num_tokens_in_batch[i])\n            embeddings[i] = (average / np.linalg.norm(average)).tolist()\n        return embeddings\n[docs]    def embed_documents(\n        self, texts: List[str], chunk_size: Optional[int] = 0\n    ) -> List[List[float]]:\n        \"\"\"Call out to OpenAI's embedding endpoint for embedding search docs.\n        Args:\n            texts: The list of texts to embed.\n            chunk_size: The chunk size of embeddings. If None, will use the chunk size\n                specified by the class.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        # NOTE: to keep things simple, we assume the list may contain texts longer\n        #       than the maximum context and use length-safe embedding function.\n        engine = cast(str, self.deployment)\n        return self._get_len_safe_embeddings(texts, engine=engine)\n[docs]    async def aembed_documents(\n        self, texts: List[str], chunk_size: Optional[int] = 0\n    ) -> List[List[float]]:\n        \"\"\"Call out to OpenAI's embedding endpoint async for embedding search docs.\n        Args:\n            texts: The list of texts to embed.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "71c07b4045a3-14", "text": "Args:\n            texts: The list of texts to embed.\n            chunk_size: The chunk size of embeddings. If None, will use the chunk size\n                specified by the class.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        # NOTE: to keep things simple, we assume the list may contain texts longer\n        #       than the maximum context and use length-safe embedding function.\n        engine = cast(str, self.deployment)\n        return await self._aget_len_safe_embeddings(texts, engine=engine)\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to OpenAI's embedding endpoint for embedding query text.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embedding for the text.\n        \"\"\"\n        return self.embed_documents([text])[0]\n[docs]    async def aembed_query(self, text: str) -> List[float]:\n        \"\"\"Call out to OpenAI's embedding endpoint async for embedding query text.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embedding for the text.\n        \"\"\"\n        embeddings = await self.aembed_documents([text])\n        return embeddings[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html"}
{"id": "81ddc58c16a5-0", "text": "Source code for langchain.embeddings.fastembed\nfrom typing import Any, Dict, List, Literal, Optional\nimport numpy as np\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.embeddings import Embeddings\n[docs]class FastEmbedEmbeddings(BaseModel, Embeddings):\n    \"\"\"Qdrant FastEmbedding models.\n    FastEmbed is a lightweight, fast, Python library built for embedding generation.\n    See more documentation at:\n    * https://github.com/qdrant/fastembed/\n    * https://qdrant.github.io/fastembed/\n    To use this class, you must install the `fastembed` Python package.\n    `pip install fastembed`\n    Example:\n        from langchain.embeddings import FastEmbedEmbeddings\n        fastembed = FastEmbedEmbeddings()\n    \"\"\"\n    model_name: str = \"BAAI/bge-small-en-v1.5\"\n    \"\"\"Name of the FastEmbedding model to use\n    Defaults to \"BAAI/bge-small-en-v1.5\"\n    Find the list of supported models at\n    https://qdrant.github.io/fastembed/examples/Supported_Models/\n    \"\"\"\n    max_length: int = 512\n    \"\"\"The maximum number of tokens. Defaults to 512.\n    Unknown behavior for values > 512.\n    \"\"\"\n    cache_dir: Optional[str]\n    \"\"\"The path to the cache directory.\n    Defaults to `local_cache` in the parent directory\n    \"\"\"\n    threads: Optional[int]\n    \"\"\"The number of threads single onnxruntime session can use.\n    Defaults to None\n    \"\"\"\n    doc_embed_type: Literal[\"default\", \"passage\"] = \"default\"\n    \"\"\"Type of embedding to use for documents", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/fastembed.html"}
{"id": "81ddc58c16a5-1", "text": "\"\"\"Type of embedding to use for documents\n    \"default\": Uses FastEmbed's default embedding method\n    \"passage\": Prefixes the text with \"passage\" before embedding.\n    \"\"\"\n    _model: Any  # : :meta private:\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that FastEmbed has been installed.\"\"\"\n        try:\n            from fastembed.embedding import FlagEmbedding\n            model_name = values.get(\"model_name\")\n            max_length = values.get(\"max_length\")\n            cache_dir = values.get(\"cache_dir\")\n            threads = values.get(\"threads\")\n            values[\"_model\"] = FlagEmbedding(\n                model_name=model_name,\n                max_length=max_length,\n                cache_dir=cache_dir,\n                threads=threads,\n            )\n        except ImportError as ie:\n            raise ImportError(\n                \"Could not import 'fastembed' Python package. \"\n                \"Please install it with `pip install fastembed`.\"\n            ) from ie\n        return values\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Generate embeddings for documents using FastEmbed.\n        Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        embeddings: List[np.ndarray]\n        if self.doc_embed_type == \"passage\":\n            embeddings = self._model.passage_embed(texts)\n        else:\n            embeddings = self._model.embed(texts)\n        return [e.tolist() for e in embeddings]\n[docs]    def embed_query(self, text: str) -> List[float]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/fastembed.html"}
{"id": "81ddc58c16a5-2", "text": "[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Generate query embeddings using FastEmbed.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        query_embeddings: np.ndarray = next(self._model.query_embed(text))\n        return query_embeddings.tolist()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/fastembed.html"}
{"id": "f4a6324df779-0", "text": "Source code for langchain.embeddings.modelscope_hub\nfrom typing import Any, List, Optional\nfrom langchain.pydantic_v1 import BaseModel, Extra\nfrom langchain.schema.embeddings import Embeddings\n[docs]class ModelScopeEmbeddings(BaseModel, Embeddings):\n    \"\"\"ModelScopeHub embedding models.\n    To use, you should have the ``modelscope`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import ModelScopeEmbeddings\n            model_id = \"damo/nlp_corom_sentence-embedding_english-base\"\n            embed = ModelScopeEmbeddings(model_id=model_id, model_revision=\"v1.0.0\")\n    \"\"\"\n    embed: Any\n    model_id: str = \"damo/nlp_corom_sentence-embedding_english-base\"\n    \"\"\"Model name to use.\"\"\"\n    model_revision: Optional[str] = None\n    def __init__(self, **kwargs: Any):\n        \"\"\"Initialize the modelscope\"\"\"\n        super().__init__(**kwargs)\n        try:\n            from modelscope.pipelines import pipeline\n            from modelscope.utils.constant import Tasks\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import some python packages.\"\n                \"Please install it with `pip install modelscope`.\"\n            ) from e\n        self.embed = pipeline(\n            Tasks.sentence_embedding,\n            model=self.model_id,\n            model_revision=self.model_revision,\n        )\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Compute doc embeddings using a modelscope embedding model.\n        Args:\n            texts: The list of texts to embed.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html"}
{"id": "f4a6324df779-1", "text": "Args:\n            texts: The list of texts to embed.\n        Returns:\n            List of embeddings, one for each text.\n        \"\"\"\n        texts = list(map(lambda x: x.replace(\"\\n\", \" \"), texts))\n        inputs = {\"source_sentence\": texts}\n        embeddings = self.embed(input=inputs)[\"text_embedding\"]\n        return embeddings.tolist()\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Compute query embeddings using a modelscope embedding model.\n        Args:\n            text: The text to embed.\n        Returns:\n            Embeddings for the text.\n        \"\"\"\n        text = text.replace(\"\\n\", \" \")\n        inputs = {\"source_sentence\": [text]}\n        embedding = self.embed(input=inputs)[\"text_embedding\"][0]\n        return embedding.tolist()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html"}
{"id": "a267d1d5ff44-0", "text": "Source code for langchain.retrievers.web_research\nimport logging\nimport re\nfrom typing import List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.chains import LLMChain\nfrom langchain.chains.prompt_selector import ConditionalPromptSelector\nfrom langchain.document_loaders import AsyncHtmlLoader\nfrom langchain.document_transformers import Html2TextTransformer\nfrom langchain.llms import LlamaCpp\nfrom langchain.llms.base import BaseLLM\nfrom langchain.output_parsers.pydantic import PydanticOutputParser\nfrom langchain.prompts import BasePromptTemplate, PromptTemplate\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter, TextSplitter\nfrom langchain.utilities import GoogleSearchAPIWrapper\nlogger = logging.getLogger(__name__)\n[docs]class SearchQueries(BaseModel):\n    \"\"\"Search queries to research for the user's goal.\"\"\"\n    queries: List[str] = Field(\n        ..., description=\"List of search queries to look up on Google\"\n    )\nDEFAULT_LLAMA_SEARCH_PROMPT = PromptTemplate(\n    input_variables=[\"question\"],\n    template=\"\"\"<<SYS>> \\n You are an assistant tasked with improving Google search \\\nresults. \\n <</SYS>> \\n\\n [INST] Generate THREE Google search queries that \\\nare similar to this question. The output should be a numbered list of questions \\\nand each should have a question mark at the end: \\n\\n {question} [/INST]\"\"\",\n)\nDEFAULT_SEARCH_PROMPT = PromptTemplate(\n    input_variables=[\"question\"],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html"}
{"id": "a267d1d5ff44-1", "text": ")\nDEFAULT_SEARCH_PROMPT = PromptTemplate(\n    input_variables=[\"question\"],\n    template=\"\"\"You are an assistant tasked with improving Google search \\\nresults. Generate THREE Google search queries that are similar to \\\nthis question. The output should be a numbered list of questions and each \\\nshould have a question mark at the end: {question}\"\"\",\n)\n[docs]class LineList(BaseModel):\n    \"\"\"List of questions.\"\"\"\n    lines: List[str] = Field(description=\"Questions\")\n[docs]class QuestionListOutputParser(PydanticOutputParser):\n    \"\"\"Output parser for a list of numbered questions.\"\"\"\n    def __init__(self) -> None:\n        super().__init__(pydantic_object=LineList)\n[docs]    def parse(self, text: str) -> LineList:\n        lines = re.findall(r\"\\d+\\..*?(?:\\n|$)\", text)\n        return LineList(lines=lines)\n[docs]class WebResearchRetriever(BaseRetriever):\n    \"\"\"`Google Search API` retriever.\"\"\"\n    # Inputs\n    vectorstore: VectorStore = Field(\n        ..., description=\"Vector store for storing web pages\"\n    )\n    llm_chain: LLMChain\n    search: GoogleSearchAPIWrapper = Field(..., description=\"Google Search API Wrapper\")\n    num_search_results: int = Field(1, description=\"Number of pages per Google search\")\n    text_splitter: TextSplitter = Field(\n        RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=50),\n        description=\"Text splitter for splitting web pages into chunks\",\n    )\n    url_database: List[str] = Field(\n        default_factory=list, description=\"List of processed URLs\"\n    )\n[docs]    @classmethod\n    def from_llm(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html"}
{"id": "a267d1d5ff44-2", "text": ")\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        vectorstore: VectorStore,\n        llm: BaseLLM,\n        search: GoogleSearchAPIWrapper,\n        prompt: Optional[BasePromptTemplate] = None,\n        num_search_results: int = 1,\n        text_splitter: RecursiveCharacterTextSplitter = RecursiveCharacterTextSplitter(\n            chunk_size=1500, chunk_overlap=150\n        ),\n    ) -> \"WebResearchRetriever\":\n        \"\"\"Initialize from llm using default template.\n        Args:\n            vectorstore: Vector store for storing web pages\n            llm: llm for search question generation\n            search: GoogleSearchAPIWrapper\n            prompt: prompt to generating search questions\n            num_search_results: Number of pages per Google search\n            text_splitter: Text splitter for splitting web pages into chunks\n        Returns:\n            WebResearchRetriever\n        \"\"\"\n        if not prompt:\n            QUESTION_PROMPT_SELECTOR = ConditionalPromptSelector(\n                default_prompt=DEFAULT_SEARCH_PROMPT,\n                conditionals=[\n                    (lambda llm: isinstance(llm, LlamaCpp), DEFAULT_LLAMA_SEARCH_PROMPT)\n                ],\n            )\n            prompt = QUESTION_PROMPT_SELECTOR.get_prompt(llm)\n        # Use chat model prompt\n        llm_chain = LLMChain(\n            llm=llm,\n            prompt=prompt,\n            output_parser=QuestionListOutputParser(),\n        )\n        return cls(\n            vectorstore=vectorstore,\n            llm_chain=llm_chain,\n            search=search,\n            num_search_results=num_search_results,\n            text_splitter=text_splitter,\n        )\n[docs]    def clean_search_query(self, query: str) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html"}
{"id": "a267d1d5ff44-3", "text": "[docs]    def clean_search_query(self, query: str) -> str:\n        # Some search tools (e.g., Google) will\n        # fail to return results if query has a\n        # leading digit: 1. \"LangCh...\"\n        # Check if the first character is a digit\n        if query[0].isdigit():\n            # Find the position of the first quote\n            first_quote_pos = query.find('\"')\n            if first_quote_pos != -1:\n                # Extract the part of the string after the quote\n                query = query[first_quote_pos + 1 :]\n                # Remove the trailing quote if present\n                if query.endswith('\"'):\n                    query = query[:-1]\n        return query.strip()\n[docs]    def search_tool(self, query: str, num_search_results: int = 1) -> List[dict]:\n        \"\"\"Returns num_search_results pages per Google search.\"\"\"\n        query_clean = self.clean_search_query(query)\n        result = self.search.results(query_clean, num_search_results)\n        return result\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n    ) -> List[Document]:\n        \"\"\"Search Google for documents related to the query input.\n        Args:\n            query: user query\n        Returns:\n            Relevant documents from all various urls.\n        \"\"\"\n        # Get search questions\n        logger.info(\"Generating questions for Google Search ...\")\n        result = self.llm_chain({\"question\": query})\n        logger.info(f\"Questions for Google Search (raw): {result}\")\n        questions = getattr(result[\"text\"], \"lines\", [])\n        logger.info(f\"Questions for Google Search: {questions}\")\n        # Get urls\n        logger.info(\"Searching for relevant urls...\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html"}
{"id": "a267d1d5ff44-4", "text": "# Get urls\n        logger.info(\"Searching for relevant urls...\")\n        urls_to_look = []\n        for query in questions:\n            # Google search\n            search_results = self.search_tool(query, self.num_search_results)\n            logger.info(\"Searching for relevant urls...\")\n            logger.info(f\"Search results: {search_results}\")\n            for res in search_results:\n                if res.get(\"link\", None):\n                    urls_to_look.append(res[\"link\"])\n        # Relevant urls\n        urls = set(urls_to_look)\n        # Check for any new urls that we have not processed\n        new_urls = list(urls.difference(self.url_database))\n        logger.info(f\"New URLs to load: {new_urls}\")\n        # Load, split, and add new urls to vectorstore\n        if new_urls:\n            loader = AsyncHtmlLoader(new_urls, ignore_load_errors=True)\n            html2text = Html2TextTransformer()\n            logger.info(\"Indexing new urls...\")\n            docs = loader.load()\n            docs = list(html2text.transform_documents(docs))\n            docs = self.text_splitter.split_documents(docs)\n            self.vectorstore.add_documents(docs)\n            self.url_database.extend(new_urls)\n        # Search for relevant splits\n        # TODO: make this async\n        logger.info(\"Grabbing most relevant splits from urls...\")\n        docs = []\n        for query in questions:\n            docs.extend(self.vectorstore.similarity_search(query))\n        # Get unique docs\n        unique_documents_dict = {\n            (doc.page_content, tuple(sorted(doc.metadata.items()))): doc for doc in docs\n        }\n        unique_documents = list(unique_documents_dict.values())\n        return unique_documents\n    async def _aget_relevant_documents(\n        self,\n        query: str,\n        *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html"}
{"id": "a267d1d5ff44-5", "text": "self,\n        query: str,\n        *,\n        run_manager: AsyncCallbackManagerForRetrieverRun,\n    ) -> List[Document]:\n        raise NotImplementedError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html"}
{"id": "d0c14b2482d8-0", "text": "Source code for langchain.retrievers.metal\nfrom typing import Any, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import BaseRetriever, Document\n[docs]class MetalRetriever(BaseRetriever):\n    \"\"\"`Metal API` retriever.\"\"\"\n    client: Any\n    \"\"\"The Metal client to use.\"\"\"\n    params: Optional[dict] = None\n    \"\"\"The parameters to pass to the Metal client.\"\"\"\n    @root_validator(pre=True)\n    def validate_client(cls, values: dict) -> dict:\n        \"\"\"Validate that the client is of the correct type.\"\"\"\n        from metal_sdk.metal import Metal\n        if \"client\" in values:\n            client = values[\"client\"]\n            if not isinstance(client, Metal):\n                raise ValueError(\n                    \"Got unexpected client, should be of type metal_sdk.metal.Metal. \"\n                    f\"Instead, got {type(client)}\"\n                )\n        values[\"params\"] = values.get(\"params\", {})\n        return values\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        results = self.client.search({\"text\": query}, **self.params)\n        final_results = []\n        for r in results[\"data\"]:\n            metadata = {k: v for k, v in r.items() if k != \"text\"}\n            final_results.append(Document(page_content=r[\"text\"], metadata=metadata))\n        return final_results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/metal.html"}
{"id": "7822f1c2bd99-0", "text": "Source code for langchain.retrievers.azure_cognitive_search\nfrom __future__ import annotations\nimport json\nfrom typing import Dict, List, Optional\nimport aiohttp\nimport requests\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.utils import get_from_dict_or_env\n[docs]class AzureCognitiveSearchRetriever(BaseRetriever):\n    \"\"\"`Azure Cognitive Search` service retriever.\"\"\"\n    service_name: str = \"\"\n    \"\"\"Name of Azure Cognitive Search service\"\"\"\n    index_name: str = \"\"\n    \"\"\"Name of Index inside Azure Cognitive Search service\"\"\"\n    api_key: str = \"\"\n    \"\"\"API Key. Both Admin and Query keys work, but for reading data it's\n    recommended to use a Query key.\"\"\"\n    api_version: str = \"2020-06-30\"\n    \"\"\"API version\"\"\"\n    aiosession: Optional[aiohttp.ClientSession] = None\n    \"\"\"ClientSession, in case we want to reuse connection for better performance.\"\"\"\n    content_key: str = \"content\"\n    \"\"\"Key in a retrieved result to set as the Document page_content.\"\"\"\n    top_k: Optional[int] = None\n    \"\"\"Number of results to retrieve. Set to None to retrieve all results.\"\"\"\n    class Config:\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that service name, index name and api key exists in environment.\"\"\"\n        values[\"service_name\"] = get_from_dict_or_env(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html"}
{"id": "7822f1c2bd99-1", "text": "values[\"service_name\"] = get_from_dict_or_env(\n            values, \"service_name\", \"AZURE_COGNITIVE_SEARCH_SERVICE_NAME\"\n        )\n        values[\"index_name\"] = get_from_dict_or_env(\n            values, \"index_name\", \"AZURE_COGNITIVE_SEARCH_INDEX_NAME\"\n        )\n        values[\"api_key\"] = get_from_dict_or_env(\n            values, \"api_key\", \"AZURE_COGNITIVE_SEARCH_API_KEY\"\n        )\n        return values\n    def _build_search_url(self, query: str) -> str:\n        base_url = f\"https://{self.service_name}.search.windows.net/\"\n        endpoint_path = f\"indexes/{self.index_name}/docs?api-version={self.api_version}\"\n        top_param = f\"&$top={self.top_k}\" if self.top_k else \"\"\n        return base_url + endpoint_path + f\"&search={query}\" + top_param\n    @property\n    def _headers(self) -> Dict[str, str]:\n        return {\n            \"Content-Type\": \"application/json\",\n            \"api-key\": self.api_key,\n        }\n    def _search(self, query: str) -> List[dict]:\n        search_url = self._build_search_url(query)\n        response = requests.get(search_url, headers=self._headers)\n        if response.status_code != 200:\n            raise Exception(f\"Error in search request: {response}\")\n        return json.loads(response.text)[\"value\"]\n    async def _asearch(self, query: str) -> List[dict]:\n        search_url = self._build_search_url(query)\n        if not self.aiosession:\n            async with aiohttp.ClientSession() as session:\n                async with session.get(search_url, headers=self._headers) as response:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html"}
{"id": "7822f1c2bd99-2", "text": "async with session.get(search_url, headers=self._headers) as response:\n                    response_json = await response.json()\n        else:\n            async with self.aiosession.get(\n                search_url, headers=self._headers\n            ) as response:\n                response_json = await response.json()\n        return response_json[\"value\"]\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        search_results = self._search(query)\n        return [\n            Document(page_content=result.pop(self.content_key), metadata=result)\n            for result in search_results\n        ]\n    async def _aget_relevant_documents(\n        self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        search_results = await self._asearch(query)\n        return [\n            Document(page_content=result.pop(self.content_key), metadata=result)\n            for result in search_results\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html"}
{"id": "396e28bfca69-0", "text": "Source code for langchain.retrievers.chaindesk\nfrom typing import Any, List, Optional\nimport aiohttp\nimport requests\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.schema import BaseRetriever, Document\n[docs]class ChaindeskRetriever(BaseRetriever):\n    \"\"\"`Chaindesk API` retriever.\"\"\"\n    datastore_url: str\n    top_k: Optional[int]\n    api_key: Optional[str]\n    def __init__(\n        self,\n        datastore_url: str,\n        top_k: Optional[int] = None,\n        api_key: Optional[str] = None,\n    ):\n        self.datastore_url = datastore_url\n        self.api_key = api_key\n        self.top_k = top_k\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n        **kwargs: Any,\n    ) -> List[Document]:\n        response = requests.post(\n            self.datastore_url,\n            json={\n                \"query\": query,\n                **({\"topK\": self.top_k} if self.top_k is not None else {}),\n            },\n            headers={\n                \"Content-Type\": \"application/json\",\n                **(\n                    {\"Authorization\": f\"Bearer {self.api_key}\"}\n                    if self.api_key is not None\n                    else {}\n                ),\n            },\n        )\n        data = response.json()\n        return [\n            Document(\n                page_content=r[\"text\"],\n                metadata={\"source\": r[\"source\"], \"score\": r[\"score\"]},\n            )\n            for r in data[\"results\"]\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/chaindesk.html"}
{"id": "396e28bfca69-1", "text": ")\n            for r in data[\"results\"]\n        ]\n    async def _aget_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: AsyncCallbackManagerForRetrieverRun,\n        **kwargs: Any,\n    ) -> List[Document]:\n        async with aiohttp.ClientSession() as session:\n            async with session.request(\n                \"POST\",\n                self.datastore_url,\n                json={\n                    \"query\": query,\n                    **({\"topK\": self.top_k} if self.top_k is not None else {}),\n                },\n                headers={\n                    \"Content-Type\": \"application/json\",\n                    **(\n                        {\"Authorization\": f\"Bearer {self.api_key}\"}\n                        if self.api_key is not None\n                        else {}\n                    ),\n                },\n            ) as response:\n                data = await response.json()\n        return [\n            Document(\n                page_content=r[\"text\"],\n                metadata={\"source\": r[\"source\"], \"score\": r[\"score\"]},\n            )\n            for r in data[\"results\"]\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/chaindesk.html"}
{"id": "c29c869a2afd-0", "text": "Source code for langchain.retrievers.tavily_search_api\nimport os\nfrom enum import Enum\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.schema import Document\nfrom langchain.schema.retriever import BaseRetriever\n[docs]class SearchDepth(Enum):\n    \"\"\"Search depth as enumerator.\"\"\"\n    BASIC = \"basic\"\n    ADVANCED = \"advanced\"\n[docs]class TavilySearchAPIRetriever(BaseRetriever):\n    \"\"\"Tavily Search API retriever.\"\"\"\n    k: int = 10\n    include_generated_answer: bool = False\n    include_raw_content: bool = False\n    include_images: bool = False\n    search_depth: SearchDepth = SearchDepth.BASIC\n    include_domains: Optional[List[str]] = None\n    exclude_domains: Optional[List[str]] = None\n    kwargs: Optional[Dict[str, Any]] = {}\n    api_key: Optional[str] = None\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        try:\n            from tavily import Client\n        except ImportError:\n            raise ImportError(\n                \"Tavily python package not found. \"\n                \"Please install it with `pip install tavily-python`.\"\n            )\n        tavily = Client(api_key=self.api_key or os.environ[\"TAVILY_API_KEY\"])\n        max_results = self.k if not self.include_generated_answer else self.k - 1\n        response = tavily.search(\n            query=query,\n            max_results=max_results,\n            search_depth=self.search_depth.value,\n            include_answer=self.include_generated_answer,\n            include_domains=self.include_domains,\n            exclude_domains=self.exclude_domains,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/tavily_search_api.html"}
{"id": "c29c869a2afd-1", "text": "include_domains=self.include_domains,\n            exclude_domains=self.exclude_domains,\n            include_raw_content=self.include_raw_content,\n            include_images=self.include_images,\n            **self.kwargs,\n        )\n        docs = [\n            Document(\n                page_content=result.get(\"content\", \"\")\n                if not self.include_raw_content\n                else result.get(\"raw_content\", \"\"),\n                metadata={\n                    \"title\": result.get(\"title\", \"\"),\n                    \"source\": result.get(\"url\", \"\"),\n                    **{\n                        k: v\n                        for k, v in result.items()\n                        if k not in (\"content\", \"title\", \"url\", \"raw_content\")\n                    },\n                    \"images\": response.get(\"images\"),\n                },\n            )\n            for result in response.get(\"results\")\n        ]\n        if self.include_generated_answer:\n            docs = [\n                Document(\n                    page_content=response.get(\"answer\", \"\"),\n                    metadata={\n                        \"title\": \"Suggested Answer\",\n                        \"source\": \"https://tavily.com/\",\n                    },\n                ),\n                *docs,\n            ]\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/tavily_search_api.html"}
{"id": "89893d4a26fb-0", "text": "Source code for langchain.retrievers.elastic_search_bm25\n\"\"\"Wrapper around Elasticsearch vector database.\"\"\"\nfrom __future__ import annotations\nimport uuid\nfrom typing import Any, Iterable, List\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.docstore.document import Document\nfrom langchain.schema import BaseRetriever\n[docs]class ElasticSearchBM25Retriever(BaseRetriever):\n    \"\"\"`Elasticsearch` retriever that uses `BM25`.\n    To connect to an Elasticsearch instance that requires login credentials,\n    including Elastic Cloud, use the Elasticsearch URL format\n    https://username:password@es_host:9243. For example, to connect to Elastic\n    Cloud, create the Elasticsearch URL with the required authentication details and\n    pass it to the ElasticVectorSearch constructor as the named parameter\n    elasticsearch_url.\n    You can obtain your Elastic Cloud URL and login credentials by logging in to the\n    Elastic Cloud console at https://cloud.elastic.co, selecting your deployment, and\n    navigating to the \"Deployments\" page.\n    To obtain your Elastic Cloud password for the default \"elastic\" user:\n    1. Log in to the Elastic Cloud console at https://cloud.elastic.co\n    2. Go to \"Security\" > \"Users\"\n    3. Locate the \"elastic\" user and click \"Edit\"\n    4. Click \"Reset password\"\n    5. Follow the prompts to reset the password\n    The format for Elastic Cloud URLs is\n    https://username:password@cluster_id.region_id.gcp.cloud.es.io:9243.\n    \"\"\"\n    client: Any\n    \"\"\"Elasticsearch client.\"\"\"\n    index_name: str\n    \"\"\"Name of the index to use in Elasticsearch.\"\"\"\n[docs]    @classmethod\n    def create(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html"}
{"id": "89893d4a26fb-1", "text": "[docs]    @classmethod\n    def create(\n        cls, elasticsearch_url: str, index_name: str, k1: float = 2.0, b: float = 0.75\n    ) -> ElasticSearchBM25Retriever:\n        \"\"\"\n        Create a ElasticSearchBM25Retriever from a list of texts.\n        Args:\n            elasticsearch_url: URL of the Elasticsearch instance to connect to.\n            index_name: Name of the index to use in Elasticsearch.\n            k1: BM25 parameter k1.\n            b: BM25 parameter b.\n        Returns:\n        \"\"\"\n        from elasticsearch import Elasticsearch\n        # Create an Elasticsearch client instance\n        es = Elasticsearch(elasticsearch_url)\n        # Define the index settings and mappings\n        settings = {\n            \"analysis\": {\"analyzer\": {\"default\": {\"type\": \"standard\"}}},\n            \"similarity\": {\n                \"custom_bm25\": {\n                    \"type\": \"BM25\",\n                    \"k1\": k1,\n                    \"b\": b,\n                }\n            },\n        }\n        mappings = {\n            \"properties\": {\n                \"content\": {\n                    \"type\": \"text\",\n                    \"similarity\": \"custom_bm25\",  # Use the custom BM25 similarity\n                }\n            }\n        }\n        # Create the index with the specified settings and mappings\n        es.indices.create(index=index_name, mappings=mappings, settings=settings)\n        return cls(client=es, index_name=index_name)\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        refresh_indices: bool = True,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the retriever.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html"}
{"id": "89893d4a26fb-2", "text": "\"\"\"Run more texts through the embeddings and add to the retriever.\n        Args:\n            texts: Iterable of strings to add to the retriever.\n            refresh_indices: bool to refresh ElasticSearch indices\n        Returns:\n            List of ids from adding the texts into the retriever.\n        \"\"\"\n        try:\n            from elasticsearch.helpers import bulk\n        except ImportError:\n            raise ValueError(\n                \"Could not import elasticsearch python package. \"\n                \"Please install it with `pip install elasticsearch`.\"\n            )\n        requests = []\n        ids = []\n        for i, text in enumerate(texts):\n            _id = str(uuid.uuid4())\n            request = {\n                \"_op_type\": \"index\",\n                \"_index\": self.index_name,\n                \"content\": text,\n                \"_id\": _id,\n            }\n            ids.append(_id)\n            requests.append(request)\n        bulk(self.client, requests)\n        if refresh_indices:\n            self.client.indices.refresh(index=self.index_name)\n        return ids\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        query_dict = {\"query\": {\"match\": {\"content\": query}}}\n        res = self.client.search(index=self.index_name, body=query_dict)\n        docs = []\n        for r in res[\"hits\"][\"hits\"]:\n            docs.append(Document(page_content=r[\"_source\"][\"content\"]))\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html"}
{"id": "7fb52dd5a4e8-0", "text": "Source code for langchain.retrievers.remote_retriever\nfrom typing import List, Optional\nimport aiohttp\nimport requests\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.schema import BaseRetriever, Document\n[docs]class RemoteLangChainRetriever(BaseRetriever):\n    \"\"\"`LangChain API` retriever.\"\"\"\n    url: str\n    \"\"\"URL of the remote LangChain API.\"\"\"\n    headers: Optional[dict] = None\n    \"\"\"Headers to use for the request.\"\"\"\n    input_key: str = \"message\"\n    \"\"\"Key to use for the input in the request.\"\"\"\n    response_key: str = \"response\"\n    \"\"\"Key to use for the response in the request.\"\"\"\n    page_content_key: str = \"page_content\"\n    \"\"\"Key to use for the page content in the response.\"\"\"\n    metadata_key: str = \"metadata\"\n    \"\"\"Key to use for the metadata in the response.\"\"\"\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        response = requests.post(\n            self.url, json={self.input_key: query}, headers=self.headers\n        )\n        result = response.json()\n        return [\n            Document(\n                page_content=r[self.page_content_key], metadata=r[self.metadata_key]\n            )\n            for r in result[self.response_key]\n        ]\n    async def _aget_relevant_documents(\n        self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        async with aiohttp.ClientSession() as session:\n            async with session.request(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html"}
{"id": "7fb52dd5a4e8-1", "text": "async with aiohttp.ClientSession() as session:\n            async with session.request(\n                \"POST\", self.url, headers=self.headers, json={self.input_key: query}\n            ) as response:\n                result = await response.json()\n        return [\n            Document(\n                page_content=r[self.page_content_key], metadata=r[self.metadata_key]\n            )\n            for r in result[self.response_key]\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html"}
{"id": "d9852de95864-0", "text": "Source code for langchain.retrievers.svm\nfrom __future__ import annotations\nimport concurrent.futures\nfrom typing import Any, Iterable, List, Optional\nimport numpy as np\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.schema.embeddings import Embeddings\n[docs]def create_index(contexts: List[str], embeddings: Embeddings) -> np.ndarray:\n    \"\"\"\n    Create an index of embeddings for a list of contexts.\n    Args:\n        contexts: List of contexts to embed.\n        embeddings: Embeddings model to use.\n    Returns:\n        Index of embeddings.\n    \"\"\"\n    with concurrent.futures.ThreadPoolExecutor() as executor:\n        return np.array(list(executor.map(embeddings.embed_query, contexts)))\n[docs]class SVMRetriever(BaseRetriever):\n    \"\"\"`SVM` retriever.\n    Largely based on\n    https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb\n    \"\"\"\n    embeddings: Embeddings\n    \"\"\"Embeddings model to use.\"\"\"\n    index: Any\n    \"\"\"Index of embeddings.\"\"\"\n    texts: List[str]\n    \"\"\"List of texts to index.\"\"\"\n    metadatas: Optional[List[dict]] = None\n    \"\"\"List of metadatas corresponding with each text.\"\"\"\n    k: int = 4\n    \"\"\"Number of results to return.\"\"\"\n    relevancy_threshold: Optional[float] = None\n    \"\"\"Threshold for relevancy.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embeddings: Embeddings,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html"}
{"id": "d9852de95864-1", "text": "cls,\n        texts: List[str],\n        embeddings: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> SVMRetriever:\n        index = create_index(texts, embeddings)\n        return cls(\n            embeddings=embeddings,\n            index=index,\n            texts=texts,\n            metadatas=metadatas,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_documents(\n        cls,\n        documents: Iterable[Document],\n        embeddings: Embeddings,\n        **kwargs: Any,\n    ) -> SVMRetriever:\n        texts, metadatas = zip(*((d.page_content, d.metadata) for d in documents))\n        return cls.from_texts(\n            texts=texts, embeddings=embeddings, metadatas=metadatas, **kwargs\n        )\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        try:\n            from sklearn import svm\n        except ImportError:\n            raise ImportError(\n                \"Could not import scikit-learn, please install with `pip install \"\n                \"scikit-learn`.\"\n            )\n        query_embeds = np.array(self.embeddings.embed_query(query))\n        x = np.concatenate([query_embeds[None, ...], self.index])\n        y = np.zeros(x.shape[0])\n        y[0] = 1\n        clf = svm.LinearSVC(\n            class_weight=\"balanced\", verbose=False, max_iter=10000, tol=1e-6, C=0.1\n        )\n        clf.fit(x, y)\n        similarities = clf.decision_function(x)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html"}
{"id": "d9852de95864-2", "text": "clf.fit(x, y)\n        similarities = clf.decision_function(x)\n        sorted_ix = np.argsort(-similarities)\n        # svm.LinearSVC in scikit-learn is non-deterministic.\n        # if a text is the same as a query, there is no guarantee\n        # the query will be in the first index.\n        # this performs a simple swap, this works because anything\n        # left of the 0 should be equivalent.\n        zero_index = np.where(sorted_ix == 0)[0][0]\n        if zero_index != 0:\n            sorted_ix[0], sorted_ix[zero_index] = sorted_ix[zero_index], sorted_ix[0]\n        denominator = np.max(similarities) - np.min(similarities) + 1e-6\n        normalized_similarities = (similarities - np.min(similarities)) / denominator\n        top_k_results = []\n        for row in sorted_ix[1 : self.k + 1]:\n            if (\n                self.relevancy_threshold is None\n                or normalized_similarities[row] >= self.relevancy_threshold\n            ):\n                metadata = self.metadatas[row - 1] if self.metadatas else {}\n                doc = Document(page_content=self.texts[row - 1], metadata=metadata)\n                top_k_results.append(doc)\n        return top_k_results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html"}
{"id": "af07c67c9ead-0", "text": "Source code for langchain.retrievers.zep\nfrom __future__ import annotations\nfrom enum import Enum\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import BaseRetriever, Document\nif TYPE_CHECKING:\n    from zep_python.memory import MemorySearchResult\n[docs]class SearchScope(str, Enum):\n    \"\"\"Which documents to search. Messages or Summaries?\"\"\"\n    messages = \"messages\"\n    \"\"\"Search chat history messages.\"\"\"\n    summary = \"summary\"\n    \"\"\"Search chat history summaries.\"\"\"\n[docs]class SearchType(str, Enum):\n    \"\"\"Enumerator of the types of search to perform.\"\"\"\n    similarity = \"similarity\"\n    \"\"\"Similarity search.\"\"\"\n    mmr = \"mmr\"\n    \"\"\"Maximal Marginal Relevance reranking of similarity search.\"\"\"\n[docs]class ZepRetriever(BaseRetriever):\n    \"\"\"`Zep` MemoryStore Retriever.\n    Search your user's long-term chat history with Zep.\n    Zep offers both simple semantic search and Maximal Marginal Relevance (MMR)\n    reranking of search results.\n    Note: You will need to provide the user's `session_id` to use this retriever.\n    Args:\n        url: URL of your Zep server (required)\n        api_key: Your Zep API key (optional)\n        session_id: Identifies your user or a user's session (required)\n        top_k: Number of documents to return (default: 3, optional)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html"}
{"id": "af07c67c9ead-1", "text": "top_k: Number of documents to return (default: 3, optional)\n        search_type: Type of search to perform (similarity / mmr) (default: similarity,\n                                                                    optional)\n        mmr_lambda: Lambda value for MMR search. Defaults to 0.5 (optional)\n    Zep - Fast, scalable building blocks for LLM Apps\n    =========\n    Zep is an open source platform for productionizing LLM apps. Go from a prototype\n    built in LangChain or LlamaIndex, or a custom app, to production in minutes without\n    rewriting code.\n    For server installation instructions, see:\n    https://docs.getzep.com/deployment/quickstart/\n    \"\"\"\n    zep_client: Optional[Any] = None\n    \"\"\"Zep client.\"\"\"\n    url: str\n    \"\"\"URL of your Zep server.\"\"\"\n    api_key: Optional[str] = None\n    \"\"\"Your Zep API key.\"\"\"\n    session_id: str\n    \"\"\"Zep session ID.\"\"\"\n    top_k: Optional[int]\n    \"\"\"Number of items to return.\"\"\"\n    search_scope: SearchScope = SearchScope.messages\n    \"\"\"Which documents to search. Messages or Summaries?\"\"\"\n    search_type: SearchType = SearchType.similarity\n    \"\"\"Type of search to perform (similarity / mmr)\"\"\"\n    mmr_lambda: Optional[float] = None\n    \"\"\"Lambda value for MMR search.\"\"\"\n    @root_validator(pre=True)\n    def create_client(cls, values: dict) -> dict:\n        try:\n            from zep_python import ZepClient\n        except ImportError:\n            raise ImportError(\n                \"Could not import zep-python package. \"\n                \"Please install it with `pip install zep-python`.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html"}
{"id": "af07c67c9ead-2", "text": "\"Please install it with `pip install zep-python`.\"\n            )\n        values[\"zep_client\"] = values.get(\n            \"zep_client\",\n            ZepClient(base_url=values[\"url\"], api_key=values.get(\"api_key\")),\n        )\n        return values\n    def _messages_search_result_to_doc(\n        self, results: List[MemorySearchResult]\n    ) -> List[Document]:\n        return [\n            Document(\n                page_content=r.message.pop(\"content\"),\n                metadata={\"score\": r.dist, **r.message},\n            )\n            for r in results\n            if r.message\n        ]\n    def _summary_search_result_to_doc(\n        self, results: List[MemorySearchResult]\n    ) -> List[Document]:\n        return [\n            Document(\n                page_content=r.summary.content,\n                metadata={\n                    \"score\": r.dist,\n                    \"uuid\": r.summary.uuid,\n                    \"created_at\": r.summary.created_at,\n                    \"token_count\": r.summary.token_count,\n                },\n            )\n            for r in results\n            if r.summary\n        ]\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n        metadata: Optional[Dict[str, Any]] = None,\n    ) -> List[Document]:\n        from zep_python.memory import MemorySearchPayload\n        if not self.zep_client:\n            raise RuntimeError(\"Zep client not initialized.\")\n        payload = MemorySearchPayload(\n            text=query,\n            metadata=metadata,\n            search_scope=self.search_scope,\n            search_type=self.search_type,\n            mmr_lambda=self.mmr_lambda,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html"}
{"id": "af07c67c9ead-3", "text": "mmr_lambda=self.mmr_lambda,\n        )\n        results: List[MemorySearchResult] = self.zep_client.memory.search_memory(\n            self.session_id, payload, limit=self.top_k\n        )\n        if self.search_scope == SearchScope.summary:\n            return self._summary_search_result_to_doc(results)\n        return self._messages_search_result_to_doc(results)\n    async def _aget_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: AsyncCallbackManagerForRetrieverRun,\n        metadata: Optional[Dict[str, Any]] = None,\n    ) -> List[Document]:\n        from zep_python.memory import MemorySearchPayload\n        if not self.zep_client:\n            raise RuntimeError(\"Zep client not initialized.\")\n        payload = MemorySearchPayload(\n            text=query,\n            metadata=metadata,\n            search_scope=self.search_scope,\n            search_type=self.search_type,\n            mmr_lambda=self.mmr_lambda,\n        )\n        results: List[MemorySearchResult] = await self.zep_client.memory.asearch_memory(\n            self.session_id, payload, limit=self.top_k\n        )\n        if self.search_scope == SearchScope.summary:\n            return self._summary_search_result_to_doc(results)\n        return self._messages_search_result_to_doc(results)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html"}
{"id": "d4cbc66f961c-0", "text": "Source code for langchain.retrievers.kay\nfrom __future__ import annotations\nfrom typing import Any, List\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.schema import BaseRetriever, Document\n[docs]class KayAiRetriever(BaseRetriever):\n    \"\"\"\n    Retriever for Kay.ai datasets.\n    To work properly, expects you to have KAY_API_KEY env variable set.\n    You can get one for free at https://kay.ai/.\n    \"\"\"\n    client: Any\n    num_contexts: int\n[docs]    @classmethod\n    def create(\n        cls,\n        dataset_id: str,\n        data_types: List[str],\n        num_contexts: int = 6,\n    ) -> KayAiRetriever:\n        \"\"\"\n        Create a KayRetriever given a Kay dataset id and a list of datasources.\n        Args:\n            dataset_id: A dataset id category in Kay, like \"company\"\n            data_types: A list of datasources present within a dataset. For\n                \"company\" the corresponding datasources could be\n                [\"10-K\", \"10-Q\", \"8-K\", \"PressRelease\"].\n            num_contexts: The number of documents to retrieve on each query.\n                Defaults to 6.\n        \"\"\"\n        try:\n            from kay.rag.retrievers import KayRetriever\n        except ImportError:\n            raise ImportError(\n                \"Could not import kay python package. Please install it with \"\n                \"`pip install kay`.\",\n            )\n        client = KayRetriever(dataset_id, data_types)\n        return cls(client=client, num_contexts=num_contexts)\n    def _get_relevant_documents(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/kay.html"}
{"id": "d4cbc66f961c-1", "text": "def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        ctxs = self.client.query(query=query, num_context=self.num_contexts)\n        docs = []\n        for ctx in ctxs:\n            page_content = ctx.pop(\"chunk_embed_text\", None)\n            if page_content is None:\n                continue\n            docs.append(Document(page_content=page_content, metadata={**ctx}))\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/kay.html"}
{"id": "dc63a3d96191-0", "text": "Source code for langchain.retrievers.zilliz\nimport warnings\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.vectorstores.zilliz import Zilliz\n# TODO: Update to ZillizClient + Hybrid Search when available\n[docs]class ZillizRetriever(BaseRetriever):\n    \"\"\"`Zilliz API` retriever.\"\"\"\n    embedding_function: Embeddings\n    \"\"\"The underlying embedding function from which documents will be retrieved.\"\"\"\n    collection_name: str = \"LangChainCollection\"\n    \"\"\"The name of the collection in Zilliz.\"\"\"\n    connection_args: Optional[Dict[str, Any]] = None\n    \"\"\"The connection arguments for the Zilliz client.\"\"\"\n    consistency_level: str = \"Session\"\n    \"\"\"The consistency level for the Zilliz client.\"\"\"\n    search_params: Optional[dict] = None\n    \"\"\"The search parameters for the Zilliz client.\"\"\"\n    store: Zilliz\n    \"\"\"The underlying Zilliz store.\"\"\"\n    retriever: BaseRetriever\n    \"\"\"The underlying retriever.\"\"\"\n    @root_validator(pre=True)\n    def create_client(cls, values: dict) -> dict:\n        values[\"store\"] = Zilliz(\n            values[\"embedding_function\"],\n            values[\"collection_name\"],\n            values[\"connection_args\"],\n            values[\"consistency_level\"],\n        )\n        values[\"retriever\"] = values[\"store\"].as_retriever(\n            search_kwargs={\"param\": values[\"search_params\"]}\n        )\n        return values\n[docs]    def add_texts(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/zilliz.html"}
{"id": "dc63a3d96191-1", "text": ")\n        return values\n[docs]    def add_texts(\n        self, texts: List[str], metadatas: Optional[List[dict]] = None\n    ) -> None:\n        \"\"\"Add text to the Zilliz store\n        Args:\n            texts (List[str]): The text\n            metadatas (List[dict]): Metadata dicts, must line up with existing store\n        \"\"\"\n        self.store.add_texts(texts, metadatas)\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n        **kwargs: Any,\n    ) -> List[Document]:\n        return self.retriever.get_relevant_documents(\n            query, run_manager=run_manager.get_child(), **kwargs\n        )\n[docs]def ZillizRetreiver(*args: Any, **kwargs: Any) -> ZillizRetriever:\n    \"\"\"Deprecated ZillizRetreiver.\n    Please use ZillizRetriever ('i' before 'e') instead.\n    Args:\n        *args:\n        **kwargs:\n    Returns:\n        ZillizRetriever\n    \"\"\"\n    warnings.warn(\n        \"ZillizRetreiver will be deprecated in the future. \"\n        \"Please use ZillizRetriever ('i' before 'e') instead.\",\n        DeprecationWarning,\n    )\n    return ZillizRetriever(*args, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/zilliz.html"}
{"id": "ab57e9ad404c-0", "text": "Source code for langchain.retrievers.contextual_compression\nfrom typing import Any, List\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.retrievers.document_compressors.base import (\n    BaseDocumentCompressor,\n)\nfrom langchain.schema import BaseRetriever, Document\n[docs]class ContextualCompressionRetriever(BaseRetriever):\n    \"\"\"Retriever that wraps a base retriever and compresses the results.\"\"\"\n    base_compressor: BaseDocumentCompressor\n    \"\"\"Compressor for compressing retrieved documents.\"\"\"\n    base_retriever: BaseRetriever\n    \"\"\"Base Retriever to use for getting relevant documents.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Get documents relevant for a query.\n        Args:\n            query: string to find relevant documents for\n        Returns:\n            Sequence of relevant documents\n        \"\"\"\n        docs = self.base_retriever.get_relevant_documents(\n            query, callbacks=run_manager.get_child(), **kwargs\n        )\n        if docs:\n            compressed_docs = self.base_compressor.compress_documents(\n                docs, query, callbacks=run_manager.get_child()\n            )\n            return list(compressed_docs)\n        else:\n            return []\n    async def _aget_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: AsyncCallbackManagerForRetrieverRun,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html"}
{"id": "ab57e9ad404c-1", "text": "run_manager: AsyncCallbackManagerForRetrieverRun,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Get documents relevant for a query.\n        Args:\n            query: string to find relevant documents for\n        Returns:\n            List of relevant documents\n        \"\"\"\n        docs = await self.base_retriever.aget_relevant_documents(\n            query, callbacks=run_manager.get_child(), **kwargs\n        )\n        if docs:\n            compressed_docs = await self.base_compressor.acompress_documents(\n                docs, query, callbacks=run_manager.get_child()\n            )\n            return list(compressed_docs)\n        else:\n            return []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html"}
{"id": "26c624d131a2-0", "text": "Source code for langchain.retrievers.knn\n\"\"\"KNN Retriever.\nLargely based on\nhttps://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb\"\"\"\nfrom __future__ import annotations\nimport concurrent.futures\nfrom typing import Any, List, Optional\nimport numpy as np\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.schema.embeddings import Embeddings\n[docs]def create_index(contexts: List[str], embeddings: Embeddings) -> np.ndarray:\n    \"\"\"\n    Create an index of embeddings for a list of contexts.\n    Args:\n        contexts: List of contexts to embed.\n        embeddings: Embeddings model to use.\n    Returns:\n        Index of embeddings.\n    \"\"\"\n    with concurrent.futures.ThreadPoolExecutor() as executor:\n        return np.array(list(executor.map(embeddings.embed_query, contexts)))\n[docs]class KNNRetriever(BaseRetriever):\n    \"\"\"`KNN` retriever.\"\"\"\n    embeddings: Embeddings\n    \"\"\"Embeddings model to use.\"\"\"\n    index: Any\n    \"\"\"Index of embeddings.\"\"\"\n    texts: List[str]\n    \"\"\"List of texts to index.\"\"\"\n    k: int = 4\n    \"\"\"Number of results to return.\"\"\"\n    relevancy_threshold: Optional[float] = None\n    \"\"\"Threshold for relevancy.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    @classmethod\n    def from_texts(\n        cls, texts: List[str], embeddings: Embeddings, **kwargs: Any\n    ) -> KNNRetriever:\n        index = create_index(texts, embeddings)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html"}
{"id": "26c624d131a2-1", "text": "index = create_index(texts, embeddings)\n        return cls(embeddings=embeddings, index=index, texts=texts, **kwargs)\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        query_embeds = np.array(self.embeddings.embed_query(query))\n        # calc L2 norm\n        index_embeds = self.index / np.sqrt((self.index**2).sum(1, keepdims=True))\n        query_embeds = query_embeds / np.sqrt((query_embeds**2).sum())\n        similarities = index_embeds.dot(query_embeds)\n        sorted_ix = np.argsort(-similarities)\n        denominator = np.max(similarities) - np.min(similarities) + 1e-6\n        normalized_similarities = (similarities - np.min(similarities)) / denominator\n        top_k_results = [\n            Document(page_content=self.texts[row])\n            for row in sorted_ix[0 : self.k]\n            if (\n                self.relevancy_threshold is None\n                or normalized_similarities[row] >= self.relevancy_threshold\n            )\n        ]\n        return top_k_results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html"}
{"id": "6287afc97d46-0", "text": "Source code for langchain.retrievers.cohere_rag_retriever\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Any, Dict, List\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BaseRetriever, Document, HumanMessage\nif TYPE_CHECKING:\n    from langchain.schema.messages import BaseMessage\ndef _get_docs(response: Any) -> List[Document]:\n    docs = [\n        Document(page_content=doc[\"snippet\"], metadata=doc)\n        for doc in response.generation_info[\"documents\"]\n    ]\n    docs.append(\n        Document(\n            page_content=response.message.content,\n            metadata={\n                \"type\": \"model_response\",\n                \"citations\": response.generation_info[\"citations\"],\n                \"search_results\": response.generation_info[\"search_results\"],\n                \"search_queries\": response.generation_info[\"search_queries\"],\n                \"token_count\": response.generation_info[\"token_count\"],\n            },\n        )\n    )\n    return docs\n[docs]class CohereRagRetriever(BaseRetriever):\n    \"\"\"Cohere Chat API with RAG.\"\"\"\n    connectors: List[Dict] = Field(default_factory=lambda: [{\"id\": \"web-search\"}])\n    \"\"\"\n    When specified, the model's reply will be enriched with information found by\n    querying each of the connectors (RAG). These will be returned as langchain\n    documents.\n    Currently only accepts {\"id\": \"web-search\"}.\n    \"\"\"\n    llm: BaseChatModel\n    \"\"\"Cohere ChatModel to use.\"\"\"\n    class Config:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/cohere_rag_retriever.html"}
{"id": "6287afc97d46-1", "text": "\"\"\"Cohere ChatModel to use.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n        \"\"\"Allow arbitrary types.\"\"\"\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any\n    ) -> List[Document]:\n        messages: List[List[BaseMessage]] = [[HumanMessage(content=query)]]\n        res = self.llm.generate(\n            messages,\n            connectors=self.connectors,\n            callbacks=run_manager.get_child(),\n            **kwargs,\n        ).generations[0][0]\n        return _get_docs(res)\n    async def _aget_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: AsyncCallbackManagerForRetrieverRun,\n        **kwargs: Any,\n    ) -> List[Document]:\n        messages: List[List[BaseMessage]] = [[HumanMessage(content=query)]]\n        res = (\n            await self.llm.agenerate(\n                messages,\n                connectors=self.connectors,\n                callbacks=run_manager.get_child(),\n                **kwargs,\n            )\n        ).generations[0][0]\n        return _get_docs(res)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/cohere_rag_retriever.html"}
{"id": "e2732978521a-0", "text": "Source code for langchain.retrievers.kendra\nimport re\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Union\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator, validator\nfrom langchain.schema import BaseRetriever\n[docs]def clean_excerpt(excerpt: str) -> str:\n    \"\"\"Clean an excerpt from Kendra.\n    Args:\n        excerpt: The excerpt to clean.\n    Returns:\n        The cleaned excerpt.\n    \"\"\"\n    if not excerpt:\n        return excerpt\n    res = re.sub(r\"\\s+\", \" \", excerpt).replace(\"...\", \"\")\n    return res\n[docs]def combined_text(item: \"ResultItem\") -> str:\n    \"\"\"Combine a ResultItem title and excerpt into a single string.\n    Args:\n        item: the ResultItem of a Kendra search.\n    Returns:\n        A combined text of the title and excerpt of the given item.\n    \"\"\"\n    text = \"\"\n    title = item.get_title()\n    if title:\n        text += f\"Document Title: {title}\\n\"\n    excerpt = clean_excerpt(item.get_excerpt())\n    if excerpt:\n        text += f\"Document Excerpt: \\n{excerpt}\\n\"\n    return text\nDocumentAttributeValueType = Union[str, int, List[str], None]\n\"\"\"Possible types of a DocumentAttributeValue.\nDates are also represented as str.\n\"\"\"\n# Unexpected keyword argument \"extra\" for \"__init_subclass__\" of \"object\"\n[docs]class Highlight(BaseModel, extra=Extra.allow):  # type: ignore[call-arg]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html"}
{"id": "e2732978521a-1", "text": "\"\"\"Information that highlights the keywords in the excerpt.\"\"\"\n    BeginOffset: int\n    \"\"\"The zero-based location in the excerpt where the highlight starts.\"\"\"\n    EndOffset: int\n    \"\"\"The zero-based location in the excerpt where the highlight ends.\"\"\"\n    TopAnswer: Optional[bool]\n    \"\"\"Indicates whether the result is the best one.\"\"\"\n    Type: Optional[str]\n    \"\"\"The highlight type: STANDARD or THESAURUS_SYNONYM.\"\"\"\n# Unexpected keyword argument \"extra\" for \"__init_subclass__\" of \"object\"\n[docs]class TextWithHighLights(BaseModel, extra=Extra.allow):  # type: ignore[call-arg]\n    \"\"\"Text with highlights.\"\"\"\n    Text: str\n    \"\"\"The text.\"\"\"\n    Highlights: Optional[Any]\n    \"\"\"The highlights.\"\"\"\n# Unexpected keyword argument \"extra\" for \"__init_subclass__\" of \"object\"\n[docs]class AdditionalResultAttributeValue(  # type: ignore[call-arg]\n    BaseModel, extra=Extra.allow\n):\n    \"\"\"Value of an additional result attribute.\"\"\"\n    TextWithHighlightsValue: TextWithHighLights\n    \"\"\"The text with highlights value.\"\"\"\n# Unexpected keyword argument \"extra\" for \"__init_subclass__\" of \"object\"\n[docs]class AdditionalResultAttribute(BaseModel, extra=Extra.allow):  # type: ignore[call-arg]\n    \"\"\"Additional result attribute.\"\"\"\n    Key: str\n    \"\"\"The key of the attribute.\"\"\"\n    ValueType: Literal[\"TEXT_WITH_HIGHLIGHTS_VALUE\"]\n    \"\"\"The type of the value.\"\"\"\n    Value: AdditionalResultAttributeValue\n    \"\"\"The value of the attribute.\"\"\"\n[docs]    def get_value_text(self) -> str:\n        return self.Value.TextWithHighlightsValue.Text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html"}
{"id": "e2732978521a-2", "text": "return self.Value.TextWithHighlightsValue.Text\n# Unexpected keyword argument \"extra\" for \"__init_subclass__\" of \"object\"\n[docs]class DocumentAttributeValue(BaseModel, extra=Extra.allow):  # type: ignore[call-arg]\n    \"\"\"Value of a document attribute.\"\"\"\n    DateValue: Optional[str]\n    \"\"\"The date expressed as an ISO 8601 string.\"\"\"\n    LongValue: Optional[int]\n    \"\"\"The long value.\"\"\"\n    StringListValue: Optional[List[str]]\n    \"\"\"The string list value.\"\"\"\n    StringValue: Optional[str]\n    \"\"\"The string value.\"\"\"\n    @property\n    def value(self) -> DocumentAttributeValueType:\n        \"\"\"The only defined document attribute value or None.\n        According to Amazon Kendra, you can only provide one\n        value for a document attribute.\n        \"\"\"\n        if self.DateValue:\n            return self.DateValue\n        if self.LongValue:\n            return self.LongValue\n        if self.StringListValue:\n            return self.StringListValue\n        if self.StringValue:\n            return self.StringValue\n        return None\n# Unexpected keyword argument \"extra\" for \"__init_subclass__\" of \"object\"\n[docs]class DocumentAttribute(BaseModel, extra=Extra.allow):  # type: ignore[call-arg]\n    \"\"\"Document attribute.\"\"\"\n    Key: str\n    \"\"\"The key of the attribute.\"\"\"\n    Value: DocumentAttributeValue\n    \"\"\"The value of the attribute.\"\"\"\n# Unexpected keyword argument \"extra\" for \"__init_subclass__\" of \"object\"\n[docs]class ResultItem(BaseModel, ABC, extra=Extra.allow):  # type: ignore[call-arg]\n    \"\"\"Base class of a result item.\"\"\"\n    Id: Optional[str]\n    \"\"\"The ID of the relevant result item.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html"}
{"id": "e2732978521a-3", "text": "Id: Optional[str]\n    \"\"\"The ID of the relevant result item.\"\"\"\n    DocumentId: Optional[str]\n    \"\"\"The document ID.\"\"\"\n    DocumentURI: Optional[str]\n    \"\"\"The document URI.\"\"\"\n    DocumentAttributes: Optional[List[DocumentAttribute]] = []\n    \"\"\"The document attributes.\"\"\"\n[docs]    @abstractmethod\n    def get_title(self) -> str:\n        \"\"\"Document title.\"\"\"\n[docs]    @abstractmethod\n    def get_excerpt(self) -> str:\n        \"\"\"Document excerpt or passage original content as retrieved by Kendra.\"\"\"\n[docs]    def get_additional_metadata(self) -> dict:\n        \"\"\"Document additional metadata dict.\n        This returns any extra metadata except these:\n            * result_id\n            * document_id\n            * source\n            * title\n            * excerpt\n            * document_attributes\n        \"\"\"\n        return {}\n[docs]    def get_document_attributes_dict(self) -> Dict[str, DocumentAttributeValueType]:\n        \"\"\"Document attributes dict.\"\"\"\n        return {attr.Key: attr.Value.value for attr in (self.DocumentAttributes or [])}\n[docs]    def to_doc(\n        self, page_content_formatter: Callable[[\"ResultItem\"], str] = combined_text\n    ) -> Document:\n        \"\"\"Converts this item to a Document.\"\"\"\n        page_content = page_content_formatter(self)\n        metadata = self.get_additional_metadata()\n        metadata.update(\n            {\n                \"result_id\": self.Id,\n                \"document_id\": self.DocumentId,\n                \"source\": self.DocumentURI,\n                \"title\": self.get_title(),\n                \"excerpt\": self.get_excerpt(),\n                \"document_attributes\": self.get_document_attributes_dict(),\n            }\n        )\n        return Document(page_content=page_content, metadata=metadata)\n[docs]class QueryResultItem(ResultItem):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html"}
{"id": "e2732978521a-4", "text": "[docs]class QueryResultItem(ResultItem):\n    \"\"\"Query API result item.\"\"\"\n    DocumentTitle: TextWithHighLights\n    \"\"\"The document title.\"\"\"\n    FeedbackToken: Optional[str]\n    \"\"\"Identifies a particular result from a particular query.\"\"\"\n    Format: Optional[str]\n    \"\"\"\n    If the Type is ANSWER, then format is either:\n        * TABLE: a table excerpt is returned in TableExcerpt;\n        * TEXT: a text excerpt is returned in DocumentExcerpt.\n    \"\"\"\n    Type: Optional[str]\n    \"\"\"Type of result: DOCUMENT or QUESTION_ANSWER or ANSWER\"\"\"\n    AdditionalAttributes: Optional[List[AdditionalResultAttribute]] = []\n    \"\"\"One or more additional attributes associated with the result.\"\"\"\n    DocumentExcerpt: Optional[TextWithHighLights]\n    \"\"\"Excerpt of the document text.\"\"\"\n[docs]    def get_title(self) -> str:\n        return self.DocumentTitle.Text\n[docs]    def get_attribute_value(self) -> str:\n        if not self.AdditionalAttributes:\n            return \"\"\n        if not self.AdditionalAttributes[0]:\n            return \"\"\n        else:\n            return self.AdditionalAttributes[0].get_value_text()\n[docs]    def get_excerpt(self) -> str:\n        if (\n            self.AdditionalAttributes\n            and self.AdditionalAttributes[0].Key == \"AnswerText\"\n        ):\n            excerpt = self.get_attribute_value()\n        elif self.DocumentExcerpt:\n            excerpt = self.DocumentExcerpt.Text\n        else:\n            excerpt = \"\"\n        return excerpt\n[docs]    def get_additional_metadata(self) -> dict:\n        additional_metadata = {\"type\": self.Type}\n        return additional_metadata\n[docs]class RetrieveResultItem(ResultItem):\n    \"\"\"Retrieve API result item.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html"}
{"id": "e2732978521a-5", "text": "[docs]class RetrieveResultItem(ResultItem):\n    \"\"\"Retrieve API result item.\"\"\"\n    DocumentTitle: Optional[str]\n    \"\"\"The document title.\"\"\"\n    Content: Optional[str]\n    \"\"\"The content of the item.\"\"\"\n[docs]    def get_title(self) -> str:\n        return self.DocumentTitle or \"\"\n[docs]    def get_excerpt(self) -> str:\n        return self.Content or \"\"\n# Unexpected keyword argument \"extra\" for \"__init_subclass__\" of \"object\"\n[docs]class QueryResult(BaseModel, extra=Extra.allow):  # type: ignore[call-arg]\n    \"\"\"`Amazon Kendra Query API` search result.\n    It is composed of:\n        * Relevant suggested answers: either a text excerpt or table excerpt.\n        * Matching FAQs or questions-answer from your FAQ file.\n        * Documents including an excerpt of each document with its title.\n    \"\"\"\n    ResultItems: List[QueryResultItem]\n    \"\"\"The result items.\"\"\"\n# Unexpected keyword argument \"extra\" for \"__init_subclass__\" of \"object\"\n[docs]class RetrieveResult(BaseModel, extra=Extra.allow):  # type: ignore[call-arg]\n    \"\"\"`Amazon Kendra Retrieve API` search result.\n    It is composed of:\n        * relevant passages or text excerpts given an input query.\n    \"\"\"\n    QueryId: str\n    \"\"\"The ID of the query.\"\"\"\n    ResultItems: List[RetrieveResultItem]\n    \"\"\"The result items.\"\"\"\n[docs]class AmazonKendraRetriever(BaseRetriever):\n    \"\"\"`Amazon Kendra Index` retriever.\n    Args:\n        index_id: Kendra index id\n        region_name: The aws region e.g., `us-west-2`.\n            Fallsback to AWS_DEFAULT_REGION env variable", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html"}
{"id": "e2732978521a-6", "text": "Fallsback to AWS_DEFAULT_REGION env variable\n            or region specified in ~/.aws/config.\n        credentials_profile_name: The name of the profile in the ~/.aws/credentials\n            or ~/.aws/config files, which has either access keys or role information\n            specified. If not specified, the default credential profile or, if on an\n            EC2 instance, credentials from IMDS will be used.\n        top_k: No of results to return\n        attribute_filter: Additional filtering of results based on metadata\n            See: https://docs.aws.amazon.com/kendra/latest/APIReference\n        page_content_formatter: generates the Document page_content\n            allowing access to all result item attributes. By default, it uses\n            the item's title and excerpt.\n        client: boto3 client for Kendra\n        user_context: Provides information about the user context\n            See: https://docs.aws.amazon.com/kendra/latest/APIReference\n    Example:\n        .. code-block:: python\n            retriever = AmazonKendraRetriever(\n                index_id=\"c0806df7-e76b-4bce-9b5c-d5582f6b1a03\"\n            )\n    \"\"\"\n    index_id: str\n    region_name: Optional[str] = None\n    credentials_profile_name: Optional[str] = None\n    top_k: int = 3\n    attribute_filter: Optional[Dict] = None\n    page_content_formatter: Callable[[ResultItem], str] = combined_text\n    client: Any\n    user_context: Optional[Dict] = None\n    @validator(\"top_k\")\n    def validate_top_k(cls, value: int) -> int:\n        if value < 0:\n            raise ValueError(f\"top_k ({value}) cannot be negative.\")\n        return value\n    @root_validator(pre=True)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html"}
{"id": "e2732978521a-7", "text": "return value\n    @root_validator(pre=True)\n    def create_client(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        if values.get(\"client\") is not None:\n            return values\n        try:\n            import boto3\n            if values.get(\"credentials_profile_name\"):\n                session = boto3.Session(profile_name=values[\"credentials_profile_name\"])\n            else:\n                # use default credentials\n                session = boto3.Session()\n            client_params = {}\n            if values.get(\"region_name\"):\n                client_params[\"region_name\"] = values[\"region_name\"]\n            values[\"client\"] = session.client(\"kendra\", **client_params)\n            return values\n        except ImportError:\n            raise ModuleNotFoundError(\n                \"Could not import boto3 python package. \"\n                \"Please install it with `pip install boto3`.\"\n            )\n        except Exception as e:\n            raise ValueError(\n                \"Could not load credentials to authenticate with AWS client. \"\n                \"Please check that credentials in the specified \"\n                \"profile name are valid.\"\n            ) from e\n    def _kendra_query(self, query: str) -> Sequence[ResultItem]:\n        kendra_kwargs = {\n            \"IndexId\": self.index_id,\n            \"QueryText\": query.strip(),\n            \"PageSize\": self.top_k,\n        }\n        if self.attribute_filter is not None:\n            kendra_kwargs[\"AttributeFilter\"] = self.attribute_filter\n        if self.user_context is not None:\n            kendra_kwargs[\"UserContext\"] = self.user_context\n        response = self.client.retrieve(**kendra_kwargs)\n        r_result = RetrieveResult.parse_obj(response)\n        if r_result.ResultItems:\n            return r_result.ResultItems\n        # Retrieve API returned 0 results, fall back to Query API", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html"}
{"id": "e2732978521a-8", "text": "# Retrieve API returned 0 results, fall back to Query API\n        response = self.client.query(**kendra_kwargs)\n        q_result = QueryResult.parse_obj(response)\n        return q_result.ResultItems\n    def _get_top_k_docs(self, result_items: Sequence[ResultItem]) -> List[Document]:\n        top_docs = [\n            item.to_doc(self.page_content_formatter)\n            for item in result_items[: self.top_k]\n        ]\n        return top_docs\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n    ) -> List[Document]:\n        \"\"\"Run search on Kendra index and get top k documents\n        Example:\n        .. code-block:: python\n            docs = retriever.get_relevant_documents('This is my query')\n        \"\"\"\n        result_items = self._kendra_query(query)\n        top_k_docs = self._get_top_k_docs(result_items)\n        return top_k_docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html"}
{"id": "b2a31e689324-0", "text": "Source code for langchain.retrievers.bm25\nfrom __future__ import annotations\nfrom typing import Any, Callable, Dict, Iterable, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.schema import BaseRetriever, Document\n[docs]def default_preprocessing_func(text: str) -> List[str]:\n    return text.split()\n[docs]class BM25Retriever(BaseRetriever):\n    \"\"\"`BM25` retriever without Elasticsearch.\"\"\"\n    vectorizer: Any\n    \"\"\" BM25 vectorizer.\"\"\"\n    docs: List[Document]\n    \"\"\" List of documents.\"\"\"\n    k: int = 4\n    \"\"\" Number of documents to return.\"\"\"\n    preprocess_func: Callable[[str], List[str]] = default_preprocessing_func\n    \"\"\" Preprocessing function to use on the text before BM25 vectorization.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: Iterable[str],\n        metadatas: Optional[Iterable[dict]] = None,\n        bm25_params: Optional[Dict[str, Any]] = None,\n        preprocess_func: Callable[[str], List[str]] = default_preprocessing_func,\n        **kwargs: Any,\n    ) -> BM25Retriever:\n        \"\"\"\n        Create a BM25Retriever from a list of texts.\n        Args:\n            texts: A list of texts to vectorize.\n            metadatas: A list of metadata dicts to associate with each text.\n            bm25_params: Parameters to pass to the BM25 vectorizer.\n            preprocess_func: A function to preprocess each text before vectorization.\n            **kwargs: Any other arguments to pass to the retriever.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/bm25.html"}
{"id": "b2a31e689324-1", "text": "**kwargs: Any other arguments to pass to the retriever.\n        Returns:\n            A BM25Retriever instance.\n        \"\"\"\n        try:\n            from rank_bm25 import BM25Okapi\n        except ImportError:\n            raise ImportError(\n                \"Could not import rank_bm25, please install with `pip install \"\n                \"rank_bm25`.\"\n            )\n        texts_processed = [preprocess_func(t) for t in texts]\n        bm25_params = bm25_params or {}\n        vectorizer = BM25Okapi(texts_processed, **bm25_params)\n        metadatas = metadatas or ({} for _ in texts)\n        docs = [Document(page_content=t, metadata=m) for t, m in zip(texts, metadatas)]\n        return cls(\n            vectorizer=vectorizer, docs=docs, preprocess_func=preprocess_func, **kwargs\n        )\n[docs]    @classmethod\n    def from_documents(\n        cls,\n        documents: Iterable[Document],\n        *,\n        bm25_params: Optional[Dict[str, Any]] = None,\n        preprocess_func: Callable[[str], List[str]] = default_preprocessing_func,\n        **kwargs: Any,\n    ) -> BM25Retriever:\n        \"\"\"\n        Create a BM25Retriever from a list of Documents.\n        Args:\n            documents: A list of Documents to vectorize.\n            bm25_params: Parameters to pass to the BM25 vectorizer.\n            preprocess_func: A function to preprocess each text before vectorization.\n            **kwargs: Any other arguments to pass to the retriever.\n        Returns:\n            A BM25Retriever instance.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/bm25.html"}
{"id": "b2a31e689324-2", "text": "Returns:\n            A BM25Retriever instance.\n        \"\"\"\n        texts, metadatas = zip(*((d.page_content, d.metadata) for d in documents))\n        return cls.from_texts(\n            texts=texts,\n            bm25_params=bm25_params,\n            metadatas=metadatas,\n            preprocess_func=preprocess_func,\n            **kwargs,\n        )\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        processed_query = self.preprocess_func(query)\n        return_docs = self.vectorizer.get_top_n(processed_query, self.docs, n=self.k)\n        return return_docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/bm25.html"}
{"id": "a8cdc189842b-0", "text": "Source code for langchain.retrievers.tfidf\nfrom __future__ import annotations\nimport pickle\nfrom pathlib import Path\nfrom typing import Any, Dict, Iterable, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.schema import BaseRetriever, Document\n[docs]class TFIDFRetriever(BaseRetriever):\n    \"\"\"`TF-IDF` retriever.\n    Largely based on\n    https://github.com/asvskartheek/Text-Retrieval/blob/master/TF-IDF%20Search%20Engine%20(SKLEARN).ipynb\n    \"\"\"\n    vectorizer: Any\n    \"\"\"TF-IDF vectorizer.\"\"\"\n    docs: List[Document]\n    \"\"\"Documents.\"\"\"\n    tfidf_array: Any\n    \"\"\"TF-IDF array.\"\"\"\n    k: int = 4\n    \"\"\"Number of documents to return.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: Iterable[str],\n        metadatas: Optional[Iterable[dict]] = None,\n        tfidf_params: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> TFIDFRetriever:\n        try:\n            from sklearn.feature_extraction.text import TfidfVectorizer\n        except ImportError:\n            raise ImportError(\n                \"Could not import scikit-learn, please install with `pip install \"\n                \"scikit-learn`.\"\n            )\n        tfidf_params = tfidf_params or {}\n        vectorizer = TfidfVectorizer(**tfidf_params)\n        tfidf_array = vectorizer.fit_transform(texts)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html"}
{"id": "a8cdc189842b-1", "text": "tfidf_array = vectorizer.fit_transform(texts)\n        metadatas = metadatas or ({} for _ in texts)\n        docs = [Document(page_content=t, metadata=m) for t, m in zip(texts, metadatas)]\n        return cls(vectorizer=vectorizer, docs=docs, tfidf_array=tfidf_array, **kwargs)\n[docs]    @classmethod\n    def from_documents(\n        cls,\n        documents: Iterable[Document],\n        *,\n        tfidf_params: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> TFIDFRetriever:\n        texts, metadatas = zip(*((d.page_content, d.metadata) for d in documents))\n        return cls.from_texts(\n            texts=texts, tfidf_params=tfidf_params, metadatas=metadatas, **kwargs\n        )\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        from sklearn.metrics.pairwise import cosine_similarity\n        query_vec = self.vectorizer.transform(\n            [query]\n        )  # Ip -- (n_docs,x), Op -- (n_docs,n_Feats)\n        results = cosine_similarity(self.tfidf_array, query_vec).reshape(\n            (-1,)\n        )  # Op -- (n_docs,1) -- Cosine Sim with each doc\n        return_docs = [self.docs[i] for i in results.argsort()[-self.k :][::-1]]\n        return return_docs\n[docs]    def save_local(\n        self,\n        folder_path: str,\n        file_name: str = \"tfidf_vectorizer\",\n    ) -> None:\n        try:\n            import joblib", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html"}
{"id": "a8cdc189842b-2", "text": ") -> None:\n        try:\n            import joblib\n        except ImportError:\n            raise ImportError(\n                \"Could not import joblib, please install with `pip install joblib`.\"\n            )\n        path = Path(folder_path)\n        path.mkdir(exist_ok=True, parents=True)\n        # Save vectorizer with joblib dump.\n        joblib.dump(self.vectorizer, path / f\"{file_name}.joblib\")\n        # Save docs and tfidf array as pickle.\n        with open(path / f\"{file_name}.pkl\", \"wb\") as f:\n            pickle.dump((self.docs, self.tfidf_array), f)\n[docs]    @classmethod\n    def load_local(\n        cls,\n        folder_path: str,\n        file_name: str = \"tfidf_vectorizer\",\n    ) -> TFIDFRetriever:\n        try:\n            import joblib\n        except ImportError:\n            raise ImportError(\n                \"Could not import joblib, please install with `pip install joblib`.\"\n            )\n        path = Path(folder_path)\n        # Load vectorizer with joblib load.\n        vectorizer = joblib.load(path / f\"{file_name}.joblib\")\n        # Load docs and tfidf array as pickle.\n        with open(path / f\"{file_name}.pkl\", \"rb\") as f:\n            docs, tfidf_array = pickle.load(f)\n        return cls(vectorizer=vectorizer, docs=docs, tfidf_array=tfidf_array)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html"}
{"id": "7be6cae5f816-0", "text": "Source code for langchain.retrievers.multi_query\nimport asyncio\nimport logging\nfrom typing import List, Sequence\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.chains.llm import LLMChain\nfrom langchain.llms.base import BaseLLM\nfrom langchain.output_parsers.pydantic import PydanticOutputParser\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema import BaseRetriever, Document\nlogger = logging.getLogger(__name__)\n[docs]class LineList(BaseModel):\n    \"\"\"List of lines.\"\"\"\n    lines: List[str] = Field(description=\"Lines of text\")\n    \"\"\"List of lines.\"\"\"\n[docs]class LineListOutputParser(PydanticOutputParser):\n    \"\"\"Output parser for a list of lines.\"\"\"\n    def __init__(self) -> None:\n        super().__init__(pydantic_object=LineList)\n[docs]    def parse(self, text: str) -> LineList:\n        lines = text.strip().split(\"\\n\")\n        return LineList(lines=lines)\n# Default prompt\nDEFAULT_QUERY_PROMPT = PromptTemplate(\n    input_variables=[\"question\"],\n    template=\"\"\"You are an AI language model assistant. Your task is \n    to generate 3 different versions of the given user \n    question to retrieve relevant documents from a vector  database. \n    By generating multiple perspectives on the user question, \n    your goal is to help the user overcome some of the limitations \n    of distance-based similarity search. Provide these alternative \n    questions separated by newlines. Original question: {question}\"\"\",\n)\ndef _unique_documents(documents: Sequence[Document]) -> List[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html"}
{"id": "7be6cae5f816-1", "text": ")\ndef _unique_documents(documents: Sequence[Document]) -> List[Document]:\n    return [doc for i, doc in enumerate(documents) if doc not in documents[:i]]\n[docs]class MultiQueryRetriever(BaseRetriever):\n    \"\"\"Given a query, use an LLM to write a set of queries.\n    Retrieve docs for each query. Return the unique union of all retrieved docs.\n    \"\"\"\n    retriever: BaseRetriever\n    llm_chain: LLMChain\n    verbose: bool = True\n    parser_key: str = \"lines\"\n    include_original: bool = False\n    \"\"\"Whether to include the original query in the list of generated queries.\"\"\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        retriever: BaseRetriever,\n        llm: BaseLLM,\n        prompt: PromptTemplate = DEFAULT_QUERY_PROMPT,\n        parser_key: str = \"lines\",\n        include_original: bool = False,\n    ) -> \"MultiQueryRetriever\":\n        \"\"\"Initialize from llm using default template.\n        Args:\n            retriever: retriever to query documents from\n            llm: llm for query generation using DEFAULT_QUERY_PROMPT\n            include_original: Whether to include the original query in the list of\n                generated queries.\n        Returns:\n            MultiQueryRetriever\n        \"\"\"\n        output_parser = LineListOutputParser()\n        llm_chain = LLMChain(llm=llm, prompt=prompt, output_parser=output_parser)\n        return cls(\n            retriever=retriever,\n            llm_chain=llm_chain,\n            parser_key=parser_key,\n            include_original=include_original,\n        )\n    async def _aget_relevant_documents(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html"}
{"id": "7be6cae5f816-2", "text": ")\n    async def _aget_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: AsyncCallbackManagerForRetrieverRun,\n    ) -> List[Document]:\n        \"\"\"Get relevant documents given a user query.\n        Args:\n            question: user query\n        Returns:\n            Unique union of relevant documents from all generated queries\n        \"\"\"\n        queries = await self.agenerate_queries(query, run_manager)\n        if self.include_original:\n            queries.append(query)\n        documents = await self.aretrieve_documents(queries, run_manager)\n        return self.unique_union(documents)\n[docs]    async def agenerate_queries(\n        self, question: str, run_manager: AsyncCallbackManagerForRetrieverRun\n    ) -> List[str]:\n        \"\"\"Generate queries based upon user input.\n        Args:\n            question: user query\n        Returns:\n            List of LLM generated queries that are similar to the user input\n        \"\"\"\n        response = await self.llm_chain.acall(\n            inputs={\"question\": question}, callbacks=run_manager.get_child()\n        )\n        lines = getattr(response[\"text\"], self.parser_key, [])\n        if self.verbose:\n            logger.info(f\"Generated queries: {lines}\")\n        return lines\n[docs]    async def aretrieve_documents(\n        self, queries: List[str], run_manager: AsyncCallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"Run all LLM generated queries.\n        Args:\n            queries: query list\n        Returns:\n            List of retrieved Documents\n        \"\"\"\n        document_lists = await asyncio.gather(\n            *(\n                self.retriever.aget_relevant_documents(\n                    query, callbacks=run_manager.get_child()\n                )\n                for query in queries\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html"}
{"id": "7be6cae5f816-3", "text": ")\n                for query in queries\n            )\n        )\n        return [doc for docs in document_lists for doc in docs]\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n    ) -> List[Document]:\n        \"\"\"Get relevant documents given a user query.\n        Args:\n            question: user query\n        Returns:\n            Unique union of relevant documents from all generated queries\n        \"\"\"\n        queries = self.generate_queries(query, run_manager)\n        if self.include_original:\n            queries.append(query)\n        documents = self.retrieve_documents(queries, run_manager)\n        return self.unique_union(documents)\n[docs]    def generate_queries(\n        self, question: str, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[str]:\n        \"\"\"Generate queries based upon user input.\n        Args:\n            question: user query\n        Returns:\n            List of LLM generated queries that are similar to the user input\n        \"\"\"\n        response = self.llm_chain(\n            {\"question\": question}, callbacks=run_manager.get_child()\n        )\n        lines = getattr(response[\"text\"], self.parser_key, [])\n        if self.verbose:\n            logger.info(f\"Generated queries: {lines}\")\n        return lines\n[docs]    def retrieve_documents(\n        self, queries: List[str], run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"Run all LLM generated queries.\n        Args:\n            queries: query list\n        Returns:\n            List of retrieved Documents\n        \"\"\"\n        documents = []\n        for query in queries:\n            docs = self.retriever.get_relevant_documents(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html"}
{"id": "7be6cae5f816-4", "text": "for query in queries:\n            docs = self.retriever.get_relevant_documents(\n                query, callbacks=run_manager.get_child()\n            )\n            documents.extend(docs)\n        return documents\n[docs]    def unique_union(self, documents: List[Document]) -> List[Document]:\n        \"\"\"Get unique Documents.\n        Args:\n            documents: List of retrieved Documents\n        Returns:\n            List of unique retrieved Documents\n        \"\"\"\n        return _unique_documents(documents)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html"}
{"id": "a649a063a12a-0", "text": "Source code for langchain.retrievers.google_cloud_documentai_warehouse\n\"\"\"Retriever wrapper for Google Cloud Document AI Warehouse.\"\"\"\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import BaseRetriever\nfrom langchain.utilities.vertexai import get_client_info\nfrom langchain.utils import get_from_dict_or_env\nif TYPE_CHECKING:\n    from google.cloud.contentwarehouse_v1 import (\n        DocumentServiceClient,\n        RequestMetadata,\n        SearchDocumentsRequest,\n    )\n    from google.cloud.contentwarehouse_v1.services.document_service.pagers import (\n        SearchDocumentsPager,\n    )\n[docs]class GoogleDocumentAIWarehouseRetriever(BaseRetriever):\n    \"\"\"A retriever based on Document AI Warehouse.\n    Documents should be created and documents should be uploaded\n        in a separate flow, and this retriever uses only Document AI\n        schema_id provided to search for revelant documents.\n    More info: https://cloud.google.com/document-ai-warehouse.\n    \"\"\"\n    location: str = \"us\"\n    \"\"\"Google Cloud location where Document AI Warehouse is placed.\"\"\"\n    project_number: str\n    \"\"\"Google Cloud project number, should contain digits only.\"\"\"\n    schema_id: Optional[str] = None\n    \"\"\"Document AI Warehouse schema to query against.\n    If nothing is provided, all documents in the project will be searched.\"\"\"\n    qa_size_limit: int = 5\n    \"\"\"The limit on the number of documents returned.\"\"\"\n    client: \"DocumentServiceClient\" = None  #: :meta private:\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_cloud_documentai_warehouse.html"}
{"id": "a649a063a12a-1", "text": "@root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validates the environment.\"\"\"\n        try:  # noqa: F401\n            from google.cloud.contentwarehouse_v1 import DocumentServiceClient\n        except ImportError as exc:\n            raise ImportError(\n                \"google.cloud.contentwarehouse is not installed.\"\n                \"Please install it with pip install google-cloud-contentwarehouse\"\n            ) from exc\n        values[\"project_number\"] = get_from_dict_or_env(\n            values, \"project_number\", \"PROJECT_NUMBER\"\n        )\n        values[\"client\"] = DocumentServiceClient(\n            client_info=get_client_info(module=\"document-ai-warehouse\")\n        )\n        return values\n    def _prepare_request_metadata(self, user_ldap: str) -> \"RequestMetadata\":\n        from google.cloud.contentwarehouse_v1 import RequestMetadata, UserInfo\n        user_info = UserInfo(id=f\"user:{user_ldap}\")\n        return RequestMetadata(user_info=user_info)\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any\n    ) -> List[Document]:\n        request = self._prepare_search_request(query, **kwargs)\n        response = self.client.search_documents(request=request)\n        return self._parse_search_response(response=response)\n    def _prepare_search_request(\n        self, query: str, **kwargs: Any\n    ) -> \"SearchDocumentsRequest\":\n        from google.cloud.contentwarehouse_v1 import (\n            DocumentQuery,\n            SearchDocumentsRequest,\n        )\n        try:\n            user_ldap = kwargs[\"user_ldap\"]\n        except KeyError:\n            raise ValueError(\"Argument user_ldap should be provided!\")\n        request_metadata = self._prepare_request_metadata(user_ldap=user_ldap)\n        schemas = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_cloud_documentai_warehouse.html"}
{"id": "a649a063a12a-2", "text": "schemas = []\n        if self.schema_id:\n            schemas.append(\n                self.client.document_schema_path(\n                    project=self.project_number,\n                    location=self.location,\n                    document_schema=self.schema_id,\n                )\n            )\n        return SearchDocumentsRequest(\n            parent=self.client.common_location_path(self.project_number, self.location),\n            request_metadata=request_metadata,\n            document_query=DocumentQuery(\n                query=query, is_nl_query=True, document_schema_names=schemas\n            ),\n            qa_size_limit=self.qa_size_limit,\n        )\n    def _parse_search_response(\n        self, response: \"SearchDocumentsPager\"\n    ) -> List[Document]:\n        documents = []\n        for doc in response.matching_documents:\n            metadata = {\n                \"title\": doc.document.title,\n                \"source\": doc.document.raw_document_path,\n            }\n            documents.append(\n                Document(page_content=doc.search_text_snippet, metadata=metadata)\n            )\n        return documents", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_cloud_documentai_warehouse.html"}
{"id": "6388295a2869-0", "text": "Source code for langchain.retrievers.arcee\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.schema import BaseRetriever\nfrom langchain.utilities.arcee import ArceeWrapper, DALMFilter\nfrom langchain.utils import get_from_dict_or_env\n[docs]class ArceeRetriever(BaseRetriever):\n    \"\"\"Document retriever for Arcee's Domain Adapted Language Models (DALMs).\n    To use, set the ``ARCEE_API_KEY`` environment variable with your Arcee API key,\n    or pass ``arcee_api_key`` as a named parameter.\n    Example:\n        .. code-block:: python\n            from langchain.retrievers import ArceeRetriever\n            retriever = ArceeRetriever(\n                model=\"DALM-PubMed\",\n                arcee_api_key=\"ARCEE-API-KEY\"\n            )\n            documents = retriever.get_relevant_documents(\"AI-driven music therapy\")\n    \"\"\"\n    _client: Optional[ArceeWrapper] = None  #: :meta private:\n    \"\"\"Arcee client.\"\"\"\n    arcee_api_key: str = \"\"\n    \"\"\"Arcee API Key\"\"\"\n    model: str\n    \"\"\"Arcee DALM name\"\"\"\n    arcee_api_url: str = \"https://api.arcee.ai\"\n    \"\"\"Arcee API URL\"\"\"\n    arcee_api_version: str = \"v2\"\n    \"\"\"Arcee API Version\"\"\"\n    arcee_app_url: str = \"https://app.arcee.ai\"\n    \"\"\"Arcee App URL\"\"\"\n    model_kwargs: Optional[Dict[str, Any]] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/arcee.html"}
{"id": "6388295a2869-1", "text": "\"\"\"Keyword arguments to pass to the model.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        underscore_attrs_are_private = True\n    def __init__(self, **data: Any) -> None:\n        \"\"\"Initializes private fields.\"\"\"\n        super().__init__(**data)\n        self._client = ArceeWrapper(\n            arcee_api_key=self.arcee_api_key,\n            arcee_api_url=self.arcee_api_url,\n            arcee_api_version=self.arcee_api_version,\n            model_kwargs=self.model_kwargs,\n            model_name=self.model,\n        )\n        self._client.validate_model_training_status()\n    @root_validator()\n    def validate_environments(cls, values: Dict) -> Dict:\n        \"\"\"Validate Arcee environment variables.\"\"\"\n        # validate env vars\n        values[\"arcee_api_key\"] = get_from_dict_or_env(\n            values,\n            \"arcee_api_key\",\n            \"ARCEE_API_KEY\",\n        )\n        values[\"arcee_api_url\"] = get_from_dict_or_env(\n            values,\n            \"arcee_api_url\",\n            \"ARCEE_API_URL\",\n        )\n        values[\"arcee_app_url\"] = get_from_dict_or_env(\n            values,\n            \"arcee_app_url\",\n            \"ARCEE_APP_URL\",\n        )\n        values[\"arcee_api_version\"] = get_from_dict_or_env(\n            values,\n            \"arcee_api_version\",\n            \"ARCEE_API_VERSION\",\n        )\n        # validate model kwargs\n        if values[\"model_kwargs\"]:\n            kw = values[\"model_kwargs\"]\n            # validate size\n            if kw.get(\"size\") is not None:\n                if not kw.get(\"size\") >= 0:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/arcee.html"}
{"id": "6388295a2869-2", "text": "if not kw.get(\"size\") >= 0:\n                    raise ValueError(\"`size` must not be negative.\")\n            # validate filters\n            if kw.get(\"filters\") is not None:\n                if not isinstance(kw.get(\"filters\"), List):\n                    raise ValueError(\"`filters` must be a list.\")\n                for f in kw.get(\"filters\"):\n                    DALMFilter(**f)\n        return values\n    def _get_relevant_documents(\n        self, query: str, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Retrieve {size} contexts with your retriever for a given query\n        Args:\n            query: Query to submit to the model\n            size: The max number of context results to retrieve.\n            Defaults to 3. (Can be less if filters are provided).\n            filters: Filters to apply to the context dataset.\n        \"\"\"\n        try:\n            if not self._client:\n                raise ValueError(\"Client is not initialized.\")\n            return self._client.retrieve(query=query, **kwargs)\n        except Exception as e:\n            raise ValueError(f\"Error while retrieving documents: {e}\") from e", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/arcee.html"}
{"id": "c8a9f523757a-0", "text": "Source code for langchain.retrievers.databerry\nfrom typing import List, Optional\nimport aiohttp\nimport requests\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.schema import BaseRetriever, Document\n[docs]class DataberryRetriever(BaseRetriever):\n    \"\"\"`Databerry API` retriever.\"\"\"\n    datastore_url: str\n    top_k: Optional[int]\n    api_key: Optional[str]\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        response = requests.post(\n            self.datastore_url,\n            json={\n                \"query\": query,\n                **({\"topK\": self.top_k} if self.top_k is not None else {}),\n            },\n            headers={\n                \"Content-Type\": \"application/json\",\n                **(\n                    {\"Authorization\": f\"Bearer {self.api_key}\"}\n                    if self.api_key is not None\n                    else {}\n                ),\n            },\n        )\n        data = response.json()\n        return [\n            Document(\n                page_content=r[\"text\"],\n                metadata={\"source\": r[\"source\"], \"score\": r[\"score\"]},\n            )\n            for r in data[\"results\"]\n        ]\n    async def _aget_relevant_documents(\n        self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        async with aiohttp.ClientSession() as session:\n            async with session.request(\n                \"POST\",\n                self.datastore_url,\n                json={\n                    \"query\": query,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html"}
{"id": "c8a9f523757a-1", "text": "self.datastore_url,\n                json={\n                    \"query\": query,\n                    **({\"topK\": self.top_k} if self.top_k is not None else {}),\n                },\n                headers={\n                    \"Content-Type\": \"application/json\",\n                    **(\n                        {\"Authorization\": f\"Bearer {self.api_key}\"}\n                        if self.api_key is not None\n                        else {}\n                    ),\n                },\n            ) as response:\n                data = await response.json()\n        return [\n            Document(\n                page_content=r[\"text\"],\n                metadata={\"source\": r[\"source\"], \"score\": r[\"score\"]},\n            )\n            for r in data[\"results\"]\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html"}
{"id": "a03384beff91-0", "text": "Source code for langchain.retrievers.multi_vector\nfrom typing import List\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BaseRetriever, BaseStore, Document\nfrom langchain.schema.vectorstore import VectorStore\n[docs]class MultiVectorRetriever(BaseRetriever):\n    \"\"\"Retrieve from a set of multiple embeddings for the same document.\"\"\"\n    vectorstore: VectorStore\n    \"\"\"The underlying vectorstore to use to store small chunks\n    and their embedding vectors\"\"\"\n    docstore: BaseStore[str, Document]\n    \"\"\"The storage layer for the parent documents\"\"\"\n    id_key: str = \"doc_id\"\n    search_kwargs: dict = Field(default_factory=dict)\n    \"\"\"Keyword arguments to pass to the search function.\"\"\"\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"Get documents relevant to a query.\n        Args:\n            query: String to find relevant documents for\n            run_manager: The callbacks handler to use\n        Returns:\n            List of relevant documents\n        \"\"\"\n        sub_docs = self.vectorstore.similarity_search(query, **self.search_kwargs)\n        # We do this to maintain the order of the ids that are returned\n        ids = []\n        for d in sub_docs:\n            if d.metadata[self.id_key] not in ids:\n                ids.append(d.metadata[self.id_key])\n        docs = self.docstore.mget(ids)\n        return [d for d in docs if d is not None]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_vector.html"}
{"id": "3eb11acf49eb-0", "text": "Source code for langchain.retrievers.llama_index\nfrom typing import Any, Dict, List, cast\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BaseRetriever, Document\n[docs]class LlamaIndexRetriever(BaseRetriever):\n    \"\"\"`LlamaIndex` retriever.\n    It is used for the question-answering with sources over\n    an LlamaIndex data structure.\"\"\"\n    index: Any\n    \"\"\"LlamaIndex index to query.\"\"\"\n    query_kwargs: Dict = Field(default_factory=dict)\n    \"\"\"Keyword arguments to pass to the query method.\"\"\"\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"Get documents relevant for a query.\"\"\"\n        try:\n            from llama_index.indices.base import BaseGPTIndex\n            from llama_index.response.schema import Response\n        except ImportError:\n            raise ImportError(\n                \"You need to install `pip install llama-index` to use this retriever.\"\n            )\n        index = cast(BaseGPTIndex, self.index)\n        response = index.query(query, response_mode=\"no_text\", **self.query_kwargs)\n        response = cast(Response, response)\n        # parse source nodes\n        docs = []\n        for source_node in response.source_nodes:\n            metadata = source_node.extra_info or {}\n            docs.append(\n                Document(page_content=source_node.source_text, metadata=metadata)\n            )\n        return docs\n[docs]class LlamaIndexGraphRetriever(BaseRetriever):\n    \"\"\"`LlamaIndex` graph data structure retriever.\n    It is used for question-answering with sources over an LlamaIndex", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html"}
{"id": "3eb11acf49eb-1", "text": "It is used for question-answering with sources over an LlamaIndex\n    graph data structure.\"\"\"\n    graph: Any\n    \"\"\"LlamaIndex graph to query.\"\"\"\n    query_configs: List[Dict] = Field(default_factory=list)\n    \"\"\"List of query configs to pass to the query method.\"\"\"\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"Get documents relevant for a query.\"\"\"\n        try:\n            from llama_index.composability.graph import (\n                QUERY_CONFIG_TYPE,\n                ComposableGraph,\n            )\n            from llama_index.response.schema import Response\n        except ImportError:\n            raise ImportError(\n                \"You need to install `pip install llama-index` to use this retriever.\"\n            )\n        graph = cast(ComposableGraph, self.graph)\n        # for now, inject response_mode=\"no_text\" into query configs\n        for query_config in self.query_configs:\n            query_config[\"response_mode\"] = \"no_text\"\n        query_configs = cast(List[QUERY_CONFIG_TYPE], self.query_configs)\n        response = graph.query(query, query_configs=query_configs)\n        response = cast(Response, response)\n        # parse source nodes\n        docs = []\n        for source_node in response.source_nodes:\n            metadata = source_node.extra_info or {}\n            docs.append(\n                Document(page_content=source_node.source_text, metadata=metadata)\n            )\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html"}
{"id": "734db843c82e-0", "text": "Source code for langchain.retrievers.arxiv\nfrom typing import List\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.utilities.arxiv import ArxivAPIWrapper\n[docs]class ArxivRetriever(BaseRetriever, ArxivAPIWrapper):\n    \"\"\"`Arxiv` retriever.\n    It wraps load() to get_relevant_documents().\n    It uses all ArxivAPIWrapper arguments without any change.\n    \"\"\"\n    get_full_documents: bool = False\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        if self.get_full_documents:\n            return self.load(query=query)\n        else:\n            return self.get_summaries_as_docs(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/arxiv.html"}
{"id": "4434ac392004-0", "text": "Source code for langchain.retrievers.docarray\nfrom enum import Enum\nfrom typing import Any, Dict, List, Optional, Union\nimport numpy as np\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\n[docs]class SearchType(str, Enum):\n    \"\"\"Enumerator of the types of search to perform.\"\"\"\n    similarity = \"similarity\"\n    mmr = \"mmr\"\n[docs]class DocArrayRetriever(BaseRetriever):\n    \"\"\"`DocArray Document Indices` retriever.\n    Currently, it supports 5 backends:\n    InMemoryExactNNIndex, HnswDocumentIndex, QdrantDocumentIndex,\n    ElasticDocIndex, and WeaviateDocumentIndex.\n    Args:\n        index: One of the above-mentioned index instances\n        embeddings: Embedding model to represent text as vectors\n        search_field: Field to consider for searching in the documents.\n            Should be an embedding/vector/tensor.\n        content_field: Field that represents the main content in your document schema.\n            Will be used as a `page_content`. Everything else will go into `metadata`.\n        search_type: Type of search to perform (similarity / mmr)\n        filters: Filters applied for document retrieval.\n        top_k: Number of documents to return\n    \"\"\"\n    index: Any\n    embeddings: Embeddings\n    search_field: str\n    content_field: str\n    search_type: SearchType = SearchType.similarity\n    top_k: int = 1\n    filters: Optional[Any] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html"}
{"id": "4434ac392004-1", "text": "\"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n    ) -> List[Document]:\n        \"\"\"Get documents relevant for a query.\n        Args:\n            query: string to find relevant documents for\n        Returns:\n            List of relevant documents\n        \"\"\"\n        query_emb = np.array(self.embeddings.embed_query(query))\n        if self.search_type == SearchType.similarity:\n            results = self._similarity_search(query_emb)\n        elif self.search_type == SearchType.mmr:\n            results = self._mmr_search(query_emb)\n        else:\n            raise ValueError(\n                f\"Search type {self.search_type} does not exist. \"\n                f\"Choose either 'similarity' or 'mmr'.\"\n            )\n        return results\n    def _search(\n        self, query_emb: np.ndarray, top_k: int\n    ) -> List[Union[Dict[str, Any], Any]]:\n        \"\"\"\n        Perform a search using the query embedding and return top_k documents.\n        Args:\n            query_emb: Query represented as an embedding\n            top_k: Number of documents to return\n        Returns:\n            A list of top_k documents matching the query\n        \"\"\"\n        from docarray.index import ElasticDocIndex, WeaviateDocumentIndex\n        filter_args = {}\n        search_field = self.search_field\n        if isinstance(self.index, WeaviateDocumentIndex):\n            filter_args[\"where_filter\"] = self.filters\n            search_field = \"\"\n        elif isinstance(self.index, ElasticDocIndex):\n            filter_args[\"query\"] = self.filters\n        else:\n            filter_args[\"filter_query\"] = self.filters", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html"}
{"id": "4434ac392004-2", "text": "else:\n            filter_args[\"filter_query\"] = self.filters\n        if self.filters:\n            query = (\n                self.index.build_query()  # get empty query object\n                .find(\n                    query=query_emb, search_field=search_field\n                )  # add vector similarity search\n                .filter(**filter_args)  # add filter search\n                .build(limit=top_k)  # build the query\n            )\n            # execute the combined query and return the results\n            docs = self.index.execute_query(query)\n            if hasattr(docs, \"documents\"):\n                docs = docs.documents\n            docs = docs[:top_k]\n        else:\n            docs = self.index.find(\n                query=query_emb, search_field=search_field, limit=top_k\n            ).documents\n        return docs\n    def _similarity_search(self, query_emb: np.ndarray) -> List[Document]:\n        \"\"\"\n        Perform a similarity search.\n        Args:\n            query_emb: Query represented as an embedding\n        Returns:\n            A list of documents most similar to the query\n        \"\"\"\n        docs = self._search(query_emb=query_emb, top_k=self.top_k)\n        results = [self._docarray_to_langchain_doc(doc) for doc in docs]\n        return results\n    def _mmr_search(self, query_emb: np.ndarray) -> List[Document]:\n        \"\"\"\n        Perform a maximal marginal relevance (mmr) search.\n        Args:\n            query_emb: Query represented as an embedding\n        Returns:\n            A list of diverse documents related to the query\n        \"\"\"\n        docs = self._search(query_emb=query_emb, top_k=20)\n        mmr_selected = maximal_marginal_relevance(\n            query_emb,\n            [\n                doc[self.search_field]\n                if isinstance(doc, dict)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html"}
{"id": "4434ac392004-3", "text": "[\n                doc[self.search_field]\n                if isinstance(doc, dict)\n                else getattr(doc, self.search_field)\n                for doc in docs\n            ],\n            k=self.top_k,\n        )\n        results = [self._docarray_to_langchain_doc(docs[idx]) for idx in mmr_selected]\n        return results\n    def _docarray_to_langchain_doc(self, doc: Union[Dict[str, Any], Any]) -> Document:\n        \"\"\"\n        Convert a DocArray document (which also might be a dict)\n        to a langchain document format.\n        DocArray document can contain arbitrary fields, so the mapping is done\n        in the following way:\n        page_content <-> content_field\n        metadata <-> all other fields excluding\n            tensors and embeddings (so float, int, string)\n        Args:\n            doc: DocArray document\n        Returns:\n            Document in langchain format\n        Raises:\n            ValueError: If the document doesn't contain the content field\n        \"\"\"\n        fields = doc.keys() if isinstance(doc, dict) else doc.__fields__\n        if self.content_field not in fields:\n            raise ValueError(\n                f\"Document does not contain the content field - {self.content_field}.\"\n            )\n        lc_doc = Document(\n            page_content=doc[self.content_field]\n            if isinstance(doc, dict)\n            else getattr(doc, self.content_field)\n        )\n        for name in fields:\n            value = doc[name] if isinstance(doc, dict) else getattr(doc, name)\n            if (\n                isinstance(value, (str, int, float, bool))\n                and name != self.content_field\n            ):\n                lc_doc.metadata[name] = value\n        return lc_doc", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html"}
{"id": "81c91d92a589-0", "text": "Source code for langchain.retrievers.milvus\n\"\"\"Milvus Retriever\"\"\"\nimport warnings\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.vectorstores.milvus import Milvus\n# TODO: Update to MilvusClient + Hybrid Search when available\n[docs]class MilvusRetriever(BaseRetriever):\n    \"\"\"`Milvus API` retriever.\"\"\"\n    embedding_function: Embeddings\n    collection_name: str = \"LangChainCollection\"\n    connection_args: Optional[Dict[str, Any]] = None\n    consistency_level: str = \"Session\"\n    search_params: Optional[dict] = None\n    store: Milvus\n    retriever: BaseRetriever\n    @root_validator(pre=True)\n    def create_retriever(cls, values: Dict) -> Dict:\n        \"\"\"Create the Milvus store and retriever.\"\"\"\n        values[\"store\"] = Milvus(\n            values[\"embedding_function\"],\n            values[\"collection_name\"],\n            values[\"connection_args\"],\n            values[\"consistency_level\"],\n        )\n        values[\"retriever\"] = values[\"store\"].as_retriever(\n            search_kwargs={\"param\": values[\"search_params\"]}\n        )\n        return values\n[docs]    def add_texts(\n        self, texts: List[str], metadatas: Optional[List[dict]] = None\n    ) -> None:\n        \"\"\"Add text to the Milvus store\n        Args:\n            texts (List[str]): The text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/milvus.html"}
{"id": "81c91d92a589-1", "text": "Args:\n            texts (List[str]): The text\n            metadatas (List[dict]): Metadata dicts, must line up with existing store\n        \"\"\"\n        self.store.add_texts(texts, metadatas)\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n        **kwargs: Any,\n    ) -> List[Document]:\n        return self.retriever.get_relevant_documents(\n            query, run_manager=run_manager.get_child(), **kwargs\n        )\n[docs]def MilvusRetreiver(*args: Any, **kwargs: Any) -> MilvusRetriever:\n    \"\"\"Deprecated MilvusRetreiver. Please use MilvusRetriever ('i' before 'e') instead.\n    Args:\n        *args:\n        **kwargs:\n    Returns:\n        MilvusRetriever\n    \"\"\"\n    warnings.warn(\n        \"MilvusRetreiver will be deprecated in the future. \"\n        \"Please use MilvusRetriever ('i' before 'e') instead.\",\n        DeprecationWarning,\n    )\n    return MilvusRetriever(*args, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/milvus.html"}
{"id": "faef2f9faf23-0", "text": "Source code for langchain.retrievers.wikipedia\nfrom typing import List\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.utilities.wikipedia import WikipediaAPIWrapper\n[docs]class WikipediaRetriever(BaseRetriever, WikipediaAPIWrapper):\n    \"\"\"`Wikipedia API` retriever.\n    It wraps load() to get_relevant_documents().\n    It uses all WikipediaAPIWrapper arguments without any change.\n    \"\"\"\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        return self.load(query=query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/wikipedia.html"}
{"id": "012377404a81-0", "text": "Source code for langchain.retrievers.parent_document_retriever\nimport uuid\nfrom typing import List, Optional\nfrom langchain.retrievers import MultiVectorRetriever\nfrom langchain.schema.document import Document\nfrom langchain.text_splitter import TextSplitter\n[docs]class ParentDocumentRetriever(MultiVectorRetriever):\n    \"\"\"Retrieve small chunks then retrieve their parent documents.\n    When splitting documents for retrieval, there are often conflicting desires:\n    1. You may want to have small documents, so that their embeddings can most\n        accurately reflect their meaning. If too long, then the embeddings can\n        lose meaning.\n    2. You want to have long enough documents that the context of each chunk is\n        retained.\n    The ParentDocumentRetriever strikes that balance by splitting and storing\n    small chunks of data. During retrieval, it first fetches the small chunks\n    but then looks up the parent ids for those chunks and returns those larger\n    documents.\n    Note that \"parent document\" refers to the document that a small chunk\n    originated from. This can either be the whole raw document OR a larger\n    chunk.\n    Examples:\n        .. code-block:: python\n            # Imports\n            from langchain.vectorstores import Chroma\n            from langchain.embeddings import OpenAIEmbeddings\n            from langchain.text_splitter import RecursiveCharacterTextSplitter\n            from langchain.storage import InMemoryStore\n            # This text splitter is used to create the parent documents\n            parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000)\n            # This text splitter is used to create the child documents\n            # It should create documents smaller than the parent\n            child_splitter = RecursiveCharacterTextSplitter(chunk_size=400)\n            # The vectorstore to use to index the child chunks", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/parent_document_retriever.html"}
{"id": "012377404a81-1", "text": "# The vectorstore to use to index the child chunks\n            vectorstore = Chroma(embedding_function=OpenAIEmbeddings())\n            # The storage layer for the parent documents\n            store = InMemoryStore()\n            # Initialize the retriever\n            retriever = ParentDocumentRetriever(\n                vectorstore=vectorstore,\n                docstore=store,\n                child_splitter=child_splitter,\n                parent_splitter=parent_splitter,\n            )\n    \"\"\"\n    child_splitter: TextSplitter\n    \"\"\"The text splitter to use to create child documents.\"\"\"\n    \"\"\"The key to use to track the parent id. This will be stored in the\n    metadata of child documents.\"\"\"\n    parent_splitter: Optional[TextSplitter] = None\n    \"\"\"The text splitter to use to create parent documents.\n    If none, then the parent documents will be the raw documents passed in.\"\"\"\n[docs]    def add_documents(\n        self,\n        documents: List[Document],\n        ids: Optional[List[str]] = None,\n        add_to_docstore: bool = True,\n    ) -> None:\n        \"\"\"Adds documents to the docstore and vectorstores.\n        Args:\n            documents: List of documents to add\n            ids: Optional list of ids for documents. If provided should be the same\n                length as the list of documents. Can provided if parent documents\n                are already in the document store and you don't want to re-add\n                to the docstore. If not provided, random UUIDs will be used as\n                ids.\n            add_to_docstore: Boolean of whether to add documents to docstore.\n                This can be false if and only if `ids` are provided. You may want\n                to set this to False if the documents are already in the docstore", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/parent_document_retriever.html"}
{"id": "012377404a81-2", "text": "to set this to False if the documents are already in the docstore\n                and you don't want to re-add them.\n        \"\"\"\n        if self.parent_splitter is not None:\n            documents = self.parent_splitter.split_documents(documents)\n        if ids is None:\n            doc_ids = [str(uuid.uuid4()) for _ in documents]\n            if not add_to_docstore:\n                raise ValueError(\n                    \"If ids are not passed in, `add_to_docstore` MUST be True\"\n                )\n        else:\n            if len(documents) != len(ids):\n                raise ValueError(\n                    \"Got uneven list of documents and ids. \"\n                    \"If `ids` is provided, should be same length as `documents`.\"\n                )\n            doc_ids = ids\n        docs = []\n        full_docs = []\n        for i, doc in enumerate(documents):\n            _id = doc_ids[i]\n            sub_docs = self.child_splitter.split_documents([doc])\n            for _doc in sub_docs:\n                _doc.metadata[self.id_key] = _id\n            docs.extend(sub_docs)\n            full_docs.append((_id, doc))\n        self.vectorstore.add_documents(docs)\n        if add_to_docstore:\n            self.docstore.mset(full_docs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/parent_document_retriever.html"}
{"id": "767448b82452-0", "text": "Source code for langchain.retrievers.time_weighted_retriever\nimport datetime\nfrom copy import deepcopy\nfrom typing import Any, Dict, List, Optional, Tuple\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.schema.vectorstore import VectorStore\ndef _get_hours_passed(time: datetime.datetime, ref_time: datetime.datetime) -> float:\n    \"\"\"Get the hours passed between two datetimes.\"\"\"\n    return (time - ref_time).total_seconds() / 3600\n[docs]class TimeWeightedVectorStoreRetriever(BaseRetriever):\n    \"\"\"Retriever that combines embedding similarity with\n    recency in retrieving values.\"\"\"\n    vectorstore: VectorStore\n    \"\"\"The vectorstore to store documents and determine salience.\"\"\"\n    search_kwargs: dict = Field(default_factory=lambda: dict(k=100))\n    \"\"\"Keyword arguments to pass to the vectorstore similarity search.\"\"\"\n    # TODO: abstract as a queue\n    memory_stream: List[Document] = Field(default_factory=list)\n    \"\"\"The memory_stream of documents to search through.\"\"\"\n    decay_rate: float = Field(default=0.01)\n    \"\"\"The exponential decay factor used as (1.0-decay_rate)**(hrs_passed).\"\"\"\n    k: int = 4\n    \"\"\"The maximum number of documents to retrieve in a given call.\"\"\"\n    other_score_keys: List[str] = []\n    \"\"\"Other keys in the metadata to factor into the score, e.g. 'importance'.\"\"\"\n    default_salience: Optional[float] = None\n    \"\"\"The salience to assign memories not retrieved from the vector store.\n    None assigns no salience to documents not fetched from the vector store.\n    \"\"\"\n    class Config:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html"}
{"id": "767448b82452-1", "text": "\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    def _document_get_date(self, field: str, document: Document) -> datetime.datetime:\n        \"\"\"Return the value of the date field of a document.\"\"\"\n        if field in document.metadata:\n            if isinstance(document.metadata[field], float):\n                return datetime.datetime.fromtimestamp(document.metadata[field])\n            return document.metadata[field]\n        return datetime.datetime.now()\n    def _get_combined_score(\n        self,\n        document: Document,\n        vector_relevance: Optional[float],\n        current_time: datetime.datetime,\n    ) -> float:\n        \"\"\"Return the combined score for a document.\"\"\"\n        hours_passed = _get_hours_passed(\n            current_time,\n            self._document_get_date(\"last_accessed_at\", document),\n        )\n        score = (1.0 - self.decay_rate) ** hours_passed\n        for key in self.other_score_keys:\n            if key in document.metadata:\n                score += document.metadata[key]\n        if vector_relevance is not None:\n            score += vector_relevance\n        return score\n[docs]    def get_salient_docs(self, query: str) -> Dict[int, Tuple[Document, float]]:\n        \"\"\"Return documents that are salient to the query.\"\"\"\n        docs_and_scores: List[Tuple[Document, float]]\n        docs_and_scores = self.vectorstore.similarity_search_with_relevance_scores(\n            query, **self.search_kwargs\n        )\n        results = {}\n        for fetched_doc, relevance in docs_and_scores:\n            if \"buffer_idx\" in fetched_doc.metadata:\n                buffer_idx = fetched_doc.metadata[\"buffer_idx\"]\n                doc = self.memory_stream[buffer_idx]\n                results[buffer_idx] = (doc, relevance)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html"}
{"id": "767448b82452-2", "text": "results[buffer_idx] = (doc, relevance)\n        return results\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"Return documents that are relevant to the query.\"\"\"\n        current_time = datetime.datetime.now()\n        docs_and_scores = {\n            doc.metadata[\"buffer_idx\"]: (doc, self.default_salience)\n            for doc in self.memory_stream[-self.k :]\n        }\n        # If a doc is considered salient, update the salience score\n        docs_and_scores.update(self.get_salient_docs(query))\n        rescored_docs = [\n            (doc, self._get_combined_score(doc, relevance, current_time))\n            for doc, relevance in docs_and_scores.values()\n        ]\n        rescored_docs.sort(key=lambda x: x[1], reverse=True)\n        result = []\n        # Ensure frequently accessed memories aren't forgotten\n        for doc, _ in rescored_docs[: self.k]:\n            # TODO: Update vector store doc once `update` method is exposed.\n            buffered_doc = self.memory_stream[doc.metadata[\"buffer_idx\"]]\n            buffered_doc.metadata[\"last_accessed_at\"] = current_time\n            result.append(buffered_doc)\n        return result\n[docs]    def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]:\n        \"\"\"Add documents to vectorstore.\"\"\"\n        current_time = kwargs.get(\"current_time\")\n        if current_time is None:\n            current_time = datetime.datetime.now()\n        # Avoid mutating input documents\n        dup_docs = [deepcopy(d) for d in documents]\n        for i, doc in enumerate(dup_docs):\n            if \"last_accessed_at\" not in doc.metadata:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html"}
{"id": "767448b82452-3", "text": "if \"last_accessed_at\" not in doc.metadata:\n                doc.metadata[\"last_accessed_at\"] = current_time\n            if \"created_at\" not in doc.metadata:\n                doc.metadata[\"created_at\"] = current_time\n            doc.metadata[\"buffer_idx\"] = len(self.memory_stream) + i\n        self.memory_stream.extend(dup_docs)\n        return self.vectorstore.add_documents(dup_docs, **kwargs)\n[docs]    async def aadd_documents(\n        self, documents: List[Document], **kwargs: Any\n    ) -> List[str]:\n        \"\"\"Add documents to vectorstore.\"\"\"\n        current_time = kwargs.get(\"current_time\")\n        if current_time is None:\n            current_time = datetime.datetime.now()\n        # Avoid mutating input documents\n        dup_docs = [deepcopy(d) for d in documents]\n        for i, doc in enumerate(dup_docs):\n            if \"last_accessed_at\" not in doc.metadata:\n                doc.metadata[\"last_accessed_at\"] = current_time\n            if \"created_at\" not in doc.metadata:\n                doc.metadata[\"created_at\"] = current_time\n            doc.metadata[\"buffer_idx\"] = len(self.memory_stream) + i\n        self.memory_stream.extend(dup_docs)\n        return await self.vectorstore.aadd_documents(dup_docs, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html"}
{"id": "63be1662c062-0", "text": "Source code for langchain.retrievers.chatgpt_plugin_retriever\nfrom __future__ import annotations\nfrom typing import List, Optional\nimport aiohttp\nimport requests\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.schema import BaseRetriever, Document\n[docs]class ChatGPTPluginRetriever(BaseRetriever):\n    \"\"\"`ChatGPT plugin` retriever.\"\"\"\n    url: str\n    \"\"\"URL of the ChatGPT plugin.\"\"\"\n    bearer_token: str\n    \"\"\"Bearer token for the ChatGPT plugin.\"\"\"\n    top_k: int = 3\n    \"\"\"Number of documents to return.\"\"\"\n    filter: Optional[dict] = None\n    \"\"\"Filter to apply to the results.\"\"\"\n    aiosession: Optional[aiohttp.ClientSession] = None\n    \"\"\"Aiohttp session to use for requests.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n        \"\"\"Allow arbitrary types.\"\"\"\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        url, json, headers = self._create_request(query)\n        response = requests.post(url, json=json, headers=headers)\n        results = response.json()[\"results\"][0][\"results\"]\n        docs = []\n        for d in results:\n            content = d.pop(\"text\")\n            metadata = d.pop(\"metadata\", d)\n            if metadata.get(\"source_id\"):\n                metadata[\"source\"] = metadata.pop(\"source_id\")\n            docs.append(Document(page_content=content, metadata=metadata))\n        return docs\n    async def _aget_relevant_documents(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html"}
{"id": "63be1662c062-1", "text": "return docs\n    async def _aget_relevant_documents(\n        self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        url, json, headers = self._create_request(query)\n        if not self.aiosession:\n            async with aiohttp.ClientSession() as session:\n                async with session.post(url, headers=headers, json=json) as response:\n                    res = await response.json()\n        else:\n            async with self.aiosession.post(\n                url, headers=headers, json=json\n            ) as response:\n                res = await response.json()\n        results = res[\"results\"][0][\"results\"]\n        docs = []\n        for d in results:\n            content = d.pop(\"text\")\n            metadata = d.pop(\"metadata\", d)\n            if metadata.get(\"source_id\"):\n                metadata[\"source\"] = metadata.pop(\"source_id\")\n            docs.append(Document(page_content=content, metadata=metadata))\n        return docs\n    def _create_request(self, query: str) -> tuple[str, dict, dict]:\n        url = f\"{self.url}/query\"\n        json = {\n            \"queries\": [\n                {\n                    \"query\": query,\n                    \"filter\": self.filter,\n                    \"top_k\": self.top_k,\n                }\n            ]\n        }\n        headers = {\n            \"Content-Type\": \"application/json\",\n            \"Authorization\": f\"Bearer {self.bearer_token}\",\n        }\n        return url, json, headers", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html"}
{"id": "d5a8a13d84fd-0", "text": "Source code for langchain.retrievers.merger_retriever\nimport asyncio\nfrom typing import List\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.schema import BaseRetriever, Document\n[docs]class MergerRetriever(BaseRetriever):\n    \"\"\"Retriever that merges the results of multiple retrievers.\"\"\"\n    retrievers: List[BaseRetriever]\n    \"\"\"A list of retrievers to merge.\"\"\"\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n    ) -> List[Document]:\n        \"\"\"\n        Get the relevant documents for a given query.\n        Args:\n            query: The query to search for.\n        Returns:\n            A list of relevant documents.\n        \"\"\"\n        # Merge the results of the retrievers.\n        merged_documents = self.merge_documents(query, run_manager)\n        return merged_documents\n    async def _aget_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: AsyncCallbackManagerForRetrieverRun,\n    ) -> List[Document]:\n        \"\"\"\n        Asynchronously get the relevant documents for a given query.\n        Args:\n            query: The query to search for.\n        Returns:\n            A list of relevant documents.\n        \"\"\"\n        # Merge the results of the retrievers.\n        merged_documents = await self.amerge_documents(query, run_manager)\n        return merged_documents\n[docs]    def merge_documents(\n        self, query: str, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"\n        Merge the results of the retrievers.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html"}
{"id": "d5a8a13d84fd-1", "text": "\"\"\"\n        Merge the results of the retrievers.\n        Args:\n            query: The query to search for.\n        Returns:\n            A list of merged documents.\n        \"\"\"\n        # Get the results of all retrievers.\n        retriever_docs = [\n            retriever.get_relevant_documents(\n                query, callbacks=run_manager.get_child(\"retriever_{}\".format(i + 1))\n            )\n            for i, retriever in enumerate(self.retrievers)\n        ]\n        # Merge the results of the retrievers.\n        merged_documents = []\n        max_docs = max(len(docs) for docs in retriever_docs)\n        for i in range(max_docs):\n            for retriever, doc in zip(self.retrievers, retriever_docs):\n                if i < len(doc):\n                    merged_documents.append(doc[i])\n        return merged_documents\n[docs]    async def amerge_documents(\n        self, query: str, run_manager: AsyncCallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"\n        Asynchronously merge the results of the retrievers.\n        Args:\n            query: The query to search for.\n        Returns:\n            A list of merged documents.\n        \"\"\"\n        # Get the results of all retrievers.\n        retriever_docs = await asyncio.gather(\n            *(\n                retriever.aget_relevant_documents(\n                    query, callbacks=run_manager.get_child(\"retriever_{}\".format(i + 1))\n                )\n                for i, retriever in enumerate(self.retrievers)\n            )\n        )\n        # Merge the results of the retrievers.\n        merged_documents = []\n        max_docs = max(len(docs) for docs in retriever_docs)\n        for i in range(max_docs):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html"}
{"id": "d5a8a13d84fd-2", "text": "for i in range(max_docs):\n            for retriever, doc in zip(self.retrievers, retriever_docs):\n                if i < len(doc):\n                    merged_documents.append(doc[i])\n        return merged_documents", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html"}
{"id": "27fad2887f89-0", "text": "Source code for langchain.retrievers.pubmed\nfrom typing import List\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.utilities.pubmed import PubMedAPIWrapper\n[docs]class PubMedRetriever(BaseRetriever, PubMedAPIWrapper):\n    \"\"\"`PubMed API` retriever.\n    It wraps load() to get_relevant_documents().\n    It uses all PubMedAPIWrapper arguments without any change.\n    \"\"\"\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        return self.load_docs(query=query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/pubmed.html"}
{"id": "8caf3b79fbb5-0", "text": "Source code for langchain.retrievers.ensemble\n\"\"\"\nEnsemble retriever that ensemble the results of \nmultiple retrievers by using weighted  Reciprocal Rank Fusion\n\"\"\"\nfrom typing import Any, Dict, List\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import BaseRetriever, Document\n[docs]class EnsembleRetriever(BaseRetriever):\n    \"\"\"Retriever that ensembles the multiple retrievers.\n    It uses a rank fusion.\n    Args:\n        retrievers: A list of retrievers to ensemble.\n        weights: A list of weights corresponding to the retrievers. Defaults to equal\n            weighting for all retrievers.\n        c: A constant added to the rank, controlling the balance between the importance\n            of high-ranked items and the consideration given to lower-ranked items.\n            Default is 60.\n    \"\"\"\n    retrievers: List[BaseRetriever]\n    weights: List[float]\n    c: int = 60\n    @root_validator(pre=True)\n    def set_weights(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        if not values.get(\"weights\"):\n            n_retrievers = len(values[\"retrievers\"])\n            values[\"weights\"] = [1 / n_retrievers] * n_retrievers\n        return values\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n    ) -> List[Document]:\n        \"\"\"\n        Get the relevant documents for a given query.\n        Args:\n            query: The query to search for.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html"}
{"id": "8caf3b79fbb5-1", "text": "Args:\n            query: The query to search for.\n        Returns:\n            A list of reranked documents.\n        \"\"\"\n        # Get fused result of the retrievers.\n        fused_documents = self.rank_fusion(query, run_manager)\n        return fused_documents\n    async def _aget_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: AsyncCallbackManagerForRetrieverRun,\n    ) -> List[Document]:\n        \"\"\"\n        Asynchronously get the relevant documents for a given query.\n        Args:\n            query: The query to search for.\n        Returns:\n            A list of reranked documents.\n        \"\"\"\n        # Get fused result of the retrievers.\n        fused_documents = await self.arank_fusion(query, run_manager)\n        return fused_documents\n[docs]    def rank_fusion(\n        self, query: str, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"\n        Retrieve the results of the retrievers and use rank_fusion_func to get\n        the final result.\n        Args:\n            query: The query to search for.\n        Returns:\n            A list of reranked documents.\n        \"\"\"\n        # Get the results of all retrievers.\n        retriever_docs = [\n            retriever.get_relevant_documents(\n                query, callbacks=run_manager.get_child(tag=f\"retriever_{i+1}\")\n            )\n            for i, retriever in enumerate(self.retrievers)\n        ]\n        # apply rank fusion\n        fused_documents = self.weighted_reciprocal_rank(retriever_docs)\n        return fused_documents\n[docs]    async def arank_fusion(\n        self, query: str, run_manager: AsyncCallbackManagerForRetrieverRun", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html"}
{"id": "8caf3b79fbb5-2", "text": "self, query: str, run_manager: AsyncCallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"\n        Asynchronously retrieve the results of the retrievers\n        and use rank_fusion_func to get the final result.\n        Args:\n            query: The query to search for.\n        Returns:\n            A list of reranked documents.\n        \"\"\"\n        # Get the results of all retrievers.\n        retriever_docs = [\n            await retriever.aget_relevant_documents(\n                query, callbacks=run_manager.get_child(tag=f\"retriever_{i+1}\")\n            )\n            for i, retriever in enumerate(self.retrievers)\n        ]\n        # apply rank fusion\n        fused_documents = self.weighted_reciprocal_rank(retriever_docs)\n        return fused_documents\n[docs]    def weighted_reciprocal_rank(\n        self, doc_lists: List[List[Document]]\n    ) -> List[Document]:\n        \"\"\"\n        Perform weighted Reciprocal Rank Fusion on multiple rank lists.\n        You can find more details about RRF here:\n        https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf\n        Args:\n            doc_lists: A list of rank lists, where each rank list contains unique items.\n        Returns:\n            list: The final aggregated list of items sorted by their weighted RRF\n                    scores in descending order.\n        \"\"\"\n        if len(doc_lists) != len(self.weights):\n            raise ValueError(\n                \"Number of rank lists must be equal to the number of weights.\"\n            )\n        # Create a union of all unique documents in the input doc_lists\n        all_documents = set()\n        for doc_list in doc_lists:\n            for doc in doc_list:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html"}
{"id": "8caf3b79fbb5-3", "text": "for doc_list in doc_lists:\n            for doc in doc_list:\n                all_documents.add(doc.page_content)\n        # Initialize the RRF score dictionary for each document\n        rrf_score_dic = {doc: 0.0 for doc in all_documents}\n        # Calculate RRF scores for each document\n        for doc_list, weight in zip(doc_lists, self.weights):\n            for rank, doc in enumerate(doc_list, start=1):\n                rrf_score = weight * (1 / (rank + self.c))\n                rrf_score_dic[doc.page_content] += rrf_score\n        # Sort documents by their RRF scores in descending order\n        sorted_documents = sorted(\n            rrf_score_dic.keys(), key=lambda x: rrf_score_dic[x], reverse=True\n        )\n        # Map the sorted page_content back to the original document objects\n        page_content_to_doc_map = {\n            doc.page_content: doc for doc_list in doc_lists for doc in doc_list\n        }\n        sorted_docs = [\n            page_content_to_doc_map[page_content] for page_content in sorted_documents\n        ]\n        return sorted_docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html"}
{"id": "e23fd02f59f4-0", "text": "Source code for langchain.retrievers.weaviate_hybrid_search\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional, cast\nfrom uuid import uuid4\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import BaseRetriever\n[docs]class WeaviateHybridSearchRetriever(BaseRetriever):\n    \"\"\"`Weaviate hybrid search` retriever.\n    See the documentation:\n      https://weaviate.io/blog/hybrid-search-explained\n    \"\"\"\n    client: Any\n    \"\"\"keyword arguments to pass to the Weaviate client.\"\"\"\n    index_name: str\n    \"\"\"The name of the index to use.\"\"\"\n    text_key: str\n    \"\"\"The name of the text key to use.\"\"\"\n    alpha: float = 0.5\n    \"\"\"The weight of the text key in the hybrid search.\"\"\"\n    k: int = 4\n    \"\"\"The number of results to return.\"\"\"\n    attributes: List[str]\n    \"\"\"The attributes to return in the results.\"\"\"\n    create_schema_if_missing: bool = True\n    \"\"\"Whether to create the schema if it doesn't exist.\"\"\"\n    @root_validator(pre=True)\n    def validate_client(\n        cls,\n        values: Dict[str, Any],\n    ) -> Dict[str, Any]:\n        try:\n            import weaviate\n        except ImportError:\n            raise ImportError(\n                \"Could not import weaviate python package. \"\n                \"Please install it with `pip install weaviate-client`.\"\n            )\n        if not isinstance(values[\"client\"], weaviate.Client):\n            client = values[\"client\"]\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html"}
{"id": "e23fd02f59f4-1", "text": "client = values[\"client\"]\n            raise ValueError(\n                f\"client should be an instance of weaviate.Client, got {type(client)}\"\n            )\n        if values.get(\"attributes\") is None:\n            values[\"attributes\"] = []\n        cast(List, values[\"attributes\"]).append(values[\"text_key\"])\n        if values.get(\"create_schema_if_missing\", True):\n            class_obj = {\n                \"class\": values[\"index_name\"],\n                \"properties\": [{\"name\": values[\"text_key\"], \"dataType\": [\"text\"]}],\n                \"vectorizer\": \"text2vec-openai\",\n            }\n            if not values[\"client\"].schema.exists(values[\"index_name\"]):\n                values[\"client\"].schema.create_class(class_obj)\n        return values\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    # added text_key\n[docs]    def add_documents(self, docs: List[Document], **kwargs: Any) -> List[str]:\n        \"\"\"Upload documents to Weaviate.\"\"\"\n        from weaviate.util import get_valid_uuid\n        with self.client.batch as batch:\n            ids = []\n            for i, doc in enumerate(docs):\n                metadata = doc.metadata or {}\n                data_properties = {self.text_key: doc.page_content, **metadata}\n                # If the UUID of one of the objects already exists\n                # then the existing objectwill be replaced by the new object.\n                if \"uuids\" in kwargs:\n                    _id = kwargs[\"uuids\"][i]\n                else:\n                    _id = get_valid_uuid(uuid4())\n                batch.add_data_object(data_properties, self.index_name, _id)\n                ids.append(_id)\n        return ids\n    def _get_relevant_documents(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html"}
{"id": "e23fd02f59f4-2", "text": "return ids\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n        where_filter: Optional[Dict[str, object]] = None,\n        score: bool = False,\n        hybrid_search_kwargs: Optional[Dict[str, object]] = None,\n    ) -> List[Document]:\n        \"\"\"Look up similar documents in Weaviate.\n        query: The query to search for relevant documents\n         of using weviate hybrid search.\n        where_filter: A filter to apply to the query.\n            https://weaviate.io/developers/weaviate/guides/querying/#filtering\n        score: Whether to include the score, and score explanation\n            in the returned Documents meta_data.\n        hybrid_search_kwargs: Used to pass additional arguments\n         to the .with_hybrid() method.\n            The primary uses cases for this are:\n            1)  Search specific properties only -\n                specify which properties to be used during hybrid search portion.\n                Note: this is not the same as the (self.attributes) to be returned.\n                Example - hybrid_search_kwargs={\"properties\": [\"question\", \"answer\"]}\n            https://weaviate.io/developers/weaviate/search/hybrid#selected-properties-only\n            2) Weight boosted searched properties -\n                Boost the weight of certain properties during the hybrid search portion.\n                Example - hybrid_search_kwargs={\"properties\": [\"question^2\", \"answer\"]}\n            https://weaviate.io/developers/weaviate/search/hybrid#weight-boost-searched-properties\n            3) Search with a custom vector - Define a different vector\n                to be used during the hybrid search portion.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html"}
{"id": "e23fd02f59f4-3", "text": "to be used during the hybrid search portion.\n                Example - hybrid_search_kwargs={\"vector\": [0.1, 0.2, 0.3, ...]}\n            https://weaviate.io/developers/weaviate/search/hybrid#with-a-custom-vector\n            4) Use Fusion ranking method\n                Example - from weaviate.gql.get import HybridFusion\n                hybrid_search_kwargs={\"fusion\": fusion_type=HybridFusion.RELATIVE_SCORE}\n            https://weaviate.io/developers/weaviate/search/hybrid#fusion-ranking-method\n        \"\"\"\n        query_obj = self.client.query.get(self.index_name, self.attributes)\n        if where_filter:\n            query_obj = query_obj.with_where(where_filter)\n        if score:\n            query_obj = query_obj.with_additional([\"score\", \"explainScore\"])\n        if hybrid_search_kwargs is None:\n            hybrid_search_kwargs = {}\n        result = (\n            query_obj.with_hybrid(query, alpha=self.alpha, **hybrid_search_kwargs)\n            .with_limit(self.k)\n            .do()\n        )\n        if \"errors\" in result:\n            raise ValueError(f\"Error during query: {result['errors']}\")\n        docs = []\n        for res in result[\"data\"][\"Get\"][self.index_name]:\n            text = res.pop(self.text_key)\n            docs.append(Document(page_content=text, metadata=res))\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html"}
{"id": "ffe3488b7cad-0", "text": "Source code for langchain.retrievers.re_phraser\nimport logging\nfrom typing import List\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.chains.llm import LLMChain\nfrom langchain.llms.base import BaseLLM\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.schema import BaseRetriever, Document\nlogger = logging.getLogger(__name__)\n# Default template\nDEFAULT_TEMPLATE = \"\"\"You are an assistant tasked with taking a natural language \\\nquery from a user and converting it into a query for a vectorstore. \\\nIn this process, you strip out information that is not relevant for \\\nthe retrieval task. Here is the user query: {question}\"\"\"\n# Default prompt\nDEFAULT_QUERY_PROMPT = PromptTemplate.from_template(DEFAULT_TEMPLATE)\n[docs]class RePhraseQueryRetriever(BaseRetriever):\n    \"\"\"Given a query, use an LLM to re-phrase it.\n    Then, retrieve docs for the re-phrased query.\"\"\"\n    retriever: BaseRetriever\n    llm_chain: LLMChain\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        retriever: BaseRetriever,\n        llm: BaseLLM,\n        prompt: PromptTemplate = DEFAULT_QUERY_PROMPT,\n    ) -> \"RePhraseQueryRetriever\":\n        \"\"\"Initialize from llm using default template.\n        The prompt used here expects a single input: `question`\n        Args:\n            retriever: retriever to query documents from\n            llm: llm for query generation using DEFAULT_QUERY_PROMPT\n            prompt: prompt template for query generation\n        Returns:\n            RePhraseQueryRetriever\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/re_phraser.html"}
{"id": "ffe3488b7cad-1", "text": "Returns:\n            RePhraseQueryRetriever\n        \"\"\"\n        llm_chain = LLMChain(llm=llm, prompt=prompt)\n        return cls(\n            retriever=retriever,\n            llm_chain=llm_chain,\n        )\n    def _get_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: CallbackManagerForRetrieverRun,\n    ) -> List[Document]:\n        \"\"\"Get relevated documents given a user question.\n        Args:\n            query: user question\n        Returns:\n            Relevant documents for re-phrased question\n        \"\"\"\n        response = self.llm_chain(query, callbacks=run_manager.get_child())\n        re_phrased_question = response[\"text\"]\n        logger.info(f\"Re-phrased question: {re_phrased_question}\")\n        docs = self.retriever.get_relevant_documents(\n            re_phrased_question, callbacks=run_manager.get_child()\n        )\n        return docs\n    async def _aget_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: AsyncCallbackManagerForRetrieverRun,\n    ) -> List[Document]:\n        raise NotImplementedError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/re_phraser.html"}
{"id": "6059e267b354-0", "text": "Source code for langchain.retrievers.google_vertex_ai_search\n\"\"\"Retriever wrapper for Google Vertex AI Search.\"\"\"\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.utilities.vertexai import get_client_info\nfrom langchain.utils import get_from_dict_or_env\nif TYPE_CHECKING:\n    from google.api_core.client_options import ClientOptions\n    from google.cloud.discoveryengine_v1beta import (\n        ConversationalSearchServiceClient,\n        SearchRequest,\n        SearchResult,\n        SearchServiceClient,\n    )\nclass _BaseGoogleVertexAISearchRetriever(BaseModel):\n    project_id: str\n    \"\"\"Google Cloud Project ID.\"\"\"\n    data_store_id: str\n    \"\"\"Vertex AI Search data store ID.\"\"\"\n    location_id: str = \"global\"\n    \"\"\"Vertex AI Search data store location.\"\"\"\n    serving_config_id: str = \"default_config\"\n    \"\"\"Vertex AI Search serving config ID.\"\"\"\n    credentials: Any = None\n    \"\"\"The default custom credentials (google.auth.credentials.Credentials) to use\n    when making API calls. If not provided, credentials will be ascertained from\n    the environment.\"\"\"\n    engine_data_type: int = Field(default=0, ge=0, le=2)\n    \"\"\" Defines the Vertex AI Search data type\n    0 - Unstructured data \n    1 - Structured data\n    2 - Website data\n    \"\"\"\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validates the environment.\"\"\"\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html"}
{"id": "6059e267b354-1", "text": "\"\"\"Validates the environment.\"\"\"\n        try:\n            from google.cloud import discoveryengine_v1beta  # noqa: F401\n        except ImportError as exc:\n            raise ImportError(\n                \"google.cloud.discoveryengine is not installed.\"\n                \"Please install it with pip install \"\n                \"google-cloud-discoveryengine>=0.11.0\"\n            ) from exc\n        try:\n            from google.api_core.exceptions import InvalidArgument  # noqa: F401\n        except ImportError as exc:\n            raise ImportError(\n                \"google.api_core.exceptions is not installed. \"\n                \"Please install it with pip install google-api-core\"\n            ) from exc\n        values[\"project_id\"] = get_from_dict_or_env(values, \"project_id\", \"PROJECT_ID\")\n        try:\n            # For backwards compatibility\n            search_engine_id = get_from_dict_or_env(\n                values, \"search_engine_id\", \"SEARCH_ENGINE_ID\"\n            )\n            if search_engine_id:\n                import warnings\n                warnings.warn(\n                    \"The `search_engine_id` parameter is deprecated. Use `data_store_id` instead.\",  # noqa: E501\n                    DeprecationWarning,\n                )\n                values[\"data_store_id\"] = search_engine_id\n        except:  # noqa: E722\n            pass\n        values[\"data_store_id\"] = get_from_dict_or_env(\n            values, \"data_store_id\", \"DATA_STORE_ID\"\n        )\n        return values\n    @property\n    def client_options(self) -> \"ClientOptions\":\n        from google.api_core.client_options import ClientOptions\n        return ClientOptions(\n            api_endpoint=f\"{self.location_id}-discoveryengine.googleapis.com\"\n            if self.location_id != \"global\"\n            else None\n        )\n    def _convert_structured_search_response(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html"}
{"id": "6059e267b354-2", "text": "else None\n        )\n    def _convert_structured_search_response(\n        self, results: Sequence[SearchResult]\n    ) -> List[Document]:\n        \"\"\"Converts a sequence of search results to a list of LangChain documents.\"\"\"\n        import json\n        from google.protobuf.json_format import MessageToDict\n        documents: List[Document] = []\n        for result in results:\n            document_dict = MessageToDict(\n                result.document._pb, preserving_proto_field_name=True\n            )\n            documents.append(\n                Document(\n                    page_content=json.dumps(document_dict.get(\"struct_data\", {})),\n                    metadata={\"id\": document_dict[\"id\"], \"name\": document_dict[\"name\"]},\n                )\n            )\n        return documents\n    def _convert_unstructured_search_response(\n        self, results: Sequence[SearchResult], chunk_type: str\n    ) -> List[Document]:\n        \"\"\"Converts a sequence of search results to a list of LangChain documents.\"\"\"\n        from google.protobuf.json_format import MessageToDict\n        documents: List[Document] = []\n        for result in results:\n            document_dict = MessageToDict(\n                result.document._pb, preserving_proto_field_name=True\n            )\n            derived_struct_data = document_dict.get(\"derived_struct_data\")\n            if not derived_struct_data:\n                continue\n            doc_metadata = document_dict.get(\"struct_data\", {})\n            doc_metadata[\"id\"] = document_dict[\"id\"]\n            if chunk_type not in derived_struct_data:\n                continue\n            for chunk in derived_struct_data[chunk_type]:\n                doc_metadata[\"source\"] = derived_struct_data.get(\"link\", \"\")\n                if chunk_type == \"extractive_answers\":\n                    doc_metadata[\"source\"] += f\":{chunk.get('pageNumber', '')}\"\n                documents.append(\n                    Document(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html"}
{"id": "6059e267b354-3", "text": "documents.append(\n                    Document(\n                        page_content=chunk.get(\"content\", \"\"), metadata=doc_metadata\n                    )\n                )\n        return documents\n    def _convert_website_search_response(\n        self, results: Sequence[SearchResult], chunk_type: str\n    ) -> List[Document]:\n        \"\"\"Converts a sequence of search results to a list of LangChain documents.\"\"\"\n        from google.protobuf.json_format import MessageToDict\n        documents: List[Document] = []\n        for result in results:\n            document_dict = MessageToDict(\n                result.document._pb, preserving_proto_field_name=True\n            )\n            derived_struct_data = document_dict.get(\"derived_struct_data\")\n            if not derived_struct_data:\n                continue\n            doc_metadata = document_dict.get(\"struct_data\", {})\n            doc_metadata[\"id\"] = document_dict[\"id\"]\n            doc_metadata[\"source\"] = derived_struct_data.get(\"link\", \"\")\n            if chunk_type not in derived_struct_data:\n                continue\n            text_field = \"snippet\" if chunk_type == \"snippets\" else \"content\"\n            for chunk in derived_struct_data[chunk_type]:\n                documents.append(\n                    Document(\n                        page_content=chunk.get(text_field, \"\"), metadata=doc_metadata\n                    )\n                )\n        if not documents:\n            print(f\"No {chunk_type} could be found.\")\n            if chunk_type == \"extractive_answers\":\n                print(\n                    \"Make sure that your data store is using Advanced Website \"\n                    \"Indexing.\\n\"\n                    \"https://cloud.google.com/generative-ai-app-builder/docs/about-advanced-features#advanced-website-indexing\"  # noqa: E501\n                )\n        return documents", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html"}
{"id": "6059e267b354-4", "text": ")\n        return documents\n[docs]class GoogleVertexAISearchRetriever(BaseRetriever, _BaseGoogleVertexAISearchRetriever):\n    \"\"\"`Google Vertex AI Search` retriever.\n    For a detailed explanation of the Vertex AI Search concepts\n    and configuration parameters, refer to the product documentation.\n    https://cloud.google.com/generative-ai-app-builder/docs/enterprise-search-introduction\n    \"\"\"\n    filter: Optional[str] = None\n    \"\"\"Filter expression.\"\"\"\n    get_extractive_answers: bool = False\n    \"\"\"If True return Extractive Answers, otherwise return Extractive Segments or Snippets.\"\"\"  # noqa: E501\n    max_documents: int = Field(default=5, ge=1, le=100)\n    \"\"\"The maximum number of documents to return.\"\"\"\n    max_extractive_answer_count: int = Field(default=1, ge=1, le=5)\n    \"\"\"The maximum number of extractive answers returned in each search result.\n    At most 5 answers will be returned for each SearchResult.\n    \"\"\"\n    max_extractive_segment_count: int = Field(default=1, ge=1, le=1)\n    \"\"\"The maximum number of extractive segments returned in each search result.\n    Currently one segment will be returned for each SearchResult.\n    \"\"\"\n    query_expansion_condition: int = Field(default=1, ge=0, le=2)\n    \"\"\"Specification to determine under which conditions query expansion should occur.\n    0 - Unspecified query expansion condition. In this case, server behavior defaults \n        to disabled\n    1 - Disabled query expansion. Only the exact search query is used, even if \n        SearchResponse.total_size is zero.\n    2 - Automatic query expansion built by the Search API.\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html"}
{"id": "6059e267b354-5", "text": "2 - Automatic query expansion built by the Search API.\n    \"\"\"\n    spell_correction_mode: int = Field(default=2, ge=0, le=2)\n    \"\"\"Specification to determine under which conditions query expansion should occur.\n    0 - Unspecified spell correction mode. In this case, server behavior defaults \n        to auto.\n    1 - Suggestion only. Search API will try to find a spell suggestion if there is any\n        and put in the `SearchResponse.corrected_query`.\n        The spell suggestion will not be used as the search query.\n    2 - Automatic spell correction built by the Search API.\n        Search will be based on the corrected query if found.\n    \"\"\"\n    _client: SearchServiceClient\n    _serving_config: str\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.ignore\n        arbitrary_types_allowed = True\n        underscore_attrs_are_private = True\n    def __init__(self, **kwargs: Any) -> None:\n        \"\"\"Initializes private fields.\"\"\"\n        try:\n            from google.cloud.discoveryengine_v1beta import SearchServiceClient\n        except ImportError as exc:\n            raise ImportError(\n                \"google.cloud.discoveryengine is not installed.\"\n                \"Please install it with pip install google-cloud-discoveryengine\"\n            ) from exc\n        super().__init__(**kwargs)\n        #  For more information, refer to:\n        # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store\n        self._client = SearchServiceClient(\n            credentials=self.credentials,\n            client_options=self.client_options,\n            client_info=get_client_info(module=\"vertex-ai-search\"),\n        )\n        self._serving_config = self._client.serving_config_path(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html"}
{"id": "6059e267b354-6", "text": ")\n        self._serving_config = self._client.serving_config_path(\n            project=self.project_id,\n            location=self.location_id,\n            data_store=self.data_store_id,\n            serving_config=self.serving_config_id,\n        )\n    def _create_search_request(self, query: str) -> SearchRequest:\n        \"\"\"Prepares a SearchRequest object.\"\"\"\n        from google.cloud.discoveryengine_v1beta import SearchRequest\n        query_expansion_spec = SearchRequest.QueryExpansionSpec(\n            condition=self.query_expansion_condition,\n        )\n        spell_correction_spec = SearchRequest.SpellCorrectionSpec(\n            mode=self.spell_correction_mode\n        )\n        if self.engine_data_type == 0:\n            if self.get_extractive_answers:\n                extractive_content_spec = (\n                    SearchRequest.ContentSearchSpec.ExtractiveContentSpec(\n                        max_extractive_answer_count=self.max_extractive_answer_count,\n                    )\n                )\n            else:\n                extractive_content_spec = (\n                    SearchRequest.ContentSearchSpec.ExtractiveContentSpec(\n                        max_extractive_segment_count=self.max_extractive_segment_count,\n                    )\n                )\n            content_search_spec = SearchRequest.ContentSearchSpec(\n                extractive_content_spec=extractive_content_spec\n            )\n        elif self.engine_data_type == 1:\n            content_search_spec = None\n        elif self.engine_data_type == 2:\n            content_search_spec = SearchRequest.ContentSearchSpec(\n                extractive_content_spec=SearchRequest.ContentSearchSpec.ExtractiveContentSpec(\n                    max_extractive_answer_count=self.max_extractive_answer_count,\n                ),\n                snippet_spec=SearchRequest.ContentSearchSpec.SnippetSpec(\n                    return_snippet=True\n                ),\n            )\n        else:\n            raise NotImplementedError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html"}
{"id": "6059e267b354-7", "text": "),\n            )\n        else:\n            raise NotImplementedError(\n                \"Only data store type 0 (Unstructured), 1 (Structured),\"\n                \"or 2 (Website) are supported currently.\"\n                + f\" Got {self.engine_data_type}\"\n            )\n        return SearchRequest(\n            query=query,\n            filter=self.filter,\n            serving_config=self._serving_config,\n            page_size=self.max_documents,\n            content_search_spec=content_search_spec,\n            query_expansion_spec=query_expansion_spec,\n            spell_correction_spec=spell_correction_spec,\n        )\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"Get documents relevant for a query.\"\"\"\n        from google.api_core.exceptions import InvalidArgument\n        search_request = self._create_search_request(query)\n        try:\n            response = self._client.search(search_request)\n        except InvalidArgument as exc:\n            raise type(exc)(\n                exc.message\n                + \" This might be due to engine_data_type not set correctly.\"\n            )\n        if self.engine_data_type == 0:\n            chunk_type = (\n                \"extractive_answers\"\n                if self.get_extractive_answers\n                else \"extractive_segments\"\n            )\n            documents = self._convert_unstructured_search_response(\n                response.results, chunk_type\n            )\n        elif self.engine_data_type == 1:\n            documents = self._convert_structured_search_response(response.results)\n        elif self.engine_data_type == 2:\n            chunk_type = (\n                \"extractive_answers\" if self.get_extractive_answers else \"snippets\"\n            )\n            documents = self._convert_website_search_response(\n                response.results, chunk_type\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html"}
{"id": "6059e267b354-8", "text": "response.results, chunk_type\n            )\n        else:\n            raise NotImplementedError(\n                \"Only data store type 0 (Unstructured), 1 (Structured),\"\n                \"or 2 (Website) are supported currently.\"\n                + f\" Got {self.engine_data_type}\"\n            )\n        return documents\n[docs]class GoogleVertexAIMultiTurnSearchRetriever(\n    BaseRetriever, _BaseGoogleVertexAISearchRetriever\n):\n    \"\"\"`Google Vertex AI Search` retriever for multi-turn conversations.\"\"\"\n    conversation_id: str = \"-\"\n    \"\"\"Vertex AI Search Conversation ID.\"\"\"\n    _client: ConversationalSearchServiceClient\n    _serving_config: str\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.ignore\n        arbitrary_types_allowed = True\n        underscore_attrs_are_private = True\n    def __init__(self, **kwargs: Any):\n        super().__init__(**kwargs)\n        from google.cloud.discoveryengine_v1beta import (\n            ConversationalSearchServiceClient,\n        )\n        self._client = ConversationalSearchServiceClient(\n            credentials=self.credentials,\n            client_options=self.client_options,\n            client_info=get_client_info(module=\"vertex-ai-search\"),\n        )\n        self._serving_config = self._client.serving_config_path(\n            project=self.project_id,\n            location=self.location_id,\n            data_store=self.data_store_id,\n            serving_config=self.serving_config_id,\n        )\n        if self.engine_data_type == 1:\n            raise NotImplementedError(\n                \"Data store type 1 (Structured)\"\n                \"is not currently supported for multi-turn search.\"\n                + f\" Got {self.engine_data_type}\"\n            )\n    def _get_relevant_documents(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html"}
{"id": "6059e267b354-9", "text": ")\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"Get documents relevant for a query.\"\"\"\n        from google.cloud.discoveryengine_v1beta import (\n            ConverseConversationRequest,\n            TextInput,\n        )\n        request = ConverseConversationRequest(\n            name=self._client.conversation_path(\n                self.project_id,\n                self.location_id,\n                self.data_store_id,\n                self.conversation_id,\n            ),\n            serving_config=self._serving_config,\n            query=TextInput(input=query),\n        )\n        response = self._client.converse_conversation(request)\n        if self.engine_data_type == 2:\n            return self._convert_website_search_response(\n                response.search_results, \"extractive_answers\"\n            )\n        return self._convert_unstructured_search_response(\n            response.search_results, \"extractive_answers\"\n        )\n[docs]class GoogleCloudEnterpriseSearchRetriever(GoogleVertexAISearchRetriever):\n    \"\"\"`Google Vertex Search API` retriever alias for backwards compatibility.\n    DEPRECATED: Use `GoogleVertexAISearchRetriever` instead.\n    \"\"\"\n    def __init__(self, **data: Any):\n        import warnings\n        warnings.warn(\n            \"GoogleCloudEnterpriseSearchRetriever is deprecated, use GoogleVertexAISearchRetriever\",  # noqa: E501\n            DeprecationWarning,\n        )\n        super().__init__(**data)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html"}
{"id": "857e62d570f4-0", "text": "Source code for langchain.retrievers.vespa_retriever\nfrom __future__ import annotations\nimport json\nfrom typing import Any, Dict, List, Literal, Optional, Sequence, Union\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.schema import BaseRetriever, Document\n[docs]class VespaRetriever(BaseRetriever):\n    \"\"\"`Vespa` retriever.\"\"\"\n    app: Any\n    \"\"\"Vespa application to query.\"\"\"\n    body: Dict\n    \"\"\"Body of the query.\"\"\"\n    content_field: str\n    \"\"\"Name of the content field.\"\"\"\n    metadata_fields: Sequence[str]\n    \"\"\"Names of the metadata fields.\"\"\"\n    def _query(self, body: Dict) -> List[Document]:\n        response = self.app.query(body)\n        if not str(response.status_code).startswith(\"2\"):\n            raise RuntimeError(\n                \"Could not retrieve data from Vespa. Error code: {}\".format(\n                    response.status_code\n                )\n            )\n        root = response.json[\"root\"]\n        if \"errors\" in root:\n            raise RuntimeError(json.dumps(root[\"errors\"]))\n        docs = []\n        for child in response.hits:\n            page_content = child[\"fields\"].pop(self.content_field, \"\")\n            if self.metadata_fields == \"*\":\n                metadata = child[\"fields\"]\n            else:\n                metadata = {mf: child[\"fields\"].get(mf) for mf in self.metadata_fields}\n            metadata[\"id\"] = child[\"id\"]\n            docs.append(Document(page_content=page_content, metadata=metadata))\n        return docs\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        body = self.body.copy()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html"}
{"id": "857e62d570f4-1", "text": ") -> List[Document]:\n        body = self.body.copy()\n        body[\"query\"] = query\n        return self._query(body)\n[docs]    def get_relevant_documents_with_filter(\n        self, query: str, *, _filter: Optional[str] = None\n    ) -> List[Document]:\n        body = self.body.copy()\n        _filter = f\" and {_filter}\" if _filter else \"\"\n        body[\"yql\"] = body[\"yql\"] + _filter\n        body[\"query\"] = query\n        return self._query(body)\n[docs]    @classmethod\n    def from_params(\n        cls,\n        url: str,\n        content_field: str,\n        *,\n        k: Optional[int] = None,\n        metadata_fields: Union[Sequence[str], Literal[\"*\"]] = (),\n        sources: Union[Sequence[str], Literal[\"*\"], None] = None,\n        _filter: Optional[str] = None,\n        yql: Optional[str] = None,\n        **kwargs: Any,\n    ) -> VespaRetriever:\n        \"\"\"Instantiate retriever from params.\n        Args:\n            url (str): Vespa app URL.\n            content_field (str): Field in results to return as Document page_content.\n            k (Optional[int]): Number of Documents to return. Defaults to None.\n            metadata_fields(Sequence[str] or \"*\"): Fields in results to include in\n                document metadata. Defaults to empty tuple ().\n            sources (Sequence[str] or \"*\" or None): Sources to retrieve\n                from. Defaults to None.\n            _filter (Optional[str]): Document filter condition expressed in YQL.\n                Defaults to None.\n            yql (Optional[str]): Full YQL query to be used. Should not be specified", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html"}
{"id": "857e62d570f4-2", "text": "yql (Optional[str]): Full YQL query to be used. Should not be specified\n                if _filter or sources are specified. Defaults to None.\n            kwargs (Any): Keyword arguments added to query body.\n        Returns:\n            VespaRetriever: Instantiated VespaRetriever.\n        \"\"\"\n        try:\n            from vespa.application import Vespa\n        except ImportError:\n            raise ImportError(\n                \"pyvespa is not installed, please install with `pip install pyvespa`\"\n            )\n        app = Vespa(url)\n        body = kwargs.copy()\n        if yql and (sources or _filter):\n            raise ValueError(\n                \"yql should only be specified if both sources and _filter are not \"\n                \"specified.\"\n            )\n        else:\n            if metadata_fields == \"*\":\n                _fields = \"*\"\n                body[\"summary\"] = \"short\"\n            else:\n                _fields = \", \".join([content_field] + list(metadata_fields or []))\n            _sources = \", \".join(sources) if isinstance(sources, Sequence) else \"*\"\n            _filter = f\" and {_filter}\" if _filter else \"\"\n            yql = f\"select {_fields} from sources {_sources} where userQuery(){_filter}\"\n        body[\"yql\"] = yql\n        if k:\n            body[\"hits\"] = k\n        return cls(\n            app=app,\n            body=body,\n            content_field=content_field,\n            metadata_fields=metadata_fields,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html"}
{"id": "61068e6a3711-0", "text": "Source code for langchain.retrievers.you\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.utils import get_from_dict_or_env\n[docs]class YouRetriever(BaseRetriever):\n    \"\"\"`You` retriever that uses You.com's search API.\n    To connect to the You.com api requires an API key which\n    you can get by emailing api@you.com.\n    You can check out our docs at https://documentation.you.com.\n    You need to set the environment variable `YDC_API_KEY` for retriever to operate.\n    \"\"\"\n    ydc_api_key: str\n    k: Optional[int] = None\n    n_hits: Optional[int] = None\n    n_snippets_per_hit: Optional[int] = None\n    endpoint_type: str = \"web\"\n    @root_validator(pre=True)\n    def validate_client(\n        cls,\n        values: Dict[str, Any],\n    ) -> Dict[str, Any]:\n        values[\"ydc_api_key\"] = get_from_dict_or_env(\n            values, \"ydc_api_key\", \"YDC_API_KEY\"\n        )\n        return values\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        import requests\n        headers = {\"X-API-Key\": self.ydc_api_key}\n        if self.endpoint_type == \"web\":\n            results = requests.get(\n                f\"https://api.ydc-index.io/search?query={query}\",\n                headers=headers,\n            ).json()\n            docs = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/you.html"}
{"id": "61068e6a3711-1", "text": "headers=headers,\n            ).json()\n            docs = []\n            n_hits = self.n_hits or len(results[\"hits\"])\n            for hit in results[\"hits\"][:n_hits]:\n                n_snippets_per_hit = self.n_snippets_per_hit or len(hit[\"snippets\"])\n                for snippet in hit[\"snippets\"][:n_snippets_per_hit]:\n                    docs.append(Document(page_content=snippet))\n                    if self.k is not None and len(docs) >= self.k:\n                        return docs\n            return docs\n        elif self.endpoint_type == \"snippet\":\n            results = requests.get(\n                f\"https://api.ydc-index.io/snippet_search?query={query}\",\n                headers=headers,\n            ).json()\n            return [Document(page_content=snippet) for snippet in results]\n        else:\n            raise RuntimeError(f\"Invalid endpoint type provided {self.endpoint_type}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/you.html"}
{"id": "7cc089ce94b5-0", "text": "Source code for langchain.retrievers.pinecone_hybrid_search\n\"\"\"Taken from: https://docs.pinecone.io/docs/hybrid-search\"\"\"\nimport hashlib\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.schema.embeddings import Embeddings\n[docs]def hash_text(text: str) -> str:\n    \"\"\"Hash a text using SHA256.\n    Args:\n        text: Text to hash.\n    Returns:\n        Hashed text.\n    \"\"\"\n    return str(hashlib.sha256(text.encode(\"utf-8\")).hexdigest())\n[docs]def create_index(\n    contexts: List[str],\n    index: Any,\n    embeddings: Embeddings,\n    sparse_encoder: Any,\n    ids: Optional[List[str]] = None,\n    metadatas: Optional[List[dict]] = None,\n    namespace: Optional[str] = None,\n) -> None:\n    \"\"\"Create an index from a list of contexts.\n    It modifies the index argument in-place!\n    Args:\n        contexts: List of contexts to embed.\n        index: Index to use.\n        embeddings: Embeddings model to use.\n        sparse_encoder: Sparse encoder to use.\n        ids: List of ids to use for the documents.\n        metadatas: List of metadata to use for the documents.\n    \"\"\"\n    batch_size = 32\n    _iterator = range(0, len(contexts), batch_size)\n    try:\n        from tqdm.auto import tqdm\n        _iterator = tqdm(_iterator)\n    except ImportError:\n        pass\n    if ids is None:\n        # create unique ids using hash of the text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html"}
{"id": "7cc089ce94b5-1", "text": "if ids is None:\n        # create unique ids using hash of the text\n        ids = [hash_text(context) for context in contexts]\n    for i in _iterator:\n        # find end of batch\n        i_end = min(i + batch_size, len(contexts))\n        # extract batch\n        context_batch = contexts[i:i_end]\n        batch_ids = ids[i:i_end]\n        metadata_batch = (\n            metadatas[i:i_end] if metadatas else [{} for _ in context_batch]\n        )\n        # add context passages as metadata\n        meta = [\n            {\"context\": context, **metadata}\n            for context, metadata in zip(context_batch, metadata_batch)\n        ]\n        # create dense vectors\n        dense_embeds = embeddings.embed_documents(context_batch)\n        # create sparse vectors\n        sparse_embeds = sparse_encoder.encode_documents(context_batch)\n        for s in sparse_embeds:\n            s[\"values\"] = [float(s1) for s1 in s[\"values\"]]\n        vectors = []\n        # loop through the data and create dictionaries for upserts\n        for doc_id, sparse, dense, metadata in zip(\n            batch_ids, sparse_embeds, dense_embeds, meta\n        ):\n            vectors.append(\n                {\n                    \"id\": doc_id,\n                    \"sparse_values\": sparse,\n                    \"values\": dense,\n                    \"metadata\": metadata,\n                }\n            )\n        # upload the documents to the new hybrid index\n        index.upsert(vectors, namespace=namespace)\n[docs]class PineconeHybridSearchRetriever(BaseRetriever):\n    \"\"\"`Pinecone Hybrid Search` retriever.\"\"\"\n    embeddings: Embeddings\n    \"\"\"Embeddings model to use.\"\"\"\n    \"\"\"description\"\"\"\n    sparse_encoder: Any", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html"}
{"id": "7cc089ce94b5-2", "text": "\"\"\"Embeddings model to use.\"\"\"\n    \"\"\"description\"\"\"\n    sparse_encoder: Any\n    \"\"\"Sparse encoder to use.\"\"\"\n    index: Any\n    \"\"\"Pinecone index to use.\"\"\"\n    top_k: int = 4\n    \"\"\"Number of documents to return.\"\"\"\n    alpha: float = 0.5\n    \"\"\"Alpha value for hybrid search.\"\"\"\n    namespace: Optional[str] = None\n    \"\"\"Namespace value for index partition.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n[docs]    def add_texts(\n        self,\n        texts: List[str],\n        ids: Optional[List[str]] = None,\n        metadatas: Optional[List[dict]] = None,\n        namespace: Optional[str] = None,\n    ) -> None:\n        create_index(\n            texts,\n            self.index,\n            self.embeddings,\n            self.sparse_encoder,\n            ids=ids,\n            metadatas=metadatas,\n            namespace=namespace,\n        )\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        try:\n            from pinecone_text.hybrid import hybrid_convex_scale  # noqa:F401\n            from pinecone_text.sparse.base_sparse_encoder import (\n                BaseSparseEncoder,  # noqa:F401\n            )\n        except ImportError:\n            raise ImportError(\n                \"Could not import pinecone_text python package. \"\n                \"Please install it with `pip install pinecone_text`.\"\n            )\n        return values\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html"}
{"id": "7cc089ce94b5-3", "text": "self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        from pinecone_text.hybrid import hybrid_convex_scale\n        sparse_vec = self.sparse_encoder.encode_queries(query)\n        # convert the question into a dense vector\n        dense_vec = self.embeddings.embed_query(query)\n        # scale alpha with hybrid_scale\n        dense_vec, sparse_vec = hybrid_convex_scale(dense_vec, sparse_vec, self.alpha)\n        sparse_vec[\"values\"] = [float(s1) for s1 in sparse_vec[\"values\"]]\n        # query pinecone with the query parameters\n        result = self.index.query(\n            vector=dense_vec,\n            sparse_vector=sparse_vec,\n            top_k=self.top_k,\n            include_metadata=True,\n            namespace=self.namespace,\n        )\n        final_result = []\n        for res in result[\"matches\"]:\n            context = res[\"metadata\"].pop(\"context\")\n            final_result.append(\n                Document(page_content=context, metadata=res[\"metadata\"])\n            )\n        # return search results as json\n        return final_result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html"}
{"id": "71625645dfbd-0", "text": "Source code for langchain.retrievers.document_compressors.chain_filter\n\"\"\"Filter that uses an LLM to drop documents that aren't relevant to the query.\"\"\"\nfrom typing import Any, Callable, Dict, Optional, Sequence\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains import LLMChain\nfrom langchain.output_parsers.boolean import BooleanOutputParser\nfrom langchain.prompts import PromptTemplate\nfrom langchain.retrievers.document_compressors.base import BaseDocumentCompressor\nfrom langchain.retrievers.document_compressors.chain_filter_prompt import (\n    prompt_template,\n)\nfrom langchain.schema import BasePromptTemplate, Document\nfrom langchain.schema.language_model import BaseLanguageModel\ndef _get_default_chain_prompt() -> PromptTemplate:\n    return PromptTemplate(\n        template=prompt_template,\n        input_variables=[\"question\", \"context\"],\n        output_parser=BooleanOutputParser(),\n    )\n[docs]def default_get_input(query: str, doc: Document) -> Dict[str, Any]:\n    \"\"\"Return the compression chain input.\"\"\"\n    return {\"question\": query, \"context\": doc.page_content}\n[docs]class LLMChainFilter(BaseDocumentCompressor):\n    \"\"\"Filter that drops documents that aren't relevant to the query.\"\"\"\n    llm_chain: LLMChain\n    \"\"\"LLM wrapper to use for filtering documents. \n    The chain prompt is expected to have a BooleanOutputParser.\"\"\"\n    get_input: Callable[[str, Document], dict] = default_get_input\n    \"\"\"Callable for constructing the chain input from the query and a Document.\"\"\"\n[docs]    def compress_documents(\n        self,\n        documents: Sequence[Document],\n        query: str,\n        callbacks: Optional[Callbacks] = None,\n    ) -> Sequence[Document]:\n        \"\"\"Filter down documents based on their relevance to the query.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html"}
{"id": "71625645dfbd-1", "text": "\"\"\"Filter down documents based on their relevance to the query.\"\"\"\n        filtered_docs = []\n        for doc in documents:\n            _input = self.get_input(query, doc)\n            include_doc = self.llm_chain.predict_and_parse(\n                **_input, callbacks=callbacks\n            )\n            if include_doc:\n                filtered_docs.append(doc)\n        return filtered_docs\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        prompt: Optional[BasePromptTemplate] = None,\n        **kwargs: Any,\n    ) -> \"LLMChainFilter\":\n        \"\"\"Create a LLMChainFilter from a language model.\n        Args:\n            llm: The language model to use for filtering.\n            prompt: The prompt to use for the filter.\n            **kwargs: Additional arguments to pass to the constructor.\n        Returns:\n            A LLMChainFilter that uses the given language model.\n        \"\"\"\n        _prompt = prompt if prompt is not None else _get_default_chain_prompt()\n        llm_chain = LLMChain(llm=llm, prompt=_prompt)\n        return cls(llm_chain=llm_chain, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html"}
{"id": "90e3a0c5dc9b-0", "text": "Source code for langchain.retrievers.document_compressors.cohere_rerank\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Dict, Optional, Sequence\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.retrievers.document_compressors.base import BaseDocumentCompressor\nfrom langchain.schema import Document\nfrom langchain.utils import get_from_dict_or_env\nif TYPE_CHECKING:\n    from cohere import Client\nelse:\n    # We do to avoid pydantic annotation issues when actually instantiating\n    # while keeping this import optional\n    try:\n        from cohere import Client\n    except ImportError:\n        pass\n[docs]class CohereRerank(BaseDocumentCompressor):\n    \"\"\"Document compressor that uses `Cohere Rerank API`.\"\"\"\n    client: Client\n    \"\"\"Cohere client to use for compressing documents.\"\"\"\n    top_n: int = 3\n    \"\"\"Number of documents to return.\"\"\"\n    model: str = \"rerank-english-v2.0\"\n    \"\"\"Model to use for reranking.\"\"\"\n    cohere_api_key: Optional[str] = None\n    user_agent: str = \"langchain\"\n    \"\"\"Identifier for the application making the request.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        try:\n            import cohere\n        except ImportError:\n            raise ImportError(\n                \"Could not import cohere python package. \"\n                \"Please install it with `pip install cohere`.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html"}
{"id": "90e3a0c5dc9b-1", "text": "\"Please install it with `pip install cohere`.\"\n            )\n        cohere_api_key = get_from_dict_or_env(\n            values, \"cohere_api_key\", \"COHERE_API_KEY\"\n        )\n        client_name = values[\"user_agent\"]\n        values[\"client\"] = cohere.Client(cohere_api_key, client_name=client_name)\n        return values\n[docs]    def compress_documents(\n        self,\n        documents: Sequence[Document],\n        query: str,\n        callbacks: Optional[Callbacks] = None,\n    ) -> Sequence[Document]:\n        \"\"\"\n        Compress documents using Cohere's rerank API.\n        Args:\n            documents: A sequence of documents to compress.\n            query: The query to use for compressing the documents.\n            callbacks: Callbacks to run during the compression process.\n        Returns:\n            A sequence of compressed documents.\n        \"\"\"\n        if len(documents) == 0:  # to avoid empty api call\n            return []\n        doc_list = list(documents)\n        _docs = [d.page_content for d in doc_list]\n        results = self.client.rerank(\n            model=self.model, query=query, documents=_docs, top_n=self.top_n\n        )\n        final_results = []\n        for r in results:\n            doc = doc_list[r.index]\n            doc.metadata[\"relevance_score\"] = r.relevance_score\n            final_results.append(doc)\n        return final_results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html"}
{"id": "0cc4b162dbae-0", "text": "Source code for langchain.retrievers.document_compressors.base\nimport asyncio\nfrom abc import ABC, abstractmethod\nfrom inspect import signature\nfrom typing import List, Optional, Sequence, Union\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema import BaseDocumentTransformer, Document\n[docs]class BaseDocumentCompressor(BaseModel, ABC):\n    \"\"\"Base class for document compressors.\"\"\"\n[docs]    @abstractmethod\n    def compress_documents(\n        self,\n        documents: Sequence[Document],\n        query: str,\n        callbacks: Optional[Callbacks] = None,\n    ) -> Sequence[Document]:\n        \"\"\"Compress retrieved documents given the query context.\"\"\"\n[docs]    async def acompress_documents(\n        self,\n        documents: Sequence[Document],\n        query: str,\n        callbacks: Optional[Callbacks] = None,\n    ) -> Sequence[Document]:\n        \"\"\"Compress retrieved documents given the query context.\"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, self.compress_documents, documents, query, callbacks\n        )\n[docs]class DocumentCompressorPipeline(BaseDocumentCompressor):\n    \"\"\"Document compressor that uses a pipeline of Transformers.\"\"\"\n    transformers: List[Union[BaseDocumentTransformer, BaseDocumentCompressor]]\n    \"\"\"List of document filters that are chained together and run in sequence.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def compress_documents(\n        self,\n        documents: Sequence[Document],\n        query: str,\n        callbacks: Optional[Callbacks] = None,\n    ) -> Sequence[Document]:\n        \"\"\"Transform a list of documents.\"\"\"\n        for _transformer in self.transformers:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html"}
{"id": "0cc4b162dbae-1", "text": "\"\"\"Transform a list of documents.\"\"\"\n        for _transformer in self.transformers:\n            if isinstance(_transformer, BaseDocumentCompressor):\n                accepts_callbacks = (\n                    signature(_transformer.compress_documents).parameters.get(\n                        \"callbacks\"\n                    )\n                    is not None\n                )\n                if accepts_callbacks:\n                    documents = _transformer.compress_documents(\n                        documents, query, callbacks=callbacks\n                    )\n                else:\n                    documents = _transformer.compress_documents(documents, query)\n            elif isinstance(_transformer, BaseDocumentTransformer):\n                documents = _transformer.transform_documents(documents)\n            else:\n                raise ValueError(f\"Got unexpected transformer type: {_transformer}\")\n        return documents\n[docs]    async def acompress_documents(\n        self,\n        documents: Sequence[Document],\n        query: str,\n        callbacks: Optional[Callbacks] = None,\n    ) -> Sequence[Document]:\n        \"\"\"Compress retrieved documents given the query context.\"\"\"\n        for _transformer in self.transformers:\n            if isinstance(_transformer, BaseDocumentCompressor):\n                accepts_callbacks = (\n                    signature(_transformer.acompress_documents).parameters.get(\n                        \"callbacks\"\n                    )\n                    is not None\n                )\n                if accepts_callbacks:\n                    documents = await _transformer.acompress_documents(\n                        documents, query, callbacks=callbacks\n                    )\n                else:\n                    documents = await _transformer.acompress_documents(documents, query)\n            elif isinstance(_transformer, BaseDocumentTransformer):\n                documents = await _transformer.atransform_documents(documents)\n            else:\n                raise ValueError(f\"Got unexpected transformer type: {_transformer}\")\n        return documents", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html"}
{"id": "5eddf846c1e4-0", "text": "Source code for langchain.retrievers.document_compressors.chain_extract\n\"\"\"DocumentFilter that uses an LLM chain to extract the relevant parts of documents.\"\"\"\nfrom __future__ import annotations\nimport asyncio\nfrom typing import Any, Callable, Dict, Optional, Sequence\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.retrievers.document_compressors.base import BaseDocumentCompressor\nfrom langchain.retrievers.document_compressors.chain_extract_prompt import (\n    prompt_template,\n)\nfrom langchain.schema import BaseOutputParser, Document\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]def default_get_input(query: str, doc: Document) -> Dict[str, Any]:\n    \"\"\"Return the compression chain input.\"\"\"\n    return {\"question\": query, \"context\": doc.page_content}\n[docs]class NoOutputParser(BaseOutputParser[str]):\n    \"\"\"Parse outputs that could return a null string of some sort.\"\"\"\n    no_output_str: str = \"NO_OUTPUT\"\n[docs]    def parse(self, text: str) -> str:\n        cleaned_text = text.strip()\n        if cleaned_text == self.no_output_str:\n            return \"\"\n        return cleaned_text\ndef _get_default_chain_prompt() -> PromptTemplate:\n    output_parser = NoOutputParser()\n    template = prompt_template.format(no_output_str=output_parser.no_output_str)\n    return PromptTemplate(\n        template=template,\n        input_variables=[\"question\", \"context\"],\n        output_parser=output_parser,\n    )\n[docs]class LLMChainExtractor(BaseDocumentCompressor):\n    \"\"\"Document compressor that uses an LLM chain to extract\n    the relevant parts of documents.\"\"\"\n    llm_chain: LLMChain\n    \"\"\"LLM wrapper to use for compressing documents.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html"}
{"id": "5eddf846c1e4-1", "text": "\"\"\"LLM wrapper to use for compressing documents.\"\"\"\n    get_input: Callable[[str, Document], dict] = default_get_input\n    \"\"\"Callable for constructing the chain input from the query and a Document.\"\"\"\n[docs]    def compress_documents(\n        self,\n        documents: Sequence[Document],\n        query: str,\n        callbacks: Optional[Callbacks] = None,\n    ) -> Sequence[Document]:\n        \"\"\"Compress page content of raw documents.\"\"\"\n        compressed_docs = []\n        for doc in documents:\n            _input = self.get_input(query, doc)\n            output = self.llm_chain.predict_and_parse(**_input, callbacks=callbacks)\n            if len(output) == 0:\n                continue\n            compressed_docs.append(Document(page_content=output, metadata=doc.metadata))\n        return compressed_docs\n[docs]    async def acompress_documents(\n        self,\n        documents: Sequence[Document],\n        query: str,\n        callbacks: Optional[Callbacks] = None,\n    ) -> Sequence[Document]:\n        \"\"\"Compress page content of raw documents asynchronously.\"\"\"\n        outputs = await asyncio.gather(\n            *[\n                self.llm_chain.apredict_and_parse(\n                    **self.get_input(query, doc), callbacks=callbacks\n                )\n                for doc in documents\n            ]\n        )\n        compressed_docs = []\n        for i, doc in enumerate(documents):\n            if len(outputs[i]) == 0:\n                continue\n            compressed_docs.append(\n                Document(page_content=outputs[i], metadata=doc.metadata)\n            )\n        return compressed_docs\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        prompt: Optional[PromptTemplate] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html"}
{"id": "5eddf846c1e4-2", "text": "prompt: Optional[PromptTemplate] = None,\n        get_input: Optional[Callable[[str, Document], str]] = None,\n        llm_chain_kwargs: Optional[dict] = None,\n    ) -> LLMChainExtractor:\n        \"\"\"Initialize from LLM.\"\"\"\n        _prompt = prompt if prompt is not None else _get_default_chain_prompt()\n        _get_input = get_input if get_input is not None else default_get_input\n        llm_chain = LLMChain(llm=llm, prompt=_prompt, **(llm_chain_kwargs or {}))\n        return cls(llm_chain=llm_chain, get_input=_get_input)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html"}
{"id": "279eb365d026-0", "text": "Source code for langchain.retrievers.document_compressors.embeddings_filter\nfrom typing import Callable, Dict, Optional, Sequence\nimport numpy as np\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.document_transformers.embeddings_redundant_filter import (\n    _get_embeddings_from_stateful_docs,\n    get_stateful_documents,\n)\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.retrievers.document_compressors.base import (\n    BaseDocumentCompressor,\n)\nfrom langchain.schema import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.utils.math import cosine_similarity\n[docs]class EmbeddingsFilter(BaseDocumentCompressor):\n    \"\"\"Document compressor that uses embeddings to drop documents\n    unrelated to the query.\"\"\"\n    embeddings: Embeddings\n    \"\"\"Embeddings to use for embedding document contents and queries.\"\"\"\n    similarity_fn: Callable = cosine_similarity\n    \"\"\"Similarity function for comparing documents. Function expected to take as input\n    two matrices (List[List[float]]) and return a matrix of scores where higher values\n    indicate greater similarity.\"\"\"\n    k: Optional[int] = 20\n    \"\"\"The number of relevant documents to return. Can be set to None, in which case\n    `similarity_threshold` must be specified. Defaults to 20.\"\"\"\n    similarity_threshold: Optional[float]\n    \"\"\"Threshold for determining when two documents are similar enough\n    to be considered redundant. Defaults to None, must be specified if `k` is set\n    to None.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @root_validator()\n    def validate_params(cls, values: Dict) -> Dict:\n        \"\"\"Validate similarity parameters.\"\"\"\n        if values[\"k\"] is None and values[\"similarity_threshold\"] is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html"}
{"id": "279eb365d026-1", "text": "if values[\"k\"] is None and values[\"similarity_threshold\"] is None:\n            raise ValueError(\"Must specify one of `k` or `similarity_threshold`.\")\n        return values\n[docs]    def compress_documents(\n        self,\n        documents: Sequence[Document],\n        query: str,\n        callbacks: Optional[Callbacks] = None,\n    ) -> Sequence[Document]:\n        \"\"\"Filter documents based on similarity of their embeddings to the query.\"\"\"\n        stateful_documents = get_stateful_documents(documents)\n        embedded_documents = _get_embeddings_from_stateful_docs(\n            self.embeddings, stateful_documents\n        )\n        embedded_query = self.embeddings.embed_query(query)\n        similarity = self.similarity_fn([embedded_query], embedded_documents)[0]\n        included_idxs = np.arange(len(embedded_documents))\n        if self.k is not None:\n            included_idxs = np.argsort(similarity)[::-1][: self.k]\n        if self.similarity_threshold is not None:\n            similar_enough = np.where(\n                similarity[included_idxs] > self.similarity_threshold\n            )\n            included_idxs = included_idxs[similar_enough]\n        for i in included_idxs:\n            stateful_documents[i].state[\"query_similarity_score\"] = similarity[i]\n        return [stateful_documents[i] for i in included_idxs]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html"}
{"id": "cf8858655bb0-0", "text": "Source code for langchain.retrievers.self_query.chroma\nfrom typing import Dict, Tuple, Union\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\n[docs]class ChromaTranslator(Visitor):\n    \"\"\"Translate `Chroma` internal query language elements to valid filters.\"\"\"\n    allowed_operators = [Operator.AND, Operator.OR]\n    \"\"\"Subset of allowed logical operators.\"\"\"\n    allowed_comparators = [\n        Comparator.EQ,\n        Comparator.NE,\n        Comparator.GT,\n        Comparator.GTE,\n        Comparator.LT,\n        Comparator.LTE,\n    ]\n    \"\"\"Subset of allowed logical comparators.\"\"\"\n    def _format_func(self, func: Union[Operator, Comparator]) -> str:\n        self._validate_func(func)\n        return f\"${func.value}\"\n[docs]    def visit_operation(self, operation: Operation) -> Dict:\n        args = [arg.accept(self) for arg in operation.arguments]\n        return {self._format_func(operation.operator): args}\n[docs]    def visit_comparison(self, comparison: Comparison) -> Dict:\n        return {\n            comparison.attribute: {\n                self._format_func(comparison.comparator): comparison.value\n            }\n        }\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, dict]:\n        if structured_query.filter is None:\n            kwargs = {}\n        else:\n            kwargs = {\"filter\": structured_query.filter.accept(self)}\n        return structured_query.query, kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/chroma.html"}
{"id": "749e62ef222c-0", "text": "Source code for langchain.retrievers.self_query.qdrant\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Tuple\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\nif TYPE_CHECKING:\n    from qdrant_client.http import models as rest\n[docs]class QdrantTranslator(Visitor):\n    \"\"\"Translate `Qdrant` internal query language elements to valid filters.\"\"\"\n    allowed_operators = (\n        Operator.AND,\n        Operator.OR,\n        Operator.NOT,\n    )\n    \"\"\"Subset of allowed logical operators.\"\"\"\n    allowed_comparators = (\n        Comparator.EQ,\n        Comparator.LT,\n        Comparator.LTE,\n        Comparator.GT,\n        Comparator.GTE,\n    )\n    \"\"\"Subset of allowed logical comparators.\"\"\"\n[docs]    def __init__(self, metadata_key: str):\n        self.metadata_key = metadata_key\n[docs]    def visit_operation(self, operation: Operation) -> rest.Filter:\n        try:\n            from qdrant_client.http import models as rest\n        except ImportError as e:\n            raise ImportError(\n                \"Cannot import qdrant_client. Please install with `pip install \"\n                \"qdrant-client`.\"\n            ) from e\n        args = [arg.accept(self) for arg in operation.arguments]\n        operator = {\n            Operator.AND: \"must\",\n            Operator.OR: \"should\",\n            Operator.NOT: \"must_not\",\n        }[operation.operator]\n        return rest.Filter(**{operator: args})\n[docs]    def visit_comparison(self, comparison: Comparison) -> rest.FieldCondition:\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/qdrant.html"}
{"id": "749e62ef222c-1", "text": "try:\n            from qdrant_client.http import models as rest\n        except ImportError as e:\n            raise ImportError(\n                \"Cannot import qdrant_client. Please install with `pip install \"\n                \"qdrant-client`.\"\n            ) from e\n        self._validate_func(comparison.comparator)\n        attribute = self.metadata_key + \".\" + comparison.attribute\n        if comparison.comparator == Comparator.EQ:\n            return rest.FieldCondition(\n                key=attribute, match=rest.MatchValue(value=comparison.value)\n            )\n        kwargs = {comparison.comparator.value: comparison.value}\n        return rest.FieldCondition(key=attribute, range=rest.Range(**kwargs))\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, dict]:\n        try:\n            from qdrant_client.http import models as rest\n        except ImportError as e:\n            raise ImportError(\n                \"Cannot import qdrant_client. Please install with `pip install \"\n                \"qdrant-client`.\"\n            ) from e\n        if structured_query.filter is None:\n            kwargs = {}\n        else:\n            filter = structured_query.filter.accept(self)\n            if isinstance(filter, rest.FieldCondition):\n                filter = rest.Filter(must=[filter])\n            kwargs = {\"filter\": filter}\n        return structured_query.query, kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/qdrant.html"}
{"id": "d35b2231bd3e-0", "text": "Source code for langchain.retrievers.self_query.dashvector\n\"\"\"Logic for converting internal query language to a valid DashVector query.\"\"\"\nfrom typing import Tuple, Union\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\n[docs]class DashvectorTranslator(Visitor):\n    \"\"\"Logic for converting internal query language elements to valid filters.\"\"\"\n    allowed_operators = [Operator.AND, Operator.OR]\n    allowed_comparators = [\n        Comparator.EQ,\n        Comparator.GT,\n        Comparator.GTE,\n        Comparator.LT,\n        Comparator.LTE,\n        Comparator.LIKE,\n    ]\n    map_dict = {\n        Operator.AND: \" AND \",\n        Operator.OR: \" OR \",\n        Comparator.EQ: \" = \",\n        Comparator.GT: \" > \",\n        Comparator.GTE: \" >= \",\n        Comparator.LT: \" < \",\n        Comparator.LTE: \" <= \",\n        Comparator.LIKE: \" LIKE \",\n    }\n    def _format_func(self, func: Union[Operator, Comparator]) -> str:\n        self._validate_func(func)\n        return self.map_dict[func]\n[docs]    def visit_operation(self, operation: Operation) -> str:\n        args = [arg.accept(self) for arg in operation.arguments]\n        return self._format_func(operation.operator).join(args)\n[docs]    def visit_comparison(self, comparison: Comparison) -> str:\n        value = comparison.value\n        if isinstance(value, str):\n            if comparison.comparator == Comparator.LIKE:\n                value = f\"'%{value}%'\"\n            else:\n                value = f\"'{value}'\"\n        return (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/dashvector.html"}
{"id": "d35b2231bd3e-1", "text": "else:\n                value = f\"'{value}'\"\n        return (\n            f\"{comparison.attribute}{self._format_func(comparison.comparator)}{value}\"\n        )\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, dict]:\n        if structured_query.filter is None:\n            kwargs = {}\n        else:\n            kwargs = {\"filter\": structured_query.filter.accept(self)}\n        return structured_query.query, kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/dashvector.html"}
{"id": "66a0fc0c6533-0", "text": "Source code for langchain.retrievers.self_query.supabase\nfrom typing import Any, Dict, Tuple\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\n[docs]class SupabaseVectorTranslator(Visitor):\n    \"\"\"Translate Langchain filters to Supabase PostgREST filters.\"\"\"\n    allowed_operators = [Operator.AND, Operator.OR]\n    \"\"\"Subset of allowed logical operators.\"\"\"\n    allowed_comparators = [\n        Comparator.EQ,\n        Comparator.NE,\n        Comparator.GT,\n        Comparator.GTE,\n        Comparator.LT,\n        Comparator.LTE,\n        Comparator.LIKE,\n    ]\n    \"\"\"Subset of allowed logical comparators.\"\"\"\n    metadata_column = \"metadata\"\n    def _map_comparator(self, comparator: Comparator) -> str:\n        \"\"\"\n        Maps Langchain comparator to PostgREST comparator:\n        https://postgrest.org/en/stable/references/api/tables_views.html#operators\n        \"\"\"\n        postgrest_comparator = {\n            Comparator.EQ: \"eq\",\n            Comparator.NE: \"neq\",\n            Comparator.GT: \"gt\",\n            Comparator.GTE: \"gte\",\n            Comparator.LT: \"lt\",\n            Comparator.LTE: \"lte\",\n            Comparator.LIKE: \"like\",\n        }.get(comparator)\n        if postgrest_comparator is None:\n            raise Exception(\n                f\"Comparator '{comparator}' is not currently \"\n                \"supported in Supabase Vector\"\n            )\n        return postgrest_comparator\n    def _get_json_operator(self, value: Any) -> str:\n        if isinstance(value, str):\n            return \"->>\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/supabase.html"}
{"id": "66a0fc0c6533-1", "text": "if isinstance(value, str):\n            return \"->>\"\n        else:\n            return \"->\"\n[docs]    def visit_operation(self, operation: Operation) -> str:\n        args = [arg.accept(self) for arg in operation.arguments]\n        return f\"{operation.operator.value}({','.join(args)})\"\n[docs]    def visit_comparison(self, comparison: Comparison) -> str:\n        if isinstance(comparison.value, list):\n            return self.visit_operation(\n                Operation(\n                    operator=Operator.AND,\n                    arguments=(\n                        Comparison(\n                            comparator=comparison.comparator,\n                            attribute=comparison.attribute,\n                            value=value,\n                        )\n                        for value in comparison.value\n                    ),\n                )\n            )\n        return \".\".join(\n            [\n                f\"{self.metadata_column}{self._get_json_operator(comparison.value)}{comparison.attribute}\",\n                f\"{self._map_comparator(comparison.comparator)}\",\n                f\"{comparison.value}\",\n            ]\n        )\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, Dict[str, str]]:\n        if structured_query.filter is None:\n            kwargs = {}\n        else:\n            kwargs = {\"postgrest_filter\": structured_query.filter.accept(self)}\n        return structured_query.query, kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/supabase.html"}
{"id": "79b3672dee4e-0", "text": "Source code for langchain.retrievers.self_query.timescalevector\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Tuple, Union\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\nif TYPE_CHECKING:\n    from timescale_vector import client\n[docs]class TimescaleVectorTranslator(Visitor):\n    \"\"\"Translate the internal query language elements to valid filters.\"\"\"\n    allowed_operators = [Operator.AND, Operator.OR, Operator.NOT]\n    \"\"\"Subset of allowed logical operators.\"\"\"\n    allowed_comparators = [\n        Comparator.EQ,\n        Comparator.GT,\n        Comparator.GTE,\n        Comparator.LT,\n        Comparator.LTE,\n    ]\n    COMPARATOR_MAP = {\n        Comparator.EQ: \"==\",\n        Comparator.GT: \">\",\n        Comparator.GTE: \">=\",\n        Comparator.LT: \"<\",\n        Comparator.LTE: \"<=\",\n    }\n    OPERATOR_MAP = {Operator.AND: \"AND\", Operator.OR: \"OR\", Operator.NOT: \"NOT\"}\n    def _format_func(self, func: Union[Operator, Comparator]) -> str:\n        self._validate_func(func)\n        if isinstance(func, Operator):\n            value = self.OPERATOR_MAP[func.value]  # type: ignore\n        elif isinstance(func, Comparator):\n            value = self.COMPARATOR_MAP[func.value]  # type: ignore\n        return f\"{value}\"\n[docs]    def visit_operation(self, operation: Operation) -> client.Predicates:\n        try:\n            from timescale_vector import client\n        except ImportError as e:\n            raise ImportError(\n                \"Cannot import timescale-vector. Please install with `pip install \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/timescalevector.html"}
{"id": "79b3672dee4e-1", "text": "\"Cannot import timescale-vector. Please install with `pip install \"\n                \"timescale-vector`.\"\n            ) from e\n        args = [arg.accept(self) for arg in operation.arguments]\n        return client.Predicates(*args, operator=self._format_func(operation.operator))\n[docs]    def visit_comparison(self, comparison: Comparison) -> client.Predicates:\n        try:\n            from timescale_vector import client\n        except ImportError as e:\n            raise ImportError(\n                \"Cannot import timescale-vector. Please install with `pip install \"\n                \"timescale-vector`.\"\n            ) from e\n        return client.Predicates(\n            (\n                comparison.attribute,\n                self._format_func(comparison.comparator),\n                comparison.value,\n            )\n        )\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, dict]:\n        if structured_query.filter is None:\n            kwargs = {}\n        else:\n            kwargs = {\"predicates\": structured_query.filter.accept(self)}\n        return structured_query.query, kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/timescalevector.html"}
{"id": "7cd8f0df84ec-0", "text": "Source code for langchain.retrievers.self_query.opensearch\nfrom typing import Dict, Tuple, Union\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\n[docs]class OpenSearchTranslator(Visitor):\n    \"\"\"Translate `OpenSearch` internal query domain-specific\n    language elements to valid filters.\"\"\"\n    allowed_comparators = [\n        Comparator.EQ,\n        Comparator.LT,\n        Comparator.LTE,\n        Comparator.GT,\n        Comparator.GTE,\n        Comparator.CONTAIN,\n        Comparator.LIKE,\n    ]\n    \"\"\"Subset of allowed logical comparators.\"\"\"\n    allowed_operators = [Operator.AND, Operator.OR, Operator.NOT]\n    \"\"\"Subset of allowed logical operators.\"\"\"\n    def _format_func(self, func: Union[Operator, Comparator]) -> str:\n        self._validate_func(func)\n        comp_operator_map = {\n            Comparator.EQ: \"term\",\n            Comparator.LT: \"lt\",\n            Comparator.LTE: \"lte\",\n            Comparator.GT: \"gt\",\n            Comparator.GTE: \"gte\",\n            Comparator.CONTAIN: \"match\",\n            Comparator.LIKE: \"fuzzy\",\n            Operator.AND: \"must\",\n            Operator.OR: \"should\",\n            Operator.NOT: \"must_not\",\n        }\n        return comp_operator_map[func]\n[docs]    def visit_operation(self, operation: Operation) -> Dict:\n        args = [arg.accept(self) for arg in operation.arguments]\n        return {\"bool\": {self._format_func(operation.operator): args}}\n[docs]    def visit_comparison(self, comparison: Comparison) -> Dict:\n        field = f\"metadata.{comparison.attribute}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/opensearch.html"}
{"id": "7cd8f0df84ec-1", "text": "field = f\"metadata.{comparison.attribute}\"\n        if comparison.comparator in [\n            Comparator.LT,\n            Comparator.LTE,\n            Comparator.GT,\n            Comparator.GTE,\n        ]:\n            return {\n                \"range\": {\n                    field: {self._format_func(comparison.comparator): comparison.value}\n                }\n            }\n        if comparison.comparator == Comparator.LIKE:\n            return {\n                self._format_func(comparison.comparator): {\n                    field: {\"value\": comparison.value}\n                }\n            }\n        field = f\"{field}.keyword\" if isinstance(comparison.value, str) else field\n        return {self._format_func(comparison.comparator): {field: comparison.value}}\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, dict]:\n        if structured_query.filter is None:\n            kwargs = {}\n        else:\n            kwargs = {\"filter\": structured_query.filter.accept(self)}\n        return structured_query.query, kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/opensearch.html"}
{"id": "7a7f0b1bc25e-0", "text": "Source code for langchain.retrievers.self_query.base\n\"\"\"Retriever that generates and executes structured queries over its own data source.\"\"\"\nimport logging\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.chains.query_constructor.base import load_query_constructor_runnable\nfrom langchain.chains.query_constructor.ir import StructuredQuery, Visitor\nfrom langchain.chains.query_constructor.schema import AttributeInfo\nfrom langchain.pydantic_v1 import BaseModel, Field, root_validator\nfrom langchain.retrievers.self_query.chroma import ChromaTranslator\nfrom langchain.retrievers.self_query.dashvector import DashvectorTranslator\nfrom langchain.retrievers.self_query.deeplake import DeepLakeTranslator\nfrom langchain.retrievers.self_query.elasticsearch import ElasticsearchTranslator\nfrom langchain.retrievers.self_query.milvus import MilvusTranslator\nfrom langchain.retrievers.self_query.myscale import MyScaleTranslator\nfrom langchain.retrievers.self_query.opensearch import OpenSearchTranslator\nfrom langchain.retrievers.self_query.pinecone import PineconeTranslator\nfrom langchain.retrievers.self_query.qdrant import QdrantTranslator\nfrom langchain.retrievers.self_query.redis import RedisTranslator\nfrom langchain.retrievers.self_query.supabase import SupabaseVectorTranslator\nfrom langchain.retrievers.self_query.timescalevector import TimescaleVectorTranslator\nfrom langchain.retrievers.self_query.vectara import VectaraTranslator\nfrom langchain.retrievers.self_query.weaviate import WeaviateTranslator\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.runnable import Runnable", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html"}
{"id": "7a7f0b1bc25e-1", "text": "from langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.runnable import Runnable\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores import (\n    Chroma,\n    DashVector,\n    DeepLake,\n    ElasticsearchStore,\n    Milvus,\n    MyScale,\n    OpenSearchVectorSearch,\n    Pinecone,\n    Qdrant,\n    Redis,\n    SupabaseVectorStore,\n    TimescaleVector,\n    Vectara,\n    Weaviate,\n)\nlogger = logging.getLogger(__name__)\ndef _get_builtin_translator(vectorstore: VectorStore) -> Visitor:\n    \"\"\"Get the translator class corresponding to the vector store class.\"\"\"\n    BUILTIN_TRANSLATORS: Dict[Type[VectorStore], Type[Visitor]] = {\n        Pinecone: PineconeTranslator,\n        Chroma: ChromaTranslator,\n        DashVector: DashvectorTranslator,\n        Weaviate: WeaviateTranslator,\n        Vectara: VectaraTranslator,\n        Qdrant: QdrantTranslator,\n        MyScale: MyScaleTranslator,\n        DeepLake: DeepLakeTranslator,\n        ElasticsearchStore: ElasticsearchTranslator,\n        Milvus: MilvusTranslator,\n        SupabaseVectorStore: SupabaseVectorTranslator,\n        TimescaleVector: TimescaleVectorTranslator,\n        OpenSearchVectorSearch: OpenSearchTranslator,\n    }\n    if isinstance(vectorstore, Qdrant):\n        return QdrantTranslator(metadata_key=vectorstore.metadata_payload_key)\n    elif isinstance(vectorstore, MyScale):\n        return MyScaleTranslator(metadata_key=vectorstore.metadata_column)\n    elif isinstance(vectorstore, Redis):\n        return RedisTranslator.from_vectorstore(vectorstore)\n    elif vectorstore.__class__ in BUILTIN_TRANSLATORS:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html"}
{"id": "7a7f0b1bc25e-2", "text": "elif vectorstore.__class__ in BUILTIN_TRANSLATORS:\n        return BUILTIN_TRANSLATORS[vectorstore.__class__]()\n    else:\n        raise ValueError(\n            f\"Self query retriever with Vector Store type {vectorstore.__class__}\"\n            f\" not supported.\"\n        )\n[docs]class SelfQueryRetriever(BaseRetriever, BaseModel):\n    \"\"\"Retriever that uses a vector store and an LLM to generate\n    the vector store queries.\"\"\"\n    vectorstore: VectorStore\n    \"\"\"The underlying vector store from which documents will be retrieved.\"\"\"\n    query_constructor: Runnable[dict, StructuredQuery] = Field(alias=\"llm_chain\")\n    \"\"\"The query constructor chain for generating the vector store queries.\n    \n    llm_chain is legacy name kept for backwards compatibility.\"\"\"\n    search_type: str = \"similarity\"\n    \"\"\"The search type to perform on the vector store.\"\"\"\n    search_kwargs: dict = Field(default_factory=dict)\n    \"\"\"Keyword arguments to pass in to the vector store search.\"\"\"\n    structured_query_translator: Visitor\n    \"\"\"Translator for turning internal query language into vectorstore search params.\"\"\"\n    verbose: bool = False\n    use_original_query: bool = False\n    \"\"\"Use original query instead of the revised new query from LLM\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n        allow_population_by_field_name = True\n    @root_validator(pre=True)\n    def validate_translator(cls, values: Dict) -> Dict:\n        \"\"\"Validate translator.\"\"\"\n        if \"structured_query_translator\" not in values:\n            values[\"structured_query_translator\"] = _get_builtin_translator(\n                values[\"vectorstore\"]\n            )\n        return values\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html"}
{"id": "7a7f0b1bc25e-3", "text": "values[\"vectorstore\"]\n            )\n        return values\n    @property\n    def llm_chain(self) -> Runnable:\n        \"\"\"llm_chain is legacy name kept for backwards compatibility.\"\"\"\n        return self.query_constructor\n    def _prepare_query(\n        self, query: str, structured_query: StructuredQuery\n    ) -> Tuple[str, Dict[str, Any]]:\n        new_query, new_kwargs = self.structured_query_translator.visit_structured_query(\n            structured_query\n        )\n        if structured_query.limit is not None:\n            new_kwargs[\"k\"] = structured_query.limit\n        if self.use_original_query:\n            new_query = query\n        search_kwargs = {**self.search_kwargs, **new_kwargs}\n        return new_query, search_kwargs\n    def _get_docs_with_query(\n        self, query: str, search_kwargs: Dict[str, Any]\n    ) -> List[Document]:\n        docs = self.vectorstore.search(query, self.search_type, **search_kwargs)\n        return docs\n    async def _aget_docs_with_query(\n        self, query: str, search_kwargs: Dict[str, Any]\n    ) -> List[Document]:\n        docs = await self.vectorstore.asearch(query, self.search_type, **search_kwargs)\n        return docs\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"Get documents relevant for a query.\n        Args:\n            query: string to find relevant documents for\n        Returns:\n            List of relevant documents\n        \"\"\"\n        structured_query = self.query_constructor.invoke(\n            {\"query\": query}, config={\"callbacks\": run_manager.get_child()}\n        )\n        if self.verbose:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html"}
{"id": "7a7f0b1bc25e-4", "text": ")\n        if self.verbose:\n            logger.info(f\"Generated Query: {structured_query}\")\n        new_query, search_kwargs = self._prepare_query(query, structured_query)\n        docs = self._get_docs_with_query(new_query, search_kwargs)\n        return docs\n    async def _aget_relevant_documents(\n        self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"Get documents relevant for a query.\n        Args:\n            query: string to find relevant documents for\n        Returns:\n            List of relevant documents\n        \"\"\"\n        structured_query = await self.query_constructor.ainvoke(\n            {\"query\": query}, config={\"callbacks\": run_manager.get_child()}\n        )\n        if self.verbose:\n            logger.info(f\"Generated Query: {structured_query}\")\n        new_query, search_kwargs = self._prepare_query(query, structured_query)\n        docs = await self._aget_docs_with_query(new_query, search_kwargs)\n        return docs\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        vectorstore: VectorStore,\n        document_contents: str,\n        metadata_field_info: Sequence[Union[AttributeInfo, dict]],\n        structured_query_translator: Optional[Visitor] = None,\n        chain_kwargs: Optional[Dict] = None,\n        enable_limit: bool = False,\n        use_original_query: bool = False,\n        **kwargs: Any,\n    ) -> \"SelfQueryRetriever\":\n        if structured_query_translator is None:\n            structured_query_translator = _get_builtin_translator(vectorstore)\n        chain_kwargs = chain_kwargs or {}\n        if (\n            \"allowed_comparators\" not in chain_kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html"}
{"id": "7a7f0b1bc25e-5", "text": "if (\n            \"allowed_comparators\" not in chain_kwargs\n            and structured_query_translator.allowed_comparators is not None\n        ):\n            chain_kwargs[\n                \"allowed_comparators\"\n            ] = structured_query_translator.allowed_comparators\n        if (\n            \"allowed_operators\" not in chain_kwargs\n            and structured_query_translator.allowed_operators is not None\n        ):\n            chain_kwargs[\n                \"allowed_operators\"\n            ] = structured_query_translator.allowed_operators\n        query_constructor = load_query_constructor_runnable(\n            llm,\n            document_contents,\n            metadata_field_info,\n            enable_limit=enable_limit,\n            **chain_kwargs,\n        )\n        return cls(\n            query_constructor=query_constructor,\n            vectorstore=vectorstore,\n            use_original_query=use_original_query,\n            structured_query_translator=structured_query_translator,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html"}
{"id": "f653d616933a-0", "text": "Source code for langchain.retrievers.self_query.myscale\nimport re\nfrom typing import Any, Callable, Dict, Tuple\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\ndef _DEFAULT_COMPOSER(op_name: str) -> Callable:\n    \"\"\"\n    Default composer for logical operators.\n    Args:\n        op_name: Name of the operator.\n    Returns:\n        Callable that takes a list of arguments and returns a string.\n    \"\"\"\n    def f(*args: Any) -> str:\n        args_: map[str] = map(str, args)\n        return f\" {op_name} \".join(args_)\n    return f\ndef _FUNCTION_COMPOSER(op_name: str) -> Callable:\n    \"\"\"\n    Composer for functions.\n    Args:\n        op_name: Name of the function.\n    Returns:\n        Callable that takes a list of arguments and returns a string.\n    \"\"\"\n    def f(*args: Any) -> str:\n        args_: map[str] = map(str, args)\n        return f\"{op_name}({','.join(args_)})\"\n    return f\n[docs]class MyScaleTranslator(Visitor):\n    \"\"\"Translate `MyScale` internal query language elements to valid filters.\"\"\"\n    allowed_operators = [Operator.AND, Operator.OR, Operator.NOT]\n    \"\"\"Subset of allowed logical operators.\"\"\"\n    allowed_comparators = [\n        Comparator.EQ,\n        Comparator.GT,\n        Comparator.GTE,\n        Comparator.LT,\n        Comparator.LTE,\n        Comparator.CONTAIN,\n        Comparator.LIKE,\n    ]\n    map_dict = {\n        Operator.AND: _DEFAULT_COMPOSER(\"AND\"),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html"}
{"id": "f653d616933a-1", "text": "map_dict = {\n        Operator.AND: _DEFAULT_COMPOSER(\"AND\"),\n        Operator.OR: _DEFAULT_COMPOSER(\"OR\"),\n        Operator.NOT: _DEFAULT_COMPOSER(\"NOT\"),\n        Comparator.EQ: _DEFAULT_COMPOSER(\"=\"),\n        Comparator.GT: _DEFAULT_COMPOSER(\">\"),\n        Comparator.GTE: _DEFAULT_COMPOSER(\">=\"),\n        Comparator.LT: _DEFAULT_COMPOSER(\"<\"),\n        Comparator.LTE: _DEFAULT_COMPOSER(\"<=\"),\n        Comparator.CONTAIN: _FUNCTION_COMPOSER(\"has\"),\n        Comparator.LIKE: _DEFAULT_COMPOSER(\"ILIKE\"),\n    }\n[docs]    def __init__(self, metadata_key: str = \"metadata\") -> None:\n        super().__init__()\n        self.metadata_key = metadata_key\n[docs]    def visit_operation(self, operation: Operation) -> Dict:\n        args = [arg.accept(self) for arg in operation.arguments]\n        func = operation.operator\n        self._validate_func(func)\n        return self.map_dict[func](*args)\n[docs]    def visit_comparison(self, comparison: Comparison) -> Dict:\n        regex = r\"\\((.*?)\\)\"\n        matched = re.search(r\"\\(\\w+\\)\", comparison.attribute)\n        # If arbitrary function is applied to an attribute\n        if matched:\n            attr = re.sub(\n                regex,\n                f\"({self.metadata_key}.{matched.group(0)[1:-1]})\",\n                comparison.attribute,\n            )\n        else:\n            attr = f\"{self.metadata_key}.{comparison.attribute}\"\n        value = comparison.value\n        comp = comparison.comparator\n        value = f\"'{value}'\" if isinstance(value, str) else value\n        # convert timestamp for datetime objects", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html"}
{"id": "f653d616933a-2", "text": "# convert timestamp for datetime objects\n        if isinstance(value, dict) and value.get(\"type\") == \"date\":\n            attr = f\"parseDateTime32BestEffort({attr})\"\n            value = f\"parseDateTime32BestEffort('{value['date']}')\"\n        # string pattern match\n        if comp is Comparator.LIKE:\n            value = f\"'%{value[1:-1]}%'\"\n        return self.map_dict[comp](attr, value)\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, dict]:\n        print(structured_query)\n        if structured_query.filter is None:\n            kwargs = {}\n        else:\n            kwargs = {\"where_str\": structured_query.filter.accept(self)}\n        return structured_query.query, kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html"}
{"id": "3cc6ed280451-0", "text": "Source code for langchain.retrievers.self_query.deeplake\n\"\"\"Logic for converting internal query language to a valid Chroma query.\"\"\"\nfrom typing import Tuple, Union\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\nCOMPARATOR_TO_TQL = {\n    Comparator.EQ: \"==\",\n    Comparator.GT: \">\",\n    Comparator.GTE: \">=\",\n    Comparator.LT: \"<\",\n    Comparator.LTE: \"<=\",\n}\nOPERATOR_TO_TQL = {\n    Operator.AND: \"and\",\n    Operator.OR: \"or\",\n    Operator.NOT: \"NOT\",\n}\n[docs]def can_cast_to_float(string: str) -> bool:\n    \"\"\"Check if a string can be cast to a float.\"\"\"\n    try:\n        float(string)\n        return True\n    except ValueError:\n        return False\n[docs]class DeepLakeTranslator(Visitor):\n    \"\"\"Translate `DeepLake` internal query language elements to valid filters.\"\"\"\n    allowed_operators = [Operator.AND, Operator.OR, Operator.NOT]\n    \"\"\"Subset of allowed logical operators.\"\"\"\n    allowed_comparators = [\n        Comparator.EQ,\n        Comparator.GT,\n        Comparator.GTE,\n        Comparator.LT,\n        Comparator.LTE,\n    ]\n    \"\"\"Subset of allowed logical comparators.\"\"\"\n    def _format_func(self, func: Union[Operator, Comparator]) -> str:\n        self._validate_func(func)\n        if isinstance(func, Operator):\n            value = OPERATOR_TO_TQL[func.value]  # type: ignore\n        elif isinstance(func, Comparator):\n            value = COMPARATOR_TO_TQL[func.value]  # type: ignore", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/deeplake.html"}
{"id": "3cc6ed280451-1", "text": "value = COMPARATOR_TO_TQL[func.value]  # type: ignore\n        return f\"{value}\"\n[docs]    def visit_operation(self, operation: Operation) -> str:\n        args = [arg.accept(self) for arg in operation.arguments]\n        operator = self._format_func(operation.operator)\n        return \"(\" + (\" \" + operator + \" \").join(args) + \")\"\n[docs]    def visit_comparison(self, comparison: Comparison) -> str:\n        comparator = self._format_func(comparison.comparator)\n        values = comparison.value\n        if isinstance(values, list):\n            tql = []\n            for value in values:\n                comparison.value = value\n                tql.append(self.visit_comparison(comparison))\n            return \"(\" + (\" or \").join(tql) + \")\"\n        if not can_cast_to_float(comparison.value):\n            values = f\"'{values}'\"\n        return f\"metadata['{comparison.attribute}'] {comparator} {values}\"\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, dict]:\n        if structured_query.filter is None:\n            kwargs = {}\n        else:\n            tqL = f\"SELECT * WHERE {structured_query.filter.accept(self)}\"\n            kwargs = {\"tql\": tqL}\n        return structured_query.query, kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/deeplake.html"}
{"id": "f467654fbf8c-0", "text": "Source code for langchain.retrievers.self_query.pinecone\nfrom typing import Dict, Tuple, Union\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\n[docs]class PineconeTranslator(Visitor):\n    \"\"\"Translate `Pinecone` internal query language elements to valid filters.\"\"\"\n    allowed_comparators = (\n        Comparator.EQ,\n        Comparator.NE,\n        Comparator.LT,\n        Comparator.LTE,\n        Comparator.GT,\n        Comparator.GTE,\n        Comparator.IN,\n        Comparator.NIN,\n    )\n    \"\"\"Subset of allowed logical comparators.\"\"\"\n    allowed_operators = (Operator.AND, Operator.OR)\n    \"\"\"Subset of allowed logical operators.\"\"\"\n    def _format_func(self, func: Union[Operator, Comparator]) -> str:\n        self._validate_func(func)\n        return f\"${func.value}\"\n[docs]    def visit_operation(self, operation: Operation) -> Dict:\n        args = [arg.accept(self) for arg in operation.arguments]\n        return {self._format_func(operation.operator): args}\n[docs]    def visit_comparison(self, comparison: Comparison) -> Dict:\n        if comparison.comparator in (Comparator.IN, Comparator.NIN) and not isinstance(\n            comparison.value, list\n        ):\n            comparison.value = [comparison.value]\n        return {\n            comparison.attribute: {\n                self._format_func(comparison.comparator): comparison.value\n            }\n        }\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, dict]:\n        if structured_query.filter is None:\n            kwargs = {}\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/pinecone.html"}
{"id": "f467654fbf8c-1", "text": "if structured_query.filter is None:\n            kwargs = {}\n        else:\n            kwargs = {\"filter\": structured_query.filter.accept(self)}\n        return structured_query.query, kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/pinecone.html"}
{"id": "78f55be927d5-0", "text": "Source code for langchain.retrievers.self_query.elasticsearch\nfrom typing import Dict, Tuple, Union\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\n[docs]class ElasticsearchTranslator(Visitor):\n    \"\"\"Translate `Elasticsearch` internal query language elements to valid filters.\"\"\"\n    allowed_comparators = [\n        Comparator.EQ,\n        Comparator.GT,\n        Comparator.GTE,\n        Comparator.LT,\n        Comparator.LTE,\n        Comparator.CONTAIN,\n        Comparator.LIKE,\n    ]\n    \"\"\"Subset of allowed logical comparators.\"\"\"\n    allowed_operators = [Operator.AND, Operator.OR, Operator.NOT]\n    \"\"\"Subset of allowed logical operators.\"\"\"\n    def _format_func(self, func: Union[Operator, Comparator]) -> str:\n        self._validate_func(func)\n        map_dict = {\n            Operator.OR: \"should\",\n            Operator.NOT: \"must_not\",\n            Operator.AND: \"must\",\n            Comparator.EQ: \"term\",\n            Comparator.GT: \"gt\",\n            Comparator.GTE: \"gte\",\n            Comparator.LT: \"lt\",\n            Comparator.LTE: \"lte\",\n            Comparator.CONTAIN: \"match\",\n            Comparator.LIKE: \"match\",\n        }\n        return map_dict[func]\n[docs]    def visit_operation(self, operation: Operation) -> Dict:\n        args = [arg.accept(self) for arg in operation.arguments]\n        return {\"bool\": {self._format_func(operation.operator): args}}\n[docs]    def visit_comparison(self, comparison: Comparison) -> Dict:\n        # ElasticsearchStore filters require to target\n        # the metadata object field\n        field = f\"metadata.{comparison.attribute}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/elasticsearch.html"}
{"id": "78f55be927d5-1", "text": "# the metadata object field\n        field = f\"metadata.{comparison.attribute}\"\n        is_range_comparator = comparison.comparator in [\n            Comparator.GT,\n            Comparator.GTE,\n            Comparator.LT,\n            Comparator.LTE,\n        ]\n        if is_range_comparator:\n            return {\n                \"range\": {\n                    field: {self._format_func(comparison.comparator): comparison.value}\n                }\n            }\n        if comparison.comparator == Comparator.CONTAIN:\n            return {\n                self._format_func(comparison.comparator): {\n                    field: {\"query\": comparison.value}\n                }\n            }\n        if comparison.comparator == Comparator.LIKE:\n            return {\n                self._format_func(comparison.comparator): {\n                    field: {\"query\": comparison.value, \"fuzziness\": \"AUTO\"}\n                }\n            }\n        # we assume that if the value is a string,\n        # we want to use the keyword field\n        field = f\"{field}.keyword\" if isinstance(comparison.value, str) else field\n        return {self._format_func(comparison.comparator): {field: comparison.value}}\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, dict]:\n        if structured_query.filter is None:\n            kwargs = {}\n        else:\n            kwargs = {\"filter\": [structured_query.filter.accept(self)]}\n        return structured_query.query, kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/elasticsearch.html"}
{"id": "7481770f3ff7-0", "text": "Source code for langchain.retrievers.self_query.milvus\n\"\"\"Logic for converting internal query language to a valid Milvus query.\"\"\"\nfrom typing import Tuple, Union\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\nCOMPARATOR_TO_BER = {\n    Comparator.EQ: \"==\",\n    Comparator.GT: \">\",\n    Comparator.GTE: \">=\",\n    Comparator.LT: \"<\",\n    Comparator.LTE: \"<=\",\n}\nUNARY_OPERATORS = [Operator.NOT]\n[docs]def process_value(value: Union[int, float, str]) -> str:\n    \"\"\"Convert a value to a string and add double quotes if it is a string.\n    It required for comparators involving strings.\n    Args:\n        value: The value to convert.\n    Returns:\n        The converted value as a string.\n    \"\"\"\n    #\n    if isinstance(value, str):\n        # If the value is already a string, add double quotes\n        return f'\"{value}\"'\n    else:\n        # If the valueis not a string, convert it to a string without double quotes\n        return str(value)\n[docs]class MilvusTranslator(Visitor):\n    \"\"\"Translate Milvus internal query language elements to valid filters.\"\"\"\n    \"\"\"Subset of allowed logical operators.\"\"\"\n    allowed_operators = [Operator.AND, Operator.NOT, Operator.OR]\n    \"\"\"Subset of allowed logical comparators.\"\"\"\n    allowed_comparators = [\n        Comparator.EQ,\n        Comparator.GT,\n        Comparator.GTE,\n        Comparator.LT,\n        Comparator.LTE,\n    ]\n    def _format_func(self, func: Union[Operator, Comparator]) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/milvus.html"}
{"id": "7481770f3ff7-1", "text": "def _format_func(self, func: Union[Operator, Comparator]) -> str:\n        self._validate_func(func)\n        value = func.value\n        if isinstance(func, Comparator):\n            value = COMPARATOR_TO_BER[func]\n        return f\"{value}\"\n[docs]    def visit_operation(self, operation: Operation) -> str:\n        if operation.operator in UNARY_OPERATORS and len(operation.arguments) == 1:\n            operator = self._format_func(operation.operator)\n            return operator + \"(\" + operation.arguments[0].accept(self) + \")\"\n        elif operation.operator in UNARY_OPERATORS:\n            raise ValueError(\n                f'\"{operation.operator.value}\" can have only one argument in Milvus'\n            )\n        else:\n            args = [arg.accept(self) for arg in operation.arguments]\n            operator = self._format_func(operation.operator)\n            return \"(\" + (\" \" + operator + \" \").join(args) + \")\"\n[docs]    def visit_comparison(self, comparison: Comparison) -> str:\n        comparator = self._format_func(comparison.comparator)\n        processed_value = process_value(comparison.value)\n        attribute = comparison.attribute\n        return \"( \" + attribute + \" \" + comparator + \" \" + processed_value + \" )\"\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, dict]:\n        if structured_query.filter is None:\n            kwargs = {}\n        else:\n            kwargs = {\"expr\": structured_query.filter.accept(self)}\n        return structured_query.query, kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/milvus.html"}
{"id": "ba55fef2c0b2-0", "text": "Source code for langchain.retrievers.self_query.redis\nfrom __future__ import annotations\nfrom typing import Any, Tuple\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\nfrom langchain.vectorstores.redis import Redis\nfrom langchain.vectorstores.redis.filters import (\n    RedisFilterExpression,\n    RedisFilterField,\n    RedisFilterOperator,\n    RedisNum,\n    RedisTag,\n    RedisText,\n)\nfrom langchain.vectorstores.redis.schema import RedisModel\n_COMPARATOR_TO_BUILTIN_METHOD = {\n    Comparator.EQ: \"__eq__\",\n    Comparator.NE: \"__ne__\",\n    Comparator.LT: \"__lt__\",\n    Comparator.GT: \"__gt__\",\n    Comparator.LTE: \"__le__\",\n    Comparator.GTE: \"__ge__\",\n    Comparator.CONTAIN: \"__eq__\",\n    Comparator.LIKE: \"__mod__\",\n}\n[docs]class RedisTranslator(Visitor):\n    \"\"\"Translate\"\"\"\n    allowed_comparators = (\n        Comparator.EQ,\n        Comparator.NE,\n        Comparator.LT,\n        Comparator.LTE,\n        Comparator.GT,\n        Comparator.GTE,\n        Comparator.CONTAIN,\n        Comparator.LIKE,\n    )\n    \"\"\"Subset of allowed logical comparators.\"\"\"\n    allowed_operators = (Operator.AND, Operator.OR)\n    \"\"\"Subset of allowed logical operators.\"\"\"\n[docs]    def __init__(self, schema: RedisModel) -> None:\n        self._schema = schema\n    def _attribute_to_filter_field(self, attribute: str) -> RedisFilterField:\n        if attribute in [tf.name for tf in self._schema.text]:\n            return RedisText(attribute)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/redis.html"}
{"id": "ba55fef2c0b2-1", "text": "return RedisText(attribute)\n        elif attribute in [tf.name for tf in self._schema.tag or []]:\n            return RedisTag(attribute)\n        elif attribute in [tf.name for tf in self._schema.numeric or []]:\n            return RedisNum(attribute)\n        else:\n            raise ValueError(\n                f\"Invalid attribute {attribute} not in vector store schema. Schema is:\"\n                f\"\\n{self._schema.as_dict()}\"\n            )\n[docs]    def visit_comparison(self, comparison: Comparison) -> RedisFilterExpression:\n        filter_field = self._attribute_to_filter_field(comparison.attribute)\n        comparison_method = _COMPARATOR_TO_BUILTIN_METHOD[comparison.comparator]\n        return getattr(filter_field, comparison_method)(comparison.value)\n[docs]    def visit_operation(self, operation: Operation) -> Any:\n        left = operation.arguments[0].accept(self)\n        if len(operation.arguments) > 2:\n            right = self.visit_operation(\n                Operation(\n                    operator=operation.operator, arguments=operation.arguments[1:]\n                )\n            )\n        else:\n            right = operation.arguments[1].accept(self)\n        redis_operator = (\n            RedisFilterOperator.OR\n            if operation.operator == Operator.OR\n            else RedisFilterOperator.AND\n        )\n        return RedisFilterExpression(operator=redis_operator, left=left, right=right)\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, dict]:\n        if structured_query.filter is None:\n            kwargs = {}\n        else:\n            kwargs = {\"filter\": structured_query.filter.accept(self)}\n        return structured_query.query, kwargs\n[docs]    @classmethod\n    def from_vectorstore(cls, vectorstore: Redis) -> RedisTranslator:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/redis.html"}
{"id": "ba55fef2c0b2-2", "text": "def from_vectorstore(cls, vectorstore: Redis) -> RedisTranslator:\n        return cls(vectorstore._schema)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/redis.html"}
{"id": "b2c87bfa1f34-0", "text": "Source code for langchain.retrievers.self_query.weaviate\nfrom datetime import datetime\nfrom typing import Dict, Tuple, Union\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\n[docs]class WeaviateTranslator(Visitor):\n    \"\"\"Translate `Weaviate` internal query language elements to valid filters.\"\"\"\n    allowed_operators = [Operator.AND, Operator.OR]\n    \"\"\"Subset of allowed logical operators.\"\"\"\n    allowed_comparators = [\n        Comparator.EQ,\n        Comparator.NE,\n        Comparator.GTE,\n        Comparator.LTE,\n        Comparator.LT,\n        Comparator.GT,\n    ]\n    def _format_func(self, func: Union[Operator, Comparator]) -> str:\n        self._validate_func(func)\n        # https://weaviate.io/developers/weaviate/api/graphql/filters\n        map_dict = {\n            Operator.AND: \"And\",\n            Operator.OR: \"Or\",\n            Comparator.EQ: \"Equal\",\n            Comparator.NE: \"NotEqual\",\n            Comparator.GTE: \"GreaterThanEqual\",\n            Comparator.LTE: \"LessThanEqual\",\n            Comparator.LT: \"LessThan\",\n            Comparator.GT: \"GreaterThan\",\n        }\n        return map_dict[func]\n[docs]    def visit_operation(self, operation: Operation) -> Dict:\n        args = [arg.accept(self) for arg in operation.arguments]\n        return {\"operator\": self._format_func(operation.operator), \"operands\": args}\n[docs]    def visit_comparison(self, comparison: Comparison) -> Dict:\n        value_type = \"valueText\"\n        value = comparison.value\n        if isinstance(comparison.value, bool):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/weaviate.html"}
{"id": "b2c87bfa1f34-1", "text": "value = comparison.value\n        if isinstance(comparison.value, bool):\n            value_type = \"valueBoolean\"\n        elif isinstance(comparison.value, float):\n            value_type = \"valueNumber\"\n        elif isinstance(comparison.value, int):\n            value_type = \"valueInt\"\n        elif (\n            isinstance(comparison.value, dict)\n            and comparison.value.get(\"type\") == \"date\"\n        ):\n            value_type = \"valueDate\"\n            # ISO 8601 timestamp, formatted as RFC3339\n            date = datetime.strptime(comparison.value[\"date\"], \"%Y-%m-%d\")\n            value = date.strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n        filter = {\n            \"path\": [comparison.attribute],\n            \"operator\": self._format_func(comparison.comparator),\n            value_type: value,\n        }\n        return filter\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, dict]:\n        if structured_query.filter is None:\n            kwargs = {}\n        else:\n            kwargs = {\"where_filter\": structured_query.filter.accept(self)}\n        return structured_query.query, kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/weaviate.html"}
{"id": "e2f90608eb61-0", "text": "Source code for langchain.retrievers.self_query.vectara\nfrom typing import Tuple, Union\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    Operation,\n    Operator,\n    StructuredQuery,\n    Visitor,\n)\n[docs]def process_value(value: Union[int, float, str]) -> str:\n    \"\"\"Convert a value to a string and add single quotes if it is a string.\"\"\"\n    if isinstance(value, str):\n        return f\"'{value}'\"\n    else:\n        return str(value)\n[docs]class VectaraTranslator(Visitor):\n    \"\"\"Translate `Vectara` internal query language elements to valid filters.\"\"\"\n    allowed_operators = [Operator.AND, Operator.OR]\n    \"\"\"Subset of allowed logical operators.\"\"\"\n    allowed_comparators = [\n        Comparator.EQ,\n        Comparator.NE,\n        Comparator.GT,\n        Comparator.GTE,\n        Comparator.LT,\n        Comparator.LTE,\n    ]\n    \"\"\"Subset of allowed logical comparators.\"\"\"\n    def _format_func(self, func: Union[Operator, Comparator]) -> str:\n        map_dict = {\n            Operator.AND: \" and \",\n            Operator.OR: \" or \",\n            Comparator.EQ: \"=\",\n            Comparator.NE: \"!=\",\n            Comparator.GT: \">\",\n            Comparator.GTE: \">=\",\n            Comparator.LT: \"<\",\n            Comparator.LTE: \"<=\",\n        }\n        self._validate_func(func)\n        return map_dict[func]\n[docs]    def visit_operation(self, operation: Operation) -> str:\n        args = [arg.accept(self) for arg in operation.arguments]\n        operator = self._format_func(operation.operator)\n        return \"( \" + operator.join(args) + \" )\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/vectara.html"}
{"id": "e2f90608eb61-1", "text": "return \"( \" + operator.join(args) + \" )\"\n[docs]    def visit_comparison(self, comparison: Comparison) -> str:\n        comparator = self._format_func(comparison.comparator)\n        processed_value = process_value(comparison.value)\n        attribute = comparison.attribute\n        return (\n            \"( \" + \"doc.\" + attribute + \" \" + comparator + \" \" + processed_value + \" )\"\n        )\n[docs]    def visit_structured_query(\n        self, structured_query: StructuredQuery\n    ) -> Tuple[str, dict]:\n        if structured_query.filter is None:\n            kwargs = {}\n        else:\n            kwargs = {\"filter\": structured_query.filter.accept(self)}\n        return structured_query.query, kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/vectara.html"}
{"id": "0e4a5073f508-0", "text": "Source code for langchain.runnables.openai_functions\nfrom operator import itemgetter\nfrom typing import Any, Callable, List, Mapping, Optional, Union\nfrom typing_extensions import TypedDict\nfrom langchain.output_parsers.openai_functions import JsonOutputFunctionsParser\nfrom langchain.schema.messages import BaseMessage\nfrom langchain.schema.runnable import RouterRunnable, Runnable\nfrom langchain.schema.runnable.base import RunnableBindingBase\n[docs]class OpenAIFunction(TypedDict):\n    \"\"\"A function description for ChatOpenAI\"\"\"\n    name: str\n    \"\"\"The name of the function.\"\"\"\n    description: str\n    \"\"\"The description of the function.\"\"\"\n    parameters: dict\n    \"\"\"The parameters to the function.\"\"\"\n[docs]class OpenAIFunctionsRouter(RunnableBindingBase[BaseMessage, Any]):\n    \"\"\"A runnable that routes to the selected function.\"\"\"\n    functions: Optional[List[OpenAIFunction]]\n    def __init__(\n        self,\n        runnables: Mapping[\n            str,\n            Union[\n                Runnable[dict, Any],\n                Callable[[dict], Any],\n            ],\n        ],\n        functions: Optional[List[OpenAIFunction]] = None,\n    ):\n        if functions is not None:\n            assert len(functions) == len(runnables)\n            assert all(func[\"name\"] in runnables for func in functions)\n        router = (\n            JsonOutputFunctionsParser(args_only=False)\n            | {\"key\": itemgetter(\"name\"), \"input\": itemgetter(\"arguments\")}\n            | RouterRunnable(runnables)\n        )\n        super().__init__(bound=router, kwargs={}, functions=functions)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/runnables/openai_functions.html"}
{"id": "36e0516aa8bc-0", "text": "Source code for langchain.runnables.hub\nfrom typing import Any, Optional\nfrom langchain.schema.runnable.base import Input, Output, RunnableBindingBase\n[docs]class HubRunnable(RunnableBindingBase[Input, Output]):\n    \"\"\"\n    An instance of a runnable stored in the LangChain Hub.\n    \"\"\"\n    owner_repo_commit: str\n    def __init__(\n        self,\n        owner_repo_commit: str,\n        *,\n        api_url: Optional[str] = None,\n        api_key: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        from langchain.hub import pull\n        pulled = pull(owner_repo_commit, api_url=api_url, api_key=api_key)\n        super_kwargs = {\n            \"kwargs\": {},\n            \"config\": {},\n            **kwargs,\n            \"bound\": pulled,\n            \"owner_repo_commit\": owner_repo_commit,\n        }\n        super().__init__(**super_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/runnables/hub.html"}
{"id": "27cbd746a3d9-0", "text": "Source code for langchain.chains.llm\n\"\"\"Chain that just formats a prompt and calls an LLM.\"\"\"\nfrom __future__ import annotations\nimport warnings\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManager,\n    AsyncCallbackManagerForChainRun,\n    CallbackManager,\n    CallbackManagerForChainRun,\n    Callbacks,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.load.dump import dumpd\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.pydantic_v1 import Extra, Field\nfrom langchain.schema import (\n    BaseLLMOutputParser,\n    BaseMessage,\n    BasePromptTemplate,\n    ChatGeneration,\n    Generation,\n    LLMResult,\n    PromptValue,\n    StrOutputParser,\n)\nfrom langchain.schema.language_model import (\n    BaseLanguageModel,\n    LanguageModelInput,\n)\nfrom langchain.schema.runnable import (\n    Runnable,\n    RunnableBinding,\n    RunnableBranch,\n    RunnableWithFallbacks,\n)\nfrom langchain.schema.runnable.configurable import DynamicRunnable\nfrom langchain.utils.input import get_colored_text\n[docs]class LLMChain(Chain):\n    \"\"\"Chain to run queries against LLMs.\n    Example:\n        .. code-block:: python\n            from langchain.chains import LLMChain\n            from langchain.llms import OpenAI\n            from langchain.prompts import PromptTemplate\n            prompt_template = \"Tell me a {adjective} joke\"\n            prompt = PromptTemplate(\n                input_variables=[\"adjective\"], template=prompt_template\n            )\n            llm = LLMChain(llm=OpenAI(), prompt=prompt)\n    \"\"\"\n[docs]    @classmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html"}
{"id": "27cbd746a3d9-1", "text": "\"\"\"\n[docs]    @classmethod\n    def is_lc_serializable(self) -> bool:\n        return True\n    prompt: BasePromptTemplate\n    \"\"\"Prompt object to use.\"\"\"\n    llm: Union[\n        Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]\n    ]\n    \"\"\"Language model to call.\"\"\"\n    output_key: str = \"text\"  #: :meta private:\n    output_parser: BaseLLMOutputParser = Field(default_factory=StrOutputParser)\n    \"\"\"Output parser to use.\n    Defaults to one that takes the most likely string but does not change it \n    otherwise.\"\"\"\n    return_final_only: bool = True\n    \"\"\"Whether to return only the final parsed result. Defaults to True.\n    If false, will return a bunch of extra information about the generation.\"\"\"\n    llm_kwargs: dict = Field(default_factory=dict)\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Will be whatever keys the prompt expects.\n        :meta private:\n        \"\"\"\n        return self.prompt.input_variables\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Will always return text key.\n        :meta private:\n        \"\"\"\n        if self.return_final_only:\n            return [self.output_key]\n        else:\n            return [self.output_key, \"full_generation\"]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        response = self.generate([inputs], run_manager=run_manager)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html"}
{"id": "27cbd746a3d9-2", "text": "response = self.generate([inputs], run_manager=run_manager)\n        return self.create_outputs(response)[0]\n[docs]    def generate(\n        self,\n        input_list: List[Dict[str, Any]],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> LLMResult:\n        \"\"\"Generate LLM result from inputs.\"\"\"\n        prompts, stop = self.prep_prompts(input_list, run_manager=run_manager)\n        callbacks = run_manager.get_child() if run_manager else None\n        if isinstance(self.llm, BaseLanguageModel):\n            return self.llm.generate_prompt(\n                prompts,\n                stop,\n                callbacks=callbacks,\n                **self.llm_kwargs,\n            )\n        else:\n            results = self.llm.bind(stop=stop, **self.llm_kwargs).batch(\n                cast(List, prompts), {\"callbacks\": callbacks}\n            )\n            generations: List[List[Generation]] = []\n            for res in results:\n                if isinstance(res, BaseMessage):\n                    generations.append([ChatGeneration(message=res)])\n                else:\n                    generations.append([Generation(text=res)])\n            return LLMResult(generations=generations)\n[docs]    async def agenerate(\n        self,\n        input_list: List[Dict[str, Any]],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> LLMResult:\n        \"\"\"Generate LLM result from inputs.\"\"\"\n        prompts, stop = await self.aprep_prompts(input_list, run_manager=run_manager)\n        callbacks = run_manager.get_child() if run_manager else None\n        if isinstance(self.llm, BaseLanguageModel):\n            return await self.llm.agenerate_prompt(\n                prompts,\n                stop,\n                callbacks=callbacks,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html"}
{"id": "27cbd746a3d9-3", "text": "prompts,\n                stop,\n                callbacks=callbacks,\n                **self.llm_kwargs,\n            )\n        else:\n            results = await self.llm.bind(stop=stop, **self.llm_kwargs).abatch(\n                cast(List, prompts), {\"callbacks\": callbacks}\n            )\n            generations: List[List[Generation]] = []\n            for res in results:\n                if isinstance(res, BaseMessage):\n                    generations.append([ChatGeneration(message=res)])\n                else:\n                    generations.append([Generation(text=res)])\n            return LLMResult(generations=generations)\n[docs]    def prep_prompts(\n        self,\n        input_list: List[Dict[str, Any]],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Tuple[List[PromptValue], Optional[List[str]]]:\n        \"\"\"Prepare prompts from inputs.\"\"\"\n        stop = None\n        if len(input_list) == 0:\n            return [], stop\n        if \"stop\" in input_list[0]:\n            stop = input_list[0][\"stop\"]\n        prompts = []\n        for inputs in input_list:\n            selected_inputs = {k: inputs[k] for k in self.prompt.input_variables}\n            prompt = self.prompt.format_prompt(**selected_inputs)\n            _colored_text = get_colored_text(prompt.to_string(), \"green\")\n            _text = \"Prompt after formatting:\\n\" + _colored_text\n            if run_manager:\n                run_manager.on_text(_text, end=\"\\n\", verbose=self.verbose)\n            if \"stop\" in inputs and inputs[\"stop\"] != stop:\n                raise ValueError(\n                    \"If `stop` is present in any inputs, should be present in all.\"\n                )\n            prompts.append(prompt)\n        return prompts, stop", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html"}
{"id": "27cbd746a3d9-4", "text": ")\n            prompts.append(prompt)\n        return prompts, stop\n[docs]    async def aprep_prompts(\n        self,\n        input_list: List[Dict[str, Any]],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Tuple[List[PromptValue], Optional[List[str]]]:\n        \"\"\"Prepare prompts from inputs.\"\"\"\n        stop = None\n        if len(input_list) == 0:\n            return [], stop\n        if \"stop\" in input_list[0]:\n            stop = input_list[0][\"stop\"]\n        prompts = []\n        for inputs in input_list:\n            selected_inputs = {k: inputs[k] for k in self.prompt.input_variables}\n            prompt = self.prompt.format_prompt(**selected_inputs)\n            _colored_text = get_colored_text(prompt.to_string(), \"green\")\n            _text = \"Prompt after formatting:\\n\" + _colored_text\n            if run_manager:\n                await run_manager.on_text(_text, end=\"\\n\", verbose=self.verbose)\n            if \"stop\" in inputs and inputs[\"stop\"] != stop:\n                raise ValueError(\n                    \"If `stop` is present in any inputs, should be present in all.\"\n                )\n            prompts.append(prompt)\n        return prompts, stop\n[docs]    def apply(\n        self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None\n    ) -> List[Dict[str, str]]:\n        \"\"\"Utilize the LLM generate method for speed gains.\"\"\"\n        callback_manager = CallbackManager.configure(\n            callbacks, self.callbacks, self.verbose\n        )\n        run_manager = callback_manager.on_chain_start(\n            dumpd(self),\n            {\"input_list\": input_list},\n        )\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html"}
{"id": "27cbd746a3d9-5", "text": "{\"input_list\": input_list},\n        )\n        try:\n            response = self.generate(input_list, run_manager=run_manager)\n        except BaseException as e:\n            run_manager.on_chain_error(e)\n            raise e\n        outputs = self.create_outputs(response)\n        run_manager.on_chain_end({\"outputs\": outputs})\n        return outputs\n[docs]    async def aapply(\n        self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None\n    ) -> List[Dict[str, str]]:\n        \"\"\"Utilize the LLM generate method for speed gains.\"\"\"\n        callback_manager = AsyncCallbackManager.configure(\n            callbacks, self.callbacks, self.verbose\n        )\n        run_manager = await callback_manager.on_chain_start(\n            dumpd(self),\n            {\"input_list\": input_list},\n        )\n        try:\n            response = await self.agenerate(input_list, run_manager=run_manager)\n        except BaseException as e:\n            await run_manager.on_chain_error(e)\n            raise e\n        outputs = self.create_outputs(response)\n        await run_manager.on_chain_end({\"outputs\": outputs})\n        return outputs\n    @property\n    def _run_output_key(self) -> str:\n        return self.output_key\n[docs]    def create_outputs(self, llm_result: LLMResult) -> List[Dict[str, Any]]:\n        \"\"\"Create outputs from response.\"\"\"\n        result = [\n            # Get the text of the top generated string.\n            {\n                self.output_key: self.output_parser.parse_result(generation),\n                \"full_generation\": generation,\n            }\n            for generation in llm_result.generations\n        ]\n        if self.return_final_only:\n            result = [{self.output_key: r[self.output_key]} for r in result]\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html"}
{"id": "27cbd746a3d9-6", "text": "return result\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        response = await self.agenerate([inputs], run_manager=run_manager)\n        return self.create_outputs(response)[0]\n[docs]    def predict(self, callbacks: Callbacks = None, **kwargs: Any) -> str:\n        \"\"\"Format prompt with kwargs and pass to LLM.\n        Args:\n            callbacks: Callbacks to pass to LLMChain\n            **kwargs: Keys to pass to prompt template.\n        Returns:\n            Completion from LLM.\n        Example:\n            .. code-block:: python\n                completion = llm.predict(adjective=\"funny\")\n        \"\"\"\n        return self(kwargs, callbacks=callbacks)[self.output_key]\n[docs]    async def apredict(self, callbacks: Callbacks = None, **kwargs: Any) -> str:\n        \"\"\"Format prompt with kwargs and pass to LLM.\n        Args:\n            callbacks: Callbacks to pass to LLMChain\n            **kwargs: Keys to pass to prompt template.\n        Returns:\n            Completion from LLM.\n        Example:\n            .. code-block:: python\n                completion = llm.predict(adjective=\"funny\")\n        \"\"\"\n        return (await self.acall(kwargs, callbacks=callbacks))[self.output_key]\n[docs]    def predict_and_parse(\n        self, callbacks: Callbacks = None, **kwargs: Any\n    ) -> Union[str, List[str], Dict[str, Any]]:\n        \"\"\"Call predict and then parse the results.\"\"\"\n        warnings.warn(\n            \"The predict_and_parse method is deprecated, \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html"}
{"id": "27cbd746a3d9-7", "text": "warnings.warn(\n            \"The predict_and_parse method is deprecated, \"\n            \"instead pass an output parser directly to LLMChain.\"\n        )\n        result = self.predict(callbacks=callbacks, **kwargs)\n        if self.prompt.output_parser is not None:\n            return self.prompt.output_parser.parse(result)\n        else:\n            return result\n[docs]    async def apredict_and_parse(\n        self, callbacks: Callbacks = None, **kwargs: Any\n    ) -> Union[str, List[str], Dict[str, str]]:\n        \"\"\"Call apredict and then parse the results.\"\"\"\n        warnings.warn(\n            \"The apredict_and_parse method is deprecated, \"\n            \"instead pass an output parser directly to LLMChain.\"\n        )\n        result = await self.apredict(callbacks=callbacks, **kwargs)\n        if self.prompt.output_parser is not None:\n            return self.prompt.output_parser.parse(result)\n        else:\n            return result\n[docs]    def apply_and_parse(\n        self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None\n    ) -> Sequence[Union[str, List[str], Dict[str, str]]]:\n        \"\"\"Call apply and then parse the results.\"\"\"\n        warnings.warn(\n            \"The apply_and_parse method is deprecated, \"\n            \"instead pass an output parser directly to LLMChain.\"\n        )\n        result = self.apply(input_list, callbacks=callbacks)\n        return self._parse_generation(result)\n    def _parse_generation(\n        self, generation: List[Dict[str, str]]\n    ) -> Sequence[Union[str, List[str], Dict[str, str]]]:\n        if self.prompt.output_parser is not None:\n            return [\n                self.prompt.output_parser.parse(res[self.output_key])\n                for res in generation", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html"}
{"id": "27cbd746a3d9-8", "text": "self.prompt.output_parser.parse(res[self.output_key])\n                for res in generation\n            ]\n        else:\n            return generation\n[docs]    async def aapply_and_parse(\n        self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None\n    ) -> Sequence[Union[str, List[str], Dict[str, str]]]:\n        \"\"\"Call apply and then parse the results.\"\"\"\n        warnings.warn(\n            \"The aapply_and_parse method is deprecated, \"\n            \"instead pass an output parser directly to LLMChain.\"\n        )\n        result = await self.aapply(input_list, callbacks=callbacks)\n        return self._parse_generation(result)\n    @property\n    def _chain_type(self) -> str:\n        return \"llm_chain\"\n[docs]    @classmethod\n    def from_string(cls, llm: BaseLanguageModel, template: str) -> LLMChain:\n        \"\"\"Create LLMChain from LLM and template.\"\"\"\n        prompt_template = PromptTemplate.from_template(template)\n        return cls(llm=llm, prompt=prompt_template)\n    def _get_num_tokens(self, text: str) -> int:\n        return _get_language_model(self.llm).get_num_tokens(text)\ndef _get_language_model(llm_like: Runnable) -> BaseLanguageModel:\n    if isinstance(llm_like, BaseLanguageModel):\n        return llm_like\n    elif isinstance(llm_like, RunnableBinding):\n        return _get_language_model(llm_like.bound)\n    elif isinstance(llm_like, RunnableWithFallbacks):\n        return _get_language_model(llm_like.runnable)\n    elif isinstance(llm_like, (RunnableBranch, DynamicRunnable)):\n        return _get_language_model(llm_like.default)\n    else:\n        raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html"}
{"id": "27cbd746a3d9-9", "text": "else:\n        raise ValueError(\n            f\"Unable to extract BaseLanguageModel from llm_like object of type \"\n            f\"{type(llm_like)}\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html"}
{"id": "01e09df3201d-0", "text": "Source code for langchain.chains.example_generator\nfrom typing import List\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts.few_shot import FewShotPromptTemplate\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nTEST_GEN_TEMPLATE_SUFFIX = \"Add another example.\"\n[docs]def generate_example(\n    examples: List[dict], llm: BaseLanguageModel, prompt_template: PromptTemplate\n) -> str:\n    \"\"\"Return another example given a list of examples for a prompt.\"\"\"\n    prompt = FewShotPromptTemplate(\n        examples=examples,\n        suffix=TEST_GEN_TEMPLATE_SUFFIX,\n        input_variables=[],\n        example_prompt=prompt_template,\n    )\n    chain = LLMChain(llm=llm, prompt=prompt)\n    return chain.predict()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/example_generator.html"}
{"id": "fa7c749cec59-0", "text": "Source code for langchain.chains.llm_requests\n\"\"\"Chain that hits a URL and then uses an LLM to parse results.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains import LLMChain\nfrom langchain.chains.base import Chain\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.utilities.requests import TextRequestsWrapper\nDEFAULT_HEADERS = {\n    \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36\"  # noqa: E501\n}\n[docs]class LLMRequestsChain(Chain):\n    \"\"\"Chain that requests a URL and then uses an LLM to parse results.\n    **Security Note**: This chain can make GET requests to arbitrary URLs,\n        including internal URLs.\n        Control access to who can run this chain and what network access\n        this chain has.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    llm_chain: LLMChain\n    requests_wrapper: TextRequestsWrapper = Field(\n        default_factory=lambda: TextRequestsWrapper(headers=DEFAULT_HEADERS),\n        exclude=True,\n    )\n    text_length: int = 8000\n    requests_key: str = \"requests_result\"  #: :meta private:\n    input_key: str = \"url\"  #: :meta private:\n    output_key: str = \"output\"  #: :meta private:\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html"}
{"id": "fa7c749cec59-1", "text": "extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Will be whatever keys the prompt expects.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Will always return text key.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        try:\n            from bs4 import BeautifulSoup  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"Could not import bs4 python package. \"\n                \"Please install it with `pip install bs4`.\"\n            )\n        return values\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        from bs4 import BeautifulSoup\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        # Other keys are assumed to be needed for LLM prediction\n        other_keys = {k: v for k, v in inputs.items() if k != self.input_key}\n        url = inputs[self.input_key]\n        res = self.requests_wrapper.get(url)\n        # extract the text from the html\n        soup = BeautifulSoup(res, \"html.parser\")\n        other_keys[self.requests_key] = soup.get_text()[: self.text_length]\n        result = self.llm_chain.predict(\n            callbacks=_run_manager.get_child(), **other_keys\n        )\n        return {self.output_key: result}\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html"}
{"id": "fa7c749cec59-2", "text": ")\n        return {self.output_key: result}\n    @property\n    def _chain_type(self) -> str:\n        return \"llm_requests_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html"}
{"id": "2154a11e75c0-0", "text": "Source code for langchain.chains.moderation\n\"\"\"Pass input through a moderation endpoint.\"\"\"\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class OpenAIModerationChain(Chain):\n    \"\"\"Pass input through a moderation endpoint.\n    To use, you should have the ``openai`` python package installed, and the\n    environment variable ``OPENAI_API_KEY`` set with your API key.\n    Any parameters that are valid to be passed to the openai.create call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.chains import OpenAIModerationChain\n            moderation = OpenAIModerationChain()\n    \"\"\"\n    client: Any  #: :meta private:\n    model_name: Optional[str] = None\n    \"\"\"Moderation model name to use.\"\"\"\n    error: bool = False\n    \"\"\"Whether or not to error if bad content was found.\"\"\"\n    input_key: str = \"input\"  #: :meta private:\n    output_key: str = \"output\"  #: :meta private:\n    openai_api_key: Optional[str] = None\n    openai_organization: Optional[str] = None\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        openai_api_key = get_from_dict_or_env(\n            values, \"openai_api_key\", \"OPENAI_API_KEY\"\n        )\n        openai_organization = get_from_dict_or_env(\n            values,\n            \"openai_organization\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/moderation.html"}
{"id": "2154a11e75c0-1", "text": "values,\n            \"openai_organization\",\n            \"OPENAI_ORGANIZATION\",\n            default=\"\",\n        )\n        try:\n            import openai\n            openai.api_key = openai_api_key\n            if openai_organization:\n                openai.organization = openai_organization\n            values[\"client\"] = openai.Moderation\n        except ImportError:\n            raise ImportError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\"\n            )\n        return values\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return output key.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n    def _moderate(self, text: str, results: dict) -> str:\n        if results[\"flagged\"]:\n            error_str = \"Text was found that violates OpenAI's content policy.\"\n            if self.error:\n                raise ValueError(error_str)\n            else:\n                return error_str\n        return text\n    def _call(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        text = inputs[self.input_key]\n        results = self.client.create(text)\n        output = self._moderate(text, results[\"results\"][0])\n        return {self.output_key: output}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/moderation.html"}
{"id": "f66c413dc0d9-0", "text": "Source code for langchain.chains.prompt_selector\nfrom abc import ABC, abstractmethod\nfrom typing import Callable, List, Tuple\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.llms.base import BaseLLM\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class BasePromptSelector(BaseModel, ABC):\n    \"\"\"Base class for prompt selectors.\"\"\"\n[docs]    @abstractmethod\n    def get_prompt(self, llm: BaseLanguageModel) -> BasePromptTemplate:\n        \"\"\"Get default prompt for a language model.\"\"\"\n[docs]class ConditionalPromptSelector(BasePromptSelector):\n    \"\"\"Prompt collection that goes through conditionals.\"\"\"\n    default_prompt: BasePromptTemplate\n    \"\"\"Default prompt to use if no conditionals match.\"\"\"\n    conditionals: List[\n        Tuple[Callable[[BaseLanguageModel], bool], BasePromptTemplate]\n    ] = Field(default_factory=list)\n    \"\"\"List of conditionals and prompts to use if the conditionals match.\"\"\"\n[docs]    def get_prompt(self, llm: BaseLanguageModel) -> BasePromptTemplate:\n        \"\"\"Get default prompt for a language model.\n        Args:\n            llm: Language model to get prompt for.\n        Returns:\n            Prompt to use for the language model.\n        \"\"\"\n        for condition, prompt in self.conditionals:\n            if condition(llm):\n                return prompt\n        return self.default_prompt\n[docs]def is_llm(llm: BaseLanguageModel) -> bool:\n    \"\"\"Check if the language model is a LLM.\n    Args:\n        llm: Language model to check.\n    Returns:\n        True if the language model is a BaseLLM model, False otherwise.\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/prompt_selector.html"}
{"id": "f66c413dc0d9-1", "text": "True if the language model is a BaseLLM model, False otherwise.\n    \"\"\"\n    return isinstance(llm, BaseLLM)\n[docs]def is_chat_model(llm: BaseLanguageModel) -> bool:\n    \"\"\"Check if the language model is a chat model.\n    Args:\n        llm: Language model to check.\n    Returns:\n        True if the language model is a BaseChatModel model, False otherwise.\n    \"\"\"\n    return isinstance(llm, BaseChatModel)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/prompt_selector.html"}
{"id": "e6e5c70a982d-0", "text": "Source code for langchain.chains.base\n\"\"\"Base interface that all chains should implement.\"\"\"\nimport asyncio\nimport inspect\nimport json\nimport logging\nimport warnings\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Type, Union\nimport yaml\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManager,\n    AsyncCallbackManagerForChainRun,\n    CallbackManager,\n    CallbackManagerForChainRun,\n    Callbacks,\n)\nfrom langchain.load.dump import dumpd\nfrom langchain.pydantic_v1 import (\n    BaseModel,\n    Field,\n    create_model,\n    root_validator,\n    validator,\n)\nfrom langchain.schema import RUN_KEY, BaseMemory, RunInfo\nfrom langchain.schema.runnable import RunnableConfig, RunnableSerializable\nlogger = logging.getLogger(__name__)\ndef _get_verbosity() -> bool:\n    from langchain.globals import get_verbose\n    return get_verbose()\n[docs]class Chain(RunnableSerializable[Dict[str, Any], Dict[str, Any]], ABC):\n    \"\"\"Abstract base class for creating structured sequences of calls to components.\n    Chains should be used to encode a sequence of calls to components like\n    models, document retrievers, other chains, etc., and provide a simple interface\n    to this sequence.\n    The Chain interface makes it easy to create apps that are:\n        - Stateful: add Memory to any Chain to give it state,\n        - Observable: pass Callbacks to a Chain to execute additional functionality,\n            like logging, outside the main sequence of component calls,\n        - Composable: the Chain API is flexible enough that it is easy to combine\n            Chains with other components, including other Chains.\n    The main methods exposed by chains are:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-1", "text": "The main methods exposed by chains are:\n        - `__call__`: Chains are callable. The `__call__` method is the primary way to\n            execute a Chain. This takes inputs as a dictionary and returns a\n            dictionary output.\n        - `run`: A convenience method that takes inputs as args/kwargs and returns the\n            output as a string or object. This method can only be used for a subset of\n            chains and cannot return as rich of an output as `__call__`.\n    \"\"\"\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        # This is correct, but pydantic typings/mypy don't think so.\n        return create_model(  # type: ignore[call-overload]\n            \"ChainInput\", **{k: (Any, None) for k in self.input_keys}\n        )\n[docs]    def get_output_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        # This is correct, but pydantic typings/mypy don't think so.\n        return create_model(  # type: ignore[call-overload]\n            \"ChainOutput\", **{k: (Any, None) for k in self.output_keys}\n        )\n[docs]    def invoke(\n        self,\n        input: Dict[str, Any],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Dict[str, Any]:\n        config = config or {}\n        return self(\n            input,\n            callbacks=config.get(\"callbacks\"),\n            tags=config.get(\"tags\"),\n            metadata=config.get(\"metadata\"),\n            run_name=config.get(\"run_name\"),\n            **kwargs,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-2", "text": "run_name=config.get(\"run_name\"),\n            **kwargs,\n        )\n[docs]    async def ainvoke(\n        self,\n        input: Dict[str, Any],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Dict[str, Any]:\n        config = config or {}\n        return await self.acall(\n            input,\n            callbacks=config.get(\"callbacks\"),\n            tags=config.get(\"tags\"),\n            metadata=config.get(\"metadata\"),\n            run_name=config.get(\"run_name\"),\n            **kwargs,\n        )\n    memory: Optional[BaseMemory] = None\n    \"\"\"Optional memory object. Defaults to None.\n    Memory is a class that gets called at the start\n    and at the end of every chain. At the start, memory loads variables and passes\n    them along in the chain. At the end, it saves any returned variables.\n    There are many different types of memory - please see memory docs\n    for the full catalog.\"\"\"\n    callbacks: Callbacks = Field(default=None, exclude=True)\n    \"\"\"Optional list of callback handlers (or callback manager). Defaults to None.\n    Callback handlers are called throughout the lifecycle of a call to a chain,\n    starting with on_chain_start, ending with on_chain_end or on_chain_error.\n    Each custom chain can optionally call additional callback methods, see Callback docs\n    for full details.\"\"\"\n    callback_manager: Optional[BaseCallbackManager] = Field(default=None, exclude=True)\n    \"\"\"Deprecated, use `callbacks` instead.\"\"\"\n    verbose: bool = Field(default_factory=_get_verbosity)\n    \"\"\"Whether or not run in verbose mode. In verbose mode, some intermediate logs\n    will be printed to the console. Defaults to the global `verbose` value,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-3", "text": "will be printed to the console. Defaults to the global `verbose` value,\n    accessible via `langchain.globals.get_verbose()`.\"\"\"\n    tags: Optional[List[str]] = None\n    \"\"\"Optional list of tags associated with the chain. Defaults to None.\n    These tags will be associated with each call to this chain,\n    and passed as arguments to the handlers defined in `callbacks`.\n    You can use these to eg identify a specific instance of a chain with its use case.\n    \"\"\"\n    metadata: Optional[Dict[str, Any]] = None\n    \"\"\"Optional metadata associated with the chain. Defaults to None.\n    This metadata will be associated with each call to this chain,\n    and passed as arguments to the handlers defined in `callbacks`.\n    You can use these to eg identify a specific instance of a chain with its use case.\n    \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @property\n    def _chain_type(self) -> str:\n        raise NotImplementedError(\"Saving not supported for this chain type.\")\n    @root_validator()\n    def raise_callback_manager_deprecation(cls, values: Dict) -> Dict:\n        \"\"\"Raise deprecation warning if callback_manager is used.\"\"\"\n        if values.get(\"callback_manager\") is not None:\n            if values.get(\"callbacks\") is not None:\n                raise ValueError(\n                    \"Cannot specify both callback_manager and callbacks. \"\n                    \"callback_manager is deprecated, callbacks is the preferred \"\n                    \"parameter to pass in.\"\n                )\n            warnings.warn(\n                \"callback_manager is deprecated. Please use callbacks instead.\",\n                DeprecationWarning,\n            )\n            values[\"callbacks\"] = values.pop(\"callback_manager\", None)\n        return values\n    @validator(\"verbose\", pre=True, always=True)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-4", "text": "return values\n    @validator(\"verbose\", pre=True, always=True)\n    def set_verbose(cls, verbose: Optional[bool]) -> bool:\n        \"\"\"Set the chain verbosity.\n        Defaults to the global setting if not specified by the user.\n        \"\"\"\n        if verbose is None:\n            return _get_verbosity()\n        else:\n            return verbose\n    @property\n    @abstractmethod\n    def input_keys(self) -> List[str]:\n        \"\"\"Keys expected to be in the chain input.\"\"\"\n    @property\n    @abstractmethod\n    def output_keys(self) -> List[str]:\n        \"\"\"Keys expected to be in the chain output.\"\"\"\n    def _validate_inputs(self, inputs: Dict[str, Any]) -> None:\n        \"\"\"Check that all inputs are present.\"\"\"\n        missing_keys = set(self.input_keys).difference(inputs)\n        if missing_keys:\n            raise ValueError(f\"Missing some input keys: {missing_keys}\")\n    def _validate_outputs(self, outputs: Dict[str, Any]) -> None:\n        missing_keys = set(self.output_keys).difference(outputs)\n        if missing_keys:\n            raise ValueError(f\"Missing some output keys: {missing_keys}\")\n    @abstractmethod\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Execute the chain.\n        This is a private method that is not user-facing. It is only called within\n            `Chain.__call__`, which is the user-facing wrapper method that handles\n            callbacks configuration and some input/output processing.\n        Args:\n            inputs: A dict of named inputs to the chain. Assumed to contain all inputs\n                specified in `Chain.input_keys`, including any inputs added by memory.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-5", "text": "specified in `Chain.input_keys`, including any inputs added by memory.\n            run_manager: The callbacks manager that contains the callback handlers for\n                this run of the chain.\n        Returns:\n            A dict of named outputs. Should contain all outputs specified in\n                `Chain.output_keys`.\n        \"\"\"\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Asynchronously execute the chain.\n        This is a private method that is not user-facing. It is only called within\n            `Chain.acall`, which is the user-facing wrapper method that handles\n            callbacks configuration and some input/output processing.\n        Args:\n            inputs: A dict of named inputs to the chain. Assumed to contain all inputs\n                specified in `Chain.input_keys`, including any inputs added by memory.\n            run_manager: The callbacks manager that contains the callback handlers for\n                this run of the chain.\n        Returns:\n            A dict of named outputs. Should contain all outputs specified in\n                `Chain.output_keys`.\n        \"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, self._call, inputs, run_manager\n        )\n[docs]    def __call__(\n        self,\n        inputs: Union[Dict[str, Any], Any],\n        return_only_outputs: bool = False,\n        callbacks: Callbacks = None,\n        *,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        run_name: Optional[str] = None,\n        include_run_info: bool = False,\n    ) -> Dict[str, Any]:\n        \"\"\"Execute the chain.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-6", "text": ") -> Dict[str, Any]:\n        \"\"\"Execute the chain.\n        Args:\n            inputs: Dictionary of inputs, or single input if chain expects\n                only one param. Should contain all inputs specified in\n                `Chain.input_keys` except for inputs that will be set by the chain's\n                memory.\n            return_only_outputs: Whether to return only outputs in the\n                response. If True, only new keys generated by this chain will be\n                returned. If False, both input keys and new keys generated by this\n                chain will be returned. Defaults to False.\n            callbacks: Callbacks to use for this chain run. These will be called in\n                addition to callbacks passed to the chain during construction, but only\n                these runtime callbacks will propagate to calls to other objects.\n            tags: List of string tags to pass to all callbacks. These will be passed in\n                addition to tags passed to the chain during construction, but only\n                these runtime tags will propagate to calls to other objects.\n            metadata: Optional metadata associated with the chain. Defaults to None\n            include_run_info: Whether to include run info in the response. Defaults\n                to False.\n        Returns:\n            A dict of named outputs. Should contain all outputs specified in\n                `Chain.output_keys`.\n        \"\"\"\n        inputs = self.prep_inputs(inputs)\n        callback_manager = CallbackManager.configure(\n            callbacks,\n            self.callbacks,\n            self.verbose,\n            tags,\n            self.tags,\n            metadata,\n            self.metadata,\n        )\n        new_arg_supported = inspect.signature(self._call).parameters.get(\"run_manager\")\n        run_manager = callback_manager.on_chain_start(\n            dumpd(self),\n            inputs,\n            name=run_name,\n        )\n        try:\n            outputs = (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-7", "text": "name=run_name,\n        )\n        try:\n            outputs = (\n                self._call(inputs, run_manager=run_manager)\n                if new_arg_supported\n                else self._call(inputs)\n            )\n        except BaseException as e:\n            run_manager.on_chain_error(e)\n            raise e\n        run_manager.on_chain_end(outputs)\n        final_outputs: Dict[str, Any] = self.prep_outputs(\n            inputs, outputs, return_only_outputs\n        )\n        if include_run_info:\n            final_outputs[RUN_KEY] = RunInfo(run_id=run_manager.run_id)\n        return final_outputs\n[docs]    async def acall(\n        self,\n        inputs: Union[Dict[str, Any], Any],\n        return_only_outputs: bool = False,\n        callbacks: Callbacks = None,\n        *,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        run_name: Optional[str] = None,\n        include_run_info: bool = False,\n    ) -> Dict[str, Any]:\n        \"\"\"Asynchronously execute the chain.\n        Args:\n            inputs: Dictionary of inputs, or single input if chain expects\n                only one param. Should contain all inputs specified in\n                `Chain.input_keys` except for inputs that will be set by the chain's\n                memory.\n            return_only_outputs: Whether to return only outputs in the\n                response. If True, only new keys generated by this chain will be\n                returned. If False, both input keys and new keys generated by this\n                chain will be returned. Defaults to False.\n            callbacks: Callbacks to use for this chain run. These will be called in\n                addition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-8", "text": "addition to callbacks passed to the chain during construction, but only\n                these runtime callbacks will propagate to calls to other objects.\n            tags: List of string tags to pass to all callbacks. These will be passed in\n                addition to tags passed to the chain during construction, but only\n                these runtime tags will propagate to calls to other objects.\n            metadata: Optional metadata associated with the chain. Defaults to None\n            include_run_info: Whether to include run info in the response. Defaults\n                to False.\n        Returns:\n            A dict of named outputs. Should contain all outputs specified in\n                `Chain.output_keys`.\n        \"\"\"\n        inputs = self.prep_inputs(inputs)\n        callback_manager = AsyncCallbackManager.configure(\n            callbacks,\n            self.callbacks,\n            self.verbose,\n            tags,\n            self.tags,\n            metadata,\n            self.metadata,\n        )\n        new_arg_supported = inspect.signature(self._acall).parameters.get(\"run_manager\")\n        run_manager = await callback_manager.on_chain_start(\n            dumpd(self),\n            inputs,\n            name=run_name,\n        )\n        try:\n            outputs = (\n                await self._acall(inputs, run_manager=run_manager)\n                if new_arg_supported\n                else await self._acall(inputs)\n            )\n        except BaseException as e:\n            await run_manager.on_chain_error(e)\n            raise e\n        await run_manager.on_chain_end(outputs)\n        final_outputs: Dict[str, Any] = self.prep_outputs(\n            inputs, outputs, return_only_outputs\n        )\n        if include_run_info:\n            final_outputs[RUN_KEY] = RunInfo(run_id=run_manager.run_id)\n        return final_outputs\n[docs]    def prep_outputs(\n        self,\n        inputs: Dict[str, str],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-9", "text": "self,\n        inputs: Dict[str, str],\n        outputs: Dict[str, str],\n        return_only_outputs: bool = False,\n    ) -> Dict[str, str]:\n        \"\"\"Validate and prepare chain outputs, and save info about this run to memory.\n        Args:\n            inputs: Dictionary of chain inputs, including any inputs added by chain\n                memory.\n            outputs: Dictionary of initial chain outputs.\n            return_only_outputs: Whether to only return the chain outputs. If False,\n                inputs are also added to the final outputs.\n        Returns:\n            A dict of the final chain outputs.\n        \"\"\"\n        self._validate_outputs(outputs)\n        if self.memory is not None:\n            self.memory.save_context(inputs, outputs)\n        if return_only_outputs:\n            return outputs\n        else:\n            return {**inputs, **outputs}\n[docs]    def prep_inputs(self, inputs: Union[Dict[str, Any], Any]) -> Dict[str, str]:\n        \"\"\"Validate and prepare chain inputs, including adding inputs from memory.\n        Args:\n            inputs: Dictionary of raw inputs, or single input if chain expects\n                only one param. Should contain all inputs specified in\n                `Chain.input_keys` except for inputs that will be set by the chain's\n                memory.\n        Returns:\n            A dictionary of all inputs, including those added by the chain's memory.\n        \"\"\"\n        if not isinstance(inputs, dict):\n            _input_keys = set(self.input_keys)\n            if self.memory is not None:\n                # If there are multiple input keys, but some get set by memory so that\n                # only one is not set, we can still figure out which key it is.\n                _input_keys = _input_keys.difference(self.memory.memory_variables)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-10", "text": "_input_keys = _input_keys.difference(self.memory.memory_variables)\n            if len(_input_keys) != 1:\n                raise ValueError(\n                    f\"A single string input was passed in, but this chain expects \"\n                    f\"multiple inputs ({_input_keys}). When a chain expects \"\n                    f\"multiple inputs, please call it by passing in a dictionary, \"\n                    \"eg `chain({'foo': 1, 'bar': 2})`\"\n                )\n            inputs = {list(_input_keys)[0]: inputs}\n        if self.memory is not None:\n            external_context = self.memory.load_memory_variables(inputs)\n            inputs = dict(inputs, **external_context)\n        self._validate_inputs(inputs)\n        return inputs\n    @property\n    def _run_output_key(self) -> str:\n        if len(self.output_keys) != 1:\n            raise ValueError(\n                f\"`run` not supported when there is not exactly \"\n                f\"one output key. Got {self.output_keys}.\"\n            )\n        return self.output_keys[0]\n[docs]    def run(\n        self,\n        *args: Any,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Convenience method for executing chain.\n        The main difference between this method and `Chain.__call__` is that this\n        method expects inputs to be passed directly in as positional arguments or\n        keyword arguments, whereas `Chain.__call__` expects a single input dictionary\n        with all the inputs\n        Args:\n            *args: If the chain expects a single input, it can be passed in as the\n                sole positional argument.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-11", "text": "sole positional argument.\n            callbacks: Callbacks to use for this chain run. These will be called in\n                addition to callbacks passed to the chain during construction, but only\n                these runtime callbacks will propagate to calls to other objects.\n            tags: List of string tags to pass to all callbacks. These will be passed in\n                addition to tags passed to the chain during construction, but only\n                these runtime tags will propagate to calls to other objects.\n            **kwargs: If the chain expects multiple inputs, they can be passed in\n                directly as keyword arguments.\n        Returns:\n            The chain output.\n        Example:\n            .. code-block:: python\n                # Suppose we have a single-input chain that takes a 'question' string:\n                chain.run(\"What's the temperature in Boise, Idaho?\")\n                # -> \"The temperature in Boise is...\"\n                # Suppose we have a multi-input chain that takes a 'question' string\n                # and 'context' string:\n                question = \"What's the temperature in Boise, Idaho?\"\n                context = \"Weather report for Boise, Idaho on 07/03/23...\"\n                chain.run(question=question, context=context)\n                # -> \"The temperature in Boise is...\"\n        \"\"\"\n        # Run at start to make sure this is possible/defined\n        _output_key = self._run_output_key\n        if args and not kwargs:\n            if len(args) != 1:\n                raise ValueError(\"`run` supports only one positional argument.\")\n            return self(args[0], callbacks=callbacks, tags=tags, metadata=metadata)[\n                _output_key\n            ]\n        if kwargs and not args:\n            return self(kwargs, callbacks=callbacks, tags=tags, metadata=metadata)[\n                _output_key\n            ]\n        if not kwargs and not args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-12", "text": "_output_key\n            ]\n        if not kwargs and not args:\n            raise ValueError(\n                \"`run` supported with either positional arguments or keyword arguments,\"\n                \" but none were provided.\"\n            )\n        else:\n            raise ValueError(\n                f\"`run` supported with either positional arguments or keyword arguments\"\n                f\" but not both. Got args: {args} and kwargs: {kwargs}.\"\n            )\n[docs]    async def arun(\n        self,\n        *args: Any,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Convenience method for executing chain.\n        The main difference between this method and `Chain.__call__` is that this\n        method expects inputs to be passed directly in as positional arguments or\n        keyword arguments, whereas `Chain.__call__` expects a single input dictionary\n        with all the inputs\n        Args:\n            *args: If the chain expects a single input, it can be passed in as the\n                sole positional argument.\n            callbacks: Callbacks to use for this chain run. These will be called in\n                addition to callbacks passed to the chain during construction, but only\n                these runtime callbacks will propagate to calls to other objects.\n            tags: List of string tags to pass to all callbacks. These will be passed in\n                addition to tags passed to the chain during construction, but only\n                these runtime tags will propagate to calls to other objects.\n            **kwargs: If the chain expects multiple inputs, they can be passed in\n                directly as keyword arguments.\n        Returns:\n            The chain output.\n        Example:\n            .. code-block:: python", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-13", "text": "The chain output.\n        Example:\n            .. code-block:: python\n                # Suppose we have a single-input chain that takes a 'question' string:\n                await chain.arun(\"What's the temperature in Boise, Idaho?\")\n                # -> \"The temperature in Boise is...\"\n                # Suppose we have a multi-input chain that takes a 'question' string\n                # and 'context' string:\n                question = \"What's the temperature in Boise, Idaho?\"\n                context = \"Weather report for Boise, Idaho on 07/03/23...\"\n                await chain.arun(question=question, context=context)\n                # -> \"The temperature in Boise is...\"\n        \"\"\"\n        if len(self.output_keys) != 1:\n            raise ValueError(\n                f\"`run` not supported when there is not exactly \"\n                f\"one output key. Got {self.output_keys}.\"\n            )\n        elif args and not kwargs:\n            if len(args) != 1:\n                raise ValueError(\"`run` supports only one positional argument.\")\n            return (\n                await self.acall(\n                    args[0], callbacks=callbacks, tags=tags, metadata=metadata\n                )\n            )[self.output_keys[0]]\n        if kwargs and not args:\n            return (\n                await self.acall(\n                    kwargs, callbacks=callbacks, tags=tags, metadata=metadata\n                )\n            )[self.output_keys[0]]\n        raise ValueError(\n            f\"`run` supported with either positional arguments or keyword arguments\"\n            f\" but not both. Got args: {args} and kwargs: {kwargs}.\"\n        )\n[docs]    def dict(self, **kwargs: Any) -> Dict:\n        \"\"\"Dictionary representation of chain.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-14", "text": "\"\"\"Dictionary representation of chain.\n        Expects `Chain._chain_type` property to be implemented and for memory to be\n            null.\n        Args:\n            **kwargs: Keyword arguments passed to default `pydantic.BaseModel.dict`\n                method.\n        Returns:\n            A dictionary representation of the chain.\n        Example:\n            .. code-block:: python\n                chain.dict(exclude_unset=True)\n                # -> {\"_type\": \"foo\", \"verbose\": False, ...}\n        \"\"\"\n        _dict = super().dict(**kwargs)\n        try:\n            _dict[\"_type\"] = self._chain_type\n        except NotImplementedError:\n            pass\n        return _dict\n[docs]    def save(self, file_path: Union[Path, str]) -> None:\n        \"\"\"Save the chain.\n        Expects `Chain._chain_type` property to be implemented and for memory to be\n            null.\n        Args:\n            file_path: Path to file to save the chain to.\n        Example:\n            .. code-block:: python\n                chain.save(file_path=\"path/chain.yaml\")\n        \"\"\"\n        if self.memory is not None:\n            raise ValueError(\"Saving of memory is not yet supported.\")\n        # Fetch dictionary to save\n        chain_dict = self.dict()\n        if \"_type\" not in chain_dict:\n            raise NotImplementedError(f\"Chain {self} does not support saving.\")\n        # Convert file to Path object.\n        if isinstance(file_path, str):\n            save_path = Path(file_path)\n        else:\n            save_path = file_path\n        directory_path = save_path.parent\n        directory_path.mkdir(parents=True, exist_ok=True)\n        if save_path.suffix == \".json\":\n            with open(file_path, \"w\") as f:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "e6e5c70a982d-15", "text": "with open(file_path, \"w\") as f:\n                json.dump(chain_dict, f, indent=4)\n        elif save_path.suffix == \".yaml\":\n            with open(file_path, \"w\") as f:\n                yaml.dump(chain_dict, f, default_flow_style=False)\n        else:\n            raise ValueError(f\"{save_path} must be json or yaml\")\n[docs]    def apply(\n        self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None\n    ) -> List[Dict[str, str]]:\n        \"\"\"Call the chain on all inputs in the list.\"\"\"\n        return [self(inputs, callbacks=callbacks) for inputs in input_list]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html"}
{"id": "1dd1e757ea03-0", "text": "Source code for langchain.chains.sequential\n\"\"\"Chain pipeline where the outputs of one step feed directly into next.\"\"\"\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utils.input import get_color_mapping\n[docs]class SequentialChain(Chain):\n    \"\"\"Chain where the outputs of one chain feed directly into next.\"\"\"\n    chains: List[Chain]\n    input_variables: List[str]\n    output_variables: List[str]  #: :meta private:\n    return_all: bool = False\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return expected input keys to the chain.\n        :meta private:\n        \"\"\"\n        return self.input_variables\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return output key.\n        :meta private:\n        \"\"\"\n        return self.output_variables\n    @root_validator(pre=True)\n    def validate_chains(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the correct inputs exist for all chains.\"\"\"\n        chains = values[\"chains\"]\n        input_variables = values[\"input_variables\"]\n        memory_keys = list()\n        if \"memory\" in values and values[\"memory\"] is not None:\n            \"\"\"Validate that prompt input variables are consistent.\"\"\"\n            memory_keys = values[\"memory\"].memory_variables\n            if set(input_variables).intersection(set(memory_keys)):\n                overlapping_keys = set(input_variables) & set(memory_keys)\n                raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html"}
{"id": "1dd1e757ea03-1", "text": "overlapping_keys = set(input_variables) & set(memory_keys)\n                raise ValueError(\n                    f\"The input key(s) {''.join(overlapping_keys)} are found \"\n                    f\"in the Memory keys ({memory_keys}) - please use input and \"\n                    f\"memory keys that don't overlap.\"\n                )\n        known_variables = set(input_variables + memory_keys)\n        for chain in chains:\n            missing_vars = set(chain.input_keys).difference(known_variables)\n            if chain.memory:\n                missing_vars = missing_vars.difference(chain.memory.memory_variables)\n            if missing_vars:\n                raise ValueError(\n                    f\"Missing required input keys: {missing_vars}, \"\n                    f\"only had {known_variables}\"\n                )\n            overlapping_keys = known_variables.intersection(chain.output_keys)\n            if overlapping_keys:\n                raise ValueError(\n                    f\"Chain returned keys that already exist: {overlapping_keys}\"\n                )\n            known_variables |= set(chain.output_keys)\n        if \"output_variables\" not in values:\n            if values.get(\"return_all\", False):\n                output_keys = known_variables.difference(input_variables)\n            else:\n                output_keys = chains[-1].output_keys\n            values[\"output_variables\"] = output_keys\n        else:\n            missing_vars = set(values[\"output_variables\"]).difference(known_variables)\n            if missing_vars:\n                raise ValueError(\n                    f\"Expected output variables that were not found: {missing_vars}.\"\n                )\n        return values\n    def _call(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        known_values = inputs.copy()\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html"}
{"id": "1dd1e757ea03-2", "text": "_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        for i, chain in enumerate(self.chains):\n            callbacks = _run_manager.get_child()\n            outputs = chain(known_values, return_only_outputs=True, callbacks=callbacks)\n            known_values.update(outputs)\n        return {k: known_values[k] for k in self.output_variables}\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        known_values = inputs.copy()\n        _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        for i, chain in enumerate(self.chains):\n            outputs = await chain.acall(\n                known_values, return_only_outputs=True, callbacks=callbacks\n            )\n            known_values.update(outputs)\n        return {k: known_values[k] for k in self.output_variables}\n[docs]class SimpleSequentialChain(Chain):\n    \"\"\"Simple chain where the outputs of one step feed directly into next.\"\"\"\n    chains: List[Chain]\n    strip_outputs: bool = False\n    input_key: str = \"input\"  #: :meta private:\n    output_key: str = \"output\"  #: :meta private:\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return output key.\n        :meta private:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html"}
{"id": "1dd1e757ea03-3", "text": "\"\"\"Return output key.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n    @root_validator()\n    def validate_chains(cls, values: Dict) -> Dict:\n        \"\"\"Validate that chains are all single input/output.\"\"\"\n        for chain in values[\"chains\"]:\n            if len(chain.input_keys) != 1:\n                raise ValueError(\n                    \"Chains used in SimplePipeline should all have one input, got \"\n                    f\"{chain} with {len(chain.input_keys)} inputs.\"\n                )\n            if len(chain.output_keys) != 1:\n                raise ValueError(\n                    \"Chains used in SimplePipeline should all have one output, got \"\n                    f\"{chain} with {len(chain.output_keys)} outputs.\"\n                )\n        return values\n    def _call(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        _input = inputs[self.input_key]\n        color_mapping = get_color_mapping([str(i) for i in range(len(self.chains))])\n        for i, chain in enumerate(self.chains):\n            _input = chain.run(_input, callbacks=_run_manager.get_child(f\"step_{i+1}\"))\n            if self.strip_outputs:\n                _input = _input.strip()\n            _run_manager.on_text(\n                _input, color=color_mapping[str(i)], end=\"\\n\", verbose=self.verbose\n            )\n        return {self.output_key: _input}\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html"}
{"id": "1dd1e757ea03-4", "text": "run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()\n        _input = inputs[self.input_key]\n        color_mapping = get_color_mapping([str(i) for i in range(len(self.chains))])\n        for i, chain in enumerate(self.chains):\n            _input = await chain.arun(\n                _input, callbacks=_run_manager.get_child(f\"step_{i+1}\")\n            )\n            if self.strip_outputs:\n                _input = _input.strip()\n            await _run_manager.on_text(\n                _input, color=color_mapping[str(i)], end=\"\\n\", verbose=self.verbose\n            )\n        return {self.output_key: _input}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html"}
{"id": "e18fde16c33a-0", "text": "Source code for langchain.chains.loading\n\"\"\"Functionality for loading chains.\"\"\"\nimport json\nfrom pathlib import Path\nfrom typing import Any, Union\nimport yaml\nfrom langchain.chains import ReduceDocumentsChain\nfrom langchain.chains.api.base import APIChain\nfrom langchain.chains.base import Chain\nfrom langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain\nfrom langchain.chains.combine_documents.map_rerank import MapRerankDocumentsChain\nfrom langchain.chains.combine_documents.refine import RefineDocumentsChain\nfrom langchain.chains.combine_documents.stuff import StuffDocumentsChain\nfrom langchain.chains.graph_qa.cypher import GraphCypherQAChain\nfrom langchain.chains.hyde.base import HypotheticalDocumentEmbedder\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.llm_checker.base import LLMCheckerChain\nfrom langchain.chains.llm_math.base import LLMMathChain\nfrom langchain.chains.llm_requests import LLMRequestsChain\nfrom langchain.chains.qa_with_sources.base import QAWithSourcesChain\nfrom langchain.chains.qa_with_sources.retrieval import RetrievalQAWithSourcesChain\nfrom langchain.chains.qa_with_sources.vector_db import VectorDBQAWithSourcesChain\nfrom langchain.chains.retrieval_qa.base import RetrievalQA, VectorDBQA\nfrom langchain.llms.loading import load_llm, load_llm_from_config\nfrom langchain.prompts.loading import (\n    _load_output_parser,\n    load_prompt,\n    load_prompt_from_config,\n)\nfrom langchain.utilities.loading import try_load_from_hub\nURL_BASE = \"https://raw.githubusercontent.com/hwchase17/langchain-hub/master/chains/\"\ndef _load_llm_chain(config: dict, **kwargs: Any) -> LLMChain:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-1", "text": "\"\"\"Load LLM chain from config dict.\"\"\"\n    if \"llm\" in config:\n        llm_config = config.pop(\"llm\")\n        llm = load_llm_from_config(llm_config)\n    elif \"llm_path\" in config:\n        llm = load_llm(config.pop(\"llm_path\"))\n    else:\n        raise ValueError(\"One of `llm` or `llm_path` must be present.\")\n    if \"prompt\" in config:\n        prompt_config = config.pop(\"prompt\")\n        prompt = load_prompt_from_config(prompt_config)\n    elif \"prompt_path\" in config:\n        prompt = load_prompt(config.pop(\"prompt_path\"))\n    else:\n        raise ValueError(\"One of `prompt` or `prompt_path` must be present.\")\n    _load_output_parser(config)\n    return LLMChain(llm=llm, prompt=prompt, **config)\ndef _load_hyde_chain(config: dict, **kwargs: Any) -> HypotheticalDocumentEmbedder:\n    \"\"\"Load hypothetical document embedder chain from config dict.\"\"\"\n    if \"llm_chain\" in config:\n        llm_chain_config = config.pop(\"llm_chain\")\n        llm_chain = load_chain_from_config(llm_chain_config)\n    elif \"llm_chain_path\" in config:\n        llm_chain = load_chain(config.pop(\"llm_chain_path\"))\n    else:\n        raise ValueError(\"One of `llm_chain` or `llm_chain_path` must be present.\")\n    if \"embeddings\" in kwargs:\n        embeddings = kwargs.pop(\"embeddings\")\n    else:\n        raise ValueError(\"`embeddings` must be present.\")\n    return HypotheticalDocumentEmbedder(\n        llm_chain=llm_chain, base_embeddings=embeddings, **config\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-2", "text": ")\ndef _load_stuff_documents_chain(config: dict, **kwargs: Any) -> StuffDocumentsChain:\n    if \"llm_chain\" in config:\n        llm_chain_config = config.pop(\"llm_chain\")\n        llm_chain = load_chain_from_config(llm_chain_config)\n    elif \"llm_chain_path\" in config:\n        llm_chain = load_chain(config.pop(\"llm_chain_path\"))\n    else:\n        raise ValueError(\"One of `llm_chain` or `llm_chain_path` must be present.\")\n    if not isinstance(llm_chain, LLMChain):\n        raise ValueError(f\"Expected LLMChain, got {llm_chain}\")\n    if \"document_prompt\" in config:\n        prompt_config = config.pop(\"document_prompt\")\n        document_prompt = load_prompt_from_config(prompt_config)\n    elif \"document_prompt_path\" in config:\n        document_prompt = load_prompt(config.pop(\"document_prompt_path\"))\n    else:\n        raise ValueError(\n            \"One of `document_prompt` or `document_prompt_path` must be present.\"\n        )\n    return StuffDocumentsChain(\n        llm_chain=llm_chain, document_prompt=document_prompt, **config\n    )\ndef _load_map_reduce_documents_chain(\n    config: dict, **kwargs: Any\n) -> MapReduceDocumentsChain:\n    if \"llm_chain\" in config:\n        llm_chain_config = config.pop(\"llm_chain\")\n        llm_chain = load_chain_from_config(llm_chain_config)\n    elif \"llm_chain_path\" in config:\n        llm_chain = load_chain(config.pop(\"llm_chain_path\"))\n    else:\n        raise ValueError(\"One of `llm_chain` or `llm_chain_path` must be present.\")\n    if not isinstance(llm_chain, LLMChain):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-3", "text": "if not isinstance(llm_chain, LLMChain):\n        raise ValueError(f\"Expected LLMChain, got {llm_chain}\")\n    if \"reduce_documents_chain\" in config:\n        reduce_documents_chain = load_chain_from_config(\n            config.pop(\"reduce_documents_chain\")\n        )\n    elif \"reduce_documents_chain_path\" in config:\n        reduce_documents_chain = load_chain(config.pop(\"reduce_documents_chain_path\"))\n    else:\n        reduce_documents_chain = _load_reduce_documents_chain(config)\n    return MapReduceDocumentsChain(\n        llm_chain=llm_chain,\n        reduce_documents_chain=reduce_documents_chain,\n        **config,\n    )\ndef _load_reduce_documents_chain(config: dict, **kwargs: Any) -> ReduceDocumentsChain:\n    combine_documents_chain = None\n    collapse_documents_chain = None\n    if \"combine_documents_chain\" in config:\n        combine_document_chain_config = config.pop(\"combine_documents_chain\")\n        combine_documents_chain = load_chain_from_config(combine_document_chain_config)\n    elif \"combine_document_chain\" in config:\n        combine_document_chain_config = config.pop(\"combine_document_chain\")\n        combine_documents_chain = load_chain_from_config(combine_document_chain_config)\n    elif \"combine_documents_chain_path\" in config:\n        combine_documents_chain = load_chain(config.pop(\"combine_documents_chain_path\"))\n    elif \"combine_document_chain_path\" in config:\n        combine_documents_chain = load_chain(config.pop(\"combine_document_chain_path\"))\n    else:\n        raise ValueError(\n            \"One of `combine_documents_chain` or \"\n            \"`combine_documents_chain_path` must be present.\"\n        )\n    if \"collapse_documents_chain\" in config:\n        collapse_document_chain_config = config.pop(\"collapse_documents_chain\")\n        if collapse_document_chain_config is None:\n            collapse_documents_chain = None\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-4", "text": "collapse_documents_chain = None\n        else:\n            collapse_documents_chain = load_chain_from_config(\n                collapse_document_chain_config\n            )\n    elif \"collapse_documents_chain_path\" in config:\n        collapse_documents_chain = load_chain(\n            config.pop(\"collapse_documents_chain_path\")\n        )\n    elif \"collapse_document_chain\" in config:\n        collapse_document_chain_config = config.pop(\"collapse_document_chain\")\n        if collapse_document_chain_config is None:\n            collapse_documents_chain = None\n        else:\n            collapse_documents_chain = load_chain_from_config(\n                collapse_document_chain_config\n            )\n    elif \"collapse_document_chain_path\" in config:\n        collapse_documents_chain = load_chain(\n            config.pop(\"collapse_document_chain_path\")\n        )\n    return ReduceDocumentsChain(\n        combine_documents_chain=combine_documents_chain,\n        collapse_documents_chain=collapse_documents_chain,\n        **config,\n    )\ndef _load_llm_bash_chain(config: dict, **kwargs: Any) -> Any:\n    from langchain_experimental.llm_bash.base import LLMBashChain\n    llm_chain = None\n    if \"llm_chain\" in config:\n        llm_chain_config = config.pop(\"llm_chain\")\n        llm_chain = load_chain_from_config(llm_chain_config)\n    elif \"llm_chain_path\" in config:\n        llm_chain = load_chain(config.pop(\"llm_chain_path\"))\n    # llm attribute is deprecated in favor of llm_chain, here to support old configs\n    elif \"llm\" in config:\n        llm_config = config.pop(\"llm\")\n        llm = load_llm_from_config(llm_config)\n    # llm_path attribute is deprecated in favor of llm_chain_path,\n    # its to support old configs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-5", "text": "# its to support old configs\n    elif \"llm_path\" in config:\n        llm = load_llm(config.pop(\"llm_path\"))\n    else:\n        raise ValueError(\"One of `llm_chain` or `llm_chain_path` must be present.\")\n    if \"prompt\" in config:\n        prompt_config = config.pop(\"prompt\")\n        prompt = load_prompt_from_config(prompt_config)\n    elif \"prompt_path\" in config:\n        prompt = load_prompt(config.pop(\"prompt_path\"))\n    if llm_chain:\n        return LLMBashChain(llm_chain=llm_chain, prompt=prompt, **config)\n    else:\n        return LLMBashChain(llm=llm, prompt=prompt, **config)\ndef _load_llm_checker_chain(config: dict, **kwargs: Any) -> LLMCheckerChain:\n    if \"llm\" in config:\n        llm_config = config.pop(\"llm\")\n        llm = load_llm_from_config(llm_config)\n    elif \"llm_path\" in config:\n        llm = load_llm(config.pop(\"llm_path\"))\n    else:\n        raise ValueError(\"One of `llm` or `llm_path` must be present.\")\n    if \"create_draft_answer_prompt\" in config:\n        create_draft_answer_prompt_config = config.pop(\"create_draft_answer_prompt\")\n        create_draft_answer_prompt = load_prompt_from_config(\n            create_draft_answer_prompt_config\n        )\n    elif \"create_draft_answer_prompt_path\" in config:\n        create_draft_answer_prompt = load_prompt(\n            config.pop(\"create_draft_answer_prompt_path\")\n        )\n    if \"list_assertions_prompt\" in config:\n        list_assertions_prompt_config = config.pop(\"list_assertions_prompt\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-6", "text": "list_assertions_prompt_config = config.pop(\"list_assertions_prompt\")\n        list_assertions_prompt = load_prompt_from_config(list_assertions_prompt_config)\n    elif \"list_assertions_prompt_path\" in config:\n        list_assertions_prompt = load_prompt(config.pop(\"list_assertions_prompt_path\"))\n    if \"check_assertions_prompt\" in config:\n        check_assertions_prompt_config = config.pop(\"check_assertions_prompt\")\n        check_assertions_prompt = load_prompt_from_config(\n            check_assertions_prompt_config\n        )\n    elif \"check_assertions_prompt_path\" in config:\n        check_assertions_prompt = load_prompt(\n            config.pop(\"check_assertions_prompt_path\")\n        )\n    if \"revised_answer_prompt\" in config:\n        revised_answer_prompt_config = config.pop(\"revised_answer_prompt\")\n        revised_answer_prompt = load_prompt_from_config(revised_answer_prompt_config)\n    elif \"revised_answer_prompt_path\" in config:\n        revised_answer_prompt = load_prompt(config.pop(\"revised_answer_prompt_path\"))\n    return LLMCheckerChain(\n        llm=llm,\n        create_draft_answer_prompt=create_draft_answer_prompt,\n        list_assertions_prompt=list_assertions_prompt,\n        check_assertions_prompt=check_assertions_prompt,\n        revised_answer_prompt=revised_answer_prompt,\n        **config,\n    )\ndef _load_llm_math_chain(config: dict, **kwargs: Any) -> LLMMathChain:\n    llm_chain = None\n    if \"llm_chain\" in config:\n        llm_chain_config = config.pop(\"llm_chain\")\n        llm_chain = load_chain_from_config(llm_chain_config)\n    elif \"llm_chain_path\" in config:\n        llm_chain = load_chain(config.pop(\"llm_chain_path\"))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-7", "text": "llm_chain = load_chain(config.pop(\"llm_chain_path\"))\n    # llm attribute is deprecated in favor of llm_chain, here to support old configs\n    elif \"llm\" in config:\n        llm_config = config.pop(\"llm\")\n        llm = load_llm_from_config(llm_config)\n    # llm_path attribute is deprecated in favor of llm_chain_path,\n    # its to support old configs\n    elif \"llm_path\" in config:\n        llm = load_llm(config.pop(\"llm_path\"))\n    else:\n        raise ValueError(\"One of `llm_chain` or `llm_chain_path` must be present.\")\n    if \"prompt\" in config:\n        prompt_config = config.pop(\"prompt\")\n        prompt = load_prompt_from_config(prompt_config)\n    elif \"prompt_path\" in config:\n        prompt = load_prompt(config.pop(\"prompt_path\"))\n    if llm_chain:\n        return LLMMathChain(llm_chain=llm_chain, prompt=prompt, **config)\n    else:\n        return LLMMathChain(llm=llm, prompt=prompt, **config)\ndef _load_map_rerank_documents_chain(\n    config: dict, **kwargs: Any\n) -> MapRerankDocumentsChain:\n    if \"llm_chain\" in config:\n        llm_chain_config = config.pop(\"llm_chain\")\n        llm_chain = load_chain_from_config(llm_chain_config)\n    elif \"llm_chain_path\" in config:\n        llm_chain = load_chain(config.pop(\"llm_chain_path\"))\n    else:\n        raise ValueError(\"One of `llm_chain` or `llm_chain_path` must be present.\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-8", "text": "return MapRerankDocumentsChain(llm_chain=llm_chain, **config)\ndef _load_pal_chain(config: dict, **kwargs: Any) -> Any:\n    from langchain_experimental.pal_chain import PALChain\n    if \"llm_chain\" in config:\n        llm_chain_config = config.pop(\"llm_chain\")\n        llm_chain = load_chain_from_config(llm_chain_config)\n    elif \"llm_chain_path\" in config:\n        llm_chain = load_chain(config.pop(\"llm_chain_path\"))\n    else:\n        raise ValueError(\"One of `llm_chain` or `llm_chain_path` must be present.\")\n    return PALChain(llm_chain=llm_chain, **config)\ndef _load_refine_documents_chain(config: dict, **kwargs: Any) -> RefineDocumentsChain:\n    if \"initial_llm_chain\" in config:\n        initial_llm_chain_config = config.pop(\"initial_llm_chain\")\n        initial_llm_chain = load_chain_from_config(initial_llm_chain_config)\n    elif \"initial_llm_chain_path\" in config:\n        initial_llm_chain = load_chain(config.pop(\"initial_llm_chain_path\"))\n    else:\n        raise ValueError(\n            \"One of `initial_llm_chain` or `initial_llm_chain_path` must be present.\"\n        )\n    if \"refine_llm_chain\" in config:\n        refine_llm_chain_config = config.pop(\"refine_llm_chain\")\n        refine_llm_chain = load_chain_from_config(refine_llm_chain_config)\n    elif \"refine_llm_chain_path\" in config:\n        refine_llm_chain = load_chain(config.pop(\"refine_llm_chain_path\"))\n    else:\n        raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-9", "text": "else:\n        raise ValueError(\n            \"One of `refine_llm_chain` or `refine_llm_chain_path` must be present.\"\n        )\n    if \"document_prompt\" in config:\n        prompt_config = config.pop(\"document_prompt\")\n        document_prompt = load_prompt_from_config(prompt_config)\n    elif \"document_prompt_path\" in config:\n        document_prompt = load_prompt(config.pop(\"document_prompt_path\"))\n    return RefineDocumentsChain(\n        initial_llm_chain=initial_llm_chain,\n        refine_llm_chain=refine_llm_chain,\n        document_prompt=document_prompt,\n        **config,\n    )\ndef _load_qa_with_sources_chain(config: dict, **kwargs: Any) -> QAWithSourcesChain:\n    if \"combine_documents_chain\" in config:\n        combine_documents_chain_config = config.pop(\"combine_documents_chain\")\n        combine_documents_chain = load_chain_from_config(combine_documents_chain_config)\n    elif \"combine_documents_chain_path\" in config:\n        combine_documents_chain = load_chain(config.pop(\"combine_documents_chain_path\"))\n    else:\n        raise ValueError(\n            \"One of `combine_documents_chain` or \"\n            \"`combine_documents_chain_path` must be present.\"\n        )\n    return QAWithSourcesChain(combine_documents_chain=combine_documents_chain, **config)\ndef _load_sql_database_chain(config: dict, **kwargs: Any) -> Any:\n    from langchain_experimental.sql import SQLDatabaseChain\n    if \"database\" in kwargs:\n        database = kwargs.pop(\"database\")\n    else:\n        raise ValueError(\"`database` must be present.\")\n    if \"llm_chain\" in config:\n        llm_chain_config = config.pop(\"llm_chain\")\n        chain = load_chain_from_config(llm_chain_config)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-10", "text": "chain = load_chain_from_config(llm_chain_config)\n        return SQLDatabaseChain(llm_chain=chain, database=database, **config)\n    if \"llm\" in config:\n        llm_config = config.pop(\"llm\")\n        llm = load_llm_from_config(llm_config)\n    elif \"llm_path\" in config:\n        llm = load_llm(config.pop(\"llm_path\"))\n    else:\n        raise ValueError(\"One of `llm` or `llm_path` must be present.\")\n    if \"prompt\" in config:\n        prompt_config = config.pop(\"prompt\")\n        prompt = load_prompt_from_config(prompt_config)\n    else:\n        prompt = None\n    return SQLDatabaseChain.from_llm(llm, database, prompt=prompt, **config)\ndef _load_vector_db_qa_with_sources_chain(\n    config: dict, **kwargs: Any\n) -> VectorDBQAWithSourcesChain:\n    if \"vectorstore\" in kwargs:\n        vectorstore = kwargs.pop(\"vectorstore\")\n    else:\n        raise ValueError(\"`vectorstore` must be present.\")\n    if \"combine_documents_chain\" in config:\n        combine_documents_chain_config = config.pop(\"combine_documents_chain\")\n        combine_documents_chain = load_chain_from_config(combine_documents_chain_config)\n    elif \"combine_documents_chain_path\" in config:\n        combine_documents_chain = load_chain(config.pop(\"combine_documents_chain_path\"))\n    else:\n        raise ValueError(\n            \"One of `combine_documents_chain` or \"\n            \"`combine_documents_chain_path` must be present.\"\n        )\n    return VectorDBQAWithSourcesChain(\n        combine_documents_chain=combine_documents_chain,\n        vectorstore=vectorstore,\n        **config,\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-11", "text": "vectorstore=vectorstore,\n        **config,\n    )\ndef _load_retrieval_qa(config: dict, **kwargs: Any) -> RetrievalQA:\n    if \"retriever\" in kwargs:\n        retriever = kwargs.pop(\"retriever\")\n    else:\n        raise ValueError(\"`retriever` must be present.\")\n    if \"combine_documents_chain\" in config:\n        combine_documents_chain_config = config.pop(\"combine_documents_chain\")\n        combine_documents_chain = load_chain_from_config(combine_documents_chain_config)\n    elif \"combine_documents_chain_path\" in config:\n        combine_documents_chain = load_chain(config.pop(\"combine_documents_chain_path\"))\n    else:\n        raise ValueError(\n            \"One of `combine_documents_chain` or \"\n            \"`combine_documents_chain_path` must be present.\"\n        )\n    return RetrievalQA(\n        combine_documents_chain=combine_documents_chain,\n        retriever=retriever,\n        **config,\n    )\ndef _load_retrieval_qa_with_sources_chain(\n    config: dict, **kwargs: Any\n) -> RetrievalQAWithSourcesChain:\n    if \"retriever\" in kwargs:\n        retriever = kwargs.pop(\"retriever\")\n    else:\n        raise ValueError(\"`retriever` must be present.\")\n    if \"combine_documents_chain\" in config:\n        combine_documents_chain_config = config.pop(\"combine_documents_chain\")\n        combine_documents_chain = load_chain_from_config(combine_documents_chain_config)\n    elif \"combine_documents_chain_path\" in config:\n        combine_documents_chain = load_chain(config.pop(\"combine_documents_chain_path\"))\n    else:\n        raise ValueError(\n            \"One of `combine_documents_chain` or \"\n            \"`combine_documents_chain_path` must be present.\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-12", "text": "\"`combine_documents_chain_path` must be present.\"\n        )\n    return RetrievalQAWithSourcesChain(\n        combine_documents_chain=combine_documents_chain,\n        retriever=retriever,\n        **config,\n    )\ndef _load_vector_db_qa(config: dict, **kwargs: Any) -> VectorDBQA:\n    if \"vectorstore\" in kwargs:\n        vectorstore = kwargs.pop(\"vectorstore\")\n    else:\n        raise ValueError(\"`vectorstore` must be present.\")\n    if \"combine_documents_chain\" in config:\n        combine_documents_chain_config = config.pop(\"combine_documents_chain\")\n        combine_documents_chain = load_chain_from_config(combine_documents_chain_config)\n    elif \"combine_documents_chain_path\" in config:\n        combine_documents_chain = load_chain(config.pop(\"combine_documents_chain_path\"))\n    else:\n        raise ValueError(\n            \"One of `combine_documents_chain` or \"\n            \"`combine_documents_chain_path` must be present.\"\n        )\n    return VectorDBQA(\n        combine_documents_chain=combine_documents_chain,\n        vectorstore=vectorstore,\n        **config,\n    )\ndef _load_graph_cypher_chain(config: dict, **kwargs: Any) -> GraphCypherQAChain:\n    if \"graph\" in kwargs:\n        graph = kwargs.pop(\"graph\")\n    else:\n        raise ValueError(\"`graph` must be present.\")\n    if \"cypher_generation_chain\" in config:\n        cypher_generation_chain_config = config.pop(\"cypher_generation_chain\")\n        cypher_generation_chain = load_chain_from_config(cypher_generation_chain_config)\n    else:\n        raise ValueError(\"`cypher_generation_chain` must be present.\")\n    if \"qa_chain\" in config:\n        qa_chain_config = config.pop(\"qa_chain\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-13", "text": "qa_chain_config = config.pop(\"qa_chain\")\n        qa_chain = load_chain_from_config(qa_chain_config)\n    else:\n        raise ValueError(\"`qa_chain` must be present.\")\n    return GraphCypherQAChain(\n        graph=graph,\n        cypher_generation_chain=cypher_generation_chain,\n        qa_chain=qa_chain,\n        **config,\n    )\ndef _load_api_chain(config: dict, **kwargs: Any) -> APIChain:\n    if \"api_request_chain\" in config:\n        api_request_chain_config = config.pop(\"api_request_chain\")\n        api_request_chain = load_chain_from_config(api_request_chain_config)\n    elif \"api_request_chain_path\" in config:\n        api_request_chain = load_chain(config.pop(\"api_request_chain_path\"))\n    else:\n        raise ValueError(\n            \"One of `api_request_chain` or `api_request_chain_path` must be present.\"\n        )\n    if \"api_answer_chain\" in config:\n        api_answer_chain_config = config.pop(\"api_answer_chain\")\n        api_answer_chain = load_chain_from_config(api_answer_chain_config)\n    elif \"api_answer_chain_path\" in config:\n        api_answer_chain = load_chain(config.pop(\"api_answer_chain_path\"))\n    else:\n        raise ValueError(\n            \"One of `api_answer_chain` or `api_answer_chain_path` must be present.\"\n        )\n    if \"requests_wrapper\" in kwargs:\n        requests_wrapper = kwargs.pop(\"requests_wrapper\")\n    else:\n        raise ValueError(\"`requests_wrapper` must be present.\")\n    return APIChain(\n        api_request_chain=api_request_chain,\n        api_answer_chain=api_answer_chain,\n        requests_wrapper=requests_wrapper,\n        **config,\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-14", "text": "requests_wrapper=requests_wrapper,\n        **config,\n    )\ndef _load_llm_requests_chain(config: dict, **kwargs: Any) -> LLMRequestsChain:\n    if \"llm_chain\" in config:\n        llm_chain_config = config.pop(\"llm_chain\")\n        llm_chain = load_chain_from_config(llm_chain_config)\n    elif \"llm_chain_path\" in config:\n        llm_chain = load_chain(config.pop(\"llm_chain_path\"))\n    else:\n        raise ValueError(\"One of `llm_chain` or `llm_chain_path` must be present.\")\n    if \"requests_wrapper\" in kwargs:\n        requests_wrapper = kwargs.pop(\"requests_wrapper\")\n        return LLMRequestsChain(\n            llm_chain=llm_chain, requests_wrapper=requests_wrapper, **config\n        )\n    else:\n        return LLMRequestsChain(llm_chain=llm_chain, **config)\ntype_to_loader_dict = {\n    \"api_chain\": _load_api_chain,\n    \"hyde_chain\": _load_hyde_chain,\n    \"llm_chain\": _load_llm_chain,\n    \"llm_bash_chain\": _load_llm_bash_chain,\n    \"llm_checker_chain\": _load_llm_checker_chain,\n    \"llm_math_chain\": _load_llm_math_chain,\n    \"llm_requests_chain\": _load_llm_requests_chain,\n    \"pal_chain\": _load_pal_chain,\n    \"qa_with_sources_chain\": _load_qa_with_sources_chain,\n    \"stuff_documents_chain\": _load_stuff_documents_chain,\n    \"map_reduce_documents_chain\": _load_map_reduce_documents_chain,\n    \"reduce_documents_chain\": _load_reduce_documents_chain,\n    \"map_rerank_documents_chain\": _load_map_rerank_documents_chain,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-15", "text": "\"map_rerank_documents_chain\": _load_map_rerank_documents_chain,\n    \"refine_documents_chain\": _load_refine_documents_chain,\n    \"sql_database_chain\": _load_sql_database_chain,\n    \"vector_db_qa_with_sources_chain\": _load_vector_db_qa_with_sources_chain,\n    \"vector_db_qa\": _load_vector_db_qa,\n    \"retrieval_qa\": _load_retrieval_qa,\n    \"retrieval_qa_with_sources_chain\": _load_retrieval_qa_with_sources_chain,\n    \"graph_cypher_chain\": _load_graph_cypher_chain,\n}\n[docs]def load_chain_from_config(config: dict, **kwargs: Any) -> Chain:\n    \"\"\"Load chain from Config Dict.\"\"\"\n    if \"_type\" not in config:\n        raise ValueError(\"Must specify a chain Type in config\")\n    config_type = config.pop(\"_type\")\n    if config_type not in type_to_loader_dict:\n        raise ValueError(f\"Loading {config_type} chain not supported\")\n    chain_loader = type_to_loader_dict[config_type]\n    return chain_loader(config, **kwargs)\n[docs]def load_chain(path: Union[str, Path], **kwargs: Any) -> Chain:\n    \"\"\"Unified method for loading a chain from LangChainHub or local fs.\"\"\"\n    if hub_result := try_load_from_hub(\n        path, _load_chain_from_file, \"chains\", {\"json\", \"yaml\"}, **kwargs\n    ):\n        return hub_result\n    else:\n        return _load_chain_from_file(path, **kwargs)\ndef _load_chain_from_file(file: Union[str, Path], **kwargs: Any) -> Chain:\n    \"\"\"Load chain from file.\"\"\"\n    # Convert file to Path object.\n    if isinstance(file, str):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "e18fde16c33a-16", "text": "# Convert file to Path object.\n    if isinstance(file, str):\n        file_path = Path(file)\n    else:\n        file_path = file\n    # Load from either json or yaml.\n    if file_path.suffix == \".json\":\n        with open(file_path) as f:\n            config = json.load(f)\n    elif file_path.suffix == \".yaml\":\n        with open(file_path, \"r\") as f:\n            config = yaml.safe_load(f)\n    else:\n        raise ValueError(\"File type must be json or yaml\")\n    # Override default 'verbose' and 'memory' for the chain\n    if \"verbose\" in kwargs:\n        config[\"verbose\"] = kwargs.pop(\"verbose\")\n    if \"memory\" in kwargs:\n        config[\"memory\"] = kwargs.pop(\"memory\")\n    # Load the chain from the config now.\n    return load_chain_from_config(config, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html"}
{"id": "cb7c4f6763ea-0", "text": "Source code for langchain.chains.transform\n\"\"\"Chain that runs an arbitrary python function.\"\"\"\nimport functools\nimport logging\nfrom typing import Any, Awaitable, Callable, Dict, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.pydantic_v1 import Field\nlogger = logging.getLogger(__name__)\n[docs]class TransformChain(Chain):\n    \"\"\"Chain that transforms the chain output.\n    Example:\n        .. code-block:: python\n            from langchain.chains import TransformChain\n            transform_chain = TransformChain(input_variables=[\"text\"],\n             output_variables[\"entities\"], transform=func())\n    \"\"\"\n    input_variables: List[str]\n    \"\"\"The keys expected by the transform's input dictionary.\"\"\"\n    output_variables: List[str]\n    \"\"\"The keys returned by the transform's output dictionary.\"\"\"\n    transform_cb: Callable[[Dict[str, str]], Dict[str, str]] = Field(alias=\"transform\")\n    \"\"\"The transform function.\"\"\"\n    atransform_cb: Optional[\n        Callable[[Dict[str, Any]], Awaitable[Dict[str, Any]]]\n    ] = Field(None, alias=\"atransform\")\n    \"\"\"The async coroutine transform function.\"\"\"\n    @staticmethod\n    @functools.lru_cache\n    def _log_once(msg: str) -> None:\n        \"\"\"Log a message once.\n        :meta private:\n        \"\"\"\n        logger.warning(msg)\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input keys.\n        :meta private:\n        \"\"\"\n        return self.input_variables\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return output keys.\n        :meta private:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/transform.html"}
{"id": "cb7c4f6763ea-1", "text": "\"\"\"Return output keys.\n        :meta private:\n        \"\"\"\n        return self.output_variables\n    def _call(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        return self.transform_cb(inputs)\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        if self.atransform_cb is not None:\n            return await self.atransform_cb(inputs)\n        else:\n            self._log_once(\n                \"TransformChain's atransform is not provided, falling\"\n                \" back to synchronous transform\"\n            )\n            return self.transform_cb(inputs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/transform.html"}
{"id": "6893ed29458b-0", "text": "Source code for langchain.chains.mapreduce\n\"\"\"Map-reduce chain.\nSplits up a document, sends the smaller parts to the LLM with one prompt,\nthen combines the results with another one.\n\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun, Callbacks\nfrom langchain.chains import ReduceDocumentsChain\nfrom langchain.chains.base import Chain\nfrom langchain.chains.combine_documents.base import BaseCombineDocumentsChain\nfrom langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain\nfrom langchain.chains.combine_documents.stuff import StuffDocumentsChain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import Extra\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.text_splitter import TextSplitter\n[docs]class MapReduceChain(Chain):\n    \"\"\"Map-reduce chain.\"\"\"\n    combine_documents_chain: BaseCombineDocumentsChain\n    \"\"\"Chain to use to combine documents.\"\"\"\n    text_splitter: TextSplitter\n    \"\"\"Text splitter to use.\"\"\"\n    input_key: str = \"input_text\"  #: :meta private:\n    output_key: str = \"output_text\"  #: :meta private:\n[docs]    @classmethod\n    def from_params(\n        cls,\n        llm: BaseLanguageModel,\n        prompt: BasePromptTemplate,\n        text_splitter: TextSplitter,\n        callbacks: Callbacks = None,\n        combine_chain_kwargs: Optional[Mapping[str, Any]] = None,\n        reduce_chain_kwargs: Optional[Mapping[str, Any]] = None,\n        **kwargs: Any,\n    ) -> MapReduceChain:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html"}
{"id": "6893ed29458b-1", "text": "**kwargs: Any,\n    ) -> MapReduceChain:\n        \"\"\"Construct a map-reduce chain that uses the chain for map and reduce.\"\"\"\n        llm_chain = LLMChain(llm=llm, prompt=prompt, callbacks=callbacks)\n        stuff_chain = StuffDocumentsChain(\n            llm_chain=llm_chain,\n            callbacks=callbacks,\n            **(reduce_chain_kwargs if reduce_chain_kwargs else {}),\n        )\n        reduce_documents_chain = ReduceDocumentsChain(\n            combine_documents_chain=stuff_chain\n        )\n        combine_documents_chain = MapReduceDocumentsChain(\n            llm_chain=llm_chain,\n            reduce_documents_chain=reduce_documents_chain,\n            callbacks=callbacks,\n            **(combine_chain_kwargs if combine_chain_kwargs else {}),\n        )\n        return cls(\n            combine_documents_chain=combine_documents_chain,\n            text_splitter=text_splitter,\n            callbacks=callbacks,\n            **kwargs,\n        )\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return output key.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n    def _call(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        # Split the larger text into smaller chunks.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html"}
{"id": "6893ed29458b-2", "text": "# Split the larger text into smaller chunks.\n        doc_text = inputs.pop(self.input_key)\n        texts = self.text_splitter.split_text(doc_text)\n        docs = [Document(page_content=text) for text in texts]\n        _inputs: Dict[str, Any] = {\n            **inputs,\n            self.combine_documents_chain.input_key: docs,\n        }\n        outputs = self.combine_documents_chain.run(\n            _inputs, callbacks=_run_manager.get_child()\n        )\n        return {self.output_key: outputs}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html"}
{"id": "01f7da59136f-0", "text": "Source code for langchain.chains.llm_math.base\n\"\"\"Chain that interprets a prompt and executes python code to do math.\"\"\"\nfrom __future__ import annotations\nimport math\nimport re\nimport warnings\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.llm_math.prompt import PROMPT\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class LLMMathChain(Chain):\n    \"\"\"Chain that interprets a prompt and executes python code to do math.\n    Example:\n        .. code-block:: python\n            from langchain.chains import LLMMathChain\n            from langchain.llms import OpenAI\n            llm_math = LLMMathChain.from_llm(OpenAI())\n    \"\"\"\n    llm_chain: LLMChain\n    llm: Optional[BaseLanguageModel] = None\n    \"\"\"[Deprecated] LLM wrapper to use.\"\"\"\n    prompt: BasePromptTemplate = PROMPT\n    \"\"\"[Deprecated] Prompt to use to translate to python if necessary.\"\"\"\n    input_key: str = \"question\"  #: :meta private:\n    output_key: str = \"answer\"  #: :meta private:\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator(pre=True)\n    def raise_deprecation(cls, values: Dict) -> Dict:\n        try:\n            import numexpr  # noqa: F401\n        except ImportError:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html"}
{"id": "01f7da59136f-1", "text": "except ImportError:\n            raise ImportError(\n                \"LLMMathChain requires the numexpr package. \"\n                \"Please install it with `pip install numexpr`.\"\n            )\n        if \"llm\" in values:\n            warnings.warn(\n                \"Directly instantiating an LLMMathChain with an llm is deprecated. \"\n                \"Please instantiate with llm_chain argument or using the from_llm \"\n                \"class method.\"\n            )\n            if \"llm_chain\" not in values and values[\"llm\"] is not None:\n                prompt = values.get(\"prompt\", PROMPT)\n                values[\"llm_chain\"] = LLMChain(llm=values[\"llm\"], prompt=prompt)\n        return values\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Expect output key.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n    def _evaluate_expression(self, expression: str) -> str:\n        import numexpr  # noqa: F401\n        try:\n            local_dict = {\"pi\": math.pi, \"e\": math.e}\n            output = str(\n                numexpr.evaluate(\n                    expression.strip(),\n                    global_dict={},  # restrict access to globals\n                    local_dict=local_dict,  # add common mathematical functions\n                )\n            )\n        except Exception as e:\n            raise ValueError(\n                f'LLMMathChain._evaluate(\"{expression}\") raised error: {e}.'\n                \" Please try again with a valid numerical expression\"\n            )\n        # Remove any leading and trailing brackets from the output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html"}
{"id": "01f7da59136f-2", "text": ")\n        # Remove any leading and trailing brackets from the output\n        return re.sub(r\"^\\[|\\]$\", \"\", output)\n    def _process_llm_result(\n        self, llm_output: str, run_manager: CallbackManagerForChainRun\n    ) -> Dict[str, str]:\n        run_manager.on_text(llm_output, color=\"green\", verbose=self.verbose)\n        llm_output = llm_output.strip()\n        text_match = re.search(r\"^```text(.*?)```\", llm_output, re.DOTALL)\n        if text_match:\n            expression = text_match.group(1)\n            output = self._evaluate_expression(expression)\n            run_manager.on_text(\"\\nAnswer: \", verbose=self.verbose)\n            run_manager.on_text(output, color=\"yellow\", verbose=self.verbose)\n            answer = \"Answer: \" + output\n        elif llm_output.startswith(\"Answer:\"):\n            answer = llm_output\n        elif \"Answer:\" in llm_output:\n            answer = \"Answer: \" + llm_output.split(\"Answer:\")[-1]\n        else:\n            raise ValueError(f\"unknown format from LLM: {llm_output}\")\n        return {self.output_key: answer}\n    async def _aprocess_llm_result(\n        self,\n        llm_output: str,\n        run_manager: AsyncCallbackManagerForChainRun,\n    ) -> Dict[str, str]:\n        await run_manager.on_text(llm_output, color=\"green\", verbose=self.verbose)\n        llm_output = llm_output.strip()\n        text_match = re.search(r\"^```text(.*?)```\", llm_output, re.DOTALL)\n        if text_match:\n            expression = text_match.group(1)\n            output = self._evaluate_expression(expression)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html"}
{"id": "01f7da59136f-3", "text": "expression = text_match.group(1)\n            output = self._evaluate_expression(expression)\n            await run_manager.on_text(\"\\nAnswer: \", verbose=self.verbose)\n            await run_manager.on_text(output, color=\"yellow\", verbose=self.verbose)\n            answer = \"Answer: \" + output\n        elif llm_output.startswith(\"Answer:\"):\n            answer = llm_output\n        elif \"Answer:\" in llm_output:\n            answer = \"Answer: \" + llm_output.split(\"Answer:\")[-1]\n        else:\n            raise ValueError(f\"unknown format from LLM: {llm_output}\")\n        return {self.output_key: answer}\n    def _call(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        _run_manager.on_text(inputs[self.input_key])\n        llm_output = self.llm_chain.predict(\n            question=inputs[self.input_key],\n            stop=[\"```output\"],\n            callbacks=_run_manager.get_child(),\n        )\n        return self._process_llm_result(llm_output, _run_manager)\n    async def _acall(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()\n        await _run_manager.on_text(inputs[self.input_key])\n        llm_output = await self.llm_chain.apredict(\n            question=inputs[self.input_key],\n            stop=[\"```output\"],\n            callbacks=_run_manager.get_child(),\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html"}
{"id": "01f7da59136f-4", "text": "stop=[\"```output\"],\n            callbacks=_run_manager.get_child(),\n        )\n        return await self._aprocess_llm_result(llm_output, _run_manager)\n    @property\n    def _chain_type(self) -> str:\n        return \"llm_math_chain\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        prompt: BasePromptTemplate = PROMPT,\n        **kwargs: Any,\n    ) -> LLMMathChain:\n        llm_chain = LLMChain(llm=llm, prompt=prompt)\n        return cls(llm_chain=llm_chain, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html"}
{"id": "3c6b7392d94f-0", "text": "Source code for langchain.chains.sql_database.query\nfrom typing import List, Optional, TypedDict, Union\nfrom langchain.chains.sql_database.prompt import PROMPT, SQL_PROMPTS\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.output_parser import NoOpOutputParser\nfrom langchain.schema.prompt_template import BasePromptTemplate\nfrom langchain.schema.runnable import Runnable, RunnableParallel\nfrom langchain.utilities.sql_database import SQLDatabase\ndef _strip(text: str) -> str:\n    return text.strip()\n[docs]class SQLInput(TypedDict):\n    \"\"\"Input for a SQL Chain.\"\"\"\n    question: str\n[docs]class SQLInputWithTables(TypedDict):\n    \"\"\"Input for a SQL Chain.\"\"\"\n    question: str\n    table_names_to_use: List[str]\n[docs]def create_sql_query_chain(\n    llm: BaseLanguageModel,\n    db: SQLDatabase,\n    prompt: Optional[BasePromptTemplate] = None,\n    k: int = 5,\n) -> Runnable[Union[SQLInput, SQLInputWithTables], str]:\n    \"\"\"Create a chain that generates SQL queries.\n    *Security Note*: This chain generates SQL queries for the given database.\n        The SQLDatabase class provides a get_table_info method that can be used\n        to get column information as well as sample data from the table.\n        To mitigate risk of leaking sensitive data, limit permissions\n        to read and scope to the tables that are needed.\n        Optionally, use the SQLInputWithTables input type to specify which tables\n        are allowed to be accessed.\n        Control access to who can submit requests to this chain.\n        See https://python.langchain.com/docs/security for more information.\n    Args:\n        llm: The language model to use\n        db: The SQLDatabase to generate the query for", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sql_database/query.html"}
{"id": "3c6b7392d94f-1", "text": "db: The SQLDatabase to generate the query for\n        prompt: The prompt to use. If none is provided, will choose one\n            based on dialect. Defaults to None.\n        k: The number of results per select statement to return. Defaults to 5.\n    Returns:\n        A chain that takes in a question and generates a SQL query that answers\n        that question.\n    \"\"\"\n    if prompt is not None:\n        prompt_to_use = prompt\n    elif db.dialect in SQL_PROMPTS:\n        prompt_to_use = SQL_PROMPTS[db.dialect]\n    else:\n        prompt_to_use = PROMPT\n    inputs = {\n        \"input\": lambda x: x[\"question\"] + \"\\nSQLQuery: \",\n        \"top_k\": lambda _: k,\n        \"table_info\": lambda x: db.get_table_info(\n            table_names=x.get(\"table_names_to_use\")\n        ),\n    }\n    if \"dialect\" in prompt_to_use.input_variables:\n        inputs[\"dialect\"] = lambda _: (db.dialect, prompt_to_use)\n    return (\n        RunnableParallel(inputs)\n        | prompt_to_use\n        | llm.bind(stop=[\"\\nSQLResult:\"])\n        | NoOpOutputParser()\n        | _strip\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sql_database/query.html"}
{"id": "0233e51d43c2-0", "text": "Source code for langchain.chains.api.base\n\"\"\"Chain that makes API calls and summarizes the responses to answer a question.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple\nfrom urllib.parse import urlparse\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains.api.prompt import API_RESPONSE_PROMPT, API_URL_PROMPT\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.utilities.requests import TextRequestsWrapper\ndef _extract_scheme_and_domain(url: str) -> Tuple[str, str]:\n    \"\"\"Extract the scheme + domain from a given URL.\n    Args:\n        url (str): The input URL.\n    Returns:\n        return a 2-tuple of scheme and domain\n    \"\"\"\n    parsed_uri = urlparse(url)\n    return parsed_uri.scheme, parsed_uri.netloc\ndef _check_in_allowed_domain(url: str, limit_to_domains: Sequence[str]) -> bool:\n    \"\"\"Check if a URL is in the allowed domains.\n    Args:\n        url (str): The input URL.\n        limit_to_domains (Sequence[str]): The allowed domains.\n    Returns:\n        bool: True if the URL is in the allowed domains, False otherwise.\n    \"\"\"\n    scheme, domain = _extract_scheme_and_domain(url)\n    for allowed_domain in limit_to_domains:\n        allowed_scheme, allowed_domain = _extract_scheme_and_domain(allowed_domain)\n        if scheme == allowed_scheme and domain == allowed_domain:\n            return True\n    return False\n[docs]class APIChain(Chain):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html"}
{"id": "0233e51d43c2-1", "text": "return True\n    return False\n[docs]class APIChain(Chain):\n    \"\"\"Chain that makes API calls and summarizes the responses to answer a question.\n    *Security Note*: This API chain uses the requests toolkit\n        to make GET, POST, PATCH, PUT, and DELETE requests to an API.\n        Exercise care in who is allowed to use this chain. If exposing\n        to end users, consider that users will be able to make arbitrary\n        requests on behalf of the server hosting the code. For example,\n        users could ask the server to make a request to a private API\n        that is only accessible from the server.\n        Control access to who can submit issue requests using this toolkit and\n        what network access it has.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    api_request_chain: LLMChain\n    api_answer_chain: LLMChain\n    requests_wrapper: TextRequestsWrapper = Field(exclude=True)\n    api_docs: str\n    question_key: str = \"question\"  #: :meta private:\n    output_key: str = \"output\"  #: :meta private:\n    limit_to_domains: Optional[Sequence[str]]\n    \"\"\"Use to limit the domains that can be accessed by the API chain.\n    \n    * For example, to limit to just the domain `https://www.example.com`, set\n        `limit_to_domains=[\"https://www.example.com\"]`.\n        \n    * The default value is an empty tuple, which means that no domains are\n      allowed by default. By design this will raise an error on instantiation.\n    * Use a None if you want to allow all domains by default -- this is not\n      recommended for security reasons, as it would allow malicious users to\n      make requests to arbitrary URLS including internal APIs accessible from\n      the server.\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html"}
{"id": "0233e51d43c2-2", "text": "the server.\n    \"\"\"\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        return [self.question_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Expect output key.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n    @root_validator(pre=True)\n    def validate_api_request_prompt(cls, values: Dict) -> Dict:\n        \"\"\"Check that api request prompt expects the right variables.\"\"\"\n        input_vars = values[\"api_request_chain\"].prompt.input_variables\n        expected_vars = {\"question\", \"api_docs\"}\n        if set(input_vars) != expected_vars:\n            raise ValueError(\n                f\"Input variables should be {expected_vars}, got {input_vars}\"\n            )\n        return values\n    @root_validator(pre=True)\n    def validate_limit_to_domains(cls, values: Dict) -> Dict:\n        \"\"\"Check that allowed domains are valid.\"\"\"\n        if \"limit_to_domains\" not in values:\n            raise ValueError(\n                \"You must specify a list of domains to limit access using \"\n                \"`limit_to_domains`\"\n            )\n        if not values[\"limit_to_domains\"] and values[\"limit_to_domains\"] is not None:\n            raise ValueError(\n                \"Please provide a list of domains to limit access using \"\n                \"`limit_to_domains`.\"\n            )\n        return values\n    @root_validator(pre=True)\n    def validate_api_answer_prompt(cls, values: Dict) -> Dict:\n        \"\"\"Check that api answer prompt expects the right variables.\"\"\"\n        input_vars = values[\"api_answer_chain\"].prompt.input_variables\n        expected_vars = {\"question\", \"api_docs\", \"api_url\", \"api_response\"}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html"}
{"id": "0233e51d43c2-3", "text": "expected_vars = {\"question\", \"api_docs\", \"api_url\", \"api_response\"}\n        if set(input_vars) != expected_vars:\n            raise ValueError(\n                f\"Input variables should be {expected_vars}, got {input_vars}\"\n            )\n        return values\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        question = inputs[self.question_key]\n        api_url = self.api_request_chain.predict(\n            question=question,\n            api_docs=self.api_docs,\n            callbacks=_run_manager.get_child(),\n        )\n        _run_manager.on_text(api_url, color=\"green\", end=\"\\n\", verbose=self.verbose)\n        api_url = api_url.strip()\n        if self.limit_to_domains and not _check_in_allowed_domain(\n            api_url, self.limit_to_domains\n        ):\n            raise ValueError(\n                f\"{api_url} is not in the allowed domains: {self.limit_to_domains}\"\n            )\n        api_response = self.requests_wrapper.get(api_url)\n        _run_manager.on_text(\n            api_response, color=\"yellow\", end=\"\\n\", verbose=self.verbose\n        )\n        answer = self.api_answer_chain.predict(\n            question=question,\n            api_docs=self.api_docs,\n            api_url=api_url,\n            api_response=api_response,\n            callbacks=_run_manager.get_child(),\n        )\n        return {self.output_key: answer}\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html"}
{"id": "0233e51d43c2-4", "text": "run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()\n        question = inputs[self.question_key]\n        api_url = await self.api_request_chain.apredict(\n            question=question,\n            api_docs=self.api_docs,\n            callbacks=_run_manager.get_child(),\n        )\n        await _run_manager.on_text(\n            api_url, color=\"green\", end=\"\\n\", verbose=self.verbose\n        )\n        api_url = api_url.strip()\n        if self.limit_to_domains and not _check_in_allowed_domain(\n            api_url, self.limit_to_domains\n        ):\n            raise ValueError(\n                f\"{api_url} is not in the allowed domains: {self.limit_to_domains}\"\n            )\n        api_response = await self.requests_wrapper.aget(api_url)\n        await _run_manager.on_text(\n            api_response, color=\"yellow\", end=\"\\n\", verbose=self.verbose\n        )\n        answer = await self.api_answer_chain.apredict(\n            question=question,\n            api_docs=self.api_docs,\n            api_url=api_url,\n            api_response=api_response,\n            callbacks=_run_manager.get_child(),\n        )\n        return {self.output_key: answer}\n[docs]    @classmethod\n    def from_llm_and_api_docs(\n        cls,\n        llm: BaseLanguageModel,\n        api_docs: str,\n        headers: Optional[dict] = None,\n        api_url_prompt: BasePromptTemplate = API_URL_PROMPT,\n        api_response_prompt: BasePromptTemplate = API_RESPONSE_PROMPT,\n        limit_to_domains: Optional[Sequence[str]] = tuple(),\n        **kwargs: Any,\n    ) -> APIChain:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html"}
{"id": "0233e51d43c2-5", "text": "**kwargs: Any,\n    ) -> APIChain:\n        \"\"\"Load chain from just an LLM and the api docs.\"\"\"\n        get_request_chain = LLMChain(llm=llm, prompt=api_url_prompt)\n        requests_wrapper = TextRequestsWrapper(headers=headers)\n        get_answer_chain = LLMChain(llm=llm, prompt=api_response_prompt)\n        return cls(\n            api_request_chain=get_request_chain,\n            api_answer_chain=get_answer_chain,\n            requests_wrapper=requests_wrapper,\n            api_docs=api_docs,\n            limit_to_domains=limit_to_domains,\n            **kwargs,\n        )\n    @property\n    def _chain_type(self) -> str:\n        return \"api_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html"}
{"id": "919930cbf19b-0", "text": "Source code for langchain.chains.api.openapi.requests_chain\n\"\"\"request parser.\"\"\"\nimport json\nimport re\nfrom typing import Any\nfrom langchain.chains.api.openapi.prompts import REQUEST_TEMPLATE\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.schema import BaseOutputParser\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class APIRequesterOutputParser(BaseOutputParser):\n    \"\"\"Parse the request and error tags.\"\"\"\n    def _load_json_block(self, serialized_block: str) -> str:\n        try:\n            return json.dumps(json.loads(serialized_block, strict=False))\n        except json.JSONDecodeError:\n            return \"ERROR serializing request.\"\n[docs]    def parse(self, llm_output: str) -> str:\n        \"\"\"Parse the request and error tags.\"\"\"\n        json_match = re.search(r\"```json(.*?)```\", llm_output, re.DOTALL)\n        if json_match:\n            return self._load_json_block(json_match.group(1).strip())\n        message_match = re.search(r\"```text(.*?)```\", llm_output, re.DOTALL)\n        if message_match:\n            return f\"MESSAGE: {message_match.group(1).strip()}\"\n        return \"ERROR making request\"\n    @property\n    def _type(self) -> str:\n        return \"api_requester\"\n[docs]class APIRequesterChain(LLMChain):\n    \"\"\"Get the request parser.\"\"\"\n[docs]    @classmethod\n    def from_llm_and_typescript(\n        cls,\n        llm: BaseLanguageModel,\n        typescript_definition: str,\n        verbose: bool = True,\n        **kwargs: Any,\n    ) -> LLMChain:\n        \"\"\"Get the request parser.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/requests_chain.html"}
{"id": "919930cbf19b-1", "text": ") -> LLMChain:\n        \"\"\"Get the request parser.\"\"\"\n        output_parser = APIRequesterOutputParser()\n        prompt = PromptTemplate(\n            template=REQUEST_TEMPLATE,\n            output_parser=output_parser,\n            partial_variables={\"schema\": typescript_definition},\n            input_variables=[\"instructions\"],\n        )\n        return cls(prompt=prompt, llm=llm, verbose=verbose, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/requests_chain.html"}
{"id": "4865abb63265-0", "text": "Source code for langchain.chains.api.openapi.chain\n\"\"\"Chain that makes API calls and summarizes the responses to answer a question.\"\"\"\nfrom __future__ import annotations\nimport json\nfrom typing import Any, Dict, List, NamedTuple, Optional, cast\nfrom requests import Response\nfrom langchain.callbacks.manager import CallbackManagerForChainRun, Callbacks\nfrom langchain.chains.api.openapi.requests_chain import APIRequesterChain\nfrom langchain.chains.api.openapi.response_chain import APIResponderChain\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools.openapi.utils.api_models import APIOperation\nfrom langchain.utilities.requests import Requests\nclass _ParamMapping(NamedTuple):\n    \"\"\"Mapping from parameter name to parameter value.\"\"\"\n    query_params: List[str]\n    body_params: List[str]\n    path_params: List[str]\n[docs]class OpenAPIEndpointChain(Chain, BaseModel):\n    \"\"\"Chain interacts with an OpenAPI endpoint using natural language.\"\"\"\n    api_request_chain: LLMChain\n    api_response_chain: Optional[LLMChain]\n    api_operation: APIOperation\n    requests: Requests = Field(exclude=True, default_factory=Requests)\n    param_mapping: _ParamMapping = Field(alias=\"param_mapping\")\n    return_intermediate_steps: bool = False\n    instructions_key: str = \"instructions\"  #: :meta private:\n    output_key: str = \"output\"  #: :meta private:\n    max_text_length: Optional[int] = Field(ge=0)  #: :meta private:\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        return [self.instructions_key]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html"}
{"id": "4865abb63265-1", "text": ":meta private:\n        \"\"\"\n        return [self.instructions_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Expect output key.\n        :meta private:\n        \"\"\"\n        if not self.return_intermediate_steps:\n            return [self.output_key]\n        else:\n            return [self.output_key, \"intermediate_steps\"]\n    def _construct_path(self, args: Dict[str, str]) -> str:\n        \"\"\"Construct the path from the deserialized input.\"\"\"\n        path = self.api_operation.base_url + self.api_operation.path\n        for param in self.param_mapping.path_params:\n            path = path.replace(f\"{{{param}}}\", str(args.pop(param, \"\")))\n        return path\n    def _extract_query_params(self, args: Dict[str, str]) -> Dict[str, str]:\n        \"\"\"Extract the query params from the deserialized input.\"\"\"\n        query_params = {}\n        for param in self.param_mapping.query_params:\n            if param in args:\n                query_params[param] = args.pop(param)\n        return query_params\n    def _extract_body_params(self, args: Dict[str, str]) -> Optional[Dict[str, str]]:\n        \"\"\"Extract the request body params from the deserialized input.\"\"\"\n        body_params = None\n        if self.param_mapping.body_params:\n            body_params = {}\n            for param in self.param_mapping.body_params:\n                if param in args:\n                    body_params[param] = args.pop(param)\n        return body_params\n[docs]    def deserialize_json_input(self, serialized_args: str) -> dict:\n        \"\"\"Use the serialized typescript dictionary.\n        Resolve the path, query params dict, and optional requestBody dict.\n        \"\"\"\n        args: dict = json.loads(serialized_args)\n        path = self._construct_path(args)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html"}
{"id": "4865abb63265-2", "text": "path = self._construct_path(args)\n        body_params = self._extract_body_params(args)\n        query_params = self._extract_query_params(args)\n        return {\n            \"url\": path,\n            \"data\": body_params,\n            \"params\": query_params,\n        }\n    def _get_output(self, output: str, intermediate_steps: dict) -> dict:\n        \"\"\"Return the output from the API call.\"\"\"\n        if self.return_intermediate_steps:\n            return {\n                self.output_key: output,\n                \"intermediate_steps\": intermediate_steps,\n            }\n        else:\n            return {self.output_key: output}\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        intermediate_steps = {}\n        instructions = inputs[self.instructions_key]\n        instructions = instructions[: self.max_text_length]\n        _api_arguments = self.api_request_chain.predict_and_parse(\n            instructions=instructions, callbacks=_run_manager.get_child()\n        )\n        api_arguments = cast(str, _api_arguments)\n        intermediate_steps[\"request_args\"] = api_arguments\n        _run_manager.on_text(\n            api_arguments, color=\"green\", end=\"\\n\", verbose=self.verbose\n        )\n        if api_arguments.startswith(\"ERROR\"):\n            return self._get_output(api_arguments, intermediate_steps)\n        elif api_arguments.startswith(\"MESSAGE:\"):\n            return self._get_output(\n                api_arguments[len(\"MESSAGE:\") :], intermediate_steps\n            )\n        try:\n            request_args = self.deserialize_json_input(api_arguments)\n            method = getattr(self.requests, self.api_operation.method.value)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html"}
{"id": "4865abb63265-3", "text": "method = getattr(self.requests, self.api_operation.method.value)\n            api_response: Response = method(**request_args)\n            if api_response.status_code != 200:\n                method_str = str(self.api_operation.method.value)\n                response_text = (\n                    f\"{api_response.status_code}: {api_response.reason}\"\n                    + f\"\\nFor {method_str.upper()}  {request_args['url']}\\n\"\n                    + f\"Called with args: {request_args['params']}\"\n                )\n            else:\n                response_text = api_response.text\n        except Exception as e:\n            response_text = f\"Error with message {str(e)}\"\n        response_text = response_text[: self.max_text_length]\n        intermediate_steps[\"response_text\"] = response_text\n        _run_manager.on_text(\n            response_text, color=\"blue\", end=\"\\n\", verbose=self.verbose\n        )\n        if self.api_response_chain is not None:\n            _answer = self.api_response_chain.predict_and_parse(\n                response=response_text,\n                instructions=instructions,\n                callbacks=_run_manager.get_child(),\n            )\n            answer = cast(str, _answer)\n            _run_manager.on_text(answer, color=\"yellow\", end=\"\\n\", verbose=self.verbose)\n            return self._get_output(answer, intermediate_steps)\n        else:\n            return self._get_output(response_text, intermediate_steps)\n[docs]    @classmethod\n    def from_url_and_method(\n        cls,\n        spec_url: str,\n        path: str,\n        method: str,\n        llm: BaseLanguageModel,\n        requests: Optional[Requests] = None,\n        return_intermediate_steps: bool = False,\n        **kwargs: Any,\n        # TODO: Handle async\n    ) -> \"OpenAPIEndpointChain\":", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html"}
{"id": "4865abb63265-4", "text": "# TODO: Handle async\n    ) -> \"OpenAPIEndpointChain\":\n        \"\"\"Create an OpenAPIEndpoint from a spec at the specified url.\"\"\"\n        operation = APIOperation.from_openapi_url(spec_url, path, method)\n        return cls.from_api_operation(\n            operation,\n            requests=requests,\n            llm=llm,\n            return_intermediate_steps=return_intermediate_steps,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_api_operation(\n        cls,\n        operation: APIOperation,\n        llm: BaseLanguageModel,\n        requests: Optional[Requests] = None,\n        verbose: bool = False,\n        return_intermediate_steps: bool = False,\n        raw_response: bool = False,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n        # TODO: Handle async\n    ) -> \"OpenAPIEndpointChain\":\n        \"\"\"Create an OpenAPIEndpointChain from an operation and a spec.\"\"\"\n        param_mapping = _ParamMapping(\n            query_params=operation.query_params,\n            body_params=operation.body_params,\n            path_params=operation.path_params,\n        )\n        requests_chain = APIRequesterChain.from_llm_and_typescript(\n            llm,\n            typescript_definition=operation.to_typescript(),\n            verbose=verbose,\n            callbacks=callbacks,\n        )\n        if raw_response:\n            response_chain = None\n        else:\n            response_chain = APIResponderChain.from_llm(\n                llm, verbose=verbose, callbacks=callbacks\n            )\n        _requests = requests or Requests()\n        return cls(\n            api_request_chain=requests_chain,\n            api_response_chain=response_chain,\n            api_operation=operation,\n            requests=_requests,\n            param_mapping=param_mapping,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html"}
{"id": "4865abb63265-5", "text": "requests=_requests,\n            param_mapping=param_mapping,\n            verbose=verbose,\n            return_intermediate_steps=return_intermediate_steps,\n            callbacks=callbacks,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html"}
{"id": "c06c0d07db07-0", "text": "Source code for langchain.chains.api.openapi.response_chain\n\"\"\"Response parser.\"\"\"\nimport json\nimport re\nfrom typing import Any\nfrom langchain.chains.api.openapi.prompts import RESPONSE_TEMPLATE\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.schema import BaseOutputParser\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class APIResponderOutputParser(BaseOutputParser):\n    \"\"\"Parse the response and error tags.\"\"\"\n    def _load_json_block(self, serialized_block: str) -> str:\n        try:\n            response_content = json.loads(serialized_block, strict=False)\n            return response_content.get(\"response\", \"ERROR parsing response.\")\n        except json.JSONDecodeError:\n            return \"ERROR parsing response.\"\n        except:\n            raise\n[docs]    def parse(self, llm_output: str) -> str:\n        \"\"\"Parse the response and error tags.\"\"\"\n        json_match = re.search(r\"```json(.*?)```\", llm_output, re.DOTALL)\n        if json_match:\n            return self._load_json_block(json_match.group(1).strip())\n        else:\n            raise ValueError(f\"No response found in output: {llm_output}.\")\n    @property\n    def _type(self) -> str:\n        return \"api_responder\"\n[docs]class APIResponderChain(LLMChain):\n    \"\"\"Get the response parser.\"\"\"\n[docs]    @classmethod\n    def from_llm(\n        cls, llm: BaseLanguageModel, verbose: bool = True, **kwargs: Any\n    ) -> LLMChain:\n        \"\"\"Get the response parser.\"\"\"\n        output_parser = APIResponderOutputParser()\n        prompt = PromptTemplate(\n            template=RESPONSE_TEMPLATE,\n            output_parser=output_parser,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/response_chain.html"}
{"id": "c06c0d07db07-1", "text": "template=RESPONSE_TEMPLATE,\n            output_parser=output_parser,\n            input_variables=[\"response\", \"instructions\"],\n        )\n        return cls(prompt=prompt, llm=llm, verbose=verbose, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/response_chain.html"}
{"id": "2550425fd5d2-0", "text": "Source code for langchain.chains.flare.prompts\nfrom typing import Tuple\nfrom langchain.prompts import PromptTemplate\nfrom langchain.schema import BaseOutputParser\n[docs]class FinishedOutputParser(BaseOutputParser[Tuple[str, bool]]):\n    \"\"\"Output parser that checks if the output is finished.\"\"\"\n    finished_value: str = \"FINISHED\"\n    \"\"\"Value that indicates the output is finished.\"\"\"\n[docs]    def parse(self, text: str) -> Tuple[str, bool]:\n        cleaned = text.strip()\n        finished = self.finished_value in cleaned\n        return cleaned.replace(self.finished_value, \"\"), finished\nPROMPT_TEMPLATE = \"\"\"\\\nRespond to the user message using any relevant context. \\\nIf context is provided, you should ground your answer in that context. \\\nOnce you're done responding return FINISHED.\n>>> CONTEXT: {context}\n>>> USER INPUT: {user_input}\n>>> RESPONSE: {response}\\\n\"\"\"\nPROMPT = PromptTemplate(\n    template=PROMPT_TEMPLATE,\n    input_variables=[\"user_input\", \"context\", \"response\"],\n)\nQUESTION_GENERATOR_PROMPT_TEMPLATE = \"\"\"\\\nGiven a user input and an existing partial response as context, \\\nask a question to which the answer is the given term/entity/phrase:\n>>> USER INPUT: {user_input}\n>>> EXISTING PARTIAL RESPONSE: {current_response}\nThe question to which the answer is the term/entity/phrase \"{uncertain_span}\" is:\"\"\"\nQUESTION_GENERATOR_PROMPT = PromptTemplate(\n    template=QUESTION_GENERATOR_PROMPT_TEMPLATE,\n    input_variables=[\"user_input\", \"current_response\", \"uncertain_span\"],\n)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/prompts.html"}
{"id": "f94ecb61892d-0", "text": "Source code for langchain.chains.flare.base\nfrom __future__ import annotations\nimport re\nfrom abc import abstractmethod\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple\nimport numpy as np\nfrom langchain.callbacks.manager import (\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.chains.flare.prompts import (\n    PROMPT,\n    QUESTION_GENERATOR_PROMPT,\n    FinishedOutputParser,\n)\nfrom langchain.chains.llm import LLMChain\nfrom langchain.llms.openai import OpenAI\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BasePromptTemplate, BaseRetriever, Generation\nfrom langchain.schema.language_model import BaseLanguageModel\nclass _ResponseChain(LLMChain):\n    \"\"\"Base class for chains that generate responses.\"\"\"\n    prompt: BasePromptTemplate = PROMPT\n    @property\n    def input_keys(self) -> List[str]:\n        return self.prompt.input_variables\n    def generate_tokens_and_log_probs(\n        self,\n        _input: Dict[str, Any],\n        *,\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Tuple[Sequence[str], Sequence[float]]:\n        llm_result = self.generate([_input], run_manager=run_manager)\n        return self._extract_tokens_and_log_probs(llm_result.generations[0])\n    @abstractmethod\n    def _extract_tokens_and_log_probs(\n        self, generations: List[Generation]\n    ) -> Tuple[Sequence[str], Sequence[float]]:\n        \"\"\"Extract tokens and log probs from response.\"\"\"\nclass _OpenAIResponseChain(_ResponseChain):\n    \"\"\"Chain that generates responses from user input and context.\"\"\"\n    llm: OpenAI = Field(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html"}
{"id": "f94ecb61892d-1", "text": "llm: OpenAI = Field(\n        default_factory=lambda: OpenAI(\n            max_tokens=32, model_kwargs={\"logprobs\": 1}, temperature=0\n        )\n    )\n    def _extract_tokens_and_log_probs(\n        self, generations: List[Generation]\n    ) -> Tuple[Sequence[str], Sequence[float]]:\n        tokens = []\n        log_probs = []\n        for gen in generations:\n            if gen.generation_info is None:\n                raise ValueError\n            tokens.extend(gen.generation_info[\"logprobs\"][\"tokens\"])\n            log_probs.extend(gen.generation_info[\"logprobs\"][\"token_logprobs\"])\n        return tokens, log_probs\n[docs]class QuestionGeneratorChain(LLMChain):\n    \"\"\"Chain that generates questions from uncertain spans.\"\"\"\n    prompt: BasePromptTemplate = QUESTION_GENERATOR_PROMPT\n    \"\"\"Prompt template for the chain.\"\"\"\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Input keys for the chain.\"\"\"\n        return [\"user_input\", \"context\", \"response\"]\ndef _low_confidence_spans(\n    tokens: Sequence[str],\n    log_probs: Sequence[float],\n    min_prob: float,\n    min_token_gap: int,\n    num_pad_tokens: int,\n) -> List[str]:\n    _low_idx = np.where(np.exp(log_probs) < min_prob)[0]\n    low_idx = [i for i in _low_idx if re.search(r\"\\w\", tokens[i])]\n    if len(low_idx) == 0:\n        return []\n    spans = [[low_idx[0], low_idx[0] + num_pad_tokens + 1]]\n    for i, idx in enumerate(low_idx[1:]):\n        end = idx + num_pad_tokens + 1", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html"}
{"id": "f94ecb61892d-2", "text": "end = idx + num_pad_tokens + 1\n        if idx - low_idx[i] < min_token_gap:\n            spans[-1][1] = end\n        else:\n            spans.append([idx, end])\n    return [\"\".join(tokens[start:end]) for start, end in spans]\n[docs]class FlareChain(Chain):\n    \"\"\"Chain that combines a retriever, a question generator,\n    and a response generator.\"\"\"\n    question_generator_chain: QuestionGeneratorChain\n    \"\"\"Chain that generates questions from uncertain spans.\"\"\"\n    response_chain: _ResponseChain = Field(default_factory=_OpenAIResponseChain)\n    \"\"\"Chain that generates responses from user input and context.\"\"\"\n    output_parser: FinishedOutputParser = Field(default_factory=FinishedOutputParser)\n    \"\"\"Parser that determines whether the chain is finished.\"\"\"\n    retriever: BaseRetriever\n    \"\"\"Retriever that retrieves relevant documents from a user input.\"\"\"\n    min_prob: float = 0.2\n    \"\"\"Minimum probability for a token to be considered low confidence.\"\"\"\n    min_token_gap: int = 5\n    \"\"\"Minimum number of tokens between two low confidence spans.\"\"\"\n    num_pad_tokens: int = 2\n    \"\"\"Number of tokens to pad around a low confidence span.\"\"\"\n    max_iter: int = 10\n    \"\"\"Maximum number of iterations.\"\"\"\n    start_with_retrieval: bool = True\n    \"\"\"Whether to start with retrieval.\"\"\"\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Input keys for the chain.\"\"\"\n        return [\"user_input\"]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Output keys for the chain.\"\"\"\n        return [\"response\"]\n    def _do_generation(\n        self,\n        questions: List[str],\n        user_input: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html"}
{"id": "f94ecb61892d-3", "text": "self,\n        questions: List[str],\n        user_input: str,\n        response: str,\n        _run_manager: CallbackManagerForChainRun,\n    ) -> Tuple[str, bool]:\n        callbacks = _run_manager.get_child()\n        docs = []\n        for question in questions:\n            docs.extend(self.retriever.get_relevant_documents(question))\n        context = \"\\n\\n\".join(d.page_content for d in docs)\n        result = self.response_chain.predict(\n            user_input=user_input,\n            context=context,\n            response=response,\n            callbacks=callbacks,\n        )\n        marginal, finished = self.output_parser.parse(result)\n        return marginal, finished\n    def _do_retrieval(\n        self,\n        low_confidence_spans: List[str],\n        _run_manager: CallbackManagerForChainRun,\n        user_input: str,\n        response: str,\n        initial_response: str,\n    ) -> Tuple[str, bool]:\n        question_gen_inputs = [\n            {\n                \"user_input\": user_input,\n                \"current_response\": initial_response,\n                \"uncertain_span\": span,\n            }\n            for span in low_confidence_spans\n        ]\n        callbacks = _run_manager.get_child()\n        question_gen_outputs = self.question_generator_chain.apply(\n            question_gen_inputs, callbacks=callbacks\n        )\n        questions = [\n            output[self.question_generator_chain.output_keys[0]]\n            for output in question_gen_outputs\n        ]\n        _run_manager.on_text(\n            f\"Generated Questions: {questions}\", color=\"yellow\", end=\"\\n\"\n        )\n        return self._do_generation(questions, user_input, response, _run_manager)\n    def _call(\n        self,\n        inputs: Dict[str, Any],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html"}
{"id": "f94ecb61892d-4", "text": "def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        user_input = inputs[self.input_keys[0]]\n        response = \"\"\n        for i in range(self.max_iter):\n            _run_manager.on_text(\n                f\"Current Response: {response}\", color=\"blue\", end=\"\\n\"\n            )\n            _input = {\"user_input\": user_input, \"context\": \"\", \"response\": response}\n            tokens, log_probs = self.response_chain.generate_tokens_and_log_probs(\n                _input, run_manager=_run_manager\n            )\n            low_confidence_spans = _low_confidence_spans(\n                tokens,\n                log_probs,\n                self.min_prob,\n                self.min_token_gap,\n                self.num_pad_tokens,\n            )\n            initial_response = response.strip() + \" \" + \"\".join(tokens)\n            if not low_confidence_spans:\n                response = initial_response\n                final_response, finished = self.output_parser.parse(response)\n                if finished:\n                    return {self.output_keys[0]: final_response}\n                continue\n            marginal, finished = self._do_retrieval(\n                low_confidence_spans,\n                _run_manager,\n                user_input,\n                response,\n                initial_response,\n            )\n            response = response.strip() + \" \" + marginal\n            if finished:\n                break\n        return {self.output_keys[0]: response}\n[docs]    @classmethod\n    def from_llm(\n        cls, llm: BaseLanguageModel, max_generation_len: int = 32, **kwargs: Any", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html"}
{"id": "f94ecb61892d-5", "text": ") -> FlareChain:\n        \"\"\"Creates a FlareChain from a language model.\n        Args:\n            llm: Language model to use.\n            max_generation_len: Maximum length of the generated response.\n            **kwargs: Additional arguments to pass to the constructor.\n        Returns:\n            FlareChain class with the given language model.\n        \"\"\"\n        question_gen_chain = QuestionGeneratorChain(llm=llm)\n        response_llm = OpenAI(\n            max_tokens=max_generation_len, model_kwargs={\"logprobs\": 1}, temperature=0\n        )\n        response_chain = _OpenAIResponseChain(llm=response_llm)\n        return cls(\n            question_generator_chain=question_gen_chain,\n            response_chain=response_chain,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html"}
{"id": "88dd862d0ec3-0", "text": "Source code for langchain.chains.qa_generation.base\nfrom __future__ import annotations\nimport json\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.qa_generation.prompt import PROMPT_SELECTOR\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter, TextSplitter\n[docs]class QAGenerationChain(Chain):\n    \"\"\"Base class for question-answer generation chains.\"\"\"\n    llm_chain: LLMChain\n    \"\"\"LLM Chain that generates responses from user input and context.\"\"\"\n    text_splitter: TextSplitter = Field(\n        default=RecursiveCharacterTextSplitter(chunk_overlap=500)\n    )\n    \"\"\"Text splitter that splits the input into chunks.\"\"\"\n    input_key: str = \"text\"\n    \"\"\"Key of the input to the chain.\"\"\"\n    output_key: str = \"questions\"\n    \"\"\"Key of the output of the chain.\"\"\"\n    k: Optional[int] = None\n    \"\"\"Number of questions to generate.\"\"\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        prompt: Optional[BasePromptTemplate] = None,\n        **kwargs: Any,\n    ) -> QAGenerationChain:\n        \"\"\"\n        Create a QAGenerationChain from a language model.\n        Args:\n            llm: a language model\n            prompt: a prompt template\n            **kwargs: additional arguments\n        Returns:\n            a QAGenerationChain class\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html"}
{"id": "88dd862d0ec3-1", "text": "Returns:\n            a QAGenerationChain class\n        \"\"\"\n        _prompt = prompt or PROMPT_SELECTOR.get_prompt(llm)\n        chain = LLMChain(llm=llm, prompt=_prompt)\n        return cls(llm_chain=chain, **kwargs)\n    @property\n    def _chain_type(self) -> str:\n        raise NotImplementedError\n    @property\n    def input_keys(self) -> List[str]:\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        return [self.output_key]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, List]:\n        docs = self.text_splitter.create_documents([inputs[self.input_key]])\n        results = self.llm_chain.generate(\n            [{\"text\": d.page_content} for d in docs], run_manager=run_manager\n        )\n        qa = [json.loads(res[0].text) for res in results.generations]\n        return {self.output_key: qa}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html"}
{"id": "3ca04cccfc92-0", "text": "Source code for langchain.chains.graph_qa.cypher\n\"\"\"Question answering over a graph.\"\"\"\nfrom __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.graph_qa.cypher_utils import CypherQueryCorrector, Schema\nfrom langchain.chains.graph_qa.prompts import CYPHER_GENERATION_PROMPT, CYPHER_QA_PROMPT\nfrom langchain.chains.llm import LLMChain\nfrom langchain.graphs.graph_store import GraphStore\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nINTERMEDIATE_STEPS_KEY = \"intermediate_steps\"\n[docs]def extract_cypher(text: str) -> str:\n    \"\"\"Extract Cypher code from a text.\n    Args:\n        text: Text to extract Cypher code from.\n    Returns:\n        Cypher code extracted from the text.\n    \"\"\"\n    # The pattern to find Cypher code enclosed in triple backticks\n    pattern = r\"```(.*?)```\"\n    # Find all matches in the input text\n    matches = re.findall(pattern, text, re.DOTALL)\n    return matches[0] if matches else text\n[docs]def construct_schema(\n    structured_schema: Dict[str, Any],\n    include_types: List[str],\n    exclude_types: List[str],\n) -> str:\n    \"\"\"Filter the schema based on included or excluded types\"\"\"\n    def filter_func(x: str) -> bool:\n        return x in include_types if include_types else x not in exclude_types\n    filtered_schema = {\n        \"node_props\": {\n            k: v", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html"}
{"id": "3ca04cccfc92-1", "text": "filtered_schema = {\n        \"node_props\": {\n            k: v\n            for k, v in structured_schema.get(\"node_props\", {}).items()\n            if filter_func(k)\n        },\n        \"rel_props\": {\n            k: v\n            for k, v in structured_schema.get(\"rel_props\", {}).items()\n            if filter_func(k)\n        },\n        \"relationships\": [\n            r\n            for r in structured_schema.get(\"relationships\", [])\n            if all(filter_func(r[t]) for t in [\"start\", \"end\", \"type\"])\n        ],\n    }\n    return (\n        f\"Node properties are the following: \\n {filtered_schema['node_props']}\\n\"\n        f\"Relationships properties are the following: \\n {filtered_schema['rel_props']}\"\n        \"\\nRelationships are: \\n\"\n        + str(\n            [\n                f\"(:{el['start']})-[:{el['type']}]->(:{el['end']})\"\n                for el in filtered_schema[\"relationships\"]\n            ]\n        )\n    )\n[docs]class GraphCypherQAChain(Chain):\n    \"\"\"Chain for question-answering against a graph by generating Cypher statements.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html"}
{"id": "3ca04cccfc92-2", "text": "limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    graph: GraphStore = Field(exclude=True)\n    cypher_generation_chain: LLMChain\n    qa_chain: LLMChain\n    graph_schema: str\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:\n    top_k: int = 10\n    \"\"\"Number of results to return from the query\"\"\"\n    return_intermediate_steps: bool = False\n    \"\"\"Whether or not to return the intermediate steps along with the final answer.\"\"\"\n    return_direct: bool = False\n    \"\"\"Whether or not to return the result of querying the graph directly.\"\"\"\n    cypher_query_corrector: Optional[CypherQueryCorrector] = None\n    \"\"\"Optional cypher validation tool\"\"\"\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the output keys.\n        :meta private:\n        \"\"\"\n        _output_keys = [self.output_key]\n        return _output_keys\n    @property\n    def _chain_type(self) -> str:\n        return \"graph_cypher_chain\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: Optional[BaseLanguageModel] = None,\n        *,\n        qa_prompt: Optional[BasePromptTemplate] = None,\n        cypher_prompt: Optional[BasePromptTemplate] = None,\n        cypher_llm: Optional[BaseLanguageModel] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html"}
{"id": "3ca04cccfc92-3", "text": "cypher_llm: Optional[BaseLanguageModel] = None,\n        qa_llm: Optional[BaseLanguageModel] = None,\n        exclude_types: List[str] = [],\n        include_types: List[str] = [],\n        validate_cypher: bool = False,\n        qa_llm_kwargs: Optional[Dict[str, Any]] = None,\n        cypher_llm_kwargs: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> GraphCypherQAChain:\n        \"\"\"Initialize from LLM.\"\"\"\n        if not cypher_llm and not llm:\n            raise ValueError(\"Either `llm` or `cypher_llm` parameters must be provided\")\n        if not qa_llm and not llm:\n            raise ValueError(\"Either `llm` or `qa_llm` parameters must be provided\")\n        if cypher_llm and qa_llm and llm:\n            raise ValueError(\n                \"You can specify up to two of 'cypher_llm', 'qa_llm'\"\n                \", and 'llm', but not all three simultaneously.\"\n            )\n        if cypher_prompt and cypher_llm_kwargs:\n            raise ValueError(\n                \"Specifying cypher_prompt and cypher_llm_kwargs together is\"\n                \" not allowed. Please pass prompt via cypher_llm_kwargs.\"\n            )\n        if qa_prompt and qa_llm_kwargs:\n            raise ValueError(\n                \"Specifying qa_prompt and qa_llm_kwargs together is\"\n                \" not allowed. Please pass prompt via qa_llm_kwargs.\"\n            )\n        use_qa_llm_kwargs = qa_llm_kwargs if qa_llm_kwargs is not None else {}\n        use_cypher_llm_kwargs = (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html"}
{"id": "3ca04cccfc92-4", "text": "use_cypher_llm_kwargs = (\n            cypher_llm_kwargs if cypher_llm_kwargs is not None else {}\n        )\n        if \"prompt\" not in use_qa_llm_kwargs:\n            use_qa_llm_kwargs[\"prompt\"] = (\n                qa_prompt if qa_prompt is not None else CYPHER_QA_PROMPT\n            )\n        if \"prompt\" not in use_cypher_llm_kwargs:\n            use_cypher_llm_kwargs[\"prompt\"] = (\n                cypher_prompt if cypher_prompt is not None else CYPHER_GENERATION_PROMPT\n            )\n        qa_chain = LLMChain(llm=qa_llm or llm, **use_qa_llm_kwargs)\n        cypher_generation_chain = LLMChain(\n            llm=cypher_llm or llm, **use_cypher_llm_kwargs\n        )\n        if exclude_types and include_types:\n            raise ValueError(\n                \"Either `exclude_types` or `include_types` \"\n                \"can be provided, but not both\"\n            )\n        graph_schema = construct_schema(\n            kwargs[\"graph\"].get_structured_schema, include_types, exclude_types\n        )\n        cypher_query_corrector = None\n        if validate_cypher:\n            corrector_schema = [\n                Schema(el[\"start\"], el[\"type\"], el[\"end\"])\n                for el in kwargs[\"graph\"].structured_schema.get(\"relationships\")\n            ]\n            cypher_query_corrector = CypherQueryCorrector(corrector_schema)\n        return cls(\n            graph_schema=graph_schema,\n            qa_chain=qa_chain,\n            cypher_generation_chain=cypher_generation_chain,\n            cypher_query_corrector=cypher_query_corrector,\n            **kwargs,\n        )\n    def _call(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html"}
{"id": "3ca04cccfc92-5", "text": "**kwargs,\n        )\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Generate Cypher statement, use it to look up in db and answer question.\"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        question = inputs[self.input_key]\n        intermediate_steps: List = []\n        generated_cypher = self.cypher_generation_chain.run(\n            {\"question\": question, \"schema\": self.graph_schema}, callbacks=callbacks\n        )\n        # Extract Cypher code if it is wrapped in backticks\n        generated_cypher = extract_cypher(generated_cypher)\n        # Correct Cypher query if enabled\n        if self.cypher_query_corrector:\n            generated_cypher = self.cypher_query_corrector(generated_cypher)\n        _run_manager.on_text(\"Generated Cypher:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(\n            generated_cypher, color=\"green\", end=\"\\n\", verbose=self.verbose\n        )\n        intermediate_steps.append({\"query\": generated_cypher})\n        # Retrieve and limit the number of results\n        # Generated Cypher be null if query corrector identifies invalid schema\n        if generated_cypher:\n            context = self.graph.query(generated_cypher)[: self.top_k]\n        else:\n            context = []\n        if self.return_direct:\n            final_result = context\n        else:\n            _run_manager.on_text(\"Full Context:\", end=\"\\n\", verbose=self.verbose)\n            _run_manager.on_text(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html"}
{"id": "3ca04cccfc92-6", "text": "_run_manager.on_text(\n                str(context), color=\"green\", end=\"\\n\", verbose=self.verbose\n            )\n            intermediate_steps.append({\"context\": context})\n            result = self.qa_chain(\n                {\"question\": question, \"context\": context},\n                callbacks=callbacks,\n            )\n            final_result = result[self.qa_chain.output_key]\n        chain_result: Dict[str, Any] = {self.output_key: final_result}\n        if self.return_intermediate_steps:\n            chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps\n        return chain_result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html"}
{"id": "e18825aab6c3-0", "text": "Source code for langchain.chains.graph_qa.arangodb\n\"\"\"Question answering over a graph.\"\"\"\nfrom __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Optional\nfrom langchain.base_language import BaseLanguageModel\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.graph_qa.prompts import (\n    AQL_FIX_PROMPT,\n    AQL_GENERATION_PROMPT,\n    AQL_QA_PROMPT,\n)\nfrom langchain.chains.llm import LLMChain\nfrom langchain.graphs.arangodb_graph import ArangoGraph\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BasePromptTemplate\n[docs]class ArangoGraphQAChain(Chain):\n    \"\"\"Chain for question-answering against a graph by generating AQL statements.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    graph: ArangoGraph = Field(exclude=True)\n    aql_generation_chain: LLMChain\n    aql_fix_chain: LLMChain\n    qa_chain: LLMChain\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html"}
{"id": "e18825aab6c3-1", "text": "output_key: str = \"result\"  #: :meta private:\n    # Specifies the maximum number of AQL Query Results to return\n    top_k: int = 10\n    # Specifies the set of AQL Query Examples that promote few-shot-learning\n    aql_examples: str = \"\"\n    # Specify whether to return the AQL Query in the output dictionary\n    return_aql_query: bool = False\n    # Specify whether to return the AQL JSON Result in the output dictionary\n    return_aql_result: bool = False\n    # Specify the maximum amount of AQL Generation attempts that should be made\n    max_aql_generation_attempts: int = 3\n    @property\n    def input_keys(self) -> List[str]:\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        return [self.output_key]\n    @property\n    def _chain_type(self) -> str:\n        return \"graph_aql_chain\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        *,\n        qa_prompt: BasePromptTemplate = AQL_QA_PROMPT,\n        aql_generation_prompt: BasePromptTemplate = AQL_GENERATION_PROMPT,\n        aql_fix_prompt: BasePromptTemplate = AQL_FIX_PROMPT,\n        **kwargs: Any,\n    ) -> ArangoGraphQAChain:\n        \"\"\"Initialize from LLM.\"\"\"\n        qa_chain = LLMChain(llm=llm, prompt=qa_prompt)\n        aql_generation_chain = LLMChain(llm=llm, prompt=aql_generation_prompt)\n        aql_fix_chain = LLMChain(llm=llm, prompt=aql_fix_prompt)\n        return cls(\n            qa_chain=qa_chain,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html"}
{"id": "e18825aab6c3-2", "text": "return cls(\n            qa_chain=qa_chain,\n            aql_generation_chain=aql_generation_chain,\n            aql_fix_chain=aql_fix_chain,\n            **kwargs,\n        )\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"\n        Generate an AQL statement from user input, use it retrieve a response\n        from an ArangoDB Database instance, and respond to the user input\n        in natural language.\n        Users can modify the following ArangoGraphQAChain Class Variables:\n        :var top_k: The maximum number of AQL Query Results to return\n        :type top_k: int\n        :var aql_examples: A set of AQL Query Examples that are passed to\n            the AQL Generation Prompt Template to promote few-shot-learning.\n            Defaults to an empty string.\n        :type aql_examples: str\n        :var return_aql_query: Whether to return the AQL Query in the\n            output dictionary. Defaults to False.\n        :type return_aql_query: bool\n        :var return_aql_result: Whether to return the AQL Query in the\n            output dictionary. Defaults to False\n        :type return_aql_result: bool\n        :var max_aql_generation_attempts: The maximum amount of AQL\n            Generation attempts to be made prior to raising the last\n            AQL Query Execution Error. Defaults to 3.\n        :type max_aql_generation_attempts: int\n        \"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        user_input = inputs[self.input_key]\n        #########################\n        # Generate AQL Query #", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html"}
{"id": "e18825aab6c3-3", "text": "#########################\n        # Generate AQL Query #\n        aql_generation_output = self.aql_generation_chain.run(\n            {\n                \"adb_schema\": self.graph.schema,\n                \"aql_examples\": self.aql_examples,\n                \"user_input\": user_input,\n            },\n            callbacks=callbacks,\n        )\n        #########################\n        aql_query = \"\"\n        aql_error = \"\"\n        aql_result = None\n        aql_generation_attempt = 1\n        while (\n            aql_result is None\n            and aql_generation_attempt < self.max_aql_generation_attempts + 1\n        ):\n            #####################\n            # Extract AQL Query #\n            pattern = r\"```(?i:aql)?(.*?)```\"\n            matches = re.findall(pattern, aql_generation_output, re.DOTALL)\n            if not matches:\n                _run_manager.on_text(\n                    \"Invalid Response: \", end=\"\\n\", verbose=self.verbose\n                )\n                _run_manager.on_text(\n                    aql_generation_output, color=\"red\", end=\"\\n\", verbose=self.verbose\n                )\n                raise ValueError(f\"Response is Invalid: {aql_generation_output}\")\n            aql_query = matches[0]\n            #####################\n            _run_manager.on_text(\n                f\"AQL Query ({aql_generation_attempt}):\", verbose=self.verbose\n            )\n            _run_manager.on_text(\n                aql_query, color=\"green\", end=\"\\n\", verbose=self.verbose\n            )\n            #####################\n            # Execute AQL Query #\n            from arango import AQLQueryExecuteError\n            try:\n                aql_result = self.graph.query(aql_query, self.top_k)\n            except AQLQueryExecuteError as e:\n                aql_error = e.error_message\n                _run_manager.on_text(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html"}
{"id": "e18825aab6c3-4", "text": "aql_error = e.error_message\n                _run_manager.on_text(\n                    \"AQL Query Execution Error: \", end=\"\\n\", verbose=self.verbose\n                )\n                _run_manager.on_text(\n                    aql_error, color=\"yellow\", end=\"\\n\\n\", verbose=self.verbose\n                )\n                ########################\n                # Retry AQL Generation #\n                aql_generation_output = self.aql_fix_chain.run(\n                    {\n                        \"adb_schema\": self.graph.schema,\n                        \"aql_query\": aql_query,\n                        \"aql_error\": aql_error,\n                    },\n                    callbacks=callbacks,\n                )\n                ########################\n            #####################\n            aql_generation_attempt += 1\n        if aql_result is None:\n            m = f\"\"\"\n                Maximum amount of AQL Query Generation attempts reached.\n                Unable to execute the AQL Query due to the following error:\n                {aql_error}\n            \"\"\"\n            raise ValueError(m)\n        _run_manager.on_text(\"AQL Result:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(\n            str(aql_result), color=\"green\", end=\"\\n\", verbose=self.verbose\n        )\n        ########################\n        # Interpret AQL Result #\n        result = self.qa_chain(\n            {\n                \"adb_schema\": self.graph.schema,\n                \"user_input\": user_input,\n                \"aql_query\": aql_query,\n                \"aql_result\": aql_result,\n            },\n            callbacks=callbacks,\n        )\n        ########################\n        # Return results #\n        result = {self.output_key: result[self.qa_chain.output_key]}\n        if self.return_aql_query:\n            result[\"aql_query\"] = aql_query\n        if self.return_aql_result:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html"}
{"id": "e18825aab6c3-5", "text": "if self.return_aql_result:\n            result[\"aql_result\"] = aql_result\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html"}
{"id": "49198b6adcc8-0", "text": "Source code for langchain.chains.graph_qa.cypher_utils\nimport re\nfrom collections import namedtuple\nfrom typing import Any, Dict, List, Optional, Tuple\nSchema = namedtuple(\"Schema\", [\"left_node\", \"relation\", \"right_node\"])\n[docs]class CypherQueryCorrector:\n    \"\"\"\n    Used to correct relationship direction in generated Cypher statements.\n    This code is copied from the winner's submission to the Cypher competition:\n    https://github.com/sakusaku-rich/cypher-direction-competition\n    \"\"\"\n    property_pattern = re.compile(r\"\\{.+?\\}\")\n    node_pattern = re.compile(r\"\\(.+?\\)\")\n    path_pattern = re.compile(r\"\\(.*\\).*-.*-.*\\(.*\\)\")\n    node_relation_node_pattern = re.compile(\n        r\"(\\()+(?P<left_node>[^()]*?)\\)(?P<relation>.*?)\\((?P<right_node>[^()]*?)(\\))+\"\n    )\n    relation_type_pattern = re.compile(r\":(?P<relation_type>.+?)?(\\{.+\\})?]\")\n[docs]    def __init__(self, schemas: List[Schema]):\n        \"\"\"\n        Args:\n            schemas: list of schemas\n        \"\"\"\n        self.schemas = schemas\n[docs]    def clean_node(self, node: str) -> str:\n        \"\"\"\n        Args:\n            node: node in string format\n        \"\"\"\n        node = re.sub(self.property_pattern, \"\", node)\n        node = node.replace(\"(\", \"\")\n        node = node.replace(\")\", \"\")\n        node = node.strip()\n        return node\n[docs]    def detect_node_variables(self, query: str) -> Dict[str, List[str]]:\n        \"\"\"\n        Args:\n            query: cypher query", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher_utils.html"}
{"id": "49198b6adcc8-1", "text": "\"\"\"\n        Args:\n            query: cypher query\n        \"\"\"\n        nodes = re.findall(self.node_pattern, query)\n        nodes = [self.clean_node(node) for node in nodes]\n        res: Dict[str, Any] = {}\n        for node in nodes:\n            parts = node.split(\":\")\n            if parts == \"\":\n                continue\n            variable = parts[0]\n            if variable not in res:\n                res[variable] = []\n            res[variable] += parts[1:]\n        return res\n[docs]    def extract_paths(self, query: str) -> \"List[str]\":\n        \"\"\"\n        Args:\n            query: cypher query\n        \"\"\"\n        return re.findall(self.path_pattern, query)\n[docs]    def judge_direction(self, relation: str) -> str:\n        \"\"\"\n        Args:\n            relation: relation in string format\n        \"\"\"\n        direction = \"BIDIRECTIONAL\"\n        if relation[0] == \"<\":\n            direction = \"INCOMING\"\n        if relation[-1] == \">\":\n            direction = \"OUTGOING\"\n        return direction\n[docs]    def extract_node_variable(self, part: str) -> Optional[str]:\n        \"\"\"\n        Args:\n            part: node in string format\n        \"\"\"\n        part = part.lstrip(\"(\").rstrip(\")\")\n        idx = part.find(\":\")\n        if idx != -1:\n            part = part[:idx]\n        return None if part == \"\" else part\n[docs]    def detect_labels(\n        self, str_node: str, node_variable_dict: Dict[str, Any]\n    ) -> List[str]:\n        \"\"\"\n        Args:\n            str_node: node in string format\n            node_variable_dict: dictionary of node variables\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher_utils.html"}
{"id": "49198b6adcc8-2", "text": "node_variable_dict: dictionary of node variables\n        \"\"\"\n        splitted_node = str_node.split(\":\")\n        variable = splitted_node[0]\n        labels = []\n        if variable in node_variable_dict:\n            labels = node_variable_dict[variable]\n        elif variable == \"\" and len(splitted_node) > 1:\n            labels = splitted_node[1:]\n        return labels\n[docs]    def verify_schema(\n        self,\n        from_node_labels: List[str],\n        relation_types: List[str],\n        to_node_labels: List[str],\n    ) -> bool:\n        \"\"\"\n        Args:\n            from_node_labels: labels of the from node\n            relation_type: type of the relation\n            to_node_labels: labels of the to node\n        \"\"\"\n        valid_schemas = self.schemas\n        if from_node_labels != []:\n            from_node_labels = [label.strip(\"`\") for label in from_node_labels]\n            valid_schemas = [\n                schema for schema in valid_schemas if schema[0] in from_node_labels\n            ]\n        if to_node_labels != []:\n            to_node_labels = [label.strip(\"`\") for label in to_node_labels]\n            valid_schemas = [\n                schema for schema in valid_schemas if schema[2] in to_node_labels\n            ]\n        if relation_types != []:\n            relation_types = [type.strip(\"`\") for type in relation_types]\n            valid_schemas = [\n                schema for schema in valid_schemas if schema[1] in relation_types\n            ]\n        return valid_schemas != []\n[docs]    def detect_relation_types(self, str_relation: str) -> Tuple[str, List[str]]:\n        \"\"\"\n        Args:\n            str_relation: relation in string format\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher_utils.html"}
{"id": "49198b6adcc8-3", "text": "\"\"\"\n        Args:\n            str_relation: relation in string format\n        \"\"\"\n        relation_direction = self.judge_direction(str_relation)\n        relation_type = self.relation_type_pattern.search(str_relation)\n        if relation_type is None or relation_type.group(\"relation_type\") is None:\n            return relation_direction, []\n        relation_types = [\n            t.strip().strip(\"!\")\n            for t in relation_type.group(\"relation_type\").split(\"|\")\n        ]\n        return relation_direction, relation_types\n[docs]    def correct_query(self, query: str) -> str:\n        \"\"\"\n        Args:\n            query: cypher query\n        \"\"\"\n        node_variable_dict = self.detect_node_variables(query)\n        paths = self.extract_paths(query)\n        for path in paths:\n            original_path = path\n            start_idx = 0\n            while start_idx < len(path):\n                match_res = re.match(self.node_relation_node_pattern, path[start_idx:])\n                if match_res is None:\n                    break\n                start_idx += match_res.start()\n                match_dict = match_res.groupdict()\n                left_node_labels = self.detect_labels(\n                    match_dict[\"left_node\"], node_variable_dict\n                )\n                right_node_labels = self.detect_labels(\n                    match_dict[\"right_node\"], node_variable_dict\n                )\n                end_idx = (\n                    start_idx\n                    + 4\n                    + len(match_dict[\"left_node\"])\n                    + len(match_dict[\"relation\"])\n                    + len(match_dict[\"right_node\"])\n                )\n                original_partial_path = original_path[start_idx : end_idx + 1]\n                relation_direction, relation_types = self.detect_relation_types(\n                    match_dict[\"relation\"]\n                )\n                if relation_types != [] and \"\".join(relation_types).find(\"*\") != -1:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher_utils.html"}
{"id": "49198b6adcc8-4", "text": "start_idx += (\n                        len(match_dict[\"left_node\"]) + len(match_dict[\"relation\"]) + 2\n                    )\n                    continue\n                if relation_direction == \"OUTGOING\":\n                    is_legal = self.verify_schema(\n                        left_node_labels, relation_types, right_node_labels\n                    )\n                    if not is_legal:\n                        is_legal = self.verify_schema(\n                            right_node_labels, relation_types, left_node_labels\n                        )\n                        if is_legal:\n                            corrected_relation = \"<\" + match_dict[\"relation\"][:-1]\n                            corrected_partial_path = original_partial_path.replace(\n                                match_dict[\"relation\"], corrected_relation\n                            )\n                            query = query.replace(\n                                original_partial_path, corrected_partial_path\n                            )\n                        else:\n                            return \"\"\n                elif relation_direction == \"INCOMING\":\n                    is_legal = self.verify_schema(\n                        right_node_labels, relation_types, left_node_labels\n                    )\n                    if not is_legal:\n                        is_legal = self.verify_schema(\n                            left_node_labels, relation_types, right_node_labels\n                        )\n                        if is_legal:\n                            corrected_relation = match_dict[\"relation\"][1:] + \">\"\n                            corrected_partial_path = original_partial_path.replace(\n                                match_dict[\"relation\"], corrected_relation\n                            )\n                            query = query.replace(\n                                original_partial_path, corrected_partial_path\n                            )\n                        else:\n                            return \"\"\n                else:\n                    is_legal = self.verify_schema(\n                        left_node_labels, relation_types, right_node_labels\n                    )\n                    is_legal |= self.verify_schema(\n                        right_node_labels, relation_types, left_node_labels\n                    )\n                    if not is_legal:\n                        return \"\"\n                start_idx += (\n                    len(match_dict[\"left_node\"]) + len(match_dict[\"relation\"]) + 2\n                )\n        return query", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher_utils.html"}
{"id": "49198b6adcc8-5", "text": ")\n        return query\n    def __call__(self, query: str) -> str:\n        \"\"\"Correct the query to make it valid. If\n        Args:\n            query: cypher query\n        \"\"\"\n        return self.correct_query(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher_utils.html"}
{"id": "77f2edfc50f7-0", "text": "Source code for langchain.chains.graph_qa.hugegraph\n\"\"\"Question answering over a graph.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.graph_qa.prompts import (\n    CYPHER_QA_PROMPT,\n    GREMLIN_GENERATION_PROMPT,\n)\nfrom langchain.chains.llm import LLMChain\nfrom langchain.graphs.hugegraph import HugeGraph\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class HugeGraphQAChain(Chain):\n    \"\"\"Chain for question-answering against a graph by generating gremlin statements.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    graph: HugeGraph = Field(exclude=True)\n    gremlin_generation_chain: LLMChain\n    qa_chain: LLMChain\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Input keys.\n        :meta private:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/hugegraph.html"}
{"id": "77f2edfc50f7-1", "text": "\"\"\"Input keys.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Output keys.\n        :meta private:\n        \"\"\"\n        _output_keys = [self.output_key]\n        return _output_keys\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        *,\n        qa_prompt: BasePromptTemplate = CYPHER_QA_PROMPT,\n        gremlin_prompt: BasePromptTemplate = GREMLIN_GENERATION_PROMPT,\n        **kwargs: Any,\n    ) -> HugeGraphQAChain:\n        \"\"\"Initialize from LLM.\"\"\"\n        qa_chain = LLMChain(llm=llm, prompt=qa_prompt)\n        gremlin_generation_chain = LLMChain(llm=llm, prompt=gremlin_prompt)\n        return cls(\n            qa_chain=qa_chain,\n            gremlin_generation_chain=gremlin_generation_chain,\n            **kwargs,\n        )\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        \"\"\"Generate gremlin statement, use it to look up in db and answer question.\"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        question = inputs[self.input_key]\n        generated_gremlin = self.gremlin_generation_chain.run(\n            {\"question\": question, \"schema\": self.graph.get_schema}, callbacks=callbacks\n        )\n        _run_manager.on_text(\"Generated gremlin:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/hugegraph.html"}
{"id": "77f2edfc50f7-2", "text": "_run_manager.on_text(\n            generated_gremlin, color=\"green\", end=\"\\n\", verbose=self.verbose\n        )\n        context = self.graph.query(generated_gremlin)\n        _run_manager.on_text(\"Full Context:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(\n            str(context), color=\"green\", end=\"\\n\", verbose=self.verbose\n        )\n        result = self.qa_chain(\n            {\"question\": question, \"context\": context},\n            callbacks=callbacks,\n        )\n        return {self.output_key: result[self.qa_chain.output_key]}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/hugegraph.html"}
{"id": "8f92bd80470c-0", "text": "Source code for langchain.chains.graph_qa.base\n\"\"\"Question answering over a graph.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.graph_qa.prompts import ENTITY_EXTRACTION_PROMPT, GRAPH_QA_PROMPT\nfrom langchain.chains.llm import LLMChain\nfrom langchain.graphs.networkx_graph import NetworkxEntityGraph, get_entities\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class GraphQAChain(Chain):\n    \"\"\"Chain for question-answering against a graph.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    graph: NetworkxEntityGraph = Field(exclude=True)\n    entity_extraction_chain: LLMChain\n    qa_chain: LLMChain\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Input keys.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html"}
{"id": "8f92bd80470c-1", "text": "\"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Output keys.\n        :meta private:\n        \"\"\"\n        _output_keys = [self.output_key]\n        return _output_keys\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        qa_prompt: BasePromptTemplate = GRAPH_QA_PROMPT,\n        entity_prompt: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT,\n        **kwargs: Any,\n    ) -> GraphQAChain:\n        \"\"\"Initialize from LLM.\"\"\"\n        qa_chain = LLMChain(llm=llm, prompt=qa_prompt)\n        entity_chain = LLMChain(llm=llm, prompt=entity_prompt)\n        return cls(\n            qa_chain=qa_chain,\n            entity_extraction_chain=entity_chain,\n            **kwargs,\n        )\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        \"\"\"Extract entities, look up info and answer question.\"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        question = inputs[self.input_key]\n        entity_string = self.entity_extraction_chain.run(question)\n        _run_manager.on_text(\"Entities Extracted:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(\n            entity_string, color=\"green\", end=\"\\n\", verbose=self.verbose\n        )\n        entities = get_entities(entity_string)\n        context = \"\"\n        all_triplets = []\n        for entity in entities:\n            all_triplets.extend(self.graph.get_entity_knowledge(entity))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html"}
{"id": "8f92bd80470c-2", "text": "all_triplets.extend(self.graph.get_entity_knowledge(entity))\n        context = \"\\n\".join(all_triplets)\n        _run_manager.on_text(\"Full Context:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(context, color=\"green\", end=\"\\n\", verbose=self.verbose)\n        result = self.qa_chain(\n            {\"question\": question, \"context\": context},\n            callbacks=_run_manager.get_child(),\n        )\n        return {self.output_key: result[self.qa_chain.output_key]}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html"}
{"id": "c17c1e7e05b7-0", "text": "Source code for langchain.chains.graph_qa.sparql\n\"\"\"\nQuestion answering over an RDF or OWL graph using SPARQL.\n\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.graph_qa.prompts import (\n    SPARQL_GENERATION_SELECT_PROMPT,\n    SPARQL_GENERATION_UPDATE_PROMPT,\n    SPARQL_INTENT_PROMPT,\n    SPARQL_QA_PROMPT,\n)\nfrom langchain.chains.llm import LLMChain\nfrom langchain.graphs.rdf_graph import RdfGraph\nfrom langchain.prompts.base import BasePromptTemplate\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class GraphSparqlQAChain(Chain):\n    \"\"\"Question-answering against an RDF or OWL graph by generating SPARQL statements.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    graph: RdfGraph = Field(exclude=True)\n    sparql_generation_select_chain: LLMChain\n    sparql_generation_update_chain: LLMChain\n    sparql_intent_chain: LLMChain", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/sparql.html"}
{"id": "c17c1e7e05b7-1", "text": "sparql_intent_chain: LLMChain\n    qa_chain: LLMChain\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:\n    @property\n    def input_keys(self) -> List[str]:\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        _output_keys = [self.output_key]\n        return _output_keys\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        *,\n        qa_prompt: BasePromptTemplate = SPARQL_QA_PROMPT,\n        sparql_select_prompt: BasePromptTemplate = SPARQL_GENERATION_SELECT_PROMPT,\n        sparql_update_prompt: BasePromptTemplate = SPARQL_GENERATION_UPDATE_PROMPT,\n        sparql_intent_prompt: BasePromptTemplate = SPARQL_INTENT_PROMPT,\n        **kwargs: Any,\n    ) -> GraphSparqlQAChain:\n        \"\"\"Initialize from LLM.\"\"\"\n        qa_chain = LLMChain(llm=llm, prompt=qa_prompt)\n        sparql_generation_select_chain = LLMChain(llm=llm, prompt=sparql_select_prompt)\n        sparql_generation_update_chain = LLMChain(llm=llm, prompt=sparql_update_prompt)\n        sparql_intent_chain = LLMChain(llm=llm, prompt=sparql_intent_prompt)\n        return cls(\n            qa_chain=qa_chain,\n            sparql_generation_select_chain=sparql_generation_select_chain,\n            sparql_generation_update_chain=sparql_generation_update_chain,\n            sparql_intent_chain=sparql_intent_chain,\n            **kwargs,\n        )\n    def _call(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/sparql.html"}
{"id": "c17c1e7e05b7-2", "text": "**kwargs,\n        )\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        \"\"\"\n        Generate SPARQL query, use it to retrieve a response from the gdb and answer\n        the question.\n        \"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        prompt = inputs[self.input_key]\n        _intent = self.sparql_intent_chain.run({\"prompt\": prompt}, callbacks=callbacks)\n        intent = _intent.strip()\n        if \"SELECT\" in intent and \"UPDATE\" not in intent:\n            sparql_generation_chain = self.sparql_generation_select_chain\n            intent = \"SELECT\"\n        elif \"UPDATE\" in intent and \"SELECT\" not in intent:\n            sparql_generation_chain = self.sparql_generation_update_chain\n            intent = \"UPDATE\"\n        else:\n            raise ValueError(\n                \"I am sorry, but this prompt seems to fit none of the currently \"\n                \"supported SPARQL query types, i.e., SELECT and UPDATE.\"\n            )\n        _run_manager.on_text(\"Identified intent:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(intent, color=\"green\", end=\"\\n\", verbose=self.verbose)\n        generated_sparql = sparql_generation_chain.run(\n            {\"prompt\": prompt, \"schema\": self.graph.get_schema}, callbacks=callbacks\n        )\n        _run_manager.on_text(\"Generated SPARQL:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(\n            generated_sparql, color=\"green\", end=\"\\n\", verbose=self.verbose\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/sparql.html"}
{"id": "c17c1e7e05b7-3", "text": ")\n        if intent == \"SELECT\":\n            context = self.graph.query(generated_sparql)\n            _run_manager.on_text(\"Full Context:\", end=\"\\n\", verbose=self.verbose)\n            _run_manager.on_text(\n                str(context), color=\"green\", end=\"\\n\", verbose=self.verbose\n            )\n            result = self.qa_chain(\n                {\"prompt\": prompt, \"context\": context},\n                callbacks=callbacks,\n            )\n            res = result[self.qa_chain.output_key]\n        elif intent == \"UPDATE\":\n            self.graph.update(generated_sparql)\n            res = \"Successfully inserted triples into the graph.\"\n        else:\n            raise ValueError(\"Unsupported SPARQL query type.\")\n        return {self.output_key: res}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/sparql.html"}
{"id": "19a254c2de1d-0", "text": "Source code for langchain.chains.graph_qa.neptune_cypher\nfrom __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Optional\nfrom langchain.base_language import BaseLanguageModel\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.graph_qa.prompts import (\n    CYPHER_QA_PROMPT,\n    NEPTUNE_OPENCYPHER_GENERATION_PROMPT,\n    NEPTUNE_OPENCYPHER_GENERATION_SIMPLE_PROMPT,\n)\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.prompt_selector import ConditionalPromptSelector\nfrom langchain.graphs import NeptuneGraph\nfrom langchain.prompts.base import BasePromptTemplate\nfrom langchain.pydantic_v1 import Field\nINTERMEDIATE_STEPS_KEY = \"intermediate_steps\"\n[docs]def trim_query(query: str) -> str:\n    \"\"\"Trim the query to only include Cypher keywords.\"\"\"\n    keywords = (\n        \"CALL\",\n        \"CREATE\",\n        \"DELETE\",\n        \"DETACH\",\n        \"LIMIT\",\n        \"MATCH\",\n        \"MERGE\",\n        \"OPTIONAL\",\n        \"ORDER\",\n        \"REMOVE\",\n        \"RETURN\",\n        \"SET\",\n        \"SKIP\",\n        \"UNWIND\",\n        \"WITH\",\n        \"WHERE\",\n        \"//\",\n    )\n    lines = query.split(\"\\n\")\n    new_query = \"\"\n    for line in lines:\n        if line.strip().upper().startswith(keywords):\n            new_query += line + \"\\n\"\n    return new_query\n[docs]def extract_cypher(text: str) -> str:\n    \"\"\"Extract Cypher code from text using Regex.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/neptune_cypher.html"}
{"id": "19a254c2de1d-1", "text": "\"\"\"Extract Cypher code from text using Regex.\"\"\"\n    # The pattern to find Cypher code enclosed in triple backticks\n    pattern = r\"```(.*?)```\"\n    # Find all matches in the input text\n    matches = re.findall(pattern, text, re.DOTALL)\n    return matches[0] if matches else text\n[docs]def use_simple_prompt(llm: BaseLanguageModel) -> bool:\n    \"\"\"Decides whether to use the simple prompt\"\"\"\n    if llm._llm_type and \"anthropic\" in llm._llm_type:  # type: ignore\n        return True\n    # Bedrock anthropic\n    if hasattr(llm, \"model_id\") and \"anthropic\" in llm.model_id:  # type: ignore\n        return True\n    return False\nPROMPT_SELECTOR = ConditionalPromptSelector(\n    default_prompt=NEPTUNE_OPENCYPHER_GENERATION_PROMPT,\n    conditionals=[(use_simple_prompt, NEPTUNE_OPENCYPHER_GENERATION_SIMPLE_PROMPT)],\n)\n[docs]class NeptuneOpenCypherQAChain(Chain):\n    \"\"\"Chain for question-answering against a Neptune graph\n    by generating openCypher statements.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    Example:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/neptune_cypher.html"}
{"id": "19a254c2de1d-2", "text": "See https://python.langchain.com/docs/security for more information.\n    Example:\n        .. code-block:: python\n        chain = NeptuneOpenCypherQAChain.from_llm(\n            llm=llm,\n            graph=graph\n        )\n        response = chain.run(query)\n    \"\"\"\n    graph: NeptuneGraph = Field(exclude=True)\n    cypher_generation_chain: LLMChain\n    qa_chain: LLMChain\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:\n    top_k: int = 10\n    return_intermediate_steps: bool = False\n    \"\"\"Whether or not to return the intermediate steps along with the final answer.\"\"\"\n    return_direct: bool = False\n    \"\"\"Whether or not to return the result of querying the graph directly.\"\"\"\n    extra_instructions: Optional[str] = None\n    \"\"\"Extra instructions by the appended to the query generation prompt.\"\"\"\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the output keys.\n        :meta private:\n        \"\"\"\n        _output_keys = [self.output_key]\n        return _output_keys\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        *,\n        qa_prompt: BasePromptTemplate = CYPHER_QA_PROMPT,\n        cypher_prompt: Optional[BasePromptTemplate] = None,\n        extra_instructions: Optional[str] = None,\n        **kwargs: Any,\n    ) -> NeptuneOpenCypherQAChain:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/neptune_cypher.html"}
{"id": "19a254c2de1d-3", "text": "**kwargs: Any,\n    ) -> NeptuneOpenCypherQAChain:\n        \"\"\"Initialize from LLM.\"\"\"\n        qa_chain = LLMChain(llm=llm, prompt=qa_prompt)\n        _cypher_prompt = cypher_prompt or PROMPT_SELECTOR.get_prompt(llm)\n        cypher_generation_chain = LLMChain(llm=llm, prompt=_cypher_prompt)\n        return cls(\n            qa_chain=qa_chain,\n            cypher_generation_chain=cypher_generation_chain,\n            extra_instructions=extra_instructions,\n            **kwargs,\n        )\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Generate Cypher statement, use it to look up in db and answer question.\"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        question = inputs[self.input_key]\n        intermediate_steps: List = []\n        generated_cypher = self.cypher_generation_chain.run(\n            {\n                \"question\": question,\n                \"schema\": self.graph.get_schema,\n                \"extra_instructions\": self.extra_instructions or \"\",\n            },\n            callbacks=callbacks,\n        )\n        # Extract Cypher code if it is wrapped in backticks\n        generated_cypher = extract_cypher(generated_cypher)\n        generated_cypher = trim_query(generated_cypher)\n        _run_manager.on_text(\"Generated Cypher:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(\n            generated_cypher, color=\"green\", end=\"\\n\", verbose=self.verbose\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/neptune_cypher.html"}
{"id": "19a254c2de1d-4", "text": ")\n        intermediate_steps.append({\"query\": generated_cypher})\n        context = self.graph.query(generated_cypher)\n        if self.return_direct:\n            final_result = context\n        else:\n            _run_manager.on_text(\"Full Context:\", end=\"\\n\", verbose=self.verbose)\n            _run_manager.on_text(\n                str(context), color=\"green\", end=\"\\n\", verbose=self.verbose\n            )\n            intermediate_steps.append({\"context\": context})\n            result = self.qa_chain(\n                {\"question\": question, \"context\": context},\n                callbacks=callbacks,\n            )\n            final_result = result[self.qa_chain.output_key]\n        chain_result: Dict[str, Any] = {self.output_key: final_result}\n        if self.return_intermediate_steps:\n            chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps\n        return chain_result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/neptune_cypher.html"}
{"id": "cd3cd25fe848-0", "text": "Source code for langchain.chains.graph_qa.kuzu\n\"\"\"Question answering over a graph.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.graph_qa.prompts import CYPHER_QA_PROMPT, KUZU_GENERATION_PROMPT\nfrom langchain.chains.llm import LLMChain\nfrom langchain.graphs.kuzu_graph import KuzuGraph\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class KuzuQAChain(Chain):\n    \"\"\"Question-answering against a graph by generating Cypher statements for K\u00f9zu.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    graph: KuzuGraph = Field(exclude=True)\n    cypher_generation_chain: LLMChain\n    qa_chain: LLMChain\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys.\n        :meta private:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/kuzu.html"}
{"id": "cd3cd25fe848-1", "text": "\"\"\"Return the input keys.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the output keys.\n        :meta private:\n        \"\"\"\n        _output_keys = [self.output_key]\n        return _output_keys\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        *,\n        qa_prompt: BasePromptTemplate = CYPHER_QA_PROMPT,\n        cypher_prompt: BasePromptTemplate = KUZU_GENERATION_PROMPT,\n        **kwargs: Any,\n    ) -> KuzuQAChain:\n        \"\"\"Initialize from LLM.\"\"\"\n        qa_chain = LLMChain(llm=llm, prompt=qa_prompt)\n        cypher_generation_chain = LLMChain(llm=llm, prompt=cypher_prompt)\n        return cls(\n            qa_chain=qa_chain,\n            cypher_generation_chain=cypher_generation_chain,\n            **kwargs,\n        )\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        \"\"\"Generate Cypher statement, use it to look up in db and answer question.\"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        question = inputs[self.input_key]\n        generated_cypher = self.cypher_generation_chain.run(\n            {\"question\": question, \"schema\": self.graph.get_schema}, callbacks=callbacks\n        )\n        _run_manager.on_text(\"Generated Cypher:\", end=\"\\n\", verbose=self.verbose)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/kuzu.html"}
{"id": "cd3cd25fe848-2", "text": "_run_manager.on_text(\"Generated Cypher:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(\n            generated_cypher, color=\"green\", end=\"\\n\", verbose=self.verbose\n        )\n        context = self.graph.query(generated_cypher)\n        _run_manager.on_text(\"Full Context:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(\n            str(context), color=\"green\", end=\"\\n\", verbose=self.verbose\n        )\n        result = self.qa_chain(\n            {\"question\": question, \"context\": context},\n            callbacks=callbacks,\n        )\n        return {self.output_key: result[self.qa_chain.output_key]}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/kuzu.html"}
{"id": "b7ebf2a07f04-0", "text": "Source code for langchain.chains.graph_qa.nebulagraph\n\"\"\"Question answering over a graph.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.graph_qa.prompts import CYPHER_QA_PROMPT, NGQL_GENERATION_PROMPT\nfrom langchain.chains.llm import LLMChain\nfrom langchain.graphs.nebula_graph import NebulaGraph\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class NebulaGraphQAChain(Chain):\n    \"\"\"Chain for question-answering against a graph by generating nGQL statements.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    graph: NebulaGraph = Field(exclude=True)\n    ngql_generation_chain: LLMChain\n    qa_chain: LLMChain\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys.\n        :meta private:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/nebulagraph.html"}
{"id": "b7ebf2a07f04-1", "text": "\"\"\"Return the input keys.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the output keys.\n        :meta private:\n        \"\"\"\n        _output_keys = [self.output_key]\n        return _output_keys\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        *,\n        qa_prompt: BasePromptTemplate = CYPHER_QA_PROMPT,\n        ngql_prompt: BasePromptTemplate = NGQL_GENERATION_PROMPT,\n        **kwargs: Any,\n    ) -> NebulaGraphQAChain:\n        \"\"\"Initialize from LLM.\"\"\"\n        qa_chain = LLMChain(llm=llm, prompt=qa_prompt)\n        ngql_generation_chain = LLMChain(llm=llm, prompt=ngql_prompt)\n        return cls(\n            qa_chain=qa_chain,\n            ngql_generation_chain=ngql_generation_chain,\n            **kwargs,\n        )\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        \"\"\"Generate nGQL statement, use it to look up in db and answer question.\"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        question = inputs[self.input_key]\n        generated_ngql = self.ngql_generation_chain.run(\n            {\"question\": question, \"schema\": self.graph.get_schema}, callbacks=callbacks\n        )\n        _run_manager.on_text(\"Generated nGQL:\", end=\"\\n\", verbose=self.verbose)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/nebulagraph.html"}
{"id": "b7ebf2a07f04-2", "text": "_run_manager.on_text(\n            generated_ngql, color=\"green\", end=\"\\n\", verbose=self.verbose\n        )\n        context = self.graph.query(generated_ngql)\n        _run_manager.on_text(\"Full Context:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(\n            str(context), color=\"green\", end=\"\\n\", verbose=self.verbose\n        )\n        result = self.qa_chain(\n            {\"question\": question, \"context\": context},\n            callbacks=callbacks,\n        )\n        return {self.output_key: result[self.qa_chain.output_key]}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/nebulagraph.html"}
{"id": "a85a14f9a237-0", "text": "Source code for langchain.chains.graph_qa.falkordb\n\"\"\"Question answering over a graph.\"\"\"\nfrom __future__ import annotations\nimport re\nfrom typing import Any, Dict, List, Optional\nfrom langchain.base_language import BaseLanguageModel\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.graph_qa.prompts import CYPHER_GENERATION_PROMPT, CYPHER_QA_PROMPT\nfrom langchain.chains.llm import LLMChain\nfrom langchain.graphs import FalkorDBGraph\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BasePromptTemplate\nINTERMEDIATE_STEPS_KEY = \"intermediate_steps\"\n[docs]def extract_cypher(text: str) -> str:\n    \"\"\"\n    Extract Cypher code from a text.\n    Args:\n        text: Text to extract Cypher code from.\n    Returns:\n        Cypher code extracted from the text.\n    \"\"\"\n    # The pattern to find Cypher code enclosed in triple backticks\n    pattern = r\"```(.*?)```\"\n    # Find all matches in the input text\n    matches = re.findall(pattern, text, re.DOTALL)\n    return matches[0] if matches else text\n[docs]class FalkorDBQAChain(Chain):\n    \"\"\"Chain for question-answering against a graph by generating Cypher statements.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/falkordb.html"}
{"id": "a85a14f9a237-1", "text": "data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    graph: FalkorDBGraph = Field(exclude=True)\n    cypher_generation_chain: LLMChain\n    qa_chain: LLMChain\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:\n    top_k: int = 10\n    \"\"\"Number of results to return from the query\"\"\"\n    return_intermediate_steps: bool = False\n    \"\"\"Whether or not to return the intermediate steps along with the final answer.\"\"\"\n    return_direct: bool = False\n    \"\"\"Whether or not to return the result of querying the graph directly.\"\"\"\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the output keys.\n        :meta private:\n        \"\"\"\n        _output_keys = [self.output_key]\n        return _output_keys\n    @property\n    def _chain_type(self) -> str:\n        return \"graph_cypher_chain\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        *,\n        qa_prompt: BasePromptTemplate = CYPHER_QA_PROMPT,\n        cypher_prompt: BasePromptTemplate = CYPHER_GENERATION_PROMPT,\n        **kwargs: Any,\n    ) -> FalkorDBQAChain:\n        \"\"\"Initialize from LLM.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/falkordb.html"}
{"id": "a85a14f9a237-2", "text": ") -> FalkorDBQAChain:\n        \"\"\"Initialize from LLM.\"\"\"\n        qa_chain = LLMChain(llm=llm, prompt=qa_prompt)\n        cypher_generation_chain = LLMChain(llm=llm, prompt=cypher_prompt)\n        return cls(\n            qa_chain=qa_chain,\n            cypher_generation_chain=cypher_generation_chain,\n            **kwargs,\n        )\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Generate Cypher statement, use it to look up in db and answer question.\"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        question = inputs[self.input_key]\n        intermediate_steps: List = []\n        generated_cypher = self.cypher_generation_chain.run(\n            {\"question\": question, \"schema\": self.graph.schema}, callbacks=callbacks\n        )\n        # Extract Cypher code if it is wrapped in backticks\n        generated_cypher = extract_cypher(generated_cypher)\n        _run_manager.on_text(\"Generated Cypher:\", end=\"\\n\", verbose=self.verbose)\n        _run_manager.on_text(\n            generated_cypher, color=\"green\", end=\"\\n\", verbose=self.verbose\n        )\n        intermediate_steps.append({\"query\": generated_cypher})\n        # Retrieve and limit the number of results\n        context = self.graph.query(generated_cypher)[: self.top_k]\n        if self.return_direct:\n            final_result = context\n        else:\n            _run_manager.on_text(\"Full Context:\", end=\"\\n\", verbose=self.verbose)\n            _run_manager.on_text(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/falkordb.html"}
{"id": "a85a14f9a237-3", "text": "_run_manager.on_text(\n                str(context), color=\"green\", end=\"\\n\", verbose=self.verbose\n            )\n            intermediate_steps.append({\"context\": context})\n            result = self.qa_chain(\n                {\"question\": question, \"context\": context},\n                callbacks=callbacks,\n            )\n            final_result = result[self.qa_chain.output_key]\n        chain_result: Dict[str, Any] = {self.output_key: final_result}\n        if self.return_intermediate_steps:\n            chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps\n        return chain_result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/falkordb.html"}
{"id": "e3cbe8b0e7bb-0", "text": "Source code for langchain.chains.constitutional_ai.base\n\"\"\"Chain for applying constitutional principles to the outputs of another chain.\"\"\"\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.constitutional_ai.models import ConstitutionalPrinciple\nfrom langchain.chains.constitutional_ai.principles import PRINCIPLES\nfrom langchain.chains.constitutional_ai.prompts import CRITIQUE_PROMPT, REVISION_PROMPT\nfrom langchain.chains.llm import LLMChain\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class ConstitutionalChain(Chain):\n    \"\"\"Chain for applying constitutional principles.\n    Example:\n        .. code-block:: python\n            from langchain.llms import OpenAI\n            from langchain.chains import LLMChain, ConstitutionalChain\n            from langchain.chains.constitutional_ai.models \\\n                import ConstitutionalPrinciple\n            llm = OpenAI()\n            qa_prompt = PromptTemplate(\n                template=\"Q: {question} A:\",\n                input_variables=[\"question\"],\n            )\n            qa_chain = LLMChain(llm=llm, prompt=qa_prompt)\n            constitutional_chain = ConstitutionalChain.from_llm(\n                llm=llm,\n                chain=qa_chain,\n                constitutional_principles=[\n                    ConstitutionalPrinciple(\n                        critique_request=\"Tell if this answer is good.\",\n                        revision_request=\"Give a better answer.\",\n                    )\n                ],\n            )\n            constitutional_chain.run(question=\"What is the meaning of life?\")\n    \"\"\"\n    chain: LLMChain\n    constitutional_principles: List[ConstitutionalPrinciple]\n    critique_chain: LLMChain", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html"}
{"id": "e3cbe8b0e7bb-1", "text": "critique_chain: LLMChain\n    revision_chain: LLMChain\n    return_intermediate_steps: bool = False\n[docs]    @classmethod\n    def get_principles(\n        cls, names: Optional[List[str]] = None\n    ) -> List[ConstitutionalPrinciple]:\n        if names is None:\n            return list(PRINCIPLES.values())\n        else:\n            return [PRINCIPLES[name] for name in names]\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        chain: LLMChain,\n        critique_prompt: BasePromptTemplate = CRITIQUE_PROMPT,\n        revision_prompt: BasePromptTemplate = REVISION_PROMPT,\n        **kwargs: Any,\n    ) -> \"ConstitutionalChain\":\n        \"\"\"Create a chain from an LLM.\"\"\"\n        critique_chain = LLMChain(llm=llm, prompt=critique_prompt)\n        revision_chain = LLMChain(llm=llm, prompt=revision_prompt)\n        return cls(\n            chain=chain,\n            critique_chain=critique_chain,\n            revision_chain=revision_chain,\n            **kwargs,\n        )\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Input keys.\"\"\"\n        return self.chain.input_keys\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Output keys.\"\"\"\n        if self.return_intermediate_steps:\n            return [\"output\", \"critiques_and_revisions\", \"initial_output\"]\n        return [\"output\"]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html"}
{"id": "e3cbe8b0e7bb-2", "text": ") -> Dict[str, Any]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        response = self.chain.run(\n            **inputs,\n            callbacks=_run_manager.get_child(\"original\"),\n        )\n        initial_response = response\n        input_prompt = self.chain.prompt.format(**inputs)\n        _run_manager.on_text(\n            text=\"Initial response: \" + response + \"\\n\\n\",\n            verbose=self.verbose,\n            color=\"yellow\",\n        )\n        critiques_and_revisions = []\n        for constitutional_principle in self.constitutional_principles:\n            # Do critique\n            raw_critique = self.critique_chain.run(\n                input_prompt=input_prompt,\n                output_from_model=response,\n                critique_request=constitutional_principle.critique_request,\n                callbacks=_run_manager.get_child(\"critique\"),\n            )\n            critique = self._parse_critique(\n                output_string=raw_critique,\n            ).strip()\n            # if the critique contains \"No critique needed\", then we're done\n            # in this case, initial_output is the same as output,\n            # but we'll keep it for consistency\n            if \"no critique needed\" in critique.lower():\n                critiques_and_revisions.append((critique, \"\"))\n                continue\n            # Do revision\n            revision = self.revision_chain.run(\n                input_prompt=input_prompt,\n                output_from_model=response,\n                critique_request=constitutional_principle.critique_request,\n                critique=critique,\n                revision_request=constitutional_principle.revision_request,\n                callbacks=_run_manager.get_child(\"revision\"),\n            ).strip()\n            response = revision\n            critiques_and_revisions.append((critique, revision))\n            _run_manager.on_text(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html"}
{"id": "e3cbe8b0e7bb-3", "text": "_run_manager.on_text(\n                text=f\"Applying {constitutional_principle.name}...\" + \"\\n\\n\",\n                verbose=self.verbose,\n                color=\"green\",\n            )\n            _run_manager.on_text(\n                text=\"Critique: \" + critique + \"\\n\\n\",\n                verbose=self.verbose,\n                color=\"blue\",\n            )\n            _run_manager.on_text(\n                text=\"Updated response: \" + revision + \"\\n\\n\",\n                verbose=self.verbose,\n                color=\"yellow\",\n            )\n        final_output: Dict[str, Any] = {\"output\": response}\n        if self.return_intermediate_steps:\n            final_output[\"initial_output\"] = initial_response\n            final_output[\"critiques_and_revisions\"] = critiques_and_revisions\n        return final_output\n    @staticmethod\n    def _parse_critique(output_string: str) -> str:\n        if \"Revision request:\" not in output_string:\n            return output_string\n        output_string = output_string.split(\"Revision request:\")[0]\n        if \"\\n\\n\" in output_string:\n            output_string = output_string.split(\"\\n\\n\")[0]\n        return output_string", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html"}
{"id": "661e38815525-0", "text": "Source code for langchain.chains.constitutional_ai.models\n\"\"\"Models for the Constitutional AI chain.\"\"\"\nfrom langchain.pydantic_v1 import BaseModel\n[docs]class ConstitutionalPrinciple(BaseModel):\n    \"\"\"Class for a constitutional principle.\"\"\"\n    critique_request: str\n    revision_request: str\n    name: str = \"Constitutional Principle\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/models.html"}
{"id": "d2bd37184976-0", "text": "Source code for langchain.chains.openai_functions.citation_fuzzy_match\nfrom typing import Iterator, List\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.openai_functions.utils import get_llm_kwargs\nfrom langchain.output_parsers.openai_functions import (\n    PydanticOutputFunctionsParser,\n)\nfrom langchain.prompts.chat import ChatPromptTemplate, HumanMessagePromptTemplate\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import HumanMessage, SystemMessage\n[docs]class FactWithEvidence(BaseModel):\n    \"\"\"Class representing a single statement.\n    Each fact has a body and a list of sources.\n    If there are multiple facts make sure to break them apart\n    such that each one only uses a set of sources that are relevant to it.\n    \"\"\"\n    fact: str = Field(..., description=\"Body of the sentence, as part of a response\")\n    substring_quote: List[str] = Field(\n        ...,\n        description=(\n            \"Each source should be a direct quote from the context, \"\n            \"as a substring of the original content\"\n        ),\n    )\n    def _get_span(self, quote: str, context: str, errs: int = 100) -> Iterator[str]:\n        import regex\n        minor = quote\n        major = context\n        errs_ = 0\n        s = regex.search(f\"({minor}){{e<={errs_}}}\", major)\n        while s is None and errs_ <= errs:\n            errs_ += 1\n            s = regex.search(f\"({minor}){{e<={errs_}}}\", major)\n        if s is not None:\n            yield from s.spans()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/citation_fuzzy_match.html"}
{"id": "d2bd37184976-1", "text": "if s is not None:\n            yield from s.spans()\n[docs]    def get_spans(self, context: str) -> Iterator[str]:\n        for quote in self.substring_quote:\n            yield from self._get_span(quote, context)\n[docs]class QuestionAnswer(BaseModel):\n    \"\"\"A question and its answer as a list of facts each one should have a source.\n    each sentence contains a body and a list of sources.\"\"\"\n    question: str = Field(..., description=\"Question that was asked\")\n    answer: List[FactWithEvidence] = Field(\n        ...,\n        description=(\n            \"Body of the answer, each fact should be \"\n            \"its separate object with a body and a list of sources\"\n        ),\n    )\n[docs]def create_citation_fuzzy_match_chain(llm: BaseLanguageModel) -> LLMChain:\n    \"\"\"Create a citation fuzzy match chain.\n    Args:\n        llm: Language model to use for the chain.\n    Returns:\n        Chain (LLMChain) that can be used to answer questions with citations.\n    \"\"\"\n    output_parser = PydanticOutputFunctionsParser(pydantic_schema=QuestionAnswer)\n    schema = QuestionAnswer.schema()\n    function = {\n        \"name\": schema[\"title\"],\n        \"description\": schema[\"description\"],\n        \"parameters\": schema,\n    }\n    llm_kwargs = get_llm_kwargs(function)\n    messages = [\n        SystemMessage(\n            content=(\n                \"You are a world class algorithm to answer \"\n                \"questions with correct and exact citations.\"\n            )\n        ),\n        HumanMessage(content=\"Answer question using the following context\"),\n        HumanMessagePromptTemplate.from_template(\"{context}\"),\n        HumanMessagePromptTemplate.from_template(\"Question: {question}\"),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/citation_fuzzy_match.html"}
{"id": "d2bd37184976-2", "text": "HumanMessagePromptTemplate.from_template(\"Question: {question}\"),\n        HumanMessage(\n            content=(\n                \"Tips: Make sure to cite your sources, \"\n                \"and use the exact words from the context.\"\n            )\n        ),\n    ]\n    prompt = ChatPromptTemplate(messages=messages)\n    chain = LLMChain(\n        llm=llm,\n        prompt=prompt,\n        llm_kwargs=llm_kwargs,\n        output_parser=output_parser,\n    )\n    return chain", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/citation_fuzzy_match.html"}
{"id": "40e078c7ee99-0", "text": "Source code for langchain.chains.openai_functions.base\n\"\"\"Methods for creating chains that use OpenAI function-calling APIs.\"\"\"\nimport inspect\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    Type,\n    Union,\n    cast,\n)\nfrom langchain.base_language import BaseLanguageModel\nfrom langchain.chains import LLMChain\nfrom langchain.output_parsers.openai_functions import (\n    JsonOutputFunctionsParser,\n    PydanticAttrOutputFunctionsParser,\n    PydanticOutputFunctionsParser,\n)\nfrom langchain.prompts import BasePromptTemplate\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema import BaseLLMOutputParser\nfrom langchain.schema.output_parser import BaseGenerationOutputParser, BaseOutputParser\nfrom langchain.schema.runnable import Runnable\nfrom langchain.utils.openai_functions import convert_pydantic_to_openai_function\nPYTHON_TO_JSON_TYPES = {\n    \"str\": \"string\",\n    \"int\": \"number\",\n    \"float\": \"number\",\n    \"bool\": \"boolean\",\n}\ndef _get_python_function_name(function: Callable) -> str:\n    \"\"\"Get the name of a Python function.\"\"\"\n    return function.__name__\ndef _parse_python_function_docstring(function: Callable) -> Tuple[str, dict]:\n    \"\"\"Parse the function and argument descriptions from the docstring of a function.\n    Assumes the function docstring follows Google Python style guide.\n    \"\"\"\n    docstring = inspect.getdoc(function)\n    if docstring:\n        docstring_blocks = docstring.split(\"\\n\\n\")\n        descriptors = []\n        args_block = None\n        past_descriptors = False\n        for block in docstring_blocks:\n            if block.startswith(\"Args:\"):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "40e078c7ee99-1", "text": "for block in docstring_blocks:\n            if block.startswith(\"Args:\"):\n                args_block = block\n                break\n            elif block.startswith(\"Returns:\") or block.startswith(\"Example:\"):\n                # Don't break in case Args come after\n                past_descriptors = True\n            elif not past_descriptors:\n                descriptors.append(block)\n            else:\n                continue\n        description = \" \".join(descriptors)\n    else:\n        description = \"\"\n        args_block = None\n    arg_descriptions = {}\n    if args_block:\n        arg = None\n        for line in args_block.split(\"\\n\")[1:]:\n            if \":\" in line:\n                arg, desc = line.split(\":\")\n                arg_descriptions[arg.strip()] = desc.strip()\n            elif arg:\n                arg_descriptions[arg.strip()] += \" \" + line.strip()\n    return description, arg_descriptions\ndef _get_python_function_arguments(function: Callable, arg_descriptions: dict) -> dict:\n    \"\"\"Get JsonSchema describing a Python functions arguments.\n    Assumes all function arguments are of primitive types (int, float, str, bool) or\n    are subclasses of pydantic.BaseModel.\n    \"\"\"\n    properties = {}\n    annotations = inspect.getfullargspec(function).annotations\n    for arg, arg_type in annotations.items():\n        if arg == \"return\":\n            continue\n        if isinstance(arg_type, type) and issubclass(arg_type, BaseModel):\n            # Mypy error:\n            # \"type\" has no attribute \"schema\"\n            properties[arg] = arg_type.schema()  # type: ignore[attr-defined]\n        elif arg_type.__name__ in PYTHON_TO_JSON_TYPES:\n            properties[arg] = {\"type\": PYTHON_TO_JSON_TYPES[arg_type.__name__]}\n        if arg in arg_descriptions:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "40e078c7ee99-2", "text": "if arg in arg_descriptions:\n            if arg not in properties:\n                properties[arg] = {}\n            properties[arg][\"description\"] = arg_descriptions[arg]\n    return properties\ndef _get_python_function_required_args(function: Callable) -> List[str]:\n    \"\"\"Get the required arguments for a Python function.\"\"\"\n    spec = inspect.getfullargspec(function)\n    required = spec.args[: -len(spec.defaults)] if spec.defaults else spec.args\n    required += [k for k in spec.kwonlyargs if k not in (spec.kwonlydefaults or {})]\n    is_class = type(function) is type\n    if is_class and required[0] == \"self\":\n        required = required[1:]\n    return required\n[docs]def convert_python_function_to_openai_function(\n    function: Callable,\n) -> Dict[str, Any]:\n    \"\"\"Convert a Python function to an OpenAI function-calling API compatible dict.\n    Assumes the Python function has type hints and a docstring with a description. If\n        the docstring has Google Python style argument descriptions, these will be\n        included as well.\n    \"\"\"\n    description, arg_descriptions = _parse_python_function_docstring(function)\n    return {\n        \"name\": _get_python_function_name(function),\n        \"description\": description,\n        \"parameters\": {\n            \"type\": \"object\",\n            \"properties\": _get_python_function_arguments(function, arg_descriptions),\n            \"required\": _get_python_function_required_args(function),\n        },\n    }\n[docs]def convert_to_openai_function(\n    function: Union[Dict[str, Any], Type[BaseModel], Callable]\n) -> Dict[str, Any]:\n    \"\"\"Convert a raw function/class to an OpenAI function.\n    Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "40e078c7ee99-3", "text": "\"\"\"Convert a raw function/class to an OpenAI function.\n    Args:\n        function: Either a dictionary, a pydantic.BaseModel class, or a Python function.\n            If a dictionary is passed in, it is assumed to already be a valid OpenAI\n            function.\n    Returns:\n        A dict version of the passed in function which is compatible with the\n            OpenAI function-calling API.\n    \"\"\"\n    if isinstance(function, dict):\n        return function\n    elif isinstance(function, type) and issubclass(function, BaseModel):\n        return cast(Dict, convert_pydantic_to_openai_function(function))\n    elif callable(function):\n        return convert_python_function_to_openai_function(function)\n    else:\n        raise ValueError(\n            f\"Unsupported function type {type(function)}. Functions must be passed in\"\n            f\" as Dict, pydantic.BaseModel, or Callable.\"\n        )\n[docs]def get_openai_output_parser(\n    functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]],\n) -> Union[BaseOutputParser, BaseGenerationOutputParser]:\n    \"\"\"Get the appropriate function output parser given the user functions.\n    Args:\n        functions: Sequence where element is a dictionary, a pydantic.BaseModel class,\n            or a Python function. If a dictionary is passed in, it is assumed to\n            already be a valid OpenAI function.\n    Returns:\n        A PydanticOutputFunctionsParser if functions are Pydantic classes, otherwise\n            a JsonOutputFunctionsParser. If there's only one function and it is\n            not a Pydantic class, then the output parser will automatically extract\n            only the function arguments and not the function name.\n    \"\"\"\n    function_names = [convert_to_openai_function(f)[\"name\"] for f in functions]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "40e078c7ee99-4", "text": "function_names = [convert_to_openai_function(f)[\"name\"] for f in functions]\n    if isinstance(functions[0], type) and issubclass(functions[0], BaseModel):\n        if len(functions) > 1:\n            pydantic_schema: Union[Dict, Type[BaseModel]] = {\n                name: fn for name, fn in zip(function_names, functions)\n            }\n        else:\n            pydantic_schema = functions[0]\n        output_parser: Union[\n            BaseOutputParser, BaseGenerationOutputParser\n        ] = PydanticOutputFunctionsParser(pydantic_schema=pydantic_schema)\n    else:\n        output_parser = JsonOutputFunctionsParser(args_only=len(functions) <= 1)\n    return output_parser\n[docs]def create_openai_fn_runnable(\n    functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]],\n    llm: Runnable,\n    prompt: BasePromptTemplate,\n    *,\n    output_parser: Optional[Union[BaseOutputParser, BaseGenerationOutputParser]] = None,\n    **kwargs: Any,\n) -> Runnable:\n    \"\"\"Create a runnable sequence that uses OpenAI functions.\n    Args:\n        functions: A sequence of either dictionaries, pydantic.BaseModels classes, or\n            Python functions. If dictionaries are passed in, they are assumed to\n            already be a valid OpenAI functions. If only a single\n            function is passed in, then it will be enforced that the model use that\n            function. pydantic.BaseModels and Python functions should have docstrings\n            describing what the function does. For best results, pydantic.BaseModels\n            should have descriptions of the parameters and Python functions should have\n            Google Python style args descriptions in the docstring. Additionally,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "40e078c7ee99-5", "text": "Google Python style args descriptions in the docstring. Additionally,\n            Python functions should only use primitive types (str, int, float, bool) or\n            pydantic.BaseModels for arguments.\n        llm: Language model to use, assumed to support the OpenAI function-calling API.\n        prompt: BasePromptTemplate to pass to the model.\n        output_parser: BaseLLMOutputParser to use for parsing model outputs. By default\n            will be inferred from the function types. If pydantic.BaseModels are passed\n            in, then the OutputParser will try to parse outputs using those. Otherwise\n            model outputs will simply be parsed as JSON. If multiple functions are\n            passed in and they are not pydantic.BaseModels, the chain output will\n            include both the name of the function that was returned and the arguments\n            to pass to the function.\n    Returns:\n        A runnable sequence that will pass in the given functions to the model when run.\n    Example:\n        .. code-block:: python\n                from typing import Optional\n                from langchain.chains.openai_functions import create_openai_fn_chain\n                from langchain.chat_models import ChatOpenAI\n                from langchain.prompts import ChatPromptTemplate\n                from langchain.pydantic_v1 import BaseModel, Field\n                class RecordPerson(BaseModel):\n                    \\\"\\\"\\\"Record some identifying information about a person.\\\"\\\"\\\"\n                    name: str = Field(..., description=\"The person's name\")\n                    age: int = Field(..., description=\"The person's age\")\n                    fav_food: Optional[str] = Field(None, description=\"The person's favorite food\")\n                class RecordDog(BaseModel):\n                    \\\"\\\"\\\"Record some identifying information about a dog.\\\"\\\"\\\"\n                    name: str = Field(..., description=\"The dog's name\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "40e078c7ee99-6", "text": "name: str = Field(..., description=\"The dog's name\")\n                    color: str = Field(..., description=\"The dog's color\")\n                    fav_food: Optional[str] = Field(None, description=\"The dog's favorite food\")\n                llm = ChatOpenAI(model=\"gpt-4\", temperature=0)\n                prompt = ChatPromptTemplate.from_messages(\n                    [\n                        (\"system\", \"You are a world class algorithm for recording entities.\"),\n                        (\"human\", \"Make calls to the relevant function to record the entities in the following input: {input}\"),\n                        (\"human\", \"Tip: Make sure to answer in the correct format\"),\n                    ]\n                )\n                chain = create_openai_fn_runnable([RecordPerson, RecordDog], llm, prompt)\n                chain.invoke({\"input\": \"Harry was a chubby brown beagle who loved chicken\"})\n                # -> RecordDog(name=\"Harry\", color=\"brown\", fav_food=\"chicken\")\n    \"\"\"  # noqa: E501\n    if not functions:\n        raise ValueError(\"Need to pass in at least one function. Received zero.\")\n    openai_functions = [convert_to_openai_function(f) for f in functions]\n    llm_kwargs: Dict[str, Any] = {\"functions\": openai_functions, **kwargs}\n    if len(openai_functions) == 1:\n        llm_kwargs[\"function_call\"] = {\"name\": openai_functions[0][\"name\"]}\n    output_parser = output_parser or get_openai_output_parser(functions)\n    return prompt | llm.bind(**llm_kwargs) | output_parser\n[docs]def create_structured_output_runnable(\n    output_schema: Union[Dict[str, Any], Type[BaseModel]],\n    llm: Runnable,\n    prompt: BasePromptTemplate,\n    *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "40e078c7ee99-7", "text": "llm: Runnable,\n    prompt: BasePromptTemplate,\n    *,\n    output_parser: Optional[Union[BaseOutputParser, BaseGenerationOutputParser]] = None,\n    **kwargs: Any,\n) -> Runnable:\n    \"\"\"Create a runnable that uses an OpenAI function to get a structured output.\n    Args:\n        output_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary\n            is passed in, it's assumed to already be a valid JsonSchema.\n            For best results, pydantic.BaseModels should have docstrings describing what\n            the schema represents and descriptions for the parameters.\n        llm: Language model to use, assumed to support the OpenAI function-calling API.\n        prompt: BasePromptTemplate to pass to the model.\n        output_parser: BaseLLMOutputParser to use for parsing model outputs. By default\n            will be inferred from the function types. If pydantic.BaseModels are passed\n            in, then the OutputParser will try to parse outputs using those. Otherwise\n            model outputs will simply be parsed as JSON.\n    Returns:\n        A runnable sequence that will pass the given function to the model when run.\n    Example:\n        .. code-block:: python\n                from typing import Optional\n                from langchain.chains.openai_functions import create_structured_output_chain\n                from langchain.chat_models import ChatOpenAI\n                from langchain.prompts import ChatPromptTemplate\n                from langchain.pydantic_v1 import BaseModel, Field\n                class Dog(BaseModel):\n                    \\\"\\\"\\\"Identifying information about a dog.\\\"\\\"\\\"\n                    name: str = Field(..., description=\"The dog's name\")\n                    color: str = Field(..., description=\"The dog's color\")\n                    fav_food: Optional[str] = Field(None, description=\"The dog's favorite food\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "40e078c7ee99-8", "text": "fav_food: Optional[str] = Field(None, description=\"The dog's favorite food\")\n                llm = ChatOpenAI(model=\"gpt-3.5-turbo-0613\", temperature=0)\n                prompt = ChatPromptTemplate.from_messages(\n                    [\n                        (\"system\", \"You are a world class algorithm for extracting information in structured formats.\"),\n                        (\"human\", \"Use the given format to extract information from the following input: {input}\"),\n                        (\"human\", \"Tip: Make sure to answer in the correct format\"),\n                    ]\n                )\n                chain = create_structured_output_chain(Dog, llm, prompt)\n                chain.invoke({\"input\": \"Harry was a chubby brown beagle who loved chicken\"})\n                # -> Dog(name=\"Harry\", color=\"brown\", fav_food=\"chicken\")\n    \"\"\"  # noqa: E501\n    if isinstance(output_schema, dict):\n        function: Any = {\n            \"name\": \"output_formatter\",\n            \"description\": (\n                \"Output formatter. Should always be used to format your response to the\"\n                \" user.\"\n            ),\n            \"parameters\": output_schema,\n        }\n    else:\n        class _OutputFormatter(BaseModel):\n            \"\"\"Output formatter. Should always be used to format your response to the user.\"\"\"  # noqa: E501\n            output: output_schema  # type: ignore\n        function = _OutputFormatter\n        output_parser = output_parser or PydanticAttrOutputFunctionsParser(\n            pydantic_schema=_OutputFormatter, attr_name=\"output\"\n        )\n    return create_openai_fn_runnable(\n        [function],\n        llm,\n        prompt,\n        output_parser=output_parser,\n        **kwargs,\n    )\n\"\"\" --- Legacy --- \"\"\"\n[docs]def create_openai_fn_chain(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "40e078c7ee99-9", "text": ")\n\"\"\" --- Legacy --- \"\"\"\n[docs]def create_openai_fn_chain(\n    functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]],\n    llm: BaseLanguageModel,\n    prompt: BasePromptTemplate,\n    *,\n    output_key: str = \"function\",\n    output_parser: Optional[BaseLLMOutputParser] = None,\n    **kwargs: Any,\n) -> LLMChain:\n    \"\"\"[Legacy] Create an LLM chain that uses OpenAI functions.\n    Args:\n        functions: A sequence of either dictionaries, pydantic.BaseModels classes, or\n            Python functions. If dictionaries are passed in, they are assumed to\n            already be a valid OpenAI functions. If only a single\n            function is passed in, then it will be enforced that the model use that\n            function. pydantic.BaseModels and Python functions should have docstrings\n            describing what the function does. For best results, pydantic.BaseModels\n            should have descriptions of the parameters and Python functions should have\n            Google Python style args descriptions in the docstring. Additionally,\n            Python functions should only use primitive types (str, int, float, bool) or\n            pydantic.BaseModels for arguments.\n        llm: Language model to use, assumed to support the OpenAI function-calling API.\n        prompt: BasePromptTemplate to pass to the model.\n        output_key: The key to use when returning the output in LLMChain.__call__.\n        output_parser: BaseLLMOutputParser to use for parsing model outputs. By default\n            will be inferred from the function types. If pydantic.BaseModels are passed\n            in, then the OutputParser will try to parse outputs using those. Otherwise\n            model outputs will simply be parsed as JSON. If multiple functions are", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "40e078c7ee99-10", "text": "model outputs will simply be parsed as JSON. If multiple functions are\n            passed in and they are not pydantic.BaseModels, the chain output will\n            include both the name of the function that was returned and the arguments\n            to pass to the function.\n    Returns:\n        An LLMChain that will pass in the given functions to the model when run.\n    Example:\n        .. code-block:: python\n                from typing import Optional\n                from langchain.chains.openai_functions import create_openai_fn_chain\n                from langchain.chat_models import ChatOpenAI\n                from langchain.prompts import ChatPromptTemplate\n                from langchain.pydantic_v1 import BaseModel, Field\n                class RecordPerson(BaseModel):\n                    \\\"\\\"\\\"Record some identifying information about a person.\\\"\\\"\\\"\n                    name: str = Field(..., description=\"The person's name\")\n                    age: int = Field(..., description=\"The person's age\")\n                    fav_food: Optional[str] = Field(None, description=\"The person's favorite food\")\n                class RecordDog(BaseModel):\n                    \\\"\\\"\\\"Record some identifying information about a dog.\\\"\\\"\\\"\n                    name: str = Field(..., description=\"The dog's name\")\n                    color: str = Field(..., description=\"The dog's color\")\n                    fav_food: Optional[str] = Field(None, description=\"The dog's favorite food\")\n                llm = ChatOpenAI(model=\"gpt-4\", temperature=0)\n                prompt = ChatPromptTemplate.from_messages(\n                    [\n                        (\"system\", \"You are a world class algorithm for recording entities.\"),\n                        (\"human\", \"Make calls to the relevant function to record the entities in the following input: {input}\"),\n                        (\"human\", \"Tip: Make sure to answer in the correct format\"),\n                    ]\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "40e078c7ee99-11", "text": "]\n                )\n                chain = create_openai_fn_chain([RecordPerson, RecordDog], llm, prompt)\n                chain.run(\"Harry was a chubby brown beagle who loved chicken\")\n                # -> RecordDog(name=\"Harry\", color=\"brown\", fav_food=\"chicken\")\n    \"\"\"  # noqa: E501\n    if not functions:\n        raise ValueError(\"Need to pass in at least one function. Received zero.\")\n    openai_functions = [convert_to_openai_function(f) for f in functions]\n    output_parser = output_parser or get_openai_output_parser(functions)\n    llm_kwargs: Dict[str, Any] = {\n        \"functions\": openai_functions,\n    }\n    if len(openai_functions) == 1:\n        llm_kwargs[\"function_call\"] = {\"name\": openai_functions[0][\"name\"]}\n    llm_chain = LLMChain(\n        llm=llm,\n        prompt=prompt,\n        output_parser=output_parser,\n        llm_kwargs=llm_kwargs,\n        output_key=output_key,\n        **kwargs,\n    )\n    return llm_chain\n[docs]def create_structured_output_chain(\n    output_schema: Union[Dict[str, Any], Type[BaseModel]],\n    llm: BaseLanguageModel,\n    prompt: BasePromptTemplate,\n    *,\n    output_key: str = \"function\",\n    output_parser: Optional[BaseLLMOutputParser] = None,\n    **kwargs: Any,\n) -> LLMChain:\n    \"\"\"[Legacy] Create an LLMChain that uses an OpenAI function to get a structured output.\n    Args:\n        output_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "40e078c7ee99-12", "text": "output_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary\n            is passed in, it's assumed to already be a valid JsonSchema.\n            For best results, pydantic.BaseModels should have docstrings describing what\n            the schema represents and descriptions for the parameters.\n        llm: Language model to use, assumed to support the OpenAI function-calling API.\n        prompt: BasePromptTemplate to pass to the model.\n        output_key: The key to use when returning the output in LLMChain.__call__.\n        output_parser: BaseLLMOutputParser to use for parsing model outputs. By default\n            will be inferred from the function types. If pydantic.BaseModels are passed\n            in, then the OutputParser will try to parse outputs using those. Otherwise\n            model outputs will simply be parsed as JSON.\n    Returns:\n        An LLMChain that will pass the given function to the model.\n    Example:\n        .. code-block:: python\n                from typing import Optional\n                from langchain.chains.openai_functions import create_structured_output_chain\n                from langchain.chat_models import ChatOpenAI\n                from langchain.prompts import ChatPromptTemplate\n                from langchain.pydantic_v1 import BaseModel, Field\n                class Dog(BaseModel):\n                    \\\"\\\"\\\"Identifying information about a dog.\\\"\\\"\\\"\n                    name: str = Field(..., description=\"The dog's name\")\n                    color: str = Field(..., description=\"The dog's color\")\n                    fav_food: Optional[str] = Field(None, description=\"The dog's favorite food\")\n                llm = ChatOpenAI(model=\"gpt-3.5-turbo-0613\", temperature=0)\n                prompt = ChatPromptTemplate.from_messages(\n                    [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "40e078c7ee99-13", "text": "prompt = ChatPromptTemplate.from_messages(\n                    [\n                        (\"system\", \"You are a world class algorithm for extracting information in structured formats.\"),\n                        (\"human\", \"Use the given format to extract information from the following input: {input}\"),\n                        (\"human\", \"Tip: Make sure to answer in the correct format\"),\n                    ]\n                )\n                chain = create_structured_output_chain(Dog, llm, prompt)\n                chain.run(\"Harry was a chubby brown beagle who loved chicken\")\n                # -> Dog(name=\"Harry\", color=\"brown\", fav_food=\"chicken\")\n    \"\"\"  # noqa: E501\n    if isinstance(output_schema, dict):\n        function: Any = {\n            \"name\": \"output_formatter\",\n            \"description\": (\n                \"Output formatter. Should always be used to format your response to the\"\n                \" user.\"\n            ),\n            \"parameters\": output_schema,\n        }\n    else:\n        class _OutputFormatter(BaseModel):\n            \"\"\"Output formatter. Should always be used to format your response to the user.\"\"\"  # noqa: E501\n            output: output_schema  # type: ignore\n        function = _OutputFormatter\n        output_parser = output_parser or PydanticAttrOutputFunctionsParser(\n            pydantic_schema=_OutputFormatter, attr_name=\"output\"\n        )\n    return create_openai_fn_chain(\n        [function],\n        llm,\n        prompt,\n        output_key=output_key,\n        output_parser=output_parser,\n        **kwargs,\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html"}
{"id": "c12915812514-0", "text": "Source code for langchain.chains.openai_functions.qa_with_structure\nfrom typing import Any, List, Optional, Type, Union\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.openai_functions.utils import get_llm_kwargs\nfrom langchain.output_parsers.openai_functions import (\n    OutputFunctionsParser,\n    PydanticOutputFunctionsParser,\n)\nfrom langchain.prompts import PromptTemplate\nfrom langchain.prompts.chat import ChatPromptTemplate, HumanMessagePromptTemplate\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema import BaseLLMOutputParser\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import HumanMessage, SystemMessage\n[docs]class AnswerWithSources(BaseModel):\n    \"\"\"An answer to the question, with sources.\"\"\"\n    answer: str = Field(..., description=\"Answer to the question that was asked\")\n    sources: List[str] = Field(\n        ..., description=\"List of sources used to answer the question\"\n    )\n[docs]def create_qa_with_structure_chain(\n    llm: BaseLanguageModel,\n    schema: Union[dict, Type[BaseModel]],\n    output_parser: str = \"base\",\n    prompt: Optional[Union[PromptTemplate, ChatPromptTemplate]] = None,\n    verbose: bool = False,\n) -> LLMChain:\n    \"\"\"Create a question answering chain that returns an answer with sources\n     based on schema.\n    Args:\n        llm: Language model to use for the chain.\n        schema: Pydantic schema to use for the output.\n        output_parser: Output parser to use. Should be one of `pydantic` or `base`.\n            Default to `base`.\n        prompt: Optional prompt to use for the chain.\n    Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/qa_with_structure.html"}
{"id": "c12915812514-1", "text": "prompt: Optional prompt to use for the chain.\n    Returns:\n    \"\"\"\n    if output_parser == \"pydantic\":\n        if not (isinstance(schema, type) and issubclass(schema, BaseModel)):\n            raise ValueError(\n                \"Must provide a pydantic class for schema when output_parser is \"\n                \"'pydantic'.\"\n            )\n        _output_parser: BaseLLMOutputParser = PydanticOutputFunctionsParser(\n            pydantic_schema=schema\n        )\n    elif output_parser == \"base\":\n        _output_parser = OutputFunctionsParser()\n    else:\n        raise ValueError(\n            f\"Got unexpected output_parser: {output_parser}. \"\n            f\"Should be one of `pydantic` or `base`.\"\n        )\n    if isinstance(schema, type) and issubclass(schema, BaseModel):\n        schema_dict = schema.schema()\n    else:\n        schema_dict = schema\n    function = {\n        \"name\": schema_dict[\"title\"],\n        \"description\": schema_dict[\"description\"],\n        \"parameters\": schema_dict,\n    }\n    llm_kwargs = get_llm_kwargs(function)\n    messages = [\n        SystemMessage(\n            content=(\n                \"You are a world class algorithm to answer \"\n                \"questions in a specific format.\"\n            )\n        ),\n        HumanMessage(content=\"Answer question using the following context\"),\n        HumanMessagePromptTemplate.from_template(\"{context}\"),\n        HumanMessagePromptTemplate.from_template(\"Question: {question}\"),\n        HumanMessage(content=\"Tips: Make sure to answer in the correct format\"),\n    ]\n    prompt = prompt or ChatPromptTemplate(messages=messages)\n    chain = LLMChain(\n        llm=llm,\n        prompt=prompt,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/qa_with_structure.html"}
{"id": "c12915812514-2", "text": "llm=llm,\n        prompt=prompt,\n        llm_kwargs=llm_kwargs,\n        output_parser=_output_parser,\n        verbose=verbose,\n    )\n    return chain\n[docs]def create_qa_with_sources_chain(\n    llm: BaseLanguageModel, verbose: bool = False, **kwargs: Any\n) -> LLMChain:\n    \"\"\"Create a question answering chain that returns an answer with sources.\n    Args:\n        llm: Language model to use for the chain.\n        verbose: Whether to print the details of the chain\n        **kwargs: Keyword arguments to pass to `create_qa_with_structure_chain`.\n    Returns:\n        Chain (LLMChain) that can be used to answer questions with citations.\n    \"\"\"\n    return create_qa_with_structure_chain(\n        llm, AnswerWithSources, verbose=verbose, **kwargs\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/qa_with_structure.html"}
{"id": "42e0fb958e32-0", "text": "Source code for langchain.chains.openai_functions.utils\nfrom typing import Any, Dict\ndef _resolve_schema_references(schema: Any, definitions: Dict[str, Any]) -> Any:\n    \"\"\"\n    Resolves the $ref keys in a JSON schema object using the provided definitions.\n    \"\"\"\n    if isinstance(schema, list):\n        for i, item in enumerate(schema):\n            schema[i] = _resolve_schema_references(item, definitions)\n    elif isinstance(schema, dict):\n        if \"$ref\" in schema:\n            ref_key = schema.pop(\"$ref\").split(\"/\")[-1]\n            ref = definitions.get(ref_key, {})\n            schema.update(ref)\n        else:\n            for key, value in schema.items():\n                schema[key] = _resolve_schema_references(value, definitions)\n    return schema\ndef _convert_schema(schema: dict) -> dict:\n    props = {k: {\"title\": k, **v} for k, v in schema[\"properties\"].items()}\n    return {\n        \"type\": \"object\",\n        \"properties\": props,\n        \"required\": schema.get(\"required\", []),\n    }\n[docs]def get_llm_kwargs(function: dict) -> dict:\n    \"\"\"Returns the kwargs for the LLMChain constructor.\n    Args:\n        function: The function to use.\n    Returns:\n        The kwargs for the LLMChain constructor.\n    \"\"\"\n    return {\"functions\": [function], \"function_call\": {\"name\": function[\"name\"]}}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/utils.html"}
{"id": "d255c12e79cc-0", "text": "Source code for langchain.chains.openai_functions.tagging\nfrom typing import Any, Optional\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.openai_functions.utils import _convert_schema, get_llm_kwargs\nfrom langchain.output_parsers.openai_functions import (\n    JsonOutputFunctionsParser,\n    PydanticOutputFunctionsParser,\n)\nfrom langchain.prompts import ChatPromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\ndef _get_tagging_function(schema: dict) -> dict:\n    return {\n        \"name\": \"information_extraction\",\n        \"description\": \"Extracts the relevant information from the passage.\",\n        \"parameters\": _convert_schema(schema),\n    }\n_TAGGING_TEMPLATE = \"\"\"Extract the desired information from the following passage.\nOnly extract the properties mentioned in the 'information_extraction' function.\nPassage:\n{input}\n\"\"\"\n[docs]def create_tagging_chain(\n    schema: dict,\n    llm: BaseLanguageModel,\n    prompt: Optional[ChatPromptTemplate] = None,\n    **kwargs: Any,\n) -> Chain:\n    \"\"\"Creates a chain that extracts information from a passage\n     based on a schema.\n    Args:\n        schema: The schema of the entities to extract.\n        llm: The language model to use.\n    Returns:\n        Chain (LLMChain) that can be used to extract information from a passage.\n    \"\"\"\n    function = _get_tagging_function(schema)\n    prompt = prompt or ChatPromptTemplate.from_template(_TAGGING_TEMPLATE)\n    output_parser = JsonOutputFunctionsParser()\n    llm_kwargs = get_llm_kwargs(function)\n    chain = LLMChain(\n        llm=llm,\n        prompt=prompt,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/tagging.html"}
{"id": "d255c12e79cc-1", "text": "llm=llm,\n        prompt=prompt,\n        llm_kwargs=llm_kwargs,\n        output_parser=output_parser,\n        **kwargs,\n    )\n    return chain\n[docs]def create_tagging_chain_pydantic(\n    pydantic_schema: Any,\n    llm: BaseLanguageModel,\n    prompt: Optional[ChatPromptTemplate] = None,\n    **kwargs: Any,\n) -> Chain:\n    \"\"\"Creates a chain that extracts information from a passage\n     based on a pydantic schema.\n    Args:\n        pydantic_schema: The pydantic schema of the entities to extract.\n        llm: The language model to use.\n    Returns:\n        Chain (LLMChain) that can be used to extract information from a passage.\n    \"\"\"\n    openai_schema = pydantic_schema.schema()\n    function = _get_tagging_function(openai_schema)\n    prompt = prompt or ChatPromptTemplate.from_template(_TAGGING_TEMPLATE)\n    output_parser = PydanticOutputFunctionsParser(pydantic_schema=pydantic_schema)\n    llm_kwargs = get_llm_kwargs(function)\n    chain = LLMChain(\n        llm=llm,\n        prompt=prompt,\n        llm_kwargs=llm_kwargs,\n        output_parser=output_parser,\n        **kwargs,\n    )\n    return chain", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/tagging.html"}
{"id": "4eea511ec31a-0", "text": "Source code for langchain.chains.openai_functions.extraction\nfrom typing import Any, List, Optional\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.openai_functions.utils import (\n    _convert_schema,\n    _resolve_schema_references,\n    get_llm_kwargs,\n)\nfrom langchain.output_parsers.openai_functions import (\n    JsonKeyOutputFunctionsParser,\n    PydanticAttrOutputFunctionsParser,\n)\nfrom langchain.prompts import ChatPromptTemplate\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\ndef _get_extraction_function(entity_schema: dict) -> dict:\n    return {\n        \"name\": \"information_extraction\",\n        \"description\": \"Extracts the relevant information from the passage.\",\n        \"parameters\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"info\": {\"type\": \"array\", \"items\": _convert_schema(entity_schema)}\n            },\n            \"required\": [\"info\"],\n        },\n    }\n_EXTRACTION_TEMPLATE = \"\"\"Extract and save the relevant entities mentioned \\\nin the following passage together with their properties.\nOnly extract the properties mentioned in the 'information_extraction' function.\nIf a property is not present and is not required in the function parameters, do not include it in the output.\nPassage:\n{input}\n\"\"\"  # noqa: E501\n[docs]def create_extraction_chain(\n    schema: dict,\n    llm: BaseLanguageModel,\n    prompt: Optional[BasePromptTemplate] = None,\n    tags: Optional[List[str]] = None,\n    verbose: bool = False,\n) -> Chain:\n    \"\"\"Creates a chain that extracts information from a passage.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/extraction.html"}
{"id": "4eea511ec31a-1", "text": ") -> Chain:\n    \"\"\"Creates a chain that extracts information from a passage.\n    Args:\n        schema: The schema of the entities to extract.\n        llm: The language model to use.\n        prompt: The prompt to use for extraction.\n        verbose: Whether to run in verbose mode. In verbose mode, some intermediate\n            logs will be printed to the console. Defaults to the global `verbose` value,\n            accessible via `langchain.globals.get_verbose()`.\n    Returns:\n        Chain that can be used to extract information from a passage.\n    \"\"\"\n    function = _get_extraction_function(schema)\n    extraction_prompt = prompt or ChatPromptTemplate.from_template(_EXTRACTION_TEMPLATE)\n    output_parser = JsonKeyOutputFunctionsParser(key_name=\"info\")\n    llm_kwargs = get_llm_kwargs(function)\n    chain = LLMChain(\n        llm=llm,\n        prompt=extraction_prompt,\n        llm_kwargs=llm_kwargs,\n        output_parser=output_parser,\n        tags=tags,\n        verbose=verbose,\n    )\n    return chain\n[docs]def create_extraction_chain_pydantic(\n    pydantic_schema: Any,\n    llm: BaseLanguageModel,\n    prompt: Optional[BasePromptTemplate] = None,\n    verbose: bool = False,\n) -> Chain:\n    \"\"\"Creates a chain that extracts information from a passage using pydantic schema.\n    Args:\n        pydantic_schema: The pydantic schema of the entities to extract.\n        llm: The language model to use.\n        prompt: The prompt to use for extraction.\n        verbose: Whether to run in verbose mode. In verbose mode, some intermediate\n            logs will be printed to the console. Defaults to the global `verbose` value,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/extraction.html"}
{"id": "4eea511ec31a-2", "text": "logs will be printed to the console. Defaults to the global `verbose` value,\n            accessible via `langchain.globals.get_verbose()`\n    Returns:\n        Chain that can be used to extract information from a passage.\n    \"\"\"\n    class PydanticSchema(BaseModel):\n        info: List[pydantic_schema]  # type: ignore\n    openai_schema = pydantic_schema.schema()\n    openai_schema = _resolve_schema_references(\n        openai_schema, openai_schema.get(\"definitions\", {})\n    )\n    function = _get_extraction_function(openai_schema)\n    extraction_prompt = prompt or ChatPromptTemplate.from_template(_EXTRACTION_TEMPLATE)\n    output_parser = PydanticAttrOutputFunctionsParser(\n        pydantic_schema=PydanticSchema, attr_name=\"info\"\n    )\n    llm_kwargs = get_llm_kwargs(function)\n    chain = LLMChain(\n        llm=llm,\n        prompt=extraction_prompt,\n        llm_kwargs=llm_kwargs,\n        output_parser=output_parser,\n        verbose=verbose,\n    )\n    return chain", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/extraction.html"}
{"id": "fe2132fb8960-0", "text": "Source code for langchain.chains.openai_functions.openapi\nfrom __future__ import annotations\nimport json\nimport re\nfrom collections import defaultdict\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union\nimport requests\nfrom requests import Response\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.sequential import SequentialChain\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.output_parsers.openai_functions import JsonOutputFunctionsParser\nfrom langchain.prompts import ChatPromptTemplate\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools import APIOperation\nfrom langchain.utilities.openapi import OpenAPISpec\nfrom langchain.utils.input import get_colored_text\nif TYPE_CHECKING:\n    from openapi_pydantic import Parameter\ndef _get_description(o: Any, prefer_short: bool) -> Optional[str]:\n    summary = getattr(o, \"summary\", None)\n    description = getattr(o, \"description\", None)\n    if prefer_short:\n        return summary or description\n    return description or summary\ndef _format_url(url: str, path_params: dict) -> str:\n    expected_path_param = re.findall(r\"{(.*?)}\", url)\n    new_params = {}\n    for param in expected_path_param:\n        clean_param = param.lstrip(\".;\").rstrip(\"*\")\n        val = path_params[clean_param]\n        if isinstance(val, list):\n            if param[0] == \".\":\n                sep = \".\" if param[-1] == \"*\" else \",\"\n                new_val = \".\" + sep.join(val)\n            elif param[0] == \";\":", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html"}
{"id": "fe2132fb8960-1", "text": "elif param[0] == \";\":\n                sep = f\"{clean_param}=\" if param[-1] == \"*\" else \",\"\n                new_val = f\"{clean_param}=\" + sep.join(val)\n            else:\n                new_val = \",\".join(val)\n        elif isinstance(val, dict):\n            kv_sep = \"=\" if param[-1] == \"*\" else \",\"\n            kv_strs = [kv_sep.join((k, v)) for k, v in val.items()]\n            if param[0] == \".\":\n                sep = \".\"\n                new_val = \".\"\n            elif param[0] == \";\":\n                sep = \";\"\n                new_val = \";\"\n            else:\n                sep = \",\"\n                new_val = \"\"\n            new_val += sep.join(kv_strs)\n        else:\n            if param[0] == \".\":\n                new_val = f\".{val}\"\n            elif param[0] == \";\":\n                new_val = f\";{clean_param}={val}\"\n            else:\n                new_val = val\n        new_params[param] = new_val\n    return url.format(**new_params)\ndef _openapi_params_to_json_schema(params: List[Parameter], spec: OpenAPISpec) -> dict:\n    properties = {}\n    required = []\n    for p in params:\n        if p.param_schema:\n            schema = spec.get_schema(p.param_schema)\n        else:\n            media_type_schema = list(p.content.values())[0].media_type_schema  # type: ignore  # noqa: E501\n            schema = spec.get_schema(media_type_schema)\n        if p.description and not schema.description:\n            schema.description = p.description\n        properties[p.name] = json.loads(schema.json(exclude_none=True))\n        if p.required:\n            required.append(p.name)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html"}
{"id": "fe2132fb8960-2", "text": "if p.required:\n            required.append(p.name)\n    return {\"type\": \"object\", \"properties\": properties, \"required\": required}\n[docs]def openapi_spec_to_openai_fn(\n    spec: OpenAPISpec,\n) -> Tuple[List[Dict[str, Any]], Callable]:\n    \"\"\"Convert a valid OpenAPI spec to the JSON Schema format expected for OpenAI\n        functions.\n    Args:\n        spec: OpenAPI spec to convert.\n    Returns:\n        Tuple of the OpenAI functions JSON schema and a default function for executing\n            a request based on the OpenAI function schema.\n    \"\"\"\n    if not spec.paths:\n        return [], lambda: None\n    functions = []\n    _name_to_call_map = {}\n    for path in spec.paths:\n        path_params = {\n            (p.name, p.param_in): p for p in spec.get_parameters_for_path(path)\n        }\n        for method in spec.get_methods_for_path(path):\n            request_args = {}\n            op = spec.get_operation(path, method)\n            op_params = path_params.copy()\n            for param in spec.get_parameters_for_operation(op):\n                op_params[(param.name, param.param_in)] = param\n            params_by_type = defaultdict(list)\n            for name_loc, p in op_params.items():\n                params_by_type[name_loc[1]].append(p)\n            param_loc_to_arg_name = {\n                \"query\": \"params\",\n                \"header\": \"headers\",\n                \"cookie\": \"cookies\",\n                \"path\": \"path_params\",\n            }\n            for param_loc, arg_name in param_loc_to_arg_name.items():\n                if params_by_type[param_loc]:\n                    request_args[arg_name] = _openapi_params_to_json_schema(\n                        params_by_type[param_loc], spec\n                    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html"}
{"id": "fe2132fb8960-3", "text": "params_by_type[param_loc], spec\n                    )\n            request_body = spec.get_request_body_for_operation(op)\n            # TODO: Support more MIME types.\n            if request_body and request_body.content:\n                media_types = {}\n                for media_type, media_type_object in request_body.content.items():\n                    if media_type_object.media_type_schema:\n                        schema = spec.get_schema(media_type_object.media_type_schema)\n                        media_types[media_type] = json.loads(\n                            schema.json(exclude_none=True)\n                        )\n                if len(media_types) == 1:\n                    media_type, schema_dict = list(media_types.items())[0]\n                    key = \"json\" if media_type == \"application/json\" else \"data\"\n                    request_args[key] = schema_dict\n                elif len(media_types) > 1:\n                    request_args[\"data\"] = {\"anyOf\": list(media_types.values())}\n            api_op = APIOperation.from_openapi_spec(spec, path, method)\n            fn = {\n                \"name\": api_op.operation_id,\n                \"description\": api_op.description,\n                \"parameters\": {\n                    \"type\": \"object\",\n                    \"properties\": request_args,\n                },\n            }\n            functions.append(fn)\n            _name_to_call_map[fn[\"name\"]] = {\n                \"method\": method,\n                \"url\": api_op.base_url + api_op.path,\n            }\n    def default_call_api(\n        name: str,\n        fn_args: dict,\n        headers: Optional[dict] = None,\n        params: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> Any:\n        method = _name_to_call_map[name][\"method\"]\n        url = _name_to_call_map[name][\"url\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html"}
{"id": "fe2132fb8960-4", "text": "url = _name_to_call_map[name][\"url\"]\n        path_params = fn_args.pop(\"path_params\", {})\n        url = _format_url(url, path_params)\n        if \"data\" in fn_args and isinstance(fn_args[\"data\"], dict):\n            fn_args[\"data\"] = json.dumps(fn_args[\"data\"])\n        _kwargs = {**fn_args, **kwargs}\n        if headers is not None:\n            if \"headers\" in _kwargs:\n                _kwargs[\"headers\"].update(headers)\n            else:\n                _kwargs[\"headers\"] = headers\n        if params is not None:\n            if \"params\" in _kwargs:\n                _kwargs[\"params\"].update(params)\n            else:\n                _kwargs[\"params\"] = params\n        return requests.request(method, url, **_kwargs)\n    return functions, default_call_api\n[docs]class SimpleRequestChain(Chain):\n    \"\"\"Chain for making a simple request to an API endpoint.\"\"\"\n    request_method: Callable\n    \"\"\"Method to use for making the request.\"\"\"\n    output_key: str = \"response\"\n    \"\"\"Key to use for the output of the request.\"\"\"\n    input_key: str = \"function\"\n    \"\"\"Key to use for the input of the request.\"\"\"\n    @property\n    def input_keys(self) -> List[str]:\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        return [self.output_key]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Run the logic of this chain and return the output.\"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html"}
{"id": "fe2132fb8960-5", "text": "_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        name = inputs[self.input_key].pop(\"name\")\n        args = inputs[self.input_key].pop(\"arguments\")\n        _pretty_name = get_colored_text(name, \"green\")\n        _pretty_args = get_colored_text(json.dumps(args, indent=2), \"green\")\n        _text = f\"Calling endpoint {_pretty_name} with arguments:\\n\" + _pretty_args\n        _run_manager.on_text(_text)\n        api_response: Response = self.request_method(name, args)\n        if api_response.status_code != 200:\n            response = (\n                f\"{api_response.status_code}: {api_response.reason}\"\n                + f\"\\nFor {name} \"\n                + f\"Called with args: {args.get('params','')}\"\n            )\n        else:\n            try:\n                response = api_response.json()\n            except Exception:  # noqa: E722\n                response = api_response.text\n        return {self.output_key: response}\n[docs]def get_openapi_chain(\n    spec: Union[OpenAPISpec, str],\n    llm: Optional[BaseLanguageModel] = None,\n    prompt: Optional[BasePromptTemplate] = None,\n    request_chain: Optional[Chain] = None,\n    llm_chain_kwargs: Optional[Dict] = None,\n    verbose: bool = False,\n    headers: Optional[Dict] = None,\n    params: Optional[Dict] = None,\n    **kwargs: Any,\n) -> SequentialChain:\n    \"\"\"Create a chain for querying an API from a OpenAPI spec.\n    Args:\n        spec: OpenAPISpec or url/file/text string corresponding to one.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html"}
{"id": "fe2132fb8960-6", "text": "spec: OpenAPISpec or url/file/text string corresponding to one.\n        llm: language model, should be an OpenAI function-calling model, e.g.\n            `ChatOpenAI(model=\"gpt-3.5-turbo-0613\")`.\n        prompt: Main prompt template to use.\n        request_chain: Chain for taking the functions output and executing the request.\n    \"\"\"\n    if isinstance(spec, str):\n        for conversion in (\n            OpenAPISpec.from_url,\n            OpenAPISpec.from_file,\n            OpenAPISpec.from_text,\n        ):\n            try:\n                spec = conversion(spec)  # type: ignore[arg-type]\n                break\n            except ImportError as e:\n                raise e\n            except Exception:  # noqa: E722\n                pass\n        if isinstance(spec, str):\n            raise ValueError(f\"Unable to parse spec from source {spec}\")\n    openai_fns, call_api_fn = openapi_spec_to_openai_fn(spec)\n    llm = llm or ChatOpenAI(\n        model=\"gpt-3.5-turbo-0613\",\n    )\n    prompt = prompt or ChatPromptTemplate.from_template(\n        \"Use the provided API's to respond to this user query:\\n\\n{query}\"\n    )\n    llm_chain = LLMChain(\n        llm=llm,\n        prompt=prompt,\n        llm_kwargs={\"functions\": openai_fns},\n        output_parser=JsonOutputFunctionsParser(args_only=False),\n        output_key=\"function\",\n        verbose=verbose,\n        **(llm_chain_kwargs or {}),\n    )\n    request_chain = request_chain or SimpleRequestChain(\n        request_method=lambda name, args: call_api_fn(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html"}
{"id": "fe2132fb8960-7", "text": "request_method=lambda name, args: call_api_fn(\n            name, args, headers=headers, params=params\n        ),\n        verbose=verbose,\n    )\n    return SequentialChain(\n        chains=[llm_chain, request_chain],\n        input_variables=llm_chain.input_keys,\n        output_variables=[\"response\"],\n        verbose=verbose,\n        **kwargs,\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html"}
{"id": "8dc3fe4576c7-0", "text": "Source code for langchain.chains.elasticsearch_database.base\n\"\"\"Chain for interacting with Elasticsearch Database.\"\"\"\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.elasticsearch_database.prompts import ANSWER_PROMPT, DSL_PROMPT\nfrom langchain.chains.llm import LLMChain\nfrom langchain.output_parsers.json import SimpleJsonOutputParser\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.schema import BaseLLMOutputParser, BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nif TYPE_CHECKING:\n    from elasticsearch import Elasticsearch\nINTERMEDIATE_STEPS_KEY = \"intermediate_steps\"\n[docs]class ElasticsearchDatabaseChain(Chain):\n    \"\"\"Chain for interacting with Elasticsearch Database.\n    Example:\n        .. code-block:: python\n            from langchain.chains import ElasticsearchDatabaseChain\n            from langchain.llms import OpenAI\n            from elasticsearch import Elasticsearch\n            database = Elasticsearch(\"http://localhost:9200\")\n            db_chain = ElasticsearchDatabaseChain.from_llm(OpenAI(), database)\n    \"\"\"\n    query_chain: LLMChain\n    \"\"\"Chain for creating the ES query.\"\"\"\n    answer_chain: LLMChain\n    \"\"\"Chain for answering the user question.\"\"\"\n    database: Any\n    \"\"\"Elasticsearch database to connect to of type elasticsearch.Elasticsearch.\"\"\"\n    top_k: int = 10\n    \"\"\"Number of results to return from the query\"\"\"\n    ignore_indices: Optional[List[str]] = None\n    include_indices: Optional[List[str]] = None\n    input_key: str = \"question\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/elasticsearch_database/base.html"}
{"id": "8dc3fe4576c7-1", "text": "output_key: str = \"result\"  #: :meta private:\n    sample_documents_in_index_info: int = 3\n    return_intermediate_steps: bool = False\n    \"\"\"Whether or not to return the intermediate steps along with the final answer.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator()\n    def validate_indices(cls, values: dict) -> dict:\n        if values[\"include_indices\"] and values[\"ignore_indices\"]:\n            raise ValueError(\n                \"Cannot specify both 'include_indices' and 'ignore_indices'.\"\n            )\n        return values\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the singular input key.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the singular output key.\n        :meta private:\n        \"\"\"\n        if not self.return_intermediate_steps:\n            return [self.output_key]\n        else:\n            return [self.output_key, INTERMEDIATE_STEPS_KEY]\n    def _list_indices(self) -> List[str]:\n        all_indices = [\n            index[\"index\"] for index in self.database.cat.indices(format=\"json\")\n        ]\n        if self.include_indices:\n            all_indices = [i for i in all_indices if i in self.include_indices]\n        if self.ignore_indices:\n            all_indices = [i for i in all_indices if i not in self.ignore_indices]\n        return all_indices\n    def _get_indices_infos(self, indices: List[str]) -> str:\n        mappings = self.database.indices.get_mapping(index=\",\".join(indices))\n        if self.sample_documents_in_index_info > 0:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/elasticsearch_database/base.html"}
{"id": "8dc3fe4576c7-2", "text": "if self.sample_documents_in_index_info > 0:\n            for k, v in mappings.items():\n                hits = self.database.search(\n                    index=k,\n                    query={\"match_all\": {}},\n                    size=self.sample_documents_in_index_info,\n                )[\"hits\"][\"hits\"]\n                hits = [str(hit[\"_source\"]) for hit in hits]\n                mappings[k][\"mappings\"] = str(v) + \"\\n\\n/*\\n\" + \"\\n\".join(hits) + \"\\n*/\"\n        return \"\\n\\n\".join(\n            [\n                \"Mapping for index {}:\\n{}\".format(index, mappings[index][\"mappings\"])\n                for index in mappings\n            ]\n        )\n    def _search(self, indices: List[str], query: str) -> str:\n        result = self.database.search(index=\",\".join(indices), body=query)\n        return str(result)\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        input_text = f\"{inputs[self.input_key]}\\nESQuery:\"\n        _run_manager.on_text(input_text, verbose=self.verbose)\n        indices = self._list_indices()\n        indices_info = self._get_indices_infos(indices)\n        query_inputs: dict = {\n            \"input\": input_text,\n            \"top_k\": str(self.top_k),\n            \"indices_info\": indices_info,\n            \"stop\": [\"\\nESResult:\"],\n        }\n        intermediate_steps: List = []\n        try:\n            intermediate_steps.append(query_inputs)  # input: es generation\n            es_cmd = self.query_chain.run(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/elasticsearch_database/base.html"}
{"id": "8dc3fe4576c7-3", "text": "es_cmd = self.query_chain.run(\n                callbacks=_run_manager.get_child(),\n                **query_inputs,\n            )\n            _run_manager.on_text(es_cmd, color=\"green\", verbose=self.verbose)\n            intermediate_steps.append(\n                es_cmd\n            )  # output: elasticsearch dsl generation (no checker)\n            intermediate_steps.append({\"es_cmd\": es_cmd})  # input: ES search\n            result = self._search(indices=indices, query=es_cmd)\n            intermediate_steps.append(str(result))  # output: ES search\n            _run_manager.on_text(\"\\nESResult: \", verbose=self.verbose)\n            _run_manager.on_text(result, color=\"yellow\", verbose=self.verbose)\n            _run_manager.on_text(\"\\nAnswer:\", verbose=self.verbose)\n            answer_inputs: dict = {\"data\": result, \"input\": input_text}\n            intermediate_steps.append(answer_inputs)  # input: final answer\n            final_result = self.answer_chain.run(\n                callbacks=_run_manager.get_child(),\n                **answer_inputs,\n            )\n            intermediate_steps.append(final_result)  # output: final answer\n            _run_manager.on_text(final_result, color=\"green\", verbose=self.verbose)\n            chain_result: Dict[str, Any] = {self.output_key: final_result}\n            if self.return_intermediate_steps:\n                chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps\n            return chain_result\n        except Exception as exc:\n            # Append intermediate steps to exception, to aid in logging and later\n            # improvement of few shot prompt seeds\n            exc.intermediate_steps = intermediate_steps  # type: ignore\n            raise exc\n    @property\n    def _chain_type(self) -> str:\n        return \"elasticsearch_database_chain\"\n[docs]    @classmethod\n    def from_llm(\n        cls,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/elasticsearch_database/base.html"}
{"id": "8dc3fe4576c7-4", "text": "[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        database: Elasticsearch,\n        *,\n        query_prompt: Optional[BasePromptTemplate] = None,\n        answer_prompt: Optional[BasePromptTemplate] = None,\n        query_output_parser: Optional[BaseLLMOutputParser] = None,\n        **kwargs: Any,\n    ) -> ElasticsearchDatabaseChain:\n        \"\"\"Convenience method to construct ElasticsearchDatabaseChain from an LLM.\n        Args:\n            llm: The language model to use.\n            database: The Elasticsearch db.\n            query_prompt: The prompt to use for query construction.\n            answer_prompt: The prompt to use for answering user question given data.\n            query_output_parser: The output parser to use for parsing model-generated\n                ES query. Defaults to SimpleJsonOutputParser.\n            **kwargs: Additional arguments to pass to the constructor.\n        \"\"\"\n        query_prompt = query_prompt or DSL_PROMPT\n        query_output_parser = query_output_parser or SimpleJsonOutputParser()\n        query_chain = LLMChain(\n            llm=llm, prompt=query_prompt, output_parser=query_output_parser\n        )\n        answer_prompt = answer_prompt or ANSWER_PROMPT\n        answer_chain = LLMChain(llm=llm, prompt=answer_prompt)\n        return cls(\n            query_chain=query_chain,\n            answer_chain=answer_chain,\n            database=database,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/elasticsearch_database/base.html"}
{"id": "19cd24c17291-0", "text": "Source code for langchain.chains.llm_checker.base\n\"\"\"Chain for question-answering with self-verification.\"\"\"\nfrom __future__ import annotations\nimport warnings\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.llm_checker.prompt import (\n    CHECK_ASSERTIONS_PROMPT,\n    CREATE_DRAFT_ANSWER_PROMPT,\n    LIST_ASSERTIONS_PROMPT,\n    REVISED_ANSWER_PROMPT,\n)\nfrom langchain.chains.sequential import SequentialChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.schema.language_model import BaseLanguageModel\ndef _load_question_to_checked_assertions_chain(\n    llm: BaseLanguageModel,\n    create_draft_answer_prompt: PromptTemplate,\n    list_assertions_prompt: PromptTemplate,\n    check_assertions_prompt: PromptTemplate,\n    revised_answer_prompt: PromptTemplate,\n) -> SequentialChain:\n    create_draft_answer_chain = LLMChain(\n        llm=llm,\n        prompt=create_draft_answer_prompt,\n        output_key=\"statement\",\n    )\n    list_assertions_chain = LLMChain(\n        llm=llm,\n        prompt=list_assertions_prompt,\n        output_key=\"assertions\",\n    )\n    check_assertions_chain = LLMChain(\n        llm=llm,\n        prompt=check_assertions_prompt,\n        output_key=\"checked_assertions\",\n    )\n    revised_answer_chain = LLMChain(\n        llm=llm,\n        prompt=revised_answer_prompt,\n        output_key=\"revised_statement\",\n    )\n    chains = [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html"}
{"id": "19cd24c17291-1", "text": "output_key=\"revised_statement\",\n    )\n    chains = [\n        create_draft_answer_chain,\n        list_assertions_chain,\n        check_assertions_chain,\n        revised_answer_chain,\n    ]\n    question_to_checked_assertions_chain = SequentialChain(\n        chains=chains,\n        input_variables=[\"question\"],\n        output_variables=[\"revised_statement\"],\n        verbose=True,\n    )\n    return question_to_checked_assertions_chain\n[docs]class LLMCheckerChain(Chain):\n    \"\"\"Chain for question-answering with self-verification.\n    Example:\n        .. code-block:: python\n            from langchain.llms import OpenAI\n            from langchain.chains import LLMCheckerChain\n            llm = OpenAI(temperature=0.7)\n            checker_chain = LLMCheckerChain.from_llm(llm)\n    \"\"\"\n    question_to_checked_assertions_chain: SequentialChain\n    llm: Optional[BaseLanguageModel] = None\n    \"\"\"[Deprecated] LLM wrapper to use.\"\"\"\n    create_draft_answer_prompt: PromptTemplate = CREATE_DRAFT_ANSWER_PROMPT\n    \"\"\"[Deprecated]\"\"\"\n    list_assertions_prompt: PromptTemplate = LIST_ASSERTIONS_PROMPT\n    \"\"\"[Deprecated]\"\"\"\n    check_assertions_prompt: PromptTemplate = CHECK_ASSERTIONS_PROMPT\n    \"\"\"[Deprecated]\"\"\"\n    revised_answer_prompt: PromptTemplate = REVISED_ANSWER_PROMPT\n    \"\"\"[Deprecated] Prompt to use when questioning the documents.\"\"\"\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator(pre=True)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html"}
{"id": "19cd24c17291-2", "text": "arbitrary_types_allowed = True\n    @root_validator(pre=True)\n    def raise_deprecation(cls, values: Dict) -> Dict:\n        if \"llm\" in values:\n            warnings.warn(\n                \"Directly instantiating an LLMCheckerChain with an llm is deprecated. \"\n                \"Please instantiate with question_to_checked_assertions_chain \"\n                \"or using the from_llm class method.\"\n            )\n            if (\n                \"question_to_checked_assertions_chain\" not in values\n                and values[\"llm\"] is not None\n            ):\n                question_to_checked_assertions_chain = (\n                    _load_question_to_checked_assertions_chain(\n                        values[\"llm\"],\n                        values.get(\n                            \"create_draft_answer_prompt\", CREATE_DRAFT_ANSWER_PROMPT\n                        ),\n                        values.get(\"list_assertions_prompt\", LIST_ASSERTIONS_PROMPT),\n                        values.get(\"check_assertions_prompt\", CHECK_ASSERTIONS_PROMPT),\n                        values.get(\"revised_answer_prompt\", REVISED_ANSWER_PROMPT),\n                    )\n                )\n                values[\n                    \"question_to_checked_assertions_chain\"\n                ] = question_to_checked_assertions_chain\n        return values\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the singular input key.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the singular output key.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html"}
{"id": "19cd24c17291-3", "text": ") -> Dict[str, str]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        question = inputs[self.input_key]\n        output = self.question_to_checked_assertions_chain(\n            {\"question\": question}, callbacks=_run_manager.get_child()\n        )\n        return {self.output_key: output[\"revised_statement\"]}\n    @property\n    def _chain_type(self) -> str:\n        return \"llm_checker_chain\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        create_draft_answer_prompt: PromptTemplate = CREATE_DRAFT_ANSWER_PROMPT,\n        list_assertions_prompt: PromptTemplate = LIST_ASSERTIONS_PROMPT,\n        check_assertions_prompt: PromptTemplate = CHECK_ASSERTIONS_PROMPT,\n        revised_answer_prompt: PromptTemplate = REVISED_ANSWER_PROMPT,\n        **kwargs: Any,\n    ) -> LLMCheckerChain:\n        question_to_checked_assertions_chain = (\n            _load_question_to_checked_assertions_chain(\n                llm,\n                create_draft_answer_prompt,\n                list_assertions_prompt,\n                check_assertions_prompt,\n                revised_answer_prompt,\n            )\n        )\n        return cls(\n            question_to_checked_assertions_chain=question_to_checked_assertions_chain,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html"}
{"id": "3cc2db946746-0", "text": "Source code for langchain.chains.natbot.crawler\n# flake8: noqa\nimport time\nfrom sys import platform\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Set,\n    Tuple,\n    TypedDict,\n    Union,\n)\nif TYPE_CHECKING:\n    from playwright.sync_api import Browser, CDPSession, Page, sync_playwright\nblack_listed_elements: Set[str] = {\n    \"html\",\n    \"head\",\n    \"title\",\n    \"meta\",\n    \"iframe\",\n    \"body\",\n    \"script\",\n    \"style\",\n    \"path\",\n    \"svg\",\n    \"br\",\n    \"::marker\",\n}\n[docs]class ElementInViewPort(TypedDict):\n    \"\"\"A typed dictionary containing information about elements in the viewport.\"\"\"\n    node_index: str\n    backend_node_id: int\n    node_name: Optional[str]\n    node_value: Optional[str]\n    node_meta: List[str]\n    is_clickable: bool\n    origin_x: int\n    origin_y: int\n    center_x: int\n    center_y: int\n[docs]class Crawler:\n    \"\"\"A crawler for web pages.\n    **Security Note**: This is an implementation of a crawler that uses a browser via\n        Playwright.\n        This crawler can be used to load arbitrary webpages INCLUDING content\n        from the local file system.\n        Control access to who can submit crawling requests and what network access\n        the crawler has.\n        Make sure to scope permissions to the minimal permissions necessary for\n        the application.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n[docs]    def __init__(self) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html"}
{"id": "3cc2db946746-1", "text": "\"\"\"\n[docs]    def __init__(self) -> None:\n        try:\n            from playwright.sync_api import sync_playwright\n        except ImportError:\n            raise ImportError(\n                \"Could not import playwright python package. \"\n                \"Please install it with `pip install playwright`.\"\n            )\n        self.browser: Browser = (\n            sync_playwright().start().chromium.launch(headless=False)\n        )\n        self.page: Page = self.browser.new_page()\n        self.page.set_viewport_size({\"width\": 1280, \"height\": 1080})\n        self.page_element_buffer: Dict[int, ElementInViewPort]\n        self.client: CDPSession\n[docs]    def go_to_page(self, url: str) -> None:\n        self.page.goto(url=url if \"://\" in url else \"http://\" + url)\n        self.client = self.page.context.new_cdp_session(self.page)\n        self.page_element_buffer = {}\n[docs]    def scroll(self, direction: str) -> None:\n        if direction == \"up\":\n            self.page.evaluate(\n                \"(document.scrollingElement || document.body).scrollTop = (document.scrollingElement || document.body).scrollTop - window.innerHeight;\"\n            )\n        elif direction == \"down\":\n            self.page.evaluate(\n                \"(document.scrollingElement || document.body).scrollTop = (document.scrollingElement || document.body).scrollTop + window.innerHeight;\"\n            )\n[docs]    def click(self, id: Union[str, int]) -> None:\n        # Inject javascript into the page which removes the target= attribute from all links\n        js = \"\"\"\n\t\tlinks = document.getElementsByTagName(\"a\");\n\t\tfor (var i = 0; i < links.length; i++) {\n\t\t\tlinks[i].removeAttribute(\"target\");\n\t\t}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html"}
{"id": "3cc2db946746-2", "text": "links[i].removeAttribute(\"target\");\n\t\t}\n\t\t\"\"\"\n        self.page.evaluate(js)\n        element = self.page_element_buffer.get(int(id))\n        if element:\n            x: float = element[\"center_x\"]\n            y: float = element[\"center_y\"]\n            self.page.mouse.click(x, y)\n        else:\n            print(\"Could not find element\")\n[docs]    def type(self, id: Union[str, int], text: str) -> None:\n        self.click(id)\n        self.page.keyboard.type(text)\n[docs]    def enter(self) -> None:\n        self.page.keyboard.press(\"Enter\")\n[docs]    def crawl(self) -> List[str]:\n        page = self.page\n        page_element_buffer = self.page_element_buffer\n        start = time.time()\n        page_state_as_text = []\n        device_pixel_ratio: float = page.evaluate(\"window.devicePixelRatio\")\n        if platform == \"darwin\" and device_pixel_ratio == 1:  # lies\n            device_pixel_ratio = 2\n        win_upper_bound: float = page.evaluate(\"window.pageYOffset\")\n        win_left_bound: float = page.evaluate(\"window.pageXOffset\")\n        win_width: float = page.evaluate(\"window.screen.width\")\n        win_height: float = page.evaluate(\"window.screen.height\")\n        win_right_bound: float = win_left_bound + win_width\n        win_lower_bound: float = win_upper_bound + win_height\n        # \t\tpercentage_progress_start = (win_upper_bound / document_scroll_height) * 100\n        # \t\tpercentage_progress_end = (\n        # \t\t\t(win_height + win_upper_bound) / document_scroll_height\n        # \t\t) * 100\n        percentage_progress_start = 1\n        percentage_progress_end = 2\n        page_state_as_text.append(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html"}
{"id": "3cc2db946746-3", "text": "percentage_progress_end = 2\n        page_state_as_text.append(\n            {\n                \"x\": 0,\n                \"y\": 0,\n                \"text\": \"[scrollbar {:0.2f}-{:0.2f}%]\".format(\n                    round(percentage_progress_start, 2), round(percentage_progress_end)\n                ),\n            }\n        )\n        tree = self.client.send(\n            \"DOMSnapshot.captureSnapshot\",\n            {\"computedStyles\": [], \"includeDOMRects\": True, \"includePaintOrder\": True},\n        )\n        strings: Dict[int, str] = tree[\"strings\"]\n        document: Dict[str, Any] = tree[\"documents\"][0]\n        nodes: Dict[str, Any] = document[\"nodes\"]\n        backend_node_id: Dict[int, int] = nodes[\"backendNodeId\"]\n        attributes: Dict[int, Dict[int, Any]] = nodes[\"attributes\"]\n        node_value: Dict[int, int] = nodes[\"nodeValue\"]\n        parent: Dict[int, int] = nodes[\"parentIndex\"]\n        node_names: Dict[int, int] = nodes[\"nodeName\"]\n        is_clickable: Set[int] = set(nodes[\"isClickable\"][\"index\"])\n        input_value: Dict[str, Any] = nodes[\"inputValue\"]\n        input_value_index: List[int] = input_value[\"index\"]\n        input_value_values: List[int] = input_value[\"value\"]\n        layout: Dict[str, Any] = document[\"layout\"]\n        layout_node_index: List[int] = layout[\"nodeIndex\"]\n        bounds: Dict[int, List[float]] = layout[\"bounds\"]\n        cursor: int = 0\n        child_nodes: Dict[str, List[Dict[str, Any]]] = {}\n        elements_in_view_port: List[ElementInViewPort] = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html"}
{"id": "3cc2db946746-4", "text": "elements_in_view_port: List[ElementInViewPort] = []\n        anchor_ancestry: Dict[str, Tuple[bool, Optional[int]]] = {\"-1\": (False, None)}\n        button_ancestry: Dict[str, Tuple[bool, Optional[int]]] = {\"-1\": (False, None)}\n        def convert_name(\n            node_name: Optional[str], has_click_handler: Optional[bool]\n        ) -> str:\n            if node_name == \"a\":\n                return \"link\"\n            if node_name == \"input\":\n                return \"input\"\n            if node_name == \"img\":\n                return \"img\"\n            if (\n                node_name == \"button\" or has_click_handler\n            ):  # found pages that needed this quirk\n                return \"button\"\n            else:\n                return \"text\"\n        def find_attributes(\n            attributes: Dict[int, Any], keys: List[str]\n        ) -> Dict[str, str]:\n            values = {}\n            for [key_index, value_index] in zip(*(iter(attributes),) * 2):\n                if value_index < 0:\n                    continue\n                key = strings[key_index]\n                value = strings[value_index]\n                if key in keys:\n                    values[key] = value\n                    keys.remove(key)\n                    if not keys:\n                        return values\n            return values\n        def add_to_hash_tree(\n            hash_tree: Dict[str, Tuple[bool, Optional[int]]],\n            tag: str,\n            node_id: int,\n            node_name: Optional[str],\n            parent_id: int,\n        ) -> Tuple[bool, Optional[int]]:\n            parent_id_str = str(parent_id)\n            if not parent_id_str in hash_tree:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html"}
{"id": "3cc2db946746-5", "text": "if not parent_id_str in hash_tree:\n                parent_name = strings[node_names[parent_id]].lower()\n                grand_parent_id = parent[parent_id]\n                add_to_hash_tree(\n                    hash_tree, tag, parent_id, parent_name, grand_parent_id\n                )\n            is_parent_desc_anchor, anchor_id = hash_tree[parent_id_str]\n            # even if the anchor is nested in another anchor, we set the \"root\" for all descendants to be ::Self\n            if node_name == tag:\n                value: Tuple[bool, Optional[int]] = (True, node_id)\n            elif (\n                is_parent_desc_anchor\n            ):  # reuse the parent's anchor_id (which could be much higher in the tree)\n                value = (True, anchor_id)\n            else:\n                value = (\n                    False,\n                    None,\n                )  # not a descendant of an anchor, most likely it will become text, an interactive element or discarded\n            hash_tree[str(node_id)] = value\n            return value\n        for index, node_name_index in enumerate(node_names):\n            node_parent = parent[index]\n            node_name: Optional[str] = strings[node_name_index].lower()\n            is_ancestor_of_anchor, anchor_id = add_to_hash_tree(\n                anchor_ancestry, \"a\", index, node_name, node_parent\n            )\n            is_ancestor_of_button, button_id = add_to_hash_tree(\n                button_ancestry, \"button\", index, node_name, node_parent\n            )\n            try:\n                cursor = layout_node_index.index(\n                    index\n                )  # todo replace this with proper cursoring, ignoring the fact this is O(n^2) for the moment\n            except:\n                continue\n            if node_name in black_listed_elements:\n                continue", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html"}
{"id": "3cc2db946746-6", "text": "continue\n            if node_name in black_listed_elements:\n                continue\n            [x, y, width, height] = bounds[cursor]\n            x /= device_pixel_ratio\n            y /= device_pixel_ratio\n            width /= device_pixel_ratio\n            height /= device_pixel_ratio\n            elem_left_bound = x\n            elem_top_bound = y\n            elem_right_bound = x + width\n            elem_lower_bound = y + height\n            partially_is_in_viewport = (\n                elem_left_bound < win_right_bound\n                and elem_right_bound >= win_left_bound\n                and elem_top_bound < win_lower_bound\n                and elem_lower_bound >= win_upper_bound\n            )\n            if not partially_is_in_viewport:\n                continue\n            meta_data: List[str] = []\n            # inefficient to grab the same set of keys for kinds of objects, but it's fine for now\n            element_attributes = find_attributes(\n                attributes[index], [\"type\", \"placeholder\", \"aria-label\", \"title\", \"alt\"]\n            )\n            ancestor_exception = is_ancestor_of_anchor or is_ancestor_of_button\n            ancestor_node_key = (\n                None\n                if not ancestor_exception\n                else str(anchor_id)\n                if is_ancestor_of_anchor\n                else str(button_id)\n            )\n            ancestor_node = (\n                None\n                if not ancestor_exception\n                else child_nodes.setdefault(str(ancestor_node_key), [])\n            )\n            if node_name == \"#text\" and ancestor_exception and ancestor_node:\n                text = strings[node_value[index]]\n                if text == \"|\" or text == \"\u2022\":\n                    continue\n                ancestor_node.append({\"type\": \"type\", \"value\": text})\n            else:\n                if (\n                    node_name == \"input\" and element_attributes.get(\"type\") == \"submit\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html"}
{"id": "3cc2db946746-7", "text": "node_name == \"input\" and element_attributes.get(\"type\") == \"submit\"\n                ) or node_name == \"button\":\n                    node_name = \"button\"\n                    element_attributes.pop(\n                        \"type\", None\n                    )  # prevent [button ... (button)..]\n                for key in element_attributes:\n                    if ancestor_exception and ancestor_node:\n                        ancestor_node.append(\n                            {\n                                \"type\": \"attribute\",\n                                \"key\": key,\n                                \"value\": element_attributes[key],\n                            }\n                        )\n                    else:\n                        meta_data.append(element_attributes[key])\n            element_node_value = None\n            if node_value[index] >= 0:\n                element_node_value = strings[node_value[index]]\n                if (\n                    element_node_value == \"|\"\n                ):  # commonly used as a separator, does not add much context - lets save ourselves some token space\n                    continue\n            elif (\n                node_name == \"input\"\n                and index in input_value_index\n                and element_node_value is None\n            ):\n                node_input_text_index = input_value_index.index(index)\n                text_index = input_value_values[node_input_text_index]\n                if node_input_text_index >= 0 and text_index >= 0:\n                    element_node_value = strings[text_index]\n            # remove redundant elements\n            if ancestor_exception and (node_name != \"a\" and node_name != \"button\"):\n                continue\n            elements_in_view_port.append(\n                {\n                    \"node_index\": str(index),\n                    \"backend_node_id\": backend_node_id[index],\n                    \"node_name\": node_name,\n                    \"node_value\": element_node_value,\n                    \"node_meta\": meta_data,\n                    \"is_clickable\": index in is_clickable,\n                    \"origin_x\": int(x),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html"}
{"id": "3cc2db946746-8", "text": "\"origin_x\": int(x),\n                    \"origin_y\": int(y),\n                    \"center_x\": int(x + (width / 2)),\n                    \"center_y\": int(y + (height / 2)),\n                }\n            )\n        # lets filter further to remove anything that does not hold any text nor has click handlers + merge text from leaf#text nodes with the parent\n        elements_of_interest = []\n        id_counter = 0\n        for element in elements_in_view_port:\n            node_index = element.get(\"node_index\")\n            node_name = element.get(\"node_name\")\n            element_node_value = element.get(\"node_value\")\n            node_is_clickable = element.get(\"is_clickable\")\n            node_meta_data: Optional[List[str]] = element.get(\"node_meta\")\n            inner_text = f\"{element_node_value} \" if element_node_value else \"\"\n            meta = \"\"\n            if node_index in child_nodes:\n                for child in child_nodes[node_index]:\n                    entry_type = child.get(\"type\")\n                    entry_value = child.get(\"value\")\n                    if entry_type == \"attribute\" and node_meta_data:\n                        entry_key = child.get(\"key\")\n                        node_meta_data.append(f'{entry_key}=\"{entry_value}\"')\n                    else:\n                        inner_text += f\"{entry_value} \"\n            if node_meta_data:\n                meta_string = \" \".join(node_meta_data)\n                meta = f\" {meta_string}\"\n            if inner_text != \"\":\n                inner_text = f\"{inner_text.strip()}\"\n            converted_node_name = convert_name(node_name, node_is_clickable)\n            # not very elegant, more like a placeholder\n            if (\n                (converted_node_name != \"button\" or meta == \"\")\n                and converted_node_name != \"link\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html"}
{"id": "3cc2db946746-9", "text": "and converted_node_name != \"link\"\n                and converted_node_name != \"input\"\n                and converted_node_name != \"img\"\n                and converted_node_name != \"textarea\"\n            ) and inner_text.strip() == \"\":\n                continue\n            page_element_buffer[id_counter] = element\n            if inner_text != \"\":\n                elements_of_interest.append(\n                    f\"\"\"<{converted_node_name} id={id_counter}{meta}>{inner_text}</{converted_node_name}>\"\"\"\n                )\n            else:\n                elements_of_interest.append(\n                    f\"\"\"<{converted_node_name} id={id_counter}{meta}/>\"\"\"\n                )\n            id_counter += 1\n        print(\"Parsing time: {:0.2f} seconds\".format(time.time() - start))\n        return elements_of_interest", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html"}
{"id": "355519ebce64-0", "text": "Source code for langchain.chains.natbot.base\n\"\"\"Implement an LLM driven browser.\"\"\"\nfrom __future__ import annotations\nimport warnings\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.natbot.prompt import PROMPT\nfrom langchain.llms.openai import OpenAI\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class NatBotChain(Chain):\n    \"\"\"Implement an LLM driven browser.\n    **Security Note**: This toolkit provides code to control a web-browser.\n        The web-browser can be used to navigate to:\n        - Any URL (including any internal network URLs)\n        - And local files\n        Exercise care if exposing this chain to end-users. Control who is able to\n        access and use this chain, and isolate the network access of the server\n        that hosts this chain.\n        See https://python.langchain.com/docs/security for more information.\n    Example:\n        .. code-block:: python\n            from langchain.chains import NatBotChain\n            natbot = NatBotChain.from_default(\"Buy me a new hat.\")\n    \"\"\"\n    llm_chain: LLMChain\n    objective: str\n    \"\"\"Objective that NatBot is tasked with completing.\"\"\"\n    llm: Optional[BaseLanguageModel] = None\n    \"\"\"[Deprecated] LLM wrapper to use.\"\"\"\n    input_url_key: str = \"url\"  #: :meta private:\n    input_browser_content_key: str = \"browser_content\"  #: :meta private:\n    previous_command: str = \"\"  #: :meta private:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html"}
{"id": "355519ebce64-1", "text": "previous_command: str = \"\"  #: :meta private:\n    output_key: str = \"command\"  #: :meta private:\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator(pre=True)\n    def raise_deprecation(cls, values: Dict) -> Dict:\n        if \"llm\" in values:\n            warnings.warn(\n                \"Directly instantiating an NatBotChain with an llm is deprecated. \"\n                \"Please instantiate with llm_chain argument or using the from_llm \"\n                \"class method.\"\n            )\n            if \"llm_chain\" not in values and values[\"llm\"] is not None:\n                values[\"llm_chain\"] = LLMChain(llm=values[\"llm\"], prompt=PROMPT)\n        return values\n[docs]    @classmethod\n    def from_default(cls, objective: str, **kwargs: Any) -> NatBotChain:\n        \"\"\"Load with default LLMChain.\"\"\"\n        llm = OpenAI(temperature=0.5, best_of=10, n=3, max_tokens=50)\n        return cls.from_llm(llm, objective, **kwargs)\n[docs]    @classmethod\n    def from_llm(\n        cls, llm: BaseLanguageModel, objective: str, **kwargs: Any\n    ) -> NatBotChain:\n        \"\"\"Load from LLM.\"\"\"\n        llm_chain = LLMChain(llm=llm, prompt=PROMPT)\n        return cls(llm_chain=llm_chain, objective=objective, **kwargs)\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect url and browser content.\n        :meta private:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html"}
{"id": "355519ebce64-2", "text": "\"\"\"Expect url and browser content.\n        :meta private:\n        \"\"\"\n        return [self.input_url_key, self.input_browser_content_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return command.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n    def _call(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        url = inputs[self.input_url_key]\n        browser_content = inputs[self.input_browser_content_key]\n        llm_cmd = self.llm_chain.predict(\n            objective=self.objective,\n            url=url[:100],\n            previous_command=self.previous_command,\n            browser_content=browser_content[:4500],\n            callbacks=_run_manager.get_child(),\n        )\n        llm_cmd = llm_cmd.strip()\n        self.previous_command = llm_cmd\n        return {self.output_key: llm_cmd}\n[docs]    def execute(self, url: str, browser_content: str) -> str:\n        \"\"\"Figure out next browser command to run.\n        Args:\n            url: URL of the site currently on.\n            browser_content: Content of the page as currently displayed by the browser.\n        Returns:\n            Next browser command to run.\n        Example:\n            .. code-block:: python\n                browser_content = \"....\"\n                llm_command = natbot.run(\"www.google.com\", browser_content)\n        \"\"\"\n        _inputs = {\n            self.input_url_key: url,\n            self.input_browser_content_key: browser_content,\n        }\n        return self(_inputs)[self.output_key]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html"}
{"id": "355519ebce64-3", "text": "}\n        return self(_inputs)[self.output_key]\n    @property\n    def _chain_type(self) -> str:\n        return \"nat_bot_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html"}
{"id": "e5e8ce940b6e-0", "text": "Source code for langchain.chains.openai_tools.extraction\nfrom typing import List, Type, Union\nfrom langchain.output_parsers import PydanticToolsParser\nfrom langchain.prompts import ChatPromptTemplate\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.runnable import Runnable\nfrom langchain.utils.openai_functions import convert_pydantic_to_openai_function\n_EXTRACTION_TEMPLATE = \"\"\"Extract and save the relevant entities mentioned \\\nin the following passage together with their properties.\nIf a property is not present and is not required in the function parameters, do not include it in the output.\"\"\"  # noqa: E501\n[docs]def create_extraction_chain_pydantic(\n    pydantic_schemas: Union[List[Type[BaseModel]], Type[BaseModel]],\n    llm: BaseLanguageModel,\n    system_message: str = _EXTRACTION_TEMPLATE,\n) -> Runnable:\n    if not isinstance(pydantic_schemas, list):\n        pydantic_schemas = [pydantic_schemas]\n    prompt = ChatPromptTemplate.from_messages(\n        [(\"system\", system_message), (\"user\", \"{input}\")]\n    )\n    functions = [convert_pydantic_to_openai_function(p) for p in pydantic_schemas]\n    tools = [{\"type\": \"function\", \"function\": d} for d in functions]\n    model = llm.bind(tools=tools)\n    chain = prompt | model | PydanticToolsParser(tools=pydantic_schemas)\n    return chain", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_tools/extraction.html"}
{"id": "312ed69e5445-0", "text": "Source code for langchain.chains.hyde.base\n\"\"\"Hypothetical Document Embeddings.\nhttps://arxiv.org/abs/2212.10496\n\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional\nimport numpy as np\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.hyde.prompts import PROMPT_MAP\nfrom langchain.chains.llm import LLMChain\nfrom langchain.pydantic_v1 import Extra\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class HypotheticalDocumentEmbedder(Chain, Embeddings):\n    \"\"\"Generate hypothetical document for query, and then embed that.\n    Based on https://arxiv.org/abs/2212.10496\n    \"\"\"\n    base_embeddings: Embeddings\n    llm_chain: LLMChain\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Input keys for Hyde's LLM chain.\"\"\"\n        return self.llm_chain.input_keys\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Output keys for Hyde's LLM chain.\"\"\"\n        return self.llm_chain.output_keys\n[docs]    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Call the base embeddings.\"\"\"\n        return self.base_embeddings.embed_documents(texts)\n[docs]    def combine_embeddings(self, embeddings: List[List[float]]) -> List[float]:\n        \"\"\"Combine embeddings into final embeddings.\"\"\"\n        return list(np.array(embeddings).mean(axis=0))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html"}
{"id": "312ed69e5445-1", "text": "return list(np.array(embeddings).mean(axis=0))\n[docs]    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Generate a hypothetical document and embedded it.\"\"\"\n        var_name = self.llm_chain.input_keys[0]\n        result = self.llm_chain.generate([{var_name: text}])\n        documents = [generation.text for generation in result.generations[0]]\n        embeddings = self.embed_documents(documents)\n        return self.combine_embeddings(embeddings)\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        \"\"\"Call the internal llm chain.\"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        return self.llm_chain(inputs, callbacks=_run_manager.get_child())\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        base_embeddings: Embeddings,\n        prompt_key: str,\n        **kwargs: Any,\n    ) -> HypotheticalDocumentEmbedder:\n        \"\"\"Load and use LLMChain for a specific prompt key.\"\"\"\n        prompt = PROMPT_MAP[prompt_key]\n        llm_chain = LLMChain(llm=llm, prompt=prompt)\n        return cls(base_embeddings=base_embeddings, llm_chain=llm_chain, **kwargs)\n    @property\n    def _chain_type(self) -> str:\n        return \"hyde_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html"}
{"id": "c8a1fffc9b01-0", "text": "Source code for langchain.chains.conversation.base\n\"\"\"Chain that carries on a conversation and calls an LLM.\"\"\"\nfrom typing import Dict, List\nfrom langchain.chains.conversation.prompt import PROMPT\nfrom langchain.chains.llm import LLMChain\nfrom langchain.memory.buffer import ConversationBufferMemory\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.schema import BaseMemory, BasePromptTemplate\n[docs]class ConversationChain(LLMChain):\n    \"\"\"Chain to have a conversation and load context from memory.\n    Example:\n        .. code-block:: python\n            from langchain.chains import ConversationChain\n            from langchain.llms import OpenAI\n            conversation = ConversationChain(llm=OpenAI())\n    \"\"\"\n    memory: BaseMemory = Field(default_factory=ConversationBufferMemory)\n    \"\"\"Default memory store.\"\"\"\n    prompt: BasePromptTemplate = PROMPT\n    \"\"\"Default conversation prompt to use.\"\"\"\n    input_key: str = \"input\"  #: :meta private:\n    output_key: str = \"response\"  #: :meta private:\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Use this since so some prompt vars come from history.\"\"\"\n        return [self.input_key]\n    @root_validator()\n    def validate_prompt_input_variables(cls, values: Dict) -> Dict:\n        \"\"\"Validate that prompt input variables are consistent.\"\"\"\n        memory_keys = values[\"memory\"].memory_variables\n        input_key = values[\"input_key\"]\n        if input_key in memory_keys:\n            raise ValueError(\n                f\"The input key {input_key} was also found in the memory keys \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversation/base.html"}
{"id": "c8a1fffc9b01-1", "text": "f\"The input key {input_key} was also found in the memory keys \"\n                f\"({memory_keys}) - please provide keys that don't overlap.\"\n            )\n        prompt_variables = values[\"prompt\"].input_variables\n        expected_keys = memory_keys + [input_key]\n        if set(expected_keys) != set(prompt_variables):\n            raise ValueError(\n                \"Got unexpected prompt input variables. The prompt expects \"\n                f\"{prompt_variables}, but got {memory_keys} as inputs from \"\n                f\"memory, and {input_key} as the normal input key.\"\n            )\n        return values", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversation/base.html"}
{"id": "cd870b8b73a8-0", "text": "Source code for langchain.chains.combine_documents.map_rerank\n\"\"\"Combining documents by mapping a chain over them first, then reranking results.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union, cast\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains.combine_documents.base import BaseCombineDocumentsChain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.docstore.document import Document\nfrom langchain.output_parsers.regex import RegexParser\nfrom langchain.pydantic_v1 import BaseModel, Extra, create_model, root_validator\nfrom langchain.schema.runnable.config import RunnableConfig\n[docs]class MapRerankDocumentsChain(BaseCombineDocumentsChain):\n    \"\"\"Combining documents by mapping a chain over them, then reranking results.\n    This algorithm calls an LLMChain on each input document. The LLMChain is expected\n    to have an OutputParser that parses the result into both an answer (`answer_key`)\n    and a score (`rank_key`). The answer with the highest score is then returned.\n    Example:\n        .. code-block:: python\n            from langchain.chains import StuffDocumentsChain, LLMChain\n            from langchain.prompts import PromptTemplate\n            from langchain.llms import OpenAI\n            from langchain.output_parsers.regex import RegexParser\n            document_variable_name = \"context\"\n            llm = OpenAI()\n            # The prompt here should take as an input variable the\n            # `document_variable_name`\n            # The actual prompt will need to be a lot more complex, this is just\n            # an example.\n            prompt_template = (\n                \"Use the following context to tell me the chemical formula \"\n                \"for water. Output both your answer and a score of how confident \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html"}
{"id": "cd870b8b73a8-1", "text": "\"for water. Output both your answer and a score of how confident \"\n                \"you are. Context: {content}\"\n            )\n            output_parser = RegexParser(\n                regex=r\"(.*?)\\nScore: (.*)\",\n                output_keys=[\"answer\", \"score\"],\n            )\n            prompt = PromptTemplate(\n                template=prompt_template,\n                input_variables=[\"context\"],\n                output_parser=output_parser,\n            )\n            llm_chain = LLMChain(llm=llm, prompt=prompt)\n            chain = MapRerankDocumentsChain(\n                llm_chain=llm_chain,\n                document_variable_name=document_variable_name,\n                rank_key=\"score\",\n                answer_key=\"answer\",\n            )\n    \"\"\"\n    llm_chain: LLMChain\n    \"\"\"Chain to apply to each document individually.\"\"\"\n    document_variable_name: str\n    \"\"\"The variable name in the llm_chain to put the documents in.\n    If only one variable in the llm_chain, this need not be provided.\"\"\"\n    rank_key: str\n    \"\"\"Key in output of llm_chain to rank on.\"\"\"\n    answer_key: str\n    \"\"\"Key in output of llm_chain to return as answer.\"\"\"\n    metadata_keys: Optional[List[str]] = None\n    \"\"\"Additional metadata from the chosen document to return.\"\"\"\n    return_intermediate_steps: bool = False\n    \"\"\"Return intermediate steps.\n    Intermediate steps include the results of calling llm_chain on each document.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n[docs]    def get_output_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        schema: Dict[str, Any] = {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html"}
{"id": "cd870b8b73a8-2", "text": ") -> Type[BaseModel]:\n        schema: Dict[str, Any] = {\n            self.output_key: (str, None),\n        }\n        if self.return_intermediate_steps:\n            schema[\"intermediate_steps\"] = (List[str], None)\n        if self.metadata_keys:\n            schema.update({key: (Any, None) for key in self.metadata_keys})\n        return create_model(\"MapRerankOutput\", **schema)\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        _output_keys = super().output_keys\n        if self.return_intermediate_steps:\n            _output_keys = _output_keys + [\"intermediate_steps\"]\n        if self.metadata_keys is not None:\n            _output_keys += self.metadata_keys\n        return _output_keys\n    @root_validator()\n    def validate_llm_output(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the combine chain outputs a dictionary.\"\"\"\n        output_parser = values[\"llm_chain\"].prompt.output_parser\n        if not isinstance(output_parser, RegexParser):\n            raise ValueError(\n                \"Output parser of llm_chain should be a RegexParser,\"\n                f\" got {output_parser}\"\n            )\n        output_keys = output_parser.output_keys\n        if values[\"rank_key\"] not in output_keys:\n            raise ValueError(\n                f\"Got {values['rank_key']} as key to rank on, but did not find \"\n                f\"it in the llm_chain output keys ({output_keys})\"\n            )\n        if values[\"answer_key\"] not in output_keys:\n            raise ValueError(\n                f\"Got {values['answer_key']} as key to return, but did not find \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html"}
{"id": "cd870b8b73a8-3", "text": "f\"it in the llm_chain output keys ({output_keys})\"\n            )\n        return values\n    @root_validator(pre=True)\n    def get_default_document_variable_name(cls, values: Dict) -> Dict:\n        \"\"\"Get default document variable name, if not provided.\"\"\"\n        if \"document_variable_name\" not in values:\n            llm_chain_variables = values[\"llm_chain\"].prompt.input_variables\n            if len(llm_chain_variables) == 1:\n                values[\"document_variable_name\"] = llm_chain_variables[0]\n            else:\n                raise ValueError(\n                    \"document_variable_name must be provided if there are \"\n                    \"multiple llm_chain input_variables\"\n                )\n        else:\n            llm_chain_variables = values[\"llm_chain\"].prompt.input_variables\n            if values[\"document_variable_name\"] not in llm_chain_variables:\n                raise ValueError(\n                    f\"document_variable_name {values['document_variable_name']} was \"\n                    f\"not found in llm_chain input_variables: {llm_chain_variables}\"\n                )\n        return values\n[docs]    def combine_docs(\n        self, docs: List[Document], callbacks: Callbacks = None, **kwargs: Any\n    ) -> Tuple[str, dict]:\n        \"\"\"Combine documents in a map rerank manner.\n        Combine by mapping first chain over all documents, then reranking the results.\n        Args:\n            docs: List of documents to combine\n            callbacks: Callbacks to be passed through\n            **kwargs: additional parameters to be passed to LLM calls (like other\n                input variables besides the documents)\n        Returns:\n            The first element returned is the single string output. The second\n            element returned is a dictionary of other keys to return.\n        \"\"\"\n        results = self.llm_chain.apply_and_parse(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html"}
{"id": "cd870b8b73a8-4", "text": "\"\"\"\n        results = self.llm_chain.apply_and_parse(\n            # FYI - this is parallelized and so it is fast.\n            [{**{self.document_variable_name: d.page_content}, **kwargs} for d in docs],\n            callbacks=callbacks,\n        )\n        return self._process_results(docs, results)\n[docs]    async def acombine_docs(\n        self, docs: List[Document], callbacks: Callbacks = None, **kwargs: Any\n    ) -> Tuple[str, dict]:\n        \"\"\"Combine documents in a map rerank manner.\n        Combine by mapping first chain over all documents, then reranking the results.\n        Args:\n            docs: List of documents to combine\n            callbacks: Callbacks to be passed through\n            **kwargs: additional parameters to be passed to LLM calls (like other\n                input variables besides the documents)\n        Returns:\n            The first element returned is the single string output. The second\n            element returned is a dictionary of other keys to return.\n        \"\"\"\n        results = await self.llm_chain.aapply_and_parse(\n            # FYI - this is parallelized and so it is fast.\n            [{**{self.document_variable_name: d.page_content}, **kwargs} for d in docs],\n            callbacks=callbacks,\n        )\n        return self._process_results(docs, results)\n    def _process_results(\n        self,\n        docs: List[Document],\n        results: Sequence[Union[str, List[str], Dict[str, str]]],\n    ) -> Tuple[str, dict]:\n        typed_results = cast(List[dict], results)\n        sorted_res = sorted(\n            zip(typed_results, docs), key=lambda x: -int(x[0][self.rank_key])\n        )\n        output, document = sorted_res[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html"}
{"id": "cd870b8b73a8-5", "text": ")\n        output, document = sorted_res[0]\n        extra_info = {}\n        if self.metadata_keys is not None:\n            for key in self.metadata_keys:\n                extra_info[key] = document.metadata[key]\n        if self.return_intermediate_steps:\n            extra_info[\"intermediate_steps\"] = results\n        return output[self.answer_key], extra_info\n    @property\n    def _chain_type(self) -> str:\n        return \"map_rerank_documents_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html"}
{"id": "38c6a19de250-0", "text": "Source code for langchain.chains.combine_documents.stuff\n\"\"\"Chain that combines documents by stuffing into context.\"\"\"\nfrom typing import Any, Dict, List, Optional, Tuple\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains.combine_documents.base import (\n    BaseCombineDocumentsChain,\n)\nfrom langchain.chains.llm import LLMChain\nfrom langchain.docstore.document import Document\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.schema import BasePromptTemplate, format_document\ndef _get_default_document_prompt() -> PromptTemplate:\n    return PromptTemplate(input_variables=[\"page_content\"], template=\"{page_content}\")\n[docs]class StuffDocumentsChain(BaseCombineDocumentsChain):\n    \"\"\"Chain that combines documents by stuffing into context.\n    This chain takes a list of documents and first combines them into a single string.\n    It does this by formatting each document into a string with the `document_prompt`\n    and then joining them together with `document_separator`. It then adds that new\n    string to the inputs with the variable name set by `document_variable_name`.\n    Those inputs are then passed to the `llm_chain`.\n    Example:\n        .. code-block:: python\n            from langchain.chains import StuffDocumentsChain, LLMChain\n            from langchain.prompts import PromptTemplate\n            from langchain.llms import OpenAI\n            # This controls how each document will be formatted. Specifically,\n            # it will be passed to `format_document` - see that function for more\n            # details.\n            document_prompt = PromptTemplate(\n                input_variables=[\"page_content\"],\n                template=\"{page_content}\"\n            )\n            document_variable_name = \"context\"\n            llm = OpenAI()\n            # The prompt here should take as an input variable the", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html"}
{"id": "38c6a19de250-1", "text": "# The prompt here should take as an input variable the\n            # `document_variable_name`\n            prompt = PromptTemplate.from_template(\n                \"Summarize this content: {context}\"\n            )\n            llm_chain = LLMChain(llm=llm, prompt=prompt)\n            chain = StuffDocumentsChain(\n                llm_chain=llm_chain,\n                document_prompt=document_prompt,\n                document_variable_name=document_variable_name\n            )\n    \"\"\"\n    llm_chain: LLMChain\n    \"\"\"LLM chain which is called with the formatted document string,\n    along with any other inputs.\"\"\"\n    document_prompt: BasePromptTemplate = Field(\n        default_factory=_get_default_document_prompt\n    )\n    \"\"\"Prompt to use to format each document, gets passed to `format_document`.\"\"\"\n    document_variable_name: str\n    \"\"\"The variable name in the llm_chain to put the documents in.\n    If only one variable in the llm_chain, this need not be provided.\"\"\"\n    document_separator: str = \"\\n\\n\"\n    \"\"\"The string with which to join the formatted documents\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator(pre=True)\n    def get_default_document_variable_name(cls, values: Dict) -> Dict:\n        \"\"\"Get default document variable name, if not provided.\n        If only one variable is present in the llm_chain.prompt,\n        we can infer that the formatted documents should be passed in\n        with this variable name.\n        \"\"\"\n        llm_chain_variables = values[\"llm_chain\"].prompt.input_variables\n        if \"document_variable_name\" not in values:\n            if len(llm_chain_variables) == 1:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html"}
{"id": "38c6a19de250-2", "text": "if len(llm_chain_variables) == 1:\n                values[\"document_variable_name\"] = llm_chain_variables[0]\n            else:\n                raise ValueError(\n                    \"document_variable_name must be provided if there are \"\n                    \"multiple llm_chain_variables\"\n                )\n        else:\n            if values[\"document_variable_name\"] not in llm_chain_variables:\n                raise ValueError(\n                    f\"document_variable_name {values['document_variable_name']} was \"\n                    f\"not found in llm_chain input_variables: {llm_chain_variables}\"\n                )\n        return values\n    @property\n    def input_keys(self) -> List[str]:\n        extra_keys = [\n            k for k in self.llm_chain.input_keys if k != self.document_variable_name\n        ]\n        return super().input_keys + extra_keys\n    def _get_inputs(self, docs: List[Document], **kwargs: Any) -> dict:\n        \"\"\"Construct inputs from kwargs and docs.\n        Format and the join all the documents together into one input with name\n        `self.document_variable_name`. The pluck any additional variables\n        from **kwargs.\n        Args:\n            docs: List of documents to format and then join into single input\n            **kwargs: additional inputs to chain, will pluck any other required\n                arguments from here.\n        Returns:\n            dictionary of inputs to LLMChain\n        \"\"\"\n        # Format each document according to the prompt\n        doc_strings = [format_document(doc, self.document_prompt) for doc in docs]\n        # Join the documents together to put them in the prompt.\n        inputs = {\n            k: v\n            for k, v in kwargs.items()\n            if k in self.llm_chain.prompt.input_variables\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html"}
{"id": "38c6a19de250-3", "text": "if k in self.llm_chain.prompt.input_variables\n        }\n        inputs[self.document_variable_name] = self.document_separator.join(doc_strings)\n        return inputs\n[docs]    def prompt_length(self, docs: List[Document], **kwargs: Any) -> Optional[int]:\n        \"\"\"Return the prompt length given the documents passed in.\n        This can be used by a caller to determine whether passing in a list\n        of documents would exceed a certain prompt length. This useful when\n        trying to ensure that the size of a prompt remains below a certain\n        context limit.\n        Args:\n            docs: List[Document], a list of documents to use to calculate the\n                total prompt length.\n        Returns:\n            Returns None if the method does not depend on the prompt length,\n            otherwise the length of the prompt in tokens.\n        \"\"\"\n        inputs = self._get_inputs(docs, **kwargs)\n        prompt = self.llm_chain.prompt.format(**inputs)\n        return self.llm_chain._get_num_tokens(prompt)\n[docs]    def combine_docs(\n        self, docs: List[Document], callbacks: Callbacks = None, **kwargs: Any\n    ) -> Tuple[str, dict]:\n        \"\"\"Stuff all documents into one prompt and pass to LLM.\n        Args:\n            docs: List of documents to join together into one variable\n            callbacks: Optional callbacks to pass along\n            **kwargs: additional parameters to use to get inputs to LLMChain.\n        Returns:\n            The first element returned is the single string output. The second\n            element returned is a dictionary of other keys to return.\n        \"\"\"\n        inputs = self._get_inputs(docs, **kwargs)\n        # Call predict on the LLM.\n        return self.llm_chain.predict(callbacks=callbacks, **inputs), {}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html"}
{"id": "38c6a19de250-4", "text": "return self.llm_chain.predict(callbacks=callbacks, **inputs), {}\n[docs]    async def acombine_docs(\n        self, docs: List[Document], callbacks: Callbacks = None, **kwargs: Any\n    ) -> Tuple[str, dict]:\n        \"\"\"Async stuff all documents into one prompt and pass to LLM.\n        Args:\n            docs: List of documents to join together into one variable\n            callbacks: Optional callbacks to pass along\n            **kwargs: additional parameters to use to get inputs to LLMChain.\n        Returns:\n            The first element returned is the single string output. The second\n            element returned is a dictionary of other keys to return.\n        \"\"\"\n        inputs = self._get_inputs(docs, **kwargs)\n        # Call predict on the LLM.\n        return await self.llm_chain.apredict(callbacks=callbacks, **inputs), {}\n    @property\n    def _chain_type(self) -> str:\n        return \"stuff_documents_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html"}
{"id": "5957d20dc08b-0", "text": "Source code for langchain.chains.combine_documents.base\n\"\"\"Base interface for chains combining documents.\"\"\"\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Dict, List, Optional, Tuple, Type\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import BaseModel, Field, create_model\nfrom langchain.schema.runnable.config import RunnableConfig\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter, TextSplitter\n[docs]class BaseCombineDocumentsChain(Chain, ABC):\n    \"\"\"Base interface for chains combining documents.\n    Subclasses of this chain deal with combining documents in a variety of\n    ways. This base class exists to add some uniformity in the interface these types\n    of chains should expose. Namely, they expect an input key related to the documents\n    to use (default `input_documents`), and then also expose a method to calculate\n    the length of a prompt from documents (useful for outside callers to use to\n    determine whether it's safe to pass a list of documents into this chain or whether\n    that will longer than the context length).\n    \"\"\"\n    input_key: str = \"input_documents\"  #: :meta private:\n    output_key: str = \"output_text\"  #: :meta private:\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        return create_model(\n            \"CombineDocumentsInput\",\n            **{self.input_key: (List[Document], None)},  # type: ignore[call-overload]\n        )\n[docs]    def get_output_schema(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html"}
{"id": "5957d20dc08b-1", "text": ")\n[docs]    def get_output_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        return create_model(\n            \"CombineDocumentsOutput\",\n            **{self.output_key: (str, None)},  # type: ignore[call-overload]\n        )\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return output key.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n[docs]    def prompt_length(self, docs: List[Document], **kwargs: Any) -> Optional[int]:\n        \"\"\"Return the prompt length given the documents passed in.\n        This can be used by a caller to determine whether passing in a list\n        of documents would exceed a certain prompt length. This useful when\n        trying to ensure that the size of a prompt remains below a certain\n        context limit.\n        Args:\n            docs: List[Document], a list of documents to use to calculate the\n                total prompt length.\n        Returns:\n            Returns None if the method does not depend on the prompt length,\n            otherwise the length of the prompt in tokens.\n        \"\"\"\n        return None\n[docs]    @abstractmethod\n    def combine_docs(self, docs: List[Document], **kwargs: Any) -> Tuple[str, dict]:\n        \"\"\"Combine documents into a single string.\n        Args:\n            docs: List[Document], the documents to combine\n            **kwargs: Other parameters to use in combining documents, often\n                other inputs to the prompt.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html"}
{"id": "5957d20dc08b-2", "text": "other inputs to the prompt.\n        Returns:\n            The first element returned is the single string output. The second\n            element returned is a dictionary of other keys to return.\n        \"\"\"\n[docs]    @abstractmethod\n    async def acombine_docs(\n        self, docs: List[Document], **kwargs: Any\n    ) -> Tuple[str, dict]:\n        \"\"\"Combine documents into a single string.\n        Args:\n            docs: List[Document], the documents to combine\n            **kwargs: Other parameters to use in combining documents, often\n                other inputs to the prompt.\n        Returns:\n            The first element returned is the single string output. The second\n            element returned is a dictionary of other keys to return.\n        \"\"\"\n    def _call(\n        self,\n        inputs: Dict[str, List[Document]],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        \"\"\"Prepare inputs, call combine docs, prepare outputs.\"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        docs = inputs[self.input_key]\n        # Other keys are assumed to be needed for LLM prediction\n        other_keys = {k: v for k, v in inputs.items() if k != self.input_key}\n        output, extra_return_dict = self.combine_docs(\n            docs, callbacks=_run_manager.get_child(), **other_keys\n        )\n        extra_return_dict[self.output_key] = output\n        return extra_return_dict\n    async def _acall(\n        self,\n        inputs: Dict[str, List[Document]],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        \"\"\"Prepare inputs, call combine docs, prepare outputs.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html"}
{"id": "5957d20dc08b-3", "text": "\"\"\"Prepare inputs, call combine docs, prepare outputs.\"\"\"\n        _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()\n        docs = inputs[self.input_key]\n        # Other keys are assumed to be needed for LLM prediction\n        other_keys = {k: v for k, v in inputs.items() if k != self.input_key}\n        output, extra_return_dict = await self.acombine_docs(\n            docs, callbacks=_run_manager.get_child(), **other_keys\n        )\n        extra_return_dict[self.output_key] = output\n        return extra_return_dict\n[docs]class AnalyzeDocumentChain(Chain):\n    \"\"\"Chain that splits documents, then analyzes it in pieces.\n    This chain is parameterized by a TextSplitter and a CombineDocumentsChain.\n    This chain takes a single document as input, and then splits it up into chunks\n    and then passes those chucks to the CombineDocumentsChain.\n    \"\"\"\n    input_key: str = \"input_document\"  #: :meta private:\n    text_splitter: TextSplitter = Field(default_factory=RecursiveCharacterTextSplitter)\n    combine_docs_chain: BaseCombineDocumentsChain\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return output key.\n        :meta private:\n        \"\"\"\n        return self.combine_docs_chain.output_keys\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        return create_model(\n            \"AnalyzeDocumentChain\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html"}
{"id": "5957d20dc08b-4", "text": "return create_model(\n            \"AnalyzeDocumentChain\",\n            **{self.input_key: (str, None)},  # type: ignore[call-overload]\n        )\n[docs]    def get_output_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        return self.combine_docs_chain.get_output_schema(config)\n    def _call(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        \"\"\"Split document into chunks and pass to CombineDocumentsChain.\"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        document = inputs[self.input_key]\n        docs = self.text_splitter.create_documents([document])\n        # Other keys are assumed to be needed for LLM prediction\n        other_keys: Dict = {k: v for k, v in inputs.items() if k != self.input_key}\n        other_keys[self.combine_docs_chain.input_key] = docs\n        return self.combine_docs_chain(\n            other_keys, return_only_outputs=True, callbacks=_run_manager.get_child()\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html"}
{"id": "d9c32bc2d44b-0", "text": "Source code for langchain.chains.combine_documents.reduce\n\"\"\"Combine many documents together by recursively reducing them.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Callable, List, Optional, Protocol, Tuple\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains.combine_documents.base import BaseCombineDocumentsChain\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import Extra\n[docs]class CombineDocsProtocol(Protocol):\n    \"\"\"Interface for the combine_docs method.\"\"\"\n    def __call__(self, docs: List[Document], **kwargs: Any) -> str:\n        \"\"\"Interface for the combine_docs method.\"\"\"\n[docs]class AsyncCombineDocsProtocol(Protocol):\n    \"\"\"Interface for the combine_docs method.\"\"\"\n    async def __call__(self, docs: List[Document], **kwargs: Any) -> str:\n        \"\"\"Async interface for the combine_docs method.\"\"\"\n[docs]def split_list_of_docs(\n    docs: List[Document], length_func: Callable, token_max: int, **kwargs: Any\n) -> List[List[Document]]:\n    \"\"\"Split Documents into subsets that each meet a cumulative length constraint.\n    Args:\n        docs: The full list of Documents.\n        length_func: Function for computing the cumulative length of a set of Documents.\n        token_max: The maximum cumulative length of any subset of Documents.\n        **kwargs: Arbitrary additional keyword params to pass to each call of the\n            length_func.\n    Returns:\n        A List[List[Document]].\n    \"\"\"\n    new_result_doc_list = []\n    _sub_result_docs = []\n    for doc in docs:\n        _sub_result_docs.append(doc)\n        _num_tokens = length_func(_sub_result_docs, **kwargs)\n        if _num_tokens > token_max:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html"}
{"id": "d9c32bc2d44b-1", "text": "if _num_tokens > token_max:\n            if len(_sub_result_docs) == 1:\n                raise ValueError(\n                    \"A single document was longer than the context length,\"\n                    \" we cannot handle this.\"\n                )\n            new_result_doc_list.append(_sub_result_docs[:-1])\n            _sub_result_docs = _sub_result_docs[-1:]\n    new_result_doc_list.append(_sub_result_docs)\n    return new_result_doc_list\n[docs]def collapse_docs(\n    docs: List[Document],\n    combine_document_func: CombineDocsProtocol,\n    **kwargs: Any,\n) -> Document:\n    \"\"\"Execute a collapse function on a set of documents and merge their metadatas.\n    Args:\n        docs: A list of Documents to combine.\n        combine_document_func: A function that takes in a list of Documents and\n            optionally addition keyword parameters and combines them into a single\n            string.\n        **kwargs: Arbitrary additional keyword params to pass to the\n            combine_document_func.\n    Returns:\n        A single Document with the output of combine_document_func for the page content\n            and the combined metadata's of all the input documents. All metadata values\n            are strings, and where there are overlapping keys across documents the\n            values are joined by \", \".\n    \"\"\"\n    result = combine_document_func(docs, **kwargs)\n    combined_metadata = {k: str(v) for k, v in docs[0].metadata.items()}\n    for doc in docs[1:]:\n        for k, v in doc.metadata.items():\n            if k in combined_metadata:\n                combined_metadata[k] += f\", {v}\"\n            else:\n                combined_metadata[k] = str(v)\n    return Document(page_content=result, metadata=combined_metadata)\n[docs]async def acollapse_docs(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html"}
{"id": "d9c32bc2d44b-2", "text": "[docs]async def acollapse_docs(\n    docs: List[Document],\n    combine_document_func: AsyncCombineDocsProtocol,\n    **kwargs: Any,\n) -> Document:\n    \"\"\"Execute a collapse function on a set of documents and merge their metadatas.\n    Args:\n        docs: A list of Documents to combine.\n        combine_document_func: A function that takes in a list of Documents and\n            optionally addition keyword parameters and combines them into a single\n            string.\n        **kwargs: Arbitrary additional keyword params to pass to the\n            combine_document_func.\n    Returns:\n        A single Document with the output of combine_document_func for the page content\n            and the combined metadata's of all the input documents. All metadata values\n            are strings, and where there are overlapping keys across documents the\n            values are joined by \", \".\n    \"\"\"\n    result = await combine_document_func(docs, **kwargs)\n    combined_metadata = {k: str(v) for k, v in docs[0].metadata.items()}\n    for doc in docs[1:]:\n        for k, v in doc.metadata.items():\n            if k in combined_metadata:\n                combined_metadata[k] += f\", {v}\"\n            else:\n                combined_metadata[k] = str(v)\n    return Document(page_content=result, metadata=combined_metadata)\n[docs]class ReduceDocumentsChain(BaseCombineDocumentsChain):\n    \"\"\"Combine documents by recursively reducing them.\n    This involves\n    - combine_documents_chain\n    - collapse_documents_chain\n    `combine_documents_chain` is ALWAYS provided. This is final chain that is called.\n    We pass all previous results to this chain, and the output of this chain is\n    returned as a final result.\n    `collapse_documents_chain` is used if the documents passed in are too many to all", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html"}
{"id": "d9c32bc2d44b-3", "text": "`collapse_documents_chain` is used if the documents passed in are too many to all\n    be passed to `combine_documents_chain` in one go. In this case,\n    `collapse_documents_chain` is called recursively on as big of groups of documents\n    as are allowed.\n    Example:\n        .. code-block:: python\n            from langchain.chains import (\n                StuffDocumentsChain, LLMChain, ReduceDocumentsChain\n            )\n            from langchain.prompts import PromptTemplate\n            from langchain.llms import OpenAI\n            # This controls how each document will be formatted. Specifically,\n            # it will be passed to `format_document` - see that function for more\n            # details.\n            document_prompt = PromptTemplate(\n                input_variables=[\"page_content\"],\n                 template=\"{page_content}\"\n            )\n            document_variable_name = \"context\"\n            llm = OpenAI()\n            # The prompt here should take as an input variable the\n            # `document_variable_name`\n            prompt = PromptTemplate.from_template(\n                \"Summarize this content: {context}\"\n            )\n            llm_chain = LLMChain(llm=llm, prompt=prompt)\n            combine_documents_chain = StuffDocumentsChain(\n                llm_chain=llm_chain,\n                document_prompt=document_prompt,\n                document_variable_name=document_variable_name\n            )\n            chain = ReduceDocumentsChain(\n                combine_documents_chain=combine_documents_chain,\n            )\n            # If we wanted to, we could also pass in collapse_documents_chain\n            # which is specifically aimed at collapsing documents BEFORE\n            # the final call.\n            prompt = PromptTemplate.from_template(\n                \"Collapse this content: {context}\"\n            )\n            llm_chain = LLMChain(llm=llm, prompt=prompt)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html"}
{"id": "d9c32bc2d44b-4", "text": "llm_chain = LLMChain(llm=llm, prompt=prompt)\n            collapse_documents_chain = StuffDocumentsChain(\n                llm_chain=llm_chain,\n                document_prompt=document_prompt,\n                document_variable_name=document_variable_name\n            )\n            chain = ReduceDocumentsChain(\n                combine_documents_chain=combine_documents_chain,\n                collapse_documents_chain=collapse_documents_chain,\n            )\n    \"\"\"\n    combine_documents_chain: BaseCombineDocumentsChain\n    \"\"\"Final chain to call to combine documents.\n    This is typically a StuffDocumentsChain.\"\"\"\n    collapse_documents_chain: Optional[BaseCombineDocumentsChain] = None\n    \"\"\"Chain to use to collapse documents if needed until they can all fit.\n    If None, will use the combine_documents_chain.\n    This is typically a StuffDocumentsChain.\"\"\"\n    token_max: int = 3000\n    \"\"\"The maximum number of tokens to group documents into. For example, if\n    set to 3000 then documents will be grouped into chunks of no greater than\n    3000 tokens before trying to combine them into a smaller chunk.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def _collapse_chain(self) -> BaseCombineDocumentsChain:\n        if self.collapse_documents_chain is not None:\n            return self.collapse_documents_chain\n        else:\n            return self.combine_documents_chain\n[docs]    def combine_docs(\n        self,\n        docs: List[Document],\n        token_max: Optional[int] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Tuple[str, dict]:\n        \"\"\"Combine multiple documents recursively.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html"}
{"id": "d9c32bc2d44b-5", "text": "\"\"\"Combine multiple documents recursively.\n        Args:\n            docs: List of documents to combine, assumed that each one is less than\n                `token_max`.\n            token_max: Recursively creates groups of documents less than this number\n                of tokens.\n            callbacks: Callbacks to be passed through\n            **kwargs: additional parameters to be passed to LLM calls (like other\n                input variables besides the documents)\n        Returns:\n            The first element returned is the single string output. The second\n            element returned is a dictionary of other keys to return.\n        \"\"\"\n        result_docs, extra_return_dict = self._collapse(\n            docs, token_max=token_max, callbacks=callbacks, **kwargs\n        )\n        return self.combine_documents_chain.combine_docs(\n            docs=result_docs, callbacks=callbacks, **kwargs\n        )\n[docs]    async def acombine_docs(\n        self,\n        docs: List[Document],\n        token_max: Optional[int] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Tuple[str, dict]:\n        \"\"\"Async combine multiple documents recursively.\n        Args:\n            docs: List of documents to combine, assumed that each one is less than\n                `token_max`.\n            token_max: Recursively creates groups of documents less than this number\n                of tokens.\n            callbacks: Callbacks to be passed through\n            **kwargs: additional parameters to be passed to LLM calls (like other\n                input variables besides the documents)\n        Returns:\n            The first element returned is the single string output. The second\n            element returned is a dictionary of other keys to return.\n        \"\"\"\n        result_docs, extra_return_dict = await self._acollapse(\n            docs, token_max=token_max, callbacks=callbacks, **kwargs\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html"}
{"id": "d9c32bc2d44b-6", "text": "docs, token_max=token_max, callbacks=callbacks, **kwargs\n        )\n        return await self.combine_documents_chain.acombine_docs(\n            docs=result_docs, callbacks=callbacks, **kwargs\n        )\n    def _collapse(\n        self,\n        docs: List[Document],\n        token_max: Optional[int] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Tuple[List[Document], dict]:\n        result_docs = docs\n        length_func = self.combine_documents_chain.prompt_length\n        num_tokens = length_func(result_docs, **kwargs)\n        def _collapse_docs_func(docs: List[Document], **kwargs: Any) -> str:\n            return self._collapse_chain.run(\n                input_documents=docs, callbacks=callbacks, **kwargs\n            )\n        _token_max = token_max or self.token_max\n        while num_tokens is not None and num_tokens > _token_max:\n            new_result_doc_list = split_list_of_docs(\n                result_docs, length_func, _token_max, **kwargs\n            )\n            result_docs = []\n            for docs in new_result_doc_list:\n                new_doc = collapse_docs(docs, _collapse_docs_func, **kwargs)\n                result_docs.append(new_doc)\n            num_tokens = length_func(result_docs, **kwargs)\n        return result_docs, {}\n    async def _acollapse(\n        self,\n        docs: List[Document],\n        token_max: Optional[int] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Tuple[List[Document], dict]:\n        result_docs = docs\n        length_func = self.combine_documents_chain.prompt_length\n        num_tokens = length_func(result_docs, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html"}
{"id": "d9c32bc2d44b-7", "text": "num_tokens = length_func(result_docs, **kwargs)\n        async def _collapse_docs_func(docs: List[Document], **kwargs: Any) -> str:\n            return await self._collapse_chain.arun(\n                input_documents=docs, callbacks=callbacks, **kwargs\n            )\n        _token_max = token_max or self.token_max\n        while num_tokens is not None and num_tokens > _token_max:\n            new_result_doc_list = split_list_of_docs(\n                result_docs, length_func, _token_max, **kwargs\n            )\n            result_docs = []\n            for docs in new_result_doc_list:\n                new_doc = await acollapse_docs(docs, _collapse_docs_func, **kwargs)\n                result_docs.append(new_doc)\n            num_tokens = length_func(result_docs, **kwargs)\n        return result_docs, {}\n    @property\n    def _chain_type(self) -> str:\n        return \"reduce_documents_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html"}
{"id": "f99e5cbe750d-0", "text": "Source code for langchain.chains.combine_documents.map_reduce\n\"\"\"Combining documents by mapping a chain over them first, then combining results.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional, Tuple, Type\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains.combine_documents.base import BaseCombineDocumentsChain\nfrom langchain.chains.combine_documents.reduce import ReduceDocumentsChain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import BaseModel, Extra, create_model, root_validator\nfrom langchain.schema.runnable.config import RunnableConfig\n[docs]class MapReduceDocumentsChain(BaseCombineDocumentsChain):\n    \"\"\"Combining documents by mapping a chain over them, then combining results.\n    We first call `llm_chain` on each document individually, passing in the\n    `page_content` and any other kwargs. This is the `map` step.\n    We then process the results of that `map` step in a `reduce` step. This should\n    likely be a ReduceDocumentsChain.\n    Example:\n        .. code-block:: python\n            from langchain.chains import (\n                StuffDocumentsChain,\n                LLMChain,\n                ReduceDocumentsChain,\n                MapReduceDocumentsChain,\n            )\n            from langchain.prompts import PromptTemplate\n            from langchain.llms import OpenAI\n            # This controls how each document will be formatted. Specifically,\n            # it will be passed to `format_document` - see that function for more\n            # details.\n            document_prompt = PromptTemplate(\n                input_variables=[\"page_content\"],\n                 template=\"{page_content}\"\n            )\n            document_variable_name = \"context\"\n            llm = OpenAI()\n            # The prompt here should take as an input variable the", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html"}
{"id": "f99e5cbe750d-1", "text": "# The prompt here should take as an input variable the\n            # `document_variable_name`\n            prompt = PromptTemplate.from_template(\n                \"Summarize this content: {context}\"\n            )\n            llm_chain = LLMChain(llm=llm, prompt=prompt)\n            # We now define how to combine these summaries\n            reduce_prompt = PromptTemplate.from_template(\n                \"Combine these summaries: {context}\"\n            )\n            reduce_llm_chain = LLMChain(llm=llm, prompt=reduce_prompt)\n            combine_documents_chain = StuffDocumentsChain(\n                llm_chain=reduce_llm_chain,\n                document_prompt=document_prompt,\n                document_variable_name=document_variable_name\n            )\n            reduce_documents_chain = ReduceDocumentsChain(\n                combine_documents_chain=combine_documents_chain,\n            )\n            chain = MapReduceDocumentsChain(\n                llm_chain=llm_chain,\n                reduce_documents_chain=reduce_documents_chain,\n            )\n            # If we wanted to, we could also pass in collapse_documents_chain\n            # which is specifically aimed at collapsing documents BEFORE\n            # the final call.\n            prompt = PromptTemplate.from_template(\n                \"Collapse this content: {context}\"\n            )\n            llm_chain = LLMChain(llm=llm, prompt=prompt)\n            collapse_documents_chain = StuffDocumentsChain(\n                llm_chain=llm_chain,\n                document_prompt=document_prompt,\n                document_variable_name=document_variable_name\n            )\n            reduce_documents_chain = ReduceDocumentsChain(\n                combine_documents_chain=combine_documents_chain,\n                collapse_documents_chain=collapse_documents_chain,\n            )\n            chain = MapReduceDocumentsChain(\n                llm_chain=llm_chain,\n                reduce_documents_chain=reduce_documents_chain,\n            )\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html"}
{"id": "f99e5cbe750d-2", "text": "reduce_documents_chain=reduce_documents_chain,\n            )\n    \"\"\"\n    llm_chain: LLMChain\n    \"\"\"Chain to apply to each document individually.\"\"\"\n    reduce_documents_chain: BaseCombineDocumentsChain\n    \"\"\"Chain to use to reduce the results of applying `llm_chain` to each doc.\n    This typically either a ReduceDocumentChain or StuffDocumentChain.\"\"\"\n    document_variable_name: str\n    \"\"\"The variable name in the llm_chain to put the documents in.\n    If only one variable in the llm_chain, this need not be provided.\"\"\"\n    return_intermediate_steps: bool = False\n    \"\"\"Return the results of the map steps in the output.\"\"\"\n[docs]    def get_output_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        if self.return_intermediate_steps:\n            return create_model(\n                \"MapReduceDocumentsOutput\",\n                **{\n                    self.output_key: (str, None),\n                    \"intermediate_steps\": (List[str], None),\n                },  # type: ignore[call-overload]\n            )\n        return super().get_output_schema(config)\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        _output_keys = super().output_keys\n        if self.return_intermediate_steps:\n            _output_keys = _output_keys + [\"intermediate_steps\"]\n        return _output_keys\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator(pre=True)\n    def get_reduce_chain(cls, values: Dict) -> Dict:\n        \"\"\"For backwards compatibility.\"\"\"\n        if \"combine_document_chain\" in values:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html"}
{"id": "f99e5cbe750d-3", "text": "\"\"\"For backwards compatibility.\"\"\"\n        if \"combine_document_chain\" in values:\n            if \"reduce_documents_chain\" in values:\n                raise ValueError(\n                    \"Both `reduce_documents_chain` and `combine_document_chain` \"\n                    \"cannot be provided at the same time. `combine_document_chain` \"\n                    \"is deprecated, please only provide `reduce_documents_chain`\"\n                )\n            combine_chain = values[\"combine_document_chain\"]\n            collapse_chain = values.get(\"collapse_document_chain\")\n            reduce_chain = ReduceDocumentsChain(\n                combine_documents_chain=combine_chain,\n                collapse_documents_chain=collapse_chain,\n            )\n            values[\"reduce_documents_chain\"] = reduce_chain\n            del values[\"combine_document_chain\"]\n            if \"collapse_document_chain\" in values:\n                del values[\"collapse_document_chain\"]\n        return values\n    @root_validator(pre=True)\n    def get_return_intermediate_steps(cls, values: Dict) -> Dict:\n        \"\"\"For backwards compatibility.\"\"\"\n        if \"return_map_steps\" in values:\n            values[\"return_intermediate_steps\"] = values[\"return_map_steps\"]\n            del values[\"return_map_steps\"]\n        return values\n    @root_validator(pre=True)\n    def get_default_document_variable_name(cls, values: Dict) -> Dict:\n        \"\"\"Get default document variable name, if not provided.\"\"\"\n        if \"document_variable_name\" not in values:\n            llm_chain_variables = values[\"llm_chain\"].prompt.input_variables\n            if len(llm_chain_variables) == 1:\n                values[\"document_variable_name\"] = llm_chain_variables[0]\n            else:\n                raise ValueError(\n                    \"document_variable_name must be provided if there are \"\n                    \"multiple llm_chain input_variables\"\n                )\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html"}
{"id": "f99e5cbe750d-4", "text": "\"multiple llm_chain input_variables\"\n                )\n        else:\n            llm_chain_variables = values[\"llm_chain\"].prompt.input_variables\n            if values[\"document_variable_name\"] not in llm_chain_variables:\n                raise ValueError(\n                    f\"document_variable_name {values['document_variable_name']} was \"\n                    f\"not found in llm_chain input_variables: {llm_chain_variables}\"\n                )\n        return values\n    @property\n    def collapse_document_chain(self) -> BaseCombineDocumentsChain:\n        \"\"\"Kept for backward compatibility.\"\"\"\n        if isinstance(self.reduce_documents_chain, ReduceDocumentsChain):\n            if self.reduce_documents_chain.collapse_documents_chain:\n                return self.reduce_documents_chain.collapse_documents_chain\n            else:\n                return self.reduce_documents_chain.combine_documents_chain\n        else:\n            raise ValueError(\n                f\"`reduce_documents_chain` is of type \"\n                f\"{type(self.reduce_documents_chain)} so it does not have \"\n                f\"this attribute.\"\n            )\n    @property\n    def combine_document_chain(self) -> BaseCombineDocumentsChain:\n        \"\"\"Kept for backward compatibility.\"\"\"\n        if isinstance(self.reduce_documents_chain, ReduceDocumentsChain):\n            return self.reduce_documents_chain.combine_documents_chain\n        else:\n            raise ValueError(\n                f\"`reduce_documents_chain` is of type \"\n                f\"{type(self.reduce_documents_chain)} so it does not have \"\n                f\"this attribute.\"\n            )\n[docs]    def combine_docs(\n        self,\n        docs: List[Document],\n        token_max: Optional[int] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Tuple[str, dict]:\n        \"\"\"Combine documents in a map reduce manner.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html"}
{"id": "f99e5cbe750d-5", "text": ") -> Tuple[str, dict]:\n        \"\"\"Combine documents in a map reduce manner.\n        Combine by mapping first chain over all documents, then reducing the results.\n        This reducing can be done recursively if needed (if there are many documents).\n        \"\"\"\n        map_results = self.llm_chain.apply(\n            # FYI - this is parallelized and so it is fast.\n            [{self.document_variable_name: d.page_content, **kwargs} for d in docs],\n            callbacks=callbacks,\n        )\n        question_result_key = self.llm_chain.output_key\n        result_docs = [\n            Document(page_content=r[question_result_key], metadata=docs[i].metadata)\n            # This uses metadata from the docs, and the textual results from `results`\n            for i, r in enumerate(map_results)\n        ]\n        result, extra_return_dict = self.reduce_documents_chain.combine_docs(\n            result_docs, token_max=token_max, callbacks=callbacks, **kwargs\n        )\n        if self.return_intermediate_steps:\n            intermediate_steps = [r[question_result_key] for r in map_results]\n            extra_return_dict[\"intermediate_steps\"] = intermediate_steps\n        return result, extra_return_dict\n[docs]    async def acombine_docs(\n        self,\n        docs: List[Document],\n        token_max: Optional[int] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Tuple[str, dict]:\n        \"\"\"Combine documents in a map reduce manner.\n        Combine by mapping first chain over all documents, then reducing the results.\n        This reducing can be done recursively if needed (if there are many documents).\n        \"\"\"\n        map_results = await self.llm_chain.aapply(\n            # FYI - this is parallelized and so it is fast.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html"}
{"id": "f99e5cbe750d-6", "text": "# FYI - this is parallelized and so it is fast.\n            [{**{self.document_variable_name: d.page_content}, **kwargs} for d in docs],\n            callbacks=callbacks,\n        )\n        question_result_key = self.llm_chain.output_key\n        result_docs = [\n            Document(page_content=r[question_result_key], metadata=docs[i].metadata)\n            # This uses metadata from the docs, and the textual results from `results`\n            for i, r in enumerate(map_results)\n        ]\n        result, extra_return_dict = await self.reduce_documents_chain.acombine_docs(\n            result_docs, token_max=token_max, callbacks=callbacks, **kwargs\n        )\n        if self.return_intermediate_steps:\n            intermediate_steps = [r[question_result_key] for r in map_results]\n            extra_return_dict[\"intermediate_steps\"] = intermediate_steps\n        return result, extra_return_dict\n    @property\n    def _chain_type(self) -> str:\n        return \"map_reduce_documents_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html"}
{"id": "4e0127867a4a-0", "text": "Source code for langchain.chains.combine_documents.refine\n\"\"\"Combine documents by doing a first pass and then refining on more documents.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Tuple\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains.combine_documents.base import (\n    BaseCombineDocumentsChain,\n)\nfrom langchain.chains.llm import LLMChain\nfrom langchain.docstore.document import Document\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.schema import BasePromptTemplate, format_document\ndef _get_default_document_prompt() -> PromptTemplate:\n    return PromptTemplate(input_variables=[\"page_content\"], template=\"{page_content}\")\n[docs]class RefineDocumentsChain(BaseCombineDocumentsChain):\n    \"\"\"Combine documents by doing a first pass and then refining on more documents.\n    This algorithm first calls `initial_llm_chain` on the first document, passing\n    that first document in with the variable name `document_variable_name`, and\n    produces a new variable with the variable name `initial_response_name`.\n    Then, it loops over every remaining document. This is called the \"refine\" step.\n    It calls `refine_llm_chain`,\n    passing in that document with the variable name `document_variable_name`\n    as well as the previous response with the variable name `initial_response_name`.\n    Example:\n        .. code-block:: python\n            from langchain.chains import RefineDocumentsChain, LLMChain\n            from langchain.prompts import PromptTemplate\n            from langchain.llms import OpenAI\n            # This controls how each document will be formatted. Specifically,\n            # it will be passed to `format_document` - see that function for more\n            # details.\n            document_prompt = PromptTemplate(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html"}
{"id": "4e0127867a4a-1", "text": "# details.\n            document_prompt = PromptTemplate(\n                input_variables=[\"page_content\"],\n                 template=\"{page_content}\"\n            )\n            document_variable_name = \"context\"\n            llm = OpenAI()\n            # The prompt here should take as an input variable the\n            # `document_variable_name`\n            prompt = PromptTemplate.from_template(\n                \"Summarize this content: {context}\"\n            )\n            initial_llm_chain = LLMChain(llm=llm, prompt=prompt)\n            initial_response_name = \"prev_response\"\n            # The prompt here should take as an input variable the\n            # `document_variable_name` as well as `initial_response_name`\n            prompt_refine = PromptTemplate.from_template(\n                \"Here's your first summary: {prev_response}. \"\n                \"Now add to it based on the following context: {context}\"\n            )\n            refine_llm_chain = LLMChain(llm=llm, prompt=prompt_refine)\n            chain = RefineDocumentsChain(\n                initial_llm_chain=initial_llm_chain,\n                refine_llm_chain=refine_llm_chain,\n                document_prompt=document_prompt,\n                document_variable_name=document_variable_name,\n                initial_response_name=initial_response_name,\n            )\n    \"\"\"\n    initial_llm_chain: LLMChain\n    \"\"\"LLM chain to use on initial document.\"\"\"\n    refine_llm_chain: LLMChain\n    \"\"\"LLM chain to use when refining.\"\"\"\n    document_variable_name: str\n    \"\"\"The variable name in the initial_llm_chain to put the documents in.\n    If only one variable in the initial_llm_chain, this need not be provided.\"\"\"\n    initial_response_name: str\n    \"\"\"The variable name to format the initial response in when refining.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html"}
{"id": "4e0127867a4a-2", "text": "\"\"\"The variable name to format the initial response in when refining.\"\"\"\n    document_prompt: BasePromptTemplate = Field(\n        default_factory=_get_default_document_prompt\n    )\n    \"\"\"Prompt to use to format each document, gets passed to `format_document`.\"\"\"\n    return_intermediate_steps: bool = False\n    \"\"\"Return the results of the refine steps in the output.\"\"\"\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        _output_keys = super().output_keys\n        if self.return_intermediate_steps:\n            _output_keys = _output_keys + [\"intermediate_steps\"]\n        return _output_keys\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator(pre=True)\n    def get_return_intermediate_steps(cls, values: Dict) -> Dict:\n        \"\"\"For backwards compatibility.\"\"\"\n        if \"return_refine_steps\" in values:\n            values[\"return_intermediate_steps\"] = values[\"return_refine_steps\"]\n            del values[\"return_refine_steps\"]\n        return values\n    @root_validator(pre=True)\n    def get_default_document_variable_name(cls, values: Dict) -> Dict:\n        \"\"\"Get default document variable name, if not provided.\"\"\"\n        if \"document_variable_name\" not in values:\n            llm_chain_variables = values[\"initial_llm_chain\"].prompt.input_variables\n            if len(llm_chain_variables) == 1:\n                values[\"document_variable_name\"] = llm_chain_variables[0]\n            else:\n                raise ValueError(\n                    \"document_variable_name must be provided if there are \"\n                    \"multiple llm_chain input_variables\"\n                )\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html"}
{"id": "4e0127867a4a-3", "text": "\"multiple llm_chain input_variables\"\n                )\n        else:\n            llm_chain_variables = values[\"initial_llm_chain\"].prompt.input_variables\n            if values[\"document_variable_name\"] not in llm_chain_variables:\n                raise ValueError(\n                    f\"document_variable_name {values['document_variable_name']} was \"\n                    f\"not found in llm_chain input_variables: {llm_chain_variables}\"\n                )\n        return values\n[docs]    def combine_docs(\n        self, docs: List[Document], callbacks: Callbacks = None, **kwargs: Any\n    ) -> Tuple[str, dict]:\n        \"\"\"Combine by mapping first chain over all, then stuffing into final chain.\n        Args:\n            docs: List of documents to combine\n            callbacks: Callbacks to be passed through\n            **kwargs: additional parameters to be passed to LLM calls (like other\n                input variables besides the documents)\n        Returns:\n            The first element returned is the single string output. The second\n            element returned is a dictionary of other keys to return.\n        \"\"\"\n        inputs = self._construct_initial_inputs(docs, **kwargs)\n        res = self.initial_llm_chain.predict(callbacks=callbacks, **inputs)\n        refine_steps = [res]\n        for doc in docs[1:]:\n            base_inputs = self._construct_refine_inputs(doc, res)\n            inputs = {**base_inputs, **kwargs}\n            res = self.refine_llm_chain.predict(callbacks=callbacks, **inputs)\n            refine_steps.append(res)\n        return self._construct_result(refine_steps, res)\n[docs]    async def acombine_docs(\n        self, docs: List[Document], callbacks: Callbacks = None, **kwargs: Any\n    ) -> Tuple[str, dict]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html"}
{"id": "4e0127867a4a-4", "text": ") -> Tuple[str, dict]:\n        \"\"\"Async combine by mapping a first chain over all, then stuffing\n         into a final chain.\n        Args:\n            docs: List of documents to combine\n            callbacks: Callbacks to be passed through\n            **kwargs: additional parameters to be passed to LLM calls (like other\n                input variables besides the documents)\n        Returns:\n            The first element returned is the single string output. The second\n            element returned is a dictionary of other keys to return.\n        \"\"\"\n        inputs = self._construct_initial_inputs(docs, **kwargs)\n        res = await self.initial_llm_chain.apredict(callbacks=callbacks, **inputs)\n        refine_steps = [res]\n        for doc in docs[1:]:\n            base_inputs = self._construct_refine_inputs(doc, res)\n            inputs = {**base_inputs, **kwargs}\n            res = await self.refine_llm_chain.apredict(callbacks=callbacks, **inputs)\n            refine_steps.append(res)\n        return self._construct_result(refine_steps, res)\n    def _construct_result(self, refine_steps: List[str], res: str) -> Tuple[str, dict]:\n        if self.return_intermediate_steps:\n            extra_return_dict = {\"intermediate_steps\": refine_steps}\n        else:\n            extra_return_dict = {}\n        return res, extra_return_dict\n    def _construct_refine_inputs(self, doc: Document, res: str) -> Dict[str, Any]:\n        return {\n            self.document_variable_name: format_document(doc, self.document_prompt),\n            self.initial_response_name: res,\n        }\n    def _construct_initial_inputs(\n        self, docs: List[Document], **kwargs: Any\n    ) -> Dict[str, Any]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html"}
{"id": "4e0127867a4a-5", "text": ") -> Dict[str, Any]:\n        base_info = {\"page_content\": docs[0].page_content}\n        base_info.update(docs[0].metadata)\n        document_info = {k: base_info[k] for k in self.document_prompt.input_variables}\n        base_inputs: dict = {\n            self.document_variable_name: self.document_prompt.format(**document_info)\n        }\n        inputs = {**base_inputs, **kwargs}\n        return inputs\n    @property\n    def _chain_type(self) -> str:\n        return \"refine_documents_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html"}
{"id": "8a5bba9cfe17-0", "text": "Source code for langchain.chains.router.multi_prompt\n\"\"\"Use a single chain to route an input to one of multiple llm chains.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional\nfrom langchain.chains import ConversationChain\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.router.base import MultiRouteChain\nfrom langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser\nfrom langchain.chains.router.multi_prompt_prompt import MULTI_PROMPT_ROUTER_TEMPLATE\nfrom langchain.prompts import PromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class MultiPromptChain(MultiRouteChain):\n    \"\"\"A multi-route chain that uses an LLM router chain to choose amongst prompts.\"\"\"\n    @property\n    def output_keys(self) -> List[str]:\n        return [\"text\"]\n[docs]    @classmethod\n    def from_prompts(\n        cls,\n        llm: BaseLanguageModel,\n        prompt_infos: List[Dict[str, str]],\n        default_chain: Optional[Chain] = None,\n        **kwargs: Any,\n    ) -> MultiPromptChain:\n        \"\"\"Convenience constructor for instantiating from destination prompts.\"\"\"\n        destinations = [f\"{p['name']}: {p['description']}\" for p in prompt_infos]\n        destinations_str = \"\\n\".join(destinations)\n        router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(\n            destinations=destinations_str\n        )\n        router_prompt = PromptTemplate(\n            template=router_template,\n            input_variables=[\"input\"],\n            output_parser=RouterOutputParser(),\n        )\n        router_chain = LLMRouterChain.from_llm(llm, router_prompt)\n        destination_chains = {}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_prompt.html"}
{"id": "8a5bba9cfe17-1", "text": "destination_chains = {}\n        for p_info in prompt_infos:\n            name = p_info[\"name\"]\n            prompt_template = p_info[\"prompt_template\"]\n            prompt = PromptTemplate(template=prompt_template, input_variables=[\"input\"])\n            chain = LLMChain(llm=llm, prompt=prompt)\n            destination_chains[name] = chain\n        _default_chain = default_chain or ConversationChain(llm=llm, output_key=\"text\")\n        return cls(\n            router_chain=router_chain,\n            destination_chains=destination_chains,\n            default_chain=_default_chain,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_prompt.html"}
{"id": "41192c30ff56-0", "text": "Source code for langchain.chains.router.base\n\"\"\"Base classes for chain routing.\"\"\"\nfrom __future__ import annotations\nfrom abc import ABC\nfrom typing import Any, Dict, List, Mapping, NamedTuple, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n    Callbacks,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.pydantic_v1 import Extra\n[docs]class Route(NamedTuple):\n    destination: Optional[str]\n    next_inputs: Dict[str, Any]\n[docs]class RouterChain(Chain, ABC):\n    \"\"\"Chain that outputs the name of a destination chain and the inputs to it.\"\"\"\n    @property\n    def output_keys(self) -> List[str]:\n        return [\"destination\", \"next_inputs\"]\n[docs]    def route(self, inputs: Dict[str, Any], callbacks: Callbacks = None) -> Route:\n        \"\"\"\n        Route inputs to a destination chain.\n        Args:\n            inputs: inputs to the chain\n            callbacks: callbacks to use for the chain\n        Returns:\n            a Route object\n        \"\"\"\n        result = self(inputs, callbacks=callbacks)\n        return Route(result[\"destination\"], result[\"next_inputs\"])\n[docs]    async def aroute(\n        self, inputs: Dict[str, Any], callbacks: Callbacks = None\n    ) -> Route:\n        result = await self.acall(inputs, callbacks=callbacks)\n        return Route(result[\"destination\"], result[\"next_inputs\"])\n[docs]class MultiRouteChain(Chain):\n    \"\"\"Use a single chain to route an input to one of multiple candidate chains.\"\"\"\n    router_chain: RouterChain\n    \"\"\"Chain that routes inputs to destination chains.\"\"\"\n    destination_chains: Mapping[str, Chain]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/router/base.html"}
{"id": "41192c30ff56-1", "text": "destination_chains: Mapping[str, Chain]\n    \"\"\"Chains that return final answer to inputs.\"\"\"\n    default_chain: Chain\n    \"\"\"Default chain to use when none of the destination chains are suitable.\"\"\"\n    silent_errors: bool = False\n    \"\"\"If True, use default_chain when an invalid destination name is provided. \n    Defaults to False.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Will be whatever keys the router chain prompt expects.\n        :meta private:\n        \"\"\"\n        return self.router_chain.input_keys\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Will always return text key.\n        :meta private:\n        \"\"\"\n        return []\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        route = self.router_chain.route(inputs, callbacks=callbacks)\n        _run_manager.on_text(\n            str(route.destination) + \": \" + str(route.next_inputs), verbose=self.verbose\n        )\n        if not route.destination:\n            return self.default_chain(route.next_inputs, callbacks=callbacks)\n        elif route.destination in self.destination_chains:\n            return self.destination_chains[route.destination](\n                route.next_inputs, callbacks=callbacks\n            )\n        elif self.silent_errors:\n            return self.default_chain(route.next_inputs, callbacks=callbacks)\n        else:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/router/base.html"}
{"id": "41192c30ff56-2", "text": "else:\n            raise ValueError(\n                f\"Received invalid destination chain name '{route.destination}'\"\n            )\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        route = await self.router_chain.aroute(inputs, callbacks=callbacks)\n        await _run_manager.on_text(\n            str(route.destination) + \": \" + str(route.next_inputs), verbose=self.verbose\n        )\n        if not route.destination:\n            return await self.default_chain.acall(\n                route.next_inputs, callbacks=callbacks\n            )\n        elif route.destination in self.destination_chains:\n            return await self.destination_chains[route.destination].acall(\n                route.next_inputs, callbacks=callbacks\n            )\n        elif self.silent_errors:\n            return await self.default_chain.acall(\n                route.next_inputs, callbacks=callbacks\n            )\n        else:\n            raise ValueError(\n                f\"Received invalid destination chain name '{route.destination}'\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/router/base.html"}
{"id": "1df5e7648768-0", "text": "Source code for langchain.chains.router.multi_retrieval_qa\n\"\"\"Use a single chain to route an input to one of multiple retrieval qa chains.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.chains import ConversationChain\nfrom langchain.chains.base import Chain\nfrom langchain.chains.conversation.prompt import DEFAULT_TEMPLATE\nfrom langchain.chains.retrieval_qa.base import BaseRetrievalQA, RetrievalQA\nfrom langchain.chains.router.base import MultiRouteChain\nfrom langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser\nfrom langchain.chains.router.multi_retrieval_prompt import (\n    MULTI_RETRIEVAL_ROUTER_TEMPLATE,\n)\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.prompts import PromptTemplate\nfrom langchain.schema import BaseRetriever\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class MultiRetrievalQAChain(MultiRouteChain):\n    \"\"\"A multi-route chain that uses an LLM router chain to choose amongst retrieval\n    qa chains.\"\"\"\n    router_chain: LLMRouterChain\n    \"\"\"Chain for deciding a destination chain and the input to it.\"\"\"\n    destination_chains: Mapping[str, BaseRetrievalQA]\n    \"\"\"Map of name to candidate chains that inputs can be routed to.\"\"\"\n    default_chain: Chain\n    \"\"\"Default chain to use when router doesn't map input to one of the destinations.\"\"\"\n    @property\n    def output_keys(self) -> List[str]:\n        return [\"result\"]\n[docs]    @classmethod\n    def from_retrievers(\n        cls,\n        llm: BaseLanguageModel,\n        retriever_infos: List[Dict[str, Any]],\n        default_retriever: Optional[BaseRetriever] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_retrieval_qa.html"}
{"id": "1df5e7648768-1", "text": "default_retriever: Optional[BaseRetriever] = None,\n        default_prompt: Optional[PromptTemplate] = None,\n        default_chain: Optional[Chain] = None,\n        **kwargs: Any,\n    ) -> MultiRetrievalQAChain:\n        if default_prompt and not default_retriever:\n            raise ValueError(\n                \"`default_retriever` must be specified if `default_prompt` is \"\n                \"provided. Received only `default_prompt`.\"\n            )\n        destinations = [f\"{r['name']}: {r['description']}\" for r in retriever_infos]\n        destinations_str = \"\\n\".join(destinations)\n        router_template = MULTI_RETRIEVAL_ROUTER_TEMPLATE.format(\n            destinations=destinations_str\n        )\n        router_prompt = PromptTemplate(\n            template=router_template,\n            input_variables=[\"input\"],\n            output_parser=RouterOutputParser(next_inputs_inner_key=\"query\"),\n        )\n        router_chain = LLMRouterChain.from_llm(llm, router_prompt)\n        destination_chains = {}\n        for r_info in retriever_infos:\n            prompt = r_info.get(\"prompt\")\n            retriever = r_info[\"retriever\"]\n            chain = RetrievalQA.from_llm(llm, prompt=prompt, retriever=retriever)\n            name = r_info[\"name\"]\n            destination_chains[name] = chain\n        if default_chain:\n            _default_chain = default_chain\n        elif default_retriever:\n            _default_chain = RetrievalQA.from_llm(\n                llm, prompt=default_prompt, retriever=default_retriever\n            )\n        else:\n            prompt_template = DEFAULT_TEMPLATE.replace(\"input\", \"query\")\n            prompt = PromptTemplate(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_retrieval_qa.html"}
{"id": "1df5e7648768-2", "text": "prompt = PromptTemplate(\n                template=prompt_template, input_variables=[\"history\", \"query\"]\n            )\n            _default_chain = ConversationChain(\n                llm=ChatOpenAI(), prompt=prompt, input_key=\"query\", output_key=\"result\"\n            )\n        return cls(\n            router_chain=router_chain,\n            destination_chains=destination_chains,\n            default_chain=_default_chain,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_retrieval_qa.html"}
{"id": "297caacedd83-0", "text": "Source code for langchain.chains.router.llm_router\n\"\"\"Base classes for LLM-powered router chains.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional, Type, cast\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains import LLMChain\nfrom langchain.chains.router.base import RouterChain\nfrom langchain.output_parsers.json import parse_and_check_json_markdown\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import BaseOutputParser, BasePromptTemplate, OutputParserException\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class LLMRouterChain(RouterChain):\n    \"\"\"A router chain that uses an LLM chain to perform routing.\"\"\"\n    llm_chain: LLMChain\n    \"\"\"LLM chain used to perform routing\"\"\"\n    @root_validator()\n    def validate_prompt(cls, values: dict) -> dict:\n        prompt = values[\"llm_chain\"].prompt\n        if prompt.output_parser is None:\n            raise ValueError(\n                \"LLMRouterChain requires base llm_chain prompt to have an output\"\n                \" parser that converts LLM text output to a dictionary with keys\"\n                \" 'destination' and 'next_inputs'. Received a prompt with no output\"\n                \" parser.\"\n            )\n        return values\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Will be whatever keys the LLM chain prompt expects.\n        :meta private:\n        \"\"\"\n        return self.llm_chain.input_keys\n    def _validate_outputs(self, outputs: Dict[str, Any]) -> None:\n        super()._validate_outputs(outputs)\n        if not isinstance(outputs[\"next_inputs\"], dict):\n            raise ValueError\n    def _call(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/router/llm_router.html"}
{"id": "297caacedd83-1", "text": "raise ValueError\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        output = cast(\n            Dict[str, Any],\n            self.llm_chain.predict_and_parse(callbacks=callbacks, **inputs),\n        )\n        return output\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        output = cast(\n            Dict[str, Any],\n            await self.llm_chain.apredict_and_parse(callbacks=callbacks, **inputs),\n        )\n        return output\n[docs]    @classmethod\n    def from_llm(\n        cls, llm: BaseLanguageModel, prompt: BasePromptTemplate, **kwargs: Any\n    ) -> LLMRouterChain:\n        \"\"\"Convenience constructor.\"\"\"\n        llm_chain = LLMChain(llm=llm, prompt=prompt)\n        return cls(llm_chain=llm_chain, **kwargs)\n[docs]class RouterOutputParser(BaseOutputParser[Dict[str, str]]):\n    \"\"\"Parser for output of router chain in the multi-prompt chain.\"\"\"\n    default_destination: str = \"DEFAULT\"\n    next_inputs_type: Type = str\n    next_inputs_inner_key: str = \"input\"\n[docs]    def parse(self, text: str) -> Dict[str, Any]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/router/llm_router.html"}
{"id": "297caacedd83-2", "text": "[docs]    def parse(self, text: str) -> Dict[str, Any]:\n        try:\n            expected_keys = [\"destination\", \"next_inputs\"]\n            parsed = parse_and_check_json_markdown(text, expected_keys)\n            if not isinstance(parsed[\"destination\"], str):\n                raise ValueError(\"Expected 'destination' to be a string.\")\n            if not isinstance(parsed[\"next_inputs\"], self.next_inputs_type):\n                raise ValueError(\n                    f\"Expected 'next_inputs' to be {self.next_inputs_type}.\"\n                )\n            parsed[\"next_inputs\"] = {self.next_inputs_inner_key: parsed[\"next_inputs\"]}\n            if (\n                parsed[\"destination\"].strip().lower()\n                == self.default_destination.lower()\n            ):\n                parsed[\"destination\"] = None\n            else:\n                parsed[\"destination\"] = parsed[\"destination\"].strip()\n            return parsed\n        except Exception as e:\n            raise OutputParserException(\n                f\"Parsing text\\n{text}\\n raised following error:\\n{e}\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/router/llm_router.html"}
{"id": "da97f556e112-0", "text": "Source code for langchain.chains.router.embedding_router\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Type\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.router.base import RouterChain\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import Extra\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\n[docs]class EmbeddingRouterChain(RouterChain):\n    \"\"\"Chain that uses embeddings to route between options.\"\"\"\n    vectorstore: VectorStore\n    routing_keys: List[str] = [\"query\"]\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Will be whatever keys the LLM chain prompt expects.\n        :meta private:\n        \"\"\"\n        return self.routing_keys\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _input = \", \".join([inputs[k] for k in self.routing_keys])\n        results = self.vectorstore.similarity_search(_input, k=1)\n        return {\"next_inputs\": inputs, \"destination\": results[0].metadata[\"name\"]}\n[docs]    @classmethod\n    def from_names_and_descriptions(\n        cls,\n        names_and_descriptions: Sequence[Tuple[str, Sequence[str]]],\n        vectorstore_cls: Type[VectorStore],\n        embeddings: Embeddings,\n        **kwargs: Any,\n    ) -> EmbeddingRouterChain:\n        \"\"\"Convenience constructor.\"\"\"\n        documents = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/router/embedding_router.html"}
{"id": "da97f556e112-1", "text": "\"\"\"Convenience constructor.\"\"\"\n        documents = []\n        for name, descriptions in names_and_descriptions:\n            for description in descriptions:\n                documents.append(\n                    Document(page_content=description, metadata={\"name\": name})\n                )\n        vectorstore = vectorstore_cls.from_documents(documents, embeddings)\n        return cls(vectorstore=vectorstore, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/router/embedding_router.html"}
{"id": "e4a77c41e8a8-0", "text": "Source code for langchain.chains.query_constructor.schema\nfrom langchain.pydantic_v1 import BaseModel\n[docs]class AttributeInfo(BaseModel):\n    \"\"\"Information about a data source attribute.\"\"\"\n    name: str\n    description: str\n    type: str\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n        frozen = True", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/schema.html"}
{"id": "15562f57066a-0", "text": "Source code for langchain.chains.query_constructor.base\n\"\"\"LLM Chain for turning a user text query into a structured query.\"\"\"\nfrom __future__ import annotations\nimport json\nfrom typing import Any, Callable, List, Optional, Sequence, Tuple, Union, cast\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    FilterDirective,\n    Operation,\n    Operator,\n    StructuredQuery,\n)\nfrom langchain.chains.query_constructor.parser import get_parser\nfrom langchain.chains.query_constructor.prompt import (\n    DEFAULT_EXAMPLES,\n    DEFAULT_PREFIX,\n    DEFAULT_SCHEMA_PROMPT,\n    DEFAULT_SUFFIX,\n    EXAMPLE_PROMPT,\n    EXAMPLES_WITH_LIMIT,\n    PREFIX_WITH_DATA_SOURCE,\n    SCHEMA_WITH_LIMIT_PROMPT,\n    SUFFIX_WITHOUT_DATA_SOURCE,\n    USER_SPECIFIED_EXAMPLE_PROMPT,\n)\nfrom langchain.chains.query_constructor.schema import AttributeInfo\nfrom langchain.output_parsers.json import parse_and_check_json_markdown\nfrom langchain.prompts.few_shot import FewShotPromptTemplate\nfrom langchain.schema import BaseOutputParser, BasePromptTemplate, OutputParserException\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.runnable import Runnable\n[docs]class StructuredQueryOutputParser(BaseOutputParser[StructuredQuery]):\n    \"\"\"Output parser that parses a structured query.\"\"\"\n    ast_parse: Callable\n    \"\"\"Callable that parses dict into internal representation of query language.\"\"\"\n[docs]    def parse(self, text: str) -> StructuredQuery:\n        try:\n            expected_keys = [\"query\", \"filter\"]\n            allowed_keys = [\"query\", \"filter\", \"limit\"]\n            parsed = parse_and_check_json_markdown(text, expected_keys)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/base.html"}
{"id": "15562f57066a-1", "text": "parsed = parse_and_check_json_markdown(text, expected_keys)\n            if len(parsed[\"query\"]) == 0:\n                parsed[\"query\"] = \" \"\n            if parsed[\"filter\"] == \"NO_FILTER\" or not parsed[\"filter\"]:\n                parsed[\"filter\"] = None\n            else:\n                parsed[\"filter\"] = self.ast_parse(parsed[\"filter\"])\n            if not parsed.get(\"limit\"):\n                parsed.pop(\"limit\", None)\n            return StructuredQuery(\n                **{k: v for k, v in parsed.items() if k in allowed_keys}\n            )\n        except Exception as e:\n            raise OutputParserException(\n                f\"Parsing text\\n{text}\\n raised following error:\\n{e}\"\n            )\n[docs]    @classmethod\n    def from_components(\n        cls,\n        allowed_comparators: Optional[Sequence[Comparator]] = None,\n        allowed_operators: Optional[Sequence[Operator]] = None,\n        allowed_attributes: Optional[Sequence[str]] = None,\n        fix_invalid: bool = False,\n    ) -> StructuredQueryOutputParser:\n        \"\"\"\n        Create a structured query output parser from components.\n        Args:\n            allowed_comparators: allowed comparators\n            allowed_operators: allowed operators\n        Returns:\n            a structured query output parser\n        \"\"\"\n        ast_parse: Callable\n        if fix_invalid:\n            def ast_parse(raw_filter: str) -> Optional[FilterDirective]:\n                filter = cast(Optional[FilterDirective], get_parser().parse(raw_filter))\n                fixed = fix_filter_directive(\n                    filter,\n                    allowed_comparators=allowed_comparators,\n                    allowed_operators=allowed_operators,\n                    allowed_attributes=allowed_attributes,\n                )\n                return fixed\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/base.html"}
{"id": "15562f57066a-2", "text": "allowed_attributes=allowed_attributes,\n                )\n                return fixed\n        else:\n            ast_parse = get_parser(\n                allowed_comparators=allowed_comparators,\n                allowed_operators=allowed_operators,\n                allowed_attributes=allowed_attributes,\n            ).parse\n        return cls(ast_parse=ast_parse)\n[docs]def fix_filter_directive(\n    filter: Optional[FilterDirective],\n    *,\n    allowed_comparators: Optional[Sequence[Comparator]] = None,\n    allowed_operators: Optional[Sequence[Operator]] = None,\n    allowed_attributes: Optional[Sequence[str]] = None,\n) -> Optional[FilterDirective]:\n    \"\"\"Fix invalid filter directive.\n    Args:\n        filter: Filter directive to fix.\n        allowed_comparators: allowed comparators. Defaults to all comparators.\n        allowed_operators: allowed operators. Defaults to all operators.\n        allowed_attributes: allowed attributes. Defaults to all attributes.\n    Returns:\n        Fixed filter directive.\n    \"\"\"\n    if (\n        not (allowed_comparators or allowed_operators or allowed_attributes)\n    ) or not filter:\n        return filter\n    elif isinstance(filter, Comparison):\n        if allowed_comparators and filter.comparator not in allowed_comparators:\n            return None\n        if allowed_attributes and filter.attribute not in allowed_attributes:\n            return None\n        return filter\n    elif isinstance(filter, Operation):\n        if allowed_operators and filter.operator not in allowed_operators:\n            return None\n        args = [\n            fix_filter_directive(\n                arg,\n                allowed_comparators=allowed_comparators,\n                allowed_operators=allowed_operators,\n                allowed_attributes=allowed_attributes,\n            )\n            for arg in filter.arguments\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/base.html"}
{"id": "15562f57066a-3", "text": ")\n            for arg in filter.arguments\n        ]\n        args = [arg for arg in args if arg is not None]\n        if not args:\n            return None\n        elif len(args) == 1 and filter.operator in (Operator.AND, Operator.OR):\n            return args[0]\n        else:\n            return Operation(\n                operator=filter.operator,\n                arguments=args,\n            )\n    else:\n        return filter\ndef _format_attribute_info(info: Sequence[Union[AttributeInfo, dict]]) -> str:\n    info_dicts = {}\n    for i in info:\n        i_dict = dict(i)\n        info_dicts[i_dict.pop(\"name\")] = i_dict\n    return json.dumps(info_dicts, indent=4).replace(\"{\", \"{{\").replace(\"}\", \"}}\")\n[docs]def construct_examples(input_output_pairs: Sequence[Tuple[str, dict]]) -> List[dict]:\n    \"\"\"Construct examples from input-output pairs.\n    Args:\n        input_output_pairs: Sequence of input-output pairs.\n    Returns:\n        List of examples.\n    \"\"\"\n    examples = []\n    for i, (_input, output) in enumerate(input_output_pairs):\n        structured_request = (\n            json.dumps(output, indent=4).replace(\"{\", \"{{\").replace(\"}\", \"}}\")\n        )\n        example = {\n            \"i\": i + 1,\n            \"user_query\": _input,\n            \"structured_request\": structured_request,\n        }\n        examples.append(example)\n    return examples\n[docs]def get_query_constructor_prompt(\n    document_contents: str,\n    attribute_info: Sequence[Union[AttributeInfo, dict]],\n    *,\n    examples: Optional[Sequence] = None,\n    allowed_comparators: Sequence[Comparator] = tuple(Comparator),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/base.html"}
{"id": "15562f57066a-4", "text": "allowed_comparators: Sequence[Comparator] = tuple(Comparator),\n    allowed_operators: Sequence[Operator] = tuple(Operator),\n    enable_limit: bool = False,\n    schema_prompt: Optional[BasePromptTemplate] = None,\n    **kwargs: Any,\n) -> BasePromptTemplate:\n    \"\"\"Create query construction prompt.\n    Args:\n        document_contents: The contents of the document to be queried.\n        attribute_info: A list of AttributeInfo objects describing\n            the attributes of the document.\n        examples: Optional list of examples to use for the chain.\n        allowed_comparators: Sequence of allowed comparators.\n        allowed_operators: Sequence of allowed operators.\n        enable_limit: Whether to enable the limit operator. Defaults to False.\n        schema_prompt: Prompt for describing query schema. Should have string input\n            variables allowed_comparators and allowed_operators.\n        **kwargs: Additional named params to pass to FewShotPromptTemplate init.\n    Returns:\n        A prompt template that can be used to construct queries.\n    \"\"\"\n    default_schema_prompt = (\n        SCHEMA_WITH_LIMIT_PROMPT if enable_limit else DEFAULT_SCHEMA_PROMPT\n    )\n    schema_prompt = schema_prompt or default_schema_prompt\n    attribute_str = _format_attribute_info(attribute_info)\n    schema = schema_prompt.format(\n        allowed_comparators=\" | \".join(allowed_comparators),\n        allowed_operators=\" | \".join(allowed_operators),\n    )\n    if examples and isinstance(examples[0], tuple):\n        examples = construct_examples(examples)\n        example_prompt = USER_SPECIFIED_EXAMPLE_PROMPT\n        prefix = PREFIX_WITH_DATA_SOURCE.format(\n            schema=schema, content=document_contents, attributes=attribute_str\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/base.html"}
{"id": "15562f57066a-5", "text": "schema=schema, content=document_contents, attributes=attribute_str\n        )\n        suffix = SUFFIX_WITHOUT_DATA_SOURCE.format(i=len(examples) + 1)\n    else:\n        examples = examples or (\n            EXAMPLES_WITH_LIMIT if enable_limit else DEFAULT_EXAMPLES\n        )\n        example_prompt = EXAMPLE_PROMPT\n        prefix = DEFAULT_PREFIX.format(schema=schema)\n        suffix = DEFAULT_SUFFIX.format(\n            i=len(examples) + 1, content=document_contents, attributes=attribute_str\n        )\n    return FewShotPromptTemplate(\n        examples=list(examples),\n        example_prompt=example_prompt,\n        input_variables=[\"query\"],\n        suffix=suffix,\n        prefix=prefix,\n        **kwargs,\n    )\n[docs]def load_query_constructor_chain(\n    llm: BaseLanguageModel,\n    document_contents: str,\n    attribute_info: Sequence[Union[AttributeInfo, dict]],\n    examples: Optional[List] = None,\n    allowed_comparators: Sequence[Comparator] = tuple(Comparator),\n    allowed_operators: Sequence[Operator] = tuple(Operator),\n    enable_limit: bool = False,\n    schema_prompt: Optional[BasePromptTemplate] = None,\n    **kwargs: Any,\n) -> LLMChain:\n    \"\"\"Load a query constructor chain.\n    Args:\n        llm: BaseLanguageModel to use for the chain.\n        document_contents: The contents of the document to be queried.\n        attribute_info: Sequence of attributes in the document.\n        examples: Optional list of examples to use for the chain.\n        allowed_comparators: Sequence of allowed comparators. Defaults to all\n            Comparators.\n        allowed_operators: Sequence of allowed operators. Defaults to all Operators.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/base.html"}
{"id": "15562f57066a-6", "text": "allowed_operators: Sequence of allowed operators. Defaults to all Operators.\n        enable_limit: Whether to enable the limit operator. Defaults to False.\n        schema_prompt: Prompt for describing query schema. Should have string input\n            variables allowed_comparators and allowed_operators.\n        **kwargs: Arbitrary named params to pass to LLMChain.\n    Returns:\n        A LLMChain that can be used to construct queries.\n    \"\"\"\n    prompt = get_query_constructor_prompt(\n        document_contents,\n        attribute_info,\n        examples=examples,\n        allowed_comparators=allowed_comparators,\n        allowed_operators=allowed_operators,\n        enable_limit=enable_limit,\n        schema_prompt=schema_prompt,\n    )\n    allowed_attributes = []\n    for ainfo in attribute_info:\n        allowed_attributes.append(\n            ainfo.name if isinstance(ainfo, AttributeInfo) else ainfo[\"name\"]\n        )\n    output_parser = StructuredQueryOutputParser.from_components(\n        allowed_comparators=allowed_comparators,\n        allowed_operators=allowed_operators,\n        allowed_attributes=allowed_attributes,\n    )\n    # For backwards compatibility.\n    prompt.output_parser = output_parser\n    return LLMChain(llm=llm, prompt=prompt, output_parser=output_parser, **kwargs)\n[docs]def load_query_constructor_runnable(\n    llm: BaseLanguageModel,\n    document_contents: str,\n    attribute_info: Sequence[Union[AttributeInfo, dict]],\n    *,\n    examples: Optional[Sequence] = None,\n    allowed_comparators: Sequence[Comparator] = tuple(Comparator),\n    allowed_operators: Sequence[Operator] = tuple(Operator),\n    enable_limit: bool = False,\n    schema_prompt: Optional[BasePromptTemplate] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/base.html"}
{"id": "15562f57066a-7", "text": "schema_prompt: Optional[BasePromptTemplate] = None,\n    fix_invalid: bool = False,\n    **kwargs: Any,\n) -> Runnable:\n    \"\"\"Load a query constructor runnable chain.\n    Args:\n        llm: BaseLanguageModel to use for the chain.\n        document_contents: The contents of the document to be queried.\n        attribute_info: Sequence of attributes in the document.\n        examples: Optional list of examples to use for the chain.\n        allowed_comparators: Sequence of allowed comparators. Defaults to all\n            Comparators.\n        allowed_operators: Sequence of allowed operators. Defaults to all Operators.\n        enable_limit: Whether to enable the limit operator. Defaults to False.\n        schema_prompt: Prompt for describing query schema. Should have string input\n            variables allowed_comparators and allowed_operators.\n        fix_invalid: Whether to fix invalid filter directives by ignoring invalid\n            operators, comparators and attributes.\n        **kwargs: Additional named params to pass to FewShotPromptTemplate init.\n    Returns:\n        A Runnable that can be used to construct queries.\n    \"\"\"\n    prompt = get_query_constructor_prompt(\n        document_contents,\n        attribute_info,\n        examples=examples,\n        allowed_comparators=allowed_comparators,\n        allowed_operators=allowed_operators,\n        enable_limit=enable_limit,\n        schema_prompt=schema_prompt,\n        **kwargs,\n    )\n    allowed_attributes = []\n    for ainfo in attribute_info:\n        allowed_attributes.append(\n            ainfo.name if isinstance(ainfo, AttributeInfo) else ainfo[\"name\"]\n        )\n    output_parser = StructuredQueryOutputParser.from_components(\n        allowed_comparators=allowed_comparators,\n        allowed_operators=allowed_operators,\n        allowed_attributes=allowed_attributes,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/base.html"}
{"id": "15562f57066a-8", "text": "allowed_operators=allowed_operators,\n        allowed_attributes=allowed_attributes,\n        fix_invalid=fix_invalid,\n    )\n    return prompt | llm | output_parser", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/base.html"}
{"id": "067c9d2ec823-0", "text": "Source code for langchain.chains.query_constructor.ir\n\"\"\"Internal representation of a structured query language.\"\"\"\nfrom __future__ import annotations\nfrom abc import ABC, abstractmethod\nfrom enum import Enum\nfrom typing import Any, List, Optional, Sequence, Union\nfrom langchain.pydantic_v1 import BaseModel\n[docs]class Visitor(ABC):\n    \"\"\"Defines interface for IR translation using visitor pattern.\"\"\"\n    allowed_comparators: Optional[Sequence[Comparator]] = None\n    allowed_operators: Optional[Sequence[Operator]] = None\n    def _validate_func(self, func: Union[Operator, Comparator]) -> None:\n        if isinstance(func, Operator) and self.allowed_operators is not None:\n            if func not in self.allowed_operators:\n                raise ValueError(\n                    f\"Received disallowed operator {func}. Allowed \"\n                    f\"comparators are {self.allowed_operators}\"\n                )\n        if isinstance(func, Comparator) and self.allowed_comparators is not None:\n            if func not in self.allowed_comparators:\n                raise ValueError(\n                    f\"Received disallowed comparator {func}. Allowed \"\n                    f\"comparators are {self.allowed_comparators}\"\n                )\n[docs]    @abstractmethod\n    def visit_operation(self, operation: Operation) -> Any:\n        \"\"\"Translate an Operation.\"\"\"\n[docs]    @abstractmethod\n    def visit_comparison(self, comparison: Comparison) -> Any:\n        \"\"\"Translate a Comparison.\"\"\"\n[docs]    @abstractmethod\n    def visit_structured_query(self, structured_query: StructuredQuery) -> Any:\n        \"\"\"Translate a StructuredQuery.\"\"\"\ndef _to_snake_case(name: str) -> str:\n    \"\"\"Convert a name into snake_case.\"\"\"\n    snake_case = \"\"\n    for i, char in enumerate(name):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/ir.html"}
{"id": "067c9d2ec823-1", "text": "snake_case = \"\"\n    for i, char in enumerate(name):\n        if char.isupper() and i != 0:\n            snake_case += \"_\" + char.lower()\n        else:\n            snake_case += char.lower()\n    return snake_case\n[docs]class Expr(BaseModel):\n    \"\"\"Base class for all expressions.\"\"\"\n[docs]    def accept(self, visitor: Visitor) -> Any:\n        \"\"\"Accept a visitor.\n        Args:\n            visitor: visitor to accept\n        Returns:\n            result of visiting\n        \"\"\"\n        return getattr(visitor, f\"visit_{_to_snake_case(self.__class__.__name__)}\")(\n            self\n        )\n[docs]class Operator(str, Enum):\n    \"\"\"Enumerator of the operations.\"\"\"\n    AND = \"and\"\n    OR = \"or\"\n    NOT = \"not\"\n[docs]class Comparator(str, Enum):\n    \"\"\"Enumerator of the comparison operators.\"\"\"\n    EQ = \"eq\"\n    NE = \"ne\"\n    GT = \"gt\"\n    GTE = \"gte\"\n    LT = \"lt\"\n    LTE = \"lte\"\n    CONTAIN = \"contain\"\n    LIKE = \"like\"\n    IN = \"in\"\n    NIN = \"nin\"\n[docs]class FilterDirective(Expr, ABC):\n    \"\"\"A filtering expression.\"\"\"\n[docs]class Comparison(FilterDirective):\n    \"\"\"A comparison to a value.\"\"\"\n    comparator: Comparator\n    attribute: str\n    value: Any\n[docs]class Operation(FilterDirective):\n    \"\"\"A logical operation over other directives.\"\"\"\n    operator: Operator\n    arguments: List[FilterDirective]\n[docs]class StructuredQuery(Expr):\n    \"\"\"A structured query.\"\"\"\n    query: str\n    \"\"\"Query string.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/ir.html"}
{"id": "067c9d2ec823-2", "text": "\"\"\"A structured query.\"\"\"\n    query: str\n    \"\"\"Query string.\"\"\"\n    filter: Optional[FilterDirective]\n    \"\"\"Filtering expression.\"\"\"\n    limit: Optional[int]\n    \"\"\"Limit on the number of results.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/ir.html"}
{"id": "5d9c74164a1e-0", "text": "Source code for langchain.chains.query_constructor.parser\nimport datetime\nimport warnings\nfrom typing import Any, Literal, Optional, Sequence, Union\nfrom typing_extensions import TypedDict\nfrom langchain.utils import check_package_version\ntry:\n    check_package_version(\"lark\", gte_version=\"1.1.5\")\n    from lark import Lark, Transformer, v_args\nexcept ImportError:\n[docs]    def v_args(*args: Any, **kwargs: Any) -> Any:  # type: ignore\n        \"\"\"Dummy decorator for when lark is not installed.\"\"\"\n        return lambda _: None\n    Transformer = object  # type: ignore\n    Lark = object  # type: ignore\nfrom langchain.chains.query_constructor.ir import (\n    Comparator,\n    Comparison,\n    FilterDirective,\n    Operation,\n    Operator,\n)\nGRAMMAR = r\"\"\"\n    ?program: func_call\n    ?expr: func_call\n        | value\n    func_call: CNAME \"(\" [args] \")\"\n    ?value: SIGNED_INT -> int\n        | SIGNED_FLOAT -> float\n        | DATE -> date\n        | list\n        | string\n        | (\"false\" | \"False\" | \"FALSE\") -> false\n        | (\"true\" | \"True\" | \"TRUE\") -> true\n    args: expr (\",\" expr)*\n    DATE.2: /[\"']?(\\d{4}-[01]\\d-[0-3]\\d)[\"']?/\n    string: /'[^']*'/ | ESCAPED_STRING\n    list: \"[\" [args] \"]\"\n    %import common.CNAME\n    %import common.ESCAPED_STRING\n    %import common.SIGNED_FLOAT\n    %import common.SIGNED_INT\n    %import common.WS\n    %ignore WS\n\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/parser.html"}
{"id": "5d9c74164a1e-1", "text": "%import common.WS\n    %ignore WS\n\"\"\"\n[docs]class ISO8601Date(TypedDict):\n    \"\"\"A date in ISO 8601 format (YYYY-MM-DD).\"\"\"\n    date: str\n    type: Literal[\"date\"]\n@v_args(inline=True)\nclass QueryTransformer(Transformer):\n    \"\"\"Transforms a query string into an intermediate representation.\"\"\"\n    def __init__(\n        self,\n        *args: Any,\n        allowed_comparators: Optional[Sequence[Comparator]] = None,\n        allowed_operators: Optional[Sequence[Operator]] = None,\n        allowed_attributes: Optional[Sequence[str]] = None,\n        **kwargs: Any,\n    ):\n        super().__init__(*args, **kwargs)\n        self.allowed_comparators = allowed_comparators\n        self.allowed_operators = allowed_operators\n        self.allowed_attributes = allowed_attributes\n    def program(self, *items: Any) -> tuple:\n        return items\n    def func_call(self, func_name: Any, args: list) -> FilterDirective:\n        func = self._match_func_name(str(func_name))\n        if isinstance(func, Comparator):\n            if self.allowed_attributes and args[0] not in self.allowed_attributes:\n                raise ValueError(\n                    f\"Received invalid attributes {args[0]}. Allowed attributes are \"\n                    f\"{self.allowed_attributes}\"\n                )\n            return Comparison(comparator=func, attribute=args[0], value=args[1])\n        elif len(args) == 1 and func in (Operator.AND, Operator.OR):\n            return args[0]\n        else:\n            return Operation(operator=func, arguments=args)\n    def _match_func_name(self, func_name: str) -> Union[Operator, Comparator]:\n        if func_name in set(Comparator):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/parser.html"}
{"id": "5d9c74164a1e-2", "text": "if func_name in set(Comparator):\n            if self.allowed_comparators is not None:\n                if func_name not in self.allowed_comparators:\n                    raise ValueError(\n                        f\"Received disallowed comparator {func_name}. Allowed \"\n                        f\"comparators are {self.allowed_comparators}\"\n                    )\n            return Comparator(func_name)\n        elif func_name in set(Operator):\n            if self.allowed_operators is not None:\n                if func_name not in self.allowed_operators:\n                    raise ValueError(\n                        f\"Received disallowed operator {func_name}. Allowed operators\"\n                        f\" are {self.allowed_operators}\"\n                    )\n            return Operator(func_name)\n        else:\n            raise ValueError(\n                f\"Received unrecognized function {func_name}. Valid functions are \"\n                f\"{list(Operator) + list(Comparator)}\"\n            )\n    def args(self, *items: Any) -> tuple:\n        return items\n    def false(self) -> bool:\n        return False\n    def true(self) -> bool:\n        return True\n    def list(self, item: Any) -> list:\n        if item is None:\n            return []\n        return list(item)\n    def int(self, item: Any) -> int:\n        return int(item)\n    def float(self, item: Any) -> float:\n        return float(item)\n    def date(self, item: Any) -> ISO8601Date:\n        item = str(item).strip(\"\\\"'\")\n        try:\n            datetime.datetime.strptime(item, \"%Y-%m-%d\")\n        except ValueError:\n            warnings.warn(\n                \"Dates are expected to be provided in ISO 8601 date format \"\n                \"(YYYY-MM-DD).\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/parser.html"}
{"id": "5d9c74164a1e-3", "text": "\"(YYYY-MM-DD).\"\n            )\n        return {\"date\": item, \"type\": \"date\"}\n    def string(self, item: Any) -> str:\n        # Remove escaped quotes\n        return str(item).strip(\"\\\"'\")\n[docs]def get_parser(\n    allowed_comparators: Optional[Sequence[Comparator]] = None,\n    allowed_operators: Optional[Sequence[Operator]] = None,\n    allowed_attributes: Optional[Sequence[str]] = None,\n) -> Lark:\n    \"\"\"\n    Returns a parser for the query language.\n    Args:\n        allowed_comparators: Optional[Sequence[Comparator]]\n        allowed_operators: Optional[Sequence[Operator]]\n    Returns:\n        Lark parser for the query language.\n    \"\"\"\n    # QueryTransformer is None when Lark cannot be imported.\n    if QueryTransformer is None:\n        raise ImportError(\n            \"Cannot import lark, please install it with 'pip install lark'.\"\n        )\n    transformer = QueryTransformer(\n        allowed_comparators=allowed_comparators,\n        allowed_operators=allowed_operators,\n        allowed_attributes=allowed_attributes,\n    )\n    return Lark(GRAMMAR, parser=\"lalr\", transformer=transformer, start=\"program\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/parser.html"}
{"id": "f4715a3a37e3-0", "text": "Source code for langchain.chains.qa_with_sources.retrieval\n\"\"\"Question-answering with sources over an index.\"\"\"\nfrom typing import Any, Dict, List\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains.combine_documents.stuff import StuffDocumentsChain\nfrom langchain.chains.qa_with_sources.base import BaseQAWithSourcesChain\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BaseRetriever\n[docs]class RetrievalQAWithSourcesChain(BaseQAWithSourcesChain):\n    \"\"\"Question-answering with sources over an index.\"\"\"\n    retriever: BaseRetriever = Field(exclude=True)\n    \"\"\"Index to connect to.\"\"\"\n    reduce_k_below_max_tokens: bool = False\n    \"\"\"Reduce the number of results to return from store based on tokens limit\"\"\"\n    max_tokens_limit: int = 3375\n    \"\"\"Restrict the docs to return from store based on tokens,\n    enforced only for StuffDocumentChain and if reduce_k_below_max_tokens is to true\"\"\"\n    def _reduce_tokens_below_limit(self, docs: List[Document]) -> List[Document]:\n        num_docs = len(docs)\n        if self.reduce_k_below_max_tokens and isinstance(\n            self.combine_documents_chain, StuffDocumentsChain\n        ):\n            tokens = [\n                self.combine_documents_chain.llm_chain._get_num_tokens(doc.page_content)\n                for doc in docs\n            ]\n            token_count = sum(tokens[:num_docs])\n            while token_count > self.max_tokens_limit:\n                num_docs -= 1\n                token_count -= tokens[num_docs]\n        return docs[:num_docs]\n    def _get_docs(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/retrieval.html"}
{"id": "f4715a3a37e3-1", "text": "return docs[:num_docs]\n    def _get_docs(\n        self, inputs: Dict[str, Any], *, run_manager: CallbackManagerForChainRun\n    ) -> List[Document]:\n        question = inputs[self.question_key]\n        docs = self.retriever.get_relevant_documents(\n            question, callbacks=run_manager.get_child()\n        )\n        return self._reduce_tokens_below_limit(docs)\n    async def _aget_docs(\n        self, inputs: Dict[str, Any], *, run_manager: AsyncCallbackManagerForChainRun\n    ) -> List[Document]:\n        question = inputs[self.question_key]\n        docs = await self.retriever.aget_relevant_documents(\n            question, callbacks=run_manager.get_child()\n        )\n        return self._reduce_tokens_below_limit(docs)\n    @property\n    def _chain_type(self) -> str:\n        \"\"\"Return the chain type.\"\"\"\n        return \"retrieval_qa_with_sources_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/retrieval.html"}
{"id": "68eadb54b8b7-0", "text": "Source code for langchain.chains.qa_with_sources.base\n\"\"\"Question answering with sources over documents.\"\"\"\nfrom __future__ import annotations\nimport inspect\nimport re\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Dict, List, Optional, Tuple\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains import ReduceDocumentsChain\nfrom langchain.chains.base import Chain\nfrom langchain.chains.combine_documents.base import BaseCombineDocumentsChain\nfrom langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain\nfrom langchain.chains.combine_documents.stuff import StuffDocumentsChain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.qa_with_sources.loading import load_qa_with_sources_chain\nfrom langchain.chains.qa_with_sources.map_reduce_prompt import (\n    COMBINE_PROMPT,\n    EXAMPLE_PROMPT,\n    QUESTION_PROMPT,\n)\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]class BaseQAWithSourcesChain(Chain, ABC):\n    \"\"\"Question answering chain with sources over documents.\"\"\"\n    combine_documents_chain: BaseCombineDocumentsChain\n    \"\"\"Chain to use to combine documents.\"\"\"\n    question_key: str = \"question\"  #: :meta private:\n    input_docs_key: str = \"docs\"  #: :meta private:\n    answer_key: str = \"answer\"  #: :meta private:\n    sources_answer_key: str = \"sources\"  #: :meta private:\n    return_source_documents: bool = False\n    \"\"\"Return the source documents.\"\"\"\n[docs]    @classmethod\n    def from_llm(\n        cls,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html"}
{"id": "68eadb54b8b7-1", "text": "[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        document_prompt: BasePromptTemplate = EXAMPLE_PROMPT,\n        question_prompt: BasePromptTemplate = QUESTION_PROMPT,\n        combine_prompt: BasePromptTemplate = COMBINE_PROMPT,\n        **kwargs: Any,\n    ) -> BaseQAWithSourcesChain:\n        \"\"\"Construct the chain from an LLM.\"\"\"\n        llm_question_chain = LLMChain(llm=llm, prompt=question_prompt)\n        llm_combine_chain = LLMChain(llm=llm, prompt=combine_prompt)\n        combine_results_chain = StuffDocumentsChain(\n            llm_chain=llm_combine_chain,\n            document_prompt=document_prompt,\n            document_variable_name=\"summaries\",\n        )\n        reduce_documents_chain = ReduceDocumentsChain(\n            combine_documents_chain=combine_results_chain\n        )\n        combine_documents_chain = MapReduceDocumentsChain(\n            llm_chain=llm_question_chain,\n            reduce_documents_chain=reduce_documents_chain,\n            document_variable_name=\"context\",\n        )\n        return cls(\n            combine_documents_chain=combine_documents_chain,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_chain_type(\n        cls,\n        llm: BaseLanguageModel,\n        chain_type: str = \"stuff\",\n        chain_type_kwargs: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> BaseQAWithSourcesChain:\n        \"\"\"Load chain from chain type.\"\"\"\n        _chain_kwargs = chain_type_kwargs or {}\n        combine_documents_chain = load_qa_with_sources_chain(\n            llm, chain_type=chain_type, **_chain_kwargs\n        )\n        return cls(combine_documents_chain=combine_documents_chain, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html"}
{"id": "68eadb54b8b7-2", "text": ")\n        return cls(combine_documents_chain=combine_documents_chain, **kwargs)\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        return [self.question_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return output key.\n        :meta private:\n        \"\"\"\n        _output_keys = [self.answer_key, self.sources_answer_key]\n        if self.return_source_documents:\n            _output_keys = _output_keys + [\"source_documents\"]\n        return _output_keys\n    @root_validator(pre=True)\n    def validate_naming(cls, values: Dict) -> Dict:\n        \"\"\"Fix backwards compatibility in naming.\"\"\"\n        if \"combine_document_chain\" in values:\n            values[\"combine_documents_chain\"] = values.pop(\"combine_document_chain\")\n        return values\n    def _split_sources(self, answer: str) -> Tuple[str, str]:\n        \"\"\"Split sources from answer.\"\"\"\n        if re.search(r\"SOURCES?:\", answer, re.IGNORECASE):\n            answer, sources = re.split(\n                r\"SOURCES?:|QUESTION:\\s\", answer, flags=re.IGNORECASE\n            )[:2]\n            sources = re.split(r\"\\n\", sources)[0].strip()\n        else:\n            sources = \"\"\n        return answer, sources\n    @abstractmethod\n    def _get_docs(\n        self,\n        inputs: Dict[str, Any],\n        *,\n        run_manager: CallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs to run questioning over.\"\"\"\n    def _call(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html"}
{"id": "68eadb54b8b7-3", "text": "\"\"\"Get docs to run questioning over.\"\"\"\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        accepts_run_manager = (\n            \"run_manager\" in inspect.signature(self._get_docs).parameters\n        )\n        if accepts_run_manager:\n            docs = self._get_docs(inputs, run_manager=_run_manager)\n        else:\n            docs = self._get_docs(inputs)  # type: ignore[call-arg]\n        answer = self.combine_documents_chain.run(\n            input_documents=docs, callbacks=_run_manager.get_child(), **inputs\n        )\n        answer, sources = self._split_sources(answer)\n        result: Dict[str, Any] = {\n            self.answer_key: answer,\n            self.sources_answer_key: sources,\n        }\n        if self.return_source_documents:\n            result[\"source_documents\"] = docs\n        return result\n    @abstractmethod\n    async def _aget_docs(\n        self,\n        inputs: Dict[str, Any],\n        *,\n        run_manager: AsyncCallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs to run questioning over.\"\"\"\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()\n        accepts_run_manager = (\n            \"run_manager\" in inspect.signature(self._aget_docs).parameters\n        )\n        if accepts_run_manager:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html"}
{"id": "68eadb54b8b7-4", "text": ")\n        if accepts_run_manager:\n            docs = await self._aget_docs(inputs, run_manager=_run_manager)\n        else:\n            docs = await self._aget_docs(inputs)  # type: ignore[call-arg]\n        answer = await self.combine_documents_chain.arun(\n            input_documents=docs, callbacks=_run_manager.get_child(), **inputs\n        )\n        answer, sources = self._split_sources(answer)\n        result: Dict[str, Any] = {\n            self.answer_key: answer,\n            self.sources_answer_key: sources,\n        }\n        if self.return_source_documents:\n            result[\"source_documents\"] = docs\n        return result\n[docs]class QAWithSourcesChain(BaseQAWithSourcesChain):\n    \"\"\"Question answering with sources over documents.\"\"\"\n    input_docs_key: str = \"docs\"  #: :meta private:\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Expect input key.\n        :meta private:\n        \"\"\"\n        return [self.input_docs_key, self.question_key]\n    def _get_docs(\n        self,\n        inputs: Dict[str, Any],\n        *,\n        run_manager: CallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs to run questioning over.\"\"\"\n        return inputs.pop(self.input_docs_key)\n    async def _aget_docs(\n        self,\n        inputs: Dict[str, Any],\n        *,\n        run_manager: AsyncCallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs to run questioning over.\"\"\"\n        return inputs.pop(self.input_docs_key)\n    @property\n    def _chain_type(self) -> str:\n        return \"qa_with_sources_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html"}
{"id": "4270919abe82-0", "text": "Source code for langchain.chains.qa_with_sources.loading\n\"\"\"Load question answering with sources chains.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Mapping, Optional, Protocol\nfrom langchain.chains.combine_documents.base import BaseCombineDocumentsChain\nfrom langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain\nfrom langchain.chains.combine_documents.map_rerank import MapRerankDocumentsChain\nfrom langchain.chains.combine_documents.reduce import ReduceDocumentsChain\nfrom langchain.chains.combine_documents.refine import RefineDocumentsChain\nfrom langchain.chains.combine_documents.stuff import StuffDocumentsChain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.qa_with_sources import (\n    map_reduce_prompt,\n    refine_prompts,\n    stuff_prompt,\n)\nfrom langchain.chains.question_answering.map_rerank_prompt import (\n    PROMPT as MAP_RERANK_PROMPT,\n)\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.prompt_template import BasePromptTemplate\n[docs]class LoadingCallable(Protocol):\n    \"\"\"Interface for loading the combine documents chain.\"\"\"\n    def __call__(\n        self, llm: BaseLanguageModel, **kwargs: Any\n    ) -> BaseCombineDocumentsChain:\n        \"\"\"Callable to load the combine documents chain.\"\"\"\ndef _load_map_rerank_chain(\n    llm: BaseLanguageModel,\n    prompt: BasePromptTemplate = MAP_RERANK_PROMPT,\n    verbose: bool = False,\n    document_variable_name: str = \"context\",\n    rank_key: str = \"score\",\n    answer_key: str = \"answer\",\n    **kwargs: Any,\n) -> MapRerankDocumentsChain:\n    llm_chain = LLMChain(llm=llm, prompt=prompt, verbose=verbose)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/loading.html"}
{"id": "4270919abe82-1", "text": "return MapRerankDocumentsChain(\n        llm_chain=llm_chain,\n        rank_key=rank_key,\n        answer_key=answer_key,\n        document_variable_name=document_variable_name,\n        **kwargs,\n    )\ndef _load_stuff_chain(\n    llm: BaseLanguageModel,\n    prompt: BasePromptTemplate = stuff_prompt.PROMPT,\n    document_prompt: BasePromptTemplate = stuff_prompt.EXAMPLE_PROMPT,\n    document_variable_name: str = \"summaries\",\n    verbose: Optional[bool] = None,\n    **kwargs: Any,\n) -> StuffDocumentsChain:\n    llm_chain = LLMChain(llm=llm, prompt=prompt, verbose=verbose)\n    return StuffDocumentsChain(\n        llm_chain=llm_chain,\n        document_variable_name=document_variable_name,\n        document_prompt=document_prompt,\n        verbose=verbose,\n        **kwargs,\n    )\ndef _load_map_reduce_chain(\n    llm: BaseLanguageModel,\n    question_prompt: BasePromptTemplate = map_reduce_prompt.QUESTION_PROMPT,\n    combine_prompt: BasePromptTemplate = map_reduce_prompt.COMBINE_PROMPT,\n    document_prompt: BasePromptTemplate = map_reduce_prompt.EXAMPLE_PROMPT,\n    combine_document_variable_name: str = \"summaries\",\n    map_reduce_document_variable_name: str = \"context\",\n    collapse_prompt: Optional[BasePromptTemplate] = None,\n    reduce_llm: Optional[BaseLanguageModel] = None,\n    collapse_llm: Optional[BaseLanguageModel] = None,\n    verbose: Optional[bool] = None,\n    token_max: int = 3000,\n    **kwargs: Any,\n) -> MapReduceDocumentsChain:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/loading.html"}
{"id": "4270919abe82-2", "text": "**kwargs: Any,\n) -> MapReduceDocumentsChain:\n    map_chain = LLMChain(llm=llm, prompt=question_prompt, verbose=verbose)\n    _reduce_llm = reduce_llm or llm\n    reduce_chain = LLMChain(llm=_reduce_llm, prompt=combine_prompt, verbose=verbose)\n    combine_documents_chain = StuffDocumentsChain(\n        llm_chain=reduce_chain,\n        document_variable_name=combine_document_variable_name,\n        document_prompt=document_prompt,\n        verbose=verbose,\n    )\n    if collapse_prompt is None:\n        collapse_chain = None\n        if collapse_llm is not None:\n            raise ValueError(\n                \"collapse_llm provided, but collapse_prompt was not: please \"\n                \"provide one or stop providing collapse_llm.\"\n            )\n    else:\n        _collapse_llm = collapse_llm or llm\n        collapse_chain = StuffDocumentsChain(\n            llm_chain=LLMChain(\n                llm=_collapse_llm,\n                prompt=collapse_prompt,\n                verbose=verbose,\n            ),\n            document_variable_name=combine_document_variable_name,\n            document_prompt=document_prompt,\n        )\n    reduce_documents_chain = ReduceDocumentsChain(\n        combine_documents_chain=combine_documents_chain,\n        collapse_documents_chain=collapse_chain,\n        token_max=token_max,\n        verbose=verbose,\n    )\n    return MapReduceDocumentsChain(\n        llm_chain=map_chain,\n        reduce_documents_chain=reduce_documents_chain,\n        document_variable_name=map_reduce_document_variable_name,\n        verbose=verbose,\n        **kwargs,\n    )\ndef _load_refine_chain(\n    llm: BaseLanguageModel,\n    question_prompt: BasePromptTemplate = refine_prompts.DEFAULT_TEXT_QA_PROMPT,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/loading.html"}
{"id": "4270919abe82-3", "text": "question_prompt: BasePromptTemplate = refine_prompts.DEFAULT_TEXT_QA_PROMPT,\n    refine_prompt: BasePromptTemplate = refine_prompts.DEFAULT_REFINE_PROMPT,\n    document_prompt: BasePromptTemplate = refine_prompts.EXAMPLE_PROMPT,\n    document_variable_name: str = \"context_str\",\n    initial_response_name: str = \"existing_answer\",\n    refine_llm: Optional[BaseLanguageModel] = None,\n    verbose: Optional[bool] = None,\n    **kwargs: Any,\n) -> RefineDocumentsChain:\n    initial_chain = LLMChain(llm=llm, prompt=question_prompt, verbose=verbose)\n    _refine_llm = refine_llm or llm\n    refine_chain = LLMChain(llm=_refine_llm, prompt=refine_prompt, verbose=verbose)\n    return RefineDocumentsChain(\n        initial_llm_chain=initial_chain,\n        refine_llm_chain=refine_chain,\n        document_variable_name=document_variable_name,\n        initial_response_name=initial_response_name,\n        document_prompt=document_prompt,\n        verbose=verbose,\n        **kwargs,\n    )\n[docs]def load_qa_with_sources_chain(\n    llm: BaseLanguageModel,\n    chain_type: str = \"stuff\",\n    verbose: Optional[bool] = None,\n    **kwargs: Any,\n) -> BaseCombineDocumentsChain:\n    \"\"\"Load a question answering with sources chain.\n    Args:\n        llm: Language Model to use in the chain.\n        chain_type: Type of document combining chain to use. Should be one of \"stuff\",\n            \"map_reduce\", \"refine\" and \"map_rerank\".\n        verbose: Whether chains should be run in verbose mode or not. Note that this", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/loading.html"}
{"id": "4270919abe82-4", "text": "verbose: Whether chains should be run in verbose mode or not. Note that this\n            applies to all chains that make up the final chain.\n    Returns:\n        A chain to use for question answering with sources.\n    \"\"\"\n    loader_mapping: Mapping[str, LoadingCallable] = {\n        \"stuff\": _load_stuff_chain,\n        \"map_reduce\": _load_map_reduce_chain,\n        \"refine\": _load_refine_chain,\n        \"map_rerank\": _load_map_rerank_chain,\n    }\n    if chain_type not in loader_mapping:\n        raise ValueError(\n            f\"Got unsupported chain type: {chain_type}. \"\n            f\"Should be one of {loader_mapping.keys()}\"\n        )\n    _func: LoadingCallable = loader_mapping[chain_type]\n    return _func(llm, verbose=verbose, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/loading.html"}
{"id": "568f7b36f232-0", "text": "Source code for langchain.chains.qa_with_sources.vector_db\n\"\"\"Question-answering with sources over a vector database.\"\"\"\nimport warnings\nfrom typing import Any, Dict, List\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains.combine_documents.stuff import StuffDocumentsChain\nfrom langchain.chains.qa_with_sources.base import BaseQAWithSourcesChain\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema.vectorstore import VectorStore\n[docs]class VectorDBQAWithSourcesChain(BaseQAWithSourcesChain):\n    \"\"\"Question-answering with sources over a vector database.\"\"\"\n    vectorstore: VectorStore = Field(exclude=True)\n    \"\"\"Vector Database to connect to.\"\"\"\n    k: int = 4\n    \"\"\"Number of results to return from store\"\"\"\n    reduce_k_below_max_tokens: bool = False\n    \"\"\"Reduce the number of results to return from store based on tokens limit\"\"\"\n    max_tokens_limit: int = 3375\n    \"\"\"Restrict the docs to return from store based on tokens,\n    enforced only for StuffDocumentChain and if reduce_k_below_max_tokens is to true\"\"\"\n    search_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Extra search args.\"\"\"\n    def _reduce_tokens_below_limit(self, docs: List[Document]) -> List[Document]:\n        num_docs = len(docs)\n        if self.reduce_k_below_max_tokens and isinstance(\n            self.combine_documents_chain, StuffDocumentsChain\n        ):\n            tokens = [\n                self.combine_documents_chain.llm_chain._get_num_tokens(doc.page_content)\n                for doc in docs\n            ]\n            token_count = sum(tokens[:num_docs])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/vector_db.html"}
{"id": "568f7b36f232-1", "text": "for doc in docs\n            ]\n            token_count = sum(tokens[:num_docs])\n            while token_count > self.max_tokens_limit:\n                num_docs -= 1\n                token_count -= tokens[num_docs]\n        return docs[:num_docs]\n    def _get_docs(\n        self, inputs: Dict[str, Any], *, run_manager: CallbackManagerForChainRun\n    ) -> List[Document]:\n        question = inputs[self.question_key]\n        docs = self.vectorstore.similarity_search(\n            question, k=self.k, **self.search_kwargs\n        )\n        return self._reduce_tokens_below_limit(docs)\n    async def _aget_docs(\n        self, inputs: Dict[str, Any], *, run_manager: AsyncCallbackManagerForChainRun\n    ) -> List[Document]:\n        raise NotImplementedError(\"VectorDBQAWithSourcesChain does not support async\")\n    @root_validator()\n    def raise_deprecation(cls, values: Dict) -> Dict:\n        warnings.warn(\n            \"`VectorDBQAWithSourcesChain` is deprecated - \"\n            \"please use `from langchain.chains import RetrievalQAWithSourcesChain`\"\n        )\n        return values\n    @property\n    def _chain_type(self) -> str:\n        return \"vector_db_qa_with_sources_chain\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/vector_db.html"}
{"id": "56b7c4702295-0", "text": "Source code for langchain.chains.llm_summarization_checker.base\n\"\"\"Chain for summarization with self-verification.\"\"\"\nfrom __future__ import annotations\nimport warnings\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForChainRun\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.sequential import SequentialChain\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.schema.language_model import BaseLanguageModel\nPROMPTS_DIR = Path(__file__).parent / \"prompts\"\nCREATE_ASSERTIONS_PROMPT = PromptTemplate.from_file(\n    PROMPTS_DIR / \"create_facts.txt\", [\"summary\"]\n)\nCHECK_ASSERTIONS_PROMPT = PromptTemplate.from_file(\n    PROMPTS_DIR / \"check_facts.txt\", [\"assertions\"]\n)\nREVISED_SUMMARY_PROMPT = PromptTemplate.from_file(\n    PROMPTS_DIR / \"revise_summary.txt\", [\"checked_assertions\", \"summary\"]\n)\nARE_ALL_TRUE_PROMPT = PromptTemplate.from_file(\n    PROMPTS_DIR / \"are_all_true_prompt.txt\", [\"checked_assertions\"]\n)\ndef _load_sequential_chain(\n    llm: BaseLanguageModel,\n    create_assertions_prompt: PromptTemplate,\n    check_assertions_prompt: PromptTemplate,\n    revised_summary_prompt: PromptTemplate,\n    are_all_true_prompt: PromptTemplate,\n    verbose: bool = False,\n) -> SequentialChain:\n    chain = SequentialChain(\n        chains=[\n            LLMChain(\n                llm=llm,\n                prompt=create_assertions_prompt,\n                output_key=\"assertions\",\n                verbose=verbose,\n            ),\n            LLMChain(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html"}
{"id": "56b7c4702295-1", "text": "verbose=verbose,\n            ),\n            LLMChain(\n                llm=llm,\n                prompt=check_assertions_prompt,\n                output_key=\"checked_assertions\",\n                verbose=verbose,\n            ),\n            LLMChain(\n                llm=llm,\n                prompt=revised_summary_prompt,\n                output_key=\"revised_summary\",\n                verbose=verbose,\n            ),\n            LLMChain(\n                llm=llm,\n                output_key=\"all_true\",\n                prompt=are_all_true_prompt,\n                verbose=verbose,\n            ),\n        ],\n        input_variables=[\"summary\"],\n        output_variables=[\"all_true\", \"revised_summary\"],\n        verbose=verbose,\n    )\n    return chain\n[docs]class LLMSummarizationCheckerChain(Chain):\n    \"\"\"Chain for question-answering with self-verification.\n    Example:\n        .. code-block:: python\n            from langchain.llms import OpenAI\n            from langchain.chains import LLMSummarizationCheckerChain\n            llm = OpenAI(temperature=0.0)\n            checker_chain = LLMSummarizationCheckerChain.from_llm(llm)\n    \"\"\"\n    sequential_chain: SequentialChain\n    llm: Optional[BaseLanguageModel] = None\n    \"\"\"[Deprecated] LLM wrapper to use.\"\"\"\n    create_assertions_prompt: PromptTemplate = CREATE_ASSERTIONS_PROMPT\n    \"\"\"[Deprecated]\"\"\"\n    check_assertions_prompt: PromptTemplate = CHECK_ASSERTIONS_PROMPT\n    \"\"\"[Deprecated]\"\"\"\n    revised_summary_prompt: PromptTemplate = REVISED_SUMMARY_PROMPT\n    \"\"\"[Deprecated]\"\"\"\n    are_all_true_prompt: PromptTemplate = ARE_ALL_TRUE_PROMPT\n    \"\"\"[Deprecated]\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html"}
{"id": "56b7c4702295-2", "text": "\"\"\"[Deprecated]\"\"\"\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:\n    max_checks: int = 2\n    \"\"\"Maximum number of times to check the assertions. Default to double-checking.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator(pre=True)\n    def raise_deprecation(cls, values: Dict) -> Dict:\n        if \"llm\" in values:\n            warnings.warn(\n                \"Directly instantiating an LLMSummarizationCheckerChain with an llm is \"\n                \"deprecated. Please instantiate with\"\n                \" sequential_chain argument or using the from_llm class method.\"\n            )\n            if \"sequential_chain\" not in values and values[\"llm\"] is not None:\n                values[\"sequential_chain\"] = _load_sequential_chain(\n                    values[\"llm\"],\n                    values.get(\"create_assertions_prompt\", CREATE_ASSERTIONS_PROMPT),\n                    values.get(\"check_assertions_prompt\", CHECK_ASSERTIONS_PROMPT),\n                    values.get(\"revised_summary_prompt\", REVISED_SUMMARY_PROMPT),\n                    values.get(\"are_all_true_prompt\", ARE_ALL_TRUE_PROMPT),\n                    verbose=values.get(\"verbose\", False),\n                )\n        return values\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the singular input key.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the singular output key.\n        :meta private:\n        \"\"\"\n        return [self.output_key]\n    def _call(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html"}
{"id": "56b7c4702295-3", "text": "return [self.output_key]\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        all_true = False\n        count = 0\n        output = None\n        original_input = inputs[self.input_key]\n        chain_input = original_input\n        while not all_true and count < self.max_checks:\n            output = self.sequential_chain(\n                {\"summary\": chain_input}, callbacks=_run_manager.get_child()\n            )\n            count += 1\n            if output[\"all_true\"].strip() == \"True\":\n                break\n            if self.verbose:\n                print(output[\"revised_summary\"])\n            chain_input = output[\"revised_summary\"]\n        if not output:\n            raise ValueError(\"No output from chain\")\n        return {self.output_key: output[\"revised_summary\"].strip()}\n    @property\n    def _chain_type(self) -> str:\n        return \"llm_summarization_checker_chain\"\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        create_assertions_prompt: PromptTemplate = CREATE_ASSERTIONS_PROMPT,\n        check_assertions_prompt: PromptTemplate = CHECK_ASSERTIONS_PROMPT,\n        revised_summary_prompt: PromptTemplate = REVISED_SUMMARY_PROMPT,\n        are_all_true_prompt: PromptTemplate = ARE_ALL_TRUE_PROMPT,\n        verbose: bool = False,\n        **kwargs: Any,\n    ) -> LLMSummarizationCheckerChain:\n        chain = _load_sequential_chain(\n            llm,\n            create_assertions_prompt,\n            check_assertions_prompt,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html"}
{"id": "56b7c4702295-4", "text": "llm,\n            create_assertions_prompt,\n            check_assertions_prompt,\n            revised_summary_prompt,\n            are_all_true_prompt,\n            verbose=verbose,\n        )\n        return cls(sequential_chain=chain, verbose=verbose, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html"}
{"id": "1e8d05445472-0", "text": "Source code for langchain.chains.retrieval_qa.base\n\"\"\"Chain for question-answering against a vector database.\"\"\"\nfrom __future__ import annotations\nimport inspect\nimport warnings\nfrom abc import abstractmethod\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n    Callbacks,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.chains.combine_documents.base import BaseCombineDocumentsChain\nfrom langchain.chains.combine_documents.stuff import StuffDocumentsChain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.question_answering import load_qa_chain\nfrom langchain.chains.question_answering.stuff_prompt import PROMPT_SELECTOR\nfrom langchain.prompts import PromptTemplate\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.schema import BaseRetriever, Document\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.vectorstore import VectorStore\n[docs]class BaseRetrievalQA(Chain):\n    \"\"\"Base class for question-answering chains.\"\"\"\n    combine_documents_chain: BaseCombineDocumentsChain\n    \"\"\"Chain to use to combine the documents.\"\"\"\n    input_key: str = \"query\"  #: :meta private:\n    output_key: str = \"result\"  #: :meta private:\n    return_source_documents: bool = False\n    \"\"\"Return the source documents or not.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n        allow_population_by_field_name = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Input keys.\n        :meta private:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html"}
{"id": "1e8d05445472-1", "text": "\"\"\"Input keys.\n        :meta private:\n        \"\"\"\n        return [self.input_key]\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Output keys.\n        :meta private:\n        \"\"\"\n        _output_keys = [self.output_key]\n        if self.return_source_documents:\n            _output_keys = _output_keys + [\"source_documents\"]\n        return _output_keys\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        prompt: Optional[PromptTemplate] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> BaseRetrievalQA:\n        \"\"\"Initialize from LLM.\"\"\"\n        _prompt = prompt or PROMPT_SELECTOR.get_prompt(llm)\n        llm_chain = LLMChain(llm=llm, prompt=_prompt, callbacks=callbacks)\n        document_prompt = PromptTemplate(\n            input_variables=[\"page_content\"], template=\"Context:\\n{page_content}\"\n        )\n        combine_documents_chain = StuffDocumentsChain(\n            llm_chain=llm_chain,\n            document_variable_name=\"context\",\n            document_prompt=document_prompt,\n            callbacks=callbacks,\n        )\n        return cls(\n            combine_documents_chain=combine_documents_chain,\n            callbacks=callbacks,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_chain_type(\n        cls,\n        llm: BaseLanguageModel,\n        chain_type: str = \"stuff\",\n        chain_type_kwargs: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> BaseRetrievalQA:\n        \"\"\"Load chain from chain type.\"\"\"\n        _chain_type_kwargs = chain_type_kwargs or {}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html"}
{"id": "1e8d05445472-2", "text": "_chain_type_kwargs = chain_type_kwargs or {}\n        combine_documents_chain = load_qa_chain(\n            llm, chain_type=chain_type, **_chain_type_kwargs\n        )\n        return cls(combine_documents_chain=combine_documents_chain, **kwargs)\n    @abstractmethod\n    def _get_docs(\n        self,\n        question: str,\n        *,\n        run_manager: CallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get documents to do question answering over.\"\"\"\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Run get_relevant_text and llm on input query.\n        If chain has 'return_source_documents' as 'True', returns\n        the retrieved documents as well under the key 'source_documents'.\n        Example:\n        .. code-block:: python\n        res = indexqa({'query': 'This is my query'})\n        answer, docs = res['result'], res['source_documents']\n        \"\"\"\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        question = inputs[self.input_key]\n        accepts_run_manager = (\n            \"run_manager\" in inspect.signature(self._get_docs).parameters\n        )\n        if accepts_run_manager:\n            docs = self._get_docs(question, run_manager=_run_manager)\n        else:\n            docs = self._get_docs(question)  # type: ignore[call-arg]\n        answer = self.combine_documents_chain.run(\n            input_documents=docs, question=question, callbacks=_run_manager.get_child()\n        )\n        if self.return_source_documents:\n            return {self.output_key: answer, \"source_documents\": docs}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html"}
{"id": "1e8d05445472-3", "text": "return {self.output_key: answer, \"source_documents\": docs}\n        else:\n            return {self.output_key: answer}\n    @abstractmethod\n    async def _aget_docs(\n        self,\n        question: str,\n        *,\n        run_manager: AsyncCallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get documents to do question answering over.\"\"\"\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Run get_relevant_text and llm on input query.\n        If chain has 'return_source_documents' as 'True', returns\n        the retrieved documents as well under the key 'source_documents'.\n        Example:\n        .. code-block:: python\n        res = indexqa({'query': 'This is my query'})\n        answer, docs = res['result'], res['source_documents']\n        \"\"\"\n        _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()\n        question = inputs[self.input_key]\n        accepts_run_manager = (\n            \"run_manager\" in inspect.signature(self._aget_docs).parameters\n        )\n        if accepts_run_manager:\n            docs = await self._aget_docs(question, run_manager=_run_manager)\n        else:\n            docs = await self._aget_docs(question)  # type: ignore[call-arg]\n        answer = await self.combine_documents_chain.arun(\n            input_documents=docs, question=question, callbacks=_run_manager.get_child()\n        )\n        if self.return_source_documents:\n            return {self.output_key: answer, \"source_documents\": docs}\n        else:\n            return {self.output_key: answer}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html"}
{"id": "1e8d05445472-4", "text": "else:\n            return {self.output_key: answer}\n[docs]class RetrievalQA(BaseRetrievalQA):\n    \"\"\"Chain for question-answering against an index.\n    Example:\n        .. code-block:: python\n            from langchain.llms import OpenAI\n            from langchain.chains import RetrievalQA\n            from langchain.vectorstores import FAISS\n            from langchain.schema.vectorstore import VectorStoreRetriever\n            retriever = VectorStoreRetriever(vectorstore=FAISS(...))\n            retrievalQA = RetrievalQA.from_llm(llm=OpenAI(), retriever=retriever)\n    \"\"\"\n    retriever: BaseRetriever = Field(exclude=True)\n    def _get_docs(\n        self,\n        question: str,\n        *,\n        run_manager: CallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs.\"\"\"\n        return self.retriever.get_relevant_documents(\n            question, callbacks=run_manager.get_child()\n        )\n    async def _aget_docs(\n        self,\n        question: str,\n        *,\n        run_manager: AsyncCallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs.\"\"\"\n        return await self.retriever.aget_relevant_documents(\n            question, callbacks=run_manager.get_child()\n        )\n    @property\n    def _chain_type(self) -> str:\n        \"\"\"Return the chain type.\"\"\"\n        return \"retrieval_qa\"\n[docs]class VectorDBQA(BaseRetrievalQA):\n    \"\"\"Chain for question-answering against a vector database.\"\"\"\n    vectorstore: VectorStore = Field(exclude=True, alias=\"vectorstore\")\n    \"\"\"Vector Database to connect to.\"\"\"\n    k: int = 4", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html"}
{"id": "1e8d05445472-5", "text": "\"\"\"Vector Database to connect to.\"\"\"\n    k: int = 4\n    \"\"\"Number of documents to query for.\"\"\"\n    search_type: str = \"similarity\"\n    \"\"\"Search type to use over vectorstore. `similarity` or `mmr`.\"\"\"\n    search_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Extra search args.\"\"\"\n    @root_validator()\n    def raise_deprecation(cls, values: Dict) -> Dict:\n        warnings.warn(\n            \"`VectorDBQA` is deprecated - \"\n            \"please use `from langchain.chains import RetrievalQA`\"\n        )\n        return values\n    @root_validator()\n    def validate_search_type(cls, values: Dict) -> Dict:\n        \"\"\"Validate search type.\"\"\"\n        if \"search_type\" in values:\n            search_type = values[\"search_type\"]\n            if search_type not in (\"similarity\", \"mmr\"):\n                raise ValueError(f\"search_type of {search_type} not allowed.\")\n        return values\n    def _get_docs(\n        self,\n        question: str,\n        *,\n        run_manager: CallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs.\"\"\"\n        if self.search_type == \"similarity\":\n            docs = self.vectorstore.similarity_search(\n                question, k=self.k, **self.search_kwargs\n            )\n        elif self.search_type == \"mmr\":\n            docs = self.vectorstore.max_marginal_relevance_search(\n                question, k=self.k, **self.search_kwargs\n            )\n        else:\n            raise ValueError(f\"search_type of {self.search_type} not allowed.\")\n        return docs\n    async def _aget_docs(\n        self,\n        question: str,\n        *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html"}
{"id": "1e8d05445472-6", "text": "self,\n        question: str,\n        *,\n        run_manager: AsyncCallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs.\"\"\"\n        raise NotImplementedError(\"VectorDBQA does not support async\")\n    @property\n    def _chain_type(self) -> str:\n        \"\"\"Return the chain type.\"\"\"\n        return \"vector_db_qa\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html"}
{"id": "6d8a26754629-0", "text": "Source code for langchain.chains.conversational_retrieval.base\n\"\"\"Chain for chatting with a vector database.\"\"\"\nfrom __future__ import annotations\nimport inspect\nimport warnings\nfrom abc import abstractmethod\nfrom pathlib import Path\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n    Callbacks,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.chains.combine_documents.base import BaseCombineDocumentsChain\nfrom langchain.chains.combine_documents.stuff import StuffDocumentsChain\nfrom langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chains.question_answering import load_qa_chain\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator\nfrom langchain.schema import BasePromptTemplate, BaseRetriever, Document\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import BaseMessage\nfrom langchain.schema.runnable.config import RunnableConfig\nfrom langchain.schema.vectorstore import VectorStore\n# Depending on the memory type and configuration, the chat history format may differ.\n# This needs to be consolidated.\nCHAT_TURN_TYPE = Union[Tuple[str, str], BaseMessage]\n_ROLE_MAP = {\"human\": \"Human: \", \"ai\": \"Assistant: \"}\ndef _get_chat_history(chat_history: List[CHAT_TURN_TYPE]) -> str:\n    buffer = \"\"\n    for dialogue_turn in chat_history:\n        if isinstance(dialogue_turn, BaseMessage):\n            role_prefix = _ROLE_MAP.get(dialogue_turn.type, f\"{dialogue_turn.type}: \")\n            buffer += f\"\\n{role_prefix}{dialogue_turn.content}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html"}
{"id": "6d8a26754629-1", "text": "buffer += f\"\\n{role_prefix}{dialogue_turn.content}\"\n        elif isinstance(dialogue_turn, tuple):\n            human = \"Human: \" + dialogue_turn[0]\n            ai = \"Assistant: \" + dialogue_turn[1]\n            buffer += \"\\n\" + \"\\n\".join([human, ai])\n        else:\n            raise ValueError(\n                f\"Unsupported chat history format: {type(dialogue_turn)}.\"\n                f\" Full chat history: {chat_history} \"\n            )\n    return buffer\n[docs]class InputType(BaseModel):\n    question: str\n    chat_history: List[CHAT_TURN_TYPE] = Field(default_factory=list)\n[docs]class BaseConversationalRetrievalChain(Chain):\n    \"\"\"Chain for chatting with an index.\"\"\"\n    combine_docs_chain: BaseCombineDocumentsChain\n    \"\"\"The chain used to combine any retrieved documents.\"\"\"\n    question_generator: LLMChain\n    \"\"\"The chain used to generate a new question for the sake of retrieval.\n    This chain will take in the current question (with variable `question`)\n    and any chat history (with variable `chat_history`) and will produce\n    a new standalone question to be used later on.\"\"\"\n    output_key: str = \"answer\"\n    \"\"\"The output key to return the final answer of this chain in.\"\"\"\n    rephrase_question: bool = True\n    \"\"\"Whether or not to pass the new generated question to the combine_docs_chain.\n    If True, will pass the new generated question along.\n    If False, will only use the new generated question for retrieval and pass the\n    original question along to the combine_docs_chain.\"\"\"\n    return_source_documents: bool = False\n    \"\"\"Return the retrieved source documents as part of the final result.\"\"\"\n    return_generated_question: bool = False", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html"}
{"id": "6d8a26754629-2", "text": "return_generated_question: bool = False\n    \"\"\"Return the generated question as part of the final result.\"\"\"\n    get_chat_history: Optional[Callable[[List[CHAT_TURN_TYPE]], str]] = None\n    \"\"\"An optional function to get a string of the chat history.\n    If None is provided, will use a default.\"\"\"\n    response_if_no_docs_found: Optional[str]\n    \"\"\"If specified, the chain will return a fixed response if no docs \n    are found for the question. \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n        allow_population_by_field_name = True\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Input keys.\"\"\"\n        return [\"question\", \"chat_history\"]\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        return InputType\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the output keys.\n        :meta private:\n        \"\"\"\n        _output_keys = [self.output_key]\n        if self.return_source_documents:\n            _output_keys = _output_keys + [\"source_documents\"]\n        if self.return_generated_question:\n            _output_keys = _output_keys + [\"generated_question\"]\n        return _output_keys\n    @abstractmethod\n    def _get_docs(\n        self,\n        question: str,\n        inputs: Dict[str, Any],\n        *,\n        run_manager: CallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs.\"\"\"\n    def _call(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[CallbackManagerForChainRun] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html"}
{"id": "6d8a26754629-3", "text": "run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        question = inputs[\"question\"]\n        get_chat_history = self.get_chat_history or _get_chat_history\n        chat_history_str = get_chat_history(inputs[\"chat_history\"])\n        if chat_history_str:\n            callbacks = _run_manager.get_child()\n            new_question = self.question_generator.run(\n                question=question, chat_history=chat_history_str, callbacks=callbacks\n            )\n        else:\n            new_question = question\n        accepts_run_manager = (\n            \"run_manager\" in inspect.signature(self._get_docs).parameters\n        )\n        if accepts_run_manager:\n            docs = self._get_docs(new_question, inputs, run_manager=_run_manager)\n        else:\n            docs = self._get_docs(new_question, inputs)  # type: ignore[call-arg]\n        output: Dict[str, Any] = {}\n        if self.response_if_no_docs_found is not None and len(docs) == 0:\n            output[self.output_key] = self.response_if_no_docs_found\n        else:\n            new_inputs = inputs.copy()\n            if self.rephrase_question:\n                new_inputs[\"question\"] = new_question\n            new_inputs[\"chat_history\"] = chat_history_str\n            answer = self.combine_docs_chain.run(\n                input_documents=docs, callbacks=_run_manager.get_child(), **new_inputs\n            )\n            output[self.output_key] = answer\n        if self.return_source_documents:\n            output[\"source_documents\"] = docs\n        if self.return_generated_question:\n            output[\"generated_question\"] = new_question\n        return output\n    @abstractmethod\n    async def _aget_docs(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html"}
{"id": "6d8a26754629-4", "text": "return output\n    @abstractmethod\n    async def _aget_docs(\n        self,\n        question: str,\n        inputs: Dict[str, Any],\n        *,\n        run_manager: AsyncCallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs.\"\"\"\n    async def _acall(\n        self,\n        inputs: Dict[str, Any],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()\n        question = inputs[\"question\"]\n        get_chat_history = self.get_chat_history or _get_chat_history\n        chat_history_str = get_chat_history(inputs[\"chat_history\"])\n        if chat_history_str:\n            callbacks = _run_manager.get_child()\n            new_question = await self.question_generator.arun(\n                question=question, chat_history=chat_history_str, callbacks=callbacks\n            )\n        else:\n            new_question = question\n        accepts_run_manager = (\n            \"run_manager\" in inspect.signature(self._aget_docs).parameters\n        )\n        if accepts_run_manager:\n            docs = await self._aget_docs(new_question, inputs, run_manager=_run_manager)\n        else:\n            docs = await self._aget_docs(new_question, inputs)  # type: ignore[call-arg]\n        new_inputs = inputs.copy()\n        if self.rephrase_question:\n            new_inputs[\"question\"] = new_question\n        new_inputs[\"chat_history\"] = chat_history_str\n        answer = await self.combine_docs_chain.arun(\n            input_documents=docs, callbacks=_run_manager.get_child(), **new_inputs\n        )\n        output: Dict[str, Any] = {self.output_key: answer}\n        if self.return_source_documents:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html"}
{"id": "6d8a26754629-5", "text": "if self.return_source_documents:\n            output[\"source_documents\"] = docs\n        if self.return_generated_question:\n            output[\"generated_question\"] = new_question\n        return output\n[docs]    def save(self, file_path: Union[Path, str]) -> None:\n        if self.get_chat_history:\n            raise ValueError(\"Chain not saveable when `get_chat_history` is not None.\")\n        super().save(file_path)\n[docs]class ConversationalRetrievalChain(BaseConversationalRetrievalChain):\n    \"\"\"Chain for having a conversation based on retrieved documents.\n    This chain takes in chat history (a list of messages) and new questions,\n    and then returns an answer to that question.\n    The algorithm for this chain consists of three parts:\n    1. Use the chat history and the new question to create a \"standalone question\".\n    This is done so that this question can be passed into the retrieval step to fetch\n    relevant documents. If only the new question was passed in, then relevant context\n    may be lacking. If the whole conversation was passed into retrieval, there may\n    be unnecessary information there that would distract from retrieval.\n    2. This new question is passed to the retriever and relevant documents are\n    returned.\n    3. The retrieved documents are passed to an LLM along with either the new question\n    (default behavior) or the original question and chat history to generate a final\n    response.\n    Example:\n        .. code-block:: python\n            from langchain.chains import (\n                StuffDocumentsChain, LLMChain, ConversationalRetrievalChain\n            )\n            from langchain.prompts import PromptTemplate\n            from langchain.llms import OpenAI\n            combine_docs_chain = StuffDocumentsChain(...)\n            vectorstore = ...", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html"}
{"id": "6d8a26754629-6", "text": "combine_docs_chain = StuffDocumentsChain(...)\n            vectorstore = ...\n            retriever = vectorstore.as_retriever()\n            # This controls how the standalone question is generated.\n            # Should take `chat_history` and `question` as input variables.\n            template = (\n                \"Combine the chat history and follow up question into \"\n                \"a standalone question. Chat History: {chat_history}\"\n                \"Follow up question: {question}\"\n            )\n            prompt = PromptTemplate.from_template(template)\n            llm = OpenAI()\n            question_generator_chain = LLMChain(llm=llm, prompt=prompt)\n            chain = ConversationalRetrievalChain(\n                combine_docs_chain=combine_docs_chain,\n                retriever=retriever,\n                question_generator=question_generator_chain,\n            )\n    \"\"\"\n    retriever: BaseRetriever\n    \"\"\"Retriever to use to fetch documents.\"\"\"\n    max_tokens_limit: Optional[int] = None\n    \"\"\"If set, enforces that the documents returned are less than this limit.\n    This is only enforced if `combine_docs_chain` is of type StuffDocumentsChain.\"\"\"\n    def _reduce_tokens_below_limit(self, docs: List[Document]) -> List[Document]:\n        num_docs = len(docs)\n        if self.max_tokens_limit and isinstance(\n            self.combine_docs_chain, StuffDocumentsChain\n        ):\n            tokens = [\n                self.combine_docs_chain.llm_chain._get_num_tokens(doc.page_content)\n                for doc in docs\n            ]\n            token_count = sum(tokens[:num_docs])\n            while token_count > self.max_tokens_limit:\n                num_docs -= 1\n                token_count -= tokens[num_docs]\n        return docs[:num_docs]\n    def _get_docs(\n        self,\n        question: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html"}
{"id": "6d8a26754629-7", "text": "def _get_docs(\n        self,\n        question: str,\n        inputs: Dict[str, Any],\n        *,\n        run_manager: CallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs.\"\"\"\n        docs = self.retriever.get_relevant_documents(\n            question, callbacks=run_manager.get_child()\n        )\n        return self._reduce_tokens_below_limit(docs)\n    async def _aget_docs(\n        self,\n        question: str,\n        inputs: Dict[str, Any],\n        *,\n        run_manager: AsyncCallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs.\"\"\"\n        docs = await self.retriever.aget_relevant_documents(\n            question, callbacks=run_manager.get_child()\n        )\n        return self._reduce_tokens_below_limit(docs)\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        retriever: BaseRetriever,\n        condense_question_prompt: BasePromptTemplate = CONDENSE_QUESTION_PROMPT,\n        chain_type: str = \"stuff\",\n        verbose: bool = False,\n        condense_question_llm: Optional[BaseLanguageModel] = None,\n        combine_docs_chain_kwargs: Optional[Dict] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> BaseConversationalRetrievalChain:\n        \"\"\"Convenience method to load chain from LLM and retriever.\n        This provides some logic to create the `question_generator` chain\n        as well as the combine_docs_chain.\n        Args:\n            llm: The default language model to use at every part of this chain\n                (eg in both the question generation and the answering)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html"}
{"id": "6d8a26754629-8", "text": "(eg in both the question generation and the answering)\n            retriever: The retriever to use to fetch relevant documents from.\n            condense_question_prompt: The prompt to use to condense the chat history\n                and new question into a standalone question.\n            chain_type: The chain type to use to create the combine_docs_chain, will\n                be sent to `load_qa_chain`.\n            verbose: Verbosity flag for logging to stdout.\n            condense_question_llm: The language model to use for condensing the chat\n                history and new question into a standalone question. If none is\n                provided, will default to `llm`.\n            combine_docs_chain_kwargs: Parameters to pass as kwargs to `load_qa_chain`\n                when constructing the combine_docs_chain.\n            callbacks: Callbacks to pass to all subchains.\n            **kwargs: Additional parameters to pass when initializing\n                ConversationalRetrievalChain\n        \"\"\"\n        combine_docs_chain_kwargs = combine_docs_chain_kwargs or {}\n        doc_chain = load_qa_chain(\n            llm,\n            chain_type=chain_type,\n            verbose=verbose,\n            callbacks=callbacks,\n            **combine_docs_chain_kwargs,\n        )\n        _llm = condense_question_llm or llm\n        condense_question_chain = LLMChain(\n            llm=_llm,\n            prompt=condense_question_prompt,\n            verbose=verbose,\n            callbacks=callbacks,\n        )\n        return cls(\n            retriever=retriever,\n            combine_docs_chain=doc_chain,\n            question_generator=condense_question_chain,\n            callbacks=callbacks,\n            **kwargs,\n        )\n[docs]class ChatVectorDBChain(BaseConversationalRetrievalChain):\n    \"\"\"Chain for chatting with a vector database.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html"}
{"id": "6d8a26754629-9", "text": "\"\"\"Chain for chatting with a vector database.\"\"\"\n    vectorstore: VectorStore = Field(alias=\"vectorstore\")\n    top_k_docs_for_context: int = 4\n    search_kwargs: dict = Field(default_factory=dict)\n    @property\n    def _chain_type(self) -> str:\n        return \"chat-vector-db\"\n    @root_validator()\n    def raise_deprecation(cls, values: Dict) -> Dict:\n        warnings.warn(\n            \"`ChatVectorDBChain` is deprecated - \"\n            \"please use `from langchain.chains import ConversationalRetrievalChain`\"\n        )\n        return values\n    def _get_docs(\n        self,\n        question: str,\n        inputs: Dict[str, Any],\n        *,\n        run_manager: CallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs.\"\"\"\n        vectordbkwargs = inputs.get(\"vectordbkwargs\", {})\n        full_kwargs = {**self.search_kwargs, **vectordbkwargs}\n        return self.vectorstore.similarity_search(\n            question, k=self.top_k_docs_for_context, **full_kwargs\n        )\n    async def _aget_docs(\n        self,\n        question: str,\n        inputs: Dict[str, Any],\n        *,\n        run_manager: AsyncCallbackManagerForChainRun,\n    ) -> List[Document]:\n        \"\"\"Get docs.\"\"\"\n        raise NotImplementedError(\"ChatVectorDBChain does not support async\")\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        vectorstore: VectorStore,\n        condense_question_prompt: BasePromptTemplate = CONDENSE_QUESTION_PROMPT,\n        chain_type: str = \"stuff\",\n        combine_docs_chain_kwargs: Optional[Dict] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html"}
{"id": "6d8a26754629-10", "text": "combine_docs_chain_kwargs: Optional[Dict] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> BaseConversationalRetrievalChain:\n        \"\"\"Load chain from LLM.\"\"\"\n        combine_docs_chain_kwargs = combine_docs_chain_kwargs or {}\n        doc_chain = load_qa_chain(\n            llm,\n            chain_type=chain_type,\n            callbacks=callbacks,\n            **combine_docs_chain_kwargs,\n        )\n        condense_question_chain = LLMChain(\n            llm=llm, prompt=condense_question_prompt, callbacks=callbacks\n        )\n        return cls(\n            vectorstore=vectorstore,\n            combine_docs_chain=doc_chain,\n            question_generator=condense_question_chain,\n            callbacks=callbacks,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html"}
{"id": "0275cedc3677-0", "text": "Source code for langchain.vectorstores.xata\nfrom __future__ import annotations\nimport time\nfrom itertools import repeat\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Type\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\n[docs]class XataVectorStore(VectorStore):\n    \"\"\"`Xata` vector store.\n    It assumes you have a Xata database\n    created with the right schema. See the guide at:\n    https://integrations.langchain.com/vectorstores?integration_name=XataVectorStore\n    \"\"\"\n[docs]    def __init__(\n        self,\n        api_key: str,\n        db_url: str,\n        embedding: Embeddings,\n        table_name: str,\n    ) -> None:\n        \"\"\"Initialize with Xata client.\"\"\"\n        try:\n            from xata.client import XataClient  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"Could not import xata python package. \"\n                \"Please install it with `pip install xata`.\"\n            )\n        self._client = XataClient(api_key=api_key, db_url=db_url)\n        self._embedding: Embeddings = embedding\n        self._table_name = table_name or \"vectors\"\n    @property\n    def embeddings(self) -> Embeddings:\n        return self._embedding\n[docs]    def add_vectors(\n        self,\n        vectors: List[List[float]],\n        documents: List[Document],\n        ids: Optional[List[str]] = None,\n    ) -> List[str]:\n        return self._add_vectors(vectors, documents, ids)\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html"}
{"id": "0275cedc3677-1", "text": "[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[Dict[Any, Any]]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        ids = ids\n        docs = self._texts_to_documents(texts, metadatas)\n        vectors = self._embedding.embed_documents(list(texts))\n        return self.add_vectors(vectors, docs, ids)\n    def _add_vectors(\n        self,\n        vectors: List[List[float]],\n        documents: List[Document],\n        ids: Optional[List[str]] = None,\n    ) -> List[str]:\n        \"\"\"Add vectors to the Xata database.\"\"\"\n        rows: List[Dict[str, Any]] = []\n        for idx, embedding in enumerate(vectors):\n            row = {\n                \"content\": documents[idx].page_content,\n                \"embedding\": embedding,\n            }\n            if ids:\n                row[\"id\"] = ids[idx]\n            for key, val in documents[idx].metadata.items():\n                if key not in [\"id\", \"content\", \"embedding\"]:\n                    row[key] = val\n            rows.append(row)\n        # XXX: I would have liked to use the BulkProcessor here, but it\n        # doesn't return the IDs, which we need here. Manual chunking it is.\n        chunk_size = 1000\n        id_list: List[str] = []\n        for i in range(0, len(rows), chunk_size):\n            chunk = rows[i : i + chunk_size]\n            r = self._client.records().bulk_insert(self._table_name, {\"records\": chunk})\n            if r.status_code != 200:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html"}
{"id": "0275cedc3677-2", "text": "if r.status_code != 200:\n                raise Exception(f\"Error adding vectors to Xata: {r.status_code} {r}\")\n            id_list.extend(r[\"recordIDs\"])\n        return id_list\n    @staticmethod\n    def _texts_to_documents(\n        texts: Iterable[str],\n        metadatas: Optional[Iterable[Dict[Any, Any]]] = None,\n    ) -> List[Document]:\n        \"\"\"Return list of Documents from list of texts and metadatas.\"\"\"\n        if metadatas is None:\n            metadatas = repeat({})\n        docs = [\n            Document(page_content=text, metadata=metadata)\n            for text, metadata in zip(texts, metadatas)\n        ]\n        return docs\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[\"XataVectorStore\"],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        api_key: Optional[str] = None,\n        db_url: Optional[str] = None,\n        table_name: str = \"vectors\",\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> \"XataVectorStore\":\n        \"\"\"Return VectorStore initialized from texts and embeddings.\"\"\"\n        if not api_key or not db_url:\n            raise ValueError(\"Xata api_key and db_url must be set.\")\n        embeddings = embedding.embed_documents(texts)\n        ids = None  # Xata will generate them for us\n        docs = cls._texts_to_documents(texts, metadatas)\n        vector_db = cls(\n            api_key=api_key,\n            db_url=db_url,\n            embedding=embedding,\n            table_name=table_name,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html"}
{"id": "0275cedc3677-3", "text": "embedding=embedding,\n            table_name=table_name,\n        )\n        vector_db._add_vectors(embeddings, docs, ids)\n        return vector_db\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(query, k, filter=filter)\n        documents = [d[0] for d in docs_and_scores]\n        return documents\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Run similarity search with Chroma with distance.\n        Args:\n            query (str): Query text to search for.\n            k (int): Number of results to return. Defaults to 4.\n            filter (Optional[dict]): Filter by metadata. Defaults to None.\n        Returns:\n            List[Tuple[Document, float]]: List of documents most similar to the query\n                text with distance in float.\n        \"\"\"\n        embedding = self._embedding.embed_query(query)\n        payload = {\n            \"queryVector\": embedding,\n            \"column\": \"embedding\",\n            \"size\": k,\n        }\n        if filter:\n            payload[\"filter\"] = filter", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html"}
{"id": "0275cedc3677-4", "text": "}\n        if filter:\n            payload[\"filter\"] = filter\n        r = self._client.data().vector_search(self._table_name, payload=payload)\n        if r.status_code != 200:\n            raise Exception(f\"Error running similarity search: {r.status_code} {r}\")\n        hits = r[\"records\"]\n        docs_and_scores = [\n            (\n                Document(\n                    page_content=hit[\"content\"],\n                    metadata=self._extractMetadata(hit),\n                ),\n                hit[\"xata\"][\"score\"],\n            )\n            for hit in hits\n        ]\n        return docs_and_scores\n    def _extractMetadata(self, record: dict) -> dict:\n        \"\"\"Extract metadata from a record. Filters out known columns.\"\"\"\n        metadata = {}\n        for key, val in record.items():\n            if key not in [\"id\", \"content\", \"embedding\", \"xata\"]:\n                metadata[key] = val\n        return metadata\n[docs]    def delete(\n        self,\n        ids: Optional[List[str]] = None,\n        delete_all: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Delete by vector IDs.\n        Args:\n            ids: List of ids to delete.\n            delete_all: Delete all records in the table.\n        \"\"\"\n        if delete_all:\n            self._delete_all()\n            self.wait_for_indexing(ndocs=0)\n        elif ids is not None:\n            chunk_size = 500\n            for i in range(0, len(ids), chunk_size):\n                chunk = ids[i : i + chunk_size]\n                operations = [\n                    {\"delete\": {\"table\": self._table_name, \"id\": id}} for id in chunk\n                ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html"}
{"id": "0275cedc3677-5", "text": "]\n                self._client.records().transaction(payload={\"operations\": operations})\n        else:\n            raise ValueError(\"Either ids or delete_all must be set.\")\n    def _delete_all(self) -> None:\n        \"\"\"Delete all records in the table.\"\"\"\n        while True:\n            r = self._client.data().query(self._table_name, payload={\"columns\": [\"id\"]})\n            if r.status_code != 200:\n                raise Exception(f\"Error running query: {r.status_code} {r}\")\n            ids = [rec[\"id\"] for rec in r[\"records\"]]\n            if len(ids) == 0:\n                break\n            operations = [\n                {\"delete\": {\"table\": self._table_name, \"id\": id}} for id in ids\n            ]\n            self._client.records().transaction(payload={\"operations\": operations})\n[docs]    def wait_for_indexing(self, timeout: float = 5, ndocs: int = 1) -> None:\n        \"\"\"Wait for the search index to contain a certain number of\n        documents. Useful in tests.\n        \"\"\"\n        start = time.time()\n        while True:\n            r = self._client.data().search_table(\n                self._table_name, payload={\"query\": \"\", \"page\": {\"size\": 0}}\n            )\n            if r.status_code != 200:\n                raise Exception(f\"Error running search: {r.status_code} {r}\")\n            if r[\"totalCount\"] == ndocs:\n                break\n            if time.time() - start > timeout:\n                raise Exception(\"Timed out waiting for indexing to complete.\")\n            time.sleep(0.5)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html"}
{"id": "59e89252a429-0", "text": "Source code for langchain.vectorstores.chroma\nfrom __future__ import annotations\nimport base64\nimport logging\nimport uuid\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n)\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import xor_args\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nif TYPE_CHECKING:\n    import chromadb\n    import chromadb.config\n    from chromadb.api.types import ID, OneOrMany, Where, WhereDocument\nlogger = logging.getLogger()\nDEFAULT_K = 4  # Number of Documents to return.\ndef _results_to_docs(results: Any) -> List[Document]:\n    return [doc for doc, _ in _results_to_docs_and_scores(results)]\ndef _results_to_docs_and_scores(results: Any) -> List[Tuple[Document, float]]:\n    return [\n        # TODO: Chroma can do batch querying,\n        # we shouldn't hard code to the 1st result\n        (Document(page_content=result[0], metadata=result[1] or {}), result[2])\n        for result in zip(\n            results[\"documents\"][0],\n            results[\"metadatas\"][0],\n            results[\"distances\"][0],\n        )\n    ]\n[docs]class Chroma(VectorStore):\n    \"\"\"`ChromaDB` vector store.\n    To use, you should have the ``chromadb`` python package installed.\n    Example:\n        .. code-block:: python\n                from langchain.vectorstores import Chroma", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-1", "text": ".. code-block:: python\n                from langchain.vectorstores import Chroma\n                from langchain.embeddings.openai import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                vectorstore = Chroma(\"langchain_store\", embeddings)\n    \"\"\"\n    _LANGCHAIN_DEFAULT_COLLECTION_NAME = \"langchain\"\n[docs]    def __init__(\n        self,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        embedding_function: Optional[Embeddings] = None,\n        persist_directory: Optional[str] = None,\n        client_settings: Optional[chromadb.config.Settings] = None,\n        collection_metadata: Optional[Dict] = None,\n        client: Optional[chromadb.Client] = None,\n        relevance_score_fn: Optional[Callable[[float], float]] = None,\n    ) -> None:\n        \"\"\"Initialize with a Chroma client.\"\"\"\n        try:\n            import chromadb\n            import chromadb.config\n        except ImportError:\n            raise ImportError(\n                \"Could not import chromadb python package. \"\n                \"Please install it with `pip install chromadb`.\"\n            )\n        if client is not None:\n            self._client_settings = client_settings\n            self._client = client\n            self._persist_directory = persist_directory\n        else:\n            if client_settings:\n                # If client_settings is provided with persist_directory specified,\n                # then it is \"in-memory and persisting to disk\" mode.\n                client_settings.persist_directory = (\n                    persist_directory or client_settings.persist_directory\n                )\n                if client_settings.persist_directory is not None:\n                    # Maintain backwards compatibility with chromadb < 0.4.0\n                    major, minor, _ = chromadb.__version__.split(\".\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-2", "text": "major, minor, _ = chromadb.__version__.split(\".\")\n                    if int(major) == 0 and int(minor) < 4:\n                        client_settings.chroma_db_impl = \"duckdb+parquet\"\n                _client_settings = client_settings\n            elif persist_directory:\n                # Maintain backwards compatibility with chromadb < 0.4.0\n                major, minor, _ = chromadb.__version__.split(\".\")\n                if int(major) == 0 and int(minor) < 4:\n                    _client_settings = chromadb.config.Settings(\n                        chroma_db_impl=\"duckdb+parquet\",\n                    )\n                else:\n                    _client_settings = chromadb.config.Settings(is_persistent=True)\n                _client_settings.persist_directory = persist_directory\n            else:\n                _client_settings = chromadb.config.Settings()\n            self._client_settings = _client_settings\n            self._client = chromadb.Client(_client_settings)\n            self._persist_directory = (\n                _client_settings.persist_directory or persist_directory\n            )\n        self._embedding_function = embedding_function\n        self._collection = self._client.get_or_create_collection(\n            name=collection_name,\n            embedding_function=None,\n            metadata=collection_metadata,\n        )\n        self.override_relevance_score_fn = relevance_score_fn\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return self._embedding_function\n    @xor_args((\"query_texts\", \"query_embeddings\"))\n    def __query_collection(\n        self,\n        query_texts: Optional[List[str]] = None,\n        query_embeddings: Optional[List[List[float]]] = None,\n        n_results: int = 4,\n        where: Optional[Dict[str, str]] = None,\n        where_document: Optional[Dict[str, str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-3", "text": "where_document: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Query the chroma collection.\"\"\"\n        try:\n            import chromadb  # noqa: F401\n        except ImportError:\n            raise ValueError(\n                \"Could not import chromadb python package. \"\n                \"Please install it with `pip install chromadb`.\"\n            )\n        return self._collection.query(\n            query_texts=query_texts,\n            query_embeddings=query_embeddings,\n            n_results=n_results,\n            where=where,\n            where_document=where_document,\n            **kwargs,\n        )\n[docs]    def encode_image(self, uri: str) -> str:\n        \"\"\"Get base64 string from image URI.\"\"\"\n        with open(uri, \"rb\") as image_file:\n            return base64.b64encode(image_file.read()).decode(\"utf-8\")\n[docs]    def add_images(\n        self,\n        uris: List[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more images through the embeddings and add to the vectorstore.\n        Args:\n            images (List[List[float]]): Images to add to the vectorstore.\n            metadatas (Optional[List[dict]], optional): Optional list of metadatas.\n            ids (Optional[List[str]], optional): Optional list of IDs.\n        Returns:\n            List[str]: List of IDs of the added images.\n        \"\"\"\n        # Map from uris to b64 encoded strings\n        b64_texts = [self.encode_image(uri=uri) for uri in uris]\n        # Populate IDs\n        if ids is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-4", "text": "# Populate IDs\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in uris]\n        embeddings = None\n        # Set embeddings\n        if self._embedding_function is not None and hasattr(\n            self._embedding_function, \"embed_image\"\n        ):\n            embeddings = self._embedding_function.embed_image(uris=uris)\n        if metadatas:\n            # fill metadatas with empty dicts if somebody\n            # did not specify metadata for all images\n            length_diff = len(uris) - len(metadatas)\n            if length_diff:\n                metadatas = metadatas + [{}] * length_diff\n            empty_ids = []\n            non_empty_ids = []\n            for idx, m in enumerate(metadatas):\n                if m:\n                    non_empty_ids.append(idx)\n                else:\n                    empty_ids.append(idx)\n            if non_empty_ids:\n                metadatas = [metadatas[idx] for idx in non_empty_ids]\n                images_with_metadatas = [uris[idx] for idx in non_empty_ids]\n                embeddings_with_metadatas = (\n                    [embeddings[idx] for idx in non_empty_ids] if embeddings else None\n                )\n                ids_with_metadata = [ids[idx] for idx in non_empty_ids]\n                try:\n                    self._collection.upsert(\n                        metadatas=metadatas,\n                        embeddings=embeddings_with_metadatas,\n                        documents=images_with_metadatas,\n                        ids=ids_with_metadata,\n                    )\n                except ValueError as e:\n                    if \"Expected metadata value to be\" in str(e):\n                        msg = (\n                            \"Try filtering complex metadata using \"\n                            \"langchain.vectorstores.utils.filter_complex_metadata.\"\n                        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-5", "text": "\"langchain.vectorstores.utils.filter_complex_metadata.\"\n                        )\n                        raise ValueError(e.args[0] + \"\\n\\n\" + msg)\n                    else:\n                        raise e\n            if empty_ids:\n                images_without_metadatas = [uris[j] for j in empty_ids]\n                embeddings_without_metadatas = (\n                    [embeddings[j] for j in empty_ids] if embeddings else None\n                )\n                ids_without_metadatas = [ids[j] for j in empty_ids]\n                self._collection.upsert(\n                    embeddings=embeddings_without_metadatas,\n                    documents=images_without_metadatas,\n                    ids=ids_without_metadatas,\n                )\n        else:\n            self._collection.upsert(\n                embeddings=embeddings,\n                documents=b64_texts,\n                ids=ids,\n            )\n        return ids\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts (Iterable[str]): Texts to add to the vectorstore.\n            metadatas (Optional[List[dict]], optional): Optional list of metadatas.\n            ids (Optional[List[str]], optional): Optional list of IDs.\n        Returns:\n            List[str]: List of IDs of the added texts.\n        \"\"\"\n        # TODO: Handle the case where the user doesn't provide ids on the Collection\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        embeddings = None\n        texts = list(texts)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-6", "text": "embeddings = None\n        texts = list(texts)\n        if self._embedding_function is not None:\n            embeddings = self._embedding_function.embed_documents(texts)\n        if metadatas:\n            # fill metadatas with empty dicts if somebody\n            # did not specify metadata for all texts\n            length_diff = len(texts) - len(metadatas)\n            if length_diff:\n                metadatas = metadatas + [{}] * length_diff\n            empty_ids = []\n            non_empty_ids = []\n            for idx, m in enumerate(metadatas):\n                if m:\n                    non_empty_ids.append(idx)\n                else:\n                    empty_ids.append(idx)\n            if non_empty_ids:\n                metadatas = [metadatas[idx] for idx in non_empty_ids]\n                texts_with_metadatas = [texts[idx] for idx in non_empty_ids]\n                embeddings_with_metadatas = (\n                    [embeddings[idx] for idx in non_empty_ids] if embeddings else None\n                )\n                ids_with_metadata = [ids[idx] for idx in non_empty_ids]\n                try:\n                    self._collection.upsert(\n                        metadatas=metadatas,\n                        embeddings=embeddings_with_metadatas,\n                        documents=texts_with_metadatas,\n                        ids=ids_with_metadata,\n                    )\n                except ValueError as e:\n                    if \"Expected metadata value to be\" in str(e):\n                        msg = (\n                            \"Try filtering complex metadata from the document using \"\n                            \"langchain.vectorstores.utils.filter_complex_metadata.\"\n                        )\n                        raise ValueError(e.args[0] + \"\\n\\n\" + msg)\n                    else:\n                        raise e\n            if empty_ids:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-7", "text": "else:\n                        raise e\n            if empty_ids:\n                texts_without_metadatas = [texts[j] for j in empty_ids]\n                embeddings_without_metadatas = (\n                    [embeddings[j] for j in empty_ids] if embeddings else None\n                )\n                ids_without_metadatas = [ids[j] for j in empty_ids]\n                self._collection.upsert(\n                    embeddings=embeddings_without_metadatas,\n                    documents=texts_without_metadatas,\n                    ids=ids_without_metadatas,\n                )\n        else:\n            self._collection.upsert(\n                embeddings=embeddings,\n                documents=texts,\n                ids=ids,\n            )\n        return ids\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = DEFAULT_K,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Run similarity search with Chroma.\n        Args:\n            query (str): Query text to search for.\n            k (int): Number of results to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List[Document]: List of documents most similar to the query text.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(query, k, filter=filter)\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = DEFAULT_K,\n        filter: Optional[Dict[str, str]] = None,\n        where_document: Optional[Dict[str, str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-8", "text": "where_document: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding (List[float]): Embedding to look up documents similar to.\n            k (int): Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query vector.\n        \"\"\"\n        results = self.__query_collection(\n            query_embeddings=embedding,\n            n_results=k,\n            where=filter,\n            where_document=where_document,\n        )\n        return _results_to_docs(results)\n[docs]    def similarity_search_by_vector_with_relevance_scores(\n        self,\n        embedding: List[float],\n        k: int = DEFAULT_K,\n        filter: Optional[Dict[str, str]] = None,\n        where_document: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Return docs most similar to embedding vector and similarity score.\n        Args:\n            embedding (List[float]): Embedding to look up documents similar to.\n            k (int): Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List[Tuple[Document, float]]: List of documents most similar to\n            the query text and cosine distance in float for each.\n            Lower score represents more similarity.\n        \"\"\"\n        results = self.__query_collection(\n            query_embeddings=embedding,\n            n_results=k,\n            where=filter,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-9", "text": "query_embeddings=embedding,\n            n_results=k,\n            where=filter,\n            where_document=where_document,\n        )\n        return _results_to_docs_and_scores(results)\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = DEFAULT_K,\n        filter: Optional[Dict[str, str]] = None,\n        where_document: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Run similarity search with Chroma with distance.\n        Args:\n            query (str): Query text to search for.\n            k (int): Number of results to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List[Tuple[Document, float]]: List of documents most similar to\n            the query text and cosine distance in float for each.\n            Lower score represents more similarity.\n        \"\"\"\n        if self._embedding_function is None:\n            results = self.__query_collection(\n                query_texts=[query],\n                n_results=k,\n                where=filter,\n                where_document=where_document,\n            )\n        else:\n            query_embedding = self._embedding_function.embed_query(query)\n            results = self.__query_collection(\n                query_embeddings=[query_embedding],\n                n_results=k,\n                where=filter,\n                where_document=where_document,\n            )\n        return _results_to_docs_and_scores(results)\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        \"\"\"\n        The 'correct' relevance function\n        may differ depending on a few things, including:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-10", "text": "The 'correct' relevance function\n        may differ depending on a few things, including:\n        - the distance / similarity metric used by the VectorStore\n        - the scale of your embeddings (OpenAI's are unit normed. Many others are not!)\n        - embedding dimensionality\n        - etc.\n        \"\"\"\n        if self.override_relevance_score_fn:\n            return self.override_relevance_score_fn\n        distance = \"l2\"\n        distance_key = \"hnsw:space\"\n        metadata = self._collection.metadata\n        if metadata and distance_key in metadata:\n            distance = metadata[distance_key]\n        if distance == \"cosine\":\n            return self._cosine_relevance_score_fn\n        elif distance == \"l2\":\n            return self._euclidean_relevance_score_fn\n        elif distance == \"ip\":\n            return self._max_inner_product_relevance_score_fn\n        else:\n            raise ValueError(\n                \"No supported normalization function\"\n                f\" for distance metric of type: {distance}.\"\n                \"Consider providing relevance_score_fn to Chroma constructor.\"\n            )\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = DEFAULT_K,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, str]] = None,\n        where_document: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-11", "text": "Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        results = self.__query_collection(\n            query_embeddings=embedding,\n            n_results=fetch_k,\n            where=filter,\n            where_document=where_document,\n            include=[\"metadatas\", \"documents\", \"distances\", \"embeddings\"],\n        )\n        mmr_selected = maximal_marginal_relevance(\n            np.array(embedding, dtype=np.float32),\n            results[\"embeddings\"][0],\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        candidates = _results_to_docs(results)\n        selected_results = [r for i, r in enumerate(candidates) if i in mmr_selected]\n        return selected_results\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = DEFAULT_K,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, str]] = None,\n        where_document: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-12", "text": ") -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        if self._embedding_function is None:\n            raise ValueError(\n                \"For MMR search, you must specify an embedding function on\" \"creation.\"\n            )\n        embedding = self._embedding_function.embed_query(query)\n        docs = self.max_marginal_relevance_search_by_vector(\n            embedding,\n            k,\n            fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n            where_document=where_document,\n        )\n        return docs\n[docs]    def delete_collection(self) -> None:\n        \"\"\"Delete the collection.\"\"\"\n        self._client.delete_collection(self._collection.name)\n[docs]    def get(\n        self,\n        ids: Optional[OneOrMany[ID]] = None,\n        where: Optional[Where] = None,\n        limit: Optional[int] = None,\n        offset: Optional[int] = None,\n        where_document: Optional[WhereDocument] = None,\n        include: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-13", "text": "include: Optional[List[str]] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Gets the collection.\n        Args:\n            ids: The ids of the embeddings to get. Optional.\n            where: A Where type dict used to filter results by.\n                   E.g. `{\"color\" : \"red\", \"price\": 4.20}`. Optional.\n            limit: The number of documents to return. Optional.\n            offset: The offset to start returning results from.\n                    Useful for paging results with limit. Optional.\n            where_document: A WhereDocument type dict used to filter by the documents.\n                            E.g. `{$contains: \"hello\"}`. Optional.\n            include: A list of what to include in the results.\n                     Can contain `\"embeddings\"`, `\"metadatas\"`, `\"documents\"`.\n                     Ids are always included.\n                     Defaults to `[\"metadatas\", \"documents\"]`. Optional.\n        \"\"\"\n        kwargs = {\n            \"ids\": ids,\n            \"where\": where,\n            \"limit\": limit,\n            \"offset\": offset,\n            \"where_document\": where_document,\n        }\n        if include is not None:\n            kwargs[\"include\"] = include\n        return self._collection.get(**kwargs)\n[docs]    def persist(self) -> None:\n        \"\"\"Persist the collection.\n        This can be used to explicitly persist the data to disk.\n        It will also be called automatically when the object is destroyed.\n        \"\"\"\n        if self._persist_directory is None:\n            raise ValueError(\n                \"You must specify a persist_directory on\"\n                \"creation to persist the collection.\"\n            )\n        import chromadb\n        # Maintain backwards compatibility with chromadb < 0.4.0", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-14", "text": "# Maintain backwards compatibility with chromadb < 0.4.0\n        major, minor, _ = chromadb.__version__.split(\".\")\n        if int(major) == 0 and int(minor) < 4:\n            self._client.persist()\n[docs]    def update_document(self, document_id: str, document: Document) -> None:\n        \"\"\"Update a document in the collection.\n        Args:\n            document_id (str): ID of the document to update.\n            document (Document): Document to update.\n        \"\"\"\n        return self.update_documents([document_id], [document])\n[docs]    def update_documents(self, ids: List[str], documents: List[Document]) -> None:\n        \"\"\"Update a document in the collection.\n        Args:\n            ids (List[str]): List of ids of the document to update.\n            documents (List[Document]): List of documents to update.\n        \"\"\"\n        text = [document.page_content for document in documents]\n        metadata = [document.metadata for document in documents]\n        if self._embedding_function is None:\n            raise ValueError(\n                \"For update, you must specify an embedding function on creation.\"\n            )\n        embeddings = self._embedding_function.embed_documents(text)\n        if hasattr(\n            self._collection._client, \"max_batch_size\"\n        ):  # for Chroma 0.4.10 and above\n            from chromadb.utils.batch_utils import create_batches\n            for batch in create_batches(\n                api=self._collection._client,\n                ids=ids,\n                metadatas=metadata,\n                documents=text,\n                embeddings=embeddings,\n            ):\n                self._collection.update(\n                    ids=batch[0],\n                    embeddings=batch[1],\n                    documents=batch[3],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-15", "text": "embeddings=batch[1],\n                    documents=batch[3],\n                    metadatas=batch[2],\n                )\n        else:\n            self._collection.update(\n                ids=ids,\n                embeddings=embeddings,\n                documents=text,\n                metadatas=metadata,\n            )\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[Chroma],\n        texts: List[str],\n        embedding: Optional[Embeddings] = None,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        persist_directory: Optional[str] = None,\n        client_settings: Optional[chromadb.config.Settings] = None,\n        client: Optional[chromadb.Client] = None,\n        collection_metadata: Optional[Dict] = None,\n        **kwargs: Any,\n    ) -> Chroma:\n        \"\"\"Create a Chroma vectorstore from a raw documents.\n        If a persist_directory is specified, the collection will be persisted there.\n        Otherwise, the data will be ephemeral in-memory.\n        Args:\n            texts (List[str]): List of texts to add to the collection.\n            collection_name (str): Name of the collection to create.\n            persist_directory (Optional[str]): Directory to persist the collection.\n            embedding (Optional[Embeddings]): Embedding function. Defaults to None.\n            metadatas (Optional[List[dict]]): List of metadatas. Defaults to None.\n            ids (Optional[List[str]]): List of document IDs. Defaults to None.\n            client_settings (Optional[chromadb.config.Settings]): Chroma client settings\n            collection_metadata (Optional[Dict]): Collection configurations.\n                                                  Defaults to None.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-16", "text": "Defaults to None.\n        Returns:\n            Chroma: Chroma vectorstore.\n        \"\"\"\n        chroma_collection = cls(\n            collection_name=collection_name,\n            embedding_function=embedding,\n            persist_directory=persist_directory,\n            client_settings=client_settings,\n            client=client,\n            collection_metadata=collection_metadata,\n            **kwargs,\n        )\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        if hasattr(\n            chroma_collection._client, \"max_batch_size\"\n        ):  # for Chroma 0.4.10 and above\n            from chromadb.utils.batch_utils import create_batches\n            for batch in create_batches(\n                api=chroma_collection._client,\n                ids=ids,\n                metadatas=metadatas,\n                documents=texts,\n            ):\n                chroma_collection.add_texts(\n                    texts=batch[3] if batch[3] else [],\n                    metadatas=batch[2] if batch[2] else None,\n                    ids=batch[0],\n                )\n        else:\n            chroma_collection.add_texts(texts=texts, metadatas=metadatas, ids=ids)\n        return chroma_collection\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[Chroma],\n        documents: List[Document],\n        embedding: Optional[Embeddings] = None,\n        ids: Optional[List[str]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        persist_directory: Optional[str] = None,\n        client_settings: Optional[chromadb.config.Settings] = None,\n        client: Optional[chromadb.Client] = None,  # Add this line\n        collection_metadata: Optional[Dict] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "59e89252a429-17", "text": "collection_metadata: Optional[Dict] = None,\n        **kwargs: Any,\n    ) -> Chroma:\n        \"\"\"Create a Chroma vectorstore from a list of documents.\n        If a persist_directory is specified, the collection will be persisted there.\n        Otherwise, the data will be ephemeral in-memory.\n        Args:\n            collection_name (str): Name of the collection to create.\n            persist_directory (Optional[str]): Directory to persist the collection.\n            ids (Optional[List[str]]): List of document IDs. Defaults to None.\n            documents (List[Document]): List of documents to add to the vectorstore.\n            embedding (Optional[Embeddings]): Embedding function. Defaults to None.\n            client_settings (Optional[chromadb.config.Settings]): Chroma client settings\n            collection_metadata (Optional[Dict]): Collection configurations.\n                                                  Defaults to None.\n        Returns:\n            Chroma: Chroma vectorstore.\n        \"\"\"\n        texts = [doc.page_content for doc in documents]\n        metadatas = [doc.metadata for doc in documents]\n        return cls.from_texts(\n            texts=texts,\n            embedding=embedding,\n            metadatas=metadatas,\n            ids=ids,\n            collection_name=collection_name,\n            persist_directory=persist_directory,\n            client_settings=client_settings,\n            client=client,\n            collection_metadata=collection_metadata,\n            **kwargs,\n        )\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None:\n        \"\"\"Delete by vector IDs.\n        Args:\n            ids: List of ids to delete.\n        \"\"\"\n        self._collection.delete(ids=ids)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html"}
{"id": "3454d191cb44-0", "text": "Source code for langchain.vectorstores.starrocks\nfrom __future__ import annotations\nimport json\nimport logging\nfrom hashlib import sha1\nfrom threading import Thread\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import BaseSettings\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nlogger = logging.getLogger()\nDEBUG = False\n[docs]def has_mul_sub_str(s: str, *args: Any) -> bool:\n    \"\"\"\n    Check if a string has multiple substrings.\n    Args:\n        s: The string to check\n        *args: The substrings to check for in the string\n    Returns:\n        bool: True if all substrings are present in the string, False otherwise\n    \"\"\"\n    for a in args:\n        if a not in s:\n            return False\n    return True\n[docs]def debug_output(s: Any) -> None:\n    \"\"\"\n    Print a debug message if DEBUG is True.\n    Args:\n        s: The message to print\n    \"\"\"\n    if DEBUG:\n        print(s)\n[docs]def get_named_result(connection: Any, query: str) -> List[dict[str, Any]]:\n    \"\"\"\n    Get a named result from a query.\n    Args:\n        connection: The connection to the database\n        query: The query to execute\n    Returns:\n        List[dict[str, Any]]: The result of the query\n    \"\"\"\n    cursor = connection.cursor()\n    cursor.execute(query)\n    columns = cursor.description\n    result = []\n    for value in cursor.fetchall():\n        r = {}\n        for idx, datum in enumerate(value):\n            k = columns[idx][0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html"}
{"id": "3454d191cb44-1", "text": "for idx, datum in enumerate(value):\n            k = columns[idx][0]\n            r[k] = datum\n        result.append(r)\n    debug_output(result)\n    cursor.close()\n    return result\n[docs]class StarRocksSettings(BaseSettings):\n    \"\"\"StarRocks client configuration.\n    Attribute:\n        StarRocks_host (str) : An URL to connect to MyScale backend.\n                             Defaults to 'localhost'.\n        StarRocks_port (int) : URL port to connect with HTTP. Defaults to 8443.\n        username (str) : Username to login. Defaults to None.\n        password (str) : Password to login. Defaults to None.\n        database (str) : Database name to find the table. Defaults to 'default'.\n        table (str) : Table name to operate on.\n                      Defaults to 'vector_table'.\n        column_map (Dict) : Column type map to project column name onto langchain\n                            semantics. Must have keys: `text`, `id`, `vector`,\n                            must be same size to number of columns. For example:\n                            .. code-block:: python\n                                {\n                                    'id': 'text_id',\n                                    'embedding': 'text_embedding',\n                                    'document': 'text_plain',\n                                    'metadata': 'metadata_dictionary_in_json',\n                                }\n                            Defaults to identity map.\n    \"\"\"\n    host: str = \"localhost\"\n    port: int = 9030\n    username: str = \"root\"\n    password: str = \"\"\n    column_map: Dict[str, str] = {\n        \"id\": \"id\",\n        \"document\": \"document\",\n        \"embedding\": \"embedding\",\n        \"metadata\": \"metadata\",\n    }\n    database: str = \"default\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html"}
{"id": "3454d191cb44-2", "text": "\"metadata\": \"metadata\",\n    }\n    database: str = \"default\"\n    table: str = \"langchain\"\n    def __getitem__(self, item: str) -> Any:\n        return getattr(self, item)\n    class Config:\n        env_file = \".env\"\n        env_prefix = \"starrocks_\"\n        env_file_encoding = \"utf-8\"\n[docs]class StarRocks(VectorStore):\n    \"\"\"`StarRocks` vector store.\n    You need a `pymysql` python package, and a valid account\n    to connect to StarRocks.\n    Right now StarRocks has only implemented `cosine_similarity` function to\n    compute distance between two vectors. And there is no vector inside right now,\n    so we have to iterate all vectors and compute spatial distance.\n    For more information, please visit\n        [StarRocks official site](https://www.starrocks.io/)\n        [StarRocks github](https://github.com/StarRocks/starrocks)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        config: Optional[StarRocksSettings] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"StarRocks Wrapper to LangChain\n        embedding_function (Embeddings):\n        config (StarRocksSettings): Configuration to StarRocks Client\n        \"\"\"\n        try:\n            import pymysql  # type: ignore[import]\n        except ImportError:\n            raise ImportError(\n                \"Could not import pymysql python package. \"\n                \"Please install it with `pip install pymysql`.\"\n            )\n        try:\n            from tqdm import tqdm\n            self.pgbar = tqdm\n        except ImportError:\n            # Just in case if tqdm is not installed", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html"}
{"id": "3454d191cb44-3", "text": "except ImportError:\n            # Just in case if tqdm is not installed\n            self.pgbar = lambda x, **kwargs: x\n        super().__init__()\n        if config is not None:\n            self.config = config\n        else:\n            self.config = StarRocksSettings()\n        assert self.config\n        assert self.config.host and self.config.port\n        assert self.config.column_map and self.config.database and self.config.table\n        for k in [\"id\", \"embedding\", \"document\", \"metadata\"]:\n            assert k in self.config.column_map\n        # initialize the schema\n        dim = len(embedding.embed_query(\"test\"))\n        self.schema = f\"\"\"\\\nCREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}(    \n    {self.config.column_map['id']} string,\n    {self.config.column_map['document']} string,\n    {self.config.column_map['embedding']} array<float>,\n    {self.config.column_map['metadata']} string\n) ENGINE = OLAP PRIMARY KEY(id) DISTRIBUTED BY HASH(id) \\\n  PROPERTIES (\"replication_num\" = \"1\")\\\n\"\"\"\n        self.dim = dim\n        self.BS = \"\\\\\"\n        self.must_escape = (\"\\\\\", \"'\")\n        self.embedding_function = embedding\n        self.dist_order = \"DESC\"\n        debug_output(self.config)\n        # Create a connection to StarRocks\n        self.connection = pymysql.connect(\n            host=self.config.host,\n            port=self.config.port,\n            user=self.config.username,\n            password=self.config.password,\n            database=self.config.database,\n            **kwargs,\n        )\n        debug_output(self.schema)\n        get_named_result(self.connection, self.schema)\n[docs]    def escape_str(self, value: str) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html"}
{"id": "3454d191cb44-4", "text": "[docs]    def escape_str(self, value: str) -> str:\n        return \"\".join(f\"{self.BS}{c}\" if c in self.must_escape else c for c in value)\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding_function\n    def _build_insert_sql(self, transac: Iterable, column_names: Iterable[str]) -> str:\n        ks = \",\".join(column_names)\n        embed_tuple_index = tuple(column_names).index(\n            self.config.column_map[\"embedding\"]\n        )\n        _data = []\n        for n in transac:\n            n = \",\".join(\n                [\n                    f\"'{self.escape_str(str(_n))}'\"\n                    if idx != embed_tuple_index\n                    else f\"array<float>{str(_n)}\"\n                    for (idx, _n) in enumerate(n)\n                ]\n            )\n            _data.append(f\"({n})\")\n        i_str = f\"\"\"\n                INSERT INTO\n                    {self.config.database}.{self.config.table}({ks})\n                VALUES\n                {','.join(_data)}\n                \"\"\"\n        return i_str\n    def _insert(self, transac: Iterable, column_names: Iterable[str]) -> None:\n        _insert_query = self._build_insert_sql(transac, column_names)\n        debug_output(_insert_query)\n        get_named_result(self.connection, _insert_query)\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        batch_size: int = 32,\n        ids: Optional[Iterable[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Insert more texts through the embeddings and add to the VectorStore.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html"}
{"id": "3454d191cb44-5", "text": "\"\"\"Insert more texts through the embeddings and add to the VectorStore.\n        Args:\n            texts: Iterable of strings to add to the VectorStore.\n            ids: Optional list of ids to associate with the texts.\n            batch_size: Batch size of insertion\n            metadata: Optional column data to be inserted\n        Returns:\n            List of ids from adding the texts into the VectorStore.\n        \"\"\"\n        # Embed and create the documents\n        ids = ids or [sha1(t.encode(\"utf-8\")).hexdigest() for t in texts]\n        colmap_ = self.config.column_map\n        transac = []\n        column_names = {\n            colmap_[\"id\"]: ids,\n            colmap_[\"document\"]: texts,\n            colmap_[\"embedding\"]: self.embedding_function.embed_documents(list(texts)),\n        }\n        metadatas = metadatas or [{} for _ in texts]\n        column_names[colmap_[\"metadata\"]] = map(json.dumps, metadatas)\n        assert len(set(colmap_) - set(column_names)) >= 0\n        keys, values = zip(*column_names.items())\n        try:\n            t = None\n            for v in self.pgbar(\n                zip(*values), desc=\"Inserting data...\", total=len(metadatas)\n            ):\n                assert (\n                    len(v[keys.index(self.config.column_map[\"embedding\"])]) == self.dim\n                )\n                transac.append(v)\n                if len(transac) == batch_size:\n                    if t:\n                        t.join()\n                    t = Thread(target=self._insert, args=[transac, keys])\n                    t.start()\n                    transac = []\n            if len(transac) > 0:\n                if t:\n                    t.join()\n                self._insert(transac, keys)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html"}
{"id": "3454d191cb44-6", "text": "if t:\n                    t.join()\n                self._insert(transac, keys)\n            return [i for i in ids]\n        except Exception as e:\n            logger.error(f\"\\033[91m\\033[1m{type(e)}\\033[0m \\033[95m{str(e)}\\033[0m\")\n            return []\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[Dict[Any, Any]]] = None,\n        config: Optional[StarRocksSettings] = None,\n        text_ids: Optional[Iterable[str]] = None,\n        batch_size: int = 32,\n        **kwargs: Any,\n    ) -> StarRocks:\n        \"\"\"Create StarRocks wrapper with existing texts\n        Args:\n            embedding_function (Embeddings): Function to extract text embedding\n            texts (Iterable[str]): List or tuple of strings to be added\n            config (StarRocksSettings, Optional): StarRocks configuration\n            text_ids (Optional[Iterable], optional): IDs for the texts.\n                                                     Defaults to None.\n            batch_size (int, optional): Batchsize when transmitting data to StarRocks.\n                                        Defaults to 32.\n            metadata (List[dict], optional): metadata to texts. Defaults to None.\n        Returns:\n            StarRocks Index\n        \"\"\"\n        ctx = cls(embedding, config, **kwargs)\n        ctx.add_texts(texts, ids=text_ids, batch_size=batch_size, metadatas=metadatas)\n        return ctx\n    def __repr__(self) -> str:\n        \"\"\"Text representation for StarRocks Vector Store, prints backends, username", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html"}
{"id": "3454d191cb44-7", "text": "\"\"\"Text representation for StarRocks Vector Store, prints backends, username\n            and schemas. Easy to use with `str(StarRocks())`\n        Returns:\n            repr: string to show connection info and data schema\n        \"\"\"\n        _repr = f\"\\033[92m\\033[1m{self.config.database}.{self.config.table} @ \"\n        _repr += f\"{self.config.host}:{self.config.port}\\033[0m\\n\\n\"\n        _repr += f\"\\033[1musername: {self.config.username}\\033[0m\\n\\nTable Schema:\\n\"\n        width = 25\n        fields = 3\n        _repr += \"-\" * (width * fields + 1) + \"\\n\"\n        columns = [\"name\", \"type\", \"key\"]\n        _repr += f\"|\\033[94m{columns[0]:24s}\\033[0m|\\033[96m{columns[1]:24s}\"\n        _repr += f\"\\033[0m|\\033[96m{columns[2]:24s}\\033[0m|\\n\"\n        _repr += \"-\" * (width * fields + 1) + \"\\n\"\n        q_str = f\"DESC {self.config.database}.{self.config.table}\"\n        debug_output(q_str)\n        rs = get_named_result(self.connection, q_str)\n        for r in rs:\n            _repr += f\"|\\033[94m{r['Field']:24s}\\033[0m|\\033[96m{r['Type']:24s}\"\n            _repr += f\"\\033[0m|\\033[96m{r['Key']:24s}\\033[0m|\\n\"\n        _repr += \"-\" * (width * fields + 1) + \"\\n\"\n        return _repr", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html"}
{"id": "3454d191cb44-8", "text": "return _repr\n    def _build_query_sql(\n        self, q_emb: List[float], topk: int, where_str: Optional[str] = None\n    ) -> str:\n        q_emb_str = \",\".join(map(str, q_emb))\n        if where_str:\n            where_str = f\"WHERE {where_str}\"\n        else:\n            where_str = \"\"\n        q_str = f\"\"\"\n            SELECT {self.config.column_map['document']}, \n                {self.config.column_map['metadata']}, \n                cosine_similarity_norm(array<float>[{q_emb_str}],\n                  {self.config.column_map['embedding']}) as dist\n            FROM {self.config.database}.{self.config.table}\n            {where_str}\n            ORDER BY dist {self.dist_order}\n            LIMIT {topk}\n            \"\"\"\n        debug_output(q_str)\n        return q_str\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Perform a similarity search with StarRocks\n        Args:\n            query (str): query string\n            k (int, optional): Top K neighbors to retrieve. Defaults to 4.\n            where_str (Optional[str], optional): where condition string.\n                                                 Defaults to None.\n            NOTE: Please do not let end-user to fill this and always be aware\n                  of SQL injection. When dealing with metadatas, remember to\n                  use `{self.metadata_column}.attribute` instead of `attribute`\n                  alone. The default name for it is `metadata`.\n        Returns:\n            List[Document]: List of Documents\n        \"\"\"\n        return self.similarity_search_by_vector(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html"}
{"id": "3454d191cb44-9", "text": "\"\"\"\n        return self.similarity_search_by_vector(\n            self.embedding_function.embed_query(query), k, where_str, **kwargs\n        )\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        where_str: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform a similarity search with StarRocks by vectors\n        Args:\n            query (str): query string\n            k (int, optional): Top K neighbors to retrieve. Defaults to 4.\n            where_str (Optional[str], optional): where condition string.\n                                                 Defaults to None.\n            NOTE: Please do not let end-user to fill this and always be aware\n                  of SQL injection. When dealing with metadatas, remember to\n                  use `{self.metadata_column}.attribute` instead of `attribute`\n                  alone. The default name for it is `metadata`.\n        Returns:\n            List[Document]: List of (Document, similarity)\n        \"\"\"\n        q_str = self._build_query_sql(embedding, k, where_str)\n        try:\n            return [\n                Document(\n                    page_content=r[self.config.column_map[\"document\"]],\n                    metadata=json.loads(r[self.config.column_map[\"metadata\"]]),\n                )\n                for r in get_named_result(self.connection, q_str)\n            ]\n        except Exception as e:\n            logger.error(f\"\\033[91m\\033[1m{type(e)}\\033[0m \\033[95m{str(e)}\\033[0m\")\n            return []\n[docs]    def similarity_search_with_relevance_scores(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html"}
{"id": "3454d191cb44-10", "text": "return []\n[docs]    def similarity_search_with_relevance_scores(\n        self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Perform a similarity search with StarRocks\n        Args:\n            query (str): query string\n            k (int, optional): Top K neighbors to retrieve. Defaults to 4.\n            where_str (Optional[str], optional): where condition string.\n                                                 Defaults to None.\n            NOTE: Please do not let end-user to fill this and always be aware\n                  of SQL injection. When dealing with metadatas, remember to\n                  use `{self.metadata_column}.attribute` instead of `attribute`\n                  alone. The default name for it is `metadata`.\n        Returns:\n            List[Document]: List of documents\n        \"\"\"\n        q_str = self._build_query_sql(\n            self.embedding_function.embed_query(query), k, where_str\n        )\n        try:\n            return [\n                (\n                    Document(\n                        page_content=r[self.config.column_map[\"document\"]],\n                        metadata=json.loads(r[self.config.column_map[\"metadata\"]]),\n                    ),\n                    r[\"dist\"],\n                )\n                for r in get_named_result(self.connection, q_str)\n            ]\n        except Exception as e:\n            logger.error(f\"\\033[91m\\033[1m{type(e)}\\033[0m \\033[95m{str(e)}\\033[0m\")\n            return []\n[docs]    def drop(self) -> None:\n        \"\"\"\n        Helper function: Drop data\n        \"\"\"\n        get_named_result(\n            self.connection,\n            f\"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}\",\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html"}
{"id": "3454d191cb44-11", "text": "f\"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}\",\n        )\n    @property\n    def metadata_column(self) -> str:\n        return self.config.column_map[\"metadata\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html"}
{"id": "eec294367d7f-0", "text": "Source code for langchain.vectorstores.qdrant\nfrom __future__ import annotations\nimport asyncio\nimport functools\nimport uuid\nimport warnings\nfrom itertools import islice\nfrom operator import itemgetter\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    AsyncGenerator,\n    Callable,\n    Dict,\n    Generator,\n    Iterable,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    Type,\n    Union,\n)\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nif TYPE_CHECKING:\n    from qdrant_client import grpc  # noqa\n    from qdrant_client.conversions import common_types\n    from qdrant_client.http import models as rest\n    DictFilter = Dict[str, Union[str, int, bool, dict, list]]\n    MetadataFilter = Union[DictFilter, common_types.Filter]\n[docs]class QdrantException(Exception):\n    \"\"\"`Qdrant` related exceptions.\"\"\"\n[docs]def sync_call_fallback(method: Callable) -> Callable:\n    \"\"\"\n    Decorator to call the synchronous method of the class if the async method is not\n    implemented. This decorator might be only used for the methods that are defined\n    as async in the class.\n    \"\"\"\n    @functools.wraps(method)\n    async def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:\n        try:\n            return await method(self, *args, **kwargs)\n        except NotImplementedError:\n            # If the async method is not implemented, call the synchronous method\n            # by removing the first letter from the method name. For example,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-1", "text": "# by removing the first letter from the method name. For example,\n            # if the async method is called ``aaad_texts``, the synchronous method\n            # will be called ``aad_texts``.\n            sync_method = functools.partial(\n                getattr(self, method.__name__[1:]), *args, **kwargs\n            )\n            return await asyncio.get_event_loop().run_in_executor(None, sync_method)\n    return wrapper\n[docs]class Qdrant(VectorStore):\n    \"\"\"`Qdrant` vector store.\n    To use you should have the ``qdrant-client`` package installed.\n    Example:\n        .. code-block:: python\n            from qdrant_client import QdrantClient\n            from langchain.vectorstores import Qdrant\n            client = QdrantClient()\n            collection_name = \"MyCollection\"\n            qdrant = Qdrant(client, collection_name, embedding_function)\n    \"\"\"\n    CONTENT_KEY = \"page_content\"\n    METADATA_KEY = \"metadata\"\n    VECTOR_NAME = None\n[docs]    def __init__(\n        self,\n        client: Any,\n        collection_name: str,\n        embeddings: Optional[Embeddings] = None,\n        content_payload_key: str = CONTENT_KEY,\n        metadata_payload_key: str = METADATA_KEY,\n        distance_strategy: str = \"COSINE\",\n        vector_name: Optional[str] = VECTOR_NAME,\n        embedding_function: Optional[Callable] = None,  # deprecated\n    ):\n        \"\"\"Initialize with necessary components.\"\"\"\n        try:\n            import qdrant_client\n        except ImportError:\n            raise ImportError(\n                \"Could not import qdrant-client python package. \"\n                \"Please install it with `pip install qdrant-client`.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-2", "text": "\"Please install it with `pip install qdrant-client`.\"\n            )\n        if not isinstance(client, qdrant_client.QdrantClient):\n            raise ValueError(\n                f\"client should be an instance of qdrant_client.QdrantClient, \"\n                f\"got {type(client)}\"\n            )\n        if embeddings is None and embedding_function is None:\n            raise ValueError(\n                \"`embeddings` value can't be None. Pass `Embeddings` instance.\"\n            )\n        if embeddings is not None and embedding_function is not None:\n            raise ValueError(\n                \"Both `embeddings` and `embedding_function` are passed. \"\n                \"Use `embeddings` only.\"\n            )\n        self._embeddings = embeddings\n        self._embeddings_function = embedding_function\n        self.client: qdrant_client.QdrantClient = client\n        self.collection_name = collection_name\n        self.content_payload_key = content_payload_key or self.CONTENT_KEY\n        self.metadata_payload_key = metadata_payload_key or self.METADATA_KEY\n        self.vector_name = vector_name or self.VECTOR_NAME\n        if embedding_function is not None:\n            warnings.warn(\n                \"Using `embedding_function` is deprecated. \"\n                \"Pass `Embeddings` instance to `embeddings` instead.\"\n            )\n        if not isinstance(embeddings, Embeddings):\n            warnings.warn(\n                \"`embeddings` should be an instance of `Embeddings`.\"\n                \"Using `embeddings` as `embedding_function` which is deprecated\"\n            )\n            self._embeddings_function = embeddings\n            self._embeddings = None\n        self.distance_strategy = distance_strategy.upper()\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return self._embeddings", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-3", "text": "def embeddings(self) -> Optional[Embeddings]:\n        return self._embeddings\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[Sequence[str]] = None,\n        batch_size: int = 64,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids:\n                Optional list of ids to associate with the texts. Ids have to be\n                uuid-like strings.\n            batch_size:\n                How many vectors upload per-request.\n                Default: 64\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        added_ids = []\n        for batch_ids, points in self._generate_rest_batches(\n            texts, metadatas, ids, batch_size\n        ):\n            self.client.upsert(\n                collection_name=self.collection_name, points=points, **kwargs\n            )\n            added_ids.extend(batch_ids)\n        return added_ids\n[docs]    @sync_call_fallback\n    async def aadd_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[Sequence[str]] = None,\n        batch_size: int = 64,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-4", "text": "Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids:\n                Optional list of ids to associate with the texts. Ids have to be\n                uuid-like strings.\n            batch_size:\n                How many vectors upload per-request.\n                Default: 64\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        from qdrant_client import grpc  # noqa\n        from qdrant_client.conversions.conversion import RestToGrpc\n        added_ids = []\n        async for batch_ids, points in self._agenerate_rest_batches(\n            texts, metadatas, ids, batch_size\n        ):\n            await self.client.async_grpc_points.Upsert(\n                grpc.UpsertPoints(\n                    collection_name=self.collection_name,\n                    points=[RestToGrpc.convert_point_struct(point) for point in points],\n                )\n            )\n            added_ids.extend(batch_ids)\n        return added_ids\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        offset: int = 0,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-5", "text": "filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params\n            offset:\n                Offset of the first result to return.\n                May be used to paginate results.\n                Note: large offset values may cause performance issues.\n            score_threshold:\n                Define a minimal score threshold for the result.\n                If defined, less similar results will not be returned.\n                Score of the returned result might be higher or smaller than the\n                threshold depending on the Distance function used.\n                E.g. for cosine similarity only higher scores will be returned.\n            consistency:\n                Read consistency of the search. Defines how many replicas should be\n                queried before returning the result.\n                Values:\n                - int - number of replicas to query, values should present in all\n                        queried replicas\n                - 'majority' - query all replicas, but return values present in the\n                               majority of replicas\n                - 'quorum' - query the majority of replicas, return values present in\n                             all of them\n                - 'all' - query all replicas, and return values present in all replicas\n            **kwargs:\n                Any other named arguments to pass through to QdrantClient.search()\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        results = self.similarity_search_with_score(\n            query,\n            k,\n            filter=filter,\n            search_params=search_params,\n            offset=offset,\n            score_threshold=score_threshold,\n            consistency=consistency,\n            **kwargs,\n        )\n        return list(map(itemgetter(0), results))\n[docs]    @sync_call_fallback\n    async def asimilarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[MetadataFilter] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-6", "text": "filter: Optional[MetadataFilter] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        results = await self.asimilarity_search_with_score(query, k, filter, **kwargs)\n        return list(map(itemgetter(0), results))\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        offset: int = 0,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params\n            offset:\n                Offset of the first result to return.\n                May be used to paginate results.\n                Note: large offset values may cause performance issues.\n            score_threshold:\n                Define a minimal score threshold for the result.\n                If defined, less similar results will not be returned.\n                Score of the returned result might be higher or smaller than the\n                threshold depending on the Distance function used.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-7", "text": "threshold depending on the Distance function used.\n                E.g. for cosine similarity only higher scores will be returned.\n            consistency:\n                Read consistency of the search. Defines how many replicas should be\n                queried before returning the result.\n                Values:\n                - int - number of replicas to query, values should present in all\n                        queried replicas\n                - 'majority' - query all replicas, but return values present in the\n                               majority of replicas\n                - 'quorum' - query the majority of replicas, return values present in\n                             all of them\n                - 'all' - query all replicas, and return values present in all replicas\n            **kwargs:\n                Any other named arguments to pass through to QdrantClient.search()\n        Returns:\n            List of documents most similar to the query text and distance for each.\n        \"\"\"\n        return self.similarity_search_with_score_by_vector(\n            self._embed_query(query),\n            k,\n            filter=filter,\n            search_params=search_params,\n            offset=offset,\n            score_threshold=score_threshold,\n            consistency=consistency,\n            **kwargs,\n        )\n[docs]    @sync_call_fallback\n    async def asimilarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        offset: int = 0,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-8", "text": "Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params\n            offset:\n                Offset of the first result to return.\n                May be used to paginate results.\n                Note: large offset values may cause performance issues.\n            score_threshold:\n                Define a minimal score threshold for the result.\n                If defined, less similar results will not be returned.\n                Score of the returned result might be higher or smaller than the\n                threshold depending on the Distance function used.\n                E.g. for cosine similarity only higher scores will be returned.\n            consistency:\n                Read consistency of the search. Defines how many replicas should be\n                queried before returning the result.\n                Values:\n                - int - number of replicas to query, values should present in all\n                        queried replicas\n                - 'majority' - query all replicas, but return values present in the\n                               majority of replicas\n                - 'quorum' - query the majority of replicas, return values present in\n                             all of them\n                - 'all' - query all replicas, and return values present in all replicas\n            **kwargs:\n                Any other named arguments to pass through to\n                QdrantClient.async_grpc_points.Search().\n        Returns:\n            List of documents most similar to the query text and distance for each.\n        \"\"\"\n        return await self.asimilarity_search_with_score_by_vector(\n            self._embed_query(query),\n            k,\n            filter=filter,\n            search_params=search_params,\n            offset=offset,\n            score_threshold=score_threshold,\n            consistency=consistency,\n            **kwargs,\n        )\n[docs]    def similarity_search_by_vector(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-9", "text": "**kwargs,\n        )\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        offset: int = 0,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding vector to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params\n            offset:\n                Offset of the first result to return.\n                May be used to paginate results.\n                Note: large offset values may cause performance issues.\n            score_threshold:\n                Define a minimal score threshold for the result.\n                If defined, less similar results will not be returned.\n                Score of the returned result might be higher or smaller than the\n                threshold depending on the Distance function used.\n                E.g. for cosine similarity only higher scores will be returned.\n            consistency:\n                Read consistency of the search. Defines how many replicas should be\n                queried before returning the result.\n                Values:\n                - int - number of replicas to query, values should present in all\n                        queried replicas\n                - 'majority' - query all replicas, but return values present in the\n                               majority of replicas\n                - 'quorum' - query the majority of replicas, return values present in\n                             all of them\n                - 'all' - query all replicas, and return values present in all replicas", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-10", "text": "- 'all' - query all replicas, and return values present in all replicas\n            **kwargs:\n                Any other named arguments to pass through to QdrantClient.search()\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        results = self.similarity_search_with_score_by_vector(\n            embedding,\n            k,\n            filter=filter,\n            search_params=search_params,\n            offset=offset,\n            score_threshold=score_threshold,\n            consistency=consistency,\n            **kwargs,\n        )\n        return list(map(itemgetter(0), results))\n[docs]    @sync_call_fallback\n    async def asimilarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        offset: int = 0,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding vector to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params\n            offset:\n                Offset of the first result to return.\n                May be used to paginate results.\n                Note: large offset values may cause performance issues.\n            score_threshold:\n                Define a minimal score threshold for the result.\n                If defined, less similar results will not be returned.\n                Score of the returned result might be higher or smaller than the", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-11", "text": "Score of the returned result might be higher or smaller than the\n                threshold depending on the Distance function used.\n                E.g. for cosine similarity only higher scores will be returned.\n            consistency:\n                Read consistency of the search. Defines how many replicas should be\n                queried before returning the result.\n                Values:\n                - int - number of replicas to query, values should present in all\n                        queried replicas\n                - 'majority' - query all replicas, but return values present in the\n                               majority of replicas\n                - 'quorum' - query the majority of replicas, return values present in\n                             all of them\n                - 'all' - query all replicas, and return values present in all replicas\n            **kwargs:\n                Any other named arguments to pass through to\n                QdrantClient.async_grpc_points.Search().\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        results = await self.asimilarity_search_with_score_by_vector(\n            embedding,\n            k,\n            filter=filter,\n            search_params=search_params,\n            offset=offset,\n            score_threshold=score_threshold,\n            consistency=consistency,\n            **kwargs,\n        )\n        return list(map(itemgetter(0), results))\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        offset: int = 0,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-12", "text": "**kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding vector to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params\n            offset:\n                Offset of the first result to return.\n                May be used to paginate results.\n                Note: large offset values may cause performance issues.\n            score_threshold:\n                Define a minimal score threshold for the result.\n                If defined, less similar results will not be returned.\n                Score of the returned result might be higher or smaller than the\n                threshold depending on the Distance function used.\n                E.g. for cosine similarity only higher scores will be returned.\n            consistency:\n                Read consistency of the search. Defines how many replicas should be\n                queried before returning the result.\n                Values:\n                - int - number of replicas to query, values should present in all\n                        queried replicas\n                - 'majority' - query all replicas, but return values present in the\n                               majority of replicas\n                - 'quorum' - query the majority of replicas, return values present in\n                             all of them\n                - 'all' - query all replicas, and return values present in all replicas\n            **kwargs:\n                Any other named arguments to pass through to QdrantClient.search()\n        Returns:\n            List of documents most similar to the query text and distance for each.\n        \"\"\"\n        if filter is not None and isinstance(filter, dict):\n            warnings.warn(\n                \"Using dict as a `filter` is deprecated. Please use qdrant-client \"\n                \"filters directly: \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-13", "text": "\"filters directly: \"\n                \"https://qdrant.tech/documentation/concepts/filtering/\",\n                DeprecationWarning,\n            )\n            qdrant_filter = self._qdrant_filter_from_dict(filter)\n        else:\n            qdrant_filter = filter\n        query_vector = embedding\n        if self.vector_name is not None:\n            query_vector = (self.vector_name, embedding)  # type: ignore[assignment]\n        results = self.client.search(\n            collection_name=self.collection_name,\n            query_vector=query_vector,\n            query_filter=qdrant_filter,\n            search_params=search_params,\n            limit=k,\n            offset=offset,\n            with_payload=True,\n            with_vectors=False,  # Langchain does not expect vectors to be returned\n            score_threshold=score_threshold,\n            consistency=consistency,\n            **kwargs,\n        )\n        return [\n            (\n                self._document_from_scored_point(\n                    result, self.content_payload_key, self.metadata_payload_key\n                ),\n                result.score,\n            )\n            for result in results\n        ]\n    async def _asearch_with_score_by_vector(\n        self,\n        embedding: List[float],\n        *,\n        k: int = 4,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        offset: int = 0,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        with_vectors: bool = False,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Return results most similar to embedding vector.\"\"\"\n        from qdrant_client import grpc  # noqa", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-14", "text": "from qdrant_client import grpc  # noqa\n        from qdrant_client.conversions.conversion import RestToGrpc\n        from qdrant_client.http import models as rest\n        if filter is not None and isinstance(filter, dict):\n            warnings.warn(\n                \"Using dict as a `filter` is deprecated. Please use qdrant-client \"\n                \"filters directly: \"\n                \"https://qdrant.tech/documentation/concepts/filtering/\",\n                DeprecationWarning,\n            )\n            qdrant_filter = self._qdrant_filter_from_dict(filter)\n        else:\n            qdrant_filter = filter\n        if qdrant_filter is not None and isinstance(qdrant_filter, rest.Filter):\n            qdrant_filter = RestToGrpc.convert_filter(qdrant_filter)\n        response = await self.client.async_grpc_points.Search(\n            grpc.SearchPoints(\n                collection_name=self.collection_name,\n                vector_name=self.vector_name,\n                vector=embedding,\n                filter=qdrant_filter,\n                params=search_params,\n                limit=k,\n                offset=offset,\n                with_payload=grpc.WithPayloadSelector(enable=True),\n                with_vectors=grpc.WithVectorsSelector(enable=with_vectors),\n                score_threshold=score_threshold,\n                read_consistency=consistency,\n                **kwargs,\n            )\n        )\n        return response\n[docs]    @sync_call_fallback\n    async def asimilarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        offset: int = 0,\n        score_threshold: Optional[float] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-15", "text": "offset: int = 0,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding vector to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params\n            offset:\n                Offset of the first result to return.\n                May be used to paginate results.\n                Note: large offset values may cause performance issues.\n            score_threshold:\n                Define a minimal score threshold for the result.\n                If defined, less similar results will not be returned.\n                Score of the returned result might be higher or smaller than the\n                threshold depending on the Distance function used.\n                E.g. for cosine similarity only higher scores will be returned.\n            consistency:\n                Read consistency of the search. Defines how many replicas should be\n                queried before returning the result.\n                Values:\n                - int - number of replicas to query, values should present in all\n                        queried replicas\n                - 'majority' - query all replicas, but return values present in the\n                               majority of replicas\n                - 'quorum' - query the majority of replicas, return values present in\n                             all of them\n                - 'all' - query all replicas, and return values present in all replicas\n            **kwargs:\n                Any other named arguments to pass through to\n                QdrantClient.async_grpc_points.Search().\n        Returns:\n            List of documents most similar to the query text and distance for each.\n        \"\"\"\n        response = await self._asearch_with_score_by_vector(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-16", "text": "\"\"\"\n        response = await self._asearch_with_score_by_vector(\n            embedding,\n            k=k,\n            filter=filter,\n            search_params=search_params,\n            offset=offset,\n            score_threshold=score_threshold,\n            consistency=consistency,\n            **kwargs,\n        )\n        return [\n            (\n                self._document_from_scored_point_grpc(\n                    result, self.content_payload_key, self.metadata_payload_key\n                ),\n                result.score,\n            )\n            for result in response.result\n        ]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n                     Defaults to 20.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-17", "text": "filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params\n            score_threshold:\n                Define a minimal score threshold for the result.\n                If defined, less similar results will not be returned.\n                Score of the returned result might be higher or smaller than the\n                threshold depending on the Distance function used.\n                E.g. for cosine similarity only higher scores will be returned.\n            consistency:\n                Read consistency of the search. Defines how many replicas should be\n                queried before returning the result.\n                Values:\n                - int - number of replicas to query, values should present in all\n                        queried replicas\n                - 'majority' - query all replicas, but return values present in the\n                               majority of replicas\n                - 'quorum' - query the majority of replicas, return values present in\n                             all of them\n                - 'all' - query all replicas, and return values present in all replicas\n            **kwargs:\n                Any other named arguments to pass through to QdrantClient.search()\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        query_embedding = self._embed_query(query)\n        return self.max_marginal_relevance_search_by_vector(\n            query_embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n            search_params=search_params,\n            score_threshold=score_threshold,\n            consistency=consistency,\n            **kwargs,\n        )\n[docs]    @sync_call_fallback\n    async def amax_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-18", "text": "lambda_mult: float = 0.5,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n                     Defaults to 20.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params\n            score_threshold:\n                Define a minimal score threshold for the result.\n                If defined, less similar results will not be returned.\n                Score of the returned result might be higher or smaller than the\n                threshold depending on the Distance function used.\n                E.g. for cosine similarity only higher scores will be returned.\n            consistency:\n                Read consistency of the search. Defines how many replicas should be\n                queried before returning the result.\n                Values:\n                - int - number of replicas to query, values should present in all\n                        queried replicas\n                - 'majority' - query all replicas, but return values present in the\n                               majority of replicas\n                - 'quorum' - query the majority of replicas, return values present in\n                             all of them", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-19", "text": "all of them\n                - 'all' - query all replicas, and return values present in all replicas\n            **kwargs:\n                Any other named arguments to pass through to\n                QdrantClient.async_grpc_points.Search().\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        query_embedding = self._embed_query(query)\n        return await self.amax_marginal_relevance_search_by_vector(\n            query_embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n            search_params=search_params,\n            score_threshold=score_threshold,\n            consistency=consistency,\n            **kwargs,\n        )\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-20", "text": "of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params\n            score_threshold:\n                Define a minimal score threshold for the result.\n                If defined, less similar results will not be returned.\n                Score of the returned result might be higher or smaller than the\n                threshold depending on the Distance function used.\n                E.g. for cosine similarity only higher scores will be returned.\n            consistency:\n                Read consistency of the search. Defines how many replicas should be\n                queried before returning the result.\n                Values:\n                - int - number of replicas to query, values should present in all\n                        queried replicas\n                - 'majority' - query all replicas, but return values present in the\n                               majority of replicas\n                - 'quorum' - query the majority of replicas, return values present in\n                             all of them\n                - 'all' - query all replicas, and return values present in all replicas\n            **kwargs:\n                Any other named arguments to pass through to QdrantClient.search()\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        results = self.max_marginal_relevance_search_with_score_by_vector(\n            embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n            search_params=search_params,\n            score_threshold=score_threshold,\n            consistency=consistency,\n            **kwargs,\n        )\n        return list(map(itemgetter(0), results))\n[docs]    @sync_call_fallback\n    async def amax_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-21", "text": "self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n                     Defaults to 20.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params\n            score_threshold:\n                Define a minimal score threshold for the result.\n                If defined, less similar results will not be returned.\n                Score of the returned result might be higher or smaller than the\n                threshold depending on the Distance function used.\n                E.g. for cosine similarity only higher scores will be returned.\n            consistency:\n                Read consistency of the search. Defines how many replicas should be\n                queried before returning the result.\n                Values:\n                - int - number of replicas to query, values should present in all\n                        queried replicas", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-22", "text": "- int - number of replicas to query, values should present in all\n                        queried replicas\n                - 'majority' - query all replicas, but return values present in the\n                               majority of replicas\n                - 'quorum' - query the majority of replicas, return values present in\n                             all of them\n                - 'all' - query all replicas, and return values present in all replicas\n            **kwargs:\n                Any other named arguments to pass through to\n                QdrantClient.async_grpc_points.Search().\n        Returns:\n            List of Documents selected by maximal marginal relevance and distance for\n            each.\n        \"\"\"\n        results = await self.amax_marginal_relevance_search_with_score_by_vector(\n            embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n            search_params=search_params,\n            score_threshold=score_threshold,\n            consistency=consistency,\n            **kwargs,\n        )\n        return list(map(itemgetter(0), results))\n[docs]    def max_marginal_relevance_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-23", "text": "among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n                     Defaults to 20.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            filter: Filter by metadata. Defaults to None.\n            search_params: Additional search params\n            score_threshold:\n                Define a minimal score threshold for the result.\n                If defined, less similar results will not be returned.\n                Score of the returned result might be higher or smaller than the\n                threshold depending on the Distance function used.\n                E.g. for cosine similarity only higher scores will be returned.\n            consistency:\n                Read consistency of the search. Defines how many replicas should be\n                queried before returning the result.\n                Values:\n                - int - number of replicas to query, values should present in all\n                        queried replicas\n                - 'majority' - query all replicas, but return values present in the\n                               majority of replicas\n                - 'quorum' - query the majority of replicas, return values present in\n                             all of them\n                - 'all' - query all replicas, and return values present in all replicas\n            **kwargs:\n                Any other named arguments to pass through to QdrantClient.search()\n        Returns:\n            List of Documents selected by maximal marginal relevance and distance for\n            each.\n        \"\"\"\n        query_vector = embedding\n        if self.vector_name is not None:\n            query_vector = (self.vector_name, query_vector)  # type: ignore[assignment]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-24", "text": "results = self.client.search(\n            collection_name=self.collection_name,\n            query_vector=query_vector,\n            query_filter=filter,\n            search_params=search_params,\n            limit=fetch_k,\n            with_payload=True,\n            with_vectors=True,\n            score_threshold=score_threshold,\n            consistency=consistency,\n            **kwargs,\n        )\n        embeddings = [\n            result.vector.get(self.vector_name)  # type: ignore[index, union-attr]\n            if self.vector_name is not None\n            else result.vector\n            for result in results\n        ]\n        mmr_selected = maximal_marginal_relevance(\n            np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult\n        )\n        return [\n            (\n                self._document_from_scored_point(\n                    results[i], self.content_payload_key, self.metadata_payload_key\n                ),\n                results[i].score,\n            )\n            for i in mmr_selected\n        ]\n[docs]    @sync_call_fallback\n    async def amax_marginal_relevance_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[MetadataFilter] = None,\n        search_params: Optional[common_types.SearchParams] = None,\n        score_threshold: Optional[float] = None,\n        consistency: Optional[common_types.ReadConsistency] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-25", "text": "among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n                     Defaults to 20.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance and distance for\n            each.\n        \"\"\"\n        from qdrant_client.conversions.conversion import GrpcToRest\n        response = await self._asearch_with_score_by_vector(\n            embedding,\n            k=fetch_k,\n            filter=filter,\n            search_params=search_params,\n            score_threshold=score_threshold,\n            consistency=consistency,\n            with_vectors=True,\n            **kwargs,\n        )\n        results = [\n            GrpcToRest.convert_vectors(result.vectors) for result in response.result\n        ]\n        embeddings: List[List[float]] = [\n            result.get(self.vector_name)  # type: ignore\n            if isinstance(result, dict)\n            else result\n            for result in results\n        ]\n        mmr_selected: List[int] = maximal_marginal_relevance(\n            np.array(embedding),\n            embeddings,\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        return [\n            (\n                self._document_from_scored_point_grpc(\n                    response.result[i],\n                    self.content_payload_key,\n                    self.metadata_payload_key,\n                ),\n                response.result[i].score,\n            )\n            for i in mmr_selected\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-26", "text": ")\n            for i in mmr_selected\n        ]\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:\n        \"\"\"Delete by vector ID or other criteria.\n        Args:\n            ids: List of ids to delete.\n            **kwargs: Other keyword arguments that subclasses might use.\n        Returns:\n            Optional[bool]: True if deletion is successful,\n            False otherwise, None if not implemented.\n        \"\"\"\n        from qdrant_client.http import models as rest\n        result = self.client.delete(\n            collection_name=self.collection_name,\n            points_selector=ids,\n        )\n        return result.status == rest.UpdateStatus.COMPLETED\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[Qdrant],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[Sequence[str]] = None,\n        location: Optional[str] = None,\n        url: Optional[str] = None,\n        port: Optional[int] = 6333,\n        grpc_port: int = 6334,\n        prefer_grpc: bool = False,\n        https: Optional[bool] = None,\n        api_key: Optional[str] = None,\n        prefix: Optional[str] = None,\n        timeout: Optional[float] = None,\n        host: Optional[str] = None,\n        path: Optional[str] = None,\n        collection_name: Optional[str] = None,\n        distance_func: str = \"Cosine\",\n        content_payload_key: str = CONTENT_KEY,\n        metadata_payload_key: str = METADATA_KEY,\n        vector_name: Optional[str] = VECTOR_NAME,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-27", "text": "vector_name: Optional[str] = VECTOR_NAME,\n        batch_size: int = 64,\n        shard_number: Optional[int] = None,\n        replication_factor: Optional[int] = None,\n        write_consistency_factor: Optional[int] = None,\n        on_disk_payload: Optional[bool] = None,\n        hnsw_config: Optional[common_types.HnswConfigDiff] = None,\n        optimizers_config: Optional[common_types.OptimizersConfigDiff] = None,\n        wal_config: Optional[common_types.WalConfigDiff] = None,\n        quantization_config: Optional[common_types.QuantizationConfig] = None,\n        init_from: Optional[common_types.InitFrom] = None,\n        on_disk: Optional[bool] = None,\n        force_recreate: bool = False,\n        **kwargs: Any,\n    ) -> Qdrant:\n        \"\"\"Construct Qdrant wrapper from a list of texts.\n        Args:\n            texts: A list of texts to be indexed in Qdrant.\n            embedding: A subclass of `Embeddings`, responsible for text vectorization.\n            metadatas:\n                An optional list of metadata. If provided it has to be of the same\n                length as a list of texts.\n            ids:\n                Optional list of ids to associate with the texts. Ids have to be\n                uuid-like strings.\n            location:\n                If `:memory:` - use in-memory Qdrant instance.\n                If `str` - use it as a `url` parameter.\n                If `None` - fallback to relying on `host` and `port` parameters.\n            url: either host or str of \"Optional[scheme], host, Optional[port],\n                Optional[prefix]\". Default: `None`", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-28", "text": "Optional[prefix]\". Default: `None`\n            port: Port of the REST API interface. Default: 6333\n            grpc_port: Port of the gRPC interface. Default: 6334\n            prefer_grpc:\n                If true - use gPRC interface whenever possible in custom methods.\n                Default: False\n            https: If true - use HTTPS(SSL) protocol. Default: None\n            api_key: API key for authentication in Qdrant Cloud. Default: None\n            prefix:\n                If not None - add prefix to the REST URL path.\n                Example: service/v1 will result in\n                    http://localhost:6333/service/v1/{qdrant-endpoint} for REST API.\n                Default: None\n            timeout:\n                Timeout for REST and gRPC API requests.\n                Default: 5.0 seconds for REST and unlimited for gRPC\n            host:\n                Host name of Qdrant service. If url and host are None, set to\n                'localhost'. Default: None\n            path:\n                Path in which the vectors will be stored while using local mode.\n                Default: None\n            collection_name:\n                Name of the Qdrant collection to be used. If not provided,\n                it will be created randomly. Default: None\n            distance_func:\n                Distance function. One of: \"Cosine\" / \"Euclid\" / \"Dot\".\n                Default: \"Cosine\"\n            content_payload_key:\n                A payload key used to store the content of the document.\n                Default: \"page_content\"\n            metadata_payload_key:\n                A payload key used to store the metadata of the document.\n                Default: \"metadata\"\n            vector_name:\n                Name of the vector to be used internally in Qdrant.\n                Default: None\n            batch_size:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-29", "text": "Default: None\n            batch_size:\n                How many vectors upload per-request.\n                Default: 64\n            shard_number: Number of shards in collection. Default is 1, minimum is 1.\n            replication_factor:\n                Replication factor for collection. Default is 1, minimum is 1.\n                Defines how many copies of each shard will be created.\n                Have effect only in distributed mode.\n            write_consistency_factor:\n                Write consistency factor for collection. Default is 1, minimum is 1.\n                Defines how many replicas should apply the operation for us to consider\n                it successful. Increasing this number will make the collection more\n                resilient to inconsistencies, but will also make it fail if not enough\n                replicas are available.\n                Does not have any performance impact.\n                Have effect only in distributed mode.\n            on_disk_payload:\n                If true - point`s payload will not be stored in memory.\n                It will be read from the disk every time it is requested.\n                This setting saves RAM by (slightly) increasing the response time.\n                Note: those payload values that are involved in filtering and are\n                indexed - remain in RAM.\n            hnsw_config: Params for HNSW index\n            optimizers_config: Params for optimizer\n            wal_config: Params for Write-Ahead-Log\n            quantization_config:\n                Params for quantization, if None - quantization will be disabled\n            init_from:\n                Use data stored in another collection to initialize this collection\n            force_recreate:\n                Force recreating the collection\n            **kwargs:\n                Additional arguments passed directly into REST client initialization\n        This is a user-friendly interface that:\n        1. Creates embeddings, one for each text\n        2. Initializes the Qdrant database as an in-memory docstore by default", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-30", "text": "2. Initializes the Qdrant database as an in-memory docstore by default\n           (and overridable to a remote docstore)\n        3. Adds the text embeddings to the Qdrant database\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import Qdrant\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                qdrant = Qdrant.from_texts(texts, embeddings, \"localhost\")\n        \"\"\"\n        qdrant = cls.construct_instance(\n            texts,\n            embedding,\n            location,\n            url,\n            port,\n            grpc_port,\n            prefer_grpc,\n            https,\n            api_key,\n            prefix,\n            timeout,\n            host,\n            path,\n            collection_name,\n            distance_func,\n            content_payload_key,\n            metadata_payload_key,\n            vector_name,\n            shard_number,\n            replication_factor,\n            write_consistency_factor,\n            on_disk_payload,\n            hnsw_config,\n            optimizers_config,\n            wal_config,\n            quantization_config,\n            init_from,\n            on_disk,\n            force_recreate,\n            **kwargs,\n        )\n        qdrant.add_texts(texts, metadatas, ids, batch_size)\n        return qdrant\n[docs]    @classmethod\n    @sync_call_fallback\n    async def afrom_texts(\n        cls: Type[Qdrant],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[Sequence[str]] = None,\n        location: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-31", "text": "location: Optional[str] = None,\n        url: Optional[str] = None,\n        port: Optional[int] = 6333,\n        grpc_port: int = 6334,\n        prefer_grpc: bool = False,\n        https: Optional[bool] = None,\n        api_key: Optional[str] = None,\n        prefix: Optional[str] = None,\n        timeout: Optional[float] = None,\n        host: Optional[str] = None,\n        path: Optional[str] = None,\n        collection_name: Optional[str] = None,\n        distance_func: str = \"Cosine\",\n        content_payload_key: str = CONTENT_KEY,\n        metadata_payload_key: str = METADATA_KEY,\n        vector_name: Optional[str] = VECTOR_NAME,\n        batch_size: int = 64,\n        shard_number: Optional[int] = None,\n        replication_factor: Optional[int] = None,\n        write_consistency_factor: Optional[int] = None,\n        on_disk_payload: Optional[bool] = None,\n        hnsw_config: Optional[common_types.HnswConfigDiff] = None,\n        optimizers_config: Optional[common_types.OptimizersConfigDiff] = None,\n        wal_config: Optional[common_types.WalConfigDiff] = None,\n        quantization_config: Optional[common_types.QuantizationConfig] = None,\n        init_from: Optional[common_types.InitFrom] = None,\n        on_disk: Optional[bool] = None,\n        force_recreate: bool = False,\n        **kwargs: Any,\n    ) -> Qdrant:\n        \"\"\"Construct Qdrant wrapper from a list of texts.\n        Args:\n            texts: A list of texts to be indexed in Qdrant.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-32", "text": "Args:\n            texts: A list of texts to be indexed in Qdrant.\n            embedding: A subclass of `Embeddings`, responsible for text vectorization.\n            metadatas:\n                An optional list of metadata. If provided it has to be of the same\n                length as a list of texts.\n            ids:\n                Optional list of ids to associate with the texts. Ids have to be\n                uuid-like strings.\n            location:\n                If `:memory:` - use in-memory Qdrant instance.\n                If `str` - use it as a `url` parameter.\n                If `None` - fallback to relying on `host` and `port` parameters.\n            url: either host or str of \"Optional[scheme], host, Optional[port],\n                Optional[prefix]\". Default: `None`\n            port: Port of the REST API interface. Default: 6333\n            grpc_port: Port of the gRPC interface. Default: 6334\n            prefer_grpc:\n                If true - use gPRC interface whenever possible in custom methods.\n                Default: False\n            https: If true - use HTTPS(SSL) protocol. Default: None\n            api_key: API key for authentication in Qdrant Cloud. Default: None\n            prefix:\n                If not None - add prefix to the REST URL path.\n                Example: service/v1 will result in\n                    http://localhost:6333/service/v1/{qdrant-endpoint} for REST API.\n                Default: None\n            timeout:\n                Timeout for REST and gRPC API requests.\n                Default: 5.0 seconds for REST and unlimited for gRPC\n            host:\n                Host name of Qdrant service. If url and host are None, set to\n                'localhost'. Default: None\n            path:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-33", "text": "'localhost'. Default: None\n            path:\n                Path in which the vectors will be stored while using local mode.\n                Default: None\n            collection_name:\n                Name of the Qdrant collection to be used. If not provided,\n                it will be created randomly. Default: None\n            distance_func:\n                Distance function. One of: \"Cosine\" / \"Euclid\" / \"Dot\".\n                Default: \"Cosine\"\n            content_payload_key:\n                A payload key used to store the content of the document.\n                Default: \"page_content\"\n            metadata_payload_key:\n                A payload key used to store the metadata of the document.\n                Default: \"metadata\"\n            vector_name:\n                Name of the vector to be used internally in Qdrant.\n                Default: None\n            batch_size:\n                How many vectors upload per-request.\n                Default: 64\n            shard_number: Number of shards in collection. Default is 1, minimum is 1.\n            replication_factor:\n                Replication factor for collection. Default is 1, minimum is 1.\n                Defines how many copies of each shard will be created.\n                Have effect only in distributed mode.\n            write_consistency_factor:\n                Write consistency factor for collection. Default is 1, minimum is 1.\n                Defines how many replicas should apply the operation for us to consider\n                it successful. Increasing this number will make the collection more\n                resilient to inconsistencies, but will also make it fail if not enough\n                replicas are available.\n                Does not have any performance impact.\n                Have effect only in distributed mode.\n            on_disk_payload:\n                If true - point`s payload will not be stored in memory.\n                It will be read from the disk every time it is requested.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-34", "text": "It will be read from the disk every time it is requested.\n                This setting saves RAM by (slightly) increasing the response time.\n                Note: those payload values that are involved in filtering and are\n                indexed - remain in RAM.\n            hnsw_config: Params for HNSW index\n            optimizers_config: Params for optimizer\n            wal_config: Params for Write-Ahead-Log\n            quantization_config:\n                Params for quantization, if None - quantization will be disabled\n            init_from:\n                Use data stored in another collection to initialize this collection\n            force_recreate:\n                Force recreating the collection\n            **kwargs:\n                Additional arguments passed directly into REST client initialization\n        This is a user-friendly interface that:\n        1. Creates embeddings, one for each text\n        2. Initializes the Qdrant database as an in-memory docstore by default\n           (and overridable to a remote docstore)\n        3. Adds the text embeddings to the Qdrant database\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import Qdrant\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                qdrant = await Qdrant.afrom_texts(texts, embeddings, \"localhost\")\n        \"\"\"\n        qdrant = await cls.aconstruct_instance(\n            texts,\n            embedding,\n            location,\n            url,\n            port,\n            grpc_port,\n            prefer_grpc,\n            https,\n            api_key,\n            prefix,\n            timeout,\n            host,\n            path,\n            collection_name,\n            distance_func,\n            content_payload_key,\n            metadata_payload_key,\n            vector_name,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-35", "text": "content_payload_key,\n            metadata_payload_key,\n            vector_name,\n            shard_number,\n            replication_factor,\n            write_consistency_factor,\n            on_disk_payload,\n            hnsw_config,\n            optimizers_config,\n            wal_config,\n            quantization_config,\n            init_from,\n            on_disk,\n            force_recreate,\n            **kwargs,\n        )\n        await qdrant.aadd_texts(texts, metadatas, ids, batch_size)\n        return qdrant\n[docs]    @classmethod\n    def construct_instance(\n        cls: Type[Qdrant],\n        texts: List[str],\n        embedding: Embeddings,\n        location: Optional[str] = None,\n        url: Optional[str] = None,\n        port: Optional[int] = 6333,\n        grpc_port: int = 6334,\n        prefer_grpc: bool = False,\n        https: Optional[bool] = None,\n        api_key: Optional[str] = None,\n        prefix: Optional[str] = None,\n        timeout: Optional[float] = None,\n        host: Optional[str] = None,\n        path: Optional[str] = None,\n        collection_name: Optional[str] = None,\n        distance_func: str = \"Cosine\",\n        content_payload_key: str = CONTENT_KEY,\n        metadata_payload_key: str = METADATA_KEY,\n        vector_name: Optional[str] = VECTOR_NAME,\n        shard_number: Optional[int] = None,\n        replication_factor: Optional[int] = None,\n        write_consistency_factor: Optional[int] = None,\n        on_disk_payload: Optional[bool] = None,\n        hnsw_config: Optional[common_types.HnswConfigDiff] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-36", "text": "hnsw_config: Optional[common_types.HnswConfigDiff] = None,\n        optimizers_config: Optional[common_types.OptimizersConfigDiff] = None,\n        wal_config: Optional[common_types.WalConfigDiff] = None,\n        quantization_config: Optional[common_types.QuantizationConfig] = None,\n        init_from: Optional[common_types.InitFrom] = None,\n        on_disk: Optional[bool] = None,\n        force_recreate: bool = False,\n        **kwargs: Any,\n    ) -> Qdrant:\n        try:\n            import qdrant_client\n        except ImportError:\n            raise ValueError(\n                \"Could not import qdrant-client python package. \"\n                \"Please install it with `pip install qdrant-client`.\"\n            )\n        from grpc import RpcError\n        from qdrant_client.http import models as rest\n        from qdrant_client.http.exceptions import UnexpectedResponse\n        # Just do a single quick embedding to get vector size\n        partial_embeddings = embedding.embed_documents(texts[:1])\n        vector_size = len(partial_embeddings[0])\n        collection_name = collection_name or uuid.uuid4().hex\n        distance_func = distance_func.upper()\n        client = qdrant_client.QdrantClient(\n            location=location,\n            url=url,\n            port=port,\n            grpc_port=grpc_port,\n            prefer_grpc=prefer_grpc,\n            https=https,\n            api_key=api_key,\n            prefix=prefix,\n            timeout=timeout,\n            host=host,\n            path=path,\n            **kwargs,\n        )\n        try:\n            # Skip any validation in case of forced collection recreate.\n            if force_recreate:\n                raise ValueError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-37", "text": "if force_recreate:\n                raise ValueError\n            # Get the vector configuration of the existing collection and vector, if it\n            # was specified. If the old configuration does not match the current one,\n            # an exception is being thrown.\n            collection_info = client.get_collection(collection_name=collection_name)\n            current_vector_config = collection_info.config.params.vectors\n            if isinstance(current_vector_config, dict) and vector_name is not None:\n                if vector_name not in current_vector_config:\n                    raise QdrantException(\n                        f\"Existing Qdrant collection {collection_name} does not \"\n                        f\"contain vector named {vector_name}. Did you mean one of the \"\n                        f\"existing vectors: {', '.join(current_vector_config.keys())}? \"\n                        f\"If you want to recreate the collection, set `force_recreate` \"\n                        f\"parameter to `True`.\"\n                    )\n                current_vector_config = current_vector_config.get(vector_name)  # type: ignore[assignment]\n            elif isinstance(current_vector_config, dict) and vector_name is None:\n                raise QdrantException(\n                    f\"Existing Qdrant collection {collection_name} uses named vectors. \"\n                    f\"If you want to reuse it, please set `vector_name` to any of the \"\n                    f\"existing named vectors: \"\n                    f\"{', '.join(current_vector_config.keys())}.\"  # noqa\n                    f\"If you want to recreate the collection, set `force_recreate` \"\n                    f\"parameter to `True`.\"\n                )\n            elif (\n                not isinstance(current_vector_config, dict) and vector_name is not None\n            ):\n                raise QdrantException(\n                    f\"Existing Qdrant collection {collection_name} doesn't use named \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-38", "text": "f\"Existing Qdrant collection {collection_name} doesn't use named \"\n                    f\"vectors. If you want to reuse it, please set `vector_name` to \"\n                    f\"`None`. If you want to recreate the collection, set \"\n                    f\"`force_recreate` parameter to `True`.\"\n                )\n            # Check if the vector configuration has the same dimensionality.\n            if current_vector_config.size != vector_size:  # type: ignore[union-attr]\n                raise QdrantException(\n                    f\"Existing Qdrant collection is configured for vectors with \"\n                    f\"{current_vector_config.size} \"  # type: ignore[union-attr]\n                    f\"dimensions. Selected embeddings are {vector_size}-dimensional. \"\n                    f\"If you want to recreate the collection, set `force_recreate` \"\n                    f\"parameter to `True`.\"\n                )\n            current_distance_func = (\n                current_vector_config.distance.name.upper()  # type: ignore[union-attr]\n            )\n            if current_distance_func != distance_func:\n                raise QdrantException(\n                    f\"Existing Qdrant collection is configured for \"\n                    f\"{current_distance_func} similarity, but requested \"\n                    f\"{distance_func}. Please set `distance_func` parameter to \"\n                    f\"`{current_distance_func}` if you want to reuse it. \"\n                    f\"If you want to recreate the collection, set `force_recreate` \"\n                    f\"parameter to `True`.\"\n                )\n        except (UnexpectedResponse, RpcError, ValueError):\n            vectors_config = rest.VectorParams(\n                size=vector_size,\n                distance=rest.Distance[distance_func],\n                on_disk=on_disk,\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-39", "text": "on_disk=on_disk,\n            )\n            # If vector name was provided, we're going to use the named vectors feature\n            # with just a single vector.\n            if vector_name is not None:\n                vectors_config = {  # type: ignore[assignment]\n                    vector_name: vectors_config,\n                }\n            client.recreate_collection(\n                collection_name=collection_name,\n                vectors_config=vectors_config,\n                shard_number=shard_number,\n                replication_factor=replication_factor,\n                write_consistency_factor=write_consistency_factor,\n                on_disk_payload=on_disk_payload,\n                hnsw_config=hnsw_config,\n                optimizers_config=optimizers_config,\n                wal_config=wal_config,\n                quantization_config=quantization_config,\n                init_from=init_from,\n                timeout=timeout,  # type: ignore[arg-type]\n            )\n        qdrant = cls(\n            client=client,\n            collection_name=collection_name,\n            embeddings=embedding,\n            content_payload_key=content_payload_key,\n            metadata_payload_key=metadata_payload_key,\n            distance_strategy=distance_func,\n            vector_name=vector_name,\n        )\n        return qdrant\n[docs]    @classmethod\n    async def aconstruct_instance(\n        cls: Type[Qdrant],\n        texts: List[str],\n        embedding: Embeddings,\n        location: Optional[str] = None,\n        url: Optional[str] = None,\n        port: Optional[int] = 6333,\n        grpc_port: int = 6334,\n        prefer_grpc: bool = False,\n        https: Optional[bool] = None,\n        api_key: Optional[str] = None,\n        prefix: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-40", "text": "prefix: Optional[str] = None,\n        timeout: Optional[float] = None,\n        host: Optional[str] = None,\n        path: Optional[str] = None,\n        collection_name: Optional[str] = None,\n        distance_func: str = \"Cosine\",\n        content_payload_key: str = CONTENT_KEY,\n        metadata_payload_key: str = METADATA_KEY,\n        vector_name: Optional[str] = VECTOR_NAME,\n        shard_number: Optional[int] = None,\n        replication_factor: Optional[int] = None,\n        write_consistency_factor: Optional[int] = None,\n        on_disk_payload: Optional[bool] = None,\n        hnsw_config: Optional[common_types.HnswConfigDiff] = None,\n        optimizers_config: Optional[common_types.OptimizersConfigDiff] = None,\n        wal_config: Optional[common_types.WalConfigDiff] = None,\n        quantization_config: Optional[common_types.QuantizationConfig] = None,\n        init_from: Optional[common_types.InitFrom] = None,\n        on_disk: Optional[bool] = None,\n        force_recreate: bool = False,\n        **kwargs: Any,\n    ) -> Qdrant:\n        try:\n            import qdrant_client\n        except ImportError:\n            raise ValueError(\n                \"Could not import qdrant-client python package. \"\n                \"Please install it with `pip install qdrant-client`.\"\n            )\n        from grpc import RpcError\n        from qdrant_client.http import models as rest\n        from qdrant_client.http.exceptions import UnexpectedResponse\n        # Just do a single quick embedding to get vector size\n        partial_embeddings = await embedding.aembed_documents(texts[:1])\n        vector_size = len(partial_embeddings[0])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-41", "text": "vector_size = len(partial_embeddings[0])\n        collection_name = collection_name or uuid.uuid4().hex\n        distance_func = distance_func.upper()\n        client = qdrant_client.QdrantClient(\n            location=location,\n            url=url,\n            port=port,\n            grpc_port=grpc_port,\n            prefer_grpc=prefer_grpc,\n            https=https,\n            api_key=api_key,\n            prefix=prefix,\n            timeout=timeout,\n            host=host,\n            path=path,\n            **kwargs,\n        )\n        try:\n            # Skip any validation in case of forced collection recreate.\n            if force_recreate:\n                raise ValueError\n            # Get the vector configuration of the existing collection and vector, if it\n            # was specified. If the old configuration does not match the current one,\n            # an exception is being thrown.\n            collection_info = client.get_collection(collection_name=collection_name)\n            current_vector_config = collection_info.config.params.vectors\n            if isinstance(current_vector_config, dict) and vector_name is not None:\n                if vector_name not in current_vector_config:\n                    raise QdrantException(\n                        f\"Existing Qdrant collection {collection_name} does not \"\n                        f\"contain vector named {vector_name}. Did you mean one of the \"\n                        f\"existing vectors: {', '.join(current_vector_config.keys())}? \"\n                        f\"If you want to recreate the collection, set `force_recreate` \"\n                        f\"parameter to `True`.\"\n                    )\n                current_vector_config = current_vector_config.get(vector_name)  # type: ignore[assignment]\n            elif isinstance(current_vector_config, dict) and vector_name is None:\n                raise QdrantException(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-42", "text": "raise QdrantException(\n                    f\"Existing Qdrant collection {collection_name} uses named vectors. \"\n                    f\"If you want to reuse it, please set `vector_name` to any of the \"\n                    f\"existing named vectors: \"\n                    f\"{', '.join(current_vector_config.keys())}.\"  # noqa\n                    f\"If you want to recreate the collection, set `force_recreate` \"\n                    f\"parameter to `True`.\"\n                )\n            elif (\n                not isinstance(current_vector_config, dict) and vector_name is not None\n            ):\n                raise QdrantException(\n                    f\"Existing Qdrant collection {collection_name} doesn't use named \"\n                    f\"vectors. If you want to reuse it, please set `vector_name` to \"\n                    f\"`None`. If you want to recreate the collection, set \"\n                    f\"`force_recreate` parameter to `True`.\"\n                )\n            # Check if the vector configuration has the same dimensionality.\n            if current_vector_config.size != vector_size:  # type: ignore[union-attr]\n                raise QdrantException(\n                    f\"Existing Qdrant collection is configured for vectors with \"\n                    f\"{current_vector_config.size} \"  # type: ignore[union-attr]\n                    f\"dimensions. Selected embeddings are {vector_size}-dimensional. \"\n                    f\"If you want to recreate the collection, set `force_recreate` \"\n                    f\"parameter to `True`.\"\n                )\n            current_distance_func = (\n                current_vector_config.distance.name.upper()  # type: ignore[union-attr]\n            )\n            if current_distance_func != distance_func:\n                raise QdrantException(\n                    f\"Existing Qdrant collection is configured for \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-43", "text": "f\"Existing Qdrant collection is configured for \"\n                    f\"{current_vector_config.distance} \"  # type: ignore[union-attr]\n                    f\"similarity. Please set `distance_func` parameter to \"\n                    f\"`{distance_func}` if you want to reuse it. If you want to \"\n                    f\"recreate the collection, set `force_recreate` parameter to \"\n                    f\"`True`.\"\n                )\n        except (UnexpectedResponse, RpcError, ValueError):\n            vectors_config = rest.VectorParams(\n                size=vector_size,\n                distance=rest.Distance[distance_func],\n                on_disk=on_disk,\n            )\n            # If vector name was provided, we're going to use the named vectors feature\n            # with just a single vector.\n            if vector_name is not None:\n                vectors_config = {  # type: ignore[assignment]\n                    vector_name: vectors_config,\n                }\n            client.recreate_collection(\n                collection_name=collection_name,\n                vectors_config=vectors_config,\n                shard_number=shard_number,\n                replication_factor=replication_factor,\n                write_consistency_factor=write_consistency_factor,\n                on_disk_payload=on_disk_payload,\n                hnsw_config=hnsw_config,\n                optimizers_config=optimizers_config,\n                wal_config=wal_config,\n                quantization_config=quantization_config,\n                init_from=init_from,\n                timeout=timeout,  # type: ignore[arg-type]\n            )\n        qdrant = cls(\n            client=client,\n            collection_name=collection_name,\n            embeddings=embedding,\n            content_payload_key=content_payload_key,\n            metadata_payload_key=metadata_payload_key,\n            distance_strategy=distance_func,\n            vector_name=vector_name,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-44", "text": "distance_strategy=distance_func,\n            vector_name=vector_name,\n        )\n        return qdrant\n    @staticmethod\n    def _cosine_relevance_score_fn(distance: float) -> float:\n        \"\"\"Normalize the distance to a score on a scale [0, 1].\"\"\"\n        return (distance + 1.0) / 2.0\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        \"\"\"\n        The 'correct' relevance function\n        may differ depending on a few things, including:\n        - the distance / similarity metric used by the VectorStore\n        - the scale of your embeddings (OpenAI's are unit normed. Many others are not!)\n        - embedding dimensionality\n        - etc.\n        \"\"\"\n        if self.distance_strategy == \"COSINE\":\n            return self._cosine_relevance_score_fn\n        elif self.distance_strategy == \"DOT\":\n            return self._max_inner_product_relevance_score_fn\n        elif self.distance_strategy == \"EUCLID\":\n            return self._euclidean_relevance_score_fn\n        else:\n            raise ValueError(\n                \"Unknown distance strategy, must be cosine, \"\n                \"max_inner_product, or euclidean\"\n            )\n    def _similarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs and relevance scores in the range [0, 1].\n        0 is dissimilar, 1 is most similar.\n        Args:\n            query: input text\n            k: Number of Documents to return. Defaults to 4.\n            **kwargs: kwargs to be passed to similarity search. Should include:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-45", "text": "**kwargs: kwargs to be passed to similarity search. Should include:\n                score_threshold: Optional, a floating point value between 0 to 1 to\n                    filter the resulting set of retrieved docs\n        Returns:\n            List of Tuples of (doc, similarity_score)\n        \"\"\"\n        return self.similarity_search_with_score(query, k, **kwargs)\n    @classmethod\n    def _build_payloads(\n        cls,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]],\n        content_payload_key: str,\n        metadata_payload_key: str,\n    ) -> List[dict]:\n        payloads = []\n        for i, text in enumerate(texts):\n            if text is None:\n                raise ValueError(\n                    \"At least one of the texts is None. Please remove it before \"\n                    \"calling .from_texts or .add_texts on Qdrant instance.\"\n                )\n            metadata = metadatas[i] if metadatas is not None else None\n            payloads.append(\n                {\n                    content_payload_key: text,\n                    metadata_payload_key: metadata,\n                }\n            )\n        return payloads\n    @classmethod\n    def _document_from_scored_point(\n        cls,\n        scored_point: Any,\n        content_payload_key: str,\n        metadata_payload_key: str,\n    ) -> Document:\n        return Document(\n            page_content=scored_point.payload.get(content_payload_key),\n            metadata=scored_point.payload.get(metadata_payload_key) or {},\n        )\n    @classmethod\n    def _document_from_scored_point_grpc(\n        cls,\n        scored_point: Any,\n        content_payload_key: str,\n        metadata_payload_key: str,\n    ) -> Document:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-46", "text": "metadata_payload_key: str,\n    ) -> Document:\n        from qdrant_client.conversions.conversion import grpc_to_payload\n        payload = grpc_to_payload(scored_point.payload)\n        return Document(\n            page_content=payload[content_payload_key],\n            metadata=payload.get(metadata_payload_key) or {},\n        )\n    def _build_condition(self, key: str, value: Any) -> List[rest.FieldCondition]:\n        from qdrant_client.http import models as rest\n        out = []\n        if isinstance(value, dict):\n            for _key, value in value.items():\n                out.extend(self._build_condition(f\"{key}.{_key}\", value))\n        elif isinstance(value, list):\n            for _value in value:\n                if isinstance(_value, dict):\n                    out.extend(self._build_condition(f\"{key}[]\", _value))\n                else:\n                    out.extend(self._build_condition(f\"{key}\", _value))\n        else:\n            out.append(\n                rest.FieldCondition(\n                    key=f\"{self.metadata_payload_key}.{key}\",\n                    match=rest.MatchValue(value=value),\n                )\n            )\n        return out\n    def _qdrant_filter_from_dict(\n        self, filter: Optional[DictFilter]\n    ) -> Optional[rest.Filter]:\n        from qdrant_client.http import models as rest\n        if not filter:\n            return None\n        return rest.Filter(\n            must=[\n                condition\n                for key, value in filter.items()\n                for condition in self._build_condition(key, value)\n            ]\n        )\n    def _embed_query(self, query: str) -> List[float]:\n        \"\"\"Embed query text.\n        Used to provide backward compatibility with `embedding_function` argument.\n        Args:\n            query: Query text.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-47", "text": "Args:\n            query: Query text.\n        Returns:\n            List of floats representing the query embedding.\n        \"\"\"\n        if self.embeddings is not None:\n            embedding = self.embeddings.embed_query(query)\n        else:\n            if self._embeddings_function is not None:\n                embedding = self._embeddings_function(query)\n            else:\n                raise ValueError(\"Neither of embeddings or embedding_function is set\")\n        return embedding.tolist() if hasattr(embedding, \"tolist\") else embedding\n    def _embed_texts(self, texts: Iterable[str]) -> List[List[float]]:\n        \"\"\"Embed search texts.\n        Used to provide backward compatibility with `embedding_function` argument.\n        Args:\n            texts: Iterable of texts to embed.\n        Returns:\n            List of floats representing the texts embedding.\n        \"\"\"\n        if self.embeddings is not None:\n            embeddings = self.embeddings.embed_documents(list(texts))\n            if hasattr(embeddings, \"tolist\"):\n                embeddings = embeddings.tolist()\n        elif self._embeddings_function is not None:\n            embeddings = []\n            for text in texts:\n                embedding = self._embeddings_function(text)\n                if hasattr(embeddings, \"tolist\"):\n                    embedding = embedding.tolist()\n                embeddings.append(embedding)\n        else:\n            raise ValueError(\"Neither of embeddings or embedding_function is set\")\n        return embeddings\n    async def _aembed_texts(self, texts: Iterable[str]) -> List[List[float]]:\n        \"\"\"Embed search texts.\n        Used to provide backward compatibility with `embedding_function` argument.\n        Args:\n            texts: Iterable of texts to embed.\n        Returns:\n            List of floats representing the texts embedding.\n        \"\"\"\n        if self.embeddings is not None:\n            embeddings = await self.embeddings.aembed_documents(list(texts))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-48", "text": "embeddings = await self.embeddings.aembed_documents(list(texts))\n            if hasattr(embeddings, \"tolist\"):\n                embeddings = embeddings.tolist()\n        elif self._embeddings_function is not None:\n            embeddings = []\n            for text in texts:\n                embedding = self._embeddings_function(text)\n                if hasattr(embeddings, \"tolist\"):\n                    embedding = embedding.tolist()\n                embeddings.append(embedding)\n        else:\n            raise ValueError(\"Neither of embeddings or embedding_function is set\")\n        return embeddings\n    def _generate_rest_batches(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[Sequence[str]] = None,\n        batch_size: int = 64,\n    ) -> Generator[Tuple[List[str], List[rest.PointStruct]], None, None]:\n        from qdrant_client.http import models as rest\n        texts_iterator = iter(texts)\n        metadatas_iterator = iter(metadatas or [])\n        ids_iterator = iter(ids or [uuid.uuid4().hex for _ in iter(texts)])\n        while batch_texts := list(islice(texts_iterator, batch_size)):\n            # Take the corresponding metadata and id for each text in a batch\n            batch_metadatas = list(islice(metadatas_iterator, batch_size)) or None\n            batch_ids = list(islice(ids_iterator, batch_size))\n            # Generate the embeddings for all the texts in a batch\n            batch_embeddings = self._embed_texts(batch_texts)\n            points = [\n                rest.PointStruct(\n                    id=point_id,\n                    vector=vector\n                    if self.vector_name is None\n                    else {self.vector_name: vector},\n                    payload=payload,\n                )\n                for point_id, vector, payload in zip(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-49", "text": ")\n                for point_id, vector, payload in zip(\n                    batch_ids,\n                    batch_embeddings,\n                    self._build_payloads(\n                        batch_texts,\n                        batch_metadatas,\n                        self.content_payload_key,\n                        self.metadata_payload_key,\n                    ),\n                )\n            ]\n            yield batch_ids, points\n    async def _agenerate_rest_batches(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[Sequence[str]] = None,\n        batch_size: int = 64,\n    ) -> AsyncGenerator[Tuple[List[str], List[rest.PointStruct]], None]:\n        from qdrant_client.http import models as rest\n        texts_iterator = iter(texts)\n        metadatas_iterator = iter(metadatas or [])\n        ids_iterator = iter(ids or [uuid.uuid4().hex for _ in iter(texts)])\n        while batch_texts := list(islice(texts_iterator, batch_size)):\n            # Take the corresponding metadata and id for each text in a batch\n            batch_metadatas = list(islice(metadatas_iterator, batch_size)) or None\n            batch_ids = list(islice(ids_iterator, batch_size))\n            # Generate the embeddings for all the texts in a batch\n            batch_embeddings = await self._aembed_texts(batch_texts)\n            points = [\n                rest.PointStruct(\n                    id=point_id,\n                    vector=vector\n                    if self.vector_name is None\n                    else {self.vector_name: vector},\n                    payload=payload,\n                )\n                for point_id, vector, payload in zip(\n                    batch_ids,\n                    batch_embeddings,\n                    self._build_payloads(\n                        batch_texts,\n                        batch_metadatas,\n                        self.content_payload_key,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "eec294367d7f-50", "text": "batch_texts,\n                        batch_metadatas,\n                        self.content_payload_key,\n                        self.metadata_payload_key,\n                    ),\n                )\n            ]\n            yield batch_ids, points", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html"}
{"id": "4bfae7e95860-0", "text": "Source code for langchain.vectorstores.epsilla\n\"\"\"Wrapper around Epsilla vector database.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport uuid\nfrom typing import TYPE_CHECKING, Any, Iterable, List, Optional, Type\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nif TYPE_CHECKING:\n    from pyepsilla import vectordb\nlogger = logging.getLogger()\n[docs]class Epsilla(VectorStore):\n    \"\"\"\n    Wrapper around Epsilla vector database.\n    As a prerequisite, you need to install ``pyepsilla`` package\n    and have a running Epsilla vector database (for example, through our docker image)\n    See the following documentation for how to run an Epsilla vector database:\n    https://epsilla-inc.gitbook.io/epsilladb/quick-start\n    Args:\n        client (Any): Epsilla client to connect to.\n        embeddings (Embeddings): Function used to embed the texts.\n        db_path (Optional[str]): The path where the database will be persisted.\n                                 Defaults to \"/tmp/langchain-epsilla\".\n        db_name (Optional[str]): Give a name to the loaded database.\n                                 Defaults to \"langchain_store\".\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import Epsilla\n            from pyepsilla import vectordb\n            client = vectordb.Client()\n            embeddings = OpenAIEmbeddings()\n            db_path = \"/tmp/vectorstore\"\n            db_name = \"langchain_store\"\n            epsilla = Epsilla(client, embeddings, db_path, db_name)\n    \"\"\"\n    _LANGCHAIN_DEFAULT_DB_NAME = \"langchain_store\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html"}
{"id": "4bfae7e95860-1", "text": "\"\"\"\n    _LANGCHAIN_DEFAULT_DB_NAME = \"langchain_store\"\n    _LANGCHAIN_DEFAULT_DB_PATH = \"/tmp/langchain-epsilla\"\n    _LANGCHAIN_DEFAULT_TABLE_NAME = \"langchain_collection\"\n[docs]    def __init__(\n        self,\n        client: Any,\n        embeddings: Embeddings,\n        db_path: Optional[str] = _LANGCHAIN_DEFAULT_DB_PATH,\n        db_name: Optional[str] = _LANGCHAIN_DEFAULT_DB_NAME,\n    ):\n        \"\"\"Initialize with necessary components.\"\"\"\n        try:\n            import pyepsilla\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import pyepsilla python package. \"\n                \"Please install pyepsilla package with `pip install pyepsilla`.\"\n            ) from e\n        if not isinstance(client, pyepsilla.vectordb.Client):\n            raise TypeError(\n                f\"client should be an instance of pyepsilla.vectordb.Client, \"\n                f\"got {type(client)}\"\n            )\n        self._client: vectordb.Client = client\n        self._db_name = db_name\n        self._embeddings = embeddings\n        self._collection_name = Epsilla._LANGCHAIN_DEFAULT_TABLE_NAME\n        self._client.load_db(db_name=db_name, db_path=db_path)\n        self._client.use_db(db_name=db_name)\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return self._embeddings\n[docs]    def use_collection(self, collection_name: str) -> None:\n        \"\"\"\n        Set default collection to use.\n        Args:\n            collection_name (str): The name of the collection.\n        \"\"\"\n        self._collection_name = collection_name", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html"}
{"id": "4bfae7e95860-2", "text": "\"\"\"\n        self._collection_name = collection_name\n[docs]    def clear_data(self, collection_name: str = \"\") -> None:\n        \"\"\"\n        Clear data in a collection.\n        Args:\n            collection_name (Optional[str]): The name of the collection.\n                If not provided, the default collection will be used.\n        \"\"\"\n        if not collection_name:\n            collection_name = self._collection_name\n        self._client.drop_table(collection_name)\n[docs]    def get(\n        self, collection_name: str = \"\", response_fields: Optional[List[str]] = None\n    ) -> List[dict]:\n        \"\"\"Get the collection.\n        Args:\n            collection_name (Optional[str]): The name of the collection\n                to retrieve data from.\n                If not provided, the default collection will be used.\n            response_fields (Optional[List[str]]): List of field names in the result.\n                If not specified, all available fields will be responded.\n        Returns:\n            A list of the retrieved data.\n        \"\"\"\n        if not collection_name:\n            collection_name = self._collection_name\n        status_code, response = self._client.get(\n            table_name=collection_name, response_fields=response_fields\n        )\n        if status_code != 200:\n            logger.error(f\"Failed to get records: {response['message']}\")\n            raise Exception(\"Error: {}.\".format(response[\"message\"]))\n        return response[\"result\"]\n    def _create_collection(\n        self, table_name: str, embeddings: list, metadatas: Optional[list[dict]] = None\n    ) -> None:\n        if not embeddings:\n            raise ValueError(\"Embeddings list is empty.\")\n        dim = len(embeddings[0])\n        fields: List[dict] = [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html"}
{"id": "4bfae7e95860-3", "text": "dim = len(embeddings[0])\n        fields: List[dict] = [\n            {\"name\": \"id\", \"dataType\": \"INT\"},\n            {\"name\": \"text\", \"dataType\": \"STRING\"},\n            {\"name\": \"embeddings\", \"dataType\": \"VECTOR_FLOAT\", \"dimensions\": dim},\n        ]\n        if metadatas is not None:\n            field_names = [field[\"name\"] for field in fields]\n            for metadata in metadatas:\n                for key, value in metadata.items():\n                    if key in field_names:\n                        continue\n                    d_type: str\n                    if isinstance(value, str):\n                        d_type = \"STRING\"\n                    elif isinstance(value, int):\n                        d_type = \"INT\"\n                    elif isinstance(value, float):\n                        d_type = \"FLOAT\"\n                    elif isinstance(value, bool):\n                        d_type = \"BOOL\"\n                    else:\n                        raise ValueError(f\"Unsupported data type for {key}.\")\n                    fields.append({\"name\": key, \"dataType\": d_type})\n                    field_names.append(key)\n        status_code, response = self._client.create_table(\n            table_name, table_fields=fields\n        )\n        if status_code != 200:\n            if status_code == 409:\n                logger.info(f\"Continuing with the existing table {table_name}.\")\n            else:\n                logger.error(\n                    f\"Failed to create collection {table_name}: {response['message']}\"\n                )\n                raise Exception(\"Error: {}.\".format(response[\"message\"]))\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        collection_name: Optional[str] = \"\",\n        drop_old: Optional[bool] = False,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html"}
{"id": "4bfae7e95860-4", "text": "drop_old: Optional[bool] = False,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"\n        Embed texts and add them to the database.\n        Args:\n            texts (Iterable[str]): The texts to embed.\n            metadatas (Optional[List[dict]]): Metadata dicts\n                        attached to each of the texts. Defaults to None.\n            collection_name (Optional[str]): Which collection to use.\n                        Defaults to \"langchain_collection\".\n                        If provided, default collection name will be set as well.\n            drop_old (Optional[bool]): Whether to drop the previous collection\n                        and create a new one. Defaults to False.\n        Returns:\n            List of ids of the added texts.\n        \"\"\"\n        if not collection_name:\n            collection_name = self._collection_name\n        else:\n            self._collection_name = collection_name\n        if drop_old:\n            self._client.drop_db(db_name=collection_name)\n        texts = list(texts)\n        try:\n            embeddings = self._embeddings.embed_documents(texts)\n        except NotImplementedError:\n            embeddings = [self._embeddings.embed_query(x) for x in texts]\n        if len(embeddings) == 0:\n            logger.debug(\"Nothing to insert, skipping.\")\n            return []\n        self._create_collection(\n            table_name=collection_name, embeddings=embeddings, metadatas=metadatas\n        )\n        ids = [hash(uuid.uuid4()) for _ in texts]\n        records = []\n        for index, id in enumerate(ids):\n            record = {\n                \"id\": id,\n                \"text\": texts[index],\n                \"embeddings\": embeddings[index],\n            }\n            if metadatas is not None:\n                metadata = metadatas[index].items()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html"}
{"id": "4bfae7e95860-5", "text": "metadata = metadatas[index].items()\n                for key, value in metadata:\n                    record[key] = value\n            records.append(record)\n        status_code, response = self._client.insert(\n            table_name=collection_name, records=records\n        )\n        if status_code != 200:\n            logger.error(\n                f\"Failed to add records to {collection_name}: {response['message']}\"\n            )\n            raise Exception(\"Error: {}.\".format(response[\"message\"]))\n        return [str(id) for id in ids]\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, collection_name: str = \"\", **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"\n        Return the documents that are semantically most relevant to the query.\n        Args:\n            query (str): String to query the vectorstore with.\n            k (Optional[int]): Number of documents to return. Defaults to 4.\n            collection_name (Optional[str]): Collection to use.\n                Defaults to \"langchain_store\" or the one provided before.\n        Returns:\n            List of documents that are semantically most relevant to the query\n        \"\"\"\n        if not collection_name:\n            collection_name = self._collection_name\n        query_vector = self._embeddings.embed_query(query)\n        status_code, response = self._client.query(\n            table_name=collection_name,\n            query_field=\"embeddings\",\n            query_vector=query_vector,\n            limit=k,\n        )\n        if status_code != 200:\n            logger.error(f\"Search failed: {response['message']}.\")\n            raise Exception(\"Error: {}.\".format(response[\"message\"]))\n        exclude_keys = [\"id\", \"text\", \"embeddings\"]\n        return list(\n            map(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html"}
{"id": "4bfae7e95860-6", "text": "return list(\n            map(\n                lambda item: Document(\n                    page_content=item[\"text\"],\n                    metadata={\n                        key: item[key] for key in item if key not in exclude_keys\n                    },\n                ),\n                response[\"result\"],\n            )\n        )\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[Epsilla],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        client: Any = None,\n        db_path: Optional[str] = _LANGCHAIN_DEFAULT_DB_PATH,\n        db_name: Optional[str] = _LANGCHAIN_DEFAULT_DB_NAME,\n        collection_name: Optional[str] = _LANGCHAIN_DEFAULT_TABLE_NAME,\n        drop_old: Optional[bool] = False,\n        **kwargs: Any,\n    ) -> Epsilla:\n        \"\"\"Create an Epsilla vectorstore from raw documents.\n        Args:\n            texts (List[str]): List of text data to be inserted.\n            embeddings (Embeddings): Embedding function.\n            client (pyepsilla.vectordb.Client): Epsilla client to connect to.\n            metadatas (Optional[List[dict]]): Metadata for each text.\n                    Defaults to None.\n            db_path (Optional[str]): The path where the database will be persisted.\n                    Defaults to \"/tmp/langchain-epsilla\".\n            db_name (Optional[str]): Give a name to the loaded database.\n                    Defaults to \"langchain_store\".\n            collection_name (Optional[str]): Which collection to use.\n                    Defaults to \"langchain_collection\".\n                    If provided, default collection name will be set as well.\n            drop_old (Optional[bool]): Whether to drop the previous collection", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html"}
{"id": "4bfae7e95860-7", "text": "drop_old (Optional[bool]): Whether to drop the previous collection\n                    and create a new one. Defaults to False.\n        Returns:\n            Epsilla: Epsilla vector store.\n        \"\"\"\n        instance = Epsilla(client, embedding, db_path=db_path, db_name=db_name)\n        instance.add_texts(\n            texts,\n            metadatas=metadatas,\n            collection_name=collection_name,\n            drop_old=drop_old,\n            **kwargs,\n        )\n        return instance\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[Epsilla],\n        documents: List[Document],\n        embedding: Embeddings,\n        client: Any = None,\n        db_path: Optional[str] = _LANGCHAIN_DEFAULT_DB_PATH,\n        db_name: Optional[str] = _LANGCHAIN_DEFAULT_DB_NAME,\n        collection_name: Optional[str] = _LANGCHAIN_DEFAULT_TABLE_NAME,\n        drop_old: Optional[bool] = False,\n        **kwargs: Any,\n    ) -> Epsilla:\n        \"\"\"Create an Epsilla vectorstore from a list of documents.\n        Args:\n            texts (List[str]): List of text data to be inserted.\n            embeddings (Embeddings): Embedding function.\n            client (pyepsilla.vectordb.Client): Epsilla client to connect to.\n            metadatas (Optional[List[dict]]): Metadata for each text.\n                    Defaults to None.\n            db_path (Optional[str]): The path where the database will be persisted.\n                    Defaults to \"/tmp/langchain-epsilla\".\n            db_name (Optional[str]): Give a name to the loaded database.\n                    Defaults to \"langchain_store\".\n            collection_name (Optional[str]): Which collection to use.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html"}
{"id": "4bfae7e95860-8", "text": "collection_name (Optional[str]): Which collection to use.\n                    Defaults to \"langchain_collection\".\n                    If provided, default collection name will be set as well.\n            drop_old (Optional[bool]): Whether to drop the previous collection\n                    and create a new one. Defaults to False.\n        Returns:\n            Epsilla: Epsilla vector store.\n        \"\"\"\n        texts = [doc.page_content for doc in documents]\n        metadatas = [doc.metadata for doc in documents]\n        return cls.from_texts(\n            texts,\n            embedding,\n            metadatas=metadatas,\n            client=client,\n            db_path=db_path,\n            db_name=db_name,\n            collection_name=collection_name,\n            drop_old=drop_old,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/epsilla.html"}
{"id": "1437a67e6df1-0", "text": "Source code for langchain.vectorstores.dingo\nfrom __future__ import annotations\nimport logging\nimport uuid\nfrom typing import Any, Iterable, List, Optional, Tuple\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nlogger = logging.getLogger(__name__)\n[docs]class Dingo(VectorStore):\n    \"\"\"`Dingo` vector store.\n    To use, you should have the ``dingodb`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import Dingo\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            embeddings = OpenAIEmbeddings()\n            dingo = Dingo(embeddings, \"text\")\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        text_key: str,\n        *,\n        client: Any = None,\n        index_name: Optional[str] = None,\n        dimension: int = 1024,\n        host: Optional[List[str]] = None,\n        user: str = \"root\",\n        password: str = \"123123\",\n        self_id: bool = False,\n    ):\n        \"\"\"Initialize with Dingo client.\"\"\"\n        try:\n            import dingodb\n        except ImportError:\n            raise ImportError(\n                \"Could not import dingo python package. \"\n                \"Please install it with `pip install dingodb.\"\n            )\n        host = host if host is not None else [\"172.20.31.10:13000\"]\n        # collection\n        if client is not None:\n            dingo_client = client\n        else:\n            try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html"}
{"id": "1437a67e6df1-1", "text": "dingo_client = client\n        else:\n            try:\n                # connect to dingo db\n                dingo_client = dingodb.DingoDB(user, password, host)\n            except ValueError as e:\n                raise ValueError(f\"Dingo failed to connect: {e}\")\n        self._text_key = text_key\n        self._client = dingo_client\n        if (\n            index_name is not None\n            and index_name not in dingo_client.get_index()\n            and index_name.upper() not in dingo_client.get_index()\n        ):\n            if self_id is True:\n                dingo_client.create_index(\n                    index_name, dimension=dimension, auto_id=False\n                )\n            else:\n                dingo_client.create_index(index_name, dimension=dimension)\n        self._index_name = index_name\n        self._embedding = embedding\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return self._embedding\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        text_key: str = \"text\",\n        batch_size: int = 500,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of ids to associate with the texts.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        # Embed and create the documents", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html"}
{"id": "1437a67e6df1-2", "text": "\"\"\"\n        # Embed and create the documents\n        ids = ids or [str(uuid.uuid1().int)[:13] for _ in texts]\n        metadatas_list = []\n        texts = list(texts)\n        embeds = self._embedding.embed_documents(texts)\n        for i, text in enumerate(texts):\n            metadata = metadatas[i] if metadatas else {}\n            metadata[self._text_key] = text\n            metadatas_list.append(metadata)\n        # upsert to Dingo\n        for i in range(0, len(list(texts)), batch_size):\n            j = i + batch_size\n            add_res = self._client.vector_add(\n                self._index_name, metadatas_list[i:j], embeds[i:j], ids[i:j]\n            )\n            if not add_res:\n                raise Exception(\"vector add fail\")\n        return ids\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        search_params: Optional[dict] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return Dingo documents most similar to query, along with scores.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            search_params: Dictionary of argument(s) to filter on metadata\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(\n            query, k=k, search_params=search_params\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search_with_score(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html"}
{"id": "1437a67e6df1-3", "text": "[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        search_params: Optional[dict] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return Dingo documents most similar to query, along with scores.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            search_params: Dictionary of argument(s) to filter on metadata\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        docs = []\n        query_obj = self._embedding.embed_query(query)\n        results = self._client.vector_search(\n            self._index_name, xq=query_obj, top_k=k, search_params=search_params\n        )\n        if not results:\n            return []\n        for res in results[0][\"vectorWithDistances\"]:\n            metadatas = res[\"scalarData\"]\n            id = res[\"id\"]\n            score = res[\"distance\"]\n            text = metadatas[self._text_key][\"fields\"][0][\"data\"]\n            metadata = {\"id\": id, \"text\": text, \"score\": score}\n            for meta_key in metadatas.keys():\n                metadata[meta_key] = metadatas[meta_key][\"fields\"][0][\"data\"]\n            docs.append((Document(page_content=text, metadata=metadata), score))\n        return docs\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html"}
{"id": "1437a67e6df1-4", "text": "k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        search_params: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        results = self._client.vector_search(\n            self._index_name, [embedding], search_params=search_params, top_k=k\n        )\n        mmr_selected = maximal_marginal_relevance(\n            np.array([embedding], dtype=np.float32),\n            [\n                item[\"vector\"][\"floatValues\"]\n                for item in results[0][\"vectorWithDistances\"]\n            ],\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        selected = []\n        for i in mmr_selected:\n            meta_data = {}\n            for k, v in results[0][\"vectorWithDistances\"][i][\"scalarData\"].items():\n                meta_data.update({str(k): v[\"fields\"][0][\"data\"]})\n            selected.append(meta_data)\n        return [\n            Document(page_content=metadata.pop(self._text_key), metadata=metadata)\n            for metadata in selected", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html"}
{"id": "1437a67e6df1-5", "text": "for metadata in selected\n        ]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        search_params: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        embedding = self._embedding.embed_query(query)\n        return self.max_marginal_relevance_search_by_vector(\n            embedding, k, fetch_k, lambda_mult, search_params\n        )\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        text_key: str = \"text\",\n        index_name: Optional[str] = None,\n        dimension: int = 1024,\n        client: Any = None,\n        host: List[str] = [\"172.20.31.10:13000\"],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html"}
{"id": "1437a67e6df1-6", "text": "host: List[str] = [\"172.20.31.10:13000\"],\n        user: str = \"root\",\n        password: str = \"123123\",\n        batch_size: int = 500,\n        **kwargs: Any,\n    ) -> Dingo:\n        \"\"\"Construct Dingo wrapper from raw documents.\n                This is a user friendly interface that:\n                    1. Embeds documents.\n                    2. Adds the documents to a provided Dingo index\n                This is intended to be a quick way to get started.\n                Example:\n                    .. code-block:: python\n                        from langchain.vectorstores import Dingo\n                        from langchain.embeddings import OpenAIEmbeddings\n                        import dingodb\n        sss\n                        embeddings = OpenAIEmbeddings()\n                        dingo = Dingo.from_texts(\n                            texts,\n                            embeddings,\n                            index_name=\"langchain-demo\"\n                        )\n        \"\"\"\n        try:\n            import dingodb\n        except ImportError:\n            raise ImportError(\n                \"Could not import dingo python package. \"\n                \"Please install it with `pip install dingodb`.\"\n            )\n        if client is not None:\n            dingo_client = client\n        else:\n            try:\n                # connect to dingo db\n                dingo_client = dingodb.DingoDB(user, password, host)\n            except ValueError as e:\n                raise ValueError(f\"Dingo failed to connect: {e}\")\n        if kwargs is not None and kwargs.get(\"self_id\") is True:\n            if (\n                index_name is not None\n                and index_name not in dingo_client.get_index()\n                and index_name.upper() not in dingo_client.get_index()\n            ):\n                dingo_client.create_index(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html"}
{"id": "1437a67e6df1-7", "text": "):\n                dingo_client.create_index(\n                    index_name, dimension=dimension, auto_id=False\n                )\n        else:\n            if (\n                index_name is not None\n                and index_name not in dingo_client.get_index()\n                and index_name.upper() not in dingo_client.get_index()\n            ):\n                dingo_client.create_index(index_name, dimension=dimension)\n        # Embed and create the documents\n        ids = ids or [str(uuid.uuid1().int)[:13] for _ in texts]\n        metadatas_list = []\n        texts = list(texts)\n        embeds = embedding.embed_documents(texts)\n        for i, text in enumerate(texts):\n            metadata = metadatas[i] if metadatas else {}\n            metadata[text_key] = text\n            metadatas_list.append(metadata)\n        # upsert to Dingo\n        for i in range(0, len(list(texts)), batch_size):\n            j = i + batch_size\n            add_res = dingo_client.vector_add(\n                index_name, metadatas_list[i:j], embeds[i:j], ids[i:j]\n            )\n            if not add_res:\n                raise Exception(\"vector add fail\")\n        return cls(embedding, text_key, client=dingo_client, index_name=index_name)\n[docs]    def delete(\n        self,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Delete by vector IDs or filter.\n        Args:\n            ids: List of ids to delete.\n        \"\"\"\n        if ids is None:\n            raise ValueError(\"No ids provided to delete.\")\n        return self._client.vector_delete(self._index_name, ids=ids)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dingo.html"}
{"id": "252c3ae2a6d6-0", "text": "Source code for langchain.vectorstores.cassandra\nfrom __future__ import annotations\nimport typing\nimport uuid\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n    TypeVar,\n    Union,\n)\nimport numpy as np\nif typing.TYPE_CHECKING:\n    from cassandra.cluster import Session\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nCVST = TypeVar(\"CVST\", bound=\"Cassandra\")\n[docs]class Cassandra(VectorStore):\n    \"\"\"Wrapper around Apache Cassandra(R) for vector-store workloads.\n    To use it, you need a recent installation of the `cassio` library\n    and a Cassandra cluster / Astra DB instance supporting vector capabilities.\n    Visit the cassio.org website for extensive quickstarts and code examples.\n    Example:\n        .. code-block:: python\n                from langchain.vectorstores import Cassandra\n                from langchain.embeddings.openai import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                session = ...             # create your Cassandra session object\n                keyspace = 'my_keyspace'  # the keyspace should exist already\n                table_name = 'my_vector_store'\n                vectorstore = Cassandra(embeddings, session, keyspace, table_name)\n    \"\"\"\n    _embedding_dimension: Union[int, None]\n    @staticmethod\n    def _filter_to_metadata(filter_dict: Optional[Dict[str, str]]) -> Dict[str, Any]:\n        if filter_dict is None:\n            return {}\n        else:\n            return filter_dict\n    def _get_embedding_dimension(self) -> int:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html"}
{"id": "252c3ae2a6d6-1", "text": "return filter_dict\n    def _get_embedding_dimension(self) -> int:\n        if self._embedding_dimension is None:\n            self._embedding_dimension = len(\n                self.embedding.embed_query(\"This is a sample sentence.\")\n            )\n        return self._embedding_dimension\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        session: Session,\n        keyspace: str,\n        table_name: str,\n        ttl_seconds: Optional[int] = None,\n    ) -> None:\n        try:\n            from cassio.vector import VectorTable\n        except (ImportError, ModuleNotFoundError):\n            raise ImportError(\n                \"Could not import cassio python package. \"\n                \"Please install it with `pip install cassio`.\"\n            )\n        \"\"\"Create a vector table.\"\"\"\n        self.embedding = embedding\n        self.session = session\n        self.keyspace = keyspace\n        self.table_name = table_name\n        self.ttl_seconds = ttl_seconds\n        #\n        self._embedding_dimension = None\n        #\n        self.table = VectorTable(\n            session=session,\n            keyspace=keyspace,\n            table=table_name,\n            embedding_dimension=self._get_embedding_dimension(),\n            primary_key_type=\"TEXT\",\n        )\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding\n    @staticmethod\n    def _dont_flip_the_cos_score(distance: float) -> float:\n        # the identity\n        return distance\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        \"\"\"\n        The underlying VectorTable already returns a \"score proper\",\n        i.e. one in [0, 1] where higher means more *similar*,\n        so here the final score transformation is not reversing the interval:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html"}
{"id": "252c3ae2a6d6-2", "text": "so here the final score transformation is not reversing the interval:\n        \"\"\"\n        return self._dont_flip_the_cos_score\n[docs]    def delete_collection(self) -> None:\n        \"\"\"\n        Just an alias for `clear`\n        (to better align with other VectorStore implementations).\n        \"\"\"\n        self.clear()\n[docs]    def clear(self) -> None:\n        \"\"\"Empty the collection.\"\"\"\n        self.table.clear()\n[docs]    def delete_by_document_id(self, document_id: str) -> None:\n        return self.table.delete(document_id)\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:\n        \"\"\"Delete by vector IDs.\n        Args:\n            ids: List of ids to delete.\n        Returns:\n            Optional[bool]: True if deletion is successful,\n            False otherwise, None if not implemented.\n        \"\"\"\n        if ids is None:\n            raise ValueError(\"No ids provided to delete.\")\n        for document_id in ids:\n            self.delete_by_document_id(document_id)\n        return True\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        batch_size: int = 16,\n        ttl_seconds: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts (Iterable[str]): Texts to add to the vectorstore.\n            metadatas (Optional[List[dict]], optional): Optional list of metadatas.\n            ids (Optional[List[str]], optional): Optional list of IDs.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html"}
{"id": "252c3ae2a6d6-3", "text": "ids (Optional[List[str]], optional): Optional list of IDs.\n            batch_size (int): Number of concurrent requests to send to the server.\n            ttl_seconds (Optional[int], optional): Optional time-to-live\n                for the added texts.\n        Returns:\n            List[str]: List of IDs of the added texts.\n        \"\"\"\n        _texts = list(texts)  # lest it be a generator or something\n        if ids is None:\n            ids = [uuid.uuid4().hex for _ in _texts]\n        if metadatas is None:\n            metadatas = [{} for _ in _texts]\n        #\n        ttl_seconds = ttl_seconds or self.ttl_seconds\n        #\n        embedding_vectors = self.embedding.embed_documents(_texts)\n        #\n        for i in range(0, len(_texts), batch_size):\n            batch_texts = _texts[i : i + batch_size]\n            batch_embedding_vectors = embedding_vectors[i : i + batch_size]\n            batch_ids = ids[i : i + batch_size]\n            batch_metadatas = metadatas[i : i + batch_size]\n            futures = [\n                self.table.put_async(\n                    text, embedding_vector, text_id, metadata, ttl_seconds\n                )\n                for text, embedding_vector, text_id, metadata in zip(\n                    batch_texts, batch_embedding_vectors, batch_ids, batch_metadatas\n                )\n            ]\n            for future in futures:\n                future.result()\n        return ids\n    # id-returning search facilities\n[docs]    def similarity_search_with_score_id_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n    ) -> List[Tuple[Document, float, str]]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html"}
{"id": "252c3ae2a6d6-4", "text": ") -> List[Tuple[Document, float, str]]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding (str): Embedding to look up documents similar to.\n            k (int): Number of Documents to return. Defaults to 4.\n        Returns:\n            List of (Document, score, id), the most similar to the query vector.\n        \"\"\"\n        search_metadata = self._filter_to_metadata(filter)\n        #\n        hits = self.table.search(\n            embedding_vector=embedding,\n            top_k=k,\n            metric=\"cos\",\n            metric_threshold=None,\n            metadata=search_metadata,\n        )\n        # We stick to 'cos' distance as it can be normalized on a 0-1 axis\n        # (1=most relevant), as required by this class' contract.\n        return [\n            (\n                Document(\n                    page_content=hit[\"document\"],\n                    metadata=hit[\"metadata\"],\n                ),\n                0.5 + 0.5 * hit[\"distance\"],\n                hit[\"document_id\"],\n            )\n            for hit in hits\n        ]\n[docs]    def similarity_search_with_score_id(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n    ) -> List[Tuple[Document, float, str]]:\n        embedding_vector = self.embedding.embed_query(query)\n        return self.similarity_search_with_score_id_by_vector(\n            embedding=embedding_vector,\n            k=k,\n            filter=filter,\n        )\n    # id-unaware search facilities\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html"}
{"id": "252c3ae2a6d6-5", "text": "self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding (str): Embedding to look up documents similar to.\n            k (int): Number of Documents to return. Defaults to 4.\n        Returns:\n            List of (Document, score), the most similar to the query vector.\n        \"\"\"\n        return [\n            (doc, score)\n            for (doc, score, docId) in self.similarity_search_with_score_id_by_vector(\n                embedding=embedding,\n                k=k,\n                filter=filter,\n            )\n        ]\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        embedding_vector = self.embedding.embed_query(query)\n        return self.similarity_search_by_vector(\n            embedding_vector,\n            k,\n            filter=filter,\n        )\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        return [\n            doc\n            for doc, _ in self.similarity_search_with_score_by_vector(\n                embedding,\n                k,\n                filter=filter,\n            )\n        ]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html"}
{"id": "252c3ae2a6d6-6", "text": "self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n    ) -> List[Tuple[Document, float]]:\n        embedding_vector = self.embedding.embed_query(query)\n        return self.similarity_search_with_score_by_vector(\n            embedding_vector,\n            k,\n            filter=filter,\n        )\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        search_metadata = self._filter_to_metadata(filter)\n        prefetchHits = self.table.search(\n            embedding_vector=embedding,\n            top_k=fetch_k,\n            metric=\"cos\",\n            metric_threshold=None,\n            metadata=search_metadata,\n        )\n        # let the mmr utility pick the *indices* in the above array\n        mmrChosenIndices = maximal_marginal_relevance(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html"}
{"id": "252c3ae2a6d6-7", "text": "mmrChosenIndices = maximal_marginal_relevance(\n            np.array(embedding, dtype=np.float32),\n            [pfHit[\"embedding_vector\"] for pfHit in prefetchHits],\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        mmrHits = [\n            pfHit\n            for pfIndex, pfHit in enumerate(prefetchHits)\n            if pfIndex in mmrChosenIndices\n        ]\n        return [\n            Document(\n                page_content=hit[\"document\"],\n                metadata=hit[\"metadata\"],\n            )\n            for hit in mmrHits\n        ]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Optional.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        embedding_vector = self.embedding.embed_query(query)\n        return self.max_marginal_relevance_search_by_vector(\n            embedding_vector,\n            k,\n            fetch_k,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html"}
{"id": "252c3ae2a6d6-8", "text": "embedding_vector,\n            k,\n            fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n        )\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[CVST],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        batch_size: int = 16,\n        **kwargs: Any,\n    ) -> CVST:\n        \"\"\"Create a Cassandra vectorstore from raw texts.\n        No support for specifying text IDs\n        Returns:\n            a Cassandra vectorstore.\n        \"\"\"\n        session: Session = kwargs[\"session\"]\n        keyspace: str = kwargs[\"keyspace\"]\n        table_name: str = kwargs[\"table_name\"]\n        cassandraStore = cls(\n            embedding=embedding,\n            session=session,\n            keyspace=keyspace,\n            table_name=table_name,\n        )\n        cassandraStore.add_texts(texts=texts, metadatas=metadatas)\n        return cassandraStore\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[CVST],\n        documents: List[Document],\n        embedding: Embeddings,\n        batch_size: int = 16,\n        **kwargs: Any,\n    ) -> CVST:\n        \"\"\"Create a Cassandra vectorstore from a document list.\n        No support for specifying text IDs\n        Returns:\n            a Cassandra vectorstore.\n        \"\"\"\n        texts = [doc.page_content for doc in documents]\n        metadatas = [doc.metadata for doc in documents]\n        session: Session = kwargs[\"session\"]\n        keyspace: str = kwargs[\"keyspace\"]\n        table_name: str = kwargs[\"table_name\"]\n        return cls.from_texts(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html"}
{"id": "252c3ae2a6d6-9", "text": "table_name: str = kwargs[\"table_name\"]\n        return cls.from_texts(\n            texts=texts,\n            metadatas=metadatas,\n            embedding=embedding,\n            session=session,\n            keyspace=keyspace,\n            table_name=table_name,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html"}
{"id": "bb31951a288f-0", "text": "Source code for langchain.vectorstores.baiducloud_vector_search\nimport logging\nimport uuid\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Union,\n)\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nif TYPE_CHECKING:\n    from elasticsearch import Elasticsearch\nlogger = logging.getLogger(__name__)\n[docs]class BESVectorStore(VectorStore):\n    \"\"\"`Baidu Elasticsearch` vector store.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import BESVectorStore\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            embeddings = OpenAIEmbeddings()\n            vectorstore = BESVectorStore(\n                embedding=OpenAIEmbeddings(),\n                index_name=\"langchain-demo\",\n                bes_url=\"http://localhost:9200\"\n            )\n    Args:\n        index_name: Name of the Elasticsearch index to create.\n        bes_url: URL of the Baidu Elasticsearch instance to connect to.\n        user: Username to use when connecting to Elasticsearch.\n        password: Password to use when connecting to Elasticsearch.\n        More information can be obtained from:\n        https://cloud.baidu.com/doc/BES/s/8llyn0hh4\n    \"\"\"\n[docs]    def __init__(\n        self,\n        index_name: str,\n        bes_url: str,\n        user: Optional[str] = None,\n        password: Optional[str] = None,\n        embedding: Optional[Embeddings] = None,\n        **kwargs: Optional[dict],\n    ) -> None:\n        self.embedding = embedding\n        self.index_name = index_name", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/baiducloud_vector_search.html"}
{"id": "bb31951a288f-1", "text": ") -> None:\n        self.embedding = embedding\n        self.index_name = index_name\n        self.query_field = kwargs.get(\"query_field\", \"text\")\n        self.vector_query_field = kwargs.get(\"vector_query_field\", \"vector\")\n        self.space_type = kwargs.get(\"space_type\", \"cosine\")\n        self.index_type = kwargs.get(\"index_type\", \"linear\")\n        self.index_params = kwargs.get(\"index_params\") or {}\n        if bes_url is not None:\n            self.client = BESVectorStore.bes_client(\n                bes_url=bes_url, username=user, password=password\n            )\n        else:\n            raise ValueError(\"\"\"Please specified a bes connection url.\"\"\")\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return self.embedding\n[docs]    @staticmethod\n    def bes_client(\n        *,\n        bes_url: Optional[str] = None,\n        username: Optional[str] = None,\n        password: Optional[str] = None,\n    ) -> \"Elasticsearch\":\n        try:\n            import elasticsearch\n        except ImportError:\n            raise ImportError(\n                \"Could not import elasticsearch python package. \"\n                \"Please install it with `pip install elasticsearch`.\"\n            )\n        connection_params: Dict[str, Any] = {}\n        connection_params[\"hosts\"] = [bes_url]\n        if username and password:\n            connection_params[\"basic_auth\"] = (username, password)\n        es_client = elasticsearch.Elasticsearch(**connection_params)\n        try:\n            es_client.info()\n        except Exception as e:\n            logger.error(f\"Error connecting to Elasticsearch: {e}\")\n            raise e\n        return es_client\n    def _create_index_if_not_exists(self, dims_length: Optional[int] = None) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/baiducloud_vector_search.html"}
{"id": "bb31951a288f-2", "text": "\"\"\"Create the index if it doesn't already exist.\n        Args:\n            dims_length: Length of the embedding vectors.\n        \"\"\"\n        if self.client.indices.exists(index=self.index_name):\n            logger.info(f\"Index {self.index_name} already exists. Skipping creation.\")\n        else:\n            if dims_length is None:\n                raise ValueError(\n                    \"Cannot create index without specifying dims_length \"\n                    + \"when the index doesn't already exist. \"\n                )\n            indexMapping = self._index_mapping(dims_length=dims_length)\n            logger.debug(\n                f\"Creating index {self.index_name} with mappings {indexMapping}\"\n            )\n            self.client.indices.create(\n                index=self.index_name,\n                body={\n                    \"settings\": {\"index\": {\"knn\": True}},\n                    \"mappings\": {\"properties\": indexMapping},\n                },\n            )\n    def _index_mapping(self, dims_length: Union[int, None]) -> Dict:\n        \"\"\"\n        Executes when the index is created.\n        Args:\n            dims_length: Numeric length of the embedding vectors,\n                        or None if not using vector-based query.\n            index_params: The extra pamameters for creating index.\n        Returns:\n            Dict: The Elasticsearch settings and mappings for the strategy.\n        \"\"\"\n        if \"linear\" == self.index_type:\n            return {\n                self.vector_query_field: {\n                    \"type\": \"bpack_vector\",\n                    \"dims\": dims_length,\n                    \"build_index\": self.index_params.get(\"build_index\", False),\n                }\n            }\n        elif \"hnsw\" == self.index_type:\n            return {\n                self.vector_query_field: {\n                    \"type\": \"bpack_vector\",\n                    \"dims\": dims_length,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/baiducloud_vector_search.html"}
{"id": "bb31951a288f-3", "text": "\"type\": \"bpack_vector\",\n                    \"dims\": dims_length,\n                    \"index_type\": \"hnsw\",\n                    \"space_type\": self.space_type,\n                    \"parameters\": {\n                        \"ef_construction\": self.index_params.get(\n                            \"hnsw_ef_construction\", 200\n                        ),\n                        \"m\": self.index_params.get(\"hnsw_m\", 4),\n                    },\n                }\n            }\n        else:\n            return {\n                self.vector_query_field: {\n                    \"type\": \"bpack_vector\",\n                    \"model_id\": self.index_params.get(\"model_id\", \"\"),\n                }\n            }\n[docs]    def delete(\n        self,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Optional[bool]:\n        \"\"\"Delete documents from the index.\n        Args:\n            ids: List of ids of documents to delete\n        \"\"\"\n        try:\n            from elasticsearch.helpers import BulkIndexError, bulk\n        except ImportError:\n            raise ImportError(\n                \"Could not import elasticsearch python package. \"\n                \"Please install it with `pip install elasticsearch`.\"\n            )\n        body = []\n        if ids is None:\n            raise ValueError(\"ids must be provided.\")\n        for _id in ids:\n            body.append({\"_op_type\": \"delete\", \"_index\": self.index_name, \"_id\": _id})\n        if len(body) > 0:\n            try:\n                bulk(\n                    self.client,\n                    body,\n                    refresh=kwargs.get(\"refresh_indices\", True),\n                    ignore_status=404,\n                )\n                logger.debug(f\"Deleted {len(body)} texts from index\")\n                return True\n            except BulkIndexError as e:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/baiducloud_vector_search.html"}
{"id": "bb31951a288f-4", "text": "return True\n            except BulkIndexError as e:\n                logger.error(f\"Error deleting texts: {e}\")\n                raise e\n        else:\n            logger.info(\"No documents to delete\")\n            return False\n    def _query_body(\n        self,\n        query_vector: Union[List[float], None],\n        filter: Optional[dict] = None,\n        search_params: Dict = {},\n    ) -> Dict:\n        query_vector_body = {\"vector\": query_vector, \"k\": search_params.get(\"k\", 2)}\n        if filter is not None and len(filter) != 0:\n            query_vector_body[\"filter\"] = filter\n        if \"linear\" == self.index_type:\n            query_vector_body[\"linear\"] = True\n        else:\n            query_vector_body[\"ef\"] = search_params.get(\"ef\", 10)\n        return {\n            \"size\": search_params.get(\"size\", 4),\n            \"query\": {\"knn\": {self.vector_query_field: query_vector_body}},\n        }\n    def _search(\n        self,\n        query: Optional[str] = None,\n        query_vector: Union[List[float], None] = None,\n        filter: Optional[dict] = None,\n        custom_query: Optional[Callable[[Dict, Union[str, None]], Dict]] = None,\n        search_params: Dict = {},\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return searched documents result from BES\n        Args:\n            query: Text to look up documents similar to.\n            query_vector: Embedding to look up documents similar to.\n            filter: Array of Baidu ElasticSearch filter clauses to apply to the query.\n            custom_query: Function to modify the query body before it is sent to BES.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/baiducloud_vector_search.html"}
{"id": "bb31951a288f-5", "text": "Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        if self.embedding and query is not None:\n            query_vector = self.embedding.embed_query(query)\n        query_body = self._query_body(\n            query_vector=query_vector, filter=filter, search_params=search_params\n        )\n        if custom_query is not None:\n            query_body = custom_query(query_body, query)\n            logger.debug(f\"Calling custom_query, Query body now: {query_body}\")\n        logger.debug(f\"Query body: {query_body}\")\n        # Perform the kNN search on the BES index and return the results.\n        response = self.client.search(index=self.index_name, body=query_body)\n        logger.debug(f\"response={response}\")\n        hits = [hit for hit in response[\"hits\"][\"hits\"]]\n        docs_and_scores = [\n            (\n                Document(\n                    page_content=hit[\"_source\"][self.query_field],\n                    metadata=hit[\"_source\"][\"metadata\"],\n                ),\n                hit[\"_score\"],\n            )\n            for hit in hits\n        ]\n        return docs_and_scores\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return documents most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Array of Elasticsearch filter clauses to apply to the query.\n        Returns:\n            List of Documents most similar to the query,\n            in descending order of similarity.\n        \"\"\"\n        results = self.similarity_search_with_score(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/baiducloud_vector_search.html"}
{"id": "bb31951a288f-6", "text": "\"\"\"\n        results = self.similarity_search_with_score(\n            query=query, k=k, filter=filter, **kwargs\n        )\n        return [doc for doc, _ in results]\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int, filter: Optional[dict] = None, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return documents most similar to query, along with scores.\n        Args:\n            query: Text to look up documents similar to.\n            size: Number of Documents to return. Defaults to 4.\n            filter: Array of Elasticsearch filter clauses to apply to the query.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        search_params = kwargs.get(\"search_params\") or {}\n        if len(search_params) == 0 or search_params.get(\"size\") is None:\n            search_params[\"size\"] = k\n        return self._search(query=query, filter=filter, **kwargs)\n[docs]    @classmethod\n    def from_documents(\n        cls,\n        documents: List[Document],\n        embedding: Optional[Embeddings] = None,\n        **kwargs: Any,\n    ) -> \"BESVectorStore\":\n        \"\"\"Construct BESVectorStore wrapper from documents.\n        Args:\n            documents: List of documents to add to the Elasticsearch index.\n            embedding: Embedding function to use to embed the texts.\n                      Do not provide if using a strategy\n                      that doesn't require inference.\n            kwargs: create index key words arguments\n        \"\"\"\n        vectorStore = BESVectorStore._bes_vector_store(embedding=embedding, **kwargs)\n        # Encode the provided texts and add them to the newly created index.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/baiducloud_vector_search.html"}
{"id": "bb31951a288f-7", "text": "# Encode the provided texts and add them to the newly created index.\n        vectorStore.add_documents(documents)\n        return vectorStore\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Optional[Embeddings] = None,\n        metadatas: Optional[List[Dict[str, Any]]] = None,\n        **kwargs: Any,\n    ) -> \"BESVectorStore\":\n        \"\"\"Construct BESVectorStore wrapper from raw documents.\n        Args:\n            texts: List of texts to add to the Elasticsearch index.\n            embedding: Embedding function to use to embed the texts.\n            metadatas: Optional list of metadatas associated with the texts.\n            index_name: Name of the Elasticsearch index to create.\n            kwargs: create index key words arguments\n        \"\"\"\n        vectorStore = BESVectorStore._bes_vector_store(embedding=embedding, **kwargs)\n        # Encode the provided texts and add them to the newly created index.\n        vectorStore.add_texts(texts, metadatas=metadatas, **kwargs)\n        return vectorStore\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[Dict[Any, Any]]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        try:\n            from elasticsearch.helpers import BulkIndexError, bulk\n        except ImportError:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/baiducloud_vector_search.html"}
{"id": "bb31951a288f-8", "text": "except ImportError:\n            raise ImportError(\n                \"Could not import elasticsearch python package. \"\n                \"Please install it with `pip install elasticsearch`.\"\n            )\n        embeddings = []\n        create_index_if_not_exists = kwargs.get(\"create_index_if_not_exists\", True)\n        ids = kwargs.get(\"ids\", [str(uuid.uuid4()) for _ in texts])\n        refresh_indices = kwargs.get(\"refresh_indices\", True)\n        requests = []\n        if self.embedding is not None:\n            embeddings = self.embedding.embed_documents(list(texts))\n            dims_length = len(embeddings[0])\n            if create_index_if_not_exists:\n                self._create_index_if_not_exists(dims_length=dims_length)\n            for i, (text, vector) in enumerate(zip(texts, embeddings)):\n                metadata = metadatas[i] if metadatas else {}\n                requests.append(\n                    {\n                        \"_op_type\": \"index\",\n                        \"_index\": self.index_name,\n                        self.query_field: text,\n                        self.vector_query_field: vector,\n                        \"metadata\": metadata,\n                        \"_id\": ids[i],\n                    }\n                )\n        else:\n            if create_index_if_not_exists:\n                self._create_index_if_not_exists()\n            for i, text in enumerate(texts):\n                metadata = metadatas[i] if metadatas else {}\n                requests.append(\n                    {\n                        \"_op_type\": \"index\",\n                        \"_index\": self.index_name,\n                        self.query_field: text,\n                        \"metadata\": metadata,\n                        \"_id\": ids[i],\n                    }\n                )\n        if len(requests) > 0:\n            try:\n                success, failed = bulk(\n                    self.client, requests, stats_only=True, refresh=refresh_indices\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/baiducloud_vector_search.html"}
{"id": "bb31951a288f-9", "text": "self.client, requests, stats_only=True, refresh=refresh_indices\n                )\n                logger.debug(\n                    f\"Added {success} and failed to add {failed} texts to index\"\n                )\n                logger.debug(f\"added texts {ids} to index\")\n                return ids\n            except BulkIndexError as e:\n                logger.error(f\"Error adding texts: {e}\")\n                firstError = e.errors[0].get(\"index\", {}).get(\"error\", {})\n                logger.error(f\"First error reason: {firstError.get('reason')}\")\n                raise e\n        else:\n            logger.debug(\"No texts to add to index\")\n            return []\n    @staticmethod\n    def _bes_vector_store(\n        embedding: Optional[Embeddings] = None, **kwargs: Any\n    ) -> \"BESVectorStore\":\n        index_name = kwargs.get(\"index_name\")\n        if index_name is None:\n            raise ValueError(\"Please provide an index_name.\")\n        bes_url = kwargs.get(\"bes_url\")\n        if bes_url is None:\n            raise ValueError(\"Please provided a valid bes connection url\")\n        return BESVectorStore(embedding=embedding, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/baiducloud_vector_search.html"}
{"id": "c53dda550dc3-0", "text": "Source code for langchain.vectorstores.clickhouse\nfrom __future__ import annotations\nimport json\nimport logging\nfrom hashlib import sha1\nfrom threading import Thread\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Union\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import BaseSettings\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nlogger = logging.getLogger()\n[docs]def has_mul_sub_str(s: str, *args: Any) -> bool:\n    \"\"\"\n    Check if a string contains multiple substrings.\n    Args:\n        s: string to check.\n        *args: substrings to check.\n    Returns:\n        True if all substrings are in the string, False otherwise.\n    \"\"\"\n    for a in args:\n        if a not in s:\n            return False\n    return True\n[docs]class ClickhouseSettings(BaseSettings):\n    \"\"\"`ClickHouse` client configuration.\n    Attribute:\n        host (str) : An URL to connect to MyScale backend.\n                             Defaults to 'localhost'.\n        port (int) : URL port to connect with HTTP. Defaults to 8443.\n        username (str) : Username to login. Defaults to None.\n        password (str) : Password to login. Defaults to None.\n        index_type (str): index type string.\n        index_param (list): index build parameter.\n        index_query_params(dict): index query parameters.\n        database (str) : Database name to find the table. Defaults to 'default'.\n        table (str) : Table name to operate on.\n                      Defaults to 'vector_table'.\n        metric (str) : Metric to compute distance,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html"}
{"id": "c53dda550dc3-1", "text": "Defaults to 'vector_table'.\n        metric (str) : Metric to compute distance,\n                       supported are ('angular', 'euclidean', 'manhattan', 'hamming',\n                       'dot'). Defaults to 'angular'.\n                       https://github.com/spotify/annoy/blob/main/src/annoymodule.cc#L149-L169\n        column_map (Dict) : Column type map to project column name onto langchain\n                            semantics. Must have keys: `text`, `id`, `vector`,\n                            must be same size to number of columns. For example:\n                            .. code-block:: python\n                                {\n                                    'id': 'text_id',\n                                    'uuid': 'global_unique_id'\n                                    'embedding': 'text_embedding',\n                                    'document': 'text_plain',\n                                    'metadata': 'metadata_dictionary_in_json',\n                                }\n                            Defaults to identity map.\n    \"\"\"\n    host: str = \"localhost\"\n    port: int = 8123\n    username: Optional[str] = None\n    password: Optional[str] = None\n    index_type: str = \"annoy\"\n    # Annoy supports L2Distance and cosineDistance.\n    index_param: Optional[Union[List, Dict]] = [\"'L2Distance'\", 100]\n    index_query_params: Dict[str, str] = {}\n    column_map: Dict[str, str] = {\n        \"id\": \"id\",\n        \"uuid\": \"uuid\",\n        \"document\": \"document\",\n        \"embedding\": \"embedding\",\n        \"metadata\": \"metadata\",\n    }\n    database: str = \"default\"\n    table: str = \"langchain\"\n    metric: str = \"angular\"\n    def __getitem__(self, item: str) -> Any:\n        return getattr(self, item)\n    class Config:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html"}
{"id": "c53dda550dc3-2", "text": "return getattr(self, item)\n    class Config:\n        env_file = \".env\"\n        env_prefix = \"clickhouse_\"\n        env_file_encoding = \"utf-8\"\n[docs]class Clickhouse(VectorStore):\n    \"\"\"`ClickHouse VectorSearch` vector store.\n    You need a `clickhouse-connect` python package, and a valid account\n    to connect to ClickHouse.\n    ClickHouse can not only search with simple vector indexes,\n    it also supports complex query with multiple conditions,\n    constraints and even sub-queries.\n    For more information, please visit\n        [ClickHouse official site](https://clickhouse.com/clickhouse)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        config: Optional[ClickhouseSettings] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"ClickHouse Wrapper to LangChain\n        embedding_function (Embeddings):\n        config (ClickHouseSettings): Configuration to ClickHouse Client\n        Other keyword arguments will pass into\n            [clickhouse-connect](https://docs.clickhouse.com/)\n        \"\"\"\n        try:\n            from clickhouse_connect import get_client\n        except ImportError:\n            raise ImportError(\n                \"Could not import clickhouse connect python package. \"\n                \"Please install it with `pip install clickhouse-connect`.\"\n            )\n        try:\n            from tqdm import tqdm\n            self.pgbar = tqdm\n        except ImportError:\n            # Just in case if tqdm is not installed\n            self.pgbar = lambda x, **kwargs: x\n        super().__init__()\n        if config is not None:\n            self.config = config\n        else:\n            self.config = ClickhouseSettings()\n        assert self.config\n        assert self.config.host and self.config.port", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html"}
{"id": "c53dda550dc3-3", "text": "assert self.config\n        assert self.config.host and self.config.port\n        assert (\n            self.config.column_map\n            and self.config.database\n            and self.config.table\n            and self.config.metric\n        )\n        for k in [\"id\", \"embedding\", \"document\", \"metadata\", \"uuid\"]:\n            assert k in self.config.column_map\n        assert self.config.metric in [\n            \"angular\",\n            \"euclidean\",\n            \"manhattan\",\n            \"hamming\",\n            \"dot\",\n        ]\n        # initialize the schema\n        dim = len(embedding.embed_query(\"test\"))\n        index_params = (\n            (\n                \",\".join([f\"'{k}={v}'\" for k, v in self.config.index_param.items()])\n                if self.config.index_param\n                else \"\"\n            )\n            if isinstance(self.config.index_param, Dict)\n            else \",\".join([str(p) for p in self.config.index_param])\n            if isinstance(self.config.index_param, List)\n            else self.config.index_param\n        )\n        self.schema = f\"\"\"\\\nCREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}(\n    {self.config.column_map['id']} Nullable(String),\n    {self.config.column_map['document']} Nullable(String),\n    {self.config.column_map['embedding']} Array(Float32),\n    {self.config.column_map['metadata']} JSON,\n    {self.config.column_map['uuid']} UUID DEFAULT generateUUIDv4(),\n    CONSTRAINT cons_vec_len CHECK length({self.config.column_map['embedding']}) = {dim},\n    INDEX vec_idx {self.config.column_map['embedding']} TYPE \\\n{self.config.index_type}({index_params}) GRANULARITY 1000\n) ENGINE = MergeTree ORDER BY uuid SETTINGS index_granularity = 8192\\\n\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html"}
{"id": "c53dda550dc3-4", "text": "\"\"\"\n        self.dim = dim\n        self.BS = \"\\\\\"\n        self.must_escape = (\"\\\\\", \"'\")\n        self.embedding_function = embedding\n        self.dist_order = \"ASC\"  # Only support ConsingDistance and L2Distance\n        # Create a connection to clickhouse\n        self.client = get_client(\n            host=self.config.host,\n            port=self.config.port,\n            username=self.config.username,\n            password=self.config.password,\n            **kwargs,\n        )\n        # Enable JSON type\n        self.client.command(\"SET allow_experimental_object_type=1\")\n        # Enable Annoy index\n        self.client.command(\"SET allow_experimental_annoy_index=1\")\n        self.client.command(self.schema)\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding_function\n[docs]    def escape_str(self, value: str) -> str:\n        return \"\".join(f\"{self.BS}{c}\" if c in self.must_escape else c for c in value)\n    def _build_insert_sql(self, transac: Iterable, column_names: Iterable[str]) -> str:\n        ks = \",\".join(column_names)\n        _data = []\n        for n in transac:\n            n = \",\".join([f\"'{self.escape_str(str(_n))}'\" for _n in n])\n            _data.append(f\"({n})\")\n        i_str = f\"\"\"\n                INSERT INTO TABLE \n                    {self.config.database}.{self.config.table}({ks})\n                VALUES\n                {','.join(_data)}\n                \"\"\"\n        return i_str\n    def _insert(self, transac: Iterable, column_names: Iterable[str]) -> None:\n        _insert_query = self._build_insert_sql(transac, column_names)\n        self.client.command(_insert_query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html"}
{"id": "c53dda550dc3-5", "text": "self.client.command(_insert_query)\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        batch_size: int = 32,\n        ids: Optional[Iterable[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Insert more texts through the embeddings and add to the VectorStore.\n        Args:\n            texts: Iterable of strings to add to the VectorStore.\n            ids: Optional list of ids to associate with the texts.\n            batch_size: Batch size of insertion\n            metadata: Optional column data to be inserted\n        Returns:\n            List of ids from adding the texts into the VectorStore.\n        \"\"\"\n        # Embed and create the documents\n        ids = ids or [sha1(t.encode(\"utf-8\")).hexdigest() for t in texts]\n        colmap_ = self.config.column_map\n        transac = []\n        column_names = {\n            colmap_[\"id\"]: ids,\n            colmap_[\"document\"]: texts,\n            colmap_[\"embedding\"]: self.embedding_function.embed_documents(list(texts)),\n        }\n        metadatas = metadatas or [{} for _ in texts]\n        column_names[colmap_[\"metadata\"]] = map(json.dumps, metadatas)\n        assert len(set(colmap_) - set(column_names)) >= 0\n        keys, values = zip(*column_names.items())\n        try:\n            t = None\n            for v in self.pgbar(\n                zip(*values), desc=\"Inserting data...\", total=len(metadatas)\n            ):\n                assert (\n                    len(v[keys.index(self.config.column_map[\"embedding\"])]) == self.dim\n                )\n                transac.append(v)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html"}
{"id": "c53dda550dc3-6", "text": ")\n                transac.append(v)\n                if len(transac) == batch_size:\n                    if t:\n                        t.join()\n                    t = Thread(target=self._insert, args=[transac, keys])\n                    t.start()\n                    transac = []\n            if len(transac) > 0:\n                if t:\n                    t.join()\n                self._insert(transac, keys)\n            return [i for i in ids]\n        except Exception as e:\n            logger.error(f\"\\033[91m\\033[1m{type(e)}\\033[0m \\033[95m{str(e)}\\033[0m\")\n            return []\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[Dict[Any, Any]]] = None,\n        config: Optional[ClickhouseSettings] = None,\n        text_ids: Optional[Iterable[str]] = None,\n        batch_size: int = 32,\n        **kwargs: Any,\n    ) -> Clickhouse:\n        \"\"\"Create ClickHouse wrapper with existing texts\n        Args:\n            embedding_function (Embeddings): Function to extract text embedding\n            texts (Iterable[str]): List or tuple of strings to be added\n            config (ClickHouseSettings, Optional): ClickHouse configuration\n            text_ids (Optional[Iterable], optional): IDs for the texts.\n                                                     Defaults to None.\n            batch_size (int, optional): Batchsize when transmitting data to ClickHouse.\n                                        Defaults to 32.\n            metadata (List[dict], optional): metadata to texts. Defaults to None.\n            Other keyword arguments will pass into", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html"}
{"id": "c53dda550dc3-7", "text": "Other keyword arguments will pass into\n                [clickhouse-connect](https://clickhouse.com/docs/en/integrations/python#clickhouse-connect-driver-api)\n        Returns:\n            ClickHouse Index\n        \"\"\"\n        ctx = cls(embedding, config, **kwargs)\n        ctx.add_texts(texts, ids=text_ids, batch_size=batch_size, metadatas=metadatas)\n        return ctx\n    def __repr__(self) -> str:\n        \"\"\"Text representation for ClickHouse Vector Store, prints backends, username\n            and schemas. Easy to use with `str(ClickHouse())`\n        Returns:\n            repr: string to show connection info and data schema\n        \"\"\"\n        _repr = f\"\\033[92m\\033[1m{self.config.database}.{self.config.table} @ \"\n        _repr += f\"{self.config.host}:{self.config.port}\\033[0m\\n\\n\"\n        _repr += f\"\\033[1musername: {self.config.username}\\033[0m\\n\\nTable Schema:\\n\"\n        _repr += \"-\" * 51 + \"\\n\"\n        for r in self.client.query(\n            f\"DESC {self.config.database}.{self.config.table}\"\n        ).named_results():\n            _repr += (\n                f\"|\\033[94m{r['name']:24s}\\033[0m|\\033[96m{r['type']:24s}\\033[0m|\\n\"\n            )\n        _repr += \"-\" * 51 + \"\\n\"\n        return _repr\n    def _build_query_sql(\n        self, q_emb: List[float], topk: int, where_str: Optional[str] = None\n    ) -> str:\n        q_emb_str = \",\".join(map(str, q_emb))\n        if where_str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html"}
{"id": "c53dda550dc3-8", "text": "if where_str:\n            where_str = f\"PREWHERE {where_str}\"\n        else:\n            where_str = \"\"\n        settings_strs = []\n        if self.config.index_query_params:\n            for k in self.config.index_query_params:\n                settings_strs.append(f\"SETTING {k}={self.config.index_query_params[k]}\")\n        q_str = f\"\"\"\n            SELECT {self.config.column_map['document']}, \n                {self.config.column_map['metadata']}, dist\n            FROM {self.config.database}.{self.config.table}\n            {where_str}\n            ORDER BY L2Distance({self.config.column_map['embedding']}, [{q_emb_str}]) \n                AS dist {self.dist_order}\n            LIMIT {topk} {' '.join(settings_strs)}\n            \"\"\"\n        return q_str\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Perform a similarity search with ClickHouse\n        Args:\n            query (str): query string\n            k (int, optional): Top K neighbors to retrieve. Defaults to 4.\n            where_str (Optional[str], optional): where condition string.\n                                                 Defaults to None.\n            NOTE: Please do not let end-user to fill this and always be aware\n                  of SQL injection. When dealing with metadatas, remember to\n                  use `{self.metadata_column}.attribute` instead of `attribute`\n                  alone. The default name for it is `metadata`.\n        Returns:\n            List[Document]: List of Documents\n        \"\"\"\n        return self.similarity_search_by_vector(\n            self.embedding_function.embed_query(query), k, where_str, **kwargs\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html"}
{"id": "c53dda550dc3-9", "text": "self.embedding_function.embed_query(query), k, where_str, **kwargs\n        )\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        where_str: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform a similarity search with ClickHouse by vectors\n        Args:\n            query (str): query string\n            k (int, optional): Top K neighbors to retrieve. Defaults to 4.\n            where_str (Optional[str], optional): where condition string.\n                                                 Defaults to None.\n            NOTE: Please do not let end-user to fill this and always be aware\n                  of SQL injection. When dealing with metadatas, remember to\n                  use `{self.metadata_column}.attribute` instead of `attribute`\n                  alone. The default name for it is `metadata`.\n        Returns:\n            List[Document]: List of documents\n        \"\"\"\n        q_str = self._build_query_sql(embedding, k, where_str)\n        try:\n            return [\n                Document(\n                    page_content=r[self.config.column_map[\"document\"]],\n                    metadata=r[self.config.column_map[\"metadata\"]],\n                )\n                for r in self.client.query(q_str).named_results()\n            ]\n        except Exception as e:\n            logger.error(f\"\\033[91m\\033[1m{type(e)}\\033[0m \\033[95m{str(e)}\\033[0m\")\n            return []\n[docs]    def similarity_search_with_relevance_scores(\n        self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html"}
{"id": "c53dda550dc3-10", "text": ") -> List[Tuple[Document, float]]:\n        \"\"\"Perform a similarity search with ClickHouse\n        Args:\n            query (str): query string\n            k (int, optional): Top K neighbors to retrieve. Defaults to 4.\n            where_str (Optional[str], optional): where condition string.\n                                                 Defaults to None.\n            NOTE: Please do not let end-user to fill this and always be aware\n                  of SQL injection. When dealing with metadatas, remember to\n                  use `{self.metadata_column}.attribute` instead of `attribute`\n                  alone. The default name for it is `metadata`.\n        Returns:\n            List[Document]: List of (Document, similarity)\n        \"\"\"\n        q_str = self._build_query_sql(\n            self.embedding_function.embed_query(query), k, where_str\n        )\n        try:\n            return [\n                (\n                    Document(\n                        page_content=r[self.config.column_map[\"document\"]],\n                        metadata=r[self.config.column_map[\"metadata\"]],\n                    ),\n                    r[\"dist\"],\n                )\n                for r in self.client.query(q_str).named_results()\n            ]\n        except Exception as e:\n            logger.error(f\"\\033[91m\\033[1m{type(e)}\\033[0m \\033[95m{str(e)}\\033[0m\")\n            return []\n[docs]    def drop(self) -> None:\n        \"\"\"\n        Helper function: Drop data\n        \"\"\"\n        self.client.command(\n            f\"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}\"\n        )\n    @property\n    def metadata_column(self) -> str:\n        return self.config.column_map[\"metadata\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html"}
{"id": "30088a248d2c-0", "text": "Source code for langchain.vectorstores.zep\nfrom __future__ import annotations\nimport logging\nimport warnings\nfrom dataclasses import asdict, dataclass\nfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nif TYPE_CHECKING:\n    from zep_python.document import Document as ZepDocument\n    from zep_python.document import DocumentCollection\nlogger = logging.getLogger()\n[docs]@dataclass\nclass CollectionConfig:\n    \"\"\"Configuration for a `Zep Collection`.\n    If the collection does not exist, it will be created.\n    Attributes:\n        name (str): The name of the collection.\n        description (Optional[str]): An optional description of the collection.\n        metadata (Optional[Dict[str, Any]]): Optional metadata for the collection.\n        embedding_dimensions (int): The number of dimensions for the embeddings in\n            the collection. This should match the Zep server configuration\n            if auto-embed is true.\n        is_auto_embedded (bool): A flag indicating whether the collection is\n            automatically embedded by Zep.\n    \"\"\"\n    name: str\n    description: Optional[str]\n    metadata: Optional[Dict[str, Any]]\n    embedding_dimensions: int\n    is_auto_embedded: bool\n[docs]class ZepVectorStore(VectorStore):\n    \"\"\"`Zep` vector store.\n    It provides methods for adding texts or documents to the store,\n    searching for similar documents, and deleting documents.\n    Search scores are calculated using cosine similarity normalized to [0, 1].\n    Args:\n        api_url (str): The URL of the Zep API.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "30088a248d2c-1", "text": "Args:\n        api_url (str): The URL of the Zep API.\n        collection_name (str): The name of the collection in the Zep store.\n        api_key (Optional[str]): The API key for the Zep API.\n        config (Optional[CollectionConfig]): The configuration for the collection.\n            Required if the collection does not already exist.\n        embedding (Optional[Embeddings]): Optional embedding function to use to\n            embed the texts. Required if the collection is not auto-embedded.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        collection_name: str,\n        api_url: str,\n        *,\n        api_key: Optional[str] = None,\n        config: Optional[CollectionConfig] = None,\n        embedding: Optional[Embeddings] = None,\n    ) -> None:\n        super().__init__()\n        if not collection_name:\n            raise ValueError(\n                \"collection_name must be specified when using ZepVectorStore.\"\n            )\n        try:\n            from zep_python import ZepClient\n        except ImportError:\n            raise ImportError(\n                \"Could not import zep-python python package. \"\n                \"Please install it with `pip install zep-python`.\"\n            )\n        self._client = ZepClient(api_url, api_key=api_key)\n        self.collection_name = collection_name\n        # If for some reason the collection name is not the same as the one in the\n        # config, update it.\n        if config and config.name != self.collection_name:\n            config.name = self.collection_name\n        self._collection_config = config\n        self._collection = self._load_collection()\n        self._embedding = embedding\n        # self.add_texts(texts, metadatas=metadatas, **kwargs)\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "30088a248d2c-2", "text": "@property\n    def embeddings(self) -> Optional[Embeddings]:\n        \"\"\"Access the query embedding object if available.\"\"\"\n        return self._embedding\n    def _load_collection(self) -> DocumentCollection:\n        \"\"\"\n        Load the collection from the Zep backend.\n        \"\"\"\n        from zep_python import NotFoundError\n        try:\n            collection = self._client.document.get_collection(self.collection_name)\n        except NotFoundError:\n            logger.info(\n                f\"Collection {self.collection_name} not found. Creating new collection.\"\n            )\n            collection = self._create_collection()\n        return collection\n    def _create_collection(self) -> DocumentCollection:\n        \"\"\"\n        Create a new collection in the Zep backend.\n        \"\"\"\n        if not self._collection_config:\n            raise ValueError(\n                \"Collection config must be specified when creating a new collection.\"\n            )\n        collection = self._client.document.add_collection(\n            **asdict(self._collection_config)\n        )\n        return collection\n    def _generate_documents_to_add(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[Dict[Any, Any]]] = None,\n        document_ids: Optional[List[str]] = None,\n    ) -> List[ZepDocument]:\n        from zep_python.document import Document as ZepDocument\n        embeddings = None\n        if self._collection and self._collection.is_auto_embedded:\n            if self._embedding is not None:\n                warnings.warn(\n                    \"\"\"The collection is set to auto-embed and an embedding \n                function is present. Ignoring the embedding function.\"\"\",\n                    stacklevel=2,\n                )\n        elif self._embedding is not None:\n            embeddings = self._embedding.embed_documents(list(texts))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "30088a248d2c-3", "text": "embeddings = self._embedding.embed_documents(list(texts))\n            if self._collection and self._collection.embedding_dimensions != len(\n                embeddings[0]\n            ):\n                raise ValueError(\n                    \"The embedding dimensions of the collection and the embedding\"\n                    \" function do not match. Collection dimensions:\"\n                    f\" {self._collection.embedding_dimensions}, Embedding dimensions:\"\n                    f\" {len(embeddings[0])}\"\n                )\n        else:\n            pass\n        documents: List[ZepDocument] = []\n        for i, d in enumerate(texts):\n            documents.append(\n                ZepDocument(\n                    content=d,\n                    metadata=metadatas[i] if metadatas else None,\n                    document_id=document_ids[i] if document_ids else None,\n                    embedding=embeddings[i] if embeddings else None,\n                )\n            )\n        return documents\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[Dict[str, Any]]] = None,\n        document_ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            document_ids: Optional list of document ids associated with the texts.\n            kwargs: vectorstore specific parameters\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        if not self._collection:\n            raise ValueError(\n                \"collection should be an instance of a Zep DocumentCollection\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "30088a248d2c-4", "text": "\"collection should be an instance of a Zep DocumentCollection\"\n            )\n        documents = self._generate_documents_to_add(texts, metadatas, document_ids)\n        uuids = self._collection.add_documents(documents)\n        return uuids\n[docs]    async def aadd_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[Dict[str, Any]]] = None,\n        document_ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\"\"\"\n        if not self._collection:\n            raise ValueError(\n                \"collection should be an instance of a Zep DocumentCollection\"\n            )\n        documents = self._generate_documents_to_add(texts, metadatas, document_ids)\n        uuids = await self._collection.aadd_documents(documents)\n        return uuids\n[docs]    def search(\n        self,\n        query: str,\n        search_type: str,\n        metadata: Optional[Dict[str, Any]] = None,\n        k: int = 3,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query using specified search type.\"\"\"\n        if search_type == \"similarity\":\n            return self.similarity_search(query, k=k, metadata=metadata, **kwargs)\n        elif search_type == \"mmr\":\n            return self.max_marginal_relevance_search(\n                query, k=k, metadata=metadata, **kwargs\n            )\n        else:\n            raise ValueError(\n                f\"search_type of {search_type} not allowed. Expected \"\n                \"search_type to be 'similarity' or 'mmr'.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "30088a248d2c-5", "text": "\"search_type to be 'similarity' or 'mmr'.\"\n            )\n[docs]    async def asearch(\n        self,\n        query: str,\n        search_type: str,\n        metadata: Optional[Dict[str, Any]] = None,\n        k: int = 3,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query using specified search type.\"\"\"\n        if search_type == \"similarity\":\n            return await self.asimilarity_search(\n                query, k=k, metadata=metadata, **kwargs\n            )\n        elif search_type == \"mmr\":\n            return await self.amax_marginal_relevance_search(\n                query, k=k, metadata=metadata, **kwargs\n            )\n        else:\n            raise ValueError(\n                f\"search_type of {search_type} not allowed. Expected \"\n                \"search_type to be 'similarity' or 'mmr'.\"\n            )\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\"\"\"\n        results = self._similarity_search_with_relevance_scores(\n            query, k=k, metadata=metadata, **kwargs\n        )\n        return [doc for doc, _ in results]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "30088a248d2c-6", "text": "**kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Run similarity search with distance.\"\"\"\n        return self._similarity_search_with_relevance_scores(\n            query, k=k, metadata=metadata, **kwargs\n        )\n    def _similarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Default similarity search with relevance scores. Modify if necessary\n        in subclass.\n        Return docs and relevance scores in the range [0, 1].\n        0 is dissimilar, 1 is most similar.\n        Args:\n            query: input text\n            k: Number of Documents to return. Defaults to 4.\n            metadata: Optional, metadata filter\n            **kwargs: kwargs to be passed to similarity search. Should include:\n                score_threshold: Optional, a floating point value between 0 to 1 and\n                    filter the resulting set of retrieved docs\n        Returns:\n            List of Tuples of (doc, similarity_score)\n        \"\"\"\n        if not self._collection:\n            raise ValueError(\n                \"collection should be an instance of a Zep DocumentCollection\"\n            )\n        if not self._collection.is_auto_embedded and self._embedding:\n            query_vector = self._embedding.embed_query(query)\n            results = self._collection.search(\n                embedding=query_vector, limit=k, metadata=metadata, **kwargs\n            )\n        else:\n            results = self._collection.search(\n                query, limit=k, metadata=metadata, **kwargs\n            )\n        return [\n            (\n                Document(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "30088a248d2c-7", "text": ")\n        return [\n            (\n                Document(\n                    page_content=doc.content,\n                    metadata=doc.metadata,\n                ),\n                doc.score or 0.0,\n            )\n            for doc in results\n        ]\n[docs]    async def asimilarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\"\"\"\n        if not self._collection:\n            raise ValueError(\n                \"collection should be an instance of a Zep DocumentCollection\"\n            )\n        if not self._collection.is_auto_embedded and self._embedding:\n            query_vector = self._embedding.embed_query(query)\n            results = await self._collection.asearch(\n                embedding=query_vector, limit=k, metadata=metadata, **kwargs\n            )\n        else:\n            results = await self._collection.asearch(\n                query, limit=k, metadata=metadata, **kwargs\n            )\n        return [\n            (\n                Document(\n                    page_content=doc.content,\n                    metadata=doc.metadata,\n                ),\n                doc.score or 0.0,\n            )\n            for doc in results\n        ]\n[docs]    async def asimilarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\"\"\"\n        results = await self.asimilarity_search_with_relevance_scores(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "30088a248d2c-8", "text": "results = await self.asimilarity_search_with_relevance_scores(\n            query, k, metadata=metadata, **kwargs\n        )\n        return [doc for doc, _ in results]\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            metadata: Optional, metadata filter\n        Returns:\n            List of Documents most similar to the query vector.\n        \"\"\"\n        if not self._collection:\n            raise ValueError(\n                \"collection should be an instance of a Zep DocumentCollection\"\n            )\n        results = self._collection.search(\n            embedding=embedding, limit=k, metadata=metadata, **kwargs\n        )\n        return [\n            Document(\n                page_content=doc.content,\n                metadata=doc.metadata,\n            )\n            for doc in results\n        ]\n[docs]    async def asimilarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\"\"\"\n        if not self._collection:\n            raise ValueError(\n                \"collection should be an instance of a Zep DocumentCollection\"\n            )\n        results = self._collection.search(\n            embedding=embedding, limit=k, metadata=metadata, **kwargs\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "30088a248d2c-9", "text": "embedding=embedding, limit=k, metadata=metadata, **kwargs\n        )\n        return [\n            Document(\n                page_content=doc.content,\n                metadata=doc.metadata,\n            )\n            for doc in results\n        ]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n                     Zep determines this automatically and this parameter is\n                        ignored.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            metadata: Optional, metadata to filter the resulting set of retrieved docs\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        if not self._collection:\n            raise ValueError(\n                \"collection should be an instance of a Zep DocumentCollection\"\n            )\n        if not self._collection.is_auto_embedded and self._embedding:\n            query_vector = self._embedding.embed_query(query)\n            results = self._collection.search(\n                embedding=query_vector,\n                limit=k,\n                metadata=metadata,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "30088a248d2c-10", "text": "embedding=query_vector,\n                limit=k,\n                metadata=metadata,\n                search_type=\"mmr\",\n                mmr_lambda=lambda_mult,\n                **kwargs,\n            )\n        else:\n            results, query_vector = self._collection.search_return_query_vector(\n                query,\n                limit=k,\n                metadata=metadata,\n                search_type=\"mmr\",\n                mmr_lambda=lambda_mult,\n                **kwargs,\n            )\n        return [Document(page_content=d.content, metadata=d.metadata) for d in results]\n[docs]    async def amax_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\"\"\"\n        if not self._collection:\n            raise ValueError(\n                \"collection should be an instance of a Zep DocumentCollection\"\n            )\n        if not self._collection.is_auto_embedded and self._embedding:\n            query_vector = self._embedding.embed_query(query)\n            results = await self._collection.asearch(\n                embedding=query_vector,\n                limit=k,\n                metadata=metadata,\n                search_type=\"mmr\",\n                mmr_lambda=lambda_mult,\n                **kwargs,\n            )\n        else:\n            results, query_vector = await self._collection.asearch_return_query_vector(\n                query,\n                limit=k,\n                metadata=metadata,\n                search_type=\"mmr\",\n                mmr_lambda=lambda_mult,\n                **kwargs,\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "30088a248d2c-11", "text": "mmr_lambda=lambda_mult,\n                **kwargs,\n            )\n        return [Document(page_content=d.content, metadata=d.metadata) for d in results]\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n                     Zep determines this automatically and this parameter is\n                        ignored.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            metadata: Optional, metadata to filter the resulting set of retrieved docs\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        if not self._collection:\n            raise ValueError(\n                \"collection should be an instance of a Zep DocumentCollection\"\n            )\n        results = self._collection.search(\n            embedding=embedding,\n            limit=k,\n            metadata=metadata,\n            search_type=\"mmr\",\n            mmr_lambda=lambda_mult,\n            **kwargs,\n        )\n        return [Document(page_content=d.content, metadata=d.metadata) for d in results]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "30088a248d2c-12", "text": "return [Document(page_content=d.content, metadata=d.metadata) for d in results]\n[docs]    async def amax_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\"\"\"\n        if not self._collection:\n            raise ValueError(\n                \"collection should be an instance of a Zep DocumentCollection\"\n            )\n        results = await self._collection.asearch(\n            embedding=embedding,\n            limit=k,\n            metadata=metadata,\n            search_type=\"mmr\",\n            mmr_lambda=lambda_mult,\n            **kwargs,\n        )\n        return [Document(page_content=d.content, metadata=d.metadata) for d in results]\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Optional[Embeddings] = None,\n        metadatas: Optional[List[dict]] = None,\n        collection_name: str = \"\",\n        api_url: str = \"\",\n        api_key: Optional[str] = None,\n        config: Optional[CollectionConfig] = None,\n        **kwargs: Any,\n    ) -> ZepVectorStore:\n        \"\"\"\n        Class method that returns a ZepVectorStore instance initialized from texts.\n        If the collection does not exist, it will be created.\n        Args:\n            texts (List[str]): The list of texts to add to the vectorstore.\n            embedding (Optional[Embeddings]): Optional embedding function to use to", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "30088a248d2c-13", "text": "embedding (Optional[Embeddings]): Optional embedding function to use to\n               embed the texts.\n            metadatas (Optional[List[Dict[str, Any]]]): Optional list of metadata\n               associated with the texts.\n            collection_name (str): The name of the collection in the Zep store.\n            api_url (str): The URL of the Zep API.\n            api_key (Optional[str]): The API key for the Zep API.\n            config (Optional[CollectionConfig]): The configuration for the collection.\n            **kwargs: Additional parameters specific to the vectorstore.\n        Returns:\n            ZepVectorStore: An instance of ZepVectorStore.\n        \"\"\"\n        vecstore = cls(\n            collection_name,\n            api_url,\n            api_key=api_key,\n            config=config,\n            embedding=embedding,\n        )\n        vecstore.add_texts(texts, metadatas)\n        return vecstore\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None:\n        \"\"\"Delete by Zep vector UUIDs.\n        Parameters\n        ----------\n        ids : Optional[List[str]]\n            The UUIDs of the vectors to delete.\n        Raises\n        ------\n        ValueError\n            If no UUIDs are provided.\n        \"\"\"\n        if ids is None or len(ids) == 0:\n            raise ValueError(\"No uuids provided to delete.\")\n        if self._collection is None:\n            raise ValueError(\"No collection name provided.\")\n        for u in ids:\n            self._collection.delete_document(u)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zep.html"}
{"id": "4bae1c8108af-0", "text": "Source code for langchain.vectorstores.vespa\nfrom __future__ import annotations\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Type, Union\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.vectorstores.base import VectorStore, VectorStoreRetriever\n[docs]class VespaStore(VectorStore):\n    \"\"\"\n    `Vespa` vector store.\n    To use, you should have the python client library ``pyvespa`` installed.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import VespaStore\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            from vespa.application import Vespa\n            # Create a vespa client dependent upon your application,\n            # e.g. either connecting to Vespa Cloud or a local deployment\n            # such as Docker. Please refer to the PyVespa documentation on\n            # how to initialize the client.\n            vespa_app = Vespa(url=\"...\", port=..., application_package=...)\n            # You need to instruct LangChain on which fields to use for embeddings\n            vespa_config = dict(\n                page_content_field=\"text\",\n                embedding_field=\"embedding\",\n                input_field=\"query_embedding\",\n                metadata_fields=[\"date\", \"rating\", \"author\"]\n            )\n            embedding_function = OpenAIEmbeddings()\n            vectorstore = VespaStore(vespa_app, embedding_function, **vespa_config)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        app: Any,\n        embedding_function: Optional[Embeddings] = None,\n        page_content_field: Optional[str] = None,\n        embedding_field: Optional[str] = None,\n        input_field: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vespa.html"}
{"id": "4bae1c8108af-1", "text": "input_field: Optional[str] = None,\n        metadata_fields: Optional[List[str]] = None,\n    ) -> None:\n        \"\"\"\n        Initialize with a PyVespa client.\n        \"\"\"\n        try:\n            from vespa.application import Vespa\n        except ImportError:\n            raise ImportError(\n                \"Could not import Vespa python package. \"\n                \"Please install it with `pip install pyvespa`.\"\n            )\n        if not isinstance(app, Vespa):\n            raise ValueError(\n                f\"app should be an instance of vespa.application.Vespa, got {type(app)}\"\n            )\n        self._vespa_app = app\n        self._embedding_function = embedding_function\n        self._page_content_field = page_content_field\n        self._embedding_field = embedding_field\n        self._input_field = input_field\n        self._metadata_fields = metadata_fields\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"\n        Add texts to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of ids associated with the texts.\n            kwargs: vectorstore specific parameters\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        embeddings = None\n        if self._embedding_function is not None:\n            embeddings = self._embedding_function.embed_documents(list(texts))\n        if ids is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vespa.html"}
{"id": "4bae1c8108af-2", "text": "if ids is None:\n            ids = [str(f\"{i+1}\") for i, _ in enumerate(texts)]\n        batch = []\n        for i, text in enumerate(texts):\n            fields: Dict[str, Union[str, List[float]]] = {}\n            if self._page_content_field is not None:\n                fields[self._page_content_field] = text\n            if self._embedding_field is not None and embeddings is not None:\n                fields[self._embedding_field] = embeddings[i]\n            if metadatas is not None and self._metadata_fields is not None:\n                for metadata_field in self._metadata_fields:\n                    if metadata_field in metadatas[i]:\n                        fields[metadata_field] = metadatas[i][metadata_field]\n            batch.append({\"id\": ids[i], \"fields\": fields})\n        results = self._vespa_app.feed_batch(batch)\n        for result in results:\n            if not (str(result.status_code).startswith(\"2\")):\n                raise RuntimeError(\n                    f\"Could not add document to Vespa. \"\n                    f\"Error code: {result.status_code}. \"\n                    f\"Message: {result.json['message']}\"\n                )\n        return ids\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:\n        if ids is None:\n            return False\n        batch = [{\"id\": id} for id in ids]\n        result = self._vespa_app.delete_batch(batch)\n        return sum([0 if r.status_code == 200 else 1 for r in result]) == 0\n    def _create_query(\n        self, query_embedding: List[float], k: int = 4, **kwargs: Any\n    ) -> Dict:\n        hits = k", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vespa.html"}
{"id": "4bae1c8108af-3", "text": ") -> Dict:\n        hits = k\n        doc_embedding_field = self._embedding_field\n        input_embedding_field = self._input_field\n        ranking_function = kwargs[\"ranking\"] if \"ranking\" in kwargs else \"default\"\n        filter = kwargs[\"filter\"] if \"filter\" in kwargs else None\n        approximate = kwargs[\"approximate\"] if \"approximate\" in kwargs else False\n        approximate = \"true\" if approximate else \"false\"\n        yql = \"select * from sources * where \"\n        yql += f\"{{targetHits: {hits}, approximate: {approximate}}}\"\n        yql += f\"nearestNeighbor({doc_embedding_field}, {input_embedding_field})\"\n        if filter is not None:\n            yql += f\" and {filter}\"\n        query = {\n            \"yql\": yql,\n            f\"input.query({input_embedding_field})\": query_embedding,\n            \"ranking\": ranking_function,\n            \"hits\": hits,\n        }\n        return query\n[docs]    def similarity_search_by_vector_with_score(\n        self, query_embedding: List[float], k: int = 4, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Performs similarity search from a embeddings vector.\n        Args:\n            query_embedding: Embeddings vector to search for.\n            k: Number of results to return.\n            custom_query: Use this custom query instead default query (kwargs)\n            kwargs: other vector store specific parameters\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        if \"custom_query\" in kwargs:\n            query = kwargs[\"custom_query\"]\n        else:\n            query = self._create_query(query_embedding, k, **kwargs)\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vespa.html"}
{"id": "4bae1c8108af-4", "text": "query = self._create_query(query_embedding, k, **kwargs)\n        try:\n            response = self._vespa_app.query(body=query)\n        except Exception as e:\n            raise RuntimeError(\n                f\"Could not retrieve data from Vespa: \"\n                f\"{e.args[0][0]['summary']}. \"\n                f\"Error: {e.args[0][0]['message']}\"\n            )\n        if not str(response.status_code).startswith(\"2\"):\n            raise RuntimeError(\n                f\"Could not retrieve data from Vespa. \"\n                f\"Error code: {response.status_code}. \"\n                f\"Message: {response.json['message']}\"\n            )\n        root = response.json[\"root\"]\n        if \"errors\" in root:\n            import json\n            raise RuntimeError(json.dumps(root[\"errors\"]))\n        if response is None or response.hits is None:\n            return []\n        docs = []\n        for child in response.hits:\n            page_content = child[\"fields\"][self._page_content_field]\n            score = child[\"relevance\"]\n            metadata = {\"id\": child[\"id\"]}\n            if self._metadata_fields is not None:\n                for field in self._metadata_fields:\n                    metadata[field] = child[\"fields\"].get(field)\n            doc = Document(page_content=page_content, metadata=metadata)\n            docs.append((doc, score))\n        return docs\n[docs]    def similarity_search_by_vector(\n        self, embedding: List[float], k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        results = self.similarity_search_by_vector_with_score(embedding, k, **kwargs)\n        return [r[0] for r in results]\n[docs]    def similarity_search_with_score(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vespa.html"}
{"id": "4bae1c8108af-5", "text": "[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        query_emb = []\n        if self._embedding_function is not None:\n            query_emb = self._embedding_function.embed_query(query)\n        return self.similarity_search_by_vector_with_score(query_emb, k, **kwargs)\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        results = self.similarity_search_with_score(query, k, **kwargs)\n        return [r[0] for r in results]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        raise NotImplementedError(\"MMR search not implemented\")\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        raise NotImplementedError(\"MMR search by vector not implemented\")\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[VespaStore],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vespa.html"}
{"id": "4bae1c8108af-6", "text": "ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> VespaStore:\n        vespa = cls(embedding_function=embedding, **kwargs)\n        vespa.add_texts(texts=texts, metadatas=metadatas, ids=ids)\n        return vespa\n[docs]    def as_retriever(self, **kwargs: Any) -> VectorStoreRetriever:\n        return super().as_retriever(**kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vespa.html"}
{"id": "005c33cdfcc1-0", "text": "Source code for langchain.vectorstores.semadb\nfrom typing import Any, Iterable, List, Optional, Tuple\nfrom uuid import uuid4\nimport numpy as np\nimport requests\nfrom langchain.schema.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_env\nfrom langchain.vectorstores.utils import DistanceStrategy\n[docs]class SemaDB(VectorStore):\n    \"\"\"`SemaDB` vector store.\n    This vector store is a wrapper around the SemaDB database.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import SemaDB\n            db = SemaDB('mycollection', 768, embeddings, DistanceStrategy.COSINE)\n    \"\"\"\n    HOST = \"semadb.p.rapidapi.com\"\n    BASE_URL = \"https://\" + HOST\n[docs]    def __init__(\n        self,\n        collection_name: str,\n        vector_size: int,\n        embedding: Embeddings,\n        distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE,\n        api_key: str = \"\",\n    ):\n        \"\"\"Initialise the SemaDB vector store.\"\"\"\n        self.collection_name = collection_name\n        self.vector_size = vector_size\n        self.api_key = api_key or get_from_env(\"api_key\", \"SEMADB_API_KEY\")\n        self._embedding = embedding\n        self.distance_strategy = distance_strategy\n    @property\n    def headers(self) -> dict:\n        \"\"\"Return the common headers.\"\"\"\n        return {\n            \"content-type\": \"application/json\",\n            \"X-RapidAPI-Key\": self.api_key,\n            \"X-RapidAPI-Host\": SemaDB.HOST,\n        }\n    def _get_internal_distance_strategy(self) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/semadb.html"}
{"id": "005c33cdfcc1-1", "text": "}\n    def _get_internal_distance_strategy(self) -> str:\n        \"\"\"Return the internal distance strategy.\"\"\"\n        if self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE:\n            return \"euclidean\"\n        elif self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:\n            raise ValueError(\"Max inner product is not supported by SemaDB\")\n        elif self.distance_strategy == DistanceStrategy.DOT_PRODUCT:\n            return \"dot\"\n        elif self.distance_strategy == DistanceStrategy.JACCARD:\n            raise ValueError(\"Max inner product is not supported by SemaDB\")\n        elif self.distance_strategy == DistanceStrategy.COSINE:\n            return \"cosine\"\n        else:\n            raise ValueError(f\"Unknown distance strategy {self.distance_strategy}\")\n[docs]    def create_collection(self) -> bool:\n        \"\"\"Creates the corresponding collection in SemaDB.\"\"\"\n        payload = {\n            \"id\": self.collection_name,\n            \"vectorSize\": self.vector_size,\n            \"distanceMetric\": self._get_internal_distance_strategy(),\n        }\n        response = requests.post(\n            SemaDB.BASE_URL + \"/collections\",\n            json=payload,\n            headers=self.headers,\n        )\n        return response.status_code == 200\n[docs]    def delete_collection(self) -> bool:\n        \"\"\"Deletes the corresponding collection in SemaDB.\"\"\"\n        response = requests.delete(\n            SemaDB.BASE_URL + f\"/collections/{self.collection_name}\",\n            headers=self.headers,\n        )\n        return response.status_code == 200\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        batch_size: int = 1000,\n        **kwargs: Any,\n    ) -> List[str]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/semadb.html"}
{"id": "005c33cdfcc1-2", "text": "**kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add texts to the vector store.\"\"\"\n        if not isinstance(texts, list):\n            texts = list(texts)\n        embeddings = self._embedding.embed_documents(texts)\n        # Check dimensions\n        if len(embeddings[0]) != self.vector_size:\n            raise ValueError(\n                f\"Embedding size mismatch {len(embeddings[0])} != {self.vector_size}\"\n            )\n        # Normalise if needed\n        if self.distance_strategy == DistanceStrategy.COSINE:\n            embed_matrix = np.array(embeddings)\n            embed_matrix = embed_matrix / np.linalg.norm(\n                embed_matrix, axis=1, keepdims=True\n            )\n            embeddings = embed_matrix.tolist()\n        # Create points\n        ids: List[str] = []\n        points = []\n        if metadatas is not None:\n            for text, embedding, metadata in zip(texts, embeddings, metadatas):\n                new_id = str(uuid4())\n                ids.append(new_id)\n                points.append(\n                    {\n                        \"id\": new_id,\n                        \"vector\": embedding,\n                        \"metadata\": {**metadata, **{\"text\": text}},\n                    }\n                )\n        else:\n            for text, embedding in zip(texts, embeddings):\n                new_id = str(uuid4())\n                ids.append(new_id)\n                points.append(\n                    {\n                        \"id\": new_id,\n                        \"vector\": embedding,\n                        \"metadata\": {\"text\": text},\n                    }\n                )\n        # Insert points in batches\n        for i in range(0, len(points), batch_size):\n            batch = points[i : i + batch_size]\n            response = requests.post(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/semadb.html"}
{"id": "005c33cdfcc1-3", "text": "batch = points[i : i + batch_size]\n            response = requests.post(\n                SemaDB.BASE_URL + f\"/collections/{self.collection_name}/points\",\n                json={\"points\": batch},\n                headers=self.headers,\n            )\n            if response.status_code != 200:\n                print(\"HERE--\", batch)\n                raise ValueError(f\"Error adding points: {response.text}\")\n            failed_ranges = response.json()[\"failedRanges\"]\n            if len(failed_ranges) > 0:\n                raise ValueError(f\"Error adding points: {failed_ranges}\")\n        # Return ids\n        return ids\n    @property\n    def embeddings(self) -> Embeddings:\n        \"\"\"Return the embeddings.\"\"\"\n        return self._embedding\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:\n        \"\"\"Delete by vector ID or other criteria.\n        Args:\n            ids: List of ids to delete.\n            **kwargs: Other keyword arguments that subclasses might use.\n        Returns:\n            Optional[bool]: True if deletion is successful,\n            False otherwise, None if not implemented.\n        \"\"\"\n        payload = {\n            \"ids\": ids,\n        }\n        response = requests.delete(\n            SemaDB.BASE_URL + f\"/collections/{self.collection_name}/points\",\n            json=payload,\n            headers=self.headers,\n        )\n        return response.status_code == 200 and len(response.json()[\"failedPoints\"]) == 0\n    def _search_points(self, embedding: List[float], k: int = 4) -> List[dict]:\n        \"\"\"Search points.\"\"\"\n        # Normalise if needed\n        if self.distance_strategy == DistanceStrategy.COSINE:\n            vec = np.array(embedding)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/semadb.html"}
{"id": "005c33cdfcc1-4", "text": "vec = np.array(embedding)\n            vec = vec / np.linalg.norm(vec)\n            embedding = vec.tolist()\n        # Perform search request\n        payload = {\n            \"vector\": embedding,\n            \"limit\": k,\n        }\n        response = requests.post(\n            SemaDB.BASE_URL + f\"/collections/{self.collection_name}/points/search\",\n            json=payload,\n            headers=self.headers,\n        )\n        if response.status_code != 200:\n            raise ValueError(f\"Error searching: {response.text}\")\n        return response.json()[\"points\"]\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\"\"\"\n        query_embedding = self._embedding.embed_query(query)\n        return self.similarity_search_by_vector(query_embedding, k=k)\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Run similarity search with distance.\"\"\"\n        query_embedding = self._embedding.embed_query(query)\n        points = self._search_points(query_embedding, k=k)\n        return [\n            (\n                Document(page_content=p[\"metadata\"][\"text\"], metadata=p[\"metadata\"]),\n                p[\"distance\"],\n            )\n            for p in points\n        ]\n[docs]    def similarity_search_by_vector(\n        self, embedding: List[float], k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/semadb.html"}
{"id": "005c33cdfcc1-5", "text": "Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query vector.\n        \"\"\"\n        points = self._search_points(embedding, k=k)\n        return [\n            Document(page_content=p[\"metadata\"][\"text\"], metadata=p[\"metadata\"])\n            for p in points\n        ]\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        collection_name: str = \"\",\n        vector_size: int = 0,\n        api_key: str = \"\",\n        distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE,\n        **kwargs: Any,\n    ) -> \"SemaDB\":\n        \"\"\"Return VectorStore initialized from texts and embeddings.\"\"\"\n        if not collection_name:\n            raise ValueError(\"Collection name must be provided\")\n        if not vector_size:\n            raise ValueError(\"Vector size must be provided\")\n        if not api_key:\n            raise ValueError(\"API key must be provided\")\n        semadb = cls(\n            collection_name,\n            vector_size,\n            embedding,\n            distance_strategy=distance_strategy,\n            api_key=api_key,\n        )\n        if not semadb.create_collection():\n            raise ValueError(\"Error creating collection\")\n        semadb.add_texts(texts, metadatas=metadatas)\n        return semadb", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/semadb.html"}
{"id": "b84a692fa8ab-0", "text": "Source code for langchain.vectorstores.hippo\nfrom __future__ import annotations\nimport logging\nfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nif TYPE_CHECKING:\n    from transwarp_hippo_api.hippo_client import HippoClient\n# Default connection\nDEFAULT_HIPPO_CONNECTION = {\n    \"host\": \"localhost\",\n    \"port\": \"7788\",\n    \"username\": \"admin\",\n    \"password\": \"admin\",\n}\nlogger = logging.getLogger(__name__)\n[docs]class Hippo(VectorStore):\n    \"\"\"`Hippo` vector store.\n    You need to install `hippo-api` and run Hippo.\n    Please visit our official website for how to run a Hippo instance:\n    https://www.transwarp.cn/starwarp\n    Args:\n        embedding_function (Embeddings): Function used to embed the text.\n        table_name (str): Which Hippo table to use. Defaults to\n            \"test\".\n        database_name (str): Which Hippo database to use. Defaults to\n            \"default\".\n        number_of_shards (int): The number of shards for the Hippo table.Defaults to\n            1.\n        number_of_replicas (int): The number of replicas for the Hippo table.Defaults to\n            1.\n        connection_args (Optional[dict[str, any]]): The connection args used for\n            this class comes in the form of a dict.\n        index_params (Optional[dict]): Which index params to use. Defaults to\n            IVF_FLAT.\n        drop_old (Optional[bool]): Whether to drop the current collection. Defaults\n            to False.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-1", "text": "to False.\n        primary_field (str): Name of the primary key field. Defaults to \"pk\".\n        text_field (str): Name of the text field. Defaults to \"text\".\n        vector_field (str): Name of the vector field. Defaults to \"vector\".\n    The connection args used for this class comes in the form of a dict,\n    here are a few of the options:\n        host (str): The host of Hippo instance. Default at \"localhost\".\n        port (str/int): The port of Hippo instance. Default at 7788.\n        user (str): Use which user to connect to Hippo instance. If user and\n            password are provided, we will add related header in every RPC call.\n        password (str): Required when user is provided. The password\n            corresponding to the user.\n    Example:\n        .. code-block:: python\n        from langchain.vectorstores import Hippo\n        from langchain.embeddings import OpenAIEmbeddings\n        embedding = OpenAIEmbeddings()\n        # Connect to a hippo instance on localhost\n        vector_store = Hippo.from_documents(\n            docs,\n            embedding=embeddings,\n            table_name=\"langchain_test\",\n            connection_args=HIPPO_CONNECTION\n        )\n    Raises:\n        ValueError: If the hippo-api python package is not installed.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding_function: Embeddings,\n        table_name: str = \"test\",\n        database_name: str = \"default\",\n        number_of_shards: int = 1,\n        number_of_replicas: int = 1,\n        connection_args: Optional[Dict[str, Any]] = None,\n        index_params: Optional[dict] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-2", "text": "index_params: Optional[dict] = None,\n        drop_old: Optional[bool] = False,\n    ):\n        self.number_of_shards = number_of_shards\n        self.number_of_replicas = number_of_replicas\n        self.embedding_func = embedding_function\n        self.table_name = table_name\n        self.database_name = database_name\n        self.index_params = index_params\n        # In order for a collection to be compatible,\n        # 'pk' should be an auto-increment primary key and string\n        self._primary_field = \"pk\"\n        # In order for compatibility, the text field will need to be called \"text\"\n        self._text_field = \"text\"\n        # In order for compatibility, the vector field needs to be called \"vector\"\n        self._vector_field = \"vector\"\n        self.fields: List[str] = []\n        # Create the connection to the server\n        if connection_args is None:\n            connection_args = DEFAULT_HIPPO_CONNECTION\n        self.hc = self._create_connection_alias(connection_args)\n        self.col: Any = None\n        # If the collection exists, delete it\n        try:\n            if (\n                self.hc.check_table_exists(self.table_name, self.database_name)\n                and drop_old\n            ):\n                self.hc.delete_table(self.table_name, self.database_name)\n        except Exception as e:\n            logging.error(\n                f\"An error occurred while deleting the table \" f\"{self.table_name}: {e}\"\n            )\n            raise\n        try:\n            if self.hc.check_table_exists(self.table_name, self.database_name):\n                self.col = self.hc.get_table(self.table_name, self.database_name)\n        except Exception as e:\n            logging.error(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-3", "text": "except Exception as e:\n            logging.error(\n                f\"An error occurred while getting the table \" f\"{self.table_name}: {e}\"\n            )\n            raise\n        # Initialize the vector database\n        self._get_env()\n    def _create_connection_alias(self, connection_args: dict) -> HippoClient:\n        \"\"\"Create the connection to the Hippo server.\"\"\"\n        # Grab the connection arguments that are used for checking existing connection\n        try:\n            from transwarp_hippo_api.hippo_client import HippoClient\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import transwarp_hipp_api, please install with \"\n                \"`pip install hippo-api`.\"\n            ) from e\n        host: str = connection_args.get(\"host\", None)\n        port: int = connection_args.get(\"port\", None)\n        username: str = connection_args.get(\"username\", \"shiva\")\n        password: str = connection_args.get(\"password\", \"shiva\")\n        # Order of use is host/port, uri, address\n        if host is not None and port is not None:\n            if \",\" in host:\n                hosts = host.split(\",\")\n                given_address = \",\".join([f\"{h}:{port}\" for h in hosts])\n            else:\n                given_address = str(host) + \":\" + str(port)\n        else:\n            raise ValueError(\"Missing standard address type for reuse attempt\")\n        try:\n            logger.info(f\"create HippoClient[{given_address}]\")\n            return HippoClient([given_address], username=username, pwd=password)\n        except Exception as e:\n            logger.error(\"Failed to create new connection\")\n            raise e\n    def _get_env(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-4", "text": "raise e\n    def _get_env(\n        self, embeddings: Optional[list] = None, metadatas: Optional[List[dict]] = None\n    ) -> None:\n        logger.info(\"init ...\")\n        if embeddings is not None:\n            logger.info(\"create collection\")\n            self._create_collection(embeddings, metadatas)\n        self._extract_fields()\n        self._create_index()\n    def _create_collection(\n        self, embeddings: list, metadatas: Optional[List[dict]] = None\n    ) -> None:\n        from transwarp_hippo_api.hippo_client import HippoField\n        from transwarp_hippo_api.hippo_type import HippoType\n        # Determine embedding dim\n        dim = len(embeddings[0])\n        logger.debug(f\"[_create_collection] dim: {dim}\")\n        fields = []\n        # Create the primary key field\n        fields.append(HippoField(self._primary_field, True, HippoType.STRING))\n        # Create the text field\n        fields.append(HippoField(self._text_field, False, HippoType.STRING))\n        # Create the vector field, supports binary or float vectors\n        # to The binary vector type is to be developed.\n        fields.append(\n            HippoField(\n                self._vector_field,\n                False,\n                HippoType.FLOAT_VECTOR,\n                type_params={\"dimension\": dim},\n            )\n        )\n        # to In Hippo,there is no method similar to the infer_type_data\n        # types, so currently all non-vector data is converted to string type.\n        if metadatas:\n            #     # Create FieldSchema for each entry in metadata.\n            for key, value in metadatas[0].items():\n                #         # Infer the corresponding datatype of the metadata", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-5", "text": "#         # Infer the corresponding datatype of the metadata\n                if isinstance(value, list):\n                    value_dim = len(value)\n                    fields.append(\n                        HippoField(\n                            key,\n                            False,\n                            HippoType.FLOAT_VECTOR,\n                            type_params={\"dimension\": value_dim},\n                        )\n                    )\n                else:\n                    fields.append(HippoField(key, False, HippoType.STRING))\n        logger.debug(f\"[_create_collection] fields: {fields}\")\n        # Create the collection\n        self.hc.create_table(\n            name=self.table_name,\n            auto_id=True,\n            fields=fields,\n            database_name=self.database_name,\n            number_of_shards=self.number_of_shards,\n            number_of_replicas=self.number_of_replicas,\n        )\n        self.col = self.hc.get_table(self.table_name, self.database_name)\n        logger.info(\n            f\"[_create_collection] : \"\n            f\"create table {self.table_name} in {self.database_name} successfully\"\n        )\n    def _extract_fields(self) -> None:\n        \"\"\"Grab the existing fields from the Collection\"\"\"\n        from transwarp_hippo_api.hippo_client import HippoTable\n        if isinstance(self.col, HippoTable):\n            schema = self.col.schema\n            logger.debug(f\"[_extract_fields] schema:{schema}\")\n            for x in schema:\n                self.fields.append(x.name)\n            logger.debug(f\"04 [_extract_fields] fields:{self.fields}\")\n    # TO CAN: Translated into English, your statement would be: \"Currently,\n    # only the field named 'vector' (the automatically created vector field)\n    # is checked for indexing. Indexes need to be created manually for other\n    # vector type columns.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-6", "text": "# vector type columns.\n    def _get_index(self) -> Optional[Dict[str, Any]]:\n        \"\"\"Return the vector index information if it exists\"\"\"\n        from transwarp_hippo_api.hippo_client import HippoTable\n        if isinstance(self.col, HippoTable):\n            table_info = self.hc.get_table_info(\n                self.table_name, self.database_name\n            ).get(self.table_name, {})\n            embedding_indexes = table_info.get(\"embedding_indexes\", None)\n            if embedding_indexes is None:\n                return None\n            else:\n                for x in self.hc.get_table_info(self.table_name, self.database_name)[\n                    self.table_name\n                ][\"embedding_indexes\"]:\n                    logger.debug(f\"[_get_index] embedding_indexes {embedding_indexes}\")\n                    if x[\"column\"] == self._vector_field:\n                        return x\n        return None\n    # TO Indexes can only be created for the self._vector_field field.\n    def _create_index(self) -> None:\n        \"\"\"Create a index on the collection\"\"\"\n        from transwarp_hippo_api.hippo_client import HippoTable\n        from transwarp_hippo_api.hippo_type import IndexType, MetricType\n        if isinstance(self.col, HippoTable) and self._get_index() is None:\n            if self._get_index() is None:\n                if self.index_params is None:\n                    self.index_params = {\n                        \"index_name\": \"langchain_auto_create\",\n                        \"metric_type\": MetricType.L2,\n                        \"index_type\": IndexType.IVF_FLAT,\n                        \"nlist\": 10,\n                    }\n                    self.col.create_index(\n                        self._vector_field,\n                        self.index_params[\"index_name\"],\n                        self.index_params[\"index_type\"],\n                        self.index_params[\"metric_type\"],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-7", "text": "self.index_params[\"index_type\"],\n                        self.index_params[\"metric_type\"],\n                        nlist=self.index_params[\"nlist\"],\n                    )\n                    logger.debug(\n                        self.col.activate_index(self.index_params[\"index_name\"])\n                    )\n                    logger.info(\"create index successfully\")\n                else:\n                    index_dict = {\n                        \"IVF_FLAT\": IndexType.IVF_FLAT,\n                        \"FLAT\": IndexType.FLAT,\n                        \"IVF_SQ\": IndexType.IVF_SQ,\n                        \"IVF_PQ\": IndexType.IVF_PQ,\n                        \"HNSW\": IndexType.HNSW,\n                    }\n                    metric_dict = {\n                        \"ip\": MetricType.IP,\n                        \"IP\": MetricType.IP,\n                        \"l2\": MetricType.L2,\n                        \"L2\": MetricType.L2,\n                    }\n                    self.index_params[\"metric_type\"] = metric_dict[\n                        self.index_params[\"metric_type\"]\n                    ]\n                    if self.index_params[\"index_type\"] == \"FLAT\":\n                        self.index_params[\"index_type\"] = index_dict[\n                            self.index_params[\"index_type\"]\n                        ]\n                        self.col.create_index(\n                            self._vector_field,\n                            self.index_params[\"index_name\"],\n                            self.index_params[\"index_type\"],\n                            self.index_params[\"metric_type\"],\n                        )\n                        logger.debug(\n                            self.col.activate_index(self.index_params[\"index_name\"])\n                        )\n                    elif (\n                        self.index_params[\"index_type\"] == \"IVF_FLAT\"\n                        or self.index_params[\"index_type\"] == \"IVF_SQ\"\n                    ):\n                        self.index_params[\"index_type\"] = index_dict[\n                            self.index_params[\"index_type\"]\n                        ]\n                        self.col.create_index(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-8", "text": "self.index_params[\"index_type\"]\n                        ]\n                        self.col.create_index(\n                            self._vector_field,\n                            self.index_params[\"index_name\"],\n                            self.index_params[\"index_type\"],\n                            self.index_params[\"metric_type\"],\n                            nlist=self.index_params.get(\"nlist\", 10),\n                            nprobe=self.index_params.get(\"nprobe\", 10),\n                        )\n                        logger.debug(\n                            self.col.activate_index(self.index_params[\"index_name\"])\n                        )\n                    elif self.index_params[\"index_type\"] == \"IVF_PQ\":\n                        self.index_params[\"index_type\"] = index_dict[\n                            self.index_params[\"index_type\"]\n                        ]\n                        self.col.create_index(\n                            self._vector_field,\n                            self.index_params[\"index_name\"],\n                            self.index_params[\"index_type\"],\n                            self.index_params[\"metric_type\"],\n                            nlist=self.index_params.get(\"nlist\", 10),\n                            nprobe=self.index_params.get(\"nprobe\", 10),\n                            nbits=self.index_params.get(\"nbits\", 8),\n                            m=self.index_params.get(\"m\"),\n                        )\n                        logger.debug(\n                            self.col.activate_index(self.index_params[\"index_name\"])\n                        )\n                    elif self.index_params[\"index_type\"] == \"HNSW\":\n                        self.index_params[\"index_type\"] = index_dict[\n                            self.index_params[\"index_type\"]\n                        ]\n                        self.col.create_index(\n                            self._vector_field,\n                            self.index_params[\"index_name\"],\n                            self.index_params[\"index_type\"],\n                            self.index_params[\"metric_type\"],\n                            M=self.index_params.get(\"M\"),\n                            ef_construction=self.index_params.get(\"ef_construction\"),\n                            ef_search=self.index_params.get(\"ef_search\"),\n                        )\n                        logger.debug(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-9", "text": "ef_search=self.index_params.get(\"ef_search\"),\n                        )\n                        logger.debug(\n                            self.col.activate_index(self.index_params[\"index_name\"])\n                        )\n                    else:\n                        raise ValueError(\n                            \"Index name does not match, \"\n                            \"please enter the correct index name. \"\n                            \"(FLAT, IVF_FLAT, IVF_PQ,IVF_SQ, HNSW)\"\n                        )\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        timeout: Optional[int] = None,\n        batch_size: int = 1000,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"\n        Add text to the collection.\n        Args:\n            texts: An iterable that contains the text to be added.\n            metadatas: An optional list of dictionaries,\n            each dictionary contains the metadata associated with a text.\n            timeout: Optional timeout, in seconds.\n            batch_size: The number of texts inserted in each batch, defaults to 1000.\n            **kwargs: Other optional parameters.\n        Returns:\n            A list of strings, containing the unique identifiers of the inserted texts.\n        Note:\n            If the collection has not yet been created,\n            this method will create a new collection.\n        \"\"\"\n        from transwarp_hippo_api.hippo_client import HippoTable\n        if not texts or all(t == \"\" for t in texts):\n            logger.debug(\"Nothing to insert, skipping.\")\n            return []\n        texts = list(texts)\n        logger.debug(f\"[add_texts] texts: {texts}\")\n        try:\n            embeddings = self.embedding_func.embed_documents(texts)\n        except NotImplementedError:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-10", "text": "embeddings = self.embedding_func.embed_documents(texts)\n        except NotImplementedError:\n            embeddings = [self.embedding_func.embed_query(x) for x in texts]\n        if len(embeddings) == 0:\n            logger.debug(\"Nothing to insert, skipping.\")\n            return []\n        logger.debug(f\"[add_texts] len_embeddings:{len(embeddings)}\")\n        # \u5982\u679c\u8fd8\u6ca1\u6709\u521b\u5efacollection\u5219\u521b\u5efacollection\n        if not isinstance(self.col, HippoTable):\n            self._get_env(embeddings, metadatas)\n        # Dict to hold all insert columns\n        insert_dict: Dict[str, list] = {\n            self._text_field: texts,\n            self._vector_field: embeddings,\n        }\n        logger.debug(f\"[add_texts] metadatas:{metadatas}\")\n        logger.debug(f\"[add_texts] fields:{self.fields}\")\n        if metadatas is not None:\n            for d in metadatas:\n                for key, value in d.items():\n                    if key in self.fields:\n                        insert_dict.setdefault(key, []).append(value)\n        logger.debug(insert_dict[self._text_field])\n        # Total insert count\n        vectors: list = insert_dict[self._vector_field]\n        total_count = len(vectors)\n        if \"pk\" in self.fields:\n            self.fields.remove(\"pk\")\n        logger.debug(f\"[add_texts] total_count:{total_count}\")\n        for i in range(0, total_count, batch_size):\n            # Grab end index\n            end = min(i + batch_size, total_count)\n            # Convert dict to list of lists batch for insertion\n            insert_list = [insert_dict[x][i:end] for x in self.fields]\n            try:\n                res = self.col.insert_rows(insert_list)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-11", "text": "try:\n                res = self.col.insert_rows(insert_list)\n                logger.info(f\"05 [add_texts] insert {res}\")\n            except Exception as e:\n                logger.error(\n                    \"Failed to insert batch starting at entity: %s/%s\", i, total_count\n                )\n                raise e\n        return [\"\"]\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"\n        Perform a similarity search on the query string.\n        Args:\n            query (str): The text to search for.\n            k (int, optional): The number of results to return. Default is 4.\n            param (dict, optional): Specifies the search parameters for the index.\n            Defaults to None.\n            expr (str, optional): Filtering expression. Defaults to None.\n            timeout (int, optional): Time to wait before a timeout error.\n            Defaults to None.\n            kwargs: Keyword arguments for Collection.search().\n        Returns:\n            List[Document]: The document results of the search.\n        \"\"\"\n        if self.col is None:\n            logger.debug(\"No existing collection to search.\")\n            return []\n        res = self.similarity_search_with_score(\n            query=query, k=k, param=param, expr=expr, timeout=timeout, **kwargs\n        )\n        return [doc for doc, _ in res]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        param: Optional[dict] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-12", "text": "k: int = 4,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Performs a search on the query string and returns results with scores.\n        Args:\n            query (str): The text being searched.\n            k (int, optional): The number of results to return.\n            Default is 4.\n            param (dict): Specifies the search parameters for the index.\n            Default is None.\n            expr (str, optional): Filtering expression. Default is None.\n            timeout (int, optional): The waiting time before a timeout error.\n            Default is None.\n            kwargs: Keyword arguments for Collection.search().\n        Returns:\n            List[float], List[Tuple[Document, any, any]]:\n        \"\"\"\n        if self.col is None:\n            logger.debug(\"No existing collection to search.\")\n            return []\n        # Embed the query text.\n        embedding = self.embedding_func.embed_query(query)\n        ret = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs\n        )\n        return ret\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Performs a search on the query string and returns results with scores.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-13", "text": "Performs a search on the query string and returns results with scores.\n        Args:\n            embedding (List[float]): The embedding vector being searched.\n            k (int, optional): The number of results to return.\n            Default is 4.\n            param (dict): Specifies the search parameters for the index.\n            Default is None.\n            expr (str, optional): Filtering expression. Default is None.\n            timeout (int, optional): The waiting time before a timeout error.\n            Default is None.\n            kwargs: Keyword arguments for Collection.search().\n        Returns:\n            List[Tuple[Document, float]]: Resulting documents and scores.\n        \"\"\"\n        if self.col is None:\n            logger.debug(\"No existing collection to search.\")\n            return []\n        # if param is None:\n        #     param = self.search_params\n        # Determine result metadata fields.\n        output_fields = self.fields[:]\n        output_fields.remove(self._vector_field)\n        # Perform the search.\n        logger.debug(f\"search_field:{self._vector_field}\")\n        logger.debug(f\"vectors:{[embedding]}\")\n        logger.debug(f\"output_fields:{output_fields}\")\n        logger.debug(f\"topk:{k}\")\n        logger.debug(f\"dsl:{expr}\")\n        res = self.col.query(\n            search_field=self._vector_field,\n            vectors=[embedding],\n            output_fields=output_fields,\n            topk=k,\n            dsl=expr,\n        )\n        # Organize results.\n        logger.debug(f\"[similarity_search_with_score_by_vector] res:{res}\")\n        score_col = self._text_field + \"%scores\"\n        ret = []\n        count = 0\n        for items in zip(*[res[0][field] for field in output_fields]):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-14", "text": "for items in zip(*[res[0][field] for field in output_fields]):\n            meta = {field: value for field, value in zip(output_fields, items)}\n            doc = Document(page_content=meta.pop(self._text_field), metadata=meta)\n            logger.debug(\n                f\"[similarity_search_with_score_by_vector] \"\n                f\"res[0][score_col]:{res[0][score_col]}\"\n            )\n            score = res[0][score_col][count]\n            count += 1\n            ret.append((doc, score))\n        return ret\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        table_name: str = \"test\",\n        database_name: str = \"default\",\n        connection_args: Dict[str, Any] = DEFAULT_HIPPO_CONNECTION,\n        index_params: Optional[Dict[Any, Any]] = None,\n        search_params: Optional[Dict[str, Any]] = None,\n        drop_old: bool = False,\n        **kwargs: Any,\n    ) -> \"Hippo\":\n        \"\"\"\n        Creates an instance of the VST class from the given texts.\n        Args:\n            texts (List[str]): List of texts to be added.\n            embedding (Embeddings): Embedding model for the texts.\n            metadatas (List[dict], optional):\n            List of metadata dictionaries for each text.Defaults to None.\n            table_name (str): Name of the table. Defaults to \"test\".\n            database_name (str): Name of the database. Defaults to \"default\".\n            connection_args (dict[str, Any]): Connection parameters.\n            Defaults to DEFAULT_HIPPO_CONNECTION.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "b84a692fa8ab-15", "text": "Defaults to DEFAULT_HIPPO_CONNECTION.\n            index_params (dict): Indexing parameters. Defaults to None.\n            search_params (dict): Search parameters. Defaults to an empty dictionary.\n            drop_old (bool): Whether to drop the old collection. Defaults to False.\n            kwargs: Other arguments.\n        Returns:\n            Hippo: An instance of the VST class.\n        \"\"\"\n        if search_params is None:\n            search_params = {}\n        logger.info(\"00 [from_texts] init the class of Hippo\")\n        vector_db = cls(\n            embedding_function=embedding,\n            table_name=table_name,\n            database_name=database_name,\n            connection_args=connection_args,\n            index_params=index_params,\n            drop_old=drop_old,\n            **kwargs,\n        )\n        logger.debug(f\"[from_texts] texts:{texts}\")\n        logger.debug(f\"[from_texts] metadatas:{metadatas}\")\n        vector_db.add_texts(texts=texts, metadatas=metadatas)\n        return vector_db", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hippo.html"}
{"id": "c5eeed205c69-0", "text": "Source code for langchain.vectorstores.tigris\nfrom __future__ import annotations\nimport itertools\nfrom typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple\nfrom langchain.schema import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nif TYPE_CHECKING:\n    from tigrisdb import TigrisClient\n    from tigrisdb import VectorStore as TigrisVectorStore\n    from tigrisdb.types.filters import Filter as TigrisFilter\n    from tigrisdb.types.vector import Document as TigrisDocument\n[docs]class Tigris(VectorStore):\n    \"\"\"`Tigris` vector store.\"\"\"\n[docs]    def __init__(self, client: TigrisClient, embeddings: Embeddings, index_name: str):\n        \"\"\"Initialize Tigris vector store.\"\"\"\n        try:\n            import tigrisdb  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"Could not import tigrisdb python package. \"\n                \"Please install it with `pip install tigrisdb`\"\n            )\n        self._embed_fn = embeddings\n        self._vector_store = TigrisVectorStore(client.get_search(), index_name)\n    @property\n    def embeddings(self) -> Embeddings:\n        return self._embed_fn\n    @property\n    def search_index(self) -> TigrisVectorStore:\n        return self._vector_store\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html"}
{"id": "c5eeed205c69-1", "text": "\"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of ids for documents.\n                Ids will be autogenerated if not provided.\n            kwargs: vectorstore specific parameters\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        docs = self._prep_docs(texts, metadatas, ids)\n        result = self.search_index.add_documents(docs)\n        return [r.id for r in result]\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[TigrisFilter] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\"\"\"\n        docs_with_scores = self.similarity_search_with_score(query, k, filter)\n        return [doc for doc, _ in docs_with_scores]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[TigrisFilter] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Run similarity search with Chroma with distance.\n        Args:\n            query (str): Query text to search for.\n            k (int): Number of results to return. Defaults to 4.\n            filter (Optional[TigrisFilter]): Filter by metadata. Defaults to None.\n        Returns:\n            List[Tuple[Document, float]]: List of documents most similar to the query\n                text with distance in float.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html"}
{"id": "c5eeed205c69-2", "text": "text with distance in float.\n        \"\"\"\n        vector = self._embed_fn.embed_query(query)\n        result = self.search_index.similarity_search(\n            vector=vector, k=k, filter_by=filter\n        )\n        docs: List[Tuple[Document, float]] = []\n        for r in result:\n            docs.append(\n                (\n                    Document(\n                        page_content=r.doc[\"text\"], metadata=r.doc.get(\"metadata\")\n                    ),\n                    r.score,\n                )\n            )\n        return docs\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        client: Optional[TigrisClient] = None,\n        index_name: Optional[str] = None,\n        **kwargs: Any,\n    ) -> Tigris:\n        \"\"\"Return VectorStore initialized from texts and embeddings.\"\"\"\n        if not index_name:\n            raise ValueError(\"`index_name` is required\")\n        if not client:\n            client = TigrisClient()\n        store = cls(client, embedding, index_name)\n        store.add_texts(texts=texts, metadatas=metadatas, ids=ids)\n        return store\n    def _prep_docs(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]],\n        ids: Optional[List[str]],\n    ) -> List[TigrisDocument]:\n        embeddings: List[List[float]] = self._embed_fn.embed_documents(list(texts))\n        docs: List[TigrisDocument] = []\n        for t, m, e, _id in itertools.zip_longest(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html"}
{"id": "c5eeed205c69-3", "text": "for t, m, e, _id in itertools.zip_longest(\n            texts, metadatas or [], embeddings or [], ids or []\n        ):\n            doc: TigrisDocument = {\n                \"text\": t,\n                \"embeddings\": e or [],\n                \"metadata\": m or {},\n            }\n            if _id:\n                doc[\"id\"] = _id\n            docs.append(doc)\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html"}
{"id": "0e0d6e5a9a5b-0", "text": "Source code for langchain.vectorstores.bageldb\nfrom __future__ import annotations\nimport uuid\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n)\nif TYPE_CHECKING:\n    import bagel\n    import bagel.config\n    from bagel.api.types import ID, OneOrMany, Where, WhereDocument\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import xor_args\nDEFAULT_K = 5\ndef _results_to_docs(results: Any) -> List[Document]:\n    return [doc for doc, _ in _results_to_docs_and_scores(results)]\ndef _results_to_docs_and_scores(results: Any) -> List[Tuple[Document, float]]:\n    return [\n        (Document(page_content=result[0], metadata=result[1] or {}), result[2])\n        for result in zip(\n            results[\"documents\"][0],\n            results[\"metadatas\"][0],\n            results[\"distances\"][0],\n        )\n    ]\n[docs]class Bagel(VectorStore):\n    \"\"\"``BagelDB.ai`` vector store.\n    To use, you should have the ``betabageldb`` python package installed.\n    Example:\n        .. code-block:: python\n                from langchain.vectorstores import Bagel\n                vectorstore = Bagel(cluster_name=\"langchain_store\")\n    \"\"\"\n    _LANGCHAIN_DEFAULT_CLUSTER_NAME = \"langchain\"\n[docs]    def __init__(\n        self,\n        cluster_name: str = _LANGCHAIN_DEFAULT_CLUSTER_NAME,\n        client_settings: Optional[bagel.config.Settings] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html"}
{"id": "0e0d6e5a9a5b-1", "text": "client_settings: Optional[bagel.config.Settings] = None,\n        embedding_function: Optional[Embeddings] = None,\n        cluster_metadata: Optional[Dict] = None,\n        client: Optional[bagel.Client] = None,\n        relevance_score_fn: Optional[Callable[[float], float]] = None,\n    ) -> None:\n        \"\"\"Initialize with bagel client\"\"\"\n        try:\n            import bagel\n            import bagel.config\n        except ImportError:\n            raise ImportError(\"Please install bagel `pip install betabageldb`.\")\n        if client is not None:\n            self._client_settings = client_settings\n            self._client = client\n        else:\n            if client_settings:\n                _client_settings = client_settings\n            else:\n                _client_settings = bagel.config.Settings(\n                    bagel_api_impl=\"rest\",\n                    bagel_server_host=\"api.bageldb.ai\",\n                )\n            self._client_settings = _client_settings\n            self._client = bagel.Client(_client_settings)\n        self._cluster = self._client.get_or_create_cluster(\n            name=cluster_name,\n            metadata=cluster_metadata,\n        )\n        self.override_relevance_score_fn = relevance_score_fn\n        self._embedding_function = embedding_function\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return self._embedding_function\n    @xor_args((\"query_texts\", \"query_embeddings\"))\n    def __query_cluster(\n        self,\n        query_texts: Optional[List[str]] = None,\n        query_embeddings: Optional[List[List[float]]] = None,\n        n_results: int = 4,\n        where: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html"}
{"id": "0e0d6e5a9a5b-2", "text": "**kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Query the BagelDB cluster based on the provided parameters.\"\"\"\n        try:\n            import bagel  # noqa: F401\n        except ImportError:\n            raise ImportError(\"Please install bagel `pip install betabageldb`.\")\n        return self._cluster.find(\n            query_texts=query_texts,\n            query_embeddings=query_embeddings,\n            n_results=n_results,\n            where=where,\n            **kwargs,\n        )\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        embeddings: Optional[List[List[float]]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"\n        Add texts along with their corresponding embeddings and optional\n        metadata to the BagelDB cluster.\n        Args:\n            texts (Iterable[str]): Texts to be added.\n            embeddings (Optional[List[float]]): List of embeddingvectors\n            metadatas (Optional[List[dict]]): Optional list of metadatas.\n            ids (Optional[List[str]]): List of unique ID for the texts.\n        Returns:\n            List[str]: List of unique ID representing the added texts.\n        \"\"\"\n        # creating unique ids if None\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        texts = list(texts)\n        if self._embedding_function and embeddings is None and texts:\n            embeddings = self._embedding_function.embed_documents(texts)\n        if metadatas:\n            length_diff = len(texts) - len(metadatas)\n            if length_diff:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html"}
{"id": "0e0d6e5a9a5b-3", "text": "if length_diff:\n                metadatas = metadatas + [{}] * length_diff\n            empty_ids = []\n            non_empty_ids = []\n            for idx, metadata in enumerate(metadatas):\n                if metadata:\n                    non_empty_ids.append(idx)\n                else:\n                    empty_ids.append(idx)\n            if non_empty_ids:\n                metadatas = [metadatas[idx] for idx in non_empty_ids]\n                texts_with_metadatas = [texts[idx] for idx in non_empty_ids]\n                embeddings_with_metadatas = (\n                    [embeddings[idx] for idx in non_empty_ids] if embeddings else None\n                )\n                ids_with_metadata = [ids[idx] for idx in non_empty_ids]\n                self._cluster.upsert(\n                    embeddings=embeddings_with_metadatas,\n                    metadatas=metadatas,\n                    documents=texts_with_metadatas,\n                    ids=ids_with_metadata,\n                )\n            if empty_ids:\n                texts_without_metadatas = [texts[j] for j in empty_ids]\n                embeddings_without_metadatas = (\n                    [embeddings[j] for j in empty_ids] if embeddings else None\n                )\n                ids_without_metadatas = [ids[j] for j in empty_ids]\n                self._cluster.upsert(\n                    embeddings=embeddings_without_metadatas,\n                    documents=texts_without_metadatas,\n                    ids=ids_without_metadatas,\n                )\n        else:\n            metadatas = [{}] * len(texts)\n            self._cluster.upsert(\n                embeddings=embeddings,\n                documents=texts,\n                metadatas=metadatas,\n                ids=ids,\n            )\n        return ids\n[docs]    def similarity_search(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html"}
{"id": "0e0d6e5a9a5b-4", "text": ")\n        return ids\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = DEFAULT_K,\n        where: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"\n        Run a similarity search with BagelDB.\n        Args:\n            query (str): The query text to search for similar documents/texts.\n            k (int): The number of results to return.\n            where (Optional[Dict[str, str]]): Metadata filters to narrow down.\n        Returns:\n            List[Document]: List of documents objects representing\n            the documents most similar to the query text.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(query, k, where=where)\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = DEFAULT_K,\n        where: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Run a similarity search with BagelDB and return documents with their\n        corresponding similarity scores.\n        Args:\n            query (str): The query text to search for similar documents.\n            k (int): The number of results to return.\n            where (Optional[Dict[str, str]]): Filter using metadata.\n        Returns:\n            List[Tuple[Document, float]]: List of tuples, each containing a\n            Document object representing a similar document and its\n            corresponding similarity score.\n        \"\"\"\n        results = self.__query_cluster(query_texts=[query], n_results=k, where=where)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html"}
{"id": "0e0d6e5a9a5b-5", "text": "return _results_to_docs_and_scores(results)\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[Bagel],\n        texts: List[str],\n        embedding: Optional[Embeddings] = None,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        cluster_name: str = _LANGCHAIN_DEFAULT_CLUSTER_NAME,\n        client_settings: Optional[bagel.config.Settings] = None,\n        cluster_metadata: Optional[Dict] = None,\n        client: Optional[bagel.Client] = None,\n        text_embeddings: Optional[List[List[float]]] = None,\n        **kwargs: Any,\n    ) -> Bagel:\n        \"\"\"\n        Create and initialize a Bagel instance from list of texts.\n        Args:\n            texts (List[str]): List of text content to be added.\n            cluster_name (str): The name of the BagelDB cluster.\n            client_settings (Optional[bagel.config.Settings]): Client settings.\n            cluster_metadata (Optional[Dict]): Metadata of the cluster.\n            embeddings (Optional[Embeddings]): List of embedding.\n            metadatas (Optional[List[dict]]): List of metadata.\n            ids (Optional[List[str]]): List of unique ID. Defaults to None.\n            client (Optional[bagel.Client]): Bagel client instance.\n        Returns:\n            Bagel: Bagel vectorstore.\n        \"\"\"\n        bagel_cluster = cls(\n            cluster_name=cluster_name,\n            embedding_function=embedding,\n            client_settings=client_settings,\n            client=client,\n            cluster_metadata=cluster_metadata,\n            **kwargs,\n        )\n        _ = bagel_cluster.add_texts(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html"}
{"id": "0e0d6e5a9a5b-6", "text": "**kwargs,\n        )\n        _ = bagel_cluster.add_texts(\n            texts=texts, embeddings=text_embeddings, metadatas=metadatas, ids=ids\n        )\n        return bagel_cluster\n[docs]    def delete_cluster(self) -> None:\n        \"\"\"Delete the cluster.\"\"\"\n        self._client.delete_cluster(self._cluster.name)\n[docs]    def similarity_search_by_vector_with_relevance_scores(\n        self,\n        query_embeddings: List[float],\n        k: int = DEFAULT_K,\n        where: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Return docs most similar to embedding vector and similarity score.\n        \"\"\"\n        results = self.__query_cluster(\n            query_embeddings=query_embeddings, n_results=k, where=where\n        )\n        return _results_to_docs_and_scores(results)\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = DEFAULT_K,\n        where: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\"\"\"\n        results = self.__query_cluster(\n            query_embeddings=embedding, n_results=k, where=where\n        )\n        return _results_to_docs(results)\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        \"\"\"\n        Select and return the appropriate relevance score function based\n        on the distance metric used in the BagelDB cluster.\n        \"\"\"\n        if self.override_relevance_score_fn:\n            return self.override_relevance_score_fn\n        distance = \"l2\"\n        distance_key = \"hnsw:space\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html"}
{"id": "0e0d6e5a9a5b-7", "text": "distance = \"l2\"\n        distance_key = \"hnsw:space\"\n        metadata = self._cluster.metadata\n        if metadata and distance_key in metadata:\n            distance = metadata[distance_key]\n        if distance == \"cosine\":\n            return self._cosine_relevance_score_fn\n        elif distance == \"l2\":\n            return self._euclidean_relevance_score_fn\n        elif distance == \"ip\":\n            return self._max_inner_product_relevance_score_fn\n        else:\n            raise ValueError(\n                \"No supported normalization function for distance\"\n                f\" metric of type: {distance}. Consider providing\"\n                \" relevance_score_fn to Bagel constructor.\"\n            )\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[Bagel],\n        documents: List[Document],\n        embedding: Optional[Embeddings] = None,\n        ids: Optional[List[str]] = None,\n        cluster_name: str = _LANGCHAIN_DEFAULT_CLUSTER_NAME,\n        client_settings: Optional[bagel.config.Settings] = None,\n        client: Optional[bagel.Client] = None,\n        cluster_metadata: Optional[Dict] = None,\n        **kwargs: Any,\n    ) -> Bagel:\n        \"\"\"\n        Create a Bagel vectorstore from a list of documents.\n        Args:\n            documents (List[Document]): List of Document objects to add to the\n                                        Bagel vectorstore.\n            embedding (Optional[List[float]]): List of embedding.\n            ids (Optional[List[str]]): List of IDs. Defaults to None.\n            cluster_name (str): The name of the BagelDB cluster.\n            client_settings (Optional[bagel.config.Settings]): Client settings.\n            client (Optional[bagel.Client]): Bagel client instance.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html"}
{"id": "0e0d6e5a9a5b-8", "text": "client (Optional[bagel.Client]): Bagel client instance.\n            cluster_metadata (Optional[Dict]): Metadata associated with the\n                                               Bagel cluster. Defaults to None.\n        Returns:\n            Bagel: Bagel vectorstore.\n        \"\"\"\n        texts = [doc.page_content for doc in documents]\n        metadatas = [doc.metadata for doc in documents]\n        return cls.from_texts(\n            texts=texts,\n            embedding=embedding,\n            metadatas=metadatas,\n            ids=ids,\n            cluster_name=cluster_name,\n            client_settings=client_settings,\n            client=client,\n            cluster_metadata=cluster_metadata,\n            **kwargs,\n        )\n[docs]    def update_document(self, document_id: str, document: Document) -> None:\n        \"\"\"Update a document in the cluster.\n        Args:\n            document_id (str): ID of the document to update.\n            document (Document): Document to update.\n        \"\"\"\n        text = document.page_content\n        metadata = document.metadata\n        self._cluster.update(\n            ids=[document_id],\n            documents=[text],\n            metadatas=[metadata],\n        )\n[docs]    def get(\n        self,\n        ids: Optional[OneOrMany[ID]] = None,\n        where: Optional[Where] = None,\n        limit: Optional[int] = None,\n        offset: Optional[int] = None,\n        where_document: Optional[WhereDocument] = None,\n        include: Optional[List[str]] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Gets the collection.\"\"\"\n        kwargs = {\n            \"ids\": ids,\n            \"where\": where,\n            \"limit\": limit,\n            \"offset\": offset,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html"}
{"id": "0e0d6e5a9a5b-9", "text": "\"limit\": limit,\n            \"offset\": offset,\n            \"where_document\": where_document,\n        }\n        if include is not None:\n            kwargs[\"include\"] = include\n        return self._cluster.get(**kwargs)\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None:\n        \"\"\"\n        Delete by IDs.\n        Args:\n            ids: List of ids to delete.\n        \"\"\"\n        self._cluster.delete(ids=ids)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/bageldb.html"}
{"id": "38fdd588dd0f-0", "text": "Source code for langchain.vectorstores.dashvector\nfrom __future__ import annotations\nimport logging\nimport uuid\nfrom typing import (\n    Any,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n)\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_env\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nlogger = logging.getLogger(__name__)\n[docs]class DashVector(VectorStore):\n    \"\"\"`DashVector` vector store.\n    To use, you should have the ``dashvector`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import dashvector\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            import dashvector\n            client = dashvector.Client.init(api_key=\"***\")\n            client.create(\"langchain\")\n            collection = client.get(\"langchain\")\n            embeddings = OpenAIEmbeddings()\n            vectorstore = Dashvector(collection, embeddings.embed_query, \"text\")\n    \"\"\"\n[docs]    def __init__(\n        self,\n        collection: Any,\n        embedding: Embeddings,\n        text_field: str,\n    ):\n        \"\"\"Initialize with DashVector collection.\"\"\"\n        try:\n            import dashvector\n        except ImportError:\n            raise ValueError(\n                \"Could not import dashvector python package. \"\n                \"Please install it with `pip install dashvector`.\"\n            )\n        if not isinstance(collection, dashvector.Collection):\n            raise ValueError(\n                f\"collection should be an instance of dashvector.Collection, \"\n                f\"bug got {type(collection)}\"\n            )\n        self._collection = collection", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html"}
{"id": "38fdd588dd0f-1", "text": ")\n        self._collection = collection\n        self._embedding = embedding\n        self._text_field = text_field\n    def _similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[str] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query vector, along with scores\"\"\"\n        # query by vector\n        ret = self._collection.query(embedding, topk=k, filter=filter)\n        if not ret:\n            raise ValueError(\n                f\"Fail to query docs by vector, error {self._collection.message}\"\n            )\n        docs = []\n        for doc in ret:\n            metadata = doc.fields\n            text = metadata.pop(self._text_field)\n            score = doc.score\n            docs.append((Document(page_content=text, metadata=metadata), score))\n        return docs\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        batch_size: int = 25,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of ids associated with the texts.\n            batch_size: Optional batch size to upsert docs.\n            kwargs: vectorstore specific parameters\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html"}
{"id": "38fdd588dd0f-2", "text": "List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        ids = ids or [str(uuid.uuid4().hex) for _ in texts]\n        text_list = list(texts)\n        for i in range(0, len(text_list), batch_size):\n            # batch end\n            end = min(i + batch_size, len(text_list))\n            batch_texts = text_list[i:end]\n            batch_ids = ids[i:end]\n            batch_embeddings = self._embedding.embed_documents(list(batch_texts))\n            # batch metadatas\n            if metadatas:\n                batch_metadatas = metadatas[i:end]\n            else:\n                batch_metadatas = [{} for _ in range(i, end)]\n            for metadata, text in zip(batch_metadatas, batch_texts):\n                metadata[self._text_field] = text\n            # batch upsert to collection\n            docs = list(zip(batch_ids, batch_embeddings, batch_metadatas))\n            ret = self._collection.upsert(docs)\n            if not ret:\n                raise ValueError(\n                    f\"Fail to upsert docs to dashvector vector database,\"\n                    f\"Error: {ret.message}\"\n                )\n        return ids\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> bool:\n        \"\"\"Delete by vector ID.\n        Args:\n            ids: List of ids to delete.\n        Returns:\n            True if deletion is successful,\n            False otherwise.\n        \"\"\"\n        return bool(self._collection.delete(ids))\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html"}
{"id": "38fdd588dd0f-3", "text": "**kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to search documents similar to.\n            k: Number of documents to return. Default to 4.\n            filter: Doc fields filter conditions that meet the SQL where clause\n                    specification.\n        Returns:\n            List of Documents most similar to the query text.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_relevance_scores(query, k, filter)\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query text , alone with relevance scores.\n        Less is more similar, more is more dissimilar.\n        Args:\n            query: input text\n            k: Number of Documents to return. Defaults to 4.\n            filter: Doc fields filter conditions that meet the SQL where clause\n                    specification.\n        Returns:\n            List of Tuples of (doc, similarity_score)\n        \"\"\"\n        embedding = self._embedding.embed_query(query)\n        return self._similarity_search_with_score_by_vector(\n            embedding, k=k, filter=filter\n        )\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html"}
{"id": "38fdd588dd0f-4", "text": "\"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Doc fields filter conditions that meet the SQL where clause\n                    specification.\n        Returns:\n            List of Documents most similar to the query vector.\n        \"\"\"\n        docs_and_scores = self._similarity_search_with_score_by_vector(\n            embedding, k, filter\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            filter: Doc fields filter conditions that meet the SQL where clause\n                    specification.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        embedding = self._embedding.embed_query(query)\n        return self.max_marginal_relevance_search_by_vector(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html"}
{"id": "38fdd588dd0f-5", "text": "return self.max_marginal_relevance_search_by_vector(\n            embedding, k, fetch_k, lambda_mult, filter\n        )\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            filter: Doc fields filter conditions that meet the SQL where clause\n                    specification.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        # query by vector\n        ret = self._collection.query(\n            embedding, topk=fetch_k, filter=filter, include_vector=True\n        )\n        if not ret:\n            raise ValueError(\n                f\"Fail to query docs by vector, error {self._collection.message}\"\n            )\n        candidate_embeddings = [doc.vector for doc in ret]\n        mmr_selected = maximal_marginal_relevance(\n            np.array(embedding), candidate_embeddings, lambda_mult, k\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html"}
{"id": "38fdd588dd0f-6", "text": "np.array(embedding), candidate_embeddings, lambda_mult, k\n        )\n        metadatas = [ret.output[i].fields for i in mmr_selected]\n        return [\n            Document(page_content=metadata.pop(self._text_field), metadata=metadata)\n            for metadata in metadatas\n        ]\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        dashvector_api_key: Optional[str] = None,\n        collection_name: str = \"langchain\",\n        text_field: str = \"text\",\n        batch_size: int = 25,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> DashVector:\n        \"\"\"Return DashVector VectorStore initialized from texts and embeddings.\n        This is the quick way to get started with dashvector vector store.\n        Example:\n            .. code-block:: python\n            from langchain.vectorstores import DashVector\n            from langchain.embeddings import OpenAIEmbeddings\n            import dashvector\n            embeddings = OpenAIEmbeddings()\n            dashvector = DashVector.from_documents(\n                docs,\n                embeddings,\n                dashvector_api_key=\"{DASHVECTOR_API_KEY}\"\n            )\n        \"\"\"\n        try:\n            import dashvector\n        except ImportError:\n            raise ValueError(\n                \"Could not import dashvector python package. \"\n                \"Please install it with `pip install dashvector`.\"\n            )\n        dashvector_api_key = dashvector_api_key or get_from_env(\n            \"dashvector_api_key\", \"DASHVECTOR_API_KEY\"\n        )\n        dashvector_client = dashvector.Client(api_key=dashvector_api_key)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html"}
{"id": "38fdd588dd0f-7", "text": ")\n        dashvector_client = dashvector.Client(api_key=dashvector_api_key)\n        dashvector_client.delete(collection_name)\n        collection = dashvector_client.get(collection_name)\n        if not collection:\n            dim = len(embedding.embed_query(texts[0]))\n            # create collection if not existed\n            resp = dashvector_client.create(collection_name, dimension=dim)\n            if resp:\n                collection = dashvector_client.get(collection_name)\n            else:\n                raise ValueError(\n                    \"Fail to create collection. \" f\"Error: {resp.message}.\"\n                )\n        dashvector_vector_db = cls(collection, embedding, text_field)\n        dashvector_vector_db.add_texts(texts, metadatas, ids, batch_size)\n        return dashvector_vector_db", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/dashvector.html"}
{"id": "7e2ddef7886f-0", "text": "Source code for langchain.vectorstores.analyticdb\nfrom __future__ import annotations\nimport logging\nimport uuid\nfrom typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Type\nfrom sqlalchemy import REAL, Column, String, Table, create_engine, insert, text\nfrom sqlalchemy.dialects.postgresql import ARRAY, JSON, TEXT\ntry:\n    from sqlalchemy.orm import declarative_base\nexcept ImportError:\n    from sqlalchemy.ext.declarative import declarative_base\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_dict_or_env\n_LANGCHAIN_DEFAULT_EMBEDDING_DIM = 1536\n_LANGCHAIN_DEFAULT_COLLECTION_NAME = \"langchain_document\"\nBase = declarative_base()  # type: Any\n[docs]class AnalyticDB(VectorStore):\n    \"\"\"`AnalyticDB` (distributed PostgreSQL) vector store.\n    AnalyticDB is a distributed full postgresql syntax cloud-native database.\n    - `connection_string` is a postgres connection string.\n    - `embedding_function` any embedding function implementing\n        `langchain.embeddings.base.Embeddings` interface.\n    - `collection_name` is the name of the collection to use. (default: langchain)\n        - NOTE: This is not the name of the table, but the name of the collection.\n            The tables will be created when initializing the store (if not exists)\n            So, make sure the user has the right permissions to create tables.\n    - `pre_delete_collection` if True, will delete the collection if it exists.\n        (default: False)\n        - Useful for testing.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        connection_string: str,\n        embedding_function: Embeddings,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html"}
{"id": "7e2ddef7886f-1", "text": "self,\n        connection_string: str,\n        embedding_function: Embeddings,\n        embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        pre_delete_collection: bool = False,\n        logger: Optional[logging.Logger] = None,\n        engine_args: Optional[dict] = None,\n    ) -> None:\n        self.connection_string = connection_string\n        self.embedding_function = embedding_function\n        self.embedding_dimension = embedding_dimension\n        self.collection_name = collection_name\n        self.pre_delete_collection = pre_delete_collection\n        self.logger = logger or logging.getLogger(__name__)\n        self.__post_init__(engine_args)\n    def __post_init__(\n        self,\n        engine_args: Optional[dict] = None,\n    ) -> None:\n        \"\"\"\n        Initialize the store.\n        \"\"\"\n        _engine_args = engine_args or {}\n        if (\n            \"pool_recycle\" not in _engine_args\n        ):  # Check if pool_recycle is not in _engine_args\n            _engine_args[\n                \"pool_recycle\"\n            ] = 3600  # Set pool_recycle to 3600s if not present\n        self.engine = create_engine(self.connection_string, **_engine_args)\n        self.create_collection()\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding_function\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        return self._euclidean_relevance_score_fn\n[docs]    def create_table_if_not_exists(self) -> None:\n        # Define the dynamic table\n        Table(\n            self.collection_name,\n            Base.metadata,\n            Column(\"id\", TEXT, primary_key=True, default=uuid.uuid4),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html"}
{"id": "7e2ddef7886f-2", "text": "Column(\"id\", TEXT, primary_key=True, default=uuid.uuid4),\n            Column(\"embedding\", ARRAY(REAL)),\n            Column(\"document\", String, nullable=True),\n            Column(\"metadata\", JSON, nullable=True),\n            extend_existing=True,\n        )\n        with self.engine.connect() as conn:\n            with conn.begin():\n                # Create the table\n                Base.metadata.create_all(conn)\n                # Check if the index exists\n                index_name = f\"{self.collection_name}_embedding_idx\"\n                index_query = text(\n                    f\"\"\"\n                    SELECT 1\n                    FROM pg_indexes\n                    WHERE indexname = '{index_name}';\n                \"\"\"\n                )\n                result = conn.execute(index_query).scalar()\n                # Create the index if it doesn't exist\n                if not result:\n                    index_statement = text(\n                        f\"\"\"\n                        CREATE INDEX {index_name}\n                        ON {self.collection_name} USING ann(embedding)\n                        WITH (\n                            \"dim\" = {self.embedding_dimension},\n                            \"hnsw_m\" = 100\n                        );\n                    \"\"\"\n                    )\n                    conn.execute(index_statement)\n[docs]    def create_collection(self) -> None:\n        if self.pre_delete_collection:\n            self.delete_collection()\n        self.create_table_if_not_exists()\n[docs]    def delete_collection(self) -> None:\n        self.logger.debug(\"Trying to delete collection\")\n        drop_statement = text(f\"DROP TABLE IF EXISTS {self.collection_name};\")\n        with self.engine.connect() as conn:\n            with conn.begin():\n                conn.execute(drop_statement)\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html"}
{"id": "7e2ddef7886f-3", "text": "ids: Optional[List[str]] = None,\n        batch_size: int = 500,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        embeddings = self.embedding_function.embed_documents(list(texts))\n        if not metadatas:\n            metadatas = [{} for _ in texts]\n        # Define the table schema\n        chunks_table = Table(\n            self.collection_name,\n            Base.metadata,\n            Column(\"id\", TEXT, primary_key=True),\n            Column(\"embedding\", ARRAY(REAL)),\n            Column(\"document\", String, nullable=True),\n            Column(\"metadata\", JSON, nullable=True),\n            extend_existing=True,\n        )\n        chunks_table_data = []\n        with self.engine.connect() as conn:\n            with conn.begin():\n                for document, metadata, chunk_id, embedding in zip(\n                    texts, metadatas, ids, embeddings\n                ):\n                    chunks_table_data.append(\n                        {\n                            \"id\": chunk_id,\n                            \"embedding\": embedding,\n                            \"document\": document,\n                            \"metadata\": metadata,\n                        }\n                    )\n                    # Execute the batch insert when the batch size is reached\n                    if len(chunks_table_data) == batch_size:\n                        conn.execute(insert(chunks_table).values(chunks_table_data))\n                        # Clear the chunks_table_data list for the next batch", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html"}
{"id": "7e2ddef7886f-4", "text": "# Clear the chunks_table_data list for the next batch\n                        chunks_table_data.clear()\n                # Insert any remaining records that didn't make up a full batch\n                if chunks_table_data:\n                    conn.execute(insert(chunks_table).values(chunks_table_data))\n        return ids\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Run similarity search with AnalyticDB with distance.\n        Args:\n            query (str): Query text to search for.\n            k (int): Number of results to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        embedding = self.embedding_function.embed_query(text=query)\n        return self.similarity_search_by_vector(\n            embedding=embedding,\n            k=k,\n            filter=filter,\n        )\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[dict] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        embedding = self.embedding_function.embed_query(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html"}
{"id": "7e2ddef7886f-5", "text": "\"\"\"\n        embedding = self.embedding_function.embed_query(query)\n        docs = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, filter=filter\n        )\n        return docs\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[dict] = None,\n    ) -> List[Tuple[Document, float]]:\n        # Add the filter if provided\n        try:\n            from sqlalchemy.engine import Row\n        except ImportError:\n            raise ImportError(\n                \"Could not import Row from sqlalchemy.engine. \"\n                \"Please 'pip install sqlalchemy>=1.4'.\"\n            )\n        filter_condition = \"\"\n        if filter is not None:\n            conditions = [\n                f\"metadata->>{key!r} = {value!r}\" for key, value in filter.items()\n            ]\n            filter_condition = f\"WHERE {' AND '.join(conditions)}\"\n        # Define the base query\n        sql_query = f\"\"\"\n            SELECT *, l2_distance(embedding, :embedding) as distance\n            FROM {self.collection_name}\n            {filter_condition}\n            ORDER BY embedding <-> :embedding\n            LIMIT :k\n        \"\"\"\n        # Set up the query parameters\n        params = {\"embedding\": embedding, \"k\": k}\n        # Execute the query and fetch the results\n        with self.engine.connect() as conn:\n            results: Sequence[Row] = conn.execute(text(sql_query), params).fetchall()\n        documents_with_scores = [\n            (\n                Document(\n                    page_content=result.document,\n                    metadata=result.metadata,\n                ),\n                result.distance if self.embedding_function is not None else None,\n            )\n            for result in results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html"}
{"id": "7e2ddef7886f-6", "text": ")\n            for result in results\n        ]\n        return documents_with_scores\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query vector.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, filter=filter\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:\n        \"\"\"Delete by vector IDs.\n        Args:\n            ids: List of ids to delete.\n        \"\"\"\n        if ids is None:\n            raise ValueError(\"No ids provided to delete.\")\n        # Define the table schema\n        chunks_table = Table(\n            self.collection_name,\n            Base.metadata,\n            Column(\"id\", TEXT, primary_key=True),\n            Column(\"embedding\", ARRAY(REAL)),\n            Column(\"document\", String, nullable=True),\n            Column(\"metadata\", JSON, nullable=True),\n            extend_existing=True,\n        )\n        try:\n            with self.engine.connect() as conn:\n                with conn.begin():\n                    delete_condition = chunks_table.c.id.in_(ids)\n                    conn.execute(chunks_table.delete().where(delete_condition))\n                    return True", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html"}
{"id": "7e2ddef7886f-7", "text": "conn.execute(chunks_table.delete().where(delete_condition))\n                    return True\n        except Exception as e:\n            print(\"Delete operation failed:\", str(e))\n            return False\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[AnalyticDB],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        engine_args: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> AnalyticDB:\n        \"\"\"\n        Return VectorStore initialized from texts and embeddings.\n        Postgres Connection string is required\n        Either pass it as a parameter\n        or set the PG_CONNECTION_STRING environment variable.\n        \"\"\"\n        connection_string = cls.get_connection_string(kwargs)\n        store = cls(\n            connection_string=connection_string,\n            collection_name=collection_name,\n            embedding_function=embedding,\n            embedding_dimension=embedding_dimension,\n            pre_delete_collection=pre_delete_collection,\n            engine_args=engine_args,\n        )\n        store.add_texts(texts=texts, metadatas=metadatas, ids=ids, **kwargs)\n        return store\n[docs]    @classmethod\n    def get_connection_string(cls, kwargs: Dict[str, Any]) -> str:\n        connection_string: str = get_from_dict_or_env(\n            data=kwargs,\n            key=\"connection_string\",\n            env_key=\"PG_CONNECTION_STRING\",\n        )\n        if not connection_string:\n            raise ValueError(\n                \"Postgres connection string is required\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html"}
{"id": "7e2ddef7886f-8", "text": "raise ValueError(\n                \"Postgres connection string is required\"\n                \"Either pass it as a parameter\"\n                \"or set the PG_CONNECTION_STRING environment variable.\"\n            )\n        return connection_string\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[AnalyticDB],\n        documents: List[Document],\n        embedding: Embeddings,\n        embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        engine_args: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> AnalyticDB:\n        \"\"\"\n        Return VectorStore initialized from documents and embeddings.\n        Postgres Connection string is required\n        Either pass it as a parameter\n        or set the PG_CONNECTION_STRING environment variable.\n        \"\"\"\n        texts = [d.page_content for d in documents]\n        metadatas = [d.metadata for d in documents]\n        connection_string = cls.get_connection_string(kwargs)\n        kwargs[\"connection_string\"] = connection_string\n        return cls.from_texts(\n            texts=texts,\n            pre_delete_collection=pre_delete_collection,\n            embedding=embedding,\n            embedding_dimension=embedding_dimension,\n            metadatas=metadatas,\n            ids=ids,\n            collection_name=collection_name,\n            engine_args=engine_args,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def connection_string_from_db_params(\n        cls,\n        driver: str,\n        host: str,\n        port: int,\n        database: str,\n        user: str,\n        password: str,\n    ) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html"}
{"id": "7e2ddef7886f-9", "text": "user: str,\n        password: str,\n    ) -> str:\n        \"\"\"Return connection string from database parameters.\"\"\"\n        return f\"postgresql+{driver}://{user}:{password}@{host}:{port}/{database}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html"}
{"id": "c03189824e43-0", "text": "Source code for langchain.vectorstores.pgvecto_rs\nfrom __future__ import annotations\nimport uuid\nfrom typing import Any, Iterable, List, Literal, Optional, Tuple, Type\nimport numpy as np\nimport sqlalchemy\nfrom sqlalchemy import insert, select\nfrom sqlalchemy.dialects import postgresql\nfrom sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column\nfrom sqlalchemy.orm.session import Session\nfrom langchain.schema import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nclass _ORMBase(DeclarativeBase):\n    __tablename__: str\n    id: Mapped[uuid.UUID]\n    text: Mapped[str]\n    meta: Mapped[dict]\n    embedding: Mapped[np.ndarray]\n[docs]class PGVecto_rs(VectorStore):\n    _engine: sqlalchemy.engine.Engine\n    _table: Type[_ORMBase]\n    _embedding: Embeddings\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        dimension: int,\n        db_url: str,\n        collection_name: str,\n        new_table: bool = False,\n    ) -> None:\n        try:\n            from pgvecto_rs.sqlalchemy import Vector\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import pgvector_rs, please install with \"\n                \"`pip install pgvector_rs`.\"\n            ) from e\n        class _Table(_ORMBase):\n            __tablename__ = f\"collection_{collection_name}\"\n            id: Mapped[uuid.UUID] = mapped_column(\n                postgresql.UUID(as_uuid=True), primary_key=True, default=uuid.uuid4\n            )\n            text: Mapped[str] = mapped_column(sqlalchemy.String)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvecto_rs.html"}
{"id": "c03189824e43-1", "text": ")\n            text: Mapped[str] = mapped_column(sqlalchemy.String)\n            meta: Mapped[dict] = mapped_column(postgresql.JSONB)\n            embedding: Mapped[np.ndarray] = mapped_column(Vector(dimension))\n        self._engine = sqlalchemy.create_engine(db_url)\n        self._table = _Table\n        self._table.__table__.create(self._engine, checkfirst=not new_table)  # type: ignore\n        self._embedding = embedding\n    # ================ Create interface =================\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        db_url: str = \"\",\n        collection_name: str = str(uuid.uuid4().hex),\n        **kwargs: Any,\n    ) -> PGVecto_rs:\n        \"\"\"Return VectorStore initialized from texts and optional metadatas.\"\"\"\n        sample_embedding = embedding.embed_query(\"Hello pgvecto_rs!\")\n        dimension = len(sample_embedding)\n        if db_url is None:\n            raise ValueError(\"db_url must be provided\")\n        _self: PGVecto_rs = cls(\n            embedding=embedding,\n            dimension=dimension,\n            db_url=db_url,\n            collection_name=collection_name,\n            new_table=True,\n        )\n        _self.add_texts(texts, metadatas, **kwargs)\n        return _self\n[docs]    @classmethod\n    def from_documents(\n        cls,\n        documents: List[Document],\n        embedding: Embeddings,\n        db_url: str = \"\",\n        collection_name: str = str(uuid.uuid4().hex),\n        **kwargs: Any,\n    ) -> PGVecto_rs:\n        \"\"\"Return VectorStore initialized from documents.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvecto_rs.html"}
{"id": "c03189824e43-2", "text": ") -> PGVecto_rs:\n        \"\"\"Return VectorStore initialized from documents.\"\"\"\n        texts = [document.page_content for document in documents]\n        metadatas = [document.metadata for document in documents]\n        return cls.from_texts(\n            texts, embedding, metadatas, db_url, collection_name, **kwargs\n        )\n[docs]    @classmethod\n    def from_collection_name(\n        cls,\n        embedding: Embeddings,\n        db_url: str,\n        collection_name: str,\n    ) -> PGVecto_rs:\n        \"\"\"Create new empty vectorstore with collection_name.\n        Or connect to an existing vectorstore in database if exists.\n        Arguments should be the same as when the vectorstore was created.\"\"\"\n        sample_embedding = embedding.embed_query(\"Hello pgvecto_rs!\")\n        return cls(\n            embedding=embedding,\n            dimension=len(sample_embedding),\n            db_url=db_url,\n            collection_name=collection_name,\n        )\n    # ================ Insert interface =================\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        Returns:\n            List of ids of the added texts.\n        \"\"\"\n        embeddings = self._embedding.embed_documents(list(texts))\n        with Session(self._engine) as _session:\n            results: List[str] = []\n            for text, embedding, metadata in zip(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvecto_rs.html"}
{"id": "c03189824e43-3", "text": "results: List[str] = []\n            for text, embedding, metadata in zip(\n                texts, embeddings, metadatas or [dict()] * len(list(texts))\n            ):\n                t = insert(self._table).values(\n                    text=text, meta=metadata, embedding=embedding\n                )\n                id = _session.execute(t).inserted_primary_key[0]  # type: ignore\n                results.append(str(id))\n            _session.commit()\n            return results\n[docs]    def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]:\n        \"\"\"Run more documents through the embeddings and add to the vectorstore.\n        Args:\n            documents (List[Document]): List of documents to add to the vectorstore.\n        Returns:\n            List of ids of the added documents.\n        \"\"\"\n        return self.add_texts(\n            [document.page_content for document in documents],\n            [document.metadata for document in documents],\n            **kwargs,\n        )\n    # ================ Query interface =================\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        query_vector: List[float],\n        k: int = 4,\n        distance_func: Literal[\n            \"sqrt_euclid\", \"neg_dot_prod\", \"ned_cos\"\n        ] = \"sqrt_euclid\",\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query vector, with its score.\"\"\"\n        with Session(self._engine) as _session:\n            real_distance_func = (\n                self._table.embedding.squared_euclidean_distance\n                if distance_func == \"sqrt_euclid\"\n                else self._table.embedding.negative_dot_product_distance\n                if distance_func == \"neg_dot_prod\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvecto_rs.html"}
{"id": "c03189824e43-4", "text": "if distance_func == \"neg_dot_prod\"\n                else self._table.embedding.negative_cosine_distance\n                if distance_func == \"ned_cos\"\n                else None\n            )\n            if real_distance_func is None:\n                raise ValueError(\"Invalid distance function\")\n            t = (\n                select(self._table, real_distance_func(query_vector).label(\"score\"))\n                .order_by(\"score\")\n                .limit(k)  # type: ignore\n            )\n            return [\n                (Document(page_content=row[0].text, metadata=row[0].meta), row[1])\n                for row in _session.execute(t)\n            ]\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        distance_func: Literal[\n            \"sqrt_euclid\", \"neg_dot_prod\", \"ned_cos\"\n        ] = \"sqrt_euclid\",\n        **kwargs: Any,\n    ) -> List[Document]:\n        return [\n            doc\n            for doc, score in self.similarity_search_with_score_by_vector(\n                embedding, k, distance_func, **kwargs\n            )\n        ]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        distance_func: Literal[\n            \"sqrt_euclid\", \"neg_dot_prod\", \"ned_cos\"\n        ] = \"sqrt_euclid\",\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        query_vector = self._embedding.embed_query(query)\n        return self.similarity_search_with_score_by_vector(\n            query_vector, k, distance_func, **kwargs\n        )\n[docs]    def similarity_search(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvecto_rs.html"}
{"id": "c03189824e43-5", "text": ")\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        distance_func: Literal[\n            \"sqrt_euclid\", \"neg_dot_prod\", \"ned_cos\"\n        ] = \"sqrt_euclid\",\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\"\"\"\n        query_vector = self._embedding.embed_query(query)\n        return [\n            doc\n            for doc, score in self.similarity_search_with_score_by_vector(\n                query_vector, k, distance_func, **kwargs\n            )\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvecto_rs.html"}
{"id": "d29ff38a3a7c-0", "text": "Source code for langchain.vectorstores.elastic_vector_search\nfrom __future__ import annotations\nimport uuid\nimport warnings\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Dict,\n    Iterable,\n    List,\n    Mapping,\n    Optional,\n    Tuple,\n    Union,\n)\nfrom langchain._api import deprecated\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_dict_or_env\nif TYPE_CHECKING:\n    from elasticsearch import Elasticsearch\ndef _default_text_mapping(dim: int) -> Dict:\n    return {\n        \"properties\": {\n            \"text\": {\"type\": \"text\"},\n            \"vector\": {\"type\": \"dense_vector\", \"dims\": dim},\n        }\n    }\ndef _default_script_query(query_vector: List[float], filter: Optional[dict]) -> Dict:\n    if filter:\n        ((key, value),) = filter.items()\n        filter = {\"match\": {f\"metadata.{key}.keyword\": f\"{value}\"}}\n    else:\n        filter = {\"match_all\": {}}\n    return {\n        \"script_score\": {\n            \"query\": filter,\n            \"script\": {\n                \"source\": \"cosineSimilarity(params.query_vector, 'vector') + 1.0\",\n                \"params\": {\"query_vector\": query_vector},\n            },\n        }\n    }\n[docs]class ElasticVectorSearch(VectorStore):\n    \"\"\"\n    ElasticVectorSearch uses the brute force method of searching on vectors.\n    Recommended to use ElasticsearchStore instead, which gives you the option\n    to uses the approx  HNSW algorithm which performs better on large datasets.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-1", "text": "to uses the approx  HNSW algorithm which performs better on large datasets.\n    ElasticsearchStore also supports metadata filtering, customising the\n    query retriever and much more!\n    You can read more on ElasticsearchStore:\n    https://python.langchain.com/docs/integrations/vectorstores/elasticsearch\n    To connect to an `Elasticsearch` instance that does not require\n    login credentials, pass the Elasticsearch URL and index name along with the\n    embedding object to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import ElasticVectorSearch\n            from langchain.embeddings import OpenAIEmbeddings\n            embedding = OpenAIEmbeddings()\n            elastic_vector_search = ElasticVectorSearch(\n                elasticsearch_url=\"http://localhost:9200\",\n                index_name=\"test_index\",\n                embedding=embedding\n            )\n    To connect to an Elasticsearch instance that requires login credentials,\n    including Elastic Cloud, use the Elasticsearch URL format\n    https://username:password@es_host:9243. For example, to connect to Elastic\n    Cloud, create the Elasticsearch URL with the required authentication details and\n    pass it to the ElasticVectorSearch constructor as the named parameter\n    elasticsearch_url.\n    You can obtain your Elastic Cloud URL and login credentials by logging in to the\n    Elastic Cloud console at https://cloud.elastic.co, selecting your deployment, and\n    navigating to the \"Deployments\" page.\n    To obtain your Elastic Cloud password for the default \"elastic\" user:\n    1. Log in to the Elastic Cloud console at https://cloud.elastic.co\n    2. Go to \"Security\" > \"Users\"\n    3. Locate the \"elastic\" user and click \"Edit\"\n    4. Click \"Reset password\"\n    5. Follow the prompts to reset the password", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-2", "text": "5. Follow the prompts to reset the password\n    The format for Elastic Cloud URLs is\n    https://username:password@cluster_id.region_id.gcp.cloud.es.io:9243.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import ElasticVectorSearch\n            from langchain.embeddings import OpenAIEmbeddings\n            embedding = OpenAIEmbeddings()\n            elastic_host = \"cluster_id.region_id.gcp.cloud.es.io\"\n            elasticsearch_url = f\"https://username:password@{elastic_host}:9243\"\n            elastic_vector_search = ElasticVectorSearch(\n                elasticsearch_url=elasticsearch_url,\n                index_name=\"test_index\",\n                embedding=embedding\n            )\n    Args:\n        elasticsearch_url (str): The URL for the Elasticsearch instance.\n        index_name (str): The name of the Elasticsearch index for the embeddings.\n        embedding (Embeddings): An object that provides the ability to embed text.\n                It should be an instance of a class that subclasses the Embeddings\n                abstract base class, such as OpenAIEmbeddings()\n    Raises:\n        ValueError: If the elasticsearch python package is not installed.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        elasticsearch_url: str,\n        index_name: str,\n        embedding: Embeddings,\n        *,\n        ssl_verify: Optional[Dict[str, Any]] = None,\n    ):\n        \"\"\"Initialize with necessary components.\"\"\"\n        warnings.warn(\n            \"ElasticVectorSearch will be removed in a future release. See\"\n            \"Elasticsearch integration docs on how to upgrade.\"\n        )\n        try:\n            import elasticsearch\n        except ImportError:\n            raise ImportError(\n                \"Could not import elasticsearch python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-3", "text": "raise ImportError(\n                \"Could not import elasticsearch python package. \"\n                \"Please install it with `pip install elasticsearch`.\"\n            )\n        self.embedding = embedding\n        self.index_name = index_name\n        _ssl_verify = ssl_verify or {}\n        try:\n            self.client = elasticsearch.Elasticsearch(\n                elasticsearch_url,\n                **_ssl_verify,\n                headers={\"user-agent\": self.get_user_agent()},\n            )\n        except ValueError as e:\n            raise ValueError(\n                f\"Your elasticsearch client string is mis-formatted. Got error: {e} \"\n            )\n[docs]    @staticmethod\n    def get_user_agent() -> str:\n        from langchain import __version__\n        return f\"langchain-py-dvs/{__version__}\"\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        refresh_indices: bool = True,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of unique IDs.\n            refresh_indices: bool to refresh ElasticSearch indices\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        try:\n            from elasticsearch.exceptions import NotFoundError\n            from elasticsearch.helpers import bulk\n        except ImportError:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-4", "text": "from elasticsearch.helpers import bulk\n        except ImportError:\n            raise ImportError(\n                \"Could not import elasticsearch python package. \"\n                \"Please install it with `pip install elasticsearch`.\"\n            )\n        requests = []\n        ids = ids or [str(uuid.uuid4()) for _ in texts]\n        embeddings = self.embedding.embed_documents(list(texts))\n        dim = len(embeddings[0])\n        mapping = _default_text_mapping(dim)\n        # check to see if the index already exists\n        try:\n            self.client.indices.get(index=self.index_name)\n        except NotFoundError:\n            # TODO would be nice to create index before embedding,\n            # just to save expensive steps for last\n            self.create_index(self.client, self.index_name, mapping)\n        for i, text in enumerate(texts):\n            metadata = metadatas[i] if metadatas else {}\n            request = {\n                \"_op_type\": \"index\",\n                \"_index\": self.index_name,\n                \"vector\": embeddings[i],\n                \"text\": text,\n                \"metadata\": metadata,\n                \"_id\": ids[i],\n            }\n            requests.append(request)\n        bulk(self.client, requests)\n        if refresh_indices:\n            self.client.indices.refresh(index=self.index_name)\n        return ids\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-5", "text": "Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(query, k, filter=filter)\n        documents = [d[0] for d in docs_and_scores]\n        return documents\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        embedding = self.embedding.embed_query(query)\n        script_query = _default_script_query(embedding, filter)\n        response = self.client_search(\n            self.client, self.index_name, script_query, size=k\n        )\n        hits = [hit for hit in response[\"hits\"][\"hits\"]]\n        docs_and_scores = [\n            (\n                Document(\n                    page_content=hit[\"_source\"][\"text\"],\n                    metadata=hit[\"_source\"][\"metadata\"],\n                ),\n                hit[\"_score\"],\n            )\n            for hit in hits\n        ]\n        return docs_and_scores\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        index_name: Optional[str] = None,\n        refresh_indices: bool = True,\n        **kwargs: Any,\n    ) -> ElasticVectorSearch:\n        \"\"\"Construct ElasticVectorSearch wrapper from raw documents.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-6", "text": ") -> ElasticVectorSearch:\n        \"\"\"Construct ElasticVectorSearch wrapper from raw documents.\n        This is a user-friendly interface that:\n            1. Embeds documents.\n            2. Creates a new index for the embeddings in the Elasticsearch instance.\n            3. Adds the documents to the newly created Elasticsearch index.\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import ElasticVectorSearch\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                elastic_vector_search = ElasticVectorSearch.from_texts(\n                    texts,\n                    embeddings,\n                    elasticsearch_url=\"http://localhost:9200\"\n                )\n        \"\"\"\n        elasticsearch_url = get_from_dict_or_env(\n            kwargs, \"elasticsearch_url\", \"ELASTICSEARCH_URL\"\n        )\n        if \"elasticsearch_url\" in kwargs:\n            del kwargs[\"elasticsearch_url\"]\n        index_name = index_name or uuid.uuid4().hex\n        vectorsearch = cls(elasticsearch_url, index_name, embedding, **kwargs)\n        vectorsearch.add_texts(\n            texts, metadatas=metadatas, ids=ids, refresh_indices=refresh_indices\n        )\n        return vectorsearch\n[docs]    def create_index(self, client: Any, index_name: str, mapping: Dict) -> None:\n        version_num = client.info()[\"version\"][\"number\"][0]\n        version_num = int(version_num)\n        if version_num >= 8:\n            client.indices.create(index=index_name, mappings=mapping)\n        else:\n            client.indices.create(index=index_name, body={\"mappings\": mapping})\n[docs]    def client_search(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-7", "text": "[docs]    def client_search(\n        self, client: Any, index_name: str, script_query: Dict, size: int\n    ) -> Any:\n        version_num = client.info()[\"version\"][\"number\"][0]\n        version_num = int(version_num)\n        if version_num >= 8:\n            response = client.search(index=index_name, query=script_query, size=size)\n        else:\n            response = client.search(\n                index=index_name, body={\"query\": script_query, \"size\": size}\n            )\n        return response\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None:\n        \"\"\"Delete by vector IDs.\n        Args:\n            ids: List of ids to delete.\n        \"\"\"\n        if ids is None:\n            raise ValueError(\"No ids provided to delete.\")\n        # TODO: Check if this can be done in bulk\n        for id in ids:\n            self.client.delete(index=self.index_name, id=id)\n[docs]@deprecated(\"0.0.265\", alternative=\"ElasticsearchStore class.\", pending=True)\nclass ElasticKnnSearch(VectorStore):\n    \"\"\"[DEPRECATED] `Elasticsearch` with k-nearest neighbor search\n    (`k-NN`) vector store.\n    Recommended to use ElasticsearchStore instead, which supports\n    metadata filtering, customising the query retriever and much more!\n    You can read more on ElasticsearchStore:\n    https://python.langchain.com/docs/integrations/vectorstores/elasticsearch\n    It creates an Elasticsearch index of text data that\n    can be searched using k-NN search. The text data is transformed into\n    vector embeddings using a provided embedding model, and these embeddings\n    are stored in the Elasticsearch index.\n    Attributes:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-8", "text": "are stored in the Elasticsearch index.\n    Attributes:\n        index_name (str): The name of the Elasticsearch index.\n        embedding (Embeddings): The embedding model to use for transforming text data\n            into vector embeddings.\n        es_connection (Elasticsearch, optional): An existing Elasticsearch connection.\n        es_cloud_id (str, optional): The Cloud ID of your Elasticsearch Service\n            deployment.\n        es_user (str, optional): The username for your Elasticsearch Service deployment.\n        es_password (str, optional): The password for your Elasticsearch Service\n            deployment.\n        vector_query_field (str, optional): The name of the field in the Elasticsearch\n            index that contains the vector embeddings.\n        query_field (str, optional): The name of the field in the Elasticsearch index\n            that contains the original text data.\n    Usage:\n        >>> from embeddings import Embeddings\n        >>> embedding = Embeddings.load('glove')\n        >>> es_search = ElasticKnnSearch('my_index', embedding)\n        >>> es_search.add_texts(['Hello world!', 'Another text'])\n        >>> results = es_search.knn_search('Hello')\n        [(Document(page_content='Hello world!', metadata={}), 0.9)]\n    \"\"\"\n[docs]    def __init__(\n        self,\n        index_name: str,\n        embedding: Embeddings,\n        es_connection: Optional[\"Elasticsearch\"] = None,\n        es_cloud_id: Optional[str] = None,\n        es_user: Optional[str] = None,\n        es_password: Optional[str] = None,\n        vector_query_field: Optional[str] = \"vector\",\n        query_field: Optional[str] = \"text\",\n    ):\n        try:\n            import elasticsearch\n        except ImportError:\n            raise ImportError(\n                \"Could not import elasticsearch python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-9", "text": "raise ImportError(\n                \"Could not import elasticsearch python package. \"\n                \"Please install it with `pip install elasticsearch`.\"\n            )\n        warnings.warn(\n            \"ElasticKnnSearch will be removed in a future release.\"\n            \"Use ElasticsearchStore instead. See Elasticsearch \"\n            \"integration docs on how to upgrade.\"\n        )\n        self.embedding = embedding\n        self.index_name = index_name\n        self.query_field = query_field\n        self.vector_query_field = vector_query_field\n        # If a pre-existing Elasticsearch connection is provided, use it.\n        if es_connection is not None:\n            self.client = es_connection\n        else:\n            # If credentials for a new Elasticsearch connection are provided,\n            # create a new connection.\n            if es_cloud_id and es_user and es_password:\n                self.client = elasticsearch.Elasticsearch(\n                    cloud_id=es_cloud_id, basic_auth=(es_user, es_password)\n                )\n            else:\n                raise ValueError(\n                    \"\"\"Either provide a pre-existing Elasticsearch connection, \\\n                or valid credentials for creating a new connection.\"\"\"\n                )\n    @staticmethod\n    def _default_knn_mapping(\n        dims: int, similarity: Optional[str] = \"dot_product\"\n    ) -> Dict:\n        return {\n            \"properties\": {\n                \"text\": {\"type\": \"text\"},\n                \"vector\": {\n                    \"type\": \"dense_vector\",\n                    \"dims\": dims,\n                    \"index\": True,\n                    \"similarity\": similarity,\n                },\n            }\n        }\n    def _default_knn_query(\n        self,\n        query_vector: Optional[List[float]] = None,\n        query: Optional[str] = None,\n        model_id: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-10", "text": "model_id: Optional[str] = None,\n        k: Optional[int] = 10,\n        num_candidates: Optional[int] = 10,\n    ) -> Dict:\n        knn: Dict = {\n            \"field\": self.vector_query_field,\n            \"k\": k,\n            \"num_candidates\": num_candidates,\n        }\n        # Case 1: `query_vector` is provided, but not `model_id` -> use query_vector\n        if query_vector and not model_id:\n            knn[\"query_vector\"] = query_vector\n        # Case 2: `query` and `model_id` are provided, -> use query_vector_builder\n        elif query and model_id:\n            knn[\"query_vector_builder\"] = {\n                \"text_embedding\": {\n                    \"model_id\": model_id,  # use 'model_id' argument\n                    \"model_text\": query,  # use 'query' argument\n                }\n            }\n        else:\n            raise ValueError(\n                \"Either `query_vector` or `model_id` must be provided, but not both.\"\n            )\n        return knn\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"\n        Pass through to `knn_search`\n        \"\"\"\n        results = self.knn_search(query=query, k=k, **kwargs)\n        return [doc for doc, score in results]\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 10, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Pass through to `knn_search including score`\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-11", "text": "\"\"\"Pass through to `knn_search including score`\"\"\"\n        return self.knn_search(query=query, k=k, **kwargs)\n[docs]    def knn_search(\n        self,\n        query: Optional[str] = None,\n        k: Optional[int] = 10,\n        query_vector: Optional[List[float]] = None,\n        model_id: Optional[str] = None,\n        size: Optional[int] = 10,\n        source: Optional[bool] = True,\n        fields: Optional[\n            Union[List[Mapping[str, Any]], Tuple[Mapping[str, Any], ...], None]\n        ] = None,\n        page_content: Optional[str] = \"text\",\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Perform a k-NN search on the Elasticsearch index.\n        Args:\n            query (str, optional): The query text to search for.\n            k (int, optional): The number of nearest neighbors to return.\n            query_vector (List[float], optional): The query vector to search for.\n            model_id (str, optional): The ID of the model to use for transforming the\n                query text into a vector.\n            size (int, optional): The number of search results to return.\n            source (bool, optional): Whether to return the source of the search results.\n            fields (List[Mapping[str, Any]], optional): The fields to return in the\n                search results.\n            page_content (str, optional): The name of the field that contains the page\n                content.\n        Returns:\n            A list of tuples, where each tuple contains a Document object and a score.\n        \"\"\"\n        # if not source and (fields == None or page_content not in fields):\n        if not source and (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-12", "text": "if not source and (\n            fields is None or not any(page_content in field for field in fields)\n        ):\n            raise ValueError(\"If source=False `page_content` field must be in `fields`\")\n        knn_query_body = self._default_knn_query(\n            query_vector=query_vector, query=query, model_id=model_id, k=k\n        )\n        # Perform the kNN search on the Elasticsearch index and return the results.\n        response = self.client.search(\n            index=self.index_name,\n            knn=knn_query_body,\n            size=size,\n            source=source,\n            fields=fields,\n        )\n        hits = [hit for hit in response[\"hits\"][\"hits\"]]\n        docs_and_scores = [\n            (\n                Document(\n                    page_content=hit[\"_source\"][page_content]\n                    if source\n                    else hit[\"fields\"][page_content][0],\n                    metadata=hit[\"fields\"] if fields else {},\n                ),\n                hit[\"_score\"],\n            )\n            for hit in hits\n        ]\n        return docs_and_scores\n[docs]    def knn_hybrid_search(\n        self,\n        query: Optional[str] = None,\n        k: Optional[int] = 10,\n        query_vector: Optional[List[float]] = None,\n        model_id: Optional[str] = None,\n        size: Optional[int] = 10,\n        source: Optional[bool] = True,\n        knn_boost: Optional[float] = 0.9,\n        query_boost: Optional[float] = 0.1,\n        fields: Optional[\n            Union[List[Mapping[str, Any]], Tuple[Mapping[str, Any], ...], None]\n        ] = None,\n        page_content: Optional[str] = \"text\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-13", "text": "] = None,\n        page_content: Optional[str] = \"text\",\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Perform a hybrid k-NN and text search on the Elasticsearch index.\n        Args:\n            query (str, optional): The query text to search for.\n            k (int, optional): The number of nearest neighbors to return.\n            query_vector (List[float], optional): The query vector to search for.\n            model_id (str, optional): The ID of the model to use for transforming the\n                query text into a vector.\n            size (int, optional): The number of search results to return.\n            source (bool, optional): Whether to return the source of the search results.\n            knn_boost (float, optional): The boost value to apply to the k-NN search\n                results.\n            query_boost (float, optional): The boost value to apply to the text search\n                results.\n            fields (List[Mapping[str, Any]], optional): The fields to return in the\n                search results.\n            page_content (str, optional): The name of the field that contains the page\n                content.\n        Returns:\n            A list of tuples, where each tuple contains a Document object and a score.\n        \"\"\"\n        # if not source and (fields == None or page_content not in fields):\n        if not source and (\n            fields is None or not any(page_content in field for field in fields)\n        ):\n            raise ValueError(\"If source=False `page_content` field must be in `fields`\")\n        knn_query_body = self._default_knn_query(\n            query_vector=query_vector, query=query, model_id=model_id, k=k\n        )\n        # Modify the knn_query_body to add a \"boost\" parameter", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-14", "text": ")\n        # Modify the knn_query_body to add a \"boost\" parameter\n        knn_query_body[\"boost\"] = knn_boost\n        # Generate the body of the standard Elasticsearch query\n        match_query_body = {\n            \"match\": {self.query_field: {\"query\": query, \"boost\": query_boost}}\n        }\n        # Perform the hybrid search on the Elasticsearch index and return the results.\n        response = self.client.search(\n            index=self.index_name,\n            query=match_query_body,\n            knn=knn_query_body,\n            fields=fields,\n            size=size,\n            source=source,\n        )\n        hits = [hit for hit in response[\"hits\"][\"hits\"]]\n        docs_and_scores = [\n            (\n                Document(\n                    page_content=hit[\"_source\"][page_content]\n                    if source\n                    else hit[\"fields\"][page_content][0],\n                    metadata=hit[\"fields\"] if fields else {},\n                ),\n                hit[\"_score\"],\n            )\n            for hit in hits\n        ]\n        return docs_and_scores\n[docs]    def create_knn_index(self, mapping: Dict) -> None:\n        \"\"\"\n        Create a new k-NN index in Elasticsearch.\n        Args:\n            mapping (Dict): The mapping to use for the new index.\n        Returns:\n            None\n        \"\"\"\n        self.client.indices.create(index=self.index_name, mappings=mapping)\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[Dict[Any, Any]]] = None,\n        model_id: Optional[str] = None,\n        refresh_indices: bool = False,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-15", "text": "**kwargs: Any,\n    ) -> List[str]:\n        \"\"\"\n        Add a list of texts to the Elasticsearch index.\n        Args:\n            texts (Iterable[str]): The texts to add to the index.\n            metadatas (List[Dict[Any, Any]], optional): A list of metadata dictionaries\n                to associate with the texts.\n            model_id (str, optional): The ID of the model to use for transforming the\n                texts into vectors.\n            refresh_indices (bool, optional): Whether to refresh the Elasticsearch\n                indices after adding the texts.\n            **kwargs: Arbitrary keyword arguments.\n        Returns:\n            A list of IDs for the added texts.\n        \"\"\"\n        # Check if the index exists.\n        if not self.client.indices.exists(index=self.index_name):\n            dims = kwargs.get(\"dims\")\n            if dims is None:\n                raise ValueError(\"ElasticKnnSearch requires 'dims' parameter\")\n            similarity = kwargs.get(\"similarity\")\n            optional_args = {}\n            if similarity is not None:\n                optional_args[\"similarity\"] = similarity\n            mapping = self._default_knn_mapping(dims=dims, **optional_args)\n            self.create_knn_index(mapping)\n        embeddings = self.embedding.embed_documents(list(texts))\n        # body = []\n        body: List[Mapping[str, Any]] = []\n        for text, vector in zip(texts, embeddings):\n            body.extend(\n                [\n                    {\"index\": {\"_index\": self.index_name}},\n                    {\"text\": text, \"vector\": vector},\n                ]\n            )\n        responses = self.client.bulk(operations=body)\n        ids = [\n            item[\"index\"][\"_id\"]\n            for item in responses[\"items\"]\n            if item[\"index\"][\"result\"] == \"created\"\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-16", "text": "if item[\"index\"][\"result\"] == \"created\"\n        ]\n        if refresh_indices:\n            self.client.indices.refresh(index=self.index_name)\n        return ids\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[Dict[Any, Any]]] = None,\n        **kwargs: Any,\n    ) -> ElasticKnnSearch:\n        \"\"\"\n        Create a new ElasticKnnSearch instance and add a list of texts to the\n            Elasticsearch index.\n        Args:\n            texts (List[str]): The texts to add to the index.\n            embedding (Embeddings): The embedding model to use for transforming the\n                texts into vectors.\n            metadatas (List[Dict[Any, Any]], optional): A list of metadata dictionaries\n                to associate with the texts.\n            **kwargs: Arbitrary keyword arguments.\n        Returns:\n            A new ElasticKnnSearch instance.\n        \"\"\"\n        index_name = kwargs.get(\"index_name\", str(uuid.uuid4()))\n        es_connection = kwargs.get(\"es_connection\")\n        es_cloud_id = kwargs.get(\"es_cloud_id\")\n        es_user = kwargs.get(\"es_user\")\n        es_password = kwargs.get(\"es_password\")\n        vector_query_field = kwargs.get(\"vector_query_field\", \"vector\")\n        query_field = kwargs.get(\"query_field\", \"text\")\n        model_id = kwargs.get(\"model_id\")\n        dims = kwargs.get(\"dims\")\n        if dims is None:\n            raise ValueError(\"ElasticKnnSearch requires 'dims' parameter\")\n        optional_args = {}\n        if vector_query_field is not None:\n            optional_args[\"vector_query_field\"] = vector_query_field\n        if query_field is not None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "d29ff38a3a7c-17", "text": "if query_field is not None:\n            optional_args[\"query_field\"] = query_field\n        knnvectorsearch = cls(\n            index_name=index_name,\n            embedding=embedding,\n            es_connection=es_connection,\n            es_cloud_id=es_cloud_id,\n            es_user=es_user,\n            es_password=es_password,\n            **optional_args,\n        )\n        # Encode the provided texts and add them to the newly created index.\n        knnvectorsearch.add_texts(texts, model_id=model_id, dims=dims, **optional_args)\n        return knnvectorsearch", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html"}
{"id": "19aa06699be3-0", "text": "Source code for langchain.vectorstores.zilliz\nfrom __future__ import annotations\nimport logging\nfrom typing import Any, Dict, List, Optional\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.vectorstores.milvus import Milvus\nlogger = logging.getLogger(__name__)\n[docs]class Zilliz(Milvus):\n    \"\"\"`Zilliz` vector store.\n    You need to have `pymilvus` installed and a\n    running Zilliz database.\n    See the following documentation for how to run a Zilliz instance:\n    https://docs.zilliz.com/docs/create-cluster\n    IF USING L2/IP metric IT IS HIGHLY SUGGESTED TO NORMALIZE YOUR DATA.\n    Args:\n        embedding_function (Embeddings): Function used to embed the text.\n        collection_name (str): Which Zilliz collection to use. Defaults to\n            \"LangChainCollection\".\n        connection_args (Optional[dict[str, any]]): The connection args used for\n            this class comes in the form of a dict.\n        consistency_level (str): The consistency level to use for a collection.\n            Defaults to \"Session\".\n        index_params (Optional[dict]): Which index params to use. Defaults to\n            HNSW/AUTOINDEX depending on service.\n        search_params (Optional[dict]): Which search params to use. Defaults to\n            default of index.\n        drop_old (Optional[bool]): Whether to drop the current collection. Defaults\n            to False.\n    The connection args used for this class comes in the form of a dict,\n    here are a few of the options:\n        address (str): The actual address of Zilliz\n            instance. Example address: \"localhost:19530\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html"}
{"id": "19aa06699be3-1", "text": "instance. Example address: \"localhost:19530\"\n        uri (str): The uri of Zilliz instance. Example uri:\n            \"https://in03-ba4234asae.api.gcp-us-west1.zillizcloud.com\",\n        host (str): The host of Zilliz instance. Default at \"localhost\",\n            PyMilvus will fill in the default host if only port is provided.\n        port (str/int): The port of Zilliz instance. Default at 19530, PyMilvus\n            will fill in the default port if only host is provided.\n        user (str): Use which user to connect to Zilliz instance. If user and\n            password are provided, we will add related header in every RPC call.\n        password (str): Required when user is provided. The password\n            corresponding to the user.\n        token (str): API key, for serverless clusters which can be used as\n            replacements for user and password.\n        secure (bool): Default is false. If set to true, tls will be enabled.\n        client_key_path (str): If use tls two-way authentication, need to\n            write the client.key path.\n        client_pem_path (str): If use tls two-way authentication, need to\n            write the client.pem path.\n        ca_pem_path (str): If use tls two-way authentication, need to write\n            the ca.pem path.\n        server_pem_path (str): If use tls one-way authentication, need to\n            write the server.pem path.\n        server_name (str): If use tls, need to write the common name.\n    Example:\n        .. code-block:: python\n        from langchain.vectorstores import Zilliz\n        from langchain.embeddings import OpenAIEmbeddings\n        embedding = OpenAIEmbeddings()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html"}
{"id": "19aa06699be3-2", "text": "embedding = OpenAIEmbeddings()\n        # Connect to a Zilliz instance\n        milvus_store = Milvus(\n            embedding_function = embedding,\n            collection_name = \"LangChainCollection\",\n            connection_args = {\n                \"uri\": \"https://in03-ba4234asae.api.gcp-us-west1.zillizcloud.com\",\n                \"user\": \"temp\",\n                \"password\": \"temp\",\n                \"token\": \"temp\", # API key as replacements for user and password\n                \"secure\": True\n            }\n            drop_old: True,\n        )\n    Raises:\n        ValueError: If the pymilvus python package is not installed.\n    \"\"\"\n    def _create_index(self) -> None:\n        \"\"\"Create a index on the collection\"\"\"\n        from pymilvus import Collection, MilvusException\n        if isinstance(self.col, Collection) and self._get_index() is None:\n            try:\n                # If no index params, use a default AutoIndex based one\n                if self.index_params is None:\n                    self.index_params = {\n                        \"metric_type\": \"L2\",\n                        \"index_type\": \"AUTOINDEX\",\n                        \"params\": {},\n                    }\n                try:\n                    self.col.create_index(\n                        self._vector_field,\n                        index_params=self.index_params,\n                        using=self.alias,\n                    )\n                # If default did not work, most likely Milvus self-hosted\n                except MilvusException:\n                    # Use HNSW based index\n                    self.index_params = {\n                        \"metric_type\": \"L2\",\n                        \"index_type\": \"HNSW\",\n                        \"params\": {\"M\": 8, \"efConstruction\": 64},\n                    }\n                    self.col.create_index(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html"}
{"id": "19aa06699be3-3", "text": "}\n                    self.col.create_index(\n                        self._vector_field,\n                        index_params=self.index_params,\n                        using=self.alias,\n                    )\n                logger.debug(\n                    \"Successfully created an index on collection: %s\",\n                    self.collection_name,\n                )\n            except MilvusException as e:\n                logger.error(\n                    \"Failed to create an index on collection: %s\", self.collection_name\n                )\n                raise e\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        collection_name: str = \"LangChainCollection\",\n        connection_args: Optional[Dict[str, Any]] = None,\n        consistency_level: str = \"Session\",\n        index_params: Optional[dict] = None,\n        search_params: Optional[dict] = None,\n        drop_old: bool = False,\n        **kwargs: Any,\n    ) -> Zilliz:\n        \"\"\"Create a Zilliz collection, indexes it with HNSW, and insert data.\n        Args:\n            texts (List[str]): Text data.\n            embedding (Embeddings): Embedding function.\n            metadatas (Optional[List[dict]]): Metadata for each text if it exists.\n                Defaults to None.\n            collection_name (str, optional): Collection name to use. Defaults to\n                \"LangChainCollection\".\n            connection_args (dict[str, Any], optional): Connection args to use. Defaults\n                to DEFAULT_MILVUS_CONNECTION.\n            consistency_level (str, optional): Which consistency level to use. Defaults\n                to \"Session\".\n            index_params (Optional[dict], optional): Which index_params to use.\n                Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html"}
{"id": "19aa06699be3-4", "text": "Defaults to None.\n            search_params (Optional[dict], optional): Which search params to use.\n                Defaults to None.\n            drop_old (Optional[bool], optional): Whether to drop the collection with\n                that name if it exists. Defaults to False.\n        Returns:\n            Zilliz: Zilliz Vector Store\n        \"\"\"\n        vector_db = cls(\n            embedding_function=embedding,\n            collection_name=collection_name,\n            connection_args=connection_args or {},\n            consistency_level=consistency_level,\n            index_params=index_params,\n            search_params=search_params,\n            drop_old=drop_old,\n            **kwargs,\n        )\n        vector_db.add_texts(texts=texts, metadatas=metadatas)\n        return vector_db", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html"}
{"id": "6ab8567287fd-0", "text": "Source code for langchain.vectorstores.sklearn\n\"\"\" Wrapper around scikit-learn NearestNeighbors implementation.\nThe vector store can be persisted in json, bson or parquet format.\n\"\"\"\nimport json\nimport math\nimport os\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Dict, Iterable, List, Literal, Optional, Tuple, Type\nfrom uuid import uuid4\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import guard_import\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nDEFAULT_K = 4  # Number of Documents to return.\nDEFAULT_FETCH_K = 20  # Number of Documents to initially fetch during MMR search.\n[docs]class BaseSerializer(ABC):\n    \"\"\"Base class for serializing data.\"\"\"\n[docs]    def __init__(self, persist_path: str) -> None:\n        self.persist_path = persist_path\n[docs]    @classmethod\n    @abstractmethod\n    def extension(cls) -> str:\n        \"\"\"The file extension suggested by this serializer (without dot).\"\"\"\n[docs]    @abstractmethod\n    def save(self, data: Any) -> None:\n        \"\"\"Saves the data to the persist_path\"\"\"\n[docs]    @abstractmethod\n    def load(self) -> Any:\n        \"\"\"Loads the data from the persist_path\"\"\"\n[docs]class JsonSerializer(BaseSerializer):\n    \"\"\"Serializes data in json using the json package from python standard library.\"\"\"\n[docs]    @classmethod\n    def extension(cls) -> str:\n        return \"json\"\n[docs]    def save(self, data: Any) -> None:\n        with open(self.persist_path, \"w\") as fp:\n            json.dump(data, fp)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html"}
{"id": "6ab8567287fd-1", "text": "json.dump(data, fp)\n[docs]    def load(self) -> Any:\n        with open(self.persist_path, \"r\") as fp:\n            return json.load(fp)\n[docs]class BsonSerializer(BaseSerializer):\n    \"\"\"Serializes data in binary json using the `bson` python package.\"\"\"\n[docs]    def __init__(self, persist_path: str) -> None:\n        super().__init__(persist_path)\n        self.bson = guard_import(\"bson\")\n[docs]    @classmethod\n    def extension(cls) -> str:\n        return \"bson\"\n[docs]    def save(self, data: Any) -> None:\n        with open(self.persist_path, \"wb\") as fp:\n            fp.write(self.bson.dumps(data))\n[docs]    def load(self) -> Any:\n        with open(self.persist_path, \"rb\") as fp:\n            return self.bson.loads(fp.read())\n[docs]class ParquetSerializer(BaseSerializer):\n    \"\"\"Serializes data in `Apache Parquet` format using the `pyarrow` package.\"\"\"\n[docs]    def __init__(self, persist_path: str) -> None:\n        super().__init__(persist_path)\n        self.pd = guard_import(\"pandas\")\n        self.pa = guard_import(\"pyarrow\")\n        self.pq = guard_import(\"pyarrow.parquet\")\n[docs]    @classmethod\n    def extension(cls) -> str:\n        return \"parquet\"\n[docs]    def save(self, data: Any) -> None:\n        df = self.pd.DataFrame(data)\n        table = self.pa.Table.from_pandas(df)\n        if os.path.exists(self.persist_path):\n            backup_path = str(self.persist_path) + \"-backup\"\n            os.rename(self.persist_path, backup_path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html"}
{"id": "6ab8567287fd-2", "text": "os.rename(self.persist_path, backup_path)\n            try:\n                self.pq.write_table(table, self.persist_path)\n            except Exception as exc:\n                os.rename(backup_path, self.persist_path)\n                raise exc\n            else:\n                os.remove(backup_path)\n        else:\n            self.pq.write_table(table, self.persist_path)\n[docs]    def load(self) -> Any:\n        table = self.pq.read_table(self.persist_path)\n        df = table.to_pandas()\n        return {col: series.tolist() for col, series in df.items()}\nSERIALIZER_MAP: Dict[str, Type[BaseSerializer]] = {\n    \"json\": JsonSerializer,\n    \"bson\": BsonSerializer,\n    \"parquet\": ParquetSerializer,\n}\n[docs]class SKLearnVectorStoreException(RuntimeError):\n    \"\"\"Exception raised by SKLearnVectorStore.\"\"\"\n    pass\n[docs]class SKLearnVectorStore(VectorStore):\n    \"\"\"Simple in-memory vector store based on the `scikit-learn` library\n    `NearestNeighbors` implementation.\"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        *,\n        persist_path: Optional[str] = None,\n        serializer: Literal[\"json\", \"bson\", \"parquet\"] = \"json\",\n        metric: str = \"cosine\",\n        **kwargs: Any,\n    ) -> None:\n        np = guard_import(\"numpy\")\n        sklearn_neighbors = guard_import(\"sklearn.neighbors\", pip_name=\"scikit-learn\")\n        # non-persistent properties\n        self._np = np\n        self._neighbors = sklearn_neighbors.NearestNeighbors(metric=metric, **kwargs)\n        self._neighbors_fitted = False\n        self._embedding_function = embedding", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html"}
{"id": "6ab8567287fd-3", "text": "self._neighbors_fitted = False\n        self._embedding_function = embedding\n        self._persist_path = persist_path\n        self._serializer: Optional[BaseSerializer] = None\n        if self._persist_path is not None:\n            serializer_cls = SERIALIZER_MAP[serializer]\n            self._serializer = serializer_cls(persist_path=self._persist_path)\n        # data properties\n        self._embeddings: List[List[float]] = []\n        self._texts: List[str] = []\n        self._metadatas: List[dict] = []\n        self._ids: List[str] = []\n        # cache properties\n        self._embeddings_np: Any = np.asarray([])\n        if self._persist_path is not None and os.path.isfile(self._persist_path):\n            self._load()\n    @property\n    def embeddings(self) -> Embeddings:\n        return self._embedding_function\n[docs]    def persist(self) -> None:\n        if self._serializer is None:\n            raise SKLearnVectorStoreException(\n                \"You must specify a persist_path on creation to persist the \"\n                \"collection.\"\n            )\n        data = {\n            \"ids\": self._ids,\n            \"texts\": self._texts,\n            \"metadatas\": self._metadatas,\n            \"embeddings\": self._embeddings,\n        }\n        self._serializer.save(data)\n    def _load(self) -> None:\n        if self._serializer is None:\n            raise SKLearnVectorStoreException(\n                \"You must specify a persist_path on creation to load the \" \"collection.\"\n            )\n        data = self._serializer.load()\n        self._embeddings = data[\"embeddings\"]\n        self._texts = data[\"texts\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html"}
{"id": "6ab8567287fd-4", "text": "self._texts = data[\"texts\"]\n        self._metadatas = data[\"metadatas\"]\n        self._ids = data[\"ids\"]\n        self._update_neighbors()\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        _texts = list(texts)\n        _ids = ids or [str(uuid4()) for _ in _texts]\n        self._texts.extend(_texts)\n        self._embeddings.extend(self._embedding_function.embed_documents(_texts))\n        self._metadatas.extend(metadatas or ([{}] * len(_texts)))\n        self._ids.extend(_ids)\n        self._update_neighbors()\n        return _ids\n    def _update_neighbors(self) -> None:\n        if len(self._embeddings) == 0:\n            raise SKLearnVectorStoreException(\n                \"No data was added to SKLearnVectorStore.\"\n            )\n        self._embeddings_np = self._np.asarray(self._embeddings)\n        self._neighbors.fit(self._embeddings_np)\n        self._neighbors_fitted = True\n    def _similarity_index_search_with_score(\n        self, query_embedding: List[float], *, k: int = DEFAULT_K, **kwargs: Any\n    ) -> List[Tuple[int, float]]:\n        \"\"\"Search k embeddings similar to the query embedding. Returns a list of\n        (index, distance) tuples.\"\"\"\n        if not self._neighbors_fitted:\n            raise SKLearnVectorStoreException(\n                \"No data was added to SKLearnVectorStore.\"\n            )\n        neigh_dists, neigh_idxs = self._neighbors.kneighbors(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html"}
{"id": "6ab8567287fd-5", "text": ")\n        neigh_dists, neigh_idxs = self._neighbors.kneighbors(\n            [query_embedding], n_neighbors=k\n        )\n        return list(zip(neigh_idxs[0], neigh_dists[0]))\n[docs]    def similarity_search_with_score(\n        self, query: str, *, k: int = DEFAULT_K, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        query_embedding = self._embedding_function.embed_query(query)\n        indices_dists = self._similarity_index_search_with_score(\n            query_embedding, k=k, **kwargs\n        )\n        return [\n            (\n                Document(\n                    page_content=self._texts[idx],\n                    metadata={\"id\": self._ids[idx], **self._metadatas[idx]},\n                ),\n                dist,\n            )\n            for idx, dist in indices_dists\n        ]\n[docs]    def similarity_search(\n        self, query: str, k: int = DEFAULT_K, **kwargs: Any\n    ) -> List[Document]:\n        docs_scores = self.similarity_search_with_score(query, k=k, **kwargs)\n        return [doc for doc, _ in docs_scores]\n    def _similarity_search_with_relevance_scores(\n        self, query: str, k: int = DEFAULT_K, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        docs_dists = self.similarity_search_with_score(query, k=k, **kwargs)\n        docs, dists = zip(*docs_dists)\n        scores = [1 / math.exp(dist) for dist in dists]\n        return list(zip(list(docs), scores))\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html"}
{"id": "6ab8567287fd-6", "text": "self,\n        embedding: List[float],\n        k: int = DEFAULT_K,\n        fetch_k: int = DEFAULT_FETCH_K,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        indices_dists = self._similarity_index_search_with_score(\n            embedding, k=fetch_k, **kwargs\n        )\n        indices, _ = zip(*indices_dists)\n        result_embeddings = self._embeddings_np[indices,]\n        mmr_selected = maximal_marginal_relevance(\n            self._np.array(embedding, dtype=self._np.float32),\n            result_embeddings,\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        mmr_indices = [indices[i] for i in mmr_selected]\n        return [\n            Document(\n                page_content=self._texts[idx],\n                metadata={\"id\": self._ids[idx], **self._metadatas[idx]},\n            )\n            for idx in mmr_indices\n        ]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html"}
{"id": "6ab8567287fd-7", "text": "self,\n        query: str,\n        k: int = DEFAULT_K,\n        fetch_k: int = DEFAULT_FETCH_K,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        if self._embedding_function is None:\n            raise ValueError(\n                \"For MMR search, you must specify an embedding function on creation.\"\n            )\n        embedding = self._embedding_function.embed_query(query)\n        docs = self.max_marginal_relevance_search_by_vector(\n            embedding, k, fetch_k, lambda_mul=lambda_mult\n        )\n        return docs\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        persist_path: Optional[str] = None,\n        **kwargs: Any,\n    ) -> \"SKLearnVectorStore\":\n        vs = SKLearnVectorStore(embedding, persist_path=persist_path, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html"}
{"id": "6ab8567287fd-8", "text": "vs = SKLearnVectorStore(embedding, persist_path=persist_path, **kwargs)\n        vs.add_texts(texts, metadatas=metadatas, ids=ids)\n        return vs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html"}
{"id": "43878bab6695-0", "text": "Source code for langchain.vectorstores.scann\nfrom __future__ import annotations\nimport operator\nimport pickle\nimport uuid\nfrom pathlib import Path\nfrom typing import Any, Callable, Dict, Iterable, List, Optional, Tuple\nimport numpy as np\nfrom langchain.docstore.base import AddableMixin, Docstore\nfrom langchain.docstore.document import Document\nfrom langchain.docstore.in_memory import InMemoryDocstore\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import DistanceStrategy\n[docs]def normalize(x: np.ndarray) -> np.ndarray:\n    \"\"\"Normalize vectors to unit length.\"\"\"\n    x /= np.clip(np.linalg.norm(x, axis=-1, keepdims=True), 1e-12, None)\n    return x\n[docs]def dependable_scann_import() -> Any:\n    \"\"\"\n    Import `scann` if available, otherwise raise error.\n    \"\"\"\n    try:\n        import scann\n    except ImportError:\n        raise ImportError(\n            \"Could not import scann python package. \"\n            \"Please install it with `pip install scann` \"\n        )\n    return scann\n[docs]class ScaNN(VectorStore):\n    \"\"\"`ScaNN` vector store.\n    To use, you should have the ``scann`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import HuggingFaceEmbeddings\n            from langchain.vectorstores import ScaNN\n            db = ScaNN.from_texts(\n                ['foo', 'bar', 'barz', 'qux'],\n                HuggingFaceEmbeddings())\n            db.similarity_search('foo?', k=1)\n    \"\"\"\n[docs]    def __init__(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html"}
{"id": "43878bab6695-1", "text": "\"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        index: Any,\n        docstore: Docstore,\n        index_to_docstore_id: Dict[int, str],\n        relevance_score_fn: Optional[Callable[[float], float]] = None,\n        normalize_L2: bool = False,\n        distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE,\n        scann_config: Optional[str] = None,\n    ):\n        \"\"\"Initialize with necessary components.\"\"\"\n        self.embedding = embedding\n        self.index = index\n        self.docstore = docstore\n        self.index_to_docstore_id = index_to_docstore_id\n        self.distance_strategy = distance_strategy\n        self.override_relevance_score_fn = relevance_score_fn\n        self._normalize_L2 = normalize_L2\n        self._scann_config = scann_config\n    def __add(\n        self,\n        texts: Iterable[str],\n        embeddings: Iterable[List[float]],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        if not isinstance(self.docstore, AddableMixin):\n            raise ValueError(\n                \"If trying to add texts, the underlying docstore should support \"\n                f\"adding items, which {self.docstore} does not\"\n            )\n        raise NotImplementedError(\"Updates are not available in ScaNN, yet.\")\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html"}
{"id": "43878bab6695-2", "text": "**kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of unique IDs.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        # Embed and create the documents.\n        embeddings = self.embedding.embed_documents(list(texts))\n        return self.__add(texts, embeddings, metadatas=metadatas, ids=ids, **kwargs)\n[docs]    def add_embeddings(\n        self,\n        text_embeddings: Iterable[Tuple[str, List[float]]],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            text_embeddings: Iterable pairs of string and embedding to\n                add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of unique IDs.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        if not isinstance(self.docstore, AddableMixin):\n            raise ValueError(\n                \"If trying to add texts, the underlying docstore should support \"\n                f\"adding items, which {self.docstore} does not\"\n            )\n        # Embed and create the documents.\n        texts, embeddings = zip(*text_embeddings)\n        return self.__add(texts, embeddings, metadatas=metadatas, ids=ids, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html"}
{"id": "43878bab6695-3", "text": "[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:\n        \"\"\"Delete by vector ID or other criteria.\n        Args:\n            ids: List of ids to delete.\n            **kwargs: Other keyword arguments that subclasses might use.\n        Returns:\n            Optional[bool]: True if deletion is successful,\n            False otherwise, None if not implemented.\n        \"\"\"\n        raise NotImplementedError(\"Deletions are not available in ScaNN, yet.\")\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            embedding: Embedding vector to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, Any]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n            **kwargs: kwargs to be passed to similarity search. Can include:\n                score_threshold: Optional, a floating point value between 0 to 1 to\n                    filter the resulting set of retrieved docs\n        Returns:\n            List of documents most similar to the query text and L2 distance\n            in float for each. Lower score represents more similarity.\n        \"\"\"\n        vector = np.array([embedding], dtype=np.float32)\n        if self._normalize_L2:\n            vector = normalize(vector)\n        indices, scores = self.index.search_batched(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html"}
{"id": "43878bab6695-4", "text": "vector = normalize(vector)\n        indices, scores = self.index.search_batched(\n            vector, k if filter is None else fetch_k\n        )\n        docs = []\n        for j, i in enumerate(indices[0]):\n            if i == -1:\n                # This happens when not enough docs are returned.\n                continue\n            _id = self.index_to_docstore_id[i]\n            doc = self.docstore.search(_id)\n            if not isinstance(doc, Document):\n                raise ValueError(f\"Could not find document for id {_id}, got {doc}\")\n            if filter is not None:\n                filter = {\n                    key: [value] if not isinstance(value, list) else value\n                    for key, value in filter.items()\n                }\n                if all(doc.metadata.get(key) in value for key, value in filter.items()):\n                    docs.append((doc, scores[0][j]))\n            else:\n                docs.append((doc, scores[0][j]))\n        score_threshold = kwargs.get(\"score_threshold\")\n        if score_threshold is not None:\n            cmp = (\n                operator.ge\n                if self.distance_strategy\n                in (DistanceStrategy.MAX_INNER_PRODUCT, DistanceStrategy.JACCARD)\n                else operator.le\n            )\n            docs = [\n                (doc, similarity)\n                for doc, similarity in docs\n                if cmp(similarity, score_threshold)\n            ]\n        return docs[:k]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html"}
{"id": "43878bab6695-5", "text": "**kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n        Returns:\n            List of documents most similar to the query text with\n            L2 distance in float. Lower score represents more similarity.\n        \"\"\"\n        embedding = self.embedding.embed_query(query)\n        docs = self.similarity_search_with_score_by_vector(\n            embedding,\n            k,\n            filter=filter,\n            fetch_k=fetch_k,\n            **kwargs,\n        )\n        return docs\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n        Returns:\n            List of Documents most similar to the embedding.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score_by_vector(\n            embedding,\n            k,\n            filter=filter,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html"}
{"id": "43878bab6695-6", "text": "embedding,\n            k,\n            filter=filter,\n            fetch_k=fetch_k,\n            **kwargs,\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(\n            query, k, filter=filter, fetch_k=fetch_k, **kwargs\n        )\n        return [doc for doc, _ in docs_and_scores]\n    @classmethod\n    def __from(\n        cls,\n        texts: List[str],\n        embeddings: List[List[float]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        normalize_L2: bool = False,\n        **kwargs: Any,\n    ) -> ScaNN:\n        scann = dependable_scann_import()\n        distance_strategy = kwargs.get(\n            \"distance_strategy\", DistanceStrategy.EUCLIDEAN_DISTANCE\n        )\n        scann_config = kwargs.get(\"scann_config\", None)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html"}
{"id": "43878bab6695-7", "text": ")\n        scann_config = kwargs.get(\"scann_config\", None)\n        vector = np.array(embeddings, dtype=np.float32)\n        if normalize_L2:\n            vector = normalize(vector)\n        if scann_config is not None:\n            index = scann.scann_ops_pybind.create_searcher(vector, scann_config)\n        else:\n            if distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:\n                index = (\n                    scann.scann_ops_pybind.builder(vector, 1, \"dot_product\")\n                    .score_brute_force()\n                    .build()\n                )\n            else:\n                # Default to L2, currently other metric types not initialized.\n                index = (\n                    scann.scann_ops_pybind.builder(vector, 1, \"squared_l2\")\n                    .score_brute_force()\n                    .build()\n                )\n        documents = []\n        if ids is None:\n            ids = [str(uuid.uuid4()) for _ in texts]\n        for i, text in enumerate(texts):\n            metadata = metadatas[i] if metadatas else {}\n            documents.append(Document(page_content=text, metadata=metadata))\n        index_to_id = dict(enumerate(ids))\n        if len(index_to_id) != len(documents):\n            raise Exception(\n                f\"{len(index_to_id)} ids provided for {len(documents)} documents.\"\n                \" Each document should have an id.\"\n            )\n        docstore = InMemoryDocstore(dict(zip(index_to_id.values(), documents)))\n        return cls(\n            embedding,\n            index,\n            docstore,\n            index_to_id,\n            normalize_L2=normalize_L2,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_texts(\n        cls,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html"}
{"id": "43878bab6695-8", "text": ")\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> ScaNN:\n        \"\"\"Construct ScaNN wrapper from raw documents.\n        This is a user friendly interface that:\n            1. Embeds documents.\n            2. Creates an in memory docstore\n            3. Initializes the ScaNN database\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import ScaNN\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                scann = ScaNN.from_texts(texts, embeddings)\n        \"\"\"\n        embeddings = embedding.embed_documents(texts)\n        return cls.__from(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_embeddings(\n        cls,\n        text_embeddings: List[Tuple[str, List[float]]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> ScaNN:\n        \"\"\"Construct ScaNN wrapper from raw documents.\n        This is a user friendly interface that:\n            1. Embeds documents.\n            2. Creates an in memory docstore\n            3. Initializes the ScaNN database\n        This is intended to be a quick way to get started.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html"}
{"id": "43878bab6695-9", "text": "This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import ScaNN\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                text_embeddings = embeddings.embed_documents(texts)\n                text_embedding_pairs = list(zip(texts, text_embeddings))\n                scann = ScaNN.from_embeddings(text_embedding_pairs, embeddings)\n        \"\"\"\n        texts = [t[0] for t in text_embeddings]\n        embeddings = [t[1] for t in text_embeddings]\n        return cls.__from(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            **kwargs,\n        )\n[docs]    def save_local(self, folder_path: str, index_name: str = \"index\") -> None:\n        \"\"\"Save ScaNN index, docstore, and index_to_docstore_id to disk.\n        Args:\n            folder_path: folder path to save index, docstore,\n                and index_to_docstore_id to.\n        \"\"\"\n        path = Path(folder_path)\n        scann_path = path / \"{index_name}.scann\".format(index_name=index_name)\n        scann_path.mkdir(exist_ok=True, parents=True)\n        # save index separately since it is not picklable\n        self.index.serialize(str(scann_path))\n        # save docstore and index_to_docstore_id\n        with open(path / \"{index_name}.pkl\".format(index_name=index_name), \"wb\") as f:\n            pickle.dump((self.docstore, self.index_to_docstore_id), f)\n[docs]    @classmethod\n    def load_local(\n        cls,\n        folder_path: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html"}
{"id": "43878bab6695-10", "text": "def load_local(\n        cls,\n        folder_path: str,\n        embedding: Embeddings,\n        index_name: str = \"index\",\n        **kwargs: Any,\n    ) -> ScaNN:\n        \"\"\"Load ScaNN index, docstore, and index_to_docstore_id from disk.\n        Args:\n            folder_path: folder path to load index, docstore,\n                and index_to_docstore_id from.\n            embeddings: Embeddings to use when generating queries\n            index_name: for saving with a specific index file name\n        \"\"\"\n        path = Path(folder_path)\n        scann_path = path / \"{index_name}.scann\".format(index_name=index_name)\n        scann_path.mkdir(exist_ok=True, parents=True)\n        # load index separately since it is not picklable\n        scann = dependable_scann_import()\n        index = scann.scann_ops_pybind.load_searcher(str(scann_path))\n        # load docstore and index_to_docstore_id\n        with open(path / \"{index_name}.pkl\".format(index_name=index_name), \"rb\") as f:\n            docstore, index_to_docstore_id = pickle.load(f)\n        return cls(embedding, index, docstore, index_to_docstore_id, **kwargs)\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        \"\"\"\n        The 'correct' relevance function\n        may differ depending on a few things, including:\n        - the distance / similarity metric used by the VectorStore\n        - the scale of your embeddings (OpenAI's are unit normed. Many others are not!)\n        - embedding dimensionality\n        - etc.\n        \"\"\"\n        if self.override_relevance_score_fn is not None:\n            return self.override_relevance_score_fn", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html"}
{"id": "43878bab6695-11", "text": "return self.override_relevance_score_fn\n        # Default strategy is to rely on distance strategy provided in\n        # vectorstore constructor\n        if self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:\n            return self._max_inner_product_relevance_score_fn\n        elif self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE:\n            # Default behavior is to use euclidean distance relevancy\n            return self._euclidean_relevance_score_fn\n        else:\n            raise ValueError(\n                \"Unknown distance strategy, must be cosine, max_inner_product,\"\n                \" or euclidean\"\n            )\n    def _similarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs and their similarity scores on a scale from 0 to 1.\"\"\"\n        # Pop score threshold so that only relevancy scores, not raw scores, are\n        # filtered.\n        score_threshold = kwargs.pop(\"score_threshold\", None)\n        relevance_score_fn = self._select_relevance_score_fn()\n        if relevance_score_fn is None:\n            raise ValueError(\n                \"normalize_score_fn must be provided to\"\n                \" ScaNN constructor to normalize scores\"\n            )\n        docs_and_scores = self.similarity_search_with_score(\n            query,\n            k=k,\n            filter=filter,\n            fetch_k=fetch_k,\n            **kwargs,\n        )\n        docs_and_rel_scores = [\n            (doc, relevance_score_fn(score)) for doc, score in docs_and_scores\n        ]\n        if score_threshold is not None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html"}
{"id": "43878bab6695-12", "text": "]\n        if score_threshold is not None:\n            docs_and_rel_scores = [\n                (doc, similarity)\n                for doc, similarity in docs_and_rel_scores\n                if similarity >= score_threshold\n            ]\n        return docs_and_rel_scores", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html"}
{"id": "448739961ed5-0", "text": "Source code for langchain.vectorstores.opensearch_vector_search\nfrom __future__ import annotations\nimport uuid\nimport warnings\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple\nimport numpy as np\nfrom langchain.schema import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_dict_or_env\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nIMPORT_OPENSEARCH_PY_ERROR = (\n    \"Could not import OpenSearch. Please install it with `pip install opensearch-py`.\"\n)\nSCRIPT_SCORING_SEARCH = \"script_scoring\"\nPAINLESS_SCRIPTING_SEARCH = \"painless_scripting\"\nMATCH_ALL_QUERY = {\"match_all\": {}}  # type: Dict\ndef _import_opensearch() -> Any:\n    \"\"\"Import OpenSearch if available, otherwise raise error.\"\"\"\n    try:\n        from opensearchpy import OpenSearch\n    except ImportError:\n        raise ImportError(IMPORT_OPENSEARCH_PY_ERROR)\n    return OpenSearch\ndef _import_bulk() -> Any:\n    \"\"\"Import bulk if available, otherwise raise error.\"\"\"\n    try:\n        from opensearchpy.helpers import bulk\n    except ImportError:\n        raise ImportError(IMPORT_OPENSEARCH_PY_ERROR)\n    return bulk\ndef _import_not_found_error() -> Any:\n    \"\"\"Import not found error if available, otherwise raise error.\"\"\"\n    try:\n        from opensearchpy.exceptions import NotFoundError\n    except ImportError:\n        raise ImportError(IMPORT_OPENSEARCH_PY_ERROR)\n    return NotFoundError\ndef _get_opensearch_client(opensearch_url: str, **kwargs: Any) -> Any:\n    \"\"\"Get OpenSearch client from the opensearch_url, otherwise raise error.\"\"\"\n    try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-1", "text": "try:\n        opensearch = _import_opensearch()\n        client = opensearch(opensearch_url, **kwargs)\n    except ValueError as e:\n        raise ImportError(\n            f\"OpenSearch client string provided is not in proper format. \"\n            f\"Got error: {e} \"\n        )\n    return client\ndef _validate_embeddings_and_bulk_size(embeddings_length: int, bulk_size: int) -> None:\n    \"\"\"Validate Embeddings Length and Bulk Size.\"\"\"\n    if embeddings_length == 0:\n        raise RuntimeError(\"Embeddings size is zero\")\n    if bulk_size < embeddings_length:\n        raise RuntimeError(\n            f\"The embeddings count, {embeddings_length} is more than the \"\n            f\"[bulk_size], {bulk_size}. Increase the value of [bulk_size].\"\n        )\ndef _validate_aoss_with_engines(is_aoss: bool, engine: str) -> None:\n    \"\"\"Validate AOSS with the engine.\"\"\"\n    if is_aoss and engine != \"nmslib\" and engine != \"faiss\":\n        raise ValueError(\n            \"Amazon OpenSearch Service Serverless only \"\n            \"supports `nmslib` or `faiss` engines\"\n        )\ndef _is_aoss_enabled(http_auth: Any) -> bool:\n    \"\"\"Check if the service is http_auth is set as `aoss`.\"\"\"\n    if (\n        http_auth is not None\n        and hasattr(http_auth, \"service\")\n        and http_auth.service == \"aoss\"\n    ):\n        return True\n    return False\ndef _bulk_ingest_embeddings(\n    client: Any,\n    index_name: str,\n    embeddings: List[List[float]],\n    texts: Iterable[str],\n    metadatas: Optional[List[dict]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-2", "text": "metadatas: Optional[List[dict]] = None,\n    ids: Optional[List[str]] = None,\n    vector_field: str = \"vector_field\",\n    text_field: str = \"text\",\n    mapping: Optional[Dict] = None,\n    max_chunk_bytes: Optional[int] = 1 * 1024 * 1024,\n    is_aoss: bool = False,\n) -> List[str]:\n    \"\"\"Bulk Ingest Embeddings into given index.\"\"\"\n    if not mapping:\n        mapping = dict()\n    bulk = _import_bulk()\n    not_found_error = _import_not_found_error()\n    requests = []\n    return_ids = []\n    mapping = mapping\n    try:\n        client.indices.get(index=index_name)\n    except not_found_error:\n        client.indices.create(index=index_name, body=mapping)\n    for i, text in enumerate(texts):\n        metadata = metadatas[i] if metadatas else {}\n        _id = ids[i] if ids else str(uuid.uuid4())\n        request = {\n            \"_op_type\": \"index\",\n            \"_index\": index_name,\n            vector_field: embeddings[i],\n            text_field: text,\n            \"metadata\": metadata,\n        }\n        if is_aoss:\n            request[\"id\"] = _id\n        else:\n            request[\"_id\"] = _id\n        requests.append(request)\n        return_ids.append(_id)\n    bulk(client, requests, max_chunk_bytes=max_chunk_bytes)\n    if not is_aoss:\n        client.indices.refresh(index=index_name)\n    return return_ids\ndef _default_scripting_text_mapping(\n    dim: int,\n    vector_field: str = \"vector_field\",\n) -> Dict:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-3", "text": "vector_field: str = \"vector_field\",\n) -> Dict:\n    \"\"\"For Painless Scripting or Script Scoring,the default mapping to create index.\"\"\"\n    return {\n        \"mappings\": {\n            \"properties\": {\n                vector_field: {\"type\": \"knn_vector\", \"dimension\": dim},\n            }\n        }\n    }\ndef _default_text_mapping(\n    dim: int,\n    engine: str = \"nmslib\",\n    space_type: str = \"l2\",\n    ef_search: int = 512,\n    ef_construction: int = 512,\n    m: int = 16,\n    vector_field: str = \"vector_field\",\n) -> Dict:\n    \"\"\"For Approximate k-NN Search, this is the default mapping to create index.\"\"\"\n    return {\n        \"settings\": {\"index\": {\"knn\": True, \"knn.algo_param.ef_search\": ef_search}},\n        \"mappings\": {\n            \"properties\": {\n                vector_field: {\n                    \"type\": \"knn_vector\",\n                    \"dimension\": dim,\n                    \"method\": {\n                        \"name\": \"hnsw\",\n                        \"space_type\": space_type,\n                        \"engine\": engine,\n                        \"parameters\": {\"ef_construction\": ef_construction, \"m\": m},\n                    },\n                }\n            }\n        },\n    }\ndef _default_approximate_search_query(\n    query_vector: List[float],\n    k: int = 4,\n    vector_field: str = \"vector_field\",\n) -> Dict:\n    \"\"\"For Approximate k-NN Search, this is the default query.\"\"\"\n    return {\n        \"size\": k,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-4", "text": "return {\n        \"size\": k,\n        \"query\": {\"knn\": {vector_field: {\"vector\": query_vector, \"k\": k}}},\n    }\ndef _approximate_search_query_with_boolean_filter(\n    query_vector: List[float],\n    boolean_filter: Dict,\n    k: int = 4,\n    vector_field: str = \"vector_field\",\n    subquery_clause: str = \"must\",\n) -> Dict:\n    \"\"\"For Approximate k-NN Search, with Boolean Filter.\"\"\"\n    return {\n        \"size\": k,\n        \"query\": {\n            \"bool\": {\n                \"filter\": boolean_filter,\n                subquery_clause: [\n                    {\"knn\": {vector_field: {\"vector\": query_vector, \"k\": k}}}\n                ],\n            }\n        },\n    }\ndef _approximate_search_query_with_efficient_filter(\n    query_vector: List[float],\n    efficient_filter: Dict,\n    k: int = 4,\n    vector_field: str = \"vector_field\",\n) -> Dict:\n    \"\"\"For Approximate k-NN Search, with Efficient Filter for Lucene and\n    Faiss Engines.\"\"\"\n    search_query = _default_approximate_search_query(\n        query_vector, k=k, vector_field=vector_field\n    )\n    search_query[\"query\"][\"knn\"][vector_field][\"filter\"] = efficient_filter\n    return search_query\ndef _default_script_query(\n    query_vector: List[float],\n    k: int = 4,\n    space_type: str = \"l2\",\n    pre_filter: Optional[Dict] = None,\n    vector_field: str = \"vector_field\",\n) -> Dict:\n    \"\"\"For Script Scoring Search, this is the default query.\"\"\"\n    if not pre_filter:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-5", "text": "if not pre_filter:\n        pre_filter = MATCH_ALL_QUERY\n    return {\n        \"size\": k,\n        \"query\": {\n            \"script_score\": {\n                \"query\": pre_filter,\n                \"script\": {\n                    \"source\": \"knn_score\",\n                    \"lang\": \"knn\",\n                    \"params\": {\n                        \"field\": vector_field,\n                        \"query_value\": query_vector,\n                        \"space_type\": space_type,\n                    },\n                },\n            }\n        },\n    }\ndef __get_painless_scripting_source(\n    space_type: str, vector_field: str = \"vector_field\"\n) -> str:\n    \"\"\"For Painless Scripting, it returns the script source based on space type.\"\"\"\n    source_value = (\n        \"(1.0 + \" + space_type + \"(params.query_value, doc['\" + vector_field + \"']))\"\n    )\n    if space_type == \"cosineSimilarity\":\n        return source_value\n    else:\n        return \"1/\" + source_value\ndef _default_painless_scripting_query(\n    query_vector: List[float],\n    k: int = 4,\n    space_type: str = \"l2Squared\",\n    pre_filter: Optional[Dict] = None,\n    vector_field: str = \"vector_field\",\n) -> Dict:\n    \"\"\"For Painless Scripting Search, this is the default query.\"\"\"\n    if not pre_filter:\n        pre_filter = MATCH_ALL_QUERY\n    source = __get_painless_scripting_source(space_type, vector_field=vector_field)\n    return {\n        \"size\": k,\n        \"query\": {\n            \"script_score\": {\n                \"query\": pre_filter,\n                \"script\": {\n                    \"source\": source,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-6", "text": "\"script\": {\n                    \"source\": source,\n                    \"params\": {\n                        \"field\": vector_field,\n                        \"query_value\": query_vector,\n                    },\n                },\n            }\n        },\n    }\n[docs]class OpenSearchVectorSearch(VectorStore):\n    \"\"\"`Amazon OpenSearch Vector Engine` vector store.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import OpenSearchVectorSearch\n            opensearch_vector_search = OpenSearchVectorSearch(\n                \"http://localhost:9200\",\n                \"embeddings\",\n                embedding_function\n            )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        opensearch_url: str,\n        index_name: str,\n        embedding_function: Embeddings,\n        **kwargs: Any,\n    ):\n        \"\"\"Initialize with necessary components.\"\"\"\n        self.embedding_function = embedding_function\n        self.index_name = index_name\n        http_auth = kwargs.get(\"http_auth\")\n        self.is_aoss = _is_aoss_enabled(http_auth=http_auth)\n        self.client = _get_opensearch_client(opensearch_url, **kwargs)\n        self.engine = kwargs.get(\"engine\")\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding_function\n    def __add(\n        self,\n        texts: Iterable[str],\n        embeddings: List[List[float]],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        bulk_size: int = 500,\n        **kwargs: Any,\n    ) -> List[str]:\n        _validate_embeddings_and_bulk_size(len(embeddings), bulk_size)\n        index_name = kwargs.get(\"index_name\", self.index_name)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-7", "text": "index_name = kwargs.get(\"index_name\", self.index_name)\n        text_field = kwargs.get(\"text_field\", \"text\")\n        dim = len(embeddings[0])\n        engine = kwargs.get(\"engine\", \"nmslib\")\n        space_type = kwargs.get(\"space_type\", \"l2\")\n        ef_search = kwargs.get(\"ef_search\", 512)\n        ef_construction = kwargs.get(\"ef_construction\", 512)\n        m = kwargs.get(\"m\", 16)\n        vector_field = kwargs.get(\"vector_field\", \"vector_field\")\n        max_chunk_bytes = kwargs.get(\"max_chunk_bytes\", 1 * 1024 * 1024)\n        _validate_aoss_with_engines(self.is_aoss, engine)\n        mapping = _default_text_mapping(\n            dim, engine, space_type, ef_search, ef_construction, m, vector_field\n        )\n        return _bulk_ingest_embeddings(\n            self.client,\n            index_name,\n            embeddings,\n            texts,\n            metadatas=metadatas,\n            ids=ids,\n            vector_field=vector_field,\n            text_field=text_field,\n            mapping=mapping,\n            max_chunk_bytes=max_chunk_bytes,\n            is_aoss=self.is_aoss,\n        )\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        bulk_size: int = 500,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-8", "text": "Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of ids to associate with the texts.\n            bulk_size: Bulk API request count; Default: 500\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        Optional Args:\n            vector_field: Document field embeddings are stored in. Defaults to\n            \"vector_field\".\n            text_field: Document field the text of the document is stored in. Defaults\n            to \"text\".\n        \"\"\"\n        embeddings = self.embedding_function.embed_documents(list(texts))\n        return self.__add(\n            texts,\n            embeddings,\n            metadatas=metadatas,\n            ids=ids,\n            bulk_size=bulk_size,\n            kwargs=kwargs,\n        )\n[docs]    def add_embeddings(\n        self,\n        text_embeddings: Iterable[Tuple[str, List[float]]],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        bulk_size: int = 500,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add the given texts and embeddings to the vectorstore.\n        Args:\n            text_embeddings: Iterable pairs of string and embedding to\n                add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of ids to associate with the texts.\n            bulk_size: Bulk API request count; Default: 500\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        Optional Args:\n            vector_field: Document field embeddings are stored in. Defaults to\n            \"vector_field\".", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-9", "text": "vector_field: Document field embeddings are stored in. Defaults to\n            \"vector_field\".\n            text_field: Document field the text of the document is stored in. Defaults\n            to \"text\".\n        \"\"\"\n        texts, embeddings = zip(*text_embeddings)\n        return self.__add(\n            list(texts),\n            list(embeddings),\n            metadatas=metadatas,\n            ids=ids,\n            bulk_size=bulk_size,\n            kwargs=kwargs,\n        )\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        By default, supports Approximate Search.\n        Also supports Script Scoring and Painless Scripting.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query.\n        Optional Args:\n            vector_field: Document field embeddings are stored in. Defaults to\n            \"vector_field\".\n            text_field: Document field the text of the document is stored in. Defaults\n            to \"text\".\n            metadata_field: Document field that metadata is stored in. Defaults to\n            \"metadata\".\n            Can be set to a special value \"*\" to include the entire document.\n        Optional Args for Approximate Search:\n            search_type: \"approximate_search\"; default: \"approximate_search\"\n            boolean_filter: A Boolean filter is a post filter consists of a Boolean\n            query that contains a k-NN query and a filter.\n            subquery_clause: Query clause on the knn vector field; default: \"must\"\n            lucene_filter: the Lucene algorithm decides whether to perform an exact", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-10", "text": "lucene_filter: the Lucene algorithm decides whether to perform an exact\n            k-NN search with pre-filtering or an approximate search with modified\n            post-filtering. (deprecated, use `efficient_filter`)\n            efficient_filter: the Lucene Engine or Faiss Engine decides whether to\n            perform an exact k-NN search with pre-filtering or an approximate search\n            with modified post-filtering.\n        Optional Args for Script Scoring Search:\n            search_type: \"script_scoring\"; default: \"approximate_search\"\n            space_type: \"l2\", \"l1\", \"linf\", \"cosinesimil\", \"innerproduct\",\n            \"hammingbit\"; default: \"l2\"\n            pre_filter: script_score query to pre-filter documents before identifying\n            nearest neighbors; default: {\"match_all\": {}}\n        Optional Args for Painless Scripting Search:\n            search_type: \"painless_scripting\"; default: \"approximate_search\"\n            space_type: \"l2Squared\", \"l1Norm\", \"cosineSimilarity\"; default: \"l2Squared\"\n            pre_filter: script_score query to pre-filter documents before identifying\n            nearest neighbors; default: {\"match_all\": {}}\n        \"\"\"\n        docs_with_scores = self.similarity_search_with_score(query, k, **kwargs)\n        return [doc[0] for doc in docs_with_scores]\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs and it's scores most similar to query.\n        By default, supports Approximate Search.\n        Also supports Script Scoring and Painless Scripting.\n        Args:\n            query: Text to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-11", "text": "Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents along with its scores most similar to the query.\n        Optional Args:\n            same as `similarity_search`\n        \"\"\"\n        text_field = kwargs.get(\"text_field\", \"text\")\n        metadata_field = kwargs.get(\"metadata_field\", \"metadata\")\n        hits = self._raw_similarity_search_with_score(query=query, k=k, **kwargs)\n        documents_with_scores = [\n            (\n                Document(\n                    page_content=hit[\"_source\"][text_field],\n                    metadata=hit[\"_source\"]\n                    if metadata_field == \"*\" or metadata_field not in hit[\"_source\"]\n                    else hit[\"_source\"][metadata_field],\n                ),\n                hit[\"_score\"],\n            )\n            for hit in hits\n        ]\n        return documents_with_scores\n    def _raw_similarity_search_with_score(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[dict]:\n        \"\"\"Return raw opensearch documents (dict) including vectors,\n        scores most similar to query.\n        By default, supports Approximate Search.\n        Also supports Script Scoring and Painless Scripting.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of dict with its scores most similar to the query.\n        Optional Args:\n            same as `similarity_search`\n        \"\"\"\n        embedding = self.embedding_function.embed_query(query)\n        search_type = kwargs.get(\"search_type\", \"approximate_search\")\n        vector_field = kwargs.get(\"vector_field\", \"vector_field\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-12", "text": "vector_field = kwargs.get(\"vector_field\", \"vector_field\")\n        index_name = kwargs.get(\"index_name\", self.index_name)\n        filter = kwargs.get(\"filter\", {})\n        if (\n            self.is_aoss\n            and search_type != \"approximate_search\"\n            and search_type != SCRIPT_SCORING_SEARCH\n        ):\n            raise ValueError(\n                \"Amazon OpenSearch Service Serverless only \"\n                \"supports `approximate_search` and `script_scoring`\"\n            )\n        if search_type == \"approximate_search\":\n            boolean_filter = kwargs.get(\"boolean_filter\", {})\n            subquery_clause = kwargs.get(\"subquery_clause\", \"must\")\n            efficient_filter = kwargs.get(\"efficient_filter\", {})\n            # `lucene_filter` is deprecated, added for Backwards Compatibility\n            lucene_filter = kwargs.get(\"lucene_filter\", {})\n            if boolean_filter != {} and efficient_filter != {}:\n                raise ValueError(\n                    \"Both `boolean_filter` and `efficient_filter` are provided which \"\n                    \"is invalid\"\n                )\n            if lucene_filter != {} and efficient_filter != {}:\n                raise ValueError(\n                    \"Both `lucene_filter` and `efficient_filter` are provided which \"\n                    \"is invalid. `lucene_filter` is deprecated\"\n                )\n            if lucene_filter != {} and boolean_filter != {}:\n                raise ValueError(\n                    \"Both `lucene_filter` and `boolean_filter` are provided which \"\n                    \"is invalid. `lucene_filter` is deprecated\"\n                )\n            if (\n                efficient_filter == {}\n                and boolean_filter == {}\n                and lucene_filter == {}\n                and filter != {}\n            ):\n                if self.engine in [\"faiss\", \"lucene\"]:\n                    efficient_filter = filter\n                else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-13", "text": "efficient_filter = filter\n                else:\n                    boolean_filter = filter\n            if boolean_filter != {}:\n                search_query = _approximate_search_query_with_boolean_filter(\n                    embedding,\n                    boolean_filter,\n                    k=k,\n                    vector_field=vector_field,\n                    subquery_clause=subquery_clause,\n                )\n            elif efficient_filter != {}:\n                search_query = _approximate_search_query_with_efficient_filter(\n                    embedding, efficient_filter, k=k, vector_field=vector_field\n                )\n            elif lucene_filter != {}:\n                warnings.warn(\n                    \"`lucene_filter` is deprecated. Please use the keyword argument\"\n                    \" `efficient_filter`\"\n                )\n                search_query = _approximate_search_query_with_efficient_filter(\n                    embedding, lucene_filter, k=k, vector_field=vector_field\n                )\n            else:\n                search_query = _default_approximate_search_query(\n                    embedding, k=k, vector_field=vector_field\n                )\n        elif search_type == SCRIPT_SCORING_SEARCH:\n            space_type = kwargs.get(\"space_type\", \"l2\")\n            pre_filter = kwargs.get(\"pre_filter\", MATCH_ALL_QUERY)\n            search_query = _default_script_query(\n                embedding, k, space_type, pre_filter, vector_field\n            )\n        elif search_type == PAINLESS_SCRIPTING_SEARCH:\n            space_type = kwargs.get(\"space_type\", \"l2Squared\")\n            pre_filter = kwargs.get(\"pre_filter\", MATCH_ALL_QUERY)\n            search_query = _default_painless_scripting_query(\n                embedding, k, space_type, pre_filter, vector_field\n            )\n        else:\n            raise ValueError(\"Invalid `search_type` provided as an argument\")\n        response = self.client.search(index=index_name, body=search_query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-14", "text": "response = self.client.search(index=index_name, body=search_query)\n        return [hit for hit in response[\"hits\"][\"hits\"]]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> list[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n                     Defaults to 20.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        vector_field = kwargs.get(\"vector_field\", \"vector_field\")\n        text_field = kwargs.get(\"text_field\", \"text\")\n        metadata_field = kwargs.get(\"metadata_field\", \"metadata\")\n        # Get embedding of the user query\n        embedding = self.embedding_function.embed_query(query)\n        # Do ANN/KNN search to get top fetch_k results where fetch_k >= k\n        results = self._raw_similarity_search_with_score(query, fetch_k, **kwargs)\n        embeddings = [result[\"_source\"][vector_field] for result in results]\n        # Rerank top k results using MMR, (mmr_selected is a list of indices)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-15", "text": "mmr_selected = maximal_marginal_relevance(\n            np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult\n        )\n        return [\n            Document(\n                page_content=results[i][\"_source\"][text_field],\n                metadata=results[i][\"_source\"][metadata_field],\n            )\n            for i in mmr_selected\n        ]\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        bulk_size: int = 500,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> OpenSearchVectorSearch:\n        \"\"\"Construct OpenSearchVectorSearch wrapper from raw texts.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import OpenSearchVectorSearch\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                opensearch_vector_search = OpenSearchVectorSearch.from_texts(\n                    texts,\n                    embeddings,\n                    opensearch_url=\"http://localhost:9200\"\n                )\n        OpenSearch by default supports Approximate Search powered by nmslib, faiss\n        and lucene engines recommended for large datasets. Also supports brute force\n        search through Script Scoring and Painless Scripting.\n        Optional Args:\n            vector_field: Document field embeddings are stored in. Defaults to\n            \"vector_field\".\n            text_field: Document field the text of the document is stored in. Defaults\n            to \"text\".\n        Optional Keyword Args for Approximate Search:\n            engine: \"nmslib\", \"faiss\", \"lucene\"; default: \"nmslib\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-16", "text": "space_type: \"l2\", \"l1\", \"cosinesimil\", \"linf\", \"innerproduct\"; default: \"l2\"\n            ef_search: Size of the dynamic list used during k-NN searches. Higher values\n            lead to more accurate but slower searches; default: 512\n            ef_construction: Size of the dynamic list used during k-NN graph creation.\n            Higher values lead to more accurate graph but slower indexing speed;\n            default: 512\n            m: Number of bidirectional links created for each new element. Large impact\n            on memory consumption. Between 2 and 100; default: 16\n        Keyword Args for Script Scoring or Painless Scripting:\n            is_appx_search: False\n        \"\"\"\n        embeddings = embedding.embed_documents(texts)\n        return cls.from_embeddings(\n            embeddings,\n            texts,\n            embedding,\n            metadatas=metadatas,\n            bulk_size=bulk_size,\n            ids=ids,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_embeddings(\n        cls,\n        embeddings: List[List[float]],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        bulk_size: int = 500,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> OpenSearchVectorSearch:\n        \"\"\"Construct OpenSearchVectorSearch wrapper from pre-vectorized embeddings.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import OpenSearchVectorSearch\n                from langchain.embeddings import OpenAIEmbeddings\n                embedder = OpenAIEmbeddings()\n                embeddings = embedder.embed_documents([\"foo\", \"bar\"])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-17", "text": "embeddings = embedder.embed_documents([\"foo\", \"bar\"])\n                opensearch_vector_search = OpenSearchVectorSearch.from_embeddings(\n                    embeddings,\n                    texts,\n                    embedder,\n                    opensearch_url=\"http://localhost:9200\"\n                )\n        OpenSearch by default supports Approximate Search powered by nmslib, faiss\n        and lucene engines recommended for large datasets. Also supports brute force\n        search through Script Scoring and Painless Scripting.\n        Optional Args:\n            vector_field: Document field embeddings are stored in. Defaults to\n            \"vector_field\".\n            text_field: Document field the text of the document is stored in. Defaults\n            to \"text\".\n        Optional Keyword Args for Approximate Search:\n            engine: \"nmslib\", \"faiss\", \"lucene\"; default: \"nmslib\"\n            space_type: \"l2\", \"l1\", \"cosinesimil\", \"linf\", \"innerproduct\"; default: \"l2\"\n            ef_search: Size of the dynamic list used during k-NN searches. Higher values\n            lead to more accurate but slower searches; default: 512\n            ef_construction: Size of the dynamic list used during k-NN graph creation.\n            Higher values lead to more accurate graph but slower indexing speed;\n            default: 512\n            m: Number of bidirectional links created for each new element. Large impact\n            on memory consumption. Between 2 and 100; default: 16\n        Keyword Args for Script Scoring or Painless Scripting:\n            is_appx_search: False\n        \"\"\"\n        opensearch_url = get_from_dict_or_env(\n            kwargs, \"opensearch_url\", \"OPENSEARCH_URL\"\n        )\n        # List of arguments that needs to be removed from kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-18", "text": ")\n        # List of arguments that needs to be removed from kwargs\n        # before passing kwargs to get opensearch client\n        keys_list = [\n            \"opensearch_url\",\n            \"index_name\",\n            \"is_appx_search\",\n            \"vector_field\",\n            \"text_field\",\n            \"engine\",\n            \"space_type\",\n            \"ef_search\",\n            \"ef_construction\",\n            \"m\",\n            \"max_chunk_bytes\",\n            \"is_aoss\",\n        ]\n        _validate_embeddings_and_bulk_size(len(embeddings), bulk_size)\n        dim = len(embeddings[0])\n        # Get the index name from either from kwargs or ENV Variable\n        # before falling back to random generation\n        index_name = get_from_dict_or_env(\n            kwargs, \"index_name\", \"OPENSEARCH_INDEX_NAME\", default=uuid.uuid4().hex\n        )\n        is_appx_search = kwargs.get(\"is_appx_search\", True)\n        vector_field = kwargs.get(\"vector_field\", \"vector_field\")\n        text_field = kwargs.get(\"text_field\", \"text\")\n        max_chunk_bytes = kwargs.get(\"max_chunk_bytes\", 1 * 1024 * 1024)\n        http_auth = kwargs.get(\"http_auth\")\n        is_aoss = _is_aoss_enabled(http_auth=http_auth)\n        engine = None\n        if is_aoss and not is_appx_search:\n            raise ValueError(\n                \"Amazon OpenSearch Service Serverless only \"\n                \"supports `approximate_search`\"\n            )\n        if is_appx_search:\n            engine = kwargs.get(\"engine\", \"nmslib\")\n            space_type = kwargs.get(\"space_type\", \"l2\")\n            ef_search = kwargs.get(\"ef_search\", 512)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "448739961ed5-19", "text": "ef_search = kwargs.get(\"ef_search\", 512)\n            ef_construction = kwargs.get(\"ef_construction\", 512)\n            m = kwargs.get(\"m\", 16)\n            _validate_aoss_with_engines(is_aoss, engine)\n            mapping = _default_text_mapping(\n                dim, engine, space_type, ef_search, ef_construction, m, vector_field\n            )\n        else:\n            mapping = _default_scripting_text_mapping(dim)\n        [kwargs.pop(key, None) for key in keys_list]\n        client = _get_opensearch_client(opensearch_url, **kwargs)\n        _bulk_ingest_embeddings(\n            client,\n            index_name,\n            embeddings,\n            texts,\n            ids=ids,\n            metadatas=metadatas,\n            vector_field=vector_field,\n            text_field=text_field,\n            mapping=mapping,\n            max_chunk_bytes=max_chunk_bytes,\n            is_aoss=is_aoss,\n        )\n        kwargs[\"engine\"] = engine\n        return cls(opensearch_url, index_name, embedding, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html"}
{"id": "a6ad2e704c72-0", "text": "Source code for langchain.vectorstores.matching_engine\nfrom __future__ import annotations\nimport json\nimport logging\nimport time\nimport uuid\nfrom typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type\nfrom langchain.schema.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utilities.vertexai import get_client_info\nif TYPE_CHECKING:\n    from google.cloud import storage\n    from google.cloud.aiplatform import MatchingEngineIndex, MatchingEngineIndexEndpoint\n    from google.cloud.aiplatform.matching_engine.matching_engine_index_endpoint import (\n        Namespace,\n    )\n    from google.oauth2.service_account import Credentials\n    from langchain.embeddings import TensorflowHubEmbeddings\nlogger = logging.getLogger()\n[docs]class MatchingEngine(VectorStore):\n    \"\"\"`Google Vertex AI Matching Engine` vector store.\n    While the embeddings are stored in the Matching Engine, the embedded\n    documents will be stored in GCS.\n    An existing Index and corresponding Endpoint are preconditions for\n    using this module.\n    See usage in docs/modules/indexes/vectorstores/examples/matchingengine.ipynb\n    Note that this implementation is mostly meant for reading if you are\n    planning to do a real time implementation. While reading is a real time\n    operation, updating the index takes close to one hour.\"\"\"\n[docs]    def __init__(\n        self,\n        project_id: str,\n        index: MatchingEngineIndex,\n        endpoint: MatchingEngineIndexEndpoint,\n        embedding: Embeddings,\n        gcs_client: storage.Client,\n        gcs_bucket_name: str,\n        credentials: Optional[Credentials] = None,\n    ):\n        \"\"\"Vertex Matching Engine implementation of the vector store.\n        While the embeddings are stored in the Matching Engine, the embedded", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html"}
{"id": "a6ad2e704c72-1", "text": "While the embeddings are stored in the Matching Engine, the embedded\n        documents will be stored in GCS.\n        An existing Index and corresponding Endpoint are preconditions for\n        using this module.\n        See usage in\n        docs/modules/indexes/vectorstores/examples/matchingengine.ipynb.\n        Note that this implementation is mostly meant for reading if you are\n        planning to do a real time implementation. While reading is a real time\n        operation, updating the index takes close to one hour.\n        Attributes:\n            project_id: The GCS project id.\n            index: The created index class. See\n                ~:func:`MatchingEngine.from_components`.\n            endpoint: The created endpoint class. See\n                ~:func:`MatchingEngine.from_components`.\n            embedding: A :class:`Embeddings` that will be used for\n                embedding the text sent. If none is sent, then the\n                multilingual Tensorflow Universal Sentence Encoder will be used.\n            gcs_client: The GCS client.\n            gcs_bucket_name: The GCS bucket name.\n            credentials (Optional): Created GCP credentials.\n        \"\"\"\n        super().__init__()\n        self._validate_google_libraries_installation()\n        self.project_id = project_id\n        self.index = index\n        self.endpoint = endpoint\n        self.embedding = embedding\n        self.gcs_client = gcs_client\n        self.credentials = credentials\n        self.gcs_bucket_name = gcs_bucket_name\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding\n    def _validate_google_libraries_installation(self) -> None:\n        \"\"\"Validates that Google libraries that are needed are installed.\"\"\"\n        try:\n            from google.cloud import aiplatform, storage  # noqa: F401\n            from google.oauth2 import service_account  # noqa: F401", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html"}
{"id": "a6ad2e704c72-2", "text": "from google.oauth2 import service_account  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"You must run `pip install --upgrade \"\n                \"google-cloud-aiplatform google-cloud-storage`\"\n                \"to use the MatchingEngine Vectorstore.\"\n            )\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        texts = list(texts)\n        if metadatas is not None and len(texts) != len(metadatas):\n            raise ValueError(\n                \"texts and metadatas do not have the same length. Received \"\n                f\"{len(texts)} texts and {len(metadatas)} metadatas.\"\n            )\n        logger.debug(\"Embedding documents.\")\n        embeddings = self.embedding.embed_documents(texts)\n        jsons = []\n        ids = []\n        # Could be improved with async.\n        for idx, (embedding, text) in enumerate(zip(embeddings, texts)):\n            id = str(uuid.uuid4())\n            ids.append(id)\n            json_: dict = {\"id\": id, \"embedding\": embedding}\n            if metadatas is not None:\n                json_[\"metadata\"] = metadatas[idx]\n            jsons.append(json_)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html"}
{"id": "a6ad2e704c72-3", "text": "json_[\"metadata\"] = metadatas[idx]\n            jsons.append(json_)\n            self._upload_to_gcs(text, f\"documents/{id}\")\n        logger.debug(f\"Uploaded {len(ids)} documents to GCS.\")\n        # Creating json lines from the embedded documents.\n        result_str = \"\\n\".join([json.dumps(x) for x in jsons])\n        filename_prefix = f\"indexes/{uuid.uuid4()}\"\n        filename = f\"{filename_prefix}/{time.time()}.json\"\n        self._upload_to_gcs(result_str, filename)\n        logger.debug(\n            f\"Uploaded updated json with embeddings to \"\n            f\"{self.gcs_bucket_name}/{filename}.\"\n        )\n        self.index = self.index.update_embeddings(\n            contents_delta_uri=f\"gs://{self.gcs_bucket_name}/{filename_prefix}/\"\n        )\n        logger.debug(\"Updated index with new configuration.\")\n        return ids\n    def _upload_to_gcs(self, data: str, gcs_location: str) -> None:\n        \"\"\"Uploads data to gcs_location.\n        Args:\n            data: The data that will be stored.\n            gcs_location: The location where the data will be stored.\n        \"\"\"\n        bucket = self.gcs_client.get_bucket(self.gcs_bucket_name)\n        blob = bucket.blob(gcs_location)\n        blob.upload_from_string(data)\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[List[Namespace]] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query and their cosine distance from the query.\n        Args:\n            query: String query look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html"}
{"id": "a6ad2e704c72-4", "text": "Args:\n            query: String query look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Optional. A list of Namespaces for filtering\n                the matching results.\n                For example:\n                [Namespace(\"color\", [\"red\"], []), Namespace(\"shape\", [], [\"squared\"])]\n                will match datapoints that satisfy \"red color\" but not include\n                datapoints with \"squared shape\". Please refer to\n                https://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json\n                for more detail.\n        Returns:\n            List[Tuple[Document, float]]: List of documents most similar to\n            the query text and cosine distance in float for each.\n            Lower score represents more similarity.\n        \"\"\"\n        logger.debug(f\"Embedding query {query}.\")\n        embedding_query = self.embedding.embed_query(query)\n        return self.similarity_search_by_vector_with_score(\n            embedding_query, k=k, filter=filter\n        )\n[docs]    def similarity_search_by_vector_with_score(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[List[Namespace]] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to the embedding and their cosine distance.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Optional. A list of Namespaces for filtering\n                the matching results.\n                For example:\n                [Namespace(\"color\", [\"red\"], []), Namespace(\"shape\", [], [\"squared\"])]\n                will match datapoints that satisfy \"red color\" but not include", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html"}
{"id": "a6ad2e704c72-5", "text": "will match datapoints that satisfy \"red color\" but not include\n                datapoints with \"squared shape\". Please refer to\n                https://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json\n                for more detail.\n        Returns:\n            List[Tuple[Document, float]]: List of documents most similar to\n            the query text and cosine distance in float for each.\n            Lower score represents more similarity.\n        \"\"\"\n        filter = filter or []\n        # If the endpoint is public we use the find_neighbors function.\n        if self.endpoint._public_match_client:\n            response = self.endpoint.find_neighbors(\n                deployed_index_id=self._get_index_id(),\n                queries=[embedding],\n                num_neighbors=k,\n                filter=filter,\n            )\n        else:\n            response = self.endpoint.match(\n                deployed_index_id=self._get_index_id(),\n                queries=[embedding],\n                num_neighbors=k,\n                filter=filter,\n            )\n        logger.debug(f\"Found {len(response)} matches.\")\n        if len(response) == 0:\n            return []\n        results = []\n        # I'm only getting the first one because queries receives an array\n        # and the similarity_search method only receives one query. This\n        # means that the match method will always return an array with only\n        # one element.\n        for doc in response[0]:\n            page_content = self._download_from_gcs(f\"documents/{doc.id}\")\n            results.append((Document(page_content=page_content), doc.distance))\n        logger.debug(\"Downloaded documents for query.\")\n        return results\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[List[Namespace]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html"}
{"id": "a6ad2e704c72-6", "text": "filter: Optional[List[Namespace]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: The string that will be used to search for similar documents.\n            k: The amount of neighbors that will be retrieved.\n            filter: Optional. A list of Namespaces for filtering the matching results.\n                For example:\n                [Namespace(\"color\", [\"red\"], []), Namespace(\"shape\", [], [\"squared\"])]\n                will match datapoints that satisfy \"red color\" but not include\n                datapoints with \"squared shape\". Please refer to\n                https://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json\n                 for more detail.\n        Returns:\n            A list of k matching documents.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(\n            query, k=k, filter=filter, **kwargs\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[List[Namespace]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to the embedding.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: The amount of neighbors that will be retrieved.\n            filter: Optional. A list of Namespaces for filtering the matching results.\n                For example:\n                [Namespace(\"color\", [\"red\"], []), Namespace(\"shape\", [], [\"squared\"])]\n                will match datapoints that satisfy \"red color\" but not include\n                datapoints with \"squared shape\". Please refer to", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html"}
{"id": "a6ad2e704c72-7", "text": "datapoints with \"squared shape\". Please refer to\n                https://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json\n                 for more detail.\n        Returns:\n            A list of k matching documents.\n        \"\"\"\n        docs_and_scores = self.similarity_search_by_vector_with_score(\n            embedding, k=k, filter=filter, **kwargs\n        )\n        return [doc for doc, _ in docs_and_scores]\n    def _get_index_id(self) -> str:\n        \"\"\"Gets the correct index id for the endpoint.\n        Returns:\n            The index id if found (which should be found) or throws\n            ValueError otherwise.\n        \"\"\"\n        for index in self.endpoint.deployed_indexes:\n            if index.index == self.index.resource_name:\n                return index.id\n        raise ValueError(\n            f\"No index with id {self.index.resource_name} \"\n            f\"deployed on endpoint \"\n            f\"{self.endpoint.display_name}.\"\n        )\n    def _download_from_gcs(self, gcs_location: str) -> str:\n        \"\"\"Downloads from GCS in text format.\n        Args:\n            gcs_location: The location where the file is located.\n        Returns:\n            The string contents of the file.\n        \"\"\"\n        bucket = self.gcs_client.get_bucket(self.gcs_bucket_name)\n        blob = bucket.blob(gcs_location)\n        return blob.download_as_string()\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[\"MatchingEngine\"],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> \"MatchingEngine\":\n        \"\"\"Use from components instead.\"\"\"\n        raise NotImplementedError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html"}
{"id": "a6ad2e704c72-8", "text": "\"\"\"Use from components instead.\"\"\"\n        raise NotImplementedError(\n            \"This method is not implemented. Instead, you should initialize the class\"\n            \" with `MatchingEngine.from_components(...)` and then call \"\n            \"`add_texts`\"\n        )\n[docs]    @classmethod\n    def from_components(\n        cls: Type[\"MatchingEngine\"],\n        project_id: str,\n        region: str,\n        gcs_bucket_name: str,\n        index_id: str,\n        endpoint_id: str,\n        credentials_path: Optional[str] = None,\n        embedding: Optional[Embeddings] = None,\n    ) -> \"MatchingEngine\":\n        \"\"\"Takes the object creation out of the constructor.\n        Args:\n            project_id: The GCP project id.\n            region: The default location making the API calls. It must have\n            the same location as the GCS bucket and must be regional.\n            gcs_bucket_name: The location where the vectors will be stored in\n            order for the index to be created.\n            index_id: The id of the created index.\n            endpoint_id: The id of the created endpoint.\n            credentials_path: (Optional) The path of the Google credentials on\n            the local file system.\n            embedding: The :class:`Embeddings` that will be used for\n            embedding the texts.\n        Returns:\n            A configured MatchingEngine with the texts added to the index.\n        \"\"\"\n        gcs_bucket_name = cls._validate_gcs_bucket(gcs_bucket_name)\n        credentials = cls._create_credentials_from_file(credentials_path)\n        index = cls._create_index_by_id(index_id, project_id, region, credentials)\n        endpoint = cls._create_endpoint_by_id(\n            endpoint_id, project_id, region, credentials\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html"}
{"id": "a6ad2e704c72-9", "text": "endpoint_id, project_id, region, credentials\n        )\n        gcs_client = cls._get_gcs_client(credentials, project_id)\n        cls._init_aiplatform(project_id, region, gcs_bucket_name, credentials)\n        return cls(\n            project_id=project_id,\n            index=index,\n            endpoint=endpoint,\n            embedding=embedding or cls._get_default_embeddings(),\n            gcs_client=gcs_client,\n            credentials=credentials,\n            gcs_bucket_name=gcs_bucket_name,\n        )\n    @classmethod\n    def _validate_gcs_bucket(cls, gcs_bucket_name: str) -> str:\n        \"\"\"Validates the gcs_bucket_name as a bucket name.\n        Args:\n              gcs_bucket_name: The received bucket uri.\n        Returns:\n              A valid gcs_bucket_name or throws ValueError if full path is\n              provided.\n        \"\"\"\n        gcs_bucket_name = gcs_bucket_name.replace(\"gs://\", \"\")\n        if \"/\" in gcs_bucket_name:\n            raise ValueError(\n                f\"The argument gcs_bucket_name should only be \"\n                f\"the bucket name. Received {gcs_bucket_name}\"\n            )\n        return gcs_bucket_name\n    @classmethod\n    def _create_credentials_from_file(\n        cls, json_credentials_path: Optional[str]\n    ) -> Optional[Credentials]:\n        \"\"\"Creates credentials for GCP.\n        Args:\n             json_credentials_path: The path on the file system where the\n             credentials are stored.\n         Returns:\n             An optional of Credentials or None, in which case the default\n             will be used.\n        \"\"\"\n        from google.oauth2 import service_account\n        credentials = None\n        if json_credentials_path is not None:\n            credentials = service_account.Credentials.from_service_account_file(\n                json_credentials_path", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html"}
{"id": "a6ad2e704c72-10", "text": "credentials = service_account.Credentials.from_service_account_file(\n                json_credentials_path\n            )\n        return credentials\n    @classmethod\n    def _create_index_by_id(\n        cls, index_id: str, project_id: str, region: str, credentials: \"Credentials\"\n    ) -> MatchingEngineIndex:\n        \"\"\"Creates a MatchingEngineIndex object by id.\n        Args:\n            index_id: The created index id.\n            project_id: The project to retrieve index from.\n            region: Location to retrieve index from.\n            credentials: GCS credentials.\n        Returns:\n            A configured MatchingEngineIndex.\n        \"\"\"\n        from google.cloud import aiplatform\n        logger.debug(f\"Creating matching engine index with id {index_id}.\")\n        return aiplatform.MatchingEngineIndex(\n            index_name=index_id,\n            project=project_id,\n            location=region,\n            credentials=credentials,\n        )\n    @classmethod\n    def _create_endpoint_by_id(\n        cls, endpoint_id: str, project_id: str, region: str, credentials: \"Credentials\"\n    ) -> MatchingEngineIndexEndpoint:\n        \"\"\"Creates a MatchingEngineIndexEndpoint object by id.\n        Args:\n            endpoint_id: The created endpoint id.\n            project_id: The project to retrieve index from.\n            region: Location to retrieve index from.\n            credentials: GCS credentials.\n        Returns:\n            A configured MatchingEngineIndexEndpoint.\n        \"\"\"\n        from google.cloud import aiplatform\n        logger.debug(f\"Creating endpoint with id {endpoint_id}.\")\n        return aiplatform.MatchingEngineIndexEndpoint(\n            index_endpoint_name=endpoint_id,\n            project=project_id,\n            location=region,\n            credentials=credentials,\n        )\n    @classmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html"}
{"id": "a6ad2e704c72-11", "text": "location=region,\n            credentials=credentials,\n        )\n    @classmethod\n    def _get_gcs_client(\n        cls, credentials: \"Credentials\", project_id: str\n    ) -> \"storage.Client\":\n        \"\"\"Lazily creates a GCS client.\n        Returns:\n            A configured GCS client.\n        \"\"\"\n        from google.cloud import storage\n        return storage.Client(\n            credentials=credentials,\n            project=project_id,\n            client_info=get_client_info(module=\"vertex-ai-matching-engine\"),\n        )\n    @classmethod\n    def _init_aiplatform(\n        cls,\n        project_id: str,\n        region: str,\n        gcs_bucket_name: str,\n        credentials: \"Credentials\",\n    ) -> None:\n        \"\"\"Configures the aiplatform library.\n        Args:\n            project_id: The GCP project id.\n            region: The default location making the API calls. It must have\n            the same location as the GCS bucket and must be regional.\n            gcs_bucket_name: GCS staging location.\n            credentials: The GCS Credentials object.\n        \"\"\"\n        from google.cloud import aiplatform\n        logger.debug(\n            f\"Initializing AI Platform for project {project_id} on \"\n            f\"{region} and for {gcs_bucket_name}.\"\n        )\n        aiplatform.init(\n            project=project_id,\n            location=region,\n            staging_bucket=gcs_bucket_name,\n            credentials=credentials,\n        )\n    @classmethod\n    def _get_default_embeddings(cls) -> \"TensorflowHubEmbeddings\":\n        \"\"\"This function returns the default embedding.\n        Returns:\n            Default TensorflowHubEmbeddings to use.\n        \"\"\"\n        from langchain.embeddings import TensorflowHubEmbeddings", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html"}
{"id": "a6ad2e704c72-12", "text": "\"\"\"\n        from langchain.embeddings import TensorflowHubEmbeddings\n        return TensorflowHubEmbeddings()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html"}
{"id": "5b7db5d31643-0", "text": "Source code for langchain.vectorstores.clarifai\nfrom __future__ import annotations\nimport logging\nimport os\nimport traceback\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import Any, Iterable, List, Optional, Tuple\nimport requests\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nlogger = logging.getLogger(__name__)\n[docs]class Clarifai(VectorStore):\n    \"\"\"`Clarifai AI` vector store.\n    To use, you should have the ``clarifai`` python package installed.\n    Example:\n        .. code-block:: python\n                from langchain.vectorstores import Clarifai\n                from langchain.embeddings.openai import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                vectorstore = Clarifai(\"langchain_store\", embeddings.embed_query)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        user_id: Optional[str] = None,\n        app_id: Optional[str] = None,\n        pat: Optional[str] = None,\n        number_of_docs: Optional[int] = None,\n        api_base: Optional[str] = None,\n    ) -> None:\n        \"\"\"Initialize with Clarifai client.\n        Args:\n            user_id (Optional[str], optional): User ID. Defaults to None.\n            app_id (Optional[str], optional): App ID. Defaults to None.\n            pat (Optional[str], optional): Personal access token. Defaults to None.\n            number_of_docs (Optional[int], optional): Number of documents to return\n            during vector search. Defaults to None.\n            api_base (Optional[str], optional): API base. Defaults to None.\n        Raises:\n            ValueError: If user ID, app ID or personal access token is not provided.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html"}
{"id": "5b7db5d31643-1", "text": "ValueError: If user ID, app ID or personal access token is not provided.\n        \"\"\"\n        try:\n            from clarifai.auth.helper import DEFAULT_BASE, ClarifaiAuthHelper\n            from clarifai.client import create_stub\n        except ImportError:\n            raise ImportError(\n                \"Could not import clarifai python package. \"\n                \"Please install it with `pip install clarifai`.\"\n            )\n        if api_base is None:\n            self._api_base = DEFAULT_BASE\n        self._user_id = user_id or os.environ.get(\"CLARIFAI_USER_ID\")\n        self._app_id = app_id or os.environ.get(\"CLARIFAI_APP_ID\")\n        self._pat = pat or os.environ.get(\"CLARIFAI_PAT\")\n        if self._user_id is None or self._app_id is None or self._pat is None:\n            raise ValueError(\n                \"Could not find CLARIFAI_USER_ID, CLARIFAI_APP_ID or\\\n                CLARIFAI_PAT in your environment. \"\n                \"Please set those env variables with a valid user ID, \\\n                app ID and personal access token \\\n                from https://clarifai.com/settings/security.\"\n            )\n        self._auth = ClarifaiAuthHelper(\n            user_id=self._user_id,\n            app_id=self._app_id,\n            pat=self._pat,\n            base=self._api_base,\n        )\n        self._stub = create_stub(self._auth)\n        self._userDataObject = self._auth.get_user_app_id_proto()\n        self._number_of_docs = number_of_docs\n    def _post_texts_as_inputs(\n        self, texts: List[str], metadatas: Optional[List[dict]] = None\n    ) -> List[str]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html"}
{"id": "5b7db5d31643-2", "text": ") -> List[str]:\n        \"\"\"Post text to Clarifai and return the ID of the input.\n        Args:\n            text (str): Text to post.\n            metadata (dict): Metadata to post.\n        Returns:\n            str: ID of the input.\n        \"\"\"\n        try:\n            from clarifai_grpc.grpc.api import resources_pb2, service_pb2\n            from clarifai_grpc.grpc.api.status import status_code_pb2\n            from google.protobuf.struct_pb2 import Struct  # type: ignore\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import clarifai python package. \"\n                \"Please install it with `pip install clarifai`.\"\n            ) from e\n        if metadatas is not None:\n            assert len(list(texts)) == len(\n                metadatas\n            ), \"Number of texts and metadatas should be the same.\"\n        inputs = []\n        for idx, text in enumerate(texts):\n            if metadatas is not None:\n                input_metadata = Struct()\n                input_metadata.update(metadatas[idx])\n            inputs.append(\n                resources_pb2.Input(\n                    data=resources_pb2.Data(\n                        text=resources_pb2.Text(raw=text),\n                        metadata=input_metadata,\n                    )\n                )\n            )\n        post_inputs_response = self._stub.PostInputs(\n            service_pb2.PostInputsRequest(\n                user_app_id=self._userDataObject,\n                inputs=inputs,\n            )\n        )\n        if post_inputs_response.status.code != status_code_pb2.SUCCESS:\n            logger.error(post_inputs_response.status)\n            raise Exception(\n                \"Post inputs failed, status: \" + post_inputs_response.status.description\n            )\n        input_ids = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html"}
{"id": "5b7db5d31643-3", "text": ")\n        input_ids = []\n        for input in post_inputs_response.inputs:\n            input_ids.append(input.id)\n        return input_ids\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add texts to the Clarifai vectorstore. This will push the text\n        to a Clarifai application.\n        Application use a base workflow that create and store embedding for each text.\n        Make sure you are using a base workflow that is compatible with text\n        (such as Language Understanding).\n        Args:\n            texts (Iterable[str]): Texts to add to the vectorstore.\n            metadatas (Optional[List[dict]], optional): Optional list of metadatas.\n            ids (Optional[List[str]], optional): Optional list of IDs.\n        Returns:\n            List[str]: List of IDs of the added texts.\n        \"\"\"\n        ltexts = list(texts)\n        length = len(ltexts)\n        assert length > 0, \"No texts provided to add to the vectorstore.\"\n        if metadatas is not None:\n            assert length == len(\n                metadatas\n            ), \"Number of texts and metadatas should be the same.\"\n        batch_size = 32\n        input_ids = []\n        for idx in range(0, length, batch_size):\n            try:\n                batch_texts = ltexts[idx : idx + batch_size]\n                batch_metadatas = (\n                    metadatas[idx : idx + batch_size] if metadatas else None\n                )\n                result_ids = self._post_texts_as_inputs(batch_texts, batch_metadatas)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html"}
{"id": "5b7db5d31643-4", "text": "result_ids = self._post_texts_as_inputs(batch_texts, batch_metadatas)\n                input_ids.extend(result_ids)\n                logger.debug(f\"Input {result_ids} posted successfully.\")\n            except Exception as error:\n                logger.warning(f\"Post inputs failed: {error}\")\n                traceback.print_exc()\n        return input_ids\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[dict] = None,\n        namespace: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Run similarity search with score using Clarifai.\n        Args:\n            query (str): Query text to search for.\n            k (int): Number of results to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata.\n            Defaults to None.\n        Returns:\n            List[Document]: List of documents most similar to the query text.\n        \"\"\"\n        try:\n            from clarifai_grpc.grpc.api import resources_pb2, service_pb2\n            from clarifai_grpc.grpc.api.status import status_code_pb2\n            from google.protobuf import json_format  # type: ignore\n            from google.protobuf.struct_pb2 import Struct  # type: ignore\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import clarifai python package. \"\n                \"Please install it with `pip install clarifai`.\"\n            ) from e\n        # Get number of docs to return\n        if self._number_of_docs is not None:\n            k = self._number_of_docs\n        req = service_pb2.PostAnnotationsSearchesRequest(\n            user_app_id=self._userDataObject,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html"}
{"id": "5b7db5d31643-5", "text": "user_app_id=self._userDataObject,\n            searches=[\n                resources_pb2.Search(\n                    query=resources_pb2.Query(\n                        ranks=[\n                            resources_pb2.Rank(\n                                annotation=resources_pb2.Annotation(\n                                    data=resources_pb2.Data(\n                                        text=resources_pb2.Text(raw=query),\n                                    )\n                                )\n                            )\n                        ]\n                    )\n                )\n            ],\n            pagination=service_pb2.Pagination(page=1, per_page=k),\n        )\n        # Add filter by metadata if provided.\n        if filter is not None:\n            search_metadata = Struct()\n            search_metadata.update(filter)\n            f = req.searches[0].query.filters.add()\n            f.annotation.data.metadata.update(search_metadata)\n        post_annotations_searches_response = self._stub.PostAnnotationsSearches(req)\n        # Check if search was successful\n        if post_annotations_searches_response.status.code != status_code_pb2.SUCCESS:\n            raise Exception(\n                \"Post searches failed, status: \"\n                + post_annotations_searches_response.status.description\n            )\n        # Retrieve hits\n        hits = post_annotations_searches_response.hits\n        executor = ThreadPoolExecutor(max_workers=10)\n        def hit_to_document(hit: resources_pb2.Hit) -> Tuple[Document, float]:\n            metadata = json_format.MessageToDict(hit.input.data.metadata)\n            h = {\"Authorization\": f\"Key {self._auth.pat}\"}\n            request = requests.get(hit.input.data.text.url, headers=h)\n            # override encoding by real educated guess as provided by chardet\n            request.encoding = request.apparent_encoding\n            requested_text = request.text\n            logger.debug(\n                f\"\\tScore {hit.score:.2f} for annotation: {hit.annotation.id}\\", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html"}
{"id": "5b7db5d31643-6", "text": "off input: {hit.input.id}, text: {requested_text[:125]}\"\n            )\n            return (Document(page_content=requested_text, metadata=metadata), hit.score)\n        # Iterate over hits and retrieve metadata and text\n        futures = [executor.submit(hit_to_document, hit) for hit in hits]\n        docs_and_scores = [future.result() for future in futures]\n        return docs_and_scores\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Run similarity search using Clarifai.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(query, **kwargs)\n        return [doc for doc, _ in docs_and_scores]\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Optional[Embeddings] = None,\n        metadatas: Optional[List[dict]] = None,\n        user_id: Optional[str] = None,\n        app_id: Optional[str] = None,\n        pat: Optional[str] = None,\n        number_of_docs: Optional[int] = None,\n        api_base: Optional[str] = None,\n        **kwargs: Any,\n    ) -> Clarifai:\n        \"\"\"Create a Clarifai vectorstore from a list of texts.\n        Args:\n            user_id (str): User ID.\n            app_id (str): App ID.\n            texts (List[str]): List of texts to add.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html"}
{"id": "5b7db5d31643-7", "text": "texts (List[str]): List of texts to add.\n            pat (Optional[str]): Personal access token. Defaults to None.\n            number_of_docs (Optional[int]): Number of documents to return\n            during vector search. Defaults to None.\n            api_base (Optional[str]): API base. Defaults to None.\n            metadatas (Optional[List[dict]]): Optional list of metadatas.\n            Defaults to None.\n        Returns:\n            Clarifai: Clarifai vectorstore.\n        \"\"\"\n        clarifai_vector_db = cls(\n            user_id=user_id,\n            app_id=app_id,\n            pat=pat,\n            number_of_docs=number_of_docs,\n            api_base=api_base,\n        )\n        clarifai_vector_db.add_texts(texts=texts, metadatas=metadatas)\n        return clarifai_vector_db\n[docs]    @classmethod\n    def from_documents(\n        cls,\n        documents: List[Document],\n        embedding: Optional[Embeddings] = None,\n        user_id: Optional[str] = None,\n        app_id: Optional[str] = None,\n        pat: Optional[str] = None,\n        number_of_docs: Optional[int] = None,\n        api_base: Optional[str] = None,\n        **kwargs: Any,\n    ) -> Clarifai:\n        \"\"\"Create a Clarifai vectorstore from a list of documents.\n        Args:\n            user_id (str): User ID.\n            app_id (str): App ID.\n            documents (List[Document]): List of documents to add.\n            pat (Optional[str]): Personal access token. Defaults to None.\n            number_of_docs (Optional[int]): Number of documents to return\n            during vector search. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html"}
{"id": "5b7db5d31643-8", "text": "during vector search. Defaults to None.\n            api_base (Optional[str]): API base. Defaults to None.\n        Returns:\n            Clarifai: Clarifai vectorstore.\n        \"\"\"\n        texts = [doc.page_content for doc in documents]\n        metadatas = [doc.metadata for doc in documents]\n        return cls.from_texts(\n            user_id=user_id,\n            app_id=app_id,\n            texts=texts,\n            pat=pat,\n            number_of_docs=number_of_docs,\n            api_base=api_base,\n            metadatas=metadatas,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html"}
{"id": "9cdde1982c83-0", "text": "Source code for langchain.vectorstores.supabase\nfrom __future__ import annotations\nimport uuid\nfrom itertools import repeat\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n    Union,\n)\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nif TYPE_CHECKING:\n    import supabase\n[docs]class SupabaseVectorStore(VectorStore):\n    \"\"\"`Supabase Postgres` vector store.\n    It assumes you have the `pgvector`\n    extension installed and a `match_documents` (or similar) function. For more details:\n    https://integrations.langchain.com/vectorstores?integration_name=SupabaseVectorStore\n    You can implement your own `match_documents` function in order to limit the search\n    space to a subset of documents based on your own authorization or business logic.\n    Note that the Supabase Python client does not yet support async operations.\n    If you'd like to use `max_marginal_relevance_search`, please review the instructions\n    below on modifying the `match_documents` function to return matched embeddings.\n    Examples:\n    .. code-block:: python\n        from langchain.embeddings.openai import OpenAIEmbeddings\n        from langchain.schema import Document\n        from langchain.vectorstores import SupabaseVectorStore\n        from supabase.client import create_client\n        docs = [\n            Document(page_content=\"foo\", metadata={\"id\": 1}),\n        ]\n        embeddings = OpenAIEmbeddings()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html"}
{"id": "9cdde1982c83-1", "text": "]\n        embeddings = OpenAIEmbeddings()\n        supabase_client = create_client(\"my_supabase_url\", \"my_supabase_key\")\n        vector_store = SupabaseVectorStore.from_documents(\n            docs,\n            embeddings,\n            client=supabase_client,\n            table_name=\"documents\",\n            query_name=\"match_documents\",\n            chunk_size=500,\n        )\n    To load from an existing table:\n    .. code-block:: python\n        from langchain.embeddings.openai import OpenAIEmbeddings\n        from langchain.vectorstores import SupabaseVectorStore\n        from supabase.client import create_client\n        embeddings = OpenAIEmbeddings()\n        supabase_client = create_client(\"my_supabase_url\", \"my_supabase_key\")\n        vector_store = SupabaseVectorStore(\n            client=supabase_client,\n            embedding=embeddings,\n            table_name=\"documents\",\n            query_name=\"match_documents\",\n        )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        client: supabase.client.Client,\n        embedding: Embeddings,\n        table_name: str,\n        chunk_size: int = 500,\n        query_name: Union[str, None] = None,\n    ) -> None:\n        \"\"\"Initialize with supabase client.\"\"\"\n        try:\n            import supabase  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"Could not import supabase python package. \"\n                \"Please install it with `pip install supabase`.\"\n            )\n        self._client = client\n        self._embedding: Embeddings = embedding\n        self.table_name = table_name or \"documents\"\n        self.query_name = query_name or \"match_documents\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html"}
{"id": "9cdde1982c83-2", "text": "self.query_name = query_name or \"match_documents\"\n        self.chunk_size = chunk_size or 500\n        # According to the SupabaseVectorStore JS implementation, the best chunk size\n        # is 500. Though for large datasets it can be too large so it is configurable.\n    @property\n    def embeddings(self) -> Embeddings:\n        return self._embedding\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[Dict[Any, Any]]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        ids = ids or [str(uuid.uuid4()) for _ in texts]\n        docs = self._texts_to_documents(texts, metadatas)\n        vectors = self._embedding.embed_documents(list(texts))\n        return self.add_vectors(vectors, docs, ids)\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[\"SupabaseVectorStore\"],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        client: Optional[supabase.client.Client] = None,\n        table_name: Optional[str] = \"documents\",\n        query_name: Union[str, None] = \"match_documents\",\n        chunk_size: int = 500,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> \"SupabaseVectorStore\":\n        \"\"\"Return VectorStore initialized from texts and embeddings.\"\"\"\n        if not client:\n            raise ValueError(\"Supabase client is required.\")\n        if not table_name:\n            raise ValueError(\"Supabase document table_name is required.\")\n        embeddings = embedding.embed_documents(texts)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html"}
{"id": "9cdde1982c83-3", "text": "embeddings = embedding.embed_documents(texts)\n        ids = [str(uuid.uuid4()) for _ in texts]\n        docs = cls._texts_to_documents(texts, metadatas)\n        cls._add_vectors(client, table_name, embeddings, docs, ids, chunk_size)\n        return cls(\n            client=client,\n            embedding=embedding,\n            table_name=table_name,\n            query_name=query_name,\n            chunk_size=chunk_size,\n        )\n[docs]    def add_vectors(\n        self,\n        vectors: List[List[float]],\n        documents: List[Document],\n        ids: List[str],\n    ) -> List[str]:\n        return self._add_vectors(\n            self._client, self.table_name, vectors, documents, ids, self.chunk_size\n        )\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        vector = self._embedding.embed_query(query)\n        return self.similarity_search_by_vector(vector, k=k, filter=filter, **kwargs)\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        result = self.similarity_search_by_vector_with_relevance_scores(\n            embedding, k=k, filter=filter, **kwargs\n        )\n        documents = [doc for doc, _ in result]\n        return documents\n[docs]    def similarity_search_with_relevance_scores(\n        self,\n        query: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html"}
{"id": "9cdde1982c83-4", "text": "self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        vector = self._embedding.embed_query(query)\n        return self.similarity_search_by_vector_with_relevance_scores(\n            vector, k=k, filter=filter\n        )\n[docs]    def match_args(\n        self, query: List[float], filter: Optional[Dict[str, Any]]\n    ) -> Dict[str, Any]:\n        ret: Dict[str, Any] = dict(query_embedding=query)\n        if filter:\n            ret[\"filter\"] = filter\n        return ret\n[docs]    def similarity_search_by_vector_with_relevance_scores(\n        self,\n        query: List[float],\n        k: int,\n        filter: Optional[Dict[str, Any]] = None,\n        postgrest_filter: Optional[str] = None,\n    ) -> List[Tuple[Document, float]]:\n        match_documents_params = self.match_args(query, filter)\n        query_builder = self._client.rpc(self.query_name, match_documents_params)\n        if postgrest_filter:\n            query_builder.params = query_builder.params.set(\n                \"and\", f\"({postgrest_filter})\"\n            )\n        query_builder.params = query_builder.params.set(\"limit\", k)\n        res = query_builder.execute()\n        match_result = [\n            (\n                Document(\n                    metadata=search.get(\"metadata\", {}),  # type: ignore\n                    page_content=search.get(\"content\", \"\"),\n                ),\n                search.get(\"similarity\", 0.0),\n            )\n            for search in res.data\n            if search.get(\"content\")\n        ]\n        return match_result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html"}
{"id": "9cdde1982c83-5", "text": "if search.get(\"content\")\n        ]\n        return match_result\n[docs]    def similarity_search_by_vector_returning_embeddings(\n        self,\n        query: List[float],\n        k: int,\n        filter: Optional[Dict[str, Any]] = None,\n        postgrest_filter: Optional[str] = None,\n    ) -> List[Tuple[Document, float, np.ndarray[np.float32, Any]]]:\n        match_documents_params = self.match_args(query, filter)\n        query_builder = self._client.rpc(self.query_name, match_documents_params)\n        if postgrest_filter:\n            query_builder.params = query_builder.params.set(\n                \"and\", f\"({postgrest_filter})\"\n            )\n        query_builder.params = query_builder.params.set(\"limit\", k)\n        res = query_builder.execute()\n        match_result = [\n            (\n                Document(\n                    metadata=search.get(\"metadata\", {}),  # type: ignore\n                    page_content=search.get(\"content\", \"\"),\n                ),\n                search.get(\"similarity\", 0.0),\n                # Supabase returns a vector type as its string represation (!).\n                # This is a hack to convert the string to numpy array.\n                np.fromstring(\n                    search.get(\"embedding\", \"\").strip(\"[]\"), np.float32, sep=\",\"\n                ),\n            )\n            for search in res.data\n            if search.get(\"content\")\n        ]\n        return match_result\n    @staticmethod\n    def _texts_to_documents(\n        texts: Iterable[str],\n        metadatas: Optional[Iterable[Dict[Any, Any]]] = None,\n    ) -> List[Document]:\n        \"\"\"Return list of Documents from list of texts and metadatas.\"\"\"\n        if metadatas is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html"}
{"id": "9cdde1982c83-6", "text": "if metadatas is None:\n            metadatas = repeat({})\n        docs = [\n            Document(page_content=text, metadata=metadata)\n            for text, metadata in zip(texts, metadatas)\n        ]\n        return docs\n    @staticmethod\n    def _add_vectors(\n        client: supabase.client.Client,\n        table_name: str,\n        vectors: List[List[float]],\n        documents: List[Document],\n        ids: List[str],\n        chunk_size: int,\n    ) -> List[str]:\n        \"\"\"Add vectors to Supabase table.\"\"\"\n        rows: List[Dict[str, Any]] = [\n            {\n                \"id\": ids[idx],\n                \"content\": documents[idx].page_content,\n                \"embedding\": embedding,\n                \"metadata\": documents[idx].metadata,  # type: ignore\n            }\n            for idx, embedding in enumerate(vectors)\n        ]\n        id_list: List[str] = []\n        for i in range(0, len(rows), chunk_size):\n            chunk = rows[i : i + chunk_size]\n            result = client.from_(table_name).upsert(chunk).execute()  # type: ignore\n            if len(result.data) == 0:\n                raise Exception(\"Error inserting: No rows added\")\n            # VectorStore.add_vectors returns ids as strings\n            ids = [str(i.get(\"id\")) for i in result.data if i.get(\"id\")]\n            id_list.extend(ids)\n        return id_list\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html"}
{"id": "9cdde1982c83-7", "text": "lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        result = self.similarity_search_by_vector_returning_embeddings(\n            embedding, fetch_k\n        )\n        matched_documents = [doc_tuple[0] for doc_tuple in result]\n        matched_embeddings = [doc_tuple[2] for doc_tuple in result]\n        mmr_selected = maximal_marginal_relevance(\n            np.array([embedding], dtype=np.float32),\n            matched_embeddings,\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        filtered_documents = [matched_documents[i] for i in mmr_selected]\n        return filtered_documents\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html"}
{"id": "9cdde1982c83-8", "text": "Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        `max_marginal_relevance_search` requires that `query_name` returns matched\n        embeddings alongside the match documents. The following function\n        demonstrates how to do this:\n        ```sql\n        CREATE FUNCTION match_documents_embeddings(query_embedding vector(1536),\n                                                   match_count int)\n            RETURNS TABLE(\n                id uuid,\n                content text,\n                metadata jsonb,\n                embedding vector(1536),\n                similarity float)\n            LANGUAGE plpgsql\n            AS $$\n            # variable_conflict use_column\n        BEGIN\n            RETURN query\n            SELECT\n                id,\n                content,\n                metadata,\n                embedding,\n                1 -(docstore.embedding <=> query_embedding) AS similarity\n            FROM\n                docstore\n            ORDER BY\n                docstore.embedding <=> query_embedding\n            LIMIT match_count;\n        END;\n        $$;\n        ```\n        \"\"\"\n        embedding = self._embedding.embed_query(query)\n        docs = self.max_marginal_relevance_search_by_vector(\n            embedding, k, fetch_k, lambda_mult=lambda_mult\n        )\n        return docs\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html"}
{"id": "9cdde1982c83-9", "text": "\"\"\"Delete by vector IDs.\n        Args:\n            ids: List of ids to delete.\n        \"\"\"\n        if ids is None:\n            raise ValueError(\"No ids provided to delete.\")\n        rows: List[Dict[str, Any]] = [\n            {\n                \"id\": id,\n            }\n            for id in ids\n        ]\n        # TODO: Check if this can be done in bulk\n        for row in rows:\n            self._client.from_(self.table_name).delete().eq(\"id\", row[\"id\"]).execute()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html"}
{"id": "950c0400f22a-0", "text": "Source code for langchain.vectorstores.sqlitevss\nfrom __future__ import annotations\nimport json\nimport logging\nimport warnings\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n)\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nif TYPE_CHECKING:\n    import sqlite3\nlogger = logging.getLogger(__name__)\n[docs]class SQLiteVSS(VectorStore):\n    \"\"\"Wrapper around SQLite with vss extension as a vector database.\n    To use, you should have the ``sqlite-vss`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import SQLiteVSS\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            ...\n    \"\"\"\n[docs]    def __init__(\n        self,\n        table: str,\n        connection: Optional[sqlite3.Connection],\n        embedding: Embeddings,\n        db_file: str = \"vss.db\",\n    ):\n        \"\"\"Initialize with sqlite client with vss extension.\"\"\"\n        try:\n            import sqlite_vss  # noqa  # pylint: disable=unused-import\n        except ImportError:\n            raise ImportError(\n                \"Could not import sqlite-vss python package. \"\n                \"Please install it with `pip install sqlite-vss`.\"\n            )\n        if not connection:\n            connection = self.create_connection(db_file)\n        if not isinstance(embedding, Embeddings):\n            warnings.warn(\"embeddings input must be Embeddings object.\")\n        self._connection = connection\n        self._table = table\n        self._embedding = embedding\n        self.create_table_if_not_exists()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sqlitevss.html"}
{"id": "950c0400f22a-1", "text": "self._embedding = embedding\n        self.create_table_if_not_exists()\n[docs]    def create_table_if_not_exists(self) -> None:\n        self._connection.execute(\n            f\"\"\"\n            CREATE TABLE IF NOT EXISTS {self._table}\n            (\n              rowid INTEGER PRIMARY KEY AUTOINCREMENT,\n              text TEXT,\n              metadata BLOB,\n              text_embedding BLOB\n            )\n            ;\n            \"\"\"\n        )\n        self._connection.execute(\n            f\"\"\"\n                CREATE VIRTUAL TABLE IF NOT EXISTS vss_{self._table} USING vss0(\n                  text_embedding({self.get_dimensionality()})\n                );\n            \"\"\"\n        )\n        self._connection.execute(\n            f\"\"\"\n                CREATE TRIGGER IF NOT EXISTS embed_text \n                AFTER INSERT ON {self._table}\n                BEGIN\n                    INSERT INTO vss_{self._table}(rowid, text_embedding)\n                    VALUES (new.rowid, new.text_embedding) \n                    ;\n                END;\n            \"\"\"\n        )\n        self._connection.commit()\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add more texts to the vectorstore index.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        \"\"\"\n        max_id = self._connection.execute(\n            f\"SELECT max(rowid) as rowid FROM {self._table}\"\n        ).fetchone()[\"rowid\"]\n        if max_id is None:  # no text added yet\n            max_id = 0", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sqlitevss.html"}
{"id": "950c0400f22a-2", "text": "max_id = 0\n        embeds = self._embedding.embed_documents(list(texts))\n        if not metadatas:\n            metadatas = [{} for _ in texts]\n        data_input = [\n            (text, json.dumps(metadata), json.dumps(embed))\n            for text, metadata, embed in zip(texts, metadatas, embeds)\n        ]\n        self._connection.executemany(\n            f\"INSERT INTO {self._table}(text, metadata, text_embedding) \"\n            f\"VALUES (?,?,?)\",\n            data_input,\n        )\n        self._connection.commit()\n        # pulling every ids we just inserted\n        results = self._connection.execute(\n            f\"SELECT rowid FROM {self._table} WHERE rowid > {max_id}\"\n        )\n        return [row[\"rowid\"] for row in results]\n[docs]    def similarity_search_with_score_by_vector(\n        self, embedding: List[float], k: int = 4, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        sql_query = f\"\"\"\n            SELECT \n                text,\n                metadata,\n                distance\n            FROM {self._table} e\n            INNER JOIN vss_{self._table} v on v.rowid = e.rowid  \n            WHERE vss_search(\n              v.text_embedding,\n              vss_search_params('{json.dumps(embedding)}', {k})\n            )\n        \"\"\"\n        cursor = self._connection.cursor()\n        cursor.execute(sql_query)\n        results = cursor.fetchall()\n        documents = []\n        for row in results:\n            metadata = json.loads(row[\"metadata\"]) or {}\n            doc = Document(page_content=row[\"text\"], metadata=metadata)\n            documents.append((doc, row[\"distance\"]))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sqlitevss.html"}
{"id": "950c0400f22a-3", "text": "documents.append((doc, row[\"distance\"]))\n        return documents\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\"\"\"\n        embedding = self._embedding.embed_query(query)\n        documents = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k\n        )\n        return [doc for doc, _ in documents]\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\"\"\"\n        embedding = self._embedding.embed_query(query)\n        documents = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k\n        )\n        return documents\n[docs]    def similarity_search_by_vector(\n        self, embedding: List[float], k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        documents = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k\n        )\n        return [doc for doc, _ in documents]\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[SQLiteVSS],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        table: str = \"langchain\",\n        db_file: str = \"vss.db\",\n        **kwargs: Any,\n    ) -> SQLiteVSS:\n        \"\"\"Return VectorStore initialized from texts and embeddings.\"\"\"\n        connection = cls.create_connection(db_file)\n        vss = cls(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sqlitevss.html"}
{"id": "950c0400f22a-4", "text": "connection = cls.create_connection(db_file)\n        vss = cls(\n            table=table, connection=connection, db_file=db_file, embedding=embedding\n        )\n        vss.add_texts(texts=texts, metadatas=metadatas)\n        return vss\n[docs]    @staticmethod\n    def create_connection(db_file: str) -> sqlite3.Connection:\n        import sqlite3\n        import sqlite_vss\n        connection = sqlite3.connect(db_file)\n        connection.row_factory = sqlite3.Row\n        connection.enable_load_extension(True)\n        sqlite_vss.load(connection)\n        connection.enable_load_extension(False)\n        return connection\n[docs]    def get_dimensionality(self) -> int:\n        \"\"\"\n        Function that does a dummy embedding to figure out how many dimensions\n        this embedding function returns. Needed for the virtual table DDL.\n        \"\"\"\n        dummy_text = \"This is a dummy text\"\n        dummy_embedding = self._embedding.embed_query(dummy_text)\n        return len(dummy_embedding)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sqlitevss.html"}
{"id": "2afc1092a31b-0", "text": "Source code for langchain.vectorstores.awadb\nfrom __future__ import annotations\nimport logging\nimport uuid\nfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Set, Tuple, Type\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nif TYPE_CHECKING:\n    import awadb\nlogger = logging.getLogger()\nDEFAULT_TOPN = 4\n[docs]class AwaDB(VectorStore):\n    \"\"\"`AwaDB` vector store.\"\"\"\n    _DEFAULT_TABLE_NAME = \"langchain_awadb\"\n[docs]    def __init__(\n        self,\n        table_name: str = _DEFAULT_TABLE_NAME,\n        embedding: Optional[Embeddings] = None,\n        log_and_data_dir: Optional[str] = None,\n        client: Optional[awadb.Client] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Initialize with AwaDB client.\n           If table_name is not specified,\n           a random table name of `_DEFAULT_TABLE_NAME + last segment of uuid`\n           would be created automatically.\n        Args:\n            table_name: Name of the table created, default _DEFAULT_TABLE_NAME.\n            embedding: Optional Embeddings initially set.\n            log_and_data_dir: Optional the root directory of log and data.\n            client: Optional AwaDB client.\n            kwargs: Any possible extend parameters in the future.\n        Returns:\n            None.\n        \"\"\"\n        try:\n            import awadb\n        except ImportError:\n            raise ImportError(\n                \"Could not import awadb python package. \"\n                \"Please install it with `pip install awadb`.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html"}
{"id": "2afc1092a31b-1", "text": "\"Please install it with `pip install awadb`.\"\n            )\n        if client is not None:\n            self.awadb_client = client\n        else:\n            if log_and_data_dir is not None:\n                self.awadb_client = awadb.Client(log_and_data_dir)\n            else:\n                self.awadb_client = awadb.Client()\n        if table_name == self._DEFAULT_TABLE_NAME:\n            table_name += \"_\"\n            table_name += str(uuid.uuid4()).split(\"-\")[-1]\n        self.awadb_client.Create(table_name)\n        self.table2embeddings: dict[str, Embeddings] = {}\n        if embedding is not None:\n            self.table2embeddings[table_name] = embedding\n        self.using_table_name = table_name\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        if self.using_table_name in self.table2embeddings:\n            return self.table2embeddings[self.using_table_name]\n        return None\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        is_duplicate_texts: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            is_duplicate_texts: Optional whether to duplicate texts. Defaults to True.\n            kwargs: any possible extend parameters in the future.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        if self.awadb_client is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html"}
{"id": "2afc1092a31b-2", "text": "\"\"\"\n        if self.awadb_client is None:\n            raise ValueError(\"AwaDB client is None!!!\")\n        embeddings = None\n        if self.using_table_name in self.table2embeddings:\n            embeddings = self.table2embeddings[self.using_table_name].embed_documents(\n                list(texts)\n            )\n        return self.awadb_client.AddTexts(\n            \"embedding_text\",\n            \"text_embedding\",\n            texts,\n            embeddings,\n            metadatas,\n            is_duplicate_texts,\n        )\n[docs]    def load_local(\n        self,\n        table_name: str,\n        **kwargs: Any,\n    ) -> bool:\n        \"\"\"Load the local specified table.\n        Args:\n            table_name: Table name\n            kwargs: Any possible extend parameters in the future.\n        Returns:\n            Success or failure of loading the local specified table\n        \"\"\"\n        if self.awadb_client is None:\n            raise ValueError(\"AwaDB client is None!!!\")\n        return self.awadb_client.Load(table_name)\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = DEFAULT_TOPN,\n        text_in_page_content: Optional[str] = None,\n        meta_filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text query.\n            k: The maximum number of documents to return.\n            text_in_page_content: Filter by the text in page_content of Document.\n            meta_filter (Optional[dict]): Filter by metadata. Defaults to None.\n            E.g. `{\"color\" : \"red\", \"price\": 4.20}`. Optional.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html"}
{"id": "2afc1092a31b-3", "text": "E.g. `{\"max_price\" : 15.66, \"min_price\": 4.20}`\n            `price` is the metadata field, means range filter(4.20<'price'<15.66).\n            E.g. `{\"maxe_price\" : 15.66, \"mine_price\": 4.20}`\n            `price` is the metadata field, means range filter(4.20<='price'<=15.66).\n            kwargs: Any possible extend parameters in the future.\n        Returns:\n            Returns the k most similar documents to the specified text query.\n        \"\"\"\n        if self.awadb_client is None:\n            raise ValueError(\"AwaDB client is None!!!\")\n        embedding = None\n        if self.using_table_name in self.table2embeddings:\n            embedding = self.table2embeddings[self.using_table_name].embed_query(query)\n        else:\n            from awadb import AwaEmbedding\n            embedding = AwaEmbedding().Embedding(query)\n        not_include_fields: Set[str] = {\"text_embedding\", \"_id\", \"score\"}\n        return self.similarity_search_by_vector(\n            embedding,\n            k,\n            text_in_page_content=text_in_page_content,\n            meta_filter=meta_filter,\n            not_include_fields_in_metadata=not_include_fields,\n        )\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = DEFAULT_TOPN,\n        text_in_page_content: Optional[str] = None,\n        meta_filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"The most k similar documents and scores of the specified query.\n        Args:\n            query: Text query.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html"}
{"id": "2afc1092a31b-4", "text": "Args:\n            query: Text query.\n            k: The k most similar documents to the text query.\n            text_in_page_content: Filter by the text in page_content of Document.\n            meta_filter: Filter by metadata. Defaults to None.\n            kwargs: Any possible extend parameters in the future.\n        Returns:\n            The k most similar documents to the specified text query.\n            0 is dissimilar, 1 is the most similar.\n        \"\"\"\n        if self.awadb_client is None:\n            raise ValueError(\"AwaDB client is None!!!\")\n        embedding = None\n        if self.using_table_name in self.table2embeddings:\n            embedding = self.table2embeddings[self.using_table_name].embed_query(query)\n        else:\n            from awadb import AwaEmbedding\n            embedding = AwaEmbedding().Embedding(query)\n        results: List[Tuple[Document, float]] = []\n        not_include_fields: Set[str] = {\"text_embedding\", \"_id\"}\n        retrieval_docs = self.similarity_search_by_vector(\n            embedding,\n            k,\n            text_in_page_content=text_in_page_content,\n            meta_filter=meta_filter,\n            not_include_fields_in_metadata=not_include_fields,\n        )\n        for doc in retrieval_docs:\n            score = doc.metadata[\"score\"]\n            del doc.metadata[\"score\"]\n            doc_tuple = (doc, score)\n            results.append(doc_tuple)\n        return results\n    def _similarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        return self.similarity_search_with_score(query, k, **kwargs)\n[docs]    def similarity_search_by_vector(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html"}
{"id": "2afc1092a31b-5", "text": "[docs]    def similarity_search_by_vector(\n        self,\n        embedding: Optional[List[float]] = None,\n        k: int = DEFAULT_TOPN,\n        text_in_page_content: Optional[str] = None,\n        meta_filter: Optional[dict] = None,\n        not_include_fields_in_metadata: Optional[Set[str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            text_in_page_content: Filter by the text in page_content of Document.\n            meta_filter: Filter by metadata. Defaults to None.\n            not_incude_fields_in_metadata: Not include meta fields of each document.\n        Returns:\n            List of Documents which are the most similar to the query vector.\n        \"\"\"\n        if self.awadb_client is None:\n            raise ValueError(\"AwaDB client is None!!!\")\n        results: List[Document] = []\n        if embedding is None:\n            return results\n        show_results = self.awadb_client.Search(\n            embedding,\n            k,\n            text_in_page_content=text_in_page_content,\n            meta_filter=meta_filter,\n            not_include_fields=not_include_fields_in_metadata,\n        )\n        if show_results.__len__() == 0:\n            return results\n        for item_detail in show_results[0][\"ResultItems\"]:\n            content = \"\"\n            meta_data = {}\n            for item_key in item_detail:\n                if item_key == \"embedding_text\":\n                    content = item_detail[item_key]\n                    continue\n                elif not_include_fields_in_metadata is not None:\n                    if item_key in not_include_fields_in_metadata:\n                        continue", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html"}
{"id": "2afc1092a31b-6", "text": "if item_key in not_include_fields_in_metadata:\n                        continue\n                meta_data[item_key] = item_detail[item_key]\n            results.append(Document(page_content=content, metadata=meta_data))\n        return results\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        text_in_page_content: Optional[str] = None,\n        meta_filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            text_in_page_content: Filter by the text in page_content of Document.\n            meta_filter (Optional[dict]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        if self.awadb_client is None:\n            raise ValueError(\"AwaDB client is None!!!\")\n        embedding: List[float] = []\n        if self.using_table_name in self.table2embeddings:\n            embedding = self.table2embeddings[self.using_table_name].embed_query(query)\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html"}
{"id": "2afc1092a31b-7", "text": "else:\n            from awadb import AwaEmbedding\n            embedding = AwaEmbedding().Embedding(query)\n        if embedding.__len__() == 0:\n            return []\n        results = self.max_marginal_relevance_search_by_vector(\n            embedding,\n            k,\n            fetch_k,\n            lambda_mult=lambda_mult,\n            text_in_page_content=text_in_page_content,\n            meta_filter=meta_filter,\n        )\n        return results\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        text_in_page_content: Optional[str] = None,\n        meta_filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            text_in_page_content: Filter by the text in page_content of Document.\n            meta_filter (Optional[dict]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        if self.awadb_client is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html"}
{"id": "2afc1092a31b-8", "text": "\"\"\"\n        if self.awadb_client is None:\n            raise ValueError(\"AwaDB client is None!!!\")\n        results: List[Document] = []\n        if embedding is None:\n            return results\n        not_include_fields: set = {\"_id\", \"score\"}\n        retrieved_docs = self.similarity_search_by_vector(\n            embedding,\n            fetch_k,\n            text_in_page_content=text_in_page_content,\n            meta_filter=meta_filter,\n            not_include_fields_in_metadata=not_include_fields,\n        )\n        top_embeddings = []\n        for doc in retrieved_docs:\n            top_embeddings.append(doc.metadata[\"text_embedding\"])\n        selected_docs = maximal_marginal_relevance(\n            np.array(embedding, dtype=np.float32), embedding_list=top_embeddings\n        )\n        for s_id in selected_docs:\n            if \"text_embedding\" in retrieved_docs[s_id].metadata:\n                del retrieved_docs[s_id].metadata[\"text_embedding\"]\n                results.append(retrieved_docs[s_id])\n        return results\n[docs]    def get(\n        self,\n        ids: Optional[List[str]] = None,\n        text_in_page_content: Optional[str] = None,\n        meta_filter: Optional[dict] = None,\n        not_include_fields: Optional[Set[str]] = None,\n        limit: Optional[int] = None,\n        **kwargs: Any,\n    ) -> Dict[str, Document]:\n        \"\"\"Return docs according ids.\n        Args:\n            ids: The ids of the embedding vectors.\n            text_in_page_content: Filter by the text in page_content of Document.\n            meta_filter: Filter by any metadata of the document.\n            not_include_fields: Not pack the specified fields of each document.\n            limit: The number of documents to return. Defaults to 5. Optional.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html"}
{"id": "2afc1092a31b-9", "text": "limit: The number of documents to return. Defaults to 5. Optional.\n        Returns:\n            Documents which satisfy the input conditions.\n        \"\"\"\n        if self.awadb_client is None:\n            raise ValueError(\"AwaDB client is None!!!\")\n        docs_detail = self.awadb_client.Get(\n            ids=ids,\n            text_in_page_content=text_in_page_content,\n            meta_filter=meta_filter,\n            not_include_fields=not_include_fields,\n            limit=limit,\n        )\n        results: Dict[str, Document] = {}\n        for doc_detail in docs_detail:\n            content = \"\"\n            meta_info = {}\n            for field in doc_detail:\n                if field == \"embedding_text\":\n                    content = doc_detail[field]\n                    continue\n                elif field == \"text_embedding\" or field == \"_id\":\n                    continue\n                meta_info[field] = doc_detail[field]\n            doc = Document(page_content=content, metadata=meta_info)\n            results[doc_detail[\"_id\"]] = doc\n        return results\n[docs]    def delete(\n        self,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Optional[bool]:\n        \"\"\"Delete the documents which have the specified ids.\n        Args:\n            ids: The ids of the embedding vectors.\n            **kwargs: Other keyword arguments that subclasses might use.\n        Returns:\n            Optional[bool]: True if deletion is successful.\n            False otherwise, None if not implemented.\n        \"\"\"\n        if self.awadb_client is None:\n            raise ValueError(\"AwaDB client is None!!!\")\n        ret: Optional[bool] = None\n        if ids is None or ids.__len__() == 0:\n            return ret\n        ret = self.awadb_client.Delete(ids)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html"}
{"id": "2afc1092a31b-10", "text": "return ret\n        ret = self.awadb_client.Delete(ids)\n        return ret\n[docs]    def update(\n        self,\n        ids: List[str],\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Update the documents which have the specified ids.\n        Args:\n            ids: The id list of the updating embedding vector.\n            texts: The texts of the updating documents.\n            metadatas: The metadatas of the updating documents.\n        Returns:\n            the ids of the updated documents.\n        \"\"\"\n        if self.awadb_client is None:\n            raise ValueError(\"AwaDB client is None!!!\")\n        return self.awadb_client.UpdateTexts(\n            ids=ids, text_field_name=\"embedding_text\", texts=texts, metadatas=metadatas\n        )\n[docs]    def create_table(\n        self,\n        table_name: str,\n        **kwargs: Any,\n    ) -> bool:\n        \"\"\"Create a new table.\"\"\"\n        if self.awadb_client is None:\n            return False\n        ret = self.awadb_client.Create(table_name)\n        if ret:\n            self.using_table_name = table_name\n        return ret\n[docs]    def use(\n        self,\n        table_name: str,\n        **kwargs: Any,\n    ) -> bool:\n        \"\"\"Use the specified table. Don't know the tables, please invoke list_tables.\"\"\"\n        if self.awadb_client is None:\n            return False\n        ret = self.awadb_client.Use(table_name)\n        if ret:\n            self.using_table_name = table_name\n        return ret\n[docs]    def list_tables(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html"}
{"id": "2afc1092a31b-11", "text": "return ret\n[docs]    def list_tables(\n        self,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"List all the tables created by the client.\"\"\"\n        if self.awadb_client is None:\n            return []\n        return self.awadb_client.ListAllTables()\n[docs]    def get_current_table(\n        self,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Get the current table.\"\"\"\n        return self.using_table_name\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[AwaDB],\n        texts: List[str],\n        embedding: Optional[Embeddings] = None,\n        metadatas: Optional[List[dict]] = None,\n        table_name: str = _DEFAULT_TABLE_NAME,\n        log_and_data_dir: Optional[str] = None,\n        client: Optional[awadb.Client] = None,\n        **kwargs: Any,\n    ) -> AwaDB:\n        \"\"\"Create an AwaDB vectorstore from a raw documents.\n        Args:\n            texts (List[str]): List of texts to add to the table.\n            embedding (Optional[Embeddings]): Embedding function. Defaults to None.\n            metadatas (Optional[List[dict]]): List of metadatas. Defaults to None.\n            table_name (str): Name of the table to create.\n            log_and_data_dir (Optional[str]): Directory of logging and persistence.\n            client (Optional[awadb.Client]): AwaDB client\n        Returns:\n            AwaDB: AwaDB vectorstore.\n        \"\"\"\n        awadb_client = cls(\n            table_name=table_name,\n            embedding=embedding,\n            log_and_data_dir=log_and_data_dir,\n            client=client,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html"}
{"id": "2afc1092a31b-12", "text": "log_and_data_dir=log_and_data_dir,\n            client=client,\n        )\n        awadb_client.add_texts(texts=texts, metadatas=metadatas)\n        return awadb_client\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[AwaDB],\n        documents: List[Document],\n        embedding: Optional[Embeddings] = None,\n        table_name: str = _DEFAULT_TABLE_NAME,\n        log_and_data_dir: Optional[str] = None,\n        client: Optional[awadb.Client] = None,\n        **kwargs: Any,\n    ) -> AwaDB:\n        \"\"\"Create an AwaDB vectorstore from a list of documents.\n        If a log_and_data_dir specified, the table will be persisted there.\n        Args:\n            documents (List[Document]): List of documents to add to the vectorstore.\n            embedding (Optional[Embeddings]): Embedding function. Defaults to None.\n            table_name (str): Name of the table to create.\n            log_and_data_dir (Optional[str]): Directory to persist the table.\n            client (Optional[awadb.Client]): AwaDB client.\n            Any: Any possible parameters in the future\n        Returns:\n            AwaDB: AwaDB vectorstore.\n        \"\"\"\n        texts = [doc.page_content for doc in documents]\n        metadatas = [doc.metadata for doc in documents]\n        return cls.from_texts(\n            texts=texts,\n            embedding=embedding,\n            metadatas=metadatas,\n            table_name=table_name,\n            log_and_data_dir=log_and_data_dir,\n            client=client,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html"}
{"id": "8f68c7541f78-0", "text": "Source code for langchain.vectorstores.pgembedding\nfrom __future__ import annotations\nimport logging\nimport uuid\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Type\nimport sqlalchemy\nfrom sqlalchemy import func\nfrom sqlalchemy.dialects.postgresql import JSON, UUID\nfrom sqlalchemy.orm import Session, relationship\ntry:\n    from sqlalchemy.orm import declarative_base\nexcept ImportError:\n    from sqlalchemy.ext.declarative import declarative_base\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_dict_or_env\nBase = declarative_base()  # type: Any\nADA_TOKEN_COUNT = 1536\n_LANGCHAIN_DEFAULT_COLLECTION_NAME = \"langchain\"\n[docs]class BaseModel(Base):\n    \"\"\"Base model for all SQL stores.\"\"\"\n    __abstract__ = True\n    uuid = sqlalchemy.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)\n[docs]class CollectionStore(BaseModel):\n    \"\"\"Collection store.\"\"\"\n    __tablename__ = \"langchain_pg_collection\"\n    name = sqlalchemy.Column(sqlalchemy.String)\n    cmetadata = sqlalchemy.Column(JSON)\n    embeddings = relationship(\n        \"EmbeddingStore\",\n        back_populates=\"collection\",\n        passive_deletes=True,\n    )\n[docs]    @classmethod\n    def get_by_name(cls, session: Session, name: str) -> Optional[\"CollectionStore\"]:\n        return session.query(cls).filter(cls.name == name).first()  # type: ignore\n[docs]    @classmethod\n    def get_or_create(\n        cls,\n        session: Session,\n        name: str,\n        cmetadata: Optional[dict] = None,\n    ) -> Tuple[\"CollectionStore\", bool]:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html"}
{"id": "8f68c7541f78-1", "text": ") -> Tuple[\"CollectionStore\", bool]:\n        \"\"\"\n        Get or create a collection.\n        Returns [Collection, bool] where the bool is True if the collection was created.\n        \"\"\"\n        created = False\n        collection = cls.get_by_name(session, name)\n        if collection:\n            return collection, created\n        collection = cls(name=name, cmetadata=cmetadata)\n        session.add(collection)\n        session.commit()\n        created = True\n        return collection, created\n[docs]class EmbeddingStore(BaseModel):\n    \"\"\"Embedding store.\"\"\"\n    __tablename__ = \"langchain_pg_embedding\"\n    collection_id = sqlalchemy.Column(\n        UUID(as_uuid=True),\n        sqlalchemy.ForeignKey(\n            f\"{CollectionStore.__tablename__}.uuid\",\n            ondelete=\"CASCADE\",\n        ),\n    )\n    collection = relationship(CollectionStore, back_populates=\"embeddings\")\n    embedding = sqlalchemy.Column(sqlalchemy.ARRAY(sqlalchemy.REAL))  # type: ignore\n    document = sqlalchemy.Column(sqlalchemy.String, nullable=True)\n    cmetadata = sqlalchemy.Column(JSON, nullable=True)\n    # custom_id : any user defined id\n    custom_id = sqlalchemy.Column(sqlalchemy.String, nullable=True)\n[docs]class QueryResult:\n    \"\"\"Result from a query.\"\"\"\n    EmbeddingStore: EmbeddingStore\n    distance: float\n[docs]class PGEmbedding(VectorStore):\n    \"\"\"`Postgres` with the `pg_embedding` extension as a vector store.\n    pg_embedding uses sequential scan by default. but you can create a HNSW index\n    using the create_hnsw_index method.\n    - `connection_string` is a postgres connection string.\n    - `embedding_function` any embedding function implementing\n        `langchain.embeddings.base.Embeddings` interface.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html"}
{"id": "8f68c7541f78-2", "text": "`langchain.embeddings.base.Embeddings` interface.\n    - `collection_name` is the name of the collection to use. (default: langchain)\n        - NOTE: This is not the name of the table, but the name of the collection.\n            The tables will be created when initializing the store (if not exists)\n            So, make sure the user has the right permissions to create tables.\n    - `distance_strategy` is the distance strategy to use. (default: EUCLIDEAN)\n        - `EUCLIDEAN` is the euclidean distance.\n    - `pre_delete_collection` if True, will delete the collection if it exists.\n        (default: False)\n        - Useful for testing.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        connection_string: str,\n        embedding_function: Embeddings,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        collection_metadata: Optional[dict] = None,\n        pre_delete_collection: bool = False,\n        logger: Optional[logging.Logger] = None,\n    ) -> None:\n        self.connection_string = connection_string\n        self.embedding_function = embedding_function\n        self.collection_name = collection_name\n        self.collection_metadata = collection_metadata\n        self.pre_delete_collection = pre_delete_collection\n        self.logger = logger or logging.getLogger(__name__)\n        self.__post_init__()\n    def __post_init__(\n        self,\n    ) -> None:\n        self._conn = self.connect()\n        self.create_hnsw_extension()\n        self.create_tables_if_not_exists()\n        self.create_collection()\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding_function\n[docs]    def connect(self) -> sqlalchemy.engine.Connection:\n        engine = sqlalchemy.create_engine(self.connection_string)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html"}
{"id": "8f68c7541f78-3", "text": "engine = sqlalchemy.create_engine(self.connection_string)\n        conn = engine.connect()\n        return conn\n[docs]    def create_hnsw_extension(self) -> None:\n        try:\n            with Session(self._conn) as session:\n                statement = sqlalchemy.text(\"CREATE EXTENSION IF NOT EXISTS embedding\")\n                session.execute(statement)\n                session.commit()\n        except Exception as e:\n            self.logger.exception(e)\n[docs]    def create_tables_if_not_exists(self) -> None:\n        with self._conn.begin():\n            Base.metadata.create_all(self._conn)\n[docs]    def drop_tables(self) -> None:\n        with self._conn.begin():\n            Base.metadata.drop_all(self._conn)\n[docs]    def create_collection(self) -> None:\n        if self.pre_delete_collection:\n            self.delete_collection()\n        with Session(self._conn) as session:\n            CollectionStore.get_or_create(\n                session, self.collection_name, cmetadata=self.collection_metadata\n            )\n[docs]    def create_hnsw_index(\n        self,\n        max_elements: int = 10000,\n        dims: int = ADA_TOKEN_COUNT,\n        m: int = 8,\n        ef_construction: int = 16,\n        ef_search: int = 16,\n    ) -> None:\n        create_index_query = sqlalchemy.text(\n            \"CREATE INDEX IF NOT EXISTS langchain_pg_embedding_idx \"\n            \"ON langchain_pg_embedding USING hnsw (embedding) \"\n            \"WITH (\"\n            \"maxelements = {}, \"\n            \"dims = {}, \"\n            \"m = {}, \"\n            \"efconstruction = {}, \"\n            \"efsearch = {}\"\n            \");\".format(max_elements, dims, m, ef_construction, ef_search)\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html"}
{"id": "8f68c7541f78-4", "text": ")\n        # Execute the queries\n        try:\n            with Session(self._conn) as session:\n                # Create the HNSW index\n                session.execute(create_index_query)\n                session.commit()\n            print(\"HNSW extension and index created successfully.\")\n        except Exception as e:\n            print(f\"Failed to create HNSW extension or index: {e}\")\n[docs]    def delete_collection(self) -> None:\n        self.logger.debug(\"Trying to delete collection\")\n        with Session(self._conn) as session:\n            collection = self.get_collection(session)\n            if not collection:\n                self.logger.warning(\"Collection not found\")\n                return\n            session.delete(collection)\n            session.commit()\n[docs]    def get_collection(self, session: Session) -> Optional[\"CollectionStore\"]:\n        return CollectionStore.get_by_name(session, self.collection_name)\n    @classmethod\n    def _initialize_from_embeddings(\n        cls,\n        texts: List[str],\n        embeddings: List[List[float]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> PGEmbedding:\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        if not metadatas:\n            metadatas = [{} for _ in texts]\n        connection_string = cls.get_connection_string(kwargs)\n        store = cls(\n            connection_string=connection_string,\n            collection_name=collection_name,\n            embedding_function=embedding,\n            pre_delete_collection=pre_delete_collection,\n        )\n        store.add_embeddings(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html"}
{"id": "8f68c7541f78-5", "text": "pre_delete_collection=pre_delete_collection,\n        )\n        store.add_embeddings(\n            texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs\n        )\n        return store\n[docs]    def add_embeddings(\n        self,\n        texts: List[str],\n        embeddings: List[List[float]],\n        metadatas: List[dict],\n        ids: List[str],\n        **kwargs: Any,\n    ) -> None:\n        with Session(self._conn) as session:\n            collection = self.get_collection(session)\n            if not collection:\n                raise ValueError(\"Collection not found\")\n            for text, metadata, embedding, id in zip(texts, metadatas, embeddings, ids):\n                embedding_store = EmbeddingStore(\n                    embedding=embedding,\n                    document=text,\n                    cmetadata=metadata,\n                    custom_id=id,\n                )\n                collection.embeddings.append(embedding_store)\n                session.add(embedding_store)\n            session.commit()\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        embeddings = self.embedding_function.embed_documents(list(texts))\n        if not metadatas:\n            metadatas = [{} for _ in texts]\n        with Session(self._conn) as session:\n            collection = self.get_collection(session)\n            if not collection:\n                raise ValueError(\"Collection not found\")\n            for text, metadata, embedding, id in zip(texts, metadatas, embeddings, ids):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html"}
{"id": "8f68c7541f78-6", "text": "embedding_store = EmbeddingStore(\n                    embedding=embedding,\n                    document=text,\n                    cmetadata=metadata,\n                    custom_id=id,\n                )\n                collection.embeddings.append(embedding_store)\n                session.add(embedding_store)\n            session.commit()\n        return ids\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        embedding = self.embedding_function.embed_query(text=query)\n        return self.similarity_search_by_vector(\n            embedding=embedding,\n            k=k,\n            filter=filter,\n        )\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[dict] = None,\n    ) -> List[Tuple[Document, float]]:\n        embedding = self.embedding_function.embed_query(query)\n        docs = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, filter=filter\n        )\n        return docs\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[dict] = None,\n    ) -> List[Tuple[Document, float]]:\n        with Session(self._conn) as session:\n            collection = self.get_collection(session)\n            set_enable_seqscan_stmt = sqlalchemy.text(\"SET enable_seqscan = off\")\n            session.execute(set_enable_seqscan_stmt)\n            if not collection:\n                raise ValueError(\"Collection not found\")\n            filter_by = EmbeddingStore.collection_id == collection.uuid\n            if filter is not None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html"}
{"id": "8f68c7541f78-7", "text": "if filter is not None:\n                filter_clauses = []\n                for key, value in filter.items():\n                    IN = \"in\"\n                    if isinstance(value, dict) and IN in map(str.lower, value):\n                        value_case_insensitive = {\n                            k.lower(): v for k, v in value.items()\n                        }\n                        filter_by_metadata = EmbeddingStore.cmetadata[key].astext.in_(\n                            value_case_insensitive[IN]\n                        )\n                        filter_clauses.append(filter_by_metadata)\n                    elif isinstance(value, dict) and \"substring\" in map(\n                        str.lower, value\n                    ):\n                        filter_by_metadata = EmbeddingStore.cmetadata[key].astext.ilike(\n                            f\"%{value['substring']}%\"\n                        )\n                        filter_clauses.append(filter_by_metadata)\n                    else:\n                        filter_by_metadata = EmbeddingStore.cmetadata[\n                            key\n                        ].astext == str(value)\n                        filter_clauses.append(filter_by_metadata)\n                filter_by = sqlalchemy.and_(filter_by, *filter_clauses)\n            results: List[QueryResult] = (\n                session.query(\n                    EmbeddingStore,\n                    func.abs(EmbeddingStore.embedding.op(\"<->\")(embedding)).label(\n                        \"distance\"\n                    ),\n                )  # Specify the columns you need here, e.g., EmbeddingStore.embedding\n                .filter(filter_by)\n                .order_by(\n                    func.abs(EmbeddingStore.embedding.op(\"<->\")(embedding)).asc()\n                )  # Using PostgreSQL specific operator with the correct column name\n                .limit(k)\n                .all()\n            )\n        docs = [\n            (\n                Document(\n                    page_content=result.EmbeddingStore.document,\n                    metadata=result.EmbeddingStore.cmetadata,\n                ),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html"}
{"id": "8f68c7541f78-8", "text": "metadata=result.EmbeddingStore.cmetadata,\n                ),\n                result.distance if self.embedding_function is not None else None,\n            )\n            for result in results\n        ]\n        return docs\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        docs_and_scores = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, filter=filter\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[PGEmbedding],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> PGEmbedding:\n        embeddings = embedding.embed_documents(list(texts))\n        return cls._initialize_from_embeddings(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            collection_name=collection_name,\n            pre_delete_collection=pre_delete_collection,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_embeddings(\n        cls,\n        text_embeddings: List[Tuple[str, List[float]]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        ids: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html"}
{"id": "8f68c7541f78-9", "text": "ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> PGEmbedding:\n        texts = [t[0] for t in text_embeddings]\n        embeddings = [t[1] for t in text_embeddings]\n        return cls._initialize_from_embeddings(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            collection_name=collection_name,\n            pre_delete_collection=pre_delete_collection,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_existing_index(\n        cls: Type[PGEmbedding],\n        embedding: Embeddings,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> PGEmbedding:\n        connection_string = cls.get_connection_string(kwargs)\n        store = cls(\n            connection_string=connection_string,\n            collection_name=collection_name,\n            embedding_function=embedding,\n            pre_delete_collection=pre_delete_collection,\n        )\n        return store\n[docs]    @classmethod\n    def get_connection_string(cls, kwargs: Dict[str, Any]) -> str:\n        connection_string: str = get_from_dict_or_env(\n            data=kwargs,\n            key=\"connection_string\",\n            env_key=\"POSTGRES_CONNECTION_STRING\",\n        )\n        if not connection_string:\n            raise ValueError(\n                \"Postgres connection string is required\"\n                \"Either pass it as a parameter\"\n                \"or set the POSTGRES_CONNECTION_STRING environment variable.\"\n            )\n        return connection_string\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[PGEmbedding],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html"}
{"id": "8f68c7541f78-10", "text": "def from_documents(\n        cls: Type[PGEmbedding],\n        documents: List[Document],\n        embedding: Embeddings,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> PGEmbedding:\n        texts = [d.page_content for d in documents]\n        metadatas = [d.metadata for d in documents]\n        connection_string = cls.get_connection_string(kwargs)\n        kwargs[\"connection_string\"] = connection_string\n        return cls.from_texts(\n            texts=texts,\n            pre_delete_collection=pre_delete_collection,\n            embedding=embedding,\n            metadatas=metadatas,\n            ids=ids,\n            collection_name=collection_name,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html"}
{"id": "b806188a751d-0", "text": "Source code for langchain.vectorstores.timescalevector\n\"\"\"VectorStore wrapper around a Postgres-TimescaleVector database.\"\"\"\nfrom __future__ import annotations\nimport enum\nimport logging\nimport uuid\nfrom datetime import timedelta\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n    Union,\n)\nfrom langchain.schema.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_dict_or_env\nfrom langchain.vectorstores.utils import DistanceStrategy\nif TYPE_CHECKING:\n    from timescale_vector import Predicates\nDEFAULT_DISTANCE_STRATEGY = DistanceStrategy.COSINE\nADA_TOKEN_COUNT = 1536\n_LANGCHAIN_DEFAULT_COLLECTION_NAME = \"langchain_store\"\n[docs]class TimescaleVector(VectorStore):\n    \"\"\"VectorStore implementation using the timescale vector client to store vectors\n    in Postgres.\n    To use, you should have the ``timescale_vector`` python package installed.\n    Args:\n        service_url: Service url on timescale cloud.\n        embedding: Any embedding function implementing\n            `langchain.embeddings.base.Embeddings` interface.\n        collection_name: The name of the collection to use. (default: langchain_store)\n            This will become the table name used for the collection.\n        distance_strategy: The distance strategy to use. (default: COSINE)\n        pre_delete_collection: If True, will delete the collection if it exists.\n            (default: False). Useful for testing.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import TimescaleVector\n            from langchain.embeddings.openai import OpenAIEmbeddings", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-1", "text": "from langchain.embeddings.openai import OpenAIEmbeddings\n            SERVICE_URL = \"postgres://tsdbadmin:<password>@<id>.tsdb.cloud.timescale.com:<port>/tsdb?sslmode=require\"\n            COLLECTION_NAME = \"state_of_the_union_test\"\n            embeddings = OpenAIEmbeddings()\n            vectorestore = TimescaleVector.from_documents(\n                embedding=embeddings,\n                documents=docs,\n                collection_name=COLLECTION_NAME,\n                service_url=SERVICE_URL,\n            )\n    \"\"\"  # noqa: E501\n[docs]    def __init__(\n        self,\n        service_url: str,\n        embedding: Embeddings,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        num_dimensions: int = ADA_TOKEN_COUNT,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        pre_delete_collection: bool = False,\n        logger: Optional[logging.Logger] = None,\n        relevance_score_fn: Optional[Callable[[float], float]] = None,\n        time_partition_interval: Optional[timedelta] = None,\n        **kwargs: Any,\n    ) -> None:\n        try:\n            from timescale_vector import client\n        except ImportError:\n            raise ImportError(\n                \"Could not import timescale_vector python package. \"\n                \"Please install it with `pip install timescale-vector`.\"\n            )\n        self.service_url = service_url\n        self.embedding = embedding\n        self.collection_name = collection_name\n        self.num_dimensions = num_dimensions\n        self._distance_strategy = distance_strategy\n        self.pre_delete_collection = pre_delete_collection\n        self.logger = logger or logging.getLogger(__name__)\n        self.override_relevance_score_fn = relevance_score_fn\n        self._time_partition_interval = time_partition_interval\n        self.sync_client = client.Sync(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-2", "text": "self._time_partition_interval = time_partition_interval\n        self.sync_client = client.Sync(\n            self.service_url,\n            self.collection_name,\n            self.num_dimensions,\n            self._distance_strategy.value.lower(),\n            time_partition_interval=self._time_partition_interval,\n            **kwargs,\n        )\n        self.async_client = client.Async(\n            self.service_url,\n            self.collection_name,\n            self.num_dimensions,\n            self._distance_strategy.value.lower(),\n            time_partition_interval=self._time_partition_interval,\n            **kwargs,\n        )\n        self.__post_init__()\n    def __post_init__(\n        self,\n    ) -> None:\n        \"\"\"\n        Initialize the store.\n        \"\"\"\n        self.sync_client.create_tables()\n        if self.pre_delete_collection:\n            self.sync_client.delete_all()\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding\n[docs]    def drop_tables(self) -> None:\n        self.sync_client.drop_table()\n    @classmethod\n    def __from(\n        cls,\n        texts: List[str],\n        embeddings: List[List[float]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        service_url: Optional[str] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> TimescaleVector:\n        num_dimensions = len(embeddings[0])\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        if not metadatas:\n            metadatas = [{} for _ in texts]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-3", "text": "metadatas = [{} for _ in texts]\n        if service_url is None:\n            service_url = cls.get_service_url(kwargs)\n        store = cls(\n            service_url=service_url,\n            num_dimensions=num_dimensions,\n            collection_name=collection_name,\n            embedding=embedding,\n            distance_strategy=distance_strategy,\n            pre_delete_collection=pre_delete_collection,\n            **kwargs,\n        )\n        store.add_embeddings(\n            texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs\n        )\n        return store\n    @classmethod\n    async def __afrom(\n        cls,\n        texts: List[str],\n        embeddings: List[List[float]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        service_url: Optional[str] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> TimescaleVector:\n        num_dimensions = len(embeddings[0])\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        if not metadatas:\n            metadatas = [{} for _ in texts]\n        if service_url is None:\n            service_url = cls.get_service_url(kwargs)\n        store = cls(\n            service_url=service_url,\n            num_dimensions=num_dimensions,\n            collection_name=collection_name,\n            embedding=embedding,\n            distance_strategy=distance_strategy,\n            pre_delete_collection=pre_delete_collection,\n            **kwargs,\n        )\n        await store.aadd_embeddings(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-4", "text": "**kwargs,\n        )\n        await store.aadd_embeddings(\n            texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs\n        )\n        return store\n[docs]    def add_embeddings(\n        self,\n        texts: Iterable[str],\n        embeddings: List[List[float]],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add embeddings to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            embeddings: List of list of embedding vectors.\n            metadatas: List of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        \"\"\"\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        if not metadatas:\n            metadatas = [{} for _ in texts]\n        records = list(zip(ids, metadatas, texts, embeddings))\n        self.sync_client.upsert(records)\n        return ids\n[docs]    async def aadd_embeddings(\n        self,\n        texts: Iterable[str],\n        embeddings: List[List[float]],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add embeddings to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            embeddings: List of list of embedding vectors.\n            metadatas: List of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        \"\"\"\n        if ids is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-5", "text": "kwargs: vectorstore specific parameters\n        \"\"\"\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        if not metadatas:\n            metadatas = [{} for _ in texts]\n        records = list(zip(ids, metadatas, texts, embeddings))\n        await self.async_client.upsert(records)\n        return ids\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        embeddings = self.embedding.embed_documents(list(texts))\n        return self.add_embeddings(\n            texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs\n        )\n[docs]    async def aadd_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-6", "text": "kwargs: vectorstore specific parameters\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        embeddings = self.embedding.embed_documents(list(texts))\n        return await self.aadd_embeddings(\n            texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs\n        )\n    def _embed_query(self, query: str) -> Optional[List[float]]:\n        # an empty query should not be embedded\n        if query is None or query == \"\" or query.isspace():\n            return None\n        else:\n            return self.embedding.embed_query(query)\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Union[dict, list]] = None,\n        predicates: Optional[Predicates] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Run similarity search with TimescaleVector with distance.\n        Args:\n            query (str): Query text to search for.\n            k (int): Number of results to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        embedding = self._embed_query(query)\n        return self.similarity_search_by_vector(\n            embedding=embedding,\n            k=k,\n            filter=filter,\n            predicates=predicates,\n            **kwargs,\n        )\n[docs]    async def asimilarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Union[dict, list]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-7", "text": "filter: Optional[Union[dict, list]] = None,\n        predicates: Optional[Predicates] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Run similarity search with TimescaleVector with distance.\n        Args:\n            query (str): Query text to search for.\n            k (int): Number of results to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        embedding = self._embed_query(query)\n        return await self.asimilarity_search_by_vector(\n            embedding=embedding,\n            k=k,\n            filter=filter,\n            predicates=predicates,\n            **kwargs,\n        )\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Union[dict, list]] = None,\n        predicates: Optional[Predicates] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        embedding = self._embed_query(query)\n        docs = self.similarity_search_with_score_by_vector(\n            embedding=embedding,\n            k=k,\n            filter=filter,\n            predicates=predicates,\n            **kwargs,\n        )\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-8", "text": "predicates=predicates,\n            **kwargs,\n        )\n        return docs\n[docs]    async def asimilarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Union[dict, list]] = None,\n        predicates: Optional[Predicates] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        embedding = self._embed_query(query)\n        return await self.asimilarity_search_with_score_by_vector(\n            embedding=embedding,\n            k=k,\n            filter=filter,\n            predicates=predicates,\n            **kwargs,\n        )\n[docs]    def date_to_range_filter(self, **kwargs: Any) -> Any:\n        constructor_args = {\n            key: kwargs[key]\n            for key in [\n                \"start_date\",\n                \"end_date\",\n                \"time_delta\",\n                \"start_inclusive\",\n                \"end_inclusive\",\n            ]\n            if key in kwargs\n        }\n        if not constructor_args or len(constructor_args) == 0:\n            return None\n        try:\n            from timescale_vector import client\n        except ImportError:\n            raise ImportError(\n                \"Could not import timescale_vector python package. \"\n                \"Please install it with `pip install timescale-vector`.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-9", "text": "\"Please install it with `pip install timescale-vector`.\"\n            )\n        return client.UUIDTimeRange(**constructor_args)\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: Optional[List[float]],\n        k: int = 4,\n        filter: Optional[Union[dict, list]] = None,\n        predicates: Optional[Predicates] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        try:\n            from timescale_vector import client\n        except ImportError:\n            raise ImportError(\n                \"Could not import timescale_vector python package. \"\n                \"Please install it with `pip install timescale-vector`.\"\n            )\n        results = self.sync_client.search(\n            embedding,\n            limit=k,\n            filter=filter,\n            predicates=predicates,\n            uuid_time_filter=self.date_to_range_filter(**kwargs),\n        )\n        docs = [\n            (\n                Document(\n                    page_content=result[client.SEARCH_RESULT_CONTENTS_IDX],\n                    metadata=result[client.SEARCH_RESULT_METADATA_IDX],\n                ),\n                result[client.SEARCH_RESULT_DISTANCE_IDX],\n            )\n            for result in results\n        ]\n        return docs\n[docs]    async def asimilarity_search_with_score_by_vector(\n        self,\n        embedding: Optional[List[float]],\n        k: int = 4,\n        filter: Optional[Union[dict, list]] = None,\n        predicates: Optional[Predicates] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        try:\n            from timescale_vector import client\n        except ImportError:\n            raise ImportError(\n                \"Could not import timescale_vector python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-10", "text": "raise ImportError(\n                \"Could not import timescale_vector python package. \"\n                \"Please install it with `pip install timescale-vector`.\"\n            )\n        results = await self.async_client.search(\n            embedding,\n            limit=k,\n            filter=filter,\n            predicates=predicates,\n            uuid_time_filter=self.date_to_range_filter(**kwargs),\n        )\n        docs = [\n            (\n                Document(\n                    page_content=result[client.SEARCH_RESULT_CONTENTS_IDX],\n                    metadata=result[client.SEARCH_RESULT_METADATA_IDX],\n                ),\n                result[client.SEARCH_RESULT_DISTANCE_IDX],\n            )\n            for result in results\n        ]\n        return docs\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: Optional[List[float]],\n        k: int = 4,\n        filter: Optional[Union[dict, list]] = None,\n        predicates: Optional[Predicates] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query vector.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, filter=filter, predicates=predicates, **kwargs\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    async def asimilarity_search_by_vector(\n        self,\n        embedding: Optional[List[float]],\n        k: int = 4,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-11", "text": "embedding: Optional[List[float]],\n        k: int = 4,\n        filter: Optional[Union[dict, list]] = None,\n        predicates: Optional[Predicates] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query vector.\n        \"\"\"\n        docs_and_scores = await self.asimilarity_search_with_score_by_vector(\n            embedding=embedding, k=k, filter=filter, predicates=predicates, **kwargs\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[TimescaleVector],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> TimescaleVector:\n        \"\"\"\n        Return VectorStore initialized from texts and embeddings.\n        Postgres connection string is required\n        \"Either pass it as a parameter\n        or set the TIMESCALE_SERVICE_URL environment variable.\n        \"\"\"\n        embeddings = embedding.embed_documents(list(texts))\n        return cls.__from(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-12", "text": "embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            collection_name=collection_name,\n            distance_strategy=distance_strategy,\n            pre_delete_collection=pre_delete_collection,\n            **kwargs,\n        )\n[docs]    @classmethod\n    async def afrom_texts(\n        cls: Type[TimescaleVector],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> TimescaleVector:\n        \"\"\"\n        Return VectorStore initialized from texts and embeddings.\n        Postgres connection string is required\n        \"Either pass it as a parameter\n        or set the TIMESCALE_SERVICE_URL environment variable.\n        \"\"\"\n        embeddings = embedding.embed_documents(list(texts))\n        return await cls.__afrom(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            collection_name=collection_name,\n            distance_strategy=distance_strategy,\n            pre_delete_collection=pre_delete_collection,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_embeddings(\n        cls,\n        text_embeddings: List[Tuple[str, List[float]]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        ids: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-13", "text": "ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> TimescaleVector:\n        \"\"\"Construct TimescaleVector wrapper from raw documents and pre-\n        generated embeddings.\n        Return VectorStore initialized from documents and embeddings.\n        Postgres connection string is required\n        \"Either pass it as a parameter\n        or set the TIMESCALE_SERVICE_URL environment variable.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import TimescaleVector\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                text_embeddings = embeddings.embed_documents(texts)\n                text_embedding_pairs = list(zip(texts, text_embeddings))\n                tvs = TimescaleVector.from_embeddings(text_embedding_pairs, embeddings)\n        \"\"\"\n        texts = [t[0] for t in text_embeddings]\n        embeddings = [t[1] for t in text_embeddings]\n        return cls.__from(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            collection_name=collection_name,\n            distance_strategy=distance_strategy,\n            pre_delete_collection=pre_delete_collection,\n            **kwargs,\n        )\n[docs]    @classmethod\n    async def afrom_embeddings(\n        cls,\n        text_embeddings: List[Tuple[str, List[float]]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> TimescaleVector:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-14", "text": "**kwargs: Any,\n    ) -> TimescaleVector:\n        \"\"\"Construct TimescaleVector wrapper from raw documents and pre-\n        generated embeddings.\n        Return VectorStore initialized from documents and embeddings.\n        Postgres connection string is required\n        \"Either pass it as a parameter\n        or set the TIMESCALE_SERVICE_URL environment variable.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import TimescaleVector\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                text_embeddings = embeddings.embed_documents(texts)\n                text_embedding_pairs = list(zip(texts, text_embeddings))\n                tvs = TimescaleVector.from_embeddings(text_embedding_pairs, embeddings)\n        \"\"\"\n        texts = [t[0] for t in text_embeddings]\n        embeddings = [t[1] for t in text_embeddings]\n        return await cls.__afrom(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            collection_name=collection_name,\n            distance_strategy=distance_strategy,\n            pre_delete_collection=pre_delete_collection,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_existing_index(\n        cls: Type[TimescaleVector],\n        embedding: Embeddings,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> TimescaleVector:\n        \"\"\"\n        Get instance of an existing TimescaleVector store.This method will\n        return the instance of the store without inserting any new\n        embeddings\n        \"\"\"\n        service_url = cls.get_service_url(kwargs)\n        store = cls(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-15", "text": "\"\"\"\n        service_url = cls.get_service_url(kwargs)\n        store = cls(\n            service_url=service_url,\n            collection_name=collection_name,\n            embedding=embedding,\n            distance_strategy=distance_strategy,\n            pre_delete_collection=pre_delete_collection,\n        )\n        return store\n[docs]    @classmethod\n    def get_service_url(cls, kwargs: Dict[str, Any]) -> str:\n        service_url: str = get_from_dict_or_env(\n            data=kwargs,\n            key=\"service_url\",\n            env_key=\"TIMESCALE_SERVICE_URL\",\n        )\n        if not service_url:\n            raise ValueError(\n                \"Postgres connection string is required\"\n                \"Either pass it as a parameter\"\n                \"or set the TIMESCALE_SERVICE_URL environment variable.\"\n            )\n        return service_url\n[docs]    @classmethod\n    def service_url_from_db_params(\n        cls,\n        host: str,\n        port: int,\n        database: str,\n        user: str,\n        password: str,\n    ) -> str:\n        \"\"\"Return connection string from database parameters.\"\"\"\n        return f\"postgresql://{user}:{password}@{host}:{port}/{database}\"\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        \"\"\"\n        The 'correct' relevance function\n        may differ depending on a few things, including:\n        - the distance / similarity metric used by the VectorStore\n        - the scale of your embeddings (OpenAI's are unit normed. Many others are not!)\n        - embedding dimensionality\n        - etc.\n        \"\"\"\n        if self.override_relevance_score_fn is not None:\n            return self.override_relevance_score_fn\n        # Default strategy is to rely on distance strategy provided\n        # in vectorstore constructor", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-16", "text": "# Default strategy is to rely on distance strategy provided\n        # in vectorstore constructor\n        if self._distance_strategy == DistanceStrategy.COSINE:\n            return self._cosine_relevance_score_fn\n        elif self._distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE:\n            return self._euclidean_relevance_score_fn\n        elif self._distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:\n            return self._max_inner_product_relevance_score_fn\n        else:\n            raise ValueError(\n                \"No supported normalization function\"\n                f\" for distance_strategy of {self._distance_strategy}.\"\n                \"Consider providing relevance_score_fn to TimescaleVector constructor.\"\n            )\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:\n        \"\"\"Delete by vector ID or other criteria.\n        Args:\n            ids: List of ids to delete.\n            **kwargs: Other keyword arguments that subclasses might use.\n        Returns:\n            Optional[bool]: True if deletion is successful,\n            False otherwise, None if not implemented.\n        \"\"\"\n        if ids is None:\n            raise ValueError(\"No ids provided to delete.\")\n        self.sync_client.delete_by_ids(ids)\n        return True\n    # todo should this be part of delete|()?\n[docs]    def delete_by_metadata(\n        self, filter: Union[Dict[str, str], List[Dict[str, str]]], **kwargs: Any\n    ) -> Optional[bool]:\n        \"\"\"Delete by vector ID or other criteria.\n        Args:\n            ids: List of ids to delete.\n            **kwargs: Other keyword arguments that subclasses might use.\n        Returns:\n            Optional[bool]: True if deletion is successful,\n            False otherwise, None if not implemented.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "b806188a751d-17", "text": "False otherwise, None if not implemented.\n        \"\"\"\n        self.sync_client.delete_by_metadata(filter)\n        return True\n    class IndexType(str, enum.Enum):\n        \"\"\"Enumerator for the supported Index types\"\"\"\n        TIMESCALE_VECTOR = \"tsv\"\n        PGVECTOR_IVFFLAT = \"ivfflat\"\n        PGVECTOR_HNSW = \"hnsw\"\n    DEFAULT_INDEX_TYPE = IndexType.TIMESCALE_VECTOR\n[docs]    def create_index(\n        self, index_type: Union[IndexType, str] = DEFAULT_INDEX_TYPE, **kwargs: Any\n    ) -> None:\n        try:\n            from timescale_vector import client\n        except ImportError:\n            raise ImportError(\n                \"Could not import timescale_vector python package. \"\n                \"Please install it with `pip install timescale-vector`.\"\n            )\n        index_type = (\n            index_type.value if isinstance(index_type, self.IndexType) else index_type\n        )\n        if index_type == self.IndexType.PGVECTOR_IVFFLAT.value:\n            self.sync_client.create_embedding_index(client.IvfflatIndex(**kwargs))\n        if index_type == self.IndexType.PGVECTOR_HNSW.value:\n            self.sync_client.create_embedding_index(client.HNSWIndex(**kwargs))\n        if index_type == self.IndexType.TIMESCALE_VECTOR.value:\n            self.sync_client.create_embedding_index(\n                client.TimescaleVectorIndex(**kwargs)\n            )\n[docs]    def drop_index(self) -> None:\n        self.sync_client.drop_embedding_index()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/timescalevector.html"}
{"id": "4cb2cc145e35-0", "text": "Source code for langchain.vectorstores.mongodb_atlas\nfrom __future__ import annotations\nimport logging\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Dict,\n    Generator,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    TypeVar,\n    Union,\n)\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nif TYPE_CHECKING:\n    from pymongo.collection import Collection\nMongoDBDocumentType = TypeVar(\"MongoDBDocumentType\", bound=Dict[str, Any])\nlogger = logging.getLogger(__name__)\nDEFAULT_INSERT_BATCH_SIZE = 100\n[docs]class MongoDBAtlasVectorSearch(VectorStore):\n    \"\"\"`MongoDB Atlas Vector Search` vector store.\n    To use, you should have both:\n    - the ``pymongo`` python package installed\n    - a connection string associated with a MongoDB Atlas Cluster having deployed an\n        Atlas Search index\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import MongoDBAtlasVectorSearch\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            from pymongo import MongoClient\n            mongo_client = MongoClient(\"<YOUR-CONNECTION-STRING>\")\n            collection = mongo_client[\"<db_name>\"][\"<collection_name>\"]\n            embeddings = OpenAIEmbeddings()\n            vectorstore = MongoDBAtlasVectorSearch(collection, embeddings)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        collection: Collection[MongoDBDocumentType],\n        embedding: Embeddings,\n        *,\n        index_name: str = \"default\",\n        text_key: str = \"text\",\n        embedding_key: str = \"embedding\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html"}
{"id": "4cb2cc145e35-1", "text": "text_key: str = \"text\",\n        embedding_key: str = \"embedding\",\n    ):\n        \"\"\"\n        Args:\n            collection: MongoDB collection to add the texts to.\n            embedding: Text embedding model to use.\n            text_key: MongoDB field that will contain the text for each\n                document.\n            embedding_key: MongoDB field that will contain the embedding for\n                each document.\n            index_name: Name of the Atlas Search index.\n        \"\"\"\n        self._collection = collection\n        self._embedding = embedding\n        self._index_name = index_name\n        self._text_key = text_key\n        self._embedding_key = embedding_key\n    @property\n    def embeddings(self) -> Embeddings:\n        return self._embedding\n[docs]    @classmethod\n    def from_connection_string(\n        cls,\n        connection_string: str,\n        namespace: str,\n        embedding: Embeddings,\n        **kwargs: Any,\n    ) -> MongoDBAtlasVectorSearch:\n        \"\"\"Construct a `MongoDB Atlas Vector Search` vector store\n        from a MongoDB connection URI.\n        Args:\n            connection_string: A valid MongoDB connection URI.\n            namespace: A valid MongoDB namespace (database and collection).\n            embedding: The text embedding model to use for the vector store.\n        Returns:\n            A new MongoDBAtlasVectorSearch instance.\n        \"\"\"\n        try:\n            from importlib.metadata import version\n            from pymongo import DriverInfo, MongoClient\n        except ImportError:\n            raise ImportError(\n                \"Could not import pymongo, please install it with \"\n                \"`pip install pymongo`.\"\n            )\n        client: MongoClient = MongoClient(\n            connection_string,\n            driver=DriverInfo(name=\"Langchain\", version=version(\"langchain\")),\n        )\n        db_name, collection_name = namespace.split(\".\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html"}
{"id": "4cb2cc145e35-2", "text": ")\n        db_name, collection_name = namespace.split(\".\")\n        collection = client[db_name][collection_name]\n        return cls(collection, embedding, **kwargs)\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[Dict[str, Any]]] = None,\n        **kwargs: Any,\n    ) -> List:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        batch_size = kwargs.get(\"batch_size\", DEFAULT_INSERT_BATCH_SIZE)\n        _metadatas: Union[List, Generator] = metadatas or ({} for _ in texts)\n        texts_batch = []\n        metadatas_batch = []\n        result_ids = []\n        for i, (text, metadata) in enumerate(zip(texts, _metadatas)):\n            texts_batch.append(text)\n            metadatas_batch.append(metadata)\n            if (i + 1) % batch_size == 0:\n                result_ids.extend(self._insert_texts(texts_batch, metadatas_batch))\n                texts_batch = []\n                metadatas_batch = []\n        if texts_batch:\n            result_ids.extend(self._insert_texts(texts_batch, metadatas_batch))\n        return result_ids\n    def _insert_texts(self, texts: List[str], metadatas: List[Dict[str, Any]]) -> List:\n        if not texts:\n            return []\n        # Embed and create the documents\n        embeddings = self._embedding.embed_documents(texts)\n        to_insert = [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html"}
{"id": "4cb2cc145e35-3", "text": "embeddings = self._embedding.embed_documents(texts)\n        to_insert = [\n            {self._text_key: t, self._embedding_key: embedding, **m}\n            for t, m, embedding in zip(texts, metadatas, embeddings)\n        ]\n        # insert the documents in MongoDB Atlas\n        insert_result = self._collection.insert_many(to_insert)  # type: ignore\n        return insert_result.inserted_ids\n    def _similarity_search_with_score(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        pre_filter: Optional[Dict] = None,\n        post_filter_pipeline: Optional[List[Dict]] = None,\n    ) -> List[Tuple[Document, float]]:\n        params = {\n            \"queryVector\": embedding,\n            \"path\": self._embedding_key,\n            \"numCandidates\": k * 10,\n            \"limit\": k,\n            \"index\": self._index_name,\n        }\n        if pre_filter:\n            params[\"filter\"] = pre_filter\n        query = {\"$vectorSearch\": params}\n        pipeline = [\n            query,\n            {\"$set\": {\"score\": {\"$meta\": \"vectorSearchScore\"}}},\n        ]\n        if post_filter_pipeline is not None:\n            pipeline.extend(post_filter_pipeline)\n        cursor = self._collection.aggregate(pipeline)  # type: ignore[arg-type]\n        docs = []\n        for res in cursor:\n            text = res.pop(self._text_key)\n            score = res.pop(\"score\")\n            docs.append((Document(page_content=text, metadata=res), score))\n        return docs\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        *,\n        k: int = 4,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html"}
{"id": "4cb2cc145e35-4", "text": "query: str,\n        *,\n        k: int = 4,\n        pre_filter: Optional[Dict] = None,\n        post_filter_pipeline: Optional[List[Dict]] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return MongoDB documents most similar to the given query and their scores.\n        Uses the knnBeta Operator available in MongoDB Atlas Search.\n        This feature is in early access and available only for evaluation purposes, to\n        validate functionality, and to gather feedback from a small closed group of\n        early access users. It is not recommended for production deployments as we\n        may introduce breaking changes.\n        For more: https://www.mongodb.com/docs/atlas/atlas-search/knn-beta\n        Args:\n            query: Text to look up documents similar to.\n            k: (Optional) number of documents to return. Defaults to 4.\n            pre_filter: (Optional) dictionary of argument(s) to prefilter document\n                fields on.\n            post_filter_pipeline: (Optional) Pipeline of MongoDB aggregation stages\n                following the knnBeta vector search.\n        Returns:\n            List of documents most similar to the query and their scores.\n        \"\"\"\n        embedding = self._embedding.embed_query(query)\n        docs = self._similarity_search_with_score(\n            embedding,\n            k=k,\n            pre_filter=pre_filter,\n            post_filter_pipeline=post_filter_pipeline,\n        )\n        return docs\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        pre_filter: Optional[Dict] = None,\n        post_filter_pipeline: Optional[List[Dict]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return MongoDB documents most similar to the given query.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html"}
{"id": "4cb2cc145e35-5", "text": "\"\"\"Return MongoDB documents most similar to the given query.\n        Uses the knnBeta Operator available in MongoDB Atlas Search.\n        This feature is in early access and available only for evaluation purposes, to\n        validate functionality, and to gather feedback from a small closed group of\n        early access users. It is not recommended for production deployments as we\n        may introduce breaking changes.\n        For more: https://www.mongodb.com/docs/atlas/atlas-search/knn-beta\n        Args:\n            query: Text to look up documents similar to.\n            k: (Optional) number of documents to return. Defaults to 4.\n            pre_filter: (Optional) dictionary of argument(s) to prefilter document\n                fields on.\n            post_filter_pipeline: (Optional) Pipeline of MongoDB aggregation stages\n                following the knnBeta vector search.\n        Returns:\n            List of documents most similar to the query and their scores.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(\n            query,\n            k=k,\n            pre_filter=pre_filter,\n            post_filter_pipeline=post_filter_pipeline,\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        pre_filter: Optional[Dict] = None,\n        post_filter_pipeline: Optional[List[Dict]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return documents selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html"}
{"id": "4cb2cc145e35-6", "text": "Args:\n            query: Text to look up documents similar to.\n            k: (Optional) number of documents to return. Defaults to 4.\n            fetch_k: (Optional) number of documents to fetch before passing to MMR\n                algorithm. Defaults to 20.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n            pre_filter: (Optional) dictionary of argument(s) to prefilter on document\n                fields.\n            post_filter_pipeline: (Optional) pipeline of MongoDB aggregation stages\n                following the knnBeta vector search.\n        Returns:\n            List of documents selected by maximal marginal relevance.\n        \"\"\"\n        query_embedding = self._embedding.embed_query(query)\n        docs = self._similarity_search_with_score(\n            query_embedding,\n            k=fetch_k,\n            pre_filter=pre_filter,\n            post_filter_pipeline=post_filter_pipeline,\n        )\n        mmr_doc_indexes = maximal_marginal_relevance(\n            np.array(query_embedding),\n            [doc.metadata[self._embedding_key] for doc, _ in docs],\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        mmr_docs = [docs[i][0] for i in mmr_doc_indexes]\n        return mmr_docs\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[Dict]] = None,\n        collection: Optional[Collection[MongoDBDocumentType]] = None,\n        **kwargs: Any,\n    ) -> MongoDBAtlasVectorSearch:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html"}
{"id": "4cb2cc145e35-7", "text": "**kwargs: Any,\n    ) -> MongoDBAtlasVectorSearch:\n        \"\"\"Construct a `MongoDB Atlas Vector Search` vector store from raw documents.\n        This is a user-friendly interface that:\n            1. Embeds documents.\n            2. Adds the documents to a provided MongoDB Atlas Vector Search index\n                (Lucene)\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from pymongo import MongoClient\n                from langchain.vectorstores import MongoDBAtlasVectorSearch\n                from langchain.embeddings import OpenAIEmbeddings\n                mongo_client = MongoClient(\"<YOUR-CONNECTION-STRING>\")\n                collection = mongo_client[\"<db_name>\"][\"<collection_name>\"]\n                embeddings = OpenAIEmbeddings()\n                vectorstore = MongoDBAtlasVectorSearch.from_texts(\n                    texts,\n                    embeddings,\n                    metadatas=metadatas,\n                    collection=collection\n                )\n        \"\"\"\n        if collection is None:\n            raise ValueError(\"Must provide 'collection' named parameter.\")\n        vectorstore = cls(collection, embedding, **kwargs)\n        vectorstore.add_texts(texts, metadatas=metadatas)\n        return vectorstore", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html"}
{"id": "32546b1c8542-0", "text": "Source code for langchain.vectorstores.astradb\nfrom __future__ import annotations\nimport uuid\nimport warnings\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Set,\n    Tuple,\n    Type,\n    TypeVar,\n)\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils.iter import batch_iterate\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nADBVST = TypeVar(\"ADBVST\", bound=\"AstraDB\")\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\nDocDict = Dict[str, Any]  # dicts expressing entries to insert\n# Batch/concurrency default values (if parameters not provided):\n# Size of batches for bulk insertions:\n#   (20 is the max batch size for the HTTP API at the time of writing)\nDEFAULT_BATCH_SIZE = 20\n# Number of threads to insert batches concurrently:\nDEFAULT_BULK_INSERT_BATCH_CONCURRENCY = 16\n# Number of threads in a batch to insert pre-existing entries:\nDEFAULT_BULK_INSERT_OVERWRITE_CONCURRENCY = 10\n# Number of threads (for deleting multiple rows concurrently):\nDEFAULT_BULK_DELETE_CONCURRENCY = 20\ndef _unique_list(lst: List[T], key: Callable[[T], U]) -> List[T]:\n    visited_keys: Set[U] = set()\n    new_lst = []\n    for item in lst:\n        item_key = key(item)\n        if item_key not in visited_keys:\n            visited_keys.add(item_key)\n            new_lst.append(item)\n    return new_lst", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-1", "text": "visited_keys.add(item_key)\n            new_lst.append(item)\n    return new_lst\n[docs]class AstraDB(VectorStore):\n    \"\"\"Wrapper around DataStax Astra DB for vector-store workloads.\n    To use it, you need a recent installation of the `astrapy` library\n    and an Astra DB cloud database.\n    For quickstart and details, visit:\n        docs.datastax.com/en/astra/home/astra.html\n    Example:\n        .. code-block:: python\n                from langchain.vectorstores import AstraDB\n                from langchain.embeddings.openai import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                vectorstore = AstraDB(\n                  embedding=embeddings,\n                  collection_name=\"my_store\",\n                  token=\"AstraCS:...\",\n                  api_endpoint=\"https://<DB-ID>-us-east1.apps.astra.datastax.com\"\n                )\n                vectorstore.add_texts([\"Giraffes\", \"All good here\"])\n                results = vectorstore.similarity_search(\"Everything's ok\", k=1)\n    \"\"\"\n    @staticmethod\n    def _filter_to_metadata(filter_dict: Optional[Dict[str, str]]) -> Dict[str, Any]:\n        if filter_dict is None:\n            return {}\n        else:\n            return {f\"metadata.{mdk}\": mdv for mdk, mdv in filter_dict.items()}\n[docs]    def __init__(\n        self,\n        *,\n        embedding: Embeddings,\n        collection_name: str,\n        token: Optional[str] = None,\n        api_endpoint: Optional[str] = None,\n        astra_db_client: Optional[Any] = None,  # 'astrapy.db.AstraDB' if passed\n        namespace: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-2", "text": "namespace: Optional[str] = None,\n        metric: Optional[str] = None,\n        batch_size: Optional[int] = None,\n        bulk_insert_batch_concurrency: Optional[int] = None,\n        bulk_insert_overwrite_concurrency: Optional[int] = None,\n        bulk_delete_concurrency: Optional[int] = None,\n    ) -> None:\n        try:\n            from astrapy.db import (\n                AstraDB as LibAstraDB,\n            )\n            from astrapy.db import (\n                AstraDBCollection as LibAstraDBCollection,\n            )\n        except (ImportError, ModuleNotFoundError):\n            raise ImportError(\n                \"Could not import a recent astrapy python package. \"\n                \"Please install it with `pip install --upgrade astrapy`.\"\n            )\n        \"\"\"\n        Create an AstraDB vector store object.\n        Args (only keyword-arguments accepted):\n            embedding (Embeddings): embedding function to use.\n            collection_name (str): name of the Astra DB collection to create/use.\n            token (Optional[str]): API token for Astra DB usage.\n            api_endpoint (Optional[str]): full URL to the API endpoint,\n                such as \"https://<DB-ID>-us-east1.apps.astra.datastax.com\".\n            astra_db_client (Optional[Any]): *alternative to token+api_endpoint*,\n                you can pass an already-created 'astrapy.db.AstraDB' instance.\n            namespace (Optional[str]): namespace (aka keyspace) where the\n                collection is created. Defaults to the database's \"default namespace\".\n            metric (Optional[str]): similarity function to use out of those\n                available in Astra DB. If left out, it will use Astra DB API's", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-3", "text": "available in Astra DB. If left out, it will use Astra DB API's\n                defaults (i.e. \"cosine\" - but, for performance reasons,\n                \"dot_product\" is suggested if embeddings are normalized to one).\n        Advanced arguments (coming with sensible defaults):\n            batch_size (Optional[int]): Size of batches for bulk insertions.\n            bulk_insert_batch_concurrency (Optional[int]): Number of threads\n                to insert batches concurrently.\n            bulk_insert_overwrite_concurrency (Optional[int]): Number of\n                threads in a batch to insert pre-existing entries.\n            bulk_delete_concurrency (Optional[int]): Number of threads\n                (for deleting multiple rows concurrently).\n        A note on concurrency: as a rule of thumb, on a typical client machine\n        it is suggested to keep the quantity\n            bulk_insert_batch_concurrency * bulk_insert_overwrite_concurrency\n        much below 1000 to avoid exhausting the client multithreading/networking\n        resources. The hardcoded defaults are somewhat conservative to meet\n        most machines' specs, but a sensible choice to test may be:\n            bulk_insert_batch_concurrency = 80\n            bulk_insert_overwrite_concurrency = 10\n        A bit of experimentation is required to nail the best results here,\n        depending on both the machine/network specs and the expected workload\n        (specifically, how often a write is an update of an existing id).\n        Remember you can pass concurrency settings to individual calls to\n        add_texts and add_documents as well.\n        \"\"\"\n        # Conflicting-arg checks:\n        if astra_db_client is not None:\n            if token is not None or api_endpoint is not None:\n                raise ValueError(\n                    \"You cannot pass 'astra_db_client' to AstraDB if passing \"\n                    \"'token' and 'api_endpoint'.\"\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-4", "text": "\"'token' and 'api_endpoint'.\"\n                )\n        self.embedding = embedding\n        self.collection_name = collection_name\n        self.token = token\n        self.api_endpoint = api_endpoint\n        self.namespace = namespace\n        # Concurrency settings\n        self.batch_size: int = batch_size or DEFAULT_BATCH_SIZE\n        self.bulk_insert_batch_concurrency: int = (\n            bulk_insert_batch_concurrency or DEFAULT_BULK_INSERT_BATCH_CONCURRENCY\n        )\n        self.bulk_insert_overwrite_concurrency: int = (\n            bulk_insert_overwrite_concurrency\n            or DEFAULT_BULK_INSERT_OVERWRITE_CONCURRENCY\n        )\n        self.bulk_delete_concurrency: int = (\n            bulk_delete_concurrency or DEFAULT_BULK_DELETE_CONCURRENCY\n        )\n        # \"vector-related\" settings\n        self._embedding_dimension: Optional[int] = None\n        self.metric = metric\n        if astra_db_client is not None:\n            self.astra_db = astra_db_client\n        else:\n            self.astra_db = LibAstraDB(\n                token=self.token,\n                api_endpoint=self.api_endpoint,\n                namespace=self.namespace,\n            )\n        self._provision_collection()\n        self.collection = LibAstraDBCollection(\n            collection_name=self.collection_name,\n            astra_db=self.astra_db,\n        )\n    def _get_embedding_dimension(self) -> int:\n        if self._embedding_dimension is None:\n            self._embedding_dimension = len(\n                self.embedding.embed_query(\"This is a sample sentence.\")\n            )\n        return self._embedding_dimension\n    def _drop_collection(self) -> None:\n        \"\"\"\n        Drop the collection from storage.\n        This is meant as an internal-usage method, no members\n        are set other than actual deletion on the backend.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-5", "text": "are set other than actual deletion on the backend.\n        \"\"\"\n        _ = self.astra_db.delete_collection(\n            collection_name=self.collection_name,\n        )\n        return None\n    def _provision_collection(self) -> None:\n        \"\"\"\n        Run the API invocation to create the collection on the backend.\n        Internal-usage method, no object members are set,\n        other than working on the underlying actual storage.\n        \"\"\"\n        _ = self.astra_db.create_collection(\n            dimension=self._get_embedding_dimension(),\n            collection_name=self.collection_name,\n            metric=self.metric,\n        )\n        return None\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding\n    @staticmethod\n    def _dont_flip_the_cos_score(similarity0to1: float) -> float:\n        \"\"\"Keep similarity from client unchanged ad it's in [0:1] already.\"\"\"\n        return similarity0to1\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        \"\"\"\n        The underlying API calls already returns a \"score proper\",\n        i.e. one in [0, 1] where higher means more *similar*,\n        so here the final score transformation is not reversing the interval:\n        \"\"\"\n        return self._dont_flip_the_cos_score\n[docs]    def clear(self) -> None:\n        \"\"\"Empty the collection of all its stored entries.\"\"\"\n        self._drop_collection()\n        self._provision_collection()\n        return None\n[docs]    def delete_by_document_id(self, document_id: str) -> bool:\n        \"\"\"\n        Remove a single document from the store, given its document_id (str).\n        Return True if a document has indeed been deleted, False if ID not found.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-6", "text": "\"\"\"\n        deletion_response = self.collection.delete(document_id)\n        return ((deletion_response or {}).get(\"status\") or {}).get(\n            \"deletedCount\", 0\n        ) == 1\n[docs]    def delete(\n        self,\n        ids: Optional[List[str]] = None,\n        concurrency: Optional[int] = None,\n        **kwargs: Any,\n    ) -> Optional[bool]:\n        \"\"\"Delete by vector ids.\n        Args:\n            ids (Optional[List[str]]): List of ids to delete.\n            concurrency (Optional[int]): max number of threads issuing\n                single-doc delete requests. Defaults to instance-level setting.\n        Returns:\n            Optional[bool]: True if deletion is successful,\n                False otherwise, None if not implemented.\n        \"\"\"\n        if kwargs:\n            warnings.warn(\n                \"Method 'delete' of AstraDB vector store invoked with \"\n                f\"unsupported arguments ({', '.join(sorted(kwargs.keys()))}), \"\n                \"which will be ignored.\"\n            )\n        if ids is None:\n            raise ValueError(\"No ids provided to delete.\")\n        _max_workers = concurrency or self.bulk_delete_concurrency\n        with ThreadPoolExecutor(max_workers=_max_workers) as tpe:\n            _ = list(\n                tpe.map(\n                    self.delete_by_document_id,\n                    ids,\n                )\n            )\n        return True\n[docs]    def delete_collection(self) -> None:\n        \"\"\"\n        Completely delete the collection from the database (as opposed\n        to 'clear()', which empties it only).\n        Stored data is lost and unrecoverable, resources are freed.\n        Use with caution.\n        \"\"\"\n        self._drop_collection()\n        return None\n[docs]    def add_texts(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-7", "text": "return None\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        *,\n        batch_size: Optional[int] = None,\n        batch_concurrency: Optional[int] = None,\n        overwrite_concurrency: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run texts through the embeddings and add them to the vectorstore.\n        If passing explicit ids, those entries whose id is in the store already\n        will be replaced.\n        Args:\n            texts (Iterable[str]): Texts to add to the vectorstore.\n            metadatas (Optional[List[dict]], optional): Optional list of metadatas.\n            ids (Optional[List[str]], optional): Optional list of ids.\n            batch_size (Optional[int]): Number of documents in each API call.\n                Check the underlying Astra DB HTTP API specs for the max value\n                (20 at the time of writing this). If not provided, defaults\n                to the instance-level setting.\n            batch_concurrency (Optional[int]): number of threads to process\n                insertion batches concurrently. Defaults to instance-level\n                setting if not provided.\n            overwrite_concurrency (Optional[int]):  number of threads to process\n                pre-existing documents in each batch (which require individual\n                API calls). Defaults to instance-level setting if not provided.\n        A note on metadata: there are constraints on the allowed field names\n        in this dictionary, coming from the underlying Astra DB API.\n        For instance, the `$` (dollar sign) cannot be used in the dict keys.\n        See this document for details:\n            docs.datastax.com/en/astra-serverless/docs/develop/dev-with-json.html", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-8", "text": "docs.datastax.com/en/astra-serverless/docs/develop/dev-with-json.html\n        Returns:\n            List[str]: List of ids of the added texts.\n        \"\"\"\n        if kwargs:\n            warnings.warn(\n                \"Method 'add_texts' of AstraDB vector store invoked with \"\n                f\"unsupported arguments ({', '.join(sorted(kwargs.keys()))}), \"\n                \"which will be ignored.\"\n            )\n        _texts = list(texts)\n        if ids is None:\n            ids = [uuid.uuid4().hex for _ in _texts]\n        if metadatas is None:\n            metadatas = [{} for _ in _texts]\n        #\n        embedding_vectors = self.embedding.embed_documents(_texts)\n        documents_to_insert = [\n            {\n                \"content\": b_txt,\n                \"_id\": b_id,\n                \"$vector\": b_emb,\n                \"metadata\": b_md,\n            }\n            for b_txt, b_emb, b_id, b_md in zip(\n                _texts,\n                embedding_vectors,\n                ids,\n                metadatas,\n            )\n        ]\n        # make unique by id, keeping the last\n        uniqued_documents_to_insert = _unique_list(\n            documents_to_insert[::-1],\n            lambda document: document[\"_id\"],\n        )[::-1]\n        all_ids = []\n        def _handle_batch(document_batch: List[DocDict]) -> List[str]:\n            im_result = self.collection.insert_many(\n                documents=document_batch,\n                options={\"ordered\": False},\n                partial_failures_allowed=True,\n            )\n            if \"status\" not in im_result:\n                raise ValueError(\n                    f\"API Exception while running bulk insertion: {str(im_result)}\"\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-9", "text": "f\"API Exception while running bulk insertion: {str(im_result)}\"\n                )\n            batch_inserted = im_result[\"status\"][\"insertedIds\"]\n            # estimation of the preexisting documents that failed\n            missed_inserted_ids = {\n                document[\"_id\"] for document in document_batch\n            } - set(batch_inserted)\n            errors = im_result.get(\"errors\", [])\n            # careful for other sources of error other than \"doc already exists\"\n            num_errors = len(errors)\n            unexpected_errors = any(\n                error.get(\"errorCode\") != \"DOCUMENT_ALREADY_EXISTS\" for error in errors\n            )\n            if num_errors != len(missed_inserted_ids) or unexpected_errors:\n                raise ValueError(\n                    f\"API Exception while running bulk insertion: {str(errors)}\"\n                )\n            # deal with the missing insertions as upserts\n            missing_from_batch = [\n                document\n                for document in document_batch\n                if document[\"_id\"] in missed_inserted_ids\n            ]\n            def _handle_missing_document(missing_document: DocDict) -> str:\n                replacement_result = self.collection.find_one_and_replace(\n                    filter={\"_id\": missing_document[\"_id\"]},\n                    replacement=missing_document,\n                )\n                return replacement_result[\"data\"][\"document\"][\"_id\"]\n            _u_max_workers = (\n                overwrite_concurrency or self.bulk_insert_overwrite_concurrency\n            )\n            with ThreadPoolExecutor(max_workers=_u_max_workers) as tpe2:\n                batch_replaced = list(\n                    tpe2.map(\n                        _handle_missing_document,\n                        missing_from_batch,\n                    )\n                )\n            upsert_ids = batch_inserted + batch_replaced\n            return upsert_ids\n        _b_max_workers = batch_concurrency or self.bulk_insert_batch_concurrency", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-10", "text": "_b_max_workers = batch_concurrency or self.bulk_insert_batch_concurrency\n        with ThreadPoolExecutor(max_workers=_b_max_workers) as tpe:\n            all_ids_nested = tpe.map(\n                _handle_batch,\n                batch_iterate(\n                    batch_size or self.batch_size,\n                    uniqued_documents_to_insert,\n                ),\n            )\n        all_ids = [iid for id_list in all_ids_nested for iid in id_list]\n        return all_ids\n[docs]    def similarity_search_with_score_id_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n    ) -> List[Tuple[Document, float, str]]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding (str): Embedding to look up documents similar to.\n            k (int): Number of Documents to return. Defaults to 4.\n        Returns:\n            List of (Document, score, id), the most similar to the query vector.\n        \"\"\"\n        metadata_parameter = self._filter_to_metadata(filter)\n        #\n        hits = list(\n            self.collection.paginated_find(\n                filter=metadata_parameter,\n                sort={\"$vector\": embedding},\n                options={\"limit\": k},\n                projection={\n                    \"_id\": 1,\n                    \"content\": 1,\n                    \"metadata\": 1,\n                    \"$similarity\": 1,\n                },\n            )\n        )\n        #\n        return [\n            (\n                Document(\n                    page_content=hit[\"content\"],\n                    metadata=hit[\"metadata\"],\n                ),\n                hit[\"$similarity\"],\n                hit[\"_id\"],\n            )\n            for hit in hits\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-11", "text": "hit[\"_id\"],\n            )\n            for hit in hits\n        ]\n[docs]    def similarity_search_with_score_id(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n    ) -> List[Tuple[Document, float, str]]:\n        embedding_vector = self.embedding.embed_query(query)\n        return self.similarity_search_with_score_id_by_vector(\n            embedding=embedding_vector,\n            k=k,\n            filter=filter,\n        )\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding (str): Embedding to look up documents similar to.\n            k (int): Number of Documents to return. Defaults to 4.\n        Returns:\n            List of (Document, score), the most similar to the query vector.\n        \"\"\"\n        return [\n            (doc, score)\n            for (doc, score, doc_id) in self.similarity_search_with_score_id_by_vector(\n                embedding=embedding,\n                k=k,\n                filter=filter,\n            )\n        ]\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        embedding_vector = self.embedding.embed_query(query)\n        return self.similarity_search_by_vector(\n            embedding_vector,\n            k,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-12", "text": "return self.similarity_search_by_vector(\n            embedding_vector,\n            k,\n            filter=filter,\n        )\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        return [\n            doc\n            for doc, _ in self.similarity_search_with_score_by_vector(\n                embedding,\n                k,\n                filter=filter,\n            )\n        ]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n    ) -> List[Tuple[Document, float]]:\n        embedding_vector = self.embedding.embed_query(query)\n        return self.similarity_search_with_score_by_vector(\n            embedding_vector,\n            k,\n            filter=filter,\n        )\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-13", "text": "fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        metadata_parameter = self._filter_to_metadata(filter)\n        prefetch_hits = list(\n            self.collection.paginated_find(\n                filter=metadata_parameter,\n                sort={\"$vector\": embedding},\n                options={\"limit\": fetch_k},\n                projection={\n                    \"_id\": 1,\n                    \"content\": 1,\n                    \"metadata\": 1,\n                    \"$similarity\": 1,\n                    \"$vector\": 1,\n                },\n            )\n        )\n        mmr_chosen_indices = maximal_marginal_relevance(\n            np.array(embedding, dtype=np.float32),\n            [prefetch_hit[\"$vector\"] for prefetch_hit in prefetch_hits],\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        mmr_hits = [\n            prefetch_hit\n            for prefetch_index, prefetch_hit in enumerate(prefetch_hits)\n            if prefetch_index in mmr_chosen_indices\n        ]\n        return [\n            Document(\n                page_content=hit[\"content\"],\n                metadata=hit[\"metadata\"],\n            )\n            for hit in mmr_hits\n        ]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-14", "text": "**kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query (str): Text to look up documents similar to.\n            k (int = 4): Number of Documents to return.\n            fetch_k (int = 20): Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult (float = 0.5): Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Optional.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        embedding_vector = self.embedding.embed_query(query)\n        return self.max_marginal_relevance_search_by_vector(\n            embedding_vector,\n            k,\n            fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n        )\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[ADBVST],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> ADBVST:\n        \"\"\"Create an Astra DB vectorstore from raw texts.\n        Args:\n            texts (List[str]): the texts to insert.\n            embedding (Embeddings): the embedding function to use in the store.\n            metadatas (Optional[List[dict]]): metadata dicts for the texts.\n            ids (Optional[List[str]]): ids to associate to the texts.\n            *Additional arguments*: you can pass any argument that you would", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-15", "text": "*Additional arguments*: you can pass any argument that you would\n                to 'add_texts' and/or to the 'AstraDB' class constructor\n                (see these methods for details). These arguments will be\n                routed to the respective methods as they are.\n        Returns:\n            an `AstraDb` vectorstore.\n        \"\"\"\n        known_kwargs = {\n            \"collection_name\",\n            \"token\",\n            \"api_endpoint\",\n            \"astra_db_client\",\n            \"namespace\",\n            \"metric\",\n            \"batch_size\",\n            \"bulk_insert_batch_concurrency\",\n            \"bulk_insert_overwrite_concurrency\",\n            \"bulk_delete_concurrency\",\n            \"batch_concurrency\",\n            \"overwrite_concurrency\",\n        }\n        if kwargs:\n            unknown_kwargs = set(kwargs.keys()) - known_kwargs\n            if unknown_kwargs:\n                warnings.warn(\n                    \"Method 'from_texts' of AstraDB vector store invoked with \"\n                    f\"unsupported arguments ({', '.join(sorted(unknown_kwargs))}), \"\n                    \"which will be ignored.\"\n                )\n        collection_name: str = kwargs[\"collection_name\"]\n        token = kwargs.get(\"token\")\n        api_endpoint = kwargs.get(\"api_endpoint\")\n        astra_db_client = kwargs.get(\"astra_db_client\")\n        namespace = kwargs.get(\"namespace\")\n        metric = kwargs.get(\"metric\")\n        astra_db_store = cls(\n            embedding=embedding,\n            collection_name=collection_name,\n            token=token,\n            api_endpoint=api_endpoint,\n            astra_db_client=astra_db_client,\n            namespace=namespace,\n            metric=metric,\n            batch_size=kwargs.get(\"batch_size\"),\n            bulk_insert_batch_concurrency=kwargs.get(\"bulk_insert_batch_concurrency\"),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "32546b1c8542-16", "text": "bulk_insert_batch_concurrency=kwargs.get(\"bulk_insert_batch_concurrency\"),\n            bulk_insert_overwrite_concurrency=kwargs.get(\n                \"bulk_insert_overwrite_concurrency\"\n            ),\n            bulk_delete_concurrency=kwargs.get(\"bulk_delete_concurrency\"),\n        )\n        astra_db_store.add_texts(\n            texts=texts,\n            metadatas=metadatas,\n            ids=ids,\n            batch_size=kwargs.get(\"batch_size\"),\n            batch_concurrency=kwargs.get(\"batch_concurrency\"),\n            overwrite_concurrency=kwargs.get(\"overwrite_concurrency\"),\n        )\n        return astra_db_store\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[ADBVST],\n        documents: List[Document],\n        embedding: Embeddings,\n        **kwargs: Any,\n    ) -> ADBVST:\n        \"\"\"Create an Astra DB vectorstore from a document list.\n        Utility method that defers to 'from_texts' (see that one).\n        Args: see 'from_texts', except here you have to supply 'documents'\n            in place of 'texts' and 'metadatas'.\n        Returns:\n            an `AstraDB` vectorstore.\n        \"\"\"\n        return super().from_documents(documents, embedding, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/astradb.html"}
{"id": "1544452feae7-0", "text": "Source code for langchain.vectorstores.myscale\nfrom __future__ import annotations\nimport json\nimport logging\nfrom hashlib import sha1\nfrom threading import Thread\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import BaseSettings\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nlogger = logging.getLogger()\n[docs]def has_mul_sub_str(s: str, *args: Any) -> bool:\n    \"\"\"\n    Check if a string contains multiple substrings.\n    Args:\n        s: string to check.\n        *args: substrings to check.\n    Returns:\n        True if all substrings are in the string, False otherwise.\n    \"\"\"\n    for a in args:\n        if a not in s:\n            return False\n    return True\n[docs]class MyScaleSettings(BaseSettings):\n    \"\"\"MyScale client configuration.\n    Attribute:\n        myscale_host (str) : An URL to connect to MyScale backend.\n                             Defaults to 'localhost'.\n        myscale_port (int) : URL port to connect with HTTP. Defaults to 8443.\n        username (str) : Username to login. Defaults to None.\n        password (str) : Password to login. Defaults to None.\n        index_type (str): index type string.\n        index_param (dict): index build parameter.\n        database (str) : Database name to find the table. Defaults to 'default'.\n        table (str) : Table name to operate on.\n                      Defaults to 'vector_table'.\n        metric (str) : Metric to compute distance,\n                       supported are ('L2', 'Cosine', 'IP'). Defaults to 'Cosine'.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-1", "text": "column_map (Dict) : Column type map to project column name onto langchain\n                            semantics. Must have keys: `text`, `id`, `vector`,\n                            must be same size to number of columns. For example:\n                            .. code-block:: python\n                                {\n                                    'id': 'text_id',\n                                    'vector': 'text_embedding',\n                                    'text': 'text_plain',\n                                    'metadata': 'metadata_dictionary_in_json',\n                                }\n                            Defaults to identity map.\n    \"\"\"\n    host: str = \"localhost\"\n    port: int = 8443\n    username: Optional[str] = None\n    password: Optional[str] = None\n    index_type: str = \"MSTG\"\n    index_param: Optional[Dict[str, str]] = None\n    column_map: Dict[str, str] = {\n        \"id\": \"id\",\n        \"text\": \"text\",\n        \"vector\": \"vector\",\n        \"metadata\": \"metadata\",\n    }\n    database: str = \"default\"\n    table: str = \"langchain\"\n    metric: str = \"Cosine\"\n    def __getitem__(self, item: str) -> Any:\n        return getattr(self, item)\n    class Config:\n        env_file = \".env\"\n        env_prefix = \"myscale_\"\n        env_file_encoding = \"utf-8\"\n[docs]class MyScale(VectorStore):\n    \"\"\"`MyScale` vector store.\n    You need a `clickhouse-connect` python package, and a valid account\n    to connect to MyScale.\n    MyScale can not only search with simple vector indexes.\n    It also supports a complex query with multiple conditions,\n    constraints and even sub-queries.\n    For more information, please visit", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-2", "text": "constraints and even sub-queries.\n    For more information, please visit\n        [myscale official site](https://docs.myscale.com/en/overview/)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        config: Optional[MyScaleSettings] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"MyScale Wrapper to LangChain\n        embedding (Embeddings):\n        config (MyScaleSettings): Configuration to MyScale Client\n        Other keyword arguments will pass into\n            [clickhouse-connect](https://docs.myscale.com/)\n        \"\"\"\n        try:\n            from clickhouse_connect import get_client\n        except ImportError:\n            raise ImportError(\n                \"Could not import clickhouse connect python package. \"\n                \"Please install it with `pip install clickhouse-connect`.\"\n            )\n        try:\n            from tqdm import tqdm\n            self.pgbar = tqdm\n        except ImportError:\n            # Just in case if tqdm is not installed\n            self.pgbar = lambda x: x\n        super().__init__()\n        if config is not None:\n            self.config = config\n        else:\n            self.config = MyScaleSettings()\n        assert self.config\n        assert self.config.host and self.config.port\n        assert (\n            self.config.column_map\n            and self.config.database\n            and self.config.table\n            and self.config.metric\n        )\n        for k in [\"id\", \"vector\", \"text\", \"metadata\"]:\n            assert k in self.config.column_map\n        assert self.config.metric.upper() in [\"IP\", \"COSINE\", \"L2\"]\n        if self.config.metric in [\"ip\", \"cosine\", \"l2\"]:\n            logger.warning(\n                \"Lower case metric types will be deprecated \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-3", "text": "logger.warning(\n                \"Lower case metric types will be deprecated \"\n                \"the future. Please use one of ('IP', 'Cosine', 'L2')\"\n            )\n        # initialize the schema\n        dim = len(embedding.embed_query(\"try this out\"))\n        index_params = (\n            \", \" + \",\".join([f\"'{k}={v}'\" for k, v in self.config.index_param.items()])\n            if self.config.index_param\n            else \"\"\n        )\n        schema_ = f\"\"\"\n            CREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}(\n                {self.config.column_map['id']} String,\n                {self.config.column_map['text']} String,\n                {self.config.column_map['vector']} Array(Float32),\n                {self.config.column_map['metadata']} JSON,\n                CONSTRAINT cons_vec_len CHECK length(\\\n                    {self.config.column_map['vector']}) = {dim},\n                VECTOR INDEX vidx {self.config.column_map['vector']} \\\n                    TYPE {self.config.index_type}(\\\n                        'metric_type={self.config.metric}'{index_params})\n            ) ENGINE = MergeTree ORDER BY {self.config.column_map['id']}\n        \"\"\"\n        self.dim = dim\n        self.BS = \"\\\\\"\n        self.must_escape = (\"\\\\\", \"'\")\n        self._embeddings = embedding\n        self.dist_order = (\n            \"ASC\" if self.config.metric.upper() in [\"COSINE\", \"L2\"] else \"DESC\"\n        )\n        # Create a connection to myscale\n        self.client = get_client(\n            host=self.config.host,\n            port=self.config.port,\n            username=self.config.username,\n            password=self.config.password,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-4", "text": "password=self.config.password,\n            **kwargs,\n        )\n        self.client.command(\"SET allow_experimental_object_type=1\")\n        self.client.command(schema_)\n    @property\n    def embeddings(self) -> Embeddings:\n        return self._embeddings\n[docs]    def escape_str(self, value: str) -> str:\n        return \"\".join(f\"{self.BS}{c}\" if c in self.must_escape else c for c in value)\n    def _build_istr(self, transac: Iterable, column_names: Iterable[str]) -> str:\n        ks = \",\".join(column_names)\n        _data = []\n        for n in transac:\n            n = \",\".join([f\"'{self.escape_str(str(_n))}'\" for _n in n])\n            _data.append(f\"({n})\")\n        i_str = f\"\"\"\n                INSERT INTO TABLE \n                    {self.config.database}.{self.config.table}({ks})\n                VALUES\n                {','.join(_data)}\n                \"\"\"\n        return i_str\n    def _insert(self, transac: Iterable, column_names: Iterable[str]) -> None:\n        _i_str = self._build_istr(transac, column_names)\n        self.client.command(_i_str)\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        batch_size: int = 32,\n        ids: Optional[Iterable[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            ids: Optional list of ids to associate with the texts.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-5", "text": "ids: Optional list of ids to associate with the texts.\n            batch_size: Batch size of insertion\n            metadata: Optional column data to be inserted\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        # Embed and create the documents\n        ids = ids or [sha1(t.encode(\"utf-8\")).hexdigest() for t in texts]\n        colmap_ = self.config.column_map\n        transac = []\n        column_names = {\n            colmap_[\"id\"]: ids,\n            colmap_[\"text\"]: texts,\n            colmap_[\"vector\"]: map(self._embeddings.embed_query, texts),\n        }\n        metadatas = metadatas or [{} for _ in texts]\n        column_names[colmap_[\"metadata\"]] = map(json.dumps, metadatas)\n        assert len(set(colmap_) - set(column_names)) >= 0\n        keys, values = zip(*column_names.items())\n        try:\n            t = None\n            for v in self.pgbar(\n                zip(*values), desc=\"Inserting data...\", total=len(metadatas)\n            ):\n                assert len(v[keys.index(self.config.column_map[\"vector\"])]) == self.dim\n                transac.append(v)\n                if len(transac) == batch_size:\n                    if t:\n                        t.join()\n                    t = Thread(target=self._insert, args=[transac, keys])\n                    t.start()\n                    transac = []\n            if len(transac) > 0:\n                if t:\n                    t.join()\n                self._insert(transac, keys)\n            return [i for i in ids]\n        except Exception as e:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-6", "text": "return [i for i in ids]\n        except Exception as e:\n            logger.error(f\"\\033[91m\\033[1m{type(e)}\\033[0m \\033[95m{str(e)}\\033[0m\")\n            return []\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: Iterable[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[Dict[Any, Any]]] = None,\n        config: Optional[MyScaleSettings] = None,\n        text_ids: Optional[Iterable[str]] = None,\n        batch_size: int = 32,\n        **kwargs: Any,\n    ) -> MyScale:\n        \"\"\"Create Myscale wrapper with existing texts\n        Args:\n            texts (Iterable[str]): List or tuple of strings to be added\n            embedding (Embeddings): Function to extract text embedding\n            config (MyScaleSettings, Optional): Myscale configuration\n            text_ids (Optional[Iterable], optional): IDs for the texts.\n                                                     Defaults to None.\n            batch_size (int, optional): Batchsize when transmitting data to MyScale.\n                                        Defaults to 32.\n            metadata (List[dict], optional): metadata to texts. Defaults to None.\n            Other keyword arguments will pass into\n                [clickhouse-connect](https://clickhouse.com/docs/en/integrations/python#clickhouse-connect-driver-api)\n        Returns:\n            MyScale Index\n        \"\"\"\n        ctx = cls(embedding, config, **kwargs)\n        ctx.add_texts(texts, ids=text_ids, batch_size=batch_size, metadatas=metadatas)\n        return ctx\n    def __repr__(self) -> str:\n        \"\"\"Text representation for myscale, prints backends, username and schemas.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-7", "text": "\"\"\"Text representation for myscale, prints backends, username and schemas.\n            Easy to use with `str(Myscale())`\n        Returns:\n            repr: string to show connection info and data schema\n        \"\"\"\n        _repr = f\"\\033[92m\\033[1m{self.config.database}.{self.config.table} @ \"\n        _repr += f\"{self.config.host}:{self.config.port}\\033[0m\\n\\n\"\n        _repr += f\"\\033[1musername: {self.config.username}\\033[0m\\n\\nTable Schema:\\n\"\n        _repr += \"-\" * 51 + \"\\n\"\n        for r in self.client.query(\n            f\"DESC {self.config.database}.{self.config.table}\"\n        ).named_results():\n            _repr += (\n                f\"|\\033[94m{r['name']:24s}\\033[0m|\\033[96m{r['type']:24s}\\033[0m|\\n\"\n            )\n        _repr += \"-\" * 51 + \"\\n\"\n        return _repr\n    def _build_qstr(\n        self, q_emb: List[float], topk: int, where_str: Optional[str] = None\n    ) -> str:\n        q_emb_str = \",\".join(map(str, q_emb))\n        if where_str:\n            where_str = f\"PREWHERE {where_str}\"\n        else:\n            where_str = \"\"\n        q_str = f\"\"\"\n            SELECT {self.config.column_map['text']}, \n                {self.config.column_map['metadata']}, dist\n            FROM {self.config.database}.{self.config.table}\n            {where_str}\n            ORDER BY distance({self.config.column_map['vector']}, [{q_emb_str}]) \n                AS dist {self.dist_order}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-8", "text": "AS dist {self.dist_order}\n            LIMIT {topk}\n            \"\"\"\n        return q_str\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Perform a similarity search with MyScale\n        Args:\n            query (str): query string\n            k (int, optional): Top K neighbors to retrieve. Defaults to 4.\n            where_str (Optional[str], optional): where condition string.\n                                                 Defaults to None.\n            NOTE: Please do not let end-user to fill this and always be aware\n                  of SQL injection. When dealing with metadatas, remember to\n                  use `{self.metadata_column}.attribute` instead of `attribute`\n                  alone. The default name for it is `metadata`.\n        Returns:\n            List[Document]: List of Documents\n        \"\"\"\n        return self.similarity_search_by_vector(\n            self._embeddings.embed_query(query), k, where_str, **kwargs\n        )\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        where_str: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform a similarity search with MyScale by vectors\n        Args:\n            query (str): query string\n            k (int, optional): Top K neighbors to retrieve. Defaults to 4.\n            where_str (Optional[str], optional): where condition string.\n                                                 Defaults to None.\n            NOTE: Please do not let end-user to fill this and always be aware\n                  of SQL injection. When dealing with metadatas, remember to", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-9", "text": "of SQL injection. When dealing with metadatas, remember to\n                  use `{self.metadata_column}.attribute` instead of `attribute`\n                  alone. The default name for it is `metadata`.\n        Returns:\n            List[Document]: List of (Document, similarity)\n        \"\"\"\n        q_str = self._build_qstr(embedding, k, where_str)\n        try:\n            return [\n                Document(\n                    page_content=r[self.config.column_map[\"text\"]],\n                    metadata=r[self.config.column_map[\"metadata\"]],\n                )\n                for r in self.client.query(q_str).named_results()\n            ]\n        except Exception as e:\n            logger.error(f\"\\033[91m\\033[1m{type(e)}\\033[0m \\033[95m{str(e)}\\033[0m\")\n            return []\n[docs]    def similarity_search_with_relevance_scores(\n        self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Perform a similarity search with MyScale\n        Args:\n            query (str): query string\n            k (int, optional): Top K neighbors to retrieve. Defaults to 4.\n            where_str (Optional[str], optional): where condition string.\n                                                 Defaults to None.\n            NOTE: Please do not let end-user to fill this and always be aware\n                  of SQL injection. When dealing with metadatas, remember to\n                  use `{self.metadata_column}.attribute` instead of `attribute`\n                  alone. The default name for it is `metadata`.\n        Returns:\n            List[Document]: List of documents most similar to the query text\n            and cosine distance in float for each.\n            Lower score represents more similarity.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-10", "text": "and cosine distance in float for each.\n            Lower score represents more similarity.\n        \"\"\"\n        q_str = self._build_qstr(self._embeddings.embed_query(query), k, where_str)\n        try:\n            return [\n                (\n                    Document(\n                        page_content=r[self.config.column_map[\"text\"]],\n                        metadata=r[self.config.column_map[\"metadata\"]],\n                    ),\n                    r[\"dist\"],\n                )\n                for r in self.client.query(q_str).named_results()\n            ]\n        except Exception as e:\n            logger.error(f\"\\033[91m\\033[1m{type(e)}\\033[0m \\033[95m{str(e)}\\033[0m\")\n            return []\n[docs]    def drop(self) -> None:\n        \"\"\"\n        Helper function: Drop data\n        \"\"\"\n        self.client.command(\n            f\"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}\"\n        )\n[docs]    def delete(\n        self,\n        ids: Optional[List[str]] = None,\n        where_str: Optional[str] = None,\n        **kwargs: Any,\n    ) -> Optional[bool]:\n        \"\"\"Delete by vector ID or other criteria.\n        Args:\n            ids: List of ids to delete.\n            **kwargs: Other keyword arguments that subclasses might use.\n        Returns:\n            Optional[bool]: True if deletion is successful,\n            False otherwise, None if not implemented.\n        \"\"\"\n        assert not (\n            ids is None and where_str is None\n        ), \"You need to specify where to be deleted! Either with `ids` or `where_str`\"\n        conds = []\n        if ids:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-11", "text": "conds = []\n        if ids:\n            conds.extend([f\"{self.config.column_map['id']} = '{id}'\" for id in ids])\n        if where_str:\n            conds.append(where_str)\n        assert len(conds) > 0\n        where_str_final = \" AND \".join(conds)\n        qstr = (\n            f\"DELETE FROM {self.config.database}.{self.config.table} \"\n            f\"WHERE {where_str_final}\"\n        )\n        try:\n            self.client.command(qstr)\n            return True\n        except Exception as e:\n            logger.error(str(e))\n            return False\n    @property\n    def metadata_column(self) -> str:\n        return self.config.column_map[\"metadata\"]\n[docs]class MyScaleWithoutJSON(MyScale):\n    \"\"\"MyScale vector store without metadata column\n    This is super handy if you are working to a SQL-native table\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        config: Optional[MyScaleSettings] = None,\n        must_have_cols: List[str] = [],\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Building a myscale vector store without metadata column\n        embedding (Embeddings): embedding model\n        config (MyScaleSettings): Configuration to MyScale Client\n        must_have_cols (List[str]): column names to be included in query\n        Other keyword arguments will pass into\n            [clickhouse-connect](https://docs.myscale.com/)\n        \"\"\"\n        super().__init__(embedding, config, **kwargs)\n        self.must_have_cols: List[str] = must_have_cols\n    def _build_qstr(\n        self, q_emb: List[float], topk: int, where_str: Optional[str] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-12", "text": ") -> str:\n        q_emb_str = \",\".join(map(str, q_emb))\n        if where_str:\n            where_str = f\"PREWHERE {where_str}\"\n        else:\n            where_str = \"\"\n        q_str = f\"\"\"\n            SELECT {self.config.column_map['text']}, dist, \n                {','.join(self.must_have_cols)}\n            FROM {self.config.database}.{self.config.table}\n            {where_str}\n            ORDER BY distance({self.config.column_map['vector']}, [{q_emb_str}]) \n                AS dist {self.dist_order}\n            LIMIT {topk}\n            \"\"\"\n        return q_str\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        where_str: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform a similarity search with MyScale by vectors\n        Args:\n            query (str): query string\n            k (int, optional): Top K neighbors to retrieve. Defaults to 4.\n            where_str (Optional[str], optional): where condition string.\n                                                 Defaults to None.\n            NOTE: Please do not let end-user to fill this and always be aware\n                  of SQL injection. When dealing with metadatas, remember to\n                  use `{self.metadata_column}.attribute` instead of `attribute`\n                  alone. The default name for it is `metadata`.\n        Returns:\n            List[Document]: List of (Document, similarity)\n        \"\"\"\n        q_str = self._build_qstr(embedding, k, where_str)\n        try:\n            return [\n                Document(\n                    page_content=r[self.config.column_map[\"text\"]],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-13", "text": "Document(\n                    page_content=r[self.config.column_map[\"text\"]],\n                    metadata={k: r[k] for k in self.must_have_cols},\n                )\n                for r in self.client.query(q_str).named_results()\n            ]\n        except Exception as e:\n            logger.error(f\"\\033[91m\\033[1m{type(e)}\\033[0m \\033[95m{str(e)}\\033[0m\")\n            return []\n[docs]    def similarity_search_with_relevance_scores(\n        self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Perform a similarity search with MyScale\n        Args:\n            query (str): query string\n            k (int, optional): Top K neighbors to retrieve. Defaults to 4.\n            where_str (Optional[str], optional): where condition string.\n                                                 Defaults to None.\n            NOTE: Please do not let end-user to fill this and always be aware\n                  of SQL injection. When dealing with metadatas, remember to\n                  use `{self.metadata_column}.attribute` instead of `attribute`\n                  alone. The default name for it is `metadata`.\n        Returns:\n            List[Document]: List of documents most similar to the query text\n            and cosine distance in float for each.\n            Lower score represents more similarity.\n        \"\"\"\n        q_str = self._build_qstr(self._embeddings.embed_query(query), k, where_str)\n        try:\n            return [\n                (\n                    Document(\n                        page_content=r[self.config.column_map[\"text\"]],\n                        metadata={k: r[k] for k in self.must_have_cols},\n                    ),\n                    r[\"dist\"],\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "1544452feae7-14", "text": "),\n                    r[\"dist\"],\n                )\n                for r in self.client.query(q_str).named_results()\n            ]\n        except Exception as e:\n            logger.error(f\"\\033[91m\\033[1m{type(e)}\\033[0m \\033[95m{str(e)}\\033[0m\")\n            return []\n    @property\n    def metadata_column(self) -> str:\n        return \"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html"}
{"id": "9e5865f764a7-0", "text": "Source code for langchain.vectorstores.meilisearch\nfrom __future__ import annotations\nimport uuid\nfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_env\nif TYPE_CHECKING:\n    from meilisearch import Client\ndef _create_client(\n    client: Optional[Client] = None,\n    url: Optional[str] = None,\n    api_key: Optional[str] = None,\n) -> Client:\n    try:\n        import meilisearch\n    except ImportError:\n        raise ImportError(\n            \"Could not import meilisearch python package. \"\n            \"Please install it with `pip install meilisearch`.\"\n        )\n    if not client:\n        url = url or get_from_env(\"url\", \"MEILI_HTTP_ADDR\")\n        try:\n            api_key = api_key or get_from_env(\"api_key\", \"MEILI_MASTER_KEY\")\n        except Exception:\n            pass\n        client = meilisearch.Client(url=url, api_key=api_key)\n    elif not isinstance(client, meilisearch.Client):\n        raise ValueError(\n            f\"client should be an instance of meilisearch.Client, \"\n            f\"got {type(client)}\"\n        )\n    try:\n        client.version()\n    except ValueError as e:\n        raise ValueError(f\"Failed to connect to Meilisearch: {e}\")\n    return client\n[docs]class Meilisearch(VectorStore):\n    \"\"\"`Meilisearch` vector store.\n    To use this, you need to have `meilisearch` python package installed,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html"}
{"id": "9e5865f764a7-1", "text": "To use this, you need to have `meilisearch` python package installed,\n    and a running Meilisearch instance.\n    To learn more about Meilisearch Python, refer to the in-depth\n    Meilisearch Python documentation: https://meilisearch.github.io/meilisearch-python/.\n    See the following documentation for how to run a Meilisearch instance:\n    https://www.meilisearch.com/docs/learn/getting_started/quick_start.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import Meilisearch\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            import meilisearch\n            # api_key is optional; provide it if your meilisearch instance requires it\n            client = meilisearch.Client(url='http://127.0.0.1:7700', api_key='***')\n            embeddings = OpenAIEmbeddings()\n            vectorstore = Meilisearch(\n                embedding=embeddings,\n                client=client,\n                index_name='langchain_demo',\n                text_key='text')\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        client: Optional[Client] = None,\n        url: Optional[str] = None,\n        api_key: Optional[str] = None,\n        index_name: str = \"langchain-demo\",\n        text_key: str = \"text\",\n        metadata_key: str = \"metadata\",\n    ):\n        \"\"\"Initialize with Meilisearch client.\"\"\"\n        client = _create_client(client=client, url=url, api_key=api_key)\n        self._client = client\n        self._index_name = index_name\n        self._embedding = embedding", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html"}
{"id": "9e5865f764a7-2", "text": "self._index_name = index_name\n        self._embedding = embedding\n        self._text_key = text_key\n        self._metadata_key = metadata_key\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embedding and add them to the vector store.\n        Args:\n            texts (Iterable[str]): Iterable of strings/text to add to the vectorstore.\n            metadatas (Optional[List[dict]]): Optional list of metadata.\n                Defaults to None.\n            ids Optional[List[str]]: Optional list of IDs.\n                Defaults to None.\n        Returns:\n            List[str]: List of IDs of the texts added to the vectorstore.\n        \"\"\"\n        texts = list(texts)\n        # Embed and create the documents\n        docs = []\n        if ids is None:\n            ids = [uuid.uuid4().hex for _ in texts]\n        if metadatas is None:\n            metadatas = [{} for _ in texts]\n        embedding_vectors = self._embedding.embed_documents(texts)\n        for i, text in enumerate(texts):\n            id = ids[i]\n            metadata = metadatas[i]\n            metadata[self._text_key] = text\n            embedding = embedding_vectors[i]\n            docs.append(\n                {\n                    \"id\": id,\n                    \"_vectors\": embedding,\n                    f\"{self._metadata_key}\": metadata,\n                }\n            )\n        # Send to Meilisearch\n        self._client.index(str(self._index_name)).add_documents(docs)\n        return ids\n[docs]    def similarity_search(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html"}
{"id": "9e5865f764a7-3", "text": "return ids\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return meilisearch documents most similar to the query.\n        Args:\n            query (str): Query text for which to find similar documents.\n            k (int): Number of documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata.\n                Defaults to None.\n        Returns:\n            List[Document]: List of Documents most similar to the query\n            text and score for each.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(\n            query=query,\n            k=k,\n            filter=filter,\n            kwargs=kwargs,\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return meilisearch documents most similar to the query, along with scores.\n        Args:\n            query (str): Query text for which to find similar documents.\n            k (int): Number of documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata.\n                Defaults to None.\n        Returns:\n            List[Document]: List of Documents most similar to the query\n            text and score for each.\n        \"\"\"\n        _query = self._embedding.embed_query(query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html"}
{"id": "9e5865f764a7-4", "text": "\"\"\"\n        _query = self._embedding.embed_query(query)\n        docs = self.similarity_search_by_vector_with_scores(\n            embedding=_query,\n            k=k,\n            filter=filter,\n            kwargs=kwargs,\n        )\n        return docs\n[docs]    def similarity_search_by_vector_with_scores(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return meilisearch documents most similar to embedding vector.\n        Args:\n            embedding (List[float]): Embedding to look up similar documents.\n            k (int): Number of documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata.\n                Defaults to None.\n        Returns:\n            List[Document]: List of Documents most similar to the query\n                vector and score for each.\n        \"\"\"\n        docs = []\n        results = self._client.index(str(self._index_name)).search(\n            \"\", {\"vector\": embedding, \"limit\": k, \"filter\": filter}\n        )\n        for result in results[\"hits\"]:\n            metadata = result[self._metadata_key]\n            if self._text_key in metadata:\n                text = metadata.pop(self._text_key)\n                semantic_score = result[\"_semanticScore\"]\n                docs.append(\n                    (Document(page_content=text, metadata=metadata), semantic_score)\n                )\n        return docs\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html"}
{"id": "9e5865f764a7-5", "text": "**kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return meilisearch documents most similar to embedding vector.\n        Args:\n            embedding (List[float]): Embedding to look up similar documents.\n            k (int): Number of documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata.\n                Defaults to None.\n        Returns:\n            List[Document]: List of Documents most similar to the query\n                vector and score for each.\n        \"\"\"\n        docs = self.similarity_search_by_vector_with_scores(\n            embedding=embedding,\n            k=k,\n            filter=filter,\n            kwargs=kwargs,\n        )\n        return [doc for doc, _ in docs]\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[Meilisearch],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        client: Optional[Client] = None,\n        url: Optional[str] = None,\n        api_key: Optional[str] = None,\n        index_name: str = \"langchain-demo\",\n        ids: Optional[List[str]] = None,\n        text_key: Optional[str] = \"text\",\n        metadata_key: Optional[str] = \"metadata\",\n        **kwargs: Any,\n    ) -> Meilisearch:\n        \"\"\"Construct Meilisearch wrapper from raw documents.\n        This is a user-friendly interface that:\n            1. Embeds documents.\n            2. Adds the documents to a provided Meilisearch index.\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html"}
{"id": "9e5865f764a7-6", "text": "Example:\n            .. code-block:: python\n                from langchain.vectorstores import Meilisearch\n                from langchain.embeddings import OpenAIEmbeddings\n                import meilisearch\n                # The environment should be the one specified next to the API key\n                # in your Meilisearch console\n                client = meilisearch.Client(url='http://127.0.0.1:7700', api_key='***')\n                embeddings = OpenAIEmbeddings()\n                docsearch = Meilisearch.from_texts(\n                    client=client,\n                    embeddings=embeddings,\n                )\n        \"\"\"\n        client = _create_client(client=client, url=url, api_key=api_key)\n        vectorstore = cls(\n            embedding=embedding,\n            client=client,\n            index_name=index_name,\n        )\n        vectorstore.add_texts(\n            texts=texts,\n            metadatas=metadatas,\n            ids=ids,\n            text_key=text_key,\n            metadata_key=metadata_key,\n        )\n        return vectorstore", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html"}
{"id": "f655d0022c59-0", "text": "Source code for langchain.vectorstores.singlestoredb\nfrom __future__ import annotations\nimport json\nimport re\nfrom typing import (\n    Any,\n    Callable,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n)\nfrom sqlalchemy.pool import QueuePool\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore, VectorStoreRetriever\nfrom langchain.vectorstores.utils import DistanceStrategy\nDEFAULT_DISTANCE_STRATEGY = DistanceStrategy.DOT_PRODUCT\nORDERING_DIRECTIVE: dict = {\n    DistanceStrategy.EUCLIDEAN_DISTANCE: \"\",\n    DistanceStrategy.DOT_PRODUCT: \"DESC\",\n}\n[docs]class SingleStoreDB(VectorStore):\n    \"\"\"`SingleStore DB` vector store.\n    The prerequisite for using this class is the installation of the ``singlestoredb``\n    Python package.\n    The SingleStoreDB vectorstore can be created by providing an embedding function and\n    the relevant parameters for the database connection, connection pool, and\n    optionally, the names of the table and the fields to use.\n    \"\"\"\n    def _get_connection(self: SingleStoreDB) -> Any:\n        try:\n            import singlestoredb as s2\n        except ImportError:\n            raise ImportError(\n                \"Could not import singlestoredb python package. \"\n                \"Please install it with `pip install singlestoredb`.\"\n            )\n        return s2.connect(**self.connection_kwargs)\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        *,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        table_name: str = \"embeddings\",\n        content_field: str = \"content\",\n        metadata_field: str = \"metadata\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html"}
{"id": "f655d0022c59-1", "text": "content_field: str = \"content\",\n        metadata_field: str = \"metadata\",\n        vector_field: str = \"vector\",\n        pool_size: int = 5,\n        max_overflow: int = 10,\n        timeout: float = 30,\n        **kwargs: Any,\n    ):\n        \"\"\"Initialize with necessary components.\n        Args:\n            embedding (Embeddings): A text embedding model.\n            distance_strategy (DistanceStrategy, optional):\n                Determines the strategy employed for calculating\n                the distance between vectors in the embedding space.\n                Defaults to DOT_PRODUCT.\n                Available options are:\n                - DOT_PRODUCT: Computes the scalar product of two vectors.\n                    This is the default behavior\n                - EUCLIDEAN_DISTANCE: Computes the Euclidean distance between\n                    two vectors. This metric considers the geometric distance in\n                    the vector space, and might be more suitable for embeddings\n                    that rely on spatial relationships.\n            table_name (str, optional): Specifies the name of the table in use.\n                Defaults to \"embeddings\".\n            content_field (str, optional): Specifies the field to store the content.\n                Defaults to \"content\".\n            metadata_field (str, optional): Specifies the field to store metadata.\n                Defaults to \"metadata\".\n            vector_field (str, optional): Specifies the field to store the vector.\n                Defaults to \"vector\".\n            Following arguments pertain to the connection pool:\n            pool_size (int, optional): Determines the number of active connections in\n                the pool. Defaults to 5.\n            max_overflow (int, optional): Determines the maximum number of connections\n                allowed beyond the pool_size. Defaults to 10.\n            timeout (float, optional): Specifies the maximum wait time in seconds for\n                establishing a connection. Defaults to 30.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html"}
{"id": "f655d0022c59-2", "text": "establishing a connection. Defaults to 30.\n            Following arguments pertain to the database connection:\n            host (str, optional): Specifies the hostname, IP address, or URL for the\n                database connection. The default scheme is \"mysql\".\n            user (str, optional): Database username.\n            password (str, optional): Database password.\n            port (int, optional): Database port. Defaults to 3306 for non-HTTP\n                connections, 80 for HTTP connections, and 443 for HTTPS connections.\n            database (str, optional): Database name.\n            Additional optional arguments provide further customization over the\n            database connection:\n            pure_python (bool, optional): Toggles the connector mode. If True,\n                operates in pure Python mode.\n            local_infile (bool, optional): Allows local file uploads.\n            charset (str, optional): Specifies the character set for string values.\n            ssl_key (str, optional): Specifies the path of the file containing the SSL\n                key.\n            ssl_cert (str, optional): Specifies the path of the file containing the SSL\n                certificate.\n            ssl_ca (str, optional): Specifies the path of the file containing the SSL\n                certificate authority.\n            ssl_cipher (str, optional): Sets the SSL cipher list.\n            ssl_disabled (bool, optional): Disables SSL usage.\n            ssl_verify_cert (bool, optional): Verifies the server's certificate.\n                Automatically enabled if ``ssl_ca`` is specified.\n            ssl_verify_identity (bool, optional): Verifies the server's identity.\n            conv (dict[int, Callable], optional): A dictionary of data conversion\n                functions.\n            credential_type (str, optional): Specifies the type of authentication to\n                use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html"}
{"id": "f655d0022c59-3", "text": "use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.\n            autocommit (bool, optional): Enables autocommits.\n            results_type (str, optional): Determines the structure of the query results:\n                tuples, namedtuples, dicts.\n            results_format (str, optional): Deprecated. This option has been renamed to\n                results_type.\n        Examples:\n            Basic Usage:\n            .. code-block:: python\n                from langchain.embeddings import OpenAIEmbeddings\n                from langchain.vectorstores import SingleStoreDB\n                vectorstore = SingleStoreDB(\n                    OpenAIEmbeddings(),\n                    host=\"https://user:password@127.0.0.1:3306/database\"\n                )\n            Advanced Usage:\n            .. code-block:: python\n                from langchain.embeddings import OpenAIEmbeddings\n                from langchain.vectorstores import SingleStoreDB\n                vectorstore = SingleStoreDB(\n                    OpenAIEmbeddings(),\n                    distance_strategy=DistanceStrategy.EUCLIDEAN_DISTANCE,\n                    host=\"127.0.0.1\",\n                    port=3306,\n                    user=\"user\",\n                    password=\"password\",\n                    database=\"db\",\n                    table_name=\"my_custom_table\",\n                    pool_size=10,\n                    timeout=60,\n                )\n            Using environment variables:\n            .. code-block:: python\n                from langchain.embeddings import OpenAIEmbeddings\n                from langchain.vectorstores import SingleStoreDB\n                os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'\n                vectorstore = SingleStoreDB(OpenAIEmbeddings())\n        \"\"\"\n        self.embedding = embedding\n        self.distance_strategy = distance_strategy\n        self.table_name = self._sanitize_input(table_name)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html"}
{"id": "f655d0022c59-4", "text": "self.table_name = self._sanitize_input(table_name)\n        self.content_field = self._sanitize_input(content_field)\n        self.metadata_field = self._sanitize_input(metadata_field)\n        self.vector_field = self._sanitize_input(vector_field)\n        # Pass the rest of the kwargs to the connection.\n        self.connection_kwargs = kwargs\n        # Add program name and version to connection attributes.\n        if \"conn_attrs\" not in self.connection_kwargs:\n            self.connection_kwargs[\"conn_attrs\"] = dict()\n        self.connection_kwargs[\"conn_attrs\"][\"_connector_name\"] = \"langchain python sdk\"\n        self.connection_kwargs[\"conn_attrs\"][\"_connector_version\"] = \"1.0.1\"\n        # Create connection pool.\n        self.connection_pool = QueuePool(\n            self._get_connection,\n            max_overflow=max_overflow,\n            pool_size=pool_size,\n            timeout=timeout,\n        )\n        self._create_table()\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding\n    def _sanitize_input(self, input_str: str) -> str:\n        # Remove characters that are not alphanumeric or underscores\n        return re.sub(r\"[^a-zA-Z0-9_]\", \"\", input_str)\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        return self._max_inner_product_relevance_score_fn\n    def _create_table(self: SingleStoreDB) -> None:\n        \"\"\"Create table if it doesn't exist.\"\"\"\n        conn = self.connection_pool.connect()\n        try:\n            cur = conn.cursor()\n            try:\n                cur.execute(\n                    \"\"\"CREATE TABLE IF NOT EXISTS {}\n                    ({} TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci,\n                    {} BLOB, {} JSON);\"\"\".format(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html"}
{"id": "f655d0022c59-5", "text": "{} BLOB, {} JSON);\"\"\".format(\n                        self.table_name,\n                        self.content_field,\n                        self.vector_field,\n                        self.metadata_field,\n                    ),\n                )\n            finally:\n                cur.close()\n        finally:\n            conn.close()\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        embeddings: Optional[List[List[float]]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add more texts to the vectorstore.\n        Args:\n            texts (Iterable[str]): Iterable of strings/text to add to the vectorstore.\n            metadatas (Optional[List[dict]], optional): Optional list of metadatas.\n                Defaults to None.\n            embeddings (Optional[List[List[float]]], optional): Optional pre-generated\n                embeddings. Defaults to None.\n        Returns:\n            List[str]: empty list\n        \"\"\"\n        conn = self.connection_pool.connect()\n        try:\n            cur = conn.cursor()\n            try:\n                # Write data to singlestore db\n                for i, text in enumerate(texts):\n                    # Use provided values by default or fallback\n                    metadata = metadatas[i] if metadatas else {}\n                    embedding = (\n                        embeddings[i]\n                        if embeddings\n                        else self.embedding.embed_documents([text])[0]\n                    )\n                    cur.execute(\n                        \"INSERT INTO {} VALUES (%s, JSON_ARRAY_PACK(%s), %s)\".format(\n                            self.table_name\n                        ),\n                        (\n                            text,\n                            \"[{}]\".format(\",\".join(map(str, embedding))),\n                            json.dumps(metadata),\n                        ),\n                    )\n            finally:\n                cur.close()\n        finally:\n            conn.close()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html"}
{"id": "f655d0022c59-6", "text": "finally:\n                cur.close()\n        finally:\n            conn.close()\n        return []\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Returns the most similar indexed documents to the query text.\n        Uses cosine similarity.\n        Args:\n            query (str): The query text for which to find similar documents.\n            k (int): The number of documents to return. Default is 4.\n            filter (dict): A dictionary of metadata fields and values to filter by.\n        Returns:\n            List[Document]: A list of documents that are most similar to the query text.\n        Examples:\n            .. code-block:: python\n                from langchain.vectorstores import SingleStoreDB\n                from langchain.embeddings import OpenAIEmbeddings\n                s2 = SingleStoreDB.from_documents(\n                    docs,\n                    OpenAIEmbeddings(),\n                    host=\"username:password@localhost:3306/database\"\n                )\n                s2.similarity_search(\"query text\", 1,\n                    {\"metadata_field\": \"metadata_value\"})\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(\n            query=query, k=k, filter=filter\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 4, filter: Optional[dict] = None\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query. Uses cosine similarity.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html"}
{"id": "f655d0022c59-7", "text": "k: Number of Documents to return. Defaults to 4.\n            filter: A dictionary of metadata fields and values to filter by.\n                    Defaults to None.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        # Creates embedding vector from user query\n        embedding = self.embedding.embed_query(query)\n        conn = self.connection_pool.connect()\n        result = []\n        where_clause: str = \"\"\n        where_clause_values: List[Any] = []\n        if filter:\n            where_clause = \"WHERE \"\n            arguments = []\n            def build_where_clause(\n                where_clause_values: List[Any],\n                sub_filter: dict,\n                prefix_args: Optional[List[str]] = None,\n            ) -> None:\n                prefix_args = prefix_args or []\n                for key in sub_filter.keys():\n                    if isinstance(sub_filter[key], dict):\n                        build_where_clause(\n                            where_clause_values, sub_filter[key], prefix_args + [key]\n                        )\n                    else:\n                        arguments.append(\n                            \"JSON_EXTRACT_JSON({}, {}) = %s\".format(\n                                self.metadata_field,\n                                \", \".join([\"%s\"] * (len(prefix_args) + 1)),\n                            )\n                        )\n                        where_clause_values += prefix_args + [key]\n                        where_clause_values.append(json.dumps(sub_filter[key]))\n            build_where_clause(where_clause_values, filter)\n            where_clause += \" AND \".join(arguments)\n        try:\n            cur = conn.cursor()\n            try:\n                cur.execute(\n                    \"\"\"SELECT {}, {}, {}({}, JSON_ARRAY_PACK(%s)) as __score\n                    FROM {} {} ORDER BY __score {} LIMIT %s\"\"\".format(\n                        self.content_field,\n                        self.metadata_field,\n                        self.distance_strategy.name", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html"}
{"id": "f655d0022c59-8", "text": "self.content_field,\n                        self.metadata_field,\n                        self.distance_strategy.name\n                        if isinstance(self.distance_strategy, DistanceStrategy)\n                        else self.distance_strategy,\n                        self.vector_field,\n                        self.table_name,\n                        where_clause,\n                        ORDERING_DIRECTIVE[self.distance_strategy],\n                    ),\n                    (\"[{}]\".format(\",\".join(map(str, embedding))),)\n                    + tuple(where_clause_values)\n                    + (k,),\n                )\n                for row in cur.fetchall():\n                    doc = Document(page_content=row[0], metadata=row[1])\n                    result.append((doc, float(row[2])))\n            finally:\n                cur.close()\n        finally:\n            conn.close()\n        return result\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[SingleStoreDB],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        table_name: str = \"embeddings\",\n        content_field: str = \"content\",\n        metadata_field: str = \"metadata\",\n        vector_field: str = \"vector\",\n        pool_size: int = 5,\n        max_overflow: int = 10,\n        timeout: float = 30,\n        **kwargs: Any,\n    ) -> SingleStoreDB:\n        \"\"\"Create a SingleStoreDB vectorstore from raw documents.\n        This is a user-friendly interface that:\n            1. Embeds documents.\n            2. Creates a new table for the embeddings in SingleStoreDB.\n            3. Adds the documents to the newly created table.\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html"}
{"id": "f655d0022c59-9", "text": "Example:\n            .. code-block:: python\n                from langchain.vectorstores import SingleStoreDB\n                from langchain.embeddings import OpenAIEmbeddings\n                s2 = SingleStoreDB.from_texts(\n                    texts,\n                    OpenAIEmbeddings(),\n                    host=\"username:password@localhost:3306/database\"\n                )\n        \"\"\"\n        instance = cls(\n            embedding,\n            distance_strategy=distance_strategy,\n            table_name=table_name,\n            content_field=content_field,\n            metadata_field=metadata_field,\n            vector_field=vector_field,\n            pool_size=pool_size,\n            max_overflow=max_overflow,\n            timeout=timeout,\n            **kwargs,\n        )\n        instance.add_texts(texts, metadatas, embedding.embed_documents(texts), **kwargs)\n        return instance\n# SingleStoreDBRetriever is not needed, but we keep it for backwards compatibility\nSingleStoreDBRetriever = VectorStoreRetriever", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html"}
{"id": "7f5bdd22c70f-0", "text": "Source code for langchain.vectorstores.nucliadb\nimport os\nfrom typing import Any, Dict, Iterable, List, Optional, Type\nfrom langchain.schema.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VST, VectorStore\nFIELD_TYPES = {\n    \"f\": \"files\",\n    \"t\": \"texts\",\n    \"l\": \"links\",\n}\n[docs]class NucliaDB(VectorStore):\n    \"\"\"NucliaDB vector store.\"\"\"\n    _config: Dict[str, Any] = {}\n[docs]    def __init__(\n        self,\n        knowledge_box: str,\n        local: bool,\n        api_key: Optional[str] = None,\n        backend: Optional[str] = None,\n    ) -> None:\n        \"\"\"Initialize the NucliaDB client.\n        Args:\n            knowledge_box: the Knowledge Box id.\n            local: Whether to use a local NucliaDB instance or Nuclia Cloud\n            api_key: A contributor API key for the kb (needed when local is False)\n            backend: The backend url to use when local is True, defaults to\n            http://localhost:8080\n        \"\"\"\n        try:\n            from nuclia.sdk import NucliaAuth\n        except ImportError:\n            raise ValueError(\n                \"nuclia python package not found. \"\n                \"Please install it with `pip install nuclia`.\"\n            )\n        self._config[\"LOCAL\"] = local\n        zone = os.environ.get(\"NUCLIA_ZONE\", \"europe-1\")\n        self._kb = knowledge_box\n        if local:\n            if not backend:\n                backend = \"http://localhost:8080\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/nucliadb.html"}
{"id": "7f5bdd22c70f-1", "text": "if not backend:\n                backend = \"http://localhost:8080\"\n            self._config[\"BACKEND\"] = f\"{backend}/api/v1\"\n            self._config[\"TOKEN\"] = None\n            NucliaAuth().nucliadb(url=backend)\n            NucliaAuth().kb(url=self.kb_url, interactive=False)\n        else:\n            self._config[\"BACKEND\"] = f\"https://{zone}.nuclia.cloud/api/v1\"\n            self._config[\"TOKEN\"] = api_key\n            NucliaAuth().kb(\n                url=self.kb_url, token=self._config[\"TOKEN\"], interactive=False\n            )\n    @property\n    def is_local(self) -> str:\n        return self._config[\"LOCAL\"]\n    @property\n    def kb_url(self) -> str:\n        return f\"{self._config['BACKEND']}/kb/{self._kb}\"\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Upload texts to NucliaDB\"\"\"\n        ids = []\n        from nuclia.sdk import NucliaResource\n        factory = NucliaResource()\n        for i, text in enumerate(texts):\n            extra: Dict[str, Any] = {\"metadata\": \"\"}\n            if metadatas:\n                extra = {\"metadata\": metadatas[i]}\n            id = factory.create(\n                texts={\"text\": {\"body\": text}},\n                extra=extra,\n                url=self.kb_url,\n                api_key=self._config[\"TOKEN\"],\n            )\n            ids.append(id)\n        return ids", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/nucliadb.html"}
{"id": "7f5bdd22c70f-2", "text": ")\n            ids.append(id)\n        return ids\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:\n        if not ids:\n            return None\n        from nuclia.sdk import NucliaResource\n        factory = NucliaResource()\n        results: List[bool] = []\n        for id in ids:\n            try:\n                factory.delete(rid=id, url=self.kb_url, api_key=self._config[\"TOKEN\"])\n                results.append(True)\n            except ValueError:\n                results.append(False)\n        return all(results)\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        from nuclia.sdk import NucliaSearch\n        from nucliadb_models.search import FindRequest, ResourceProperties\n        request = FindRequest(\n            query=query,\n            page_size=k,\n            show=[ResourceProperties.VALUES, ResourceProperties.EXTRA],\n        )\n        search = NucliaSearch()\n        results = search.find(\n            query=request, url=self.kb_url, api_key=self._config[\"TOKEN\"]\n        )\n        paragraphs = []\n        for resource in results.resources.values():\n            for field in resource.fields.values():\n                for paragraph_id, paragraph in field.paragraphs.items():\n                    info = paragraph_id.split(\"/\")\n                    field_type = FIELD_TYPES.get(info[1], None)\n                    field_id = info[2]\n                    if not field_type:\n                        continue\n                    value = getattr(resource.data, field_type, {}).get(field_id, None)\n                    paragraphs.append(\n                        {\n                            \"text\": paragraph.text,\n                            \"metadata\": {\n                                \"extra\": getattr(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/nucliadb.html"}
{"id": "7f5bdd22c70f-3", "text": "\"metadata\": {\n                                \"extra\": getattr(\n                                    getattr(resource, \"extra\", {}), \"metadata\", None\n                                ),\n                                \"value\": value,\n                            },\n                            \"order\": paragraph.order,\n                        }\n                    )\n        sorted_paragraphs = sorted(paragraphs, key=lambda x: x[\"order\"])\n        return [\n            Document(page_content=paragraph[\"text\"], metadata=paragraph[\"metadata\"])\n            for paragraph in sorted_paragraphs\n        ]\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[VST],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> VST:\n        \"\"\"Return VectorStore initialized from texts and embeddings.\"\"\"\n        raise NotImplementedError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/nucliadb.html"}
{"id": "07301f37fbdb-0", "text": "Source code for langchain.vectorstores.hologres\nfrom __future__ import annotations\nimport json\nimport logging\nimport uuid\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Type\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_dict_or_env\nADA_TOKEN_COUNT = 1536\n_LANGCHAIN_DEFAULT_TABLE_NAME = \"langchain_pg_embedding\"\n[docs]class HologresWrapper:\n    \"\"\"`Hologres API` wrapper.\"\"\"\n[docs]    def __init__(self, connection_string: str, ndims: int, table_name: str) -> None:\n        \"\"\"Initialize the wrapper.\n        Args:\n            connection_string: Hologres connection string.\n            ndims: Number of dimensions of the embedding output.\n            table_name: Name of the table to store embeddings and data.\n        \"\"\"\n        import psycopg2\n        self.table_name = table_name\n        self.conn = psycopg2.connect(connection_string)\n        self.cursor = self.conn.cursor()\n        self.conn.autocommit = False\n        self.ndims = ndims\n[docs]    def create_vector_extension(self) -> None:\n        self.cursor.execute(\"create extension if not exists proxima\")\n        self.conn.commit()\n[docs]    def create_table(self, drop_if_exist: bool = True) -> None:\n        if drop_if_exist:\n            self.cursor.execute(f\"drop table if exists {self.table_name}\")\n        self.conn.commit()\n        self.cursor.execute(\n            f\"\"\"create table if not exists {self.table_name} (\nid text,\nembedding float4[] check(array_ndims(embedding) = 1 and \\\narray_length(embedding, 1) = {self.ndims}),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html"}
{"id": "07301f37fbdb-1", "text": "array_length(embedding, 1) = {self.ndims}),\nmetadata json,\ndocument text);\"\"\"\n        )\n        self.cursor.execute(\n            f\"call set_table_property('{self.table_name}'\"\n            + \"\"\", 'proxima_vectors', \n'{\"embedding\":{\"algorithm\":\"Graph\",\n\"distance_method\":\"SquaredEuclidean\",\n\"build_params\":{\"min_flush_proxima_row_count\" : 1,\n\"min_compaction_proxima_row_count\" : 1, \n\"max_total_size_to_merge_mb\" : 2000}}}');\"\"\"\n        )\n        self.conn.commit()\n[docs]    def get_by_id(self, id: str) -> List[Tuple]:\n        statement = (\n            f\"select id, embedding, metadata, \"\n            f\"document from {self.table_name} where id = %s;\"\n        )\n        self.cursor.execute(\n            statement,\n            (id),\n        )\n        self.conn.commit()\n        return self.cursor.fetchall()\n[docs]    def insert(\n        self,\n        embedding: List[float],\n        metadata: dict,\n        document: str,\n        id: Optional[str] = None,\n    ) -> None:\n        self.cursor.execute(\n            f'insert into \"{self.table_name}\" '\n            f\"values (%s, array{json.dumps(embedding)}::float4[], %s, %s)\",\n            (id if id is not None else \"null\", json.dumps(metadata), document),\n        )\n        self.conn.commit()\n[docs]    def query_nearest_neighbours(\n        self, embedding: List[float], k: int, filter: Optional[Dict[str, str]] = None\n    ) -> List[Tuple[str, str, float]]:\n        params = []\n        filter_clause = \"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html"}
{"id": "07301f37fbdb-2", "text": "params = []\n        filter_clause = \"\"\n        if filter is not None:\n            conjuncts = []\n            for key, val in filter.items():\n                conjuncts.append(\"metadata->>%s=%s\")\n                params.append(key)\n                params.append(val)\n            filter_clause = \"where \" + \" and \".join(conjuncts)\n        sql = (\n            f\"select document, metadata::text, \"\n            f\"pm_approx_squared_euclidean_distance(array{json.dumps(embedding)}\"\n            f\"::float4[], embedding) as distance from\"\n            f\" {self.table_name} {filter_clause} order by distance asc limit {k};\"\n        )\n        self.cursor.execute(sql, tuple(params))\n        self.conn.commit()\n        return self.cursor.fetchall()\n[docs]class Hologres(VectorStore):\n    \"\"\"`Hologres API` vector store.\n    - `connection_string` is a hologres connection string.\n    - `embedding_function` any embedding function implementing\n        `langchain.embeddings.base.Embeddings` interface.\n    - `ndims` is the number of dimensions of the embedding output.\n    - `table_name` is the name of the table to store embeddings and data.\n        (default: langchain_pg_embedding)\n        - NOTE: The table will be created when initializing the store (if not exists)\n            So, make sure the user has the right permissions to create tables.\n    - `pre_delete_table` if True, will delete the table if it exists.\n        (default: False)\n        - Useful for testing.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        connection_string: str,\n        embedding_function: Embeddings,\n        ndims: int = ADA_TOKEN_COUNT,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html"}
{"id": "07301f37fbdb-3", "text": "embedding_function: Embeddings,\n        ndims: int = ADA_TOKEN_COUNT,\n        table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME,\n        pre_delete_table: bool = False,\n        logger: Optional[logging.Logger] = None,\n    ) -> None:\n        self.connection_string = connection_string\n        self.ndims = ndims\n        self.table_name = table_name\n        self.embedding_function = embedding_function\n        self.pre_delete_table = pre_delete_table\n        self.logger = logger or logging.getLogger(__name__)\n        self.__post_init__()\n    def __post_init__(\n        self,\n    ) -> None:\n        \"\"\"\n        Initialize the store.\n        \"\"\"\n        self.storage = HologresWrapper(\n            self.connection_string, self.ndims, self.table_name\n        )\n        self.create_vector_extension()\n        self.create_table()\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding_function\n[docs]    def create_vector_extension(self) -> None:\n        try:\n            self.storage.create_vector_extension()\n        except Exception as e:\n            self.logger.exception(e)\n            raise e\n[docs]    def create_table(self) -> None:\n        self.storage.create_table(self.pre_delete_table)\n    @classmethod\n    def __from(\n        cls,\n        texts: List[str],\n        embeddings: List[List[float]],\n        embedding_function: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        ndims: int = ADA_TOKEN_COUNT,\n        table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME,\n        pre_delete_table: bool = False,\n        **kwargs: Any,\n    ) -> Hologres:\n        if ids is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html"}
{"id": "07301f37fbdb-4", "text": ") -> Hologres:\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        if not metadatas:\n            metadatas = [{} for _ in texts]\n        connection_string = cls.get_connection_string(kwargs)\n        store = cls(\n            connection_string=connection_string,\n            embedding_function=embedding_function,\n            ndims=ndims,\n            table_name=table_name,\n            pre_delete_table=pre_delete_table,\n        )\n        store.add_embeddings(\n            texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs\n        )\n        return store\n[docs]    def add_embeddings(\n        self,\n        texts: Iterable[str],\n        embeddings: List[List[float]],\n        metadatas: List[dict],\n        ids: List[str],\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Add embeddings to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            embeddings: List of list of embedding vectors.\n            metadatas: List of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        \"\"\"\n        try:\n            for text, metadata, embedding, id in zip(texts, metadatas, embeddings, ids):\n                self.storage.insert(embedding, metadata, text, id)\n        except Exception as e:\n            self.logger.exception(e)\n            self.storage.conn.commit()\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html"}
{"id": "07301f37fbdb-5", "text": "**kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        embeddings = self.embedding_function.embed_documents(list(texts))\n        if not metadatas:\n            metadatas = [{} for _ in texts]\n        self.add_embeddings(texts, embeddings, metadatas, ids, **kwargs)\n        return ids\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Run similarity search with Hologres with distance.\n        Args:\n            query (str): Query text to search for.\n            k (int): Number of results to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        embedding = self.embedding_function.embed_query(text=query)\n        return self.similarity_search_by_vector(\n            embedding=embedding,\n            k=k,\n            filter=filter,\n        )\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[dict] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html"}
{"id": "07301f37fbdb-6", "text": "k: int = 4,\n        filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query vector.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, filter=filter\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[dict] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        embedding = self.embedding_function.embed_query(query)\n        docs = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, filter=filter\n        )\n        return docs\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[dict] = None,\n    ) -> List[Tuple[Document, float]]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html"}
{"id": "07301f37fbdb-7", "text": ") -> List[Tuple[Document, float]]:\n        results: List[Tuple[str, str, float]] = self.storage.query_nearest_neighbours(\n            embedding, k, filter\n        )\n        docs = [\n            (\n                Document(\n                    page_content=result[0],\n                    metadata=json.loads(result[1]),\n                ),\n                result[2],\n            )\n            for result in results\n        ]\n        return docs\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[Hologres],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ndims: int = ADA_TOKEN_COUNT,\n        table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME,\n        ids: Optional[List[str]] = None,\n        pre_delete_table: bool = False,\n        **kwargs: Any,\n    ) -> Hologres:\n        \"\"\"\n        Return VectorStore initialized from texts and embeddings.\n        Postgres connection string is required\n        \"Either pass it as a parameter\n        or set the HOLOGRES_CONNECTION_STRING environment variable.\n        \"\"\"\n        embeddings = embedding.embed_documents(list(texts))\n        return cls.__from(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            ndims=ndims,\n            table_name=table_name,\n            pre_delete_table=pre_delete_table,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_embeddings(\n        cls,\n        text_embeddings: List[Tuple[str, List[float]]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ndims: int = ADA_TOKEN_COUNT,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html"}
{"id": "07301f37fbdb-8", "text": "ndims: int = ADA_TOKEN_COUNT,\n        table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME,\n        ids: Optional[List[str]] = None,\n        pre_delete_table: bool = False,\n        **kwargs: Any,\n    ) -> Hologres:\n        \"\"\"Construct Hologres wrapper from raw documents and pre-\n        generated embeddings.\n        Return VectorStore initialized from documents and embeddings.\n        Postgres connection string is required\n        \"Either pass it as a parameter\n        or set the HOLOGRES_CONNECTION_STRING environment variable.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import Hologres\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                text_embeddings = embeddings.embed_documents(texts)\n                text_embedding_pairs = list(zip(texts, text_embeddings))\n                faiss = Hologres.from_embeddings(text_embedding_pairs, embeddings)\n        \"\"\"\n        texts = [t[0] for t in text_embeddings]\n        embeddings = [t[1] for t in text_embeddings]\n        return cls.__from(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            ndims=ndims,\n            table_name=table_name,\n            pre_delete_table=pre_delete_table,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_existing_index(\n        cls: Type[Hologres],\n        embedding: Embeddings,\n        ndims: int = ADA_TOKEN_COUNT,\n        table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME,\n        pre_delete_table: bool = False,\n        **kwargs: Any,\n    ) -> Hologres:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html"}
{"id": "07301f37fbdb-9", "text": "**kwargs: Any,\n    ) -> Hologres:\n        \"\"\"\n        Get instance of an existing Hologres store.This method will\n        return the instance of the store without inserting any new\n        embeddings\n        \"\"\"\n        connection_string = cls.get_connection_string(kwargs)\n        store = cls(\n            connection_string=connection_string,\n            ndims=ndims,\n            table_name=table_name,\n            embedding_function=embedding,\n            pre_delete_table=pre_delete_table,\n        )\n        return store\n[docs]    @classmethod\n    def get_connection_string(cls, kwargs: Dict[str, Any]) -> str:\n        connection_string: str = get_from_dict_or_env(\n            data=kwargs,\n            key=\"connection_string\",\n            env_key=\"HOLOGRES_CONNECTION_STRING\",\n        )\n        if not connection_string:\n            raise ValueError(\n                \"Postgres connection string is required\"\n                \"Either pass it as a parameter\"\n                \"or set the HOLOGRES_CONNECTION_STRING environment variable.\"\n            )\n        return connection_string\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[Hologres],\n        documents: List[Document],\n        embedding: Embeddings,\n        ndims: int = ADA_TOKEN_COUNT,\n        table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME,\n        ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> Hologres:\n        \"\"\"\n        Return VectorStore initialized from documents and embeddings.\n        Postgres connection string is required\n        \"Either pass it as a parameter\n        or set the HOLOGRES_CONNECTION_STRING environment variable.\n        \"\"\"\n        texts = [d.page_content for d in documents]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html"}
{"id": "07301f37fbdb-10", "text": "\"\"\"\n        texts = [d.page_content for d in documents]\n        metadatas = [d.metadata for d in documents]\n        connection_string = cls.get_connection_string(kwargs)\n        kwargs[\"connection_string\"] = connection_string\n        return cls.from_texts(\n            texts=texts,\n            pre_delete_collection=pre_delete_collection,\n            embedding=embedding,\n            metadatas=metadatas,\n            ids=ids,\n            ndims=ndims,\n            table_name=table_name,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def connection_string_from_db_params(\n        cls,\n        host: str,\n        port: int,\n        database: str,\n        user: str,\n        password: str,\n    ) -> str:\n        \"\"\"Return connection string from database parameters.\"\"\"\n        return (\n            f\"dbname={database} user={user} password={password} host={host} port={port}\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html"}
{"id": "ee245b530eaa-0", "text": "Source code for langchain.vectorstores.utils\n\"\"\"Utility functions for working with vectors and vectorstores.\"\"\"\nfrom enum import Enum\nfrom typing import List, Tuple, Type\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.utils.math import cosine_similarity\n[docs]class DistanceStrategy(str, Enum):\n    \"\"\"Enumerator of the Distance strategies for calculating distances\n    between vectors.\"\"\"\n    EUCLIDEAN_DISTANCE = \"EUCLIDEAN_DISTANCE\"\n    MAX_INNER_PRODUCT = \"MAX_INNER_PRODUCT\"\n    DOT_PRODUCT = \"DOT_PRODUCT\"\n    JACCARD = \"JACCARD\"\n    COSINE = \"COSINE\"\n[docs]def maximal_marginal_relevance(\n    query_embedding: np.ndarray,\n    embedding_list: list,\n    lambda_mult: float = 0.5,\n    k: int = 4,\n) -> List[int]:\n    \"\"\"Calculate maximal marginal relevance.\"\"\"\n    if min(k, len(embedding_list)) <= 0:\n        return []\n    if query_embedding.ndim == 1:\n        query_embedding = np.expand_dims(query_embedding, axis=0)\n    similarity_to_query = cosine_similarity(query_embedding, embedding_list)[0]\n    most_similar = int(np.argmax(similarity_to_query))\n    idxs = [most_similar]\n    selected = np.array([embedding_list[most_similar]])\n    while len(idxs) < min(k, len(embedding_list)):\n        best_score = -np.inf\n        idx_to_add = -1\n        similarity_to_selected = cosine_similarity(embedding_list, selected)\n        for i, query_score in enumerate(similarity_to_query):\n            if i in idxs:\n                continue\n            redundant_score = max(similarity_to_selected[i])\n            equation_score = (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/utils.html"}
{"id": "ee245b530eaa-1", "text": "redundant_score = max(similarity_to_selected[i])\n            equation_score = (\n                lambda_mult * query_score - (1 - lambda_mult) * redundant_score\n            )\n            if equation_score > best_score:\n                best_score = equation_score\n                idx_to_add = i\n        idxs.append(idx_to_add)\n        selected = np.append(selected, [embedding_list[idx_to_add]], axis=0)\n    return idxs\n[docs]def filter_complex_metadata(\n    documents: List[Document],\n    *,\n    allowed_types: Tuple[Type, ...] = (str, bool, int, float),\n) -> List[Document]:\n    \"\"\"Filter out metadata types that are not supported for a vector store.\"\"\"\n    updated_documents = []\n    for document in documents:\n        filtered_metadata = {}\n        for key, value in document.metadata.items():\n            if not isinstance(value, allowed_types):\n                continue\n            filtered_metadata[key] = value\n        document.metadata = filtered_metadata\n        updated_documents.append(document)\n    return updated_documents", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/utils.html"}
{"id": "6910dad2b44b-0", "text": "Source code for langchain.vectorstores.azure_cosmos_db\nfrom __future__ import annotations\nimport logging\nfrom enum import Enum\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Dict,\n    Generator,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    TypeVar,\n    Union,\n)\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.vectorstores.base import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nif TYPE_CHECKING:\n    from pymongo.collection import Collection\n    from langchain.schema.embeddings import Embeddings\n# Before Python 3.11 native StrEnum is not available\n[docs]class CosmosDBSimilarityType(str, Enum):\n    \"\"\"Cosmos DB Similarity Type as enumerator.\"\"\"\n    COS = \"COS\"\n    \"\"\"CosineSimilarity\"\"\"\n    IP = \"IP\"\n    \"\"\"inner - product\"\"\"\n    L2 = \"L2\"\n    \"\"\"Euclidean distance\"\"\"\nCosmosDBDocumentType = TypeVar(\"CosmosDBDocumentType\", bound=Dict[str, Any])\nlogger = logging.getLogger(__name__)\nDEFAULT_INSERT_BATCH_SIZE = 128\n[docs]class AzureCosmosDBVectorSearch(VectorStore):\n    \"\"\"`Azure Cosmos DB for MongoDB vCore` vector store.\n    To use, you should have both:\n    - the ``pymongo`` python package installed\n    - a connection string associated with a MongoDB VCore Cluster\n    Example:\n        . code-block:: python\n            from langchain.vectorstores import AzureCosmosDBVectorSearch\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            from pymongo import MongoClient\n            mongo_client = MongoClient(\"<YOUR-CONNECTION-STRING>\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html"}
{"id": "6910dad2b44b-1", "text": "from pymongo import MongoClient\n            mongo_client = MongoClient(\"<YOUR-CONNECTION-STRING>\")\n            collection = mongo_client[\"<db_name>\"][\"<collection_name>\"]\n            embeddings = OpenAIEmbeddings()\n            vectorstore = AzureCosmosDBVectorSearch(collection, embeddings)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        collection: Collection[CosmosDBDocumentType],\n        embedding: Embeddings,\n        *,\n        index_name: str = \"vectorSearchIndex\",\n        text_key: str = \"textContent\",\n        embedding_key: str = \"vectorContent\",\n    ):\n        \"\"\"Constructor for AzureCosmosDBVectorSearch\n        Args:\n            collection: MongoDB collection to add the texts to.\n            embedding: Text embedding model to use.\n            index_name: Name of the Atlas Search index.\n            text_key: MongoDB field that will contain the text\n                for each document.\n            embedding_key: MongoDB field that will contain the embedding\n                for each document.\n        \"\"\"\n        self._collection = collection\n        self._embedding = embedding\n        self._index_name = index_name\n        self._text_key = text_key\n        self._embedding_key = embedding_key\n    @property\n    def embeddings(self) -> Embeddings:\n        return self._embedding\n[docs]    def get_index_name(self) -> str:\n        \"\"\"Returns the index name\n        Returns:\n            Returns the index name\n        \"\"\"\n        return self._index_name\n[docs]    @classmethod\n    def from_connection_string(\n        cls,\n        connection_string: str,\n        namespace: str,\n        embedding: Embeddings,\n        **kwargs: Any,\n    ) -> AzureCosmosDBVectorSearch:\n        \"\"\"Creates an Instance of AzureCosmosDBVectorSearch from a Connection String", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html"}
{"id": "6910dad2b44b-2", "text": "\"\"\"Creates an Instance of AzureCosmosDBVectorSearch from a Connection String\n        Args:\n            connection_string: The MongoDB vCore instance connection string\n            namespace: The namespace (database.collection)\n            embedding: The embedding utility\n            **kwargs: Dynamic keyword arguments\n        Returns:\n            an instance of the vector store\n        \"\"\"\n        try:\n            from pymongo import MongoClient\n        except ImportError:\n            raise ImportError(\n                \"Could not import pymongo, please install it with \"\n                \"`pip install pymongo`.\"\n            )\n        client: MongoClient = MongoClient(connection_string)\n        db_name, collection_name = namespace.split(\".\")\n        collection = client[db_name][collection_name]\n        return cls(collection, embedding, **kwargs)\n[docs]    def index_exists(self) -> bool:\n        \"\"\"Verifies if the specified index name during instance\n            construction exists on the collection\n        Returns:\n          Returns True on success and False if no such index exists\n            on the collection\n        \"\"\"\n        cursor = self._collection.list_indexes()\n        index_name = self._index_name\n        for res in cursor:\n            current_index_name = res.pop(\"name\")\n            if current_index_name == index_name:\n                return True\n        return False\n[docs]    def delete_index(self) -> None:\n        \"\"\"Deletes the index specified during instance construction if it exists\"\"\"\n        if self.index_exists():\n            self._collection.drop_index(self._index_name)\n            # Raises OperationFailure on an error (e.g. trying to drop\n            # an index that does not exist)\n[docs]    def create_index(\n        self,\n        num_lists: int = 100,\n        dimensions: int = 1536,\n        similarity: CosmosDBSimilarityType = CosmosDBSimilarityType.COS,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html"}
{"id": "6910dad2b44b-3", "text": "similarity: CosmosDBSimilarityType = CosmosDBSimilarityType.COS,\n    ) -> dict[str, Any]:\n        \"\"\"Creates an index using the index name specified at\n            instance construction\n        Setting the numLists parameter correctly is important for achieving\n            good accuracy and performance.\n            Since the vector store uses IVF as the indexing strategy,\n            you should create the index only after you\n            have loaded a large enough sample documents to ensure that the\n            centroids for the respective buckets are\n            faily distributed.\n        We recommend that numLists is set to documentCount/1000 for up\n            to 1 million documents\n            and to sqrt(documentCount) for more than 1 million documents.\n            As the number of items in your database grows, you should\n            tune numLists to be larger\n            in order to achieve good latency performance for vector search.\n            If you're experimenting with a new scenario or creating a\n            small demo, you can start with numLists\n            set to 1 to perform a brute-force search across all vectors.\n            This should provide you with the most\n            accurate results from the vector search, however be aware that\n            the search speed and latency will be slow.\n            After your initial setup, you should go ahead and tune\n            the numLists parameter using the above guidance.\n        Args:\n            num_lists: This integer is the number of clusters that the\n                inverted file (IVF) index uses to group the vector data.\n                We recommend that numLists is set to documentCount/1000\n                for up to 1 million documents and to sqrt(documentCount)\n                for more than 1 million documents.\n                Using a numLists value of 1 is akin to performing\n                brute-force search, which has limited performance\n            dimensions: Number of dimensions for vector similarity.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html"}
{"id": "6910dad2b44b-4", "text": "dimensions: Number of dimensions for vector similarity.\n                The maximum number of supported dimensions is 2000\n            similarity: Similarity metric to use with the IVF index.\n                Possible options are:\n                    - CosmosDBSimilarityType.COS (cosine distance),\n                    - CosmosDBSimilarityType.L2 (Euclidean distance), and\n                    - CosmosDBSimilarityType.IP (inner product).\n        Returns:\n            An object describing the created index\n        \"\"\"\n        # prepare the command\n        create_index_commands = {\n            \"createIndexes\": self._collection.name,\n            \"indexes\": [\n                {\n                    \"name\": self._index_name,\n                    \"key\": {\"vectorContent\": \"cosmosSearch\"},\n                    \"cosmosSearchOptions\": {\n                        \"kind\": \"vector-ivf\",\n                        \"numLists\": num_lists,\n                        \"similarity\": similarity,\n                        \"dimensions\": dimensions,\n                    },\n                }\n            ],\n        }\n        # retrieve the database object\n        current_database = self._collection.database\n        # invoke the command from the database object\n        create_index_responses: dict[str, Any] = current_database.command(\n            create_index_commands\n        )\n        return create_index_responses\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[Dict[str, Any]]] = None,\n        **kwargs: Any,\n    ) -> List:\n        batch_size = kwargs.get(\"batch_size\", DEFAULT_INSERT_BATCH_SIZE)\n        _metadatas: Union[List, Generator] = metadatas or ({} for _ in texts)\n        texts_batch = []\n        metadatas_batch = []\n        result_ids = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html"}
{"id": "6910dad2b44b-5", "text": "texts_batch = []\n        metadatas_batch = []\n        result_ids = []\n        for i, (text, metadata) in enumerate(zip(texts, _metadatas)):\n            texts_batch.append(text)\n            metadatas_batch.append(metadata)\n            if (i + 1) % batch_size == 0:\n                result_ids.extend(self._insert_texts(texts_batch, metadatas_batch))\n                texts_batch = []\n                metadatas_batch = []\n        if texts_batch:\n            result_ids.extend(self._insert_texts(texts_batch, metadatas_batch))\n        return result_ids\n    def _insert_texts(self, texts: List[str], metadatas: List[Dict[str, Any]]) -> List:\n        \"\"\"Used to Load Documents into the collection\n        Args:\n            texts: The list of documents strings to load\n            metadatas: The list of metadata objects associated with each document\n        Returns:\n        \"\"\"\n        # If the text is empty, then exit early\n        if not texts:\n            return []\n        # Embed and create the documents\n        embeddings = self._embedding.embed_documents(texts)\n        to_insert = [\n            {self._text_key: t, self._embedding_key: embedding, **m}\n            for t, m, embedding in zip(texts, metadatas, embeddings)\n        ]\n        # insert the documents in Cosmos DB\n        insert_result = self._collection.insert_many(to_insert)  # type: ignore\n        return insert_result.inserted_ids\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        collection: Optional[Collection[CosmosDBDocumentType]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html"}
{"id": "6910dad2b44b-6", "text": "collection: Optional[Collection[CosmosDBDocumentType]] = None,\n        **kwargs: Any,\n    ) -> AzureCosmosDBVectorSearch:\n        if collection is None:\n            raise ValueError(\"Must provide 'collection' named parameter.\")\n        vectorstore = cls(collection, embedding, **kwargs)\n        vectorstore.add_texts(texts, metadatas=metadatas)\n        return vectorstore\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:\n        if ids is None:\n            raise ValueError(\"No document ids provided to delete.\")\n        for document_id in ids:\n            self.delete_document_by_id(document_id)\n        return True\n[docs]    def delete_document_by_id(self, document_id: Optional[str] = None) -> None:\n        \"\"\"Removes a Specific Document by Id\n        Args:\n            document_id: The document identifier\n        \"\"\"\n        try:\n            from bson.objectid import ObjectId\n        except ImportError as e:\n            raise ImportError(\n                \"Unable to import bson, please install with `pip install bson`.\"\n            ) from e\n        if document_id is None:\n            raise ValueError(\"No document id provided to delete.\")\n        self._collection.delete_one({\"_id\": ObjectId(document_id)})\n    def _similarity_search_with_score(\n        self, embeddings: List[float], k: int = 4\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Returns a list of documents with their scores\n        Args:\n            embeddings: The query vector\n            k: the number of documents to return\n        Returns:\n            A list of documents closest to the query vector\n        \"\"\"\n        pipeline: List[dict[str, Any]] = [\n            {\n                \"$search\": {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html"}
{"id": "6910dad2b44b-7", "text": "{\n                \"$search\": {\n                    \"cosmosSearch\": {\n                        \"vector\": embeddings,\n                        \"path\": self._embedding_key,\n                        \"k\": k,\n                    },\n                    \"returnStoredSource\": True,\n                }\n            },\n            {\n                \"$project\": {\n                    \"similarityScore\": {\"$meta\": \"searchScore\"},\n                    \"document\": \"$$ROOT\",\n                }\n            },\n        ]\n        cursor = self._collection.aggregate(pipeline)\n        docs = []\n        for res in cursor:\n            score = res.pop(\"similarityScore\")\n            document_object_field = res.pop(\"document\")\n            text = document_object_field.pop(self._text_key)\n            docs.append(\n                (Document(page_content=text, metadata=document_object_field), score)\n            )\n        return docs\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 4\n    ) -> List[Tuple[Document, float]]:\n        embeddings = self._embedding.embed_query(query)\n        docs = self._similarity_search_with_score(embeddings=embeddings, k=k)\n        return docs\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        docs_and_scores = self.similarity_search_with_score(query, k=k)\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html"}
{"id": "6910dad2b44b-8", "text": "**kwargs: Any,\n    ) -> List[Document]:\n        # Retrieves the docs with similarity scores\n        # sorted by similarity scores in DESC order\n        docs = self._similarity_search_with_score(embedding, k=fetch_k)\n        # Re-ranks the docs using MMR\n        mmr_doc_indexes = maximal_marginal_relevance(\n            np.array(embedding),\n            [doc.metadata[self._embedding_key] for doc, _ in docs],\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        mmr_docs = [docs[i][0] for i in mmr_doc_indexes]\n        return mmr_docs\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        # compute the embeddings vector from the query string\n        embeddings = self._embedding.embed_query(query)\n        docs = self.max_marginal_relevance_search_by_vector(\n            embeddings, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult\n        )\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azure_cosmos_db.html"}
{"id": "4fcb959a9089-0", "text": "Source code for langchain.vectorstores.deeplake\nfrom __future__ import annotations\nimport logging\nfrom typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union\nimport numpy as np\ntry:\n    import deeplake\n    from deeplake import VectorStore as DeepLakeVectorStore\n    from deeplake.core.fast_forwarding import version_compare\n    _DEEPLAKE_INSTALLED = True\nexcept ImportError:\n    _DEEPLAKE_INSTALLED = False\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nlogger = logging.getLogger(__name__)\n[docs]class DeepLake(VectorStore):\n    \"\"\"`Activeloop Deep Lake` vector store.\n    We integrated deeplake's similarity search and filtering for fast prototyping.\n    Now, it supports Tensor Query Language (TQL) for production use cases\n    over billion rows.\n    Why Deep Lake?\n    - Not only stores embeddings, but also the original data with version control.\n    - Serverless, doesn't require another service and can be used with major\n        cloud providers (S3, GCS, etc.)\n    - More than just a multi-modal vector store. You can use the dataset\n        to fine-tune your own LLM models.\n    To use, you should have the ``deeplake`` python package installed.\n    Example:\n        .. code-block:: python\n                from langchain.vectorstores import DeepLake\n                from langchain.embeddings.openai import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                vectorstore = DeepLake(\"langchain_store\", embeddings.embed_query)\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-1", "text": "vectorstore = DeepLake(\"langchain_store\", embeddings.embed_query)\n    \"\"\"\n    _LANGCHAIN_DEFAULT_DEEPLAKE_PATH = \"./deeplake/\"\n[docs]    def __init__(\n        self,\n        dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH,\n        token: Optional[str] = None,\n        embedding: Optional[Embeddings] = None,\n        embedding_function: Optional[Embeddings] = None,\n        read_only: bool = False,\n        ingestion_batch_size: int = 1000,\n        num_workers: int = 0,\n        verbose: bool = True,\n        exec_option: Optional[str] = None,\n        runtime: Optional[Dict] = None,\n        index_params: Optional[Dict[str, Union[int, str]]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Creates an empty DeepLakeVectorStore or loads an existing one.\n        The DeepLakeVectorStore is located at the specified ``path``.\n        Examples:\n            >>> # Create a vector store with default tensors\n            >>> deeplake_vectorstore = DeepLake(\n            ...        path = <path_for_storing_Data>,\n            ... )\n            >>>\n            >>> # Create a vector store in the Deep Lake Managed Tensor Database\n            >>> data = DeepLake(\n            ...        path = \"hub://org_id/dataset_name\",\n            ...        runtime = {\"tensor_db\": True},\n            ... )\n        Args:\n            dataset_path (str): Path to existing dataset or where to create\n                a new one. Defaults to _LANGCHAIN_DEFAULT_DEEPLAKE_PATH.\n            token (str, optional):  Activeloop token, for fetching credentials\n                to the dataset at path if it is a Deep Lake dataset.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-2", "text": "to the dataset at path if it is a Deep Lake dataset.\n                Tokens are normally autogenerated. Optional.\n            embedding (Embeddings, optional): Function to convert\n                either documents or query. Optional.\n            embedding_function (Embeddings, optional): Function to convert\n                either documents or query. Optional. Deprecated: keeping this\n                parameter for backwards compatibility.\n            read_only (bool): Open dataset in read-only mode. Default is False.\n            ingestion_batch_size (int): During data ingestion, data is divided\n                into batches. Batch size is the size of each batch.\n                Default is 1000.\n            num_workers (int): Number of workers to use during data ingestion.\n                Default is 0.\n            verbose (bool): Print dataset summary after each operation.\n                Default is True.\n            exec_option (str, optional): DeepLakeVectorStore supports 3 ways to perform\n                searching - \"python\", \"compute_engine\", \"tensor_db\" and auto.\n                Default is None.\n                - ``auto``- Selects the best execution method based on the storage\n                    location of the Vector Store. It is the default option.\n                - ``python`` - Pure-python implementation that runs on the client.\n                    WARNING: using this with big datasets can lead to memory\n                    issues. Data can be stored anywhere.\n                - ``compute_engine`` - C++ implementation of the Deep Lake Compute\n                    Engine that runs on the client. Can be used for any data stored in\n                    or connected to Deep Lake. Not for in-memory or local datasets.\n                - ``tensor_db`` - Hosted Managed Tensor Database that is\n                    responsible for storage and query execution. Only for data stored in\n                    the Deep Lake Managed Database. Use runtime = {\"db_engine\": True}\n                    during dataset creation.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-3", "text": "during dataset creation.\n            runtime (Dict, optional): Parameters for creating the Vector Store in\n                Deep Lake's Managed Tensor Database. Not applicable when loading an\n                existing Vector Store. To create a Vector Store in the Managed Tensor\n                Database, set `runtime = {\"tensor_db\": True}`.\n            index_params (Optional[Dict[str, Union[int, str]]], optional): Dictionary\n                containing information about vector index that will be created. Defaults\n                to None, which will utilize ``DEFAULT_VECTORSTORE_INDEX_PARAMS`` from\n                ``deeplake.constants``. The specified key-values override the default\n                ones.\n                - threshold: The threshold for the dataset size above which an index\n                    will be created for the embedding tensor. When the threshold value\n                    is set to -1, index creation is turned off. Defaults to -1, which\n                    turns off the index.\n                - distance_metric: This key specifies the method of calculating the\n                    distance between vectors when creating the vector database (VDB)\n                    index. It can either be a string that corresponds to a member of\n                    the DistanceType enumeration, or the string value itself.\n                    - If no value is provided, it defaults to \"L2\".\n                    - \"L2\" corresponds to DistanceType.L2_NORM.\n                    - \"COS\" corresponds to DistanceType.COSINE_SIMILARITY.\n                - additional_params: Additional parameters for fine-tuning the index.\n            **kwargs: Other optional keyword arguments.\n        Raises:\n            ValueError: If some condition is not met.\n        \"\"\"\n        self.ingestion_batch_size = ingestion_batch_size\n        self.num_workers = num_workers\n        self.verbose = verbose\n        if _DEEPLAKE_INSTALLED is False:\n            raise ImportError(\n                \"Could not import deeplake python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-4", "text": "raise ImportError(\n                \"Could not import deeplake python package. \"\n                \"Please install it with `pip install deeplake[enterprise]`.\"\n            )\n        if (\n            runtime == {\"tensor_db\": True}\n            and version_compare(deeplake.__version__, \"3.6.7\") == -1\n        ):\n            raise ImportError(\n                \"To use tensor_db option you need to update deeplake to `3.6.7` or \"\n                \"higher. \"\n                f\"Currently installed deeplake version is {deeplake.__version__}. \"\n            )\n        self.dataset_path = dataset_path\n        if embedding_function:\n            logger.warning(\n                \"Using embedding function is deprecated and will be removed \"\n                \"in the future. Please use embedding instead.\"\n            )\n        self.vectorstore = DeepLakeVectorStore(\n            path=self.dataset_path,\n            embedding_function=embedding_function or embedding,\n            read_only=read_only,\n            token=token,\n            exec_option=exec_option,\n            verbose=verbose,\n            runtime=runtime,\n            index_params=index_params,\n            **kwargs,\n        )\n        self._embedding_function = embedding_function or embedding\n        self._id_tensor_name = \"ids\" if \"ids\" in self.vectorstore.tensors() else \"id\"\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return self._embedding_function\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Examples:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-5", "text": "\"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Examples:\n            >>> ids = deeplake_vectorstore.add_texts(\n            ...     texts = <list_of_texts>,\n            ...     metadatas = <list_of_metadata_jsons>,\n            ...     ids = <list_of_ids>,\n            ... )\n        Args:\n            texts (Iterable[str]): Texts to add to the vectorstore.\n            metadatas (Optional[List[dict]], optional): Optional list of metadatas.\n            ids (Optional[List[str]], optional): Optional list of IDs.\n            embedding_function (Optional[Embeddings], optional): Embedding function\n                to use to convert the text into embeddings.\n            **kwargs (Any): Any additional keyword arguments passed is not supported\n                by this method.\n        Returns:\n            List[str]: List of IDs of the added texts.\n        \"\"\"\n        if kwargs:\n            unsupported_items = \"`, `\".join(set(kwargs.keys()))\n            raise TypeError(\n                f\"`{unsupported_items}` is/are not a valid argument to add_text method\"\n            )\n        kwargs = {}\n        if ids:\n            if self._id_tensor_name == \"ids\":  # for backwards compatibility\n                kwargs[\"ids\"] = ids\n            else:\n                kwargs[\"id\"] = ids\n        if metadatas is None:\n            metadatas = [{}] * len(list(texts))\n        if not isinstance(texts, list):\n            texts = list(texts)\n        if texts is None:\n            raise ValueError(\"`texts` parameter shouldn't be None.\")\n        elif len(texts) == 0:\n            raise ValueError(\"`texts` parameter shouldn't be empty.\")\n        return self.vectorstore.add(\n            text=texts,\n            metadata=metadatas,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-6", "text": "text=texts,\n            metadata=metadatas,\n            embedding_data=texts,\n            embedding_tensor=\"embedding\",\n            embedding_function=self._embedding_function.embed_documents,  # type: ignore\n            return_ids=True,\n            **kwargs,\n        )\n    def _search_tql(\n        self,\n        tql: Optional[str],\n        exec_option: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Function for performing tql_search.\n        Args:\n            tql (str): TQL Query string for direct evaluation.\n                Available only for `compute_engine` and `tensor_db`.\n            exec_option (str, optional): Supports 3 ways to search.\n                Could be \"python\", \"compute_engine\" or \"tensor_db\". Default is \"python\".\n                - ``python`` - Pure-python implementation for the client.\n                    WARNING: not recommended for big datasets due to potential memory\n                    issues.\n                - ``compute_engine`` - C++ implementation of Deep Lake Compute\n                    Engine for the client. Not for in-memory or local datasets.\n                - ``tensor_db`` - Hosted Managed Tensor Database for storage\n                    and query execution. Only for data in Deep Lake Managed Database.\n                        Use runtime = {\"db_engine\": True} during dataset creation.\n            return_score (bool): Return score with document. Default is False.\n        Returns:\n            Tuple[List[Document], List[Tuple[Document, float]]] - A tuple of two lists.\n                The first list contains Documents, and the second list contains\n                tuples of Document and float score.\n        Raises:\n            ValueError: If return_score is True but some condition is not met.\n        \"\"\"\n        result = self.vectorstore.search(\n            query=tql,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-7", "text": "\"\"\"\n        result = self.vectorstore.search(\n            query=tql,\n            exec_option=exec_option,\n        )\n        metadatas = result[\"metadata\"]\n        texts = result[\"text\"]\n        docs = [\n            Document(\n                page_content=text,\n                metadata=metadata,\n            )\n            for text, metadata in zip(texts, metadatas)\n        ]\n        if kwargs:\n            unsupported_argument = next(iter(kwargs))\n            if kwargs[unsupported_argument] is not False:\n                raise ValueError(\n                    f\"specifying {unsupported_argument} is \"\n                    \"not supported with tql search.\"\n                )\n        return docs\n    def _search(\n        self,\n        query: Optional[str] = None,\n        embedding: Optional[Union[List[float], np.ndarray]] = None,\n        embedding_function: Optional[Callable] = None,\n        k: int = 4,\n        distance_metric: Optional[str] = None,\n        use_maximal_marginal_relevance: bool = False,\n        fetch_k: Optional[int] = 20,\n        filter: Optional[Union[Dict, Callable]] = None,\n        return_score: bool = False,\n        exec_option: Optional[str] = None,\n        deep_memory: bool = False,\n        **kwargs: Any,\n    ) -> Any[List[Document], List[Tuple[Document, float]]]:\n        \"\"\"\n        Return docs similar to query.\n        Args:\n            query (str, optional): Text to look up similar docs.\n            embedding (Union[List[float], np.ndarray], optional): Query's embedding.\n            embedding_function (Callable, optional): Function to convert `query`\n                into embedding.\n            k (int): Number of Documents to return.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-8", "text": "into embedding.\n            k (int): Number of Documents to return.\n            distance_metric (Optional[str], optional): `L2` for Euclidean, `L1` for\n                Nuclear, `max` for L-infinity distance, `cos` for cosine similarity,\n                'dot' for dot product.\n            filter (Union[Dict, Callable], optional): Additional filter prior\n                to the embedding search.\n                - ``Dict`` - Key-value search on tensors of htype json, on an\n                    AND basis (a sample must satisfy all key-value filters to be True)\n                    Dict = {\"tensor_name_1\": {\"key\": value},\n                            \"tensor_name_2\": {\"key\": value}}\n                - ``Function`` - Any function compatible with `deeplake.filter`.\n            use_maximal_marginal_relevance (bool): Use maximal marginal relevance.\n            fetch_k (int): Number of Documents for MMR algorithm.\n            return_score (bool): Return the score.\n            exec_option (str, optional): Supports 3 ways to perform searching.\n                Could be \"python\", \"compute_engine\" or \"tensor_db\".\n                - ``python`` - Pure-python implementation for the client.\n                    WARNING: not recommended for big datasets.\n                - ``compute_engine`` - C++ implementation of Deep Lake Compute\n                    Engine for the client. Not for in-memory or local datasets.\n                - ``tensor_db`` - Hosted Managed Tensor Database for storage\n                    and query execution. Only for data in Deep Lake Managed Database.\n                    Use runtime = {\"db_engine\": True} during dataset creation.\n            deep_memory (bool): Whether to use the Deep Memory model for improving\n                search results. Defaults to False if deep_memory is not specified in\n                the Vector Store initialization. If True, the distance metric is set", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-9", "text": "the Vector Store initialization. If True, the distance metric is set\n                to \"deepmemory_distance\", which represents the metric with which the\n                model was trained. The search is performed using the Deep Memory model.\n                If False, the distance metric is set to \"COS\" or whatever distance\n                metric user specifies.\n            **kwargs: Additional keyword arguments.\n        Returns:\n            List of Documents by the specified distance metric,\n            if return_score True, return a tuple of (Document, score)\n        Raises:\n            ValueError: if both `embedding` and `embedding_function` are not specified.\n        \"\"\"\n        if kwargs.get(\"tql\"):\n            return self._search_tql(\n                tql=kwargs[\"tql\"],\n                exec_option=exec_option,\n                return_score=return_score,\n                embedding=embedding,\n                embedding_function=embedding_function,\n                distance_metric=distance_metric,\n                use_maximal_marginal_relevance=use_maximal_marginal_relevance,\n                filter=filter,\n            )\n        if embedding_function:\n            if isinstance(embedding_function, Embeddings):\n                _embedding_function = embedding_function.embed_query\n            else:\n                _embedding_function = embedding_function\n        elif self._embedding_function:\n            _embedding_function = self._embedding_function.embed_query\n        else:\n            _embedding_function = None\n        if embedding is None:\n            if _embedding_function is None:\n                raise ValueError(\n                    \"Either `embedding` or `embedding_function` needs to be\"\n                    \" specified.\"\n                )\n            embedding = _embedding_function(query) if query else None\n        if isinstance(embedding, list):\n            embedding = np.array(embedding, dtype=np.float32)\n            if len(embedding.shape) > 1:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-10", "text": "if len(embedding.shape) > 1:\n                embedding = embedding[0]\n        result = self.vectorstore.search(\n            embedding=embedding,\n            k=fetch_k if use_maximal_marginal_relevance else k,\n            distance_metric=distance_metric,\n            filter=filter,\n            exec_option=exec_option,\n            return_tensors=[\"embedding\", \"metadata\", \"text\", \"id\"],\n            deep_memory=deep_memory,\n        )\n        scores = result[\"score\"]\n        embeddings = result[\"embedding\"]\n        metadatas = result[\"metadata\"]\n        texts = result[\"text\"]\n        if use_maximal_marginal_relevance:\n            lambda_mult = kwargs.get(\"lambda_mult\", 0.5)\n            indices = maximal_marginal_relevance(  # type: ignore\n                embedding,  # type: ignore\n                embeddings,\n                k=min(k, len(texts)),\n                lambda_mult=lambda_mult,\n            )\n            scores = [scores[i] for i in indices]\n            texts = [texts[i] for i in indices]\n            metadatas = [metadatas[i] for i in indices]\n        docs = [\n            Document(\n                page_content=text,\n                metadata=metadata,\n            )\n            for text, metadata in zip(texts, metadatas)\n        ]\n        if return_score:\n            return [(doc, score) for doc, score in zip(docs, scores)]\n        return docs\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"\n        Return docs most similar to query.\n        Examples:\n            >>> # Search using an embedding", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-11", "text": "Examples:\n            >>> # Search using an embedding\n            >>> data = vector_store.similarity_search(\n            ...     query=<your_query>,\n            ...     k=<num_items>,\n            ...     exec_option=<preferred_exec_option>,\n            ... )\n            >>> # Run tql search:\n            >>> data = vector_store.similarity_search(\n            ...     query=None,\n            ...     tql=\"SELECT * WHERE id == <id>\",\n            ...     exec_option=\"compute_engine\",\n            ... )\n        Args:\n            k (int): Number of Documents to return. Defaults to 4.\n            query (str): Text to look up similar documents.\n            **kwargs: Additional keyword arguments include:\n                embedding (Callable): Embedding function to use. Defaults to None.\n                distance_metric (str): 'L2' for Euclidean, 'L1' for Nuclear, 'max'\n                    for L-infinity, 'cos' for cosine, 'dot' for dot product.\n                    Defaults to 'L2'.\n                filter (Union[Dict, Callable], optional): Additional filter\n                    before embedding search.\n                    - Dict: Key-value search on tensors of htype json,\n                        (sample must satisfy all key-value filters)\n                        Dict = {\"tensor_1\": {\"key\": value}, \"tensor_2\": {\"key\": value}}\n                    - Function: Compatible with `deeplake.filter`.\n                    Defaults to None.\n                exec_option (str): Supports 3 ways to perform searching.\n                    'python', 'compute_engine', or 'tensor_db'. Defaults to 'python'.\n                    - 'python': Pure-python implementation for the client.\n                        WARNING: not recommended for big datasets.\n                    - 'compute_engine': C++ implementation of the Compute Engine for\n                        the client. Not for in-memory or local datasets.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-12", "text": "the client. Not for in-memory or local datasets.\n                    - 'tensor_db': Managed Tensor Database for storage and query.\n                        Only for data in Deep Lake Managed Database.\n                        Use `runtime = {\"db_engine\": True}` during dataset creation.\n                deep_memory (bool): Whether to use the Deep Memory model for improving\n                    search results. Defaults to False if deep_memory is not specified\n                    in the Vector Store initialization. If True, the distance metric\n                    is set to \"deepmemory_distance\", which represents the metric with\n                    which the model was trained. The search is performed using the Deep\n                    Memory model. If False, the distance metric is set to \"COS\" or\n                    whatever distance metric user specifies.\n        Returns:\n            List[Document]: List of Documents most similar to the query vector.\n        \"\"\"\n        return self._search(\n            query=query,\n            k=k,\n            use_maximal_marginal_relevance=False,\n            return_score=False,\n            **kwargs,\n        )\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: Union[List[float], np.ndarray],\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"\n        Return docs most similar to embedding vector.\n        Examples:\n            >>> # Search using an embedding\n            >>> data = vector_store.similarity_search_by_vector(\n            ...    embedding=<your_embedding>,\n            ...    k=<num_items_to_return>,\n            ...    exec_option=<preferred_exec_option>,\n            ... )\n        Args:\n            embedding (Union[List[float], np.ndarray]):\n                Embedding to find similar docs.\n            k (int): Number of Documents to return. Defaults to 4.\n            **kwargs: Additional keyword arguments including:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-13", "text": "**kwargs: Additional keyword arguments including:\n                filter (Union[Dict, Callable], optional):\n                    Additional filter before embedding search.\n                    - ``Dict`` - Key-value search on tensors of htype json. True\n                        if all key-value filters are satisfied.\n                        Dict = {\"tensor_name_1\": {\"key\": value},\n                                \"tensor_name_2\": {\"key\": value}}\n                    - ``Function`` - Any function compatible with\n                        `deeplake.filter`.\n                    Defaults to None.\n                exec_option (str): Options for search execution include\n                    \"python\", \"compute_engine\", or \"tensor_db\". Defaults to\n                    \"python\".\n                    - \"python\" - Pure-python implementation running on the client.\n                        Can be used for data stored anywhere. WARNING: using this\n                        option with big datasets is discouraged due to potential\n                        memory issues.\n                    - \"compute_engine\" - Performant C++ implementation of the Deep\n                        Lake Compute Engine. Runs on the client and can be used for\n                        any data stored in or connected to Deep Lake. It cannot be\n                        used with in-memory or local datasets.\n                    - \"tensor_db\" - Performant, fully-hosted Managed Tensor Database.\n                        Responsible for storage and query execution. Only available\n                        for data stored in the Deep Lake Managed Database.\n                        To store datasets in this database, specify\n                        `runtime = {\"db_engine\": True}` during dataset creation.\n                distance_metric (str): `L2` for Euclidean, `L1` for Nuclear,\n                    `max` for L-infinity distance, `cos` for cosine similarity,\n                    'dot' for dot product. Defaults to `L2`.\n                deep_memory (bool): Whether to use the Deep Memory model for improving\n                    search results. Defaults to False if deep_memory is not specified", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-14", "text": "search results. Defaults to False if deep_memory is not specified\n                    in the Vector Store initialization. If True, the distance metric\n                    is set to \"deepmemory_distance\", which represents the metric with\n                    which the model was trained. The search is performed using the Deep\n                    Memory model. If False, the distance metric is set to \"COS\" or\n                    whatever distance metric user specifies.\n        Returns:\n            List[Document]: List of Documents most similar to the query vector.\n        \"\"\"\n        return self._search(\n            embedding=embedding,\n            k=k,\n            use_maximal_marginal_relevance=False,\n            return_score=False,\n            **kwargs,\n        )\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Run similarity search with Deep Lake with distance returned.\n        Examples:\n        >>> data = vector_store.similarity_search_with_score(\n        ...     query=<your_query>,\n        ...     embedding=<your_embedding_function>\n        ...     k=<number_of_items_to_return>,\n        ...     exec_option=<preferred_exec_option>,\n        ... )\n        Args:\n            query (str): Query text to search for.\n            k (int): Number of results to return. Defaults to 4.\n            **kwargs: Additional keyword arguments. Some of these arguments are:\n                distance_metric: `L2` for Euclidean, `L1` for Nuclear, `max` L-infinity\n                    distance, `cos` for cosine similarity, 'dot' for dot product.\n                    Defaults to `L2`.\n                filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-15", "text": "filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n                    embedding_function (Callable): Embedding function to use. Defaults\n                    to None.\n                exec_option (str): DeepLakeVectorStore supports 3 ways to perform\n                    searching. It could be either \"python\", \"compute_engine\" or\n                    \"tensor_db\". Defaults to \"python\".\n                    - \"python\" - Pure-python implementation running on the client.\n                        Can be used for data stored anywhere. WARNING: using this\n                        option with big datasets is discouraged due to potential\n                        memory issues.\n                    - \"compute_engine\" - Performant C++ implementation of the Deep\n                        Lake Compute Engine. Runs on the client and can be used for\n                        any data stored in or connected to Deep Lake. It cannot be used\n                        with in-memory or local datasets.\n                    - \"tensor_db\" - Performant, fully-hosted Managed Tensor Database.\n                        Responsible for storage and query execution. Only available for\n                        data stored in the Deep Lake Managed Database. To store datasets\n                        in this database, specify `runtime = {\"db_engine\": True}`\n                        during dataset creation.\n                deep_memory (bool): Whether to use the Deep Memory model for improving\n                    search results. Defaults to False if deep_memory is not specified\n                    in the Vector Store initialization. If True, the distance metric\n                    is set to \"deepmemory_distance\", which represents the metric with\n                    which the model was trained. The search is performed using the Deep\n                    Memory model. If False, the distance metric is set to \"COS\" or\n                    whatever distance metric user specifies.\n        Returns:\n            List[Tuple[Document, float]]: List of documents most similar to the query\n                text with distance in float.\"\"\"\n        return self._search(\n            query=query,\n            k=k,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-16", "text": "return self._search(\n            query=query,\n            k=k,\n            return_score=True,\n            **kwargs,\n        )\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        exec_option: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"\n        Return docs selected using the maximal marginal relevance. Maximal marginal\n        relevance optimizes for similarity to query AND diversity among selected docs.\n        Examples:\n        >>> data = vector_store.max_marginal_relevance_search_by_vector(\n        ...        embedding=<your_embedding>,\n        ...        fetch_k=<elements_to_fetch_before_mmr_search>,\n        ...        k=<number_of_items_to_return>,\n        ...        exec_option=<preferred_exec_option>,\n        ... )\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch for MMR algorithm.\n            lambda_mult: Number between 0 and 1 determining the degree of diversity.\n                0 corresponds to max diversity and 1 to min diversity. Defaults to 0.5.\n            exec_option (str): DeepLakeVectorStore supports 3 ways for searching.\n                Could be \"python\", \"compute_engine\" or \"tensor_db\". Defaults to\n                \"python\".\n                - \"python\" - Pure-python implementation running on the client.\n                    Can be used for data stored anywhere. WARNING: using this\n                    option with big datasets is discouraged due to potential\n                    memory issues.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-17", "text": "option with big datasets is discouraged due to potential\n                    memory issues.\n                - \"compute_engine\" - Performant C++ implementation of the Deep\n                    Lake Compute Engine. Runs on the client and can be used for\n                    any data stored in or connected to Deep Lake. It cannot be used\n                    with in-memory or local datasets.\n                - \"tensor_db\" - Performant, fully-hosted Managed Tensor Database.\n                    Responsible for storage and query execution. Only available for\n                    data stored in the Deep Lake Managed Database. To store datasets\n                    in this database, specify `runtime = {\"db_engine\": True}`\n                    during dataset creation.\n            deep_memory (bool): Whether to use the Deep Memory model for improving\n                search results. Defaults to False if deep_memory is not specified\n                in the Vector Store initialization. If True, the distance metric\n                is set to \"deepmemory_distance\", which represents the metric with\n                which the model was trained. The search is performed using the Deep\n                Memory model. If False, the distance metric is set to \"COS\" or\n                whatever distance metric user specifies.\n            **kwargs: Additional keyword arguments.\n        Returns:\n            List[Documents] - A list of documents.\n        \"\"\"\n        return self._search(\n            embedding=embedding,\n            k=k,\n            fetch_k=fetch_k,\n            use_maximal_marginal_relevance=True,\n            lambda_mult=lambda_mult,\n            exec_option=exec_option,\n            **kwargs,\n        )\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        exec_option: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-18", "text": "exec_option: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Examples:\n        >>> # Search using an embedding\n        >>> data = vector_store.max_marginal_relevance_search(\n        ...        query = <query_to_search>,\n        ...        embedding_function = <embedding_function_for_query>,\n        ...        k = <number_of_items_to_return>,\n        ...        exec_option = <preferred_exec_option>,\n        ... )\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents for MMR algorithm.\n            lambda_mult: Value between 0 and 1. 0 corresponds\n                        to maximum diversity and 1 to minimum.\n                        Defaults to 0.5.\n            exec_option (str): Supports 3 ways to perform searching.\n                - \"python\" - Pure-python implementation running on the client.\n                        Can be used for data stored anywhere. WARNING: using this\n                        option with big datasets is discouraged due to potential\n                        memory issues.\n                    - \"compute_engine\" - Performant C++ implementation of the Deep\n                        Lake Compute Engine. Runs on the client and can be used for\n                        any data stored in or connected to Deep Lake. It cannot be\n                        used with in-memory or local datasets.\n                    - \"tensor_db\" - Performant, fully-hosted Managed Tensor Database.\n                        Responsible for storage and query execution. Only available\n                        for data stored in the Deep Lake Managed Database. To store\n                        datasets in this database, specify\n                        `runtime = {\"db_engine\": True}` during dataset creation.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-19", "text": "`runtime = {\"db_engine\": True}` during dataset creation.\n            deep_memory (bool): Whether to use the Deep Memory model for improving\n                search results. Defaults to False if deep_memory is not specified\n                in the Vector Store initialization. If True, the distance metric\n                is set to \"deepmemory_distance\", which represents the metric with\n                which the model was trained. The search is performed using the Deep\n                Memory model. If False, the distance metric is set to \"COS\" or\n                whatever distance metric user specifies.\n            **kwargs: Additional keyword arguments\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        Raises:\n            ValueError: when MRR search is on but embedding function is\n                not specified.\n        \"\"\"\n        embedding_function = kwargs.get(\"embedding\") or self._embedding_function\n        if embedding_function is None:\n            raise ValueError(\n                \"For MMR search, you must specify an embedding function on\"\n                \" `creation` or during add call.\"\n            )\n        return self._search(\n            query=query,\n            k=k,\n            fetch_k=fetch_k,\n            use_maximal_marginal_relevance=True,\n            lambda_mult=lambda_mult,\n            exec_option=exec_option,\n            embedding_function=embedding_function,  # type: ignore\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Optional[Embeddings] = None,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH,\n        **kwargs: Any,\n    ) -> DeepLake:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-20", "text": "**kwargs: Any,\n    ) -> DeepLake:\n        \"\"\"Create a Deep Lake dataset from a raw documents.\n        If a dataset_path is specified, the dataset will be persisted in that location,\n        otherwise by default at `./deeplake`\n        Examples:\n        >>> # Search using an embedding\n        >>> vector_store = DeepLake.from_texts(\n        ...        texts = <the_texts_that_you_want_to_embed>,\n        ...        embedding_function = <embedding_function_for_query>,\n        ...        k = <number_of_items_to_return>,\n        ...        exec_option = <preferred_exec_option>,\n        ... )\n        Args:\n            dataset_path (str): - The full path to the dataset. Can be:\n                - Deep Lake cloud path of the form ``hub://username/dataset_name``.\n                    To write to Deep Lake cloud datasets,\n                    ensure that you are logged in to Deep Lake\n                    (use 'activeloop login' from command line)\n                - AWS S3 path of the form ``s3://bucketname/path/to/dataset``.\n                    Credentials are required in either the environment\n                - Google Cloud Storage path of the form\n                    ``gcs://bucketname/path/to/dataset`` Credentials are required\n                    in either the environment\n                - Local file system path of the form ``./path/to/dataset`` or\n                    ``~/path/to/dataset`` or ``path/to/dataset``.\n                - In-memory path of the form ``mem://path/to/dataset`` which doesn't\n                    save the dataset, but keeps it in memory instead.\n                    Should be used only for testing as it does not persist.\n            texts (List[Document]): List of documents to add.\n            embedding (Optional[Embeddings]): Embedding function. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-21", "text": "embedding (Optional[Embeddings]): Embedding function. Defaults to None.\n                Note, in other places, it is called embedding_function.\n            metadatas (Optional[List[dict]]): List of metadatas. Defaults to None.\n            ids (Optional[List[str]]): List of document IDs. Defaults to None.\n            **kwargs: Additional keyword arguments.\n        Returns:\n            DeepLake: Deep Lake dataset.\n        \"\"\"\n        deeplake_dataset = cls(dataset_path=dataset_path, embedding=embedding, **kwargs)\n        deeplake_dataset.add_texts(\n            texts=texts,\n            metadatas=metadatas,\n            ids=ids,\n        )\n        return deeplake_dataset\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> bool:\n        \"\"\"Delete the entities in the dataset.\n        Args:\n            ids (Optional[List[str]], optional): The document_ids to delete.\n                Defaults to None.\n            **kwargs: Other keyword arguments that subclasses might use.\n                - filter (Optional[Dict[str, str]], optional): The filter to delete by.\n                - delete_all (Optional[bool], optional): Whether to drop the dataset.\n        Returns:\n            bool: Whether the delete operation was successful.\n        \"\"\"\n        filter = kwargs.get(\"filter\")\n        delete_all = kwargs.get(\"delete_all\")\n        self.vectorstore.delete(ids=ids, filter=filter, delete_all=delete_all)\n        return True\n[docs]    @classmethod\n    def force_delete_by_path(cls, path: str) -> None:\n        \"\"\"Force delete dataset by path.\n        Args:\n            path (str): path of the dataset to delete.\n        Raises:\n            ValueError: if deeplake is not installed.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "4fcb959a9089-22", "text": "Raises:\n            ValueError: if deeplake is not installed.\n        \"\"\"\n        try:\n            import deeplake\n        except ImportError:\n            raise ValueError(\n                \"Could not import deeplake python package. \"\n                \"Please install it with `pip install deeplake`.\"\n            )\n        deeplake.delete(path, large_ok=True, force=True)\n[docs]    def delete_dataset(self) -> None:\n        \"\"\"Delete the collection.\"\"\"\n        self.delete(delete_all=True)\n[docs]    def ds(self) -> Any:\n        logger.warning(\n            \"this method is deprecated and will be removed, \"\n            \"better to use `db.vectorstore.dataset` instead.\"\n        )\n        return self.vectorstore.dataset", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html"}
{"id": "3eede363533c-0", "text": "Source code for langchain.vectorstores.pinecone\nfrom __future__ import annotations\nimport logging\nimport uuid\nimport warnings\nfrom typing import TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Tuple, Union\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils.iter import batch_iterate\nfrom langchain.vectorstores.utils import DistanceStrategy, maximal_marginal_relevance\nif TYPE_CHECKING:\n    from pinecone import Index\nlogger = logging.getLogger(__name__)\n[docs]class Pinecone(VectorStore):\n    \"\"\"`Pinecone` vector store.\n    To use, you should have the ``pinecone-client`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import Pinecone\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            import pinecone\n            # The environment should be the one specified next to the API key\n            # in your Pinecone console\n            pinecone.init(api_key=\"***\", environment=\"...\")\n            index = pinecone.Index(\"langchain-demo\")\n            embeddings = OpenAIEmbeddings()\n            vectorstore = Pinecone(index, embeddings.embed_query, \"text\")\n    \"\"\"\n[docs]    def __init__(\n        self,\n        index: Any,\n        embedding: Union[Embeddings, Callable],\n        text_key: str,\n        namespace: Optional[str] = None,\n        distance_strategy: Optional[DistanceStrategy] = DistanceStrategy.COSINE,\n    ):\n        \"\"\"Initialize with Pinecone client.\"\"\"\n        try:\n            import pinecone\n        except ImportError:\n            raise ImportError(\n                \"Could not import pinecone python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html"}
{"id": "3eede363533c-1", "text": "raise ImportError(\n                \"Could not import pinecone python package. \"\n                \"Please install it with `pip install pinecone-client`.\"\n            )\n        if not isinstance(embedding, Embeddings):\n            warnings.warn(\n                \"Passing in `embedding` as a Callable is deprecated. Please pass in an\"\n                \" Embeddings object instead.\"\n            )\n        if not isinstance(index, pinecone.index.Index):\n            raise ValueError(\n                f\"client should be an instance of pinecone.index.Index, \"\n                f\"got {type(index)}\"\n            )\n        self._index = index\n        self._embedding = embedding\n        self._text_key = text_key\n        self._namespace = namespace\n        self.distance_strategy = distance_strategy\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        \"\"\"Access the query embedding object if available.\"\"\"\n        if isinstance(self._embedding, Embeddings):\n            return self._embedding\n        return None\n    def _embed_documents(self, texts: Iterable[str]) -> List[List[float]]:\n        \"\"\"Embed search docs.\"\"\"\n        if isinstance(self._embedding, Embeddings):\n            return self._embedding.embed_documents(list(texts))\n        return [self._embedding(t) for t in texts]\n    def _embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed query text.\"\"\"\n        if isinstance(self._embedding, Embeddings):\n            return self._embedding.embed_query(text)\n        return self._embedding(text)\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        namespace: Optional[str] = None,\n        batch_size: int = 32,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html"}
{"id": "3eede363533c-2", "text": "namespace: Optional[str] = None,\n        batch_size: int = 32,\n        embedding_chunk_size: int = 1000,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Upsert optimization is done by chunking the embeddings and upserting them.\n        This is done to avoid memory issues and optimize using HTTP based embeddings.\n        For OpenAI embeddings, use pool_threads>4 when constructing the pinecone.Index,\n        embedding_chunk_size>1000 and batch_size~64 for best performance.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of ids to associate with the texts.\n            namespace: Optional pinecone namespace to add the texts to.\n            batch_size: Batch size to use when adding the texts to the vectorstore.\n            embedding_chunk_size: Chunk size to use when embedding the texts.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        if namespace is None:\n            namespace = self._namespace\n        texts = list(texts)\n        ids = ids or [str(uuid.uuid4()) for _ in texts]\n        metadatas = metadatas or [{} for _ in texts]\n        for metadata, text in zip(metadatas, texts):\n            metadata[self._text_key] = text\n        # For loops to avoid memory issues and optimize when using HTTP based embeddings\n        # The first loop runs the embeddings, it benefits when using OpenAI embeddings\n        # The second loops runs the pinecone upsert asynchronously.\n        for i in range(0, len(texts), embedding_chunk_size):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html"}
{"id": "3eede363533c-3", "text": "for i in range(0, len(texts), embedding_chunk_size):\n            chunk_texts = texts[i : i + embedding_chunk_size]\n            chunk_ids = ids[i : i + embedding_chunk_size]\n            chunk_metadatas = metadatas[i : i + embedding_chunk_size]\n            embeddings = self._embed_documents(chunk_texts)\n            async_res = [\n                self._index.upsert(\n                    vectors=batch,\n                    namespace=namespace,\n                    async_req=True,\n                    **kwargs,\n                )\n                for batch in batch_iterate(\n                    batch_size, zip(chunk_ids, embeddings, chunk_metadatas)\n                )\n            ]\n            [res.get() for res in async_res]\n        return ids\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[dict] = None,\n        namespace: Optional[str] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return pinecone documents most similar to query, along with scores.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Dictionary of argument(s) to filter on metadata\n            namespace: Namespace to search in. Default will search in '' namespace.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        return self.similarity_search_by_vector_with_score(\n            self._embed_query(query), k=k, filter=filter, namespace=namespace\n        )\n[docs]    def similarity_search_by_vector_with_score(\n        self,\n        embedding: List[float],\n        *,\n        k: int = 4,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html"}
{"id": "3eede363533c-4", "text": "embedding: List[float],\n        *,\n        k: int = 4,\n        filter: Optional[dict] = None,\n        namespace: Optional[str] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return pinecone documents most similar to embedding, along with scores.\"\"\"\n        if namespace is None:\n            namespace = self._namespace\n        docs = []\n        results = self._index.query(\n            [embedding],\n            top_k=k,\n            include_metadata=True,\n            namespace=namespace,\n            filter=filter,\n        )\n        for res in results[\"matches\"]:\n            metadata = res[\"metadata\"]\n            if self._text_key in metadata:\n                text = metadata.pop(self._text_key)\n                score = res[\"score\"]\n                docs.append((Document(page_content=text, metadata=metadata), score))\n            else:\n                logger.warning(\n                    f\"Found document with no `{self._text_key}` key. Skipping.\"\n                )\n        return docs\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[dict] = None,\n        namespace: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return pinecone documents most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Dictionary of argument(s) to filter on metadata\n            namespace: Namespace to search in. Default will search in '' namespace.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html"}
{"id": "3eede363533c-5", "text": "\"\"\"\n        docs_and_scores = self.similarity_search_with_score(\n            query, k=k, filter=filter, namespace=namespace, **kwargs\n        )\n        return [doc for doc, _ in docs_and_scores]\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        \"\"\"\n        The 'correct' relevance function\n        may differ depending on a few things, including:\n        - the distance / similarity metric used by the VectorStore\n        - the scale of your embeddings (OpenAI's are unit normed. Many others are not!)\n        - embedding dimensionality\n        - etc.\n        \"\"\"\n        if self.distance_strategy == DistanceStrategy.COSINE:\n            return self._cosine_relevance_score_fn\n        elif self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:\n            return self._max_inner_product_relevance_score_fn\n        elif self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE:\n            return self._euclidean_relevance_score_fn\n        else:\n            raise ValueError(\n                \"Unknown distance strategy, must be cosine, max_inner_product \"\n                \"(dot product), or euclidean\"\n            )\n    @staticmethod\n    def _cosine_relevance_score_fn(score: float) -> float:\n        \"\"\"Pinecone returns cosine similarity scores between [-1,1]\"\"\"\n        return (score + 1) / 2\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[dict] = None,\n        namespace: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html"}
{"id": "3eede363533c-6", "text": "**kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        if namespace is None:\n            namespace = self._namespace\n        results = self._index.query(\n            [embedding],\n            top_k=fetch_k,\n            include_values=True,\n            include_metadata=True,\n            namespace=namespace,\n            filter=filter,\n        )\n        mmr_selected = maximal_marginal_relevance(\n            np.array([embedding], dtype=np.float32),\n            [item[\"values\"] for item in results[\"matches\"]],\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        selected = [results[\"matches\"][i][\"metadata\"] for i in mmr_selected]\n        return [\n            Document(page_content=metadata.pop((self._text_key)), metadata=metadata)\n            for metadata in selected\n        ]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[dict] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html"}
{"id": "3eede363533c-7", "text": "filter: Optional[dict] = None,\n        namespace: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        embedding = self._embed_query(query)\n        return self.max_marginal_relevance_search_by_vector(\n            embedding, k, fetch_k, lambda_mult, filter, namespace\n        )\n[docs]    @classmethod\n    def get_pinecone_index(\n        cls,\n        index_name: Optional[str],\n        pool_threads: int = 4,\n    ) -> Index:\n        \"\"\"Return a Pinecone Index instance.\n        Args:\n            index_name: Name of the index to use.\n            pool_threads: Number of threads to use for index upsert.\n        Returns:\n            Pinecone Index instance.\"\"\"\n        try:\n            import pinecone\n        except ImportError:\n            raise ValueError(\n                \"Could not import pinecone python package. \"\n                \"Please install it with `pip install pinecone-client`.\"\n            )\n        indexes = pinecone.list_indexes()  # checks if provided index exists\n        if index_name in indexes:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html"}
{"id": "3eede363533c-8", "text": "if index_name in indexes:\n            index = pinecone.Index(index_name, pool_threads=pool_threads)\n        elif len(indexes) == 0:\n            raise ValueError(\n                \"No active indexes found in your Pinecone project, \"\n                \"are you sure you're using the right Pinecone API key and Environment? \"\n                \"Please double check your Pinecone dashboard.\"\n            )\n        else:\n            raise ValueError(\n                f\"Index '{index_name}' not found in your Pinecone project. \"\n                f\"Did you mean one of the following indexes: {', '.join(indexes)}\"\n            )\n        return index\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        batch_size: int = 32,\n        text_key: str = \"text\",\n        namespace: Optional[str] = None,\n        index_name: Optional[str] = None,\n        upsert_kwargs: Optional[dict] = None,\n        pool_threads: int = 4,\n        embeddings_chunk_size: int = 1000,\n        **kwargs: Any,\n    ) -> Pinecone:\n        \"\"\"Construct Pinecone wrapper from raw documents.\n        This is a user friendly interface that:\n            1. Embeds documents.\n            2. Adds the documents to a provided Pinecone index\n        This is intended to be a quick way to get started.\n        The `pool_threads` affects the speed of the upsert operations.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import Pinecone\n                from langchain.embeddings import OpenAIEmbeddings\n                import pinecone", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html"}
{"id": "3eede363533c-9", "text": "from langchain.embeddings import OpenAIEmbeddings\n                import pinecone\n                # The environment should be the one specified next to the API key\n                # in your Pinecone console\n                pinecone.init(api_key=\"***\", environment=\"...\")\n                embeddings = OpenAIEmbeddings()\n                pinecone = Pinecone.from_texts(\n                    texts,\n                    embeddings,\n                    index_name=\"langchain-demo\"\n                )\n        \"\"\"\n        pinecone_index = cls.get_pinecone_index(index_name, pool_threads)\n        pinecone = cls(pinecone_index, embedding, text_key, namespace, **kwargs)\n        pinecone.add_texts(\n            texts,\n            metadatas=metadatas,\n            ids=ids,\n            namespace=namespace,\n            batch_size=batch_size,\n            embedding_chunk_size=embeddings_chunk_size,\n            **(upsert_kwargs or {}),\n        )\n        return pinecone\n[docs]    @classmethod\n    def from_existing_index(\n        cls,\n        index_name: str,\n        embedding: Embeddings,\n        text_key: str = \"text\",\n        namespace: Optional[str] = None,\n        pool_threads: int = 4,\n    ) -> Pinecone:\n        \"\"\"Load pinecone vectorstore from index name.\"\"\"\n        pinecone_index = cls.get_pinecone_index(index_name, pool_threads)\n        return cls(pinecone_index, embedding, text_key, namespace)\n[docs]    def delete(\n        self,\n        ids: Optional[List[str]] = None,\n        delete_all: Optional[bool] = None,\n        namespace: Optional[str] = None,\n        filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Delete by vector IDs or filter.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html"}
{"id": "3eede363533c-10", "text": ") -> None:\n        \"\"\"Delete by vector IDs or filter.\n        Args:\n            ids: List of ids to delete.\n            filter: Dictionary of conditions to filter vectors to delete.\n        \"\"\"\n        if namespace is None:\n            namespace = self._namespace\n        if delete_all:\n            self._index.delete(delete_all=True, namespace=namespace, **kwargs)\n        elif ids is not None:\n            chunk_size = 1000\n            for i in range(0, len(ids), chunk_size):\n                chunk = ids[i : i + chunk_size]\n                self._index.delete(ids=chunk, namespace=namespace, **kwargs)\n        elif filter is not None:\n            self._index.delete(filter=filter, namespace=namespace, **kwargs)\n        else:\n            raise ValueError(\"Either ids, delete_all, or filter must be provided.\")\n        return None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html"}
{"id": "da09e904578a-0", "text": "Source code for langchain.vectorstores.rocksetdb\nfrom __future__ import annotations\nimport logging\nfrom enum import Enum\nfrom typing import Any, Iterable, List, Optional, Tuple\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nlogger = logging.getLogger(__name__)\n[docs]class Rockset(VectorStore):\n    \"\"\"`Rockset` vector store.\n    To use, you should have the `rockset` python package installed. Note that to use\n    this, the collection being used must already exist in your Rockset instance.\n    You must also ensure you use a Rockset ingest transformation to apply\n    `VECTOR_ENFORCE` on the column being used to store `embedding_key` in the\n    collection.\n    See: https://rockset.com/blog/introducing-vector-search-on-rockset/ for more details\n    Everything below assumes `commons` Rockset workspace.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import Rockset\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            import rockset\n            # Make sure you use the right host (region) for your Rockset instance\n            # and APIKEY has both read-write access to your collection.\n            rs = rockset.RocksetClient(host=rockset.Regions.use1a1, api_key=\"***\")\n            collection_name = \"langchain_demo\"\n            embeddings = OpenAIEmbeddings()\n            vectorstore = Rockset(rs, collection_name, embeddings,\n                \"description\", \"description_embedding\")\n    \"\"\"\n[docs]    def __init__(\n        self,\n        client: Any,\n        embeddings: Embeddings,\n        collection_name: str,\n        text_key: str,\n        embedding_key: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html"}
{"id": "da09e904578a-1", "text": "text_key: str,\n        embedding_key: str,\n        workspace: str = \"commons\",\n    ):\n        \"\"\"Initialize with Rockset client.\n        Args:\n            client: Rockset client object\n            collection: Rockset collection to insert docs / query\n            embeddings: Langchain Embeddings object to use to generate\n                        embedding for given text.\n            text_key: column in Rockset collection to use to store the text\n            embedding_key: column in Rockset collection to use to store the embedding.\n                           Note: We must apply `VECTOR_ENFORCE()` on this column via\n                           Rockset ingest transformation.\n        \"\"\"\n        try:\n            from rockset import RocksetClient\n        except ImportError:\n            raise ImportError(\n                \"Could not import rockset client python package. \"\n                \"Please install it with `pip install rockset`.\"\n            )\n        if not isinstance(client, RocksetClient):\n            raise ValueError(\n                f\"client should be an instance of rockset.RocksetClient, \"\n                f\"got {type(client)}\"\n            )\n        # TODO: check that `collection_name` exists in rockset. Create if not.\n        self._client = client\n        self._collection_name = collection_name\n        self._embeddings = embeddings\n        self._text_key = text_key\n        self._embedding_key = embedding_key\n        self._workspace = workspace\n        try:\n            self._client.set_application(\"langchain\")\n        except AttributeError:\n            # ignore\n            pass\n    @property\n    def embeddings(self) -> Embeddings:\n        return self._embeddings\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html"}
{"id": "da09e904578a-2", "text": "ids: Optional[List[str]] = None,\n        batch_size: int = 32,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore\n                Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of ids to associate with the texts.\n            batch_size: Send documents in batches to rockset.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        batch: list[dict] = []\n        stored_ids = []\n        for i, text in enumerate(texts):\n            if len(batch) == batch_size:\n                stored_ids += self._write_documents_to_rockset(batch)\n                batch = []\n            doc = {}\n            if metadatas and len(metadatas) > i:\n                doc = metadatas[i]\n            if ids and len(ids) > i:\n                doc[\"_id\"] = ids[i]\n            doc[self._text_key] = text\n            doc[self._embedding_key] = self._embeddings.embed_query(text)\n            batch.append(doc)\n        if len(batch) > 0:\n            stored_ids += self._write_documents_to_rockset(batch)\n            batch = []\n        return stored_ids\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        client: Any = None,\n        collection_name: str = \"\",\n        text_key: str = \"\",\n        embedding_key: str = \"\",\n        ids: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html"}
{"id": "da09e904578a-3", "text": "embedding_key: str = \"\",\n        ids: Optional[List[str]] = None,\n        batch_size: int = 32,\n        **kwargs: Any,\n    ) -> Rockset:\n        \"\"\"Create Rockset wrapper with existing texts.\n        This is intended as a quicker way to get started.\n        \"\"\"\n        # Sanitize inputs\n        assert client is not None, \"Rockset Client cannot be None\"\n        assert collection_name, \"Collection name cannot be empty\"\n        assert text_key, \"Text key name cannot be empty\"\n        assert embedding_key, \"Embedding key cannot be empty\"\n        rockset = cls(client, embedding, collection_name, text_key, embedding_key)\n        rockset.add_texts(texts, metadatas, ids, batch_size)\n        return rockset\n    # Rockset supports these vector distance functions.\n    class DistanceFunction(Enum):\n        COSINE_SIM = \"COSINE_SIM\"\n        EUCLIDEAN_DIST = \"EUCLIDEAN_DIST\"\n        DOT_PRODUCT = \"DOT_PRODUCT\"\n        # how to sort results for \"similarity\"\n        def order_by(self) -> str:\n            if self.value == \"EUCLIDEAN_DIST\":\n                return \"ASC\"\n            return \"DESC\"\n[docs]    def similarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        distance_func: DistanceFunction = DistanceFunction.COSINE_SIM,\n        where_str: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Perform a similarity search with Rockset\n        Args:\n            query (str): Text to look up documents similar to.\n            distance_func (DistanceFunction): how to compute distance between two", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html"}
{"id": "da09e904578a-4", "text": "distance_func (DistanceFunction): how to compute distance between two\n                vectors in Rockset.\n            k (int, optional): Top K neighbors to retrieve. Defaults to 4.\n            where_str (Optional[str], optional): Metadata filters supplied as a\n                SQL `where` condition string. Defaults to None.\n                eg. \"price<=70.0 AND brand='Nintendo'\"\n            NOTE: Please do not let end-user to fill this and always be aware\n                  of SQL injection.\n        Returns:\n            List[Tuple[Document, float]]: List of documents with their relevance score\n        \"\"\"\n        return self.similarity_search_by_vector_with_relevance_scores(\n            self._embeddings.embed_query(query),\n            k,\n            distance_func,\n            where_str,\n            **kwargs,\n        )\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        distance_func: DistanceFunction = DistanceFunction.COSINE_SIM,\n        where_str: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Same as `similarity_search_with_relevance_scores` but\n        doesn't return the scores.\n        \"\"\"\n        return self.similarity_search_by_vector(\n            self._embeddings.embed_query(query),\n            k,\n            distance_func,\n            where_str,\n            **kwargs,\n        )\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        distance_func: DistanceFunction = DistanceFunction.COSINE_SIM,\n        where_str: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html"}
{"id": "da09e904578a-5", "text": "**kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Accepts a query_embedding (vector), and returns documents with\n        similar embeddings.\"\"\"\n        docs_and_scores = self.similarity_search_by_vector_with_relevance_scores(\n            embedding, k, distance_func, where_str, **kwargs\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search_by_vector_with_relevance_scores(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        distance_func: DistanceFunction = DistanceFunction.COSINE_SIM,\n        where_str: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Accepts a query_embedding (vector), and returns documents with\n        similar embeddings along with their relevance scores.\"\"\"\n        q_str = self._build_query_sql(embedding, distance_func, k, where_str)\n        try:\n            query_response = self._client.Queries.query(sql={\"query\": q_str})\n        except Exception as e:\n            logger.error(\"Exception when querying Rockset: %s\\n\", e)\n            return []\n        finalResult: list[Tuple[Document, float]] = []\n        for document in query_response.results:\n            metadata = {}\n            assert isinstance(\n                document, dict\n            ), \"document should be of type `dict[str,Any]`. But found: `{}`\".format(\n                type(document)\n            )\n            for k, v in document.items():\n                if k == self._text_key:\n                    assert isinstance(v, str), (\n                        \"page content stored in column `{}` must be of type `str`. \"\n                        \"But found: `{}`\"\n                    ).format(self._text_key, type(v))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html"}
{"id": "da09e904578a-6", "text": ").format(self._text_key, type(v))\n                    page_content = v\n                elif k == \"dist\":\n                    assert isinstance(v, float), (\n                        \"Computed distance between vectors must of type `float`. \"\n                        \"But found {}\"\n                    ).format(type(v))\n                    score = v\n                elif k not in [\"_id\", \"_event_time\", \"_meta\"]:\n                    # These columns are populated by Rockset when documents are\n                    # inserted. No need to return them in metadata dict.\n                    metadata[k] = v\n            finalResult.append(\n                (Document(page_content=page_content, metadata=metadata), score)\n            )\n        return finalResult\n    # Helper functions\n    def _build_query_sql(\n        self,\n        query_embedding: List[float],\n        distance_func: DistanceFunction,\n        k: int = 4,\n        where_str: Optional[str] = None,\n    ) -> str:\n        \"\"\"Builds Rockset SQL query to query similar vectors to query_vector\"\"\"\n        q_embedding_str = \",\".join(map(str, query_embedding))\n        distance_str = f\"\"\"{distance_func.value}({self._embedding_key}, \\\n[{q_embedding_str}]) as dist\"\"\"\n        where_str = f\"WHERE {where_str}\\n\" if where_str else \"\"\n        return f\"\"\"\\\nSELECT * EXCEPT({self._embedding_key}), {distance_str}\nFROM {self._workspace}.{self._collection_name}\n{where_str}\\\nORDER BY dist {distance_func.order_by()}\nLIMIT {str(k)}\n\"\"\"\n    def _write_documents_to_rockset(self, batch: List[dict]) -> List[str]:\n        add_doc_res = self._client.Documents.add_documents(\n            collection=self._collection_name, data=batch, workspace=self._workspace\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html"}
{"id": "da09e904578a-7", "text": "collection=self._collection_name, data=batch, workspace=self._workspace\n        )\n        return [doc_status._id for doc_status in add_doc_res.data]\n[docs]    def delete_texts(self, ids: List[str]) -> None:\n        \"\"\"Delete a list of docs from the Rockset collection\"\"\"\n        try:\n            from rockset.models import DeleteDocumentsRequestData\n        except ImportError:\n            raise ImportError(\n                \"Could not import rockset client python package. \"\n                \"Please install it with `pip install rockset`.\"\n            )\n        self._client.Documents.delete_documents(\n            collection=self._collection_name,\n            data=[DeleteDocumentsRequestData(id=i) for i in ids],\n            workspace=self._workspace,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html"}
{"id": "55461e2fe158-0", "text": "Source code for langchain.vectorstores.momento_vector_index\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n    TypeVar,\n    cast,\n)\nfrom uuid import uuid4\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_env\nfrom langchain.vectorstores.utils import DistanceStrategy\nVST = TypeVar(\"VST\", bound=\"VectorStore\")\nif TYPE_CHECKING:\n    from momento import PreviewVectorIndexClient\n[docs]class MomentoVectorIndex(VectorStore):\n    \"\"\"`Momento Vector Index` (MVI) vector store.\n    Momento Vector Index is a serverless vector index that can be used to store and\n    search vectors. To use you should have the ``momento`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import OpenAIEmbeddings\n            from langchain.vectorstores import MomentoVectorIndex\n            from momento import (\n                CredentialProvider,\n                PreviewVectorIndexClient,\n                VectorIndexConfigurations,\n            )\n            vectorstore = MomentoVectorIndex(\n                embedding=OpenAIEmbeddings(),\n                client=PreviewVectorIndexClient(\n                    VectorIndexConfigurations.Default.latest(),\n                    credential_provider=CredentialProvider.from_environment_variable(\n                        \"MOMENTO_API_KEY\"\n                    ),\n                ),\n                index_name=\"my-index\",\n            )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        client: \"PreviewVectorIndexClient\",\n        index_name: str = \"default\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html"}
{"id": "55461e2fe158-1", "text": "client: \"PreviewVectorIndexClient\",\n        index_name: str = \"default\",\n        distance_strategy: DistanceStrategy = DistanceStrategy.COSINE,\n        text_field: str = \"text\",\n        ensure_index_exists: bool = True,\n        **kwargs: Any,\n    ):\n        \"\"\"Initialize a Vector Store backed by Momento Vector Index.\n        Args:\n            embedding (Embeddings): The embedding function to use.\n            configuration (VectorIndexConfiguration): The configuration to initialize\n                the Vector Index with.\n            credential_provider (CredentialProvider): The credential provider to\n                authenticate the Vector Index with.\n            index_name (str, optional): The name of the index to store the documents in.\n                Defaults to \"default\".\n            distance_strategy (DistanceStrategy, optional): The distance strategy to\n                use. Defaults to DistanceStrategy.COSINE. If you select\n                DistanceStrategy.EUCLIDEAN_DISTANCE, Momento uses the squared\n                Euclidean distance.\n            text_field (str, optional): The name of the metadata field to store the\n                original text in. Defaults to \"text\".\n            ensure_index_exists (bool, optional): Whether to ensure that the index\n                exists before adding documents to it. Defaults to True.\n        \"\"\"\n        try:\n            from momento import PreviewVectorIndexClient\n        except ImportError:\n            raise ImportError(\n                \"Could not import momento python package. \"\n                \"Please install it with `pip install momento`.\"\n            )\n        self._client: PreviewVectorIndexClient = client\n        self._embedding = embedding\n        self.index_name = index_name\n        self.__validate_distance_strategy(distance_strategy)\n        self.distance_strategy = distance_strategy\n        self.text_field = text_field\n        self._ensure_index_exists = ensure_index_exists\n    @staticmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html"}
{"id": "55461e2fe158-2", "text": "self._ensure_index_exists = ensure_index_exists\n    @staticmethod\n    def __validate_distance_strategy(distance_strategy: DistanceStrategy) -> None:\n        if distance_strategy not in [\n            DistanceStrategy.COSINE,\n            DistanceStrategy.MAX_INNER_PRODUCT,\n            DistanceStrategy.MAX_INNER_PRODUCT,\n        ]:\n            raise ValueError(f\"Distance strategy {distance_strategy} not implemented.\")\n    @property\n    def embeddings(self) -> Embeddings:\n        return self._embedding\n    def _create_index_if_not_exists(self, num_dimensions: int) -> bool:\n        \"\"\"Create index if it does not exist.\"\"\"\n        from momento.requests.vector_index import SimilarityMetric\n        from momento.responses.vector_index import CreateIndex\n        similarity_metric = None\n        if self.distance_strategy == DistanceStrategy.COSINE:\n            similarity_metric = SimilarityMetric.COSINE_SIMILARITY\n        elif self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:\n            similarity_metric = SimilarityMetric.INNER_PRODUCT\n        elif self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE:\n            similarity_metric = SimilarityMetric.EUCLIDEAN_SIMILARITY\n        else:\n            raise ValueError(\n                f\"Distance strategy {self.distance_strategy} not implemented.\"\n            )\n        response = self._client.create_index(\n            self.index_name, num_dimensions, similarity_metric\n        )\n        if isinstance(response, CreateIndex.Success):\n            return True\n        elif isinstance(response, CreateIndex.IndexAlreadyExists):\n            return False\n        elif isinstance(response, CreateIndex.Error):\n            raise response.inner_exception\n        else:\n            raise Exception(f\"Unexpected response: {response}\")\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html"}
{"id": "55461e2fe158-3", "text": "**kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts (Iterable[str]): Iterable of strings to add to the vectorstore.\n            metadatas (Optional[List[dict]]): Optional list of metadatas associated with\n                the texts.\n            kwargs (Any): Other optional parameters. Specifically:\n            - ids (List[str], optional): List of ids to use for the texts.\n                Defaults to None, in which case uuids are generated.\n        Returns:\n            List[str]: List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        from momento.requests.vector_index import Item\n        from momento.responses.vector_index import UpsertItemBatch\n        texts = list(texts)\n        if len(texts) == 0:\n            return []\n        if metadatas is not None:\n            for metadata, text in zip(metadatas, texts):\n                metadata[self.text_field] = text\n        else:\n            metadatas = [{self.text_field: text} for text in texts]\n        try:\n            embeddings = self._embedding.embed_documents(texts)\n        except NotImplementedError:\n            embeddings = [self._embedding.embed_query(x) for x in texts]\n        # Create index if it does not exist.\n        # We assume that if it does exist, then it was created with the desired number\n        # of dimensions and similarity metric.\n        if self._ensure_index_exists:\n            self._create_index_if_not_exists(len(embeddings[0]))\n        if \"ids\" in kwargs:\n            ids = kwargs[\"ids\"]\n            if len(ids) != len(embeddings):\n                raise ValueError(\"Number of ids must match number of texts\")\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html"}
{"id": "55461e2fe158-4", "text": "raise ValueError(\"Number of ids must match number of texts\")\n        else:\n            ids = [str(uuid4()) for _ in range(len(embeddings))]\n        batch_size = 128\n        for i in range(0, len(embeddings), batch_size):\n            start = i\n            end = min(i + batch_size, len(embeddings))\n            items = [\n                Item(id=id, vector=vector, metadata=metadata)\n                for id, vector, metadata in zip(\n                    ids[start:end],\n                    embeddings[start:end],\n                    metadatas[start:end],\n                )\n            ]\n            response = self._client.upsert_item_batch(self.index_name, items)\n            if isinstance(response, UpsertItemBatch.Success):\n                pass\n            elif isinstance(response, UpsertItemBatch.Error):\n                raise response.inner_exception\n            else:\n                raise Exception(f\"Unexpected response: {response}\")\n        return ids\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:\n        \"\"\"Delete by vector ID.\n        Args:\n            ids (List[str]): List of ids to delete.\n            kwargs (Any): Other optional parameters (unused)\n        Returns:\n            Optional[bool]: True if deletion is successful,\n            False otherwise, None if not implemented.\n        \"\"\"\n        from momento.responses.vector_index import DeleteItemBatch\n        if ids is None:\n            return True\n        response = self._client.delete_item_batch(self.index_name, ids)\n        return isinstance(response, DeleteItemBatch.Success)\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Search for similar documents to the query string.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html"}
{"id": "55461e2fe158-5", "text": "\"\"\"Search for similar documents to the query string.\n        Args:\n            query (str): The query string to search for.\n            k (int, optional): The number of results to return. Defaults to 4.\n        Returns:\n            List[Document]: A list of documents that are similar to the query.\n        \"\"\"\n        res = self.similarity_search_with_score(query=query, k=k, **kwargs)\n        return [doc for doc, _ in res]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Search for similar documents to the query string.\n        Args:\n            query (str): The query string to search for.\n            k (int, optional): The number of results to return. Defaults to 4.\n            kwargs (Any): Vector Store specific search parameters. The following are\n                forwarded to the Momento Vector Index:\n            - top_k (int, optional): The number of results to return.\n        Returns:\n            List[Tuple[Document, float]]: A list of tuples of the form\n                (Document, score).\n        \"\"\"\n        embedding = self._embedding.embed_query(query)\n        results = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, **kwargs\n        )\n        return results\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Search for similar documents to the query vector.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html"}
{"id": "55461e2fe158-6", "text": "\"\"\"Search for similar documents to the query vector.\n        Args:\n            embedding (List[float]): The query vector to search for.\n            k (int, optional): The number of results to return. Defaults to 4.\n            kwargs (Any): Vector Store specific search parameters. The following are\n                forwarded to the Momento Vector Index:\n            - top_k (int, optional): The number of results to return.\n        Returns:\n            List[Tuple[Document, float]]: A list of tuples of the form\n                (Document, score).\n        \"\"\"\n        from momento.requests.vector_index import ALL_METADATA\n        from momento.responses.vector_index import Search\n        if \"top_k\" in kwargs:\n            k = kwargs[\"k\"]\n        response = self._client.search(\n            self.index_name, embedding, top_k=k, metadata_fields=ALL_METADATA\n        )\n        if not isinstance(response, Search.Success):\n            return []\n        results = []\n        for hit in response.hits:\n            text = cast(str, hit.metadata.pop(self.text_field))\n            doc = Document(page_content=text, metadata=hit.metadata)\n            pair = (doc, hit.score)\n            results.append(pair)\n        return results\n[docs]    def similarity_search_by_vector(\n        self, embedding: List[float], k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Search for similar documents to the query vector.\n        Args:\n            embedding (List[float]): The query vector to search for.\n            k (int, optional): The number of results to return. Defaults to 4.\n        Returns:\n            List[Document]: A list of documents that are similar to the query.\n        \"\"\"\n        results = self.similarity_search_with_score_by_vector(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html"}
{"id": "55461e2fe158-7", "text": "\"\"\"\n        results = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, **kwargs\n        )\n        return [doc for doc, _ in results]\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[VST],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> VST:\n        \"\"\"Return the Vector Store initialized from texts and embeddings.\n        Args:\n            cls (Type[VST]): The Vector Store class to use to initialize\n                the Vector Store.\n            texts (List[str]): The texts to initialize the Vector Store with.\n            embedding (Embeddings): The embedding function to use.\n            metadatas (Optional[List[dict]], optional): The metadata associated with\n                the texts. Defaults to None.\n            kwargs (Any): Vector Store specific parameters. The following are forwarded\n                to the Vector Store constructor and required:\n            - index_name (str, optional): The name of the index to store the documents\n                in. Defaults to \"default\".\n            - text_field (str, optional): The name of the metadata field to store the\n                original text in. Defaults to \"text\".\n            - distance_strategy (DistanceStrategy, optional): The distance strategy to\n                use. Defaults to DistanceStrategy.COSINE. If you select\n                DistanceStrategy.EUCLIDEAN_DISTANCE, Momento uses the squared\n                Euclidean distance.\n            - ensure_index_exists (bool, optional): Whether to ensure that the index\n                exists before adding documents to it. Defaults to True.\n            Additionally you can either pass in a client or an API key\n            - client (PreviewVectorIndexClient): The Momento Vector Index client to use.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html"}
{"id": "55461e2fe158-8", "text": "- client (PreviewVectorIndexClient): The Momento Vector Index client to use.\n            - api_key (Optional[str]): The configuration to use to initialize\n                the Vector Index with. Defaults to None. If None, the configuration\n                is initialized from the environment variable `MOMENTO_API_KEY`.\n        Returns:\n            VST: Momento Vector Index vector store initialized from texts and\n                embeddings.\n        \"\"\"\n        from momento import (\n            CredentialProvider,\n            PreviewVectorIndexClient,\n            VectorIndexConfigurations,\n        )\n        if \"client\" in kwargs:\n            client = kwargs.pop(\"client\")\n        else:\n            supplied_api_key = kwargs.pop(\"api_key\", None)\n            api_key = supplied_api_key or get_from_env(\"api_key\", \"MOMENTO_API_KEY\")\n            client = PreviewVectorIndexClient(\n                configuration=VectorIndexConfigurations.Default.latest(),\n                credential_provider=CredentialProvider.from_string(api_key),\n            )\n        vector_db = cls(embedding=embedding, client=client, **kwargs)  # type: ignore\n        vector_db.add_texts(texts=texts, metadatas=metadatas, **kwargs)\n        return vector_db", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/momento_vector_index.html"}
{"id": "deda41dbc8c5-0", "text": "Source code for langchain.vectorstores.elasticsearch\nimport logging\nimport uuid\nfrom abc import ABC, abstractmethod\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Literal,\n    Optional,\n    Tuple,\n    Union,\n)\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import DistanceStrategy, maximal_marginal_relevance\nif TYPE_CHECKING:\n    from elasticsearch import Elasticsearch\nlogger = logging.getLogger(__name__)\n[docs]class BaseRetrievalStrategy(ABC):\n    \"\"\"Base class for `Elasticsearch` retrieval strategies.\"\"\"\n[docs]    @abstractmethod\n    def query(\n        self,\n        query_vector: Union[List[float], None],\n        query: Union[str, None],\n        *,\n        k: int,\n        fetch_k: int,\n        vector_query_field: str,\n        text_field: str,\n        filter: List[dict],\n        similarity: Union[DistanceStrategy, None],\n    ) -> Dict:\n        \"\"\"\n        Executes when a search is performed on the store.\n        Args:\n            query_vector: The query vector,\n                          or None if not using vector-based query.\n            query: The text query, or None if not using text-based query.\n            k: The total number of results to retrieve.\n            fetch_k: The number of results to fetch initially.\n            vector_query_field: The field containing the vector\n                                representations in the index.\n            text_field: The field containing the text data in the index.\n            filter: List of filter clauses to apply to the query.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-1", "text": "filter: List of filter clauses to apply to the query.\n            similarity: The similarity strategy to use, or None if not using one.\n        Returns:\n            Dict: The Elasticsearch query body.\n        \"\"\"\n[docs]    @abstractmethod\n    def index(\n        self,\n        dims_length: Union[int, None],\n        vector_query_field: str,\n        similarity: Union[DistanceStrategy, None],\n    ) -> Dict:\n        \"\"\"\n        Executes when the index is created.\n        Args:\n            dims_length: Numeric length of the embedding vectors,\n                        or None if not using vector-based query.\n            vector_query_field: The field containing the vector\n                                representations in the index.\n            similarity: The similarity strategy to use,\n                        or None if not using one.\n        Returns:\n            Dict: The Elasticsearch settings and mappings for the strategy.\n        \"\"\"\n[docs]    def before_index_setup(\n        self, client: \"Elasticsearch\", text_field: str, vector_query_field: str\n    ) -> None:\n        \"\"\"\n        Executes before the index is created. Used for setting up\n        any required Elasticsearch resources like a pipeline.\n        Args:\n            client: The Elasticsearch client.\n            text_field: The field containing the text data in the index.\n            vector_query_field: The field containing the vector\n                                representations in the index.\n        \"\"\"\n[docs]    def require_inference(self) -> bool:\n        \"\"\"\n        Returns whether or not the strategy requires inference\n        to be performed on the text before it is added to the index.\n        Returns:\n            bool: Whether or not the strategy requires inference\n            to be performed on the text before it is added to the index.\n        \"\"\"\n        return True", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-2", "text": "\"\"\"\n        return True\n[docs]class ApproxRetrievalStrategy(BaseRetrievalStrategy):\n    \"\"\"Approximate retrieval strategy using the `HNSW` algorithm.\"\"\"\n[docs]    def __init__(\n        self,\n        query_model_id: Optional[str] = None,\n        hybrid: Optional[bool] = False,\n        rrf: Optional[Union[dict, bool]] = True,\n    ):\n        self.query_model_id = query_model_id\n        self.hybrid = hybrid\n        # RRF has two optional parameters\n        # 'rank_constant', 'window_size'\n        # https://www.elastic.co/guide/en/elasticsearch/reference/current/rrf.html\n        self.rrf = rrf\n[docs]    def query(\n        self,\n        query_vector: Union[List[float], None],\n        query: Union[str, None],\n        k: int,\n        fetch_k: int,\n        vector_query_field: str,\n        text_field: str,\n        filter: List[dict],\n        similarity: Union[DistanceStrategy, None],\n    ) -> Dict:\n        knn = {\n            \"filter\": filter,\n            \"field\": vector_query_field,\n            \"k\": k,\n            \"num_candidates\": fetch_k,\n        }\n        # Embedding provided via the embedding function\n        if query_vector and not self.query_model_id:\n            knn[\"query_vector\"] = query_vector\n        # Case 2: Used when model has been deployed to\n        # Elasticsearch and can infer the query vector from the query text\n        elif query and self.query_model_id:\n            knn[\"query_vector_builder\"] = {\n                \"text_embedding\": {\n                    \"model_id\": self.query_model_id,  # use 'model_id' argument", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-3", "text": "\"model_id\": self.query_model_id,  # use 'model_id' argument\n                    \"model_text\": query,  # use 'query' argument\n                }\n            }\n        else:\n            raise ValueError(\n                \"You must provide an embedding function or a\"\n                \" query_model_id to perform a similarity search.\"\n            )\n        # If hybrid, add a query to the knn query\n        # RRF is used to even the score from the knn query and text query\n        # RRF has two optional parameters: {'rank_constant':int, 'window_size':int}\n        # https://www.elastic.co/guide/en/elasticsearch/reference/current/rrf.html\n        if self.hybrid:\n            query_body = {\n                \"knn\": knn,\n                \"query\": {\n                    \"bool\": {\n                        \"must\": [\n                            {\n                                \"match\": {\n                                    text_field: {\n                                        \"query\": query,\n                                    }\n                                }\n                            }\n                        ],\n                        \"filter\": filter,\n                    }\n                },\n            }\n            if isinstance(self.rrf, dict):\n                query_body[\"rank\"] = {\"rrf\": self.rrf}\n            elif isinstance(self.rrf, bool) and self.rrf is True:\n                query_body[\"rank\"] = {\"rrf\": {}}\n            return query_body\n        else:\n            return {\"knn\": knn}\n[docs]    def index(\n        self,\n        dims_length: Union[int, None],\n        vector_query_field: str,\n        similarity: Union[DistanceStrategy, None],\n    ) -> Dict:\n        \"\"\"Create the mapping for the Elasticsearch index.\"\"\"\n        if similarity is DistanceStrategy.COSINE:\n            similarityAlgo = \"cosine\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-4", "text": "similarityAlgo = \"cosine\"\n        elif similarity is DistanceStrategy.EUCLIDEAN_DISTANCE:\n            similarityAlgo = \"l2_norm\"\n        elif similarity is DistanceStrategy.DOT_PRODUCT:\n            similarityAlgo = \"dot_product\"\n        else:\n            raise ValueError(f\"Similarity {similarity} not supported.\")\n        return {\n            \"mappings\": {\n                \"properties\": {\n                    vector_query_field: {\n                        \"type\": \"dense_vector\",\n                        \"dims\": dims_length,\n                        \"index\": True,\n                        \"similarity\": similarityAlgo,\n                    },\n                }\n            }\n        }\n[docs]class ExactRetrievalStrategy(BaseRetrievalStrategy):\n    \"\"\"Exact retrieval strategy using the `script_score` query.\"\"\"\n[docs]    def query(\n        self,\n        query_vector: Union[List[float], None],\n        query: Union[str, None],\n        k: int,\n        fetch_k: int,\n        vector_query_field: str,\n        text_field: str,\n        filter: Union[List[dict], None],\n        similarity: Union[DistanceStrategy, None],\n    ) -> Dict:\n        if similarity is DistanceStrategy.COSINE:\n            similarityAlgo = (\n                f\"cosineSimilarity(params.query_vector, '{vector_query_field}') + 1.0\"\n            )\n        elif similarity is DistanceStrategy.EUCLIDEAN_DISTANCE:\n            similarityAlgo = (\n                f\"1 / (1 + l2norm(params.query_vector, '{vector_query_field}'))\"\n            )\n        elif similarity is DistanceStrategy.DOT_PRODUCT:\n            similarityAlgo = f\"\"\"\n            double value = dotProduct(params.query_vector, '{vector_query_field}');", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-5", "text": "double value = dotProduct(params.query_vector, '{vector_query_field}');\n            return sigmoid(1, Math.E, -value); \n            \"\"\"\n        else:\n            raise ValueError(f\"Similarity {similarity} not supported.\")\n        queryBool: Dict = {\"match_all\": {}}\n        if filter:\n            queryBool = {\"bool\": {\"filter\": filter}}\n        return {\n            \"query\": {\n                \"script_score\": {\n                    \"query\": queryBool,\n                    \"script\": {\n                        \"source\": similarityAlgo,\n                        \"params\": {\"query_vector\": query_vector},\n                    },\n                },\n            }\n        }\n[docs]    def index(\n        self,\n        dims_length: Union[int, None],\n        vector_query_field: str,\n        similarity: Union[DistanceStrategy, None],\n    ) -> Dict:\n        \"\"\"Create the mapping for the Elasticsearch index.\"\"\"\n        return {\n            \"mappings\": {\n                \"properties\": {\n                    vector_query_field: {\n                        \"type\": \"dense_vector\",\n                        \"dims\": dims_length,\n                        \"index\": False,\n                    },\n                }\n            }\n        }\n[docs]class SparseRetrievalStrategy(BaseRetrievalStrategy):\n    \"\"\"Sparse retrieval strategy using the `text_expansion` processor.\"\"\"\n[docs]    def __init__(self, model_id: Optional[str] = None):\n        self.model_id = model_id or \".elser_model_1\"\n[docs]    def query(\n        self,\n        query_vector: Union[List[float], None],\n        query: Union[str, None],\n        k: int,\n        fetch_k: int,\n        vector_query_field: str,\n        text_field: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-6", "text": "vector_query_field: str,\n        text_field: str,\n        filter: List[dict],\n        similarity: Union[DistanceStrategy, None],\n    ) -> Dict:\n        return {\n            \"query\": {\n                \"bool\": {\n                    \"must\": [\n                        {\n                            \"text_expansion\": {\n                                f\"{vector_query_field}.tokens\": {\n                                    \"model_id\": self.model_id,\n                                    \"model_text\": query,\n                                }\n                            }\n                        }\n                    ],\n                    \"filter\": filter,\n                }\n            }\n        }\n    def _get_pipeline_name(self) -> str:\n        return f\"{self.model_id}_sparse_embedding\"\n[docs]    def before_index_setup(\n        self, client: \"Elasticsearch\", text_field: str, vector_query_field: str\n    ) -> None:\n        # If model_id is provided, create a pipeline for the model\n        if self.model_id:\n            client.ingest.put_pipeline(\n                id=self._get_pipeline_name(),\n                description=\"Embedding pipeline for langchain vectorstore\",\n                processors=[\n                    {\n                        \"inference\": {\n                            \"model_id\": self.model_id,\n                            \"target_field\": vector_query_field,\n                            \"field_map\": {text_field: \"text_field\"},\n                            \"inference_config\": {\n                                \"text_expansion\": {\"results_field\": \"tokens\"}\n                            },\n                        }\n                    }\n                ],\n            )\n[docs]    def index(\n        self,\n        dims_length: Union[int, None],\n        vector_query_field: str,\n        similarity: Union[DistanceStrategy, None],\n    ) -> Dict:\n        return {\n            \"mappings\": {\n                \"properties\": {\n                    vector_query_field: {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-7", "text": "\"mappings\": {\n                \"properties\": {\n                    vector_query_field: {\n                        \"properties\": {\"tokens\": {\"type\": \"rank_features\"}}\n                    }\n                }\n            },\n            \"settings\": {\"default_pipeline\": self._get_pipeline_name()},\n        }\n[docs]    def require_inference(self) -> bool:\n        return False\n[docs]class ElasticsearchStore(VectorStore):\n    \"\"\"`Elasticsearch` vector store.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import ElasticsearchStore\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            embeddings = OpenAIEmbeddings()\n            vectorstore = ElasticsearchStore(\n                embedding=OpenAIEmbeddings(),\n                index_name=\"langchain-demo\",\n                es_url=\"http://localhost:9200\"\n            )\n    Args:\n        index_name: Name of the Elasticsearch index to create.\n        es_url: URL of the Elasticsearch instance to connect to.\n        cloud_id: Cloud ID of the Elasticsearch instance to connect to.\n        es_user: Username to use when connecting to Elasticsearch.\n        es_password: Password to use when connecting to Elasticsearch.\n        es_api_key: API key to use when connecting to Elasticsearch.\n        es_connection: Optional pre-existing Elasticsearch connection.\n        vector_query_field: Optional. Name of the field to store\n                            the embedding vectors in.\n        query_field: Optional. Name of the field to store the texts in.\n        strategy: Optional. Retrieval strategy to use when searching the index.\n                 Defaults to ApproxRetrievalStrategy. Can be one of\n                 ExactRetrievalStrategy, ApproxRetrievalStrategy,\n                 or SparseRetrievalStrategy.\n        distance_strategy: Optional. Distance strategy to use when\n                            searching the index.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-8", "text": "distance_strategy: Optional. Distance strategy to use when\n                            searching the index.\n                            Defaults to COSINE. Can be one of COSINE,\n                            EUCLIDEAN_DISTANCE, or DOT_PRODUCT.\n    If you want to use a cloud hosted Elasticsearch instance, you can pass in the\n    cloud_id argument instead of the es_url argument.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import ElasticsearchStore\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            vectorstore = ElasticsearchStore(\n                embedding=OpenAIEmbeddings(),\n                index_name=\"langchain-demo\",\n                es_cloud_id=\"<cloud_id>\"\n                es_user=\"elastic\",\n                es_password=\"<password>\"\n            )\n    You can also connect to an existing Elasticsearch instance by passing in a\n    pre-existing Elasticsearch connection via the es_connection argument.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import ElasticsearchStore\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            from elasticsearch import Elasticsearch\n            es_connection = Elasticsearch(\"http://localhost:9200\")\n            vectorstore = ElasticsearchStore(\n                embedding=OpenAIEmbeddings(),\n                index_name=\"langchain-demo\",\n                es_connection=es_connection\n            )\n    ElasticsearchStore by default uses the ApproxRetrievalStrategy, which uses the\n    HNSW algorithm to perform approximate nearest neighbor search. This is the\n    fastest and most memory efficient algorithm.\n    If you want to use the Brute force / Exact strategy for searching vectors, you\n    can pass in the ExactRetrievalStrategy to the ElasticsearchStore constructor.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import ElasticsearchStore\n            from langchain.embeddings.openai import OpenAIEmbeddings", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-9", "text": "from langchain.embeddings.openai import OpenAIEmbeddings\n            vectorstore = ElasticsearchStore(\n                embedding=OpenAIEmbeddings(),\n                index_name=\"langchain-demo\",\n                es_url=\"http://localhost:9200\",\n                strategy=ElasticsearchStore.ExactRetrievalStrategy()\n            )\n    Both strategies require that you know the similarity metric you want to use\n    when creating the index. The default is cosine similarity, but you can also\n    use dot product or euclidean distance.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import ElasticsearchStore\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            from langchain.vectorstores.utils import DistanceStrategy\n            vectorstore = ElasticsearchStore(\n                embedding=OpenAIEmbeddings(),\n                index_name=\"langchain-demo\",\n                es_url=\"http://localhost:9200\",\n                distance_strategy=\"DOT_PRODUCT\"\n            )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        index_name: str,\n        *,\n        embedding: Optional[Embeddings] = None,\n        es_connection: Optional[\"Elasticsearch\"] = None,\n        es_url: Optional[str] = None,\n        es_cloud_id: Optional[str] = None,\n        es_user: Optional[str] = None,\n        es_api_key: Optional[str] = None,\n        es_password: Optional[str] = None,\n        vector_query_field: str = \"vector\",\n        query_field: str = \"text\",\n        distance_strategy: Optional[\n            Literal[\n                DistanceStrategy.COSINE,\n                DistanceStrategy.DOT_PRODUCT,\n                DistanceStrategy.EUCLIDEAN_DISTANCE,\n            ]\n        ] = None,\n        strategy: BaseRetrievalStrategy = ApproxRetrievalStrategy(),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-10", "text": "strategy: BaseRetrievalStrategy = ApproxRetrievalStrategy(),\n    ):\n        self.embedding = embedding\n        self.index_name = index_name\n        self.query_field = query_field\n        self.vector_query_field = vector_query_field\n        self.distance_strategy = (\n            DistanceStrategy.COSINE\n            if distance_strategy is None\n            else DistanceStrategy[distance_strategy]\n        )\n        self.strategy = strategy\n        if es_connection is not None:\n            self.client = es_connection.options(\n                headers={\"user-agent\": self.get_user_agent()}\n            )\n        elif es_url is not None or es_cloud_id is not None:\n            self.client = ElasticsearchStore.connect_to_elasticsearch(\n                es_url=es_url,\n                username=es_user,\n                password=es_password,\n                cloud_id=es_cloud_id,\n                api_key=es_api_key,\n            )\n        else:\n            raise ValueError(\n                \"\"\"Either provide a pre-existing Elasticsearch connection, \\\n                or valid credentials for creating a new connection.\"\"\"\n            )\n[docs]    @staticmethod\n    def get_user_agent() -> str:\n        from langchain import __version__\n        return f\"langchain-py-vs/{__version__}\"\n[docs]    @staticmethod\n    def connect_to_elasticsearch(\n        *,\n        es_url: Optional[str] = None,\n        cloud_id: Optional[str] = None,\n        api_key: Optional[str] = None,\n        username: Optional[str] = None,\n        password: Optional[str] = None,\n    ) -> \"Elasticsearch\":\n        try:\n            import elasticsearch\n        except ImportError:\n            raise ImportError(\n                \"Could not import elasticsearch python package. \"\n                \"Please install it with `pip install elasticsearch`.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-11", "text": "\"Please install it with `pip install elasticsearch`.\"\n            )\n        if es_url and cloud_id:\n            raise ValueError(\n                \"Both es_url and cloud_id are defined. Please provide only one.\"\n            )\n        connection_params: Dict[str, Any] = {}\n        if es_url:\n            connection_params[\"hosts\"] = [es_url]\n        elif cloud_id:\n            connection_params[\"cloud_id\"] = cloud_id\n        else:\n            raise ValueError(\"Please provide either elasticsearch_url or cloud_id.\")\n        if api_key:\n            connection_params[\"api_key\"] = api_key\n        elif username and password:\n            connection_params[\"basic_auth\"] = (username, password)\n        es_client = elasticsearch.Elasticsearch(\n            **connection_params,\n            headers={\"user-agent\": ElasticsearchStore.get_user_agent()},\n        )\n        try:\n            es_client.info()\n        except Exception as e:\n            logger.error(f\"Error connecting to Elasticsearch: {e}\")\n            raise e\n        return es_client\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return self.embedding\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 50,\n        filter: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return Elasticsearch documents most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k (int): Number of Documents to fetch to pass to knn num_candidates.\n            filter: Array of Elasticsearch filter clauses to apply to the query.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-12", "text": "filter: Array of Elasticsearch filter clauses to apply to the query.\n        Returns:\n            List of Documents most similar to the query,\n            in descending order of similarity.\n        \"\"\"\n        results = self._search(\n            query=query, k=k, fetch_k=fetch_k, filter=filter, **kwargs\n        )\n        return [doc for doc, _ in results]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        fields: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n            among selected documents.\n        Args:\n            query (str): Text to look up documents similar to.\n            k (int): Number of Documents to return. Defaults to 4.\n            fetch_k (int): Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult (float): Number between 0 and 1 that determines the degree\n                of diversity among the results with 0 corresponding\n                to maximum diversity and 1 to minimum diversity.\n                Defaults to 0.5.\n            fields: Other fields to get from elasticsearch source. These fields\n                will be added to the document metadata.\n        Returns:\n            List[Document]: A list of Documents selected by maximal marginal relevance.\n        \"\"\"\n        if self.embedding is None:\n            raise ValueError(\"You must provide an embedding function to perform MMR\")\n        remove_vector_query_field_from_metadata = True\n        if fields is None:\n            fields = [self.vector_query_field]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-13", "text": "if fields is None:\n            fields = [self.vector_query_field]\n        elif self.vector_query_field not in fields:\n            fields.append(self.vector_query_field)\n        else:\n            remove_vector_query_field_from_metadata = False\n        # Embed the query\n        query_embedding = self.embedding.embed_query(query)\n        # Fetch the initial documents\n        got_docs = self._search(\n            query_vector=query_embedding, k=fetch_k, fields=fields, **kwargs\n        )\n        # Get the embeddings for the fetched documents\n        got_embeddings = [doc.metadata[self.vector_query_field] for doc, _ in got_docs]\n        # Select documents using maximal marginal relevance\n        selected_indices = maximal_marginal_relevance(\n            np.array(query_embedding), got_embeddings, lambda_mult=lambda_mult, k=k\n        )\n        selected_docs = [got_docs[i][0] for i in selected_indices]\n        if remove_vector_query_field_from_metadata:\n            for doc in selected_docs:\n                del doc.metadata[self.vector_query_field]\n        return selected_docs\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 4, filter: Optional[List[dict]] = None, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return Elasticsearch documents most similar to query, along with scores.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Array of Elasticsearch filter clauses to apply to the query.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        return self._search(query=query, k=k, filter=filter, **kwargs)\n[docs]    def similarity_search_by_vector_with_relevance_scores(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-14", "text": "[docs]    def similarity_search_by_vector_with_relevance_scores(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[List[Dict]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return Elasticsearch documents most similar to query, along with scores.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: Array of Elasticsearch filter clauses to apply to the query.\n        Returns:\n            List of Documents most similar to the embedding and score for each\n        \"\"\"\n        return self._search(query_vector=embedding, k=k, filter=filter, **kwargs)\n    def _search(\n        self,\n        query: Optional[str] = None,\n        k: int = 4,\n        query_vector: Union[List[float], None] = None,\n        fetch_k: int = 50,\n        fields: Optional[List[str]] = None,\n        filter: Optional[List[dict]] = None,\n        custom_query: Optional[Callable[[Dict, Union[str, None]], Dict]] = None,\n        doc_builder: Optional[Callable[[Dict], Document]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return Elasticsearch documents most similar to query, along with scores.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            query_vector: Embedding to look up documents similar to.\n            fetch_k: Number of candidates to fetch from each shard.\n                    Defaults to 50.\n            fields: List of fields to return from Elasticsearch.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-15", "text": "Defaults to 50.\n            fields: List of fields to return from Elasticsearch.\n                    Defaults to only returning the text field.\n            filter: Array of Elasticsearch filter clauses to apply to the query.\n            custom_query: Function to modify the Elasticsearch\n                         query body before it is sent to Elasticsearch.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        if fields is None:\n            fields = []\n        if \"metadata\" not in fields:\n            fields.append(\"metadata\")\n        if self.query_field not in fields:\n            fields.append(self.query_field)\n        if self.embedding and query is not None:\n            query_vector = self.embedding.embed_query(query)\n        query_body = self.strategy.query(\n            query_vector=query_vector,\n            query=query,\n            k=k,\n            fetch_k=fetch_k,\n            vector_query_field=self.vector_query_field,\n            text_field=self.query_field,\n            filter=filter or [],\n            similarity=self.distance_strategy,\n        )\n        logger.debug(f\"Query body: {query_body}\")\n        if custom_query is not None:\n            query_body = custom_query(query_body, query)\n            logger.debug(f\"Calling custom_query, Query body now: {query_body}\")\n        # Perform the kNN search on the Elasticsearch index and return the results.\n        response = self.client.search(\n            index=self.index_name,\n            **query_body,\n            size=k,\n            source=fields,\n        )\n        def default_doc_builder(hit: Dict) -> Document:\n            return Document(\n                page_content=hit[\"_source\"].get(self.query_field, \"\"),\n                metadata=hit[\"_source\"][\"metadata\"],\n            )\n        doc_builder = doc_builder or default_doc_builder\n        docs_and_scores = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-16", "text": "doc_builder = doc_builder or default_doc_builder\n        docs_and_scores = []\n        for hit in response[\"hits\"][\"hits\"]:\n            for field in fields:\n                if field in hit[\"_source\"] and field not in [\n                    \"metadata\",\n                    self.query_field,\n                ]:\n                    hit[\"_source\"][\"metadata\"][field] = hit[\"_source\"][field]\n            docs_and_scores.append(\n                (\n                    doc_builder(hit),\n                    hit[\"_score\"],\n                )\n            )\n        return docs_and_scores\n[docs]    def delete(\n        self,\n        ids: Optional[List[str]] = None,\n        refresh_indices: Optional[bool] = True,\n        **kwargs: Any,\n    ) -> Optional[bool]:\n        \"\"\"Delete documents from the Elasticsearch index.\n        Args:\n            ids: List of ids of documents to delete.\n            refresh_indices: Whether to refresh the index\n                            after deleting documents. Defaults to True.\n        \"\"\"\n        try:\n            from elasticsearch.helpers import BulkIndexError, bulk\n        except ImportError:\n            raise ImportError(\n                \"Could not import elasticsearch python package. \"\n                \"Please install it with `pip install elasticsearch`.\"\n            )\n        body = []\n        if ids is None:\n            raise ValueError(\"ids must be provided.\")\n        for _id in ids:\n            body.append({\"_op_type\": \"delete\", \"_index\": self.index_name, \"_id\": _id})\n        if len(body) > 0:\n            try:\n                bulk(self.client, body, refresh=refresh_indices, ignore_status=404)\n                logger.debug(f\"Deleted {len(body)} texts from index\")\n                return True\n            except BulkIndexError as e:\n                logger.error(f\"Error deleting texts: {e}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-17", "text": "logger.error(f\"Error deleting texts: {e}\")\n                firstError = e.errors[0].get(\"index\", {}).get(\"error\", {})\n                logger.error(f\"First error reason: {firstError.get('reason')}\")\n                raise e\n        else:\n            logger.debug(\"No texts to delete from index\")\n            return False\n    def _create_index_if_not_exists(\n        self, index_name: str, dims_length: Optional[int] = None\n    ) -> None:\n        \"\"\"Create the Elasticsearch index if it doesn't already exist.\n        Args:\n            index_name: Name of the Elasticsearch index to create.\n            dims_length: Length of the embedding vectors.\n        \"\"\"\n        if self.client.indices.exists(index=index_name):\n            logger.debug(f\"Index {index_name} already exists. Skipping creation.\")\n        else:\n            if dims_length is None and self.strategy.require_inference():\n                raise ValueError(\n                    \"Cannot create index without specifying dims_length \"\n                    \"when the index doesn't already exist. We infer \"\n                    \"dims_length from the first embedding. Check that \"\n                    \"you have provided an embedding function.\"\n                )\n            self.strategy.before_index_setup(\n                client=self.client,\n                text_field=self.query_field,\n                vector_query_field=self.vector_query_field,\n            )\n            indexSettings = self.strategy.index(\n                vector_query_field=self.vector_query_field,\n                dims_length=dims_length,\n                similarity=self.distance_strategy,\n            )\n            logger.debug(\n                f\"Creating index {index_name} with mappings {indexSettings['mappings']}\"\n            )\n            self.client.indices.create(index=index_name, **indexSettings)\n    def __add(\n        self,\n        texts: Iterable[str],\n        embeddings: Optional[List[List[float]]],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-18", "text": "texts: Iterable[str],\n        embeddings: Optional[List[List[float]]],\n        metadatas: Optional[List[Dict[Any, Any]]] = None,\n        ids: Optional[List[str]] = None,\n        refresh_indices: bool = True,\n        create_index_if_not_exists: bool = True,\n        bulk_kwargs: Optional[Dict] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        try:\n            from elasticsearch.helpers import BulkIndexError, bulk\n        except ImportError:\n            raise ImportError(\n                \"Could not import elasticsearch python package. \"\n                \"Please install it with `pip install elasticsearch`.\"\n            )\n        bulk_kwargs = bulk_kwargs or {}\n        ids = ids or [str(uuid.uuid4()) for _ in texts]\n        requests = []\n        if create_index_if_not_exists:\n            if embeddings:\n                dims_length = len(embeddings[0])\n            else:\n                dims_length = None\n            self._create_index_if_not_exists(\n                index_name=self.index_name, dims_length=dims_length\n            )\n        for i, text in enumerate(texts):\n            metadata = metadatas[i] if metadatas else {}\n            request = {\n                \"_op_type\": \"index\",\n                \"_index\": self.index_name,\n                self.query_field: text,\n                \"metadata\": metadata,\n                \"_id\": ids[i],\n            }\n            if embeddings:\n                request[self.vector_query_field] = embeddings[i]\n            requests.append(request)\n        if len(requests) > 0:\n            try:\n                success, failed = bulk(\n                    self.client,\n                    requests,\n                    stats_only=True,\n                    refresh=refresh_indices,\n                    **bulk_kwargs,\n                )\n                logger.debug(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-19", "text": "**bulk_kwargs,\n                )\n                logger.debug(\n                    f\"Added {success} and failed to add {failed} texts to index\"\n                )\n                logger.debug(f\"added texts {ids} to index\")\n                return ids\n            except BulkIndexError as e:\n                logger.error(f\"Error adding texts: {e}\")\n                firstError = e.errors[0].get(\"index\", {}).get(\"error\", {})\n                logger.error(f\"First error reason: {firstError.get('reason')}\")\n                raise e\n        else:\n            logger.debug(\"No texts to add to index\")\n            return []\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[Dict[Any, Any]]] = None,\n        ids: Optional[List[str]] = None,\n        refresh_indices: bool = True,\n        create_index_if_not_exists: bool = True,\n        bulk_kwargs: Optional[Dict] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of ids to associate with the texts.\n            refresh_indices: Whether to refresh the Elasticsearch indices\n                            after adding the texts.\n            create_index_if_not_exists: Whether to create the Elasticsearch\n                                        index if it doesn't already exist.\n            *bulk_kwargs: Additional arguments to pass to Elasticsearch bulk.\n                - chunk_size: Optional. Number of texts to add to the\n                    index at a time. Defaults to 500.\n        Returns:\n            List of ids from adding the texts into the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-20", "text": "Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        if self.embedding is not None:\n            # If no search_type requires inference, we use the provided\n            # embedding function to embed the texts.\n            embeddings = self.embedding.embed_documents(list(texts))\n        else:\n            # the search_type doesn't require inference, so we don't need to\n            # embed the texts.\n            embeddings = None\n        return self.__add(\n            texts,\n            embeddings,\n            metadatas=metadatas,\n            ids=ids,\n            refresh_indices=refresh_indices,\n            create_index_if_not_exists=create_index_if_not_exists,\n            bulk_kwargs=bulk_kwargs,\n            kwargs=kwargs,\n        )\n[docs]    def add_embeddings(\n        self,\n        text_embeddings: Iterable[Tuple[str, List[float]]],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        refresh_indices: bool = True,\n        create_index_if_not_exists: bool = True,\n        bulk_kwargs: Optional[Dict] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add the given texts and embeddings to the vectorstore.\n        Args:\n            text_embeddings: Iterable pairs of string and embedding to\n                add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of unique IDs.\n            refresh_indices: Whether to refresh the Elasticsearch indices\n                            after adding the texts.\n            create_index_if_not_exists: Whether to create the Elasticsearch\n                                        index if it doesn't already exist.\n            *bulk_kwargs: Additional arguments to pass to Elasticsearch bulk.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-21", "text": "*bulk_kwargs: Additional arguments to pass to Elasticsearch bulk.\n                - chunk_size: Optional. Number of texts to add to the\n                    index at a time. Defaults to 500.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        texts, embeddings = zip(*text_embeddings)\n        return self.__add(\n            list(texts),\n            list(embeddings),\n            metadatas=metadatas,\n            ids=ids,\n            refresh_indices=refresh_indices,\n            create_index_if_not_exists=create_index_if_not_exists,\n            bulk_kwargs=bulk_kwargs,\n            kwargs=kwargs,\n        )\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Optional[Embeddings] = None,\n        metadatas: Optional[List[Dict[str, Any]]] = None,\n        bulk_kwargs: Optional[Dict] = None,\n        **kwargs: Any,\n    ) -> \"ElasticsearchStore\":\n        \"\"\"Construct ElasticsearchStore wrapper from raw documents.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import ElasticsearchStore\n                from langchain.embeddings.openai import OpenAIEmbeddings\n                db = ElasticsearchStore.from_texts(\n                    texts,\n                    // embeddings optional if using\n                    // a strategy that doesn't require inference\n                    embeddings,\n                    index_name=\"langchain-demo\",\n                    es_url=\"http://localhost:9200\"\n                )\n        Args:\n            texts: List of texts to add to the Elasticsearch index.\n            embedding: Embedding function to use to embed the texts.\n            metadatas: Optional list of metadatas associated with the texts.\n            index_name: Name of the Elasticsearch index to create.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-22", "text": "index_name: Name of the Elasticsearch index to create.\n            es_url: URL of the Elasticsearch instance to connect to.\n            cloud_id: Cloud ID of the Elasticsearch instance to connect to.\n            es_user: Username to use when connecting to Elasticsearch.\n            es_password: Password to use when connecting to Elasticsearch.\n            es_api_key: API key to use when connecting to Elasticsearch.\n            es_connection: Optional pre-existing Elasticsearch connection.\n            vector_query_field: Optional. Name of the field to\n                                store the embedding vectors in.\n            query_field: Optional. Name of the field to store the texts in.\n            distance_strategy: Optional. Name of the distance\n                                strategy to use. Defaults to \"COSINE\".\n                                can be one of \"COSINE\",\n                                \"EUCLIDEAN_DISTANCE\", \"DOT_PRODUCT\".\n            bulk_kwargs: Optional. Additional arguments to pass to\n                        Elasticsearch bulk.\n        \"\"\"\n        elasticsearchStore = ElasticsearchStore._create_cls_from_kwargs(\n            embedding=embedding, **kwargs\n        )\n        # Encode the provided texts and add them to the newly created index.\n        elasticsearchStore.add_texts(\n            texts, metadatas=metadatas, bulk_kwargs=bulk_kwargs\n        )\n        return elasticsearchStore\n    @staticmethod\n    def _create_cls_from_kwargs(\n        embedding: Optional[Embeddings] = None, **kwargs: Any\n    ) -> \"ElasticsearchStore\":\n        index_name = kwargs.get(\"index_name\")\n        if index_name is None:\n            raise ValueError(\"Please provide an index_name.\")\n        es_connection = kwargs.get(\"es_connection\")\n        es_cloud_id = kwargs.get(\"es_cloud_id\")\n        es_url = kwargs.get(\"es_url\")\n        es_user = kwargs.get(\"es_user\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-23", "text": "es_user = kwargs.get(\"es_user\")\n        es_password = kwargs.get(\"es_password\")\n        es_api_key = kwargs.get(\"es_api_key\")\n        vector_query_field = kwargs.get(\"vector_query_field\")\n        query_field = kwargs.get(\"query_field\")\n        distance_strategy = kwargs.get(\"distance_strategy\")\n        strategy = kwargs.get(\"strategy\", ElasticsearchStore.ApproxRetrievalStrategy())\n        optional_args = {}\n        if vector_query_field is not None:\n            optional_args[\"vector_query_field\"] = vector_query_field\n        if query_field is not None:\n            optional_args[\"query_field\"] = query_field\n        return ElasticsearchStore(\n            index_name=index_name,\n            embedding=embedding,\n            es_url=es_url,\n            es_connection=es_connection,\n            es_cloud_id=es_cloud_id,\n            es_user=es_user,\n            es_password=es_password,\n            es_api_key=es_api_key,\n            strategy=strategy,\n            distance_strategy=distance_strategy,\n            **optional_args,\n        )\n[docs]    @classmethod\n    def from_documents(\n        cls,\n        documents: List[Document],\n        embedding: Optional[Embeddings] = None,\n        bulk_kwargs: Optional[Dict] = None,\n        **kwargs: Any,\n    ) -> \"ElasticsearchStore\":\n        \"\"\"Construct ElasticsearchStore wrapper from documents.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import ElasticsearchStore\n                from langchain.embeddings.openai import OpenAIEmbeddings\n                db = ElasticsearchStore.from_documents(\n                    texts,\n                    embeddings,\n                    index_name=\"langchain-demo\",\n                    es_url=\"http://localhost:9200\"\n                )\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-24", "text": "es_url=\"http://localhost:9200\"\n                )\n        Args:\n            texts: List of texts to add to the Elasticsearch index.\n            embedding: Embedding function to use to embed the texts.\n                      Do not provide if using a strategy\n                      that doesn't require inference.\n            metadatas: Optional list of metadatas associated with the texts.\n            index_name: Name of the Elasticsearch index to create.\n            es_url: URL of the Elasticsearch instance to connect to.\n            cloud_id: Cloud ID of the Elasticsearch instance to connect to.\n            es_user: Username to use when connecting to Elasticsearch.\n            es_password: Password to use when connecting to Elasticsearch.\n            es_api_key: API key to use when connecting to Elasticsearch.\n            es_connection: Optional pre-existing Elasticsearch connection.\n            vector_query_field: Optional. Name of the field\n                                to store the embedding vectors in.\n            query_field: Optional. Name of the field to store the texts in.\n            bulk_kwargs: Optional. Additional arguments to pass to\n                        Elasticsearch bulk.\n        \"\"\"\n        elasticsearchStore = ElasticsearchStore._create_cls_from_kwargs(\n            embedding=embedding, **kwargs\n        )\n        # Encode the provided texts and add them to the newly created index.\n        elasticsearchStore.add_documents(documents, bulk_kwargs=bulk_kwargs)\n        return elasticsearchStore\n[docs]    @staticmethod\n    def ExactRetrievalStrategy() -> \"ExactRetrievalStrategy\":\n        \"\"\"Used to perform brute force / exact\n        nearest neighbor search via script_score.\"\"\"\n        return ExactRetrievalStrategy()\n[docs]    @staticmethod\n    def ApproxRetrievalStrategy(\n        query_model_id: Optional[str] = None,\n        hybrid: Optional[bool] = False,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-25", "text": "hybrid: Optional[bool] = False,\n        rrf: Optional[Union[dict, bool]] = True,\n    ) -> \"ApproxRetrievalStrategy\":\n        \"\"\"Used to perform approximate nearest neighbor search\n        using the HNSW algorithm.\n        At build index time, this strategy will create a\n        dense vector field in the index and store the\n        embedding vectors in the index.\n        At query time, the text will either be embedded using the\n        provided embedding function or the query_model_id\n        will be used to embed the text using the model\n        deployed to Elasticsearch.\n        if query_model_id is used, do not provide an embedding function.\n        Args:\n            query_model_id: Optional. ID of the model to use to\n                            embed the query text within the stack. Requires\n                            embedding model to be deployed to Elasticsearch.\n            hybrid: Optional. If True, will perform a hybrid search\n                    using both the knn query and a text query.\n                    Defaults to False.\n            rrf: Optional. rrf is Reciprocal Rank Fusion.\n                 When `hybrid` is True,\n                    and `rrf` is True, then rrf: {}.\n                    and `rrf` is False, then rrf is omitted.\n                    and isinstance(rrf, dict) is True, then pass in the dict values.\n                 rrf could be passed for adjusting 'rank_constant' and 'window_size'.\n        \"\"\"\n        return ApproxRetrievalStrategy(\n            query_model_id=query_model_id, hybrid=hybrid, rrf=rrf\n        )\n[docs]    @staticmethod\n    def SparseVectorRetrievalStrategy(\n        model_id: Optional[str] = None,\n    ) -> \"SparseRetrievalStrategy\":\n        \"\"\"Used to perform sparse vector search via text_expansion.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "deda41dbc8c5-26", "text": "\"\"\"Used to perform sparse vector search via text_expansion.\n        Used for when you want to use ELSER model to perform document search.\n        At build index time, this strategy will create a pipeline that\n        will embed the text using the ELSER model and store the\n        resulting tokens in the index.\n        At query time, the text will be embedded using the ELSER\n        model and the resulting tokens will be used to\n        perform a text_expansion query.\n        Args:\n            model_id: Optional. Default is \".elser_model_1\".\n                    ID of the model to use to embed the query text\n                    within the stack. Requires embedding model to be\n                    deployed to Elasticsearch.\n        \"\"\"\n        return SparseRetrievalStrategy(model_id=model_id)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html"}
{"id": "924dcd67ade9-0", "text": "Source code for langchain.vectorstores.vald\n\"\"\"Wrapper around Vald vector database.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Iterable, List, Optional, Tuple, Type\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\n[docs]class Vald(VectorStore):\n    \"\"\"Wrapper around Vald vector database.\n    To use, you should have the ``vald-client-python`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings import HuggingFaceEmbeddings\n            from langchain.vectorstores import Vald\n            texts = ['foo', 'bar', 'baz']\n            vald = Vald.from_texts(\n                texts=texts,\n                embedding=HuggingFaceEmbeddings(),\n                host=\"localhost\",\n                port=8080,\n                skip_strict_exist_check=False,\n             )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        host: str = \"localhost\",\n        port: int = 8080,\n        grpc_options: Tuple = (\n            (\"grpc.keepalive_time_ms\", 1000 * 10),\n            (\"grpc.keepalive_timeout_ms\", 1000 * 10),\n        ),\n    ):\n        self._embedding = embedding\n        self.target = host + \":\" + str(port)\n        self.grpc_options = grpc_options\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return self._embedding\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html"}
{"id": "924dcd67ade9-1", "text": "metadatas: Optional[List[dict]] = None,\n        skip_strict_exist_check: bool = False,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"\n        Args:\n            skip_strict_exist_check: Deprecated. This is not used basically.\n        \"\"\"\n        try:\n            import grpc\n            from vald.v1.payload import payload_pb2\n            from vald.v1.vald import upsert_pb2_grpc\n        except ImportError:\n            raise ValueError(\n                \"Could not import vald-client-python python package. \"\n                \"Please install it with `pip install vald-client-python`.\"\n            )\n        channel = grpc.insecure_channel(self.target, options=self.grpc_options)\n        # Depending on the network quality,\n        # it is necessary to wait for ChannelConnectivity.READY.\n        # _ = grpc.channel_ready_future(channel).result(timeout=10)\n        stub = upsert_pb2_grpc.UpsertStub(channel)\n        cfg = payload_pb2.Upsert.Config(skip_strict_exist_check=skip_strict_exist_check)\n        ids = []\n        embs = self._embedding.embed_documents(list(texts))\n        for text, emb in zip(texts, embs):\n            vec = payload_pb2.Object.Vector(id=text, vector=emb)\n            res = stub.Upsert(payload_pb2.Upsert.Request(vector=vec, config=cfg))\n            ids.append(res.uuid)\n        channel.close()\n        return ids\n[docs]    def delete(\n        self,\n        ids: Optional[List[str]] = None,\n        skip_strict_exist_check: bool = False,\n        **kwargs: Any,\n    ) -> Optional[bool]:\n        \"\"\"\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html"}
{"id": "924dcd67ade9-2", "text": ") -> Optional[bool]:\n        \"\"\"\n        Args:\n            skip_strict_exist_check: Deprecated. This is not used basically.\n        \"\"\"\n        try:\n            import grpc\n            from vald.v1.payload import payload_pb2\n            from vald.v1.vald import remove_pb2_grpc\n        except ImportError:\n            raise ValueError(\n                \"Could not import vald-client-python python package. \"\n                \"Please install it with `pip install vald-client-python`.\"\n            )\n        if ids is None:\n            raise ValueError(\"No ids provided to delete\")\n        channel = grpc.insecure_channel(self.target, options=self.grpc_options)\n        # Depending on the network quality,\n        # it is necessary to wait for ChannelConnectivity.READY.\n        # _ = grpc.channel_ready_future(channel).result(timeout=10)\n        stub = remove_pb2_grpc.RemoveStub(channel)\n        cfg = payload_pb2.Remove.Config(skip_strict_exist_check=skip_strict_exist_check)\n        for _id in ids:\n            oid = payload_pb2.Object.ID(id=_id)\n            _ = stub.Remove(payload_pb2.Remove.Request(id=oid, config=cfg))\n        channel.close()\n        return True\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        radius: float = -1.0,\n        epsilon: float = 0.01,\n        timeout: int = 3000000000,\n        **kwargs: Any,\n    ) -> List[Document]:\n        docs_and_scores = self.similarity_search_with_score(\n            query, k, radius, epsilon, timeout\n        )\n        docs = []\n        for doc, _ in docs_and_scores:\n            docs.append(doc)\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html"}
{"id": "924dcd67ade9-3", "text": "docs.append(doc)\n        return docs\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        radius: float = -1.0,\n        epsilon: float = 0.01,\n        timeout: int = 3000000000,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        emb = self._embedding.embed_query(query)\n        docs_and_scores = self.similarity_search_with_score_by_vector(\n            emb, k, radius, epsilon, timeout\n        )\n        return docs_and_scores\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        radius: float = -1.0,\n        epsilon: float = 0.01,\n        timeout: int = 3000000000,\n        **kwargs: Any,\n    ) -> List[Document]:\n        docs_and_scores = self.similarity_search_with_score_by_vector(\n            embedding, k, radius, epsilon, timeout\n        )\n        docs = []\n        for doc, _ in docs_and_scores:\n            docs.append(doc)\n        return docs\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        radius: float = -1.0,\n        epsilon: float = 0.01,\n        timeout: int = 3000000000,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        try:\n            import grpc\n            from vald.v1.payload import payload_pb2\n            from vald.v1.vald import search_pb2_grpc", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html"}
{"id": "924dcd67ade9-4", "text": "from vald.v1.vald import search_pb2_grpc\n        except ImportError:\n            raise ValueError(\n                \"Could not import vald-client-python python package. \"\n                \"Please install it with `pip install vald-client-python`.\"\n            )\n        channel = grpc.insecure_channel(self.target, options=self.grpc_options)\n        # Depending on the network quality,\n        # it is necessary to wait for ChannelConnectivity.READY.\n        # _ = grpc.channel_ready_future(channel).result(timeout=10)\n        stub = search_pb2_grpc.SearchStub(channel)\n        cfg = payload_pb2.Search.Config(\n            num=k, radius=radius, epsilon=epsilon, timeout=timeout\n        )\n        res = stub.Search(payload_pb2.Search.Request(vector=embedding, config=cfg))\n        docs_and_scores = []\n        for result in res.results:\n            docs_and_scores.append((Document(page_content=result.id), result.distance))\n        channel.close()\n        return docs_and_scores\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        radius: float = -1.0,\n        epsilon: float = 0.01,\n        timeout: int = 3000000000,\n        **kwargs: Any,\n    ) -> List[Document]:\n        emb = self._embedding.embed_query(query)\n        docs = self.max_marginal_relevance_search_by_vector(\n            emb,\n            k=k,\n            fetch_k=fetch_k,\n            radius=radius,\n            epsilon=epsilon,\n            timeout=timeout,\n            lambda_mult=lambda_mult,\n        )\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html"}
{"id": "924dcd67ade9-5", "text": "timeout=timeout,\n            lambda_mult=lambda_mult,\n        )\n        return docs\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        radius: float = -1.0,\n        epsilon: float = 0.01,\n        timeout: int = 3000000000,\n        **kwargs: Any,\n    ) -> List[Document]:\n        try:\n            import grpc\n            from vald.v1.payload import payload_pb2\n            from vald.v1.vald import object_pb2_grpc\n        except ImportError:\n            raise ValueError(\n                \"Could not import vald-client-python python package. \"\n                \"Please install it with `pip install vald-client-python`.\"\n            )\n        channel = grpc.insecure_channel(self.target, options=self.grpc_options)\n        # Depending on the network quality,\n        # it is necessary to wait for ChannelConnectivity.READY.\n        # _ = grpc.channel_ready_future(channel).result(timeout=10)\n        stub = object_pb2_grpc.ObjectStub(channel)\n        docs_and_scores = self.similarity_search_with_score_by_vector(\n            embedding, fetch_k=fetch_k, radius=radius, epsilon=epsilon, timeout=timeout\n        )\n        docs = []\n        embs = []\n        for doc, _ in docs_and_scores:\n            vec = stub.GetObject(\n                payload_pb2.Object.VectorRequest(\n                    id=payload_pb2.Object.ID(id=doc.page_content)\n                )\n            )\n            embs.append(vec.vector)\n            docs.append(doc)\n        mmr = maximal_marginal_relevance(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html"}
{"id": "924dcd67ade9-6", "text": "docs.append(doc)\n        mmr = maximal_marginal_relevance(\n            np.array(embedding),\n            embs,\n            lambda_mult=lambda_mult,\n            k=k,\n        )\n        channel.close()\n        return [docs[i] for i in mmr]\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[Vald],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        host: str = \"localhost\",\n        port: int = 8080,\n        grpc_options: Tuple = (\n            (\"grpc.keepalive_time_ms\", 1000 * 10),\n            (\"grpc.keepalive_timeout_ms\", 1000 * 10),\n        ),\n        skip_strict_exist_check: bool = False,\n        **kwargs: Any,\n    ) -> Vald:\n        \"\"\"\n        Args:\n            skip_strict_exist_check: Deprecated. This is not used basically.\n        \"\"\"\n        vald = cls(\n            embedding=embedding,\n            host=host,\n            port=port,\n            grpc_options=grpc_options,\n            **kwargs,\n        )\n        vald.add_texts(\n            texts=texts,\n            metadatas=metadatas,\n            skip_strict_exist_check=skip_strict_exist_check,\n        )\n        return vald\n\"\"\"We will support if there are any requests.\"\"\"\n#    async def aadd_texts(\n#        self,\n#        texts: Iterable[str],\n#        metadatas: Optional[List[dict]] = None,\n#        **kwargs: Any,\n#    ) -> List[str]:\n#        pass\n#", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html"}
{"id": "924dcd67ade9-7", "text": "#    ) -> List[str]:\n#        pass\n#\n#    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n#        pass\n#\n#    def _similarity_search_with_relevance_scores(\n#        self,\n#        query: str,\n#        k: int = 4,\n#        **kwargs: Any,\n#    ) -> List[Tuple[Document, float]]:\n#        pass\n#\n#    def similarity_search_with_relevance_scores(\n#        self,\n#        query: str,\n#        k: int = 4,\n#        **kwargs: Any,\n#    ) -> List[Tuple[Document, float]]:\n#        pass\n#\n#    async def amax_marginal_relevance_search_by_vector(\n#        self,\n#        embedding: List[float],\n#        k: int = 4,\n#        fetch_k: int = 20,\n#        lambda_mult: float = 0.5,\n#        **kwargs: Any,\n#    ) -> List[Document]:\n#        pass\n#\n#    @classmethod\n#    async def afrom_texts(\n#        cls: Type[VST],\n#        texts: List[str],\n#        embedding: Embeddings,\n#        metadatas: Optional[List[dict]] = None,\n#        **kwargs: Any,\n#    ) -> VST:\n#        pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vald.html"}
{"id": "9fe3a1ab7e46-0", "text": "Source code for langchain.vectorstores.marqo\nfrom __future__ import annotations\nimport json\nimport uuid\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n    Union,\n)\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nif TYPE_CHECKING:\n    import marqo\n[docs]class Marqo(VectorStore):\n    \"\"\"`Marqo` vector store.\n    Marqo indexes have their own models associated with them to generate your\n    embeddings. This means that you can selected from a range of different models\n    and also use CLIP models to create multimodal indexes\n    with images and text together.\n    Marqo also supports more advanced queries with multiple weighted terms, see See\n    https://docs.marqo.ai/latest/#searching-using-weights-in-queries.\n    This class can flexibly take strings or dictionaries for weighted queries\n    in its similarity search methods.\n    To use, you should have the `marqo` python package installed, you can do this with\n    `pip install marqo`.\n    Example:\n        .. code-block:: python\n            import marqo\n            from langchain.vectorstores import Marqo\n            client = marqo.Client(url=os.environ[\"MARQO_URL\"], ...)\n            vectorstore = Marqo(client, index_name)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        client: marqo.Client,\n        index_name: str,\n        add_documents_settings: Optional[Dict[str, Any]] = None,\n        searchable_attributes: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html"}
{"id": "9fe3a1ab7e46-1", "text": "searchable_attributes: Optional[List[str]] = None,\n        page_content_builder: Optional[Callable[[Dict[str, Any]], str]] = None,\n    ):\n        \"\"\"Initialize with Marqo client.\"\"\"\n        try:\n            import marqo\n        except ImportError:\n            raise ImportError(\n                \"Could not import marqo python package. \"\n                \"Please install it with `pip install marqo`.\"\n            )\n        if not isinstance(client, marqo.Client):\n            raise ValueError(\n                f\"client should be an instance of marqo.Client, got {type(client)}\"\n            )\n        self._client = client\n        self._index_name = index_name\n        self._add_documents_settings = (\n            {} if add_documents_settings is None else add_documents_settings\n        )\n        self._searchable_attributes = searchable_attributes\n        self.page_content_builder = page_content_builder\n        self.tensor_fields = [\"text\"]\n        self._document_batch_size = 1024\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return None\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Upload texts with metadata (properties) to Marqo.\n        You can either have marqo generate ids for each document or you can provide\n        your own by including a \"_id\" field in the metadata objects.\n        Args:\n            texts (Iterable[str]): am iterator of texts - assumed to preserve an\n            order that matches the metadatas.\n            metadatas (Optional[List[dict]], optional): a list of metadatas.\n        Raises:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html"}
{"id": "9fe3a1ab7e46-2", "text": "Raises:\n            ValueError: if metadatas is provided and the number of metadatas differs\n            from the number of texts.\n        Returns:\n            List[str]: The list of ids that were added.\n        \"\"\"\n        if self._client.index(self._index_name).get_settings()[\"index_defaults\"][\n            \"treat_urls_and_pointers_as_images\"\n        ]:\n            raise ValueError(\n                \"Marqo.add_texts is disabled for multimodal indexes. To add documents \"\n                \"with a multimodal index use the Python client for Marqo directly.\"\n            )\n        documents: List[Dict[str, str]] = []\n        num_docs = 0\n        for i, text in enumerate(texts):\n            doc = {\n                \"text\": text,\n                \"metadata\": json.dumps(metadatas[i]) if metadatas else json.dumps({}),\n            }\n            documents.append(doc)\n            num_docs += 1\n        ids = []\n        for i in range(0, num_docs, self._document_batch_size):\n            response = self._client.index(self._index_name).add_documents(\n                documents[i : i + self._document_batch_size],\n                tensor_fields=self.tensor_fields,\n                **self._add_documents_settings,\n            )\n            if response[\"errors\"]:\n                err_msg = (\n                    f\"Error in upload for documents in index range [{i},\"\n                    f\"{i + self._document_batch_size}], \"\n                    f\"check Marqo logs.\"\n                )\n                raise RuntimeError(err_msg)\n            ids += [item[\"_id\"] for item in response[\"items\"]]\n        return ids\n[docs]    def similarity_search(\n        self,\n        query: Union[str, Dict[str, float]],\n        k: int = 4,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html"}
{"id": "9fe3a1ab7e46-3", "text": "k: int = 4,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Search the marqo index for the most similar documents.\n        Args:\n            query (Union[str, Dict[str, float]]): The query for the search, either\n            as a string or a weighted query.\n            k (int, optional): The number of documents to return. Defaults to 4.\n        Returns:\n            List[Document]: k documents ordered from best to worst match.\n        \"\"\"\n        results = self.marqo_similarity_search(query=query, k=k)\n        documents = self._construct_documents_from_results_without_score(results)\n        return documents\n[docs]    def similarity_search_with_score(\n        self,\n        query: Union[str, Dict[str, float]],\n        k: int = 4,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return documents from Marqo that are similar to the query as well\n        as their scores.\n        Args:\n            query (str): The query to search with, either as a string or a weighted\n            query.\n            k (int, optional): The number of documents to return. Defaults to 4.\n        Returns:\n            List[Tuple[Document, float]]: The matching documents and their scores,\n            ordered by descending score.\n        \"\"\"\n        results = self.marqo_similarity_search(query=query, k=k)\n        scored_documents = self._construct_documents_from_results_with_score(results)\n        return scored_documents\n[docs]    def bulk_similarity_search(\n        self,\n        queries: Iterable[Union[str, Dict[str, float]]],\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[List[Document]]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html"}
{"id": "9fe3a1ab7e46-4", "text": "**kwargs: Any,\n    ) -> List[List[Document]]:\n        \"\"\"Search the marqo index for the most similar documents in bulk with multiple\n        queries.\n        Args:\n            queries (Iterable[Union[str, Dict[str, float]]]): An iterable of queries to\n            execute in bulk, queries in the list can be strings or dictionaries of\n            weighted queries.\n            k (int, optional): The number of documents to return for each query.\n            Defaults to 4.\n        Returns:\n            List[List[Document]]: A list of results for each query.\n        \"\"\"\n        bulk_results = self.marqo_bulk_similarity_search(queries=queries, k=k)\n        bulk_documents: List[List[Document]] = []\n        for results in bulk_results[\"result\"]:\n            documents = self._construct_documents_from_results_without_score(results)\n            bulk_documents.append(documents)\n        return bulk_documents\n[docs]    def bulk_similarity_search_with_score(\n        self,\n        queries: Iterable[Union[str, Dict[str, float]]],\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[List[Tuple[Document, float]]]:\n        \"\"\"Return documents from Marqo that are similar to the query as well as\n        their scores using a batch of queries.\n        Args:\n            query (Iterable[Union[str, Dict[str, float]]]): An iterable of queries\n            to execute in bulk, queries in the list can be strings or dictionaries\n            of weighted queries.\n            k (int, optional): The number of documents to return. Defaults to 4.\n        Returns:\n            List[Tuple[Document, float]]: A list of lists of the matching\n            documents and their scores for each query\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html"}
{"id": "9fe3a1ab7e46-5", "text": "documents and their scores for each query\n        \"\"\"\n        bulk_results = self.marqo_bulk_similarity_search(queries=queries, k=k)\n        bulk_documents: List[List[Tuple[Document, float]]] = []\n        for results in bulk_results[\"result\"]:\n            documents = self._construct_documents_from_results_with_score(results)\n            bulk_documents.append(documents)\n        return bulk_documents\n    def _construct_documents_from_results_with_score(\n        self, results: Dict[str, List[Dict[str, str]]]\n    ) -> List[Tuple[Document, Any]]:\n        \"\"\"Helper to convert Marqo results into documents.\n        Args:\n            results (List[dict]): A marqo results object with the 'hits'.\n            include_scores (bool, optional): Include scores alongside documents.\n            Defaults to False.\n        Returns:\n            Union[List[Document], List[Tuple[Document, float]]]: The documents or\n            document score pairs if `include_scores` is true.\n        \"\"\"\n        documents: List[Tuple[Document, Any]] = []\n        for res in results[\"hits\"]:\n            if self.page_content_builder is None:\n                text = res[\"text\"]\n            else:\n                text = self.page_content_builder(res)\n            metadata = json.loads(res.get(\"metadata\", \"{}\"))\n            documents.append(\n                (Document(page_content=text, metadata=metadata), res[\"_score\"])\n            )\n        return documents\n    def _construct_documents_from_results_without_score(\n        self, results: Dict[str, List[Dict[str, str]]]\n    ) -> List[Document]:\n        \"\"\"Helper to convert Marqo results into documents.\n        Args:\n            results (List[dict]): A marqo results object with the 'hits'.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html"}
{"id": "9fe3a1ab7e46-6", "text": "results (List[dict]): A marqo results object with the 'hits'.\n            include_scores (bool, optional): Include scores alongside documents.\n            Defaults to False.\n        Returns:\n            Union[List[Document], List[Tuple[Document, float]]]: The documents or\n            document score pairs if `include_scores` is true.\n        \"\"\"\n        documents: List[Document] = []\n        for res in results[\"hits\"]:\n            if self.page_content_builder is None:\n                text = res[\"text\"]\n            else:\n                text = self.page_content_builder(res)\n            metadata = json.loads(res.get(\"metadata\", \"{}\"))\n            documents.append(Document(page_content=text, metadata=metadata))\n        return documents\n[docs]    def marqo_similarity_search(\n        self,\n        query: Union[str, Dict[str, float]],\n        k: int = 4,\n    ) -> Dict[str, List[Dict[str, str]]]:\n        \"\"\"Return documents from Marqo exposing Marqo's output directly\n        Args:\n            query (str): The query to search with.\n            k (int, optional): The number of documents to return. Defaults to 4.\n        Returns:\n            List[Dict[str, Any]]: This hits from marqo.\n        \"\"\"\n        results = self._client.index(self._index_name).search(\n            q=query, searchable_attributes=self._searchable_attributes, limit=k\n        )\n        return results\n[docs]    def marqo_bulk_similarity_search(\n        self, queries: Iterable[Union[str, Dict[str, float]]], k: int = 4\n    ) -> Dict[str, List[Dict[str, List[Dict[str, str]]]]]:\n        \"\"\"Return documents from Marqo using a bulk search, exposes Marqo's", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html"}
{"id": "9fe3a1ab7e46-7", "text": "\"\"\"Return documents from Marqo using a bulk search, exposes Marqo's\n        output directly\n        Args:\n            queries (Iterable[Union[str, Dict[str, float]]]): A list of queries.\n            k (int, optional): The number of documents to return for each query.\n            Defaults to 4.\n        Returns:\n            Dict[str, Dict[List[Dict[str, Dict[str, Any]]]]]: A bulk search results\n            object\n        \"\"\"\n        bulk_results = {\n            \"result\": [\n                self._client.index(self._index_name).search(\n                    q=query, searchable_attributes=self._searchable_attributes, limit=k\n                )\n                for query in queries\n            ]\n        }\n        return bulk_results\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[Marqo],\n        documents: List[Document],\n        embedding: Union[Embeddings, None] = None,\n        **kwargs: Any,\n    ) -> Marqo:\n        \"\"\"Return VectorStore initialized from documents. Note that Marqo does not\n        need embeddings, we retain the parameter to adhere to the Liskov substitution\n        principle.\n        Args:\n            documents (List[Document]): Input documents\n            embedding (Any, optional): Embeddings (not required). Defaults to None.\n        Returns:\n            VectorStore: A Marqo vectorstore\n        \"\"\"\n        texts = [d.page_content for d in documents]\n        metadatas = [d.metadata for d in documents]\n        return cls.from_texts(texts, metadatas=metadatas, **kwargs)\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Any = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html"}
{"id": "9fe3a1ab7e46-8", "text": "cls,\n        texts: List[str],\n        embedding: Any = None,\n        metadatas: Optional[List[dict]] = None,\n        index_name: str = \"\",\n        url: str = \"http://localhost:8882\",\n        api_key: str = \"\",\n        add_documents_settings: Optional[Dict[str, Any]] = None,\n        searchable_attributes: Optional[List[str]] = None,\n        page_content_builder: Optional[Callable[[Dict[str, str]], str]] = None,\n        index_settings: Optional[Dict[str, Any]] = None,\n        verbose: bool = True,\n        **kwargs: Any,\n    ) -> Marqo:\n        \"\"\"Return Marqo initialized from texts. Note that Marqo does not need\n        embeddings, we retain the parameter to adhere to the Liskov\n        substitution principle.\n        This is a quick way to get started with marqo - simply provide your texts and\n        metadatas and this will create an instance of the data store and index the\n        provided data.\n        To know the ids of your documents with this approach you will need to include\n        them in under the key \"_id\" in your metadatas for each text\n        Example:\n        .. code-block:: python\n                from langchain.vectorstores import Marqo\n                datastore = Marqo(texts=['text'], index_name='my-first-index',\n                url='http://localhost:8882')\n        Args:\n            texts (List[str]): A list of texts to index into marqo upon creation.\n            embedding (Any, optional): Embeddings (not required). Defaults to None.\n            index_name (str, optional): The name of the index to use, if none is\n            provided then one will be created with a UUID. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html"}
{"id": "9fe3a1ab7e46-9", "text": "provided then one will be created with a UUID. Defaults to None.\n            url (str, optional): The URL for Marqo. Defaults to \"http://localhost:8882\".\n            api_key (str, optional): The API key for Marqo. Defaults to \"\".\n            metadatas (Optional[List[dict]], optional): A list of metadatas, to\n            accompany the texts. Defaults to None.\n            this is only used when a new index is being created. Defaults to \"cpu\". Can\n            be \"cpu\" or \"cuda\".\n            add_documents_settings (Optional[Dict[str, Any]], optional): Settings\n            for adding documents, see\n            https://docs.marqo.ai/0.0.16/API-Reference/documents/#query-parameters.\n            Defaults to {}.\n            index_settings (Optional[Dict[str, Any]], optional): Index settings if\n            the index doesn't exist, see\n            https://docs.marqo.ai/0.0.16/API-Reference/indexes/#index-defaults-object.\n            Defaults to {}.\n        Returns:\n            Marqo: An instance of the Marqo vector store\n        \"\"\"\n        try:\n            import marqo\n        except ImportError:\n            raise ImportError(\n                \"Could not import marqo python package. \"\n                \"Please install it with `pip install marqo`.\"\n            )\n        if not index_name:\n            index_name = str(uuid.uuid4())\n        client = marqo.Client(url=url, api_key=api_key)\n        try:\n            client.create_index(index_name, settings_dict=index_settings or {})\n            if verbose:\n                print(f\"Created {index_name} successfully.\")\n        except Exception:\n            if verbose:\n                print(f\"Index {index_name} exists.\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html"}
{"id": "9fe3a1ab7e46-10", "text": "if verbose:\n                print(f\"Index {index_name} exists.\")\n        instance: Marqo = cls(\n            client,\n            index_name,\n            searchable_attributes=searchable_attributes,\n            add_documents_settings=add_documents_settings or {},\n            page_content_builder=page_content_builder,\n        )\n        instance.add_texts(texts, metadatas)\n        return instance\n[docs]    def get_indexes(self) -> List[Dict[str, str]]:\n        \"\"\"Helper to see your available indexes in marqo, useful if the\n        from_texts method was used without an index name specified\n        Returns:\n            List[Dict[str, str]]: The list of indexes\n        \"\"\"\n        return self._client.get_indexes()[\"results\"]\n[docs]    def get_number_of_documents(self) -> int:\n        \"\"\"Helper to see the number of documents in the index\n        Returns:\n            int: The number of documents\n        \"\"\"\n        return self._client.index(self._index_name).get_stats()[\"numberOfDocuments\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/marqo.html"}
{"id": "9f102ce8fba8-0", "text": "Source code for langchain.vectorstores.llm_rails\n\"\"\"Wrapper around LLMRails vector database.\"\"\"\nfrom __future__ import annotations\nimport json\nimport logging\nimport os\nimport uuid\nfrom typing import Any, Iterable, List, Optional, Tuple\nimport requests\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.vectorstores.base import VectorStore, VectorStoreRetriever\n[docs]class LLMRails(VectorStore):\n    \"\"\"Implementation of Vector Store using LLMRails.\n     See https://llmrails.com/\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import LLMRails\n            vectorstore = LLMRails(\n                api_key=llm_rails_api_key,\n                datastore_id=datastore_id\n            )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        datastore_id: Optional[str] = None,\n        api_key: Optional[str] = None,\n    ):\n        \"\"\"Initialize with LLMRails API.\"\"\"\n        self._datastore_id = datastore_id or os.environ.get(\"LLM_RAILS_DATASTORE_ID\")\n        self._api_key = api_key or os.environ.get(\"LLM_RAILS_API_KEY\")\n        if self._api_key is None:\n            logging.warning(\"Can't find Rails credentials in environment.\")\n        self._session = requests.Session()  # to reuse connections\n        self.datastore_id = datastore_id\n        self.base_url = \"https://api.llmrails.com/v1\"\n    def _get_post_headers(self) -> dict:\n        \"\"\"Returns headers that should be attached to each post request.\"\"\"\n        return {\"X-API-KEY\": self._api_key}\n[docs]    def add_texts(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html"}
{"id": "9f102ce8fba8-1", "text": "[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        names: List[str] = []\n        for text in texts:\n            doc_name = str(uuid.uuid4())\n            response = self._session.post(\n                f\"{self.base_url}/datastores/{self._datastore_id}/text\",\n                json={\"name\": doc_name, \"text\": text},\n                verify=True,\n                headers=self._get_post_headers(),\n            )\n            if response.status_code != 200:\n                logging.error(\n                    f\"Create request failed for doc_name = {doc_name} with status code \"\n                    f\"{response.status_code}, reason {response.reason}, text \"\n                    f\"{response.text}\"\n                )\n                return names\n            names.append(doc_name)\n        return names\n[docs]    def add_files(\n        self,\n        files_list: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> bool:\n        \"\"\"\n        LLMRails provides a way to add documents directly via our API where\n        pre-processing and chunking occurs internally in an optimal way\n        This method provides a way to use that API in LangChain\n        Args:\n            files_list: Iterable of strings, each representing a local file path.\n                    Files could be text, HTML, PDF, markdown, doc/docx, ppt/pptx, etc.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html"}
{"id": "9f102ce8fba8-2", "text": "see API docs for full list\n        Returns:\n            List of ids associated with each of the files indexed\n        \"\"\"\n        files = []\n        for file in files_list:\n            if not os.path.exists(file):\n                logging.error(f\"File {file} does not exist, skipping\")\n                continue\n            files.append((\"file\", (os.path.basename(file), open(file, \"rb\"))))\n        response = self._session.post(\n            f\"{self.base_url}/datastores/{self._datastore_id}/file\",\n            files=files,\n            verify=True,\n            headers=self._get_post_headers(),\n        )\n        if response.status_code != 200:\n            logging.error(\n                f\"Create request failed for datastore = {self._datastore_id} \"\n                f\"with status code {response.status_code}, reason {response.reason}, \"\n                f\"text {response.text}\"\n            )\n            return False\n        return True\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 5\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return LLMRails documents most similar to query, along with scores.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 5 Max 10.\n            alpha: parameter for hybrid search .\n        Returns:\n            List of Documents most similar to the query and score for each.\n        \"\"\"\n        response = self._session.post(\n            headers=self._get_post_headers(),\n            url=f\"{self.base_url}/datastores/{self._datastore_id}/search\",\n            data=json.dumps({\"k\": k, \"text\": query}),\n            timeout=10,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html"}
{"id": "9f102ce8fba8-3", "text": "timeout=10,\n        )\n        if response.status_code != 200:\n            logging.error(\n                \"Query failed %s\",\n                f\"(code {response.status_code}, reason {response.reason}, details \"\n                f\"{response.text})\",\n            )\n            return []\n        results = response.json()[\"results\"]\n        docs = [\n            (\n                Document(\n                    page_content=x[\"text\"],\n                    metadata={\n                        key: value\n                        for key, value in x[\"metadata\"].items()\n                        if key != \"score\"\n                    },\n                ),\n                x[\"metadata\"][\"score\"],\n            )\n            for x in results\n        ]\n        return docs\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return LLMRails documents most similar to query, along with scores.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 5.\n        Returns:\n            List of Documents most similar to the query\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(query, k=k)\n        return [doc for doc, _ in docs_and_scores]\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Optional[Embeddings] = None,\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> LLMRails:\n        \"\"\"Construct LLMRails wrapper from raw documents.\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import LLMRails", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html"}
{"id": "9f102ce8fba8-4", "text": ".. code-block:: python\n                from langchain.vectorstores import LLMRails\n                llm_rails = LLMRails.from_texts(\n                    texts,\n                    datastore_id=datastore_id,\n                    api_key=llm_rails_api_key\n                )\n        \"\"\"\n        # Note: LLMRails generates its own embeddings, so we ignore the provided\n        # embeddings (required by interface)\n        llm_rails = cls(**kwargs)\n        llm_rails.add_texts(texts)\n        return llm_rails\n[docs]    def as_retriever(self, **kwargs: Any) -> LLMRailsRetriever:\n        return LLMRailsRetriever(vectorstore=self, **kwargs)\n[docs]class LLMRailsRetriever(VectorStoreRetriever):\n    \"\"\"Retriever for LLMRails.\"\"\"\n    vectorstore: LLMRails\n    search_kwargs: dict = Field(default_factory=lambda: {\"k\": 5})\n    \"\"\"Search params.\n        k: Number of Documents to return. Defaults to 5.\n        alpha: parameter for hybrid search .\n    \"\"\"\n[docs]    def add_texts(self, texts: List[str]) -> None:\n        \"\"\"Add text to the datastore.\n        Args:\n            texts (List[str]): The text\n        \"\"\"\n        self.vectorstore.add_texts(texts)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/llm_rails.html"}
{"id": "b57c5a0a0ddc-0", "text": "Source code for langchain.vectorstores.milvus\nfrom __future__ import annotations\nimport logging\nfrom typing import Any, Iterable, List, Optional, Tuple, Union\nfrom uuid import uuid4\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nlogger = logging.getLogger(__name__)\nDEFAULT_MILVUS_CONNECTION = {\n    \"host\": \"localhost\",\n    \"port\": \"19530\",\n    \"user\": \"\",\n    \"password\": \"\",\n    \"secure\": False,\n}\n[docs]class Milvus(VectorStore):\n    \"\"\"`Milvus` vector store.\n    You need to install `pymilvus` and run Milvus.\n    See the following documentation for how to run a Milvus instance:\n    https://milvus.io/docs/install_standalone-docker.md\n    If looking for a hosted Milvus, take a look at this documentation:\n    https://zilliz.com/cloud and make use of the Zilliz vectorstore found in\n    this project.\n    IF USING L2/IP metric, IT IS HIGHLY SUGGESTED TO NORMALIZE YOUR DATA.\n    Args:\n        embedding_function (Embeddings): Function used to embed the text.\n        collection_name (str): Which Milvus collection to use. Defaults to\n            \"LangChainCollection\".\n        connection_args (Optional[dict[str, any]]): The connection args used for\n            this class comes in the form of a dict.\n        consistency_level (str): The consistency level to use for a collection.\n            Defaults to \"Session\".\n        index_params (Optional[dict]): Which index params to use. Defaults to", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-1", "text": "index_params (Optional[dict]): Which index params to use. Defaults to\n            HNSW/AUTOINDEX depending on service.\n        search_params (Optional[dict]): Which search params to use. Defaults to\n            default of index.\n        drop_old (Optional[bool]): Whether to drop the current collection. Defaults\n            to False.\n        primary_field (str): Name of the primary key field. Defaults to \"pk\".\n        text_field (str): Name of the text field. Defaults to \"text\".\n        vector_field (str): Name of the vector field. Defaults to \"vector\".\n    The connection args used for this class comes in the form of a dict,\n    here are a few of the options:\n        address (str): The actual address of Milvus\n            instance. Example address: \"localhost:19530\"\n        uri (str): The uri of Milvus instance. Example uri:\n            \"http://randomwebsite:19530\",\n            \"tcp:foobarsite:19530\",\n            \"https://ok.s3.south.com:19530\".\n        host (str): The host of Milvus instance. Default at \"localhost\",\n            PyMilvus will fill in the default host if only port is provided.\n        port (str/int): The port of Milvus instance. Default at 19530, PyMilvus\n            will fill in the default port if only host is provided.\n        user (str): Use which user to connect to Milvus instance. If user and\n            password are provided, we will add related header in every RPC call.\n        password (str): Required when user is provided. The password\n            corresponding to the user.\n        secure (bool): Default is false. If set to true, tls will be enabled.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-2", "text": "secure (bool): Default is false. If set to true, tls will be enabled.\n        client_key_path (str): If use tls two-way authentication, need to\n            write the client.key path.\n        client_pem_path (str): If use tls two-way authentication, need to\n            write the client.pem path.\n        ca_pem_path (str): If use tls two-way authentication, need to write\n            the ca.pem path.\n        server_pem_path (str): If use tls one-way authentication, need to\n            write the server.pem path.\n        server_name (str): If use tls, need to write the common name.\n    Example:\n        .. code-block:: python\n        from langchain.vectorstores import Milvus\n        from langchain.embeddings import OpenAIEmbeddings\n        embedding = OpenAIEmbeddings()\n        # Connect to a milvus instance on localhost\n        milvus_store = Milvus(\n            embedding_function = Embeddings,\n            collection_name = \"LangChainCollection\",\n            drop_old = True,\n        )\n    Raises:\n        ValueError: If the pymilvus python package is not installed.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding_function: Embeddings,\n        collection_name: str = \"LangChainCollection\",\n        connection_args: Optional[dict[str, Any]] = None,\n        consistency_level: str = \"Session\",\n        index_params: Optional[dict] = None,\n        search_params: Optional[dict] = None,\n        drop_old: Optional[bool] = False,\n        *,\n        primary_field: str = \"pk\",\n        text_field: str = \"text\",\n        vector_field: str = \"vector\",\n    ):\n        \"\"\"Initialize the Milvus vector store.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-3", "text": "):\n        \"\"\"Initialize the Milvus vector store.\"\"\"\n        try:\n            from pymilvus import Collection, utility\n        except ImportError:\n            raise ValueError(\n                \"Could not import pymilvus python package. \"\n                \"Please install it with `pip install pymilvus`.\"\n            )\n        # Default search params when one is not provided.\n        self.default_search_params = {\n            \"IVF_FLAT\": {\"metric_type\": \"L2\", \"params\": {\"nprobe\": 10}},\n            \"IVF_SQ8\": {\"metric_type\": \"L2\", \"params\": {\"nprobe\": 10}},\n            \"IVF_PQ\": {\"metric_type\": \"L2\", \"params\": {\"nprobe\": 10}},\n            \"HNSW\": {\"metric_type\": \"L2\", \"params\": {\"ef\": 10}},\n            \"RHNSW_FLAT\": {\"metric_type\": \"L2\", \"params\": {\"ef\": 10}},\n            \"RHNSW_SQ\": {\"metric_type\": \"L2\", \"params\": {\"ef\": 10}},\n            \"RHNSW_PQ\": {\"metric_type\": \"L2\", \"params\": {\"ef\": 10}},\n            \"IVF_HNSW\": {\"metric_type\": \"L2\", \"params\": {\"nprobe\": 10, \"ef\": 10}},\n            \"ANNOY\": {\"metric_type\": \"L2\", \"params\": {\"search_k\": 10}},\n            \"AUTOINDEX\": {\"metric_type\": \"L2\", \"params\": {}},\n        }\n        self.embedding_func = embedding_function\n        self.collection_name = collection_name\n        self.index_params = index_params\n        self.search_params = search_params\n        self.consistency_level = consistency_level", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-4", "text": "self.search_params = search_params\n        self.consistency_level = consistency_level\n        # In order for a collection to be compatible, pk needs to be auto'id and int\n        self._primary_field = primary_field\n        # In order for compatibility, the text field will need to be called \"text\"\n        self._text_field = text_field\n        # In order for compatibility, the vector field needs to be called \"vector\"\n        self._vector_field = vector_field\n        self.fields: list[str] = []\n        # Create the connection to the server\n        if connection_args is None:\n            connection_args = DEFAULT_MILVUS_CONNECTION\n        self.alias = self._create_connection_alias(connection_args)\n        self.col: Optional[Collection] = None\n        # Grab the existing collection if it exists\n        if utility.has_collection(self.collection_name, using=self.alias):\n            self.col = Collection(\n                self.collection_name,\n                using=self.alias,\n            )\n        # If need to drop old, drop it\n        if drop_old and isinstance(self.col, Collection):\n            self.col.drop()\n            self.col = None\n        # Initialize the vector store\n        self._init()\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding_func\n    def _create_connection_alias(self, connection_args: dict) -> str:\n        \"\"\"Create the connection to the Milvus server.\"\"\"\n        from pymilvus import MilvusException, connections\n        # Grab the connection arguments that are used for checking existing connection\n        host: str = connection_args.get(\"host\", None)\n        port: Union[str, int] = connection_args.get(\"port\", None)\n        address: str = connection_args.get(\"address\", None)\n        uri: str = connection_args.get(\"uri\", None)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-5", "text": "uri: str = connection_args.get(\"uri\", None)\n        user = connection_args.get(\"user\", None)\n        # Order of use is host/port, uri, address\n        if host is not None and port is not None:\n            given_address = str(host) + \":\" + str(port)\n        elif uri is not None:\n            given_address = uri.split(\"https://\")[1]\n        elif address is not None:\n            given_address = address\n        else:\n            given_address = None\n            logger.debug(\"Missing standard address type for reuse attempt\")\n        # User defaults to empty string when getting connection info\n        if user is not None:\n            tmp_user = user\n        else:\n            tmp_user = \"\"\n        # If a valid address was given, then check if a connection exists\n        if given_address is not None:\n            for con in connections.list_connections():\n                addr = connections.get_connection_addr(con[0])\n                if (\n                    con[1]\n                    and (\"address\" in addr)\n                    and (addr[\"address\"] == given_address)\n                    and (\"user\" in addr)\n                    and (addr[\"user\"] == tmp_user)\n                ):\n                    logger.debug(\"Using previous connection: %s\", con[0])\n                    return con[0]\n        # Generate a new connection if one doesn't exist\n        alias = uuid4().hex\n        try:\n            connections.connect(alias=alias, **connection_args)\n            logger.debug(\"Created new connection using: %s\", alias)\n            return alias\n        except MilvusException as e:\n            logger.error(\"Failed to create new connection using: %s\", alias)\n            raise e\n    def _init(\n        self, embeddings: Optional[list] = None, metadatas: Optional[list[dict]] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-6", "text": ") -> None:\n        if embeddings is not None:\n            self._create_collection(embeddings, metadatas)\n        self._extract_fields()\n        self._create_index()\n        self._create_search_params()\n        self._load()\n    def _create_collection(\n        self, embeddings: list, metadatas: Optional[list[dict]] = None\n    ) -> None:\n        from pymilvus import (\n            Collection,\n            CollectionSchema,\n            DataType,\n            FieldSchema,\n            MilvusException,\n        )\n        from pymilvus.orm.types import infer_dtype_bydata\n        # Determine embedding dim\n        dim = len(embeddings[0])\n        fields = []\n        # Determine metadata schema\n        if metadatas:\n            # Create FieldSchema for each entry in metadata.\n            for key, value in metadatas[0].items():\n                # Infer the corresponding datatype of the metadata\n                dtype = infer_dtype_bydata(value)\n                # Datatype isn't compatible\n                if dtype == DataType.UNKNOWN or dtype == DataType.NONE:\n                    logger.error(\n                        \"Failure to create collection, unrecognized dtype for key: %s\",\n                        key,\n                    )\n                    raise ValueError(f\"Unrecognized datatype for {key}.\")\n                # Dataype is a string/varchar equivalent\n                elif dtype == DataType.VARCHAR:\n                    fields.append(FieldSchema(key, DataType.VARCHAR, max_length=65_535))\n                else:\n                    fields.append(FieldSchema(key, dtype))\n        # Create the text field\n        fields.append(\n            FieldSchema(self._text_field, DataType.VARCHAR, max_length=65_535)\n        )\n        # Create the primary key field\n        fields.append(\n            FieldSchema(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-7", "text": "# Create the primary key field\n        fields.append(\n            FieldSchema(\n                self._primary_field, DataType.INT64, is_primary=True, auto_id=True\n            )\n        )\n        # Create the vector field, supports binary or float vectors\n        fields.append(\n            FieldSchema(self._vector_field, infer_dtype_bydata(embeddings[0]), dim=dim)\n        )\n        # Create the schema for the collection\n        schema = CollectionSchema(fields)\n        # Create the collection\n        try:\n            self.col = Collection(\n                name=self.collection_name,\n                schema=schema,\n                consistency_level=self.consistency_level,\n                using=self.alias,\n            )\n        except MilvusException as e:\n            logger.error(\n                \"Failed to create collection: %s error: %s\", self.collection_name, e\n            )\n            raise e\n    def _extract_fields(self) -> None:\n        \"\"\"Grab the existing fields from the Collection\"\"\"\n        from pymilvus import Collection\n        if isinstance(self.col, Collection):\n            schema = self.col.schema\n            for x in schema.fields:\n                self.fields.append(x.name)\n            # Since primary field is auto-id, no need to track it\n            self.fields.remove(self._primary_field)\n    def _get_index(self) -> Optional[dict[str, Any]]:\n        \"\"\"Return the vector index information if it exists\"\"\"\n        from pymilvus import Collection\n        if isinstance(self.col, Collection):\n            for x in self.col.indexes:\n                if x.field_name == self._vector_field:\n                    return x.to_dict()\n        return None\n    def _create_index(self) -> None:\n        \"\"\"Create a index on the collection\"\"\"\n        from pymilvus import Collection, MilvusException", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-8", "text": "from pymilvus import Collection, MilvusException\n        if isinstance(self.col, Collection) and self._get_index() is None:\n            try:\n                # If no index params, use a default HNSW based one\n                if self.index_params is None:\n                    self.index_params = {\n                        \"metric_type\": \"L2\",\n                        \"index_type\": \"HNSW\",\n                        \"params\": {\"M\": 8, \"efConstruction\": 64},\n                    }\n                try:\n                    self.col.create_index(\n                        self._vector_field,\n                        index_params=self.index_params,\n                        using=self.alias,\n                    )\n                # If default did not work, most likely on Zilliz Cloud\n                except MilvusException:\n                    # Use AUTOINDEX based index\n                    self.index_params = {\n                        \"metric_type\": \"L2\",\n                        \"index_type\": \"AUTOINDEX\",\n                        \"params\": {},\n                    }\n                    self.col.create_index(\n                        self._vector_field,\n                        index_params=self.index_params,\n                        using=self.alias,\n                    )\n                logger.debug(\n                    \"Successfully created an index on collection: %s\",\n                    self.collection_name,\n                )\n            except MilvusException as e:\n                logger.error(\n                    \"Failed to create an index on collection: %s\", self.collection_name\n                )\n                raise e\n    def _create_search_params(self) -> None:\n        \"\"\"Generate search params based on the current index type\"\"\"\n        from pymilvus import Collection\n        if isinstance(self.col, Collection) and self.search_params is None:\n            index = self._get_index()\n            if index is not None:\n                index_type: str = index[\"index_param\"][\"index_type\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-9", "text": "index_type: str = index[\"index_param\"][\"index_type\"]\n                metric_type: str = index[\"index_param\"][\"metric_type\"]\n                self.search_params = self.default_search_params[index_type]\n                self.search_params[\"metric_type\"] = metric_type\n    def _load(self) -> None:\n        \"\"\"Load the collection if available.\"\"\"\n        from pymilvus import Collection\n        if isinstance(self.col, Collection) and self._get_index() is not None:\n            self.col.load()\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        timeout: Optional[int] = None,\n        batch_size: int = 1000,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Insert text data into Milvus.\n        Inserting data when the collection has not be made yet will result\n        in creating a new Collection. The data of the first entity decides\n        the schema of the new collection, the dim is extracted from the first\n        embedding and the columns are decided by the first metadata dict.\n        Metada keys will need to be present for all inserted values. At\n        the moment there is no None equivalent in Milvus.\n        Args:\n            texts (Iterable[str]): The texts to embed, it is assumed\n                that they all fit in memory.\n            metadatas (Optional[List[dict]]): Metadata dicts attached to each of\n                the texts. Defaults to None.\n            timeout (Optional[int]): Timeout for each batch insert. Defaults\n                to None.\n            batch_size (int, optional): Batch size to use for insertion.\n                Defaults to 1000.\n        Raises:\n            MilvusException: Failure to add texts\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-10", "text": "Raises:\n            MilvusException: Failure to add texts\n        Returns:\n            List[str]: The resulting keys for each inserted element.\n        \"\"\"\n        from pymilvus import Collection, MilvusException\n        texts = list(texts)\n        try:\n            embeddings = self.embedding_func.embed_documents(texts)\n        except NotImplementedError:\n            embeddings = [self.embedding_func.embed_query(x) for x in texts]\n        if len(embeddings) == 0:\n            logger.debug(\"Nothing to insert, skipping.\")\n            return []\n        # If the collection hasn't been initialized yet, perform all steps to do so\n        if not isinstance(self.col, Collection):\n            self._init(embeddings, metadatas)\n        # Dict to hold all insert columns\n        insert_dict: dict[str, list] = {\n            self._text_field: texts,\n            self._vector_field: embeddings,\n        }\n        # Collect the metadata into the insert dict.\n        if metadatas is not None:\n            for d in metadatas:\n                for key, value in d.items():\n                    if key in self.fields:\n                        insert_dict.setdefault(key, []).append(value)\n        # Total insert count\n        vectors: list = insert_dict[self._vector_field]\n        total_count = len(vectors)\n        pks: list[str] = []\n        assert isinstance(self.col, Collection)\n        for i in range(0, total_count, batch_size):\n            # Grab end index\n            end = min(i + batch_size, total_count)\n            # Convert dict to list of lists batch for insertion\n            insert_list = [insert_dict[x][i:end] for x in self.fields]\n            # Insert into the collection.\n            try:\n                res: Collection", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-11", "text": "# Insert into the collection.\n            try:\n                res: Collection\n                res = self.col.insert(insert_list, timeout=timeout, **kwargs)\n                pks.extend(res.primary_keys)\n            except MilvusException as e:\n                logger.error(\n                    \"Failed to insert batch starting at entity: %s/%s\", i, total_count\n                )\n                raise e\n        return pks\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform a similarity search against the query string.\n        Args:\n            query (str): The text to search.\n            k (int, optional): How many results to return. Defaults to 4.\n            param (dict, optional): The search params for the index type.\n                Defaults to None.\n            expr (str, optional): Filtering expression. Defaults to None.\n            timeout (int, optional): How long to wait before timeout error.\n                Defaults to None.\n            kwargs: Collection.search() keyword arguments.\n        Returns:\n            List[Document]: Document results for search.\n        \"\"\"\n        if self.col is None:\n            logger.debug(\"No existing collection to search.\")\n            return []\n        res = self.similarity_search_with_score(\n            query=query, k=k, param=param, expr=expr, timeout=timeout, **kwargs\n        )\n        return [doc for doc, _ in res]\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-12", "text": "self,\n        embedding: List[float],\n        k: int = 4,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform a similarity search against the query string.\n        Args:\n            embedding (List[float]): The embedding vector to search.\n            k (int, optional): How many results to return. Defaults to 4.\n            param (dict, optional): The search params for the index type.\n                Defaults to None.\n            expr (str, optional): Filtering expression. Defaults to None.\n            timeout (int, optional): How long to wait before timeout error.\n                Defaults to None.\n            kwargs: Collection.search() keyword arguments.\n        Returns:\n            List[Document]: Document results for search.\n        \"\"\"\n        if self.col is None:\n            logger.debug(\"No existing collection to search.\")\n            return []\n        res = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs\n        )\n        return [doc for doc, _ in res]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Perform a search on a query string and return results with score.\n        For more information about the search parameters, take a look at the pymilvus\n        documentation found here:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-13", "text": "documentation found here:\n        https://milvus.io/api-reference/pymilvus/v2.2.6/Collection/search().md\n        Args:\n            query (str): The text being searched.\n            k (int, optional): The amount of results to return. Defaults to 4.\n            param (dict): The search params for the specified index.\n                Defaults to None.\n            expr (str, optional): Filtering expression. Defaults to None.\n            timeout (int, optional): How long to wait before timeout error.\n                Defaults to None.\n            kwargs: Collection.search() keyword arguments.\n        Returns:\n            List[float], List[Tuple[Document, any, any]]:\n        \"\"\"\n        if self.col is None:\n            logger.debug(\"No existing collection to search.\")\n            return []\n        # Embed the query text.\n        embedding = self.embedding_func.embed_query(query)\n        res = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs\n        )\n        return res\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Perform a search on a query string and return results with score.\n        For more information about the search parameters, take a look at the pymilvus\n        documentation found here:\n        https://milvus.io/api-reference/pymilvus/v2.2.6/Collection/search().md\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-14", "text": "Args:\n            embedding (List[float]): The embedding vector being searched.\n            k (int, optional): The amount of results to return. Defaults to 4.\n            param (dict): The search params for the specified index.\n                Defaults to None.\n            expr (str, optional): Filtering expression. Defaults to None.\n            timeout (int, optional): How long to wait before timeout error.\n                Defaults to None.\n            kwargs: Collection.search() keyword arguments.\n        Returns:\n            List[Tuple[Document, float]]: Result doc and score.\n        \"\"\"\n        if self.col is None:\n            logger.debug(\"No existing collection to search.\")\n            return []\n        if param is None:\n            param = self.search_params\n        # Determine result metadata fields.\n        output_fields = self.fields[:]\n        output_fields.remove(self._vector_field)\n        # Perform the search.\n        res = self.col.search(\n            data=[embedding],\n            anns_field=self._vector_field,\n            param=param,\n            limit=k,\n            expr=expr,\n            output_fields=output_fields,\n            timeout=timeout,\n            **kwargs,\n        )\n        # Organize results.\n        ret = []\n        for result in res[0]:\n            meta = {x: result.entity.get(x) for x in output_fields}\n            doc = Document(page_content=meta.pop(self._text_field), metadata=meta)\n            pair = (doc, result.score)\n            ret.append(pair)\n        return ret\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-15", "text": "lambda_mult: float = 0.5,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform a search and return results that are reordered by MMR.\n        Args:\n            query (str): The text being searched.\n            k (int, optional): How many results to give. Defaults to 4.\n            fetch_k (int, optional): Total results to select k from.\n                Defaults to 20.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5\n            param (dict, optional): The search params for the specified index.\n                Defaults to None.\n            expr (str, optional): Filtering expression. Defaults to None.\n            timeout (int, optional): How long to wait before timeout error.\n                Defaults to None.\n            kwargs: Collection.search() keyword arguments.\n        Returns:\n            List[Document]: Document results for search.\n        \"\"\"\n        if self.col is None:\n            logger.debug(\"No existing collection to search.\")\n            return []\n        embedding = self.embedding_func.embed_query(query)\n        return self.max_marginal_relevance_search_by_vector(\n            embedding=embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            param=param,\n            expr=expr,\n            timeout=timeout,\n            **kwargs,\n        )\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: list[float],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-16", "text": "self,\n        embedding: list[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform a search and return results that are reordered by MMR.\n        Args:\n            embedding (str): The embedding vector being searched.\n            k (int, optional): How many results to give. Defaults to 4.\n            fetch_k (int, optional): Total results to select k from.\n                Defaults to 20.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5\n            param (dict, optional): The search params for the specified index.\n                Defaults to None.\n            expr (str, optional): Filtering expression. Defaults to None.\n            timeout (int, optional): How long to wait before timeout error.\n                Defaults to None.\n            kwargs: Collection.search() keyword arguments.\n        Returns:\n            List[Document]: Document results for search.\n        \"\"\"\n        if self.col is None:\n            logger.debug(\"No existing collection to search.\")\n            return []\n        if param is None:\n            param = self.search_params\n        # Determine result metadata fields.\n        output_fields = self.fields[:]\n        output_fields.remove(self._vector_field)\n        # Perform the search.\n        res = self.col.search(\n            data=[embedding],\n            anns_field=self._vector_field,\n            param=param,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-17", "text": "anns_field=self._vector_field,\n            param=param,\n            limit=fetch_k,\n            expr=expr,\n            output_fields=output_fields,\n            timeout=timeout,\n            **kwargs,\n        )\n        # Organize results.\n        ids = []\n        documents = []\n        scores = []\n        for result in res[0]:\n            meta = {x: result.entity.get(x) for x in output_fields}\n            doc = Document(page_content=meta.pop(self._text_field), metadata=meta)\n            documents.append(doc)\n            scores.append(result.score)\n            ids.append(result.id)\n        vectors = self.col.query(\n            expr=f\"{self._primary_field} in {ids}\",\n            output_fields=[self._primary_field, self._vector_field],\n            timeout=timeout,\n        )\n        # Reorganize the results from query to match search order.\n        vectors = {x[self._primary_field]: x[self._vector_field] for x in vectors}\n        ordered_result_embeddings = [vectors[x] for x in ids]\n        # Get the new order of results.\n        new_ordering = maximal_marginal_relevance(\n            np.array(embedding), ordered_result_embeddings, k=k, lambda_mult=lambda_mult\n        )\n        # Reorder the values and return.\n        ret = []\n        for x in new_ordering:\n            # Function can return -1 index\n            if x == -1:\n                break\n            else:\n                ret.append(documents[x])\n        return ret\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        collection_name: str = \"LangChainCollection\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-18", "text": "collection_name: str = \"LangChainCollection\",\n        connection_args: dict[str, Any] = DEFAULT_MILVUS_CONNECTION,\n        consistency_level: str = \"Session\",\n        index_params: Optional[dict] = None,\n        search_params: Optional[dict] = None,\n        drop_old: bool = False,\n        **kwargs: Any,\n    ) -> Milvus:\n        \"\"\"Create a Milvus collection, indexes it with HNSW, and insert data.\n        Args:\n            texts (List[str]): Text data.\n            embedding (Embeddings): Embedding function.\n            metadatas (Optional[List[dict]]): Metadata for each text if it exists.\n                Defaults to None.\n            collection_name (str, optional): Collection name to use. Defaults to\n                \"LangChainCollection\".\n            connection_args (dict[str, Any], optional): Connection args to use. Defaults\n                to DEFAULT_MILVUS_CONNECTION.\n            consistency_level (str, optional): Which consistency level to use. Defaults\n                to \"Session\".\n            index_params (Optional[dict], optional): Which index_params to use. Defaults\n                to None.\n            search_params (Optional[dict], optional): Which search params to use.\n                Defaults to None.\n            drop_old (Optional[bool], optional): Whether to drop the collection with\n                that name if it exists. Defaults to False.\n        Returns:\n            Milvus: Milvus Vector Store\n        \"\"\"\n        vector_db = cls(\n            embedding_function=embedding,\n            collection_name=collection_name,\n            connection_args=connection_args,\n            consistency_level=consistency_level,\n            index_params=index_params,\n            search_params=search_params,\n            drop_old=drop_old,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "b57c5a0a0ddc-19", "text": "drop_old=drop_old,\n            **kwargs,\n        )\n        vector_db.add_texts(texts=texts, metadatas=metadatas)\n        return vector_db", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html"}
{"id": "537c741cc790-0", "text": "Source code for langchain.vectorstores.tiledb\n\"\"\"Wrapper around TileDB vector database.\"\"\"\nfrom __future__ import annotations\nimport pickle\nimport random\nimport sys\nfrom typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nINDEX_METRICS = frozenset([\"euclidean\"])\nDEFAULT_METRIC = \"euclidean\"\nDOCUMENTS_ARRAY_NAME = \"documents\"\nVECTOR_INDEX_NAME = \"vectors\"\nMAX_UINT64 = np.iinfo(np.dtype(\"uint64\")).max\nMAX_FLOAT_32 = np.finfo(np.dtype(\"float32\")).max\nMAX_FLOAT = sys.float_info.max\n[docs]def dependable_tiledb_import() -> Any:\n    \"\"\"Import tiledb-vector-search if available, otherwise raise error.\"\"\"\n    try:\n        import tiledb as tiledb\n        import tiledb.vector_search as tiledb_vs\n    except ImportError:\n        raise ValueError(\n            \"Could not import tiledb-vector-search python package. \"\n            \"Please install it with `conda install -c tiledb tiledb-vector-search` \"\n            \"or `pip install tiledb-vector-search`\"\n        )\n    return tiledb_vs, tiledb\n[docs]def get_vector_index_uri_from_group(group: Any) -> str:\n    return group[VECTOR_INDEX_NAME].uri\n[docs]def get_documents_array_uri_from_group(group: Any) -> str:\n    return group[DOCUMENTS_ARRAY_NAME].uri\n[docs]def get_vector_index_uri(uri: str) -> str:\n    return f\"{uri}/{VECTOR_INDEX_NAME}\"\n[docs]def get_documents_array_uri(uri: str) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-1", "text": "[docs]def get_documents_array_uri(uri: str) -> str:\n    return f\"{uri}/{DOCUMENTS_ARRAY_NAME}\"\n[docs]class TileDB(VectorStore):\n    \"\"\"Wrapper around TileDB vector database.\n    To use, you should have the ``tiledb-vector-search`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain import TileDB\n            embeddings = OpenAIEmbeddings()\n            db = TileDB(embeddings, index_uri, metric)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        index_uri: str,\n        metric: str,\n        *,\n        vector_index_uri: str = \"\",\n        docs_array_uri: str = \"\",\n        config: Optional[Mapping[str, Any]] = None,\n        timestamp: Any = None,\n        **kwargs: Any,\n    ):\n        \"\"\"Initialize with necessary components.\"\"\"\n        self.embedding = embedding\n        self.embedding_function = embedding.embed_query\n        self.index_uri = index_uri\n        self.metric = metric\n        self.config = config\n        tiledb_vs, tiledb = dependable_tiledb_import()\n        with tiledb.scope_ctx(ctx_or_config=config):\n            index_group = tiledb.Group(self.index_uri, \"r\")\n            self.vector_index_uri = (\n                vector_index_uri\n                if vector_index_uri != \"\"\n                else get_vector_index_uri_from_group(index_group)\n            )\n            self.docs_array_uri = (\n                docs_array_uri\n                if docs_array_uri != \"\"\n                else get_documents_array_uri_from_group(index_group)\n            )\n            index_group.close()\n            group = tiledb.Group(self.vector_index_uri, \"r\")\n            self.index_type = group.meta.get(\"index_type\")\n            group.close()\n            self.timestamp = timestamp", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-2", "text": "group.close()\n            self.timestamp = timestamp\n            if self.index_type == \"FLAT\":\n                self.vector_index = tiledb_vs.flat_index.FlatIndex(\n                    uri=self.vector_index_uri,\n                    config=self.config,\n                    timestamp=self.timestamp,\n                    **kwargs,\n                )\n            elif self.index_type == \"IVF_FLAT\":\n                self.vector_index = tiledb_vs.ivf_flat_index.IVFFlatIndex(\n                    uri=self.vector_index_uri,\n                    config=self.config,\n                    timestamp=self.timestamp,\n                    **kwargs,\n                )\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return self.embedding\n[docs]    def process_index_results(\n        self,\n        ids: List[int],\n        scores: List[float],\n        *,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        score_threshold: float = MAX_FLOAT,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Turns TileDB results into a list of documents and scores.\n        Args:\n            ids: List of indices of the documents in the index.\n            scores: List of distances of the documents in the index.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, Any]]): Filter by metadata. Defaults to None.\n            score_threshold: Optional, a floating point value to filter the\n                resulting set of retrieved docs\n        Returns:\n            List of Documents and scores.\n        \"\"\"\n        tiledb_vs, tiledb = dependable_tiledb_import()\n        docs = []\n        docs_array = tiledb.open(\n            self.docs_array_uri, \"r\", timestamp=self.timestamp, config=self.config\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-3", "text": "self.docs_array_uri, \"r\", timestamp=self.timestamp, config=self.config\n        )\n        for idx, score in zip(ids, scores):\n            if idx == 0 and score == 0:\n                continue\n            if idx == MAX_UINT64 and score == MAX_FLOAT_32:\n                continue\n            doc = docs_array[idx]\n            if doc is None or len(doc[\"text\"]) == 0:\n                raise ValueError(f\"Could not find document for id {idx}, got {doc}\")\n            pickled_metadata = doc.get(\"metadata\")\n            result_doc = Document(page_content=str(doc[\"text\"][0]))\n            if pickled_metadata is not None:\n                metadata = pickle.loads(\n                    np.array(pickled_metadata.tolist()).astype(np.uint8).tobytes()\n                )\n                result_doc.metadata = metadata\n            if filter is not None:\n                filter = {\n                    key: [value] if not isinstance(value, list) else value\n                    for key, value in filter.items()\n                }\n                if all(\n                    result_doc.metadata.get(key) in value\n                    for key, value in filter.items()\n                ):\n                    docs.append((result_doc, score))\n            else:\n                docs.append((result_doc, score))\n        docs_array.close()\n        docs = [(doc, score) for doc, score in docs if score <= score_threshold]\n        return docs[:k]\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        *,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-4", "text": "\"\"\"Return docs most similar to query.\n        Args:\n            embedding: Embedding vector to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, Any]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n            **kwargs: kwargs to be passed to similarity search. Can include:\n                nprobe: Optional, number of partitions to check if using IVF_FLAT index\n                score_threshold: Optional, a floating point value to filter the\n                    resulting set of retrieved docs\n        Returns:\n            List of documents most similar to the query text and distance\n            in float for each. Lower score represents more similarity.\n        \"\"\"\n        if \"score_threshold\" in kwargs:\n            score_threshold = kwargs.pop(\"score_threshold\")\n        else:\n            score_threshold = MAX_FLOAT\n        d, i = self.vector_index.query(\n            np.array([np.array(embedding).astype(np.float32)]).astype(np.float32),\n            k=k if filter is None else fetch_k,\n            **kwargs,\n        )\n        return self.process_index_results(\n            ids=i[0], scores=d[0], filter=filter, k=k, score_threshold=score_threshold\n        )\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        *,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-5", "text": "Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n        Returns:\n            List of documents most similar to the query text with\n            Distance as float. Lower score represents more similarity.\n        \"\"\"\n        embedding = self.embedding_function(query)\n        docs = self.similarity_search_with_score_by_vector(\n            embedding,\n            k=k,\n            filter=filter,\n            fetch_k=fetch_k,\n            **kwargs,\n        )\n        return docs\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n        Returns:\n            List of Documents most similar to the embedding.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score_by_vector(\n            embedding,\n            k=k,\n            filter=filter,\n            fetch_k=fetch_k,\n            **kwargs,\n        )\n        return [doc for doc, _ in docs_and_scores]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-6", "text": ")\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(\n            query, k=k, filter=filter, fetch_k=fetch_k, **kwargs\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def max_marginal_relevance_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        *,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs and their similarity scores selected using the maximal marginal\n            relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-7", "text": "Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch before filtering to\n                     pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents and similarity scores selected by maximal marginal\n                relevance and score for each.\n        \"\"\"\n        if \"score_threshold\" in kwargs:\n            score_threshold = kwargs.pop(\"score_threshold\")\n        else:\n            score_threshold = MAX_FLOAT\n        scores, indices = self.vector_index.query(\n            np.array([np.array(embedding).astype(np.float32)]).astype(np.float32),\n            k=fetch_k if filter is None else fetch_k * 2,\n            **kwargs,\n        )\n        results = self.process_index_results(\n            ids=indices[0],\n            scores=scores[0],\n            filter=filter,\n            k=fetch_k if filter is None else fetch_k * 2,\n            score_threshold=score_threshold,\n        )\n        embeddings = [\n            self.embedding.embed_documents([doc.page_content])[0] for doc, _ in results\n        ]\n        mmr_selected = maximal_marginal_relevance(\n            np.array([embedding], dtype=np.float32),\n            embeddings,\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        docs_and_scores = []\n        for i in mmr_selected:\n            docs_and_scores.append(results[i])\n        return docs_and_scores\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-8", "text": "[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch before filtering to\n                     pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        docs_and_scores = self.max_marginal_relevance_search_with_score_by_vector(\n            embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n            **kwargs,\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-9", "text": "**kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch before filtering (if needed) to\n                     pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        embedding = self.embedding_function(query)\n        docs = self.max_marginal_relevance_search_by_vector(\n            embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n            **kwargs,\n        )\n        return docs\n[docs]    @classmethod\n    def create(\n        cls,\n        index_uri: str,\n        index_type: str,\n        dimensions: int,\n        vector_type: np.dtype,\n        *,\n        metadatas: bool = True,\n        config: Optional[Mapping[str, Any]] = None,\n    ) -> None:\n        tiledb_vs, tiledb = dependable_tiledb_import()\n        with tiledb.scope_ctx(ctx_or_config=config):\n            try:\n                tiledb.group_create(index_uri)\n            except tiledb.TileDBError as err:\n                raise err\n            group = tiledb.Group(index_uri, \"w\")\n            vector_index_uri = get_vector_index_uri(group.uri)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-10", "text": "vector_index_uri = get_vector_index_uri(group.uri)\n            docs_uri = get_documents_array_uri(group.uri)\n            if index_type == \"FLAT\":\n                tiledb_vs.flat_index.create(\n                    uri=vector_index_uri,\n                    dimensions=dimensions,\n                    vector_type=vector_type,\n                    config=config,\n                )\n            elif index_type == \"IVF_FLAT\":\n                tiledb_vs.ivf_flat_index.create(\n                    uri=vector_index_uri,\n                    dimensions=dimensions,\n                    vector_type=vector_type,\n                    config=config,\n                )\n            group.add(vector_index_uri, name=VECTOR_INDEX_NAME)\n            # Create TileDB array to store Documents\n            # TODO add a Document store API to tiledb-vector-search to allow storing\n            #  different types of objects and metadata in a more generic way.\n            dim = tiledb.Dim(\n                name=\"id\",\n                domain=(0, MAX_UINT64 - 1),\n                dtype=np.dtype(np.uint64),\n            )\n            dom = tiledb.Domain(dim)\n            text_attr = tiledb.Attr(name=\"text\", dtype=np.dtype(\"U1\"), var=True)\n            attrs = [text_attr]\n            if metadatas:\n                metadata_attr = tiledb.Attr(name=\"metadata\", dtype=np.uint8, var=True)\n                attrs.append(metadata_attr)\n            schema = tiledb.ArraySchema(\n                domain=dom,\n                sparse=True,\n                allows_duplicates=False,\n                attrs=attrs,\n            )\n            tiledb.Array.create(docs_uri, schema)\n            group.add(docs_uri, name=DOCUMENTS_ARRAY_NAME)\n            group.close()\n    @classmethod\n    def __from(\n        cls,\n        texts: List[str],\n        embeddings: List[List[float]],\n        embedding: Embeddings,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-11", "text": "embeddings: List[List[float]],\n        embedding: Embeddings,\n        index_uri: str,\n        *,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        metric: str = DEFAULT_METRIC,\n        index_type: str = \"FLAT\",\n        config: Optional[Mapping[str, Any]] = None,\n        index_timestamp: int = 0,\n        **kwargs: Any,\n    ) -> TileDB:\n        if metric not in INDEX_METRICS:\n            raise ValueError(\n                (\n                    f\"Unsupported distance metric: {metric}. \"\n                    f\"Expected one of {list(INDEX_METRICS)}\"\n                )\n            )\n        tiledb_vs, tiledb = dependable_tiledb_import()\n        input_vectors = np.array(embeddings).astype(np.float32)\n        cls.create(\n            index_uri=index_uri,\n            index_type=index_type,\n            dimensions=input_vectors.shape[1],\n            vector_type=input_vectors.dtype,\n            metadatas=metadatas is not None,\n            config=config,\n        )\n        with tiledb.scope_ctx(ctx_or_config=config):\n            if not embeddings:\n                raise ValueError(\"embeddings must be provided to build a TileDB index\")\n            vector_index_uri = get_vector_index_uri(index_uri)\n            docs_uri = get_documents_array_uri(index_uri)\n            if ids is None:\n                ids = [str(random.randint(0, MAX_UINT64 - 1)) for _ in texts]\n            external_ids = np.array(ids).astype(np.uint64)\n            tiledb_vs.ingestion.ingest(\n                index_type=index_type,\n                index_uri=vector_index_uri,\n                input_vectors=input_vectors,\n                external_ids=external_ids,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-12", "text": "input_vectors=input_vectors,\n                external_ids=external_ids,\n                index_timestamp=index_timestamp if index_timestamp != 0 else None,\n                config=config,\n                **kwargs,\n            )\n            with tiledb.open(docs_uri, \"w\") as A:\n                if external_ids is None:\n                    external_ids = np.zeros(len(texts), dtype=np.uint64)\n                    for i in range(len(texts)):\n                        external_ids[i] = i\n                data = {}\n                data[\"text\"] = np.array(texts)\n                if metadatas is not None:\n                    metadata_attr = np.empty([len(metadatas)], dtype=object)\n                    i = 0\n                    for metadata in metadatas:\n                        metadata_attr[i] = np.frombuffer(\n                            pickle.dumps(metadata), dtype=np.uint8\n                        )\n                        i += 1\n                    data[\"metadata\"] = metadata_attr\n                A[external_ids] = data\n        return cls(\n            embedding=embedding,\n            index_uri=index_uri,\n            metric=metric,\n            config=config,\n            **kwargs,\n        )\n[docs]    def delete(\n        self, ids: Optional[List[str]] = None, timestamp: int = 0, **kwargs: Any\n    ) -> Optional[bool]:\n        \"\"\"Delete by vector ID or other criteria.\n        Args:\n            ids: List of ids to delete.\n            timestamp: Optional timestamp to delete with.\n            **kwargs: Other keyword arguments that subclasses might use.\n        Returns:\n            Optional[bool]: True if deletion is successful,\n            False otherwise, None if not implemented.\n        \"\"\"\n        external_ids = np.array(ids).astype(np.uint64)\n        self.vector_index.delete_batch(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-13", "text": "self.vector_index.delete_batch(\n            external_ids=external_ids, timestamp=timestamp if timestamp != 0 else None\n        )\n        return True\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        timestamp: int = 0,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional ids of each text object.\n            timestamp: Optional timestamp to write new texts with.\n            kwargs: vectorstore specific parameters\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        tiledb_vs, tiledb = dependable_tiledb_import()\n        embeddings = self.embedding.embed_documents(list(texts))\n        if ids is None:\n            ids = [str(random.randint(0, MAX_UINT64 - 1)) for _ in texts]\n        external_ids = np.array(ids).astype(np.uint64)\n        vectors = np.empty((len(embeddings)), dtype=\"O\")\n        for i in range(len(embeddings)):\n            vectors[i] = np.array(embeddings[i], dtype=np.float32)\n        self.vector_index.update_batch(\n            vectors=vectors,\n            external_ids=external_ids,\n            timestamp=timestamp if timestamp != 0 else None,\n        )\n        docs = {}\n        docs[\"text\"] = np.array(texts)\n        if metadatas is not None:\n            metadata_attr = np.empty([len(metadatas)], dtype=object)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-14", "text": "metadata_attr = np.empty([len(metadatas)], dtype=object)\n            i = 0\n            for metadata in metadatas:\n                metadata_attr[i] = np.frombuffer(pickle.dumps(metadata), dtype=np.uint8)\n                i += 1\n            docs[\"metadata\"] = metadata_attr\n        docs_array = tiledb.open(\n            self.docs_array_uri,\n            \"w\",\n            timestamp=timestamp if timestamp != 0 else None,\n            config=self.config,\n        )\n        docs_array[external_ids] = docs\n        docs_array.close()\n        return ids\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        metric: str = DEFAULT_METRIC,\n        index_uri: str = \"/tmp/tiledb_array\",\n        index_type: str = \"FLAT\",\n        config: Optional[Mapping[str, Any]] = None,\n        index_timestamp: int = 0,\n        **kwargs: Any,\n    ) -> TileDB:\n        \"\"\"Construct a TileDB index from raw documents.\n        Args:\n            texts: List of documents to index.\n            embedding: Embedding function to use.\n            metadatas: List of metadata dictionaries to associate with documents.\n            ids: Optional ids of each text object.\n            metric: Metric to use for indexing. Defaults to \"euclidean\".\n            index_uri: The URI to write the TileDB arrays\n            index_type: Optional,  Vector index type (\"FLAT\", IVF_FLAT\")\n            config: Optional, TileDB config\n            index_timestamp: Optional, timestamp to write new texts with.\n        Example:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-15", "text": "index_timestamp: Optional, timestamp to write new texts with.\n        Example:\n            .. code-block:: python\n                from langchain import TileDB\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                index = TileDB.from_texts(texts, embeddings)\n        \"\"\"\n        embeddings = []\n        embeddings = embedding.embed_documents(texts)\n        return cls.__from(\n            texts=texts,\n            embeddings=embeddings,\n            embedding=embedding,\n            metadatas=metadatas,\n            ids=ids,\n            metric=metric,\n            index_uri=index_uri,\n            index_type=index_type,\n            config=config,\n            index_timestamp=index_timestamp,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_embeddings(\n        cls,\n        text_embeddings: List[Tuple[str, List[float]]],\n        embedding: Embeddings,\n        index_uri: str,\n        *,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        metric: str = DEFAULT_METRIC,\n        index_type: str = \"FLAT\",\n        config: Optional[Mapping[str, Any]] = None,\n        index_timestamp: int = 0,\n        **kwargs: Any,\n    ) -> TileDB:\n        \"\"\"Construct TileDB index from embeddings.\n        Args:\n            text_embeddings: List of tuples of (text, embedding)\n            embedding: Embedding function to use.\n            index_uri: The URI to write the TileDB arrays\n            metadatas: List of metadata dictionaries to associate with documents.\n            metric: Optional, Metric to use for indexing. Defaults to \"euclidean\".", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-16", "text": "metric: Optional, Metric to use for indexing. Defaults to \"euclidean\".\n            index_type: Optional, Vector index type (\"FLAT\", IVF_FLAT\")\n            config: Optional, TileDB config\n            index_timestamp: Optional, timestamp to write new texts with.\n        Example:\n            .. code-block:: python\n                from langchain import TileDB\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                text_embeddings = embeddings.embed_documents(texts)\n                text_embedding_pairs = list(zip(texts, text_embeddings))\n                db = TileDB.from_embeddings(text_embedding_pairs, embeddings)\n        \"\"\"\n        texts = [t[0] for t in text_embeddings]\n        embeddings = [t[1] for t in text_embeddings]\n        return cls.__from(\n            texts=texts,\n            embeddings=embeddings,\n            embedding=embedding,\n            metadatas=metadatas,\n            ids=ids,\n            metric=metric,\n            index_uri=index_uri,\n            index_type=index_type,\n            config=config,\n            index_timestamp=index_timestamp,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def load(\n        cls,\n        index_uri: str,\n        embedding: Embeddings,\n        *,\n        metric: str = DEFAULT_METRIC,\n        config: Optional[Mapping[str, Any]] = None,\n        timestamp: Any = None,\n        **kwargs: Any,\n    ) -> TileDB:\n        \"\"\"Load a TileDB index from a URI.\n        Args:\n            index_uri: The URI of the TileDB vector index.\n            embedding: Embeddings to use when generating queries.\n            metric: Optional, Metric to use for indexing. Defaults to \"euclidean\".", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "537c741cc790-17", "text": "metric: Optional, Metric to use for indexing. Defaults to \"euclidean\".\n            config: Optional, TileDB config\n            timestamp: Optional, timestamp to use for opening the arrays.\n        \"\"\"\n        return cls(\n            embedding=embedding,\n            index_uri=index_uri,\n            metric=metric,\n            config=config,\n            timestamp=timestamp,\n            **kwargs,\n        )\n[docs]    def consolidate_updates(self, **kwargs: Any) -> None:\n        self.vector_index = self.vector_index.consolidate_updates(**kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tiledb.html"}
{"id": "6954469a780b-0", "text": "Source code for langchain.vectorstores.weaviate\nfrom __future__ import annotations\nimport datetime\nimport os\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n)\nfrom uuid import uuid4\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nif TYPE_CHECKING:\n    import weaviate\ndef _default_schema(index_name: str) -> Dict:\n    return {\n        \"class\": index_name,\n        \"properties\": [\n            {\n                \"name\": \"text\",\n                \"dataType\": [\"text\"],\n            }\n        ],\n    }\ndef _create_weaviate_client(\n    url: Optional[str] = None,\n    api_key: Optional[str] = None,\n    **kwargs: Any,\n) -> weaviate.Client:\n    try:\n        import weaviate\n    except ImportError:\n        raise ImportError(\n            \"Could not import weaviate python  package. \"\n            \"Please install it with `pip install weaviate-client`\"\n        )\n    url = url or os.environ.get(\"WEAVIATE_URL\")\n    api_key = api_key or os.environ.get(\"WEAVIATE_API_KEY\")\n    auth = weaviate.auth.AuthApiKey(api_key=api_key) if api_key else None\n    return weaviate.Client(url=url, auth_client_secret=auth, **kwargs)\ndef _default_score_normalizer(val: float) -> float:\n    return 1 - 1 / (1 + np.exp(val))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html"}
{"id": "6954469a780b-1", "text": "return 1 - 1 / (1 + np.exp(val))\ndef _json_serializable(value: Any) -> Any:\n    if isinstance(value, datetime.datetime):\n        return value.isoformat()\n    return value\n[docs]class Weaviate(VectorStore):\n    \"\"\"`Weaviate` vector store.\n    To use, you should have the ``weaviate-client`` python package installed.\n    Example:\n        .. code-block:: python\n            import weaviate\n            from langchain.vectorstores import Weaviate\n            client = weaviate.Client(url=os.environ[\"WEAVIATE_URL\"], ...)\n            weaviate = Weaviate(client, index_name, text_key)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        client: Any,\n        index_name: str,\n        text_key: str,\n        embedding: Optional[Embeddings] = None,\n        attributes: Optional[List[str]] = None,\n        relevance_score_fn: Optional[\n            Callable[[float], float]\n        ] = _default_score_normalizer,\n        by_text: bool = True,\n    ):\n        \"\"\"Initialize with Weaviate client.\"\"\"\n        try:\n            import weaviate\n        except ImportError:\n            raise ImportError(\n                \"Could not import weaviate python package. \"\n                \"Please install it with `pip install weaviate-client`.\"\n            )\n        if not isinstance(client, weaviate.Client):\n            raise ValueError(\n                f\"client should be an instance of weaviate.Client, got {type(client)}\"\n            )\n        self._client = client\n        self._index_name = index_name\n        self._embedding = embedding\n        self._text_key = text_key\n        self._query_attrs = [self._text_key]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html"}
{"id": "6954469a780b-2", "text": "self._query_attrs = [self._text_key]\n        self.relevance_score_fn = relevance_score_fn\n        self._by_text = by_text\n        if attributes is not None:\n            self._query_attrs.extend(attributes)\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return self._embedding\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        return (\n            self.relevance_score_fn\n            if self.relevance_score_fn\n            else _default_score_normalizer\n        )\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Upload texts with metadata (properties) to Weaviate.\"\"\"\n        from weaviate.util import get_valid_uuid\n        ids = []\n        embeddings: Optional[List[List[float]]] = None\n        if self._embedding:\n            if not isinstance(texts, list):\n                texts = list(texts)\n            embeddings = self._embedding.embed_documents(texts)\n        with self._client.batch as batch:\n            for i, text in enumerate(texts):\n                data_properties = {self._text_key: text}\n                if metadatas is not None:\n                    for key, val in metadatas[i].items():\n                        data_properties[key] = _json_serializable(val)\n                # Allow for ids (consistent w/ other methods)\n                # # Or uuids (backwards compatible w/ existing arg)\n                # If the UUID of one of the objects already exists\n                # then the existing object will be replaced by the new object.\n                _id = get_valid_uuid(uuid4())\n                if \"uuids\" in kwargs:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html"}
{"id": "6954469a780b-3", "text": "if \"uuids\" in kwargs:\n                    _id = kwargs[\"uuids\"][i]\n                elif \"ids\" in kwargs:\n                    _id = kwargs[\"ids\"][i]\n                batch.add_data_object(\n                    data_object=data_properties,\n                    class_name=self._index_name,\n                    uuid=_id,\n                    vector=embeddings[i] if embeddings else None,\n                )\n                ids.append(_id)\n        return ids\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        if self._by_text:\n            return self.similarity_search_by_text(query, k, **kwargs)\n        else:\n            if self._embedding is None:\n                raise ValueError(\n                    \"_embedding cannot be None for similarity_search when \"\n                    \"_by_text=False\"\n                )\n            embedding = self._embedding.embed_query(query)\n            return self.similarity_search_by_vector(embedding, k, **kwargs)\n[docs]    def similarity_search_by_text(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        content: Dict[str, Any] = {\"concepts\": [query]}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html"}
{"id": "6954469a780b-4", "text": "\"\"\"\n        content: Dict[str, Any] = {\"concepts\": [query]}\n        if kwargs.get(\"search_distance\"):\n            content[\"certainty\"] = kwargs.get(\"search_distance\")\n        query_obj = self._client.query.get(self._index_name, self._query_attrs)\n        if kwargs.get(\"where_filter\"):\n            query_obj = query_obj.with_where(kwargs.get(\"where_filter\"))\n        if kwargs.get(\"tenant\"):\n            query_obj = query_obj.with_tenant(kwargs.get(\"tenant\"))\n        if kwargs.get(\"additional\"):\n            query_obj = query_obj.with_additional(kwargs.get(\"additional\"))\n        result = query_obj.with_near_text(content).with_limit(k).do()\n        if \"errors\" in result:\n            raise ValueError(f\"Error during query: {result['errors']}\")\n        docs = []\n        for res in result[\"data\"][\"Get\"][self._index_name]:\n            text = res.pop(self._text_key)\n            docs.append(Document(page_content=text, metadata=res))\n        return docs\n[docs]    def similarity_search_by_vector(\n        self, embedding: List[float], k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Look up similar documents by embedding vector in Weaviate.\"\"\"\n        vector = {\"vector\": embedding}\n        query_obj = self._client.query.get(self._index_name, self._query_attrs)\n        if kwargs.get(\"where_filter\"):\n            query_obj = query_obj.with_where(kwargs.get(\"where_filter\"))\n        if kwargs.get(\"tenant\"):\n            query_obj = query_obj.with_tenant(kwargs.get(\"tenant\"))\n        if kwargs.get(\"additional\"):\n            query_obj = query_obj.with_additional(kwargs.get(\"additional\"))\n        result = query_obj.with_near_vector(vector).with_limit(k).do()\n        if \"errors\" in result:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html"}
{"id": "6954469a780b-5", "text": "if \"errors\" in result:\n            raise ValueError(f\"Error during query: {result['errors']}\")\n        docs = []\n        for res in result[\"data\"][\"Get\"][self._index_name]:\n            text = res.pop(self._text_key)\n            docs.append(Document(page_content=text, metadata=res))\n        return docs\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        if self._embedding is not None:\n            embedding = self._embedding.embed_query(query)\n        else:\n            raise ValueError(\n                \"max_marginal_relevance_search requires a suitable Embeddings object\"\n            )\n        return self.max_marginal_relevance_search_by_vector(\n            embedding, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, **kwargs\n        )\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html"}
{"id": "6954469a780b-6", "text": "[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        vector = {\"vector\": embedding}\n        query_obj = self._client.query.get(self._index_name, self._query_attrs)\n        if kwargs.get(\"where_filter\"):\n            query_obj = query_obj.with_where(kwargs.get(\"where_filter\"))\n        if kwargs.get(\"tenant\"):\n            query_obj = query_obj.with_tenant(kwargs.get(\"tenant\"))\n        results = (\n            query_obj.with_additional(\"vector\")\n            .with_near_vector(vector)\n            .with_limit(fetch_k)\n            .do()\n        )\n        payload = results[\"data\"][\"Get\"][self._index_name]\n        embeddings = [result[\"_additional\"][\"vector\"] for result in payload]\n        mmr_selected = maximal_marginal_relevance(\n            np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html"}
{"id": "6954469a780b-7", "text": "np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult\n        )\n        docs = []\n        for idx in mmr_selected:\n            text = payload[idx].pop(self._text_key)\n            payload[idx].pop(\"_additional\")\n            meta = payload[idx]\n            docs.append(Document(page_content=text, metadata=meta))\n        return docs\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Return list of documents most similar to the query\n        text and cosine distance in float for each.\n        Lower score represents more similarity.\n        \"\"\"\n        if self._embedding is None:\n            raise ValueError(\n                \"_embedding cannot be None for similarity_search_with_score\"\n            )\n        content: Dict[str, Any] = {\"concepts\": [query]}\n        if kwargs.get(\"search_distance\"):\n            content[\"certainty\"] = kwargs.get(\"search_distance\")\n        query_obj = self._client.query.get(self._index_name, self._query_attrs)\n        if kwargs.get(\"where_filter\"):\n            query_obj = query_obj.with_where(kwargs.get(\"where_filter\"))\n        if kwargs.get(\"tenant\"):\n            query_obj = query_obj.with_tenant(kwargs.get(\"tenant\"))\n        embedded_query = self._embedding.embed_query(query)\n        if not self._by_text:\n            vector = {\"vector\": embedded_query}\n            result = (\n                query_obj.with_near_vector(vector)\n                .with_limit(k)\n                .with_additional(\"vector\")\n                .do()\n            )\n        else:\n            result = (\n                query_obj.with_near_text(content)\n                .with_limit(k)\n                .with_additional(\"vector\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html"}
{"id": "6954469a780b-8", "text": ".with_limit(k)\n                .with_additional(\"vector\")\n                .do()\n            )\n        if \"errors\" in result:\n            raise ValueError(f\"Error during query: {result['errors']}\")\n        docs_and_scores = []\n        for res in result[\"data\"][\"Get\"][self._index_name]:\n            text = res.pop(self._text_key)\n            score = np.dot(res[\"_additional\"][\"vector\"], embedded_query)\n            docs_and_scores.append((Document(page_content=text, metadata=res), score))\n        return docs_and_scores\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        *,\n        client: Optional[weaviate.Client] = None,\n        weaviate_url: Optional[str] = None,\n        weaviate_api_key: Optional[str] = None,\n        batch_size: Optional[int] = None,\n        index_name: Optional[str] = None,\n        text_key: str = \"text\",\n        by_text: bool = False,\n        relevance_score_fn: Optional[\n            Callable[[float], float]\n        ] = _default_score_normalizer,\n        **kwargs: Any,\n    ) -> Weaviate:\n        \"\"\"Construct Weaviate wrapper from raw documents.\n        This is a user-friendly interface that:\n            1. Embeds documents.\n            2. Creates a new index for the embeddings in the Weaviate instance.\n            3. Adds the documents to the newly created Weaviate index.\n        This is intended to be a quick way to get started.\n        Args:\n            texts: Texts to add to vector store.\n            embedding: Text embedding model to use.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html"}
{"id": "6954469a780b-9", "text": "embedding: Text embedding model to use.\n            metadatas: Metadata associated with each text.\n            client: weaviate.Client to use.\n            weaviate_url: The Weaviate URL. If using Weaviate Cloud Services get it\n                from the ``Details`` tab. Can be passed in as a named param or by\n                setting the environment variable ``WEAVIATE_URL``. Should not be\n                specified if client is provided.\n            weaviate_api_key: The Weaviate API key. If enabled and using Weaviate Cloud\n                Services, get it from ``Details`` tab. Can be passed in as a named param\n                or by setting the environment variable ``WEAVIATE_API_KEY``. Should\n                not be specified if client is provided.\n            batch_size: Size of batch operations.\n            index_name: Index name.\n            text_key: Key to use for uploading/retrieving text to/from vectorstore.\n            by_text: Whether to search by text or by embedding.\n            relevance_score_fn: Function for converting whatever distance function the\n                vector store uses to a relevance score, which is a normalized similarity\n                score (0 means dissimilar, 1 means similar).\n            **kwargs: Additional named parameters to pass to ``Weaviate.__init__()``.\n        Example:\n            .. code-block:: python\n                from langchain.embeddings import OpenAIEmbeddings\n                from langchain.vectorstores import Weaviate\n                embeddings = OpenAIEmbeddings()\n                weaviate = Weaviate.from_texts(\n                    texts,\n                    embeddings,\n                    weaviate_url=\"http://localhost:8080\"\n                )\n        \"\"\"\n        try:\n            from weaviate.util import get_valid_uuid\n        except ImportError as e:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html"}
{"id": "6954469a780b-10", "text": "except ImportError as e:\n            raise ImportError(\n                \"Could not import weaviate python  package. \"\n                \"Please install it with `pip install weaviate-client`\"\n            ) from e\n        client = client or _create_weaviate_client(\n            url=weaviate_url,\n            api_key=weaviate_api_key,\n        )\n        if batch_size:\n            client.batch.configure(batch_size=batch_size)\n        index_name = index_name or f\"LangChain_{uuid4().hex}\"\n        schema = _default_schema(index_name)\n        # check whether the index already exists\n        if not client.schema.exists(index_name):\n            client.schema.create_class(schema)\n        embeddings = embedding.embed_documents(texts) if embedding else None\n        attributes = list(metadatas[0].keys()) if metadatas else None\n        # If the UUID of one of the objects already exists\n        # then the existing object will be replaced by the new object.\n        if \"uuids\" in kwargs:\n            uuids = kwargs.pop(\"uuids\")\n        else:\n            uuids = [get_valid_uuid(uuid4()) for _ in range(len(texts))]\n        with client.batch as batch:\n            for i, text in enumerate(texts):\n                data_properties = {\n                    text_key: text,\n                }\n                if metadatas is not None:\n                    for key in metadatas[i].keys():\n                        data_properties[key] = metadatas[i][key]\n                _id = uuids[i]\n                # if an embedding strategy is not provided, we let\n                # weaviate create the embedding. Note that this will only\n                # work if weaviate has been installed with a vectorizer module\n                # like text2vec-contextionary for example", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html"}
{"id": "6954469a780b-11", "text": "# like text2vec-contextionary for example\n                params = {\n                    \"uuid\": _id,\n                    \"data_object\": data_properties,\n                    \"class_name\": index_name,\n                }\n                if embeddings is not None:\n                    params[\"vector\"] = embeddings[i]\n                batch.add_data_object(**params)\n            batch.flush()\n        return cls(\n            client,\n            index_name,\n            text_key,\n            embedding=embedding,\n            attributes=attributes,\n            relevance_score_fn=relevance_score_fn,\n            by_text=by_text,\n            **kwargs,\n        )\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None:\n        \"\"\"Delete by vector IDs.\n        Args:\n            ids: List of ids to delete.\n        \"\"\"\n        if ids is None:\n            raise ValueError(\"No ids provided to delete.\")\n        # TODO: Check if this can be done in bulk\n        for id in ids:\n            self._client.data_object.delete(uuid=id)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html"}
{"id": "c16601bbdd12-0", "text": "Source code for langchain.vectorstores.faiss\nfrom __future__ import annotations\nimport asyncio\nimport logging\nimport operator\nimport os\nimport pickle\nimport uuid\nimport warnings\nfrom functools import partial\nfrom pathlib import Path\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Sized,\n    Tuple,\n    Union,\n)\nimport numpy as np\nfrom langchain.docstore.base import AddableMixin, Docstore\nfrom langchain.docstore.document import Document\nfrom langchain.docstore.in_memory import InMemoryDocstore\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import DistanceStrategy, maximal_marginal_relevance\nlogger = logging.getLogger(__name__)\n[docs]def dependable_faiss_import(no_avx2: Optional[bool] = None) -> Any:\n    \"\"\"\n    Import faiss if available, otherwise raise error.\n    If FAISS_NO_AVX2 environment variable is set, it will be considered\n    to load FAISS with no AVX2 optimization.\n    Args:\n        no_avx2: Load FAISS strictly with no AVX2 optimization\n            so that the vectorstore is portable and compatible with other devices.\n    \"\"\"\n    if no_avx2 is None and \"FAISS_NO_AVX2\" in os.environ:\n        no_avx2 = bool(os.getenv(\"FAISS_NO_AVX2\"))\n    try:\n        if no_avx2:\n            from faiss import swigfaiss as faiss\n        else:\n            import faiss\n    except ImportError:\n        raise ImportError(\n            \"Could not import faiss python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-1", "text": "raise ImportError(\n            \"Could not import faiss python package. \"\n            \"Please install it with `pip install faiss-gpu` (for CUDA supported GPU) \"\n            \"or `pip install faiss-cpu` (depending on Python version).\"\n        )\n    return faiss\ndef _len_check_if_sized(x: Any, y: Any, x_name: str, y_name: str) -> None:\n    if isinstance(x, Sized) and isinstance(y, Sized) and len(x) != len(y):\n        raise ValueError(\n            f\"{x_name} and {y_name} expected to be equal length but \"\n            f\"len({x_name})={len(x)} and len({y_name})={len(y)}\"\n        )\n    return\n[docs]class FAISS(VectorStore):\n    \"\"\"`Meta Faiss` vector store.\n    To use, you must have the ``faiss`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            from langchain.vectorstores import FAISS\n            embeddings = OpenAIEmbeddings()\n            texts = [\"FAISS is an important library\", \"LangChain supports FAISS\"]\n            faiss = FAISS.from_texts(texts, embeddings)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding_function: Union[\n            Callable[[str], List[float]],\n            Embeddings,\n        ],\n        index: Any,\n        docstore: Docstore,\n        index_to_docstore_id: Dict[int, str],\n        relevance_score_fn: Optional[Callable[[float], float]] = None,\n        normalize_L2: bool = False,\n        distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE,\n    ):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-2", "text": "distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE,\n    ):\n        \"\"\"Initialize with necessary components.\"\"\"\n        if not isinstance(embedding_function, Embeddings):\n            logger.warning(\n                \"`embedding_function` is expected to be an Embeddings object, support \"\n                \"for passing in a function will soon be removed.\"\n            )\n        self.embedding_function = embedding_function\n        self.index = index\n        self.docstore = docstore\n        self.index_to_docstore_id = index_to_docstore_id\n        self.distance_strategy = distance_strategy\n        self.override_relevance_score_fn = relevance_score_fn\n        self._normalize_L2 = normalize_L2\n        if (\n            self.distance_strategy != DistanceStrategy.EUCLIDEAN_DISTANCE\n            and self._normalize_L2\n        ):\n            warnings.warn(\n                \"Normalizing L2 is not applicable for metric type: {strategy}\".format(\n                    strategy=self.distance_strategy\n                )\n            )\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return (\n            self.embedding_function\n            if isinstance(self.embedding_function, Embeddings)\n            else None\n        )\n    def _embed_documents(self, texts: List[str]) -> List[List[float]]:\n        if isinstance(self.embedding_function, Embeddings):\n            return self.embedding_function.embed_documents(texts)\n        else:\n            return [self.embedding_function(text) for text in texts]\n    async def _aembed_documents(self, texts: List[str]) -> List[List[float]]:\n        if isinstance(self.embedding_function, Embeddings):\n            return await self.embedding_function.aembed_documents(texts)\n        else:\n            # return await asyncio.gather(\n            #     [self.embedding_function(text) for text in texts]\n            # )\n            raise Exception(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-3", "text": "# )\n            raise Exception(\n                \"`embedding_function` is expected to be an Embeddings object, support \"\n                \"for passing in a function will soon be removed.\"\n            )\n    def _embed_query(self, text: str) -> List[float]:\n        if isinstance(self.embedding_function, Embeddings):\n            return self.embedding_function.embed_query(text)\n        else:\n            return self.embedding_function(text)\n    async def _aembed_query(self, text: str) -> List[float]:\n        if isinstance(self.embedding_function, Embeddings):\n            return await self.embedding_function.aembed_query(text)\n        else:\n            # return await self.embedding_function(text)\n            raise Exception(\n                \"`embedding_function` is expected to be an Embeddings object, support \"\n                \"for passing in a function will soon be removed.\"\n            )\n    def __add(\n        self,\n        texts: Iterable[str],\n        embeddings: Iterable[List[float]],\n        metadatas: Optional[Iterable[dict]] = None,\n        ids: Optional[List[str]] = None,\n    ) -> List[str]:\n        faiss = dependable_faiss_import()\n        if not isinstance(self.docstore, AddableMixin):\n            raise ValueError(\n                \"If trying to add texts, the underlying docstore should support \"\n                f\"adding items, which {self.docstore} does not\"\n            )\n        _len_check_if_sized(texts, metadatas, \"texts\", \"metadatas\")\n        _metadatas = metadatas or ({} for _ in texts)\n        documents = [\n            Document(page_content=t, metadata=m) for t, m in zip(texts, _metadatas)\n        ]\n        _len_check_if_sized(documents, embeddings, \"documents\", \"embeddings\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-4", "text": "_len_check_if_sized(documents, embeddings, \"documents\", \"embeddings\")\n        _len_check_if_sized(documents, ids, \"documents\", \"ids\")\n        # Add to the index.\n        vector = np.array(embeddings, dtype=np.float32)\n        if self._normalize_L2:\n            faiss.normalize_L2(vector)\n        self.index.add(vector)\n        # Add information to docstore and index.\n        ids = ids or [str(uuid.uuid4()) for _ in texts]\n        self.docstore.add({id_: doc for id_, doc in zip(ids, documents)})\n        starting_len = len(self.index_to_docstore_id)\n        index_to_id = {starting_len + j: id_ for j, id_ in enumerate(ids)}\n        self.index_to_docstore_id.update(index_to_id)\n        return ids\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of unique IDs.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        texts = list(texts)\n        embeddings = self._embed_documents(texts)\n        return self.__add(texts, embeddings, metadatas=metadatas, ids=ids)\n[docs]    async def aadd_texts(\n        self,\n        texts: Iterable[str],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-5", "text": "self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore\n            asynchronously.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of unique IDs.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        texts = list(texts)\n        embeddings = await self._aembed_documents(texts)\n        return self.__add(texts, embeddings, metadatas=metadatas, ids=ids)\n[docs]    def add_embeddings(\n        self,\n        text_embeddings: Iterable[Tuple[str, List[float]]],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add the given texts and embeddings to the vectorstore.\n        Args:\n            text_embeddings: Iterable pairs of string and embedding to\n                add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of unique IDs.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        # Embed and create the documents.\n        texts, embeddings = zip(*text_embeddings)\n        return self.__add(texts, embeddings, metadatas=metadatas, ids=ids)\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-6", "text": "self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            embedding: Embedding vector to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, Any]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n            **kwargs: kwargs to be passed to similarity search. Can include:\n                score_threshold: Optional, a floating point value between 0 to 1 to\n                    filter the resulting set of retrieved docs\n        Returns:\n            List of documents most similar to the query text and L2 distance\n            in float for each. Lower score represents more similarity.\n        \"\"\"\n        faiss = dependable_faiss_import()\n        vector = np.array([embedding], dtype=np.float32)\n        if self._normalize_L2:\n            faiss.normalize_L2(vector)\n        scores, indices = self.index.search(vector, k if filter is None else fetch_k)\n        docs = []\n        for j, i in enumerate(indices[0]):\n            if i == -1:\n                # This happens when not enough docs are returned.\n                continue\n            _id = self.index_to_docstore_id[i]\n            doc = self.docstore.search(_id)\n            if not isinstance(doc, Document):\n                raise ValueError(f\"Could not find document for id {_id}, got {doc}\")\n            if filter is not None:\n                filter = {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-7", "text": "if filter is not None:\n                filter = {\n                    key: [value] if not isinstance(value, list) else value\n                    for key, value in filter.items()\n                }\n                if all(doc.metadata.get(key) in value for key, value in filter.items()):\n                    docs.append((doc, scores[0][j]))\n            else:\n                docs.append((doc, scores[0][j]))\n        score_threshold = kwargs.get(\"score_threshold\")\n        if score_threshold is not None:\n            cmp = (\n                operator.ge\n                if self.distance_strategy\n                in (DistanceStrategy.MAX_INNER_PRODUCT, DistanceStrategy.JACCARD)\n                else operator.le\n            )\n            docs = [\n                (doc, similarity)\n                for doc, similarity in docs\n                if cmp(similarity, score_threshold)\n            ]\n        return docs[:k]\n[docs]    async def asimilarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query asynchronously.\n        Args:\n            embedding: Embedding vector to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, Any]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n            **kwargs: kwargs to be passed to similarity search. Can include:\n                score_threshold: Optional, a floating point value between 0 to 1 to", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-8", "text": "score_threshold: Optional, a floating point value between 0 to 1 to\n                    filter the resulting set of retrieved docs\n        Returns:\n            List of documents most similar to the query text and L2 distance\n            in float for each. Lower score represents more similarity.\n        \"\"\"\n        # This is a temporary workaround to make the similarity search asynchronous.\n        func = partial(\n            self.similarity_search_with_score_by_vector,\n            embedding,\n            k=k,\n            filter=filter,\n            fetch_k=fetch_k,\n            **kwargs,\n        )\n        return await asyncio.get_event_loop().run_in_executor(None, func)\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n        Returns:\n            List of documents most similar to the query text with\n            L2 distance in float. Lower score represents more similarity.\n        \"\"\"\n        embedding = self._embed_query(query)\n        docs = self.similarity_search_with_score_by_vector(\n            embedding,\n            k,\n            filter=filter,\n            fetch_k=fetch_k,\n            **kwargs,\n        )\n        return docs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-9", "text": "fetch_k=fetch_k,\n            **kwargs,\n        )\n        return docs\n[docs]    async def asimilarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query asynchronously.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n        Returns:\n            List of documents most similar to the query text with\n            L2 distance in float. Lower score represents more similarity.\n        \"\"\"\n        embedding = await self._aembed_query(query)\n        docs = await self.asimilarity_search_with_score_by_vector(\n            embedding,\n            k,\n            filter=filter,\n            fetch_k=fetch_k,\n            **kwargs,\n        )\n        return docs\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-10", "text": "k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n        Returns:\n            List of Documents most similar to the embedding.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score_by_vector(\n            embedding,\n            k,\n            filter=filter,\n            fetch_k=fetch_k,\n            **kwargs,\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    async def asimilarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector asynchronously.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n        Returns:\n            List of Documents most similar to the embedding.\n        \"\"\"\n        docs_and_scores = await self.asimilarity_search_with_score_by_vector(\n            embedding,\n            k,\n            filter=filter,\n            fetch_k=fetch_k,\n            **kwargs,\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search(\n        self,\n        query: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-11", "text": "[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(\n            query, k, filter=filter, fetch_k=fetch_k, **kwargs\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    async def asimilarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query asynchronously.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter: (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n            fetch_k: (Optional[int]) Number of Documents to fetch before filtering.\n                      Defaults to 20.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-12", "text": "Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        docs_and_scores = await self.asimilarity_search_with_score(\n            query, k, filter=filter, fetch_k=fetch_k, **kwargs\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def max_marginal_relevance_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        *,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, Any]] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs and their similarity scores selected using the maximal marginal\n            relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch before filtering to\n                     pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents and similarity scores selected by maximal marginal\n                relevance and score for each.\n        \"\"\"\n        scores, indices = self.index.search(\n            np.array([embedding], dtype=np.float32),\n            fetch_k if filter is None else fetch_k * 2,\n        )\n        if filter is not None:\n            filtered_indices = []\n            for i in indices[0]:\n                if i == -1:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-13", "text": "for i in indices[0]:\n                if i == -1:\n                    # This happens when not enough docs are returned.\n                    continue\n                _id = self.index_to_docstore_id[i]\n                doc = self.docstore.search(_id)\n                if not isinstance(doc, Document):\n                    raise ValueError(f\"Could not find document for id {_id}, got {doc}\")\n                if all(\n                    doc.metadata.get(key) in value\n                    if isinstance(value, list)\n                    else doc.metadata.get(key) == value\n                    for key, value in filter.items()\n                ):\n                    filtered_indices.append(i)\n            indices = np.array([filtered_indices])\n        # -1 happens when not enough docs are returned.\n        embeddings = [self.index.reconstruct(int(i)) for i in indices[0] if i != -1]\n        mmr_selected = maximal_marginal_relevance(\n            np.array([embedding], dtype=np.float32),\n            embeddings,\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        selected_indices = [indices[0][i] for i in mmr_selected]\n        selected_scores = [scores[0][i] for i in mmr_selected]\n        docs_and_scores = []\n        for i, score in zip(selected_indices, selected_scores):\n            if i == -1:\n                # This happens when not enough docs are returned.\n                continue\n            _id = self.index_to_docstore_id[i]\n            doc = self.docstore.search(_id)\n            if not isinstance(doc, Document):\n                raise ValueError(f\"Could not find document for id {_id}, got {doc}\")\n            docs_and_scores.append((doc, score))\n        return docs_and_scores\n[docs]    async def amax_marginal_relevance_search_with_score_by_vector(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-14", "text": "[docs]    async def amax_marginal_relevance_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        *,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, Any]] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs and their similarity scores selected using the maximal marginal\n            relevance asynchronously.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch before filtering to\n                     pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents and similarity scores selected by maximal marginal\n                relevance and score for each.\n        \"\"\"\n        # This is a temporary workaround to make the similarity search asynchronous.\n        func = partial(\n            self.max_marginal_relevance_search_with_score_by_vector,\n            embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n        )\n        return await asyncio.get_event_loop().run_in_executor(None, func)\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-15", "text": "k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch before filtering to\n                     pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        docs_and_scores = self.max_marginal_relevance_search_with_score_by_vector(\n            embedding, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, filter=filter\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    async def amax_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance asynchronously.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-16", "text": "among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch before filtering to\n                     pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        docs_and_scores = (\n            await self.amax_marginal_relevance_search_with_score_by_vector(\n                embedding, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, filter=filter\n            )\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch before filtering (if needed) to\n                     pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-17", "text": "of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        embedding = self._embed_query(query)\n        docs = self.max_marginal_relevance_search_by_vector(\n            embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n            **kwargs,\n        )\n        return docs\n[docs]    async def amax_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance asynchronously.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch before filtering (if needed) to\n                     pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        embedding = await self._aembed_query(query)\n        docs = await self.amax_marginal_relevance_search_by_vector(\n            embedding,\n            k=k,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-18", "text": "embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n            **kwargs,\n        )\n        return docs\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:\n        \"\"\"Delete by ID. These are the IDs in the vectorstore.\n        Args:\n            ids: List of ids to delete.\n        Returns:\n            Optional[bool]: True if deletion is successful,\n            False otherwise, None if not implemented.\n        \"\"\"\n        if ids is None:\n            raise ValueError(\"No ids provided to delete.\")\n        missing_ids = set(ids).difference(self.index_to_docstore_id.values())\n        if missing_ids:\n            raise ValueError(\n                f\"Some specified ids do not exist in the current store. Ids not found: \"\n                f\"{missing_ids}\"\n            )\n        reversed_index = {id_: idx for idx, id_ in self.index_to_docstore_id.items()}\n        index_to_delete = [reversed_index[id_] for id_ in ids]\n        self.index.remove_ids(np.array(index_to_delete, dtype=np.int64))\n        self.docstore.delete(ids)\n        remaining_ids = [\n            id_\n            for i, id_ in sorted(self.index_to_docstore_id.items())\n            if i not in index_to_delete\n        ]\n        self.index_to_docstore_id = {i: id_ for i, id_ in enumerate(remaining_ids)}\n        return True\n[docs]    def merge_from(self, target: FAISS) -> None:\n        \"\"\"Merge another FAISS object with the current one.\n        Add the target FAISS to the current one.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-19", "text": "Add the target FAISS to the current one.\n        Args:\n            target: FAISS object you wish to merge into the current one\n        Returns:\n            None.\n        \"\"\"\n        if not isinstance(self.docstore, AddableMixin):\n            raise ValueError(\"Cannot merge with this type of docstore\")\n        # Numerical index for target docs are incremental on existing ones\n        starting_len = len(self.index_to_docstore_id)\n        # Merge two IndexFlatL2\n        self.index.merge_from(target.index)\n        # Get id and docs from target FAISS object\n        full_info = []\n        for i, target_id in target.index_to_docstore_id.items():\n            doc = target.docstore.search(target_id)\n            if not isinstance(doc, Document):\n                raise ValueError(\"Document should be returned\")\n            full_info.append((starting_len + i, target_id, doc))\n        # Add information to docstore and index_to_docstore_id.\n        self.docstore.add({_id: doc for _, _id, doc in full_info})\n        index_to_id = {index: _id for index, _id, _ in full_info}\n        self.index_to_docstore_id.update(index_to_id)\n    @classmethod\n    def __from(\n        cls,\n        texts: Iterable[str],\n        embeddings: List[List[float]],\n        embedding: Embeddings,\n        metadatas: Optional[Iterable[dict]] = None,\n        ids: Optional[List[str]] = None,\n        normalize_L2: bool = False,\n        distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE,\n        **kwargs: Any,\n    ) -> FAISS:\n        faiss = dependable_faiss_import()\n        if distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-20", "text": "if distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:\n            index = faiss.IndexFlatIP(len(embeddings[0]))\n        else:\n            # Default to L2, currently other metric types not initialized.\n            index = faiss.IndexFlatL2(len(embeddings[0]))\n        vecstore = cls(\n            embedding,\n            index,\n            InMemoryDocstore(),\n            {},\n            normalize_L2=normalize_L2,\n            distance_strategy=distance_strategy,\n            **kwargs,\n        )\n        vecstore.__add(texts, embeddings, metadatas=metadatas, ids=ids)\n        return vecstore\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> FAISS:\n        \"\"\"Construct FAISS wrapper from raw documents.\n        This is a user friendly interface that:\n            1. Embeds documents.\n            2. Creates an in memory docstore\n            3. Initializes the FAISS database\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import FAISS\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                faiss = FAISS.from_texts(texts, embeddings)\n        \"\"\"\n        embeddings = embedding.embed_documents(texts)\n        return cls.__from(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            **kwargs,\n        )\n[docs]    @classmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-21", "text": "**kwargs,\n        )\n[docs]    @classmethod\n    async def afrom_texts(\n        cls,\n        texts: list[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> FAISS:\n        \"\"\"Construct FAISS wrapper from raw documents asynchronously.\n        This is a user friendly interface that:\n            1. Embeds documents.\n            2. Creates an in memory docstore\n            3. Initializes the FAISS database\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import FAISS\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                faiss = await FAISS.afrom_texts(texts, embeddings)\n        \"\"\"\n        embeddings = await embedding.aembed_documents(texts)\n        return cls.__from(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_embeddings(\n        cls,\n        text_embeddings: Iterable[Tuple[str, List[float]]],\n        embedding: Embeddings,\n        metadatas: Optional[Iterable[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> FAISS:\n        \"\"\"Construct FAISS wrapper from raw documents.\n        This is a user friendly interface that:\n            1. Embeds documents.\n            2. Creates an in memory docstore\n            3. Initializes the FAISS database", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-22", "text": "3. Initializes the FAISS database\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import FAISS\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                text_embeddings = embeddings.embed_documents(texts)\n                text_embedding_pairs = zip(texts, text_embeddings)\n                faiss = FAISS.from_embeddings(text_embedding_pairs, embeddings)\n        \"\"\"\n        texts = [t[0] for t in text_embeddings]\n        embeddings = [t[1] for t in text_embeddings]\n        return cls.__from(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            **kwargs,\n        )\n[docs]    @classmethod\n    async def afrom_embeddings(\n        cls,\n        text_embeddings: Iterable[Tuple[str, List[float]]],\n        embedding: Embeddings,\n        metadatas: Optional[Iterable[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> FAISS:\n        \"\"\"Construct FAISS wrapper from raw documents asynchronously.\"\"\"\n        return cls.from_embeddings(\n            text_embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            **kwargs,\n        )\n[docs]    def save_local(self, folder_path: str, index_name: str = \"index\") -> None:\n        \"\"\"Save FAISS index, docstore, and index_to_docstore_id to disk.\n        Args:\n            folder_path: folder path to save index, docstore,\n                and index_to_docstore_id to.\n            index_name: for saving with a specific index file name", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-23", "text": "index_name: for saving with a specific index file name\n        \"\"\"\n        path = Path(folder_path)\n        path.mkdir(exist_ok=True, parents=True)\n        # save index separately since it is not picklable\n        faiss = dependable_faiss_import()\n        faiss.write_index(\n            self.index, str(path / \"{index_name}.faiss\".format(index_name=index_name))\n        )\n        # save docstore and index_to_docstore_id\n        with open(path / \"{index_name}.pkl\".format(index_name=index_name), \"wb\") as f:\n            pickle.dump((self.docstore, self.index_to_docstore_id), f)\n[docs]    @classmethod\n    def load_local(\n        cls,\n        folder_path: str,\n        embeddings: Embeddings,\n        index_name: str = \"index\",\n        **kwargs: Any,\n    ) -> FAISS:\n        \"\"\"Load FAISS index, docstore, and index_to_docstore_id from disk.\n        Args:\n            folder_path: folder path to load index, docstore,\n                and index_to_docstore_id from.\n            embeddings: Embeddings to use when generating queries\n            index_name: for saving with a specific index file name\n            asynchronous: whether to use async version or not\n        \"\"\"\n        path = Path(folder_path)\n        # load index separately since it is not picklable\n        faiss = dependable_faiss_import()\n        index = faiss.read_index(\n            str(path / \"{index_name}.faiss\".format(index_name=index_name))\n        )\n        # load docstore and index_to_docstore_id\n        with open(path / \"{index_name}.pkl\".format(index_name=index_name), \"rb\") as f:\n            docstore, index_to_docstore_id = pickle.load(f)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-24", "text": "docstore, index_to_docstore_id = pickle.load(f)\n        return cls(embeddings, index, docstore, index_to_docstore_id, **kwargs)\n[docs]    def serialize_to_bytes(self) -> bytes:\n        \"\"\"Serialize FAISS index, docstore, and index_to_docstore_id to bytes.\"\"\"\n        return pickle.dumps((self.index, self.docstore, self.index_to_docstore_id))\n[docs]    @classmethod\n    def deserialize_from_bytes(\n        cls,\n        serialized: bytes,\n        embeddings: Embeddings,\n        **kwargs: Any,\n    ) -> FAISS:\n        \"\"\"Deserialize FAISS index, docstore, and index_to_docstore_id from bytes.\"\"\"\n        index, docstore, index_to_docstore_id = pickle.loads(serialized)\n        return cls(embeddings, index, docstore, index_to_docstore_id, **kwargs)\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        \"\"\"\n        The 'correct' relevance function\n        may differ depending on a few things, including:\n        - the distance / similarity metric used by the VectorStore\n        - the scale of your embeddings (OpenAI's are unit normed. Many others are not!)\n        - embedding dimensionality\n        - etc.\n        \"\"\"\n        if self.override_relevance_score_fn is not None:\n            return self.override_relevance_score_fn\n        # Default strategy is to rely on distance strategy provided in\n        # vectorstore constructor\n        if self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:\n            return self._max_inner_product_relevance_score_fn\n        elif self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE:\n            # Default behavior is to use euclidean distance relevancy\n            return self._euclidean_relevance_score_fn", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-25", "text": "return self._euclidean_relevance_score_fn\n        elif self.distance_strategy == DistanceStrategy.COSINE:\n            return self._cosine_relevance_score_fn\n        else:\n            raise ValueError(\n                \"Unknown distance strategy, must be cosine, max_inner_product,\"\n                \" or euclidean\"\n            )\n    def _similarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs and their similarity scores on a scale from 0 to 1.\"\"\"\n        # Pop score threshold so that only relevancy scores, not raw scores, are\n        # filtered.\n        relevance_score_fn = self._select_relevance_score_fn()\n        if relevance_score_fn is None:\n            raise ValueError(\n                \"normalize_score_fn must be provided to\"\n                \" FAISS constructor to normalize scores\"\n            )\n        docs_and_scores = self.similarity_search_with_score(\n            query,\n            k=k,\n            filter=filter,\n            fetch_k=fetch_k,\n            **kwargs,\n        )\n        docs_and_rel_scores = [\n            (doc, relevance_score_fn(score)) for doc, score in docs_and_scores\n        ]\n        return docs_and_rel_scores\n    async def _asimilarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[Dict[str, Any]] = None,\n        fetch_k: int = 20,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c16601bbdd12-26", "text": "**kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs and their similarity scores on a scale from 0 to 1.\"\"\"\n        # Pop score threshold so that only relevancy scores, not raw scores, are\n        # filtered.\n        relevance_score_fn = self._select_relevance_score_fn()\n        if relevance_score_fn is None:\n            raise ValueError(\n                \"normalize_score_fn must be provided to\"\n                \" FAISS constructor to normalize scores\"\n            )\n        docs_and_scores = await self.asimilarity_search_with_score(\n            query,\n            k=k,\n            filter=filter,\n            fetch_k=fetch_k,\n            **kwargs,\n        )\n        docs_and_rel_scores = [\n            (doc, relevance_score_fn(score)) for doc, score in docs_and_scores\n        ]\n        return docs_and_rel_scores", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html"}
{"id": "c26e5ec88402-0", "text": "Source code for langchain.vectorstores.vectara\nfrom __future__ import annotations\nimport json\nimport logging\nimport os\nfrom hashlib import md5\nfrom typing import Any, Iterable, List, Optional, Tuple, Type\nimport requests\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore, VectorStoreRetriever\nlogger = logging.getLogger(__name__)\n[docs]class Vectara(VectorStore):\n    \"\"\"`Vectara API` vector store.\n     See (https://vectara.com).\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import Vectara\n            vectorstore = Vectara(\n                vectara_customer_id=vectara_customer_id,\n                vectara_corpus_id=vectara_corpus_id,\n                vectara_api_key=vectara_api_key\n            )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        vectara_customer_id: Optional[str] = None,\n        vectara_corpus_id: Optional[str] = None,\n        vectara_api_key: Optional[str] = None,\n        vectara_api_timeout: int = 60,\n        source: str = \"langchain\",\n    ):\n        \"\"\"Initialize with Vectara API.\"\"\"\n        self._vectara_customer_id = vectara_customer_id or os.environ.get(\n            \"VECTARA_CUSTOMER_ID\"\n        )\n        self._vectara_corpus_id = vectara_corpus_id or os.environ.get(\n            \"VECTARA_CORPUS_ID\"\n        )\n        self._vectara_api_key = vectara_api_key or os.environ.get(\"VECTARA_API_KEY\")\n        if (\n            self._vectara_customer_id is None\n            or self._vectara_corpus_id is None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html"}
{"id": "c26e5ec88402-1", "text": "or self._vectara_corpus_id is None\n            or self._vectara_api_key is None\n        ):\n            logger.warning(\n                \"Can't find Vectara credentials, customer_id or corpus_id in \"\n                \"environment.\"\n            )\n        else:\n            logger.debug(f\"Using corpus id {self._vectara_corpus_id}\")\n        self._source = source\n        self._session = requests.Session()  # to reuse connections\n        adapter = requests.adapters.HTTPAdapter(max_retries=3)\n        self._session.mount(\"http://\", adapter)\n        self.vectara_api_timeout = vectara_api_timeout\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return None\n    def _get_post_headers(self) -> dict:\n        \"\"\"Returns headers that should be attached to each post request.\"\"\"\n        return {\n            \"x-api-key\": self._vectara_api_key,\n            \"customer-id\": self._vectara_customer_id,\n            \"Content-Type\": \"application/json\",\n            \"X-Source\": self._source,\n        }\n    def _delete_doc(self, doc_id: str) -> bool:\n        \"\"\"\n        Delete a document from the Vectara corpus.\n        Args:\n            url (str): URL of the page to delete.\n            doc_id (str): ID of the document to delete.\n        Returns:\n            bool: True if deletion was successful, False otherwise.\n        \"\"\"\n        body = {\n            \"customer_id\": self._vectara_customer_id,\n            \"corpus_id\": self._vectara_corpus_id,\n            \"document_id\": doc_id,\n        }\n        response = self._session.post(\n            \"https://api.vectara.io/v1/delete-doc\",\n            data=json.dumps(body),\n            verify=True,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html"}
{"id": "c26e5ec88402-2", "text": "data=json.dumps(body),\n            verify=True,\n            headers=self._get_post_headers(),\n            timeout=self.vectara_api_timeout,\n        )\n        if response.status_code != 200:\n            logger.error(\n                f\"Delete request failed for doc_id = {doc_id} with status code \"\n                f\"{response.status_code}, reason {response.reason}, text \"\n                f\"{response.text}\"\n            )\n            return False\n        return True\n    def _index_doc(self, doc: dict) -> str:\n        request: dict[str, Any] = {}\n        request[\"customer_id\"] = self._vectara_customer_id\n        request[\"corpus_id\"] = self._vectara_corpus_id\n        request[\"document\"] = doc\n        response = self._session.post(\n            headers=self._get_post_headers(),\n            url=\"https://api.vectara.io/v1/index\",\n            data=json.dumps(request),\n            timeout=self.vectara_api_timeout,\n            verify=True,\n        )\n        status_code = response.status_code\n        result = response.json()\n        status_str = result[\"status\"][\"code\"] if \"status\" in result else None\n        if status_code == 409 or status_str and (status_str == \"ALREADY_EXISTS\"):\n            return \"E_ALREADY_EXISTS\"\n        elif status_str and (status_str == \"FORBIDDEN\"):\n            return \"E_NO_PERMISSIONS\"\n        else:\n            return \"E_SUCCEEDED\"\n[docs]    def add_files(\n        self,\n        files_list: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"\n        Vectara provides a way to add documents directly via our API where", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html"}
{"id": "c26e5ec88402-3", "text": "\"\"\"\n        Vectara provides a way to add documents directly via our API where\n        pre-processing and chunking occurs internally in an optimal way\n        This method provides a way to use that API in LangChain\n        Args:\n            files_list: Iterable of strings, each representing a local file path.\n                    Files could be text, HTML, PDF, markdown, doc/docx, ppt/pptx, etc.\n                    see API docs for full list\n            metadatas: Optional list of metadatas associated with each file\n        Returns:\n            List of ids associated with each of the files indexed\n        \"\"\"\n        doc_ids = []\n        for inx, file in enumerate(files_list):\n            if not os.path.exists(file):\n                logger.error(f\"File {file} does not exist, skipping\")\n                continue\n            md = metadatas[inx] if metadatas else {}\n            files: dict = {\n                \"file\": (file, open(file, \"rb\")),\n                \"doc_metadata\": json.dumps(md),\n            }\n            headers = self._get_post_headers()\n            headers.pop(\"Content-Type\")\n            response = self._session.post(\n                f\"https://api.vectara.io/upload?c={self._vectara_customer_id}&o={self._vectara_corpus_id}&d=True\",\n                files=files,\n                verify=True,\n                headers=headers,\n                timeout=self.vectara_api_timeout,\n            )\n            if response.status_code == 409:\n                doc_id = response.json()[\"document\"][\"documentId\"]\n                logger.info(\n                    f\"File {file} already exists on Vectara (doc_id={doc_id}), skipping\"\n                )\n            elif response.status_code == 200:\n                doc_id = response.json()[\"document\"][\"documentId\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html"}
{"id": "c26e5ec88402-4", "text": "doc_id = response.json()[\"document\"][\"documentId\"]\n                doc_ids.append(doc_id)\n            else:\n                logger.info(f\"Error indexing file {file}: {response.json()}\")\n        return doc_ids\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        doc_metadata: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            doc_metadata: optional metadata for the document\n        This function indexes all the input text strings in the Vectara corpus as a\n        single Vectara document, where each input text is considered a \"section\" and the\n        metadata are associated with each section.\n        if 'doc_metadata' is provided, it is associated with the Vectara document.\n        Returns:\n            document ID of the document added\n        \"\"\"\n        doc_hash = md5()\n        for t in texts:\n            doc_hash.update(t.encode())\n        doc_id = doc_hash.hexdigest()\n        if metadatas is None:\n            metadatas = [{} for _ in texts]\n        if doc_metadata:\n            doc_metadata[\"source\"] = \"langchain\"\n        else:\n            doc_metadata = {\"source\": \"langchain\"}\n        doc = {\n            \"document_id\": doc_id,\n            \"metadataJson\": json.dumps(doc_metadata),\n            \"section\": [\n                {\"text\": text, \"metadataJson\": json.dumps(md)}\n                for text, md in zip(texts, metadatas)\n            ],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html"}
{"id": "c26e5ec88402-5", "text": "for text, md in zip(texts, metadatas)\n            ],\n        }\n        success_str = self._index_doc(doc)\n        if success_str == \"E_ALREADY_EXISTS\":\n            self._delete_doc(doc_id)\n            self._index_doc(doc)\n        elif success_str == \"E_NO_PERMISSIONS\":\n            print(\n                \"\"\"No permissions to add document to Vectara. \n                Check your corpus ID, customer ID and API key\"\"\"\n            )\n        return [doc_id]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 5,\n        lambda_val: float = 0.025,\n        filter: Optional[str] = None,\n        score_threshold: Optional[float] = None,\n        n_sentence_context: int = 2,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return Vectara documents most similar to query, along with scores.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 5.\n            lambda_val: lexical match parameter for hybrid search.\n            filter: Dictionary of argument(s) to filter on metadata. For example a\n                filter can be \"doc.rating > 3.0 and part.lang = 'deu'\"} see\n                https://docs.vectara.com/docs/search-apis/sql/filter-overview\n                for more details.\n            score_threshold: minimal score threshold for the result.\n                If defined, results with score less than this value will be\n                filtered out.\n            n_sentence_context: number of sentences before/after the matching segment\n                to add, defaults to 2\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html"}
{"id": "c26e5ec88402-6", "text": "to add, defaults to 2\n        Returns:\n            List of Documents most similar to the query and score for each.\n        \"\"\"\n        data = json.dumps(\n            {\n                \"query\": [\n                    {\n                        \"query\": query,\n                        \"start\": 0,\n                        \"num_results\": k,\n                        \"context_config\": {\n                            \"sentences_before\": n_sentence_context,\n                            \"sentences_after\": n_sentence_context,\n                        },\n                        \"corpus_key\": [\n                            {\n                                \"customer_id\": self._vectara_customer_id,\n                                \"corpus_id\": self._vectara_corpus_id,\n                                \"metadataFilter\": filter,\n                                \"lexical_interpolation_config\": {\"lambda\": lambda_val},\n                            }\n                        ],\n                    }\n                ]\n            }\n        )\n        response = self._session.post(\n            headers=self._get_post_headers(),\n            url=\"https://api.vectara.io/v1/query\",\n            data=data,\n            timeout=self.vectara_api_timeout,\n        )\n        if response.status_code != 200:\n            logger.error(\n                \"Query failed %s\",\n                f\"(code {response.status_code}, reason {response.reason}, details \"\n                f\"{response.text})\",\n            )\n            return []\n        result = response.json()\n        if score_threshold:\n            responses = [\n                r\n                for r in result[\"responseSet\"][0][\"response\"]\n                if r[\"score\"] > score_threshold\n            ]\n        else:\n            responses = result[\"responseSet\"][0][\"response\"]\n        documents = result[\"responseSet\"][0][\"document\"]\n        metadatas = []\n        for x in responses:\n            md = {m[\"name\"]: m[\"value\"] for m in x[\"metadata\"]}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html"}
{"id": "c26e5ec88402-7", "text": "md = {m[\"name\"]: m[\"value\"] for m in x[\"metadata\"]}\n            doc_num = x[\"documentIndex\"]\n            doc_md = {m[\"name\"]: m[\"value\"] for m in documents[doc_num][\"metadata\"]}\n            md.update(doc_md)\n            metadatas.append(md)\n        docs_with_score = [\n            (\n                Document(\n                    page_content=x[\"text\"],\n                    metadata=md,\n                ),\n                x[\"score\"],\n            )\n            for x, md in zip(responses, metadatas)\n        ]\n        return docs_with_score\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 5,\n        lambda_val: float = 0.025,\n        filter: Optional[str] = None,\n        n_sentence_context: int = 2,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return Vectara documents most similar to query, along with scores.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 5.\n            filter: Dictionary of argument(s) to filter on metadata. For example a\n                filter can be \"doc.rating > 3.0 and part.lang = 'deu'\"} see\n                https://docs.vectara.com/docs/search-apis/sql/filter-overview for more\n                details.\n            n_sentence_context: number of sentences before/after the matching segment\n                to add, defaults to 2\n        Returns:\n            List of Documents most similar to the query\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(\n            query,\n            k=k,\n            lambda_val=lambda_val,\n            filter=filter,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html"}
{"id": "c26e5ec88402-8", "text": "k=k,\n            lambda_val=lambda_val,\n            filter=filter,\n            score_threshold=None,\n            n_sentence_context=n_sentence_context,\n            **kwargs,\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[Vectara],\n        texts: List[str],\n        embedding: Optional[Embeddings] = None,\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> Vectara:\n        \"\"\"Construct Vectara wrapper from raw documents.\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import Vectara\n                vectara = Vectara.from_texts(\n                    texts,\n                    vectara_customer_id=customer_id,\n                    vectara_corpus_id=corpus_id,\n                    vectara_api_key=api_key,\n                )\n        \"\"\"\n        # Notes:\n        # * Vectara generates its own embeddings, so we ignore the provided\n        #   embeddings (required by interface)\n        # * when metadatas[] are provided they are associated with each \"part\"\n        #   in Vectara. doc_metadata can be used to provide additional metadata\n        #   for the document itself (applies to all \"texts\" in this call)\n        doc_metadata = kwargs.pop(\"doc_metadata\", {})\n        vectara = cls(**kwargs)\n        vectara.add_texts(texts, metadatas, doc_metadata=doc_metadata, **kwargs)\n        return vectara\n[docs]    @classmethod\n    def from_files(\n        cls: Type[Vectara],\n        files: List[str],\n        embedding: Optional[Embeddings] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html"}
{"id": "c26e5ec88402-9", "text": "files: List[str],\n        embedding: Optional[Embeddings] = None,\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> Vectara:\n        \"\"\"Construct Vectara wrapper from raw documents.\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import Vectara\n                vectara = Vectara.from_files(\n                    files_list,\n                    vectara_customer_id=customer_id,\n                    vectara_corpus_id=corpus_id,\n                    vectara_api_key=api_key,\n                )\n        \"\"\"\n        # Note: Vectara generates its own embeddings, so we ignore the provided\n        # embeddings (required by interface)\n        vectara = cls(**kwargs)\n        vectara.add_files(files, metadatas)\n        return vectara\n[docs]    def as_retriever(self, **kwargs: Any) -> VectaraRetriever:\n        tags = kwargs.pop(\"tags\", None) or []\n        tags.extend(self._get_retriever_tags())\n        return VectaraRetriever(vectorstore=self, **kwargs, tags=tags)\n[docs]class VectaraRetriever(VectorStoreRetriever):\n    \"\"\"Retriever class for `Vectara`.\"\"\"\n    vectorstore: Vectara\n    \"\"\"Vectara vectorstore.\"\"\"\n    search_kwargs: dict = Field(\n        default_factory=lambda: {\n            \"lambda_val\": 0.025,\n            \"k\": 5,\n            \"filter\": \"\",\n            \"n_sentence_context\": \"2\",\n        }\n    )\n    \"\"\"Search params.\n        k: Number of Documents to return. Defaults to 5.\n        lambda_val: lexical match parameter for hybrid search.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html"}
{"id": "c26e5ec88402-10", "text": "lambda_val: lexical match parameter for hybrid search.\n        filter: Dictionary of argument(s) to filter on metadata. For example a\n            filter can be \"doc.rating > 3.0 and part.lang = 'deu'\"} see\n            https://docs.vectara.com/docs/search-apis/sql/filter-overview\n            for more details.\n        n_sentence_context: number of sentences before/after the matching segment to add\n    \"\"\"\n[docs]    def add_texts(\n        self,\n        texts: List[str],\n        metadatas: Optional[List[dict]] = None,\n        doc_metadata: Optional[dict] = None,\n    ) -> None:\n        \"\"\"Add text to the Vectara vectorstore.\n        Args:\n            texts (List[str]): The text\n            metadatas (List[dict]): Metadata dicts, must line up with existing store\n        \"\"\"\n        self.vectorstore.add_texts(texts, metadatas, doc_metadata or {})", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html"}
{"id": "cc4a876c20c3-0", "text": "Source code for langchain.vectorstores.vearch\nfrom __future__ import annotations\nimport os\nimport time\nimport uuid\nfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nif TYPE_CHECKING:\n    import vearch\nDEFAULT_TOPN = 4\n[docs]class Vearch(VectorStore):\n    _DEFAULT_TABLE_NAME = \"langchain_vearch\"\n    _DEFAULT_CLUSTER_DB_NAME = \"cluster_client_db\"\n    _DEFAULT_VERSION = 1\n[docs]    def __init__(\n        self,\n        embedding_function: Embeddings,\n        path_or_url: Optional[str] = None,\n        table_name: str = _DEFAULT_TABLE_NAME,\n        db_name: str = _DEFAULT_CLUSTER_DB_NAME,\n        flag: int = _DEFAULT_VERSION,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Initialize vearch vector store\n        flag 1 for cluster,0 for standalone\n        \"\"\"\n        try:\n            if flag:\n                import vearch_cluster\n            else:\n                import vearch\n        except ImportError:\n            raise ValueError(\n                \"Could not import suitable python package. \"\n                \"Please install it with `pip install vearch or vearch_cluster`.\"\n            )\n        if flag:\n            if path_or_url is None:\n                raise ValueError(\"Please input url of cluster\")\n            if not db_name:\n                db_name = self._DEFAULT_CLUSTER_DB_NAME\n                db_name += \"_\"\n                db_name += str(uuid.uuid4()).split(\"-\")[-1]\n            self.using_db_name = db_name\n            self.url = path_or_url", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html"}
{"id": "cc4a876c20c3-1", "text": "self.using_db_name = db_name\n            self.url = path_or_url\n            self.vearch = vearch_cluster.VearchCluster(path_or_url)\n        else:\n            if path_or_url is None:\n                metadata_path = os.getcwd().replace(\"\\\\\", \"/\")\n            else:\n                metadata_path = path_or_url\n            if not os.path.isdir(metadata_path):\n                os.makedirs(metadata_path)\n            log_path = os.path.join(metadata_path, \"log\")\n            if not os.path.isdir(log_path):\n                os.makedirs(log_path)\n            self.vearch = vearch.Engine(metadata_path, log_path)\n            self.using_metapath = metadata_path\n        if not table_name:\n            table_name = self._DEFAULT_TABLE_NAME\n            table_name += \"_\"\n            table_name += str(uuid.uuid4()).split(\"-\")[-1]\n        self.using_table_name = table_name\n        self.embedding_func = embedding_function\n        self.flag = flag\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return self.embedding_func\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[Vearch],\n        documents: List[Document],\n        embedding: Embeddings,\n        path_or_url: Optional[str] = None,\n        table_name: str = _DEFAULT_TABLE_NAME,\n        db_name: str = _DEFAULT_CLUSTER_DB_NAME,\n        flag: int = _DEFAULT_VERSION,\n        **kwargs: Any,\n    ) -> Vearch:\n        \"\"\"Return Vearch VectorStore\"\"\"\n        texts = [d.page_content for d in documents]\n        metadatas = [d.metadata for d in documents]\n        return cls.from_texts(\n            texts=texts,\n            embedding=embedding,\n            metadatas=metadatas,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html"}
{"id": "cc4a876c20c3-2", "text": "embedding=embedding,\n            metadatas=metadatas,\n            path_or_url=path_or_url,\n            table_name=table_name,\n            db_name=db_name,\n            flag=flag,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[Vearch],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        path_or_url: Optional[str] = None,\n        table_name: str = _DEFAULT_TABLE_NAME,\n        db_name: str = _DEFAULT_CLUSTER_DB_NAME,\n        flag: int = _DEFAULT_VERSION,\n        **kwargs: Any,\n    ) -> Vearch:\n        \"\"\"Return Vearch VectorStore\"\"\"\n        vearch_db = cls(\n            embedding_function=embedding,\n            embedding=embedding,\n            path_or_url=path_or_url,\n            db_name=db_name,\n            table_name=table_name,\n            flag=flag,\n        )\n        vearch_db.add_texts(texts=texts, metadatas=metadatas)\n        return vearch_db\n    def _create_table(\n        self,\n        dim: int = 1024,\n        field_list: List[dict] = [\n            {\"field\": \"text\", \"type\": \"str\"},\n            {\"field\": \"metadata\", \"type\": \"str\"},\n        ],\n    ) -> int:\n        \"\"\"\n        Create VectorStore Table\n        Args:\n            dim:dimension of vector\n            fields_list: the field you want to store\n        Return:\n            code,0 for success,1 for failed\n        \"\"\"\n        type_dict = {\"int\": vearch.dataType.INT, \"str\": vearch.dataType.STRING}\n        engine_info = {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html"}
{"id": "cc4a876c20c3-3", "text": "engine_info = {\n            \"index_size\": 10000,\n            \"retrieval_type\": \"IVFPQ\",\n            \"retrieval_param\": {\"ncentroids\": 2048, \"nsubvector\": 32},\n        }\n        fields = [\n            vearch.GammaFieldInfo(fi[\"field\"], type_dict[fi[\"type\"]])\n            for fi in field_list\n        ]\n        vector_field = vearch.GammaVectorInfo(\n            name=\"text_embedding\",\n            type=vearch.dataType.VECTOR,\n            is_index=True,\n            dimension=dim,\n            model_id=\"\",\n            store_type=\"MemoryOnly\",\n            store_param={\"cache_size\": 10000},\n            has_source=False,\n        )\n        response_code = self.vearch.create_table(\n            engine_info,\n            name=self.using_table_name,\n            fields=fields,\n            vector_field=vector_field,\n        )\n        return response_code\n    def _create_space(\n        self,\n        dim: int = 1024,\n    ) -> int:\n        \"\"\"\n        Create VectorStore space\n        Args:\n            dim:dimension of vector\n        Return:\n            code,0 failed for ,1 for success\n        \"\"\"\n        space_config = {\n            \"name\": self.using_table_name,\n            \"partition_num\": 1,\n            \"replica_num\": 1,\n            \"engine\": {\n                \"name\": \"gamma\",\n                \"index_size\": 1,\n                \"retrieval_type\": \"FLAT\",\n                \"retrieval_param\": {\n                    \"metric_type\": \"L2\",\n                },\n            },\n            \"properties\": {\n                \"text\": {\n                    \"type\": \"string\",\n                },", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html"}
{"id": "cc4a876c20c3-4", "text": "\"text\": {\n                    \"type\": \"string\",\n                },\n                \"metadata\": {\n                    \"type\": \"string\",\n                },\n                \"text_embedding\": {\n                    \"type\": \"vector\",\n                    \"index\": True,\n                    \"dimension\": dim,\n                    \"store_type\": \"MemoryOnly\",\n                },\n            },\n        }\n        response_code = self.vearch.create_space(self.using_db_name, space_config)\n        return response_code\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        embeddings = None\n        if self.embedding_func is not None:\n            embeddings = self.embedding_func.embed_documents(list(texts))\n        if embeddings is None:\n            raise ValueError(\"embeddings is None\")\n        if self.flag:\n            dbs_list = self.vearch.list_dbs()\n            if self.using_db_name not in dbs_list:\n                create_db_code = self.vearch.create_db(self.using_db_name)\n                if not create_db_code:\n                    raise ValueError(\"create db failed!!!\")\n            space_list = self.vearch.list_spaces(self.using_db_name)\n            if self.using_table_name not in space_list:\n                create_space_code = self._create_space(len(embeddings[0]))\n                if not create_space_code:\n                    raise ValueError(\"create space failed!!!\")\n            docid = []\n            if embeddings is not None and metadatas is not None:\n                for text, metadata, embed in zip(texts, metadatas, embeddings):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html"}
{"id": "cc4a876c20c3-5", "text": "for text, metadata, embed in zip(texts, metadatas, embeddings):\n                    profiles: dict[str, Any] = {}\n                    profiles[\"text\"] = text\n                    profiles[\"metadata\"] = metadata[\"source\"]\n                    embed_np = np.array(embed)\n                    profiles[\"text_embedding\"] = {\n                        \"feature\": (embed_np / np.linalg.norm(embed_np)).tolist()\n                    }\n                    insert_res = self.vearch.insert_one(\n                        self.using_db_name, self.using_table_name, profiles\n                    )\n                    if insert_res[\"status\"] == 200:\n                        docid.append(insert_res[\"_id\"])\n                        continue\n                    else:\n                        retry_insert = self.vearch.insert_one(\n                            self.using_db_name, self.using_table_name, profiles\n                        )\n                        docid.append(retry_insert[\"_id\"])\n                        continue\n        else:\n            table_path = os.path.join(\n                self.using_metapath, self.using_table_name + \".schema\"\n            )\n            if not os.path.exists(table_path):\n                dim = len(embeddings[0])\n                response_code = self._create_table(dim)\n                if response_code:\n                    raise ValueError(\"create table failed!!!\")\n            if embeddings is not None and metadatas is not None:\n                doc_items = []\n                for text, metadata, embed in zip(texts, metadatas, embeddings):\n                    profiles_v: dict[str, Any] = {}\n                    profiles_v[\"text\"] = text\n                    profiles_v[\"metadata\"] = metadata[\"source\"]\n                    embed_np = np.array(embed)\n                    profiles_v[\"text_embedding\"] = embed_np / np.linalg.norm(embed_np)\n                    doc_items.append(profiles_v)\n                docid = self.vearch.add(doc_items)\n                t_time = 0", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html"}
{"id": "cc4a876c20c3-6", "text": "docid = self.vearch.add(doc_items)\n                t_time = 0\n                while len(docid) != len(embeddings):\n                    time.sleep(0.5)\n                    if t_time > 6:\n                        break\n                    t_time += 1\n                self.vearch.dump()\n        return docid\n    def _load(self) -> None:\n        \"\"\"\n        load vearch engine for standalone vearch\n        \"\"\"\n        self.vearch.load()\n[docs]    @classmethod\n    def load_local(\n        cls,\n        embedding: Embeddings,\n        path_or_url: Optional[str] = None,\n        table_name: str = _DEFAULT_TABLE_NAME,\n        db_name: str = _DEFAULT_CLUSTER_DB_NAME,\n        flag: int = _DEFAULT_VERSION,\n        **kwargs: Any,\n    ) -> Vearch:\n        \"\"\"Load the local specified table of standalone vearch.\n        Returns:\n            Success or failure of loading the local specified table\n        \"\"\"\n        if not path_or_url:\n            raise ValueError(\"No metadata path!!!\")\n        if not table_name:\n            raise ValueError(\"No table name!!!\")\n        table_path = os.path.join(path_or_url, table_name + \".schema\")\n        if not os.path.exists(table_path):\n            raise ValueError(\"vearch vectorbase table not exist!!!\")\n        vearch_db = cls(\n            embedding_function=embedding,\n            path_or_url=path_or_url,\n            table_name=table_name,\n            db_name=db_name,\n            flag=flag,\n        )\n        vearch_db._load()\n        return vearch_db\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = DEFAULT_TOPN,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html"}
{"id": "cc4a876c20c3-7", "text": "k: int = DEFAULT_TOPN,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"\n        Return docs most similar to query.\n        \"\"\"\n        if self.embedding_func is None:\n            raise ValueError(\"embedding_func is None!!!\")\n        embeddings = self.embedding_func.embed_query(query)\n        docs = self.similarity_search_by_vector(embeddings, k)\n        return docs\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = DEFAULT_TOPN,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"The most k similar documents and scores of the specified query.\n        Args:\n            embeddings: embedding vector of the query.\n            k: The k most similar documents to the text query.\n            min_score: the score of similar documents to the text query\n        Returns:\n            The k most similar documents to the specified text query.\n            0 is dissimilar, 1 is the most similar.\n        \"\"\"\n        embed = np.array(embedding)\n        if self.flag:\n            query_data = {\n                \"query\": {\n                    \"sum\": [\n                        {\n                            \"field\": \"text_embedding\",\n                            \"feature\": (embed / np.linalg.norm(embed)).tolist(),\n                        }\n                    ],\n                },\n                \"size\": k,\n                \"fields\": [\"text\", \"metadata\"],\n            }\n            query_result = self.vearch.search(\n                self.using_db_name, self.using_table_name, query_data\n            )\n            res = query_result[\"hits\"][\"hits\"]\n        else:\n            query_data = {\n                \"vector\": [\n                    {\n                        \"field\": \"text_embedding\",\n                        \"feature\": embed / np.linalg.norm(embed),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html"}
{"id": "cc4a876c20c3-8", "text": "\"feature\": embed / np.linalg.norm(embed),\n                    }\n                ],\n                \"fields\": [],\n                \"is_brute_search\": 1,\n                \"retrieval_param\": {\"metric_type\": \"InnerProduct\", \"nprobe\": 20},\n                \"topn\": k,\n            }\n            query_result = self.vearch.search(query_data)\n            res = query_result[0][\"result_items\"]\n        docs = []\n        for item in res:\n            content = \"\"\n            meta_data = {}\n            if self.flag:\n                item = item[\"_source\"]\n            for item_key in item:\n                if item_key == \"text\":\n                    content = item[item_key]\n                    continue\n                if item_key == \"metadata\":\n                    meta_data[\"source\"] = item[item_key]\n                    continue\n            docs.append(Document(page_content=content, metadata=meta_data))\n        return docs\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = DEFAULT_TOPN,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"The most k similar documents and scores of the specified query.\n        Args:\n            embeddings: embedding vector of the query.\n            k: The k most similar documents to the text query.\n            min_score: the score of similar documents to the text query\n        Returns:\n            The k most similar documents to the specified text query.\n            0 is dissimilar, 1 is the most similar.\n        \"\"\"\n        if self.embedding_func is None:\n            raise ValueError(\"embedding_func is None!!!\")\n        embeddings = self.embedding_func.embed_query(query)\n        embed = np.array(embeddings)\n        if self.flag:\n            query_data = {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html"}
{"id": "cc4a876c20c3-9", "text": "if self.flag:\n            query_data = {\n                \"query\": {\n                    \"sum\": [\n                        {\n                            \"field\": \"text_embedding\",\n                            \"feature\": (embed / np.linalg.norm(embed)).tolist(),\n                        }\n                    ],\n                },\n                \"size\": k,\n                \"fields\": [\"text_embedding\", \"text\", \"metadata\"],\n            }\n            query_result = self.vearch.search(\n                self.using_db_name, self.using_table_name, query_data\n            )\n            res = query_result[\"hits\"][\"hits\"]\n        else:\n            query_data = {\n                \"vector\": [\n                    {\n                        \"field\": \"text_embedding\",\n                        \"feature\": embed / np.linalg.norm(embed),\n                    }\n                ],\n                \"fields\": [],\n                \"is_brute_search\": 1,\n                \"retrieval_param\": {\"metric_type\": \"InnerProduct\", \"nprobe\": 20},\n                \"topn\": k,\n            }\n            query_result = self.vearch.search(query_data)\n            res = query_result[0][\"result_items\"]\n        results: List[Tuple[Document, float]] = []\n        for item in res:\n            content = \"\"\n            meta_data = {}\n            if self.flag:\n                score = item[\"_score\"]\n                item = item[\"_source\"]\n            for item_key in item:\n                if item_key == \"text\":\n                    content = item[item_key]\n                    continue\n                if item_key == \"metadata\":\n                    meta_data[\"source\"] = item[item_key]\n                    continue\n                if self.flag != 1 and item_key == \"score\":\n                    score = item[item_key]\n                    continue\n            tmp_res = (Document(page_content=content, metadata=meta_data), score)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html"}
{"id": "cc4a876c20c3-10", "text": "tmp_res = (Document(page_content=content, metadata=meta_data), score)\n            results.append(tmp_res)\n        return results\n    def _similarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        return self.similarity_search_with_score(query, k, **kwargs)\n[docs]    def delete(\n        self,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Optional[bool]:\n        \"\"\"Delete the documents which have the specified ids.\n        Args:\n            ids: The ids of the embedding vectors.\n            **kwargs: Other keyword arguments that subclasses might use.\n        Returns:\n            Optional[bool]: True if deletion is successful.\n            False otherwise, None if not implemented.\n        \"\"\"\n        ret: Optional[bool] = None\n        tmp_res = []\n        if ids is None or ids.__len__() == 0:\n            return ret\n        for _id in ids:\n            if self.flag:\n                ret = self.vearch.delete(self.using_db_name, self.using_table_name, _id)\n            else:\n                ret = self.vearch.del_doc(_id)\n            tmp_res.append(ret)\n        ret = all(i == 0 for i in tmp_res)\n        return ret\n[docs]    def get(\n        self,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Dict[str, Document]:\n        \"\"\"Return docs according ids.\n        Args:\n            ids: The ids of the embedding vectors.\n        Returns:\n            Documents which satisfy the input conditions.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html"}
{"id": "cc4a876c20c3-11", "text": "Returns:\n            Documents which satisfy the input conditions.\n        \"\"\"\n        results: Dict[str, Document] = {}\n        if ids is None or ids.__len__() == 0:\n            return results\n        if self.flag:\n            query_data = {\"query\": {\"ids\": ids}}\n            docs_detail = self.vearch.mget_by_ids(\n                self.using_db_name, self.using_table_name, query_data\n            )\n            for record in docs_detail:\n                if record[\"found\"] is False:\n                    continue\n                content = \"\"\n                meta_info = {}\n                for field in record[\"_source\"]:\n                    if field == \"text\":\n                        content = record[\"_source\"][field]\n                        continue\n                    elif field == \"metadata\":\n                        meta_info[\"source\"] = record[\"_source\"][field]\n                        continue\n                results[record[\"_id\"]] = Document(\n                    page_content=content, metadata=meta_info\n                )\n        else:\n            for id in ids:\n                docs_detail = self.vearch.get_doc_by_id(id)\n                if docs_detail == {}:\n                    continue\n                content = \"\"\n                meta_info = {}\n                for field in docs_detail:\n                    if field == \"text\":\n                        content = docs_detail[field]\n                        continue\n                    elif field == \"metadata\":\n                        meta_info[\"source\"] = docs_detail[field]\n                        continue\n                results[docs_detail[\"_id\"]] = Document(\n                    page_content=content, metadata=meta_info\n                )\n        return results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html"}
{"id": "682eef8aaa20-0", "text": "Source code for langchain.vectorstores.tair\nfrom __future__ import annotations\nimport json\nimport logging\nimport uuid\nfrom typing import Any, Iterable, List, Optional, Type\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\ndef _uuid_key() -> str:\n    return uuid.uuid4().hex\n[docs]class Tair(VectorStore):\n    \"\"\"`Tair` vector store.\"\"\"\n[docs]    def __init__(\n        self,\n        embedding_function: Embeddings,\n        url: str,\n        index_name: str,\n        content_key: str = \"content\",\n        metadata_key: str = \"metadata\",\n        search_params: Optional[dict] = None,\n        **kwargs: Any,\n    ):\n        self.embedding_function = embedding_function\n        self.index_name = index_name\n        try:\n            from tair import Tair as TairClient\n        except ImportError:\n            raise ImportError(\n                \"Could not import tair python package. \"\n                \"Please install it with `pip install tair`.\"\n            )\n        try:\n            # connect to tair from url\n            client = TairClient.from_url(url, **kwargs)\n        except ValueError as e:\n            raise ValueError(f\"Tair failed to connect: {e}\")\n        self.client = client\n        self.content_key = content_key\n        self.metadata_key = metadata_key\n        self.search_params = search_params\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding_function\n[docs]    def create_index_if_not_exist(\n        self,\n        dim: int,\n        distance_type: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html"}
{"id": "682eef8aaa20-1", "text": "self,\n        dim: int,\n        distance_type: str,\n        index_type: str,\n        data_type: str,\n        **kwargs: Any,\n    ) -> bool:\n        index = self.client.tvs_get_index(self.index_name)\n        if index is not None:\n            logger.info(\"Index already exists\")\n            return False\n        self.client.tvs_create_index(\n            self.index_name,\n            dim,\n            distance_type,\n            index_type,\n            data_type,\n            **kwargs,\n        )\n        return True\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add texts data to an existing index.\"\"\"\n        ids = []\n        keys = kwargs.get(\"keys\", None)\n        use_hybrid_search = False\n        index = self.client.tvs_get_index(self.index_name)\n        if index is not None and index.get(\"lexical_algorithm\") == \"bm25\":\n            use_hybrid_search = True\n        # Write data to tair\n        pipeline = self.client.pipeline(transaction=False)\n        embeddings = self.embedding_function.embed_documents(list(texts))\n        for i, text in enumerate(texts):\n            # Use provided key otherwise use default key\n            key = keys[i] if keys else _uuid_key()\n            metadata = metadatas[i] if metadatas else {}\n            if use_hybrid_search:\n                # tair use TEXT attr hybrid search\n                pipeline.tvs_hset(\n                    self.index_name,\n                    key,\n                    embeddings[i],\n                    False,\n                    **{\n                        \"TEXT\": text,\n                        self.content_key: text,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html"}
{"id": "682eef8aaa20-2", "text": "**{\n                        \"TEXT\": text,\n                        self.content_key: text,\n                        self.metadata_key: json.dumps(metadata),\n                    },\n                )\n            else:\n                pipeline.tvs_hset(\n                    self.index_name,\n                    key,\n                    embeddings[i],\n                    False,\n                    **{\n                        self.content_key: text,\n                        self.metadata_key: json.dumps(metadata),\n                    },\n                )\n            ids.append(key)\n        pipeline.execute()\n        return ids\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"\n        Returns the most similar indexed documents to the query text.\n        Args:\n            query (str): The query text for which to find similar documents.\n            k (int): The number of documents to return. Default is 4.\n        Returns:\n            List[Document]: A list of documents that are most similar to the query text.\n        \"\"\"\n        # Creates embedding vector from user query\n        embedding = self.embedding_function.embed_query(query)\n        keys_and_scores = self.client.tvs_knnsearch(\n            self.index_name, k, embedding, False, None, **kwargs\n        )\n        pipeline = self.client.pipeline(transaction=False)\n        for key, _ in keys_and_scores:\n            pipeline.tvs_hmget(\n                self.index_name, key, self.metadata_key, self.content_key\n            )\n        docs = pipeline.execute()\n        return [\n            Document(\n                page_content=d[1],\n                metadata=json.loads(d[0]),\n            )\n            for d in docs\n        ]\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[Tair],\n        texts: List[str],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html"}
{"id": "682eef8aaa20-3", "text": "cls: Type[Tair],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        index_name: str = \"langchain\",\n        content_key: str = \"content\",\n        metadata_key: str = \"metadata\",\n        **kwargs: Any,\n    ) -> Tair:\n        try:\n            from tair import tairvector\n        except ImportError:\n            raise ValueError(\n                \"Could not import tair python package. \"\n                \"Please install it with `pip install tair`.\"\n            )\n        url = get_from_dict_or_env(kwargs, \"tair_url\", \"TAIR_URL\")\n        if \"tair_url\" in kwargs:\n            kwargs.pop(\"tair_url\")\n        distance_type = tairvector.DistanceMetric.InnerProduct\n        if \"distance_type\" in kwargs:\n            distance_type = kwargs.pop(\"distance_type\")\n        index_type = tairvector.IndexType.HNSW\n        if \"index_type\" in kwargs:\n            index_type = kwargs.pop(\"index_type\")\n        data_type = tairvector.DataType.Float32\n        if \"data_type\" in kwargs:\n            data_type = kwargs.pop(\"data_type\")\n        index_params = {}\n        if \"index_params\" in kwargs:\n            index_params = kwargs.pop(\"index_params\")\n        search_params = {}\n        if \"search_params\" in kwargs:\n            search_params = kwargs.pop(\"search_params\")\n        keys = None\n        if \"keys\" in kwargs:\n            keys = kwargs.pop(\"keys\")\n        try:\n            tair_vector_store = cls(\n                embedding,\n                url,\n                index_name,\n                content_key=content_key,\n                metadata_key=metadata_key,\n                search_params=search_params,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html"}
{"id": "682eef8aaa20-4", "text": "metadata_key=metadata_key,\n                search_params=search_params,\n                **kwargs,\n            )\n        except ValueError as e:\n            raise ValueError(f\"tair failed to connect: {e}\")\n        # Create embeddings for documents\n        embeddings = embedding.embed_documents(texts)\n        tair_vector_store.create_index_if_not_exist(\n            len(embeddings[0]),\n            distance_type,\n            index_type,\n            data_type,\n            **index_params,\n        )\n        tair_vector_store.add_texts(texts, metadatas, keys=keys)\n        return tair_vector_store\n[docs]    @classmethod\n    def from_documents(\n        cls,\n        documents: List[Document],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        index_name: str = \"langchain\",\n        content_key: str = \"content\",\n        metadata_key: str = \"metadata\",\n        **kwargs: Any,\n    ) -> Tair:\n        texts = [d.page_content for d in documents]\n        metadatas = [d.metadata for d in documents]\n        return cls.from_texts(\n            texts, embedding, metadatas, index_name, content_key, metadata_key, **kwargs\n        )\n[docs]    @staticmethod\n    def drop_index(\n        index_name: str = \"langchain\",\n        **kwargs: Any,\n    ) -> bool:\n        \"\"\"\n        Drop an existing index.\n        Args:\n            index_name (str): Name of the index to drop.\n        Returns:\n            bool: True if the index is dropped successfully.\n        \"\"\"\n        try:\n            from tair import Tair as TairClient\n        except ImportError:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html"}
{"id": "682eef8aaa20-5", "text": "except ImportError:\n            raise ValueError(\n                \"Could not import tair python package. \"\n                \"Please install it with `pip install tair`.\"\n            )\n        url = get_from_dict_or_env(kwargs, \"tair_url\", \"TAIR_URL\")\n        try:\n            if \"tair_url\" in kwargs:\n                kwargs.pop(\"tair_url\")\n            client = TairClient.from_url(url=url, **kwargs)\n        except ValueError as e:\n            raise ValueError(f\"Tair connection error: {e}\")\n        # delete index\n        ret = client.tvs_del_index(index_name)\n        if ret == 0:\n            # index not exist\n            logger.info(\"Index does not exist\")\n            return False\n        return True\n[docs]    @classmethod\n    def from_existing_index(\n        cls,\n        embedding: Embeddings,\n        index_name: str = \"langchain\",\n        content_key: str = \"content\",\n        metadata_key: str = \"metadata\",\n        **kwargs: Any,\n    ) -> Tair:\n        \"\"\"Connect to an existing Tair index.\"\"\"\n        url = get_from_dict_or_env(kwargs, \"tair_url\", \"TAIR_URL\")\n        search_params = {}\n        if \"search_params\" in kwargs:\n            search_params = kwargs.pop(\"search_params\")\n        return cls(\n            embedding,\n            url,\n            index_name,\n            content_key=content_key,\n            metadata_key=metadata_key,\n            search_params=search_params,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html"}
{"id": "7106ac669f38-0", "text": "Source code for langchain.vectorstores.atlas\nfrom __future__ import annotations\nimport logging\nimport uuid\nfrom typing import Any, Iterable, List, Optional, Type\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nlogger = logging.getLogger(__name__)\n[docs]class AtlasDB(VectorStore):\n    \"\"\"`Atlas` vector store.\n     Atlas is the `Nomic's` neural database and `rhizomatic` instrument.\n    To use, you should have the ``nomic`` python package installed.\n    Example:\n        .. code-block:: python\n                from langchain.vectorstores import AtlasDB\n                from langchain.embeddings.openai import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                vectorstore = AtlasDB(\"my_project\", embeddings.embed_query)\n    \"\"\"\n    _ATLAS_DEFAULT_ID_FIELD = \"atlas_id\"\n[docs]    def __init__(\n        self,\n        name: str,\n        embedding_function: Optional[Embeddings] = None,\n        api_key: Optional[str] = None,\n        description: str = \"A description for your project\",\n        is_public: bool = True,\n        reset_project_if_exists: bool = False,\n    ) -> None:\n        \"\"\"\n        Initialize the Atlas Client\n        Args:\n            name (str): The name of your project. If the project already exists,\n                it will be loaded.\n            embedding_function (Optional[Embeddings]): An optional function used for\n                embedding your data. If None, data will be embedded with\n                Nomic's embed model.\n            api_key (str): Your nomic API key\n            description (str): A description for your project.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html"}
{"id": "7106ac669f38-1", "text": "description (str): A description for your project.\n            is_public (bool): Whether your project is publicly accessible.\n                True by default.\n            reset_project_if_exists (bool): Whether to reset this project if it\n                already exists. Default False.\n                Generally useful during development and testing.\n        \"\"\"\n        try:\n            import nomic\n            from nomic import AtlasProject\n        except ImportError:\n            raise ImportError(\n                \"Could not import nomic python package. \"\n                \"Please install it with `pip install nomic`.\"\n            )\n        if api_key is None:\n            raise ValueError(\"No API key provided. Sign up at atlas.nomic.ai!\")\n        nomic.login(api_key)\n        self._embedding_function = embedding_function\n        modality = \"text\"\n        if self._embedding_function is not None:\n            modality = \"embedding\"\n        # Check if the project exists, create it if not\n        self.project = AtlasProject(\n            name=name,\n            description=description,\n            modality=modality,\n            is_public=is_public,\n            reset_project_if_exists=reset_project_if_exists,\n            unique_id_field=AtlasDB._ATLAS_DEFAULT_ID_FIELD,\n        )\n        self.project._latest_project_state()\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        return self._embedding_function\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        refresh: bool = True,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html"}
{"id": "7106ac669f38-2", "text": "\"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts (Iterable[str]): Texts to add to the vectorstore.\n            metadatas (Optional[List[dict]], optional): Optional list of metadatas.\n            ids (Optional[List[str]]): An optional list of ids.\n            refresh(bool): Whether or not to refresh indices with the updated data.\n                Default True.\n        Returns:\n            List[str]: List of IDs of the added texts.\n        \"\"\"\n        if (\n            metadatas is not None\n            and len(metadatas) > 0\n            and \"text\" in metadatas[0].keys()\n        ):\n            raise ValueError(\"Cannot accept key text in metadata!\")\n        texts = list(texts)\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        # Embedding upload case\n        if self._embedding_function is not None:\n            _embeddings = self._embedding_function.embed_documents(texts)\n            embeddings = np.stack(_embeddings)\n            if metadatas is None:\n                data = [\n                    {AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i], \"text\": texts[i]}\n                    for i, _ in enumerate(texts)\n                ]\n            else:\n                for i in range(len(metadatas)):\n                    metadatas[i][AtlasDB._ATLAS_DEFAULT_ID_FIELD] = ids[i]\n                    metadatas[i][\"text\"] = texts[i]\n                data = metadatas\n            self.project._validate_map_data_inputs(\n                [], id_field=AtlasDB._ATLAS_DEFAULT_ID_FIELD, data=data\n            )\n            with self.project.wait_for_project_lock():\n                self.project.add_embeddings(embeddings=embeddings, data=data)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html"}
{"id": "7106ac669f38-3", "text": "self.project.add_embeddings(embeddings=embeddings, data=data)\n        # Text upload case\n        else:\n            if metadatas is None:\n                data = [\n                    {\"text\": text, AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i]}\n                    for i, text in enumerate(texts)\n                ]\n            else:\n                for i, text in enumerate(texts):\n                    metadatas[i][\"text\"] = texts\n                    metadatas[i][AtlasDB._ATLAS_DEFAULT_ID_FIELD] = ids[i]\n                data = metadatas\n            self.project._validate_map_data_inputs(\n                [], id_field=AtlasDB._ATLAS_DEFAULT_ID_FIELD, data=data\n            )\n            with self.project.wait_for_project_lock():\n                self.project.add_text(data)\n        if refresh:\n            if len(self.project.indices) > 0:\n                with self.project.wait_for_project_lock():\n                    self.project.rebuild_maps()\n        return ids\n[docs]    def create_index(self, **kwargs: Any) -> Any:\n        \"\"\"Creates an index in your project.\n        See\n        https://docs.nomic.ai/atlas_api.html#nomic.project.AtlasProject.create_index\n        for full detail.\n        \"\"\"\n        with self.project.wait_for_project_lock():\n            return self.project.create_index(**kwargs)\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Run similarity search with AtlasDB\n        Args:\n            query (str): Query text to search for.\n            k (int): Number of results to return. Defaults to 4.\n        Returns:\n            List[Document]: List of documents most similar to the query text.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html"}
{"id": "7106ac669f38-4", "text": "Returns:\n            List[Document]: List of documents most similar to the query text.\n        \"\"\"\n        if self._embedding_function is None:\n            raise NotImplementedError(\n                \"AtlasDB requires an embedding_function for text similarity search!\"\n            )\n        _embedding = self._embedding_function.embed_documents([query])[0]\n        embedding = np.array(_embedding).reshape(1, -1)\n        with self.project.wait_for_project_lock():\n            neighbors, _ = self.project.projections[0].vector_search(\n                queries=embedding, k=k\n            )\n            data = self.project.get_data(ids=neighbors[0])\n        docs = [\n            Document(page_content=data[i][\"text\"], metadata=data[i])\n            for i, neighbor in enumerate(neighbors)\n        ]\n        return docs\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[AtlasDB],\n        texts: List[str],\n        embedding: Optional[Embeddings] = None,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        name: Optional[str] = None,\n        api_key: Optional[str] = None,\n        description: str = \"A description for your project\",\n        is_public: bool = True,\n        reset_project_if_exists: bool = False,\n        index_kwargs: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> AtlasDB:\n        \"\"\"Create an AtlasDB vectorstore from a raw documents.\n        Args:\n            texts (List[str]): The list of texts to ingest.\n            name (str): Name of the project to create.\n            api_key (str): Your nomic API key,\n            embedding (Optional[Embeddings]): Embedding function. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html"}
{"id": "7106ac669f38-5", "text": "embedding (Optional[Embeddings]): Embedding function. Defaults to None.\n            metadatas (Optional[List[dict]]): List of metadatas. Defaults to None.\n            ids (Optional[List[str]]): Optional list of document IDs. If None,\n                ids will be auto created\n            description (str): A description for your project.\n            is_public (bool): Whether your project is publicly accessible.\n                True by default.\n            reset_project_if_exists (bool): Whether to reset this project if it\n                already exists. Default False.\n                Generally useful during development and testing.\n            index_kwargs (Optional[dict]): Dict of kwargs for index creation.\n                See https://docs.nomic.ai/atlas_api.html\n        Returns:\n            AtlasDB: Nomic's neural database and finest rhizomatic instrument\n        \"\"\"\n        if name is None or api_key is None:\n            raise ValueError(\"`name` and `api_key` cannot be None.\")\n        # Inject relevant kwargs\n        all_index_kwargs = {\"name\": name + \"_index\", \"indexed_field\": \"text\"}\n        if index_kwargs is not None:\n            for k, v in index_kwargs.items():\n                all_index_kwargs[k] = v\n        # Build project\n        atlasDB = cls(\n            name,\n            embedding_function=embedding,\n            api_key=api_key,\n            description=\"A description for your project\",\n            is_public=is_public,\n            reset_project_if_exists=reset_project_if_exists,\n        )\n        with atlasDB.project.wait_for_project_lock():\n            atlasDB.add_texts(texts=texts, metadatas=metadatas, ids=ids)\n            atlasDB.create_index(**all_index_kwargs)\n        return atlasDB\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[AtlasDB],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html"}
{"id": "7106ac669f38-6", "text": "def from_documents(\n        cls: Type[AtlasDB],\n        documents: List[Document],\n        embedding: Optional[Embeddings] = None,\n        ids: Optional[List[str]] = None,\n        name: Optional[str] = None,\n        api_key: Optional[str] = None,\n        persist_directory: Optional[str] = None,\n        description: str = \"A description for your project\",\n        is_public: bool = True,\n        reset_project_if_exists: bool = False,\n        index_kwargs: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> AtlasDB:\n        \"\"\"Create an AtlasDB vectorstore from a list of documents.\n        Args:\n            name (str): Name of the collection to create.\n            api_key (str): Your nomic API key,\n            documents (List[Document]): List of documents to add to the vectorstore.\n            embedding (Optional[Embeddings]): Embedding function. Defaults to None.\n            ids (Optional[List[str]]): Optional list of document IDs. If None,\n                ids will be auto created\n            description (str): A description for your project.\n            is_public (bool): Whether your project is publicly accessible.\n                True by default.\n            reset_project_if_exists (bool): Whether to reset this project if\n                it already exists. Default False.\n                Generally useful during development and testing.\n            index_kwargs (Optional[dict]): Dict of kwargs for index creation.\n                See https://docs.nomic.ai/atlas_api.html\n        Returns:\n            AtlasDB: Nomic's neural database and finest rhizomatic instrument\n        \"\"\"\n        if name is None or api_key is None:\n            raise ValueError(\"`name` and `api_key` cannot be None.\")\n        texts = [doc.page_content for doc in documents]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html"}
{"id": "7106ac669f38-7", "text": "texts = [doc.page_content for doc in documents]\n        metadatas = [doc.metadata for doc in documents]\n        return cls.from_texts(\n            name=name,\n            api_key=api_key,\n            texts=texts,\n            embedding=embedding,\n            metadatas=metadatas,\n            ids=ids,\n            description=description,\n            is_public=is_public,\n            reset_project_if_exists=reset_project_if_exists,\n            index_kwargs=index_kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html"}
{"id": "f83b20163cfe-0", "text": "Source code for langchain.vectorstores.tencentvectordb\n\"\"\"Wrapper around the Tencent vector database.\"\"\"\nfrom __future__ import annotations\nimport json\nimport logging\nimport time\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple\nimport numpy as np\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import guard_import\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nlogger = logging.getLogger(__name__)\n[docs]class ConnectionParams:\n    \"\"\"Tencent vector DB Connection params.\n    See the following documentation for details:\n    https://cloud.tencent.com/document/product/1709/95820\n    Attribute:\n        url (str) : The access address of the vector database server\n            that the client needs to connect to.\n        key (str): API key for client to access the vector database server,\n            which is used for authentication.\n        username (str) : Account for client to access the vector database server.\n        timeout (int) : Request Timeout.\n    \"\"\"\n[docs]    def __init__(self, url: str, key: str, username: str = \"root\", timeout: int = 10):\n        self.url = url\n        self.key = key\n        self.username = username\n        self.timeout = timeout\n[docs]class IndexParams:\n    \"\"\"Tencent vector DB Index params.\n    See the following documentation for details:\n    https://cloud.tencent.com/document/product/1709/95826\n    \"\"\"\n[docs]    def __init__(\n        self,\n        dimension: int,\n        shard: int = 1,\n        replicas: int = 2,\n        index_type: str = \"HNSW\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html"}
{"id": "f83b20163cfe-1", "text": "index_type: str = \"HNSW\",\n        metric_type: str = \"L2\",\n        params: Optional[Dict] = None,\n    ):\n        self.dimension = dimension\n        self.shard = shard\n        self.replicas = replicas\n        self.index_type = index_type\n        self.metric_type = metric_type\n        self.params = params\n[docs]class TencentVectorDB(VectorStore):\n    \"\"\"Initialize wrapper around the tencent vector database.\n    In order to use this you need to have a database instance.\n    See the following documentation for details:\n    https://cloud.tencent.com/document/product/1709/94951\n    \"\"\"\n    field_id: str = \"id\"\n    field_vector: str = \"vector\"\n    field_text: str = \"text\"\n    field_metadata: str = \"metadata\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        connection_params: ConnectionParams,\n        index_params: IndexParams = IndexParams(128),\n        database_name: str = \"LangChainDatabase\",\n        collection_name: str = \"LangChainCollection\",\n        drop_old: Optional[bool] = False,\n    ):\n        self.document = guard_import(\"tcvectordb.model.document\")\n        tcvectordb = guard_import(\"tcvectordb\")\n        self.embedding_func = embedding\n        self.index_params = index_params\n        self.vdb_client = tcvectordb.VectorDBClient(\n            url=connection_params.url,\n            username=connection_params.username,\n            key=connection_params.key,\n            timeout=connection_params.timeout,\n        )\n        db_list = self.vdb_client.list_databases()\n        db_exist: bool = False\n        for db in db_list:\n            if database_name == db.database_name:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html"}
{"id": "f83b20163cfe-2", "text": "for db in db_list:\n            if database_name == db.database_name:\n                db_exist = True\n                break\n        if db_exist:\n            self.database = self.vdb_client.database(database_name)\n        else:\n            self.database = self.vdb_client.create_database(database_name)\n        try:\n            self.collection = self.database.describe_collection(collection_name)\n            if drop_old:\n                self.database.drop_collection(collection_name)\n                self._create_collection(collection_name)\n        except tcvectordb.exceptions.VectorDBException:\n            self._create_collection(collection_name)\n    def _create_collection(self, collection_name: str) -> None:\n        enum = guard_import(\"tcvectordb.model.enum\")\n        vdb_index = guard_import(\"tcvectordb.model.index\")\n        index_type = None\n        for k, v in enum.IndexType.__members__.items():\n            if k == self.index_params.index_type:\n                index_type = v\n        if index_type is None:\n            raise ValueError(\"unsupported index_type\")\n        metric_type = None\n        for k, v in enum.MetricType.__members__.items():\n            if k == self.index_params.metric_type:\n                metric_type = v\n        if metric_type is None:\n            raise ValueError(\"unsupported metric_type\")\n        if self.index_params.params is None:\n            params = vdb_index.HNSWParams(m=16, efconstruction=200)\n        else:\n            params = vdb_index.HNSWParams(\n                m=self.index_params.params.get(\"M\", 16),\n                efconstruction=self.index_params.params.get(\"efConstruction\", 200),\n            )\n        index = vdb_index.Index(\n            vdb_index.FilterIndex(\n                self.field_id, enum.FieldType.String, enum.IndexType.PRIMARY_KEY\n            ),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html"}
{"id": "f83b20163cfe-3", "text": "self.field_id, enum.FieldType.String, enum.IndexType.PRIMARY_KEY\n            ),\n            vdb_index.VectorIndex(\n                self.field_vector,\n                self.index_params.dimension,\n                index_type,\n                metric_type,\n                params,\n            ),\n            vdb_index.FilterIndex(\n                self.field_text, enum.FieldType.String, enum.IndexType.FILTER\n            ),\n            vdb_index.FilterIndex(\n                self.field_metadata, enum.FieldType.String, enum.IndexType.FILTER\n            ),\n        )\n        self.collection = self.database.create_collection(\n            name=collection_name,\n            shard=self.index_params.shard,\n            replicas=self.index_params.replicas,\n            description=\"Collection for LangChain\",\n            index=index,\n        )\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding_func\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        connection_params: Optional[ConnectionParams] = None,\n        index_params: Optional[IndexParams] = None,\n        database_name: str = \"LangChainDatabase\",\n        collection_name: str = \"LangChainCollection\",\n        drop_old: Optional[bool] = False,\n        **kwargs: Any,\n    ) -> TencentVectorDB:\n        \"\"\"Create a collection, indexes it with HNSW, and insert data.\"\"\"\n        if len(texts) == 0:\n            raise ValueError(\"texts is empty\")\n        if connection_params is None:\n            raise ValueError(\"connection_params is empty\")\n        try:\n            embeddings = embedding.embed_documents(texts[0:1])\n        except NotImplementedError:\n            embeddings = [embedding.embed_query(texts[0])]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html"}
{"id": "f83b20163cfe-4", "text": "except NotImplementedError:\n            embeddings = [embedding.embed_query(texts[0])]\n        dimension = len(embeddings[0])\n        if index_params is None:\n            index_params = IndexParams(dimension=dimension)\n        else:\n            index_params.dimension = dimension\n        vector_db = cls(\n            embedding=embedding,\n            connection_params=connection_params,\n            index_params=index_params,\n            database_name=database_name,\n            collection_name=collection_name,\n            drop_old=drop_old,\n        )\n        vector_db.add_texts(texts=texts, metadatas=metadatas)\n        return vector_db\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        timeout: Optional[int] = None,\n        batch_size: int = 1000,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Insert text data into TencentVectorDB.\"\"\"\n        texts = list(texts)\n        try:\n            embeddings = self.embedding_func.embed_documents(texts)\n        except NotImplementedError:\n            embeddings = [self.embedding_func.embed_query(x) for x in texts]\n        if len(embeddings) == 0:\n            logger.debug(\"Nothing to insert, skipping.\")\n            return []\n        pks: list[str] = []\n        total_count = len(embeddings)\n        for start in range(0, total_count, batch_size):\n            # Grab end index\n            docs = []\n            end = min(start + batch_size, total_count)\n            for id in range(start, end, 1):\n                metadata = \"{}\"\n                if metadatas is not None:\n                    metadata = json.dumps(metadatas[id])\n                doc = self.document.Document(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html"}
{"id": "f83b20163cfe-5", "text": "metadata = json.dumps(metadatas[id])\n                doc = self.document.Document(\n                    id=\"{}-{}-{}\".format(time.time_ns(), hash(texts[id]), id),\n                    vector=embeddings[id],\n                    text=texts[id],\n                    metadata=metadata,\n                )\n                docs.append(doc)\n                pks.append(str(id))\n            self.collection.upsert(docs, timeout)\n        return pks\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform a similarity search against the query string.\"\"\"\n        res = self.similarity_search_with_score(\n            query=query, k=k, param=param, expr=expr, timeout=timeout, **kwargs\n        )\n        return [doc for doc, _ in res]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Perform a search on a query string and return results with score.\"\"\"\n        # Embed the query text.\n        embedding = self.embedding_func.embed_query(query)\n        res = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs\n        )\n        return res\n[docs]    def similarity_search_by_vector(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html"}
{"id": "f83b20163cfe-6", "text": ")\n        return res\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform a similarity search against the query string.\"\"\"\n        res = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs\n        )\n        return [doc for doc, _ in res]\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Perform a search on a query string and return results with score.\"\"\"\n        filter = None if expr is None else self.document.Filter(expr)\n        ef = 10 if param is None else param.get(\"ef\", 10)\n        res: List[List[Dict]] = self.collection.search(\n            vectors=[embedding],\n            filter=filter,\n            params=self.document.HNSWSearchParams(ef=ef),\n            retrieve_vector=False,\n            limit=k,\n            timeout=timeout,\n        )\n        # Organize results.\n        ret: List[Tuple[Document, float]] = []\n        if res is None or len(res) == 0:\n            return ret\n        for result in res[0]:\n            meta = result.get(self.field_metadata)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html"}
{"id": "f83b20163cfe-7", "text": "for result in res[0]:\n            meta = result.get(self.field_metadata)\n            if meta is not None:\n                meta = json.loads(meta)\n            doc = Document(page_content=result.get(self.field_text), metadata=meta)\n            pair = (doc, result.get(\"score\", 0.0))\n            ret.append(pair)\n        return ret\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform a search and return results that are reordered by MMR.\"\"\"\n        embedding = self.embedding_func.embed_query(query)\n        return self.max_marginal_relevance_search_by_vector(\n            embedding=embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            param=param,\n            expr=expr,\n            timeout=timeout,\n            **kwargs,\n        )\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: list[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        param: Optional[dict] = None,\n        expr: Optional[str] = None,\n        timeout: Optional[int] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform a search and return results that are reordered by MMR.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html"}
{"id": "f83b20163cfe-8", "text": "\"\"\"Perform a search and return results that are reordered by MMR.\"\"\"\n        filter = None if expr is None else self.document.Filter(expr)\n        ef = 10 if param is None else param.get(\"ef\", 10)\n        res: List[List[Dict]] = self.collection.search(\n            vectors=[embedding],\n            filter=filter,\n            params=self.document.HNSWSearchParams(ef=ef),\n            retrieve_vector=True,\n            limit=fetch_k,\n            timeout=timeout,\n        )\n        # Organize results.\n        documents = []\n        ordered_result_embeddings = []\n        for result in res[0]:\n            meta = result.get(self.field_metadata)\n            if meta is not None:\n                meta = json.loads(meta)\n            doc = Document(page_content=result.get(self.field_text), metadata=meta)\n            documents.append(doc)\n            ordered_result_embeddings.append(result.get(self.field_vector))\n        # Get the new order of results.\n        new_ordering = maximal_marginal_relevance(\n            np.array(embedding), ordered_result_embeddings, k=k, lambda_mult=lambda_mult\n        )\n        # Reorder the values and return.\n        ret = []\n        for x in new_ordering:\n            # Function can return -1 index\n            if x == -1:\n                break\n            else:\n                ret.append(documents[x])\n        return ret", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html"}
{"id": "0aba36bff0d0-0", "text": "Source code for langchain.vectorstores.neo4j_vector\nfrom __future__ import annotations\nimport enum\nimport logging\nimport os\nimport uuid\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n)\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_env\nfrom langchain.vectorstores.utils import DistanceStrategy\nDEFAULT_DISTANCE_STRATEGY = DistanceStrategy.COSINE\nDISTANCE_MAPPING = {\n    DistanceStrategy.EUCLIDEAN_DISTANCE: \"euclidean\",\n    DistanceStrategy.COSINE: \"cosine\",\n}\n[docs]class SearchType(str, enum.Enum):\n    \"\"\"Enumerator of the Distance strategies.\"\"\"\n    VECTOR = \"vector\"\n    HYBRID = \"hybrid\"\nDEFAULT_SEARCH_TYPE = SearchType.VECTOR\ndef _get_search_index_query(search_type: SearchType) -> str:\n    type_to_query_map = {\n        SearchType.VECTOR: (\n            \"CALL db.index.vector.queryNodes($index, $k, $embedding) YIELD node, score \"\n        ),\n        SearchType.HYBRID: (\n            \"CALL { \"\n            \"CALL db.index.vector.queryNodes($index, $k, $embedding) \"\n            \"YIELD node, score \"\n            \"RETURN node, score UNION \"\n            \"CALL db.index.fulltext.queryNodes($keyword_index, $query, {limit: $k}) \"\n            \"YIELD node, score \"\n            \"WITH collect({node:node, score:score}) AS nodes, max(score) AS max \"\n            \"UNWIND nodes AS n \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-1", "text": "\"UNWIND nodes AS n \"\n            \"RETURN n.node AS node, (n.score / max) AS score \"  # We use 0 as min\n            \"} \"\n            \"WITH node, max(score) AS score ORDER BY score DESC LIMIT $k \"  # dedup\n        ),\n    }\n    return type_to_query_map[search_type]\n[docs]def check_if_not_null(props: List[str], values: List[Any]) -> None:\n    \"\"\"Check if the values are not None or empty string\"\"\"\n    for prop, value in zip(props, values):\n        if not value:\n            raise ValueError(f\"Parameter `{prop}` must not be None or empty string\")\n[docs]def sort_by_index_name(\n    lst: List[Dict[str, Any]], index_name: str\n) -> List[Dict[str, Any]]:\n    \"\"\"Sort first element to match the index_name if exists\"\"\"\n    return sorted(lst, key=lambda x: x.get(\"index_name\") != index_name)\n[docs]class Neo4jVector(VectorStore):\n    \"\"\"`Neo4j` vector index.\n    To use, you should have the ``neo4j`` python package installed.\n    Args:\n        url: Neo4j connection url\n        username: Neo4j username.\n        password: Neo4j password\n        database: Optionally provide Neo4j database\n                  Defaults to \"neo4j\"\n        embedding: Any embedding function implementing\n            `langchain.embeddings.base.Embeddings` interface.\n        distance_strategy: The distance strategy to use. (default: COSINE)\n        pre_delete_collection: If True, will delete existing data if it exists.\n            (default: False). Useful for testing.\n    Example:\n        .. code-block:: python", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-2", "text": "Example:\n        .. code-block:: python\n            from langchain.vectorstores.neo4j_vector import Neo4jVector\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            url=\"bolt://localhost:7687\"\n            username=\"neo4j\"\n            password=\"pleaseletmein\"\n            embeddings = OpenAIEmbeddings()\n            vectorestore = Neo4jVector.from_documents(\n                embedding=embeddings,\n                documents=docs,\n                url=url\n                username=username,\n                password=password,\n            )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        *,\n        search_type: SearchType = SearchType.VECTOR,\n        username: Optional[str] = None,\n        password: Optional[str] = None,\n        url: Optional[str] = None,\n        keyword_index_name: Optional[str] = \"keyword\",\n        database: str = \"neo4j\",\n        index_name: str = \"vector\",\n        node_label: str = \"Chunk\",\n        embedding_node_property: str = \"embedding\",\n        text_node_property: str = \"text\",\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        logger: Optional[logging.Logger] = None,\n        pre_delete_collection: bool = False,\n        retrieval_query: str = \"\",\n        relevance_score_fn: Optional[Callable[[float], float]] = None,\n    ) -> None:\n        try:\n            import neo4j\n        except ImportError:\n            raise ImportError(\n                \"Could not import neo4j python package. \"\n                \"Please install it with `pip install neo4j`.\"\n            )\n        # Allow only cosine and euclidean distance strategies\n        if distance_strategy not in [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-3", "text": "# Allow only cosine and euclidean distance strategies\n        if distance_strategy not in [\n            DistanceStrategy.EUCLIDEAN_DISTANCE,\n            DistanceStrategy.COSINE,\n        ]:\n            raise ValueError(\n                \"distance_strategy must be either 'EUCLIDEAN_DISTANCE' or 'COSINE'\"\n            )\n        # Handle if the credentials are environment variables\n        # Support URL for backwards compatibility\n        url = os.environ.get(\"NEO4J_URL\", url)\n        url = get_from_env(\"url\", \"NEO4J_URI\", url)\n        username = get_from_env(\"username\", \"NEO4J_USERNAME\", username)\n        password = get_from_env(\"password\", \"NEO4J_PASSWORD\", password)\n        database = get_from_env(\"database\", \"NEO4J_DATABASE\", database)\n        self._driver = neo4j.GraphDatabase.driver(url, auth=(username, password))\n        self._database = database\n        self.schema = \"\"\n        # Verify connection\n        try:\n            self._driver.verify_connectivity()\n        except neo4j.exceptions.ServiceUnavailable:\n            raise ValueError(\n                \"Could not connect to Neo4j database. \"\n                \"Please ensure that the url is correct\"\n            )\n        except neo4j.exceptions.AuthError:\n            raise ValueError(\n                \"Could not connect to Neo4j database. \"\n                \"Please ensure that the username and password are correct\"\n            )\n        # Verify if the version support vector index\n        self.verify_version()\n        # Verify that required values are not null\n        check_if_not_null(\n            [\n                \"index_name\",\n                \"node_label\",\n                \"embedding_node_property\",\n                \"text_node_property\",\n            ],\n            [index_name, node_label, embedding_node_property, text_node_property],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-4", "text": "],\n            [index_name, node_label, embedding_node_property, text_node_property],\n        )\n        self.embedding = embedding\n        self._distance_strategy = distance_strategy\n        self.index_name = index_name\n        self.keyword_index_name = keyword_index_name\n        self.node_label = node_label\n        self.embedding_node_property = embedding_node_property\n        self.text_node_property = text_node_property\n        self.logger = logger or logging.getLogger(__name__)\n        self.override_relevance_score_fn = relevance_score_fn\n        self.retrieval_query = retrieval_query\n        self.search_type = search_type\n        # Calculate embedding dimension\n        self.embedding_dimension = len(embedding.embed_query(\"foo\"))\n        # Delete existing data if flagged\n        if pre_delete_collection:\n            from neo4j.exceptions import DatabaseError\n            self.query(\n                f\"MATCH (n:`{self.node_label}`) \"\n                \"CALL { WITH n DETACH DELETE n } \"\n                \"IN TRANSACTIONS OF 10000 ROWS;\"\n            )\n            # Delete index\n            try:\n                self.query(f\"DROP INDEX {self.index_name}\")\n            except DatabaseError:  # Index didn't exist yet\n                pass\n[docs]    def query(\n        self, query: str, *, params: Optional[dict] = None\n    ) -> List[Dict[str, Any]]:\n        \"\"\"\n        This method sends a Cypher query to the connected Neo4j database\n        and returns the results as a list of dictionaries.\n        Args:\n            query (str): The Cypher query to execute.\n            params (dict, optional): Dictionary of query parameters. Defaults to {}.\n        Returns:\n            List[Dict[str, Any]]: List of dictionaries containing the query results.\n        \"\"\"\n        from neo4j.exceptions import CypherSyntaxError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-5", "text": "\"\"\"\n        from neo4j.exceptions import CypherSyntaxError\n        params = params or {}\n        with self._driver.session(database=self._database) as session:\n            try:\n                data = session.run(query, params)\n                return [r.data() for r in data]\n            except CypherSyntaxError as e:\n                raise ValueError(f\"Cypher Statement is not valid\\n{e}\")\n[docs]    def verify_version(self) -> None:\n        \"\"\"\n        Check if the connected Neo4j database version supports vector indexing.\n        Queries the Neo4j database to retrieve its version and compares it\n        against a target version (5.11.0) that is known to support vector\n        indexing. Raises a ValueError if the connected Neo4j version is\n        not supported.\n        \"\"\"\n        version = self.query(\"CALL dbms.components()\")[0][\"versions\"][0]\n        if \"aura\" in version:\n            version_tuple = tuple(map(int, version.split(\"-\")[0].split(\".\"))) + (0,)\n        else:\n            version_tuple = tuple(map(int, version.split(\".\")))\n        target_version = (5, 11, 0)\n        if version_tuple < target_version:\n            raise ValueError(\n                \"Version index is only supported in Neo4j version 5.11 or greater\"\n            )\n[docs]    def retrieve_existing_index(self) -> Optional[int]:\n        \"\"\"\n        Check if the vector index exists in the Neo4j database\n        and returns its embedding dimension.\n        This method queries the Neo4j database for existing indexes\n        and attempts to retrieve the dimension of the vector index\n        with the specified name. If the index exists, its dimension is returned.\n        If the index doesn't exist, `None` is returned.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-6", "text": "If the index doesn't exist, `None` is returned.\n        Returns:\n            int or None: The embedding dimension of the existing index if found.\n        \"\"\"\n        index_information = self.query(\n            \"SHOW INDEXES YIELD name, type, labelsOrTypes, properties, options \"\n            \"WHERE type = 'VECTOR' AND (name = $index_name \"\n            \"OR (labelsOrTypes[0] = $node_label AND \"\n            \"properties[0] = $embedding_node_property)) \"\n            \"RETURN name, labelsOrTypes, properties, options \",\n            params={\n                \"index_name\": self.index_name,\n                \"node_label\": self.node_label,\n                \"embedding_node_property\": self.embedding_node_property,\n            },\n        )\n        # sort by index_name\n        index_information = sort_by_index_name(index_information, self.index_name)\n        try:\n            self.index_name = index_information[0][\"name\"]\n            self.node_label = index_information[0][\"labelsOrTypes\"][0]\n            self.embedding_node_property = index_information[0][\"properties\"][0]\n            embedding_dimension = index_information[0][\"options\"][\"indexConfig\"][\n                \"vector.dimensions\"\n            ]\n            return embedding_dimension\n        except IndexError:\n            return None\n[docs]    def retrieve_existing_fts_index(\n        self, text_node_properties: List[str] = []\n    ) -> Optional[str]:\n        \"\"\"\n        Check if the fulltext index exists in the Neo4j database\n        This method queries the Neo4j database for existing fts indexes\n        with the specified name.\n        Returns:\n            (Tuple): keyword index information\n        \"\"\"\n        index_information = self.query(\n            \"SHOW INDEXES YIELD name, type, labelsOrTypes, properties, options \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-7", "text": "\"SHOW INDEXES YIELD name, type, labelsOrTypes, properties, options \"\n            \"WHERE type = 'FULLTEXT' AND (name = $keyword_index_name \"\n            \"OR (labelsOrTypes = [$node_label] AND \"\n            \"properties = $text_node_property)) \"\n            \"RETURN name, labelsOrTypes, properties, options \",\n            params={\n                \"keyword_index_name\": self.keyword_index_name,\n                \"node_label\": self.node_label,\n                \"text_node_property\": text_node_properties or [self.text_node_property],\n            },\n        )\n        # sort by index_name\n        index_information = sort_by_index_name(index_information, self.index_name)\n        try:\n            self.keyword_index_name = index_information[0][\"name\"]\n            self.text_node_property = index_information[0][\"properties\"][0]\n            node_label = index_information[0][\"labelsOrTypes\"][0]\n            return node_label\n        except IndexError:\n            return None\n[docs]    def create_new_index(self) -> None:\n        \"\"\"\n        This method constructs a Cypher query and executes it\n        to create a new vector index in Neo4j.\n        \"\"\"\n        index_query = (\n            \"CALL db.index.vector.createNodeIndex(\"\n            \"$index_name,\"\n            \"$node_label,\"\n            \"$embedding_node_property,\"\n            \"toInteger($embedding_dimension),\"\n            \"$similarity_metric )\"\n        )\n        parameters = {\n            \"index_name\": self.index_name,\n            \"node_label\": self.node_label,\n            \"embedding_node_property\": self.embedding_node_property,\n            \"embedding_dimension\": self.embedding_dimension,\n            \"similarity_metric\": DISTANCE_MAPPING[self._distance_strategy],\n        }\n        self.query(index_query, params=parameters)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-8", "text": "}\n        self.query(index_query, params=parameters)\n[docs]    def create_new_keyword_index(self, text_node_properties: List[str] = []) -> None:\n        \"\"\"\n        This method constructs a Cypher query and executes it\n        to create a new full text index in Neo4j.\n        \"\"\"\n        node_props = text_node_properties or [self.text_node_property]\n        fts_index_query = (\n            f\"CREATE FULLTEXT INDEX {self.keyword_index_name} \"\n            f\"FOR (n:`{self.node_label}`) ON EACH \"\n            f\"[{', '.join(['n.`' + el + '`' for el in node_props])}]\"\n        )\n        self.query(fts_index_query)\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding\n    @classmethod\n    def __from(\n        cls,\n        texts: List[str],\n        embeddings: List[List[float]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        create_id_index: bool = True,\n        search_type: SearchType = SearchType.VECTOR,\n        **kwargs: Any,\n    ) -> Neo4jVector:\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        if not metadatas:\n            metadatas = [{} for _ in texts]\n        store = cls(\n            embedding=embedding,\n            search_type=search_type,\n            **kwargs,\n        )\n        # Check if the vector index already exists\n        embedding_dimension = store.retrieve_existing_index()\n        # If the vector index doesn't exist yet\n        if not embedding_dimension:\n            store.create_new_index()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-9", "text": "if not embedding_dimension:\n            store.create_new_index()\n        # If the index already exists, check if embedding dimensions match\n        elif not store.embedding_dimension == embedding_dimension:\n            raise ValueError(\n                f\"Index with name {store.index_name} already exists.\"\n                \"The provided embedding function and vector index \"\n                \"dimensions do not match.\\n\"\n                f\"Embedding function dimension: {store.embedding_dimension}\\n\"\n                f\"Vector index dimension: {embedding_dimension}\"\n            )\n        if search_type == SearchType.HYBRID:\n            fts_node_label = store.retrieve_existing_fts_index()\n            # If the FTS index doesn't exist yet\n            if not fts_node_label:\n                store.create_new_keyword_index()\n            else:  # Validate that FTS and Vector index use the same information\n                if not fts_node_label == store.node_label:\n                    raise ValueError(\n                        \"Vector and keyword index don't index the same node label\"\n                    )\n        # Create unique constraint for faster import\n        if create_id_index:\n            store.query(\n                \"CREATE CONSTRAINT IF NOT EXISTS \"\n                f\"FOR (n:`{store.node_label}`) REQUIRE n.id IS UNIQUE;\"\n            )\n        store.add_embeddings(\n            texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs\n        )\n        return store\n[docs]    def add_embeddings(\n        self,\n        texts: Iterable[str],\n        embeddings: List[List[float]],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add embeddings to the vectorstore.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-10", "text": "\"\"\"Add embeddings to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            embeddings: List of list of embedding vectors.\n            metadatas: List of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        \"\"\"\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        if not metadatas:\n            metadatas = [{} for _ in texts]\n        import_query = (\n            \"UNWIND $data AS row \"\n            \"CALL { WITH row \"\n            f\"MERGE (c:`{self.node_label}` {{id: row.id}}) \"\n            \"WITH c, row \"\n            f\"CALL db.create.setVectorProperty(c, \"\n            f\"'{self.embedding_node_property}', row.embedding) \"\n            \"YIELD node \"\n            f\"SET c.`{self.text_node_property}` = row.text \"\n            \"SET c += row.metadata } IN TRANSACTIONS OF 1000 ROWS\"\n        )\n        parameters = {\n            \"data\": [\n                {\"text\": text, \"metadata\": metadata, \"embedding\": embedding, \"id\": id}\n                for text, metadata, embedding, id in zip(\n                    texts, metadatas, embeddings, ids\n                )\n            ]\n        }\n        self.query(import_query, params=parameters)\n        return ids\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-11", "text": "\"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        embeddings = self.embedding.embed_documents(list(texts))\n        return self.add_embeddings(\n            texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs\n        )\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Run similarity search with Neo4jVector.\n        Args:\n            query (str): Query text to search for.\n            k (int): Number of results to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        embedding = self.embedding.embed_query(text=query)\n        return self.similarity_search_by_vector(\n            embedding=embedding,\n            k=k,\n            query=query,\n        )\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 4\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        embedding = self.embedding.embed_query(query)\n        docs = self.similarity_search_with_score_by_vector(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-12", "text": "docs = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, query=query\n        )\n        return docs\n[docs]    def similarity_search_with_score_by_vector(\n        self, embedding: List[float], k: int = 4, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Perform a similarity search in the Neo4j database using a\n        given vector and return the top k similar documents with their scores.\n        This method uses a Cypher query to find the top k documents that\n        are most similar to a given embedding. The similarity is measured\n        using a vector index in the Neo4j database. The results are returned\n        as a list of tuples, each containing a Document object and\n        its similarity score.\n        Args:\n            embedding (List[float]): The embedding vector to compare against.\n            k (int, optional): The number of top similar documents to retrieve.\n        Returns:\n            List[Tuple[Document, float]]: A list of tuples, each containing\n                                a Document object and its similarity score.\n        \"\"\"\n        default_retrieval = (\n            f\"RETURN node.`{self.text_node_property}` AS text, score, \"\n            f\"node {{.*, `{self.text_node_property}`: Null, \"\n            f\"`{self.embedding_node_property}`: Null, id: Null }} AS metadata\"\n        )\n        retrieval_query = (\n            self.retrieval_query if self.retrieval_query else default_retrieval\n        )\n        read_query = _get_search_index_query(self.search_type) + retrieval_query\n        parameters = {\n            \"index\": self.index_name,\n            \"k\": k,\n            \"embedding\": embedding,\n            \"keyword_index\": self.keyword_index_name,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-13", "text": "\"embedding\": embedding,\n            \"keyword_index\": self.keyword_index_name,\n            \"query\": kwargs[\"query\"],\n        }\n        results = self.query(read_query, params=parameters)\n        docs = [\n            (\n                Document(\n                    page_content=result[\"text\"],\n                    metadata={\n                        k: v for k, v in result[\"metadata\"].items() if v is not None\n                    },\n                ),\n                result[\"score\"],\n            )\n            for result in results\n        ]\n        return docs\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query vector.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, **kwargs\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[Neo4jVector],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Neo4jVector:\n        \"\"\"\n        Return Neo4jVector initialized from texts and embeddings.\n        Neo4j credentials are required in the form of `url`, `username`,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-14", "text": "Neo4j credentials are required in the form of `url`, `username`,\n        and `password` and optional `database` parameters.\n        \"\"\"\n        embeddings = embedding.embed_documents(list(texts))\n        return cls.__from(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            distance_strategy=distance_strategy,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_embeddings(\n        cls,\n        text_embeddings: List[Tuple[str, List[float]]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> Neo4jVector:\n        \"\"\"Construct Neo4jVector wrapper from raw documents and pre-\n        generated embeddings.\n        Return Neo4jVector initialized from documents and embeddings.\n        Neo4j credentials are required in the form of `url`, `username`,\n        and `password` and optional `database` parameters.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores.neo4j_vector import Neo4jVector\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                text_embeddings = embeddings.embed_documents(texts)\n                text_embedding_pairs = list(zip(texts, text_embeddings))\n                vectorstore = Neo4jVector.from_embeddings(\n                    text_embedding_pairs, embeddings)\n        \"\"\"\n        texts = [t[0] for t in text_embeddings]\n        embeddings = [t[1] for t in text_embeddings]\n        return cls.__from(\n            texts,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-15", "text": "return cls.__from(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            distance_strategy=distance_strategy,\n            pre_delete_collection=pre_delete_collection,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_existing_index(\n        cls: Type[Neo4jVector],\n        embedding: Embeddings,\n        index_name: str,\n        search_type: SearchType = DEFAULT_SEARCH_TYPE,\n        keyword_index_name: Optional[str] = None,\n        **kwargs: Any,\n    ) -> Neo4jVector:\n        \"\"\"\n        Get instance of an existing Neo4j vector index. This method will\n        return the instance of the store without inserting any new\n        embeddings.\n        Neo4j credentials are required in the form of `url`, `username`,\n        and `password` and optional `database` parameters along with\n        the `index_name` definition.\n        \"\"\"\n        if search_type == SearchType.HYBRID and not keyword_index_name:\n            raise ValueError(\n                \"keyword_index name has to be specified \"\n                \"when using hybrid search option\"\n            )\n        store = cls(\n            embedding=embedding,\n            index_name=index_name,\n            keyword_index_name=keyword_index_name,\n            search_type=search_type,\n            **kwargs,\n        )\n        embedding_dimension = store.retrieve_existing_index()\n        if not embedding_dimension:\n            raise ValueError(\n                \"The specified vector index name does not exist. \"\n                \"Make sure to check if you spelled it correctly\"\n            )\n        # Check if embedding function and vector index dimensions match\n        if not store.embedding_dimension == embedding_dimension:\n            raise ValueError(\n                \"The provided embedding function and vector index \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-16", "text": "raise ValueError(\n                \"The provided embedding function and vector index \"\n                \"dimensions do not match.\\n\"\n                f\"Embedding function dimension: {store.embedding_dimension}\\n\"\n                f\"Vector index dimension: {embedding_dimension}\"\n            )\n        if search_type == SearchType.HYBRID:\n            fts_node_label = store.retrieve_existing_fts_index()\n            # If the FTS index doesn't exist yet\n            if not fts_node_label:\n                raise ValueError(\n                    \"The specified keyword index name does not exist. \"\n                    \"Make sure to check if you spelled it correctly\"\n                )\n            else:  # Validate that FTS and Vector index use the same information\n                if not fts_node_label == store.node_label:\n                    raise ValueError(\n                        \"Vector and keyword index don't index the same node label\"\n                    )\n        return store\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[Neo4jVector],\n        documents: List[Document],\n        embedding: Embeddings,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Neo4jVector:\n        \"\"\"\n        Return Neo4jVector initialized from documents and embeddings.\n        Neo4j credentials are required in the form of `url`, `username`,\n        and `password` and optional `database` parameters.\n        \"\"\"\n        texts = [d.page_content for d in documents]\n        metadatas = [d.metadata for d in documents]\n        return cls.from_texts(\n            texts=texts,\n            embedding=embedding,\n            distance_strategy=distance_strategy,\n            metadatas=metadatas,\n            ids=ids,\n            **kwargs,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-17", "text": "ids=ids,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_existing_graph(\n        cls: Type[Neo4jVector],\n        embedding: Embeddings,\n        node_label: str,\n        embedding_node_property: str,\n        text_node_properties: List[str],\n        *,\n        keyword_index_name: Optional[str] = \"keyword\",\n        index_name: str = \"vector\",\n        search_type: SearchType = DEFAULT_SEARCH_TYPE,\n        retrieval_query: str = \"\",\n        **kwargs: Any,\n    ) -> Neo4jVector:\n        \"\"\"\n        Initialize and return a Neo4jVector instance from an existing graph.\n        This method initializes a Neo4jVector instance using the provided\n        parameters and the existing graph. It validates the existence of\n        the indices and creates new ones if they don't exist.\n        Returns:\n        Neo4jVector: An instance of Neo4jVector initialized with the provided parameters\n                    and existing graph.\n        Example:\n        >>> neo4j_vector = Neo4jVector.from_existing_graph(\n        ...     embedding=my_embedding,\n        ...     node_label=\"Document\",\n        ...     embedding_node_property=\"embedding\",\n        ...     text_node_properties=[\"title\", \"content\"]\n        ... )\n        Note:\n        Neo4j credentials are required in the form of `url`, `username`, and `password`,\n        and optional `database` parameters passed as additional keyword arguments.\n        \"\"\"\n        # Validate the list is not empty\n        if not text_node_properties:\n            raise ValueError(\n                \"Parameter `text_node_properties` must not be an empty list\"\n            )\n        # Prefer retrieval query from params, otherwise construct it\n        if not retrieval_query:\n            retrieval_query = (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-18", "text": "if not retrieval_query:\n            retrieval_query = (\n                f\"RETURN reduce(str='', k IN {text_node_properties} |\"\n                \" str + '\\\\n' + k + ': ' + coalesce(node[k], '')) AS text, \"\n                \"node {.*, `\"\n                + embedding_node_property\n                + \"`: Null, id: Null, \"\n                + \", \".join([f\"`{prop}`: Null\" for prop in text_node_properties])\n                + \"} AS metadata, score\"\n            )\n        store = cls(\n            embedding=embedding,\n            index_name=index_name,\n            keyword_index_name=keyword_index_name,\n            search_type=search_type,\n            retrieval_query=retrieval_query,\n            node_label=node_label,\n            embedding_node_property=embedding_node_property,\n            **kwargs,\n        )\n        # Check if the vector index already exists\n        embedding_dimension = store.retrieve_existing_index()\n        # If the vector index doesn't exist yet\n        if not embedding_dimension:\n            store.create_new_index()\n        # If the index already exists, check if embedding dimensions match\n        elif not store.embedding_dimension == embedding_dimension:\n            raise ValueError(\n                f\"Index with name {store.index_name} already exists.\"\n                \"The provided embedding function and vector index \"\n                \"dimensions do not match.\\n\"\n                f\"Embedding function dimension: {store.embedding_dimension}\\n\"\n                f\"Vector index dimension: {embedding_dimension}\"\n            )\n        # FTS index for Hybrid search\n        if search_type == SearchType.HYBRID:\n            fts_node_label = store.retrieve_existing_fts_index(text_node_properties)\n            # If the FTS index doesn't exist yet\n            if not fts_node_label:\n                store.create_new_keyword_index(text_node_properties)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-19", "text": "if not fts_node_label:\n                store.create_new_keyword_index(text_node_properties)\n            else:  # Validate that FTS and Vector index use the same information\n                if not fts_node_label == store.node_label:\n                    raise ValueError(\n                        \"Vector and keyword index don't index the same node label\"\n                    )\n        # Populate embeddings\n        while True:\n            fetch_query = (\n                f\"MATCH (n:`{node_label}`) \"\n                f\"WHERE n.{embedding_node_property} IS null \"\n                \"AND any(k in $props WHERE n[k] IS NOT null) \"\n                f\"RETURN elementId(n) AS id, reduce(str='',\"\n                \"k IN $props | str + '\\\\n' + k + ':' + coalesce(n[k], '')) AS text \"\n                \"LIMIT 1000\"\n            )\n            data = store.query(fetch_query, params={\"props\": text_node_properties})\n            text_embeddings = embedding.embed_documents([el[\"text\"] for el in data])\n            params = {\n                \"data\": [\n                    {\"id\": el[\"id\"], \"embedding\": embedding}\n                    for el, embedding in zip(data, text_embeddings)\n                ]\n            }\n            store.query(\n                \"UNWIND $data AS row \"\n                f\"MATCH (n:`{node_label}`) \"\n                \"WHERE elementId(n) = row.id \"\n                f\"CALL db.create.setVectorProperty(n, \"\n                f\"'{embedding_node_property}', row.embedding) \"\n                \"YIELD node RETURN count(*)\",\n                params=params,\n            )\n            # If embedding calculation should be stopped\n            if len(data) < 1000:\n                break\n        return store\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "0aba36bff0d0-20", "text": "def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        \"\"\"\n        The 'correct' relevance function\n        may differ depending on a few things, including:\n        - the distance / similarity metric used by the VectorStore\n        - the scale of your embeddings (OpenAI's are unit normed. Many others are not!)\n        - embedding dimensionality\n        - etc.\n        \"\"\"\n        if self.override_relevance_score_fn is not None:\n            return self.override_relevance_score_fn\n        # Default strategy is to rely on distance strategy provided\n        # in vectorstore constructor\n        if self._distance_strategy == DistanceStrategy.COSINE:\n            return lambda x: x\n        elif self._distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE:\n            return lambda x: x\n        else:\n            raise ValueError(\n                \"No supported normalization function\"\n                f\" for distance_strategy of {self._distance_strategy}.\"\n                \"Consider providing relevance_score_fn to PGVector constructor.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html"}
{"id": "41e880cdf43f-0", "text": "Source code for langchain.vectorstores.azuresearch\nfrom __future__ import annotations\nimport base64\nimport json\nimport logging\nimport uuid\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n)\nimport numpy as np\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForRetrieverRun,\n    CallbackManagerForRetrieverRun,\n)\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import BaseRetriever\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_env\nlogger = logging.getLogger()\nif TYPE_CHECKING:\n    from azure.search.documents import SearchClient\n    from azure.search.documents.indexes.models import (\n        ScoringProfile,\n        SearchField,\n        SemanticSettings,\n        VectorSearch,\n    )\n# Allow overriding field names for Azure Search\nFIELDS_ID = get_from_env(\n    key=\"AZURESEARCH_FIELDS_ID\", env_key=\"AZURESEARCH_FIELDS_ID\", default=\"id\"\n)\nFIELDS_CONTENT = get_from_env(\n    key=\"AZURESEARCH_FIELDS_CONTENT\",\n    env_key=\"AZURESEARCH_FIELDS_CONTENT\",\n    default=\"content\",\n)\nFIELDS_CONTENT_VECTOR = get_from_env(\n    key=\"AZURESEARCH_FIELDS_CONTENT_VECTOR\",\n    env_key=\"AZURESEARCH_FIELDS_CONTENT_VECTOR\",\n    default=\"content_vector\",\n)\nFIELDS_METADATA = get_from_env(\n    key=\"AZURESEARCH_FIELDS_TAG\", env_key=\"AZURESEARCH_FIELDS_TAG\", default=\"metadata\"\n)\nMAX_UPLOAD_BATCH_SIZE = 1000\ndef _get_search_client(\n    endpoint: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "41e880cdf43f-1", "text": "def _get_search_client(\n    endpoint: str,\n    key: str,\n    index_name: str,\n    semantic_configuration_name: Optional[str] = None,\n    fields: Optional[List[SearchField]] = None,\n    vector_search: Optional[VectorSearch] = None,\n    semantic_settings: Optional[SemanticSettings] = None,\n    scoring_profiles: Optional[List[ScoringProfile]] = None,\n    default_scoring_profile: Optional[str] = None,\n    default_fields: Optional[List[SearchField]] = None,\n    user_agent: Optional[str] = \"langchain\",\n) -> SearchClient:\n    from azure.core.credentials import AzureKeyCredential\n    from azure.core.exceptions import ResourceNotFoundError\n    from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential\n    from azure.search.documents import SearchClient\n    from azure.search.documents.indexes import SearchIndexClient\n    from azure.search.documents.indexes.models import (\n        HnswVectorSearchAlgorithmConfiguration,\n        PrioritizedFields,\n        SearchIndex,\n        SemanticConfiguration,\n        SemanticField,\n        SemanticSettings,\n        VectorSearch,\n    )\n    default_fields = default_fields or []\n    if key is None:\n        credential = DefaultAzureCredential()\n    elif key.upper() == \"INTERACTIVE\":\n        credential = InteractiveBrowserCredential()\n        credential.get_token(\"https://search.azure.com/.default\")\n    else:\n        credential = AzureKeyCredential(key)\n    index_client: SearchIndexClient = SearchIndexClient(\n        endpoint=endpoint, credential=credential, user_agent=user_agent\n    )\n    try:\n        index_client.get_index(name=index_name)\n    except ResourceNotFoundError:\n        # Fields configuration\n        if fields is not None:\n            # Check mandatory fields", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "41e880cdf43f-2", "text": "# Fields configuration\n        if fields is not None:\n            # Check mandatory fields\n            fields_types = {f.name: f.type for f in fields}\n            mandatory_fields = {df.name: df.type for df in default_fields}\n            # Check for missing keys\n            missing_fields = {\n                key: mandatory_fields[key]\n                for key, value in set(mandatory_fields.items())\n                - set(fields_types.items())\n            }\n            if len(missing_fields) > 0:\n                # Helper for formatting field information for each missing field.\n                def fmt_err(x: str) -> str:\n                    return (\n                        f\"{x} current type: '{fields_types.get(x, 'MISSING')}'. \"\n                        f\"It has to be '{mandatory_fields.get(x)}' or you can point \"\n                        f\"to a different '{mandatory_fields.get(x)}' field name by \"\n                        f\"using the env variable 'AZURESEARCH_FIELDS_{x.upper()}'\"\n                    )\n                error = \"\\n\".join([fmt_err(x) for x in missing_fields])\n                raise ValueError(\n                    f\"You need to specify at least the following fields \"\n                    f\"{missing_fields} or provide alternative field names in the env \"\n                    f\"variables.\\n\\n{error}\"\n                )\n        else:\n            fields = default_fields\n        # Vector search configuration\n        if vector_search is None:\n            vector_search = VectorSearch(\n                algorithm_configurations=[\n                    HnswVectorSearchAlgorithmConfiguration(\n                        name=\"default\",\n                        kind=\"hnsw\",\n                        parameters={  # type: ignore\n                            \"m\": 4,\n                            \"efConstruction\": 400,\n                            \"efSearch\": 500,\n                            \"metric\": \"cosine\",\n                        },\n                    )\n                ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "41e880cdf43f-3", "text": "\"metric\": \"cosine\",\n                        },\n                    )\n                ]\n            )\n        # Create the semantic settings with the configuration\n        if semantic_settings is None and semantic_configuration_name is not None:\n            semantic_settings = SemanticSettings(\n                configurations=[\n                    SemanticConfiguration(\n                        name=semantic_configuration_name,\n                        prioritized_fields=PrioritizedFields(\n                            prioritized_content_fields=[\n                                SemanticField(field_name=FIELDS_CONTENT)\n                            ],\n                        ),\n                    )\n                ]\n            )\n        # Create the search index with the semantic settings and vector search\n        index = SearchIndex(\n            name=index_name,\n            fields=fields,\n            vector_search=vector_search,\n            semantic_settings=semantic_settings,\n            scoring_profiles=scoring_profiles,\n            default_scoring_profile=default_scoring_profile,\n        )\n        index_client.create_index(index)\n    # Create the search client\n    return SearchClient(\n        endpoint=endpoint,\n        index_name=index_name,\n        credential=credential,\n        user_agent=user_agent,\n    )\n[docs]class AzureSearch(VectorStore):\n    \"\"\"`Azure Cognitive Search` vector store.\"\"\"\n[docs]    def __init__(\n        self,\n        azure_search_endpoint: str,\n        azure_search_key: str,\n        index_name: str,\n        embedding_function: Callable,\n        search_type: str = \"hybrid\",\n        semantic_configuration_name: Optional[str] = None,\n        semantic_query_language: str = \"en-us\",\n        fields: Optional[List[SearchField]] = None,\n        vector_search: Optional[VectorSearch] = None,\n        semantic_settings: Optional[SemanticSettings] = None,\n        scoring_profiles: Optional[List[ScoringProfile]] = None,\n        default_scoring_profile: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "41e880cdf43f-4", "text": "default_scoring_profile: Optional[str] = None,\n        **kwargs: Any,\n    ):\n        from azure.search.documents.indexes.models import (\n            SearchableField,\n            SearchField,\n            SearchFieldDataType,\n            SimpleField,\n        )\n        \"\"\"Initialize with necessary components.\"\"\"\n        # Initialize base class\n        self.embedding_function = embedding_function\n        default_fields = [\n            SimpleField(\n                name=FIELDS_ID,\n                type=SearchFieldDataType.String,\n                key=True,\n                filterable=True,\n            ),\n            SearchableField(\n                name=FIELDS_CONTENT,\n                type=SearchFieldDataType.String,\n            ),\n            SearchField(\n                name=FIELDS_CONTENT_VECTOR,\n                type=SearchFieldDataType.Collection(SearchFieldDataType.Single),\n                searchable=True,\n                vector_search_dimensions=len(embedding_function(\"Text\")),\n                vector_search_configuration=\"default\",\n            ),\n            SearchableField(\n                name=FIELDS_METADATA,\n                type=SearchFieldDataType.String,\n            ),\n        ]\n        user_agent = \"langchain\"\n        if \"user_agent\" in kwargs and kwargs[\"user_agent\"]:\n            user_agent += \" \" + kwargs[\"user_agent\"]\n        self.client = _get_search_client(\n            azure_search_endpoint,\n            azure_search_key,\n            index_name,\n            semantic_configuration_name=semantic_configuration_name,\n            fields=fields,\n            vector_search=vector_search,\n            semantic_settings=semantic_settings,\n            scoring_profiles=scoring_profiles,\n            default_scoring_profile=default_scoring_profile,\n            default_fields=default_fields,\n            user_agent=user_agent,\n        )\n        self.search_type = search_type\n        self.semantic_configuration_name = semantic_configuration_name\n        self.semantic_query_language = semantic_query_language\n        self.fields = fields if fields else default_fields", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "41e880cdf43f-5", "text": "self.fields = fields if fields else default_fields\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        # TODO: Support embedding object directly\n        return None\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add texts data to an existing index.\"\"\"\n        keys = kwargs.get(\"keys\")\n        ids = []\n        # Write data to index\n        data = []\n        for i, text in enumerate(texts):\n            # Use provided key otherwise use default key\n            key = keys[i] if keys else str(uuid.uuid4())\n            # Encoding key for Azure Search valid characters\n            key = base64.urlsafe_b64encode(bytes(key, \"utf-8\")).decode(\"ascii\")\n            metadata = metadatas[i] if metadatas else {}\n            # Add data to index\n            # Additional metadata to fields mapping\n            doc = {\n                \"@search.action\": \"upload\",\n                FIELDS_ID: key,\n                FIELDS_CONTENT: text,\n                FIELDS_CONTENT_VECTOR: np.array(\n                    self.embedding_function(text), dtype=np.float32\n                ).tolist(),\n                FIELDS_METADATA: json.dumps(metadata),\n            }\n            if metadata:\n                additional_fields = {\n                    k: v\n                    for k, v in metadata.items()\n                    if k in [x.name for x in self.fields]\n                }\n                doc.update(additional_fields)\n            data.append(doc)\n            ids.append(key)\n            # Upload data in batches\n            if len(data) == MAX_UPLOAD_BATCH_SIZE:\n                response = self.client.upload_documents(documents=data)\n                # Check if all documents were successfully uploaded", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "41e880cdf43f-6", "text": "# Check if all documents were successfully uploaded\n                if not all([r.succeeded for r in response]):\n                    raise Exception(response)\n                # Reset data\n                data = []\n        # Considering case where data is an exact multiple of batch-size entries\n        if len(data) == 0:\n            return ids\n        # Upload data to index\n        response = self.client.upload_documents(documents=data)\n        # Check if all documents were successfully uploaded\n        if all([r.succeeded for r in response]):\n            return ids\n        else:\n            raise Exception(response)\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        search_type = kwargs.get(\"search_type\", self.search_type)\n        if search_type == \"similarity\":\n            docs = self.vector_search(query, k=k, **kwargs)\n        elif search_type == \"hybrid\":\n            docs = self.hybrid_search(query, k=k, **kwargs)\n        elif search_type == \"semantic_hybrid\":\n            docs = self.semantic_hybrid_search(query, k=k, **kwargs)\n        else:\n            raise ValueError(f\"search_type of {search_type} not allowed.\")\n        return docs\n[docs]    def similarity_search_with_relevance_scores(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        score_threshold = kwargs.pop(\"score_threshold\", None)\n        result = self.vector_search_with_score(query, k=k, **kwargs)\n        return (\n            result\n            if score_threshold is None\n            else [r for r in result if r[1] >= score_threshold]\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "41e880cdf43f-7", "text": ")\n[docs]    def vector_search(self, query: str, k: int = 4, **kwargs: Any) -> List[Document]:\n        \"\"\"\n        Returns the most similar indexed documents to the query text.\n        Args:\n            query (str): The query text for which to find similar documents.\n            k (int): The number of documents to return. Default is 4.\n        Returns:\n            List[Document]: A list of documents that are most similar to the query text.\n        \"\"\"\n        docs_and_scores = self.vector_search_with_score(\n            query, k=k, filters=kwargs.get(\"filters\", None)\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def vector_search_with_score(\n        self, query: str, k: int = 4, filters: Optional[str] = None\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        from azure.search.documents.models import Vector\n        results = self.client.search(\n            search_text=\"\",\n            vectors=[\n                Vector(\n                    value=np.array(\n                        self.embedding_function(query), dtype=np.float32\n                    ).tolist(),\n                    k=k,\n                    fields=FIELDS_CONTENT_VECTOR,\n                )\n            ],\n            filter=filters,\n        )\n        # Convert results to Document objects\n        docs = [\n            (\n                Document(\n                    page_content=result.pop(FIELDS_CONTENT),\n                    metadata=json.loads(result[FIELDS_METADATA])\n                    if FIELDS_METADATA in result\n                    else {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "41e880cdf43f-8", "text": "if FIELDS_METADATA in result\n                    else {\n                        k: v for k, v in result.items() if k != FIELDS_CONTENT_VECTOR\n                    },\n                ),\n                float(result[\"@search.score\"]),\n            )\n            for result in results\n        ]\n        return docs\n[docs]    def hybrid_search(self, query: str, k: int = 4, **kwargs: Any) -> List[Document]:\n        \"\"\"\n        Returns the most similar indexed documents to the query text.\n        Args:\n            query (str): The query text for which to find similar documents.\n            k (int): The number of documents to return. Default is 4.\n        Returns:\n            List[Document]: A list of documents that are most similar to the query text.\n        \"\"\"\n        docs_and_scores = self.hybrid_search_with_score(\n            query, k=k, filters=kwargs.get(\"filters\", None)\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def hybrid_search_with_score(\n        self, query: str, k: int = 4, filters: Optional[str] = None\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query with an hybrid query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        from azure.search.documents.models import Vector\n        results = self.client.search(\n            search_text=query,\n            vectors=[\n                Vector(\n                    value=np.array(\n                        self.embedding_function(query), dtype=np.float32\n                    ).tolist(),\n                    k=k,\n                    fields=FIELDS_CONTENT_VECTOR,\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "41e880cdf43f-9", "text": "k=k,\n                    fields=FIELDS_CONTENT_VECTOR,\n                )\n            ],\n            filter=filters,\n            top=k,\n        )\n        # Convert results to Document objects\n        docs = [\n            (\n                Document(\n                    page_content=result.pop(FIELDS_CONTENT),\n                    metadata=json.loads(result[FIELDS_METADATA])\n                    if FIELDS_METADATA in result\n                    else {\n                        k: v for k, v in result.items() if k != FIELDS_CONTENT_VECTOR\n                    },\n                ),\n                float(result[\"@search.score\"]),\n            )\n            for result in results\n        ]\n        return docs\n[docs]    def semantic_hybrid_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"\n        Returns the most similar indexed documents to the query text.\n        Args:\n            query (str): The query text for which to find similar documents.\n            k (int): The number of documents to return. Default is 4.\n        Returns:\n            List[Document]: A list of documents that are most similar to the query text.\n        \"\"\"\n        docs_and_scores = self.semantic_hybrid_search_with_score_and_rerank(\n            query, k=k, filters=kwargs.get(\"filters\", None)\n        )\n        return [doc for doc, _, _ in docs_and_scores]\n[docs]    def semantic_hybrid_search_with_score(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Returns the most similar indexed documents to the query text.\n        Args:\n            query (str): The query text for which to find similar documents.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "41e880cdf43f-10", "text": "Args:\n            query (str): The query text for which to find similar documents.\n            k (int): The number of documents to return. Default is 4.\n        Returns:\n            List[Document]: A list of documents that are most similar to the query text.\n        \"\"\"\n        docs_and_scores = self.semantic_hybrid_search_with_score_and_rerank(\n            query, k=k, filters=kwargs.get(\"filters\", None)\n        )\n        return [(doc, score) for doc, score, _ in docs_and_scores]\n[docs]    def semantic_hybrid_search_with_score_and_rerank(\n        self, query: str, k: int = 4, filters: Optional[str] = None\n    ) -> List[Tuple[Document, float, float]]:\n        \"\"\"Return docs most similar to query with an hybrid query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        from azure.search.documents.models import Vector\n        results = self.client.search(\n            search_text=query,\n            vectors=[\n                Vector(\n                    value=np.array(\n                        self.embedding_function(query), dtype=np.float32\n                    ).tolist(),\n                    k=50,\n                    fields=FIELDS_CONTENT_VECTOR,\n                )\n            ],\n            filter=filters,\n            query_type=\"semantic\",\n            query_language=self.semantic_query_language,\n            semantic_configuration_name=self.semantic_configuration_name,\n            query_caption=\"extractive\",\n            query_answer=\"extractive\",\n            top=k,\n        )\n        # Get Semantic Answers\n        semantic_answers = results.get_answers() or []\n        semantic_answers_dict: Dict = {}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "41e880cdf43f-11", "text": "semantic_answers = results.get_answers() or []\n        semantic_answers_dict: Dict = {}\n        for semantic_answer in semantic_answers:\n            semantic_answers_dict[semantic_answer.key] = {\n                \"text\": semantic_answer.text,\n                \"highlights\": semantic_answer.highlights,\n            }\n        # Convert results to Document objects\n        docs = [\n            (\n                Document(\n                    page_content=result.pop(FIELDS_CONTENT),\n                    metadata={\n                        **(\n                            json.loads(result[FIELDS_METADATA])\n                            if FIELDS_METADATA in result\n                            else {\n                                k: v\n                                for k, v in result.items()\n                                if k != FIELDS_CONTENT_VECTOR\n                            }\n                        ),\n                        **{\n                            \"captions\": {\n                                \"text\": result.get(\"@search.captions\", [{}])[0].text,\n                                \"highlights\": result.get(\"@search.captions\", [{}])[\n                                    0\n                                ].highlights,\n                            }\n                            if result.get(\"@search.captions\")\n                            else {},\n                            \"answers\": semantic_answers_dict.get(\n                                json.loads(result[\"metadata\"]).get(\"key\"), \"\"\n                            ),\n                        },\n                    },\n                ),\n                float(result[\"@search.score\"]),\n                float(result[\"@search.reranker_score\"]),\n            )\n            for result in results\n        ]\n        return docs\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[AzureSearch],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        azure_search_endpoint: str = \"\",\n        azure_search_key: str = \"\",\n        index_name: str = \"langchain-index\",\n        **kwargs: Any,\n    ) -> AzureSearch:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "41e880cdf43f-12", "text": "**kwargs: Any,\n    ) -> AzureSearch:\n        # Creating a new Azure Search instance\n        azure_search = cls(\n            azure_search_endpoint,\n            azure_search_key,\n            index_name,\n            embedding.embed_query,\n        )\n        azure_search.add_texts(texts, metadatas, **kwargs)\n        return azure_search\n[docs]class AzureSearchVectorStoreRetriever(BaseRetriever):\n    \"\"\"Retriever that uses `Azure Cognitive Search`.\"\"\"\n    vectorstore: AzureSearch\n    \"\"\"Azure Search instance used to find similar documents.\"\"\"\n    search_type: str = \"hybrid\"\n    \"\"\"Type of search to perform. Options are \"similarity\", \"hybrid\",\n    \"semantic_hybrid\".\"\"\"\n    k: int = 4\n    \"\"\"Number of documents to return.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @root_validator()\n    def validate_search_type(cls, values: Dict) -> Dict:\n        \"\"\"Validate search type.\"\"\"\n        if \"search_type\" in values:\n            search_type = values[\"search_type\"]\n            if search_type not in (\"similarity\", \"hybrid\", \"semantic_hybrid\"):\n                raise ValueError(f\"search_type of {search_type} not allowed.\")\n        return values\n    def _get_relevant_documents(\n        self,\n        query: str,\n        run_manager: CallbackManagerForRetrieverRun,\n        **kwargs: Any,\n    ) -> List[Document]:\n        if self.search_type == \"similarity\":\n            docs = self.vectorstore.vector_search(query, k=self.k, **kwargs)\n        elif self.search_type == \"hybrid\":\n            docs = self.vectorstore.hybrid_search(query, k=self.k, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "41e880cdf43f-13", "text": "docs = self.vectorstore.hybrid_search(query, k=self.k, **kwargs)\n        elif self.search_type == \"semantic_hybrid\":\n            docs = self.vectorstore.semantic_hybrid_search(query, k=self.k, **kwargs)\n        else:\n            raise ValueError(f\"search_type of {self.search_type} not allowed.\")\n        return docs\n    async def _aget_relevant_documents(\n        self,\n        query: str,\n        *,\n        run_manager: AsyncCallbackManagerForRetrieverRun,\n    ) -> List[Document]:\n        raise NotImplementedError(\n            \"AzureSearchVectorStoreRetriever does not support async\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html"}
{"id": "efb92b8561a3-0", "text": "Source code for langchain.vectorstores.lancedb\nfrom __future__ import annotations\nimport uuid\nfrom typing import Any, Iterable, List, Optional\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\n[docs]class LanceDB(VectorStore):\n    \"\"\"`LanceDB` vector store.\n    To use, you should have ``lancedb`` python package installed.\n    Example:\n        .. code-block:: python\n            db = lancedb.connect('./lancedb')\n            table = db.open_table('my_table')\n            vectorstore = LanceDB(table, embedding_function)\n            vectorstore.add_texts(['text1', 'text2'])\n            result = vectorstore.similarity_search('text1')\n    \"\"\"\n[docs]    def __init__(\n        self,\n        connection: Any,\n        embedding: Embeddings,\n        vector_key: Optional[str] = \"vector\",\n        id_key: Optional[str] = \"id\",\n        text_key: Optional[str] = \"text\",\n    ):\n        \"\"\"Initialize with Lance DB connection\"\"\"\n        try:\n            import lancedb\n        except ImportError:\n            raise ImportError(\n                \"Could not import lancedb python package. \"\n                \"Please install it with `pip install lancedb`.\"\n            )\n        if not isinstance(connection, lancedb.db.LanceTable):\n            raise ValueError(\n                \"connection should be an instance of lancedb.db.LanceTable, \",\n                f\"got {type(connection)}\",\n            )\n        self._connection = connection\n        self._embedding = embedding\n        self._vector_key = vector_key\n        self._id_key = id_key\n        self._text_key = text_key\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html"}
{"id": "efb92b8561a3-1", "text": "self._text_key = text_key\n    @property\n    def embeddings(self) -> Embeddings:\n        return self._embedding\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Turn texts into embedding and add it to the database\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of ids to associate with the texts.\n        Returns:\n            List of ids of the added texts.\n        \"\"\"\n        # Embed texts and create documents\n        docs = []\n        ids = ids or [str(uuid.uuid4()) for _ in texts]\n        embeddings = self._embedding.embed_documents(list(texts))\n        for idx, text in enumerate(texts):\n            embedding = embeddings[idx]\n            metadata = metadatas[idx] if metadatas else {}\n            docs.append(\n                {\n                    self._vector_key: embedding,\n                    self._id_key: ids[idx],\n                    self._text_key: text,\n                    **metadata,\n                }\n            )\n        self._connection.add(docs)\n        return ids\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return documents most similar to the query\n        Args:\n            query: String to query the vectorstore with.\n            k: Number of documents to return.\n        Returns:\n            List of documents most similar to the query.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html"}
{"id": "efb92b8561a3-2", "text": "Returns:\n            List of documents most similar to the query.\n        \"\"\"\n        embedding = self._embedding.embed_query(query)\n        docs = self._connection.search(embedding).limit(k).to_df()\n        return [\n            Document(\n                page_content=row[self._text_key],\n                metadata=row[docs.columns != self._text_key],\n            )\n            for _, row in docs.iterrows()\n        ]\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        connection: Any = None,\n        vector_key: Optional[str] = \"vector\",\n        id_key: Optional[str] = \"id\",\n        text_key: Optional[str] = \"text\",\n        **kwargs: Any,\n    ) -> LanceDB:\n        instance = LanceDB(\n            connection,\n            embedding,\n            vector_key,\n            id_key,\n            text_key,\n        )\n        instance.add_texts(texts, metadatas=metadatas, **kwargs)\n        return instance", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html"}
{"id": "5fec310b6df0-0", "text": "Source code for langchain.vectorstores.pgvector\nfrom __future__ import annotations\nimport asyncio\nimport contextlib\nimport enum\nimport logging\nimport uuid\nfrom functools import partial\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Generator,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n)\nimport numpy as np\nimport sqlalchemy\nfrom sqlalchemy import delete\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom sqlalchemy.orm import Session\ntry:\n    from sqlalchemy.orm import declarative_base\nexcept ImportError:\n    from sqlalchemy.ext.declarative import declarative_base\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_dict_or_env\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nif TYPE_CHECKING:\n    from langchain.vectorstores._pgvector_data_models import CollectionStore\n[docs]class DistanceStrategy(str, enum.Enum):\n    \"\"\"Enumerator of the Distance strategies.\"\"\"\n    EUCLIDEAN = \"l2\"\n    COSINE = \"cosine\"\n    MAX_INNER_PRODUCT = \"inner\"\nDEFAULT_DISTANCE_STRATEGY = DistanceStrategy.COSINE\nBase = declarative_base()  # type: Any\n_LANGCHAIN_DEFAULT_COLLECTION_NAME = \"langchain\"\n[docs]class BaseModel(Base):\n    \"\"\"Base model for the SQL stores.\"\"\"\n    __abstract__ = True\n    uuid = sqlalchemy.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)\ndef _results_to_docs(docs_and_scores: Any) -> List[Document]:\n    \"\"\"Return docs from docs and scores.\"\"\"\n    return [doc for doc, _ in docs_and_scores]\n[docs]class PGVector(VectorStore):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-1", "text": "[docs]class PGVector(VectorStore):\n    \"\"\"`Postgres`/`PGVector` vector store.\n    To use, you should have the ``pgvector`` python package installed.\n    Args:\n        connection_string: Postgres connection string.\n        embedding_function: Any embedding function implementing\n            `langchain.embeddings.base.Embeddings` interface.\n        collection_name: The name of the collection to use. (default: langchain)\n            NOTE: This is not the name of the table, but the name of the collection.\n            The tables will be created when initializing the store (if not exists)\n            So, make sure the user has the right permissions to create tables.\n        distance_strategy: The distance strategy to use. (default: COSINE)\n        pre_delete_collection: If True, will delete the collection if it exists.\n            (default: False). Useful for testing.\n        engine_args: SQLAlchemy's create engine arguments.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import PGVector\n            from langchain.embeddings.openai import OpenAIEmbeddings\n            CONNECTION_STRING = \"postgresql+psycopg2://hwc@localhost:5432/test3\"\n            COLLECTION_NAME = \"state_of_the_union_test\"\n            embeddings = OpenAIEmbeddings()\n            vectorestore = PGVector.from_documents(\n                embedding=embeddings,\n                documents=docs,\n                collection_name=COLLECTION_NAME,\n                connection_string=CONNECTION_STRING,\n            )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        connection_string: str,\n        embedding_function: Embeddings,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        collection_metadata: Optional[dict] = None,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-2", "text": "distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        pre_delete_collection: bool = False,\n        logger: Optional[logging.Logger] = None,\n        relevance_score_fn: Optional[Callable[[float], float]] = None,\n        *,\n        connection: Optional[sqlalchemy.engine.Connection] = None,\n        engine_args: Optional[dict[str, Any]] = None,\n    ) -> None:\n        self.connection_string = connection_string\n        self.embedding_function = embedding_function\n        self.collection_name = collection_name\n        self.collection_metadata = collection_metadata\n        self._distance_strategy = distance_strategy\n        self.pre_delete_collection = pre_delete_collection\n        self.logger = logger or logging.getLogger(__name__)\n        self.override_relevance_score_fn = relevance_score_fn\n        self.engine_args = engine_args or {}\n        # Create a connection if not provided, otherwise use the provided connection\n        self._conn = connection if connection else self.connect()\n        self.__post_init__()\n    def __post_init__(\n        self,\n    ) -> None:\n        \"\"\"Initialize the store.\"\"\"\n        self.create_vector_extension()\n        from langchain.vectorstores._pgvector_data_models import (\n            CollectionStore,\n            EmbeddingStore,\n        )\n        self.CollectionStore = CollectionStore\n        self.EmbeddingStore = EmbeddingStore\n        self.create_tables_if_not_exists()\n        self.create_collection()\n    def __del__(self) -> None:\n        if self._conn:\n            self._conn.close()\n    @property\n    def embeddings(self) -> Embeddings:\n        return self.embedding_function\n[docs]    def connect(self) -> sqlalchemy.engine.Connection:\n        engine = sqlalchemy.create_engine(self.connection_string, **self.engine_args)\n        conn = engine.connect()\n        return conn", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-3", "text": "conn = engine.connect()\n        return conn\n[docs]    def create_vector_extension(self) -> None:\n        try:\n            with Session(self._conn) as session:\n                # The advisor lock fixes issue arising from concurrent\n                # creation of the vector extension.\n                # https://github.com/langchain-ai/langchain/issues/12933\n                # For more information see:\n                # https://www.postgresql.org/docs/16/explicit-locking.html#ADVISORY-LOCKS\n                statement = sqlalchemy.text(\n                    \"BEGIN;\"\n                    \"SELECT pg_advisory_xact_lock(1573678846307946496);\"\n                    \"CREATE EXTENSION IF NOT EXISTS vector;\"\n                    \"COMMIT;\"\n                )\n                session.execute(statement)\n                session.commit()\n        except Exception as e:\n            raise Exception(f\"Failed to create vector extension: {e}\") from e\n[docs]    def create_tables_if_not_exists(self) -> None:\n        with self._conn.begin():\n            Base.metadata.create_all(self._conn)\n[docs]    def drop_tables(self) -> None:\n        with self._conn.begin():\n            Base.metadata.drop_all(self._conn)\n[docs]    def create_collection(self) -> None:\n        if self.pre_delete_collection:\n            self.delete_collection()\n        with Session(self._conn) as session:\n            self.CollectionStore.get_or_create(\n                session, self.collection_name, cmetadata=self.collection_metadata\n            )\n[docs]    def delete_collection(self) -> None:\n        self.logger.debug(\"Trying to delete collection\")\n        with Session(self._conn) as session:\n            collection = self.get_collection(session)\n            if not collection:\n                self.logger.warning(\"Collection not found\")\n                return\n            session.delete(collection)\n            session.commit()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-4", "text": "return\n            session.delete(collection)\n            session.commit()\n    @contextlib.contextmanager\n    def _make_session(self) -> Generator[Session, None, None]:\n        \"\"\"Create a context manager for the session, bind to _conn string.\"\"\"\n        yield Session(self._conn)\n[docs]    def delete(\n        self,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Delete vectors by ids or uuids.\n        Args:\n            ids: List of ids to delete.\n        \"\"\"\n        with Session(self._conn) as session:\n            if ids is not None:\n                self.logger.debug(\n                    \"Trying to delete vectors by ids (represented by the model \"\n                    \"using the custom ids field)\"\n                )\n                stmt = delete(self.EmbeddingStore).where(\n                    self.EmbeddingStore.custom_id.in_(ids)\n                )\n                session.execute(stmt)\n            session.commit()\n[docs]    def get_collection(self, session: Session) -> Optional[\"CollectionStore\"]:\n        return self.CollectionStore.get_by_name(session, self.collection_name)\n    @classmethod\n    def __from(\n        cls,\n        texts: List[str],\n        embeddings: List[List[float]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        connection_string: Optional[str] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> PGVector:\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-5", "text": "ids = [str(uuid.uuid1()) for _ in texts]\n        if not metadatas:\n            metadatas = [{} for _ in texts]\n        if connection_string is None:\n            connection_string = cls.get_connection_string(kwargs)\n        store = cls(\n            connection_string=connection_string,\n            collection_name=collection_name,\n            embedding_function=embedding,\n            distance_strategy=distance_strategy,\n            pre_delete_collection=pre_delete_collection,\n            **kwargs,\n        )\n        store.add_embeddings(\n            texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs\n        )\n        return store\n[docs]    def add_embeddings(\n        self,\n        texts: Iterable[str],\n        embeddings: List[List[float]],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add embeddings to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            embeddings: List of list of embedding vectors.\n            metadatas: List of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        \"\"\"\n        if ids is None:\n            ids = [str(uuid.uuid1()) for _ in texts]\n        if not metadatas:\n            metadatas = [{} for _ in texts]\n        with Session(self._conn) as session:\n            collection = self.get_collection(session)\n            if not collection:\n                raise ValueError(\"Collection not found\")\n            for text, metadata, embedding, id in zip(texts, metadatas, embeddings, ids):\n                embedding_store = self.EmbeddingStore(\n                    embedding=embedding,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-6", "text": "embedding_store = self.EmbeddingStore(\n                    embedding=embedding,\n                    document=text,\n                    cmetadata=metadata,\n                    custom_id=id,\n                    collection_id=collection.uuid,\n                )\n                session.add(embedding_store)\n            session.commit()\n        return ids\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        embeddings = self.embedding_function.embed_documents(list(texts))\n        return self.add_embeddings(\n            texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs\n        )\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Run similarity search with PGVector with distance.\n        Args:\n            query (str): Query text to search for.\n            k (int): Number of results to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        embedding = self.embedding_function.embed_query(text=query)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-7", "text": "\"\"\"\n        embedding = self.embedding_function.embed_query(text=query)\n        return self.similarity_search_by_vector(\n            embedding=embedding,\n            k=k,\n            filter=filter,\n        )\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[dict] = None,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query and score for each.\n        \"\"\"\n        embedding = self.embedding_function.embed_query(query)\n        docs = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, filter=filter\n        )\n        return docs\n    @property\n    def distance_strategy(self) -> Any:\n        if self._distance_strategy == DistanceStrategy.EUCLIDEAN:\n            return self.EmbeddingStore.embedding.l2_distance\n        elif self._distance_strategy == DistanceStrategy.COSINE:\n            return self.EmbeddingStore.embedding.cosine_distance\n        elif self._distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:\n            return self.EmbeddingStore.embedding.max_inner_product\n        else:\n            raise ValueError(\n                f\"Got unexpected value for distance: {self._distance_strategy}. \"\n                f\"Should be one of {', '.join([ds.value for ds in DistanceStrategy])}.\"\n            )\n[docs]    def similarity_search_with_score_by_vector(\n        self,\n        embedding: List[float],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-8", "text": "self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[dict] = None,\n    ) -> List[Tuple[Document, float]]:\n        results = self.__query_collection(embedding=embedding, k=k, filter=filter)\n        return self._results_to_docs_and_scores(results)\n    def _results_to_docs_and_scores(self, results: Any) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs and scores from results.\"\"\"\n        docs = [\n            (\n                Document(\n                    page_content=result.EmbeddingStore.document,\n                    metadata=result.EmbeddingStore.cmetadata,\n                ),\n                result.distance if self.embedding_function is not None else None,\n            )\n            for result in results\n        ]\n        return docs\n    def __query_collection(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[Dict[str, str]] = None,\n    ) -> List[Any]:\n        \"\"\"Query the collection.\"\"\"\n        with Session(self._conn) as session:\n            collection = self.get_collection(session)\n            if not collection:\n                raise ValueError(\"Collection not found\")\n            filter_by = self.EmbeddingStore.collection_id == collection.uuid\n            if filter is not None:\n                filter_clauses = []\n                for key, value in filter.items():\n                    IN = \"in\"\n                    if isinstance(value, dict) and IN in map(str.lower, value):\n                        value_case_insensitive = {\n                            k.lower(): v for k, v in value.items()\n                        }\n                        filter_by_metadata = self.EmbeddingStore.cmetadata[\n                            key\n                        ].astext.in_(value_case_insensitive[IN])\n                        filter_clauses.append(filter_by_metadata)\n                    else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-9", "text": "filter_clauses.append(filter_by_metadata)\n                    else:\n                        filter_by_metadata = self.EmbeddingStore.cmetadata[\n                            key\n                        ].astext == str(value)\n                        filter_clauses.append(filter_by_metadata)\n                filter_by = sqlalchemy.and_(filter_by, *filter_clauses)\n            _type = self.EmbeddingStore\n            results: List[Any] = (\n                session.query(\n                    self.EmbeddingStore,\n                    self.distance_strategy(embedding).label(\"distance\"),  # type: ignore\n                )\n                .filter(filter_by)\n                .order_by(sqlalchemy.asc(\"distance\"))\n                .join(\n                    self.CollectionStore,\n                    self.EmbeddingStore.collection_id == self.CollectionStore.uuid,\n                )\n                .limit(k)\n                .all()\n            )\n        return results\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List of Documents most similar to the query vector.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score_by_vector(\n            embedding=embedding, k=k, filter=filter\n        )\n        return _results_to_docs(docs_and_scores)\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[PGVector],\n        texts: List[str],\n        embedding: Embeddings,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-10", "text": "texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> PGVector:\n        \"\"\"\n        Return VectorStore initialized from texts and embeddings.\n        Postgres connection string is required\n        \"Either pass it as a parameter\n        or set the PGVECTOR_CONNECTION_STRING environment variable.\n        \"\"\"\n        embeddings = embedding.embed_documents(list(texts))\n        return cls.__from(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            collection_name=collection_name,\n            distance_strategy=distance_strategy,\n            pre_delete_collection=pre_delete_collection,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_embeddings(\n        cls,\n        text_embeddings: List[Tuple[str, List[float]]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> PGVector:\n        \"\"\"Construct PGVector wrapper from raw documents and pre-\n        generated embeddings.\n        Return VectorStore initialized from documents and embeddings.\n        Postgres connection string is required\n        \"Either pass it as a parameter\n        or set the PGVECTOR_CONNECTION_STRING environment variable.\n        Example:\n            .. code-block:: python", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-11", "text": "Example:\n            .. code-block:: python\n                from langchain.vectorstores import PGVector\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                text_embeddings = embeddings.embed_documents(texts)\n                text_embedding_pairs = list(zip(texts, text_embeddings))\n                faiss = PGVector.from_embeddings(text_embedding_pairs, embeddings)\n        \"\"\"\n        texts = [t[0] for t in text_embeddings]\n        embeddings = [t[1] for t in text_embeddings]\n        return cls.__from(\n            texts,\n            embeddings,\n            embedding,\n            metadatas=metadatas,\n            ids=ids,\n            collection_name=collection_name,\n            distance_strategy=distance_strategy,\n            pre_delete_collection=pre_delete_collection,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_existing_index(\n        cls: Type[PGVector],\n        embedding: Embeddings,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> PGVector:\n        \"\"\"\n        Get instance of an existing PGVector store.This method will\n        return the instance of the store without inserting any new\n        embeddings\n        \"\"\"\n        connection_string = cls.get_connection_string(kwargs)\n        store = cls(\n            connection_string=connection_string,\n            collection_name=collection_name,\n            embedding_function=embedding,\n            distance_strategy=distance_strategy,\n            pre_delete_collection=pre_delete_collection,\n        )\n        return store\n[docs]    @classmethod\n    def get_connection_string(cls, kwargs: Dict[str, Any]) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-12", "text": "def get_connection_string(cls, kwargs: Dict[str, Any]) -> str:\n        connection_string: str = get_from_dict_or_env(\n            data=kwargs,\n            key=\"connection_string\",\n            env_key=\"PGVECTOR_CONNECTION_STRING\",\n        )\n        if not connection_string:\n            raise ValueError(\n                \"Postgres connection string is required\"\n                \"Either pass it as a parameter\"\n                \"or set the PGVECTOR_CONNECTION_STRING environment variable.\"\n            )\n        return connection_string\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[PGVector],\n        documents: List[Document],\n        embedding: Embeddings,\n        collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,\n        distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,\n        ids: Optional[List[str]] = None,\n        pre_delete_collection: bool = False,\n        **kwargs: Any,\n    ) -> PGVector:\n        \"\"\"\n        Return VectorStore initialized from documents and embeddings.\n        Postgres connection string is required\n        \"Either pass it as a parameter\n        or set the PGVECTOR_CONNECTION_STRING environment variable.\n        \"\"\"\n        texts = [d.page_content for d in documents]\n        metadatas = [d.metadata for d in documents]\n        connection_string = cls.get_connection_string(kwargs)\n        kwargs[\"connection_string\"] = connection_string\n        return cls.from_texts(\n            texts=texts,\n            pre_delete_collection=pre_delete_collection,\n            embedding=embedding,\n            distance_strategy=distance_strategy,\n            metadatas=metadatas,\n            ids=ids,\n            collection_name=collection_name,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def connection_string_from_db_params(\n        cls,\n        driver: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-13", "text": "def connection_string_from_db_params(\n        cls,\n        driver: str,\n        host: str,\n        port: int,\n        database: str,\n        user: str,\n        password: str,\n    ) -> str:\n        \"\"\"Return connection string from database parameters.\"\"\"\n        return f\"postgresql+{driver}://{user}:{password}@{host}:{port}/{database}\"\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        \"\"\"\n        The 'correct' relevance function\n        may differ depending on a few things, including:\n        - the distance / similarity metric used by the VectorStore\n        - the scale of your embeddings (OpenAI's are unit normed. Many others are not!)\n        - embedding dimensionality\n        - etc.\n        \"\"\"\n        if self.override_relevance_score_fn is not None:\n            return self.override_relevance_score_fn\n        # Default strategy is to rely on distance strategy provided\n        # in vectorstore constructor\n        if self._distance_strategy == DistanceStrategy.COSINE:\n            return self._cosine_relevance_score_fn\n        elif self._distance_strategy == DistanceStrategy.EUCLIDEAN:\n            return self._euclidean_relevance_score_fn\n        elif self._distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:\n            return self._max_inner_product_relevance_score_fn\n        else:\n            raise ValueError(\n                \"No supported normalization function\"\n                f\" for distance_strategy of {self._distance_strategy}.\"\n                \"Consider providing relevance_score_fn to PGVector constructor.\"\n            )\n[docs]    def max_marginal_relevance_search_with_score_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-14", "text": "k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs selected using the maximal marginal relevance with score\n            to embedding vector.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n            among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k (int): Number of Documents to return. Defaults to 4.\n            fetch_k (int): Number of Documents to fetch to pass to MMR algorithm.\n                Defaults to 20.\n            lambda_mult (float): Number between 0 and 1 that determines the degree\n                of diversity among the results with 0 corresponding\n                to maximum diversity and 1 to minimum diversity.\n                Defaults to 0.5.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List[Tuple[Document, float]]: List of Documents selected by maximal marginal\n                relevance to the query and score for each.\n        \"\"\"\n        results = self.__query_collection(embedding=embedding, k=fetch_k, filter=filter)\n        embedding_list = [result.EmbeddingStore.embedding for result in results]\n        mmr_selected = maximal_marginal_relevance(\n            np.array(embedding, dtype=np.float32),\n            embedding_list,\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        candidates = self._results_to_docs_and_scores(results)\n        return [r for i, r in enumerate(candidates) if i in mmr_selected]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-15", "text": "[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n            among selected documents.\n        Args:\n            query (str): Text to look up documents similar to.\n            k (int): Number of Documents to return. Defaults to 4.\n            fetch_k (int): Number of Documents to fetch to pass to MMR algorithm.\n                Defaults to 20.\n            lambda_mult (float): Number between 0 and 1 that determines the degree\n                of diversity among the results with 0 corresponding\n                to maximum diversity and 1 to minimum diversity.\n                Defaults to 0.5.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List[Document]: List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        embedding = self.embedding_function.embed_query(query)\n        return self.max_marginal_relevance_search_by_vector(\n            embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n            **kwargs,\n        )\n[docs]    def max_marginal_relevance_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[dict] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-16", "text": "filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs selected using the maximal marginal relevance with score.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n            among selected documents.\n        Args:\n            query (str): Text to look up documents similar to.\n            k (int): Number of Documents to return. Defaults to 4.\n            fetch_k (int): Number of Documents to fetch to pass to MMR algorithm.\n                Defaults to 20.\n            lambda_mult (float): Number between 0 and 1 that determines the degree\n                of diversity among the results with 0 corresponding\n                to maximum diversity and 1 to minimum diversity.\n                Defaults to 0.5.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List[Tuple[Document, float]]: List of Documents selected by maximal marginal\n                relevance to the query and score for each.\n        \"\"\"\n        embedding = self.embedding_function.embed_query(query)\n        docs = self.max_marginal_relevance_search_with_score_by_vector(\n            embedding=embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n            **kwargs,\n        )\n        return docs\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-17", "text": "**kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance\n            to embedding vector.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n            among selected documents.\n        Args:\n            embedding (str): Text to look up documents similar to.\n            k (int): Number of Documents to return. Defaults to 4.\n            fetch_k (int): Number of Documents to fetch to pass to MMR algorithm.\n                Defaults to 20.\n            lambda_mult (float): Number between 0 and 1 that determines the degree\n                of diversity among the results with 0 corresponding\n                to maximum diversity and 1 to minimum diversity.\n                Defaults to 0.5.\n            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.\n        Returns:\n            List[Document]: List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        docs_and_scores = self.max_marginal_relevance_search_with_score_by_vector(\n            embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n            **kwargs,\n        )\n        return _results_to_docs(docs_and_scores)\n[docs]    async def amax_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[Dict[str, str]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\"\"\"\n        # This is a temporary workaround to make the similarity search", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "5fec310b6df0-18", "text": "# This is a temporary workaround to make the similarity search\n        # asynchronous. The proper solution is to make the similarity search\n        # asynchronous in the vector store implementations.\n        func = partial(\n            self.max_marginal_relevance_search_by_vector,\n            embedding,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            filter=filter,\n            **kwargs,\n        )\n        return await asyncio.get_event_loop().run_in_executor(None, func)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html"}
{"id": "cb7de7174d73-0", "text": "Source code for langchain.vectorstores.typesense\nfrom __future__ import annotations\nimport uuid\nfrom typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.utils import get_from_env\nif TYPE_CHECKING:\n    from typesense.client import Client\n    from typesense.collection import Collection\n[docs]class Typesense(VectorStore):\n    \"\"\"`Typesense` vector store.\n    To use, you should have the ``typesense`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.embedding.openai import OpenAIEmbeddings\n            from langchain.vectorstores import Typesense\n            import typesense\n            node = {\n                \"host\": \"localhost\",  # For Typesense Cloud use xxx.a1.typesense.net\n                \"port\": \"8108\",       # For Typesense Cloud use 443\n                \"protocol\": \"http\"    # For Typesense Cloud use https\n            }\n            typesense_client = typesense.Client(\n                {\n                  \"nodes\": [node],\n                  \"api_key\": \"<API_KEY>\",\n                  \"connection_timeout_seconds\": 2\n                }\n            )\n            typesense_collection_name = \"langchain-memory\"\n            embedding = OpenAIEmbeddings()\n            vectorstore = Typesense(\n                typesense_client=typesense_client,\n                embedding=embedding,\n                typesense_collection_name=typesense_collection_name,\n                text_key=\"text\",\n            )\n    \"\"\"\n[docs]    def __init__(\n        self,\n        typesense_client: Client,\n        embedding: Embeddings,\n        *,\n        typesense_collection_name: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html"}
{"id": "cb7de7174d73-1", "text": "*,\n        typesense_collection_name: Optional[str] = None,\n        text_key: str = \"text\",\n    ):\n        \"\"\"Initialize with Typesense client.\"\"\"\n        try:\n            from typesense import Client\n        except ImportError:\n            raise ImportError(\n                \"Could not import typesense python package. \"\n                \"Please install it with `pip install typesense`.\"\n            )\n        if not isinstance(typesense_client, Client):\n            raise ValueError(\n                f\"typesense_client should be an instance of typesense.Client, \"\n                f\"got {type(typesense_client)}\"\n            )\n        self._typesense_client = typesense_client\n        self._embedding = embedding\n        self._typesense_collection_name = (\n            typesense_collection_name or f\"langchain-{str(uuid.uuid4())}\"\n        )\n        self._text_key = text_key\n    @property\n    def _collection(self) -> Collection:\n        return self._typesense_client.collections[self._typesense_collection_name]\n    @property\n    def embeddings(self) -> Embeddings:\n        return self._embedding\n    def _prep_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]],\n        ids: Optional[List[str]],\n    ) -> List[dict]:\n        \"\"\"Embed and create the documents\"\"\"\n        _ids = ids or (str(uuid.uuid4()) for _ in texts)\n        _metadatas: Iterable[dict] = metadatas or ({} for _ in texts)\n        embedded_texts = self._embedding.embed_documents(list(texts))\n        return [\n            {\"id\": _id, \"vec\": vec, f\"{self._text_key}\": text, \"metadata\": metadata}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html"}
{"id": "cb7de7174d73-2", "text": "for _id, vec, text, metadata in zip(_ids, embedded_texts, texts, _metadatas)\n        ]\n    def _create_collection(self, num_dim: int) -> None:\n        fields = [\n            {\"name\": \"vec\", \"type\": \"float[]\", \"num_dim\": num_dim},\n            {\"name\": f\"{self._text_key}\", \"type\": \"string\"},\n            {\"name\": \".*\", \"type\": \"auto\"},\n        ]\n        self._typesense_client.collections.create(\n            {\"name\": self._typesense_collection_name, \"fields\": fields}\n        )\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embedding and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of ids to associate with the texts.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        from typesense.exceptions import ObjectNotFound\n        docs = self._prep_texts(texts, metadatas, ids)\n        try:\n            self._collection.documents.import_(docs, {\"action\": \"upsert\"})\n        except ObjectNotFound:\n            # Create the collection if it doesn't already exist\n            self._create_collection(len(docs[0][\"vec\"]))\n            self._collection.documents.import_(docs, {\"action\": \"upsert\"})\n        return [doc[\"id\"] for doc in docs]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html"}
{"id": "cb7de7174d73-3", "text": "return [doc[\"id\"] for doc in docs]\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 10,\n        filter: Optional[str] = \"\",\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return typesense documents most similar to query, along with scores.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 10.\n                Minimum 10 results would be returned.\n            filter: typesense filter_by expression to filter documents on\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        embedded_query = [str(x) for x in self._embedding.embed_query(query)]\n        query_obj = {\n            \"q\": \"*\",\n            \"vector_query\": f'vec:([{\",\".join(embedded_query)}], k:{k})',\n            \"filter_by\": filter,\n            \"collection\": self._typesense_collection_name,\n        }\n        docs = []\n        response = self._typesense_client.multi_search.perform(\n            {\"searches\": [query_obj]}, {}\n        )\n        for hit in response[\"results\"][0][\"hits\"]:\n            document = hit[\"document\"]\n            metadata = document[\"metadata\"]\n            text = document[self._text_key]\n            score = hit[\"vector_distance\"]\n            docs.append((Document(page_content=text, metadata=metadata), score))\n        return docs\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 10,\n        filter: Optional[str] = \"\",\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return typesense documents most similar to query.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html"}
{"id": "cb7de7174d73-4", "text": ") -> List[Document]:\n        \"\"\"Return typesense documents most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 10.\n                Minimum 10 results would be returned.\n            filter: typesense filter_by expression to filter documents on\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        docs_and_score = self.similarity_search_with_score(query, k=k, filter=filter)\n        return [doc for doc, _ in docs_and_score]\n[docs]    @classmethod\n    def from_client_params(\n        cls,\n        embedding: Embeddings,\n        *,\n        host: str = \"localhost\",\n        port: Union[str, int] = \"8108\",\n        protocol: str = \"http\",\n        typesense_api_key: Optional[str] = None,\n        connection_timeout_seconds: int = 2,\n        **kwargs: Any,\n    ) -> Typesense:\n        \"\"\"Initialize Typesense directly from client parameters.\n        Example:\n            .. code-block:: python\n                from langchain.embedding.openai import OpenAIEmbeddings\n                from langchain.vectorstores import Typesense\n                # Pass in typesense_api_key as kwarg or set env var \"TYPESENSE_API_KEY\".\n                vectorstore = Typesense(\n                    OpenAIEmbeddings(),\n                    host=\"localhost\",\n                    port=\"8108\",\n                    protocol=\"http\",\n                    typesense_collection_name=\"langchain-memory\",\n                )\n        \"\"\"\n        try:\n            from typesense import Client\n        except ImportError:\n            raise ValueError(\n                \"Could not import typesense python package. \"\n                \"Please install it with `pip install typesense`.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html"}
{"id": "cb7de7174d73-5", "text": "\"Please install it with `pip install typesense`.\"\n            )\n        node = {\n            \"host\": host,\n            \"port\": str(port),\n            \"protocol\": protocol,\n        }\n        typesense_api_key = typesense_api_key or get_from_env(\n            \"typesense_api_key\", \"TYPESENSE_API_KEY\"\n        )\n        client_config = {\n            \"nodes\": [node],\n            \"api_key\": typesense_api_key,\n            \"connection_timeout_seconds\": connection_timeout_seconds,\n        }\n        return cls(Client(client_config), embedding, **kwargs)\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        ids: Optional[List[str]] = None,\n        typesense_client: Optional[Client] = None,\n        typesense_client_params: Optional[dict] = None,\n        typesense_collection_name: Optional[str] = None,\n        text_key: str = \"text\",\n        **kwargs: Any,\n    ) -> Typesense:\n        \"\"\"Construct Typesense wrapper from raw text.\"\"\"\n        if typesense_client:\n            vectorstore = cls(typesense_client, embedding, **kwargs)\n        elif typesense_client_params:\n            vectorstore = cls.from_client_params(\n                embedding, **typesense_client_params, **kwargs\n            )\n        else:\n            raise ValueError(\n                \"Must specify one of typesense_client or typesense_client_params.\"\n            )\n        vectorstore.add_texts(texts, metadatas=metadatas, ids=ids)\n        return vectorstore", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html"}
{"id": "af33f86b6972-0", "text": "Source code for langchain.vectorstores.usearch\nfrom __future__ import annotations\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple\nimport numpy as np\nfrom langchain.docstore.base import AddableMixin, Docstore\nfrom langchain.docstore.document import Document\nfrom langchain.docstore.in_memory import InMemoryDocstore\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\n[docs]def dependable_usearch_import() -> Any:\n    \"\"\"\n    Import usearch if available, otherwise raise error.\n    \"\"\"\n    try:\n        import usearch.index\n    except ImportError:\n        raise ImportError(\n            \"Could not import usearch python package. \"\n            \"Please install it with `pip install usearch` \"\n        )\n    return usearch.index\n[docs]class USearch(VectorStore):\n    \"\"\"`USearch` vector store.\n    To use, you should have the ``usearch`` python package installed.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        index: Any,\n        docstore: Docstore,\n        ids: List[str],\n    ):\n        \"\"\"Initialize with necessary components.\"\"\"\n        self.embedding = embedding\n        self.index = index\n        self.docstore = docstore\n        self.ids = ids\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[Dict]] = None,\n        ids: Optional[np.ndarray] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html"}
{"id": "af33f86b6972-1", "text": "Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            ids: Optional list of unique IDs.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        if not isinstance(self.docstore, AddableMixin):\n            raise ValueError(\n                \"If trying to add texts, the underlying docstore should support \"\n                f\"adding items, which {self.docstore} does not\"\n            )\n        embeddings = self.embedding.embed_documents(list(texts))\n        documents = []\n        for i, text in enumerate(texts):\n            metadata = metadatas[i] if metadatas else {}\n            documents.append(Document(page_content=text, metadata=metadata))\n        last_id = int(self.ids[-1]) + 1\n        if ids is None:\n            ids = np.array([str(last_id + id) for id, _ in enumerate(texts)])\n        self.index.add(np.array(ids), np.array(embeddings))\n        self.docstore.add(dict(zip(ids, documents)))\n        self.ids.extend(ids)\n        return ids.tolist()\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of documents most similar to the query with distance.\n        \"\"\"\n        query_embedding = self.embedding.embed_query(query)\n        matches = self.index.search(np.array(query_embedding), k)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html"}
{"id": "af33f86b6972-2", "text": "matches = self.index.search(np.array(query_embedding), k)\n        docs_with_scores: List[Tuple[Document, float]] = []\n        for id, score in zip(matches.keys, matches.distances):\n            doc = self.docstore.search(str(id))\n            if not isinstance(doc, Document):\n                raise ValueError(f\"Could not find document for id {id}, got {doc}\")\n            docs_with_scores.append((doc, score))\n        return docs_with_scores\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        query_embedding = self.embedding.embed_query(query)\n        matches = self.index.search(np.array(query_embedding), k)\n        docs: List[Document] = []\n        for id in matches.keys:\n            doc = self.docstore.search(str(id))\n            if not isinstance(doc, Document):\n                raise ValueError(f\"Could not find document for id {id}, got {doc}\")\n            docs.append(doc)\n        return docs\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[Dict]] = None,\n        ids: Optional[np.ndarray] = None,\n        metric: str = \"cos\",\n        **kwargs: Any,\n    ) -> USearch:\n        \"\"\"Construct USearch wrapper from raw documents.\n        This is a user friendly interface that:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html"}
{"id": "af33f86b6972-3", "text": "This is a user friendly interface that:\n            1. Embeds documents.\n            2. Creates an in memory docstore\n            3. Initializes the USearch database\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import USearch\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                usearch = USearch.from_texts(texts, embeddings)\n        \"\"\"\n        embeddings = embedding.embed_documents(texts)\n        documents: List[Document] = []\n        if ids is None:\n            ids = np.array([str(id) for id, _ in enumerate(texts)])\n        for i, text in enumerate(texts):\n            metadata = metadatas[i] if metadatas else {}\n            documents.append(Document(page_content=text, metadata=metadata))\n        docstore = InMemoryDocstore(dict(zip(ids, documents)))\n        usearch = dependable_usearch_import()\n        index = usearch.Index(ndim=len(embeddings[0]), metric=metric)\n        index.add(np.array(ids), np.array(embeddings))\n        return cls(embedding, index, docstore, ids.tolist())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html"}
{"id": "6000f17d8a69-0", "text": "Source code for langchain.vectorstores.alibabacloud_opensearch\nimport json\nimport logging\nimport numbers\nfrom hashlib import sha1\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple\nfrom langchain.schema import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nlogger = logging.getLogger()\n[docs]class AlibabaCloudOpenSearchSettings:\n    \"\"\"Alibaba Cloud Opensearch` client configuration.\n    Attribute:\n        endpoint (str) : The endpoint of opensearch instance, You can find it\n         from the console of Alibaba Cloud OpenSearch.\n        instance_id (str) : The identify of opensearch instance, You can find\n         it from the console of Alibaba Cloud OpenSearch.\n        username (str) : The username specified when purchasing the instance.\n        password (str) : The password specified when purchasing the instance\uff0c\n          After the instance is created, you can modify it on the console.\n        tablename (str): The table name specified during instance configuration.\n        field_name_mapping (Dict) : Using field name mapping between opensearch\n          vector store and opensearch instance configuration table field names:\n        {\n            'id': 'The id field name map of index document.',\n            'document': 'The text field name map of index document.',\n            'embedding': 'In the embedding field of the opensearch instance,\n              the values must be in float type and separated by separator,\n              default is comma.',\n            'metadata_field_x': 'Metadata field mapping includes the mapped\n             field name and operator in the mapping value, separated by a comma\n             between the mapped field name and the operator.',\n        }\n        protocol (str): Communication Protocol between SDK and Server, default is http.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html"}
{"id": "6000f17d8a69-1", "text": "}\n        protocol (str): Communication Protocol between SDK and Server, default is http.\n        namespace (str) : The instance data will be partitioned based on the \"namespace\"\n         field,If the namespace is enabled, you need to specify the namespace field\n         name during initialization, Otherwise, the queries cannot be executed\n         correctly.\n        embedding_field_separator(str): Delimiter specified for writing vector\n         field data, default is comma.\n        output_fields: Specify the field list returned when invoking OpenSearch,\n         by default it is the value list of the field mapping field.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        endpoint: str,\n        instance_id: str,\n        username: str,\n        password: str,\n        table_name: str,\n        field_name_mapping: Dict[str, str],\n        protocol: str = \"http\",\n        namespace: str = \"\",\n        embedding_field_separator: str = \",\",\n        output_fields: Optional[List[str]] = None,\n    ) -> None:\n        self.endpoint = endpoint\n        self.instance_id = instance_id\n        self.protocol = protocol\n        self.username = username\n        self.password = password\n        self.namespace = namespace\n        self.table_name = table_name\n        self.opt_table_name = \"_\".join([self.instance_id, self.table_name])\n        self.field_name_mapping = field_name_mapping\n        self.embedding_field_separator = embedding_field_separator\n        if output_fields is None:\n            self.output_fields = [\n                field.split(\",\")[0] for field in self.field_name_mapping.values()\n            ]\n        self.inverse_field_name_mapping: Dict[str, str] = {}\n        for key, value in self.field_name_mapping.items():\n            self.inverse_field_name_mapping[value.split(\",\")[0]] = key", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html"}
{"id": "6000f17d8a69-2", "text": "self.inverse_field_name_mapping[value.split(\",\")[0]] = key\n    def __getitem__(self, item: str) -> Any:\n        return getattr(self, item)\n[docs]def create_metadata(fields: Dict[str, Any]) -> Dict[str, Any]:\n    \"\"\"Create metadata from fields.\n    Args:\n        fields: The fields of the document. The fields must be a dict.\n    Returns:\n        metadata: The metadata of the document. The metadata must be a dict.\n    \"\"\"\n    metadata: Dict[str, Any] = {}\n    for key, value in fields.items():\n        if key == \"id\" or key == \"document\" or key == \"embedding\":\n            continue\n        metadata[key] = value\n    return metadata\n[docs]class AlibabaCloudOpenSearch(VectorStore):\n    \"\"\"`Alibaba Cloud OpenSearch` vector store.\"\"\"\n[docs]    def __init__(\n        self,\n        embedding: Embeddings,\n        config: AlibabaCloudOpenSearchSettings,\n        **kwargs: Any,\n    ) -> None:\n        try:\n            from alibabacloud_ha3engine_vector import client, models\n            from alibabacloud_tea_util import models as util_models\n        except ImportError:\n            raise ImportError(\n                \"Could not import alibaba cloud opensearch python package. \"\n                \"Please install it with `pip install alibabacloud-ha3engine-vector`.\"\n            )\n        self.config = config\n        self.embedding = embedding\n        self.runtime = util_models.RuntimeOptions(\n            connect_timeout=5000,\n            read_timeout=10000,\n            autoretry=False,\n            ignore_ssl=False,\n            max_idle_conns=50,\n        )\n        self.ha3_engine_client = client.Client(\n            models.Config(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html"}
{"id": "6000f17d8a69-3", "text": ")\n        self.ha3_engine_client = client.Client(\n            models.Config(\n                endpoint=config.endpoint,\n                instance_id=config.instance_id,\n                protocol=config.protocol,\n                access_user_name=config.username,\n                access_pass_word=config.password,\n            )\n        )\n        self.options_headers: Dict[str, str] = {}\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Insert documents into the instance..\n        Args:\n            texts: The text segments to be inserted into the vector storage,\n             should not be empty.\n            metadatas: Metadata information.\n        Returns:\n            id_list: List of document IDs.\n        \"\"\"\n        def _upsert(push_doc_list: List[Dict]) -> List[str]:\n            if push_doc_list is None or len(push_doc_list) == 0:\n                return []\n            try:\n                push_request = models.PushDocumentsRequest(\n                    self.options_headers, push_doc_list\n                )\n                push_response = self.ha3_engine_client.push_documents(\n                    self.config.opt_table_name, field_name_map[\"id\"], push_request\n                )\n                json_response = json.loads(push_response.body)\n                if json_response[\"status\"] == \"OK\":\n                    return [\n                        push_doc[\"fields\"][field_name_map[\"id\"]]\n                        for push_doc in push_doc_list\n                    ]\n                return []\n            except Exception as e:\n                logger.error(\n                    f\"add doc to endpoint:{self.config.endpoint} \"\n                    f\"instance_id:{self.config.instance_id} failed.\",\n                    e,\n                )\n                raise e", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html"}
{"id": "6000f17d8a69-4", "text": "e,\n                )\n                raise e\n        from alibabacloud_ha3engine_vector import models\n        id_list = [sha1(t.encode(\"utf-8\")).hexdigest() for t in texts]\n        embeddings = self.embedding.embed_documents(list(texts))\n        metadatas = metadatas or [{} for _ in texts]\n        field_name_map = self.config.field_name_mapping\n        add_doc_list = []\n        text_list = list(texts)\n        for idx, doc_id in enumerate(id_list):\n            embedding = embeddings[idx] if idx < len(embeddings) else None\n            metadata = metadatas[idx] if idx < len(metadatas) else None\n            text = text_list[idx] if idx < len(text_list) else None\n            add_doc: Dict[str, Any] = dict()\n            add_doc_fields: Dict[str, Any] = dict()\n            add_doc_fields.__setitem__(field_name_map[\"id\"], doc_id)\n            add_doc_fields.__setitem__(field_name_map[\"document\"], text)\n            if embedding is not None:\n                add_doc_fields.__setitem__(\n                    field_name_map[\"embedding\"],\n                    self.config.embedding_field_separator.join(\n                        str(unit) for unit in embedding\n                    ),\n                )\n            if metadata is not None:\n                for md_key, md_value in metadata.items():\n                    add_doc_fields.__setitem__(\n                        field_name_map[md_key].split(\",\")[0], md_value\n                    )\n            add_doc.__setitem__(\"fields\", add_doc_fields)\n            add_doc.__setitem__(\"cmd\", \"add\")\n            add_doc_list.append(add_doc)\n        return _upsert(add_doc_list)\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html"}
{"id": "6000f17d8a69-5", "text": "self,\n        query: str,\n        k: int = 4,\n        search_filter: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform similarity retrieval based on text.\n        Args:\n            query: Vectorize text for retrieval.\uff0cshould not be empty.\n            k: top n.\n            search_filter: Additional filtering conditions.\n        Returns:\n            document_list: List of documents.\n        \"\"\"\n        embedding = self.embedding.embed_query(query)\n        return self.create_results(\n            self.inner_embedding_query(\n                embedding=embedding, search_filter=search_filter, k=k\n            )\n        )\n[docs]    def similarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        search_filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Perform similarity retrieval based on text with scores.\n        Args:\n            query: Vectorize text for retrieval.\uff0cshould not be empty.\n            k: top n.\n            search_filter: Additional filtering conditions.\n        Returns:\n            document_list: List of documents.\n        \"\"\"\n        embedding: List[float] = self.embedding.embed_query(query)\n        return self.create_results_with_score(\n            self.inner_embedding_query(\n                embedding=embedding, search_filter=search_filter, k=k\n            )\n        )\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        search_filter: Optional[dict] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Perform retrieval directly using vectors.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html"}
{"id": "6000f17d8a69-6", "text": ") -> List[Document]:\n        \"\"\"Perform retrieval directly using vectors.\n        Args:\n            embedding: vectors.\n            k: top n.\n            search_filter: Additional filtering conditions.\n        Returns:\n            document_list: List of documents.\n        \"\"\"\n        return self.create_results(\n            self.inner_embedding_query(\n                embedding=embedding, search_filter=search_filter, k=k\n            )\n        )\n[docs]    def inner_embedding_query(\n        self,\n        embedding: List[float],\n        search_filter: Optional[Dict[str, Any]] = None,\n        k: int = 4,\n    ) -> Dict[str, Any]:\n        def generate_filter_query() -> str:\n            if search_filter is None:\n                return \"\"\n            filter_clause = \" AND \".join(\n                [\n                    create_filter(md_key, md_value)\n                    for md_key, md_value in search_filter.items()\n                ]\n            )\n            return filter_clause\n        def create_filter(md_key: str, md_value: Any) -> str:\n            md_filter_expr = self.config.field_name_mapping[md_key]\n            if md_filter_expr is None:\n                return \"\"\n            expr = md_filter_expr.split(\",\")\n            if len(expr) != 2:\n                logger.error(\n                    f\"filter {md_filter_expr} express is not correct, \"\n                    f\"must contain mapping field and operator.\"\n                )\n                return \"\"\n            md_filter_key = expr[0].strip()\n            md_filter_operator = expr[1].strip()\n            if isinstance(md_value, numbers.Number):\n                return f\"{md_filter_key} {md_filter_operator} {md_value}\"\n            return f'{md_filter_key}{md_filter_operator}\"{md_value}\"'", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html"}
{"id": "6000f17d8a69-7", "text": "return f'{md_filter_key}{md_filter_operator}\"{md_value}\"'\n        def search_data() -> Dict[str, Any]:\n            request = QueryRequest(\n                table_name=self.config.table_name,\n                namespace=self.config.namespace,\n                vector=embedding,\n                include_vector=True,\n                output_fields=self.config.output_fields,\n                filter=generate_filter_query(),\n                top_k=k,\n            )\n            query_result = self.ha3_engine_client.query(request)\n            return json.loads(query_result.body)\n        from alibabacloud_ha3engine_vector.models import QueryRequest\n        try:\n            json_response = search_data()\n            if (\n                \"errorCode\" in json_response\n                and \"errorMsg\" in json_response\n                and len(json_response[\"errorMsg\"]) > 0\n            ):\n                logger.error(\n                    f\"query {self.config.endpoint} {self.config.instance_id} \"\n                    f\"failed:{json_response['errorMsg']}.\"\n                )\n            else:\n                return json_response\n        except Exception as e:\n            logger.error(\n                f\"query instance endpoint:{self.config.endpoint} \"\n                f\"instance_id:{self.config.instance_id} failed.\",\n                e,\n            )\n        return {}\n[docs]    def create_results(self, json_result: Dict[str, Any]) -> List[Document]:\n        \"\"\"Assemble documents.\"\"\"\n        items = json_result[\"result\"]\n        query_result_list: List[Document] = []\n        for item in items:\n            if (\n                \"fields\" not in item\n                or self.config.field_name_mapping[\"document\"] not in item[\"fields\"]\n            ):\n                query_result_list.append(Document())\n            else:\n                fields = item[\"fields\"]\n                query_result_list.append(\n                    Document(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html"}
{"id": "6000f17d8a69-8", "text": "fields = item[\"fields\"]\n                query_result_list.append(\n                    Document(\n                        page_content=fields[self.config.field_name_mapping[\"document\"]],\n                        metadata=self.create_inverse_metadata(fields),\n                    )\n                )\n        return query_result_list\n[docs]    def create_inverse_metadata(self, fields: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Create metadata from fields.\n        Args:\n            fields: The fields of the document. The fields must be a dict.\n        Returns:\n            metadata: The metadata of the document. The metadata must be a dict.\n        \"\"\"\n        metadata: Dict[str, Any] = {}\n        for key, value in fields.items():\n            if key == \"id\" or key == \"document\" or key == \"embedding\":\n                continue\n            metadata[self.config.inverse_field_name_mapping[key]] = value\n        return metadata\n[docs]    def create_results_with_score(\n        self, json_result: Dict[str, Any]\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Parsing the returned results with scores.\n        Args:\n            json_result: Results from OpenSearch query.\n        Returns:\n            query_result_list: Results with scores.\n        \"\"\"\n        items = json_result[\"result\"]\n        query_result_list: List[Tuple[Document, float]] = []\n        for item in items:\n            fields = item[\"fields\"]\n            query_result_list.append(\n                (\n                    Document(\n                        page_content=fields[self.config.field_name_mapping[\"document\"]],\n                        metadata=self.create_inverse_metadata(fields),\n                    ),\n                    float(item[\"score\"]),\n                )\n            )\n        return query_result_list\n[docs]    def delete_documents_with_texts(self, texts: List[str]) -> bool:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html"}
{"id": "6000f17d8a69-9", "text": "[docs]    def delete_documents_with_texts(self, texts: List[str]) -> bool:\n        \"\"\"Delete documents based on their page content.\n        Args:\n            texts: List of document page content.\n        Returns:\n           Whether the deletion was successful or not.\n        \"\"\"\n        id_list = [sha1(t.encode(\"utf-8\")).hexdigest() for t in texts]\n        return self.delete_documents_with_document_id(id_list)\n[docs]    def delete_documents_with_document_id(self, id_list: List[str]) -> bool:\n        \"\"\"Delete documents based on their IDs.\n        Args:\n            id_list: List of document IDs.\n        Returns:\n            Whether the deletion was successful or not.\n        \"\"\"\n        if id_list is None or len(id_list) == 0:\n            return True\n        from alibabacloud_ha3engine_vector import models\n        delete_doc_list = []\n        for doc_id in id_list:\n            delete_doc_list.append(\n                {\n                    \"fields\": {self.config.field_name_mapping[\"id\"]: doc_id},\n                    \"cmd\": \"delete\",\n                }\n            )\n        delete_request = models.PushDocumentsRequest(\n            self.options_headers, delete_doc_list\n        )\n        try:\n            delete_response = self.ha3_engine_client.push_documents(\n                self.config.opt_table_name,\n                self.config.field_name_mapping[\"id\"],\n                delete_request,\n            )\n            json_response = json.loads(delete_response.body)\n            return json_response[\"status\"] == \"OK\"\n        except Exception as e:\n            logger.error(\n                f\"delete doc from :{self.config.endpoint} \"\n                f\"instance_id:{self.config.instance_id} failed.\",\n                e,\n            )\n            raise e\n[docs]    @classmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html"}
{"id": "6000f17d8a69-10", "text": "e,\n            )\n            raise e\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        config: Optional[AlibabaCloudOpenSearchSettings] = None,\n        **kwargs: Any,\n    ) -> \"AlibabaCloudOpenSearch\":\n        \"\"\"Create alibaba cloud opensearch vector store instance.\n        Args:\n            texts: The text segments to be inserted into the vector storage,\n             should not be empty.\n            embedding: Embedding function, Embedding function.\n            config: Alibaba OpenSearch instance configuration.\n            metadatas: Metadata information.\n        Returns:\n            AlibabaCloudOpenSearch: Alibaba cloud opensearch vector store instance.\n        \"\"\"\n        if texts is None or len(texts) == 0:\n            raise Exception(\"the inserted text segments, should not be empty.\")\n        if embedding is None:\n            raise Exception(\"the embeddings should not be empty.\")\n        if config is None:\n            raise Exception(\"config should not be none.\")\n        ctx = cls(embedding, config, **kwargs)\n        ctx.add_texts(texts=texts, metadatas=metadatas)\n        return ctx\n[docs]    @classmethod\n    def from_documents(\n        cls,\n        documents: List[Document],\n        embedding: Embeddings,\n        config: Optional[AlibabaCloudOpenSearchSettings] = None,\n        **kwargs: Any,\n    ) -> \"AlibabaCloudOpenSearch\":\n        \"\"\"Create alibaba cloud opensearch vector store instance.\n        Args:\n            documents: Documents to be inserted into the vector storage,\n             should not be empty.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html"}
{"id": "6000f17d8a69-11", "text": "documents: Documents to be inserted into the vector storage,\n             should not be empty.\n            embedding: Embedding function, Embedding function.\n            config: Alibaba OpenSearch instance configuration.\n            ids: Specify the ID for the inserted document. If left empty, the ID will be\n             automatically generated based on the text content.\n        Returns:\n            AlibabaCloudOpenSearch: Alibaba cloud opensearch vector store instance.\n        \"\"\"\n        if documents is None or len(documents) == 0:\n            raise Exception(\"the inserted documents, should not be empty.\")\n        if embedding is None:\n            raise Exception(\"the embeddings should not be empty.\")\n        if config is None:\n            raise Exception(\"config can't be none\")\n        texts = [d.page_content for d in documents]\n        metadatas = [d.metadata for d in documents]\n        return cls.from_texts(\n            texts=texts,\n            embedding=embedding,\n            metadatas=metadatas,\n            config=config,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html"}
{"id": "384da15d45c4-0", "text": "Source code for langchain.vectorstores.annoy\nfrom __future__ import annotations\nimport os\nimport pickle\nimport uuid\nfrom configparser import ConfigParser\nfrom pathlib import Path\nfrom typing import Any, Callable, Dict, Iterable, List, Optional, Tuple\nimport numpy as np\nfrom langchain.docstore.base import Docstore\nfrom langchain.docstore.document import Document\nfrom langchain.docstore.in_memory import InMemoryDocstore\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nINDEX_METRICS = frozenset([\"angular\", \"euclidean\", \"manhattan\", \"hamming\", \"dot\"])\nDEFAULT_METRIC = \"angular\"\n[docs]def dependable_annoy_import() -> Any:\n    \"\"\"Import annoy if available, otherwise raise error.\"\"\"\n    try:\n        import annoy\n    except ImportError:\n        raise ImportError(\n            \"Could not import annoy python package. \"\n            \"Please install it with `pip install --user annoy` \"\n        )\n    return annoy\n[docs]class Annoy(VectorStore):\n    \"\"\"`Annoy` vector store.\n    To use, you should have the ``annoy`` python package installed.\n    Example:\n        .. code-block:: python\n            from langchain.vectorstores import Annoy\n            db = Annoy(embedding_function, index, docstore, index_to_docstore_id)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        embedding_function: Callable,\n        index: Any,\n        metric: str,\n        docstore: Docstore,\n        index_to_docstore_id: Dict[int, str],\n    ):\n        \"\"\"Initialize with necessary components.\"\"\"\n        self.embedding_function = embedding_function\n        self.index = index", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html"}
{"id": "384da15d45c4-1", "text": "self.embedding_function = embedding_function\n        self.index = index\n        self.metric = metric\n        self.docstore = docstore\n        self.index_to_docstore_id = index_to_docstore_id\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        # TODO: Accept embedding object directly\n        return None\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        raise NotImplementedError(\n            \"Annoy does not allow to add new data once the index is build.\"\n        )\n[docs]    def process_index_results(\n        self, idxs: List[int], dists: List[float]\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Turns annoy results into a list of documents and scores.\n        Args:\n            idxs: List of indices of the documents in the index.\n            dists: List of distances of the documents in the index.\n        Returns:\n            List of Documents and scores.\n        \"\"\"\n        docs = []\n        for idx, dist in zip(idxs, dists):\n            _id = self.index_to_docstore_id[idx]\n            doc = self.docstore.search(_id)\n            if not isinstance(doc, Document):\n                raise ValueError(f\"Could not find document for id {_id}, got {doc}\")\n            docs.append((doc, dist))\n        return docs\n[docs]    def similarity_search_with_score_by_vector(\n        self, embedding: List[float], k: int = 4, search_k: int = -1\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html"}
{"id": "384da15d45c4-2", "text": "\"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            search_k: inspect up to search_k nodes which defaults\n                to n_trees * n if not provided\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        idxs, dists = self.index.get_nns_by_vector(\n            embedding, k, search_k=search_k, include_distances=True\n        )\n        return self.process_index_results(idxs, dists)\n[docs]    def similarity_search_with_score_by_index(\n        self, docstore_index: int, k: int = 4, search_k: int = -1\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            search_k: inspect up to search_k nodes which defaults\n                to n_trees * n if not provided\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        idxs, dists = self.index.get_nns_by_item(\n            docstore_index, k, search_k=search_k, include_distances=True\n        )\n        return self.process_index_results(idxs, dists)\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 4, search_k: int = -1\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html"}
{"id": "384da15d45c4-3", "text": "Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            search_k: inspect up to search_k nodes which defaults\n                to n_trees * n if not provided\n        Returns:\n            List of Documents most similar to the query and score for each\n        \"\"\"\n        embedding = self.embedding_function(query)\n        docs = self.similarity_search_with_score_by_vector(embedding, k, search_k)\n        return docs\n[docs]    def similarity_search_by_vector(\n        self, embedding: List[float], k: int = 4, search_k: int = -1, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            search_k: inspect up to search_k nodes which defaults\n                to n_trees * n if not provided\n        Returns:\n            List of Documents most similar to the embedding.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score_by_vector(\n            embedding, k, search_k\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search_by_index(\n        self, docstore_index: int, k: int = 4, search_k: int = -1, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to docstore_index.\n        Args:\n            docstore_index: Index of document in docstore\n            k: Number of Documents to return. Defaults to 4.\n            search_k: inspect up to search_k nodes which defaults\n                to n_trees * n if not provided\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html"}
{"id": "384da15d45c4-4", "text": "to n_trees * n if not provided\n        Returns:\n            List of Documents most similar to the embedding.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score_by_index(\n            docstore_index, k, search_k\n        )\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, search_k: int = -1, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            search_k: inspect up to search_k nodes which defaults\n                to n_trees * n if not provided\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        docs_and_scores = self.similarity_search_with_score(query, k, search_k)\n        return [doc for doc, _ in docs_and_scores]\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            k: Number of Documents to return. Defaults to 4.\n            lambda_mult: Number between 0 and 1 that determines the degree", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html"}
{"id": "384da15d45c4-5", "text": "lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        idxs = self.index.get_nns_by_vector(\n            embedding, fetch_k, search_k=-1, include_distances=False\n        )\n        embeddings = [self.index.get_item_vector(i) for i in idxs]\n        mmr_selected = maximal_marginal_relevance(\n            np.array([embedding], dtype=np.float32),\n            embeddings,\n            k=k,\n            lambda_mult=lambda_mult,\n        )\n        # ignore the -1's if not enough docs are returned/indexed\n        selected_indices = [idxs[i] for i in mmr_selected if i != -1]\n        docs = []\n        for i in selected_indices:\n            _id = self.index_to_docstore_id[i]\n            doc = self.docstore.search(_id)\n            if not isinstance(doc, Document):\n                raise ValueError(f\"Could not find document for id {_id}, got {doc}\")\n            docs.append(doc)\n        return docs\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html"}
{"id": "384da15d45c4-6", "text": "Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        embedding = self.embedding_function(query)\n        docs = self.max_marginal_relevance_search_by_vector(\n            embedding, k, fetch_k, lambda_mult=lambda_mult\n        )\n        return docs\n    @classmethod\n    def __from(\n        cls,\n        texts: List[str],\n        embeddings: List[List[float]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        metric: str = DEFAULT_METRIC,\n        trees: int = 100,\n        n_jobs: int = -1,\n        **kwargs: Any,\n    ) -> Annoy:\n        if metric not in INDEX_METRICS:\n            raise ValueError(\n                (\n                    f\"Unsupported distance metric: {metric}. \"\n                    f\"Expected one of {list(INDEX_METRICS)}\"\n                )\n            )\n        annoy = dependable_annoy_import()\n        if not embeddings:\n            raise ValueError(\"embeddings must be provided to build AnnoyIndex\")\n        f = len(embeddings[0])\n        index = annoy.AnnoyIndex(f, metric=metric)\n        for i, emb in enumerate(embeddings):\n            index.add_item(i, emb)\n        index.build(trees, n_jobs=n_jobs)\n        documents = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html"}
{"id": "384da15d45c4-7", "text": "index.build(trees, n_jobs=n_jobs)\n        documents = []\n        for i, text in enumerate(texts):\n            metadata = metadatas[i] if metadatas else {}\n            documents.append(Document(page_content=text, metadata=metadata))\n        index_to_id = {i: str(uuid.uuid4()) for i in range(len(documents))}\n        docstore = InMemoryDocstore(\n            {index_to_id[i]: doc for i, doc in enumerate(documents)}\n        )\n        return cls(embedding.embed_query, index, metric, docstore, index_to_id)\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        metric: str = DEFAULT_METRIC,\n        trees: int = 100,\n        n_jobs: int = -1,\n        **kwargs: Any,\n    ) -> Annoy:\n        \"\"\"Construct Annoy wrapper from raw documents.\n        Args:\n            texts: List of documents to index.\n            embedding: Embedding function to use.\n            metadatas: List of metadata dictionaries to associate with documents.\n            metric: Metric to use for indexing. Defaults to \"angular\".\n            trees: Number of trees to use for indexing. Defaults to 100.\n            n_jobs: Number of jobs to use for indexing. Defaults to -1.\n        This is a user friendly interface that:\n            1. Embeds documents.\n            2. Creates an in memory docstore\n            3. Initializes the Annoy database\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import Annoy", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html"}
{"id": "384da15d45c4-8", "text": ".. code-block:: python\n                from langchain.vectorstores import Annoy\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                index = Annoy.from_texts(texts, embeddings)\n        \"\"\"\n        embeddings = embedding.embed_documents(texts)\n        return cls.__from(\n            texts, embeddings, embedding, metadatas, metric, trees, n_jobs, **kwargs\n        )\n[docs]    @classmethod\n    def from_embeddings(\n        cls,\n        text_embeddings: List[Tuple[str, List[float]]],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        metric: str = DEFAULT_METRIC,\n        trees: int = 100,\n        n_jobs: int = -1,\n        **kwargs: Any,\n    ) -> Annoy:\n        \"\"\"Construct Annoy wrapper from embeddings.\n        Args:\n            text_embeddings: List of tuples of (text, embedding)\n            embedding: Embedding function to use.\n            metadatas: List of metadata dictionaries to associate with documents.\n            metric: Metric to use for indexing. Defaults to \"angular\".\n            trees: Number of trees to use for indexing. Defaults to 100.\n            n_jobs: Number of jobs to use for indexing. Defaults to -1\n        This is a user friendly interface that:\n            1. Creates an in memory docstore with provided embeddings\n            2. Initializes the Annoy database\n        This is intended to be a quick way to get started.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import Annoy\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                text_embeddings = embeddings.embed_documents(texts)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html"}
{"id": "384da15d45c4-9", "text": "embeddings = OpenAIEmbeddings()\n                text_embeddings = embeddings.embed_documents(texts)\n                text_embedding_pairs = list(zip(texts, text_embeddings))\n                db = Annoy.from_embeddings(text_embedding_pairs, embeddings)\n        \"\"\"\n        texts = [t[0] for t in text_embeddings]\n        embeddings = [t[1] for t in text_embeddings]\n        return cls.__from(\n            texts, embeddings, embedding, metadatas, metric, trees, n_jobs, **kwargs\n        )\n[docs]    def save_local(self, folder_path: str, prefault: bool = False) -> None:\n        \"\"\"Save Annoy index, docstore, and index_to_docstore_id to disk.\n        Args:\n            folder_path: folder path to save index, docstore,\n                and index_to_docstore_id to.\n            prefault: Whether to pre-load the index into memory.\n        \"\"\"\n        path = Path(folder_path)\n        os.makedirs(path, exist_ok=True)\n        # save index, index config, docstore and index_to_docstore_id\n        config_object = ConfigParser()\n        config_object[\"ANNOY\"] = {\n            \"f\": self.index.f,\n            \"metric\": self.metric,\n        }\n        self.index.save(str(path / \"index.annoy\"), prefault=prefault)\n        with open(path / \"index.pkl\", \"wb\") as file:\n            pickle.dump((self.docstore, self.index_to_docstore_id, config_object), file)\n[docs]    @classmethod\n    def load_local(\n        cls,\n        folder_path: str,\n        embeddings: Embeddings,\n    ) -> Annoy:\n        \"\"\"Load Annoy index, docstore, and index_to_docstore_id to disk.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html"}
{"id": "384da15d45c4-10", "text": "Args:\n            folder_path: folder path to load index, docstore,\n                and index_to_docstore_id from.\n            embeddings: Embeddings to use when generating queries.\n        \"\"\"\n        path = Path(folder_path)\n        # load index separately since it is not picklable\n        annoy = dependable_annoy_import()\n        # load docstore and index_to_docstore_id\n        with open(path / \"index.pkl\", \"rb\") as file:\n            docstore, index_to_docstore_id, config_object = pickle.load(file)\n        f = int(config_object[\"ANNOY\"][\"f\"])\n        metric = config_object[\"ANNOY\"][\"metric\"]\n        index = annoy.AnnoyIndex(f, metric=metric)\n        index.load(str(path / \"index.annoy\"))\n        return cls(\n            embeddings.embed_query, index, metric, docstore, index_to_docstore_id\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html"}
{"id": "7b8b53e55210-0", "text": "Source code for langchain.vectorstores.docarray.base\nfrom abc import ABC\nfrom typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type\nimport numpy as np\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nif TYPE_CHECKING:\n    from docarray import BaseDoc\n    from docarray.index.abstract import BaseDocIndex\ndef _check_docarray_import() -> None:\n    try:\n        import docarray\n        da_version = docarray.__version__.split(\".\")\n        if int(da_version[0]) == 0 and int(da_version[1]) <= 31:\n            raise ImportError(\n                f\"To use the DocArrayHnswSearch VectorStore the docarray \"\n                f\"version >=0.32.0 is expected, received: {docarray.__version__}.\"\n                f\"To upgrade, please run: `pip install -U docarray`.\"\n            )\n    except ImportError:\n        raise ImportError(\n            \"Could not import docarray python package. \"\n            'Please install it with `pip install \"langchain[docarray]\"`.'\n        )\n[docs]class DocArrayIndex(VectorStore, ABC):\n    \"\"\"Base class for `DocArray` based vector stores.\"\"\"\n[docs]    def __init__(\n        self,\n        doc_index: \"BaseDocIndex\",\n        embedding: Embeddings,\n    ):\n        \"\"\"Initialize a vector store from DocArray's DocIndex.\"\"\"\n        self.doc_index = doc_index\n        self.embedding = embedding\n    @staticmethod\n    def _get_doc_cls(**embeddings_params: Any) -> Type[\"BaseDoc\"]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html"}
{"id": "7b8b53e55210-1", "text": "def _get_doc_cls(**embeddings_params: Any) -> Type[\"BaseDoc\"]:\n        \"\"\"Get docarray Document class describing the schema of DocIndex.\"\"\"\n        from docarray import BaseDoc\n        from docarray.typing import NdArray\n        class DocArrayDoc(BaseDoc):\n            text: Optional[str]\n            embedding: Optional[NdArray] = Field(**embeddings_params)\n            metadata: Optional[dict]\n        return DocArrayDoc\n    @property\n    def doc_cls(self) -> Type[\"BaseDoc\"]:\n        if self.doc_index._schema is None:\n            raise ValueError(\"doc_index expected to have non-null _schema attribute.\")\n        return self.doc_index._schema\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Embed texts and add to the vector store.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n        ids: List[str] = []\n        embeddings = self.embedding.embed_documents(list(texts))\n        for i, (t, e) in enumerate(zip(texts, embeddings)):\n            m = metadatas[i] if metadatas else {}\n            doc = self.doc_cls(text=t, embedding=e, metadata=m)\n            self.doc_index.index([doc])\n            ids.append(str(doc.id))\n        return ids\n[docs]    def similarity_search_with_score(\n        self, query: str, k: int = 4, **kwargs: Any", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html"}
{"id": "7b8b53e55210-2", "text": "self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of documents most similar to the query text and\n            cosine distance in float for each.\n            Lower score represents more similarity.\n        \"\"\"\n        query_embedding = self.embedding.embed_query(query)\n        query_doc = self.doc_cls(embedding=query_embedding)  # type: ignore\n        docs, scores = self.doc_index.find(query_doc, search_field=\"embedding\", limit=k)\n        result = [\n            (Document(page_content=doc.text, metadata=doc.metadata), score)\n            for doc, score in zip(docs, scores)\n        ]\n        return result\n[docs]    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query.\n        \"\"\"\n        results = self.similarity_search_with_score(query, k=k, **kwargs)\n        return [doc for doc, _ in results]\n    def _similarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs and relevance scores, normalized on a scale from 0 to 1.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html"}
{"id": "7b8b53e55210-3", "text": "\"\"\"Return docs and relevance scores, normalized on a scale from 0 to 1.\n        0 is dissimilar, 1 is most similar.\n        \"\"\"\n        raise NotImplementedError()\n[docs]    def similarity_search_by_vector(\n        self, embedding: List[float], k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query vector.\n        \"\"\"\n        query_doc = self.doc_cls(embedding=embedding)  # type: ignore\n        docs = self.doc_index.find(\n            query_doc, search_field=\"embedding\", limit=k\n        ).documents\n        result = [\n            Document(page_content=doc.text, metadata=doc.metadata) for doc in docs\n        ]\n        return result\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                of diversity among the results with 0 corresponding", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html"}
{"id": "7b8b53e55210-4", "text": "of diversity among the results with 0 corresponding\n                to maximum diversity and 1 to minimum diversity.\n                Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        query_embedding = self.embedding.embed_query(query)\n        query_doc = self.doc_cls(embedding=query_embedding)  # type: ignore\n        docs = self.doc_index.find(\n            query_doc, search_field=\"embedding\", limit=fetch_k\n        ).documents\n        mmr_selected = maximal_marginal_relevance(\n            np.array(query_embedding), docs.embedding, k=k\n        )\n        results = [\n            Document(page_content=docs[idx].text, metadata=docs[idx].metadata)\n            for idx in mmr_selected\n        ]\n        return results", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html"}
{"id": "b988c1177e44-0", "text": "Source code for langchain.vectorstores.docarray.hnsw\nfrom __future__ import annotations\nfrom typing import Any, List, Literal, Optional\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.vectorstores.docarray.base import (\n    DocArrayIndex,\n    _check_docarray_import,\n)\n[docs]class DocArrayHnswSearch(DocArrayIndex):\n    \"\"\"`HnswLib` storage using `DocArray` package.\n    To use it, you should have the ``docarray`` package with version >=0.32.0 installed.\n    You can install it with `pip install \"langchain[docarray]\"`.\n    \"\"\"\n[docs]    @classmethod\n    def from_params(\n        cls,\n        embedding: Embeddings,\n        work_dir: str,\n        n_dim: int,\n        dist_metric: Literal[\"cosine\", \"ip\", \"l2\"] = \"cosine\",\n        max_elements: int = 1024,\n        index: bool = True,\n        ef_construction: int = 200,\n        ef: int = 10,\n        M: int = 16,\n        allow_replace_deleted: bool = True,\n        num_threads: int = 1,\n        **kwargs: Any,\n    ) -> DocArrayHnswSearch:\n        \"\"\"Initialize DocArrayHnswSearch store.\n        Args:\n            embedding (Embeddings): Embedding function.\n            work_dir (str): path to the location where all the data will be stored.\n            n_dim (int): dimension of an embedding.\n            dist_metric (str): Distance metric for DocArrayHnswSearch can be one of:\n                \"cosine\", \"ip\", and \"l2\". Defaults to \"cosine\".", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html"}
{"id": "b988c1177e44-1", "text": "\"cosine\", \"ip\", and \"l2\". Defaults to \"cosine\".\n            max_elements (int): Maximum number of vectors that can be stored.\n                Defaults to 1024.\n            index (bool): Whether an index should be built for this field.\n                Defaults to True.\n            ef_construction (int): defines a construction time/accuracy trade-off.\n                Defaults to 200.\n            ef (int): parameter controlling query time/accuracy trade-off.\n                Defaults to 10.\n            M (int): parameter that defines the maximum number of outgoing\n                connections in the graph. Defaults to 16.\n            allow_replace_deleted (bool): Enables replacing of deleted elements\n                with new added ones. Defaults to True.\n            num_threads (int): Sets the number of cpu threads to use. Defaults to 1.\n            **kwargs: Other keyword arguments to be passed to the get_doc_cls method.\n        \"\"\"\n        _check_docarray_import()\n        from docarray.index import HnswDocumentIndex\n        doc_cls = cls._get_doc_cls(\n            dim=n_dim,\n            space=dist_metric,\n            max_elements=max_elements,\n            index=index,\n            ef_construction=ef_construction,\n            ef=ef,\n            M=M,\n            allow_replace_deleted=allow_replace_deleted,\n            num_threads=num_threads,\n            **kwargs,\n        )\n        doc_index = HnswDocumentIndex[doc_cls](work_dir=work_dir)  # type: ignore\n        return cls(doc_index, embedding)\n[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        work_dir: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html"}
{"id": "b988c1177e44-2", "text": "work_dir: Optional[str] = None,\n        n_dim: Optional[int] = None,\n        **kwargs: Any,\n    ) -> DocArrayHnswSearch:\n        \"\"\"Create an DocArrayHnswSearch store and insert data.\n        Args:\n            texts (List[str]): Text data.\n            embedding (Embeddings): Embedding function.\n            metadatas (Optional[List[dict]]): Metadata for each text if it exists.\n                Defaults to None.\n            work_dir (str): path to the location where all the data will be stored.\n            n_dim (int): dimension of an embedding.\n            **kwargs: Other keyword arguments to be passed to the __init__ method.\n        Returns:\n            DocArrayHnswSearch Vector Store\n        \"\"\"\n        if work_dir is None:\n            raise ValueError(\"`work_dir` parameter has not been set.\")\n        if n_dim is None:\n            raise ValueError(\"`n_dim` parameter has not been set.\")\n        store = cls.from_params(embedding, work_dir, n_dim, **kwargs)\n        store.add_texts(texts=texts, metadatas=metadatas)\n        return store", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html"}
{"id": "36d2b2044acb-0", "text": "Source code for langchain.vectorstores.docarray.in_memory\n\"\"\"Wrapper around in-memory storage.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Literal, Optional\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.vectorstores.docarray.base import (\n    DocArrayIndex,\n    _check_docarray_import,\n)\n[docs]class DocArrayInMemorySearch(DocArrayIndex):\n    \"\"\"In-memory `DocArray` storage for exact search.\n    To use it, you should have the ``docarray`` package with version >=0.32.0 installed.\n    You can install it with `pip install \"langchain[docarray]\"`.\n    \"\"\"\n[docs]    @classmethod\n    def from_params(\n        cls,\n        embedding: Embeddings,\n        metric: Literal[\n            \"cosine_sim\", \"euclidian_dist\", \"sgeuclidean_dist\"\n        ] = \"cosine_sim\",\n        **kwargs: Any,\n    ) -> DocArrayInMemorySearch:\n        \"\"\"Initialize DocArrayInMemorySearch store.\n        Args:\n            embedding (Embeddings): Embedding function.\n            metric (str): metric for exact nearest-neighbor search.\n                Can be one of: \"cosine_sim\", \"euclidean_dist\" and \"sqeuclidean_dist\".\n                Defaults to \"cosine_sim\".\n            **kwargs: Other keyword arguments to be passed to the get_doc_cls method.\n        \"\"\"\n        _check_docarray_import()\n        from docarray.index import InMemoryExactNNIndex\n        doc_cls = cls._get_doc_cls(space=metric, **kwargs)\n        doc_index = InMemoryExactNNIndex[doc_cls]()  # type: ignore\n        return cls(doc_index, embedding)\n[docs]    @classmethod\n    def from_texts(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html"}
{"id": "36d2b2044acb-1", "text": "[docs]    @classmethod\n    def from_texts(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[Dict[Any, Any]]] = None,\n        **kwargs: Any,\n    ) -> DocArrayInMemorySearch:\n        \"\"\"Create an DocArrayInMemorySearch store and insert data.\n        Args:\n            texts (List[str]): Text data.\n            embedding (Embeddings): Embedding function.\n            metadatas (Optional[List[Dict[Any, Any]]]): Metadata for each text\n                if it exists. Defaults to None.\n            metric (str): metric for exact nearest-neighbor search.\n                Can be one of: \"cosine_sim\", \"euclidean_dist\" and \"sqeuclidean_dist\".\n                Defaults to \"cosine_sim\".\n        Returns:\n            DocArrayInMemorySearch Vector Store\n        \"\"\"\n        store = cls.from_params(embedding, **kwargs)\n        store.add_texts(texts=texts, metadatas=metadatas)\n        return store", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html"}
{"id": "e04c01785db2-0", "text": "Source code for langchain.vectorstores.redis.schema\nfrom __future__ import annotations\nimport os\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Union\nimport numpy as np\nimport yaml\nfrom typing_extensions import TYPE_CHECKING, Literal\nfrom langchain.pydantic_v1 import BaseModel, Field, validator\nfrom langchain.vectorstores.redis.constants import REDIS_VECTOR_DTYPE_MAP\nif TYPE_CHECKING:\n    from redis.commands.search.field import (  # type: ignore\n        NumericField,\n        TagField,\n        TextField,\n        VectorField,\n    )\n[docs]class RedisDistanceMetric(str, Enum):\n    \"\"\"Distance metrics for Redis vector fields.\"\"\"\n    l2 = \"L2\"\n    cosine = \"COSINE\"\n    ip = \"IP\"\n[docs]class RedisField(BaseModel):\n    \"\"\"Base class for Redis fields.\"\"\"\n    name: str = Field(...)\n[docs]class TextFieldSchema(RedisField):\n    \"\"\"Schema for text fields in Redis.\"\"\"\n    weight: float = 1\n    no_stem: bool = False\n    phonetic_matcher: Optional[str] = None\n    withsuffixtrie: bool = False\n    no_index: bool = False\n    sortable: Optional[bool] = False\n[docs]    def as_field(self) -> TextField:\n        from redis.commands.search.field import TextField  # type: ignore\n        return TextField(\n            self.name,\n            weight=self.weight,\n            no_stem=self.no_stem,\n            phonetic_matcher=self.phonetic_matcher,  # type: ignore\n            sortable=self.sortable,\n            no_index=self.no_index,\n        )\n[docs]class TagFieldSchema(RedisField):\n    \"\"\"Schema for tag fields in Redis.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html"}
{"id": "e04c01785db2-1", "text": "\"\"\"Schema for tag fields in Redis.\"\"\"\n    separator: str = \",\"\n    case_sensitive: bool = False\n    no_index: bool = False\n    sortable: Optional[bool] = False\n[docs]    def as_field(self) -> TagField:\n        from redis.commands.search.field import TagField  # type: ignore\n        return TagField(\n            self.name,\n            separator=self.separator,\n            case_sensitive=self.case_sensitive,\n            sortable=self.sortable,\n            no_index=self.no_index,\n        )\n[docs]class NumericFieldSchema(RedisField):\n    \"\"\"Schema for numeric fields in Redis.\"\"\"\n    no_index: bool = False\n    sortable: Optional[bool] = False\n[docs]    def as_field(self) -> NumericField:\n        from redis.commands.search.field import NumericField  # type: ignore\n        return NumericField(self.name, sortable=self.sortable, no_index=self.no_index)\n[docs]class RedisVectorField(RedisField):\n    \"\"\"Base class for Redis vector fields.\"\"\"\n    dims: int = Field(...)\n    algorithm: object = Field(...)\n    datatype: str = Field(default=\"FLOAT32\")\n    distance_metric: RedisDistanceMetric = Field(default=\"COSINE\")\n    initial_cap: Optional[int] = None\n    @validator(\"algorithm\", \"datatype\", \"distance_metric\", pre=True, each_item=True)\n    def uppercase_strings(cls, v: str) -> str:\n        return v.upper()\n    @validator(\"datatype\", pre=True)\n    def uppercase_and_check_dtype(cls, v: str) -> str:\n        if v.upper() not in REDIS_VECTOR_DTYPE_MAP:\n            raise ValueError(\n                f\"datatype must be one of {REDIS_VECTOR_DTYPE_MAP.keys()}. Got {v}\"\n            )\n        return v.upper()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html"}
{"id": "e04c01785db2-2", "text": ")\n        return v.upper()\n    def _fields(self) -> Dict[str, Any]:\n        field_data = {\n            \"TYPE\": self.datatype,\n            \"DIM\": self.dims,\n            \"DISTANCE_METRIC\": self.distance_metric,\n        }\n        if self.initial_cap is not None:  # Only include it if it's set\n            field_data[\"INITIAL_CAP\"] = self.initial_cap\n        return field_data\n[docs]class FlatVectorField(RedisVectorField):\n    \"\"\"Schema for flat vector fields in Redis.\"\"\"\n    algorithm: Literal[\"FLAT\"] = \"FLAT\"\n    block_size: Optional[int] = None\n[docs]    def as_field(self) -> VectorField:\n        from redis.commands.search.field import VectorField  # type: ignore\n        field_data = super()._fields()\n        if self.block_size is not None:\n            field_data[\"BLOCK_SIZE\"] = self.block_size\n        return VectorField(self.name, self.algorithm, field_data)\n[docs]class HNSWVectorField(RedisVectorField):\n    \"\"\"Schema for HNSW vector fields in Redis.\"\"\"\n    algorithm: Literal[\"HNSW\"] = \"HNSW\"\n    m: int = Field(default=16)\n    ef_construction: int = Field(default=200)\n    ef_runtime: int = Field(default=10)\n    epsilon: float = Field(default=0.01)\n[docs]    def as_field(self) -> VectorField:\n        from redis.commands.search.field import VectorField  # type: ignore\n        field_data = super()._fields()\n        field_data.update(\n            {\n                \"M\": self.m,\n                \"EF_CONSTRUCTION\": self.ef_construction,\n                \"EF_RUNTIME\": self.ef_runtime,\n                \"EPSILON\": self.epsilon,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html"}
{"id": "e04c01785db2-3", "text": "\"EF_RUNTIME\": self.ef_runtime,\n                \"EPSILON\": self.epsilon,\n            }\n        )\n        return VectorField(self.name, self.algorithm, field_data)\n[docs]class RedisModel(BaseModel):\n    \"\"\"Schema for Redis index.\"\"\"\n    # always have a content field for text\n    text: List[TextFieldSchema] = [TextFieldSchema(name=\"content\")]\n    tag: Optional[List[TagFieldSchema]] = None\n    numeric: Optional[List[NumericFieldSchema]] = None\n    extra: Optional[List[RedisField]] = None\n    # filled by default_vector_schema\n    vector: Optional[List[Union[FlatVectorField, HNSWVectorField]]] = None\n    content_key: str = \"content\"\n    content_vector_key: str = \"content_vector\"\n[docs]    def add_content_field(self) -> None:\n        if self.text is None:\n            self.text = []\n        for field in self.text:\n            if field.name == self.content_key:\n                return\n        self.text.append(TextFieldSchema(name=self.content_key))\n[docs]    def add_vector_field(self, vector_field: Dict[str, Any]) -> None:\n        # catch case where user inputted no vector field spec\n        # in the index schema\n        if self.vector is None:\n            self.vector = []\n        # ignore types as pydantic is handling type validation and conversion\n        if vector_field[\"algorithm\"] == \"FLAT\":\n            self.vector.append(FlatVectorField(**vector_field))  # type: ignore\n        elif vector_field[\"algorithm\"] == \"HNSW\":\n            self.vector.append(HNSWVectorField(**vector_field))  # type: ignore\n        else:\n            raise ValueError(\n                f\"algorithm must be either FLAT or HNSW. Got \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html"}
{"id": "e04c01785db2-4", "text": "f\"algorithm must be either FLAT or HNSW. Got \"\n                f\"{vector_field['algorithm']}\"\n            )\n[docs]    def as_dict(self) -> Dict[str, List[Any]]:\n        schemas: Dict[str, List[Any]] = {\"text\": [], \"tag\": [], \"numeric\": []}\n        # iter over all class attributes\n        for attr, attr_value in self.__dict__.items():\n            # only non-empty lists\n            if isinstance(attr_value, list) and len(attr_value) > 0:\n                field_values: List[Dict[str, Any]] = []\n                # iterate over all fields in each category (tag, text, etc)\n                for val in attr_value:\n                    value: Dict[str, Any] = {}\n                    # iterate over values within each field to extract\n                    # settings for that field (i.e. name, weight, etc)\n                    for field, field_value in val.__dict__.items():\n                        # make enums into strings\n                        if isinstance(field_value, Enum):\n                            value[field] = field_value.value\n                        # don't write null values\n                        elif field_value is not None:\n                            value[field] = field_value\n                    field_values.append(value)\n                schemas[attr] = field_values\n        schema: Dict[str, List[Any]] = {}\n        # only write non-empty lists from defaults\n        for k, v in schemas.items():\n            if len(v) > 0:\n                schema[k] = v\n        return schema\n    @property\n    def content_vector(self) -> Union[FlatVectorField, HNSWVectorField]:\n        if not self.vector:\n            raise ValueError(\"No vector fields found\")\n        for field in self.vector:\n            if field.name == self.content_vector_key:\n                return field", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html"}
{"id": "e04c01785db2-5", "text": "if field.name == self.content_vector_key:\n                return field\n        raise ValueError(\"No content_vector field found\")\n    @property\n    def vector_dtype(self) -> np.dtype:\n        # should only ever be called after pydantic has validated the schema\n        return REDIS_VECTOR_DTYPE_MAP[self.content_vector.datatype]\n    @property\n    def is_empty(self) -> bool:\n        return all(\n            field is None for field in [self.tag, self.text, self.numeric, self.vector]\n        )\n[docs]    def get_fields(self) -> List[\"RedisField\"]:\n        redis_fields: List[\"RedisField\"] = []\n        if self.is_empty:\n            return redis_fields\n        for field_name in self.__fields__.keys():\n            if field_name not in [\"content_key\", \"content_vector_key\", \"extra\"]:\n                field_group = getattr(self, field_name)\n                if field_group is not None:\n                    for field in field_group:\n                        redis_fields.append(field.as_field())\n        return redis_fields\n    @property\n    def metadata_keys(self) -> List[str]:\n        keys: List[str] = []\n        if self.is_empty:\n            return keys\n        for field_name in self.__fields__.keys():\n            field_group = getattr(self, field_name)\n            if field_group is not None:\n                for field in field_group:\n                    # check if it's a metadata field. exclude vector and content key\n                    if not isinstance(field, str) and field.name not in [\n                        self.content_key,\n                        self.content_vector_key,\n                    ]:\n                        keys.append(field.name)\n        return keys\n[docs]def read_schema(\n    index_schema: Optional[Union[Dict[str, List[Any]], str, os.PathLike]]\n) -> Dict[str, Any]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html"}
{"id": "e04c01785db2-6", "text": ") -> Dict[str, Any]:\n    \"\"\"Reads in the index schema from a dict or yaml file.\n    Check if it is a dict and return RedisModel otherwise, check if it's a path and\n    read in the file assuming it's a yaml file and return a RedisModel\n    \"\"\"\n    if isinstance(index_schema, dict):\n        return index_schema\n    elif isinstance(index_schema, Path):\n        with open(index_schema, \"rb\") as f:\n            return yaml.safe_load(f)\n    elif isinstance(index_schema, str):\n        if Path(index_schema).resolve().is_file():\n            with open(index_schema, \"rb\") as f:\n                return yaml.safe_load(f)\n        else:\n            raise FileNotFoundError(f\"index_schema file {index_schema} does not exist\")\n    else:\n        raise TypeError(\n            f\"index_schema must be a dict, or path to a yaml file \"\n            f\"Got {type(index_schema)}\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html"}
{"id": "dc70e738e6bd-0", "text": "Source code for langchain.vectorstores.redis.base\n\"\"\"Wrapper around Redis vector database.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport os\nimport uuid\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Mapping,\n    Optional,\n    Tuple,\n    Type,\n    Union,\n    cast,\n)\nimport numpy as np\nimport yaml\nfrom langchain._api import deprecated\nfrom langchain.callbacks.manager import CallbackManagerForRetrieverRun\nfrom langchain.docstore.document import Document\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore, VectorStoreRetriever\nfrom langchain.utilities.redis import (\n    _array_to_buffer,\n    _buffer_to_array,\n    check_redis_module_exist,\n    get_client,\n)\nfrom langchain.utils import get_from_dict_or_env\nfrom langchain.vectorstores.redis.constants import (\n    REDIS_REQUIRED_MODULES,\n    REDIS_TAG_SEPARATOR,\n)\nfrom langchain.vectorstores.utils import maximal_marginal_relevance\nlogger = logging.getLogger(__name__)\nif TYPE_CHECKING:\n    from redis.client import Redis as RedisType\n    from redis.commands.search.query import Query\n    from langchain.vectorstores.redis.filters import RedisFilterExpression\n    from langchain.vectorstores.redis.schema import RedisModel\ndef _default_relevance_score(val: float) -> float:\n    return 1 - val\n[docs]def check_index_exists(client: RedisType, index_name: str) -> bool:\n    \"\"\"Check if Redis index exists.\"\"\"\n    try:\n        client.ft(index_name).info()\n    except:  # noqa: E722\n        logger.info(\"Index does not exist\")\n        return False\n    logger.info(\"Index already exists\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-1", "text": "return False\n    logger.info(\"Index already exists\")\n    return True\n[docs]class Redis(VectorStore):\n    \"\"\"Redis vector database.\n    To use, you should have the ``redis`` python package installed\n    and have a running Redis Enterprise or Redis-Stack server\n    For production use cases, it is recommended to use Redis Enterprise\n    as the scaling, performance, stability and availability is much\n    better than Redis-Stack.\n    For testing and prototyping, however, this is not required.\n    Redis-Stack is available as a docker container the full vector\n    search API available.\n    .. code-block:: bash\n        # to run redis stack in docker locally\n        docker run -d -p 6379:6379 -p 8001:8001 redis/redis-stack:latest\n    Once running, you can connect to the redis server with the following url schemas:\n    - redis://<host>:<port> # simple connection\n    - redis://<username>:<password>@<host>:<port> # connection with authentication\n    - rediss://<host>:<port> # connection with SSL\n    - rediss://<username>:<password>@<host>:<port> # connection with SSL and auth\n    Examples:\n    The following examples show various ways to use the Redis VectorStore with\n    LangChain.\n    For all the following examples assume we have the following imports:\n    .. code-block:: python\n        from langchain.vectorstores import Redis\n        from langchain.embeddings import OpenAIEmbeddings\n    Initialize, create index, and load Documents\n        .. code-block:: python\n            from langchain.vectorstores import Redis\n            from langchain.embeddings import OpenAIEmbeddings\n            rds = Redis.from_documents(\n                documents, # a list of Document objects from loaders or created", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-2", "text": "documents, # a list of Document objects from loaders or created\n                embeddings, # an Embeddings object\n                redis_url=\"redis://localhost:6379\",\n            )\n    Initialize, create index, and load Documents with metadata\n        .. code-block:: python\n            rds = Redis.from_texts(\n                texts, # a list of strings\n                metadata, # a list of metadata dicts\n                embeddings, # an Embeddings object\n                redis_url=\"redis://localhost:6379\",\n            )\n    Initialize, create index, and load Documents with metadata and return keys\n        .. code-block:: python\n            rds, keys = Redis.from_texts_return_keys(\n                texts, # a list of strings\n                metadata, # a list of metadata dicts\n                embeddings, # an Embeddings object\n                redis_url=\"redis://localhost:6379\",\n            )\n    For use cases where the index needs to stay alive, you can initialize\n    with an index name such that it's easier to reference later\n        .. code-block:: python\n            rds = Redis.from_texts(\n                texts, # a list of strings\n                metadata, # a list of metadata dicts\n                embeddings, # an Embeddings object\n                index_name=\"my-index\",\n                redis_url=\"redis://localhost:6379\",\n            )\n    Initialize and connect to an existing index (from above)\n        .. code-block:: python\n            rds = Redis.from_existing_index(\n                embeddings, # an Embeddings object\n                index_name=\"my-index\",\n                redis_url=\"redis://localhost:6379\",\n            )\n    Advanced examples:\n    Custom vector schema can be supplied to change the way that\n    Redis creates the underlying vector schema. This is useful\n    for production use cases where you want to optimize the", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-3", "text": "for production use cases where you want to optimize the\n    vector schema for your use case. ex. using HNSW instead of\n    FLAT (knn) which is the default\n        .. code-block:: python\n            vector_schema = {\n                \"algorithm\": \"HNSW\"\n            }\n            rds = Redis.from_texts(\n                texts, # a list of strings\n                metadata, # a list of metadata dicts\n                embeddings, # an Embeddings object\n                vector_schema=vector_schema,\n                redis_url=\"redis://localhost:6379\",\n            )\n    Custom index schema can be supplied to change the way that the\n    metadata is indexed. This is useful for you would like to use the\n    hybrid querying (filtering) capability of Redis.\n    By default, this implementation will automatically generate the index\n    schema according to the following rules:\n        - All strings are indexed as text fields\n        - All numbers are indexed as numeric fields\n        - All lists of strings are indexed as tag fields (joined by\n            langchain.vectorstores.redis.constants.REDIS_TAG_SEPARATOR)\n        - All None values are not indexed but still stored in Redis these are\n            not retrievable through the interface here, but the raw Redis client\n            can be used to retrieve them.\n        - All other types are not indexed\n    To override these rules, you can pass in a custom index schema like the following\n        .. code-block:: yaml\n            tag:\n                - name: credit_score\n            text:\n                - name: user\n                - name: job\n    Typically, the ``credit_score`` field would be a text field since it's a string,\n    however, we can override this behavior by specifying the field type as shown with\n    the yaml config (can also be a dictionary) above and the code below.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-4", "text": "the yaml config (can also be a dictionary) above and the code below.\n        .. code-block:: python\n            rds = Redis.from_texts(\n                texts, # a list of strings\n                metadata, # a list of metadata dicts\n                embeddings, # an Embeddings object\n                index_schema=\"path/to/index_schema.yaml\", # can also be a dictionary\n                redis_url=\"redis://localhost:6379\",\n            )\n    When connecting to an existing index where a custom schema has been applied, it's\n    important to pass in the same schema to the ``from_existing_index`` method.\n    Otherwise, the schema for newly added samples will be incorrect and metadata\n    will not be returned.\n    \"\"\"\n    DEFAULT_VECTOR_SCHEMA = {\n        \"name\": \"content_vector\",\n        \"algorithm\": \"FLAT\",\n        \"dims\": 1536,\n        \"distance_metric\": \"COSINE\",\n        \"datatype\": \"FLOAT32\",\n    }\n[docs]    def __init__(\n        self,\n        redis_url: str,\n        index_name: str,\n        embedding: Embeddings,\n        index_schema: Optional[Union[Dict[str, str], str, os.PathLike]] = None,\n        vector_schema: Optional[Dict[str, Union[str, int]]] = None,\n        relevance_score_fn: Optional[Callable[[float], float]] = None,\n        key_prefix: Optional[str] = None,\n        **kwargs: Any,\n    ):\n        \"\"\"Initialize with necessary components.\"\"\"\n        self._check_deprecated_kwargs(kwargs)\n        try:\n            # TODO use importlib to check if redis is installed\n            import redis  # noqa: F401\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import redis python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-5", "text": "raise ImportError(\n                \"Could not import redis python package. \"\n                \"Please install it with `pip install redis`.\"\n            ) from e\n        self.index_name = index_name\n        self._embeddings = embedding\n        try:\n            redis_client = get_client(redis_url=redis_url, **kwargs)\n            # check if redis has redisearch module installed\n            check_redis_module_exist(redis_client, REDIS_REQUIRED_MODULES)\n        except ValueError as e:\n            raise ValueError(f\"Redis failed to connect: {e}\")\n        self.client = redis_client\n        self.relevance_score_fn = relevance_score_fn\n        self._schema = self._get_schema_with_defaults(index_schema, vector_schema)\n        self.key_prefix = key_prefix if key_prefix is not None else f\"doc:{index_name}\"\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        \"\"\"Access the query embedding object if available.\"\"\"\n        return self._embeddings\n[docs]    @classmethod\n    def from_texts_return_keys(\n        cls,\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        index_name: Optional[str] = None,\n        index_schema: Optional[Union[Dict[str, str], str, os.PathLike]] = None,\n        vector_schema: Optional[Dict[str, Union[str, int]]] = None,\n        **kwargs: Any,\n    ) -> Tuple[Redis, List[str]]:\n        \"\"\"Create a Redis vectorstore from raw documents.\n        This is a user-friendly interface that:\n            1. Embeds documents.\n            2. Creates a new Redis index if it doesn't already exist\n            3. Adds the documents to the newly created Redis index.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-6", "text": "3. Adds the documents to the newly created Redis index.\n            4. Returns the keys of the newly created documents once stored.\n        This method will generate schema based on the metadata passed in\n        if the `index_schema` is not defined. If the `index_schema` is defined,\n        it will compare against the generated schema and warn if there are\n        differences. If you are purposefully defining the schema for the\n        metadata, then you can ignore that warning.\n        To examine the schema options, initialize an instance of this class\n        and print out the schema using the `Redis.schema`` property. This\n        will include the content and content_vector classes which are\n        always present in the langchain schema.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import Redis\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                redis, keys = Redis.from_texts_return_keys(\n                    texts,\n                    embeddings,\n                    redis_url=\"redis://localhost:6379\"\n                )\n        Args:\n            texts (List[str]): List of texts to add to the vectorstore.\n            embedding (Embeddings): Embeddings to use for the vectorstore.\n            metadatas (Optional[List[dict]], optional): Optional list of metadata\n                dicts to add to the vectorstore. Defaults to None.\n            index_name (Optional[str], optional): Optional name of the index to\n                create or add to. Defaults to None.\n            index_schema (Optional[Union[Dict[str, str], str, os.PathLike]], optional):\n                Optional fields to index within the metadata. Overrides generated\n                schema. Defaults to None.\n            vector_schema (Optional[Dict[str, Union[str, int]]], optional): Optional\n                vector schema to use. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-7", "text": "vector schema to use. Defaults to None.\n            **kwargs (Any): Additional keyword arguments to pass to the Redis client.\n        Returns:\n            Tuple[Redis, List[str]]: Tuple of the Redis instance and the keys of\n                the newly created documents.\n        Raises:\n            ValueError: If the number of metadatas does not match the number of texts.\n        \"\"\"\n        try:\n            # TODO use importlib to check if redis is installed\n            import redis  # noqa: F401\n            from langchain.vectorstores.redis.schema import read_schema\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import redis python package. \"\n                \"Please install it with `pip install redis`.\"\n            ) from e\n        redis_url = get_from_dict_or_env(kwargs, \"redis_url\", \"REDIS_URL\")\n        if \"redis_url\" in kwargs:\n            kwargs.pop(\"redis_url\")\n        # flag to use generated schema\n        if \"generate\" in kwargs:\n            kwargs.pop(\"generate\")\n        # see if the user specified keys\n        keys = None\n        if \"keys\" in kwargs:\n            keys = kwargs.pop(\"keys\")\n        # Name of the search index if not given\n        if not index_name:\n            index_name = uuid.uuid4().hex\n        # type check for metadata\n        if metadatas:\n            if isinstance(metadatas, list) and len(metadatas) != len(texts):  # type: ignore  # noqa: E501\n                raise ValueError(\"Number of metadatas must match number of texts\")\n            if not (isinstance(metadatas, list) and isinstance(metadatas[0], dict)):\n                raise ValueError(\"Metadatas must be a list of dicts\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-8", "text": "raise ValueError(\"Metadatas must be a list of dicts\")\n            generated_schema = _generate_field_schema(metadatas[0])\n            if index_schema:\n                # read in the schema solely to compare to the generated schema\n                user_schema = read_schema(index_schema)  # type: ignore\n                # the very rare case where a super user decides to pass the index\n                # schema and a document loader is used that has metadata which\n                # we need to map into fields.\n                if user_schema != generated_schema:\n                    logger.warning(\n                        \"`index_schema` does not match generated metadata schema.\\n\"\n                        + \"If you meant to manually override the schema, please \"\n                        + \"ignore this message.\\n\"\n                        + f\"index_schema: {user_schema}\\n\"\n                        + f\"generated_schema: {generated_schema}\\n\"\n                    )\n            else:\n                # use the generated schema\n                index_schema = generated_schema\n        # Create instance\n        instance = cls(\n            redis_url,\n            index_name,\n            embedding,\n            index_schema=index_schema,\n            vector_schema=vector_schema,\n            **kwargs,\n        )\n        # Add data to Redis\n        keys = instance.add_texts(texts, metadatas, keys=keys)\n        return instance, keys\n[docs]    @classmethod\n    def from_texts(\n        cls: Type[Redis],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        index_name: Optional[str] = None,\n        index_schema: Optional[Union[Dict[str, str], str, os.PathLike]] = None,\n        vector_schema: Optional[Dict[str, Union[str, int]]] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-9", "text": "**kwargs: Any,\n    ) -> Redis:\n        \"\"\"Create a Redis vectorstore from a list of texts.\n        This is a user-friendly interface that:\n            1. Embeds documents.\n            2. Creates a new Redis index if it doesn't already exist\n            3. Adds the documents to the newly created Redis index.\n        This method will generate schema based on the metadata passed in\n        if the `index_schema` is not defined. If the `index_schema` is defined,\n        it will compare against the generated schema and warn if there are\n        differences. If you are purposefully defining the schema for the\n        metadata, then you can ignore that warning.\n        To examine the schema options, initialize an instance of this class\n        and print out the schema using the `Redis.schema`` property. This\n        will include the content and content_vector classes which are\n        always present in the langchain schema.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import Redis\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                redisearch = RediSearch.from_texts(\n                    texts,\n                    embeddings,\n                    redis_url=\"redis://username:password@localhost:6379\"\n                )\n        Args:\n            texts (List[str]): List of texts to add to the vectorstore.\n            embedding (Embeddings): Embedding model class (i.e. OpenAIEmbeddings)\n                for embedding queries.\n            metadatas (Optional[List[dict]], optional): Optional list of metadata dicts\n                to add to the vectorstore. Defaults to None.\n            index_name (Optional[str], optional): Optional name of the index to create\n                or add to. Defaults to None.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-10", "text": "or add to. Defaults to None.\n            index_schema (Optional[Union[Dict[str, str], str, os.PathLike]], optional):\n                Optional fields to index within the metadata. Overrides generated\n                schema. Defaults to None.\n            vector_schema (Optional[Dict[str, Union[str, int]]], optional): Optional\n                vector schema to use. Defaults to None.\n            **kwargs (Any): Additional keyword arguments to pass to the Redis client.\n        Returns:\n            Redis: Redis VectorStore instance.\n        Raises:\n            ValueError: If the number of metadatas does not match the number of texts.\n            ImportError: If the redis python package is not installed.\n        \"\"\"\n        instance, _ = cls.from_texts_return_keys(\n            texts,\n            embedding,\n            metadatas=metadatas,\n            index_name=index_name,\n            index_schema=index_schema,\n            vector_schema=vector_schema,\n            **kwargs,\n        )\n        return instance\n[docs]    @classmethod\n    def from_existing_index(\n        cls,\n        embedding: Embeddings,\n        index_name: str,\n        schema: Union[Dict[str, str], str, os.PathLike],\n        **kwargs: Any,\n    ) -> Redis:\n        \"\"\"Connect to an existing Redis index.\n        Example:\n            .. code-block:: python\n                from langchain.vectorstores import Redis\n                from langchain.embeddings import OpenAIEmbeddings\n                embeddings = OpenAIEmbeddings()\n                redisearch = Redis.from_existing_index(\n                    embeddings,\n                    index_name=\"my-index\",\n                    redis_url=\"redis://username:password@localhost:6379\"\n                )\n        Args:\n            embedding (Embeddings): Embedding model class (i.e. OpenAIEmbeddings)\n                for embedding queries.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-11", "text": "for embedding queries.\n            index_name (str): Name of the index to connect to.\n            schema (Union[Dict[str, str], str, os.PathLike]): Schema of the index\n                and the vector schema. Can be a dict, or path to yaml file\n            **kwargs (Any): Additional keyword arguments to pass to the Redis client.\n        Returns:\n            Redis: Redis VectorStore instance.\n        Raises:\n            ValueError: If the index does not exist.\n            ImportError: If the redis python package is not installed.\n        \"\"\"\n        redis_url = get_from_dict_or_env(kwargs, \"redis_url\", \"REDIS_URL\")\n        try:\n            # We need to first remove redis_url from kwargs,\n            # otherwise passing it to Redis will result in an error.\n            if \"redis_url\" in kwargs:\n                kwargs.pop(\"redis_url\")\n            client = get_client(redis_url=redis_url, **kwargs)\n            # check if redis has redisearch module installed\n            check_redis_module_exist(client, REDIS_REQUIRED_MODULES)\n            # ensure that the index already exists\n            assert check_index_exists(\n                client, index_name\n            ), f\"Index {index_name} does not exist\"\n        except Exception as e:\n            raise ValueError(f\"Redis failed to connect: {e}\")\n        return cls(\n            redis_url,\n            index_name,\n            embedding,\n            index_schema=schema,\n            **kwargs,\n        )\n    @property\n    def schema(self) -> Dict[str, List[Any]]:\n        \"\"\"Return the schema of the index.\"\"\"\n        return self._schema.as_dict()\n[docs]    def write_schema(self, path: Union[str, os.PathLike]) -> None:\n        \"\"\"Write the schema to a yaml file.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-12", "text": "\"\"\"Write the schema to a yaml file.\"\"\"\n        with open(path, \"w+\") as f:\n            yaml.dump(self.schema, f)\n[docs]    @staticmethod\n    def delete(\n        ids: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> bool:\n        \"\"\"\n        Delete a Redis entry.\n        Args:\n            ids: List of ids (keys in redis) to delete.\n            redis_url: Redis connection url. This should be passed in the kwargs\n                or set as an environment variable: REDIS_URL.\n        Returns:\n            bool: Whether or not the deletions were successful.\n        Raises:\n            ValueError: If the redis python package is not installed.\n            ValueError: If the ids (keys in redis) are not provided\n        \"\"\"\n        redis_url = get_from_dict_or_env(kwargs, \"redis_url\", \"REDIS_URL\")\n        if ids is None:\n            raise ValueError(\"'ids' (keys)() were not provided.\")\n        try:\n            import redis  # noqa: F401\n        except ImportError:\n            raise ValueError(\n                \"Could not import redis python package. \"\n                \"Please install it with `pip install redis`.\"\n            )\n        try:\n            # We need to first remove redis_url from kwargs,\n            # otherwise passing it to Redis will result in an error.\n            if \"redis_url\" in kwargs:\n                kwargs.pop(\"redis_url\")\n            client = get_client(redis_url=redis_url, **kwargs)\n        except ValueError as e:\n            raise ValueError(f\"Your redis connected error: {e}\")\n        # Check if index exists\n        try:\n            client.delete(*ids)\n            logger.info(\"Entries deleted\")\n            return True\n        except:  # noqa: E722", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-13", "text": "return True\n        except:  # noqa: E722\n            # ids does not exist\n            return False\n[docs]    @staticmethod\n    def drop_index(\n        index_name: str,\n        delete_documents: bool,\n        **kwargs: Any,\n    ) -> bool:\n        \"\"\"\n        Drop a Redis search index.\n        Args:\n            index_name (str): Name of the index to drop.\n            delete_documents (bool): Whether to drop the associated documents.\n        Returns:\n            bool: Whether or not the drop was successful.\n        \"\"\"\n        redis_url = get_from_dict_or_env(kwargs, \"redis_url\", \"REDIS_URL\")\n        try:\n            import redis  # noqa: F401\n        except ImportError:\n            raise ValueError(\n                \"Could not import redis python package. \"\n                \"Please install it with `pip install redis`.\"\n            )\n        try:\n            # We need to first remove redis_url from kwargs,\n            # otherwise passing it to Redis will result in an error.\n            if \"redis_url\" in kwargs:\n                kwargs.pop(\"redis_url\")\n            client = get_client(redis_url=redis_url, **kwargs)\n        except ValueError as e:\n            raise ValueError(f\"Your redis connected error: {e}\")\n        # Check if index exists\n        try:\n            client.ft(index_name).dropindex(delete_documents)\n            logger.info(\"Drop index\")\n            return True\n        except:  # noqa: E722\n            # Index not exist\n            return False\n[docs]    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        embeddings: Optional[List[List[float]]] = None,\n        batch_size: int = 1000,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-14", "text": "batch_size: int = 1000,\n        clean_metadata: bool = True,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Add more texts to the vectorstore.\n        Args:\n            texts (Iterable[str]): Iterable of strings/text to add to the vectorstore.\n            metadatas (Optional[List[dict]], optional): Optional list of metadatas.\n                Defaults to None.\n            embeddings (Optional[List[List[float]]], optional): Optional pre-generated\n                embeddings. Defaults to None.\n            keys (List[str]) or ids (List[str]): Identifiers of entries.\n                Defaults to None.\n            batch_size (int, optional): Batch size to use for writes. Defaults to 1000.\n        Returns:\n            List[str]: List of ids added to the vectorstore\n        \"\"\"\n        ids = []\n        # Get keys or ids from kwargs\n        # Other vectorstores use ids\n        keys_or_ids = kwargs.get(\"keys\", kwargs.get(\"ids\"))\n        # type check for metadata\n        if metadatas:\n            if isinstance(metadatas, list) and len(metadatas) != len(texts):  # type: ignore  # noqa: E501\n                raise ValueError(\"Number of metadatas must match number of texts\")\n            if not (isinstance(metadatas, list) and isinstance(metadatas[0], dict)):\n                raise ValueError(\"Metadatas must be a list of dicts\")\n        embeddings = embeddings or self._embeddings.embed_documents(list(texts))\n        self._create_index_if_not_exist(dim=len(embeddings[0]))\n        # Write data to redis\n        pipeline = self.client.pipeline(transaction=False)\n        for i, text in enumerate(texts):\n            # Use provided values by default or fallback", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-15", "text": "# Use provided values by default or fallback\n            key = keys_or_ids[i] if keys_or_ids else str(uuid.uuid4().hex)\n            if not key.startswith(self.key_prefix + \":\"):\n                key = self.key_prefix + \":\" + key\n            metadata = metadatas[i] if metadatas else {}\n            metadata = _prepare_metadata(metadata) if clean_metadata else metadata\n            pipeline.hset(\n                key,\n                mapping={\n                    self._schema.content_key: text,\n                    self._schema.content_vector_key: _array_to_buffer(\n                        embeddings[i], self._schema.vector_dtype\n                    ),\n                    **metadata,\n                },\n            )\n            ids.append(key)\n            # Write batch\n            if i % batch_size == 0:\n                pipeline.execute()\n        # Cleanup final batch\n        pipeline.execute()\n        return ids\n[docs]    def as_retriever(self, **kwargs: Any) -> RedisVectorStoreRetriever:\n        tags = kwargs.pop(\"tags\", None) or []\n        tags.extend(self._get_retriever_tags())\n        return RedisVectorStoreRetriever(vectorstore=self, **kwargs, tags=tags)\n[docs]    @deprecated(\"0.0.272\", alternative=\"similarity_search(distance_threshold=0.1)\")\n    def similarity_search_limit_score(\n        self, query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"\n        Returns the most similar indexed documents to the query text within the\n        score_threshold range.\n        Deprecated: Use similarity_search with distance_threshold instead.\n        Args:\n            query (str): The query text for which to find similar documents.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-16", "text": "Args:\n            query (str): The query text for which to find similar documents.\n            k (int): The number of documents to return. Default is 4.\n            score_threshold (float): The minimum matching *distance* required\n                for a document to be considered a match. Defaults to 0.2.\n        Returns:\n            List[Document]: A list of documents that are most similar to the query text\n                including the match score for each document.\n        Note:\n            If there are no documents that satisfy the score_threshold value,\n            an empty list is returned.\n        \"\"\"\n        return self.similarity_search(\n            query, k=k, distance_threshold=score_threshold, **kwargs\n        )\n[docs]    def similarity_search_with_score(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[RedisFilterExpression] = None,\n        return_metadata: bool = True,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Run similarity search with **vector distance**.\n        The \"scores\" returned from this function are the raw vector\n        distances from the query vector. For similarity scores, use\n        ``similarity_search_with_relevance_scores``.\n        Args:\n            query (str): The query text for which to find similar documents.\n            k (int): The number of documents to return. Default is 4.\n            filter (RedisFilterExpression, optional): Optional metadata filter.\n                Defaults to None.\n            return_metadata (bool, optional): Whether to return metadata.\n                Defaults to True.\n        Returns:\n            List[Tuple[Document, float]]: A list of documents that are\n                most similar to the query with the distance for each document.\n        \"\"\"\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-17", "text": "\"\"\"\n        try:\n            import redis\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import redis python package. \"\n                \"Please install it with `pip install redis`.\"\n            ) from e\n        if \"score_threshold\" in kwargs:\n            logger.warning(\n                \"score_threshold is deprecated. Use distance_threshold instead.\"\n                + \"score_threshold should only be used in \"\n                + \"similarity_search_with_relevance_scores.\"\n                + \"score_threshold will be removed in a future release.\",\n            )\n        query_embedding = self._embeddings.embed_query(query)\n        redis_query, params_dict = self._prepare_query(\n            query_embedding,\n            k=k,\n            filter=filter,\n            with_metadata=return_metadata,\n            with_distance=True,\n            **kwargs,\n        )\n        # Perform vector search\n        # ignore type because redis-py is wrong about bytes\n        try:\n            results = self.client.ft(self.index_name).search(redis_query, params_dict)  # type: ignore  # noqa: E501\n        except redis.exceptions.ResponseError as e:\n            # split error message and see if it starts with \"Syntax\"\n            if str(e).split(\" \")[0] == \"Syntax\":\n                raise ValueError(\n                    \"Query failed with syntax error. \"\n                    + \"This is likely due to malformation of \"\n                    + \"filter, vector, or query argument\"\n                ) from e\n            raise e\n        # Prepare document results\n        docs_with_scores: List[Tuple[Document, float]] = []\n        for result in results.docs:\n            metadata = {}\n            if return_metadata:\n                metadata = {\"id\": result.id}\n                metadata.update(self._collect_metadata(result))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-18", "text": "metadata = {\"id\": result.id}\n                metadata.update(self._collect_metadata(result))\n            doc = Document(page_content=result.content, metadata=metadata)\n            distance = self._calculate_fp_distance(result.distance)\n            docs_with_scores.append((doc, distance))\n        return docs_with_scores\n[docs]    def similarity_search(\n        self,\n        query: str,\n        k: int = 4,\n        filter: Optional[RedisFilterExpression] = None,\n        return_metadata: bool = True,\n        distance_threshold: Optional[float] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Run similarity search\n        Args:\n            query (str): The query text for which to find similar documents.\n            k (int): The number of documents to return. Default is 4.\n            filter (RedisFilterExpression, optional): Optional metadata filter.\n                Defaults to None.\n            return_metadata (bool, optional): Whether to return metadata.\n                Defaults to True.\n            distance_threshold (Optional[float], optional): Maximum vector distance\n                between selected documents and the query vector. Defaults to None.\n        Returns:\n            List[Document]: A list of documents that are most similar to the query\n                text.\n        \"\"\"\n        query_embedding = self._embeddings.embed_query(query)\n        return self.similarity_search_by_vector(\n            query_embedding,\n            k=k,\n            filter=filter,\n            return_metadata=return_metadata,\n            distance_threshold=distance_threshold,\n            **kwargs,\n        )\n[docs]    def similarity_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        filter: Optional[RedisFilterExpression] = None,\n        return_metadata: bool = True,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-19", "text": "return_metadata: bool = True,\n        distance_threshold: Optional[float] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Run similarity search between a query vector and the indexed vectors.\n        Args:\n            embedding (List[float]): The query vector for which to find similar\n                documents.\n            k (int): The number of documents to return. Default is 4.\n            filter (RedisFilterExpression, optional): Optional metadata filter.\n                Defaults to None.\n            return_metadata (bool, optional): Whether to return metadata.\n                Defaults to True.\n            distance_threshold (Optional[float], optional): Maximum vector distance\n                between selected documents and the query vector. Defaults to None.\n        Returns:\n            List[Document]: A list of documents that are most similar to the query\n                text.\n        \"\"\"\n        try:\n            import redis\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import redis python package. \"\n                \"Please install it with `pip install redis`.\"\n            ) from e\n        if \"score_threshold\" in kwargs:\n            logger.warning(\n                \"score_threshold is deprecated. Use distance_threshold instead.\"\n                + \"score_threshold should only be used in \"\n                + \"similarity_search_with_relevance_scores.\"\n                + \"score_threshold will be removed in a future release.\",\n            )\n        redis_query, params_dict = self._prepare_query(\n            embedding,\n            k=k,\n            filter=filter,\n            distance_threshold=distance_threshold,\n            with_metadata=return_metadata,\n            with_distance=False,\n        )\n        # Perform vector search\n        # ignore type because redis-py is wrong about bytes\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-20", "text": "# ignore type because redis-py is wrong about bytes\n        try:\n            results = self.client.ft(self.index_name).search(redis_query, params_dict)  # type: ignore  # noqa: E501\n        except redis.exceptions.ResponseError as e:\n            # split error message and see if it starts with \"Syntax\"\n            if str(e).split(\" \")[0] == \"Syntax\":\n                raise ValueError(\n                    \"Query failed with syntax error. \"\n                    + \"This is likely due to malformation of \"\n                    + \"filter, vector, or query argument\"\n                ) from e\n            raise e\n        # Prepare document results\n        docs = []\n        for result in results.docs:\n            metadata = {}\n            if return_metadata:\n                metadata = {\"id\": result.id}\n                metadata.update(self._collect_metadata(result))\n            content_key = self._schema.content_key\n            docs.append(\n                Document(page_content=getattr(result, content_key), metadata=metadata)\n            )\n        return docs\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        filter: Optional[RedisFilterExpression] = None,\n        return_metadata: bool = True,\n        distance_threshold: Optional[float] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n            among selected documents.\n        Args:\n            query (str): Text to look up documents similar to.\n            k (int): Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-21", "text": "k (int): Number of Documents to return. Defaults to 4.\n            fetch_k (int): Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult (float): Number between 0 and 1 that determines the degree\n                of diversity among the results with 0 corresponding\n                to maximum diversity and 1 to minimum diversity.\n                Defaults to 0.5.\n            filter (RedisFilterExpression, optional): Optional metadata filter.\n                Defaults to None.\n            return_metadata (bool, optional): Whether to return metadata.\n                Defaults to True.\n            distance_threshold (Optional[float], optional): Maximum vector distance\n                between selected documents and the query vector. Defaults to None.\n        Returns:\n            List[Document]: A list of Documents selected by maximal marginal relevance.\n        \"\"\"\n        # Embed the query\n        query_embedding = self._embeddings.embed_query(query)\n        # Fetch the initial documents\n        prefetch_docs = self.similarity_search_by_vector(\n            query_embedding,\n            k=fetch_k,\n            filter=filter,\n            return_metadata=return_metadata,\n            distance_threshold=distance_threshold,\n            **kwargs,\n        )\n        prefetch_ids = [doc.metadata[\"id\"] for doc in prefetch_docs]\n        # Get the embeddings for the fetched documents\n        prefetch_embeddings = [\n            _buffer_to_array(\n                cast(\n                    bytes,\n                    self.client.hget(prefetch_id, self._schema.content_vector_key),\n                ),\n                dtype=self._schema.vector_dtype,\n            )\n            for prefetch_id in prefetch_ids\n        ]\n        # Select documents using maximal marginal relevance\n        selected_indices = maximal_marginal_relevance(\n            np.array(query_embedding), prefetch_embeddings, lambda_mult=lambda_mult, k=k\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-22", "text": "np.array(query_embedding), prefetch_embeddings, lambda_mult=lambda_mult, k=k\n        )\n        selected_docs = [prefetch_docs[i] for i in selected_indices]\n        return selected_docs\n    def _collect_metadata(self, result: \"Document\") -> Dict[str, Any]:\n        \"\"\"Collect metadata from Redis.\n        Method ensures that there isn't a mismatch between the metadata\n        and the index schema passed to this class by the user or generated\n        by this class.\n        Args:\n            result (Document): redis.commands.search.Document object returned\n                from Redis.\n        Returns:\n            Dict[str, Any]: Collected metadata.\n        \"\"\"\n        # new metadata dict as modified by this method\n        meta = {}\n        for key in self._schema.metadata_keys:\n            try:\n                meta[key] = getattr(result, key)\n            except AttributeError:\n                # warning about attribute missing\n                logger.warning(\n                    f\"Metadata key {key} not found in metadata. \"\n                    + \"Setting to None. \\n\"\n                    + \"Metadata fields defined for this instance: \"\n                    + f\"{self._schema.metadata_keys}\"\n                )\n                meta[key] = None\n        return meta\n    def _prepare_query(\n        self,\n        query_embedding: List[float],\n        k: int = 4,\n        filter: Optional[RedisFilterExpression] = None,\n        distance_threshold: Optional[float] = None,\n        with_metadata: bool = True,\n        with_distance: bool = False,\n    ) -> Tuple[\"Query\", Dict[str, Any]]:\n        # Creates Redis query\n        params_dict: Dict[str, Union[str, bytes, float]] = {\n            \"vector\": _array_to_buffer(query_embedding, self._schema.vector_dtype),\n        }\n        # prepare return fields including score", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-23", "text": "}\n        # prepare return fields including score\n        return_fields = [self._schema.content_key]\n        if with_distance:\n            return_fields.append(\"distance\")\n        if with_metadata:\n            return_fields.extend(self._schema.metadata_keys)\n        if distance_threshold:\n            params_dict[\"distance_threshold\"] = distance_threshold\n            return (\n                self._prepare_range_query(\n                    k, filter=filter, return_fields=return_fields\n                ),\n                params_dict,\n            )\n        return (\n            self._prepare_vector_query(k, filter=filter, return_fields=return_fields),\n            params_dict,\n        )\n    def _prepare_range_query(\n        self,\n        k: int,\n        filter: Optional[RedisFilterExpression] = None,\n        return_fields: Optional[List[str]] = None,\n    ) -> \"Query\":\n        try:\n            from redis.commands.search.query import Query\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import redis python package. \"\n                \"Please install it with `pip install redis`.\"\n            ) from e\n        return_fields = return_fields or []\n        vector_key = self._schema.content_vector_key\n        base_query = f\"@{vector_key}:[VECTOR_RANGE $distance_threshold $vector]\"\n        if filter:\n            base_query = \"(\" + base_query + \" \" + str(filter) + \")\"\n        query_string = base_query + \"=>{$yield_distance_as: distance}\"\n        return (\n            Query(query_string)\n            .return_fields(*return_fields)\n            .sort_by(\"distance\")\n            .paging(0, k)\n            .dialect(2)\n        )\n    def _prepare_vector_query(\n        self,\n        k: int,\n        filter: Optional[RedisFilterExpression] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-24", "text": "k: int,\n        filter: Optional[RedisFilterExpression] = None,\n        return_fields: Optional[List[str]] = None,\n    ) -> \"Query\":\n        \"\"\"Prepare query for vector search.\n        Args:\n            k: Number of results to return.\n            filter: Optional metadata filter.\n        Returns:\n            query: Query object.\n        \"\"\"\n        try:\n            from redis.commands.search.query import Query\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import redis python package. \"\n                \"Please install it with `pip install redis`.\"\n            ) from e\n        return_fields = return_fields or []\n        query_prefix = \"*\"\n        if filter:\n            query_prefix = f\"{str(filter)}\"\n        vector_key = self._schema.content_vector_key\n        base_query = f\"({query_prefix})=>[KNN {k} @{vector_key} $vector AS distance]\"\n        query = (\n            Query(base_query)\n            .return_fields(*return_fields)\n            .sort_by(\"distance\")\n            .paging(0, k)\n            .dialect(2)\n        )\n        return query\n    def _get_schema_with_defaults(\n        self,\n        index_schema: Optional[Union[Dict[str, str], str, os.PathLike]] = None,\n        vector_schema: Optional[Dict[str, Union[str, int]]] = None,\n    ) -> \"RedisModel\":\n        # should only be called after init of Redis (so Import handled)\n        from langchain.vectorstores.redis.schema import RedisModel, read_schema\n        schema = RedisModel()\n        # read in schema (yaml file or dict) and\n        # pass to the Pydantic validators\n        if index_schema:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-25", "text": "# pass to the Pydantic validators\n        if index_schema:\n            schema_values = read_schema(index_schema)  # type: ignore\n            schema = RedisModel(**schema_values)\n            # ensure user did not exclude the content field\n            # no modifications if content field found\n            schema.add_content_field()\n        # if no content_vector field, add vector field to schema\n        # this makes adding a vector field to the schema optional when\n        # the user just wants additional metadata\n        try:\n            # see if user overrode the content vector\n            schema.content_vector\n            # if user overrode the content vector, check if they\n            # also passed vector schema. This won't be used since\n            # the index schema overrode the content vector\n            if vector_schema:\n                logger.warning(\n                    \"`vector_schema` is ignored since content_vector is \"\n                    + \"overridden in `index_schema`.\"\n                )\n        # user did not override content vector\n        except ValueError:\n            # set default vector schema and update with user provided schema\n            # if the user provided any\n            vector_field = self.DEFAULT_VECTOR_SCHEMA.copy()\n            if vector_schema:\n                vector_field.update(vector_schema)\n            # add the vector field either way\n            schema.add_vector_field(vector_field)\n        return schema\n    def _create_index_if_not_exist(self, dim: int = 1536) -> None:\n        try:\n            from redis.commands.search.indexDefinition import (  # type: ignore\n                IndexDefinition,\n                IndexType,\n            )\n        except ImportError:\n            raise ImportError(\n                \"Could not import redis python package. \"\n                \"Please install it with `pip install redis`.\"\n            )\n        # Set vector dimension\n        # can't obtain beforehand because we don't", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-26", "text": ")\n        # Set vector dimension\n        # can't obtain beforehand because we don't\n        # know which embedding model is being used.\n        self._schema.content_vector.dims = dim\n        # Check if index exists\n        if not check_index_exists(self.client, self.index_name):\n            # Create Redis Index\n            self.client.ft(self.index_name).create_index(\n                fields=self._schema.get_fields(),\n                definition=IndexDefinition(\n                    prefix=[self.key_prefix], index_type=IndexType.HASH\n                ),\n            )\n    def _calculate_fp_distance(self, distance: str) -> float:\n        \"\"\"Calculate the distance based on the vector datatype\n        Two datatypes supported:\n        - FLOAT32\n        - FLOAT64\n        if it's FLOAT32, we need to round the distance to 4 decimal places\n        otherwise, round to 7 decimal places.\n        \"\"\"\n        if self._schema.content_vector.datatype == \"FLOAT32\":\n            return round(float(distance), 4)\n        return round(float(distance), 7)\n    def _check_deprecated_kwargs(self, kwargs: Mapping[str, Any]) -> None:\n        \"\"\"Check for deprecated kwargs.\"\"\"\n        deprecated_kwargs = {\n            \"redis_host\": \"redis_url\",\n            \"redis_port\": \"redis_url\",\n            \"redis_password\": \"redis_url\",\n            \"content_key\": \"index_schema\",\n            \"vector_key\": \"vector_schema\",\n            \"distance_metric\": \"vector_schema\",\n        }\n        for key, value in kwargs.items():\n            if key in deprecated_kwargs:\n                raise ValueError(\n                    f\"Keyword argument '{key}' is deprecated. \"\n                    f\"Please use '{deprecated_kwargs[key]}' instead.\"\n                )\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-27", "text": "def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        if self.relevance_score_fn:\n            return self.relevance_score_fn\n        metric_map = {\n            \"COSINE\": self._cosine_relevance_score_fn,\n            \"IP\": self._max_inner_product_relevance_score_fn,\n            \"L2\": self._euclidean_relevance_score_fn,\n        }\n        try:\n            return metric_map[self._schema.content_vector.distance_metric]\n        except KeyError:\n            return _default_relevance_score\ndef _generate_field_schema(data: Dict[str, Any]) -> Dict[str, Any]:\n    \"\"\"\n    Generate a schema for the search index in Redis based on the input metadata.\n    Given a dictionary of metadata, this function categorizes each metadata\n        field into one of the three categories:\n    - text: The field contains textual data.\n    - numeric: The field contains numeric data (either integer or float).\n    - tag: The field contains list of tags (strings).\n    Args\n        data (Dict[str, Any]): A dictionary where keys are metadata field names\n            and values are the metadata values.\n    Returns:\n        Dict[str, Any]: A dictionary with three keys \"text\", \"numeric\", and \"tag\".\n            Each key maps to a list of fields that belong to that category.\n    Raises:\n        ValueError: If a metadata field cannot be categorized into any of\n            the three known types.\n    \"\"\"\n    result: Dict[str, Any] = {\n        \"text\": [],\n        \"numeric\": [],\n        \"tag\": [],\n    }\n    for key, value in data.items():\n        # Numeric fields\n        try:\n            int(value)\n            result[\"numeric\"].append({\"name\": key})\n            continue", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-28", "text": "int(value)\n            result[\"numeric\"].append({\"name\": key})\n            continue\n        except (ValueError, TypeError):\n            pass\n        # None values are not indexed as of now\n        if value is None:\n            continue\n        # if it's a list of strings, we assume it's a tag\n        if isinstance(value, (list, tuple)):\n            if not value or isinstance(value[0], str):\n                result[\"tag\"].append({\"name\": key})\n            else:\n                name = type(value[0]).__name__\n                raise ValueError(\n                    f\"List/tuple values should contain strings: '{key}': {name}\"\n                )\n            continue\n        # Check if value is string before processing further\n        if isinstance(value, str):\n            result[\"text\"].append({\"name\": key})\n            continue\n        # Unable to classify the field value\n        name = type(value).__name__\n        raise ValueError(\n            \"Could not generate Redis index field type mapping \"\n            + f\"for metadata: '{key}': {name}\"\n        )\n    return result\ndef _prepare_metadata(metadata: Dict[str, Any]) -> Dict[str, Any]:\n    \"\"\"\n    Prepare metadata for indexing in Redis by sanitizing its values.\n    - String, integer, and float values remain unchanged.\n    - None or empty values are replaced with empty strings.\n    - Lists/tuples of strings are joined into a single string with a comma separator.\n    Args:\n        metadata (Dict[str, Any]): A dictionary where keys are metadata\n            field names and values are the metadata values.\n    Returns:\n        Dict[str, Any]: A sanitized dictionary ready for indexing in Redis.\n    Raises:\n        ValueError: If any metadata value is not one of the known", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-29", "text": "Raises:\n        ValueError: If any metadata value is not one of the known\n            types (string, int, float, or list of strings).\n    \"\"\"\n    def raise_error(key: str, value: Any) -> None:\n        raise ValueError(\n            f\"Metadata value for key '{key}' must be a string, int, \"\n            + f\"float, or list of strings. Got {type(value).__name__}\"\n        )\n    clean_meta: Dict[str, Union[str, float, int]] = {}\n    for key, value in metadata.items():\n        if not value:\n            clean_meta[key] = \"\"\n            continue\n        # No transformation needed\n        if isinstance(value, (str, int, float)):\n            clean_meta[key] = value\n        # if it's a list/tuple of strings, we join it\n        elif isinstance(value, (list, tuple)):\n            if not value or isinstance(value[0], str):\n                clean_meta[key] = REDIS_TAG_SEPARATOR.join(value)\n            else:\n                raise_error(key, value)\n        else:\n            raise_error(key, value)\n    return clean_meta\n[docs]class RedisVectorStoreRetriever(VectorStoreRetriever):\n    \"\"\"Retriever for Redis VectorStore.\"\"\"\n    vectorstore: Redis\n    \"\"\"Redis VectorStore.\"\"\"\n    search_type: str = \"similarity\"\n    \"\"\"Type of search to perform. Can be either\n    'similarity',\n    'similarity_distance_threshold',\n    'similarity_score_threshold'\n    \"\"\"\n    search_kwargs: Dict[str, Any] = {\n        \"k\": 4,\n        \"score_threshold\": 0.9,\n        # set to None to avoid distance used in score_threshold search\n        \"distance_threshold\": None,\n    }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-30", "text": "\"distance_threshold\": None,\n    }\n    \"\"\"Default search kwargs.\"\"\"\n    allowed_search_types = [\n        \"similarity\",\n        \"similarity_distance_threshold\",\n        \"similarity_score_threshold\",\n        \"mmr\",\n    ]\n    \"\"\"Allowed search types.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        if self.search_type == \"similarity\":\n            docs = self.vectorstore.similarity_search(query, **self.search_kwargs)\n        elif self.search_type == \"similarity_distance_threshold\":\n            if self.search_kwargs[\"distance_threshold\"] is None:\n                raise ValueError(\n                    \"distance_threshold must be provided for \"\n                    + \"similarity_distance_threshold retriever\"\n                )\n            docs = self.vectorstore.similarity_search(query, **self.search_kwargs)\n        elif self.search_type == \"similarity_score_threshold\":\n            docs_and_similarities = (\n                self.vectorstore.similarity_search_with_relevance_scores(\n                    query, **self.search_kwargs\n                )\n            )\n            docs = [doc for doc, _ in docs_and_similarities]\n        elif self.search_type == \"mmr\":\n            docs = self.vectorstore.max_marginal_relevance_search(\n                query, **self.search_kwargs\n            )\n        else:\n            raise ValueError(f\"search_type of {self.search_type} not allowed.\")\n        return docs\n[docs]    def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]:\n        \"\"\"Add documents to vectorstore.\"\"\"\n        return self.vectorstore.add_documents(documents, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "dc70e738e6bd-31", "text": "return self.vectorstore.add_documents(documents, **kwargs)\n[docs]    async def aadd_documents(\n        self, documents: List[Document], **kwargs: Any\n    ) -> List[str]:\n        \"\"\"Add documents to vectorstore.\"\"\"\n        return await self.vectorstore.aadd_documents(documents, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html"}
{"id": "55ba1c957158-0", "text": "Source code for langchain.vectorstores.redis.filters\nfrom enum import Enum\nfrom functools import wraps\nfrom numbers import Number\nfrom typing import Any, Callable, Dict, List, Optional, Union\nfrom langchain.utilities.redis import TokenEscaper\n# disable mypy error for dunder method overrides\n# mypy: disable-error-code=\"override\"\n[docs]class RedisFilterOperator(Enum):\n    \"\"\"RedisFilterOperator enumerator is used to create RedisFilterExpressions.\"\"\"\n    EQ = 1\n    NE = 2\n    LT = 3\n    GT = 4\n    LE = 5\n    GE = 6\n    OR = 7\n    AND = 8\n    LIKE = 9\n    IN = 10\n[docs]class RedisFilter:\n    \"\"\"Collection of RedisFilterFields.\"\"\"\n[docs]    @staticmethod\n    def text(field: str) -> \"RedisText\":\n        return RedisText(field)\n[docs]    @staticmethod\n    def num(field: str) -> \"RedisNum\":\n        return RedisNum(field)\n[docs]    @staticmethod\n    def tag(field: str) -> \"RedisTag\":\n        return RedisTag(field)\n[docs]class RedisFilterField:\n    \"\"\"Base class for RedisFilterFields.\"\"\"\n    escaper: \"TokenEscaper\" = TokenEscaper()\n    OPERATORS: Dict[RedisFilterOperator, str] = {}\n[docs]    def __init__(self, field: str):\n        self._field = field\n        self._value: Any = None\n        self._operator: RedisFilterOperator = RedisFilterOperator.EQ\n[docs]    def equals(self, other: \"RedisFilterField\") -> bool:\n        if not isinstance(other, type(self)):\n            return False\n        return self._field == other._field and self._value == other._value", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html"}
{"id": "55ba1c957158-1", "text": "return self._field == other._field and self._value == other._value\n    def _set_value(\n        self, val: Any, val_type: type, operator: RedisFilterOperator\n    ) -> None:\n        # check that the operator is supported by this class\n        if operator not in self.OPERATORS:\n            raise ValueError(\n                f\"Operator {operator} not supported by {self.__class__.__name__}. \"\n                + f\"Supported operators are {self.OPERATORS.values()}.\"\n            )\n        if not isinstance(val, val_type):\n            raise TypeError(\n                f\"Right side argument passed to operator {self.OPERATORS[operator]} \"\n                f\"with left side \"\n                f\"argument {self.__class__.__name__} must be of type {val_type}, \"\n                f\"received value {val}\"\n            )\n        self._value = val\n        self._operator = operator\n[docs]def check_operator_misuse(func: Callable) -> Callable:\n    \"\"\"Decorator to check for misuse of equality operators.\"\"\"\n    @wraps(func)\n    def wrapper(instance: Any, *args: Any, **kwargs: Any) -> Any:\n        # Extracting 'other' from positional arguments or keyword arguments\n        other = kwargs.get(\"other\") if \"other\" in kwargs else None\n        if not other:\n            for arg in args:\n                if isinstance(arg, type(instance)):\n                    other = arg\n                    break\n        if isinstance(other, type(instance)):\n            raise ValueError(\n                \"Equality operators are overridden for FilterExpression creation. Use \"\n                \".equals() for equality checks\"\n            )\n        return func(instance, *args, **kwargs)\n    return wrapper\n[docs]class RedisTag(RedisFilterField):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html"}
{"id": "55ba1c957158-2", "text": "return wrapper\n[docs]class RedisTag(RedisFilterField):\n    \"\"\"A RedisFilterField representing a tag in a Redis index.\"\"\"\n    OPERATORS: Dict[RedisFilterOperator, str] = {\n        RedisFilterOperator.EQ: \"==\",\n        RedisFilterOperator.NE: \"!=\",\n        RedisFilterOperator.IN: \"==\",\n    }\n    OPERATOR_MAP: Dict[RedisFilterOperator, str] = {\n        RedisFilterOperator.EQ: \"@%s:{%s}\",\n        RedisFilterOperator.NE: \"(-@%s:{%s})\",\n        RedisFilterOperator.IN: \"@%s:{%s}\",\n    }\n[docs]    def __init__(self, field: str):\n        \"\"\"Create a RedisTag FilterField\n        Args:\n            field (str): The name of the RedisTag field in the index to be queried\n                against.\n        \"\"\"\n        super().__init__(field)\n    def _set_tag_value(\n        self, other: Union[List[str], str], operator: RedisFilterOperator\n    ) -> None:\n        if isinstance(other, list):\n            if not all(isinstance(tag, str) for tag in other):\n                raise ValueError(\"All tags must be strings\")\n        else:\n            other = [other]\n        self._set_value(other, list, operator)\n    @check_operator_misuse\n    def __eq__(self, other: Union[List[str], str]) -> \"RedisFilterExpression\":\n        \"\"\"Create a RedisTag equality filter expression\n        Args:\n            other (Union[List[str], str]): The tag(s) to filter on.\n        Example:\n            >>> from langchain.vectorstores.redis import RedisTag\n            >>> filter = RedisTag(\"brand\") == \"nike\"\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html"}
{"id": "55ba1c957158-3", "text": ">>> filter = RedisTag(\"brand\") == \"nike\"\n        \"\"\"\n        self._set_tag_value(other, RedisFilterOperator.EQ)\n        return RedisFilterExpression(str(self))\n    @check_operator_misuse\n    def __ne__(self, other: Union[List[str], str]) -> \"RedisFilterExpression\":\n        \"\"\"Create a RedisTag inequality filter expression\n        Args:\n            other (Union[List[str], str]): The tag(s) to filter on.\n        Example:\n            >>> from langchain.vectorstores.redis import RedisTag\n            >>> filter = RedisTag(\"brand\") != \"nike\"\n        \"\"\"\n        self._set_tag_value(other, RedisFilterOperator.NE)\n        return RedisFilterExpression(str(self))\n    @property\n    def _formatted_tag_value(self) -> str:\n        return \"|\".join([self.escaper.escape(tag) for tag in self._value])\n    def __str__(self) -> str:\n        if not self._value:\n            raise ValueError(\n                f\"Operator must be used before calling __str__. Operators are \"\n                f\"{self.OPERATORS.values()}\"\n            )\n        \"\"\"Return the Redis Query syntax for a RedisTag filter expression\"\"\"\n        return self.OPERATOR_MAP[self._operator] % (\n            self._field,\n            self._formatted_tag_value,\n        )\n[docs]class RedisNum(RedisFilterField):\n    \"\"\"A RedisFilterField representing a numeric field in a Redis index.\"\"\"\n    OPERATORS: Dict[RedisFilterOperator, str] = {\n        RedisFilterOperator.EQ: \"==\",\n        RedisFilterOperator.NE: \"!=\",\n        RedisFilterOperator.LT: \"<\",\n        RedisFilterOperator.GT: \">\",\n        RedisFilterOperator.LE: \"<=\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html"}
{"id": "55ba1c957158-4", "text": "RedisFilterOperator.GT: \">\",\n        RedisFilterOperator.LE: \"<=\",\n        RedisFilterOperator.GE: \">=\",\n    }\n    OPERATOR_MAP: Dict[RedisFilterOperator, str] = {\n        RedisFilterOperator.EQ: \"@%s:[%f %f]\",\n        RedisFilterOperator.NE: \"(-@%s:[%f %f])\",\n        RedisFilterOperator.GT: \"@%s:[(%f +inf]\",\n        RedisFilterOperator.LT: \"@%s:[-inf (%f]\",\n        RedisFilterOperator.GE: \"@%s:[%f +inf]\",\n        RedisFilterOperator.LE: \"@%s:[-inf %f]\",\n    }\n    def __str__(self) -> str:\n        \"\"\"Return the Redis Query syntax for a Numeric filter expression\"\"\"\n        if not self._value:\n            raise ValueError(\n                f\"Operator must be used before calling __str__. Operators are \"\n                f\"{self.OPERATORS.values()}\"\n            )\n        if (\n            self._operator == RedisFilterOperator.EQ\n            or self._operator == RedisFilterOperator.NE\n        ):\n            return self.OPERATOR_MAP[self._operator] % (\n                self._field,\n                self._value,\n                self._value,\n            )\n        else:\n            return self.OPERATOR_MAP[self._operator] % (self._field, self._value)\n    @check_operator_misuse\n    def __eq__(self, other: Union[int, float]) -> \"RedisFilterExpression\":\n        \"\"\"Create a Numeric equality filter expression\n        Args:\n            other (Number): The value to filter on.\n        Example:\n            >>> from langchain.vectorstores.redis import RedisNum\n            >>> filter = RedisNum(\"zipcode\") == 90210", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html"}
{"id": "55ba1c957158-5", "text": ">>> filter = RedisNum(\"zipcode\") == 90210\n        \"\"\"\n        self._set_value(other, Number, RedisFilterOperator.EQ)\n        return RedisFilterExpression(str(self))\n    @check_operator_misuse\n    def __ne__(self, other: Union[int, float]) -> \"RedisFilterExpression\":\n        \"\"\"Create a Numeric inequality filter expression\n        Args:\n            other (Number): The value to filter on.\n        Example:\n            >>> from langchain.vectorstores.redis import RedisNum\n            >>> filter = RedisNum(\"zipcode\") != 90210\n        \"\"\"\n        self._set_value(other, Number, RedisFilterOperator.NE)\n        return RedisFilterExpression(str(self))\n    def __gt__(self, other: Union[int, float]) -> \"RedisFilterExpression\":\n        \"\"\"Create a RedisNumeric greater than filter expression\n        Args:\n            other (Number): The value to filter on.\n        Example:\n            >>> from langchain.vectorstores.redis import RedisNum\n            >>> filter = RedisNum(\"age\") > 18\n        \"\"\"\n        self._set_value(other, Number, RedisFilterOperator.GT)\n        return RedisFilterExpression(str(self))\n    def __lt__(self, other: Union[int, float]) -> \"RedisFilterExpression\":\n        \"\"\"Create a Numeric less than filter expression\n        Args:\n            other (Number): The value to filter on.\n        Example:\n            >>> from langchain.vectorstores.redis import RedisNum\n            >>> filter = RedisNum(\"age\") < 18\n        \"\"\"\n        self._set_value(other, Number, RedisFilterOperator.LT)\n        return RedisFilterExpression(str(self))\n    def __ge__(self, other: Union[int, float]) -> \"RedisFilterExpression\":\n        \"\"\"Create a Numeric greater than or equal to filter expression", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html"}
{"id": "55ba1c957158-6", "text": "\"\"\"Create a Numeric greater than or equal to filter expression\n        Args:\n            other (Number): The value to filter on.\n        Example:\n            >>> from langchain.vectorstores.redis import RedisNum\n            >>> filter = RedisNum(\"age\") >= 18\n        \"\"\"\n        self._set_value(other, Number, RedisFilterOperator.GE)\n        return RedisFilterExpression(str(self))\n    def __le__(self, other: Union[int, float]) -> \"RedisFilterExpression\":\n        \"\"\"Create a Numeric less than or equal to filter expression\n        Args:\n            other (Number): The value to filter on.\n        Example:\n            >>> from langchain.vectorstores.redis import RedisNum\n            >>> filter = RedisNum(\"age\") <= 18\n        \"\"\"\n        self._set_value(other, Number, RedisFilterOperator.LE)\n        return RedisFilterExpression(str(self))\n[docs]class RedisText(RedisFilterField):\n    \"\"\"A RedisFilterField representing a text field in a Redis index.\"\"\"\n    OPERATORS = {\n        RedisFilterOperator.EQ: \"==\",\n        RedisFilterOperator.NE: \"!=\",\n        RedisFilterOperator.LIKE: \"%\",\n    }\n    OPERATOR_MAP = {\n        RedisFilterOperator.EQ: '@%s:\"%s\"',\n        RedisFilterOperator.NE: '(-@%s:\"%s\")',\n        RedisFilterOperator.LIKE: \"@%s:%s\",\n    }\n    @check_operator_misuse\n    def __eq__(self, other: str) -> \"RedisFilterExpression\":\n        \"\"\"Create a RedisText equality filter expression\n        Args:\n            other (str): The text value to filter on.\n        Example:\n            >>> from langchain.vectorstores.redis import RedisText\n            >>> filter = RedisText(\"job\") == \"engineer\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html"}
{"id": "55ba1c957158-7", "text": ">>> filter = RedisText(\"job\") == \"engineer\"\n        \"\"\"\n        self._set_value(other, str, RedisFilterOperator.EQ)\n        return RedisFilterExpression(str(self))\n    @check_operator_misuse\n    def __ne__(self, other: str) -> \"RedisFilterExpression\":\n        \"\"\"Create a RedisText inequality filter expression\n        Args:\n            other (str): The text value to filter on.\n        Example:\n            >>> from langchain.vectorstores.redis import RedisText\n            >>> filter = RedisText(\"job\") != \"engineer\"\n        \"\"\"\n        self._set_value(other, str, RedisFilterOperator.NE)\n        return RedisFilterExpression(str(self))\n    def __mod__(self, other: str) -> \"RedisFilterExpression\":\n        \"\"\"Create a RedisText like filter expression\n        Args:\n            other (str): The text value to filter on.\n        Example:\n            >>> from langchain.vectorstores.redis import RedisText\n            >>> filter = RedisText(\"job\") % \"engineer\"\n        \"\"\"\n        self._set_value(other, str, RedisFilterOperator.LIKE)\n        return RedisFilterExpression(str(self))\n    def __str__(self) -> str:\n        if not self._value:\n            raise ValueError(\n                f\"Operator must be used before calling __str__. Operators are \"\n                f\"{self.OPERATORS.values()}\"\n            )\n        try:\n            return self.OPERATOR_MAP[self._operator] % (self._field, self._value)\n        except KeyError:\n            raise Exception(\"Invalid operator\")\n[docs]class RedisFilterExpression:\n    \"\"\"A logical expression of RedisFilterFields.\n    RedisFilterExpressions can be combined using the & and | operators to create", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html"}
{"id": "55ba1c957158-8", "text": "RedisFilterExpressions can be combined using the & and | operators to create\n    complex logical expressions that evaluate to the Redis Query language.\n    This presents an interface by which users can create complex queries\n    without having to know the Redis Query language.\n    Filter expressions are not initialized directly. Instead they are built\n    by combining RedisFilterFields using the & and | operators.\n    Examples:\n        >>> from langchain.vectorstores.redis import RedisTag, RedisNum\n        >>> brand_is_nike = RedisTag(\"brand\") == \"nike\"\n        >>> price_is_under_100 = RedisNum(\"price\") < 100\n        >>> filter = brand_is_nike & price_is_under_100\n        >>> print(str(filter))\n        (@brand:{nike} @price:[-inf (100)])\n    \"\"\"\n[docs]    def __init__(\n        self,\n        _filter: Optional[str] = None,\n        operator: Optional[RedisFilterOperator] = None,\n        left: Optional[\"RedisFilterExpression\"] = None,\n        right: Optional[\"RedisFilterExpression\"] = None,\n    ):\n        self._filter = _filter\n        self._operator = operator\n        self._left = left\n        self._right = right\n    def __and__(self, other: \"RedisFilterExpression\") -> \"RedisFilterExpression\":\n        return RedisFilterExpression(\n            operator=RedisFilterOperator.AND, left=self, right=other\n        )\n    def __or__(self, other: \"RedisFilterExpression\") -> \"RedisFilterExpression\":\n        return RedisFilterExpression(\n            operator=RedisFilterOperator.OR, left=self, right=other\n        )\n    def __str__(self) -> str:\n        # top level check that allows recursive calls to __str__", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html"}
{"id": "55ba1c957158-9", "text": "# top level check that allows recursive calls to __str__\n        if not self._filter and not self._operator:\n            raise ValueError(\"Improperly initialized RedisFilterExpression\")\n        # allow for single filter expression without operators as last\n        # expression in the chain might not have an operator\n        if self._operator:\n            operator_str = \" | \" if self._operator == RedisFilterOperator.OR else \" \"\n            return f\"({str(self._left)}{operator_str}{str(self._right)})\"\n        # check that base case, the filter is set\n        if not self._filter:\n            raise ValueError(\"Improperly initialized RedisFilterExpression\")\n        return self._filter", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/filters.html"}
{"id": "2be7e00a2b88-0", "text": "Source code for langchain.agents.agent_types\n\"\"\"Module definitions of agent types together with corresponding agents.\"\"\"\nfrom enum import Enum\n[docs]class AgentType(str, Enum):\n    \"\"\"An enum for agent types.\n    See documentation: https://python.langchain.com/docs/modules/agents/agent_types/\n    \"\"\"\n    ZERO_SHOT_REACT_DESCRIPTION = \"zero-shot-react-description\"\n    \"\"\"A zero shot agent that does a reasoning step before acting.\"\"\"\n    REACT_DOCSTORE = \"react-docstore\"\n    \"\"\"A zero shot agent that does a reasoning step before acting.\n    \n    This agent has access to a document store that allows it to look up \n    relevant information to answering the question.\n    \"\"\"\n    SELF_ASK_WITH_SEARCH = \"self-ask-with-search\"\n    \"\"\"An agent that breaks down a complex question into a series of simpler questions.\n    \n    This agent uses a search tool to look up answers to the simpler questions\n    in order to answer the original complex question.\n    \"\"\"\n    CONVERSATIONAL_REACT_DESCRIPTION = \"conversational-react-description\"\n    CHAT_ZERO_SHOT_REACT_DESCRIPTION = \"chat-zero-shot-react-description\"\n    \"\"\"A zero shot agent that does a reasoning step before acting.\n    \n    This agent is designed to be used in conjunction \n    \"\"\"\n    CHAT_CONVERSATIONAL_REACT_DESCRIPTION = \"chat-conversational-react-description\"\n    STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION = (\n        \"structured-chat-zero-shot-react-description\"\n    )\n    \"\"\"An zero-shot react agent optimized for chat models.\n    \n    This agent is capable of invoking tools that have multiple inputs.\n    \"\"\"\n    OPENAI_FUNCTIONS = \"openai-functions\"\n    \"\"\"An agent optimized for using open AI functions.\"\"\"\n    OPENAI_MULTI_FUNCTIONS = \"openai-multi-functions\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_types.html"}
{"id": "bed605727000-0", "text": "Source code for langchain.agents.agent\n\"\"\"Chain that takes in an input and produces an action and action input.\"\"\"\nfrom __future__ import annotations\nimport asyncio\nimport json\nimport logging\nimport time\nfrom abc import abstractmethod\nfrom pathlib import Path\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n)\nimport yaml\nfrom langchain.agents.agent_iterator import AgentExecutorIterator\nfrom langchain.agents.agent_types import AgentType\nfrom langchain.agents.tools import InvalidTool\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForChainRun,\n    CallbackManagerForToolRun,\n    Callbacks,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts.few_shot import FewShotPromptTemplate\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema import (\n    AgentAction,\n    AgentFinish,\n    BaseOutputParser,\n    BasePromptTemplate,\n    OutputParserException,\n)\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import BaseMessage\nfrom langchain.schema.runnable import Runnable\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.asyncio import asyncio_timeout\nfrom langchain.utils.input import get_color_mapping\nlogger = logging.getLogger(__name__)\n[docs]class BaseSingleActionAgent(BaseModel):\n    \"\"\"Base Single Action Agent class.\"\"\"\n    @property\n    def return_values(self) -> List[str]:\n        \"\"\"Return values of the agent.\"\"\"\n        return [\"output\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-1", "text": "\"\"\"Return values of the agent.\"\"\"\n        return [\"output\"]\n[docs]    def get_allowed_tools(self) -> Optional[List[str]]:\n        return None\n[docs]    @abstractmethod\n    def plan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[AgentAction, AgentFinish]:\n        \"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with observations\n            callbacks: Callbacks to run.\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.\n        \"\"\"\n[docs]    @abstractmethod\n    async def aplan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[AgentAction, AgentFinish]:\n        \"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with observations\n            callbacks: Callbacks to run.\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.\n        \"\"\"\n    @property\n    @abstractmethod\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys.\n        :meta private:\n        \"\"\"\n[docs]    def return_stopped_response(\n        self,\n        early_stopping_method: str,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        **kwargs: Any,\n    ) -> AgentFinish:\n        \"\"\"Return response when agent has been stopped due to max iterations.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-2", "text": "\"\"\"Return response when agent has been stopped due to max iterations.\"\"\"\n        if early_stopping_method == \"force\":\n            # `force` just returns a constant string\n            return AgentFinish(\n                {\"output\": \"Agent stopped due to iteration limit or time limit.\"}, \"\"\n            )\n        else:\n            raise ValueError(\n                f\"Got unsupported early_stopping_method `{early_stopping_method}`\"\n            )\n[docs]    @classmethod\n    def from_llm_and_tools(\n        cls,\n        llm: BaseLanguageModel,\n        tools: Sequence[BaseTool],\n        callback_manager: Optional[BaseCallbackManager] = None,\n        **kwargs: Any,\n    ) -> BaseSingleActionAgent:\n        raise NotImplementedError\n    @property\n    def _agent_type(self) -> str:\n        \"\"\"Return Identifier of agent type.\"\"\"\n        raise NotImplementedError\n[docs]    def dict(self, **kwargs: Any) -> Dict:\n        \"\"\"Return dictionary representation of agent.\"\"\"\n        _dict = super().dict()\n        try:\n            _type = self._agent_type\n        except NotImplementedError:\n            _type = None\n        if isinstance(_type, AgentType):\n            _dict[\"_type\"] = str(_type.value)\n        elif _type is not None:\n            _dict[\"_type\"] = _type\n        return _dict\n[docs]    def save(self, file_path: Union[Path, str]) -> None:\n        \"\"\"Save the agent.\n        Args:\n            file_path: Path to file to save the agent to.\n        Example:\n        .. code-block:: python\n            # If working with agent executor\n            agent.agent.save(file_path=\"path/agent.yaml\")\n        \"\"\"\n        # Convert file to Path object.\n        if isinstance(file_path, str):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-3", "text": "# Convert file to Path object.\n        if isinstance(file_path, str):\n            save_path = Path(file_path)\n        else:\n            save_path = file_path\n        directory_path = save_path.parent\n        directory_path.mkdir(parents=True, exist_ok=True)\n        # Fetch dictionary to save\n        agent_dict = self.dict()\n        if \"_type\" not in agent_dict:\n            raise NotImplementedError(f\"Agent {self} does not support saving\")\n        if save_path.suffix == \".json\":\n            with open(file_path, \"w\") as f:\n                json.dump(agent_dict, f, indent=4)\n        elif save_path.suffix == \".yaml\":\n            with open(file_path, \"w\") as f:\n                yaml.dump(agent_dict, f, default_flow_style=False)\n        else:\n            raise ValueError(f\"{save_path} must be json or yaml\")\n[docs]    def tool_run_logging_kwargs(self) -> Dict:\n        return {}\n[docs]class BaseMultiActionAgent(BaseModel):\n    \"\"\"Base Multi Action Agent class.\"\"\"\n    @property\n    def return_values(self) -> List[str]:\n        \"\"\"Return values of the agent.\"\"\"\n        return [\"output\"]\n[docs]    def get_allowed_tools(self) -> Optional[List[str]]:\n        return None\n[docs]    @abstractmethod\n    def plan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[List[AgentAction], AgentFinish]:\n        \"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with the observations.\n            callbacks: Callbacks to run.\n            **kwargs: User inputs.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-4", "text": "callbacks: Callbacks to run.\n            **kwargs: User inputs.\n        Returns:\n            Actions specifying what tool to use.\n        \"\"\"\n[docs]    @abstractmethod\n    async def aplan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[List[AgentAction], AgentFinish]:\n        \"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with the observations.\n            callbacks: Callbacks to run.\n            **kwargs: User inputs.\n        Returns:\n            Actions specifying what tool to use.\n        \"\"\"\n    @property\n    @abstractmethod\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys.\n        :meta private:\n        \"\"\"\n[docs]    def return_stopped_response(\n        self,\n        early_stopping_method: str,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        **kwargs: Any,\n    ) -> AgentFinish:\n        \"\"\"Return response when agent has been stopped due to max iterations.\"\"\"\n        if early_stopping_method == \"force\":\n            # `force` just returns a constant string\n            return AgentFinish({\"output\": \"Agent stopped due to max iterations.\"}, \"\")\n        else:\n            raise ValueError(\n                f\"Got unsupported early_stopping_method `{early_stopping_method}`\"\n            )\n    @property\n    def _agent_type(self) -> str:\n        \"\"\"Return Identifier of agent type.\"\"\"\n        raise NotImplementedError\n[docs]    def dict(self, **kwargs: Any) -> Dict:\n        \"\"\"Return dictionary representation of agent.\"\"\"\n        _dict = super().dict()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-5", "text": "\"\"\"Return dictionary representation of agent.\"\"\"\n        _dict = super().dict()\n        try:\n            _dict[\"_type\"] = str(self._agent_type)\n        except NotImplementedError:\n            pass\n        return _dict\n[docs]    def save(self, file_path: Union[Path, str]) -> None:\n        \"\"\"Save the agent.\n        Args:\n            file_path: Path to file to save the agent to.\n        Example:\n        .. code-block:: python\n            # If working with agent executor\n            agent.agent.save(file_path=\"path/agent.yaml\")\n        \"\"\"\n        # Convert file to Path object.\n        if isinstance(file_path, str):\n            save_path = Path(file_path)\n        else:\n            save_path = file_path\n        # Fetch dictionary to save\n        agent_dict = self.dict()\n        if \"_type\" not in agent_dict:\n            raise NotImplementedError(f\"Agent {self} does not support saving.\")\n        directory_path = save_path.parent\n        directory_path.mkdir(parents=True, exist_ok=True)\n        if save_path.suffix == \".json\":\n            with open(file_path, \"w\") as f:\n                json.dump(agent_dict, f, indent=4)\n        elif save_path.suffix == \".yaml\":\n            with open(file_path, \"w\") as f:\n                yaml.dump(agent_dict, f, default_flow_style=False)\n        else:\n            raise ValueError(f\"{save_path} must be json or yaml\")\n[docs]    def tool_run_logging_kwargs(self) -> Dict:\n        return {}\n[docs]class AgentOutputParser(BaseOutputParser[Union[AgentAction, AgentFinish]]):\n    \"\"\"Base class for parsing agent output into agent action/finish.\"\"\"\n[docs]    @abstractmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-6", "text": "[docs]    @abstractmethod\n    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        \"\"\"Parse text into agent action/finish.\"\"\"\n[docs]class MultiActionAgentOutputParser(\n    BaseOutputParser[Union[List[AgentAction], AgentFinish]]\n):\n    \"\"\"Base class for parsing agent output into agent actions/finish.\"\"\"\n[docs]    @abstractmethod\n    def parse(self, text: str) -> Union[List[AgentAction], AgentFinish]:\n        \"\"\"Parse text into agent actions/finish.\"\"\"\n[docs]class RunnableAgent(BaseSingleActionAgent):\n    \"\"\"Agent powered by runnables.\"\"\"\n    runnable: Runnable[dict, Union[AgentAction, AgentFinish]]\n    \"\"\"Runnable to call to get agent action.\"\"\"\n    _input_keys: List[str] = []\n    \"\"\"Input keys.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @property\n    def return_values(self) -> List[str]:\n        \"\"\"Return values of the agent.\"\"\"\n        return []\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys.\n        Returns:\n            List of input keys.\n        \"\"\"\n        return self._input_keys\n[docs]    def plan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[AgentAction, AgentFinish]:\n        \"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with the observations.\n            callbacks: Callbacks to run.\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-7", "text": "Returns:\n            Action specifying what tool to use.\n        \"\"\"\n        inputs = {**kwargs, **{\"intermediate_steps\": intermediate_steps}}\n        output = self.runnable.invoke(inputs, config={\"callbacks\": callbacks})\n        return output\n[docs]    async def aplan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[\n        AgentAction,\n        AgentFinish,\n    ]:\n        \"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with observations\n            callbacks: Callbacks to run.\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.\n        \"\"\"\n        inputs = {**kwargs, **{\"intermediate_steps\": intermediate_steps}}\n        output = await self.runnable.ainvoke(inputs, config={\"callbacks\": callbacks})\n        return output\n[docs]class RunnableMultiActionAgent(BaseMultiActionAgent):\n    \"\"\"Agent powered by runnables.\"\"\"\n    runnable: Runnable[dict, Union[List[AgentAction], AgentFinish]]\n    \"\"\"Runnable to call to get agent actions.\"\"\"\n    _input_keys: List[str] = []\n    \"\"\"Input keys.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @property\n    def return_values(self) -> List[str]:\n        \"\"\"Return values of the agent.\"\"\"\n        return []\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys.\n        Returns:\n            List of input keys.\n        \"\"\"\n        return self._input_keys\n[docs]    def plan(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-8", "text": "return self._input_keys\n[docs]    def plan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[\n        List[AgentAction],\n        AgentFinish,\n    ]:\n        \"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with the observations.\n            callbacks: Callbacks to run.\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.\n        \"\"\"\n        inputs = {**kwargs, **{\"intermediate_steps\": intermediate_steps}}\n        output = self.runnable.invoke(inputs, config={\"callbacks\": callbacks})\n        return output\n[docs]    async def aplan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[\n        List[AgentAction],\n        AgentFinish,\n    ]:\n        \"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with observations\n            callbacks: Callbacks to run.\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.\n        \"\"\"\n        inputs = {**kwargs, **{\"intermediate_steps\": intermediate_steps}}\n        output = await self.runnable.ainvoke(inputs, config={\"callbacks\": callbacks})\n        return output\n[docs]class LLMSingleActionAgent(BaseSingleActionAgent):\n    \"\"\"Base class for single action agents.\"\"\"\n    llm_chain: LLMChain\n    \"\"\"LLMChain to use for agent.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-9", "text": "llm_chain: LLMChain\n    \"\"\"LLMChain to use for agent.\"\"\"\n    output_parser: AgentOutputParser\n    \"\"\"Output parser to use for agent.\"\"\"\n    stop: List[str]\n    \"\"\"List of strings to stop on.\"\"\"\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys.\n        Returns:\n            List of input keys.\n        \"\"\"\n        return list(set(self.llm_chain.input_keys) - {\"intermediate_steps\"})\n[docs]    def dict(self, **kwargs: Any) -> Dict:\n        \"\"\"Return dictionary representation of agent.\"\"\"\n        _dict = super().dict()\n        del _dict[\"output_parser\"]\n        return _dict\n[docs]    def plan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[AgentAction, AgentFinish]:\n        \"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with the observations.\n            callbacks: Callbacks to run.\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.\n        \"\"\"\n        output = self.llm_chain.run(\n            intermediate_steps=intermediate_steps,\n            stop=self.stop,\n            callbacks=callbacks,\n            **kwargs,\n        )\n        return self.output_parser.parse(output)\n[docs]    async def aplan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[AgentAction, AgentFinish]:\n        \"\"\"Given input, decided what to do.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-10", "text": "\"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with observations\n            callbacks: Callbacks to run.\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.\n        \"\"\"\n        output = await self.llm_chain.arun(\n            intermediate_steps=intermediate_steps,\n            stop=self.stop,\n            callbacks=callbacks,\n            **kwargs,\n        )\n        return self.output_parser.parse(output)\n[docs]    def tool_run_logging_kwargs(self) -> Dict:\n        return {\n            \"llm_prefix\": \"\",\n            \"observation_prefix\": \"\" if len(self.stop) == 0 else self.stop[0],\n        }\n[docs]class Agent(BaseSingleActionAgent):\n    \"\"\"Agent that calls the language model and deciding the action.\n    This is driven by an LLMChain. The prompt in the LLMChain MUST include\n    a variable called \"agent_scratchpad\" where the agent can put its\n    intermediary work.\n    \"\"\"\n    llm_chain: LLMChain\n    output_parser: AgentOutputParser\n    allowed_tools: Optional[List[str]] = None\n[docs]    def dict(self, **kwargs: Any) -> Dict:\n        \"\"\"Return dictionary representation of agent.\"\"\"\n        _dict = super().dict()\n        del _dict[\"output_parser\"]\n        return _dict\n[docs]    def get_allowed_tools(self) -> Optional[List[str]]:\n        return self.allowed_tools\n    @property\n    def return_values(self) -> List[str]:\n        return [\"output\"]\n    def _fix_text(self, text: str) -> str:\n        \"\"\"Fix the text.\"\"\"\n        raise ValueError(\"fix_text not implemented for this agent.\")\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-11", "text": "raise ValueError(\"fix_text not implemented for this agent.\")\n    @property\n    def _stop(self) -> List[str]:\n        return [\n            f\"\\n{self.observation_prefix.rstrip()}\",\n            f\"\\n\\t{self.observation_prefix.rstrip()}\",\n        ]\n    def _construct_scratchpad(\n        self, intermediate_steps: List[Tuple[AgentAction, str]]\n    ) -> Union[str, List[BaseMessage]]:\n        \"\"\"Construct the scratchpad that lets the agent continue its thought process.\"\"\"\n        thoughts = \"\"\n        for action, observation in intermediate_steps:\n            thoughts += action.log\n            thoughts += f\"\\n{self.observation_prefix}{observation}\\n{self.llm_prefix}\"\n        return thoughts\n[docs]    def plan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[AgentAction, AgentFinish]:\n        \"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with observations\n            callbacks: Callbacks to run.\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.\n        \"\"\"\n        full_inputs = self.get_full_inputs(intermediate_steps, **kwargs)\n        full_output = self.llm_chain.predict(callbacks=callbacks, **full_inputs)\n        return self.output_parser.parse(full_output)\n[docs]    async def aplan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[AgentAction, AgentFinish]:\n        \"\"\"Given input, decided what to do.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-12", "text": "\"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with observations\n            callbacks: Callbacks to run.\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.\n        \"\"\"\n        full_inputs = self.get_full_inputs(intermediate_steps, **kwargs)\n        full_output = await self.llm_chain.apredict(callbacks=callbacks, **full_inputs)\n        agent_output = await self.output_parser.aparse(full_output)\n        return agent_output\n[docs]    def get_full_inputs(\n        self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any\n    ) -> Dict[str, Any]:\n        \"\"\"Create the full inputs for the LLMChain from intermediate steps.\"\"\"\n        thoughts = self._construct_scratchpad(intermediate_steps)\n        new_inputs = {\"agent_scratchpad\": thoughts, \"stop\": self._stop}\n        full_inputs = {**kwargs, **new_inputs}\n        return full_inputs\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys.\n        :meta private:\n        \"\"\"\n        return list(set(self.llm_chain.input_keys) - {\"agent_scratchpad\"})\n    @root_validator()\n    def validate_prompt(cls, values: Dict) -> Dict:\n        \"\"\"Validate that prompt matches format.\"\"\"\n        prompt = values[\"llm_chain\"].prompt\n        if \"agent_scratchpad\" not in prompt.input_variables:\n            logger.warning(\n                \"`agent_scratchpad` should be a variable in prompt.input_variables.\"\n                \" Did not find it, so adding it at the end.\"\n            )\n            prompt.input_variables.append(\"agent_scratchpad\")\n            if isinstance(prompt, PromptTemplate):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-13", "text": "if isinstance(prompt, PromptTemplate):\n                prompt.template += \"\\n{agent_scratchpad}\"\n            elif isinstance(prompt, FewShotPromptTemplate):\n                prompt.suffix += \"\\n{agent_scratchpad}\"\n            else:\n                raise ValueError(f\"Got unexpected prompt type {type(prompt)}\")\n        return values\n    @property\n    @abstractmethod\n    def observation_prefix(self) -> str:\n        \"\"\"Prefix to append the observation with.\"\"\"\n    @property\n    @abstractmethod\n    def llm_prefix(self) -> str:\n        \"\"\"Prefix to append the LLM call with.\"\"\"\n[docs]    @classmethod\n    @abstractmethod\n    def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate:\n        \"\"\"Create a prompt for this class.\"\"\"\n    @classmethod\n    def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:\n        \"\"\"Validate that appropriate tools are passed in.\"\"\"\n        pass\n    @classmethod\n    @abstractmethod\n    def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:\n        \"\"\"Get default output parser for this class.\"\"\"\n[docs]    @classmethod\n    def from_llm_and_tools(\n        cls,\n        llm: BaseLanguageModel,\n        tools: Sequence[BaseTool],\n        callback_manager: Optional[BaseCallbackManager] = None,\n        output_parser: Optional[AgentOutputParser] = None,\n        **kwargs: Any,\n    ) -> Agent:\n        \"\"\"Construct an agent from an LLM and tools.\"\"\"\n        cls._validate_tools(tools)\n        llm_chain = LLMChain(\n            llm=llm,\n            prompt=cls.create_prompt(tools),\n            callback_manager=callback_manager,\n        )\n        tool_names = [tool.name for tool in tools]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-14", "text": ")\n        tool_names = [tool.name for tool in tools]\n        _output_parser = output_parser or cls._get_default_output_parser()\n        return cls(\n            llm_chain=llm_chain,\n            allowed_tools=tool_names,\n            output_parser=_output_parser,\n            **kwargs,\n        )\n[docs]    def return_stopped_response(\n        self,\n        early_stopping_method: str,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        **kwargs: Any,\n    ) -> AgentFinish:\n        \"\"\"Return response when agent has been stopped due to max iterations.\"\"\"\n        if early_stopping_method == \"force\":\n            # `force` just returns a constant string\n            return AgentFinish(\n                {\"output\": \"Agent stopped due to iteration limit or time limit.\"}, \"\"\n            )\n        elif early_stopping_method == \"generate\":\n            # Generate does one final forward pass\n            thoughts = \"\"\n            for action, observation in intermediate_steps:\n                thoughts += action.log\n                thoughts += (\n                    f\"\\n{self.observation_prefix}{observation}\\n{self.llm_prefix}\"\n                )\n            # Adding to the previous steps, we now tell the LLM to make a final pred\n            thoughts += (\n                \"\\n\\nI now need to return a final answer based on the previous steps:\"\n            )\n            new_inputs = {\"agent_scratchpad\": thoughts, \"stop\": self._stop}\n            full_inputs = {**kwargs, **new_inputs}\n            full_output = self.llm_chain.predict(**full_inputs)\n            # We try to extract a final answer\n            parsed_output = self.output_parser.parse(full_output)\n            if isinstance(parsed_output, AgentFinish):\n                # If we can extract, we send the correct stuff\n                return parsed_output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-15", "text": "# If we can extract, we send the correct stuff\n                return parsed_output\n            else:\n                # If we can extract, but the tool is not the final tool,\n                # we just return the full output\n                return AgentFinish({\"output\": full_output}, full_output)\n        else:\n            raise ValueError(\n                \"early_stopping_method should be one of `force` or `generate`, \"\n                f\"got {early_stopping_method}\"\n            )\n[docs]    def tool_run_logging_kwargs(self) -> Dict:\n        return {\n            \"llm_prefix\": self.llm_prefix,\n            \"observation_prefix\": self.observation_prefix,\n        }\n[docs]class ExceptionTool(BaseTool):\n    \"\"\"Tool that just returns the query.\"\"\"\n    name: str = \"_Exception\"\n    \"\"\"Name of the tool.\"\"\"\n    description: str = \"Exception tool\"\n    \"\"\"Description of the tool.\"\"\"\n    def _run(\n        self,\n        query: str,\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        return query\n    async def _arun(\n        self,\n        query: str,\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        return query\n[docs]class AgentExecutor(Chain):\n    \"\"\"Agent that is using tools.\"\"\"\n    agent: Union[BaseSingleActionAgent, BaseMultiActionAgent]\n    \"\"\"The agent to run for creating a plan and determining actions\n    to take at each step of the execution loop.\"\"\"\n    tools: Sequence[BaseTool]\n    \"\"\"The valid tools the agent can call.\"\"\"\n    return_intermediate_steps: bool = False\n    \"\"\"Whether to return the agent's trajectory of intermediate steps", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-16", "text": "\"\"\"Whether to return the agent's trajectory of intermediate steps\n    at the end in addition to the final output.\"\"\"\n    max_iterations: Optional[int] = 15\n    \"\"\"The maximum number of steps to take before ending the execution\n    loop.\n    \n    Setting to 'None' could lead to an infinite loop.\"\"\"\n    max_execution_time: Optional[float] = None\n    \"\"\"The maximum amount of wall clock time to spend in the execution\n    loop.\n    \"\"\"\n    early_stopping_method: str = \"force\"\n    \"\"\"The method to use for early stopping if the agent never\n    returns `AgentFinish`. Either 'force' or 'generate'.\n    `\"force\"` returns a string saying that it stopped because it met a\n        time or iteration limit.\n    \n    `\"generate\"` calls the agent's LLM Chain one final time to generate\n        a final answer based on the previous steps.\n    \"\"\"\n    handle_parsing_errors: Union[\n        bool, str, Callable[[OutputParserException], str]\n    ] = False\n    \"\"\"How to handle errors raised by the agent's output parser.\n    Defaults to `False`, which raises the error.\n    If `true`, the error will be sent back to the LLM as an observation.\n    If a string, the string itself will be sent to the LLM as an observation.\n    If a callable function, the function will be called with the exception\n     as an argument, and the result of that function will be passed to the agent\n      as an observation.\n    \"\"\"\n    trim_intermediate_steps: Union[\n        int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]\n    ] = -1\n[docs]    @classmethod\n    def from_agent_and_tools(\n        cls,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-17", "text": "[docs]    @classmethod\n    def from_agent_and_tools(\n        cls,\n        agent: Union[BaseSingleActionAgent, BaseMultiActionAgent],\n        tools: Sequence[BaseTool],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> AgentExecutor:\n        \"\"\"Create from agent and tools.\"\"\"\n        return cls(\n            agent=agent,\n            tools=tools,\n            callbacks=callbacks,\n            **kwargs,\n        )\n    @root_validator()\n    def validate_tools(cls, values: Dict) -> Dict:\n        \"\"\"Validate that tools are compatible with agent.\"\"\"\n        agent = values[\"agent\"]\n        tools = values[\"tools\"]\n        allowed_tools = agent.get_allowed_tools()\n        if allowed_tools is not None:\n            if set(allowed_tools) != set([tool.name for tool in tools]):\n                raise ValueError(\n                    f\"Allowed tools ({allowed_tools}) different than \"\n                    f\"provided tools ({[tool.name for tool in tools]})\"\n                )\n        return values\n    @root_validator()\n    def validate_return_direct_tool(cls, values: Dict) -> Dict:\n        \"\"\"Validate that tools are compatible with agent.\"\"\"\n        agent = values[\"agent\"]\n        tools = values[\"tools\"]\n        if isinstance(agent, BaseMultiActionAgent):\n            for tool in tools:\n                if tool.return_direct:\n                    raise ValueError(\n                        \"Tools that have `return_direct=True` are not allowed \"\n                        \"in multi-action agents\"\n                    )\n        return values\n    @root_validator(pre=True)\n    def validate_runnable_agent(cls, values: Dict) -> Dict:\n        \"\"\"Convert runnable to agent if passed in.\"\"\"\n        agent = values[\"agent\"]\n        if isinstance(agent, Runnable):\n            try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-18", "text": "agent = values[\"agent\"]\n        if isinstance(agent, Runnable):\n            try:\n                output_type = agent.OutputType\n            except Exception as _:\n                multi_action = False\n            else:\n                multi_action = output_type == Union[List[AgentAction], AgentFinish]\n            if multi_action:\n                values[\"agent\"] = RunnableMultiActionAgent(runnable=agent)\n            else:\n                values[\"agent\"] = RunnableAgent(runnable=agent)\n        return values\n[docs]    def save(self, file_path: Union[Path, str]) -> None:\n        \"\"\"Raise error - saving not supported for Agent Executors.\"\"\"\n        raise ValueError(\n            \"Saving not supported for agent executors. \"\n            \"If you are trying to save the agent, please use the \"\n            \"`.save_agent(...)`\"\n        )\n[docs]    def save_agent(self, file_path: Union[Path, str]) -> None:\n        \"\"\"Save the underlying agent.\"\"\"\n        return self.agent.save(file_path)\n[docs]    def iter(\n        self,\n        inputs: Any,\n        callbacks: Callbacks = None,\n        *,\n        include_run_info: bool = False,\n        async_: bool = False,\n    ) -> AgentExecutorIterator:\n        \"\"\"Enables iteration over steps taken to reach final output.\"\"\"\n        return AgentExecutorIterator(\n            self,\n            inputs,\n            callbacks,\n            tags=self.tags,\n            include_run_info=include_run_info,\n            async_=async_,\n        )\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Return the input keys.\n        :meta private:\n        \"\"\"\n        return self.agent.input_keys\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"Return the singular output key.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-19", "text": "def output_keys(self) -> List[str]:\n        \"\"\"Return the singular output key.\n        :meta private:\n        \"\"\"\n        if self.return_intermediate_steps:\n            return self.agent.return_values + [\"intermediate_steps\"]\n        else:\n            return self.agent.return_values\n[docs]    def lookup_tool(self, name: str) -> BaseTool:\n        \"\"\"Lookup tool by name.\"\"\"\n        return {tool.name: tool for tool in self.tools}[name]\n    def _should_continue(self, iterations: int, time_elapsed: float) -> bool:\n        if self.max_iterations is not None and iterations >= self.max_iterations:\n            return False\n        if (\n            self.max_execution_time is not None\n            and time_elapsed >= self.max_execution_time\n        ):\n            return False\n        return True\n    def _return(\n        self,\n        output: AgentFinish,\n        intermediate_steps: list,\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        if run_manager:\n            run_manager.on_agent_finish(output, color=\"green\", verbose=self.verbose)\n        final_output = output.return_values\n        if self.return_intermediate_steps:\n            final_output[\"intermediate_steps\"] = intermediate_steps\n        return final_output\n    async def _areturn(\n        self,\n        output: AgentFinish,\n        intermediate_steps: list,\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        if run_manager:\n            await run_manager.on_agent_finish(\n                output, color=\"green\", verbose=self.verbose\n            )\n        final_output = output.return_values\n        if self.return_intermediate_steps:\n            final_output[\"intermediate_steps\"] = intermediate_steps\n        return final_output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-20", "text": "final_output[\"intermediate_steps\"] = intermediate_steps\n        return final_output\n    def _take_next_step(\n        self,\n        name_to_tool_map: Dict[str, BaseTool],\n        color_mapping: Dict[str, str],\n        inputs: Dict[str, str],\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Union[AgentFinish, List[Tuple[AgentAction, str]]]:\n        \"\"\"Take a single step in the thought-action-observation loop.\n        Override this to take control of how the agent makes and acts on choices.\n        \"\"\"\n        try:\n            intermediate_steps = self._prepare_intermediate_steps(intermediate_steps)\n            # Call the LLM to see what to do.\n            output = self.agent.plan(\n                intermediate_steps,\n                callbacks=run_manager.get_child() if run_manager else None,\n                **inputs,\n            )\n        except OutputParserException as e:\n            if isinstance(self.handle_parsing_errors, bool):\n                raise_error = not self.handle_parsing_errors\n            else:\n                raise_error = False\n            if raise_error:\n                raise ValueError(\n                    \"An output parsing error occurred. \"\n                    \"In order to pass this error back to the agent and have it try \"\n                    \"again, pass `handle_parsing_errors=True` to the AgentExecutor. \"\n                    f\"This is the error: {str(e)}\"\n                )\n            text = str(e)\n            if isinstance(self.handle_parsing_errors, bool):\n                if e.send_to_llm:\n                    observation = str(e.observation)\n                    text = str(e.llm_output)\n                else:\n                    observation = \"Invalid or incomplete response\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-21", "text": "else:\n                    observation = \"Invalid or incomplete response\"\n            elif isinstance(self.handle_parsing_errors, str):\n                observation = self.handle_parsing_errors\n            elif callable(self.handle_parsing_errors):\n                observation = self.handle_parsing_errors(e)\n            else:\n                raise ValueError(\"Got unexpected type of `handle_parsing_errors`\")\n            output = AgentAction(\"_Exception\", observation, text)\n            if run_manager:\n                run_manager.on_agent_action(output, color=\"green\")\n            tool_run_kwargs = self.agent.tool_run_logging_kwargs()\n            observation = ExceptionTool().run(\n                output.tool_input,\n                verbose=self.verbose,\n                color=None,\n                callbacks=run_manager.get_child() if run_manager else None,\n                **tool_run_kwargs,\n            )\n            return [(output, observation)]\n        # If the tool chosen is the finishing tool, then we end and return.\n        if isinstance(output, AgentFinish):\n            return output\n        actions: List[AgentAction]\n        if isinstance(output, AgentAction):\n            actions = [output]\n        else:\n            actions = output\n        result = []\n        for agent_action in actions:\n            if run_manager:\n                run_manager.on_agent_action(agent_action, color=\"green\")\n            # Otherwise we lookup the tool\n            if agent_action.tool in name_to_tool_map:\n                tool = name_to_tool_map[agent_action.tool]\n                return_direct = tool.return_direct\n                color = color_mapping[agent_action.tool]\n                tool_run_kwargs = self.agent.tool_run_logging_kwargs()\n                if return_direct:\n                    tool_run_kwargs[\"llm_prefix\"] = \"\"\n                # We then call the tool on the tool input to get an observation\n                observation = tool.run(\n                    agent_action.tool_input,\n                    verbose=self.verbose,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-22", "text": "observation = tool.run(\n                    agent_action.tool_input,\n                    verbose=self.verbose,\n                    color=color,\n                    callbacks=run_manager.get_child() if run_manager else None,\n                    **tool_run_kwargs,\n                )\n            else:\n                tool_run_kwargs = self.agent.tool_run_logging_kwargs()\n                observation = InvalidTool().run(\n                    {\n                        \"requested_tool_name\": agent_action.tool,\n                        \"available_tool_names\": list(name_to_tool_map.keys()),\n                    },\n                    verbose=self.verbose,\n                    color=None,\n                    callbacks=run_manager.get_child() if run_manager else None,\n                    **tool_run_kwargs,\n                )\n            result.append((agent_action, observation))\n        return result\n    async def _atake_next_step(\n        self,\n        name_to_tool_map: Dict[str, BaseTool],\n        color_mapping: Dict[str, str],\n        inputs: Dict[str, str],\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Union[AgentFinish, List[Tuple[AgentAction, str]]]:\n        \"\"\"Take a single step in the thought-action-observation loop.\n        Override this to take control of how the agent makes and acts on choices.\n        \"\"\"\n        try:\n            intermediate_steps = self._prepare_intermediate_steps(intermediate_steps)\n            # Call the LLM to see what to do.\n            output = await self.agent.aplan(\n                intermediate_steps,\n                callbacks=run_manager.get_child() if run_manager else None,\n                **inputs,\n            )\n        except OutputParserException as e:\n            if isinstance(self.handle_parsing_errors, bool):\n                raise_error = not self.handle_parsing_errors\n            else:\n                raise_error = False", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-23", "text": "else:\n                raise_error = False\n            if raise_error:\n                raise ValueError(\n                    \"An output parsing error occurred. \"\n                    \"In order to pass this error back to the agent and have it try \"\n                    \"again, pass `handle_parsing_errors=True` to the AgentExecutor. \"\n                    f\"This is the error: {str(e)}\"\n                )\n            text = str(e)\n            if isinstance(self.handle_parsing_errors, bool):\n                if e.send_to_llm:\n                    observation = str(e.observation)\n                    text = str(e.llm_output)\n                else:\n                    observation = \"Invalid or incomplete response\"\n            elif isinstance(self.handle_parsing_errors, str):\n                observation = self.handle_parsing_errors\n            elif callable(self.handle_parsing_errors):\n                observation = self.handle_parsing_errors(e)\n            else:\n                raise ValueError(\"Got unexpected type of `handle_parsing_errors`\")\n            output = AgentAction(\"_Exception\", observation, text)\n            tool_run_kwargs = self.agent.tool_run_logging_kwargs()\n            observation = await ExceptionTool().arun(\n                output.tool_input,\n                verbose=self.verbose,\n                color=None,\n                callbacks=run_manager.get_child() if run_manager else None,\n                **tool_run_kwargs,\n            )\n            return [(output, observation)]\n        # If the tool chosen is the finishing tool, then we end and return.\n        if isinstance(output, AgentFinish):\n            return output\n        actions: List[AgentAction]\n        if isinstance(output, AgentAction):\n            actions = [output]\n        else:\n            actions = output\n        async def _aperform_agent_action(\n            agent_action: AgentAction,\n        ) -> Tuple[AgentAction, str]:\n            if run_manager:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-24", "text": ") -> Tuple[AgentAction, str]:\n            if run_manager:\n                await run_manager.on_agent_action(\n                    agent_action, verbose=self.verbose, color=\"green\"\n                )\n            # Otherwise we lookup the tool\n            if agent_action.tool in name_to_tool_map:\n                tool = name_to_tool_map[agent_action.tool]\n                return_direct = tool.return_direct\n                color = color_mapping[agent_action.tool]\n                tool_run_kwargs = self.agent.tool_run_logging_kwargs()\n                if return_direct:\n                    tool_run_kwargs[\"llm_prefix\"] = \"\"\n                # We then call the tool on the tool input to get an observation\n                observation = await tool.arun(\n                    agent_action.tool_input,\n                    verbose=self.verbose,\n                    color=color,\n                    callbacks=run_manager.get_child() if run_manager else None,\n                    **tool_run_kwargs,\n                )\n            else:\n                tool_run_kwargs = self.agent.tool_run_logging_kwargs()\n                observation = await InvalidTool().arun(\n                    {\n                        \"requested_tool_name\": agent_action.tool,\n                        \"available_tool_names\": list(name_to_tool_map.keys()),\n                    },\n                    verbose=self.verbose,\n                    color=None,\n                    callbacks=run_manager.get_child() if run_manager else None,\n                    **tool_run_kwargs,\n                )\n            return agent_action, observation\n        # Use asyncio.gather to run multiple tool.arun() calls concurrently\n        result = await asyncio.gather(\n            *[_aperform_agent_action(agent_action) for agent_action in actions]\n        )\n        return list(result)\n    def _call(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-25", "text": ") -> Dict[str, Any]:\n        \"\"\"Run text through and get agent response.\"\"\"\n        # Construct a mapping of tool name to tool for easy lookup\n        name_to_tool_map = {tool.name: tool for tool in self.tools}\n        # We construct a mapping from each tool to a color, used for logging.\n        color_mapping = get_color_mapping(\n            [tool.name for tool in self.tools], excluded_colors=[\"green\", \"red\"]\n        )\n        intermediate_steps: List[Tuple[AgentAction, str]] = []\n        # Let's start tracking the number of iterations and time elapsed\n        iterations = 0\n        time_elapsed = 0.0\n        start_time = time.time()\n        # We now enter the agent loop (until it returns something).\n        while self._should_continue(iterations, time_elapsed):\n            next_step_output = self._take_next_step(\n                name_to_tool_map,\n                color_mapping,\n                inputs,\n                intermediate_steps,\n                run_manager=run_manager,\n            )\n            if isinstance(next_step_output, AgentFinish):\n                return self._return(\n                    next_step_output, intermediate_steps, run_manager=run_manager\n                )\n            intermediate_steps.extend(next_step_output)\n            if len(next_step_output) == 1:\n                next_step_action = next_step_output[0]\n                # See if tool should return directly\n                tool_return = self._get_tool_return(next_step_action)\n                if tool_return is not None:\n                    return self._return(\n                        tool_return, intermediate_steps, run_manager=run_manager\n                    )\n            iterations += 1\n            time_elapsed = time.time() - start_time\n        output = self.agent.return_stopped_response(\n            self.early_stopping_method, intermediate_steps, **inputs\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-26", "text": "self.early_stopping_method, intermediate_steps, **inputs\n        )\n        return self._return(output, intermediate_steps, run_manager=run_manager)\n    async def _acall(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, str]:\n        \"\"\"Run text through and get agent response.\"\"\"\n        # Construct a mapping of tool name to tool for easy lookup\n        name_to_tool_map = {tool.name: tool for tool in self.tools}\n        # We construct a mapping from each tool to a color, used for logging.\n        color_mapping = get_color_mapping(\n            [tool.name for tool in self.tools], excluded_colors=[\"green\"]\n        )\n        intermediate_steps: List[Tuple[AgentAction, str]] = []\n        # Let's start tracking the number of iterations and time elapsed\n        iterations = 0\n        time_elapsed = 0.0\n        start_time = time.time()\n        # We now enter the agent loop (until it returns something).\n        async with asyncio_timeout(self.max_execution_time):\n            try:\n                while self._should_continue(iterations, time_elapsed):\n                    next_step_output = await self._atake_next_step(\n                        name_to_tool_map,\n                        color_mapping,\n                        inputs,\n                        intermediate_steps,\n                        run_manager=run_manager,\n                    )\n                    if isinstance(next_step_output, AgentFinish):\n                        return await self._areturn(\n                            next_step_output,\n                            intermediate_steps,\n                            run_manager=run_manager,\n                        )\n                    intermediate_steps.extend(next_step_output)\n                    if len(next_step_output) == 1:\n                        next_step_action = next_step_output[0]\n                        # See if tool should return directly", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-27", "text": "# See if tool should return directly\n                        tool_return = self._get_tool_return(next_step_action)\n                        if tool_return is not None:\n                            return await self._areturn(\n                                tool_return, intermediate_steps, run_manager=run_manager\n                            )\n                    iterations += 1\n                    time_elapsed = time.time() - start_time\n                output = self.agent.return_stopped_response(\n                    self.early_stopping_method, intermediate_steps, **inputs\n                )\n                return await self._areturn(\n                    output, intermediate_steps, run_manager=run_manager\n                )\n            except TimeoutError:\n                # stop early when interrupted by the async timeout\n                output = self.agent.return_stopped_response(\n                    self.early_stopping_method, intermediate_steps, **inputs\n                )\n                return await self._areturn(\n                    output, intermediate_steps, run_manager=run_manager\n                )\n    def _get_tool_return(\n        self, next_step_output: Tuple[AgentAction, str]\n    ) -> Optional[AgentFinish]:\n        \"\"\"Check if the tool is a returning tool.\"\"\"\n        agent_action, observation = next_step_output\n        name_to_tool_map = {tool.name: tool for tool in self.tools}\n        return_value_key = \"output\"\n        if len(self.agent.return_values) > 0:\n            return_value_key = self.agent.return_values[0]\n        # Invalid tools won't be in the map, so we return False.\n        if agent_action.tool in name_to_tool_map:\n            if name_to_tool_map[agent_action.tool].return_direct:\n                return AgentFinish(\n                    {return_value_key: observation},\n                    \"\",\n                )\n        return None\n    def _prepare_intermediate_steps(\n        self, intermediate_steps: List[Tuple[AgentAction, str]]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "bed605727000-28", "text": "self, intermediate_steps: List[Tuple[AgentAction, str]]\n    ) -> List[Tuple[AgentAction, str]]:\n        if (\n            isinstance(self.trim_intermediate_steps, int)\n            and self.trim_intermediate_steps > 0\n        ):\n            return intermediate_steps[-self.trim_intermediate_steps :]\n        elif callable(self.trim_intermediate_steps):\n            return self.trim_intermediate_steps(intermediate_steps)\n        else:\n            return intermediate_steps", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html"}
{"id": "1cdc3a081cec-0", "text": "Source code for langchain.agents.load_tools\n# flake8: noqa\n\"\"\"Tools provide access to various resources and services.\nLangChain has a large ecosystem of integrations with various external resources\nlike local and remote file systems, APIs and databases.\nThese integrations allow developers to create versatile applications that combine the\npower of LLMs with the ability to access, interact with and manipulate external\nresources.\nWhen developing an application, developers should inspect the capabilities and\npermissions of the tools that underlie the given agent toolkit, and determine\nwhether permissions of the given toolkit are appropriate for the application.\nSee [Security](https://python.langchain.com/docs/security) for more information.\n\"\"\"\nimport warnings\nfrom typing import Any, Dict, List, Optional, Callable, Tuple\nfrom mypy_extensions import Arg, KwArg\nfrom langchain.agents.tools import Tool\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chains.api import news_docs, open_meteo_docs, podcast_docs, tmdb_docs\nfrom langchain.chains.api.base import APIChain\nfrom langchain.chains.llm_math.base import LLMMathChain\nfrom langchain.utilities.dalle_image_generator import DallEAPIWrapper\nfrom langchain.utilities.requests import TextRequestsWrapper\nfrom langchain.tools.arxiv.tool import ArxivQueryRun\nfrom langchain.tools.golden_query.tool import GoldenQueryRun\nfrom langchain.tools.pubmed.tool import PubmedQueryRun\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.bing_search.tool import BingSearchRun\nfrom langchain.tools.ddg_search.tool import DuckDuckGoSearchRun\nfrom langchain.tools.google_cloud.texttospeech import GoogleCloudTextToSpeechTool\nfrom langchain.tools.google_search.tool import GoogleSearchResults, GoogleSearchRun", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-1", "text": "from langchain.tools.google_search.tool import GoogleSearchResults, GoogleSearchRun\nfrom langchain.tools.google_scholar.tool import GoogleScholarQueryRun\nfrom langchain.tools.metaphor_search.tool import MetaphorSearchResults\nfrom langchain.tools.google_serper.tool import GoogleSerperResults, GoogleSerperRun\nfrom langchain.tools.searchapi.tool import SearchAPIResults, SearchAPIRun\nfrom langchain.tools.graphql.tool import BaseGraphQLTool\nfrom langchain.tools.human.tool import HumanInputRun\nfrom langchain.tools.requests.tool import (\n    RequestsDeleteTool,\n    RequestsGetTool,\n    RequestsPatchTool,\n    RequestsPostTool,\n    RequestsPutTool,\n)\nfrom langchain.tools.eleven_labs.text2speech import ElevenLabsText2SpeechTool\nfrom langchain.tools.scenexplain.tool import SceneXplainTool\nfrom langchain.tools.searx_search.tool import SearxSearchResults, SearxSearchRun\nfrom langchain.tools.shell.tool import ShellTool\nfrom langchain.tools.sleep.tool import SleepTool\nfrom langchain.tools.wikipedia.tool import WikipediaQueryRun\nfrom langchain.tools.wolfram_alpha.tool import WolframAlphaQueryRun\nfrom langchain.tools.openweathermap.tool import OpenWeatherMapQueryRun\nfrom langchain.tools.dataforseo_api_search import DataForSeoAPISearchRun\nfrom langchain.tools.dataforseo_api_search import DataForSeoAPISearchResults\nfrom langchain.tools.memorize.tool import Memorize\nfrom langchain.utilities.arxiv import ArxivAPIWrapper\nfrom langchain.utilities.golden_query import GoldenQueryAPIWrapper\nfrom langchain.utilities.pubmed import PubMedAPIWrapper\nfrom langchain.utilities.bing_search import BingSearchAPIWrapper\nfrom langchain.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper\nfrom langchain.utilities.google_search import GoogleSearchAPIWrapper", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-2", "text": "from langchain.utilities.google_search import GoogleSearchAPIWrapper\nfrom langchain.utilities.google_serper import GoogleSerperAPIWrapper\nfrom langchain.utilities.google_scholar import GoogleScholarAPIWrapper\nfrom langchain.utilities.metaphor_search import MetaphorSearchAPIWrapper\nfrom langchain.utilities.awslambda import LambdaWrapper\nfrom langchain.utilities.graphql import GraphQLAPIWrapper\nfrom langchain.utilities.searchapi import SearchApiAPIWrapper\nfrom langchain.utilities.searx_search import SearxSearchWrapper\nfrom langchain.utilities.serpapi import SerpAPIWrapper\nfrom langchain.utilities.twilio import TwilioAPIWrapper\nfrom langchain.utilities.wikipedia import WikipediaAPIWrapper\nfrom langchain.utilities.wolfram_alpha import WolframAlphaAPIWrapper\nfrom langchain.utilities.openweathermap import OpenWeatherMapAPIWrapper\nfrom langchain.utilities.dataforseo_api_search import DataForSeoAPIWrapper\ndef _get_python_repl() -> BaseTool:\n    raise ImportError(\n        \"This tool has been moved to langchain experiment. \"\n        \"This tool has access to a python REPL. \"\n        \"For best practices make sure to sandbox this tool. \"\n        \"Read https://github.com/langchain-ai/langchain/blob/master/SECURITY.md \"\n        \"To keep using this code as is, install langchain experimental and \"\n        \"update relevant imports replacing 'langchain' with 'langchain_experimental'\"\n    )\ndef _get_tools_requests_get() -> BaseTool:\n    return RequestsGetTool(requests_wrapper=TextRequestsWrapper())\ndef _get_tools_requests_post() -> BaseTool:\n    return RequestsPostTool(requests_wrapper=TextRequestsWrapper())\ndef _get_tools_requests_patch() -> BaseTool:\n    return RequestsPatchTool(requests_wrapper=TextRequestsWrapper())\ndef _get_tools_requests_put() -> BaseTool:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-3", "text": "def _get_tools_requests_put() -> BaseTool:\n    return RequestsPutTool(requests_wrapper=TextRequestsWrapper())\ndef _get_tools_requests_delete() -> BaseTool:\n    return RequestsDeleteTool(requests_wrapper=TextRequestsWrapper())\ndef _get_terminal() -> BaseTool:\n    return ShellTool()\ndef _get_sleep() -> BaseTool:\n    return SleepTool()\n_BASE_TOOLS: Dict[str, Callable[[], BaseTool]] = {\n    \"python_repl\": _get_python_repl,\n    \"requests\": _get_tools_requests_get,  # preserved for backwards compatibility\n    \"requests_get\": _get_tools_requests_get,\n    \"requests_post\": _get_tools_requests_post,\n    \"requests_patch\": _get_tools_requests_patch,\n    \"requests_put\": _get_tools_requests_put,\n    \"requests_delete\": _get_tools_requests_delete,\n    \"terminal\": _get_terminal,\n    \"sleep\": _get_sleep,\n}\ndef _get_llm_math(llm: BaseLanguageModel) -> BaseTool:\n    return Tool(\n        name=\"Calculator\",\n        description=\"Useful for when you need to answer questions about math.\",\n        func=LLMMathChain.from_llm(llm=llm).run,\n        coroutine=LLMMathChain.from_llm(llm=llm).arun,\n    )\ndef _get_open_meteo_api(llm: BaseLanguageModel) -> BaseTool:\n    chain = APIChain.from_llm_and_api_docs(\n        llm,\n        open_meteo_docs.OPEN_METEO_DOCS,\n        limit_to_domains=[\"https://api.open-meteo.com/\"],\n    )\n    return Tool(\n        name=\"Open-Meteo-API\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-4", "text": ")\n    return Tool(\n        name=\"Open-Meteo-API\",\n        description=\"Useful for when you want to get weather information from the OpenMeteo API. The input should be a question in natural language that this API can answer.\",\n        func=chain.run,\n    )\n_LLM_TOOLS: Dict[str, Callable[[BaseLanguageModel], BaseTool]] = {\n    \"llm-math\": _get_llm_math,\n    \"open-meteo-api\": _get_open_meteo_api,\n}\ndef _get_news_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:\n    news_api_key = kwargs[\"news_api_key\"]\n    chain = APIChain.from_llm_and_api_docs(\n        llm,\n        news_docs.NEWS_DOCS,\n        headers={\"X-Api-Key\": news_api_key},\n        limit_to_domains=[\"https://newsapi.org/\"],\n    )\n    return Tool(\n        name=\"News-API\",\n        description=\"Use this when you want to get information about the top headlines of current news stories. The input should be a question in natural language that this API can answer.\",\n        func=chain.run,\n    )\ndef _get_tmdb_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:\n    tmdb_bearer_token = kwargs[\"tmdb_bearer_token\"]\n    chain = APIChain.from_llm_and_api_docs(\n        llm,\n        tmdb_docs.TMDB_DOCS,\n        headers={\"Authorization\": f\"Bearer {tmdb_bearer_token}\"},\n        limit_to_domains=[\"https://api.themoviedb.org/\"],\n    )\n    return Tool(\n        name=\"TMDB-API\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-5", "text": ")\n    return Tool(\n        name=\"TMDB-API\",\n        description=\"Useful for when you want to get information from The Movie Database. The input should be a question in natural language that this API can answer.\",\n        func=chain.run,\n    )\ndef _get_podcast_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:\n    listen_api_key = kwargs[\"listen_api_key\"]\n    chain = APIChain.from_llm_and_api_docs(\n        llm,\n        podcast_docs.PODCAST_DOCS,\n        headers={\"X-ListenAPI-Key\": listen_api_key},\n        limit_to_domains=[\"https://listen-api.listennotes.com/\"],\n    )\n    return Tool(\n        name=\"Podcast-API\",\n        description=\"Use the Listen Notes Podcast API to search all podcasts or episodes. The input should be a question in natural language that this API can answer.\",\n        func=chain.run,\n    )\ndef _get_lambda_api(**kwargs: Any) -> BaseTool:\n    return Tool(\n        name=kwargs[\"awslambda_tool_name\"],\n        description=kwargs[\"awslambda_tool_description\"],\n        func=LambdaWrapper(**kwargs).run,\n    )\ndef _get_wolfram_alpha(**kwargs: Any) -> BaseTool:\n    return WolframAlphaQueryRun(api_wrapper=WolframAlphaAPIWrapper(**kwargs))\ndef _get_google_search(**kwargs: Any) -> BaseTool:\n    return GoogleSearchRun(api_wrapper=GoogleSearchAPIWrapper(**kwargs))\ndef _get_wikipedia(**kwargs: Any) -> BaseTool:\n    return WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(**kwargs))\ndef _get_arxiv(**kwargs: Any) -> BaseTool:\n    return ArxivQueryRun(api_wrapper=ArxivAPIWrapper(**kwargs))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-6", "text": "return ArxivQueryRun(api_wrapper=ArxivAPIWrapper(**kwargs))\ndef _get_golden_query(**kwargs: Any) -> BaseTool:\n    return GoldenQueryRun(api_wrapper=GoldenQueryAPIWrapper(**kwargs))\ndef _get_pubmed(**kwargs: Any) -> BaseTool:\n    return PubmedQueryRun(api_wrapper=PubMedAPIWrapper(**kwargs))\ndef _get_google_serper(**kwargs: Any) -> BaseTool:\n    return GoogleSerperRun(api_wrapper=GoogleSerperAPIWrapper(**kwargs))\ndef _get_google_scholar(**kwargs: Any) -> BaseTool:\n    return GoogleScholarQueryRun(api_wrapper=GoogleScholarAPIWrapper(**kwargs))\ndef _get_google_serper_results_json(**kwargs: Any) -> BaseTool:\n    return GoogleSerperResults(api_wrapper=GoogleSerperAPIWrapper(**kwargs))\ndef _get_google_search_results_json(**kwargs: Any) -> BaseTool:\n    return GoogleSearchResults(api_wrapper=GoogleSearchAPIWrapper(**kwargs))\ndef _get_searchapi(**kwargs: Any) -> BaseTool:\n    return SearchAPIRun(api_wrapper=SearchApiAPIWrapper(**kwargs))\ndef _get_searchapi_results_json(**kwargs: Any) -> BaseTool:\n    return SearchAPIResults(api_wrapper=SearchApiAPIWrapper(**kwargs))\ndef _get_serpapi(**kwargs: Any) -> BaseTool:\n    return Tool(\n        name=\"Search\",\n        description=\"A search engine. Useful for when you need to answer questions about current events. Input should be a search query.\",\n        func=SerpAPIWrapper(**kwargs).run,\n        coroutine=SerpAPIWrapper(**kwargs).arun,\n    )\ndef _get_dalle_image_generator(**kwargs: Any) -> Tool:\n    return Tool(\n        \"Dall-E-Image-Generator\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-7", "text": "return Tool(\n        \"Dall-E-Image-Generator\",\n        DallEAPIWrapper(**kwargs).run,\n        \"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description.\",\n    )\ndef _get_twilio(**kwargs: Any) -> BaseTool:\n    return Tool(\n        name=\"Text-Message\",\n        description=\"Useful for when you need to send a text message to a provided phone number.\",\n        func=TwilioAPIWrapper(**kwargs).run,\n    )\ndef _get_searx_search(**kwargs: Any) -> BaseTool:\n    return SearxSearchRun(wrapper=SearxSearchWrapper(**kwargs))\ndef _get_searx_search_results_json(**kwargs: Any) -> BaseTool:\n    wrapper_kwargs = {k: v for k, v in kwargs.items() if k != \"num_results\"}\n    return SearxSearchResults(wrapper=SearxSearchWrapper(**wrapper_kwargs), **kwargs)\ndef _get_bing_search(**kwargs: Any) -> BaseTool:\n    return BingSearchRun(api_wrapper=BingSearchAPIWrapper(**kwargs))\ndef _get_metaphor_search(**kwargs: Any) -> BaseTool:\n    return MetaphorSearchResults(api_wrapper=MetaphorSearchAPIWrapper(**kwargs))\ndef _get_ddg_search(**kwargs: Any) -> BaseTool:\n    return DuckDuckGoSearchRun(api_wrapper=DuckDuckGoSearchAPIWrapper(**kwargs))\ndef _get_human_tool(**kwargs: Any) -> BaseTool:\n    return HumanInputRun(**kwargs)\ndef _get_scenexplain(**kwargs: Any) -> BaseTool:\n    return SceneXplainTool(**kwargs)\ndef _get_graphql_tool(**kwargs: Any) -> BaseTool:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-8", "text": "def _get_graphql_tool(**kwargs: Any) -> BaseTool:\n    graphql_endpoint = kwargs[\"graphql_endpoint\"]\n    wrapper = GraphQLAPIWrapper(graphql_endpoint=graphql_endpoint)\n    return BaseGraphQLTool(graphql_wrapper=wrapper)\ndef _get_openweathermap(**kwargs: Any) -> BaseTool:\n    return OpenWeatherMapQueryRun(api_wrapper=OpenWeatherMapAPIWrapper(**kwargs))\ndef _get_dataforseo_api_search(**kwargs: Any) -> BaseTool:\n    return DataForSeoAPISearchRun(api_wrapper=DataForSeoAPIWrapper(**kwargs))\ndef _get_dataforseo_api_search_json(**kwargs: Any) -> BaseTool:\n    return DataForSeoAPISearchResults(api_wrapper=DataForSeoAPIWrapper(**kwargs))\ndef _get_eleven_labs_text2speech(**kwargs: Any) -> BaseTool:\n    return ElevenLabsText2SpeechTool(**kwargs)\ndef _get_memorize(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:\n    return Memorize(llm=llm)\ndef _get_google_cloud_texttospeech(**kwargs: Any) -> BaseTool:\n    return GoogleCloudTextToSpeechTool(**kwargs)\n_EXTRA_LLM_TOOLS: Dict[\n    str,\n    Tuple[Callable[[Arg(BaseLanguageModel, \"llm\"), KwArg(Any)], BaseTool], List[str]],\n] = {\n    \"news-api\": (_get_news_api, [\"news_api_key\"]),\n    \"tmdb-api\": (_get_tmdb_api, [\"tmdb_bearer_token\"]),\n    \"podcast-api\": (_get_podcast_api, [\"listen_api_key\"]),\n    \"memorize\": (_get_memorize, []),\n}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-9", "text": "\"memorize\": (_get_memorize, []),\n}\n_EXTRA_OPTIONAL_TOOLS: Dict[str, Tuple[Callable[[KwArg(Any)], BaseTool], List[str]]] = {\n    \"wolfram-alpha\": (_get_wolfram_alpha, [\"wolfram_alpha_appid\"]),\n    \"google-search\": (_get_google_search, [\"google_api_key\", \"google_cse_id\"]),\n    \"google-search-results-json\": (\n        _get_google_search_results_json,\n        [\"google_api_key\", \"google_cse_id\", \"num_results\"],\n    ),\n    \"searx-search-results-json\": (\n        _get_searx_search_results_json,\n        [\"searx_host\", \"engines\", \"num_results\", \"aiosession\"],\n    ),\n    \"bing-search\": (_get_bing_search, [\"bing_subscription_key\", \"bing_search_url\"]),\n    \"metaphor-search\": (_get_metaphor_search, [\"metaphor_api_key\"]),\n    \"ddg-search\": (_get_ddg_search, []),\n    \"google-serper\": (_get_google_serper, [\"serper_api_key\", \"aiosession\"]),\n    \"google-scholar\": (\n        _get_google_scholar,\n        [\"top_k_results\", \"hl\", \"lr\", \"serp_api_key\"],\n    ),\n    \"google-serper-results-json\": (\n        _get_google_serper_results_json,\n        [\"serper_api_key\", \"aiosession\"],\n    ),\n    \"searchapi\": (_get_searchapi, [\"searchapi_api_key\", \"aiosession\"]),\n    \"searchapi-results-json\": (\n        _get_searchapi_results_json,\n        [\"searchapi_api_key\", \"aiosession\"],\n    ),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-10", "text": "[\"searchapi_api_key\", \"aiosession\"],\n    ),\n    \"serpapi\": (_get_serpapi, [\"serpapi_api_key\", \"aiosession\"]),\n    \"dalle-image-generator\": (_get_dalle_image_generator, [\"openai_api_key\"]),\n    \"twilio\": (_get_twilio, [\"account_sid\", \"auth_token\", \"from_number\"]),\n    \"searx-search\": (_get_searx_search, [\"searx_host\", \"engines\", \"aiosession\"]),\n    \"wikipedia\": (_get_wikipedia, [\"top_k_results\", \"lang\"]),\n    \"arxiv\": (\n        _get_arxiv,\n        [\"top_k_results\", \"load_max_docs\", \"load_all_available_meta\"],\n    ),\n    \"golden-query\": (_get_golden_query, [\"golden_api_key\"]),\n    \"pubmed\": (_get_pubmed, [\"top_k_results\"]),\n    \"human\": (_get_human_tool, [\"prompt_func\", \"input_func\"]),\n    \"awslambda\": (\n        _get_lambda_api,\n        [\"awslambda_tool_name\", \"awslambda_tool_description\", \"function_name\"],\n    ),\n    \"sceneXplain\": (_get_scenexplain, []),\n    \"graphql\": (_get_graphql_tool, [\"graphql_endpoint\"]),\n    \"openweathermap-api\": (_get_openweathermap, [\"openweathermap_api_key\"]),\n    \"dataforseo-api-search\": (\n        _get_dataforseo_api_search,\n        [\"api_login\", \"api_password\", \"aiosession\"],\n    ),\n    \"dataforseo-api-search-json\": (\n        _get_dataforseo_api_search_json,\n        [\"api_login\", \"api_password\", \"aiosession\"],\n    ),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-11", "text": "[\"api_login\", \"api_password\", \"aiosession\"],\n    ),\n    \"eleven_labs_text2speech\": (_get_eleven_labs_text2speech, [\"eleven_api_key\"]),\n    \"google_cloud_texttospeech\": (_get_google_cloud_texttospeech, []),\n}\ndef _handle_callbacks(\n    callback_manager: Optional[BaseCallbackManager], callbacks: Callbacks\n) -> Callbacks:\n    if callback_manager is not None:\n        warnings.warn(\n            \"callback_manager is deprecated. Please use callbacks instead.\",\n            DeprecationWarning,\n        )\n        if callbacks is not None:\n            raise ValueError(\n                \"Cannot specify both callback_manager and callbacks arguments.\"\n            )\n        return callback_manager\n    return callbacks\n[docs]def load_huggingface_tool(\n    task_or_repo_id: str,\n    model_repo_id: Optional[str] = None,\n    token: Optional[str] = None,\n    remote: bool = False,\n    **kwargs: Any,\n) -> BaseTool:\n    \"\"\"Loads a tool from the HuggingFace Hub.\n    Args:\n        task_or_repo_id: Task or model repo id.\n        model_repo_id: Optional model repo id.\n        token: Optional token.\n        remote: Optional remote. Defaults to False.\n        **kwargs:\n    Returns:\n        A tool.\n    \"\"\"\n    try:\n        from transformers import load_tool\n    except ImportError:\n        raise ImportError(\n            \"HuggingFace tools require the libraries `transformers>=4.29.0`\"\n            \" and `huggingface_hub>=0.14.1` to be installed.\"\n            \" Please install it with\"\n            \" `pip install --upgrade transformers huggingface_hub`.\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-12", "text": "\" `pip install --upgrade transformers huggingface_hub`.\"\n        )\n    hf_tool = load_tool(\n        task_or_repo_id,\n        model_repo_id=model_repo_id,\n        token=token,\n        remote=remote,\n        **kwargs,\n    )\n    outputs = hf_tool.outputs\n    if set(outputs) != {\"text\"}:\n        raise NotImplementedError(\"Multimodal outputs not supported yet.\")\n    inputs = hf_tool.inputs\n    if set(inputs) != {\"text\"}:\n        raise NotImplementedError(\"Multimodal inputs not supported yet.\")\n    return Tool.from_function(\n        hf_tool.__call__, name=hf_tool.name, description=hf_tool.description\n    )\n[docs]def load_tools(\n    tool_names: List[str],\n    llm: Optional[BaseLanguageModel] = None,\n    callbacks: Callbacks = None,\n    **kwargs: Any,\n) -> List[BaseTool]:\n    \"\"\"Load tools based on their name.\n    Tools allow agents to interact with various resources and services like\n    APIs, databases, file systems, etc.\n    Please scope the permissions of each tools to the minimum required for the\n    application.\n    For example, if an application only needs to read from a database,\n    the database tool should not be given write permissions. Moreover\n    consider scoping the permissions to only allow accessing specific\n    tables and impose user-level quota for limiting resource usage.\n    Please read the APIs of the individual tools to determine which configuration\n    they support.\n    See [Security](https://python.langchain.com/docs/security) for more information.\n    Args:\n        tool_names: name of tools to load.\n        llm: An optional language model, may be needed to initialize certain tools.\n        callbacks: Optional callback manager or list of callback handlers.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-13", "text": "callbacks: Optional callback manager or list of callback handlers.\n            If not provided, default global callback manager will be used.\n    Returns:\n        List of tools.\n    \"\"\"\n    tools = []\n    callbacks = _handle_callbacks(\n        callback_manager=kwargs.get(\"callback_manager\"), callbacks=callbacks\n    )\n    for name in tool_names:\n        if name == \"requests\":\n            warnings.warn(\n                \"tool name `requests` is deprecated - \"\n                \"please use `requests_all` or specify the requests method\"\n            )\n        if name == \"requests_all\":\n            # expand requests into various methods\n            requests_method_tools = [\n                _tool for _tool in _BASE_TOOLS if _tool.startswith(\"requests_\")\n            ]\n            tool_names.extend(requests_method_tools)\n        elif name in _BASE_TOOLS:\n            tools.append(_BASE_TOOLS[name]())\n        elif name in _LLM_TOOLS:\n            if llm is None:\n                raise ValueError(f\"Tool {name} requires an LLM to be provided\")\n            tool = _LLM_TOOLS[name](llm)\n            tools.append(tool)\n        elif name in _EXTRA_LLM_TOOLS:\n            if llm is None:\n                raise ValueError(f\"Tool {name} requires an LLM to be provided\")\n            _get_llm_tool_func, extra_keys = _EXTRA_LLM_TOOLS[name]\n            missing_keys = set(extra_keys).difference(kwargs)\n            if missing_keys:\n                raise ValueError(\n                    f\"Tool {name} requires some parameters that were not \"\n                    f\"provided: {missing_keys}\"\n                )\n            sub_kwargs = {k: kwargs[k] for k in extra_keys}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "1cdc3a081cec-14", "text": ")\n            sub_kwargs = {k: kwargs[k] for k in extra_keys}\n            tool = _get_llm_tool_func(llm=llm, **sub_kwargs)\n            tools.append(tool)\n        elif name in _EXTRA_OPTIONAL_TOOLS:\n            _get_tool_func, extra_keys = _EXTRA_OPTIONAL_TOOLS[name]\n            sub_kwargs = {k: kwargs[k] for k in extra_keys if k in kwargs}\n            tool = _get_tool_func(**sub_kwargs)\n            tools.append(tool)\n        else:\n            raise ValueError(f\"Got unknown tool {name}\")\n    if callbacks is not None:\n        for tool in tools:\n            tool.callbacks = callbacks\n    return tools\n[docs]def get_all_tool_names() -> List[str]:\n    \"\"\"Get a list of all possible tool names.\"\"\"\n    return (\n        list(_BASE_TOOLS)\n        + list(_EXTRA_OPTIONAL_TOOLS)\n        + list(_EXTRA_LLM_TOOLS)\n        + list(_LLM_TOOLS)\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html"}
{"id": "d9e0d3e4936a-0", "text": "Source code for langchain.agents.schema\nfrom typing import Any, Dict, List, Tuple\nfrom langchain.prompts.chat import ChatPromptTemplate\nfrom langchain.schema import AgentAction\n[docs]class AgentScratchPadChatPromptTemplate(ChatPromptTemplate):\n    \"\"\"Chat prompt template for the agent scratchpad.\"\"\"\n    def _construct_agent_scratchpad(\n        self, intermediate_steps: List[Tuple[AgentAction, str]]\n    ) -> str:\n        if len(intermediate_steps) == 0:\n            return \"\"\n        thoughts = \"\"\n        for action, observation in intermediate_steps:\n            thoughts += action.log\n            thoughts += f\"\\nObservation: {observation}\\nThought: \"\n        return (\n            f\"This was your previous work \"\n            f\"(but I haven't seen any of it! I only see what \"\n            f\"you return as final answer):\\n{thoughts}\"\n        )\n    def _merge_partial_and_user_variables(self, **kwargs: Any) -> Dict[str, Any]:\n        intermediate_steps = kwargs.pop(\"intermediate_steps\")\n        kwargs[\"agent_scratchpad\"] = self._construct_agent_scratchpad(\n            intermediate_steps\n        )\n        return kwargs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/schema.html"}
{"id": "15864a0009ca-0", "text": "Source code for langchain.agents.initialize\n\"\"\"Load agent.\"\"\"\nfrom typing import Any, Optional, Sequence\nfrom langchain.agents.agent import AgentExecutor\nfrom langchain.agents.agent_types import AgentType\nfrom langchain.agents.loading import AGENT_TO_CLASS, load_agent\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools.base import BaseTool\n[docs]def initialize_agent(\n    tools: Sequence[BaseTool],\n    llm: BaseLanguageModel,\n    agent: Optional[AgentType] = None,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    agent_path: Optional[str] = None,\n    agent_kwargs: Optional[dict] = None,\n    *,\n    tags: Optional[Sequence[str]] = None,\n    **kwargs: Any,\n) -> AgentExecutor:\n    \"\"\"Load an agent executor given tools and LLM.\n    Args:\n        tools: List of tools this agent has access to.\n        llm: Language model to use as the agent.\n        agent: Agent type to use. If None and agent_path is also None, will default to\n            AgentType.ZERO_SHOT_REACT_DESCRIPTION.\n        callback_manager: CallbackManager to use. Global callback manager is used if\n            not provided. Defaults to None.\n        agent_path: Path to serialized agent to use.\n        agent_kwargs: Additional keyword arguments to pass to the underlying agent\n        tags: Tags to apply to the traced runs.\n        **kwargs: Additional keyword arguments passed to the agent executor\n    Returns:\n        An agent executor\n    \"\"\"\n    tags_ = list(tags) if tags else []\n    if agent is None and agent_path is None:\n        agent = AgentType.ZERO_SHOT_REACT_DESCRIPTION", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/initialize.html"}
{"id": "15864a0009ca-1", "text": "agent = AgentType.ZERO_SHOT_REACT_DESCRIPTION\n    if agent is not None and agent_path is not None:\n        raise ValueError(\n            \"Both `agent` and `agent_path` are specified, \"\n            \"but at most only one should be.\"\n        )\n    if agent is not None:\n        if agent not in AGENT_TO_CLASS:\n            raise ValueError(\n                f\"Got unknown agent type: {agent}. \"\n                f\"Valid types are: {AGENT_TO_CLASS.keys()}.\"\n            )\n        tags_.append(agent.value if isinstance(agent, AgentType) else agent)\n        agent_cls = AGENT_TO_CLASS[agent]\n        agent_kwargs = agent_kwargs or {}\n        agent_obj = agent_cls.from_llm_and_tools(\n            llm, tools, callback_manager=callback_manager, **agent_kwargs\n        )\n    elif agent_path is not None:\n        agent_obj = load_agent(\n            agent_path, llm=llm, tools=tools, callback_manager=callback_manager\n        )\n        try:\n            # TODO: Add tags from the serialized object directly.\n            tags_.append(agent_obj._agent_type)\n        except NotImplementedError:\n            pass\n    else:\n        raise ValueError(\n            \"Somehow both `agent` and `agent_path` are None, \"\n            \"this should never happen.\"\n        )\n    return AgentExecutor.from_agent_and_tools(\n        agent=agent_obj,\n        tools=tools,\n        callback_manager=callback_manager,\n        tags=tags_,\n        **kwargs,\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/initialize.html"}
{"id": "a47cfa8c9416-0", "text": "Source code for langchain.agents.utils\nfrom typing import Sequence\nfrom langchain.tools.base import BaseTool\n[docs]def validate_tools_single_input(class_name: str, tools: Sequence[BaseTool]) -> None:\n    \"\"\"Validate tools for single input.\"\"\"\n    for tool in tools:\n        if not tool.is_single_input:\n            raise ValueError(\n                f\"{class_name} does not support multi-input tool {tool.name}.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/utils.html"}
{"id": "2c3dd313aa3c-0", "text": "Source code for langchain.agents.loading\n\"\"\"Functionality for loading agents.\"\"\"\nimport json\nimport logging\nfrom pathlib import Path\nfrom typing import Any, List, Optional, Union\nimport yaml\nfrom langchain.agents.agent import BaseMultiActionAgent, BaseSingleActionAgent\nfrom langchain.agents.tools import Tool\nfrom langchain.agents.types import AGENT_TO_CLASS\nfrom langchain.chains.loading import load_chain, load_chain_from_config\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.utilities.loading import try_load_from_hub\nlogger = logging.getLogger(__file__)\nURL_BASE = \"https://raw.githubusercontent.com/hwchase17/langchain-hub/master/agents/\"\ndef _load_agent_from_tools(\n    config: dict, llm: BaseLanguageModel, tools: List[Tool], **kwargs: Any\n) -> Union[BaseSingleActionAgent, BaseMultiActionAgent]:\n    config_type = config.pop(\"_type\")\n    if config_type not in AGENT_TO_CLASS:\n        raise ValueError(f\"Loading {config_type} agent not supported\")\n    agent_cls = AGENT_TO_CLASS[config_type]\n    combined_config = {**config, **kwargs}\n    return agent_cls.from_llm_and_tools(llm, tools, **combined_config)\n[docs]def load_agent_from_config(\n    config: dict,\n    llm: Optional[BaseLanguageModel] = None,\n    tools: Optional[List[Tool]] = None,\n    **kwargs: Any,\n) -> Union[BaseSingleActionAgent, BaseMultiActionAgent]:\n    \"\"\"Load agent from Config Dict.\n    Args:\n        config: Config dict to load agent from.\n        llm: Language model to use as the agent.\n        tools: List of tools this agent has access to.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html"}
{"id": "2c3dd313aa3c-1", "text": "tools: List of tools this agent has access to.\n        **kwargs: Additional keyword arguments passed to the agent executor.\n    Returns:\n        An agent executor.\n    \"\"\"\n    if \"_type\" not in config:\n        raise ValueError(\"Must specify an agent Type in config\")\n    load_from_tools = config.pop(\"load_from_llm_and_tools\", False)\n    if load_from_tools:\n        if llm is None:\n            raise ValueError(\n                \"If `load_from_llm_and_tools` is set to True, \"\n                \"then LLM must be provided\"\n            )\n        if tools is None:\n            raise ValueError(\n                \"If `load_from_llm_and_tools` is set to True, \"\n                \"then tools must be provided\"\n            )\n        return _load_agent_from_tools(config, llm, tools, **kwargs)\n    config_type = config.pop(\"_type\")\n    if config_type not in AGENT_TO_CLASS:\n        raise ValueError(f\"Loading {config_type} agent not supported\")\n    agent_cls = AGENT_TO_CLASS[config_type]\n    if \"llm_chain\" in config:\n        config[\"llm_chain\"] = load_chain_from_config(config.pop(\"llm_chain\"))\n    elif \"llm_chain_path\" in config:\n        config[\"llm_chain\"] = load_chain(config.pop(\"llm_chain_path\"))\n    else:\n        raise ValueError(\"One of `llm_chain` and `llm_chain_path` should be specified.\")\n    if \"output_parser\" in config:\n        logger.warning(\n            \"Currently loading output parsers on agent is not supported, \"\n            \"will just use the default one.\"\n        )\n        del config[\"output_parser\"]\n    combined_config = {**config, **kwargs}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html"}
{"id": "2c3dd313aa3c-2", "text": "del config[\"output_parser\"]\n    combined_config = {**config, **kwargs}\n    return agent_cls(**combined_config)  # type: ignore\n[docs]def load_agent(\n    path: Union[str, Path], **kwargs: Any\n) -> Union[BaseSingleActionAgent, BaseMultiActionAgent]:\n    \"\"\"Unified method for loading an agent from LangChainHub or local fs.\n    Args:\n        path: Path to the agent file.\n        **kwargs: Additional keyword arguments passed to the agent executor.\n    Returns:\n        An agent executor.\n    \"\"\"\n    valid_suffixes = {\"json\", \"yaml\"}\n    if hub_result := try_load_from_hub(\n        path, _load_agent_from_file, \"agents\", valid_suffixes\n    ):\n        return hub_result\n    else:\n        return _load_agent_from_file(path, **kwargs)\ndef _load_agent_from_file(\n    file: Union[str, Path], **kwargs: Any\n) -> Union[BaseSingleActionAgent, BaseMultiActionAgent]:\n    \"\"\"Load agent from file.\"\"\"\n    valid_suffixes = {\"json\", \"yaml\"}\n    # Convert file to Path object.\n    if isinstance(file, str):\n        file_path = Path(file)\n    else:\n        file_path = file\n    # Load from either json or yaml.\n    if file_path.suffix[1:] == \"json\":\n        with open(file_path) as f:\n            config = json.load(f)\n    elif file_path.suffix[1:] == \"yaml\":\n        with open(file_path, \"r\") as f:\n            config = yaml.safe_load(f)\n    else:\n        raise ValueError(f\"Unsupported file type, must be one of {valid_suffixes}.\")\n    # Load the agent from the config now.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html"}
{"id": "2c3dd313aa3c-3", "text": "# Load the agent from the config now.\n    return load_agent_from_config(config, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html"}
{"id": "56a059692dee-0", "text": "Source code for langchain.agents.agent_iterator\nfrom __future__ import annotations\nimport logging\nimport time\nfrom abc import ABC, abstractmethod\nfrom asyncio import CancelledError\nfrom functools import wraps\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    List,\n    NoReturn,\n    Optional,\n    Tuple,\n    Type,\n    Union,\n)\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManager,\n    AsyncCallbackManagerForChainRun,\n    CallbackManager,\n    CallbackManagerForChainRun,\n    Callbacks,\n)\nfrom langchain.load.dump import dumpd\nfrom langchain.schema import RUN_KEY, AgentAction, AgentFinish, RunInfo\nfrom langchain.tools import BaseTool\nfrom langchain.utilities.asyncio import asyncio_timeout\nfrom langchain.utils.input import get_color_mapping\nif TYPE_CHECKING:\n    from langchain.agents.agent import AgentExecutor\nlogger = logging.getLogger(__name__)\n[docs]class BaseAgentExecutorIterator(ABC):\n    \"\"\"Base class for AgentExecutorIterator.\"\"\"\n[docs]    @abstractmethod\n    def build_callback_manager(self) -> None:\n        pass\n[docs]def rebuild_callback_manager_on_set(\n    setter_method: Callable[..., None]\n) -> Callable[..., None]:\n    \"\"\"Decorator to force setters to rebuild callback mgr\"\"\"\n    @wraps(setter_method)\n    def wrapper(self: BaseAgentExecutorIterator, *args: Any, **kwargs: Any) -> None:\n        setter_method(self, *args, **kwargs)\n        self.build_callback_manager()\n    return wrapper\n[docs]class AgentExecutorIterator(BaseAgentExecutorIterator):\n    \"\"\"Iterator for AgentExecutor.\"\"\"\n[docs]    def __init__(\n        self,\n        agent_executor: AgentExecutor,\n        inputs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html"}
{"id": "56a059692dee-1", "text": "self,\n        agent_executor: AgentExecutor,\n        inputs: Any,\n        callbacks: Callbacks = None,\n        *,\n        tags: Optional[list[str]] = None,\n        include_run_info: bool = False,\n        async_: bool = False,\n    ):\n        \"\"\"\n        Initialize the AgentExecutorIterator with the given AgentExecutor,\n        inputs, and optional callbacks.\n        \"\"\"\n        self._agent_executor = agent_executor\n        self.inputs = inputs\n        self.async_ = async_\n        # build callback manager on tags setter\n        self._callbacks = callbacks\n        self.tags = tags\n        self.include_run_info = include_run_info\n        self.run_manager = None\n        self.reset()\n    _callback_manager: Union[AsyncCallbackManager, CallbackManager]\n    _inputs: dict[str, str]\n    _final_outputs: Optional[dict[str, str]]\n    run_manager: Optional[\n        Union[AsyncCallbackManagerForChainRun, CallbackManagerForChainRun]\n    ]\n    timeout_manager: Any  # TODO: Fix a type here; the shim makes it tricky.\n    @property\n    def inputs(self) -> dict[str, str]:\n        return self._inputs\n    @inputs.setter\n    def inputs(self, inputs: Any) -> None:\n        self._inputs = self.agent_executor.prep_inputs(inputs)\n    @property\n    def callbacks(self) -> Callbacks:\n        return self._callbacks\n    @callbacks.setter\n    @rebuild_callback_manager_on_set\n    def callbacks(self, callbacks: Callbacks) -> None:\n        \"\"\"When callbacks are changed after __init__, rebuild callback mgr\"\"\"\n        self._callbacks = callbacks\n    @property\n    def tags(self) -> Optional[List[str]]:\n        return self._tags\n    @tags.setter", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html"}
{"id": "56a059692dee-2", "text": "return self._tags\n    @tags.setter\n    @rebuild_callback_manager_on_set\n    def tags(self, tags: Optional[List[str]]) -> None:\n        \"\"\"When tags are changed after __init__, rebuild callback mgr\"\"\"\n        self._tags = tags\n    @property\n    def agent_executor(self) -> AgentExecutor:\n        return self._agent_executor\n    @agent_executor.setter\n    @rebuild_callback_manager_on_set\n    def agent_executor(self, agent_executor: AgentExecutor) -> None:\n        self._agent_executor = agent_executor\n        # force re-prep inputs in case agent_executor's prep_inputs fn changed\n        self.inputs = self.inputs\n    @property\n    def callback_manager(self) -> Union[AsyncCallbackManager, CallbackManager]:\n        return self._callback_manager\n[docs]    def build_callback_manager(self) -> None:\n        \"\"\"\n        Create and configure the callback manager based on the current\n        callbacks and tags.\n        \"\"\"\n        CallbackMgr: Union[Type[AsyncCallbackManager], Type[CallbackManager]] = (\n            AsyncCallbackManager if self.async_ else CallbackManager\n        )\n        self._callback_manager = CallbackMgr.configure(\n            self.callbacks,\n            self.agent_executor.callbacks,\n            self.agent_executor.verbose,\n            self.tags,\n            self.agent_executor.tags,\n        )\n    @property\n    def name_to_tool_map(self) -> dict[str, BaseTool]:\n        return {tool.name: tool for tool in self.agent_executor.tools}\n    @property\n    def color_mapping(self) -> dict[str, str]:\n        return get_color_mapping(\n            [tool.name for tool in self.agent_executor.tools],\n            excluded_colors=[\"green\", \"red\"],\n        )\n[docs]    def reset(self) -> None:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html"}
{"id": "56a059692dee-3", "text": ")\n[docs]    def reset(self) -> None:\n        \"\"\"\n        Reset the iterator to its initial state, clearing intermediate steps,\n        iterations, and time elapsed.\n        \"\"\"\n        logger.debug(\"(Re)setting AgentExecutorIterator to fresh state\")\n        self.intermediate_steps: list[tuple[AgentAction, str]] = []\n        self.iterations = 0\n        # maybe better to start these on the first __anext__ call?\n        self.time_elapsed = 0.0\n        self.start_time = time.time()\n        self._final_outputs = None\n[docs]    def update_iterations(self) -> None:\n        \"\"\"\n        Increment the number of iterations and update the time elapsed.\n        \"\"\"\n        self.iterations += 1\n        self.time_elapsed = time.time() - self.start_time\n        logger.debug(\n            f\"Agent Iterations: {self.iterations} ({self.time_elapsed:.2f}s elapsed)\"\n        )\n[docs]    def raise_stopiteration(self, output: Any) -> NoReturn:\n        \"\"\"\n        Raise a StopIteration exception with the given output.\n        \"\"\"\n        logger.debug(\"Chain end: stop iteration\")\n        raise StopIteration(output)\n[docs]    async def raise_stopasynciteration(self, output: Any) -> NoReturn:\n        \"\"\"\n        Raise a StopAsyncIteration exception with the given output.\n        Close the timeout context manager.\n        \"\"\"\n        logger.debug(\"Chain end: stop async iteration\")\n        if self.timeout_manager is not None:\n            await self.timeout_manager.__aexit__(None, None, None)\n        raise StopAsyncIteration(output)\n    @property\n    def final_outputs(self) -> Optional[dict[str, Any]]:\n        return self._final_outputs\n    @final_outputs.setter", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html"}
{"id": "56a059692dee-4", "text": "return self._final_outputs\n    @final_outputs.setter\n    def final_outputs(self, outputs: Optional[Dict[str, Any]]) -> None:\n        # have access to intermediate steps by design in iterator,\n        # so return only outputs may as well always be true.\n        self._final_outputs = None\n        if outputs:\n            prepared_outputs: dict[str, Any] = self.agent_executor.prep_outputs(\n                self.inputs, outputs, return_only_outputs=True\n            )\n            if self.include_run_info and self.run_manager is not None:\n                logger.debug(\"Assign run key\")\n                prepared_outputs[RUN_KEY] = RunInfo(run_id=self.run_manager.run_id)\n            self._final_outputs = prepared_outputs\n    def __iter__(self: \"AgentExecutorIterator\") -> \"AgentExecutorIterator\":\n        logger.debug(\"Initialising AgentExecutorIterator\")\n        self.reset()\n        assert isinstance(self.callback_manager, CallbackManager)\n        self.run_manager = self.callback_manager.on_chain_start(\n            dumpd(self.agent_executor),\n            self.inputs,\n        )\n        return self\n    def __aiter__(self) -> \"AgentExecutorIterator\":\n        \"\"\"\n        N.B. __aiter__ must be a normal method, so need to initialise async run manager\n        on first __anext__ call where we can await it\n        \"\"\"\n        logger.debug(\"Initialising AgentExecutorIterator (async)\")\n        self.reset()\n        if self.agent_executor.max_execution_time:\n            self.timeout_manager = asyncio_timeout(\n                self.agent_executor.max_execution_time\n            )\n        else:\n            self.timeout_manager = None\n        return self\n    def _on_first_step(self) -> None:\n        \"\"\"\n        Perform any necessary setup for the first step of the synchronous iterator.\n        \"\"\"\n        pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html"}
{"id": "56a059692dee-5", "text": "\"\"\"\n        pass\n    async def _on_first_async_step(self) -> None:\n        \"\"\"\n        Perform any necessary setup for the first step of the asynchronous iterator.\n        \"\"\"\n        # on first step, need to await callback manager and start async timeout ctxmgr\n        if self.iterations == 0:\n            assert isinstance(self.callback_manager, AsyncCallbackManager)\n            self.run_manager = await self.callback_manager.on_chain_start(\n                dumpd(self.agent_executor),\n                self.inputs,\n            )\n            if self.timeout_manager:\n                await self.timeout_manager.__aenter__()\n    def __next__(self) -> dict[str, Any]:\n        \"\"\"\n        AgentExecutor               AgentExecutorIterator\n        __call__                    (__iter__ ->) __next__\n            _call              <=>      _call_next\n                _take_next_step             _take_next_step\n        \"\"\"\n        # first step\n        if self.iterations == 0:\n            self._on_first_step()\n        # N.B. timeout taken care of by \"_should_continue\" in sync case\n        try:\n            return self._call_next()\n        except StopIteration:\n            raise\n        except BaseException as e:\n            if self.run_manager:\n                self.run_manager.on_chain_error(e)\n            raise\n    async def __anext__(self) -> dict[str, Any]:\n        \"\"\"\n        AgentExecutor               AgentExecutorIterator\n        acall                       (__aiter__ ->) __anext__\n            _acall              <=>     _acall_next\n                _atake_next_step            _atake_next_step\n        \"\"\"\n        if self.iterations == 0:\n            await self._on_first_async_step()\n        try:\n            return await self._acall_next()\n        except StopAsyncIteration:\n            raise", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html"}
{"id": "56a059692dee-6", "text": "return await self._acall_next()\n        except StopAsyncIteration:\n            raise\n        except (TimeoutError, CancelledError):\n            await self.timeout_manager.__aexit__(None, None, None)\n            self.timeout_manager = None\n            return await self._astop()\n        except BaseException as e:\n            if self.run_manager:\n                assert isinstance(self.run_manager, AsyncCallbackManagerForChainRun)\n                await self.run_manager.on_chain_error(e)\n            raise\n    def _execute_next_step(\n        self, run_manager: Optional[CallbackManagerForChainRun]\n    ) -> Union[AgentFinish, List[Tuple[AgentAction, str]]]:\n        \"\"\"\n        Execute the next step in the chain using the\n        AgentExecutor's _take_next_step method.\n        \"\"\"\n        return self.agent_executor._take_next_step(\n            self.name_to_tool_map,\n            self.color_mapping,\n            self.inputs,\n            self.intermediate_steps,\n            run_manager=run_manager,\n        )\n    async def _execute_next_async_step(\n        self, run_manager: Optional[AsyncCallbackManagerForChainRun]\n    ) -> Union[AgentFinish, List[Tuple[AgentAction, str]]]:\n        \"\"\"\n        Execute the next step in the chain using the\n        AgentExecutor's _atake_next_step method.\n        \"\"\"\n        return await self.agent_executor._atake_next_step(\n            self.name_to_tool_map,\n            self.color_mapping,\n            self.inputs,\n            self.intermediate_steps,\n            run_manager=run_manager,\n        )\n    def _process_next_step_output(\n        self,\n        next_step_output: Union[AgentFinish, List[Tuple[AgentAction, str]]],\n        run_manager: Optional[CallbackManagerForChainRun],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html"}
{"id": "56a059692dee-7", "text": "run_manager: Optional[CallbackManagerForChainRun],\n    ) -> Dict[str, Union[str, List[Tuple[AgentAction, str]]]]:\n        \"\"\"\n        Process the output of the next step,\n        handling AgentFinish and tool return cases.\n        \"\"\"\n        logger.debug(\"Processing output of Agent loop step\")\n        if isinstance(next_step_output, AgentFinish):\n            logger.debug(\n                \"Hit AgentFinish: _return -> on_chain_end -> run final output logic\"\n            )\n            output = self.agent_executor._return(\n                next_step_output, self.intermediate_steps, run_manager=run_manager\n            )\n            if self.run_manager:\n                self.run_manager.on_chain_end(output)\n            self.final_outputs = output\n            return output\n        self.intermediate_steps.extend(next_step_output)\n        logger.debug(\"Updated intermediate_steps with step output\")\n        # Check for tool return\n        if len(next_step_output) == 1:\n            next_step_action = next_step_output[0]\n            tool_return = self.agent_executor._get_tool_return(next_step_action)\n            if tool_return is not None:\n                output = self.agent_executor._return(\n                    tool_return, self.intermediate_steps, run_manager=run_manager\n                )\n                if self.run_manager:\n                    self.run_manager.on_chain_end(output)\n                self.final_outputs = output\n                return output\n        output = {\"intermediate_step\": next_step_output}\n        return output\n    async def _aprocess_next_step_output(\n        self,\n        next_step_output: Union[AgentFinish, List[Tuple[AgentAction, str]]],\n        run_manager: Optional[AsyncCallbackManagerForChainRun],\n    ) -> Dict[str, Union[str, List[Tuple[AgentAction, str]]]]:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html"}
{"id": "56a059692dee-8", "text": "\"\"\"\n        Process the output of the next async step,\n        handling AgentFinish and tool return cases.\n        \"\"\"\n        logger.debug(\"Processing output of async Agent loop step\")\n        if isinstance(next_step_output, AgentFinish):\n            logger.debug(\n                \"Hit AgentFinish: _areturn -> on_chain_end -> run final output logic\"\n            )\n            output = await self.agent_executor._areturn(\n                next_step_output, self.intermediate_steps, run_manager=run_manager\n            )\n            if run_manager:\n                await run_manager.on_chain_end(output)\n            self.final_outputs = output\n            return output\n        self.intermediate_steps.extend(next_step_output)\n        logger.debug(\"Updated intermediate_steps with step output\")\n        # Check for tool return\n        if len(next_step_output) == 1:\n            next_step_action = next_step_output[0]\n            tool_return = self.agent_executor._get_tool_return(next_step_action)\n            if tool_return is not None:\n                output = await self.agent_executor._areturn(\n                    tool_return, self.intermediate_steps, run_manager=run_manager\n                )\n                if run_manager:\n                    await run_manager.on_chain_end(output)\n                self.final_outputs = output\n                return output\n        output = {\"intermediate_step\": next_step_output}\n        return output\n    def _stop(self) -> dict[str, Any]:\n        \"\"\"\n        Stop the iterator and raise a StopIteration exception with the stopped response.\n        \"\"\"\n        logger.warning(\"Stopping agent prematurely due to triggering stop condition\")\n        # this manually constructs agent finish with output key\n        output = self.agent_executor.agent.return_stopped_response(\n            self.agent_executor.early_stopping_method,\n            self.intermediate_steps,\n            **self.inputs,\n        )\n        assert (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html"}
{"id": "56a059692dee-9", "text": "self.intermediate_steps,\n            **self.inputs,\n        )\n        assert (\n            isinstance(self.run_manager, CallbackManagerForChainRun)\n            or self.run_manager is None\n        )\n        returned_output = self.agent_executor._return(\n            output, self.intermediate_steps, run_manager=self.run_manager\n        )\n        self.final_outputs = returned_output\n        return returned_output\n    async def _astop(self) -> dict[str, Any]:\n        \"\"\"\n        Stop the async iterator and raise a StopAsyncIteration exception with\n        the stopped response.\n        \"\"\"\n        logger.warning(\"Stopping agent prematurely due to triggering stop condition\")\n        output = self.agent_executor.agent.return_stopped_response(\n            self.agent_executor.early_stopping_method,\n            self.intermediate_steps,\n            **self.inputs,\n        )\n        assert (\n            isinstance(self.run_manager, AsyncCallbackManagerForChainRun)\n            or self.run_manager is None\n        )\n        returned_output = await self.agent_executor._areturn(\n            output, self.intermediate_steps, run_manager=self.run_manager\n        )\n        self.final_outputs = returned_output\n        return returned_output\n    def _call_next(self) -> dict[str, Any]:\n        \"\"\"\n        Perform a single iteration of the synchronous AgentExecutorIterator.\n        \"\"\"\n        # final output already reached: stopiteration (final output)\n        if self.final_outputs is not None:\n            self.raise_stopiteration(self.final_outputs)\n        # timeout/max iterations: stopiteration (stopped response)\n        if not self.agent_executor._should_continue(self.iterations, self.time_elapsed):\n            return self._stop()\n        assert (\n            isinstance(self.run_manager, CallbackManagerForChainRun)\n            or self.run_manager is None\n        )\n        next_step_output = self._execute_next_step(self.run_manager)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html"}
{"id": "56a059692dee-10", "text": ")\n        next_step_output = self._execute_next_step(self.run_manager)\n        output = self._process_next_step_output(next_step_output, self.run_manager)\n        self.update_iterations()\n        return output\n    async def _acall_next(self) -> dict[str, Any]:\n        \"\"\"\n        Perform a single iteration of the asynchronous AgentExecutorIterator.\n        \"\"\"\n        # final output already reached: stopiteration (final output)\n        if self.final_outputs is not None:\n            await self.raise_stopasynciteration(self.final_outputs)\n        # timeout/max iterations: stopiteration (stopped response)\n        if not self.agent_executor._should_continue(self.iterations, self.time_elapsed):\n            return await self._astop()\n        assert (\n            isinstance(self.run_manager, AsyncCallbackManagerForChainRun)\n            or self.run_manager is None\n        )\n        next_step_output = await self._execute_next_async_step(self.run_manager)\n        output = await self._aprocess_next_step_output(\n            next_step_output, self.run_manager\n        )\n        self.update_iterations()\n        return output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html"}
{"id": "859cebb5958a-0", "text": "Source code for langchain.agents.tools\n\"\"\"Interface for tools.\"\"\"\nfrom typing import List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForToolRun,\n    CallbackManagerForToolRun,\n)\nfrom langchain.tools.base import BaseTool, Tool, tool\n[docs]class InvalidTool(BaseTool):\n    \"\"\"Tool that is run when invalid tool name is encountered by agent.\"\"\"\n    name: str = \"invalid_tool\"\n    description: str = \"Called when tool name is invalid. Suggests valid tool names.\"\n    def _run(\n        self,\n        requested_tool_name: str,\n        available_tool_names: List[str],\n        run_manager: Optional[CallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool.\"\"\"\n        available_tool_names_str = \", \".join([tool for tool in available_tool_names])\n        return (\n            f\"{requested_tool_name} is not a valid tool, \"\n            f\"try one of [{available_tool_names_str}].\"\n        )\n    async def _arun(\n        self,\n        requested_tool_name: str,\n        available_tool_names: List[str],\n        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,\n    ) -> str:\n        \"\"\"Use the tool asynchronously.\"\"\"\n        available_tool_names_str = \", \".join([tool for tool in available_tool_names])\n        return (\n            f\"{requested_tool_name} is not a valid tool, \"\n            f\"try one of [{available_tool_names_str}].\"\n        )\n__all__ = [\"InvalidTool\", \"BaseTool\", \"tool\", \"Tool\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/tools.html"}
{"id": "1631908ee054-0", "text": "Source code for langchain.agents.conversational.base\n\"\"\"An agent designed to hold a conversation in addition to using tools.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, List, Optional, Sequence\nfrom langchain.agents.agent import Agent, AgentOutputParser\nfrom langchain.agents.agent_types import AgentType\nfrom langchain.agents.conversational.output_parser import ConvoOutputParser\nfrom langchain.agents.conversational.prompt import FORMAT_INSTRUCTIONS, PREFIX, SUFFIX\nfrom langchain.agents.utils import validate_tools_single_input\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains import LLMChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools.base import BaseTool\n[docs]class ConversationalAgent(Agent):\n    \"\"\"An agent that holds a conversation in addition to using tools.\"\"\"\n    ai_prefix: str = \"AI\"\n    \"\"\"Prefix to use before AI output.\"\"\"\n    output_parser: AgentOutputParser = Field(default_factory=ConvoOutputParser)\n    \"\"\"Output parser for the agent.\"\"\"\n    @classmethod\n    def _get_default_output_parser(\n        cls, ai_prefix: str = \"AI\", **kwargs: Any\n    ) -> AgentOutputParser:\n        return ConvoOutputParser(ai_prefix=ai_prefix)\n    @property\n    def _agent_type(self) -> str:\n        \"\"\"Return Identifier of agent type.\"\"\"\n        return AgentType.CONVERSATIONAL_REACT_DESCRIPTION\n    @property\n    def observation_prefix(self) -> str:\n        \"\"\"Prefix to append the observation with.\"\"\"\n        return \"Observation: \"\n    @property\n    def llm_prefix(self) -> str:\n        \"\"\"Prefix to append the llm call with.\"\"\"\n        return \"Thought:\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html"}
{"id": "1631908ee054-1", "text": "\"\"\"Prefix to append the llm call with.\"\"\"\n        return \"Thought:\"\n[docs]    @classmethod\n    def create_prompt(\n        cls,\n        tools: Sequence[BaseTool],\n        prefix: str = PREFIX,\n        suffix: str = SUFFIX,\n        format_instructions: str = FORMAT_INSTRUCTIONS,\n        ai_prefix: str = \"AI\",\n        human_prefix: str = \"Human\",\n        input_variables: Optional[List[str]] = None,\n    ) -> PromptTemplate:\n        \"\"\"Create prompt in the style of the zero-shot agent.\n        Args:\n            tools: List of tools the agent will have access to, used to format the\n                prompt.\n            prefix: String to put before the list of tools.\n            suffix: String to put after the list of tools.\n            ai_prefix: String to use before AI output.\n            human_prefix: String to use before human output.\n            input_variables: List of input variables the final prompt will expect.\n        Returns:\n            A PromptTemplate with the template assembled from the pieces here.\n        \"\"\"\n        tool_strings = \"\\n\".join(\n            [f\"> {tool.name}: {tool.description}\" for tool in tools]\n        )\n        tool_names = \", \".join([tool.name for tool in tools])\n        format_instructions = format_instructions.format(\n            tool_names=tool_names, ai_prefix=ai_prefix, human_prefix=human_prefix\n        )\n        template = \"\\n\\n\".join([prefix, tool_strings, format_instructions, suffix])\n        if input_variables is None:\n            input_variables = [\"input\", \"chat_history\", \"agent_scratchpad\"]\n        return PromptTemplate(template=template, input_variables=input_variables)\n    @classmethod\n    def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html"}
{"id": "1631908ee054-2", "text": "def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:\n        super()._validate_tools(tools)\n        validate_tools_single_input(cls.__name__, tools)\n[docs]    @classmethod\n    def from_llm_and_tools(\n        cls,\n        llm: BaseLanguageModel,\n        tools: Sequence[BaseTool],\n        callback_manager: Optional[BaseCallbackManager] = None,\n        output_parser: Optional[AgentOutputParser] = None,\n        prefix: str = PREFIX,\n        suffix: str = SUFFIX,\n        format_instructions: str = FORMAT_INSTRUCTIONS,\n        ai_prefix: str = \"AI\",\n        human_prefix: str = \"Human\",\n        input_variables: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Agent:\n        \"\"\"Construct an agent from an LLM and tools.\"\"\"\n        cls._validate_tools(tools)\n        prompt = cls.create_prompt(\n            tools,\n            ai_prefix=ai_prefix,\n            human_prefix=human_prefix,\n            prefix=prefix,\n            suffix=suffix,\n            format_instructions=format_instructions,\n            input_variables=input_variables,\n        )\n        llm_chain = LLMChain(\n            llm=llm,\n            prompt=prompt,\n            callback_manager=callback_manager,\n        )\n        tool_names = [tool.name for tool in tools]\n        _output_parser = output_parser or cls._get_default_output_parser(\n            ai_prefix=ai_prefix\n        )\n        return cls(\n            llm_chain=llm_chain,\n            allowed_tools=tool_names,\n            ai_prefix=ai_prefix,\n            output_parser=_output_parser,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html"}
{"id": "9f5b8a241d0b-0", "text": "Source code for langchain.agents.conversational.output_parser\nimport re\nfrom typing import Union\nfrom langchain.agents.agent import AgentOutputParser\nfrom langchain.agents.conversational.prompt import FORMAT_INSTRUCTIONS\nfrom langchain.schema import AgentAction, AgentFinish, OutputParserException\n[docs]class ConvoOutputParser(AgentOutputParser):\n    \"\"\"Output parser for the conversational agent.\"\"\"\n    ai_prefix: str = \"AI\"\n    \"\"\"Prefix to use before AI output.\"\"\"\n[docs]    def get_format_instructions(self) -> str:\n        return FORMAT_INSTRUCTIONS\n[docs]    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        if f\"{self.ai_prefix}:\" in text:\n            return AgentFinish(\n                {\"output\": text.split(f\"{self.ai_prefix}:\")[-1].strip()}, text\n            )\n        regex = r\"Action: (.*?)[\\n]*Action Input: (.*)\"\n        match = re.search(regex, text)\n        if not match:\n            raise OutputParserException(f\"Could not parse LLM output: `{text}`\")\n        action = match.group(1)\n        action_input = match.group(2)\n        return AgentAction(action.strip(), action_input.strip(\" \").strip('\"'), text)\n    @property\n    def _type(self) -> str:\n        return \"conversational\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/conversational/output_parser.html"}
{"id": "cbedca31a27f-0", "text": "Source code for langchain.agents.self_ask_with_search.base\n\"\"\"Chain that does self-ask with search.\"\"\"\nfrom typing import Any, Sequence, Union\nfrom langchain.agents.agent import Agent, AgentExecutor, AgentOutputParser\nfrom langchain.agents.agent_types import AgentType\nfrom langchain.agents.self_ask_with_search.output_parser import SelfAskOutputParser\nfrom langchain.agents.self_ask_with_search.prompt import PROMPT\nfrom langchain.agents.tools import Tool\nfrom langchain.agents.utils import validate_tools_single_input\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools.base import BaseTool\nfrom langchain.utilities.google_serper import GoogleSerperAPIWrapper\nfrom langchain.utilities.serpapi import SerpAPIWrapper\n[docs]class SelfAskWithSearchAgent(Agent):\n    \"\"\"Agent for the self-ask-with-search paper.\"\"\"\n    output_parser: AgentOutputParser = Field(default_factory=SelfAskOutputParser)\n    @classmethod\n    def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:\n        return SelfAskOutputParser()\n    @property\n    def _agent_type(self) -> str:\n        \"\"\"Return Identifier of an agent type.\"\"\"\n        return AgentType.SELF_ASK_WITH_SEARCH\n[docs]    @classmethod\n    def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate:\n        \"\"\"Prompt does not depend on tools.\"\"\"\n        return PROMPT\n    @classmethod\n    def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:\n        validate_tools_single_input(cls.__name__, tools)\n        super()._validate_tools(tools)\n        if len(tools) != 1:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html"}
{"id": "cbedca31a27f-1", "text": "super()._validate_tools(tools)\n        if len(tools) != 1:\n            raise ValueError(f\"Exactly one tool must be specified, but got {tools}\")\n        tool_names = {tool.name for tool in tools}\n        if tool_names != {\"Intermediate Answer\"}:\n            raise ValueError(\n                f\"Tool name should be Intermediate Answer, got {tool_names}\"\n            )\n    @property\n    def observation_prefix(self) -> str:\n        \"\"\"Prefix to append the observation with.\"\"\"\n        return \"Intermediate answer: \"\n    @property\n    def llm_prefix(self) -> str:\n        \"\"\"Prefix to append the LLM call with.\"\"\"\n        return \"\"\n[docs]class SelfAskWithSearchChain(AgentExecutor):\n    \"\"\"[Deprecated] Chain that does self-ask with search.\"\"\"\n    def __init__(\n        self,\n        llm: BaseLanguageModel,\n        search_chain: Union[GoogleSerperAPIWrapper, SerpAPIWrapper],\n        **kwargs: Any,\n    ):\n        \"\"\"Initialize only with an LLM and a search chain.\"\"\"\n        search_tool = Tool(\n            name=\"Intermediate Answer\",\n            func=search_chain.run,\n            coroutine=search_chain.arun,\n            description=\"Search\",\n        )\n        agent = SelfAskWithSearchAgent.from_llm_and_tools(llm, [search_tool])\n        super().__init__(agent=agent, tools=[search_tool], **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html"}
{"id": "6317ad2ee89a-0", "text": "Source code for langchain.agents.output_parsers.react_single_input\nimport re\nfrom typing import Union\nfrom langchain.agents.agent import AgentOutputParser\nfrom langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS\nfrom langchain.schema import AgentAction, AgentFinish, OutputParserException\nFINAL_ANSWER_ACTION = \"Final Answer:\"\nMISSING_ACTION_AFTER_THOUGHT_ERROR_MESSAGE = (\n    \"Invalid Format: Missing 'Action:' after 'Thought:\"\n)\nMISSING_ACTION_INPUT_AFTER_ACTION_ERROR_MESSAGE = (\n    \"Invalid Format: Missing 'Action Input:' after 'Action:'\"\n)\nFINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE = (\n    \"Parsing LLM output produced both a final answer and a parse-able action:\"\n)\n[docs]class ReActSingleInputOutputParser(AgentOutputParser):\n    \"\"\"Parses ReAct-style LLM calls that have a single tool input.\n    Expects output to be in one of two formats.\n    If the output signals that an action should be taken,\n    should be in the below format. This will result in an AgentAction\n    being returned.\n    ```\n    Thought: agent thought here\n    Action: search\n    Action Input: what is the temperature in SF?\n    ```\n    If the output signals that a final answer should be given,\n    should be in the below format. This will result in an AgentFinish\n    being returned.\n    ```\n    Thought: agent thought here\n    Final Answer: The temperature is 100 degrees\n    ```\n    \"\"\"\n[docs]    def get_format_instructions(self) -> str:\n        return FORMAT_INSTRUCTIONS\n[docs]    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        includes_answer = FINAL_ANSWER_ACTION in text\n        regex = (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/react_single_input.html"}
{"id": "6317ad2ee89a-1", "text": "includes_answer = FINAL_ANSWER_ACTION in text\n        regex = (\n            r\"Action\\s*\\d*\\s*:[\\s]*(.*?)[\\s]*Action\\s*\\d*\\s*Input\\s*\\d*\\s*:[\\s]*(.*)\"\n        )\n        action_match = re.search(regex, text, re.DOTALL)\n        if action_match:\n            if includes_answer:\n                raise OutputParserException(\n                    f\"{FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: {text}\"\n                )\n            action = action_match.group(1).strip()\n            action_input = action_match.group(2)\n            tool_input = action_input.strip(\" \")\n            tool_input = tool_input.strip('\"')\n            return AgentAction(action, tool_input, text)\n        elif includes_answer:\n            return AgentFinish(\n                {\"output\": text.split(FINAL_ANSWER_ACTION)[-1].strip()}, text\n            )\n        if not re.search(r\"Action\\s*\\d*\\s*:[\\s]*(.*?)\", text, re.DOTALL):\n            raise OutputParserException(\n                f\"Could not parse LLM output: `{text}`\",\n                observation=MISSING_ACTION_AFTER_THOUGHT_ERROR_MESSAGE,\n                llm_output=text,\n                send_to_llm=True,\n            )\n        elif not re.search(\n            r\"[\\s]*Action\\s*\\d*\\s*Input\\s*\\d*\\s*:[\\s]*(.*)\", text, re.DOTALL\n        ):\n            raise OutputParserException(\n                f\"Could not parse LLM output: `{text}`\",\n                observation=MISSING_ACTION_INPUT_AFTER_ACTION_ERROR_MESSAGE,\n                llm_output=text,\n                send_to_llm=True,\n            )\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/react_single_input.html"}
{"id": "6317ad2ee89a-2", "text": "send_to_llm=True,\n            )\n        else:\n            raise OutputParserException(f\"Could not parse LLM output: `{text}`\")\n    @property\n    def _type(self) -> str:\n        return \"react-single-input\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/react_single_input.html"}
{"id": "90559fe37185-0", "text": "Source code for langchain.agents.output_parsers.json\nfrom __future__ import annotations\nimport logging\nfrom typing import Union\nfrom langchain.agents.agent import AgentOutputParser\nfrom langchain.output_parsers.json import parse_json_markdown\nfrom langchain.schema import AgentAction, AgentFinish, OutputParserException\nlogger = logging.getLogger(__name__)\n[docs]class JSONAgentOutputParser(AgentOutputParser):\n    \"\"\"Parses tool invocations and final answers in JSON format.\n    Expects output to be in one of two formats.\n    If the output signals that an action should be taken,\n    should be in the below format. This will result in an AgentAction\n    being returned.\n    ```\n    {\n      \"action\": \"search\",\n      \"action_input\": \"2+2\"\n    }\n    ```\n    If the output signals that a final answer should be given,\n    should be in the below format. This will result in an AgentFinish\n    being returned.\n    ```\n    {\n      \"action\": \"Final Answer\",\n      \"action_input\": \"4\"\n    }\n    ```\n    \"\"\"\n[docs]    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        try:\n            response = parse_json_markdown(text)\n            if isinstance(response, list):\n                # gpt turbo frequently ignores the directive to emit a single action\n                logger.warning(\"Got multiple action responses: %s\", response)\n                response = response[0]\n            if response[\"action\"] == \"Final Answer\":\n                return AgentFinish({\"output\": response[\"action_input\"]}, text)\n            else:\n                return AgentAction(\n                    response[\"action\"], response.get(\"action_input\", {}), text\n                )\n        except Exception as e:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/json.html"}
{"id": "90559fe37185-1", "text": ")\n        except Exception as e:\n            raise OutputParserException(f\"Could not parse LLM output: {text}\") from e\n    @property\n    def _type(self) -> str:\n        return \"json-agent\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/json.html"}
{"id": "9069d8de205f-0", "text": "Source code for langchain.agents.output_parsers.openai_tools\nimport asyncio\nimport json\nfrom json import JSONDecodeError\nfrom typing import List, Union\nfrom langchain.agents.agent import MultiActionAgentOutputParser\nfrom langchain.schema import (\n    AgentAction,\n    AgentFinish,\n    OutputParserException,\n)\nfrom langchain.schema.agent import AgentActionMessageLog\nfrom langchain.schema.messages import (\n    AIMessage,\n    BaseMessage,\n)\nfrom langchain.schema.output import ChatGeneration, Generation\n[docs]class OpenAIToolAgentAction(AgentActionMessageLog):\n    tool_call_id: str\n    \"\"\"Tool call that this message is responding to.\"\"\"\n[docs]def parse_ai_message_to_openai_tool_action(\n    message: BaseMessage\n) -> Union[List[AgentAction], AgentFinish]:\n    \"\"\"Parse an AI message potentially containing tool_calls.\"\"\"\n    if not isinstance(message, AIMessage):\n        raise TypeError(f\"Expected an AI message got {type(message)}\")\n    if not message.additional_kwargs.get(\"tool_calls\"):\n        return AgentFinish(\n            return_values={\"output\": message.content}, log=str(message.content)\n        )\n    actions: List = []\n    for tool_call in message.additional_kwargs[\"tool_calls\"]:\n        function = tool_call[\"function\"]\n        function_name = function[\"name\"]\n        try:\n            _tool_input = json.loads(function[\"arguments\"])\n        except JSONDecodeError:\n            raise OutputParserException(\n                f\"Could not parse tool input: {function} because \"\n                f\"the `arguments` is not valid JSON.\"\n            )\n        # HACK HACK HACK:\n        # The code that encodes tool input into Open AI uses a special variable\n        # name called `__arg1` to handle old style tools that do not expose a", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/openai_tools.html"}
{"id": "9069d8de205f-1", "text": "# name called `__arg1` to handle old style tools that do not expose a\n        # schema and expect a single string argument as an input.\n        # We unpack the argument here if it exists.\n        # Open AI does not support passing in a JSON array as an argument.\n        if \"__arg1\" in _tool_input:\n            tool_input = _tool_input[\"__arg1\"]\n        else:\n            tool_input = _tool_input\n        content_msg = f\"responded: {message.content}\\n\" if message.content else \"\\n\"\n        log = f\"\\nInvoking: `{function_name}` with `{tool_input}`\\n{content_msg}\\n\"\n        actions.append(\n            OpenAIToolAgentAction(\n                tool=function_name,\n                tool_input=tool_input,\n                log=log,\n                message_log=[message],\n                tool_call_id=tool_call[\"id\"],\n            )\n        )\n    return actions\n[docs]class OpenAIToolsAgentOutputParser(MultiActionAgentOutputParser):\n    \"\"\"Parses a message into agent actions/finish.\n    Is meant to be used with OpenAI models, as it relies on the specific\n    tool_calls parameter from OpenAI to convey what tools to use.\n    If a tool_calls parameter is passed, then that is used to get\n    the tool names and tool inputs.\n    If one is not passed, then the AIMessage is assumed to be the final output.\n    \"\"\"\n    @property\n    def _type(self) -> str:\n        return \"openai-tools-agent-output-parser\"\n[docs]    def parse_result(\n        self, result: List[Generation], *, partial: bool = False\n    ) -> Union[List[AgentAction], AgentFinish]:\n        if not isinstance(result[0], ChatGeneration):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/openai_tools.html"}
{"id": "9069d8de205f-2", "text": "if not isinstance(result[0], ChatGeneration):\n            raise ValueError(\"This output parser only works on ChatGeneration output\")\n        message = result[0].message\n        return parse_ai_message_to_openai_tool_action(message)\n[docs]    async def aparse_result(\n        self, result: List[Generation], *, partial: bool = False\n    ) -> Union[List[AgentAction], AgentFinish]:\n        return await asyncio.get_running_loop().run_in_executor(\n            None, self.parse_result, result\n        )\n[docs]    def parse(self, text: str) -> Union[List[AgentAction], AgentFinish]:\n        raise ValueError(\"Can only parse messages\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/openai_tools.html"}
{"id": "56fc65b1a72c-0", "text": "Source code for langchain.agents.output_parsers.xml\nfrom typing import Union\nfrom langchain.agents import AgentOutputParser\nfrom langchain.schema import AgentAction, AgentFinish\n[docs]class XMLAgentOutputParser(AgentOutputParser):\n    \"\"\"Parses tool invocations and final answers in XML format.\n    Expects output to be in one of two formats.\n    If the output signals that an action should be taken,\n    should be in the below format. This will result in an AgentAction\n    being returned.\n    ```\n    <tool>search</tool>\n    <tool_input>what is 2 + 2</tool_input>\n    ```\n    If the output signals that a final answer should be given,\n    should be in the below format. This will result in an AgentFinish\n    being returned.\n    ```\n    <final_answer>Foo</final_answer>\n    ```\n    \"\"\"\n[docs]    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        if \"</tool>\" in text:\n            tool, tool_input = text.split(\"</tool>\")\n            _tool = tool.split(\"<tool>\")[1]\n            _tool_input = tool_input.split(\"<tool_input>\")[1]\n            if \"</tool_input>\" in _tool_input:\n                _tool_input = _tool_input.split(\"</tool_input>\")[0]\n            return AgentAction(tool=_tool, tool_input=_tool_input, log=text)\n        elif \"<final_answer>\" in text:\n            _, answer = text.split(\"<final_answer>\")\n            if \"</final_answer>\" in answer:\n                answer = answer.split(\"</final_answer>\")[0]\n            return AgentFinish(return_values={\"output\": answer}, log=text)\n        else:\n            raise ValueError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/xml.html"}
{"id": "56fc65b1a72c-1", "text": "else:\n            raise ValueError\n[docs]    def get_format_instructions(self) -> str:\n        raise NotImplementedError\n    @property\n    def _type(self) -> str:\n        return \"xml-agent\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/xml.html"}
{"id": "f0b100dd319a-0", "text": "Source code for langchain.agents.output_parsers.openai_functions\nimport asyncio\nimport json\nfrom json import JSONDecodeError\nfrom typing import List, Union\nfrom langchain.agents.agent import AgentOutputParser\nfrom langchain.schema import (\n    AgentAction,\n    AgentFinish,\n    OutputParserException,\n)\nfrom langchain.schema.agent import AgentActionMessageLog\nfrom langchain.schema.messages import (\n    AIMessage,\n    BaseMessage,\n)\nfrom langchain.schema.output import ChatGeneration, Generation\n[docs]class OpenAIFunctionsAgentOutputParser(AgentOutputParser):\n    \"\"\"Parses a message into agent action/finish.\n    Is meant to be used with OpenAI models, as it relies on the specific\n    function_call parameter from OpenAI to convey what tools to use.\n    If a function_call parameter is passed, then that is used to get\n    the tool and tool input.\n    If one is not passed, then the AIMessage is assumed to be the final output.\n    \"\"\"\n    @property\n    def _type(self) -> str:\n        return \"openai-functions-agent\"\n    @staticmethod\n    def _parse_ai_message(message: BaseMessage) -> Union[AgentAction, AgentFinish]:\n        \"\"\"Parse an AI message.\"\"\"\n        if not isinstance(message, AIMessage):\n            raise TypeError(f\"Expected an AI message got {type(message)}\")\n        function_call = message.additional_kwargs.get(\"function_call\", {})\n        if function_call:\n            function_name = function_call[\"name\"]\n            try:\n                if len(function_call[\"arguments\"].strip()) == 0:\n                    # OpenAI returns an empty string for functions containing no args\n                    _tool_input = {}\n                else:\n                    # otherwise it returns a json object", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/openai_functions.html"}
{"id": "f0b100dd319a-1", "text": "_tool_input = {}\n                else:\n                    # otherwise it returns a json object\n                    _tool_input = json.loads(function_call[\"arguments\"])\n            except JSONDecodeError:\n                raise OutputParserException(\n                    f\"Could not parse tool input: {function_call} because \"\n                    f\"the `arguments` is not valid JSON.\"\n                )\n            # HACK HACK HACK:\n            # The code that encodes tool input into Open AI uses a special variable\n            # name called `__arg1` to handle old style tools that do not expose a\n            # schema and expect a single string argument as an input.\n            # We unpack the argument here if it exists.\n            # Open AI does not support passing in a JSON array as an argument.\n            if \"__arg1\" in _tool_input:\n                tool_input = _tool_input[\"__arg1\"]\n            else:\n                tool_input = _tool_input\n            content_msg = f\"responded: {message.content}\\n\" if message.content else \"\\n\"\n            log = f\"\\nInvoking: `{function_name}` with `{tool_input}`\\n{content_msg}\\n\"\n            return AgentActionMessageLog(\n                tool=function_name,\n                tool_input=tool_input,\n                log=log,\n                message_log=[message],\n            )\n        return AgentFinish(\n            return_values={\"output\": message.content}, log=str(message.content)\n        )\n[docs]    def parse_result(\n        self, result: List[Generation], *, partial: bool = False\n    ) -> Union[AgentAction, AgentFinish]:\n        if not isinstance(result[0], ChatGeneration):\n            raise ValueError(\"This output parser only works on ChatGeneration output\")\n        message = result[0].message\n        return self._parse_ai_message(message)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/openai_functions.html"}
{"id": "f0b100dd319a-2", "text": "message = result[0].message\n        return self._parse_ai_message(message)\n[docs]    async def aparse_result(\n        self, result: List[Generation], *, partial: bool = False\n    ) -> Union[AgentAction, AgentFinish]:\n        return await asyncio.get_running_loop().run_in_executor(\n            None, self.parse_result, result\n        )\n[docs]    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        raise ValueError(\"Can only parse messages\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/openai_functions.html"}
{"id": "7d2b5364915f-0", "text": "Source code for langchain.agents.output_parsers.self_ask\nfrom typing import Sequence, Union\nfrom langchain.agents.agent import AgentOutputParser\nfrom langchain.schema import AgentAction, AgentFinish, OutputParserException\n[docs]class SelfAskOutputParser(AgentOutputParser):\n    \"\"\"Parses self-ask style LLM calls.\n    Expects output to be in one of two formats.\n    If the output signals that an action should be taken,\n    should be in the below format. This will result in an AgentAction\n    being returned.\n    ```\n    Thoughts go here...\n    Follow up: what is the temperature in SF?\n    ```\n    If the output signals that a final answer should be given,\n    should be in the below format. This will result in an AgentFinish\n    being returned.\n    ```\n    Thoughts go here...\n    So the final answer is: The temperature is 100 degrees\n    ```\n    \"\"\"\n    followups: Sequence[str] = (\"Follow up:\", \"Followup:\")\n    finish_string: str = \"So the final answer is: \"\n[docs]    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        last_line = text.split(\"\\n\")[-1]\n        if not any([follow in last_line for follow in self.followups]):\n            if self.finish_string not in last_line:\n                raise OutputParserException(f\"Could not parse output: {text}\")\n            return AgentFinish({\"output\": last_line[len(self.finish_string) :]}, text)\n        after_colon = text.split(\":\")[-1].strip()\n        return AgentAction(\"Intermediate Answer\", after_colon, text)\n    @property\n    def _type(self) -> str:\n        return \"self_ask\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/self_ask.html"}
{"id": "20a51e53e700-0", "text": "Source code for langchain.agents.output_parsers.react_json_single_input\nimport json\nimport re\nfrom typing import Union\nfrom langchain.agents.agent import AgentOutputParser\nfrom langchain.agents.chat.prompt import FORMAT_INSTRUCTIONS\nfrom langchain.schema import AgentAction, AgentFinish, OutputParserException\nFINAL_ANSWER_ACTION = \"Final Answer:\"\n[docs]class ReActJsonSingleInputOutputParser(AgentOutputParser):\n    \"\"\"Parses ReAct-style LLM calls that have a single tool input in json format.\n    Expects output to be in one of two formats.\n    If the output signals that an action should be taken,\n    should be in the below format. This will result in an AgentAction\n    being returned.\n    ```\n    Thought: agent thought here\n    Action:\n    ```\n    {\n        \"action\": \"search\",\n        \"action_input\": \"what is the temperature in SF\"\n    }\n    ```\n    ```\n    If the output signals that a final answer should be given,\n    should be in the below format. This will result in an AgentFinish\n    being returned.\n    ```\n    Thought: agent thought here\n    Final Answer: The temperature is 100 degrees\n    ```\n    \"\"\"\n    pattern = re.compile(r\"^.*?`{3}(?:json)?\\n(.*?)`{3}.*?$\", re.DOTALL)\n    \"\"\"Regex pattern to parse the output.\"\"\"\n[docs]    def get_format_instructions(self) -> str:\n        return FORMAT_INSTRUCTIONS\n[docs]    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        includes_answer = FINAL_ANSWER_ACTION in text\n        try:\n            found = self.pattern.search(text)\n            if not found:\n                # Fast fail to parse Final Answer.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/react_json_single_input.html"}
{"id": "20a51e53e700-1", "text": "if not found:\n                # Fast fail to parse Final Answer.\n                raise ValueError(\"action not found\")\n            action = found.group(1)\n            response = json.loads(action.strip())\n            includes_action = \"action\" in response\n            if includes_answer and includes_action:\n                raise OutputParserException(\n                    \"Parsing LLM output produced a final answer \"\n                    f\"and a parse-able action: {text}\"\n                )\n            return AgentAction(\n                response[\"action\"], response.get(\"action_input\", {}), text\n            )\n        except Exception:\n            if not includes_answer:\n                raise OutputParserException(f\"Could not parse LLM output: {text}\")\n            output = text.split(FINAL_ANSWER_ACTION)[-1].strip()\n            return AgentFinish({\"output\": output}, text)\n    @property\n    def _type(self) -> str:\n        return \"react-json-single-input\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/output_parsers/react_json_single_input.html"}
{"id": "aba37ea9c93c-0", "text": "Source code for langchain.agents.structured_chat.base\nimport re\nfrom typing import Any, List, Optional, Sequence, Tuple\nfrom langchain.agents.agent import Agent, AgentOutputParser\nfrom langchain.agents.structured_chat.output_parser import (\n    StructuredChatOutputParserWithRetries,\n)\nfrom langchain.agents.structured_chat.prompt import FORMAT_INSTRUCTIONS, PREFIX, SUFFIX\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts.chat import (\n    ChatPromptTemplate,\n    HumanMessagePromptTemplate,\n    SystemMessagePromptTemplate,\n)\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import AgentAction, BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools import BaseTool\nHUMAN_MESSAGE_TEMPLATE = \"{input}\\n\\n{agent_scratchpad}\"\n[docs]class StructuredChatAgent(Agent):\n    \"\"\"Structured Chat Agent.\"\"\"\n    output_parser: AgentOutputParser = Field(\n        default_factory=StructuredChatOutputParserWithRetries\n    )\n    \"\"\"Output parser for the agent.\"\"\"\n    @property\n    def observation_prefix(self) -> str:\n        \"\"\"Prefix to append the observation with.\"\"\"\n        return \"Observation: \"\n    @property\n    def llm_prefix(self) -> str:\n        \"\"\"Prefix to append the llm call with.\"\"\"\n        return \"Thought:\"\n    def _construct_scratchpad(\n        self, intermediate_steps: List[Tuple[AgentAction, str]]\n    ) -> str:\n        agent_scratchpad = super()._construct_scratchpad(intermediate_steps)\n        if not isinstance(agent_scratchpad, str):\n            raise ValueError(\"agent_scratchpad should be of type string.\")\n        if agent_scratchpad:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/structured_chat/base.html"}
{"id": "aba37ea9c93c-1", "text": "if agent_scratchpad:\n            return (\n                f\"This was your previous work \"\n                f\"(but I haven't seen any of it! I only see what \"\n                f\"you return as final answer):\\n{agent_scratchpad}\"\n            )\n        else:\n            return agent_scratchpad\n    @classmethod\n    def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:\n        pass\n    @classmethod\n    def _get_default_output_parser(\n        cls, llm: Optional[BaseLanguageModel] = None, **kwargs: Any\n    ) -> AgentOutputParser:\n        return StructuredChatOutputParserWithRetries.from_llm(llm=llm)\n    @property\n    def _stop(self) -> List[str]:\n        return [\"Observation:\"]\n[docs]    @classmethod\n    def create_prompt(\n        cls,\n        tools: Sequence[BaseTool],\n        prefix: str = PREFIX,\n        suffix: str = SUFFIX,\n        human_message_template: str = HUMAN_MESSAGE_TEMPLATE,\n        format_instructions: str = FORMAT_INSTRUCTIONS,\n        input_variables: Optional[List[str]] = None,\n        memory_prompts: Optional[List[BasePromptTemplate]] = None,\n    ) -> BasePromptTemplate:\n        tool_strings = []\n        for tool in tools:\n            args_schema = re.sub(\"}\", \"}}}}\", re.sub(\"{\", \"{{{{\", str(tool.args)))\n            tool_strings.append(f\"{tool.name}: {tool.description}, args: {args_schema}\")\n        formatted_tools = \"\\n\".join(tool_strings)\n        tool_names = \", \".join([tool.name for tool in tools])\n        format_instructions = format_instructions.format(tool_names=tool_names)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/structured_chat/base.html"}
{"id": "aba37ea9c93c-2", "text": "format_instructions = format_instructions.format(tool_names=tool_names)\n        template = \"\\n\\n\".join([prefix, formatted_tools, format_instructions, suffix])\n        if input_variables is None:\n            input_variables = [\"input\", \"agent_scratchpad\"]\n        _memory_prompts = memory_prompts or []\n        messages = [\n            SystemMessagePromptTemplate.from_template(template),\n            *_memory_prompts,\n            HumanMessagePromptTemplate.from_template(human_message_template),\n        ]\n        return ChatPromptTemplate(input_variables=input_variables, messages=messages)\n[docs]    @classmethod\n    def from_llm_and_tools(\n        cls,\n        llm: BaseLanguageModel,\n        tools: Sequence[BaseTool],\n        callback_manager: Optional[BaseCallbackManager] = None,\n        output_parser: Optional[AgentOutputParser] = None,\n        prefix: str = PREFIX,\n        suffix: str = SUFFIX,\n        human_message_template: str = HUMAN_MESSAGE_TEMPLATE,\n        format_instructions: str = FORMAT_INSTRUCTIONS,\n        input_variables: Optional[List[str]] = None,\n        memory_prompts: Optional[List[BasePromptTemplate]] = None,\n        **kwargs: Any,\n    ) -> Agent:\n        \"\"\"Construct an agent from an LLM and tools.\"\"\"\n        cls._validate_tools(tools)\n        prompt = cls.create_prompt(\n            tools,\n            prefix=prefix,\n            suffix=suffix,\n            human_message_template=human_message_template,\n            format_instructions=format_instructions,\n            input_variables=input_variables,\n            memory_prompts=memory_prompts,\n        )\n        llm_chain = LLMChain(\n            llm=llm,\n            prompt=prompt,\n            callback_manager=callback_manager,\n        )\n        tool_names = [tool.name for tool in tools]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/structured_chat/base.html"}
{"id": "aba37ea9c93c-3", "text": ")\n        tool_names = [tool.name for tool in tools]\n        _output_parser = output_parser or cls._get_default_output_parser(llm=llm)\n        return cls(\n            llm_chain=llm_chain,\n            allowed_tools=tool_names,\n            output_parser=_output_parser,\n            **kwargs,\n        )\n    @property\n    def _agent_type(self) -> str:\n        raise ValueError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/structured_chat/base.html"}
{"id": "08c22033c5ad-0", "text": "Source code for langchain.agents.structured_chat.output_parser\nfrom __future__ import annotations\nimport json\nimport logging\nimport re\nfrom typing import Optional, Union\nfrom langchain.agents.agent import AgentOutputParser\nfrom langchain.agents.structured_chat.prompt import FORMAT_INSTRUCTIONS\nfrom langchain.output_parsers import OutputFixingParser\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import AgentAction, AgentFinish, OutputParserException\nfrom langchain.schema.language_model import BaseLanguageModel\nlogger = logging.getLogger(__name__)\n[docs]class StructuredChatOutputParser(AgentOutputParser):\n    \"\"\"Output parser for the structured chat agent.\"\"\"\n    pattern = re.compile(r\"```(?:json\\s+)?(\\W.*?)```\", re.DOTALL)\n[docs]    def get_format_instructions(self) -> str:\n        return FORMAT_INSTRUCTIONS\n[docs]    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        try:\n            action_match = self.pattern.search(text)\n            if action_match is not None:\n                response = json.loads(action_match.group(1).strip(), strict=False)\n                if isinstance(response, list):\n                    # gpt turbo frequently ignores the directive to emit a single action\n                    logger.warning(\"Got multiple action responses: %s\", response)\n                    response = response[0]\n                if response[\"action\"] == \"Final Answer\":\n                    return AgentFinish({\"output\": response[\"action_input\"]}, text)\n                else:\n                    return AgentAction(\n                        response[\"action\"], response.get(\"action_input\", {}), text\n                    )\n            else:\n                return AgentFinish({\"output\": text}, text)\n        except Exception as e:\n            raise OutputParserException(f\"Could not parse LLM output: {text}\") from e\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/structured_chat/output_parser.html"}
{"id": "08c22033c5ad-1", "text": "@property\n    def _type(self) -> str:\n        return \"structured_chat\"\n[docs]class StructuredChatOutputParserWithRetries(AgentOutputParser):\n    \"\"\"Output parser with retries for the structured chat agent.\"\"\"\n    base_parser: AgentOutputParser = Field(default_factory=StructuredChatOutputParser)\n    \"\"\"The base parser to use.\"\"\"\n    output_fixing_parser: Optional[OutputFixingParser] = None\n    \"\"\"The output fixing parser to use.\"\"\"\n[docs]    def get_format_instructions(self) -> str:\n        return FORMAT_INSTRUCTIONS\n[docs]    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        try:\n            if self.output_fixing_parser is not None:\n                parsed_obj: Union[\n                    AgentAction, AgentFinish\n                ] = self.output_fixing_parser.parse(text)\n            else:\n                parsed_obj = self.base_parser.parse(text)\n            return parsed_obj\n        except Exception as e:\n            raise OutputParserException(f\"Could not parse LLM output: {text}\") from e\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: Optional[BaseLanguageModel] = None,\n        base_parser: Optional[StructuredChatOutputParser] = None,\n    ) -> StructuredChatOutputParserWithRetries:\n        if llm is not None:\n            base_parser = base_parser or StructuredChatOutputParser()\n            output_fixing_parser = OutputFixingParser.from_llm(\n                llm=llm, parser=base_parser\n            )\n            return cls(output_fixing_parser=output_fixing_parser)\n        elif base_parser is not None:\n            return cls(base_parser=base_parser)\n        else:\n            return cls()\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/structured_chat/output_parser.html"}
{"id": "08c22033c5ad-2", "text": "else:\n            return cls()\n    @property\n    def _type(self) -> str:\n        return \"structured_chat_with_retries\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/structured_chat/output_parser.html"}
{"id": "ab7f6802f47d-0", "text": "Source code for langchain.agents.openai_functions_multi_agent.base\n\"\"\"Module implements an agent that uses OpenAI's APIs function enabled API.\"\"\"\nimport json\nfrom json import JSONDecodeError\nfrom typing import Any, List, Optional, Sequence, Tuple, Union\nfrom langchain.agents import BaseMultiActionAgent\nfrom langchain.agents.format_scratchpad.openai_functions import (\n    format_to_openai_function_messages,\n)\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chat_models.openai import ChatOpenAI\nfrom langchain.prompts.chat import (\n    BaseMessagePromptTemplate,\n    ChatPromptTemplate,\n    HumanMessagePromptTemplate,\n    MessagesPlaceholder,\n)\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import (\n    AgentAction,\n    AgentFinish,\n    BasePromptTemplate,\n    OutputParserException,\n)\nfrom langchain.schema.agent import AgentActionMessageLog\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import (\n    AIMessage,\n    BaseMessage,\n    SystemMessage,\n)\nfrom langchain.tools import BaseTool\n# For backwards compatibility\n_FunctionsAgentAction = AgentActionMessageLog\ndef _parse_ai_message(message: BaseMessage) -> Union[List[AgentAction], AgentFinish]:\n    \"\"\"Parse an AI message.\"\"\"\n    if not isinstance(message, AIMessage):\n        raise TypeError(f\"Expected an AI message got {type(message)}\")\n    function_call = message.additional_kwargs.get(\"function_call\", {})\n    if function_call:\n        try:\n            arguments = json.loads(function_call[\"arguments\"])\n        except JSONDecodeError:\n            raise OutputParserException(\n                f\"Could not parse tool input: {function_call} because \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html"}
{"id": "ab7f6802f47d-1", "text": "f\"Could not parse tool input: {function_call} because \"\n                f\"the `arguments` is not valid JSON.\"\n            )\n        try:\n            tools = arguments[\"actions\"]\n        except (TypeError, KeyError):\n            raise OutputParserException(\n                f\"Could not parse tool input: {function_call} because \"\n                f\"the `arguments` JSON does not contain `actions` key.\"\n            )\n        final_tools: List[AgentAction] = []\n        for tool_schema in tools:\n            _tool_input = tool_schema[\"action\"]\n            function_name = tool_schema[\"action_name\"]\n            # HACK HACK HACK:\n            # The code that encodes tool input into Open AI uses a special variable\n            # name called `__arg1` to handle old style tools that do not expose a\n            # schema and expect a single string argument as an input.\n            # We unpack the argument here if it exists.\n            # Open AI does not support passing in a JSON array as an argument.\n            if \"__arg1\" in _tool_input:\n                tool_input = _tool_input[\"__arg1\"]\n            else:\n                tool_input = _tool_input\n            content_msg = f\"responded: {message.content}\\n\" if message.content else \"\\n\"\n            log = f\"\\nInvoking: `{function_name}` with `{tool_input}`\\n{content_msg}\\n\"\n            _tool = _FunctionsAgentAction(\n                tool=function_name,\n                tool_input=tool_input,\n                log=log,\n                message_log=[message],\n            )\n            final_tools.append(_tool)\n        return final_tools\n    return AgentFinish(\n        return_values={\"output\": message.content}, log=str(message.content)\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html"}
{"id": "ab7f6802f47d-2", "text": "return_values={\"output\": message.content}, log=str(message.content)\n    )\n[docs]class OpenAIMultiFunctionsAgent(BaseMultiActionAgent):\n    \"\"\"An Agent driven by OpenAIs function powered API.\n    Args:\n        llm: This should be an instance of ChatOpenAI, specifically a model\n            that supports using `functions`.\n        tools: The tools this agent has access to.\n        prompt: The prompt for this agent, should support agent_scratchpad as one\n            of the variables. For an easy way to construct this prompt, use\n            `OpenAIMultiFunctionsAgent.create_prompt(...)`\n    \"\"\"\n    llm: BaseLanguageModel\n    tools: Sequence[BaseTool]\n    prompt: BasePromptTemplate\n[docs]    def get_allowed_tools(self) -> List[str]:\n        \"\"\"Get allowed tools.\"\"\"\n        return [t.name for t in self.tools]\n    @root_validator\n    def validate_llm(cls, values: dict) -> dict:\n        if not isinstance(values[\"llm\"], ChatOpenAI):\n            raise ValueError(\"Only supported with ChatOpenAI models.\")\n        return values\n    @root_validator\n    def validate_prompt(cls, values: dict) -> dict:\n        prompt: BasePromptTemplate = values[\"prompt\"]\n        if \"agent_scratchpad\" not in prompt.input_variables:\n            raise ValueError(\n                \"`agent_scratchpad` should be one of the variables in the prompt, \"\n                f\"got {prompt.input_variables}\"\n            )\n        return values\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Get input keys. Input refers to user input here.\"\"\"\n        return [\"input\"]\n    @property\n    def functions(self) -> List[dict]:\n        enum_vals = [t.name for t in self.tools]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html"}
{"id": "ab7f6802f47d-3", "text": "enum_vals = [t.name for t in self.tools]\n        tool_selection = {\n            # OpenAI functions returns a single tool invocation\n            # Here we force the single tool invocation it returns to\n            # itself be a list of tool invocations. We do this by constructing\n            # a new tool that has one argument which is a list of tools\n            # to use.\n            \"name\": \"tool_selection\",\n            \"description\": \"A list of actions to take.\",\n            \"parameters\": {\n                \"title\": \"tool_selection\",\n                \"description\": \"A list of actions to take.\",\n                \"type\": \"object\",\n                \"properties\": {\n                    \"actions\": {\n                        \"title\": \"actions\",\n                        \"type\": \"array\",\n                        \"items\": {\n                            # This is a custom item which bundles the action_name\n                            # and the action. We do this because some actions\n                            # could have the same schema, and without this there\n                            # is no way to differentiate them.\n                            \"title\": \"tool_call\",\n                            \"type\": \"object\",\n                            \"properties\": {\n                                # This is the name of the action to take\n                                \"action_name\": {\n                                    \"title\": \"action_name\",\n                                    \"enum\": enum_vals,\n                                    \"type\": \"string\",\n                                    \"description\": (\n                                        \"Name of the action to take. The name \"\n                                        \"provided here should match up with the \"\n                                        \"parameters for the action below.\"\n                                    ),\n                                },\n                                # This is the action to take.\n                                \"action\": {\n                                    \"title\": \"Action\",\n                                    \"anyOf\": [\n                                        {\n                                            \"title\": t.name,\n                                            \"type\": \"object\",\n                                            \"properties\": t.args,\n                                        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html"}
{"id": "ab7f6802f47d-4", "text": "\"type\": \"object\",\n                                            \"properties\": t.args,\n                                        }\n                                        for t in self.tools\n                                    ],\n                                },\n                            },\n                            \"required\": [\"action_name\", \"action\"],\n                        },\n                    }\n                },\n                \"required\": [\"actions\"],\n            },\n        }\n        return [tool_selection]\n[docs]    def plan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[List[AgentAction], AgentFinish]:\n        \"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date, along with observations\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.\n        \"\"\"\n        agent_scratchpad = format_to_openai_function_messages(intermediate_steps)\n        selected_inputs = {\n            k: kwargs[k] for k in self.prompt.input_variables if k != \"agent_scratchpad\"\n        }\n        full_inputs = dict(**selected_inputs, agent_scratchpad=agent_scratchpad)\n        prompt = self.prompt.format_prompt(**full_inputs)\n        messages = prompt.to_messages()\n        predicted_message = self.llm.predict_messages(\n            messages, functions=self.functions, callbacks=callbacks\n        )\n        agent_decision = _parse_ai_message(predicted_message)\n        return agent_decision\n[docs]    async def aplan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[List[AgentAction], AgentFinish]:\n        \"\"\"Given input, decided what to do.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html"}
{"id": "ab7f6802f47d-5", "text": "\"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with observations\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.\n        \"\"\"\n        agent_scratchpad = format_to_openai_function_messages(intermediate_steps)\n        selected_inputs = {\n            k: kwargs[k] for k in self.prompt.input_variables if k != \"agent_scratchpad\"\n        }\n        full_inputs = dict(**selected_inputs, agent_scratchpad=agent_scratchpad)\n        prompt = self.prompt.format_prompt(**full_inputs)\n        messages = prompt.to_messages()\n        predicted_message = await self.llm.apredict_messages(\n            messages, functions=self.functions, callbacks=callbacks\n        )\n        agent_decision = _parse_ai_message(predicted_message)\n        return agent_decision\n[docs]    @classmethod\n    def create_prompt(\n        cls,\n        system_message: Optional[SystemMessage] = SystemMessage(\n            content=\"You are a helpful AI assistant.\"\n        ),\n        extra_prompt_messages: Optional[List[BaseMessagePromptTemplate]] = None,\n    ) -> BasePromptTemplate:\n        \"\"\"Create prompt for this agent.\n        Args:\n            system_message: Message to use as the system message that will be the\n                first in the prompt.\n            extra_prompt_messages: Prompt messages that will be placed between the\n                system message and the new human input.\n        Returns:\n            A prompt template to pass into this agent.\n        \"\"\"\n        _prompts = extra_prompt_messages or []\n        messages: List[Union[BaseMessagePromptTemplate, BaseMessage]]\n        if system_message:\n            messages = [system_message]\n        else:\n            messages = []\n        messages.extend(\n            [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html"}
{"id": "ab7f6802f47d-6", "text": "else:\n            messages = []\n        messages.extend(\n            [\n                *_prompts,\n                HumanMessagePromptTemplate.from_template(\"{input}\"),\n                MessagesPlaceholder(variable_name=\"agent_scratchpad\"),\n            ]\n        )\n        return ChatPromptTemplate(messages=messages)\n[docs]    @classmethod\n    def from_llm_and_tools(\n        cls,\n        llm: BaseLanguageModel,\n        tools: Sequence[BaseTool],\n        callback_manager: Optional[BaseCallbackManager] = None,\n        extra_prompt_messages: Optional[List[BaseMessagePromptTemplate]] = None,\n        system_message: Optional[SystemMessage] = SystemMessage(\n            content=\"You are a helpful AI assistant.\"\n        ),\n        **kwargs: Any,\n    ) -> BaseMultiActionAgent:\n        \"\"\"Construct an agent from an LLM and tools.\"\"\"\n        prompt = cls.create_prompt(\n            extra_prompt_messages=extra_prompt_messages,\n            system_message=system_message,\n        )\n        return cls(\n            llm=llm,\n            prompt=prompt,\n            tools=tools,\n            callback_manager=callback_manager,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_multi_agent/base.html"}
{"id": "9fe7ec8cc2f8-0", "text": "Source code for langchain.agents.xml.base\nfrom typing import Any, List, Tuple, Union\nfrom langchain.agents.agent import BaseSingleActionAgent\nfrom langchain.agents.output_parsers.xml import XMLAgentOutputParser\nfrom langchain.agents.xml.prompt import agent_instructions\nfrom langchain.callbacks.base import Callbacks\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts.chat import AIMessagePromptTemplate, ChatPromptTemplate\nfrom langchain.schema import AgentAction, AgentFinish\nfrom langchain.tools.base import BaseTool\n[docs]class XMLAgent(BaseSingleActionAgent):\n    \"\"\"Agent that uses XML tags.\n    Args:\n        tools: list of tools the agent can choose from\n        llm_chain: The LLMChain to call to predict the next action\n    Examples:\n        .. code-block:: python\n            from langchain.agents import XMLAgent\n            from langchain\n            tools = ...\n            model =\n    \"\"\"\n    tools: List[BaseTool]\n    \"\"\"List of tools this agent has access to.\"\"\"\n    llm_chain: LLMChain\n    \"\"\"Chain to use to predict action.\"\"\"\n    @property\n    def input_keys(self) -> List[str]:\n        return [\"input\"]\n[docs]    @staticmethod\n    def get_default_prompt() -> ChatPromptTemplate:\n        return ChatPromptTemplate.from_template(\n            agent_instructions\n        ) + AIMessagePromptTemplate.from_template(\"{intermediate_steps}\")\n[docs]    @staticmethod\n    def get_default_output_parser() -> XMLAgentOutputParser:\n        return XMLAgentOutputParser()\n[docs]    def plan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[AgentAction, AgentFinish]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/xml/base.html"}
{"id": "9fe7ec8cc2f8-1", "text": "**kwargs: Any,\n    ) -> Union[AgentAction, AgentFinish]:\n        log = \"\"\n        for action, observation in intermediate_steps:\n            log += (\n                f\"<tool>{action.tool}</tool><tool_input>{action.tool_input}\"\n                f\"</tool_input><observation>{observation}</observation>\"\n            )\n        tools = \"\"\n        for tool in self.tools:\n            tools += f\"{tool.name}: {tool.description}\\n\"\n        inputs = {\n            \"intermediate_steps\": log,\n            \"tools\": tools,\n            \"question\": kwargs[\"input\"],\n            \"stop\": [\"</tool_input>\", \"</final_answer>\"],\n        }\n        response = self.llm_chain(inputs, callbacks=callbacks)\n        return response[self.llm_chain.output_key]\n[docs]    async def aplan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[AgentAction, AgentFinish]:\n        log = \"\"\n        for action, observation in intermediate_steps:\n            log += (\n                f\"<tool>{action.tool}</tool><tool_input>{action.tool_input}\"\n                f\"</tool_input><observation>{observation}</observation>\"\n            )\n        tools = \"\"\n        for tool in self.tools:\n            tools += f\"{tool.name}: {tool.description}\\n\"\n        inputs = {\n            \"intermediate_steps\": log,\n            \"tools\": tools,\n            \"question\": kwargs[\"input\"],\n            \"stop\": [\"</tool_input>\", \"</final_answer>\"],\n        }\n        response = await self.llm_chain.acall(inputs, callbacks=callbacks)\n        return response[self.llm_chain.output_key]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/xml/base.html"}
{"id": "cd21a57a24d0-0", "text": "Source code for langchain.agents.openai_assistant.base\nfrom __future__ import annotations\nimport json\nfrom json import JSONDecodeError\nfrom time import sleep\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union\nfrom langchain.callbacks.manager import CallbackManager\nfrom langchain.load import dumpd\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema.agent import AgentAction, AgentFinish\nfrom langchain.schema.runnable import RunnableConfig, RunnableSerializable\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.render import format_tool_to_openai_tool\nif TYPE_CHECKING:\n    import openai\n    from openai.types.beta.threads import ThreadMessage\n    from openai.types.beta.threads.required_action_function_tool_call import (\n        RequiredActionFunctionToolCall,\n    )\n[docs]class OpenAIAssistantFinish(AgentFinish):\n    \"\"\"AgentFinish with run and thread metadata.\"\"\"\n    run_id: str\n    thread_id: str\n[docs]class OpenAIAssistantAction(AgentAction):\n    \"\"\"AgentAction with info needed to submit custom tool output to existing run.\"\"\"\n    tool_call_id: str\n    run_id: str\n    thread_id: str\ndef _get_openai_client() -> openai.OpenAI:\n    try:\n        import openai\n        return openai.OpenAI()\n    except ImportError as e:\n        raise ImportError(\n            \"Unable to import openai, please install with `pip install openai`.\"\n        ) from e\n    except AttributeError as e:\n        raise AttributeError(\n            \"Please make sure you are using a v1.1-compatible version of openai. You \"\n            'can install with `pip install \"openai>=1.1\"`.'\n        ) from e\nOutputType = Union[", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_assistant/base.html"}
{"id": "cd21a57a24d0-1", "text": ") from e\nOutputType = Union[\n    List[OpenAIAssistantAction],\n    OpenAIAssistantFinish,\n    List[\"ThreadMessage\"],\n    List[\"RequiredActionFunctionToolCall\"],\n]\n[docs]class OpenAIAssistantRunnable(RunnableSerializable[Dict, OutputType]):\n    \"\"\"Run an OpenAI Assistant.\n    Example using OpenAI tools:\n        .. code-block:: python\n            from langchain_experimental.openai_assistant import OpenAIAssistantRunnable\n            interpreter_assistant = OpenAIAssistantRunnable.create_assistant(\n                name=\"langchain assistant\",\n                instructions=\"You are a personal math tutor. Write and run code to answer math questions.\",\n                tools=[{\"type\": \"code_interpreter\"}],\n                model=\"gpt-4-1106-preview\"\n            )\n            output = interpreter_assistant.invoke({\"content\": \"What's 10 - 4 raised to the 2.7\"})\n    Example using custom tools and AgentExecutor:\n        .. code-block:: python\n            from langchain_experimental.openai_assistant import OpenAIAssistantRunnable\n            from langchain.agents import AgentExecutor\n            from langchain.tools import E2BDataAnalysisTool\n            tools = [E2BDataAnalysisTool(api_key=\"...\")]\n            agent = OpenAIAssistantRunnable.create_assistant(\n                name=\"langchain assistant e2b tool\",\n                instructions=\"You are a personal math tutor. Write and run code to answer math questions.\",\n                tools=tools,\n                model=\"gpt-4-1106-preview\",\n                as_agent=True\n            )\n            agent_executor = AgentExecutor(agent=agent, tools=tools)\n            agent_executor.invoke({\"content\": \"What's 10 - 4 raised to the 2.7\"})\n    Example using custom tools and custom execution:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_assistant/base.html"}
{"id": "cd21a57a24d0-2", "text": "Example using custom tools and custom execution:\n        .. code-block:: python\n            from langchain_experimental.openai_assistant import OpenAIAssistantRunnable\n            from langchain.agents import AgentExecutor\n            from langchain.schema.agent import AgentFinish\n            from langchain.tools import E2BDataAnalysisTool\n            tools = [E2BDataAnalysisTool(api_key=\"...\")]\n            agent = OpenAIAssistantRunnable.create_assistant(\n                name=\"langchain assistant e2b tool\",\n                instructions=\"You are a personal math tutor. Write and run code to answer math questions.\",\n                tools=tools,\n                model=\"gpt-4-1106-preview\",\n                as_agent=True\n            )\n            def execute_agent(agent, tools, input):\n                tool_map = {tool.name: tool for tool in tools}\n                response = agent.invoke(input)\n                while not isinstance(response, AgentFinish):\n                    tool_outputs = []\n                    for action in response:\n                        tool_output = tool_map[action.tool].invoke(action.tool_input)\n                        tool_outputs.append({\"output\": tool_output, \"tool_call_id\": action.tool_call_id})\n                    response = agent.invoke(\n                        {\n                            \"tool_outputs\": tool_outputs,\n                            \"run_id\": action.run_id,\n                            \"thread_id\": action.thread_id\n                        }\n                    )\n                return response\n            response = execute_agent(agent, tools, {\"content\": \"What's 10 - 4 raised to the 2.7\"})\n            next_response = execute_agent(agent, tools, {\"content\": \"now add 17.241\", \"thread_id\": response.thread_id})\n    \"\"\"  # noqa: E501\n    client: openai.OpenAI = Field(default_factory=_get_openai_client)\n    \"\"\"OpenAI client.\"\"\"\n    assistant_id: str", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_assistant/base.html"}
{"id": "cd21a57a24d0-3", "text": "\"\"\"OpenAI client.\"\"\"\n    assistant_id: str\n    \"\"\"OpenAI assistant id.\"\"\"\n    check_every_ms: float = 1_000.0\n    \"\"\"Frequency with which to check run progress in ms.\"\"\"\n    as_agent: bool = False\n    \"\"\"Use as a LangChain agent, compatible with the AgentExecutor.\"\"\"\n[docs]    @classmethod\n    def create_assistant(\n        cls,\n        name: str,\n        instructions: str,\n        tools: Sequence[Union[BaseTool, dict]],\n        model: str,\n        *,\n        client: Optional[openai.OpenAI] = None,\n        **kwargs: Any,\n    ) -> OpenAIAssistantRunnable:\n        \"\"\"Create an OpenAI Assistant and instantiate the Runnable.\n        Args:\n            name: Assistant name.\n            instructions: Assistant instructions.\n            tools: Assistant tools. Can be passed in in OpenAI format or as BaseTools.\n            model: Assistant model to use.\n            client: OpenAI client. Will create default client if not specified.\n        Returns:\n            OpenAIAssistantRunnable configured to run using the created assistant.\n        \"\"\"\n        client = client or _get_openai_client()\n        openai_tools: List = []\n        for tool in tools:\n            oai_tool = (\n                tool if isinstance(tool, dict) else format_tool_to_openai_tool(tool)\n            )\n            openai_tools.append(oai_tool)\n        assistant = client.beta.assistants.create(\n            name=name,\n            instructions=instructions,\n            tools=openai_tools,\n            model=model,\n        )\n        return cls(assistant_id=assistant.id, **kwargs)\n[docs]    def invoke(\n        self, input: dict, config: Optional[RunnableConfig] = None\n    ) -> OutputType:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_assistant/base.html"}
{"id": "cd21a57a24d0-4", "text": ") -> OutputType:\n        \"\"\"Invoke assistant.\n        Args:\n            input: Runnable input dict that can have:\n                content: User message when starting a new run.\n                thread_id: Existing thread to use.\n                run_id: Existing run to use. Should only be supplied when providing\n                    the tool output for a required action after an initial invocation.\n                file_ids: File ids to include in new run. Used for retrieval.\n                message_metadata: Metadata to associate with new message.\n                thread_metadata: Metadata to associate with new thread. Only relevant\n                    when new thread being created.\n                instructions: Additional run instructions.\n                model: Override Assistant model for this run.\n                tools: Override Assistant tools for this run.\n                run_metadata: Metadata to associate with new run.\n            config: Runnable config:\n        Return:\n            If self.as_agent, will return\n                Union[List[OpenAIAssistantAction], OpenAIAssistantFinish]. Otherwise\n                will return OpenAI types\n                Union[List[ThreadMessage], List[RequiredActionFunctionToolCall]].\n        \"\"\"\n        config = config or {}\n        callback_manager = CallbackManager.configure(\n            inheritable_callbacks=config.get(\"callbacks\"),\n            inheritable_tags=config.get(\"tags\"),\n            inheritable_metadata=config.get(\"metadata\"),\n        )\n        run_manager = callback_manager.on_chain_start(\n            dumpd(self), input, name=config.get(\"run_name\")\n        )\n        try:\n            # Being run within AgentExecutor and there are tool outputs to submit.\n            if self.as_agent and input.get(\"intermediate_steps\"):\n                tool_outputs = self._parse_intermediate_steps(\n                    input[\"intermediate_steps\"]\n                )\n                run = self.client.beta.threads.runs.submit_tool_outputs(**tool_outputs)\n            # Starting a new thread and a new run.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_assistant/base.html"}
{"id": "cd21a57a24d0-5", "text": "# Starting a new thread and a new run.\n            elif \"thread_id\" not in input:\n                thread = {\n                    \"messages\": [\n                        {\n                            \"role\": \"user\",\n                            \"content\": input[\"content\"],\n                            \"file_ids\": input.get(\"file_ids\", []),\n                            \"metadata\": input.get(\"message_metadata\"),\n                        }\n                    ],\n                    \"metadata\": input.get(\"thread_metadata\"),\n                }\n                run = self._create_thread_and_run(input, thread)\n            # Starting a new run in an existing thread.\n            elif \"run_id\" not in input:\n                _ = self.client.beta.threads.messages.create(\n                    input[\"thread_id\"],\n                    content=input[\"content\"],\n                    role=\"user\",\n                    file_ids=input.get(\"file_ids\", []),\n                    metadata=input.get(\"message_metadata\"),\n                )\n                run = self._create_run(input)\n            # Submitting tool outputs to an existing run, outside the AgentExecutor\n            # framework.\n            else:\n                run = self.client.beta.threads.runs.submit_tool_outputs(**input)\n            run = self._wait_for_run(run.id, run.thread_id)\n        except BaseException as e:\n            run_manager.on_chain_error(e)\n            raise e\n        try:\n            response = self._get_response(run)\n        except BaseException as e:\n            run_manager.on_chain_error(e, metadata=run.dict())\n            raise e\n        else:\n            run_manager.on_chain_end(response)\n            return response\n    def _parse_intermediate_steps(\n        self, intermediate_steps: List[Tuple[OpenAIAssistantAction, str]]\n    ) -> dict:\n        last_action, last_output = intermediate_steps[-1]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_assistant/base.html"}
{"id": "cd21a57a24d0-6", "text": ") -> dict:\n        last_action, last_output = intermediate_steps[-1]\n        run = self._wait_for_run(last_action.run_id, last_action.thread_id)\n        required_tool_call_ids = {\n            tc.id for tc in run.required_action.submit_tool_outputs.tool_calls\n        }\n        tool_outputs = [\n            {\"output\": output, \"tool_call_id\": action.tool_call_id}\n            for action, output in intermediate_steps\n            if action.tool_call_id in required_tool_call_ids\n        ]\n        submit_tool_outputs = {\n            \"tool_outputs\": tool_outputs,\n            \"run_id\": last_action.run_id,\n            \"thread_id\": last_action.thread_id,\n        }\n        return submit_tool_outputs\n    def _create_run(self, input: dict) -> Any:\n        params = {\n            k: v\n            for k, v in input.items()\n            if k in (\"instructions\", \"model\", \"tools\", \"run_metadata\")\n        }\n        return self.client.beta.threads.runs.create(\n            input[\"thread_id\"],\n            assistant_id=self.assistant_id,\n            **params,\n        )\n    def _create_thread_and_run(self, input: dict, thread: dict) -> Any:\n        params = {\n            k: v\n            for k, v in input.items()\n            if k in (\"instructions\", \"model\", \"tools\", \"run_metadata\")\n        }\n        run = self.client.beta.threads.create_and_run(\n            assistant_id=self.assistant_id,\n            thread=thread,\n            **params,\n        )\n        return run\n    def _get_response(self, run: Any) -> Any:\n        # TODO: Pagination\n        if run.status == \"completed\":\n            import openai\n            messages = self.client.beta.threads.messages.list(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_assistant/base.html"}
{"id": "cd21a57a24d0-7", "text": "import openai\n            messages = self.client.beta.threads.messages.list(\n                run.thread_id, order=\"asc\"\n            )\n            new_messages = [msg for msg in messages if msg.run_id == run.id]\n            if not self.as_agent:\n                return new_messages\n            answer: Any = [\n                msg_content for msg in new_messages for msg_content in msg.content\n            ]\n            if all(\n                isinstance(content, openai.types.beta.threads.MessageContentText)\n                for content in answer\n            ):\n                answer = \"\\n\".join(content.text.value for content in answer)\n            return OpenAIAssistantFinish(\n                return_values={\n                    \"output\": answer,\n                    \"thread_id\": run.thread_id,\n                    \"run_id\": run.id,\n                },\n                log=\"\",\n                run_id=run.id,\n                thread_id=run.thread_id,\n            )\n        elif run.status == \"requires_action\":\n            if not self.as_agent:\n                return run.required_action.submit_tool_outputs.tool_calls\n            actions = []\n            for tool_call in run.required_action.submit_tool_outputs.tool_calls:\n                function = tool_call.function\n                try:\n                    args = json.loads(function.arguments, strict=False)\n                except JSONDecodeError as e:\n                    raise ValueError(\n                        f\"Received invalid JSON function arguments: \"\n                        f\"{function.arguments} for function {function.name}\"\n                    ) from e\n                if len(args) == 1 and \"__arg1\" in args:\n                    args = args[\"__arg1\"]\n                actions.append(\n                    OpenAIAssistantAction(\n                        tool=function.name,\n                        tool_input=args,\n                        tool_call_id=tool_call.id,\n                        log=\"\",\n                        run_id=run.id,\n                        thread_id=run.thread_id,\n                    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_assistant/base.html"}
{"id": "cd21a57a24d0-8", "text": "run_id=run.id,\n                        thread_id=run.thread_id,\n                    )\n                )\n            return actions\n        else:\n            run_info = json.dumps(run.dict(), indent=2)\n            raise ValueError(\n                f\"Unexpected run status: {run.status}. Full run info:\\n\\n{run_info})\"\n            )\n    def _wait_for_run(self, run_id: str, thread_id: str) -> Any:\n        in_progress = True\n        while in_progress:\n            run = self.client.beta.threads.runs.retrieve(run_id, thread_id=thread_id)\n            in_progress = run.status in (\"in_progress\", \"queued\")\n            if in_progress:\n                sleep(self.check_every_ms / 1000)\n        return run", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_assistant/base.html"}
{"id": "e1b90671500f-0", "text": "Source code for langchain.agents.openai_functions_agent.base\n\"\"\"Module implements an agent that uses OpenAI's APIs function enabled API.\"\"\"\nfrom typing import Any, List, Optional, Sequence, Tuple, Union\nfrom langchain.agents import BaseSingleActionAgent\nfrom langchain.agents.format_scratchpad.openai_functions import (\n    format_to_openai_function_messages,\n)\nfrom langchain.agents.output_parsers.openai_functions import (\n    OpenAIFunctionsAgentOutputParser,\n)\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.chat_models.openai import ChatOpenAI\nfrom langchain.prompts.chat import (\n    BaseMessagePromptTemplate,\n    ChatPromptTemplate,\n    HumanMessagePromptTemplate,\n    MessagesPlaceholder,\n)\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import (\n    AgentAction,\n    AgentFinish,\n    BasePromptTemplate,\n)\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import (\n    BaseMessage,\n    SystemMessage,\n)\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.render import format_tool_to_openai_function\n[docs]class OpenAIFunctionsAgent(BaseSingleActionAgent):\n    \"\"\"An Agent driven by OpenAIs function powered API.\n    Args:\n        llm: This should be an instance of ChatOpenAI, specifically a model\n            that supports using `functions`.\n        tools: The tools this agent has access to.\n        prompt: The prompt for this agent, should support agent_scratchpad as one\n            of the variables. For an easy way to construct this prompt, use\n            `OpenAIFunctionsAgent.create_prompt(...)`\n    \"\"\"\n    llm: BaseLanguageModel", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html"}
{"id": "e1b90671500f-1", "text": "\"\"\"\n    llm: BaseLanguageModel\n    tools: Sequence[BaseTool]\n    prompt: BasePromptTemplate\n[docs]    def get_allowed_tools(self) -> List[str]:\n        \"\"\"Get allowed tools.\"\"\"\n        return [t.name for t in self.tools]\n    @root_validator\n    def validate_llm(cls, values: dict) -> dict:\n        if not isinstance(values[\"llm\"], ChatOpenAI):\n            raise ValueError(\"Only supported with ChatOpenAI models.\")\n        return values\n    @root_validator\n    def validate_prompt(cls, values: dict) -> dict:\n        prompt: BasePromptTemplate = values[\"prompt\"]\n        if \"agent_scratchpad\" not in prompt.input_variables:\n            raise ValueError(\n                \"`agent_scratchpad` should be one of the variables in the prompt, \"\n                f\"got {prompt.input_variables}\"\n            )\n        return values\n    @property\n    def input_keys(self) -> List[str]:\n        \"\"\"Get input keys. Input refers to user input here.\"\"\"\n        return [\"input\"]\n    @property\n    def functions(self) -> List[dict]:\n        return [dict(format_tool_to_openai_function(t)) for t in self.tools]\n[docs]    def plan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        with_functions: bool = True,\n        **kwargs: Any,\n    ) -> Union[AgentAction, AgentFinish]:\n        \"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date, along with observations\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html"}
{"id": "e1b90671500f-2", "text": "Returns:\n            Action specifying what tool to use.\n        \"\"\"\n        agent_scratchpad = format_to_openai_function_messages(intermediate_steps)\n        selected_inputs = {\n            k: kwargs[k] for k in self.prompt.input_variables if k != \"agent_scratchpad\"\n        }\n        full_inputs = dict(**selected_inputs, agent_scratchpad=agent_scratchpad)\n        prompt = self.prompt.format_prompt(**full_inputs)\n        messages = prompt.to_messages()\n        if with_functions:\n            predicted_message = self.llm.predict_messages(\n                messages,\n                functions=self.functions,\n                callbacks=callbacks,\n            )\n        else:\n            predicted_message = self.llm.predict_messages(\n                messages,\n                callbacks=callbacks,\n            )\n        agent_decision = OpenAIFunctionsAgentOutputParser._parse_ai_message(\n            predicted_message\n        )\n        return agent_decision\n[docs]    async def aplan(\n        self,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> Union[AgentAction, AgentFinish]:\n        \"\"\"Given input, decided what to do.\n        Args:\n            intermediate_steps: Steps the LLM has taken to date,\n                along with observations\n            **kwargs: User inputs.\n        Returns:\n            Action specifying what tool to use.\n        \"\"\"\n        agent_scratchpad = format_to_openai_function_messages(intermediate_steps)\n        selected_inputs = {\n            k: kwargs[k] for k in self.prompt.input_variables if k != \"agent_scratchpad\"\n        }\n        full_inputs = dict(**selected_inputs, agent_scratchpad=agent_scratchpad)\n        prompt = self.prompt.format_prompt(**full_inputs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html"}
{"id": "e1b90671500f-3", "text": "prompt = self.prompt.format_prompt(**full_inputs)\n        messages = prompt.to_messages()\n        predicted_message = await self.llm.apredict_messages(\n            messages, functions=self.functions, callbacks=callbacks\n        )\n        agent_decision = OpenAIFunctionsAgentOutputParser._parse_ai_message(\n            predicted_message\n        )\n        return agent_decision\n[docs]    def return_stopped_response(\n        self,\n        early_stopping_method: str,\n        intermediate_steps: List[Tuple[AgentAction, str]],\n        **kwargs: Any,\n    ) -> AgentFinish:\n        \"\"\"Return response when agent has been stopped due to max iterations.\"\"\"\n        if early_stopping_method == \"force\":\n            # `force` just returns a constant string\n            return AgentFinish(\n                {\"output\": \"Agent stopped due to iteration limit or time limit.\"}, \"\"\n            )\n        elif early_stopping_method == \"generate\":\n            # Generate does one final forward pass\n            agent_decision = self.plan(\n                intermediate_steps, with_functions=False, **kwargs\n            )\n            if type(agent_decision) == AgentFinish:\n                return agent_decision\n            else:\n                raise ValueError(\n                    f\"got AgentAction with no functions provided: {agent_decision}\"\n                )\n        else:\n            raise ValueError(\n                \"early_stopping_method should be one of `force` or `generate`, \"\n                f\"got {early_stopping_method}\"\n            )\n[docs]    @classmethod\n    def create_prompt(\n        cls,\n        system_message: Optional[SystemMessage] = SystemMessage(\n            content=\"You are a helpful AI assistant.\"\n        ),\n        extra_prompt_messages: Optional[List[BaseMessagePromptTemplate]] = None,\n    ) -> BasePromptTemplate:\n        \"\"\"Create prompt for this agent.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html"}
{"id": "e1b90671500f-4", "text": ") -> BasePromptTemplate:\n        \"\"\"Create prompt for this agent.\n        Args:\n            system_message: Message to use as the system message that will be the\n                first in the prompt.\n            extra_prompt_messages: Prompt messages that will be placed between the\n                system message and the new human input.\n        Returns:\n            A prompt template to pass into this agent.\n        \"\"\"\n        _prompts = extra_prompt_messages or []\n        messages: List[Union[BaseMessagePromptTemplate, BaseMessage]]\n        if system_message:\n            messages = [system_message]\n        else:\n            messages = []\n        messages.extend(\n            [\n                *_prompts,\n                HumanMessagePromptTemplate.from_template(\"{input}\"),\n                MessagesPlaceholder(variable_name=\"agent_scratchpad\"),\n            ]\n        )\n        return ChatPromptTemplate(messages=messages)\n[docs]    @classmethod\n    def from_llm_and_tools(\n        cls,\n        llm: BaseLanguageModel,\n        tools: Sequence[BaseTool],\n        callback_manager: Optional[BaseCallbackManager] = None,\n        extra_prompt_messages: Optional[List[BaseMessagePromptTemplate]] = None,\n        system_message: Optional[SystemMessage] = SystemMessage(\n            content=\"You are a helpful AI assistant.\"\n        ),\n        **kwargs: Any,\n    ) -> BaseSingleActionAgent:\n        \"\"\"Construct an agent from an LLM and tools.\"\"\"\n        if not isinstance(llm, ChatOpenAI):\n            raise ValueError(\"Only supported with ChatOpenAI models.\")\n        prompt = cls.create_prompt(\n            extra_prompt_messages=extra_prompt_messages,\n            system_message=system_message,\n        )\n        return cls(\n            llm=llm,\n            prompt=prompt,\n            tools=tools,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html"}
{"id": "e1b90671500f-5", "text": "llm=llm,\n            prompt=prompt,\n            tools=tools,\n            callback_manager=callback_manager,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html"}
{"id": "7599199ee261-0", "text": "Source code for langchain.agents.openai_functions_agent.agent_token_buffer_memory\n\"\"\"Memory used to save agent output AND intermediate steps.\"\"\"\nfrom typing import Any, Dict, List\nfrom langchain.agents.format_scratchpad.openai_functions import (\n    format_to_openai_function_messages,\n)\nfrom langchain.memory.chat_memory import BaseChatMemory\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import BaseMessage, get_buffer_string\n[docs]class AgentTokenBufferMemory(BaseChatMemory):\n    \"\"\"Memory used to save agent output AND intermediate steps.\"\"\"\n    human_prefix: str = \"Human\"\n    ai_prefix: str = \"AI\"\n    llm: BaseLanguageModel\n    memory_key: str = \"history\"\n    max_token_limit: int = 12000\n    \"\"\"The max number of tokens to keep in the buffer. \n    Once the buffer exceeds this many tokens, the oldest messages will be pruned.\"\"\"\n    return_messages: bool = True\n    output_key: str = \"output\"\n    intermediate_steps_key: str = \"intermediate_steps\"\n    @property\n    def buffer(self) -> List[BaseMessage]:\n        \"\"\"String buffer of memory.\"\"\"\n        return self.chat_memory.messages\n    @property\n    def memory_variables(self) -> List[str]:\n        \"\"\"Will always return list of memory variables.\n        :meta private:\n        \"\"\"\n        return [self.memory_key]\n[docs]    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Return history buffer.\"\"\"\n        if self.return_messages:\n            final_buffer: Any = self.buffer\n        else:\n            final_buffer = get_buffer_string(\n                self.buffer,\n                human_prefix=self.human_prefix,\n                ai_prefix=self.ai_prefix,\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/agent_token_buffer_memory.html"}
{"id": "7599199ee261-1", "text": "human_prefix=self.human_prefix,\n                ai_prefix=self.ai_prefix,\n            )\n        return {self.memory_key: final_buffer}\n[docs]    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, Any]) -> None:\n        \"\"\"Save context from this conversation to buffer. Pruned.\"\"\"\n        input_str, output_str = self._get_input_output(inputs, outputs)\n        self.chat_memory.add_user_message(input_str)\n        steps = format_to_openai_function_messages(outputs[self.intermediate_steps_key])\n        for msg in steps:\n            self.chat_memory.add_message(msg)\n        self.chat_memory.add_ai_message(output_str)\n        # Prune buffer if it exceeds max token limit\n        buffer = self.chat_memory.messages\n        curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)\n        if curr_buffer_length > self.max_token_limit:\n            while curr_buffer_length > self.max_token_limit:\n                buffer.pop(0)\n                curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/agent_token_buffer_memory.html"}
{"id": "cb3015333973-0", "text": "Source code for langchain.agents.agent_toolkits.azure_cognitive_services\nfrom __future__ import annotations\nimport sys\nfrom typing import List\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.tools.azure_cognitive_services import (\n    AzureCogsFormRecognizerTool,\n    AzureCogsImageAnalysisTool,\n    AzureCogsSpeech2TextTool,\n    AzureCogsText2SpeechTool,\n)\nfrom langchain.tools.base import BaseTool\n[docs]class AzureCognitiveServicesToolkit(BaseToolkit):\n    \"\"\"Toolkit for Azure Cognitive Services.\"\"\"\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        tools: List[BaseTool] = [\n            AzureCogsFormRecognizerTool(),\n            AzureCogsSpeech2TextTool(),\n            AzureCogsText2SpeechTool(),\n        ]\n        # TODO: Remove check once azure-ai-vision supports MacOS.\n        if sys.platform.startswith(\"linux\") or sys.platform.startswith(\"win\"):\n            tools.append(AzureCogsImageAnalysisTool())\n        return tools", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/azure_cognitive_services.html"}
{"id": "98d1f791f958-0", "text": "Source code for langchain.agents.agent_toolkits.base\n\"\"\"Toolkits for agents.\"\"\"\nfrom abc import ABC, abstractmethod\nfrom typing import List\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.tools import BaseTool\n[docs]class BaseToolkit(BaseModel, ABC):\n    \"\"\"Base Toolkit representing a collection of related tools.\"\"\"\n[docs]    @abstractmethod\n    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/base.html"}
{"id": "fd8bcdd17363-0", "text": "Source code for langchain.agents.agent_toolkits.sql.toolkit\n\"\"\"Toolkit for interacting with an SQL database.\"\"\"\nfrom typing import List\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools import BaseTool\nfrom langchain.tools.sql_database.tool import (\n    InfoSQLDatabaseTool,\n    ListSQLDatabaseTool,\n    QuerySQLCheckerTool,\n    QuerySQLDataBaseTool,\n)\nfrom langchain.utilities.sql_database import SQLDatabase\n[docs]class SQLDatabaseToolkit(BaseToolkit):\n    \"\"\"Toolkit for interacting with SQL databases.\"\"\"\n    db: SQLDatabase = Field(exclude=True)\n    llm: BaseLanguageModel = Field(exclude=True)\n    @property\n    def dialect(self) -> str:\n        \"\"\"Return string representation of SQL dialect to use.\"\"\"\n        return self.db.dialect\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        list_sql_database_tool = ListSQLDatabaseTool(db=self.db)\n        info_sql_database_tool_description = (\n            \"Input to this tool is a comma-separated list of tables, output is the \"\n            \"schema and sample rows for those tables. \"\n            \"Be sure that the tables actually exist by calling \"\n            f\"{list_sql_database_tool.name} first! \"\n            \"Example Input: table1, table2, table3\"\n        )\n        info_sql_database_tool = InfoSQLDatabaseTool(\n            db=self.db, description=info_sql_database_tool_description\n        )\n        query_sql_database_tool_description = (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/sql/toolkit.html"}
{"id": "fd8bcdd17363-1", "text": ")\n        query_sql_database_tool_description = (\n            \"Input to this tool is a detailed and correct SQL query, output is a \"\n            \"result from the database. If the query is not correct, an error message \"\n            \"will be returned. If an error is returned, rewrite the query, check the \"\n            \"query, and try again. If you encounter an issue with Unknown column \"\n            f\"'xxxx' in 'field list', use {info_sql_database_tool.name} \"\n            \"to query the correct table fields.\"\n        )\n        query_sql_database_tool = QuerySQLDataBaseTool(\n            db=self.db, description=query_sql_database_tool_description\n        )\n        query_sql_checker_tool_description = (\n            \"Use this tool to double check if your query is correct before executing \"\n            \"it. Always use this tool before executing a query with \"\n            f\"{query_sql_database_tool.name}!\"\n        )\n        query_sql_checker_tool = QuerySQLCheckerTool(\n            db=self.db, llm=self.llm, description=query_sql_checker_tool_description\n        )\n        return [\n            query_sql_database_tool,\n            info_sql_database_tool,\n            list_sql_database_tool,\n            query_sql_checker_tool,\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/sql/toolkit.html"}
{"id": "105744e046ee-0", "text": "Source code for langchain.agents.agent_toolkits.sql.base\n\"\"\"SQL agent.\"\"\"\nfrom typing import Any, Dict, List, Optional, Sequence\nfrom langchain.agents.agent import AgentExecutor, BaseSingleActionAgent\nfrom langchain.agents.agent_toolkits.sql.prompt import (\n    SQL_FUNCTIONS_SUFFIX,\n    SQL_PREFIX,\n    SQL_SUFFIX,\n)\nfrom langchain.agents.agent_toolkits.sql.toolkit import SQLDatabaseToolkit\nfrom langchain.agents.agent_types import AgentType\nfrom langchain.agents.mrkl.base import ZeroShotAgent\nfrom langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS\nfrom langchain.agents.openai_functions_agent.base import OpenAIFunctionsAgent\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts.chat import (\n    ChatPromptTemplate,\n    HumanMessagePromptTemplate,\n    MessagesPlaceholder,\n)\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import AIMessage, SystemMessage\nfrom langchain.tools import BaseTool\n[docs]def create_sql_agent(\n    llm: BaseLanguageModel,\n    toolkit: SQLDatabaseToolkit,\n    agent_type: AgentType = AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    prefix: str = SQL_PREFIX,\n    suffix: Optional[str] = None,\n    format_instructions: str = FORMAT_INSTRUCTIONS,\n    input_variables: Optional[List[str]] = None,\n    top_k: int = 10,\n    max_iterations: Optional[int] = 15,\n    max_execution_time: Optional[float] = None,\n    early_stopping_method: str = \"force\",\n    verbose: bool = False,\n    agent_executor_kwargs: Optional[Dict[str, Any]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/sql/base.html"}
{"id": "105744e046ee-1", "text": "agent_executor_kwargs: Optional[Dict[str, Any]] = None,\n    extra_tools: Sequence[BaseTool] = (),\n    **kwargs: Any,\n) -> AgentExecutor:\n    \"\"\"Construct an SQL agent from an LLM and tools.\"\"\"\n    tools = toolkit.get_tools() + list(extra_tools)\n    prefix = prefix.format(dialect=toolkit.dialect, top_k=top_k)\n    agent: BaseSingleActionAgent\n    if agent_type == AgentType.ZERO_SHOT_REACT_DESCRIPTION:\n        prompt = ZeroShotAgent.create_prompt(\n            tools,\n            prefix=prefix,\n            suffix=suffix or SQL_SUFFIX,\n            format_instructions=format_instructions,\n            input_variables=input_variables,\n        )\n        llm_chain = LLMChain(\n            llm=llm,\n            prompt=prompt,\n            callback_manager=callback_manager,\n        )\n        tool_names = [tool.name for tool in tools]\n        agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs)\n    elif agent_type == AgentType.OPENAI_FUNCTIONS:\n        messages = [\n            SystemMessage(content=prefix),\n            HumanMessagePromptTemplate.from_template(\"{input}\"),\n            AIMessage(content=suffix or SQL_FUNCTIONS_SUFFIX),\n            MessagesPlaceholder(variable_name=\"agent_scratchpad\"),\n        ]\n        input_variables = [\"input\", \"agent_scratchpad\"]\n        _prompt = ChatPromptTemplate(input_variables=input_variables, messages=messages)\n        agent = OpenAIFunctionsAgent(\n            llm=llm,\n            prompt=_prompt,\n            tools=tools,\n            callback_manager=callback_manager,\n            **kwargs,\n        )\n    else:\n        raise ValueError(f\"Agent type {agent_type} not supported at the moment.\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/sql/base.html"}
{"id": "105744e046ee-2", "text": "raise ValueError(f\"Agent type {agent_type} not supported at the moment.\")\n    return AgentExecutor.from_agent_and_tools(\n        agent=agent,\n        tools=tools,\n        callback_manager=callback_manager,\n        verbose=verbose,\n        max_iterations=max_iterations,\n        max_execution_time=max_execution_time,\n        early_stopping_method=early_stopping_method,\n        **(agent_executor_kwargs or {}),\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/sql/base.html"}
{"id": "4fb9909e5464-0", "text": "Source code for langchain.agents.agent_toolkits.openapi.toolkit\n\"\"\"Requests toolkit.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, List\nfrom langchain.agents.agent import AgentExecutor\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.agents.agent_toolkits.json.base import create_json_agent\nfrom langchain.agents.agent_toolkits.json.toolkit import JsonToolkit\nfrom langchain.agents.agent_toolkits.openapi.prompt import DESCRIPTION\nfrom langchain.agents.tools import Tool\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools import BaseTool\nfrom langchain.tools.json.tool import JsonSpec\nfrom langchain.tools.requests.tool import (\n    RequestsDeleteTool,\n    RequestsGetTool,\n    RequestsPatchTool,\n    RequestsPostTool,\n    RequestsPutTool,\n)\nfrom langchain.utilities.requests import TextRequestsWrapper\n[docs]class RequestsToolkit(BaseToolkit):\n    \"\"\"Toolkit for making REST requests.\n    *Security Note*: This toolkit contains tools to make GET, POST, PATCH, PUT,\n        and DELETE requests to an API.\n        Exercise care in who is allowed to use this toolkit. If exposing\n        to end users, consider that users will be able to make arbitrary\n        requests on behalf of the server hosting the code. For example,\n        users could ask the server to make a request to a private API\n        that is only accessible from the server.\n        Control access to who can submit issue requests using this toolkit and\n        what network access it has.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    requests_wrapper: TextRequestsWrapper\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Return a list of tools.\"\"\"\n        return [\n            RequestsGetTool(requests_wrapper=self.requests_wrapper),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/toolkit.html"}
{"id": "4fb9909e5464-1", "text": "return [\n            RequestsGetTool(requests_wrapper=self.requests_wrapper),\n            RequestsPostTool(requests_wrapper=self.requests_wrapper),\n            RequestsPatchTool(requests_wrapper=self.requests_wrapper),\n            RequestsPutTool(requests_wrapper=self.requests_wrapper),\n            RequestsDeleteTool(requests_wrapper=self.requests_wrapper),\n        ]\n[docs]class OpenAPIToolkit(BaseToolkit):\n    \"\"\"Toolkit for interacting with an OpenAPI API.\n    *Security Note*: This toolkit contains tools that can read and modify\n        the state of a service; e.g., by creating, deleting, or updating,\n        reading underlying data.\n        For example, this toolkit can be used to delete data exposed via\n        an OpenAPI compliant API.\n    \"\"\"\n    json_agent: AgentExecutor\n    requests_wrapper: TextRequestsWrapper\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        json_agent_tool = Tool(\n            name=\"json_explorer\",\n            func=self.json_agent.run,\n            description=DESCRIPTION,\n        )\n        request_toolkit = RequestsToolkit(requests_wrapper=self.requests_wrapper)\n        return [*request_toolkit.get_tools(), json_agent_tool]\n[docs]    @classmethod\n    def from_llm(\n        cls,\n        llm: BaseLanguageModel,\n        json_spec: JsonSpec,\n        requests_wrapper: TextRequestsWrapper,\n        **kwargs: Any,\n    ) -> OpenAPIToolkit:\n        \"\"\"Create json agent from llm, then initialize.\"\"\"\n        json_agent = create_json_agent(llm, JsonToolkit(spec=json_spec), **kwargs)\n        return cls(json_agent=json_agent, requests_wrapper=requests_wrapper)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/toolkit.html"}
{"id": "09bb1265109a-0", "text": "Source code for langchain.agents.agent_toolkits.openapi.planner\n\"\"\"Agent that interacts with OpenAPI APIs via a hierarchical planning approach.\"\"\"\nimport json\nimport re\nfrom functools import partial\nfrom typing import Any, Callable, Dict, List, Optional\nimport yaml\nfrom langchain.agents.agent import AgentExecutor\nfrom langchain.agents.agent_toolkits.openapi.planner_prompt import (\n    API_CONTROLLER_PROMPT,\n    API_CONTROLLER_TOOL_DESCRIPTION,\n    API_CONTROLLER_TOOL_NAME,\n    API_ORCHESTRATOR_PROMPT,\n    API_PLANNER_PROMPT,\n    API_PLANNER_TOOL_DESCRIPTION,\n    API_PLANNER_TOOL_NAME,\n    PARSING_DELETE_PROMPT,\n    PARSING_GET_PROMPT,\n    PARSING_PATCH_PROMPT,\n    PARSING_POST_PROMPT,\n    PARSING_PUT_PROMPT,\n    REQUESTS_DELETE_TOOL_DESCRIPTION,\n    REQUESTS_GET_TOOL_DESCRIPTION,\n    REQUESTS_PATCH_TOOL_DESCRIPTION,\n    REQUESTS_POST_TOOL_DESCRIPTION,\n    REQUESTS_PUT_TOOL_DESCRIPTION,\n)\nfrom langchain.agents.agent_toolkits.openapi.spec import ReducedOpenAPISpec\nfrom langchain.agents.mrkl.base import ZeroShotAgent\nfrom langchain.agents.tools import Tool\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains.llm import LLMChain\nfrom langchain.llms.openai import OpenAI\nfrom langchain.memory import ReadOnlySharedMemory\nfrom langchain.prompts import PromptTemplate\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.requests.tool import BaseRequestsTool\nfrom langchain.utilities.requests import RequestsWrapper\n#\n# Requests tools with LLM-instructed extraction of truncated responses.\n#", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/planner.html"}
{"id": "09bb1265109a-1", "text": "#\n# Requests tools with LLM-instructed extraction of truncated responses.\n#\n# Of course, truncating so bluntly may lose a lot of valuable\n# information in the response.\n# However, the goal for now is to have only a single inference step.\nMAX_RESPONSE_LENGTH = 5000\n\"\"\"Maximum length of the response to be returned.\"\"\"\ndef _get_default_llm_chain(prompt: BasePromptTemplate) -> LLMChain:\n    return LLMChain(\n        llm=OpenAI(),\n        prompt=prompt,\n    )\ndef _get_default_llm_chain_factory(\n    prompt: BasePromptTemplate,\n) -> Callable[[], LLMChain]:\n    \"\"\"Returns a default LLMChain factory.\"\"\"\n    return partial(_get_default_llm_chain, prompt)\n[docs]class RequestsGetToolWithParsing(BaseRequestsTool, BaseTool):\n    \"\"\"Requests GET tool with LLM-instructed extraction of truncated responses.\"\"\"\n    name: str = \"requests_get\"\n    \"\"\"Tool name.\"\"\"\n    description = REQUESTS_GET_TOOL_DESCRIPTION\n    \"\"\"Tool description.\"\"\"\n    response_length: Optional[int] = MAX_RESPONSE_LENGTH\n    \"\"\"Maximum length of the response to be returned.\"\"\"\n    llm_chain: LLMChain = Field(\n        default_factory=_get_default_llm_chain_factory(PARSING_GET_PROMPT)\n    )\n    \"\"\"LLMChain used to extract the response.\"\"\"\n    def _run(self, text: str) -> str:\n        try:\n            data = json.loads(text)\n        except json.JSONDecodeError as e:\n            raise e\n        data_params = data.get(\"params\")\n        response = self.requests_wrapper.get(data[\"url\"], params=data_params)\n        response = response[: self.response_length]\n        return self.llm_chain.predict(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/planner.html"}
{"id": "09bb1265109a-2", "text": "response = response[: self.response_length]\n        return self.llm_chain.predict(\n            response=response, instructions=data[\"output_instructions\"]\n        ).strip()\n    async def _arun(self, text: str) -> str:\n        raise NotImplementedError()\n[docs]class RequestsPostToolWithParsing(BaseRequestsTool, BaseTool):\n    \"\"\"Requests POST tool with LLM-instructed extraction of truncated responses.\"\"\"\n    name: str = \"requests_post\"\n    \"\"\"Tool name.\"\"\"\n    description = REQUESTS_POST_TOOL_DESCRIPTION\n    \"\"\"Tool description.\"\"\"\n    response_length: Optional[int] = MAX_RESPONSE_LENGTH\n    \"\"\"Maximum length of the response to be returned.\"\"\"\n    llm_chain: LLMChain = Field(\n        default_factory=_get_default_llm_chain_factory(PARSING_POST_PROMPT)\n    )\n    \"\"\"LLMChain used to extract the response.\"\"\"\n    def _run(self, text: str) -> str:\n        try:\n            data = json.loads(text)\n        except json.JSONDecodeError as e:\n            raise e\n        response = self.requests_wrapper.post(data[\"url\"], data[\"data\"])\n        response = response[: self.response_length]\n        return self.llm_chain.predict(\n            response=response, instructions=data[\"output_instructions\"]\n        ).strip()\n    async def _arun(self, text: str) -> str:\n        raise NotImplementedError()\n[docs]class RequestsPatchToolWithParsing(BaseRequestsTool, BaseTool):\n    \"\"\"Requests PATCH tool with LLM-instructed extraction of truncated responses.\"\"\"\n    name: str = \"requests_patch\"\n    \"\"\"Tool name.\"\"\"\n    description = REQUESTS_PATCH_TOOL_DESCRIPTION\n    \"\"\"Tool description.\"\"\"\n    response_length: Optional[int] = MAX_RESPONSE_LENGTH\n    \"\"\"Maximum length of the response to be returned.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/planner.html"}
{"id": "09bb1265109a-3", "text": "\"\"\"Maximum length of the response to be returned.\"\"\"\n    llm_chain: LLMChain = Field(\n        default_factory=_get_default_llm_chain_factory(PARSING_PATCH_PROMPT)\n    )\n    \"\"\"LLMChain used to extract the response.\"\"\"\n    def _run(self, text: str) -> str:\n        try:\n            data = json.loads(text)\n        except json.JSONDecodeError as e:\n            raise e\n        response = self.requests_wrapper.patch(data[\"url\"], data[\"data\"])\n        response = response[: self.response_length]\n        return self.llm_chain.predict(\n            response=response, instructions=data[\"output_instructions\"]\n        ).strip()\n    async def _arun(self, text: str) -> str:\n        raise NotImplementedError()\n[docs]class RequestsPutToolWithParsing(BaseRequestsTool, BaseTool):\n    \"\"\"Requests PUT tool with LLM-instructed extraction of truncated responses.\"\"\"\n    name: str = \"requests_put\"\n    \"\"\"Tool name.\"\"\"\n    description = REQUESTS_PUT_TOOL_DESCRIPTION\n    \"\"\"Tool description.\"\"\"\n    response_length: Optional[int] = MAX_RESPONSE_LENGTH\n    \"\"\"Maximum length of the response to be returned.\"\"\"\n    llm_chain: LLMChain = Field(\n        default_factory=_get_default_llm_chain_factory(PARSING_PUT_PROMPT)\n    )\n    \"\"\"LLMChain used to extract the response.\"\"\"\n    def _run(self, text: str) -> str:\n        try:\n            data = json.loads(text)\n        except json.JSONDecodeError as e:\n            raise e\n        response = self.requests_wrapper.put(data[\"url\"], data[\"data\"])\n        response = response[: self.response_length]\n        return self.llm_chain.predict(\n            response=response, instructions=data[\"output_instructions\"]\n        ).strip()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/planner.html"}
{"id": "09bb1265109a-4", "text": "response=response, instructions=data[\"output_instructions\"]\n        ).strip()\n    async def _arun(self, text: str) -> str:\n        raise NotImplementedError()\n[docs]class RequestsDeleteToolWithParsing(BaseRequestsTool, BaseTool):\n    \"\"\"A tool that sends a DELETE request and parses the response.\"\"\"\n    name: str = \"requests_delete\"\n    \"\"\"The name of the tool.\"\"\"\n    description = REQUESTS_DELETE_TOOL_DESCRIPTION\n    \"\"\"The description of the tool.\"\"\"\n    response_length: Optional[int] = MAX_RESPONSE_LENGTH\n    \"\"\"The maximum length of the response.\"\"\"\n    llm_chain: LLMChain = Field(\n        default_factory=_get_default_llm_chain_factory(PARSING_DELETE_PROMPT)\n    )\n    \"\"\"The LLM chain used to parse the response.\"\"\"\n    def _run(self, text: str) -> str:\n        try:\n            data = json.loads(text)\n        except json.JSONDecodeError as e:\n            raise e\n        response = self.requests_wrapper.delete(data[\"url\"])\n        response = response[: self.response_length]\n        return self.llm_chain.predict(\n            response=response, instructions=data[\"output_instructions\"]\n        ).strip()\n    async def _arun(self, text: str) -> str:\n        raise NotImplementedError()\n#\n# Orchestrator, planner, controller.\n#\ndef _create_api_planner_tool(\n    api_spec: ReducedOpenAPISpec, llm: BaseLanguageModel\n) -> Tool:\n    endpoint_descriptions = [\n        f\"{name} {description}\" for name, description, _ in api_spec.endpoints\n    ]\n    prompt = PromptTemplate(\n        template=API_PLANNER_PROMPT,\n        input_variables=[\"query\"],\n        partial_variables={\"endpoints\": \"- \" + \"- \".join(endpoint_descriptions)},", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/planner.html"}
{"id": "09bb1265109a-5", "text": "partial_variables={\"endpoints\": \"- \" + \"- \".join(endpoint_descriptions)},\n    )\n    chain = LLMChain(llm=llm, prompt=prompt)\n    tool = Tool(\n        name=API_PLANNER_TOOL_NAME,\n        description=API_PLANNER_TOOL_DESCRIPTION,\n        func=chain.run,\n    )\n    return tool\ndef _create_api_controller_agent(\n    api_url: str,\n    api_docs: str,\n    requests_wrapper: RequestsWrapper,\n    llm: BaseLanguageModel,\n) -> AgentExecutor:\n    get_llm_chain = LLMChain(llm=llm, prompt=PARSING_GET_PROMPT)\n    post_llm_chain = LLMChain(llm=llm, prompt=PARSING_POST_PROMPT)\n    tools: List[BaseTool] = [\n        RequestsGetToolWithParsing(\n            requests_wrapper=requests_wrapper, llm_chain=get_llm_chain\n        ),\n        RequestsPostToolWithParsing(\n            requests_wrapper=requests_wrapper, llm_chain=post_llm_chain\n        ),\n    ]\n    prompt = PromptTemplate(\n        template=API_CONTROLLER_PROMPT,\n        input_variables=[\"input\", \"agent_scratchpad\"],\n        partial_variables={\n            \"api_url\": api_url,\n            \"api_docs\": api_docs,\n            \"tool_names\": \", \".join([tool.name for tool in tools]),\n            \"tool_descriptions\": \"\\n\".join(\n                [f\"{tool.name}: {tool.description}\" for tool in tools]\n            ),\n        },\n    )\n    agent = ZeroShotAgent(\n        llm_chain=LLMChain(llm=llm, prompt=prompt),\n        allowed_tools=[tool.name for tool in tools],\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/planner.html"}
{"id": "09bb1265109a-6", "text": "allowed_tools=[tool.name for tool in tools],\n    )\n    return AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)\ndef _create_api_controller_tool(\n    api_spec: ReducedOpenAPISpec,\n    requests_wrapper: RequestsWrapper,\n    llm: BaseLanguageModel,\n) -> Tool:\n    \"\"\"Expose controller as a tool.\n    The tool is invoked with a plan from the planner, and dynamically\n    creates a controller agent with relevant documentation only to\n    constrain the context.\n    \"\"\"\n    base_url = api_spec.servers[0][\"url\"]  # TODO: do better.\n    def _create_and_run_api_controller_agent(plan_str: str) -> str:\n        pattern = r\"\\b(GET|POST|PATCH|DELETE)\\s+(/\\S+)*\"\n        matches = re.findall(pattern, plan_str)\n        endpoint_names = [\n            \"{method} {route}\".format(method=method, route=route.split(\"?\")[0])\n            for method, route in matches\n        ]\n        docs_str = \"\"\n        for endpoint_name in endpoint_names:\n            found_match = False\n            for name, _, docs in api_spec.endpoints:\n                regex_name = re.compile(re.sub(\"\\{.*?\\}\", \".*\", name))\n                if regex_name.match(endpoint_name):\n                    found_match = True\n                    docs_str += f\"== Docs for {endpoint_name} == \\n{yaml.dump(docs)}\\n\"\n            if not found_match:\n                raise ValueError(f\"{endpoint_name} endpoint does not exist.\")\n        agent = _create_api_controller_agent(base_url, docs_str, requests_wrapper, llm)\n        return agent.run(plan_str)\n    return Tool(\n        name=API_CONTROLLER_TOOL_NAME,\n        func=_create_and_run_api_controller_agent,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/planner.html"}
{"id": "09bb1265109a-7", "text": "name=API_CONTROLLER_TOOL_NAME,\n        func=_create_and_run_api_controller_agent,\n        description=API_CONTROLLER_TOOL_DESCRIPTION,\n    )\n[docs]def create_openapi_agent(\n    api_spec: ReducedOpenAPISpec,\n    requests_wrapper: RequestsWrapper,\n    llm: BaseLanguageModel,\n    shared_memory: Optional[ReadOnlySharedMemory] = None,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    verbose: bool = True,\n    agent_executor_kwargs: Optional[Dict[str, Any]] = None,\n    **kwargs: Any,\n) -> AgentExecutor:\n    \"\"\"Instantiate OpenAI API planner and controller for a given spec.\n    Inject credentials via requests_wrapper.\n    We use a top-level \"orchestrator\" agent to invoke the planner and controller,\n    rather than a top-level planner\n    that invokes a controller with its plan. This is to keep the planner simple.\n    \"\"\"\n    tools = [\n        _create_api_planner_tool(api_spec, llm),\n        _create_api_controller_tool(api_spec, requests_wrapper, llm),\n    ]\n    prompt = PromptTemplate(\n        template=API_ORCHESTRATOR_PROMPT,\n        input_variables=[\"input\", \"agent_scratchpad\"],\n        partial_variables={\n            \"tool_names\": \", \".join([tool.name for tool in tools]),\n            \"tool_descriptions\": \"\\n\".join(\n                [f\"{tool.name}: {tool.description}\" for tool in tools]\n            ),\n        },\n    )\n    agent = ZeroShotAgent(\n        llm_chain=LLMChain(llm=llm, prompt=prompt, memory=shared_memory),\n        allowed_tools=[tool.name for tool in tools],\n        **kwargs,\n    )\n    return AgentExecutor.from_agent_and_tools(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/planner.html"}
{"id": "09bb1265109a-8", "text": "**kwargs,\n    )\n    return AgentExecutor.from_agent_and_tools(\n        agent=agent,\n        tools=tools,\n        callback_manager=callback_manager,\n        verbose=verbose,\n        **(agent_executor_kwargs or {}),\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/planner.html"}
{"id": "8227c3d4e30c-0", "text": "Source code for langchain.agents.agent_toolkits.openapi.spec\n\"\"\"Quick and dirty representation for OpenAPI specs.\"\"\"\nfrom dataclasses import dataclass\nfrom typing import List, Tuple\nfrom langchain.utils.json_schema import dereference_refs\n[docs]@dataclass(frozen=True)\nclass ReducedOpenAPISpec:\n    \"\"\"A reduced OpenAPI spec.\n    This is a quick and dirty representation for OpenAPI specs.\n    Attributes:\n        servers: The servers in the spec.\n        description: The description of the spec.\n        endpoints: The endpoints in the spec.\n    \"\"\"\n    servers: List[dict]\n    description: str\n    endpoints: List[Tuple[str, str, dict]]\n[docs]def reduce_openapi_spec(spec: dict, dereference: bool = True) -> ReducedOpenAPISpec:\n    \"\"\"Simplify/distill/minify a spec somehow.\n    I want a smaller target for retrieval and (more importantly)\n    I want smaller results from retrieval.\n    I was hoping https://openapi.tools/ would have some useful bits\n    to this end, but doesn't seem so.\n    \"\"\"\n    # 1. Consider only get, post, patch, put, delete endpoints.\n    endpoints = [\n        (f\"{operation_name.upper()} {route}\", docs.get(\"description\"), docs)\n        for route, operation in spec[\"paths\"].items()\n        for operation_name, docs in operation.items()\n        if operation_name in [\"get\", \"post\", \"patch\", \"put\", \"delete\"]\n    ]\n    # 2. Replace any refs so that complete docs are retrieved.\n    # Note: probably want to do this post-retrieval, it blows up the size of the spec.\n    if dereference:\n        endpoints = [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/spec.html"}
{"id": "8227c3d4e30c-1", "text": "if dereference:\n        endpoints = [\n            (name, description, dereference_refs(docs, full_schema=spec))\n            for name, description, docs in endpoints\n        ]\n    # 3. Strip docs down to required request args + happy path response.\n    def reduce_endpoint_docs(docs: dict) -> dict:\n        out = {}\n        if docs.get(\"description\"):\n            out[\"description\"] = docs.get(\"description\")\n        if docs.get(\"parameters\"):\n            out[\"parameters\"] = [\n                parameter\n                for parameter in docs.get(\"parameters\", [])\n                if parameter.get(\"required\")\n            ]\n        if \"200\" in docs[\"responses\"]:\n            out[\"responses\"] = docs[\"responses\"][\"200\"]\n        if docs.get(\"requestBody\"):\n            out[\"requestBody\"] = docs.get(\"requestBody\")\n        return out\n    endpoints = [\n        (name, description, reduce_endpoint_docs(docs))\n        for name, description, docs in endpoints\n    ]\n    return ReducedOpenAPISpec(\n        servers=spec[\"servers\"],\n        description=spec[\"info\"].get(\"description\", \"\"),\n        endpoints=endpoints,\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/spec.html"}
{"id": "2d6314a8fab2-0", "text": "Source code for langchain.agents.agent_toolkits.openapi.base\n\"\"\"OpenAPI spec agent.\"\"\"\nfrom typing import Any, Dict, List, Optional\nfrom langchain.agents.agent import AgentExecutor\nfrom langchain.agents.agent_toolkits.openapi.prompt import (\n    OPENAPI_PREFIX,\n    OPENAPI_SUFFIX,\n)\nfrom langchain.agents.agent_toolkits.openapi.toolkit import OpenAPIToolkit\nfrom langchain.agents.mrkl.base import ZeroShotAgent\nfrom langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains.llm import LLMChain\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]def create_openapi_agent(\n    llm: BaseLanguageModel,\n    toolkit: OpenAPIToolkit,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    prefix: str = OPENAPI_PREFIX,\n    suffix: str = OPENAPI_SUFFIX,\n    format_instructions: str = FORMAT_INSTRUCTIONS,\n    input_variables: Optional[List[str]] = None,\n    max_iterations: Optional[int] = 15,\n    max_execution_time: Optional[float] = None,\n    early_stopping_method: str = \"force\",\n    verbose: bool = False,\n    return_intermediate_steps: bool = False,\n    agent_executor_kwargs: Optional[Dict[str, Any]] = None,\n    **kwargs: Any,\n) -> AgentExecutor:\n    \"\"\"Construct an OpenAPI agent from an LLM and tools.\n    *Security Note*: When creating an OpenAPI agent, check the permissions\n        and capabilities of the underlying toolkit.\n        For example, if the default implementation of OpenAPIToolkit\n        uses the RequestsToolkit which contains tools to make arbitrary", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/base.html"}
{"id": "2d6314a8fab2-1", "text": "uses the RequestsToolkit which contains tools to make arbitrary\n        network requests against any URL (e.g., GET, POST, PATCH, PUT, DELETE),\n        Control access to who can submit issue requests using this toolkit and\n        what network access it has.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    tools = toolkit.get_tools()\n    prompt = ZeroShotAgent.create_prompt(\n        tools,\n        prefix=prefix,\n        suffix=suffix,\n        format_instructions=format_instructions,\n        input_variables=input_variables,\n    )\n    llm_chain = LLMChain(\n        llm=llm,\n        prompt=prompt,\n        callback_manager=callback_manager,\n    )\n    tool_names = [tool.name for tool in tools]\n    agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs)\n    return AgentExecutor.from_agent_and_tools(\n        agent=agent,\n        tools=tools,\n        callback_manager=callback_manager,\n        verbose=verbose,\n        return_intermediate_steps=return_intermediate_steps,\n        max_iterations=max_iterations,\n        max_execution_time=max_execution_time,\n        early_stopping_method=early_stopping_method,\n        **(agent_executor_kwargs or {}),\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/base.html"}
{"id": "30b02ba7fec5-0", "text": "Source code for langchain.agents.agent_toolkits.powerbi.toolkit\n\"\"\"Toolkit for interacting with a Power BI dataset.\"\"\"\nfrom typing import List, Optional, Union\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains.llm import LLMChain\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.prompts import PromptTemplate\nfrom langchain.prompts.chat import (\n    ChatPromptTemplate,\n    HumanMessagePromptTemplate,\n    SystemMessagePromptTemplate,\n)\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools import BaseTool\nfrom langchain.tools.powerbi.prompt import (\n    QUESTION_TO_QUERY_BASE,\n    SINGLE_QUESTION_TO_QUERY,\n    USER_INPUT,\n)\nfrom langchain.tools.powerbi.tool import (\n    InfoPowerBITool,\n    ListPowerBITool,\n    QueryPowerBITool,\n)\nfrom langchain.utilities.powerbi import PowerBIDataset\n[docs]class PowerBIToolkit(BaseToolkit):\n    \"\"\"Toolkit for interacting with Power BI dataset.\n    *Security Note*: This toolkit interacts with an external service.\n        Control access to who can use this toolkit.\n        Make sure that the capabilities given by this toolkit to the calling\n        code are appropriately scoped to the application.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    powerbi: PowerBIDataset = Field(exclude=True)\n    llm: Union[BaseLanguageModel, BaseChatModel] = Field(exclude=True)\n    examples: Optional[str] = None\n    max_iterations: int = 5\n    callback_manager: Optional[BaseCallbackManager] = None\n    output_token_limit: Optional[int] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/powerbi/toolkit.html"}
{"id": "30b02ba7fec5-1", "text": "output_token_limit: Optional[int] = None\n    tiktoken_model_name: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        return [\n            QueryPowerBITool(\n                llm_chain=self._get_chain(),\n                powerbi=self.powerbi,\n                examples=self.examples,\n                max_iterations=self.max_iterations,\n                output_token_limit=self.output_token_limit,\n                tiktoken_model_name=self.tiktoken_model_name,\n            ),\n            InfoPowerBITool(powerbi=self.powerbi),\n            ListPowerBITool(powerbi=self.powerbi),\n        ]\n    def _get_chain(self) -> LLMChain:\n        \"\"\"Construct the chain based on the callback manager and model type.\"\"\"\n        if isinstance(self.llm, BaseLanguageModel):\n            return LLMChain(\n                llm=self.llm,\n                callback_manager=self.callback_manager\n                if self.callback_manager\n                else None,\n                prompt=PromptTemplate(\n                    template=SINGLE_QUESTION_TO_QUERY,\n                    input_variables=[\"tool_input\", \"tables\", \"schemas\", \"examples\"],\n                ),\n            )\n        system_prompt = SystemMessagePromptTemplate(\n            prompt=PromptTemplate(\n                template=QUESTION_TO_QUERY_BASE,\n                input_variables=[\"tables\", \"schemas\", \"examples\"],\n            )\n        )\n        human_prompt = HumanMessagePromptTemplate(\n            prompt=PromptTemplate(\n                template=USER_INPUT,\n                input_variables=[\"tool_input\"],\n            )\n        )\n        return LLMChain(\n            llm=self.llm,\n            callback_manager=self.callback_manager if self.callback_manager else None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/powerbi/toolkit.html"}
{"id": "30b02ba7fec5-2", "text": "callback_manager=self.callback_manager if self.callback_manager else None,\n            prompt=ChatPromptTemplate.from_messages([system_prompt, human_prompt]),\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/powerbi/toolkit.html"}
{"id": "537788954283-0", "text": "Source code for langchain.agents.agent_toolkits.powerbi.base\n\"\"\"Power BI agent.\"\"\"\nfrom typing import Any, Dict, List, Optional\nfrom langchain.agents import AgentExecutor\nfrom langchain.agents.agent_toolkits.powerbi.prompt import (\n    POWERBI_PREFIX,\n    POWERBI_SUFFIX,\n)\nfrom langchain.agents.agent_toolkits.powerbi.toolkit import PowerBIToolkit\nfrom langchain.agents.mrkl.base import ZeroShotAgent\nfrom langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains.llm import LLMChain\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.utilities.powerbi import PowerBIDataset\n[docs]def create_pbi_agent(\n    llm: BaseLanguageModel,\n    toolkit: Optional[PowerBIToolkit] = None,\n    powerbi: Optional[PowerBIDataset] = None,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    prefix: str = POWERBI_PREFIX,\n    suffix: str = POWERBI_SUFFIX,\n    format_instructions: str = FORMAT_INSTRUCTIONS,\n    examples: Optional[str] = None,\n    input_variables: Optional[List[str]] = None,\n    top_k: int = 10,\n    verbose: bool = False,\n    agent_executor_kwargs: Optional[Dict[str, Any]] = None,\n    **kwargs: Any,\n) -> AgentExecutor:\n    \"\"\"Construct a Power BI agent from an LLM and tools.\"\"\"\n    if toolkit is None:\n        if powerbi is None:\n            raise ValueError(\"Must provide either a toolkit or powerbi dataset\")\n        toolkit = PowerBIToolkit(powerbi=powerbi, llm=llm, examples=examples)\n    tools = toolkit.get_tools()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/powerbi/base.html"}
{"id": "537788954283-1", "text": "tools = toolkit.get_tools()\n    tables = powerbi.table_names if powerbi else toolkit.powerbi.table_names\n    agent = ZeroShotAgent(\n        llm_chain=LLMChain(\n            llm=llm,\n            prompt=ZeroShotAgent.create_prompt(\n                tools,\n                prefix=prefix.format(top_k=top_k).format(tables=tables),\n                suffix=suffix,\n                format_instructions=format_instructions,\n                input_variables=input_variables,\n            ),\n            callback_manager=callback_manager,  # type: ignore\n            verbose=verbose,\n        ),\n        allowed_tools=[tool.name for tool in tools],\n        **kwargs,\n    )\n    return AgentExecutor.from_agent_and_tools(\n        agent=agent,\n        tools=tools,\n        callback_manager=callback_manager,\n        verbose=verbose,\n        **(agent_executor_kwargs or {}),\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/powerbi/base.html"}
{"id": "682f294b6511-0", "text": "Source code for langchain.agents.agent_toolkits.powerbi.chat_base\n\"\"\"Power BI agent.\"\"\"\nfrom typing import Any, Dict, List, Optional\nfrom langchain.agents import AgentExecutor\nfrom langchain.agents.agent import AgentOutputParser\nfrom langchain.agents.agent_toolkits.powerbi.prompt import (\n    POWERBI_CHAT_PREFIX,\n    POWERBI_CHAT_SUFFIX,\n)\nfrom langchain.agents.agent_toolkits.powerbi.toolkit import PowerBIToolkit\nfrom langchain.agents.conversational_chat.base import ConversationalChatAgent\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.memory import ConversationBufferMemory\nfrom langchain.memory.chat_memory import BaseChatMemory\nfrom langchain.utilities.powerbi import PowerBIDataset\n[docs]def create_pbi_chat_agent(\n    llm: BaseChatModel,\n    toolkit: Optional[PowerBIToolkit] = None,\n    powerbi: Optional[PowerBIDataset] = None,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    output_parser: Optional[AgentOutputParser] = None,\n    prefix: str = POWERBI_CHAT_PREFIX,\n    suffix: str = POWERBI_CHAT_SUFFIX,\n    examples: Optional[str] = None,\n    input_variables: Optional[List[str]] = None,\n    memory: Optional[BaseChatMemory] = None,\n    top_k: int = 10,\n    verbose: bool = False,\n    agent_executor_kwargs: Optional[Dict[str, Any]] = None,\n    **kwargs: Any,\n) -> AgentExecutor:\n    \"\"\"Construct a Power BI agent from a Chat LLM and tools.\n    If you supply only a toolkit and no Power BI dataset, the same LLM is used for both.\n    \"\"\"\n    if toolkit is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/powerbi/chat_base.html"}
{"id": "682f294b6511-1", "text": "\"\"\"\n    if toolkit is None:\n        if powerbi is None:\n            raise ValueError(\"Must provide either a toolkit or powerbi dataset\")\n        toolkit = PowerBIToolkit(powerbi=powerbi, llm=llm, examples=examples)\n    tools = toolkit.get_tools()\n    tables = powerbi.table_names if powerbi else toolkit.powerbi.table_names\n    agent = ConversationalChatAgent.from_llm_and_tools(\n        llm=llm,\n        tools=tools,\n        system_message=prefix.format(top_k=top_k).format(tables=tables),\n        human_message=suffix,\n        input_variables=input_variables,\n        callback_manager=callback_manager,\n        output_parser=output_parser,\n        verbose=verbose,\n        **kwargs,\n    )\n    return AgentExecutor.from_agent_and_tools(\n        agent=agent,\n        tools=tools,\n        callback_manager=callback_manager,\n        memory=memory\n        or ConversationBufferMemory(memory_key=\"chat_history\", return_messages=True),\n        verbose=verbose,\n        **(agent_executor_kwargs or {}),\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/powerbi/chat_base.html"}
{"id": "9274697715de-0", "text": "Source code for langchain.agents.agent_toolkits.spark_sql.toolkit\n\"\"\"Toolkit for interacting with Spark SQL.\"\"\"\nfrom typing import List\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools import BaseTool\nfrom langchain.tools.spark_sql.tool import (\n    InfoSparkSQLTool,\n    ListSparkSQLTool,\n    QueryCheckerTool,\n    QuerySparkSQLTool,\n)\nfrom langchain.utilities.spark_sql import SparkSQL\n[docs]class SparkSQLToolkit(BaseToolkit):\n    \"\"\"Toolkit for interacting with Spark SQL.\"\"\"\n    db: SparkSQL = Field(exclude=True)\n    llm: BaseLanguageModel = Field(exclude=True)\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        return [\n            QuerySparkSQLTool(db=self.db),\n            InfoSparkSQLTool(db=self.db),\n            ListSparkSQLTool(db=self.db),\n            QueryCheckerTool(db=self.db, llm=self.llm),\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/spark_sql/toolkit.html"}
{"id": "d0da36b94272-0", "text": "Source code for langchain.agents.agent_toolkits.spark_sql.base\n\"\"\"Spark SQL agent.\"\"\"\nfrom typing import Any, Dict, List, Optional\nfrom langchain.agents.agent import AgentExecutor\nfrom langchain.agents.agent_toolkits.spark_sql.prompt import SQL_PREFIX, SQL_SUFFIX\nfrom langchain.agents.agent_toolkits.spark_sql.toolkit import SparkSQLToolkit\nfrom langchain.agents.mrkl.base import ZeroShotAgent\nfrom langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS\nfrom langchain.callbacks.base import BaseCallbackManager, Callbacks\nfrom langchain.chains.llm import LLMChain\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]def create_spark_sql_agent(\n    llm: BaseLanguageModel,\n    toolkit: SparkSQLToolkit,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    callbacks: Callbacks = None,\n    prefix: str = SQL_PREFIX,\n    suffix: str = SQL_SUFFIX,\n    format_instructions: str = FORMAT_INSTRUCTIONS,\n    input_variables: Optional[List[str]] = None,\n    top_k: int = 10,\n    max_iterations: Optional[int] = 15,\n    max_execution_time: Optional[float] = None,\n    early_stopping_method: str = \"force\",\n    verbose: bool = False,\n    agent_executor_kwargs: Optional[Dict[str, Any]] = None,\n    **kwargs: Any,\n) -> AgentExecutor:\n    \"\"\"Construct a Spark SQL agent from an LLM and tools.\"\"\"\n    tools = toolkit.get_tools()\n    prefix = prefix.format(top_k=top_k)\n    prompt = ZeroShotAgent.create_prompt(\n        tools,\n        prefix=prefix,\n        suffix=suffix,\n        format_instructions=format_instructions,\n        input_variables=input_variables,\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/spark_sql/base.html"}
{"id": "d0da36b94272-1", "text": "format_instructions=format_instructions,\n        input_variables=input_variables,\n    )\n    llm_chain = LLMChain(\n        llm=llm,\n        prompt=prompt,\n        callback_manager=callback_manager,\n        callbacks=callbacks,\n    )\n    tool_names = [tool.name for tool in tools]\n    agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs)\n    return AgentExecutor.from_agent_and_tools(\n        agent=agent,\n        tools=tools,\n        callback_manager=callback_manager,\n        callbacks=callbacks,\n        verbose=verbose,\n        max_iterations=max_iterations,\n        max_execution_time=max_execution_time,\n        early_stopping_method=early_stopping_method,\n        **(agent_executor_kwargs or {}),\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/spark_sql/base.html"}
{"id": "dc53b8201c2d-0", "text": "Source code for langchain.agents.agent_toolkits.nla.toolkit\nfrom __future__ import annotations\nfrom typing import Any, List, Optional, Sequence\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.agents.agent_toolkits.nla.tool import NLATool\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.openapi.utils.openapi_utils import OpenAPISpec\nfrom langchain.tools.plugin import AIPlugin\nfrom langchain.utilities.requests import Requests\n[docs]class NLAToolkit(BaseToolkit):\n    \"\"\"Natural Language API Toolkit.\n    *Security Note*: This toolkit creates tools that enable making calls\n        to an Open API compliant API.\n        The tools created by this toolkit may be able to make GET, POST,\n        PATCH, PUT, DELETE requests to any of the exposed endpoints on\n        the API.\n        Control access to who can use this toolkit.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    nla_tools: Sequence[NLATool] = Field(...)\n    \"\"\"List of API Endpoint Tools.\"\"\"\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools for all the API operations.\"\"\"\n        return list(self.nla_tools)\n    @staticmethod\n    def _get_http_operation_tools(\n        llm: BaseLanguageModel,\n        spec: OpenAPISpec,\n        requests: Optional[Requests] = None,\n        verbose: bool = False,\n        **kwargs: Any,\n    ) -> List[NLATool]:\n        \"\"\"Get the tools for all the API operations.\"\"\"\n        if not spec.paths:\n            return []\n        http_operation_tools = []\n        for path in spec.paths:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/nla/toolkit.html"}
{"id": "dc53b8201c2d-1", "text": "return []\n        http_operation_tools = []\n        for path in spec.paths:\n            for method in spec.get_methods_for_path(path):\n                endpoint_tool = NLATool.from_llm_and_method(\n                    llm=llm,\n                    path=path,\n                    method=method,\n                    spec=spec,\n                    requests=requests,\n                    verbose=verbose,\n                    **kwargs,\n                )\n                http_operation_tools.append(endpoint_tool)\n        return http_operation_tools\n[docs]    @classmethod\n    def from_llm_and_spec(\n        cls,\n        llm: BaseLanguageModel,\n        spec: OpenAPISpec,\n        requests: Optional[Requests] = None,\n        verbose: bool = False,\n        **kwargs: Any,\n    ) -> NLAToolkit:\n        \"\"\"Instantiate the toolkit by creating tools for each operation.\"\"\"\n        http_operation_tools = cls._get_http_operation_tools(\n            llm=llm, spec=spec, requests=requests, verbose=verbose, **kwargs\n        )\n        return cls(nla_tools=http_operation_tools)\n[docs]    @classmethod\n    def from_llm_and_url(\n        cls,\n        llm: BaseLanguageModel,\n        open_api_url: str,\n        requests: Optional[Requests] = None,\n        verbose: bool = False,\n        **kwargs: Any,\n    ) -> NLAToolkit:\n        \"\"\"Instantiate the toolkit from an OpenAPI Spec URL\"\"\"\n        spec = OpenAPISpec.from_url(open_api_url)\n        return cls.from_llm_and_spec(\n            llm=llm, spec=spec, requests=requests, verbose=verbose, **kwargs\n        )\n[docs]    @classmethod\n    def from_llm_and_ai_plugin(\n        cls,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/nla/toolkit.html"}
{"id": "dc53b8201c2d-2", "text": "def from_llm_and_ai_plugin(\n        cls,\n        llm: BaseLanguageModel,\n        ai_plugin: AIPlugin,\n        requests: Optional[Requests] = None,\n        verbose: bool = False,\n        **kwargs: Any,\n    ) -> NLAToolkit:\n        \"\"\"Instantiate the toolkit from an OpenAPI Spec URL\"\"\"\n        spec = OpenAPISpec.from_url(ai_plugin.api.url)\n        # TODO: Merge optional Auth information with the `requests` argument\n        return cls.from_llm_and_spec(\n            llm=llm,\n            spec=spec,\n            requests=requests,\n            verbose=verbose,\n            **kwargs,\n        )\n[docs]    @classmethod\n    def from_llm_and_ai_plugin_url(\n        cls,\n        llm: BaseLanguageModel,\n        ai_plugin_url: str,\n        requests: Optional[Requests] = None,\n        verbose: bool = False,\n        **kwargs: Any,\n    ) -> NLAToolkit:\n        \"\"\"Instantiate the toolkit from an OpenAPI Spec URL\"\"\"\n        plugin = AIPlugin.from_url(ai_plugin_url)\n        return cls.from_llm_and_ai_plugin(\n            llm=llm, ai_plugin=plugin, requests=requests, verbose=verbose, **kwargs\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/nla/toolkit.html"}
{"id": "d4e34ba6bd43-0", "text": "Source code for langchain.agents.agent_toolkits.nla.tool\n\"\"\"Tool for interacting with a single API with natural language definition.\"\"\"\nfrom typing import Any, Optional\nfrom langchain.agents.tools import Tool\nfrom langchain.chains.api.openapi.chain import OpenAPIEndpointChain\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools.openapi.utils.api_models import APIOperation\nfrom langchain.tools.openapi.utils.openapi_utils import OpenAPISpec\nfrom langchain.utilities.requests import Requests\n[docs]class NLATool(Tool):\n    \"\"\"Natural Language API Tool.\"\"\"\n[docs]    @classmethod\n    def from_open_api_endpoint_chain(\n        cls, chain: OpenAPIEndpointChain, api_title: str\n    ) -> \"NLATool\":\n        \"\"\"Convert an endpoint chain to an API endpoint tool.\"\"\"\n        expanded_name = (\n            f'{api_title.replace(\" \", \"_\")}.{chain.api_operation.operation_id}'\n        )\n        description = (\n            f\"I'm an AI from {api_title}. Instruct what you want,\"\n            \" and I'll assist via an API with description:\"\n            f\" {chain.api_operation.description}\"\n        )\n        return cls(name=expanded_name, func=chain.run, description=description)\n[docs]    @classmethod\n    def from_llm_and_method(\n        cls,\n        llm: BaseLanguageModel,\n        path: str,\n        method: str,\n        spec: OpenAPISpec,\n        requests: Optional[Requests] = None,\n        verbose: bool = False,\n        return_intermediate_steps: bool = False,\n        **kwargs: Any,\n    ) -> \"NLATool\":\n        \"\"\"Instantiate the tool from the specified path and method.\"\"\"\n        api_operation = APIOperation.from_openapi_spec(spec, path, method)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/nla/tool.html"}
{"id": "d4e34ba6bd43-1", "text": "api_operation = APIOperation.from_openapi_spec(spec, path, method)\n        chain = OpenAPIEndpointChain.from_api_operation(\n            api_operation,\n            llm,\n            requests=requests,\n            verbose=verbose,\n            return_intermediate_steps=return_intermediate_steps,\n            **kwargs,\n        )\n        return cls.from_open_api_endpoint_chain(chain, spec.info.title)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/nla/tool.html"}
{"id": "8dad56dedf0c-0", "text": "Source code for langchain.agents.agent_toolkits.jira.toolkit\nfrom typing import Dict, List\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.tools import BaseTool\nfrom langchain.tools.jira.prompt import (\n    JIRA_CATCH_ALL_PROMPT,\n    JIRA_CONFLUENCE_PAGE_CREATE_PROMPT,\n    JIRA_GET_ALL_PROJECTS_PROMPT,\n    JIRA_ISSUE_CREATE_PROMPT,\n    JIRA_JQL_PROMPT,\n)\nfrom langchain.tools.jira.tool import JiraAction\nfrom langchain.utilities.jira import JiraAPIWrapper\n[docs]class JiraToolkit(BaseToolkit):\n    \"\"\"Jira Toolkit.\n    *Security Note*: This toolkit contains tools that can read and modify\n        the state of a service; e.g., by creating, deleting, or updating,\n        reading underlying data.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    tools: List[BaseTool] = []\n[docs]    @classmethod\n    def from_jira_api_wrapper(cls, jira_api_wrapper: JiraAPIWrapper) -> \"JiraToolkit\":\n        operations: List[Dict] = [\n            {\n                \"mode\": \"jql\",\n                \"name\": \"JQL Query\",\n                \"description\": JIRA_JQL_PROMPT,\n            },\n            {\n                \"mode\": \"get_projects\",\n                \"name\": \"Get Projects\",\n                \"description\": JIRA_GET_ALL_PROJECTS_PROMPT,\n            },\n            {\n                \"mode\": \"create_issue\",\n                \"name\": \"Create Issue\",\n                \"description\": JIRA_ISSUE_CREATE_PROMPT,\n            },\n            {\n                \"mode\": \"other\",\n                \"name\": \"Catch all Jira API call\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/jira/toolkit.html"}
{"id": "8dad56dedf0c-1", "text": "\"name\": \"Catch all Jira API call\",\n                \"description\": JIRA_CATCH_ALL_PROMPT,\n            },\n            {\n                \"mode\": \"create_page\",\n                \"name\": \"Create confluence page\",\n                \"description\": JIRA_CONFLUENCE_PAGE_CREATE_PROMPT,\n            },\n        ]\n        tools = [\n            JiraAction(\n                name=action[\"name\"],\n                description=action[\"description\"],\n                mode=action[\"mode\"],\n                api_wrapper=jira_api_wrapper,\n            )\n            for action in operations\n        ]\n        return cls(tools=tools)\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        return self.tools", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/jira/toolkit.html"}
{"id": "8e3b2eb7de53-0", "text": "Source code for langchain.agents.agent_toolkits.playwright.toolkit\n\"\"\"Playwright web browser toolkit.\"\"\"\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, List, Optional, Type, cast\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.tools.base import BaseTool\nfrom langchain.tools.playwright.base import (\n    BaseBrowserTool,\n    lazy_import_playwright_browsers,\n)\nfrom langchain.tools.playwright.click import ClickTool\nfrom langchain.tools.playwright.current_page import CurrentWebPageTool\nfrom langchain.tools.playwright.extract_hyperlinks import ExtractHyperlinksTool\nfrom langchain.tools.playwright.extract_text import ExtractTextTool\nfrom langchain.tools.playwright.get_elements import GetElementsTool\nfrom langchain.tools.playwright.navigate import NavigateTool\nfrom langchain.tools.playwright.navigate_back import NavigateBackTool\nif TYPE_CHECKING:\n    from playwright.async_api import Browser as AsyncBrowser\n    from playwright.sync_api import Browser as SyncBrowser\nelse:\n    try:\n        # We do this so pydantic can resolve the types when instantiating\n        from playwright.async_api import Browser as AsyncBrowser\n        from playwright.sync_api import Browser as SyncBrowser\n    except ImportError:\n        pass\n[docs]class PlayWrightBrowserToolkit(BaseToolkit):\n    \"\"\"Toolkit for PlayWright browser tools.\n    **Security Note**: This toolkit provides code to control a web-browser.\n        Careful if exposing this toolkit to end-users. The tools in the toolkit\n        are capable of navigating to arbitrary webpages, clicking on arbitrary\n        elements, and extracting arbitrary text and hyperlinks from webpages.\n        Specifically, by default this toolkit allows navigating to:\n        - Any URL (including any internal network URLs)\n        - And local files", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/playwright/toolkit.html"}
{"id": "8e3b2eb7de53-1", "text": "- Any URL (including any internal network URLs)\n        - And local files\n        If exposing to end-users, consider limiting network access to the\n        server that hosts the agent; in addition, consider it is advised\n        to create a custom NavigationTool wht an args_schema that limits the URLs\n        that can be navigated to (e.g., only allow navigating to URLs that\n        start with a particular prefix).\n        Remember to scope permissions to the minimal permissions necessary for\n        the application. If the default tool selection is not appropriate for\n        the application, consider creating a custom toolkit with the appropriate\n        tools.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    sync_browser: Optional[\"SyncBrowser\"] = None\n    async_browser: Optional[\"AsyncBrowser\"] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator\n    def validate_imports_and_browser_provided(cls, values: dict) -> dict:\n        \"\"\"Check that the arguments are valid.\"\"\"\n        lazy_import_playwright_browsers()\n        if values.get(\"async_browser\") is None and values.get(\"sync_browser\") is None:\n            raise ValueError(\"Either async_browser or sync_browser must be specified.\")\n        return values\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        tool_classes: List[Type[BaseBrowserTool]] = [\n            ClickTool,\n            NavigateTool,\n            NavigateBackTool,\n            ExtractTextTool,\n            ExtractHyperlinksTool,\n            GetElementsTool,\n            CurrentWebPageTool,\n        ]\n        tools = [\n            tool_cls.from_browser(\n                sync_browser=self.sync_browser, async_browser=self.async_browser", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/playwright/toolkit.html"}
{"id": "8e3b2eb7de53-2", "text": "tool_cls.from_browser(\n                sync_browser=self.sync_browser, async_browser=self.async_browser\n            )\n            for tool_cls in tool_classes\n        ]\n        return cast(List[BaseTool], tools)\n[docs]    @classmethod\n    def from_browser(\n        cls,\n        sync_browser: Optional[SyncBrowser] = None,\n        async_browser: Optional[AsyncBrowser] = None,\n    ) -> PlayWrightBrowserToolkit:\n        \"\"\"Instantiate the toolkit.\"\"\"\n        # This is to raise a better error than the forward ref ones Pydantic would have\n        lazy_import_playwright_browsers()\n        return cls(sync_browser=sync_browser, async_browser=async_browser)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/playwright/toolkit.html"}
{"id": "94f8823c0103-0", "text": "Source code for langchain.agents.agent_toolkits.json.toolkit\nfrom __future__ import annotations\nfrom typing import List\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.tools import BaseTool\nfrom langchain.tools.json.tool import JsonGetValueTool, JsonListKeysTool, JsonSpec\n[docs]class JsonToolkit(BaseToolkit):\n    \"\"\"Toolkit for interacting with a JSON spec.\"\"\"\n    spec: JsonSpec\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        return [\n            JsonListKeysTool(spec=self.spec),\n            JsonGetValueTool(spec=self.spec),\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/json/toolkit.html"}
{"id": "d3c3dd7bc0ce-0", "text": "Source code for langchain.agents.agent_toolkits.json.base\n\"\"\"Json agent.\"\"\"\nfrom typing import Any, Dict, List, Optional\nfrom langchain.agents.agent import AgentExecutor\nfrom langchain.agents.agent_toolkits.json.prompt import JSON_PREFIX, JSON_SUFFIX\nfrom langchain.agents.agent_toolkits.json.toolkit import JsonToolkit\nfrom langchain.agents.mrkl.base import ZeroShotAgent\nfrom langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains.llm import LLMChain\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]def create_json_agent(\n    llm: BaseLanguageModel,\n    toolkit: JsonToolkit,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    prefix: str = JSON_PREFIX,\n    suffix: str = JSON_SUFFIX,\n    format_instructions: str = FORMAT_INSTRUCTIONS,\n    input_variables: Optional[List[str]] = None,\n    verbose: bool = False,\n    agent_executor_kwargs: Optional[Dict[str, Any]] = None,\n    **kwargs: Any,\n) -> AgentExecutor:\n    \"\"\"Construct a json agent from an LLM and tools.\"\"\"\n    tools = toolkit.get_tools()\n    prompt = ZeroShotAgent.create_prompt(\n        tools,\n        prefix=prefix,\n        suffix=suffix,\n        format_instructions=format_instructions,\n        input_variables=input_variables,\n    )\n    llm_chain = LLMChain(\n        llm=llm,\n        prompt=prompt,\n        callback_manager=callback_manager,\n    )\n    tool_names = [tool.name for tool in tools]\n    agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs)\n    return AgentExecutor.from_agent_and_tools(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/json/base.html"}
{"id": "d3c3dd7bc0ce-1", "text": "return AgentExecutor.from_agent_and_tools(\n        agent=agent,\n        tools=tools,\n        callback_manager=callback_manager,\n        verbose=verbose,\n        **(agent_executor_kwargs or {}),\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/json/base.html"}
{"id": "40f4d5b2b20f-0", "text": "Source code for langchain.agents.agent_toolkits.gmail.toolkit\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, List\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools import BaseTool\nfrom langchain.tools.gmail.create_draft import GmailCreateDraft\nfrom langchain.tools.gmail.get_message import GmailGetMessage\nfrom langchain.tools.gmail.get_thread import GmailGetThread\nfrom langchain.tools.gmail.search import GmailSearch\nfrom langchain.tools.gmail.send_message import GmailSendMessage\nfrom langchain.tools.gmail.utils import build_resource_service\nif TYPE_CHECKING:\n    # This is for linting and IDE typehints\n    from googleapiclient.discovery import Resource\nelse:\n    try:\n        # We do this so pydantic can resolve the types when instantiating\n        from googleapiclient.discovery import Resource\n    except ImportError:\n        pass\nSCOPES = [\"https://mail.google.com/\"]\n[docs]class GmailToolkit(BaseToolkit):\n    \"\"\"Toolkit for interacting with Gmail.\n    *Security Note*: This toolkit contains tools that can read and modify\n        the state of a service; e.g., by reading, creating, updating, deleting\n        data associated with this service.\n        For example, this toolkit can be used to send emails on behalf of the\n        associated account.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    api_resource: Resource = Field(default_factory=build_resource_service)\n    class Config:\n        \"\"\"Pydantic config.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        return [\n            GmailCreateDraft(api_resource=self.api_resource),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/gmail/toolkit.html"}
{"id": "40f4d5b2b20f-1", "text": "return [\n            GmailCreateDraft(api_resource=self.api_resource),\n            GmailSendMessage(api_resource=self.api_resource),\n            GmailSearch(api_resource=self.api_resource),\n            GmailGetMessage(api_resource=self.api_resource),\n            GmailGetThread(api_resource=self.api_resource),\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/gmail/toolkit.html"}
{"id": "ddf6cc0f43a5-0", "text": "Source code for langchain.agents.agent_toolkits.ainetwork.toolkit\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, List, Literal, Optional\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.tools import BaseTool\nfrom langchain.tools.ainetwork.app import AINAppOps\nfrom langchain.tools.ainetwork.owner import AINOwnerOps\nfrom langchain.tools.ainetwork.rule import AINRuleOps\nfrom langchain.tools.ainetwork.transfer import AINTransfer\nfrom langchain.tools.ainetwork.utils import authenticate\nfrom langchain.tools.ainetwork.value import AINValueOps\nif TYPE_CHECKING:\n    from ain.ain import Ain\n[docs]class AINetworkToolkit(BaseToolkit):\n    \"\"\"Toolkit for interacting with AINetwork Blockchain.\n    *Security Note*: This toolkit contains tools that can read and modify\n        the state of a service; e.g., by reading, creating, updating, deleting\n        data associated with this service.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    network: Optional[Literal[\"mainnet\", \"testnet\"]] = \"testnet\"\n    interface: Optional[Ain] = None\n    @root_validator(pre=True)\n    def set_interface(cls, values: dict) -> dict:\n        if not values.get(\"interface\"):\n            values[\"interface\"] = authenticate(network=values.get(\"network\", \"testnet\"))\n        return values\n    class Config:\n        \"\"\"Pydantic config.\"\"\"\n        validate_all = True\n        arbitrary_types_allowed = True\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        return [\n            AINAppOps(),\n            AINOwnerOps(),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/ainetwork/toolkit.html"}
{"id": "ddf6cc0f43a5-1", "text": "return [\n            AINAppOps(),\n            AINOwnerOps(),\n            AINRuleOps(),\n            AINTransfer(),\n            AINValueOps(),\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/ainetwork/toolkit.html"}
{"id": "3b2de347de90-0", "text": "Source code for langchain.agents.agent_toolkits.vectorstore.toolkit\n\"\"\"Toolkit for interacting with a vector store.\"\"\"\nfrom typing import List\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.llms.openai import OpenAI\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.vectorstore import VectorStore\nfrom langchain.tools import BaseTool\nfrom langchain.tools.vectorstore.tool import (\n    VectorStoreQATool,\n    VectorStoreQAWithSourcesTool,\n)\n[docs]class VectorStoreInfo(BaseModel):\n    \"\"\"Information about a VectorStore.\"\"\"\n    vectorstore: VectorStore = Field(exclude=True)\n    name: str\n    description: str\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]class VectorStoreToolkit(BaseToolkit):\n    \"\"\"Toolkit for interacting with a Vector Store.\"\"\"\n    vectorstore_info: VectorStoreInfo = Field(exclude=True)\n    llm: BaseLanguageModel = Field(default_factory=lambda: OpenAI(temperature=0))\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        description = VectorStoreQATool.get_description(\n            self.vectorstore_info.name, self.vectorstore_info.description\n        )\n        qa_tool = VectorStoreQATool(\n            name=self.vectorstore_info.name,\n            description=description,\n            vectorstore=self.vectorstore_info.vectorstore,\n            llm=self.llm,\n        )\n        description = VectorStoreQAWithSourcesTool.get_description(\n            self.vectorstore_info.name, self.vectorstore_info.description", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/vectorstore/toolkit.html"}
{"id": "3b2de347de90-1", "text": "self.vectorstore_info.name, self.vectorstore_info.description\n        )\n        qa_with_sources_tool = VectorStoreQAWithSourcesTool(\n            name=f\"{self.vectorstore_info.name}_with_sources\",\n            description=description,\n            vectorstore=self.vectorstore_info.vectorstore,\n            llm=self.llm,\n        )\n        return [qa_tool, qa_with_sources_tool]\n[docs]class VectorStoreRouterToolkit(BaseToolkit):\n    \"\"\"Toolkit for routing between Vector Stores.\"\"\"\n    vectorstores: List[VectorStoreInfo] = Field(exclude=True)\n    llm: BaseLanguageModel = Field(default_factory=lambda: OpenAI(temperature=0))\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        tools: List[BaseTool] = []\n        for vectorstore_info in self.vectorstores:\n            description = VectorStoreQATool.get_description(\n                vectorstore_info.name, vectorstore_info.description\n            )\n            qa_tool = VectorStoreQATool(\n                name=vectorstore_info.name,\n                description=description,\n                vectorstore=vectorstore_info.vectorstore,\n                llm=self.llm,\n            )\n            tools.append(qa_tool)\n        return tools", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/vectorstore/toolkit.html"}
{"id": "4fc31fed30af-0", "text": "Source code for langchain.agents.agent_toolkits.vectorstore.base\n\"\"\"VectorStore agent.\"\"\"\nfrom typing import Any, Dict, Optional\nfrom langchain.agents.agent import AgentExecutor\nfrom langchain.agents.agent_toolkits.vectorstore.prompt import PREFIX, ROUTER_PREFIX\nfrom langchain.agents.agent_toolkits.vectorstore.toolkit import (\n    VectorStoreRouterToolkit,\n    VectorStoreToolkit,\n)\nfrom langchain.agents.mrkl.base import ZeroShotAgent\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains.llm import LLMChain\nfrom langchain.schema.language_model import BaseLanguageModel\n[docs]def create_vectorstore_agent(\n    llm: BaseLanguageModel,\n    toolkit: VectorStoreToolkit,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    prefix: str = PREFIX,\n    verbose: bool = False,\n    agent_executor_kwargs: Optional[Dict[str, Any]] = None,\n    **kwargs: Any,\n) -> AgentExecutor:\n    \"\"\"Construct a VectorStore agent from an LLM and tools.\n    Args:\n        llm (BaseLanguageModel): LLM that will be used by the agent\n        toolkit (VectorStoreToolkit): Set of tools for the agent\n        callback_manager (Optional[BaseCallbackManager], optional): Object to handle the callback [ Defaults to None. ]\n        prefix (str, optional): The prefix prompt for the agent. If not provided uses default PREFIX.\n        verbose (bool, optional): If you want to see the content of the scratchpad. [ Defaults to False ]\n        agent_executor_kwargs (Optional[Dict[str, Any]], optional): If there is any other parameter you want to send to the agent. [ Defaults to None ]\n        **kwargs: Additional named parameters to pass to the ZeroShotAgent.\n    Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/vectorstore/base.html"}
{"id": "4fc31fed30af-1", "text": "**kwargs: Additional named parameters to pass to the ZeroShotAgent.\n    Returns:\n        AgentExecutor: Returns a callable AgentExecutor object. Either you can call it or use run method with the query to get the response\n    \"\"\"  # noqa: E501\n    tools = toolkit.get_tools()\n    prompt = ZeroShotAgent.create_prompt(tools, prefix=prefix)\n    llm_chain = LLMChain(\n        llm=llm,\n        prompt=prompt,\n        callback_manager=callback_manager,\n    )\n    tool_names = [tool.name for tool in tools]\n    agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs)\n    return AgentExecutor.from_agent_and_tools(\n        agent=agent,\n        tools=tools,\n        callback_manager=callback_manager,\n        verbose=verbose,\n        **(agent_executor_kwargs or {}),\n    )\n[docs]def create_vectorstore_router_agent(\n    llm: BaseLanguageModel,\n    toolkit: VectorStoreRouterToolkit,\n    callback_manager: Optional[BaseCallbackManager] = None,\n    prefix: str = ROUTER_PREFIX,\n    verbose: bool = False,\n    agent_executor_kwargs: Optional[Dict[str, Any]] = None,\n    **kwargs: Any,\n) -> AgentExecutor:\n    \"\"\"Construct a VectorStore router agent from an LLM and tools.\n    Args:\n        llm (BaseLanguageModel): LLM that will be used by the agent\n        toolkit (VectorStoreRouterToolkit): Set of tools for the agent which have routing capability with multiple vector stores\n        callback_manager (Optional[BaseCallbackManager], optional): Object to handle the callback [ Defaults to None. ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/vectorstore/base.html"}
{"id": "4fc31fed30af-2", "text": "prefix (str, optional): The prefix prompt for the router agent. If not provided uses default ROUTER_PREFIX.\n        verbose (bool, optional): If you want to see the content of the scratchpad. [ Defaults to False ]\n        agent_executor_kwargs (Optional[Dict[str, Any]], optional): If there is any other parameter you want to send to the agent. [ Defaults to None ]\n        **kwargs: Additional named parameters to pass to the ZeroShotAgent.\n    Returns:\n        AgentExecutor: Returns a callable AgentExecutor object. Either you can call it or use run method with the query to get the response.\n    \"\"\"  # noqa: E501\n    tools = toolkit.get_tools()\n    prompt = ZeroShotAgent.create_prompt(tools, prefix=prefix)\n    llm_chain = LLMChain(\n        llm=llm,\n        prompt=prompt,\n        callback_manager=callback_manager,\n    )\n    tool_names = [tool.name for tool in tools]\n    agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs)\n    return AgentExecutor.from_agent_and_tools(\n        agent=agent,\n        tools=tools,\n        callback_manager=callback_manager,\n        verbose=verbose,\n        **(agent_executor_kwargs or {}),\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/vectorstore/base.html"}
{"id": "b7fff50cad81-0", "text": "Source code for langchain.agents.agent_toolkits.multion.toolkit\n\"\"\"MultiOn agent.\"\"\"\nfrom __future__ import annotations\nfrom typing import List\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.tools import BaseTool\nfrom langchain.tools.multion.close_session import MultionCloseSession\nfrom langchain.tools.multion.create_session import MultionCreateSession\nfrom langchain.tools.multion.update_session import MultionUpdateSession\n[docs]class MultionToolkit(BaseToolkit):\n    \"\"\"Toolkit for interacting with the Browser Agent.\n    **Security Note**: This toolkit contains tools that interact with the\n        user's browser via the multion API which grants an agent\n        access to the user's browser.\n        Please review the documentation for the multion API to understand\n        the security implications of using this toolkit.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    class Config:\n        \"\"\"Pydantic config.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        return [MultionCreateSession(), MultionUpdateSession(), MultionCloseSession()]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/multion/toolkit.html"}
{"id": "def8dccbc99b-0", "text": "Source code for langchain.agents.agent_toolkits.gitlab.toolkit\n\"\"\"GitHub Toolkit.\"\"\"\nfrom typing import Dict, List\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.tools import BaseTool\nfrom langchain.tools.gitlab.prompt import (\n    COMMENT_ON_ISSUE_PROMPT,\n    CREATE_FILE_PROMPT,\n    CREATE_PULL_REQUEST_PROMPT,\n    DELETE_FILE_PROMPT,\n    GET_ISSUE_PROMPT,\n    GET_ISSUES_PROMPT,\n    READ_FILE_PROMPT,\n    UPDATE_FILE_PROMPT,\n)\nfrom langchain.tools.gitlab.tool import GitLabAction\nfrom langchain.utilities.gitlab import GitLabAPIWrapper\n[docs]class GitLabToolkit(BaseToolkit):\n    \"\"\"GitLab Toolkit.\n    *Security Note*: This toolkit contains tools that can read and modify\n        the state of a service; e.g., by creating, deleting, or updating,\n        reading underlying data.\n        For example, this toolkit can be used to create issues, pull requests,\n        and comments on GitLab.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    tools: List[BaseTool] = []\n[docs]    @classmethod\n    def from_gitlab_api_wrapper(\n        cls, gitlab_api_wrapper: GitLabAPIWrapper\n    ) -> \"GitLabToolkit\":\n        operations: List[Dict] = [\n            {\n                \"mode\": \"get_issues\",\n                \"name\": \"Get Issues\",\n                \"description\": GET_ISSUES_PROMPT,\n            },\n            {\n                \"mode\": \"get_issue\",\n                \"name\": \"Get Issue\",\n                \"description\": GET_ISSUE_PROMPT,\n            },\n            {\n                \"mode\": \"comment_on_issue\",\n                \"name\": \"Comment on Issue\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/gitlab/toolkit.html"}
{"id": "def8dccbc99b-1", "text": "\"mode\": \"comment_on_issue\",\n                \"name\": \"Comment on Issue\",\n                \"description\": COMMENT_ON_ISSUE_PROMPT,\n            },\n            {\n                \"mode\": \"create_pull_request\",\n                \"name\": \"Create Pull Request\",\n                \"description\": CREATE_PULL_REQUEST_PROMPT,\n            },\n            {\n                \"mode\": \"create_file\",\n                \"name\": \"Create File\",\n                \"description\": CREATE_FILE_PROMPT,\n            },\n            {\n                \"mode\": \"read_file\",\n                \"name\": \"Read File\",\n                \"description\": READ_FILE_PROMPT,\n            },\n            {\n                \"mode\": \"update_file\",\n                \"name\": \"Update File\",\n                \"description\": UPDATE_FILE_PROMPT,\n            },\n            {\n                \"mode\": \"delete_file\",\n                \"name\": \"Delete File\",\n                \"description\": DELETE_FILE_PROMPT,\n            },\n        ]\n        tools = [\n            GitLabAction(\n                name=action[\"name\"],\n                description=action[\"description\"],\n                mode=action[\"mode\"],\n                api_wrapper=gitlab_api_wrapper,\n            )\n            for action in operations\n        ]\n        return cls(tools=tools)\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        return self.tools", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/gitlab/toolkit.html"}
{"id": "fb640b5d18b7-0", "text": "Source code for langchain.agents.agent_toolkits.amadeus.toolkit\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, List\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools import BaseTool\nfrom langchain.tools.amadeus.closest_airport import AmadeusClosestAirport\nfrom langchain.tools.amadeus.flight_search import AmadeusFlightSearch\nfrom langchain.tools.amadeus.utils import authenticate\nif TYPE_CHECKING:\n    from amadeus import Client\n[docs]class AmadeusToolkit(BaseToolkit):\n    \"\"\"Toolkit for interacting with Amadeus which offers APIs for travel search.\"\"\"\n    client: Client = Field(default_factory=authenticate)\n    class Config:\n        \"\"\"Pydantic config.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        return [\n            AmadeusClosestAirport(),\n            AmadeusFlightSearch(),\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/amadeus/toolkit.html"}
{"id": "6f02f6fc8997-0", "text": "Source code for langchain.agents.agent_toolkits.zapier.toolkit\n\"\"\"[DEPRECATED] Zapier Toolkit.\"\"\"\nfrom typing import List\nfrom langchain._api import warn_deprecated\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.tools import BaseTool\nfrom langchain.tools.zapier.tool import ZapierNLARunAction\nfrom langchain.utilities.zapier import ZapierNLAWrapper\n[docs]class ZapierToolkit(BaseToolkit):\n    \"\"\"Zapier Toolkit.\"\"\"\n    tools: List[BaseTool] = []\n[docs]    @classmethod\n    def from_zapier_nla_wrapper(\n        cls, zapier_nla_wrapper: ZapierNLAWrapper\n    ) -> \"ZapierToolkit\":\n        \"\"\"Create a toolkit from a ZapierNLAWrapper.\"\"\"\n        actions = zapier_nla_wrapper.list()\n        tools = [\n            ZapierNLARunAction(\n                action_id=action[\"id\"],\n                zapier_description=action[\"description\"],\n                params_schema=action[\"params\"],\n                api_wrapper=zapier_nla_wrapper,\n            )\n            for action in actions\n        ]\n        return cls(tools=tools)\n[docs]    @classmethod\n    async def async_from_zapier_nla_wrapper(\n        cls, zapier_nla_wrapper: ZapierNLAWrapper\n    ) -> \"ZapierToolkit\":\n        \"\"\"Create a toolkit from a ZapierNLAWrapper.\"\"\"\n        actions = await zapier_nla_wrapper.alist()\n        tools = [\n            ZapierNLARunAction(\n                action_id=action[\"id\"],\n                zapier_description=action[\"description\"],\n                params_schema=action[\"params\"],\n                api_wrapper=zapier_nla_wrapper,\n            )\n            for action in actions\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/zapier/toolkit.html"}
{"id": "6f02f6fc8997-1", "text": ")\n            for action in actions\n        ]\n        return cls(tools=tools)\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        warn_deprecated(\n            since=\"0.0.319\",\n            message=(\n                \"This tool will be deprecated on 2023-11-17. See \"\n                \"https://nla.zapier.com/sunset/ for details\"\n            ),\n        )\n        return self.tools", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/zapier/toolkit.html"}
{"id": "d1aaa64ee72c-0", "text": "Source code for langchain.agents.agent_toolkits.github.toolkit\n\"\"\"GitHub Toolkit.\"\"\"\nfrom typing import Dict, List\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.tools import BaseTool\nfrom langchain.tools.github.prompt import (\n    COMMENT_ON_ISSUE_PROMPT,\n    CREATE_FILE_PROMPT,\n    CREATE_PULL_REQUEST_PROMPT,\n    DELETE_FILE_PROMPT,\n    GET_ISSUE_PROMPT,\n    GET_ISSUES_PROMPT,\n    READ_FILE_PROMPT,\n    UPDATE_FILE_PROMPT,\n)\nfrom langchain.tools.github.tool import GitHubAction\nfrom langchain.utilities.github import GitHubAPIWrapper\n[docs]class GitHubToolkit(BaseToolkit):\n    \"\"\"GitHub Toolkit.\n    *Security Note*: This toolkit contains tools that can read and modify\n        the state of a service; e.g., by creating, deleting, or updating,\n        reading underlying data.\n        For example, this toolkit can be used to create issues, pull requests,\n        and comments on GitHub.\n        See [Security](https://python.langchain.com/docs/security) for more information.\n    \"\"\"\n    tools: List[BaseTool] = []\n[docs]    @classmethod\n    def from_github_api_wrapper(\n        cls, github_api_wrapper: GitHubAPIWrapper\n    ) -> \"GitHubToolkit\":\n        operations: List[Dict] = [\n            {\n                \"mode\": \"get_issues\",\n                \"name\": \"Get Issues\",\n                \"description\": GET_ISSUES_PROMPT,\n            },\n            {\n                \"mode\": \"get_issue\",\n                \"name\": \"Get Issue\",\n                \"description\": GET_ISSUE_PROMPT,\n            },\n            {\n                \"mode\": \"comment_on_issue\",\n                \"name\": \"Comment on Issue\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/github/toolkit.html"}
{"id": "d1aaa64ee72c-1", "text": "\"mode\": \"comment_on_issue\",\n                \"name\": \"Comment on Issue\",\n                \"description\": COMMENT_ON_ISSUE_PROMPT,\n            },\n            {\n                \"mode\": \"create_pull_request\",\n                \"name\": \"Create Pull Request\",\n                \"description\": CREATE_PULL_REQUEST_PROMPT,\n            },\n            {\n                \"mode\": \"create_file\",\n                \"name\": \"Create File\",\n                \"description\": CREATE_FILE_PROMPT,\n            },\n            {\n                \"mode\": \"read_file\",\n                \"name\": \"Read File\",\n                \"description\": READ_FILE_PROMPT,\n            },\n            {\n                \"mode\": \"update_file\",\n                \"name\": \"Update File\",\n                \"description\": UPDATE_FILE_PROMPT,\n            },\n            {\n                \"mode\": \"delete_file\",\n                \"name\": \"Delete File\",\n                \"description\": DELETE_FILE_PROMPT,\n            },\n        ]\n        tools = [\n            GitHubAction(\n                name=action[\"name\"],\n                description=action[\"description\"],\n                mode=action[\"mode\"],\n                api_wrapper=github_api_wrapper,\n            )\n            for action in operations\n        ]\n        return cls(tools=tools)\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        return self.tools", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/github/toolkit.html"}
{"id": "ee5e3713bed0-0", "text": "Source code for langchain.agents.agent_toolkits.file_management.toolkit\nfrom __future__ import annotations\nfrom typing import List, Optional\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.tools import BaseTool\nfrom langchain.tools.file_management.copy import CopyFileTool\nfrom langchain.tools.file_management.delete import DeleteFileTool\nfrom langchain.tools.file_management.file_search import FileSearchTool\nfrom langchain.tools.file_management.list_dir import ListDirectoryTool\nfrom langchain.tools.file_management.move import MoveFileTool\nfrom langchain.tools.file_management.read import ReadFileTool\nfrom langchain.tools.file_management.write import WriteFileTool\n_FILE_TOOLS = {\n    # \"Type[Runnable[Any, Any]]\" has no attribute \"__fields__\"  [attr-defined]\n    tool_cls.__fields__[\"name\"].default: tool_cls  # type: ignore[attr-defined]\n    for tool_cls in [\n        CopyFileTool,\n        DeleteFileTool,\n        FileSearchTool,\n        MoveFileTool,\n        ReadFileTool,\n        WriteFileTool,\n        ListDirectoryTool,\n    ]\n}\n[docs]class FileManagementToolkit(BaseToolkit):\n    \"\"\"Toolkit for interacting with local files.\n    *Security Notice*: This toolkit provides methods to interact with local files.\n        If providing this toolkit to an agent on an LLM, ensure you scope\n        the agent's permissions to only include the necessary permissions\n        to perform the desired operations.\n        By **default** the agent will have access to all files within\n        the root dir and will be able to Copy, Delete, Move, Read, Write\n        and List files in that directory.\n        Consider the following:\n        - Limit access to particular directories using `root_dir`.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/file_management/toolkit.html"}
{"id": "ee5e3713bed0-1", "text": "Consider the following:\n        - Limit access to particular directories using `root_dir`.\n        - Use filesystem permissions to restrict access and permissions to only\n          the files and directories required by the agent.\n        - Limit the tools available to the agent to only the file operations\n          necessary for the agent's intended use.\n        - Sandbox the agent by running it in a container.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    root_dir: Optional[str] = None\n    \"\"\"If specified, all file operations are made relative to root_dir.\"\"\"\n    selected_tools: Optional[List[str]] = None\n    \"\"\"If provided, only provide the selected tools. Defaults to all.\"\"\"\n    @root_validator\n    def validate_tools(cls, values: dict) -> dict:\n        selected_tools = values.get(\"selected_tools\") or []\n        for tool_name in selected_tools:\n            if tool_name not in _FILE_TOOLS:\n                raise ValueError(\n                    f\"File Tool of name {tool_name} not supported.\"\n                    f\" Permitted tools: {list(_FILE_TOOLS)}\"\n                )\n        return values\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        allowed_tools = self.selected_tools or _FILE_TOOLS.keys()\n        tools: List[BaseTool] = []\n        for tool in allowed_tools:\n            tool_cls = _FILE_TOOLS[tool]\n            tools.append(tool_cls(root_dir=self.root_dir))  # type: ignore\n        return tools\n__all__ = [\"FileManagementToolkit\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/file_management/toolkit.html"}
{"id": "5adcae62f904-0", "text": "Source code for langchain.agents.agent_toolkits.clickup.toolkit\nfrom typing import Dict, List\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.tools import BaseTool\nfrom langchain.tools.clickup.prompt import (\n    CLICKUP_FOLDER_CREATE_PROMPT,\n    CLICKUP_GET_ALL_TEAMS_PROMPT,\n    CLICKUP_GET_FOLDERS_PROMPT,\n    CLICKUP_GET_LIST_PROMPT,\n    CLICKUP_GET_SPACES_PROMPT,\n    CLICKUP_GET_TASK_ATTRIBUTE_PROMPT,\n    CLICKUP_GET_TASK_PROMPT,\n    CLICKUP_LIST_CREATE_PROMPT,\n    CLICKUP_TASK_CREATE_PROMPT,\n    CLICKUP_UPDATE_TASK_ASSIGNEE_PROMPT,\n    CLICKUP_UPDATE_TASK_PROMPT,\n)\nfrom langchain.tools.clickup.tool import ClickupAction\nfrom langchain.utilities.clickup import ClickupAPIWrapper\n[docs]class ClickupToolkit(BaseToolkit):\n    \"\"\"Clickup Toolkit.\n    *Security Note*: This toolkit contains tools that can read and modify\n        the state of a service; e.g., by reading, creating, updating, deleting\n        data associated with this service.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    tools: List[BaseTool] = []\n[docs]    @classmethod\n    def from_clickup_api_wrapper(\n        cls, clickup_api_wrapper: ClickupAPIWrapper\n    ) -> \"ClickupToolkit\":\n        operations: List[Dict] = [\n            {\n                \"mode\": \"get_task\",\n                \"name\": \"Get task\",\n                \"description\": CLICKUP_GET_TASK_PROMPT,\n            },\n            {\n                \"mode\": \"get_task_attribute\",\n                \"name\": \"Get task attribute\",\n                \"description\": CLICKUP_GET_TASK_ATTRIBUTE_PROMPT,\n            },", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/clickup/toolkit.html"}
{"id": "5adcae62f904-1", "text": "\"description\": CLICKUP_GET_TASK_ATTRIBUTE_PROMPT,\n            },\n            {\n                \"mode\": \"get_teams\",\n                \"name\": \"Get Teams\",\n                \"description\": CLICKUP_GET_ALL_TEAMS_PROMPT,\n            },\n            {\n                \"mode\": \"create_task\",\n                \"name\": \"Create Task\",\n                \"description\": CLICKUP_TASK_CREATE_PROMPT,\n            },\n            {\n                \"mode\": \"create_list\",\n                \"name\": \"Create List\",\n                \"description\": CLICKUP_LIST_CREATE_PROMPT,\n            },\n            {\n                \"mode\": \"create_folder\",\n                \"name\": \"Create Folder\",\n                \"description\": CLICKUP_FOLDER_CREATE_PROMPT,\n            },\n            {\n                \"mode\": \"get_list\",\n                \"name\": \"Get all lists in the space\",\n                \"description\": CLICKUP_GET_LIST_PROMPT,\n            },\n            {\n                \"mode\": \"get_folders\",\n                \"name\": \"Get all folders in the workspace\",\n                \"description\": CLICKUP_GET_FOLDERS_PROMPT,\n            },\n            {\n                \"mode\": \"get_spaces\",\n                \"name\": \"Get all spaces in the workspace\",\n                \"description\": CLICKUP_GET_SPACES_PROMPT,\n            },\n            {\n                \"mode\": \"update_task\",\n                \"name\": \"Update task\",\n                \"description\": CLICKUP_UPDATE_TASK_PROMPT,\n            },\n            {\n                \"mode\": \"update_task_assignees\",\n                \"name\": \"Update task assignees\",\n                \"description\": CLICKUP_UPDATE_TASK_ASSIGNEE_PROMPT,\n            },\n        ]\n        tools = [\n            ClickupAction(\n                name=action[\"name\"],\n                description=action[\"description\"],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/clickup/toolkit.html"}
{"id": "5adcae62f904-2", "text": "name=action[\"name\"],\n                description=action[\"description\"],\n                mode=action[\"mode\"],\n                api_wrapper=clickup_api_wrapper,\n            )\n            for action in operations\n        ]\n        return cls(tools=tools)\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        return self.tools", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/clickup/toolkit.html"}
{"id": "4e07f41e034f-0", "text": "Source code for langchain.agents.agent_toolkits.office365.toolkit\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, List\nfrom langchain.agents.agent_toolkits.base import BaseToolkit\nfrom langchain.pydantic_v1 import Field\nfrom langchain.tools import BaseTool\nfrom langchain.tools.office365.create_draft_message import O365CreateDraftMessage\nfrom langchain.tools.office365.events_search import O365SearchEvents\nfrom langchain.tools.office365.messages_search import O365SearchEmails\nfrom langchain.tools.office365.send_event import O365SendEvent\nfrom langchain.tools.office365.send_message import O365SendMessage\nfrom langchain.tools.office365.utils import authenticate\nif TYPE_CHECKING:\n    from O365 import Account\n[docs]class O365Toolkit(BaseToolkit):\n    \"\"\"Toolkit for interacting with Office 365.\n    *Security Note*: This toolkit contains tools that can read and modify\n        the state of a service; e.g., by reading, creating, updating, deleting\n        data associated with this service.\n        For example, this toolkit can be used search through emails and events,\n        send messages and event invites, and create draft messages.\n        Please make sure that the permissions given by this toolkit\n        are appropriate for your use case.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n    account: Account = Field(default_factory=authenticate)\n    class Config:\n        \"\"\"Pydantic config.\"\"\"\n        arbitrary_types_allowed = True\n[docs]    def get_tools(self) -> List[BaseTool]:\n        \"\"\"Get the tools in the toolkit.\"\"\"\n        return [\n            O365SearchEvents(),\n            O365CreateDraftMessage(),\n            O365SearchEmails(),\n            O365SendEvent(),\n            O365SendMessage(),\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/office365/toolkit.html"}
{"id": "d51947dbd3f5-0", "text": "Source code for langchain.agents.agent_toolkits.conversational_retrieval.openai_functions\nfrom typing import Any, List, Optional\nfrom langchain.agents.agent import AgentExecutor\nfrom langchain.agents.openai_functions_agent.agent_token_buffer_memory import (\n    AgentTokenBufferMemory,\n)\nfrom langchain.agents.openai_functions_agent.base import OpenAIFunctionsAgent\nfrom langchain.chat_models.openai import ChatOpenAI\nfrom langchain.memory.token_buffer import ConversationTokenBufferMemory\nfrom langchain.prompts.chat import MessagesPlaceholder\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.memory import BaseMemory\nfrom langchain.schema.messages import SystemMessage\nfrom langchain.tools.base import BaseTool\ndef _get_default_system_message() -> SystemMessage:\n    return SystemMessage(\n        content=(\n            \"Do your best to answer the questions. \"\n            \"Feel free to use any tools available to look up \"\n            \"relevant information, only if necessary\"\n        )\n    )\n[docs]def create_conversational_retrieval_agent(\n    llm: BaseLanguageModel,\n    tools: List[BaseTool],\n    remember_intermediate_steps: bool = True,\n    memory_key: str = \"chat_history\",\n    system_message: Optional[SystemMessage] = None,\n    verbose: bool = False,\n    max_token_limit: int = 2000,\n    **kwargs: Any,\n) -> AgentExecutor:\n    \"\"\"A convenience method for creating a conversational retrieval agent.\n    Args:\n        llm: The language model to use, should be ChatOpenAI\n        tools: A list of tools the agent has access to\n        remember_intermediate_steps: Whether the agent should remember intermediate\n            steps or not. Intermediate steps refer to prior action/observation", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/conversational_retrieval/openai_functions.html"}
{"id": "d51947dbd3f5-1", "text": "steps or not. Intermediate steps refer to prior action/observation\n            pairs from previous questions. The benefit of remembering these is if\n            there is relevant information in there, the agent can use it to answer\n            follow up questions. The downside is it will take up more tokens.\n        memory_key: The name of the memory key in the prompt.\n        system_message: The system message to use. By default, a basic one will\n            be used.\n        verbose: Whether or not the final AgentExecutor should be verbose or not,\n            defaults to False.\n        max_token_limit: The max number of tokens to keep around in memory.\n            Defaults to 2000.\n    Returns:\n        An agent executor initialized appropriately\n    \"\"\"\n    if not isinstance(llm, ChatOpenAI):\n        raise ValueError(\"Only supported with ChatOpenAI models.\")\n    if remember_intermediate_steps:\n        memory: BaseMemory = AgentTokenBufferMemory(\n            memory_key=memory_key, llm=llm, max_token_limit=max_token_limit\n        )\n    else:\n        memory = ConversationTokenBufferMemory(\n            memory_key=memory_key,\n            return_messages=True,\n            output_key=\"output\",\n            llm=llm,\n            max_token_limit=max_token_limit,\n        )\n    _system_message = system_message or _get_default_system_message()\n    prompt = OpenAIFunctionsAgent.create_prompt(\n        system_message=_system_message,\n        extra_prompt_messages=[MessagesPlaceholder(variable_name=memory_key)],\n    )\n    agent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=prompt)\n    return AgentExecutor(\n        agent=agent,\n        tools=tools,\n        memory=memory,\n        verbose=verbose,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/conversational_retrieval/openai_functions.html"}
{"id": "d51947dbd3f5-2", "text": "tools=tools,\n        memory=memory,\n        verbose=verbose,\n        return_intermediate_steps=remember_intermediate_steps,\n        **kwargs,\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/conversational_retrieval/openai_functions.html"}
{"id": "54d960f9c97d-0", "text": "Source code for langchain.agents.chat.base\nfrom typing import Any, List, Optional, Sequence, Tuple\nfrom langchain.agents.agent import Agent, AgentOutputParser\nfrom langchain.agents.chat.output_parser import ChatOutputParser\nfrom langchain.agents.chat.prompt import (\n    FORMAT_INSTRUCTIONS,\n    HUMAN_MESSAGE,\n    SYSTEM_MESSAGE_PREFIX,\n    SYSTEM_MESSAGE_SUFFIX,\n)\nfrom langchain.agents.utils import validate_tools_single_input\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains.llm import LLMChain\nfrom langchain.prompts.chat import (\n    ChatPromptTemplate,\n    HumanMessagePromptTemplate,\n    SystemMessagePromptTemplate,\n)\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import AgentAction, BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools.base import BaseTool\n[docs]class ChatAgent(Agent):\n    \"\"\"Chat Agent.\"\"\"\n    output_parser: AgentOutputParser = Field(default_factory=ChatOutputParser)\n    \"\"\"Output parser for the agent.\"\"\"\n    @property\n    def observation_prefix(self) -> str:\n        \"\"\"Prefix to append the observation with.\"\"\"\n        return \"Observation: \"\n    @property\n    def llm_prefix(self) -> str:\n        \"\"\"Prefix to append the llm call with.\"\"\"\n        return \"Thought:\"\n    def _construct_scratchpad(\n        self, intermediate_steps: List[Tuple[AgentAction, str]]\n    ) -> str:\n        agent_scratchpad = super()._construct_scratchpad(intermediate_steps)\n        if not isinstance(agent_scratchpad, str):\n            raise ValueError(\"agent_scratchpad should be of type string.\")\n        if agent_scratchpad:\n            return (\n                f\"This was your previous work \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/chat/base.html"}
{"id": "54d960f9c97d-1", "text": "return (\n                f\"This was your previous work \"\n                f\"(but I haven't seen any of it! I only see what \"\n                f\"you return as final answer):\\n{agent_scratchpad}\"\n            )\n        else:\n            return agent_scratchpad\n    @classmethod\n    def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:\n        return ChatOutputParser()\n    @classmethod\n    def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:\n        super()._validate_tools(tools)\n        validate_tools_single_input(class_name=cls.__name__, tools=tools)\n    @property\n    def _stop(self) -> List[str]:\n        return [\"Observation:\"]\n[docs]    @classmethod\n    def create_prompt(\n        cls,\n        tools: Sequence[BaseTool],\n        system_message_prefix: str = SYSTEM_MESSAGE_PREFIX,\n        system_message_suffix: str = SYSTEM_MESSAGE_SUFFIX,\n        human_message: str = HUMAN_MESSAGE,\n        format_instructions: str = FORMAT_INSTRUCTIONS,\n        input_variables: Optional[List[str]] = None,\n    ) -> BasePromptTemplate:\n        tool_strings = \"\\n\".join([f\"{tool.name}: {tool.description}\" for tool in tools])\n        tool_names = \", \".join([tool.name for tool in tools])\n        format_instructions = format_instructions.format(tool_names=tool_names)\n        template = \"\\n\\n\".join(\n            [\n                system_message_prefix,\n                tool_strings,\n                format_instructions,\n                system_message_suffix,\n            ]\n        )\n        messages = [\n            SystemMessagePromptTemplate.from_template(template),\n            HumanMessagePromptTemplate.from_template(human_message),\n        ]\n        if input_variables is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/chat/base.html"}
{"id": "54d960f9c97d-2", "text": "]\n        if input_variables is None:\n            input_variables = [\"input\", \"agent_scratchpad\"]\n        return ChatPromptTemplate(input_variables=input_variables, messages=messages)\n[docs]    @classmethod\n    def from_llm_and_tools(\n        cls,\n        llm: BaseLanguageModel,\n        tools: Sequence[BaseTool],\n        callback_manager: Optional[BaseCallbackManager] = None,\n        output_parser: Optional[AgentOutputParser] = None,\n        system_message_prefix: str = SYSTEM_MESSAGE_PREFIX,\n        system_message_suffix: str = SYSTEM_MESSAGE_SUFFIX,\n        human_message: str = HUMAN_MESSAGE,\n        format_instructions: str = FORMAT_INSTRUCTIONS,\n        input_variables: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Agent:\n        \"\"\"Construct an agent from an LLM and tools.\"\"\"\n        cls._validate_tools(tools)\n        prompt = cls.create_prompt(\n            tools,\n            system_message_prefix=system_message_prefix,\n            system_message_suffix=system_message_suffix,\n            human_message=human_message,\n            format_instructions=format_instructions,\n            input_variables=input_variables,\n        )\n        llm_chain = LLMChain(\n            llm=llm,\n            prompt=prompt,\n            callback_manager=callback_manager,\n        )\n        tool_names = [tool.name for tool in tools]\n        _output_parser = output_parser or cls._get_default_output_parser()\n        return cls(\n            llm_chain=llm_chain,\n            allowed_tools=tool_names,\n            output_parser=_output_parser,\n            **kwargs,\n        )\n    @property\n    def _agent_type(self) -> str:\n        raise ValueError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/chat/base.html"}
{"id": "75ec7ae6683a-0", "text": "Source code for langchain.agents.chat.output_parser\nimport json\nimport re\nfrom typing import Union\nfrom langchain.agents.agent import AgentOutputParser\nfrom langchain.agents.chat.prompt import FORMAT_INSTRUCTIONS\nfrom langchain.schema import AgentAction, AgentFinish, OutputParserException\nFINAL_ANSWER_ACTION = \"Final Answer:\"\n[docs]class ChatOutputParser(AgentOutputParser):\n    \"\"\"Output parser for the chat agent.\"\"\"\n    pattern = re.compile(r\"^.*?`{3}(?:json)?\\n(.*?)`{3}.*?$\", re.DOTALL)\n    \"\"\"Regex pattern to parse the output.\"\"\"\n[docs]    def get_format_instructions(self) -> str:\n        return FORMAT_INSTRUCTIONS\n[docs]    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        includes_answer = FINAL_ANSWER_ACTION in text\n        try:\n            found = self.pattern.search(text)\n            if not found:\n                # Fast fail to parse Final Answer.\n                raise ValueError(\"action not found\")\n            action = found.group(1)\n            response = json.loads(action.strip())\n            includes_action = \"action\" in response\n            if includes_answer and includes_action:\n                raise OutputParserException(\n                    \"Parsing LLM output produced a final answer \"\n                    f\"and a parse-able action: {text}\"\n                )\n            return AgentAction(\n                response[\"action\"], response.get(\"action_input\", {}), text\n            )\n        except Exception as exc:\n            if not includes_answer:\n                raise OutputParserException(\n                    f\"Could not parse LLM output: {text}\"\n                ) from exc\n            output = text.split(FINAL_ANSWER_ACTION)[-1].strip()\n            return AgentFinish({\"output\": output}, text)\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/chat/output_parser.html"}
{"id": "75ec7ae6683a-1", "text": "return AgentFinish({\"output\": output}, text)\n    @property\n    def _type(self) -> str:\n        return \"chat\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/chat/output_parser.html"}
{"id": "fbec6f99dde1-0", "text": "Source code for langchain.agents.mrkl.base\n\"\"\"Attempt to implement MRKL systems as described in arxiv.org/pdf/2205.00445.pdf.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Callable, List, NamedTuple, Optional, Sequence\nfrom langchain.agents.agent import Agent, AgentExecutor, AgentOutputParser\nfrom langchain.agents.agent_types import AgentType\nfrom langchain.agents.mrkl.output_parser import MRKLOutputParser\nfrom langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS, PREFIX, SUFFIX\nfrom langchain.agents.tools import Tool\nfrom langchain.agents.utils import validate_tools_single_input\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains import LLMChain\nfrom langchain.prompts import PromptTemplate\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools.base import BaseTool\n[docs]class ChainConfig(NamedTuple):\n    \"\"\"Configuration for chain to use in MRKL system.\n    Args:\n        action_name: Name of the action.\n        action: Action function to call.\n        action_description: Description of the action.\n    \"\"\"\n    action_name: str\n    action: Callable\n    action_description: str\n[docs]class ZeroShotAgent(Agent):\n    \"\"\"Agent for the MRKL chain.\"\"\"\n    output_parser: AgentOutputParser = Field(default_factory=MRKLOutputParser)\n    @classmethod\n    def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:\n        return MRKLOutputParser()\n    @property\n    def _agent_type(self) -> str:\n        \"\"\"Return Identifier of agent type.\"\"\"\n        return AgentType.ZERO_SHOT_REACT_DESCRIPTION\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html"}
{"id": "fbec6f99dde1-1", "text": "return AgentType.ZERO_SHOT_REACT_DESCRIPTION\n    @property\n    def observation_prefix(self) -> str:\n        \"\"\"Prefix to append the observation with.\"\"\"\n        return \"Observation: \"\n    @property\n    def llm_prefix(self) -> str:\n        \"\"\"Prefix to append the llm call with.\"\"\"\n        return \"Thought:\"\n[docs]    @classmethod\n    def create_prompt(\n        cls,\n        tools: Sequence[BaseTool],\n        prefix: str = PREFIX,\n        suffix: str = SUFFIX,\n        format_instructions: str = FORMAT_INSTRUCTIONS,\n        input_variables: Optional[List[str]] = None,\n    ) -> PromptTemplate:\n        \"\"\"Create prompt in the style of the zero shot agent.\n        Args:\n            tools: List of tools the agent will have access to, used to format the\n                prompt.\n            prefix: String to put before the list of tools.\n            suffix: String to put after the list of tools.\n            input_variables: List of input variables the final prompt will expect.\n        Returns:\n            A PromptTemplate with the template assembled from the pieces here.\n        \"\"\"\n        tool_strings = \"\\n\".join([f\"{tool.name}: {tool.description}\" for tool in tools])\n        tool_names = \", \".join([tool.name for tool in tools])\n        format_instructions = format_instructions.format(tool_names=tool_names)\n        template = \"\\n\\n\".join([prefix, tool_strings, format_instructions, suffix])\n        if input_variables is None:\n            input_variables = [\"input\", \"agent_scratchpad\"]\n        return PromptTemplate(template=template, input_variables=input_variables)\n[docs]    @classmethod\n    def from_llm_and_tools(\n        cls,\n        llm: BaseLanguageModel,\n        tools: Sequence[BaseTool],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html"}
{"id": "fbec6f99dde1-2", "text": "llm: BaseLanguageModel,\n        tools: Sequence[BaseTool],\n        callback_manager: Optional[BaseCallbackManager] = None,\n        output_parser: Optional[AgentOutputParser] = None,\n        prefix: str = PREFIX,\n        suffix: str = SUFFIX,\n        format_instructions: str = FORMAT_INSTRUCTIONS,\n        input_variables: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Agent:\n        \"\"\"Construct an agent from an LLM and tools.\"\"\"\n        cls._validate_tools(tools)\n        prompt = cls.create_prompt(\n            tools,\n            prefix=prefix,\n            suffix=suffix,\n            format_instructions=format_instructions,\n            input_variables=input_variables,\n        )\n        llm_chain = LLMChain(\n            llm=llm,\n            prompt=prompt,\n            callback_manager=callback_manager,\n        )\n        tool_names = [tool.name for tool in tools]\n        _output_parser = output_parser or cls._get_default_output_parser()\n        return cls(\n            llm_chain=llm_chain,\n            allowed_tools=tool_names,\n            output_parser=_output_parser,\n            **kwargs,\n        )\n    @classmethod\n    def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:\n        validate_tools_single_input(cls.__name__, tools)\n        if len(tools) == 0:\n            raise ValueError(\n                f\"Got no tools for {cls.__name__}. At least one tool must be provided.\"\n            )\n        for tool in tools:\n            if tool.description is None:\n                raise ValueError(\n                    f\"Got a tool {tool.name} without a description. For this agent, \"\n                    f\"a description must always be provided.\"\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html"}
{"id": "fbec6f99dde1-3", "text": "f\"a description must always be provided.\"\n                )\n        super()._validate_tools(tools)\n[docs]class MRKLChain(AgentExecutor):\n    \"\"\"[Deprecated] Chain that implements the MRKL system.\"\"\"\n[docs]    @classmethod\n    def from_chains(\n        cls, llm: BaseLanguageModel, chains: List[ChainConfig], **kwargs: Any\n    ) -> AgentExecutor:\n        \"\"\"User friendly way to initialize the MRKL chain.\n        This is intended to be an easy way to get up and running with the\n        MRKL chain.\n        Args:\n            llm: The LLM to use as the agent LLM.\n            chains: The chains the MRKL system has access to.\n            **kwargs: parameters to be passed to initialization.\n        Returns:\n            An initialized MRKL chain.\n        \"\"\"\n        tools = [\n            Tool(\n                name=c.action_name,\n                func=c.action,\n                description=c.action_description,\n            )\n            for c in chains\n        ]\n        agent = ZeroShotAgent.from_llm_and_tools(llm, tools)\n        return cls(agent=agent, tools=tools, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html"}
{"id": "cebfdb148fc0-0", "text": "Source code for langchain.agents.mrkl.output_parser\nimport re\nfrom typing import Union\nfrom langchain.agents.agent import AgentOutputParser\nfrom langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS\nfrom langchain.schema import AgentAction, AgentFinish, OutputParserException\nFINAL_ANSWER_ACTION = \"Final Answer:\"\nMISSING_ACTION_AFTER_THOUGHT_ERROR_MESSAGE = (\n    \"Invalid Format: Missing 'Action:' after 'Thought:\"\n)\nMISSING_ACTION_INPUT_AFTER_ACTION_ERROR_MESSAGE = (\n    \"Invalid Format: Missing 'Action Input:' after 'Action:'\"\n)\nFINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE = (\n    \"Parsing LLM output produced both a final answer and a parse-able action:\"\n)\n[docs]class MRKLOutputParser(AgentOutputParser):\n    \"\"\"MRKL Output parser for the chat agent.\"\"\"\n[docs]    def get_format_instructions(self) -> str:\n        return FORMAT_INSTRUCTIONS\n[docs]    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        includes_answer = FINAL_ANSWER_ACTION in text\n        regex = (\n            r\"Action\\s*\\d*\\s*:[\\s]*(.*?)[\\s]*Action\\s*\\d*\\s*Input\\s*\\d*\\s*:[\\s]*(.*)\"\n        )\n        action_match = re.search(regex, text, re.DOTALL)\n        if action_match and includes_answer:\n            if text.find(FINAL_ANSWER_ACTION) < text.find(action_match.group(0)):\n                # if final answer is before the hallucination, return final answer\n                start_index = text.find(FINAL_ANSWER_ACTION) + len(FINAL_ANSWER_ACTION)\n                end_index = text.find(\"\\n\\n\", start_index)\n                return AgentFinish(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/output_parser.html"}
{"id": "cebfdb148fc0-1", "text": "end_index = text.find(\"\\n\\n\", start_index)\n                return AgentFinish(\n                    {\"output\": text[start_index:end_index].strip()}, text[:end_index]\n                )\n            else:\n                raise OutputParserException(\n                    f\"{FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: {text}\"\n                )\n        if action_match:\n            action = action_match.group(1).strip()\n            action_input = action_match.group(2)\n            tool_input = action_input.strip(\" \")\n            # ensure if its a well formed SQL query we don't remove any trailing \" chars\n            if tool_input.startswith(\"SELECT \") is False:\n                tool_input = tool_input.strip('\"')\n            return AgentAction(action, tool_input, text)\n        elif includes_answer:\n            return AgentFinish(\n                {\"output\": text.split(FINAL_ANSWER_ACTION)[-1].strip()}, text\n            )\n        if not re.search(r\"Action\\s*\\d*\\s*:[\\s]*(.*?)\", text, re.DOTALL):\n            raise OutputParserException(\n                f\"Could not parse LLM output: `{text}`\",\n                observation=MISSING_ACTION_AFTER_THOUGHT_ERROR_MESSAGE,\n                llm_output=text,\n                send_to_llm=True,\n            )\n        elif not re.search(\n            r\"[\\s]*Action\\s*\\d*\\s*Input\\s*\\d*\\s*:[\\s]*(.*)\", text, re.DOTALL\n        ):\n            raise OutputParserException(\n                f\"Could not parse LLM output: `{text}`\",\n                observation=MISSING_ACTION_INPUT_AFTER_ACTION_ERROR_MESSAGE,\n                llm_output=text,\n                send_to_llm=True,\n            )\n        else:\n            raise OutputParserException(f\"Could not parse LLM output: `{text}`\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/output_parser.html"}
{"id": "cebfdb148fc0-2", "text": "raise OutputParserException(f\"Could not parse LLM output: `{text}`\")\n    @property\n    def _type(self) -> str:\n        return \"mrkl\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/output_parser.html"}
{"id": "f80623bddd1b-0", "text": "Source code for langchain.agents.react.base\n\"\"\"Chain that implements the ReAct paper from https://arxiv.org/pdf/2210.03629.pdf.\"\"\"\nfrom typing import Any, List, Optional, Sequence\nfrom langchain.agents.agent import Agent, AgentExecutor, AgentOutputParser\nfrom langchain.agents.agent_types import AgentType\nfrom langchain.agents.react.output_parser import ReActOutputParser\nfrom langchain.agents.react.textworld_prompt import TEXTWORLD_PROMPT\nfrom langchain.agents.react.wiki_prompt import WIKI_PROMPT\nfrom langchain.agents.tools import Tool\nfrom langchain.agents.utils import validate_tools_single_input\nfrom langchain.docstore.base import Docstore\nfrom langchain.docstore.document import Document\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.tools.base import BaseTool\n[docs]class ReActDocstoreAgent(Agent):\n    \"\"\"Agent for the ReAct chain.\"\"\"\n    output_parser: AgentOutputParser = Field(default_factory=ReActOutputParser)\n    @classmethod\n    def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:\n        return ReActOutputParser()\n    @property\n    def _agent_type(self) -> str:\n        \"\"\"Return Identifier of an agent type.\"\"\"\n        return AgentType.REACT_DOCSTORE\n[docs]    @classmethod\n    def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate:\n        \"\"\"Return default prompt.\"\"\"\n        return WIKI_PROMPT\n    @classmethod\n    def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:\n        validate_tools_single_input(cls.__name__, tools)\n        super()._validate_tools(tools)\n        if len(tools) != 2:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html"}
{"id": "f80623bddd1b-1", "text": "super()._validate_tools(tools)\n        if len(tools) != 2:\n            raise ValueError(f\"Exactly two tools must be specified, but got {tools}\")\n        tool_names = {tool.name for tool in tools}\n        if tool_names != {\"Lookup\", \"Search\"}:\n            raise ValueError(\n                f\"Tool names should be Lookup and Search, got {tool_names}\"\n            )\n    @property\n    def observation_prefix(self) -> str:\n        \"\"\"Prefix to append the observation with.\"\"\"\n        return \"Observation: \"\n    @property\n    def _stop(self) -> List[str]:\n        return [\"\\nObservation:\"]\n    @property\n    def llm_prefix(self) -> str:\n        \"\"\"Prefix to append the LLM call with.\"\"\"\n        return \"Thought:\"\n[docs]class DocstoreExplorer:\n    \"\"\"Class to assist with exploration of a document store.\"\"\"\n[docs]    def __init__(self, docstore: Docstore):\n        \"\"\"Initialize with a docstore, and set initial document to None.\"\"\"\n        self.docstore = docstore\n        self.document: Optional[Document] = None\n        self.lookup_str = \"\"\n        self.lookup_index = 0\n[docs]    def search(self, term: str) -> str:\n        \"\"\"Search for a term in the docstore, and if found save.\"\"\"\n        result = self.docstore.search(term)\n        if isinstance(result, Document):\n            self.document = result\n            return self._summary\n        else:\n            self.document = None\n            return result\n[docs]    def lookup(self, term: str) -> str:\n        \"\"\"Lookup a term in document (if saved).\"\"\"\n        if self.document is None:\n            raise ValueError(\"Cannot lookup without a successful search first\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html"}
{"id": "f80623bddd1b-2", "text": "raise ValueError(\"Cannot lookup without a successful search first\")\n        if term.lower() != self.lookup_str:\n            self.lookup_str = term.lower()\n            self.lookup_index = 0\n        else:\n            self.lookup_index += 1\n        lookups = [p for p in self._paragraphs if self.lookup_str in p.lower()]\n        if len(lookups) == 0:\n            return \"No Results\"\n        elif self.lookup_index >= len(lookups):\n            return \"No More Results\"\n        else:\n            result_prefix = f\"(Result {self.lookup_index + 1}/{len(lookups)})\"\n            return f\"{result_prefix} {lookups[self.lookup_index]}\"\n    @property\n    def _summary(self) -> str:\n        return self._paragraphs[0]\n    @property\n    def _paragraphs(self) -> List[str]:\n        if self.document is None:\n            raise ValueError(\"Cannot get paragraphs without a document\")\n        return self.document.page_content.split(\"\\n\\n\")\n[docs]class ReActTextWorldAgent(ReActDocstoreAgent):\n    \"\"\"Agent for the ReAct TextWorld chain.\"\"\"\n[docs]    @classmethod\n    def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate:\n        \"\"\"Return default prompt.\"\"\"\n        return TEXTWORLD_PROMPT\n    @classmethod\n    def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:\n        validate_tools_single_input(cls.__name__, tools)\n        super()._validate_tools(tools)\n        if len(tools) != 1:\n            raise ValueError(f\"Exactly one tool must be specified, but got {tools}\")\n        tool_names = {tool.name for tool in tools}\n        if tool_names != {\"Play\"}:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html"}
{"id": "f80623bddd1b-3", "text": "if tool_names != {\"Play\"}:\n            raise ValueError(f\"Tool name should be Play, got {tool_names}\")\n[docs]class ReActChain(AgentExecutor):\n    \"\"\"[Deprecated] Chain that implements the ReAct paper.\"\"\"\n    def __init__(self, llm: BaseLanguageModel, docstore: Docstore, **kwargs: Any):\n        \"\"\"Initialize with the LLM and a docstore.\"\"\"\n        docstore_explorer = DocstoreExplorer(docstore)\n        tools = [\n            Tool(\n                name=\"Search\",\n                func=docstore_explorer.search,\n                description=\"Search for a term in the docstore.\",\n            ),\n            Tool(\n                name=\"Lookup\",\n                func=docstore_explorer.lookup,\n                description=\"Lookup a term in the docstore.\",\n            ),\n        ]\n        agent = ReActDocstoreAgent.from_llm_and_tools(llm, tools)\n        super().__init__(agent=agent, tools=tools, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html"}
{"id": "41bef2ccf4a5-0", "text": "Source code for langchain.agents.react.output_parser\nimport re\nfrom typing import Union\nfrom langchain.agents.agent import AgentOutputParser\nfrom langchain.schema import AgentAction, AgentFinish, OutputParserException\n[docs]class ReActOutputParser(AgentOutputParser):\n    \"\"\"Output parser for the ReAct agent.\"\"\"\n[docs]    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        action_prefix = \"Action: \"\n        if not text.strip().split(\"\\n\")[-1].startswith(action_prefix):\n            raise OutputParserException(f\"Could not parse LLM Output: {text}\")\n        action_block = text.strip().split(\"\\n\")[-1]\n        action_str = action_block[len(action_prefix) :]\n        # Parse out the action and the directive.\n        re_matches = re.search(r\"(.*?)\\[(.*?)\\]\", action_str)\n        if re_matches is None:\n            raise OutputParserException(\n                f\"Could not parse action directive: {action_str}\"\n            )\n        action, action_input = re_matches.group(1), re_matches.group(2)\n        if action == \"Finish\":\n            return AgentFinish({\"output\": action_input}, text)\n        else:\n            return AgentAction(action, action_input, text)\n    @property\n    def _type(self) -> str:\n        return \"react\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/react/output_parser.html"}
{"id": "00890ac95c01-0", "text": "Source code for langchain.agents.conversational_chat.base\n\"\"\"An agent designed to hold a conversation in addition to using tools.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, List, Optional, Sequence, Tuple\nfrom langchain.agents.agent import Agent, AgentOutputParser\nfrom langchain.agents.conversational_chat.output_parser import ConvoOutputParser\nfrom langchain.agents.conversational_chat.prompt import (\n    PREFIX,\n    SUFFIX,\n    TEMPLATE_TOOL_RESPONSE,\n)\nfrom langchain.agents.utils import validate_tools_single_input\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.chains import LLMChain\nfrom langchain.prompts.chat import (\n    ChatPromptTemplate,\n    HumanMessagePromptTemplate,\n    MessagesPlaceholder,\n    SystemMessagePromptTemplate,\n)\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import AgentAction, BaseOutputParser, BasePromptTemplate\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import AIMessage, BaseMessage, HumanMessage\nfrom langchain.tools.base import BaseTool\n[docs]class ConversationalChatAgent(Agent):\n    \"\"\"An agent designed to hold a conversation in addition to using tools.\"\"\"\n    output_parser: AgentOutputParser = Field(default_factory=ConvoOutputParser)\n    template_tool_response: str = TEMPLATE_TOOL_RESPONSE\n    @classmethod\n    def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:\n        return ConvoOutputParser()\n    @property\n    def _agent_type(self) -> str:\n        raise NotImplementedError\n    @property\n    def observation_prefix(self) -> str:\n        \"\"\"Prefix to append the observation with.\"\"\"\n        return \"Observation: \"\n    @property\n    def llm_prefix(self) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html"}
{"id": "00890ac95c01-1", "text": "@property\n    def llm_prefix(self) -> str:\n        \"\"\"Prefix to append the llm call with.\"\"\"\n        return \"Thought:\"\n    @classmethod\n    def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:\n        super()._validate_tools(tools)\n        validate_tools_single_input(cls.__name__, tools)\n[docs]    @classmethod\n    def create_prompt(\n        cls,\n        tools: Sequence[BaseTool],\n        system_message: str = PREFIX,\n        human_message: str = SUFFIX,\n        input_variables: Optional[List[str]] = None,\n        output_parser: Optional[BaseOutputParser] = None,\n    ) -> BasePromptTemplate:\n        tool_strings = \"\\n\".join(\n            [f\"> {tool.name}: {tool.description}\" for tool in tools]\n        )\n        tool_names = \", \".join([tool.name for tool in tools])\n        _output_parser = output_parser or cls._get_default_output_parser()\n        format_instructions = human_message.format(\n            format_instructions=_output_parser.get_format_instructions()\n        )\n        final_prompt = format_instructions.format(\n            tool_names=tool_names, tools=tool_strings\n        )\n        if input_variables is None:\n            input_variables = [\"input\", \"chat_history\", \"agent_scratchpad\"]\n        messages = [\n            SystemMessagePromptTemplate.from_template(system_message),\n            MessagesPlaceholder(variable_name=\"chat_history\"),\n            HumanMessagePromptTemplate.from_template(final_prompt),\n            MessagesPlaceholder(variable_name=\"agent_scratchpad\"),\n        ]\n        return ChatPromptTemplate(input_variables=input_variables, messages=messages)\n    def _construct_scratchpad(\n        self, intermediate_steps: List[Tuple[AgentAction, str]]\n    ) -> List[BaseMessage]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html"}
{"id": "00890ac95c01-2", "text": ") -> List[BaseMessage]:\n        \"\"\"Construct the scratchpad that lets the agent continue its thought process.\"\"\"\n        thoughts: List[BaseMessage] = []\n        for action, observation in intermediate_steps:\n            thoughts.append(AIMessage(content=action.log))\n            human_message = HumanMessage(\n                content=self.template_tool_response.format(observation=observation)\n            )\n            thoughts.append(human_message)\n        return thoughts\n[docs]    @classmethod\n    def from_llm_and_tools(\n        cls,\n        llm: BaseLanguageModel,\n        tools: Sequence[BaseTool],\n        callback_manager: Optional[BaseCallbackManager] = None,\n        output_parser: Optional[AgentOutputParser] = None,\n        system_message: str = PREFIX,\n        human_message: str = SUFFIX,\n        input_variables: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Agent:\n        \"\"\"Construct an agent from an LLM and tools.\"\"\"\n        cls._validate_tools(tools)\n        _output_parser = output_parser or cls._get_default_output_parser()\n        prompt = cls.create_prompt(\n            tools,\n            system_message=system_message,\n            human_message=human_message,\n            input_variables=input_variables,\n            output_parser=_output_parser,\n        )\n        llm_chain = LLMChain(\n            llm=llm,\n            prompt=prompt,\n            callback_manager=callback_manager,\n        )\n        tool_names = [tool.name for tool in tools]\n        return cls(\n            llm_chain=llm_chain,\n            allowed_tools=tool_names,\n            output_parser=_output_parser,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html"}
{"id": "daab0c5388fc-0", "text": "Source code for langchain.agents.conversational_chat.output_parser\nfrom __future__ import annotations\nfrom typing import Union\nfrom langchain.agents import AgentOutputParser\nfrom langchain.agents.conversational_chat.prompt import FORMAT_INSTRUCTIONS\nfrom langchain.output_parsers.json import parse_json_markdown\nfrom langchain.schema import AgentAction, AgentFinish, OutputParserException\n# Define a class that parses output for conversational agents\n[docs]class ConvoOutputParser(AgentOutputParser):\n    \"\"\"Output parser for the conversational agent.\"\"\"\n[docs]    def get_format_instructions(self) -> str:\n        \"\"\"Returns formatting instructions for the given output parser.\"\"\"\n        return FORMAT_INSTRUCTIONS\n[docs]    def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n        \"\"\"Attempts to parse the given text into an AgentAction or AgentFinish.\n        Raises:\n             OutputParserException if parsing fails.\n        \"\"\"\n        try:\n            # Attempt to parse the text into a structured format (assumed to be JSON\n            # stored as markdown)\n            response = parse_json_markdown(text)\n            # If the response contains an 'action' and 'action_input'\n            if \"action\" in response and \"action_input\" in response:\n                action, action_input = response[\"action\"], response[\"action_input\"]\n                # If the action indicates a final answer, return an AgentFinish\n                if action == \"Final Answer\":\n                    return AgentFinish({\"output\": action_input}, text)\n                else:\n                    # Otherwise, return an AgentAction with the specified action and\n                    # input\n                    return AgentAction(action, action_input, text)\n            else:\n                # If the necessary keys aren't present in the response, raise an\n                # exception\n                raise OutputParserException(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/output_parser.html"}
{"id": "daab0c5388fc-1", "text": "# exception\n                raise OutputParserException(\n                    f\"Missing 'action' or 'action_input' in LLM output: {text}\"\n                )\n        except Exception as e:\n            # If any other exception is raised during parsing, also raise an\n            # OutputParserException\n            raise OutputParserException(f\"Could not parse LLM output: {text}\") from e\n    @property\n    def _type(self) -> str:\n        return \"conversational_chat\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/output_parser.html"}
{"id": "18837e6fbfc6-0", "text": "Source code for langchain.agents.format_scratchpad.log\nfrom typing import List, Tuple\nfrom langchain.schema.agent import AgentAction\n[docs]def format_log_to_str(\n    intermediate_steps: List[Tuple[AgentAction, str]],\n    observation_prefix: str = \"Observation: \",\n    llm_prefix: str = \"Thought: \",\n) -> str:\n    \"\"\"Construct the scratchpad that lets the agent continue its thought process.\"\"\"\n    thoughts = \"\"\n    for action, observation in intermediate_steps:\n        thoughts += action.log\n        thoughts += f\"\\n{observation_prefix}{observation}\\n{llm_prefix}\"\n    return thoughts", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/format_scratchpad/log.html"}
{"id": "7c3fc31a2cbf-0", "text": "Source code for langchain.agents.format_scratchpad.openai_tools\nimport json\nfrom typing import List, Sequence, Tuple\nfrom langchain.agents.output_parsers.openai_tools import OpenAIToolAgentAction\nfrom langchain.schema.agent import AgentAction\nfrom langchain.schema.messages import (\n    AIMessage,\n    BaseMessage,\n    ToolMessage,\n)\ndef _create_tool_message(\n    agent_action: OpenAIToolAgentAction, observation: str\n) -> ToolMessage:\n    \"\"\"Convert agent action and observation into a function message.\n    Args:\n        agent_action: the tool invocation request from the agent\n        observation: the result of the tool invocation\n    Returns:\n        FunctionMessage that corresponds to the original tool invocation\n    \"\"\"\n    if not isinstance(observation, str):\n        try:\n            content = json.dumps(observation, ensure_ascii=False)\n        except Exception:\n            content = str(observation)\n    else:\n        content = observation\n    return ToolMessage(\n        tool_call_id=agent_action.tool_call_id,\n        content=content,\n    )\n[docs]def format_to_openai_tool_messages(\n    intermediate_steps: Sequence[Tuple[AgentAction, str]],\n) -> List[BaseMessage]:\n    \"\"\"Convert (AgentAction, tool output) tuples into FunctionMessages.\n    Args:\n        intermediate_steps: Steps the LLM has taken to date, along with observations\n    Returns:\n        list of messages to send to the LLM for the next prediction\n    \"\"\"\n    messages = []\n    for agent_action, observation in intermediate_steps:\n        if isinstance(agent_action, OpenAIToolAgentAction):\n            new_messages = list(agent_action.message_log) + [\n                _create_tool_message(agent_action, observation)\n            ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/format_scratchpad/openai_tools.html"}
{"id": "7c3fc31a2cbf-1", "text": "_create_tool_message(agent_action, observation)\n            ]\n            messages.extend([new for new in new_messages if new not in messages])\n        else:\n            messages.append(AIMessage(content=agent_action.log))\n    return messages", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/format_scratchpad/openai_tools.html"}
{"id": "5bd7fa33ef89-0", "text": "Source code for langchain.agents.format_scratchpad.xml\nfrom typing import List, Tuple\nfrom langchain.schema.agent import AgentAction\n[docs]def format_xml(\n    intermediate_steps: List[Tuple[AgentAction, str]],\n) -> str:\n    \"\"\"Format the intermediate steps as XML.\n    Args:\n        intermediate_steps: The intermediate steps.\n    Returns:\n        The intermediate steps as XML.\n    \"\"\"\n    log = \"\"\n    for action, observation in intermediate_steps:\n        log += (\n            f\"<tool>{action.tool}</tool><tool_input>{action.tool_input}\"\n            f\"</tool_input><observation>{observation}</observation>\"\n        )\n    return log", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/format_scratchpad/xml.html"}
{"id": "53ccb0231581-0", "text": "Source code for langchain.agents.format_scratchpad.log_to_messages\nfrom typing import List, Tuple\nfrom langchain.schema.agent import AgentAction\nfrom langchain.schema.messages import AIMessage, BaseMessage, HumanMessage\n[docs]def format_log_to_messages(\n    intermediate_steps: List[Tuple[AgentAction, str]],\n    template_tool_response: str = \"{observation}\",\n) -> List[BaseMessage]:\n    \"\"\"Construct the scratchpad that lets the agent continue its thought process.\"\"\"\n    thoughts: List[BaseMessage] = []\n    for action, observation in intermediate_steps:\n        thoughts.append(AIMessage(content=action.log))\n        human_message = HumanMessage(\n            content=template_tool_response.format(observation=observation)\n        )\n        thoughts.append(human_message)\n    return thoughts", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/format_scratchpad/log_to_messages.html"}
{"id": "8295adf2a12d-0", "text": "Source code for langchain.agents.format_scratchpad.openai_functions\nimport json\nfrom typing import List, Sequence, Tuple\nfrom langchain.schema.agent import AgentAction, AgentActionMessageLog\nfrom langchain.schema.messages import AIMessage, BaseMessage, FunctionMessage\ndef _convert_agent_action_to_messages(\n    agent_action: AgentAction, observation: str\n) -> List[BaseMessage]:\n    \"\"\"Convert an agent action to a message.\n    This code is used to reconstruct the original AI message from the agent action.\n    Args:\n        agent_action: Agent action to convert.\n    Returns:\n        AIMessage that corresponds to the original tool invocation.\n    \"\"\"\n    if isinstance(agent_action, AgentActionMessageLog):\n        return list(agent_action.message_log) + [\n            _create_function_message(agent_action, observation)\n        ]\n    else:\n        return [AIMessage(content=agent_action.log)]\ndef _create_function_message(\n    agent_action: AgentAction, observation: str\n) -> FunctionMessage:\n    \"\"\"Convert agent action and observation into a function message.\n    Args:\n        agent_action: the tool invocation request from the agent\n        observation: the result of the tool invocation\n    Returns:\n        FunctionMessage that corresponds to the original tool invocation\n    \"\"\"\n    if not isinstance(observation, str):\n        try:\n            content = json.dumps(observation, ensure_ascii=False)\n        except Exception:\n            content = str(observation)\n    else:\n        content = observation\n    return FunctionMessage(\n        name=agent_action.tool,\n        content=content,\n    )\n[docs]def format_to_openai_function_messages(\n    intermediate_steps: Sequence[Tuple[AgentAction, str]],\n) -> List[BaseMessage]:\n    \"\"\"Convert (AgentAction, tool output) tuples into FunctionMessages.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/format_scratchpad/openai_functions.html"}
{"id": "8295adf2a12d-1", "text": "\"\"\"Convert (AgentAction, tool output) tuples into FunctionMessages.\n    Args:\n        intermediate_steps: Steps the LLM has taken to date, along with observations\n    Returns:\n        list of messages to send to the LLM for the next prediction\n    \"\"\"\n    messages = []\n    for agent_action, observation in intermediate_steps:\n        messages.extend(_convert_agent_action_to_messages(agent_action, observation))\n    return messages\n# Backwards compatibility\nformat_to_openai_functions = format_to_openai_function_messages", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/agents/format_scratchpad/openai_functions.html"}
{"id": "9924af10309d-0", "text": "Source code for langchain.callbacks.streaming_aiter\nfrom __future__ import annotations\nimport asyncio\nfrom typing import Any, AsyncIterator, Dict, List, Literal, Union, cast\nfrom langchain.callbacks.base import AsyncCallbackHandler\nfrom langchain.schema.output import LLMResult\n# TODO If used by two LLM runs in parallel this won't work as expected\n[docs]class AsyncIteratorCallbackHandler(AsyncCallbackHandler):\n    \"\"\"Callback handler that returns an async iterator.\"\"\"\n    queue: asyncio.Queue[str]\n    done: asyncio.Event\n    @property\n    def always_verbose(self) -> bool:\n        return True\n[docs]    def __init__(self) -> None:\n        self.queue = asyncio.Queue()\n        self.done = asyncio.Event()\n[docs]    async def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        # If two calls are made in a row, this resets the state\n        self.done.clear()\n[docs]    async def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        if token is not None and token != \"\":\n            self.queue.put_nowait(token)\n[docs]    async def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        self.done.set()\n[docs]    async def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        self.done.set()\n    # TODO implement the other methods\n[docs]    async def aiter(self) -> AsyncIterator[str]:\n        while not self.queue.empty() or not self.done.is_set():\n            # Wait for the next token in the queue,\n            # but stop waiting if the done event is set", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter.html"}
{"id": "9924af10309d-1", "text": "# but stop waiting if the done event is set\n            done, other = await asyncio.wait(\n                [\n                    # NOTE: If you add other tasks here, update the code below,\n                    # which assumes each set has exactly one task each\n                    asyncio.ensure_future(self.queue.get()),\n                    asyncio.ensure_future(self.done.wait()),\n                ],\n                return_when=asyncio.FIRST_COMPLETED,\n            )\n            # Cancel the other task\n            if other:\n                other.pop().cancel()\n            # Extract the value of the first completed task\n            token_or_done = cast(Union[str, Literal[True]], done.pop().result())\n            # If the extracted value is the boolean True, the done event was set\n            if token_or_done is True:\n                break\n            # Otherwise, the extracted value is a token, which we yield\n            yield token_or_done", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter.html"}
{"id": "6e56302c2344-0", "text": "Source code for langchain.callbacks.manager\nfrom __future__ import annotations\nimport logging\nfrom contextlib import contextmanager\nfrom contextvars import ContextVar\nfrom typing import (\n    Generator,\n    Optional,\n)\nfrom langchain.callbacks.openai_info import OpenAICallbackHandler\nfrom langchain.callbacks.tracers.wandb import WandbTracer\nfrom langchain.schema.callbacks.manager import (\n    AsyncCallbackManager,\n    AsyncCallbackManagerForChainGroup,\n    AsyncCallbackManagerForChainRun,\n    AsyncCallbackManagerForLLMRun,\n    AsyncCallbackManagerForRetrieverRun,\n    AsyncCallbackManagerForToolRun,\n    AsyncParentRunManager,\n    AsyncRunManager,\n    BaseRunManager,\n    CallbackManager,\n    CallbackManagerForChainGroup,\n    CallbackManagerForChainRun,\n    CallbackManagerForLLMRun,\n    CallbackManagerForRetrieverRun,\n    CallbackManagerForToolRun,\n    Callbacks,\n    ParentRunManager,\n    RunManager,\n    ahandle_event,\n    atrace_as_chain_group,\n    collect_runs,\n    env_var_is_set,\n    handle_event,\n    register_configure_hook,\n    trace_as_chain_group,\n    tracing_enabled,\n    tracing_v2_enabled,\n)\nlogger = logging.getLogger(__name__)\nopenai_callback_var: ContextVar[Optional[OpenAICallbackHandler]] = ContextVar(\n    \"openai_callback\", default=None\n)\nwandb_tracing_callback_var: ContextVar[Optional[WandbTracer]] = ContextVar(  # noqa: E501\n    \"tracing_wandb_callback\", default=None\n)\nregister_configure_hook(openai_callback_var, True)\nregister_configure_hook(\n    wandb_tracing_callback_var, True, WandbTracer, \"LANGCHAIN_WANDB_TRACING\"\n)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html"}
{"id": "6e56302c2344-1", "text": ")\n[docs]@contextmanager\ndef get_openai_callback() -> Generator[OpenAICallbackHandler, None, None]:\n    \"\"\"Get the OpenAI callback handler in a context manager.\n    which conveniently exposes token and cost information.\n    Returns:\n        OpenAICallbackHandler: The OpenAI callback handler.\n    Example:\n        >>> with get_openai_callback() as cb:\n        ...     # Use the OpenAI callback handler\n    \"\"\"\n    cb = OpenAICallbackHandler()\n    openai_callback_var.set(cb)\n    yield cb\n    openai_callback_var.set(None)\n[docs]@contextmanager\ndef wandb_tracing_enabled(\n    session_name: str = \"default\",\n) -> Generator[None, None, None]:\n    \"\"\"Get the WandbTracer in a context manager.\n    Args:\n        session_name (str, optional): The name of the session.\n            Defaults to \"default\".\n    Returns:\n        None\n    Example:\n        >>> with wandb_tracing_enabled() as session:\n        ...     # Use the WandbTracer session\n    \"\"\"\n    cb = WandbTracer()\n    wandb_tracing_callback_var.set(cb)\n    yield None\n    wandb_tracing_callback_var.set(None)\n__all__ = [\n    \"BaseRunManager\",\n    \"RunManager\",\n    \"ParentRunManager\",\n    \"AsyncRunManager\",\n    \"AsyncParentRunManager\",\n    \"CallbackManagerForLLMRun\",\n    \"AsyncCallbackManagerForLLMRun\",\n    \"CallbackManagerForChainRun\",\n    \"AsyncCallbackManagerForChainRun\",\n    \"CallbackManagerForToolRun\",\n    \"AsyncCallbackManagerForToolRun\",\n    \"CallbackManagerForRetrieverRun\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html"}
{"id": "6e56302c2344-2", "text": "\"CallbackManagerForRetrieverRun\",\n    \"AsyncCallbackManagerForRetrieverRun\",\n    \"CallbackManager\",\n    \"CallbackManagerForChainGroup\",\n    \"AsyncCallbackManager\",\n    \"AsyncCallbackManagerForChainGroup\",\n    \"tracing_enabled\",\n    \"tracing_v2_enabled\",\n    \"collect_runs\",\n    \"atrace_as_chain_group\",\n    \"trace_as_chain_group\",\n    \"handle_event\",\n    \"ahandle_event\",\n    \"env_var_is_set\",\n    \"Callbacks\",\n]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html"}
{"id": "2377302227fb-0", "text": "Source code for langchain.callbacks.streaming_stdout_final_only\n\"\"\"Callback Handler streams to stdout on new llm token.\"\"\"\nimport sys\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\nDEFAULT_ANSWER_PREFIX_TOKENS = [\"Final\", \"Answer\", \":\"]\n[docs]class FinalStreamingStdOutCallbackHandler(StreamingStdOutCallbackHandler):\n    \"\"\"Callback handler for streaming in agents.\n    Only works with agents using LLMs that support streaming.\n    Only the final output of the agent will be streamed.\n    \"\"\"\n[docs]    def append_to_last_tokens(self, token: str) -> None:\n        self.last_tokens.append(token)\n        self.last_tokens_stripped.append(token.strip())\n        if len(self.last_tokens) > len(self.answer_prefix_tokens):\n            self.last_tokens.pop(0)\n            self.last_tokens_stripped.pop(0)\n[docs]    def check_if_answer_reached(self) -> bool:\n        if self.strip_tokens:\n            return self.last_tokens_stripped == self.answer_prefix_tokens_stripped\n        else:\n            return self.last_tokens == self.answer_prefix_tokens\n[docs]    def __init__(\n        self,\n        *,\n        answer_prefix_tokens: Optional[List[str]] = None,\n        strip_tokens: bool = True,\n        stream_prefix: bool = False,\n    ) -> None:\n        \"\"\"Instantiate FinalStreamingStdOutCallbackHandler.\n        Args:\n            answer_prefix_tokens: Token sequence that prefixes the answer.\n                Default is [\"Final\", \"Answer\", \":\"]\n            strip_tokens: Ignore white spaces and new lines when comparing\n                answer_prefix_tokens to last tokens? (to determine if answer has been\n                reached)\n            stream_prefix: Should answer prefix itself also be streamed?\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout_final_only.html"}
{"id": "2377302227fb-1", "text": "reached)\n            stream_prefix: Should answer prefix itself also be streamed?\n        \"\"\"\n        super().__init__()\n        if answer_prefix_tokens is None:\n            self.answer_prefix_tokens = DEFAULT_ANSWER_PREFIX_TOKENS\n        else:\n            self.answer_prefix_tokens = answer_prefix_tokens\n        if strip_tokens:\n            self.answer_prefix_tokens_stripped = [\n                token.strip() for token in self.answer_prefix_tokens\n            ]\n        else:\n            self.answer_prefix_tokens_stripped = self.answer_prefix_tokens\n        self.last_tokens = [\"\"] * len(self.answer_prefix_tokens)\n        self.last_tokens_stripped = [\"\"] * len(self.answer_prefix_tokens)\n        self.strip_tokens = strip_tokens\n        self.stream_prefix = stream_prefix\n        self.answer_reached = False\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when LLM starts running.\"\"\"\n        self.answer_reached = False\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Run on new LLM token. Only available when streaming is enabled.\"\"\"\n        # Remember the last n tokens, where n = len(answer_prefix_tokens)\n        self.append_to_last_tokens(token)\n        # Check if the last n tokens match the answer_prefix_tokens list ...\n        if self.check_if_answer_reached():\n            self.answer_reached = True\n            if self.stream_prefix:\n                for t in self.last_tokens:\n                    sys.stdout.write(t)\n                sys.stdout.flush()\n            return\n        # ... if yes, then print tokens from now on\n        if self.answer_reached:\n            sys.stdout.write(token)\n            sys.stdout.flush()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout_final_only.html"}
{"id": "93aee58072b0-0", "text": "Source code for langchain.callbacks.openai_info\n\"\"\"Callback Handler that prints to std out.\"\"\"\nfrom typing import Any, Dict, List\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema import LLMResult\nMODEL_COST_PER_1K_TOKENS = {\n    # GPT-4 input\n    \"gpt-4\": 0.03,\n    \"gpt-4-0314\": 0.03,\n    \"gpt-4-0613\": 0.03,\n    \"gpt-4-32k\": 0.06,\n    \"gpt-4-32k-0314\": 0.06,\n    \"gpt-4-32k-0613\": 0.06,\n    \"gpt-4-vision-preview\": 0.01,\n    \"gpt-4-1106-preview\": 0.01,\n    # GPT-4 output\n    \"gpt-4-completion\": 0.06,\n    \"gpt-4-0314-completion\": 0.06,\n    \"gpt-4-0613-completion\": 0.06,\n    \"gpt-4-32k-completion\": 0.12,\n    \"gpt-4-32k-0314-completion\": 0.12,\n    \"gpt-4-32k-0613-completion\": 0.12,\n    \"gpt-4-vision-preview-completion\": 0.03,\n    \"gpt-4-1106-preview-completion\": 0.03,\n    # GPT-3.5 input\n    \"gpt-3.5-turbo\": 0.0015,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html"}
{"id": "93aee58072b0-1", "text": "\"gpt-3.5-turbo\": 0.0015,\n    \"gpt-3.5-turbo-0301\": 0.0015,\n    \"gpt-3.5-turbo-0613\": 0.0015,\n    \"gpt-3.5-turbo-1106\": 0.001,\n    \"gpt-3.5-turbo-instruct\": 0.0015,\n    \"gpt-3.5-turbo-16k\": 0.003,\n    \"gpt-3.5-turbo-16k-0613\": 0.003,\n    # GPT-3.5 output\n    \"gpt-3.5-turbo-completion\": 0.002,\n    \"gpt-3.5-turbo-0301-completion\": 0.002,\n    \"gpt-3.5-turbo-0613-completion\": 0.002,\n    \"gpt-3.5-turbo-1106-completion\": 0.002,\n    \"gpt-3.5-turbo-instruct-completion\": 0.002,\n    \"gpt-3.5-turbo-16k-completion\": 0.004,\n    \"gpt-3.5-turbo-16k-0613-completion\": 0.004,\n    # Azure GPT-35 input\n    \"gpt-35-turbo\": 0.0015,  # Azure OpenAI version of ChatGPT\n    \"gpt-35-turbo-0301\": 0.0015,  # Azure OpenAI version of ChatGPT", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html"}
{"id": "93aee58072b0-2", "text": "\"gpt-35-turbo-0613\": 0.0015,\n    \"gpt-35-turbo-instruct\": 0.0015,\n    \"gpt-35-turbo-16k\": 0.003,\n    \"gpt-35-turbo-16k-0613\": 0.003,\n    # Azure GPT-35 output\n    \"gpt-35-turbo-completion\": 0.002,  # Azure OpenAI version of ChatGPT\n    \"gpt-35-turbo-0301-completion\": 0.002,  # Azure OpenAI version of ChatGPT\n    \"gpt-35-turbo-0613-completion\": 0.002,\n    \"gpt-35-turbo-instruct-completion\": 0.002,\n    \"gpt-35-turbo-16k-completion\": 0.004,\n    \"gpt-35-turbo-16k-0613-completion\": 0.004,\n    # Others\n    \"text-ada-001\": 0.0004,\n    \"ada\": 0.0004,\n    \"text-babbage-001\": 0.0005,\n    \"babbage\": 0.0005,\n    \"text-curie-001\": 0.002,\n    \"curie\": 0.002,\n    \"text-davinci-003\": 0.02,\n    \"text-davinci-002\": 0.02,\n    \"code-davinci-002\": 0.02,\n    # Fine Tuned input\n    \"babbage-002-finetuned\": 0.0016,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html"}
{"id": "93aee58072b0-3", "text": "\"babbage-002-finetuned\": 0.0016,\n    \"davinci-002-finetuned\": 0.012,\n    \"gpt-3.5-turbo-0613-finetuned\": 0.012,\n    # Fine Tuned output\n    \"babbage-002-finetuned-completion\": 0.0016,\n    \"davinci-002-finetuned-completion\": 0.012,\n    \"gpt-3.5-turbo-0613-finetuned-completion\": 0.016,\n    # Azure Fine Tuned input\n    \"babbage-002-azure-finetuned\": 0.0004,\n    \"davinci-002-azure-finetuned\": 0.002,\n    \"gpt-35-turbo-0613-azure-finetuned\": 0.0015,\n    # Azure Fine Tuned output\n    \"babbage-002-azure-finetuned-completion\": 0.0004,\n    \"davinci-002-azure-finetuned-completion\": 0.002,\n    \"gpt-35-turbo-0613-azure-finetuned-completion\": 0.002,\n    # Legacy fine-tuned models\n    \"ada-finetuned-legacy\": 0.0016,\n    \"babbage-finetuned-legacy\": 0.0024,\n    \"curie-finetuned-legacy\": 0.012,\n    \"davinci-finetuned-legacy\": 0.12,\n}\n[docs]def standardize_model_name(\n    model_name: str,\n    is_completion: bool = False,\n) -> str:\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html"}
{"id": "93aee58072b0-4", "text": "is_completion: bool = False,\n) -> str:\n    \"\"\"\n    Standardize the model name to a format that can be used in the OpenAI API.\n    Args:\n        model_name: Model name to standardize.\n        is_completion: Whether the model is used for completion or not.\n            Defaults to False.\n    Returns:\n        Standardized model name.\n    \"\"\"\n    model_name = model_name.lower()\n    if \".ft-\" in model_name:\n        model_name = model_name.split(\".ft-\")[0] + \"-azure-finetuned\"\n    if \":ft-\" in model_name:\n        model_name = model_name.split(\":\")[0] + \"-finetuned-legacy\"\n    if \"ft:\" in model_name:\n        model_name = model_name.split(\":\")[1] + \"-finetuned\"\n    if is_completion and (\n        model_name.startswith(\"gpt-4\")\n        or model_name.startswith(\"gpt-3.5\")\n        or model_name.startswith(\"gpt-35\")\n        or (\"finetuned\" in model_name and \"legacy\" not in model_name)\n    ):\n        return model_name + \"-completion\"\n    else:\n        return model_name\n[docs]def get_openai_token_cost_for_model(\n    model_name: str, num_tokens: int, is_completion: bool = False\n) -> float:\n    \"\"\"\n    Get the cost in USD for a given model and number of tokens.\n    Args:\n        model_name: Name of the model\n        num_tokens: Number of tokens.\n        is_completion: Whether the model is used for completion or not.\n            Defaults to False.\n    Returns:\n        Cost in USD.\n    \"\"\"\n    model_name = standardize_model_name(model_name, is_completion=is_completion)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html"}
{"id": "93aee58072b0-5", "text": "\"\"\"\n    model_name = standardize_model_name(model_name, is_completion=is_completion)\n    if model_name not in MODEL_COST_PER_1K_TOKENS:\n        raise ValueError(\n            f\"Unknown model: {model_name}. Please provide a valid OpenAI model name.\"\n            \"Known models are: \" + \", \".join(MODEL_COST_PER_1K_TOKENS.keys())\n        )\n    return MODEL_COST_PER_1K_TOKENS[model_name] * (num_tokens / 1000)\n[docs]class OpenAICallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback Handler that tracks OpenAI info.\"\"\"\n    total_tokens: int = 0\n    prompt_tokens: int = 0\n    completion_tokens: int = 0\n    successful_requests: int = 0\n    total_cost: float = 0.0\n    def __repr__(self) -> str:\n        return (\n            f\"Tokens Used: {self.total_tokens}\\n\"\n            f\"\\tPrompt Tokens: {self.prompt_tokens}\\n\"\n            f\"\\tCompletion Tokens: {self.completion_tokens}\\n\"\n            f\"Successful Requests: {self.successful_requests}\\n\"\n            f\"Total Cost (USD): ${self.total_cost}\"\n        )\n    @property\n    def always_verbose(self) -> bool:\n        \"\"\"Whether to call verbose callbacks even if verbose is False.\"\"\"\n        return True\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        \"\"\"Print out the prompts.\"\"\"\n        pass\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Print out the token.\"\"\"\n        pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html"}
{"id": "93aee58072b0-6", "text": "\"\"\"Print out the token.\"\"\"\n        pass\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Collect token usage.\"\"\"\n        if response.llm_output is None:\n            return None\n        self.successful_requests += 1\n        if \"token_usage\" not in response.llm_output:\n            return None\n        token_usage = response.llm_output[\"token_usage\"]\n        completion_tokens = token_usage.get(\"completion_tokens\", 0)\n        prompt_tokens = token_usage.get(\"prompt_tokens\", 0)\n        model_name = standardize_model_name(response.llm_output.get(\"model_name\", \"\"))\n        if model_name in MODEL_COST_PER_1K_TOKENS:\n            completion_cost = get_openai_token_cost_for_model(\n                model_name, completion_tokens, is_completion=True\n            )\n            prompt_cost = get_openai_token_cost_for_model(model_name, prompt_tokens)\n            self.total_cost += prompt_cost + completion_cost\n        self.total_tokens += token_usage.get(\"total_tokens\", 0)\n        self.prompt_tokens += prompt_tokens\n        self.completion_tokens += completion_tokens\n    def __copy__(self) -> \"OpenAICallbackHandler\":\n        \"\"\"Return a copy of the callback handler.\"\"\"\n        return self\n    def __deepcopy__(self, memo: Any) -> \"OpenAICallbackHandler\":\n        \"\"\"Return a deep copy of the callback handler.\"\"\"\n        return self", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html"}
{"id": "169f5caba2fc-0", "text": "Source code for langchain.callbacks.confident_callback\n# flake8: noqa\nimport os\nimport warnings\nfrom typing import Any, Dict, List, Optional, Union\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\n[docs]class DeepEvalCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback Handler that logs into deepeval.\n    Args:\n        implementation_name: name of the `implementation` in deepeval\n        metrics: A list of metrics\n    Raises:\n        ImportError: if the `deepeval` package is not installed.\n    Examples:\n        >>> from langchain.llms import OpenAI\n        >>> from langchain.callbacks import DeepEvalCallbackHandler\n        >>> from deepeval.metrics import AnswerRelevancy\n        >>> metric = AnswerRelevancy(minimum_score=0.3)\n        >>> deepeval_callback = DeepEvalCallbackHandler(\n        ...     implementation_name=\"exampleImplementation\",\n        ...     metrics=[metric],\n        ... )\n        >>> llm = OpenAI(\n        ...     temperature=0,\n        ...     callbacks=[deepeval_callback],\n        ...     verbose=True,\n        ...     openai_api_key=\"API_KEY_HERE\",\n        ... )\n        >>> llm.generate([\n        ...     \"What is the best evaluation tool out there? (no bias at all)\",\n        ... ])\n        \"Deepeval, no doubt about it.\"\n    \"\"\"\n    REPO_URL: str = \"https://github.com/confident-ai/deepeval\"\n    ISSUES_URL: str = f\"{REPO_URL}/issues\"\n    BLOG_URL: str = \"https://docs.confident-ai.com\"  # noqa: E501\n[docs]    def __init__(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/confident_callback.html"}
{"id": "169f5caba2fc-1", "text": "[docs]    def __init__(\n        self,\n        metrics: List[Any],\n        implementation_name: Optional[str] = None,\n    ) -> None:\n        \"\"\"Initializes the `deepevalCallbackHandler`.\n        Args:\n            implementation_name: Name of the implementation you want.\n            metrics: What metrics do you want to track?\n        Raises:\n            ImportError: if the `deepeval` package is not installed.\n            ConnectionError: if the connection to deepeval fails.\n        \"\"\"\n        super().__init__()\n        # Import deepeval (not via `import_deepeval` to keep hints in IDEs)\n        try:\n            import deepeval  # ignore: F401,I001\n        except ImportError:\n            raise ImportError(\n                \"\"\"To use the deepeval callback manager you need to have the \n                `deepeval` Python package installed. Please install it with \n                `pip install deepeval`\"\"\"\n            )\n        if os.path.exists(\".deepeval\"):\n            warnings.warn(\n                \"\"\"You are currently not logging anything to the dashboard, we \n                recommend using `deepeval login`.\"\"\"\n            )\n        # Set the deepeval variables\n        self.implementation_name = implementation_name\n        self.metrics = metrics\n        warnings.warn(\n            (\n                \"The `DeepEvalCallbackHandler` is currently in beta and is subject to\"\n                \" change based on updates to `langchain`. Please report any issues to\"\n                f\" {self.ISSUES_URL} as an `integration` issue.\"\n            ),\n        )\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/confident_callback.html"}
{"id": "169f5caba2fc-2", "text": ") -> None:\n        \"\"\"Store the prompts\"\"\"\n        self.prompts = prompts\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Do nothing when a new token is generated.\"\"\"\n        pass\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Log records to deepeval when an LLM ends.\"\"\"\n        from deepeval.metrics.answer_relevancy import AnswerRelevancy\n        from deepeval.metrics.bias_classifier import UnBiasedMetric\n        from deepeval.metrics.metric import Metric\n        from deepeval.metrics.toxic_classifier import NonToxicMetric\n        for metric in self.metrics:\n            for i, generation in enumerate(response.generations):\n                # Here, we only measure the first generation's output\n                output = generation[0].text\n                query = self.prompts[i]\n                if isinstance(metric, AnswerRelevancy):\n                    result = metric.measure(\n                        output=output,\n                        query=query,\n                    )\n                    print(f\"Answer Relevancy: {result}\")\n                elif isinstance(metric, UnBiasedMetric):\n                    score = metric.measure(output)\n                    print(f\"Bias Score: {score}\")\n                elif isinstance(metric, NonToxicMetric):\n                    score = metric.measure(output)\n                    print(f\"Toxic Score: {score}\")\n                else:\n                    raise ValueError(\n                        f\"\"\"Metric {metric.__name__} is not supported by deepeval \n                        callbacks.\"\"\"\n                    )\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing when LLM outputs an error.\"\"\"\n        pass\n[docs]    def on_chain_start(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/confident_callback.html"}
{"id": "169f5caba2fc-3", "text": "pass\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Do nothing when chain starts\"\"\"\n        pass\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"Do nothing when chain ends.\"\"\"\n        pass\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing when LLM chain outputs an error.\"\"\"\n        pass\n[docs]    def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Do nothing when tool starts.\"\"\"\n        pass\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Do nothing when agent takes a specific action.\"\"\"\n        pass\n[docs]    def on_tool_end(\n        self,\n        output: str,\n        observation_prefix: Optional[str] = None,\n        llm_prefix: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Do nothing when tool ends.\"\"\"\n        pass\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing when tool outputs an error.\"\"\"\n        pass\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        \"\"\"Do nothing\"\"\"\n        pass\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        \"\"\"Do nothing\"\"\"\n        pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/confident_callback.html"}
{"id": "218e22867f05-0", "text": "Source code for langchain.callbacks.llmonitor_callback\nimport importlib.metadata\nimport logging\nimport os\nimport traceback\nimport warnings\nfrom contextvars import ContextVar\nfrom typing import Any, Dict, List, Union, cast\nfrom uuid import UUID\nimport requests\nfrom packaging.version import parse\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema.agent import AgentAction, AgentFinish\nfrom langchain.schema.messages import BaseMessage\nfrom langchain.schema.output import LLMResult\nlogger = logging.getLogger(__name__)\nDEFAULT_API_URL = \"https://app.llmonitor.com\"\nuser_ctx = ContextVar[Union[str, None]](\"user_ctx\", default=None)\nuser_props_ctx = ContextVar[Union[str, None]](\"user_props_ctx\", default=None)\nPARAMS_TO_CAPTURE = [\n    \"temperature\",\n    \"top_p\",\n    \"top_k\",\n    \"stop\",\n    \"presence_penalty\",\n    \"frequence_penalty\",\n    \"seed\",\n    \"function_call\",\n    \"functions\",\n    \"tools\",\n    \"tool_choice\",\n    \"response_format\",\n    \"max_tokens\",\n    \"logit_bias\",\n]\n[docs]class UserContextManager:\n    \"\"\"Context manager for LLMonitor user context.\"\"\"\n[docs]    def __init__(self, user_id: str, user_props: Any = None) -> None:\n        user_ctx.set(user_id)\n        user_props_ctx.set(user_props)\n    def __enter__(self) -> Any:\n        pass\n    def __exit__(self, exc_type: Any, exc_value: Any, exc_tb: Any) -> Any:\n        user_ctx.set(None)\n        user_props_ctx.set(None)\n[docs]def identify(user_id: str, user_props: Any = None) -> UserContextManager:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "218e22867f05-1", "text": "\"\"\"Builds an LLMonitor UserContextManager\n    Parameters:\n        - `user_id`: The user id.\n        - `user_props`: The user properties.\n    Returns:\n        A context manager that sets the user context.\n    \"\"\"\n    return UserContextManager(user_id, user_props)\ndef _serialize(obj: Any) -> Union[Dict[str, Any], List[Any], Any]:\n    if hasattr(obj, \"to_json\"):\n        return obj.to_json()\n    if isinstance(obj, dict):\n        return {key: _serialize(value) for key, value in obj.items()}\n    if isinstance(obj, list):\n        return [_serialize(element) for element in obj]\n    return obj\ndef _parse_input(raw_input: Any) -> Any:\n    if not raw_input:\n        return None\n    # if it's an array of 1, just parse the first element\n    if isinstance(raw_input, list) and len(raw_input) == 1:\n        return _parse_input(raw_input[0])\n    if not isinstance(raw_input, dict):\n        return _serialize(raw_input)\n    input_value = raw_input.get(\"input\")\n    inputs_value = raw_input.get(\"inputs\")\n    question_value = raw_input.get(\"question\")\n    query_value = raw_input.get(\"query\")\n    if input_value:\n        return input_value\n    if inputs_value:\n        return inputs_value\n    if question_value:\n        return question_value\n    if query_value:\n        return query_value\n    return _serialize(raw_input)\ndef _parse_output(raw_output: dict) -> Any:\n    if not raw_output:\n        return None\n    if not isinstance(raw_output, dict):\n        return _serialize(raw_output)\n    text_value = raw_output.get(\"text\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "218e22867f05-2", "text": "return _serialize(raw_output)\n    text_value = raw_output.get(\"text\")\n    output_value = raw_output.get(\"output\")\n    output_text_value = raw_output.get(\"output_text\")\n    answer_value = raw_output.get(\"answer\")\n    result_value = raw_output.get(\"result\")\n    if text_value:\n        return text_value\n    if answer_value:\n        return answer_value\n    if output_value:\n        return output_value\n    if output_text_value:\n        return output_text_value\n    if result_value:\n        return result_value\n    return _serialize(raw_output)\ndef _parse_lc_role(\n    role: str,\n) -> str:\n    if role == \"human\":\n        return \"user\"\n    else:\n        return role\ndef _get_user_id(metadata: Any) -> Any:\n    if user_ctx.get() is not None:\n        return user_ctx.get()\n    metadata = metadata or {}\n    user_id = metadata.get(\"user_id\")\n    if user_id is None:\n        user_id = metadata.get(\"userId\")  # legacy, to delete in the future\n    return user_id\ndef _get_user_props(metadata: Any) -> Any:\n    if user_props_ctx.get() is not None:\n        return user_props_ctx.get()\n    metadata = metadata or {}\n    return metadata.get(\"user_props\", None)\ndef _parse_lc_message(message: BaseMessage) -> Dict[str, Any]:\n    keys = [\"function_call\", \"tool_calls\", \"tool_call_id\", \"name\"]\n    parsed = {\"text\": message.content, \"role\": _parse_lc_role(message.type)}\n    parsed.update(\n        {\n            key: cast(Any, message.additional_kwargs.get(key))\n            for key in keys\n            if message.additional_kwargs.get(key) is not None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "218e22867f05-3", "text": "for key in keys\n            if message.additional_kwargs.get(key) is not None\n        }\n    )\n    return parsed\ndef _parse_lc_messages(messages: Union[List[BaseMessage], Any]) -> List[Dict[str, Any]]:\n    return [_parse_lc_message(message) for message in messages]\n[docs]class LLMonitorCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback Handler for LLMonitor`.\n    #### Parameters:\n        - `app_id`: The app id of the app you want to report to. Defaults to\n        `None`, which means that `LLMONITOR_APP_ID` will be used.\n        - `api_url`: The url of the LLMonitor API. Defaults to `None`,\n        which means that either `LLMONITOR_API_URL` environment variable\n        or `https://app.llmonitor.com` will be used.\n    #### Raises:\n        - `ValueError`: if `app_id` is not provided either as an\n        argument or as an environment variable.\n        - `ConnectionError`: if the connection to the API fails.\n    #### Example:\n    ```python\n    from langchain.llms import OpenAI\n    from langchain.callbacks import LLMonitorCallbackHandler\n    llmonitor_callback = LLMonitorCallbackHandler()\n    llm = OpenAI(callbacks=[llmonitor_callback],\n                 metadata={\"userId\": \"user-123\"})\n    llm.predict(\"Hello, how are you?\")\n    ```\n    \"\"\"\n    __api_url: str\n    __app_id: str\n    __verbose: bool\n    __llmonitor_version: str\n    __has_valid_config: bool\n[docs]    def __init__(\n        self,\n        app_id: Union[str, None] = None,\n        api_url: Union[str, None] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "218e22867f05-4", "text": "api_url: Union[str, None] = None,\n        verbose: bool = False,\n    ) -> None:\n        super().__init__()\n        self.__has_valid_config = True\n        try:\n            import llmonitor\n            self.__llmonitor_version = importlib.metadata.version(\"llmonitor\")\n            self.__track_event = llmonitor.track_event\n        except ImportError:\n            logger.warning(\n                \"\"\"[LLMonitor] To use the LLMonitor callback handler you need to \n                have the `llmonitor` Python package installed. Please install it \n                with `pip install llmonitor`\"\"\"\n            )\n            self.__has_valid_config = False\n            return\n        if parse(self.__llmonitor_version) < parse(\"0.0.32\"):\n            logger.warning(\n                f\"\"\"[LLMonitor] The installed `llmonitor` version is \n                {self.__llmonitor_version} \n                but `LLMonitorCallbackHandler` requires at least version 0.0.32 \n                upgrade `llmonitor` with `pip install --upgrade llmonitor`\"\"\"\n            )\n            self.__has_valid_config = False\n        self.__has_valid_config = True\n        self.__api_url = api_url or os.getenv(\"LLMONITOR_API_URL\") or DEFAULT_API_URL\n        self.__verbose = verbose or bool(os.getenv(\"LLMONITOR_VERBOSE\"))\n        _app_id = app_id or os.getenv(\"LLMONITOR_APP_ID\")\n        if _app_id is None:\n            logger.warning(\n                \"\"\"[LLMonitor] app_id must be provided either as an argument or \n                as an environment variable\"\"\"\n            )\n            self.__has_valid_config = False\n        else:\n            self.__app_id = _app_id\n        if self.__has_valid_config is False:\n            return None\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "218e22867f05-5", "text": "if self.__has_valid_config is False:\n            return None\n        try:\n            res = requests.get(f\"{self.__api_url}/api/app/{self.__app_id}\")\n            if not res.ok:\n                raise ConnectionError()\n        except Exception:\n            logger.warning(\n                f\"\"\"[LLMonitor] Could not connect to the LLMonitor API at \n                {self.__api_url}\"\"\"\n            )\n[docs]    def on_llm_start(\n        self,\n        serialized: Dict[str, Any],\n        prompts: List[str],\n        *,\n        run_id: UUID,\n        parent_run_id: Union[UUID, None] = None,\n        tags: Union[List[str], None] = None,\n        metadata: Union[Dict[str, Any], None] = None,\n        **kwargs: Any,\n    ) -> None:\n        if self.__has_valid_config is False:\n            return\n        try:\n            user_id = _get_user_id(metadata)\n            user_props = _get_user_props(metadata)\n            params = kwargs.get(\"invocation_params\", {})\n            params.update(\n                serialized.get(\"kwargs\", {})\n            )  # Sometimes, for example with ChatAnthropic, `invocation_params` is empty\n            name = (\n                params.get(\"model\")\n                or params.get(\"model_name\")\n                or params.get(\"model_id\")\n            )\n            if not name and \"anthropic\" in params.get(\"_type\"):\n                name = \"claude-2\"\n            extra = {\n                param: params.get(param)\n                for param in PARAMS_TO_CAPTURE\n                if params.get(param) is not None\n            }\n            input = _parse_input(prompts)\n            self.__track_event(\n                \"llm\",\n                \"start\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "218e22867f05-6", "text": "self.__track_event(\n                \"llm\",\n                \"start\",\n                user_id=user_id,\n                run_id=str(run_id),\n                parent_run_id=str(parent_run_id) if parent_run_id else None,\n                name=name,\n                input=input,\n                tags=tags,\n                extra=extra,\n                metadata=metadata,\n                user_props=user_props,\n                app_id=self.__app_id,\n            )\n        except Exception as e:\n            warnings.warn(f\"[LLMonitor] An error occurred in on_llm_start: {e}\")\n[docs]    def on_chat_model_start(\n        self,\n        serialized: Dict[str, Any],\n        messages: List[List[BaseMessage]],\n        *,\n        run_id: UUID,\n        parent_run_id: Union[UUID, None] = None,\n        tags: Union[List[str], None] = None,\n        metadata: Union[Dict[str, Any], None] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if self.__has_valid_config is False:\n            return\n        try:\n            user_id = _get_user_id(metadata)\n            user_props = _get_user_props(metadata)\n            params = kwargs.get(\"invocation_params\", {})\n            params.update(\n                serialized.get(\"kwargs\", {})\n            )  # Sometimes, for example with ChatAnthropic, `invocation_params` is empty\n            name = (\n                params.get(\"model\")\n                or params.get(\"model_name\")\n                or params.get(\"model_id\")\n            )\n            if not name and \"anthropic\" in params.get(\"_type\"):\n                name = \"claude-2\"\n            extra = {\n                param: params.get(param)\n                for param in PARAMS_TO_CAPTURE", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "218e22867f05-7", "text": "param: params.get(param)\n                for param in PARAMS_TO_CAPTURE\n                if params.get(param) is not None\n            }\n            input = _parse_lc_messages(messages[0])\n            self.__track_event(\n                \"llm\",\n                \"start\",\n                user_id=user_id,\n                run_id=str(run_id),\n                parent_run_id=str(parent_run_id) if parent_run_id else None,\n                name=name,\n                input=input,\n                tags=tags,\n                extra=extra,\n                metadata=metadata,\n                user_props=user_props,\n                app_id=self.__app_id,\n            )\n        except Exception as e:\n            logger.error(f\"[LLMonitor] An error occurred in on_chat_model_start: {e}\")\n[docs]    def on_llm_end(\n        self,\n        response: LLMResult,\n        *,\n        run_id: UUID,\n        parent_run_id: Union[UUID, None] = None,\n        **kwargs: Any,\n    ) -> None:\n        if self.__has_valid_config is False:\n            return\n        try:\n            token_usage = (response.llm_output or {}).get(\"token_usage\", {})\n            parsed_output: Any = [\n                _parse_lc_message(generation.message)\n                if hasattr(generation, \"message\")\n                else generation.text\n                for generation in response.generations[0]\n            ]\n            # if it's an array of 1, just parse the first element\n            if len(parsed_output) == 1:\n                parsed_output = parsed_output[0]\n            self.__track_event(\n                \"llm\",\n                \"end\",\n                run_id=str(run_id),\n                parent_run_id=str(parent_run_id) if parent_run_id else None,\n                output=parsed_output,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "218e22867f05-8", "text": "output=parsed_output,\n                token_usage={\n                    \"prompt\": token_usage.get(\"prompt_tokens\"),\n                    \"completion\": token_usage.get(\"completion_tokens\"),\n                },\n                app_id=self.__app_id,\n            )\n        except Exception as e:\n            logger.error(f\"[LLMonitor] An error occurred in on_llm_end: {e}\")\n[docs]    def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        *,\n        run_id: UUID,\n        parent_run_id: Union[UUID, None] = None,\n        tags: Union[List[str], None] = None,\n        metadata: Union[Dict[str, Any], None] = None,\n        **kwargs: Any,\n    ) -> None:\n        if self.__has_valid_config is False:\n            return\n        try:\n            user_id = _get_user_id(metadata)\n            user_props = _get_user_props(metadata)\n            name = serialized.get(\"name\")\n            self.__track_event(\n                \"tool\",\n                \"start\",\n                user_id=user_id,\n                run_id=str(run_id),\n                parent_run_id=str(parent_run_id) if parent_run_id else None,\n                name=name,\n                input=input_str,\n                tags=tags,\n                metadata=metadata,\n                user_props=user_props,\n                app_id=self.__app_id,\n            )\n        except Exception as e:\n            logger.error(f\"[LLMonitor] An error occurred in on_tool_start: {e}\")\n[docs]    def on_tool_end(\n        self,\n        output: str,\n        *,\n        run_id: UUID,\n        parent_run_id: Union[UUID, None] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "218e22867f05-9", "text": "parent_run_id: Union[UUID, None] = None,\n        tags: Union[List[str], None] = None,\n        **kwargs: Any,\n    ) -> None:\n        if self.__has_valid_config is False:\n            return\n        try:\n            self.__track_event(\n                \"tool\",\n                \"end\",\n                run_id=str(run_id),\n                parent_run_id=str(parent_run_id) if parent_run_id else None,\n                output=output,\n                app_id=self.__app_id,\n            )\n        except Exception as e:\n            logger.error(f\"[LLMonitor] An error occurred in on_tool_end: {e}\")\n[docs]    def on_chain_start(\n        self,\n        serialized: Dict[str, Any],\n        inputs: Dict[str, Any],\n        *,\n        run_id: UUID,\n        parent_run_id: Union[UUID, None] = None,\n        tags: Union[List[str], None] = None,\n        metadata: Union[Dict[str, Any], None] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if self.__has_valid_config is False:\n            return\n        try:\n            name = serialized.get(\"id\", [None, None, None, None])[3]\n            type = \"chain\"\n            metadata = metadata or {}\n            agentName = metadata.get(\"agent_name\")\n            if agentName is None:\n                agentName = metadata.get(\"agentName\")\n            if name == \"AgentExecutor\" or name == \"PlanAndExecute\":\n                type = \"agent\"\n            if agentName is not None:\n                type = \"agent\"\n                name = agentName\n            if parent_run_id is not None:\n                type = \"chain\"\n            user_id = _get_user_id(metadata)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "218e22867f05-10", "text": "type = \"chain\"\n            user_id = _get_user_id(metadata)\n            user_props = _get_user_props(metadata)\n            input = _parse_input(inputs)\n            self.__track_event(\n                type,\n                \"start\",\n                user_id=user_id,\n                run_id=str(run_id),\n                parent_run_id=str(parent_run_id) if parent_run_id else None,\n                name=name,\n                input=input,\n                tags=tags,\n                metadata=metadata,\n                user_props=user_props,\n                app_id=self.__app_id,\n            )\n        except Exception as e:\n            logger.error(f\"[LLMonitor] An error occurred in on_chain_start: {e}\")\n[docs]    def on_chain_end(\n        self,\n        outputs: Dict[str, Any],\n        *,\n        run_id: UUID,\n        parent_run_id: Union[UUID, None] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if self.__has_valid_config is False:\n            return\n        try:\n            output = _parse_output(outputs)\n            self.__track_event(\n                \"chain\",\n                \"end\",\n                run_id=str(run_id),\n                parent_run_id=str(parent_run_id) if parent_run_id else None,\n                output=output,\n                app_id=self.__app_id,\n            )\n        except Exception as e:\n            logger.error(f\"[LLMonitor] An error occurred in on_chain_end: {e}\")\n[docs]    def on_agent_action(\n        self,\n        action: AgentAction,\n        *,\n        run_id: UUID,\n        parent_run_id: Union[UUID, None] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if self.__has_valid_config is False:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "218e22867f05-11", "text": ") -> Any:\n        if self.__has_valid_config is False:\n            return\n        try:\n            name = action.tool\n            input = _parse_input(action.tool_input)\n            self.__track_event(\n                \"tool\",\n                \"start\",\n                run_id=str(run_id),\n                parent_run_id=str(parent_run_id) if parent_run_id else None,\n                name=name,\n                input=input,\n                app_id=self.__app_id,\n            )\n        except Exception as e:\n            logger.error(f\"[LLMonitor] An error occurred in on_agent_action: {e}\")\n[docs]    def on_agent_finish(\n        self,\n        finish: AgentFinish,\n        *,\n        run_id: UUID,\n        parent_run_id: Union[UUID, None] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if self.__has_valid_config is False:\n            return\n        try:\n            output = _parse_output(finish.return_values)\n            self.__track_event(\n                \"agent\",\n                \"end\",\n                run_id=str(run_id),\n                parent_run_id=str(parent_run_id) if parent_run_id else None,\n                output=output,\n                app_id=self.__app_id,\n            )\n        except Exception as e:\n            logger.error(f\"[LLMonitor] An error occurred in on_agent_finish: {e}\")\n[docs]    def on_chain_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Union[UUID, None] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if self.__has_valid_config is False:\n            return\n        try:\n            self.__track_event(\n                \"chain\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "218e22867f05-12", "text": "return\n        try:\n            self.__track_event(\n                \"chain\",\n                \"error\",\n                run_id=str(run_id),\n                parent_run_id=str(parent_run_id) if parent_run_id else None,\n                error={\"message\": str(error), \"stack\": traceback.format_exc()},\n                app_id=self.__app_id,\n            )\n        except Exception as e:\n            logger.error(f\"[LLMonitor] An error occurred in on_chain_error: {e}\")\n[docs]    def on_tool_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Union[UUID, None] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if self.__has_valid_config is False:\n            return\n        try:\n            self.__track_event(\n                \"tool\",\n                \"error\",\n                run_id=str(run_id),\n                parent_run_id=str(parent_run_id) if parent_run_id else None,\n                error={\"message\": str(error), \"stack\": traceback.format_exc()},\n                app_id=self.__app_id,\n            )\n        except Exception as e:\n            logger.error(f\"[LLMonitor] An error occurred in on_tool_error: {e}\")\n[docs]    def on_llm_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Union[UUID, None] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if self.__has_valid_config is False:\n            return\n        try:\n            self.__track_event(\n                \"llm\",\n                \"error\",\n                run_id=str(run_id),\n                parent_run_id=str(parent_run_id) if parent_run_id else None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "218e22867f05-13", "text": "parent_run_id=str(parent_run_id) if parent_run_id else None,\n                error={\"message\": str(error), \"stack\": traceback.format_exc()},\n                app_id=self.__app_id,\n            )\n        except Exception as e:\n            logger.error(f\"[LLMonitor] An error occurred in on_llm_error: {e}\")\n__all__ = [\"LLMonitorCallbackHandler\", \"identify\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html"}
{"id": "d08eb55b07a7-0", "text": "Source code for langchain.callbacks.file\n\"\"\"Callback Handler that writes to a file.\"\"\"\nfrom typing import Any, Dict, Optional, TextIO, cast\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema import AgentAction, AgentFinish\nfrom langchain.utils.input import print_text\n[docs]class FileCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback Handler that writes to a file.\"\"\"\n[docs]    def __init__(\n        self, filename: str, mode: str = \"a\", color: Optional[str] = None\n    ) -> None:\n        \"\"\"Initialize callback handler.\"\"\"\n        self.file = cast(TextIO, open(filename, mode, encoding=\"utf-8\"))\n        self.color = color\n    def __del__(self) -> None:\n        \"\"\"Destructor to cleanup when done.\"\"\"\n        self.file.close()\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Print out that we are entering a chain.\"\"\"\n        class_name = serialized.get(\"name\", serialized.get(\"id\", [\"<unknown>\"])[-1])\n        print_text(\n            f\"\\n\\n\\033[1m> Entering new {class_name} chain...\\033[0m\",\n            end=\"\\n\",\n            file=self.file,\n        )\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"Print out that we finished a chain.\"\"\"\n        print_text(\"\\n\\033[1m> Finished chain.\\033[0m\", end=\"\\n\", file=self.file)\n[docs]    def on_agent_action(\n        self, action: AgentAction, color: Optional[str] = None, **kwargs: Any", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/file.html"}
{"id": "d08eb55b07a7-1", "text": ") -> Any:\n        \"\"\"Run on agent action.\"\"\"\n        print_text(action.log, color=color or self.color, file=self.file)\n[docs]    def on_tool_end(\n        self,\n        output: str,\n        color: Optional[str] = None,\n        observation_prefix: Optional[str] = None,\n        llm_prefix: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"If not the final action, print out observation.\"\"\"\n        if observation_prefix is not None:\n            print_text(f\"\\n{observation_prefix}\", file=self.file)\n        print_text(output, color=color or self.color, file=self.file)\n        if llm_prefix is not None:\n            print_text(f\"\\n{llm_prefix}\", file=self.file)\n[docs]    def on_text(\n        self, text: str, color: Optional[str] = None, end: str = \"\", **kwargs: Any\n    ) -> None:\n        \"\"\"Run when agent ends.\"\"\"\n        print_text(text, color=color or self.color, end=end, file=self.file)\n[docs]    def on_agent_finish(\n        self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any\n    ) -> None:\n        \"\"\"Run on agent end.\"\"\"\n        print_text(finish.log, color=color or self.color, end=\"\\n\", file=self.file)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/file.html"}
{"id": "a2751fd82df9-0", "text": "Source code for langchain.callbacks.arize_callback\nfrom datetime import datetime\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.callbacks.utils import import_pandas\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\n[docs]class ArizeCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback Handler that logs to Arize.\"\"\"\n[docs]    def __init__(\n        self,\n        model_id: Optional[str] = None,\n        model_version: Optional[str] = None,\n        SPACE_KEY: Optional[str] = None,\n        API_KEY: Optional[str] = None,\n    ) -> None:\n        \"\"\"Initialize callback handler.\"\"\"\n        super().__init__()\n        self.model_id = model_id\n        self.model_version = model_version\n        self.space_key = SPACE_KEY\n        self.api_key = API_KEY\n        self.prompt_records: List[str] = []\n        self.response_records: List[str] = []\n        self.prediction_ids: List[str] = []\n        self.pred_timestamps: List[int] = []\n        self.response_embeddings: List[float] = []\n        self.prompt_embeddings: List[float] = []\n        self.prompt_tokens = 0\n        self.completion_tokens = 0\n        self.total_tokens = 0\n        self.step = 0\n        from arize.pandas.embeddings import EmbeddingGenerator, UseCases\n        from arize.pandas.logger import Client\n        self.generator = EmbeddingGenerator.from_use_case(\n            use_case=UseCases.NLP.SEQUENCE_CLASSIFICATION,\n            model_name=\"distilbert-base-uncased\",\n            tokenizer_max_length=512,\n            batch_size=256,\n        )\n        self.arize_client = Client(space_key=SPACE_KEY, api_key=API_KEY)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html"}
{"id": "a2751fd82df9-1", "text": "self.arize_client = Client(space_key=SPACE_KEY, api_key=API_KEY)\n        if SPACE_KEY == \"SPACE_KEY\" or API_KEY == \"API_KEY\":\n            raise ValueError(\"\u274c CHANGE SPACE AND API KEYS\")\n        else:\n            print(\"\u2705 Arize client setup done! Now you can start using Arize!\")\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        for prompt in prompts:\n            self.prompt_records.append(prompt.replace(\"\\n\", \"\"))\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Do nothing.\"\"\"\n        pass\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        pd = import_pandas()\n        from arize.utils.types import (\n            EmbeddingColumnNames,\n            Environments,\n            ModelTypes,\n            Schema,\n        )\n        # Safe check if 'llm_output' and 'token_usage' exist\n        if response.llm_output and \"token_usage\" in response.llm_output:\n            self.prompt_tokens = response.llm_output[\"token_usage\"].get(\n                \"prompt_tokens\", 0\n            )\n            self.total_tokens = response.llm_output[\"token_usage\"].get(\n                \"total_tokens\", 0\n            )\n            self.completion_tokens = response.llm_output[\"token_usage\"].get(\n                \"completion_tokens\", 0\n            )\n        else:\n            self.prompt_tokens = (\n                self.total_tokens\n            ) = self.completion_tokens = 0  # assign default value\n        for generations in response.generations:\n            for generation in generations:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html"}
{"id": "a2751fd82df9-2", "text": "for generations in response.generations:\n            for generation in generations:\n                prompt = self.prompt_records[self.step]\n                self.step = self.step + 1\n                prompt_embedding = pd.Series(\n                    self.generator.generate_embeddings(\n                        text_col=pd.Series(prompt.replace(\"\\n\", \" \"))\n                    ).reset_index(drop=True)\n                )\n                # Assigning text to response_text instead of response\n                response_text = generation.text.replace(\"\\n\", \" \")\n                response_embedding = pd.Series(\n                    self.generator.generate_embeddings(\n                        text_col=pd.Series(generation.text.replace(\"\\n\", \" \"))\n                    ).reset_index(drop=True)\n                )\n                pred_timestamp = datetime.now().timestamp()\n                # Define the columns and data\n                columns = [\n                    \"prediction_ts\",\n                    \"response\",\n                    \"prompt\",\n                    \"response_vector\",\n                    \"prompt_vector\",\n                    \"prompt_token\",\n                    \"completion_token\",\n                    \"total_token\",\n                ]\n                data = [\n                    [\n                        pred_timestamp,\n                        response_text,\n                        prompt,\n                        response_embedding[0],\n                        prompt_embedding[0],\n                        self.prompt_tokens,\n                        self.total_tokens,\n                        self.completion_tokens,\n                    ]\n                ]\n                # Create the DataFrame\n                df = pd.DataFrame(data, columns=columns)\n                # Declare prompt and response columns\n                prompt_columns = EmbeddingColumnNames(\n                    vector_column_name=\"prompt_vector\", data_column_name=\"prompt\"\n                )\n                response_columns = EmbeddingColumnNames(\n                    vector_column_name=\"response_vector\", data_column_name=\"response\"\n                )\n                schema = Schema(\n                    timestamp_column_name=\"prediction_ts\",\n                    tag_column_names=[\n                        \"prompt_token\",\n                        \"completion_token\",\n                        \"total_token\",\n                    ],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html"}
{"id": "a2751fd82df9-3", "text": "\"completion_token\",\n                        \"total_token\",\n                    ],\n                    prompt_column_names=prompt_columns,\n                    response_column_names=response_columns,\n                )\n                response_from_arize = self.arize_client.log(\n                    dataframe=df,\n                    schema=schema,\n                    model_id=self.model_id,\n                    model_version=self.model_version,\n                    model_type=ModelTypes.GENERATIVE_LLM,\n                    environment=Environments.PRODUCTION,\n                )\n                if response_from_arize.status_code == 200:\n                    print(\"\u2705 Successfully logged data to Arize!\")\n                else:\n                    print(f'\u274c Logging failed \"{response_from_arize.text}\"')\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing.\"\"\"\n        pass\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        pass\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"Do nothing.\"\"\"\n        pass\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing.\"\"\"\n        pass\n[docs]    def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        **kwargs: Any,\n    ) -> None:\n        pass\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Do nothing.\"\"\"\n        pass\n[docs]    def on_tool_end(\n        self,\n        output: str,\n        observation_prefix: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html"}
{"id": "a2751fd82df9-4", "text": "output: str,\n        observation_prefix: Optional[str] = None,\n        llm_prefix: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        pass\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        pass\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        pass\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html"}
{"id": "ec5a81de6def-0", "text": "Source code for langchain.callbacks.streaming_stdout\n\"\"\"Callback Handler streams to stdout on new llm token.\"\"\"\nimport sys\nfrom typing import Any, Dict, List\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\nfrom langchain.schema.messages import BaseMessage\n[docs]class StreamingStdOutCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback handler for streaming. Only works with LLMs that support streaming.\"\"\"\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when LLM starts running.\"\"\"\n[docs]    def on_chat_model_start(\n        self,\n        serialized: Dict[str, Any],\n        messages: List[List[BaseMessage]],\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when LLM starts running.\"\"\"\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Run on new LLM token. Only available when streaming is enabled.\"\"\"\n        sys.stdout.write(token)\n        sys.stdout.flush()\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Run when LLM ends running.\"\"\"\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when LLM errors.\"\"\"\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when chain starts running.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout.html"}
{"id": "ec5a81de6def-1", "text": ") -> None:\n        \"\"\"Run when chain starts running.\"\"\"\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"Run when chain ends running.\"\"\"\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when chain errors.\"\"\"\n[docs]    def on_tool_start(\n        self, serialized: Dict[str, Any], input_str: str, **kwargs: Any\n    ) -> None:\n        \"\"\"Run when tool starts running.\"\"\"\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Run on agent action.\"\"\"\n        pass\n[docs]    def on_tool_end(self, output: str, **kwargs: Any) -> None:\n        \"\"\"Run when tool ends running.\"\"\"\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when tool errors.\"\"\"\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        \"\"\"Run on arbitrary text.\"\"\"\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        \"\"\"Run on agent end.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout.html"}
{"id": "75d95966b7cf-0", "text": "Source code for langchain.callbacks.wandb_callback\nimport json\nimport tempfile\nfrom copy import deepcopy\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Sequence, Union\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.callbacks.utils import (\n    BaseMetadataCallbackHandler,\n    flatten_dict,\n    hash_string,\n    import_pandas,\n    import_spacy,\n    import_textstat,\n)\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\n[docs]def import_wandb() -> Any:\n    \"\"\"Import the wandb python package and raise an error if it is not installed.\"\"\"\n    try:\n        import wandb  # noqa: F401\n    except ImportError:\n        raise ImportError(\n            \"To use the wandb callback manager you need to have the `wandb` python \"\n            \"package installed. Please install it with `pip install wandb`\"\n        )\n    return wandb\n[docs]def load_json_to_dict(json_path: Union[str, Path]) -> dict:\n    \"\"\"Load json file to a dictionary.\n    Parameters:\n        json_path (str): The path to the json file.\n    Returns:\n        (dict): The dictionary representation of the json file.\n    \"\"\"\n    with open(json_path, \"r\") as f:\n        data = json.load(f)\n    return data\n[docs]def analyze_text(\n    text: str,\n    complexity_metrics: bool = True,\n    visualize: bool = True,\n    nlp: Any = None,\n    output_dir: Optional[Union[str, Path]] = None,\n) -> dict:\n    \"\"\"Analyze text using textstat and spacy.\n    Parameters:\n        text (str): The text to analyze.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html"}
{"id": "75d95966b7cf-1", "text": "Parameters:\n        text (str): The text to analyze.\n        complexity_metrics (bool): Whether to compute complexity metrics.\n        visualize (bool): Whether to visualize the text.\n        nlp (spacy.lang): The spacy language model to use for visualization.\n        output_dir (str): The directory to save the visualization files to.\n    Returns:\n        (dict): A dictionary containing the complexity metrics and visualization\n            files serialized in a wandb.Html element.\n    \"\"\"\n    resp = {}\n    textstat = import_textstat()\n    wandb = import_wandb()\n    spacy = import_spacy()\n    if complexity_metrics:\n        text_complexity_metrics = {\n            \"flesch_reading_ease\": textstat.flesch_reading_ease(text),\n            \"flesch_kincaid_grade\": textstat.flesch_kincaid_grade(text),\n            \"smog_index\": textstat.smog_index(text),\n            \"coleman_liau_index\": textstat.coleman_liau_index(text),\n            \"automated_readability_index\": textstat.automated_readability_index(text),\n            \"dale_chall_readability_score\": textstat.dale_chall_readability_score(text),\n            \"difficult_words\": textstat.difficult_words(text),\n            \"linsear_write_formula\": textstat.linsear_write_formula(text),\n            \"gunning_fog\": textstat.gunning_fog(text),\n            \"text_standard\": textstat.text_standard(text),\n            \"fernandez_huerta\": textstat.fernandez_huerta(text),\n            \"szigriszt_pazos\": textstat.szigriszt_pazos(text),\n            \"gutierrez_polini\": textstat.gutierrez_polini(text),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html"}
{"id": "75d95966b7cf-2", "text": "\"gutierrez_polini\": textstat.gutierrez_polini(text),\n            \"crawford\": textstat.crawford(text),\n            \"gulpease_index\": textstat.gulpease_index(text),\n            \"osman\": textstat.osman(text),\n        }\n        resp.update(text_complexity_metrics)\n    if visualize and nlp and output_dir is not None:\n        doc = nlp(text)\n        dep_out = spacy.displacy.render(  # type: ignore\n            doc, style=\"dep\", jupyter=False, page=True\n        )\n        dep_output_path = Path(output_dir, hash_string(f\"dep-{text}\") + \".html\")\n        dep_output_path.open(\"w\", encoding=\"utf-8\").write(dep_out)\n        ent_out = spacy.displacy.render(  # type: ignore\n            doc, style=\"ent\", jupyter=False, page=True\n        )\n        ent_output_path = Path(output_dir, hash_string(f\"ent-{text}\") + \".html\")\n        ent_output_path.open(\"w\", encoding=\"utf-8\").write(ent_out)\n        text_visualizations = {\n            \"dependency_tree\": wandb.Html(str(dep_output_path)),\n            \"entities\": wandb.Html(str(ent_output_path)),\n        }\n        resp.update(text_visualizations)\n    return resp\n[docs]def construct_html_from_prompt_and_generation(prompt: str, generation: str) -> Any:\n    \"\"\"Construct an html element from a prompt and a generation.\n    Parameters:\n        prompt (str): The prompt.\n        generation (str): The generation.\n    Returns:\n        (wandb.Html): The html element.\"\"\"\n    wandb = import_wandb()\n    formatted_prompt = prompt.replace(\"\\n\", \"<br>\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html"}
{"id": "75d95966b7cf-3", "text": "formatted_prompt = prompt.replace(\"\\n\", \"<br>\")\n    formatted_generation = generation.replace(\"\\n\", \"<br>\")\n    return wandb.Html(\n        f\"\"\"\n    <p style=\"color:black;\">{formatted_prompt}:</p>\n    <blockquote>\n      <p style=\"color:green;\">\n        {formatted_generation}\n      </p>\n    </blockquote>\n    \"\"\",\n        inject=False,\n    )\n[docs]class WandbCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):\n    \"\"\"Callback Handler that logs to Weights and Biases.\n    Parameters:\n        job_type (str): The type of job.\n        project (str): The project to log to.\n        entity (str): The entity to log to.\n        tags (list): The tags to log.\n        group (str): The group to log to.\n        name (str): The name of the run.\n        notes (str): The notes to log.\n        visualize (bool): Whether to visualize the run.\n        complexity_metrics (bool): Whether to log complexity metrics.\n        stream_logs (bool): Whether to stream callback actions to W&B\n    This handler will utilize the associated callback method called and formats\n    the input of each callback function with metadata regarding the state of LLM run,\n    and adds the response to the list of records for both the {method}_records and\n    action. It then logs the response using the run.log() method to Weights and Biases.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        job_type: Optional[str] = None,\n        project: Optional[str] = \"langchain_callback_demo\",\n        entity: Optional[str] = None,\n        tags: Optional[Sequence] = None,\n        group: Optional[str] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html"}
{"id": "75d95966b7cf-4", "text": "group: Optional[str] = None,\n        name: Optional[str] = None,\n        notes: Optional[str] = None,\n        visualize: bool = False,\n        complexity_metrics: bool = False,\n        stream_logs: bool = False,\n    ) -> None:\n        \"\"\"Initialize callback handler.\"\"\"\n        wandb = import_wandb()\n        import_pandas()\n        import_textstat()\n        spacy = import_spacy()\n        super().__init__()\n        self.job_type = job_type\n        self.project = project\n        self.entity = entity\n        self.tags = tags\n        self.group = group\n        self.name = name\n        self.notes = notes\n        self.visualize = visualize\n        self.complexity_metrics = complexity_metrics\n        self.stream_logs = stream_logs\n        self.temp_dir = tempfile.TemporaryDirectory()\n        self.run: wandb.sdk.wandb_run.Run = wandb.init(  # type: ignore\n            job_type=self.job_type,\n            project=self.project,\n            entity=self.entity,\n            tags=self.tags,\n            group=self.group,\n            name=self.name,\n            notes=self.notes,\n        )\n        warning = (\n            \"DEPRECATION: The `WandbCallbackHandler` will soon be deprecated in favor \"\n            \"of the `WandbTracer`. Please update your code to use the `WandbTracer` \"\n            \"instead.\"\n        )\n        wandb.termwarn(\n            warning,\n            repeat=False,\n        )\n        self.callback_columns: list = []\n        self.action_records: list = []\n        self.complexity_metrics = complexity_metrics\n        self.visualize = visualize\n        self.nlp = spacy.load(\"en_core_web_sm\")\n    def _init_resp(self) -> Dict:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html"}
{"id": "75d95966b7cf-5", "text": "def _init_resp(self) -> Dict:\n        return {k: None for k in self.callback_columns}\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when LLM starts.\"\"\"\n        self.step += 1\n        self.llm_starts += 1\n        self.starts += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_llm_start\"})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.get_custom_callback_meta())\n        for prompt in prompts:\n            prompt_resp = deepcopy(resp)\n            prompt_resp[\"prompts\"] = prompt\n            self.on_llm_start_records.append(prompt_resp)\n            self.action_records.append(prompt_resp)\n            if self.stream_logs:\n                self.run.log(prompt_resp)\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Run when LLM generates a new token.\"\"\"\n        self.step += 1\n        self.llm_streams += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_llm_new_token\", \"token\": token})\n        resp.update(self.get_custom_callback_meta())\n        self.on_llm_token_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.run.log(resp)\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Run when LLM ends running.\"\"\"\n        self.step += 1\n        self.llm_ends += 1\n        self.ends += 1\n        resp = self._init_resp()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html"}
{"id": "75d95966b7cf-6", "text": "self.ends += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_llm_end\"})\n        resp.update(flatten_dict(response.llm_output or {}))\n        resp.update(self.get_custom_callback_meta())\n        for generations in response.generations:\n            for generation in generations:\n                generation_resp = deepcopy(resp)\n                generation_resp.update(flatten_dict(generation.dict()))\n                generation_resp.update(\n                    analyze_text(\n                        generation.text,\n                        complexity_metrics=self.complexity_metrics,\n                        visualize=self.visualize,\n                        nlp=self.nlp,\n                        output_dir=self.temp_dir.name,\n                    )\n                )\n                self.on_llm_end_records.append(generation_resp)\n                self.action_records.append(generation_resp)\n                if self.stream_logs:\n                    self.run.log(generation_resp)\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when LLM errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when chain starts running.\"\"\"\n        self.step += 1\n        self.chain_starts += 1\n        self.starts += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_chain_start\"})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.get_custom_callback_meta())\n        chain_input = inputs[\"input\"]\n        if isinstance(chain_input, str):\n            input_resp = deepcopy(resp)\n            input_resp[\"input\"] = chain_input\n            self.on_chain_start_records.append(input_resp)\n            self.action_records.append(input_resp)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html"}
{"id": "75d95966b7cf-7", "text": "self.on_chain_start_records.append(input_resp)\n            self.action_records.append(input_resp)\n            if self.stream_logs:\n                self.run.log(input_resp)\n        elif isinstance(chain_input, list):\n            for inp in chain_input:\n                input_resp = deepcopy(resp)\n                input_resp.update(inp)\n                self.on_chain_start_records.append(input_resp)\n                self.action_records.append(input_resp)\n                if self.stream_logs:\n                    self.run.log(input_resp)\n        else:\n            raise ValueError(\"Unexpected data format provided!\")\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"Run when chain ends running.\"\"\"\n        self.step += 1\n        self.chain_ends += 1\n        self.ends += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_chain_end\", \"outputs\": outputs[\"output\"]})\n        resp.update(self.get_custom_callback_meta())\n        self.on_chain_end_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.run.log(resp)\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when chain errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_tool_start(\n        self, serialized: Dict[str, Any], input_str: str, **kwargs: Any\n    ) -> None:\n        \"\"\"Run when tool starts running.\"\"\"\n        self.step += 1\n        self.tool_starts += 1\n        self.starts += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_tool_start\", \"input_str\": input_str})\n        resp.update(flatten_dict(serialized))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html"}
{"id": "75d95966b7cf-8", "text": "resp.update(flatten_dict(serialized))\n        resp.update(self.get_custom_callback_meta())\n        self.on_tool_start_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.run.log(resp)\n[docs]    def on_tool_end(self, output: str, **kwargs: Any) -> None:\n        \"\"\"Run when tool ends running.\"\"\"\n        self.step += 1\n        self.tool_ends += 1\n        self.ends += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_tool_end\", \"output\": output})\n        resp.update(self.get_custom_callback_meta())\n        self.on_tool_end_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.run.log(resp)\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when tool errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        \"\"\"\n        Run when agent is ending.\n        \"\"\"\n        self.step += 1\n        self.text_ctr += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_text\", \"text\": text})\n        resp.update(self.get_custom_callback_meta())\n        self.on_text_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.run.log(resp)\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        \"\"\"Run when agent ends running.\"\"\"\n        self.step += 1\n        self.agent_ends += 1\n        self.ends += 1", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html"}
{"id": "75d95966b7cf-9", "text": "self.agent_ends += 1\n        self.ends += 1\n        resp = self._init_resp()\n        resp.update(\n            {\n                \"action\": \"on_agent_finish\",\n                \"output\": finish.return_values[\"output\"],\n                \"log\": finish.log,\n            }\n        )\n        resp.update(self.get_custom_callback_meta())\n        self.on_agent_finish_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.run.log(resp)\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Run on agent action.\"\"\"\n        self.step += 1\n        self.tool_starts += 1\n        self.starts += 1\n        resp = self._init_resp()\n        resp.update(\n            {\n                \"action\": \"on_agent_action\",\n                \"tool\": action.tool,\n                \"tool_input\": action.tool_input,\n                \"log\": action.log,\n            }\n        )\n        resp.update(self.get_custom_callback_meta())\n        self.on_agent_action_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.run.log(resp)\n    def _create_session_analysis_df(self) -> Any:\n        \"\"\"Create a dataframe with all the information from the session.\"\"\"\n        pd = import_pandas()\n        on_llm_start_records_df = pd.DataFrame(self.on_llm_start_records)\n        on_llm_end_records_df = pd.DataFrame(self.on_llm_end_records)\n        llm_input_prompts_df = (\n            on_llm_start_records_df[[\"step\", \"prompts\", \"name\"]]\n            .dropna(axis=1)\n            .rename({\"step\": \"prompt_step\"}, axis=1)\n        )\n        complexity_metrics_columns = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html"}
{"id": "75d95966b7cf-10", "text": ")\n        complexity_metrics_columns = []\n        visualizations_columns = []\n        if self.complexity_metrics:\n            complexity_metrics_columns = [\n                \"flesch_reading_ease\",\n                \"flesch_kincaid_grade\",\n                \"smog_index\",\n                \"coleman_liau_index\",\n                \"automated_readability_index\",\n                \"dale_chall_readability_score\",\n                \"difficult_words\",\n                \"linsear_write_formula\",\n                \"gunning_fog\",\n                \"text_standard\",\n                \"fernandez_huerta\",\n                \"szigriszt_pazos\",\n                \"gutierrez_polini\",\n                \"crawford\",\n                \"gulpease_index\",\n                \"osman\",\n            ]\n        if self.visualize:\n            visualizations_columns = [\"dependency_tree\", \"entities\"]\n        llm_outputs_df = (\n            on_llm_end_records_df[\n                [\n                    \"step\",\n                    \"text\",\n                    \"token_usage_total_tokens\",\n                    \"token_usage_prompt_tokens\",\n                    \"token_usage_completion_tokens\",\n                ]\n                + complexity_metrics_columns\n                + visualizations_columns\n            ]\n            .dropna(axis=1)\n            .rename({\"step\": \"output_step\", \"text\": \"output\"}, axis=1)\n        )\n        session_analysis_df = pd.concat([llm_input_prompts_df, llm_outputs_df], axis=1)\n        session_analysis_df[\"chat_html\"] = session_analysis_df[\n            [\"prompts\", \"output\"]\n        ].apply(\n            lambda row: construct_html_from_prompt_and_generation(\n                row[\"prompts\"], row[\"output\"]\n            ),\n            axis=1,\n        )\n        return session_analysis_df", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html"}
{"id": "75d95966b7cf-11", "text": "),\n            axis=1,\n        )\n        return session_analysis_df\n[docs]    def flush_tracker(\n        self,\n        langchain_asset: Any = None,\n        reset: bool = True,\n        finish: bool = False,\n        job_type: Optional[str] = None,\n        project: Optional[str] = None,\n        entity: Optional[str] = None,\n        tags: Optional[Sequence] = None,\n        group: Optional[str] = None,\n        name: Optional[str] = None,\n        notes: Optional[str] = None,\n        visualize: Optional[bool] = None,\n        complexity_metrics: Optional[bool] = None,\n    ) -> None:\n        \"\"\"Flush the tracker and reset the session.\n        Args:\n            langchain_asset: The langchain asset to save.\n            reset: Whether to reset the session.\n            finish: Whether to finish the run.\n            job_type: The job type.\n            project: The project.\n            entity: The entity.\n            tags: The tags.\n            group: The group.\n            name: The name.\n            notes: The notes.\n            visualize: Whether to visualize.\n            complexity_metrics: Whether to compute complexity metrics.\n            Returns:\n                None\n        \"\"\"\n        pd = import_pandas()\n        wandb = import_wandb()\n        action_records_table = wandb.Table(dataframe=pd.DataFrame(self.action_records))\n        session_analysis_table = wandb.Table(\n            dataframe=self._create_session_analysis_df()\n        )\n        self.run.log(\n            {\n                \"action_records\": action_records_table,\n                \"session_analysis\": session_analysis_table,\n            }\n        )\n        if langchain_asset:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html"}
{"id": "75d95966b7cf-12", "text": "}\n        )\n        if langchain_asset:\n            langchain_asset_path = Path(self.temp_dir.name, \"model.json\")\n            model_artifact = wandb.Artifact(name=\"model\", type=\"model\")\n            model_artifact.add(action_records_table, name=\"action_records\")\n            model_artifact.add(session_analysis_table, name=\"session_analysis\")\n            try:\n                langchain_asset.save(langchain_asset_path)\n                model_artifact.add_file(str(langchain_asset_path))\n                model_artifact.metadata = load_json_to_dict(langchain_asset_path)\n            except ValueError:\n                langchain_asset.save_agent(langchain_asset_path)\n                model_artifact.add_file(str(langchain_asset_path))\n                model_artifact.metadata = load_json_to_dict(langchain_asset_path)\n            except NotImplementedError as e:\n                print(\"Could not save model.\")\n                print(repr(e))\n                pass\n            self.run.log_artifact(model_artifact)\n        if finish or reset:\n            self.run.finish()\n            self.temp_dir.cleanup()\n            self.reset_callback_meta()\n        if reset:\n            self.__init__(  # type: ignore\n                job_type=job_type if job_type else self.job_type,\n                project=project if project else self.project,\n                entity=entity if entity else self.entity,\n                tags=tags if tags else self.tags,\n                group=group if group else self.group,\n                name=name if name else self.name,\n                notes=notes if notes else self.notes,\n                visualize=visualize if visualize else self.visualize,\n                complexity_metrics=complexity_metrics\n                if complexity_metrics\n                else self.complexity_metrics,\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html"}
{"id": "1b6ba24f9219-0", "text": "Source code for langchain.callbacks.utils\nimport hashlib\nfrom pathlib import Path\nfrom typing import Any, Dict, Iterable, Tuple, Union\n[docs]def import_spacy() -> Any:\n    \"\"\"Import the spacy python package and raise an error if it is not installed.\"\"\"\n    try:\n        import spacy\n    except ImportError:\n        raise ImportError(\n            \"This callback manager requires the `spacy` python \"\n            \"package installed. Please install it with `pip install spacy`\"\n        )\n    return spacy\n[docs]def import_pandas() -> Any:\n    \"\"\"Import the pandas python package and raise an error if it is not installed.\"\"\"\n    try:\n        import pandas\n    except ImportError:\n        raise ImportError(\n            \"This callback manager requires the `pandas` python \"\n            \"package installed. Please install it with `pip install pandas`\"\n        )\n    return pandas\n[docs]def import_textstat() -> Any:\n    \"\"\"Import the textstat python package and raise an error if it is not installed.\"\"\"\n    try:\n        import textstat\n    except ImportError:\n        raise ImportError(\n            \"This callback manager requires the `textstat` python \"\n            \"package installed. Please install it with `pip install textstat`\"\n        )\n    return textstat\ndef _flatten_dict(\n    nested_dict: Dict[str, Any], parent_key: str = \"\", sep: str = \"_\"\n) -> Iterable[Tuple[str, Any]]:\n    \"\"\"\n    Generator that yields flattened items from a nested dictionary for a flat dict.\n    Parameters:\n        nested_dict (dict): The nested dictionary to flatten.\n        parent_key (str): The prefix to prepend to the keys of the flattened dict.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html"}
{"id": "1b6ba24f9219-1", "text": "parent_key (str): The prefix to prepend to the keys of the flattened dict.\n        sep (str): The separator to use between the parent key and the key of the\n            flattened dictionary.\n    Yields:\n        (str, any): A key-value pair from the flattened dictionary.\n    \"\"\"\n    for key, value in nested_dict.items():\n        new_key = parent_key + sep + key if parent_key else key\n        if isinstance(value, dict):\n            yield from _flatten_dict(value, new_key, sep)\n        else:\n            yield new_key, value\n[docs]def flatten_dict(\n    nested_dict: Dict[str, Any], parent_key: str = \"\", sep: str = \"_\"\n) -> Dict[str, Any]:\n    \"\"\"Flattens a nested dictionary into a flat dictionary.\n    Parameters:\n        nested_dict (dict): The nested dictionary to flatten.\n        parent_key (str): The prefix to prepend to the keys of the flattened dict.\n        sep (str): The separator to use between the parent key and the key of the\n            flattened dictionary.\n    Returns:\n        (dict): A flat dictionary.\n    \"\"\"\n    flat_dict = {k: v for k, v in _flatten_dict(nested_dict, parent_key, sep)}\n    return flat_dict\n[docs]def hash_string(s: str) -> str:\n    \"\"\"Hash a string using sha1.\n    Parameters:\n        s (str): The string to hash.\n    Returns:\n        (str): The hashed string.\n    \"\"\"\n    return hashlib.sha1(s.encode(\"utf-8\")).hexdigest()\n[docs]def load_json(json_path: Union[str, Path]) -> str:\n    \"\"\"Load json file to a string.\n    Parameters:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html"}
{"id": "1b6ba24f9219-2", "text": "\"\"\"Load json file to a string.\n    Parameters:\n        json_path (str): The path to the json file.\n    Returns:\n        (str): The string representation of the json file.\n    \"\"\"\n    with open(json_path, \"r\") as f:\n        data = f.read()\n    return data\n[docs]class BaseMetadataCallbackHandler:\n    \"\"\"This class handles the metadata and associated function states for callbacks.\n    Attributes:\n        step (int): The current step.\n        starts (int): The number of times the start method has been called.\n        ends (int): The number of times the end method has been called.\n        errors (int): The number of times the error method has been called.\n        text_ctr (int): The number of times the text method has been called.\n        ignore_llm_ (bool): Whether to ignore llm callbacks.\n        ignore_chain_ (bool): Whether to ignore chain callbacks.\n        ignore_agent_ (bool): Whether to ignore agent callbacks.\n        ignore_retriever_ (bool): Whether to ignore retriever callbacks.\n        always_verbose_ (bool): Whether to always be verbose.\n        chain_starts (int): The number of times the chain start method has been called.\n        chain_ends (int): The number of times the chain end method has been called.\n        llm_starts (int): The number of times the llm start method has been called.\n        llm_ends (int): The number of times the llm end method has been called.\n        llm_streams (int): The number of times the text method has been called.\n        tool_starts (int): The number of times the tool start method has been called.\n        tool_ends (int): The number of times the tool end method has been called.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html"}
{"id": "1b6ba24f9219-3", "text": "tool_ends (int): The number of times the tool end method has been called.\n        agent_ends (int): The number of times the agent end method has been called.\n        on_llm_start_records (list): A list of records of the on_llm_start method.\n        on_llm_token_records (list): A list of records of the on_llm_token method.\n        on_llm_end_records (list): A list of records of the on_llm_end method.\n        on_chain_start_records (list): A list of records of the on_chain_start method.\n        on_chain_end_records (list): A list of records of the on_chain_end method.\n        on_tool_start_records (list): A list of records of the on_tool_start method.\n        on_tool_end_records (list): A list of records of the on_tool_end method.\n        on_agent_finish_records (list): A list of records of the on_agent_end method.\n    \"\"\"\n[docs]    def __init__(self) -> None:\n        self.step = 0\n        self.starts = 0\n        self.ends = 0\n        self.errors = 0\n        self.text_ctr = 0\n        self.ignore_llm_ = False\n        self.ignore_chain_ = False\n        self.ignore_agent_ = False\n        self.ignore_retriever_ = False\n        self.always_verbose_ = False\n        self.chain_starts = 0\n        self.chain_ends = 0\n        self.llm_starts = 0\n        self.llm_ends = 0\n        self.llm_streams = 0\n        self.tool_starts = 0\n        self.tool_ends = 0\n        self.agent_ends = 0\n        self.on_llm_start_records: list = []\n        self.on_llm_token_records: list = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html"}
{"id": "1b6ba24f9219-4", "text": "self.on_llm_token_records: list = []\n        self.on_llm_end_records: list = []\n        self.on_chain_start_records: list = []\n        self.on_chain_end_records: list = []\n        self.on_tool_start_records: list = []\n        self.on_tool_end_records: list = []\n        self.on_text_records: list = []\n        self.on_agent_finish_records: list = []\n        self.on_agent_action_records: list = []\n    @property\n    def always_verbose(self) -> bool:\n        \"\"\"Whether to call verbose callbacks even if verbose is False.\"\"\"\n        return self.always_verbose_\n    @property\n    def ignore_llm(self) -> bool:\n        \"\"\"Whether to ignore LLM callbacks.\"\"\"\n        return self.ignore_llm_\n    @property\n    def ignore_chain(self) -> bool:\n        \"\"\"Whether to ignore chain callbacks.\"\"\"\n        return self.ignore_chain_\n    @property\n    def ignore_agent(self) -> bool:\n        \"\"\"Whether to ignore agent callbacks.\"\"\"\n        return self.ignore_agent_\n[docs]    def get_custom_callback_meta(self) -> Dict[str, Any]:\n        return {\n            \"step\": self.step,\n            \"starts\": self.starts,\n            \"ends\": self.ends,\n            \"errors\": self.errors,\n            \"text_ctr\": self.text_ctr,\n            \"chain_starts\": self.chain_starts,\n            \"chain_ends\": self.chain_ends,\n            \"llm_starts\": self.llm_starts,\n            \"llm_ends\": self.llm_ends,\n            \"llm_streams\": self.llm_streams,\n            \"tool_starts\": self.tool_starts,\n            \"tool_ends\": self.tool_ends,\n            \"agent_ends\": self.agent_ends,\n        }\n[docs]    def reset_callback_meta(self) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html"}
{"id": "1b6ba24f9219-5", "text": "}\n[docs]    def reset_callback_meta(self) -> None:\n        \"\"\"Reset the callback metadata.\"\"\"\n        self.step = 0\n        self.starts = 0\n        self.ends = 0\n        self.errors = 0\n        self.text_ctr = 0\n        self.ignore_llm_ = False\n        self.ignore_chain_ = False\n        self.ignore_agent_ = False\n        self.always_verbose_ = False\n        self.chain_starts = 0\n        self.chain_ends = 0\n        self.llm_starts = 0\n        self.llm_ends = 0\n        self.llm_streams = 0\n        self.tool_starts = 0\n        self.tool_ends = 0\n        self.agent_ends = 0\n        self.on_llm_start_records = []\n        self.on_llm_token_records = []\n        self.on_llm_end_records = []\n        self.on_chain_start_records = []\n        self.on_chain_end_records = []\n        self.on_tool_start_records = []\n        self.on_tool_end_records = []\n        self.on_text_records = []\n        self.on_agent_finish_records = []\n        self.on_agent_action_records = []\n        return None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html"}
{"id": "c4d7491a702e-0", "text": "Source code for langchain.callbacks.labelstudio_callback\nimport os\nimport warnings\nfrom datetime import datetime\nfrom enum import Enum\nfrom typing import Any, Dict, List, Optional, Tuple, Union\nfrom uuid import UUID\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema import (\n    AgentAction,\n    AgentFinish,\n    BaseMessage,\n    ChatMessage,\n    Generation,\n    LLMResult,\n)\n[docs]class LabelStudioMode(Enum):\n    \"\"\"Label Studio mode enumerator.\"\"\"\n    PROMPT = \"prompt\"\n    CHAT = \"chat\"\n[docs]def get_default_label_configs(\n    mode: Union[str, LabelStudioMode]\n) -> Tuple[str, LabelStudioMode]:\n    \"\"\"Get default Label Studio configs for the given mode.\n    Parameters:\n        mode: Label Studio mode (\"prompt\" or \"chat\")\n    Returns: Tuple of Label Studio config and mode\n    \"\"\"\n    _default_label_configs = {\n        LabelStudioMode.PROMPT.value: \"\"\"\n<View>\n<Style>\n    .prompt-box {\n        background-color: white;\n        border-radius: 10px;\n        box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);\n        padding: 20px;\n    }\n</Style>\n<View className=\"root\">\n    <View className=\"prompt-box\">\n        <Text name=\"prompt\" value=\"$prompt\"/>\n    </View>\n    <TextArea name=\"response\" toName=\"prompt\"\n              maxSubmissions=\"1\" editable=\"true\"\n              required=\"true\"/>\n</View>\n<Header value=\"Rate the response:\"/>\n<Rating name=\"rating\" toName=\"prompt\"/>\n</View>\"\"\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html"}
{"id": "c4d7491a702e-1", "text": "<Rating name=\"rating\" toName=\"prompt\"/>\n</View>\"\"\",\n        LabelStudioMode.CHAT.value: \"\"\"\n<View>\n<View className=\"root\">\n     <Paragraphs name=\"dialogue\"\n               value=\"$prompt\"\n               layout=\"dialogue\"\n               textKey=\"content\"\n               nameKey=\"role\"\n               granularity=\"sentence\"/>\n  <Header value=\"Final response:\"/>\n    <TextArea name=\"response\" toName=\"dialogue\"\n              maxSubmissions=\"1\" editable=\"true\"\n              required=\"true\"/>\n</View>\n<Header value=\"Rate the response:\"/>\n<Rating name=\"rating\" toName=\"dialogue\"/>\n</View>\"\"\",\n    }\n    if isinstance(mode, str):\n        mode = LabelStudioMode(mode)\n    return _default_label_configs[mode.value], mode\n[docs]class LabelStudioCallbackHandler(BaseCallbackHandler):\n    \"\"\"Label Studio callback handler.\n    Provides the ability to send predictions to Label Studio\n    for human evaluation, feedback and annotation.\n    Parameters:\n        api_key: Label Studio API key\n        url: Label Studio URL\n        project_id: Label Studio project ID\n        project_name: Label Studio project name\n        project_config: Label Studio project config (XML)\n        mode: Label Studio mode (\"prompt\" or \"chat\")\n    Examples:\n        >>> from langchain.llms import OpenAI\n        >>> from langchain.callbacks import LabelStudioCallbackHandler\n        >>> handler = LabelStudioCallbackHandler(\n        ...             api_key='<your_key_here>',\n        ...             url='http://localhost:8080',\n        ...             project_name='LangChain-%Y-%m-%d',\n        ...             mode='prompt'\n        ... )\n        >>> llm = OpenAI(callbacks=[handler])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html"}
{"id": "c4d7491a702e-2", "text": "... )\n        >>> llm = OpenAI(callbacks=[handler])\n        >>> llm.predict('Tell me a story about a dog.')\n    \"\"\"\n    DEFAULT_PROJECT_NAME: str = \"LangChain-%Y-%m-%d\"\n[docs]    def __init__(\n        self,\n        api_key: Optional[str] = None,\n        url: Optional[str] = None,\n        project_id: Optional[int] = None,\n        project_name: str = DEFAULT_PROJECT_NAME,\n        project_config: Optional[str] = None,\n        mode: Union[str, LabelStudioMode] = LabelStudioMode.PROMPT,\n    ):\n        super().__init__()\n        # Import LabelStudio SDK\n        try:\n            import label_studio_sdk as ls\n        except ImportError:\n            raise ImportError(\n                f\"You're using {self.__class__.__name__} in your code,\"\n                f\" but you don't have the LabelStudio SDK \"\n                f\"Python package installed or upgraded to the latest version. \"\n                f\"Please run `pip install -U label-studio-sdk`\"\n                f\" before using this callback.\"\n            )\n        # Check if Label Studio API key is provided\n        if not api_key:\n            if os.getenv(\"LABEL_STUDIO_API_KEY\"):\n                api_key = str(os.getenv(\"LABEL_STUDIO_API_KEY\"))\n            else:\n                raise ValueError(\n                    f\"You're using {self.__class__.__name__} in your code,\"\n                    f\" Label Studio API key is not provided. \"\n                    f\"Please provide Label Studio API key: \"\n                    f\"go to the Label Studio instance, navigate to \"\n                    f\"Account & Settings -> Access Token and copy the key. \"\n                    f\"Use the key as a parameter for the callback: \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html"}
{"id": "c4d7491a702e-3", "text": "f\"Use the key as a parameter for the callback: \"\n                    f\"{self.__class__.__name__}\"\n                    f\"(label_studio_api_key='<your_key_here>', ...) or \"\n                    f\"set the environment variable LABEL_STUDIO_API_KEY=<your_key_here>\"\n                )\n        self.api_key = api_key\n        if not url:\n            if os.getenv(\"LABEL_STUDIO_URL\"):\n                url = os.getenv(\"LABEL_STUDIO_URL\")\n            else:\n                warnings.warn(\n                    f\"Label Studio URL is not provided, \"\n                    f\"using default URL: {ls.LABEL_STUDIO_DEFAULT_URL}\"\n                    f\"If you want to provide your own URL, use the parameter: \"\n                    f\"{self.__class__.__name__}\"\n                    f\"(label_studio_url='<your_url_here>', ...) \"\n                    f\"or set the environment variable LABEL_STUDIO_URL=<your_url_here>\"\n                )\n                url = ls.LABEL_STUDIO_DEFAULT_URL\n        self.url = url\n        # Maps run_id to prompts\n        self.payload: Dict[str, Dict] = {}\n        self.ls_client = ls.Client(url=self.url, api_key=self.api_key)\n        self.project_name = project_name\n        if project_config:\n            self.project_config = project_config\n            self.mode = None\n        else:\n            self.project_config, self.mode = get_default_label_configs(mode)\n        self.project_id = project_id or os.getenv(\"LABEL_STUDIO_PROJECT_ID\")\n        if self.project_id is not None:\n            self.ls_project = self.ls_client.get_project(int(self.project_id))\n        else:\n            project_title = datetime.today().strftime(self.project_name)\n            existing_projects = self.ls_client.get_projects(title=project_title)\n            if existing_projects:\n                self.ls_project = existing_projects[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html"}
{"id": "c4d7491a702e-4", "text": "if existing_projects:\n                self.ls_project = existing_projects[0]\n                self.project_id = self.ls_project.id\n            else:\n                self.ls_project = self.ls_client.create_project(\n                    title=project_title, label_config=self.project_config\n                )\n                self.project_id = self.ls_project.id\n        self.parsed_label_config = self.ls_project.parsed_label_config\n        # Find the first TextArea tag\n        # \"from_name\", \"to_name\", \"value\" will be used to create predictions\n        self.from_name, self.to_name, self.value, self.input_type = (\n            None,\n            None,\n            None,\n            None,\n        )\n        for tag_name, tag_info in self.parsed_label_config.items():\n            if tag_info[\"type\"] == \"TextArea\":\n                self.from_name = tag_name\n                self.to_name = tag_info[\"to_name\"][0]\n                self.value = tag_info[\"inputs\"][0][\"value\"]\n                self.input_type = tag_info[\"inputs\"][0][\"type\"]\n                break\n        if not self.from_name:\n            error_message = (\n                f'Label Studio project \"{self.project_name}\" '\n                f\"does not have a TextArea tag. \"\n                f\"Please add a TextArea tag to the project.\"\n            )\n            if self.mode == LabelStudioMode.PROMPT:\n                error_message += (\n                    \"\\nHINT: go to project Settings -> \"\n                    \"Labeling Interface -> Browse Templates\"\n                    ' and select \"Generative AI -> '\n                    'Supervised Language Model Fine-tuning\" template.'\n                )\n            else:\n                error_message += (\n                    \"\\nHINT: go to project Settings -> \"\n                    \"Labeling Interface -> Browse Templates\"\n                    \" and check available templates under \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html"}
{"id": "c4d7491a702e-5", "text": "\"Labeling Interface -> Browse Templates\"\n                    \" and check available templates under \"\n                    '\"Generative AI\" section.'\n                )\n            raise ValueError(error_message)\n[docs]    def add_prompts_generations(\n        self, run_id: str, generations: List[List[Generation]]\n    ) -> None:\n        # Create tasks in Label Studio\n        tasks = []\n        prompts = self.payload[run_id][\"prompts\"]\n        model_version = (\n            self.payload[run_id][\"kwargs\"]\n            .get(\"invocation_params\", {})\n            .get(\"model_name\")\n        )\n        for prompt, generation in zip(prompts, generations):\n            tasks.append(\n                {\n                    \"data\": {\n                        self.value: prompt,\n                        \"run_id\": run_id,\n                    },\n                    \"predictions\": [\n                        {\n                            \"result\": [\n                                {\n                                    \"from_name\": self.from_name,\n                                    \"to_name\": self.to_name,\n                                    \"type\": \"textarea\",\n                                    \"value\": {\"text\": [g.text for g in generation]},\n                                }\n                            ],\n                            \"model_version\": model_version,\n                        }\n                    ],\n                }\n            )\n        self.ls_project.import_tasks(tasks)\n[docs]    def on_llm_start(\n        self,\n        serialized: Dict[str, Any],\n        prompts: List[str],\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Save the prompts in memory when an LLM starts.\"\"\"\n        if self.input_type != \"Text\":\n            raise ValueError(\n                f'\\nLabel Studio project \"{self.project_name}\" '\n                f\"has an input type <{self.input_type}>. \"\n                f'To make it work with the mode=\"chat\", '", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html"}
{"id": "c4d7491a702e-6", "text": "f'To make it work with the mode=\"chat\", '\n                f\"the input type should be <Text>.\\n\"\n                f\"Read more here https://labelstud.io/tags/text\"\n            )\n        run_id = str(kwargs[\"run_id\"])\n        self.payload[run_id] = {\"prompts\": prompts, \"kwargs\": kwargs}\n    def _get_message_role(self, message: BaseMessage) -> str:\n        \"\"\"Get the role of the message.\"\"\"\n        if isinstance(message, ChatMessage):\n            return message.role\n        else:\n            return message.__class__.__name__\n[docs]    def on_chat_model_start(\n        self,\n        serialized: Dict[str, Any],\n        messages: List[List[BaseMessage]],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Save the prompts in memory when an LLM starts.\"\"\"\n        if self.input_type != \"Paragraphs\":\n            raise ValueError(\n                f'\\nLabel Studio project \"{self.project_name}\" '\n                f\"has an input type <{self.input_type}>. \"\n                f'To make it work with the mode=\"chat\", '\n                f\"the input type should be <Paragraphs>.\\n\"\n                f\"Read more here https://labelstud.io/tags/paragraphs\"\n            )\n        prompts = []\n        for message_list in messages:\n            dialog = []\n            for message in message_list:\n                dialog.append(\n                    {\n                        \"role\": self._get_message_role(message),\n                        \"content\": message.content,\n                    }\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html"}
{"id": "c4d7491a702e-7", "text": "\"content\": message.content,\n                    }\n                )\n            prompts.append(dialog)\n        self.payload[str(run_id)] = {\n            \"prompts\": prompts,\n            \"tags\": tags,\n            \"metadata\": metadata,\n            \"run_id\": run_id,\n            \"parent_run_id\": parent_run_id,\n            \"kwargs\": kwargs,\n        }\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Do nothing when a new token is generated.\"\"\"\n        pass\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Create a new Label Studio task for each prompt and generation.\"\"\"\n        run_id = str(kwargs[\"run_id\"])\n        # Submit results to Label Studio\n        self.add_prompts_generations(run_id, response.generations)\n        # Pop current run from `self.runs`\n        self.payload.pop(run_id)\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing when LLM outputs an error.\"\"\"\n        pass\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        pass\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        pass\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing when LLM chain outputs an error.\"\"\"\n        pass\n[docs]    def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html"}
{"id": "c4d7491a702e-8", "text": "self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Do nothing when tool starts.\"\"\"\n        pass\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Do nothing when agent takes a specific action.\"\"\"\n        pass\n[docs]    def on_tool_end(\n        self,\n        output: str,\n        observation_prefix: Optional[str] = None,\n        llm_prefix: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Do nothing when tool ends.\"\"\"\n        pass\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing when tool outputs an error.\"\"\"\n        pass\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        \"\"\"Do nothing\"\"\"\n        pass\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        \"\"\"Do nothing\"\"\"\n        pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html"}
{"id": "f2c6f2d95e70-0", "text": "Source code for langchain.callbacks.streaming_aiter_final_only\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.streaming_aiter import AsyncIteratorCallbackHandler\nfrom langchain.schema import LLMResult\nDEFAULT_ANSWER_PREFIX_TOKENS = [\"Final\", \"Answer\", \":\"]\n[docs]class AsyncFinalIteratorCallbackHandler(AsyncIteratorCallbackHandler):\n    \"\"\"Callback handler that returns an async iterator.\n    Only the final output of the agent will be iterated.\n    \"\"\"\n[docs]    def append_to_last_tokens(self, token: str) -> None:\n        self.last_tokens.append(token)\n        self.last_tokens_stripped.append(token.strip())\n        if len(self.last_tokens) > len(self.answer_prefix_tokens):\n            self.last_tokens.pop(0)\n            self.last_tokens_stripped.pop(0)\n[docs]    def check_if_answer_reached(self) -> bool:\n        if self.strip_tokens:\n            return self.last_tokens_stripped == self.answer_prefix_tokens_stripped\n        else:\n            return self.last_tokens == self.answer_prefix_tokens\n[docs]    def __init__(\n        self,\n        *,\n        answer_prefix_tokens: Optional[List[str]] = None,\n        strip_tokens: bool = True,\n        stream_prefix: bool = False,\n    ) -> None:\n        \"\"\"Instantiate AsyncFinalIteratorCallbackHandler.\n        Args:\n            answer_prefix_tokens: Token sequence that prefixes the answer.\n                Default is [\"Final\", \"Answer\", \":\"]\n            strip_tokens: Ignore white spaces and new lines when comparing\n                answer_prefix_tokens to last tokens? (to determine if answer has been\n                reached)\n            stream_prefix: Should answer prefix itself also be streamed?\n        \"\"\"\n        super().__init__()\n        if answer_prefix_tokens is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter_final_only.html"}
{"id": "f2c6f2d95e70-1", "text": "\"\"\"\n        super().__init__()\n        if answer_prefix_tokens is None:\n            self.answer_prefix_tokens = DEFAULT_ANSWER_PREFIX_TOKENS\n        else:\n            self.answer_prefix_tokens = answer_prefix_tokens\n        if strip_tokens:\n            self.answer_prefix_tokens_stripped = [\n                token.strip() for token in self.answer_prefix_tokens\n            ]\n        else:\n            self.answer_prefix_tokens_stripped = self.answer_prefix_tokens\n        self.last_tokens = [\"\"] * len(self.answer_prefix_tokens)\n        self.last_tokens_stripped = [\"\"] * len(self.answer_prefix_tokens)\n        self.strip_tokens = strip_tokens\n        self.stream_prefix = stream_prefix\n        self.answer_reached = False\n[docs]    async def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        # If two calls are made in a row, this resets the state\n        self.done.clear()\n        self.answer_reached = False\n[docs]    async def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        if self.answer_reached:\n            self.done.set()\n[docs]    async def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        # Remember the last n tokens, where n = len(answer_prefix_tokens)\n        self.append_to_last_tokens(token)\n        # Check if the last n tokens match the answer_prefix_tokens list ...\n        if self.check_if_answer_reached():\n            self.answer_reached = True\n            if self.stream_prefix:\n                for t in self.last_tokens:\n                    self.queue.put_nowait(t)\n            return\n        # If yes, then put tokens from now on\n        if self.answer_reached:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter_final_only.html"}
{"id": "f2c6f2d95e70-2", "text": "# If yes, then put tokens from now on\n        if self.answer_reached:\n            self.queue.put_nowait(token)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter_final_only.html"}
{"id": "19cd28074cbd-0", "text": "Source code for langchain.callbacks.arthur_callback\n\"\"\"ArthurAI's Callback Handler.\"\"\"\nfrom __future__ import annotations\nimport os\nimport uuid\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom time import time\nfrom typing import TYPE_CHECKING, Any, DefaultDict, Dict, List, Optional\nimport numpy as np\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\nif TYPE_CHECKING:\n    import arthurai\n    from arthurai.core.models import ArthurModel\nPROMPT_TOKENS = \"prompt_tokens\"\nCOMPLETION_TOKENS = \"completion_tokens\"\nTOKEN_USAGE = \"token_usage\"\nFINISH_REASON = \"finish_reason\"\nDURATION = \"duration\"\ndef _lazy_load_arthur() -> arthurai:\n    \"\"\"Lazy load Arthur.\"\"\"\n    try:\n        import arthurai\n    except ImportError as e:\n        raise ImportError(\n            \"To use the ArthurCallbackHandler you need the\"\n            \" `arthurai` package. Please install it with\"\n            \" `pip install arthurai`.\",\n            e,\n        )\n    return arthurai\n[docs]class ArthurCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback Handler that logs to Arthur platform.\n    Arthur helps enterprise teams optimize model operations\n    and performance at scale. The Arthur API tracks model\n    performance, explainability, and fairness across tabular,\n    NLP, and CV models. Our API is model- and platform-agnostic,\n    and continuously scales with complex and dynamic enterprise needs.\n    To learn more about Arthur, visit our website at\n    https://www.arthur.ai/ or read the Arthur docs at\n    https://docs.arthur.ai/\n    \"\"\"\n[docs]    def __init__(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html"}
{"id": "19cd28074cbd-1", "text": "\"\"\"\n[docs]    def __init__(\n        self,\n        arthur_model: ArthurModel,\n    ) -> None:\n        \"\"\"Initialize callback handler.\"\"\"\n        super().__init__()\n        arthurai = _lazy_load_arthur()\n        Stage = arthurai.common.constants.Stage\n        ValueType = arthurai.common.constants.ValueType\n        self.arthur_model = arthur_model\n        # save the attributes of this model to be used when preparing\n        # inferences to log to Arthur in on_llm_end()\n        self.attr_names = set([a.name for a in self.arthur_model.get_attributes()])\n        self.input_attr = [\n            x\n            for x in self.arthur_model.get_attributes()\n            if x.stage == Stage.ModelPipelineInput\n            and x.value_type == ValueType.Unstructured_Text\n        ][0].name\n        self.output_attr = [\n            x\n            for x in self.arthur_model.get_attributes()\n            if x.stage == Stage.PredictedValue\n            and x.value_type == ValueType.Unstructured_Text\n        ][0].name\n        self.token_likelihood_attr = None\n        if (\n            len(\n                [\n                    x\n                    for x in self.arthur_model.get_attributes()\n                    if x.value_type == ValueType.TokenLikelihoods\n                ]\n            )\n            > 0\n        ):\n            self.token_likelihood_attr = [\n                x\n                for x in self.arthur_model.get_attributes()\n                if x.value_type == ValueType.TokenLikelihoods\n            ][0].name\n        self.run_map: DefaultDict[str, Any] = defaultdict(dict)\n[docs]    @classmethod\n    def from_credentials(\n        cls,\n        model_id: str,\n        arthur_url: Optional[str] = \"https://app.arthur.ai\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html"}
{"id": "19cd28074cbd-2", "text": "arthur_url: Optional[str] = \"https://app.arthur.ai\",\n        arthur_login: Optional[str] = None,\n        arthur_password: Optional[str] = None,\n    ) -> ArthurCallbackHandler:\n        \"\"\"Initialize callback handler from Arthur credentials.\n        Args:\n            model_id (str): The ID of the arthur model to log to.\n            arthur_url (str, optional): The URL of the Arthur instance to log to.\n                Defaults to \"https://app.arthur.ai\".\n            arthur_login (str, optional): The login to use to connect to Arthur.\n                Defaults to None.\n            arthur_password (str, optional): The password to use to connect to\n                Arthur. Defaults to None.\n        Returns:\n            ArthurCallbackHandler: The initialized callback handler.\n        \"\"\"\n        arthurai = _lazy_load_arthur()\n        ArthurAI = arthurai.ArthurAI\n        ResponseClientError = arthurai.common.exceptions.ResponseClientError\n        # connect to Arthur\n        if arthur_login is None:\n            try:\n                arthur_api_key = os.environ[\"ARTHUR_API_KEY\"]\n            except KeyError:\n                raise ValueError(\n                    \"No Arthur authentication provided. Either give\"\n                    \" a login to the ArthurCallbackHandler\"\n                    \" or set an ARTHUR_API_KEY as an environment variable.\"\n                )\n            arthur = ArthurAI(url=arthur_url, access_key=arthur_api_key)\n        else:\n            if arthur_password is None:\n                arthur = ArthurAI(url=arthur_url, login=arthur_login)\n            else:\n                arthur = ArthurAI(\n                    url=arthur_url, login=arthur_login, password=arthur_password\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html"}
{"id": "19cd28074cbd-3", "text": ")\n        # get model from Arthur by the provided model ID\n        try:\n            arthur_model = arthur.get_model(model_id)\n        except ResponseClientError:\n            raise ValueError(\n                f\"Was unable to retrieve model with id {model_id} from Arthur.\"\n                \" Make sure the ID corresponds to a model that is currently\"\n                \" registered with your Arthur account.\"\n            )\n        return cls(arthur_model)\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        \"\"\"On LLM start, save the input prompts\"\"\"\n        run_id = kwargs[\"run_id\"]\n        self.run_map[run_id][\"input_texts\"] = prompts\n        self.run_map[run_id][\"start_time\"] = time()\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"On LLM end, send data to Arthur.\"\"\"\n        try:\n            import pytz  # type: ignore[import]\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import pytz. Please install it with 'pip install pytz'.\"\n            ) from e\n        run_id = kwargs[\"run_id\"]\n        # get the run params from this run ID,\n        # or raise an error if this run ID has no corresponding metadata in self.run_map\n        try:\n            run_map_data = self.run_map[run_id]\n        except KeyError as e:\n            raise KeyError(\n                \"This function has been called with a run_id\"\n                \" that was never registered in on_llm_start().\"\n                \" Restart and try running the LLM again\"\n            ) from e", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html"}
{"id": "19cd28074cbd-4", "text": "\" Restart and try running the LLM again\"\n            ) from e\n        # mark the duration time between on_llm_start() and on_llm_end()\n        time_from_start_to_end = time() - run_map_data[\"start_time\"]\n        # create inferences to log to Arthur\n        inferences = []\n        for i, generations in enumerate(response.generations):\n            for generation in generations:\n                inference = {\n                    \"partner_inference_id\": str(uuid.uuid4()),\n                    \"inference_timestamp\": datetime.now(tz=pytz.UTC),\n                    self.input_attr: run_map_data[\"input_texts\"][i],\n                    self.output_attr: generation.text,\n                }\n                if generation.generation_info is not None:\n                    # add finish reason to the inference\n                    # if generation info contains a finish reason and\n                    # if the ArthurModel was registered to monitor finish_reason\n                    if (\n                        FINISH_REASON in generation.generation_info\n                        and FINISH_REASON in self.attr_names\n                    ):\n                        inference[FINISH_REASON] = generation.generation_info[\n                            FINISH_REASON\n                        ]\n                    # add token likelihoods data to the inference if the ArthurModel\n                    # was registered to monitor token likelihoods\n                    logprobs_data = generation.generation_info[\"logprobs\"]\n                    if (\n                        logprobs_data is not None\n                        and self.token_likelihood_attr is not None\n                    ):\n                        logprobs = logprobs_data[\"top_logprobs\"]\n                        likelihoods = [\n                            {k: np.exp(v) for k, v in logprobs[i].items()}\n                            for i in range(len(logprobs))\n                        ]\n                        inference[self.token_likelihood_attr] = likelihoods\n                # add token usage counts to the inference if the", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html"}
{"id": "19cd28074cbd-5", "text": "# add token usage counts to the inference if the\n                # ArthurModel was registered to monitor token usage\n                if (\n                    isinstance(response.llm_output, dict)\n                    and TOKEN_USAGE in response.llm_output\n                ):\n                    token_usage = response.llm_output[TOKEN_USAGE]\n                    if (\n                        PROMPT_TOKENS in token_usage\n                        and PROMPT_TOKENS in self.attr_names\n                    ):\n                        inference[PROMPT_TOKENS] = token_usage[PROMPT_TOKENS]\n                    if (\n                        COMPLETION_TOKENS in token_usage\n                        and COMPLETION_TOKENS in self.attr_names\n                    ):\n                        inference[COMPLETION_TOKENS] = token_usage[COMPLETION_TOKENS]\n                # add inference duration to the inference if the ArthurModel\n                # was registered to monitor inference duration\n                if DURATION in self.attr_names:\n                    inference[DURATION] = time_from_start_to_end\n                inferences.append(inference)\n        # send inferences to arthur\n        self.arthur_model.send_inferences(inferences)\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"On chain start, do nothing.\"\"\"\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"On chain end, do nothing.\"\"\"\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing when LLM outputs an error.\"\"\"\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"On new token, pass.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html"}
{"id": "19cd28074cbd-6", "text": "\"\"\"On new token, pass.\"\"\"\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing when LLM chain outputs an error.\"\"\"\n[docs]    def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Do nothing when tool starts.\"\"\"\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Do nothing when agent takes a specific action.\"\"\"\n[docs]    def on_tool_end(\n        self,\n        output: str,\n        observation_prefix: Optional[str] = None,\n        llm_prefix: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Do nothing when tool ends.\"\"\"\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing when tool outputs an error.\"\"\"\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        \"\"\"Do nothing\"\"\"\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        \"\"\"Do nothing\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html"}
{"id": "e6b74a744905-0", "text": "Source code for langchain.callbacks.infino_callback\nimport time\nfrom typing import Any, Dict, List, Optional, cast\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\nfrom langchain.schema.messages import BaseMessage\n[docs]def import_infino() -> Any:\n    \"\"\"Import the infino client.\"\"\"\n    try:\n        from infinopy import InfinoClient\n    except ImportError:\n        raise ImportError(\n            \"To use the Infino callbacks manager you need to have the\"\n            \" `infinopy` python package installed.\"\n            \"Please install it with `pip install infinopy`\"\n        )\n    return InfinoClient()\n[docs]def import_tiktoken() -> Any:\n    \"\"\"Import tiktoken for counting tokens for OpenAI models.\"\"\"\n    try:\n        import tiktoken\n    except ImportError:\n        raise ImportError(\n            \"To use the ChatOpenAI model with Infino callback manager, you need to \"\n            \"have the `tiktoken` python package installed.\"\n            \"Please install it with `pip install tiktoken`\"\n        )\n    return tiktoken\n[docs]def get_num_tokens(string: str, openai_model_name: str) -> int:\n    \"\"\"Calculate num tokens for OpenAI with tiktoken package.\n    Official documentation: https://github.com/openai/openai-cookbook/blob/main\n                            /examples/How_to_count_tokens_with_tiktoken.ipynb\n    \"\"\"\n    tiktoken = import_tiktoken()\n    encoding = tiktoken.encoding_for_model(openai_model_name)\n    num_tokens = len(encoding.encode(string))\n    return num_tokens\n[docs]class InfinoCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback Handler that logs to Infino.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html"}
{"id": "e6b74a744905-1", "text": "\"\"\"Callback Handler that logs to Infino.\"\"\"\n[docs]    def __init__(\n        self,\n        model_id: Optional[str] = None,\n        model_version: Optional[str] = None,\n        verbose: bool = False,\n    ) -> None:\n        # Set Infino client\n        self.client = import_infino()\n        self.model_id = model_id\n        self.model_version = model_version\n        self.verbose = verbose\n        self.is_chat_openai_model = False\n        self.chat_openai_model_name = \"gpt-3.5-turbo\"\n    def _send_to_infino(\n        self,\n        key: str,\n        value: Any,\n        is_ts: bool = True,\n    ) -> None:\n        \"\"\"Send the key-value to Infino.\n        Parameters:\n        key (str): the key to send to Infino.\n        value (Any): the value to send to Infino.\n        is_ts (bool): if True, the value is part of a time series, else it\n                      is sent as a log message.\n        \"\"\"\n        payload = {\n            \"date\": int(time.time()),\n            key: value,\n            \"labels\": {\n                \"model_id\": self.model_id,\n                \"model_version\": self.model_version,\n            },\n        }\n        if self.verbose:\n            print(f\"Tracking {key} with Infino: {payload}\")\n        # Append to Infino time series only if is_ts is True, otherwise\n        # append to Infino log.\n        if is_ts:\n            self.client.append_ts(payload)\n        else:\n            self.client.append_log(payload)\n[docs]    def on_llm_start(\n        self,\n        serialized: Dict[str, Any],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html"}
{"id": "e6b74a744905-2", "text": "self,\n        serialized: Dict[str, Any],\n        prompts: List[str],\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Log the prompts to Infino, and set start time and error flag.\"\"\"\n        for prompt in prompts:\n            self._send_to_infino(\"prompt\", prompt, is_ts=False)\n        # Set the error flag to indicate no error (this will get overridden\n        # in on_llm_error if an error occurs).\n        self.error = 0\n        # Set the start time (so that we can calculate the request\n        # duration in on_llm_end).\n        self.start_time = time.time()\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Do nothing when a new token is generated.\"\"\"\n        pass\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Log the latency, error, token usage, and response to Infino.\"\"\"\n        # Calculate and track the request latency.\n        self.end_time = time.time()\n        duration = self.end_time - self.start_time\n        self._send_to_infino(\"latency\", duration)\n        # Track success or error flag.\n        self._send_to_infino(\"error\", self.error)\n        # Track prompt response.\n        for generations in response.generations:\n            for generation in generations:\n                self._send_to_infino(\"prompt_response\", generation.text, is_ts=False)\n        # Track token usage (for non-chat models).\n        if (response.llm_output is not None) and isinstance(response.llm_output, Dict):\n            token_usage = response.llm_output[\"token_usage\"]\n            if token_usage is not None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html"}
{"id": "e6b74a744905-3", "text": "if token_usage is not None:\n                prompt_tokens = token_usage[\"prompt_tokens\"]\n                total_tokens = token_usage[\"total_tokens\"]\n                completion_tokens = token_usage[\"completion_tokens\"]\n                self._send_to_infino(\"prompt_tokens\", prompt_tokens)\n                self._send_to_infino(\"total_tokens\", total_tokens)\n                self._send_to_infino(\"completion_tokens\", completion_tokens)\n        # Track completion token usage (for openai chat models).\n        if self.is_chat_openai_model:\n            messages = \" \".join(\n                generation.message.content  # type: ignore[attr-defined]\n                for generation in generations\n            )\n            completion_tokens = get_num_tokens(\n                messages, openai_model_name=self.chat_openai_model_name\n            )\n            self._send_to_infino(\"completion_tokens\", completion_tokens)\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Set the error flag.\"\"\"\n        self.error = 1\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Do nothing when LLM chain starts.\"\"\"\n        pass\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"Do nothing when LLM chain ends.\"\"\"\n        pass\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Need to log the error.\"\"\"\n        pass\n[docs]    def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        **kwargs: Any,\n    ) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html"}
{"id": "e6b74a744905-4", "text": "input_str: str,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Do nothing when tool starts.\"\"\"\n        pass\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Do nothing when agent takes a specific action.\"\"\"\n        pass\n[docs]    def on_tool_end(\n        self,\n        output: str,\n        observation_prefix: Optional[str] = None,\n        llm_prefix: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Do nothing when tool ends.\"\"\"\n        pass\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing when tool outputs an error.\"\"\"\n        pass\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        \"\"\"Do nothing.\"\"\"\n        pass\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        \"\"\"Do nothing.\"\"\"\n        pass\n[docs]    def on_chat_model_start(\n        self,\n        serialized: Dict[str, Any],\n        messages: List[List[BaseMessage]],\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when LLM starts running.\"\"\"\n        # Currently, for chat models, we only support input prompts for ChatOpenAI.\n        # Check if this model is a ChatOpenAI model.\n        values = serialized.get(\"id\")\n        if values:\n            for value in values:\n                if value == \"ChatOpenAI\":\n                    self.is_chat_openai_model = True\n                    break\n        # Track prompt tokens for ChatOpenAI model.\n        if self.is_chat_openai_model:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html"}
{"id": "e6b74a744905-5", "text": "if self.is_chat_openai_model:\n            invocation_params = kwargs.get(\"invocation_params\")\n            if invocation_params:\n                model_name = invocation_params.get(\"model_name\")\n                if model_name:\n                    self.chat_openai_model_name = model_name\n                    prompt_tokens = 0\n                    for message_list in messages:\n                        message_string = \" \".join(\n                            cast(str, msg.content) for msg in message_list\n                        )\n                        num_tokens = get_num_tokens(\n                            message_string,\n                            openai_model_name=self.chat_openai_model_name,\n                        )\n                        prompt_tokens += num_tokens\n                    self._send_to_infino(\"prompt_tokens\", prompt_tokens)\n        if self.verbose:\n            print(\n                f\"on_chat_model_start: is_chat_openai_model= \\\n                  {self.is_chat_openai_model}, \\\n                  chat_openai_model_name={self.chat_openai_model_name}\"\n            )\n        # Send the prompt to infino\n        prompt = \" \".join(\n            cast(str, msg.content) for sublist in messages for msg in sublist\n        )\n        self._send_to_infino(\"prompt\", prompt, is_ts=False)\n        # Set the error flag to indicate no error (this will get overridden\n        # in on_llm_error if an error occurs).\n        self.error = 0\n        # Set the start time (so that we can calculate the request\n        # duration in on_llm_end).\n        self.start_time = time.time()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html"}
{"id": "326a10395acf-0", "text": "Source code for langchain.callbacks.argilla_callback\nimport os\nimport warnings\nfrom typing import Any, Dict, List, Optional\nfrom packaging.version import parse\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\n[docs]class ArgillaCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback Handler that logs into Argilla.\n    Args:\n        dataset_name: name of the `FeedbackDataset` in Argilla. Note that it must\n            exist in advance. If you need help on how to create a `FeedbackDataset` in\n            Argilla, please visit\n            https://docs.argilla.io/en/latest/guides/llms/practical_guides/use_argilla_callback_in_langchain.html.\n        workspace_name: name of the workspace in Argilla where the specified\n            `FeedbackDataset` lives in. Defaults to `None`, which means that the\n            default workspace will be used.\n        api_url: URL of the Argilla Server that we want to use, and where the\n            `FeedbackDataset` lives in. Defaults to `None`, which means that either\n            `ARGILLA_API_URL` environment variable or the default will be used.\n        api_key: API Key to connect to the Argilla Server. Defaults to `None`, which\n            means that either `ARGILLA_API_KEY` environment variable or the default\n            will be used.\n    Raises:\n        ImportError: if the `argilla` package is not installed.\n        ConnectionError: if the connection to Argilla fails.\n        FileNotFoundError: if the `FeedbackDataset` retrieval from Argilla fails.\n    Examples:\n        >>> from langchain.llms import OpenAI\n        >>> from langchain.callbacks import ArgillaCallbackHandler\n        >>> argilla_callback = ArgillaCallbackHandler(\n        ...     dataset_name=\"my-dataset\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html"}
{"id": "326a10395acf-1", "text": "...     dataset_name=\"my-dataset\",\n        ...     workspace_name=\"my-workspace\",\n        ...     api_url=\"http://localhost:6900\",\n        ...     api_key=\"argilla.apikey\",\n        ... )\n        >>> llm = OpenAI(\n        ...     temperature=0,\n        ...     callbacks=[argilla_callback],\n        ...     verbose=True,\n        ...     openai_api_key=\"API_KEY_HERE\",\n        ... )\n        >>> llm.generate([\n        ...     \"What is the best NLP-annotation tool out there? (no bias at all)\",\n        ... ])\n        \"Argilla, no doubt about it.\"\n    \"\"\"\n    REPO_URL: str = \"https://github.com/argilla-io/argilla\"\n    ISSUES_URL: str = f\"{REPO_URL}/issues\"\n    BLOG_URL: str = \"https://docs.argilla.io/en/latest/guides/llms/practical_guides/use_argilla_callback_in_langchain.html\"  # noqa: E501\n    DEFAULT_API_URL: str = \"http://localhost:6900\"\n[docs]    def __init__(\n        self,\n        dataset_name: str,\n        workspace_name: Optional[str] = None,\n        api_url: Optional[str] = None,\n        api_key: Optional[str] = None,\n    ) -> None:\n        \"\"\"Initializes the `ArgillaCallbackHandler`.\n        Args:\n            dataset_name: name of the `FeedbackDataset` in Argilla. Note that it must\n                exist in advance. If you need help on how to create a `FeedbackDataset`\n                in Argilla, please visit\n                https://docs.argilla.io/en/latest/guides/llms/practical_guides/use_argilla_callback_in_langchain.html.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html"}
{"id": "326a10395acf-2", "text": "workspace_name: name of the workspace in Argilla where the specified\n                `FeedbackDataset` lives in. Defaults to `None`, which means that the\n                default workspace will be used.\n            api_url: URL of the Argilla Server that we want to use, and where the\n                `FeedbackDataset` lives in. Defaults to `None`, which means that either\n                `ARGILLA_API_URL` environment variable or the default will be used.\n            api_key: API Key to connect to the Argilla Server. Defaults to `None`, which\n                means that either `ARGILLA_API_KEY` environment variable or the default\n                will be used.\n        Raises:\n            ImportError: if the `argilla` package is not installed.\n            ConnectionError: if the connection to Argilla fails.\n            FileNotFoundError: if the `FeedbackDataset` retrieval from Argilla fails.\n        \"\"\"\n        super().__init__()\n        # Import Argilla (not via `import_argilla` to keep hints in IDEs)\n        try:\n            import argilla as rg  # noqa: F401\n            self.ARGILLA_VERSION = rg.__version__\n        except ImportError:\n            raise ImportError(\n                \"To use the Argilla callback manager you need to have the `argilla` \"\n                \"Python package installed. Please install it with `pip install argilla`\"\n            )\n        # Check whether the Argilla version is compatible\n        if parse(self.ARGILLA_VERSION) < parse(\"1.8.0\"):\n            raise ImportError(\n                f\"The installed `argilla` version is {self.ARGILLA_VERSION} but \"\n                \"`ArgillaCallbackHandler` requires at least version 1.8.0. Please \"\n                \"upgrade `argilla` with `pip install --upgrade argilla`.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html"}
{"id": "326a10395acf-3", "text": ")\n        # Show a warning message if Argilla will assume the default values will be used\n        if api_url is None and os.getenv(\"ARGILLA_API_URL\") is None:\n            warnings.warn(\n                (\n                    \"Since `api_url` is None, and the env var `ARGILLA_API_URL` is not\"\n                    f\" set, it will default to `{self.DEFAULT_API_URL}`, which is the\"\n                    \" default API URL in Argilla Quickstart.\"\n                ),\n            )\n            api_url = self.DEFAULT_API_URL\n        if api_key is None and os.getenv(\"ARGILLA_API_KEY\") is None:\n            self.DEFAULT_API_KEY = (\n                \"admin.apikey\"\n                if parse(self.ARGILLA_VERSION) < parse(\"1.11.0\")\n                else \"owner.apikey\"\n            )\n            warnings.warn(\n                (\n                    \"Since `api_key` is None, and the env var `ARGILLA_API_KEY` is not\"\n                    f\" set, it will default to `{self.DEFAULT_API_KEY}`, which is the\"\n                    \" default API key in Argilla Quickstart.\"\n                ),\n            )\n            api_url = self.DEFAULT_API_URL\n        # Connect to Argilla with the provided credentials, if applicable\n        try:\n            rg.init(api_key=api_key, api_url=api_url)\n        except Exception as e:\n            raise ConnectionError(\n                f\"Could not connect to Argilla with exception: '{e}'.\\n\"\n                \"Please check your `api_key` and `api_url`, and make sure that \"\n                \"the Argilla server is up and running. If the problem persists \"\n                f\"please report it to {self.ISSUES_URL} as an `integration` issue.\"\n            ) from e\n        # Set the Argilla variables", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html"}
{"id": "326a10395acf-4", "text": ") from e\n        # Set the Argilla variables\n        self.dataset_name = dataset_name\n        self.workspace_name = workspace_name or rg.get_workspace()\n        # Retrieve the `FeedbackDataset` from Argilla (without existing records)\n        try:\n            extra_args = {}\n            if parse(self.ARGILLA_VERSION) < parse(\"1.14.0\"):\n                warnings.warn(\n                    f\"You have Argilla {self.ARGILLA_VERSION}, but Argilla 1.14.0 or\"\n                    \" higher is recommended.\",\n                    UserWarning,\n                )\n                extra_args = {\"with_records\": False}\n            self.dataset = rg.FeedbackDataset.from_argilla(\n                name=self.dataset_name,\n                workspace=self.workspace_name,\n                **extra_args,\n            )\n        except Exception as e:\n            raise FileNotFoundError(\n                f\"`FeedbackDataset` retrieval from Argilla failed with exception `{e}`.\"\n                f\"\\nPlease check that the dataset with name={self.dataset_name} in the\"\n                f\" workspace={self.workspace_name} exists in advance. If you need help\"\n                \" on how to create a `langchain`-compatible `FeedbackDataset` in\"\n                f\" Argilla, please visit {self.BLOG_URL}. If the problem persists\"\n                f\" please report it to {self.ISSUES_URL} as an `integration` issue.\"\n            ) from e\n        supported_fields = [\"prompt\", \"response\"]\n        if supported_fields != [field.name for field in self.dataset.fields]:\n            raise ValueError(\n                f\"`FeedbackDataset` with name={self.dataset_name} in the workspace=\"\n                f\"{self.workspace_name} had fields that are not supported yet for the\"\n                f\"`langchain` integration. Supported fields are: {supported_fields},\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html"}
{"id": "326a10395acf-5", "text": "f\"`langchain` integration. Supported fields are: {supported_fields},\"\n                f\" and the current `FeedbackDataset` fields are {[field.name for field in self.dataset.fields]}.\"  # noqa: E501\n                \" For more information on how to create a `langchain`-compatible\"\n                f\" `FeedbackDataset` in Argilla, please visit {self.BLOG_URL}.\"\n            )\n        self.prompts: Dict[str, List[str]] = {}\n        warnings.warn(\n            (\n                \"The `ArgillaCallbackHandler` is currently in beta and is subject to\"\n                \" change based on updates to `langchain`. Please report any issues to\"\n                f\" {self.ISSUES_URL} as an `integration` issue.\"\n            ),\n        )\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        \"\"\"Save the prompts in memory when an LLM starts.\"\"\"\n        self.prompts.update({str(kwargs[\"parent_run_id\"] or kwargs[\"run_id\"]): prompts})\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Do nothing when a new token is generated.\"\"\"\n        pass\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Log records to Argilla when an LLM ends.\"\"\"\n        # Do nothing if there's a parent_run_id, since we will log the records when\n        # the chain ends\n        if kwargs[\"parent_run_id\"]:\n            return\n        # Creates the records and adds them to the `FeedbackDataset`\n        prompts = self.prompts[str(kwargs[\"run_id\"])]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html"}
{"id": "326a10395acf-6", "text": "prompts = self.prompts[str(kwargs[\"run_id\"])]\n        for prompt, generations in zip(prompts, response.generations):\n            self.dataset.add_records(\n                records=[\n                    {\n                        \"fields\": {\n                            \"prompt\": prompt,\n                            \"response\": generation.text.strip(),\n                        },\n                    }\n                    for generation in generations\n                ]\n            )\n        # Pop current run from `self.runs`\n        self.prompts.pop(str(kwargs[\"run_id\"]))\n        if parse(self.ARGILLA_VERSION) < parse(\"1.14.0\"):\n            # Push the records to Argilla\n            self.dataset.push_to_argilla()\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing when LLM outputs an error.\"\"\"\n        pass\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"If the key `input` is in `inputs`, then save it in `self.prompts` using\n        either the `parent_run_id` or the `run_id` as the key. This is done so that\n        we don't log the same input prompt twice, once when the LLM starts and once\n        when the chain starts.\n        \"\"\"\n        if \"input\" in inputs:\n            self.prompts.update(\n                {\n                    str(kwargs[\"parent_run_id\"] or kwargs[\"run_id\"]): (\n                        inputs[\"input\"]\n                        if isinstance(inputs[\"input\"], list)\n                        else [inputs[\"input\"]]\n                    )\n                }\n            )\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html"}
{"id": "326a10395acf-7", "text": "\"\"\"If either the `parent_run_id` or the `run_id` is in `self.prompts`, then\n        log the outputs to Argilla, and pop the run from `self.prompts`. The behavior\n        differs if the output is a list or not.\n        \"\"\"\n        if not any(\n            key in self.prompts\n            for key in [str(kwargs[\"parent_run_id\"]), str(kwargs[\"run_id\"])]\n        ):\n            return\n        prompts = self.prompts.get(str(kwargs[\"parent_run_id\"])) or self.prompts.get(\n            str(kwargs[\"run_id\"])\n        )\n        for chain_output_key, chain_output_val in outputs.items():\n            if isinstance(chain_output_val, list):\n                # Creates the records and adds them to the `FeedbackDataset`\n                self.dataset.add_records(\n                    records=[\n                        {\n                            \"fields\": {\n                                \"prompt\": prompt,\n                                \"response\": output[\"text\"].strip(),\n                            },\n                        }\n                        for prompt, output in zip(\n                            prompts,  # type: ignore\n                            chain_output_val,\n                        )\n                    ]\n                )\n            else:\n                # Creates the records and adds them to the `FeedbackDataset`\n                self.dataset.add_records(\n                    records=[\n                        {\n                            \"fields\": {\n                                \"prompt\": \" \".join(prompts),  # type: ignore\n                                \"response\": chain_output_val.strip(),\n                            },\n                        }\n                    ]\n                )\n        # Pop current run from `self.runs`\n        if str(kwargs[\"parent_run_id\"]) in self.prompts:\n            self.prompts.pop(str(kwargs[\"parent_run_id\"]))\n        if str(kwargs[\"run_id\"]) in self.prompts:\n            self.prompts.pop(str(kwargs[\"run_id\"]))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html"}
{"id": "326a10395acf-8", "text": "self.prompts.pop(str(kwargs[\"run_id\"]))\n        if parse(self.ARGILLA_VERSION) < parse(\"1.14.0\"):\n            # Push the records to Argilla\n            self.dataset.push_to_argilla()\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing when LLM chain outputs an error.\"\"\"\n        pass\n[docs]    def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Do nothing when tool starts.\"\"\"\n        pass\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Do nothing when agent takes a specific action.\"\"\"\n        pass\n[docs]    def on_tool_end(\n        self,\n        output: str,\n        observation_prefix: Optional[str] = None,\n        llm_prefix: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Do nothing when tool ends.\"\"\"\n        pass\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing when tool outputs an error.\"\"\"\n        pass\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        \"\"\"Do nothing\"\"\"\n        pass\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        \"\"\"Do nothing\"\"\"\n        pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html"}
{"id": "8a7e2f463460-0", "text": "Source code for langchain.callbacks.comet_ml_callback\nimport tempfile\nfrom copy import deepcopy\nfrom pathlib import Path\nfrom typing import Any, Callable, Dict, List, Optional, Sequence\nimport langchain\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.callbacks.utils import (\n    BaseMetadataCallbackHandler,\n    flatten_dict,\n    import_pandas,\n    import_spacy,\n    import_textstat,\n)\nfrom langchain.schema import AgentAction, AgentFinish, Generation, LLMResult\nLANGCHAIN_MODEL_NAME = \"langchain-model\"\n[docs]def import_comet_ml() -> Any:\n    \"\"\"Import comet_ml and raise an error if it is not installed.\"\"\"\n    try:\n        import comet_ml  # noqa: F401\n    except ImportError:\n        raise ImportError(\n            \"To use the comet_ml callback manager you need to have the \"\n            \"`comet_ml` python package installed. Please install it with\"\n            \" `pip install comet_ml`\"\n        )\n    return comet_ml\ndef _get_experiment(\n    workspace: Optional[str] = None, project_name: Optional[str] = None\n) -> Any:\n    comet_ml = import_comet_ml()\n    experiment = comet_ml.Experiment(  # type: ignore\n        workspace=workspace,\n        project_name=project_name,\n    )\n    return experiment\ndef _fetch_text_complexity_metrics(text: str) -> dict:\n    textstat = import_textstat()\n    text_complexity_metrics = {\n        \"flesch_reading_ease\": textstat.flesch_reading_ease(text),\n        \"flesch_kincaid_grade\": textstat.flesch_kincaid_grade(text),\n        \"smog_index\": textstat.smog_index(text),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-1", "text": "\"smog_index\": textstat.smog_index(text),\n        \"coleman_liau_index\": textstat.coleman_liau_index(text),\n        \"automated_readability_index\": textstat.automated_readability_index(text),\n        \"dale_chall_readability_score\": textstat.dale_chall_readability_score(text),\n        \"difficult_words\": textstat.difficult_words(text),\n        \"linsear_write_formula\": textstat.linsear_write_formula(text),\n        \"gunning_fog\": textstat.gunning_fog(text),\n        \"text_standard\": textstat.text_standard(text),\n        \"fernandez_huerta\": textstat.fernandez_huerta(text),\n        \"szigriszt_pazos\": textstat.szigriszt_pazos(text),\n        \"gutierrez_polini\": textstat.gutierrez_polini(text),\n        \"crawford\": textstat.crawford(text),\n        \"gulpease_index\": textstat.gulpease_index(text),\n        \"osman\": textstat.osman(text),\n    }\n    return text_complexity_metrics\ndef _summarize_metrics_for_generated_outputs(metrics: Sequence) -> dict:\n    pd = import_pandas()\n    metrics_df = pd.DataFrame(metrics)\n    metrics_summary = metrics_df.describe()\n    return metrics_summary.to_dict()\n[docs]class CometCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):\n    \"\"\"Callback Handler that logs to Comet.\n    Parameters:\n        job_type (str): The type of comet_ml task such as \"inference\",\n            \"testing\" or \"qc\"\n        project_name (str): The comet_ml project name\n        tags (list): Tags to add to the task\n        task_name (str): Name of the comet_ml task", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-2", "text": "task_name (str): Name of the comet_ml task\n        visualize (bool): Whether to visualize the run.\n        complexity_metrics (bool): Whether to log complexity metrics\n        stream_logs (bool): Whether to stream callback actions to Comet\n    This handler will utilize the associated callback method and formats\n    the input of each callback function with metadata regarding the state of LLM run,\n    and adds the response to the list of records for both the {method}_records and\n    action. It then logs the response to Comet.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        task_type: Optional[str] = \"inference\",\n        workspace: Optional[str] = None,\n        project_name: Optional[str] = None,\n        tags: Optional[Sequence] = None,\n        name: Optional[str] = None,\n        visualizations: Optional[List[str]] = None,\n        complexity_metrics: bool = False,\n        custom_metrics: Optional[Callable] = None,\n        stream_logs: bool = True,\n    ) -> None:\n        \"\"\"Initialize callback handler.\"\"\"\n        self.comet_ml = import_comet_ml()\n        super().__init__()\n        self.task_type = task_type\n        self.workspace = workspace\n        self.project_name = project_name\n        self.tags = tags\n        self.visualizations = visualizations\n        self.complexity_metrics = complexity_metrics\n        self.custom_metrics = custom_metrics\n        self.stream_logs = stream_logs\n        self.temp_dir = tempfile.TemporaryDirectory()\n        self.experiment = _get_experiment(workspace, project_name)\n        self.experiment.log_other(\"Created from\", \"langchain\")\n        if tags:\n            self.experiment.add_tags(tags)\n        self.name = name\n        if self.name:\n            self.experiment.set_name(self.name)\n        warning = (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-3", "text": "self.experiment.set_name(self.name)\n        warning = (\n            \"The comet_ml callback is currently in beta and is subject to change \"\n            \"based on updates to `langchain`. Please report any issues to \"\n            \"https://github.com/comet-ml/issue-tracking/issues with the tag \"\n            \"`langchain`.\"\n        )\n        self.comet_ml.LOGGER.warning(warning)\n        self.callback_columns: list = []\n        self.action_records: list = []\n        self.complexity_metrics = complexity_metrics\n        if self.visualizations:\n            spacy = import_spacy()\n            self.nlp = spacy.load(\"en_core_web_sm\")\n        else:\n            self.nlp = None\n    def _init_resp(self) -> Dict:\n        return {k: None for k in self.callback_columns}\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when LLM starts.\"\"\"\n        self.step += 1\n        self.llm_starts += 1\n        self.starts += 1\n        metadata = self._init_resp()\n        metadata.update({\"action\": \"on_llm_start\"})\n        metadata.update(flatten_dict(serialized))\n        metadata.update(self.get_custom_callback_meta())\n        for prompt in prompts:\n            prompt_resp = deepcopy(metadata)\n            prompt_resp[\"prompts\"] = prompt\n            self.on_llm_start_records.append(prompt_resp)\n            self.action_records.append(prompt_resp)\n            if self.stream_logs:\n                self._log_stream(prompt, metadata, self.step)\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Run when LLM generates a new token.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-4", "text": "\"\"\"Run when LLM generates a new token.\"\"\"\n        self.step += 1\n        self.llm_streams += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_llm_new_token\", \"token\": token})\n        resp.update(self.get_custom_callback_meta())\n        self.action_records.append(resp)\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Run when LLM ends running.\"\"\"\n        self.step += 1\n        self.llm_ends += 1\n        self.ends += 1\n        metadata = self._init_resp()\n        metadata.update({\"action\": \"on_llm_end\"})\n        metadata.update(flatten_dict(response.llm_output or {}))\n        metadata.update(self.get_custom_callback_meta())\n        output_complexity_metrics = []\n        output_custom_metrics = []\n        for prompt_idx, generations in enumerate(response.generations):\n            for gen_idx, generation in enumerate(generations):\n                text = generation.text\n                generation_resp = deepcopy(metadata)\n                generation_resp.update(flatten_dict(generation.dict()))\n                complexity_metrics = self._get_complexity_metrics(text)\n                if complexity_metrics:\n                    output_complexity_metrics.append(complexity_metrics)\n                    generation_resp.update(complexity_metrics)\n                custom_metrics = self._get_custom_metrics(\n                    generation, prompt_idx, gen_idx\n                )\n                if custom_metrics:\n                    output_custom_metrics.append(custom_metrics)\n                    generation_resp.update(custom_metrics)\n                if self.stream_logs:\n                    self._log_stream(text, metadata, self.step)\n                self.action_records.append(generation_resp)\n                self.on_llm_end_records.append(generation_resp)\n        self._log_text_metrics(output_complexity_metrics, step=self.step)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-5", "text": "self._log_text_metrics(output_complexity_metrics, step=self.step)\n        self._log_text_metrics(output_custom_metrics, step=self.step)\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when LLM errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when chain starts running.\"\"\"\n        self.step += 1\n        self.chain_starts += 1\n        self.starts += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_chain_start\"})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.get_custom_callback_meta())\n        for chain_input_key, chain_input_val in inputs.items():\n            if isinstance(chain_input_val, str):\n                input_resp = deepcopy(resp)\n                if self.stream_logs:\n                    self._log_stream(chain_input_val, resp, self.step)\n                input_resp.update({chain_input_key: chain_input_val})\n                self.action_records.append(input_resp)\n            else:\n                self.comet_ml.LOGGER.warning(\n                    f\"Unexpected data format provided! \"\n                    f\"Input Value for {chain_input_key} will not be logged\"\n                )\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"Run when chain ends running.\"\"\"\n        self.step += 1\n        self.chain_ends += 1\n        self.ends += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_chain_end\"})\n        resp.update(self.get_custom_callback_meta())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-6", "text": "resp.update(self.get_custom_callback_meta())\n        for chain_output_key, chain_output_val in outputs.items():\n            if isinstance(chain_output_val, str):\n                output_resp = deepcopy(resp)\n                if self.stream_logs:\n                    self._log_stream(chain_output_val, resp, self.step)\n                output_resp.update({chain_output_key: chain_output_val})\n                self.action_records.append(output_resp)\n            else:\n                self.comet_ml.LOGGER.warning(\n                    f\"Unexpected data format provided! \"\n                    f\"Output Value for {chain_output_key} will not be logged\"\n                )\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when chain errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_tool_start(\n        self, serialized: Dict[str, Any], input_str: str, **kwargs: Any\n    ) -> None:\n        \"\"\"Run when tool starts running.\"\"\"\n        self.step += 1\n        self.tool_starts += 1\n        self.starts += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_tool_start\"})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.get_custom_callback_meta())\n        if self.stream_logs:\n            self._log_stream(input_str, resp, self.step)\n        resp.update({\"input_str\": input_str})\n        self.action_records.append(resp)\n[docs]    def on_tool_end(self, output: str, **kwargs: Any) -> None:\n        \"\"\"Run when tool ends running.\"\"\"\n        self.step += 1\n        self.tool_ends += 1\n        self.ends += 1\n        resp = self._init_resp()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-7", "text": "self.ends += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_tool_end\"})\n        resp.update(self.get_custom_callback_meta())\n        if self.stream_logs:\n            self._log_stream(output, resp, self.step)\n        resp.update({\"output\": output})\n        self.action_records.append(resp)\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when tool errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        \"\"\"\n        Run when agent is ending.\n        \"\"\"\n        self.step += 1\n        self.text_ctr += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_text\"})\n        resp.update(self.get_custom_callback_meta())\n        if self.stream_logs:\n            self._log_stream(text, resp, self.step)\n        resp.update({\"text\": text})\n        self.action_records.append(resp)\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        \"\"\"Run when agent ends running.\"\"\"\n        self.step += 1\n        self.agent_ends += 1\n        self.ends += 1\n        resp = self._init_resp()\n        output = finish.return_values[\"output\"]\n        log = finish.log\n        resp.update({\"action\": \"on_agent_finish\", \"log\": log})\n        resp.update(self.get_custom_callback_meta())\n        if self.stream_logs:\n            self._log_stream(output, resp, self.step)\n        resp.update({\"output\": output})\n        self.action_records.append(resp)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-8", "text": "resp.update({\"output\": output})\n        self.action_records.append(resp)\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Run on agent action.\"\"\"\n        self.step += 1\n        self.tool_starts += 1\n        self.starts += 1\n        tool = action.tool\n        tool_input = str(action.tool_input)\n        log = action.log\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_agent_action\", \"log\": log, \"tool\": tool})\n        resp.update(self.get_custom_callback_meta())\n        if self.stream_logs:\n            self._log_stream(tool_input, resp, self.step)\n        resp.update({\"tool_input\": tool_input})\n        self.action_records.append(resp)\n    def _get_complexity_metrics(self, text: str) -> dict:\n        \"\"\"Compute text complexity metrics using textstat.\n        Parameters:\n            text (str): The text to analyze.\n        Returns:\n            (dict): A dictionary containing the complexity metrics.\n        \"\"\"\n        resp = {}\n        if self.complexity_metrics:\n            text_complexity_metrics = _fetch_text_complexity_metrics(text)\n            resp.update(text_complexity_metrics)\n        return resp\n    def _get_custom_metrics(\n        self, generation: Generation, prompt_idx: int, gen_idx: int\n    ) -> dict:\n        \"\"\"Compute Custom Metrics for an LLM Generated Output\n        Args:\n            generation (LLMResult): Output generation from an LLM\n            prompt_idx (int): List index of the input prompt\n            gen_idx (int): List index of the generated output\n        Returns:\n            dict: A dictionary containing the custom metrics.\n        \"\"\"\n        resp = {}\n        if self.custom_metrics:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-9", "text": "\"\"\"\n        resp = {}\n        if self.custom_metrics:\n            custom_metrics = self.custom_metrics(generation, prompt_idx, gen_idx)\n            resp.update(custom_metrics)\n        return resp\n[docs]    def flush_tracker(\n        self,\n        langchain_asset: Any = None,\n        task_type: Optional[str] = \"inference\",\n        workspace: Optional[str] = None,\n        project_name: Optional[str] = \"comet-langchain-demo\",\n        tags: Optional[Sequence] = None,\n        name: Optional[str] = None,\n        visualizations: Optional[List[str]] = None,\n        complexity_metrics: bool = False,\n        custom_metrics: Optional[Callable] = None,\n        finish: bool = False,\n        reset: bool = False,\n    ) -> None:\n        \"\"\"Flush the tracker and setup the session.\n        Everything after this will be a new table.\n        Args:\n            name: Name of the performed session so far so it is identifiable\n            langchain_asset: The langchain asset to save.\n            finish: Whether to finish the run.\n            Returns:\n                None\n        \"\"\"\n        self._log_session(langchain_asset)\n        if langchain_asset:\n            try:\n                self._log_model(langchain_asset)\n            except Exception:\n                self.comet_ml.LOGGER.error(\n                    \"Failed to export agent or LLM to Comet\",\n                    exc_info=True,\n                    extra={\"show_traceback\": True},\n                )\n        if finish:\n            self.experiment.end()\n        if reset:\n            self._reset(\n                task_type,\n                workspace,\n                project_name,\n                tags,\n                name,\n                visualizations,\n                complexity_metrics,\n                custom_metrics,\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-10", "text": "visualizations,\n                complexity_metrics,\n                custom_metrics,\n            )\n    def _log_stream(self, prompt: str, metadata: dict, step: int) -> None:\n        self.experiment.log_text(prompt, metadata=metadata, step=step)\n    def _log_model(self, langchain_asset: Any) -> None:\n        model_parameters = self._get_llm_parameters(langchain_asset)\n        self.experiment.log_parameters(model_parameters, prefix=\"model\")\n        langchain_asset_path = Path(self.temp_dir.name, \"model.json\")\n        model_name = self.name if self.name else LANGCHAIN_MODEL_NAME\n        try:\n            if hasattr(langchain_asset, \"save\"):\n                langchain_asset.save(langchain_asset_path)\n                self.experiment.log_model(model_name, str(langchain_asset_path))\n        except (ValueError, AttributeError, NotImplementedError) as e:\n            if hasattr(langchain_asset, \"save_agent\"):\n                langchain_asset.save_agent(langchain_asset_path)\n                self.experiment.log_model(model_name, str(langchain_asset_path))\n            else:\n                self.comet_ml.LOGGER.error(\n                    f\"{e}\"\n                    \" Could not save Langchain Asset \"\n                    f\"for {langchain_asset.__class__.__name__}\"\n                )\n    def _log_session(self, langchain_asset: Optional[Any] = None) -> None:\n        try:\n            llm_session_df = self._create_session_analysis_dataframe(langchain_asset)\n            # Log the cleaned dataframe as a table\n            self.experiment.log_table(\"langchain-llm-session.csv\", llm_session_df)\n        except Exception:\n            self.comet_ml.LOGGER.warning(\n                \"Failed to log session data to Comet\",\n                exc_info=True,\n                extra={\"show_traceback\": True},\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-11", "text": "exc_info=True,\n                extra={\"show_traceback\": True},\n            )\n        try:\n            metadata = {\"langchain_version\": str(langchain.__version__)}\n            # Log the langchain low-level records as a JSON file directly\n            self.experiment.log_asset_data(\n                self.action_records, \"langchain-action_records.json\", metadata=metadata\n            )\n        except Exception:\n            self.comet_ml.LOGGER.warning(\n                \"Failed to log session data to Comet\",\n                exc_info=True,\n                extra={\"show_traceback\": True},\n            )\n        try:\n            self._log_visualizations(llm_session_df)\n        except Exception:\n            self.comet_ml.LOGGER.warning(\n                \"Failed to log visualizations to Comet\",\n                exc_info=True,\n                extra={\"show_traceback\": True},\n            )\n    def _log_text_metrics(self, metrics: Sequence[dict], step: int) -> None:\n        if not metrics:\n            return\n        metrics_summary = _summarize_metrics_for_generated_outputs(metrics)\n        for key, value in metrics_summary.items():\n            self.experiment.log_metrics(value, prefix=key, step=step)\n    def _log_visualizations(self, session_df: Any) -> None:\n        if not (self.visualizations and self.nlp):\n            return\n        spacy = import_spacy()\n        prompts = session_df[\"prompts\"].tolist()\n        outputs = session_df[\"text\"].tolist()\n        for idx, (prompt, output) in enumerate(zip(prompts, outputs)):\n            doc = self.nlp(output)\n            sentence_spans = list(doc.sents)\n            for visualization in self.visualizations:\n                try:\n                    html = spacy.displacy.render(\n                        sentence_spans,\n                        style=visualization,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-12", "text": "sentence_spans,\n                        style=visualization,\n                        options={\"compact\": True},\n                        jupyter=False,\n                        page=True,\n                    )\n                    self.experiment.log_asset_data(\n                        html,\n                        name=f\"langchain-viz-{visualization}-{idx}.html\",\n                        metadata={\"prompt\": prompt},\n                        step=idx,\n                    )\n                except Exception as e:\n                    self.comet_ml.LOGGER.warning(\n                        e, exc_info=True, extra={\"show_traceback\": True}\n                    )\n        return\n    def _reset(\n        self,\n        task_type: Optional[str] = None,\n        workspace: Optional[str] = None,\n        project_name: Optional[str] = None,\n        tags: Optional[Sequence] = None,\n        name: Optional[str] = None,\n        visualizations: Optional[List[str]] = None,\n        complexity_metrics: bool = False,\n        custom_metrics: Optional[Callable] = None,\n    ) -> None:\n        _task_type = task_type if task_type else self.task_type\n        _workspace = workspace if workspace else self.workspace\n        _project_name = project_name if project_name else self.project_name\n        _tags = tags if tags else self.tags\n        _name = name if name else self.name\n        _visualizations = visualizations if visualizations else self.visualizations\n        _complexity_metrics = (\n            complexity_metrics if complexity_metrics else self.complexity_metrics\n        )\n        _custom_metrics = custom_metrics if custom_metrics else self.custom_metrics\n        self.__init__(  # type: ignore\n            task_type=_task_type,\n            workspace=_workspace,\n            project_name=_project_name,\n            tags=_tags,\n            name=_name,\n            visualizations=_visualizations,\n            complexity_metrics=_complexity_metrics,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-13", "text": "visualizations=_visualizations,\n            complexity_metrics=_complexity_metrics,\n            custom_metrics=_custom_metrics,\n        )\n        self.reset_callback_meta()\n        self.temp_dir = tempfile.TemporaryDirectory()\n    def _create_session_analysis_dataframe(self, langchain_asset: Any = None) -> dict:\n        pd = import_pandas()\n        llm_parameters = self._get_llm_parameters(langchain_asset)\n        num_generations_per_prompt = llm_parameters.get(\"n\", 1)\n        llm_start_records_df = pd.DataFrame(self.on_llm_start_records)\n        # Repeat each input row based on the number of outputs generated per prompt\n        llm_start_records_df = llm_start_records_df.loc[\n            llm_start_records_df.index.repeat(num_generations_per_prompt)\n        ].reset_index(drop=True)\n        llm_end_records_df = pd.DataFrame(self.on_llm_end_records)\n        llm_session_df = pd.merge(\n            llm_start_records_df,\n            llm_end_records_df,\n            left_index=True,\n            right_index=True,\n            suffixes=[\"_llm_start\", \"_llm_end\"],\n        )\n        return llm_session_df\n    def _get_llm_parameters(self, langchain_asset: Any = None) -> dict:\n        if not langchain_asset:\n            return {}\n        try:\n            if hasattr(langchain_asset, \"agent\"):\n                llm_parameters = langchain_asset.agent.llm_chain.llm.dict()\n            elif hasattr(langchain_asset, \"llm_chain\"):\n                llm_parameters = langchain_asset.llm_chain.llm.dict()\n            elif hasattr(langchain_asset, \"llm\"):\n                llm_parameters = langchain_asset.llm.dict()\n            else:\n                llm_parameters = langchain_asset.dict()\n        except Exception:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "8a7e2f463460-14", "text": "else:\n                llm_parameters = langchain_asset.dict()\n        except Exception:\n            return {}\n        return llm_parameters", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html"}
{"id": "056dc66a5e10-0", "text": "Source code for langchain.callbacks.whylabs_callback\nfrom __future__ import annotations\nimport logging\nfrom typing import TYPE_CHECKING, Any, Optional\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.utils import get_from_env\nif TYPE_CHECKING:\n    from whylogs.api.logger.logger import Logger\ndiagnostic_logger = logging.getLogger(__name__)\n[docs]def import_langkit(\n    sentiment: bool = False,\n    toxicity: bool = False,\n    themes: bool = False,\n) -> Any:\n    \"\"\"Import the langkit python package and raise an error if it is not installed.\n    Args:\n        sentiment: Whether to import the langkit.sentiment module. Defaults to False.\n        toxicity: Whether to import the langkit.toxicity module. Defaults to False.\n        themes: Whether to import the langkit.themes module. Defaults to False.\n    Returns:\n        The imported langkit module.\n    \"\"\"\n    try:\n        import langkit  # noqa: F401\n        import langkit.regexes  # noqa: F401\n        import langkit.textstat  # noqa: F401\n        if sentiment:\n            import langkit.sentiment  # noqa: F401\n        if toxicity:\n            import langkit.toxicity  # noqa: F401\n        if themes:\n            import langkit.themes  # noqa: F401\n    except ImportError:\n        raise ImportError(\n            \"To use the whylabs callback manager you need to have the `langkit` python \"\n            \"package installed. Please install it with `pip install langkit`.\"\n        )\n    return langkit\n[docs]class WhyLabsCallbackHandler(BaseCallbackHandler):\n    \"\"\"\n    Callback Handler for logging to WhyLabs. This callback handler utilizes", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html"}
{"id": "056dc66a5e10-1", "text": "\"\"\"\n    Callback Handler for logging to WhyLabs. This callback handler utilizes\n    `langkit` to extract features from the prompts & responses when interacting with\n    an LLM. These features can be used to guardrail, evaluate, and observe interactions\n    over time to detect issues relating to hallucinations, prompt engineering,\n    or output validation. LangKit is an LLM monitoring toolkit developed by WhyLabs.\n    Here are some examples of what can be monitored with LangKit:\n    * Text Quality\n      - readability score\n      - complexity and grade scores\n    * Text Relevance\n      - Similarity scores between prompt/responses\n      - Similarity scores against user-defined themes\n      - Topic classification\n    * Security and Privacy\n      - patterns - count of strings matching a user-defined regex pattern group\n      - jailbreaks - similarity scores with respect to known jailbreak attempts\n      - prompt injection - similarity scores with respect to known prompt attacks\n      - refusals - similarity scores with respect to known LLM refusal responses\n    * Sentiment and Toxicity\n      - sentiment analysis\n      - toxicity analysis\n    For more information, see https://docs.whylabs.ai/docs/language-model-monitoring\n    or check out the LangKit repo here: https://github.com/whylabs/langkit\n    ---\n    Args:\n        api_key (Optional[str]): WhyLabs API key. Optional because the preferred\n            way to specify the API key is with environment variable\n            WHYLABS_API_KEY.\n        org_id (Optional[str]): WhyLabs organization id to write profiles to.\n            Optional because the preferred way to specify the organization id is\n            with environment variable WHYLABS_DEFAULT_ORG_ID.\n        dataset_id (Optional[str]): WhyLabs dataset id to write profiles to.\n            Optional because the preferred way to specify the dataset id is", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html"}
{"id": "056dc66a5e10-2", "text": "Optional because the preferred way to specify the dataset id is\n            with environment variable WHYLABS_DEFAULT_DATASET_ID.\n        sentiment (bool): Whether to enable sentiment analysis. Defaults to False.\n        toxicity (bool): Whether to enable toxicity analysis. Defaults to False.\n        themes (bool): Whether to enable theme analysis. Defaults to False.\n    \"\"\"\n[docs]    def __init__(self, logger: Logger, handler: Any):\n        \"\"\"Initiate the rolling logger.\"\"\"\n        super().__init__()\n        if hasattr(handler, \"init\"):\n            handler.init(self)\n        if hasattr(handler, \"_get_callbacks\"):\n            self._callbacks = handler._get_callbacks()\n        else:\n            self._callbacks = dict()\n            diagnostic_logger.warning(\"initialized handler without callbacks.\")\n        self._logger = logger\n[docs]    def flush(self) -> None:\n        \"\"\"Explicitly write current profile if using a rolling logger.\"\"\"\n        if self._logger and hasattr(self._logger, \"_do_rollover\"):\n            self._logger._do_rollover()\n            diagnostic_logger.info(\"Flushing WhyLabs logger, writing profile...\")\n[docs]    def close(self) -> None:\n        \"\"\"Close any loggers to allow writing out of any profiles before exiting.\"\"\"\n        if self._logger and hasattr(self._logger, \"close\"):\n            self._logger.close()\n            diagnostic_logger.info(\"Closing WhyLabs logger, see you next time!\")\n    def __enter__(self) -> WhyLabsCallbackHandler:\n        return self\n    def __exit__(\n        self, exception_type: Any, exception_value: Any, traceback: Any\n    ) -> None:\n        self.close()\n[docs]    @classmethod\n    def from_params(\n        cls,\n        *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html"}
{"id": "056dc66a5e10-3", "text": "[docs]    @classmethod\n    def from_params(\n        cls,\n        *,\n        api_key: Optional[str] = None,\n        org_id: Optional[str] = None,\n        dataset_id: Optional[str] = None,\n        sentiment: bool = False,\n        toxicity: bool = False,\n        themes: bool = False,\n        logger: Optional[Logger] = None,\n    ) -> WhyLabsCallbackHandler:\n        \"\"\"Instantiate whylogs Logger from params.\n        Args:\n            api_key (Optional[str]): WhyLabs API key. Optional because the preferred\n                way to specify the API key is with environment variable\n                WHYLABS_API_KEY.\n            org_id (Optional[str]): WhyLabs organization id to write profiles to.\n                If not set must be specified in environment variable\n                WHYLABS_DEFAULT_ORG_ID.\n            dataset_id (Optional[str]): The model or dataset this callback is gathering\n                telemetry for. If not set must be specified in environment variable\n                WHYLABS_DEFAULT_DATASET_ID.\n            sentiment (bool): If True will initialize a model to perform\n                sentiment analysis compound score. Defaults to False and will not gather\n                this metric.\n            toxicity (bool): If True will initialize a model to score\n                toxicity. Defaults to False and will not gather this metric.\n            themes (bool): If True will initialize a model to calculate\n                distance to configured themes. Defaults to None and will not gather this\n                metric.\n            logger (Optional[Logger]): If specified will bind the configured logger as\n                the telemetry gathering agent. Defaults to LangKit schema with periodic\n                WhyLabs writer.\n        \"\"\"\n        # langkit library will import necessary whylogs libraries\n        import_langkit(sentiment=sentiment, toxicity=toxicity, themes=themes)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html"}
{"id": "056dc66a5e10-4", "text": "import whylogs as why\n        from langkit.callback_handler import get_callback_instance\n        from whylogs.api.writer.whylabs import WhyLabsWriter\n        from whylogs.experimental.core.udf_schema import udf_schema\n        if logger is None:\n            api_key = api_key or get_from_env(\"api_key\", \"WHYLABS_API_KEY\")\n            org_id = org_id or get_from_env(\"org_id\", \"WHYLABS_DEFAULT_ORG_ID\")\n            dataset_id = dataset_id or get_from_env(\n                \"dataset_id\", \"WHYLABS_DEFAULT_DATASET_ID\"\n            )\n            whylabs_writer = WhyLabsWriter(\n                api_key=api_key, org_id=org_id, dataset_id=dataset_id\n            )\n            whylabs_logger = why.logger(\n                mode=\"rolling\", interval=5, when=\"M\", schema=udf_schema()\n            )\n            whylabs_logger.append_writer(writer=whylabs_writer)\n        else:\n            diagnostic_logger.info(\"Using passed in whylogs logger {logger}\")\n            whylabs_logger = logger\n        callback_handler_cls = get_callback_instance(logger=whylabs_logger, impl=cls)\n        diagnostic_logger.info(\n            \"Started whylogs Logger with WhyLabsWriter and initialized LangKit. \ud83d\udcdd\"\n        )\n        return callback_handler_cls", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html"}
{"id": "69cff5503200-0", "text": "Source code for langchain.callbacks.sagemaker_callback\nimport json\nimport os\nimport shutil\nimport tempfile\nfrom copy import deepcopy\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.callbacks.utils import (\n    flatten_dict,\n)\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\n[docs]def save_json(data: dict, file_path: str) -> None:\n    \"\"\"Save dict to local file path.\n    Parameters:\n        data (dict): The dictionary to be saved.\n        file_path (str): Local file path.\n    \"\"\"\n    with open(file_path, \"w\") as outfile:\n        json.dump(data, outfile)\n[docs]class SageMakerCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback Handler that logs prompt artifacts and metrics to SageMaker Experiments.\n    Parameters:\n        run (sagemaker.experiments.run.Run): Run object where the experiment is logged.\n    \"\"\"\n[docs]    def __init__(self, run: Any) -> None:\n        \"\"\"Initialize callback handler.\"\"\"\n        super().__init__()\n        self.run = run\n        self.metrics = {\n            \"step\": 0,\n            \"starts\": 0,\n            \"ends\": 0,\n            \"errors\": 0,\n            \"text_ctr\": 0,\n            \"chain_starts\": 0,\n            \"chain_ends\": 0,\n            \"llm_starts\": 0,\n            \"llm_ends\": 0,\n            \"llm_streams\": 0,\n            \"tool_starts\": 0,\n            \"tool_ends\": 0,\n            \"agent_ends\": 0,\n        }\n        # Create a temporary directory\n        self.temp_dir = tempfile.mkdtemp()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html"}
{"id": "69cff5503200-1", "text": "# Create a temporary directory\n        self.temp_dir = tempfile.mkdtemp()\n    def _reset(self) -> None:\n        for k, v in self.metrics.items():\n            self.metrics[k] = 0\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when LLM starts.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"llm_starts\"] += 1\n        self.metrics[\"starts\"] += 1\n        llm_starts = self.metrics[\"llm_starts\"]\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_llm_start\"})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.metrics)\n        for idx, prompt in enumerate(prompts):\n            prompt_resp = deepcopy(resp)\n            prompt_resp[\"prompt\"] = prompt\n            self.jsonf(\n                prompt_resp,\n                self.temp_dir,\n                f\"llm_start_{llm_starts}_prompt_{idx}\",\n            )\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Run when LLM generates a new token.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"llm_streams\"] += 1\n        llm_streams = self.metrics[\"llm_streams\"]\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_llm_new_token\", \"token\": token})\n        resp.update(self.metrics)\n        self.jsonf(resp, self.temp_dir, f\"llm_new_tokens_{llm_streams}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html"}
{"id": "69cff5503200-2", "text": "[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Run when LLM ends running.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"llm_ends\"] += 1\n        self.metrics[\"ends\"] += 1\n        llm_ends = self.metrics[\"llm_ends\"]\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_llm_end\"})\n        resp.update(flatten_dict(response.llm_output or {}))\n        resp.update(self.metrics)\n        for generations in response.generations:\n            for idx, generation in enumerate(generations):\n                generation_resp = deepcopy(resp)\n                generation_resp.update(flatten_dict(generation.dict()))\n                self.jsonf(\n                    resp,\n                    self.temp_dir,\n                    f\"llm_end_{llm_ends}_generation_{idx}\",\n                )\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when LLM errors.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"errors\"] += 1\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when chain starts running.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"chain_starts\"] += 1\n        self.metrics[\"starts\"] += 1\n        chain_starts = self.metrics[\"chain_starts\"]\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_chain_start\"})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.metrics)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html"}
{"id": "69cff5503200-3", "text": "resp.update(flatten_dict(serialized))\n        resp.update(self.metrics)\n        chain_input = \",\".join([f\"{k}={v}\" for k, v in inputs.items()])\n        input_resp = deepcopy(resp)\n        input_resp[\"inputs\"] = chain_input\n        self.jsonf(input_resp, self.temp_dir, f\"chain_start_{chain_starts}\")\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"Run when chain ends running.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"chain_ends\"] += 1\n        self.metrics[\"ends\"] += 1\n        chain_ends = self.metrics[\"chain_ends\"]\n        resp: Dict[str, Any] = {}\n        chain_output = \",\".join([f\"{k}={v}\" for k, v in outputs.items()])\n        resp.update({\"action\": \"on_chain_end\", \"outputs\": chain_output})\n        resp.update(self.metrics)\n        self.jsonf(resp, self.temp_dir, f\"chain_end_{chain_ends}\")\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when chain errors.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"errors\"] += 1\n[docs]    def on_tool_start(\n        self, serialized: Dict[str, Any], input_str: str, **kwargs: Any\n    ) -> None:\n        \"\"\"Run when tool starts running.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"tool_starts\"] += 1\n        self.metrics[\"starts\"] += 1\n        tool_starts = self.metrics[\"tool_starts\"]\n        resp: Dict[str, Any] = {}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html"}
{"id": "69cff5503200-4", "text": "resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_tool_start\", \"input_str\": input_str})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.metrics)\n        self.jsonf(resp, self.temp_dir, f\"tool_start_{tool_starts}\")\n[docs]    def on_tool_end(self, output: str, **kwargs: Any) -> None:\n        \"\"\"Run when tool ends running.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"tool_ends\"] += 1\n        self.metrics[\"ends\"] += 1\n        tool_ends = self.metrics[\"tool_ends\"]\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_tool_end\", \"output\": output})\n        resp.update(self.metrics)\n        self.jsonf(resp, self.temp_dir, f\"tool_end_{tool_ends}\")\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when tool errors.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"errors\"] += 1\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        \"\"\"\n        Run when agent is ending.\n        \"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"text_ctr\"] += 1\n        text_ctr = self.metrics[\"text_ctr\"]\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_text\", \"text\": text})\n        resp.update(self.metrics)\n        self.jsonf(resp, self.temp_dir, f\"on_text_{text_ctr}\")\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        \"\"\"Run when agent ends running.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html"}
{"id": "69cff5503200-5", "text": "\"\"\"Run when agent ends running.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"agent_ends\"] += 1\n        self.metrics[\"ends\"] += 1\n        agent_ends = self.metrics[\"agent_ends\"]\n        resp: Dict[str, Any] = {}\n        resp.update(\n            {\n                \"action\": \"on_agent_finish\",\n                \"output\": finish.return_values[\"output\"],\n                \"log\": finish.log,\n            }\n        )\n        resp.update(self.metrics)\n        self.jsonf(resp, self.temp_dir, f\"agent_finish_{agent_ends}\")\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Run on agent action.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"tool_starts\"] += 1\n        self.metrics[\"starts\"] += 1\n        tool_starts = self.metrics[\"tool_starts\"]\n        resp: Dict[str, Any] = {}\n        resp.update(\n            {\n                \"action\": \"on_agent_action\",\n                \"tool\": action.tool,\n                \"tool_input\": action.tool_input,\n                \"log\": action.log,\n            }\n        )\n        resp.update(self.metrics)\n        self.jsonf(resp, self.temp_dir, f\"agent_action_{tool_starts}\")\n[docs]    def jsonf(\n        self,\n        data: Dict[str, Any],\n        data_dir: str,\n        filename: str,\n        is_output: Optional[bool] = True,\n    ) -> None:\n        \"\"\"To log the input data as json file artifact.\"\"\"\n        file_path = os.path.join(data_dir, f\"{filename}.json\")\n        save_json(data, file_path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html"}
{"id": "69cff5503200-6", "text": "save_json(data, file_path)\n        self.run.log_file(file_path, name=filename, is_output=is_output)\n[docs]    def flush_tracker(self) -> None:\n        \"\"\"Reset the steps and delete the temporary local directory.\"\"\"\n        self._reset()\n        shutil.rmtree(self.temp_dir)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html"}
{"id": "fbb9948395eb-0", "text": "Source code for langchain.callbacks.mlflow_callback\nimport os\nimport random\nimport string\nimport tempfile\nimport traceback\nfrom copy import deepcopy\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Union\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.callbacks.utils import (\n    BaseMetadataCallbackHandler,\n    flatten_dict,\n    hash_string,\n    import_pandas,\n    import_spacy,\n    import_textstat,\n)\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\nfrom langchain.utils import get_from_dict_or_env\n[docs]def import_mlflow() -> Any:\n    \"\"\"Import the mlflow python package and raise an error if it is not installed.\"\"\"\n    try:\n        import mlflow\n    except ImportError:\n        raise ImportError(\n            \"To use the mlflow callback manager you need to have the `mlflow` python \"\n            \"package installed. Please install it with `pip install mlflow>=2.3.0`\"\n        )\n    return mlflow\n[docs]def analyze_text(\n    text: str,\n    nlp: Any = None,\n) -> dict:\n    \"\"\"Analyze text using textstat and spacy.\n    Parameters:\n        text (str): The text to analyze.\n        nlp (spacy.lang): The spacy language model to use for visualization.\n    Returns:\n        (dict): A dictionary containing the complexity metrics and visualization\n            files serialized to  HTML string.\n    \"\"\"\n    resp: Dict[str, Any] = {}\n    textstat = import_textstat()\n    spacy = import_spacy()\n    text_complexity_metrics = {\n        \"flesch_reading_ease\": textstat.flesch_reading_ease(text),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-1", "text": "\"flesch_reading_ease\": textstat.flesch_reading_ease(text),\n        \"flesch_kincaid_grade\": textstat.flesch_kincaid_grade(text),\n        \"smog_index\": textstat.smog_index(text),\n        \"coleman_liau_index\": textstat.coleman_liau_index(text),\n        \"automated_readability_index\": textstat.automated_readability_index(text),\n        \"dale_chall_readability_score\": textstat.dale_chall_readability_score(text),\n        \"difficult_words\": textstat.difficult_words(text),\n        \"linsear_write_formula\": textstat.linsear_write_formula(text),\n        \"gunning_fog\": textstat.gunning_fog(text),\n        # \"text_standard\": textstat.text_standard(text),\n        \"fernandez_huerta\": textstat.fernandez_huerta(text),\n        \"szigriszt_pazos\": textstat.szigriszt_pazos(text),\n        \"gutierrez_polini\": textstat.gutierrez_polini(text),\n        \"crawford\": textstat.crawford(text),\n        \"gulpease_index\": textstat.gulpease_index(text),\n        \"osman\": textstat.osman(text),\n    }\n    resp.update({\"text_complexity_metrics\": text_complexity_metrics})\n    resp.update(text_complexity_metrics)\n    if nlp is not None:\n        doc = nlp(text)\n        dep_out = spacy.displacy.render(  # type: ignore\n            doc, style=\"dep\", jupyter=False, page=True\n        )\n        ent_out = spacy.displacy.render(  # type: ignore\n            doc, style=\"ent\", jupyter=False, page=True\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-2", "text": "doc, style=\"ent\", jupyter=False, page=True\n        )\n        text_visualizations = {\n            \"dependency_tree\": dep_out,\n            \"entities\": ent_out,\n        }\n        resp.update(text_visualizations)\n    return resp\n[docs]def construct_html_from_prompt_and_generation(prompt: str, generation: str) -> Any:\n    \"\"\"Construct an html element from a prompt and a generation.\n    Parameters:\n        prompt (str): The prompt.\n        generation (str): The generation.\n    Returns:\n        (str): The html string.\"\"\"\n    formatted_prompt = prompt.replace(\"\\n\", \"<br>\")\n    formatted_generation = generation.replace(\"\\n\", \"<br>\")\n    return f\"\"\"\n    <p style=\"color:black;\">{formatted_prompt}:</p>\n    <blockquote>\n      <p style=\"color:green;\">\n        {formatted_generation}\n      </p>\n    </blockquote>\n    \"\"\"\n[docs]class MlflowLogger:\n    \"\"\"Callback Handler that logs metrics and artifacts to mlflow server.\n    Parameters:\n        name (str): Name of the run.\n        experiment (str): Name of the experiment.\n        tags (dict): Tags to be attached for the run.\n        tracking_uri (str): MLflow tracking server uri.\n    This handler implements the helper functions to initialize,\n    log metrics and artifacts to the mlflow server.\n    \"\"\"\n[docs]    def __init__(self, **kwargs: Any):\n        self.mlflow = import_mlflow()\n        if \"DATABRICKS_RUNTIME_VERSION\" in os.environ:\n            self.mlflow.set_tracking_uri(\"databricks\")\n            self.mlf_expid = self.mlflow.tracking.fluent._get_experiment_id()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-3", "text": "self.mlf_expid = self.mlflow.tracking.fluent._get_experiment_id()\n            self.mlf_exp = self.mlflow.get_experiment(self.mlf_expid)\n        else:\n            tracking_uri = get_from_dict_or_env(\n                kwargs, \"tracking_uri\", \"MLFLOW_TRACKING_URI\", \"\"\n            )\n            self.mlflow.set_tracking_uri(tracking_uri)\n            # User can set other env variables described here\n            # > https://www.mlflow.org/docs/latest/tracking.html#logging-to-a-tracking-server\n            experiment_name = get_from_dict_or_env(\n                kwargs, \"experiment_name\", \"MLFLOW_EXPERIMENT_NAME\"\n            )\n            self.mlf_exp = self.mlflow.get_experiment_by_name(experiment_name)\n            if self.mlf_exp is not None:\n                self.mlf_expid = self.mlf_exp.experiment_id\n            else:\n                self.mlf_expid = self.mlflow.create_experiment(experiment_name)\n        self.start_run(kwargs[\"run_name\"], kwargs[\"run_tags\"])\n[docs]    def start_run(self, name: str, tags: Dict[str, str]) -> None:\n        \"\"\"To start a new run, auto generates the random suffix for name\"\"\"\n        if name.endswith(\"-%\"):\n            rname = \"\".join(random.choices(string.ascii_uppercase + string.digits, k=7))\n            name = name.replace(\"%\", rname)\n        self.run = self.mlflow.MlflowClient().create_run(\n            self.mlf_expid, run_name=name, tags=tags\n        )\n[docs]    def finish_run(self) -> None:\n        \"\"\"To finish the run.\"\"\"\n        with self.mlflow.start_run(\n            run_id=self.run.info.run_id, experiment_id=self.mlf_expid\n        ):\n            self.mlflow.end_run()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-4", "text": "):\n            self.mlflow.end_run()\n[docs]    def metric(self, key: str, value: float) -> None:\n        \"\"\"To log metric to mlflow server.\"\"\"\n        with self.mlflow.start_run(\n            run_id=self.run.info.run_id, experiment_id=self.mlf_expid\n        ):\n            self.mlflow.log_metric(key, value)\n[docs]    def metrics(\n        self, data: Union[Dict[str, float], Dict[str, int]], step: Optional[int] = 0\n    ) -> None:\n        \"\"\"To log all metrics in the input dict.\"\"\"\n        with self.mlflow.start_run(\n            run_id=self.run.info.run_id, experiment_id=self.mlf_expid\n        ):\n            self.mlflow.log_metrics(data)\n[docs]    def jsonf(self, data: Dict[str, Any], filename: str) -> None:\n        \"\"\"To log the input data as json file artifact.\"\"\"\n        with self.mlflow.start_run(\n            run_id=self.run.info.run_id, experiment_id=self.mlf_expid\n        ):\n            self.mlflow.log_dict(data, f\"{filename}.json\")\n[docs]    def table(self, name: str, dataframe) -> None:  # type: ignore\n        \"\"\"To log the input pandas dataframe as a html table\"\"\"\n        self.html(dataframe.to_html(), f\"table_{name}\")\n[docs]    def html(self, html: str, filename: str) -> None:\n        \"\"\"To log the input html string as html file artifact.\"\"\"\n        with self.mlflow.start_run(\n            run_id=self.run.info.run_id, experiment_id=self.mlf_expid\n        ):\n            self.mlflow.log_text(html, f\"{filename}.html\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-5", "text": "):\n            self.mlflow.log_text(html, f\"{filename}.html\")\n[docs]    def text(self, text: str, filename: str) -> None:\n        \"\"\"To log the input text as text file artifact.\"\"\"\n        with self.mlflow.start_run(\n            run_id=self.run.info.run_id, experiment_id=self.mlf_expid\n        ):\n            self.mlflow.log_text(text, f\"{filename}.txt\")\n[docs]    def artifact(self, path: str) -> None:\n        \"\"\"To upload the file from given path as artifact.\"\"\"\n        with self.mlflow.start_run(\n            run_id=self.run.info.run_id, experiment_id=self.mlf_expid\n        ):\n            self.mlflow.log_artifact(path)\n[docs]    def langchain_artifact(self, chain: Any) -> None:\n        with self.mlflow.start_run(\n            run_id=self.run.info.run_id, experiment_id=self.mlf_expid\n        ):\n            self.mlflow.langchain.log_model(chain, \"langchain-model\")\n[docs]class MlflowCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):\n    \"\"\"Callback Handler that logs metrics and artifacts to mlflow server.\n    Parameters:\n        name (str): Name of the run.\n        experiment (str): Name of the experiment.\n        tags (dict): Tags to be attached for the run.\n        tracking_uri (str): MLflow tracking server uri.\n    This handler will utilize the associated callback method called and formats\n    the input of each callback function with metadata regarding the state of LLM run,\n    and adds the response to the list of records for both the {method}_records and\n    action. It then logs the response to mlflow server.\n    \"\"\"\n[docs]    def __init__(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-6", "text": "\"\"\"\n[docs]    def __init__(\n        self,\n        name: Optional[str] = \"langchainrun-%\",\n        experiment: Optional[str] = \"langchain\",\n        tags: Optional[Dict] = None,\n        tracking_uri: Optional[str] = None,\n    ) -> None:\n        \"\"\"Initialize callback handler.\"\"\"\n        import_pandas()\n        import_textstat()\n        import_mlflow()\n        spacy = import_spacy()\n        super().__init__()\n        self.name = name\n        self.experiment = experiment\n        self.tags = tags or {}\n        self.tracking_uri = tracking_uri\n        self.temp_dir = tempfile.TemporaryDirectory()\n        self.mlflg = MlflowLogger(\n            tracking_uri=self.tracking_uri,\n            experiment_name=self.experiment,\n            run_name=self.name,\n            run_tags=self.tags,\n        )\n        self.action_records: list = []\n        self.nlp = spacy.load(\"en_core_web_sm\")\n        self.metrics = {\n            \"step\": 0,\n            \"starts\": 0,\n            \"ends\": 0,\n            \"errors\": 0,\n            \"text_ctr\": 0,\n            \"chain_starts\": 0,\n            \"chain_ends\": 0,\n            \"llm_starts\": 0,\n            \"llm_ends\": 0,\n            \"llm_streams\": 0,\n            \"tool_starts\": 0,\n            \"tool_ends\": 0,\n            \"agent_ends\": 0,\n        }\n        self.records: Dict[str, Any] = {\n            \"on_llm_start_records\": [],\n            \"on_llm_token_records\": [],\n            \"on_llm_end_records\": [],\n            \"on_chain_start_records\": [],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-7", "text": "\"on_llm_end_records\": [],\n            \"on_chain_start_records\": [],\n            \"on_chain_end_records\": [],\n            \"on_tool_start_records\": [],\n            \"on_tool_end_records\": [],\n            \"on_text_records\": [],\n            \"on_agent_finish_records\": [],\n            \"on_agent_action_records\": [],\n            \"action_records\": [],\n        }\n    def _reset(self) -> None:\n        for k, v in self.metrics.items():\n            self.metrics[k] = 0\n        for k, v in self.records.items():\n            self.records[k] = []\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when LLM starts.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"llm_starts\"] += 1\n        self.metrics[\"starts\"] += 1\n        llm_starts = self.metrics[\"llm_starts\"]\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_llm_start\"})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.metrics)\n        self.mlflg.metrics(self.metrics, step=self.metrics[\"step\"])\n        for idx, prompt in enumerate(prompts):\n            prompt_resp = deepcopy(resp)\n            prompt_resp[\"prompt\"] = prompt\n            self.records[\"on_llm_start_records\"].append(prompt_resp)\n            self.records[\"action_records\"].append(prompt_resp)\n            self.mlflg.jsonf(prompt_resp, f\"llm_start_{llm_starts}_prompt_{idx}\")\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Run when LLM generates a new token.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-8", "text": "\"\"\"Run when LLM generates a new token.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"llm_streams\"] += 1\n        llm_streams = self.metrics[\"llm_streams\"]\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_llm_new_token\", \"token\": token})\n        resp.update(self.metrics)\n        self.mlflg.metrics(self.metrics, step=self.metrics[\"step\"])\n        self.records[\"on_llm_token_records\"].append(resp)\n        self.records[\"action_records\"].append(resp)\n        self.mlflg.jsonf(resp, f\"llm_new_tokens_{llm_streams}\")\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Run when LLM ends running.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"llm_ends\"] += 1\n        self.metrics[\"ends\"] += 1\n        llm_ends = self.metrics[\"llm_ends\"]\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_llm_end\"})\n        resp.update(flatten_dict(response.llm_output or {}))\n        resp.update(self.metrics)\n        self.mlflg.metrics(self.metrics, step=self.metrics[\"step\"])\n        for generations in response.generations:\n            for idx, generation in enumerate(generations):\n                generation_resp = deepcopy(resp)\n                generation_resp.update(flatten_dict(generation.dict()))\n                generation_resp.update(\n                    analyze_text(\n                        generation.text,\n                        nlp=self.nlp,\n                    )\n                )\n                complexity_metrics: Dict[str, float] = generation_resp.pop(\n                    \"text_complexity_metrics\"\n                )  # type: ignore  # noqa: E501", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-9", "text": ")  # type: ignore  # noqa: E501\n                self.mlflg.metrics(\n                    complexity_metrics,\n                    step=self.metrics[\"step\"],\n                )\n                self.records[\"on_llm_end_records\"].append(generation_resp)\n                self.records[\"action_records\"].append(generation_resp)\n                self.mlflg.jsonf(resp, f\"llm_end_{llm_ends}_generation_{idx}\")\n                dependency_tree = generation_resp[\"dependency_tree\"]\n                entities = generation_resp[\"entities\"]\n                self.mlflg.html(dependency_tree, \"dep-\" + hash_string(generation.text))\n                self.mlflg.html(entities, \"ent-\" + hash_string(generation.text))\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when LLM errors.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"errors\"] += 1\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when chain starts running.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"chain_starts\"] += 1\n        self.metrics[\"starts\"] += 1\n        chain_starts = self.metrics[\"chain_starts\"]\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_chain_start\"})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.metrics)\n        self.mlflg.metrics(self.metrics, step=self.metrics[\"step\"])\n        chain_input = \",\".join([f\"{k}={v}\" for k, v in inputs.items()])\n        input_resp = deepcopy(resp)\n        input_resp[\"inputs\"] = chain_input", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-10", "text": "input_resp = deepcopy(resp)\n        input_resp[\"inputs\"] = chain_input\n        self.records[\"on_chain_start_records\"].append(input_resp)\n        self.records[\"action_records\"].append(input_resp)\n        self.mlflg.jsonf(input_resp, f\"chain_start_{chain_starts}\")\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"Run when chain ends running.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"chain_ends\"] += 1\n        self.metrics[\"ends\"] += 1\n        chain_ends = self.metrics[\"chain_ends\"]\n        resp: Dict[str, Any] = {}\n        chain_output = \",\".join([f\"{k}={v}\" for k, v in outputs.items()])\n        resp.update({\"action\": \"on_chain_end\", \"outputs\": chain_output})\n        resp.update(self.metrics)\n        self.mlflg.metrics(self.metrics, step=self.metrics[\"step\"])\n        self.records[\"on_chain_end_records\"].append(resp)\n        self.records[\"action_records\"].append(resp)\n        self.mlflg.jsonf(resp, f\"chain_end_{chain_ends}\")\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when chain errors.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"errors\"] += 1\n[docs]    def on_tool_start(\n        self, serialized: Dict[str, Any], input_str: str, **kwargs: Any\n    ) -> None:\n        \"\"\"Run when tool starts running.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"tool_starts\"] += 1\n        self.metrics[\"starts\"] += 1\n        tool_starts = self.metrics[\"tool_starts\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-11", "text": "tool_starts = self.metrics[\"tool_starts\"]\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_tool_start\", \"input_str\": input_str})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.metrics)\n        self.mlflg.metrics(self.metrics, step=self.metrics[\"step\"])\n        self.records[\"on_tool_start_records\"].append(resp)\n        self.records[\"action_records\"].append(resp)\n        self.mlflg.jsonf(resp, f\"tool_start_{tool_starts}\")\n[docs]    def on_tool_end(self, output: str, **kwargs: Any) -> None:\n        \"\"\"Run when tool ends running.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"tool_ends\"] += 1\n        self.metrics[\"ends\"] += 1\n        tool_ends = self.metrics[\"tool_ends\"]\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_tool_end\", \"output\": output})\n        resp.update(self.metrics)\n        self.mlflg.metrics(self.metrics, step=self.metrics[\"step\"])\n        self.records[\"on_tool_end_records\"].append(resp)\n        self.records[\"action_records\"].append(resp)\n        self.mlflg.jsonf(resp, f\"tool_end_{tool_ends}\")\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when tool errors.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"errors\"] += 1\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        \"\"\"\n        Run when agent is ending.\n        \"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"text_ctr\"] += 1", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-12", "text": "self.metrics[\"text_ctr\"] += 1\n        text_ctr = self.metrics[\"text_ctr\"]\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_text\", \"text\": text})\n        resp.update(self.metrics)\n        self.mlflg.metrics(self.metrics, step=self.metrics[\"step\"])\n        self.records[\"on_text_records\"].append(resp)\n        self.records[\"action_records\"].append(resp)\n        self.mlflg.jsonf(resp, f\"on_text_{text_ctr}\")\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        \"\"\"Run when agent ends running.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"agent_ends\"] += 1\n        self.metrics[\"ends\"] += 1\n        agent_ends = self.metrics[\"agent_ends\"]\n        resp: Dict[str, Any] = {}\n        resp.update(\n            {\n                \"action\": \"on_agent_finish\",\n                \"output\": finish.return_values[\"output\"],\n                \"log\": finish.log,\n            }\n        )\n        resp.update(self.metrics)\n        self.mlflg.metrics(self.metrics, step=self.metrics[\"step\"])\n        self.records[\"on_agent_finish_records\"].append(resp)\n        self.records[\"action_records\"].append(resp)\n        self.mlflg.jsonf(resp, f\"agent_finish_{agent_ends}\")\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Run on agent action.\"\"\"\n        self.metrics[\"step\"] += 1\n        self.metrics[\"tool_starts\"] += 1\n        self.metrics[\"starts\"] += 1\n        tool_starts = self.metrics[\"tool_starts\"]\n        resp: Dict[str, Any] = {}\n        resp.update(\n            {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-13", "text": "resp: Dict[str, Any] = {}\n        resp.update(\n            {\n                \"action\": \"on_agent_action\",\n                \"tool\": action.tool,\n                \"tool_input\": action.tool_input,\n                \"log\": action.log,\n            }\n        )\n        resp.update(self.metrics)\n        self.mlflg.metrics(self.metrics, step=self.metrics[\"step\"])\n        self.records[\"on_agent_action_records\"].append(resp)\n        self.records[\"action_records\"].append(resp)\n        self.mlflg.jsonf(resp, f\"agent_action_{tool_starts}\")\n    def _create_session_analysis_df(self) -> Any:\n        \"\"\"Create a dataframe with all the information from the session.\"\"\"\n        pd = import_pandas()\n        on_llm_start_records_df = pd.DataFrame(self.records[\"on_llm_start_records\"])\n        on_llm_end_records_df = pd.DataFrame(self.records[\"on_llm_end_records\"])\n        llm_input_columns = [\"step\", \"prompt\"]\n        if \"name\" in on_llm_start_records_df.columns:\n            llm_input_columns.append(\"name\")\n        elif \"id\" in on_llm_start_records_df.columns:\n            # id is llm class's full import path. For example:\n            # [\"langchain\", \"llms\", \"openai\", \"AzureOpenAI\"]\n            on_llm_start_records_df[\"name\"] = on_llm_start_records_df[\"id\"].apply(\n                lambda id_: id_[-1]\n            )\n            llm_input_columns.append(\"name\")\n        llm_input_prompts_df = (\n            on_llm_start_records_df[llm_input_columns]\n            .dropna(axis=1)\n            .rename({\"step\": \"prompt_step\"}, axis=1)\n        )\n        complexity_metrics_columns = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-14", "text": ")\n        complexity_metrics_columns = []\n        visualizations_columns = []\n        complexity_metrics_columns = [\n            \"flesch_reading_ease\",\n            \"flesch_kincaid_grade\",\n            \"smog_index\",\n            \"coleman_liau_index\",\n            \"automated_readability_index\",\n            \"dale_chall_readability_score\",\n            \"difficult_words\",\n            \"linsear_write_formula\",\n            \"gunning_fog\",\n            # \"text_standard\",\n            \"fernandez_huerta\",\n            \"szigriszt_pazos\",\n            \"gutierrez_polini\",\n            \"crawford\",\n            \"gulpease_index\",\n            \"osman\",\n        ]\n        visualizations_columns = [\"dependency_tree\", \"entities\"]\n        llm_outputs_df = (\n            on_llm_end_records_df[\n                [\n                    \"step\",\n                    \"text\",\n                    \"token_usage_total_tokens\",\n                    \"token_usage_prompt_tokens\",\n                    \"token_usage_completion_tokens\",\n                ]\n                + complexity_metrics_columns\n                + visualizations_columns\n            ]\n            .dropna(axis=1)\n            .rename({\"step\": \"output_step\", \"text\": \"output\"}, axis=1)\n        )\n        session_analysis_df = pd.concat([llm_input_prompts_df, llm_outputs_df], axis=1)\n        session_analysis_df[\"chat_html\"] = session_analysis_df[\n            [\"prompt\", \"output\"]\n        ].apply(\n            lambda row: construct_html_from_prompt_and_generation(\n                row[\"prompt\"], row[\"output\"]\n            ),\n            axis=1,\n        )\n        return session_analysis_df", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "fbb9948395eb-15", "text": "),\n            axis=1,\n        )\n        return session_analysis_df\n[docs]    def flush_tracker(self, langchain_asset: Any = None, finish: bool = False) -> None:\n        pd = import_pandas()\n        self.mlflg.table(\"action_records\", pd.DataFrame(self.records[\"action_records\"]))\n        session_analysis_df = self._create_session_analysis_df()\n        chat_html = session_analysis_df.pop(\"chat_html\")\n        chat_html = chat_html.replace(\"\\n\", \"\", regex=True)\n        self.mlflg.table(\"session_analysis\", pd.DataFrame(session_analysis_df))\n        self.mlflg.html(\"\".join(chat_html.tolist()), \"chat_html\")\n        if langchain_asset:\n            # To avoid circular import error\n            # mlflow only supports LLMChain asset\n            if \"langchain.chains.llm.LLMChain\" in str(type(langchain_asset)):\n                self.mlflg.langchain_artifact(langchain_asset)\n            else:\n                langchain_asset_path = str(Path(self.temp_dir.name, \"model.json\"))\n                try:\n                    langchain_asset.save(langchain_asset_path)\n                    self.mlflg.artifact(langchain_asset_path)\n                except ValueError:\n                    try:\n                        langchain_asset.save_agent(langchain_asset_path)\n                        self.mlflg.artifact(langchain_asset_path)\n                    except AttributeError:\n                        print(\"Could not save model.\")\n                        traceback.print_exc()\n                        pass\n                    except NotImplementedError:\n                        print(\"Could not save model.\")\n                        traceback.print_exc()\n                        pass\n                except NotImplementedError:\n                    print(\"Could not save model.\")\n                    traceback.print_exc()\n                    pass\n        if finish:\n            self.mlflg.finish_run()\n            self._reset()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html"}
{"id": "4f45b7eb6cb8-0", "text": "Source code for langchain.callbacks.clearml_callback\nfrom __future__ import annotations\nimport tempfile\nfrom copy import deepcopy\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Sequence\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.callbacks.utils import (\n    BaseMetadataCallbackHandler,\n    flatten_dict,\n    hash_string,\n    import_pandas,\n    import_spacy,\n    import_textstat,\n    load_json,\n)\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\nif TYPE_CHECKING:\n    import pandas as pd\n[docs]def import_clearml() -> Any:\n    \"\"\"Import the clearml python package and raise an error if it is not installed.\"\"\"\n    try:\n        import clearml  # noqa: F401\n    except ImportError:\n        raise ImportError(\n            \"To use the clearml callback manager you need to have the `clearml` python \"\n            \"package installed. Please install it with `pip install clearml`\"\n        )\n    return clearml\n[docs]class ClearMLCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):\n    \"\"\"Callback Handler that logs to ClearML.\n    Parameters:\n        job_type (str): The type of clearml task such as \"inference\", \"testing\" or \"qc\"\n        project_name (str): The clearml project name\n        tags (list): Tags to add to the task\n        task_name (str): Name of the clearml task\n        visualize (bool): Whether to visualize the run.\n        complexity_metrics (bool): Whether to log complexity metrics\n        stream_logs (bool): Whether to stream callback actions to ClearML\n    This handler will utilize the associated callback method and formats", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html"}
{"id": "4f45b7eb6cb8-1", "text": "This handler will utilize the associated callback method and formats\n    the input of each callback function with metadata regarding the state of LLM run,\n    and adds the response to the list of records for both the {method}_records and\n    action. It then logs the response to the ClearML console.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        task_type: Optional[str] = \"inference\",\n        project_name: Optional[str] = \"langchain_callback_demo\",\n        tags: Optional[Sequence] = None,\n        task_name: Optional[str] = None,\n        visualize: bool = False,\n        complexity_metrics: bool = False,\n        stream_logs: bool = False,\n    ) -> None:\n        \"\"\"Initialize callback handler.\"\"\"\n        clearml = import_clearml()\n        spacy = import_spacy()\n        super().__init__()\n        self.task_type = task_type\n        self.project_name = project_name\n        self.tags = tags\n        self.task_name = task_name\n        self.visualize = visualize\n        self.complexity_metrics = complexity_metrics\n        self.stream_logs = stream_logs\n        self.temp_dir = tempfile.TemporaryDirectory()\n        # Check if ClearML task already exists (e.g. in pipeline)\n        if clearml.Task.current_task():\n            self.task = clearml.Task.current_task()\n        else:\n            self.task = clearml.Task.init(  # type: ignore\n                task_type=self.task_type,\n                project_name=self.project_name,\n                tags=self.tags,\n                task_name=self.task_name,\n                output_uri=True,\n            )\n        self.logger = self.task.get_logger()\n        warning = (\n            \"The clearml callback is currently in beta and is subject to change \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html"}
{"id": "4f45b7eb6cb8-2", "text": "\"The clearml callback is currently in beta and is subject to change \"\n            \"based on updates to `langchain`. Please report any issues to \"\n            \"https://github.com/allegroai/clearml/issues with the tag `langchain`.\"\n        )\n        self.logger.report_text(warning, level=30, print_console=True)\n        self.callback_columns: list = []\n        self.action_records: list = []\n        self.complexity_metrics = complexity_metrics\n        self.visualize = visualize\n        self.nlp = spacy.load(\"en_core_web_sm\")\n    def _init_resp(self) -> Dict:\n        return {k: None for k in self.callback_columns}\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when LLM starts.\"\"\"\n        self.step += 1\n        self.llm_starts += 1\n        self.starts += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_llm_start\"})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.get_custom_callback_meta())\n        for prompt in prompts:\n            prompt_resp = deepcopy(resp)\n            prompt_resp[\"prompts\"] = prompt\n            self.on_llm_start_records.append(prompt_resp)\n            self.action_records.append(prompt_resp)\n            if self.stream_logs:\n                self.logger.report_text(prompt_resp)\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Run when LLM generates a new token.\"\"\"\n        self.step += 1\n        self.llm_streams += 1\n        resp = self._init_resp()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html"}
{"id": "4f45b7eb6cb8-3", "text": "self.llm_streams += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_llm_new_token\", \"token\": token})\n        resp.update(self.get_custom_callback_meta())\n        self.on_llm_token_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.logger.report_text(resp)\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Run when LLM ends running.\"\"\"\n        self.step += 1\n        self.llm_ends += 1\n        self.ends += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_llm_end\"})\n        resp.update(flatten_dict(response.llm_output or {}))\n        resp.update(self.get_custom_callback_meta())\n        for generations in response.generations:\n            for generation in generations:\n                generation_resp = deepcopy(resp)\n                generation_resp.update(flatten_dict(generation.dict()))\n                generation_resp.update(self.analyze_text(generation.text))\n                self.on_llm_end_records.append(generation_resp)\n                self.action_records.append(generation_resp)\n                if self.stream_logs:\n                    self.logger.report_text(generation_resp)\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when LLM errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when chain starts running.\"\"\"\n        self.step += 1\n        self.chain_starts += 1\n        self.starts += 1", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html"}
{"id": "4f45b7eb6cb8-4", "text": "self.chain_starts += 1\n        self.starts += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_chain_start\"})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.get_custom_callback_meta())\n        chain_input = inputs.get(\"input\", inputs.get(\"human_input\"))\n        if isinstance(chain_input, str):\n            input_resp = deepcopy(resp)\n            input_resp[\"input\"] = chain_input\n            self.on_chain_start_records.append(input_resp)\n            self.action_records.append(input_resp)\n            if self.stream_logs:\n                self.logger.report_text(input_resp)\n        elif isinstance(chain_input, list):\n            for inp in chain_input:\n                input_resp = deepcopy(resp)\n                input_resp.update(inp)\n                self.on_chain_start_records.append(input_resp)\n                self.action_records.append(input_resp)\n                if self.stream_logs:\n                    self.logger.report_text(input_resp)\n        else:\n            raise ValueError(\"Unexpected data format provided!\")\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"Run when chain ends running.\"\"\"\n        self.step += 1\n        self.chain_ends += 1\n        self.ends += 1\n        resp = self._init_resp()\n        resp.update(\n            {\n                \"action\": \"on_chain_end\",\n                \"outputs\": outputs.get(\"output\", outputs.get(\"text\")),\n            }\n        )\n        resp.update(self.get_custom_callback_meta())\n        self.on_chain_end_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.logger.report_text(resp)\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when chain errors.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html"}
{"id": "4f45b7eb6cb8-5", "text": "\"\"\"Run when chain errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_tool_start(\n        self, serialized: Dict[str, Any], input_str: str, **kwargs: Any\n    ) -> None:\n        \"\"\"Run when tool starts running.\"\"\"\n        self.step += 1\n        self.tool_starts += 1\n        self.starts += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_tool_start\", \"input_str\": input_str})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.get_custom_callback_meta())\n        self.on_tool_start_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.logger.report_text(resp)\n[docs]    def on_tool_end(self, output: str, **kwargs: Any) -> None:\n        \"\"\"Run when tool ends running.\"\"\"\n        self.step += 1\n        self.tool_ends += 1\n        self.ends += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_tool_end\", \"output\": output})\n        resp.update(self.get_custom_callback_meta())\n        self.on_tool_end_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.logger.report_text(resp)\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when tool errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        \"\"\"\n        Run when agent is ending.\n        \"\"\"\n        self.step += 1\n        self.text_ctr += 1\n        resp = self._init_resp()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html"}
{"id": "4f45b7eb6cb8-6", "text": "self.text_ctr += 1\n        resp = self._init_resp()\n        resp.update({\"action\": \"on_text\", \"text\": text})\n        resp.update(self.get_custom_callback_meta())\n        self.on_text_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.logger.report_text(resp)\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        \"\"\"Run when agent ends running.\"\"\"\n        self.step += 1\n        self.agent_ends += 1\n        self.ends += 1\n        resp = self._init_resp()\n        resp.update(\n            {\n                \"action\": \"on_agent_finish\",\n                \"output\": finish.return_values[\"output\"],\n                \"log\": finish.log,\n            }\n        )\n        resp.update(self.get_custom_callback_meta())\n        self.on_agent_finish_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.logger.report_text(resp)\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Run on agent action.\"\"\"\n        self.step += 1\n        self.tool_starts += 1\n        self.starts += 1\n        resp = self._init_resp()\n        resp.update(\n            {\n                \"action\": \"on_agent_action\",\n                \"tool\": action.tool,\n                \"tool_input\": action.tool_input,\n                \"log\": action.log,\n            }\n        )\n        resp.update(self.get_custom_callback_meta())\n        self.on_agent_action_records.append(resp)\n        self.action_records.append(resp)\n        if self.stream_logs:\n            self.logger.report_text(resp)\n[docs]    def analyze_text(self, text: str) -> dict:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html"}
{"id": "4f45b7eb6cb8-7", "text": "[docs]    def analyze_text(self, text: str) -> dict:\n        \"\"\"Analyze text using textstat and spacy.\n        Parameters:\n            text (str): The text to analyze.\n        Returns:\n            (dict): A dictionary containing the complexity metrics.\n        \"\"\"\n        resp = {}\n        textstat = import_textstat()\n        spacy = import_spacy()\n        if self.complexity_metrics:\n            text_complexity_metrics = {\n                \"flesch_reading_ease\": textstat.flesch_reading_ease(text),\n                \"flesch_kincaid_grade\": textstat.flesch_kincaid_grade(text),\n                \"smog_index\": textstat.smog_index(text),\n                \"coleman_liau_index\": textstat.coleman_liau_index(text),\n                \"automated_readability_index\": textstat.automated_readability_index(\n                    text\n                ),\n                \"dale_chall_readability_score\": textstat.dale_chall_readability_score(\n                    text\n                ),\n                \"difficult_words\": textstat.difficult_words(text),\n                \"linsear_write_formula\": textstat.linsear_write_formula(text),\n                \"gunning_fog\": textstat.gunning_fog(text),\n                \"text_standard\": textstat.text_standard(text),\n                \"fernandez_huerta\": textstat.fernandez_huerta(text),\n                \"szigriszt_pazos\": textstat.szigriszt_pazos(text),\n                \"gutierrez_polini\": textstat.gutierrez_polini(text),\n                \"crawford\": textstat.crawford(text),\n                \"gulpease_index\": textstat.gulpease_index(text),\n                \"osman\": textstat.osman(text),\n            }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html"}
{"id": "4f45b7eb6cb8-8", "text": "\"osman\": textstat.osman(text),\n            }\n            resp.update(text_complexity_metrics)\n        if self.visualize and self.nlp and self.temp_dir.name is not None:\n            doc = self.nlp(text)\n            dep_out = spacy.displacy.render(  # type: ignore\n                doc, style=\"dep\", jupyter=False, page=True\n            )\n            dep_output_path = Path(\n                self.temp_dir.name, hash_string(f\"dep-{text}\") + \".html\"\n            )\n            dep_output_path.open(\"w\", encoding=\"utf-8\").write(dep_out)\n            ent_out = spacy.displacy.render(  # type: ignore\n                doc, style=\"ent\", jupyter=False, page=True\n            )\n            ent_output_path = Path(\n                self.temp_dir.name, hash_string(f\"ent-{text}\") + \".html\"\n            )\n            ent_output_path.open(\"w\", encoding=\"utf-8\").write(ent_out)\n            self.logger.report_media(\n                \"Dependencies Plot\", text, local_path=dep_output_path\n            )\n            self.logger.report_media(\"Entities Plot\", text, local_path=ent_output_path)\n        return resp\n    @staticmethod\n    def _build_llm_df(\n        base_df: pd.DataFrame, base_df_fields: Sequence, rename_map: Mapping\n    ) -> pd.DataFrame:\n        base_df_fields = [field for field in base_df_fields if field in base_df]\n        rename_map = {\n            map_entry_k: map_entry_v\n            for map_entry_k, map_entry_v in rename_map.items()\n            if map_entry_k in base_df_fields\n        }\n        llm_df = base_df[base_df_fields].dropna(axis=1)\n        if rename_map:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html"}
{"id": "4f45b7eb6cb8-9", "text": "if rename_map:\n            llm_df = llm_df.rename(rename_map, axis=1)\n        return llm_df\n    def _create_session_analysis_df(self) -> Any:\n        \"\"\"Create a dataframe with all the information from the session.\"\"\"\n        pd = import_pandas()\n        on_llm_end_records_df = pd.DataFrame(self.on_llm_end_records)\n        llm_input_prompts_df = ClearMLCallbackHandler._build_llm_df(\n            base_df=on_llm_end_records_df,\n            base_df_fields=[\"step\", \"prompts\"]\n            + ([\"name\"] if \"name\" in on_llm_end_records_df else [\"id\"]),\n            rename_map={\"step\": \"prompt_step\"},\n        )\n        complexity_metrics_columns = []\n        visualizations_columns: List = []\n        if self.complexity_metrics:\n            complexity_metrics_columns = [\n                \"flesch_reading_ease\",\n                \"flesch_kincaid_grade\",\n                \"smog_index\",\n                \"coleman_liau_index\",\n                \"automated_readability_index\",\n                \"dale_chall_readability_score\",\n                \"difficult_words\",\n                \"linsear_write_formula\",\n                \"gunning_fog\",\n                \"text_standard\",\n                \"fernandez_huerta\",\n                \"szigriszt_pazos\",\n                \"gutierrez_polini\",\n                \"crawford\",\n                \"gulpease_index\",\n                \"osman\",\n            ]\n        llm_outputs_df = ClearMLCallbackHandler._build_llm_df(\n            on_llm_end_records_df,\n            [\n                \"step\",\n                \"text\",\n                \"token_usage_total_tokens\",\n                \"token_usage_prompt_tokens\",\n                \"token_usage_completion_tokens\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html"}
{"id": "4f45b7eb6cb8-10", "text": "\"token_usage_prompt_tokens\",\n                \"token_usage_completion_tokens\",\n            ]\n            + complexity_metrics_columns\n            + visualizations_columns,\n            {\"step\": \"output_step\", \"text\": \"output\"},\n        )\n        session_analysis_df = pd.concat([llm_input_prompts_df, llm_outputs_df], axis=1)\n        return session_analysis_df\n[docs]    def flush_tracker(\n        self,\n        name: Optional[str] = None,\n        langchain_asset: Any = None,\n        finish: bool = False,\n    ) -> None:\n        \"\"\"Flush the tracker and setup the session.\n        Everything after this will be a new table.\n        Args:\n            name: Name of the performed session so far so it is identifiable\n            langchain_asset: The langchain asset to save.\n            finish: Whether to finish the run.\n            Returns:\n                None\n        \"\"\"\n        pd = import_pandas()\n        clearml = import_clearml()\n        # Log the action records\n        self.logger.report_table(\n            \"Action Records\", name, table_plot=pd.DataFrame(self.action_records)\n        )\n        # Session analysis\n        session_analysis_df = self._create_session_analysis_df()\n        self.logger.report_table(\n            \"Session Analysis\", name, table_plot=session_analysis_df\n        )\n        if self.stream_logs:\n            self.logger.report_text(\n                {\n                    \"action_records\": pd.DataFrame(self.action_records),\n                    \"session_analysis\": session_analysis_df,\n                }\n            )\n        if langchain_asset:\n            langchain_asset_path = Path(self.temp_dir.name, \"model.json\")\n            try:\n                langchain_asset.save(langchain_asset_path)\n                # Create output model and connect it to the task\n                output_model = clearml.OutputModel(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html"}
{"id": "4f45b7eb6cb8-11", "text": "output_model = clearml.OutputModel(\n                    task=self.task, config_text=load_json(langchain_asset_path)\n                )\n                output_model.update_weights(\n                    weights_filename=str(langchain_asset_path),\n                    auto_delete_file=False,\n                    target_filename=name,\n                )\n            except ValueError:\n                langchain_asset.save_agent(langchain_asset_path)\n                output_model = clearml.OutputModel(\n                    task=self.task, config_text=load_json(langchain_asset_path)\n                )\n                output_model.update_weights(\n                    weights_filename=str(langchain_asset_path),\n                    auto_delete_file=False,\n                    target_filename=name,\n                )\n            except NotImplementedError as e:\n                print(\"Could not save model.\")\n                print(repr(e))\n                pass\n        # Cleanup after adding everything to ClearML\n        self.task.flush(wait_for_uploads=True)\n        self.temp_dir.cleanup()\n        self.temp_dir = tempfile.TemporaryDirectory()\n        self.reset_callback_meta()\n        if finish:\n            self.task.close()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html"}
{"id": "c8b9ba99d355-0", "text": "Source code for langchain.callbacks.trubrics_callback\nimport os\nfrom typing import Any, Dict, List, Optional\nfrom uuid import UUID\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema import LLMResult\nfrom langchain.schema.messages import (\n    AIMessage,\n    BaseMessage,\n    ChatMessage,\n    FunctionMessage,\n    HumanMessage,\n    SystemMessage,\n)\ndef _convert_message_to_dict(message: BaseMessage) -> dict:\n    message_dict: Dict[str, Any]\n    if isinstance(message, ChatMessage):\n        message_dict = {\"role\": message.role, \"content\": message.content}\n    elif isinstance(message, HumanMessage):\n        message_dict = {\"role\": \"user\", \"content\": message.content}\n    elif isinstance(message, AIMessage):\n        message_dict = {\"role\": \"assistant\", \"content\": message.content}\n        if \"function_call\" in message.additional_kwargs:\n            message_dict[\"function_call\"] = message.additional_kwargs[\"function_call\"]\n            # If function call only, content is None not empty string\n            if message_dict[\"content\"] == \"\":\n                message_dict[\"content\"] = None\n    elif isinstance(message, SystemMessage):\n        message_dict = {\"role\": \"system\", \"content\": message.content}\n    elif isinstance(message, FunctionMessage):\n        message_dict = {\n            \"role\": \"function\",\n            \"content\": message.content,\n            \"name\": message.name,\n        }\n    else:\n        raise TypeError(f\"Got unknown type {message}\")\n    if \"name\" in message.additional_kwargs:\n        message_dict[\"name\"] = message.additional_kwargs[\"name\"]\n    return message_dict\n[docs]class TrubricsCallbackHandler(BaseCallbackHandler):\n    \"\"\"\n    Callback handler for Trubrics.\n    Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/trubrics_callback.html"}
{"id": "c8b9ba99d355-1", "text": "\"\"\"\n    Callback handler for Trubrics.\n    Args:\n        project: a trubrics project, default project is \"default\"\n        email: a trubrics account email, can equally be set in env variables\n        password: a trubrics account password, can equally be set in env variables\n        **kwargs: all other kwargs are parsed and set to trubrics prompt variables,\n            or added to the `metadata` dict\n    \"\"\"\n[docs]    def __init__(\n        self,\n        project: str = \"default\",\n        email: Optional[str] = None,\n        password: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        super().__init__()\n        try:\n            from trubrics import Trubrics\n        except ImportError:\n            raise ImportError(\n                \"The TrubricsCallbackHandler requires installation of \"\n                \"the trubrics package. \"\n                \"Please install it with `pip install trubrics`.\"\n            )\n        self.trubrics = Trubrics(\n            project=project,\n            email=email or os.environ[\"TRUBRICS_EMAIL\"],\n            password=password or os.environ[\"TRUBRICS_PASSWORD\"],\n        )\n        self.config_model: dict = {}\n        self.prompt: Optional[str] = None\n        self.messages: Optional[list] = None\n        self.trubrics_kwargs: Optional[dict] = kwargs if kwargs else None\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        self.prompt = prompts[0]\n[docs]    def on_chat_model_start(\n        self,\n        serialized: Dict[str, Any],\n        messages: List[List[BaseMessage]],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/trubrics_callback.html"}
{"id": "c8b9ba99d355-2", "text": "serialized: Dict[str, Any],\n        messages: List[List[BaseMessage]],\n        **kwargs: Any,\n    ) -> None:\n        self.messages = [_convert_message_to_dict(message) for message in messages[0]]\n        self.prompt = self.messages[-1][\"content\"]\n[docs]    def on_llm_end(self, response: LLMResult, run_id: UUID, **kwargs: Any) -> None:\n        tags = [\"langchain\"]\n        user_id = None\n        session_id = None\n        metadata: dict = {\"langchain_run_id\": run_id}\n        if self.messages:\n            metadata[\"messages\"] = self.messages\n        if self.trubrics_kwargs:\n            if self.trubrics_kwargs.get(\"tags\"):\n                tags.append(*self.trubrics_kwargs.pop(\"tags\"))\n            user_id = self.trubrics_kwargs.pop(\"user_id\", None)\n            session_id = self.trubrics_kwargs.pop(\"session_id\", None)\n            metadata.update(self.trubrics_kwargs)\n        for generation in response.generations:\n            self.trubrics.log_prompt(\n                config_model={\n                    \"model\": response.llm_output.get(\"model_name\")\n                    if response.llm_output\n                    else \"NA\"\n                },\n                prompt=self.prompt,\n                generation=generation[0].text,\n                user_id=user_id,\n                session_id=session_id,\n                tags=tags,\n                metadata=metadata,\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/trubrics_callback.html"}
{"id": "9a580bfae589-0", "text": "Source code for langchain.callbacks.human\nfrom typing import Any, Callable, Dict, Optional\nfrom uuid import UUID\nfrom langchain.callbacks.base import BaseCallbackHandler\ndef _default_approve(_input: str) -> bool:\n    msg = (\n        \"Do you approve of the following input? \"\n        \"Anything except 'Y'/'Yes' (case-insensitive) will be treated as a no.\"\n    )\n    msg += \"\\n\\n\" + _input + \"\\n\"\n    resp = input(msg)\n    return resp.lower() in (\"yes\", \"y\")\ndef _default_true(_: Dict[str, Any]) -> bool:\n    return True\n[docs]class HumanRejectedException(Exception):\n    \"\"\"Exception to raise when a person manually review and rejects a value.\"\"\"\n[docs]class HumanApprovalCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback for manually validating values.\"\"\"\n    raise_error: bool = True\n[docs]    def __init__(\n        self,\n        approve: Callable[[Any], bool] = _default_approve,\n        should_check: Callable[[Dict[str, Any]], bool] = _default_true,\n    ):\n        self._approve = approve\n        self._should_check = should_check\n[docs]    def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if self._should_check(serialized) and not self._approve(input_str):\n            raise HumanRejectedException(\n                f\"Inputs {input_str} to tool {serialized} were rejected.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/human.html"}
{"id": "673a381f6dea-0", "text": "Source code for langchain.callbacks.flyte_callback\n\"\"\"FlyteKit callback handler.\"\"\"\nfrom __future__ import annotations\nimport logging\nfrom copy import deepcopy\nfrom typing import TYPE_CHECKING, Any, Dict, List, Tuple\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.callbacks.utils import (\n    BaseMetadataCallbackHandler,\n    flatten_dict,\n    import_pandas,\n    import_spacy,\n    import_textstat,\n)\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\nif TYPE_CHECKING:\n    import flytekit\n    from flytekitplugins.deck import renderer\nlogger = logging.getLogger(__name__)\n[docs]def import_flytekit() -> Tuple[flytekit, renderer]:\n    \"\"\"Import flytekit and flytekitplugins-deck-standard.\"\"\"\n    try:\n        import flytekit  # noqa: F401\n        from flytekitplugins.deck import renderer  # noqa: F401\n    except ImportError:\n        raise ImportError(\n            \"To use the flyte callback manager you need\"\n            \"to have the `flytekit` and `flytekitplugins-deck-standard`\"\n            \"packages installed. Please install them with `pip install flytekit`\"\n            \"and `pip install flytekitplugins-deck-standard`.\"\n        )\n    return flytekit, renderer\n[docs]def analyze_text(\n    text: str,\n    nlp: Any = None,\n    textstat: Any = None,\n) -> dict:\n    \"\"\"Analyze text using textstat and spacy.\n    Parameters:\n        text (str): The text to analyze.\n        nlp (spacy.lang): The spacy language model to use for visualization.\n    Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html"}
{"id": "673a381f6dea-1", "text": "Returns:\n        (dict): A dictionary containing the complexity metrics and visualization\n            files serialized to HTML string.\n    \"\"\"\n    resp: Dict[str, Any] = {}\n    if textstat is not None:\n        text_complexity_metrics = {\n            \"flesch_reading_ease\": textstat.flesch_reading_ease(text),\n            \"flesch_kincaid_grade\": textstat.flesch_kincaid_grade(text),\n            \"smog_index\": textstat.smog_index(text),\n            \"coleman_liau_index\": textstat.coleman_liau_index(text),\n            \"automated_readability_index\": textstat.automated_readability_index(text),\n            \"dale_chall_readability_score\": textstat.dale_chall_readability_score(text),\n            \"difficult_words\": textstat.difficult_words(text),\n            \"linsear_write_formula\": textstat.linsear_write_formula(text),\n            \"gunning_fog\": textstat.gunning_fog(text),\n            \"fernandez_huerta\": textstat.fernandez_huerta(text),\n            \"szigriszt_pazos\": textstat.szigriszt_pazos(text),\n            \"gutierrez_polini\": textstat.gutierrez_polini(text),\n            \"crawford\": textstat.crawford(text),\n            \"gulpease_index\": textstat.gulpease_index(text),\n            \"osman\": textstat.osman(text),\n        }\n        resp.update({\"text_complexity_metrics\": text_complexity_metrics})\n        resp.update(text_complexity_metrics)\n    if nlp is not None:\n        spacy = import_spacy()\n        doc = nlp(text)\n        dep_out = spacy.displacy.render(  # type: ignore", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html"}
{"id": "673a381f6dea-2", "text": "dep_out = spacy.displacy.render(  # type: ignore\n            doc, style=\"dep\", jupyter=False, page=True\n        )\n        ent_out = spacy.displacy.render(  # type: ignore\n            doc, style=\"ent\", jupyter=False, page=True\n        )\n        text_visualizations = {\n            \"dependency_tree\": dep_out,\n            \"entities\": ent_out,\n        }\n        resp.update(text_visualizations)\n    return resp\n[docs]class FlyteCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):\n    \"\"\"This callback handler that is used within a Flyte task.\"\"\"\n[docs]    def __init__(self) -> None:\n        \"\"\"Initialize callback handler.\"\"\"\n        flytekit, renderer = import_flytekit()\n        self.pandas = import_pandas()\n        self.textstat = None\n        try:\n            self.textstat = import_textstat()\n        except ImportError:\n            logger.warning(\n                \"Textstat library is not installed. \\\n                It may result in the inability to log \\\n                certain metrics that can be captured with Textstat.\"\n            )\n        spacy = None\n        try:\n            spacy = import_spacy()\n        except ImportError:\n            logger.warning(\n                \"Spacy library is not installed. \\\n                It may result in the inability to log \\\n                certain metrics that can be captured with Spacy.\"\n            )\n        super().__init__()\n        self.nlp = None\n        if spacy:\n            try:\n                self.nlp = spacy.load(\"en_core_web_sm\")\n            except OSError:\n                logger.warning(\n                    \"FlyteCallbackHandler uses spacy's en_core_web_sm model\"\n                    \" for certain metrics. To download,\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html"}
{"id": "673a381f6dea-3", "text": "\" for certain metrics. To download,\"\n                    \" run the following command in your terminal:\"\n                    \" `python -m spacy download en_core_web_sm`\"\n                )\n        self.table_renderer = renderer.TableRenderer\n        self.markdown_renderer = renderer.MarkdownRenderer\n        self.deck = flytekit.Deck(\n            \"LangChain Metrics\",\n            self.markdown_renderer().to_html(\"## LangChain Metrics\"),\n        )\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when LLM starts.\"\"\"\n        self.step += 1\n        self.llm_starts += 1\n        self.starts += 1\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_llm_start\"})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.get_custom_callback_meta())\n        prompt_responses = []\n        for prompt in prompts:\n            prompt_responses.append(prompt)\n        resp.update({\"prompts\": prompt_responses})\n        self.deck.append(self.markdown_renderer().to_html(\"### LLM Start\"))\n        self.deck.append(\n            self.table_renderer().to_html(self.pandas.DataFrame([resp])) + \"\\n\"\n        )\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Run when LLM generates a new token.\"\"\"\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Run when LLM ends running.\"\"\"\n        self.step += 1\n        self.llm_ends += 1\n        self.ends += 1\n        resp: Dict[str, Any] = {}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html"}
{"id": "673a381f6dea-4", "text": "self.ends += 1\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_llm_end\"})\n        resp.update(flatten_dict(response.llm_output or {}))\n        resp.update(self.get_custom_callback_meta())\n        self.deck.append(self.markdown_renderer().to_html(\"### LLM End\"))\n        self.deck.append(self.table_renderer().to_html(self.pandas.DataFrame([resp])))\n        for generations in response.generations:\n            for generation in generations:\n                generation_resp = deepcopy(resp)\n                generation_resp.update(flatten_dict(generation.dict()))\n                if self.nlp or self.textstat:\n                    generation_resp.update(\n                        analyze_text(\n                            generation.text, nlp=self.nlp, textstat=self.textstat\n                        )\n                    )\n                    complexity_metrics: Dict[str, float] = generation_resp.pop(\n                        \"text_complexity_metrics\"\n                    )  # type: ignore  # noqa: E501\n                    self.deck.append(\n                        self.markdown_renderer().to_html(\"#### Text Complexity Metrics\")\n                    )\n                    self.deck.append(\n                        self.table_renderer().to_html(\n                            self.pandas.DataFrame([complexity_metrics])\n                        )\n                        + \"\\n\"\n                    )\n                    dependency_tree = generation_resp[\"dependency_tree\"]\n                    self.deck.append(\n                        self.markdown_renderer().to_html(\"#### Dependency Tree\")\n                    )\n                    self.deck.append(dependency_tree)\n                    entities = generation_resp[\"entities\"]\n                    self.deck.append(self.markdown_renderer().to_html(\"#### Entities\"))\n                    self.deck.append(entities)\n                else:\n                    self.deck.append(\n                        self.markdown_renderer().to_html(\"#### Generated Response\")\n                    )\n                    self.deck.append(self.markdown_renderer().to_html(generation.text))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html"}
{"id": "673a381f6dea-5", "text": ")\n                    self.deck.append(self.markdown_renderer().to_html(generation.text))\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when LLM errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when chain starts running.\"\"\"\n        self.step += 1\n        self.chain_starts += 1\n        self.starts += 1\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_chain_start\"})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.get_custom_callback_meta())\n        chain_input = \",\".join([f\"{k}={v}\" for k, v in inputs.items()])\n        input_resp = deepcopy(resp)\n        input_resp[\"inputs\"] = chain_input\n        self.deck.append(self.markdown_renderer().to_html(\"### Chain Start\"))\n        self.deck.append(\n            self.table_renderer().to_html(self.pandas.DataFrame([input_resp])) + \"\\n\"\n        )\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"Run when chain ends running.\"\"\"\n        self.step += 1\n        self.chain_ends += 1\n        self.ends += 1\n        resp: Dict[str, Any] = {}\n        chain_output = \",\".join([f\"{k}={v}\" for k, v in outputs.items()])\n        resp.update({\"action\": \"on_chain_end\", \"outputs\": chain_output})\n        resp.update(self.get_custom_callback_meta())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html"}
{"id": "673a381f6dea-6", "text": "resp.update(self.get_custom_callback_meta())\n        self.deck.append(self.markdown_renderer().to_html(\"### Chain End\"))\n        self.deck.append(\n            self.table_renderer().to_html(self.pandas.DataFrame([resp])) + \"\\n\"\n        )\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when chain errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_tool_start(\n        self, serialized: Dict[str, Any], input_str: str, **kwargs: Any\n    ) -> None:\n        \"\"\"Run when tool starts running.\"\"\"\n        self.step += 1\n        self.tool_starts += 1\n        self.starts += 1\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_tool_start\", \"input_str\": input_str})\n        resp.update(flatten_dict(serialized))\n        resp.update(self.get_custom_callback_meta())\n        self.deck.append(self.markdown_renderer().to_html(\"### Tool Start\"))\n        self.deck.append(\n            self.table_renderer().to_html(self.pandas.DataFrame([resp])) + \"\\n\"\n        )\n[docs]    def on_tool_end(self, output: str, **kwargs: Any) -> None:\n        \"\"\"Run when tool ends running.\"\"\"\n        self.step += 1\n        self.tool_ends += 1\n        self.ends += 1\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_tool_end\", \"output\": output})\n        resp.update(self.get_custom_callback_meta())\n        self.deck.append(self.markdown_renderer().to_html(\"### Tool End\"))\n        self.deck.append(\n            self.table_renderer().to_html(self.pandas.DataFrame([resp])) + \"\\n\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html"}
{"id": "673a381f6dea-7", "text": "self.table_renderer().to_html(self.pandas.DataFrame([resp])) + \"\\n\"\n        )\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when tool errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        \"\"\"\n        Run when agent is ending.\n        \"\"\"\n        self.step += 1\n        self.text_ctr += 1\n        resp: Dict[str, Any] = {}\n        resp.update({\"action\": \"on_text\", \"text\": text})\n        resp.update(self.get_custom_callback_meta())\n        self.deck.append(self.markdown_renderer().to_html(\"### On Text\"))\n        self.deck.append(\n            self.table_renderer().to_html(self.pandas.DataFrame([resp])) + \"\\n\"\n        )\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        \"\"\"Run when agent ends running.\"\"\"\n        self.step += 1\n        self.agent_ends += 1\n        self.ends += 1\n        resp: Dict[str, Any] = {}\n        resp.update(\n            {\n                \"action\": \"on_agent_finish\",\n                \"output\": finish.return_values[\"output\"],\n                \"log\": finish.log,\n            }\n        )\n        resp.update(self.get_custom_callback_meta())\n        self.deck.append(self.markdown_renderer().to_html(\"### Agent Finish\"))\n        self.deck.append(\n            self.table_renderer().to_html(self.pandas.DataFrame([resp])) + \"\\n\"\n        )\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Run on agent action.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html"}
{"id": "673a381f6dea-8", "text": "\"\"\"Run on agent action.\"\"\"\n        self.step += 1\n        self.tool_starts += 1\n        self.starts += 1\n        resp: Dict[str, Any] = {}\n        resp.update(\n            {\n                \"action\": \"on_agent_action\",\n                \"tool\": action.tool,\n                \"tool_input\": action.tool_input,\n                \"log\": action.log,\n            }\n        )\n        resp.update(self.get_custom_callback_meta())\n        self.deck.append(self.markdown_renderer().to_html(\"### Agent Action\"))\n        self.deck.append(\n            self.table_renderer().to_html(self.pandas.DataFrame([resp])) + \"\\n\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html"}
{"id": "aee86706e2fc-0", "text": "Source code for langchain.callbacks.context_callback\n\"\"\"Callback handler for Context AI\"\"\"\nimport os\nfrom typing import Any, Dict, List\nfrom uuid import UUID\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema import (\n    BaseMessage,\n    LLMResult,\n)\n[docs]def import_context() -> Any:\n    \"\"\"Import the `getcontext` package.\"\"\"\n    try:\n        import getcontext  # noqa: F401\n        from getcontext.generated.models import (\n            Conversation,\n            Message,\n            MessageRole,\n            Rating,\n        )\n        from getcontext.token import Credential  # noqa: F401\n    except ImportError:\n        raise ImportError(\n            \"To use the context callback manager you need to have the \"\n            \"`getcontext` python package installed (version >=0.3.0). \"\n            \"Please install it with `pip install --upgrade python-context`\"\n        )\n    return getcontext, Credential, Conversation, Message, MessageRole, Rating\n[docs]class ContextCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback Handler that records transcripts to the Context service.\n     (https://context.ai).\n    Keyword Args:\n        token (optional): The token with which to authenticate requests to Context.\n            Visit https://with.context.ai/settings to generate a token.\n            If not provided, the value of the `CONTEXT_TOKEN` environment\n            variable will be used.\n    Raises:\n        ImportError: if the `context-python` package is not installed.\n    Chat Example:\n        >>> from langchain.llms import ChatOpenAI\n        >>> from langchain.callbacks import ContextCallbackHandler\n        >>> context_callback = ContextCallbackHandler(\n        ...     token=\"<CONTEXT_TOKEN_HERE>\",\n        ... )\n        >>> chat = ChatOpenAI(\n        ...     temperature=0,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html"}
{"id": "aee86706e2fc-1", "text": ">>> chat = ChatOpenAI(\n        ...     temperature=0,\n        ...     headers={\"user_id\": \"123\"},\n        ...     callbacks=[context_callback],\n        ...     openai_api_key=\"API_KEY_HERE\",\n        ... )\n        >>> messages = [\n        ...     SystemMessage(content=\"You translate English to French.\"),\n        ...     HumanMessage(content=\"I love programming with LangChain.\"),\n        ... ]\n        >>> chat(messages)\n    Chain Example:\n        >>> from langchain.chains import LLMChain\n        >>> from langchain.chat_models import ChatOpenAI\n        >>> from langchain.callbacks import ContextCallbackHandler\n        >>> context_callback = ContextCallbackHandler(\n        ...     token=\"<CONTEXT_TOKEN_HERE>\",\n        ... )\n        >>> human_message_prompt = HumanMessagePromptTemplate(\n        ...     prompt=PromptTemplate(\n        ...         template=\"What is a good name for a company that makes {product}?\",\n        ...         input_variables=[\"product\"],\n        ...    ),\n        ... )\n        >>> chat_prompt_template = ChatPromptTemplate.from_messages(\n        ...   [human_message_prompt]\n        ... )\n        >>> callback = ContextCallbackHandler(token)\n        >>> # Note: the same callback object must be shared between the\n        ...   LLM and the chain.\n        >>> chat = ChatOpenAI(temperature=0.9, callbacks=[callback])\n        >>> chain = LLMChain(\n        ...   llm=chat,\n        ...   prompt=chat_prompt_template,\n        ...   callbacks=[callback]\n        ... )\n        >>> chain.run(\"colorful socks\")\n    \"\"\"\n[docs]    def __init__(self, token: str = \"\", verbose: bool = False, **kwargs: Any) -> None:\n        (\n            self.context,\n            self.credential,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html"}
{"id": "aee86706e2fc-2", "text": "(\n            self.context,\n            self.credential,\n            self.conversation_model,\n            self.message_model,\n            self.message_role_model,\n            self.rating_model,\n        ) = import_context()\n        token = token or os.environ.get(\"CONTEXT_TOKEN\") or \"\"\n        self.client = self.context.ContextAPI(credential=self.credential(token))\n        self.chain_run_id = None\n        self.llm_model = None\n        self.messages: List[Any] = []\n        self.metadata: Dict[str, str] = {}\n[docs]    def on_chat_model_start(\n        self,\n        serialized: Dict[str, Any],\n        messages: List[List[BaseMessage]],\n        *,\n        run_id: UUID,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when the chat model is started.\"\"\"\n        llm_model = kwargs.get(\"invocation_params\", {}).get(\"model\", None)\n        if llm_model is not None:\n            self.metadata[\"model\"] = llm_model\n        if len(messages) == 0:\n            return\n        for message in messages[0]:\n            role = self.message_role_model.SYSTEM\n            if message.type == \"human\":\n                role = self.message_role_model.USER\n            elif message.type == \"system\":\n                role = self.message_role_model.SYSTEM\n            elif message.type == \"ai\":\n                role = self.message_role_model.ASSISTANT\n            self.messages.append(\n                self.message_model(\n                    message=message.content,\n                    role=role,\n                )\n            )\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Run when LLM ends.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html"}
{"id": "aee86706e2fc-3", "text": "\"\"\"Run when LLM ends.\"\"\"\n        if len(response.generations) == 0 or len(response.generations[0]) == 0:\n            return\n        if not self.chain_run_id:\n            generation = response.generations[0][0]\n            self.messages.append(\n                self.message_model(\n                    message=generation.text,\n                    role=self.message_role_model.ASSISTANT,\n                )\n            )\n            self._log_conversation()\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when chain starts.\"\"\"\n        self.chain_run_id = kwargs.get(\"run_id\", None)\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"Run when chain ends.\"\"\"\n        self.messages.append(\n            self.message_model(\n                message=outputs[\"text\"],\n                role=self.message_role_model.ASSISTANT,\n            )\n        )\n        self._log_conversation()\n        self.chain_run_id = None\n    def _log_conversation(self) -> None:\n        \"\"\"Log the conversation to the context API.\"\"\"\n        if len(self.messages) == 0:\n            return\n        self.client.log.conversation_upsert(\n            body={\n                \"conversation\": self.conversation_model(\n                    messages=self.messages,\n                    metadata=self.metadata,\n                )\n            }\n        )\n        self.messages = []\n        self.metadata = {}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html"}
{"id": "53ee3b064a1c-0", "text": "Source code for langchain.callbacks.aim_callback\nfrom copy import deepcopy\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\n[docs]def import_aim() -> Any:\n    \"\"\"Import the aim python package and raise an error if it is not installed.\"\"\"\n    try:\n        import aim\n    except ImportError:\n        raise ImportError(\n            \"To use the Aim callback manager you need to have the\"\n            \" `aim` python package installed.\"\n            \"Please install it with `pip install aim`\"\n        )\n    return aim\n[docs]class BaseMetadataCallbackHandler:\n    \"\"\"This class handles the metadata and associated function states for callbacks.\n    Attributes:\n        step (int): The current step.\n        starts (int): The number of times the start method has been called.\n        ends (int): The number of times the end method has been called.\n        errors (int): The number of times the error method has been called.\n        text_ctr (int): The number of times the text method has been called.\n        ignore_llm_ (bool): Whether to ignore llm callbacks.\n        ignore_chain_ (bool): Whether to ignore chain callbacks.\n        ignore_agent_ (bool): Whether to ignore agent callbacks.\n        ignore_retriever_ (bool): Whether to ignore retriever callbacks.\n        always_verbose_ (bool): Whether to always be verbose.\n        chain_starts (int): The number of times the chain start method has been called.\n        chain_ends (int): The number of times the chain end method has been called.\n        llm_starts (int): The number of times the llm start method has been called.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html"}
{"id": "53ee3b064a1c-1", "text": "llm_ends (int): The number of times the llm end method has been called.\n        llm_streams (int): The number of times the text method has been called.\n        tool_starts (int): The number of times the tool start method has been called.\n        tool_ends (int): The number of times the tool end method has been called.\n        agent_ends (int): The number of times the agent end method has been called.\n    \"\"\"\n[docs]    def __init__(self) -> None:\n        self.step = 0\n        self.starts = 0\n        self.ends = 0\n        self.errors = 0\n        self.text_ctr = 0\n        self.ignore_llm_ = False\n        self.ignore_chain_ = False\n        self.ignore_agent_ = False\n        self.ignore_retriever_ = False\n        self.always_verbose_ = False\n        self.chain_starts = 0\n        self.chain_ends = 0\n        self.llm_starts = 0\n        self.llm_ends = 0\n        self.llm_streams = 0\n        self.tool_starts = 0\n        self.tool_ends = 0\n        self.agent_ends = 0\n    @property\n    def always_verbose(self) -> bool:\n        \"\"\"Whether to call verbose callbacks even if verbose is False.\"\"\"\n        return self.always_verbose_\n    @property\n    def ignore_llm(self) -> bool:\n        \"\"\"Whether to ignore LLM callbacks.\"\"\"\n        return self.ignore_llm_\n    @property\n    def ignore_chain(self) -> bool:\n        \"\"\"Whether to ignore chain callbacks.\"\"\"\n        return self.ignore_chain_\n    @property\n    def ignore_agent(self) -> bool:\n        \"\"\"Whether to ignore agent callbacks.\"\"\"\n        return self.ignore_agent_\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html"}
{"id": "53ee3b064a1c-2", "text": "\"\"\"Whether to ignore agent callbacks.\"\"\"\n        return self.ignore_agent_\n    @property\n    def ignore_retriever(self) -> bool:\n        \"\"\"Whether to ignore retriever callbacks.\"\"\"\n        return self.ignore_retriever_\n[docs]    def get_custom_callback_meta(self) -> Dict[str, Any]:\n        return {\n            \"step\": self.step,\n            \"starts\": self.starts,\n            \"ends\": self.ends,\n            \"errors\": self.errors,\n            \"text_ctr\": self.text_ctr,\n            \"chain_starts\": self.chain_starts,\n            \"chain_ends\": self.chain_ends,\n            \"llm_starts\": self.llm_starts,\n            \"llm_ends\": self.llm_ends,\n            \"llm_streams\": self.llm_streams,\n            \"tool_starts\": self.tool_starts,\n            \"tool_ends\": self.tool_ends,\n            \"agent_ends\": self.agent_ends,\n        }\n[docs]    def reset_callback_meta(self) -> None:\n        \"\"\"Reset the callback metadata.\"\"\"\n        self.step = 0\n        self.starts = 0\n        self.ends = 0\n        self.errors = 0\n        self.text_ctr = 0\n        self.ignore_llm_ = False\n        self.ignore_chain_ = False\n        self.ignore_agent_ = False\n        self.always_verbose_ = False\n        self.chain_starts = 0\n        self.chain_ends = 0\n        self.llm_starts = 0\n        self.llm_ends = 0\n        self.llm_streams = 0\n        self.tool_starts = 0\n        self.tool_ends = 0\n        self.agent_ends = 0\n        return None\n[docs]class AimCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):\n    \"\"\"Callback Handler that logs to Aim.\n    Parameters:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html"}
{"id": "53ee3b064a1c-3", "text": "\"\"\"Callback Handler that logs to Aim.\n    Parameters:\n        repo (:obj:`str`, optional): Aim repository path or Repo object to which\n            Run object is bound. If skipped, default Repo is used.\n        experiment_name (:obj:`str`, optional): Sets Run's `experiment` property.\n            'default' if not specified. Can be used later to query runs/sequences.\n        system_tracking_interval (:obj:`int`, optional): Sets the tracking interval\n            in seconds for system usage metrics (CPU, Memory, etc.). Set to `None`\n             to disable system metrics tracking.\n        log_system_params (:obj:`bool`, optional): Enable/Disable logging of system\n            params such as installed packages, git info, environment variables, etc.\n    This handler will utilize the associated callback method called and formats\n    the input of each callback function with metadata regarding the state of LLM run\n    and then logs the response to Aim.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        repo: Optional[str] = None,\n        experiment_name: Optional[str] = None,\n        system_tracking_interval: Optional[int] = 10,\n        log_system_params: bool = True,\n    ) -> None:\n        \"\"\"Initialize callback handler.\"\"\"\n        super().__init__()\n        aim = import_aim()\n        self.repo = repo\n        self.experiment_name = experiment_name\n        self.system_tracking_interval = system_tracking_interval\n        self.log_system_params = log_system_params\n        self._run = aim.Run(\n            repo=self.repo,\n            experiment=self.experiment_name,\n            system_tracking_interval=self.system_tracking_interval,\n            log_system_params=self.log_system_params,\n        )\n        self._run_hash = self._run.hash\n        self.action_records: list = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html"}
{"id": "53ee3b064a1c-4", "text": "self._run_hash = self._run.hash\n        self.action_records: list = []\n[docs]    def setup(self, **kwargs: Any) -> None:\n        aim = import_aim()\n        if not self._run:\n            if self._run_hash:\n                self._run = aim.Run(\n                    self._run_hash,\n                    repo=self.repo,\n                    system_tracking_interval=self.system_tracking_interval,\n                )\n            else:\n                self._run = aim.Run(\n                    repo=self.repo,\n                    experiment=self.experiment_name,\n                    system_tracking_interval=self.system_tracking_interval,\n                    log_system_params=self.log_system_params,\n                )\n                self._run_hash = self._run.hash\n        if kwargs:\n            for key, value in kwargs.items():\n                self._run.set(key, value, strict=False)\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when LLM starts.\"\"\"\n        aim = import_aim()\n        self.step += 1\n        self.llm_starts += 1\n        self.starts += 1\n        resp = {\"action\": \"on_llm_start\"}\n        resp.update(self.get_custom_callback_meta())\n        prompts_res = deepcopy(prompts)\n        self._run.track(\n            [aim.Text(prompt) for prompt in prompts_res],\n            name=\"on_llm_start\",\n            context=resp,\n        )\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Run when LLM ends running.\"\"\"\n        aim = import_aim()\n        self.step += 1\n        self.llm_ends += 1\n        self.ends += 1", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html"}
{"id": "53ee3b064a1c-5", "text": "self.llm_ends += 1\n        self.ends += 1\n        resp = {\"action\": \"on_llm_end\"}\n        resp.update(self.get_custom_callback_meta())\n        response_res = deepcopy(response)\n        generated = [\n            aim.Text(generation.text)\n            for generations in response_res.generations\n            for generation in generations\n        ]\n        self._run.track(\n            generated,\n            name=\"on_llm_end\",\n            context=resp,\n        )\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Run when LLM generates a new token.\"\"\"\n        self.step += 1\n        self.llm_streams += 1\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when LLM errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when chain starts running.\"\"\"\n        aim = import_aim()\n        self.step += 1\n        self.chain_starts += 1\n        self.starts += 1\n        resp = {\"action\": \"on_chain_start\"}\n        resp.update(self.get_custom_callback_meta())\n        inputs_res = deepcopy(inputs)\n        self._run.track(\n            aim.Text(inputs_res[\"input\"]), name=\"on_chain_start\", context=resp\n        )\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        \"\"\"Run when chain ends running.\"\"\"\n        aim = import_aim()\n        self.step += 1", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html"}
{"id": "53ee3b064a1c-6", "text": "aim = import_aim()\n        self.step += 1\n        self.chain_ends += 1\n        self.ends += 1\n        resp = {\"action\": \"on_chain_end\"}\n        resp.update(self.get_custom_callback_meta())\n        outputs_res = deepcopy(outputs)\n        self._run.track(\n            aim.Text(outputs_res[\"output\"]), name=\"on_chain_end\", context=resp\n        )\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when chain errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_tool_start(\n        self, serialized: Dict[str, Any], input_str: str, **kwargs: Any\n    ) -> None:\n        \"\"\"Run when tool starts running.\"\"\"\n        aim = import_aim()\n        self.step += 1\n        self.tool_starts += 1\n        self.starts += 1\n        resp = {\"action\": \"on_tool_start\"}\n        resp.update(self.get_custom_callback_meta())\n        self._run.track(aim.Text(input_str), name=\"on_tool_start\", context=resp)\n[docs]    def on_tool_end(self, output: str, **kwargs: Any) -> None:\n        \"\"\"Run when tool ends running.\"\"\"\n        aim = import_aim()\n        self.step += 1\n        self.tool_ends += 1\n        self.ends += 1\n        resp = {\"action\": \"on_tool_end\"}\n        resp.update(self.get_custom_callback_meta())\n        self._run.track(aim.Text(output), name=\"on_tool_end\", context=resp)\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Run when tool errors.\"\"\"\n        self.step += 1", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html"}
{"id": "53ee3b064a1c-7", "text": "\"\"\"Run when tool errors.\"\"\"\n        self.step += 1\n        self.errors += 1\n[docs]    def on_text(self, text: str, **kwargs: Any) -> None:\n        \"\"\"\n        Run when agent is ending.\n        \"\"\"\n        self.step += 1\n        self.text_ctr += 1\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:\n        \"\"\"Run when agent ends running.\"\"\"\n        aim = import_aim()\n        self.step += 1\n        self.agent_ends += 1\n        self.ends += 1\n        resp = {\"action\": \"on_agent_finish\"}\n        resp.update(self.get_custom_callback_meta())\n        finish_res = deepcopy(finish)\n        text = \"OUTPUT:\\n{}\\n\\nLOG:\\n{}\".format(\n            finish_res.return_values[\"output\"], finish_res.log\n        )\n        self._run.track(aim.Text(text), name=\"on_agent_finish\", context=resp)\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Run on agent action.\"\"\"\n        aim = import_aim()\n        self.step += 1\n        self.tool_starts += 1\n        self.starts += 1\n        resp = {\n            \"action\": \"on_agent_action\",\n            \"tool\": action.tool,\n        }\n        resp.update(self.get_custom_callback_meta())\n        action_res = deepcopy(action)\n        text = \"TOOL INPUT:\\n{}\\n\\nLOG:\\n{}\".format(\n            action_res.tool_input, action_res.log\n        )\n        self._run.track(aim.Text(text), name=\"on_agent_action\", context=resp)\n[docs]    def flush_tracker(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html"}
{"id": "53ee3b064a1c-8", "text": "[docs]    def flush_tracker(\n        self,\n        repo: Optional[str] = None,\n        experiment_name: Optional[str] = None,\n        system_tracking_interval: Optional[int] = 10,\n        log_system_params: bool = True,\n        langchain_asset: Any = None,\n        reset: bool = True,\n        finish: bool = False,\n    ) -> None:\n        \"\"\"Flush the tracker and reset the session.\n        Args:\n            repo (:obj:`str`, optional): Aim repository path or Repo object to which\n                Run object is bound. If skipped, default Repo is used.\n            experiment_name (:obj:`str`, optional): Sets Run's `experiment` property.\n                'default' if not specified. Can be used later to query runs/sequences.\n            system_tracking_interval (:obj:`int`, optional): Sets the tracking interval\n                in seconds for system usage metrics (CPU, Memory, etc.). Set to `None`\n                 to disable system metrics tracking.\n            log_system_params (:obj:`bool`, optional): Enable/Disable logging of system\n                params such as installed packages, git info, environment variables, etc.\n            langchain_asset: The langchain asset to save.\n            reset: Whether to reset the session.\n            finish: Whether to finish the run.\n            Returns:\n                None\n        \"\"\"\n        if langchain_asset:\n            try:\n                for key, value in langchain_asset.dict().items():\n                    self._run.set(key, value, strict=False)\n            except Exception:\n                pass\n        if finish or reset:\n            self._run.close()\n            self.reset_callback_meta()\n        if reset:\n            self.__init__(  # type: ignore\n                repo=repo if repo else self.repo,\n                experiment_name=experiment_name", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html"}
{"id": "53ee3b064a1c-9", "text": "repo=repo if repo else self.repo,\n                experiment_name=experiment_name\n                if experiment_name\n                else self.experiment_name,\n                system_tracking_interval=system_tracking_interval\n                if system_tracking_interval\n                else self.system_tracking_interval,\n                log_system_params=log_system_params\n                if log_system_params\n                else self.log_system_params,\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html"}
{"id": "b9dd31a821f5-0", "text": "Source code for langchain.callbacks.promptlayer_callback\n\"\"\"Callback handler for promptlayer.\"\"\"\nfrom __future__ import annotations\nimport datetime\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple\nfrom uuid import UUID\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema import (\n    ChatGeneration,\n    LLMResult,\n)\nfrom langchain.schema.messages import (\n    AIMessage,\n    BaseMessage,\n    ChatMessage,\n    HumanMessage,\n    SystemMessage,\n)\nif TYPE_CHECKING:\n    import promptlayer\ndef _lazy_import_promptlayer() -> promptlayer:\n    \"\"\"Lazy import promptlayer to avoid circular imports.\"\"\"\n    try:\n        import promptlayer\n    except ImportError:\n        raise ImportError(\n            \"The PromptLayerCallbackHandler requires the promptlayer package. \"\n            \" Please install it with `pip install promptlayer`.\"\n        )\n    return promptlayer\n[docs]class PromptLayerCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback handler for promptlayer.\"\"\"\n[docs]    def __init__(\n        self,\n        pl_id_callback: Optional[Callable[..., Any]] = None,\n        pl_tags: Optional[List[str]] = None,\n    ) -> None:\n        \"\"\"Initialize the PromptLayerCallbackHandler.\"\"\"\n        _lazy_import_promptlayer()\n        self.pl_id_callback = pl_id_callback\n        self.pl_tags = pl_tags or []\n        self.runs: Dict[UUID, Dict[str, Any]] = {}\n[docs]    def on_chat_model_start(\n        self,\n        serialized: Dict[str, Any],\n        messages: List[List[BaseMessage]],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html"}
{"id": "b9dd31a821f5-1", "text": "tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Any:\n        self.runs[run_id] = {\n            \"messages\": [self._create_message_dicts(m)[0] for m in messages],\n            \"invocation_params\": kwargs.get(\"invocation_params\", {}),\n            \"name\": \".\".join(serialized[\"id\"]),\n            \"request_start_time\": datetime.datetime.now().timestamp(),\n            \"tags\": tags,\n        }\n[docs]    def on_llm_start(\n        self,\n        serialized: Dict[str, Any],\n        prompts: List[str],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Any:\n        self.runs[run_id] = {\n            \"prompts\": prompts,\n            \"invocation_params\": kwargs.get(\"invocation_params\", {}),\n            \"name\": \".\".join(serialized[\"id\"]),\n            \"request_start_time\": datetime.datetime.now().timestamp(),\n            \"tags\": tags,\n        }\n[docs]    def on_llm_end(\n        self,\n        response: LLMResult,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> None:\n        from promptlayer.utils import get_api_key, promptlayer_api_request\n        run_info = self.runs.get(run_id, {})\n        if not run_info:\n            return\n        run_info[\"request_end_time\"] = datetime.datetime.now().timestamp()\n        for i in range(len(response.generations)):\n            generation = response.generations[i][0]\n            resp = {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html"}
{"id": "b9dd31a821f5-2", "text": "generation = response.generations[i][0]\n            resp = {\n                \"text\": generation.text,\n                \"llm_output\": response.llm_output,\n            }\n            model_params = run_info.get(\"invocation_params\", {})\n            is_chat_model = run_info.get(\"messages\", None) is not None\n            model_input = (\n                run_info.get(\"messages\", [])[i]\n                if is_chat_model\n                else [run_info.get(\"prompts\", [])[i]]\n            )\n            model_response = (\n                [self._convert_message_to_dict(generation.message)]\n                if is_chat_model and isinstance(generation, ChatGeneration)\n                else resp\n            )\n            pl_request_id = promptlayer_api_request(\n                run_info.get(\"name\"),\n                \"langchain\",\n                model_input,\n                model_params,\n                self.pl_tags,\n                model_response,\n                run_info.get(\"request_start_time\"),\n                run_info.get(\"request_end_time\"),\n                get_api_key(),\n                return_pl_id=bool(self.pl_id_callback is not None),\n                metadata={\n                    \"_langchain_run_id\": str(run_id),\n                    \"_langchain_parent_run_id\": str(parent_run_id),\n                    \"_langchain_tags\": str(run_info.get(\"tags\", [])),\n                },\n            )\n            if self.pl_id_callback:\n                self.pl_id_callback(pl_request_id)\n    def _convert_message_to_dict(self, message: BaseMessage) -> Dict[str, Any]:\n        if isinstance(message, HumanMessage):\n            message_dict = {\"role\": \"user\", \"content\": message.content}\n        elif isinstance(message, AIMessage):\n            message_dict = {\"role\": \"assistant\", \"content\": message.content}\n        elif isinstance(message, SystemMessage):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html"}
{"id": "b9dd31a821f5-3", "text": "elif isinstance(message, SystemMessage):\n            message_dict = {\"role\": \"system\", \"content\": message.content}\n        elif isinstance(message, ChatMessage):\n            message_dict = {\"role\": message.role, \"content\": message.content}\n        else:\n            raise ValueError(f\"Got unknown type {message}\")\n        if \"name\" in message.additional_kwargs:\n            message_dict[\"name\"] = message.additional_kwargs[\"name\"]\n        return message_dict\n    def _create_message_dicts(\n        self, messages: List[BaseMessage]\n    ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:\n        params: Dict[str, Any] = {}\n        message_dicts = [self._convert_message_to_dict(m) for m in messages]\n        return message_dicts, params", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html"}
{"id": "db9948796294-0", "text": "Source code for langchain.callbacks.streamlit.mutable_expander\nfrom __future__ import annotations\nfrom enum import Enum\nfrom typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional\nif TYPE_CHECKING:\n    from streamlit.delta_generator import DeltaGenerator\n    from streamlit.type_util import SupportsStr\n[docs]class ChildType(Enum):\n    \"\"\"The enumerator of the child type.\"\"\"\n    MARKDOWN = \"MARKDOWN\"\n    EXCEPTION = \"EXCEPTION\"\n[docs]class ChildRecord(NamedTuple):\n    \"\"\"The child record as a NamedTuple.\"\"\"\n    type: ChildType\n    kwargs: Dict[str, Any]\n    dg: DeltaGenerator\n[docs]class MutableExpander:\n    \"\"\"A Streamlit expander that can be renamed and dynamically expanded/collapsed.\"\"\"\n[docs]    def __init__(self, parent_container: DeltaGenerator, label: str, expanded: bool):\n        \"\"\"Create a new MutableExpander.\n        Parameters\n        ----------\n        parent_container\n            The `st.container` that the expander will be created inside.\n            The expander transparently deletes and recreates its underlying\n            `st.expander` instance when its label changes, and it uses\n            `parent_container` to ensure it recreates this underlying expander in the\n            same location onscreen.\n        label\n            The expander's initial label.\n        expanded\n            The expander's initial `expanded` value.\n        \"\"\"\n        self._label = label\n        self._expanded = expanded\n        self._parent_cursor = parent_container.empty()\n        self._container = self._parent_cursor.expander(label, expanded)\n        self._child_records: List[ChildRecord] = []\n    @property\n    def label(self) -> str:\n        \"\"\"The expander's label string.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html"}
{"id": "db9948796294-1", "text": "def label(self) -> str:\n        \"\"\"The expander's label string.\"\"\"\n        return self._label\n    @property\n    def expanded(self) -> bool:\n        \"\"\"True if the expander was created with `expanded=True`.\"\"\"\n        return self._expanded\n[docs]    def clear(self) -> None:\n        \"\"\"Remove the container and its contents entirely. A cleared container can't\n        be reused.\n        \"\"\"\n        self._container = self._parent_cursor.empty()\n        self._child_records.clear()\n[docs]    def append_copy(self, other: MutableExpander) -> None:\n        \"\"\"Append a copy of another MutableExpander's children to this\n        MutableExpander.\n        \"\"\"\n        other_records = other._child_records.copy()\n        for record in other_records:\n            self._create_child(record.type, record.kwargs)\n[docs]    def update(\n        self, *, new_label: Optional[str] = None, new_expanded: Optional[bool] = None\n    ) -> None:\n        \"\"\"Change the expander's label and expanded state\"\"\"\n        if new_label is None:\n            new_label = self._label\n        if new_expanded is None:\n            new_expanded = self._expanded\n        if self._label == new_label and self._expanded == new_expanded:\n            # No change!\n            return\n        self._label = new_label\n        self._expanded = new_expanded\n        self._container = self._parent_cursor.expander(new_label, new_expanded)\n        prev_records = self._child_records\n        self._child_records = []\n        # Replay all children into the new container\n        for record in prev_records:\n            self._create_child(record.type, record.kwargs)\n[docs]    def markdown(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html"}
{"id": "db9948796294-2", "text": "[docs]    def markdown(\n        self,\n        body: SupportsStr,\n        unsafe_allow_html: bool = False,\n        *,\n        help: Optional[str] = None,\n        index: Optional[int] = None,\n    ) -> int:\n        \"\"\"Add a Markdown element to the container and return its index.\"\"\"\n        kwargs = {\"body\": body, \"unsafe_allow_html\": unsafe_allow_html, \"help\": help}\n        new_dg = self._get_dg(index).markdown(**kwargs)  # type: ignore[arg-type]\n        record = ChildRecord(ChildType.MARKDOWN, kwargs, new_dg)\n        return self._add_record(record, index)\n[docs]    def exception(\n        self, exception: BaseException, *, index: Optional[int] = None\n    ) -> int:\n        \"\"\"Add an Exception element to the container and return its index.\"\"\"\n        kwargs = {\"exception\": exception}\n        new_dg = self._get_dg(index).exception(**kwargs)\n        record = ChildRecord(ChildType.EXCEPTION, kwargs, new_dg)\n        return self._add_record(record, index)\n    def _create_child(self, type: ChildType, kwargs: Dict[str, Any]) -> None:\n        \"\"\"Create a new child with the given params\"\"\"\n        if type == ChildType.MARKDOWN:\n            self.markdown(**kwargs)\n        elif type == ChildType.EXCEPTION:\n            self.exception(**kwargs)\n        else:\n            raise RuntimeError(f\"Unexpected child type {type}\")\n    def _add_record(self, record: ChildRecord, index: Optional[int]) -> int:\n        \"\"\"Add a ChildRecord to self._children. If `index` is specified, replace\n        the existing record at that index. Otherwise, append the record to the", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html"}
{"id": "db9948796294-3", "text": "the existing record at that index. Otherwise, append the record to the\n        end of the list.\n        Return the index of the added record.\n        \"\"\"\n        if index is not None:\n            # Replace existing child\n            self._child_records[index] = record\n            return index\n        # Append new child\n        self._child_records.append(record)\n        return len(self._child_records) - 1\n    def _get_dg(self, index: Optional[int]) -> DeltaGenerator:\n        if index is not None:\n            # Existing index: reuse child's DeltaGenerator\n            assert 0 <= index < len(self._child_records), f\"Bad index: {index}\"\n            return self._child_records[index].dg\n        # No index: use container's DeltaGenerator\n        return self._container", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html"}
{"id": "d770c79a4540-0", "text": "Source code for langchain.callbacks.streamlit.streamlit_callback_handler\n\"\"\"Callback Handler that prints to streamlit.\"\"\"\nfrom __future__ import annotations\nfrom enum import Enum\nfrom typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.callbacks.streamlit.mutable_expander import MutableExpander\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\nif TYPE_CHECKING:\n    from streamlit.delta_generator import DeltaGenerator\ndef _convert_newlines(text: str) -> str:\n    \"\"\"Convert newline characters to markdown newline sequences\n    (space, space, newline).\n    \"\"\"\n    return text.replace(\"\\n\", \"  \\n\")\nCHECKMARK_EMOJI = \"\u2705\"\nTHINKING_EMOJI = \":thinking_face:\"\nHISTORY_EMOJI = \":books:\"\nEXCEPTION_EMOJI = \"\u26a0\ufe0f\"\n[docs]class LLMThoughtState(Enum):\n    \"\"\"Enumerator of the LLMThought state.\"\"\"\n    # The LLM is thinking about what to do next. We don't know which tool we'll run.\n    THINKING = \"THINKING\"\n    # The LLM has decided to run a tool. We don't have results from the tool yet.\n    RUNNING_TOOL = \"RUNNING_TOOL\"\n    # We have results from the tool.\n    COMPLETE = \"COMPLETE\"\n[docs]class ToolRecord(NamedTuple):\n    \"\"\"The tool record as a NamedTuple.\"\"\"\n    name: str\n    input_str: str\n[docs]class LLMThoughtLabeler:\n    \"\"\"\n    Generates markdown labels for LLMThought containers. Pass a custom\n    subclass of this to StreamlitCallbackHandler to override its default\n    labeling logic.\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html"}
{"id": "d770c79a4540-1", "text": "labeling logic.\n    \"\"\"\n[docs]    def get_initial_label(self) -> str:\n        \"\"\"Return the markdown label for a new LLMThought that doesn't have\n        an associated tool yet.\n        \"\"\"\n        return f\"{THINKING_EMOJI} **Thinking...**\"\n[docs]    def get_tool_label(self, tool: ToolRecord, is_complete: bool) -> str:\n        \"\"\"Return the label for an LLMThought that has an associated\n        tool.\n        Parameters\n        ----------\n        tool\n            The tool's ToolRecord\n        is_complete\n            True if the thought is complete; False if the thought\n            is still receiving input.\n        Returns\n        -------\n        The markdown label for the thought's container.\n        \"\"\"\n        input = tool.input_str\n        name = tool.name\n        emoji = CHECKMARK_EMOJI if is_complete else THINKING_EMOJI\n        if name == \"_Exception\":\n            emoji = EXCEPTION_EMOJI\n            name = \"Parsing error\"\n        idx = min([60, len(input)])\n        input = input[0:idx]\n        if len(tool.input_str) > idx:\n            input = input + \"...\"\n        input = input.replace(\"\\n\", \" \")\n        label = f\"{emoji} **{name}:** {input}\"\n        return label\n[docs]    def get_history_label(self) -> str:\n        \"\"\"Return a markdown label for the special 'history' container\n        that contains overflow thoughts.\n        \"\"\"\n        return f\"{HISTORY_EMOJI} **History**\"\n[docs]    def get_final_agent_thought_label(self) -> str:\n        \"\"\"Return the markdown label for the agent's final thought -\n        the \"Now I have the answer\" thought, that doesn't involve\n        a tool.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html"}
{"id": "d770c79a4540-2", "text": "a tool.\n        \"\"\"\n        return f\"{CHECKMARK_EMOJI} **Complete!**\"\n[docs]class LLMThought:\n    \"\"\"A thought in the LLM's thought stream.\"\"\"\n[docs]    def __init__(\n        self,\n        parent_container: DeltaGenerator,\n        labeler: LLMThoughtLabeler,\n        expanded: bool,\n        collapse_on_complete: bool,\n    ):\n        \"\"\"Initialize the LLMThought.\n        Args:\n            parent_container: The container we're writing into.\n            labeler: The labeler to use for this thought.\n            expanded: Whether the thought should be expanded by default.\n            collapse_on_complete: Whether the thought should be collapsed.\n        \"\"\"\n        self._container = MutableExpander(\n            parent_container=parent_container,\n            label=labeler.get_initial_label(),\n            expanded=expanded,\n        )\n        self._state = LLMThoughtState.THINKING\n        self._llm_token_stream = \"\"\n        self._llm_token_writer_idx: Optional[int] = None\n        self._last_tool: Optional[ToolRecord] = None\n        self._collapse_on_complete = collapse_on_complete\n        self._labeler = labeler\n    @property\n    def container(self) -> MutableExpander:\n        \"\"\"The container we're writing into.\"\"\"\n        return self._container\n    @property\n    def last_tool(self) -> Optional[ToolRecord]:\n        \"\"\"The last tool executed by this thought\"\"\"\n        return self._last_tool\n    def _reset_llm_token_stream(self) -> None:\n        self._llm_token_stream = \"\"\n        self._llm_token_writer_idx = None\n[docs]    def on_llm_start(self, serialized: Dict[str, Any], prompts: List[str]) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html"}
{"id": "d770c79a4540-3", "text": "self._reset_llm_token_stream()\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        # This is only called when the LLM is initialized with `streaming=True`\n        self._llm_token_stream += _convert_newlines(token)\n        self._llm_token_writer_idx = self._container.markdown(\n            self._llm_token_stream, index=self._llm_token_writer_idx\n        )\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        # `response` is the concatenation of all the tokens received by the LLM.\n        # If we're receiving streaming tokens from `on_llm_new_token`, this response\n        # data is redundant\n        self._reset_llm_token_stream()\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        self._container.markdown(\"**LLM encountered an error...**\")\n        self._container.exception(error)\n[docs]    def on_tool_start(\n        self, serialized: Dict[str, Any], input_str: str, **kwargs: Any\n    ) -> None:\n        # Called with the name of the tool we're about to run (in `serialized[name]`),\n        # and its input. We change our container's label to be the tool name.\n        self._state = LLMThoughtState.RUNNING_TOOL\n        tool_name = serialized[\"name\"]\n        self._last_tool = ToolRecord(name=tool_name, input_str=input_str)\n        self._container.update(\n            new_label=self._labeler.get_tool_label(self._last_tool, is_complete=False)\n        )\n[docs]    def on_tool_end(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html"}
{"id": "d770c79a4540-4", "text": ")\n[docs]    def on_tool_end(\n        self,\n        output: str,\n        color: Optional[str] = None,\n        observation_prefix: Optional[str] = None,\n        llm_prefix: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        self._container.markdown(f\"**{output}**\")\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        self._container.markdown(\"**Tool encountered an error...**\")\n        self._container.exception(error)\n[docs]    def on_agent_action(\n        self, action: AgentAction, color: Optional[str] = None, **kwargs: Any\n    ) -> Any:\n        # Called when we're about to kick off a new tool. The `action` data\n        # tells us the tool we're about to use, and the input we'll give it.\n        # We don't output anything here, because we'll receive this same data\n        # when `on_tool_start` is called immediately after.\n        pass\n[docs]    def complete(self, final_label: Optional[str] = None) -> None:\n        \"\"\"Finish the thought.\"\"\"\n        if final_label is None and self._state == LLMThoughtState.RUNNING_TOOL:\n            assert (\n                self._last_tool is not None\n            ), \"_last_tool should never be null when _state == RUNNING_TOOL\"\n            final_label = self._labeler.get_tool_label(\n                self._last_tool, is_complete=True\n            )\n        self._state = LLMThoughtState.COMPLETE\n        if self._collapse_on_complete:\n            self._container.update(new_label=final_label, new_expanded=False)\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html"}
{"id": "d770c79a4540-5", "text": "else:\n            self._container.update(new_label=final_label)\n[docs]    def clear(self) -> None:\n        \"\"\"Remove the thought from the screen. A cleared thought can't be reused.\"\"\"\n        self._container.clear()\n[docs]class StreamlitCallbackHandler(BaseCallbackHandler):\n    \"\"\"A callback handler that writes to a Streamlit app.\"\"\"\n[docs]    def __init__(\n        self,\n        parent_container: DeltaGenerator,\n        *,\n        max_thought_containers: int = 4,\n        expand_new_thoughts: bool = True,\n        collapse_completed_thoughts: bool = True,\n        thought_labeler: Optional[LLMThoughtLabeler] = None,\n    ):\n        \"\"\"Create a StreamlitCallbackHandler instance.\n        Parameters\n        ----------\n        parent_container\n            The `st.container` that will contain all the Streamlit elements that the\n            Handler creates.\n        max_thought_containers\n            The max number of completed LLM thought containers to show at once. When\n            this threshold is reached, a new thought will cause the oldest thoughts to\n            be collapsed into a \"History\" expander. Defaults to 4.\n        expand_new_thoughts\n            Each LLM \"thought\" gets its own `st.expander`. This param controls whether\n            that expander is expanded by default. Defaults to True.\n        collapse_completed_thoughts\n            If True, LLM thought expanders will be collapsed when completed.\n            Defaults to True.\n        thought_labeler\n            An optional custom LLMThoughtLabeler instance. If unspecified, the handler\n            will use the default thought labeling logic. Defaults to None.\n        \"\"\"\n        self._parent_container = parent_container\n        self._history_parent = parent_container.container()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html"}
{"id": "d770c79a4540-6", "text": "self._parent_container = parent_container\n        self._history_parent = parent_container.container()\n        self._history_container: Optional[MutableExpander] = None\n        self._current_thought: Optional[LLMThought] = None\n        self._completed_thoughts: List[LLMThought] = []\n        self._max_thought_containers = max(max_thought_containers, 1)\n        self._expand_new_thoughts = expand_new_thoughts\n        self._collapse_completed_thoughts = collapse_completed_thoughts\n        self._thought_labeler = thought_labeler or LLMThoughtLabeler()\n    def _require_current_thought(self) -> LLMThought:\n        \"\"\"Return our current LLMThought. Raise an error if we have no current\n        thought.\n        \"\"\"\n        if self._current_thought is None:\n            raise RuntimeError(\"Current LLMThought is unexpectedly None!\")\n        return self._current_thought\n    def _get_last_completed_thought(self) -> Optional[LLMThought]:\n        \"\"\"Return our most recent completed LLMThought, or None if we don't have one.\"\"\"\n        if len(self._completed_thoughts) > 0:\n            return self._completed_thoughts[len(self._completed_thoughts) - 1]\n        return None\n    @property\n    def _num_thought_containers(self) -> int:\n        \"\"\"The number of 'thought containers' we're currently showing: the\n        number of completed thought containers, the history container (if it exists),\n        and the current thought container (if it exists).\n        \"\"\"\n        count = len(self._completed_thoughts)\n        if self._history_container is not None:\n            count += 1\n        if self._current_thought is not None:\n            count += 1", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html"}
{"id": "d770c79a4540-7", "text": "if self._current_thought is not None:\n            count += 1\n        return count\n    def _complete_current_thought(self, final_label: Optional[str] = None) -> None:\n        \"\"\"Complete the current thought, optionally assigning it a new label.\n        Add it to our _completed_thoughts list.\n        \"\"\"\n        thought = self._require_current_thought()\n        thought.complete(final_label)\n        self._completed_thoughts.append(thought)\n        self._current_thought = None\n    def _prune_old_thought_containers(self) -> None:\n        \"\"\"If we have too many thoughts onscreen, move older thoughts to the\n        'history container.'\n        \"\"\"\n        while (\n            self._num_thought_containers > self._max_thought_containers\n            and len(self._completed_thoughts) > 0\n        ):\n            # Create our history container if it doesn't exist, and if\n            # max_thought_containers is > 1. (if max_thought_containers is 1, we don't\n            # have room to show history.)\n            if self._history_container is None and self._max_thought_containers > 1:\n                self._history_container = MutableExpander(\n                    self._history_parent,\n                    label=self._thought_labeler.get_history_label(),\n                    expanded=False,\n                )\n            oldest_thought = self._completed_thoughts.pop(0)\n            if self._history_container is not None:\n                self._history_container.markdown(oldest_thought.container.label)\n                self._history_container.append_copy(oldest_thought.container)\n            oldest_thought.clear()\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html"}
{"id": "d770c79a4540-8", "text": "self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        if self._current_thought is None:\n            self._current_thought = LLMThought(\n                parent_container=self._parent_container,\n                expanded=self._expand_new_thoughts,\n                collapse_on_complete=self._collapse_completed_thoughts,\n                labeler=self._thought_labeler,\n            )\n        self._current_thought.on_llm_start(serialized, prompts)\n        # We don't prune_old_thought_containers here, because our container won't\n        # be visible until it has a child.\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        self._require_current_thought().on_llm_new_token(token, **kwargs)\n        self._prune_old_thought_containers()\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        self._require_current_thought().on_llm_end(response, **kwargs)\n        self._prune_old_thought_containers()\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        self._require_current_thought().on_llm_error(error, **kwargs)\n        self._prune_old_thought_containers()\n[docs]    def on_tool_start(\n        self, serialized: Dict[str, Any], input_str: str, **kwargs: Any\n    ) -> None:\n        self._require_current_thought().on_tool_start(serialized, input_str, **kwargs)\n        self._prune_old_thought_containers()\n[docs]    def on_tool_end(\n        self,\n        output: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html"}
{"id": "d770c79a4540-9", "text": "[docs]    def on_tool_end(\n        self,\n        output: str,\n        color: Optional[str] = None,\n        observation_prefix: Optional[str] = None,\n        llm_prefix: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        self._require_current_thought().on_tool_end(\n            output, color, observation_prefix, llm_prefix, **kwargs\n        )\n        self._complete_current_thought()\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        self._require_current_thought().on_tool_error(error, **kwargs)\n        self._prune_old_thought_containers()\n[docs]    def on_text(\n        self,\n        text: str,\n        color: Optional[str] = None,\n        end: str = \"\",\n        **kwargs: Any,\n    ) -> None:\n        pass\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        pass\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:\n        pass\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        pass\n[docs]    def on_agent_action(\n        self, action: AgentAction, color: Optional[str] = None, **kwargs: Any\n    ) -> Any:\n        self._require_current_thought().on_agent_action(action, color, **kwargs)\n        self._prune_old_thought_containers()\n[docs]    def on_agent_finish(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html"}
{"id": "d770c79a4540-10", "text": "[docs]    def on_agent_finish(\n        self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any\n    ) -> None:\n        if self._current_thought is not None:\n            self._current_thought.complete(\n                self._thought_labeler.get_final_agent_thought_label()\n            )\n            self._current_thought = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html"}
{"id": "44f36e397620-0", "text": "Source code for langchain.callbacks.tracers.wandb\n\"\"\"A Tracer Implementation that records activity to Weights & Biases.\"\"\"\nfrom __future__ import annotations\nimport json\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Dict,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    TypedDict,\n    Union,\n)\nfrom langchain.callbacks.tracers.base import BaseTracer\nfrom langchain.callbacks.tracers.schemas import Run\nif TYPE_CHECKING:\n    from wandb import Settings as WBSettings\n    from wandb.sdk.data_types.trace_tree import Span\n    from wandb.sdk.lib.paths import StrPath\n    from wandb.wandb_run import Run as WBRun\nPRINT_WARNINGS = True\ndef _serialize_io(run_inputs: Optional[dict]) -> dict:\n    if not run_inputs:\n        return {}\n    from google.protobuf.json_format import MessageToJson\n    from google.protobuf.message import Message\n    serialized_inputs = {}\n    for key, value in run_inputs.items():\n        if isinstance(value, Message):\n            serialized_inputs[key] = MessageToJson(value)\n        elif key == \"input_documents\":\n            serialized_inputs.update(\n                {f\"input_document_{i}\": doc.json() for i, doc in enumerate(value)}\n            )\n        else:\n            serialized_inputs[key] = value\n    return serialized_inputs\n[docs]class RunProcessor:\n    \"\"\"Handles the conversion of a LangChain Runs into a WBTraceTree.\"\"\"\n[docs]    def __init__(self, wandb_module: Any, trace_module: Any):\n        self.wandb = wandb_module\n        self.trace_tree = trace_module\n[docs]    def process_span(self, run: Run) -> Optional[\"Span\"]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html"}
{"id": "44f36e397620-1", "text": "[docs]    def process_span(self, run: Run) -> Optional[\"Span\"]:\n        \"\"\"Converts a LangChain Run into a W&B Trace Span.\n        :param run: The LangChain Run to convert.\n        :return: The converted W&B Trace Span.\n        \"\"\"\n        try:\n            span = self._convert_lc_run_to_wb_span(run)\n            return span\n        except Exception as e:\n            if PRINT_WARNINGS:\n                self.wandb.termwarn(\n                    f\"Skipping trace saving - unable to safely convert LangChain Run \"\n                    f\"into W&B Trace due to: {e}\"\n                )\n            return None\n    def _convert_run_to_wb_span(self, run: Run) -> \"Span\":\n        \"\"\"Base utility to create a span from a run.\n        :param run: The run to convert.\n        :return: The converted Span.\n        \"\"\"\n        attributes = {**run.extra} if run.extra else {}\n        attributes[\"execution_order\"] = run.execution_order\n        return self.trace_tree.Span(\n            span_id=str(run.id) if run.id is not None else None,\n            name=run.name,\n            start_time_ms=int(run.start_time.timestamp() * 1000),\n            end_time_ms=int(run.end_time.timestamp() * 1000)\n            if run.end_time is not None\n            else None,\n            status_code=self.trace_tree.StatusCode.SUCCESS\n            if run.error is None\n            else self.trace_tree.StatusCode.ERROR,\n            status_message=run.error,\n            attributes=attributes,\n        )\n    def _convert_llm_run_to_wb_span(self, run: Run) -> \"Span\":\n        \"\"\"Converts a LangChain LLM Run into a W&B Trace Span.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html"}
{"id": "44f36e397620-2", "text": "\"\"\"Converts a LangChain LLM Run into a W&B Trace Span.\n        :param run: The LangChain LLM Run to convert.\n        :return: The converted W&B Trace Span.\n        \"\"\"\n        base_span = self._convert_run_to_wb_span(run)\n        if base_span.attributes is None:\n            base_span.attributes = {}\n        base_span.attributes[\"llm_output\"] = (run.outputs or {}).get(\"llm_output\", {})\n        base_span.results = [\n            self.trace_tree.Result(\n                inputs={\"prompt\": prompt},\n                outputs={\n                    f\"gen_{g_i}\": gen[\"text\"]\n                    for g_i, gen in enumerate(run.outputs[\"generations\"][ndx])\n                }\n                if (\n                    run.outputs is not None\n                    and len(run.outputs[\"generations\"]) > ndx\n                    and len(run.outputs[\"generations\"][ndx]) > 0\n                )\n                else None,\n            )\n            for ndx, prompt in enumerate(run.inputs[\"prompts\"] or [])\n        ]\n        base_span.span_kind = self.trace_tree.SpanKind.LLM\n        return base_span\n    def _convert_chain_run_to_wb_span(self, run: Run) -> \"Span\":\n        \"\"\"Converts a LangChain Chain Run into a W&B Trace Span.\n        :param run: The LangChain Chain Run to convert.\n        :return: The converted W&B Trace Span.\n        \"\"\"\n        base_span = self._convert_run_to_wb_span(run)\n        base_span.results = [\n            self.trace_tree.Result(\n                inputs=_serialize_io(run.inputs), outputs=_serialize_io(run.outputs)\n            )\n        ]\n        base_span.child_spans = [\n            self._convert_lc_run_to_wb_span(child_run) for child_run in run.child_runs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html"}
{"id": "44f36e397620-3", "text": "]\n        base_span.span_kind = (\n            self.trace_tree.SpanKind.AGENT\n            if \"agent\" in run.name.lower()\n            else self.trace_tree.SpanKind.CHAIN\n        )\n        return base_span\n    def _convert_tool_run_to_wb_span(self, run: Run) -> \"Span\":\n        \"\"\"Converts a LangChain Tool Run into a W&B Trace Span.\n        :param run: The LangChain Tool Run to convert.\n        :return: The converted W&B Trace Span.\n        \"\"\"\n        base_span = self._convert_run_to_wb_span(run)\n        base_span.results = [\n            self.trace_tree.Result(\n                inputs=_serialize_io(run.inputs), outputs=_serialize_io(run.outputs)\n            )\n        ]\n        base_span.child_spans = [\n            self._convert_lc_run_to_wb_span(child_run) for child_run in run.child_runs\n        ]\n        base_span.span_kind = self.trace_tree.SpanKind.TOOL\n        return base_span\n    def _convert_lc_run_to_wb_span(self, run: Run) -> \"Span\":\n        \"\"\"Utility to convert any generic LangChain Run into a W&B Trace Span.\n        :param run: The LangChain Run to convert.\n        :return: The converted W&B Trace Span.\n        \"\"\"\n        if run.run_type == \"llm\":\n            return self._convert_llm_run_to_wb_span(run)\n        elif run.run_type == \"chain\":\n            return self._convert_chain_run_to_wb_span(run)\n        elif run.run_type == \"tool\":\n            return self._convert_tool_run_to_wb_span(run)\n        else:\n            return self._convert_run_to_wb_span(run)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html"}
{"id": "44f36e397620-4", "text": "else:\n            return self._convert_run_to_wb_span(run)\n[docs]    def process_model(self, run: Run) -> Optional[Dict[str, Any]]:\n        \"\"\"Utility to process a run for wandb model_dict serialization.\n        :param run: The run to process.\n        :return: The convert model_dict to pass to WBTraceTree.\n        \"\"\"\n        try:\n            data = json.loads(run.json())\n            processed = self.flatten_run(data)\n            keep_keys = (\n                \"id\",\n                \"name\",\n                \"serialized\",\n                \"inputs\",\n                \"outputs\",\n                \"parent_run_id\",\n                \"execution_order\",\n            )\n            processed = self.truncate_run_iterative(processed, keep_keys=keep_keys)\n            exact_keys, partial_keys = (\"lc\", \"type\"), (\"api_key\",)\n            processed = self.modify_serialized_iterative(\n                processed, exact_keys=exact_keys, partial_keys=partial_keys\n            )\n            output = self.build_tree(processed)\n            return output\n        except Exception as e:\n            if PRINT_WARNINGS:\n                self.wandb.termwarn(f\"WARNING: Failed to serialize model: {e}\")\n            return None\n[docs]    def flatten_run(self, run: Dict[str, Any]) -> List[Dict[str, Any]]:\n        \"\"\"Utility to flatten a nest run object into a list of runs.\n        :param run: The base run to flatten.\n        :return: The flattened list of runs.\n        \"\"\"\n        def flatten(child_runs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:\n            \"\"\"Utility to recursively flatten a list of child runs in a run.\n            :param child_runs: The list of child runs to flatten.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html"}
{"id": "44f36e397620-5", "text": ":param child_runs: The list of child runs to flatten.\n            :return: The flattened list of runs.\n            \"\"\"\n            if child_runs is None:\n                return []\n            result = []\n            for item in child_runs:\n                child_runs = item.pop(\"child_runs\", [])\n                result.append(item)\n                result.extend(flatten(child_runs))\n            return result\n        return flatten([run])\n[docs]    def truncate_run_iterative(\n        self, runs: List[Dict[str, Any]], keep_keys: Tuple[str, ...] = ()\n    ) -> List[Dict[str, Any]]:\n        \"\"\"Utility to truncate a list of runs dictionaries to only keep the specified\n            keys in each run.\n        :param runs: The list of runs to truncate.\n        :param keep_keys: The keys to keep in each run.\n        :return: The truncated list of runs.\n        \"\"\"\n        def truncate_single(run: Dict[str, Any]) -> Dict[str, Any]:\n            \"\"\"Utility to truncate a single run dictionary to only keep the specified\n                keys.\n            :param run: The run dictionary to truncate.\n            :return: The truncated run dictionary\n            \"\"\"\n            new_dict = {}\n            for key in run:\n                if key in keep_keys:\n                    new_dict[key] = run.get(key)\n            return new_dict\n        return list(map(truncate_single, runs))\n[docs]    def modify_serialized_iterative(\n        self,\n        runs: List[Dict[str, Any]],\n        exact_keys: Tuple[str, ...] = (),\n        partial_keys: Tuple[str, ...] = (),\n    ) -> List[Dict[str, Any]]:\n        \"\"\"Utility to modify the serialized field of a list of runs dictionaries.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html"}
{"id": "44f36e397620-6", "text": "\"\"\"Utility to modify the serialized field of a list of runs dictionaries.\n        removes any keys that match the exact_keys and any keys that contain any of the\n        partial_keys.\n        recursively moves the dictionaries under the kwargs key to the top level.\n        changes the \"id\" field to a string \"_kind\" field that tells WBTraceTree how to\n        visualize the run. promotes the \"serialized\" field to the top level.\n        :param runs: The list of runs to modify.\n        :param exact_keys: A tuple of keys to remove from the serialized field.\n        :param partial_keys: A tuple of partial keys to remove from the serialized\n            field.\n        :return: The modified list of runs.\n        \"\"\"\n        def remove_exact_and_partial_keys(obj: Dict[str, Any]) -> Dict[str, Any]:\n            \"\"\"Recursively removes exact and partial keys from a dictionary.\n            :param obj: The dictionary to remove keys from.\n            :return: The modified dictionary.\n            \"\"\"\n            if isinstance(obj, dict):\n                obj = {\n                    k: v\n                    for k, v in obj.items()\n                    if k not in exact_keys\n                    and not any(partial in k for partial in partial_keys)\n                }\n                for k, v in obj.items():\n                    obj[k] = remove_exact_and_partial_keys(v)\n            elif isinstance(obj, list):\n                obj = [remove_exact_and_partial_keys(x) for x in obj]\n            return obj\n        def handle_id_and_kwargs(\n            obj: Dict[str, Any], root: bool = False\n        ) -> Dict[str, Any]:\n            \"\"\"Recursively handles the id and kwargs fields of a dictionary.\n            changes the id field to a string \"_kind\" field that tells WBTraceTree how", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html"}
{"id": "44f36e397620-7", "text": "changes the id field to a string \"_kind\" field that tells WBTraceTree how\n            to visualize the run. recursively moves the dictionaries under the kwargs\n            key to the top level.\n            :param obj: a run dictionary with id and kwargs fields.\n            :param root: whether this is the root dictionary or the serialized\n                dictionary.\n            :return: The modified dictionary.\n            \"\"\"\n            if isinstance(obj, dict):\n                if (\"id\" in obj or \"name\" in obj) and not root:\n                    _kind = obj.get(\"id\")\n                    if not _kind:\n                        _kind = [obj.get(\"name\")]\n                    obj[\"_kind\"] = _kind[-1]\n                    obj.pop(\"id\", None)\n                    obj.pop(\"name\", None)\n                    if \"kwargs\" in obj:\n                        kwargs = obj.pop(\"kwargs\")\n                        for k, v in kwargs.items():\n                            obj[k] = v\n                for k, v in obj.items():\n                    obj[k] = handle_id_and_kwargs(v)\n            elif isinstance(obj, list):\n                obj = [handle_id_and_kwargs(x) for x in obj]\n            return obj\n        def transform_serialized(serialized: Dict[str, Any]) -> Dict[str, Any]:\n            \"\"\"Transforms the serialized field of a run dictionary to be compatible\n                with WBTraceTree.\n            :param serialized: The serialized field of a run dictionary.\n            :return: The transformed serialized field.\n            \"\"\"\n            serialized = handle_id_and_kwargs(serialized, root=True)\n            serialized = remove_exact_and_partial_keys(serialized)\n            return serialized\n        def transform_run(run: Dict[str, Any]) -> Dict[str, Any]:\n            \"\"\"Transforms a run dictionary to be compatible with WBTraceTree.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html"}
{"id": "44f36e397620-8", "text": "\"\"\"Transforms a run dictionary to be compatible with WBTraceTree.\n            :param run: The run dictionary to transform.\n            :return: The transformed run dictionary.\n            \"\"\"\n            transformed_dict = transform_serialized(run)\n            serialized = transformed_dict.pop(\"serialized\")\n            for k, v in serialized.items():\n                transformed_dict[k] = v\n            _kind = transformed_dict.get(\"_kind\", None)\n            name = transformed_dict.pop(\"name\", None)\n            exec_ord = transformed_dict.pop(\"execution_order\", None)\n            if not name:\n                name = _kind\n            output_dict = {\n                f\"{exec_ord}_{name}\": transformed_dict,\n            }\n            return output_dict\n        return list(map(transform_run, runs))\n[docs]    def build_tree(self, runs: List[Dict[str, Any]]) -> Dict[str, Any]:\n        \"\"\"Builds a nested dictionary from a list of runs.\n        :param runs: The list of runs to build the tree from.\n        :return: The nested dictionary representing the langchain Run in a tree\n            structure compatible with WBTraceTree.\n        \"\"\"\n        id_to_data = {}\n        child_to_parent = {}\n        for entity in runs:\n            for key, data in entity.items():\n                id_val = data.pop(\"id\", None)\n                parent_run_id = data.pop(\"parent_run_id\", None)\n                id_to_data[id_val] = {key: data}\n                if parent_run_id:\n                    child_to_parent[id_val] = parent_run_id\n        for child_id, parent_id in child_to_parent.items():\n            parent_dict = id_to_data[parent_id]\n            parent_dict[next(iter(parent_dict))][\n                next(iter(id_to_data[child_id]))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html"}
{"id": "44f36e397620-9", "text": "parent_dict[next(iter(parent_dict))][\n                next(iter(id_to_data[child_id]))\n            ] = id_to_data[child_id][next(iter(id_to_data[child_id]))]\n        root_dict = next(\n            data for id_val, data in id_to_data.items() if id_val not in child_to_parent\n        )\n        return root_dict\n[docs]class WandbRunArgs(TypedDict):\n    \"\"\"Arguments for the WandbTracer.\"\"\"\n    job_type: Optional[str]\n    dir: Optional[StrPath]\n    config: Union[Dict, str, None]\n    project: Optional[str]\n    entity: Optional[str]\n    reinit: Optional[bool]\n    tags: Optional[Sequence]\n    group: Optional[str]\n    name: Optional[str]\n    notes: Optional[str]\n    magic: Optional[Union[dict, str, bool]]\n    config_exclude_keys: Optional[List[str]]\n    config_include_keys: Optional[List[str]]\n    anonymous: Optional[str]\n    mode: Optional[str]\n    allow_val_change: Optional[bool]\n    resume: Optional[Union[bool, str]]\n    force: Optional[bool]\n    tensorboard: Optional[bool]\n    sync_tensorboard: Optional[bool]\n    monitor_gym: Optional[bool]\n    save_code: Optional[bool]\n    id: Optional[str]\n    settings: Union[WBSettings, Dict[str, Any], None]\n[docs]class WandbTracer(BaseTracer):\n    \"\"\"Callback Handler that logs to Weights and Biases.\n    This handler will log the model architecture and run traces to Weights and Biases.\n    This will ensure that all LangChain activity is logged to W&B.\n    \"\"\"\n    _run: Optional[WBRun] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html"}
{"id": "44f36e397620-10", "text": "\"\"\"\n    _run: Optional[WBRun] = None\n    _run_args: Optional[WandbRunArgs] = None\n[docs]    def __init__(self, run_args: Optional[WandbRunArgs] = None, **kwargs: Any) -> None:\n        \"\"\"Initializes the WandbTracer.\n        Parameters:\n            run_args: (dict, optional) Arguments to pass to `wandb.init()`. If not\n                provided, `wandb.init()` will be called with no arguments. Please\n                refer to the `wandb.init` for more details.\n        To use W&B to monitor all LangChain activity, add this tracer like any other\n        LangChain callback:\n        ```\n        from wandb.integration.langchain import WandbTracer\n        tracer = WandbTracer()\n        chain = LLMChain(llm, callbacks=[tracer])\n        # ...end of notebook / script:\n        tracer.finish()\n        ```\n        \"\"\"\n        super().__init__(**kwargs)\n        try:\n            import wandb\n            from wandb.sdk.data_types import trace_tree\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import wandb python package.\"\n                \"Please install it with `pip install -U wandb`.\"\n            ) from e\n        self._wandb = wandb\n        self._trace_tree = trace_tree\n        self._run_args = run_args\n        self._ensure_run(should_print_url=(wandb.run is None))\n        self.run_processor = RunProcessor(self._wandb, self._trace_tree)\n[docs]    def finish(self) -> None:\n        \"\"\"Waits for all asynchronous processes to finish and data to upload.\n        Proxy for `wandb.finish()`.\n        \"\"\"\n        self._wandb.finish()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html"}
{"id": "44f36e397620-11", "text": "\"\"\"\n        self._wandb.finish()\n    def _log_trace_from_run(self, run: Run) -> None:\n        \"\"\"Logs a LangChain Run to W*B as a W&B Trace.\"\"\"\n        self._ensure_run()\n        root_span = self.run_processor.process_span(run)\n        model_dict = self.run_processor.process_model(run)\n        if root_span is None:\n            return\n        model_trace = self._trace_tree.WBTraceTree(\n            root_span=root_span,\n            model_dict=model_dict,\n        )\n        if self._wandb.run is not None:\n            self._wandb.run.log({\"langchain_trace\": model_trace})\n    def _ensure_run(self, should_print_url: bool = False) -> None:\n        \"\"\"Ensures an active W&B run exists.\n        If not, will start a new run with the provided run_args.\n        \"\"\"\n        if self._wandb.run is None:\n            run_args = self._run_args or {}  # type: ignore\n            run_args: dict = {**run_args}  # type: ignore\n            if \"settings\" not in run_args:  # type: ignore\n                run_args[\"settings\"] = {\"silent\": True}  # type: ignore\n            self._wandb.init(**run_args)\n        if self._wandb.run is not None:\n            if should_print_url:\n                run_url = self._wandb.run.settings.run_url\n                self._wandb.termlog(\n                    f\"Streaming LangChain activity to W&B at {run_url}\\n\"\n                    \"`WandbTracer` is currently in beta.\\n\"\n                    \"Please report any issues to \"\n                    \"https://github.com/wandb/wandb/issues with the tag \"\n                    \"`langchain`.\"\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html"}
{"id": "44f36e397620-12", "text": "\"`langchain`.\"\n                )\n            self._wandb.run._label(repo=\"langchain\")\n    def _persist_run(self, run: \"Run\") -> None:\n        \"\"\"Persist a run.\"\"\"\n        self._log_trace_from_run(run)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html"}
{"id": "8fb1c6a656ef-0", "text": "Source code for langchain.docstore.base\n\"\"\"Interface to access to place that stores documents.\"\"\"\nfrom abc import ABC, abstractmethod\nfrom typing import Dict, List, Union\nfrom langchain.docstore.document import Document\n[docs]class Docstore(ABC):\n    \"\"\"Interface to access to place that stores documents.\"\"\"\n[docs]    @abstractmethod\n    def search(self, search: str) -> Union[str, Document]:\n        \"\"\"Search for document.\n        If page exists, return the page summary, and a Document object.\n        If page does not exist, return similar entries.\n        \"\"\"\n[docs]    def delete(self, ids: List) -> None:\n        \"\"\"Deleting IDs from in memory dictionary.\"\"\"\n        raise NotImplementedError\n[docs]class AddableMixin(ABC):\n    \"\"\"Mixin class that supports adding texts.\"\"\"\n[docs]    @abstractmethod\n    def add(self, texts: Dict[str, Document]) -> None:\n        \"\"\"Add more documents.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/docstore/base.html"}
{"id": "99a87cd34bba-0", "text": "Source code for langchain.docstore.wikipedia\n\"\"\"Wrapper around wikipedia API.\"\"\"\nfrom typing import Union\nfrom langchain.docstore.base import Docstore\nfrom langchain.docstore.document import Document\n[docs]class Wikipedia(Docstore):\n    \"\"\"Wrapper around wikipedia API.\"\"\"\n[docs]    def __init__(self) -> None:\n        \"\"\"Check that wikipedia package is installed.\"\"\"\n        try:\n            import wikipedia  # noqa: F401\n        except ImportError:\n            raise ImportError(\n                \"Could not import wikipedia python package. \"\n                \"Please install it with `pip install wikipedia`.\"\n            )\n[docs]    def search(self, search: str) -> Union[str, Document]:\n        \"\"\"Try to search for wiki page.\n        If page exists, return the page summary, and a PageWithLookups object.\n        If page does not exist, return similar entries.\n        Args:\n            search: search string.\n        Returns: a Document object or error message.\n        \"\"\"\n        import wikipedia\n        try:\n            page_content = wikipedia.page(search).content\n            url = wikipedia.page(search).url\n            result: Union[str, Document] = Document(\n                page_content=page_content, metadata={\"page\": url}\n            )\n        except wikipedia.PageError:\n            result = f\"Could not find [{search}]. Similar: {wikipedia.search(search)}\"\n        except wikipedia.DisambiguationError:\n            result = f\"Could not find [{search}]. Similar: {wikipedia.search(search)}\"\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/docstore/wikipedia.html"}
{"id": "4ef954a81e65-0", "text": "Source code for langchain.docstore.arbitrary_fn\nfrom typing import Callable, Union\nfrom langchain.docstore.base import Docstore\nfrom langchain.schema import Document\n[docs]class DocstoreFn(Docstore):\n    \"\"\"Langchain Docstore via arbitrary lookup function.\n    This is useful when:\n     * it's expensive to construct an InMemoryDocstore/dict\n     * you retrieve documents from remote sources\n     * you just want to reuse existing objects\n    \"\"\"\n[docs]    def __init__(\n        self,\n        lookup_fn: Callable[[str], Union[Document, str]],\n    ):\n        self._lookup_fn = lookup_fn\n[docs]    def search(self, search: str) -> Document:\n        \"\"\"Search for a document.\n        Args:\n            search: search string\n        Returns:\n            Document if found, else error message.\n        \"\"\"\n        r = self._lookup_fn(search)\n        if isinstance(r, str):\n            # NOTE: assume the search string is the source ID\n            return Document(page_content=r, metadata={\"source\": search})\n        elif isinstance(r, Document):\n            return r\n        raise ValueError(f\"Unexpected type of document {type(r)}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/docstore/arbitrary_fn.html"}
{"id": "54cf80ba11d3-0", "text": "Source code for langchain.docstore.in_memory\n\"\"\"Simple in memory docstore in the form of a dict.\"\"\"\nfrom typing import Dict, List, Optional, Union\nfrom langchain.docstore.base import AddableMixin, Docstore\nfrom langchain.docstore.document import Document\n[docs]class InMemoryDocstore(Docstore, AddableMixin):\n    \"\"\"Simple in memory docstore in the form of a dict.\"\"\"\n[docs]    def __init__(self, _dict: Optional[Dict[str, Document]] = None):\n        \"\"\"Initialize with dict.\"\"\"\n        self._dict = _dict if _dict is not None else {}\n[docs]    def add(self, texts: Dict[str, Document]) -> None:\n        \"\"\"Add texts to in memory dictionary.\n        Args:\n            texts: dictionary of id -> document.\n        Returns:\n            None\n        \"\"\"\n        overlapping = set(texts).intersection(self._dict)\n        if overlapping:\n            raise ValueError(f\"Tried to add ids that already exist: {overlapping}\")\n        self._dict = {**self._dict, **texts}\n[docs]    def delete(self, ids: List) -> None:\n        \"\"\"Deleting IDs from in memory dictionary.\"\"\"\n        overlapping = set(ids).intersection(self._dict)\n        if not overlapping:\n            raise ValueError(f\"Tried to delete ids that does not  exist: {ids}\")\n        for _id in ids:\n            self._dict.pop(_id)\n[docs]    def search(self, search: str) -> Union[str, Document]:\n        \"\"\"Search via direct lookup.\n        Args:\n            search: id of a document to search for.\n        Returns:\n            Document if found, else error message.\n        \"\"\"\n        if search not in self._dict:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html"}
{"id": "54cf80ba11d3-1", "text": "\"\"\"\n        if search not in self._dict:\n            return f\"ID {search} not found.\"\n        else:\n            return self._dict[search]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html"}
{"id": "9767901d2013-0", "text": "Source code for langchain.smith.evaluation.string_run_evaluator\n\"\"\"Run evaluator wrapper for string evaluators.\"\"\"\nfrom __future__ import annotations\nfrom abc import abstractmethod\nfrom typing import Any, Dict, List, Optional\nfrom langsmith import EvaluationResult, RunEvaluator\nfrom langsmith.schemas import DataType, Example, Run\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForChainRun,\n    CallbackManagerForChainRun,\n)\nfrom langchain.chains.base import Chain\nfrom langchain.evaluation.schema import StringEvaluator\nfrom langchain.load.dump import dumpd\nfrom langchain.load.load import load\nfrom langchain.load.serializable import Serializable\nfrom langchain.schema import RUN_KEY, messages_from_dict\nfrom langchain.schema.messages import BaseMessage, get_buffer_string\ndef _get_messages_from_run_dict(messages: List[dict]) -> List[BaseMessage]:\n    if not messages:\n        return []\n    first_message = messages[0]\n    if \"lc\" in first_message:\n        return [load(dumpd(message)) for message in messages]\n    else:\n        return messages_from_dict(messages)\n[docs]class StringRunMapper(Serializable):\n    \"\"\"Extract items to evaluate from the run object.\"\"\"\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"The keys to extract from the run.\"\"\"\n        return [\"prediction\", \"input\"]\n[docs]    @abstractmethod\n    def map(self, run: Run) -> Dict[str, str]:\n        \"\"\"Maps the Run to a dictionary.\"\"\"\n[docs]    def __call__(self, run: Run) -> Dict[str, str]:\n        \"\"\"Maps the Run to a dictionary.\"\"\"\n        if not run.outputs:\n            raise ValueError(f\"Run {run.id} has no outputs to evaluate.\")\n        return self.map(run)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html"}
{"id": "9767901d2013-1", "text": "return self.map(run)\n[docs]class LLMStringRunMapper(StringRunMapper):\n    \"\"\"Extract items to evaluate from the run object.\"\"\"\n[docs]    def serialize_chat_messages(self, messages: List[Dict]) -> str:\n        \"\"\"Extract the input messages from the run.\"\"\"\n        if isinstance(messages, list) and messages:\n            if isinstance(messages[0], dict):\n                chat_messages = _get_messages_from_run_dict(messages)\n            elif isinstance(messages[0], list):\n                # Runs from Tracer have messages as a list of lists of dicts\n                chat_messages = _get_messages_from_run_dict(messages[0])\n            else:\n                raise ValueError(f\"Could not extract messages to evaluate {messages}\")\n            return get_buffer_string(chat_messages)\n        raise ValueError(f\"Could not extract messages to evaluate {messages}\")\n[docs]    def serialize_inputs(self, inputs: Dict) -> str:\n        if \"prompts\" in inputs:  # Should we even accept this?\n            input_ = \"\\n\\n\".join(inputs[\"prompts\"])\n        elif \"prompt\" in inputs:\n            input_ = inputs[\"prompt\"]\n        elif \"messages\" in inputs:\n            input_ = self.serialize_chat_messages(inputs[\"messages\"])\n        else:\n            raise ValueError(\"LLM Run must have either messages or prompts as inputs.\")\n        return input_\n[docs]    def serialize_outputs(self, outputs: Dict) -> str:\n        if not outputs.get(\"generations\"):\n            raise ValueError(\"Cannot evaluate LLM Run without generations.\")\n        generations: List[Dict] = outputs[\"generations\"]\n        if not generations:\n            raise ValueError(\"Cannot evaluate LLM run with empty generations.\")\n        first_generation: Dict = generations[0]\n        if isinstance(first_generation, list):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html"}
{"id": "9767901d2013-2", "text": "first_generation: Dict = generations[0]\n        if isinstance(first_generation, list):\n            # Runs from Tracer have generations as a list of lists of dicts\n            # Whereas Runs from the API have a list of dicts\n            first_generation = first_generation[0]\n        if \"message\" in first_generation:\n            output_ = self.serialize_chat_messages([first_generation[\"message\"]])\n        else:\n            output_ = first_generation[\"text\"]\n        return output_\n[docs]    def map(self, run: Run) -> Dict[str, str]:\n        \"\"\"Maps the Run to a dictionary.\"\"\"\n        if run.run_type != \"llm\":\n            raise ValueError(\"LLM RunMapper only supports LLM runs.\")\n        elif not run.outputs:\n            if run.error:\n                raise ValueError(\n                    f\"Cannot evaluate errored LLM run {run.id}: {run.error}\"\n                )\n            else:\n                raise ValueError(\n                    f\"Run {run.id} has no outputs. Cannot evaluate this run.\"\n                )\n        else:\n            try:\n                inputs = self.serialize_inputs(run.inputs)\n            except Exception as e:\n                raise ValueError(\n                    f\"Could not parse LM input from run inputs {run.inputs}\"\n                ) from e\n            try:\n                output_ = self.serialize_outputs(run.outputs)\n            except Exception as e:\n                raise ValueError(\n                    f\"Could not parse LM prediction from run outputs {run.outputs}\"\n                ) from e\n            return {\"input\": inputs, \"prediction\": output_}\n[docs]class ChainStringRunMapper(StringRunMapper):\n    \"\"\"Extract items to evaluate from the run object from a chain.\"\"\"\n    input_key: Optional[str] = None\n    \"\"\"The key from the model Run's inputs to use as the eval input.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html"}
{"id": "9767901d2013-3", "text": "\"\"\"The key from the model Run's inputs to use as the eval input.\n    If not provided, will use the only input key or raise an\n    error if there are multiple.\"\"\"\n    prediction_key: Optional[str] = None\n    \"\"\"The key from the model Run's outputs to use as the eval prediction.\n    If not provided, will use the only output key or raise an error\n    if there are multiple.\"\"\"\n    def _get_key(self, source: Dict, key: Optional[str], which: str) -> str:\n        if key is not None:\n            return source[key]\n        elif len(source) == 1:\n            return next(iter(source.values()))\n        else:\n            raise ValueError(\n                f\"Could not map run {which} with multiple keys: \"\n                f\"{source}\\nPlease manually specify a {which}_key\"\n            )\n[docs]    def map(self, run: Run) -> Dict[str, str]:\n        \"\"\"Maps the Run to a dictionary.\"\"\"\n        if not run.outputs:\n            raise ValueError(\n                f\"Run with ID {run.id} lacks outputs required for evaluation.\"\n                \" Ensure the Run has valid outputs.\"\n            )\n        if self.input_key is not None and self.input_key not in run.inputs:\n            raise ValueError(\n                f\"Run with ID {run.id} is missing the expected input key\"\n                f\" '{self.input_key}'.\\nAvailable input keys in this Run\"\n                f\"  are: {run.inputs.keys()}.\\nAdjust the evaluator's\"\n                f\" input_key or ensure your input data includes key\"\n                f\" '{self.input_key}'.\"\n            )\n        elif self.prediction_key is not None and self.prediction_key not in run.outputs:\n            available_keys = \", \".join(run.outputs.keys())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html"}
{"id": "9767901d2013-4", "text": "available_keys = \", \".join(run.outputs.keys())\n            raise ValueError(\n                f\"Run with ID {run.id} doesn't have the expected prediction key\"\n                f\" '{self.prediction_key}'. Available prediction keys in this Run are:\"\n                f\" {available_keys}. Adjust the evaluator's prediction_key or\"\n                \" ensure the Run object's outputs the expected key.\"\n            )\n        else:\n            input_ = self._get_key(run.inputs, self.input_key, \"input\")\n            prediction = self._get_key(run.outputs, self.prediction_key, \"prediction\")\n            return {\n                \"input\": input_,\n                \"prediction\": prediction,\n            }\n[docs]class ToolStringRunMapper(StringRunMapper):\n    \"\"\"Map an input to the tool.\"\"\"\n[docs]    def map(self, run: Run) -> Dict[str, str]:\n        if not run.outputs:\n            raise ValueError(f\"Run {run.id} has no outputs to evaluate.\")\n        return {\"input\": run.inputs[\"input\"], \"prediction\": run.outputs[\"output\"]}\n[docs]class StringExampleMapper(Serializable):\n    \"\"\"Map an example, or row in the dataset, to the inputs of an evaluation.\"\"\"\n    reference_key: Optional[str] = None\n    @property\n    def output_keys(self) -> List[str]:\n        \"\"\"The keys to extract from the run.\"\"\"\n        return [\"reference\"]\n[docs]    def serialize_chat_messages(self, messages: List[Dict]) -> str:\n        \"\"\"Extract the input messages from the run.\"\"\"\n        chat_messages = _get_messages_from_run_dict(messages)\n        return get_buffer_string(chat_messages)\n[docs]    def map(self, example: Example) -> Dict[str, str]:\n        \"\"\"Maps the Example, or dataset row to a dictionary.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html"}
{"id": "9767901d2013-5", "text": "\"\"\"Maps the Example, or dataset row to a dictionary.\"\"\"\n        if not example.outputs:\n            raise ValueError(\n                f\"Example {example.id} has no outputs to use as a reference.\"\n            )\n        if self.reference_key is None:\n            if len(example.outputs) > 1:\n                raise ValueError(\n                    f\"Example {example.id} has multiple outputs, so you must\"\n                    \" specify a reference_key.\"\n                )\n            else:\n                output = list(example.outputs.values())[0]\n        elif self.reference_key not in example.outputs:\n            raise ValueError(\n                f\"Example {example.id} does not have reference key\"\n                f\" {self.reference_key}.\"\n            )\n        else:\n            output = example.outputs[self.reference_key]\n        return {\n            \"reference\": self.serialize_chat_messages([output])\n            if isinstance(output, dict) and output.get(\"type\") and output.get(\"data\")\n            else output\n        }\n[docs]    def __call__(self, example: Example) -> Dict[str, str]:\n        \"\"\"Maps the Run and Example to a dictionary.\"\"\"\n        if not example.outputs:\n            raise ValueError(\n                f\"Example {example.id} has no outputs to use as areference label.\"\n            )\n        return self.map(example)\n[docs]class StringRunEvaluatorChain(Chain, RunEvaluator):\n    \"\"\"Evaluate Run and optional examples.\"\"\"\n    run_mapper: StringRunMapper\n    \"\"\"Maps the Run to a dictionary with 'input' and 'prediction' strings.\"\"\"\n    example_mapper: Optional[StringExampleMapper] = None\n    \"\"\"Maps the Example (dataset row) to a dictionary\n    with a 'reference' string.\"\"\"\n    name: str\n    \"\"\"The name of the evaluation metric.\"\"\"\n    string_evaluator: StringEvaluator", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html"}
{"id": "9767901d2013-6", "text": "\"\"\"The name of the evaluation metric.\"\"\"\n    string_evaluator: StringEvaluator\n    \"\"\"The evaluation chain.\"\"\"\n    @property\n    def input_keys(self) -> List[str]:\n        return [\"run\", \"example\"]\n    @property\n    def output_keys(self) -> List[str]:\n        return [\"feedback\"]\n    def _prepare_input(self, inputs: Dict[str, Any]) -> Dict[str, str]:\n        run: Run = inputs[\"run\"]\n        example: Optional[Example] = inputs.get(\"example\")\n        evaluate_strings_inputs = self.run_mapper(run)\n        if not self.string_evaluator.requires_input:\n            # Hide warning about unused input\n            evaluate_strings_inputs.pop(\"input\", None)\n        if example and self.example_mapper and self.string_evaluator.requires_reference:\n            evaluate_strings_inputs.update(self.example_mapper(example))\n        elif self.string_evaluator.requires_reference:\n            raise ValueError(\n                f\"Evaluator {self.name} requires an reference\"\n                \" example from the dataset,\"\n                f\" but none was provided for run {run.id}.\"\n            )\n        return evaluate_strings_inputs\n    def _prepare_output(self, output: Dict[str, Any]) -> Dict[str, Any]:\n        evaluation_result = EvaluationResult(\n            key=self.name, comment=output.get(\"reasoning\"), **output\n        )\n        if RUN_KEY in output:\n            # TODO: Not currently surfaced. Update\n            evaluation_result.evaluator_info[RUN_KEY] = output[RUN_KEY]\n        return {\"feedback\": evaluation_result}\n    def _call(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[CallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Call the evaluation chain.\"\"\"\n        evaluate_strings_inputs = self._prepare_input(inputs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html"}
{"id": "9767901d2013-7", "text": "\"\"\"Call the evaluation chain.\"\"\"\n        evaluate_strings_inputs = self._prepare_input(inputs)\n        _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        chain_output = self.string_evaluator.evaluate_strings(\n            **evaluate_strings_inputs,\n            callbacks=callbacks,\n            include_run_info=True,\n        )\n        return self._prepare_output(chain_output)\n    async def _acall(\n        self,\n        inputs: Dict[str, str],\n        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Call the evaluation chain.\"\"\"\n        evaluate_strings_inputs = self._prepare_input(inputs)\n        _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()\n        callbacks = _run_manager.get_child()\n        chain_output = await self.string_evaluator.aevaluate_strings(\n            **evaluate_strings_inputs,\n            callbacks=callbacks,\n            include_run_info=True,\n        )\n        return self._prepare_output(chain_output)\n    def _prepare_evaluator_output(self, output: Dict[str, Any]) -> EvaluationResult:\n        feedback: EvaluationResult = output[\"feedback\"]\n        if RUN_KEY not in feedback.evaluator_info:\n            feedback.evaluator_info[RUN_KEY] = output[RUN_KEY]\n        return feedback\n[docs]    def evaluate_run(\n        self, run: Run, example: Optional[Example] = None\n    ) -> EvaluationResult:\n        \"\"\"Evaluate an example.\"\"\"\n        try:\n            result = self({\"run\": run, \"example\": example}, include_run_info=True)\n            return self._prepare_evaluator_output(result)\n        except Exception as e:\n            return EvaluationResult(\n                key=self.string_evaluator.evaluation_name,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html"}
{"id": "9767901d2013-8", "text": "return EvaluationResult(\n                key=self.string_evaluator.evaluation_name,\n                comment=f\"Error evaluating run {run.id}: {e}\",\n                # TODO: Add run ID once we can declare it via callbacks\n            )\n[docs]    async def aevaluate_run(\n        self, run: Run, example: Optional[Example] = None\n    ) -> EvaluationResult:\n        \"\"\"Evaluate an example.\"\"\"\n        try:\n            result = await self.acall(\n                {\"run\": run, \"example\": example}, include_run_info=True\n            )\n            return self._prepare_evaluator_output(result)\n        except Exception as e:\n            return EvaluationResult(\n                key=self.string_evaluator.evaluation_name,\n                comment=f\"Error evaluating run {run.id}: {e}\",\n            )\n[docs]    @classmethod\n    def from_run_and_data_type(\n        cls,\n        evaluator: StringEvaluator,\n        run_type: str,\n        data_type: DataType,\n        input_key: Optional[str] = None,\n        prediction_key: Optional[str] = None,\n        reference_key: Optional[str] = None,\n        tags: Optional[List[str]] = None,\n    ) -> StringRunEvaluatorChain:\n        \"\"\"\n        Create a StringRunEvaluatorChain from an evaluator and the run and dataset types.\n        This method provides an easy way to instantiate a StringRunEvaluatorChain, by\n        taking an evaluator and information about the type of run and the data.\n        The method supports LLM and chain runs.\n        Args:\n            evaluator (StringEvaluator): The string evaluator to use.\n            run_type (str): The type of run being evaluated.\n                Supported types are LLM and Chain.\n            data_type (DataType): The type of dataset used in the run.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html"}
{"id": "9767901d2013-9", "text": "data_type (DataType): The type of dataset used in the run.\n            input_key (str, optional): The key used to map the input from the run.\n            prediction_key (str, optional): The key used to map the prediction from the run.\n            reference_key (str, optional): The key used to map the reference from the dataset.\n            tags (List[str], optional): List of tags to attach to the evaluation chain.\n        Returns:\n            StringRunEvaluatorChain: The instantiated evaluation chain.\n        Raises:\n            ValueError: If the run type is not supported, or if the evaluator requires a\n                reference from the dataset but the reference key is not provided.\n        \"\"\"  # noqa: E501\n        # Configure how run inputs/predictions are passed to the evaluator\n        if run_type == \"llm\":\n            run_mapper: StringRunMapper = LLMStringRunMapper()\n        elif run_type == \"chain\":\n            run_mapper = ChainStringRunMapper(\n                input_key=input_key, prediction_key=prediction_key\n            )\n        else:\n            raise ValueError(\n                f\"Unsupported run type {run_type}. Expected one of 'llm' or 'chain'.\"\n            )\n        # Configure how example rows are fed as a reference string to the evaluator\n        if (\n            reference_key is not None\n            or data_type in (DataType.llm, DataType.chat)\n            or evaluator.requires_reference\n        ):\n            example_mapper = StringExampleMapper(reference_key=reference_key)\n        elif evaluator.requires_reference:\n            raise ValueError(\n                f\"Evaluator {evaluator.evaluation_name} requires a reference\"\n                \" example from the dataset. Please specify the reference key from\"\n                \" amongst the dataset outputs keys.\"\n            )\n        else:\n            example_mapper = None\n        return cls(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html"}
{"id": "9767901d2013-10", "text": ")\n        else:\n            example_mapper = None\n        return cls(\n            name=evaluator.evaluation_name,\n            run_mapper=run_mapper,\n            example_mapper=example_mapper,\n            string_evaluator=evaluator,\n            tags=tags,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html"}
{"id": "c128777ea886-0", "text": "Source code for langchain.smith.evaluation.name_generation\nimport random\nadjectives = [\n    \"abandoned\",\n    \"aching\",\n    \"advanced\",\n    \"ample\",\n    \"artistic\",\n    \"back\",\n    \"best\",\n    \"bold\",\n    \"brief\",\n    \"clear\",\n    \"cold\",\n    \"complicated\",\n    \"cooked\",\n    \"crazy\",\n    \"crushing\",\n    \"damp\",\n    \"dear\",\n    \"definite\",\n    \"dependable\",\n    \"diligent\",\n    \"drab\",\n    \"earnest\",\n    \"elderly\",\n    \"enchanted\",\n    \"essential\",\n    \"excellent\",\n    \"extraneous\",\n    \"fixed\",\n    \"flowery\",\n    \"formal\",\n    \"fresh\",\n    \"frosty\",\n    \"giving\",\n    \"glossy\",\n    \"healthy\",\n    \"helpful\",\n    \"impressionable\",\n    \"kind\",\n    \"large\",\n    \"left\",\n    \"long\",\n    \"loyal\",\n    \"mealy\",\n    \"memorable\",\n    \"monthly\",\n    \"new\",\n    \"notable\",\n    \"only\",\n    \"ordinary\",\n    \"passionate\",\n    \"perfect\",\n    \"pertinent\",\n    \"proper\",\n    \"puzzled\",\n    \"reflecting\",\n    \"respectful\",\n    \"roasted\",\n    \"scholarly\",\n    \"shiny\",\n    \"slight\",\n    \"sparkling\",\n    \"spotless\",\n    \"stupendous\",\n    \"sunny\",\n    \"tart\",\n    \"terrific\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html"}
{"id": "c128777ea886-1", "text": "\"sunny\",\n    \"tart\",\n    \"terrific\",\n    \"timely\",\n    \"unique\",\n    \"upbeat\",\n    \"vacant\",\n    \"virtual\",\n    \"warm\",\n    \"weary\",\n    \"whispered\",\n    \"worthwhile\",\n    \"yellow\",\n]\nnouns = [\n    \"account\",\n    \"acknowledgment\",\n    \"address\",\n    \"advertising\",\n    \"airplane\",\n    \"animal\",\n    \"appointment\",\n    \"arrival\",\n    \"artist\",\n    \"attachment\",\n    \"attitude\",\n    \"availability\",\n    \"backpack\",\n    \"bag\",\n    \"balance\",\n    \"bass\",\n    \"bean\",\n    \"beauty\",\n    \"bibliography\",\n    \"bill\",\n    \"bite\",\n    \"blossom\",\n    \"boat\",\n    \"book\",\n    \"box\",\n    \"boy\",\n    \"bread\",\n    \"bridge\",\n    \"broccoli\",\n    \"building\",\n    \"butter\",\n    \"button\",\n    \"cabbage\",\n    \"cake\",\n    \"camera\",\n    \"camp\",\n    \"candle\",\n    \"candy\",\n    \"canvas\",\n    \"car\",\n    \"card\",\n    \"carrot\",\n    \"cart\",\n    \"case\",\n    \"cat\",\n    \"chain\",\n    \"chair\",\n    \"chalk\",\n    \"chance\",\n    \"change\",\n    \"channel\",\n    \"character\",\n    \"charge\",\n    \"charm\",\n    \"chart\",\n    \"check\",\n    \"cheek\",\n    \"cheese\",\n    \"chef\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html"}
{"id": "c128777ea886-2", "text": "\"cheek\",\n    \"cheese\",\n    \"chef\",\n    \"cherry\",\n    \"chicken\",\n    \"child\",\n    \"church\",\n    \"circle\",\n    \"class\",\n    \"clay\",\n    \"click\",\n    \"clock\",\n    \"cloth\",\n    \"cloud\",\n    \"clove\",\n    \"club\",\n    \"coach\",\n    \"coal\",\n    \"coast\",\n    \"coat\",\n    \"cod\",\n    \"coffee\",\n    \"collar\",\n    \"color\",\n    \"comb\",\n    \"comfort\",\n    \"comic\",\n    \"committee\",\n    \"community\",\n    \"company\",\n    \"comparison\",\n    \"competition\",\n    \"condition\",\n    \"connection\",\n    \"control\",\n    \"cook\",\n    \"copper\",\n    \"copy\",\n    \"corn\",\n    \"cough\",\n    \"country\",\n    \"cover\",\n    \"crate\",\n    \"crayon\",\n    \"cream\",\n    \"creator\",\n    \"crew\",\n    \"crown\",\n    \"current\",\n    \"curtain\",\n    \"curve\",\n    \"cushion\",\n    \"dad\",\n    \"daughter\",\n    \"day\",\n    \"death\",\n    \"debt\",\n    \"decision\",\n    \"deer\",\n    \"degree\",\n    \"design\",\n    \"desire\",\n    \"desk\",\n    \"detail\",\n    \"development\",\n    \"digestion\",\n    \"dime\",\n    \"dinner\",\n    \"direction\",\n    \"dirt\",\n    \"discovery\",\n    \"discussion\",\n    \"disease\",\n    \"disgust\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html"}
{"id": "c128777ea886-3", "text": "\"discussion\",\n    \"disease\",\n    \"disgust\",\n    \"distance\",\n    \"distribution\",\n    \"division\",\n    \"doctor\",\n    \"dog\",\n    \"door\",\n    \"drain\",\n    \"drawer\",\n    \"dress\",\n    \"drink\",\n    \"driving\",\n    \"dust\",\n    \"ear\",\n    \"earth\",\n    \"edge\",\n    \"education\",\n    \"effect\",\n    \"egg\",\n    \"end\",\n    \"energy\",\n    \"engine\",\n    \"error\",\n    \"event\",\n    \"example\",\n    \"exchange\",\n    \"existence\",\n    \"expansion\",\n    \"experience\",\n    \"expert\",\n    \"eye\",\n    \"face\",\n    \"fact\",\n    \"fall\",\n    \"family\",\n    \"farm\",\n    \"father\",\n    \"fear\",\n    \"feeling\",\n    \"field\",\n    \"finger\",\n    \"fire\",\n    \"fish\",\n    \"flag\",\n    \"flight\",\n    \"floor\",\n    \"flower\",\n    \"fold\",\n    \"food\",\n    \"football\",\n    \"force\",\n    \"form\",\n    \"frame\",\n    \"friend\",\n    \"frog\",\n    \"fruit\",\n    \"fuel\",\n    \"furniture\",\n    \"game\",\n    \"garden\",\n    \"gate\",\n    \"girl\",\n    \"glass\",\n    \"glove\",\n    \"goat\",\n    \"gold\",\n    \"government\",\n    \"grade\",\n    \"grain\",\n    \"grass\",\n    \"green\",\n    \"grip\",\n    \"group\",\n    \"growth\",\n    \"guide\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html"}
{"id": "c128777ea886-4", "text": "\"group\",\n    \"growth\",\n    \"guide\",\n    \"guitar\",\n    \"hair\",\n    \"hall\",\n    \"hand\",\n    \"harbor\",\n    \"harmony\",\n    \"hat\",\n    \"head\",\n    \"health\",\n    \"heart\",\n    \"heat\",\n    \"hill\",\n    \"history\",\n    \"hobbies\",\n    \"hole\",\n    \"hope\",\n    \"horn\",\n    \"horse\",\n    \"hospital\",\n    \"hour\",\n    \"house\",\n    \"humor\",\n    \"idea\",\n    \"impulse\",\n    \"income\",\n    \"increase\",\n    \"industry\",\n    \"ink\",\n    \"insect\",\n    \"instrument\",\n    \"insurance\",\n    \"interest\",\n    \"invention\",\n    \"iron\",\n    \"island\",\n    \"jelly\",\n    \"jet\",\n    \"jewel\",\n    \"join\",\n    \"judge\",\n    \"juice\",\n    \"jump\",\n    \"kettle\",\n    \"key\",\n    \"kick\",\n    \"kiss\",\n    \"kitten\",\n    \"knee\",\n    \"knife\",\n    \"knowledge\",\n    \"land\",\n    \"language\",\n    \"laugh\",\n    \"law\",\n    \"lead\",\n    \"learning\",\n    \"leather\",\n    \"leg\",\n    \"lettuce\",\n    \"level\",\n    \"library\",\n    \"lift\",\n    \"light\",\n    \"limit\",\n    \"line\",\n    \"linen\",\n    \"lip\",\n    \"liquid\",\n    \"list\",\n    \"look\",\n    \"loss\",\n    \"love\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html"}
{"id": "c128777ea886-5", "text": "\"list\",\n    \"look\",\n    \"loss\",\n    \"love\",\n    \"lunch\",\n    \"machine\",\n    \"man\",\n    \"manager\",\n    \"map\",\n    \"marble\",\n    \"mark\",\n    \"market\",\n    \"mass\",\n    \"match\",\n    \"meal\",\n    \"measure\",\n    \"meat\",\n    \"meeting\",\n    \"memory\",\n    \"metal\",\n    \"middle\",\n    \"milk\",\n    \"mind\",\n    \"mine\",\n    \"minute\",\n    \"mist\",\n    \"mitten\",\n    \"mom\",\n    \"money\",\n    \"monkey\",\n    \"month\",\n    \"moon\",\n    \"morning\",\n    \"mother\",\n    \"motion\",\n    \"mountain\",\n    \"mouth\",\n    \"muscle\",\n    \"music\",\n    \"nail\",\n    \"name\",\n    \"nation\",\n    \"neck\",\n    \"need\",\n    \"news\",\n    \"night\",\n    \"noise\",\n    \"note\",\n    \"number\",\n    \"nut\",\n    \"observation\",\n    \"offer\",\n    \"oil\",\n    \"operation\",\n    \"opinion\",\n    \"orange\",\n    \"order\",\n    \"organization\",\n    \"ornament\",\n    \"oven\",\n    \"page\",\n    \"pail\",\n    \"pain\",\n    \"paint\",\n    \"pan\",\n    \"pancake\",\n    \"paper\",\n    \"parcel\",\n    \"parent\",\n    \"part\",\n    \"passenger\",\n    \"paste\",\n    \"payment\",\n    \"peace\",\n    \"pear\",\n    \"pen\",\n    \"pencil\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html"}
{"id": "c128777ea886-6", "text": "\"pear\",\n    \"pen\",\n    \"pencil\",\n    \"person\",\n    \"pest\",\n    \"pet\",\n    \"picture\",\n    \"pie\",\n    \"pin\",\n    \"pipe\",\n    \"pizza\",\n    \"place\",\n    \"plane\",\n    \"plant\",\n    \"plastic\",\n    \"plate\",\n    \"play\",\n    \"pleasure\",\n    \"plot\",\n    \"plough\",\n    \"pocket\",\n    \"point\",\n    \"poison\",\n    \"police\",\n    \"pollution\",\n    \"popcorn\",\n    \"porter\",\n    \"position\",\n    \"pot\",\n    \"potato\",\n    \"powder\",\n    \"power\",\n    \"price\",\n    \"print\",\n    \"process\",\n    \"produce\",\n    \"product\",\n    \"profit\",\n    \"property\",\n    \"prose\",\n    \"protest\",\n    \"pull\",\n    \"pump\",\n    \"punishment\",\n    \"purpose\",\n    \"push\",\n    \"quarter\",\n    \"question\",\n    \"quiet\",\n    \"quill\",\n    \"quilt\",\n    \"quince\",\n    \"rabbit\",\n    \"rail\",\n    \"rain\",\n    \"range\",\n    \"rat\",\n    \"rate\",\n    \"ray\",\n    \"reaction\",\n    \"reading\",\n    \"reason\",\n    \"record\",\n    \"regret\",\n    \"relation\",\n    \"religion\",\n    \"representative\",\n    \"request\",\n    \"respect\",\n    \"rest\",\n    \"reward\",\n    \"rhythm\",\n    \"rice\",\n    \"river\",\n    \"road\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html"}
{"id": "c128777ea886-7", "text": "\"rice\",\n    \"river\",\n    \"road\",\n    \"roll\",\n    \"room\",\n    \"root\",\n    \"rose\",\n    \"route\",\n    \"rub\",\n    \"rule\",\n    \"run\",\n    \"sack\",\n    \"sail\",\n    \"salt\",\n    \"sand\",\n    \"scale\",\n    \"scarecrow\",\n    \"scarf\",\n    \"scene\",\n    \"scent\",\n    \"school\",\n    \"science\",\n    \"scissors\",\n    \"screw\",\n    \"sea\",\n    \"seat\",\n    \"secretary\",\n    \"seed\",\n    \"selection\",\n    \"self\",\n    \"sense\",\n    \"servant\",\n    \"shade\",\n    \"shake\",\n    \"shame\",\n    \"shape\",\n    \"sheep\",\n    \"sheet\",\n    \"shelf\",\n    \"ship\",\n    \"shirt\",\n    \"shock\",\n    \"shoe\",\n    \"shop\",\n    \"show\",\n    \"side\",\n    \"sign\",\n    \"silk\",\n    \"sink\",\n    \"sister\",\n    \"size\",\n    \"sky\",\n    \"slave\",\n    \"sleep\",\n    \"smash\",\n    \"smell\",\n    \"smile\",\n    \"smoke\",\n    \"snail\",\n    \"snake\",\n    \"sneeze\",\n    \"snow\",\n    \"soap\",\n    \"society\",\n    \"sock\",\n    \"soda\",\n    \"sofa\",\n    \"son\",\n    \"song\",\n    \"sort\",\n    \"sound\",\n    \"soup\",\n    \"space\",\n    \"spark\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html"}
{"id": "c128777ea886-8", "text": "\"sound\",\n    \"soup\",\n    \"space\",\n    \"spark\",\n    \"speed\",\n    \"sponge\",\n    \"spoon\",\n    \"spray\",\n    \"spring\",\n    \"spy\",\n    \"square\",\n    \"stamp\",\n    \"star\",\n    \"start\",\n    \"statement\",\n    \"station\",\n    \"steam\",\n    \"steel\",\n    \"stem\",\n    \"step\",\n    \"stew\",\n    \"stick\",\n    \"stitch\",\n    \"stocking\",\n    \"stomach\",\n    \"stone\",\n    \"stop\",\n    \"store\",\n    \"story\",\n    \"stove\",\n    \"stranger\",\n    \"straw\",\n    \"stream\",\n    \"street\",\n    \"stretch\",\n    \"string\",\n    \"structure\",\n    \"substance\",\n    \"sugar\",\n    \"suggestion\",\n    \"suit\",\n    \"summer\",\n    \"sun\",\n    \"support\",\n    \"surprise\",\n    \"sweater\",\n    \"swim\",\n    \"system\",\n    \"table\",\n    \"tail\",\n    \"talk\",\n    \"tank\",\n    \"taste\",\n    \"tax\",\n    \"tea\",\n    \"teaching\",\n    \"team\",\n    \"tendency\",\n    \"test\",\n    \"texture\",\n    \"theory\",\n    \"thing\",\n    \"thought\",\n    \"thread\",\n    \"throat\",\n    \"thumb\",\n    \"thunder\",\n    \"ticket\",\n    \"time\",\n    \"tin\",\n    \"title\",\n    \"toad\",\n    \"toe\",\n    \"tooth\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html"}
{"id": "c128777ea886-9", "text": "\"toad\",\n    \"toe\",\n    \"tooth\",\n    \"toothpaste\",\n    \"touch\",\n    \"town\",\n    \"toy\",\n    \"trade\",\n    \"train\",\n    \"transport\",\n    \"tray\",\n    \"treatment\",\n    \"tree\",\n    \"trick\",\n    \"trip\",\n    \"trouble\",\n    \"trousers\",\n    \"truck\",\n    \"tub\",\n    \"turkey\",\n    \"turn\",\n    \"twist\",\n    \"umbrella\",\n    \"uncle\",\n    \"underwear\",\n    \"unit\",\n    \"use\",\n    \"vacation\",\n    \"value\",\n    \"van\",\n    \"vase\",\n    \"vegetable\",\n    \"veil\",\n    \"vein\",\n    \"verse\",\n    \"vessel\",\n    \"view\",\n    \"visitor\",\n    \"voice\",\n    \"volcano\",\n    \"walk\",\n    \"wall\",\n    \"war\",\n    \"wash\",\n    \"waste\",\n    \"watch\",\n    \"water\",\n    \"wave\",\n    \"wax\",\n    \"way\",\n    \"wealth\",\n    \"weather\",\n    \"week\",\n    \"weight\",\n    \"wheel\",\n    \"whip\",\n    \"whistle\",\n    \"window\",\n    \"wine\",\n    \"wing\",\n    \"winter\",\n    \"wire\",\n    \"wish\",\n    \"woman\",\n    \"wood\",\n    \"wool\",\n    \"word\",\n    \"work\",\n    \"worm\",\n    \"wound\",\n    \"wrist\",\n    \"writer\",\n    \"yard\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html"}
{"id": "c128777ea886-10", "text": "\"wrist\",\n    \"writer\",\n    \"yard\",\n    \"yoke\",\n    \"zebra\",\n    \"zinc\",\n    \"zipper\",\n    \"zone\",\n]\n[docs]def random_name(prefix: str = \"test\") -> str:\n    \"\"\"Generate a random name.\"\"\"\n    adjective = random.choice(adjectives)\n    noun = random.choice(nouns)\n    number = random.randint(1, 100)\n    return f\"{prefix}-{adjective}-{noun}-{number}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html"}
{"id": "4c966120638b-0", "text": "Source code for langchain.smith.evaluation.progress\n\"\"\"A simple progress bar for the console.\"\"\"\nimport threading\nfrom typing import Any, Dict, Optional, Sequence\nfrom uuid import UUID\nfrom langchain.callbacks import base as base_callbacks\nfrom langchain.schema.document import Document\nfrom langchain.schema.output import LLMResult\n[docs]class ProgressBarCallback(base_callbacks.BaseCallbackHandler):\n    \"\"\"A simple progress bar for the console.\"\"\"\n[docs]    def __init__(self, total: int, ncols: int = 50, **kwargs: Any):\n        \"\"\"Initialize the progress bar.\n        Args:\n            total: int, the total number of items to be processed.\n            ncols: int, the character width of the progress bar.\n        \"\"\"\n        self.total = total\n        self.ncols = ncols\n        self.counter = 0\n        self.lock = threading.Lock()\n        self._print_bar()\n[docs]    def increment(self) -> None:\n        \"\"\"Increment the counter and update the progress bar.\"\"\"\n        with self.lock:\n            self.counter += 1\n            self._print_bar()\n    def _print_bar(self) -> None:\n        \"\"\"Print the progress bar to the console.\"\"\"\n        progress = self.counter / self.total\n        arrow = \"-\" * int(round(progress * self.ncols) - 1) + \">\"\n        spaces = \" \" * (self.ncols - len(arrow))\n        print(f\"\\r[{arrow + spaces}] {self.counter}/{self.total}\", end=\"\")\n[docs]    def on_chain_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if parent_run_id is None:\n            self.increment()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/progress.html"}
{"id": "4c966120638b-1", "text": ") -> Any:\n        if parent_run_id is None:\n            self.increment()\n[docs]    def on_chain_end(\n        self,\n        outputs: Dict[str, Any],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if parent_run_id is None:\n            self.increment()\n[docs]    def on_retriever_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if parent_run_id is None:\n            self.increment()\n[docs]    def on_retriever_end(\n        self,\n        documents: Sequence[Document],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if parent_run_id is None:\n            self.increment()\n[docs]    def on_llm_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if parent_run_id is None:\n            self.increment()\n[docs]    def on_llm_end(\n        self,\n        response: LLMResult,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if parent_run_id is None:\n            self.increment()\n[docs]    def on_tool_error(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/progress.html"}
{"id": "4c966120638b-2", "text": "self.increment()\n[docs]    def on_tool_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if parent_run_id is None:\n            self.increment()\n[docs]    def on_tool_end(\n        self,\n        output: str,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        if parent_run_id is None:\n            self.increment()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/progress.html"}
{"id": "2dfea7e2b96b-0", "text": "Source code for langchain.smith.evaluation.config\n\"\"\"Configuration for run evaluators.\"\"\"\nfrom typing import Any, Dict, List, Optional, Union\nfrom langsmith import RunEvaluator\nfrom langchain.evaluation.criteria.eval_chain import CRITERIA_TYPE\nfrom langchain.evaluation.embedding_distance.base import (\n    EmbeddingDistance as EmbeddingDistanceEnum,\n)\nfrom langchain.evaluation.schema import EvaluatorType, StringEvaluator\nfrom langchain.evaluation.string_distance.base import (\n    StringDistance as StringDistanceEnum,\n)\nfrom langchain.pydantic_v1 import BaseModel, Field\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.prompt_template import BasePromptTemplate\n[docs]class EvalConfig(BaseModel):\n    \"\"\"Configuration for a given run evaluator.\n    Parameters\n    ----------\n    evaluator_type : EvaluatorType\n        The type of evaluator to use.\n    Methods\n    -------\n    get_kwargs()\n        Get the keyword arguments for the evaluator configuration.\n    \"\"\"\n    evaluator_type: EvaluatorType\n[docs]    def get_kwargs(self) -> Dict[str, Any]:\n        \"\"\"Get the keyword arguments for the load_evaluator call.\n        Returns\n        -------\n        Dict[str, Any]\n            The keyword arguments for the load_evaluator call.\n        \"\"\"\n        kwargs = {}\n        for field, val in self:\n            if field == \"evaluator_type\":\n                continue\n            elif val is None:\n                continue\n            kwargs[field] = val\n        return kwargs\n[docs]class SingleKeyEvalConfig(EvalConfig):\n    reference_key: Optional[str] = None\n    \"\"\"The key in the dataset run to use as the reference string.\n    If not provided, we will attempt to infer automatically.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html"}
{"id": "2dfea7e2b96b-1", "text": "If not provided, we will attempt to infer automatically.\"\"\"\n    prediction_key: Optional[str] = None\n    \"\"\"The key from the traced run's outputs dictionary to use to\n    represent the prediction. If not provided, it will be inferred\n    automatically.\"\"\"\n    input_key: Optional[str] = None\n    \"\"\"The key from the traced run's inputs dictionary to use to represent the\n    input. If not provided, it will be inferred automatically.\"\"\"\n[docs]    def get_kwargs(self) -> Dict[str, Any]:\n        kwargs = super().get_kwargs()\n        # Filer out the keys that are not needed for the evaluator.\n        for key in [\"reference_key\", \"prediction_key\", \"input_key\"]:\n            kwargs.pop(key, None)\n        return kwargs\n[docs]class RunEvalConfig(BaseModel):\n    \"\"\"Configuration for a run evaluation.\n    Parameters\n    ----------\n    evaluators : List[Union[EvaluatorType, EvalConfig]]\n        Configurations for which evaluators to apply to the dataset run.\n        Each can be the string of an :class:`EvaluatorType <langchain.evaluation.schema.EvaluatorType>`, such\n        as EvaluatorType.QA, the evaluator type string (\"qa\"), or a configuration for a\n        given evaluator (e.g., :class:`RunEvalConfig.QA <langchain.smith.evaluation.config.RunEvalConfig.QA>`).\n    custom_evaluators : Optional[List[Union[RunEvaluator, StringEvaluator]]]\n        Custom evaluators to apply to the dataset run.\n    reference_key : Optional[str]\n        The key in the dataset run to use as the reference string.\n        If not provided, it will be inferred automatically.\n    prediction_key : Optional[str]\n        The key from the traced run's outputs dictionary to use to", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html"}
{"id": "2dfea7e2b96b-2", "text": "The key from the traced run's outputs dictionary to use to\n        represent the prediction. If not provided, it will be inferred\n        automatically.\n    input_key : Optional[str]\n        The key from the traced run's inputs dictionary to use to represent the\n        input. If not provided, it will be inferred automatically.\n    eval_llm : Optional[BaseLanguageModel]\n        The language model to pass to any evaluators that use a language model.\n    \"\"\"  # noqa: E501\n    evaluators: List[Union[EvaluatorType, str, EvalConfig]] = Field(\n        default_factory=list\n    )\n    \"\"\"Configurations for which evaluators to apply to the dataset run.\n    Each can be the string of an\n    :class:`EvaluatorType <langchain.evaluation.schema.EvaluatorType>`, such\n    as `EvaluatorType.QA`, the evaluator type string (\"qa\"), or a configuration for a\n    given evaluator\n    (e.g., \n    :class:`RunEvalConfig.QA <langchain.smith.evaluation.config.RunEvalConfig.QA>`).\"\"\"  # noqa: E501\n    custom_evaluators: Optional[List[Union[RunEvaluator, StringEvaluator]]] = None\n    \"\"\"Custom evaluators to apply to the dataset run.\"\"\"\n    reference_key: Optional[str] = None\n    \"\"\"The key in the dataset run to use as the reference string.\n    If not provided, we will attempt to infer automatically.\"\"\"\n    prediction_key: Optional[str] = None\n    \"\"\"The key from the traced run's outputs dictionary to use to\n    represent the prediction. If not provided, it will be inferred\n    automatically.\"\"\"\n    input_key: Optional[str] = None\n    \"\"\"The key from the traced run's inputs dictionary to use to represent the", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html"}
{"id": "2dfea7e2b96b-3", "text": "\"\"\"The key from the traced run's inputs dictionary to use to represent the\n    input. If not provided, it will be inferred automatically.\"\"\"\n    eval_llm: Optional[BaseLanguageModel] = None\n    \"\"\"The language model to pass to any evaluators that require one.\"\"\"\n    class Config:\n        arbitrary_types_allowed = True\n[docs]    class Criteria(SingleKeyEvalConfig):\n        \"\"\"Configuration for a reference-free criteria evaluator.\n        Parameters\n        ----------\n        criteria : Optional[CRITERIA_TYPE]\n            The criteria to evaluate.\n        llm : Optional[BaseLanguageModel]\n            The language model to use for the evaluation chain.\n        \"\"\"\n        criteria: Optional[CRITERIA_TYPE] = None\n        llm: Optional[BaseLanguageModel] = None\n        evaluator_type: EvaluatorType = EvaluatorType.CRITERIA\n        def __init__(\n            self, criteria: Optional[CRITERIA_TYPE] = None, **kwargs: Any\n        ) -> None:\n            super().__init__(criteria=criteria, **kwargs)\n[docs]    class LabeledCriteria(SingleKeyEvalConfig):\n        \"\"\"Configuration for a labeled (with references) criteria evaluator.\n        Parameters\n        ----------\n        criteria : Optional[CRITERIA_TYPE]\n            The criteria to evaluate.\n        llm : Optional[BaseLanguageModel]\n            The language model to use for the evaluation chain.\n        \"\"\"\n        criteria: Optional[CRITERIA_TYPE] = None\n        llm: Optional[BaseLanguageModel] = None\n        evaluator_type: EvaluatorType = EvaluatorType.LABELED_CRITERIA\n        def __init__(\n            self, criteria: Optional[CRITERIA_TYPE] = None, **kwargs: Any\n        ) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html"}
{"id": "2dfea7e2b96b-4", "text": ") -> None:\n            super().__init__(criteria=criteria, **kwargs)\n[docs]    class EmbeddingDistance(SingleKeyEvalConfig):\n        \"\"\"Configuration for an embedding distance evaluator.\n        Parameters\n        ----------\n        embeddings : Optional[Embeddings]\n            The embeddings to use for computing the distance.\n        distance_metric : Optional[EmbeddingDistanceEnum]\n            The distance metric to use for computing the distance.\n        \"\"\"\n        evaluator_type: EvaluatorType = EvaluatorType.EMBEDDING_DISTANCE\n        embeddings: Optional[Embeddings] = None\n        distance_metric: Optional[EmbeddingDistanceEnum] = None\n        class Config:\n            arbitrary_types_allowed = True\n[docs]    class StringDistance(SingleKeyEvalConfig):\n        \"\"\"Configuration for a string distance evaluator.\n        Parameters\n        ----------\n        distance : Optional[StringDistanceEnum]\n            The string distance metric to use.\n        \"\"\"\n        evaluator_type: EvaluatorType = EvaluatorType.STRING_DISTANCE\n        distance: Optional[StringDistanceEnum] = None\n        \"\"\"The string distance metric to use.\n            damerau_levenshtein: The Damerau-Levenshtein distance.\n            levenshtein: The Levenshtein distance.\n            jaro: The Jaro distance.\n            jaro_winkler: The Jaro-Winkler distance.\n        \"\"\"\n        normalize_score: bool = True\n        \"\"\"Whether to normalize the distance to between 0 and 1.\n        Applies only to the Levenshtein and Damerau-Levenshtein distances.\"\"\"\n[docs]    class QA(SingleKeyEvalConfig):\n        \"\"\"Configuration for a QA evaluator.\n        Parameters\n        ----------\n        prompt : Optional[BasePromptTemplate]\n            The prompt template to use for generating the question.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html"}
{"id": "2dfea7e2b96b-5", "text": "The prompt template to use for generating the question.\n        llm : Optional[BaseLanguageModel]\n            The language model to use for the evaluation chain.\n        \"\"\"\n        evaluator_type: EvaluatorType = EvaluatorType.QA\n        llm: Optional[BaseLanguageModel] = None\n        prompt: Optional[BasePromptTemplate] = None\n[docs]    class ContextQA(SingleKeyEvalConfig):\n        \"\"\"Configuration for a context-based QA evaluator.\n        Parameters\n        ----------\n        prompt : Optional[BasePromptTemplate]\n            The prompt template to use for generating the question.\n        llm : Optional[BaseLanguageModel]\n            The language model to use for the evaluation chain.\n        \"\"\"\n        evaluator_type: EvaluatorType = EvaluatorType.CONTEXT_QA\n        llm: Optional[BaseLanguageModel] = None\n        prompt: Optional[BasePromptTemplate] = None\n[docs]    class CoTQA(SingleKeyEvalConfig):\n        \"\"\"Configuration for a context-based QA evaluator.\n        Parameters\n        ----------\n        prompt : Optional[BasePromptTemplate]\n            The prompt template to use for generating the question.\n        llm : Optional[BaseLanguageModel]\n            The language model to use for the evaluation chain.\n        \"\"\"\n        evaluator_type: EvaluatorType = EvaluatorType.CONTEXT_QA\n        llm: Optional[BaseLanguageModel] = None\n        prompt: Optional[BasePromptTemplate] = None\n[docs]    class JsonValidity(SingleKeyEvalConfig):\n        \"\"\"Configuration for a json validity evaluator.\n        Parameters\n        ----------\n        \"\"\"\n        evaluator_type: EvaluatorType = EvaluatorType.JSON_VALIDITY\n[docs]    class JsonEqualityEvaluator(EvalConfig):\n        \"\"\"Configuration for a json equality evaluator.\n        Parameters\n        ----------\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html"}
{"id": "2dfea7e2b96b-6", "text": "\"\"\"Configuration for a json equality evaluator.\n        Parameters\n        ----------\n        \"\"\"\n        evaluator_type: EvaluatorType = EvaluatorType.JSON_EQUALITY\n[docs]    class ExactMatch(SingleKeyEvalConfig):\n        \"\"\"Configuration for an exact match string evaluator.\n        Parameters\n        ----------\n        ignore_case : bool\n            Whether to ignore case when comparing strings.\n        ignore_punctuation : bool\n            Whether to ignore punctuation when comparing strings.\n        ignore_numbers : bool\n            Whether to ignore numbers when comparing strings.\n        \"\"\"\n        evaluator_type: EvaluatorType = EvaluatorType.STRING_DISTANCE\n        ignore_case: bool = False\n        ignore_punctuation: bool = False\n        ignore_numbers: bool = False\n[docs]    class RegexMatch(SingleKeyEvalConfig):\n        \"\"\"Configuration for a regex match string evaluator.\n        Parameters\n        ----------\n        flags : int\n            The flags to pass to the regex. Example: re.IGNORECASE.\n        \"\"\"\n        evaluator_type: EvaluatorType = EvaluatorType.REGEX_MATCH\n        flags: int = 0\n[docs]    class ScoreString(SingleKeyEvalConfig):\n        \"\"\"Configuration for a score string evaluator.\n        This is like the criteria evaluator but it is configured by\n        default to return a score on the scale from 1-10.\n        It is recommended to normalize these scores\n        by setting `normalize_by` to 10.\n        Parameters\n        ----------\n        criteria : Optional[CRITERIA_TYPE]\n            The criteria to evaluate.\n        llm : Optional[BaseLanguageModel]\n            The language model to use for the evaluation chain.\n        normalize_by: Optional[int] = None\n            If you want to normalize the score, the denominator to use.\n            If not provided, the score will be between 1 and 10 (by default).", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html"}
{"id": "2dfea7e2b96b-7", "text": "If not provided, the score will be between 1 and 10 (by default).\n        prompt : Optional[BasePromptTemplate]\n        \"\"\"\n        evaluator_type: EvaluatorType = EvaluatorType.SCORE_STRING\n        criteria: Optional[CRITERIA_TYPE] = None\n        llm: Optional[BaseLanguageModel] = None\n        normalize_by: Optional[float] = None\n        prompt: Optional[BasePromptTemplate] = None\n        def __init__(\n            self,\n            criteria: Optional[CRITERIA_TYPE] = None,\n            normalize_by: Optional[float] = None,\n            **kwargs: Any,\n        ) -> None:\n            super().__init__(criteria=criteria, normalize_by=normalize_by, **kwargs)\n[docs]    class LabeledScoreString(ScoreString):\n        evaluator_type: EvaluatorType = EvaluatorType.LABELED_SCORE_STRING", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html"}
{"id": "94b373b81797-0", "text": "Source code for langchain.smith.evaluation.runner_utils\n\"\"\"Utilities for running language models or Chains over datasets.\"\"\"\nfrom __future__ import annotations\nimport functools\nimport inspect\nimport logging\nimport uuid\nfrom enum import Enum\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n    cast,\n)\nfrom langsmith.client import Client\nfrom langsmith.evaluation import RunEvaluator\nfrom langsmith.run_helpers import as_runnable, is_traceable_function\nfrom langsmith.schemas import Dataset, DataType, Example\nfrom langsmith.utils import LangSmithError\nfrom requests import HTTPError\nfrom langchain._api import warn_deprecated\nfrom langchain.callbacks.manager import Callbacks\nfrom langchain.callbacks.tracers.evaluation import (\n    EvaluatorCallbackHandler,\n    wait_for_all_evaluators,\n)\nfrom langchain.callbacks.tracers.langchain import LangChainTracer\nfrom langchain.chains.base import Chain\nfrom langchain.evaluation.loading import load_evaluator\nfrom langchain.evaluation.schema import (\n    EvaluatorType,\n    PairwiseStringEvaluator,\n    StringEvaluator,\n)\nfrom langchain.schema import ChatResult, LLMResult\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.messages import BaseMessage, messages_from_dict\nfrom langchain.schema.runnable import Runnable, RunnableConfig, RunnableLambda\nfrom langchain.schema.runnable import config as runnable_config\nfrom langchain.schema.runnable import utils as runnable_utils\nfrom langchain.smith import evaluation as smith_eval\nfrom langchain.smith.evaluation import config as smith_eval_config\nfrom langchain.smith.evaluation import name_generation, progress\nif TYPE_CHECKING:\n    import pandas as pd\nlogger = logging.getLogger(__name__)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-1", "text": "if TYPE_CHECKING:\n    import pandas as pd\nlogger = logging.getLogger(__name__)\nMODEL_OR_CHAIN_FACTORY = Union[\n    Callable[[], Union[Chain, Runnable]],\n    BaseLanguageModel,\n    Callable[[dict], Any],\n    Runnable,\n    Chain,\n]\nMCF = Union[Callable[[], Union[Chain, Runnable]], BaseLanguageModel]\n[docs]class InputFormatError(Exception):\n    \"\"\"Raised when the input format is invalid.\"\"\"\n## Shared Utilities\n[docs]class TestResult(dict):\n    \"\"\"A dictionary of the results of a single test run.\"\"\"\n[docs]    def get_aggregate_feedback(\n        self, quantiles: Optional[Sequence[float]] = None\n    ) -> pd.DataFrame:\n        \"\"\"Return quantiles for the feedback scores.\n        This method calculates and prints the quantiles for the feedback scores\n        across all feedback keys.\n        Returns:\n            A DataFrame containing the quantiles for each feedback key.\n        \"\"\"\n        df = self.to_dataframe()\n        feedback_cols = [\n            col for col in df.columns if col not in [\"input\", \"output\", \"reference\"]\n        ]\n        _quantiles = df[feedback_cols].quantile(\n            quantiles or [0.25, 0.5, 0.75], numeric_only=True\n        )\n        _quantiles.loc[\"mean\"] = df[feedback_cols].mean()\n        _quantiles.loc[\"mode\"] = df[feedback_cols].mode().iloc[0]\n        return _quantiles.transpose()\n[docs]    def to_dataframe(self) -> pd.DataFrame:\n        \"\"\"Convert the results to a dataframe.\"\"\"\n        try:\n            import pandas as pd\n        except ImportError as e:\n            raise ImportError(\n                \"Pandas is required to convert the results to a dataframe.\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-2", "text": "raise ImportError(\n                \"Pandas is required to convert the results to a dataframe.\"\n                \" to install pandas, run `pip install pandas`.\"\n            ) from e\n        indices = []\n        records = []\n        for example_id, result in self[\"results\"].items():\n            feedback = result[\"feedback\"]\n            r = {\n                **{f.key: f.score for f in feedback},\n                \"input\": result[\"input\"],\n                \"output\": result[\"output\"],\n                \"execution_time\": result[\"execution_time\"],\n            }\n            if \"reference\" in result:\n                r[\"reference\"] = result[\"reference\"]\n            records.append(r)\n            indices.append(example_id)\n        return pd.DataFrame(records, index=indices)\ndef _wrap_in_chain_factory(\n    llm_or_chain_factory: MODEL_OR_CHAIN_FACTORY,\n    dataset_name: str = \"<my_dataset>\",\n) -> MCF:\n    \"\"\"Forgive the user if they pass in a chain without memory instead of a chain\n    factory. It's a common mistake. Raise a more helpful error message as well.\"\"\"\n    if isinstance(llm_or_chain_factory, Chain):\n        chain = llm_or_chain_factory\n        chain_class = chain.__class__.__name__\n        if llm_or_chain_factory.memory is not None:\n            memory_class = chain.memory.__class__.__name__\n            raise ValueError(\n                \"Cannot directly evaluate a chain with stateful memory.\"\n                \" To evaluate this chain, pass in a chain constructor\"\n                \" that initializes fresh memory each time it is called.\"\n                \"  This will safegaurd against information\"\n                \" leakage between dataset examples.\"\n                \"\\nFor example:\\n\\n\"\n                \"def chain_constructor():\\n\"\n                f\"    new_memory = {memory_class}(...)\\n\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-3", "text": "f\"    new_memory = {memory_class}(...)\\n\"\n                f\"    return {chain_class}\"\n                \"(memory=new_memory, ...)\\n\\n\"\n                f'run_on_dataset(\"{dataset_name}\", chain_constructor, ...)'\n            )\n        return lambda: chain\n    elif isinstance(llm_or_chain_factory, BaseLanguageModel):\n        return llm_or_chain_factory\n    elif isinstance(llm_or_chain_factory, Runnable):\n        # Memory may exist here, but it's not elegant to check all those cases.\n        lcf = llm_or_chain_factory\n        return lambda: lcf\n    elif callable(llm_or_chain_factory):\n        if is_traceable_function(llm_or_chain_factory):\n            runnable_ = as_runnable(cast(Callable, llm_or_chain_factory))\n            return lambda: runnable_\n        try:\n            _model = llm_or_chain_factory()  # type: ignore[call-arg]\n        except TypeError:\n            # It's an arbitrary function, wrap it in a RunnableLambda\n            user_func = cast(Callable, llm_or_chain_factory)\n            sig = inspect.signature(user_func)\n            logger.info(f\"Wrapping function {sig} as RunnableLambda.\")\n            wrapped = RunnableLambda(user_func)\n            return lambda: wrapped\n        constructor = cast(Callable, llm_or_chain_factory)\n        if isinstance(_model, BaseLanguageModel):\n            # It's not uncommon to do an LLM constructor instead of raw LLM,\n            # so we'll unpack it for the user.\n            return _model\n        elif is_traceable_function(cast(Callable, _model)):\n            runnable_ = as_runnable(cast(Callable, _model))\n            return lambda: runnable_\n        elif not isinstance(_model, Runnable):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-4", "text": "return lambda: runnable_\n        elif not isinstance(_model, Runnable):\n            # This is unlikely to happen - a constructor for a model function\n            return lambda: RunnableLambda(constructor)\n        else:\n            # Typical correct case\n            return constructor  # noqa\n    return llm_or_chain_factory\ndef _get_prompt(inputs: Dict[str, Any]) -> str:\n    \"\"\"Get prompt from inputs.\n    Args:\n        inputs: The input dictionary.\n    Returns:\n        A string prompt.\n    Raises:\n        InputFormatError: If the input format is invalid.\n    \"\"\"\n    if not inputs:\n        raise InputFormatError(\"Inputs should not be empty.\")\n    prompts = []\n    if \"prompt\" in inputs:\n        if not isinstance(inputs[\"prompt\"], str):\n            raise InputFormatError(\n                \"Expected string for 'prompt', got\"\n                f\" {type(inputs['prompt']).__name__}\"\n            )\n        prompts = [inputs[\"prompt\"]]\n    elif \"prompts\" in inputs:\n        if not isinstance(inputs[\"prompts\"], list) or not all(\n            isinstance(i, str) for i in inputs[\"prompts\"]\n        ):\n            raise InputFormatError(\n                \"Expected list of strings for 'prompts',\"\n                f\" got {type(inputs['prompts']).__name__}\"\n            )\n        prompts = inputs[\"prompts\"]\n    elif len(inputs) == 1:\n        prompt_ = next(iter(inputs.values()))\n        if isinstance(prompt_, str):\n            prompts = [prompt_]\n        elif isinstance(prompt_, list) and all(isinstance(i, str) for i in prompt_):\n            prompts = prompt_\n        else:\n            raise InputFormatError(f\"LLM Run expects string prompt input. Got {inputs}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-5", "text": "raise InputFormatError(f\"LLM Run expects string prompt input. Got {inputs}\")\n    else:\n        raise InputFormatError(\n            f\"LLM Run expects 'prompt' or 'prompts' in inputs. Got {inputs}\"\n        )\n    if len(prompts) == 1:\n        return prompts[0]\n    else:\n        raise InputFormatError(\n            f\"LLM Run expects single prompt input. Got {len(prompts)} prompts.\"\n        )\ndef _get_messages(inputs: Dict[str, Any]) -> List[BaseMessage]:\n    \"\"\"Get Chat Messages from inputs.\n    Args:\n        inputs: The input dictionary.\n    Returns:\n        A list of chat messages.\n    Raises:\n        InputFormatError: If the input format is invalid.\n    \"\"\"\n    if not inputs:\n        raise InputFormatError(\"Inputs should not be empty.\")\n    if \"messages\" in inputs:\n        single_input = inputs[\"messages\"]\n    elif len(inputs) == 1:\n        single_input = next(iter(inputs.values()))\n    else:\n        raise InputFormatError(\n            f\"Chat Run expects 'messages' in inputs when example has multiple\"\n            f\" input keys. Got {inputs}\"\n        )\n    if isinstance(single_input, list) and all(\n        isinstance(i, dict) for i in single_input\n    ):\n        raw_messages = [single_input]\n    elif isinstance(single_input, list) and all(\n        isinstance(i, list) for i in single_input\n    ):\n        raw_messages = single_input\n    else:\n        raise InputFormatError(\n            f\"Chat Run expects List[dict] or List[List[dict]] values for\"\n            f\" 'messages' key input. Got {inputs}\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-6", "text": "f\" 'messages' key input. Got {inputs}\"\n        )\n    if len(raw_messages) == 1:\n        return messages_from_dict(raw_messages[0])\n    else:\n        raise InputFormatError(\n            f\"Chat Run expects single List[dict] or List[List[dict]] 'messages'\"\n            f\" input. Got {len(raw_messages)} messages from inputs {inputs}\"\n        )\n## Shared data validation utilities\ndef _validate_example_inputs_for_language_model(\n    first_example: Example,\n    input_mapper: Optional[Callable[[Dict], Any]],\n) -> None:\n    if input_mapper:\n        prompt_input = input_mapper(first_example.inputs)\n        if not isinstance(prompt_input, str) and not (\n            isinstance(prompt_input, list)\n            and all(isinstance(msg, BaseMessage) for msg in prompt_input)\n        ):\n            raise InputFormatError(\n                \"When using an input_mapper to prepare dataset example inputs\"\n                \" for an LLM or chat model, the output must a single string or\"\n                \" a list of chat messages.\"\n                f\"\\nGot: {prompt_input} of type {type(prompt_input)}.\"\n            )\n    else:\n        try:\n            _get_prompt(first_example.inputs)\n        except InputFormatError:\n            try:\n                _get_messages(first_example.inputs)\n            except InputFormatError:\n                raise InputFormatError(\n                    \"Example inputs do not match language model input format. \"\n                    \"Expected a dictionary with messages or a single prompt.\"\n                    f\" Got: {first_example.inputs}\"\n                    \" Please update your dataset OR provide an input_mapper\"\n                    \" to convert the example.inputs to a compatible format\"\n                    \" for the llm or chat model you wish to evaluate.\"\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-7", "text": "\" for the llm or chat model you wish to evaluate.\"\n                )\ndef _validate_example_inputs_for_chain(\n    first_example: Example,\n    chain: Chain,\n    input_mapper: Optional[Callable[[Dict], Any]],\n) -> None:\n    \"\"\"Validate that the example inputs match the chain input keys.\"\"\"\n    if input_mapper:\n        first_inputs = input_mapper(first_example.inputs)\n        missing_keys = set(chain.input_keys).difference(first_inputs)\n        if not isinstance(first_inputs, dict):\n            raise InputFormatError(\n                \"When using an input_mapper to prepare dataset example\"\n                \" inputs for a chain, the mapped value must be a dictionary.\"\n                f\"\\nGot: {first_inputs} of type {type(first_inputs)}.\"\n            )\n        if missing_keys:\n            raise InputFormatError(\n                \"Missing keys after loading example using input_mapper.\"\n                f\"\\nExpected: {chain.input_keys}. Got: {first_inputs.keys()}\"\n            )\n    else:\n        first_inputs = first_example.inputs\n        missing_keys = set(chain.input_keys).difference(first_inputs)\n        if len(first_inputs) == 1 and len(chain.input_keys) == 1:\n            # We can pass this through the run method.\n            # Refrain from calling to validate.\n            pass\n        elif missing_keys:\n            raise InputFormatError(\n                \"Example inputs missing expected chain input keys.\"\n                \" Please provide an input_mapper to convert the example.inputs\"\n                \" to a compatible format for the chain you wish to evaluate.\"\n                f\"Expected: {chain.input_keys}. \"\n                f\"Got: {first_inputs.keys()}\"\n            )\ndef _validate_example_inputs(\n    example: Example,\n    llm_or_chain_factory: MCF,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-8", "text": "example: Example,\n    llm_or_chain_factory: MCF,\n    input_mapper: Optional[Callable[[Dict], Any]],\n) -> None:\n    \"\"\"Validate that the example inputs are valid for the model.\"\"\"\n    if isinstance(llm_or_chain_factory, BaseLanguageModel):\n        _validate_example_inputs_for_language_model(example, input_mapper)\n    else:\n        chain = llm_or_chain_factory()\n        if isinstance(chain, Chain):\n            # Otherwise it's a runnable\n            _validate_example_inputs_for_chain(example, chain, input_mapper)\n        elif isinstance(chain, Runnable):\n            logger.debug(f\"Skipping input validation for {chain}\")\n## Shared Evaluator Setup Utilities\ndef _setup_evaluation(\n    llm_or_chain_factory: MCF,\n    examples: List[Example],\n    evaluation: Optional[smith_eval.RunEvalConfig],\n    data_type: DataType,\n) -> Optional[List[RunEvaluator]]:\n    \"\"\"Configure the evaluators to run on the results of the chain.\"\"\"\n    if evaluation:\n        if isinstance(llm_or_chain_factory, BaseLanguageModel):\n            run_inputs, run_outputs = None, None\n            run_type = \"llm\"\n        else:\n            run_type = \"chain\"\n            if data_type in (DataType.chat, DataType.llm):\n                val = data_type.value if isinstance(data_type, Enum) else data_type\n                raise ValueError(\n                    \"Cannot evaluate a chain on dataset with \"\n                    f\"data_type={val}. \"\n                    \"Please specify a dataset with the default 'kv' data type.\"\n                )\n            chain = llm_or_chain_factory()\n            run_inputs = chain.input_keys if isinstance(chain, Chain) else None\n            run_outputs = chain.output_keys if isinstance(chain, Chain) else None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-9", "text": "run_outputs = chain.output_keys if isinstance(chain, Chain) else None\n        run_evaluators = _load_run_evaluators(\n            evaluation,\n            run_type,\n            data_type,\n            list(examples[0].outputs) if examples[0].outputs else None,\n            run_inputs,\n            run_outputs,\n        )\n    else:\n        # TODO: Create a default helpfulness evaluator\n        run_evaluators = None\n    return run_evaluators\ndef _determine_input_key(\n    config: smith_eval.RunEvalConfig,\n    run_inputs: Optional[List[str]],\n) -> Optional[str]:\n    input_key = None\n    if config.input_key:\n        input_key = config.input_key\n        if run_inputs and input_key not in run_inputs:\n            logger.warning(\n                f\"Input key {input_key} not in chain's specified\"\n                f\" input keys {run_inputs}. Evaluation behavior may be undefined.\"\n            )\n    elif run_inputs and len(run_inputs) == 1:\n        input_key = run_inputs[0]\n    elif run_inputs is not None and len(run_inputs) > 1:\n        logger.warning(\n            f\"Chain expects multiple input keys: {run_inputs},\"\n            f\" Evaluator is likely to fail. Evaluation behavior may be undefined.\"\n            \" Specify an input_key in the RunEvalConfig to avoid this warning.\"\n        )\n    return input_key\ndef _determine_prediction_key(\n    config: smith_eval.RunEvalConfig,\n    run_outputs: Optional[List[str]],\n) -> Optional[str]:\n    prediction_key = None\n    if config.prediction_key:\n        prediction_key = config.prediction_key\n        if run_outputs and prediction_key not in run_outputs:\n            logger.warning(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-10", "text": "if run_outputs and prediction_key not in run_outputs:\n            logger.warning(\n                f\"Prediction key {prediction_key} not in chain's specified\"\n                f\" output keys {run_outputs}. Evaluation behavior may be undefined.\"\n            )\n    elif run_outputs and len(run_outputs) == 1:\n        prediction_key = run_outputs[0]\n    elif run_outputs is not None and len(run_outputs) > 1:\n        logger.warning(\n            f\"Chain expects multiple output keys: {run_outputs},\"\n            f\" Evaluation behavior may be undefined. Specify a prediction_key\"\n            \" in the RunEvalConfig to avoid this warning.\"\n        )\n    return prediction_key\ndef _determine_reference_key(\n    config: smith_eval.RunEvalConfig,\n    example_outputs: Optional[List[str]],\n) -> Optional[str]:\n    if config.reference_key:\n        reference_key = config.reference_key\n        if example_outputs and reference_key not in example_outputs:\n            raise ValueError(\n                f\"Reference key {reference_key} not in Dataset\"\n                f\" example outputs: {example_outputs}\"\n            )\n    elif example_outputs and len(example_outputs) == 1:\n        reference_key = list(example_outputs)[0]\n    else:\n        reference_key = None\n    return reference_key\ndef _construct_run_evaluator(\n    eval_config: Union[EvaluatorType, str, smith_eval_config.EvalConfig],\n    eval_llm: Optional[BaseLanguageModel],\n    run_type: str,\n    data_type: DataType,\n    example_outputs: Optional[List[str]],\n    reference_key: Optional[str],\n    input_key: Optional[str],\n    prediction_key: Optional[str],\n) -> RunEvaluator:\n    if isinstance(eval_config, (EvaluatorType, str)):\n        if not isinstance(eval_config, EvaluatorType):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-11", "text": "if not isinstance(eval_config, EvaluatorType):\n            eval_config = EvaluatorType(eval_config)\n        evaluator_ = load_evaluator(eval_config, llm=eval_llm)\n        eval_type_tag = eval_config.value\n    else:\n        kwargs = {\"llm\": eval_llm, **eval_config.get_kwargs()}\n        evaluator_ = load_evaluator(eval_config.evaluator_type, **kwargs)\n        eval_type_tag = eval_config.evaluator_type.value\n        # Override keys if specified in the config\n        if isinstance(eval_config, smith_eval_config.SingleKeyEvalConfig):\n            input_key = eval_config.input_key or input_key\n            prediction_key = eval_config.prediction_key or prediction_key\n            reference_key = eval_config.reference_key or reference_key\n    if isinstance(evaluator_, StringEvaluator):\n        if evaluator_.requires_reference and reference_key is None:\n            raise ValueError(\n                f\"Must specify reference_key in smith_eval.RunEvalConfig to use\"\n                f\" evaluator of type {eval_type_tag} with\"\n                f\" dataset with multiple output keys: {example_outputs}.\"\n            )\n        run_evaluator = smith_eval.StringRunEvaluatorChain.from_run_and_data_type(\n            evaluator_,\n            run_type,\n            data_type,\n            input_key=input_key,\n            prediction_key=prediction_key,\n            reference_key=reference_key,\n            tags=[eval_type_tag],\n        )\n    elif isinstance(evaluator_, PairwiseStringEvaluator):\n        raise NotImplementedError(\n            f\"Run evaluator for {eval_type_tag} is not implemented.\"\n            \" PairwiseStringEvaluators compare the outputs of two different models\"\n            \" rather than the output of a single model.\"\n            \" Did you mean to use a StringEvaluator instead?\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-12", "text": "\" Did you mean to use a StringEvaluator instead?\"\n            \"\\nSee: https://python.langchain.com/docs/guides/evaluation/string/\"\n        )\n    else:\n        raise NotImplementedError(\n            f\"Run evaluator for {eval_type_tag} is not implemented\"\n        )\n    return run_evaluator\ndef _get_keys(\n    config: smith_eval.RunEvalConfig,\n    run_inputs: Optional[List[str]],\n    run_outputs: Optional[List[str]],\n    example_outputs: Optional[List[str]],\n) -> Tuple[Optional[str], Optional[str], Optional[str]]:\n    input_key = _determine_input_key(config, run_inputs)\n    prediction_key = _determine_prediction_key(config, run_outputs)\n    reference_key = _determine_reference_key(config, example_outputs)\n    return input_key, prediction_key, reference_key\ndef _load_run_evaluators(\n    config: smith_eval.RunEvalConfig,\n    run_type: str,\n    data_type: DataType,\n    example_outputs: Optional[List[str]],\n    run_inputs: Optional[List[str]],\n    run_outputs: Optional[List[str]],\n) -> List[RunEvaluator]:\n    \"\"\"\n    Load run evaluators from a configuration.\n    Args:\n        config: Configuration for the run evaluators.\n    Returns:\n        A list of run evaluators.\n    \"\"\"\n    run_evaluators = []\n    input_key, prediction_key, reference_key = None, None, None\n    if (\n        config.evaluators\n        or any([isinstance(e, EvaluatorType) for e in config.evaluators])\n        or (\n            config.custom_evaluators\n            and any([isinstance(e, StringEvaluator) for e in config.custom_evaluators])\n        )\n    ):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-13", "text": ")\n    ):\n        input_key, prediction_key, reference_key = _get_keys(\n            config, run_inputs, run_outputs, example_outputs\n        )\n    for eval_config in config.evaluators:\n        run_evaluator = _construct_run_evaluator(\n            eval_config,\n            config.eval_llm,\n            run_type,\n            data_type,\n            example_outputs,\n            reference_key,\n            input_key,\n            prediction_key,\n        )\n        run_evaluators.append(run_evaluator)\n    custom_evaluators = config.custom_evaluators or []\n    for custom_evaluator in custom_evaluators:\n        if isinstance(custom_evaluator, RunEvaluator):\n            run_evaluators.append(custom_evaluator)\n        elif isinstance(custom_evaluator, StringEvaluator):\n            run_evaluators.append(\n                smith_eval.StringRunEvaluatorChain.from_run_and_data_type(\n                    custom_evaluator,\n                    run_type,\n                    data_type,\n                    input_key=input_key,\n                    prediction_key=prediction_key,\n                    reference_key=reference_key,\n                )\n            )\n        else:\n            raise ValueError(\n                f\"Unsupported custom evaluator: {custom_evaluator}.\"\n                f\" Expected RunEvaluator or StringEvaluator.\"\n            )\n    return run_evaluators\n### Async Helpers\nasync def _arun_llm(\n    llm: BaseLanguageModel,\n    inputs: Dict[str, Any],\n    *,\n    tags: Optional[List[str]] = None,\n    callbacks: Callbacks = None,\n    input_mapper: Optional[Callable[[Dict], Any]] = None,\n) -> Union[str, BaseMessage]:\n    \"\"\"Asynchronously run the language model.\n    Args:\n        llm: The language model to run.\n        inputs: The input dictionary.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-14", "text": "llm: The language model to run.\n        inputs: The input dictionary.\n        tags: Optional tags to add to the run.\n        callbacks: Optional callbacks to use during the run.\n        input_mapper: Optional function to map inputs to the expected format.\n    Returns:\n        The LLMResult or ChatResult.\n    Raises:\n        ValueError: If the LLM type is unsupported.\n        InputFormatError: If the input format is invalid.\n    \"\"\"\n    if input_mapper is not None:\n        prompt_or_messages = input_mapper(inputs)\n        if isinstance(prompt_or_messages, str):\n            return await llm.apredict(\n                prompt_or_messages, callbacks=callbacks, tags=tags\n            )\n        elif isinstance(prompt_or_messages, list) and all(\n            isinstance(msg, BaseMessage) for msg in prompt_or_messages\n        ):\n            return await llm.apredict_messages(\n                prompt_or_messages, callbacks=callbacks, tags=tags\n            )\n        else:\n            raise InputFormatError(\n                \"Input mapper returned invalid format\"\n                f\" {prompt_or_messages}\"\n                \"\\nExpected a single string or list of chat messages.\"\n            )\n    else:\n        try:\n            prompt = _get_prompt(inputs)\n            llm_output: Union[str, BaseMessage] = await llm.apredict(\n                prompt, callbacks=callbacks, tags=tags\n            )\n        except InputFormatError:\n            messages = _get_messages(inputs)\n            llm_output = await llm.apredict_messages(\n                messages, callbacks=callbacks, tags=tags\n            )\n    return llm_output\nasync def _arun_chain(\n    chain: Union[Chain, Runnable],\n    inputs: Dict[str, Any],\n    callbacks: Callbacks,\n    *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-15", "text": "inputs: Dict[str, Any],\n    callbacks: Callbacks,\n    *,\n    tags: Optional[List[str]] = None,\n    input_mapper: Optional[Callable[[Dict], Any]] = None,\n) -> Union[dict, str]:\n    \"\"\"Run a chain asynchronously on inputs.\"\"\"\n    inputs_ = inputs if input_mapper is None else input_mapper(inputs)\n    if (\n        isinstance(chain, Chain)\n        and isinstance(inputs_, dict)\n        and len(inputs_) == 1\n        and chain.input_keys\n    ):\n        val = next(iter(inputs_.values()))\n        output = await chain.acall(val, callbacks=callbacks, tags=tags)\n    else:\n        runnable_config = RunnableConfig(tags=tags or [], callbacks=callbacks)\n        output = await chain.ainvoke(inputs_, config=runnable_config)\n    return output\nasync def _arun_llm_or_chain(\n    example: Example,\n    config: RunnableConfig,\n    *,\n    llm_or_chain_factory: MCF,\n    input_mapper: Optional[Callable[[Dict], Any]] = None,\n) -> Union[dict, str, LLMResult, ChatResult]:\n    \"\"\"Asynchronously run the Chain or language model.\n    Args:\n        example: The example to run.\n        llm_or_chain_factory: The Chain or language model constructor to run.\n        tags: Optional tags to add to the run.\n        callbacks: Optional callbacks to use during the run.\n        input_mapper: Optional function to map the input to the expected format.\n    Returns:\n        A list of outputs.\n    \"\"\"\n    chain_or_llm = (\n        \"LLM\" if isinstance(llm_or_chain_factory, BaseLanguageModel) else \"Chain\"\n    )\n    result = None\n    try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-16", "text": ")\n    result = None\n    try:\n        if isinstance(llm_or_chain_factory, BaseLanguageModel):\n            output: Any = await _arun_llm(\n                llm_or_chain_factory,\n                example.inputs,\n                tags=config[\"tags\"],\n                callbacks=config[\"callbacks\"],\n                input_mapper=input_mapper,\n            )\n        else:\n            chain = llm_or_chain_factory()\n            output = await _arun_chain(\n                chain,\n                example.inputs,\n                tags=config[\"tags\"],\n                callbacks=config[\"callbacks\"],\n                input_mapper=input_mapper,\n            )\n        result = output\n    except Exception as e:\n        logger.warning(\n            f\"{chain_or_llm} failed for example {example.id} \"\n            f\"with inputs {example.inputs}\"\n            f\"\\n{repr(e)}\"\n        )\n        result = {\"Error\": repr(e)}\n    return result\n## Sync Utilities\ndef _run_llm(\n    llm: BaseLanguageModel,\n    inputs: Dict[str, Any],\n    callbacks: Callbacks,\n    *,\n    tags: Optional[List[str]] = None,\n    input_mapper: Optional[Callable[[Dict], Any]] = None,\n) -> Union[str, BaseMessage]:\n    \"\"\"\n    Run the language model on the example.\n    Args:\n        llm: The language model to run.\n        inputs: The input dictionary.\n        callbacks: The callbacks to use during the run.\n        tags: Optional tags to add to the run.\n        input_mapper: function to map to the inputs dictionary from an Example\n    Returns:\n        The LLMResult or ChatResult.\n    Raises:\n        ValueError: If the LLM type is unsupported.\n        InputFormatError: If the input format is invalid.\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-17", "text": "InputFormatError: If the input format is invalid.\n    \"\"\"\n    if input_mapper is not None:\n        prompt_or_messages = input_mapper(inputs)\n        if isinstance(prompt_or_messages, str):\n            llm_output: Union[str, BaseMessage] = llm.predict(\n                prompt_or_messages, callbacks=callbacks, tags=tags\n            )\n        elif isinstance(prompt_or_messages, list) and all(\n            isinstance(msg, BaseMessage) for msg in prompt_or_messages\n        ):\n            llm_output = llm.predict_messages(\n                prompt_or_messages, callbacks=callbacks, tags=tags\n            )\n        else:\n            raise InputFormatError(\n                \"Input mapper returned invalid format: \"\n                f\" {prompt_or_messages}\"\n                \"\\nExpected a single string or list of chat messages.\"\n            )\n    else:\n        try:\n            llm_prompts = _get_prompt(inputs)\n            llm_output = llm.predict(llm_prompts, callbacks=callbacks, tags=tags)\n        except InputFormatError:\n            llm_messages = _get_messages(inputs)\n            llm_output = llm.predict_messages(llm_messages, callbacks=callbacks)\n    return llm_output\ndef _run_chain(\n    chain: Union[Chain, Runnable],\n    inputs: Dict[str, Any],\n    callbacks: Callbacks,\n    *,\n    tags: Optional[List[str]] = None,\n    input_mapper: Optional[Callable[[Dict], Any]] = None,\n) -> Union[Dict, str]:\n    \"\"\"Run a chain on inputs.\"\"\"\n    inputs_ = inputs if input_mapper is None else input_mapper(inputs)\n    if (\n        isinstance(chain, Chain)\n        and isinstance(inputs_, dict)\n        and len(inputs_) == 1\n        and chain.input_keys\n    ):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-18", "text": "and len(inputs_) == 1\n        and chain.input_keys\n    ):\n        val = next(iter(inputs_.values()))\n        output = chain(val, callbacks=callbacks, tags=tags)\n    else:\n        runnable_config = RunnableConfig(tags=tags or [], callbacks=callbacks)\n        output = chain.invoke(inputs_, config=runnable_config)\n    return output\ndef _run_llm_or_chain(\n    example: Example,\n    config: RunnableConfig,\n    *,\n    llm_or_chain_factory: MCF,\n    input_mapper: Optional[Callable[[Dict], Any]] = None,\n) -> Union[dict, str, LLMResult, ChatResult]:\n    \"\"\"\n    Run the Chain or language model synchronously.\n    Args:\n        example: The example to run.\n        llm_or_chain_factory: The Chain or language model constructor to run.\n        tags: Optional tags to add to the run.\n        callbacks: Optional callbacks to use during the run.\n    Returns:\n        Union[List[dict], List[str], List[LLMResult], List[ChatResult]]:\n          The outputs of the model or chain.\n    \"\"\"\n    chain_or_llm = (\n        \"LLM\" if isinstance(llm_or_chain_factory, BaseLanguageModel) else \"Chain\"\n    )\n    result = None\n    try:\n        if isinstance(llm_or_chain_factory, BaseLanguageModel):\n            output: Any = _run_llm(\n                llm_or_chain_factory,\n                example.inputs,\n                config[\"callbacks\"],\n                tags=config[\"tags\"],\n                input_mapper=input_mapper,\n            )\n        else:\n            chain = llm_or_chain_factory()\n            output = _run_chain(\n                chain,\n                example.inputs,\n                config[\"callbacks\"],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-19", "text": "chain,\n                example.inputs,\n                config[\"callbacks\"],\n                tags=config[\"tags\"],\n                input_mapper=input_mapper,\n            )\n        result = output\n    except Exception as e:\n        error_type = type(e).__name__\n        logger.warning(\n            f\"{chain_or_llm} failed for example {example.id} \"\n            f\"with inputs {example.inputs}\"\n            f\"\\nError Type: {error_type}, Message: {e}\"\n        )\n        result = {\"Error\": repr(e)}\n    return result\n## Public API\ndef _prepare_eval_run(\n    client: Client,\n    dataset_name: str,\n    llm_or_chain_factory: MODEL_OR_CHAIN_FACTORY,\n    project_name: str,\n    project_metadata: Optional[Dict[str, Any]] = None,\n) -> Tuple[MCF, str, Dataset, List[Example]]:\n    wrapped_model = _wrap_in_chain_factory(llm_or_chain_factory, dataset_name)\n    dataset = client.read_dataset(dataset_name=dataset_name)\n    try:\n        project = client.create_project(\n            project_name,\n            reference_dataset_id=dataset.id,\n            project_extra={\"metadata\": project_metadata} if project_metadata else {},\n        )\n    except (HTTPError, ValueError, LangSmithError) as e:\n        if \"already exists \" not in str(e):\n            raise e\n        uid = uuid.uuid4()\n        example_msg = f\"\"\"\nrun_on_dataset(\n    ...\n    project_name=\"{project_name} - {uid}\", # Update since {project_name} already exists\n)\n\"\"\"\n        raise ValueError(\n            f\"Test project {project_name} already exists. Please use a different name:\"\n            f\"\\n\\n{example_msg}\"\n        )\n    print(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-20", "text": "f\"\\n\\n{example_msg}\"\n        )\n    print(\n        f\"View the evaluation results for project '{project_name}'\"\n        f\" at:\\n{project.url}?eval=true\\n\\n\"\n        f\"View all tests for Dataset {dataset_name} at:\\n{dataset.url}\",\n        flush=True,\n    )\n    examples = list(client.list_examples(dataset_id=dataset.id))\n    if not examples:\n        raise ValueError(f\"Dataset {dataset_name} has no example rows.\")\n    return wrapped_model, project_name, dataset, examples\ndef _prepare_run_on_dataset(\n    client: Client,\n    dataset_name: str,\n    llm_or_chain_factory: MODEL_OR_CHAIN_FACTORY,\n    project_name: Optional[str],\n    evaluation: Optional[smith_eval.RunEvalConfig] = None,\n    tags: Optional[List[str]] = None,\n    input_mapper: Optional[Callable[[Dict], Any]] = None,\n    concurrency_level: int = 5,\n    project_metadata: Optional[Dict[str, Any]] = None,\n) -> Tuple[MCF, str, List[Example], List[RunnableConfig]]:\n    project_name = project_name or name_generation.random_name()\n    wrapped_model, project_name, dataset, examples = _prepare_eval_run(\n        client,\n        dataset_name,\n        llm_or_chain_factory,\n        project_name,\n        project_metadata=project_metadata,\n    )\n    wrapped_model = _wrap_in_chain_factory(llm_or_chain_factory)\n    run_evaluators = _setup_evaluation(\n        wrapped_model, examples, evaluation, dataset.data_type or DataType.kv\n    )\n    _validate_example_inputs(examples[0], wrapped_model, input_mapper)\n    progress_bar = progress.ProgressBarCallback(len(examples))\n    configs = [\n        RunnableConfig(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-21", "text": "configs = [\n        RunnableConfig(\n            callbacks=[\n                LangChainTracer(\n                    project_name=project_name,\n                    client=client,\n                    use_threading=False,\n                    example_id=example.id,\n                ),\n                EvaluatorCallbackHandler(\n                    evaluators=run_evaluators or [],\n                    client=client,\n                    example_id=example.id,\n                ),\n                progress_bar,\n            ],\n            tags=tags or [],\n            max_concurrency=concurrency_level,\n        )\n        for example in examples\n    ]\n    return wrapped_model, project_name, examples, configs\ndef _collect_test_results(\n    examples: List[Example],\n    batch_results: List[Union[dict, str, LLMResult, ChatResult]],\n    configs: List[RunnableConfig],\n    project_name: str,\n) -> TestResult:\n    wait_for_all_evaluators()\n    all_eval_results = {}\n    for c in configs:\n        for callback in cast(list, c[\"callbacks\"]):\n            if isinstance(callback, EvaluatorCallbackHandler):\n                eval_results = callback.logged_eval_results\n                all_eval_results.update(\n                    {example_id: v for (_, example_id), v in eval_results.items()}\n                )\n            elif isinstance(callback, LangChainTracer):\n                run = callback.latest_run\n                execution_time = (\n                    (run.end_time - run.start_time).total_seconds()\n                    if run and run.end_time\n                    else None\n                )\n    results = {}\n    for example, output in zip(examples, batch_results):\n        feedback = all_eval_results.get(str(example.id), [])\n        results[str(example.id)] = {\n            \"output\": output,\n            \"input\": example.inputs,\n            \"feedback\": feedback,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-22", "text": "\"input\": example.inputs,\n            \"feedback\": feedback,\n            \"execution_time\": execution_time,\n        }\n        if example.outputs:\n            results[str(example.id)][\"reference\"] = example.outputs\n    return TestResult(\n        project_name=project_name,\n        results=results,\n    )\n_INPUT_MAPPER_DEP_WARNING = (\n    \"The input_mapper argument is deprecated and \"\n    \"will be removed in a future release. Please add a \"\n    \" RunnableLambda to your chain to map inputs to the expected format\"\n    \" instead. Example:\\n\"\n    \"def construct_chain():\\n\"\n    \"    my_chain = ...\\n\"\n    \"    input_mapper = {'other_key': 'MyOtherInput', 'my_input_key': x}\\n\"\n    \"    return input_mapper | my_chain\\n\"\n    \"run_on_dataset(..., llm_or_chain_factory=construct_chain)\\n\"\n    \"(See https://api.python.langchain.com/en/latest/schema/\"\n    \"langchain.schema.runnable.base.RunnableLambda.html)\"\n)\n[docs]async def arun_on_dataset(\n    client: Optional[Client],\n    dataset_name: str,\n    llm_or_chain_factory: MODEL_OR_CHAIN_FACTORY,\n    *,\n    evaluation: Optional[smith_eval.RunEvalConfig] = None,\n    concurrency_level: int = 5,\n    project_name: Optional[str] = None,\n    project_metadata: Optional[Dict[str, Any]] = None,\n    verbose: bool = False,\n    tags: Optional[List[str]] = None,\n    **kwargs: Any,\n) -> Dict[str, Any]:\n    input_mapper = kwargs.pop(\"input_mapper\", None)\n    if input_mapper:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-23", "text": "input_mapper = kwargs.pop(\"input_mapper\", None)\n    if input_mapper:\n        warn_deprecated(\"0.0.305\", message=_INPUT_MAPPER_DEP_WARNING, pending=True)\n    if kwargs:\n        warn_deprecated(\n            \"0.0.305\",\n            message=\"The following arguments are deprecated and \"\n            \"will be removed in a future release: \"\n            f\"{kwargs.keys()}.\",\n            removal=\"0.0.305\",\n        )\n    client = client or Client()\n    wrapped_model, project_name, examples, configs = _prepare_run_on_dataset(\n        client,\n        dataset_name,\n        llm_or_chain_factory,\n        project_name,\n        evaluation,\n        tags,\n        input_mapper,\n        concurrency_level,\n        project_metadata=project_metadata,\n    )\n    batch_results = await runnable_utils.gather_with_concurrency(\n        configs[0].get(\"max_concurrency\"),\n        *map(\n            functools.partial(\n                _arun_llm_or_chain,\n                llm_or_chain_factory=wrapped_model,\n                input_mapper=input_mapper,\n            ),\n            examples,\n            configs,\n        ),\n    )\n    results = _collect_test_results(examples, batch_results, configs, project_name)\n    if verbose:\n        try:\n            agg_feedback = results.get_aggregate_feedback()\n            print(\"\\n Eval quantiles:\")\n            print(agg_feedback)\n        except Exception as e:\n            logger.debug(f\"Failed to print aggregate feedback: {repr(e)}\")\n    return results\n[docs]def run_on_dataset(\n    client: Optional[Client],\n    dataset_name: str,\n    llm_or_chain_factory: MODEL_OR_CHAIN_FACTORY,\n    *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-24", "text": "llm_or_chain_factory: MODEL_OR_CHAIN_FACTORY,\n    *,\n    evaluation: Optional[smith_eval.RunEvalConfig] = None,\n    concurrency_level: int = 5,\n    project_name: Optional[str] = None,\n    project_metadata: Optional[Dict[str, Any]] = None,\n    verbose: bool = False,\n    tags: Optional[List[str]] = None,\n    **kwargs: Any,\n) -> Dict[str, Any]:\n    input_mapper = kwargs.pop(\"input_mapper\", None)\n    if input_mapper:\n        warn_deprecated(\"0.0.305\", message=_INPUT_MAPPER_DEP_WARNING, pending=True)\n    if kwargs:\n        warn_deprecated(\n            \"0.0.305\",\n            message=\"The following arguments are deprecated and \"\n            \"will be removed in a future release: \"\n            f\"{kwargs.keys()}.\",\n            removal=\"0.0.305\",\n        )\n    client = client or Client()\n    wrapped_model, project_name, examples, configs = _prepare_run_on_dataset(\n        client,\n        dataset_name,\n        llm_or_chain_factory,\n        project_name,\n        evaluation,\n        tags,\n        input_mapper,\n        concurrency_level,\n        project_metadata=project_metadata,\n    )\n    if concurrency_level == 0:\n        batch_results = [\n            _run_llm_or_chain(\n                example,\n                config,\n                llm_or_chain_factory=wrapped_model,\n                input_mapper=input_mapper,\n            )\n            for example, config in zip(examples, configs)\n        ]\n    else:\n        with runnable_config.get_executor_for_config(configs[0]) as executor:\n            batch_results = list(\n                executor.map(\n                    functools.partial(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-25", "text": "batch_results = list(\n                executor.map(\n                    functools.partial(\n                        _run_llm_or_chain,\n                        llm_or_chain_factory=wrapped_model,\n                        input_mapper=input_mapper,\n                    ),\n                    examples,\n                    configs,\n                )\n            )\n    results = _collect_test_results(examples, batch_results, configs, project_name)\n    if verbose:\n        try:\n            agg_feedback = results.get_aggregate_feedback()\n            print(\"\\n Eval quantiles:\")\n            print(agg_feedback)\n        except Exception as e:\n            logger.debug(f\"Failed to print aggregate feedback: {repr(e)}\")\n    return results\n_RUN_ON_DATASET_DOCSTRING = \"\"\"\nRun the Chain or language model on a dataset and store traces\nto the specified project name.\nArgs:\n    dataset_name: Name of the dataset to run the chain on.\n    llm_or_chain_factory: Language model or Chain constructor to run\n        over the dataset. The Chain constructor is used to permit\n        independent calls on each example without carrying over state.\n    evaluation: Configuration for evaluators to run on the\n        results of the chain\n    concurrency_level: The number of async tasks to run concurrently.\n    project_name: Name of the project to store the traces in.\n        Defaults to {dataset_name}-{chain class name}-{datetime}.\n    project_metadata: Optional metadata to add to the project.\n        Useful for storing information the test variant.\n        (prompt version, model version, etc.)\n    client: LangSmith client to use to access the dataset and to\n        log feedback and run traces.\n    verbose: Whether to print progress.\n    tags: Tags to add to each run in the project.\nReturns:\n    A dictionary containing the run's project name and the resulting model outputs.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-26", "text": "Returns:\n    A dictionary containing the run's project name and the resulting model outputs.\nFor the (usually faster) async version of this function, see :func:`arun_on_dataset`.\nExamples\n--------\n.. code-block:: python\n    from langsmith import Client\n    from langchain.chat_models import ChatOpenAI\n    from langchain.chains import LLMChain\n    from langchain.smith import smith_eval.RunEvalConfig, run_on_dataset\n    # Chains may have memory. Passing in a constructor function lets the\n    # evaluation framework avoid cross-contamination between runs.\n    def construct_chain():\n        llm = ChatOpenAI(temperature=0)\n        chain = LLMChain.from_string(\n            llm,\n            \"What's the answer to {your_input_key}\"\n        )\n        return chain\n    # Load off-the-shelf evaluators via config or the EvaluatorType (string or enum)\n    evaluation_config = smith_eval.RunEvalConfig(\n        evaluators=[\n            \"qa\",  # \"Correctness\" against a reference answer\n            \"embedding_distance\",\n            smith_eval.RunEvalConfig.Criteria(\"helpfulness\"),\n            smith_eval.RunEvalConfig.Criteria({\n                \"fifth-grader-score\": \"Do you have to be smarter than a fifth grader to answer this question?\"\n            }),\n        ]\n    )\n    client = Client()\n    run_on_dataset(\n        client,\n        \"<my_dataset_name>\",\n        construct_chain,\n        evaluation=evaluation_config,\n    )\nYou can also create custom evaluators by subclassing the\n:class:`StringEvaluator <langchain.evaluation.schema.StringEvaluator>`\nor LangSmith's `RunEvaluator` classes.\n.. code-block:: python\n    from typing import Optional\n    from langchain.evaluation import StringEvaluator\n    class MyStringEvaluator(StringEvaluator):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "94b373b81797-27", "text": "from langchain.evaluation import StringEvaluator\n    class MyStringEvaluator(StringEvaluator):\n        @property\n        def requires_input(self) -> bool:\n            return False\n        @property\n        def requires_reference(self) -> bool:\n            return True\n        @property\n        def evaluation_name(self) -> str:\n            return \"exact_match\"\n        def _evaluate_strings(self, prediction, reference=None, input=None, **kwargs) -> dict:\n            return {\"score\": prediction == reference}\n    evaluation_config = smith_eval.RunEvalConfig(\n        custom_evaluators = [MyStringEvaluator()],\n    )\n    run_on_dataset(\n        client,\n        \"<my_dataset_name>\",\n        construct_chain,\n        evaluation=evaluation_config,\n    )\n\"\"\"  # noqa: E501\nrun_on_dataset.__doc__ = _RUN_ON_DATASET_DOCSTRING\narun_on_dataset.__doc__ = _RUN_ON_DATASET_DOCSTRING.replace(\n    \"run_on_dataset(\", \"await arun_on_dataset(\"\n)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html"}
{"id": "7f1882058aec-0", "text": "Source code for langchain.prompts.chat\n\"\"\"Chat prompt template.\"\"\"\nfrom __future__ import annotations\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    List,\n    Literal,\n    Sequence,\n    Set,\n    Tuple,\n    Type,\n    TypeVar,\n    Union,\n    overload,\n)\nfrom langchain._api import deprecated\nfrom langchain.load.serializable import Serializable\nfrom langchain.prompts.base import StringPromptTemplate\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema import (\n    BasePromptTemplate,\n    PromptValue,\n)\nfrom langchain.schema.messages import (\n    AIMessage,\n    AnyMessage,\n    BaseMessage,\n    ChatMessage,\n    HumanMessage,\n    SystemMessage,\n    get_buffer_string,\n)\n[docs]class BaseMessagePromptTemplate(Serializable, ABC):\n    \"\"\"Base class for message prompt templates.\"\"\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether or not the class is serializable.\"\"\"\n        return True\n[docs]    @abstractmethod\n    def format_messages(self, **kwargs: Any) -> List[BaseMessage]:\n        \"\"\"Format messages from kwargs. Should return a list of BaseMessages.\n        Args:\n            **kwargs: Keyword arguments to use for formatting.\n        Returns:\n            List of BaseMessages.\n        \"\"\"\n    @property\n    @abstractmethod\n    def input_variables(self) -> List[str]:\n        \"\"\"Input variables for this prompt template.\n        Returns:\n            List of input variables.\n        \"\"\"\n    def __add__(self, other: Any) -> ChatPromptTemplate:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-1", "text": "\"\"\"\n    def __add__(self, other: Any) -> ChatPromptTemplate:\n        \"\"\"Combine two prompt templates.\n        Args:\n            other: Another prompt template.\n        Returns:\n            Combined prompt template.\n        \"\"\"\n        prompt = ChatPromptTemplate(messages=[self])\n        return prompt + other\n[docs]class MessagesPlaceholder(BaseMessagePromptTemplate):\n    \"\"\"Prompt template that assumes variable is already list of messages.\"\"\"\n    variable_name: str\n    \"\"\"Name of variable to use as messages.\"\"\"\n    def __init__(self, variable_name: str, **kwargs: Any):\n        return super().__init__(variable_name=variable_name, **kwargs)\n[docs]    def format_messages(self, **kwargs: Any) -> List[BaseMessage]:\n        \"\"\"Format messages from kwargs.\n        Args:\n            **kwargs: Keyword arguments to use for formatting.\n        Returns:\n            List of BaseMessage.\n        \"\"\"\n        value = kwargs[self.variable_name]\n        if not isinstance(value, list):\n            raise ValueError(\n                f\"variable {self.variable_name} should be a list of base messages, \"\n                f\"got {value}\"\n            )\n        for v in value:\n            if not isinstance(v, BaseMessage):\n                raise ValueError(\n                    f\"variable {self.variable_name} should be a list of base messages,\"\n                    f\" got {value}\"\n                )\n        return value\n    @property\n    def input_variables(self) -> List[str]:\n        \"\"\"Input variables for this prompt template.\n        Returns:\n            List of input variable names.\n        \"\"\"\n        return [self.variable_name]\nMessagePromptTemplateT = TypeVar(\n    \"MessagePromptTemplateT\", bound=\"BaseStringMessagePromptTemplate\"\n)\n\"\"\"Type variable for message prompt templates.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-2", "text": ")\n\"\"\"Type variable for message prompt templates.\"\"\"\n[docs]class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):\n    \"\"\"Base class for message prompt templates that use a string prompt template.\"\"\"\n    prompt: StringPromptTemplate\n    \"\"\"String prompt template.\"\"\"\n    additional_kwargs: dict = Field(default_factory=dict)\n    \"\"\"Additional keyword arguments to pass to the prompt template.\"\"\"\n[docs]    @classmethod\n    def from_template(\n        cls: Type[MessagePromptTemplateT],\n        template: str,\n        template_format: str = \"f-string\",\n        **kwargs: Any,\n    ) -> MessagePromptTemplateT:\n        \"\"\"Create a class from a string template.\n        Args:\n            template: a template.\n            template_format: format of the template.\n            **kwargs: keyword arguments to pass to the constructor.\n        Returns:\n            A new instance of this class.\n        \"\"\"\n        prompt = PromptTemplate.from_template(template, template_format=template_format)\n        return cls(prompt=prompt, **kwargs)\n[docs]    @classmethod\n    def from_template_file(\n        cls: Type[MessagePromptTemplateT],\n        template_file: Union[str, Path],\n        input_variables: List[str],\n        **kwargs: Any,\n    ) -> MessagePromptTemplateT:\n        \"\"\"Create a class from a template file.\n        Args:\n            template_file: path to a template file. String or Path.\n            input_variables: list of input variables.\n            **kwargs: keyword arguments to pass to the constructor.\n        Returns:\n            A new instance of this class.\n        \"\"\"\n        prompt = PromptTemplate.from_file(template_file, input_variables)\n        return cls(prompt=prompt, **kwargs)\n[docs]    @abstractmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-3", "text": "return cls(prompt=prompt, **kwargs)\n[docs]    @abstractmethod\n    def format(self, **kwargs: Any) -> BaseMessage:\n        \"\"\"Format the prompt template.\n        Args:\n            **kwargs: Keyword arguments to use for formatting.\n        Returns:\n            Formatted message.\n        \"\"\"\n[docs]    def format_messages(self, **kwargs: Any) -> List[BaseMessage]:\n        \"\"\"Format messages from kwargs.\n        Args:\n            **kwargs: Keyword arguments to use for formatting.\n        Returns:\n            List of BaseMessages.\n        \"\"\"\n        return [self.format(**kwargs)]\n    @property\n    def input_variables(self) -> List[str]:\n        \"\"\"\n        Input variables for this prompt template.\n        Returns:\n            List of input variable names.\n        \"\"\"\n        return self.prompt.input_variables\n[docs]class ChatMessagePromptTemplate(BaseStringMessagePromptTemplate):\n    \"\"\"Chat message prompt template.\"\"\"\n    role: str\n    \"\"\"Role of the message.\"\"\"\n[docs]    def format(self, **kwargs: Any) -> BaseMessage:\n        \"\"\"Format the prompt template.\n        Args:\n            **kwargs: Keyword arguments to use for formatting.\n        Returns:\n            Formatted message.\n        \"\"\"\n        text = self.prompt.format(**kwargs)\n        return ChatMessage(\n            content=text, role=self.role, additional_kwargs=self.additional_kwargs\n        )\n[docs]class HumanMessagePromptTemplate(BaseStringMessagePromptTemplate):\n    \"\"\"Human message prompt template. This is a message sent from the user.\"\"\"\n[docs]    def format(self, **kwargs: Any) -> BaseMessage:\n        \"\"\"Format the prompt template.\n        Args:\n            **kwargs: Keyword arguments to use for formatting.\n        Returns:\n            Formatted message.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-4", "text": "Returns:\n            Formatted message.\n        \"\"\"\n        text = self.prompt.format(**kwargs)\n        return HumanMessage(content=text, additional_kwargs=self.additional_kwargs)\n[docs]class AIMessagePromptTemplate(BaseStringMessagePromptTemplate):\n    \"\"\"AI message prompt template. This is a message sent from the AI.\"\"\"\n[docs]    def format(self, **kwargs: Any) -> BaseMessage:\n        \"\"\"Format the prompt template.\n        Args:\n            **kwargs: Keyword arguments to use for formatting.\n        Returns:\n            Formatted message.\n        \"\"\"\n        text = self.prompt.format(**kwargs)\n        return AIMessage(content=text, additional_kwargs=self.additional_kwargs)\n[docs]class SystemMessagePromptTemplate(BaseStringMessagePromptTemplate):\n    \"\"\"System message prompt template.\n    This is a message that is not sent to the user.\n    \"\"\"\n[docs]    def format(self, **kwargs: Any) -> BaseMessage:\n        \"\"\"Format the prompt template.\n        Args:\n            **kwargs: Keyword arguments to use for formatting.\n        Returns:\n            Formatted message.\n        \"\"\"\n        text = self.prompt.format(**kwargs)\n        return SystemMessage(content=text, additional_kwargs=self.additional_kwargs)\n[docs]class ChatPromptValue(PromptValue):\n    \"\"\"Chat prompt value.\n    A type of a prompt value that is built from messages.\n    \"\"\"\n    messages: Sequence[BaseMessage]\n    \"\"\"List of messages.\"\"\"\n[docs]    def to_string(self) -> str:\n        \"\"\"Return prompt as string.\"\"\"\n        return get_buffer_string(self.messages)\n[docs]    def to_messages(self) -> List[BaseMessage]:\n        \"\"\"Return prompt as a list of messages.\"\"\"\n        return list(self.messages)\n[docs]class ChatPromptValueConcrete(ChatPromptValue):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-5", "text": "return list(self.messages)\n[docs]class ChatPromptValueConcrete(ChatPromptValue):\n    \"\"\"Chat prompt value which explicitly lists out the message types it accepts.\n    For use in external schemas.\"\"\"\n    messages: Sequence[AnyMessage]\n    type: Literal[\"ChatPromptValueConcrete\"] = \"ChatPromptValueConcrete\"\n[docs]class BaseChatPromptTemplate(BasePromptTemplate, ABC):\n    \"\"\"Base class for chat prompt templates.\"\"\"\n    @property\n    def lc_attributes(self) -> Dict:\n        \"\"\"\n        Return a list of attribute names that should be included in the\n        serialized kwargs. These attributes must be accepted by the\n        constructor.\n        \"\"\"\n        return {\"input_variables\": self.input_variables}\n[docs]    def format(self, **kwargs: Any) -> str:\n        \"\"\"Format the chat template into a string.\n        Args:\n            **kwargs: keyword arguments to use for filling in template variables\n                      in all the template messages in this chat template.\n        Returns:\n            formatted string\n        \"\"\"\n        return self.format_prompt(**kwargs).to_string()\n[docs]    def format_prompt(self, **kwargs: Any) -> PromptValue:\n        \"\"\"\n        Format prompt. Should return a PromptValue.\n        Args:\n            **kwargs: Keyword arguments to use for formatting.\n        Returns:\n            PromptValue.\n        \"\"\"\n        messages = self.format_messages(**kwargs)\n        return ChatPromptValue(messages=messages)\n[docs]    @abstractmethod\n    def format_messages(self, **kwargs: Any) -> List[BaseMessage]:\n        \"\"\"Format kwargs into a list of messages.\"\"\"\nMessageLike = Union[BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate]\nMessageLikeRepresentation = Union[\n    MessageLike,\n    Tuple[str, str],\n    Tuple[Type, str],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-6", "text": "MessageLike,\n    Tuple[str, str],\n    Tuple[Type, str],\n    str,\n]\n[docs]class ChatPromptTemplate(BaseChatPromptTemplate):\n    \"\"\"A prompt template for chat models.\n    Use to create flexible templated prompts for chat models.\n    Examples:\n        .. code-block:: python\n            from langchain.prompts import ChatPromptTemplate\n            template = ChatPromptTemplate.from_messages([\n                (\"system\", \"You are a helpful AI bot. Your name is {name}.\"),\n                (\"human\", \"Hello, how are you doing?\"),\n                (\"ai\", \"I'm doing well, thanks!\"),\n                (\"human\", \"{user_input}\"),\n            ])\n            messages = template.format_messages(\n                name=\"Bob\",\n                user_input=\"What is your name?\"\n            )\n    \"\"\"\n    input_variables: List[str]\n    \"\"\"List of input variables in template messages. Used for validation.\"\"\"\n    messages: List[MessageLike]\n    \"\"\"List of messages consisting of either message prompt templates or messages.\"\"\"\n    validate_template: bool = False\n    \"\"\"Whether or not to try validating the template.\"\"\"\n    def __add__(self, other: Any) -> ChatPromptTemplate:\n        \"\"\"Combine two prompt templates.\n        Args:\n            other: Another prompt template.\n        Returns:\n            Combined prompt template.\n        \"\"\"\n        # Allow for easy combining\n        if isinstance(other, ChatPromptTemplate):\n            return ChatPromptTemplate(messages=self.messages + other.messages)\n        elif isinstance(\n            other, (BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate)\n        ):\n            return ChatPromptTemplate(messages=self.messages + [other])\n        elif isinstance(other, (list, tuple)):\n            _other = ChatPromptTemplate.from_messages(other)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-7", "text": "_other = ChatPromptTemplate.from_messages(other)\n            return ChatPromptTemplate(messages=self.messages + _other.messages)\n        elif isinstance(other, str):\n            prompt = HumanMessagePromptTemplate.from_template(other)\n            return ChatPromptTemplate(messages=self.messages + [prompt])\n        else:\n            raise NotImplementedError(f\"Unsupported operand type for +: {type(other)}\")\n    @root_validator(pre=True)\n    def validate_input_variables(cls, values: dict) -> dict:\n        \"\"\"Validate input variables.\n        If input_variables is not set, it will be set to the union of\n        all input variables in the messages.\n        Args:\n            values: values to validate.\n        Returns:\n            Validated values.\n        \"\"\"\n        messages = values[\"messages\"]\n        input_vars = set()\n        input_types: Dict[str, Any] = values.get(\"input_types\", {})\n        for message in messages:\n            if isinstance(message, (BaseMessagePromptTemplate, BaseChatPromptTemplate)):\n                input_vars.update(message.input_variables)\n            if isinstance(message, MessagesPlaceholder):\n                if message.variable_name not in input_types:\n                    input_types[message.variable_name] = List[AnyMessage]\n        if \"partial_variables\" in values:\n            input_vars = input_vars - set(values[\"partial_variables\"])\n        if \"input_variables\" in values and values.get(\"validate_template\"):\n            if input_vars != set(values[\"input_variables\"]):\n                raise ValueError(\n                    \"Got mismatched input_variables. \"\n                    f\"Expected: {input_vars}. \"\n                    f\"Got: {values['input_variables']}\"\n                )\n        else:\n            values[\"input_variables\"] = sorted(input_vars)\n        values[\"input_types\"] = input_types\n        return values\n[docs]    @classmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-8", "text": "return values\n[docs]    @classmethod\n    def from_template(cls, template: str, **kwargs: Any) -> ChatPromptTemplate:\n        \"\"\"Create a chat prompt template from a template string.\n        Creates a chat template consisting of a single message assumed to be from\n        the human.\n        Args:\n            template: template string\n            **kwargs: keyword arguments to pass to the constructor.\n        Returns:\n            A new instance of this class.\n        \"\"\"\n        prompt_template = PromptTemplate.from_template(template, **kwargs)\n        message = HumanMessagePromptTemplate(prompt=prompt_template)\n        return cls.from_messages([message])\n[docs]    @classmethod\n    @deprecated(\"0.0.260\", alternative=\"from_messages classmethod\", pending=True)\n    def from_role_strings(\n        cls, string_messages: List[Tuple[str, str]]\n    ) -> ChatPromptTemplate:\n        \"\"\"Create a chat prompt template from a list of (role, template) tuples.\n        Args:\n            string_messages: list of (role, template) tuples.\n        Returns:\n            a chat prompt template\n        \"\"\"\n        return cls(\n            messages=[\n                ChatMessagePromptTemplate.from_template(template, role=role)\n                for role, template in string_messages\n            ]\n        )\n[docs]    @classmethod\n    @deprecated(\"0.0.260\", alternative=\"from_messages classmethod\", pending=True)\n    def from_strings(\n        cls, string_messages: List[Tuple[Type[BaseMessagePromptTemplate], str]]\n    ) -> ChatPromptTemplate:\n        \"\"\"Create a chat prompt template from a list of (role class, template) tuples.\n        Args:\n            string_messages: list of (role class, template) tuples.\n        Returns:\n            a chat prompt template\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-9", "text": "Returns:\n            a chat prompt template\n        \"\"\"\n        return cls.from_messages(string_messages)\n[docs]    @classmethod\n    def from_messages(\n        cls,\n        messages: Sequence[MessageLikeRepresentation],\n    ) -> ChatPromptTemplate:\n        \"\"\"Create a chat prompt template from a variety of message formats.\n        Examples:\n            Instantiation from a list of message templates:\n            .. code-block:: python\n                template = ChatPromptTemplate.from_messages([\n                    (\"human\", \"Hello, how are you?\"),\n                    (\"ai\", \"I'm doing well, thanks!\"),\n                    (\"human\", \"That's good to hear.\"),\n                ])\n            Instantiation from mixed message formats:\n            .. code-block:: python\n                template = ChatPromptTemplate.from_messages([\n                    SystemMessage(content=\"hello\"),\n                    (\"human\", \"Hello, how are you?\"),\n                ])\n        Args:\n            messages: sequence of message representations.\n                  A message can be represented using the following formats:\n                  (1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of\n                  (message type, template); e.g., (\"human\", \"{user_input}\"),\n                  (4) 2-tuple of (message class, template), (4) a string which is\n                  shorthand for (\"human\", template); e.g., \"{user_input}\"\n        Returns:\n            a chat prompt template\n        \"\"\"\n        _messages = [_convert_to_message(message) for message in messages]\n        # Automatically infer input variables from messages\n        input_vars: Set[str] = set()\n        for _message in _messages:\n            if isinstance(\n                _message, (BaseChatPromptTemplate, BaseMessagePromptTemplate)\n            ):\n                input_vars.update(_message.input_variables)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-10", "text": "):\n                input_vars.update(_message.input_variables)\n        return cls(input_variables=sorted(input_vars), messages=_messages)\n[docs]    def format(self, **kwargs: Any) -> str:\n        \"\"\"Format the chat template into a string.\n        Args:\n            **kwargs: keyword arguments to use for filling in template variables\n                      in all the template messages in this chat template.\n        Returns:\n            formatted string\n        \"\"\"\n        return self.format_prompt(**kwargs).to_string()\n[docs]    def format_messages(self, **kwargs: Any) -> List[BaseMessage]:\n        \"\"\"Format the chat template into a list of finalized messages.\n        Args:\n            **kwargs: keyword arguments to use for filling in template variables\n                      in all the template messages in this chat template.\n        Returns:\n            list of formatted messages\n        \"\"\"\n        kwargs = self._merge_partial_and_user_variables(**kwargs)\n        result = []\n        for message_template in self.messages:\n            if isinstance(message_template, BaseMessage):\n                result.extend([message_template])\n            elif isinstance(\n                message_template, (BaseMessagePromptTemplate, BaseChatPromptTemplate)\n            ):\n                rel_params = {\n                    k: v\n                    for k, v in kwargs.items()\n                    if k in message_template.input_variables\n                }\n                message = message_template.format_messages(**rel_params)\n                result.extend(message)\n            else:\n                raise ValueError(f\"Unexpected input: {message_template}\")\n        return result\n[docs]    def partial(self, **kwargs: Union[str, Callable[[], str]]) -> ChatPromptTemplate:\n        \"\"\"Get a new ChatPromptTemplate with some input variables already filled in.\n        Args:\n            **kwargs: keyword arguments to use for filling in template variables. Ought", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-11", "text": "**kwargs: keyword arguments to use for filling in template variables. Ought\n                        to be a subset of the input variables.\n        Returns:\n            A new ChatPromptTemplate.\n        Example:\n            .. code-block:: python\n                from langchain.prompts import ChatPromptTemplate\n                template = ChatPromptTemplate.from_messages(\n                    [\n                        (\"system\", \"You are an AI assistant named {name}.\"),\n                        (\"human\", \"Hi I'm {user}\"),\n                        (\"ai\", \"Hi there, {user}, I'm {name}.\"),\n                        (\"human\", \"{input}\"),\n                    ]\n                )\n                template2 = template.partial(user=\"Lucy\", name=\"R2D2\")\n                template2.format_messages(input=\"hello\")\n        \"\"\"\n        prompt_dict = self.__dict__.copy()\n        prompt_dict[\"input_variables\"] = list(\n            set(self.input_variables).difference(kwargs)\n        )\n        prompt_dict[\"partial_variables\"] = {**self.partial_variables, **kwargs}\n        return type(self)(**prompt_dict)\n[docs]    def append(self, message: MessageLikeRepresentation) -> None:\n        \"\"\"Append message to the end of the chat template.\n        Args:\n            message: representation of a message to append.\n        \"\"\"\n        self.messages.append(_convert_to_message(message))\n[docs]    def extend(self, messages: Sequence[MessageLikeRepresentation]) -> None:\n        \"\"\"Extend the chat template with a sequence of messages.\"\"\"\n        self.messages.extend([_convert_to_message(message) for message in messages])\n    @overload\n    def __getitem__(self, index: int) -> MessageLike:\n        ...\n    @overload\n    def __getitem__(self, index: slice) -> ChatPromptTemplate:\n        ...\n    def __getitem__(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-12", "text": "...\n    def __getitem__(\n        self, index: Union[int, slice]\n    ) -> Union[MessageLike, ChatPromptTemplate]:\n        \"\"\"Use to index into the chat template.\"\"\"\n        if isinstance(index, slice):\n            start, stop, step = index.indices(len(self.messages))\n            messages = self.messages[start:stop:step]\n            return ChatPromptTemplate.from_messages(messages)\n        else:\n            return self.messages[index]\n    def __len__(self) -> int:\n        \"\"\"Get the length of the chat template.\"\"\"\n        return len(self.messages)\n    @property\n    def _prompt_type(self) -> str:\n        \"\"\"Name of prompt type.\"\"\"\n        return \"chat\"\n[docs]    def save(self, file_path: Union[Path, str]) -> None:\n        \"\"\"Save prompt to file.\n        Args:\n            file_path: path to file.\n        \"\"\"\n        raise NotImplementedError()\ndef _create_template_from_message_type(\n    message_type: str, template: str\n) -> BaseMessagePromptTemplate:\n    \"\"\"Create a message prompt template from a message type and template string.\n    Args:\n        message_type: str the type of the message template (e.g., \"human\", \"ai\", etc.)\n        template: str the template string.\n    Returns:\n        a message prompt template of the appropriate type.\n    \"\"\"\n    if message_type in (\"human\", \"user\"):\n        message: BaseMessagePromptTemplate = HumanMessagePromptTemplate.from_template(\n            template\n        )\n    elif message_type in (\"ai\", \"assistant\"):\n        message = AIMessagePromptTemplate.from_template(template)\n    elif message_type == \"system\":\n        message = SystemMessagePromptTemplate.from_template(template)\n    else:\n        raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-13", "text": "else:\n        raise ValueError(\n            f\"Unexpected message type: {message_type}. Use one of 'human',\"\n            f\" 'user', 'ai', 'assistant', or 'system'.\"\n        )\n    return message\ndef _convert_to_message(\n    message: MessageLikeRepresentation,\n) -> Union[BaseMessage, BaseMessagePromptTemplate, BaseChatPromptTemplate]:\n    \"\"\"Instantiate a message from a variety of message formats.\n    The message format can be one of the following:\n    - BaseMessagePromptTemplate\n    - BaseMessage\n    - 2-tuple of (role string, template); e.g., (\"human\", \"{user_input}\")\n    - 2-tuple of (message class, template)\n    - string: shorthand for (\"human\", template); e.g., \"{user_input}\"\n    Args:\n        message: a representation of a message in one of the supported formats\n    Returns:\n        an instance of a message or a message template\n    \"\"\"\n    if isinstance(message, (BaseMessagePromptTemplate, BaseChatPromptTemplate)):\n        _message: Union[\n            BaseMessage, BaseMessagePromptTemplate, BaseChatPromptTemplate\n        ] = message\n    elif isinstance(message, BaseMessage):\n        _message = message\n    elif isinstance(message, str):\n        _message = _create_template_from_message_type(\"human\", message)\n    elif isinstance(message, tuple):\n        if len(message) != 2:\n            raise ValueError(f\"Expected 2-tuple of (role, template), got {message}\")\n        message_type_str, template = message\n        if isinstance(message_type_str, str):\n            _message = _create_template_from_message_type(message_type_str, template)\n        else:\n            _message = message_type_str(prompt=PromptTemplate.from_template(template))\n    else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "7f1882058aec-14", "text": "_message = message_type_str(prompt=PromptTemplate.from_template(template))\n    else:\n        raise NotImplementedError(f\"Unsupported message type: {type(message)}\")\n    return _message", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html"}
{"id": "9b82c62c98d7-0", "text": "Source code for langchain.prompts.few_shot\n\"\"\"Prompt template that contains few shot examples.\"\"\"\nfrom __future__ import annotations\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Literal, Optional, Union\nfrom langchain.prompts.base import (\n    DEFAULT_FORMATTER_MAPPING,\n    StringPromptTemplate,\n    check_valid_template,\n    get_template_variables,\n)\nfrom langchain.prompts.chat import BaseChatPromptTemplate, BaseMessagePromptTemplate\nfrom langchain.prompts.example_selector.base import BaseExampleSelector\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator\nfrom langchain.schema.messages import BaseMessage, get_buffer_string\nclass _FewShotPromptTemplateMixin(BaseModel):\n    \"\"\"Prompt template that contains few shot examples.\"\"\"\n    examples: Optional[List[dict]] = None\n    \"\"\"Examples to format into the prompt.\n    Either this or example_selector should be provided.\"\"\"\n    example_selector: Optional[BaseExampleSelector] = None\n    \"\"\"ExampleSelector to choose the examples to format into the prompt.\n    Either this or examples should be provided.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    @root_validator(pre=True)\n    def check_examples_and_selector(cls, values: Dict) -> Dict:\n        \"\"\"Check that one and only one of examples/example_selector are provided.\"\"\"\n        examples = values.get(\"examples\", None)\n        example_selector = values.get(\"example_selector\", None)\n        if examples and example_selector:\n            raise ValueError(\n                \"Only one of 'examples' and 'example_selector' should be provided\"\n            )\n        if examples is None and example_selector is None:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html"}
{"id": "9b82c62c98d7-1", "text": ")\n        if examples is None and example_selector is None:\n            raise ValueError(\n                \"One of 'examples' and 'example_selector' should be provided\"\n            )\n        return values\n    def _get_examples(self, **kwargs: Any) -> List[dict]:\n        \"\"\"Get the examples to use for formatting the prompt.\n        Args:\n            **kwargs: Keyword arguments to be passed to the example selector.\n        Returns:\n            List of examples.\n        \"\"\"\n        if self.examples is not None:\n            return self.examples\n        elif self.example_selector is not None:\n            return self.example_selector.select_examples(kwargs)\n        else:\n            raise ValueError(\n                \"One of 'examples' and 'example_selector' should be provided\"\n            )\n[docs]class FewShotPromptTemplate(_FewShotPromptTemplateMixin, StringPromptTemplate):\n    \"\"\"Prompt template that contains few shot examples.\"\"\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether or not the class is serializable.\"\"\"\n        return False\n    validate_template: bool = False\n    \"\"\"Whether or not to try validating the template.\"\"\"\n    input_variables: List[str]\n    \"\"\"A list of the names of the variables the prompt template expects.\"\"\"\n    example_prompt: PromptTemplate\n    \"\"\"PromptTemplate used to format an individual example.\"\"\"\n    suffix: str\n    \"\"\"A prompt template string to put after the examples.\"\"\"\n    example_separator: str = \"\\n\\n\"\n    \"\"\"String separator used to join the prefix, the examples, and suffix.\"\"\"\n    prefix: str = \"\"\n    \"\"\"A prompt template string to put before the examples.\"\"\"\n    template_format: Union[Literal[\"f-string\"], Literal[\"jinja2\"]] = \"f-string\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html"}
{"id": "9b82c62c98d7-2", "text": "\"\"\"The format of the prompt template. Options are: 'f-string', 'jinja2'.\"\"\"\n    @root_validator()\n    def template_is_valid(cls, values: Dict) -> Dict:\n        \"\"\"Check that prefix, suffix, and input variables are consistent.\"\"\"\n        if values[\"validate_template\"]:\n            check_valid_template(\n                values[\"prefix\"] + values[\"suffix\"],\n                values[\"template_format\"],\n                values[\"input_variables\"] + list(values[\"partial_variables\"]),\n            )\n        elif values.get(\"template_format\"):\n            values[\"input_variables\"] = [\n                var\n                for var in get_template_variables(\n                    values[\"prefix\"] + values[\"suffix\"], values[\"template_format\"]\n                )\n                if var not in values[\"partial_variables\"]\n            ]\n        return values\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n[docs]    def format(self, **kwargs: Any) -> str:\n        \"\"\"Format the prompt with the inputs.\n        Args:\n            **kwargs: Any arguments to be passed to the prompt template.\n        Returns:\n            A formatted string.\n        Example:\n        .. code-block:: python\n            prompt.format(variable1=\"foo\")\n        \"\"\"\n        kwargs = self._merge_partial_and_user_variables(**kwargs)\n        # Get the examples to use.\n        examples = self._get_examples(**kwargs)\n        examples = [\n            {k: e[k] for k in self.example_prompt.input_variables} for e in examples\n        ]\n        # Format the examples.\n        example_strings = [\n            self.example_prompt.format(**example) for example in examples\n        ]\n        # Create the overall template.\n        pieces = [self.prefix, *example_strings, self.suffix]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html"}
{"id": "9b82c62c98d7-3", "text": "pieces = [self.prefix, *example_strings, self.suffix]\n        template = self.example_separator.join([piece for piece in pieces if piece])\n        # Format the template with the input variables.\n        return DEFAULT_FORMATTER_MAPPING[self.template_format](template, **kwargs)\n    @property\n    def _prompt_type(self) -> str:\n        \"\"\"Return the prompt type key.\"\"\"\n        return \"few_shot\"\n[docs]    def save(self, file_path: Union[Path, str]) -> None:\n        if self.example_selector:\n            raise ValueError(\"Saving an example selector is not currently supported\")\n        return super().save(file_path)\n[docs]class FewShotChatMessagePromptTemplate(\n    BaseChatPromptTemplate, _FewShotPromptTemplateMixin\n):\n    \"\"\"Chat prompt template that supports few-shot examples.\n    The high level structure of produced by this prompt template is a list of messages\n    consisting of prefix message(s), example message(s), and suffix message(s).\n    This structure enables creating a conversation with intermediate examples like:\n        System: You are a helpful AI Assistant\n        Human: What is 2+2?\n        AI: 4\n        Human: What is 2+3?\n        AI: 5\n        Human: What is 4+4?\n    This prompt template can be used to generate a fixed list of examples or else\n    to dynamically select examples based on the input.\n    Examples:\n        Prompt template with a fixed list of examples (matching the sample\n        conversation above):\n        .. code-block:: python\n            from langchain.prompts import (\n                FewShotChatMessagePromptTemplate,\n                ChatPromptTemplate\n            )\n            examples = [\n                {\"input\": \"2+2\", \"output\": \"4\"},", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html"}
{"id": "9b82c62c98d7-4", "text": "{\"input\": \"2+2\", \"output\": \"4\"},\n                {\"input\": \"2+3\", \"output\": \"5\"},\n            ]\n            example_prompt = ChatPromptTemplate.from_messages(\n                [('human', '{input}'), ('ai', '{output}')]\n            )\n            few_shot_prompt = FewShotChatMessagePromptTemplate(\n                examples=examples,\n                # This is a prompt template used to format each individual example.\n                example_prompt=example_prompt,\n            )\n            final_prompt = ChatPromptTemplate.from_messages(\n                [\n                    ('system', 'You are a helpful AI Assistant'),\n                    few_shot_prompt,\n                    ('human', '{input}'),\n                ]\n            )\n            final_prompt.format(input=\"What is 4+4?\")\n        Prompt template with dynamically selected examples:\n        .. code-block:: python\n            from langchain.prompts import SemanticSimilarityExampleSelector\n            from langchain.embeddings import OpenAIEmbeddings\n            from langchain.vectorstores import Chroma\n            examples = [\n                {\"input\": \"2+2\", \"output\": \"4\"},\n                {\"input\": \"2+3\", \"output\": \"5\"},\n                {\"input\": \"2+4\", \"output\": \"6\"},\n                # ...\n            ]\n            to_vectorize = [\n                \" \".join(example.values())\n                for example in examples\n            ]\n            embeddings = OpenAIEmbeddings()\n            vectorstore = Chroma.from_texts(\n                to_vectorize, embeddings, metadatas=examples\n            )\n            example_selector = SemanticSimilarityExampleSelector(\n                vectorstore=vectorstore\n            )\n            from langchain.schema import SystemMessage\n            from langchain.prompts import HumanMessagePromptTemplate", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html"}
{"id": "9b82c62c98d7-5", "text": "from langchain.prompts import HumanMessagePromptTemplate\n            from langchain.prompts.few_shot import FewShotChatMessagePromptTemplate\n            few_shot_prompt = FewShotChatMessagePromptTemplate(\n                # Which variable(s) will be passed to the example selector.\n                input_variables=[\"input\"],\n                example_selector=example_selector,\n                # Define how each example will be formatted.\n                # In this case, each example will become 2 messages:\n                # 1 human, and 1 AI\n                example_prompt=(\n                    HumanMessagePromptTemplate.from_template(\"{input}\")\n                    + AIMessagePromptTemplate.from_template(\"{output}\")\n                ),\n            )\n            # Define the overall prompt.\n            final_prompt = (\n                SystemMessagePromptTemplate.from_template(\n                    \"You are a helpful AI Assistant\"\n                )\n                + few_shot_prompt\n                + HumanMessagePromptTemplate.from_template(\"{input}\")\n            )\n            # Show the prompt\n            print(final_prompt.format_messages(input=\"What's 3+3?\"))\n            # Use within an LLM\n            from langchain.chat_models import ChatAnthropic\n            chain = final_prompt | ChatAnthropic()\n            chain.invoke({\"input\": \"What's 3+3?\"})\n    \"\"\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether or not the class is serializable.\"\"\"\n        return False\n    input_variables: List[str] = Field(default_factory=list)\n    \"\"\"A list of the names of the variables the prompt template will use\n    to pass to the example_selector, if provided.\"\"\"\n    example_prompt: Union[BaseMessagePromptTemplate, BaseChatPromptTemplate]\n    \"\"\"The class to format each example.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html"}
{"id": "9b82c62c98d7-6", "text": "\"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n[docs]    def format_messages(self, **kwargs: Any) -> List[BaseMessage]:\n        \"\"\"Format kwargs into a list of messages.\n        Args:\n            **kwargs: keyword arguments to use for filling in templates in messages.\n        Returns:\n            A list of formatted messages with all template variables filled in.\n        \"\"\"\n        # Get the examples to use.\n        examples = self._get_examples(**kwargs)\n        examples = [\n            {k: e[k] for k in self.example_prompt.input_variables} for e in examples\n        ]\n        # Format the examples.\n        messages = [\n            message\n            for example in examples\n            for message in self.example_prompt.format_messages(**example)\n        ]\n        return messages\n[docs]    def format(self, **kwargs: Any) -> str:\n        \"\"\"Format the prompt with inputs generating a string.\n        Use this method to generate a string representation of a prompt consisting\n        of chat messages.\n        Useful for feeding into a string based completion language model or debugging.\n        Args:\n            **kwargs: keyword arguments to use for formatting.\n        Returns:\n            A string representation of the prompt\n        \"\"\"\n        messages = self.format_messages(**kwargs)\n        return get_buffer_string(messages)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html"}
{"id": "40de01057950-0", "text": "Source code for langchain.prompts.pipeline\nfrom typing import Any, Dict, List, Tuple\nfrom langchain.prompts.chat import BaseChatPromptTemplate\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import BasePromptTemplate, PromptValue\ndef _get_inputs(inputs: dict, input_variables: List[str]) -> dict:\n    return {k: inputs[k] for k in input_variables}\n[docs]class PipelinePromptTemplate(BasePromptTemplate):\n    \"\"\"A prompt template for composing multiple prompt templates together.\n    This can be useful when you want to reuse parts of prompts.\n    A PipelinePrompt consists of two main parts:\n        - final_prompt: This is the final prompt that is returned\n        - pipeline_prompts: This is a list of tuples, consisting\n            of a string (`name`) and a Prompt Template.\n            Each PromptTemplate will be formatted and then passed\n            to future prompt templates as a variable with\n            the same name as `name`\n    \"\"\"\n    final_prompt: BasePromptTemplate\n    \"\"\"The final prompt that is returned.\"\"\"\n    pipeline_prompts: List[Tuple[str, BasePromptTemplate]]\n    \"\"\"A list of tuples, consisting of a string (`name`) and a Prompt Template.\"\"\"\n    @root_validator(pre=True)\n    def get_input_variables(cls, values: Dict) -> Dict:\n        \"\"\"Get input variables.\"\"\"\n        created_variables = set()\n        all_variables = set()\n        for k, prompt in values[\"pipeline_prompts\"]:\n            created_variables.add(k)\n            all_variables.update(prompt.input_variables)\n        values[\"input_variables\"] = list(all_variables.difference(created_variables))\n        return values\n[docs]    def format_prompt(self, **kwargs: Any) -> PromptValue:\n        for k, prompt in self.pipeline_prompts:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/pipeline.html"}
{"id": "40de01057950-1", "text": "for k, prompt in self.pipeline_prompts:\n            _inputs = _get_inputs(kwargs, prompt.input_variables)\n            if isinstance(prompt, BaseChatPromptTemplate):\n                kwargs[k] = prompt.format_messages(**_inputs)\n            else:\n                kwargs[k] = prompt.format(**_inputs)\n        _inputs = _get_inputs(kwargs, self.final_prompt.input_variables)\n        return self.final_prompt.format_prompt(**_inputs)\n[docs]    def format(self, **kwargs: Any) -> str:\n        return self.format_prompt(**kwargs).to_string()\n    @property\n    def _prompt_type(self) -> str:\n        raise ValueError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/pipeline.html"}
{"id": "1355eba9ddc3-0", "text": "Source code for langchain.prompts.prompt\n\"\"\"Prompt schema definition.\"\"\"\nfrom __future__ import annotations\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Literal, Optional, Union\nfrom langchain.prompts.base import (\n    DEFAULT_FORMATTER_MAPPING,\n    StringPromptTemplate,\n    check_valid_template,\n    get_template_variables,\n)\nfrom langchain.pydantic_v1 import root_validator\n[docs]class PromptTemplate(StringPromptTemplate):\n    \"\"\"A prompt template for a language model.\n    A prompt template consists of a string template. It accepts a set of parameters\n    from the user that can be used to generate a prompt for a language model.\n    The template can be formatted using either f-strings (default) or jinja2 syntax.\n    *Security warning*: Prefer using `template_format=\"f-string\"` instead of\n        `template_format=\"jinja2\"`, or make sure to NEVER accept jinja2 templates\n        from untrusted sources as they may lead to arbitrary Python code execution.\n        As of LangChain 0.0.329, Jinja2 templates will be rendered using\n        Jinja2's SandboxedEnvironment by default. This sand-boxing should\n        be treated as a best-effort approach rather than a guarantee of security,\n        as it is an opt-out rather than opt-in approach.\n        Despite the sand-boxing, we recommend to never use jinja2 templates\n        from untrusted sources.\n    Example:\n        .. code-block:: python\n            from langchain.prompts import PromptTemplate\n            # Instantiation using from_template (recommended)\n            prompt = PromptTemplate.from_template(\"Say {foo}\")\n            prompt.format(foo=\"bar\")\n            # Instantiation using initializer\n            prompt = PromptTemplate(input_variables=[\"foo\"], template=\"Say {foo}\")\n    \"\"\"\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html"}
{"id": "1355eba9ddc3-1", "text": "\"\"\"\n    @property\n    def lc_attributes(self) -> Dict[str, Any]:\n        return {\n            \"template_format\": self.template_format,\n        }\n    input_variables: List[str]\n    \"\"\"A list of the names of the variables the prompt template expects.\"\"\"\n    template: str\n    \"\"\"The prompt template.\"\"\"\n    template_format: Union[Literal[\"f-string\"], Literal[\"jinja2\"]] = \"f-string\"\n    \"\"\"The format of the prompt template. Options are: 'f-string', 'jinja2'.\"\"\"\n    validate_template: bool = False\n    \"\"\"Whether or not to try validating the template.\"\"\"\n    def __add__(self, other: Any) -> PromptTemplate:\n        \"\"\"Override the + operator to allow for combining prompt templates.\"\"\"\n        # Allow for easy combining\n        if isinstance(other, PromptTemplate):\n            if self.template_format != \"f-string\":\n                raise ValueError(\n                    \"Adding prompt templates only supported for f-strings.\"\n                )\n            if other.template_format != \"f-string\":\n                raise ValueError(\n                    \"Adding prompt templates only supported for f-strings.\"\n                )\n            input_variables = list(\n                set(self.input_variables) | set(other.input_variables)\n            )\n            template = self.template + other.template\n            # If any do not want to validate, then don't\n            validate_template = self.validate_template and other.validate_template\n            partial_variables = {k: v for k, v in self.partial_variables.items()}\n            for k, v in other.partial_variables.items():\n                if k in partial_variables:\n                    raise ValueError(\"Cannot have same variable partialed twice.\")\n                else:\n                    partial_variables[k] = v\n            return PromptTemplate(\n                template=template,\n                input_variables=input_variables,\n                partial_variables=partial_variables,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html"}
{"id": "1355eba9ddc3-2", "text": "input_variables=input_variables,\n                partial_variables=partial_variables,\n                template_format=\"f-string\",\n                validate_template=validate_template,\n            )\n        elif isinstance(other, str):\n            prompt = PromptTemplate.from_template(other)\n            return self + prompt\n        else:\n            raise NotImplementedError(f\"Unsupported operand type for +: {type(other)}\")\n    @property\n    def _prompt_type(self) -> str:\n        \"\"\"Return the prompt type key.\"\"\"\n        return \"prompt\"\n[docs]    def format(self, **kwargs: Any) -> str:\n        \"\"\"Format the prompt with the inputs.\n        Args:\n            kwargs: Any arguments to be passed to the prompt template.\n        Returns:\n            A formatted string.\n        Example:\n            .. code-block:: python\n                prompt.format(variable1=\"foo\")\n        \"\"\"\n        kwargs = self._merge_partial_and_user_variables(**kwargs)\n        return DEFAULT_FORMATTER_MAPPING[self.template_format](self.template, **kwargs)\n    @root_validator()\n    def template_is_valid(cls, values: Dict) -> Dict:\n        \"\"\"Check that template and input variables are consistent.\"\"\"\n        if values[\"validate_template\"]:\n            all_inputs = values[\"input_variables\"] + list(values[\"partial_variables\"])\n            check_valid_template(\n                values[\"template\"], values[\"template_format\"], all_inputs\n            )\n        elif values.get(\"template_format\"):\n            values[\"input_variables\"] = [\n                var\n                for var in get_template_variables(\n                    values[\"template\"], values[\"template_format\"]\n                )\n                if var not in values[\"partial_variables\"]\n            ]\n        return values\n[docs]    @classmethod\n    def from_examples(\n        cls,\n        examples: List[str],\n        suffix: str,\n        input_variables: List[str],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html"}
{"id": "1355eba9ddc3-3", "text": "suffix: str,\n        input_variables: List[str],\n        example_separator: str = \"\\n\\n\",\n        prefix: str = \"\",\n        **kwargs: Any,\n    ) -> PromptTemplate:\n        \"\"\"Take examples in list format with prefix and suffix to create a prompt.\n        Intended to be used as a way to dynamically create a prompt from examples.\n        Args:\n            examples: List of examples to use in the prompt.\n            suffix: String to go after the list of examples. Should generally\n                set up the user's input.\n            input_variables: A list of variable names the final prompt template\n                will expect.\n            example_separator: The separator to use in between examples. Defaults\n                to two new line characters.\n            prefix: String that should go before any examples. Generally includes\n                examples. Default to an empty string.\n        Returns:\n            The final prompt generated.\n        \"\"\"\n        template = example_separator.join([prefix, *examples, suffix])\n        return cls(input_variables=input_variables, template=template, **kwargs)\n[docs]    @classmethod\n    def from_file(\n        cls, template_file: Union[str, Path], input_variables: List[str], **kwargs: Any\n    ) -> PromptTemplate:\n        \"\"\"Load a prompt from a file.\n        Args:\n            template_file: The path to the file containing the prompt template.\n            input_variables: A list of variable names the final prompt template\n                will expect.\n        Returns:\n            The prompt loaded from the file.\n        \"\"\"\n        with open(str(template_file), \"r\") as f:\n            template = f.read()\n        return cls(input_variables=input_variables, template=template, **kwargs)\n[docs]    @classmethod\n    def from_template(\n        cls,\n        template: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html"}
{"id": "1355eba9ddc3-4", "text": "def from_template(\n        cls,\n        template: str,\n        *,\n        template_format: str = \"f-string\",\n        partial_variables: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> PromptTemplate:\n        \"\"\"Load a prompt template from a template.\n        *Security warning*: Prefer using `template_format=\"f-string\"` instead of\n            `template_format=\"jinja2\"`, or make sure to NEVER accept jinja2 templates\n            from untrusted sources as they may lead to arbitrary Python code execution.\n            As of LangChain 0.0.329, Jinja2 templates will be rendered using\n            Jinja2's SandboxedEnvironment by default. This sand-boxing should\n            be treated as a best-effort approach rather than a guarantee of security,\n            as it is an opt-out rather than opt-in approach.\n            Despite the sand-boxing, we recommend to never use jinja2 templates\n            from untrusted sources.\n        Args:\n            template: The template to load.\n            template_format: The format of the template. Use `jinja2` for jinja2,\n                             and `f-string` or None for f-strings.\n            partial_variables: A dictionary of variables that can be used to partially\n                               fill in the template. For example, if the template is\n                              `\"{variable1} {variable2}\"`, and `partial_variables` is\n                              `{\"variable1\": \"foo\"}`, then the final prompt will be\n                              `\"foo {variable2}\"`.\n        Returns:\n            The prompt template loaded from the template.\n        \"\"\"\n        input_variables = get_template_variables(template, template_format)\n        _partial_variables = partial_variables or {}\n        if _partial_variables:\n            input_variables = [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html"}
{"id": "1355eba9ddc3-5", "text": "if _partial_variables:\n            input_variables = [\n                var for var in input_variables if var not in _partial_variables\n            ]\n        return cls(\n            input_variables=input_variables,\n            template=template,\n            template_format=template_format,\n            partial_variables=_partial_variables,\n            **kwargs,\n        )\n# For backwards compatibility.\nPrompt = PromptTemplate", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html"}
{"id": "e5e29154b0fe-0", "text": "Source code for langchain.prompts.base\n\"\"\"BasePrompt schema definition.\"\"\"\nfrom __future__ import annotations\nimport warnings\nfrom abc import ABC\nfrom string import Formatter\nfrom typing import Any, Callable, Dict, List, Literal, Set\nfrom langchain.schema.messages import BaseMessage, HumanMessage\nfrom langchain.schema.prompt import PromptValue\nfrom langchain.schema.prompt_template import BasePromptTemplate\nfrom langchain.utils.formatting import formatter\n[docs]def jinja2_formatter(template: str, **kwargs: Any) -> str:\n    \"\"\"Format a template using jinja2.\n    *Security warning*: As of LangChain 0.0.329, this method uses Jinja2's\n        SandboxedEnvironment by default. However, this sand-boxing should\n        be treated as a best-effort approach rather than a guarantee of security.\n        Do not accept jinja2 templates from untrusted sources as they may lead\n        to arbitrary Python code execution.\n        https://jinja.palletsprojects.com/en/3.1.x/sandbox/\n    \"\"\"\n    try:\n        from jinja2.sandbox import SandboxedEnvironment\n    except ImportError:\n        raise ImportError(\n            \"jinja2 not installed, which is needed to use the jinja2_formatter. \"\n            \"Please install it with `pip install jinja2`.\"\n            \"Please be cautious when using jinja2 templates. \"\n            \"Do not expand jinja2 templates using unverified or user-controlled \"\n            \"inputs as that can result in arbitrary Python code execution.\"\n        )\n    # This uses a sandboxed environment to prevent arbitrary code execution.\n    # Jinja2 uses an opt-out rather than opt-in approach for sand-boxing.\n    # Please treat this sand-boxing as a best-effort approach rather than\n    # a guarantee of security.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html"}
{"id": "e5e29154b0fe-1", "text": "# a guarantee of security.\n    # We recommend to never use jinja2 templates with untrusted inputs.\n    # https://jinja.palletsprojects.com/en/3.1.x/sandbox/\n    # approach not a guarantee of security.\n    return SandboxedEnvironment().from_string(template).render(**kwargs)\n[docs]def validate_jinja2(template: str, input_variables: List[str]) -> None:\n    \"\"\"\n    Validate that the input variables are valid for the template.\n    Issues a warning if missing or extra variables are found.\n    Args:\n        template: The template string.\n        input_variables: The input variables.\n    \"\"\"\n    input_variables_set = set(input_variables)\n    valid_variables = _get_jinja2_variables_from_template(template)\n    missing_variables = valid_variables - input_variables_set\n    extra_variables = input_variables_set - valid_variables\n    warning_message = \"\"\n    if missing_variables:\n        warning_message += f\"Missing variables: {missing_variables} \"\n    if extra_variables:\n        warning_message += f\"Extra variables: {extra_variables}\"\n    if warning_message:\n        warnings.warn(warning_message.strip())\ndef _get_jinja2_variables_from_template(template: str) -> Set[str]:\n    try:\n        from jinja2 import Environment, meta\n    except ImportError:\n        raise ImportError(\n            \"jinja2 not installed, which is needed to use the jinja2_formatter. \"\n            \"Please install it with `pip install jinja2`.\"\n        )\n    env = Environment()\n    ast = env.parse(template)\n    variables = meta.find_undeclared_variables(ast)\n    return variables\nDEFAULT_FORMATTER_MAPPING: Dict[str, Callable] = {\n    \"f-string\": formatter.format,\n    \"jinja2\": jinja2_formatter,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html"}
{"id": "e5e29154b0fe-2", "text": "\"jinja2\": jinja2_formatter,\n}\nDEFAULT_VALIDATOR_MAPPING: Dict[str, Callable] = {\n    \"f-string\": formatter.validate_input_variables,\n    \"jinja2\": validate_jinja2,\n}\n[docs]def check_valid_template(\n    template: str, template_format: str, input_variables: List[str]\n) -> None:\n    \"\"\"Check that template string is valid.\n    Args:\n        template: The template string.\n        template_format: The template format. Should be one of \"f-string\" or \"jinja2\".\n        input_variables: The input variables.\n    Raises:\n        ValueError: If the template format is not supported.\n    \"\"\"\n    if template_format not in DEFAULT_FORMATTER_MAPPING:\n        valid_formats = list(DEFAULT_FORMATTER_MAPPING)\n        raise ValueError(\n            f\"Invalid template format. Got `{template_format}`;\"\n            f\" should be one of {valid_formats}\"\n        )\n    try:\n        validator_func = DEFAULT_VALIDATOR_MAPPING[template_format]\n        validator_func(template, input_variables)\n    except KeyError as e:\n        raise ValueError(\n            \"Invalid prompt schema; check for mismatched or missing input parameters. \"\n            + str(e)\n        )\n[docs]def get_template_variables(template: str, template_format: str) -> List[str]:\n    \"\"\"Get the variables from the template.\n    Args:\n        template: The template string.\n        template_format: The template format. Should be one of \"f-string\" or \"jinja2\".\n    Returns:\n        The variables from the template.\n    Raises:\n        ValueError: If the template format is not supported.\n    \"\"\"\n    if template_format == \"jinja2\":\n        # Get the variables for the template", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html"}
{"id": "e5e29154b0fe-3", "text": "if template_format == \"jinja2\":\n        # Get the variables for the template\n        input_variables = _get_jinja2_variables_from_template(template)\n    elif template_format == \"f-string\":\n        input_variables = {\n            v for _, v, _, _ in Formatter().parse(template) if v is not None\n        }\n    else:\n        raise ValueError(f\"Unsupported template format: {template_format}\")\n    return sorted(input_variables)\n[docs]class StringPromptValue(PromptValue):\n    \"\"\"String prompt value.\"\"\"\n    text: str\n    \"\"\"Prompt text.\"\"\"\n    type: Literal[\"StringPromptValue\"] = \"StringPromptValue\"\n[docs]    def to_string(self) -> str:\n        \"\"\"Return prompt as string.\"\"\"\n        return self.text\n[docs]    def to_messages(self) -> List[BaseMessage]:\n        \"\"\"Return prompt as messages.\"\"\"\n        return [HumanMessage(content=self.text)]\n[docs]class StringPromptTemplate(BasePromptTemplate, ABC):\n    \"\"\"String prompt that exposes the format method, returning a prompt.\"\"\"\n[docs]    def format_prompt(self, **kwargs: Any) -> PromptValue:\n        \"\"\"Create Chat Messages.\"\"\"\n        return StringPromptValue(text=self.format(**kwargs))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html"}
{"id": "408171d04ffe-0", "text": "Source code for langchain.prompts.loading\n\"\"\"Load prompts.\"\"\"\nimport json\nimport logging\nfrom pathlib import Path\nfrom typing import Callable, Dict, Union\nimport yaml\nfrom langchain.prompts.few_shot import FewShotPromptTemplate\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.schema import BaseLLMOutputParser, BasePromptTemplate, StrOutputParser\nfrom langchain.utils.loading import try_load_from_hub\nURL_BASE = \"https://raw.githubusercontent.com/hwchase17/langchain-hub/master/prompts/\"\nlogger = logging.getLogger(__name__)\n[docs]def load_prompt_from_config(config: dict) -> BasePromptTemplate:\n    \"\"\"Load prompt from Config Dict.\"\"\"\n    if \"_type\" not in config:\n        logger.warning(\"No `_type` key found, defaulting to `prompt`.\")\n    config_type = config.pop(\"_type\", \"prompt\")\n    if config_type not in type_to_loader_dict:\n        raise ValueError(f\"Loading {config_type} prompt not supported\")\n    prompt_loader = type_to_loader_dict[config_type]\n    return prompt_loader(config)\ndef _load_template(var_name: str, config: dict) -> dict:\n    \"\"\"Load template from the path if applicable.\"\"\"\n    # Check if template_path exists in config.\n    if f\"{var_name}_path\" in config:\n        # If it does, make sure template variable doesn't also exist.\n        if var_name in config:\n            raise ValueError(\n                f\"Both `{var_name}_path` and `{var_name}` cannot be provided.\"\n            )\n        # Pop the template path from the config.\n        template_path = Path(config.pop(f\"{var_name}_path\"))\n        # Load the template.\n        if template_path.suffix == \".txt\":\n            with open(template_path) as f:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html"}
{"id": "408171d04ffe-1", "text": "with open(template_path) as f:\n                template = f.read()\n        else:\n            raise ValueError\n        # Set the template variable to the extracted variable.\n        config[var_name] = template\n    return config\ndef _load_examples(config: dict) -> dict:\n    \"\"\"Load examples if necessary.\"\"\"\n    if isinstance(config[\"examples\"], list):\n        pass\n    elif isinstance(config[\"examples\"], str):\n        with open(config[\"examples\"]) as f:\n            if config[\"examples\"].endswith(\".json\"):\n                examples = json.load(f)\n            elif config[\"examples\"].endswith((\".yaml\", \".yml\")):\n                examples = yaml.safe_load(f)\n            else:\n                raise ValueError(\n                    \"Invalid file format. Only json or yaml formats are supported.\"\n                )\n        config[\"examples\"] = examples\n    else:\n        raise ValueError(\"Invalid examples format. Only list or string are supported.\")\n    return config\ndef _load_output_parser(config: dict) -> dict:\n    \"\"\"Load output parser.\"\"\"\n    if \"output_parser\" in config and config[\"output_parser\"]:\n        _config = config.pop(\"output_parser\")\n        output_parser_type = _config.pop(\"_type\")\n        if output_parser_type == \"regex_parser\":\n            from langchain.output_parsers.regex import RegexParser\n            output_parser: BaseLLMOutputParser = RegexParser(**_config)\n        elif output_parser_type == \"default\":\n            output_parser = StrOutputParser(**_config)\n        else:\n            raise ValueError(f\"Unsupported output parser {output_parser_type}\")\n        config[\"output_parser\"] = output_parser\n    return config\ndef _load_few_shot_prompt(config: dict) -> FewShotPromptTemplate:\n    \"\"\"Load the \"few shot\" prompt from the config.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html"}
{"id": "408171d04ffe-2", "text": "\"\"\"Load the \"few shot\" prompt from the config.\"\"\"\n    # Load the suffix and prefix templates.\n    config = _load_template(\"suffix\", config)\n    config = _load_template(\"prefix\", config)\n    # Load the example prompt.\n    if \"example_prompt_path\" in config:\n        if \"example_prompt\" in config:\n            raise ValueError(\n                \"Only one of example_prompt and example_prompt_path should \"\n                \"be specified.\"\n            )\n        config[\"example_prompt\"] = load_prompt(config.pop(\"example_prompt_path\"))\n    else:\n        config[\"example_prompt\"] = load_prompt_from_config(config[\"example_prompt\"])\n    # Load the examples.\n    config = _load_examples(config)\n    config = _load_output_parser(config)\n    return FewShotPromptTemplate(**config)\ndef _load_prompt(config: dict) -> PromptTemplate:\n    \"\"\"Load the prompt template from config.\"\"\"\n    # Load the template from disk if necessary.\n    config = _load_template(\"template\", config)\n    config = _load_output_parser(config)\n    template_format = config.get(\"template_format\", \"f-string\")\n    if template_format == \"jinja2\":\n        # Disabled due to:\n        # https://github.com/langchain-ai/langchain/issues/4394\n        raise ValueError(\n            f\"Loading templates with '{template_format}' format is no longer supported \"\n            f\"since it can lead to arbitrary code execution. Please migrate to using \"\n            f\"the 'f-string' template format, which does not suffer from this issue.\"\n        )\n    return PromptTemplate(**config)\n[docs]def load_prompt(path: Union[str, Path]) -> BasePromptTemplate:\n    \"\"\"Unified method for loading a prompt from LangChainHub or local fs.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html"}
{"id": "408171d04ffe-3", "text": "\"\"\"Unified method for loading a prompt from LangChainHub or local fs.\"\"\"\n    if hub_result := try_load_from_hub(\n        path, _load_prompt_from_file, \"prompts\", {\"py\", \"json\", \"yaml\"}\n    ):\n        return hub_result\n    else:\n        return _load_prompt_from_file(path)\ndef _load_prompt_from_file(file: Union[str, Path]) -> BasePromptTemplate:\n    \"\"\"Load prompt from file.\"\"\"\n    # Convert file to a Path object.\n    if isinstance(file, str):\n        file_path = Path(file)\n    else:\n        file_path = file\n    # Load from either json or yaml.\n    if file_path.suffix == \".json\":\n        with open(file_path) as f:\n            config = json.load(f)\n    elif file_path.suffix == \".yaml\":\n        with open(file_path, \"r\") as f:\n            config = yaml.safe_load(f)\n    else:\n        raise ValueError(f\"Got unsupported file type {file_path.suffix}\")\n    # Load the prompt from the config now.\n    return load_prompt_from_config(config)\ntype_to_loader_dict: Dict[str, Callable[[dict], BasePromptTemplate]] = {\n    \"prompt\": _load_prompt,\n    \"few_shot\": _load_few_shot_prompt,\n}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html"}
{"id": "8f60699980cf-0", "text": "Source code for langchain.prompts.few_shot_with_templates\n\"\"\"Prompt template that contains few shot examples.\"\"\"\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Union\nfrom langchain.prompts.base import DEFAULT_FORMATTER_MAPPING, StringPromptTemplate\nfrom langchain.prompts.example_selector.base import BaseExampleSelector\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.pydantic_v1 import Extra, root_validator\n[docs]class FewShotPromptWithTemplates(StringPromptTemplate):\n    \"\"\"Prompt template that contains few shot examples.\"\"\"\n    examples: Optional[List[dict]] = None\n    \"\"\"Examples to format into the prompt.\n    Either this or example_selector should be provided.\"\"\"\n    example_selector: Optional[BaseExampleSelector] = None\n    \"\"\"ExampleSelector to choose the examples to format into the prompt.\n    Either this or examples should be provided.\"\"\"\n    example_prompt: PromptTemplate\n    \"\"\"PromptTemplate used to format an individual example.\"\"\"\n    suffix: StringPromptTemplate\n    \"\"\"A PromptTemplate to put after the examples.\"\"\"\n    input_variables: List[str]\n    \"\"\"A list of the names of the variables the prompt template expects.\"\"\"\n    example_separator: str = \"\\n\\n\"\n    \"\"\"String separator used to join the prefix, the examples, and suffix.\"\"\"\n    prefix: Optional[StringPromptTemplate] = None\n    \"\"\"A PromptTemplate to put before the examples.\"\"\"\n    template_format: str = \"f-string\"\n    \"\"\"The format of the prompt template. Options are: 'f-string', 'jinja2'.\"\"\"\n    validate_template: bool = False\n    \"\"\"Whether or not to try validating the template.\"\"\"\n    @root_validator(pre=True)\n    def check_examples_and_selector(cls, values: Dict) -> Dict:\n        \"\"\"Check that one and only one of examples/example_selector are provided.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html"}
{"id": "8f60699980cf-1", "text": "\"\"\"Check that one and only one of examples/example_selector are provided.\"\"\"\n        examples = values.get(\"examples\", None)\n        example_selector = values.get(\"example_selector\", None)\n        if examples and example_selector:\n            raise ValueError(\n                \"Only one of 'examples' and 'example_selector' should be provided\"\n            )\n        if examples is None and example_selector is None:\n            raise ValueError(\n                \"One of 'examples' and 'example_selector' should be provided\"\n            )\n        return values\n    @root_validator()\n    def template_is_valid(cls, values: Dict) -> Dict:\n        \"\"\"Check that prefix, suffix, and input variables are consistent.\"\"\"\n        if values[\"validate_template\"]:\n            input_variables = values[\"input_variables\"]\n            expected_input_variables = set(values[\"suffix\"].input_variables)\n            expected_input_variables |= set(values[\"partial_variables\"])\n            if values[\"prefix\"] is not None:\n                expected_input_variables |= set(values[\"prefix\"].input_variables)\n            missing_vars = expected_input_variables.difference(input_variables)\n            if missing_vars:\n                raise ValueError(\n                    f\"Got input_variables={input_variables}, but based on \"\n                    f\"prefix/suffix expected {expected_input_variables}\"\n                )\n        else:\n            values[\"input_variables\"] = sorted(\n                set(values[\"suffix\"].input_variables)\n                | set(values[\"prefix\"].input_variables if values[\"prefix\"] else [])\n                - set(values[\"partial_variables\"])\n            )\n        return values\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n    def _get_examples(self, **kwargs: Any) -> List[dict]:\n        if self.examples is not None:\n            return self.examples", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html"}
{"id": "8f60699980cf-2", "text": "if self.examples is not None:\n            return self.examples\n        elif self.example_selector is not None:\n            return self.example_selector.select_examples(kwargs)\n        else:\n            raise ValueError\n[docs]    def format(self, **kwargs: Any) -> str:\n        \"\"\"Format the prompt with the inputs.\n        Args:\n            kwargs: Any arguments to be passed to the prompt template.\n        Returns:\n            A formatted string.\n        Example:\n        .. code-block:: python\n            prompt.format(variable1=\"foo\")\n        \"\"\"\n        kwargs = self._merge_partial_and_user_variables(**kwargs)\n        # Get the examples to use.\n        examples = self._get_examples(**kwargs)\n        # Format the examples.\n        example_strings = [\n            self.example_prompt.format(**example) for example in examples\n        ]\n        # Create the overall prefix.\n        if self.prefix is None:\n            prefix = \"\"\n        else:\n            prefix_kwargs = {\n                k: v for k, v in kwargs.items() if k in self.prefix.input_variables\n            }\n            for k in prefix_kwargs.keys():\n                kwargs.pop(k)\n            prefix = self.prefix.format(**prefix_kwargs)\n        # Create the overall suffix\n        suffix_kwargs = {\n            k: v for k, v in kwargs.items() if k in self.suffix.input_variables\n        }\n        for k in suffix_kwargs.keys():\n            kwargs.pop(k)\n        suffix = self.suffix.format(\n            **suffix_kwargs,\n        )\n        pieces = [prefix, *example_strings, suffix]\n        template = self.example_separator.join([piece for piece in pieces if piece])\n        # Format the template with the input variables.\n        return DEFAULT_FORMATTER_MAPPING[self.template_format](template, **kwargs)\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html"}
{"id": "8f60699980cf-3", "text": "return DEFAULT_FORMATTER_MAPPING[self.template_format](template, **kwargs)\n    @property\n    def _prompt_type(self) -> str:\n        \"\"\"Return the prompt type key.\"\"\"\n        return \"few_shot_with_templates\"\n[docs]    def save(self, file_path: Union[Path, str]) -> None:\n        if self.example_selector:\n            raise ValueError(\"Saving an example selector is not currently supported\")\n        return super().save(file_path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html"}
{"id": "41cb1c5d7063-0", "text": "Source code for langchain.prompts.example_selector.ngram_overlap\n\"\"\"Select and order examples based on ngram overlap score (sentence_bleu score).\nhttps://www.nltk.org/_modules/nltk/translate/bleu_score.html\nhttps://aclanthology.org/P02-1040.pdf\n\"\"\"\nfrom typing import Dict, List\nimport numpy as np\nfrom langchain.prompts.example_selector.base import BaseExampleSelector\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.pydantic_v1 import BaseModel, root_validator\n[docs]def ngram_overlap_score(source: List[str], example: List[str]) -> float:\n    \"\"\"Compute ngram overlap score of source and example as sentence_bleu score.\n    Use sentence_bleu with method1 smoothing function and auto reweighting.\n    Return float value between 0.0 and 1.0 inclusive.\n    https://www.nltk.org/_modules/nltk/translate/bleu_score.html\n    https://aclanthology.org/P02-1040.pdf\n    \"\"\"\n    from nltk.translate.bleu_score import (\n        SmoothingFunction,  # type: ignore\n        sentence_bleu,\n    )\n    hypotheses = source[0].split()\n    references = [s.split() for s in example]\n    return float(\n        sentence_bleu(\n            references,\n            hypotheses,\n            smoothing_function=SmoothingFunction().method1,\n            auto_reweigh=True,\n        )\n    )\n[docs]class NGramOverlapExampleSelector(BaseExampleSelector, BaseModel):\n    \"\"\"Select and order examples based on ngram overlap score (sentence_bleu score).\n    https://www.nltk.org/_modules/nltk/translate/bleu_score.html\n    https://aclanthology.org/P02-1040.pdf\n    \"\"\"\n    examples: List[dict]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html"}
{"id": "41cb1c5d7063-1", "text": "\"\"\"\n    examples: List[dict]\n    \"\"\"A list of the examples that the prompt template expects.\"\"\"\n    example_prompt: PromptTemplate\n    \"\"\"Prompt template used to format the examples.\"\"\"\n    threshold: float = -1.0\n    \"\"\"Threshold at which algorithm stops. Set to -1.0 by default.\n    For negative threshold:\n    select_examples sorts examples by ngram_overlap_score, but excludes none.\n    For threshold greater than 1.0:\n    select_examples excludes all examples, and returns an empty list.\n    For threshold equal to 0.0:\n    select_examples sorts examples by ngram_overlap_score,\n    and excludes examples with no ngram overlap with input.\n    \"\"\"\n    @root_validator(pre=True)\n    def check_dependencies(cls, values: Dict) -> Dict:\n        \"\"\"Check that valid dependencies exist.\"\"\"\n        try:\n            from nltk.translate.bleu_score import (  # noqa: F401\n                SmoothingFunction,\n                sentence_bleu,\n            )\n        except ImportError as e:\n            raise ImportError(\n                \"Not all the correct dependencies for this ExampleSelect exist.\"\n                \"Please install nltk with `pip install nltk`.\"\n            ) from e\n        return values\n[docs]    def add_example(self, example: Dict[str, str]) -> None:\n        \"\"\"Add new example to list.\"\"\"\n        self.examples.append(example)\n[docs]    def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:\n        \"\"\"Return list of examples sorted by ngram_overlap_score with input.\n        Descending order.\n        Excludes any examples with ngram_overlap_score less than or equal to threshold.\n        \"\"\"\n        inputs = list(input_variables.values())\n        examples = []\n        k = len(self.examples)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html"}
{"id": "41cb1c5d7063-2", "text": "examples = []\n        k = len(self.examples)\n        score = [0.0] * k\n        first_prompt_template_key = self.example_prompt.input_variables[0]\n        for i in range(k):\n            score[i] = ngram_overlap_score(\n                inputs, [self.examples[i][first_prompt_template_key]]\n            )\n        while True:\n            arg_max = np.argmax(score)\n            if (score[arg_max] < self.threshold) or abs(\n                score[arg_max] - self.threshold\n            ) < 1e-9:\n                break\n            examples.append(self.examples[arg_max])\n            score[arg_max] = self.threshold - 1.0\n        return examples", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html"}
{"id": "665440fd29b0-0", "text": "Source code for langchain.prompts.example_selector.semantic_similarity\n\"\"\"Example selector that selects examples based on SemanticSimilarity.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional, Type\nfrom langchain.prompts.example_selector.base import BaseExampleSelector\nfrom langchain.pydantic_v1 import BaseModel, Extra\nfrom langchain.schema.embeddings import Embeddings\nfrom langchain.schema.vectorstore import VectorStore\n[docs]def sorted_values(values: Dict[str, str]) -> List[Any]:\n    \"\"\"Return a list of values in dict sorted by key.\"\"\"\n    return [values[val] for val in sorted(values)]\n[docs]class SemanticSimilarityExampleSelector(BaseExampleSelector, BaseModel):\n    \"\"\"Example selector that selects examples based on SemanticSimilarity.\"\"\"\n    vectorstore: VectorStore\n    \"\"\"VectorStore than contains information about examples.\"\"\"\n    k: int = 4\n    \"\"\"Number of examples to select.\"\"\"\n    example_keys: Optional[List[str]] = None\n    \"\"\"Optional keys to filter examples to.\"\"\"\n    input_keys: Optional[List[str]] = None\n    \"\"\"Optional keys to filter input to. If provided, the search is based on\n    the input variables instead of all variables.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        arbitrary_types_allowed = True\n[docs]    def add_example(self, example: Dict[str, str]) -> str:\n        \"\"\"Add new example to vectorstore.\"\"\"\n        if self.input_keys:\n            string_example = \" \".join(\n                sorted_values({key: example[key] for key in self.input_keys})\n            )\n        else:\n            string_example = \" \".join(sorted_values(example))\n        ids = self.vectorstore.add_texts([string_example], metadatas=[example])\n        return ids[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html"}
{"id": "665440fd29b0-1", "text": "return ids[0]\n[docs]    def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:\n        \"\"\"Select which examples to use based on semantic similarity.\"\"\"\n        # Get the docs with the highest similarity.\n        if self.input_keys:\n            input_variables = {key: input_variables[key] for key in self.input_keys}\n        query = \" \".join(sorted_values(input_variables))\n        example_docs = self.vectorstore.similarity_search(query, k=self.k)\n        # Get the examples from the metadata.\n        # This assumes that examples are stored in metadata.\n        examples = [dict(e.metadata) for e in example_docs]\n        # If example keys are provided, filter examples to those keys.\n        if self.example_keys:\n            examples = [{k: eg[k] for k in self.example_keys} for eg in examples]\n        return examples\n[docs]    @classmethod\n    def from_examples(\n        cls,\n        examples: List[dict],\n        embeddings: Embeddings,\n        vectorstore_cls: Type[VectorStore],\n        k: int = 4,\n        input_keys: Optional[List[str]] = None,\n        **vectorstore_cls_kwargs: Any,\n    ) -> SemanticSimilarityExampleSelector:\n        \"\"\"Create k-shot example selector using example list and embeddings.\n        Reshuffles examples dynamically based on query similarity.\n        Args:\n            examples: List of examples to use in the prompt.\n            embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().\n            vectorstore_cls: A vector store DB interface class, e.g. FAISS.\n            k: Number of examples to select\n            input_keys: If provided, the search is based on the input variables\n                instead of all variables.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html"}
{"id": "665440fd29b0-2", "text": "instead of all variables.\n            vectorstore_cls_kwargs: optional kwargs containing url for vector store\n        Returns:\n            The ExampleSelector instantiated, backed by a vector store.\n        \"\"\"\n        if input_keys:\n            string_examples = [\n                \" \".join(sorted_values({k: eg[k] for k in input_keys}))\n                for eg in examples\n            ]\n        else:\n            string_examples = [\" \".join(sorted_values(eg)) for eg in examples]\n        vectorstore = vectorstore_cls.from_texts(\n            string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs\n        )\n        return cls(vectorstore=vectorstore, k=k, input_keys=input_keys)\n[docs]class MaxMarginalRelevanceExampleSelector(SemanticSimilarityExampleSelector):\n    \"\"\"ExampleSelector that selects examples based on Max Marginal Relevance.\n    This was shown to improve performance in this paper:\n    https://arxiv.org/pdf/2211.13892.pdf\n    \"\"\"\n    fetch_k: int = 20\n    \"\"\"Number of examples to fetch to rerank.\"\"\"\n[docs]    def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:\n        \"\"\"Select which examples to use based on semantic similarity.\"\"\"\n        # Get the docs with the highest similarity.\n        if self.input_keys:\n            input_variables = {key: input_variables[key] for key in self.input_keys}\n        query = \" \".join(sorted_values(input_variables))\n        example_docs = self.vectorstore.max_marginal_relevance_search(\n            query, k=self.k, fetch_k=self.fetch_k\n        )\n        # Get the examples from the metadata.\n        # This assumes that examples are stored in metadata.\n        examples = [dict(e.metadata) for e in example_docs]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html"}
{"id": "665440fd29b0-3", "text": "examples = [dict(e.metadata) for e in example_docs]\n        # If example keys are provided, filter examples to those keys.\n        if self.example_keys:\n            examples = [{k: eg[k] for k in self.example_keys} for eg in examples]\n        return examples\n[docs]    @classmethod\n    def from_examples(\n        cls,\n        examples: List[dict],\n        embeddings: Embeddings,\n        vectorstore_cls: Type[VectorStore],\n        k: int = 4,\n        input_keys: Optional[List[str]] = None,\n        fetch_k: int = 20,\n        **vectorstore_cls_kwargs: Any,\n    ) -> MaxMarginalRelevanceExampleSelector:\n        \"\"\"Create k-shot example selector using example list and embeddings.\n        Reshuffles examples dynamically based on query similarity.\n        Args:\n            examples: List of examples to use in the prompt.\n            embeddings: An iniialized embedding API interface, e.g. OpenAIEmbeddings().\n            vectorstore_cls: A vector store DB interface class, e.g. FAISS.\n            k: Number of examples to select\n            input_keys: If provided, the search is based on the input variables\n                instead of all variables.\n            vectorstore_cls_kwargs: optional kwargs containing url for vector store\n        Returns:\n            The ExampleSelector instantiated, backed by a vector store.\n        \"\"\"\n        if input_keys:\n            string_examples = [\n                \" \".join(sorted_values({k: eg[k] for k in input_keys}))\n                for eg in examples\n            ]\n        else:\n            string_examples = [\" \".join(sorted_values(eg)) for eg in examples]\n        vectorstore = vectorstore_cls.from_texts(\n            string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html"}
{"id": "665440fd29b0-4", "text": ")\n        return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html"}
{"id": "de2e7739d670-0", "text": "Source code for langchain.prompts.example_selector.base\n\"\"\"Interface for selecting examples to include in prompts.\"\"\"\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Dict, List\n[docs]class BaseExampleSelector(ABC):\n    \"\"\"Interface for selecting examples to include in prompts.\"\"\"\n[docs]    @abstractmethod\n    def add_example(self, example: Dict[str, str]) -> Any:\n        \"\"\"Add new example to store for a key.\"\"\"\n[docs]    @abstractmethod\n    def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:\n        \"\"\"Select which examples to use based on the inputs.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/base.html"}
{"id": "d6ac79cc46b4-0", "text": "Source code for langchain.prompts.example_selector.length_based\n\"\"\"Select examples based on length.\"\"\"\nimport re\nfrom typing import Callable, Dict, List\nfrom langchain.prompts.example_selector.base import BaseExampleSelector\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.pydantic_v1 import BaseModel, validator\ndef _get_length_based(text: str) -> int:\n    return len(re.split(\"\\n| \", text))\n[docs]class LengthBasedExampleSelector(BaseExampleSelector, BaseModel):\n    \"\"\"Select examples based on length.\"\"\"\n    examples: List[dict]\n    \"\"\"A list of the examples that the prompt template expects.\"\"\"\n    example_prompt: PromptTemplate\n    \"\"\"Prompt template used to format the examples.\"\"\"\n    get_text_length: Callable[[str], int] = _get_length_based\n    \"\"\"Function to measure prompt length. Defaults to word count.\"\"\"\n    max_length: int = 2048\n    \"\"\"Max length for the prompt, beyond which examples are cut.\"\"\"\n    example_text_lengths: List[int] = []  #: :meta private:\n[docs]    def add_example(self, example: Dict[str, str]) -> None:\n        \"\"\"Add new example to list.\"\"\"\n        self.examples.append(example)\n        string_example = self.example_prompt.format(**example)\n        self.example_text_lengths.append(self.get_text_length(string_example))\n    @validator(\"example_text_lengths\", always=True)\n    def calculate_example_text_lengths(cls, v: List[int], values: Dict) -> List[int]:\n        \"\"\"Calculate text lengths if they don't exist.\"\"\"\n        # Check if text lengths were passed in\n        if v:\n            return v\n        # If they were not, calculate them\n        example_prompt = values[\"example_prompt\"]\n        get_text_length = values[\"get_text_length\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html"}
{"id": "d6ac79cc46b4-1", "text": "get_text_length = values[\"get_text_length\"]\n        string_examples = [example_prompt.format(**eg) for eg in values[\"examples\"]]\n        return [get_text_length(eg) for eg in string_examples]\n[docs]    def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:\n        \"\"\"Select which examples to use based on the input lengths.\"\"\"\n        inputs = \" \".join(input_variables.values())\n        remaining_length = self.max_length - self.get_text_length(inputs)\n        i = 0\n        examples = []\n        while remaining_length > 0 and i < len(self.examples):\n            new_length = remaining_length - self.example_text_lengths[i]\n            if new_length < 0:\n                break\n            else:\n                examples.append(self.examples[i])\n                remaining_length = new_length\n            i += 1\n        return examples", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html"}
{"id": "57e8a26c3616-0", "text": "Source code for langchain.storage.exceptions\nfrom langchain.schema import LangChainException\n[docs]class InvalidKeyException(LangChainException):\n    \"\"\"Raised when a key is invalid; e.g., uses incorrect characters.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/exceptions.html"}
{"id": "4bd286c73082-0", "text": "Source code for langchain.storage.upstash_redis\nfrom typing import Any, Iterator, List, Optional, Sequence, Tuple, cast\nfrom langchain.schema import BaseStore\n[docs]class UpstashRedisStore(BaseStore[str, str]):\n    \"\"\"BaseStore implementation using Upstash Redis as the underlying store.\"\"\"\n[docs]    def __init__(\n        self,\n        *,\n        client: Any = None,\n        url: Optional[str] = None,\n        token: Optional[str] = None,\n        ttl: Optional[int] = None,\n        namespace: Optional[str] = None,\n    ) -> None:\n        \"\"\"Initialize the UpstashRedisStore with HTTP API.\n        Must provide either an Upstash Redis client or a url.\n        Args:\n            client: An Upstash Redis instance\n            url: UPSTASH_REDIS_REST_URL\n            token: UPSTASH_REDIS_REST_TOKEN\n            ttl: time to expire keys in seconds if provided,\n                 if None keys will never expire\n            namespace: if provided, all keys will be prefixed with this namespace\n        \"\"\"\n        try:\n            from upstash_redis import Redis\n        except ImportError as e:\n            raise ImportError(\n                \"UpstashRedisStore requires the upstash_redis library to be installed. \"\n                \"pip install upstash_redis\"\n            ) from e\n        if client and url:\n            raise ValueError(\n                \"Either an Upstash Redis client or a url must be provided, not both.\"\n            )\n        if client:\n            if not isinstance(client, Redis):\n                raise TypeError(\n                    f\"Expected Upstash Redis client, got {type(client).__name__}.\"\n                )\n            _client = client\n        else:\n            if not url or not token:\n                raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/upstash_redis.html"}
{"id": "4bd286c73082-1", "text": "else:\n            if not url or not token:\n                raise ValueError(\n                    \"Either an Upstash Redis client or url and token must be provided.\"\n                )\n            _client = Redis(url=url, token=token)\n        self.client = _client\n        if not isinstance(ttl, int) and ttl is not None:\n            raise TypeError(f\"Expected int or None, got {type(ttl)} instead.\")\n        self.ttl = ttl\n        self.namespace = namespace\n    def _get_prefixed_key(self, key: str) -> str:\n        \"\"\"Get the key with the namespace prefix.\n        Args:\n            key (str): The original key.\n        Returns:\n            str: The key with the namespace prefix.\n        \"\"\"\n        delimiter = \"/\"\n        if self.namespace:\n            return f\"{self.namespace}{delimiter}{key}\"\n        return key\n[docs]    def mget(self, keys: Sequence[str]) -> List[Optional[str]]:\n        \"\"\"Get the values associated with the given keys.\"\"\"\n        keys = [self._get_prefixed_key(key) for key in keys]\n        return cast(\n            List[Optional[str]],\n            self.client.mget(*keys),\n        )\n[docs]    def mset(self, key_value_pairs: Sequence[Tuple[str, str]]) -> None:\n        \"\"\"Set the given key-value pairs.\"\"\"\n        for key, value in key_value_pairs:\n            self.client.set(self._get_prefixed_key(key), value, ex=self.ttl)\n[docs]    def mdelete(self, keys: Sequence[str]) -> None:\n        \"\"\"Delete the given keys.\"\"\"\n        _keys = [self._get_prefixed_key(key) for key in keys]\n        self.client.delete(*_keys)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/upstash_redis.html"}
{"id": "4bd286c73082-2", "text": "self.client.delete(*_keys)\n[docs]    def yield_keys(self, *, prefix: Optional[str] = None) -> Iterator[str]:\n        \"\"\"Yield keys in the store.\"\"\"\n        if prefix:\n            pattern = self._get_prefixed_key(prefix)\n        else:\n            pattern = self._get_prefixed_key(\"*\")\n        cursor, keys = self.client.scan(0, match=pattern)\n        for key in keys:\n            if self.namespace:\n                relative_key = key[len(self.namespace) + 1 :]\n                yield relative_key\n            else:\n                yield key\n        while cursor != 0:\n            cursor, keys = self.client.scan(cursor, match=pattern)\n            for key in keys:\n                if self.namespace:\n                    relative_key = key[len(self.namespace) + 1 :]\n                    yield relative_key\n                else:\n                    yield key", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/upstash_redis.html"}
{"id": "af43cc304d33-0", "text": "Source code for langchain.storage.redis\nfrom typing import Any, Iterator, List, Optional, Sequence, Tuple, cast\nfrom langchain.schema import BaseStore\nfrom langchain.utilities.redis import get_client\n[docs]class RedisStore(BaseStore[str, bytes]):\n    \"\"\"BaseStore implementation using Redis as the underlying store.\n    Examples:\n        Create a RedisStore instance and perform operations on it:\n        .. code-block:: python\n            # Instantiate the RedisStore with a Redis connection\n            from langchain.storage import RedisStore\n            from langchain.utilities.redis import get_client\n            client = get_client('redis://localhost:6379')\n            redis_store = RedisStore(client)\n            # Set values for keys\n            redis_store.mset([(\"key1\", b\"value1\"), (\"key2\", b\"value2\")])\n            # Get values for keys\n            values = redis_store.mget([\"key1\", \"key2\"])\n            # [b\"value1\", b\"value2\"]\n            # Delete keys\n            redis_store.mdelete([\"key1\"])\n            # Iterate over keys\n            for key in redis_store.yield_keys():\n                print(key)\n    \"\"\"\n[docs]    def __init__(\n        self,\n        *,\n        client: Any = None,\n        redis_url: Optional[str] = None,\n        client_kwargs: Optional[dict] = None,\n        ttl: Optional[int] = None,\n        namespace: Optional[str] = None,\n    ) -> None:\n        \"\"\"Initialize the RedisStore with a Redis connection.\n        Must provide either a Redis client or a redis_url with optional client_kwargs.\n        Args:\n            client: A Redis connection instance\n            redis_url: redis url\n            client_kwargs: Keyword arguments to pass to the Redis client\n            ttl: time to expire keys in seconds if provided,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/redis.html"}
{"id": "af43cc304d33-1", "text": "ttl: time to expire keys in seconds if provided,\n                 if None keys will never expire\n            namespace: if provided, all keys will be prefixed with this namespace\n        \"\"\"\n        try:\n            from redis import Redis\n        except ImportError as e:\n            raise ImportError(\n                \"The RedisStore requires the redis library to be installed. \"\n                \"pip install redis\"\n            ) from e\n        if client and redis_url or client and client_kwargs:\n            raise ValueError(\n                \"Either a Redis client or a redis_url with optional client_kwargs \"\n                \"must be provided, but not both.\"\n            )\n        if client:\n            if not isinstance(client, Redis):\n                raise TypeError(\n                    f\"Expected Redis client, got {type(client).__name__} instead.\"\n                )\n            _client = client\n        else:\n            if not redis_url:\n                raise ValueError(\n                    \"Either a Redis client or a redis_url must be provided.\"\n                )\n            _client = get_client(redis_url, **(client_kwargs or {}))\n        self.client = _client\n        if not isinstance(ttl, int) and ttl is not None:\n            raise TypeError(f\"Expected int or None, got {type(ttl)} instead.\")\n        self.ttl = ttl\n        self.namespace = namespace\n    def _get_prefixed_key(self, key: str) -> str:\n        \"\"\"Get the key with the namespace prefix.\n        Args:\n            key (str): The original key.\n        Returns:\n            str: The key with the namespace prefix.\n        \"\"\"\n        delimiter = \"/\"\n        if self.namespace:\n            return f\"{self.namespace}{delimiter}{key}\"\n        return key\n[docs]    def mget(self, keys: Sequence[str]) -> List[Optional[bytes]]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/redis.html"}
{"id": "af43cc304d33-2", "text": "\"\"\"Get the values associated with the given keys.\"\"\"\n        return cast(\n            List[Optional[bytes]],\n            self.client.mget([self._get_prefixed_key(key) for key in keys]),\n        )\n[docs]    def mset(self, key_value_pairs: Sequence[Tuple[str, bytes]]) -> None:\n        \"\"\"Set the given key-value pairs.\"\"\"\n        pipe = self.client.pipeline()\n        for key, value in key_value_pairs:\n            pipe.set(self._get_prefixed_key(key), value, ex=self.ttl)\n        pipe.execute()\n[docs]    def mdelete(self, keys: Sequence[str]) -> None:\n        \"\"\"Delete the given keys.\"\"\"\n        _keys = [self._get_prefixed_key(key) for key in keys]\n        self.client.delete(*_keys)\n[docs]    def yield_keys(self, *, prefix: Optional[str] = None) -> Iterator[str]:\n        \"\"\"Yield keys in the store.\"\"\"\n        if prefix:\n            pattern = self._get_prefixed_key(prefix)\n        else:\n            pattern = self._get_prefixed_key(\"*\")\n        scan_iter = cast(Iterator[bytes], self.client.scan_iter(match=pattern))\n        for key in scan_iter:\n            decoded_key = key.decode(\"utf-8\")\n            if self.namespace:\n                relative_key = decoded_key[len(self.namespace) + 1 :]\n                yield relative_key\n            else:\n                yield decoded_key", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/redis.html"}
{"id": "fddb35974b92-0", "text": "Source code for langchain.storage.encoder_backed\nfrom typing import (\n    Any,\n    Callable,\n    Iterator,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    TypeVar,\n    Union,\n)\nfrom langchain.schema import BaseStore\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n[docs]class EncoderBackedStore(BaseStore[K, V]):\n    \"\"\"Wraps a store with key and value encoders/decoders.\n    Examples that uses JSON for encoding/decoding:\n    .. code-block:: python\n        import json\n        def key_encoder(key: int) -> str:\n            return json.dumps(key)\n        def value_serializer(value: float) -> str:\n            return json.dumps(value)\n        def value_deserializer(serialized_value: str) -> float:\n            return json.loads(serialized_value)\n        # Create an instance of the abstract store\n        abstract_store = MyCustomStore()\n        # Create an instance of the encoder-backed store\n        store = EncoderBackedStore(\n            store=abstract_store,\n            key_encoder=key_encoder,\n            value_serializer=value_serializer,\n            value_deserializer=value_deserializer\n        )\n        # Use the encoder-backed store methods\n        store.mset([(1, 3.14), (2, 2.718)])\n        values = store.mget([1, 2])  # Retrieves [3.14, 2.718]\n        store.mdelete([1, 2])  # Deletes the keys 1 and 2\n    \"\"\"\n[docs]    def __init__(\n        self,\n        store: BaseStore[str, Any],\n        key_encoder: Callable[[K], str],\n        value_serializer: Callable[[V], bytes],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/encoder_backed.html"}
{"id": "fddb35974b92-1", "text": "value_serializer: Callable[[V], bytes],\n        value_deserializer: Callable[[Any], V],\n    ) -> None:\n        \"\"\"Initialize an EncodedStore.\"\"\"\n        self.store = store\n        self.key_encoder = key_encoder\n        self.value_serializer = value_serializer\n        self.value_deserializer = value_deserializer\n[docs]    def mget(self, keys: Sequence[K]) -> List[Optional[V]]:\n        \"\"\"Get the values associated with the given keys.\"\"\"\n        encoded_keys: List[str] = [self.key_encoder(key) for key in keys]\n        values = self.store.mget(encoded_keys)\n        return [\n            self.value_deserializer(value) if value is not None else value\n            for value in values\n        ]\n[docs]    def mset(self, key_value_pairs: Sequence[Tuple[K, V]]) -> None:\n        \"\"\"Set the values for the given keys.\"\"\"\n        encoded_pairs = [\n            (self.key_encoder(key), self.value_serializer(value))\n            for key, value in key_value_pairs\n        ]\n        self.store.mset(encoded_pairs)\n[docs]    def mdelete(self, keys: Sequence[K]) -> None:\n        \"\"\"Delete the given keys and their associated values.\"\"\"\n        encoded_keys = [self.key_encoder(key) for key in keys]\n        self.store.mdelete(encoded_keys)\n[docs]    def yield_keys(\n        self, *, prefix: Optional[str] = None\n    ) -> Union[Iterator[K], Iterator[str]]:\n        \"\"\"Get an iterator over keys that match the given prefix.\"\"\"\n        # For the time being this does not return K, but str\n        # it's for debugging purposes. Should fix this.\n        yield from self.store.yield_keys(prefix=prefix)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/encoder_backed.html"}
{"id": "a1985bb1201d-0", "text": "Source code for langchain.storage.file_system\nimport re\nfrom pathlib import Path\nfrom typing import Iterator, List, Optional, Sequence, Tuple, Union\nfrom langchain.schema import BaseStore\nfrom langchain.storage.exceptions import InvalidKeyException\n[docs]class LocalFileStore(BaseStore[str, bytes]):\n    \"\"\"BaseStore interface that works on the local file system.\n    Examples:\n        Create a LocalFileStore instance and perform operations on it:\n        .. code-block:: python\n            from langchain.storage import LocalFileStore\n            # Instantiate the LocalFileStore with the root path\n            file_store = LocalFileStore(\"/path/to/root\")\n            # Set values for keys\n            file_store.mset([(\"key1\", b\"value1\"), (\"key2\", b\"value2\")])\n            # Get values for keys\n            values = file_store.mget([\"key1\", \"key2\"])  # Returns [b\"value1\", b\"value2\"]\n            # Delete keys\n            file_store.mdelete([\"key1\"])\n            # Iterate over keys\n            for key in file_store.yield_keys():\n                print(key)\n    \"\"\"\n[docs]    def __init__(self, root_path: Union[str, Path]) -> None:\n        \"\"\"Implement the BaseStore interface for the local file system.\n        Args:\n            root_path (Union[str, Path]): The root path of the file store. All keys are\n                interpreted as paths relative to this root.\n        \"\"\"\n        self.root_path = Path(root_path)\n    def _get_full_path(self, key: str) -> Path:\n        \"\"\"Get the full path for a given key relative to the root path.\n        Args:\n            key (str): The key relative to the root path.\n        Returns:\n            Path: The full path for the given key.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/file_system.html"}
{"id": "a1985bb1201d-1", "text": "Returns:\n            Path: The full path for the given key.\n        \"\"\"\n        if not re.match(r\"^[a-zA-Z0-9_.\\-/]+$\", key):\n            raise InvalidKeyException(f\"Invalid characters in key: {key}\")\n        return self.root_path / key\n[docs]    def mget(self, keys: Sequence[str]) -> List[Optional[bytes]]:\n        \"\"\"Get the values associated with the given keys.\n        Args:\n            keys: A sequence of keys.\n        Returns:\n            A sequence of optional values associated with the keys.\n            If a key is not found, the corresponding value will be None.\n        \"\"\"\n        values: List[Optional[bytes]] = []\n        for key in keys:\n            full_path = self._get_full_path(key)\n            if full_path.exists():\n                value = full_path.read_bytes()\n                values.append(value)\n            else:\n                values.append(None)\n        return values\n[docs]    def mset(self, key_value_pairs: Sequence[Tuple[str, bytes]]) -> None:\n        \"\"\"Set the values for the given keys.\n        Args:\n            key_value_pairs: A sequence of key-value pairs.\n        Returns:\n            None\n        \"\"\"\n        for key, value in key_value_pairs:\n            full_path = self._get_full_path(key)\n            full_path.parent.mkdir(parents=True, exist_ok=True)\n            full_path.write_bytes(value)\n[docs]    def mdelete(self, keys: Sequence[str]) -> None:\n        \"\"\"Delete the given keys and their associated values.\n        Args:\n            keys (Sequence[str]): A sequence of keys to delete.\n        Returns:\n            None\n        \"\"\"\n        for key in keys:\n            full_path = self._get_full_path(key)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/file_system.html"}
{"id": "a1985bb1201d-2", "text": "for key in keys:\n            full_path = self._get_full_path(key)\n            if full_path.exists():\n                full_path.unlink()\n[docs]    def yield_keys(self, prefix: Optional[str] = None) -> Iterator[str]:\n        \"\"\"Get an iterator over keys that match the given prefix.\n        Args:\n            prefix (Optional[str]): The prefix to match.\n        Returns:\n            Iterator[str]: An iterator over keys that match the given prefix.\n        \"\"\"\n        prefix_path = self._get_full_path(prefix) if prefix else self.root_path\n        for file in prefix_path.rglob(\"*\"):\n            if file.is_file():\n                relative_path = file.relative_to(self.root_path)\n                yield str(relative_path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/file_system.html"}
{"id": "40fb6623156b-0", "text": "Source code for langchain.storage.in_memory\n\"\"\"In memory store that is not thread safe and has no eviction policy.\nThis is a simple implementation of the BaseStore using a dictionary that is useful\nprimarily for unit testing purposes.\n\"\"\"\nfrom typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple\nfrom langchain.schema import BaseStore\n[docs]class InMemoryStore(BaseStore[str, Any]):\n    \"\"\"In-memory implementation of the BaseStore using a dictionary.\n    Attributes:\n        store (Dict[str, Any]): The underlying dictionary that stores\n            the key-value pairs.\n    Examples:\n        .. code-block:: python\n            from langchain.storage import InMemoryStore\n            store = InMemoryStore()\n            store.mset([('key1', 'value1'), ('key2', 'value2')])\n            store.mget(['key1', 'key2'])\n            # ['value1', 'value2']\n            store.mdelete(['key1'])\n            list(store.yield_keys())\n            # ['key2']\n            list(store.yield_keys(prefix='k'))\n            # ['key2']\n    \"\"\"\n[docs]    def __init__(self) -> None:\n        \"\"\"Initialize an empty store.\"\"\"\n        self.store: Dict[str, Any] = {}\n[docs]    def mget(self, keys: Sequence[str]) -> List[Optional[Any]]:\n        \"\"\"Get the values associated with the given keys.\n        Args:\n            keys (Sequence[str]): A sequence of keys.\n        Returns:\n            A sequence of optional values associated with the keys.\n            If a key is not found, the corresponding value will be None.\n        \"\"\"\n        return [self.store.get(key) for key in keys]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/in_memory.html"}
{"id": "40fb6623156b-1", "text": "\"\"\"\n        return [self.store.get(key) for key in keys]\n[docs]    def mset(self, key_value_pairs: Sequence[Tuple[str, Any]]) -> None:\n        \"\"\"Set the values for the given keys.\n        Args:\n            key_value_pairs (Sequence[Tuple[str, V]]): A sequence of key-value pairs.\n        Returns:\n            None\n        \"\"\"\n        for key, value in key_value_pairs:\n            self.store[key] = value\n[docs]    def mdelete(self, keys: Sequence[str]) -> None:\n        \"\"\"Delete the given keys and their associated values.\n        Args:\n            keys (Sequence[str]): A sequence of keys to delete.\n        \"\"\"\n        for key in keys:\n            self.store.pop(key, None)\n[docs]    def yield_keys(self, prefix: Optional[str] = None) -> Iterator[str]:\n        \"\"\"Get an iterator over keys that match the given prefix.\n        Args:\n            prefix (str, optional): The prefix to match. Defaults to None.\n        Returns:\n            Iterator[str]: An iterator over keys that match the given prefix.\n        \"\"\"\n        if prefix is None:\n            yield from self.store.keys()\n        else:\n            for key in self.store.keys():\n                if key.startswith(prefix):\n                    yield key", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/storage/in_memory.html"}
{"id": "5b1160badd35-0", "text": "Source code for langchain.chat_models.everlyai\n\"\"\"EverlyAI Endpoints chat wrapper. Relies heavily on ChatOpenAI.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport sys\nfrom typing import TYPE_CHECKING, Dict, Optional, Set\nfrom langchain.adapters.openai import convert_message_to_dict\nfrom langchain.chat_models.openai import (\n    ChatOpenAI,\n    _import_tiktoken,\n)\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema.messages import BaseMessage\nfrom langchain.utils import get_from_dict_or_env\nif TYPE_CHECKING:\n    import tiktoken\nlogger = logging.getLogger(__name__)\nDEFAULT_API_BASE = \"https://everlyai.xyz/hosted\"\nDEFAULT_MODEL = \"meta-llama/Llama-2-7b-chat-hf\"\n[docs]class ChatEverlyAI(ChatOpenAI):\n    \"\"\"`EverlyAI` Chat large language models.\n    To use, you should have the ``openai`` python package installed, and the\n    environment variable ``EVERLYAI_API_KEY`` set with your API key.\n    Alternatively, you can use the everlyai_api_key keyword argument.\n    Any parameters that are valid to be passed to the `openai.create` call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import ChatEverlyAI\n            chat = ChatEverlyAI(model_name=\"meta-llama/Llama-2-7b-chat-hf\")\n    \"\"\"\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat model.\"\"\"\n        return \"everlyai-chat\"\n    @property\n    def lc_secrets(self) -> Dict[str, str]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/everlyai.html"}
{"id": "5b1160badd35-1", "text": "@property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"everlyai_api_key\": \"EVERLYAI_API_KEY\"}\n    everlyai_api_key: Optional[str] = None\n    \"\"\"EverlyAI Endpoints API keys.\"\"\"\n    model_name: str = Field(default=DEFAULT_MODEL, alias=\"model\")\n    \"\"\"Model name to use.\"\"\"\n    everlyai_api_base: str = DEFAULT_API_BASE\n    \"\"\"Base URL path for API requests.\"\"\"\n    available_models: Optional[Set[str]] = None\n    \"\"\"Available models from EverlyAI API.\"\"\"\n[docs]    @staticmethod\n    def get_available_models() -> Set[str]:\n        \"\"\"Get available models from EverlyAI API.\"\"\"\n        # EverlyAI doesn't yet support dynamically query for available models.\n        return set(\n            [\n                \"meta-llama/Llama-2-7b-chat-hf\",\n                \"meta-llama/Llama-2-13b-chat-hf-quantized\",\n            ]\n        )\n    @root_validator(pre=True)\n    def validate_environment_override(cls, values: dict) -> dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"openai_api_key\"] = get_from_dict_or_env(\n            values,\n            \"everlyai_api_key\",\n            \"EVERLYAI_API_KEY\",\n        )\n        values[\"openai_api_base\"] = DEFAULT_API_BASE\n        try:\n            import openai\n        except ImportError as e:\n            raise ValueError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\",\n            ) from e\n        try:\n            values[\"client\"] = openai.ChatCompletion\n        except AttributeError as exc:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/everlyai.html"}
{"id": "5b1160badd35-2", "text": "except AttributeError as exc:\n            raise ValueError(\n                \"`openai` has no `ChatCompletion` attribute, this is likely \"\n                \"due to an old version of the openai package. Try upgrading it \"\n                \"with `pip install --upgrade openai`.\",\n            ) from exc\n        if \"model_name\" not in values.keys():\n            values[\"model_name\"] = DEFAULT_MODEL\n        model_name = values[\"model_name\"]\n        available_models = cls.get_available_models()\n        if model_name not in available_models:\n            raise ValueError(\n                f\"Model name {model_name} not found in available models: \"\n                f\"{available_models}.\",\n            )\n        values[\"available_models\"] = available_models\n        return values\n    def _get_encoding_model(self) -> tuple[str, tiktoken.Encoding]:\n        tiktoken_ = _import_tiktoken()\n        if self.tiktoken_model_name is not None:\n            model = self.tiktoken_model_name\n        else:\n            model = self.model_name\n        # Returns the number of tokens used by a list of messages.\n        try:\n            encoding = tiktoken_.encoding_for_model(\"gpt-3.5-turbo-0301\")\n        except KeyError:\n            logger.warning(\"Warning: model not found. Using cl100k_base encoding.\")\n            model = \"cl100k_base\"\n            encoding = tiktoken_.get_encoding(model)\n        return model, encoding\n[docs]    def get_num_tokens_from_messages(self, messages: list[BaseMessage]) -> int:\n        \"\"\"Calculate num tokens with tiktoken package.\n        Official documentation: https://github.com/openai/openai-cookbook/blob/\n        main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/everlyai.html"}
{"id": "5b1160badd35-3", "text": "main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb\"\"\"\n        if sys.version_info[1] <= 7:\n            return super().get_num_tokens_from_messages(messages)\n        model, encoding = self._get_encoding_model()\n        tokens_per_message = 3\n        tokens_per_name = 1\n        num_tokens = 0\n        messages_dict = [convert_message_to_dict(m) for m in messages]\n        for message in messages_dict:\n            num_tokens += tokens_per_message\n            for key, value in message.items():\n                # Cast str(value) in case the message value is not a string\n                # This occurs with function messages\n                num_tokens += len(encoding.encode(str(value)))\n                if key == \"name\":\n                    num_tokens += tokens_per_name\n        # every reply is primed with <im_start>assistant\n        num_tokens += 3\n        return num_tokens", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/everlyai.html"}
{"id": "76106380b621-0", "text": "Source code for langchain.chat_models.azureml_endpoint\nimport json\nfrom typing import Any, Dict, List, Optional, cast\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.chat_models.base import SimpleChatModel\nfrom langchain.llms.azureml_endpoint import AzureMLEndpointClient, ContentFormatterBase\nfrom langchain.pydantic_v1 import SecretStr, validator\nfrom langchain.schema.messages import (\n    AIMessage,\n    BaseMessage,\n    ChatMessage,\n    HumanMessage,\n    SystemMessage,\n)\nfrom langchain.utils import convert_to_secret_str, get_from_dict_or_env\n[docs]class LlamaContentFormatter(ContentFormatterBase):\n    \"\"\"Content formatter for `LLaMA`.\"\"\"\n    SUPPORTED_ROLES: List[str] = [\"user\", \"assistant\", \"system\"]\n    @staticmethod\n    def _convert_message_to_dict(message: BaseMessage) -> Dict:\n        \"\"\"Converts message to a dict according to role\"\"\"\n        content = cast(str, message.content)\n        if isinstance(message, HumanMessage):\n            return {\n                \"role\": \"user\",\n                \"content\": ContentFormatterBase.escape_special_characters(content),\n            }\n        elif isinstance(message, AIMessage):\n            return {\n                \"role\": \"assistant\",\n                \"content\": ContentFormatterBase.escape_special_characters(content),\n            }\n        elif isinstance(message, SystemMessage):\n            return {\n                \"role\": \"system\",\n                \"content\": ContentFormatterBase.escape_special_characters(content),\n            }\n        elif (\n            isinstance(message, ChatMessage)\n            and message.role in LlamaContentFormatter.SUPPORTED_ROLES\n        ):\n            return {\n                \"role\": message.role,\n                \"content\": ContentFormatterBase.escape_special_characters(content),\n            }\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html"}
{"id": "76106380b621-1", "text": "\"content\": ContentFormatterBase.escape_special_characters(content),\n            }\n        else:\n            supported = \",\".join(\n                [role for role in LlamaContentFormatter.SUPPORTED_ROLES]\n            )\n            raise ValueError(\n                f\"\"\"Received unsupported role. \n                Supported roles for the LLaMa Foundation Model: {supported}\"\"\"\n            )\n    def _format_request_payload(\n        self, messages: List[BaseMessage], model_kwargs: Dict\n    ) -> bytes:\n        chat_messages = [\n            LlamaContentFormatter._convert_message_to_dict(message)\n            for message in messages\n        ]\n        prompt = json.dumps(\n            {\"input_data\": {\"input_string\": chat_messages, \"parameters\": model_kwargs}}\n        )\n        return self.format_request_payload(prompt=prompt, model_kwargs=model_kwargs)\n[docs]    def format_request_payload(self, prompt: str, model_kwargs: Dict) -> bytes:\n        \"\"\"Formats the request according to the chosen api\"\"\"\n        return str.encode(prompt)\n[docs]    def format_response_payload(self, output: bytes) -> str:\n        \"\"\"Formats response\"\"\"\n        return json.loads(output)[\"output\"]\n[docs]class AzureMLChatOnlineEndpoint(SimpleChatModel):\n    \"\"\"`AzureML` Chat models API.\n    Example:\n        .. code-block:: python\n            azure_chat = AzureMLChatOnlineEndpoint(\n                endpoint_url=\"https://<your-endpoint>.<your_region>.inference.ml.azure.com/score\",\n                endpoint_api_key=\"my-api-key\",\n                content_formatter=content_formatter,\n            )\n    \"\"\"\n    endpoint_url: str = \"\"\n    \"\"\"URL of pre-existing Endpoint. Should be passed to constructor or specified as \n        env var `AZUREML_ENDPOINT_URL`.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html"}
{"id": "76106380b621-2", "text": "env var `AZUREML_ENDPOINT_URL`.\"\"\"\n    endpoint_api_key: SecretStr = convert_to_secret_str(\"\")\n    \"\"\"Authentication Key for Endpoint. Should be passed to constructor or specified as\n        env var `AZUREML_ENDPOINT_API_KEY`.\"\"\"\n    http_client: Any = None  #: :meta private:\n    content_formatter: Any = None\n    \"\"\"The content formatter that provides an input and output\n    transform function to handle formats between the LLM and\n    the endpoint\"\"\"\n    model_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    @validator(\"http_client\", always=True, allow_reuse=True)\n    @classmethod\n    def validate_client(cls, field_value: Any, values: Dict) -> AzureMLEndpointClient:\n        \"\"\"Validate that api key and python package exist in environment.\"\"\"\n        values[\"endpoint_api_key\"] = convert_to_secret_str(\n            get_from_dict_or_env(values, \"endpoint_api_key\", \"AZUREML_ENDPOINT_API_KEY\")\n        )\n        endpoint_url = get_from_dict_or_env(\n            values, \"endpoint_url\", \"AZUREML_ENDPOINT_URL\"\n        )\n        http_client = AzureMLEndpointClient(\n            endpoint_url, values[\"endpoint_api_key\"].get_secret_value()\n        )\n        return http_client\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {\n            **{\"model_kwargs\": _model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"azureml_chat_endpoint\"\n    def _call(\n        self,\n        messages: List[BaseMessage],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html"}
{"id": "76106380b621-3", "text": "def _call(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to an AzureML Managed Online endpoint.\n        Args:\n            messages: The messages in the conversation with the chat model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = azureml_model(\"Tell me a joke.\")\n        \"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        request_payload = self.content_formatter._format_request_payload(\n            messages, _model_kwargs\n        )\n        response_payload = self.http_client.call(request_payload, **kwargs)\n        generated_text = self.content_formatter.format_response_payload(\n            response_payload\n        )\n        return generated_text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html"}
{"id": "19e0b60114ec-0", "text": "Source code for langchain.chat_models.minimax\n\"\"\"Wrapper around Minimax chat models.\"\"\"\nimport logging\nfrom typing import Any, Dict, List, Optional, cast\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.llms.minimax import MinimaxCommon\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.schema import (\n    AIMessage,\n    BaseMessage,\n    ChatResult,\n    HumanMessage,\n)\nlogger = logging.getLogger(__name__)\ndef _parse_message(msg_type: str, text: str) -> Dict:\n    return {\"sender_type\": msg_type, \"text\": text}\ndef _parse_chat_history(history: List[BaseMessage]) -> List:\n    \"\"\"Parse a sequence of messages into history.\"\"\"\n    chat_history = []\n    for message in history:\n        content = cast(str, message.content)\n        if isinstance(message, HumanMessage):\n            chat_history.append(_parse_message(\"USER\", content))\n        if isinstance(message, AIMessage):\n            chat_history.append(_parse_message(\"BOT\", content))\n    return chat_history\n[docs]class MiniMaxChat(MinimaxCommon, BaseChatModel):\n    \"\"\"Wrapper around Minimax large language models.\n    To use, you should have the environment variable ``MINIMAX_GROUP_ID`` and\n    ``MINIMAX_API_KEY`` set with your API token, or pass it as a named parameter to\n    the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import MiniMaxChat\n            llm = MiniMaxChat(model_name=\"abab5-chat\")\n    \"\"\"\n    def _generate(\n        self,\n        messages: List[BaseMessage],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/minimax.html"}
{"id": "19e0b60114ec-1", "text": "def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        \"\"\"Generate next turn in the conversation.\n        Args:\n            messages: The history of the conversation as a list of messages. Code chat\n                does not support context.\n            stop: The list of stop words (optional).\n            run_manager: The CallbackManager for LLM run, it's not used at the moment.\n        Returns:\n            The ChatResult that contains outputs generated by the model.\n        Raises:\n            ValueError: if the last message in the list is not from human.\n        \"\"\"\n        if not messages:\n            raise ValueError(\n                \"You should provide at least one message to start the chat!\"\n            )\n        history = _parse_chat_history(messages)\n        payload = self._default_params\n        payload[\"messages\"] = history\n        text = self._client.post(payload)\n        # This is required since the stop are not enforced by the model parameters\n        return text if stop is None else enforce_stop_tokens(text, stop)\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        raise NotImplementedError(\n            \"\"\"Minimax AI doesn't support async requests at the moment.\"\"\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/minimax.html"}
{"id": "55736f3a296b-0", "text": "Source code for langchain.chat_models.baichuan\nimport hashlib\nimport json\nimport logging\nimport time\nfrom typing import Any, Dict, Iterator, List, Mapping, Optional, Type\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.chat_models.base import BaseChatModel, _generate_from_stream\nfrom langchain.pydantic_v1 import Field, SecretStr, root_validator\nfrom langchain.schema import (\n    AIMessage,\n    BaseMessage,\n    ChatGeneration,\n    ChatMessage,\n    ChatResult,\n    HumanMessage,\n)\nfrom langchain.schema.messages import (\n    AIMessageChunk,\n    BaseMessageChunk,\n    ChatMessageChunk,\n    HumanMessageChunk,\n)\nfrom langchain.schema.output import ChatGenerationChunk\nfrom langchain.utils import (\n    convert_to_secret_str,\n    get_from_dict_or_env,\n    get_pydantic_field_names,\n)\nlogger = logging.getLogger(__name__)\nDEFAULT_API_BASE = \"https://api.baichuan-ai.com/v1\"\ndef _convert_message_to_dict(message: BaseMessage) -> dict:\n    message_dict: Dict[str, Any]\n    if isinstance(message, ChatMessage):\n        message_dict = {\"role\": message.role, \"content\": message.content}\n    elif isinstance(message, HumanMessage):\n        message_dict = {\"role\": \"user\", \"content\": message.content}\n    elif isinstance(message, AIMessage):\n        message_dict = {\"role\": \"assistant\", \"content\": message.content}\n    else:\n        raise TypeError(f\"Got unknown type {message}\")\n    return message_dict\ndef _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:\n    role = _dict[\"role\"]\n    if role == \"user\":", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html"}
{"id": "55736f3a296b-1", "text": "role = _dict[\"role\"]\n    if role == \"user\":\n        return HumanMessage(content=_dict[\"content\"])\n    elif role == \"assistant\":\n        return AIMessage(content=_dict.get(\"content\", \"\") or \"\")\n    else:\n        return ChatMessage(content=_dict[\"content\"], role=role)\ndef _convert_delta_to_message_chunk(\n    _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]\n) -> BaseMessageChunk:\n    role = _dict.get(\"role\")\n    content = _dict.get(\"content\") or \"\"\n    if role == \"user\" or default_class == HumanMessageChunk:\n        return HumanMessageChunk(content=content)\n    elif role == \"assistant\" or default_class == AIMessageChunk:\n        return AIMessageChunk(content=content)\n    elif role or default_class == ChatMessageChunk:\n        return ChatMessageChunk(content=content, role=role)\n    else:\n        return default_class(content=content)\n# signature generation\ndef _signature(secret_key: SecretStr, payload: Dict[str, Any], timestamp: int) -> str:\n    input_str = secret_key.get_secret_value() + json.dumps(payload) + str(timestamp)\n    md5 = hashlib.md5()\n    md5.update(input_str.encode(\"utf-8\"))\n    return md5.hexdigest()\n[docs]class ChatBaichuan(BaseChatModel):\n    \"\"\"Baichuan chat models API by Baichuan Intelligent Technology.\n    For more information, see https://platform.baichuan-ai.com/docs/api\n    \"\"\"\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\n            \"baichuan_api_key\": \"BAICHUAN_API_KEY\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html"}
{"id": "55736f3a296b-2", "text": "\"baichuan_api_key\": \"BAICHUAN_API_KEY\",\n            \"baichuan_secret_key\": \"BAICHUAN_SECRET_KEY\",\n        }\n    @property\n    def lc_serializable(self) -> bool:\n        return True\n    baichuan_api_base: str = Field(default=DEFAULT_API_BASE)\n    \"\"\"Baichuan custom endpoints\"\"\"\n    baichuan_api_key: Optional[str] = None\n    \"\"\"Baichuan API Key\"\"\"\n    baichuan_secret_key: Optional[SecretStr] = None\n    \"\"\"Baichuan Secret Key\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results or not.\"\"\"\n    request_timeout: int = 60\n    \"\"\"request timeout for chat http requests\"\"\"\n    model = \"Baichuan2-53B\"\n    \"\"\"model name of Baichuan, default is `Baichuan2-53B`.\"\"\"\n    temperature: float = 0.3\n    \"\"\"What sampling temperature to use.\"\"\"\n    top_k: int = 5\n    \"\"\"What search sampling control to use.\"\"\"\n    top_p: float = 0.85\n    \"\"\"What probability mass to use.\"\"\"\n    with_search_enhance: bool = False\n    \"\"\"Whether to use search enhance, default is False.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for API call not explicitly specified.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        allow_population_by_field_name = True\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = get_pydantic_field_names(cls)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html"}
{"id": "55736f3a296b-3", "text": "all_required_field_names = get_pydantic_field_names(cls)\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name in extra:\n                raise ValueError(f\"Found {field_name} supplied twice.\")\n            if field_name not in all_required_field_names:\n                logger.warning(\n                    f\"\"\"WARNING! {field_name} is not default parameter.\n                    {field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        invalid_model_kwargs = all_required_field_names.intersection(extra.keys())\n        if invalid_model_kwargs:\n            raise ValueError(\n                f\"Parameters {invalid_model_kwargs} should be specified explicitly. \"\n                f\"Instead they were passed in as part of `model_kwargs` parameter.\"\n            )\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        values[\"baichuan_api_base\"] = get_from_dict_or_env(\n            values,\n            \"baichuan_api_base\",\n            \"BAICHUAN_API_BASE\",\n            DEFAULT_API_BASE,\n        )\n        values[\"baichuan_api_key\"] = get_from_dict_or_env(\n            values,\n            \"baichuan_api_key\",\n            \"BAICHUAN_API_KEY\",\n        )\n        values[\"baichuan_secret_key\"] = convert_to_secret_str(\n            get_from_dict_or_env(\n                values,\n                \"baichuan_secret_key\",\n                \"BAICHUAN_SECRET_KEY\",\n            )\n        )\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html"}
{"id": "55736f3a296b-4", "text": "@property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Baichuan API.\"\"\"\n        normal_params = {\n            \"model\": self.model,\n            \"temperature\": self.temperature,\n            \"top_p\": self.top_p,\n            \"top_k\": self.top_k,\n            \"with_search_enhance\": self.with_search_enhance,\n        }\n        return {**normal_params, **self.model_kwargs}\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        if self.streaming:\n            stream_iter = self._stream(\n                messages=messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return _generate_from_stream(stream_iter)\n        res = self._chat(messages, **kwargs)\n        response = res.json()\n        if response.get(\"code\") != 0:\n            raise ValueError(f\"Error from Baichuan api response: {response}\")\n        return self._create_chat_result(response)\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        res = self._chat(messages, **kwargs)\n        default_chunk_class = AIMessageChunk\n        for chunk in res.iter_lines():\n            response = json.loads(chunk)\n            if response.get(\"code\") != 0:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html"}
{"id": "55736f3a296b-5", "text": "response = json.loads(chunk)\n            if response.get(\"code\") != 0:\n                raise ValueError(f\"Error from Baichuan api response: {response}\")\n            data = response.get(\"data\")\n            for m in data.get(\"messages\"):\n                chunk = _convert_delta_to_message_chunk(m, default_chunk_class)\n                default_chunk_class = chunk.__class__\n                yield ChatGenerationChunk(message=chunk)\n                if run_manager:\n                    run_manager.on_llm_new_token(chunk.content)\n    def _chat(self, messages: List[BaseMessage], **kwargs: Any) -> requests.Response:\n        if self.baichuan_secret_key is None:\n            raise ValueError(\"Baichuan secret key is not set.\")\n        parameters = {**self._default_params, **kwargs}\n        model = parameters.pop(\"model\")\n        headers = parameters.pop(\"headers\", {})\n        payload = {\n            \"model\": model,\n            \"messages\": [_convert_message_to_dict(m) for m in messages],\n            \"parameters\": parameters,\n        }\n        timestamp = int(time.time())\n        url = self.baichuan_api_base\n        if self.streaming:\n            url = f\"{url}/stream\"\n        url = f\"{url}/chat\"\n        res = requests.post(\n            url=url,\n            timeout=self.request_timeout,\n            headers={\n                \"Content-Type\": \"application/json\",\n                \"Authorization\": f\"Bearer {self.baichuan_api_key}\",\n                \"X-BC-Timestamp\": str(timestamp),\n                \"X-BC-Signature\": _signature(\n                    secret_key=self.baichuan_secret_key,\n                    payload=payload,\n                    timestamp=timestamp,\n                ),\n                \"X-BC-Sign-Algo\": \"MD5\",\n                **headers,\n            },", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html"}
{"id": "55736f3a296b-6", "text": "**headers,\n            },\n            json=payload,\n            stream=self.streaming,\n        )\n        return res\n    def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:\n        generations = []\n        for m in response[\"data\"][\"messages\"]:\n            message = _convert_dict_to_message(m)\n            gen = ChatGeneration(message=message)\n            generations.append(gen)\n        token_usage = response[\"usage\"]\n        llm_output = {\"token_usage\": token_usage, \"model\": self.model}\n        return ChatResult(generations=generations, llm_output=llm_output)\n    @property\n    def _llm_type(self) -> str:\n        return \"baichuan-chat\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html"}
{"id": "194e5c6709ca-0", "text": "Source code for langchain.chat_models.yandex\n\"\"\"Wrapper around YandexGPT chat models.\"\"\"\nimport logging\nfrom typing import Any, Dict, List, Optional, Tuple, cast\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.llms.yandex import _BaseYandexGPT\nfrom langchain.schema import (\n    AIMessage,\n    BaseMessage,\n    ChatGeneration,\n    ChatResult,\n    HumanMessage,\n    SystemMessage,\n)\nlogger = logging.getLogger(__name__)\ndef _parse_message(role: str, text: str) -> Dict:\n    return {\"role\": role, \"text\": text}\ndef _parse_chat_history(history: List[BaseMessage]) -> Tuple[List[Dict[str, str]], str]:\n    \"\"\"Parse a sequence of messages into history.\n    Returns:\n        A tuple of a list of parsed messages and an instruction message for the model.\n    \"\"\"\n    chat_history = []\n    instruction = \"\"\n    for message in history:\n        content = cast(str, message.content)\n        if isinstance(message, HumanMessage):\n            chat_history.append(_parse_message(\"user\", content))\n        if isinstance(message, AIMessage):\n            chat_history.append(_parse_message(\"assistant\", content))\n        if isinstance(message, SystemMessage):\n            instruction = content\n    return chat_history, instruction\n[docs]class ChatYandexGPT(_BaseYandexGPT, BaseChatModel):\n    \"\"\"Wrapper around YandexGPT large language models.\n    There are two authentication options for the service account\n    with the ``ai.languageModels.user`` role:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/yandex.html"}
{"id": "194e5c6709ca-1", "text": "with the ``ai.languageModels.user`` role:\n        - You can specify the token in a constructor parameter `iam_token`\n        or in an environment variable `YC_IAM_TOKEN`.\n        - You can specify the key in a constructor parameter `api_key`\n        or in an environment variable `YC_API_KEY`.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import ChatYandexGPT\n            chat_model = ChatYandexGPT(iam_token=\"t1.9eu...\")\n    \"\"\"\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        \"\"\"Generate next turn in the conversation.\n        Args:\n            messages: The history of the conversation as a list of messages.\n            stop: The list of stop words (optional).\n            run_manager: The CallbackManager for LLM run, it's not used at the moment.\n        Returns:\n            The ChatResult that contains outputs generated by the model.\n        Raises:\n            ValueError: if the last message in the list is not from human.\n        \"\"\"\n        try:\n            import grpc\n            from google.protobuf.wrappers_pb2 import DoubleValue, Int64Value\n            from yandex.cloud.ai.llm.v1alpha.llm_pb2 import GenerationOptions, Message\n            from yandex.cloud.ai.llm.v1alpha.llm_service_pb2 import ChatRequest\n            from yandex.cloud.ai.llm.v1alpha.llm_service_pb2_grpc import (\n                TextGenerationServiceStub,\n            )\n        except ImportError as e:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/yandex.html"}
{"id": "194e5c6709ca-2", "text": ")\n        except ImportError as e:\n            raise ImportError(\n                \"Please install YandexCloud SDK\" \" with `pip install yandexcloud`.\"\n            ) from e\n        if not messages:\n            raise ValueError(\n                \"You should provide at least one message to start the chat!\"\n            )\n        message_history, instruction = _parse_chat_history(messages)\n        channel_credentials = grpc.ssl_channel_credentials()\n        channel = grpc.secure_channel(self.url, channel_credentials)\n        request = ChatRequest(\n            model=self.model_name,\n            generation_options=GenerationOptions(\n                temperature=DoubleValue(value=self.temperature),\n                max_tokens=Int64Value(value=self.max_tokens),\n            ),\n            instruction_text=instruction,\n            messages=[Message(**message) for message in message_history],\n        )\n        stub = TextGenerationServiceStub(channel)\n        if self.iam_token:\n            metadata = ((\"authorization\", f\"Bearer {self.iam_token}\"),)\n        else:\n            metadata = ((\"authorization\", f\"Api-Key {self.api_key}\"),)\n        res = stub.Chat(request, metadata=metadata)\n        text = list(res)[0].message.text\n        text = text if stop is None else enforce_stop_tokens(text, stop)\n        message = AIMessage(content=text)\n        return ChatResult(generations=[ChatGeneration(message=message)])\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        raise NotImplementedError(\n            \"\"\"YandexGPT doesn't support async requests at the moment.\"\"\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/yandex.html"}
{"id": "c0c3b21491f4-0", "text": "Source code for langchain.chat_models.jinachat\n\"\"\"JinaChat wrapper.\"\"\"\nfrom __future__ import annotations\nimport logging\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Callable,\n    Dict,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Tuple,\n    Type,\n    Union,\n)\nfrom tenacity import (\n    before_sleep_log,\n    retry,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import (\n    BaseChatModel,\n    _agenerate_from_stream,\n    _generate_from_stream,\n)\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema import (\n    AIMessage,\n    BaseMessage,\n    ChatGeneration,\n    ChatMessage,\n    ChatResult,\n    FunctionMessage,\n    HumanMessage,\n    SystemMessage,\n)\nfrom langchain.schema.messages import (\n    AIMessageChunk,\n    BaseMessageChunk,\n    ChatMessageChunk,\n    HumanMessageChunk,\n    SystemMessageChunk,\n)\nfrom langchain.schema.output import ChatGenerationChunk\nfrom langchain.utils import get_from_dict_or_env, get_pydantic_field_names\nlogger = logging.getLogger(__name__)\ndef _create_retry_decorator(llm: JinaChat) -> Callable[[Any], Any]:\n    import openai\n    min_seconds = 1\n    max_seconds = 60\n    # Wait 2^x * 1 second between each retry starting with\n    # 4 seconds, then up to 10 seconds, then 10 seconds afterwards\n    return retry(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html"}
{"id": "c0c3b21491f4-1", "text": "return retry(\n        reraise=True,\n        stop=stop_after_attempt(llm.max_retries),\n        wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),\n        retry=(\n            retry_if_exception_type(openai.error.Timeout)\n            | retry_if_exception_type(openai.error.APIError)\n            | retry_if_exception_type(openai.error.APIConnectionError)\n            | retry_if_exception_type(openai.error.RateLimitError)\n            | retry_if_exception_type(openai.error.ServiceUnavailableError)\n        ),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\n[docs]async def acompletion_with_retry(llm: JinaChat, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the async completion call.\"\"\"\n    retry_decorator = _create_retry_decorator(llm)\n    @retry_decorator\n    async def _completion_with_retry(**kwargs: Any) -> Any:\n        # Use OpenAI's async api https://github.com/openai/openai-python#async-api\n        return await llm.client.acreate(**kwargs)\n    return await _completion_with_retry(**kwargs)\ndef _convert_delta_to_message_chunk(\n    _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]\n) -> BaseMessageChunk:\n    role = _dict.get(\"role\")\n    content = _dict.get(\"content\") or \"\"\n    if role == \"user\" or default_class == HumanMessageChunk:\n        return HumanMessageChunk(content=content)\n    elif role == \"assistant\" or default_class == AIMessageChunk:\n        return AIMessageChunk(content=content)\n    elif role == \"system\" or default_class == SystemMessageChunk:\n        return SystemMessageChunk(content=content)\n    elif role or default_class == ChatMessageChunk:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html"}
{"id": "c0c3b21491f4-2", "text": "elif role or default_class == ChatMessageChunk:\n        return ChatMessageChunk(content=content, role=role)\n    else:\n        return default_class(content=content)\ndef _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:\n    role = _dict[\"role\"]\n    if role == \"user\":\n        return HumanMessage(content=_dict[\"content\"])\n    elif role == \"assistant\":\n        content = _dict[\"content\"] or \"\"\n        return AIMessage(content=content)\n    elif role == \"system\":\n        return SystemMessage(content=_dict[\"content\"])\n    else:\n        return ChatMessage(content=_dict[\"content\"], role=role)\ndef _convert_message_to_dict(message: BaseMessage) -> dict:\n    if isinstance(message, ChatMessage):\n        message_dict = {\"role\": message.role, \"content\": message.content}\n    elif isinstance(message, HumanMessage):\n        message_dict = {\"role\": \"user\", \"content\": message.content}\n    elif isinstance(message, AIMessage):\n        message_dict = {\"role\": \"assistant\", \"content\": message.content}\n    elif isinstance(message, SystemMessage):\n        message_dict = {\"role\": \"system\", \"content\": message.content}\n    elif isinstance(message, FunctionMessage):\n        message_dict = {\n            \"role\": \"function\",\n            \"name\": message.name,\n            \"content\": message.content,\n        }\n    else:\n        raise ValueError(f\"Got unknown type {message}\")\n    if \"name\" in message.additional_kwargs:\n        message_dict[\"name\"] = message.additional_kwargs[\"name\"]\n    return message_dict\n[docs]class JinaChat(BaseChatModel):\n    \"\"\"`Jina AI` Chat models API.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html"}
{"id": "c0c3b21491f4-3", "text": "\"\"\"`Jina AI` Chat models API.\n    To use, you should have the ``openai`` python package installed, and the\n    environment variable ``JINACHAT_API_KEY`` set to your API key, which you\n    can generate at https://chat.jina.ai/api.\n    Any parameters that are valid to be passed to the openai.create call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import JinaChat\n            chat = JinaChat()\n    \"\"\"\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"jinachat_api_key\": \"JINACHAT_API_KEY\"}\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this model can be serialized by Langchain.\"\"\"\n        return True\n    client: Any  #: :meta private:\n    temperature: float = 0.7\n    \"\"\"What sampling temperature to use.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not explicitly specified.\"\"\"\n    jinachat_api_key: Optional[str] = None\n    \"\"\"Base URL path for API requests, \n    leave blank if not using a proxy or service emulator.\"\"\"\n    request_timeout: Optional[Union[float, Tuple[float, float]]] = None\n    \"\"\"Timeout for requests to JinaChat completion API. Default is 600 seconds.\"\"\"\n    max_retries: int = 6\n    \"\"\"Maximum number of retries to make when generating.\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results or not.\"\"\"\n    max_tokens: Optional[int] = None\n    \"\"\"Maximum number of tokens to generate.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html"}
{"id": "c0c3b21491f4-4", "text": "max_tokens: Optional[int] = None\n    \"\"\"Maximum number of tokens to generate.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        allow_population_by_field_name = True\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = get_pydantic_field_names(cls)\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name in extra:\n                raise ValueError(f\"Found {field_name} supplied twice.\")\n            if field_name not in all_required_field_names:\n                logger.warning(\n                    f\"\"\"WARNING! {field_name} is not default parameter.\n                    {field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        invalid_model_kwargs = all_required_field_names.intersection(extra.keys())\n        if invalid_model_kwargs:\n            raise ValueError(\n                f\"Parameters {invalid_model_kwargs} should be specified explicitly. \"\n                f\"Instead they were passed in as part of `model_kwargs` parameter.\"\n            )\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"jinachat_api_key\"] = get_from_dict_or_env(\n            values, \"jinachat_api_key\", \"JINACHAT_API_KEY\"\n        )\n        try:\n            import openai\n        except ImportError:\n            raise ValueError(\n                \"Could not import openai python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html"}
{"id": "c0c3b21491f4-5", "text": "raise ValueError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\"\n            )\n        try:\n            values[\"client\"] = openai.ChatCompletion\n        except AttributeError:\n            raise ValueError(\n                \"`openai` has no `ChatCompletion` attribute, this is likely \"\n                \"due to an old version of the openai package. Try upgrading it \"\n                \"with `pip install --upgrade openai`.\"\n            )\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling JinaChat API.\"\"\"\n        return {\n            \"request_timeout\": self.request_timeout,\n            \"max_tokens\": self.max_tokens,\n            \"stream\": self.streaming,\n            \"temperature\": self.temperature,\n            **self.model_kwargs,\n        }\n    def _create_retry_decorator(self) -> Callable[[Any], Any]:\n        import openai\n        min_seconds = 1\n        max_seconds = 60\n        # Wait 2^x * 1 second between each retry starting with\n        # 4 seconds, then up to 10 seconds, then 10 seconds afterwards\n        return retry(\n            reraise=True,\n            stop=stop_after_attempt(self.max_retries),\n            wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),\n            retry=(\n                retry_if_exception_type(openai.error.Timeout)\n                | retry_if_exception_type(openai.error.APIError)\n                | retry_if_exception_type(openai.error.APIConnectionError)\n                | retry_if_exception_type(openai.error.RateLimitError)\n                | retry_if_exception_type(openai.error.ServiceUnavailableError)\n            ),\n            before_sleep=before_sleep_log(logger, logging.WARNING),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html"}
{"id": "c0c3b21491f4-6", "text": "),\n            before_sleep=before_sleep_log(logger, logging.WARNING),\n        )\n[docs]    def completion_with_retry(self, **kwargs: Any) -> Any:\n        \"\"\"Use tenacity to retry the completion call.\"\"\"\n        retry_decorator = self._create_retry_decorator()\n        @retry_decorator\n        def _completion_with_retry(**kwargs: Any) -> Any:\n            return self.client.create(**kwargs)\n        return _completion_with_retry(**kwargs)\n    def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:\n        overall_token_usage: dict = {}\n        for output in llm_outputs:\n            if output is None:\n                # Happens in streaming\n                continue\n            token_usage = output[\"token_usage\"]\n            for k, v in token_usage.items():\n                if k in overall_token_usage:\n                    overall_token_usage[k] += v\n                else:\n                    overall_token_usage[k] = v\n        return {\"token_usage\": overall_token_usage}\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs, \"stream\": True}\n        default_chunk_class = AIMessageChunk\n        for chunk in self.completion_with_retry(messages=message_dicts, **params):\n            delta = chunk[\"choices\"][0][\"delta\"]\n            chunk = _convert_delta_to_message_chunk(delta, default_chunk_class)\n            default_chunk_class = chunk.__class__\n            yield ChatGenerationChunk(message=chunk)\n            if run_manager:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html"}
{"id": "c0c3b21491f4-7", "text": "yield ChatGenerationChunk(message=chunk)\n            if run_manager:\n                run_manager.on_llm_new_token(chunk.content)\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        if self.streaming:\n            stream_iter = self._stream(\n                messages=messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return _generate_from_stream(stream_iter)\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs}\n        response = self.completion_with_retry(messages=message_dicts, **params)\n        return self._create_chat_result(response)\n    def _create_message_dicts(\n        self, messages: List[BaseMessage], stop: Optional[List[str]]\n    ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:\n        params = dict(self._invocation_params)\n        if stop is not None:\n            if \"stop\" in params:\n                raise ValueError(\"`stop` found in both the input and default params.\")\n            params[\"stop\"] = stop\n        message_dicts = [_convert_message_to_dict(m) for m in messages]\n        return message_dicts, params\n    def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:\n        generations = []\n        for res in response[\"choices\"]:\n            message = _convert_dict_to_message(res[\"message\"])\n            gen = ChatGeneration(message=message)\n            generations.append(gen)\n        llm_output = {\"token_usage\": response[\"usage\"]}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html"}
{"id": "c0c3b21491f4-8", "text": "generations.append(gen)\n        llm_output = {\"token_usage\": response[\"usage\"]}\n        return ChatResult(generations=generations, llm_output=llm_output)\n    async def _astream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[ChatGenerationChunk]:\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs, \"stream\": True}\n        default_chunk_class = AIMessageChunk\n        async for chunk in await acompletion_with_retry(\n            self, messages=message_dicts, **params\n        ):\n            delta = chunk[\"choices\"][0][\"delta\"]\n            chunk = _convert_delta_to_message_chunk(delta, default_chunk_class)\n            default_chunk_class = chunk.__class__\n            yield ChatGenerationChunk(message=chunk)\n            if run_manager:\n                await run_manager.on_llm_new_token(chunk.content)\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        if self.streaming:\n            stream_iter = self._astream(\n                messages=messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return await _agenerate_from_stream(stream_iter)\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs}\n        response = await acompletion_with_retry(self, messages=message_dicts, **params)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html"}
{"id": "c0c3b21491f4-9", "text": "response = await acompletion_with_retry(self, messages=message_dicts, **params)\n        return self._create_chat_result(response)\n    @property\n    def _invocation_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the parameters used to invoke the model.\"\"\"\n        jinachat_creds: Dict[str, Any] = {\n            \"api_key\": self.jinachat_api_key,\n            \"api_base\": \"https://api.chat.jina.ai/v1\",\n            \"model\": \"jinachat\",\n        }\n        return {**jinachat_creds, **self._default_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat model.\"\"\"\n        return \"jinachat\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html"}
{"id": "7cb368411ffd-0", "text": "Source code for langchain.chat_models.azure_openai\n\"\"\"Azure OpenAI chat wrapper.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport os\nimport warnings\nfrom typing import Any, Dict, Union\nfrom langchain.chat_models.openai import ChatOpenAI\nfrom langchain.pydantic_v1 import BaseModel, Field, root_validator\nfrom langchain.schema import ChatResult\nfrom langchain.utils import get_from_dict_or_env\nfrom langchain.utils.openai import is_openai_v1\nlogger = logging.getLogger(__name__)\n[docs]class AzureChatOpenAI(ChatOpenAI):\n    \"\"\"`Azure OpenAI` Chat Completion API.\n    To use this class you\n    must have a deployed model on Azure OpenAI. Use `deployment_name` in the\n    constructor to refer to the \"Model deployment name\" in the Azure portal.\n    In addition, you should have the ``openai`` python package installed, and the\n    following environment variables set or passed in constructor in lower case:\n    - ``AZURE_OPENAI_API_KEY``\n    - ``AZURE_OPENAI_API_ENDPOINT``\n    - ``AZURE_OPENAI_AD_TOKEN``\n    - ``OPENAI_API_VERSION``\n    - ``OPENAI_PROXY``\n    For example, if you have `gpt-35-turbo` deployed, with the deployment name\n    `35-turbo-dev`, the constructor should look like:\n    .. code-block:: python\n        AzureChatOpenAI(\n            azure_deployment=\"35-turbo-dev\",\n            openai_api_version=\"2023-05-15\",\n        )\n    Be aware the API version may change.\n    You can also specify the version of the model using ``model_version`` constructor\n    parameter, as Azure OpenAI doesn't return model version with the response.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html"}
{"id": "7cb368411ffd-1", "text": "parameter, as Azure OpenAI doesn't return model version with the response.\n    Default is empty. When you specify the version, it will be appended to the\n    model name in the response. Setting correct version will help you to calculate the\n    cost properly. Model version is not validated, so make sure you set it correctly\n    to get the correct cost.\n    Any parameters that are valid to be passed to the openai.create call can be passed\n    in, even if not explicitly saved on this class.\n    \"\"\"\n    azure_endpoint: Union[str, None] = None\n    \"\"\"Your Azure endpoint, including the resource.\n    \n        Automatically inferred from env var `AZURE_OPENAI_ENDPOINT` if not provided.\n    \n        Example: `https://example-resource.azure.openai.com/`\n    \"\"\"\n    deployment_name: Union[str, None] = Field(default=None, alias=\"azure_deployment\")\n    \"\"\"A model deployment. \n    \n        If given sets the base client URL to include `/deployments/{azure_deployment}`.\n        Note: this means you won't be able to use non-deployment endpoints.\n    \"\"\"\n    openai_api_version: str = Field(default=\"\", alias=\"api_version\")\n    \"\"\"Automatically inferred from env var `OPENAI_API_VERSION` if not provided.\"\"\"\n    openai_api_key: Union[str, None] = Field(default=None, alias=\"api_key\")\n    \"\"\"Automatically inferred from env var `AZURE_OPENAI_API_KEY` if not provided.\"\"\"\n    azure_ad_token: Union[str, None] = None\n    \"\"\"Your Azure Active Directory token.\n    \n        Automatically inferred from env var `AZURE_OPENAI_AD_TOKEN` if not provided.\n        \n        For more: \n        https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html"}
{"id": "7cb368411ffd-2", "text": "\"\"\"  # noqa: E501\n    azure_ad_token_provider: Union[str, None] = None\n    \"\"\"A function that returns an Azure Active Directory token.\n        \n        Will be invoked on every request.\n    \"\"\"\n    model_version: str = \"\"\n    \"\"\"Legacy, for openai<1.0.0 support.\"\"\"\n    openai_api_type: str = \"\"\n    \"\"\"Legacy, for openai<1.0.0 support.\"\"\"\n    validate_base_url: bool = True\n    \"\"\"For backwards compatibility. If legacy val openai_api_base is passed in, try to \n        infer if it is a base_url or azure_endpoint and update accordingly.\n    \"\"\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        if values[\"n\"] < 1:\n            raise ValueError(\"n must be at least 1.\")\n        if values[\"n\"] > 1 and values[\"streaming\"]:\n            raise ValueError(\"n must be 1 when streaming.\")\n        # Check OPENAI_KEY for backwards compatibility.\n        # TODO: Remove OPENAI_API_KEY support to avoid possible conflict when using\n        # other forms of azure credentials.\n        values[\"openai_api_key\"] = (\n            values[\"openai_api_key\"]\n            or os.getenv(\"AZURE_OPENAI_API_KEY\")\n            or os.getenv(\"OPENAI_API_KEY\")\n        )\n        values[\"openai_api_base\"] = values[\"openai_api_base\"] or os.getenv(\n            \"OPENAI_API_BASE\"\n        )\n        values[\"openai_api_version\"] = values[\"openai_api_version\"] or os.getenv(\n            \"OPENAI_API_VERSION\"\n        )\n        # Check OPENAI_ORGANIZATION for backwards compatibility.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html"}
{"id": "7cb368411ffd-3", "text": ")\n        # Check OPENAI_ORGANIZATION for backwards compatibility.\n        values[\"openai_organization\"] = (\n            values[\"openai_organization\"]\n            or os.getenv(\"OPENAI_ORG_ID\")\n            or os.getenv(\"OPENAI_ORGANIZATION\")\n        )\n        values[\"azure_endpoint\"] = values[\"azure_endpoint\"] or os.getenv(\n            \"AZURE_OPENAI_ENDPOINT\"\n        )\n        values[\"azure_ad_token\"] = values[\"azure_ad_token\"] or os.getenv(\n            \"AZURE_OPENAI_AD_TOKEN\"\n        )\n        values[\"openai_api_type\"] = get_from_dict_or_env(\n            values, \"openai_api_type\", \"OPENAI_API_TYPE\", default=\"azure\"\n        )\n        values[\"openai_proxy\"] = get_from_dict_or_env(\n            values, \"openai_proxy\", \"OPENAI_PROXY\", default=\"\"\n        )\n        try:\n            import openai\n        except ImportError:\n            raise ImportError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\"\n            )\n        if is_openai_v1():\n            # For backwards compatibility. Before openai v1, no distinction was made\n            # between azure_endpoint and base_url (openai_api_base).\n            openai_api_base = values[\"openai_api_base\"]\n            if openai_api_base and values[\"validate_base_url\"]:\n                if \"/openai\" not in openai_api_base:\n                    values[\"openai_api_base\"] = (\n                        values[\"openai_api_base\"].rstrip(\"/\") + \"/openai\"\n                    )\n                    warnings.warn(\n                        \"As of openai>=1.0.0, Azure endpoints should be specified via \"\n                        f\"the `azure_endpoint` param not `openai_api_base` \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html"}
{"id": "7cb368411ffd-4", "text": "f\"the `azure_endpoint` param not `openai_api_base` \"\n                        f\"(or alias `base_url`). Updating `openai_api_base` from \"\n                        f\"{openai_api_base} to {values['openai_api_base']}.\"\n                    )\n                if values[\"deployment_name\"]:\n                    warnings.warn(\n                        \"As of openai>=1.0.0, if `deployment_name` (or alias \"\n                        \"`azure_deployment`) is specified then \"\n                        \"`openai_api_base` (or alias `base_url`) should not be. \"\n                        \"Instead use `deployment_name` (or alias `azure_deployment`) \"\n                        \"and `azure_endpoint`.\"\n                    )\n                    if values[\"deployment_name\"] not in values[\"openai_api_base\"]:\n                        warnings.warn(\n                            \"As of openai>=1.0.0, if `openai_api_base` \"\n                            \"(or alias `base_url`) is specified it is expected to be \"\n                            \"of the form \"\n                            \"https://example-resource.azure.openai.com/openai/deployments/example-deployment. \"  # noqa: E501\n                            f\"Updating {openai_api_base} to \"\n                            f\"{values['openai_api_base']}.\"\n                        )\n                        values[\"openai_api_base\"] += (\n                            \"/deployments/\" + values[\"deployment_name\"]\n                        )\n                    values[\"deployment_name\"] = None\n            client_params = {\n                \"api_version\": values[\"openai_api_version\"],\n                \"azure_endpoint\": values[\"azure_endpoint\"],\n                \"azure_deployment\": values[\"deployment_name\"],\n                \"api_key\": values[\"openai_api_key\"],\n                \"azure_ad_token\": values[\"azure_ad_token\"],\n                \"azure_ad_token_provider\": values[\"azure_ad_token_provider\"],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html"}
{"id": "7cb368411ffd-5", "text": "\"azure_ad_token_provider\": values[\"azure_ad_token_provider\"],\n                \"organization\": values[\"openai_organization\"],\n                \"base_url\": values[\"openai_api_base\"],\n                \"timeout\": values[\"request_timeout\"],\n                \"max_retries\": values[\"max_retries\"],\n                \"default_headers\": values[\"default_headers\"],\n                \"default_query\": values[\"default_query\"],\n                \"http_client\": values[\"http_client\"],\n            }\n            values[\"client\"] = openai.AzureOpenAI(**client_params).chat.completions\n            values[\"async_client\"] = openai.AsyncAzureOpenAI(\n                **client_params\n            ).chat.completions\n        else:\n            values[\"client\"] = openai.ChatCompletion\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling OpenAI API.\"\"\"\n        if is_openai_v1():\n            return super()._default_params\n        else:\n            return {\n                **super()._default_params,\n                \"engine\": self.deployment_name,\n            }\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**self._default_params}\n    @property\n    def _client_params(self) -> Dict[str, Any]:\n        \"\"\"Get the config params used for the openai client.\"\"\"\n        if is_openai_v1():\n            return super()._client_params\n        else:\n            return {\n                **super()._client_params,\n                \"api_type\": self.openai_api_type,\n                \"api_version\": self.openai_api_version,\n            }\n    @property\n    def _llm_type(self) -> str:\n        return \"azure-openai-chat\"\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html"}
{"id": "7cb368411ffd-6", "text": "return \"azure-openai-chat\"\n    @property\n    def lc_attributes(self) -> Dict[str, Any]:\n        return {\n            \"openai_api_type\": self.openai_api_type,\n            \"openai_api_version\": self.openai_api_version,\n        }\n    def _create_chat_result(self, response: Union[dict, BaseModel]) -> ChatResult:\n        if not isinstance(response, dict):\n            response = response.dict()\n        for res in response[\"choices\"]:\n            if res.get(\"finish_reason\", None) == \"content_filter\":\n                raise ValueError(\n                    \"Azure has not provided the response due to a content filter \"\n                    \"being triggered\"\n                )\n        chat_result = super()._create_chat_result(response)\n        if \"model\" in response:\n            model = response[\"model\"]\n            if self.model_version:\n                model = f\"{model}-{self.model_version}\"\n            if chat_result.llm_output is not None and isinstance(\n                chat_result.llm_output, dict\n            ):\n                chat_result.llm_output[\"model_name\"] = model\n        return chat_result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html"}
{"id": "cbe93ddd9e48-0", "text": "Source code for langchain.chat_models.vertexai\n\"\"\"Wrapper around Google VertexAI chat-based models.\"\"\"\nfrom __future__ import annotations\nimport logging\nfrom dataclasses import dataclass, field\nfrom typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Union, cast\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel, _generate_from_stream\nfrom langchain.llms.vertexai import _VertexAICommon, is_codey_model\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import ChatGeneration, ChatResult\nfrom langchain.schema.messages import (\n    AIMessage,\n    AIMessageChunk,\n    BaseMessage,\n    HumanMessage,\n    SystemMessage,\n)\nfrom langchain.schema.output import ChatGenerationChunk\nfrom langchain.utilities.vertexai import raise_vertex_import_error\nif TYPE_CHECKING:\n    from vertexai.language_models import (\n        ChatMessage,\n        ChatSession,\n        CodeChatSession,\n        InputOutputTextPair,\n    )\nlogger = logging.getLogger(__name__)\n@dataclass\nclass _ChatHistory:\n    \"\"\"Represents a context and a history of messages.\"\"\"\n    history: List[\"ChatMessage\"] = field(default_factory=list)\n    context: Optional[str] = None\ndef _parse_chat_history(history: List[BaseMessage]) -> _ChatHistory:\n    \"\"\"Parse a sequence of messages into history.\n    Args:\n        history: The list of messages to re-create the history of the chat.\n    Returns:\n        A parsed chat history.\n    Raises:\n        ValueError: If a sequence of message has a SystemMessage not at the\n        first place.\n    \"\"\"\n    from vertexai.language_models import ChatMessage", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html"}
{"id": "cbe93ddd9e48-1", "text": "first place.\n    \"\"\"\n    from vertexai.language_models import ChatMessage\n    vertex_messages, context = [], None\n    for i, message in enumerate(history):\n        content = cast(str, message.content)\n        if i == 0 and isinstance(message, SystemMessage):\n            context = content\n        elif isinstance(message, AIMessage):\n            vertex_message = ChatMessage(content=message.content, author=\"bot\")\n            vertex_messages.append(vertex_message)\n        elif isinstance(message, HumanMessage):\n            vertex_message = ChatMessage(content=message.content, author=\"user\")\n            vertex_messages.append(vertex_message)\n        else:\n            raise ValueError(\n                f\"Unexpected message with type {type(message)} at the position {i}.\"\n            )\n    chat_history = _ChatHistory(context=context, history=vertex_messages)\n    return chat_history\ndef _parse_examples(examples: List[BaseMessage]) -> List[\"InputOutputTextPair\"]:\n    from vertexai.language_models import InputOutputTextPair\n    if len(examples) % 2 != 0:\n        raise ValueError(\n            f\"Expect examples to have an even amount of messages, got {len(examples)}.\"\n        )\n    example_pairs = []\n    input_text = None\n    for i, example in enumerate(examples):\n        if i % 2 == 0:\n            if not isinstance(example, HumanMessage):\n                raise ValueError(\n                    f\"Expected the first message in a part to be from human, got \"\n                    f\"{type(example)} for the {i}th message.\"\n                )\n            input_text = example.content\n        if i % 2 == 1:\n            if not isinstance(example, AIMessage):\n                raise ValueError(\n                    f\"Expected the second message in a part to be from AI, got \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html"}
{"id": "cbe93ddd9e48-2", "text": "f\"Expected the second message in a part to be from AI, got \"\n                    f\"{type(example)} for the {i}th message.\"\n                )\n            pair = InputOutputTextPair(\n                input_text=input_text, output_text=example.content\n            )\n            example_pairs.append(pair)\n    return example_pairs\ndef _get_question(messages: List[BaseMessage]) -> HumanMessage:\n    \"\"\"Get the human message at the end of a list of input messages to a chat model.\"\"\"\n    if not messages:\n        raise ValueError(\"You should provide at least one message to start the chat!\")\n    question = messages[-1]\n    if not isinstance(question, HumanMessage):\n        raise ValueError(\n            f\"Last message in the list should be from human, got {question.type}.\"\n        )\n    return question\n[docs]class ChatVertexAI(_VertexAICommon, BaseChatModel):\n    \"\"\"`Vertex AI` Chat large language models API.\"\"\"\n    model_name: str = \"chat-bison\"\n    \"Underlying model name.\"\n    examples: Optional[List[BaseMessage]] = None\n[docs]    @classmethod\n    def is_lc_serializable(self) -> bool:\n        return True\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the python package exists in environment.\"\"\"\n        cls._try_init_vertexai(values)\n        try:\n            if is_codey_model(values[\"model_name\"]):\n                from vertexai.preview.language_models import CodeChatModel\n                values[\"client\"] = CodeChatModel.from_pretrained(values[\"model_name\"])\n            else:\n                from vertexai.preview.language_models import ChatModel\n                values[\"client\"] = ChatModel.from_pretrained(values[\"model_name\"])\n        except ImportError:\n            raise_vertex_import_error()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html"}
{"id": "cbe93ddd9e48-3", "text": "except ImportError:\n            raise_vertex_import_error()\n        return values\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        \"\"\"Generate next turn in the conversation.\n        Args:\n            messages: The history of the conversation as a list of messages. Code chat\n                does not support context.\n            stop: The list of stop words (optional).\n            run_manager: The CallbackManager for LLM run, it's not used at the moment.\n            stream: Whether to use the streaming endpoint.\n        Returns:\n            The ChatResult that contains outputs generated by the model.\n        Raises:\n            ValueError: if the last message in the list is not from human.\n        \"\"\"\n        should_stream = stream if stream is not None else self.streaming\n        if should_stream:\n            stream_iter = self._stream(\n                messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return _generate_from_stream(stream_iter)\n        question = _get_question(messages)\n        history = _parse_chat_history(messages[:-1])\n        params = self._prepare_params(stop=stop, stream=False, **kwargs)\n        examples = kwargs.get(\"examples\") or self.examples\n        if examples:\n            params[\"examples\"] = _parse_examples(examples)\n        msg_params = {}\n        if \"candidate_count\" in params:\n            msg_params[\"candidate_count\"] = params.pop(\"candidate_count\")\n        chat = self._start_chat(history, **params)\n        response = chat.send_message(question.content, **msg_params)\n        generations = [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html"}
{"id": "cbe93ddd9e48-4", "text": "response = chat.send_message(question.content, **msg_params)\n        generations = [\n            ChatGeneration(message=AIMessage(content=r.text))\n            for r in response.candidates\n        ]\n        return ChatResult(generations=generations)\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        \"\"\"Asynchronously generate next turn in the conversation.\n        Args:\n            messages: The history of the conversation as a list of messages. Code chat\n                does not support context.\n            stop: The list of stop words (optional).\n            run_manager: The CallbackManager for LLM run, it's not used at the moment.\n        Returns:\n            The ChatResult that contains outputs generated by the model.\n        Raises:\n            ValueError: if the last message in the list is not from human.\n        \"\"\"\n        if \"stream\" in kwargs:\n            kwargs.pop(\"stream\")\n            logger.warning(\"ChatVertexAI does not currently support async streaming.\")\n        question = _get_question(messages)\n        history = _parse_chat_history(messages[:-1])\n        params = self._prepare_params(stop=stop, **kwargs)\n        examples = kwargs.get(\"examples\", None)\n        if examples:\n            params[\"examples\"] = _parse_examples(examples)\n        msg_params = {}\n        if \"candidate_count\" in params:\n            msg_params[\"candidate_count\"] = params.pop(\"candidate_count\")\n        chat = self._start_chat(history, **params)\n        response = await chat.send_message_async(question.content, **msg_params)\n        generations = [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html"}
{"id": "cbe93ddd9e48-5", "text": "generations = [\n            ChatGeneration(message=AIMessage(content=r.text))\n            for r in response.candidates\n        ]\n        return ChatResult(generations=generations)\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        question = _get_question(messages)\n        history = _parse_chat_history(messages[:-1])\n        params = self._prepare_params(stop=stop, **kwargs)\n        examples = kwargs.get(\"examples\", None)\n        if examples:\n            params[\"examples\"] = _parse_examples(examples)\n        chat = self._start_chat(history, **params)\n        responses = chat.send_message_streaming(question.content, **params)\n        for response in responses:\n            if run_manager:\n                run_manager.on_llm_new_token(response.text)\n            yield ChatGenerationChunk(message=AIMessageChunk(content=response.text))\n    def _start_chat(\n        self, history: _ChatHistory, **kwargs: Any\n    ) -> Union[ChatSession, CodeChatSession]:\n        if not self.is_codey_model:\n            return self.client.start_chat(\n                context=history.context, message_history=history.history, **kwargs\n            )\n        else:\n            return self.client.start_chat(message_history=history.history, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html"}
{"id": "0defca26ba88-0", "text": "Source code for langchain.chat_models.google_palm\n\"\"\"Wrapper around Google's PaLM Chat API.\"\"\"\nfrom __future__ import annotations\nimport logging\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, cast\nfrom tenacity import (\n    before_sleep_log,\n    retry,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema import (\n    ChatGeneration,\n    ChatResult,\n)\nfrom langchain.schema.messages import (\n    AIMessage,\n    BaseMessage,\n    ChatMessage,\n    HumanMessage,\n    SystemMessage,\n)\nfrom langchain.utils import get_from_dict_or_env\nif TYPE_CHECKING:\n    import google.generativeai as genai\nlogger = logging.getLogger(__name__)\n[docs]class ChatGooglePalmError(Exception):\n    \"\"\"Error with the `Google PaLM` API.\"\"\"\ndef _truncate_at_stop_tokens(\n    text: str,\n    stop: Optional[List[str]],\n) -> str:\n    \"\"\"Truncates text at the earliest stop token found.\"\"\"\n    if stop is None:\n        return text\n    for stop_token in stop:\n        stop_token_idx = text.find(stop_token)\n        if stop_token_idx != -1:\n            text = text[:stop_token_idx]\n    return text\ndef _response_to_result(\n    response: genai.types.ChatResponse,\n    stop: Optional[List[str]],\n) -> ChatResult:\n    \"\"\"Converts a PaLM API response into a LangChain ChatResult.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html"}
{"id": "0defca26ba88-1", "text": "\"\"\"Converts a PaLM API response into a LangChain ChatResult.\"\"\"\n    if not response.candidates:\n        raise ChatGooglePalmError(\"ChatResponse must have at least one candidate.\")\n    generations: List[ChatGeneration] = []\n    for candidate in response.candidates:\n        author = candidate.get(\"author\")\n        if author is None:\n            raise ChatGooglePalmError(f\"ChatResponse must have an author: {candidate}\")\n        content = _truncate_at_stop_tokens(candidate.get(\"content\", \"\"), stop)\n        if content is None:\n            raise ChatGooglePalmError(f\"ChatResponse must have a content: {candidate}\")\n        if author == \"ai\":\n            generations.append(\n                ChatGeneration(text=content, message=AIMessage(content=content))\n            )\n        elif author == \"human\":\n            generations.append(\n                ChatGeneration(\n                    text=content,\n                    message=HumanMessage(content=content),\n                )\n            )\n        else:\n            generations.append(\n                ChatGeneration(\n                    text=content,\n                    message=ChatMessage(role=author, content=content),\n                )\n            )\n    return ChatResult(generations=generations)\ndef _messages_to_prompt_dict(\n    input_messages: List[BaseMessage],\n) -> genai.types.MessagePromptDict:\n    \"\"\"Converts a list of LangChain messages into a PaLM API MessagePrompt structure.\"\"\"\n    import google.generativeai as genai\n    context: str = \"\"\n    examples: List[genai.types.MessageDict] = []\n    messages: List[genai.types.MessageDict] = []\n    remaining = list(enumerate(input_messages))\n    while remaining:\n        index, input_message = remaining.pop(0)\n        if isinstance(input_message, SystemMessage):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html"}
{"id": "0defca26ba88-2", "text": "if isinstance(input_message, SystemMessage):\n            if index != 0:\n                raise ChatGooglePalmError(\"System message must be first input message.\")\n            context = cast(str, input_message.content)\n        elif isinstance(input_message, HumanMessage) and input_message.example:\n            if messages:\n                raise ChatGooglePalmError(\n                    \"Message examples must come before other messages.\"\n                )\n            _, next_input_message = remaining.pop(0)\n            if isinstance(next_input_message, AIMessage) and next_input_message.example:\n                examples.extend(\n                    [\n                        genai.types.MessageDict(\n                            author=\"human\", content=input_message.content\n                        ),\n                        genai.types.MessageDict(\n                            author=\"ai\", content=next_input_message.content\n                        ),\n                    ]\n                )\n            else:\n                raise ChatGooglePalmError(\n                    \"Human example message must be immediately followed by an \"\n                    \" AI example response.\"\n                )\n        elif isinstance(input_message, AIMessage) and input_message.example:\n            raise ChatGooglePalmError(\n                \"AI example message must be immediately preceded by a Human \"\n                \"example message.\"\n            )\n        elif isinstance(input_message, AIMessage):\n            messages.append(\n                genai.types.MessageDict(author=\"ai\", content=input_message.content)\n            )\n        elif isinstance(input_message, HumanMessage):\n            messages.append(\n                genai.types.MessageDict(author=\"human\", content=input_message.content)\n            )\n        elif isinstance(input_message, ChatMessage):\n            messages.append(\n                genai.types.MessageDict(\n                    author=input_message.role, content=input_message.content\n                )\n            )\n        else:\n            raise ChatGooglePalmError(\n                \"Messages without an explicit role not supported by PaLM API.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html"}
{"id": "0defca26ba88-3", "text": "\"Messages without an explicit role not supported by PaLM API.\"\n            )\n    return genai.types.MessagePromptDict(\n        context=context,\n        examples=examples,\n        messages=messages,\n    )\ndef _create_retry_decorator() -> Callable[[Any], Any]:\n    \"\"\"Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions\"\"\"\n    import google.api_core.exceptions\n    multiplier = 2\n    min_seconds = 1\n    max_seconds = 60\n    max_retries = 10\n    return retry(\n        reraise=True,\n        stop=stop_after_attempt(max_retries),\n        wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds),\n        retry=(\n            retry_if_exception_type(google.api_core.exceptions.ResourceExhausted)\n            | retry_if_exception_type(google.api_core.exceptions.ServiceUnavailable)\n            | retry_if_exception_type(google.api_core.exceptions.GoogleAPIError)\n        ),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\n[docs]def chat_with_retry(llm: ChatGooglePalm, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    retry_decorator = _create_retry_decorator()\n    @retry_decorator\n    def _chat_with_retry(**kwargs: Any) -> Any:\n        return llm.client.chat(**kwargs)\n    return _chat_with_retry(**kwargs)\n[docs]async def achat_with_retry(llm: ChatGooglePalm, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the async completion call.\"\"\"\n    retry_decorator = _create_retry_decorator()\n    @retry_decorator\n    async def _achat_with_retry(**kwargs: Any) -> Any:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html"}
{"id": "0defca26ba88-4", "text": "async def _achat_with_retry(**kwargs: Any) -> Any:\n        # Use OpenAI's async api https://github.com/openai/openai-python#async-api\n        return await llm.client.chat_async(**kwargs)\n    return await _achat_with_retry(**kwargs)\n[docs]class ChatGooglePalm(BaseChatModel, BaseModel):\n    \"\"\"`Google PaLM` Chat models API.\n    To use you must have the google.generativeai Python package installed and\n    either:\n        1. The ``GOOGLE_API_KEY``` environment variable set with your API key, or\n        2. Pass your API key using the google_api_key kwarg to the ChatGoogle\n           constructor.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import ChatGooglePalm\n            chat = ChatGooglePalm()\n    \"\"\"\n    client: Any  #: :meta private:\n    model_name: str = \"models/chat-bison-001\"\n    \"\"\"Model name to use.\"\"\"\n    google_api_key: Optional[str] = None\n    temperature: Optional[float] = None\n    \"\"\"Run inference with this temperature. Must by in the closed\n       interval [0.0, 1.0].\"\"\"\n    top_p: Optional[float] = None\n    \"\"\"Decode using nucleus sampling: consider the smallest set of tokens whose\n       probability sum is at least top_p. Must be in the closed interval [0.0, 1.0].\"\"\"\n    top_k: Optional[int] = None\n    \"\"\"Decode using top-k sampling: consider the set of top_k most probable tokens.\n       Must be positive.\"\"\"\n    n: int = 1\n    \"\"\"Number of chat completions to generate for each prompt. Note that the API may\n       not return the full n completions if duplicates are generated.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html"}
{"id": "0defca26ba88-5", "text": "not return the full n completions if duplicates are generated.\"\"\"\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"google_api_key\": \"GOOGLE_API_KEY\"}\n[docs]    @classmethod\n    def is_lc_serializable(self) -> bool:\n        return True\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate api key, python package exists, temperature, top_p, and top_k.\"\"\"\n        google_api_key = get_from_dict_or_env(\n            values, \"google_api_key\", \"GOOGLE_API_KEY\"\n        )\n        try:\n            import google.generativeai as genai\n            genai.configure(api_key=google_api_key)\n        except ImportError:\n            raise ChatGooglePalmError(\n                \"Could not import google.generativeai python package. \"\n                \"Please install it with `pip install google-generativeai`\"\n            )\n        values[\"client\"] = genai\n        if values[\"temperature\"] is not None and not 0 <= values[\"temperature\"] <= 1:\n            raise ValueError(\"temperature must be in the range [0.0, 1.0]\")\n        if values[\"top_p\"] is not None and not 0 <= values[\"top_p\"] <= 1:\n            raise ValueError(\"top_p must be in the range [0.0, 1.0]\")\n        if values[\"top_k\"] is not None and values[\"top_k\"] <= 0:\n            raise ValueError(\"top_k must be positive\")\n        return values\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html"}
{"id": "0defca26ba88-6", "text": "run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        prompt = _messages_to_prompt_dict(messages)\n        response: genai.types.ChatResponse = chat_with_retry(\n            self,\n            model=self.model_name,\n            prompt=prompt,\n            temperature=self.temperature,\n            top_p=self.top_p,\n            top_k=self.top_k,\n            candidate_count=self.n,\n            **kwargs,\n        )\n        return _response_to_result(response, stop)\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        prompt = _messages_to_prompt_dict(messages)\n        response: genai.types.ChatResponse = await achat_with_retry(\n            self,\n            model=self.model_name,\n            prompt=prompt,\n            temperature=self.temperature,\n            top_p=self.top_p,\n            top_k=self.top_k,\n            candidate_count=self.n,\n        )\n        return _response_to_result(response, stop)\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"model_name\": self.model_name,\n            \"temperature\": self.temperature,\n            \"top_p\": self.top_p,\n            \"top_k\": self.top_k,\n            \"n\": self.n,\n        }\n    @property\n    def _llm_type(self) -> str:\n        return \"google-palm-chat\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html"}
{"id": "000281837cd9-0", "text": "Source code for langchain.chat_models.anthropic\nfrom typing import Any, AsyncIterator, Dict, Iterator, List, Optional, cast\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import (\n    BaseChatModel,\n    _agenerate_from_stream,\n    _generate_from_stream,\n)\nfrom langchain.llms.anthropic import _AnthropicCommon\nfrom langchain.schema.messages import (\n    AIMessage,\n    AIMessageChunk,\n    BaseMessage,\n    ChatMessage,\n    HumanMessage,\n    SystemMessage,\n)\nfrom langchain.schema.output import ChatGeneration, ChatGenerationChunk, ChatResult\nfrom langchain.schema.prompt import PromptValue\ndef _convert_one_message_to_text(\n    message: BaseMessage,\n    human_prompt: str,\n    ai_prompt: str,\n) -> str:\n    content = cast(str, message.content)\n    if isinstance(message, ChatMessage):\n        message_text = f\"\\n\\n{message.role.capitalize()}: {content}\"\n    elif isinstance(message, HumanMessage):\n        message_text = f\"{human_prompt} {content}\"\n    elif isinstance(message, AIMessage):\n        message_text = f\"{ai_prompt} {content}\"\n    elif isinstance(message, SystemMessage):\n        message_text = content\n    else:\n        raise ValueError(f\"Got unknown type {message}\")\n    return message_text\n[docs]def convert_messages_to_prompt_anthropic(\n    messages: List[BaseMessage],\n    *,\n    human_prompt: str = \"\\n\\nHuman:\",\n    ai_prompt: str = \"\\n\\nAssistant:\",\n) -> str:\n    \"\"\"Format a list of messages into a full prompt for the Anthropic model\n    Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html"}
{"id": "000281837cd9-1", "text": "Args:\n        messages (List[BaseMessage]): List of BaseMessage to combine.\n        human_prompt (str, optional): Human prompt tag. Defaults to \"\\n\\nHuman:\".\n        ai_prompt (str, optional): AI prompt tag. Defaults to \"\\n\\nAssistant:\".\n    Returns:\n        str: Combined string with necessary human_prompt and ai_prompt tags.\n    \"\"\"\n    messages = messages.copy()  # don't mutate the original list\n    if not isinstance(messages[-1], AIMessage):\n        messages.append(AIMessage(content=\"\"))\n    text = \"\".join(\n        _convert_one_message_to_text(message, human_prompt, ai_prompt)\n        for message in messages\n    )\n    # trim off the trailing ' ' that might come from the \"Assistant: \"\n    return text.rstrip()\n[docs]class ChatAnthropic(BaseChatModel, _AnthropicCommon):\n    \"\"\"`Anthropic` chat large language models.\n    To use, you should have the ``anthropic`` python package installed, and the\n    environment variable ``ANTHROPIC_API_KEY`` set with your API key, or pass\n    it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            import anthropic\n            from langchain.chat_models import ChatAnthropic\n            model = ChatAnthropic(model=\"<model_name>\", anthropic_api_key=\"my-api-key\")\n    \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        allow_population_by_field_name = True\n        arbitrary_types_allowed = True\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"anthropic_api_key\": \"ANTHROPIC_API_KEY\"}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat model.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html"}
{"id": "000281837cd9-2", "text": "\"\"\"Return type of chat model.\"\"\"\n        return \"anthropic-chat\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this model can be serialized by Langchain.\"\"\"\n        return True\n    def _convert_messages_to_prompt(self, messages: List[BaseMessage]) -> str:\n        \"\"\"Format a list of messages into a full prompt for the Anthropic model\n        Args:\n            messages (List[BaseMessage]): List of BaseMessage to combine.\n        Returns:\n            str: Combined string with necessary HUMAN_PROMPT and AI_PROMPT tags.\n        \"\"\"\n        prompt_params = {}\n        if self.HUMAN_PROMPT:\n            prompt_params[\"human_prompt\"] = self.HUMAN_PROMPT\n        if self.AI_PROMPT:\n            prompt_params[\"ai_prompt\"] = self.AI_PROMPT\n        return convert_messages_to_prompt_anthropic(messages=messages, **prompt_params)\n[docs]    def convert_prompt(self, prompt: PromptValue) -> str:\n        return self._convert_messages_to_prompt(prompt.to_messages())\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        prompt = self._convert_messages_to_prompt(messages)\n        params: Dict[str, Any] = {\"prompt\": prompt, **self._default_params, **kwargs}\n        if stop:\n            params[\"stop_sequences\"] = stop\n        stream_resp = self.client.completions.create(**params, stream=True)\n        for data in stream_resp:\n            delta = data.completion\n            yield ChatGenerationChunk(message=AIMessageChunk(content=delta))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html"}
{"id": "000281837cd9-3", "text": "yield ChatGenerationChunk(message=AIMessageChunk(content=delta))\n            if run_manager:\n                run_manager.on_llm_new_token(delta)\n    async def _astream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[ChatGenerationChunk]:\n        prompt = self._convert_messages_to_prompt(messages)\n        params: Dict[str, Any] = {\"prompt\": prompt, **self._default_params, **kwargs}\n        if stop:\n            params[\"stop_sequences\"] = stop\n        stream_resp = await self.async_client.completions.create(**params, stream=True)\n        async for data in stream_resp:\n            delta = data.completion\n            yield ChatGenerationChunk(message=AIMessageChunk(content=delta))\n            if run_manager:\n                await run_manager.on_llm_new_token(delta)\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        if self.streaming:\n            stream_iter = self._stream(\n                messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return _generate_from_stream(stream_iter)\n        prompt = self._convert_messages_to_prompt(\n            messages,\n        )\n        params: Dict[str, Any] = {\n            \"prompt\": prompt,\n            **self._default_params,\n            **kwargs,\n        }\n        if stop:\n            params[\"stop_sequences\"] = stop", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html"}
{"id": "000281837cd9-4", "text": "}\n        if stop:\n            params[\"stop_sequences\"] = stop\n        response = self.client.completions.create(**params)\n        completion = response.completion\n        message = AIMessage(content=completion)\n        return ChatResult(generations=[ChatGeneration(message=message)])\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        if self.streaming:\n            stream_iter = self._astream(\n                messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return await _agenerate_from_stream(stream_iter)\n        prompt = self._convert_messages_to_prompt(\n            messages,\n        )\n        params: Dict[str, Any] = {\n            \"prompt\": prompt,\n            **self._default_params,\n            **kwargs,\n        }\n        if stop:\n            params[\"stop_sequences\"] = stop\n        response = await self.async_client.completions.create(**params)\n        completion = response.completion\n        message = AIMessage(content=completion)\n        return ChatResult(generations=[ChatGeneration(message=message)])\n[docs]    def get_num_tokens(self, text: str) -> int:\n        \"\"\"Calculate number of tokens.\"\"\"\n        if not self.count_tokens:\n            raise NameError(\"Please ensure the anthropic package is loaded\")\n        return self.count_tokens(text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html"}
{"id": "4ec3ccb3a721-0", "text": "Source code for langchain.chat_models.tongyi\nfrom __future__ import annotations\nimport logging\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Tuple,\n    Type,\n)\nfrom requests.exceptions import HTTPError\nfrom tenacity import (\n    RetryCallState,\n    retry,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.chat_models.base import (\n    BaseChatModel,\n    _generate_from_stream,\n)\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema import ChatGeneration, ChatResult\nfrom langchain.schema.messages import (\n    AIMessage,\n    AIMessageChunk,\n    BaseMessage,\n    BaseMessageChunk,\n    ChatMessage,\n    ChatMessageChunk,\n    FunctionMessage,\n    FunctionMessageChunk,\n    HumanMessage,\n    HumanMessageChunk,\n    SystemMessage,\n    SystemMessageChunk,\n)\nfrom langchain.schema.output import ChatGenerationChunk, GenerationChunk\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]def convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:\n    role = _dict[\"role\"]\n    if role == \"user\":\n        return HumanMessage(content=_dict[\"content\"])\n    elif role == \"assistant\":\n        content = _dict.get(\"content\", \"\") or \"\"\n        if _dict.get(\"function_call\"):\n            additional_kwargs = {\"function_call\": dict(_dict[\"function_call\"])}\n        else:\n            additional_kwargs = {}\n        return AIMessage(content=content, additional_kwargs=additional_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html"}
{"id": "4ec3ccb3a721-1", "text": "return AIMessage(content=content, additional_kwargs=additional_kwargs)\n    elif role == \"system\":\n        return SystemMessage(content=_dict[\"content\"])\n    elif role == \"function\":\n        return FunctionMessage(content=_dict[\"content\"], name=_dict[\"name\"])\n    else:\n        return ChatMessage(content=_dict[\"content\"], role=role)\n[docs]def convert_message_to_dict(message: BaseMessage) -> dict:\n    message_dict: Dict[str, Any]\n    if isinstance(message, ChatMessage):\n        message_dict = {\"role\": message.role, \"content\": message.content}\n    elif isinstance(message, HumanMessage):\n        message_dict = {\"role\": \"user\", \"content\": message.content}\n    elif isinstance(message, AIMessage):\n        message_dict = {\"role\": \"assistant\", \"content\": message.content}\n        if \"function_call\" in message.additional_kwargs:\n            message_dict[\"function_call\"] = message.additional_kwargs[\"function_call\"]\n            # If function call only, content is None not empty string\n            if message_dict[\"content\"] == \"\":\n                message_dict[\"content\"] = None\n    elif isinstance(message, SystemMessage):\n        message_dict = {\"role\": \"system\", \"content\": message.content}\n    elif isinstance(message, FunctionMessage):\n        message_dict = {\n            \"role\": \"function\",\n            \"content\": message.content,\n            \"name\": message.name,\n        }\n    else:\n        raise TypeError(f\"Got unknown type {message}\")\n    if \"name\" in message.additional_kwargs:\n        message_dict[\"name\"] = message.additional_kwargs[\"name\"]\n    return message_dict\ndef _stream_response_to_generation_chunk(\n    stream_response: Dict[str, Any],\n    length: int,\n) -> GenerationChunk:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html"}
{"id": "4ec3ccb3a721-2", "text": "length: int,\n) -> GenerationChunk:\n    \"\"\"Convert a stream response to a generation chunk.\n    As the low level API implement is different from openai and other llm.\n    Stream response of Tongyi is not split into chunks, but all data generated before.\n    For example, the answer 'Hi Pickle Rick! How can I assist you today?'\n    Other llm will stream answer:\n    'Hi Pickle',\n    ' Rick!',\n    ' How can I assist you today?'.\n    Tongyi answer:\n    'Hi Pickle',\n    'Hi Pickle Rick!',\n    'Hi Pickle Rick! How can I assist you today?'.\n    As the GenerationChunk is implemented with chunks. Only return full_text[length:]\n    for new chunk.\n    \"\"\"\n    full_text = stream_response[\"output\"][\"text\"]\n    text = full_text[length:]\n    finish_reason = stream_response[\"output\"].get(\"finish_reason\", None)\n    return GenerationChunk(\n        text=text,\n        generation_info=dict(\n            finish_reason=finish_reason,\n        ),\n    )\ndef _create_retry_decorator(\n    llm: ChatTongyi,\n    run_manager: Optional[CallbackManagerForLLMRun] = None,\n) -> Callable[[Any], Any]:\n    def _before_sleep(retry_state: RetryCallState) -> None:\n        if run_manager:\n            run_manager.on_retry(retry_state)\n        return None\n    min_seconds = 1\n    max_seconds = 4\n    # Wait 2^x * 1 second between each retry starting with\n    # 4 seconds, then up to 10 seconds, then 10 seconds afterwards\n    return retry(\n        reraise=True,\n        stop=stop_after_attempt(llm.max_retries),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html"}
{"id": "4ec3ccb3a721-3", "text": "reraise=True,\n        stop=stop_after_attempt(llm.max_retries),\n        wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),\n        retry=(retry_if_exception_type(HTTPError)),\n        before_sleep=_before_sleep,\n    )\ndef _convert_delta_to_message_chunk(\n    _dict: Mapping[str, Any],\n    default_class: Type[BaseMessageChunk],\n    length: int,\n) -> BaseMessageChunk:\n    role = _dict.get(\"role\")\n    full_content = _dict.get(\"content\") or \"\"\n    content = full_content[length:]\n    if _dict.get(\"function_call\"):\n        additional_kwargs = {\"function_call\": dict(_dict[\"function_call\"])}\n    else:\n        additional_kwargs = {}\n    if role == \"user\" or default_class == HumanMessageChunk:\n        return HumanMessageChunk(content=content)\n    elif role == \"assistant\" or default_class == AIMessageChunk:\n        return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)\n    elif role == \"system\" or default_class == SystemMessageChunk:\n        return SystemMessageChunk(content=content)\n    elif role == \"function\" or default_class == FunctionMessageChunk:\n        return FunctionMessageChunk(content=content, name=_dict[\"name\"])\n    elif role or default_class == ChatMessageChunk:\n        return ChatMessageChunk(content=content, role=role)\n    else:\n        return default_class(content=content)\n[docs]class ChatTongyi(BaseChatModel):\n    \"\"\"Alibaba Tongyi Qwen chat models API.\n    To use, you should have the ``dashscope`` python package installed,\n    and set env ``DASHSCOPE_API_KEY`` with your API key, or pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html"}
{"id": "4ec3ccb3a721-4", "text": "and set env ``DASHSCOPE_API_KEY`` with your API key, or pass\n    it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import Tongyi\n            Tongyi_chat = ChatTongyi()\n    \"\"\"\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"dashscope_api_key\": \"DASHSCOPE_API_KEY\"}\n    @property\n    def lc_serializable(self) -> bool:\n        return True\n    client: Any  #: :meta private:\n    model_name: str = Field(default=\"qwen-turbo\", alias=\"model\")\n    \"\"\"Model name to use.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    top_p: float = 0.8\n    \"\"\"Total probability mass of tokens to consider at each step.\"\"\"\n    dashscope_api_key: Optional[str] = None\n    \"\"\"Dashscope api key provide by alicloud.\"\"\"\n    n: int = 1\n    \"\"\"How many completions to generate for each prompt.\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results or not.\"\"\"\n    max_retries: int = 10\n    \"\"\"Maximum number of retries to make when generating.\"\"\"\n    prefix_messages: List = Field(default_factory=list)\n    \"\"\"Series of messages for Chat input.\"\"\"\n    result_format: str = Field(default=\"message\")\n    \"\"\"Return result format\"\"\"\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"tongyi\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html"}
{"id": "4ec3ccb3a721-5", "text": "\"\"\"Validate that api key and python package exists in environment.\"\"\"\n        get_from_dict_or_env(values, \"dashscope_api_key\", \"DASHSCOPE_API_KEY\")\n        try:\n            import dashscope\n        except ImportError:\n            raise ImportError(\n                \"Could not import dashscope python package. \"\n                \"Please install it with `pip install dashscope --upgrade`.\"\n            )\n        try:\n            values[\"client\"] = dashscope.Generation\n        except AttributeError:\n            raise ValueError(\n                \"`dashscope` has no `Generation` attribute, this is likely \"\n                \"due to an old version of the dashscope package. Try upgrading it \"\n                \"with `pip install --upgrade dashscope`.\"\n            )\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling OpenAI API.\"\"\"\n        return {\n            \"model\": self.model_name,\n            \"top_p\": self.top_p,\n            \"stream\": self.streaming,\n            \"n\": self.n,\n            \"result_format\": self.result_format,\n            **self.model_kwargs,\n        }\n[docs]    def completion_with_retry(\n        self, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any\n    ) -> Any:\n        \"\"\"Use tenacity to retry the completion call.\"\"\"\n        retry_decorator = _create_retry_decorator(self, run_manager=run_manager)\n        @retry_decorator\n        def _completion_with_retry(**_kwargs: Any) -> Any:\n            resp = self.client.call(**_kwargs)\n            if resp.status_code == 200:\n                return resp\n            elif resp.status_code in [400, 401]:\n                raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html"}
{"id": "4ec3ccb3a721-6", "text": "elif resp.status_code in [400, 401]:\n                raise ValueError(\n                    f\"status_code: {resp.status_code} \\n \"\n                    f\"code: {resp.code} \\n message: {resp.message}\"\n                )\n            else:\n                raise HTTPError(\n                    f\"HTTP error occurred: status_code: {resp.status_code} \\n \"\n                    f\"code: {resp.code} \\n message: {resp.message}\",\n                    response=resp,\n                )\n        return _completion_with_retry(**kwargs)\n[docs]    def stream_completion_with_retry(\n        self, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any\n    ) -> Any:\n        \"\"\"Use tenacity to retry the completion call.\"\"\"\n        retry_decorator = _create_retry_decorator(self, run_manager=run_manager)\n        @retry_decorator\n        def _stream_completion_with_retry(**_kwargs: Any) -> Any:\n            return self.client.call(**_kwargs)\n        return _stream_completion_with_retry(**kwargs)\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        should_stream = stream if stream is not None else self.streaming\n        if should_stream:\n            stream_iter = self._stream(\n                messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return _generate_from_stream(stream_iter)\n        if not messages:\n            raise ValueError(\"No messages provided.\")\n        message_dicts, params = self._create_message_dicts(messages, stop)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html"}
{"id": "4ec3ccb3a721-7", "text": "message_dicts, params = self._create_message_dicts(messages, stop)\n        if message_dicts[-1][\"role\"] != \"user\":\n            raise ValueError(\"Last message should be user message.\")\n        params = {**params, **kwargs}\n        response = self.completion_with_retry(\n            messages=message_dicts, run_manager=run_manager, **params\n        )\n        return self._create_chat_result(response)\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs, \"stream\": True}\n        # Mark current chunk total length\n        length = 0\n        default_chunk_class = AIMessageChunk\n        for chunk in self.stream_completion_with_retry(\n            messages=message_dicts, run_manager=run_manager, **params\n        ):\n            if len(chunk[\"output\"][\"choices\"]) == 0:\n                continue\n            choice = chunk[\"output\"][\"choices\"][0]\n            chunk = _convert_delta_to_message_chunk(\n                choice[\"message\"], default_chunk_class, length\n            )\n            finish_reason = choice.get(\"finish_reason\")\n            generation_info = (\n                dict(finish_reason=finish_reason) if finish_reason is not None else None\n            )\n            default_chunk_class = chunk.__class__\n            chunk = ChatGenerationChunk(message=chunk, generation_info=generation_info)\n            yield chunk\n            if run_manager:\n                run_manager.on_llm_new_token(chunk.text, chunk=chunk)\n            length = len(choice[\"message\"][\"content\"])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html"}
{"id": "4ec3ccb3a721-8", "text": "length = len(choice[\"message\"][\"content\"])\n    def _create_message_dicts(\n        self, messages: List[BaseMessage], stop: Optional[List[str]]\n    ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:\n        params = self._client_params()\n        # Ensure `stop` is a list of strings\n        if stop is not None:\n            if \"stop\" in params:\n                raise ValueError(\"`stop` found in both the input and default params.\")\n            params[\"stop\"] = stop\n        message_dicts = [convert_message_to_dict(m) for m in messages]\n        return message_dicts, params\n    def _client_params(self) -> Dict[str, Any]:\n        \"\"\"Get the parameters used for the openai client.\"\"\"\n        creds: Dict[str, Any] = {\n            \"api_key\": self.dashscope_api_key,\n        }\n        return {**self._default_params, **creds}\n    def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:\n        generations = []\n        for res in response[\"output\"][\"choices\"]:\n            message = convert_dict_to_message(res[\"message\"])\n            gen = ChatGeneration(\n                message=message,\n                generation_info=dict(finish_reason=res.get(\"finish_reason\")),\n            )\n            generations.append(gen)\n        token_usage = response.get(\"usage\", {})\n        llm_output = {\"token_usage\": token_usage, \"model_name\": self.model_name}\n        return ChatResult(generations=generations, llm_output=llm_output)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html"}
{"id": "70cf7534c67a-0", "text": "Source code for langchain.chat_models.fake\n\"\"\"Fake ChatModel for testing purposes.\"\"\"\nimport asyncio\nimport time\nfrom typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Union\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel, SimpleChatModel\nfrom langchain.schema import ChatResult\nfrom langchain.schema.messages import AIMessageChunk, BaseMessage\nfrom langchain.schema.output import ChatGeneration, ChatGenerationChunk\n[docs]class FakeMessagesListChatModel(BaseChatModel):\n    \"\"\"Fake ChatModel for testing purposes.\"\"\"\n    responses: List[BaseMessage]\n    sleep: Optional[float] = None\n    i: int = 0\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        response = self.responses[self.i]\n        if self.i < len(self.responses) - 1:\n            self.i += 1\n        else:\n            self.i = 0\n        generation = ChatGeneration(message=response)\n        return ChatResult(generations=[generation])\n    @property\n    def _llm_type(self) -> str:\n        return \"fake-messages-list-chat-model\"\n[docs]class FakeListChatModel(SimpleChatModel):\n    \"\"\"Fake ChatModel for testing purposes.\"\"\"\n    responses: List\n    sleep: Optional[float] = None\n    i: int = 0\n    @property\n    def _llm_type(self) -> str:\n        return \"fake-list-chat-model\"\n    def _call(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fake.html"}
{"id": "70cf7534c67a-1", "text": "return \"fake-list-chat-model\"\n    def _call(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"First try to lookup in queries, else return 'foo' or 'bar'.\"\"\"\n        response = self.responses[self.i]\n        if self.i < len(self.responses) - 1:\n            self.i += 1\n        else:\n            self.i = 0\n        return response\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Union[List[str], None] = None,\n        run_manager: Union[CallbackManagerForLLMRun, None] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        response = self.responses[self.i]\n        if self.i < len(self.responses) - 1:\n            self.i += 1\n        else:\n            self.i = 0\n        for c in response:\n            if self.sleep is not None:\n                time.sleep(self.sleep)\n            yield ChatGenerationChunk(message=AIMessageChunk(content=c))\n    async def _astream(\n        self,\n        messages: List[BaseMessage],\n        stop: Union[List[str], None] = None,\n        run_manager: Union[AsyncCallbackManagerForLLMRun, None] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[ChatGenerationChunk]:\n        response = self.responses[self.i]\n        if self.i < len(self.responses) - 1:\n            self.i += 1\n        else:\n            self.i = 0\n        for c in response:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fake.html"}
{"id": "70cf7534c67a-2", "text": "else:\n            self.i = 0\n        for c in response:\n            if self.sleep is not None:\n                await asyncio.sleep(self.sleep)\n            yield ChatGenerationChunk(message=AIMessageChunk(content=c))\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        return {\"responses\": self.responses}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fake.html"}
{"id": "d4f6212c28df-0", "text": "Source code for langchain.chat_models.gigachat\nimport logging\nfrom typing import Any, AsyncIterator, Iterator, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import (\n    BaseChatModel,\n    _agenerate_from_stream,\n    _generate_from_stream,\n)\nfrom langchain.llms.gigachat import _BaseGigaChat\nfrom langchain.schema import ChatResult\nfrom langchain.schema.messages import (\n    AIMessage,\n    AIMessageChunk,\n    BaseMessage,\n    ChatMessage,\n    HumanMessage,\n    SystemMessage,\n)\nfrom langchain.schema.output import ChatGeneration, ChatGenerationChunk\nlogger = logging.getLogger(__name__)\ndef _convert_dict_to_message(message: Any) -> BaseMessage:\n    from gigachat.models import MessagesRole\n    if message.role == MessagesRole.SYSTEM:\n        return SystemMessage(content=message.content)\n    elif message.role == MessagesRole.USER:\n        return HumanMessage(content=message.content)\n    elif message.role == MessagesRole.ASSISTANT:\n        return AIMessage(content=message.content)\n    else:\n        raise TypeError(f\"Got unknown role {message.role} {message}\")\ndef _convert_message_to_dict(message: BaseMessage) -> Any:\n    from gigachat.models import Messages, MessagesRole\n    if isinstance(message, SystemMessage):\n        return Messages(role=MessagesRole.SYSTEM, content=message.content)\n    elif isinstance(message, HumanMessage):\n        return Messages(role=MessagesRole.USER, content=message.content)\n    elif isinstance(message, AIMessage):\n        return Messages(role=MessagesRole.ASSISTANT, content=message.content)\n    elif isinstance(message, ChatMessage):\n        return Messages(role=MessagesRole(message.role), content=message.content)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/gigachat.html"}
{"id": "d4f6212c28df-1", "text": "return Messages(role=MessagesRole(message.role), content=message.content)\n    else:\n        raise TypeError(f\"Got unknown type {message}\")\n[docs]class GigaChat(_BaseGigaChat, BaseChatModel):\n    \"\"\"`GigaChat` large language models API.\n    To use, you should pass login and password to access GigaChat API or use token.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import GigaChat\n            giga = GigaChat(credentials=..., verify_ssl_certs=False)\n    \"\"\"\n    def _build_payload(self, messages: List[BaseMessage]) -> Any:\n        from gigachat.models import Chat\n        payload = Chat(\n            messages=[_convert_message_to_dict(m) for m in messages],\n            profanity_check=self.profanity,\n        )\n        if self.temperature is not None:\n            payload.temperature = self.temperature\n        if self.max_tokens is not None:\n            payload.max_tokens = self.max_tokens\n        if self.verbose:\n            logger.info(\"Giga request: %s\", payload.dict())\n        return payload\n    def _create_chat_result(self, response: Any) -> ChatResult:\n        generations = []\n        for res in response.choices:\n            message = _convert_dict_to_message(res.message)\n            finish_reason = res.finish_reason\n            gen = ChatGeneration(\n                message=message,\n                generation_info={\"finish_reason\": finish_reason},\n            )\n            generations.append(gen)\n            if finish_reason != \"stop\":\n                logger.warning(\n                    \"Giga generation stopped with reason: %s\",\n                    finish_reason,\n                )\n            if self.verbose:\n                logger.info(\"Giga response: %s\", message.content)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/gigachat.html"}
{"id": "d4f6212c28df-2", "text": "logger.info(\"Giga response: %s\", message.content)\n        llm_output = {\"token_usage\": response.usage, \"model_name\": response.model}\n        return ChatResult(generations=generations, llm_output=llm_output)\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        should_stream = stream if stream is not None else self.streaming\n        if should_stream:\n            stream_iter = self._stream(\n                messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return _generate_from_stream(stream_iter)\n        payload = self._build_payload(messages)\n        response = self._client.chat(payload)\n        return self._create_chat_result(response)\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        should_stream = stream if stream is not None else self.streaming\n        if should_stream:\n            stream_iter = self._astream(\n                messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return await _agenerate_from_stream(stream_iter)\n        payload = self._build_payload(messages)\n        response = await self._client.achat(payload)\n        return self._create_chat_result(response)\n    def _stream(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/gigachat.html"}
{"id": "d4f6212c28df-3", "text": "return self._create_chat_result(response)\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        payload = self._build_payload(messages)\n        for chunk in self._client.stream(payload):\n            if chunk.choices:\n                content = chunk.choices[0].delta.content\n                yield ChatGenerationChunk(message=AIMessageChunk(content=content))\n                if run_manager:\n                    run_manager.on_llm_new_token(content)\n    async def _astream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[ChatGenerationChunk]:\n        payload = self._build_payload(messages)\n        async for chunk in self._client.astream(payload):\n            if chunk.choices:\n                content = chunk.choices[0].delta.content\n                yield ChatGenerationChunk(message=AIMessageChunk(content=content))\n                if run_manager:\n                    await run_manager.on_llm_new_token(content)\n[docs]    def get_num_tokens(self, text: str) -> int:\n        \"\"\"Count approximate number of tokens\"\"\"\n        return round(len(text) / 4.6)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/gigachat.html"}
{"id": "54a0fcb72306-0", "text": "Source code for langchain.chat_models.litellm\n\"\"\"Wrapper around LiteLLM's model I/O library.\"\"\"\nfrom __future__ import annotations\nimport logging\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Callable,\n    Dict,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Tuple,\n    Type,\n    Union,\n)\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import (\n    BaseChatModel,\n    _agenerate_from_stream,\n    _generate_from_stream,\n)\nfrom langchain.llms.base import create_base_retry_decorator\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema import (\n    ChatGeneration,\n    ChatResult,\n)\nfrom langchain.schema.messages import (\n    AIMessage,\n    AIMessageChunk,\n    BaseMessage,\n    BaseMessageChunk,\n    ChatMessage,\n    ChatMessageChunk,\n    FunctionMessage,\n    FunctionMessageChunk,\n    HumanMessage,\n    HumanMessageChunk,\n    SystemMessage,\n    SystemMessageChunk,\n)\nfrom langchain.schema.output import ChatGenerationChunk\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class ChatLiteLLMException(Exception):\n    \"\"\"Error with the `LiteLLM I/O` library\"\"\"\ndef _create_retry_decorator(\n    llm: ChatLiteLLM,\n    run_manager: Optional[\n        Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]\n    ] = None,\n) -> Callable[[Any], Any]:\n    \"\"\"Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html"}
{"id": "54a0fcb72306-1", "text": "\"\"\"Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions\"\"\"\n    import litellm\n    errors = [\n        litellm.Timeout,\n        litellm.APIError,\n        litellm.APIConnectionError,\n        litellm.RateLimitError,\n    ]\n    return create_base_retry_decorator(\n        error_types=errors, max_retries=llm.max_retries, run_manager=run_manager\n    )\ndef _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:\n    role = _dict[\"role\"]\n    if role == \"user\":\n        return HumanMessage(content=_dict[\"content\"])\n    elif role == \"assistant\":\n        # Fix for azure\n        # Also OpenAI returns None for tool invocations\n        content = _dict.get(\"content\", \"\") or \"\"\n        if _dict.get(\"function_call\"):\n            additional_kwargs = {\"function_call\": dict(_dict[\"function_call\"])}\n        else:\n            additional_kwargs = {}\n        return AIMessage(content=content, additional_kwargs=additional_kwargs)\n    elif role == \"system\":\n        return SystemMessage(content=_dict[\"content\"])\n    elif role == \"function\":\n        return FunctionMessage(content=_dict[\"content\"], name=_dict[\"name\"])\n    else:\n        return ChatMessage(content=_dict[\"content\"], role=role)\n[docs]async def acompletion_with_retry(\n    llm: ChatLiteLLM,\n    run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the async completion call.\"\"\"\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @retry_decorator", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html"}
{"id": "54a0fcb72306-2", "text": "@retry_decorator\n    async def _completion_with_retry(**kwargs: Any) -> Any:\n        # Use OpenAI's async api https://github.com/openai/openai-python#async-api\n        return await llm.client.acreate(**kwargs)\n    return await _completion_with_retry(**kwargs)\ndef _convert_delta_to_message_chunk(\n    _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]\n) -> BaseMessageChunk:\n    role = _dict.get(\"role\")\n    content = _dict.get(\"content\") or \"\"\n    if _dict.get(\"function_call\"):\n        additional_kwargs = {\"function_call\": dict(_dict[\"function_call\"])}\n    else:\n        additional_kwargs = {}\n    if role == \"user\" or default_class == HumanMessageChunk:\n        return HumanMessageChunk(content=content)\n    elif role == \"assistant\" or default_class == AIMessageChunk:\n        return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)\n    elif role == \"system\" or default_class == SystemMessageChunk:\n        return SystemMessageChunk(content=content)\n    elif role == \"function\" or default_class == FunctionMessageChunk:\n        return FunctionMessageChunk(content=content, name=_dict[\"name\"])\n    elif role or default_class == ChatMessageChunk:\n        return ChatMessageChunk(content=content, role=role)\n    else:\n        return default_class(content=content)\ndef _convert_message_to_dict(message: BaseMessage) -> dict:\n    if isinstance(message, ChatMessage):\n        message_dict = {\"role\": message.role, \"content\": message.content}\n    elif isinstance(message, HumanMessage):\n        message_dict = {\"role\": \"user\", \"content\": message.content}\n    elif isinstance(message, AIMessage):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html"}
{"id": "54a0fcb72306-3", "text": "elif isinstance(message, AIMessage):\n        message_dict = {\"role\": \"assistant\", \"content\": message.content}\n        if \"function_call\" in message.additional_kwargs:\n            message_dict[\"function_call\"] = message.additional_kwargs[\"function_call\"]\n    elif isinstance(message, SystemMessage):\n        message_dict = {\"role\": \"system\", \"content\": message.content}\n    elif isinstance(message, FunctionMessage):\n        message_dict = {\n            \"role\": \"function\",\n            \"content\": message.content,\n            \"name\": message.name,\n        }\n    else:\n        raise ValueError(f\"Got unknown type {message}\")\n    if \"name\" in message.additional_kwargs:\n        message_dict[\"name\"] = message.additional_kwargs[\"name\"]\n    return message_dict\n[docs]class ChatLiteLLM(BaseChatModel):\n    \"\"\"A chat model that uses the LiteLLM API.\"\"\"\n    client: Any  #: :meta private:\n    model: str = \"gpt-3.5-turbo\"\n    model_name: Optional[str] = None\n    \"\"\"Model name to use.\"\"\"\n    openai_api_key: Optional[str] = None\n    azure_api_key: Optional[str] = None\n    anthropic_api_key: Optional[str] = None\n    replicate_api_key: Optional[str] = None\n    cohere_api_key: Optional[str] = None\n    openrouter_api_key: Optional[str] = None\n    streaming: bool = False\n    api_base: Optional[str] = None\n    organization: Optional[str] = None\n    custom_llm_provider: Optional[str] = None\n    request_timeout: Optional[Union[float, Tuple[float, float]]] = None\n    temperature: Optional[float] = 1\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html"}
{"id": "54a0fcb72306-4", "text": "model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Run inference with this temperature. Must by in the closed\n       interval [0.0, 1.0].\"\"\"\n    top_p: Optional[float] = None\n    \"\"\"Decode using nucleus sampling: consider the smallest set of tokens whose\n       probability sum is at least top_p. Must be in the closed interval [0.0, 1.0].\"\"\"\n    top_k: Optional[int] = None\n    \"\"\"Decode using top-k sampling: consider the set of top_k most probable tokens.\n       Must be positive.\"\"\"\n    n: int = 1\n    \"\"\"Number of chat completions to generate for each prompt. Note that the API may\n       not return the full n completions if duplicates are generated.\"\"\"\n    max_tokens: int = 256\n    max_retries: int = 6\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling OpenAI API.\"\"\"\n        set_model_value = self.model\n        if self.model_name is not None:\n            set_model_value = self.model_name\n        return {\n            \"model\": set_model_value,\n            \"force_timeout\": self.request_timeout,\n            \"max_tokens\": self.max_tokens,\n            \"stream\": self.streaming,\n            \"n\": self.n,\n            \"temperature\": self.temperature,\n            \"custom_llm_provider\": self.custom_llm_provider,\n            **self.model_kwargs,\n        }\n    @property\n    def _client_params(self) -> Dict[str, Any]:\n        \"\"\"Get the parameters used for the openai client.\"\"\"\n        set_model_value = self.model\n        if self.model_name is not None:\n            set_model_value = self.model_name\n        self.client.api_base = self.api_base", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html"}
{"id": "54a0fcb72306-5", "text": "set_model_value = self.model_name\n        self.client.api_base = self.api_base\n        self.client.organization = self.organization\n        creds: Dict[str, Any] = {\n            \"model\": set_model_value,\n            \"force_timeout\": self.request_timeout,\n        }\n        return {**self._default_params, **creds}\n[docs]    def completion_with_retry(\n        self, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any\n    ) -> Any:\n        \"\"\"Use tenacity to retry the completion call.\"\"\"\n        retry_decorator = _create_retry_decorator(self, run_manager=run_manager)\n        @retry_decorator\n        def _completion_with_retry(**kwargs: Any) -> Any:\n            return self.client.completion(**kwargs)\n        return _completion_with_retry(**kwargs)\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate api key, python package exists, temperature, top_p, and top_k.\"\"\"\n        try:\n            import litellm\n        except ImportError:\n            raise ChatLiteLLMException(\n                \"Could not import google.generativeai python package. \"\n                \"Please install it with `pip install google-generativeai`\"\n            )\n        values[\"openai_api_key\"] = get_from_dict_or_env(\n            values, \"openai_api_key\", \"OPENAI_API_KEY\", default=\"\"\n        )\n        values[\"azure_api_key\"] = get_from_dict_or_env(\n            values, \"azure_api_key\", \"AZURE_API_KEY\", default=\"\"\n        )\n        values[\"anthropic_api_key\"] = get_from_dict_or_env(\n            values, \"anthropic_api_key\", \"ANTHROPIC_API_KEY\", default=\"\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html"}
{"id": "54a0fcb72306-6", "text": ")\n        values[\"replicate_api_key\"] = get_from_dict_or_env(\n            values, \"replicate_api_key\", \"REPLICATE_API_KEY\", default=\"\"\n        )\n        values[\"openrouter_api_key\"] = get_from_dict_or_env(\n            values, \"openrouter_api_key\", \"OPENROUTER_API_KEY\", default=\"\"\n        )\n        values[\"cohere_api_key\"] = get_from_dict_or_env(\n            values, \"cohere_api_key\", \"COHERE_API_KEY\", default=\"\"\n        )\n        values[\"huggingface_api_key\"] = get_from_dict_or_env(\n            values, \"huggingface_api_key\", \"HUGGINGFACE_API_KEY\", default=\"\"\n        )\n        values[\"together_ai_api_key\"] = get_from_dict_or_env(\n            values, \"together_ai_api_key\", \"TOGETHERAI_API_KEY\", default=\"\"\n        )\n        values[\"client\"] = litellm\n        if values[\"temperature\"] is not None and not 0 <= values[\"temperature\"] <= 1:\n            raise ValueError(\"temperature must be in the range [0.0, 1.0]\")\n        if values[\"top_p\"] is not None and not 0 <= values[\"top_p\"] <= 1:\n            raise ValueError(\"top_p must be in the range [0.0, 1.0]\")\n        if values[\"top_k\"] is not None and values[\"top_k\"] <= 0:\n            raise ValueError(\"top_k must be positive\")\n        return values\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html"}
{"id": "54a0fcb72306-7", "text": "stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        should_stream = stream if stream is not None else self.streaming\n        if should_stream:\n            stream_iter = self._stream(\n                messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return _generate_from_stream(stream_iter)\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs}\n        response = self.completion_with_retry(\n            messages=message_dicts, run_manager=run_manager, **params\n        )\n        return self._create_chat_result(response)\n    def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:\n        generations = []\n        for res in response[\"choices\"]:\n            message = _convert_dict_to_message(res[\"message\"])\n            gen = ChatGeneration(\n                message=message,\n                generation_info=dict(finish_reason=res.get(\"finish_reason\")),\n            )\n            generations.append(gen)\n        token_usage = response.get(\"usage\", {})\n        set_model_value = self.model\n        if self.model_name is not None:\n            set_model_value = self.model_name\n        llm_output = {\"token_usage\": token_usage, \"model\": set_model_value}\n        return ChatResult(generations=generations, llm_output=llm_output)\n    def _create_message_dicts(\n        self, messages: List[BaseMessage], stop: Optional[List[str]]\n    ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:\n        params = self._client_params\n        if stop is not None:\n            if \"stop\" in params:\n                raise ValueError(\"`stop` found in both the input and default params.\")\n            params[\"stop\"] = stop", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html"}
{"id": "54a0fcb72306-8", "text": "params[\"stop\"] = stop\n        message_dicts = [_convert_message_to_dict(m) for m in messages]\n        return message_dicts, params\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs, \"stream\": True}\n        default_chunk_class = AIMessageChunk\n        for chunk in self.completion_with_retry(\n            messages=message_dicts, run_manager=run_manager, **params\n        ):\n            if len(chunk[\"choices\"]) == 0:\n                continue\n            delta = chunk[\"choices\"][0][\"delta\"]\n            chunk = _convert_delta_to_message_chunk(delta, default_chunk_class)\n            default_chunk_class = chunk.__class__\n            yield ChatGenerationChunk(message=chunk)\n            if run_manager:\n                run_manager.on_llm_new_token(chunk.content)\n    async def _astream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[ChatGenerationChunk]:\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs, \"stream\": True}\n        default_chunk_class = AIMessageChunk\n        async for chunk in await acompletion_with_retry(\n            self, messages=message_dicts, run_manager=run_manager, **params\n        ):\n            if len(chunk[\"choices\"]) == 0:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html"}
{"id": "54a0fcb72306-9", "text": "):\n            if len(chunk[\"choices\"]) == 0:\n                continue\n            delta = chunk[\"choices\"][0][\"delta\"]\n            chunk = _convert_delta_to_message_chunk(delta, default_chunk_class)\n            default_chunk_class = chunk.__class__\n            yield ChatGenerationChunk(message=chunk)\n            if run_manager:\n                await run_manager.on_llm_new_token(chunk.content)\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        should_stream = stream if stream is not None else self.streaming\n        if should_stream:\n            stream_iter = self._astream(\n                messages=messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return await _agenerate_from_stream(stream_iter)\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs}\n        response = await acompletion_with_retry(\n            self, messages=message_dicts, run_manager=run_manager, **params\n        )\n        return self._create_chat_result(response)\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        set_model_value = self.model\n        if self.model_name is not None:\n            set_model_value = self.model_name\n        return {\n            \"model\": set_model_value,\n            \"temperature\": self.temperature,\n            \"top_p\": self.top_p,\n            \"top_k\": self.top_k,\n            \"n\": self.n,\n        }\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html"}
{"id": "54a0fcb72306-10", "text": "\"n\": self.n,\n        }\n    @property\n    def _llm_type(self) -> str:\n        return \"litellm-chat\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html"}
{"id": "20dbc24204c5-0", "text": "Source code for langchain.chat_models.promptlayer_openai\n\"\"\"PromptLayer wrapper.\"\"\"\nimport datetime\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.schema import ChatResult\nfrom langchain.schema.messages import BaseMessage\n[docs]class PromptLayerChatOpenAI(ChatOpenAI):\n    \"\"\"`PromptLayer` and `OpenAI` Chat large language models API.\n    To use, you should have the ``openai`` and ``promptlayer`` python\n    package installed, and the environment variable ``OPENAI_API_KEY``\n    and ``PROMPTLAYER_API_KEY`` set with your openAI API key and\n    promptlayer key respectively.\n    All parameters that can be passed to the OpenAI LLM can also\n    be passed here. The PromptLayerChatOpenAI adds to optional\n    parameters:\n        ``pl_tags``: List of strings to tag the request with.\n        ``return_pl_id``: If True, the PromptLayer request ID will be\n            returned in the ``generation_info`` field of the\n            ``Generation`` object.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import PromptLayerChatOpenAI\n            openai = PromptLayerChatOpenAI(model_name=\"gpt-3.5-turbo\")\n    \"\"\"\n    pl_tags: Optional[List[str]]\n    return_pl_id: Optional[bool] = False\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html"}
{"id": "20dbc24204c5-1", "text": "stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        \"\"\"Call ChatOpenAI generate and then call PromptLayer API to log the request.\"\"\"\n        from promptlayer.utils import get_api_key, promptlayer_api_request\n        request_start_time = datetime.datetime.now().timestamp()\n        generated_responses = super()._generate(\n            messages, stop, run_manager, stream=stream, **kwargs\n        )\n        request_end_time = datetime.datetime.now().timestamp()\n        message_dicts, params = super()._create_message_dicts(messages, stop)\n        for i, generation in enumerate(generated_responses.generations):\n            response_dict, params = super()._create_message_dicts(\n                [generation.message], stop\n            )\n            params = {**params, **kwargs}\n            pl_request_id = promptlayer_api_request(\n                \"langchain.PromptLayerChatOpenAI\",\n                \"langchain\",\n                message_dicts,\n                params,\n                self.pl_tags,\n                response_dict,\n                request_start_time,\n                request_end_time,\n                get_api_key(),\n                return_pl_id=self.return_pl_id,\n            )\n            if self.return_pl_id:\n                if generation.generation_info is None or not isinstance(\n                    generation.generation_info, dict\n                ):\n                    generation.generation_info = {}\n                generation.generation_info[\"pl_request_id\"] = pl_request_id\n        return generated_responses\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> ChatResult:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html"}
{"id": "20dbc24204c5-2", "text": "**kwargs: Any,\n    ) -> ChatResult:\n        \"\"\"Call ChatOpenAI agenerate and then call PromptLayer to log.\"\"\"\n        from promptlayer.utils import get_api_key, promptlayer_api_request_async\n        request_start_time = datetime.datetime.now().timestamp()\n        generated_responses = await super()._agenerate(\n            messages, stop, run_manager, stream=stream, **kwargs\n        )\n        request_end_time = datetime.datetime.now().timestamp()\n        message_dicts, params = super()._create_message_dicts(messages, stop)\n        for i, generation in enumerate(generated_responses.generations):\n            response_dict, params = super()._create_message_dicts(\n                [generation.message], stop\n            )\n            params = {**params, **kwargs}\n            pl_request_id = await promptlayer_api_request_async(\n                \"langchain.PromptLayerChatOpenAI.async\",\n                \"langchain\",\n                message_dicts,\n                params,\n                self.pl_tags,\n                response_dict,\n                request_start_time,\n                request_end_time,\n                get_api_key(),\n                return_pl_id=self.return_pl_id,\n            )\n            if self.return_pl_id:\n                if generation.generation_info is None or not isinstance(\n                    generation.generation_info, dict\n                ):\n                    generation.generation_info = {}\n                generation.generation_info[\"pl_request_id\"] = pl_request_id\n        return generated_responses\n    @property\n    def _llm_type(self) -> str:\n        return \"promptlayer-openai-chat\"\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        return {\n            **super()._identifying_params,\n            \"pl_tags\": self.pl_tags,\n            \"return_pl_id\": self.return_pl_id,\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html"}
{"id": "48354d66bb76-0", "text": "Source code for langchain.chat_models.mlflow_ai_gateway\nimport asyncio\nimport logging\nfrom functools import partial\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.pydantic_v1 import BaseModel, Extra\nfrom langchain.schema import (\n    ChatGeneration,\n    ChatResult,\n)\nfrom langchain.schema.messages import (\n    AIMessage,\n    BaseMessage,\n    ChatMessage,\n    FunctionMessage,\n    HumanMessage,\n    SystemMessage,\n)\nlogger = logging.getLogger(__name__)\n# Ignoring type because below is valid pydantic code\n# Unexpected keyword argument \"extra\" for \"__init_subclass__\" of \"object\"  [call-arg]\n[docs]class ChatParams(BaseModel, extra=Extra.allow):  # type: ignore[call-arg]\n    \"\"\"Parameters for the `MLflow AI Gateway` LLM.\"\"\"\n    temperature: float = 0.0\n    candidate_count: int = 1\n    \"\"\"The number of candidates to return.\"\"\"\n    stop: Optional[List[str]] = None\n    max_tokens: Optional[int] = None\n[docs]class ChatMLflowAIGateway(BaseChatModel):\n    \"\"\"`MLflow AI Gateway` chat models API.\n    To use, you should have the ``mlflow[gateway]`` python package installed.\n    For more information, see https://mlflow.org/docs/latest/gateway/index.html.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import ChatMLflowAIGateway\n            chat = ChatMLflowAIGateway(\n                gateway_uri=\"<your-mlflow-ai-gateway-uri>\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html"}
{"id": "48354d66bb76-1", "text": "gateway_uri=\"<your-mlflow-ai-gateway-uri>\",\n                route=\"<your-mlflow-ai-gateway-chat-route>\",\n                params={\n                    \"temperature\": 0.1\n                }\n            )\n    \"\"\"\n    def __init__(self, **kwargs: Any):\n        try:\n            import mlflow.gateway\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import `mlflow.gateway` module. \"\n                \"Please install it with `pip install mlflow[gateway]`.\"\n            ) from e\n        super().__init__(**kwargs)\n        if self.gateway_uri:\n            mlflow.gateway.set_gateway_uri(self.gateway_uri)\n    route: str\n    gateway_uri: Optional[str] = None\n    params: Optional[ChatParams] = None\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        params: Dict[str, Any] = {\n            \"gateway_uri\": self.gateway_uri,\n            \"route\": self.route,\n            **(self.params.dict() if self.params else {}),\n        }\n        return params\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        try:\n            import mlflow.gateway\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import `mlflow.gateway` module. \"\n                \"Please install it with `pip install mlflow[gateway]`.\"\n            ) from e\n        message_dicts = [\n            ChatMLflowAIGateway._convert_message_to_dict(message)\n            for message in messages\n        ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html"}
{"id": "48354d66bb76-2", "text": "for message in messages\n        ]\n        data: Dict[str, Any] = {\n            \"messages\": message_dicts,\n            **(self.params.dict() if self.params else {}),\n        }\n        resp = mlflow.gateway.query(self.route, data=data)\n        return ChatMLflowAIGateway._create_chat_result(resp)\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        func = partial(\n            self._generate, messages, stop=stop, run_manager=run_manager, **kwargs\n        )\n        return await asyncio.get_event_loop().run_in_executor(None, func)\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        return self._default_params\n    def _get_invocation_params(\n        self, stop: Optional[List[str]] = None, **kwargs: Any\n    ) -> Dict[str, Any]:\n        \"\"\"Get the parameters used to invoke the model FOR THE CALLBACKS.\"\"\"\n        return {\n            **self._default_params,\n            **super()._get_invocation_params(stop=stop, **kwargs),\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat model.\"\"\"\n        return \"mlflow-ai-gateway-chat\"\n    @staticmethod\n    def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:\n        role = _dict[\"role\"]\n        content = _dict[\"content\"]\n        if role == \"user\":\n            return HumanMessage(content=content)\n        elif role == \"assistant\":", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html"}
{"id": "48354d66bb76-3", "text": "return HumanMessage(content=content)\n        elif role == \"assistant\":\n            return AIMessage(content=content)\n        elif role == \"system\":\n            return SystemMessage(content=content)\n        else:\n            return ChatMessage(content=content, role=role)\n    @staticmethod\n    def _raise_functions_not_supported() -> None:\n        raise ValueError(\n            \"Function messages are not supported by the MLflow AI Gateway. Please\"\n            \" create a feature request at https://github.com/mlflow/mlflow/issues.\"\n        )\n    @staticmethod\n    def _convert_message_to_dict(message: BaseMessage) -> dict:\n        if isinstance(message, ChatMessage):\n            message_dict = {\"role\": message.role, \"content\": message.content}\n        elif isinstance(message, HumanMessage):\n            message_dict = {\"role\": \"user\", \"content\": message.content}\n        elif isinstance(message, AIMessage):\n            message_dict = {\"role\": \"assistant\", \"content\": message.content}\n        elif isinstance(message, SystemMessage):\n            message_dict = {\"role\": \"system\", \"content\": message.content}\n        elif isinstance(message, FunctionMessage):\n            raise ValueError(\n                \"Function messages are not supported by the MLflow AI Gateway. Please\"\n                \" create a feature request at https://github.com/mlflow/mlflow/issues.\"\n            )\n        else:\n            raise ValueError(f\"Got unknown message type: {message}\")\n        if \"function_call\" in message.additional_kwargs:\n            ChatMLflowAIGateway._raise_functions_not_supported()\n        if message.additional_kwargs:\n            logger.warning(\n                \"Additional message arguments are unsupported by MLflow AI Gateway \"\n                \" and will be ignored: %s\",\n                message.additional_kwargs,\n            )\n        return message_dict\n    @staticmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html"}
{"id": "48354d66bb76-4", "text": "message.additional_kwargs,\n            )\n        return message_dict\n    @staticmethod\n    def _create_chat_result(response: Mapping[str, Any]) -> ChatResult:\n        generations = []\n        for candidate in response[\"candidates\"]:\n            message = ChatMLflowAIGateway._convert_dict_to_message(candidate[\"message\"])\n            message_metadata = candidate.get(\"metadata\", {})\n            gen = ChatGeneration(\n                message=message,\n                generation_info=dict(message_metadata),\n            )\n            generations.append(gen)\n        response_metadata = response.get(\"metadata\", {})\n        return ChatResult(generations=generations, llm_output=response_metadata)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html"}
{"id": "a056541cdbde-0", "text": "Source code for langchain.chat_models.bedrock\nfrom typing import Any, Dict, Iterator, List, Optional\nfrom langchain.callbacks.manager import (\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.anthropic import convert_messages_to_prompt_anthropic\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.llms.bedrock import BedrockBase\nfrom langchain.pydantic_v1 import Extra\nfrom langchain.schema.messages import AIMessage, AIMessageChunk, BaseMessage\nfrom langchain.schema.output import ChatGeneration, ChatGenerationChunk, ChatResult\nfrom langchain.utilities.anthropic import (\n    get_num_tokens_anthropic,\n    get_token_ids_anthropic,\n)\n[docs]class ChatPromptAdapter:\n    \"\"\"Adapter class to prepare the inputs from Langchain to prompt format\n    that Chat model expects.\n    \"\"\"\n[docs]    @classmethod\n    def convert_messages_to_prompt(\n        cls, provider: str, messages: List[BaseMessage]\n    ) -> str:\n        if provider == \"anthropic\":\n            prompt = convert_messages_to_prompt_anthropic(messages=messages)\n        else:\n            raise NotImplementedError(\n                f\"Provider {provider} model does not support chat.\"\n            )\n        return prompt\n[docs]class BedrockChat(BaseChatModel, BedrockBase):\n    \"\"\"A chat model that uses the Bedrock API.\"\"\"\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat model.\"\"\"\n        return \"amazon_bedrock_chat\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this model can be serialized by Langchain.\"\"\"\n        return True\n    @property\n    def lc_attributes(self) -> Dict[str, Any]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/bedrock.html"}
{"id": "a056541cdbde-1", "text": "@property\n    def lc_attributes(self) -> Dict[str, Any]:\n        attributes: Dict[str, Any] = {}\n        print(self.region_name)\n        if self.region_name:\n            attributes[\"region_name\"] = self.region_name\n        return attributes\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        provider = self._get_provider()\n        prompt = ChatPromptAdapter.convert_messages_to_prompt(\n            provider=provider, messages=messages\n        )\n        for chunk in self._prepare_input_and_invoke_stream(\n            prompt=prompt, stop=stop, run_manager=run_manager, **kwargs\n        ):\n            delta = chunk.text\n            yield ChatGenerationChunk(message=AIMessageChunk(content=delta))\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        completion = \"\"\n        if self.streaming:\n            for chunk in self._stream(messages, stop, run_manager, **kwargs):\n                completion += chunk.text\n        else:\n            provider = self._get_provider()\n            prompt = ChatPromptAdapter.convert_messages_to_prompt(\n                provider=provider, messages=messages\n            )\n            params: Dict[str, Any] = {**kwargs}\n            if stop:\n                params[\"stop_sequences\"] = stop", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/bedrock.html"}
{"id": "a056541cdbde-2", "text": "if stop:\n                params[\"stop_sequences\"] = stop\n            completion = self._prepare_input_and_invoke(\n                prompt=prompt, stop=stop, run_manager=run_manager, **params\n            )\n        message = AIMessage(content=completion)\n        return ChatResult(generations=[ChatGeneration(message=message)])\n[docs]    def get_num_tokens(self, text: str) -> int:\n        if self._model_is_anthropic:\n            return get_num_tokens_anthropic(text)\n        else:\n            return super().get_num_tokens(text)\n[docs]    def get_token_ids(self, text: str) -> List[int]:\n        if self._model_is_anthropic:\n            return get_token_ids_anthropic(text)\n        else:\n            return super().get_token_ids(text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/bedrock.html"}
{"id": "c9ae3e0bc862-0", "text": "Source code for langchain.chat_models.base\nimport asyncio\nimport inspect\nimport warnings\nfrom abc import ABC, abstractmethod\nfrom functools import partial\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Dict,\n    Iterator,\n    List,\n    Optional,\n    Sequence,\n    cast,\n)\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManager,\n    AsyncCallbackManagerForLLMRun,\n    CallbackManager,\n    CallbackManagerForLLMRun,\n    Callbacks,\n)\nfrom langchain.globals import get_llm_cache\nfrom langchain.load.dump import dumpd, dumps\nfrom langchain.prompts.base import StringPromptValue\nfrom langchain.prompts.chat import ChatPromptValue\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema import (\n    ChatGeneration,\n    ChatResult,\n    LLMResult,\n    PromptValue,\n    RunInfo,\n)\nfrom langchain.schema.language_model import BaseLanguageModel, LanguageModelInput\nfrom langchain.schema.messages import (\n    AIMessage,\n    AnyMessage,\n    BaseMessage,\n    BaseMessageChunk,\n    HumanMessage,\n)\nfrom langchain.schema.output import ChatGenerationChunk\nfrom langchain.schema.runnable import RunnableConfig\ndef _get_verbosity() -> bool:\n    from langchain.globals import get_verbose\n    return get_verbose()\ndef _generate_from_stream(stream: Iterator[ChatGenerationChunk]) -> ChatResult:\n    generation: Optional[ChatGenerationChunk] = None\n    for chunk in stream:\n        if generation is None:\n            generation = chunk\n        else:\n            generation += chunk\n    assert generation is not None\n    return ChatResult(generations=[generation])\nasync def _agenerate_from_stream(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-1", "text": "return ChatResult(generations=[generation])\nasync def _agenerate_from_stream(\n    stream: AsyncIterator[ChatGenerationChunk],\n) -> ChatResult:\n    generation: Optional[ChatGenerationChunk] = None\n    async for chunk in stream:\n        if generation is None:\n            generation = chunk\n        else:\n            generation += chunk\n    assert generation is not None\n    return ChatResult(generations=[generation])\n[docs]class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):\n    \"\"\"Base class for Chat models.\"\"\"\n    cache: Optional[bool] = None\n    \"\"\"Whether to cache the response.\"\"\"\n    verbose: bool = Field(default_factory=_get_verbosity)\n    \"\"\"Whether to print out response text.\"\"\"\n    callbacks: Callbacks = Field(default=None, exclude=True)\n    \"\"\"Callbacks to add to the run trace.\"\"\"\n    callback_manager: Optional[BaseCallbackManager] = Field(default=None, exclude=True)\n    \"\"\"Callback manager to add to the run trace.\"\"\"\n    tags: Optional[List[str]] = Field(default=None, exclude=True)\n    \"\"\"Tags to add to the run trace.\"\"\"\n    metadata: Optional[Dict[str, Any]] = Field(default=None, exclude=True)\n    \"\"\"Metadata to add to the run trace.\"\"\"\n    @root_validator()\n    def raise_deprecation(cls, values: Dict) -> Dict:\n        \"\"\"Raise deprecation warning if callback_manager is used.\"\"\"\n        if values.get(\"callback_manager\") is not None:\n            warnings.warn(\n                \"callback_manager is deprecated. Please use callbacks instead.\",\n                DeprecationWarning,\n            )\n            values[\"callbacks\"] = values.pop(\"callback_manager\", None)\n        return values\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-2", "text": "\"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    # --- Runnable methods ---\n    @property\n    def OutputType(self) -> Any:\n        \"\"\"Get the output type for this runnable.\"\"\"\n        return AnyMessage\n    def _convert_input(self, input: LanguageModelInput) -> PromptValue:\n        if isinstance(input, PromptValue):\n            return input\n        elif isinstance(input, str):\n            return StringPromptValue(text=input)\n        elif isinstance(input, list):\n            return ChatPromptValue(messages=input)\n        else:\n            raise ValueError(\n                f\"Invalid input type {type(input)}. \"\n                \"Must be a PromptValue, str, or list of BaseMessages.\"\n            )\n[docs]    def invoke(\n        self,\n        input: LanguageModelInput,\n        config: Optional[RunnableConfig] = None,\n        *,\n        stop: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> BaseMessage:\n        config = config or {}\n        return cast(\n            ChatGeneration,\n            self.generate_prompt(\n                [self._convert_input(input)],\n                stop=stop,\n                callbacks=config.get(\"callbacks\"),\n                tags=config.get(\"tags\"),\n                metadata=config.get(\"metadata\"),\n                run_name=config.get(\"run_name\"),\n                **kwargs,\n            ).generations[0][0],\n        ).message\n[docs]    async def ainvoke(\n        self,\n        input: LanguageModelInput,\n        config: Optional[RunnableConfig] = None,\n        *,\n        stop: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> BaseMessage:\n        config = config or {}\n        llm_result = await self.agenerate_prompt(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-3", "text": "config = config or {}\n        llm_result = await self.agenerate_prompt(\n            [self._convert_input(input)],\n            stop=stop,\n            callbacks=config.get(\"callbacks\"),\n            tags=config.get(\"tags\"),\n            metadata=config.get(\"metadata\"),\n            run_name=config.get(\"run_name\"),\n            **kwargs,\n        )\n        return cast(ChatGeneration, llm_result.generations[0][0]).message\n[docs]    def stream(\n        self,\n        input: LanguageModelInput,\n        config: Optional[RunnableConfig] = None,\n        *,\n        stop: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Iterator[BaseMessageChunk]:\n        if type(self)._stream == BaseChatModel._stream:\n            # model doesn't implement streaming, so use default implementation\n            yield cast(\n                BaseMessageChunk, self.invoke(input, config=config, stop=stop, **kwargs)\n            )\n        else:\n            config = config or {}\n            messages = self._convert_input(input).to_messages()\n            params = self._get_invocation_params(stop=stop, **kwargs)\n            options = {\"stop\": stop, **kwargs}\n            callback_manager = CallbackManager.configure(\n                config.get(\"callbacks\"),\n                self.callbacks,\n                self.verbose,\n                config.get(\"tags\"),\n                self.tags,\n                config.get(\"metadata\"),\n                self.metadata,\n            )\n            (run_manager,) = callback_manager.on_chat_model_start(\n                dumpd(self),\n                [messages],\n                invocation_params=params,\n                options=options,\n                name=config.get(\"run_name\"),\n            )\n            try:\n                generation: Optional[ChatGenerationChunk] = None\n                for chunk in self._stream(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-4", "text": "for chunk in self._stream(\n                    messages, stop=stop, run_manager=run_manager, **kwargs\n                ):\n                    yield chunk.message\n                    if generation is None:\n                        generation = chunk\n                    else:\n                        generation += chunk\n                assert generation is not None\n            except BaseException as e:\n                run_manager.on_llm_error(e)\n                raise e\n            else:\n                run_manager.on_llm_end(\n                    LLMResult(generations=[[generation]]),\n                )\n[docs]    async def astream(\n        self,\n        input: LanguageModelInput,\n        config: Optional[RunnableConfig] = None,\n        *,\n        stop: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[BaseMessageChunk]:\n        if type(self)._astream == BaseChatModel._astream:\n            # model doesn't implement streaming, so use default implementation\n            yield cast(\n                BaseMessageChunk, self.invoke(input, config=config, stop=stop, **kwargs)\n            )\n        else:\n            config = config or {}\n            messages = self._convert_input(input).to_messages()\n            params = self._get_invocation_params(stop=stop, **kwargs)\n            options = {\"stop\": stop, **kwargs}\n            callback_manager = AsyncCallbackManager.configure(\n                config.get(\"callbacks\"),\n                self.callbacks,\n                self.verbose,\n                config.get(\"tags\"),\n                self.tags,\n                config.get(\"metadata\"),\n                self.metadata,\n            )\n            (run_manager,) = await callback_manager.on_chat_model_start(\n                dumpd(self),\n                [messages],\n                invocation_params=params,\n                options=options,\n                name=config.get(\"run_name\"),\n            )\n            try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-5", "text": "name=config.get(\"run_name\"),\n            )\n            try:\n                generation: Optional[ChatGenerationChunk] = None\n                async for chunk in self._astream(\n                    messages, stop=stop, run_manager=run_manager, **kwargs\n                ):\n                    yield chunk.message\n                    if generation is None:\n                        generation = chunk\n                    else:\n                        generation += chunk\n                assert generation is not None\n            except BaseException as e:\n                await run_manager.on_llm_error(e)\n                raise e\n            else:\n                await run_manager.on_llm_end(\n                    LLMResult(generations=[[generation]]),\n                )\n    # --- Custom methods ---\n    def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:\n        return {}\n    def _get_invocation_params(\n        self,\n        stop: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> dict:\n        params = self.dict()\n        params[\"stop\"] = stop\n        return {**params, **kwargs}\n    def _get_llm_string(self, stop: Optional[List[str]] = None, **kwargs: Any) -> str:\n        if self.is_lc_serializable():\n            params = {**kwargs, **{\"stop\": stop}}\n            param_string = str(sorted([(k, v) for k, v in params.items()]))\n            llm_string = dumps(self)\n            return llm_string + \"---\" + param_string\n        else:\n            params = self._get_invocation_params(stop=stop, **kwargs)\n            params = {**params, **kwargs}\n            return str(sorted([(k, v) for k, v in params.items()]))\n[docs]    def generate(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-6", "text": "[docs]    def generate(\n        self,\n        messages: List[List[BaseMessage]],\n        stop: Optional[List[str]] = None,\n        callbacks: Callbacks = None,\n        *,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        run_name: Optional[str] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Top Level call\"\"\"\n        params = self._get_invocation_params(stop=stop, **kwargs)\n        options = {\"stop\": stop}\n        callback_manager = CallbackManager.configure(\n            callbacks,\n            self.callbacks,\n            self.verbose,\n            tags,\n            self.tags,\n            metadata,\n            self.metadata,\n        )\n        run_managers = callback_manager.on_chat_model_start(\n            dumpd(self),\n            messages,\n            invocation_params=params,\n            options=options,\n            name=run_name,\n        )\n        results = []\n        for i, m in enumerate(messages):\n            try:\n                results.append(\n                    self._generate_with_cache(\n                        m,\n                        stop=stop,\n                        run_manager=run_managers[i] if run_managers else None,\n                        **kwargs,\n                    )\n                )\n            except BaseException as e:\n                if run_managers:\n                    run_managers[i].on_llm_error(e)\n                raise e\n        flattened_outputs = [\n            LLMResult(generations=[res.generations], llm_output=res.llm_output)\n            for res in results\n        ]\n        llm_output = self._combine_llm_outputs([res.llm_output for res in results])\n        generations = [res.generations for res in results]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-7", "text": "generations = [res.generations for res in results]\n        output = LLMResult(generations=generations, llm_output=llm_output)\n        if run_managers:\n            run_infos = []\n            for manager, flattened_output in zip(run_managers, flattened_outputs):\n                manager.on_llm_end(flattened_output)\n                run_infos.append(RunInfo(run_id=manager.run_id))\n            output.run = run_infos\n        return output\n[docs]    async def agenerate(\n        self,\n        messages: List[List[BaseMessage]],\n        stop: Optional[List[str]] = None,\n        callbacks: Callbacks = None,\n        *,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        run_name: Optional[str] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Top Level call\"\"\"\n        params = self._get_invocation_params(stop=stop, **kwargs)\n        options = {\"stop\": stop}\n        callback_manager = AsyncCallbackManager.configure(\n            callbacks,\n            self.callbacks,\n            self.verbose,\n            tags,\n            self.tags,\n            metadata,\n            self.metadata,\n        )\n        run_managers = await callback_manager.on_chat_model_start(\n            dumpd(self),\n            messages,\n            invocation_params=params,\n            options=options,\n            name=run_name,\n        )\n        results = await asyncio.gather(\n            *[\n                self._agenerate_with_cache(\n                    m,\n                    stop=stop,\n                    run_manager=run_managers[i] if run_managers else None,\n                    **kwargs,\n                )\n                for i, m in enumerate(messages)\n            ],\n            return_exceptions=True,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-8", "text": "],\n            return_exceptions=True,\n        )\n        exceptions = []\n        for i, res in enumerate(results):\n            if isinstance(res, BaseException):\n                if run_managers:\n                    await run_managers[i].on_llm_error(res)\n                exceptions.append(res)\n        if exceptions:\n            if run_managers:\n                await asyncio.gather(\n                    *[\n                        run_manager.on_llm_end(\n                            LLMResult(\n                                generations=[res.generations], llm_output=res.llm_output\n                            )\n                        )\n                        for run_manager, res in zip(run_managers, results)\n                        if not isinstance(res, Exception)\n                    ]\n                )\n            raise exceptions[0]\n        flattened_outputs = [\n            LLMResult(generations=[res.generations], llm_output=res.llm_output)\n            for res in results\n        ]\n        llm_output = self._combine_llm_outputs([res.llm_output for res in results])\n        generations = [res.generations for res in results]\n        output = LLMResult(generations=generations, llm_output=llm_output)\n        await asyncio.gather(\n            *[\n                run_manager.on_llm_end(flattened_output)\n                for run_manager, flattened_output in zip(\n                    run_managers, flattened_outputs\n                )\n            ]\n        )\n        if run_managers:\n            output.run = [\n                RunInfo(run_id=run_manager.run_id) for run_manager in run_managers\n            ]\n        return output\n[docs]    def generate_prompt(\n        self,\n        prompts: List[PromptValue],\n        stop: Optional[List[str]] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> LLMResult:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-9", "text": "**kwargs: Any,\n    ) -> LLMResult:\n        prompt_messages = [p.to_messages() for p in prompts]\n        return self.generate(prompt_messages, stop=stop, callbacks=callbacks, **kwargs)\n[docs]    async def agenerate_prompt(\n        self,\n        prompts: List[PromptValue],\n        stop: Optional[List[str]] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        prompt_messages = [p.to_messages() for p in prompts]\n        return await self.agenerate(\n            prompt_messages, stop=stop, callbacks=callbacks, **kwargs\n        )\n    def _generate_with_cache(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        new_arg_supported = inspect.signature(self._generate).parameters.get(\n            \"run_manager\"\n        )\n        disregard_cache = self.cache is not None and not self.cache\n        llm_cache = get_llm_cache()\n        if llm_cache is None or disregard_cache:\n            # This happens when langchain.cache is None, but self.cache is True\n            if self.cache is not None and self.cache:\n                raise ValueError(\n                    \"Asked to cache, but no cache found at `langchain.cache`.\"\n                )\n            if new_arg_supported:\n                return self._generate(\n                    messages, stop=stop, run_manager=run_manager, **kwargs\n                )\n            else:\n                return self._generate(messages, stop=stop, **kwargs)\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-10", "text": "return self._generate(messages, stop=stop, **kwargs)\n        else:\n            llm_string = self._get_llm_string(stop=stop, **kwargs)\n            prompt = dumps(messages)\n            cache_val = llm_cache.lookup(prompt, llm_string)\n            if isinstance(cache_val, list):\n                return ChatResult(generations=cache_val)\n            else:\n                if new_arg_supported:\n                    result = self._generate(\n                        messages, stop=stop, run_manager=run_manager, **kwargs\n                    )\n                else:\n                    result = self._generate(messages, stop=stop, **kwargs)\n                llm_cache.update(prompt, llm_string, result.generations)\n                return result\n    async def _agenerate_with_cache(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        new_arg_supported = inspect.signature(self._agenerate).parameters.get(\n            \"run_manager\"\n        )\n        disregard_cache = self.cache is not None and not self.cache\n        llm_cache = get_llm_cache()\n        if llm_cache is None or disregard_cache:\n            # This happens when langchain.cache is None, but self.cache is True\n            if self.cache is not None and self.cache:\n                raise ValueError(\n                    \"Asked to cache, but no cache found at `langchain.cache`.\"\n                )\n            if new_arg_supported:\n                return await self._agenerate(\n                    messages, stop=stop, run_manager=run_manager, **kwargs\n                )\n            else:\n                return await self._agenerate(messages, stop=stop, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-11", "text": "return await self._agenerate(messages, stop=stop, **kwargs)\n        else:\n            llm_string = self._get_llm_string(stop=stop, **kwargs)\n            prompt = dumps(messages)\n            cache_val = llm_cache.lookup(prompt, llm_string)\n            if isinstance(cache_val, list):\n                return ChatResult(generations=cache_val)\n            else:\n                if new_arg_supported:\n                    result = await self._agenerate(\n                        messages, stop=stop, run_manager=run_manager, **kwargs\n                    )\n                else:\n                    result = await self._agenerate(messages, stop=stop, **kwargs)\n                llm_cache.update(prompt, llm_string, result.generations)\n                return result\n    @abstractmethod\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        \"\"\"Top Level call\"\"\"\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        \"\"\"Top Level call\"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, partial(self._generate, **kwargs), messages, stop, run_manager\n        )\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-12", "text": "**kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        raise NotImplementedError()\n    def _astream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[ChatGenerationChunk]:\n        raise NotImplementedError()\n[docs]    def __call__(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> BaseMessage:\n        generation = self.generate(\n            [messages], stop=stop, callbacks=callbacks, **kwargs\n        ).generations[0][0]\n        if isinstance(generation, ChatGeneration):\n            return generation.message\n        else:\n            raise ValueError(\"Unexpected generation type\")\n    async def _call_async(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> BaseMessage:\n        result = await self.agenerate(\n            [messages], stop=stop, callbacks=callbacks, **kwargs\n        )\n        generation = result.generations[0][0]\n        if isinstance(generation, ChatGeneration):\n            return generation.message\n        else:\n            raise ValueError(\"Unexpected generation type\")\n[docs]    def call_as_llm(\n        self, message: str, stop: Optional[List[str]] = None, **kwargs: Any\n    ) -> str:\n        return self.predict(message, stop=stop, **kwargs)\n[docs]    def predict(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-13", "text": "[docs]    def predict(\n        self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any\n    ) -> str:\n        if stop is None:\n            _stop = None\n        else:\n            _stop = list(stop)\n        result = self([HumanMessage(content=text)], stop=_stop, **kwargs)\n        if isinstance(result.content, str):\n            return result.content\n        else:\n            raise ValueError(\"Cannot use predict when output is not a string.\")\n[docs]    def predict_messages(\n        self,\n        messages: List[BaseMessage],\n        *,\n        stop: Optional[Sequence[str]] = None,\n        **kwargs: Any,\n    ) -> BaseMessage:\n        if stop is None:\n            _stop = None\n        else:\n            _stop = list(stop)\n        return self(messages, stop=_stop, **kwargs)\n[docs]    async def apredict(\n        self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any\n    ) -> str:\n        if stop is None:\n            _stop = None\n        else:\n            _stop = list(stop)\n        result = await self._call_async(\n            [HumanMessage(content=text)], stop=_stop, **kwargs\n        )\n        if isinstance(result.content, str):\n            return result.content\n        else:\n            raise ValueError(\"Cannot use predict when output is not a string.\")\n[docs]    async def apredict_messages(\n        self,\n        messages: List[BaseMessage],\n        *,\n        stop: Optional[Sequence[str]] = None,\n        **kwargs: Any,\n    ) -> BaseMessage:\n        if stop is None:\n            _stop = None\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-14", "text": "if stop is None:\n            _stop = None\n        else:\n            _stop = list(stop)\n        return await self._call_async(messages, stop=_stop, **kwargs)\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {}\n    @property\n    @abstractmethod\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat model.\"\"\"\n[docs]    def dict(self, **kwargs: Any) -> Dict:\n        \"\"\"Return a dictionary of the LLM.\"\"\"\n        starter_dict = dict(self._identifying_params)\n        starter_dict[\"_type\"] = self._llm_type\n        return starter_dict\n[docs]class SimpleChatModel(BaseChatModel):\n    \"\"\"Simple Chat Model.\"\"\"\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        output_str = self._call(messages, stop=stop, run_manager=run_manager, **kwargs)\n        message = AIMessage(content=output_str)\n        generation = ChatGeneration(message=message)\n        return ChatResult(generations=[generation])\n    @abstractmethod\n    def _call(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Simpler interface.\"\"\"\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "c9ae3e0bc862-15", "text": "messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        func = partial(\n            self._generate, messages, stop=stop, run_manager=run_manager, **kwargs\n        )\n        return await asyncio.get_event_loop().run_in_executor(None, func)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html"}
{"id": "43c7db9c9a0c-0", "text": "Source code for langchain.chat_models.pai_eas_endpoint\nimport asyncio\nimport json\nimport logging\nfrom functools import partial\nfrom typing import Any, AsyncIterator, Dict, List, Optional, cast\nimport requests\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import ChatGeneration, ChatResult\nfrom langchain.schema.messages import (\n    AIMessage,\n    AIMessageChunk,\n    BaseMessage,\n    ChatMessage,\n    HumanMessage,\n    SystemMessage,\n)\nfrom langchain.schema.output import ChatGenerationChunk\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class PaiEasChatEndpoint(BaseChatModel):\n    \"\"\"Eas LLM Service chat model API.\n        To use, must have a deployed eas chat llm service on AliCloud. One can set the\n    environment variable ``eas_service_url`` and ``eas_service_token`` set with your eas\n    service url and service token.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import PaiEasChatEndpoint\n            eas_chat_endpoint = PaiEasChatEndpoint(\n                eas_service_url=\"your_service_url\",\n                eas_service_token=\"your_service_token\"\n            )\n    \"\"\"\n    \"\"\"PAI-EAS Service URL\"\"\"\n    eas_service_url: str\n    \"\"\"PAI-EAS Service TOKEN\"\"\"\n    eas_service_token: str\n    \"\"\"PAI-EAS Service Infer Params\"\"\"\n    max_new_tokens: Optional[int] = 512\n    temperature: Optional[float] = 0.8", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html"}
{"id": "43c7db9c9a0c-1", "text": "temperature: Optional[float] = 0.8\n    top_p: Optional[float] = 0.1\n    top_k: Optional[int] = 10\n    do_sample: Optional[bool] = False\n    use_cache: Optional[bool] = True\n    stop_sequences: Optional[List[str]] = None\n    \"\"\"Enable stream chat mode.\"\"\"\n    streaming: bool = False\n    \"\"\"Key/value arguments to pass to the model. Reserved for future use\"\"\"\n    model_kwargs: Optional[dict] = None\n    version: Optional[str] = \"2.0\"\n    timeout: Optional[int] = 5000\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"eas_service_url\"] = get_from_dict_or_env(\n            values, \"eas_service_url\", \"EAS_SERVICE_URL\"\n        )\n        values[\"eas_service_token\"] = get_from_dict_or_env(\n            values, \"eas_service_token\", \"EAS_SERVICE_TOKEN\"\n        )\n        return values\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {\n            \"eas_service_url\": self.eas_service_url,\n            \"eas_service_token\": self.eas_service_token,\n            **{\"model_kwargs\": _model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"pai_eas_chat_endpoint\"\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Cohere API.\"\"\"\n        return {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html"}
{"id": "43c7db9c9a0c-2", "text": "\"\"\"Get the default parameters for calling Cohere API.\"\"\"\n        return {\n            \"max_new_tokens\": self.max_new_tokens,\n            \"temperature\": self.temperature,\n            \"top_k\": self.top_k,\n            \"top_p\": self.top_p,\n            \"stop_sequences\": [],\n            \"do_sample\": self.do_sample,\n            \"use_cache\": self.use_cache,\n        }\n    def _invocation_params(\n        self, stop_sequences: Optional[List[str]], **kwargs: Any\n    ) -> dict:\n        params = self._default_params\n        if self.model_kwargs:\n            params.update(self.model_kwargs)\n        if self.stop_sequences is not None and stop_sequences is not None:\n            raise ValueError(\"`stop` found in both the input and default params.\")\n        elif self.stop_sequences is not None:\n            params[\"stop\"] = self.stop_sequences\n        else:\n            params[\"stop\"] = stop_sequences\n        return {**params, **kwargs}\n[docs]    def format_request_payload(\n        self, messages: List[BaseMessage], **model_kwargs: Any\n    ) -> dict:\n        prompt: Dict[str, Any] = {}\n        user_content: List[str] = []\n        assistant_content: List[str] = []\n        for message in messages:\n            \"\"\"Converts message to a dict according to role\"\"\"\n            content = cast(str, message.content)\n            if isinstance(message, HumanMessage):\n                user_content = user_content + [content]\n            elif isinstance(message, AIMessage):\n                assistant_content = assistant_content + [content]\n            elif isinstance(message, SystemMessage):\n                prompt[\"system_prompt\"] = content\n            elif isinstance(message, ChatMessage) and message.role in [\n                \"user\",\n                \"assistant\",\n                \"system\",\n            ]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html"}
{"id": "43c7db9c9a0c-3", "text": "\"user\",\n                \"assistant\",\n                \"system\",\n            ]:\n                if message.role == \"system\":\n                    prompt[\"system_prompt\"] = content\n                elif message.role == \"user\":\n                    user_content = user_content + [content]\n                elif message.role == \"assistant\":\n                    assistant_content = assistant_content + [content]\n            else:\n                supported = \",\".join([role for role in [\"user\", \"assistant\", \"system\"]])\n                raise ValueError(\n                    f\"\"\"Received unsupported role. \n                    Supported roles for the LLaMa Foundation Model: {supported}\"\"\"\n                )\n        prompt[\"prompt\"] = user_content[len(user_content) - 1]\n        history = [\n            history_item\n            for _, history_item in enumerate(zip(user_content[:-1], assistant_content))\n        ]\n        prompt[\"history\"] = history\n        return {**prompt, **model_kwargs}\n    def _format_response_payload(\n        self, output: bytes, stop_sequences: Optional[List[str]]\n    ) -> str:\n        \"\"\"Formats response\"\"\"\n        try:\n            text = json.loads(output)[\"response\"]\n            if stop_sequences:\n                text = enforce_stop_tokens(text, stop_sequences)\n            return text\n        except Exception as e:\n            if isinstance(e, json.decoder.JSONDecodeError):\n                return output.decode(\"utf-8\")\n            raise e\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        output_str = self._call(messages, stop=stop, run_manager=run_manager, **kwargs)\n        message = AIMessage(content=output_str)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html"}
{"id": "43c7db9c9a0c-4", "text": "message = AIMessage(content=output_str)\n        generation = ChatGeneration(message=message)\n        return ChatResult(generations=[generation])\n    def _call(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        params = self._invocation_params(stop, **kwargs)\n        request_payload = self.format_request_payload(messages, **params)\n        response_payload = self._call_eas(request_payload)\n        generated_text = self._format_response_payload(response_payload, params[\"stop\"])\n        if run_manager:\n            run_manager.on_llm_new_token(generated_text)\n        return generated_text\n    def _call_eas(self, query_body: dict) -> Any:\n        \"\"\"Generate text from the eas service.\"\"\"\n        headers = {\n            \"Content-Type\": \"application/json\",\n            \"Accept\": \"application/json\",\n            \"Authorization\": f\"{self.eas_service_token}\",\n        }\n        # make request\n        response = requests.post(\n            self.eas_service_url, headers=headers, json=query_body, timeout=self.timeout\n        )\n        if response.status_code != 200:\n            raise Exception(\n                f\"Request failed with status code {response.status_code}\"\n                f\" and message {response.text}\"\n            )\n        return response.text\n    def _call_eas_stream(self, query_body: dict) -> Any:\n        \"\"\"Generate text from the eas service.\"\"\"\n        headers = {\n            \"Content-Type\": \"application/json\",\n            \"Accept\": \"application/json\",\n            \"Authorization\": f\"{self.eas_service_token}\",\n        }\n        # make request\n        response = requests.post(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html"}
{"id": "43c7db9c9a0c-5", "text": "}\n        # make request\n        response = requests.post(\n            self.eas_service_url, headers=headers, json=query_body, timeout=self.timeout\n        )\n        if response.status_code != 200:\n            raise Exception(\n                f\"Request failed with status code {response.status_code}\"\n                f\" and message {response.text}\"\n            )\n        return response\n    def _convert_chunk_to_message_message(\n        self,\n        chunk: str,\n    ) -> AIMessageChunk:\n        data = json.loads(chunk.encode(\"utf-8\"))\n        return AIMessageChunk(content=data.get(\"response\", \"\"))\n    async def _astream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[ChatGenerationChunk]:\n        params = self._invocation_params(stop, **kwargs)\n        request_payload = self.format_request_payload(messages, **params)\n        request_payload[\"use_stream_chat\"] = True\n        response = self._call_eas_stream(request_payload)\n        for chunk in response.iter_lines(\n            chunk_size=8192, decode_unicode=False, delimiter=b\"\\0\"\n        ):\n            if chunk:\n                content = self._convert_chunk_to_message_message(chunk)\n                # identify stop sequence in generated text, if any\n                stop_seq_found: Optional[str] = None\n                for stop_seq in params[\"stop\"]:\n                    if stop_seq in content.content:\n                        stop_seq_found = stop_seq\n                # identify text to yield\n                text: Optional[str] = None\n                if stop_seq_found:\n                    content.content = content.content[\n                        : content.content.index(stop_seq_found)\n                    ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html"}
{"id": "43c7db9c9a0c-6", "text": ": content.content.index(stop_seq_found)\n                    ]\n                # yield text, if any\n                if text:\n                    if run_manager:\n                        await run_manager.on_llm_new_token(cast(str, content.content))\n                    yield ChatGenerationChunk(message=content)\n                # break if stop sequence found\n                if stop_seq_found:\n                    break\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        if stream if stream is not None else self.streaming:\n            generation: Optional[ChatGenerationChunk] = None\n            async for chunk in self._astream(\n                messages=messages, stop=stop, run_manager=run_manager, **kwargs\n            ):\n                generation = chunk\n            assert generation is not None\n            return ChatResult(generations=[generation])\n        func = partial(\n            self._generate, messages, stop=stop, run_manager=run_manager, **kwargs\n        )\n        return await asyncio.get_event_loop().run_in_executor(None, func)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html"}
{"id": "be82e6eb3e0a-0", "text": "Source code for langchain.chat_models.ernie\nimport logging\nimport threading\nfrom typing import Any, Dict, List, Mapping, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema import (\n    AIMessage,\n    BaseMessage,\n    ChatGeneration,\n    ChatMessage,\n    ChatResult,\n    HumanMessage,\n)\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\ndef _convert_message_to_dict(message: BaseMessage) -> dict:\n    if isinstance(message, ChatMessage):\n        message_dict = {\"role\": message.role, \"content\": message.content}\n    elif isinstance(message, HumanMessage):\n        message_dict = {\"role\": \"user\", \"content\": message.content}\n    elif isinstance(message, AIMessage):\n        message_dict = {\"role\": \"assistant\", \"content\": message.content}\n    else:\n        raise ValueError(f\"Got unknown type {message}\")\n    return message_dict\n[docs]class ErnieBotChat(BaseChatModel):\n    \"\"\"`ERNIE-Bot` large language model.\n    ERNIE-Bot is a large language model developed by Baidu,\n    covering a huge amount of Chinese data.\n    To use, you should have the `ernie_client_id` and `ernie_client_secret` set,\n    or set the environment variable `ERNIE_CLIENT_ID` and `ERNIE_CLIENT_SECRET`.\n    Note:\n    access_token will be automatically generated based on client_id and client_secret,\n    and will be regenerated after expiration (30 days).\n    Default model is `ERNIE-Bot-turbo`,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html"}
{"id": "be82e6eb3e0a-1", "text": "Default model is `ERNIE-Bot-turbo`,\n    currently supported models are `ERNIE-Bot-turbo`, `ERNIE-Bot`\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import ErnieBotChat\n            chat = ErnieBotChat(model_name='ERNIE-Bot')\n    \"\"\"\n    ernie_api_base: Optional[str] = None\n    \"\"\"Baidu application custom endpoints\"\"\"\n    ernie_client_id: Optional[str] = None\n    \"\"\"Baidu application client id\"\"\"\n    ernie_client_secret: Optional[str] = None\n    \"\"\"Baidu application client secret\"\"\"\n    access_token: Optional[str] = None\n    \"\"\"access token is generated by client id and client secret, \n    setting this value directly will cause an error\"\"\"\n    model_name: str = \"ERNIE-Bot-turbo\"\n    \"\"\"model name of ernie, default is `ERNIE-Bot-turbo`.\n      Currently supported `ERNIE-Bot-turbo`, `ERNIE-Bot`\"\"\"\n    request_timeout: Optional[int] = 60\n    \"\"\"request timeout for chat http requests\"\"\"\n    streaming: Optional[bool] = False\n    \"\"\"streaming mode. not supported yet.\"\"\"\n    top_p: Optional[float] = 0.8\n    temperature: Optional[float] = 0.95\n    penalty_score: Optional[float] = 1\n    _lock = threading.Lock()\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        values[\"ernie_api_base\"] = get_from_dict_or_env(\n            values, \"ernie_api_base\", \"ERNIE_API_BASE\", \"https://aip.baidubce.com\"\n        )\n        values[\"ernie_client_id\"] = get_from_dict_or_env(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html"}
{"id": "be82e6eb3e0a-2", "text": ")\n        values[\"ernie_client_id\"] = get_from_dict_or_env(\n            values,\n            \"ernie_client_id\",\n            \"ERNIE_CLIENT_ID\",\n        )\n        values[\"ernie_client_secret\"] = get_from_dict_or_env(\n            values,\n            \"ernie_client_secret\",\n            \"ERNIE_CLIENT_SECRET\",\n        )\n        return values\n    def _chat(self, payload: object) -> dict:\n        base_url = f\"{self.ernie_api_base}/rpc/2.0/ai_custom/v1/wenxinworkshop/chat\"\n        model_paths = {\n            \"ERNIE-Bot-turbo\": \"eb-instant\",\n            \"ERNIE-Bot\": \"completions\",\n            \"ERNIE-Bot-4\": \"completions_pro\",\n            \"BLOOMZ-7B\": \"bloomz_7b1\",\n            \"Llama-2-7b-chat\": \"llama_2_7b\",\n            \"Llama-2-13b-chat\": \"llama_2_13b\",\n            \"Llama-2-70b-chat\": \"llama_2_70b\",\n        }\n        if self.model_name in model_paths:\n            url = f\"{base_url}/{model_paths[self.model_name]}\"\n        else:\n            raise ValueError(f\"Got unknown model_name {self.model_name}\")\n        resp = requests.post(\n            url,\n            timeout=self.request_timeout,\n            headers={\n                \"Content-Type\": \"application/json\",\n            },\n            params={\"access_token\": self.access_token},\n            json=payload,\n        )\n        return resp.json()\n    def _refresh_access_token_with_lock(self) -> None:\n        with self._lock:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html"}
{"id": "be82e6eb3e0a-3", "text": "with self._lock:\n            logger.debug(\"Refreshing access token\")\n            base_url: str = f\"{self.ernie_api_base}/oauth/2.0/token\"\n            resp = requests.post(\n                base_url,\n                timeout=10,\n                headers={\n                    \"Content-Type\": \"application/json\",\n                    \"Accept\": \"application/json\",\n                },\n                params={\n                    \"grant_type\": \"client_credentials\",\n                    \"client_id\": self.ernie_client_id,\n                    \"client_secret\": self.ernie_client_secret,\n                },\n            )\n            self.access_token = str(resp.json().get(\"access_token\"))\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        if self.streaming:\n            raise ValueError(\"`streaming` option currently unsupported.\")\n        if not self.access_token:\n            self._refresh_access_token_with_lock()\n        payload = {\n            \"messages\": [_convert_message_to_dict(m) for m in messages],\n            \"top_p\": self.top_p,\n            \"temperature\": self.temperature,\n            \"penalty_score\": self.penalty_score,\n            **kwargs,\n        }\n        logger.debug(f\"Payload for ernie api is {payload}\")\n        resp = self._chat(payload)\n        if resp.get(\"error_code\"):\n            if resp.get(\"error_code\") == 111:\n                logger.debug(\"access_token expired, refresh it\")\n                self._refresh_access_token_with_lock()\n                resp = self._chat(payload)\n            else:\n                raise ValueError(f\"Error from ErnieChat api response: {resp}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html"}
{"id": "be82e6eb3e0a-4", "text": "raise ValueError(f\"Error from ErnieChat api response: {resp}\")\n        return self._create_chat_result(resp)\n    def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:\n        generations = [\n            ChatGeneration(message=AIMessage(content=response.get(\"result\")))\n        ]\n        token_usage = response.get(\"usage\", {})\n        llm_output = {\"token_usage\": token_usage, \"model_name\": self.model_name}\n        return ChatResult(generations=generations, llm_output=llm_output)\n    @property\n    def _llm_type(self) -> str:\n        return \"ernie-bot-chat\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html"}
{"id": "197e4fd60a2b-0", "text": "Source code for langchain.chat_models.konko\n\"\"\"KonkoAI chat wrapper.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport os\nfrom typing import (\n    Any,\n    Dict,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Set,\n    Tuple,\n    Union,\n)\nimport requests\nfrom langchain.adapters.openai import convert_dict_to_message, convert_message_to_dict\nfrom langchain.callbacks.manager import (\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel, _generate_from_stream\nfrom langchain.chat_models.openai import _convert_delta_to_message_chunk\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema import ChatGeneration, ChatResult\nfrom langchain.schema.messages import AIMessageChunk, BaseMessage\nfrom langchain.schema.output import ChatGenerationChunk\nfrom langchain.utils import get_from_dict_or_env\nDEFAULT_API_BASE = \"https://api.konko.ai/v1\"\nDEFAULT_MODEL = \"meta-llama/Llama-2-13b-chat-hf\"\nlogger = logging.getLogger(__name__)\n[docs]class ChatKonko(BaseChatModel):\n    \"\"\"`ChatKonko` Chat large language models API.\n    To use, you should have the ``konko`` python package installed, and the\n    environment variable ``KONKO_API_KEY`` and ``OPENAI_API_KEY`` set with your API key.\n    Any parameters that are valid to be passed to the konko.create call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import ChatKonko\n            llm = ChatKonko(model=\"meta-llama/Llama-2-13b-chat-hf\")\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html"}
{"id": "197e4fd60a2b-1", "text": "\"\"\"\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"konko_api_key\": \"KONKO_API_KEY\", \"openai_api_key\": \"OPENAI_API_KEY\"}\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this model can be serialized by Langchain.\"\"\"\n        return True\n    client: Any = None  #: :meta private:\n    model: str = Field(default=DEFAULT_MODEL, alias=\"model\")\n    \"\"\"Model name to use.\"\"\"\n    temperature: float = 0.7\n    \"\"\"What sampling temperature to use.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not explicitly specified.\"\"\"\n    openai_api_key: Optional[str] = None\n    konko_api_key: Optional[str] = None\n    request_timeout: Optional[Union[float, Tuple[float, float]]] = None\n    \"\"\"Timeout for requests to Konko completion API.\"\"\"\n    max_retries: int = 6\n    \"\"\"Maximum number of retries to make when generating.\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results or not.\"\"\"\n    n: int = 1\n    \"\"\"Number of chat completions to generate for each prompt.\"\"\"\n    max_tokens: int = 20\n    \"\"\"Maximum number of tokens to generate.\"\"\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"konko_api_key\"] = get_from_dict_or_env(\n            values, \"konko_api_key\", \"KONKO_API_KEY\"\n        )\n        try:\n            import konko\n        except ImportError:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html"}
{"id": "197e4fd60a2b-2", "text": "try:\n            import konko\n        except ImportError:\n            raise ValueError(\n                \"Could not import konko python package. \"\n                \"Please install it with `pip install konko`.\"\n            )\n        try:\n            values[\"client\"] = konko.ChatCompletion\n        except AttributeError:\n            raise ValueError(\n                \"`konko` has no `ChatCompletion` attribute, this is likely \"\n                \"due to an old version of the konko package. Try upgrading it \"\n                \"with `pip install --upgrade konko`.\"\n            )\n        if values[\"n\"] < 1:\n            raise ValueError(\"n must be at least 1.\")\n        if values[\"n\"] > 1 and values[\"streaming\"]:\n            raise ValueError(\"n must be 1 when streaming.\")\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Konko API.\"\"\"\n        return {\n            \"model\": self.model,\n            \"request_timeout\": self.request_timeout,\n            \"max_tokens\": self.max_tokens,\n            \"stream\": self.streaming,\n            \"n\": self.n,\n            \"temperature\": self.temperature,\n            **self.model_kwargs,\n        }\n[docs]    @staticmethod\n    def get_available_models(\n        konko_api_key: Optional[str] = None,\n        openai_api_key: Optional[str] = None,\n        konko_api_base: str = DEFAULT_API_BASE,\n    ) -> Set[str]:\n        \"\"\"Get available models from Konko API.\"\"\"\n        # Try to retrieve the OpenAI API key if it's not passed as an argument\n        if not openai_api_key:\n            try:\n                openai_api_key = os.environ[\"OPENAI_API_KEY\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html"}
{"id": "197e4fd60a2b-3", "text": "try:\n                openai_api_key = os.environ[\"OPENAI_API_KEY\"]\n            except KeyError:\n                pass  # It's okay if it's not set, we just won't use it\n        # Try to retrieve the Konko API key if it's not passed as an argument\n        if not konko_api_key:\n            try:\n                konko_api_key = os.environ[\"KONKO_API_KEY\"]\n            except KeyError:\n                raise ValueError(\n                    \"Konko API key must be passed as keyword argument or \"\n                    \"set in environment variable KONKO_API_KEY.\"\n                )\n        models_url = f\"{konko_api_base}/models\"\n        headers = {\n            \"Authorization\": f\"Bearer {konko_api_key}\",\n        }\n        if openai_api_key:\n            headers[\"X-OpenAI-Api-Key\"] = openai_api_key\n        models_response = requests.get(models_url, headers=headers)\n        if models_response.status_code != 200:\n            raise ValueError(\n                f\"Error getting models from {models_url}: \"\n                f\"{models_response.status_code}\"\n            )\n        return {model[\"id\"] for model in models_response.json()[\"data\"]}\n[docs]    def completion_with_retry(\n        self, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any\n    ) -> Any:\n        def _completion_with_retry(**kwargs: Any) -> Any:\n            return self.client.create(**kwargs)\n        return _completion_with_retry(**kwargs)\n    def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:\n        overall_token_usage: dict = {}\n        for output in llm_outputs:\n            if output is None:\n                # Happens in streaming\n                continue", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html"}
{"id": "197e4fd60a2b-4", "text": "if output is None:\n                # Happens in streaming\n                continue\n            token_usage = output[\"token_usage\"]\n            for k, v in token_usage.items():\n                if k in overall_token_usage:\n                    overall_token_usage[k] += v\n                else:\n                    overall_token_usage[k] = v\n        return {\"token_usage\": overall_token_usage, \"model_name\": self.model}\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs, \"stream\": True}\n        default_chunk_class = AIMessageChunk\n        for chunk in self.completion_with_retry(\n            messages=message_dicts, run_manager=run_manager, **params\n        ):\n            if len(chunk[\"choices\"]) == 0:\n                continue\n            choice = chunk[\"choices\"][0]\n            chunk = _convert_delta_to_message_chunk(\n                choice[\"delta\"], default_chunk_class\n            )\n            finish_reason = choice.get(\"finish_reason\")\n            generation_info = (\n                dict(finish_reason=finish_reason) if finish_reason is not None else None\n            )\n            default_chunk_class = chunk.__class__\n            chunk = ChatGenerationChunk(message=chunk, generation_info=generation_info)\n            yield chunk\n            if run_manager:\n                run_manager.on_llm_new_token(chunk.text, chunk=chunk)\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html"}
{"id": "197e4fd60a2b-5", "text": "messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        should_stream = stream if stream is not None else self.streaming\n        if should_stream:\n            stream_iter = self._stream(\n                messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return _generate_from_stream(stream_iter)\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs}\n        response = self.completion_with_retry(\n            messages=message_dicts, run_manager=run_manager, **params\n        )\n        return self._create_chat_result(response)\n    def _create_message_dicts(\n        self, messages: List[BaseMessage], stop: Optional[List[str]]\n    ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:\n        params = self._client_params\n        if stop is not None:\n            if \"stop\" in params:\n                raise ValueError(\"`stop` found in both the input and default params.\")\n            params[\"stop\"] = stop\n        message_dicts = [convert_message_to_dict(m) for m in messages]\n        return message_dicts, params\n    def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:\n        generations = []\n        for res in response[\"choices\"]:\n            message = convert_dict_to_message(res[\"message\"])\n            gen = ChatGeneration(\n                message=message,\n                generation_info=dict(finish_reason=res.get(\"finish_reason\")),\n            )\n            generations.append(gen)\n        token_usage = response.get(\"usage\", {})", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html"}
{"id": "197e4fd60a2b-6", "text": ")\n            generations.append(gen)\n        token_usage = response.get(\"usage\", {})\n        llm_output = {\"token_usage\": token_usage, \"model_name\": self.model}\n        return ChatResult(generations=generations, llm_output=llm_output)\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model_name\": self.model}, **self._default_params}\n    @property\n    def _client_params(self) -> Dict[str, Any]:\n        \"\"\"Get the parameters used for the konko client.\"\"\"\n        return {**self._default_params}\n    def _get_invocation_params(\n        self, stop: Optional[List[str]] = None, **kwargs: Any\n    ) -> Dict[str, Any]:\n        \"\"\"Get the parameters used to invoke the model.\"\"\"\n        return {\n            \"model\": self.model,\n            **super()._get_invocation_params(stop=stop),\n            **self._default_params,\n            **kwargs,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat model.\"\"\"\n        return \"konko-chat\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html"}
{"id": "309bf2dbb34f-0", "text": "Source code for langchain.chat_models.baidu_qianfan_endpoint\nfrom __future__ import annotations\nimport logging\nfrom typing import Any, AsyncIterator, Dict, Iterator, List, Mapping, Optional, cast\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema import ChatGeneration, ChatResult\nfrom langchain.schema.messages import (\n    AIMessage,\n    AIMessageChunk,\n    BaseMessage,\n    ChatMessage,\n    FunctionMessage,\n    HumanMessage,\n    SystemMessage,\n)\nfrom langchain.schema.output import ChatGenerationChunk\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]def convert_message_to_dict(message: BaseMessage) -> dict:\n    \"\"\"Convert a message to a dictionary that can be passed to the API.\"\"\"\n    message_dict: Dict[str, Any]\n    if isinstance(message, ChatMessage):\n        message_dict = {\"role\": message.role, \"content\": message.content}\n    elif isinstance(message, HumanMessage):\n        message_dict = {\"role\": \"user\", \"content\": message.content}\n    elif isinstance(message, AIMessage):\n        message_dict = {\"role\": \"assistant\", \"content\": message.content}\n        if \"function_call\" in message.additional_kwargs:\n            message_dict[\"function_call\"] = message.additional_kwargs[\"function_call\"]\n            # If function call only, content is None not empty string\n            if message_dict[\"content\"] == \"\":\n                message_dict[\"content\"] = None\n    elif isinstance(message, FunctionMessage):\n        message_dict = {\n            \"role\": \"function\",\n            \"content\": message.content,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html"}
{"id": "309bf2dbb34f-1", "text": "\"role\": \"function\",\n            \"content\": message.content,\n            \"name\": message.name,\n        }\n    else:\n        raise TypeError(f\"Got unknown type {message}\")\n    return message_dict\ndef _convert_dict_to_message(_dict: Mapping[str, Any]) -> AIMessage:\n    content = _dict.get(\"result\", \"\") or \"\"\n    if _dict.get(\"function_call\"):\n        additional_kwargs = {\"function_call\": dict(_dict[\"function_call\"])}\n        if \"thoughts\" in additional_kwargs[\"function_call\"]:\n            # align to api sample, which affects the llm function_call output\n            additional_kwargs[\"function_call\"].pop(\"thoughts\")\n    else:\n        additional_kwargs = {}\n    return AIMessage(\n        content=content,\n        additional_kwargs={**_dict.get(\"body\", {}), **additional_kwargs},\n    )\n[docs]class QianfanChatEndpoint(BaseChatModel):\n    \"\"\"Baidu Qianfan chat models.\n    To use, you should have the ``qianfan`` python package installed, and\n    the environment variable ``qianfan_ak`` and ``qianfan_sk`` set with your\n    API key and Secret Key.\n    ak, sk are required parameters\n    which you could get from  https://cloud.baidu.com/product/wenxinworkshop\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import QianfanChatEndpoint\n            qianfan_chat = QianfanChatEndpoint(model=\"ERNIE-Bot\",\n                endpoint=\"your_endpoint\", qianfan_ak=\"your_ak\", qianfan_sk=\"your_sk\")\n    \"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    client: Any\n    qianfan_ak: Optional[str] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html"}
{"id": "309bf2dbb34f-2", "text": "client: Any\n    qianfan_ak: Optional[str] = None\n    qianfan_sk: Optional[str] = None\n    streaming: Optional[bool] = False\n    \"\"\"Whether to stream the results or not.\"\"\"\n    request_timeout: Optional[int] = 60\n    \"\"\"request timeout for chat http requests\"\"\"\n    top_p: Optional[float] = 0.8\n    temperature: Optional[float] = 0.95\n    penalty_score: Optional[float] = 1\n    \"\"\"Model params, only supported in ERNIE-Bot and ERNIE-Bot-turbo.\n    In the case of other model, passing these params will not affect the result.\n    \"\"\"\n    model: str = \"ERNIE-Bot-turbo\"\n    \"\"\"Model name.\n    you could get from https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu\n    \n    preset models are mapping to an endpoint.\n    `model` will be ignored if `endpoint` is set.\n    Default is ERNIE-Bot-turbo.\n    \"\"\"\n    endpoint: Optional[str] = None\n    \"\"\"Endpoint of the Qianfan LLM, required if custom model used.\"\"\"\n    @root_validator()\n    def validate_enviroment(cls, values: Dict) -> Dict:\n        values[\"qianfan_ak\"] = get_from_dict_or_env(\n            values,\n            \"qianfan_ak\",\n            \"QIANFAN_AK\",\n        )\n        values[\"qianfan_sk\"] = get_from_dict_or_env(\n            values,\n            \"qianfan_sk\",\n            \"QIANFAN_SK\",\n        )\n        params = {\n            \"ak\": values[\"qianfan_ak\"],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html"}
{"id": "309bf2dbb34f-3", "text": ")\n        params = {\n            \"ak\": values[\"qianfan_ak\"],\n            \"sk\": values[\"qianfan_sk\"],\n            \"model\": values[\"model\"],\n            \"stream\": values[\"streaming\"],\n        }\n        if values[\"endpoint\"] is not None and values[\"endpoint\"] != \"\":\n            params[\"endpoint\"] = values[\"endpoint\"]\n        try:\n            import qianfan\n            values[\"client\"] = qianfan.ChatCompletion(**params)\n        except ImportError:\n            raise ValueError(\n                \"qianfan package not found, please install it with \"\n                \"`pip install qianfan`\"\n            )\n        return values\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        return {\n            **{\"endpoint\": self.endpoint, \"model\": self.model},\n            **super()._identifying_params,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat_model.\"\"\"\n        return \"baidu-qianfan-chat\"\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Qianfan API.\"\"\"\n        normal_params = {\n            \"model\": self.model,\n            \"endpoint\": self.endpoint,\n            \"stream\": self.streaming,\n            \"request_timeout\": self.request_timeout,\n            \"top_p\": self.top_p,\n            \"temperature\": self.temperature,\n            \"penalty_score\": self.penalty_score,\n        }\n        return {**normal_params, **self.model_kwargs}\n    def _convert_prompt_msg_params(\n        self,\n        messages: List[BaseMessage],\n        **kwargs: Any,\n    ) -> Dict[str, Any]:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html"}
{"id": "309bf2dbb34f-4", "text": "**kwargs: Any,\n    ) -> Dict[str, Any]:\n        \"\"\"\n        Converts a list of messages into a dictionary containing the message content\n        and default parameters.\n        Args:\n            messages (List[BaseMessage]): The list of messages.\n            **kwargs (Any): Optional arguments to add additional parameters to the\n            resulting dictionary.\n        Returns:\n            Dict[str, Any]: A dictionary containing the message content and default\n            parameters.\n        \"\"\"\n        messages_dict: Dict[str, Any] = {\n            \"messages\": [\n                convert_message_to_dict(m)\n                for m in messages\n                if not isinstance(m, SystemMessage)\n            ]\n        }\n        for i in [i for i, m in enumerate(messages) if isinstance(m, SystemMessage)]:\n            if \"system\" not in messages_dict:\n                messages_dict[\"system\"] = \"\"\n            messages_dict[\"system\"] += cast(str, messages[i].content) + \"\\n\"\n        return {\n            **messages_dict,\n            **self._default_params,\n            **kwargs,\n        }\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        \"\"\"Call out to an qianfan models endpoint for each generation with a prompt.\n        Args:\n            messages: The messages to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = qianfan_model(\"Tell me a joke.\")\n        \"\"\"\n        if self.streaming:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html"}
{"id": "309bf2dbb34f-5", "text": "\"\"\"\n        if self.streaming:\n            completion = \"\"\n            for chunk in self._stream(messages, stop, run_manager, **kwargs):\n                completion += chunk.text\n            lc_msg = AIMessage(content=completion, additional_kwargs={})\n            gen = ChatGeneration(\n                message=lc_msg,\n                generation_info=dict(finish_reason=\"stop\"),\n            )\n            return ChatResult(\n                generations=[gen],\n                llm_output={\"token_usage\": {}, \"model_name\": self.model},\n            )\n        params = self._convert_prompt_msg_params(messages, **kwargs)\n        response_payload = self.client.do(**params)\n        lc_msg = _convert_dict_to_message(response_payload)\n        gen = ChatGeneration(\n            message=lc_msg,\n            generation_info={\n                \"finish_reason\": \"stop\",\n                **response_payload.get(\"body\", {}),\n            },\n        )\n        token_usage = response_payload.get(\"usage\", {})\n        llm_output = {\"token_usage\": token_usage, \"model_name\": self.model}\n        return ChatResult(generations=[gen], llm_output=llm_output)\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        if self.streaming:\n            completion = \"\"\n            token_usage = {}\n            async for chunk in self._astream(messages, stop, run_manager, **kwargs):\n                completion += chunk.text\n            lc_msg = AIMessage(content=completion, additional_kwargs={})\n            gen = ChatGeneration(\n                message=lc_msg,\n                generation_info=dict(finish_reason=\"stop\"),\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html"}
{"id": "309bf2dbb34f-6", "text": "generation_info=dict(finish_reason=\"stop\"),\n            )\n            return ChatResult(\n                generations=[gen],\n                llm_output={\"token_usage\": {}, \"model_name\": self.model},\n            )\n        params = self._convert_prompt_msg_params(messages, **kwargs)\n        response_payload = await self.client.ado(**params)\n        lc_msg = _convert_dict_to_message(response_payload)\n        generations = []\n        gen = ChatGeneration(\n            message=lc_msg,\n            generation_info={\n                \"finish_reason\": \"stop\",\n                **response_payload.get(\"body\", {}),\n            },\n        )\n        generations.append(gen)\n        token_usage = response_payload.get(\"usage\", {})\n        llm_output = {\"token_usage\": token_usage, \"model_name\": self.model}\n        return ChatResult(generations=generations, llm_output=llm_output)\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        params = self._convert_prompt_msg_params(messages, **kwargs)\n        for res in self.client.do(**params):\n            if res:\n                msg = _convert_dict_to_message(res)\n                chunk = ChatGenerationChunk(\n                    text=res[\"result\"],\n                    message=AIMessageChunk(\n                        content=msg.content,\n                        role=\"assistant\",\n                        additional_kwargs=msg.additional_kwargs,\n                    ),\n                )\n                yield chunk\n                if run_manager:\n                    run_manager.on_llm_new_token(chunk.text, chunk=chunk)\n    async def _astream(\n        self,\n        messages: List[BaseMessage],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html"}
{"id": "309bf2dbb34f-7", "text": "self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[ChatGenerationChunk]:\n        params = self._convert_prompt_msg_params(messages, **kwargs)\n        async for res in await self.client.ado(**params):\n            if res:\n                msg = _convert_dict_to_message(res)\n                chunk = ChatGenerationChunk(\n                    text=res[\"result\"],\n                    message=AIMessageChunk(\n                        content=msg.content,\n                        role=\"assistant\",\n                        additional_kwargs=msg.additional_kwargs,\n                    ),\n                )\n                yield chunk\n                if run_manager:\n                    await run_manager.on_llm_new_token(chunk.text, chunk=chunk)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html"}
{"id": "11fba190c80c-0", "text": "Source code for langchain.chat_models.javelin_ai_gateway\nimport logging\nfrom typing import Any, Dict, List, Mapping, Optional, cast\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.pydantic_v1 import BaseModel, Extra, SecretStr\nfrom langchain.schema import (\n    ChatGeneration,\n    ChatResult,\n)\nfrom langchain.schema.messages import (\n    AIMessage,\n    BaseMessage,\n    ChatMessage,\n    FunctionMessage,\n    HumanMessage,\n    SystemMessage,\n)\nlogger = logging.getLogger(__name__)\n# Ignoring type because below is valid pydantic code\n# Unexpected keyword argument \"extra\" for \"__init_subclass__\" of \"object\"  [call-arg]\n[docs]class ChatParams(BaseModel, extra=Extra.allow):  # type: ignore[call-arg]\n    \"\"\"Parameters for the `Javelin AI Gateway` LLM.\"\"\"\n    temperature: float = 0.0\n    stop: Optional[List[str]] = None\n    max_tokens: Optional[int] = None\n[docs]class ChatJavelinAIGateway(BaseChatModel):\n    \"\"\"`Javelin AI Gateway` chat models API.\n    To use, you should have the ``javelin_sdk`` python package installed.\n    For more information, see https://docs.getjavelin.io\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import ChatJavelinAIGateway\n            chat = ChatJavelinAIGateway(\n                gateway_uri=\"<javelin-ai-gateway-uri>\",\n                route=\"<javelin-ai-gateway-chat-route>\",\n                params={", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/javelin_ai_gateway.html"}
{"id": "11fba190c80c-1", "text": "route=\"<javelin-ai-gateway-chat-route>\",\n                params={\n                    \"temperature\": 0.1\n                }\n            )\n    \"\"\"\n    route: str\n    \"\"\"The route to use for the Javelin AI Gateway API.\"\"\"\n    gateway_uri: Optional[str] = None\n    \"\"\"The URI for the Javelin AI Gateway API.\"\"\"\n    params: Optional[ChatParams] = None\n    \"\"\"Parameters for the Javelin AI Gateway LLM.\"\"\"\n    client: Any\n    \"\"\"javelin client.\"\"\"\n    javelin_api_key: Optional[SecretStr] = None\n    \"\"\"The API key for the Javelin AI Gateway.\"\"\"\n    def __init__(self, **kwargs: Any):\n        try:\n            from javelin_sdk import (\n                JavelinClient,\n                UnauthorizedError,\n            )\n        except ImportError:\n            raise ImportError(\n                \"Could not import javelin_sdk python package. \"\n                \"Please install it with `pip install javelin_sdk`.\"\n            )\n        super().__init__(**kwargs)\n        if self.gateway_uri:\n            try:\n                self.client = JavelinClient(\n                    base_url=self.gateway_uri,\n                    api_key=cast(SecretStr, self.javelin_api_key).get_secret_value(),\n                )\n            except UnauthorizedError as e:\n                raise ValueError(\"Javelin: Incorrect API Key.\") from e\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        params: Dict[str, Any] = {\n            \"gateway_uri\": self.gateway_uri,\n            \"javelin_api_key\": cast(SecretStr, self.javelin_api_key).get_secret_value(),\n            \"route\": self.route,\n            **(self.params.dict() if self.params else {}),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/javelin_ai_gateway.html"}
{"id": "11fba190c80c-2", "text": "**(self.params.dict() if self.params else {}),\n        }\n        return params\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        message_dicts = [\n            ChatJavelinAIGateway._convert_message_to_dict(message)\n            for message in messages\n        ]\n        data: Dict[str, Any] = {\n            \"messages\": message_dicts,\n            **(self.params.dict() if self.params else {}),\n        }\n        resp = self.client.query_route(self.route, query_body=data)\n        return ChatJavelinAIGateway._create_chat_result(resp.dict())\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        message_dicts = [\n            ChatJavelinAIGateway._convert_message_to_dict(message)\n            for message in messages\n        ]\n        data: Dict[str, Any] = {\n            \"messages\": message_dicts,\n            **(self.params.dict() if self.params else {}),\n        }\n        resp = await self.client.aquery_route(self.route, query_body=data)\n        return ChatJavelinAIGateway._create_chat_result(resp.dict())\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        return self._default_params\n    def _get_invocation_params(\n        self, stop: Optional[List[str]] = None, **kwargs: Any", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/javelin_ai_gateway.html"}
{"id": "11fba190c80c-3", "text": "self, stop: Optional[List[str]] = None, **kwargs: Any\n    ) -> Dict[str, Any]:\n        \"\"\"Get the parameters used to invoke the model FOR THE CALLBACKS.\"\"\"\n        return {\n            **self._default_params,\n            **super()._get_invocation_params(stop=stop, **kwargs),\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat model.\"\"\"\n        return \"javelin-ai-gateway-chat\"\n    @staticmethod\n    def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:\n        role = _dict[\"role\"]\n        content = _dict[\"content\"]\n        if role == \"user\":\n            return HumanMessage(content=content)\n        elif role == \"assistant\":\n            return AIMessage(content=content)\n        elif role == \"system\":\n            return SystemMessage(content=content)\n        else:\n            return ChatMessage(content=content, role=role)\n    @staticmethod\n    def _raise_functions_not_supported() -> None:\n        raise ValueError(\n            \"Function messages are not supported by the Javelin AI Gateway. Please\"\n            \" create a feature request at https://docs.getjavelin.io\"\n        )\n    @staticmethod\n    def _convert_message_to_dict(message: BaseMessage) -> dict:\n        if isinstance(message, ChatMessage):\n            message_dict = {\"role\": message.role, \"content\": message.content}\n        elif isinstance(message, HumanMessage):\n            message_dict = {\"role\": \"user\", \"content\": message.content}\n        elif isinstance(message, AIMessage):\n            message_dict = {\"role\": \"assistant\", \"content\": message.content}\n        elif isinstance(message, SystemMessage):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/javelin_ai_gateway.html"}
{"id": "11fba190c80c-4", "text": "elif isinstance(message, SystemMessage):\n            message_dict = {\"role\": \"system\", \"content\": message.content}\n        elif isinstance(message, FunctionMessage):\n            raise ValueError(\n                \"Function messages are not supported by the Javelin AI Gateway. Please\"\n                \" create a feature request at https://docs.getjavelin.io\"\n            )\n        else:\n            raise ValueError(f\"Got unknown message type: {message}\")\n        if \"function_call\" in message.additional_kwargs:\n            ChatJavelinAIGateway._raise_functions_not_supported()\n        if message.additional_kwargs:\n            logger.warning(\n                \"Additional message arguments are unsupported by Javelin AI Gateway \"\n                \" and will be ignored: %s\",\n                message.additional_kwargs,\n            )\n        return message_dict\n    @staticmethod\n    def _create_chat_result(response: Mapping[str, Any]) -> ChatResult:\n        generations = []\n        for candidate in response[\"llm_response\"][\"choices\"]:\n            message = ChatJavelinAIGateway._convert_dict_to_message(\n                candidate[\"message\"]\n            )\n            message_metadata = candidate.get(\"metadata\", {})\n            gen = ChatGeneration(\n                message=message,\n                generation_info=dict(message_metadata),\n            )\n            generations.append(gen)\n        response_metadata = response.get(\"metadata\", {})\n        return ChatResult(generations=generations, llm_output=response_metadata)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/javelin_ai_gateway.html"}
{"id": "7fafb2f8847f-0", "text": "Source code for langchain.chat_models.anyscale\n\"\"\"Anyscale Endpoints chat wrapper. Relies heavily on ChatOpenAI.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport os\nimport sys\nfrom typing import TYPE_CHECKING, Dict, Optional, Set\nimport requests\nfrom langchain.adapters.openai import convert_message_to_dict\nfrom langchain.chat_models.openai import (\n    ChatOpenAI,\n    _import_tiktoken,\n)\nfrom langchain.pydantic_v1 import Field, SecretStr, root_validator\nfrom langchain.schema.messages import BaseMessage\nfrom langchain.utils import convert_to_secret_str, get_from_dict_or_env\nfrom langchain.utils.openai import is_openai_v1\nif TYPE_CHECKING:\n    import tiktoken\nlogger = logging.getLogger(__name__)\nDEFAULT_API_BASE = \"https://api.endpoints.anyscale.com/v1\"\nDEFAULT_MODEL = \"meta-llama/Llama-2-7b-chat-hf\"\n[docs]class ChatAnyscale(ChatOpenAI):\n    \"\"\"`Anyscale` Chat large language models.\n    See https://www.anyscale.com/ for information about Anyscale.\n    To use, you should have the ``openai`` python package installed, and the\n    environment variable ``ANYSCALE_API_KEY`` set with your API key.\n    Alternatively, you can use the anyscale_api_key keyword argument.\n    Any parameters that are valid to be passed to the `openai.create` call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import ChatAnyscale\n            chat = ChatAnyscale(model_name=\"meta-llama/Llama-2-7b-chat-hf\")\n    \"\"\"\n    @property\n    def _llm_type(self) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html"}
{"id": "7fafb2f8847f-1", "text": "\"\"\"\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat model.\"\"\"\n        return \"anyscale-chat\"\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"anyscale_api_key\": \"ANYSCALE_API_KEY\"}\n    anyscale_api_key: SecretStr\n    \"\"\"AnyScale Endpoints API keys.\"\"\"\n    model_name: str = Field(default=DEFAULT_MODEL, alias=\"model\")\n    \"\"\"Model name to use.\"\"\"\n    anyscale_api_base: str = Field(default=DEFAULT_API_BASE)\n    \"\"\"Base URL path for API requests,\n    leave blank if not using a proxy or service emulator.\"\"\"\n    anyscale_proxy: Optional[str] = None\n    \"\"\"To support explicit proxy for Anyscale.\"\"\"\n    available_models: Optional[Set[str]] = None\n    \"\"\"Available models from Anyscale API.\"\"\"\n[docs]    @staticmethod\n    def get_available_models(\n        anyscale_api_key: Optional[str] = None,\n        anyscale_api_base: str = DEFAULT_API_BASE,\n    ) -> Set[str]:\n        \"\"\"Get available models from Anyscale API.\"\"\"\n        try:\n            anyscale_api_key = anyscale_api_key or os.environ[\"ANYSCALE_API_KEY\"]\n        except KeyError as e:\n            raise ValueError(\n                \"Anyscale API key must be passed as keyword argument or \"\n                \"set in environment variable ANYSCALE_API_KEY.\",\n            ) from e\n        models_url = f\"{anyscale_api_base}/models\"\n        models_response = requests.get(\n            models_url,\n            headers={\n                \"Authorization\": f\"Bearer {anyscale_api_key}\",\n            },\n        )\n        if models_response.status_code != 200:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html"}
{"id": "7fafb2f8847f-2", "text": ")\n        if models_response.status_code != 200:\n            raise ValueError(\n                f\"Error getting models from {models_url}: \"\n                f\"{models_response.status_code}\",\n            )\n        return {model[\"id\"] for model in models_response.json()[\"data\"]}\n    @root_validator(pre=True)\n    def validate_environment_override(cls, values: dict) -> dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"openai_api_key\"] = get_from_dict_or_env(\n            values,\n            \"anyscale_api_key\",\n            \"ANYSCALE_API_KEY\",\n        )\n        values[\"anyscale_api_key\"] = convert_to_secret_str(\n            get_from_dict_or_env(\n                values,\n                \"anyscale_api_key\",\n                \"ANYSCALE_API_KEY\",\n            )\n        )\n        values[\"openai_api_base\"] = get_from_dict_or_env(\n            values,\n            \"anyscale_api_base\",\n            \"ANYSCALE_API_BASE\",\n            default=DEFAULT_API_BASE,\n        )\n        values[\"openai_proxy\"] = get_from_dict_or_env(\n            values,\n            \"anyscale_proxy\",\n            \"ANYSCALE_PROXY\",\n            default=\"\",\n        )\n        try:\n            import openai\n        except ImportError as e:\n            raise ValueError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\",\n            ) from e\n        try:\n            if is_openai_v1():\n                client_params = {\n                    \"api_key\": values[\"openai_api_key\"],\n                    \"base_url\": values[\"openai_api_base\"],\n                    # To do: future support\n                    # \"organization\": values[\"openai_organization\"],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html"}
{"id": "7fafb2f8847f-3", "text": "# To do: future support\n                    # \"organization\": values[\"openai_organization\"],\n                    # \"timeout\": values[\"request_timeout\"],\n                    # \"max_retries\": values[\"max_retries\"],\n                    # \"default_headers\": values[\"default_headers\"],\n                    # \"default_query\": values[\"default_query\"],\n                    # \"http_client\": values[\"http_client\"],\n                }\n                values[\"client\"] = openai.OpenAI(**client_params).chat.completions\n            else:\n                values[\"client\"] = openai.ChatCompletion\n        except AttributeError as exc:\n            raise ValueError(\n                \"`openai` has no `ChatCompletion` attribute, this is likely \"\n                \"due to an old version of the openai package. Try upgrading it \"\n                \"with `pip install --upgrade openai`.\",\n            ) from exc\n        if \"model_name\" not in values.keys():\n            values[\"model_name\"] = DEFAULT_MODEL\n        model_name = values[\"model_name\"]\n        available_models = cls.get_available_models(\n            values[\"openai_api_key\"],\n            values[\"openai_api_base\"],\n        )\n        if model_name not in available_models:\n            raise ValueError(\n                f\"Model name {model_name} not found in available models: \"\n                f\"{available_models}.\",\n            )\n        values[\"available_models\"] = available_models\n        return values\n    def _get_encoding_model(self) -> tuple[str, tiktoken.Encoding]:\n        tiktoken_ = _import_tiktoken()\n        if self.tiktoken_model_name is not None:\n            model = self.tiktoken_model_name\n        else:\n            model = self.model_name\n        # Returns the number of tokens used by a list of messages.\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html"}
{"id": "7fafb2f8847f-4", "text": "# Returns the number of tokens used by a list of messages.\n        try:\n            encoding = tiktoken_.encoding_for_model(\"gpt-3.5-turbo-0301\")\n        except KeyError:\n            logger.warning(\"Warning: model not found. Using cl100k_base encoding.\")\n            model = \"cl100k_base\"\n            encoding = tiktoken_.get_encoding(model)\n        return model, encoding\n[docs]    def get_num_tokens_from_messages(self, messages: list[BaseMessage]) -> int:\n        \"\"\"Calculate num tokens with tiktoken package.\n        Official documentation: https://github.com/openai/openai-cookbook/blob/\n        main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb\"\"\"\n        if sys.version_info[1] <= 7:\n            return super().get_num_tokens_from_messages(messages)\n        model, encoding = self._get_encoding_model()\n        tokens_per_message = 3\n        tokens_per_name = 1\n        num_tokens = 0\n        messages_dict = [convert_message_to_dict(m) for m in messages]\n        for message in messages_dict:\n            num_tokens += tokens_per_message\n            for key, value in message.items():\n                # Cast str(value) in case the message value is not a string\n                # This occurs with function messages\n                num_tokens += len(encoding.encode(str(value)))\n                if key == \"name\":\n                    num_tokens += tokens_per_name\n        # every reply is primed with <im_start>assistant\n        num_tokens += 3\n        return num_tokens", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html"}
{"id": "e621296ae8ed-0", "text": "Source code for langchain.chat_models.cohere\nfrom typing import Any, AsyncIterator, Dict, Iterator, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import (\n    BaseChatModel,\n    _agenerate_from_stream,\n    _generate_from_stream,\n)\nfrom langchain.llms.cohere import BaseCohere\nfrom langchain.schema.messages import (\n    AIMessage,\n    AIMessageChunk,\n    BaseMessage,\n    ChatMessage,\n    HumanMessage,\n    SystemMessage,\n)\nfrom langchain.schema.output import ChatGeneration, ChatGenerationChunk, ChatResult\n[docs]def get_role(message: BaseMessage) -> str:\n    \"\"\"Get the role of the message.\n    Args:\n        message: The message.\n    Returns:\n        The role of the message.\n    Raises:\n        ValueError: If the message is of an unknown type.\n    \"\"\"\n    if isinstance(message, ChatMessage) or isinstance(message, HumanMessage):\n        return \"User\"\n    elif isinstance(message, AIMessage):\n        return \"Chatbot\"\n    elif isinstance(message, SystemMessage):\n        return \"System\"\n    else:\n        raise ValueError(f\"Got unknown type {message}\")\n[docs]def get_cohere_chat_request(\n    messages: List[BaseMessage],\n    *,\n    connectors: Optional[List[Dict[str, str]]] = None,\n    **kwargs: Any,\n) -> Dict[str, Any]:\n    \"\"\"Get the request for the Cohere chat API.\n    Args:\n        messages: The messages.\n        connectors: The connectors.\n        **kwargs: The keyword arguments.\n    Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/cohere.html"}
{"id": "e621296ae8ed-1", "text": "connectors: The connectors.\n        **kwargs: The keyword arguments.\n    Returns:\n        The request for the Cohere chat API.\n    \"\"\"\n    documents = (\n        None\n        if \"source_documents\" not in kwargs\n        else [\n            {\n                \"snippet\": doc.page_content,\n                \"id\": doc.metadata.get(\"id\") or f\"doc-{str(i)}\",\n            }\n            for i, doc in enumerate(kwargs[\"source_documents\"])\n        ]\n    )\n    kwargs.pop(\"source_documents\", None)\n    maybe_connectors = connectors if documents is None else None\n    # by enabling automatic prompt truncation, the probability of request failure is\n    # reduced with minimal impact on response quality\n    prompt_truncation = (\n        \"AUTO\" if documents is not None or connectors is not None else None\n    )\n    return {\n        \"message\": messages[-1].content,\n        \"chat_history\": [\n            {\"role\": get_role(x), \"message\": x.content} for x in messages[:-1]\n        ],\n        \"documents\": documents,\n        \"connectors\": maybe_connectors,\n        \"prompt_truncation\": prompt_truncation,\n        **kwargs,\n    }\n[docs]class ChatCohere(BaseChatModel, BaseCohere):\n    \"\"\"`Cohere` chat large language models.\n    To use, you should have the ``cohere`` python package installed, and the\n    environment variable ``COHERE_API_KEY`` set with your API key, or pass\n    it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import ChatCohere\n            from langchain.schema import HumanMessage\n            chat = ChatCohere(model=\"foo\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/cohere.html"}
{"id": "e621296ae8ed-2", "text": "chat = ChatCohere(model=\"foo\")\n            result = chat([HumanMessage(content=\"Hello\")])\n            print(result.content)\n    \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        allow_population_by_field_name = True\n        arbitrary_types_allowed = True\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat model.\"\"\"\n        return \"cohere-chat\"\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Cohere API.\"\"\"\n        return {\n            \"temperature\": self.temperature,\n        }\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model\": self.model}, **self._default_params}\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        request = get_cohere_chat_request(messages, **self._default_params, **kwargs)\n        stream = self.client.chat(**request, stream=True)\n        for data in stream:\n            if data.event_type == \"text-generation\":\n                delta = data.text\n                yield ChatGenerationChunk(message=AIMessageChunk(content=delta))\n                if run_manager:\n                    run_manager.on_llm_new_token(delta)\n    async def _astream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/cohere.html"}
{"id": "e621296ae8ed-3", "text": "**kwargs: Any,\n    ) -> AsyncIterator[ChatGenerationChunk]:\n        request = get_cohere_chat_request(messages, **self._default_params, **kwargs)\n        stream = await self.async_client.chat(**request, stream=True)\n        async for data in stream:\n            if data.event_type == \"text-generation\":\n                delta = data.text\n                yield ChatGenerationChunk(message=AIMessageChunk(content=delta))\n                if run_manager:\n                    await run_manager.on_llm_new_token(delta)\n    def _get_generation_info(self, response: Any) -> Dict[str, Any]:\n        \"\"\"Get the generation info from cohere API response.\"\"\"\n        return {\n            \"documents\": response.documents,\n            \"citations\": response.citations,\n            \"search_results\": response.search_results,\n            \"search_queries\": response.search_queries,\n            \"token_count\": response.token_count,\n        }\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        if self.streaming:\n            stream_iter = self._stream(\n                messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return _generate_from_stream(stream_iter)\n        request = get_cohere_chat_request(messages, **self._default_params, **kwargs)\n        response = self.client.chat(**request)\n        message = AIMessage(content=response.text)\n        generation_info = None\n        if hasattr(response, \"documents\"):\n            generation_info = self._get_generation_info(response)\n        return ChatResult(\n            generations=[\n                ChatGeneration(message=message, generation_info=generation_info)\n            ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/cohere.html"}
{"id": "e621296ae8ed-4", "text": "generations=[\n                ChatGeneration(message=message, generation_info=generation_info)\n            ]\n        )\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        if self.streaming:\n            stream_iter = self._astream(\n                messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return await _agenerate_from_stream(stream_iter)\n        request = get_cohere_chat_request(messages, **self._default_params, **kwargs)\n        response = self.client.chat(**request, stream=False)\n        message = AIMessage(content=response.text)\n        generation_info = None\n        if hasattr(response, \"documents\"):\n            generation_info = self._get_generation_info(response)\n        return ChatResult(\n            generations=[\n                ChatGeneration(message=message, generation_info=generation_info)\n            ]\n        )\n[docs]    def get_num_tokens(self, text: str) -> int:\n        \"\"\"Calculate number of tokens.\"\"\"\n        return len(self.client.tokenize(text).tokens)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/cohere.html"}
{"id": "ea396b6363eb-0", "text": "Source code for langchain.chat_models.human\n\"\"\"ChatModel wrapper which returns user input as the response..\"\"\"\nimport asyncio\nfrom functools import partial\nfrom io import StringIO\nfrom typing import Any, Callable, Dict, List, Mapping, Optional\nimport yaml\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema.messages import (\n    BaseMessage,\n    HumanMessage,\n    _message_from_dict,\n    messages_to_dict,\n)\nfrom langchain.schema.output import ChatGeneration, ChatResult\ndef _display_messages(messages: List[BaseMessage]) -> None:\n    dict_messages = messages_to_dict(messages)\n    for message in dict_messages:\n        yaml_string = yaml.dump(\n            message,\n            default_flow_style=False,\n            sort_keys=False,\n            allow_unicode=True,\n            width=10000,\n            line_break=None,\n        )\n        print(\"\\n\", \"======= start of message =======\", \"\\n\\n\")\n        print(yaml_string)\n        print(\"======= end of message =======\", \"\\n\\n\")\ndef _collect_yaml_input(\n    messages: List[BaseMessage], stop: Optional[List[str]] = None\n) -> BaseMessage:\n    \"\"\"Collects and returns user input as a single string.\"\"\"\n    lines = []\n    while True:\n        line = input()\n        if not line.strip():\n            break\n        if stop and any(seq in line for seq in stop):\n            break\n        lines.append(line)\n    yaml_string = \"\\n\".join(lines)\n    # Try to parse the input string as YAML\n    try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/human.html"}
{"id": "ea396b6363eb-1", "text": "# Try to parse the input string as YAML\n    try:\n        message = _message_from_dict(yaml.safe_load(StringIO(yaml_string)))\n        if message is None:\n            return HumanMessage(content=\"\")\n        if stop:\n            if isinstance(message.content, str):\n                message.content = enforce_stop_tokens(message.content, stop)\n            else:\n                raise ValueError(\"Cannot use when output is not a string.\")\n        return message\n    except yaml.YAMLError:\n        raise ValueError(\"Invalid YAML string entered.\")\n    except ValueError:\n        raise ValueError(\"Invalid message entered.\")\n[docs]class HumanInputChatModel(BaseChatModel):\n    \"\"\"ChatModel which returns user input as the response.\"\"\"\n    input_func: Callable = Field(default_factory=lambda: _collect_yaml_input)\n    message_func: Callable = Field(default_factory=lambda: _display_messages)\n    separator: str = \"\\n\"\n    input_kwargs: Mapping[str, Any] = {}\n    message_kwargs: Mapping[str, Any] = {}\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        return {\n            \"input_func\": self.input_func.__name__,\n            \"message_func\": self.message_func.__name__,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Returns the type of LLM.\"\"\"\n        return \"human-input-chat-model\"\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        \"\"\"\n        Displays the messages to the user and returns their input as a response.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/human.html"}
{"id": "ea396b6363eb-2", "text": "Displays the messages to the user and returns their input as a response.\n        Args:\n            messages (List[BaseMessage]): The messages to be displayed to the user.\n            stop (Optional[List[str]]): A list of stop strings.\n            run_manager (Optional[CallbackManagerForLLMRun]): Currently not used.\n        Returns:\n            ChatResult: The user's input as a response.\n        \"\"\"\n        self.message_func(messages, **self.message_kwargs)\n        user_input = self.input_func(messages, stop=stop, **self.input_kwargs)\n        return ChatResult(generations=[ChatGeneration(message=user_input)])\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        func = partial(\n            self._generate, messages, stop=stop, run_manager=run_manager, **kwargs\n        )\n        return await asyncio.get_event_loop().run_in_executor(None, func)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/human.html"}
{"id": "f9b060e84a7f-0", "text": "Source code for langchain.chat_models.fireworks\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Callable,\n    Dict,\n    Iterator,\n    List,\n    Optional,\n    Type,\n    Union,\n)\nfrom langchain.adapters.openai import convert_message_to_dict\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.llms.base import create_base_retry_decorator\nfrom langchain.pydantic_v1 import Field, SecretStr, root_validator\nfrom langchain.schema.messages import (\n    AIMessage,\n    AIMessageChunk,\n    BaseMessage,\n    BaseMessageChunk,\n    ChatMessage,\n    ChatMessageChunk,\n    FunctionMessage,\n    FunctionMessageChunk,\n    HumanMessage,\n    HumanMessageChunk,\n    SystemMessage,\n    SystemMessageChunk,\n)\nfrom langchain.schema.output import ChatGeneration, ChatGenerationChunk, ChatResult\nfrom langchain.utils import convert_to_secret_str\nfrom langchain.utils.env import get_from_dict_or_env\ndef _convert_delta_to_message_chunk(\n    _dict: Any, default_class: Type[BaseMessageChunk]\n) -> BaseMessageChunk:\n    \"\"\"Convert a delta response to a message chunk.\"\"\"\n    role = _dict.role\n    content = _dict.content or \"\"\n    additional_kwargs: Dict = {}\n    if role == \"user\" or default_class == HumanMessageChunk:\n        return HumanMessageChunk(content=content)\n    elif role == \"assistant\" or default_class == AIMessageChunk:\n        return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)\n    elif role == \"system\" or default_class == SystemMessageChunk:\n        return SystemMessageChunk(content=content)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html"}
{"id": "f9b060e84a7f-1", "text": "return SystemMessageChunk(content=content)\n    elif role == \"function\" or default_class == FunctionMessageChunk:\n        return FunctionMessageChunk(content=content, name=_dict.name)\n    elif role or default_class == ChatMessageChunk:\n        return ChatMessageChunk(content=content, role=role)\n    else:\n        return default_class(content=content)\n[docs]def convert_dict_to_message(_dict: Any) -> BaseMessage:\n    \"\"\"Convert a dict response to a message.\"\"\"\n    role = _dict.role\n    content = _dict.content or \"\"\n    if role == \"user\":\n        return HumanMessage(content=content)\n    elif role == \"assistant\":\n        content = _dict.content\n        additional_kwargs: Dict = {}\n        return AIMessage(content=content, additional_kwargs=additional_kwargs)\n    elif role == \"system\":\n        return SystemMessage(content=content)\n    elif role == \"function\":\n        return FunctionMessage(content=content, name=_dict.name)\n    else:\n        return ChatMessage(content=content, role=role)\n[docs]class ChatFireworks(BaseChatModel):\n    \"\"\"Fireworks Chat models.\"\"\"\n    model: str = \"accounts/fireworks/models/llama-v2-7b-chat\"\n    model_kwargs: dict = Field(\n        default_factory=lambda: {\n            \"temperature\": 0.7,\n            \"max_tokens\": 512,\n            \"top_p\": 1,\n        }.copy()\n    )\n    fireworks_api_key: Optional[SecretStr] = None\n    max_retries: int = 20\n    use_retry: bool = True\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"fireworks_api_key\": \"FIREWORKS_API_KEY\"}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html"}
{"id": "f9b060e84a7f-2", "text": "return {\"fireworks_api_key\": \"FIREWORKS_API_KEY\"}\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key in environment.\"\"\"\n        try:\n            import fireworks.client\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import fireworks-ai python package. \"\n                \"Please install it with `pip install fireworks-ai`.\"\n            ) from e\n        fireworks_api_key = convert_to_secret_str(\n            get_from_dict_or_env(values, \"fireworks_api_key\", \"FIREWORKS_API_KEY\")\n        )\n        fireworks.client.api_key = fireworks_api_key.get_secret_value()\n        return values\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"fireworks-chat\"\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        message_dicts = self._create_message_dicts(messages)\n        params = {\n            \"model\": self.model,\n            \"messages\": message_dicts,\n            **self.model_kwargs,\n        }\n        response = completion_with_retry(\n            self,\n            self.use_retry,\n            run_manager=run_manager,\n            stop=stop,\n            **params,\n        )\n        return self._create_chat_result(response)\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html"}
{"id": "f9b060e84a7f-3", "text": "messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        message_dicts = self._create_message_dicts(messages)\n        params = {\n            \"model\": self.model,\n            \"messages\": message_dicts,\n            **self.model_kwargs,\n        }\n        response = await acompletion_with_retry(\n            self, self.use_retry, run_manager=run_manager, stop=stop, **params\n        )\n        return self._create_chat_result(response)\n    def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:\n        if llm_outputs[0] is None:\n            return {}\n        return llm_outputs[0]\n    def _create_chat_result(self, response: Any) -> ChatResult:\n        generations = []\n        for res in response.choices:\n            message = convert_dict_to_message(res.message)\n            gen = ChatGeneration(\n                message=message,\n                generation_info=dict(finish_reason=res.finish_reason),\n            )\n            generations.append(gen)\n        llm_output = {\"model\": self.model}\n        return ChatResult(generations=generations, llm_output=llm_output)\n    def _create_message_dicts(\n        self, messages: List[BaseMessage]\n    ) -> List[Dict[str, Any]]:\n        message_dicts = [convert_message_to_dict(m) for m in messages]\n        return message_dicts\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html"}
{"id": "f9b060e84a7f-4", "text": "**kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        message_dicts = self._create_message_dicts(messages)\n        default_chunk_class = AIMessageChunk\n        params = {\n            \"model\": self.model,\n            \"messages\": message_dicts,\n            \"stream\": True,\n            **self.model_kwargs,\n        }\n        for chunk in completion_with_retry(\n            self, self.use_retry, run_manager=run_manager, stop=stop, **params\n        ):\n            choice = chunk.choices[0]\n            chunk = _convert_delta_to_message_chunk(choice.delta, default_chunk_class)\n            finish_reason = choice.finish_reason\n            generation_info = (\n                dict(finish_reason=finish_reason) if finish_reason is not None else None\n            )\n            default_chunk_class = chunk.__class__\n            chunk = ChatGenerationChunk(message=chunk, generation_info=generation_info)\n            yield chunk\n            if run_manager:\n                run_manager.on_llm_new_token(chunk.text, chunk=chunk)\n    async def _astream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[ChatGenerationChunk]:\n        message_dicts = self._create_message_dicts(messages)\n        default_chunk_class = AIMessageChunk\n        params = {\n            \"model\": self.model,\n            \"messages\": message_dicts,\n            \"stream\": True,\n            **self.model_kwargs,\n        }\n        async for chunk in await acompletion_with_retry_streaming(\n            self, self.use_retry, run_manager=run_manager, stop=stop, **params\n        ):\n            choice = chunk.choices[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html"}
{"id": "f9b060e84a7f-5", "text": "):\n            choice = chunk.choices[0]\n            chunk = _convert_delta_to_message_chunk(choice.delta, default_chunk_class)\n            finish_reason = choice.finish_reason\n            generation_info = (\n                dict(finish_reason=finish_reason) if finish_reason is not None else None\n            )\n            default_chunk_class = chunk.__class__\n            chunk = ChatGenerationChunk(message=chunk, generation_info=generation_info)\n            yield chunk\n            if run_manager:\n                await run_manager.on_llm_new_token(token=chunk.text, chunk=chunk)\n[docs]def conditional_decorator(\n    condition: bool, decorator: Callable[[Any], Any]\n) -> Callable[[Any], Any]:\n    def actual_decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:\n        if condition:\n            return decorator(func)\n        return func\n    return actual_decorator\n[docs]def completion_with_retry(\n    llm: ChatFireworks,\n    use_retry: bool,\n    *,\n    run_manager: Optional[CallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    import fireworks.client\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @conditional_decorator(use_retry, retry_decorator)\n    def _completion_with_retry(**kwargs: Any) -> Any:\n        return fireworks.client.ChatCompletion.create(\n            **kwargs,\n        )\n    return _completion_with_retry(**kwargs)\n[docs]async def acompletion_with_retry(\n    llm: ChatFireworks,\n    use_retry: bool,\n    *,\n    run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html"}
{"id": "f9b060e84a7f-6", "text": "**kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the async completion call.\"\"\"\n    import fireworks.client\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @conditional_decorator(use_retry, retry_decorator)\n    async def _completion_with_retry(**kwargs: Any) -> Any:\n        return await fireworks.client.ChatCompletion.acreate(\n            **kwargs,\n        )\n    return await _completion_with_retry(**kwargs)\n[docs]async def acompletion_with_retry_streaming(\n    llm: ChatFireworks,\n    use_retry: bool,\n    *,\n    run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the completion call for streaming.\"\"\"\n    import fireworks.client\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @conditional_decorator(use_retry, retry_decorator)\n    async def _completion_with_retry(**kwargs: Any) -> Any:\n        return fireworks.client.ChatCompletion.acreate(\n            **kwargs,\n        )\n    return await _completion_with_retry(**kwargs)\ndef _create_retry_decorator(\n    llm: ChatFireworks,\n    run_manager: Optional[\n        Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]\n    ] = None,\n) -> Callable[[Any], Any]:\n    \"\"\"Define retry mechanism.\"\"\"\n    import fireworks.client\n    errors = [\n        fireworks.client.error.RateLimitError,\n        fireworks.client.error.InternalServerError,\n        fireworks.client.error.BadGatewayError,\n        fireworks.client.error.ServiceUnavailableError,\n    ]\n    return create_base_retry_decorator(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html"}
{"id": "f9b060e84a7f-7", "text": "fireworks.client.error.ServiceUnavailableError,\n    ]\n    return create_base_retry_decorator(\n        error_types=errors, max_retries=llm.max_retries, run_manager=run_manager\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html"}
{"id": "bc9525303fdf-0", "text": "Source code for langchain.chat_models.hunyuan\nimport base64\nimport hashlib\nimport hmac\nimport json\nimport logging\nimport time\nfrom typing import Any, Dict, Iterator, List, Mapping, Optional, Type\nfrom urllib.parse import urlparse\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.chat_models.base import BaseChatModel, _generate_from_stream\nfrom langchain.pydantic_v1 import Field, SecretStr, root_validator\nfrom langchain.schema import (\n    AIMessage,\n    BaseMessage,\n    ChatGeneration,\n    ChatMessage,\n    ChatResult,\n    HumanMessage,\n)\nfrom langchain.schema.messages import (\n    AIMessageChunk,\n    BaseMessageChunk,\n    ChatMessageChunk,\n    HumanMessageChunk,\n)\nfrom langchain.schema.output import ChatGenerationChunk\nfrom langchain.utils import (\n    convert_to_secret_str,\n    get_from_dict_or_env,\n    get_pydantic_field_names,\n)\nlogger = logging.getLogger(__name__)\nDEFAULT_API_BASE = \"https://hunyuan.cloud.tencent.com\"\nDEFAULT_PATH = \"/hyllm/v1/chat/completions\"\ndef _convert_message_to_dict(message: BaseMessage) -> dict:\n    message_dict: Dict[str, Any]\n    if isinstance(message, ChatMessage):\n        message_dict = {\"role\": message.role, \"content\": message.content}\n    elif isinstance(message, HumanMessage):\n        message_dict = {\"role\": \"user\", \"content\": message.content}\n    elif isinstance(message, AIMessage):\n        message_dict = {\"role\": \"assistant\", \"content\": message.content}\n    else:\n        raise TypeError(f\"Got unknown type {message}\")\n    return message_dict\ndef _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/hunyuan.html"}
{"id": "bc9525303fdf-1", "text": "def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:\n    role = _dict[\"role\"]\n    if role == \"user\":\n        return HumanMessage(content=_dict[\"content\"])\n    elif role == \"assistant\":\n        return AIMessage(content=_dict.get(\"content\", \"\") or \"\")\n    else:\n        return ChatMessage(content=_dict[\"content\"], role=role)\ndef _convert_delta_to_message_chunk(\n    _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]\n) -> BaseMessageChunk:\n    role = _dict.get(\"role\")\n    content = _dict.get(\"content\") or \"\"\n    if role == \"user\" or default_class == HumanMessageChunk:\n        return HumanMessageChunk(content=content)\n    elif role == \"assistant\" or default_class == AIMessageChunk:\n        return AIMessageChunk(content=content)\n    elif role or default_class == ChatMessageChunk:\n        return ChatMessageChunk(content=content, role=role)\n    else:\n        return default_class(content=content)\n# signature generation\n# https://cloud.tencent.com/document/product/1729/97732#532252ce-e960-48a7-8821-940a9ce2ccf3\ndef _signature(secret_key: SecretStr, url: str, payload: Dict[str, Any]) -> str:\n    sorted_keys = sorted(payload.keys())\n    url_info = urlparse(url)\n    sign_str = url_info.netloc + url_info.path + \"?\"\n    for key in sorted_keys:\n        value = payload[key]\n        if isinstance(value, list) or isinstance(value, dict):\n            value = json.dumps(value, separators=(\",\", \":\"))\n        elif isinstance(value, float):\n            value = \"%g\" % value", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/hunyuan.html"}
{"id": "bc9525303fdf-2", "text": "elif isinstance(value, float):\n            value = \"%g\" % value\n        sign_str = sign_str + key + \"=\" + str(value) + \"&\"\n    sign_str = sign_str[:-1]\n    hmacstr = hmac.new(\n        key=secret_key.get_secret_value().encode(\"utf-8\"),\n        msg=sign_str.encode(\"utf-8\"),\n        digestmod=hashlib.sha1,\n    ).digest()\n    return base64.b64encode(hmacstr).decode(\"utf-8\")\ndef _create_chat_result(response: Mapping[str, Any]) -> ChatResult:\n    generations = []\n    for choice in response[\"choices\"]:\n        message = _convert_dict_to_message(choice[\"messages\"])\n        generations.append(ChatGeneration(message=message))\n    token_usage = response[\"usage\"]\n    llm_output = {\"token_usage\": token_usage}\n    return ChatResult(generations=generations, llm_output=llm_output)\n[docs]class ChatHunyuan(BaseChatModel):\n    \"\"\"Tencent Hunyuan chat models API by Tencent.\n    For more information, see https://cloud.tencent.com/document/product/1729\n    \"\"\"\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\n            \"hunyuan_app_id\": \"HUNYUAN_APP_ID\",\n            \"hunyuan_secret_id\": \"HUNYUAN_SECRET_ID\",\n            \"hunyuan_secret_key\": \"HUNYUAN_SECRET_KEY\",\n        }\n    @property\n    def lc_serializable(self) -> bool:\n        return True\n    hunyuan_api_base: str = Field(default=DEFAULT_API_BASE)\n    \"\"\"Hunyuan custom endpoints\"\"\"\n    hunyuan_app_id: Optional[str] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/hunyuan.html"}
{"id": "bc9525303fdf-3", "text": "hunyuan_app_id: Optional[str] = None\n    \"\"\"Hunyuan App ID\"\"\"\n    hunyuan_secret_id: Optional[str] = None\n    \"\"\"Hunyuan Secret ID\"\"\"\n    hunyuan_secret_key: Optional[SecretStr] = None\n    \"\"\"Hunyuan Secret Key\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results or not.\"\"\"\n    request_timeout: int = 60\n    \"\"\"Timeout for requests to Hunyuan API. Default is 60 seconds.\"\"\"\n    query_id: Optional[str] = None\n    \"\"\"Query id for troubleshooting\"\"\"\n    temperature: float = 1.0\n    \"\"\"What sampling temperature to use.\"\"\"\n    top_p: float = 1.0\n    \"\"\"What probability mass to use.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for API call not explicitly specified.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        allow_population_by_field_name = True\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = get_pydantic_field_names(cls)\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name in extra:\n                raise ValueError(f\"Found {field_name} supplied twice.\")\n            if field_name not in all_required_field_names:\n                logger.warning(\n                    f\"\"\"WARNING! {field_name} is not default parameter.\n                    {field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/hunyuan.html"}
{"id": "bc9525303fdf-4", "text": "Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        invalid_model_kwargs = all_required_field_names.intersection(extra.keys())\n        if invalid_model_kwargs:\n            raise ValueError(\n                f\"Parameters {invalid_model_kwargs} should be specified explicitly. \"\n                f\"Instead they were passed in as part of `model_kwargs` parameter.\"\n            )\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        values[\"hunyuan_api_base\"] = get_from_dict_or_env(\n            values,\n            \"hunyuan_api_base\",\n            \"HUNYUAN_API_BASE\",\n            DEFAULT_API_BASE,\n        )\n        values[\"hunyuan_app_id\"] = get_from_dict_or_env(\n            values,\n            \"hunyuan_app_id\",\n            \"HUNYUAN_APP_ID\",\n        )\n        values[\"hunyuan_secret_id\"] = get_from_dict_or_env(\n            values,\n            \"hunyuan_secret_id\",\n            \"HUNYUAN_SECRET_ID\",\n        )\n        values[\"hunyuan_secret_key\"] = convert_to_secret_str(\n            get_from_dict_or_env(\n                values,\n                \"hunyuan_secret_key\",\n                \"HUNYUAN_SECRET_KEY\",\n            )\n        )\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Hunyuan API.\"\"\"\n        normal_params = {\n            \"app_id\": self.hunyuan_app_id,\n            \"secret_id\": self.hunyuan_secret_id,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/hunyuan.html"}
{"id": "bc9525303fdf-5", "text": "\"secret_id\": self.hunyuan_secret_id,\n            \"temperature\": self.temperature,\n            \"top_p\": self.top_p,\n        }\n        if self.query_id is not None:\n            normal_params[\"query_id\"] = self.query_id\n        return {**normal_params, **self.model_kwargs}\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        if self.streaming:\n            stream_iter = self._stream(\n                messages=messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return _generate_from_stream(stream_iter)\n        res = self._chat(messages, **kwargs)\n        response = res.json()\n        if \"error\" in response:\n            raise ValueError(f\"Error from Hunyuan api response: {response}\")\n        return _create_chat_result(response)\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        res = self._chat(messages, **kwargs)\n        default_chunk_class = AIMessageChunk\n        for chunk in res.iter_lines():\n            response = json.loads(chunk)\n            if \"error\" in response:\n                raise ValueError(f\"Error from Hunyuan api response: {response}\")\n            for choice in response[\"choices\"]:\n                chunk = _convert_delta_to_message_chunk(\n                    choice[\"delta\"], default_chunk_class\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/hunyuan.html"}
{"id": "bc9525303fdf-6", "text": "choice[\"delta\"], default_chunk_class\n                )\n                default_chunk_class = chunk.__class__\n                yield ChatGenerationChunk(message=chunk)\n                if run_manager:\n                    run_manager.on_llm_new_token(chunk.content)\n    def _chat(self, messages: List[BaseMessage], **kwargs: Any) -> requests.Response:\n        if self.hunyuan_secret_key is None:\n            raise ValueError(\"Hunyuan secret key is not set.\")\n        parameters = {**self._default_params, **kwargs}\n        headers = parameters.pop(\"headers\", {})\n        timestamp = parameters.pop(\"timestamp\", int(time.time()))\n        expired = parameters.pop(\"expired\", timestamp + 24 * 60 * 60)\n        payload = {\n            \"timestamp\": timestamp,\n            \"expired\": expired,\n            \"messages\": [_convert_message_to_dict(m) for m in messages],\n            **parameters,\n        }\n        if self.streaming:\n            payload[\"stream\"] = 1\n        url = self.hunyuan_api_base + DEFAULT_PATH\n        res = requests.post(\n            url=url,\n            timeout=self.request_timeout,\n            headers={\n                \"Content-Type\": \"application/json\",\n                \"Authorization\": _signature(\n                    secret_key=self.hunyuan_secret_key, url=url, payload=payload\n                ),\n                **headers,\n            },\n            json=payload,\n            stream=self.streaming,\n        )\n        return res\n    @property\n    def _llm_type(self) -> str:\n        return \"hunyuan-chat\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/hunyuan.html"}
{"id": "725d088e8c13-0", "text": "Source code for langchain.chat_models.ollama\nimport json\nfrom typing import Any, Iterator, List, Optional\nfrom langchain.callbacks.manager import (\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import BaseChatModel\nfrom langchain.llms.ollama import _OllamaCommon\nfrom langchain.schema import ChatResult\nfrom langchain.schema.messages import (\n    AIMessage,\n    AIMessageChunk,\n    BaseMessage,\n    ChatMessage,\n    HumanMessage,\n    SystemMessage,\n)\nfrom langchain.schema.output import ChatGeneration, ChatGenerationChunk\ndef _stream_response_to_chat_generation_chunk(\n    stream_response: str,\n) -> ChatGenerationChunk:\n    \"\"\"Convert a stream response to a generation chunk.\"\"\"\n    parsed_response = json.loads(stream_response)\n    generation_info = parsed_response if parsed_response.get(\"done\") is True else None\n    return ChatGenerationChunk(\n        message=AIMessageChunk(content=parsed_response.get(\"response\", \"\")),\n        generation_info=generation_info,\n    )\n[docs]class ChatOllama(BaseChatModel, _OllamaCommon):\n    \"\"\"Ollama locally runs large language models.\n    To use, follow the instructions at https://ollama.ai/.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import ChatOllama\n            ollama = ChatOllama(model=\"llama2\")\n    \"\"\"\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat model.\"\"\"\n        return \"ollama-chat\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this model can be serialized by Langchain.\"\"\"\n        return True", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/ollama.html"}
{"id": "725d088e8c13-1", "text": "\"\"\"Return whether this model can be serialized by Langchain.\"\"\"\n        return True\n    def _format_message_as_text(self, message: BaseMessage) -> str:\n        if isinstance(message, ChatMessage):\n            message_text = f\"\\n\\n{message.role.capitalize()}: {message.content}\"\n        elif isinstance(message, HumanMessage):\n            message_text = f\"[INST] {message.content} [/INST]\"\n        elif isinstance(message, AIMessage):\n            message_text = f\"{message.content}\"\n        elif isinstance(message, SystemMessage):\n            message_text = f\"<<SYS>> {message.content} <</SYS>>\"\n        else:\n            raise ValueError(f\"Got unknown type {message}\")\n        return message_text\n    def _format_messages_as_text(self, messages: List[BaseMessage]) -> str:\n        return \"\\n\".join(\n            [self._format_message_as_text(message) for message in messages]\n        )\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        \"\"\"Call out to Ollama's generate endpoint.\n        Args:\n            messages: The list of base messages to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            Chat generations from the model\n        Example:\n            .. code-block:: python\n                response = ollama([\n                    HumanMessage(content=\"Tell me about the history of AI\")\n                ])\n        \"\"\"\n        prompt = self._format_messages_as_text(messages)\n        final_chunk = super()._stream_with_aggregation(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/ollama.html"}
{"id": "725d088e8c13-2", "text": "final_chunk = super()._stream_with_aggregation(\n            prompt, stop=stop, run_manager=run_manager, verbose=self.verbose, **kwargs\n        )\n        chat_generation = ChatGeneration(\n            message=AIMessage(content=final_chunk.text),\n            generation_info=final_chunk.generation_info,\n        )\n        return ChatResult(generations=[chat_generation])\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        prompt = self._format_messages_as_text(messages)\n        for stream_resp in self._create_stream(prompt, stop, **kwargs):\n            if stream_resp:\n                chunk = _stream_response_to_chat_generation_chunk(stream_resp)\n                yield chunk\n                if run_manager:\n                    run_manager.on_llm_new_token(\n                        chunk.text,\n                        verbose=self.verbose,\n                    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/ollama.html"}
{"id": "68a8ae8de3c5-0", "text": "Source code for langchain.chat_models.openai\n\"\"\"OpenAI chat wrapper.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport os\nimport sys\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    AsyncIterator,\n    Callable,\n    Dict,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Sequence,\n    Tuple,\n    Type,\n    Union,\n)\nfrom langchain.adapters.openai import convert_dict_to_message, convert_message_to_dict\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.chat_models.base import (\n    BaseChatModel,\n    _agenerate_from_stream,\n    _generate_from_stream,\n)\nfrom langchain.llms.base import create_base_retry_decorator\nfrom langchain.pydantic_v1 import BaseModel, Field, root_validator\nfrom langchain.schema import ChatGeneration, ChatResult\nfrom langchain.schema.language_model import LanguageModelInput\nfrom langchain.schema.messages import (\n    AIMessageChunk,\n    BaseMessage,\n    BaseMessageChunk,\n    ChatMessageChunk,\n    FunctionMessageChunk,\n    HumanMessageChunk,\n    SystemMessageChunk,\n    ToolMessageChunk,\n)\nfrom langchain.schema.output import ChatGenerationChunk\nfrom langchain.schema.runnable import Runnable\nfrom langchain.utils import (\n    get_from_dict_or_env,\n    get_pydantic_field_names,\n)\nfrom langchain.utils.openai import is_openai_v1\nif TYPE_CHECKING:\n    import tiktoken\nlogger = logging.getLogger(__name__)\ndef _import_tiktoken() -> Any:\n    try:\n        import tiktoken\n    except ImportError:\n        raise ValueError(\n            \"Could not import tiktoken python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-1", "text": "raise ValueError(\n            \"Could not import tiktoken python package. \"\n            \"This is needed in order to calculate get_token_ids. \"\n            \"Please install it with `pip install tiktoken`.\"\n        )\n    return tiktoken\ndef _create_retry_decorator(\n    llm: ChatOpenAI,\n    run_manager: Optional[\n        Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]\n    ] = None,\n) -> Callable[[Any], Any]:\n    import openai\n    errors = [\n        openai.error.Timeout,\n        openai.error.APIError,\n        openai.error.APIConnectionError,\n        openai.error.RateLimitError,\n        openai.error.ServiceUnavailableError,\n    ]\n    return create_base_retry_decorator(\n        error_types=errors, max_retries=llm.max_retries, run_manager=run_manager\n    )\n[docs]async def acompletion_with_retry(\n    llm: ChatOpenAI,\n    run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the async completion call.\"\"\"\n    if is_openai_v1():\n        return await llm.async_client.create(**kwargs)\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @retry_decorator\n    async def _completion_with_retry(**kwargs: Any) -> Any:\n        # Use OpenAI's async api https://github.com/openai/openai-python#async-api\n        return await llm.client.acreate(**kwargs)\n    return await _completion_with_retry(**kwargs)\ndef _convert_delta_to_message_chunk(\n    _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-2", "text": "_dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]\n) -> BaseMessageChunk:\n    role = _dict.get(\"role\")\n    content = _dict.get(\"content\") or \"\"\n    additional_kwargs: Dict = {}\n    if _dict.get(\"function_call\"):\n        function_call = dict(_dict[\"function_call\"])\n        if \"name\" in function_call and function_call[\"name\"] is None:\n            function_call[\"name\"] = \"\"\n        additional_kwargs[\"function_call\"] = function_call\n    if _dict.get(\"tool_calls\"):\n        additional_kwargs[\"tool_calls\"] = _dict[\"tool_calls\"]\n    if role == \"user\" or default_class == HumanMessageChunk:\n        return HumanMessageChunk(content=content)\n    elif role == \"assistant\" or default_class == AIMessageChunk:\n        return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)\n    elif role == \"system\" or default_class == SystemMessageChunk:\n        return SystemMessageChunk(content=content)\n    elif role == \"function\" or default_class == FunctionMessageChunk:\n        return FunctionMessageChunk(content=content, name=_dict[\"name\"])\n    elif role == \"tool\" or default_class == ToolMessageChunk:\n        return ToolMessageChunk(content=content, tool_call_id=_dict[\"tool_call_id\"])\n    elif role or default_class == ChatMessageChunk:\n        return ChatMessageChunk(content=content, role=role)\n    else:\n        return default_class(content=content)\n[docs]class ChatOpenAI(BaseChatModel):\n    \"\"\"`OpenAI` Chat large language models API.\n    To use, you should have the ``openai`` python package installed, and the\n    environment variable ``OPENAI_API_KEY`` set with your API key.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-3", "text": "environment variable ``OPENAI_API_KEY`` set with your API key.\n    Any parameters that are valid to be passed to the openai.create call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import ChatOpenAI\n            openai = ChatOpenAI(model_name=\"gpt-3.5-turbo\")\n    \"\"\"\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"openai_api_key\": \"OPENAI_API_KEY\"}\n    @property\n    def lc_attributes(self) -> Dict[str, Any]:\n        attributes: Dict[str, Any] = {}\n        if self.openai_organization:\n            attributes[\"openai_organization\"] = self.openai_organization\n        if self.openai_api_base:\n            attributes[\"openai_api_base\"] = self.openai_api_base\n        if self.openai_proxy:\n            attributes[\"openai_proxy\"] = self.openai_proxy\n        return attributes\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this model can be serialized by Langchain.\"\"\"\n        return True\n    client: Any = Field(default=None, exclude=True)  #: :meta private:\n    async_client: Any = Field(default=None, exclude=True)  #: :meta private:\n    model_name: str = Field(default=\"gpt-3.5-turbo\", alias=\"model\")\n    \"\"\"Model name to use.\"\"\"\n    temperature: float = 0.7\n    \"\"\"What sampling temperature to use.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not explicitly specified.\"\"\"\n    # When updating this to use a SecretStr", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-4", "text": "# When updating this to use a SecretStr\n    # Check for classes that derive from this class (as some of them\n    # may assume openai_api_key is a str)\n    openai_api_key: Optional[str] = Field(default=None, alias=\"api_key\")\n    \"\"\"Automatically inferred from env var `OPENAI_API_KEY` if not provided.\"\"\"\n    openai_api_base: Optional[str] = Field(default=None, alias=\"base_url\")\n    \"\"\"Base URL path for API requests, leave blank if not using a proxy or service \n        emulator.\"\"\"\n    openai_organization: Optional[str] = Field(default=None, alias=\"organization\")\n    \"\"\"Automatically inferred from env var `OPENAI_ORG_ID` if not provided.\"\"\"\n    # to support explicit proxy for OpenAI\n    openai_proxy: Optional[str] = None\n    request_timeout: Union[float, Tuple[float, float], Any, None] = Field(\n        default=None, alias=\"timeout\"\n    )\n    \"\"\"Timeout for requests to OpenAI completion API. Can be float, httpx.Timeout or \n        None.\"\"\"\n    max_retries: int = 2\n    \"\"\"Maximum number of retries to make when generating.\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results or not.\"\"\"\n    n: int = 1\n    \"\"\"Number of chat completions to generate for each prompt.\"\"\"\n    max_tokens: Optional[int] = None\n    \"\"\"Maximum number of tokens to generate.\"\"\"\n    tiktoken_model_name: Optional[str] = None\n    \"\"\"The model name to pass to tiktoken when using this class. \n    Tiktoken is used to count the number of tokens in documents to constrain \n    them to be under a certain limit. By default, when set to None, this will", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-5", "text": "be the same as the embedding model name. However, there are some cases \n    where you may want to use this Embedding class with a model name not \n    supported by tiktoken. This can include when using Azure embeddings or \n    when using one of the many model providers that expose an OpenAI-like \n    API but with different models. In those cases, in order to avoid erroring \n    when tiktoken is called, you can specify a model name to use here.\"\"\"\n    default_headers: Union[Mapping[str, str], None] = None\n    default_query: Union[Mapping[str, object], None] = None\n    # Configure a custom httpx client. See the\n    # [httpx documentation](https://www.python-httpx.org/api/#client) for more details.\n    http_client: Union[Any, None] = None\n    \"\"\"Optional httpx.Client.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        allow_population_by_field_name = True\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = get_pydantic_field_names(cls)\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name in extra:\n                raise ValueError(f\"Found {field_name} supplied twice.\")\n            if field_name not in all_required_field_names:\n                logger.warning(\n                    f\"\"\"WARNING! {field_name} is not default parameter.\n                    {field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-6", "text": ")\n                extra[field_name] = values.pop(field_name)\n        invalid_model_kwargs = all_required_field_names.intersection(extra.keys())\n        if invalid_model_kwargs:\n            raise ValueError(\n                f\"Parameters {invalid_model_kwargs} should be specified explicitly. \"\n                f\"Instead they were passed in as part of `model_kwargs` parameter.\"\n            )\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        if values[\"n\"] < 1:\n            raise ValueError(\"n must be at least 1.\")\n        if values[\"n\"] > 1 and values[\"streaming\"]:\n            raise ValueError(\"n must be 1 when streaming.\")\n        values[\"openai_api_key\"] = get_from_dict_or_env(\n            values, \"openai_api_key\", \"OPENAI_API_KEY\"\n        )\n        # Check OPENAI_ORGANIZATION for backwards compatibility.\n        values[\"openai_organization\"] = (\n            values[\"openai_organization\"]\n            or os.getenv(\"OPENAI_ORG_ID\")\n            or os.getenv(\"OPENAI_ORGANIZATION\")\n        )\n        values[\"openai_api_base\"] = values[\"openai_api_base\"] or os.getenv(\n            \"OPENAI_API_BASE\"\n        )\n        values[\"openai_proxy\"] = get_from_dict_or_env(\n            values,\n            \"openai_proxy\",\n            \"OPENAI_PROXY\",\n            default=\"\",\n        )\n        try:\n            import openai\n        except ImportError:\n            raise ImportError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\"\n            )\n        if is_openai_v1():", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-7", "text": ")\n        if is_openai_v1():\n            client_params = {\n                \"api_key\": values[\"openai_api_key\"],\n                \"organization\": values[\"openai_organization\"],\n                \"base_url\": values[\"openai_api_base\"],\n                \"timeout\": values[\"request_timeout\"],\n                \"max_retries\": values[\"max_retries\"],\n                \"default_headers\": values[\"default_headers\"],\n                \"default_query\": values[\"default_query\"],\n                \"http_client\": values[\"http_client\"],\n            }\n            if not values.get(\"client\"):\n                values[\"client\"] = openai.OpenAI(**client_params).chat.completions\n            if not values.get(\"async_client\"):\n                values[\"async_client\"] = openai.AsyncOpenAI(\n                    **client_params\n                ).chat.completions\n        elif not values.get(\"client\"):\n            values[\"client\"] = openai.ChatCompletion\n        else:\n            pass\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling OpenAI API.\"\"\"\n        params = {\n            \"model\": self.model_name,\n            \"stream\": self.streaming,\n            \"n\": self.n,\n            \"temperature\": self.temperature,\n            **self.model_kwargs,\n        }\n        if self.max_tokens is not None:\n            params[\"max_tokens\"] = self.max_tokens\n        if self.request_timeout is not None and not is_openai_v1():\n            params[\"request_timeout\"] = self.request_timeout\n        return params\n[docs]    def completion_with_retry(\n        self, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any\n    ) -> Any:\n        \"\"\"Use tenacity to retry the completion call.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-8", "text": ") -> Any:\n        \"\"\"Use tenacity to retry the completion call.\"\"\"\n        if is_openai_v1():\n            return self.client.create(**kwargs)\n        retry_decorator = _create_retry_decorator(self, run_manager=run_manager)\n        @retry_decorator\n        def _completion_with_retry(**kwargs: Any) -> Any:\n            return self.client.create(**kwargs)\n        return _completion_with_retry(**kwargs)\n    def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:\n        overall_token_usage: dict = {}\n        system_fingerprint = None\n        for output in llm_outputs:\n            if output is None:\n                # Happens in streaming\n                continue\n            token_usage = output[\"token_usage\"]\n            for k, v in token_usage.items():\n                if k in overall_token_usage:\n                    overall_token_usage[k] += v\n                else:\n                    overall_token_usage[k] = v\n            if system_fingerprint is None:\n                system_fingerprint = output.get(\"system_fingerprint\")\n        combined = {\"token_usage\": overall_token_usage, \"model_name\": self.model_name}\n        if system_fingerprint:\n            combined[\"system_fingerprint\"] = system_fingerprint\n        return combined\n    def _stream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[ChatGenerationChunk]:\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs, \"stream\": True}\n        default_chunk_class = AIMessageChunk\n        for chunk in self.completion_with_retry(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-9", "text": "default_chunk_class = AIMessageChunk\n        for chunk in self.completion_with_retry(\n            messages=message_dicts, run_manager=run_manager, **params\n        ):\n            if not isinstance(chunk, dict):\n                chunk = chunk.dict()\n            if len(chunk[\"choices\"]) == 0:\n                continue\n            choice = chunk[\"choices\"][0]\n            chunk = _convert_delta_to_message_chunk(\n                choice[\"delta\"], default_chunk_class\n            )\n            finish_reason = choice.get(\"finish_reason\")\n            generation_info = (\n                dict(finish_reason=finish_reason) if finish_reason is not None else None\n            )\n            default_chunk_class = chunk.__class__\n            chunk = ChatGenerationChunk(message=chunk, generation_info=generation_info)\n            yield chunk\n            if run_manager:\n                run_manager.on_llm_new_token(chunk.text, chunk=chunk)\n    def _generate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        should_stream = stream if stream is not None else self.streaming\n        if should_stream:\n            stream_iter = self._stream(\n                messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return _generate_from_stream(stream_iter)\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs}\n        response = self.completion_with_retry(\n            messages=message_dicts, run_manager=run_manager, **params\n        )\n        return self._create_chat_result(response)\n    def _create_message_dicts(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-10", "text": "return self._create_chat_result(response)\n    def _create_message_dicts(\n        self, messages: List[BaseMessage], stop: Optional[List[str]]\n    ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:\n        params = self._client_params\n        if stop is not None:\n            if \"stop\" in params:\n                raise ValueError(\"`stop` found in both the input and default params.\")\n            params[\"stop\"] = stop\n        message_dicts = [convert_message_to_dict(m) for m in messages]\n        return message_dicts, params\n    def _create_chat_result(self, response: Union[dict, BaseModel]) -> ChatResult:\n        generations = []\n        if not isinstance(response, dict):\n            response = response.dict()\n        for res in response[\"choices\"]:\n            message = convert_dict_to_message(res[\"message\"])\n            gen = ChatGeneration(\n                message=message,\n                generation_info=dict(finish_reason=res.get(\"finish_reason\")),\n            )\n            generations.append(gen)\n        token_usage = response.get(\"usage\", {})\n        llm_output = {\n            \"token_usage\": token_usage,\n            \"model_name\": self.model_name,\n            \"system_fingerprint\": response.get(\"system_fingerprint\", \"\"),\n        }\n        return ChatResult(generations=generations, llm_output=llm_output)\n    async def _astream(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[ChatGenerationChunk]:\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs, \"stream\": True}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-11", "text": "params = {**params, **kwargs, \"stream\": True}\n        default_chunk_class = AIMessageChunk\n        async for chunk in await acompletion_with_retry(\n            self, messages=message_dicts, run_manager=run_manager, **params\n        ):\n            if not isinstance(chunk, dict):\n                chunk = chunk.dict()\n            if len(chunk[\"choices\"]) == 0:\n                continue\n            choice = chunk[\"choices\"][0]\n            chunk = _convert_delta_to_message_chunk(\n                choice[\"delta\"], default_chunk_class\n            )\n            finish_reason = choice.get(\"finish_reason\")\n            generation_info = (\n                dict(finish_reason=finish_reason) if finish_reason is not None else None\n            )\n            default_chunk_class = chunk.__class__\n            chunk = ChatGenerationChunk(message=chunk, generation_info=generation_info)\n            yield chunk\n            if run_manager:\n                await run_manager.on_llm_new_token(token=chunk.text, chunk=chunk)\n    async def _agenerate(\n        self,\n        messages: List[BaseMessage],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> ChatResult:\n        should_stream = stream if stream is not None else self.streaming\n        if should_stream:\n            stream_iter = self._astream(\n                messages, stop=stop, run_manager=run_manager, **kwargs\n            )\n            return await _agenerate_from_stream(stream_iter)\n        message_dicts, params = self._create_message_dicts(messages, stop)\n        params = {**params, **kwargs}\n        response = await acompletion_with_retry(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-12", "text": "response = await acompletion_with_retry(\n            self, messages=message_dicts, run_manager=run_manager, **params\n        )\n        return self._create_chat_result(response)\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model_name\": self.model_name}, **self._default_params}\n    @property\n    def _client_params(self) -> Dict[str, Any]:\n        \"\"\"Get the parameters used for the openai client.\"\"\"\n        openai_creds: Dict[str, Any] = {\n            \"model\": self.model_name,\n        }\n        if not is_openai_v1():\n            openai_creds.update(\n                {\n                    \"api_key\": self.openai_api_key,\n                    \"api_base\": self.openai_api_base,\n                    \"organization\": self.openai_organization,\n                }\n            )\n        if self.openai_proxy:\n            import openai\n            openai.proxy = {\"http\": self.openai_proxy, \"https\": self.openai_proxy}  # type: ignore[assignment]  # noqa: E501\n        return {**self._default_params, **openai_creds}\n    def _get_invocation_params(\n        self, stop: Optional[List[str]] = None, **kwargs: Any\n    ) -> Dict[str, Any]:\n        \"\"\"Get the parameters used to invoke the model.\"\"\"\n        return {\n            \"model\": self.model_name,\n            **super()._get_invocation_params(stop=stop),\n            **self._default_params,\n            **kwargs,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of chat model.\"\"\"\n        return \"openai-chat\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-13", "text": "\"\"\"Return type of chat model.\"\"\"\n        return \"openai-chat\"\n    def _get_encoding_model(self) -> Tuple[str, tiktoken.Encoding]:\n        tiktoken_ = _import_tiktoken()\n        if self.tiktoken_model_name is not None:\n            model = self.tiktoken_model_name\n        else:\n            model = self.model_name\n            if model == \"gpt-3.5-turbo\":\n                # gpt-3.5-turbo may change over time.\n                # Returning num tokens assuming gpt-3.5-turbo-0301.\n                model = \"gpt-3.5-turbo-0301\"\n            elif model == \"gpt-4\":\n                # gpt-4 may change over time.\n                # Returning num tokens assuming gpt-4-0314.\n                model = \"gpt-4-0314\"\n        # Returns the number of tokens used by a list of messages.\n        try:\n            encoding = tiktoken_.encoding_for_model(model)\n        except KeyError:\n            logger.warning(\"Warning: model not found. Using cl100k_base encoding.\")\n            model = \"cl100k_base\"\n            encoding = tiktoken_.get_encoding(model)\n        return model, encoding\n[docs]    def get_token_ids(self, text: str) -> List[int]:\n        \"\"\"Get the tokens present in the text with tiktoken package.\"\"\"\n        # tiktoken NOT supported for Python 3.7 or below\n        if sys.version_info[1] <= 7:\n            return super().get_token_ids(text)\n        _, encoding_model = self._get_encoding_model()\n        return encoding_model.encode(text)\n[docs]    def get_num_tokens_from_messages(self, messages: List[BaseMessage]) -> int:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-14", "text": "\"\"\"Calculate num tokens for gpt-3.5-turbo and gpt-4 with tiktoken package.\n        Official documentation: https://github.com/openai/openai-cookbook/blob/\n        main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb\"\"\"\n        if sys.version_info[1] <= 7:\n            return super().get_num_tokens_from_messages(messages)\n        model, encoding = self._get_encoding_model()\n        if model.startswith(\"gpt-3.5-turbo-0301\"):\n            # every message follows <im_start>{role/name}\\n{content}<im_end>\\n\n            tokens_per_message = 4\n            # if there's a name, the role is omitted\n            tokens_per_name = -1\n        elif model.startswith(\"gpt-3.5-turbo\") or model.startswith(\"gpt-4\"):\n            tokens_per_message = 3\n            tokens_per_name = 1\n        else:\n            raise NotImplementedError(\n                f\"get_num_tokens_from_messages() is not presently implemented \"\n                f\"for model {model}.\"\n                \"See https://github.com/openai/openai-python/blob/main/chatml.md for \"\n                \"information on how messages are converted to tokens.\"\n            )\n        num_tokens = 0\n        messages_dict = [convert_message_to_dict(m) for m in messages]\n        for message in messages_dict:\n            num_tokens += tokens_per_message\n            for key, value in message.items():\n                # Cast str(value) in case the message value is not a string\n                # This occurs with function messages\n                num_tokens += len(encoding.encode(str(value)))\n                if key == \"name\":\n                    num_tokens += tokens_per_name\n        # every reply is primed with <im_start>assistant", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-15", "text": "# every reply is primed with <im_start>assistant\n        num_tokens += 3\n        return num_tokens\n[docs]    def bind_functions(\n        self,\n        functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]],\n        function_call: Optional[str] = None,\n        **kwargs: Any,\n    ) -> Runnable[LanguageModelInput, BaseMessage]:\n        \"\"\"Bind functions (and other objects) to this chat model.\n        Args:\n            functions: A list of function definitions to bind to this chat model.\n                Can be  a dictionary, pydantic model, or callable. Pydantic\n                models and callables will be automatically converted to\n                their schema dictionary representation.\n            function_call: Which function to require the model to call.\n                Must be the name of the single provided function or\n                \"auto\" to automatically determine which function to call\n                (if any).\n            kwargs: Any additional parameters to pass to the\n                :class:`~langchain.runnable.Runnable` constructor.\n        \"\"\"\n        from langchain.chains.openai_functions.base import convert_to_openai_function\n        formatted_functions = [convert_to_openai_function(fn) for fn in functions]\n        if function_call is not None:\n            if len(formatted_functions) != 1:\n                raise ValueError(\n                    \"When specifying `function_call`, you must provide exactly one \"\n                    \"function.\"\n                )\n            if formatted_functions[0][\"name\"] != function_call:\n                raise ValueError(\n                    f\"Function call {function_call} was specified, but the only \"\n                    f\"provided function was {formatted_functions[0]['name']}.\"\n                )\n            function_call_ = {\"name\": function_call}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "68a8ae8de3c5-16", "text": ")\n            function_call_ = {\"name\": function_call}\n            kwargs = {**kwargs, \"function_call\": function_call_}\n        return super().bind(\n            functions=formatted_functions,\n            **kwargs,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html"}
{"id": "064a9b403032-0", "text": "Source code for langchain.chat_loaders.gmail\nimport base64\nimport re\nfrom typing import Any, Iterator\nfrom langchain.chat_loaders.base import BaseChatLoader\nfrom langchain.schema.chat import ChatSession\nfrom langchain.schema.messages import HumanMessage\ndef _extract_email_content(msg: Any) -> HumanMessage:\n    from_email = None\n    for values in msg[\"payload\"][\"headers\"]:\n        name = values[\"name\"]\n        if name == \"From\":\n            from_email = values[\"value\"]\n    if from_email is None:\n        raise ValueError\n    for part in msg[\"payload\"][\"parts\"]:\n        if part[\"mimeType\"] == \"text/plain\":\n            data = part[\"body\"][\"data\"]\n            data = base64.urlsafe_b64decode(data).decode(\"utf-8\")\n            # Regular expression to split the email body at the first\n            # occurrence of a line that starts with \"On ... wrote:\"\n            pattern = re.compile(r\"\\r\\nOn .+(\\r\\n)*wrote:\\r\\n\")\n            # Split the email body and extract the first part\n            newest_response = re.split(pattern, data)[0]\n            message = HumanMessage(\n                content=newest_response, additional_kwargs={\"sender\": from_email}\n            )\n            return message\n    raise ValueError\ndef _get_message_data(service: Any, message: Any) -> ChatSession:\n    msg = service.users().messages().get(userId=\"me\", id=message[\"id\"]).execute()\n    message_content = _extract_email_content(msg)\n    in_reply_to = None\n    email_data = msg[\"payload\"][\"headers\"]\n    for values in email_data:\n        name = values[\"name\"]\n        if name == \"In-Reply-To\":\n            in_reply_to = values[\"value\"]\n    if in_reply_to is None:\n        raise ValueError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/gmail.html"}
{"id": "064a9b403032-1", "text": "if in_reply_to is None:\n        raise ValueError\n    thread_id = msg[\"threadId\"]\n    thread = service.users().threads().get(userId=\"me\", id=thread_id).execute()\n    messages = thread[\"messages\"]\n    response_email = None\n    for message in messages:\n        email_data = message[\"payload\"][\"headers\"]\n        for values in email_data:\n            if values[\"name\"] == \"Message-ID\":\n                message_id = values[\"value\"]\n                if message_id == in_reply_to:\n                    response_email = message\n    if response_email is None:\n        raise ValueError\n    starter_content = _extract_email_content(response_email)\n    return ChatSession(messages=[starter_content, message_content])\n[docs]class GMailLoader(BaseChatLoader):\n    \"\"\"Load data from `GMail`.\n    There are many ways you could want to load data from GMail.\n    This loader is currently fairly opinionated in how to do so.\n    The way it does it is it first looks for all messages that you have sent.\n    It then looks for messages where you are responding to a previous email.\n    It then fetches that previous email, and creates a training example\n    of that email, followed by your email.\n    Note that there are clear limitations here. For example,\n    all examples created are only looking at the previous email for context.\n    To use:\n    - Set up a Google Developer Account:\n        Go to the Google Developer Console, create a project,\n        and enable the Gmail API for that project.\n        This will give you a credentials.json file that you'll need later.\n    \"\"\"\n[docs]    def __init__(self, creds: Any, n: int = 100, raise_error: bool = False) -> None:\n        super().__init__()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/gmail.html"}
{"id": "064a9b403032-2", "text": "super().__init__()\n        self.creds = creds\n        self.n = n\n        self.raise_error = raise_error\n[docs]    def lazy_load(self) -> Iterator[ChatSession]:\n        from googleapiclient.discovery import build\n        service = build(\"gmail\", \"v1\", credentials=self.creds)\n        results = (\n            service.users()\n            .messages()\n            .list(userId=\"me\", labelIds=[\"SENT\"], maxResults=self.n)\n            .execute()\n        )\n        messages = results.get(\"messages\", [])\n        for message in messages:\n            try:\n                yield _get_message_data(service, message)\n            except Exception as e:\n                # TODO: handle errors better\n                if self.raise_error:\n                    raise e\n                else:\n                    pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/gmail.html"}
{"id": "7c54ae1edfd2-0", "text": "Source code for langchain.chat_loaders.base\nfrom abc import ABC, abstractmethod\nfrom typing import Iterator, List\nfrom langchain.schema.chat import ChatSession\n[docs]class BaseChatLoader(ABC):\n    \"\"\"Base class for chat loaders.\"\"\"\n[docs]    @abstractmethod\n    def lazy_load(self) -> Iterator[ChatSession]:\n        \"\"\"Lazy load the chat sessions.\"\"\"\n[docs]    def load(self) -> List[ChatSession]:\n        \"\"\"Eagerly load the chat sessions into memory.\"\"\"\n        return list(self.lazy_load())", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/base.html"}
{"id": "c4382d75a139-0", "text": "Source code for langchain.chat_loaders.imessage\nfrom __future__ import annotations\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Iterator, List, Optional, Union\nfrom langchain.chat_loaders.base import BaseChatLoader\nfrom langchain.schema import HumanMessage\nfrom langchain.schema.chat import ChatSession\nif TYPE_CHECKING:\n    import sqlite3\n[docs]class IMessageChatLoader(BaseChatLoader):\n    \"\"\"Load chat sessions from the `iMessage` chat.db SQLite file.\n    It only works on macOS when you have iMessage enabled and have the chat.db file.\n    The chat.db file is likely located at ~/Library/Messages/chat.db. However, your\n    terminal may not have permission to access this file. To resolve this, you can\n    copy the file to a different location, change the permissions of the file, or\n    grant full disk access for your terminal emulator\n    in System Settings > Security and Privacy > Full Disk Access.\n    \"\"\"\n[docs]    def __init__(self, path: Optional[Union[str, Path]] = None):\n        \"\"\"\n        Initialize the IMessageChatLoader.\n        Args:\n            path (str or Path, optional): Path to the chat.db SQLite file.\n                Defaults to None, in which case the default path\n                ~/Library/Messages/chat.db will be used.\n        \"\"\"\n        if path is None:\n            path = Path.home() / \"Library\" / \"Messages\" / \"chat.db\"\n        self.db_path = path if isinstance(path, Path) else Path(path)\n        if not self.db_path.exists():\n            raise FileNotFoundError(f\"File {self.db_path} not found\")\n        try:\n            import sqlite3  # noqa: F401\n        except ImportError as e:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/imessage.html"}
{"id": "c4382d75a139-1", "text": "except ImportError as e:\n            raise ImportError(\n                \"The sqlite3 module is required to load iMessage chats.\\n\"\n                \"Please install it with `pip install pysqlite3`\"\n            ) from e\n    def _load_single_chat_session(\n        self, cursor: \"sqlite3.Cursor\", chat_id: int\n    ) -> ChatSession:\n        \"\"\"\n        Load a single chat session from the iMessage chat.db.\n        Args:\n            cursor: SQLite cursor object.\n            chat_id (int): ID of the chat session to load.\n        Returns:\n            ChatSession: Loaded chat session.\n        \"\"\"\n        results: List[HumanMessage] = []\n        query = \"\"\"\n        SELECT message.date, handle.id, message.text\n        FROM message\n        JOIN chat_message_join ON message.ROWID = chat_message_join.message_id\n        JOIN handle ON message.handle_id = handle.ROWID\n        WHERE chat_message_join.chat_id = ?\n        ORDER BY message.date ASC;\n        \"\"\"\n        cursor.execute(query, (chat_id,))\n        messages = cursor.fetchall()\n        for date, sender, text in messages:\n            if text:  # Skip empty messages\n                results.append(\n                    HumanMessage(\n                        role=sender,\n                        content=text,\n                        additional_kwargs={\n                            \"message_time\": date,\n                            \"sender\": sender,\n                        },\n                    )\n                )\n        return ChatSession(messages=results)\n[docs]    def lazy_load(self) -> Iterator[ChatSession]:\n        \"\"\"\n        Lazy load the chat sessions from the iMessage chat.db\n        and yield them in the required format.\n        Yields:\n            ChatSession: Loaded chat session.\n        \"\"\"\n        import sqlite3\n        try:\n            conn = sqlite3.connect(self.db_path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/imessage.html"}
{"id": "c4382d75a139-2", "text": "import sqlite3\n        try:\n            conn = sqlite3.connect(self.db_path)\n        except sqlite3.OperationalError as e:\n            raise ValueError(\n                f\"Could not open iMessage DB file {self.db_path}.\\n\"\n                \"Make sure your terminal emulator has disk access to this file.\\n\"\n                \"   You can either copy the DB file to an accessible location\"\n                \" or grant full disk access for your terminal emulator.\"\n                \"  You can grant full disk access for your terminal emulator\"\n                \" in System Settings > Security and Privacy > Full Disk Access.\"\n            ) from e\n        cursor = conn.cursor()\n        # Fetch the list of chat IDs sorted by time (most recent first)\n        query = \"\"\"SELECT chat_id\n        FROM message\n        JOIN chat_message_join ON message.ROWID = chat_message_join.message_id\n        GROUP BY chat_id\n        ORDER BY MAX(date) DESC;\"\"\"\n        cursor.execute(query)\n        chat_ids = [row[0] for row in cursor.fetchall()]\n        for chat_id in chat_ids:\n            yield self._load_single_chat_session(cursor, chat_id)\n        conn.close()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/imessage.html"}
{"id": "ce783fcc1491-0", "text": "Source code for langchain.chat_loaders.utils\n\"\"\"Utilities for chat loaders.\"\"\"\nfrom copy import deepcopy\nfrom typing import Iterable, Iterator, List\nfrom langchain.schema.chat import ChatSession\nfrom langchain.schema.messages import AIMessage, BaseMessage\n[docs]def merge_chat_runs_in_session(\n    chat_session: ChatSession, delimiter: str = \"\\n\\n\"\n) -> ChatSession:\n    \"\"\"Merge chat runs together in a chat session.\n    A chat run is a sequence of messages from the same sender.\n    Args:\n        chat_session: A chat session.\n    Returns:\n        A chat session with merged chat runs.\n    \"\"\"\n    messages: List[BaseMessage] = []\n    for message in chat_session[\"messages\"]:\n        if not isinstance(message.content, str):\n            raise ValueError(\n                \"Chat Loaders only support messages with content type string, \"\n                f\"got {message.content}\"\n            )\n        if not messages:\n            messages.append(deepcopy(message))\n        elif (\n            isinstance(message, type(messages[-1]))\n            and messages[-1].additional_kwargs.get(\"sender\") is not None\n            and messages[-1].additional_kwargs[\"sender\"]\n            == message.additional_kwargs.get(\"sender\")\n        ):\n            if not isinstance(messages[-1].content, str):\n                raise ValueError(\n                    \"Chat Loaders only support messages with content type string, \"\n                    f\"got {messages[-1].content}\"\n                )\n            messages[-1].content = (\n                messages[-1].content + delimiter + message.content\n            ).strip()\n            messages[-1].additional_kwargs.get(\"events\", []).extend(\n                message.additional_kwargs.get(\"events\") or []\n            )\n        else:\n            messages.append(deepcopy(message))\n    return ChatSession(messages=messages)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/utils.html"}
{"id": "ce783fcc1491-1", "text": "messages.append(deepcopy(message))\n    return ChatSession(messages=messages)\n[docs]def merge_chat_runs(chat_sessions: Iterable[ChatSession]) -> Iterator[ChatSession]:\n    \"\"\"Merge chat runs together.\n    A chat run is a sequence of messages from the same sender.\n    Args:\n        chat_sessions: A list of chat sessions.\n    Returns:\n        A list of chat sessions with merged chat runs.\n    \"\"\"\n    for chat_session in chat_sessions:\n        yield merge_chat_runs_in_session(chat_session)\n[docs]def map_ai_messages_in_session(chat_sessions: ChatSession, sender: str) -> ChatSession:\n    \"\"\"Convert messages from the specified 'sender' to AI messages.\n    This is useful for fine-tuning the AI to adapt to your voice.\n    \"\"\"\n    messages = []\n    num_converted = 0\n    for message in chat_sessions[\"messages\"]:\n        if message.additional_kwargs.get(\"sender\") == sender:\n            message = AIMessage(\n                content=message.content,\n                additional_kwargs=message.additional_kwargs.copy(),\n                example=getattr(message, \"example\", None),\n            )\n            num_converted += 1\n        messages.append(message)\n    return ChatSession(messages=messages)\n[docs]def map_ai_messages(\n    chat_sessions: Iterable[ChatSession], sender: str\n) -> Iterator[ChatSession]:\n    \"\"\"Convert messages from the specified 'sender' to AI messages.\n    This is useful for fine-tuning the AI to adapt to your voice.\n    \"\"\"\n    for chat_session in chat_sessions:\n        yield map_ai_messages_in_session(chat_session, sender)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/utils.html"}
{"id": "2c178cc73461-0", "text": "Source code for langchain.chat_loaders.whatsapp\nimport logging\nimport os\nimport re\nimport zipfile\nfrom typing import Iterator, List, Union\nfrom langchain.chat_loaders.base import BaseChatLoader\nfrom langchain.schema import AIMessage, HumanMessage\nfrom langchain.schema.chat import ChatSession\nlogger = logging.getLogger(__name__)\n[docs]class WhatsAppChatLoader(BaseChatLoader):\n    \"\"\"Load `WhatsApp` conversations from a dump zip file or directory.\"\"\"\n[docs]    def __init__(self, path: str):\n        \"\"\"Initialize the WhatsAppChatLoader.\n        Args:\n            path (str): Path to the exported WhatsApp chat\n                zip directory, folder, or file.\n        To generate the dump, open the chat, click the three dots in the top\n        right corner, and select \"More\". Then select \"Export chat\" and\n        choose \"Without media\".\n        \"\"\"\n        self.path = path\n        ignore_lines = [\n            \"This message was deleted\",\n            \"<Media omitted>\",\n            \"image omitted\",\n            \"Messages and calls are end-to-end encrypted. No one outside of this chat,\"\n            \" not even WhatsApp, can read or listen to them.\",\n        ]\n        self._ignore_lines = re.compile(\n            r\"(\" + \"|\".join([r\"\\u200E*\" + line for line in ignore_lines]) + r\")\",\n            flags=re.IGNORECASE,\n        )\n        self._message_line_regex = re.compile(\n            r\"\\u200E*\\[?(\\d{1,2}/\\d{1,2}/\\d{2,4}, \\d{1,2}:\\d{2}:\\d{2} (?:AM|PM))\\]?[ \\u200E]*([^:]+): (.+)\",  # noqa\n            flags=re.IGNORECASE,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/whatsapp.html"}
{"id": "2c178cc73461-1", "text": "flags=re.IGNORECASE,\n        )\n    def _load_single_chat_session(self, file_path: str) -> ChatSession:\n        \"\"\"Load a single chat session from a file.\n        Args:\n            file_path (str): Path to the chat file.\n        Returns:\n            ChatSession: The loaded chat session.\n        \"\"\"\n        with open(file_path, \"r\", encoding=\"utf-8\") as file:\n            txt = file.read()\n        # Split messages by newlines, but keep multi-line messages grouped\n        chat_lines: List[str] = []\n        current_message = \"\"\n        for line in txt.split(\"\\n\"):\n            if self._message_line_regex.match(line):\n                if current_message:\n                    chat_lines.append(current_message)\n                current_message = line\n            else:\n                current_message += \" \" + line.strip()\n        if current_message:\n            chat_lines.append(current_message)\n        results: List[Union[HumanMessage, AIMessage]] = []\n        for line in chat_lines:\n            result = self._message_line_regex.match(line.strip())\n            if result:\n                timestamp, sender, text = result.groups()\n                if not self._ignore_lines.match(text.strip()):\n                    results.append(\n                        HumanMessage(\n                            role=sender,\n                            content=text,\n                            additional_kwargs={\n                                \"sender\": sender,\n                                \"events\": [{\"message_time\": timestamp}],\n                            },\n                        )\n                    )\n            else:\n                logger.debug(f\"Could not parse line: {line}\")\n        return ChatSession(messages=results)\n    def _iterate_files(self, path: str) -> Iterator[str]:\n        \"\"\"Iterate over the files in a directory or zip file.\n        Args:\n            path (str): Path to the directory or zip file.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/whatsapp.html"}
{"id": "2c178cc73461-2", "text": "Args:\n            path (str): Path to the directory or zip file.\n        Yields:\n            str: The path to each file.\n        \"\"\"\n        if os.path.isfile(path):\n            yield path\n        elif os.path.isdir(path):\n            for root, _, files in os.walk(path):\n                for file in files:\n                    if file.endswith(\".txt\"):\n                        yield os.path.join(root, file)\n        elif zipfile.is_zipfile(path):\n            with zipfile.ZipFile(path) as zip_file:\n                for file in zip_file.namelist():\n                    if file.endswith(\".txt\"):\n                        yield zip_file.extract(file)\n[docs]    def lazy_load(self) -> Iterator[ChatSession]:\n        \"\"\"Lazy load the messages from the chat file and yield\n        them as chat sessions.\n        Yields:\n            Iterator[ChatSession]: The loaded chat sessions.\n        \"\"\"\n        yield self._load_single_chat_session(self.path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/whatsapp.html"}
{"id": "b806c36ce6f7-0", "text": "Source code for langchain.chat_loaders.slack\nimport json\nimport logging\nimport re\nimport zipfile\nfrom pathlib import Path\nfrom typing import Dict, Iterator, List, Union\nfrom langchain.chat_loaders.base import BaseChatLoader\nfrom langchain.schema import AIMessage, HumanMessage\nfrom langchain.schema.chat import ChatSession\nlogger = logging.getLogger(__name__)\n[docs]class SlackChatLoader(BaseChatLoader):\n    \"\"\"Load `Slack` conversations from a dump zip file.\"\"\"\n[docs]    def __init__(\n        self,\n        path: Union[str, Path],\n    ):\n        \"\"\"\n        Initialize the chat loader with the path to the exported Slack dump zip file.\n        :param path: Path to the exported Slack dump zip file.\n        \"\"\"\n        self.zip_path = path if isinstance(path, Path) else Path(path)\n        if not self.zip_path.exists():\n            raise FileNotFoundError(f\"File {self.zip_path} not found\")\n    def _load_single_chat_session(self, messages: List[Dict]) -> ChatSession:\n        results: List[Union[AIMessage, HumanMessage]] = []\n        previous_sender = None\n        for message in messages:\n            if not isinstance(message, dict):\n                continue\n            text = message.get(\"text\", \"\")\n            timestamp = message.get(\"ts\", \"\")\n            sender = message.get(\"user\", \"\")\n            if not sender:\n                continue\n            skip_pattern = re.compile(\n                r\"<@U\\d+> has joined the channel\", flags=re.IGNORECASE\n            )\n            if skip_pattern.match(text):\n                continue\n            if sender == previous_sender:\n                results[-1].content += \"\\n\\n\" + text\n                results[-1].additional_kwargs[\"events\"].append(\n                    {\"message_time\": timestamp}\n                )\n            else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/slack.html"}
{"id": "b806c36ce6f7-1", "text": "{\"message_time\": timestamp}\n                )\n            else:\n                results.append(\n                    HumanMessage(\n                        role=sender,\n                        content=text,\n                        additional_kwargs={\n                            \"sender\": sender,\n                            \"events\": [{\"message_time\": timestamp}],\n                        },\n                    )\n                )\n            previous_sender = sender\n        return ChatSession(messages=results)\n    def _read_json(self, zip_file: zipfile.ZipFile, file_path: str) -> List[dict]:\n        \"\"\"Read JSON data from a zip subfile.\"\"\"\n        with zip_file.open(file_path, \"r\") as f:\n            data = json.load(f)\n        if not isinstance(data, list):\n            raise ValueError(f\"Expected list of dictionaries, got {type(data)}\")\n        return data\n[docs]    def lazy_load(self) -> Iterator[ChatSession]:\n        \"\"\"\n        Lazy load the chat sessions from the Slack dump file and yield them\n        in the required format.\n        :return: Iterator of chat sessions containing messages.\n        \"\"\"\n        with zipfile.ZipFile(str(self.zip_path), \"r\") as zip_file:\n            for file_path in zip_file.namelist():\n                if file_path.endswith(\".json\"):\n                    messages = self._read_json(zip_file, file_path)\n                    yield self._load_single_chat_session(messages)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/slack.html"}
{"id": "a3a353173816-0", "text": "Source code for langchain.chat_loaders.telegram\nimport json\nimport logging\nimport os\nimport tempfile\nimport zipfile\nfrom pathlib import Path\nfrom typing import Iterator, List, Union\nfrom langchain.chat_loaders.base import BaseChatLoader\nfrom langchain.schema import AIMessage, BaseMessage, HumanMessage\nfrom langchain.schema.chat import ChatSession\nlogger = logging.getLogger(__name__)\n[docs]class TelegramChatLoader(BaseChatLoader):\n    \"\"\"Load `telegram` conversations to LangChain chat messages.\n    To export, use the Telegram Desktop app from\n    https://desktop.telegram.org/, select a conversation, click the three dots\n    in the top right corner, and select \"Export chat history\". Then select\n    \"Machine-readable JSON\" (preferred) to export. Note: the 'lite' versions of\n    the desktop app (like \"Telegram for MacOS\") do not support exporting chat\n    history.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        path: Union[str, Path],\n    ):\n        \"\"\"Initialize the TelegramChatLoader.\n        Args:\n            path (Union[str, Path]): Path to the exported Telegram chat zip,\n                 directory, json, or HTML file.\n        \"\"\"\n        self.path = path if isinstance(path, str) else str(path)\n    def _load_single_chat_session_html(self, file_path: str) -> ChatSession:\n        \"\"\"Load a single chat session from an HTML file.\n        Args:\n            file_path (str): Path to the HTML file.\n        Returns:\n            ChatSession: The loaded chat session.\n        \"\"\"\n        try:\n            from bs4 import BeautifulSoup\n        except ImportError:\n            raise ImportError(\n                \"Please install the 'beautifulsoup4' package to load\"\n                \" Telegram HTML files. You can do this by running\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/telegram.html"}
{"id": "a3a353173816-1", "text": "\" Telegram HTML files. You can do this by running\"\n                \"'pip install beautifulsoup4' in your terminal.\"\n            )\n        with open(file_path, \"r\", encoding=\"utf-8\") as file:\n            soup = BeautifulSoup(file, \"html.parser\")\n        results: List[Union[HumanMessage, AIMessage]] = []\n        previous_sender = None\n        for message in soup.select(\".message.default\"):\n            timestamp = message.select_one(\".pull_right.date.details\")[\"title\"]\n            from_name_element = message.select_one(\".from_name\")\n            if from_name_element is None and previous_sender is None:\n                logger.debug(\"from_name not found in message\")\n                continue\n            elif from_name_element is None:\n                from_name = previous_sender\n            else:\n                from_name = from_name_element.text.strip()\n            text = message.select_one(\".text\").text.strip()\n            results.append(\n                HumanMessage(\n                    content=text,\n                    additional_kwargs={\n                        \"sender\": from_name,\n                        \"events\": [{\"message_time\": timestamp}],\n                    },\n                )\n            )\n            previous_sender = from_name\n        return ChatSession(messages=results)\n    def _load_single_chat_session_json(self, file_path: str) -> ChatSession:\n        \"\"\"Load a single chat session from a JSON file.\n        Args:\n            file_path (str): Path to the JSON file.\n        Returns:\n            ChatSession: The loaded chat session.\n        \"\"\"\n        with open(file_path, \"r\", encoding=\"utf-8\") as file:\n            data = json.load(file)\n        messages = data.get(\"messages\", [])\n        results: List[BaseMessage] = []\n        for message in messages:\n            text = message.get(\"text\", \"\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/telegram.html"}
{"id": "a3a353173816-2", "text": "for message in messages:\n            text = message.get(\"text\", \"\")\n            timestamp = message.get(\"date\", \"\")\n            from_name = message.get(\"from\", \"\")\n            results.append(\n                HumanMessage(\n                    content=text,\n                    additional_kwargs={\n                        \"sender\": from_name,\n                        \"events\": [{\"message_time\": timestamp}],\n                    },\n                )\n            )\n        return ChatSession(messages=results)\n    def _iterate_files(self, path: str) -> Iterator[str]:\n        \"\"\"Iterate over files in a directory or zip file.\n        Args:\n            path (str): Path to the directory or zip file.\n        Yields:\n            str: Path to each file.\n        \"\"\"\n        if os.path.isfile(path) and path.endswith((\".html\", \".json\")):\n            yield path\n        elif os.path.isdir(path):\n            for root, _, files in os.walk(path):\n                for file in files:\n                    if file.endswith((\".html\", \".json\")):\n                        yield os.path.join(root, file)\n        elif zipfile.is_zipfile(path):\n            with zipfile.ZipFile(path) as zip_file:\n                for file in zip_file.namelist():\n                    if file.endswith((\".html\", \".json\")):\n                        with tempfile.TemporaryDirectory() as temp_dir:\n                            yield zip_file.extract(file, path=temp_dir)\n[docs]    def lazy_load(self) -> Iterator[ChatSession]:\n        \"\"\"Lazy load the messages from the chat file and yield them\n        in as chat sessions.\n        Yields:\n            ChatSession: The loaded chat session.\n        \"\"\"\n        for file_path in self._iterate_files(self.path):\n            if file_path.endswith(\".html\"):\n                yield self._load_single_chat_session_html(file_path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/telegram.html"}
{"id": "a3a353173816-3", "text": "yield self._load_single_chat_session_html(file_path)\n            elif file_path.endswith(\".json\"):\n                yield self._load_single_chat_session_json(file_path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/telegram.html"}
{"id": "a852be63a738-0", "text": "Source code for langchain.chat_loaders.langsmith\nfrom __future__ import annotations\nimport logging\nfrom typing import TYPE_CHECKING, Dict, Iterable, Iterator, List, Optional, Union, cast\nfrom langchain.chat_loaders.base import BaseChatLoader\nfrom langchain.load import load\nfrom langchain.schema.chat import ChatSession\nif TYPE_CHECKING:\n    from langsmith.client import Client\n    from langsmith.schemas import Run\nlogger = logging.getLogger(__name__)\n[docs]class LangSmithRunChatLoader(BaseChatLoader):\n    \"\"\"\n    Load chat sessions from a list of LangSmith \"llm\" runs.\n    Attributes:\n        runs (Iterable[Union[str, Run]]): The list of LLM run IDs or run objects.\n        client (Client): Instance of LangSmith client for fetching data.\n    \"\"\"\n[docs]    def __init__(\n        self, runs: Iterable[Union[str, Run]], client: Optional[\"Client\"] = None\n    ):\n        \"\"\"\n        Initialize a new LangSmithRunChatLoader instance.\n        :param runs: List of LLM run IDs or run objects.\n        :param client: An instance of LangSmith client, if not provided,\n            a new client instance will be created.\n        \"\"\"\n        from langsmith.client import Client\n        self.runs = runs\n        self.client = client or Client()\n    def _load_single_chat_session(self, llm_run: \"Run\") -> ChatSession:\n        \"\"\"\n        Convert an individual LangSmith LLM run to a ChatSession.\n        :param llm_run: The LLM run object.\n        :return: A chat session representing the run's data.\n        \"\"\"\n        chat_session = LangSmithRunChatLoader._get_messages_from_llm_run(llm_run)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/langsmith.html"}
{"id": "a852be63a738-1", "text": "functions = LangSmithRunChatLoader._get_functions_from_llm_run(llm_run)\n        if functions:\n            chat_session[\"functions\"] = functions\n        return chat_session\n    @staticmethod\n    def _get_messages_from_llm_run(llm_run: \"Run\") -> ChatSession:\n        \"\"\"\n        Extract messages from a LangSmith LLM run.\n        :param llm_run: The LLM run object.\n        :return: ChatSession with the extracted messages.\n        \"\"\"\n        if llm_run.run_type != \"llm\":\n            raise ValueError(f\"Expected run of type llm. Got: {llm_run.run_type}\")\n        if \"messages\" not in llm_run.inputs:\n            raise ValueError(f\"Run has no 'messages' inputs. Got {llm_run.inputs}\")\n        if not llm_run.outputs:\n            raise ValueError(\"Cannot convert pending run\")\n        messages = load(llm_run.inputs)[\"messages\"]\n        message_chunk = load(llm_run.outputs)[\"generations\"][0][\"message\"]\n        return ChatSession(messages=messages + [message_chunk])\n    @staticmethod\n    def _get_functions_from_llm_run(llm_run: \"Run\") -> Optional[List[Dict]]:\n        \"\"\"\n        Extract functions from a LangSmith LLM run if they exist.\n        :param llm_run: The LLM run object.\n        :return: Functions from the run or None.\n        \"\"\"\n        if llm_run.run_type != \"llm\":\n            raise ValueError(f\"Expected run of type llm. Got: {llm_run.run_type}\")\n        return (llm_run.extra or {}).get(\"invocation_params\", {}).get(\"functions\")\n[docs]    def lazy_load(self) -> Iterator[ChatSession]:\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/langsmith.html"}
{"id": "a852be63a738-2", "text": "[docs]    def lazy_load(self) -> Iterator[ChatSession]:\n        \"\"\"\n        Lazy load the chat sessions from the iterable of run IDs.\n        This method fetches the runs and converts them to chat sessions on-the-fly,\n        yielding one session at a time.\n        :return: Iterator of chat sessions containing messages.\n        \"\"\"\n        from langsmith.schemas import Run\n        for run_obj in self.runs:\n            try:\n                if hasattr(run_obj, \"id\"):\n                    run = run_obj\n                else:\n                    run = self.client.read_run(run_obj)\n                session = self._load_single_chat_session(cast(Run, run))\n                yield session\n            except ValueError as e:\n                logger.warning(f\"Could not load run {run_obj}: {repr(e)}\")\n                continue\n[docs]class LangSmithDatasetChatLoader(BaseChatLoader):\n    \"\"\"\n    Load chat sessions from a LangSmith dataset with the \"chat\" data type.\n    Attributes:\n        dataset_name (str): The name of the LangSmith dataset.\n        client (Client): Instance of LangSmith client for fetching data.\n    \"\"\"\n[docs]    def __init__(self, *, dataset_name: str, client: Optional[\"Client\"] = None):\n        \"\"\"\n        Initialize a new LangSmithChatDatasetLoader instance.\n        :param dataset_name: The name of the LangSmith dataset.\n        :param client: An instance of LangSmith client; if not provided,\n            a new client instance will be created.\n        \"\"\"\n        try:\n            from langsmith.client import Client\n        except ImportError as e:\n            raise ImportError(\n                \"The LangSmith client is required to load LangSmith datasets.\\n\"\n                \"Please install it with `pip install langsmith`\"\n            ) from e", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/langsmith.html"}
{"id": "a852be63a738-3", "text": "\"Please install it with `pip install langsmith`\"\n            ) from e\n        self.dataset_name = dataset_name\n        self.client = client or Client()\n[docs]    def lazy_load(self) -> Iterator[ChatSession]:\n        \"\"\"\n        Lazy load the chat sessions from the specified LangSmith dataset.\n        This method fetches the chat data from the dataset and\n        converts each data point to chat sessions on-the-fly,\n        yielding one session at a time.\n        :return: Iterator of chat sessions containing messages.\n        \"\"\"\n        from langchain.adapters import openai as oai_adapter  # noqa: E402\n        data = self.client.read_dataset_openai_finetuning(\n            dataset_name=self.dataset_name\n        )\n        for data_point in data:\n            yield ChatSession(\n                messages=[\n                    oai_adapter.convert_dict_to_message(m)\n                    for m in data_point.get(\"messages\", [])\n                ],\n                functions=data_point.get(\"functions\"),\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/langsmith.html"}
{"id": "8c2b578ce10a-0", "text": "Source code for langchain.chat_loaders.facebook_messenger\nimport json\nimport logging\nfrom pathlib import Path\nfrom typing import Iterator, Union\nfrom langchain.chat_loaders.base import BaseChatLoader\nfrom langchain.schema.chat import ChatSession\nfrom langchain.schema.messages import HumanMessage\nlogger = logging.getLogger(__file__)\n[docs]class SingleFileFacebookMessengerChatLoader(BaseChatLoader):\n    \"\"\"Load `Facebook Messenger` chat data from a single file.\n    Args:\n        path (Union[Path, str]): The path to the chat file.\n    Attributes:\n        path (Path): The path to the chat file.\n    \"\"\"\n[docs]    def __init__(self, path: Union[Path, str]) -> None:\n        super().__init__()\n        self.file_path = path if isinstance(path, Path) else Path(path)\n[docs]    def lazy_load(self) -> Iterator[ChatSession]:\n        \"\"\"Lazy loads the chat data from the file.\n        Yields:\n            ChatSession: A chat session containing the loaded messages.\n        \"\"\"\n        with open(self.file_path) as f:\n            data = json.load(f)\n        sorted_data = sorted(data[\"messages\"], key=lambda x: x[\"timestamp_ms\"])\n        messages = []\n        for m in sorted_data:\n            messages.append(\n                HumanMessage(\n                    content=m[\"content\"], additional_kwargs={\"sender\": m[\"sender_name\"]}\n                )\n            )\n        yield ChatSession(messages=messages)\n[docs]class FolderFacebookMessengerChatLoader(BaseChatLoader):\n    \"\"\"Load `Facebook Messenger` chat data from a folder.\n    Args:\n        path (Union[str, Path]): The path to the directory\n            containing the chat files.\n    Attributes:\n        path (Path): The path to the directory containing the chat files.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/facebook_messenger.html"}
{"id": "8c2b578ce10a-1", "text": "Attributes:\n        path (Path): The path to the directory containing the chat files.\n    \"\"\"\n[docs]    def __init__(self, path: Union[str, Path]) -> None:\n        super().__init__()\n        self.directory_path = Path(path) if isinstance(path, str) else path\n[docs]    def lazy_load(self) -> Iterator[ChatSession]:\n        \"\"\"Lazy loads the chat data from the folder.\n        Yields:\n            ChatSession: A chat session containing the loaded messages.\n        \"\"\"\n        inbox_path = self.directory_path / \"inbox\"\n        for _dir in inbox_path.iterdir():\n            if _dir.is_dir():\n                for _file in _dir.iterdir():\n                    if _file.suffix.lower() == \".json\":\n                        file_loader = SingleFileFacebookMessengerChatLoader(path=_file)\n                        for result in file_loader.lazy_load():\n                            yield result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/facebook_messenger.html"}
{"id": "62ef9e7e024b-0", "text": "Source code for langchain.schema.chat\nfrom typing import Sequence, TypedDict\nfrom langchain.schema import BaseMessage\n[docs]class ChatSession(TypedDict, total=False):\n    \"\"\"Chat Session represents a single\n    conversation, channel, or other group of messages.\"\"\"\n    messages: Sequence[BaseMessage]\n    \"\"\"The LangChain chat messages loaded from the source.\"\"\"\n    functions: Sequence[dict]\n    \"\"\"The function calling specs for the messages.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/chat.html"}
{"id": "0e2b255b4cc9-0", "text": "Source code for langchain.schema.agent\nfrom __future__ import annotations\nfrom typing import Any, Literal, Sequence, Union\nfrom langchain.load.serializable import Serializable\nfrom langchain.schema.messages import BaseMessage\n[docs]class AgentAction(Serializable):\n    \"\"\"A full description of an action for an ActionAgent to execute.\"\"\"\n    tool: str\n    \"\"\"The name of the Tool to execute.\"\"\"\n    tool_input: Union[str, dict]\n    \"\"\"The input to pass in to the Tool.\"\"\"\n    log: str\n    \"\"\"Additional information to log about the action.\n    This log can be used in a few ways. First, it can be used to audit\n    what exactly the LLM predicted to lead to this (tool, tool_input).\n    Second, it can be used in future iterations to show the LLMs prior\n    thoughts. This is useful when (tool, tool_input) does not contain\n    full information about the LLM prediction (for example, any `thought`\n    before the tool/tool_input).\"\"\"\n    type: Literal[\"AgentAction\"] = \"AgentAction\"\n    def __init__(\n        self, tool: str, tool_input: Union[str, dict], log: str, **kwargs: Any\n    ):\n        \"\"\"Override init to support instantiation by position for backward compat.\"\"\"\n        super().__init__(tool=tool, tool_input=tool_input, log=log, **kwargs)\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether or not the class is serializable.\"\"\"\n        return True\n[docs]class AgentActionMessageLog(AgentAction):\n    message_log: Sequence[BaseMessage]\n    \"\"\"Similar to log, this can be used to pass along extra\n    information about what exact messages were predicted by the LLM", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/agent.html"}
{"id": "0e2b255b4cc9-1", "text": "information about what exact messages were predicted by the LLM\n    before parsing out the (tool, tool_input). This is again useful\n    if (tool, tool_input) cannot be used to fully recreate the LLM\n    prediction, and you need that LLM prediction (for future agent iteration).\n    Compared to `log`, this is useful when the underlying LLM is a\n    ChatModel (and therefore returns messages rather than a string).\"\"\"\n    # Ignoring type because we're overriding the type from AgentAction.\n    # And this is the correct thing to do in this case.\n    # The type literal is used for serialization purposes.\n    type: Literal[\"AgentActionMessageLog\"] = \"AgentActionMessageLog\"  # type: ignore\n[docs]class AgentFinish(Serializable):\n    \"\"\"The final return value of an ActionAgent.\"\"\"\n    return_values: dict\n    \"\"\"Dictionary of return values.\"\"\"\n    log: str\n    \"\"\"Additional information to log about the return value.\n    This is used to pass along the full LLM prediction, not just the parsed out\n    return value. For example, if the full LLM prediction was\n    `Final Answer: 2` you may want to just return `2` as a return value, but pass\n    along the full string as a `log` (for debugging or observability purposes).\n    \"\"\"\n    type: Literal[\"AgentFinish\"] = \"AgentFinish\"\n    def __init__(self, return_values: dict, log: str, **kwargs: Any):\n        \"\"\"Override init to support instantiation by position for backward compat.\"\"\"\n        super().__init__(return_values=return_values, log=log, **kwargs)\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether or not the class is serializable.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/agent.html"}
{"id": "0e2b255b4cc9-2", "text": "\"\"\"Return whether or not the class is serializable.\"\"\"\n        return True", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/agent.html"}
{"id": "4584d22dff93-0", "text": "Source code for langchain.schema.document\nfrom __future__ import annotations\nimport asyncio\nfrom abc import ABC, abstractmethod\nfrom functools import partial\nfrom typing import Any, Literal, Sequence\nfrom langchain.load.serializable import Serializable\nfrom langchain.pydantic_v1 import Field\n[docs]class Document(Serializable):\n    \"\"\"Class for storing a piece of text and associated metadata.\"\"\"\n    page_content: str\n    \"\"\"String text.\"\"\"\n    metadata: dict = Field(default_factory=dict)\n    \"\"\"Arbitrary metadata about the page content (e.g., source, relationships to other\n        documents, etc.).\n    \"\"\"\n    type: Literal[\"Document\"] = \"Document\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this class is serializable.\"\"\"\n        return True\n[docs]class BaseDocumentTransformer(ABC):\n    \"\"\"Abstract base class for document transformation systems.\n    A document transformation system takes a sequence of Documents and returns a\n    sequence of transformed Documents.\n    Example:\n        .. code-block:: python\n            class EmbeddingsRedundantFilter(BaseDocumentTransformer, BaseModel):\n                embeddings: Embeddings\n                similarity_fn: Callable = cosine_similarity\n                similarity_threshold: float = 0.95\n                class Config:\n                    arbitrary_types_allowed = True\n                def transform_documents(\n                    self, documents: Sequence[Document], **kwargs: Any\n                ) -> Sequence[Document]:\n                    stateful_documents = get_stateful_documents(documents)\n                    embedded_documents = _get_embeddings_from_stateful_docs(\n                        self.embeddings, stateful_documents\n                    )\n                    included_idxs = _filter_similar_embeddings(\n                        embedded_documents, self.similarity_fn, self.similarity_threshold\n                    )\n                    return [stateful_documents[i] for i in sorted(included_idxs)]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/document.html"}
{"id": "4584d22dff93-1", "text": ")\n                    return [stateful_documents[i] for i in sorted(included_idxs)]\n                async def atransform_documents(\n                    self, documents: Sequence[Document], **kwargs: Any\n                ) -> Sequence[Document]:\n                    raise NotImplementedError\n    \"\"\"  # noqa: E501\n[docs]    @abstractmethod\n    def transform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        \"\"\"Transform a list of documents.\n        Args:\n            documents: A sequence of Documents to be transformed.\n        Returns:\n            A list of transformed Documents.\n        \"\"\"\n[docs]    async def atransform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        \"\"\"Asynchronously transform a list of documents.\n        Args:\n            documents: A sequence of Documents to be transformed.\n        Returns:\n            A list of transformed Documents.\n        \"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, partial(self.transform_documents, **kwargs), documents\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/document.html"}
{"id": "4e647ed1cf51-0", "text": "Source code for langchain.schema.cache\nfrom __future__ import annotations\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Optional, Sequence\nfrom langchain.schema.output import Generation\nRETURN_VAL_TYPE = Sequence[Generation]\n[docs]class BaseCache(ABC):\n    \"\"\"Base interface for cache.\"\"\"\n[docs]    @abstractmethod\n    def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:\n        \"\"\"Look up based on prompt and llm_string.\"\"\"\n[docs]    @abstractmethod\n    def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:\n        \"\"\"Update cache based on prompt and llm_string.\"\"\"\n[docs]    @abstractmethod\n    def clear(self, **kwargs: Any) -> None:\n        \"\"\"Clear cache that can take additional keyword arguments.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/cache.html"}
{"id": "61ec9d2f588e-0", "text": "Source code for langchain.schema.prompt_template\nfrom __future__ import annotations\nimport json\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import Any, Callable, Dict, List, Mapping, Optional, Type, Union\nimport yaml\nfrom langchain.pydantic_v1 import BaseModel, Field, create_model, root_validator\nfrom langchain.schema.document import Document\nfrom langchain.schema.output_parser import BaseOutputParser\nfrom langchain.schema.prompt import PromptValue\nfrom langchain.schema.runnable import RunnableConfig, RunnableSerializable\n[docs]class BasePromptTemplate(RunnableSerializable[Dict, PromptValue], ABC):\n    \"\"\"Base class for all prompt templates, returning a prompt.\"\"\"\n    input_variables: List[str]\n    \"\"\"A list of the names of the variables the prompt template expects.\"\"\"\n    input_types: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"A dictionary of the types of the variables the prompt template expects.\n    If not provided, all variables are assumed to be strings.\"\"\"\n    output_parser: Optional[BaseOutputParser] = None\n    \"\"\"How to parse the output of calling an LLM on this formatted prompt.\"\"\"\n    partial_variables: Mapping[str, Union[str, Callable[[], str]]] = Field(\n        default_factory=dict\n    )\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this class is serializable.\"\"\"\n        return True\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @property\n    def OutputType(self) -> Any:\n        from langchain.prompts.base import StringPromptValue\n        from langchain.prompts.chat import ChatPromptValueConcrete\n        return Union[StringPromptValue, ChatPromptValueConcrete]\n[docs]    def get_input_schema(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html"}
{"id": "61ec9d2f588e-1", "text": "[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        # This is correct, but pydantic typings/mypy don't think so.\n        return create_model(  # type: ignore[call-overload]\n            \"PromptInput\",\n            **{k: (self.input_types.get(k, str), None) for k in self.input_variables},\n        )\n[docs]    def invoke(\n        self, input: Dict, config: Optional[RunnableConfig] = None\n    ) -> PromptValue:\n        return self._call_with_config(\n            lambda inner_input: self.format_prompt(\n                **{key: inner_input[key] for key in self.input_variables}\n            ),\n            input,\n            config,\n            run_type=\"prompt\",\n        )\n[docs]    @abstractmethod\n    def format_prompt(self, **kwargs: Any) -> PromptValue:\n        \"\"\"Create Chat Messages.\"\"\"\n    @root_validator()\n    def validate_variable_names(cls, values: Dict) -> Dict:\n        \"\"\"Validate variable names do not include restricted names.\"\"\"\n        if \"stop\" in values[\"input_variables\"]:\n            raise ValueError(\n                \"Cannot have an input variable named 'stop', as it is used internally,\"\n                \" please rename.\"\n            )\n        if \"stop\" in values[\"partial_variables\"]:\n            raise ValueError(\n                \"Cannot have an partial variable named 'stop', as it is used \"\n                \"internally, please rename.\"\n            )\n        overall = set(values[\"input_variables\"]).intersection(\n            values[\"partial_variables\"]\n        )\n        if overall:\n            raise ValueError(\n                f\"Found overlapping input and partial variables: {overall}\"\n            )\n        return values", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html"}
{"id": "61ec9d2f588e-2", "text": ")\n        return values\n[docs]    def partial(self, **kwargs: Union[str, Callable[[], str]]) -> BasePromptTemplate:\n        \"\"\"Return a partial of the prompt template.\"\"\"\n        prompt_dict = self.__dict__.copy()\n        prompt_dict[\"input_variables\"] = list(\n            set(self.input_variables).difference(kwargs)\n        )\n        prompt_dict[\"partial_variables\"] = {**self.partial_variables, **kwargs}\n        return type(self)(**prompt_dict)\n    def _merge_partial_and_user_variables(self, **kwargs: Any) -> Dict[str, Any]:\n        # Get partial params:\n        partial_kwargs = {\n            k: v if isinstance(v, str) else v()\n            for k, v in self.partial_variables.items()\n        }\n        return {**partial_kwargs, **kwargs}\n[docs]    @abstractmethod\n    def format(self, **kwargs: Any) -> str:\n        \"\"\"Format the prompt with the inputs.\n        Args:\n            kwargs: Any arguments to be passed to the prompt template.\n        Returns:\n            A formatted string.\n        Example:\n        .. code-block:: python\n            prompt.format(variable1=\"foo\")\n        \"\"\"\n    @property\n    def _prompt_type(self) -> str:\n        \"\"\"Return the prompt type key.\"\"\"\n        raise NotImplementedError\n[docs]    def dict(self, **kwargs: Any) -> Dict:\n        \"\"\"Return dictionary representation of prompt.\"\"\"\n        prompt_dict = super().dict(**kwargs)\n        try:\n            prompt_dict[\"_type\"] = self._prompt_type\n        except NotImplementedError:\n            pass\n        return prompt_dict\n[docs]    def save(self, file_path: Union[Path, str]) -> None:\n        \"\"\"Save the prompt.\n        Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html"}
{"id": "61ec9d2f588e-3", "text": "\"\"\"Save the prompt.\n        Args:\n            file_path: Path to directory to save prompt to.\n        Example:\n        .. code-block:: python\n            prompt.save(file_path=\"path/prompt.yaml\")\n        \"\"\"\n        if self.partial_variables:\n            raise ValueError(\"Cannot save prompt with partial variables.\")\n        # Fetch dictionary to save\n        prompt_dict = self.dict()\n        if \"_type\" not in prompt_dict:\n            raise NotImplementedError(f\"Prompt {self} does not support saving.\")\n        # Convert file to Path object.\n        if isinstance(file_path, str):\n            save_path = Path(file_path)\n        else:\n            save_path = file_path\n        directory_path = save_path.parent\n        directory_path.mkdir(parents=True, exist_ok=True)\n        if save_path.suffix == \".json\":\n            with open(file_path, \"w\") as f:\n                json.dump(prompt_dict, f, indent=4)\n        elif save_path.suffix == \".yaml\":\n            with open(file_path, \"w\") as f:\n                yaml.dump(prompt_dict, f, default_flow_style=False)\n        else:\n            raise ValueError(f\"{save_path} must be json or yaml\")\n[docs]def format_document(doc: Document, prompt: BasePromptTemplate) -> str:\n    \"\"\"Format a document into a string based on a prompt template.\n    First, this pulls information from the document from two sources:\n    1. `page_content`:\n        This takes the information from the `document.page_content`\n        and assigns it to a variable named `page_content`.\n    2. metadata:\n        This takes information from `document.metadata` and assigns\n        it to variables of the same name.\n    Those variables are then passed into the `prompt` to produce a formatted string.\n    Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html"}
{"id": "61ec9d2f588e-4", "text": "Args:\n        doc: Document, the page_content and metadata will be used to create\n            the final string.\n        prompt: BasePromptTemplate, will be used to format the page_content\n            and metadata into the final string.\n    Returns:\n        string of the document formatted.\n    Example:\n        .. code-block:: python\n            from langchain.schema import Document\n            from langchain.prompts import PromptTemplate\n            doc = Document(page_content=\"This is a joke\", metadata={\"page\": \"1\"})\n            prompt = PromptTemplate.from_template(\"Page {page}: {page_content}\")\n            format_document(doc, prompt)\n            >>> \"Page 1: This is a joke\"\n    \"\"\"\n    base_info = {\"page_content\": doc.page_content, **doc.metadata}\n    missing_metadata = set(prompt.input_variables).difference(base_info)\n    if len(missing_metadata) > 0:\n        required_metadata = [\n            iv for iv in prompt.input_variables if iv != \"page_content\"\n        ]\n        raise ValueError(\n            f\"Document prompt requires documents to have metadata variables: \"\n            f\"{required_metadata}. Received document with missing metadata: \"\n            f\"{list(missing_metadata)}.\"\n        )\n    document_info = {k: base_info[k] for k in prompt.input_variables}\n    return prompt.format(**document_info)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html"}
{"id": "7e5261611c0b-0", "text": "Source code for langchain.schema.exceptions\n[docs]class LangChainException(Exception):\n    \"\"\"General LangChain exception.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/exceptions.html"}
{"id": "d0c3c407787e-0", "text": "Source code for langchain.schema.retriever\nfrom __future__ import annotations\nimport asyncio\nimport warnings\nfrom abc import ABC, abstractmethod\nfrom functools import partial\nfrom inspect import signature\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional\nfrom langchain.load.dump import dumpd\nfrom langchain.schema.document import Document\nfrom langchain.schema.runnable import RunnableConfig, RunnableSerializable\nif TYPE_CHECKING:\n    from langchain.callbacks.manager import (\n        AsyncCallbackManagerForRetrieverRun,\n        CallbackManagerForRetrieverRun,\n        Callbacks,\n    )\n[docs]class BaseRetriever(RunnableSerializable[str, List[Document]], ABC):\n    \"\"\"Abstract base class for a Document retrieval system.\n    A retrieval system is defined as something that can take string queries and return\n        the most 'relevant' Documents from some source.\n    Example:\n        .. code-block:: python\n            class TFIDFRetriever(BaseRetriever, BaseModel):\n                vectorizer: Any\n                docs: List[Document]\n                tfidf_array: Any\n                k: int = 4\n                class Config:\n                    arbitrary_types_allowed = True\n                def get_relevant_documents(self, query: str) -> List[Document]:\n                    from sklearn.metrics.pairwise import cosine_similarity\n                    # Ip -- (n_docs,x), Op -- (n_docs,n_Feats)\n                    query_vec = self.vectorizer.transform([query])\n                    # Op -- (n_docs,1) -- Cosine Sim with each doc\n                    results = cosine_similarity(self.tfidf_array, query_vec).reshape((-1,))\n                    return [self.docs[i] for i in results.argsort()[-self.k :][::-1]]\n    \"\"\"  # noqa: E501\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html"}
{"id": "d0c3c407787e-1", "text": "class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    _new_arg_supported: bool = False\n    _expects_other_args: bool = False\n    tags: Optional[List[str]] = None\n    \"\"\"Optional list of tags associated with the retriever. Defaults to None\n    These tags will be associated with each call to this retriever,\n    and passed as arguments to the handlers defined in `callbacks`.\n    You can use these to eg identify a specific instance of a retriever with its \n    use case.\n    \"\"\"\n    metadata: Optional[Dict[str, Any]] = None\n    \"\"\"Optional metadata associated with the retriever. Defaults to None\n    This metadata will be associated with each call to this retriever,\n    and passed as arguments to the handlers defined in `callbacks`.\n    You can use these to eg identify a specific instance of a retriever with its \n    use case.\n    \"\"\"\n    def __init_subclass__(cls, **kwargs: Any) -> None:\n        super().__init_subclass__(**kwargs)\n        # Version upgrade for old retrievers that implemented the public\n        # methods directly.\n        if cls.get_relevant_documents != BaseRetriever.get_relevant_documents:\n            warnings.warn(\n                \"Retrievers must implement abstract `_get_relevant_documents` method\"\n                \" instead of `get_relevant_documents`\",\n                DeprecationWarning,\n            )\n            swap = cls.get_relevant_documents\n            cls.get_relevant_documents = (  # type: ignore[assignment]\n                BaseRetriever.get_relevant_documents\n            )\n            cls._get_relevant_documents = swap  # type: ignore[assignment]\n        if (\n            hasattr(cls, \"aget_relevant_documents\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html"}
{"id": "d0c3c407787e-2", "text": "if (\n            hasattr(cls, \"aget_relevant_documents\")\n            and cls.aget_relevant_documents != BaseRetriever.aget_relevant_documents\n        ):\n            warnings.warn(\n                \"Retrievers must implement abstract `_aget_relevant_documents` method\"\n                \" instead of `aget_relevant_documents`\",\n                DeprecationWarning,\n            )\n            aswap = cls.aget_relevant_documents\n            cls.aget_relevant_documents = (  # type: ignore[assignment]\n                BaseRetriever.aget_relevant_documents\n            )\n            cls._aget_relevant_documents = aswap  # type: ignore[assignment]\n        parameters = signature(cls._get_relevant_documents).parameters\n        cls._new_arg_supported = parameters.get(\"run_manager\") is not None\n        # If a V1 retriever broke the interface and expects additional arguments\n        cls._expects_other_args = (\n            len(set(parameters.keys()) - {\"self\", \"query\", \"run_manager\"}) > 0\n        )\n[docs]    def invoke(\n        self, input: str, config: Optional[RunnableConfig] = None\n    ) -> List[Document]:\n        config = config or {}\n        return self.get_relevant_documents(\n            input,\n            callbacks=config.get(\"callbacks\"),\n            tags=config.get(\"tags\"),\n            metadata=config.get(\"metadata\"),\n            run_name=config.get(\"run_name\"),\n        )\n[docs]    async def ainvoke(\n        self,\n        input: str,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> List[Document]:\n        config = config or {}\n        return await self.aget_relevant_documents(\n            input,\n            callbacks=config.get(\"callbacks\"),\n            tags=config.get(\"tags\"),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html"}
{"id": "d0c3c407787e-3", "text": "input,\n            callbacks=config.get(\"callbacks\"),\n            tags=config.get(\"tags\"),\n            metadata=config.get(\"metadata\"),\n            run_name=config.get(\"run_name\"),\n        )\n    @abstractmethod\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"Get documents relevant to a query.\n        Args:\n            query: String to find relevant documents for\n            run_manager: The callbacks handler to use\n        Returns:\n            List of relevant documents\n        \"\"\"\n    async def _aget_relevant_documents(\n        self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        \"\"\"Asynchronously get documents relevant to a query.\n        Args:\n            query: String to find relevant documents for\n            run_manager: The callbacks handler to use\n        Returns:\n            List of relevant documents\n        \"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, partial(self._get_relevant_documents, run_manager=run_manager), query\n        )\n[docs]    def get_relevant_documents(\n        self,\n        query: str,\n        *,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        run_name: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Retrieve documents relevant to a query.\n        Args:\n            query: string to find relevant documents for\n            callbacks: Callback manager or list of callbacks\n            tags: Optional list of tags associated with the retriever. Defaults to None\n                These tags will be associated with each call to this retriever,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html"}
{"id": "d0c3c407787e-4", "text": "These tags will be associated with each call to this retriever,\n                and passed as arguments to the handlers defined in `callbacks`.\n            metadata: Optional metadata associated with the retriever. Defaults to None\n                This metadata will be associated with each call to this retriever,\n                and passed as arguments to the handlers defined in `callbacks`.\n        Returns:\n            List of relevant documents\n        \"\"\"\n        from langchain.callbacks.manager import CallbackManager\n        callback_manager = CallbackManager.configure(\n            callbacks,\n            None,\n            verbose=kwargs.get(\"verbose\", False),\n            inheritable_tags=tags,\n            local_tags=self.tags,\n            inheritable_metadata=metadata,\n            local_metadata=self.metadata,\n        )\n        run_manager = callback_manager.on_retriever_start(\n            dumpd(self),\n            query,\n            name=run_name,\n            **kwargs,\n        )\n        try:\n            _kwargs = kwargs if self._expects_other_args else {}\n            if self._new_arg_supported:\n                result = self._get_relevant_documents(\n                    query, run_manager=run_manager, **_kwargs\n                )\n            else:\n                result = self._get_relevant_documents(query, **_kwargs)\n        except Exception as e:\n            run_manager.on_retriever_error(e)\n            raise e\n        else:\n            run_manager.on_retriever_end(\n                result,\n                **kwargs,\n            )\n            return result\n[docs]    async def aget_relevant_documents(\n        self,\n        query: str,\n        *,\n        callbacks: Callbacks = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        run_name: Optional[str] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html"}
{"id": "d0c3c407787e-5", "text": "run_name: Optional[str] = None,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Asynchronously get documents relevant to a query.\n        Args:\n            query: string to find relevant documents for\n            callbacks: Callback manager or list of callbacks\n            tags: Optional list of tags associated with the retriever. Defaults to None\n                These tags will be associated with each call to this retriever,\n                and passed as arguments to the handlers defined in `callbacks`.\n            metadata: Optional metadata associated with the retriever. Defaults to None\n                This metadata will be associated with each call to this retriever,\n                and passed as arguments to the handlers defined in `callbacks`.\n        Returns:\n            List of relevant documents\n        \"\"\"\n        from langchain.callbacks.manager import AsyncCallbackManager\n        callback_manager = AsyncCallbackManager.configure(\n            callbacks,\n            None,\n            verbose=kwargs.get(\"verbose\", False),\n            inheritable_tags=tags,\n            local_tags=self.tags,\n            inheritable_metadata=metadata,\n            local_metadata=self.metadata,\n        )\n        run_manager = await callback_manager.on_retriever_start(\n            dumpd(self),\n            query,\n            name=run_name,\n            **kwargs,\n        )\n        try:\n            _kwargs = kwargs if self._expects_other_args else {}\n            if self._new_arg_supported:\n                result = await self._aget_relevant_documents(\n                    query, run_manager=run_manager, **_kwargs\n                )\n            else:\n                result = await self._aget_relevant_documents(query, **_kwargs)\n        except Exception as e:\n            await run_manager.on_retriever_error(e)\n            raise e\n        else:\n            await run_manager.on_retriever_end(\n                result,\n                **kwargs,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html"}
{"id": "d0c3c407787e-6", "text": "await run_manager.on_retriever_end(\n                result,\n                **kwargs,\n            )\n            return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html"}
{"id": "2d5047ee1d6d-0", "text": "Source code for langchain.schema.prompt\nfrom __future__ import annotations\nfrom abc import ABC, abstractmethod\nfrom typing import List\nfrom langchain.load.serializable import Serializable\nfrom langchain.schema.messages import BaseMessage\n[docs]class PromptValue(Serializable, ABC):\n    \"\"\"Base abstract class for inputs to any language model.\n    PromptValues can be converted to both LLM (pure text-generation) inputs and\n        ChatModel inputs.\n    \"\"\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this class is serializable.\"\"\"\n        return True\n[docs]    @abstractmethod\n    def to_string(self) -> str:\n        \"\"\"Return prompt value as string.\"\"\"\n[docs]    @abstractmethod\n    def to_messages(self) -> List[BaseMessage]:\n        \"\"\"Return prompt as a list of Messages.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/prompt.html"}
{"id": "b618006e1d91-0", "text": "Source code for langchain.schema.chat_history\nfrom __future__ import annotations\nfrom abc import ABC, abstractmethod\nfrom typing import List\nfrom langchain.schema.messages import AIMessage, BaseMessage, HumanMessage\n[docs]class BaseChatMessageHistory(ABC):\n    \"\"\"Abstract base class for storing chat message history.\n    See `ChatMessageHistory` for default implementation.\n    Example:\n        .. code-block:: python\n            class FileChatMessageHistory(BaseChatMessageHistory):\n                storage_path:  str\n                session_id: str\n               @property\n               def messages(self):\n                   with open(os.path.join(storage_path, session_id), 'r:utf-8') as f:\n                       messages = json.loads(f.read())\n                    return messages_from_dict(messages)\n               def add_message(self, message: BaseMessage) -> None:\n                   messages = self.messages.append(_message_to_dict(message))\n                   with open(os.path.join(storage_path, session_id), 'w') as f:\n                       json.dump(f, messages)\n               def clear(self):\n                   with open(os.path.join(storage_path, session_id), 'w') as f:\n                       f.write(\"[]\")\n    \"\"\"\n    messages: List[BaseMessage]\n    \"\"\"A list of Messages stored in-memory.\"\"\"\n[docs]    def add_user_message(self, message: str) -> None:\n        \"\"\"Convenience method for adding a human message string to the store.\n        Args:\n            message: The string contents of a human message.\n        \"\"\"\n        self.add_message(HumanMessage(content=message))\n[docs]    def add_ai_message(self, message: str) -> None:\n        \"\"\"Convenience method for adding an AI message string to the store.\n        Args:\n            message: The string contents of an AI message.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/chat_history.html"}
{"id": "b618006e1d91-1", "text": "Args:\n            message: The string contents of an AI message.\n        \"\"\"\n        self.add_message(AIMessage(content=message))\n[docs]    @abstractmethod\n    def add_message(self, message: BaseMessage) -> None:\n        \"\"\"Add a Message object to the store.\n        Args:\n            message: A BaseMessage object to store.\n        \"\"\"\n        raise NotImplementedError()\n[docs]    @abstractmethod\n    def clear(self) -> None:\n        \"\"\"Remove all messages from the store\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/chat_history.html"}
{"id": "9cc02dfe64d1-0", "text": "Source code for langchain.schema.vectorstore\nfrom __future__ import annotations\nimport asyncio\nimport logging\nimport math\nimport warnings\nfrom abc import ABC, abstractmethod\nfrom functools import partial\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    ClassVar,\n    Collection,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Type,\n    TypeVar,\n)\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema import BaseRetriever\nfrom langchain.schema.document import Document\nfrom langchain.schema.embeddings import Embeddings\nif TYPE_CHECKING:\n    from langchain.callbacks.manager import (\n        AsyncCallbackManagerForRetrieverRun,\n        CallbackManagerForRetrieverRun,\n    )\nlogger = logging.getLogger(__name__)\nVST = TypeVar(\"VST\", bound=\"VectorStore\")\n[docs]class VectorStore(ABC):\n    \"\"\"Interface for vector store.\"\"\"\n[docs]    @abstractmethod\n    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\n        Args:\n            texts: Iterable of strings to add to the vectorstore.\n            metadatas: Optional list of metadatas associated with the texts.\n            kwargs: vectorstore specific parameters\n        Returns:\n            List of ids from adding the texts into the vectorstore.\n        \"\"\"\n    @property\n    def embeddings(self) -> Optional[Embeddings]:\n        \"\"\"Access the query embedding object if available.\"\"\"\n        logger.debug(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-1", "text": "\"\"\"Access the query embedding object if available.\"\"\"\n        logger.debug(\n            f\"{Embeddings.__name__} is not implemented for {self.__class__.__name__}\"\n        )\n        return None\n[docs]    def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:\n        \"\"\"Delete by vector ID or other criteria.\n        Args:\n            ids: List of ids to delete.\n            **kwargs: Other keyword arguments that subclasses might use.\n        Returns:\n            Optional[bool]: True if deletion is successful,\n            False otherwise, None if not implemented.\n        \"\"\"\n        raise NotImplementedError(\"delete method must be implemented by subclass.\")\n[docs]    async def adelete(\n        self, ids: Optional[List[str]] = None, **kwargs: Any\n    ) -> Optional[bool]:\n        \"\"\"Delete by vector ID or other criteria.\n        Args:\n            ids: List of ids to delete.\n            **kwargs: Other keyword arguments that subclasses might use.\n        Returns:\n            Optional[bool]: True if deletion is successful,\n            False otherwise, None if not implemented.\n        \"\"\"\n        raise NotImplementedError(\"delete method must be implemented by subclass.\")\n[docs]    async def aadd_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> List[str]:\n        \"\"\"Run more texts through the embeddings and add to the vectorstore.\"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, partial(self.add_texts, **kwargs), texts, metadatas\n        )\n[docs]    def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-2", "text": "\"\"\"Run more documents through the embeddings and add to the vectorstore.\n        Args:\n            documents (List[Document]: Documents to add to the vectorstore.\n        Returns:\n            List[str]: List of IDs of the added texts.\n        \"\"\"\n        # TODO: Handle the case where the user doesn't provide ids on the Collection\n        texts = [doc.page_content for doc in documents]\n        metadatas = [doc.metadata for doc in documents]\n        return self.add_texts(texts, metadatas, **kwargs)\n[docs]    async def aadd_documents(\n        self, documents: List[Document], **kwargs: Any\n    ) -> List[str]:\n        \"\"\"Run more documents through the embeddings and add to the vectorstore.\n        Args:\n            documents (List[Document]: Documents to add to the vectorstore.\n        Returns:\n            List[str]: List of IDs of the added texts.\n        \"\"\"\n        texts = [doc.page_content for doc in documents]\n        metadatas = [doc.metadata for doc in documents]\n        return await self.aadd_texts(texts, metadatas, **kwargs)\n[docs]    def search(self, query: str, search_type: str, **kwargs: Any) -> List[Document]:\n        \"\"\"Return docs most similar to query using specified search type.\"\"\"\n        if search_type == \"similarity\":\n            return self.similarity_search(query, **kwargs)\n        elif search_type == \"mmr\":\n            return self.max_marginal_relevance_search(query, **kwargs)\n        else:\n            raise ValueError(\n                f\"search_type of {search_type} not allowed. Expected \"\n                \"search_type to be 'similarity' or 'mmr'.\"\n            )\n[docs]    async def asearch(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-3", "text": ")\n[docs]    async def asearch(\n        self, query: str, search_type: str, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query using specified search type.\"\"\"\n        if search_type == \"similarity\":\n            return await self.asimilarity_search(query, **kwargs)\n        elif search_type == \"mmr\":\n            return await self.amax_marginal_relevance_search(query, **kwargs)\n        else:\n            raise ValueError(\n                f\"search_type of {search_type} not allowed. Expected \"\n                \"search_type to be 'similarity' or 'mmr'.\"\n            )\n[docs]    @abstractmethod\n    def similarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\"\"\"\n    @staticmethod\n    def _euclidean_relevance_score_fn(distance: float) -> float:\n        \"\"\"Return a similarity score on a scale [0, 1].\"\"\"\n        # The 'correct' relevance function\n        # may differ depending on a few things, including:\n        # - the distance / similarity metric used by the VectorStore\n        # - the scale of your embeddings (OpenAI's are unit normed. Many\n        #  others are not!)\n        # - embedding dimensionality\n        # - etc.\n        # This function converts the euclidean norm of normalized embeddings\n        # (0 is most similar, sqrt(2) most dissimilar)\n        # to a similarity function (0 to 1)\n        return 1.0 - distance / math.sqrt(2)\n    @staticmethod\n    def _cosine_relevance_score_fn(distance: float) -> float:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-4", "text": "def _cosine_relevance_score_fn(distance: float) -> float:\n        \"\"\"Normalize the distance to a score on a scale [0, 1].\"\"\"\n        return 1.0 - distance\n    @staticmethod\n    def _max_inner_product_relevance_score_fn(distance: float) -> float:\n        \"\"\"Normalize the distance to a score on a scale [0, 1].\"\"\"\n        if distance > 0:\n            return 1.0 - distance\n        return -1.0 * distance\n    def _select_relevance_score_fn(self) -> Callable[[float], float]:\n        \"\"\"\n        The 'correct' relevance function\n        may differ depending on a few things, including:\n        - the distance / similarity metric used by the VectorStore\n        - the scale of your embeddings (OpenAI's are unit normed. Many others are not!)\n        - embedding dimensionality\n        - etc.\n        Vectorstores should define their own selection based method of relevance.\n        \"\"\"\n        raise NotImplementedError\n[docs]    def similarity_search_with_score(\n        self, *args: Any, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Run similarity search with distance.\"\"\"\n        raise NotImplementedError\n[docs]    async def asimilarity_search_with_score(\n        self, *args: Any, **kwargs: Any\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Run similarity search with distance asynchronously.\"\"\"\n        # This is a temporary workaround to make the similarity search\n        # asynchronous. The proper solution is to make the similarity search\n        # asynchronous in the vector store implementations.\n        func = partial(self.similarity_search_with_score, *args, **kwargs)\n        return await asyncio.get_event_loop().run_in_executor(None, func)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-5", "text": "return await asyncio.get_event_loop().run_in_executor(None, func)\n    def _similarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Default similarity search with relevance scores. Modify if necessary\n        in subclass.\n        Return docs and relevance scores in the range [0, 1].\n        0 is dissimilar, 1 is most similar.\n        Args:\n            query: input text\n            k: Number of Documents to return. Defaults to 4.\n            **kwargs: kwargs to be passed to similarity search. Should include:\n                score_threshold: Optional, a floating point value between 0 to 1 to\n                    filter the resulting set of retrieved docs\n        Returns:\n            List of Tuples of (doc, similarity_score)\n        \"\"\"\n        relevance_score_fn = self._select_relevance_score_fn()\n        docs_and_scores = self.similarity_search_with_score(query, k, **kwargs)\n        return [(doc, relevance_score_fn(score)) for doc, score in docs_and_scores]\n    async def _asimilarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"\n        Default async similarity search with relevance scores. Modify if necessary\n        in subclass.\n        Return docs and relevance scores in the range [0, 1].\n        0 is dissimilar, 1 is most similar.\n        Args:\n            query: input text\n            k: Number of Documents to return. Defaults to 4.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-6", "text": "k: Number of Documents to return. Defaults to 4.\n            **kwargs: kwargs to be passed to similarity search. Should include:\n                score_threshold: Optional, a floating point value between 0 to 1 to\n                    filter the resulting set of retrieved docs\n        Returns:\n            List of Tuples of (doc, similarity_score)\n        \"\"\"\n        relevance_score_fn = self._select_relevance_score_fn()\n        docs_and_scores = await self.asimilarity_search_with_score(query, k, **kwargs)\n        return [(doc, relevance_score_fn(score)) for doc, score in docs_and_scores]\n[docs]    def similarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs and relevance scores in the range [0, 1].\n        0 is dissimilar, 1 is most similar.\n        Args:\n            query: input text\n            k: Number of Documents to return. Defaults to 4.\n            **kwargs: kwargs to be passed to similarity search. Should include:\n                score_threshold: Optional, a floating point value between 0 to 1 to\n                    filter the resulting set of retrieved docs\n        Returns:\n            List of Tuples of (doc, similarity_score)\n        \"\"\"\n        score_threshold = kwargs.pop(\"score_threshold\", None)\n        docs_and_similarities = self._similarity_search_with_relevance_scores(\n            query, k=k, **kwargs\n        )\n        if any(\n            similarity < 0.0 or similarity > 1.0\n            for _, similarity in docs_and_similarities\n        ):\n            warnings.warn(\n                \"Relevance scores must be between\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-7", "text": "):\n            warnings.warn(\n                \"Relevance scores must be between\"\n                f\" 0 and 1, got {docs_and_similarities}\"\n            )\n        if score_threshold is not None:\n            docs_and_similarities = [\n                (doc, similarity)\n                for doc, similarity in docs_and_similarities\n                if similarity >= score_threshold\n            ]\n            if len(docs_and_similarities) == 0:\n                warnings.warn(\n                    \"No relevant docs were retrieved using the relevance score\"\n                    f\" threshold {score_threshold}\"\n                )\n        return docs_and_similarities\n[docs]    async def asimilarity_search_with_relevance_scores(\n        self,\n        query: str,\n        k: int = 4,\n        **kwargs: Any,\n    ) -> List[Tuple[Document, float]]:\n        \"\"\"Return docs and relevance scores in the range [0, 1], asynchronously.\n        0 is dissimilar, 1 is most similar.\n        Args:\n            query: input text\n            k: Number of Documents to return. Defaults to 4.\n            **kwargs: kwargs to be passed to similarity search. Should include:\n                score_threshold: Optional, a floating point value between 0 to 1 to\n                    filter the resulting set of retrieved docs\n        Returns:\n            List of Tuples of (doc, similarity_score)\n        \"\"\"\n        score_threshold = kwargs.pop(\"score_threshold\", None)\n        docs_and_similarities = await self._asimilarity_search_with_relevance_scores(\n            query, k=k, **kwargs\n        )\n        if any(\n            similarity < 0.0 or similarity > 1.0\n            for _, similarity in docs_and_similarities\n        ):\n            warnings.warn(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-8", "text": "for _, similarity in docs_and_similarities\n        ):\n            warnings.warn(\n                \"Relevance scores must be between\"\n                f\" 0 and 1, got {docs_and_similarities}\"\n            )\n        if score_threshold is not None:\n            docs_and_similarities = [\n                (doc, similarity)\n                for doc, similarity in docs_and_similarities\n                if similarity >= score_threshold\n            ]\n            if len(docs_and_similarities) == 0:\n                warnings.warn(\n                    \"No relevant docs were retrieved using the relevance score\"\n                    f\" threshold {score_threshold}\"\n                )\n        return docs_and_similarities\n[docs]    async def asimilarity_search(\n        self, query: str, k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to query.\"\"\"\n        # This is a temporary workaround to make the similarity search\n        # asynchronous. The proper solution is to make the similarity search\n        # asynchronous in the vector store implementations.\n        func = partial(self.similarity_search, query, k=k, **kwargs)\n        return await asyncio.get_event_loop().run_in_executor(None, func)\n[docs]    def similarity_search_by_vector(\n        self, embedding: List[float], k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n        Returns:\n            List of Documents most similar to the query vector.\n        \"\"\"\n        raise NotImplementedError\n[docs]    async def asimilarity_search_by_vector(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-9", "text": "raise NotImplementedError\n[docs]    async def asimilarity_search_by_vector(\n        self, embedding: List[float], k: int = 4, **kwargs: Any\n    ) -> List[Document]:\n        \"\"\"Return docs most similar to embedding vector.\"\"\"\n        # This is a temporary workaround to make the similarity search\n        # asynchronous. The proper solution is to make the similarity search\n        # asynchronous in the vector store implementations.\n        func = partial(self.similarity_search_by_vector, embedding, k=k, **kwargs)\n        return await asyncio.get_event_loop().run_in_executor(None, func)\n[docs]    def max_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            query: Text to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        raise NotImplementedError\n[docs]    async def amax_marginal_relevance_search(\n        self,\n        query: str,\n        k: int = 4,\n        fetch_k: int = 20,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-10", "text": "k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\"\"\"\n        # This is a temporary workaround to make the similarity search\n        # asynchronous. The proper solution is to make the similarity search\n        # asynchronous in the vector store implementations.\n        func = partial(\n            self.max_marginal_relevance_search,\n            query,\n            k=k,\n            fetch_k=fetch_k,\n            lambda_mult=lambda_mult,\n            **kwargs,\n        )\n        return await asyncio.get_event_loop().run_in_executor(None, func)\n[docs]    def max_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\n        Maximal marginal relevance optimizes for similarity to query AND diversity\n        among selected documents.\n        Args:\n            embedding: Embedding to look up documents similar to.\n            k: Number of Documents to return. Defaults to 4.\n            fetch_k: Number of Documents to fetch to pass to MMR algorithm.\n            lambda_mult: Number between 0 and 1 that determines the degree\n                        of diversity among the results with 0 corresponding\n                        to maximum diversity and 1 to minimum diversity.\n                        Defaults to 0.5.\n        Returns:\n            List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        raise NotImplementedError", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-11", "text": "List of Documents selected by maximal marginal relevance.\n        \"\"\"\n        raise NotImplementedError\n[docs]    async def amax_marginal_relevance_search_by_vector(\n        self,\n        embedding: List[float],\n        k: int = 4,\n        fetch_k: int = 20,\n        lambda_mult: float = 0.5,\n        **kwargs: Any,\n    ) -> List[Document]:\n        \"\"\"Return docs selected using the maximal marginal relevance.\"\"\"\n        raise NotImplementedError\n[docs]    @classmethod\n    def from_documents(\n        cls: Type[VST],\n        documents: List[Document],\n        embedding: Embeddings,\n        **kwargs: Any,\n    ) -> VST:\n        \"\"\"Return VectorStore initialized from documents and embeddings.\"\"\"\n        texts = [d.page_content for d in documents]\n        metadatas = [d.metadata for d in documents]\n        return cls.from_texts(texts, embedding, metadatas=metadatas, **kwargs)\n[docs]    @classmethod\n    async def afrom_documents(\n        cls: Type[VST],\n        documents: List[Document],\n        embedding: Embeddings,\n        **kwargs: Any,\n    ) -> VST:\n        \"\"\"Return VectorStore initialized from documents and embeddings.\"\"\"\n        texts = [d.page_content for d in documents]\n        metadatas = [d.metadata for d in documents]\n        return await cls.afrom_texts(texts, embedding, metadatas=metadatas, **kwargs)\n[docs]    @classmethod\n    @abstractmethod\n    def from_texts(\n        cls: Type[VST],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-12", "text": "**kwargs: Any,\n    ) -> VST:\n        \"\"\"Return VectorStore initialized from texts and embeddings.\"\"\"\n[docs]    @classmethod\n    async def afrom_texts(\n        cls: Type[VST],\n        texts: List[str],\n        embedding: Embeddings,\n        metadatas: Optional[List[dict]] = None,\n        **kwargs: Any,\n    ) -> VST:\n        \"\"\"Return VectorStore initialized from texts and embeddings.\"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, partial(cls.from_texts, **kwargs), texts, embedding, metadatas\n        )\n    def _get_retriever_tags(self) -> List[str]:\n        \"\"\"Get tags for retriever.\"\"\"\n        tags = [self.__class__.__name__]\n        if self.embeddings:\n            tags.append(self.embeddings.__class__.__name__)\n        return tags\n[docs]    def as_retriever(self, **kwargs: Any) -> VectorStoreRetriever:\n        \"\"\"Return VectorStoreRetriever initialized from this VectorStore.\n        Args:\n            search_type (Optional[str]): Defines the type of search that\n                the Retriever should perform.\n                Can be \"similarity\" (default), \"mmr\", or\n                \"similarity_score_threshold\".\n            search_kwargs (Optional[Dict]): Keyword arguments to pass to the\n                search function. Can include things like:\n                    k: Amount of documents to return (Default: 4)\n                    score_threshold: Minimum relevance threshold\n                        for similarity_score_threshold\n                    fetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\n                    lambda_mult: Diversity of results returned by MMR;\n                        1 for minimum diversity and 0 for maximum. (Default: 0.5)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-13", "text": "filter: Filter by document metadata\n        Returns:\n            VectorStoreRetriever: Retriever class for VectorStore.\n        Examples:\n        .. code-block:: python\n            # Retrieve more documents with higher diversity\n            # Useful if your dataset has many similar documents\n            docsearch.as_retriever(\n                search_type=\"mmr\",\n                search_kwargs={'k': 6, 'lambda_mult': 0.25}\n            )\n            # Fetch more documents for the MMR algorithm to consider\n            # But only return the top 5\n            docsearch.as_retriever(\n                search_type=\"mmr\",\n                search_kwargs={'k': 5, 'fetch_k': 50}\n            )\n            # Only retrieve documents that have a relevance score\n            # Above a certain threshold\n            docsearch.as_retriever(\n                search_type=\"similarity_score_threshold\",\n                search_kwargs={'score_threshold': 0.8}\n            )\n            # Only get the single most similar document from the dataset\n            docsearch.as_retriever(search_kwargs={'k': 1})\n            # Use a filter to only retrieve documents from a specific paper\n            docsearch.as_retriever(\n                search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n            )\n        \"\"\"\n        tags = kwargs.pop(\"tags\", None) or []\n        tags.extend(self._get_retriever_tags())\n        return VectorStoreRetriever(vectorstore=self, **kwargs, tags=tags)\n[docs]class VectorStoreRetriever(BaseRetriever):\n    \"\"\"Base Retriever class for VectorStore.\"\"\"\n    vectorstore: VectorStore\n    \"\"\"VectorStore to use for retrieval.\"\"\"\n    search_type: str = \"similarity\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-14", "text": "search_type: str = \"similarity\"\n    \"\"\"Type of search to perform. Defaults to \"similarity\".\"\"\"\n    search_kwargs: dict = Field(default_factory=dict)\n    \"\"\"Keyword arguments to pass to the search function.\"\"\"\n    allowed_search_types: ClassVar[Collection[str]] = (\n        \"similarity\",\n        \"similarity_score_threshold\",\n        \"mmr\",\n    )\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @root_validator()\n    def validate_search_type(cls, values: Dict) -> Dict:\n        \"\"\"Validate search type.\"\"\"\n        search_type = values[\"search_type\"]\n        if search_type not in cls.allowed_search_types:\n            raise ValueError(\n                f\"search_type of {search_type} not allowed. Valid values are: \"\n                f\"{cls.allowed_search_types}\"\n            )\n        if search_type == \"similarity_score_threshold\":\n            score_threshold = values[\"search_kwargs\"].get(\"score_threshold\")\n            if (score_threshold is None) or (not isinstance(score_threshold, float)):\n                raise ValueError(\n                    \"`score_threshold` is not specified with a float value(0~1) \"\n                    \"in `search_kwargs`.\"\n                )\n        return values\n    def _get_relevant_documents(\n        self, query: str, *, run_manager: CallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        if self.search_type == \"similarity\":\n            docs = self.vectorstore.similarity_search(query, **self.search_kwargs)\n        elif self.search_type == \"similarity_score_threshold\":\n            docs_and_similarities = (\n                self.vectorstore.similarity_search_with_relevance_scores(\n                    query, **self.search_kwargs\n                )\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-15", "text": "query, **self.search_kwargs\n                )\n            )\n            docs = [doc for doc, _ in docs_and_similarities]\n        elif self.search_type == \"mmr\":\n            docs = self.vectorstore.max_marginal_relevance_search(\n                query, **self.search_kwargs\n            )\n        else:\n            raise ValueError(f\"search_type of {self.search_type} not allowed.\")\n        return docs\n    async def _aget_relevant_documents(\n        self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun\n    ) -> List[Document]:\n        if self.search_type == \"similarity\":\n            docs = await self.vectorstore.asimilarity_search(\n                query, **self.search_kwargs\n            )\n        elif self.search_type == \"similarity_score_threshold\":\n            docs_and_similarities = (\n                await self.vectorstore.asimilarity_search_with_relevance_scores(\n                    query, **self.search_kwargs\n                )\n            )\n            docs = [doc for doc, _ in docs_and_similarities]\n        elif self.search_type == \"mmr\":\n            docs = await self.vectorstore.amax_marginal_relevance_search(\n                query, **self.search_kwargs\n            )\n        else:\n            raise ValueError(f\"search_type of {self.search_type} not allowed.\")\n        return docs\n[docs]    def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]:\n        \"\"\"Add documents to vectorstore.\"\"\"\n        return self.vectorstore.add_documents(documents, **kwargs)\n[docs]    async def aadd_documents(\n        self, documents: List[Document], **kwargs: Any\n    ) -> List[str]:\n        \"\"\"Add documents to vectorstore.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "9cc02dfe64d1-16", "text": ") -> List[str]:\n        \"\"\"Add documents to vectorstore.\"\"\"\n        return await self.vectorstore.aadd_documents(documents, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html"}
{"id": "52bb77ea5ac5-0", "text": "Source code for langchain.schema.output_parser\nfrom __future__ import annotations\nimport asyncio\nimport functools\nfrom abc import ABC, abstractmethod\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Dict,\n    Generic,\n    Iterator,\n    List,\n    Optional,\n    Type,\n    TypeVar,\n    Union,\n)\nfrom typing_extensions import get_args\nfrom langchain.schema.messages import AnyMessage, BaseMessage, BaseMessageChunk\nfrom langchain.schema.output import (\n    ChatGeneration,\n    ChatGenerationChunk,\n    Generation,\n    GenerationChunk,\n)\nfrom langchain.schema.prompt import PromptValue\nfrom langchain.schema.runnable import RunnableConfig, RunnableSerializable\nT = TypeVar(\"T\")\n[docs]class BaseLLMOutputParser(Generic[T], ABC):\n    \"\"\"Abstract base class for parsing the outputs of a model.\"\"\"\n[docs]    @abstractmethod\n    def parse_result(self, result: List[Generation], *, partial: bool = False) -> T:\n        \"\"\"Parse a list of candidate model Generations into a specific format.\n        Args:\n            result: A list of Generations to be parsed. The Generations are assumed\n                to be different candidate outputs for a single model input.\n        Returns:\n            Structured output.\n        \"\"\"\n[docs]    async def aparse_result(\n        self, result: List[Generation], *, partial: bool = False\n    ) -> T:\n        \"\"\"Parse a list of candidate model Generations into a specific format.\n        Args:\n            result: A list of Generations to be parsed. The Generations are assumed\n                to be different candidate outputs for a single model input.\n        Returns:\n            Structured output.\n        \"\"\"\n        return await asyncio.get_running_loop().run_in_executor(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html"}
{"id": "52bb77ea5ac5-1", "text": "\"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, self.parse_result, result\n        )\n[docs]class BaseGenerationOutputParser(\n    BaseLLMOutputParser, RunnableSerializable[Union[str, BaseMessage], T]\n):\n    \"\"\"Base class to parse the output of an LLM call.\"\"\"\n    @property\n    def InputType(self) -> Any:\n        return Union[str, AnyMessage]\n    @property\n    def OutputType(self) -> Type[T]:\n        # even though mypy complains this isn't valid,\n        # it is good enough for pydantic to build the schema from\n        return T  # type: ignore[misc]\n[docs]    def invoke(\n        self, input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None\n    ) -> T:\n        if isinstance(input, BaseMessage):\n            return self._call_with_config(\n                lambda inner_input: self.parse_result(\n                    [ChatGeneration(message=inner_input)]\n                ),\n                input,\n                config,\n                run_type=\"parser\",\n            )\n        else:\n            return self._call_with_config(\n                lambda inner_input: self.parse_result([Generation(text=inner_input)]),\n                input,\n                config,\n                run_type=\"parser\",\n            )\n[docs]    async def ainvoke(\n        self,\n        input: str | BaseMessage,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> T:\n        if isinstance(input, BaseMessage):\n            return await self._acall_with_config(\n                lambda inner_input: self.aparse_result(\n                    [ChatGeneration(message=inner_input)]\n                ),\n                input,\n                config,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html"}
{"id": "52bb77ea5ac5-2", "text": "),\n                input,\n                config,\n                run_type=\"parser\",\n            )\n        else:\n            return await self._acall_with_config(\n                lambda inner_input: self.aparse_result([Generation(text=inner_input)]),\n                input,\n                config,\n                run_type=\"parser\",\n            )\n[docs]class BaseOutputParser(\n    BaseLLMOutputParser, RunnableSerializable[Union[str, BaseMessage], T]\n):\n    \"\"\"Base class to parse the output of an LLM call.\n    Output parsers help structure language model responses.\n    Example:\n        .. code-block:: python\n            class BooleanOutputParser(BaseOutputParser[bool]):\n                true_val: str = \"YES\"\n                false_val: str = \"NO\"\n                def parse(self, text: str) -> bool:\n                    cleaned_text = text.strip().upper()\n                    if cleaned_text not in (self.true_val.upper(), self.false_val.upper()):\n                        raise OutputParserException(\n                            f\"BooleanOutputParser expected output value to either be \"\n                            f\"{self.true_val} or {self.false_val} (case-insensitive). \"\n                            f\"Received {cleaned_text}.\"\n                        )\n                    return cleaned_text == self.true_val.upper()\n                    @property\n                    def _type(self) -> str:\n                            return \"boolean_output_parser\"\n    \"\"\"  # noqa: E501\n    @property\n    def InputType(self) -> Any:\n        return Union[str, AnyMessage]\n    @property\n    def OutputType(self) -> Type[T]:\n        for cls in self.__class__.__orig_bases__:  # type: ignore[attr-defined]\n            type_args = get_args(cls)\n            if type_args and len(type_args) == 1:\n                return type_args[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html"}
{"id": "52bb77ea5ac5-3", "text": "return type_args[0]\n        raise TypeError(\n            f\"Runnable {self.__class__.__name__} doesn't have an inferable OutputType. \"\n            \"Override the OutputType property to specify the output type.\"\n        )\n[docs]    def invoke(\n        self, input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None\n    ) -> T:\n        if isinstance(input, BaseMessage):\n            return self._call_with_config(\n                lambda inner_input: self.parse_result(\n                    [ChatGeneration(message=inner_input)]\n                ),\n                input,\n                config,\n                run_type=\"parser\",\n            )\n        else:\n            return self._call_with_config(\n                lambda inner_input: self.parse_result([Generation(text=inner_input)]),\n                input,\n                config,\n                run_type=\"parser\",\n            )\n[docs]    async def ainvoke(\n        self,\n        input: str | BaseMessage,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> T:\n        if isinstance(input, BaseMessage):\n            return await self._acall_with_config(\n                lambda inner_input: self.aparse_result(\n                    [ChatGeneration(message=inner_input)]\n                ),\n                input,\n                config,\n                run_type=\"parser\",\n            )\n        else:\n            return await self._acall_with_config(\n                lambda inner_input: self.aparse_result([Generation(text=inner_input)]),\n                input,\n                config,\n                run_type=\"parser\",\n            )\n[docs]    def parse_result(self, result: List[Generation], *, partial: bool = False) -> T:\n        \"\"\"Parse a list of candidate model Generations into a specific format.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html"}
{"id": "52bb77ea5ac5-4", "text": "\"\"\"Parse a list of candidate model Generations into a specific format.\n        The return value is parsed from only the first Generation in the result, which\n            is assumed to be the highest-likelihood Generation.\n        Args:\n            result: A list of Generations to be parsed. The Generations are assumed\n                to be different candidate outputs for a single model input.\n        Returns:\n            Structured output.\n        \"\"\"\n        return self.parse(result[0].text)\n[docs]    @abstractmethod\n    def parse(self, text: str) -> T:\n        \"\"\"Parse a single string model output into some structure.\n        Args:\n            text: String output of a language model.\n        Returns:\n            Structured output.\n        \"\"\"\n[docs]    async def aparse_result(\n        self, result: List[Generation], *, partial: bool = False\n    ) -> T:\n        \"\"\"Parse a list of candidate model Generations into a specific format.\n        The return value is parsed from only the first Generation in the result, which\n            is assumed to be the highest-likelihood Generation.\n        Args:\n            result: A list of Generations to be parsed. The Generations are assumed\n                to be different candidate outputs for a single model input.\n        Returns:\n            Structured output.\n        \"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, functools.partial(self.parse_result, partial=partial), result\n        )\n[docs]    async def aparse(self, text: str) -> T:\n        \"\"\"Parse a single string model output into some structure.\n        Args:\n            text: String output of a language model.\n        Returns:\n            Structured output.\n        \"\"\"\n        return await asyncio.get_running_loop().run_in_executor(None, self.parse, text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html"}
{"id": "52bb77ea5ac5-5", "text": "return await asyncio.get_running_loop().run_in_executor(None, self.parse, text)\n    # TODO: rename 'completion' -> 'text'.\n[docs]    def parse_with_prompt(self, completion: str, prompt: PromptValue) -> Any:\n        \"\"\"Parse the output of an LLM call with the input prompt for context.\n        The prompt is largely provided in the event the OutputParser wants\n        to retry or fix the output in some way, and needs information from\n        the prompt to do so.\n        Args:\n            completion: String output of a language model.\n            prompt: Input PromptValue.\n        Returns:\n            Structured output\n        \"\"\"\n        return self.parse(completion)\n[docs]    def get_format_instructions(self) -> str:\n        \"\"\"Instructions on how the LLM output should be formatted.\"\"\"\n        raise NotImplementedError\n    @property\n    def _type(self) -> str:\n        \"\"\"Return the output parser type for serialization.\"\"\"\n        raise NotImplementedError(\n            f\"_type property is not implemented in class {self.__class__.__name__}.\"\n            \" This is required for serialization.\"\n        )\n[docs]    def dict(self, **kwargs: Any) -> Dict:\n        \"\"\"Return dictionary representation of output parser.\"\"\"\n        output_parser_dict = super().dict(**kwargs)\n        try:\n            output_parser_dict[\"_type\"] = self._type\n        except NotImplementedError:\n            pass\n        return output_parser_dict\n[docs]class BaseTransformOutputParser(BaseOutputParser[T]):\n    \"\"\"Base class for an output parser that can handle streaming input.\"\"\"\n    def _transform(self, input: Iterator[Union[str, BaseMessage]]) -> Iterator[T]:\n        for chunk in input:\n            if isinstance(chunk, BaseMessage):\n                yield self.parse_result([ChatGeneration(message=chunk)])\n            else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html"}
{"id": "52bb77ea5ac5-6", "text": "yield self.parse_result([ChatGeneration(message=chunk)])\n            else:\n                yield self.parse_result([Generation(text=chunk)])\n    async def _atransform(\n        self, input: AsyncIterator[Union[str, BaseMessage]]\n    ) -> AsyncIterator[T]:\n        async for chunk in input:\n            if isinstance(chunk, BaseMessage):\n                yield self.parse_result([ChatGeneration(message=chunk)])\n            else:\n                yield self.parse_result([Generation(text=chunk)])\n[docs]    def transform(\n        self,\n        input: Iterator[Union[str, BaseMessage]],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Iterator[T]:\n        yield from self._transform_stream_with_config(\n            input, self._transform, config, run_type=\"parser\"\n        )\n[docs]    async def atransform(\n        self,\n        input: AsyncIterator[Union[str, BaseMessage]],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[T]:\n        async for chunk in self._atransform_stream_with_config(\n            input, self._atransform, config, run_type=\"parser\"\n        ):\n            yield chunk\n[docs]class BaseCumulativeTransformOutputParser(BaseTransformOutputParser[T]):\n    \"\"\"Base class for an output parser that can handle streaming input.\"\"\"\n    diff: bool = False\n    \"\"\"In streaming mode, whether to yield diffs between the previous and current\n    parsed output, or just the current parsed output.\n    \"\"\"\n    def _diff(self, prev: Optional[T], next: T) -> T:\n        \"\"\"Convert parsed outputs into a diff format. The semantics of this are\n        up to the output parser.\"\"\"\n        raise NotImplementedError()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html"}
{"id": "52bb77ea5ac5-7", "text": "up to the output parser.\"\"\"\n        raise NotImplementedError()\n    def _transform(self, input: Iterator[Union[str, BaseMessage]]) -> Iterator[Any]:\n        prev_parsed = None\n        acc_gen = None\n        for chunk in input:\n            if isinstance(chunk, BaseMessageChunk):\n                chunk_gen: Generation = ChatGenerationChunk(message=chunk)\n            elif isinstance(chunk, BaseMessage):\n                chunk_gen = ChatGenerationChunk(\n                    message=BaseMessageChunk(**chunk.dict())\n                )\n            else:\n                chunk_gen = GenerationChunk(text=chunk)\n            if acc_gen is None:\n                acc_gen = chunk_gen\n            else:\n                acc_gen += chunk_gen\n            parsed = self.parse_result([acc_gen], partial=True)\n            if parsed is not None and parsed != prev_parsed:\n                if self.diff:\n                    yield self._diff(prev_parsed, parsed)\n                else:\n                    yield parsed\n                prev_parsed = parsed\n    async def _atransform(\n        self, input: AsyncIterator[Union[str, BaseMessage]]\n    ) -> AsyncIterator[T]:\n        prev_parsed = None\n        acc_gen = None\n        async for chunk in input:\n            if isinstance(chunk, BaseMessageChunk):\n                chunk_gen: Generation = ChatGenerationChunk(message=chunk)\n            elif isinstance(chunk, BaseMessage):\n                chunk_gen = ChatGenerationChunk(\n                    message=BaseMessageChunk(**chunk.dict())\n                )\n            else:\n                chunk_gen = GenerationChunk(text=chunk)\n            if acc_gen is None:\n                acc_gen = chunk_gen\n            else:\n                acc_gen += chunk_gen\n            parsed = self.parse_result([acc_gen], partial=True)\n            if parsed is not None and parsed != prev_parsed:\n                if self.diff:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html"}
{"id": "52bb77ea5ac5-8", "text": "if parsed is not None and parsed != prev_parsed:\n                if self.diff:\n                    yield self._diff(prev_parsed, parsed)\n                else:\n                    yield parsed\n                prev_parsed = parsed\n[docs]class StrOutputParser(BaseTransformOutputParser[str]):\n    \"\"\"OutputParser that parses LLMResult into the top likely string.\"\"\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this class is serializable.\"\"\"\n        return True\n    @property\n    def _type(self) -> str:\n        \"\"\"Return the output parser type for serialization.\"\"\"\n        return \"default\"\n[docs]    def parse(self, text: str) -> str:\n        \"\"\"Returns the input text with no changes.\"\"\"\n        return text\n# TODO: Deprecate\nNoOpOutputParser = StrOutputParser\n[docs]class OutputParserException(ValueError):\n    \"\"\"Exception that output parsers should raise to signify a parsing error.\n    This exists to differentiate parsing errors from other code or execution errors\n    that also may arise inside the output parser. OutputParserExceptions will be\n    available to catch and handle in ways to fix the parsing error, while other\n    errors will be raised.\n    Args:\n        error: The error that's being re-raised or an error message.\n        observation: String explanation of error which can be passed to a\n            model to try and remediate the issue.\n        llm_output: String model output which is error-ing.\n        send_to_llm: Whether to send the observation and llm_output back to an Agent\n            after an OutputParserException has been raised. This gives the underlying\n            model driving the agent the context that the previous output was improperly\n            structured, in the hopes that it will update the output to the correct\n            format.\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html"}
{"id": "52bb77ea5ac5-9", "text": "format.\n    \"\"\"\n    def __init__(\n        self,\n        error: Any,\n        observation: Optional[str] = None,\n        llm_output: Optional[str] = None,\n        send_to_llm: bool = False,\n    ):\n        super(OutputParserException, self).__init__(error)\n        if send_to_llm:\n            if observation is None or llm_output is None:\n                raise ValueError(\n                    \"Arguments 'observation' & 'llm_output'\"\n                    \" are required if 'send_to_llm' is True\"\n                )\n        self.observation = observation\n        self.llm_output = llm_output\n        self.send_to_llm = send_to_llm", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html"}
{"id": "cf75cb40b062-0", "text": "Source code for langchain.schema.language_model\nfrom __future__ import annotations\nfrom abc import ABC, abstractmethod\nfrom functools import lru_cache\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    List,\n    Optional,\n    Sequence,\n    Set,\n    TypeVar,\n    Union,\n)\nfrom typing_extensions import TypeAlias\nfrom langchain.schema.messages import AnyMessage, BaseMessage, get_buffer_string\nfrom langchain.schema.output import LLMResult\nfrom langchain.schema.prompt import PromptValue\nfrom langchain.schema.runnable import RunnableSerializable\nfrom langchain.utils import get_pydantic_field_names\nif TYPE_CHECKING:\n    from langchain.callbacks.manager import Callbacks\n@lru_cache(maxsize=None)  # Cache the tokenizer\ndef get_tokenizer() -> Any:\n    try:\n        from transformers import GPT2TokenizerFast\n    except ImportError:\n        raise ImportError(\n            \"Could not import transformers python package. \"\n            \"This is needed in order to calculate get_token_ids. \"\n            \"Please install it with `pip install transformers`.\"\n        )\n    # create a GPT-2 tokenizer instance\n    return GPT2TokenizerFast.from_pretrained(\"gpt2\")\ndef _get_token_ids_default_method(text: str) -> List[int]:\n    \"\"\"Encode the text into token IDs.\"\"\"\n    # get the cached tokenizer\n    tokenizer = get_tokenizer()\n    # tokenize the text using the GPT-2 tokenizer\n    return tokenizer.encode(text)\nLanguageModelInput = Union[PromptValue, str, List[BaseMessage]]\nLanguageModelOutput = TypeVar(\"LanguageModelOutput\")\n[docs]class BaseLanguageModel(\n    RunnableSerializable[LanguageModelInput, LanguageModelOutput], ABC\n):\n    \"\"\"Abstract base class for interfacing with language models.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html"}
{"id": "cf75cb40b062-1", "text": "):\n    \"\"\"Abstract base class for interfacing with language models.\n    All language model wrappers inherit from BaseLanguageModel.\n    Exposes three main methods:\n    - generate_prompt: generate language model outputs for a sequence of prompt\n        values. A prompt value is a model input that can be converted to any language\n        model input format (string or messages).\n    - predict: pass in a single string to a language model and return a string\n        prediction.\n    - predict_messages: pass in a sequence of BaseMessages (corresponding to a single\n        model call) to a language model and return a BaseMessage prediction.\n    Each of these has an equivalent asynchronous method.\n    \"\"\"\n    @property\n    def InputType(self) -> TypeAlias:\n        \"\"\"Get the input type for this runnable.\"\"\"\n        from langchain.prompts.base import StringPromptValue\n        from langchain.prompts.chat import ChatPromptValueConcrete\n        # This is a version of LanguageModelInput which replaces the abstract\n        # base class BaseMessage with a union of its subclasses, which makes\n        # for a much better schema.\n        return Union[\n            str,\n            Union[StringPromptValue, ChatPromptValueConcrete],\n            List[AnyMessage],\n        ]\n[docs]    @abstractmethod\n    def generate_prompt(\n        self,\n        prompts: List[PromptValue],\n        stop: Optional[List[str]] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Pass a sequence of prompts to the model and return model generations.\n        This method should make use of batched calls for models that expose a batched\n        API.\n        Use this method when you want to:\n            1. take advantage of batched calls,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html"}
{"id": "cf75cb40b062-2", "text": "1. take advantage of batched calls,\n            2. need more output from the model than just the top generated value,\n            3. are building chains that are agnostic to the underlying language model\n                type (e.g., pure text completion models vs chat models).\n        Args:\n            prompts: List of PromptValues. A PromptValue is an object that can be\n                converted to match the format of any language model (string for pure\n                text generation models and BaseMessages for chat models).\n            stop: Stop words to use when generating. Model output is cut off at the\n                first occurrence of any of these substrings.\n            callbacks: Callbacks to pass through. Used for executing additional\n                functionality, such as logging or streaming, throughout generation.\n            **kwargs: Arbitrary additional keyword arguments. These are usually passed\n                to the model provider API call.\n        Returns:\n            An LLMResult, which contains a list of candidate Generations for each input\n                prompt and additional model provider-specific output.\n        \"\"\"\n[docs]    @abstractmethod\n    async def agenerate_prompt(\n        self,\n        prompts: List[PromptValue],\n        stop: Optional[List[str]] = None,\n        callbacks: Callbacks = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Asynchronously pass a sequence of prompts and return model generations.\n        This method should make use of batched calls for models that expose a batched\n        API.\n        Use this method when you want to:\n            1. take advantage of batched calls,\n            2. need more output from the model than just the top generated value,\n            3. are building chains that are agnostic to the underlying language model\n                type (e.g., pure text completion models vs chat models).", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html"}
{"id": "cf75cb40b062-3", "text": "type (e.g., pure text completion models vs chat models).\n        Args:\n            prompts: List of PromptValues. A PromptValue is an object that can be\n                converted to match the format of any language model (string for pure\n                text generation models and BaseMessages for chat models).\n            stop: Stop words to use when generating. Model output is cut off at the\n                first occurrence of any of these substrings.\n            callbacks: Callbacks to pass through. Used for executing additional\n                functionality, such as logging or streaming, throughout generation.\n            **kwargs: Arbitrary additional keyword arguments. These are usually passed\n                to the model provider API call.\n        Returns:\n            An LLMResult, which contains a list of candidate Generations for each input\n                prompt and additional model provider-specific output.\n        \"\"\"\n[docs]    @abstractmethod\n    def predict(\n        self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any\n    ) -> str:\n        \"\"\"Pass a single string input to the model and return a string prediction.\n         Use this method when passing in raw text. If you want to pass in specific\n            types of chat messages, use predict_messages.\n        Args:\n            text: String input to pass to the model.\n            stop: Stop words to use when generating. Model output is cut off at the\n                first occurrence of any of these substrings.\n            **kwargs: Arbitrary additional keyword arguments. These are usually passed\n                to the model provider API call.\n        Returns:\n            Top model prediction as a string.\n        \"\"\"\n[docs]    @abstractmethod\n    def predict_messages(\n        self,\n        messages: List[BaseMessage],\n        *,\n        stop: Optional[Sequence[str]] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html"}
{"id": "cf75cb40b062-4", "text": "stop: Optional[Sequence[str]] = None,\n        **kwargs: Any,\n    ) -> BaseMessage:\n        \"\"\"Pass a message sequence to the model and return a message prediction.\n        Use this method when passing in chat messages. If you want to pass in raw text,\n            use predict.\n        Args:\n            messages: A sequence of chat messages corresponding to a single model input.\n            stop: Stop words to use when generating. Model output is cut off at the\n                first occurrence of any of these substrings.\n            **kwargs: Arbitrary additional keyword arguments. These are usually passed\n                to the model provider API call.\n        Returns:\n            Top model prediction as a message.\n        \"\"\"\n[docs]    @abstractmethod\n    async def apredict(\n        self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any\n    ) -> str:\n        \"\"\"Asynchronously pass a string to the model and return a string prediction.\n        Use this method when calling pure text generation models and only the top\n            candidate generation is needed.\n        Args:\n            text: String input to pass to the model.\n            stop: Stop words to use when generating. Model output is cut off at the\n                first occurrence of any of these substrings.\n            **kwargs: Arbitrary additional keyword arguments. These are usually passed\n                to the model provider API call.\n        Returns:\n            Top model prediction as a string.\n        \"\"\"\n[docs]    @abstractmethod\n    async def apredict_messages(\n        self,\n        messages: List[BaseMessage],\n        *,\n        stop: Optional[Sequence[str]] = None,\n        **kwargs: Any,\n    ) -> BaseMessage:\n        \"\"\"Asynchronously pass messages to the model and return a message prediction.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html"}
{"id": "cf75cb40b062-5", "text": "\"\"\"Asynchronously pass messages to the model and return a message prediction.\n        Use this method when calling chat models and only the top\n            candidate generation is needed.\n        Args:\n            messages: A sequence of chat messages corresponding to a single model input.\n            stop: Stop words to use when generating. Model output is cut off at the\n                first occurrence of any of these substrings.\n            **kwargs: Arbitrary additional keyword arguments. These are usually passed\n                to the model provider API call.\n        Returns:\n            Top model prediction as a message.\n        \"\"\"\n[docs]    def get_token_ids(self, text: str) -> List[int]:\n        \"\"\"Return the ordered ids of the tokens in a text.\n        Args:\n            text: The string input to tokenize.\n        Returns:\n            A list of ids corresponding to the tokens in the text, in order they occur\n                in the text.\n        \"\"\"\n        return _get_token_ids_default_method(text)\n[docs]    def get_num_tokens(self, text: str) -> int:\n        \"\"\"Get the number of tokens present in the text.\n        Useful for checking if an input will fit in a model's context window.\n        Args:\n            text: The string input to tokenize.\n        Returns:\n            The integer number of tokens in the text.\n        \"\"\"\n        return len(self.get_token_ids(text))\n[docs]    def get_num_tokens_from_messages(self, messages: List[BaseMessage]) -> int:\n        \"\"\"Get the number of tokens in the messages.\n        Useful for checking if an input will fit in a model's context window.\n        Args:\n            messages: The message inputs to tokenize.\n        Returns:\n            The sum of the number of tokens across the messages.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html"}
{"id": "cf75cb40b062-6", "text": "Returns:\n            The sum of the number of tokens across the messages.\n        \"\"\"\n        return sum([self.get_num_tokens(get_buffer_string([m])) for m in messages])\n    @classmethod\n    def _all_required_field_names(cls) -> Set:\n        \"\"\"DEPRECATED: Kept for backwards compatibility.\n        Use get_pydantic_field_names.\n        \"\"\"\n        return get_pydantic_field_names(cls)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html"}
{"id": "c0e052313c97-0", "text": "Source code for langchain.schema.storage\nfrom abc import ABC, abstractmethod\nfrom typing import Generic, Iterator, List, Optional, Sequence, Tuple, TypeVar, Union\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n[docs]class BaseStore(Generic[K, V], ABC):\n    \"\"\"Abstract interface for a key-value store.\"\"\"\n[docs]    @abstractmethod\n    def mget(self, keys: Sequence[K]) -> List[Optional[V]]:\n        \"\"\"Get the values associated with the given keys.\n        Args:\n            keys (Sequence[K]): A sequence of keys.\n        Returns:\n            A sequence of optional values associated with the keys.\n            If a key is not found, the corresponding value will be None.\n        \"\"\"\n[docs]    @abstractmethod\n    def mset(self, key_value_pairs: Sequence[Tuple[K, V]]) -> None:\n        \"\"\"Set the values for the given keys.\n        Args:\n            key_value_pairs (Sequence[Tuple[K, V]]): A sequence of key-value pairs.\n        \"\"\"\n[docs]    @abstractmethod\n    def mdelete(self, keys: Sequence[K]) -> None:\n        \"\"\"Delete the given keys and their associated values.\n        Args:\n            keys (Sequence[K]): A sequence of keys to delete.\n        \"\"\"\n[docs]    @abstractmethod\n    def yield_keys(\n        self, *, prefix: Optional[str] = None\n    ) -> Union[Iterator[K], Iterator[str]]:\n        \"\"\"Get an iterator over keys that match the given prefix.\n        Args:\n            prefix (str): The prefix to match.\n        Returns:\n            Iterator[K | str]: An iterator over keys that match the given prefix.\n            This method is allowed to return an iterator over either K or str", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/storage.html"}
{"id": "c0e052313c97-1", "text": "This method is allowed to return an iterator over either K or str\n            depending on what makes more sense for the given store.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/storage.html"}
{"id": "cf826ffac3d0-0", "text": "Source code for langchain.schema.embeddings\nimport asyncio\nfrom abc import ABC, abstractmethod\nfrom typing import List\n[docs]class Embeddings(ABC):\n    \"\"\"Interface for embedding models.\"\"\"\n[docs]    @abstractmethod\n    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Embed search docs.\"\"\"\n[docs]    @abstractmethod\n    def embed_query(self, text: str) -> List[float]:\n        \"\"\"Embed query text.\"\"\"\n[docs]    async def aembed_documents(self, texts: List[str]) -> List[List[float]]:\n        \"\"\"Asynchronous Embed search docs.\"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, self.embed_documents, texts\n        )\n[docs]    async def aembed_query(self, text: str) -> List[float]:\n        \"\"\"Asynchronous Embed query text.\"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, self.embed_query, text\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/embeddings.html"}
{"id": "c54a189d87e1-0", "text": "Source code for langchain.schema.memory\nfrom __future__ import annotations\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Dict, List\nfrom langchain.load.serializable import Serializable\n[docs]class BaseMemory(Serializable, ABC):\n    \"\"\"Abstract base class for memory in Chains.\n    Memory refers to state in Chains. Memory can be used to store information about\n        past executions of a Chain and inject that information into the inputs of\n        future executions of the Chain. For example, for conversational Chains Memory\n        can be used to store conversations and automatically add them to future model\n        prompts so that the model has the necessary context to respond coherently to\n        the latest input.\n    Example:\n        .. code-block:: python\n            class SimpleMemory(BaseMemory):\n                memories: Dict[str, Any] = dict()\n                @property\n                def memory_variables(self) -> List[str]:\n                    return list(self.memories.keys())\n                def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:\n                    return self.memories\n                def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n                    pass\n                def clear(self) -> None:\n                    pass\n    \"\"\"  # noqa: E501\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @property\n    @abstractmethod\n    def memory_variables(self) -> List[str]:\n        \"\"\"The string keys this memory class will add to chain inputs.\"\"\"\n[docs]    @abstractmethod\n    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Return key-value pairs given the text input to the chain.\"\"\"\n[docs]    @abstractmethod", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/memory.html"}
{"id": "c54a189d87e1-1", "text": "[docs]    @abstractmethod\n    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        \"\"\"Save the context of this chain run to memory.\"\"\"\n[docs]    @abstractmethod\n    def clear(self) -> None:\n        \"\"\"Clear memory contents.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/memory.html"}
{"id": "abf03308bc75-0", "text": "Source code for langchain.schema.messages\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING, Any, Dict, List, Sequence, Union\nfrom typing_extensions import Literal\nfrom langchain.load.serializable import Serializable\nfrom langchain.pydantic_v1 import Extra, Field\nif TYPE_CHECKING:\n    from langchain.prompts.chat import ChatPromptTemplate\n[docs]def get_buffer_string(\n    messages: Sequence[BaseMessage], human_prefix: str = \"Human\", ai_prefix: str = \"AI\"\n) -> str:\n    \"\"\"Convert sequence of Messages to strings and concatenate them into one string.\n    Args:\n        messages: Messages to be converted to strings.\n        human_prefix: The prefix to prepend to contents of HumanMessages.\n        ai_prefix: THe prefix to prepend to contents of AIMessages.\n    Returns:\n        A single string concatenation of all input messages.\n    Example:\n        .. code-block:: python\n            from langchain.schema import AIMessage, HumanMessage\n            messages = [\n                HumanMessage(content=\"Hi, how are you?\"),\n                AIMessage(content=\"Good, how are you?\"),\n            ]\n            get_buffer_string(messages)\n            # -> \"Human: Hi, how are you?\\nAI: Good, how are you?\"\n    \"\"\"\n    string_messages = []\n    for m in messages:\n        if isinstance(m, HumanMessage):\n            role = human_prefix\n        elif isinstance(m, AIMessage):\n            role = ai_prefix\n        elif isinstance(m, SystemMessage):\n            role = \"System\"\n        elif isinstance(m, FunctionMessage):\n            role = \"Function\"\n        elif isinstance(m, ChatMessage):\n            role = m.role\n        else:\n            raise ValueError(f\"Got unsupported message type: {m}\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html"}
{"id": "abf03308bc75-1", "text": "else:\n            raise ValueError(f\"Got unsupported message type: {m}\")\n        message = f\"{role}: {m.content}\"\n        if isinstance(m, AIMessage) and \"function_call\" in m.additional_kwargs:\n            message += f\"{m.additional_kwargs['function_call']}\"\n        string_messages.append(message)\n    return \"\\n\".join(string_messages)\n[docs]class BaseMessage(Serializable):\n    \"\"\"The base abstract Message class.\n    Messages are the inputs and outputs of ChatModels.\n    \"\"\"\n    content: Union[str, List[Union[str, Dict]]]\n    \"\"\"The string contents of the message.\"\"\"\n    additional_kwargs: dict = Field(default_factory=dict)\n    \"\"\"Any additional information.\"\"\"\n    type: str\n    class Config:\n        extra = Extra.allow\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this class is serializable.\"\"\"\n        return True\n    def __add__(self, other: Any) -> ChatPromptTemplate:\n        from langchain.prompts.chat import ChatPromptTemplate\n        prompt = ChatPromptTemplate(messages=[self])\n        return prompt + other\n[docs]def merge_content(\n    first_content: Union[str, List[Union[str, Dict]]],\n    second_content: Union[str, List[Union[str, Dict]]],\n) -> Union[str, List[Union[str, Dict]]]:\n    # If first chunk is a string\n    if isinstance(first_content, str):\n        # If the second chunk is also a string, then merge them naively\n        if isinstance(second_content, str):\n            return first_content + second_content\n        # If the second chunk is a list, add the first chunk to the start of the list\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html"}
{"id": "abf03308bc75-2", "text": "else:\n            return_list: List[Union[str, Dict]] = [first_content]\n            return return_list + second_content\n    # If both are lists, merge them naively\n    elif isinstance(second_content, List):\n        return first_content + second_content\n    # If the first content is a list, and the second content is a string\n    else:\n        # If the last element of the first content is a string\n        # Add the second content to the last element\n        if isinstance(first_content[-1], str):\n            return first_content[:-1] + [first_content[-1] + second_content]\n        else:\n            # Otherwise, add the second content as a new element of the list\n            return first_content + [second_content]\n[docs]class BaseMessageChunk(BaseMessage):\n    \"\"\"A Message chunk, which can be concatenated with other Message chunks.\"\"\"\n    def _merge_kwargs_dict(\n        self, left: Dict[str, Any], right: Dict[str, Any]\n    ) -> Dict[str, Any]:\n        \"\"\"Merge additional_kwargs from another BaseMessageChunk into this one.\"\"\"\n        merged = left.copy()\n        for k, v in right.items():\n            if k not in merged:\n                merged[k] = v\n            elif type(merged[k]) != type(v):\n                raise ValueError(\n                    f'additional_kwargs[\"{k}\"] already exists in this message,'\n                    \" but with a different type.\"\n                )\n            elif isinstance(merged[k], str):\n                merged[k] += v\n            elif isinstance(merged[k], dict):\n                merged[k] = self._merge_kwargs_dict(merged[k], v)\n            else:\n                raise ValueError(\n                    f\"Additional kwargs key {k} already exists in this message.\"\n                )\n        return merged", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html"}
{"id": "abf03308bc75-3", "text": ")\n        return merged\n    def __add__(self, other: Any) -> BaseMessageChunk:  # type: ignore\n        if isinstance(other, BaseMessageChunk):\n            # If both are (subclasses of) BaseMessageChunk,\n            # concat into a single BaseMessageChunk\n            if isinstance(self, ChatMessageChunk):\n                return self.__class__(\n                    role=self.role,\n                    content=merge_content(self.content, other.content),\n                    additional_kwargs=self._merge_kwargs_dict(\n                        self.additional_kwargs, other.additional_kwargs\n                    ),\n                )\n            return self.__class__(\n                content=merge_content(self.content, other.content),\n                additional_kwargs=self._merge_kwargs_dict(\n                    self.additional_kwargs, other.additional_kwargs\n                ),\n            )\n        else:\n            raise TypeError(\n                'unsupported operand type(s) for +: \"'\n                f\"{self.__class__.__name__}\"\n                f'\" and \"{other.__class__.__name__}\"'\n            )\n[docs]class HumanMessage(BaseMessage):\n    \"\"\"A Message from a human.\"\"\"\n    example: bool = False\n    \"\"\"Whether this Message is being passed in to the model as part of an example \n        conversation.\n    \"\"\"\n    type: Literal[\"human\"] = \"human\"\nHumanMessage.update_forward_refs()\n[docs]class HumanMessageChunk(HumanMessage, BaseMessageChunk):\n    \"\"\"A Human Message chunk.\"\"\"\n    # Ignoring mypy re-assignment here since we're overriding the value\n    # to make sure that the chunk variant can be discriminated from the\n    # non-chunk variant.\n    type: Literal[\"HumanMessageChunk\"] = \"HumanMessageChunk\"  # type: ignore[assignment] # noqa: E501\n[docs]class AIMessage(BaseMessage):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html"}
{"id": "abf03308bc75-4", "text": "[docs]class AIMessage(BaseMessage):\n    \"\"\"A Message from an AI.\"\"\"\n    example: bool = False\n    \"\"\"Whether this Message is being passed in to the model as part of an example \n        conversation.\n    \"\"\"\n    type: Literal[\"ai\"] = \"ai\"\nAIMessage.update_forward_refs()\n[docs]class AIMessageChunk(AIMessage, BaseMessageChunk):\n    \"\"\"A Message chunk from an AI.\"\"\"\n    # Ignoring mypy re-assignment here since we're overriding the value\n    # to make sure that the chunk variant can be discriminated from the\n    # non-chunk variant.\n    type: Literal[\"AIMessageChunk\"] = \"AIMessageChunk\"  # type: ignore[assignment] # noqa: E501\n    def __add__(self, other: Any) -> BaseMessageChunk:  # type: ignore\n        if isinstance(other, AIMessageChunk):\n            if self.example != other.example:\n                raise ValueError(\n                    \"Cannot concatenate AIMessageChunks with different example values.\"\n                )\n            return self.__class__(\n                example=self.example,\n                content=merge_content(self.content, other.content),\n                additional_kwargs=self._merge_kwargs_dict(\n                    self.additional_kwargs, other.additional_kwargs\n                ),\n            )\n        return super().__add__(other)\n[docs]class SystemMessage(BaseMessage):\n    \"\"\"A Message for priming AI behavior, usually passed in as the first of a sequence\n    of input messages.\n    \"\"\"\n    type: Literal[\"system\"] = \"system\"\nSystemMessage.update_forward_refs()\n[docs]class SystemMessageChunk(SystemMessage, BaseMessageChunk):\n    \"\"\"A System Message chunk.\"\"\"\n    # Ignoring mypy re-assignment here since we're overriding the value", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html"}
{"id": "abf03308bc75-5", "text": "# Ignoring mypy re-assignment here since we're overriding the value\n    # to make sure that the chunk variant can be discriminated from the\n    # non-chunk variant.\n    type: Literal[\"SystemMessageChunk\"] = \"SystemMessageChunk\"  # type: ignore[assignment] # noqa: E501\n[docs]class FunctionMessage(BaseMessage):\n    \"\"\"A Message for passing the result of executing a function back to a model.\"\"\"\n    name: str\n    \"\"\"The name of the function that was executed.\"\"\"\n    type: Literal[\"function\"] = \"function\"\nFunctionMessage.update_forward_refs()\n[docs]class FunctionMessageChunk(FunctionMessage, BaseMessageChunk):\n    \"\"\"A Function Message chunk.\"\"\"\n    # Ignoring mypy re-assignment here since we're overriding the value\n    # to make sure that the chunk variant can be discriminated from the\n    # non-chunk variant.\n    type: Literal[\"FunctionMessageChunk\"] = \"FunctionMessageChunk\"  # type: ignore[assignment]\n    def __add__(self, other: Any) -> BaseMessageChunk:  # type: ignore\n        if isinstance(other, FunctionMessageChunk):\n            if self.name != other.name:\n                raise ValueError(\n                    \"Cannot concatenate FunctionMessageChunks with different names.\"\n                )\n            return self.__class__(\n                name=self.name,\n                content=merge_content(self.content, other.content),\n                additional_kwargs=self._merge_kwargs_dict(\n                    self.additional_kwargs, other.additional_kwargs\n                ),\n            )\n        return super().__add__(other)\n[docs]class ToolMessage(BaseMessage):\n    \"\"\"A Message for passing the result of executing a tool back to a model.\"\"\"\n    tool_call_id: str\n    \"\"\"Tool call that this message is responding to.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html"}
{"id": "abf03308bc75-6", "text": "tool_call_id: str\n    \"\"\"Tool call that this message is responding to.\"\"\"\n    type: Literal[\"tool\"] = \"tool\"\nToolMessage.update_forward_refs()\n[docs]class ToolMessageChunk(ToolMessage, BaseMessageChunk):\n    \"\"\"A Tool Message chunk.\"\"\"\n    # Ignoring mypy re-assignment here since we're overriding the value\n    # to make sure that the chunk variant can be discriminated from the\n    # non-chunk variant.\n    type: Literal[\"ToolMessageChunk\"] = \"ToolMessageChunk\"  # type: ignore[assignment]\n    def __add__(self, other: Any) -> BaseMessageChunk:  # type: ignore\n        if isinstance(other, ToolMessageChunk):\n            if self.tool_call_id != other.tool_call_id:\n                raise ValueError(\n                    \"Cannot concatenate ToolMessageChunks with different names.\"\n                )\n            return self.__class__(\n                tool_call_id=self.tool_call_id,\n                content=merge_content(self.content, other.content),\n                additional_kwargs=self._merge_kwargs_dict(\n                    self.additional_kwargs, other.additional_kwargs\n                ),\n            )\n        return super().__add__(other)\n[docs]class ChatMessage(BaseMessage):\n    \"\"\"A Message that can be assigned an arbitrary speaker (i.e. role).\"\"\"\n    role: str\n    \"\"\"The speaker / role of the Message.\"\"\"\n    type: Literal[\"chat\"] = \"chat\"\nChatMessage.update_forward_refs()\n[docs]class ChatMessageChunk(ChatMessage, BaseMessageChunk):\n    \"\"\"A Chat Message chunk.\"\"\"\n    # Ignoring mypy re-assignment here since we're overriding the value\n    # to make sure that the chunk variant can be discriminated from the\n    # non-chunk variant.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html"}
{"id": "abf03308bc75-7", "text": "# non-chunk variant.\n    type: Literal[\"ChatMessageChunk\"] = \"ChatMessageChunk\"  # type: ignore\n    def __add__(self, other: Any) -> BaseMessageChunk:  # type: ignore\n        if isinstance(other, ChatMessageChunk):\n            if self.role != other.role:\n                raise ValueError(\n                    \"Cannot concatenate ChatMessageChunks with different roles.\"\n                )\n            return self.__class__(\n                role=self.role,\n                content=merge_content(self.content, other.content),\n                additional_kwargs=self._merge_kwargs_dict(\n                    self.additional_kwargs, other.additional_kwargs\n                ),\n            )\n        return super().__add__(other)\nAnyMessage = Union[\n    AIMessage, HumanMessage, ChatMessage, SystemMessage, FunctionMessage, ToolMessage\n]\ndef _message_to_dict(message: BaseMessage) -> dict:\n    return {\"type\": message.type, \"data\": message.dict()}\n[docs]def messages_to_dict(messages: Sequence[BaseMessage]) -> List[dict]:\n    \"\"\"Convert a sequence of Messages to a list of dictionaries.\n    Args:\n        messages: Sequence of messages (as BaseMessages) to convert.\n    Returns:\n        List of messages as dicts.\n    \"\"\"\n    return [_message_to_dict(m) for m in messages]\ndef _message_from_dict(message: dict) -> BaseMessage:\n    _type = message[\"type\"]\n    if _type == \"human\":\n        return HumanMessage(**message[\"data\"])\n    elif _type == \"ai\":\n        return AIMessage(**message[\"data\"])\n    elif _type == \"system\":\n        return SystemMessage(**message[\"data\"])\n    elif _type == \"chat\":\n        return ChatMessage(**message[\"data\"])\n    elif _type == \"function\":", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html"}
{"id": "abf03308bc75-8", "text": "return ChatMessage(**message[\"data\"])\n    elif _type == \"function\":\n        return FunctionMessage(**message[\"data\"])\n    elif _type == \"tool\":\n        return ToolMessage(**message[\"data\"])\n    else:\n        raise ValueError(f\"Got unexpected message type: {_type}\")\n[docs]def messages_from_dict(messages: List[dict]) -> List[BaseMessage]:\n    \"\"\"Convert a sequence of messages from dicts to Message objects.\n    Args:\n        messages: Sequence of messages (as dicts) to convert.\n    Returns:\n        List of messages (BaseMessages).\n    \"\"\"\n    return [_message_from_dict(m) for m in messages]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html"}
{"id": "f7c3fcd00905-0", "text": "Source code for langchain.schema.output\nfrom __future__ import annotations\nfrom copy import deepcopy\nfrom typing import Any, Dict, List, Literal, Optional\nfrom uuid import UUID\nfrom langchain.load.serializable import Serializable\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema.messages import BaseMessage, BaseMessageChunk\n[docs]class Generation(Serializable):\n    \"\"\"A single text generation output.\"\"\"\n    text: str\n    \"\"\"Generated text output.\"\"\"\n    generation_info: Optional[Dict[str, Any]] = None\n    \"\"\"Raw response from the provider. May include things like the \n        reason for finishing or token log probabilities.\n    \"\"\"\n    type: Literal[\"Generation\"] = \"Generation\"\n    \"\"\"Type is used exclusively for serialization purposes.\"\"\"\n    # TODO: add log probs as separate attribute\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this class is serializable.\"\"\"\n        return True\n[docs]class GenerationChunk(Generation):\n    \"\"\"A Generation chunk, which can be concatenated with other Generation chunks.\"\"\"\n    def __add__(self, other: GenerationChunk) -> GenerationChunk:\n        if isinstance(other, GenerationChunk):\n            generation_info = (\n                {**(self.generation_info or {}), **(other.generation_info or {})}\n                if self.generation_info is not None or other.generation_info is not None\n                else None\n            )\n            return GenerationChunk(\n                text=self.text + other.text,\n                generation_info=generation_info,\n            )\n        else:\n            raise TypeError(\n                f\"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'\"\n            )\n[docs]class ChatGeneration(Generation):\n    \"\"\"A single chat generation output.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output.html"}
{"id": "f7c3fcd00905-1", "text": "[docs]class ChatGeneration(Generation):\n    \"\"\"A single chat generation output.\"\"\"\n    text: str = \"\"\n    \"\"\"*SHOULD NOT BE SET DIRECTLY* The text contents of the output message.\"\"\"\n    message: BaseMessage\n    \"\"\"The message output by the chat model.\"\"\"\n    # Override type to be ChatGeneration, ignore mypy error as this is intentional\n    type: Literal[\"ChatGeneration\"] = \"ChatGeneration\"  # type: ignore[assignment]\n    \"\"\"Type is used exclusively for serialization purposes.\"\"\"\n    @root_validator\n    def set_text(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Set the text attribute to be the contents of the message.\"\"\"\n        try:\n            values[\"text\"] = values[\"message\"].content\n        except (KeyError, AttributeError) as e:\n            raise ValueError(\"Error while initializing ChatGeneration\") from e\n        return values\n[docs]class ChatGenerationChunk(ChatGeneration):\n    \"\"\"A ChatGeneration chunk, which can be concatenated with other\n      ChatGeneration chunks.\n    Attributes:\n        message: The message chunk output by the chat model.\n    \"\"\"\n    message: BaseMessageChunk\n    # Override type to be ChatGeneration, ignore mypy error as this is intentional\n    type: Literal[\"ChatGenerationChunk\"] = \"ChatGenerationChunk\"  # type: ignore[assignment] # noqa: E501\n    \"\"\"Type is used exclusively for serialization purposes.\"\"\"\n    def __add__(self, other: ChatGenerationChunk) -> ChatGenerationChunk:\n        if isinstance(other, ChatGenerationChunk):\n            generation_info = (\n                {**(self.generation_info or {}), **(other.generation_info or {})}\n                if self.generation_info is not None or other.generation_info is not None\n                else None\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output.html"}
{"id": "f7c3fcd00905-2", "text": "else None\n            )\n            return ChatGenerationChunk(\n                message=self.message + other.message,\n                generation_info=generation_info,\n            )\n        else:\n            raise TypeError(\n                f\"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'\"\n            )\n[docs]class RunInfo(BaseModel):\n    \"\"\"Class that contains metadata for a single execution of a Chain or model.\"\"\"\n    run_id: UUID\n    \"\"\"A unique identifier for the model or chain run.\"\"\"\n[docs]class ChatResult(BaseModel):\n    \"\"\"Class that contains all results for a single chat model call.\"\"\"\n    generations: List[ChatGeneration]\n    \"\"\"List of the chat generations. This is a List because an input can have multiple \n        candidate generations.\n    \"\"\"\n    llm_output: Optional[dict] = None\n    \"\"\"For arbitrary LLM provider specific output.\"\"\"\n[docs]class LLMResult(BaseModel):\n    \"\"\"Class that contains all results for a batched LLM call.\"\"\"\n    generations: List[List[Generation]]\n    \"\"\"List of generated outputs. This is a List[List[]] because\n    each input could have multiple candidate generations.\"\"\"\n    llm_output: Optional[dict] = None\n    \"\"\"Arbitrary LLM provider-specific output.\"\"\"\n    run: Optional[List[RunInfo]] = None\n    \"\"\"List of metadata info for model call for each input.\"\"\"\n[docs]    def flatten(self) -> List[LLMResult]:\n        \"\"\"Flatten generations into a single list.\n        Unpack List[List[Generation]] -> List[LLMResult] where each returned LLMResult\n            contains only a single Generation. If token usage information is available,\n            it is kept only for the LLMResult corresponding to the top-choice", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output.html"}
{"id": "f7c3fcd00905-3", "text": "it is kept only for the LLMResult corresponding to the top-choice\n            Generation, to avoid over-counting of token usage downstream.\n        Returns:\n            List of LLMResults where each returned LLMResult contains a single\n                Generation.\n        \"\"\"\n        llm_results = []\n        for i, gen_list in enumerate(self.generations):\n            # Avoid double counting tokens in OpenAICallback\n            if i == 0:\n                llm_results.append(\n                    LLMResult(\n                        generations=[gen_list],\n                        llm_output=self.llm_output,\n                    )\n                )\n            else:\n                if self.llm_output is not None:\n                    llm_output = deepcopy(self.llm_output)\n                    llm_output[\"token_usage\"] = dict()\n                else:\n                    llm_output = None\n                llm_results.append(\n                    LLMResult(\n                        generations=[gen_list],\n                        llm_output=llm_output,\n                    )\n                )\n        return llm_results\n    def __eq__(self, other: object) -> bool:\n        \"\"\"Check for LLMResult equality by ignoring any metadata related to runs.\"\"\"\n        if not isinstance(other, LLMResult):\n            return NotImplemented\n        return (\n            self.generations == other.generations\n            and self.llm_output == other.llm_output\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output.html"}
{"id": "8cf9574238da-0", "text": "Source code for langchain.schema.callbacks.manager\nfrom __future__ import annotations\nimport asyncio\nimport functools\nimport logging\nimport os\nimport uuid\nfrom concurrent.futures import ThreadPoolExecutor\nfrom contextlib import asynccontextmanager, contextmanager\nfrom contextvars import ContextVar\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    AsyncGenerator,\n    Coroutine,\n    Dict,\n    Generator,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    Type,\n    TypeVar,\n    Union,\n    cast,\n)\nfrom uuid import UUID\nfrom langsmith import utils as ls_utils\nfrom langsmith.run_helpers import get_run_tree_context\nfrom tenacity import RetryCallState\nfrom langchain.schema import (\n    AgentAction,\n    AgentFinish,\n    Document,\n    LLMResult,\n)\nfrom langchain.schema.callbacks.base import (\n    BaseCallbackHandler,\n    BaseCallbackManager,\n    Callbacks,\n    ChainManagerMixin,\n    LLMManagerMixin,\n    RetrieverManagerMixin,\n    RunManagerMixin,\n    ToolManagerMixin,\n)\nfrom langchain.schema.callbacks.stdout import StdOutCallbackHandler\nfrom langchain.schema.callbacks.tracers import run_collector\nfrom langchain.schema.callbacks.tracers.langchain import (\n    LangChainTracer,\n)\nfrom langchain.schema.callbacks.tracers.langchain_v1 import (\n    LangChainTracerV1,\n    TracerSessionV1,\n)\nfrom langchain.schema.callbacks.tracers.stdout import ConsoleCallbackHandler\nfrom langchain.schema.messages import BaseMessage, get_buffer_string\nfrom langchain.schema.output import ChatGenerationChunk, GenerationChunk\nif TYPE_CHECKING:\n    from langsmith import Client as LangSmithClient\nlogger = logging.getLogger(__name__)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-1", "text": "from langsmith import Client as LangSmithClient\nlogger = logging.getLogger(__name__)\ntracing_callback_var: ContextVar[Optional[LangChainTracerV1]] = ContextVar(  # noqa: E501\n    \"tracing_callback\", default=None\n)\ntracing_v2_callback_var: ContextVar[Optional[LangChainTracer]] = ContextVar(  # noqa: E501\n    \"tracing_callback_v2\", default=None\n)\nrun_collector_var: ContextVar[\n    Optional[run_collector.RunCollectorCallbackHandler]\n] = ContextVar(  # noqa: E501\n    \"run_collector\", default=None\n)\ndef _get_debug() -> bool:\n    from langchain.globals import get_debug\n    return get_debug()\n[docs]@contextmanager\ndef tracing_enabled(\n    session_name: str = \"default\",\n) -> Generator[TracerSessionV1, None, None]:\n    \"\"\"Get the Deprecated LangChainTracer in a context manager.\n    Args:\n        session_name (str, optional): The name of the session.\n          Defaults to \"default\".\n    Returns:\n        TracerSessionV1: The LangChainTracer session.\n    Example:\n        >>> with tracing_enabled() as session:\n        ...     # Use the LangChainTracer session\n    \"\"\"\n    cb = LangChainTracerV1()\n    session = cast(TracerSessionV1, cb.load_session(session_name))\n    try:\n        tracing_callback_var.set(cb)\n        yield session\n    finally:\n        tracing_callback_var.set(None)\n[docs]@contextmanager\ndef tracing_v2_enabled(\n    project_name: Optional[str] = None,\n    *,\n    example_id: Optional[Union[str, UUID]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-2", "text": "*,\n    example_id: Optional[Union[str, UUID]] = None,\n    tags: Optional[List[str]] = None,\n    client: Optional[LangSmithClient] = None,\n) -> Generator[LangChainTracer, None, None]:\n    \"\"\"Instruct LangChain to log all runs in context to LangSmith.\n    Args:\n        project_name (str, optional): The name of the project.\n            Defaults to \"default\".\n        example_id (str or UUID, optional): The ID of the example.\n            Defaults to None.\n        tags (List[str], optional): The tags to add to the run.\n            Defaults to None.\n    Returns:\n        None\n    Example:\n        >>> with tracing_v2_enabled():\n        ...     # LangChain code will automatically be traced\n        You can use this to fetch the LangSmith run URL:\n        >>> with tracing_v2_enabled() as cb:\n        ...     chain.invoke(\"foo\")\n        ...     run_url = cb.get_run_url()\n    \"\"\"\n    if isinstance(example_id, str):\n        example_id = UUID(example_id)\n    cb = LangChainTracer(\n        example_id=example_id,\n        project_name=project_name,\n        tags=tags,\n        client=client,\n    )\n    try:\n        tracing_v2_callback_var.set(cb)\n        yield cb\n    finally:\n        tracing_v2_callback_var.set(None)\n[docs]@contextmanager\ndef collect_runs() -> Generator[run_collector.RunCollectorCallbackHandler, None, None]:\n    \"\"\"Collect all run traces in context.\n    Returns:\n        run_collector.RunCollectorCallbackHandler: The run collector callback handler.\n    Example:\n        >>> with collect_runs() as runs_cb:\n                chain.invoke(\"foo\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-3", "text": ">>> with collect_runs() as runs_cb:\n                chain.invoke(\"foo\")\n                run_id = runs_cb.traced_runs[0].id\n    \"\"\"\n    cb = run_collector.RunCollectorCallbackHandler()\n    run_collector_var.set(cb)\n    yield cb\n    run_collector_var.set(None)\ndef _get_trace_callbacks(\n    project_name: Optional[str] = None,\n    example_id: Optional[Union[str, UUID]] = None,\n    callback_manager: Optional[Union[CallbackManager, AsyncCallbackManager]] = None,\n) -> Callbacks:\n    if _tracing_v2_is_enabled():\n        project_name_ = project_name or _get_tracer_project()\n        tracer = tracing_v2_callback_var.get() or LangChainTracer(\n            project_name=project_name_,\n            example_id=example_id,\n        )\n        if callback_manager is None:\n            cb = cast(Callbacks, [tracer])\n        else:\n            if not any(\n                isinstance(handler, LangChainTracer)\n                for handler in callback_manager.handlers\n            ):\n                callback_manager.add_handler(tracer, True)\n                # If it already has a LangChainTracer, we don't need to add another one.\n                # this would likely mess up the trace hierarchy.\n            cb = callback_manager\n    else:\n        cb = None\n    return cb\n[docs]@contextmanager\ndef trace_as_chain_group(\n    group_name: str,\n    callback_manager: Optional[CallbackManager] = None,\n    *,\n    inputs: Optional[Dict[str, Any]] = None,\n    project_name: Optional[str] = None,\n    example_id: Optional[Union[str, UUID]] = None,\n    run_id: Optional[UUID] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-4", "text": "run_id: Optional[UUID] = None,\n    tags: Optional[List[str]] = None,\n) -> Generator[CallbackManagerForChainGroup, None, None]:\n    \"\"\"Get a callback manager for a chain group in a context manager.\n    Useful for grouping different calls together as a single run even if\n    they aren't composed in a single chain.\n    Args:\n        group_name (str): The name of the chain group.\n        callback_manager (CallbackManager, optional): The callback manager to use.\n        inputs (Dict[str, Any], optional): The inputs to the chain group.\n        project_name (str, optional): The name of the project.\n            Defaults to None.\n        example_id (str or UUID, optional): The ID of the example.\n            Defaults to None.\n        run_id (UUID, optional): The ID of the run.\n        tags (List[str], optional): The inheritable tags to apply to all runs.\n            Defaults to None.\n    Note: must have LANGCHAIN_TRACING_V2 env var set to true to see the trace in LangSmith.\n    Returns:\n        CallbackManagerForChainGroup: The callback manager for the chain group.\n    Example:\n        .. code-block:: python\n            llm_input = \"Foo\"\n            with trace_as_chain_group(\"group_name\", inputs={\"input\": llm_input}) as manager:\n                # Use the callback manager for the chain group\n                res = llm.predict(llm_input, callbacks=manager)\n                manager.on_chain_end({\"output\": res})\n    \"\"\"  # noqa: E501\n    cb = _get_trace_callbacks(\n        project_name, example_id, callback_manager=callback_manager\n    )\n    cm = CallbackManager.configure(\n        inheritable_callbacks=cb,\n        inheritable_tags=tags,\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-5", "text": "inheritable_callbacks=cb,\n        inheritable_tags=tags,\n    )\n    run_manager = cm.on_chain_start({\"name\": group_name}, inputs or {}, run_id=run_id)\n    child_cm = run_manager.get_child()\n    group_cm = CallbackManagerForChainGroup(\n        child_cm.handlers,\n        child_cm.inheritable_handlers,\n        child_cm.parent_run_id,\n        parent_run_manager=run_manager,\n        tags=child_cm.tags,\n        inheritable_tags=child_cm.inheritable_tags,\n        metadata=child_cm.metadata,\n        inheritable_metadata=child_cm.inheritable_metadata,\n    )\n    try:\n        yield group_cm\n    except Exception as e:\n        if not group_cm.ended:\n            run_manager.on_chain_error(e)\n        raise e\n    else:\n        if not group_cm.ended:\n            run_manager.on_chain_end({})\n[docs]@asynccontextmanager\nasync def atrace_as_chain_group(\n    group_name: str,\n    callback_manager: Optional[AsyncCallbackManager] = None,\n    *,\n    inputs: Optional[Dict[str, Any]] = None,\n    project_name: Optional[str] = None,\n    example_id: Optional[Union[str, UUID]] = None,\n    run_id: Optional[UUID] = None,\n    tags: Optional[List[str]] = None,\n) -> AsyncGenerator[AsyncCallbackManagerForChainGroup, None]:\n    \"\"\"Get an async callback manager for a chain group in a context manager.\n    Useful for grouping different async calls together as a single run even if\n    they aren't composed in a single chain.\n    Args:\n        group_name (str): The name of the chain group.\n        callback_manager (AsyncCallbackManager, optional): The async callback manager to use,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-6", "text": "callback_manager (AsyncCallbackManager, optional): The async callback manager to use,\n            which manages tracing and other callback behavior.\n        project_name (str, optional): The name of the project.\n            Defaults to None.\n        example_id (str or UUID, optional): The ID of the example.\n            Defaults to None.\n        run_id (UUID, optional): The ID of the run.\n        tags (List[str], optional): The inheritable tags to apply to all runs.\n            Defaults to None.\n    Returns:\n        AsyncCallbackManager: The async callback manager for the chain group.\n    Note: must have LANGCHAIN_TRACING_V2 env var set to true to see the trace in LangSmith.\n    Example:\n        .. code-block:: python\n            llm_input = \"Foo\"\n            async with atrace_as_chain_group(\"group_name\", inputs={\"input\": llm_input}) as manager:\n                # Use the async callback manager for the chain group\n                res = await llm.apredict(llm_input, callbacks=manager)\n                await manager.on_chain_end({\"output\": res})\n    \"\"\"  # noqa: E501\n    cb = _get_trace_callbacks(\n        project_name, example_id, callback_manager=callback_manager\n    )\n    cm = AsyncCallbackManager.configure(inheritable_callbacks=cb, inheritable_tags=tags)\n    run_manager = await cm.on_chain_start(\n        {\"name\": group_name}, inputs or {}, run_id=run_id\n    )\n    child_cm = run_manager.get_child()\n    group_cm = AsyncCallbackManagerForChainGroup(\n        child_cm.handlers,\n        child_cm.inheritable_handlers,\n        child_cm.parent_run_id,\n        parent_run_manager=run_manager,\n        tags=child_cm.tags,\n        inheritable_tags=child_cm.inheritable_tags,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-7", "text": "inheritable_tags=child_cm.inheritable_tags,\n        metadata=child_cm.metadata,\n        inheritable_metadata=child_cm.inheritable_metadata,\n    )\n    try:\n        yield group_cm\n    except Exception as e:\n        if not group_cm.ended:\n            await run_manager.on_chain_error(e)\n        raise e\n    else:\n        if not group_cm.ended:\n            await run_manager.on_chain_end({})\n[docs]def handle_event(\n    handlers: List[BaseCallbackHandler],\n    event_name: str,\n    ignore_condition_name: Optional[str],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Generic event handler for CallbackManager.\n    Note: This function is used by langserve to handle events.\n    Args:\n        handlers: The list of handlers that will handle the event\n        event_name: The name of the event (e.g., \"on_llm_start\")\n        ignore_condition_name: Name of the attribute defined on handler\n            that if True will cause the handler to be skipped for the given event\n        *args: The arguments to pass to the event handler\n        **kwargs: The keyword arguments to pass to the event handler\n    \"\"\"\n    coros: List[Coroutine[Any, Any, Any]] = []\n    try:\n        message_strings: Optional[List[str]] = None\n        for handler in handlers:\n            try:\n                if ignore_condition_name is None or not getattr(\n                    handler, ignore_condition_name\n                ):\n                    event = getattr(handler, event_name)(*args, **kwargs)\n                    if asyncio.iscoroutine(event):\n                        coros.append(event)\n            except NotImplementedError as e:\n                if event_name == \"on_chat_model_start\":\n                    if message_strings is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-8", "text": "if event_name == \"on_chat_model_start\":\n                    if message_strings is None:\n                        message_strings = [get_buffer_string(m) for m in args[1]]\n                    handle_event(\n                        [handler],\n                        \"on_llm_start\",\n                        \"ignore_llm\",\n                        args[0],\n                        message_strings,\n                        *args[2:],\n                        **kwargs,\n                    )\n                else:\n                    handler_name = handler.__class__.__name__\n                    logger.warning(\n                        f\"NotImplementedError in {handler_name}.{event_name}\"\n                        f\" callback: {repr(e)}\"\n                    )\n            except Exception as e:\n                logger.warning(\n                    f\"Error in {handler.__class__.__name__}.{event_name} callback:\"\n                    f\" {repr(e)}\"\n                )\n                if handler.raise_error:\n                    raise e\n    finally:\n        if coros:\n            try:\n                # Raises RuntimeError if there is no current event loop.\n                asyncio.get_running_loop()\n                loop_running = True\n            except RuntimeError:\n                loop_running = False\n            if loop_running:\n                # If we try to submit this coroutine to the running loop\n                # we end up in a deadlock, as we'd have gotten here from a\n                # running coroutine, which we cannot interrupt to run this one.\n                # The solution is to create a new loop in a new thread.\n                with ThreadPoolExecutor(1) as executor:\n                    executor.submit(_run_coros, coros).result()\n            else:\n                _run_coros(coros)\ndef _run_coros(coros: List[Coroutine[Any, Any, Any]]) -> None:\n    if hasattr(asyncio, \"Runner\"):\n        # Python 3.11+", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-9", "text": "if hasattr(asyncio, \"Runner\"):\n        # Python 3.11+\n        # Run the coroutines in a new event loop, taking care to\n        # - install signal handlers\n        # - run pending tasks scheduled by `coros`\n        # - close asyncgens and executors\n        # - close the loop\n        with asyncio.Runner() as runner:\n            # Run the coroutine, get the result\n            for coro in coros:\n                runner.run(coro)\n            # Run pending tasks scheduled by coros until they are all done\n            while pending := asyncio.all_tasks(runner.get_loop()):\n                runner.run(asyncio.wait(pending))\n    else:\n        # Before Python 3.11 we need to run each coroutine in a new event loop\n        # as the Runner api is not available.\n        for coro in coros:\n            asyncio.run(coro)\nasync def _ahandle_event_for_handler(\n    handler: BaseCallbackHandler,\n    event_name: str,\n    ignore_condition_name: Optional[str],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    try:\n        if ignore_condition_name is None or not getattr(handler, ignore_condition_name):\n            event = getattr(handler, event_name)\n            if asyncio.iscoroutinefunction(event):\n                await event(*args, **kwargs)\n            else:\n                if handler.run_inline:\n                    event(*args, **kwargs)\n                else:\n                    await asyncio.get_event_loop().run_in_executor(\n                        None, functools.partial(event, *args, **kwargs)\n                    )\n    except NotImplementedError as e:\n        if event_name == \"on_chat_model_start\":\n            message_strings = [get_buffer_string(m) for m in args[1]]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-10", "text": "message_strings = [get_buffer_string(m) for m in args[1]]\n            await _ahandle_event_for_handler(\n                handler,\n                \"on_llm_start\",\n                \"ignore_llm\",\n                args[0],\n                message_strings,\n                *args[2:],\n                **kwargs,\n            )\n        else:\n            logger.warning(\n                f\"NotImplementedError in {handler.__class__.__name__}.{event_name}\"\n                f\" callback: {repr(e)}\"\n            )\n    except Exception as e:\n        logger.warning(\n            f\"Error in {handler.__class__.__name__}.{event_name} callback:\"\n            f\" {repr(e)}\"\n        )\n        if handler.raise_error:\n            raise e\n[docs]async def ahandle_event(\n    handlers: List[BaseCallbackHandler],\n    event_name: str,\n    ignore_condition_name: Optional[str],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Generic event handler for AsyncCallbackManager.\n    Note: This function is used by langserve to handle events.\n    Args:\n        handlers: The list of handlers that will handle the event\n        event_name: The name of the event (e.g., \"on_llm_start\")\n        ignore_condition_name: Name of the attribute defined on handler\n            that if True will cause the handler to be skipped for the given event\n        *args: The arguments to pass to the event handler\n        **kwargs: The keyword arguments to pass to the event handler\n    \"\"\"\n    for handler in [h for h in handlers if h.run_inline]:\n        await _ahandle_event_for_handler(\n            handler, event_name, ignore_condition_name, *args, **kwargs\n        )\n    await asyncio.gather(\n        *(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-11", "text": ")\n    await asyncio.gather(\n        *(\n            _ahandle_event_for_handler(\n                handler, event_name, ignore_condition_name, *args, **kwargs\n            )\n            for handler in handlers\n            if not handler.run_inline\n        )\n    )\nBRM = TypeVar(\"BRM\", bound=\"BaseRunManager\")\n[docs]class BaseRunManager(RunManagerMixin):\n    \"\"\"Base class for run manager (a bound callback manager).\"\"\"\n[docs]    def __init__(\n        self,\n        *,\n        run_id: UUID,\n        handlers: List[BaseCallbackHandler],\n        inheritable_handlers: List[BaseCallbackHandler],\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        inheritable_tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        inheritable_metadata: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        \"\"\"Initialize the run manager.\n        Args:\n            run_id (UUID): The ID of the run.\n            handlers (List[BaseCallbackHandler]): The list of handlers.\n            inheritable_handlers (List[BaseCallbackHandler]):\n                The list of inheritable handlers.\n            parent_run_id (UUID, optional): The ID of the parent run.\n                Defaults to None.\n            tags (Optional[List[str]]): The list of tags.\n            inheritable_tags (Optional[List[str]]): The list of inheritable tags.\n            metadata (Optional[Dict[str, Any]]): The metadata.\n            inheritable_metadata (Optional[Dict[str, Any]]): The inheritable metadata.\n        \"\"\"\n        self.run_id = run_id\n        self.handlers = handlers\n        self.inheritable_handlers = inheritable_handlers", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-12", "text": "self.handlers = handlers\n        self.inheritable_handlers = inheritable_handlers\n        self.parent_run_id = parent_run_id\n        self.tags = tags or []\n        self.inheritable_tags = inheritable_tags or []\n        self.metadata = metadata or {}\n        self.inheritable_metadata = inheritable_metadata or {}\n[docs]    @classmethod\n    def get_noop_manager(cls: Type[BRM]) -> BRM:\n        \"\"\"Return a manager that doesn't perform any operations.\n        Returns:\n            BaseRunManager: The noop manager.\n        \"\"\"\n        return cls(\n            run_id=uuid.uuid4(),\n            handlers=[],\n            inheritable_handlers=[],\n            tags=[],\n            inheritable_tags=[],\n            metadata={},\n            inheritable_metadata={},\n        )\n[docs]class RunManager(BaseRunManager):\n    \"\"\"Sync Run Manager.\"\"\"\n[docs]    def on_text(\n        self,\n        text: str,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when text is received.\n        Args:\n            text (str): The received text.\n        Returns:\n            Any: The result of the callback.\n        \"\"\"\n        handle_event(\n            self.handlers,\n            \"on_text\",\n            None,\n            text,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    def on_retry(\n        self,\n        retry_state: RetryCallState,\n        **kwargs: Any,\n    ) -> None:\n        handle_event(\n            self.handlers,\n            \"on_retry\",\n            \"ignore_retry\",\n            retry_state,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-13", "text": "run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]class ParentRunManager(RunManager):\n    \"\"\"Sync Parent Run Manager.\"\"\"\n[docs]    def get_child(self, tag: Optional[str] = None) -> CallbackManager:\n        \"\"\"Get a child callback manager.\n        Args:\n            tag (str, optional): The tag for the child callback manager.\n                Defaults to None.\n        Returns:\n            CallbackManager: The child callback manager.\n        \"\"\"\n        manager = CallbackManager(handlers=[], parent_run_id=self.run_id)\n        manager.set_handlers(self.inheritable_handlers)\n        manager.add_tags(self.inheritable_tags)\n        manager.add_metadata(self.inheritable_metadata)\n        if tag is not None:\n            manager.add_tags([tag], False)\n        return manager\n[docs]class AsyncRunManager(BaseRunManager):\n    \"\"\"Async Run Manager.\"\"\"\n[docs]    async def on_text(\n        self,\n        text: str,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when text is received.\n        Args:\n            text (str): The received text.\n        Returns:\n            Any: The result of the callback.\n        \"\"\"\n        await ahandle_event(\n            self.handlers,\n            \"on_text\",\n            None,\n            text,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    async def on_retry(\n        self,\n        retry_state: RetryCallState,\n        **kwargs: Any,\n    ) -> None:\n        await ahandle_event(\n            self.handlers,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-14", "text": ") -> None:\n        await ahandle_event(\n            self.handlers,\n            \"on_retry\",\n            \"ignore_retry\",\n            retry_state,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]class AsyncParentRunManager(AsyncRunManager):\n    \"\"\"Async Parent Run Manager.\"\"\"\n[docs]    def get_child(self, tag: Optional[str] = None) -> AsyncCallbackManager:\n        \"\"\"Get a child callback manager.\n        Args:\n            tag (str, optional): The tag for the child callback manager.\n                Defaults to None.\n        Returns:\n            AsyncCallbackManager: The child callback manager.\n        \"\"\"\n        manager = AsyncCallbackManager(handlers=[], parent_run_id=self.run_id)\n        manager.set_handlers(self.inheritable_handlers)\n        manager.add_tags(self.inheritable_tags)\n        manager.add_metadata(self.inheritable_metadata)\n        if tag is not None:\n            manager.add_tags([tag], False)\n        return manager\n[docs]class CallbackManagerForLLMRun(RunManager, LLMManagerMixin):\n    \"\"\"Callback manager for LLM run.\"\"\"\n[docs]    def on_llm_new_token(\n        self,\n        token: str,\n        *,\n        chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when LLM generates a new token.\n        Args:\n            token (str): The new token.\n        \"\"\"\n        handle_event(\n            self.handlers,\n            \"on_llm_new_token\",\n            \"ignore_llm\",\n            token=token,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-15", "text": "run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            chunk=chunk,\n            **kwargs,\n        )\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Run when LLM ends running.\n        Args:\n            response (LLMResult): The LLM result.\n        \"\"\"\n        handle_event(\n            self.handlers,\n            \"on_llm_end\",\n            \"ignore_llm\",\n            response,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    def on_llm_error(\n        self,\n        error: BaseException,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when LLM errors.\n        Args:\n            error (Exception or KeyboardInterrupt): The error.\n        \"\"\"\n        handle_event(\n            self.handlers,\n            \"on_llm_error\",\n            \"ignore_llm\",\n            error,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]class AsyncCallbackManagerForLLMRun(AsyncRunManager, LLMManagerMixin):\n    \"\"\"Async callback manager for LLM run.\"\"\"\n[docs]    async def on_llm_new_token(\n        self,\n        token: str,\n        *,\n        chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when LLM generates a new token.\n        Args:\n            token (str): The new token.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-16", "text": "Args:\n            token (str): The new token.\n        \"\"\"\n        await ahandle_event(\n            self.handlers,\n            \"on_llm_new_token\",\n            \"ignore_llm\",\n            token,\n            chunk=chunk,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    async def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Run when LLM ends running.\n        Args:\n            response (LLMResult): The LLM result.\n        \"\"\"\n        await ahandle_event(\n            self.handlers,\n            \"on_llm_end\",\n            \"ignore_llm\",\n            response,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    async def on_llm_error(\n        self,\n        error: BaseException,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when LLM errors.\n        Args:\n            error (Exception or KeyboardInterrupt): The error.\n        \"\"\"\n        await ahandle_event(\n            self.handlers,\n            \"on_llm_error\",\n            \"ignore_llm\",\n            error,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]class CallbackManagerForChainRun(ParentRunManager, ChainManagerMixin):\n    \"\"\"Callback manager for chain run.\"\"\"\n[docs]    def on_chain_end(self, outputs: Union[Dict[str, Any], Any], **kwargs: Any) -> None:\n        \"\"\"Run when chain ends running.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-17", "text": "\"\"\"Run when chain ends running.\n        Args:\n            outputs (Union[Dict[str, Any], Any]): The outputs of the chain.\n        \"\"\"\n        handle_event(\n            self.handlers,\n            \"on_chain_end\",\n            \"ignore_chain\",\n            outputs,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    def on_chain_error(\n        self,\n        error: BaseException,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when chain errors.\n        Args:\n            error (Exception or KeyboardInterrupt): The error.\n        \"\"\"\n        handle_event(\n            self.handlers,\n            \"on_chain_error\",\n            \"ignore_chain\",\n            error,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:\n        \"\"\"Run when agent action is received.\n        Args:\n            action (AgentAction): The agent action.\n        Returns:\n            Any: The result of the callback.\n        \"\"\"\n        handle_event(\n            self.handlers,\n            \"on_agent_action\",\n            \"ignore_agent\",\n            action,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> Any:\n        \"\"\"Run when agent finish is received.\n        Args:\n            finish (AgentFinish): The agent finish.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-18", "text": "Args:\n            finish (AgentFinish): The agent finish.\n        Returns:\n            Any: The result of the callback.\n        \"\"\"\n        handle_event(\n            self.handlers,\n            \"on_agent_finish\",\n            \"ignore_agent\",\n            finish,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]class AsyncCallbackManagerForChainRun(AsyncParentRunManager, ChainManagerMixin):\n    \"\"\"Async callback manager for chain run.\"\"\"\n[docs]    async def on_chain_end(\n        self, outputs: Union[Dict[str, Any], Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when chain ends running.\n        Args:\n            outputs (Union[Dict[str, Any], Any]): The outputs of the chain.\n        \"\"\"\n        await ahandle_event(\n            self.handlers,\n            \"on_chain_end\",\n            \"ignore_chain\",\n            outputs,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    async def on_chain_error(\n        self,\n        error: BaseException,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when chain errors.\n        Args:\n            error (Exception or KeyboardInterrupt): The error.\n        \"\"\"\n        await ahandle_event(\n            self.handlers,\n            \"on_chain_error\",\n            \"ignore_chain\",\n            error,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    async def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-19", "text": "\"\"\"Run when agent action is received.\n        Args:\n            action (AgentAction): The agent action.\n        Returns:\n            Any: The result of the callback.\n        \"\"\"\n        await ahandle_event(\n            self.handlers,\n            \"on_agent_action\",\n            \"ignore_agent\",\n            action,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    async def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> Any:\n        \"\"\"Run when agent finish is received.\n        Args:\n            finish (AgentFinish): The agent finish.\n        Returns:\n            Any: The result of the callback.\n        \"\"\"\n        await ahandle_event(\n            self.handlers,\n            \"on_agent_finish\",\n            \"ignore_agent\",\n            finish,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]class CallbackManagerForToolRun(ParentRunManager, ToolManagerMixin):\n    \"\"\"Callback manager for tool run.\"\"\"\n[docs]    def on_tool_end(\n        self,\n        output: str,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when tool ends running.\n        Args:\n            output (str): The output of the tool.\n        \"\"\"\n        handle_event(\n            self.handlers,\n            \"on_tool_end\",\n            \"ignore_agent\",\n            output,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    def on_tool_error(\n        self,\n        error: BaseException,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-20", "text": "self,\n        error: BaseException,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when tool errors.\n        Args:\n            error (Exception or KeyboardInterrupt): The error.\n        \"\"\"\n        handle_event(\n            self.handlers,\n            \"on_tool_error\",\n            \"ignore_agent\",\n            error,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]class AsyncCallbackManagerForToolRun(AsyncParentRunManager, ToolManagerMixin):\n    \"\"\"Async callback manager for tool run.\"\"\"\n[docs]    async def on_tool_end(self, output: str, **kwargs: Any) -> None:\n        \"\"\"Run when tool ends running.\n        Args:\n            output (str): The output of the tool.\n        \"\"\"\n        await ahandle_event(\n            self.handlers,\n            \"on_tool_end\",\n            \"ignore_agent\",\n            output,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    async def on_tool_error(\n        self,\n        error: BaseException,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when tool errors.\n        Args:\n            error (Exception or KeyboardInterrupt): The error.\n        \"\"\"\n        await ahandle_event(\n            self.handlers,\n            \"on_tool_error\",\n            \"ignore_agent\",\n            error,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]class CallbackManagerForRetrieverRun(ParentRunManager, RetrieverManagerMixin):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-21", "text": "\"\"\"Callback manager for retriever run.\"\"\"\n[docs]    def on_retriever_end(\n        self,\n        documents: Sequence[Document],\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when retriever ends running.\"\"\"\n        handle_event(\n            self.handlers,\n            \"on_retriever_end\",\n            \"ignore_retriever\",\n            documents,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    def on_retriever_error(\n        self,\n        error: BaseException,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when retriever errors.\"\"\"\n        handle_event(\n            self.handlers,\n            \"on_retriever_error\",\n            \"ignore_retriever\",\n            error,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]class AsyncCallbackManagerForRetrieverRun(\n    AsyncParentRunManager,\n    RetrieverManagerMixin,\n):\n    \"\"\"Async callback manager for retriever run.\"\"\"\n[docs]    async def on_retriever_end(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when retriever ends running.\"\"\"\n        await ahandle_event(\n            self.handlers,\n            \"on_retriever_end\",\n            \"ignore_retriever\",\n            documents,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]    async def on_retriever_error(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-22", "text": ")\n[docs]    async def on_retriever_error(\n        self,\n        error: BaseException,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when retriever errors.\"\"\"\n        await ahandle_event(\n            self.handlers,\n            \"on_retriever_error\",\n            \"ignore_retriever\",\n            error,\n            run_id=self.run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            **kwargs,\n        )\n[docs]class CallbackManager(BaseCallbackManager):\n    \"\"\"Callback manager that handles callbacks from LangChain.\"\"\"\n[docs]    def on_llm_start(\n        self,\n        serialized: Dict[str, Any],\n        prompts: List[str],\n        **kwargs: Any,\n    ) -> List[CallbackManagerForLLMRun]:\n        \"\"\"Run when LLM starts running.\n        Args:\n            serialized (Dict[str, Any]): The serialized LLM.\n            prompts (List[str]): The list of prompts.\n            run_id (UUID, optional): The ID of the run. Defaults to None.\n        Returns:\n            List[CallbackManagerForLLMRun]: A callback manager for each\n                prompt as an LLM run.\n        \"\"\"\n        managers = []\n        for prompt in prompts:\n            run_id_ = uuid.uuid4()\n            handle_event(\n                self.handlers,\n                \"on_llm_start\",\n                \"ignore_llm\",\n                serialized,\n                [prompt],\n                run_id=run_id_,\n                parent_run_id=self.parent_run_id,\n                tags=self.tags,\n                metadata=self.metadata,\n                **kwargs,\n            )\n            managers.append(\n                CallbackManagerForLLMRun(\n                    run_id=run_id_,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-23", "text": "CallbackManagerForLLMRun(\n                    run_id=run_id_,\n                    handlers=self.handlers,\n                    inheritable_handlers=self.inheritable_handlers,\n                    parent_run_id=self.parent_run_id,\n                    tags=self.tags,\n                    inheritable_tags=self.inheritable_tags,\n                    metadata=self.metadata,\n                    inheritable_metadata=self.inheritable_metadata,\n                )\n            )\n        return managers\n[docs]    def on_chat_model_start(\n        self,\n        serialized: Dict[str, Any],\n        messages: List[List[BaseMessage]],\n        **kwargs: Any,\n    ) -> List[CallbackManagerForLLMRun]:\n        \"\"\"Run when LLM starts running.\n        Args:\n            serialized (Dict[str, Any]): The serialized LLM.\n            messages (List[List[BaseMessage]]): The list of messages.\n            run_id (UUID, optional): The ID of the run. Defaults to None.\n        Returns:\n            List[CallbackManagerForLLMRun]: A callback manager for each\n                list of messages as an LLM run.\n        \"\"\"\n        managers = []\n        for message_list in messages:\n            run_id_ = uuid.uuid4()\n            handle_event(\n                self.handlers,\n                \"on_chat_model_start\",\n                \"ignore_chat_model\",\n                serialized,\n                [message_list],\n                run_id=run_id_,\n                parent_run_id=self.parent_run_id,\n                tags=self.tags,\n                metadata=self.metadata,\n                **kwargs,\n            )\n            managers.append(\n                CallbackManagerForLLMRun(\n                    run_id=run_id_,\n                    handlers=self.handlers,\n                    inheritable_handlers=self.inheritable_handlers,\n                    parent_run_id=self.parent_run_id,\n                    tags=self.tags,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-24", "text": "parent_run_id=self.parent_run_id,\n                    tags=self.tags,\n                    inheritable_tags=self.inheritable_tags,\n                    metadata=self.metadata,\n                    inheritable_metadata=self.inheritable_metadata,\n                )\n            )\n        return managers\n[docs]    def on_chain_start(\n        self,\n        serialized: Dict[str, Any],\n        inputs: Union[Dict[str, Any], Any],\n        run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> CallbackManagerForChainRun:\n        \"\"\"Run when chain starts running.\n        Args:\n            serialized (Dict[str, Any]): The serialized chain.\n            inputs (Union[Dict[str, Any], Any]): The inputs to the chain.\n            run_id (UUID, optional): The ID of the run. Defaults to None.\n        Returns:\n            CallbackManagerForChainRun: The callback manager for the chain run.\n        \"\"\"\n        if run_id is None:\n            run_id = uuid.uuid4()\n        handle_event(\n            self.handlers,\n            \"on_chain_start\",\n            \"ignore_chain\",\n            serialized,\n            inputs,\n            run_id=run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            metadata=self.metadata,\n            **kwargs,\n        )\n        return CallbackManagerForChainRun(\n            run_id=run_id,\n            handlers=self.handlers,\n            inheritable_handlers=self.inheritable_handlers,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            inheritable_tags=self.inheritable_tags,\n            metadata=self.metadata,\n            inheritable_metadata=self.inheritable_metadata,\n        )\n[docs]    def on_tool_start(\n        self,\n        serialized: Dict[str, Any],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-25", "text": "self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        run_id: Optional[UUID] = None,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> CallbackManagerForToolRun:\n        \"\"\"Run when tool starts running.\n        Args:\n            serialized (Dict[str, Any]): The serialized tool.\n            input_str (str): The input to the tool.\n            run_id (UUID, optional): The ID of the run. Defaults to None.\n            parent_run_id (UUID, optional): The ID of the parent run. Defaults to None.\n        Returns:\n            CallbackManagerForToolRun: The callback manager for the tool run.\n        \"\"\"\n        if run_id is None:\n            run_id = uuid.uuid4()\n        handle_event(\n            self.handlers,\n            \"on_tool_start\",\n            \"ignore_agent\",\n            serialized,\n            input_str,\n            run_id=run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            metadata=self.metadata,\n            **kwargs,\n        )\n        return CallbackManagerForToolRun(\n            run_id=run_id,\n            handlers=self.handlers,\n            inheritable_handlers=self.inheritable_handlers,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            inheritable_tags=self.inheritable_tags,\n            metadata=self.metadata,\n            inheritable_metadata=self.inheritable_metadata,\n        )\n[docs]    def on_retriever_start(\n        self,\n        serialized: Dict[str, Any],\n        query: str,\n        run_id: Optional[UUID] = None,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-26", "text": "parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> CallbackManagerForRetrieverRun:\n        \"\"\"Run when retriever starts running.\"\"\"\n        if run_id is None:\n            run_id = uuid.uuid4()\n        handle_event(\n            self.handlers,\n            \"on_retriever_start\",\n            \"ignore_retriever\",\n            serialized,\n            query,\n            run_id=run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            metadata=self.metadata,\n            **kwargs,\n        )\n        return CallbackManagerForRetrieverRun(\n            run_id=run_id,\n            handlers=self.handlers,\n            inheritable_handlers=self.inheritable_handlers,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            inheritable_tags=self.inheritable_tags,\n            metadata=self.metadata,\n            inheritable_metadata=self.inheritable_metadata,\n        )\n[docs]    @classmethod\n    def configure(\n        cls,\n        inheritable_callbacks: Callbacks = None,\n        local_callbacks: Callbacks = None,\n        verbose: bool = False,\n        inheritable_tags: Optional[List[str]] = None,\n        local_tags: Optional[List[str]] = None,\n        inheritable_metadata: Optional[Dict[str, Any]] = None,\n        local_metadata: Optional[Dict[str, Any]] = None,\n    ) -> CallbackManager:\n        \"\"\"Configure the callback manager.\n        Args:\n            inheritable_callbacks (Optional[Callbacks], optional): The inheritable\n                callbacks. Defaults to None.\n            local_callbacks (Optional[Callbacks], optional): The local callbacks.\n                Defaults to None.\n            verbose (bool, optional): Whether to enable verbose mode. Defaults to False.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-27", "text": "verbose (bool, optional): Whether to enable verbose mode. Defaults to False.\n            inheritable_tags (Optional[List[str]], optional): The inheritable tags.\n                Defaults to None.\n            local_tags (Optional[List[str]], optional): The local tags.\n                Defaults to None.\n            inheritable_metadata (Optional[Dict[str, Any]], optional): The inheritable\n                metadata. Defaults to None.\n            local_metadata (Optional[Dict[str, Any]], optional): The local metadata.\n                Defaults to None.\n        Returns:\n            CallbackManager: The configured callback manager.\n        \"\"\"\n        return _configure(\n            cls,\n            inheritable_callbacks,\n            local_callbacks,\n            verbose,\n            inheritable_tags,\n            local_tags,\n            inheritable_metadata,\n            local_metadata,\n        )\n[docs]class CallbackManagerForChainGroup(CallbackManager):\n    \"\"\"Callback manager for the chain group.\"\"\"\n[docs]    def __init__(\n        self,\n        handlers: List[BaseCallbackHandler],\n        inheritable_handlers: Optional[List[BaseCallbackHandler]] = None,\n        parent_run_id: Optional[UUID] = None,\n        *,\n        parent_run_manager: CallbackManagerForChainRun,\n        **kwargs: Any,\n    ) -> None:\n        super().__init__(\n            handlers,\n            inheritable_handlers,\n            parent_run_id,\n            **kwargs,\n        )\n        self.parent_run_manager = parent_run_manager\n        self.ended = False\n[docs]    def copy(self) -> CallbackManagerForChainGroup:\n        return self.__class__(\n            handlers=self.handlers,\n            inheritable_handlers=self.inheritable_handlers,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            inheritable_tags=self.inheritable_tags,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-28", "text": "tags=self.tags,\n            inheritable_tags=self.inheritable_tags,\n            metadata=self.metadata,\n            inheritable_metadata=self.inheritable_metadata,\n            parent_run_manager=self.parent_run_manager,\n        )\n[docs]    def on_chain_end(self, outputs: Union[Dict[str, Any], Any], **kwargs: Any) -> None:\n        \"\"\"Run when traced chain group ends.\n        Args:\n            outputs (Union[Dict[str, Any], Any]): The outputs of the chain.\n        \"\"\"\n        self.ended = True\n        return self.parent_run_manager.on_chain_end(outputs, **kwargs)\n[docs]    def on_chain_error(\n        self,\n        error: BaseException,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when chain errors.\n        Args:\n            error (Exception or KeyboardInterrupt): The error.\n        \"\"\"\n        self.ended = True\n        return self.parent_run_manager.on_chain_error(error, **kwargs)\n[docs]class AsyncCallbackManager(BaseCallbackManager):\n    \"\"\"Async callback manager that handles callbacks from LangChain.\"\"\"\n    @property\n    def is_async(self) -> bool:\n        \"\"\"Return whether the handler is async.\"\"\"\n        return True\n[docs]    async def on_llm_start(\n        self,\n        serialized: Dict[str, Any],\n        prompts: List[str],\n        **kwargs: Any,\n    ) -> List[AsyncCallbackManagerForLLMRun]:\n        \"\"\"Run when LLM starts running.\n        Args:\n            serialized (Dict[str, Any]): The serialized LLM.\n            prompts (List[str]): The list of prompts.\n            run_id (UUID, optional): The ID of the run. Defaults to None.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-29", "text": "Returns:\n            List[AsyncCallbackManagerForLLMRun]: The list of async\n                callback managers, one for each LLM Run corresponding\n                to each prompt.\n        \"\"\"\n        tasks = []\n        managers = []\n        for prompt in prompts:\n            run_id_ = uuid.uuid4()\n            tasks.append(\n                ahandle_event(\n                    self.handlers,\n                    \"on_llm_start\",\n                    \"ignore_llm\",\n                    serialized,\n                    [prompt],\n                    run_id=run_id_,\n                    parent_run_id=self.parent_run_id,\n                    tags=self.tags,\n                    metadata=self.metadata,\n                    **kwargs,\n                )\n            )\n            managers.append(\n                AsyncCallbackManagerForLLMRun(\n                    run_id=run_id_,\n                    handlers=self.handlers,\n                    inheritable_handlers=self.inheritable_handlers,\n                    parent_run_id=self.parent_run_id,\n                    tags=self.tags,\n                    inheritable_tags=self.inheritable_tags,\n                    metadata=self.metadata,\n                    inheritable_metadata=self.inheritable_metadata,\n                )\n            )\n        await asyncio.gather(*tasks)\n        return managers\n[docs]    async def on_chat_model_start(\n        self,\n        serialized: Dict[str, Any],\n        messages: List[List[BaseMessage]],\n        **kwargs: Any,\n    ) -> List[AsyncCallbackManagerForLLMRun]:\n        \"\"\"Run when LLM starts running.\n        Args:\n            serialized (Dict[str, Any]): The serialized LLM.\n            messages (List[List[BaseMessage]]): The list of messages.\n            run_id (UUID, optional): The ID of the run. Defaults to None.\n        Returns:\n            List[AsyncCallbackManagerForLLMRun]: The list of", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-30", "text": "Returns:\n            List[AsyncCallbackManagerForLLMRun]: The list of\n                async callback managers, one for each LLM Run\n                corresponding to each inner  message list.\n        \"\"\"\n        tasks = []\n        managers = []\n        for message_list in messages:\n            run_id_ = uuid.uuid4()\n            tasks.append(\n                ahandle_event(\n                    self.handlers,\n                    \"on_chat_model_start\",\n                    \"ignore_chat_model\",\n                    serialized,\n                    [message_list],\n                    run_id=run_id_,\n                    parent_run_id=self.parent_run_id,\n                    tags=self.tags,\n                    metadata=self.metadata,\n                    **kwargs,\n                )\n            )\n            managers.append(\n                AsyncCallbackManagerForLLMRun(\n                    run_id=run_id_,\n                    handlers=self.handlers,\n                    inheritable_handlers=self.inheritable_handlers,\n                    parent_run_id=self.parent_run_id,\n                    tags=self.tags,\n                    inheritable_tags=self.inheritable_tags,\n                    metadata=self.metadata,\n                    inheritable_metadata=self.inheritable_metadata,\n                )\n            )\n        await asyncio.gather(*tasks)\n        return managers\n[docs]    async def on_chain_start(\n        self,\n        serialized: Dict[str, Any],\n        inputs: Union[Dict[str, Any], Any],\n        run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> AsyncCallbackManagerForChainRun:\n        \"\"\"Run when chain starts running.\n        Args:\n            serialized (Dict[str, Any]): The serialized chain.\n            inputs (Union[Dict[str, Any], Any]): The inputs to the chain.\n            run_id (UUID, optional): The ID of the run. Defaults to None.\n        Returns:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-31", "text": "Returns:\n            AsyncCallbackManagerForChainRun: The async callback manager\n                for the chain run.\n        \"\"\"\n        if run_id is None:\n            run_id = uuid.uuid4()\n        await ahandle_event(\n            self.handlers,\n            \"on_chain_start\",\n            \"ignore_chain\",\n            serialized,\n            inputs,\n            run_id=run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            metadata=self.metadata,\n            **kwargs,\n        )\n        return AsyncCallbackManagerForChainRun(\n            run_id=run_id,\n            handlers=self.handlers,\n            inheritable_handlers=self.inheritable_handlers,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            inheritable_tags=self.inheritable_tags,\n            metadata=self.metadata,\n            inheritable_metadata=self.inheritable_metadata,\n        )\n[docs]    async def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        run_id: Optional[UUID] = None,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> AsyncCallbackManagerForToolRun:\n        \"\"\"Run when tool starts running.\n        Args:\n            serialized (Dict[str, Any]): The serialized tool.\n            input_str (str): The input to the tool.\n            run_id (UUID, optional): The ID of the run. Defaults to None.\n            parent_run_id (UUID, optional): The ID of the parent run.\n                Defaults to None.\n        Returns:\n            AsyncCallbackManagerForToolRun: The async callback manager\n                for the tool run.\n        \"\"\"\n        if run_id is None:\n            run_id = uuid.uuid4()\n        await ahandle_event(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-32", "text": "run_id = uuid.uuid4()\n        await ahandle_event(\n            self.handlers,\n            \"on_tool_start\",\n            \"ignore_agent\",\n            serialized,\n            input_str,\n            run_id=run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            metadata=self.metadata,\n            **kwargs,\n        )\n        return AsyncCallbackManagerForToolRun(\n            run_id=run_id,\n            handlers=self.handlers,\n            inheritable_handlers=self.inheritable_handlers,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            inheritable_tags=self.inheritable_tags,\n            metadata=self.metadata,\n            inheritable_metadata=self.inheritable_metadata,\n        )\n[docs]    async def on_retriever_start(\n        self,\n        serialized: Dict[str, Any],\n        query: str,\n        run_id: Optional[UUID] = None,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> AsyncCallbackManagerForRetrieverRun:\n        \"\"\"Run when retriever starts running.\"\"\"\n        if run_id is None:\n            run_id = uuid.uuid4()\n        await ahandle_event(\n            self.handlers,\n            \"on_retriever_start\",\n            \"ignore_retriever\",\n            serialized,\n            query,\n            run_id=run_id,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            metadata=self.metadata,\n            **kwargs,\n        )\n        return AsyncCallbackManagerForRetrieverRun(\n            run_id=run_id,\n            handlers=self.handlers,\n            inheritable_handlers=self.inheritable_handlers,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-33", "text": "parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            inheritable_tags=self.inheritable_tags,\n            metadata=self.metadata,\n            inheritable_metadata=self.inheritable_metadata,\n        )\n[docs]    @classmethod\n    def configure(\n        cls,\n        inheritable_callbacks: Callbacks = None,\n        local_callbacks: Callbacks = None,\n        verbose: bool = False,\n        inheritable_tags: Optional[List[str]] = None,\n        local_tags: Optional[List[str]] = None,\n        inheritable_metadata: Optional[Dict[str, Any]] = None,\n        local_metadata: Optional[Dict[str, Any]] = None,\n    ) -> AsyncCallbackManager:\n        \"\"\"Configure the async callback manager.\n        Args:\n            inheritable_callbacks (Optional[Callbacks], optional): The inheritable\n                callbacks. Defaults to None.\n            local_callbacks (Optional[Callbacks], optional): The local callbacks.\n                Defaults to None.\n            verbose (bool, optional): Whether to enable verbose mode. Defaults to False.\n            inheritable_tags (Optional[List[str]], optional): The inheritable tags.\n                Defaults to None.\n            local_tags (Optional[List[str]], optional): The local tags.\n                Defaults to None.\n            inheritable_metadata (Optional[Dict[str, Any]], optional): The inheritable\n                metadata. Defaults to None.\n            local_metadata (Optional[Dict[str, Any]], optional): The local metadata.\n                Defaults to None.\n        Returns:\n            AsyncCallbackManager: The configured async callback manager.\n        \"\"\"\n        return _configure(\n            cls,\n            inheritable_callbacks,\n            local_callbacks,\n            verbose,\n            inheritable_tags,\n            local_tags,\n            inheritable_metadata,\n            local_metadata,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-34", "text": "local_tags,\n            inheritable_metadata,\n            local_metadata,\n        )\n[docs]class AsyncCallbackManagerForChainGroup(AsyncCallbackManager):\n    \"\"\"Async callback manager for the chain group.\"\"\"\n[docs]    def __init__(\n        self,\n        handlers: List[BaseCallbackHandler],\n        inheritable_handlers: Optional[List[BaseCallbackHandler]] = None,\n        parent_run_id: Optional[UUID] = None,\n        *,\n        parent_run_manager: AsyncCallbackManagerForChainRun,\n        **kwargs: Any,\n    ) -> None:\n        super().__init__(\n            handlers,\n            inheritable_handlers,\n            parent_run_id,\n            **kwargs,\n        )\n        self.parent_run_manager = parent_run_manager\n        self.ended = False\n[docs]    def copy(self) -> AsyncCallbackManagerForChainGroup:\n        return self.__class__(\n            handlers=self.handlers,\n            inheritable_handlers=self.inheritable_handlers,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            inheritable_tags=self.inheritable_tags,\n            metadata=self.metadata,\n            inheritable_metadata=self.inheritable_metadata,\n            parent_run_manager=self.parent_run_manager,\n        )\n[docs]    async def on_chain_end(\n        self, outputs: Union[Dict[str, Any], Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Run when traced chain group ends.\n        Args:\n            outputs (Union[Dict[str, Any], Any]): The outputs of the chain.\n        \"\"\"\n        self.ended = True\n        await self.parent_run_manager.on_chain_end(outputs, **kwargs)\n[docs]    async def on_chain_error(\n        self,\n        error: BaseException,\n        **kwargs: Any,\n    ) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-35", "text": "error: BaseException,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when chain errors.\n        Args:\n            error (Exception or KeyboardInterrupt): The error.\n        \"\"\"\n        self.ended = True\n        await self.parent_run_manager.on_chain_error(error, **kwargs)\nT = TypeVar(\"T\", CallbackManager, AsyncCallbackManager)\n[docs]def env_var_is_set(env_var: str) -> bool:\n    \"\"\"Check if an environment variable is set.\n    Args:\n        env_var (str): The name of the environment variable.\n    Returns:\n        bool: True if the environment variable is set, False otherwise.\n    \"\"\"\n    return env_var in os.environ and os.environ[env_var] not in (\n        \"\",\n        \"0\",\n        \"false\",\n        \"False\",\n    )\ndef _tracing_v2_is_enabled() -> bool:\n    return (\n        env_var_is_set(\"LANGCHAIN_TRACING_V2\")\n        or tracing_v2_callback_var.get() is not None\n        or get_run_tree_context() is not None\n    )\ndef _get_tracer_project() -> str:\n    run_tree = get_run_tree_context()\n    return getattr(\n        run_tree,\n        \"session_name\",\n        getattr(\n            # Note, if people are trying to nest @traceable functions and the\n            # tracing_v2_enabled context manager, this will likely mess up the\n            # tree structure.\n            tracing_v2_callback_var.get(),\n            \"project\",\n            # Have to set this to a string even though it always will return\n            # a string because `get_tracer_project` technically can return\n            # None, but only when a specific argument is supplied.\n            # Therefore, this just tricks the mypy type checker", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-36", "text": "# Therefore, this just tricks the mypy type checker\n            str(ls_utils.get_tracer_project()),\n        ),\n    )\n_configure_hooks: List[\n    Tuple[\n        ContextVar[Optional[BaseCallbackHandler]],\n        bool,\n        Optional[Type[BaseCallbackHandler]],\n        Optional[str],\n    ]\n] = []\nH = TypeVar(\"H\", bound=BaseCallbackHandler, covariant=True)\n[docs]def register_configure_hook(\n    context_var: ContextVar[Optional[Any]],\n    inheritable: bool,\n    handle_class: Optional[Type[BaseCallbackHandler]] = None,\n    env_var: Optional[str] = None,\n) -> None:\n    if env_var is not None and handle_class is None:\n        raise ValueError(\n            \"If env_var is set, handle_class must also be set to a non-None value.\"\n        )\n    _configure_hooks.append(\n        (\n            # the typings of ContextVar do not have the generic arg set as covariant\n            # so we have to cast it\n            cast(ContextVar[Optional[BaseCallbackHandler]], context_var),\n            inheritable,\n            handle_class,\n            env_var,\n        )\n    )\nregister_configure_hook(run_collector_var, False)\ndef _configure(\n    callback_manager_cls: Type[T],\n    inheritable_callbacks: Callbacks = None,\n    local_callbacks: Callbacks = None,\n    verbose: bool = False,\n    inheritable_tags: Optional[List[str]] = None,\n    local_tags: Optional[List[str]] = None,\n    inheritable_metadata: Optional[Dict[str, Any]] = None,\n    local_metadata: Optional[Dict[str, Any]] = None,\n) -> T:\n    \"\"\"Configure the callback manager.\n    Args:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-37", "text": ") -> T:\n    \"\"\"Configure the callback manager.\n    Args:\n        callback_manager_cls (Type[T]): The callback manager class.\n        inheritable_callbacks (Optional[Callbacks], optional): The inheritable\n            callbacks. Defaults to None.\n        local_callbacks (Optional[Callbacks], optional): The local callbacks.\n            Defaults to None.\n        verbose (bool, optional): Whether to enable verbose mode. Defaults to False.\n        inheritable_tags (Optional[List[str]], optional): The inheritable tags.\n            Defaults to None.\n        local_tags (Optional[List[str]], optional): The local tags. Defaults to None.\n        inheritable_metadata (Optional[Dict[str, Any]], optional): The inheritable\n            metadata. Defaults to None.\n        local_metadata (Optional[Dict[str, Any]], optional): The local metadata.\n            Defaults to None.\n    Returns:\n        T: The configured callback manager.\n    \"\"\"\n    run_tree = get_run_tree_context()\n    parent_run_id = None if run_tree is None else getattr(run_tree, \"id\")\n    callback_manager = callback_manager_cls(handlers=[], parent_run_id=parent_run_id)\n    if inheritable_callbacks or local_callbacks:\n        if isinstance(inheritable_callbacks, list) or inheritable_callbacks is None:\n            inheritable_callbacks_ = inheritable_callbacks or []\n            callback_manager = callback_manager_cls(\n                handlers=inheritable_callbacks_.copy(),\n                inheritable_handlers=inheritable_callbacks_.copy(),\n                parent_run_id=parent_run_id,\n            )\n        else:\n            callback_manager = callback_manager_cls(\n                handlers=inheritable_callbacks.handlers.copy(),\n                inheritable_handlers=inheritable_callbacks.inheritable_handlers.copy(),\n                parent_run_id=inheritable_callbacks.parent_run_id,\n                tags=inheritable_callbacks.tags.copy(),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-38", "text": "tags=inheritable_callbacks.tags.copy(),\n                inheritable_tags=inheritable_callbacks.inheritable_tags.copy(),\n                metadata=inheritable_callbacks.metadata.copy(),\n                inheritable_metadata=inheritable_callbacks.inheritable_metadata.copy(),\n            )\n        local_handlers_ = (\n            local_callbacks\n            if isinstance(local_callbacks, list)\n            else (local_callbacks.handlers if local_callbacks else [])\n        )\n        for handler in local_handlers_:\n            callback_manager.add_handler(handler, False)\n    if inheritable_tags or local_tags:\n        callback_manager.add_tags(inheritable_tags or [])\n        callback_manager.add_tags(local_tags or [], False)\n    if inheritable_metadata or local_metadata:\n        callback_manager.add_metadata(inheritable_metadata or {})\n        callback_manager.add_metadata(local_metadata or {}, False)\n    tracer = tracing_callback_var.get()\n    tracing_enabled_ = (\n        env_var_is_set(\"LANGCHAIN_TRACING\")\n        or tracer is not None\n        or env_var_is_set(\"LANGCHAIN_HANDLER\")\n    )\n    tracer_v2 = tracing_v2_callback_var.get()\n    tracing_v2_enabled_ = _tracing_v2_is_enabled()\n    tracer_project = _get_tracer_project()\n    debug = _get_debug()\n    if verbose or debug or tracing_enabled_ or tracing_v2_enabled_:\n        if verbose and not any(\n            isinstance(handler, StdOutCallbackHandler)\n            for handler in callback_manager.handlers\n        ):\n            if debug:\n                pass\n            else:\n                callback_manager.add_handler(StdOutCallbackHandler(), False)\n        if debug and not any(\n            isinstance(handler, ConsoleCallbackHandler)\n            for handler in callback_manager.handlers\n        ):\n            callback_manager.add_handler(ConsoleCallbackHandler(), True)\n        if tracing_enabled_ and not any(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "8cf9574238da-39", "text": "if tracing_enabled_ and not any(\n            isinstance(handler, LangChainTracerV1)\n            for handler in callback_manager.handlers\n        ):\n            if tracer:\n                callback_manager.add_handler(tracer, True)\n            else:\n                handler = LangChainTracerV1()\n                handler.load_session(tracer_project)\n                callback_manager.add_handler(handler, True)\n        if tracing_v2_enabled_ and not any(\n            isinstance(handler, LangChainTracer)\n            for handler in callback_manager.handlers\n        ):\n            if tracer_v2:\n                callback_manager.add_handler(tracer_v2, True)\n            else:\n                try:\n                    handler = LangChainTracer(project_name=tracer_project)\n                    callback_manager.add_handler(handler, True)\n                except Exception as e:\n                    logger.warning(\n                        \"Unable to load requested LangChainTracer.\"\n                        \" To disable this warning,\"\n                        \" unset the LANGCHAIN_TRACING_V2 environment variables.\",\n                        e,\n                    )\n    for var, inheritable, handler_class, env_var in _configure_hooks:\n        create_one = (\n            env_var is not None\n            and env_var_is_set(env_var)\n            and handler_class is not None\n        )\n        if var.get() is not None or create_one:\n            var_handler = var.get() or cast(Type[BaseCallbackHandler], handler_class)()\n            if handler_class is None:\n                if not any(\n                    handler is var_handler  # direct pointer comparison\n                    for handler in callback_manager.handlers\n                ):\n                    callback_manager.add_handler(var_handler, inheritable)\n            else:\n                if not any(\n                    isinstance(handler, handler_class)\n                    for handler in callback_manager.handlers\n                ):\n                    callback_manager.add_handler(var_handler, inheritable)\n    return callback_manager", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html"}
{"id": "f40b4e1ca980-0", "text": "Source code for langchain.schema.callbacks.stdout\n\"\"\"Callback Handler that prints to std out.\"\"\"\nfrom typing import Any, Dict, List, Optional\nfrom langchain.schema import AgentAction, AgentFinish, LLMResult\nfrom langchain.schema.callbacks.base import BaseCallbackHandler\nfrom langchain.utils.input import print_text\n[docs]class StdOutCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback Handler that prints to std out.\"\"\"\n[docs]    def __init__(self, color: Optional[str] = None) -> None:\n        \"\"\"Initialize callback handler.\"\"\"\n        self.color = color\n[docs]    def on_llm_start(\n        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any\n    ) -> None:\n        \"\"\"Print out the prompts.\"\"\"\n        pass\n[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Do nothing.\"\"\"\n        pass\n[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:\n        \"\"\"Do nothing.\"\"\"\n        pass\n[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing.\"\"\"\n        pass\n[docs]    def on_chain_start(\n        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Print out that we are entering a chain.\"\"\"\n        class_name = serialized.get(\"name\", serialized.get(\"id\", [\"<unknown>\"])[-1])\n        print(f\"\\n\\n\\033[1m> Entering new {class_name} chain...\\033[0m\")\n[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/stdout.html"}
{"id": "f40b4e1ca980-1", "text": "\"\"\"Print out that we finished a chain.\"\"\"\n        print(\"\\n\\033[1m> Finished chain.\\033[0m\")\n[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing.\"\"\"\n        pass\n[docs]    def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Do nothing.\"\"\"\n        pass\n[docs]    def on_agent_action(\n        self, action: AgentAction, color: Optional[str] = None, **kwargs: Any\n    ) -> Any:\n        \"\"\"Run on agent action.\"\"\"\n        print_text(action.log, color=color or self.color)\n[docs]    def on_tool_end(\n        self,\n        output: str,\n        color: Optional[str] = None,\n        observation_prefix: Optional[str] = None,\n        llm_prefix: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"If not the final action, print out observation.\"\"\"\n        if observation_prefix is not None:\n            print_text(f\"\\n{observation_prefix}\")\n        print_text(output, color=color or self.color)\n        if llm_prefix is not None:\n            print_text(f\"\\n{llm_prefix}\")\n[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:\n        \"\"\"Do nothing.\"\"\"\n        pass\n[docs]    def on_text(\n        self,\n        text: str,\n        color: Optional[str] = None,\n        end: str = \"\",\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when agent ends.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/stdout.html"}
{"id": "f40b4e1ca980-2", "text": ") -> None:\n        \"\"\"Run when agent ends.\"\"\"\n        print_text(text, color=color or self.color, end=end)\n[docs]    def on_agent_finish(\n        self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any\n    ) -> None:\n        \"\"\"Run on agent end.\"\"\"\n        print_text(finish.log, color=color or self.color, end=\"\\n\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/stdout.html"}
{"id": "36fe02779302-0", "text": "Source code for langchain.schema.callbacks.base\n\"\"\"Base callback handler that can be used to handle callbacks in langchain.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Optional, Sequence, TypeVar, Union\nfrom uuid import UUID\nfrom tenacity import RetryCallState\nfrom langchain.schema.agent import AgentAction, AgentFinish\nfrom langchain.schema.document import Document\nfrom langchain.schema.messages import BaseMessage\nfrom langchain.schema.output import ChatGenerationChunk, GenerationChunk, LLMResult\n[docs]class RetrieverManagerMixin:\n    \"\"\"Mixin for Retriever callbacks.\"\"\"\n[docs]    def on_retriever_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when Retriever errors.\"\"\"\n[docs]    def on_retriever_end(\n        self,\n        documents: Sequence[Document],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when Retriever ends running.\"\"\"\n[docs]class LLMManagerMixin:\n    \"\"\"Mixin for LLM callbacks.\"\"\"\n[docs]    def on_llm_new_token(\n        self,\n        token: str,\n        *,\n        chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run on new LLM token. Only available when streaming is enabled.\n        Args:\n            token (str): The new token.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html"}
{"id": "36fe02779302-1", "text": "Args:\n            token (str): The new token.\n            chunk (GenerationChunk | ChatGenerationChunk): The new generated chunk,\n            containing content and other information.\n        \"\"\"\n[docs]    def on_llm_end(\n        self,\n        response: LLMResult,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when LLM ends running.\"\"\"\n[docs]    def on_llm_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when LLM errors.\"\"\"\n[docs]class ChainManagerMixin:\n    \"\"\"Mixin for chain callbacks.\"\"\"\n[docs]    def on_chain_end(\n        self,\n        outputs: Dict[str, Any],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when chain ends running.\"\"\"\n[docs]    def on_chain_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when chain errors.\"\"\"\n[docs]    def on_agent_action(\n        self,\n        action: AgentAction,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run on agent action.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html"}
{"id": "36fe02779302-2", "text": ") -> Any:\n        \"\"\"Run on agent action.\"\"\"\n[docs]    def on_agent_finish(\n        self,\n        finish: AgentFinish,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run on agent end.\"\"\"\n[docs]class ToolManagerMixin:\n    \"\"\"Mixin for tool callbacks.\"\"\"\n[docs]    def on_tool_end(\n        self,\n        output: str,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when tool ends running.\"\"\"\n[docs]    def on_tool_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when tool errors.\"\"\"\n[docs]class CallbackManagerMixin:\n    \"\"\"Mixin for callback manager.\"\"\"\n[docs]    def on_llm_start(\n        self,\n        serialized: Dict[str, Any],\n        prompts: List[str],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when LLM starts running.\"\"\"\n[docs]    def on_chat_model_start(\n        self,\n        serialized: Dict[str, Any],\n        messages: List[List[BaseMessage]],\n        *,\n        run_id: UUID,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html"}
{"id": "36fe02779302-3", "text": "messages: List[List[BaseMessage]],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when a chat model starts running.\"\"\"\n        raise NotImplementedError(\n            f\"{self.__class__.__name__} does not implement `on_chat_model_start`\"\n        )\n[docs]    def on_retriever_start(\n        self,\n        serialized: Dict[str, Any],\n        query: str,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when Retriever starts running.\"\"\"\n[docs]    def on_chain_start(\n        self,\n        serialized: Dict[str, Any],\n        inputs: Dict[str, Any],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when chain starts running.\"\"\"\n[docs]    def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html"}
{"id": "36fe02779302-4", "text": "metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when tool starts running.\"\"\"\n[docs]class RunManagerMixin:\n    \"\"\"Mixin for run manager.\"\"\"\n[docs]    def on_text(\n        self,\n        text: str,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run on arbitrary text.\"\"\"\n[docs]    def on_retry(\n        self,\n        retry_state: RetryCallState,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run on a retry event.\"\"\"\n[docs]class BaseCallbackHandler(\n    LLMManagerMixin,\n    ChainManagerMixin,\n    ToolManagerMixin,\n    RetrieverManagerMixin,\n    CallbackManagerMixin,\n    RunManagerMixin,\n):\n    \"\"\"Base callback handler that handles callbacks from LangChain.\"\"\"\n    raise_error: bool = False\n    run_inline: bool = False\n    @property\n    def ignore_llm(self) -> bool:\n        \"\"\"Whether to ignore LLM callbacks.\"\"\"\n        return False\n    @property\n    def ignore_retry(self) -> bool:\n        \"\"\"Whether to ignore retry callbacks.\"\"\"\n        return False\n    @property\n    def ignore_chain(self) -> bool:\n        \"\"\"Whether to ignore chain callbacks.\"\"\"\n        return False\n    @property\n    def ignore_agent(self) -> bool:\n        \"\"\"Whether to ignore agent callbacks.\"\"\"\n        return False\n    @property\n    def ignore_retriever(self) -> bool:\n        \"\"\"Whether to ignore retriever callbacks.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html"}
{"id": "36fe02779302-5", "text": "\"\"\"Whether to ignore retriever callbacks.\"\"\"\n        return False\n    @property\n    def ignore_chat_model(self) -> bool:\n        \"\"\"Whether to ignore chat model callbacks.\"\"\"\n        return False\n[docs]class AsyncCallbackHandler(BaseCallbackHandler):\n    \"\"\"Async callback handler that handles callbacks from LangChain.\"\"\"\n[docs]    async def on_llm_start(\n        self,\n        serialized: Dict[str, Any],\n        prompts: List[str],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when LLM starts running.\"\"\"\n[docs]    async def on_chat_model_start(\n        self,\n        serialized: Dict[str, Any],\n        messages: List[List[BaseMessage]],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run when a chat model starts running.\"\"\"\n        raise NotImplementedError(\n            f\"{self.__class__.__name__} does not implement `on_chat_model_start`\"\n        )\n[docs]    async def on_llm_new_token(\n        self,\n        token: str,\n        *,\n        chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html"}
{"id": "36fe02779302-6", "text": "**kwargs: Any,\n    ) -> None:\n        \"\"\"Run on new LLM token. Only available when streaming is enabled.\"\"\"\n[docs]    async def on_llm_end(\n        self,\n        response: LLMResult,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when LLM ends running.\"\"\"\n[docs]    async def on_llm_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when LLM errors.\"\"\"\n[docs]    async def on_chain_start(\n        self,\n        serialized: Dict[str, Any],\n        inputs: Dict[str, Any],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when chain starts running.\"\"\"\n[docs]    async def on_chain_end(\n        self,\n        outputs: Dict[str, Any],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when chain ends running.\"\"\"\n[docs]    async def on_chain_error(\n        self,\n        error: BaseException,\n        *,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html"}
{"id": "36fe02779302-7", "text": "self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when chain errors.\"\"\"\n[docs]    async def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when tool starts running.\"\"\"\n[docs]    async def on_tool_end(\n        self,\n        output: str,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when tool ends running.\"\"\"\n[docs]    async def on_tool_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run when tool errors.\"\"\"\n[docs]    async def on_text(\n        self,\n        text: str,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run on arbitrary text.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html"}
{"id": "36fe02779302-8", "text": ") -> None:\n        \"\"\"Run on arbitrary text.\"\"\"\n[docs]    async def on_retry(\n        self,\n        retry_state: RetryCallState,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Any:\n        \"\"\"Run on a retry event.\"\"\"\n[docs]    async def on_agent_action(\n        self,\n        action: AgentAction,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run on agent action.\"\"\"\n[docs]    async def on_agent_finish(\n        self,\n        finish: AgentFinish,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run on agent end.\"\"\"\n[docs]    async def on_retriever_start(\n        self,\n        serialized: Dict[str, Any],\n        query: str,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run on retriever start.\"\"\"\n[docs]    async def on_retriever_end(\n        self,\n        documents: Sequence[Document],\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html"}
{"id": "36fe02779302-9", "text": "tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run on retriever end.\"\"\"\n[docs]    async def on_retriever_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Run on retriever error.\"\"\"\nT = TypeVar(\"T\", bound=\"BaseCallbackManager\")\n[docs]class BaseCallbackManager(CallbackManagerMixin):\n    \"\"\"Base callback manager that handles callbacks from LangChain.\"\"\"\n[docs]    def __init__(\n        self,\n        handlers: List[BaseCallbackHandler],\n        inheritable_handlers: Optional[List[BaseCallbackHandler]] = None,\n        parent_run_id: Optional[UUID] = None,\n        *,\n        tags: Optional[List[str]] = None,\n        inheritable_tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        inheritable_metadata: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        \"\"\"Initialize callback manager.\"\"\"\n        self.handlers: List[BaseCallbackHandler] = handlers\n        self.inheritable_handlers: List[BaseCallbackHandler] = (\n            inheritable_handlers or []\n        )\n        self.parent_run_id: Optional[UUID] = parent_run_id\n        self.tags = tags or []\n        self.inheritable_tags = inheritable_tags or []\n        self.metadata = metadata or {}\n        self.inheritable_metadata = inheritable_metadata or {}\n[docs]    def copy(self: T) -> T:\n        \"\"\"Copy the callback manager.\"\"\"\n        return self.__class__(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html"}
{"id": "36fe02779302-10", "text": "\"\"\"Copy the callback manager.\"\"\"\n        return self.__class__(\n            handlers=self.handlers,\n            inheritable_handlers=self.inheritable_handlers,\n            parent_run_id=self.parent_run_id,\n            tags=self.tags,\n            inheritable_tags=self.inheritable_tags,\n            metadata=self.metadata,\n            inheritable_metadata=self.inheritable_metadata,\n        )\n    @property\n    def is_async(self) -> bool:\n        \"\"\"Whether the callback manager is async.\"\"\"\n        return False\n[docs]    def add_handler(self, handler: BaseCallbackHandler, inherit: bool = True) -> None:\n        \"\"\"Add a handler to the callback manager.\"\"\"\n        if handler not in self.handlers:\n            self.handlers.append(handler)\n        if inherit and handler not in self.inheritable_handlers:\n            self.inheritable_handlers.append(handler)\n[docs]    def remove_handler(self, handler: BaseCallbackHandler) -> None:\n        \"\"\"Remove a handler from the callback manager.\"\"\"\n        self.handlers.remove(handler)\n        self.inheritable_handlers.remove(handler)\n[docs]    def set_handlers(\n        self, handlers: List[BaseCallbackHandler], inherit: bool = True\n    ) -> None:\n        \"\"\"Set handlers as the only handlers on the callback manager.\"\"\"\n        self.handlers = []\n        self.inheritable_handlers = []\n        for handler in handlers:\n            self.add_handler(handler, inherit=inherit)\n[docs]    def set_handler(self, handler: BaseCallbackHandler, inherit: bool = True) -> None:\n        \"\"\"Set handler as the only handler on the callback manager.\"\"\"\n        self.set_handlers([handler], inherit=inherit)\n[docs]    def add_tags(self, tags: List[str], inherit: bool = True) -> None:\n        for tag in tags:\n            if tag in self.tags:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html"}
{"id": "36fe02779302-11", "text": "for tag in tags:\n            if tag in self.tags:\n                self.remove_tags([tag])\n        self.tags.extend(tags)\n        if inherit:\n            self.inheritable_tags.extend(tags)\n[docs]    def remove_tags(self, tags: List[str]) -> None:\n        for tag in tags:\n            self.tags.remove(tag)\n            self.inheritable_tags.remove(tag)\n[docs]    def add_metadata(self, metadata: Dict[str, Any], inherit: bool = True) -> None:\n        self.metadata.update(metadata)\n        if inherit:\n            self.inheritable_metadata.update(metadata)\n[docs]    def remove_metadata(self, keys: List[str]) -> None:\n        for key in keys:\n            self.metadata.pop(key)\n            self.inheritable_metadata.pop(key)\nCallbacks = Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html"}
{"id": "8f80e23d99e8-0", "text": "Source code for langchain.schema.callbacks.tracers.stdout\nimport json\nfrom typing import Any, Callable, List\nfrom langchain.schema.callbacks.tracers.base import BaseTracer\nfrom langchain.schema.callbacks.tracers.schemas import Run\nfrom langchain.utils.input import get_bolded_text, get_colored_text\n[docs]def try_json_stringify(obj: Any, fallback: str) -> str:\n    \"\"\"\n    Try to stringify an object to JSON.\n    Args:\n        obj: Object to stringify.\n        fallback: Fallback string to return if the object cannot be stringified.\n    Returns:\n        A JSON string if the object can be stringified, otherwise the fallback string.\n    \"\"\"\n    try:\n        return json.dumps(obj, indent=2, ensure_ascii=False)\n    except Exception:\n        return fallback\n[docs]def elapsed(run: Any) -> str:\n    \"\"\"Get the elapsed time of a run.\n    Args:\n        run: any object with a start_time and end_time attribute.\n    Returns:\n        A string with the elapsed time in seconds or\n            milliseconds if time is less than a second.\n    \"\"\"\n    elapsed_time = run.end_time - run.start_time\n    milliseconds = elapsed_time.total_seconds() * 1000\n    if milliseconds < 1000:\n        return f\"{milliseconds:.0f}ms\"\n    return f\"{(milliseconds / 1000):.2f}s\"\n[docs]class FunctionCallbackHandler(BaseTracer):\n    \"\"\"Tracer that calls a function with a single str parameter.\"\"\"\n    name: str = \"function_callback_handler\"\n[docs]    def __init__(self, function: Callable[[str], None], **kwargs: Any) -> None:\n        super().__init__(**kwargs)\n        self.function_callback = function", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/stdout.html"}
{"id": "8f80e23d99e8-1", "text": "super().__init__(**kwargs)\n        self.function_callback = function\n    def _persist_run(self, run: Run) -> None:\n        pass\n[docs]    def get_parents(self, run: Run) -> List[Run]:\n        parents = []\n        current_run = run\n        while current_run.parent_run_id:\n            parent = self.run_map.get(str(current_run.parent_run_id))\n            if parent:\n                parents.append(parent)\n                current_run = parent\n            else:\n                break\n        return parents\n[docs]    def get_breadcrumbs(self, run: Run) -> str:\n        parents = self.get_parents(run)[::-1]\n        string = \" > \".join(\n            f\"{parent.execution_order}:{parent.run_type}:{parent.name}\"\n            if i != len(parents) - 1\n            else f\"{parent.execution_order}:{parent.run_type}:{parent.name}\"\n            for i, parent in enumerate(parents + [run])\n        )\n        return string\n    # logging methods\n    def _on_chain_start(self, run: Run) -> None:\n        crumbs = self.get_breadcrumbs(run)\n        run_type = run.run_type.capitalize()\n        self.function_callback(\n            f\"{get_colored_text('[chain/start]', color='green')} \"\n            + get_bolded_text(f\"[{crumbs}] Entering {run_type} run with input:\\n\")\n            + f\"{try_json_stringify(run.inputs, '[inputs]')}\"\n        )\n    def _on_chain_end(self, run: Run) -> None:\n        crumbs = self.get_breadcrumbs(run)\n        run_type = run.run_type.capitalize()\n        self.function_callback(\n            f\"{get_colored_text('[chain/end]', color='blue')} \"\n            + get_bolded_text(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/stdout.html"}
{"id": "8f80e23d99e8-2", "text": "+ get_bolded_text(\n                f\"[{crumbs}] [{elapsed(run)}] Exiting {run_type} run with output:\\n\"\n            )\n            + f\"{try_json_stringify(run.outputs, '[outputs]')}\"\n        )\n    def _on_chain_error(self, run: Run) -> None:\n        crumbs = self.get_breadcrumbs(run)\n        run_type = run.run_type.capitalize()\n        self.function_callback(\n            f\"{get_colored_text('[chain/error]', color='red')} \"\n            + get_bolded_text(\n                f\"[{crumbs}] [{elapsed(run)}] {run_type} run errored with error:\\n\"\n            )\n            + f\"{try_json_stringify(run.error, '[error]')}\"\n        )\n    def _on_llm_start(self, run: Run) -> None:\n        crumbs = self.get_breadcrumbs(run)\n        inputs = (\n            {\"prompts\": [p.strip() for p in run.inputs[\"prompts\"]]}\n            if \"prompts\" in run.inputs\n            else run.inputs\n        )\n        self.function_callback(\n            f\"{get_colored_text('[llm/start]', color='green')} \"\n            + get_bolded_text(f\"[{crumbs}] Entering LLM run with input:\\n\")\n            + f\"{try_json_stringify(inputs, '[inputs]')}\"\n        )\n    def _on_llm_end(self, run: Run) -> None:\n        crumbs = self.get_breadcrumbs(run)\n        self.function_callback(\n            f\"{get_colored_text('[llm/end]', color='blue')} \"\n            + get_bolded_text(\n                f\"[{crumbs}] [{elapsed(run)}] Exiting LLM run with output:\\n\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/stdout.html"}
{"id": "8f80e23d99e8-3", "text": ")\n            + f\"{try_json_stringify(run.outputs, '[response]')}\"\n        )\n    def _on_llm_error(self, run: Run) -> None:\n        crumbs = self.get_breadcrumbs(run)\n        self.function_callback(\n            f\"{get_colored_text('[llm/error]', color='red')} \"\n            + get_bolded_text(\n                f\"[{crumbs}] [{elapsed(run)}] LLM run errored with error:\\n\"\n            )\n            + f\"{try_json_stringify(run.error, '[error]')}\"\n        )\n    def _on_tool_start(self, run: Run) -> None:\n        crumbs = self.get_breadcrumbs(run)\n        self.function_callback(\n            f'{get_colored_text(\"[tool/start]\", color=\"green\")} '\n            + get_bolded_text(f\"[{crumbs}] Entering Tool run with input:\\n\")\n            + f'\"{run.inputs[\"input\"].strip()}\"'\n        )\n    def _on_tool_end(self, run: Run) -> None:\n        crumbs = self.get_breadcrumbs(run)\n        if run.outputs:\n            self.function_callback(\n                f'{get_colored_text(\"[tool/end]\", color=\"blue\")} '\n                + get_bolded_text(\n                    f\"[{crumbs}] [{elapsed(run)}] Exiting Tool run with output:\\n\"\n                )\n                + f'\"{run.outputs[\"output\"].strip()}\"'\n            )\n    def _on_tool_error(self, run: Run) -> None:\n        crumbs = self.get_breadcrumbs(run)\n        self.function_callback(\n            f\"{get_colored_text('[tool/error]', color='red')} \"\n            + get_bolded_text(f\"[{crumbs}] [{elapsed(run)}] \")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/stdout.html"}
{"id": "8f80e23d99e8-4", "text": "+ get_bolded_text(f\"[{crumbs}] [{elapsed(run)}] \")\n            + f\"Tool run errored with error:\\n\"\n            f\"{run.error}\"\n        )\n[docs]class ConsoleCallbackHandler(FunctionCallbackHandler):\n    \"\"\"Tracer that prints to the console.\"\"\"\n    name: str = \"console_callback_handler\"\n[docs]    def __init__(self, **kwargs: Any) -> None:\n        super().__init__(function=print, **kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/stdout.html"}
{"id": "1ff71c24663c-0", "text": "Source code for langchain.schema.callbacks.tracers.root_listeners\nfrom typing import Callable, Optional, Union\nfrom uuid import UUID\nfrom langchain.schema.callbacks.tracers.base import BaseTracer\nfrom langchain.schema.callbacks.tracers.schemas import Run\nfrom langchain.schema.runnable.config import (\n    RunnableConfig,\n    call_func_with_variable_args,\n)\nListener = Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]\n[docs]class RootListenersTracer(BaseTracer):\n[docs]    def __init__(\n        self,\n        *,\n        config: RunnableConfig,\n        on_start: Optional[Listener],\n        on_end: Optional[Listener],\n        on_error: Optional[Listener],\n    ) -> None:\n        super().__init__()\n        self.config = config\n        self._arg_on_start = on_start\n        self._arg_on_end = on_end\n        self._arg_on_error = on_error\n        self.root_id: Optional[UUID] = None\n    def _persist_run(self, run: Run) -> None:\n        # This is a legacy method only called once for an entire run tree\n        # therefore not useful here\n        pass\n    def _on_run_create(self, run: Run) -> None:\n        if self.root_id is not None:\n            return\n        self.root_id = run.id\n        if self._arg_on_start is not None:\n            call_func_with_variable_args(self._arg_on_start, run, self.config)\n    def _on_run_update(self, run: Run) -> None:\n        if run.id != self.root_id:\n            return\n        if run.error is None:\n            if self._arg_on_end is not None:\n                call_func_with_variable_args(self._arg_on_end, run, self.config)\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/root_listeners.html"}
{"id": "1ff71c24663c-1", "text": "else:\n            if self._arg_on_error is not None:\n                call_func_with_variable_args(self._arg_on_error, run, self.config)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/root_listeners.html"}
{"id": "2e9c3311c106-0", "text": "Source code for langchain.schema.callbacks.tracers.log_stream\nfrom __future__ import annotations\nimport math\nimport threading\nfrom collections import defaultdict\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Dict,\n    List,\n    Optional,\n    Sequence,\n    TypedDict,\n    Union,\n)\nfrom uuid import UUID\nimport jsonpatch\nfrom anyio import create_memory_object_stream\nfrom langchain.load.load import load\nfrom langchain.schema.callbacks.tracers.base import BaseTracer\nfrom langchain.schema.callbacks.tracers.schemas import Run\nfrom langchain.schema.output import ChatGenerationChunk, GenerationChunk\n[docs]class LogEntry(TypedDict):\n    \"\"\"A single entry in the run log.\"\"\"\n    id: str\n    \"\"\"ID of the sub-run.\"\"\"\n    name: str\n    \"\"\"Name of the object being run.\"\"\"\n    type: str\n    \"\"\"Type of the object being run, eg. prompt, chain, llm, etc.\"\"\"\n    tags: List[str]\n    \"\"\"List of tags for the run.\"\"\"\n    metadata: Dict[str, Any]\n    \"\"\"Key-value pairs of metadata for the run.\"\"\"\n    start_time: str\n    \"\"\"ISO-8601 timestamp of when the run started.\"\"\"\n    streamed_output_str: List[str]\n    \"\"\"List of LLM tokens streamed by this run, if applicable.\"\"\"\n    final_output: Optional[Any]\n    \"\"\"Final output of this run.\n    Only available after the run has finished successfully.\"\"\"\n    end_time: Optional[str]\n    \"\"\"ISO-8601 timestamp of when the run ended.\n    Only available after the run has finished.\"\"\"\n[docs]class RunState(TypedDict):\n    \"\"\"State of the run.\"\"\"\n    id: str\n    \"\"\"ID of the run.\"\"\"\n    streamed_output: List[Any]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html"}
{"id": "2e9c3311c106-1", "text": "\"\"\"ID of the run.\"\"\"\n    streamed_output: List[Any]\n    \"\"\"List of output chunks streamed by Runnable.stream()\"\"\"\n    final_output: Optional[Any]\n    \"\"\"Final output of the run, usually the result of aggregating (`+`) streamed_output.\n    Only available after the run has finished successfully.\"\"\"\n    logs: Dict[str, LogEntry]\n    \"\"\"Map of run names to sub-runs. If filters were supplied, this list will\n    contain only the runs that matched the filters.\"\"\"\n[docs]class RunLogPatch:\n    \"\"\"A patch to the run log.\"\"\"\n    ops: List[Dict[str, Any]]\n    \"\"\"List of jsonpatch operations, which describe how to create the run state\n    from an empty dict. This is the minimal representation of the log, designed to\n    be serialized as JSON and sent over the wire to reconstruct the log on the other\n    side. Reconstruction of the state can be done with any jsonpatch-compliant library,\n    see https://jsonpatch.com for more information.\"\"\"\n[docs]    def __init__(self, *ops: Dict[str, Any]) -> None:\n        self.ops = list(ops)\n    def __add__(self, other: Union[RunLogPatch, Any]) -> RunLog:\n        if type(other) == RunLogPatch:\n            ops = self.ops + other.ops\n            state = jsonpatch.apply_patch(None, ops)\n            return RunLog(*ops, state=state)\n        raise TypeError(\n            f\"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'\"\n        )\n    def __repr__(self) -> str:\n        from pprint import pformat\n        # 1:-1 to get rid of the [] around the list", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html"}
{"id": "2e9c3311c106-2", "text": "# 1:-1 to get rid of the [] around the list\n        return f\"RunLogPatch({pformat(self.ops)[1:-1]})\"\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, RunLogPatch) and self.ops == other.ops\n[docs]class RunLog(RunLogPatch):\n    \"\"\"A run log.\"\"\"\n    state: RunState\n    \"\"\"Current state of the log, obtained from applying all ops in sequence.\"\"\"\n[docs]    def __init__(self, *ops: Dict[str, Any], state: RunState) -> None:\n        super().__init__(*ops)\n        self.state = state\n    def __add__(self, other: Union[RunLogPatch, Any]) -> RunLog:\n        if type(other) == RunLogPatch:\n            ops = self.ops + other.ops\n            state = jsonpatch.apply_patch(self.state, other.ops)\n            return RunLog(*ops, state=state)\n        raise TypeError(\n            f\"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'\"\n        )\n    def __repr__(self) -> str:\n        from pprint import pformat\n        return f\"RunLog({pformat(self.state)})\"\n[docs]class LogStreamCallbackHandler(BaseTracer):\n    \"\"\"A tracer that streams run logs to a stream.\"\"\"\n[docs]    def __init__(\n        self,\n        *,\n        auto_close: bool = True,\n        include_names: Optional[Sequence[str]] = None,\n        include_types: Optional[Sequence[str]] = None,\n        include_tags: Optional[Sequence[str]] = None,\n        exclude_names: Optional[Sequence[str]] = None,\n        exclude_types: Optional[Sequence[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html"}
{"id": "2e9c3311c106-3", "text": "exclude_types: Optional[Sequence[str]] = None,\n        exclude_tags: Optional[Sequence[str]] = None,\n    ) -> None:\n        super().__init__()\n        self.auto_close = auto_close\n        self.include_names = include_names\n        self.include_types = include_types\n        self.include_tags = include_tags\n        self.exclude_names = exclude_names\n        self.exclude_types = exclude_types\n        self.exclude_tags = exclude_tags\n        send_stream, receive_stream = create_memory_object_stream(\n            math.inf, item_type=RunLogPatch\n        )\n        self.lock = threading.Lock()\n        self.send_stream = send_stream\n        self.receive_stream = receive_stream\n        self._key_map_by_run_id: Dict[UUID, str] = {}\n        self._counter_map_by_name: Dict[str, int] = defaultdict(int)\n        self.root_id: Optional[UUID] = None\n    def __aiter__(self) -> AsyncIterator[RunLogPatch]:\n        return self.receive_stream.__aiter__()\n[docs]    def include_run(self, run: Run) -> bool:\n        if run.id == self.root_id:\n            return False\n        run_tags = run.tags or []\n        if (\n            self.include_names is None\n            and self.include_types is None\n            and self.include_tags is None\n        ):\n            include = True\n        else:\n            include = False\n        if self.include_names is not None:\n            include = include or run.name in self.include_names\n        if self.include_types is not None:\n            include = include or run.run_type in self.include_types\n        if self.include_tags is not None:\n            include = include or any(tag in self.include_tags for tag in run_tags)\n        if self.exclude_names is not None:\n            include = include and run.name not in self.exclude_names", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html"}
{"id": "2e9c3311c106-4", "text": "include = include and run.name not in self.exclude_names\n        if self.exclude_types is not None:\n            include = include and run.run_type not in self.exclude_types\n        if self.exclude_tags is not None:\n            include = include and all(tag not in self.exclude_tags for tag in run_tags)\n        return include\n    def _persist_run(self, run: Run) -> None:\n        # This is a legacy method only called once for an entire run tree\n        # therefore not useful here\n        pass\n    def _on_run_create(self, run: Run) -> None:\n        \"\"\"Start a run.\"\"\"\n        if self.root_id is None:\n            self.root_id = run.id\n            self.send_stream.send_nowait(\n                RunLogPatch(\n                    {\n                        \"op\": \"replace\",\n                        \"path\": \"\",\n                        \"value\": RunState(\n                            id=str(run.id),\n                            streamed_output=[],\n                            final_output=None,\n                            logs={},\n                        ),\n                    }\n                )\n            )\n        if not self.include_run(run):\n            return\n        # Determine previous index, increment by 1\n        with self.lock:\n            self._counter_map_by_name[run.name] += 1\n            count = self._counter_map_by_name[run.name]\n            self._key_map_by_run_id[run.id] = (\n                run.name if count == 1 else f\"{run.name}:{count}\"\n            )\n        # Add the run to the stream\n        self.send_stream.send_nowait(\n            RunLogPatch(\n                {\n                    \"op\": \"add\",\n                    \"path\": f\"/logs/{self._key_map_by_run_id[run.id]}\",\n                    \"value\": LogEntry(\n                        id=str(run.id),\n                        name=run.name,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html"}
{"id": "2e9c3311c106-5", "text": "id=str(run.id),\n                        name=run.name,\n                        type=run.run_type,\n                        tags=run.tags or [],\n                        metadata=(run.extra or {}).get(\"metadata\", {}),\n                        start_time=run.start_time.isoformat(timespec=\"milliseconds\"),\n                        streamed_output_str=[],\n                        final_output=None,\n                        end_time=None,\n                    ),\n                }\n            )\n        )\n    def _on_run_update(self, run: Run) -> None:\n        \"\"\"Finish a run.\"\"\"\n        try:\n            index = self._key_map_by_run_id.get(run.id)\n            if index is None:\n                return\n            self.send_stream.send_nowait(\n                RunLogPatch(\n                    {\n                        \"op\": \"add\",\n                        \"path\": f\"/logs/{index}/final_output\",\n                        # to undo the dumpd done by some runnables / tracer / etc\n                        \"value\": load(run.outputs),\n                    },\n                    {\n                        \"op\": \"add\",\n                        \"path\": f\"/logs/{index}/end_time\",\n                        \"value\": run.end_time.isoformat(timespec=\"milliseconds\")\n                        if run.end_time is not None\n                        else None,\n                    },\n                )\n            )\n        finally:\n            if run.id == self.root_id:\n                self.send_stream.send_nowait(\n                    RunLogPatch(\n                        {\n                            \"op\": \"replace\",\n                            \"path\": \"/final_output\",\n                            \"value\": load(run.outputs),\n                        }\n                    )\n                )\n                if self.auto_close:\n                    self.send_stream.close()\n    def _on_llm_new_token(\n        self,\n        run: Run,\n        token: str,\n        chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html"}
{"id": "2e9c3311c106-6", "text": "chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]],\n    ) -> None:\n        \"\"\"Process new LLM token.\"\"\"\n        index = self._key_map_by_run_id.get(run.id)\n        if index is None:\n            return\n        self.send_stream.send_nowait(\n            RunLogPatch(\n                {\n                    \"op\": \"add\",\n                    \"path\": f\"/logs/{index}/streamed_output_str/-\",\n                    \"value\": token,\n                }\n            )\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html"}
{"id": "112b8d993f7b-0", "text": "Source code for langchain.schema.callbacks.tracers.langchain\n\"\"\"A Tracer implementation that records to LangChain endpoint.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport weakref\nfrom concurrent.futures import Future, ThreadPoolExecutor, wait\nfrom datetime import datetime\nfrom typing import Any, Callable, Dict, List, Optional, Union\nfrom uuid import UUID\nfrom langsmith import Client\nfrom langsmith import utils as ls_utils\nfrom tenacity import (\n    Retrying,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential_jitter,\n)\nfrom langchain.env import get_runtime_environment\nfrom langchain.load.dump import dumpd\nfrom langchain.schema.callbacks.tracers.base import BaseTracer\nfrom langchain.schema.callbacks.tracers.schemas import Run\nfrom langchain.schema.messages import BaseMessage\nlogger = logging.getLogger(__name__)\n_LOGGED = set()\n_TRACERS: weakref.WeakSet[LangChainTracer] = weakref.WeakSet()\n_CLIENT: Optional[Client] = None\n_EXECUTOR: Optional[ThreadPoolExecutor] = None\n[docs]def log_error_once(method: str, exception: Exception) -> None:\n    \"\"\"Log an error once.\"\"\"\n    global _LOGGED\n    if (method, type(exception)) in _LOGGED:\n        return\n    _LOGGED.add((method, type(exception)))\n    logger.error(exception)\n[docs]def wait_for_all_tracers() -> None:\n    \"\"\"Wait for all tracers to finish.\"\"\"\n    global _TRACERS\n    for tracer in list(_TRACERS):\n        if tracer is not None:\n            tracer.wait_for_futures()\n[docs]def get_client() -> Client:\n    \"\"\"Get the client.\"\"\"\n    global _CLIENT\n    if _CLIENT is None:\n        _CLIENT = Client()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html"}
{"id": "112b8d993f7b-1", "text": "global _CLIENT\n    if _CLIENT is None:\n        _CLIENT = Client()\n    return _CLIENT\ndef _get_executor() -> ThreadPoolExecutor:\n    \"\"\"Get the executor.\"\"\"\n    global _EXECUTOR\n    if _EXECUTOR is None:\n        _EXECUTOR = ThreadPoolExecutor()\n    return _EXECUTOR\ndef _copy(run: Run) -> Run:\n    \"\"\"Copy a run.\"\"\"\n    try:\n        return run.copy(deep=True)\n    except TypeError:\n        # Fallback in case the object contains a lock or other\n        # non-pickleable object\n        return run.copy()\n[docs]class LangChainTracer(BaseTracer):\n    \"\"\"An implementation of the SharedTracer that POSTS to the langchain endpoint.\"\"\"\n[docs]    def __init__(\n        self,\n        example_id: Optional[Union[UUID, str]] = None,\n        project_name: Optional[str] = None,\n        client: Optional[Client] = None,\n        tags: Optional[List[str]] = None,\n        use_threading: bool = True,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Initialize the LangChain tracer.\"\"\"\n        super().__init__(**kwargs)\n        self.example_id = (\n            UUID(example_id) if isinstance(example_id, str) else example_id\n        )\n        self.project_name = project_name or ls_utils.get_tracer_project()\n        self.client = client or get_client()\n        self._futures: weakref.WeakSet[Future] = weakref.WeakSet()\n        self.tags = tags or []\n        self.executor = _get_executor() if use_threading else None\n        self.latest_run: Optional[Run] = None\n        global _TRACERS\n        _TRACERS.add(self)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html"}
{"id": "112b8d993f7b-2", "text": "global _TRACERS\n        _TRACERS.add(self)\n[docs]    def on_chat_model_start(\n        self,\n        serialized: Dict[str, Any],\n        messages: List[List[BaseMessage]],\n        *,\n        run_id: UUID,\n        tags: Optional[List[str]] = None,\n        parent_run_id: Optional[UUID] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        name: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Start a trace for an LLM run.\"\"\"\n        parent_run_id_ = str(parent_run_id) if parent_run_id else None\n        execution_order = self._get_execution_order(parent_run_id_)\n        start_time = datetime.utcnow()\n        if metadata:\n            kwargs.update({\"metadata\": metadata})\n        chat_model_run = Run(\n            id=run_id,\n            parent_run_id=parent_run_id,\n            serialized=serialized,\n            inputs={\"messages\": [[dumpd(msg) for msg in batch] for batch in messages]},\n            extra=kwargs,\n            events=[{\"name\": \"start\", \"time\": start_time}],\n            start_time=start_time,\n            execution_order=execution_order,\n            child_execution_order=execution_order,\n            run_type=\"llm\",\n            tags=tags,\n            name=name,\n        )\n        self._start_trace(chat_model_run)\n        self._on_chat_model_start(chat_model_run)\n    def _persist_run(self, run: Run) -> None:\n        run_ = run.copy()\n        run_.reference_example_id = self.example_id\n        self.latest_run = run_\n[docs]    def get_run_url(self) -> str:\n        \"\"\"Get the LangSmith root run URL\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html"}
{"id": "112b8d993f7b-3", "text": "\"\"\"Get the LangSmith root run URL\"\"\"\n        if not self.latest_run:\n            raise ValueError(\"No traced run found.\")\n        # If this is the first run in a project, the project may not yet be created.\n        # This method is only really useful for debugging flows, so we will assume\n        # there is some tolerace for latency.\n        for attempt in Retrying(\n            stop=stop_after_attempt(5),\n            wait=wait_exponential_jitter(),\n            retry=retry_if_exception_type(ls_utils.LangSmithError),\n        ):\n            with attempt:\n                return self.client.get_run_url(\n                    run=self.latest_run, project_name=self.project_name\n                )\n        raise ValueError(\"Failed to get run URL.\")\n    def _get_tags(self, run: Run) -> List[str]:\n        \"\"\"Get combined tags for a run.\"\"\"\n        tags = set(run.tags or [])\n        tags.update(self.tags or [])\n        return list(tags)\n    def _persist_run_single(self, run: Run) -> None:\n        \"\"\"Persist a run.\"\"\"\n        run_dict = run.dict(exclude={\"child_runs\"})\n        run_dict[\"tags\"] = self._get_tags(run)\n        extra = run_dict.get(\"extra\", {})\n        extra[\"runtime\"] = get_runtime_environment()\n        run_dict[\"extra\"] = extra\n        try:\n            self.client.create_run(**run_dict, project_name=self.project_name)\n        except Exception as e:\n            # Errors are swallowed by the thread executor so we need to log them here\n            log_error_once(\"post\", e)\n            raise\n    def _update_run_single(self, run: Run) -> None:\n        \"\"\"Update a run.\"\"\"\n        try:\n            run_dict = run.dict()\n            run_dict[\"tags\"] = self._get_tags(run)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html"}
{"id": "112b8d993f7b-4", "text": "run_dict[\"tags\"] = self._get_tags(run)\n            self.client.update_run(run.id, **run_dict)\n        except Exception as e:\n            # Errors are swallowed by the thread executor so we need to log them here\n            log_error_once(\"patch\", e)\n            raise\n    def _submit(self, function: Callable[[Run], None], run: Run) -> None:\n        \"\"\"Submit a function to the executor.\"\"\"\n        if self.executor is None:\n            function(run)\n        else:\n            self._futures.add(self.executor.submit(function, run))\n    def _on_llm_start(self, run: Run) -> None:\n        \"\"\"Persist an LLM run.\"\"\"\n        if run.parent_run_id is None:\n            run.reference_example_id = self.example_id\n        self._submit(self._persist_run_single, _copy(run))\n    def _on_chat_model_start(self, run: Run) -> None:\n        \"\"\"Persist an LLM run.\"\"\"\n        if run.parent_run_id is None:\n            run.reference_example_id = self.example_id\n        self._submit(self._persist_run_single, _copy(run))\n    def _on_llm_end(self, run: Run) -> None:\n        \"\"\"Process the LLM Run.\"\"\"\n        self._submit(self._update_run_single, _copy(run))\n    def _on_llm_error(self, run: Run) -> None:\n        \"\"\"Process the LLM Run upon error.\"\"\"\n        self._submit(self._update_run_single, _copy(run))\n    def _on_chain_start(self, run: Run) -> None:\n        \"\"\"Process the Chain Run upon start.\"\"\"\n        if run.parent_run_id is None:\n            run.reference_example_id = self.example_id\n        self._submit(self._persist_run_single, _copy(run))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html"}
{"id": "112b8d993f7b-5", "text": "self._submit(self._persist_run_single, _copy(run))\n    def _on_chain_end(self, run: Run) -> None:\n        \"\"\"Process the Chain Run.\"\"\"\n        self._submit(self._update_run_single, _copy(run))\n    def _on_chain_error(self, run: Run) -> None:\n        \"\"\"Process the Chain Run upon error.\"\"\"\n        self._submit(self._update_run_single, _copy(run))\n    def _on_tool_start(self, run: Run) -> None:\n        \"\"\"Process the Tool Run upon start.\"\"\"\n        if run.parent_run_id is None:\n            run.reference_example_id = self.example_id\n        self._submit(self._persist_run_single, _copy(run))\n    def _on_tool_end(self, run: Run) -> None:\n        \"\"\"Process the Tool Run.\"\"\"\n        self._submit(self._update_run_single, _copy(run))\n    def _on_tool_error(self, run: Run) -> None:\n        \"\"\"Process the Tool Run upon error.\"\"\"\n        self._submit(self._update_run_single, _copy(run))\n    def _on_retriever_start(self, run: Run) -> None:\n        \"\"\"Process the Retriever Run upon start.\"\"\"\n        if run.parent_run_id is None:\n            run.reference_example_id = self.example_id\n        self._submit(self._persist_run_single, _copy(run))\n    def _on_retriever_end(self, run: Run) -> None:\n        \"\"\"Process the Retriever Run.\"\"\"\n        self._submit(self._update_run_single, _copy(run))\n    def _on_retriever_error(self, run: Run) -> None:\n        \"\"\"Process the Retriever Run upon error.\"\"\"\n        self._submit(self._update_run_single, _copy(run))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html"}
{"id": "112b8d993f7b-6", "text": "self._submit(self._update_run_single, _copy(run))\n[docs]    def wait_for_futures(self) -> None:\n        \"\"\"Wait for the given futures to complete.\"\"\"\n        wait(self._futures)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html"}
{"id": "287a21143fb9-0", "text": "Source code for langchain.schema.callbacks.tracers.base\n\"\"\"Base interfaces for tracing runs.\"\"\"\nfrom __future__ import annotations\nimport logging\nfrom abc import ABC, abstractmethod\nfrom datetime import datetime\nfrom typing import Any, Dict, List, Optional, Sequence, Union, cast\nfrom uuid import UUID\nfrom tenacity import RetryCallState\nfrom langchain.load.dump import dumpd\nfrom langchain.schema.callbacks.base import BaseCallbackHandler\nfrom langchain.schema.callbacks.tracers.schemas import Run\nfrom langchain.schema.document import Document\nfrom langchain.schema.output import (\n    ChatGeneration,\n    ChatGenerationChunk,\n    GenerationChunk,\n    LLMResult,\n)\nlogger = logging.getLogger(__name__)\n[docs]class TracerException(Exception):\n    \"\"\"Base class for exceptions in tracers module.\"\"\"\n[docs]class BaseTracer(BaseCallbackHandler, ABC):\n    \"\"\"Base interface for tracers.\"\"\"\n[docs]    def __init__(self, **kwargs: Any) -> None:\n        super().__init__(**kwargs)\n        self.run_map: Dict[str, Run] = {}\n    @staticmethod\n    def _add_child_run(\n        parent_run: Run,\n        child_run: Run,\n    ) -> None:\n        \"\"\"Add child run to a chain run or tool run.\"\"\"\n        parent_run.child_runs.append(child_run)\n    @abstractmethod\n    def _persist_run(self, run: Run) -> None:\n        \"\"\"Persist a run.\"\"\"\n    def _start_trace(self, run: Run) -> None:\n        \"\"\"Start a trace for a run.\"\"\"\n        if run.parent_run_id:\n            parent_run = self.run_map.get(str(run.parent_run_id))\n            if parent_run:\n                self._add_child_run(parent_run, run)\n                parent_run.child_execution_order = max(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html"}
{"id": "287a21143fb9-1", "text": "parent_run.child_execution_order = max(\n                    parent_run.child_execution_order, run.child_execution_order\n                )\n            else:\n                logger.debug(f\"Parent run with UUID {run.parent_run_id} not found.\")\n        self.run_map[str(run.id)] = run\n        self._on_run_create(run)\n    def _end_trace(self, run: Run) -> None:\n        \"\"\"End a trace for a run.\"\"\"\n        if not run.parent_run_id:\n            self._persist_run(run)\n        else:\n            parent_run = self.run_map.get(str(run.parent_run_id))\n            if parent_run is None:\n                logger.debug(f\"Parent run with UUID {run.parent_run_id} not found.\")\n            elif (\n                run.child_execution_order is not None\n                and parent_run.child_execution_order is not None\n                and run.child_execution_order > parent_run.child_execution_order\n            ):\n                parent_run.child_execution_order = run.child_execution_order\n        self.run_map.pop(str(run.id))\n        self._on_run_update(run)\n    def _get_execution_order(self, parent_run_id: Optional[str] = None) -> int:\n        \"\"\"Get the execution order for a run.\"\"\"\n        if parent_run_id is None:\n            return 1\n        parent_run = self.run_map.get(parent_run_id)\n        if parent_run is None:\n            logger.debug(f\"Parent run with UUID {parent_run_id} not found.\")\n            return 1\n        if parent_run.child_execution_order is None:\n            raise TracerException(\n                f\"Parent run with UUID {parent_run_id} has no child execution order.\"\n            )\n        return parent_run.child_execution_order + 1\n[docs]    def on_llm_start(\n        self,\n        serialized: Dict[str, Any],\n        prompts: List[str],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html"}
{"id": "287a21143fb9-2", "text": "self,\n        serialized: Dict[str, Any],\n        prompts: List[str],\n        *,\n        run_id: UUID,\n        tags: Optional[List[str]] = None,\n        parent_run_id: Optional[UUID] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        name: Optional[str] = None,\n        **kwargs: Any,\n    ) -> Run:\n        \"\"\"Start a trace for an LLM run.\"\"\"\n        parent_run_id_ = str(parent_run_id) if parent_run_id else None\n        execution_order = self._get_execution_order(parent_run_id_)\n        start_time = datetime.utcnow()\n        if metadata:\n            kwargs.update({\"metadata\": metadata})\n        llm_run = Run(\n            id=run_id,\n            parent_run_id=parent_run_id,\n            serialized=serialized,\n            inputs={\"prompts\": prompts},\n            extra=kwargs,\n            events=[{\"name\": \"start\", \"time\": start_time}],\n            start_time=start_time,\n            execution_order=execution_order,\n            child_execution_order=execution_order,\n            run_type=\"llm\",\n            tags=tags or [],\n            name=name,\n        )\n        self._start_trace(llm_run)\n        self._on_llm_start(llm_run)\n        return llm_run\n[docs]    def on_llm_new_token(\n        self,\n        token: str,\n        *,\n        chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        **kwargs: Any,\n    ) -> Run:\n        \"\"\"Run on new LLM token. Only available when streaming is enabled.\"\"\"\n        if not run_id:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html"}
{"id": "287a21143fb9-3", "text": "if not run_id:\n            raise TracerException(\"No run_id provided for on_llm_new_token callback.\")\n        run_id_ = str(run_id)\n        llm_run = self.run_map.get(run_id_)\n        if llm_run is None or llm_run.run_type != \"llm\":\n            raise TracerException(f\"No LLM Run found to be traced for {run_id}\")\n        event_kwargs: Dict[str, Any] = {\"token\": token}\n        if chunk:\n            event_kwargs[\"chunk\"] = chunk\n        llm_run.events.append(\n            {\n                \"name\": \"new_token\",\n                \"time\": datetime.utcnow(),\n                \"kwargs\": event_kwargs,\n            },\n        )\n        self._on_llm_new_token(llm_run, token, chunk)\n        return llm_run\n[docs]    def on_retry(\n        self,\n        retry_state: RetryCallState,\n        *,\n        run_id: UUID,\n        **kwargs: Any,\n    ) -> Run:\n        if not run_id:\n            raise TracerException(\"No run_id provided for on_retry callback.\")\n        run_id_ = str(run_id)\n        llm_run = self.run_map.get(run_id_)\n        if llm_run is None:\n            raise TracerException(\"No Run found to be traced for on_retry\")\n        retry_d: Dict[str, Any] = {\n            \"slept\": retry_state.idle_for,\n            \"attempt\": retry_state.attempt_number,\n        }\n        if retry_state.outcome is None:\n            retry_d[\"outcome\"] = \"N/A\"\n        elif retry_state.outcome.failed:\n            retry_d[\"outcome\"] = \"failed\"\n            exception = retry_state.outcome.exception()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html"}
{"id": "287a21143fb9-4", "text": "exception = retry_state.outcome.exception()\n            retry_d[\"exception\"] = str(exception)\n            retry_d[\"exception_type\"] = exception.__class__.__name__\n        else:\n            retry_d[\"outcome\"] = \"success\"\n            retry_d[\"result\"] = str(retry_state.outcome.result())\n        llm_run.events.append(\n            {\n                \"name\": \"retry\",\n                \"time\": datetime.utcnow(),\n                \"kwargs\": retry_d,\n            },\n        )\n        return llm_run\n[docs]    def on_llm_end(self, response: LLMResult, *, run_id: UUID, **kwargs: Any) -> Run:\n        \"\"\"End a trace for an LLM run.\"\"\"\n        if not run_id:\n            raise TracerException(\"No run_id provided for on_llm_end callback.\")\n        run_id_ = str(run_id)\n        llm_run = self.run_map.get(run_id_)\n        if llm_run is None or llm_run.run_type != \"llm\":\n            raise TracerException(f\"No LLM Run found to be traced for {run_id}\")\n        llm_run.outputs = response.dict()\n        for i, generations in enumerate(response.generations):\n            for j, generation in enumerate(generations):\n                output_generation = llm_run.outputs[\"generations\"][i][j]\n                if \"message\" in output_generation:\n                    output_generation[\"message\"] = dumpd(\n                        cast(ChatGeneration, generation).message\n                    )\n        llm_run.end_time = datetime.utcnow()\n        llm_run.events.append({\"name\": \"end\", \"time\": llm_run.end_time})\n        self._end_trace(llm_run)\n        self._on_llm_end(llm_run)\n        return llm_run", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html"}
{"id": "287a21143fb9-5", "text": "self._on_llm_end(llm_run)\n        return llm_run\n[docs]    def on_llm_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        **kwargs: Any,\n    ) -> Run:\n        \"\"\"Handle an error for an LLM run.\"\"\"\n        if not run_id:\n            raise TracerException(\"No run_id provided for on_llm_error callback.\")\n        run_id_ = str(run_id)\n        llm_run = self.run_map.get(run_id_)\n        if llm_run is None or llm_run.run_type != \"llm\":\n            raise TracerException(f\"No LLM Run found to be traced for {run_id}\")\n        llm_run.error = repr(error)\n        llm_run.end_time = datetime.utcnow()\n        llm_run.events.append({\"name\": \"error\", \"time\": llm_run.end_time})\n        self._end_trace(llm_run)\n        self._on_chain_error(llm_run)\n        return llm_run\n[docs]    def on_chain_start(\n        self,\n        serialized: Dict[str, Any],\n        inputs: Dict[str, Any],\n        *,\n        run_id: UUID,\n        tags: Optional[List[str]] = None,\n        parent_run_id: Optional[UUID] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        run_type: Optional[str] = None,\n        name: Optional[str] = None,\n        **kwargs: Any,\n    ) -> Run:\n        \"\"\"Start a trace for a chain run.\"\"\"\n        parent_run_id_ = str(parent_run_id) if parent_run_id else None\n        execution_order = self._get_execution_order(parent_run_id_)\n        start_time = datetime.utcnow()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html"}
{"id": "287a21143fb9-6", "text": "start_time = datetime.utcnow()\n        if metadata:\n            kwargs.update({\"metadata\": metadata})\n        chain_run = Run(\n            id=run_id,\n            parent_run_id=parent_run_id,\n            serialized=serialized,\n            inputs=inputs if isinstance(inputs, dict) else {\"input\": inputs},\n            extra=kwargs,\n            events=[{\"name\": \"start\", \"time\": start_time}],\n            start_time=start_time,\n            execution_order=execution_order,\n            child_execution_order=execution_order,\n            child_runs=[],\n            run_type=run_type or \"chain\",\n            name=name,\n            tags=tags or [],\n        )\n        self._start_trace(chain_run)\n        self._on_chain_start(chain_run)\n        return chain_run\n[docs]    def on_chain_end(\n        self,\n        outputs: Dict[str, Any],\n        *,\n        run_id: UUID,\n        inputs: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> Run:\n        \"\"\"End a trace for a chain run.\"\"\"\n        if not run_id:\n            raise TracerException(\"No run_id provided for on_chain_end callback.\")\n        chain_run = self.run_map.get(str(run_id))\n        if chain_run is None:\n            raise TracerException(f\"No chain Run found to be traced for {run_id}\")\n        chain_run.outputs = (\n            outputs if isinstance(outputs, dict) else {\"output\": outputs}\n        )\n        chain_run.end_time = datetime.utcnow()\n        chain_run.events.append({\"name\": \"end\", \"time\": chain_run.end_time})\n        if inputs is not None:\n            chain_run.inputs = inputs if isinstance(inputs, dict) else {\"input\": inputs}\n        self._end_trace(chain_run)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html"}
{"id": "287a21143fb9-7", "text": "self._end_trace(chain_run)\n        self._on_chain_end(chain_run)\n        return chain_run\n[docs]    def on_chain_error(\n        self,\n        error: BaseException,\n        *,\n        inputs: Optional[Dict[str, Any]] = None,\n        run_id: UUID,\n        **kwargs: Any,\n    ) -> Run:\n        \"\"\"Handle an error for a chain run.\"\"\"\n        if not run_id:\n            raise TracerException(\"No run_id provided for on_chain_error callback.\")\n        chain_run = self.run_map.get(str(run_id))\n        if chain_run is None:\n            raise TracerException(f\"No chain Run found to be traced for {run_id}\")\n        chain_run.error = repr(error)\n        chain_run.end_time = datetime.utcnow()\n        chain_run.events.append({\"name\": \"error\", \"time\": chain_run.end_time})\n        if inputs is not None:\n            chain_run.inputs = inputs if isinstance(inputs, dict) else {\"input\": inputs}\n        self._end_trace(chain_run)\n        self._on_chain_error(chain_run)\n        return chain_run\n[docs]    def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        *,\n        run_id: UUID,\n        tags: Optional[List[str]] = None,\n        parent_run_id: Optional[UUID] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        name: Optional[str] = None,\n        **kwargs: Any,\n    ) -> Run:\n        \"\"\"Start a trace for a tool run.\"\"\"\n        parent_run_id_ = str(parent_run_id) if parent_run_id else None\n        execution_order = self._get_execution_order(parent_run_id_)\n        start_time = datetime.utcnow()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html"}
{"id": "287a21143fb9-8", "text": "start_time = datetime.utcnow()\n        if metadata:\n            kwargs.update({\"metadata\": metadata})\n        tool_run = Run(\n            id=run_id,\n            parent_run_id=parent_run_id,\n            serialized=serialized,\n            inputs={\"input\": input_str},\n            extra=kwargs,\n            events=[{\"name\": \"start\", \"time\": start_time}],\n            start_time=start_time,\n            execution_order=execution_order,\n            child_execution_order=execution_order,\n            child_runs=[],\n            run_type=\"tool\",\n            tags=tags or [],\n            name=name,\n        )\n        self._start_trace(tool_run)\n        self._on_tool_start(tool_run)\n        return tool_run\n[docs]    def on_tool_end(self, output: str, *, run_id: UUID, **kwargs: Any) -> Run:\n        \"\"\"End a trace for a tool run.\"\"\"\n        if not run_id:\n            raise TracerException(\"No run_id provided for on_tool_end callback.\")\n        tool_run = self.run_map.get(str(run_id))\n        if tool_run is None or tool_run.run_type != \"tool\":\n            raise TracerException(f\"No tool Run found to be traced for {run_id}\")\n        tool_run.outputs = {\"output\": output}\n        tool_run.end_time = datetime.utcnow()\n        tool_run.events.append({\"name\": \"end\", \"time\": tool_run.end_time})\n        self._end_trace(tool_run)\n        self._on_tool_end(tool_run)\n        return tool_run\n[docs]    def on_tool_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        **kwargs: Any,\n    ) -> Run:\n        \"\"\"Handle an error for a tool run.\"\"\"\n        if not run_id:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html"}
{"id": "287a21143fb9-9", "text": "\"\"\"Handle an error for a tool run.\"\"\"\n        if not run_id:\n            raise TracerException(\"No run_id provided for on_tool_error callback.\")\n        tool_run = self.run_map.get(str(run_id))\n        if tool_run is None or tool_run.run_type != \"tool\":\n            raise TracerException(f\"No tool Run found to be traced for {run_id}\")\n        tool_run.error = repr(error)\n        tool_run.end_time = datetime.utcnow()\n        tool_run.events.append({\"name\": \"error\", \"time\": tool_run.end_time})\n        self._end_trace(tool_run)\n        self._on_tool_error(tool_run)\n        return tool_run\n[docs]    def on_retriever_start(\n        self,\n        serialized: Dict[str, Any],\n        query: str,\n        *,\n        run_id: UUID,\n        parent_run_id: Optional[UUID] = None,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        name: Optional[str] = None,\n        **kwargs: Any,\n    ) -> Run:\n        \"\"\"Run when Retriever starts running.\"\"\"\n        parent_run_id_ = str(parent_run_id) if parent_run_id else None\n        execution_order = self._get_execution_order(parent_run_id_)\n        start_time = datetime.utcnow()\n        if metadata:\n            kwargs.update({\"metadata\": metadata})\n        retrieval_run = Run(\n            id=run_id,\n            name=name or \"Retriever\",\n            parent_run_id=parent_run_id,\n            serialized=serialized,\n            inputs={\"query\": query},\n            extra=kwargs,\n            events=[{\"name\": \"start\", \"time\": start_time}],\n            start_time=start_time,\n            execution_order=execution_order,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html"}
{"id": "287a21143fb9-10", "text": "start_time=start_time,\n            execution_order=execution_order,\n            child_execution_order=execution_order,\n            tags=tags,\n            child_runs=[],\n            run_type=\"retriever\",\n        )\n        self._start_trace(retrieval_run)\n        self._on_retriever_start(retrieval_run)\n        return retrieval_run\n[docs]    def on_retriever_error(\n        self,\n        error: BaseException,\n        *,\n        run_id: UUID,\n        **kwargs: Any,\n    ) -> Run:\n        \"\"\"Run when Retriever errors.\"\"\"\n        if not run_id:\n            raise TracerException(\"No run_id provided for on_retriever_error callback.\")\n        retrieval_run = self.run_map.get(str(run_id))\n        if retrieval_run is None or retrieval_run.run_type != \"retriever\":\n            raise TracerException(f\"No retriever Run found to be traced for {run_id}\")\n        retrieval_run.error = repr(error)\n        retrieval_run.end_time = datetime.utcnow()\n        retrieval_run.events.append({\"name\": \"error\", \"time\": retrieval_run.end_time})\n        self._end_trace(retrieval_run)\n        self._on_retriever_error(retrieval_run)\n        return retrieval_run\n[docs]    def on_retriever_end(\n        self, documents: Sequence[Document], *, run_id: UUID, **kwargs: Any\n    ) -> Run:\n        \"\"\"Run when Retriever ends running.\"\"\"\n        if not run_id:\n            raise TracerException(\"No run_id provided for on_retriever_end callback.\")\n        retrieval_run = self.run_map.get(str(run_id))\n        if retrieval_run is None or retrieval_run.run_type != \"retriever\":", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html"}
{"id": "287a21143fb9-11", "text": "if retrieval_run is None or retrieval_run.run_type != \"retriever\":\n            raise TracerException(f\"No retriever Run found to be traced for {run_id}\")\n        retrieval_run.outputs = {\"documents\": documents}\n        retrieval_run.end_time = datetime.utcnow()\n        retrieval_run.events.append({\"name\": \"end\", \"time\": retrieval_run.end_time})\n        self._end_trace(retrieval_run)\n        self._on_retriever_end(retrieval_run)\n        return retrieval_run\n    def __deepcopy__(self, memo: dict) -> BaseTracer:\n        \"\"\"Deepcopy the tracer.\"\"\"\n        return self\n    def __copy__(self) -> BaseTracer:\n        \"\"\"Copy the tracer.\"\"\"\n        return self\n    def _on_run_create(self, run: Run) -> None:\n        \"\"\"Process a run upon creation.\"\"\"\n    def _on_run_update(self, run: Run) -> None:\n        \"\"\"Process a run upon update.\"\"\"\n    def _on_llm_start(self, run: Run) -> None:\n        \"\"\"Process the LLM Run upon start.\"\"\"\n    def _on_llm_new_token(\n        self,\n        run: Run,\n        token: str,\n        chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]],\n    ) -> None:\n        \"\"\"Process new LLM token.\"\"\"\n    def _on_llm_end(self, run: Run) -> None:\n        \"\"\"Process the LLM Run.\"\"\"\n    def _on_llm_error(self, run: Run) -> None:\n        \"\"\"Process the LLM Run upon error.\"\"\"\n    def _on_chain_start(self, run: Run) -> None:\n        \"\"\"Process the Chain Run upon start.\"\"\"\n    def _on_chain_end(self, run: Run) -> None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html"}
{"id": "287a21143fb9-12", "text": "def _on_chain_end(self, run: Run) -> None:\n        \"\"\"Process the Chain Run.\"\"\"\n    def _on_chain_error(self, run: Run) -> None:\n        \"\"\"Process the Chain Run upon error.\"\"\"\n    def _on_tool_start(self, run: Run) -> None:\n        \"\"\"Process the Tool Run upon start.\"\"\"\n    def _on_tool_end(self, run: Run) -> None:\n        \"\"\"Process the Tool Run.\"\"\"\n    def _on_tool_error(self, run: Run) -> None:\n        \"\"\"Process the Tool Run upon error.\"\"\"\n    def _on_chat_model_start(self, run: Run) -> None:\n        \"\"\"Process the Chat Model Run upon start.\"\"\"\n    def _on_retriever_start(self, run: Run) -> None:\n        \"\"\"Process the Retriever Run upon start.\"\"\"\n    def _on_retriever_end(self, run: Run) -> None:\n        \"\"\"Process the Retriever Run.\"\"\"\n    def _on_retriever_error(self, run: Run) -> None:\n        \"\"\"Process the Retriever Run upon error.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html"}
{"id": "947f1b04301c-0", "text": "Source code for langchain.schema.callbacks.tracers.schemas\n\"\"\"Schemas for tracers.\"\"\"\nfrom __future__ import annotations\nimport datetime\nimport warnings\nfrom typing import Any, Dict, List, Optional, Type\nfrom uuid import UUID\nfrom langsmith.schemas import RunBase as BaseRunV2\nfrom langsmith.schemas import RunTypeEnum as RunTypeEnumDep\nfrom langchain.pydantic_v1 import BaseModel, Field, root_validator\nfrom langchain.schema import LLMResult\n[docs]def RunTypeEnum() -> Type[RunTypeEnumDep]:\n    \"\"\"RunTypeEnum.\"\"\"\n    warnings.warn(\n        \"RunTypeEnum is deprecated. Please directly use a string instead\"\n        \" (e.g. 'llm', 'chain', 'tool').\",\n        DeprecationWarning,\n    )\n    return RunTypeEnumDep\n[docs]class TracerSessionV1Base(BaseModel):\n    \"\"\"Base class for TracerSessionV1.\"\"\"\n    start_time: datetime.datetime = Field(default_factory=datetime.datetime.utcnow)\n    name: Optional[str] = None\n    extra: Optional[Dict[str, Any]] = None\n[docs]class TracerSessionV1Create(TracerSessionV1Base):\n    \"\"\"Create class for TracerSessionV1.\"\"\"\n[docs]class TracerSessionV1(TracerSessionV1Base):\n    \"\"\"TracerSessionV1 schema.\"\"\"\n    id: int\n[docs]class TracerSessionBase(TracerSessionV1Base):\n    \"\"\"Base class for TracerSession.\"\"\"\n    tenant_id: UUID\n[docs]class TracerSession(TracerSessionBase):\n    \"\"\"TracerSessionV1 schema for the V2 API.\"\"\"\n    id: UUID\n[docs]class BaseRun(BaseModel):\n    \"\"\"Base class for Run.\"\"\"\n    uuid: str", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/schemas.html"}
{"id": "947f1b04301c-1", "text": "\"\"\"Base class for Run.\"\"\"\n    uuid: str\n    parent_uuid: Optional[str] = None\n    start_time: datetime.datetime = Field(default_factory=datetime.datetime.utcnow)\n    end_time: datetime.datetime = Field(default_factory=datetime.datetime.utcnow)\n    extra: Optional[Dict[str, Any]] = None\n    execution_order: int\n    child_execution_order: int\n    serialized: Dict[str, Any]\n    session_id: int\n    error: Optional[str] = None\n[docs]class LLMRun(BaseRun):\n    \"\"\"Class for LLMRun.\"\"\"\n    prompts: List[str]\n    response: Optional[LLMResult] = None\n[docs]class ChainRun(BaseRun):\n    \"\"\"Class for ChainRun.\"\"\"\n    inputs: Dict[str, Any]\n    outputs: Optional[Dict[str, Any]] = None\n    child_llm_runs: List[LLMRun] = Field(default_factory=list)\n    child_chain_runs: List[ChainRun] = Field(default_factory=list)\n    child_tool_runs: List[ToolRun] = Field(default_factory=list)\n[docs]class ToolRun(BaseRun):\n    \"\"\"Class for ToolRun.\"\"\"\n    tool_input: str\n    output: Optional[str] = None\n    action: str\n    child_llm_runs: List[LLMRun] = Field(default_factory=list)\n    child_chain_runs: List[ChainRun] = Field(default_factory=list)\n    child_tool_runs: List[ToolRun] = Field(default_factory=list)\n# Begin V2 API Schemas\n[docs]class Run(BaseRunV2):\n    \"\"\"Run schema for the V2 API in the Tracer.\"\"\"\n    execution_order: int\n    child_execution_order: int\n    child_runs: List[Run] = Field(default_factory=list)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/schemas.html"}
{"id": "947f1b04301c-2", "text": "child_runs: List[Run] = Field(default_factory=list)\n    tags: Optional[List[str]] = Field(default_factory=list)\n    events: List[Dict[str, Any]] = Field(default_factory=list)\n    @root_validator(pre=True)\n    def assign_name(cls, values: dict) -> dict:\n        \"\"\"Assign name to the run.\"\"\"\n        if values.get(\"name\") is None:\n            if \"name\" in values[\"serialized\"]:\n                values[\"name\"] = values[\"serialized\"][\"name\"]\n            elif \"id\" in values[\"serialized\"]:\n                values[\"name\"] = values[\"serialized\"][\"id\"][-1]\n        if values.get(\"events\") is None:\n            values[\"events\"] = []\n        return values\nChainRun.update_forward_refs()\nToolRun.update_forward_refs()\nRun.update_forward_refs()\n__all__ = [\n    \"BaseRun\",\n    \"ChainRun\",\n    \"LLMRun\",\n    \"Run\",\n    \"RunTypeEnum\",\n    \"ToolRun\",\n    \"TracerSession\",\n    \"TracerSessionBase\",\n    \"TracerSessionV1\",\n    \"TracerSessionV1Base\",\n    \"TracerSessionV1Create\",\n]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/schemas.html"}
{"id": "f6a8d154d519-0", "text": "Source code for langchain.schema.callbacks.tracers.evaluation\n\"\"\"A tracer that runs evaluators over completed runs.\"\"\"\nfrom __future__ import annotations\nimport logging\nimport threading\nimport weakref\nfrom concurrent.futures import Future, ThreadPoolExecutor, wait\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast\nfrom uuid import UUID\nimport langsmith\nfrom langsmith.evaluation.evaluator import EvaluationResult, EvaluationResults\nfrom langchain.schema.callbacks import manager\nfrom langchain.schema.callbacks.tracers import langchain as langchain_tracer\nfrom langchain.schema.callbacks.tracers.base import BaseTracer\nfrom langchain.schema.callbacks.tracers.langchain import _get_executor\nfrom langchain.schema.callbacks.tracers.schemas import Run\nlogger = logging.getLogger(__name__)\n_TRACERS: weakref.WeakSet[EvaluatorCallbackHandler] = weakref.WeakSet()\n[docs]def wait_for_all_evaluators() -> None:\n    \"\"\"Wait for all tracers to finish.\"\"\"\n    global _TRACERS\n    for tracer in list(_TRACERS):\n        if tracer is not None:\n            tracer.wait_for_futures()\n[docs]class EvaluatorCallbackHandler(BaseTracer):\n    \"\"\"A tracer that runs a run evaluator whenever a run is persisted.\n    Parameters\n    ----------\n    evaluators : Sequence[RunEvaluator]\n        The run evaluators to apply to all top level runs.\n    client : LangSmith Client, optional\n        The LangSmith client instance to use for evaluating the runs.\n        If not specified, a new instance will be created.\n    example_id : Union[UUID, str], optional\n        The example ID to be associated with the runs.\n    project_name : str, optional\n        The LangSmith project name to be organize eval chain runs under.\n    Attributes\n    ----------", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/evaluation.html"}
{"id": "f6a8d154d519-1", "text": "Attributes\n    ----------\n    example_id : Union[UUID, None]\n        The example ID associated with the runs.\n    client : Client\n        The LangSmith client instance used for evaluating the runs.\n    evaluators : Sequence[RunEvaluator]\n        The sequence of run evaluators to be executed.\n    executor : ThreadPoolExecutor\n        The thread pool executor used for running the evaluators.\n    futures : Set[Future]\n        The set of futures representing the running evaluators.\n    skip_unfinished : bool\n        Whether to skip runs that are not finished or raised\n        an error.\n    project_name : Optional[str]\n        The LangSmith project name to be organize eval chain runs under.\n    \"\"\"\n    name = \"evaluator_callback_handler\"\n[docs]    def __init__(\n        self,\n        evaluators: Sequence[langsmith.RunEvaluator],\n        client: Optional[langsmith.Client] = None,\n        example_id: Optional[Union[UUID, str]] = None,\n        skip_unfinished: bool = True,\n        project_name: Optional[str] = \"evaluators\",\n        max_concurrency: Optional[int] = None,\n        **kwargs: Any,\n    ) -> None:\n        super().__init__(**kwargs)\n        self.example_id = (\n            UUID(example_id) if isinstance(example_id, str) else example_id\n        )\n        self.client = client or langchain_tracer.get_client()\n        self.evaluators = evaluators\n        if max_concurrency is None:\n            self.executor: Optional[ThreadPoolExecutor] = _get_executor()\n        elif max_concurrency > 0:\n            self.executor = ThreadPoolExecutor(max_workers=max_concurrency)\n            weakref.finalize(\n                self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/evaluation.html"}
{"id": "f6a8d154d519-2", "text": "weakref.finalize(\n                self,\n                lambda: cast(ThreadPoolExecutor, self.executor).shutdown(wait=True),\n            )\n        else:\n            self.executor = None\n        self.futures: weakref.WeakSet[Future] = weakref.WeakSet()\n        self.skip_unfinished = skip_unfinished\n        self.project_name = project_name\n        self.logged_eval_results: Dict[Tuple[str, str], List[EvaluationResult]] = {}\n        self.lock = threading.Lock()\n        global _TRACERS\n        _TRACERS.add(self)\n    def _evaluate_in_project(self, run: Run, evaluator: langsmith.RunEvaluator) -> None:\n        \"\"\"Evaluate the run in the project.\n        Parameters\n        ----------\n        run : Run\n            The run to be evaluated.\n        evaluator : RunEvaluator\n            The evaluator to use for evaluating the run.\n        \"\"\"\n        try:\n            if self.project_name is None:\n                eval_result = self.client.evaluate_run(run, evaluator)\n                eval_results = [eval_result]\n            with manager.tracing_v2_enabled(\n                project_name=self.project_name, tags=[\"eval\"], client=self.client\n            ) as cb:\n                reference_example = (\n                    self.client.read_example(run.reference_example_id)\n                    if run.reference_example_id\n                    else None\n                )\n                evaluation_result = evaluator.evaluate_run(\n                    run,\n                    example=reference_example,\n                )\n                eval_results = self._log_evaluation_feedback(\n                    evaluation_result,\n                    run,\n                    source_run_id=cb.latest_run.id if cb.latest_run else None,\n                )\n        except Exception as e:\n            logger.error(\n                f\"Error evaluating run {run.id} with \"\n                f\"{evaluator.__class__.__name__}: {repr(e)}\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/evaluation.html"}
{"id": "f6a8d154d519-3", "text": "f\"{evaluator.__class__.__name__}: {repr(e)}\",\n                exc_info=True,\n            )\n            raise e\n        example_id = str(run.reference_example_id)\n        with self.lock:\n            for res in eval_results:\n                run_id = (\n                    str(getattr(res, \"target_run_id\"))\n                    if hasattr(res, \"target_run_id\")\n                    else str(run.id)\n                )\n                self.logged_eval_results.setdefault((run_id, example_id), []).append(\n                    res\n                )\n    def _select_eval_results(\n        self,\n        results: Union[EvaluationResult, EvaluationResults],\n    ) -> List[EvaluationResult]:\n        if isinstance(results, EvaluationResult):\n            results_ = [results]\n        elif isinstance(results, dict) and \"results\" in results:\n            results_ = cast(List[EvaluationResult], results[\"results\"])\n        else:\n            raise TypeError(\n                f\"Invalid evaluation result type {type(results)}.\"\n                \" Expected EvaluationResult or EvaluationResults.\"\n            )\n        return results_\n    def _log_evaluation_feedback(\n        self,\n        evaluator_response: Union[EvaluationResult, EvaluationResults],\n        run: Run,\n        source_run_id: Optional[UUID] = None,\n    ) -> List[EvaluationResult]:\n        results = self._select_eval_results(evaluator_response)\n        for res in results:\n            source_info_: Dict[str, Any] = {}\n            if res.evaluator_info:\n                source_info_ = {**res.evaluator_info, **source_info_}\n            run_id_ = (\n                getattr(res, \"target_run_id\")\n                if hasattr(res, \"target_run_id\") and res.target_run_id is not None\n                else run.id\n            )\n            self.client.create_feedback(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/evaluation.html"}
{"id": "f6a8d154d519-4", "text": "else run.id\n            )\n            self.client.create_feedback(\n                run_id_,\n                res.key,\n                score=res.score,\n                value=res.value,\n                comment=res.comment,\n                correction=res.correction,\n                source_info=source_info_,\n                source_run_id=res.source_run_id or source_run_id,\n                feedback_source_type=langsmith.schemas.FeedbackSourceType.MODEL,\n            )\n        return results\n    def _persist_run(self, run: Run) -> None:\n        \"\"\"Run the evaluator on the run.\n        Parameters\n        ----------\n        run : Run\n            The run to be evaluated.\n        \"\"\"\n        if self.skip_unfinished and not run.outputs:\n            logger.debug(f\"Skipping unfinished run {run.id}\")\n            return\n        run_ = run.copy()\n        run_.reference_example_id = self.example_id\n        for evaluator in self.evaluators:\n            if self.executor is None:\n                self._evaluate_in_project(run_, evaluator)\n            else:\n                self.futures.add(\n                    self.executor.submit(self._evaluate_in_project, run_, evaluator)\n                )\n[docs]    def wait_for_futures(self) -> None:\n        \"\"\"Wait for all futures to complete.\"\"\"\n        wait(self.futures)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/evaluation.html"}
{"id": "1c9bcca8f7de-0", "text": "Source code for langchain.schema.callbacks.tracers.run_collector\n\"\"\"A tracer that collects all nested runs in a list.\"\"\"\nfrom typing import Any, List, Optional, Union\nfrom uuid import UUID\nfrom langchain.schema.callbacks.tracers.base import BaseTracer\nfrom langchain.schema.callbacks.tracers.schemas import Run\n[docs]class RunCollectorCallbackHandler(BaseTracer):\n    \"\"\"\n    A tracer that collects all nested runs in a list.\n    This tracer is useful for inspection and evaluation purposes.\n    Parameters\n    ----------\n    example_id : Optional[Union[UUID, str]], default=None\n        The ID of the example being traced. It can be either a UUID or a string.\n    \"\"\"\n    name: str = \"run-collector_callback_handler\"\n[docs]    def __init__(\n        self, example_id: Optional[Union[UUID, str]] = None, **kwargs: Any\n    ) -> None:\n        \"\"\"\n        Initialize the RunCollectorCallbackHandler.\n        Parameters\n        ----------\n        example_id : Optional[Union[UUID, str]], default=None\n            The ID of the example being traced. It can be either a UUID or a string.\n        \"\"\"\n        super().__init__(**kwargs)\n        self.example_id = (\n            UUID(example_id) if isinstance(example_id, str) else example_id\n        )\n        self.traced_runs: List[Run] = []\n    def _persist_run(self, run: Run) -> None:\n        \"\"\"\n        Persist a run by adding it to the traced_runs list.\n        Parameters\n        ----------\n        run : Run\n            The run to be persisted.\n        \"\"\"\n        run_ = run.copy()\n        run_.reference_example_id = self.example_id\n        self.traced_runs.append(run_)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/run_collector.html"}
{"id": "270fb32cca4e-0", "text": "Source code for langchain.schema.callbacks.tracers.langchain_v1\nfrom __future__ import annotations\nimport logging\nimport os\nfrom typing import Any, Dict, Optional, Union\nimport requests\nfrom langchain.schema.callbacks.tracers.base import BaseTracer\nfrom langchain.schema.callbacks.tracers.schemas import (\n    ChainRun,\n    LLMRun,\n    Run,\n    ToolRun,\n    TracerSession,\n    TracerSessionV1,\n    TracerSessionV1Base,\n)\nfrom langchain.schema.messages import get_buffer_string\nfrom langchain.utils import raise_for_status_with_text\nlogger = logging.getLogger(__name__)\n[docs]def get_headers() -> Dict[str, Any]:\n    \"\"\"Get the headers for the LangChain API.\"\"\"\n    headers: Dict[str, Any] = {\"Content-Type\": \"application/json\"}\n    if os.getenv(\"LANGCHAIN_API_KEY\"):\n        headers[\"x-api-key\"] = os.getenv(\"LANGCHAIN_API_KEY\")\n    return headers\ndef _get_endpoint() -> str:\n    return os.getenv(\"LANGCHAIN_ENDPOINT\", \"http://localhost:8000\")\n[docs]class LangChainTracerV1(BaseTracer):\n    \"\"\"An implementation of the SharedTracer that POSTS to the langchain endpoint.\"\"\"\n[docs]    def __init__(self, **kwargs: Any) -> None:\n        \"\"\"Initialize the LangChain tracer.\"\"\"\n        super().__init__(**kwargs)\n        self.session: Optional[TracerSessionV1] = None\n        self._endpoint = _get_endpoint()\n        self._headers = get_headers()\n    def _convert_to_v1_run(self, run: Run) -> Union[LLMRun, ChainRun, ToolRun]:\n        session = self.session or self.load_default_session()\n        if not isinstance(session, TracerSessionV1):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain_v1.html"}
{"id": "270fb32cca4e-1", "text": "if not isinstance(session, TracerSessionV1):\n            raise ValueError(\n                \"LangChainTracerV1 is not compatible with\"\n                f\" session of type {type(session)}\"\n            )\n        if run.run_type == \"llm\":\n            if \"prompts\" in run.inputs:\n                prompts = run.inputs[\"prompts\"]\n            elif \"messages\" in run.inputs:\n                prompts = [get_buffer_string(batch) for batch in run.inputs[\"messages\"]]\n            else:\n                raise ValueError(\"No prompts found in LLM run inputs\")\n            return LLMRun(\n                uuid=str(run.id) if run.id else None,\n                parent_uuid=str(run.parent_run_id) if run.parent_run_id else None,\n                start_time=run.start_time,\n                end_time=run.end_time,\n                extra=run.extra,\n                execution_order=run.execution_order,\n                child_execution_order=run.child_execution_order,\n                serialized=run.serialized,\n                session_id=session.id,\n                error=run.error,\n                prompts=prompts,\n                response=run.outputs if run.outputs else None,\n            )\n        if run.run_type == \"chain\":\n            child_runs = [self._convert_to_v1_run(run) for run in run.child_runs]\n            return ChainRun(\n                uuid=str(run.id) if run.id else None,\n                parent_uuid=str(run.parent_run_id) if run.parent_run_id else None,\n                start_time=run.start_time,\n                end_time=run.end_time,\n                execution_order=run.execution_order,\n                child_execution_order=run.child_execution_order,\n                serialized=run.serialized,\n                session_id=session.id,\n                inputs=run.inputs,\n                outputs=run.outputs,\n                error=run.error,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain_v1.html"}
{"id": "270fb32cca4e-2", "text": "outputs=run.outputs,\n                error=run.error,\n                extra=run.extra,\n                child_llm_runs=[run for run in child_runs if isinstance(run, LLMRun)],\n                child_chain_runs=[\n                    run for run in child_runs if isinstance(run, ChainRun)\n                ],\n                child_tool_runs=[run for run in child_runs if isinstance(run, ToolRun)],\n            )\n        if run.run_type == \"tool\":\n            child_runs = [self._convert_to_v1_run(run) for run in run.child_runs]\n            return ToolRun(\n                uuid=str(run.id) if run.id else None,\n                parent_uuid=str(run.parent_run_id) if run.parent_run_id else None,\n                start_time=run.start_time,\n                end_time=run.end_time,\n                execution_order=run.execution_order,\n                child_execution_order=run.child_execution_order,\n                serialized=run.serialized,\n                session_id=session.id,\n                action=str(run.serialized),\n                tool_input=run.inputs.get(\"input\", \"\"),\n                output=None if run.outputs is None else run.outputs.get(\"output\"),\n                error=run.error,\n                extra=run.extra,\n                child_chain_runs=[\n                    run for run in child_runs if isinstance(run, ChainRun)\n                ],\n                child_tool_runs=[run for run in child_runs if isinstance(run, ToolRun)],\n                child_llm_runs=[run for run in child_runs if isinstance(run, LLMRun)],\n            )\n        raise ValueError(f\"Unknown run type: {run.run_type}\")\n    def _persist_run(self, run: Union[Run, LLMRun, ChainRun, ToolRun]) -> None:\n        \"\"\"Persist a run.\"\"\"\n        if isinstance(run, Run):\n            v1_run = self._convert_to_v1_run(run)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain_v1.html"}
{"id": "270fb32cca4e-3", "text": "v1_run = self._convert_to_v1_run(run)\n        else:\n            v1_run = run\n        if isinstance(v1_run, LLMRun):\n            endpoint = f\"{self._endpoint}/llm-runs\"\n        elif isinstance(v1_run, ChainRun):\n            endpoint = f\"{self._endpoint}/chain-runs\"\n        else:\n            endpoint = f\"{self._endpoint}/tool-runs\"\n        try:\n            response = requests.post(\n                endpoint,\n                data=v1_run.json(),\n                headers=self._headers,\n            )\n            raise_for_status_with_text(response)\n        except Exception as e:\n            logger.warning(f\"Failed to persist run: {e}\")\n    def _persist_session(\n        self, session_create: TracerSessionV1Base\n    ) -> Union[TracerSessionV1, TracerSession]:\n        \"\"\"Persist a session.\"\"\"\n        try:\n            r = requests.post(\n                f\"{self._endpoint}/sessions\",\n                data=session_create.json(),\n                headers=self._headers,\n            )\n            session = TracerSessionV1(id=r.json()[\"id\"], **session_create.dict())\n        except Exception as e:\n            logger.warning(f\"Failed to create session, using default session: {e}\")\n            session = TracerSessionV1(id=1, **session_create.dict())\n        return session\n    def _load_session(self, session_name: Optional[str] = None) -> TracerSessionV1:\n        \"\"\"Load a session from the tracer.\"\"\"\n        try:\n            url = f\"{self._endpoint}/sessions\"\n            if session_name:\n                url += f\"?name={session_name}\"\n            r = requests.get(url, headers=self._headers)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain_v1.html"}
{"id": "270fb32cca4e-4", "text": "r = requests.get(url, headers=self._headers)\n            tracer_session = TracerSessionV1(**r.json()[0])\n        except Exception as e:\n            session_type = \"default\" if not session_name else session_name\n            logger.warning(\n                f\"Failed to load {session_type} session, using empty session: {e}\"\n            )\n            tracer_session = TracerSessionV1(id=1)\n        self.session = tracer_session\n        return tracer_session\n[docs]    def load_session(self, session_name: str) -> Union[TracerSessionV1, TracerSession]:\n        \"\"\"Load a session with the given name from the tracer.\"\"\"\n        return self._load_session(session_name)\n[docs]    def load_default_session(self) -> Union[TracerSessionV1, TracerSession]:\n        \"\"\"Load the default tracing session and set it as the Tracer's session.\"\"\"\n        return self._load_session(\"default\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain_v1.html"}
{"id": "6ca47b79a450-0", "text": "Source code for langchain.schema.runnable.passthrough\n\"\"\"Implementation of the RunnablePassthrough.\"\"\"\nfrom __future__ import annotations\nimport asyncio\nimport inspect\nimport threading\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Awaitable,\n    Callable,\n    Dict,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Type,\n    Union,\n    cast,\n)\nfrom langchain.pydantic_v1 import BaseModel, create_model\nfrom langchain.schema.runnable.base import (\n    Other,\n    Runnable,\n    RunnableParallel,\n    RunnableSerializable,\n)\nfrom langchain.schema.runnable.config import (\n    RunnableConfig,\n    acall_func_with_variable_args,\n    call_func_with_variable_args,\n    get_executor_for_config,\n)\nfrom langchain.schema.runnable.utils import AddableDict, ConfigurableFieldSpec\nfrom langchain.utils.aiter import atee, py_anext\nfrom langchain.utils.iter import safetee\n[docs]def identity(x: Other) -> Other:\n    \"\"\"An identity function\"\"\"\n    return x\n[docs]async def aidentity(x: Other) -> Other:\n    \"\"\"An async identity function\"\"\"\n    return x\n[docs]class RunnablePassthrough(RunnableSerializable[Other, Other]):\n    \"\"\"A runnable to passthrough inputs unchanged or with additional keys.\n    This runnable behaves almost like the identity function, except that it\n    can be configured to add additional keys to the output, if the input is a\n    dict.\n    The examples below demonstrate this runnable works using a few simple\n    chains. The chains rely on simple lambdas to make the examples easy to execute\n    and experiment with.\n    Examples:\n        .. code-block:: python", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html"}
{"id": "6ca47b79a450-1", "text": "and experiment with.\n    Examples:\n        .. code-block:: python\n            from langchain.schema.runnable import RunnablePassthrough, RunnableParallel\n            runnable = RunnableParallel(\n                origin=RunnablePassthrough(),\n                modified=lambda x: x+1\n            )\n            runnable.invoke(1) # {'origin': 1, 'modified': 2}\n             def fake_llm(prompt: str) -> str: # Fake LLM for the example\n                return \"completion\"\n            chain = RunnableLambda(fake_llm) | {\n                'original': RunnablePassthrough(), # Original LLM output\n                'parsed': lambda text: text[::-1] # Parsing logic\n            }\n            chain.invoke('hello') # {'original': 'completion', 'parsed': 'noitelpmoc'}\n    In some cases, it may be useful to pass the input through while adding some\n    keys to the output. In this case, you can use the `assign` method:\n        .. code-block:: python\n            from langchain.schema.runnable import RunnablePassthrough, RunnableParallel\n             def fake_llm(prompt: str) -> str: # Fake LLM for the example\n                return \"completion\"\n            runnable = {\n                'llm1':  fake_llm,\n                'llm2':  fake_llm,\n            }\n            | RunnablePassthrough.assign(\n                total_chars=lambda inputs: len(inputs['llm1'] + inputs['llm2'])\n              )\n            runnable.invoke('hello')\n            # {'llm1': 'completion', 'llm2': 'completion', 'total_chars': 20}\n    \"\"\"\n    input_type: Optional[Type[Other]] = None\n    func: Optional[\n        Union[Callable[[Other], None], Callable[[Other, RunnableConfig], None]]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html"}
{"id": "6ca47b79a450-2", "text": "Union[Callable[[Other], None], Callable[[Other, RunnableConfig], None]]\n    ] = None\n    afunc: Optional[\n        Union[\n            Callable[[Other], Awaitable[None]],\n            Callable[[Other, RunnableConfig], Awaitable[None]],\n        ]\n    ] = None\n    def __init__(\n        self,\n        func: Optional[\n            Union[\n                Union[Callable[[Other], None], Callable[[Other, RunnableConfig], None]],\n                Union[\n                    Callable[[Other], Awaitable[None]],\n                    Callable[[Other, RunnableConfig], Awaitable[None]],\n                ],\n            ]\n        ] = None,\n        afunc: Optional[\n            Union[\n                Callable[[Other], Awaitable[None]],\n                Callable[[Other, RunnableConfig], Awaitable[None]],\n            ]\n        ] = None,\n        *,\n        input_type: Optional[Type[Other]] = None,\n        **kwargs: Any,\n    ) -> None:\n        if inspect.iscoroutinefunction(func):\n            afunc = func\n            func = None\n        super().__init__(func=func, afunc=afunc, input_type=input_type, **kwargs)\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n[docs]    @classmethod\n    def get_lc_namespace(cls) -> List[str]:\n        return cls.__module__.split(\".\")[:-1]\n    @property\n    def InputType(self) -> Any:\n        return self.input_type or Any\n    @property\n    def OutputType(self) -> Any:\n        return self.input_type or Any\n[docs]    @classmethod\n    def assign(\n        cls,\n        **kwargs: Union[\n            Runnable[Dict[str, Any], Any],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html"}
{"id": "6ca47b79a450-3", "text": "**kwargs: Union[\n            Runnable[Dict[str, Any], Any],\n            Callable[[Dict[str, Any]], Any],\n            Mapping[\n                str,\n                Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any]],\n            ],\n        ],\n    ) -> RunnableAssign:\n        \"\"\"Merge the Dict input with the output produced by the mapping argument.\n        Args:\n            mapping: A mapping from keys to runnables or callables.\n        Returns:\n            A runnable that merges the Dict input with the output produced by the\n            mapping argument.\n        \"\"\"\n        return RunnableAssign(RunnableParallel(kwargs))\n[docs]    def invoke(\n        self, input: Other, config: Optional[RunnableConfig] = None, **kwargs: Any\n    ) -> Other:\n        if self.func is not None:\n            call_func_with_variable_args(self.func, input, config or {}, **kwargs)\n        return self._call_with_config(identity, input, config)\n[docs]    async def ainvoke(\n        self,\n        input: Other,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Other:\n        if self.afunc is not None:\n            await acall_func_with_variable_args(\n                self.afunc, input, config or {}, **kwargs\n            )\n        elif self.func is not None:\n            call_func_with_variable_args(self.func, input, config or {}, **kwargs)\n        return await self._acall_with_config(aidentity, input, config)\n[docs]    def transform(\n        self,\n        input: Iterator[Other],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Iterator[Other]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html"}
{"id": "6ca47b79a450-4", "text": "**kwargs: Any,\n    ) -> Iterator[Other]:\n        if self.func is None:\n            for chunk in self._transform_stream_with_config(input, identity, config):\n                yield chunk\n        else:\n            final = None\n            for chunk in self._transform_stream_with_config(input, identity, config):\n                yield chunk\n                if final is None:\n                    final = chunk\n                else:\n                    final = final + chunk\n            if final is not None:\n                call_func_with_variable_args(self.func, final, config or {}, **kwargs)\n[docs]    async def atransform(\n        self,\n        input: AsyncIterator[Other],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[Other]:\n        if self.afunc is None and self.func is None:\n            async for chunk in self._atransform_stream_with_config(\n                input, identity, config\n            ):\n                yield chunk\n        else:\n            final = None\n            async for chunk in self._atransform_stream_with_config(\n                input, identity, config\n            ):\n                yield chunk\n                if final is None:\n                    final = chunk\n                else:\n                    final = final + chunk\n            if final is not None:\n                config = config or {}\n                if self.afunc is not None:\n                    await acall_func_with_variable_args(\n                        self.afunc, final, config, **kwargs\n                    )\n                elif self.func is not None:\n                    call_func_with_variable_args(self.func, final, config, **kwargs)\n[docs]    def stream(\n        self,\n        input: Other,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Iterator[Other]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html"}
{"id": "6ca47b79a450-5", "text": "**kwargs: Any,\n    ) -> Iterator[Other]:\n        return self.transform(iter([input]), config, **kwargs)\n[docs]    async def astream(\n        self,\n        input: Other,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[Other]:\n        async def input_aiter() -> AsyncIterator[Other]:\n            yield input\n        async for chunk in self.atransform(input_aiter(), config, **kwargs):\n            yield chunk\n[docs]class RunnableAssign(RunnableSerializable[Dict[str, Any], Dict[str, Any]]):\n    \"\"\"\n    A runnable that assigns key-value pairs to Dict[str, Any] inputs.\n    \"\"\"\n    mapper: RunnableParallel[Dict[str, Any]]\n    def __init__(self, mapper: RunnableParallel[Dict[str, Any]], **kwargs: Any) -> None:\n        super().__init__(mapper=mapper, **kwargs)\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n[docs]    @classmethod\n    def get_lc_namespace(cls) -> List[str]:\n        return cls.__module__.split(\".\")[:-1]\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        map_input_schema = self.mapper.get_input_schema(config)\n        if not map_input_schema.__custom_root_type__:\n            # ie. it's a dict\n            return map_input_schema\n        return super().get_input_schema(config)\n[docs]    def get_output_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        map_input_schema = self.mapper.get_input_schema(config)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html"}
{"id": "6ca47b79a450-6", "text": "map_input_schema = self.mapper.get_input_schema(config)\n        map_output_schema = self.mapper.get_output_schema(config)\n        if (\n            not map_input_schema.__custom_root_type__\n            and not map_output_schema.__custom_root_type__\n        ):\n            # ie. both are dicts\n            return create_model(  # type: ignore[call-overload]\n                \"RunnableAssignOutput\",\n                **{\n                    k: (v.type_, v.default)\n                    for s in (map_input_schema, map_output_schema)\n                    for k, v in s.__fields__.items()\n                },\n            )\n        elif not map_output_schema.__custom_root_type__:\n            # ie. only map output is a dict\n            # ie. input type is either unknown or inferred incorrectly\n            return map_output_schema\n        return super().get_output_schema(config)\n    @property\n    def config_specs(self) -> List[ConfigurableFieldSpec]:\n        return self.mapper.config_specs\n[docs]    def invoke(\n        self,\n        input: Dict[str, Any],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Dict[str, Any]:\n        assert isinstance(\n            input, dict\n        ), \"The input to RunnablePassthrough.assign() must be a dict.\"\n        return {\n            **input,\n            **self.mapper.invoke(input, config, **kwargs),\n        }\n[docs]    async def ainvoke(\n        self,\n        input: Dict[str, Any],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Dict[str, Any]:\n        assert isinstance(\n            input, dict\n        ), \"The input to RunnablePassthrough.assign() must be a dict.\"\n        return {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html"}
{"id": "6ca47b79a450-7", "text": "return {\n            **input,\n            **await self.mapper.ainvoke(input, config, **kwargs),\n        }\n[docs]    def transform(\n        self,\n        input: Iterator[Dict[str, Any]],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Iterator[Dict[str, Any]]:\n        # collect mapper keys\n        mapper_keys = set(self.mapper.steps.keys())\n        # create two streams, one for the map and one for the passthrough\n        for_passthrough, for_map = safetee(input, 2, lock=threading.Lock())\n        # create map output stream\n        map_output = self.mapper.transform(for_map, config, **kwargs)\n        # get executor to start map output stream in background\n        with get_executor_for_config(config or {}) as executor:\n            # start map output stream\n            first_map_chunk_future = executor.submit(\n                next,\n                map_output,  # type: ignore\n                None,\n            )\n            # consume passthrough stream\n            for chunk in for_passthrough:\n                assert isinstance(\n                    chunk, dict\n                ), \"The input to RunnablePassthrough.assign() must be a dict.\"\n                # remove mapper keys from passthrough chunk, to be overwritten by map\n                filtered = AddableDict(\n                    {k: v for k, v in chunk.items() if k not in mapper_keys}\n                )\n                if filtered:\n                    yield filtered\n            # yield map output\n            yield cast(Dict[str, Any], first_map_chunk_future.result())\n            for chunk in map_output:\n                yield chunk\n[docs]    async def atransform(\n        self,\n        input: AsyncIterator[Dict[str, Any]],\n        config: Optional[RunnableConfig] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html"}
{"id": "6ca47b79a450-8", "text": "config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[Dict[str, Any]]:\n        # collect mapper keys\n        mapper_keys = set(self.mapper.steps.keys())\n        # create two streams, one for the map and one for the passthrough\n        for_passthrough, for_map = atee(input, 2, lock=asyncio.Lock())\n        # create map output stream\n        map_output = self.mapper.atransform(for_map, config, **kwargs)\n        # start map output stream\n        first_map_chunk_task: asyncio.Task = asyncio.create_task(\n            py_anext(map_output, None),  # type: ignore[arg-type]\n        )\n        # consume passthrough stream\n        async for chunk in for_passthrough:\n            assert isinstance(\n                chunk, dict\n            ), \"The input to RunnablePassthrough.assign() must be a dict.\"\n            # remove mapper keys from passthrough chunk, to be overwritten by map output\n            filtered = AddableDict(\n                {k: v for k, v in chunk.items() if k not in mapper_keys}\n            )\n            if filtered:\n                yield filtered\n        # yield map output\n        yield await first_map_chunk_task\n        async for chunk in map_output:\n            yield chunk\n[docs]    def stream(\n        self,\n        input: Dict[str, Any],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Iterator[Dict[str, Any]]:\n        return self.transform(iter([input]), config, **kwargs)\n[docs]    async def astream(\n        self,\n        input: Dict[str, Any],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html"}
{"id": "6ca47b79a450-9", "text": "config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[Dict[str, Any]]:\n        async def input_aiter() -> AsyncIterator[Dict[str, Any]]:\n            yield input\n        async for chunk in self.atransform(input_aiter(), config, **kwargs):\n            yield chunk", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html"}
{"id": "c902d3a2c232-0", "text": "Source code for langchain.schema.runnable.retry\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Dict,\n    List,\n    Optional,\n    Tuple,\n    Type,\n    TypeVar,\n    Union,\n    cast,\n)\nfrom tenacity import (\n    AsyncRetrying,\n    RetryCallState,\n    RetryError,\n    Retrying,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential_jitter,\n)\nfrom langchain.schema.runnable.base import Input, Output, RunnableBindingBase\nfrom langchain.schema.runnable.config import RunnableConfig, patch_config\nif TYPE_CHECKING:\n    from langchain.callbacks.manager import (\n        AsyncCallbackManagerForChainRun,\n        CallbackManagerForChainRun,\n    )\n    T = TypeVar(\"T\", CallbackManagerForChainRun, AsyncCallbackManagerForChainRun)\nU = TypeVar(\"U\")\n[docs]class RunnableRetry(RunnableBindingBase[Input, Output]):\n    \"\"\"Retry a Runnable if it fails.\n    A RunnableRetry helps can be used to add retry logic to any object\n    that subclasses the base Runnable.\n    Such retries are especially useful for network calls that may fail\n    due to transient errors.\n    The RunnableRetry is implemented as a RunnableBinding. The easiest\n    way to use it is through the `.with_retry()` method on all Runnables.\n    Example:\n    Here's an example that uses a RunnableLambda to raise an exception\n        .. code-block:: python\n            import time\n            def foo(input) -> None:\n                '''Fake function that raises an exception.'''\n                raise ValueError(\"Invoking foo failed. At time {time.time()}\")\n            runnable = RunnableLambda(foo)\n            runnable_with_retries = runnable.with_retry(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html"}
{"id": "c902d3a2c232-1", "text": "runnable = RunnableLambda(foo)\n            runnable_with_retries = runnable.with_retry(\n                retry_exception_types=(ValueError,), # Retry only on ValueError\n                wait_exponential_jitter=True, # Add jitter to the exponential backoff\n                max_attempt_number=2, # Try twice\n            )\n            # The method invocation above is equivalent to the longer form below:\n            runnable_with_retries = RunnableRetry(\n                bound=runnable,\n                retry_exception_types=(ValueError,),\n                max_attempt_number=2,\n                wait_exponential_jitter=True\n            )\n    This logic can be used to retry any Runnable, including a chain of Runnables,\n    but in general it's best practice to keep the scope of the retry as small as\n    possible. For example, if you have a chain of Runnables, you should only retry\n    the Runnable that is likely to fail, not the entire chain.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models import ChatOpenAI\n            from langchain.prompts import PromptTemplate\n            template = PromptTemplate.from_template(\"tell me a joke about {topic}.\")\n            model = ChatOpenAI(temperature=0.5)\n            # Good\n            chain = template | model.with_retry()\n            # Bad\n            chain = template | model\n            retryable_chain = chain.with_retry()\n    \"\"\"\n    retry_exception_types: Tuple[Type[BaseException], ...] = (Exception,)\n    \"\"\"The exception types to retry on. By default all exceptions are retried.\n    \n    In general you should only retry on exceptions that are likely to be\n    transient, such as network errors.\n    \n    Good exceptions to retry are all server errors (5xx) and selected client\n    errors (4xx) such as 429 Too Many Requests.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html"}
{"id": "c902d3a2c232-2", "text": "errors (4xx) such as 429 Too Many Requests.\n    \"\"\"\n    wait_exponential_jitter: bool = True\n    \"\"\"Whether to add jitter to the exponential backoff.\"\"\"\n    max_attempt_number: int = 3\n    \"\"\"The maximum number of attempts to retry the runnable.\"\"\"\n    @property\n    def _kwargs_retrying(self) -> Dict[str, Any]:\n        kwargs: Dict[str, Any] = dict()\n        if self.max_attempt_number:\n            kwargs[\"stop\"] = stop_after_attempt(self.max_attempt_number)\n        if self.wait_exponential_jitter:\n            kwargs[\"wait\"] = wait_exponential_jitter()\n        if self.retry_exception_types:\n            kwargs[\"retry\"] = retry_if_exception_type(self.retry_exception_types)\n        return kwargs\n    def _sync_retrying(self, **kwargs: Any) -> Retrying:\n        return Retrying(**self._kwargs_retrying, **kwargs)\n    def _async_retrying(self, **kwargs: Any) -> AsyncRetrying:\n        return AsyncRetrying(**self._kwargs_retrying, **kwargs)\n    def _patch_config(\n        self,\n        config: RunnableConfig,\n        run_manager: \"T\",\n        retry_state: RetryCallState,\n    ) -> RunnableConfig:\n        attempt = retry_state.attempt_number\n        tag = \"retry:attempt:{}\".format(attempt) if attempt > 1 else None\n        return patch_config(config, callbacks=run_manager.get_child(tag))\n    def _patch_config_list(\n        self,\n        config: List[RunnableConfig],\n        run_manager: List[\"T\"],\n        retry_state: RetryCallState,\n    ) -> List[RunnableConfig]:\n        return [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html"}
{"id": "c902d3a2c232-3", "text": ") -> List[RunnableConfig]:\n        return [\n            self._patch_config(c, rm, retry_state) for c, rm in zip(config, run_manager)\n        ]\n    def _invoke(\n        self,\n        input: Input,\n        run_manager: \"CallbackManagerForChainRun\",\n        config: RunnableConfig,\n        **kwargs: Any,\n    ) -> Output:\n        for attempt in self._sync_retrying(reraise=True):\n            with attempt:\n                result = super().invoke(\n                    input,\n                    self._patch_config(config, run_manager, attempt.retry_state),\n                    **kwargs,\n                )\n            if attempt.retry_state.outcome and not attempt.retry_state.outcome.failed:\n                attempt.retry_state.set_result(result)\n        return result\n[docs]    def invoke(\n        self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any\n    ) -> Output:\n        return self._call_with_config(self._invoke, input, config, **kwargs)\n    async def _ainvoke(\n        self,\n        input: Input,\n        run_manager: \"AsyncCallbackManagerForChainRun\",\n        config: RunnableConfig,\n        **kwargs: Any,\n    ) -> Output:\n        async for attempt in self._async_retrying(reraise=True):\n            with attempt:\n                result = await super().ainvoke(\n                    input,\n                    self._patch_config(config, run_manager, attempt.retry_state),\n                    **kwargs,\n                )\n            if attempt.retry_state.outcome and not attempt.retry_state.outcome.failed:\n                attempt.retry_state.set_result(result)\n        return result\n[docs]    async def ainvoke(\n        self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html"}
{"id": "c902d3a2c232-4", "text": ") -> Output:\n        return await self._acall_with_config(self._ainvoke, input, config, **kwargs)\n    def _batch(\n        self,\n        inputs: List[Input],\n        run_manager: List[\"CallbackManagerForChainRun\"],\n        config: List[RunnableConfig],\n        **kwargs: Any,\n    ) -> List[Union[Output, Exception]]:\n        results_map: Dict[int, Output] = {}\n        def pending(iterable: List[U]) -> List[U]:\n            return [item for idx, item in enumerate(iterable) if idx not in results_map]\n        try:\n            for attempt in self._sync_retrying():\n                with attempt:\n                    # Get the results of the inputs that have not succeeded yet.\n                    result = super().batch(\n                        pending(inputs),\n                        self._patch_config_list(\n                            pending(config), pending(run_manager), attempt.retry_state\n                        ),\n                        return_exceptions=True,\n                        **kwargs,\n                    )\n                    # Register the results of the inputs that have succeeded.\n                    first_exception = None\n                    for i, r in enumerate(result):\n                        if isinstance(r, Exception):\n                            if not first_exception:\n                                first_exception = r\n                            continue\n                        results_map[i] = r\n                    # If any exception occurred, raise it, to retry the failed ones\n                    if first_exception:\n                        raise first_exception\n                if (\n                    attempt.retry_state.outcome\n                    and not attempt.retry_state.outcome.failed\n                ):\n                    attempt.retry_state.set_result(result)\n        except RetryError as e:\n            try:\n                result\n            except UnboundLocalError:\n                result = cast(List[Output], [e] * len(inputs))\n        outputs: List[Union[Output, Exception]] = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html"}
{"id": "c902d3a2c232-5", "text": "outputs: List[Union[Output, Exception]] = []\n        for idx, _ in enumerate(inputs):\n            if idx in results_map:\n                outputs.append(results_map[idx])\n            else:\n                outputs.append(result.pop(0))\n        return outputs\n[docs]    def batch(\n        self,\n        inputs: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Any,\n    ) -> List[Output]:\n        return self._batch_with_config(\n            self._batch, inputs, config, return_exceptions=return_exceptions, **kwargs\n        )\n    async def _abatch(\n        self,\n        inputs: List[Input],\n        run_manager: List[\"AsyncCallbackManagerForChainRun\"],\n        config: List[RunnableConfig],\n        **kwargs: Any,\n    ) -> List[Union[Output, Exception]]:\n        results_map: Dict[int, Output] = {}\n        def pending(iterable: List[U]) -> List[U]:\n            return [item for idx, item in enumerate(iterable) if idx not in results_map]\n        try:\n            async for attempt in self._async_retrying():\n                with attempt:\n                    # Get the results of the inputs that have not succeeded yet.\n                    result = await super().abatch(\n                        pending(inputs),\n                        self._patch_config_list(\n                            pending(config), pending(run_manager), attempt.retry_state\n                        ),\n                        return_exceptions=True,\n                        **kwargs,\n                    )\n                    # Register the results of the inputs that have succeeded.\n                    first_exception = None\n                    for i, r in enumerate(result):\n                        if isinstance(r, Exception):\n                            if not first_exception:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html"}
{"id": "c902d3a2c232-6", "text": "if isinstance(r, Exception):\n                            if not first_exception:\n                                first_exception = r\n                            continue\n                        results_map[i] = r\n                    # If any exception occurred, raise it, to retry the failed ones\n                    if first_exception:\n                        raise first_exception\n                if (\n                    attempt.retry_state.outcome\n                    and not attempt.retry_state.outcome.failed\n                ):\n                    attempt.retry_state.set_result(result)\n        except RetryError as e:\n            try:\n                result\n            except UnboundLocalError:\n                result = cast(List[Output], [e] * len(inputs))\n        outputs: List[Union[Output, Exception]] = []\n        for idx, _ in enumerate(inputs):\n            if idx in results_map:\n                outputs.append(results_map[idx])\n            else:\n                outputs.append(result.pop(0))\n        return outputs\n[docs]    async def abatch(\n        self,\n        inputs: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Any,\n    ) -> List[Output]:\n        return await self._abatch_with_config(\n            self._abatch, inputs, config, return_exceptions=return_exceptions, **kwargs\n        )\n    # stream() and transform() are not retried because retrying a stream\n    # is not very intuitive.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html"}
{"id": "053cd908fd61-0", "text": "Source code for langchain.schema.runnable.configurable\nfrom __future__ import annotations\nimport enum\nimport threading\nfrom abc import abstractmethod\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Callable,\n    Dict,\n    Iterator,\n    List,\n    Optional,\n    Sequence,\n    Type,\n    Union,\n    cast,\n)\nfrom weakref import WeakValueDictionary\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema.runnable.base import Runnable, RunnableSerializable\nfrom langchain.schema.runnable.config import (\n    RunnableConfig,\n    get_config_list,\n    get_executor_for_config,\n)\nfrom langchain.schema.runnable.utils import (\n    AnyConfigurableField,\n    ConfigurableField,\n    ConfigurableFieldMultiOption,\n    ConfigurableFieldSingleOption,\n    ConfigurableFieldSpec,\n    Input,\n    Output,\n    gather_with_concurrency,\n    get_unique_config_specs,\n)\n[docs]class DynamicRunnable(RunnableSerializable[Input, Output]):\n    \"\"\"A Serializable Runnable that can be dynamically configured.\"\"\"\n    default: RunnableSerializable[Input, Output]\n    class Config:\n        arbitrary_types_allowed = True\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n[docs]    @classmethod\n    def get_lc_namespace(cls) -> List[str]:\n        return cls.__module__.split(\".\")[:-1]\n    @property\n    def InputType(self) -> Type[Input]:\n        return self.default.InputType\n    @property\n    def OutputType(self) -> Type[Output]:\n        return self.default.OutputType\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html"}
{"id": "053cd908fd61-1", "text": ") -> Type[BaseModel]:\n        return self._prepare(config).get_input_schema(config)\n[docs]    def get_output_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        return self._prepare(config).get_output_schema(config)\n    @abstractmethod\n    def _prepare(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Runnable[Input, Output]:\n        ...\n[docs]    def invoke(\n        self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any\n    ) -> Output:\n        return self._prepare(config).invoke(input, config, **kwargs)\n[docs]    async def ainvoke(\n        self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any\n    ) -> Output:\n        return await self._prepare(config).ainvoke(input, config, **kwargs)\n[docs]    def batch(\n        self,\n        inputs: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        configs = get_config_list(config, len(inputs))\n        prepared = [self._prepare(c) for c in configs]\n        if all(p is self.default for p in prepared):\n            return self.default.batch(\n                inputs, config, return_exceptions=return_exceptions, **kwargs\n            )\n        if not inputs:\n            return []\n        configs = get_config_list(config, len(inputs))\n        def invoke(\n            bound: Runnable[Input, Output],\n            input: Input,\n            config: RunnableConfig,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html"}
{"id": "053cd908fd61-2", "text": "input: Input,\n            config: RunnableConfig,\n        ) -> Union[Output, Exception]:\n            if return_exceptions:\n                try:\n                    return bound.invoke(input, config, **kwargs)\n                except Exception as e:\n                    return e\n            else:\n                return bound.invoke(input, config, **kwargs)\n        # If there's only one input, don't bother with the executor\n        if len(inputs) == 1:\n            return cast(List[Output], [invoke(prepared[0], inputs[0], configs[0])])\n        with get_executor_for_config(configs[0]) as executor:\n            return cast(\n                List[Output], list(executor.map(invoke, prepared, inputs, configs))\n            )\n[docs]    async def abatch(\n        self,\n        inputs: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        configs = get_config_list(config, len(inputs))\n        prepared = [self._prepare(c) for c in configs]\n        if all(p is self.default for p in prepared):\n            return await self.default.abatch(\n                inputs, config, return_exceptions=return_exceptions, **kwargs\n            )\n        if not inputs:\n            return []\n        configs = get_config_list(config, len(inputs))\n        async def ainvoke(\n            bound: Runnable[Input, Output],\n            input: Input,\n            config: RunnableConfig,\n        ) -> Union[Output, Exception]:\n            if return_exceptions:\n                try:\n                    return await bound.ainvoke(input, config, **kwargs)\n                except Exception as e:\n                    return e", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html"}
{"id": "053cd908fd61-3", "text": "except Exception as e:\n                    return e\n            else:\n                return await bound.ainvoke(input, config, **kwargs)\n        coros = map(ainvoke, prepared, inputs, configs)\n        return await gather_with_concurrency(configs[0].get(\"max_concurrency\"), *coros)\n[docs]    def stream(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Iterator[Output]:\n        return self._prepare(config).stream(input, config, **kwargs)\n[docs]    async def astream(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> AsyncIterator[Output]:\n        async for chunk in self._prepare(config).astream(input, config, **kwargs):\n            yield chunk\n[docs]    def transform(\n        self,\n        input: Iterator[Input],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Iterator[Output]:\n        return self._prepare(config).transform(input, config, **kwargs)\n[docs]    async def atransform(\n        self,\n        input: AsyncIterator[Input],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> AsyncIterator[Output]:\n        async for chunk in self._prepare(config).atransform(input, config, **kwargs):\n            yield chunk\n[docs]class RunnableConfigurableFields(DynamicRunnable[Input, Output]):\n    \"\"\"A Runnable that can be dynamically configured.\"\"\"\n    fields: Dict[str, AnyConfigurableField]\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html"}
{"id": "053cd908fd61-4", "text": "fields: Dict[str, AnyConfigurableField]\n    @property\n    def config_specs(self) -> List[ConfigurableFieldSpec]:\n        return get_unique_config_specs(\n            [\n                ConfigurableFieldSpec(\n                    id=spec.id,\n                    name=spec.name,\n                    description=spec.description\n                    or self.default.__fields__[field_name].field_info.description,\n                    annotation=spec.annotation\n                    or self.default.__fields__[field_name].annotation,\n                    default=getattr(self.default, field_name),\n                )\n                if isinstance(spec, ConfigurableField)\n                else make_options_spec(\n                    spec, self.default.__fields__[field_name].field_info.description\n                )\n                for field_name, spec in self.fields.items()\n            ]\n            + list(self.default.config_specs)\n        )\n[docs]    def configurable_fields(\n        self, **kwargs: AnyConfigurableField\n    ) -> RunnableSerializable[Input, Output]:\n        return self.default.configurable_fields(**{**self.fields, **kwargs})\n    def _prepare(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Runnable[Input, Output]:\n        config = config or {}\n        specs_by_id = {spec.id: (key, spec) for key, spec in self.fields.items()}\n        configurable_fields = {\n            specs_by_id[k][0]: v\n            for k, v in config.get(\"configurable\", {}).items()\n            if k in specs_by_id and isinstance(specs_by_id[k][1], ConfigurableField)\n        }\n        configurable_single_options = {\n            k: v.options[(config.get(\"configurable\", {}).get(v.id) or v.default)]\n            for k, v in self.fields.items()\n            if isinstance(v, ConfigurableFieldSingleOption)\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html"}
{"id": "053cd908fd61-5", "text": "if isinstance(v, ConfigurableFieldSingleOption)\n        }\n        configurable_multi_options = {\n            k: [\n                v.options[o]\n                for o in config.get(\"configurable\", {}).get(v.id, v.default)\n            ]\n            for k, v in self.fields.items()\n            if isinstance(v, ConfigurableFieldMultiOption)\n        }\n        configurable = {\n            **configurable_fields,\n            **configurable_single_options,\n            **configurable_multi_options,\n        }\n        if configurable:\n            return self.default.__class__(**{**self.default.__dict__, **configurable})\n        else:\n            return self.default\n# Before Python 3.11 native StrEnum is not available\n[docs]class StrEnum(str, enum.Enum):\n    \"\"\"A string enum.\"\"\"\n    pass\n_enums_for_spec: WeakValueDictionary[\n    Union[\n        ConfigurableFieldSingleOption, ConfigurableFieldMultiOption, ConfigurableField\n    ],\n    Type[StrEnum],\n] = WeakValueDictionary()\n_enums_for_spec_lock = threading.Lock()\n[docs]class RunnableConfigurableAlternatives(DynamicRunnable[Input, Output]):\n    \"\"\"A Runnable that can be dynamically configured.\"\"\"\n    which: ConfigurableField\n    alternatives: Dict[\n        str,\n        Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]],\n    ]\n    default_key: str = \"default\"\n    @property\n    def config_specs(self) -> List[ConfigurableFieldSpec]:\n        with _enums_for_spec_lock:\n            if which_enum := _enums_for_spec.get(self.which):\n                pass\n            else:\n                which_enum = StrEnum(  # type: ignore[call-overload]\n                    self.which.name or self.which.id,\n                    (", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html"}
{"id": "053cd908fd61-6", "text": "self.which.name or self.which.id,\n                    (\n                        (v, v)\n                        for v in list(self.alternatives.keys()) + [self.default_key]\n                    ),\n                )\n                _enums_for_spec[self.which] = cast(Type[StrEnum], which_enum)\n        return [\n            ConfigurableFieldSpec(\n                id=self.which.id,\n                name=self.which.name,\n                description=self.which.description,\n                annotation=which_enum,\n                default=self.default_key,\n            ),\n            *self.default.config_specs,\n        ] + [\n            s\n            for alt in self.alternatives.values()\n            if isinstance(alt, RunnableSerializable)\n            for s in alt.config_specs\n        ]\n[docs]    def configurable_fields(\n        self, **kwargs: AnyConfigurableField\n    ) -> RunnableSerializable[Input, Output]:\n        return self.__class__(\n            which=self.which,\n            default=self.default.configurable_fields(**kwargs),\n            alternatives=self.alternatives,\n        )\n    def _prepare(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Runnable[Input, Output]:\n        config = config or {}\n        which = config.get(\"configurable\", {}).get(self.which.id, self.default_key)\n        if which == self.default_key:\n            return self.default\n        elif which in self.alternatives:\n            alt = self.alternatives[which]\n            if isinstance(alt, Runnable):\n                return alt\n            else:\n                return alt()\n        else:\n            raise ValueError(f\"Unknown alternative: {which}\")\n[docs]def make_options_spec(\n    spec: Union[ConfigurableFieldSingleOption, ConfigurableFieldMultiOption],\n    description: Optional[str],\n) -> ConfigurableFieldSpec:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html"}
{"id": "053cd908fd61-7", "text": "description: Optional[str],\n) -> ConfigurableFieldSpec:\n    \"\"\"Make a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or\n    ConfigurableFieldMultiOption.\"\"\"\n    with _enums_for_spec_lock:\n        if enum := _enums_for_spec.get(spec):\n            pass\n        else:\n            enum = StrEnum(  # type: ignore[call-overload]\n                spec.name or spec.id,\n                ((v, v) for v in list(spec.options.keys())),\n            )\n            _enums_for_spec[spec] = cast(Type[StrEnum], enum)\n    if isinstance(spec, ConfigurableFieldSingleOption):\n        return ConfigurableFieldSpec(\n            id=spec.id,\n            name=spec.name,\n            description=spec.description or description,\n            annotation=enum,\n            default=spec.default,\n        )\n    else:\n        return ConfigurableFieldSpec(\n            id=spec.id,\n            name=spec.name,\n            description=spec.description or description,\n            annotation=Sequence[enum],  # type: ignore[valid-type]\n            default=spec.default,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html"}
{"id": "7cd2723fa80e-0", "text": "Source code for langchain.schema.runnable.base\nfrom __future__ import annotations\nimport asyncio\nimport inspect\nimport threading\nfrom abc import ABC, abstractmethod\nfrom concurrent.futures import FIRST_COMPLETED, wait\nfrom functools import partial\nfrom itertools import tee\nfrom operator import itemgetter\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    AsyncIterator,\n    Awaitable,\n    Callable,\n    Dict,\n    Generic,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Sequence,\n    Tuple,\n    Type,\n    TypeVar,\n    Union,\n    cast,\n    overload,\n)\nfrom typing_extensions import Literal, get_args\nif TYPE_CHECKING:\n    from langchain.schema.callbacks.manager import (\n        AsyncCallbackManagerForChainRun,\n        CallbackManagerForChainRun,\n    )\n    from langchain.schema.callbacks.tracers.log_stream import RunLog, RunLogPatch\n    from langchain.schema.callbacks.tracers.root_listeners import Listener\n    from langchain.schema.runnable.fallbacks import (\n        RunnableWithFallbacks as RunnableWithFallbacksT,\n    )\nfrom langchain.load.dump import dumpd\nfrom langchain.load.serializable import Serializable\nfrom langchain.pydantic_v1 import BaseModel, Field, create_model\nfrom langchain.schema.runnable.config import (\n    RunnableConfig,\n    acall_func_with_variable_args,\n    call_func_with_variable_args,\n    ensure_config,\n    get_async_callback_manager_for_config,\n    get_callback_manager_for_config,\n    get_config_list,\n    get_executor_for_config,\n    merge_configs,\n    patch_config,\n)\nfrom langchain.schema.runnable.utils import (\n    AddableDict,\n    AnyConfigurableField,\n    ConfigurableField,\n    ConfigurableFieldSpec,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-1", "text": "AnyConfigurableField,\n    ConfigurableField,\n    ConfigurableFieldSpec,\n    Input,\n    Output,\n    accepts_config,\n    accepts_run_manager,\n    gather_with_concurrency,\n    get_function_first_arg_dict_keys,\n    get_lambda_source,\n    get_unique_config_specs,\n    indent_lines_after_first,\n)\nfrom langchain.utils.aiter import atee, py_anext\nfrom langchain.utils.iter import safetee\nOther = TypeVar(\"Other\")\n[docs]class Runnable(Generic[Input, Output], ABC):\n    \"\"\"A unit of work that can be invoked, batched, streamed, transformed and composed.\n     Key Methods\n     ===========\n    * invoke/ainvoke: Transforms a single input into an output.\n    * batch/abatch: Efficiently transforms multiple inputs into outputs.\n    * stream/astream: Streams output from a single input as it's produced.\n    * astream_log: Streams output and selected intermediate results from an input.\n    Built-in optimizations:\n    * Batch: By default, batch runs invoke() in parallel using a thread pool executor.\n             Override to optimize batching.\n    * Async: Methods with \"a\" suffix are asynchronous. By default, they execute\n             the sync counterpart using asyncio's thread pool.\n             Override for native async.\n    All methods accept an optional config argument, which can be used to configure\n    execution, add tags and metadata for tracing and debugging etc.\n    Runnables expose schematic information about their input, output and config via\n    the input_schema property, the output_schema property and config_schema method.\n    LCEL and Composition\n    ====================\n    The LangChain Expression Language (LCEL) is a declarative way to compose Runnables", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-2", "text": "into chains. Any chain constructed this way will automatically have sync, async,\n    batch, and streaming support.\n    The main composition primitives are RunnableSequence and RunnableParallel.\n    RunnableSequence invokes a series of runnables sequentially, with one runnable's\n    output serving as the next's input. Construct using the `|` operator or by\n    passing a list of runnables to RunnableSequence.\n    RunnableParallel invokes runnables concurrently, providing the same input\n    to each. Construct it using a dict literal within a sequence or by passing a\n    dict to RunnableParallel.\n    For example,\n    .. code-block:: python\n        from langchain.schema.runnable import RunnableLambda\n        # A RunnableSequence constructed using the `|` operator\n        sequence = RunnableLambda(lambda x: x + 1) | RunnableLambda(lambda x: x * 2)\n        sequence.invoke(1) # 4\n        sequence.batch([1, 2, 3]) # [4, 6, 8]\n        # A sequence that contains a RunnableParallel constructed using a dict literal\n        sequence = RunnableLambda(lambda x: x + 1) | {\n            'mul_2': RunnableLambda(lambda x: x * 2),\n            'mul_5': RunnableLambda(lambda x: x * 5)\n        }\n        sequence.invoke(1) # {'mul_2': 4, 'mul_5': 10}\n    Standard Methods\n    ================\n    All Runnables expose additional methods that can be used to modify their behavior\n    (e.g., add a retry policy, add lifecycle listeners, make them configurable, etc.).\n    These methods will work on any Runnable, including Runnable chains constructed\n    by composing other Runnables. See the individual methods for details.\n    For example,\n    .. code-block:: python", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-3", "text": "For example,\n    .. code-block:: python\n        from langchain.schema.runnable import RunnableLambda\n        import random\n        def add_one(x: int) -> int:\n            return x + 1\n        def buggy_double(y: int) -> int:\n            '''Buggy code that will fail 70% of the time'''\n            if random.random() > 0.3:\n                print('This code failed, and will probably be retried!')\n                raise ValueError('Triggered buggy code')\n            return y * 2\n        sequence = (\n            RunnableLambda(add_one) |\n            RunnableLambda(buggy_double).with_retry( # Retry on failure\n                stop_after_attempt=10,\n                wait_exponential_jitter=False\n            )\n        )\n        print(sequence.input_schema.schema()) # Show inferred input schema\n        print(sequence.output_schema.schema()) # Show inferred output schema\n        print(sequence.invoke(2)) # invoke the sequence (note the retry above!!)\n    Debugging and tracing\n    =====================\n    As the chains get longer, it can be useful to be able to see intermediate results\n    to debug and trace the chain.\n    You can set the global debug flag to True to enable debug output for all chains:\n        .. code-block:: python\n            from langchain.globals import set_debug\n            set_debug(True)\n    Alternatively, you can pass existing or custom callbacks to any given chain:\n       ... code-block:: python\n            from langchain.callbacks.tracers import ConsoleCallbackHandler\n            chain.invoke(\n                ...,\n                config={'callbacks': [ConsoleCallbackHandler()]}\n            )\n    For a UI (and much more) checkout LangSmith: https://docs.smith.langchain.com/\n    \"\"\"\n    @property\n    def InputType(self) -> Type[Input]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-4", "text": "\"\"\"\n    @property\n    def InputType(self) -> Type[Input]:\n        \"\"\"The type of input this runnable accepts specified as a type annotation.\"\"\"\n        for cls in self.__class__.__orig_bases__:  # type: ignore[attr-defined]\n            type_args = get_args(cls)\n            if type_args and len(type_args) == 2:\n                return type_args[0]\n        raise TypeError(\n            f\"Runnable {self.__class__.__name__} doesn't have an inferable InputType. \"\n            \"Override the InputType property to specify the input type.\"\n        )\n    @property\n    def OutputType(self) -> Type[Output]:\n        \"\"\"The type of output this runnable produces specified as a type annotation.\"\"\"\n        for cls in self.__class__.__orig_bases__:  # type: ignore[attr-defined]\n            type_args = get_args(cls)\n            if type_args and len(type_args) == 2:\n                return type_args[1]\n        raise TypeError(\n            f\"Runnable {self.__class__.__name__} doesn't have an inferable OutputType. \"\n            \"Override the OutputType property to specify the output type.\"\n        )\n    @property\n    def input_schema(self) -> Type[BaseModel]:\n        \"\"\"The type of input this runnable accepts specified as a pydantic model.\"\"\"\n        return self.get_input_schema()\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        \"\"\"Get a pydantic model that can be used to validate input to the runnable.\n        Runnables that leverage the configurable_fields and configurable_alternatives\n        methods will have a dynamic input schema that depends on which\n        configuration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-5", "text": "configuration the runnable is invoked with.\n        This method allows to get an input schema for a specific configuration.\n        Args:\n            config: A config to use when generating the schema.\n        Returns:\n            A pydantic model that can be used to validate input.\n        \"\"\"\n        root_type = self.InputType\n        if inspect.isclass(root_type) and issubclass(root_type, BaseModel):\n            return root_type\n        return create_model(\n            self.__class__.__name__ + \"Input\", __root__=(root_type, None)\n        )\n    @property\n    def output_schema(self) -> Type[BaseModel]:\n        \"\"\"The type of output this runnable produces specified as a pydantic model.\"\"\"\n        return self.get_output_schema()\n[docs]    def get_output_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        \"\"\"Get a pydantic model that can be used to validate output to the runnable.\n        Runnables that leverage the configurable_fields and configurable_alternatives\n        methods will have a dynamic output schema that depends on which\n        configuration the runnable is invoked with.\n        This method allows to get an output schema for a specific configuration.\n        Args:\n            config: A config to use when generating the schema.\n        Returns:\n            A pydantic model that can be used to validate output.\n        \"\"\"\n        root_type = self.OutputType\n        if inspect.isclass(root_type) and issubclass(root_type, BaseModel):\n            return root_type\n        return create_model(\n            self.__class__.__name__ + \"Output\", __root__=(root_type, None)\n        )\n    @property\n    def config_specs(self) -> List[ConfigurableFieldSpec]:\n        \"\"\"List configurable fields for this runnable.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-6", "text": "\"\"\"List configurable fields for this runnable.\"\"\"\n        return []\n[docs]    def config_schema(\n        self, *, include: Optional[Sequence[str]] = None\n    ) -> Type[BaseModel]:\n        \"\"\"The type of config this runnable accepts specified as a pydantic model.\n        To mark a field as configurable, see the `configurable_fields`\n        and `configurable_alternatives` methods.\n        Args:\n            include: A list of fields to include in the config schema.\n        Returns:\n            A pydantic model that can be used to validate config.\n        \"\"\"\n        class _Config:\n            arbitrary_types_allowed = True\n        include = include or []\n        config_specs = self.config_specs\n        configurable = (\n            create_model(  # type: ignore[call-overload]\n                \"Configurable\",\n                **{\n                    spec.id: (\n                        spec.annotation,\n                        Field(\n                            spec.default, title=spec.name, description=spec.description\n                        ),\n                    )\n                    for spec in config_specs\n                },\n            )\n            if config_specs\n            else None\n        )\n        return create_model(  # type: ignore[call-overload]\n            self.__class__.__name__ + \"Config\",\n            __config__=_Config,\n            **({\"configurable\": (configurable, None)} if configurable else {}),\n            **{\n                field_name: (field_type, None)\n                for field_name, field_type in RunnableConfig.__annotations__.items()\n                if field_name in [i for i in include if i != \"configurable\"]\n            },\n        )\n    def __or__(\n        self,\n        other: Union[\n            Runnable[Any, Other],\n            Callable[[Any], Other],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-7", "text": "Runnable[Any, Other],\n            Callable[[Any], Other],\n            Callable[[Iterator[Any]], Iterator[Other]],\n            Mapping[str, Union[Runnable[Any, Other], Callable[[Any], Other], Any]],\n        ],\n    ) -> RunnableSerializable[Input, Other]:\n        \"\"\"Compose this runnable with another object to create a RunnableSequence.\"\"\"\n        return RunnableSequence(first=self, last=coerce_to_runnable(other))\n    def __ror__(\n        self,\n        other: Union[\n            Runnable[Other, Any],\n            Callable[[Other], Any],\n            Callable[[Iterator[Other]], Iterator[Any]],\n            Mapping[str, Union[Runnable[Other, Any], Callable[[Other], Any], Any]],\n        ],\n    ) -> RunnableSerializable[Other, Output]:\n        \"\"\"Compose this runnable with another object to create a RunnableSequence.\"\"\"\n        return RunnableSequence(first=coerce_to_runnable(other), last=self)\n    \"\"\" --- Public API --- \"\"\"\n[docs]    @abstractmethod\n    def invoke(self, input: Input, config: Optional[RunnableConfig] = None) -> Output:\n        \"\"\"Transform a single input into an output. Override to implement.\n        Args:\n            input: The input to the runnable.\n            config: A config to use when invoking the runnable.\n               The config supports standard keys like 'tags', 'metadata' for tracing\n               purposes, 'max_concurrency' for controlling how much work to do\n               in parallel, and other keys. Please refer to the RunnableConfig\n               for more details.\n        Returns:\n            The output of the runnable.\n        \"\"\"\n[docs]    async def ainvoke(\n        self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any\n    ) -> Output:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-8", "text": ") -> Output:\n        \"\"\"Default implementation of ainvoke, calls invoke from a thread.\n        The default implementation allows usage of async code even if\n        the runnable did not implement a native async version of invoke.\n        Subclasses should override this method if they can run asynchronously.\n        \"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, partial(self.invoke, **kwargs), input, config\n        )\n[docs]    def batch(\n        self,\n        inputs: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        \"\"\"Default implementation runs invoke in parallel using a thread pool executor.\n        The default implementation of batch works well for IO bound runnables.\n        Subclasses should override this method if they can batch more efficiently;\n        e.g., if the underlying runnable uses an API which supports a batch mode.\n        \"\"\"\n        if not inputs:\n            return []\n        configs = get_config_list(config, len(inputs))\n        def invoke(input: Input, config: RunnableConfig) -> Union[Output, Exception]:\n            if return_exceptions:\n                try:\n                    return self.invoke(input, config, **kwargs)\n                except Exception as e:\n                    return e\n            else:\n                return self.invoke(input, config, **kwargs)\n        # If there's only one input, don't bother with the executor\n        if len(inputs) == 1:\n            return cast(List[Output], [invoke(inputs[0], configs[0])])\n        with get_executor_for_config(configs[0]) as executor:\n            return cast(List[Output], list(executor.map(invoke, inputs, configs)))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-9", "text": "return cast(List[Output], list(executor.map(invoke, inputs, configs)))\n[docs]    async def abatch(\n        self,\n        inputs: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        \"\"\"Default implementation runs ainvoke in parallel using asyncio.gather.\n        The default implementation of batch works well for IO bound runnables.\n        Subclasses should override this method if they can batch more efficiently;\n        e.g., if the underlying runnable uses an API which supports a batch mode.\n        \"\"\"\n        if not inputs:\n            return []\n        configs = get_config_list(config, len(inputs))\n        async def ainvoke(\n            input: Input, config: RunnableConfig\n        ) -> Union[Output, Exception]:\n            if return_exceptions:\n                try:\n                    return await self.ainvoke(input, config, **kwargs)\n                except Exception as e:\n                    return e\n            else:\n                return await self.ainvoke(input, config, **kwargs)\n        coros = map(ainvoke, inputs, configs)\n        return await gather_with_concurrency(configs[0].get(\"max_concurrency\"), *coros)\n[docs]    def stream(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Iterator[Output]:\n        \"\"\"\n        Default implementation of stream, which calls invoke.\n        Subclasses should override this method if they support streaming output.\n        \"\"\"\n        yield self.invoke(input, config, **kwargs)\n[docs]    async def astream(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-10", "text": "[docs]    async def astream(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> AsyncIterator[Output]:\n        \"\"\"\n        Default implementation of astream, which calls ainvoke.\n        Subclasses should override this method if they support streaming output.\n        \"\"\"\n        yield await self.ainvoke(input, config, **kwargs)\n    @overload\n    def astream_log(\n        self,\n        input: Any,\n        config: Optional[RunnableConfig] = None,\n        *,\n        diff: Literal[True] = True,\n        include_names: Optional[Sequence[str]] = None,\n        include_types: Optional[Sequence[str]] = None,\n        include_tags: Optional[Sequence[str]] = None,\n        exclude_names: Optional[Sequence[str]] = None,\n        exclude_types: Optional[Sequence[str]] = None,\n        exclude_tags: Optional[Sequence[str]] = None,\n        **kwargs: Optional[Any],\n    ) -> AsyncIterator[RunLogPatch]:\n        ...\n    @overload\n    def astream_log(\n        self,\n        input: Any,\n        config: Optional[RunnableConfig] = None,\n        *,\n        diff: Literal[False],\n        include_names: Optional[Sequence[str]] = None,\n        include_types: Optional[Sequence[str]] = None,\n        include_tags: Optional[Sequence[str]] = None,\n        exclude_names: Optional[Sequence[str]] = None,\n        exclude_types: Optional[Sequence[str]] = None,\n        exclude_tags: Optional[Sequence[str]] = None,\n        **kwargs: Optional[Any],\n    ) -> AsyncIterator[RunLog]:\n        ...\n[docs]    async def astream_log(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-11", "text": "...\n[docs]    async def astream_log(\n        self,\n        input: Any,\n        config: Optional[RunnableConfig] = None,\n        *,\n        diff: bool = True,\n        include_names: Optional[Sequence[str]] = None,\n        include_types: Optional[Sequence[str]] = None,\n        include_tags: Optional[Sequence[str]] = None,\n        exclude_names: Optional[Sequence[str]] = None,\n        exclude_types: Optional[Sequence[str]] = None,\n        exclude_tags: Optional[Sequence[str]] = None,\n        **kwargs: Optional[Any],\n    ) -> Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]:\n        \"\"\"\n        Stream all output from a runnable, as reported to the callback system.\n        This includes all inner runs of LLMs, Retrievers, Tools, etc.\n        Output is streamed as Log objects, which include a list of\n        jsonpatch ops that describe how the state of the run has changed in each\n        step, and the final state of the run.\n        The jsonpatch ops can be applied in order to construct state.\n        \"\"\"\n        from langchain.callbacks.base import BaseCallbackManager\n        from langchain.callbacks.tracers.log_stream import (\n            LogStreamCallbackHandler,\n            RunLog,\n            RunLogPatch,\n        )\n        # Create a stream handler that will emit Log objects\n        stream = LogStreamCallbackHandler(\n            auto_close=False,\n            include_names=include_names,\n            include_types=include_types,\n            include_tags=include_tags,\n            exclude_names=exclude_names,\n            exclude_types=exclude_types,\n            exclude_tags=exclude_tags,\n        )\n        # Assign the stream handler to the config\n        config = config or {}\n        callbacks = config.get(\"callbacks\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-12", "text": "config = config or {}\n        callbacks = config.get(\"callbacks\")\n        if callbacks is None:\n            config[\"callbacks\"] = [stream]\n        elif isinstance(callbacks, list):\n            config[\"callbacks\"] = callbacks + [stream]\n        elif isinstance(callbacks, BaseCallbackManager):\n            callbacks = callbacks.copy()\n            callbacks.add_handler(stream, inherit=True)\n            config[\"callbacks\"] = callbacks\n        else:\n            raise ValueError(\n                f\"Unexpected type for callbacks: {callbacks}.\"\n                \"Expected None, list or AsyncCallbackManager.\"\n            )\n        # Call the runnable in streaming mode,\n        # add each chunk to the output stream\n        async def consume_astream() -> None:\n            try:\n                async for chunk in self.astream(input, config, **kwargs):\n                    await stream.send_stream.send(\n                        RunLogPatch(\n                            {\n                                \"op\": \"add\",\n                                \"path\": \"/streamed_output/-\",\n                                \"value\": chunk,\n                            }\n                        )\n                    )\n            finally:\n                await stream.send_stream.aclose()\n        # Start the runnable in a task, so we can start consuming output\n        task = asyncio.create_task(consume_astream())\n        try:\n            # Yield each chunk from the output stream\n            if diff:\n                async for log in stream:\n                    yield log\n            else:\n                state = RunLog(state=None)  # type: ignore[arg-type]\n                async for log in stream:\n                    state = state + log\n                    yield state\n        finally:\n            # Wait for the runnable to finish, if not cancelled (eg. by break)\n            try:\n                await task\n            except asyncio.CancelledError:\n                pass\n[docs]    def transform(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-13", "text": "pass\n[docs]    def transform(\n        self,\n        input: Iterator[Input],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Iterator[Output]:\n        \"\"\"\n        Default implementation of transform, which buffers input and then calls stream.\n        Subclasses should override this method if they can start producing output while\n        input is still being generated.\n        \"\"\"\n        final: Input\n        got_first_val = False\n        for chunk in input:\n            if not got_first_val:\n                final = chunk\n                got_first_val = True\n            else:\n                # Make a best effort to gather, for any type that supports `+`\n                # This method should throw an error if gathering fails.\n                final = final + chunk  # type: ignore[operator]\n        if got_first_val:\n            yield from self.stream(final, config, **kwargs)\n[docs]    async def atransform(\n        self,\n        input: AsyncIterator[Input],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> AsyncIterator[Output]:\n        \"\"\"\n        Default implementation of atransform, which buffers input and calls astream.\n        Subclasses should override this method if they can start producing output while\n        input is still being generated.\n        \"\"\"\n        final: Input\n        got_first_val = False\n        async for chunk in input:\n            if not got_first_val:\n                final = chunk\n                got_first_val = True\n            else:\n                # Make a best effort to gather, for any type that supports `+`\n                # This method should throw an error if gathering fails.\n                final = final + chunk  # type: ignore[operator]\n        if got_first_val:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-14", "text": "if got_first_val:\n            async for output in self.astream(final, config, **kwargs):\n                yield output\n[docs]    def bind(self, **kwargs: Any) -> Runnable[Input, Output]:\n        \"\"\"\n        Bind arguments to a Runnable, returning a new Runnable.\n        \"\"\"\n        return RunnableBinding(bound=self, kwargs=kwargs, config={})\n[docs]    def with_config(\n        self,\n        config: Optional[RunnableConfig] = None,\n        # Sadly Unpack is not well supported by mypy so this will have to be untyped\n        **kwargs: Any,\n    ) -> Runnable[Input, Output]:\n        \"\"\"\n        Bind config to a Runnable, returning a new Runnable.\n        \"\"\"\n        return RunnableBinding(\n            bound=self,\n            config=cast(\n                RunnableConfig,\n                {**(config or {}), **kwargs},\n            ),  # type: ignore[misc]\n            kwargs={},\n        )\n[docs]    def with_listeners(\n        self,\n        *,\n        on_start: Optional[Listener] = None,\n        on_end: Optional[Listener] = None,\n        on_error: Optional[Listener] = None,\n    ) -> Runnable[Input, Output]:\n        \"\"\"\n        Bind lifecycle listeners to a Runnable, returning a new Runnable.\n        on_start: Called before the runnable starts running, with the Run object.\n        on_end: Called after the runnable finishes running, with the Run object.\n        on_error: Called if the runnable throws an error, with the Run object.\n        The Run object contains information about the run, including its id,\n        type, input, output, error, start_time, end_time, and any tags or metadata\n        added to the run.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-15", "text": "added to the run.\n        \"\"\"\n        from langchain.callbacks.tracers.root_listeners import RootListenersTracer\n        return RunnableBinding(\n            bound=self,\n            config_factories=[\n                lambda config: {\n                    \"callbacks\": [\n                        RootListenersTracer(\n                            config=config,\n                            on_start=on_start,\n                            on_end=on_end,\n                            on_error=on_error,\n                        )\n                    ],\n                }\n            ],\n        )\n[docs]    def with_types(\n        self,\n        *,\n        input_type: Optional[Type[Input]] = None,\n        output_type: Optional[Type[Output]] = None,\n    ) -> Runnable[Input, Output]:\n        \"\"\"\n        Bind input and output types to a Runnable, returning a new Runnable.\n        \"\"\"\n        return RunnableBinding(\n            bound=self,\n            custom_input_type=input_type,\n            custom_output_type=output_type,\n            kwargs={},\n        )\n[docs]    def with_retry(\n        self,\n        *,\n        retry_if_exception_type: Tuple[Type[BaseException], ...] = (Exception,),\n        wait_exponential_jitter: bool = True,\n        stop_after_attempt: int = 3,\n    ) -> Runnable[Input, Output]:\n        \"\"\"Create a new Runnable that retries the original runnable on exceptions.\n        Args:\n            retry_if_exception_type: A tuple of exception types to retry on\n            wait_exponential_jitter: Whether to add jitter to the wait time\n                                     between retries\n            stop_after_attempt: The maximum number of attempts to make before giving up\n        Returns:\n            A new Runnable that retries the original runnable on exceptions.\n        \"\"\"\n        from langchain.schema.runnable.retry import RunnableRetry\n        return RunnableRetry(\n            bound=self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-16", "text": "return RunnableRetry(\n            bound=self,\n            kwargs={},\n            config={},\n            retry_exception_types=retry_if_exception_type,\n            wait_exponential_jitter=wait_exponential_jitter,\n            max_attempt_number=stop_after_attempt,\n        )\n[docs]    def map(self) -> Runnable[List[Input], List[Output]]:\n        \"\"\"\n        Return a new Runnable that maps a list of inputs to a list of outputs,\n        by calling invoke() with each input.\n        \"\"\"\n        return RunnableEach(bound=self)\n[docs]    def with_fallbacks(\n        self,\n        fallbacks: Sequence[Runnable[Input, Output]],\n        *,\n        exceptions_to_handle: Tuple[Type[BaseException], ...] = (Exception,),\n    ) -> RunnableWithFallbacksT[Input, Output]:\n        \"\"\"Add fallbacks to a runnable, returning a new Runnable.\n        Args:\n            fallbacks: A sequence of runnables to try if the original runnable fails.\n            exceptions_to_handle: A tuple of exception types to handle.\n        Returns:\n            A new Runnable that will try the original runnable, and then each\n            fallback in order, upon failures.\n        \"\"\"\n        from langchain.schema.runnable.fallbacks import RunnableWithFallbacks\n        return RunnableWithFallbacks(\n            runnable=self,\n            fallbacks=fallbacks,\n            exceptions_to_handle=exceptions_to_handle,\n        )\n    \"\"\" --- Helper methods for Subclasses --- \"\"\"\n    def _call_with_config(\n        self,\n        func: Union[\n            Callable[[Input], Output],\n            Callable[[Input, CallbackManagerForChainRun], Output],\n            Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output],\n        ],\n        input: Input,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-17", "text": "],\n        input: Input,\n        config: Optional[RunnableConfig],\n        run_type: Optional[str] = None,\n        **kwargs: Optional[Any],\n    ) -> Output:\n        \"\"\"Helper method to transform an Input value to an Output value,\n        with callbacks. Use this method to implement invoke() in subclasses.\"\"\"\n        config = ensure_config(config)\n        callback_manager = get_callback_manager_for_config(config)\n        run_manager = callback_manager.on_chain_start(\n            dumpd(self),\n            input,\n            run_type=run_type,\n            name=config.get(\"run_name\"),\n        )\n        try:\n            output = call_func_with_variable_args(\n                func, input, config, run_manager, **kwargs\n            )\n        except BaseException as e:\n            run_manager.on_chain_error(e)\n            raise\n        else:\n            run_manager.on_chain_end(dumpd(output))\n            return output\n    async def _acall_with_config(\n        self,\n        func: Union[\n            Callable[[Input], Awaitable[Output]],\n            Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]],\n            Callable[\n                [Input, AsyncCallbackManagerForChainRun, RunnableConfig],\n                Awaitable[Output],\n            ],\n        ],\n        input: Input,\n        config: Optional[RunnableConfig],\n        run_type: Optional[str] = None,\n        **kwargs: Optional[Any],\n    ) -> Output:\n        \"\"\"Helper method to transform an Input value to an Output value,\n        with callbacks. Use this method to implement ainvoke() in subclasses.\"\"\"\n        config = ensure_config(config)\n        callback_manager = get_async_callback_manager_for_config(config)\n        run_manager = await callback_manager.on_chain_start(\n            dumpd(self),\n            input,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-18", "text": "dumpd(self),\n            input,\n            run_type=run_type,\n            name=config.get(\"run_name\"),\n        )\n        try:\n            output = await acall_func_with_variable_args(\n                func, input, config, run_manager, **kwargs\n            )\n        except BaseException as e:\n            await run_manager.on_chain_error(e)\n            raise\n        else:\n            await run_manager.on_chain_end(dumpd(output))\n            return output\n    def _batch_with_config(\n        self,\n        func: Union[\n            Callable[[List[Input]], List[Union[Exception, Output]]],\n            Callable[\n                [List[Input], List[CallbackManagerForChainRun]],\n                List[Union[Exception, Output]],\n            ],\n            Callable[\n                [List[Input], List[CallbackManagerForChainRun], List[RunnableConfig]],\n                List[Union[Exception, Output]],\n            ],\n        ],\n        input: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        run_type: Optional[str] = None,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        \"\"\"Helper method to transform an Input value to an Output value,\n        with callbacks. Use this method to implement invoke() in subclasses.\"\"\"\n        if not input:\n            return []\n        configs = get_config_list(config, len(input))\n        callback_managers = [get_callback_manager_for_config(c) for c in configs]\n        run_managers = [\n            callback_manager.on_chain_start(\n                dumpd(self),\n                input,\n                run_type=run_type,\n                name=config.get(\"run_name\"),\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-19", "text": "run_type=run_type,\n                name=config.get(\"run_name\"),\n            )\n            for callback_manager, input, config in zip(\n                callback_managers, input, configs\n            )\n        ]\n        try:\n            if accepts_config(func):\n                kwargs[\"config\"] = [\n                    patch_config(c, callbacks=rm.get_child())\n                    for c, rm in zip(configs, run_managers)\n                ]\n            if accepts_run_manager(func):\n                kwargs[\"run_manager\"] = run_managers\n            output = func(input, **kwargs)  # type: ignore[call-arg]\n        except BaseException as e:\n            for run_manager in run_managers:\n                run_manager.on_chain_error(e)\n            if return_exceptions:\n                return cast(List[Output], [e for _ in input])\n            else:\n                raise\n        else:\n            first_exception: Optional[Exception] = None\n            for run_manager, out in zip(run_managers, output):\n                if isinstance(out, Exception):\n                    first_exception = first_exception or out\n                    run_manager.on_chain_error(out)\n                else:\n                    run_manager.on_chain_end(dumpd(out))\n            if return_exceptions or first_exception is None:\n                return cast(List[Output], output)\n            else:\n                raise first_exception\n    async def _abatch_with_config(\n        self,\n        func: Union[\n            Callable[[List[Input]], Awaitable[List[Union[Exception, Output]]]],\n            Callable[\n                [List[Input], List[AsyncCallbackManagerForChainRun]],\n                Awaitable[List[Union[Exception, Output]]],\n            ],\n            Callable[\n                [\n                    List[Input],\n                    List[AsyncCallbackManagerForChainRun],\n                    List[RunnableConfig],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-20", "text": "List[AsyncCallbackManagerForChainRun],\n                    List[RunnableConfig],\n                ],\n                Awaitable[List[Union[Exception, Output]]],\n            ],\n        ],\n        input: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        run_type: Optional[str] = None,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        \"\"\"Helper method to transform an Input value to an Output value,\n        with callbacks. Use this method to implement invoke() in subclasses.\"\"\"\n        if not input:\n            return []\n        configs = get_config_list(config, len(input))\n        callback_managers = [get_async_callback_manager_for_config(c) for c in configs]\n        run_managers: List[AsyncCallbackManagerForChainRun] = await asyncio.gather(\n            *(\n                callback_manager.on_chain_start(\n                    dumpd(self),\n                    input,\n                    run_type=run_type,\n                    name=config.get(\"run_name\"),\n                )\n                for callback_manager, input, config in zip(\n                    callback_managers, input, configs\n                )\n            )\n        )\n        try:\n            if accepts_config(func):\n                kwargs[\"config\"] = [\n                    patch_config(c, callbacks=rm.get_child())\n                    for c, rm in zip(configs, run_managers)\n                ]\n            if accepts_run_manager(func):\n                kwargs[\"run_manager\"] = run_managers\n            output = await func(input, **kwargs)  # type: ignore[call-arg]\n        except BaseException as e:\n            await asyncio.gather(\n                *(run_manager.on_chain_error(e) for run_manager in run_managers)\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-21", "text": ")\n            if return_exceptions:\n                return cast(List[Output], [e for _ in input])\n            else:\n                raise\n        else:\n            first_exception: Optional[Exception] = None\n            coros: List[Awaitable[None]] = []\n            for run_manager, out in zip(run_managers, output):\n                if isinstance(out, Exception):\n                    first_exception = first_exception or out\n                    coros.append(run_manager.on_chain_error(out))\n                else:\n                    coros.append(run_manager.on_chain_end(dumpd(out)))\n            await asyncio.gather(*coros)\n            if return_exceptions or first_exception is None:\n                return cast(List[Output], output)\n            else:\n                raise first_exception\n    def _transform_stream_with_config(\n        self,\n        input: Iterator[Input],\n        transformer: Union[\n            Callable[[Iterator[Input]], Iterator[Output]],\n            Callable[[Iterator[Input], CallbackManagerForChainRun], Iterator[Output]],\n            Callable[\n                [\n                    Iterator[Input],\n                    CallbackManagerForChainRun,\n                    RunnableConfig,\n                ],\n                Iterator[Output],\n            ],\n        ],\n        config: Optional[RunnableConfig],\n        run_type: Optional[str] = None,\n        **kwargs: Optional[Any],\n    ) -> Iterator[Output]:\n        \"\"\"Helper method to transform an Iterator of Input values into an Iterator of\n        Output values, with callbacks.\n        Use this to implement `stream()` or `transform()` in Runnable subclasses.\"\"\"\n        # tee the input so we can iterate over it twice\n        input_for_tracing, input_for_transform = tee(input, 2)\n        # Start the input iterator to ensure the input runnable starts before this one", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-22", "text": "# Start the input iterator to ensure the input runnable starts before this one\n        final_input: Optional[Input] = next(input_for_tracing, None)\n        final_input_supported = True\n        final_output: Optional[Output] = None\n        final_output_supported = True\n        config = ensure_config(config)\n        callback_manager = get_callback_manager_for_config(config)\n        run_manager = callback_manager.on_chain_start(\n            dumpd(self),\n            {\"input\": \"\"},\n            run_type=run_type,\n            name=config.get(\"run_name\"),\n        )\n        try:\n            if accepts_config(transformer):\n                kwargs[\"config\"] = patch_config(\n                    config, callbacks=run_manager.get_child()\n                )\n            if accepts_run_manager(transformer):\n                kwargs[\"run_manager\"] = run_manager\n            iterator = transformer(input_for_transform, **kwargs)  # type: ignore[call-arg]\n            for chunk in iterator:\n                yield chunk\n                if final_output_supported:\n                    if final_output is None:\n                        final_output = chunk\n                    else:\n                        try:\n                            final_output = final_output + chunk  # type: ignore\n                        except TypeError:\n                            final_output = None\n                            final_output_supported = False\n            for ichunk in input_for_tracing:\n                if final_input_supported:\n                    if final_input is None:\n                        final_input = ichunk\n                    else:\n                        try:\n                            final_input = final_input + ichunk  # type: ignore\n                        except TypeError:\n                            final_input = None\n                            final_input_supported = False\n        except BaseException as e:\n            run_manager.on_chain_error(e, inputs=final_input)\n            raise\n        else:\n            run_manager.on_chain_end(final_output, inputs=final_input)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-23", "text": "else:\n            run_manager.on_chain_end(final_output, inputs=final_input)\n    async def _atransform_stream_with_config(\n        self,\n        input: AsyncIterator[Input],\n        transformer: Union[\n            Callable[[AsyncIterator[Input]], AsyncIterator[Output]],\n            Callable[\n                [AsyncIterator[Input], AsyncCallbackManagerForChainRun],\n                AsyncIterator[Output],\n            ],\n            Callable[\n                [\n                    AsyncIterator[Input],\n                    AsyncCallbackManagerForChainRun,\n                    RunnableConfig,\n                ],\n                AsyncIterator[Output],\n            ],\n        ],\n        config: Optional[RunnableConfig],\n        run_type: Optional[str] = None,\n        **kwargs: Optional[Any],\n    ) -> AsyncIterator[Output]:\n        \"\"\"Helper method to transform an Async Iterator of Input values into an Async\n        Iterator of Output values, with callbacks.\n        Use this to implement `astream()` or `atransform()` in Runnable subclasses.\"\"\"\n        # tee the input so we can iterate over it twice\n        input_for_tracing, input_for_transform = atee(input, 2)\n        # Start the input iterator to ensure the input runnable starts before this one\n        final_input: Optional[Input] = await py_anext(input_for_tracing, None)\n        final_input_supported = True\n        final_output: Optional[Output] = None\n        final_output_supported = True\n        config = ensure_config(config)\n        callback_manager = get_async_callback_manager_for_config(config)\n        run_manager = await callback_manager.on_chain_start(\n            dumpd(self),\n            {\"input\": \"\"},\n            run_type=run_type,\n            name=config.get(\"run_name\"),\n        )\n        try:\n            if accepts_config(transformer):\n                kwargs[\"config\"] = patch_config(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-24", "text": "if accepts_config(transformer):\n                kwargs[\"config\"] = patch_config(\n                    config, callbacks=run_manager.get_child()\n                )\n            if accepts_run_manager(transformer):\n                kwargs[\"run_manager\"] = run_manager\n            iterator = transformer(input_for_transform, **kwargs)  # type: ignore[call-arg]\n            async for chunk in iterator:\n                yield chunk\n                if final_output_supported:\n                    if final_output is None:\n                        final_output = chunk\n                    else:\n                        try:\n                            final_output = final_output + chunk  # type: ignore\n                        except TypeError:\n                            final_output = None\n                            final_output_supported = False\n            async for ichunk in input_for_tracing:\n                if final_input_supported:\n                    if final_input is None:\n                        final_input = ichunk\n                    else:\n                        try:\n                            final_input = final_input + ichunk  # type: ignore[operator]\n                        except TypeError:\n                            final_input = None\n                            final_input_supported = False\n        except BaseException as e:\n            await run_manager.on_chain_error(e, inputs=final_input)\n            raise\n        else:\n            await run_manager.on_chain_end(final_output, inputs=final_input)\n[docs]class RunnableSerializable(Serializable, Runnable[Input, Output]):\n    \"\"\"A Runnable that can be serialized to JSON.\"\"\"\n[docs]    def configurable_fields(\n        self, **kwargs: AnyConfigurableField\n    ) -> RunnableSerializable[Input, Output]:\n        from langchain.schema.runnable.configurable import RunnableConfigurableFields\n        for key in kwargs:\n            if key not in self.__fields__:\n                raise ValueError(\n                    f\"Configuration key {key} not found in {self}: \"\n                    \"available keys are {self.__fields__.keys()}\"\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-25", "text": "\"available keys are {self.__fields__.keys()}\"\n                )\n        return RunnableConfigurableFields(default=self, fields=kwargs)\n[docs]    def configurable_alternatives(\n        self,\n        which: ConfigurableField,\n        default_key: str = \"default\",\n        **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]],\n    ) -> RunnableSerializable[Input, Output]:\n        from langchain.schema.runnable.configurable import (\n            RunnableConfigurableAlternatives,\n        )\n        return RunnableConfigurableAlternatives(\n            which=which, default=self, alternatives=kwargs, default_key=default_key\n        )\n[docs]class RunnableSequence(RunnableSerializable[Input, Output]):\n    \"\"\"A sequence of runnables, where the output of each is the input of the next.\n    RunnableSequence is the most important composition operator in LangChain as it is\n    used in virtually every chain.\n    A RunnableSequence can be instantiated directly or more commonly by using the `|`\n    operator where either the left or right operands (or both) must be a Runnable.\n    Any RunnableSequence automatically supports sync, async, batch.\n    The default implementations of `batch` and `abatch` utilize threadpools and\n    asyncio gather and will be faster than naive invocation of invoke or ainvoke\n    for IO bound runnables.\n    Batching is implemented by invoking the batch method on each component of the\n    RunnableSequence in order.\n    A RunnableSequence preserves the streaming properties of its components, so if all\n    components of the sequence implement a `transform` method -- which\n    is the method that implements the logic to map a streaming input to a streaming\n    output -- then the sequence will be able to stream input to output!", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-26", "text": "output -- then the sequence will be able to stream input to output!\n    If any component of the sequence does not implement transform then the\n    streaming will only begin after this component is run. If there are\n    multiple blocking components, streaming begins after the last one.\n    Please note: RunnableLambdas do not support `transform` by default! So if\n        you need to use a RunnableLambdas be careful about where you place them in a\n        RunnableSequence (if you need to use the .stream()/.astream() methods).\n        If you need arbitrary logic and need streaming, you can subclass\n        Runnable, and implement `transform` for whatever logic you need.\n    Here is a simple example that uses simple functions to illustrate the use of\n    RunnableSequence:\n        .. code-block:: python\n            from langchain.schema.runnable import RunnableLambda\n            def add_one(x: int) -> int:\n                return x + 1\n            def mul_two(x: int) -> int:\n                return x * 2\n            runnable_1 = RunnableLambda(add_one)\n            runnable_2 = RunnableLambda(mul_two)\n            sequence = runnable_1 | runnable_2\n            # Or equivalently:\n            # sequence = RunnableSequence(first=runnable_1, last=runnable_2)\n            sequence.invoke(1)\n            await runnable.ainvoke(1)\n            sequence.batch([1, 2, 3])\n            await sequence.abatch([1, 2, 3])\n    Here's an example that uses streams JSON output generated by an LLM:\n        .. code-block:: python\n            from langchain.output_parsers.json import SimpleJsonOutputParser\n            from langchain.chat_models.openai import ChatOpenAI\n            prompt = PromptTemplate.from_template(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-27", "text": "prompt = PromptTemplate.from_template(\n                'In JSON format, give me a list of {topic} and their '\n                'corresponding names in French, Spanish and in a '\n                'Cat Language.'\n            )\n            model = ChatOpenAI()\n            chain = prompt | model | SimpleJsonOutputParser()\n            async for chunk in chain.astream({'topic': 'colors'}):\n                print('-')\n                print(chunk, sep='', flush=True)\n    \"\"\"\n    # The steps are broken into first, middle and last, solely for type checking\n    # purposes. It allows specifying the `Input` on the first type, the `Output` of\n    # the last type.\n    first: Runnable[Input, Any]\n    \"\"\"The first runnable in the sequence.\"\"\"\n    middle: List[Runnable[Any, Any]] = Field(default_factory=list)\n    \"\"\"The middle runnables in the sequence.\"\"\"\n    last: Runnable[Any, Output]\n    \"\"\"The last runnable in the sequence.\"\"\"\n    @property\n    def steps(self) -> List[Runnable[Any, Any]]:\n        \"\"\"All the runnables that make up the sequence in order.\"\"\"\n        return [self.first] + self.middle + [self.last]\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n[docs]    @classmethod\n    def get_lc_namespace(cls) -> List[str]:\n        return cls.__module__.split(\".\")[:-1]\n    class Config:\n        arbitrary_types_allowed = True\n    @property\n    def InputType(self) -> Type[Input]:\n        return self.first.InputType\n    @property\n    def OutputType(self) -> Type[Output]:\n        return self.last.OutputType\n[docs]    def get_input_schema(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-28", "text": "return self.last.OutputType\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        from langchain.schema.runnable.passthrough import RunnableAssign\n        if isinstance(self.first, RunnableAssign):\n            first = cast(RunnableAssign, self.first)\n            next_ = self.middle[0] if self.middle else self.last\n            next_input_schema = next_.get_input_schema(config)\n            if not next_input_schema.__custom_root_type__:\n                # it's a dict as expected\n                return create_model(  # type: ignore[call-overload]\n                    \"RunnableSequenceInput\",\n                    **{\n                        k: (v.annotation, v.default)\n                        for k, v in next_input_schema.__fields__.items()\n                        if k not in first.mapper.steps\n                    },\n                )\n        return self.first.get_input_schema(config)\n[docs]    def get_output_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        return self.last.get_output_schema(config)\n    @property\n    def config_specs(self) -> List[ConfigurableFieldSpec]:\n        return get_unique_config_specs(\n            spec for step in self.steps for spec in step.config_specs\n        )\n    def __repr__(self) -> str:\n        return \"\\n| \".join(\n            repr(s) if i == 0 else indent_lines_after_first(repr(s), \"| \")\n            for i, s in enumerate(self.steps)\n        )\n    def __or__(\n        self,\n        other: Union[\n            Runnable[Any, Other],\n            Callable[[Any], Other],\n            Callable[[Iterator[Any]], Iterator[Other]],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-29", "text": "Callable[[Any], Other],\n            Callable[[Iterator[Any]], Iterator[Other]],\n            Mapping[str, Union[Runnable[Any, Other], Callable[[Any], Other], Any]],\n        ],\n    ) -> RunnableSerializable[Input, Other]:\n        if isinstance(other, RunnableSequence):\n            return RunnableSequence(\n                first=self.first,\n                middle=self.middle + [self.last] + [other.first] + other.middle,\n                last=other.last,\n            )\n        else:\n            return RunnableSequence(\n                first=self.first,\n                middle=self.middle + [self.last],\n                last=coerce_to_runnable(other),\n            )\n    def __ror__(\n        self,\n        other: Union[\n            Runnable[Other, Any],\n            Callable[[Other], Any],\n            Callable[[Iterator[Other]], Iterator[Any]],\n            Mapping[str, Union[Runnable[Other, Any], Callable[[Other], Any], Any]],\n        ],\n    ) -> RunnableSerializable[Other, Output]:\n        if isinstance(other, RunnableSequence):\n            return RunnableSequence(\n                first=other.first,\n                middle=other.middle + [other.last] + [self.first] + self.middle,\n                last=self.last,\n            )\n        else:\n            return RunnableSequence(\n                first=coerce_to_runnable(other),\n                middle=[self.first] + self.middle,\n                last=self.last,\n            )\n[docs]    def invoke(self, input: Input, config: Optional[RunnableConfig] = None) -> Output:\n        # setup callbacks\n        config = ensure_config(config)\n        callback_manager = get_callback_manager_for_config(config)\n        # start the root run\n        run_manager = callback_manager.on_chain_start(\n            dumpd(self), input, name=config.get(\"run_name\")\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-30", "text": "dumpd(self), input, name=config.get(\"run_name\")\n        )\n        # invoke all steps in sequence\n        try:\n            for i, step in enumerate(self.steps):\n                input = step.invoke(\n                    input,\n                    # mark each step as a child run\n                    patch_config(\n                        config, callbacks=run_manager.get_child(f\"seq:step:{i+1}\")\n                    ),\n                )\n        # finish the root run\n        except BaseException as e:\n            run_manager.on_chain_error(e)\n            raise\n        else:\n            run_manager.on_chain_end(input)\n            return cast(Output, input)\n[docs]    async def ainvoke(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Output:\n        # setup callbacks\n        config = ensure_config(config)\n        callback_manager = get_async_callback_manager_for_config(config)\n        # start the root run\n        run_manager = await callback_manager.on_chain_start(\n            dumpd(self), input, name=config.get(\"run_name\")\n        )\n        # invoke all steps in sequence\n        try:\n            for i, step in enumerate(self.steps):\n                input = await step.ainvoke(\n                    input,\n                    # mark each step as a child run\n                    patch_config(\n                        config, callbacks=run_manager.get_child(f\"seq:step:{i+1}\")\n                    ),\n                )\n        # finish the root run\n        except BaseException as e:\n            await run_manager.on_chain_error(e)\n            raise\n        else:\n            await run_manager.on_chain_end(input)\n            return cast(Output, input)\n[docs]    def batch(\n        self,\n        inputs: List[Input],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-31", "text": "[docs]    def batch(\n        self,\n        inputs: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        from langchain.callbacks.manager import CallbackManager\n        if not inputs:\n            return []\n        # setup callbacks\n        configs = get_config_list(config, len(inputs))\n        callback_managers = [\n            CallbackManager.configure(\n                inheritable_callbacks=config.get(\"callbacks\"),\n                local_callbacks=None,\n                verbose=False,\n                inheritable_tags=config.get(\"tags\"),\n                local_tags=None,\n                inheritable_metadata=config.get(\"metadata\"),\n                local_metadata=None,\n            )\n            for config in configs\n        ]\n        # start the root runs, one per input\n        run_managers = [\n            cm.on_chain_start(\n                dumpd(self),\n                input,\n                name=config.get(\"run_name\"),\n            )\n            for cm, input, config in zip(callback_managers, inputs, configs)\n        ]\n        # invoke\n        try:\n            if return_exceptions:\n                # Track which inputs (by index) failed so far\n                # If an input has failed it will be present in this map,\n                # and the value will be the exception that was raised.\n                failed_inputs_map: Dict[int, Exception] = {}\n                for stepidx, step in enumerate(self.steps):\n                    # Assemble the original indexes of the remaining inputs\n                    # (i.e. the ones that haven't failed yet)\n                    remaining_idxs = [\n                        i for i in range(len(configs)) if i not in failed_inputs_map\n                    ]\n                    # Invoke the step on the remaining inputs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-32", "text": "]\n                    # Invoke the step on the remaining inputs\n                    inputs = step.batch(\n                        [\n                            inp\n                            for i, inp in zip(remaining_idxs, inputs)\n                            if i not in failed_inputs_map\n                        ],\n                        [\n                            # each step a child run of the corresponding root run\n                            patch_config(\n                                config, callbacks=rm.get_child(f\"seq:step:{stepidx+1}\")\n                            )\n                            for i, (rm, config) in enumerate(zip(run_managers, configs))\n                            if i not in failed_inputs_map\n                        ],\n                        return_exceptions=return_exceptions,\n                        **kwargs,\n                    )\n                    # If an input failed, add it to the map\n                    for i, inp in zip(remaining_idxs, inputs):\n                        if isinstance(inp, Exception):\n                            failed_inputs_map[i] = inp\n                    inputs = [inp for inp in inputs if not isinstance(inp, Exception)]\n                    # If all inputs have failed, stop processing\n                    if len(failed_inputs_map) == len(configs):\n                        break\n                # Reassemble the outputs, inserting Exceptions for failed inputs\n                inputs_copy = inputs.copy()\n                inputs = []\n                for i in range(len(configs)):\n                    if i in failed_inputs_map:\n                        inputs.append(cast(Input, failed_inputs_map[i]))\n                    else:\n                        inputs.append(inputs_copy.pop(0))\n            else:\n                for i, step in enumerate(self.steps):\n                    inputs = step.batch(\n                        inputs,\n                        [\n                            # each step a child run of the corresponding root run\n                            patch_config(\n                                config, callbacks=rm.get_child(f\"seq:step:{i+1}\")\n                            )\n                            for rm, config in zip(run_managers, configs)\n                        ],\n                    )\n        # finish the root runs", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-33", "text": "],\n                    )\n        # finish the root runs\n        except BaseException as e:\n            for rm in run_managers:\n                rm.on_chain_error(e)\n            if return_exceptions:\n                return cast(List[Output], [e for _ in inputs])\n            else:\n                raise\n        else:\n            first_exception: Optional[Exception] = None\n            for run_manager, out in zip(run_managers, inputs):\n                if isinstance(out, Exception):\n                    first_exception = first_exception or out\n                    run_manager.on_chain_error(out)\n                else:\n                    run_manager.on_chain_end(dumpd(out))\n            if return_exceptions or first_exception is None:\n                return cast(List[Output], inputs)\n            else:\n                raise first_exception\n[docs]    async def abatch(\n        self,\n        inputs: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        from langchain.callbacks.manager import (\n            AsyncCallbackManager,\n        )\n        if not inputs:\n            return []\n        # setup callbacks\n        configs = get_config_list(config, len(inputs))\n        callback_managers = [\n            AsyncCallbackManager.configure(\n                inheritable_callbacks=config.get(\"callbacks\"),\n                local_callbacks=None,\n                verbose=False,\n                inheritable_tags=config.get(\"tags\"),\n                local_tags=None,\n                inheritable_metadata=config.get(\"metadata\"),\n                local_metadata=None,\n            )\n            for config in configs\n        ]\n        # start the root runs, one per input\n        run_managers: List[AsyncCallbackManagerForChainRun] = await asyncio.gather(\n            *(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-34", "text": "*(\n                cm.on_chain_start(\n                    dumpd(self),\n                    input,\n                    name=config.get(\"run_name\"),\n                )\n                for cm, input, config in zip(callback_managers, inputs, configs)\n            )\n        )\n        # invoke .batch() on each step\n        # this uses batching optimizations in Runnable subclasses, like LLM\n        try:\n            if return_exceptions:\n                # Track which inputs (by index) failed so far\n                # If an input has failed it will be present in this map,\n                # and the value will be the exception that was raised.\n                failed_inputs_map: Dict[int, Exception] = {}\n                for stepidx, step in enumerate(self.steps):\n                    # Assemble the original indexes of the remaining inputs\n                    # (i.e. the ones that haven't failed yet)\n                    remaining_idxs = [\n                        i for i in range(len(configs)) if i not in failed_inputs_map\n                    ]\n                    # Invoke the step on the remaining inputs\n                    inputs = await step.abatch(\n                        [\n                            inp\n                            for i, inp in zip(remaining_idxs, inputs)\n                            if i not in failed_inputs_map\n                        ],\n                        [\n                            # each step a child run of the corresponding root run\n                            patch_config(\n                                config, callbacks=rm.get_child(f\"seq:step:{stepidx+1}\")\n                            )\n                            for i, (rm, config) in enumerate(zip(run_managers, configs))\n                            if i not in failed_inputs_map\n                        ],\n                        return_exceptions=return_exceptions,\n                        **kwargs,\n                    )\n                    # If an input failed, add it to the map\n                    for i, inp in zip(remaining_idxs, inputs):\n                        if isinstance(inp, Exception):\n                            failed_inputs_map[i] = inp", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-35", "text": "if isinstance(inp, Exception):\n                            failed_inputs_map[i] = inp\n                    inputs = [inp for inp in inputs if not isinstance(inp, Exception)]\n                    # If all inputs have failed, stop processing\n                    if len(failed_inputs_map) == len(configs):\n                        break\n                # Reassemble the outputs, inserting Exceptions for failed inputs\n                inputs_copy = inputs.copy()\n                inputs = []\n                for i in range(len(configs)):\n                    if i in failed_inputs_map:\n                        inputs.append(cast(Input, failed_inputs_map[i]))\n                    else:\n                        inputs.append(inputs_copy.pop(0))\n            else:\n                for i, step in enumerate(self.steps):\n                    inputs = await step.abatch(\n                        inputs,\n                        [\n                            # each step a child run of the corresponding root run\n                            patch_config(\n                                config, callbacks=rm.get_child(f\"seq:step:{i+1}\")\n                            )\n                            for rm, config in zip(run_managers, configs)\n                        ],\n                    )\n        # finish the root runs\n        except BaseException as e:\n            await asyncio.gather(*(rm.on_chain_error(e) for rm in run_managers))\n            if return_exceptions:\n                return cast(List[Output], [e for _ in inputs])\n            else:\n                raise\n        else:\n            first_exception: Optional[Exception] = None\n            coros: List[Awaitable[None]] = []\n            for run_manager, out in zip(run_managers, inputs):\n                if isinstance(out, Exception):\n                    first_exception = first_exception or out\n                    coros.append(run_manager.on_chain_error(out))\n                else:\n                    coros.append(run_manager.on_chain_end(dumpd(out)))\n            await asyncio.gather(*coros)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-36", "text": "await asyncio.gather(*coros)\n            if return_exceptions or first_exception is None:\n                return cast(List[Output], inputs)\n            else:\n                raise first_exception\n    def _transform(\n        self,\n        input: Iterator[Input],\n        run_manager: CallbackManagerForChainRun,\n        config: RunnableConfig,\n    ) -> Iterator[Output]:\n        steps = [self.first] + self.middle + [self.last]\n        # transform the input stream of each step with the next\n        # steps that don't natively support transforming an input stream will\n        # buffer input in memory until all available, and then start emitting output\n        final_pipeline = cast(Iterator[Output], input)\n        for step in steps:\n            final_pipeline = step.transform(\n                final_pipeline,\n                patch_config(\n                    config,\n                    callbacks=run_manager.get_child(f\"seq:step:{steps.index(step)+1}\"),\n                ),\n            )\n        for output in final_pipeline:\n            yield output\n    async def _atransform(\n        self,\n        input: AsyncIterator[Input],\n        run_manager: AsyncCallbackManagerForChainRun,\n        config: RunnableConfig,\n    ) -> AsyncIterator[Output]:\n        steps = [self.first] + self.middle + [self.last]\n        # stream the last steps\n        # transform the input stream of each step with the next\n        # steps that don't natively support transforming an input stream will\n        # buffer input in memory until all available, and then start emitting output\n        final_pipeline = cast(AsyncIterator[Output], input)\n        for step in steps:\n            final_pipeline = step.atransform(\n                final_pipeline,\n                patch_config(\n                    config,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-37", "text": "final_pipeline,\n                patch_config(\n                    config,\n                    callbacks=run_manager.get_child(f\"seq:step:{steps.index(step)+1}\"),\n                ),\n            )\n        async for output in final_pipeline:\n            yield output\n[docs]    def transform(\n        self,\n        input: Iterator[Input],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Iterator[Output]:\n        yield from self._transform_stream_with_config(\n            input, self._transform, config, **kwargs\n        )\n[docs]    def stream(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Iterator[Output]:\n        yield from self.transform(iter([input]), config, **kwargs)\n[docs]    async def atransform(\n        self,\n        input: AsyncIterator[Input],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> AsyncIterator[Output]:\n        async for chunk in self._atransform_stream_with_config(\n            input, self._atransform, config, **kwargs\n        ):\n            yield chunk\n[docs]    async def astream(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> AsyncIterator[Output]:\n        async def input_aiter() -> AsyncIterator[Input]:\n            yield input\n        async for chunk in self.atransform(input_aiter(), config, **kwargs):\n            yield chunk\n[docs]class RunnableParallel(RunnableSerializable[Input, Dict[str, Any]]):\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-38", "text": "\"\"\"\n    A runnable that runs a mapping of runnables in parallel,\n    and returns a mapping of their outputs.\n    \"\"\"\n    steps: Mapping[str, Runnable[Input, Any]]\n    def __init__(\n        self,\n        __steps: Optional[\n            Mapping[\n                str,\n                Union[\n                    Runnable[Input, Any],\n                    Callable[[Input], Any],\n                    Mapping[str, Union[Runnable[Input, Any], Callable[[Input], Any]]],\n                ],\n            ]\n        ] = None,\n        **kwargs: Union[\n            Runnable[Input, Any],\n            Callable[[Input], Any],\n            Mapping[str, Union[Runnable[Input, Any], Callable[[Input], Any]]],\n        ],\n    ) -> None:\n        merged = {**__steps} if __steps is not None else {}\n        merged.update(kwargs)\n        super().__init__(\n            steps={key: coerce_to_runnable(r) for key, r in merged.items()}\n        )\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n[docs]    @classmethod\n    def get_lc_namespace(cls) -> List[str]:\n        return cls.__module__.split(\".\")[:-1]\n    class Config:\n        arbitrary_types_allowed = True\n    @property\n    def InputType(self) -> Any:\n        for step in self.steps.values():\n            if step.InputType:\n                return step.InputType\n        return Any\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        if all(\n            s.get_input_schema(config).schema().get(\"type\", \"object\") == \"object\"\n            for s in self.steps.values()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-39", "text": "for s in self.steps.values()\n        ):\n            # This is correct, but pydantic typings/mypy don't think so.\n            return create_model(  # type: ignore[call-overload]\n                \"RunnableParallelInput\",\n                **{\n                    k: (v.annotation, v.default)\n                    for step in self.steps.values()\n                    for k, v in step.get_input_schema(config).__fields__.items()\n                    if k != \"__root__\"\n                },\n            )\n        return super().get_input_schema(config)\n[docs]    def get_output_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        # This is correct, but pydantic typings/mypy don't think so.\n        return create_model(  # type: ignore[call-overload]\n            \"RunnableParallelOutput\",\n            **{k: (v.OutputType, None) for k, v in self.steps.items()},\n        )\n    @property\n    def config_specs(self) -> List[ConfigurableFieldSpec]:\n        return get_unique_config_specs(\n            spec for step in self.steps.values() for spec in step.config_specs\n        )\n    def __repr__(self) -> str:\n        map_for_repr = \",\\n  \".join(\n            f\"{k}: {indent_lines_after_first(repr(v), '  ' + k + ': ')}\"\n            for k, v in self.steps.items()\n        )\n        return \"{\\n  \" + map_for_repr + \"\\n}\"\n[docs]    def invoke(\n        self, input: Input, config: Optional[RunnableConfig] = None\n    ) -> Dict[str, Any]:\n        from langchain.callbacks.manager import CallbackManager\n        # setup callbacks", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-40", "text": "from langchain.callbacks.manager import CallbackManager\n        # setup callbacks\n        config = ensure_config(config)\n        callback_manager = CallbackManager.configure(\n            inheritable_callbacks=config.get(\"callbacks\"),\n            local_callbacks=None,\n            verbose=False,\n            inheritable_tags=config.get(\"tags\"),\n            local_tags=None,\n            inheritable_metadata=config.get(\"metadata\"),\n            local_metadata=None,\n        )\n        # start the root run\n        run_manager = callback_manager.on_chain_start(\n            dumpd(self), input, name=config.get(\"run_name\")\n        )\n        # gather results from all steps\n        try:\n            # copy to avoid issues from the caller mutating the steps during invoke()\n            steps = dict(self.steps)\n            with get_executor_for_config(config) as executor:\n                futures = [\n                    executor.submit(\n                        step.invoke,\n                        input,\n                        # mark each step as a child run\n                        patch_config(\n                            config,\n                            callbacks=run_manager.get_child(f\"map:key:{key}\"),\n                        ),\n                    )\n                    for key, step in steps.items()\n                ]\n                output = {key: future.result() for key, future in zip(steps, futures)}\n        # finish the root run\n        except BaseException as e:\n            run_manager.on_chain_error(e)\n            raise\n        else:\n            run_manager.on_chain_end(output)\n            return output\n[docs]    async def ainvoke(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Dict[str, Any]:\n        # setup callbacks\n        config = ensure_config(config)\n        callback_manager = get_async_callback_manager_for_config(config)\n        # start the root run", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-41", "text": "callback_manager = get_async_callback_manager_for_config(config)\n        # start the root run\n        run_manager = await callback_manager.on_chain_start(\n            dumpd(self), input, name=config.get(\"run_name\")\n        )\n        # gather results from all steps\n        try:\n            # copy to avoid issues from the caller mutating the steps during invoke()\n            steps = dict(self.steps)\n            results = await asyncio.gather(\n                *(\n                    step.ainvoke(\n                        input,\n                        # mark each step as a child run\n                        patch_config(\n                            config, callbacks=run_manager.get_child(f\"map:key:{key}\")\n                        ),\n                    )\n                    for key, step in steps.items()\n                )\n            )\n            output = {key: value for key, value in zip(steps, results)}\n        # finish the root run\n        except BaseException as e:\n            await run_manager.on_chain_error(e)\n            raise\n        else:\n            await run_manager.on_chain_end(output)\n            return output\n    def _transform(\n        self,\n        input: Iterator[Input],\n        run_manager: CallbackManagerForChainRun,\n        config: RunnableConfig,\n    ) -> Iterator[AddableDict]:\n        # Shallow copy steps to ignore mutations while in progress\n        steps = dict(self.steps)\n        # Each step gets a copy of the input iterator,\n        # which is consumed in parallel in a separate thread.\n        input_copies = list(safetee(input, len(steps), lock=threading.Lock()))\n        with get_executor_for_config(config) as executor:\n            # Create the transform() generator for each step\n            named_generators = [\n                (\n                    name,\n                    step.transform(\n                        input_copies.pop(),\n                        patch_config(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-42", "text": "step.transform(\n                        input_copies.pop(),\n                        patch_config(\n                            config, callbacks=run_manager.get_child(f\"map:key:{name}\")\n                        ),\n                    ),\n                )\n                for name, step in steps.items()\n            ]\n            # Start the first iteration of each generator\n            futures = {\n                executor.submit(next, generator): (step_name, generator)\n                for step_name, generator in named_generators\n            }\n            # Yield chunks from each as they become available,\n            # and start the next iteration of that generator that yielded it.\n            # When all generators are exhausted, stop.\n            while futures:\n                completed_futures, _ = wait(futures, return_when=FIRST_COMPLETED)\n                for future in completed_futures:\n                    (step_name, generator) = futures.pop(future)\n                    try:\n                        chunk = AddableDict({step_name: future.result()})\n                        yield chunk\n                        futures[executor.submit(next, generator)] = (\n                            step_name,\n                            generator,\n                        )\n                    except StopIteration:\n                        pass\n[docs]    def transform(\n        self,\n        input: Iterator[Input],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Iterator[Dict[str, Any]]:\n        yield from self._transform_stream_with_config(\n            input, self._transform, config, **kwargs\n        )\n[docs]    def stream(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Iterator[Dict[str, Any]]:\n        yield from self.transform(iter([input]), config)\n    async def _atransform(\n        self,\n        input: AsyncIterator[Input],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-43", "text": "self,\n        input: AsyncIterator[Input],\n        run_manager: AsyncCallbackManagerForChainRun,\n        config: RunnableConfig,\n    ) -> AsyncIterator[AddableDict]:\n        # Shallow copy steps to ignore mutations while in progress\n        steps = dict(self.steps)\n        # Each step gets a copy of the input iterator,\n        # which is consumed in parallel in a separate thread.\n        input_copies = list(atee(input, len(steps), lock=asyncio.Lock()))\n        # Create the transform() generator for each step\n        named_generators = [\n            (\n                name,\n                step.atransform(\n                    input_copies.pop(),\n                    patch_config(\n                        config, callbacks=run_manager.get_child(f\"map:key:{name}\")\n                    ),\n                ),\n            )\n            for name, step in steps.items()\n        ]\n        # Wrap in a coroutine to satisfy linter\n        async def get_next_chunk(generator: AsyncIterator) -> Optional[Output]:\n            return await py_anext(generator)\n        # Start the first iteration of each generator\n        tasks = {\n            asyncio.create_task(get_next_chunk(generator)): (step_name, generator)\n            for step_name, generator in named_generators\n        }\n        # Yield chunks from each as they become available,\n        # and start the next iteration of the generator that yielded it.\n        # When all generators are exhausted, stop.\n        while tasks:\n            completed_tasks, _ = await asyncio.wait(\n                tasks, return_when=asyncio.FIRST_COMPLETED\n            )\n            for task in completed_tasks:\n                (step_name, generator) = tasks.pop(task)\n                try:\n                    chunk = AddableDict({step_name: task.result()})\n                    yield chunk\n                    new_task = asyncio.create_task(get_next_chunk(generator))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-44", "text": "yield chunk\n                    new_task = asyncio.create_task(get_next_chunk(generator))\n                    tasks[new_task] = (step_name, generator)\n                except StopAsyncIteration:\n                    pass\n[docs]    async def atransform(\n        self,\n        input: AsyncIterator[Input],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[Dict[str, Any]]:\n        async for chunk in self._atransform_stream_with_config(\n            input, self._atransform, config, **kwargs\n        ):\n            yield chunk\n[docs]    async def astream(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> AsyncIterator[Dict[str, Any]]:\n        async def input_aiter() -> AsyncIterator[Input]:\n            yield input\n        async for chunk in self.atransform(input_aiter(), config):\n            yield chunk\n# We support both names\nRunnableMap = RunnableParallel\n[docs]class RunnableGenerator(Runnable[Input, Output]):\n    \"\"\"\n    A runnable that runs a generator function.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        transform: Union[\n            Callable[[Iterator[Input]], Iterator[Output]],\n            Callable[[AsyncIterator[Input]], AsyncIterator[Output]],\n        ],\n        atransform: Optional[\n            Callable[[AsyncIterator[Input]], AsyncIterator[Output]]\n        ] = None,\n    ) -> None:\n        if atransform is not None:\n            self._atransform = atransform\n        if inspect.isasyncgenfunction(transform):\n            self._atransform = transform\n        elif inspect.isgeneratorfunction(transform):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-45", "text": "self._atransform = transform\n        elif inspect.isgeneratorfunction(transform):\n            self._transform = transform\n        else:\n            raise TypeError(\n                \"Expected a generator function type for `transform`.\"\n                f\"Instead got an unsupported type: {type(transform)}\"\n            )\n    @property\n    def InputType(self) -> Any:\n        func = getattr(self, \"_transform\", None) or getattr(self, \"_atransform\")\n        try:\n            params = inspect.signature(func).parameters\n            first_param = next(iter(params.values()), None)\n            if first_param and first_param.annotation != inspect.Parameter.empty:\n                return getattr(first_param.annotation, \"__args__\", (Any,))[0]\n            else:\n                return Any\n        except ValueError:\n            return Any\n    @property\n    def OutputType(self) -> Any:\n        func = getattr(self, \"_transform\", None) or getattr(self, \"_atransform\")\n        try:\n            sig = inspect.signature(func)\n            return (\n                getattr(sig.return_annotation, \"__args__\", (Any,))[0]\n                if sig.return_annotation != inspect.Signature.empty\n                else Any\n            )\n        except ValueError:\n            return Any\n    def __eq__(self, other: Any) -> bool:\n        if isinstance(other, RunnableGenerator):\n            if hasattr(self, \"_transform\") and hasattr(other, \"_transform\"):\n                return self._transform == other._transform\n            elif hasattr(self, \"_atransform\") and hasattr(other, \"_atransform\"):\n                return self._atransform == other._atransform\n            else:\n                return False\n        else:\n            return False\n    def __repr__(self) -> str:\n        return \"RunnableGenerator(...)\"\n[docs]    def transform(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-46", "text": "return \"RunnableGenerator(...)\"\n[docs]    def transform(\n        self,\n        input: Iterator[Input],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Iterator[Output]:\n        return self._transform_stream_with_config(\n            input, self._transform, config, **kwargs\n        )\n[docs]    def stream(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Iterator[Output]:\n        return self.transform(iter([input]), config, **kwargs)\n[docs]    def invoke(\n        self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any\n    ) -> Output:\n        final = None\n        for output in self.stream(input, config, **kwargs):\n            if final is None:\n                final = output\n            else:\n                final = final + output\n        return cast(Output, final)\n[docs]    def atransform(\n        self,\n        input: AsyncIterator[Input],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[Output]:\n        if not hasattr(self, \"_atransform\"):\n            raise NotImplementedError(\"This runnable does not support async methods.\")\n        return self._atransform_stream_with_config(\n            input, self._atransform, config, **kwargs\n        )\n[docs]    def astream(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[Output]:\n        async def input_aiter() -> AsyncIterator[Input]:\n            yield input", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-47", "text": "async def input_aiter() -> AsyncIterator[Input]:\n            yield input\n        return self.atransform(input_aiter(), config, **kwargs)\n[docs]    async def ainvoke(\n        self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any\n    ) -> Output:\n        final = None\n        async for output in self.astream(input, config, **kwargs):\n            if final is None:\n                final = output\n            else:\n                final = final + output\n        return cast(Output, final)\n[docs]class RunnableLambda(Runnable[Input, Output]):\n    \"\"\"RunnableLambda converts a python callable into a Runnable.\n    Wrapping a callable in a RunnableLambda makes the callable usable\n    within either a sync or async context.\n    RunnableLambda can be composed as any other Runnable and provides\n    seamless integration with LangChain tracing.\n    Examples:\n        .. code-block:: python\n            # This is a RunnableLambda\n            from langchain.schema.runnable import RunnableLambda\n            def add_one(x: int) -> int:\n                return x + 1\n            runnable = RunnableLambda(add_one)\n            runnable.invoke(1) # returns 2\n            runnable.batch([1, 2, 3]) # returns [2, 3, 4]\n            # Async is supported by default by delegating to the sync implementation\n            await runnable.ainvoke(1) # returns 2\n            await runnable.abatch([1, 2, 3]) # returns [2, 3, 4]\n            # Alternatively, can provide both synd and sync implementations\n            async def add_one_async(x: int) -> int:\n                return x + 1\n            runnable = RunnableLambda(add_one, afunc=add_one_async)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-48", "text": "runnable = RunnableLambda(add_one, afunc=add_one_async)\n            runnable.invoke(1) # Uses add_one\n            await runnable.ainvoke(1) # Uses add_one_async\n    \"\"\"\n[docs]    def __init__(\n        self,\n        func: Union[\n            Union[\n                Callable[[Input], Output],\n                Callable[[Input, RunnableConfig], Output],\n                Callable[[Input, CallbackManagerForChainRun], Output],\n                Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output],\n            ],\n            Union[\n                Callable[[Input], Awaitable[Output]],\n                Callable[[Input, RunnableConfig], Awaitable[Output]],\n                Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]],\n                Callable[\n                    [Input, AsyncCallbackManagerForChainRun, RunnableConfig],\n                    Awaitable[Output],\n                ],\n            ],\n        ],\n        afunc: Optional[\n            Union[\n                Callable[[Input], Awaitable[Output]],\n                Callable[[Input, RunnableConfig], Awaitable[Output]],\n                Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]],\n                Callable[\n                    [Input, AsyncCallbackManagerForChainRun, RunnableConfig],\n                    Awaitable[Output],\n                ],\n            ]\n        ] = None,\n    ) -> None:\n        \"\"\"Create a RunnableLambda from a callable, and async callable or both.\n        Accepts both sync and async variants to allow providing efficient\n        implementations for sync and async execution.\n        Args:\n            func: Either sync or async callable\n            afunc: An async callable that takes an input and returns an output.\n        \"\"\"\n        if afunc is not None:\n            self.afunc = afunc\n        if inspect.iscoroutinefunction(func):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-49", "text": "self.afunc = afunc\n        if inspect.iscoroutinefunction(func):\n            if afunc is not None:\n                raise TypeError(\n                    \"Func was provided as a coroutine function, but afunc was \"\n                    \"also provided. If providing both, func should be a regular \"\n                    \"function to avoid ambiguity.\"\n                )\n            self.afunc = func\n        elif callable(func):\n            self.func = cast(Callable[[Input], Output], func)\n        else:\n            raise TypeError(\n                \"Expected a callable type for `func`.\"\n                f\"Instead got an unsupported type: {type(func)}\"\n            )\n    @property\n    def InputType(self) -> Any:\n        \"\"\"The type of the input to this runnable.\"\"\"\n        func = getattr(self, \"func\", None) or getattr(self, \"afunc\")\n        try:\n            params = inspect.signature(func).parameters\n            first_param = next(iter(params.values()), None)\n            if first_param and first_param.annotation != inspect.Parameter.empty:\n                return first_param.annotation\n            else:\n                return Any\n        except ValueError:\n            return Any\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        \"\"\"The pydantic schema for the input to this runnable.\"\"\"\n        func = getattr(self, \"func\", None) or getattr(self, \"afunc\")\n        if isinstance(func, itemgetter):\n            # This is terrible, but afaict it's not possible to access _items\n            # on itemgetter objects, so we have to parse the repr\n            items = str(func).replace(\"operator.itemgetter(\", \"\")[:-1].split(\", \")\n            if all(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-50", "text": "if all(\n                item[0] == \"'\" and item[-1] == \"'\" and len(item) > 2 for item in items\n            ):\n                # It's a dict, lol\n                return create_model(\n                    \"RunnableLambdaInput\",\n                    **{item[1:-1]: (Any, None) for item in items},  # type: ignore\n                )\n            else:\n                return create_model(\"RunnableLambdaInput\", __root__=(List[Any], None))\n        if self.InputType != Any:\n            return super().get_input_schema(config)\n        if dict_keys := get_function_first_arg_dict_keys(func):\n            return create_model(\n                \"RunnableLambdaInput\",\n                **{key: (Any, None) for key in dict_keys},  # type: ignore\n            )\n        return super().get_input_schema(config)\n    @property\n    def OutputType(self) -> Any:\n        \"\"\"The type of the output of this runnable as a type annotation.\"\"\"\n        func = getattr(self, \"func\", None) or getattr(self, \"afunc\")\n        try:\n            sig = inspect.signature(func)\n            return (\n                sig.return_annotation\n                if sig.return_annotation != inspect.Signature.empty\n                else Any\n            )\n        except ValueError:\n            return Any\n    def __eq__(self, other: Any) -> bool:\n        if isinstance(other, RunnableLambda):\n            if hasattr(self, \"func\") and hasattr(other, \"func\"):\n                return self.func == other.func\n            elif hasattr(self, \"afunc\") and hasattr(other, \"afunc\"):\n                return self.afunc == other.afunc\n            else:\n                return False\n        else:\n            return False\n    def __repr__(self) -> str:\n        \"\"\"A string representation of this runnable.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-51", "text": "\"\"\"A string representation of this runnable.\"\"\"\n        if hasattr(self, \"func\"):\n            return f\"RunnableLambda({get_lambda_source(self.func) or '...'})\"\n        elif hasattr(self, \"afunc\"):\n            return f\"RunnableLambda(afunc={get_lambda_source(self.afunc) or '...'})\"\n        else:\n            return \"RunnableLambda(...)\"\n    def _invoke(\n        self,\n        input: Input,\n        run_manager: CallbackManagerForChainRun,\n        config: RunnableConfig,\n        **kwargs: Any,\n    ) -> Output:\n        output = call_func_with_variable_args(\n            self.func, input, config, run_manager, **kwargs\n        )\n        # If the output is a runnable, invoke it\n        if isinstance(output, Runnable):\n            recursion_limit = config[\"recursion_limit\"]\n            if recursion_limit <= 0:\n                raise RecursionError(\n                    f\"Recursion limit reached when invoking {self} with input {input}.\"\n                )\n            output = output.invoke(\n                input,\n                patch_config(\n                    config,\n                    callbacks=run_manager.get_child(),\n                    recursion_limit=recursion_limit - 1,\n                ),\n            )\n        return output\n    async def _ainvoke(\n        self,\n        input: Input,\n        run_manager: AsyncCallbackManagerForChainRun,\n        config: RunnableConfig,\n        **kwargs: Any,\n    ) -> Output:\n        output = await acall_func_with_variable_args(\n            self.afunc, input, config, run_manager, **kwargs\n        )\n        # If the output is a runnable, invoke it\n        if isinstance(output, Runnable):\n            recursion_limit = config[\"recursion_limit\"]\n            if recursion_limit <= 0:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-52", "text": "recursion_limit = config[\"recursion_limit\"]\n            if recursion_limit <= 0:\n                raise RecursionError(\n                    f\"Recursion limit reached when invoking {self} with input {input}.\"\n                )\n            output = await output.ainvoke(\n                input,\n                patch_config(\n                    config,\n                    callbacks=run_manager.get_child(),\n                    recursion_limit=recursion_limit - 1,\n                ),\n            )\n        return output\n    def _config(\n        self, config: Optional[RunnableConfig], callable: Callable[..., Any]\n    ) -> RunnableConfig:\n        config = config or {}\n        if config.get(\"run_name\") is None:\n            try:\n                run_name = callable.__name__\n            except AttributeError:\n                run_name = None\n            if run_name is not None:\n                return patch_config(config, run_name=run_name)\n        return config\n[docs]    def invoke(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Output:\n        \"\"\"Invoke this runnable synchronously.\"\"\"\n        if hasattr(self, \"func\"):\n            return self._call_with_config(\n                self._invoke,\n                input,\n                self._config(config, self.func),\n                **kwargs,\n            )\n        else:\n            raise TypeError(\n                \"Cannot invoke a coroutine function synchronously.\"\n                \"Use `ainvoke` instead.\"\n            )\n[docs]    async def ainvoke(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Output:\n        \"\"\"Invoke this runnable asynchronously.\"\"\"\n        if hasattr(self, \"afunc\"):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-53", "text": "\"\"\"Invoke this runnable asynchronously.\"\"\"\n        if hasattr(self, \"afunc\"):\n            return await self._acall_with_config(\n                self._ainvoke,\n                input,\n                self._config(config, self.afunc),\n                **kwargs,\n            )\n        else:\n            # Delegating to super implementation of ainvoke.\n            # Uses asyncio executor to run the sync version (invoke)\n            return await super().ainvoke(input, config)\n[docs]class RunnableEachBase(RunnableSerializable[List[Input], List[Output]]):\n    \"\"\"\n    A runnable that delegates calls to another runnable\n    with each element of the input sequence.\n    Use only if creating a new RunnableEach subclass with different __init__ args.\n    \"\"\"\n    bound: Runnable[Input, Output]\n    class Config:\n        arbitrary_types_allowed = True\n    @property\n    def InputType(self) -> Any:\n        return List[self.bound.InputType]  # type: ignore[name-defined]\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        return create_model(\n            \"RunnableEachInput\",\n            __root__=(\n                List[self.bound.get_input_schema(config)],  # type: ignore\n                None,\n            ),\n        )\n    @property\n    def OutputType(self) -> Type[List[Output]]:\n        return List[self.bound.OutputType]  # type: ignore[name-defined]\n[docs]    def get_output_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        schema = self.bound.get_output_schema(config)\n        return create_model(\n            \"RunnableEachOutput\",\n            __root__=(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-54", "text": "return create_model(\n            \"RunnableEachOutput\",\n            __root__=(\n                List[schema],  # type: ignore\n                None,\n            ),\n        )\n    @property\n    def config_specs(self) -> List[ConfigurableFieldSpec]:\n        return self.bound.config_specs\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n[docs]    @classmethod\n    def get_lc_namespace(cls) -> List[str]:\n        return cls.__module__.split(\".\")[:-1]\n    def _invoke(\n        self,\n        inputs: List[Input],\n        run_manager: CallbackManagerForChainRun,\n        config: RunnableConfig,\n        **kwargs: Any,\n    ) -> List[Output]:\n        return self.bound.batch(\n            inputs, patch_config(config, callbacks=run_manager.get_child()), **kwargs\n        )\n[docs]    def invoke(\n        self, input: List[Input], config: Optional[RunnableConfig] = None, **kwargs: Any\n    ) -> List[Output]:\n        return self._call_with_config(self._invoke, input, config, **kwargs)\n    async def _ainvoke(\n        self,\n        inputs: List[Input],\n        run_manager: AsyncCallbackManagerForChainRun,\n        config: RunnableConfig,\n        **kwargs: Any,\n    ) -> List[Output]:\n        return await self.bound.abatch(\n            inputs, patch_config(config, callbacks=run_manager.get_child()), **kwargs\n        )\n[docs]    async def ainvoke(\n        self, input: List[Input], config: Optional[RunnableConfig] = None, **kwargs: Any\n    ) -> List[Output]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-55", "text": ") -> List[Output]:\n        return await self._acall_with_config(self._ainvoke, input, config, **kwargs)\n[docs]class RunnableEach(RunnableEachBase[Input, Output]):\n    \"\"\"\n    A runnable that delegates calls to another runnable\n    with each element of the input sequence.\n    \"\"\"\n[docs]    def bind(self, **kwargs: Any) -> RunnableEach[Input, Output]:\n        return RunnableEach(bound=self.bound.bind(**kwargs))\n[docs]    def with_config(\n        self, config: Optional[RunnableConfig] = None, **kwargs: Any\n    ) -> RunnableEach[Input, Output]:\n        return RunnableEach(bound=self.bound.with_config(config, **kwargs))\n[docs]    def with_listeners(\n        self,\n        *,\n        on_start: Optional[Listener] = None,\n        on_end: Optional[Listener] = None,\n        on_error: Optional[Listener] = None,\n    ) -> RunnableEach[Input, Output]:\n        \"\"\"\n        Bind lifecycle listeners to a Runnable, returning a new Runnable.\n        on_start: Called before the runnable starts running, with the Run object.\n        on_end: Called after the runnable finishes running, with the Run object.\n        on_error: Called if the runnable throws an error, with the Run object.\n        The Run object contains information about the run, including its id,\n        type, input, output, error, start_time, end_time, and any tags or metadata\n        added to the run.\n        \"\"\"\n        return RunnableEach(\n            bound=self.bound.with_listeners(\n                on_start=on_start, on_end=on_end, on_error=on_error\n            )\n        )\n[docs]class RunnableBindingBase(RunnableSerializable[Input, Output]):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-56", "text": ")\n[docs]class RunnableBindingBase(RunnableSerializable[Input, Output]):\n    \"\"\"\n    A runnable that delegates calls to another runnable with a set of kwargs.\n    Use only if creating a new RunnableBinding subclass with different __init__ args.\n    \"\"\"\n    bound: Runnable[Input, Output]\n    kwargs: Mapping[str, Any] = Field(default_factory=dict)\n    config: RunnableConfig = Field(default_factory=dict)\n    config_factories: List[Callable[[RunnableConfig], RunnableConfig]] = Field(\n        default_factory=list\n    )\n    # Union[Type[Input], BaseModel] + things like List[str]\n    custom_input_type: Optional[Any] = None\n    # Union[Type[Output], BaseModel] + things like List[str]\n    custom_output_type: Optional[Any] = None\n    class Config:\n        arbitrary_types_allowed = True\n    def __init__(\n        self,\n        *,\n        bound: Runnable[Input, Output],\n        kwargs: Optional[Mapping[str, Any]] = None,\n        config: Optional[RunnableConfig] = None,\n        config_factories: Optional[\n            List[Callable[[RunnableConfig], RunnableConfig]]\n        ] = None,\n        custom_input_type: Optional[Union[Type[Input], BaseModel]] = None,\n        custom_output_type: Optional[Union[Type[Output], BaseModel]] = None,\n        **other_kwargs: Any,\n    ) -> None:\n        config = config or {}\n        # config_specs contains the list of valid `configurable` keys\n        if configurable := config.get(\"configurable\", None):\n            allowed_keys = set(s.id for s in bound.config_specs)\n            for key in configurable:\n                if key not in allowed_keys:\n                    raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-57", "text": "if key not in allowed_keys:\n                    raise ValueError(\n                        f\"Configurable key '{key}' not found in runnable with\"\n                        f\" config keys: {allowed_keys}\"\n                    )\n        super().__init__(\n            bound=bound,\n            kwargs=kwargs or {},\n            config=config or {},\n            config_factories=config_factories or [],\n            custom_input_type=custom_input_type,\n            custom_output_type=custom_output_type,\n            **other_kwargs,\n        )\n    @property\n    def InputType(self) -> Type[Input]:\n        return (\n            cast(Type[Input], self.custom_input_type)\n            if self.custom_input_type is not None\n            else self.bound.InputType\n        )\n    @property\n    def OutputType(self) -> Type[Output]:\n        return (\n            cast(Type[Output], self.custom_output_type)\n            if self.custom_output_type is not None\n            else self.bound.OutputType\n        )\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        if self.custom_input_type is not None:\n            return super().get_input_schema(config)\n        return self.bound.get_input_schema(merge_configs(self.config, config))\n[docs]    def get_output_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        if self.custom_output_type is not None:\n            return super().get_output_schema(config)\n        return self.bound.get_output_schema(merge_configs(self.config, config))\n    @property\n    def config_specs(self) -> List[ConfigurableFieldSpec]:\n        return self.bound.config_specs\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-58", "text": "[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n[docs]    @classmethod\n    def get_lc_namespace(cls) -> List[str]:\n        return cls.__module__.split(\".\")[:-1]\n    def _merge_configs(self, *configs: Optional[RunnableConfig]) -> RunnableConfig:\n        config = merge_configs(self.config, *configs)\n        return merge_configs(config, *(f(config) for f in self.config_factories))\n[docs]    def invoke(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Output:\n        return self.bound.invoke(\n            input,\n            self._merge_configs(config),\n            **{**self.kwargs, **kwargs},\n        )\n[docs]    async def ainvoke(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Output:\n        return await self.bound.ainvoke(\n            input,\n            self._merge_configs(config),\n            **{**self.kwargs, **kwargs},\n        )\n[docs]    def batch(\n        self,\n        inputs: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        if isinstance(config, list):\n            configs = cast(\n                List[RunnableConfig],\n                [self._merge_configs(conf) for conf in config],\n            )\n        else:\n            configs = [self._merge_configs(config) for _ in range(len(inputs))]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-59", "text": "configs = [self._merge_configs(config) for _ in range(len(inputs))]\n        return self.bound.batch(\n            inputs,\n            configs,\n            return_exceptions=return_exceptions,\n            **{**self.kwargs, **kwargs},\n        )\n[docs]    async def abatch(\n        self,\n        inputs: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        if isinstance(config, list):\n            configs = cast(\n                List[RunnableConfig],\n                [self._merge_configs(conf) for conf in config],\n            )\n        else:\n            configs = [self._merge_configs(config) for _ in range(len(inputs))]\n        return await self.bound.abatch(\n            inputs,\n            configs,\n            return_exceptions=return_exceptions,\n            **{**self.kwargs, **kwargs},\n        )\n[docs]    def stream(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Iterator[Output]:\n        yield from self.bound.stream(\n            input,\n            self._merge_configs(config),\n            **{**self.kwargs, **kwargs},\n        )\n[docs]    async def astream(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> AsyncIterator[Output]:\n        async for item in self.bound.astream(\n            input,\n            self._merge_configs(config),\n            **{**self.kwargs, **kwargs},\n        ):\n            yield item", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-60", "text": "**{**self.kwargs, **kwargs},\n        ):\n            yield item\n[docs]    def transform(\n        self,\n        input: Iterator[Input],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> Iterator[Output]:\n        yield from self.bound.transform(\n            input,\n            self._merge_configs(config),\n            **{**self.kwargs, **kwargs},\n        )\n[docs]    async def atransform(\n        self,\n        input: AsyncIterator[Input],\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[Output]:\n        async for item in self.bound.atransform(\n            input,\n            self._merge_configs(config),\n            **{**self.kwargs, **kwargs},\n        ):\n            yield item\nRunnableBindingBase.update_forward_refs(RunnableConfig=RunnableConfig)\n[docs]class RunnableBinding(RunnableBindingBase[Input, Output]):\n    \"\"\"\n    A runnable that delegates calls to another runnable with a set of kwargs.\n    \"\"\"\n[docs]    def bind(self, **kwargs: Any) -> Runnable[Input, Output]:\n        return self.__class__(\n            bound=self.bound,\n            config=self.config,\n            kwargs={**self.kwargs, **kwargs},\n            custom_input_type=self.custom_input_type,\n            custom_output_type=self.custom_output_type,\n        )\n[docs]    def with_config(\n        self,\n        config: Optional[RunnableConfig] = None,\n        # Sadly Unpack is not well supported by mypy so this will have to be untyped\n        **kwargs: Any,\n    ) -> Runnable[Input, Output]:\n        return self.__class__(\n            bound=self.bound,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-61", "text": "return self.__class__(\n            bound=self.bound,\n            kwargs=self.kwargs,\n            config=cast(RunnableConfig, {**self.config, **(config or {}), **kwargs}),\n            custom_input_type=self.custom_input_type,\n            custom_output_type=self.custom_output_type,\n        )\n[docs]    def with_listeners(\n        self,\n        *,\n        on_start: Optional[Listener] = None,\n        on_end: Optional[Listener] = None,\n        on_error: Optional[Listener] = None,\n    ) -> Runnable[Input, Output]:\n        \"\"\"\n        Bind lifecycle listeners to a Runnable, returning a new Runnable.\n        on_start: Called before the runnable starts running, with the Run object.\n        on_end: Called after the runnable finishes running, with the Run object.\n        on_error: Called if the runnable throws an error, with the Run object.\n        The Run object contains information about the run, including its id,\n        type, input, output, error, start_time, end_time, and any tags or metadata\n        added to the run.\n        \"\"\"\n        from langchain.callbacks.tracers.root_listeners import RootListenersTracer\n        return self.__class__(\n            bound=self.bound,\n            kwargs=self.kwargs,\n            config=self.config,\n            config_factories=[\n                lambda config: {\n                    \"callbacks\": [\n                        RootListenersTracer(\n                            config=config,\n                            on_start=on_start,\n                            on_end=on_end,\n                            on_error=on_error,\n                        )\n                    ],\n                }\n            ],\n            custom_input_type=self.custom_input_type,\n            custom_output_type=self.custom_output_type,\n        )\n[docs]    def with_types(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-62", "text": ")\n[docs]    def with_types(\n        self,\n        input_type: Optional[Union[Type[Input], BaseModel]] = None,\n        output_type: Optional[Union[Type[Output], BaseModel]] = None,\n    ) -> Runnable[Input, Output]:\n        return self.__class__(\n            bound=self.bound,\n            kwargs=self.kwargs,\n            config=self.config,\n            custom_input_type=input_type\n            if input_type is not None\n            else self.custom_input_type,\n            custom_output_type=output_type\n            if output_type is not None\n            else self.custom_output_type,\n        )\n[docs]    def with_retry(self, **kwargs: Any) -> Runnable[Input, Output]:\n        return self.__class__(\n            bound=self.bound.with_retry(**kwargs),\n            kwargs=self.kwargs,\n            config=self.config,\n        )\nRunnableLike = Union[\n    Runnable[Input, Output],\n    Callable[[Input], Output],\n    Callable[[Input], Awaitable[Output]],\n    Callable[[Iterator[Input]], Iterator[Output]],\n    Callable[[AsyncIterator[Input]], AsyncIterator[Output]],\n    Mapping[str, Any],\n]\n[docs]def coerce_to_runnable(thing: RunnableLike) -> Runnable[Input, Output]:\n    \"\"\"Coerce a runnable-like object into a Runnable.\n    Args:\n        thing: A runnable-like object.\n    Returns:\n        A Runnable.\n    \"\"\"\n    if isinstance(thing, Runnable):\n        return thing\n    elif inspect.isasyncgenfunction(thing) or inspect.isgeneratorfunction(thing):\n        return RunnableGenerator(thing)\n    elif callable(thing):\n        return RunnableLambda(cast(Callable[[Input], Output], thing))\n    elif isinstance(thing, dict):\n        return cast(Runnable[Input, Output], RunnableParallel(thing))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "7cd2723fa80e-63", "text": "return cast(Runnable[Input, Output], RunnableParallel(thing))\n    else:\n        raise TypeError(\n            f\"Expected a Runnable, callable or dict.\"\n            f\"Instead got an unsupported type: {type(thing)}\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html"}
{"id": "f94b50230f5b-0", "text": "Source code for langchain.schema.runnable.router\nfrom __future__ import annotations\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Callable,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Union,\n    cast,\n)\nfrom typing_extensions import TypedDict\nfrom langchain.schema.runnable.base import (\n    Input,\n    Output,\n    Runnable,\n    RunnableSerializable,\n    coerce_to_runnable,\n)\nfrom langchain.schema.runnable.config import (\n    RunnableConfig,\n    get_config_list,\n    get_executor_for_config,\n)\nfrom langchain.schema.runnable.utils import (\n    ConfigurableFieldSpec,\n    gather_with_concurrency,\n    get_unique_config_specs,\n)\n[docs]class RouterInput(TypedDict):\n    \"\"\"A Router input.\n    Attributes:\n        key: The key to route on.\n        input: The input to pass to the selected runnable.\n    \"\"\"\n    key: str\n    input: Any\n[docs]class RouterRunnable(RunnableSerializable[RouterInput, Output]):\n    \"\"\"\n    A runnable that routes to a set of runnables based on Input['key'].\n    Returns the output of the selected runnable.\n    \"\"\"\n    runnables: Mapping[str, Runnable[Any, Output]]\n    @property\n    def config_specs(self) -> List[ConfigurableFieldSpec]:\n        return get_unique_config_specs(\n            spec for step in self.runnables.values() for spec in step.config_specs\n        )\n    def __init__(\n        self,\n        runnables: Mapping[str, Union[Runnable[Any, Output], Callable[[Any], Output]]],\n    ) -> None:\n        super().__init__(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/router.html"}
{"id": "f94b50230f5b-1", "text": ") -> None:\n        super().__init__(\n            runnables={key: coerce_to_runnable(r) for key, r in runnables.items()}\n        )\n    class Config:\n        arbitrary_types_allowed = True\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this class is serializable.\"\"\"\n        return True\n[docs]    @classmethod\n    def get_lc_namespace(cls) -> List[str]:\n        return cls.__module__.split(\".\")[:-1]\n[docs]    def invoke(\n        self, input: RouterInput, config: Optional[RunnableConfig] = None\n    ) -> Output:\n        key = input[\"key\"]\n        actual_input = input[\"input\"]\n        if key not in self.runnables:\n            raise ValueError(f\"No runnable associated with key '{key}'\")\n        runnable = self.runnables[key]\n        return runnable.invoke(actual_input, config)\n[docs]    async def ainvoke(\n        self,\n        input: RouterInput,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Output:\n        key = input[\"key\"]\n        actual_input = input[\"input\"]\n        if key not in self.runnables:\n            raise ValueError(f\"No runnable associated with key '{key}'\")\n        runnable = self.runnables[key]\n        return await runnable.ainvoke(actual_input, config)\n[docs]    def batch(\n        self,\n        inputs: List[RouterInput],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        if not inputs:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/router.html"}
{"id": "f94b50230f5b-2", "text": ") -> List[Output]:\n        if not inputs:\n            return []\n        keys = [input[\"key\"] for input in inputs]\n        actual_inputs = [input[\"input\"] for input in inputs]\n        if any(key not in self.runnables for key in keys):\n            raise ValueError(\"One or more keys do not have a corresponding runnable\")\n        def invoke(\n            runnable: Runnable, input: Input, config: RunnableConfig\n        ) -> Union[Output, Exception]:\n            if return_exceptions:\n                try:\n                    return runnable.invoke(input, config, **kwargs)\n                except Exception as e:\n                    return e\n            else:\n                return runnable.invoke(input, config, **kwargs)\n        runnables = [self.runnables[key] for key in keys]\n        configs = get_config_list(config, len(inputs))\n        with get_executor_for_config(configs[0]) as executor:\n            return cast(\n                List[Output],\n                list(executor.map(invoke, runnables, actual_inputs, configs)),\n            )\n[docs]    async def abatch(\n        self,\n        inputs: List[RouterInput],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        if not inputs:\n            return []\n        keys = [input[\"key\"] for input in inputs]\n        actual_inputs = [input[\"input\"] for input in inputs]\n        if any(key not in self.runnables for key in keys):\n            raise ValueError(\"One or more keys do not have a corresponding runnable\")\n        async def ainvoke(\n            runnable: Runnable, input: Input, config: RunnableConfig", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/router.html"}
{"id": "f94b50230f5b-3", "text": "runnable: Runnable, input: Input, config: RunnableConfig\n        ) -> Union[Output, Exception]:\n            if return_exceptions:\n                try:\n                    return await runnable.ainvoke(input, config, **kwargs)\n                except Exception as e:\n                    return e\n            else:\n                return await runnable.ainvoke(input, config, **kwargs)\n        runnables = [self.runnables[key] for key in keys]\n        configs = get_config_list(config, len(inputs))\n        return await gather_with_concurrency(\n            configs[0].get(\"max_concurrency\"),\n            *(\n                ainvoke(runnable, input, config)\n                for runnable, input, config in zip(runnables, actual_inputs, configs)\n            ),\n        )\n[docs]    def stream(\n        self,\n        input: RouterInput,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Iterator[Output]:\n        key = input[\"key\"]\n        actual_input = input[\"input\"]\n        if key not in self.runnables:\n            raise ValueError(f\"No runnable associated with key '{key}'\")\n        runnable = self.runnables[key]\n        yield from runnable.stream(actual_input, config)\n[docs]    async def astream(\n        self,\n        input: RouterInput,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> AsyncIterator[Output]:\n        key = input[\"key\"]\n        actual_input = input[\"input\"]\n        if key not in self.runnables:\n            raise ValueError(f\"No runnable associated with key '{key}'\")\n        runnable = self.runnables[key]\n        async for output in runnable.astream(actual_input, config):\n            yield output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/router.html"}
{"id": "d653e3fa9b4b-0", "text": "Source code for langchain.schema.runnable.fallbacks\nimport asyncio\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Iterator,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    Type,\n    Union,\n)\nfrom langchain.load.dump import dumpd\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema.runnable.base import Runnable, RunnableSerializable\nfrom langchain.schema.runnable.config import (\n    RunnableConfig,\n    ensure_config,\n    get_async_callback_manager_for_config,\n    get_callback_manager_for_config,\n    get_config_list,\n    patch_config,\n)\nfrom langchain.schema.runnable.utils import (\n    ConfigurableFieldSpec,\n    Input,\n    Output,\n    get_unique_config_specs,\n)\nif TYPE_CHECKING:\n    from langchain.callbacks.manager import AsyncCallbackManagerForChainRun\n[docs]class RunnableWithFallbacks(RunnableSerializable[Input, Output]):\n    \"\"\"A Runnable that can fallback to other Runnables if it fails.\n    External APIs (e.g., APIs for a language model) may at times experience\n    degraded performance or even downtime.\n    In these cases, it can be useful to have a fallback runnable that can be\n    used in place of the original runnable (e.g., fallback to another LLM provider).\n    Fallbacks can be defined at the level of a single runnable, or at the level\n    of a chain of runnables. Fallbacks are tried in order until one succeeds or\n    all fail.\n    While you can instantiate a ``RunnableWithFallbacks`` directly, it is usually\n    more convenient to use the ``with_fallbacks`` method on a runnable.\n    Example:\n        .. code-block:: python\n            from langchain.chat_models.openai import ChatOpenAI", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html"}
{"id": "d653e3fa9b4b-1", "text": ".. code-block:: python\n            from langchain.chat_models.openai import ChatOpenAI\n            from langchain.chat_models.anthropic import ChatAnthropic\n            model = ChatAnthropic().with_fallbacks([ChatOpenAI()])\n            # Will usually use ChatAnthropic, but fallback to ChatOpenAI\n            # if ChatAnthropic fails.\n            model.invoke('hello')\n            # And you can also use fallbacks at the level of a chain.\n            # Here if both LLM providers fail, we'll fallback to a good hardcoded\n            # response.\n            from langchain.prompts import PromptTemplate\n            from langchain.schema.output_parser import StrOutputParser\n            from langchain.schema.runnable import RunnableLambda\n            def when_all_is_lost(inputs):\n                return (\"Looks like our LLM providers are down. \"\n                        \"Here's a nice \ud83e\udd9c\ufe0f emoji for you instead.\")\n            chain_with_fallback = (\n                PromptTemplate.from_template('Tell me a joke about {topic}')\n                | model\n                | StrOutputParser()\n            ).with_fallbacks([RunnableLambda(when_all_is_lost)])\n    \"\"\"\n    runnable: Runnable[Input, Output]\n    \"\"\"The runnable to run first.\"\"\"\n    fallbacks: Sequence[Runnable[Input, Output]]\n    \"\"\"A sequence of fallbacks to try.\"\"\"\n    exceptions_to_handle: Tuple[Type[BaseException], ...] = (Exception,)\n    \"\"\"The exceptions on which fallbacks should be tried.\n    \n    Any exception that is not a subclass of these exceptions will be raised immediately.\n    \"\"\"\n    class Config:\n        arbitrary_types_allowed = True\n    @property\n    def InputType(self) -> Type[Input]:\n        return self.runnable.InputType\n    @property\n    def OutputType(self) -> Type[Output]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html"}
{"id": "d653e3fa9b4b-2", "text": "@property\n    def OutputType(self) -> Type[Output]:\n        return self.runnable.OutputType\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        return self.runnable.get_input_schema(config)\n[docs]    def get_output_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        return self.runnable.get_output_schema(config)\n    @property\n    def config_specs(self) -> List[ConfigurableFieldSpec]:\n        return get_unique_config_specs(\n            spec\n            for step in [self.runnable, *self.fallbacks]\n            for spec in step.config_specs\n        )\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n[docs]    @classmethod\n    def get_lc_namespace(cls) -> List[str]:\n        return cls.__module__.split(\".\")[:-1]\n    @property\n    def runnables(self) -> Iterator[Runnable[Input, Output]]:\n        yield self.runnable\n        yield from self.fallbacks\n[docs]    def invoke(\n        self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any\n    ) -> Output:\n        # setup callbacks\n        config = ensure_config(config)\n        callback_manager = get_callback_manager_for_config(config)\n        # start the root run\n        run_manager = callback_manager.on_chain_start(\n            dumpd(self), input, name=config.get(\"run_name\")\n        )\n        first_error = None\n        for runnable in self.runnables:\n            try:\n                output = runnable.invoke(\n                    input,\n                    patch_config(config, callbacks=run_manager.get_child()),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html"}
{"id": "d653e3fa9b4b-3", "text": "input,\n                    patch_config(config, callbacks=run_manager.get_child()),\n                    **kwargs,\n                )\n            except self.exceptions_to_handle as e:\n                if first_error is None:\n                    first_error = e\n            except BaseException as e:\n                run_manager.on_chain_error(e)\n                raise e\n            else:\n                run_manager.on_chain_end(output)\n                return output\n        if first_error is None:\n            raise ValueError(\"No error stored at end of fallbacks.\")\n        run_manager.on_chain_error(first_error)\n        raise first_error\n[docs]    async def ainvoke(\n        self,\n        input: Input,\n        config: Optional[RunnableConfig] = None,\n        **kwargs: Optional[Any],\n    ) -> Output:\n        # setup callbacks\n        config = ensure_config(config)\n        callback_manager = get_async_callback_manager_for_config(config)\n        # start the root run\n        run_manager = await callback_manager.on_chain_start(\n            dumpd(self), input, name=config.get(\"run_name\")\n        )\n        first_error = None\n        for runnable in self.runnables:\n            try:\n                output = await runnable.ainvoke(\n                    input,\n                    patch_config(config, callbacks=run_manager.get_child()),\n                    **kwargs,\n                )\n            except self.exceptions_to_handle as e:\n                if first_error is None:\n                    first_error = e\n            except BaseException as e:\n                await run_manager.on_chain_error(e)\n                raise e\n            else:\n                await run_manager.on_chain_end(output)\n                return output\n        if first_error is None:\n            raise ValueError(\"No error stored at end of fallbacks.\")\n        await run_manager.on_chain_error(first_error)\n        raise first_error\n[docs]    def batch(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html"}
{"id": "d653e3fa9b4b-4", "text": "raise first_error\n[docs]    def batch(\n        self,\n        inputs: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        from langchain.callbacks.manager import CallbackManager\n        if return_exceptions:\n            raise NotImplementedError()\n        if not inputs:\n            return []\n        # setup callbacks\n        configs = get_config_list(config, len(inputs))\n        callback_managers = [\n            CallbackManager.configure(\n                inheritable_callbacks=config.get(\"callbacks\"),\n                local_callbacks=None,\n                verbose=False,\n                inheritable_tags=config.get(\"tags\"),\n                local_tags=None,\n                inheritable_metadata=config.get(\"metadata\"),\n                local_metadata=None,\n            )\n            for config in configs\n        ]\n        # start the root runs, one per input\n        run_managers = [\n            cm.on_chain_start(\n                dumpd(self),\n                input if isinstance(input, dict) else {\"input\": input},\n                name=config.get(\"run_name\"),\n            )\n            for cm, input, config in zip(callback_managers, inputs, configs)\n        ]\n        first_error = None\n        for runnable in self.runnables:\n            try:\n                outputs = runnable.batch(\n                    inputs,\n                    [\n                        # each step a child run of the corresponding root run\n                        patch_config(config, callbacks=rm.get_child())\n                        for rm, config in zip(run_managers, configs)\n                    ],\n                    return_exceptions=return_exceptions,\n                    **kwargs,\n                )\n            except self.exceptions_to_handle as e:\n                if first_error is None:\n                    first_error = e", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html"}
{"id": "d653e3fa9b4b-5", "text": "if first_error is None:\n                    first_error = e\n            except BaseException as e:\n                for rm in run_managers:\n                    rm.on_chain_error(e)\n                raise e\n            else:\n                for rm, output in zip(run_managers, outputs):\n                    rm.on_chain_end(output)\n                return outputs\n        if first_error is None:\n            raise ValueError(\"No error stored at end of fallbacks.\")\n        for rm in run_managers:\n            rm.on_chain_error(first_error)\n        raise first_error\n[docs]    async def abatch(\n        self,\n        inputs: List[Input],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Optional[Any],\n    ) -> List[Output]:\n        from langchain.callbacks.manager import AsyncCallbackManager\n        if return_exceptions:\n            raise NotImplementedError()\n        if not inputs:\n            return []\n        # setup callbacks\n        configs = get_config_list(config, len(inputs))\n        callback_managers = [\n            AsyncCallbackManager.configure(\n                inheritable_callbacks=config.get(\"callbacks\"),\n                local_callbacks=None,\n                verbose=False,\n                inheritable_tags=config.get(\"tags\"),\n                local_tags=None,\n                inheritable_metadata=config.get(\"metadata\"),\n                local_metadata=None,\n            )\n            for config in configs\n        ]\n        # start the root runs, one per input\n        run_managers: List[AsyncCallbackManagerForChainRun] = await asyncio.gather(\n            *(\n                cm.on_chain_start(\n                    dumpd(self),\n                    input,\n                    name=config.get(\"run_name\"),\n                )\n                for cm, input, config in zip(callback_managers, inputs, configs)\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html"}
{"id": "d653e3fa9b4b-6", "text": ")\n        )\n        first_error = None\n        for runnable in self.runnables:\n            try:\n                outputs = await runnable.abatch(\n                    inputs,\n                    [\n                        # each step a child run of the corresponding root run\n                        patch_config(config, callbacks=rm.get_child())\n                        for rm, config in zip(run_managers, configs)\n                    ],\n                    return_exceptions=return_exceptions,\n                    **kwargs,\n                )\n            except self.exceptions_to_handle as e:\n                if first_error is None:\n                    first_error = e\n            except BaseException as e:\n                await asyncio.gather(*(rm.on_chain_error(e) for rm in run_managers))\n            else:\n                await asyncio.gather(\n                    *(\n                        rm.on_chain_end(output)\n                        for rm, output in zip(run_managers, outputs)\n                    )\n                )\n                return outputs\n        if first_error is None:\n            raise ValueError(\"No error stored at end of fallbacks.\")\n        await asyncio.gather(*(rm.on_chain_error(first_error) for rm in run_managers))\n        raise first_error", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html"}
{"id": "b766d60527a8-0", "text": "Source code for langchain.schema.runnable.utils\nfrom __future__ import annotations\nimport ast\nimport asyncio\nimport inspect\nimport textwrap\nfrom inspect import signature\nfrom itertools import groupby\nfrom typing import (\n    Any,\n    AsyncIterable,\n    Callable,\n    Coroutine,\n    Dict,\n    Iterable,\n    List,\n    Mapping,\n    NamedTuple,\n    Optional,\n    Protocol,\n    Sequence,\n    Set,\n    TypeVar,\n    Union,\n)\nInput = TypeVar(\"Input\", contravariant=True)\n# Output type should implement __concat__, as eg str, list, dict do\nOutput = TypeVar(\"Output\", covariant=True)\n[docs]async def gated_coro(semaphore: asyncio.Semaphore, coro: Coroutine) -> Any:\n    \"\"\"Run a coroutine with a semaphore.\n    Args:\n        semaphore: The semaphore to use.\n        coro: The coroutine to run.\n    Returns:\n        The result of the coroutine.\n    \"\"\"\n    async with semaphore:\n        return await coro\n[docs]async def gather_with_concurrency(n: Union[int, None], *coros: Coroutine) -> list:\n    \"\"\"Gather coroutines with a limit on the number of concurrent coroutines.\"\"\"\n    if n is None:\n        return await asyncio.gather(*coros)\n    semaphore = asyncio.Semaphore(n)\n    return await asyncio.gather(*(gated_coro(semaphore, c) for c in coros))\n[docs]def accepts_run_manager(callable: Callable[..., Any]) -> bool:\n    \"\"\"Check if a callable accepts a run_manager argument.\"\"\"\n    try:\n        return signature(callable).parameters.get(\"run_manager\") is not None\n    except ValueError:\n        return False", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html"}
{"id": "b766d60527a8-1", "text": "except ValueError:\n        return False\n[docs]def accepts_config(callable: Callable[..., Any]) -> bool:\n    \"\"\"Check if a callable accepts a config argument.\"\"\"\n    try:\n        return signature(callable).parameters.get(\"config\") is not None\n    except ValueError:\n        return False\n[docs]class IsLocalDict(ast.NodeVisitor):\n    \"\"\"Check if a name is a local dict.\"\"\"\n[docs]    def __init__(self, name: str, keys: Set[str]) -> None:\n        self.name = name\n        self.keys = keys\n[docs]    def visit_Subscript(self, node: ast.Subscript) -> Any:\n        if (\n            isinstance(node.ctx, ast.Load)\n            and isinstance(node.value, ast.Name)\n            and node.value.id == self.name\n            and isinstance(node.slice, ast.Constant)\n            and isinstance(node.slice.value, str)\n        ):\n            # we've found a subscript access on the name we're looking for\n            self.keys.add(node.slice.value)\n[docs]    def visit_Call(self, node: ast.Call) -> Any:\n        if (\n            isinstance(node.func, ast.Attribute)\n            and isinstance(node.func.value, ast.Name)\n            and node.func.value.id == self.name\n            and node.func.attr == \"get\"\n            and len(node.args) in (1, 2)\n            and isinstance(node.args[0], ast.Constant)\n            and isinstance(node.args[0].value, str)\n        ):\n            # we've found a .get() call on the name we're looking for\n            self.keys.add(node.args[0].value)\n[docs]class IsFunctionArgDict(ast.NodeVisitor):\n    \"\"\"Check if the first argument of a function is a dict.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html"}
{"id": "b766d60527a8-2", "text": "\"\"\"Check if the first argument of a function is a dict.\"\"\"\n[docs]    def __init__(self) -> None:\n        self.keys: Set[str] = set()\n[docs]    def visit_Lambda(self, node: ast.Lambda) -> Any:\n        input_arg_name = node.args.args[0].arg\n        IsLocalDict(input_arg_name, self.keys).visit(node.body)\n[docs]    def visit_FunctionDef(self, node: ast.FunctionDef) -> Any:\n        input_arg_name = node.args.args[0].arg\n        IsLocalDict(input_arg_name, self.keys).visit(node)\n[docs]    def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> Any:\n        input_arg_name = node.args.args[0].arg\n        IsLocalDict(input_arg_name, self.keys).visit(node)\n[docs]class GetLambdaSource(ast.NodeVisitor):\n    \"\"\"Get the source code of a lambda function.\"\"\"\n[docs]    def __init__(self) -> None:\n        \"\"\"Initialize the visitor.\"\"\"\n        self.source: Optional[str] = None\n        self.count = 0\n[docs]    def visit_Lambda(self, node: ast.Lambda) -> Any:\n        \"\"\"Visit a lambda function.\"\"\"\n        self.count += 1\n        if hasattr(ast, \"unparse\"):\n            self.source = ast.unparse(node)\n[docs]def get_function_first_arg_dict_keys(func: Callable) -> Optional[List[str]]:\n    \"\"\"Get the keys of the first argument of a function if it is a dict.\"\"\"\n    try:\n        code = inspect.getsource(func)\n        tree = ast.parse(textwrap.dedent(code))\n        visitor = IsFunctionArgDict()\n        visitor.visit(tree)\n        return list(visitor.keys) if visitor.keys else None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html"}
{"id": "b766d60527a8-3", "text": "visitor.visit(tree)\n        return list(visitor.keys) if visitor.keys else None\n    except (SyntaxError, TypeError, OSError):\n        return None\n[docs]def get_lambda_source(func: Callable) -> Optional[str]:\n    \"\"\"Get the source code of a lambda function.\n    Args:\n        func: a callable that can be a lambda function\n    Returns:\n        str: the source code of the lambda function\n    \"\"\"\n    try:\n        code = inspect.getsource(func)\n        tree = ast.parse(textwrap.dedent(code))\n        visitor = GetLambdaSource()\n        visitor.visit(tree)\n        return visitor.source if visitor.count == 1 else None\n    except (SyntaxError, TypeError, OSError):\n        return None\n[docs]def indent_lines_after_first(text: str, prefix: str) -> str:\n    \"\"\"Indent all lines of text after the first line.\n    Args:\n        text:  The text to indent\n        prefix: Used to determine the number of spaces to indent\n    Returns:\n        str: The indented text\n    \"\"\"\n    n_spaces = len(prefix)\n    spaces = \" \" * n_spaces\n    lines = text.splitlines()\n    return \"\\n\".join([lines[0]] + [spaces + line for line in lines[1:]])\n[docs]class AddableDict(Dict[str, Any]):\n    \"\"\"\n    Dictionary that can be added to another dictionary.\n    \"\"\"\n    def __add__(self, other: AddableDict) -> AddableDict:\n        chunk = AddableDict(self)\n        for key in other:\n            if key not in chunk or chunk[key] is None:\n                chunk[key] = other[key]\n            elif other[key] is not None:\n                try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html"}
{"id": "b766d60527a8-4", "text": "elif other[key] is not None:\n                try:\n                    added = chunk[key] + other[key]\n                except TypeError:\n                    added = other[key]\n                chunk[key] = added\n        return chunk\n    def __radd__(self, other: AddableDict) -> AddableDict:\n        chunk = AddableDict(other)\n        for key in self:\n            if key not in chunk or chunk[key] is None:\n                chunk[key] = self[key]\n            elif self[key] is not None:\n                try:\n                    added = chunk[key] + self[key]\n                except TypeError:\n                    added = self[key]\n                chunk[key] = added\n        return chunk\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_T_contra = TypeVar(\"_T_contra\", contravariant=True)\n[docs]class SupportsAdd(Protocol[_T_contra, _T_co]):\n    \"\"\"Protocol for objects that support addition.\"\"\"\n    def __add__(self, __x: _T_contra) -> _T_co:\n        ...\nAddable = TypeVar(\"Addable\", bound=SupportsAdd[Any, Any])\n[docs]def add(addables: Iterable[Addable]) -> Optional[Addable]:\n    \"\"\"Add a sequence of addable objects together.\"\"\"\n    final = None\n    for chunk in addables:\n        if final is None:\n            final = chunk\n        else:\n            final = final + chunk\n    return final\n[docs]async def aadd(addables: AsyncIterable[Addable]) -> Optional[Addable]:\n    \"\"\"Asynchronously add a sequence of addable objects together.\"\"\"\n    final = None\n    async for chunk in addables:\n        if final is None:\n            final = chunk\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html"}
{"id": "b766d60527a8-5", "text": "if final is None:\n            final = chunk\n        else:\n            final = final + chunk\n    return final\n[docs]class ConfigurableField(NamedTuple):\n    \"\"\"A field that can be configured by the user.\"\"\"\n    id: str\n    name: Optional[str] = None\n    description: Optional[str] = None\n    annotation: Optional[Any] = None\n    def __hash__(self) -> int:\n        return hash((self.id, self.annotation))\n[docs]class ConfigurableFieldSingleOption(NamedTuple):\n    \"\"\"A field that can be configured by the user with a default value.\"\"\"\n    id: str\n    options: Mapping[str, Any]\n    default: str\n    name: Optional[str] = None\n    description: Optional[str] = None\n    def __hash__(self) -> int:\n        return hash((self.id, tuple(self.options.keys()), self.default))\n[docs]class ConfigurableFieldMultiOption(NamedTuple):\n    \"\"\"A field that can be configured by the user with multiple default values.\"\"\"\n    id: str\n    options: Mapping[str, Any]\n    default: Sequence[str]\n    name: Optional[str] = None\n    description: Optional[str] = None\n    def __hash__(self) -> int:\n        return hash((self.id, tuple(self.options.keys()), tuple(self.default)))\nAnyConfigurableField = Union[\n    ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption\n]\n[docs]class ConfigurableFieldSpec(NamedTuple):\n    \"\"\"A field that can be configured by the user. It is a specification of a field.\"\"\"\n    id: str\n    name: Optional[str]\n    description: Optional[str]\n    default: Any\n    annotation: Any\n[docs]def get_unique_config_specs(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html"}
{"id": "b766d60527a8-6", "text": "default: Any\n    annotation: Any\n[docs]def get_unique_config_specs(\n    specs: Iterable[ConfigurableFieldSpec],\n) -> List[ConfigurableFieldSpec]:\n    \"\"\"Get the unique config specs from a sequence of config specs.\"\"\"\n    grouped = groupby(sorted(specs, key=lambda s: s.id), lambda s: s.id)\n    unique: List[ConfigurableFieldSpec] = []\n    for id, dupes in grouped:\n        first = next(dupes)\n        others = list(dupes)\n        if len(others) == 0:\n            unique.append(first)\n        elif all(o == first for o in others):\n            unique.append(first)\n        else:\n            raise ValueError(\n                \"RunnableSequence contains conflicting config specs\"\n                f\"for {id}: {[first] + others}\"\n            )\n    return unique", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html"}
{"id": "63a357835cb9-0", "text": "Source code for langchain.schema.runnable.config\nfrom __future__ import annotations\nfrom concurrent.futures import Executor, ThreadPoolExecutor\nfrom contextlib import contextmanager\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Awaitable,\n    Callable,\n    Dict,\n    Generator,\n    List,\n    Optional,\n    Union,\n    cast,\n)\nfrom typing_extensions import TypedDict\nfrom langchain.schema.runnable.utils import (\n    Input,\n    Output,\n    accepts_config,\n    accepts_run_manager,\n)\nif TYPE_CHECKING:\n    from langchain.callbacks.base import BaseCallbackManager, Callbacks\n    from langchain.callbacks.manager import (\n        AsyncCallbackManager,\n        AsyncCallbackManagerForChainRun,\n        CallbackManager,\n        CallbackManagerForChainRun,\n    )\nelse:\n    # Pydantic validates through typed dicts, but\n    # the callbacks need forward refs updated\n    Callbacks = Optional[Union[List, Any]]\n[docs]class EmptyDict(TypedDict, total=False):\n    \"\"\"Empty dict type.\"\"\"\n    pass\n[docs]class RunnableConfig(TypedDict, total=False):\n    \"\"\"Configuration for a Runnable.\"\"\"\n    tags: List[str]\n    \"\"\"\n    Tags for this call and any sub-calls (eg. a Chain calling an LLM).\n    You can use these to filter calls.\n    \"\"\"\n    metadata: Dict[str, Any]\n    \"\"\"\n    Metadata for this call and any sub-calls (eg. a Chain calling an LLM).\n    Keys should be strings, values should be JSON-serializable.\n    \"\"\"\n    callbacks: Callbacks\n    \"\"\"\n    Callbacks for this call and any sub-calls (eg. a Chain calling an LLM).", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html"}
{"id": "63a357835cb9-1", "text": "Tags are passed to all callbacks, metadata is passed to handle*Start callbacks.\n    \"\"\"\n    run_name: str\n    \"\"\"\n    Name for the tracer run for this call. Defaults to the name of the class.\n    \"\"\"\n    max_concurrency: Optional[int]\n    \"\"\"\n    Maximum number of parallel calls to make. If not provided, defaults to \n    ThreadPoolExecutor's default.\n    \"\"\"\n    recursion_limit: int\n    \"\"\"\n    Maximum number of times a call can recurse. If not provided, defaults to 25.\n    \"\"\"\n    configurable: Dict[str, Any]\n    \"\"\"\n    Runtime values for attributes previously made configurable on this Runnable,\n    or sub-Runnables, through .configurable_fields() or .configurable_alternatives().\n    Check .output_schema() for a description of the attributes that have been made \n    configurable.\n    \"\"\"\n[docs]def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:\n    \"\"\"Ensure that a config is a dict with all keys present.\n    Args:\n        config (Optional[RunnableConfig], optional): The config to ensure.\n          Defaults to None.\n    Returns:\n        RunnableConfig: The ensured config.\n    \"\"\"\n    empty = RunnableConfig(\n        tags=[],\n        metadata={},\n        callbacks=None,\n        recursion_limit=25,\n    )\n    if config is not None:\n        empty.update(\n            cast(RunnableConfig, {k: v for k, v in config.items() if v is not None})\n        )\n    return empty\n[docs]def get_config_list(\n    config: Optional[Union[RunnableConfig, List[RunnableConfig]]], length: int\n) -> List[RunnableConfig]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html"}
{"id": "63a357835cb9-2", "text": ") -> List[RunnableConfig]:\n    \"\"\"Get a list of configs from a single config or a list of configs.\n     It is useful for subclasses overriding batch() or abatch().\n    Args:\n        config (Optional[Union[RunnableConfig, List[RunnableConfig]]]):\n          The config or list of configs.\n        length (int): The length of the list.\n    Returns:\n        List[RunnableConfig]: The list of configs.\n    Raises:\n        ValueError: If the length of the list is not equal to the length of the inputs.\n    \"\"\"\n    if length < 0:\n        raise ValueError(f\"length must be >= 0, but got {length}\")\n    if isinstance(config, list) and len(config) != length:\n        raise ValueError(\n            f\"config must be a list of the same length as inputs, \"\n            f\"but got {len(config)} configs for {length} inputs\"\n        )\n    return (\n        list(map(ensure_config, config))\n        if isinstance(config, list)\n        else [ensure_config(config) for _ in range(length)]\n    )\n[docs]def patch_config(\n    config: Optional[RunnableConfig],\n    *,\n    callbacks: Optional[BaseCallbackManager] = None,\n    recursion_limit: Optional[int] = None,\n    max_concurrency: Optional[int] = None,\n    run_name: Optional[str] = None,\n    configurable: Optional[Dict[str, Any]] = None,\n) -> RunnableConfig:\n    \"\"\"Patch a config with new values.\n    Args:\n        config (Optional[RunnableConfig]): The config to patch.\n        copy_locals (bool, optional): Whether to copy locals. Defaults to False.\n        callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html"}
{"id": "63a357835cb9-3", "text": "callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.\n          Defaults to None.\n        recursion_limit (Optional[int], optional): The recursion limit to set.\n          Defaults to None.\n        max_concurrency (Optional[int], optional): The max concurrency to set.\n          Defaults to None.\n        run_name (Optional[str], optional): The run name to set. Defaults to None.\n        configurable (Optional[Dict[str, Any]], optional): The configurable to set.\n          Defaults to None.\n    Returns:\n        RunnableConfig: The patched config.\n    \"\"\"\n    config = ensure_config(config)\n    if callbacks is not None:\n        # If we're replacing callbacks, we need to unset run_name\n        # As that should apply only to the same run as the original callbacks\n        config[\"callbacks\"] = callbacks\n        if \"run_name\" in config:\n            del config[\"run_name\"]\n    if recursion_limit is not None:\n        config[\"recursion_limit\"] = recursion_limit\n    if max_concurrency is not None:\n        config[\"max_concurrency\"] = max_concurrency\n    if run_name is not None:\n        config[\"run_name\"] = run_name\n    if configurable is not None:\n        config[\"configurable\"] = {**config.get(\"configurable\", {}), **configurable}\n    return config\n[docs]def merge_configs(*configs: Optional[RunnableConfig]) -> RunnableConfig:\n    \"\"\"Merge multiple configs into one.\n    Args:\n        *configs (Optional[RunnableConfig]): The configs to merge.\n    Returns:\n        RunnableConfig: The merged config.\n    \"\"\"\n    base: RunnableConfig = {}\n    # Even though the keys aren't literals, this is correct\n    # because both dicts are the same type", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html"}
{"id": "63a357835cb9-4", "text": "# because both dicts are the same type\n    for config in (c for c in configs if c is not None):\n        for key in config:\n            if key == \"metadata\":\n                base[key] = {  # type: ignore\n                    **base.get(key, {}),  # type: ignore\n                    **(config.get(key) or {}),  # type: ignore\n                }\n            elif key == \"tags\":\n                base[key] = list(  # type: ignore\n                    set(base.get(key, []) + (config.get(key) or [])),  # type: ignore\n                )\n            elif key == \"configurable\":\n                base[key] = {  # type: ignore\n                    **base.get(key, {}),  # type: ignore\n                    **(config.get(key) or {}),  # type: ignore\n                }\n            elif key == \"callbacks\":\n                base_callbacks = base.get(\"callbacks\")\n                these_callbacks = config[\"callbacks\"]\n                # callbacks can be either None, list[handler] or manager\n                # so merging two callbacks values has 6 cases\n                if isinstance(these_callbacks, list):\n                    if base_callbacks is None:\n                        base[\"callbacks\"] = these_callbacks\n                    elif isinstance(base_callbacks, list):\n                        base[\"callbacks\"] = base_callbacks + these_callbacks\n                    else:\n                        # base_callbacks is a manager\n                        mngr = base_callbacks.copy()\n                        for callback in these_callbacks:\n                            mngr.add_handler(callback, inherit=True)\n                        base[\"callbacks\"] = mngr\n                elif these_callbacks is not None:\n                    # these_callbacks is a manager\n                    if base_callbacks is None:\n                        base[\"callbacks\"] = these_callbacks\n                    elif isinstance(base_callbacks, list):\n                        mngr = these_callbacks.copy()\n                        for callback in base_callbacks:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html"}
{"id": "63a357835cb9-5", "text": "mngr = these_callbacks.copy()\n                        for callback in base_callbacks:\n                            mngr.add_handler(callback, inherit=True)\n                        base[\"callbacks\"] = mngr\n                    else:\n                        # base_callbacks is also a manager\n                        base[\"callbacks\"] = base_callbacks.__class__(\n                            parent_run_id=base_callbacks.parent_run_id\n                            or these_callbacks.parent_run_id,\n                            handlers=base_callbacks.handlers + these_callbacks.handlers,\n                            inheritable_handlers=base_callbacks.inheritable_handlers\n                            + these_callbacks.inheritable_handlers,\n                            tags=list(set(base_callbacks.tags + these_callbacks.tags)),\n                            inheritable_tags=list(\n                                set(\n                                    base_callbacks.inheritable_tags\n                                    + these_callbacks.inheritable_tags\n                                )\n                            ),\n                            metadata={\n                                **base_callbacks.metadata,\n                                **these_callbacks.metadata,\n                            },\n                        )\n            else:\n                base[key] = config[key] or base.get(key)  # type: ignore\n    return base\n[docs]def call_func_with_variable_args(\n    func: Union[\n        Callable[[Input], Output],\n        Callable[[Input, RunnableConfig], Output],\n        Callable[[Input, CallbackManagerForChainRun], Output],\n        Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output],\n    ],\n    input: Input,\n    config: RunnableConfig,\n    run_manager: Optional[CallbackManagerForChainRun] = None,\n    **kwargs: Any,\n) -> Output:\n    \"\"\"Call function that may optionally accept a run_manager and/or config.\n    Args:\n        func (Union[Callable[[Input], Output],\n          Callable[[Input, CallbackManagerForChainRun], Output],\n          Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]]):\n           The function to call.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html"}
{"id": "63a357835cb9-6", "text": "The function to call.\n        input (Input): The input to the function.\n        run_manager (CallbackManagerForChainRun): The run manager to\n          pass to the function.\n        config (RunnableConfig): The config to pass to the function.\n        **kwargs (Any): The keyword arguments to pass to the function.\n    Returns:\n        Output: The output of the function.\n    \"\"\"\n    if accepts_config(func):\n        if run_manager is not None:\n            kwargs[\"config\"] = patch_config(config, callbacks=run_manager.get_child())\n        else:\n            kwargs[\"config\"] = config\n    if run_manager is not None and accepts_run_manager(func):\n        kwargs[\"run_manager\"] = run_manager\n    return func(input, **kwargs)  # type: ignore[call-arg]\n[docs]async def acall_func_with_variable_args(\n    func: Union[\n        Callable[[Input], Awaitable[Output]],\n        Callable[[Input, RunnableConfig], Awaitable[Output]],\n        Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]],\n        Callable[\n            [Input, AsyncCallbackManagerForChainRun, RunnableConfig],\n            Awaitable[Output],\n        ],\n    ],\n    input: Input,\n    config: RunnableConfig,\n    run_manager: Optional[AsyncCallbackManagerForChainRun] = None,\n    **kwargs: Any,\n) -> Output:\n    \"\"\"Call function that may optionally accept a run_manager and/or config.\n    Args:\n        func (Union[Callable[[Input], Awaitable[Output]], Callable[[Input,\n            AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,\n            AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):\n            The function to call.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html"}
{"id": "63a357835cb9-7", "text": "The function to call.\n        input (Input): The input to the function.\n        run_manager (AsyncCallbackManagerForChainRun): The run manager\n          to pass to the function.\n        config (RunnableConfig): The config to pass to the function.\n        **kwargs (Any): The keyword arguments to pass to the function.\n    Returns:\n        Output: The output of the function.\n    \"\"\"\n    if accepts_config(func):\n        if run_manager is not None:\n            kwargs[\"config\"] = patch_config(config, callbacks=run_manager.get_child())\n        else:\n            kwargs[\"config\"] = config\n    if run_manager is not None and accepts_run_manager(func):\n        kwargs[\"run_manager\"] = run_manager\n    return await func(input, **kwargs)  # type: ignore[call-arg]\n[docs]def get_callback_manager_for_config(config: RunnableConfig) -> CallbackManager:\n    \"\"\"Get a callback manager for a config.\n    Args:\n        config (RunnableConfig): The config.\n    Returns:\n        CallbackManager: The callback manager.\n    \"\"\"\n    from langchain.callbacks.manager import CallbackManager\n    return CallbackManager.configure(\n        inheritable_callbacks=config.get(\"callbacks\"),\n        inheritable_tags=config.get(\"tags\"),\n        inheritable_metadata=config.get(\"metadata\"),\n    )\n[docs]def get_async_callback_manager_for_config(\n    config: RunnableConfig,\n) -> AsyncCallbackManager:\n    \"\"\"Get an async callback manager for a config.\n    Args:\n        config (RunnableConfig): The config.\n    Returns:\n        AsyncCallbackManager: The async callback manager.\n    \"\"\"\n    from langchain.callbacks.manager import AsyncCallbackManager\n    return AsyncCallbackManager.configure(\n        inheritable_callbacks=config.get(\"callbacks\"),\n        inheritable_tags=config.get(\"tags\"),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html"}
{"id": "63a357835cb9-8", "text": "inheritable_callbacks=config.get(\"callbacks\"),\n        inheritable_tags=config.get(\"tags\"),\n        inheritable_metadata=config.get(\"metadata\"),\n    )\n[docs]@contextmanager\ndef get_executor_for_config(config: RunnableConfig) -> Generator[Executor, None, None]:\n    \"\"\"Get an executor for a config.\n    Args:\n        config (RunnableConfig): The config.\n    Yields:\n        Generator[Executor, None, None]: The executor.\n    \"\"\"\n    with ThreadPoolExecutor(max_workers=config.get(\"max_concurrency\")) as executor:\n        yield executor", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html"}
{"id": "c31c0a27d954-0", "text": "Source code for langchain.schema.runnable.history\nfrom __future__ import annotations\nimport asyncio\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    List,\n    Optional,\n    Sequence,\n    Type,\n    Union,\n)\nfrom langchain.load import load\nfrom langchain.pydantic_v1 import BaseModel, create_model\nfrom langchain.schema.chat_history import BaseChatMessageHistory\nfrom langchain.schema.runnable.base import Runnable, RunnableBindingBase, RunnableLambda\nfrom langchain.schema.runnable.passthrough import RunnablePassthrough\nfrom langchain.schema.runnable.utils import (\n    ConfigurableFieldSpec,\n    get_unique_config_specs,\n)\nif TYPE_CHECKING:\n    from langchain.callbacks.tracers.schemas import Run\n    from langchain.schema.messages import BaseMessage\n    from langchain.schema.runnable.config import RunnableConfig\nMessagesOrDictWithMessages = Union[Sequence[\"BaseMessage\"], Dict[str, Any]]\nGetSessionHistoryCallable = Callable[..., BaseChatMessageHistory]\n[docs]class RunnableWithMessageHistory(RunnableBindingBase):\n    \"\"\"A runnable that manages chat message history for another runnable.\n    Base runnable must have inputs and outputs that can be converted to a list of\n        BaseMessages.\n    RunnableWithMessageHistory must always be called with a config that contains session_id, e.g.:\n        ``{\"configurable\": {\"session_id\": \"<SESSION_ID>\"}}``\n    Example (dict input):\n        .. code-block:: python\n            from typing import Optional\n            from langchain.chat_models import ChatAnthropic\n            from langchain.memory.chat_message_histories import RedisChatMessageHistory\n            from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder\n            from langchain.schema.runnable.history import RunnableWithMessageHistory\n            prompt = ChatPromptTemplate.from_messages([", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html"}
{"id": "c31c0a27d954-1", "text": "prompt = ChatPromptTemplate.from_messages([\n                (\"system\", \"You're an assistant who's good at {ability}\"),\n                MessagesPlaceholder(variable_name=\"history\"),\n                (\"human\", \"{question}\"),\n            ])\n            chain = prompt | ChatAnthropic(model=\"claude-2\")\n            chain_with_history = RunnableWithMessageHistory(\n                chain,\n                RedisChatMessageHistory,\n                input_messages_key=\"question\",\n                history_messages_key=\"history\",\n            )\n            chain_with_history.invoke(\n                {\"ability\": \"math\", \"question\": \"What does cosine mean?\"},\n                config={\"configurable\": {\"session_id\": \"foo\"}}\n            )\n            # -> \"Cosine is ...\"\n            chain_with_history.invoke(\n                {\"ability\": \"math\", \"question\": \"What's its inverse\"},\n                config={\"configurable\": {\"session_id\": \"foo\"}}\n            )\n            # -> \"The inverse of cosine is called arccosine ...\"\n    \"\"\"  # noqa: E501\n    get_session_history: GetSessionHistoryCallable\n    input_messages_key: Optional[str] = None\n    output_messages_key: Optional[str] = None\n    history_messages_key: Optional[str] = None\n    def __init__(\n        self,\n        runnable: Runnable[\n            MessagesOrDictWithMessages,\n            Union[str, BaseMessage, MessagesOrDictWithMessages],\n        ],\n        get_session_history: GetSessionHistoryCallable,\n        *,\n        input_messages_key: Optional[str] = None,\n        output_messages_key: Optional[str] = None,\n        history_messages_key: Optional[str] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Initialize RunnableWithMessageHistory.\n        Args:\n            runnable: The base Runnable to be wrapped.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html"}
{"id": "c31c0a27d954-2", "text": "Args:\n            runnable: The base Runnable to be wrapped.\n                Must take as input one of:\n                - A sequence of BaseMessages\n                - A dict with one key for all messages\n                - A dict with one key for the current input string/message(s) and\n                    a separate key for historical messages. If the input key points\n                    to a string, it will be treated as a HumanMessage in history.\n                Must return as output one of:\n                - A string which can be treated as an AIMessage\n                - A BaseMessage or sequence of BaseMessages\n                - A dict with a key for a BaseMessage or sequence of BaseMessages\n            get_session_history: Function that returns a new BaseChatMessageHistory\n                given a session id. Should take a single\n                positional argument `session_id` which is a string and a named argument\n                `user_id` which can be a string or None. e.g.:\n                ```python\n                def get_session_history(\n                    session_id: str,\n                    *,\n                    user_id: Optional[str]=None\n                ) -> BaseChatMessageHistory:\n                  ...\n                ```\n            input_messages_key: Must be specified if the base runnable accepts a dict\n                as input.\n            output_messages_key: Must be specified if the base runnable returns a dict\n                as output.\n            history_messages_key: Must be specified if the base runnable accepts a dict\n                as input and expects a separate key for historical messages.\n            **kwargs: Arbitrary additional kwargs to pass to parent class\n                ``RunnableBindingBase`` init.\n        \"\"\"  # noqa: E501\n        history_chain: Runnable = RunnableLambda(\n            self._enter_history, self._aenter_history\n        ).with_config(run_name=\"load_history\")\n        messages_key = history_messages_key or input_messages_key\n        if messages_key:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html"}
{"id": "c31c0a27d954-3", "text": "messages_key = history_messages_key or input_messages_key\n        if messages_key:\n            history_chain = RunnablePassthrough.assign(\n                **{messages_key: history_chain}\n            ).with_config(run_name=\"insert_history\")\n        bound = (\n            history_chain | runnable.with_listeners(on_end=self._exit_history)\n        ).with_config(run_name=\"RunnableWithMessageHistory\")\n        super().__init__(\n            get_session_history=get_session_history,\n            input_messages_key=input_messages_key,\n            output_messages_key=output_messages_key,\n            bound=bound,\n            history_messages_key=history_messages_key,\n            **kwargs,\n        )\n    @property\n    def config_specs(self) -> List[ConfigurableFieldSpec]:\n        return get_unique_config_specs(\n            super().config_specs\n            + [\n                ConfigurableFieldSpec(\n                    id=\"session_id\",\n                    annotation=str,\n                    name=\"Session ID\",\n                    description=\"Unique identifier for a session.\",\n                    default=\"\",\n                ),\n            ]\n        )\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        super_schema = super().get_input_schema(config)\n        if super_schema.__custom_root_type__ is not None:\n            from langchain.schema.messages import BaseMessage\n            fields: Dict = {}\n            if self.input_messages_key and self.history_messages_key:\n                fields[self.input_messages_key] = (\n                    Union[str, BaseMessage, Sequence[BaseMessage]],\n                    ...,\n                )\n            elif self.input_messages_key:\n                fields[self.input_messages_key] = (Sequence[BaseMessage], ...)\n            else:\n                fields[\"__root__\"] = (Sequence[BaseMessage], ...)\n            if self.history_messages_key:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html"}
{"id": "c31c0a27d954-4", "text": "if self.history_messages_key:\n                fields[self.history_messages_key] = (Sequence[BaseMessage], ...)\n            return create_model(  # type: ignore[call-overload]\n                \"RunnableWithChatHistoryInput\",\n                **fields,\n            )\n        else:\n            return super_schema\n    def _get_input_messages(\n        self, input_val: Union[str, BaseMessage, Sequence[BaseMessage]]\n    ) -> List[BaseMessage]:\n        from langchain.schema.messages import BaseMessage\n        if isinstance(input_val, str):\n            from langchain.schema.messages import HumanMessage\n            return [HumanMessage(content=input_val)]\n        elif isinstance(input_val, BaseMessage):\n            return [input_val]\n        elif isinstance(input_val, (list, tuple)):\n            return list(input_val)\n        else:\n            raise ValueError(\n                f\"Expected str, BaseMessage, List[BaseMessage], or Tuple[BaseMessage]. \"\n                f\"Got {input_val}.\"\n            )\n    def _get_output_messages(\n        self, output_val: Union[str, BaseMessage, Sequence[BaseMessage], dict]\n    ) -> List[BaseMessage]:\n        from langchain.schema.messages import BaseMessage\n        if isinstance(output_val, dict):\n            output_val = output_val[self.output_messages_key or \"output\"]\n        if isinstance(output_val, str):\n            from langchain.schema.messages import AIMessage\n            return [AIMessage(content=output_val)]\n        elif isinstance(output_val, BaseMessage):\n            return [output_val]\n        elif isinstance(output_val, (list, tuple)):\n            return list(output_val)\n        else:\n            raise ValueError()\n    def _enter_history(self, input: Any, config: RunnableConfig) -> List[BaseMessage]:\n        hist = config[\"configurable\"][\"message_history\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html"}
{"id": "c31c0a27d954-5", "text": "hist = config[\"configurable\"][\"message_history\"]\n        # return only historic messages\n        if self.history_messages_key:\n            return hist.messages.copy()\n        # return all messages\n        else:\n            input_val = (\n                input if not self.input_messages_key else input[self.input_messages_key]\n            )\n            return hist.messages.copy() + self._get_input_messages(input_val)\n    async def _aenter_history(\n        self, input: Dict[str, Any], config: RunnableConfig\n    ) -> List[BaseMessage]:\n        return await asyncio.get_running_loop().run_in_executor(\n            None, self._enter_history, input, config\n        )\n    def _exit_history(self, run: Run, config: RunnableConfig) -> None:\n        hist = config[\"configurable\"][\"message_history\"]\n        # Get the input messages\n        inputs = load(run.inputs)\n        input_val = inputs[self.input_messages_key or \"input\"]\n        input_messages = self._get_input_messages(input_val)\n        # Get the output messages\n        output_val = load(run.outputs)\n        output_messages = self._get_output_messages(output_val)\n        for m in input_messages + output_messages:\n            hist.add_message(m)\n    def _merge_configs(self, *configs: Optional[RunnableConfig]) -> RunnableConfig:\n        config = super()._merge_configs(*configs)\n        # extract session_id\n        if \"session_id\" not in config.get(\"configurable\", {}):\n            example_input = {self.input_messages_key: \"foo\"}\n            example_config = {\"configurable\": {\"session_id\": \"123\"}}\n            raise ValueError(\n                \"session_id_id is required.\"\n                \" Pass it in as part of the config argument to .invoke() or .stream()\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html"}
{"id": "c31c0a27d954-6", "text": "\" Pass it in as part of the config argument to .invoke() or .stream()\"\n                f\"\\neg. chain.invoke({example_input}, {example_config})\"\n            )\n        # attach message_history\n        session_id = config[\"configurable\"][\"session_id\"]\n        config[\"configurable\"][\"message_history\"] = self.get_session_history(session_id)\n        return config", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html"}
{"id": "879e07ce5e54-0", "text": "Source code for langchain.schema.runnable.branch\nfrom typing import (\n    Any,\n    Awaitable,\n    Callable,\n    List,\n    Mapping,\n    Optional,\n    Sequence,\n    Tuple,\n    Type,\n    Union,\n    cast,\n)\nfrom langchain.load.dump import dumpd\nfrom langchain.pydantic_v1 import BaseModel\nfrom langchain.schema.runnable.base import (\n    Runnable,\n    RunnableLike,\n    RunnableSerializable,\n    coerce_to_runnable,\n)\nfrom langchain.schema.runnable.config import (\n    RunnableConfig,\n    ensure_config,\n    get_callback_manager_for_config,\n    patch_config,\n)\nfrom langchain.schema.runnable.utils import (\n    ConfigurableFieldSpec,\n    Input,\n    Output,\n    get_unique_config_specs,\n)\n[docs]class RunnableBranch(RunnableSerializable[Input, Output]):\n    \"\"\"A Runnable that selects which branch to run based on a condition.\n    The runnable is initialized with a list of (condition, runnable) pairs and\n    a default branch.\n    When operating on an input, the first condition that evaluates to True is\n    selected, and the corresponding runnable is run on the input.\n    If no condition evaluates to True, the default branch is run on the input.\n    Examples:\n        .. code-block:: python\n            from langchain.schema.runnable import RunnableBranch\n            branch = RunnableBranch(\n                (lambda x: isinstance(x, str), lambda x: x.upper()),\n                (lambda x: isinstance(x, int), lambda x: x + 1),\n                (lambda x: isinstance(x, float), lambda x: x * 2),\n                lambda x: \"goodbye\",\n            )\n            branch.invoke(\"hello\") # \"HELLO\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/branch.html"}
{"id": "879e07ce5e54-1", "text": ")\n            branch.invoke(\"hello\") # \"HELLO\"\n            branch.invoke(None) # \"goodbye\"\n    \"\"\"\n    branches: Sequence[Tuple[Runnable[Input, bool], Runnable[Input, Output]]]\n    default: Runnable[Input, Output]\n    def __init__(\n        self,\n        *branches: Union[\n            Tuple[\n                Union[\n                    Runnable[Input, bool],\n                    Callable[[Input], bool],\n                    Callable[[Input], Awaitable[bool]],\n                ],\n                RunnableLike,\n            ],\n            RunnableLike,  # To accommodate the default branch\n        ],\n    ) -> None:\n        \"\"\"A Runnable that runs one of two branches based on a condition.\"\"\"\n        if len(branches) < 2:\n            raise ValueError(\"RunnableBranch requires at least two branches\")\n        default = branches[-1]\n        if not isinstance(\n            default,\n            (Runnable, Callable, Mapping),  # type: ignore[arg-type]\n        ):\n            raise TypeError(\n                \"RunnableBranch default must be runnable, callable or mapping.\"\n            )\n        default_ = cast(\n            Runnable[Input, Output], coerce_to_runnable(cast(RunnableLike, default))\n        )\n        _branches = []\n        for branch in branches[:-1]:\n            if not isinstance(branch, (tuple, list)):  # type: ignore[arg-type]\n                raise TypeError(\n                    f\"RunnableBranch branches must be \"\n                    f\"tuples or lists, not {type(branch)}\"\n                )\n            if not len(branch) == 2:\n                raise ValueError(\n                    f\"RunnableBranch branches must be \"\n                    f\"tuples or lists of length 2, not {len(branch)}\"\n                )\n            condition, runnable = branch", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/branch.html"}
{"id": "879e07ce5e54-2", "text": ")\n            condition, runnable = branch\n            condition = cast(Runnable[Input, bool], coerce_to_runnable(condition))\n            runnable = coerce_to_runnable(runnable)\n            _branches.append((condition, runnable))\n        super().__init__(branches=_branches, default=default_)\n    class Config:\n        arbitrary_types_allowed = True\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"RunnableBranch is serializable if all its branches are serializable.\"\"\"\n        return True\n[docs]    @classmethod\n    def get_lc_namespace(cls) -> List[str]:\n        \"\"\"The namespace of a RunnableBranch is the namespace of its default branch.\"\"\"\n        return cls.__module__.split(\".\")[:-1]\n[docs]    def get_input_schema(\n        self, config: Optional[RunnableConfig] = None\n    ) -> Type[BaseModel]:\n        runnables = (\n            [self.default]\n            + [r for _, r in self.branches]\n            + [r for r, _ in self.branches]\n        )\n        for runnable in runnables:\n            if runnable.get_input_schema(config).schema().get(\"type\") is not None:\n                return runnable.get_input_schema(config)\n        return super().get_input_schema(config)\n    @property\n    def config_specs(self) -> List[ConfigurableFieldSpec]:\n        return get_unique_config_specs(\n            spec\n            for step in (\n                [self.default]\n                + [r for _, r in self.branches]\n                + [r for r, _ in self.branches]\n            )\n            for spec in step.config_specs\n        )\n[docs]    def invoke(\n        self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/branch.html"}
{"id": "879e07ce5e54-3", "text": ") -> Output:\n        \"\"\"First evaluates the condition, then delegate to true or false branch.\"\"\"\n        config = ensure_config(config)\n        callback_manager = get_callback_manager_for_config(config)\n        run_manager = callback_manager.on_chain_start(\n            dumpd(self),\n            input,\n            name=config.get(\"run_name\"),\n        )\n        try:\n            for idx, branch in enumerate(self.branches):\n                condition, runnable = branch\n                expression_value = condition.invoke(\n                    input,\n                    config=patch_config(\n                        config,\n                        callbacks=run_manager.get_child(tag=f\"condition:{idx + 1}\"),\n                    ),\n                )\n                if expression_value:\n                    output = runnable.invoke(\n                        input,\n                        config=patch_config(\n                            config,\n                            callbacks=run_manager.get_child(tag=f\"branch:{idx + 1}\"),\n                        ),\n                        **kwargs,\n                    )\n                    break\n            else:\n                output = self.default.invoke(\n                    input,\n                    config=patch_config(\n                        config, callbacks=run_manager.get_child(tag=\"branch:default\")\n                    ),\n                    **kwargs,\n                )\n        except Exception as e:\n            run_manager.on_chain_error(e)\n            raise\n        run_manager.on_chain_end(dumpd(output))\n        return output\n[docs]    async def ainvoke(\n        self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any\n    ) -> Output:\n        \"\"\"Async version of invoke.\"\"\"\n        config = ensure_config(config)\n        callback_manager = get_callback_manager_for_config(config)\n        run_manager = callback_manager.on_chain_start(\n            dumpd(self),\n            input,\n            name=config.get(\"run_name\"),\n        )\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/branch.html"}
{"id": "879e07ce5e54-4", "text": "input,\n            name=config.get(\"run_name\"),\n        )\n        try:\n            for idx, branch in enumerate(self.branches):\n                condition, runnable = branch\n                expression_value = await condition.ainvoke(\n                    input,\n                    config=patch_config(\n                        config,\n                        callbacks=run_manager.get_child(tag=f\"condition:{idx + 1}\"),\n                    ),\n                )\n                if expression_value:\n                    output = await runnable.ainvoke(\n                        input,\n                        config=patch_config(\n                            config,\n                            callbacks=run_manager.get_child(tag=f\"branch:{idx + 1}\"),\n                        ),\n                        **kwargs,\n                    )\n                    break\n            else:\n                output = await self.default.ainvoke(\n                    input,\n                    config=patch_config(\n                        config, callbacks=run_manager.get_child(tag=\"branch:default\")\n                    ),\n                    **kwargs,\n                )\n        except Exception as e:\n            run_manager.on_chain_error(e)\n            raise\n        run_manager.on_chain_end(dumpd(output))\n        return output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/branch.html"}
{"id": "df1ad08b95f6-0", "text": "Source code for langchain.graphs.rdf_graph\nfrom __future__ import annotations\nfrom typing import (\n    TYPE_CHECKING,\n    List,\n    Optional,\n)\nif TYPE_CHECKING:\n    import rdflib\nprefixes = {\n    \"owl\": \"\"\"PREFIX owl: <http://www.w3.org/2002/07/owl#>\\n\"\"\",\n    \"rdf\": \"\"\"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\\n\"\"\",\n    \"rdfs\": \"\"\"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\\n\"\"\",\n    \"xsd\": \"\"\"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\\n\"\"\",\n}\ncls_query_rdf = prefixes[\"rdfs\"] + (\n    \"\"\"SELECT DISTINCT ?cls ?com\\n\"\"\"\n    \"\"\"WHERE { \\n\"\"\"\n    \"\"\"    ?instance a ?cls . \\n\"\"\"\n    \"\"\"    OPTIONAL { ?cls rdfs:comment ?com } \\n\"\"\"\n    \"\"\"}\"\"\"\n)\ncls_query_rdfs = prefixes[\"rdfs\"] + (\n    \"\"\"SELECT DISTINCT ?cls ?com\\n\"\"\"\n    \"\"\"WHERE { \\n\"\"\"\n    \"\"\"    ?instance a/rdfs:subClassOf* ?cls . \\n\"\"\"\n    \"\"\"    OPTIONAL { ?cls rdfs:comment ?com } \\n\"\"\"\n    \"\"\"}\"\"\"\n)\ncls_query_owl = prefixes[\"rdfs\"] + (\n    \"\"\"SELECT DISTINCT ?cls ?com\\n\"\"\"\n    \"\"\"WHERE { \\n\"\"\"\n    \"\"\"    ?instance a/rdfs:subClassOf* ?cls . \\n\"\"\"\n    \"\"\"    FILTER (isIRI(?cls)) . \\n\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html"}
{"id": "df1ad08b95f6-1", "text": "\"\"\"    FILTER (isIRI(?cls)) . \\n\"\"\"\n    \"\"\"    OPTIONAL { ?cls rdfs:comment ?com } \\n\"\"\"\n    \"\"\"}\"\"\"\n)\nrel_query_rdf = prefixes[\"rdfs\"] + (\n    \"\"\"SELECT DISTINCT ?rel ?com\\n\"\"\"\n    \"\"\"WHERE { \\n\"\"\"\n    \"\"\"    ?subj ?rel ?obj . \\n\"\"\"\n    \"\"\"    OPTIONAL { ?rel rdfs:comment ?com } \\n\"\"\"\n    \"\"\"}\"\"\"\n)\nrel_query_rdfs = (\n    prefixes[\"rdf\"]\n    + prefixes[\"rdfs\"]\n    + (\n        \"\"\"SELECT DISTINCT ?rel ?com\\n\"\"\"\n        \"\"\"WHERE { \\n\"\"\"\n        \"\"\"    ?rel a/rdfs:subPropertyOf* rdf:Property . \\n\"\"\"\n        \"\"\"    OPTIONAL { ?rel rdfs:comment ?com } \\n\"\"\"\n        \"\"\"}\"\"\"\n    )\n)\nop_query_owl = (\n    prefixes[\"rdfs\"]\n    + prefixes[\"owl\"]\n    + (\n        \"\"\"SELECT DISTINCT ?op ?com\\n\"\"\"\n        \"\"\"WHERE { \\n\"\"\"\n        \"\"\"    ?op a/rdfs:subPropertyOf* owl:ObjectProperty . \\n\"\"\"\n        \"\"\"    OPTIONAL { ?op rdfs:comment ?com } \\n\"\"\"\n        \"\"\"}\"\"\"\n    )\n)\ndp_query_owl = (\n    prefixes[\"rdfs\"]\n    + prefixes[\"owl\"]\n    + (\n        \"\"\"SELECT DISTINCT ?dp ?com\\n\"\"\"\n        \"\"\"WHERE { \\n\"\"\"\n        \"\"\"    ?dp a/rdfs:subPropertyOf* owl:DatatypeProperty . \\n\"\"\"\n        \"\"\"    OPTIONAL { ?dp rdfs:comment ?com } \\n\"\"\"\n        \"\"\"}\"\"\"\n    )\n)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html"}
{"id": "df1ad08b95f6-2", "text": "\"\"\"}\"\"\"\n    )\n)\n[docs]class RdfGraph:\n    \"\"\"RDFlib wrapper for graph operations.\n    Modes:\n    * local: Local file - can be queried and changed\n    * online: Online file - can only be queried, changes can be stored locally\n    * store: Triple store - can be queried and changed if update_endpoint available\n    Together with a source file, the serialization should be specified.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        source_file: Optional[str] = None,\n        serialization: Optional[str] = \"ttl\",\n        query_endpoint: Optional[str] = None,\n        update_endpoint: Optional[str] = None,\n        standard: Optional[str] = \"rdf\",\n        local_copy: Optional[str] = None,\n    ) -> None:\n        \"\"\"\n        Set up the RDFlib graph\n        :param source_file: either a path for a local file or a URL\n        :param serialization: serialization of the input\n        :param query_endpoint: SPARQL endpoint for queries, read access\n        :param update_endpoint: SPARQL endpoint for UPDATE queries, write access\n        :param standard: RDF, RDFS, or OWL", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html"}
{"id": "df1ad08b95f6-3", "text": ":param standard: RDF, RDFS, or OWL\n        :param local_copy: new local copy for storing changes\n        \"\"\"\n        self.source_file = source_file\n        self.serialization = serialization\n        self.query_endpoint = query_endpoint\n        self.update_endpoint = update_endpoint\n        self.standard = standard\n        self.local_copy = local_copy\n        try:\n            import rdflib\n            from rdflib.graph import DATASET_DEFAULT_GRAPH_ID as default\n            from rdflib.plugins.stores import sparqlstore\n        except ImportError:\n            raise ValueError(\n                \"Could not import rdflib python package. \"\n                \"Please install it with `pip install rdflib`.\"\n            )\n        if self.standard not in (supported_standards := (\"rdf\", \"rdfs\", \"owl\")):\n            raise ValueError(\n                f\"Invalid standard. Supported standards are: {supported_standards}.\"\n            )\n        if (\n            not source_file\n            and not query_endpoint\n            or source_file\n            and (query_endpoint or update_endpoint)\n        ):\n            raise ValueError(\n                \"Could not unambiguously initialize the graph wrapper. \"\n                \"Specify either a file (local or online) via the source_file \"\n                \"or a triple store via the endpoints.\"\n            )\n        if source_file:\n            if source_file.startswith(\"http\"):\n                self.mode = \"online\"\n            else:\n                self.mode = \"local\"\n                if self.local_copy is None:\n                    self.local_copy = self.source_file\n            self.graph = rdflib.Graph()\n            self.graph.parse(source_file, format=self.serialization)\n        if query_endpoint:\n            self.mode = \"store\"\n            if not update_endpoint:\n                self._store = sparqlstore.SPARQLStore()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html"}
{"id": "df1ad08b95f6-4", "text": "self._store = sparqlstore.SPARQLStore()\n                self._store.open(query_endpoint)\n            else:\n                self._store = sparqlstore.SPARQLUpdateStore()\n                self._store.open((query_endpoint, update_endpoint))\n            self.graph = rdflib.Graph(self._store, identifier=default)\n        # Verify that the graph was loaded\n        if not len(self.graph):\n            raise AssertionError(\"The graph is empty.\")\n        # Set schema\n        self.schema = \"\"\n        self.load_schema()\n    @property\n    def get_schema(self) -> str:\n        \"\"\"\n        Returns the schema of the graph database.\n        \"\"\"\n        return self.schema\n[docs]    def query(\n        self,\n        query: str,\n    ) -> List[rdflib.query.ResultRow]:\n        \"\"\"\n        Query the graph.\n        \"\"\"\n        from rdflib.exceptions import ParserError\n        from rdflib.query import ResultRow\n        try:\n            res = self.graph.query(query)\n        except ParserError as e:\n            raise ValueError(\"Generated SPARQL statement is invalid\\n\" f\"{e}\")\n        return [r for r in res if isinstance(r, ResultRow)]\n[docs]    def update(\n        self,\n        query: str,\n    ) -> None:\n        \"\"\"\n        Update the graph.\n        \"\"\"\n        from rdflib.exceptions import ParserError\n        try:\n            self.graph.update(query)\n        except ParserError as e:\n            raise ValueError(\"Generated SPARQL statement is invalid\\n\" f\"{e}\")\n        if self.local_copy:\n            self.graph.serialize(\n                destination=self.local_copy, format=self.local_copy.split(\".\")[-1]\n            )\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html"}
{"id": "df1ad08b95f6-5", "text": ")\n        else:\n            raise ValueError(\"No target file specified for saving the updated file.\")\n    @staticmethod\n    def _get_local_name(iri: str) -> str:\n        if \"#\" in iri:\n            local_name = iri.split(\"#\")[-1]\n        elif \"/\" in iri:\n            local_name = iri.split(\"/\")[-1]\n        else:\n            raise ValueError(f\"Unexpected IRI '{iri}', contains neither '#' nor '/'.\")\n        return local_name\n    def _res_to_str(self, res: rdflib.query.ResultRow, var: str) -> str:\n        return (\n            \"<\"\n            + str(res[var])\n            + \"> (\"\n            + self._get_local_name(res[var])\n            + \", \"\n            + str(res[\"com\"])\n            + \")\"\n        )\n[docs]    def load_schema(self) -> None:\n        \"\"\"\n        Load the graph schema information.\n        \"\"\"\n        def _rdf_s_schema(\n            classes: List[rdflib.query.ResultRow],\n            relationships: List[rdflib.query.ResultRow],\n        ) -> str:\n            return (\n                f\"In the following, each IRI is followed by the local name and \"\n                f\"optionally its description in parentheses. \\n\"\n                f\"The RDF graph supports the following node types:\\n\"\n                f'{\", \".join([self._res_to_str(r, \"cls\") for r in classes])}\\n'\n                f\"The RDF graph supports the following relationships:\\n\"\n                f'{\", \".join([self._res_to_str(r, \"rel\") for r in relationships])}\\n'\n            )\n        if self.standard == \"rdf\":\n            clss = self.query(cls_query_rdf)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html"}
{"id": "df1ad08b95f6-6", "text": "clss = self.query(cls_query_rdf)\n            rels = self.query(rel_query_rdf)\n            self.schema = _rdf_s_schema(clss, rels)\n        elif self.standard == \"rdfs\":\n            clss = self.query(cls_query_rdfs)\n            rels = self.query(rel_query_rdfs)\n            self.schema = _rdf_s_schema(clss, rels)\n        elif self.standard == \"owl\":\n            clss = self.query(cls_query_owl)\n            ops = self.query(op_query_owl)\n            dps = self.query(dp_query_owl)\n            self.schema = (\n                f\"In the following, each IRI is followed by the local name and \"\n                f\"optionally its description in parentheses. \\n\"\n                f\"The OWL graph supports the following node types:\\n\"\n                f'{\", \".join([self._res_to_str(r, \"cls\") for r in clss])}\\n'\n                f\"The OWL graph supports the following object properties, \"\n                f\"i.e., relationships between objects:\\n\"\n                f'{\", \".join([self._res_to_str(r, \"op\") for r in ops])}\\n'\n                f\"The OWL graph supports the following data properties, \"\n                f\"i.e., relationships between objects and literals:\\n\"\n                f'{\", \".join([self._res_to_str(r, \"dp\") for r in dps])}\\n'\n            )\n        else:\n            raise ValueError(f\"Mode '{self.standard}' is currently not supported.\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html"}
{"id": "9a18d086743f-0", "text": "Source code for langchain.graphs.kuzu_graph\nfrom typing import Any, Dict, List\n[docs]class KuzuGraph:\n    \"\"\"K\u00f9zu wrapper for graph operations.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n[docs]    def __init__(self, db: Any, database: str = \"kuzu\") -> None:\n        try:\n            import kuzu\n        except ImportError:\n            raise ImportError(\n                \"Could not import K\u00f9zu python package.\"\n                \"Please install K\u00f9zu with `pip install kuzu`.\"\n            )\n        self.db = db\n        self.conn = kuzu.Connection(self.db)\n        self.database = database\n        self.refresh_schema()\n    @property\n    def get_schema(self) -> str:\n        \"\"\"Returns the schema of the K\u00f9zu database\"\"\"\n        return self.schema\n[docs]    def query(self, query: str, params: dict = {}) -> List[Dict[str, Any]]:\n        \"\"\"Query K\u00f9zu database\"\"\"\n        params_list = []\n        for param_name in params:\n            params_list.append([param_name, params[param_name]])\n        result = self.conn.execute(query, params_list)\n        column_names = result.get_column_names()\n        return_list = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/kuzu_graph.html"}
{"id": "9a18d086743f-1", "text": "column_names = result.get_column_names()\n        return_list = []\n        while result.has_next():\n            row = result.get_next()\n            return_list.append(dict(zip(column_names, row)))\n        return return_list\n[docs]    def refresh_schema(self) -> None:\n        \"\"\"Refreshes the K\u00f9zu graph schema information\"\"\"\n        node_properties = []\n        node_table_names = self.conn._get_node_table_names()\n        for table_name in node_table_names:\n            current_table_schema = {\"properties\": [], \"label\": table_name}\n            properties = self.conn._get_node_property_names(table_name)\n            for property_name in properties:\n                property_type = properties[property_name][\"type\"]\n                list_type_flag = \"\"\n                if properties[property_name][\"dimension\"] > 0:\n                    if \"shape\" in properties[property_name]:\n                        for s in properties[property_name][\"shape\"]:\n                            list_type_flag += \"[%s]\" % s\n                    else:\n                        for i in range(properties[property_name][\"dimension\"]):\n                            list_type_flag += \"[]\"\n                property_type += list_type_flag\n                current_table_schema[\"properties\"].append(\n                    (property_name, property_type)\n                )\n            node_properties.append(current_table_schema)\n        relationships = []\n        rel_tables = self.conn._get_rel_table_names()\n        for table in rel_tables:\n            relationships.append(\n                \"(:%s)-[:%s]->(:%s)\" % (table[\"src\"], table[\"name\"], table[\"dst\"])\n            )\n        rel_properties = []\n        for table in rel_tables:\n            current_table_schema = {\"properties\": [], \"label\": table[\"name\"]}\n            properties_text = self.conn._connection.get_rel_property_names(\n                table[\"name\"]\n            ).split(\"\\n\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/kuzu_graph.html"}
{"id": "9a18d086743f-2", "text": "table[\"name\"]\n            ).split(\"\\n\")\n            for i, line in enumerate(properties_text):\n                # The first 3 lines defines src, dst and name, so we skip them\n                if i < 3:\n                    continue\n                if not line:\n                    continue\n                property_name, property_type = line.strip().split(\" \")\n                current_table_schema[\"properties\"].append(\n                    (property_name, property_type)\n                )\n            rel_properties.append(current_table_schema)\n        self.schema = (\n            f\"Node properties: {node_properties}\\n\"\n            f\"Relationships properties: {rel_properties}\\n\"\n            f\"Relationships: {relationships}\\n\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/kuzu_graph.html"}
{"id": "a830323f4010-0", "text": "Source code for langchain.graphs.neptune_graph\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n[docs]class NeptuneQueryException(Exception):\n    \"\"\"A class to handle queries that fail to execute\"\"\"\n    def __init__(self, exception: Union[str, Dict]):\n        if isinstance(exception, dict):\n            self.message = exception[\"message\"] if \"message\" in exception else \"unknown\"\n            self.details = exception[\"details\"] if \"details\" in exception else \"unknown\"\n        else:\n            self.message = exception\n            self.details = \"unknown\"\n    def get_message(self) -> str:\n        return self.message\n    def get_details(self) -> Any:\n        return self.details\n[docs]class NeptuneGraph:\n    \"\"\"Neptune wrapper for graph operations.\n    Args:\n        host: endpoint for the database instance\n        port: port number for the database instance, default is 8182\n        use_https: whether to use secure connection, default is True\n        client: optional boto3 Neptune client\n        credentials_profile_name: optional AWS profile name\n        region_name: optional AWS region, e.g., us-west-2\n        service: optional service name, default is neptunedata\n        sign: optional, whether to sign the request payload, default is True\n    Example:\n        .. code-block:: python\n        graph = NeptuneGraph(\n            host='<my-cluster>',\n            port=8182\n        )\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html"}
{"id": "a830323f4010-1", "text": "data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        host: str,\n        port: int = 8182,\n        use_https: bool = True,\n        client: Any = None,\n        credentials_profile_name: Optional[str] = None,\n        region_name: Optional[str] = None,\n        service: str = \"neptunedata\",\n        sign: bool = True,\n    ) -> None:\n        \"\"\"Create a new Neptune graph wrapper instance.\"\"\"\n        try:\n            if client is not None:\n                self.client = client\n            else:\n                import boto3\n                if credentials_profile_name is not None:\n                    session = boto3.Session(profile_name=credentials_profile_name)\n                else:\n                    # use default credentials\n                    session = boto3.Session()\n                client_params = {}\n                if region_name:\n                    client_params[\"region_name\"] = region_name\n                protocol = \"https\" if use_https else \"http\"\n                client_params[\"endpoint_url\"] = f\"{protocol}://{host}:{port}\"\n                if sign:\n                    self.client = session.client(service, **client_params)\n                else:\n                    from botocore import UNSIGNED\n                    from botocore.config import Config\n                    self.client = session.client(\n                        service,\n                        **client_params,\n                        config=Config(signature_version=UNSIGNED),\n                    )\n        except ImportError:\n            raise ModuleNotFoundError(\n                \"Could not import boto3 python package. \"\n                \"Please install it with `pip install boto3`.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html"}
{"id": "a830323f4010-2", "text": "\"Please install it with `pip install boto3`.\"\n            )\n        except Exception as e:\n            if type(e).__name__ == \"UnknownServiceError\":\n                raise ModuleNotFoundError(\n                    \"NeptuneGraph requires a boto3 version 1.28.38 or greater.\"\n                    \"Please install it with `pip install -U boto3`.\"\n                ) from e\n            else:\n                raise ValueError(\n                    \"Could not load credentials to authenticate with AWS client. \"\n                    \"Please check that credentials in the specified \"\n                    \"profile name are valid.\"\n                ) from e\n        try:\n            self._refresh_schema()\n        except Exception as e:\n            raise NeptuneQueryException(\n                {\n                    \"message\": \"Could not get schema for Neptune database\",\n                    \"detail\": str(e),\n                }\n            )\n    @property\n    def get_schema(self) -> str:\n        \"\"\"Returns the schema of the Neptune database\"\"\"\n        return self.schema\n[docs]    def query(self, query: str, params: dict = {}) -> Dict[str, Any]:\n        \"\"\"Query Neptune database.\"\"\"\n        try:\n            return self.client.execute_open_cypher_query(openCypherQuery=query)\n        except Exception as e:\n            raise NeptuneQueryException(\n                {\n                    \"message\": \"An error occurred while executing the query.\",\n                    \"details\": str(e),\n                }\n            )\n    def _get_summary(self) -> Dict:\n        try:\n            response = self.client.get_propertygraph_summary()\n        except Exception as e:\n            raise NeptuneQueryException(\n                {\n                    \"message\": (\n                        \"Summary API is not available for this instance of Neptune,\"\n                        \"ensure the engine version is >=1.2.1.0\"\n                    ),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html"}
{"id": "a830323f4010-3", "text": "\"ensure the engine version is >=1.2.1.0\"\n                    ),\n                    \"details\": str(e),\n                }\n            )\n        try:\n            summary = response[\"payload\"][\"graphSummary\"]\n        except Exception:\n            raise NeptuneQueryException(\n                {\n                    \"message\": \"Summary API did not return a valid response.\",\n                    \"details\": response.content.decode(),\n                }\n            )\n        else:\n            return summary\n    def _get_labels(self) -> Tuple[List[str], List[str]]:\n        \"\"\"Get node and edge labels from the Neptune statistics summary\"\"\"\n        summary = self._get_summary()\n        n_labels = summary[\"nodeLabels\"]\n        e_labels = summary[\"edgeLabels\"]\n        return n_labels, e_labels\n    def _get_triples(self, e_labels: List[str]) -> List[str]:\n        triple_query = \"\"\"\n        MATCH (a)-[e:`{e_label}`]->(b)\n        WITH a,e,b LIMIT 3000\n        RETURN DISTINCT labels(a) AS from, type(e) AS edge, labels(b) AS to\n        LIMIT 10\n        \"\"\"\n        triple_template = \"(:`{a}`)-[:`{e}`]->(:`{b}`)\"\n        triple_schema = []\n        for label in e_labels:\n            q = triple_query.format(e_label=label)\n            data = self.query(q)\n            for d in data[\"results\"]:\n                triple = triple_template.format(\n                    a=d[\"from\"][0], e=d[\"edge\"], b=d[\"to\"][0]\n                )\n                triple_schema.append(triple)\n        return triple_schema\n    def _get_node_properties(self, n_labels: List[str], types: Dict) -> List:\n        node_properties_query = \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html"}
{"id": "a830323f4010-4", "text": "node_properties_query = \"\"\"\n        MATCH (a:`{n_label}`)\n        RETURN properties(a) AS props\n        LIMIT 100\n        \"\"\"\n        node_properties = []\n        for label in n_labels:\n            q = node_properties_query.format(n_label=label)\n            data = {\"label\": label, \"properties\": self.query(q)[\"results\"]}\n            s = set({})\n            for p in data[\"properties\"]:\n                for k, v in p[\"props\"].items():\n                    s.add((k, types[type(v).__name__]))\n            np = {\n                \"properties\": [{\"property\": k, \"type\": v} for k, v in s],\n                \"labels\": label,\n            }\n            node_properties.append(np)\n        return node_properties\n    def _get_edge_properties(self, e_labels: List[str], types: Dict[str, Any]) -> List:\n        edge_properties_query = \"\"\"\n        MATCH ()-[e:`{e_label}`]->()\n        RETURN properties(e) AS props\n        LIMIT 100\n        \"\"\"\n        edge_properties = []\n        for label in e_labels:\n            q = edge_properties_query.format(e_label=label)\n            data = {\"label\": label, \"properties\": self.query(q)[\"results\"]}\n            s = set({})\n            for p in data[\"properties\"]:\n                for k, v in p[\"props\"].items():\n                    s.add((k, types[type(v).__name__]))\n            ep = {\n                \"type\": label,\n                \"properties\": [{\"property\": k, \"type\": v} for k, v in s],\n            }\n            edge_properties.append(ep)\n        return edge_properties\n    def _refresh_schema(self) -> None:\n        \"\"\"\n        Refreshes the Neptune graph schema information.\n        \"\"\"\n        types = {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html"}
{"id": "a830323f4010-5", "text": "Refreshes the Neptune graph schema information.\n        \"\"\"\n        types = {\n            \"str\": \"STRING\",\n            \"float\": \"DOUBLE\",\n            \"int\": \"INTEGER\",\n            \"list\": \"LIST\",\n            \"dict\": \"MAP\",\n            \"bool\": \"BOOLEAN\",\n        }\n        n_labels, e_labels = self._get_labels()\n        triple_schema = self._get_triples(e_labels)\n        node_properties = self._get_node_properties(n_labels, types)\n        edge_properties = self._get_edge_properties(e_labels, types)\n        self.schema = f\"\"\"\n        Node properties are the following:\n        {node_properties}\n        Relationship properties are the following:\n        {edge_properties}\n        The relationships are the following:\n        {triple_schema}\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html"}
{"id": "e8d39e6beec3-0", "text": "Source code for langchain.graphs.networkx_graph\n\"\"\"Networkx wrapper for graph operations.\"\"\"\nfrom __future__ import annotations\nfrom typing import Any, List, NamedTuple, Optional, Tuple\nKG_TRIPLE_DELIMITER = \"<|>\"\n[docs]class KnowledgeTriple(NamedTuple):\n    \"\"\"A triple in the graph.\"\"\"\n    subject: str\n    predicate: str\n    object_: str\n[docs]    @classmethod\n    def from_string(cls, triple_string: str) -> \"KnowledgeTriple\":\n        \"\"\"Create a KnowledgeTriple from a string.\"\"\"\n        subject, predicate, object_ = triple_string.strip().split(\", \")\n        subject = subject[1:]\n        object_ = object_[:-1]\n        return cls(subject, predicate, object_)\n[docs]def parse_triples(knowledge_str: str) -> List[KnowledgeTriple]:\n    \"\"\"Parse knowledge triples from the knowledge string.\"\"\"\n    knowledge_str = knowledge_str.strip()\n    if not knowledge_str or knowledge_str == \"NONE\":\n        return []\n    triple_strs = knowledge_str.split(KG_TRIPLE_DELIMITER)\n    results = []\n    for triple_str in triple_strs:\n        try:\n            kg_triple = KnowledgeTriple.from_string(triple_str)\n        except ValueError:\n            continue\n        results.append(kg_triple)\n    return results\n[docs]def get_entities(entity_str: str) -> List[str]:\n    \"\"\"Extract entities from entity string.\"\"\"\n    if entity_str.strip() == \"NONE\":\n        return []\n    else:\n        return [w.strip() for w in entity_str.split(\",\")]\n[docs]class NetworkxEntityGraph:\n    \"\"\"Networkx wrapper for entity graph operations.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html"}
{"id": "e8d39e6beec3-1", "text": "that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n[docs]    def __init__(self, graph: Optional[Any] = None) -> None:\n        \"\"\"Create a new graph.\"\"\"\n        try:\n            import networkx as nx\n        except ImportError:\n            raise ImportError(\n                \"Could not import networkx python package. \"\n                \"Please install it with `pip install networkx`.\"\n            )\n        if graph is not None:\n            if not isinstance(graph, nx.DiGraph):\n                raise ValueError(\"Passed in graph is not of correct shape\")\n            self._graph = graph\n        else:\n            self._graph = nx.DiGraph()\n[docs]    @classmethod\n    def from_gml(cls, gml_path: str) -> NetworkxEntityGraph:\n        try:\n            import networkx as nx\n        except ImportError:\n            raise ImportError(\n                \"Could not import networkx python package. \"\n                \"Please install it with `pip install networkx`.\"\n            )\n        graph = nx.read_gml(gml_path)\n        return cls(graph)\n[docs]    def add_triple(self, knowledge_triple: KnowledgeTriple) -> None:\n        \"\"\"Add a triple to the graph.\"\"\"\n        # Creates nodes if they don't exist\n        # Overwrites existing edges", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html"}
{"id": "e8d39e6beec3-2", "text": "# Creates nodes if they don't exist\n        # Overwrites existing edges\n        if not self._graph.has_node(knowledge_triple.subject):\n            self._graph.add_node(knowledge_triple.subject)\n        if not self._graph.has_node(knowledge_triple.object_):\n            self._graph.add_node(knowledge_triple.object_)\n        self._graph.add_edge(\n            knowledge_triple.subject,\n            knowledge_triple.object_,\n            relation=knowledge_triple.predicate,\n        )\n[docs]    def delete_triple(self, knowledge_triple: KnowledgeTriple) -> None:\n        \"\"\"Delete a triple from the graph.\"\"\"\n        if self._graph.has_edge(knowledge_triple.subject, knowledge_triple.object_):\n            self._graph.remove_edge(knowledge_triple.subject, knowledge_triple.object_)\n[docs]    def get_triples(self) -> List[Tuple[str, str, str]]:\n        \"\"\"Get all triples in the graph.\"\"\"\n        return [(u, v, d[\"relation\"]) for u, v, d in self._graph.edges(data=True)]\n[docs]    def get_entity_knowledge(self, entity: str, depth: int = 1) -> List[str]:\n        \"\"\"Get information about an entity.\"\"\"\n        import networkx as nx\n        # TODO: Have more information-specific retrieval methods\n        if not self._graph.has_node(entity):\n            return []\n        results = []\n        for src, sink in nx.dfs_edges(self._graph, entity, depth_limit=depth):\n            relation = self._graph[src][sink][\"relation\"]\n            results.append(f\"{src} {relation} {sink}\")\n        return results\n[docs]    def write_to_gml(self, path: str) -> None:\n        import networkx as nx\n        nx.write_gml(self._graph, path)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html"}
{"id": "e8d39e6beec3-3", "text": "import networkx as nx\n        nx.write_gml(self._graph, path)\n[docs]    def clear(self) -> None:\n        \"\"\"Clear the graph.\"\"\"\n        self._graph.clear()\n[docs]    def get_topological_sort(self) -> List[str]:\n        \"\"\"Get a list of entity names in the graph sorted by causal dependence.\"\"\"\n        import networkx as nx\n        return list(nx.topological_sort(self._graph))\n[docs]    def draw_graphviz(self, **kwargs: Any) -> None:\n        \"\"\"\n        Provides better drawing\n        Usage in a jupyter notebook:\n            >>> from IPython.display import SVG\n            >>> self.draw_graphviz_svg(layout=\"dot\", filename=\"web.svg\")\n            >>> SVG('web.svg')\n        \"\"\"\n        from networkx.drawing.nx_agraph import to_agraph\n        try:\n            import pygraphviz  # noqa: F401\n        except ImportError as e:\n            if e.name == \"_graphviz\":\n                \"\"\"\n                >>> e.msg  # pygraphviz throws this error\n                ImportError: libcgraph.so.6: cannot open shared object file\n                \"\"\"\n                raise ImportError(\n                    \"Could not import graphviz debian package. \"\n                    \"Please install it with:\"\n                    \"`sudo apt-get update`\"\n                    \"`sudo apt-get install graphviz graphviz-dev`\"\n                )\n            else:\n                raise ImportError(\n                    \"Could not import pygraphviz python package. \"\n                    \"Please install it with:\"\n                    \"`pip install pygraphviz`.\"\n                )\n        graph = to_agraph(self._graph)  # --> pygraphviz.agraph.AGraph\n        # pygraphviz.github.io/documentation/stable/tutorial.html#layout-and-drawing\n        graph.layout(prog=kwargs.get(\"prog\", \"dot\"))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html"}
{"id": "e8d39e6beec3-4", "text": "graph.layout(prog=kwargs.get(\"prog\", \"dot\"))\n        graph.draw(kwargs.get(\"path\", \"graph.svg\"))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html"}
{"id": "a7058a339ea3-0", "text": "Source code for langchain.graphs.neo4j_graph\nfrom typing import Any, Dict, List, Optional\nfrom langchain.graphs.graph_document import GraphDocument\nfrom langchain.graphs.graph_store import GraphStore\nfrom langchain.utils import get_from_env\nnode_properties_query = \"\"\"\nCALL apoc.meta.data()\nYIELD label, other, elementType, type, property\nWHERE NOT type = \"RELATIONSHIP\" AND elementType = \"node\"\nWITH label AS nodeLabels, collect({property:property, type:type}) AS properties\nRETURN {labels: nodeLabels, properties: properties} AS output\n\"\"\"\nrel_properties_query = \"\"\"\nCALL apoc.meta.data()\nYIELD label, other, elementType, type, property\nWHERE NOT type = \"RELATIONSHIP\" AND elementType = \"relationship\"\nWITH label AS nodeLabels, collect({property:property, type:type}) AS properties\nRETURN {type: nodeLabels, properties: properties} AS output\n\"\"\"\nrel_query = \"\"\"\nCALL apoc.meta.data()\nYIELD label, other, elementType, type, property\nWHERE type = \"RELATIONSHIP\" AND elementType = \"node\"\nUNWIND other AS other_node\nRETURN {start: label, type: property, end: toString(other_node)} AS output\n\"\"\"\n[docs]class Neo4jGraph(GraphStore):\n    \"\"\"Neo4j wrapper for graph operations.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html"}
{"id": "a7058a339ea3-1", "text": "The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        url: Optional[str] = None,\n        username: Optional[str] = None,\n        password: Optional[str] = None,\n        database: str = \"neo4j\",\n    ) -> None:\n        \"\"\"Create a new Neo4j graph wrapper instance.\"\"\"\n        try:\n            import neo4j\n        except ImportError:\n            raise ValueError(\n                \"Could not import neo4j python package. \"\n                \"Please install it with `pip install neo4j`.\"\n            )\n        url = get_from_env(\"url\", \"NEO4J_URI\", url)\n        username = get_from_env(\"username\", \"NEO4J_USERNAME\", username)\n        password = get_from_env(\"password\", \"NEO4J_PASSWORD\", password)\n        database = get_from_env(\"database\", \"NEO4J_DATABASE\", database)\n        self._driver = neo4j.GraphDatabase.driver(url, auth=(username, password))\n        self._database = database\n        self.schema: str = \"\"\n        self.structured_schema: Dict[str, Any] = {}\n        # Verify connection\n        try:\n            self._driver.verify_connectivity()\n        except neo4j.exceptions.ServiceUnavailable:\n            raise ValueError(\n                \"Could not connect to Neo4j database. \"\n                \"Please ensure that the url is correct\"\n            )\n        except neo4j.exceptions.AuthError:\n            raise ValueError(\n                \"Could not connect to Neo4j database. \"\n                \"Please ensure that the username and password are correct\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html"}
{"id": "a7058a339ea3-2", "text": "\"Please ensure that the username and password are correct\"\n            )\n        # Set schema\n        try:\n            self.refresh_schema()\n        except neo4j.exceptions.ClientError:\n            raise ValueError(\n                \"Could not use APOC procedures. \"\n                \"Please ensure the APOC plugin is installed in Neo4j and that \"\n                \"'apoc.meta.data()' is allowed in Neo4j configuration \"\n            )\n    @property\n    def get_schema(self) -> str:\n        \"\"\"Returns the schema of the Graph\"\"\"\n        return self.schema\n    @property\n    def get_structured_schema(self) -> Dict[str, Any]:\n        \"\"\"Returns the structured schema of the Graph\"\"\"\n        return self.structured_schema\n[docs]    def query(self, query: str, params: dict = {}) -> List[Dict[str, Any]]:\n        \"\"\"Query Neo4j database.\"\"\"\n        from neo4j.exceptions import CypherSyntaxError\n        with self._driver.session(database=self._database) as session:\n            try:\n                data = session.run(query, params)\n                return [r.data() for r in data]\n            except CypherSyntaxError as e:\n                raise ValueError(f\"Generated Cypher Statement is not valid\\n{e}\")\n[docs]    def refresh_schema(self) -> None:\n        \"\"\"\n        Refreshes the Neo4j graph schema information.\n        \"\"\"\n        node_properties = [el[\"output\"] for el in self.query(node_properties_query)]\n        rel_properties = [el[\"output\"] for el in self.query(rel_properties_query)]\n        relationships = [el[\"output\"] for el in self.query(rel_query)]\n        self.structured_schema = {\n            \"node_props\": {el[\"labels\"]: el[\"properties\"] for el in node_properties},", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html"}
{"id": "a7058a339ea3-3", "text": "\"rel_props\": {el[\"type\"]: el[\"properties\"] for el in rel_properties},\n            \"relationships\": relationships,\n        }\n        self.schema = f\"\"\"\n        Node properties are the following:\n        {node_properties}\n        Relationship properties are the following:\n        {rel_properties}\n        The relationships are the following:\n        {[f\"(:{el['start']})-[:{el['type']}]->(:{el['end']})\" for el in relationships]}\n        \"\"\"\n[docs]    def add_graph_documents(\n        self, graph_documents: List[GraphDocument], include_source: bool = False\n    ) -> None:\n        \"\"\"\n        Take GraphDocument as input as uses it to construct a graph.\n        \"\"\"\n        for document in graph_documents:\n            include_docs_query = (\n                \"CREATE (d:Document) \"\n                \"SET d.text = $document.page_content \"\n                \"SET d += $document.metadata \"\n                \"WITH d \"\n            )\n            # Import nodes\n            self.query(\n                (\n                    f\"{include_docs_query if include_source else ''}\"\n                    \"UNWIND $data AS row \"\n                    \"CALL apoc.merge.node([row.type], {id: row.id}, \"\n                    \"row.properties, {}) YIELD node \"\n                    f\"{'MERGE (d)-[:MENTIONS]->(node) ' if include_source else ''}\"\n                    \"RETURN distinct 'done' AS result\"\n                ),\n                {\n                    \"data\": [el.__dict__ for el in document.nodes],\n                    \"document\": document.source.__dict__,\n                },\n            )\n            # Import relationships\n            self.query(\n                \"UNWIND $data AS row \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html"}
{"id": "a7058a339ea3-4", "text": "self.query(\n                \"UNWIND $data AS row \"\n                \"CALL apoc.merge.node([row.source_label], {id: row.source},\"\n                \"{}, {}) YIELD node as source \"\n                \"CALL apoc.merge.node([row.target_label], {id: row.target},\"\n                \"{}, {}) YIELD node as target \"\n                \"CALL apoc.merge.relationship(source, row.type, \"\n                \"{}, row.properties, target) YIELD rel \"\n                \"RETURN distinct 'done'\",\n                {\n                    \"data\": [\n                        {\n                            \"source\": el.source.id,\n                            \"source_label\": el.source.type,\n                            \"target\": el.target.id,\n                            \"target_label\": el.target.type,\n                            \"type\": el.type.replace(\" \", \"_\").upper(),\n                            \"properties\": el.properties,\n                        }\n                        for el in document.relationships\n                    ]\n                },\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html"}
{"id": "8835e4fc83b3-0", "text": "Source code for langchain.graphs.graph_document\nfrom __future__ import annotations\nfrom typing import List, Union\nfrom langchain.load.serializable import Serializable\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema import Document\n[docs]class Node(Serializable):\n    \"\"\"Represents a node in a graph with associated properties.\n    Attributes:\n        id (Union[str, int]): A unique identifier for the node.\n        type (str): The type or label of the node, default is \"Node\".\n        properties (dict): Additional properties and metadata associated with the node.\n    \"\"\"\n    id: Union[str, int]\n    type: str = \"Node\"\n    properties: dict = Field(default_factory=dict)\n[docs]class Relationship(Serializable):\n    \"\"\"Represents a directed relationship between two nodes in a graph.\n    Attributes:\n        source (Node): The source node of the relationship.\n        target (Node): The target node of the relationship.\n        type (str): The type of the relationship.\n        properties (dict): Additional properties associated with the relationship.\n    \"\"\"\n    source: Node\n    target: Node\n    type: str\n    properties: dict = Field(default_factory=dict)\n[docs]class GraphDocument(Serializable):\n    \"\"\"Represents a graph document consisting of nodes and relationships.\n    Attributes:\n        nodes (List[Node]): A list of nodes in the graph.\n        relationships (List[Relationship]): A list of relationships in the graph.\n        source (Document): The document from which the graph information is derived.\n    \"\"\"\n    nodes: List[Node]\n    relationships: List[Relationship]\n    source: Document", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/graph_document.html"}
{"id": "b0c785826f45-0", "text": "Source code for langchain.graphs.hugegraph\nfrom typing import Any, Dict, List\n[docs]class HugeGraph:\n    \"\"\"HugeGraph wrapper for graph operations.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        username: str = \"default\",\n        password: str = \"default\",\n        address: str = \"127.0.0.1\",\n        port: int = 8081,\n        graph: str = \"hugegraph\",\n    ) -> None:\n        \"\"\"Create a new HugeGraph wrapper instance.\"\"\"\n        try:\n            from hugegraph.connection import PyHugeGraph\n        except ImportError:\n            raise ValueError(\n                \"Please install HugeGraph Python client first: \"\n                \"`pip3 install hugegraph-python`\"\n            )\n        self.username = username\n        self.password = password\n        self.address = address\n        self.port = port\n        self.graph = graph\n        self.client = PyHugeGraph(\n            address, port, user=username, pwd=password, graph=graph\n        )\n        self.schema = \"\"\n        # Set schema\n        try:\n            self.refresh_schema()\n        except Exception as e:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/hugegraph.html"}
{"id": "b0c785826f45-1", "text": "try:\n            self.refresh_schema()\n        except Exception as e:\n            raise ValueError(f\"Could not refresh schema. Error: {e}\")\n    @property\n    def get_schema(self) -> str:\n        \"\"\"Returns the schema of the HugeGraph database\"\"\"\n        return self.schema\n[docs]    def refresh_schema(self) -> None:\n        \"\"\"\n        Refreshes the HugeGraph schema information.\n        \"\"\"\n        schema = self.client.schema()\n        vertex_schema = schema.getVertexLabels()\n        edge_schema = schema.getEdgeLabels()\n        relationships = schema.getRelations()\n        self.schema = (\n            f\"Node properties: {vertex_schema}\\n\"\n            f\"Edge properties: {edge_schema}\\n\"\n            f\"Relationships: {relationships}\\n\"\n        )\n[docs]    def query(self, query: str) -> List[Dict[str, Any]]:\n        g = self.client.gremlin()\n        res = g.exec(query)\n        return res[\"data\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/hugegraph.html"}
{"id": "ade25e025f6a-0", "text": "Source code for langchain.graphs.arangodb_graph\nimport os\nfrom math import ceil\nfrom typing import Any, Dict, List, Optional\n[docs]class ArangoGraph:\n    \"\"\"ArangoDB wrapper for graph operations.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n[docs]    def __init__(self, db: Any) -> None:\n        \"\"\"Create a new ArangoDB graph wrapper instance.\"\"\"\n        self.set_db(db)\n        self.set_schema()\n    @property\n    def db(self) -> Any:\n        return self.__db\n    @property\n    def schema(self) -> Dict[str, Any]:\n        return self.__schema\n[docs]    def set_db(self, db: Any) -> None:\n        from arango.database import Database\n        if not isinstance(db, Database):\n            msg = \"**db** parameter must inherit from arango.database.Database\"\n            raise TypeError(msg)\n        self.__db: Database = db\n        self.set_schema()\n[docs]    def set_schema(self, schema: Optional[Dict[str, Any]] = None) -> None:\n        \"\"\"\n        Set the schema of the ArangoDB Database.\n        Auto-generates Schema if **schema** is None.\n        \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html"}
{"id": "ade25e025f6a-1", "text": "Auto-generates Schema if **schema** is None.\n        \"\"\"\n        self.__schema = self.generate_schema() if schema is None else schema\n[docs]    def generate_schema(\n        self, sample_ratio: float = 0\n    ) -> Dict[str, List[Dict[str, Any]]]:\n        \"\"\"\n        Generates the schema of the ArangoDB Database and returns it\n        User can specify a **sample_ratio** (0 to 1) to determine the\n        ratio of documents/edges used (in relation to the Collection size)\n        to render each Collection Schema.\n        \"\"\"\n        if not 0 <= sample_ratio <= 1:\n            raise ValueError(\"**sample_ratio** value must be in between 0 to 1\")\n        # Stores the Edge Relationships between each ArangoDB Document Collection\n        graph_schema: List[Dict[str, Any]] = [\n            {\"graph_name\": g[\"name\"], \"edge_definitions\": g[\"edge_definitions\"]}\n            for g in self.db.graphs()\n        ]\n        # Stores the schema of every ArangoDB Document/Edge collection\n        collection_schema: List[Dict[str, Any]] = []\n        for collection in self.db.collections():\n            if collection[\"system\"]:\n                continue\n            # Extract collection name, type, and size\n            col_name: str = collection[\"name\"]\n            col_type: str = collection[\"type\"]\n            col_size: int = self.db.collection(col_name).count()\n            # Skip collection if empty\n            if col_size == 0:\n                continue\n            # Set number of ArangoDB documents/edges to retrieve\n            limit_amount = ceil(sample_ratio * col_size) or 1\n            aql = f\"\"\"\n                FOR doc in {col_name}\n                    LIMIT {limit_amount}\n                    RETURN doc\n            \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html"}
{"id": "ade25e025f6a-2", "text": "LIMIT {limit_amount}\n                    RETURN doc\n            \"\"\"\n            doc: Dict[str, Any]\n            properties: List[Dict[str, str]] = []\n            for doc in self.__db.aql.execute(aql):\n                for key, value in doc.items():\n                    properties.append({\"name\": key, \"type\": type(value).__name__})\n            collection_schema.append(\n                {\n                    \"collection_name\": col_name,\n                    \"collection_type\": col_type,\n                    f\"{col_type}_properties\": properties,\n                    f\"example_{col_type}\": doc,\n                }\n            )\n        return {\"Graph Schema\": graph_schema, \"Collection Schema\": collection_schema}\n[docs]    def query(\n        self, query: str, top_k: Optional[int] = None, **kwargs: Any\n    ) -> List[Dict[str, Any]]:\n        \"\"\"Query the ArangoDB database.\"\"\"\n        import itertools\n        cursor = self.__db.aql.execute(query, **kwargs)\n        return [doc for doc in itertools.islice(cursor, top_k)]\n[docs]    @classmethod\n    def from_db_credentials(\n        cls,\n        url: Optional[str] = None,\n        dbname: Optional[str] = None,\n        username: Optional[str] = None,\n        password: Optional[str] = None,\n    ) -> Any:\n        \"\"\"Convenience constructor that builds Arango DB from credentials.\n        Args:\n            url: Arango DB url. Can be passed in as named arg or set as environment\n                var ``ARANGODB_URL``. Defaults to \"http://localhost:8529\".\n            dbname: Arango DB name. Can be passed in as named arg or set as\n                environment var ``ARANGODB_DBNAME``. Defaults to \"_system\".", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html"}
{"id": "ade25e025f6a-3", "text": "environment var ``ARANGODB_DBNAME``. Defaults to \"_system\".\n            username: Can be passed in as named arg or set as environment var\n                ``ARANGODB_USERNAME``. Defaults to \"root\".\n            password: Can be passed ni as named arg or set as environment var\n                ``ARANGODB_PASSWORD``. Defaults to \"\".\n        Returns:\n            An arango.database.StandardDatabase.\n        \"\"\"\n        db = get_arangodb_client(\n            url=url, dbname=dbname, username=username, password=password\n        )\n        return cls(db)\n[docs]def get_arangodb_client(\n    url: Optional[str] = None,\n    dbname: Optional[str] = None,\n    username: Optional[str] = None,\n    password: Optional[str] = None,\n) -> Any:\n    \"\"\"Get the Arango DB client from credentials.\n    Args:\n        url: Arango DB url. Can be passed in as named arg or set as environment\n            var ``ARANGODB_URL``. Defaults to \"http://localhost:8529\".\n        dbname: Arango DB name. Can be passed in as named arg or set as\n            environment var ``ARANGODB_DBNAME``. Defaults to \"_system\".\n        username: Can be passed in as named arg or set as environment var\n            ``ARANGODB_USERNAME``. Defaults to \"root\".\n        password: Can be passed ni as named arg or set as environment var\n            ``ARANGODB_PASSWORD``. Defaults to \"\".\n    Returns:\n        An arango.database.StandardDatabase.\n    \"\"\"\n    try:\n        from arango import ArangoClient\n    except ImportError as e:\n        raise ImportError(\n            \"Unable to import arango, please install with `pip install python-arango`.\"\n        ) from e", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html"}
{"id": "ade25e025f6a-4", "text": ") from e\n    _url: str = url or os.environ.get(\"ARANGODB_URL\", \"http://localhost:8529\")  # type: ignore[assignment]  # noqa: E501\n    _dbname: str = dbname or os.environ.get(\"ARANGODB_DBNAME\", \"_system\")  # type: ignore[assignment]  # noqa: E501\n    _username: str = username or os.environ.get(\"ARANGODB_USERNAME\", \"root\")  # type: ignore[assignment]  # noqa: E501\n    _password: str = password or os.environ.get(\"ARANGODB_PASSWORD\", \"\")  # type: ignore[assignment]  # noqa: E501\n    return ArangoClient(_url).db(_dbname, _username, _password, verify=True)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html"}
{"id": "b23bed57542e-0", "text": "Source code for langchain.graphs.nebula_graph\nimport logging\nfrom string import Template\nfrom typing import Any, Dict, Optional\nlogger = logging.getLogger(__name__)\nrel_query = Template(\n    \"\"\"\nMATCH ()-[e:`$edge_type`]->()\n  WITH e limit 1\nMATCH (m)-[:`$edge_type`]->(n) WHERE id(m) == src(e) AND id(n) == dst(e)\nRETURN \"(:\" + tags(m)[0] + \")-[:$edge_type]->(:\" + tags(n)[0] + \")\" AS rels\n\"\"\"\n)\nRETRY_TIMES = 3\n[docs]class NebulaGraph:\n    \"\"\"NebulaGraph wrapper for graph operations.\n    NebulaGraph inherits methods from Neo4jGraph to bring ease to the user space.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        space: str,\n        username: str = \"root\",\n        password: str = \"nebula\",\n        address: str = \"127.0.0.1\",\n        port: int = 9669,\n        session_pool_size: int = 30,\n    ) -> None:\n        \"\"\"Create a new NebulaGraph wrapper instance.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html"}
{"id": "b23bed57542e-1", "text": ") -> None:\n        \"\"\"Create a new NebulaGraph wrapper instance.\"\"\"\n        try:\n            import nebula3  # noqa: F401\n            import pandas  # noqa: F401\n        except ImportError:\n            raise ValueError(\n                \"Please install NebulaGraph Python client and pandas first: \"\n                \"`pip install nebula3-python pandas`\"\n            )\n        self.username = username\n        self.password = password\n        self.address = address\n        self.port = port\n        self.space = space\n        self.session_pool_size = session_pool_size\n        self.session_pool = self._get_session_pool()\n        self.schema = \"\"\n        # Set schema\n        try:\n            self.refresh_schema()\n        except Exception as e:\n            raise ValueError(f\"Could not refresh schema. Error: {e}\")\n    def _get_session_pool(self) -> Any:\n        assert all(\n            [self.username, self.password, self.address, self.port, self.space]\n        ), (\n            \"Please provide all of the following parameters: \"\n            \"username, password, address, port, space\"\n        )\n        from nebula3.Config import SessionPoolConfig\n        from nebula3.Exception import AuthFailedException, InValidHostname\n        from nebula3.gclient.net.SessionPool import SessionPool\n        config = SessionPoolConfig()\n        config.max_size = self.session_pool_size\n        try:\n            session_pool = SessionPool(\n                self.username,\n                self.password,\n                self.space,\n                [(self.address, self.port)],\n            )\n        except InValidHostname:\n            raise ValueError(\n                \"Could not connect to NebulaGraph database. \"\n                \"Please ensure that the address and port are correct\"\n            )\n        try:\n            session_pool.init(config)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html"}
{"id": "b23bed57542e-2", "text": ")\n        try:\n            session_pool.init(config)\n        except AuthFailedException:\n            raise ValueError(\n                \"Could not connect to NebulaGraph database. \"\n                \"Please ensure that the username and password are correct\"\n            )\n        except RuntimeError as e:\n            raise ValueError(f\"Error initializing session pool. Error: {e}\")\n        return session_pool\n    def __del__(self) -> None:\n        try:\n            self.session_pool.close()\n        except Exception as e:\n            logger.warning(f\"Could not close session pool. Error: {e}\")\n    @property\n    def get_schema(self) -> str:\n        \"\"\"Returns the schema of the NebulaGraph database\"\"\"\n        return self.schema\n[docs]    def execute(self, query: str, params: Optional[dict] = None, retry: int = 0) -> Any:\n        \"\"\"Query NebulaGraph database.\"\"\"\n        from nebula3.Exception import IOErrorException, NoValidSessionException\n        from nebula3.fbthrift.transport.TTransport import TTransportException\n        params = params or {}\n        try:\n            result = self.session_pool.execute_parameter(query, params)\n            if not result.is_succeeded():\n                logger.warning(\n                    f\"Error executing query to NebulaGraph. \"\n                    f\"Error: {result.error_msg()}\\n\"\n                    f\"Query: {query} \\n\"\n                )\n            return result\n        except NoValidSessionException:\n            logger.warning(\n                f\"No valid session found in session pool. \"\n                f\"Please consider increasing the session pool size. \"\n                f\"Current size: {self.session_pool_size}\"\n            )\n            raise ValueError(\n                f\"No valid session found in session pool. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html"}
{"id": "b23bed57542e-3", "text": ")\n            raise ValueError(\n                f\"No valid session found in session pool. \"\n                f\"Please consider increasing the session pool size. \"\n                f\"Current size: {self.session_pool_size}\"\n            )\n        except RuntimeError as e:\n            if retry < RETRY_TIMES:\n                retry += 1\n                logger.warning(\n                    f\"Error executing query to NebulaGraph. \"\n                    f\"Retrying ({retry}/{RETRY_TIMES})...\\n\"\n                    f\"query: {query} \\n\"\n                    f\"Error: {e}\"\n                )\n                return self.execute(query, params, retry)\n            else:\n                raise ValueError(f\"Error executing query to NebulaGraph. Error: {e}\")\n        except (TTransportException, IOErrorException):\n            # connection issue, try to recreate session pool\n            if retry < RETRY_TIMES:\n                retry += 1\n                logger.warning(\n                    f\"Connection issue with NebulaGraph. \"\n                    f\"Retrying ({retry}/{RETRY_TIMES})...\\n to recreate session pool\"\n                )\n                self.session_pool = self._get_session_pool()\n                return self.execute(query, params, retry)\n[docs]    def refresh_schema(self) -> None:\n        \"\"\"\n        Refreshes the NebulaGraph schema information.\n        \"\"\"\n        tags_schema, edge_types_schema, relationships = [], [], []\n        for tag in self.execute(\"SHOW TAGS\").column_values(\"Name\"):\n            tag_name = tag.cast()\n            tag_schema = {\"tag\": tag_name, \"properties\": []}\n            r = self.execute(f\"DESCRIBE TAG `{tag_name}`\")\n            props, types = r.column_values(\"Field\"), r.column_values(\"Type\")\n            for i in range(r.row_size()):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html"}
{"id": "b23bed57542e-4", "text": "for i in range(r.row_size()):\n                tag_schema[\"properties\"].append((props[i].cast(), types[i].cast()))\n            tags_schema.append(tag_schema)\n        for edge_type in self.execute(\"SHOW EDGES\").column_values(\"Name\"):\n            edge_type_name = edge_type.cast()\n            edge_schema = {\"edge\": edge_type_name, \"properties\": []}\n            r = self.execute(f\"DESCRIBE EDGE `{edge_type_name}`\")\n            props, types = r.column_values(\"Field\"), r.column_values(\"Type\")\n            for i in range(r.row_size()):\n                edge_schema[\"properties\"].append((props[i].cast(), types[i].cast()))\n            edge_types_schema.append(edge_schema)\n            # build relationships types\n            r = self.execute(\n                rel_query.substitute(edge_type=edge_type_name)\n            ).column_values(\"rels\")\n            if len(r) > 0:\n                relationships.append(r[0].cast())\n        self.schema = (\n            f\"Node properties: {tags_schema}\\n\"\n            f\"Edge properties: {edge_types_schema}\\n\"\n            f\"Relationships: {relationships}\\n\"\n        )\n[docs]    def query(self, query: str, retry: int = 0) -> Dict[str, Any]:\n        result = self.execute(query, retry=retry)\n        columns = result.keys()\n        d: Dict[str, list] = {}\n        for col_num in range(result.col_size()):\n            col_name = columns[col_num]\n            col_list = result.column_values(col_name)\n            d[col_name] = [x.cast() for x in col_list]\n        return d", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html"}
{"id": "702633c1c847-0", "text": "Source code for langchain.graphs.memgraph_graph\nfrom langchain.graphs.neo4j_graph import Neo4jGraph\nSCHEMA_QUERY = \"\"\"\nCALL llm_util.schema(\"prompt_ready\")\nYIELD *\nRETURN *\n\"\"\"\nRAW_SCHEMA_QUERY = \"\"\"\nCALL llm_util.schema(\"raw\")\nYIELD *\nRETURN *\n\"\"\"\n[docs]class MemgraphGraph(Neo4jGraph):\n    \"\"\"Memgraph wrapper for graph operations.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n[docs]    def __init__(\n        self, url: str, username: str, password: str, *, database: str = \"memgraph\"\n    ) -> None:\n        \"\"\"Create a new Memgraph graph wrapper instance.\"\"\"\n        super().__init__(url, username, password, database=database)\n[docs]    def refresh_schema(self) -> None:\n        \"\"\"\n        Refreshes the Memgraph graph schema information.\n        \"\"\"\n        db_schema = self.query(SCHEMA_QUERY)[0].get(\"schema\")\n        assert db_schema is not None\n        self.schema = db_schema\n        db_structured_schema = self.query(RAW_SCHEMA_QUERY)[0].get(\"schema\")\n        assert db_structured_schema is not None\n        self.structured_schema = db_structured_schema", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/memgraph_graph.html"}
{"id": "447fc2513621-0", "text": "Source code for langchain.graphs.falkordb_graph\nfrom typing import Any, Dict, List, Optional\nfrom langchain.graphs.graph_document import GraphDocument\nfrom langchain.graphs.graph_store import GraphStore\nnode_properties_query = \"\"\"\nMATCH (n)\nWITH keys(n) as keys, labels(n) AS labels\nWITH CASE WHEN keys = [] THEN [NULL] ELSE keys END AS keys, labels\nUNWIND labels AS label\nUNWIND keys AS key\nWITH label, collect(DISTINCT key) AS keys\nRETURN {label:label, keys:keys} AS output\n\"\"\"\nrel_properties_query = \"\"\"\nMATCH ()-[r]->()\nWITH keys(r) as keys, type(r) AS types\nWITH CASE WHEN keys = [] THEN [NULL] ELSE keys END AS keys, types \nUNWIND types AS type\nUNWIND keys AS key WITH type,\ncollect(DISTINCT key) AS keys \nRETURN {types:type, keys:keys} AS output\n\"\"\"\nrel_query = \"\"\"\nMATCH (n)-[r]->(m)\nUNWIND labels(n) as src_label\nUNWIND labels(m) as dst_label\nUNWIND type(r) as rel_type\nRETURN DISTINCT {start: src_label, type: rel_type, end: dst_label} AS output\n\"\"\"\n[docs]class FalkorDBGraph(GraphStore):\n    \"\"\"FalkorDB wrapper for graph operations.\n    *Security note*: Make sure that the database connection uses credentials\n        that are narrowly-scoped to only include necessary permissions.\n        Failure to do so may result in data corruption or loss, since the calling\n        code may attempt commands that would result in deletion, mutation\n        of data if appropriately prompted or reading sensitive data if such\n        data is present in the database.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/falkordb_graph.html"}
{"id": "447fc2513621-1", "text": "data is present in the database.\n        The best way to guard against such negative outcomes is to (as appropriate)\n        limit the permissions granted to the credentials used with this tool.\n        See https://python.langchain.com/docs/security for more information.\n    \"\"\"\n[docs]    def __init__(\n        self,\n        database: str,\n        host: str = \"localhost\",\n        port: int = 6379,\n        username: Optional[str] = None,\n        password: Optional[str] = None,\n        ssl: bool = False,\n    ) -> None:\n        \"\"\"Create a new FalkorDB graph wrapper instance.\"\"\"\n        try:\n            import redis\n            from redis.commands.graph import Graph\n        except ImportError:\n            raise ImportError(\n                \"Could not import redis python package. \"\n                \"Please install it with `pip install redis`.\"\n            )\n        self._driver = redis.Redis(\n            host=host, port=port, username=username, password=password, ssl=ssl\n        )\n        self._graph = Graph(self._driver, database)\n        self.schema: str = \"\"\n        self.structured_schema: Dict[str, Any] = {}\n        try:\n            self.refresh_schema()\n        except Exception as e:\n            raise ValueError(f\"Could not refresh schema. Error: {e}\")\n    @property\n    def get_schema(self) -> str:\n        \"\"\"Returns the schema of the FalkorDB database\"\"\"\n        return self.schema\n    @property\n    def get_structured_schema(self) -> Dict[str, Any]:\n        \"\"\"Returns the structured schema of the Graph\"\"\"\n        return self.structured_schema\n[docs]    def refresh_schema(self) -> None:\n        \"\"\"Refreshes the schema of the FalkorDB database\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/falkordb_graph.html"}
{"id": "447fc2513621-2", "text": "\"\"\"Refreshes the schema of the FalkorDB database\"\"\"\n        node_properties: List[Any] = self.query(node_properties_query)\n        rel_properties: List[Any] = self.query(rel_properties_query)\n        relationships: List[Any] = self.query(rel_query)\n        self.structured_schema = {\n            \"node_props\": {el[0][\"label\"]: el[0][\"keys\"] for el in node_properties},\n            \"rel_props\": {el[0][\"types\"]: el[0][\"keys\"] for el in rel_properties},\n            \"relationships\": [el[0] for el in relationships],\n        }\n        self.schema = (\n            f\"Node properties: {node_properties}\\n\"\n            f\"Relationships properties: {rel_properties}\\n\"\n            f\"Relationships: {relationships}\\n\"\n        )\n[docs]    def query(self, query: str, params: dict = {}) -> List[Dict[str, Any]]:\n        \"\"\"Query FalkorDB database.\"\"\"\n        try:\n            data = self._graph.query(query, params)\n            return data.result_set\n        except Exception as e:\n            raise ValueError(\"Generated Cypher Statement is not valid\\n\" f\"{e}\")\n[docs]    def add_graph_documents(\n        self, graph_documents: List[GraphDocument], include_source: bool = False\n    ) -> None:\n        \"\"\"\n        Take GraphDocument as input as uses it to construct a graph.\n        \"\"\"\n        for document in graph_documents:\n            # Import nodes\n            for node in document.nodes:\n                self.query(\n                    (\n                        f\"MERGE (n:{node.type} {{id:'{node.id}'}}) \"\n                        \"SET n += $properties \"\n                        \"RETURN distinct 'done' AS result\"\n                    ),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/falkordb_graph.html"}
{"id": "447fc2513621-3", "text": "\"RETURN distinct 'done' AS result\"\n                    ),\n                    {\"properties\": node.properties},\n                )\n            # Import relationships\n            for rel in document.relationships:\n                self.query(\n                    (\n                        f\"MATCH (a:{rel.source.type} {{id:'{rel.source.id}'}}), \"\n                        f\"(b:{rel.target.type} {{id:'{rel.target.id}'}}) \"\n                        f\"MERGE (a)-[r:{(rel.type.replace(' ', '_').upper())}]->(b) \"\n                        \"SET r += $properties \"\n                        \"RETURN distinct 'done' AS result\"\n                    ),\n                    {\"properties\": rel.properties},\n                )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/falkordb_graph.html"}
{"id": "b76a57615593-0", "text": "Source code for langchain.graphs.graph_store\nfrom abc import abstractmethod\nfrom typing import Any, Dict, List\nfrom langchain.graphs.graph_document import GraphDocument\n[docs]class GraphStore:\n    \"\"\"An abstract class wrapper for graph operations.\"\"\"\n    @property\n    @abstractmethod\n    def get_schema(self) -> str:\n        \"\"\"Returns the schema of the Graph database\"\"\"\n        pass\n    @property\n    @abstractmethod\n    def get_structured_schema(self) -> Dict[str, Any]:\n        \"\"\"Returns the schema of the Graph database\"\"\"\n        pass\n[docs]    @abstractmethod\n    def query(self, query: str, params: dict = {}) -> List[Dict[str, Any]]:\n        \"\"\"Query the graph.\"\"\"\n        pass\n[docs]    @abstractmethod\n    def refresh_schema(self) -> None:\n        \"\"\"Refreshes the graph schema information.\"\"\"\n        pass\n[docs]    @abstractmethod\n    def add_graph_documents(\n        self, graph_documents: List[GraphDocument], include_source: bool = False\n    ) -> None:\n        \"\"\"Take GraphDocument as input as uses it to construct a graph.\"\"\"\n        pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/graph_store.html"}
{"id": "7107e9278fff-0", "text": "Source code for langchain.llms.cerebriumai\nimport logging\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class CerebriumAI(LLM):\n    \"\"\"CerebriumAI large language models.\n    To use, you should have the ``cerebrium`` python package installed, and the\n    environment variable ``CEREBRIUMAI_API_KEY`` set with your API key.\n    Any parameters that are valid to be passed to the call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.llms import CerebriumAI\n            cerebrium = CerebriumAI(endpoint_url=\"\")\n    \"\"\"\n    endpoint_url: str = \"\"\n    \"\"\"model endpoint to use\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not\n    explicitly specified.\"\"\"\n    cerebriumai_api_key: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic config.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = {field.alias for field in cls.__fields__.values()}\n        extra = values.get(\"model_kwargs\", {})", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html"}
{"id": "7107e9278fff-1", "text": "extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name not in all_required_field_names:\n                if field_name in extra:\n                    raise ValueError(f\"Found {field_name} supplied twice.\")\n                logger.warning(\n                    f\"\"\"{field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        cerebriumai_api_key = get_from_dict_or_env(\n            values, \"cerebriumai_api_key\", \"CEREBRIUMAI_API_KEY\"\n        )\n        values[\"cerebriumai_api_key\"] = cerebriumai_api_key\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"endpoint_url\": self.endpoint_url},\n            **{\"model_kwargs\": self.model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"cerebriumai\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call to CerebriumAI endpoint.\"\"\"\n        try:\n            from cerebrium import model_api_request\n        except ImportError:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html"}
{"id": "7107e9278fff-2", "text": "from cerebrium import model_api_request\n        except ImportError:\n            raise ValueError(\n                \"Could not import cerebrium python package. \"\n                \"Please install it with `pip install cerebrium`.\"\n            )\n        params = self.model_kwargs or {}\n        response = model_api_request(\n            self.endpoint_url,\n            {\"prompt\": prompt, **params, **kwargs},\n            self.cerebriumai_api_key,\n        )\n        text = response[\"data\"][\"result\"]\n        if stop is not None:\n            # I believe this is required since the stop tokens\n            # are not enforced by the model parameters\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html"}
{"id": "d4ba7116d9a9-0", "text": "Source code for langchain.llms.chatglm\nimport logging\nfrom typing import Any, List, Mapping, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nlogger = logging.getLogger(__name__)\n[docs]class ChatGLM(LLM):\n    \"\"\"ChatGLM LLM service.\n    Example:\n        .. code-block:: python\n            from langchain.llms import ChatGLM\n            endpoint_url = (\n                \"http://127.0.0.1:8000\"\n            )\n            ChatGLM_llm = ChatGLM(\n                endpoint_url=endpoint_url\n            )\n    \"\"\"\n    endpoint_url: str = \"http://127.0.0.1:8000/\"\n    \"\"\"Endpoint URL to use.\"\"\"\n    model_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    max_token: int = 20000\n    \"\"\"Max token allowed to pass to the model.\"\"\"\n    temperature: float = 0.1\n    \"\"\"LLM model temperature from 0 to 10.\"\"\"\n    history: List[List] = []\n    \"\"\"History of the conversation\"\"\"\n    top_p: float = 0.7\n    \"\"\"Top P for nucleus sampling from 0 to 1\"\"\"\n    with_history: bool = False\n    \"\"\"Whether to use history or not\"\"\"\n    @property\n    def _llm_type(self) -> str:\n        return \"chat_glm\"\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {\n            **{\"endpoint_url\": self.endpoint_url},", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/chatglm.html"}
{"id": "d4ba7116d9a9-1", "text": "return {\n            **{\"endpoint_url\": self.endpoint_url},\n            **{\"model_kwargs\": _model_kwargs},\n        }\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to a ChatGLM LLM inference endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = chatglm_llm(\"Who are you?\")\n        \"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        # HTTP headers for authorization\n        headers = {\"Content-Type\": \"application/json\"}\n        payload = {\n            \"prompt\": prompt,\n            \"temperature\": self.temperature,\n            \"history\": self.history,\n            \"max_length\": self.max_token,\n            \"top_p\": self.top_p,\n        }\n        payload.update(_model_kwargs)\n        payload.update(kwargs)\n        logger.debug(f\"ChatGLM payload: {payload}\")\n        # call api\n        try:\n            response = requests.post(self.endpoint_url, headers=headers, json=payload)\n        except requests.exceptions.RequestException as e:\n            raise ValueError(f\"Error raised by inference endpoint: {e}\")\n        logger.debug(f\"ChatGLM response: {response}\")\n        if response.status_code != 200:\n            raise ValueError(f\"Failed with response: {response}\")\n        try:\n            parsed_response = response.json()\n            # Check if response content does exists\n            if isinstance(parsed_response, dict):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/chatglm.html"}
{"id": "d4ba7116d9a9-2", "text": "# Check if response content does exists\n            if isinstance(parsed_response, dict):\n                content_keys = \"response\"\n                if content_keys in parsed_response:\n                    text = parsed_response[content_keys]\n                else:\n                    raise ValueError(f\"No content in response : {parsed_response}\")\n            else:\n                raise ValueError(f\"Unexpected response type: {parsed_response}\")\n        except requests.exceptions.JSONDecodeError as e:\n            raise ValueError(\n                f\"Error raised during decoding response from inference endpoint: {e}.\"\n                f\"\\nResponse: {response.text}\"\n            )\n        if stop is not None:\n            text = enforce_stop_tokens(text, stop)\n        if self.with_history:\n            self.history = self.history + [[None, parsed_response[\"response\"]]]\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/chatglm.html"}
{"id": "08d6223e104d-0", "text": "Source code for langchain.llms.huggingface_hub\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\nDEFAULT_REPO_ID = \"gpt2\"\nVALID_TASKS = (\"text2text-generation\", \"text-generation\", \"summarization\")\n[docs]class HuggingFaceHub(LLM):\n    \"\"\"HuggingFaceHub  models.\n    To use, you should have the ``huggingface_hub`` python package installed, and the\n    environment variable ``HUGGINGFACEHUB_API_TOKEN`` set with your API token, or pass\n    it as a named parameter to the constructor.\n    Only supports `text-generation`, `text2text-generation` and `summarization` for now.\n    Example:\n        .. code-block:: python\n            from langchain.llms import HuggingFaceHub\n            hf = HuggingFaceHub(repo_id=\"gpt2\", huggingfacehub_api_token=\"my-api-key\")\n    \"\"\"\n    client: Any  #: :meta private:\n    repo_id: str = DEFAULT_REPO_ID\n    \"\"\"Model name to use.\"\"\"\n    task: Optional[str] = None\n    \"\"\"Task to call the model with.\n    Should be a task that returns `generated_text` or `summary_text`.\"\"\"\n    model_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    huggingfacehub_api_token: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html"}
{"id": "08d6223e104d-1", "text": "extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        huggingfacehub_api_token = get_from_dict_or_env(\n            values, \"huggingfacehub_api_token\", \"HUGGINGFACEHUB_API_TOKEN\"\n        )\n        try:\n            from huggingface_hub.inference_api import InferenceApi\n            repo_id = values[\"repo_id\"]\n            client = InferenceApi(\n                repo_id=repo_id,\n                token=huggingfacehub_api_token,\n                task=values.get(\"task\"),\n            )\n            if client.task not in VALID_TASKS:\n                raise ValueError(\n                    f\"Got invalid task {client.task}, \"\n                    f\"currently only {VALID_TASKS} are supported\"\n                )\n            values[\"client\"] = client\n        except ImportError:\n            raise ValueError(\n                \"Could not import huggingface_hub python package. \"\n                \"Please install it with `pip install huggingface_hub`.\"\n            )\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {\n            **{\"repo_id\": self.repo_id, \"task\": self.task},\n            **{\"model_kwargs\": _model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"huggingface_hub\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html"}
{"id": "08d6223e104d-2", "text": "run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to HuggingFace Hub's inference endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = hf(\"Tell me a joke.\")\n        \"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        params = {**_model_kwargs, **kwargs}\n        response = self.client(inputs=prompt, params=params)\n        if \"error\" in response:\n            raise ValueError(f\"Error raised by inference API: {response['error']}\")\n        if self.client.task == \"text-generation\":\n            # Text generation return includes the starter text.\n            text = response[0][\"generated_text\"][len(prompt) :]\n        elif self.client.task == \"text2text-generation\":\n            text = response[0][\"generated_text\"]\n        elif self.client.task == \"summarization\":\n            text = response[0][\"summary_text\"]\n        else:\n            raise ValueError(\n                f\"Got invalid task {self.client.task}, \"\n                f\"currently only {VALID_TASKS} are supported\"\n            )\n        if stop is not None:\n            # This is a bit hacky, but I can't figure out a better way to enforce\n            # stop tokens when making calls to huggingface_hub.\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html"}
{"id": "39a0014d469a-0", "text": "Source code for langchain.llms.amazon_api_gateway\nfrom typing import Any, Dict, List, Mapping, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra\n[docs]class ContentHandlerAmazonAPIGateway:\n    \"\"\"Adapter to prepare the inputs from Langchain to a format\n    that LLM model expects.\n    It also provides helper function to extract\n    the generated text from the model response.\"\"\"\n[docs]    @classmethod\n    def transform_input(\n        cls, prompt: str, model_kwargs: Dict[str, Any]\n    ) -> Dict[str, Any]:\n        return {\"inputs\": prompt, \"parameters\": model_kwargs}\n[docs]    @classmethod\n    def transform_output(cls, response: Any) -> str:\n        return response.json()[0][\"generated_text\"]\n[docs]class AmazonAPIGateway(LLM):\n    \"\"\"Amazon API Gateway to access LLM models hosted on AWS.\"\"\"\n    api_url: str\n    \"\"\"API Gateway URL\"\"\"\n    headers: Optional[Dict] = None\n    \"\"\"API Gateway HTTP Headers to send, e.g. for authentication\"\"\"\n    model_kwargs: Optional[Dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    content_handler: ContentHandlerAmazonAPIGateway = ContentHandlerAmazonAPIGateway()\n    \"\"\"The content handler class that provides an input and\n    output transform functions to handle formats between LLM\n    and the endpoint.\n    \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/amazon_api_gateway.html"}
{"id": "39a0014d469a-1", "text": "\"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {\n            **{\"api_url\": self.api_url, \"headers\": self.headers},\n            **{\"model_kwargs\": _model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"amazon_api_gateway\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Amazon API Gateway model.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = se(\"Tell me a joke.\")\n        \"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        payload = self.content_handler.transform_input(prompt, _model_kwargs)\n        try:\n            response = requests.post(\n                self.api_url,\n                headers=self.headers,\n                json=payload,\n            )\n            text = self.content_handler.transform_output(response)\n        except Exception as error:\n            raise ValueError(f\"Error raised by the service: {error}\")\n        if stop is not None:\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/amazon_api_gateway.html"}
{"id": "81b97065f8fd-0", "text": "Source code for langchain.llms.azureml_endpoint\nimport json\nimport urllib.request\nimport warnings\nfrom abc import abstractmethod\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import BaseModel, validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class AzureMLEndpointClient(object):\n    \"\"\"AzureML Managed Endpoint client.\"\"\"\n[docs]    def __init__(\n        self, endpoint_url: str, endpoint_api_key: str, deployment_name: str = \"\"\n    ) -> None:\n        \"\"\"Initialize the class.\"\"\"\n        if not endpoint_api_key or not endpoint_url:\n            raise ValueError(\n                \"\"\"A key/token and REST endpoint should \n                be provided to invoke the endpoint\"\"\"\n            )\n        self.endpoint_url = endpoint_url\n        self.endpoint_api_key = endpoint_api_key\n        self.deployment_name = deployment_name\n[docs]    def call(self, body: bytes, **kwargs: Any) -> bytes:\n        \"\"\"call.\"\"\"\n        # The azureml-model-deployment header will force the request to go to a\n        # specific deployment. Remove this header to have the request observe the\n        # endpoint traffic rules.\n        headers = {\n            \"Content-Type\": \"application/json\",\n            \"Authorization\": (\"Bearer \" + self.endpoint_api_key),\n        }\n        if self.deployment_name != \"\":\n            headers[\"azureml-model-deployment\"] = self.deployment_name\n        req = urllib.request.Request(self.endpoint_url, body, headers)\n        response = urllib.request.urlopen(req, timeout=kwargs.get(\"timeout\", 50))\n        result = response.read()\n        return result\n[docs]class ContentFormatterBase:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html"}
{"id": "81b97065f8fd-1", "text": "result = response.read()\n        return result\n[docs]class ContentFormatterBase:\n    \"\"\"Transform request and response of AzureML endpoint to match with\n    required schema.\n    \"\"\"\n    \"\"\"\n    Example:\n        .. code-block:: python\n        \n            class ContentFormatter(ContentFormatterBase):\n                content_type = \"application/json\"\n                accepts = \"application/json\"\n                \n                def format_request_payload(\n                    self, \n                    prompt: str, \n                    model_kwargs: Dict\n                ) -> bytes:\n                    input_str = json.dumps(\n                        {\n                            \"inputs\": {\"input_string\": [prompt]}, \n                            \"parameters\": model_kwargs,\n                        }\n                    )\n                    return str.encode(input_str)\n                    \n                def format_response_payload(self, output: str) -> str:\n                    response_json = json.loads(output)\n                    return response_json[0][\"0\"]\n    \"\"\"\n    content_type: Optional[str] = \"application/json\"\n    \"\"\"The MIME type of the input data passed to the endpoint\"\"\"\n    accepts: Optional[str] = \"application/json\"\n    \"\"\"The MIME type of the response data returned from the endpoint\"\"\"\n[docs]    @staticmethod\n    def escape_special_characters(prompt: str) -> str:\n        \"\"\"Escapes any special characters in `prompt`\"\"\"\n        escape_map = {\n            \"\\\\\": \"\\\\\\\\\",\n            '\"': '\\\\\"',\n            \"\\b\": \"\\\\b\",\n            \"\\f\": \"\\\\f\",\n            \"\\n\": \"\\\\n\",\n            \"\\r\": \"\\\\r\",\n            \"\\t\": \"\\\\t\",\n        }\n        # Replace each occurrence of the specified characters with escaped versions\n        for escape_sequence, escaped_sequence in escape_map.items():\n            prompt = prompt.replace(escape_sequence, escaped_sequence)\n        return prompt", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html"}
{"id": "81b97065f8fd-2", "text": "prompt = prompt.replace(escape_sequence, escaped_sequence)\n        return prompt\n[docs]    @abstractmethod\n    def format_request_payload(self, prompt: str, model_kwargs: Dict) -> bytes:\n        \"\"\"Formats the request body according to the input schema of\n        the model. Returns bytes or seekable file like object in the\n        format specified in the content_type request header.\n        \"\"\"\n[docs]    @abstractmethod\n    def format_response_payload(self, output: bytes) -> str:\n        \"\"\"Formats the response body according to the output\n        schema of the model. Returns the data type that is\n        received from the response.\n        \"\"\"\n[docs]class GPT2ContentFormatter(ContentFormatterBase):\n    \"\"\"Content handler for GPT2\"\"\"\n[docs]    def format_request_payload(self, prompt: str, model_kwargs: Dict) -> bytes:\n        prompt = ContentFormatterBase.escape_special_characters(prompt)\n        request_payload = json.dumps(\n            {\"inputs\": {\"input_string\": [f'\"{prompt}\"']}, \"parameters\": model_kwargs}\n        )\n        return str.encode(request_payload)\n[docs]    def format_response_payload(self, output: bytes) -> str:\n        return json.loads(output)[0][\"0\"]\n[docs]class OSSContentFormatter(GPT2ContentFormatter):\n    \"\"\"Deprecated: Kept for backwards compatibility\n    Content handler for LLMs from the OSS catalog.\"\"\"\n    content_formatter: Any = None\n[docs]    def __init__(self) -> None:\n        super().__init__()\n        warnings.warn(\n            \"\"\"`OSSContentFormatter` will be deprecated in the future. \n                      Please use `GPT2ContentFormatter` instead.  \n                      \"\"\"\n        )\n[docs]class HFContentFormatter(ContentFormatterBase):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html"}
{"id": "81b97065f8fd-3", "text": "\"\"\"\n        )\n[docs]class HFContentFormatter(ContentFormatterBase):\n    \"\"\"Content handler for LLMs from the HuggingFace catalog.\"\"\"\n[docs]    def format_request_payload(self, prompt: str, model_kwargs: Dict) -> bytes:\n        ContentFormatterBase.escape_special_characters(prompt)\n        request_payload = json.dumps(\n            {\"inputs\": [f'\"{prompt}\"'], \"parameters\": model_kwargs}\n        )\n        return str.encode(request_payload)\n[docs]    def format_response_payload(self, output: bytes) -> str:\n        return json.loads(output)[0][\"generated_text\"]\n[docs]class DollyContentFormatter(ContentFormatterBase):\n    \"\"\"Content handler for the Dolly-v2-12b model\"\"\"\n[docs]    def format_request_payload(self, prompt: str, model_kwargs: Dict) -> bytes:\n        prompt = ContentFormatterBase.escape_special_characters(prompt)\n        request_payload = json.dumps(\n            {\n                \"input_data\": {\"input_string\": [f'\"{prompt}\"']},\n                \"parameters\": model_kwargs,\n            }\n        )\n        return str.encode(request_payload)\n[docs]    def format_response_payload(self, output: bytes) -> str:\n        return json.loads(output)[0]\n[docs]class LlamaContentFormatter(ContentFormatterBase):\n    \"\"\"Content formatter for LLaMa\"\"\"\n[docs]    def format_request_payload(self, prompt: str, model_kwargs: Dict) -> bytes:\n        \"\"\"Formats the request according to the chosen api\"\"\"\n        prompt = ContentFormatterBase.escape_special_characters(prompt)\n        request_payload = json.dumps(\n            {\n                \"input_data\": {\n                    \"input_string\": [f'\"{prompt}\"'],\n                    \"parameters\": model_kwargs,\n                }\n            }\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html"}
{"id": "81b97065f8fd-4", "text": "\"parameters\": model_kwargs,\n                }\n            }\n        )\n        return str.encode(request_payload)\n[docs]    def format_response_payload(self, output: bytes) -> str:\n        \"\"\"Formats response\"\"\"\n        return json.loads(output)[0][\"0\"]\n[docs]class AzureMLOnlineEndpoint(LLM, BaseModel):\n    \"\"\"Azure ML Online Endpoint models.\n    Example:\n        .. code-block:: python\n            azure_llm = AzureMLOnlineEndpoint(\n                endpoint_url=\"https://<your-endpoint>.<your_region>.inference.ml.azure.com/score\",\n                endpoint_api_key=\"my-api-key\",\n                content_formatter=content_formatter,\n            )\n    \"\"\"  # noqa: E501\n    endpoint_url: str = \"\"\n    \"\"\"URL of pre-existing Endpoint. Should be passed to constructor or specified as \n        env var `AZUREML_ENDPOINT_URL`.\"\"\"\n    endpoint_api_key: str = \"\"\n    \"\"\"Authentication Key for Endpoint. Should be passed to constructor or specified as\n        env var `AZUREML_ENDPOINT_API_KEY`.\"\"\"\n    deployment_name: str = \"\"\n    \"\"\"Deployment Name for Endpoint. NOT REQUIRED to call endpoint. Should be passed \n        to constructor or specified as env var `AZUREML_DEPLOYMENT_NAME`.\"\"\"\n    http_client: Any = None  #: :meta private:\n    content_formatter: Any = None\n    \"\"\"The content formatter that provides an input and output\n    transform function to handle formats between the LLM and\n    the endpoint\"\"\"\n    model_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    @validator(\"http_client\", always=True, allow_reuse=True)\n    @classmethod\n    def validate_client(cls, field_value: Any, values: Dict) -> AzureMLEndpointClient:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html"}
{"id": "81b97065f8fd-5", "text": "\"\"\"Validate that api key and python package exists in environment.\"\"\"\n        endpoint_key = get_from_dict_or_env(\n            values, \"endpoint_api_key\", \"AZUREML_ENDPOINT_API_KEY\"\n        )\n        endpoint_url = get_from_dict_or_env(\n            values, \"endpoint_url\", \"AZUREML_ENDPOINT_URL\"\n        )\n        deployment_name = get_from_dict_or_env(\n            values, \"deployment_name\", \"AZUREML_DEPLOYMENT_NAME\", \"\"\n        )\n        http_client = AzureMLEndpointClient(endpoint_url, endpoint_key, deployment_name)\n        return http_client\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {\n            **{\"deployment_name\": self.deployment_name},\n            **{\"model_kwargs\": _model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"azureml_endpoint\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to an AzureML Managed Online endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = azureml_model(\"Tell me a joke.\")\n        \"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        request_payload = self.content_formatter.format_request_payload(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html"}
{"id": "81b97065f8fd-6", "text": "request_payload = self.content_formatter.format_request_payload(\n            prompt, _model_kwargs\n        )\n        response_payload = self.http_client.call(request_payload, **kwargs)\n        generated_text = self.content_formatter.format_response_payload(\n            response_payload\n        )\n        return generated_text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html"}
{"id": "961c0eb8f5f8-0", "text": "Source code for langchain.llms.minimax\n\"\"\"Wrapper around Minimax APIs.\"\"\"\nfrom __future__ import annotations\nimport logging\nfrom typing import (\n    Any,\n    Dict,\n    List,\n    Optional,\n)\nimport requests\nfrom langchain.callbacks.manager import (\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import BaseModel, Field, root_validator\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\nclass _MinimaxEndpointClient(BaseModel):\n    \"\"\"An API client that talks to a Minimax llm endpoint.\"\"\"\n    host: str\n    group_id: str\n    api_key: str\n    api_url: str\n    @root_validator(pre=True, allow_reuse=True)\n    def set_api_url(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        if \"api_url\" not in values:\n            host = values[\"host\"]\n            group_id = values[\"group_id\"]\n            api_url = f\"{host}/v1/text/chatcompletion?GroupId={group_id}\"\n            values[\"api_url\"] = api_url\n        return values\n    def post(self, request: Any) -> Any:\n        headers = {\"Authorization\": f\"Bearer {self.api_key}\"}\n        response = requests.post(self.api_url, headers=headers, json=request)\n        # TODO: error handling and automatic retries\n        if not response.ok:\n            raise ValueError(f\"HTTP {response.status_code} error: {response.text}\")\n        if response.json()[\"base_resp\"][\"status_code\"] > 0:\n            raise ValueError(\n                f\"API {response.json()['base_resp']['status_code']}\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/minimax.html"}
{"id": "961c0eb8f5f8-1", "text": "f\"API {response.json()['base_resp']['status_code']}\"\n                f\" error: {response.json()['base_resp']['status_msg']}\"\n            )\n        return response.json()[\"reply\"]\n[docs]class MinimaxCommon(BaseModel):\n    \"\"\"Common parameters for Minimax large language models.\"\"\"\n    _client: Any = None\n    model: str = \"abab5.5-chat\"\n    \"\"\"Model name to use.\"\"\"\n    max_tokens: int = 256\n    \"\"\"Denotes the number of tokens to predict per generation.\"\"\"\n    temperature: float = 0.7\n    \"\"\"A non-negative float that tunes the degree of randomness in generation.\"\"\"\n    top_p: float = 0.95\n    \"\"\"Total probability mass of tokens to consider at each step.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not explicitly specified.\"\"\"\n    minimax_api_host: Optional[str] = None\n    minimax_group_id: Optional[str] = None\n    minimax_api_key: Optional[str] = None\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"minimax_api_key\"] = get_from_dict_or_env(\n            values, \"minimax_api_key\", \"MINIMAX_API_KEY\"\n        )\n        values[\"minimax_group_id\"] = get_from_dict_or_env(\n            values, \"minimax_group_id\", \"MINIMAX_GROUP_ID\"\n        )\n        # Get custom api url from environment.\n        values[\"minimax_api_host\"] = get_from_dict_or_env(\n            values,\n            \"minimax_api_host\",\n            \"MINIMAX_API_HOST\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/minimax.html"}
{"id": "961c0eb8f5f8-2", "text": "\"minimax_api_host\",\n            \"MINIMAX_API_HOST\",\n            default=\"https://api.minimax.chat\",\n        )\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling OpenAI API.\"\"\"\n        return {\n            \"model\": self.model,\n            \"tokens_to_generate\": self.max_tokens,\n            \"temperature\": self.temperature,\n            \"top_p\": self.top_p,\n            **self.model_kwargs,\n        }\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model\": self.model}, **self._default_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"minimax\"\n    def __init__(self, **data: Any):\n        super().__init__(**data)\n        self._client = _MinimaxEndpointClient(\n            host=self.minimax_api_host,\n            api_key=self.minimax_api_key,\n            group_id=self.minimax_group_id,\n        )\n[docs]class Minimax(MinimaxCommon, LLM):\n    \"\"\"Wrapper around Minimax large language models.\n    To use, you should have the environment variable\n    ``MINIMAX_API_KEY`` and ``MINIMAX_GROUP_ID`` set with your API key,\n    or pass them as a named parameter to the constructor.\n    Example:\n     . code-block:: python\n         from langchain.llms.minimax import Minimax\n         minimax = Minimax(model=\"<model_name>\", minimax_api_key=\"my-api-key\",\n          minimax_group_id=\"my-group-id\")\n    \"\"\"\n    def _call(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/minimax.html"}
{"id": "961c0eb8f5f8-3", "text": "\"\"\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        r\"\"\"Call out to Minimax's completion endpoint to chat\n        Args:\n            prompt: The prompt to pass into the model.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = minimax(\"Tell me a joke.\")\n        \"\"\"\n        request = self._default_params\n        request[\"messages\"] = [{\"sender_type\": \"USER\", \"text\": prompt}]\n        request.update(kwargs)\n        text = self._client.post(request)\n        if stop is not None:\n            # This is required since the stop tokens\n            # are not enforced by the model parameters\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/minimax.html"}
{"id": "8d42d338d2a0-0", "text": "Source code for langchain.llms.xinference\nfrom typing import TYPE_CHECKING, Any, Dict, Generator, List, Mapping, Optional, Union\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nif TYPE_CHECKING:\n    from xinference.client import RESTfulChatModelHandle, RESTfulGenerateModelHandle\n    from xinference.model.llm.core import LlamaCppGenerateConfig\n[docs]class Xinference(LLM):\n    \"\"\"Wrapper for accessing Xinference's large-scale model inference service.\n    To use, you should have the xinference library installed:\n    .. code-block:: bash\n       pip install \"xinference[all]\"\n    Check out: https://github.com/xorbitsai/inference\n    To run, you need to start a Xinference supervisor on one server and Xinference workers on the other servers\n    Example:\n        To start a local instance of Xinference, run\n        .. code-block:: bash\n           $ xinference\n        You can also deploy Xinference in a distributed cluster. Here are the steps:\n        Starting the supervisor:\n        .. code-block:: bash\n           $ xinference-supervisor\n        Starting the worker:\n        .. code-block:: bash\n           $ xinference-worker\n    Then, launch a model using command line interface (CLI).\n    Example:\n    .. code-block:: bash\n       $ xinference launch -n orca -s 3 -q q4_0\n    It will return a model UID. Then, you can use Xinference with LangChain.\n    Example:\n    .. code-block:: python\n        from langchain.llms import Xinference\n        llm = Xinference(\n            server_url=\"http://0.0.0.0:9997\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/xinference.html"}
{"id": "8d42d338d2a0-1", "text": "server_url=\"http://0.0.0.0:9997\",\n            model_uid = {model_uid} # replace model_uid with the model UID return from launching the model\n        )\n        llm(\n            prompt=\"Q: where can we visit in the capital of France? A:\",\n            generate_config={\"max_tokens\": 1024, \"stream\": True},\n        )\n    To view all the supported builtin models, run:\n    .. code-block:: bash\n        $ xinference list --all\n    \"\"\"  # noqa: E501\n    client: Any\n    server_url: Optional[str]\n    \"\"\"URL of the xinference server\"\"\"\n    model_uid: Optional[str]\n    \"\"\"UID of the launched model\"\"\"\n    model_kwargs: Dict[str, Any]\n    \"\"\"Keyword arguments to be passed to xinference.LLM\"\"\"\n    def __init__(\n        self,\n        server_url: Optional[str] = None,\n        model_uid: Optional[str] = None,\n        **model_kwargs: Any,\n    ):\n        try:\n            from xinference.client import RESTfulClient\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import RESTfulClient from xinference. Please install it\"\n                \" with `pip install xinference`.\"\n            ) from e\n        model_kwargs = model_kwargs or {}\n        super().__init__(\n            **{\n                \"server_url\": server_url,\n                \"model_uid\": model_uid,\n                \"model_kwargs\": model_kwargs,\n            }\n        )\n        if self.server_url is None:\n            raise ValueError(\"Please provide server URL\")\n        if self.model_uid is None:\n            raise ValueError(\"Please provide the model UID\")\n        self.client = RESTfulClient(server_url)\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/xinference.html"}
{"id": "8d42d338d2a0-2", "text": "self.client = RESTfulClient(server_url)\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"xinference\"\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"server_url\": self.server_url},\n            **{\"model_uid\": self.model_uid},\n            **{\"model_kwargs\": self.model_kwargs},\n        }\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call the xinference model and return the output.\n        Args:\n            prompt: The prompt to use for generation.\n            stop: Optional list of stop words to use when generating.\n            generate_config: Optional dictionary for the configuration used for\n                generation.\n        Returns:\n            The generated string by the model.\n        \"\"\"\n        model = self.client.get_model(self.model_uid)\n        generate_config: \"LlamaCppGenerateConfig\" = kwargs.get(\"generate_config\", {})\n        generate_config = {**self.model_kwargs, **generate_config}\n        if stop:\n            generate_config[\"stop\"] = stop\n        if generate_config and generate_config.get(\"stream\"):\n            combined_text_output = \"\"\n            for token in self._stream_generate(\n                model=model,\n                prompt=prompt,\n                run_manager=run_manager,\n                generate_config=generate_config,\n            ):\n                combined_text_output += token\n            return combined_text_output\n        else:\n            completion = model.generate(prompt=prompt, generate_config=generate_config)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/xinference.html"}
{"id": "8d42d338d2a0-3", "text": "else:\n            completion = model.generate(prompt=prompt, generate_config=generate_config)\n            return completion[\"choices\"][0][\"text\"]\n    def _stream_generate(\n        self,\n        model: Union[\"RESTfulGenerateModelHandle\", \"RESTfulChatModelHandle\"],\n        prompt: str,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        generate_config: Optional[\"LlamaCppGenerateConfig\"] = None,\n    ) -> Generator[str, None, None]:\n        \"\"\"\n        Args:\n            prompt: The prompt to use for generation.\n            model: The model used for generation.\n            stop: Optional list of stop words to use when generating.\n            generate_config: Optional dictionary for the configuration used for\n                generation.\n        Yields:\n            A string token.\n        \"\"\"\n        streaming_response = model.generate(\n            prompt=prompt, generate_config=generate_config\n        )\n        for chunk in streaming_response:\n            if isinstance(chunk, dict):\n                choices = chunk.get(\"choices\", [])\n                if choices:\n                    choice = choices[0]\n                    if isinstance(choice, dict):\n                        token = choice.get(\"text\", \"\")\n                        log_probs = choice.get(\"logprobs\")\n                        if run_manager:\n                            run_manager.on_llm_new_token(\n                                token=token, verbose=self.verbose, log_probs=log_probs\n                            )\n                        yield token", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/xinference.html"}
{"id": "b3a209a7cd08-0", "text": "Source code for langchain.llms.together\n\"\"\"Wrapper around Together AI's Completion API.\"\"\"\nimport logging\nfrom typing import Any, Dict, List, Optional\nfrom aiohttp import ClientSession\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utilities.requests import Requests\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class Together(LLM):\n    \"\"\"Wrapper around Together AI models.\n    To use, you'll need an API key which you can find here:\n    https://api.together.xyz/settings/api-keys. This can be passed in as init param\n    ``together_api_key`` or set as environment variable ``TOGETHER_API_KEY``.\n    Together AI API reference: https://docs.together.ai/reference/inference\n    \"\"\"\n    base_url: str = \"https://api.together.xyz/inference\"\n    \"\"\"Base inference API URL.\"\"\"\n    together_api_key: str\n    \"\"\"Together AI API key. Get it here: https://api.together.xyz/settings/api-keys\"\"\"\n    model: str\n    \"\"\"Model name. Available models listed here: \n        https://docs.together.ai/docs/inference-models\n    \"\"\"\n    temperature: Optional[float] = None\n    \"\"\"Model temperature.\"\"\"\n    top_p: Optional[float] = None\n    \"\"\"Used to dynamically adjust the number of choices for each predicted token based \n        on the cumulative probabilities. A value of 1 will always yield the same \n        output. A temperature less than 1 favors more correctness and is appropriate \n        for question answering or summarization. A value greater than 1 introduces more", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/together.html"}
{"id": "b3a209a7cd08-1", "text": "for question answering or summarization. A value greater than 1 introduces more \n        randomness in the output.\n    \"\"\"\n    top_k: Optional[int] = None\n    \"\"\"Used to limit the number of choices for the next predicted word or token. It \n        specifies the maximum number of tokens to consider at each step, based on their \n        probability of occurrence. This technique helps to speed up the generation \n        process and can improve the quality of the generated text by focusing on the \n        most likely options.\n    \"\"\"\n    max_tokens: Optional[int] = None\n    \"\"\"The maximum number of tokens to generate.\"\"\"\n    repetition_penalty: Optional[float] = None\n    \"\"\"A number that controls the diversity of generated text by reducing the \n        likelihood of repeated sequences. Higher values decrease repetition.\n    \"\"\"\n    logprobs: Optional[int] = None\n    \"\"\"An integer that specifies how many top token log probabilities are included in \n        the response for each token generation step.\n    \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key exists in environment.\"\"\"\n        values[\"together_api_key\"] = get_from_dict_or_env(\n            values, \"together_api_key\", \"TOGETHER_API_KEY\"\n        )\n        return values\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of model.\"\"\"\n        return \"together\"\n    def _format_output(self, output: dict) -> str:\n        return output[\"output\"][\"choices\"][0][\"text\"]\n[docs]    @staticmethod\n    def get_user_agent() -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/together.html"}
{"id": "b3a209a7cd08-2", "text": "[docs]    @staticmethod\n    def get_user_agent() -> str:\n        from langchain import __version__\n        return f\"langchain/{__version__}\"\n    @property\n    def default_params(self) -> Dict[str, Any]:\n        return {\n            \"model\": self.model,\n            \"temperature\": self.temperature,\n            \"top_p\": self.top_p,\n            \"top_k\": self.top_k,\n            \"max_tokens\": self.max_tokens,\n            \"repetition_penalty\": self.repetition_penalty,\n        }\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Together's text generation endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n        Returns:\n            The string generated by the model..\n        \"\"\"\n        headers = {\n            \"Authorization\": f\"Bearer {self.together_api_key}\",\n            \"Content-Type\": \"application/json\",\n        }\n        stop_to_use = stop[0] if stop and len(stop) == 1 else stop\n        payload: Dict[str, Any] = {\n            **self.default_params,\n            \"prompt\": prompt,\n            \"stop\": stop_to_use,\n            **kwargs,\n        }\n        # filter None values to not pass them to the http payload\n        payload = {k: v for k, v in payload.items() if v is not None}\n        request = Requests(headers=headers)\n        response = request.post(url=self.base_url, data=payload)\n        if response.status_code >= 500:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/together.html"}
{"id": "b3a209a7cd08-3", "text": "if response.status_code >= 500:\n            raise Exception(f\"Together Server: Error {response.status_code}\")\n        elif response.status_code >= 400:\n            raise ValueError(f\"Together received an invalid payload: {response.text}\")\n        elif response.status_code != 200:\n            raise Exception(\n                f\"Together returned an unexpected response with status \"\n                f\"{response.status_code}: {response.text}\"\n            )\n        data = response.json()\n        if data.get(\"status\") != \"finished\":\n            err_msg = data.get(\"error\", \"Undefined Error\")\n            raise Exception(err_msg)\n        output = self._format_output(data)\n        return output\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call Together model to get predictions based on the prompt.\n        Args:\n            prompt: The prompt to pass into the model.\n        Returns:\n            The string generated by the model.\n        \"\"\"\n        headers = {\n            \"Authorization\": f\"Bearer {self.together_api_key}\",\n            \"Content-Type\": \"application/json\",\n        }\n        stop_to_use = stop[0] if stop and len(stop) == 1 else stop\n        payload: Dict[str, Any] = {\n            **self.default_params,\n            \"prompt\": prompt,\n            \"stop\": stop_to_use,\n            **kwargs,\n        }\n        # filter None values to not pass them to the http payload\n        payload = {k: v for k, v in payload.items() if v is not None}\n        async with ClientSession() as session:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/together.html"}
{"id": "b3a209a7cd08-4", "text": "async with ClientSession() as session:\n            async with session.post(\n                self.base_url, json=payload, headers=headers\n            ) as response:\n                if response.status >= 500:\n                    raise Exception(f\"Together Server: Error {response.status}\")\n                elif response.status >= 400:\n                    raise ValueError(\n                        f\"Together received an invalid payload: {response.text}\"\n                    )\n                elif response.status != 200:\n                    raise Exception(\n                        f\"Together returned an unexpected response with status \"\n                        f\"{response.status}: {response.text}\"\n                    )\n                response_json = await response.json()\n                if response_json.get(\"status\") != \"finished\":\n                    err_msg = response_json.get(\"error\", \"Undefined Error\")\n                    raise Exception(err_msg)\n                output = self._format_output(response_json)\n                return output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/together.html"}
{"id": "1e22e36802e2-0", "text": "Source code for langchain.llms.bittensor\nimport http.client\nimport json\nimport ssl\nfrom typing import Any, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\n[docs]class NIBittensorLLM(LLM):\n    \"\"\"NIBittensor LLMs\n    NIBittensorLLM is created by Neural Internet (https://neuralinternet.ai/),\n    powered by Bittensor, a decentralized network full of different AI models.\n    To analyze API_KEYS and logs of your usage visit\n        https://api.neuralinternet.ai/api-keys\n        https://api.neuralinternet.ai/logs\n    Example:\n        .. code-block:: python\n            from langchain.llms import NIBittensorLLM\n            llm = NIBittensorLLM()\n    \"\"\"\n    system_prompt: Optional[str]\n    \"\"\"Provide system prompt that you want to supply it to model before every prompt\"\"\"\n    top_responses: Optional[int] = 0\n    \"\"\"Provide top_responses to get Top N miner responses on one request.May get delayed\n        Don't use in Production\"\"\"\n    @property\n    def _llm_type(self) -> str:\n        return \"NIBittensorLLM\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"\n        Wrapper around the bittensor top miner models. Its built by Neural Internet.\n        Call the Neural Internet's BTVEP Server and return the output.\n        Parameters (optional):\n            system_prompt(str): A system prompt defining how your model should respond.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bittensor.html"}
{"id": "1e22e36802e2-1", "text": "system_prompt(str): A system prompt defining how your model should respond.\n            top_responses(int): Total top miner responses to retrieve from Bittensor\n                protocol.\n        Return:\n            The generated response(s).\n        Example:\n            .. code-block:: python\n                from langchain.llms import NIBittensorLLM\n                llm = NIBittensorLLM(system_prompt=\"Act like you are programmer with \\\n                5+ years of experience.\")\n        \"\"\"\n        # Creating HTTPS connection with SSL\n        context = ssl.create_default_context()\n        context.check_hostname = True\n        conn = http.client.HTTPSConnection(\"test.neuralinternet.ai\", context=context)\n        # Sanitizing User Input before passing to API.\n        if isinstance(self.top_responses, int):\n            top_n = min(100, self.top_responses)\n        else:\n            top_n = 0\n        default_prompt = \"You are an assistant which is created by Neural Internet(NI) \\\n            in decentralized network named as a Bittensor.\"\n        if self.system_prompt is None:\n            system_prompt = (\n                default_prompt\n                + \" Your task is to provide accurate response based on user prompt\"\n            )\n        else:\n            system_prompt = default_prompt + str(self.system_prompt)\n        # Retrieving API KEY to pass into header of each request\n        conn.request(\"GET\", \"/admin/api-keys/\")\n        api_key_response = conn.getresponse()\n        api_keys_data = (\n            api_key_response.read().decode(\"utf-8\").replace(\"\\n\", \"\").replace(\"\\t\", \"\")\n        )\n        api_keys_json = json.loads(api_keys_data)\n        api_key = api_keys_json[0][\"api_key\"]\n        # Creating Header and getting top benchmark miner uids\n        headers = {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bittensor.html"}
{"id": "1e22e36802e2-2", "text": "# Creating Header and getting top benchmark miner uids\n        headers = {\n            \"Content-Type\": \"application/json\",\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Endpoint-Version\": \"2023-05-19\",\n        }\n        conn.request(\"GET\", \"/top_miner_uids\", headers=headers)\n        miner_response = conn.getresponse()\n        miner_data = (\n            miner_response.read().decode(\"utf-8\").replace(\"\\n\", \"\").replace(\"\\t\", \"\")\n        )\n        uids = json.loads(miner_data)\n        # Condition for benchmark miner response\n        if isinstance(uids, list) and uids and not top_n:\n            for uid in uids:\n                try:\n                    payload = json.dumps(\n                        {\n                            \"uids\": [uid],\n                            \"messages\": [\n                                {\"role\": \"system\", \"content\": system_prompt},\n                                {\"role\": \"user\", \"content\": prompt},\n                            ],\n                        }\n                    )\n                    conn.request(\"POST\", \"/chat\", payload, headers)\n                    init_response = conn.getresponse()\n                    init_data = (\n                        init_response.read()\n                        .decode(\"utf-8\")\n                        .replace(\"\\n\", \"\")\n                        .replace(\"\\t\", \"\")\n                    )\n                    init_json = json.loads(init_data)\n                    if \"choices\" not in init_json:\n                        continue\n                    reply = init_json[\"choices\"][0][\"message\"][\"content\"]\n                    conn.close()\n                    return reply\n                except Exception:\n                    continue\n        # For top miner based on bittensor response\n        try:\n            payload = json.dumps(\n                {\n                    \"top_n\": top_n,\n                    \"messages\": [\n                        {\"role\": \"system\", \"content\": system_prompt},", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bittensor.html"}
{"id": "1e22e36802e2-3", "text": "\"messages\": [\n                        {\"role\": \"system\", \"content\": system_prompt},\n                        {\"role\": \"user\", \"content\": prompt},\n                    ],\n                }\n            )\n            conn.request(\"POST\", \"/chat\", payload, headers)\n            response = conn.getresponse()\n            utf_string = (\n                response.read().decode(\"utf-8\").replace(\"\\n\", \"\").replace(\"\\t\", \"\")\n            )\n            if top_n:\n                conn.close()\n                return utf_string\n            json_resp = json.loads(utf_string)\n            reply = json_resp[\"choices\"][0][\"message\"][\"content\"]\n            conn.close()\n            return reply\n        except Exception as e:\n            conn.request(\"GET\", f\"/error_msg?e={e}&p={prompt}\", headers=headers)\n            return \"Sorry I am unable to provide response now, Please try again later.\"\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"system_prompt\": self.system_prompt,\n            \"top_responses\": self.top_responses,\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bittensor.html"}
{"id": "b919950053b7-0", "text": "Source code for langchain.llms.deepinfra\nimport json\nfrom typing import Any, AsyncIterator, Dict, Iterator, List, Mapping, Optional\nimport aiohttp\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM, GenerationChunk\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utilities.requests import Requests\nfrom langchain.utils import get_from_dict_or_env\nDEFAULT_MODEL_ID = \"google/flan-t5-xl\"\n[docs]class DeepInfra(LLM):\n    \"\"\"DeepInfra models.\n    To use, you should have the environment variable ``DEEPINFRA_API_TOKEN``\n    set with your API token, or pass it as a named parameter to the\n    constructor.\n    Only supports `text-generation` and `text2text-generation` for now.\n    Example:\n        .. code-block:: python\n            from langchain.llms import DeepInfra\n            di = DeepInfra(model_id=\"google/flan-t5-xl\",\n                                deepinfra_api_token=\"my-api-key\")\n    \"\"\"\n    model_id: str = DEFAULT_MODEL_ID\n    model_kwargs: Optional[Dict] = None\n    deepinfra_api_token: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        deepinfra_api_token = get_from_dict_or_env(\n            values, \"deepinfra_api_token\", \"DEEPINFRA_API_TOKEN\"\n        )\n        values[\"deepinfra_api_token\"] = deepinfra_api_token\n        return values\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html"}
{"id": "b919950053b7-1", "text": "return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"model_id\": self.model_id},\n            **{\"model_kwargs\": self.model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"deepinfra\"\n    def _url(self) -> str:\n        return f\"https://api.deepinfra.com/v1/inference/{self.model_id}\"\n    def _headers(self) -> Dict:\n        return {\n            \"Authorization\": f\"bearer {self.deepinfra_api_token}\",\n            \"Content-Type\": \"application/json\",\n        }\n    def _body(self, prompt: str, kwargs: Any) -> Dict:\n        model_kwargs = self.model_kwargs or {}\n        model_kwargs = {**model_kwargs, **kwargs}\n        return {\n            \"input\": prompt,\n            **model_kwargs,\n        }\n    def _handle_status(self, code: int, text: Any) -> None:\n        if code >= 500:\n            raise Exception(f\"DeepInfra Server: Error {code}\")\n        elif code >= 400:\n            raise ValueError(f\"DeepInfra received an invalid payload: {text}\")\n        elif code != 200:\n            raise Exception(\n                f\"DeepInfra returned an unexpected response with status \"\n                f\"{code}: {text}\"\n            )\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html"}
{"id": "b919950053b7-2", "text": "**kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to DeepInfra's inference API endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = di(\"Tell me a joke.\")\n        \"\"\"\n        request = Requests(headers=self._headers())\n        response = request.post(url=self._url(), data=self._body(prompt, kwargs))\n        self._handle_status(response.status_code, response.text)\n        data = response.json()\n        return data[\"results\"][0][\"generated_text\"]\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        request = Requests(headers=self._headers())\n        async with request.apost(\n            url=self._url(), data=self._body(prompt, kwargs)\n        ) as response:\n            self._handle_status(response.status, response.text)\n            data = await response.json()\n            return data[\"results\"][0][\"generated_text\"]\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        request = Requests(headers=self._headers())\n        response = request.post(\n            url=self._url(), data=self._body(prompt, {**kwargs, \"stream\": True})\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html"}
{"id": "b919950053b7-3", "text": ")\n        self._handle_status(response.status_code, response.text)\n        for line in _parse_stream(response.iter_lines()):\n            chunk = _handle_sse_line(line)\n            if chunk:\n                yield chunk\n                if run_manager:\n                    run_manager.on_llm_new_token(chunk.text)\n    async def _astream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[GenerationChunk]:\n        request = Requests(headers=self._headers())\n        async with request.apost(\n            url=self._url(), data=self._body(prompt, {**kwargs, \"stream\": True})\n        ) as response:\n            self._handle_status(response.status, response.text)\n            async for line in _parse_stream_async(response.content):\n                chunk = _handle_sse_line(line)\n                if chunk:\n                    yield chunk\n                    if run_manager:\n                        await run_manager.on_llm_new_token(chunk.text)\ndef _parse_stream(rbody: Iterator[bytes]) -> Iterator[str]:\n    for line in rbody:\n        _line = _parse_stream_helper(line)\n        if _line is not None:\n            yield _line\nasync def _parse_stream_async(rbody: aiohttp.StreamReader) -> AsyncIterator[str]:\n    async for line in rbody:\n        _line = _parse_stream_helper(line)\n        if _line is not None:\n            yield _line\ndef _parse_stream_helper(line: bytes) -> Optional[str]:\n    if line and line.startswith(b\"data:\"):\n        if line.startswith(b\"data: \"):\n            # SSE event may be valid when it contain whitespace", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html"}
{"id": "b919950053b7-4", "text": "# SSE event may be valid when it contain whitespace\n            line = line[len(b\"data: \") :]\n        else:\n            line = line[len(b\"data:\") :]\n        if line.strip() == b\"[DONE]\":\n            # return here will cause GeneratorExit exception in urllib3\n            # and it will close http connection with TCP Reset\n            return None\n        else:\n            return line.decode(\"utf-8\")\n    return None\ndef _handle_sse_line(line: str) -> Optional[GenerationChunk]:\n    try:\n        obj = json.loads(line)\n        return GenerationChunk(\n            text=obj.get(\"token\", {}).get(\"text\"),\n        )\n    except Exception:\n        return None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html"}
{"id": "9924e9867f8f-0", "text": "Source code for langchain.llms.titan_takeoff_pro\nfrom typing import Any, Iterator, List, Mapping, Optional\nimport requests\nfrom requests.exceptions import ConnectionError\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.schema.output import GenerationChunk\n[docs]class TitanTakeoffPro(LLM):\n    base_url: Optional[str] = \"http://localhost:3000\"\n    \"\"\"Specifies the baseURL to use for the Titan Takeoff Pro API.\n    Default = http://localhost:3000.\n    \"\"\"\n    max_new_tokens: Optional[int] = None\n    \"\"\"Maximum tokens generated.\"\"\"\n    min_new_tokens: Optional[int] = None\n    \"\"\"Minimum tokens generated.\"\"\"\n    sampling_topk: Optional[int] = None\n    \"\"\"Sample predictions from the top K most probable candidates.\"\"\"\n    sampling_topp: Optional[float] = None\n    \"\"\"Sample from predictions whose cumulative probability exceeds this value.\n    \"\"\"\n    sampling_temperature: Optional[float] = None\n    \"\"\"Sample with randomness. Bigger temperatures are associated with \n    more randomness and 'creativity'.\n    \"\"\"\n    repetition_penalty: Optional[float] = None\n    \"\"\"Penalise the generation of tokens that have been generated before. \n    Set to > 1 to penalize.\n    \"\"\"\n    regex_string: Optional[str] = None\n    \"\"\"A regex string for constrained generation.\"\"\"\n    no_repeat_ngram_size: Optional[int] = None\n    \"\"\"Prevent repetitions of ngrams of this size. Default = 0 (turned off).\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the output. Default = False.\"\"\"\n    @property\n    def _default_params(self) -> Mapping[str, Any]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff_pro.html"}
{"id": "9924e9867f8f-1", "text": "@property\n    def _default_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the default parameters for calling Titan Takeoff Server (Pro).\"\"\"\n        return {\n            **(\n                {\"regex_string\": self.regex_string}\n                if self.regex_string is not None\n                else {}\n            ),\n            **(\n                {\"sampling_temperature\": self.sampling_temperature}\n                if self.sampling_temperature is not None\n                else {}\n            ),\n            **(\n                {\"sampling_topp\": self.sampling_topp}\n                if self.sampling_topp is not None\n                else {}\n            ),\n            **(\n                {\"repetition_penalty\": self.repetition_penalty}\n                if self.repetition_penalty is not None\n                else {}\n            ),\n            **(\n                {\"max_new_tokens\": self.max_new_tokens}\n                if self.max_new_tokens is not None\n                else {}\n            ),\n            **(\n                {\"min_new_tokens\": self.min_new_tokens}\n                if self.min_new_tokens is not None\n                else {}\n            ),\n            **(\n                {\"sampling_topk\": self.sampling_topk}\n                if self.sampling_topk is not None\n                else {}\n            ),\n            **(\n                {\"no_repeat_ngram_size\": self.no_repeat_ngram_size}\n                if self.no_repeat_ngram_size is not None\n                else {}\n            ),\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"titan_takeoff_pro\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff_pro.html"}
{"id": "9924e9867f8f-2", "text": "**kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Titan Takeoff (Pro) generate endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                prompt = \"What is the capital of the United Kingdom?\"\n                response = model(prompt)\n        \"\"\"\n        try:\n            if self.streaming:\n                text_output = \"\"\n                for chunk in self._stream(\n                    prompt=prompt,\n                    stop=stop,\n                    run_manager=run_manager,\n                ):\n                    text_output += chunk.text\n                return text_output\n            url = f\"{self.base_url}/generate\"\n            params = {\"text\": prompt, **self._default_params}\n            response = requests.post(url, json=params)\n            response.raise_for_status()\n            response.encoding = \"utf-8\"\n            text = \"\"\n            if \"text\" in response.json():\n                text = response.json()[\"text\"]\n                text = text.replace(\"</s>\", \"\")\n            else:\n                raise ValueError(\"Something went wrong.\")\n            if stop is not None:\n                text = enforce_stop_tokens(text, stop)\n            return text\n        except ConnectionError:\n            raise ConnectionError(\n                \"Could not connect to Titan Takeoff (Pro) server. \\\n                Please make sure that the server is running.\"\n            )\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff_pro.html"}
{"id": "9924e9867f8f-3", "text": "**kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        \"\"\"Call out to Titan Takeoff (Pro) stream endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Yields:\n            A dictionary like object containing a string token.\n        Example:\n            .. code-block:: python\n                prompt = \"What is the capital of the United Kingdom?\"\n                response = model(prompt)\n        \"\"\"\n        url = f\"{self.base_url}/generate_stream\"\n        params = {\"text\": prompt, **self._default_params}\n        response = requests.post(url, json=params, stream=True)\n        response.encoding = \"utf-8\"\n        buffer = \"\"\n        for text in response.iter_content(chunk_size=1, decode_unicode=True):\n            buffer += text\n            if \"data:\" in buffer:\n                # Remove the first instance of \"data:\" from the buffer.\n                if buffer.startswith(\"data:\"):\n                    buffer = \"\"\n                if len(buffer.split(\"data:\", 1)) == 2:\n                    content, _ = buffer.split(\"data:\", 1)\n                    buffer = content.rstrip(\"\\n\")\n                # Trim the buffer to only have content after the \"data:\" part.\n                if buffer:  # Ensure that there's content to process.\n                    chunk = GenerationChunk(text=buffer)\n                    buffer = \"\"  # Reset buffer for the next set of data.\n                    yield chunk\n                    if run_manager:\n                        run_manager.on_llm_new_token(token=chunk.text)\n        # Yield any remaining content in the buffer.\n        if buffer:\n            chunk = GenerationChunk(text=buffer.replace(\"</s>\", \"\"))\n            yield chunk", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff_pro.html"}
{"id": "9924e9867f8f-4", "text": "chunk = GenerationChunk(text=buffer.replace(\"</s>\", \"\"))\n            yield chunk\n            if run_manager:\n                run_manager.on_llm_new_token(token=chunk.text)\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\"base_url\": self.base_url, **{}, **self._default_params}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff_pro.html"}
{"id": "e6b77633a886-0", "text": "Source code for langchain.llms.yandex\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.load.serializable import Serializable\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.utils import get_from_dict_or_env\nclass _BaseYandexGPT(Serializable):\n    iam_token: str = \"\"\n    \"\"\"Yandex Cloud IAM token for service account\n    with the `ai.languageModels.user` role\"\"\"\n    api_key: str = \"\"\n    \"\"\"Yandex Cloud Api Key for service account\n    with the `ai.languageModels.user` role\"\"\"\n    model_name: str = \"general\"\n    \"\"\"Model name to use.\"\"\"\n    temperature: float = 0.6\n    \"\"\"What sampling temperature to use.\n    Should be a double number between 0 (inclusive) and 1 (inclusive).\"\"\"\n    max_tokens: int = 7400\n    \"\"\"Sets the maximum limit on the total number of tokens\n    used for both the input prompt and the generated response.\n    Must be greater than zero and not exceed 7400 tokens.\"\"\"\n    stop: Optional[List[str]] = None\n    \"\"\"Sequences when completion generation will stop.\"\"\"\n    url: str = \"llm.api.cloud.yandex.net:443\"\n    \"\"\"The url of the API.\"\"\"\n    @property\n    def _llm_type(self) -> str:\n        return \"yandex_gpt\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that iam token exists in environment.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/yandex.html"}
{"id": "e6b77633a886-1", "text": "\"\"\"Validate that iam token exists in environment.\"\"\"\n        iam_token = get_from_dict_or_env(values, \"iam_token\", \"YC_IAM_TOKEN\", \"\")\n        values[\"iam_token\"] = iam_token\n        api_key = get_from_dict_or_env(values, \"api_key\", \"YC_API_KEY\", \"\")\n        values[\"api_key\"] = api_key\n        if api_key == \"\" and iam_token == \"\":\n            raise ValueError(\"Either 'YC_API_KEY' or 'YC_IAM_TOKEN' must be provided.\")\n        return values\n[docs]class YandexGPT(_BaseYandexGPT, LLM):\n    \"\"\"Yandex large language models.\n    To use, you should have the ``yandexcloud`` python package installed.\n    There are two authentication options for the service account\n    with the ``ai.languageModels.user`` role:\n        - You can specify the token in a constructor parameter `iam_token`\n        or in an environment variable `YC_IAM_TOKEN`.\n        - You can specify the key in a constructor parameter `api_key`\n        or in an environment variable `YC_API_KEY`.\n    Example:\n        .. code-block:: python\n            from langchain.llms import YandexGPT\n            yandex_gpt = YandexGPT(iam_token=\"t1.9eu...\")\n    \"\"\"\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"model_name\": self.model_name,\n            \"temperature\": self.temperature,\n            \"max_tokens\": self.max_tokens,\n            \"stop\": self.stop,\n        }\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/yandex.html"}
{"id": "e6b77633a886-2", "text": "prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call the Yandex GPT model and return the output.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = YandexGPT(\"Tell me a joke.\")\n        \"\"\"\n        try:\n            import grpc\n            from google.protobuf.wrappers_pb2 import DoubleValue, Int64Value\n            from yandex.cloud.ai.llm.v1alpha.llm_pb2 import GenerationOptions\n            from yandex.cloud.ai.llm.v1alpha.llm_service_pb2 import InstructRequest\n            from yandex.cloud.ai.llm.v1alpha.llm_service_pb2_grpc import (\n                TextGenerationServiceStub,\n            )\n        except ImportError as e:\n            raise ImportError(\n                \"Please install YandexCloud SDK\" \" with `pip install yandexcloud`.\"\n            ) from e\n        channel_credentials = grpc.ssl_channel_credentials()\n        channel = grpc.secure_channel(self.url, channel_credentials)\n        request = InstructRequest(\n            model=self.model_name,\n            request_text=prompt,\n            generation_options=GenerationOptions(\n                temperature=DoubleValue(value=self.temperature),\n                max_tokens=Int64Value(value=self.max_tokens),\n            ),\n        )\n        stub = TextGenerationServiceStub(channel)\n        if self.iam_token:\n            metadata = ((\"authorization\", f\"Bearer {self.iam_token}\"),)\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/yandex.html"}
{"id": "e6b77633a886-3", "text": "else:\n            metadata = ((\"authorization\", f\"Api-Key {self.api_key}\"),)\n        res = stub.Instruct(request, metadata=metadata)\n        text = list(res)[0].alternatives[0].text\n        if stop is not None:\n            text = enforce_stop_tokens(text, stop)\n        return text\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Async call the Yandex GPT model and return the output.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        \"\"\"\n        try:\n            import asyncio\n            import grpc\n            from google.protobuf.wrappers_pb2 import DoubleValue, Int64Value\n            from yandex.cloud.ai.llm.v1alpha.llm_pb2 import GenerationOptions\n            from yandex.cloud.ai.llm.v1alpha.llm_service_pb2 import (\n                InstructRequest,\n                InstructResponse,\n            )\n            from yandex.cloud.ai.llm.v1alpha.llm_service_pb2_grpc import (\n                TextGenerationAsyncServiceStub,\n            )\n            from yandex.cloud.operation.operation_service_pb2 import GetOperationRequest\n            from yandex.cloud.operation.operation_service_pb2_grpc import (\n                OperationServiceStub,\n            )\n        except ImportError as e:\n            raise ImportError(\n                \"Please install YandexCloud SDK\" \" with `pip install yandexcloud`.\"\n            ) from e\n        operation_api_url = \"operation.api.cloud.yandex.net:443\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/yandex.html"}
{"id": "e6b77633a886-4", "text": "operation_api_url = \"operation.api.cloud.yandex.net:443\"\n        channel_credentials = grpc.ssl_channel_credentials()\n        async with grpc.aio.secure_channel(self.url, channel_credentials) as channel:\n            request = InstructRequest(\n                model=self.model_name,\n                request_text=prompt,\n                generation_options=GenerationOptions(\n                    temperature=DoubleValue(value=self.temperature),\n                    max_tokens=Int64Value(value=self.max_tokens),\n                ),\n            )\n            stub = TextGenerationAsyncServiceStub(channel)\n            if self.iam_token:\n                metadata = ((\"authorization\", f\"Bearer {self.iam_token}\"),)\n            else:\n                metadata = ((\"authorization\", f\"Api-Key {self.api_key}\"),)\n            operation = await stub.Instruct(request, metadata=metadata)\n            async with grpc.aio.secure_channel(\n                operation_api_url, channel_credentials\n            ) as operation_channel:\n                operation_stub = OperationServiceStub(operation_channel)\n                while not operation.done:\n                    await asyncio.sleep(1)\n                    operation_request = GetOperationRequest(operation_id=operation.id)\n                    operation = await operation_stub.Get(\n                        operation_request, metadata=metadata\n                    )\n            instruct_response = InstructResponse()\n            operation.response.Unpack(instruct_response)\n            text = instruct_response.alternatives[0].text\n            if stop is not None:\n                text = enforce_stop_tokens(text, stop)\n            return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/yandex.html"}
{"id": "c642eaca5eef-0", "text": "Source code for langchain.llms.deepsparse\n# flake8: noqa\nfrom typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Union\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.schema.output import GenerationChunk\n[docs]class DeepSparse(LLM):\n    \"\"\"Neural Magic DeepSparse LLM interface.\n    To use, you should have the ``deepsparse`` or ``deepsparse-nightly``\n    python package installed. See https://github.com/neuralmagic/deepsparse\n    This interface let's you deploy optimized LLMs straight from the\n    [SparseZoo](https://sparsezoo.neuralmagic.com/?useCase=text_generation)\n    Example:\n        .. code-block:: python\n            from langchain.llms import DeepSparse\n            llm = DeepSparse(model=\"zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base_quant-none\")\n    \"\"\"  # noqa: E501\n    pipeline: Any  #: :meta private:\n    model: str\n    \"\"\"The path to a model file or directory or the name of a SparseZoo model stub.\"\"\"\n    model_config: Optional[Dict[str, Any]] = None\n    \"\"\"Keyword arguments passed to the pipeline construction.\n    Common parameters are sequence_length, prompt_sequence_length\"\"\"\n    generation_config: Union[None, str, Dict] = None\n    \"\"\"GenerationConfig dictionary consisting of parameters used to control\n    sequences generated for each prompt. Common parameters are:\n    max_length, max_new_tokens, num_return_sequences, output_scores,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html"}
{"id": "c642eaca5eef-1", "text": "max_length, max_new_tokens, num_return_sequences, output_scores,\n    top_p, top_k, repetition_penalty.\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results, token by token.\"\"\"\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"model\": self.model,\n            \"model_config\": self.model_config,\n            \"generation_config\": self.generation_config,\n            \"streaming\": self.streaming,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"deepsparse\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that ``deepsparse`` package is installed.\"\"\"\n        try:\n            from deepsparse import Pipeline\n        except ImportError:\n            raise ImportError(\n                \"Could not import `deepsparse` package. \"\n                \"Please install it with `pip install deepsparse`\"\n            )\n        model_config = values[\"model_config\"] or {}\n        values[\"pipeline\"] = Pipeline.create(\n            task=\"text_generation\",\n            model_path=values[\"model\"],\n            **model_config,\n        )\n        return values\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Generate text from a prompt.\n        Args:\n            prompt: The prompt to generate text from.\n            stop: A list of strings to stop generation when encountered.\n        Returns:\n            The generated text.\n        Example:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html"}
{"id": "c642eaca5eef-2", "text": "Returns:\n            The generated text.\n        Example:\n            .. code-block:: python\n                from langchain.llms import DeepSparse\n                llm = DeepSparse(model=\"zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base_quant-none\")\n                llm(\"Tell me a joke.\")\n        \"\"\"\n        if self.streaming:\n            combined_output = \"\"\n            for chunk in self._stream(\n                prompt=prompt, stop=stop, run_manager=run_manager, **kwargs\n            ):\n                combined_output += chunk.text\n            text = combined_output\n        else:\n            text = (\n                self.pipeline(\n                    sequences=prompt, generation_config=self.generation_config\n                )\n                .generations[0]\n                .text\n            )\n        if stop is not None:\n            text = enforce_stop_tokens(text, stop)\n        return text\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Generate text from a prompt.\n        Args:\n            prompt: The prompt to generate text from.\n            stop: A list of strings to stop generation when encountered.\n        Returns:\n            The generated text.\n        Example:\n            .. code-block:: python\n                from langchain.llms import DeepSparse\n                llm = DeepSparse(model=\"zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base_quant-none\")\n                llm(\"Tell me a joke.\")\n        \"\"\"\n        if self.streaming:\n            combined_output = \"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html"}
{"id": "c642eaca5eef-3", "text": "\"\"\"\n        if self.streaming:\n            combined_output = \"\"\n            async for chunk in self._astream(\n                prompt=prompt, stop=stop, run_manager=run_manager, **kwargs\n            ):\n                combined_output += chunk.text\n            text = combined_output\n        else:\n            text = (\n                self.pipeline(\n                    sequences=prompt, generation_config=self.generation_config\n                )\n                .generations[0]\n                .text\n            )\n        if stop is not None:\n            text = enforce_stop_tokens(text, stop)\n        return text\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        \"\"\"Yields results objects as they are generated in real time.\n        It also calls the callback manager's on_llm_new_token event with\n        similar parameters to the OpenAI LLM class method of the same name.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            A generator representing the stream of tokens being generated.\n        Yields:\n            A dictionary like object containing a string token.\n        Example:\n            .. code-block:: python\n                from langchain.llms import DeepSparse\n                llm = DeepSparse(\n                    model=\"zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base_quant-none\",\n                    streaming=True\n                )\n                for chunk in llm.stream(\"Tell me a joke\",\n                        stop=[\"'\",\"\\n\"]):\n                    print(chunk, end='', flush=True)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html"}
{"id": "c642eaca5eef-4", "text": "stop=[\"'\",\"\\n\"]):\n                    print(chunk, end='', flush=True)\n        \"\"\"\n        inference = self.pipeline(\n            sequences=prompt, generation_config=self.generation_config, streaming=True\n        )\n        for token in inference:\n            chunk = GenerationChunk(text=token.generations[0].text)\n            yield chunk\n            if run_manager:\n                run_manager.on_llm_new_token(token=chunk.text)\n    async def _astream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[GenerationChunk]:\n        \"\"\"Yields results objects as they are generated in real time.\n        It also calls the callback manager's on_llm_new_token event with\n        similar parameters to the OpenAI LLM class method of the same name.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            A generator representing the stream of tokens being generated.\n        Yields:\n            A dictionary like object containing a string token.\n        Example:\n            .. code-block:: python\n                from langchain.llms import DeepSparse\n                llm = DeepSparse(\n                    model=\"zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base_quant-none\",\n                    streaming=True\n                )\n                for chunk in llm.stream(\"Tell me a joke\",\n                        stop=[\"'\",\"\\n\"]):\n                    print(chunk, end='', flush=True)\n        \"\"\"\n        inference = self.pipeline(\n            sequences=prompt, generation_config=self.generation_config, streaming=True\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html"}
{"id": "c642eaca5eef-5", "text": "sequences=prompt, generation_config=self.generation_config, streaming=True\n        )\n        for token in inference:\n            chunk = GenerationChunk(text=token.generations[0].text)\n            yield chunk\n            if run_manager:\n                await run_manager.on_llm_new_token(token=chunk.text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html"}
{"id": "319b845ed006-0", "text": "Source code for langchain.llms.baseten\nimport logging\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Field\nlogger = logging.getLogger(__name__)\n[docs]class Baseten(LLM):\n    \"\"\"Baseten models.\n    To use, you should have the ``baseten`` python package installed,\n    and run ``baseten.login()`` with your Baseten API key.\n    The required ``model`` param can be either a model id or model\n    version id. Using a model version ID will result in\n    slightly faster invocation.\n    Any other model parameters can also\n    be passed in with the format input={model_param: value, ...}\n    The Baseten model must accept a dictionary of input with the key\n    \"prompt\" and return a dictionary with a key \"data\" which maps\n    to a list of response strings.\n    Example:\n        .. code-block:: python\n            from langchain.llms import Baseten\n            my_model = Baseten(model=\"MODEL_ID\")\n            output = my_model(\"prompt\")\n    \"\"\"\n    model: str\n    input: Dict[str, Any] = Field(default_factory=dict)\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"model_kwargs\": self.model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of model.\"\"\"\n        return \"baseten\"\n    def _call(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html"}
{"id": "319b845ed006-1", "text": "return \"baseten\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call to Baseten deployed model endpoint.\"\"\"\n        try:\n            import baseten\n        except ImportError as exc:\n            raise ImportError(\n                \"Could not import Baseten Python package. \"\n                \"Please install it with `pip install baseten`.\"\n            ) from exc\n        # get the model and version\n        try:\n            model = baseten.deployed_model_version_id(self.model)\n            response = model.predict({\"prompt\": prompt, **kwargs})\n        except baseten.common.core.ApiError:\n            model = baseten.deployed_model_id(self.model)\n            response = model.predict({\"prompt\": prompt, **kwargs})\n        return \"\".join(response)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html"}
{"id": "463f176f76a2-0", "text": "Source code for langchain.llms.vertexai\nfrom __future__ import annotations\nfrom concurrent.futures import Executor, ThreadPoolExecutor\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    ClassVar,\n    Dict,\n    Iterator,\n    List,\n    Optional,\n    Union,\n)\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import BaseLLM, create_base_retry_decorator\nfrom langchain.pydantic_v1 import BaseModel, Field, root_validator\nfrom langchain.schema import (\n    Generation,\n    LLMResult,\n)\nfrom langchain.schema.output import GenerationChunk\nfrom langchain.utilities.vertexai import (\n    get_client_info,\n    init_vertexai,\n    raise_vertex_import_error,\n)\nif TYPE_CHECKING:\n    from google.cloud.aiplatform.gapic import (\n        PredictionServiceAsyncClient,\n        PredictionServiceClient,\n    )\n    from vertexai.language_models._language_models import (\n        TextGenerationResponse,\n        _LanguageModel,\n    )\ndef _response_to_generation(\n    response: TextGenerationResponse,\n) -> GenerationChunk:\n    \"\"\"Convert a stream response to a generation chunk.\"\"\"\n    try:\n        generation_info = {\n            \"is_blocked\": response.is_blocked,\n            \"safety_attributes\": response.safety_attributes,\n        }\n    except Exception:\n        generation_info = None\n    return GenerationChunk(text=response.text, generation_info=generation_info)\n[docs]def is_codey_model(model_name: str) -> bool:\n    \"\"\"Returns True if the model name is a Codey model.\n    Args:\n        model_name: The model name to check.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html"}
{"id": "463f176f76a2-1", "text": "Args:\n        model_name: The model name to check.\n    Returns: True if the model name is a Codey model.\n    \"\"\"\n    return \"code\" in model_name\ndef _create_retry_decorator(\n    llm: VertexAI,\n    *,\n    run_manager: Optional[\n        Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]\n    ] = None,\n) -> Callable[[Any], Any]:\n    import google.api_core\n    errors = [\n        google.api_core.exceptions.ResourceExhausted,\n        google.api_core.exceptions.ServiceUnavailable,\n        google.api_core.exceptions.Aborted,\n        google.api_core.exceptions.DeadlineExceeded,\n    ]\n    decorator = create_base_retry_decorator(\n        error_types=errors, max_retries=llm.max_retries, run_manager=run_manager\n    )\n    return decorator\n[docs]def completion_with_retry(\n    llm: VertexAI,\n    *args: Any,\n    run_manager: Optional[CallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @retry_decorator\n    def _completion_with_retry(*args: Any, **kwargs: Any) -> Any:\n        return llm.client.predict(*args, **kwargs)\n    return _completion_with_retry(*args, **kwargs)\n[docs]def stream_completion_with_retry(\n    llm: VertexAI,\n    *args: Any,\n    run_manager: Optional[CallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html"}
{"id": "463f176f76a2-2", "text": ") -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @retry_decorator\n    def _completion_with_retry(*args: Any, **kwargs: Any) -> Any:\n        return llm.client.predict_streaming(*args, **kwargs)\n    return _completion_with_retry(*args, **kwargs)\n[docs]async def acompletion_with_retry(\n    llm: VertexAI,\n    *args: Any,\n    run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @retry_decorator\n    async def _acompletion_with_retry(*args: Any, **kwargs: Any) -> Any:\n        return await llm.client.predict_async(*args, **kwargs)\n    return await _acompletion_with_retry(*args, **kwargs)\nclass _VertexAIBase(BaseModel):\n    project: Optional[str] = None\n    \"The default GCP project to use when making Vertex API calls.\"\n    location: str = \"us-central1\"\n    \"The default location to use when making API calls.\"\n    request_parallelism: int = 5\n    \"The amount of parallelism allowed for requests issued to VertexAI models. \"\n    \"Default is 5.\"\n    max_retries: int = 6\n    \"\"\"The maximum number of retries to make when generating.\"\"\"\n    task_executor: ClassVar[Optional[Executor]] = Field(default=None, exclude=True)\n    stop: Optional[List[str]] = None\n    \"Optional list of stop words to use when generating.\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html"}
{"id": "463f176f76a2-3", "text": "\"Optional list of stop words to use when generating.\"\n    model_name: Optional[str] = None\n    \"Underlying model name.\"\n    @classmethod\n    def _get_task_executor(cls, request_parallelism: int = 5) -> Executor:\n        if cls.task_executor is None:\n            cls.task_executor = ThreadPoolExecutor(max_workers=request_parallelism)\n        return cls.task_executor\nclass _VertexAICommon(_VertexAIBase):\n    client: \"_LanguageModel\" = None  #: :meta private:\n    model_name: str\n    \"Underlying model name.\"\n    temperature: float = 0.0\n    \"Sampling temperature, it controls the degree of randomness in token selection.\"\n    max_output_tokens: int = 128\n    \"Token limit determines the maximum amount of text output from one prompt.\"\n    top_p: float = 0.95\n    \"Tokens are selected from most probable to least until the sum of their \"\n    \"probabilities equals the top-p value. Top-p is ignored for Codey models.\"\n    top_k: int = 40\n    \"How the model selects tokens for output, the next token is selected from \"\n    \"among the top-k most probable tokens. Top-k is ignored for Codey models.\"\n    credentials: Any = Field(default=None, exclude=True)\n    \"The default custom credentials (google.auth.credentials.Credentials) to use \"\n    \"when making API calls. If not provided, credentials will be ascertained from \"\n    \"the environment.\"\n    n: int = 1\n    \"\"\"How many completions to generate for each prompt.\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results or not.\"\"\"\n    @property\n    def _llm_type(self) -> str:\n        return \"vertexai\"\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html"}
{"id": "463f176f76a2-4", "text": "return \"vertexai\"\n    @property\n    def is_codey_model(self) -> bool:\n        return is_codey_model(self.model_name)\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model_name\": self.model_name}, **self._default_params}\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        if self.is_codey_model:\n            return {\n                \"temperature\": self.temperature,\n                \"max_output_tokens\": self.max_output_tokens,\n            }\n        else:\n            return {\n                \"temperature\": self.temperature,\n                \"max_output_tokens\": self.max_output_tokens,\n                \"top_k\": self.top_k,\n                \"top_p\": self.top_p,\n                \"candidate_count\": self.n,\n            }\n    @classmethod\n    def _try_init_vertexai(cls, values: Dict) -> None:\n        allowed_params = [\"project\", \"location\", \"credentials\"]\n        params = {k: v for k, v in values.items() if k in allowed_params}\n        init_vertexai(**params)\n        return None\n    def _prepare_params(\n        self,\n        stop: Optional[List[str]] = None,\n        stream: bool = False,\n        **kwargs: Any,\n    ) -> dict:\n        stop_sequences = stop or self.stop\n        params_mapping = {\"n\": \"candidate_count\"}\n        params = {params_mapping.get(k, k): v for k, v in kwargs.items()}\n        params = {**self._default_params, \"stop_sequences\": stop_sequences, **params}\n        if stream or self.streaming:\n            params.pop(\"candidate_count\")\n        return params", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html"}
{"id": "463f176f76a2-5", "text": "if stream or self.streaming:\n            params.pop(\"candidate_count\")\n        return params\n[docs]class VertexAI(_VertexAICommon, BaseLLM):\n    \"\"\"Google Vertex AI large language models.\"\"\"\n    model_name: str = \"text-bison\"\n    \"The name of the Vertex AI large language model.\"\n    tuned_model_name: Optional[str] = None\n    \"The name of a tuned model. If provided, model_name is ignored.\"\n[docs]    @classmethod\n    def is_lc_serializable(self) -> bool:\n        return True\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the python package exists in environment.\"\"\"\n        cls._try_init_vertexai(values)\n        tuned_model_name = values.get(\"tuned_model_name\")\n        model_name = values[\"model_name\"]\n        try:\n            if not is_codey_model(model_name):\n                from vertexai.preview.language_models import TextGenerationModel\n                if tuned_model_name:\n                    values[\"client\"] = TextGenerationModel.get_tuned_model(\n                        tuned_model_name\n                    )\n                else:\n                    values[\"client\"] = TextGenerationModel.from_pretrained(model_name)\n            else:\n                from vertexai.preview.language_models import CodeGenerationModel\n                if tuned_model_name:\n                    values[\"client\"] = CodeGenerationModel.get_tuned_model(\n                        tuned_model_name\n                    )\n                else:\n                    values[\"client\"] = CodeGenerationModel.from_pretrained(model_name)\n        except ImportError:\n            raise_vertex_import_error()\n        if values[\"streaming\"] and values[\"n\"] > 1:\n            raise ValueError(\"Only one candidate can be generated with streaming!\")\n        return values\n[docs]    def get_num_tokens(self, text: str) -> int:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html"}
{"id": "463f176f76a2-6", "text": "[docs]    def get_num_tokens(self, text: str) -> int:\n        \"\"\"Get the number of tokens present in the text.\n        Useful for checking if an input will fit in a model's context window.\n        Args:\n            text: The string input to tokenize.\n        Returns:\n            The integer number of tokens in the text.\n        \"\"\"\n        try:\n            result = self.client.count_tokens(text)\n        except AttributeError:\n            raise NotImplementedError(\n                \"Your google-cloud-aiplatform version didn't implement count_tokens.\"\n                \"Please, install it with pip install google-cloud-aiplatform>=1.35.0\"\n            )\n        return result.total_tokens\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        should_stream = stream if stream is not None else self.streaming\n        params = self._prepare_params(stop=stop, stream=should_stream, **kwargs)\n        generations = []\n        for prompt in prompts:\n            if should_stream:\n                generation = GenerationChunk(text=\"\")\n                for chunk in self._stream(\n                    prompt, stop=stop, run_manager=run_manager, **kwargs\n                ):\n                    generation += chunk\n                generations.append([generation])\n            else:\n                res = completion_with_retry(\n                    self, prompt, run_manager=run_manager, **params\n                )\n                if self.is_codey_model:\n                    generations.append([_response_to_generation(res)])\n                else:\n                    generations.append(\n                        [_response_to_generation(r) for r in res.candidates]\n                    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html"}
{"id": "463f176f76a2-7", "text": "[_response_to_generation(r) for r in res.candidates]\n                    )\n        return LLMResult(generations=generations)\n    async def _agenerate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        params = self._prepare_params(stop=stop, **kwargs)\n        generations = []\n        for prompt in prompts:\n            res = await acompletion_with_retry(\n                self, prompt, run_manager=run_manager, **params\n            )\n            generations.append([_response_to_generation(r) for r in res.candidates])\n        return LLMResult(generations=generations)\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        params = self._prepare_params(stop=stop, stream=True, **kwargs)\n        for stream_resp in stream_completion_with_retry(\n            self, prompt, run_manager=run_manager, **params\n        ):\n            chunk = _response_to_generation(stream_resp)\n            yield chunk\n            if run_manager:\n                run_manager.on_llm_new_token(\n                    chunk.text,\n                    chunk=chunk,\n                    verbose=self.verbose,\n                )\n[docs]class VertexAIModelGarden(_VertexAIBase, BaseLLM):\n    \"\"\"Large language models served from Vertex AI Model Garden.\"\"\"\n    client: \"PredictionServiceClient\" = None  #: :meta private:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html"}
{"id": "463f176f76a2-8", "text": "client: \"PredictionServiceClient\" = None  #: :meta private:\n    async_client: \"PredictionServiceAsyncClient\" = None  #: :meta private:\n    endpoint_id: str\n    \"A name of an endpoint where the model has been deployed.\"\n    allowed_model_args: Optional[List[str]] = None\n    \"\"\"Allowed optional args to be passed to the model.\"\"\"\n    prompt_arg: str = \"prompt\"\n    result_arg: str = \"generated_text\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the python package exists in environment.\"\"\"\n        try:\n            from google.api_core.client_options import ClientOptions\n            from google.cloud.aiplatform.gapic import (\n                PredictionServiceAsyncClient,\n                PredictionServiceClient,\n            )\n        except ImportError:\n            raise_vertex_import_error()\n        if values[\"project\"] is None:\n            raise ValueError(\n                \"A GCP project should be provided to run inference on Model Garden!\"\n            )\n        client_options = ClientOptions(\n            api_endpoint=f\"{values['location']}-aiplatform.googleapis.com\"\n        )\n        client_info = get_client_info(module=\"vertex-ai-model-garden\")\n        values[\"client\"] = PredictionServiceClient(\n            client_options=client_options, client_info=client_info\n        )\n        values[\"async_client\"] = PredictionServiceAsyncClient(\n            client_options=client_options, client_info=client_info\n        )\n        return values\n    @property\n    def _llm_type(self) -> str:\n        return \"vertexai_model_garden\"\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html"}
{"id": "463f176f76a2-9", "text": "run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Run the LLM on the given prompt and input.\"\"\"\n        try:\n            from google.protobuf import json_format\n            from google.protobuf.struct_pb2 import Value\n        except ImportError:\n            raise ImportError(\n                \"protobuf package not found, please install it with\"\n                \" `pip install protobuf`\"\n            )\n        instances = []\n        for prompt in prompts:\n            if self.allowed_model_args:\n                instance = {\n                    k: v for k, v in kwargs.items() if k in self.allowed_model_args\n                }\n            else:\n                instance = {}\n            instance[self.prompt_arg] = prompt\n            instances.append(instance)\n        predict_instances = [\n            json_format.ParseDict(instance_dict, Value()) for instance_dict in instances\n        ]\n        endpoint = self.client.endpoint_path(\n            project=self.project, location=self.location, endpoint=self.endpoint_id\n        )\n        response = self.client.predict(endpoint=endpoint, instances=predict_instances)\n        generations: List[List[Generation]] = []\n        for result in response.predictions:\n            generations.append(\n                [Generation(text=prediction[self.result_arg]) for prediction in result]\n            )\n        return LLMResult(generations=generations)\n    async def _agenerate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Run the LLM on the given prompt and input.\"\"\"\n        try:\n            from google.protobuf import json_format\n            from google.protobuf.struct_pb2 import Value", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html"}
{"id": "463f176f76a2-10", "text": "from google.protobuf import json_format\n            from google.protobuf.struct_pb2 import Value\n        except ImportError:\n            raise ImportError(\n                \"protobuf package not found, please install it with\"\n                \" `pip install protobuf`\"\n            )\n        instances = []\n        for prompt in prompts:\n            if self.allowed_model_args:\n                instance = {\n                    k: v for k, v in kwargs.items() if k in self.allowed_model_args\n                }\n            else:\n                instance = {}\n            instance[self.prompt_arg] = prompt\n            instances.append(instance)\n        predict_instances = [\n            json_format.ParseDict(instance_dict, Value()) for instance_dict in instances\n        ]\n        endpoint = self.async_client.endpoint_path(\n            project=self.project, location=self.location, endpoint=self.endpoint_id\n        )\n        response = await self.async_client.predict(\n            endpoint=endpoint, instances=predict_instances\n        )\n        generations: List[List[Generation]] = []\n        for result in response.predictions:\n            generations.append(\n                [Generation(text=prediction[self.result_arg]) for prediction in result]\n            )\n        return LLMResult(generations=generations)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html"}
{"id": "c29bb7e5a646-0", "text": "Source code for langchain.llms.google_palm\nfrom __future__ import annotations\nimport logging\nfrom typing import Any, Callable, Dict, List, Optional\nfrom tenacity import (\n    before_sleep_log,\n    retry,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms import BaseLLM\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema import Generation, LLMResult\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\ndef _create_retry_decorator() -> Callable[[Any], Any]:\n    \"\"\"Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions\"\"\"\n    try:\n        import google.api_core.exceptions\n    except ImportError:\n        raise ImportError(\n            \"Could not import google-api-core python package. \"\n            \"Please install it with `pip install google-api-core`.\"\n        )\n    multiplier = 2\n    min_seconds = 1\n    max_seconds = 60\n    max_retries = 10\n    return retry(\n        reraise=True,\n        stop=stop_after_attempt(max_retries),\n        wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds),\n        retry=(\n            retry_if_exception_type(google.api_core.exceptions.ResourceExhausted)\n            | retry_if_exception_type(google.api_core.exceptions.ServiceUnavailable)\n            | retry_if_exception_type(google.api_core.exceptions.GoogleAPIError)\n        ),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\n[docs]def generate_with_retry(llm: GooglePalm, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html"}
{"id": "c29bb7e5a646-1", "text": "\"\"\"Use tenacity to retry the completion call.\"\"\"\n    retry_decorator = _create_retry_decorator()\n    @retry_decorator\n    def _generate_with_retry(**kwargs: Any) -> Any:\n        return llm.client.generate_text(**kwargs)\n    return _generate_with_retry(**kwargs)\ndef _strip_erroneous_leading_spaces(text: str) -> str:\n    \"\"\"Strip erroneous leading spaces from text.\n    The PaLM API will sometimes erroneously return a single leading space in all\n    lines > 1. This function strips that space.\n    \"\"\"\n    has_leading_space = all(not line or line[0] == \" \" for line in text.split(\"\\n\")[1:])\n    if has_leading_space:\n        return text.replace(\"\\n \", \"\\n\")\n    else:\n        return text\n[docs]class GooglePalm(BaseLLM, BaseModel):\n    \"\"\"Google PaLM models.\"\"\"\n    client: Any  #: :meta private:\n    google_api_key: Optional[str]\n    model_name: str = \"models/text-bison-001\"\n    \"\"\"Model name to use.\"\"\"\n    temperature: float = 0.7\n    \"\"\"Run inference with this temperature. Must by in the closed interval\n       [0.0, 1.0].\"\"\"\n    top_p: Optional[float] = None\n    \"\"\"Decode using nucleus sampling: consider the smallest set of tokens whose\n       probability sum is at least top_p. Must be in the closed interval [0.0, 1.0].\"\"\"\n    top_k: Optional[int] = None\n    \"\"\"Decode using top-k sampling: consider the set of top_k most probable tokens.\n       Must be positive.\"\"\"\n    max_output_tokens: Optional[int] = None\n    \"\"\"Maximum number of tokens to include in a candidate. Must be greater than zero.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html"}
{"id": "c29bb7e5a646-2", "text": "\"\"\"Maximum number of tokens to include in a candidate. Must be greater than zero.\n       If unset, will default to 64.\"\"\"\n    n: int = 1\n    \"\"\"Number of chat completions to generate for each prompt. Note that the API may\n       not return the full n completions if duplicates are generated.\"\"\"\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"google_api_key\": \"GOOGLE_API_KEY\"}\n[docs]    @classmethod\n    def is_lc_serializable(self) -> bool:\n        return True\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate api key, python package exists.\"\"\"\n        google_api_key = get_from_dict_or_env(\n            values, \"google_api_key\", \"GOOGLE_API_KEY\"\n        )\n        try:\n            import google.generativeai as genai\n            genai.configure(api_key=google_api_key)\n        except ImportError:\n            raise ImportError(\n                \"Could not import google-generativeai python package. \"\n                \"Please install it with `pip install google-generativeai`.\"\n            )\n        values[\"client\"] = genai\n        if values[\"temperature\"] is not None and not 0 <= values[\"temperature\"] <= 1:\n            raise ValueError(\"temperature must be in the range [0.0, 1.0]\")\n        if values[\"top_p\"] is not None and not 0 <= values[\"top_p\"] <= 1:\n            raise ValueError(\"top_p must be in the range [0.0, 1.0]\")\n        if values[\"top_k\"] is not None and values[\"top_k\"] <= 0:\n            raise ValueError(\"top_k must be positive\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html"}
{"id": "c29bb7e5a646-3", "text": "raise ValueError(\"top_k must be positive\")\n        if values[\"max_output_tokens\"] is not None and values[\"max_output_tokens\"] <= 0:\n            raise ValueError(\"max_output_tokens must be greater than zero\")\n        return values\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        generations = []\n        for prompt in prompts:\n            completion = generate_with_retry(\n                self,\n                model=self.model_name,\n                prompt=prompt,\n                stop_sequences=stop,\n                temperature=self.temperature,\n                top_p=self.top_p,\n                top_k=self.top_k,\n                max_output_tokens=self.max_output_tokens,\n                candidate_count=self.n,\n                **kwargs,\n            )\n            prompt_generations = []\n            for candidate in completion.candidates:\n                raw_text = candidate[\"output\"]\n                stripped_text = _strip_erroneous_leading_spaces(raw_text)\n                prompt_generations.append(Generation(text=stripped_text))\n            generations.append(prompt_generations)\n        return LLMResult(generations=generations)\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"google_palm\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html"}
{"id": "9a65ddc07570-0", "text": "Source code for langchain.llms.beam\nimport base64\nimport json\nimport logging\nimport subprocess\nimport textwrap\nimport time\nfrom typing import Any, Dict, List, Mapping, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\nDEFAULT_NUM_TRIES = 10\nDEFAULT_SLEEP_TIME = 4\n[docs]class Beam(LLM):\n    \"\"\"Beam API for gpt2 large language model.\n    To use, you should have the ``beam-sdk`` python package installed,\n    and the environment variable ``BEAM_CLIENT_ID`` set with your client id\n    and ``BEAM_CLIENT_SECRET`` set with your client secret. Information on how\n    to get this is available here: https://docs.beam.cloud/account/api-keys.\n    The wrapper can then be called as follows, where the name, cpu, memory, gpu,\n    python version, and python packages can be updated accordingly. Once deployed,\n    the instance can be called.\n    Example:\n        .. code-block:: python\n            llm = Beam(model_name=\"gpt2\",\n                name=\"langchain-gpt2\",\n                cpu=8,\n                memory=\"32Gi\",\n                gpu=\"A10G\",\n                python_version=\"python3.8\",\n                python_packages=[\n                    \"diffusers[torch]>=0.10\",\n                    \"transformers\",\n                    \"torch\",\n                    \"pillow\",\n                    \"accelerate\",\n                    \"safetensors\",\n                    \"xformers\",],\n                max_length=50)\n            llm._deploy()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html"}
{"id": "9a65ddc07570-1", "text": "max_length=50)\n            llm._deploy()\n            call_result = llm._call(input)\n    \"\"\"\n    model_name: str = \"\"\n    name: str = \"\"\n    cpu: str = \"\"\n    memory: str = \"\"\n    gpu: str = \"\"\n    python_version: str = \"\"\n    python_packages: List[str] = []\n    max_length: str = \"\"\n    url: str = \"\"\n    \"\"\"model endpoint to use\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not\n    explicitly specified.\"\"\"\n    beam_client_id: str = \"\"\n    beam_client_secret: str = \"\"\n    app_id: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic config.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = {field.alias for field in cls.__fields__.values()}\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name not in all_required_field_names:\n                if field_name in extra:\n                    raise ValueError(f\"Found {field_name} supplied twice.\")\n                logger.warning(\n                    f\"\"\"{field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html"}
{"id": "9a65ddc07570-2", "text": "@root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        beam_client_id = get_from_dict_or_env(\n            values, \"beam_client_id\", \"BEAM_CLIENT_ID\"\n        )\n        beam_client_secret = get_from_dict_or_env(\n            values, \"beam_client_secret\", \"BEAM_CLIENT_SECRET\"\n        )\n        values[\"beam_client_id\"] = beam_client_id\n        values[\"beam_client_secret\"] = beam_client_secret\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"model_name\": self.model_name,\n            \"name\": self.name,\n            \"cpu\": self.cpu,\n            \"memory\": self.memory,\n            \"gpu\": self.gpu,\n            \"python_version\": self.python_version,\n            \"python_packages\": self.python_packages,\n            \"max_length\": self.max_length,\n            \"model_kwargs\": self.model_kwargs,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"beam\"\n[docs]    def app_creation(self) -> None:\n        \"\"\"Creates a Python file which will contain your Beam app definition.\"\"\"\n        script = textwrap.dedent(\n            \"\"\"\\\n        import beam\n        # The environment your code will run on\n        app = beam.App(\n            name=\"{name}\",\n            cpu={cpu},\n            memory=\"{memory}\",\n            gpu=\"{gpu}\",\n            python_version=\"{python_version}\",\n            python_packages={python_packages},\n        )\n        app.Trigger.RestAPI(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html"}
{"id": "9a65ddc07570-3", "text": "python_packages={python_packages},\n        )\n        app.Trigger.RestAPI(\n            inputs={{\"prompt\": beam.Types.String(), \"max_length\": beam.Types.String()}},\n            outputs={{\"text\": beam.Types.String()}},\n            handler=\"run.py:beam_langchain\",\n        )\n        \"\"\"\n        )\n        script_name = \"app.py\"\n        with open(script_name, \"w\") as file:\n            file.write(\n                script.format(\n                    name=self.name,\n                    cpu=self.cpu,\n                    memory=self.memory,\n                    gpu=self.gpu,\n                    python_version=self.python_version,\n                    python_packages=self.python_packages,\n                )\n            )\n[docs]    def run_creation(self) -> None:\n        \"\"\"Creates a Python file which will be deployed on beam.\"\"\"\n        script = textwrap.dedent(\n            \"\"\"\n        import os\n        import transformers\n        from transformers import GPT2LMHeadModel, GPT2Tokenizer\n        model_name = \"{model_name}\"\n        def beam_langchain(**inputs):\n            prompt = inputs[\"prompt\"]\n            length = inputs[\"max_length\"]\n            tokenizer = GPT2Tokenizer.from_pretrained(model_name)\n            model = GPT2LMHeadModel.from_pretrained(model_name)\n            encodedPrompt = tokenizer.encode(prompt, return_tensors='pt')\n            outputs = model.generate(encodedPrompt, max_length=int(length),\n              do_sample=True, pad_token_id=tokenizer.eos_token_id)\n            output = tokenizer.decode(outputs[0], skip_special_tokens=True)\n            print(output)\n            return {{\"text\": output}}\n        \"\"\"\n        )\n        script_name = \"run.py\"\n        with open(script_name, \"w\") as file:\n            file.write(script.format(model_name=self.model_name))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html"}
{"id": "9a65ddc07570-4", "text": "file.write(script.format(model_name=self.model_name))\n    def _deploy(self) -> str:\n        \"\"\"Call to Beam.\"\"\"\n        try:\n            import beam  # type: ignore\n            if beam.__path__ == \"\":\n                raise ImportError\n        except ImportError:\n            raise ImportError(\n                \"Could not import beam python package. \"\n                \"Please install it with `curl \"\n                \"https://raw.githubusercontent.com/slai-labs\"\n                \"/get-beam/main/get-beam.sh -sSfL | sh`.\"\n            )\n        self.app_creation()\n        self.run_creation()\n        process = subprocess.run(\n            \"beam deploy app.py\", shell=True, capture_output=True, text=True\n        )\n        if process.returncode == 0:\n            output = process.stdout\n            logger.info(output)\n            lines = output.split(\"\\n\")\n            for line in lines:\n                if line.startswith(\" i  Send requests to: https://apps.beam.cloud/\"):\n                    self.app_id = line.split(\"/\")[-1]\n                    self.url = line.split(\":\")[1].strip()\n                    return self.app_id\n            raise ValueError(\n                f\"\"\"Failed to retrieve the appID from the deployment output.\n                Deployment output: {output}\"\"\"\n            )\n        else:\n            raise ValueError(f\"Deployment failed. Error: {process.stderr}\")\n    @property\n    def authorization(self) -> str:\n        if self.beam_client_id:\n            credential_str = self.beam_client_id + \":\" + self.beam_client_secret\n        else:\n            credential_str = self.beam_client_secret\n        return base64.b64encode(credential_str.encode()).decode()\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[list] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html"}
{"id": "9a65ddc07570-5", "text": "self,\n        prompt: str,\n        stop: Optional[list] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call to Beam.\"\"\"\n        url = \"https://apps.beam.cloud/\" + self.app_id if self.app_id else self.url\n        payload = {\"prompt\": prompt, \"max_length\": self.max_length}\n        payload.update(kwargs)\n        headers = {\n            \"Accept\": \"*/*\",\n            \"Accept-Encoding\": \"gzip, deflate\",\n            \"Authorization\": \"Basic \" + self.authorization,\n            \"Connection\": \"keep-alive\",\n            \"Content-Type\": \"application/json\",\n        }\n        for _ in range(DEFAULT_NUM_TRIES):\n            request = requests.post(url, headers=headers, data=json.dumps(payload))\n            if request.status_code == 200:\n                return request.json()[\"text\"]\n            time.sleep(DEFAULT_SLEEP_TIME)\n        logger.warning(\"Unable to successfully call model.\")\n        return \"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html"}
{"id": "5c29157effa5-0", "text": "Source code for langchain.llms.anthropic\nimport re\nimport warnings\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Callable,\n    Dict,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n)\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Field, SecretStr, root_validator\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.output import GenerationChunk\nfrom langchain.schema.prompt import PromptValue\nfrom langchain.utils import (\n    check_package_version,\n    get_from_dict_or_env,\n    get_pydantic_field_names,\n)\nfrom langchain.utils.utils import build_extra_kwargs, convert_to_secret_str\nclass _AnthropicCommon(BaseLanguageModel):\n    client: Any = None  #: :meta private:\n    async_client: Any = None  #: :meta private:\n    model: str = Field(default=\"claude-2\", alias=\"model_name\")\n    \"\"\"Model name to use.\"\"\"\n    max_tokens_to_sample: int = Field(default=256, alias=\"max_tokens\")\n    \"\"\"Denotes the number of tokens to predict per generation.\"\"\"\n    temperature: Optional[float] = None\n    \"\"\"A non-negative float that tunes the degree of randomness in generation.\"\"\"\n    top_k: Optional[int] = None\n    \"\"\"Number of most likely tokens to consider at each step.\"\"\"\n    top_p: Optional[float] = None\n    \"\"\"Total probability mass of tokens to consider at each step.\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results.\"\"\"\n    default_request_timeout: Optional[float] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html"}
{"id": "5c29157effa5-1", "text": "\"\"\"Whether to stream the results.\"\"\"\n    default_request_timeout: Optional[float] = None\n    \"\"\"Timeout for requests to Anthropic Completion API. Default is 600 seconds.\"\"\"\n    anthropic_api_url: Optional[str] = None\n    anthropic_api_key: Optional[SecretStr] = None\n    HUMAN_PROMPT: Optional[str] = None\n    AI_PROMPT: Optional[str] = None\n    count_tokens: Optional[Callable[[str], int]] = None\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict) -> Dict:\n        extra = values.get(\"model_kwargs\", {})\n        all_required_field_names = get_pydantic_field_names(cls)\n        values[\"model_kwargs\"] = build_extra_kwargs(\n            extra, values, all_required_field_names\n        )\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"anthropic_api_key\"] = convert_to_secret_str(\n            get_from_dict_or_env(values, \"anthropic_api_key\", \"ANTHROPIC_API_KEY\")\n        )\n        # Get custom api url from environment.\n        values[\"anthropic_api_url\"] = get_from_dict_or_env(\n            values,\n            \"anthropic_api_url\",\n            \"ANTHROPIC_API_URL\",\n            default=\"https://api.anthropic.com\",\n        )\n        try:\n            import anthropic\n            check_package_version(\"anthropic\", gte_version=\"0.3\")\n            values[\"client\"] = anthropic.Anthropic(\n                base_url=values[\"anthropic_api_url\"],\n                api_key=values[\"anthropic_api_key\"].get_secret_value(),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html"}
{"id": "5c29157effa5-2", "text": "api_key=values[\"anthropic_api_key\"].get_secret_value(),\n                timeout=values[\"default_request_timeout\"],\n            )\n            values[\"async_client\"] = anthropic.AsyncAnthropic(\n                base_url=values[\"anthropic_api_url\"],\n                api_key=values[\"anthropic_api_key\"].get_secret_value(),\n                timeout=values[\"default_request_timeout\"],\n            )\n            values[\"HUMAN_PROMPT\"] = anthropic.HUMAN_PROMPT\n            values[\"AI_PROMPT\"] = anthropic.AI_PROMPT\n            values[\"count_tokens\"] = values[\"client\"].count_tokens\n        except ImportError:\n            raise ImportError(\n                \"Could not import anthropic python package. \"\n                \"Please it install it with `pip install anthropic`.\"\n            )\n        return values\n    @property\n    def _default_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the default parameters for calling Anthropic API.\"\"\"\n        d = {\n            \"max_tokens_to_sample\": self.max_tokens_to_sample,\n            \"model\": self.model,\n        }\n        if self.temperature is not None:\n            d[\"temperature\"] = self.temperature\n        if self.top_k is not None:\n            d[\"top_k\"] = self.top_k\n        if self.top_p is not None:\n            d[\"top_p\"] = self.top_p\n        return {**d, **self.model_kwargs}\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{}, **self._default_params}\n    def _get_anthropic_stop(self, stop: Optional[List[str]] = None) -> List[str]:\n        if not self.HUMAN_PROMPT or not self.AI_PROMPT:\n            raise NameError(\"Please ensure the anthropic package is loaded\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html"}
{"id": "5c29157effa5-3", "text": "raise NameError(\"Please ensure the anthropic package is loaded\")\n        if stop is None:\n            stop = []\n        # Never want model to invent new turns of Human / Assistant dialog.\n        stop.extend([self.HUMAN_PROMPT])\n        return stop\n[docs]class Anthropic(LLM, _AnthropicCommon):\n    \"\"\"Anthropic large language models.\n    To use, you should have the ``anthropic`` python package installed, and the\n    environment variable ``ANTHROPIC_API_KEY`` set with your API key, or pass\n    it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            import anthropic\n            from langchain.llms import Anthropic\n            model = Anthropic(model=\"<model_name>\", anthropic_api_key=\"my-api-key\")\n            # Simplest invocation, automatically wrapped with HUMAN_PROMPT\n            # and AI_PROMPT.\n            response = model(\"What are the biggest risks facing humanity?\")\n            # Or if you want to use the chat mode, build a few-shot-prompt, or\n            # put words in the Assistant's mouth, use HUMAN_PROMPT and AI_PROMPT:\n            raw_prompt = \"What are the biggest risks facing humanity?\"\n            prompt = f\"{anthropic.HUMAN_PROMPT} {prompt}{anthropic.AI_PROMPT}\"\n            response = model(prompt)\n    \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        allow_population_by_field_name = True\n        arbitrary_types_allowed = True\n    @root_validator()\n    def raise_warning(cls, values: Dict) -> Dict:\n        \"\"\"Raise warning that this class is deprecated.\"\"\"\n        warnings.warn(\n            \"This Anthropic LLM is deprecated. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html"}
{"id": "5c29157effa5-4", "text": "warnings.warn(\n            \"This Anthropic LLM is deprecated. \"\n            \"Please use `from langchain.chat_models import ChatAnthropic` instead\"\n        )\n        return values\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"anthropic-llm\"\n    def _wrap_prompt(self, prompt: str) -> str:\n        if not self.HUMAN_PROMPT or not self.AI_PROMPT:\n            raise NameError(\"Please ensure the anthropic package is loaded\")\n        if prompt.startswith(self.HUMAN_PROMPT):\n            return prompt  # Already wrapped.\n        # Guard against common errors in specifying wrong number of newlines.\n        corrected_prompt, n_subs = re.subn(r\"^\\n*Human:\", self.HUMAN_PROMPT, prompt)\n        if n_subs == 1:\n            return corrected_prompt\n        # As a last resort, wrap the prompt ourselves to emulate instruct-style.\n        return f\"{self.HUMAN_PROMPT} {prompt}{self.AI_PROMPT} Sure, here you go:\\n\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        r\"\"\"Call out to Anthropic's completion endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                prompt = \"What are the biggest risks facing humanity?\"\n                prompt = f\"\\n\\nHuman: {prompt}\\n\\nAssistant:\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html"}
{"id": "5c29157effa5-5", "text": "prompt = f\"\\n\\nHuman: {prompt}\\n\\nAssistant:\"\n                response = model(prompt)\n        \"\"\"\n        if self.streaming:\n            completion = \"\"\n            for chunk in self._stream(\n                prompt=prompt, stop=stop, run_manager=run_manager, **kwargs\n            ):\n                completion += chunk.text\n            return completion\n        stop = self._get_anthropic_stop(stop)\n        params = {**self._default_params, **kwargs}\n        response = self.client.completions.create(\n            prompt=self._wrap_prompt(prompt),\n            stop_sequences=stop,\n            **params,\n        )\n        return response.completion\n[docs]    def convert_prompt(self, prompt: PromptValue) -> str:\n        return self._wrap_prompt(prompt.to_string())\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Anthropic's completion endpoint asynchronously.\"\"\"\n        if self.streaming:\n            completion = \"\"\n            async for chunk in self._astream(\n                prompt=prompt, stop=stop, run_manager=run_manager, **kwargs\n            ):\n                completion += chunk.text\n            return completion\n        stop = self._get_anthropic_stop(stop)\n        params = {**self._default_params, **kwargs}\n        response = await self.async_client.completions.create(\n            prompt=self._wrap_prompt(prompt),\n            stop_sequences=stop,\n            **params,\n        )\n        return response.completion\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html"}
{"id": "5c29157effa5-6", "text": "prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        r\"\"\"Call Anthropic completion_stream and return the resulting generator.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            A generator representing the stream of tokens from Anthropic.\n        Example:\n            .. code-block:: python\n                prompt = \"Write a poem about a stream.\"\n                prompt = f\"\\n\\nHuman: {prompt}\\n\\nAssistant:\"\n                generator = anthropic.stream(prompt)\n                for token in generator:\n                    yield token\n        \"\"\"\n        stop = self._get_anthropic_stop(stop)\n        params = {**self._default_params, **kwargs}\n        for token in self.client.completions.create(\n            prompt=self._wrap_prompt(prompt), stop_sequences=stop, stream=True, **params\n        ):\n            chunk = GenerationChunk(text=token.completion)\n            yield chunk\n            if run_manager:\n                run_manager.on_llm_new_token(chunk.text, chunk=chunk)\n    async def _astream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[GenerationChunk]:\n        r\"\"\"Call Anthropic completion_stream and return the resulting generator.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            A generator representing the stream of tokens from Anthropic.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html"}
{"id": "5c29157effa5-7", "text": "Returns:\n            A generator representing the stream of tokens from Anthropic.\n        Example:\n            .. code-block:: python\n                prompt = \"Write a poem about a stream.\"\n                prompt = f\"\\n\\nHuman: {prompt}\\n\\nAssistant:\"\n                generator = anthropic.stream(prompt)\n                for token in generator:\n                    yield token\n        \"\"\"\n        stop = self._get_anthropic_stop(stop)\n        params = {**self._default_params, **kwargs}\n        async for token in await self.async_client.completions.create(\n            prompt=self._wrap_prompt(prompt),\n            stop_sequences=stop,\n            stream=True,\n            **params,\n        ):\n            chunk = GenerationChunk(text=token.completion)\n            yield chunk\n            if run_manager:\n                await run_manager.on_llm_new_token(chunk.text, chunk=chunk)\n[docs]    def get_num_tokens(self, text: str) -> int:\n        \"\"\"Calculate number of tokens.\"\"\"\n        if not self.count_tokens:\n            raise NameError(\"Please ensure the anthropic package is loaded\")\n        return self.count_tokens(text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html"}
{"id": "8774c8ff6f9d-0", "text": "Source code for langchain.llms.ctransformers\nfrom functools import partial\nfrom typing import Any, Dict, List, Optional, Sequence\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import root_validator\n[docs]class CTransformers(LLM):\n    \"\"\"C Transformers LLM models.\n    To use, you should have the ``ctransformers`` python package installed.\n    See https://github.com/marella/ctransformers\n    Example:\n        .. code-block:: python\n            from langchain.llms import CTransformers\n            llm = CTransformers(model=\"/path/to/ggml-gpt-2.bin\", model_type=\"gpt2\")\n    \"\"\"\n    client: Any  #: :meta private:\n    model: str\n    \"\"\"The path to a model file or directory or the name of a Hugging Face Hub\n    model repo.\"\"\"\n    model_type: Optional[str] = None\n    \"\"\"The model type.\"\"\"\n    model_file: Optional[str] = None\n    \"\"\"The name of the model file in repo or directory.\"\"\"\n    config: Optional[Dict[str, Any]] = None\n    \"\"\"The config parameters.\n    See https://github.com/marella/ctransformers#config\"\"\"\n    lib: Optional[str] = None\n    \"\"\"The path to a shared library or one of `avx2`, `avx`, `basic`.\"\"\"\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"model\": self.model,\n            \"model_type\": self.model_type,\n            \"model_file\": self.model_file,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html"}
{"id": "8774c8ff6f9d-1", "text": "\"model_type\": self.model_type,\n            \"model_file\": self.model_file,\n            \"config\": self.config,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"ctransformers\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that ``ctransformers`` package is installed.\"\"\"\n        try:\n            from ctransformers import AutoModelForCausalLM\n        except ImportError:\n            raise ImportError(\n                \"Could not import `ctransformers` package. \"\n                \"Please install it with `pip install ctransformers`\"\n            )\n        config = values[\"config\"] or {}\n        values[\"client\"] = AutoModelForCausalLM.from_pretrained(\n            values[\"model\"],\n            model_type=values[\"model_type\"],\n            model_file=values[\"model_file\"],\n            lib=values[\"lib\"],\n            **config,\n        )\n        return values\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[Sequence[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Generate text from a prompt.\n        Args:\n            prompt: The prompt to generate text from.\n            stop: A list of sequences to stop generation when encountered.\n        Returns:\n            The generated text.\n        Example:\n            .. code-block:: python\n                response = llm(\"Tell me a joke.\")\n        \"\"\"\n        text = []\n        _run_manager = run_manager or CallbackManagerForLLMRun.get_noop_manager()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html"}
{"id": "8774c8ff6f9d-2", "text": "_run_manager = run_manager or CallbackManagerForLLMRun.get_noop_manager()\n        for chunk in self.client(prompt, stop=stop, stream=True):\n            text.append(chunk)\n            _run_manager.on_llm_new_token(chunk, verbose=self.verbose)\n        return \"\".join(text)\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Asynchronous Call out to CTransformers generate method.\n        Very helpful when streaming (like with websockets!)\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: A list of strings to stop generation when encountered.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = llm(\"Once upon a time, \")\n        \"\"\"\n        text_callback = None\n        if run_manager:\n            text_callback = partial(run_manager.on_llm_new_token, verbose=self.verbose)\n        text = \"\"\n        for token in self.client(prompt, stop=stop, stream=True):\n            if text_callback:\n                await text_callback(token)\n            text += token\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html"}
{"id": "c9ff28d924c7-0", "text": "Source code for langchain.llms.petals\nimport logging\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class Petals(LLM):\n    \"\"\"Petals Bloom models.\n    To use, you should have the ``petals`` python package installed, and the\n    environment variable ``HUGGINGFACE_API_KEY`` set with your API key.\n    Any parameters that are valid to be passed to the call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.llms import petals\n            petals = Petals()\n    \"\"\"\n    client: Any\n    \"\"\"The client to use for the API calls.\"\"\"\n    tokenizer: Any\n    \"\"\"The tokenizer to use for the API calls.\"\"\"\n    model_name: str = \"bigscience/bloom-petals\"\n    \"\"\"The model to use.\"\"\"\n    temperature: float = 0.7\n    \"\"\"What sampling temperature to use\"\"\"\n    max_new_tokens: int = 256\n    \"\"\"The maximum number of new tokens to generate in the completion.\"\"\"\n    top_p: float = 0.9\n    \"\"\"The cumulative probability for top-p sampling.\"\"\"\n    top_k: Optional[int] = None\n    \"\"\"The number of highest probability vocabulary tokens\n    to keep for top-k-filtering.\"\"\"\n    do_sample: bool = True\n    \"\"\"Whether or not to use sampling; use greedy decoding otherwise.\"\"\"\n    max_length: Optional[int] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html"}
{"id": "c9ff28d924c7-1", "text": "max_length: Optional[int] = None\n    \"\"\"The maximum length of the sequence to be generated.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call\n    not explicitly specified.\"\"\"\n    huggingface_api_key: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic config.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = {field.alias for field in cls.__fields__.values()}\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name not in all_required_field_names:\n                if field_name in extra:\n                    raise ValueError(f\"Found {field_name} supplied twice.\")\n                logger.warning(\n                    f\"\"\"WARNING! {field_name} is not default parameter.\n                    {field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        huggingface_api_key = get_from_dict_or_env(\n            values, \"huggingface_api_key\", \"HUGGINGFACE_API_KEY\"\n        )\n        try:\n            from petals import AutoDistributedModelForCausalLM\n            from transformers import AutoTokenizer\n            model_name = values[\"model_name\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html"}
{"id": "c9ff28d924c7-2", "text": "from transformers import AutoTokenizer\n            model_name = values[\"model_name\"]\n            values[\"tokenizer\"] = AutoTokenizer.from_pretrained(model_name)\n            values[\"client\"] = AutoDistributedModelForCausalLM.from_pretrained(\n                model_name\n            )\n            values[\"huggingface_api_key\"] = huggingface_api_key\n        except ImportError:\n            raise ImportError(\n                \"Could not import transformers or petals python package.\"\n                \"Please install with `pip install -U transformers petals`.\"\n            )\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Petals API.\"\"\"\n        normal_params = {\n            \"temperature\": self.temperature,\n            \"max_new_tokens\": self.max_new_tokens,\n            \"top_p\": self.top_p,\n            \"top_k\": self.top_k,\n            \"do_sample\": self.do_sample,\n            \"max_length\": self.max_length,\n        }\n        return {**normal_params, **self.model_kwargs}\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model_name\": self.model_name}, **self._default_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"petals\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call the Petals API.\"\"\"\n        params = self._default_params\n        params = {**params, **kwargs}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html"}
{"id": "c9ff28d924c7-3", "text": "params = self._default_params\n        params = {**params, **kwargs}\n        inputs = self.tokenizer(prompt, return_tensors=\"pt\")[\"input_ids\"]\n        outputs = self.client.generate(inputs, **params)\n        text = self.tokenizer.decode(outputs[0])\n        if stop is not None:\n            # I believe this is required since the stop tokens\n            # are not enforced by the model parameters\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html"}
{"id": "6dc18c4db5c3-0", "text": "Source code for langchain.llms.tongyi\nfrom __future__ import annotations\nimport logging\nfrom typing import Any, Callable, Dict, List, Optional\nfrom requests.exceptions import HTTPError\nfrom tenacity import (\n    before_sleep_log,\n    retry,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema import Generation, LLMResult\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\ndef _create_retry_decorator(llm: Tongyi) -> Callable[[Any], Any]:\n    min_seconds = 1\n    max_seconds = 4\n    # Wait 2^x * 1 second between each retry starting with\n    # 4 seconds, then up to 10 seconds, then 10 seconds afterwards\n    return retry(\n        reraise=True,\n        stop=stop_after_attempt(llm.max_retries),\n        wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),\n        retry=(retry_if_exception_type(HTTPError)),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\n[docs]def generate_with_retry(llm: Tongyi, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    retry_decorator = _create_retry_decorator(llm)\n    @retry_decorator\n    def _generate_with_retry(**_kwargs: Any) -> Any:\n        resp = llm.client.call(**_kwargs)\n        if resp.status_code == 200:\n            return resp\n        elif resp.status_code in [400, 401]:\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html"}
{"id": "6dc18c4db5c3-1", "text": "elif resp.status_code in [400, 401]:\n            raise ValueError(\n                f\"status_code: {resp.status_code} \\n \"\n                f\"code: {resp.code} \\n message: {resp.message}\"\n            )\n        else:\n            raise HTTPError(\n                f\"HTTP error occurred: status_code: {resp.status_code} \\n \"\n                f\"code: {resp.code} \\n message: {resp.message}\",\n                response=resp,\n            )\n    return _generate_with_retry(**kwargs)\n[docs]def stream_generate_with_retry(llm: Tongyi, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    retry_decorator = _create_retry_decorator(llm)\n    @retry_decorator\n    def _stream_generate_with_retry(**_kwargs: Any) -> Any:\n        stream_resps = []\n        resps = llm.client.call(**_kwargs)\n        for resp in resps:\n            if resp.status_code == 200:\n                stream_resps.append(resp)\n            elif resp.status_code in [400, 401]:\n                raise ValueError(\n                    f\"status_code: {resp.status_code} \\n \"\n                    f\"code: {resp.code} \\n message: {resp.message}\"\n                )\n            else:\n                raise HTTPError(\n                    f\"HTTP error occurred: status_code: {resp.status_code} \\n \"\n                    f\"code: {resp.code} \\n message: {resp.message}\",\n                    response=resp,\n                )\n        return stream_resps\n    return _stream_generate_with_retry(**kwargs)\n[docs]class Tongyi(LLM):\n    \"\"\"Tongyi Qwen large language models.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html"}
{"id": "6dc18c4db5c3-2", "text": "\"\"\"Tongyi Qwen large language models.\n    To use, you should have the ``dashscope`` python package installed, and the\n    environment variable ``DASHSCOPE_API_KEY`` set with your API key, or pass\n    it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.llms import Tongyi\n            Tongyi = tongyi()\n    \"\"\"\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"dashscope_api_key\": \"DASHSCOPE_API_KEY\"}\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n    client: Any  #: :meta private:\n    model_name: str = \"qwen-plus-v1\"\n    \"\"\"Model name to use.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    top_p: float = 0.8\n    \"\"\"Total probability mass of tokens to consider at each step.\"\"\"\n    dashscope_api_key: Optional[str] = None\n    \"\"\"Dashscope api key provide by alicloud.\"\"\"\n    n: int = 1\n    \"\"\"How many completions to generate for each prompt.\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results or not.\"\"\"\n    max_retries: int = 10\n    \"\"\"Maximum number of retries to make when generating.\"\"\"\n    prefix_messages: List = Field(default_factory=list)\n    \"\"\"Series of messages for Chat input.\"\"\"\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"tongyi\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html"}
{"id": "6dc18c4db5c3-3", "text": "@root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        get_from_dict_or_env(values, \"dashscope_api_key\", \"DASHSCOPE_API_KEY\")\n        try:\n            import dashscope\n        except ImportError:\n            raise ImportError(\n                \"Could not import dashscope python package. \"\n                \"Please install it with `pip install dashscope`.\"\n            )\n        try:\n            values[\"client\"] = dashscope.Generation\n        except AttributeError:\n            raise ValueError(\n                \"`dashscope` has no `Generation` attribute, this is likely \"\n                \"due to an old version of the dashscope package. Try upgrading it \"\n                \"with `pip install --upgrade dashscope`.\"\n            )\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling OpenAI API.\"\"\"\n        normal_params = {\n            \"top_p\": self.top_p,\n        }\n        return {**normal_params, **self.model_kwargs}\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Tongyi's generate endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = tongyi(\"Tell me a joke.\")\n        \"\"\"\n        params: Dict[str, Any] = {\n            **{\"model\": self.model_name},\n            **self._default_params,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html"}
{"id": "6dc18c4db5c3-4", "text": "**{\"model\": self.model_name},\n            **self._default_params,\n            **kwargs,\n        }\n        completion = generate_with_retry(\n            self,\n            prompt=prompt,\n            **params,\n        )\n        return completion[\"output\"][\"text\"]\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        generations = []\n        params: Dict[str, Any] = {\n            **{\"model\": self.model_name},\n            **self._default_params,\n            **kwargs,\n        }\n        if self.streaming:\n            if len(prompts) > 1:\n                raise ValueError(\"Cannot stream results with multiple prompts.\")\n            params[\"stream\"] = True\n            for stream_resp in stream_generate_with_retry(\n                self, prompt=prompts[0], **params\n            ):\n                generations.append(\n                    [\n                        Generation(\n                            text=stream_resp[\"output\"][\"text\"],\n                            generation_info=dict(\n                                finish_reason=stream_resp[\"output\"][\"finish_reason\"],\n                            ),\n                        )\n                    ]\n                )\n        else:\n            for prompt in prompts:\n                completion = generate_with_retry(\n                    self,\n                    prompt=prompt,\n                    **params,\n                )\n                generations.append(\n                    [\n                        Generation(\n                            text=completion[\"output\"][\"text\"],\n                            generation_info=dict(\n                                finish_reason=completion[\"output\"][\"finish_reason\"],\n                            ),\n                        )\n                    ]\n                )\n        return LLMResult(generations=generations)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html"}
{"id": "c71012282eac-0", "text": "Source code for langchain.llms.fake\nimport asyncio\nimport time\nfrom typing import Any, AsyncIterator, Iterator, List, Mapping, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.schema.language_model import LanguageModelInput\nfrom langchain.schema.runnable import RunnableConfig\n[docs]class FakeListLLM(LLM):\n    \"\"\"Fake LLM for testing purposes.\"\"\"\n    responses: List[str]\n    sleep: Optional[float] = None\n    i: int = 0\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"fake-list\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Return next response\"\"\"\n        response = self.responses[self.i]\n        if self.i < len(self.responses) - 1:\n            self.i += 1\n        else:\n            self.i = 0\n        return response\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Return next response\"\"\"\n        response = self.responses[self.i]\n        if self.i < len(self.responses) - 1:\n            self.i += 1\n        else:\n            self.i = 0\n        return response\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fake.html"}
{"id": "c71012282eac-1", "text": "else:\n            self.i = 0\n        return response\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        return {\"responses\": self.responses}\n[docs]class FakeStreamingListLLM(FakeListLLM):\n    \"\"\"Fake streaming list LLM for testing purposes.\"\"\"\n[docs]    def stream(\n        self,\n        input: LanguageModelInput,\n        config: Optional[RunnableConfig] = None,\n        *,\n        stop: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Iterator[str]:\n        result = self.invoke(input, config)\n        for c in result:\n            if self.sleep is not None:\n                time.sleep(self.sleep)\n            yield c\n[docs]    async def astream(\n        self,\n        input: LanguageModelInput,\n        config: Optional[RunnableConfig] = None,\n        *,\n        stop: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[str]:\n        result = await self.ainvoke(input, config)\n        for c in result:\n            if self.sleep is not None:\n                await asyncio.sleep(self.sleep)\n            yield c", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fake.html"}
{"id": "7dd2e86421b2-0", "text": "Source code for langchain.llms.clarifai\nimport logging\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.schema import Generation, LLMResult\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class Clarifai(LLM):\n    \"\"\"Clarifai large language models.\n    To use, you should have an account on the Clarifai platform,\n    the ``clarifai`` python package installed, and the\n    environment variable ``CLARIFAI_PAT`` set with your PAT key,\n    or pass it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.llms import Clarifai\n            clarifai_llm = Clarifai(pat=CLARIFAI_PAT, \\\n                user_id=USER_ID, app_id=APP_ID, model_id=MODEL_ID)\n    \"\"\"\n    stub: Any  #: :meta private:\n    userDataObject: Any\n    model_id: Optional[str] = None\n    \"\"\"Model id to use.\"\"\"\n    model_version_id: Optional[str] = None\n    \"\"\"Model version id to use.\"\"\"\n    app_id: Optional[str] = None\n    \"\"\"Clarifai application id to use.\"\"\"\n    user_id: Optional[str] = None\n    \"\"\"Clarifai user id to use.\"\"\"\n    pat: Optional[str] = None\n    api_base: str = \"https://api.clarifai.com\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html"}
{"id": "7dd2e86421b2-1", "text": "\"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that we have all required info to access Clarifai\n        platform and python package exists in environment.\"\"\"\n        values[\"pat\"] = get_from_dict_or_env(values, \"pat\", \"CLARIFAI_PAT\")\n        user_id = values.get(\"user_id\")\n        app_id = values.get(\"app_id\")\n        model_id = values.get(\"model_id\")\n        if values[\"pat\"] is None:\n            raise ValueError(\"Please provide a pat.\")\n        if user_id is None:\n            raise ValueError(\"Please provide a user_id.\")\n        if app_id is None:\n            raise ValueError(\"Please provide a app_id.\")\n        if model_id is None:\n            raise ValueError(\"Please provide a model_id.\")\n        try:\n            from clarifai.auth.helper import ClarifaiAuthHelper\n            from clarifai.client import create_stub\n        except ImportError:\n            raise ImportError(\n                \"Could not import clarifai python package. \"\n                \"Please install it with `pip install clarifai`.\"\n            )\n        auth = ClarifaiAuthHelper(\n            user_id=user_id,\n            app_id=app_id,\n            pat=values[\"pat\"],\n            base=values[\"api_base\"],\n        )\n        values[\"userDataObject\"] = auth.get_user_app_id_proto()\n        values[\"stub\"] = create_stub(auth)\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Clarifai API.\"\"\"\n        return {}\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html"}
{"id": "7dd2e86421b2-2", "text": "@property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\n                \"user_id\": self.user_id,\n                \"app_id\": self.app_id,\n                \"model_id\": self.model_id,\n            }\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"clarifai\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Clarfai's PostModelOutputs endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = clarifai_llm(\"Tell me a joke.\")\n        \"\"\"\n        try:\n            from clarifai_grpc.grpc.api import (\n                resources_pb2,\n                service_pb2,\n            )\n            from clarifai_grpc.grpc.api.status import status_code_pb2\n        except ImportError:\n            raise ImportError(\n                \"Could not import clarifai python package. \"\n                \"Please install it with `pip install clarifai`.\"\n            )\n        # The userDataObject is created in the overview and\n        # is required when using a PAT\n        # If version_id None, Defaults to the latest model version\n        post_model_outputs_request = service_pb2.PostModelOutputsRequest(\n            user_app_id=self.userDataObject,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html"}
{"id": "7dd2e86421b2-3", "text": "user_app_id=self.userDataObject,\n            model_id=self.model_id,\n            version_id=self.model_version_id,\n            inputs=[\n                resources_pb2.Input(\n                    data=resources_pb2.Data(text=resources_pb2.Text(raw=prompt))\n                )\n            ],\n        )\n        post_model_outputs_response = self.stub.PostModelOutputs(\n            post_model_outputs_request\n        )\n        if post_model_outputs_response.status.code != status_code_pb2.SUCCESS:\n            logger.error(post_model_outputs_response.status)\n            first_model_failure = (\n                post_model_outputs_response.outputs[0].status\n                if len(post_model_outputs_response.outputs)\n                else None\n            )\n            raise Exception(\n                f\"Post model outputs failed, status: \"\n                f\"{post_model_outputs_response.status}, first output failure: \"\n                f\"{first_model_failure}\"\n            )\n        text = post_model_outputs_response.outputs[0].data.text.raw\n        # In order to make this consistent with other endpoints, we strip them.\n        if stop is not None:\n            text = enforce_stop_tokens(text, stop)\n        return text\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Run the LLM on the given prompt and input.\"\"\"\n        try:\n            from clarifai_grpc.grpc.api import (\n                resources_pb2,\n                service_pb2,\n            )\n            from clarifai_grpc.grpc.api.status import status_code_pb2\n        except ImportError:\n            raise ImportError(\n                \"Could not import clarifai python package. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html"}
{"id": "7dd2e86421b2-4", "text": "raise ImportError(\n                \"Could not import clarifai python package. \"\n                \"Please install it with `pip install clarifai`.\"\n            )\n        # TODO: add caching here.\n        generations = []\n        batch_size = 32\n        for i in range(0, len(prompts), batch_size):\n            batch = prompts[i : i + batch_size]\n            post_model_outputs_request = service_pb2.PostModelOutputsRequest(\n                user_app_id=self.userDataObject,\n                model_id=self.model_id,\n                version_id=self.model_version_id,\n                inputs=[\n                    resources_pb2.Input(\n                        data=resources_pb2.Data(text=resources_pb2.Text(raw=prompt))\n                    )\n                    for prompt in batch\n                ],\n            )\n            post_model_outputs_response = self.stub.PostModelOutputs(\n                post_model_outputs_request\n            )\n            if post_model_outputs_response.status.code != status_code_pb2.SUCCESS:\n                logger.error(post_model_outputs_response.status)\n                first_model_failure = (\n                    post_model_outputs_response.outputs[0].status\n                    if len(post_model_outputs_response.outputs)\n                    else None\n                )\n                raise Exception(\n                    f\"Post model outputs failed, status: \"\n                    f\"{post_model_outputs_response.status}, first output failure: \"\n                    f\"{first_model_failure}\"\n                )\n            for output in post_model_outputs_response.outputs:\n                if stop is not None:\n                    text = enforce_stop_tokens(output.data.text.raw, stop)\n                else:\n                    text = output.data.text.raw\n                generations.append([Generation(text=text)])\n        return LLMResult(generations=generations)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html"}
{"id": "a8c3a00041c0-0", "text": "Source code for langchain.llms.textgen\nimport json\nimport logging\nfrom typing import Any, AsyncIterator, Dict, Iterator, List, Optional\nimport requests\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Field\nfrom langchain.schema.output import GenerationChunk\nlogger = logging.getLogger(__name__)\n[docs]class TextGen(LLM):\n    \"\"\"text-generation-webui models.\n    To use, you should have the text-generation-webui installed, a model loaded,\n    and --api added as a command-line option.\n    Suggested installation, use one-click installer for your OS:\n    https://github.com/oobabooga/text-generation-webui#one-click-installers\n    Parameters below taken from text-generation-webui api example:\n    https://github.com/oobabooga/text-generation-webui/blob/main/api-examples/api-example.py\n    Example:\n        .. code-block:: python\n            from langchain.llms import TextGen\n            llm = TextGen(model_url=\"http://localhost:8500\")\n    \"\"\"\n    model_url: str\n    \"\"\"The full URL to the textgen webui including http[s]://host:port \"\"\"\n    preset: Optional[str] = None\n    \"\"\"The preset to use in the textgen webui \"\"\"\n    max_new_tokens: Optional[int] = 250\n    \"\"\"The maximum number of tokens to generate.\"\"\"\n    do_sample: bool = Field(True, alias=\"do_sample\")\n    \"\"\"Do sample\"\"\"\n    temperature: Optional[float] = 1.3\n    \"\"\"Primary factor to control randomness of outputs. 0 = deterministic\n    (only the most likely token is used). Higher value = more randomness.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html"}
{"id": "a8c3a00041c0-1", "text": "(only the most likely token is used). Higher value = more randomness.\"\"\"\n    top_p: Optional[float] = 0.1\n    \"\"\"If not set to 1, select tokens with probabilities adding up to less than this\n    number. Higher value = higher range of possible random results.\"\"\"\n    typical_p: Optional[float] = 1\n    \"\"\"If not set to 1, select only tokens that are at least this much more likely to\n    appear than random tokens, given the prior text.\"\"\"\n    epsilon_cutoff: Optional[float] = 0  # In units of 1e-4\n    \"\"\"Epsilon cutoff\"\"\"\n    eta_cutoff: Optional[float] = 0  # In units of 1e-4\n    \"\"\"ETA cutoff\"\"\"\n    repetition_penalty: Optional[float] = 1.18\n    \"\"\"Exponential penalty factor for repeating prior tokens. 1 means no penalty,\n    higher value = less repetition, lower value = more repetition.\"\"\"\n    top_k: Optional[float] = 40\n    \"\"\"Similar to top_p, but select instead only the top_k most likely tokens.\n    Higher value = higher range of possible random results.\"\"\"\n    min_length: Optional[int] = 0\n    \"\"\"Minimum generation length in tokens.\"\"\"\n    no_repeat_ngram_size: Optional[int] = 0\n    \"\"\"If not set to 0, specifies the length of token sets that are completely blocked\n    from repeating at all. Higher values = blocks larger phrases,\n    lower values = blocks words or letters from repeating.\n    Only 0 or high values are a good idea in most cases.\"\"\"\n    num_beams: Optional[int] = 1\n    \"\"\"Number of beams\"\"\"\n    penalty_alpha: Optional[float] = 0\n    \"\"\"Penalty Alpha\"\"\"\n    length_penalty: Optional[float] = 1", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html"}
{"id": "a8c3a00041c0-2", "text": "\"\"\"Penalty Alpha\"\"\"\n    length_penalty: Optional[float] = 1\n    \"\"\"Length Penalty\"\"\"\n    early_stopping: bool = Field(False, alias=\"early_stopping\")\n    \"\"\"Early stopping\"\"\"\n    seed: int = Field(-1, alias=\"seed\")\n    \"\"\"Seed (-1 for random)\"\"\"\n    add_bos_token: bool = Field(True, alias=\"add_bos_token\")\n    \"\"\"Add the bos_token to the beginning of prompts.\n    Disabling this can make the replies more creative.\"\"\"\n    truncation_length: Optional[int] = 2048\n    \"\"\"Truncate the prompt up to this length. The leftmost tokens are removed if\n    the prompt exceeds this length. Most models require this to be at most 2048.\"\"\"\n    ban_eos_token: bool = Field(False, alias=\"ban_eos_token\")\n    \"\"\"Ban the eos_token. Forces the model to never end the generation prematurely.\"\"\"\n    skip_special_tokens: bool = Field(True, alias=\"skip_special_tokens\")\n    \"\"\"Skip special tokens. Some specific models need this unset.\"\"\"\n    stopping_strings: Optional[List[str]] = []\n    \"\"\"A list of strings to stop generation when encountered.\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results, token by token.\"\"\"\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling textgen.\"\"\"\n        return {\n            \"max_new_tokens\": self.max_new_tokens,\n            \"do_sample\": self.do_sample,\n            \"temperature\": self.temperature,\n            \"top_p\": self.top_p,\n            \"typical_p\": self.typical_p,\n            \"epsilon_cutoff\": self.epsilon_cutoff,\n            \"eta_cutoff\": self.eta_cutoff,\n            \"repetition_penalty\": self.repetition_penalty,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html"}
{"id": "a8c3a00041c0-3", "text": "\"repetition_penalty\": self.repetition_penalty,\n            \"top_k\": self.top_k,\n            \"min_length\": self.min_length,\n            \"no_repeat_ngram_size\": self.no_repeat_ngram_size,\n            \"num_beams\": self.num_beams,\n            \"penalty_alpha\": self.penalty_alpha,\n            \"length_penalty\": self.length_penalty,\n            \"early_stopping\": self.early_stopping,\n            \"seed\": self.seed,\n            \"add_bos_token\": self.add_bos_token,\n            \"truncation_length\": self.truncation_length,\n            \"ban_eos_token\": self.ban_eos_token,\n            \"skip_special_tokens\": self.skip_special_tokens,\n            \"stopping_strings\": self.stopping_strings,\n        }\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model_url\": self.model_url}, **self._default_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"textgen\"\n    def _get_parameters(self, stop: Optional[List[str]] = None) -> Dict[str, Any]:\n        \"\"\"\n        Performs sanity check, preparing parameters in format needed by textgen.\n        Args:\n            stop (Optional[List[str]]): List of stop sequences for textgen.\n        Returns:\n            Dictionary containing the combined parameters.\n        \"\"\"\n        # Raise error if stop sequences are in both input and default params\n        # if self.stop and stop is not None:\n        if self.stopping_strings and stop is not None:\n            raise ValueError(\"`stop` found in both the input and default params.\")\n        if self.preset is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html"}
{"id": "a8c3a00041c0-4", "text": "if self.preset is None:\n            params = self._default_params\n        else:\n            params = {\"preset\": self.preset}\n        # then sets it as configured, or default to an empty list:\n        params[\"stopping_strings\"] = self.stopping_strings or stop or []\n        return params\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call the textgen web API and return the output.\n        Args:\n            prompt: The prompt to use for generation.\n            stop: A list of strings to stop generation when encountered.\n        Returns:\n            The generated text.\n        Example:\n            .. code-block:: python\n                from langchain.llms import TextGen\n                llm = TextGen(model_url=\"http://localhost:5000\")\n                llm(\"Write a story about llamas.\")\n        \"\"\"\n        if self.streaming:\n            combined_text_output = \"\"\n            for chunk in self._stream(\n                prompt=prompt, stop=stop, run_manager=run_manager, **kwargs\n            ):\n                combined_text_output += chunk.text\n            result = combined_text_output\n        else:\n            url = f\"{self.model_url}/api/v1/generate\"\n            params = self._get_parameters(stop)\n            request = params.copy()\n            request[\"prompt\"] = prompt\n            response = requests.post(url, json=request)\n            if response.status_code == 200:\n                result = response.json()[\"results\"][0][\"text\"]\n            else:\n                print(f\"ERROR: response: {response}\")\n                result = \"\"\n        return result", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html"}
{"id": "a8c3a00041c0-5", "text": "result = \"\"\n        return result\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call the textgen web API and return the output.\n        Args:\n            prompt: The prompt to use for generation.\n            stop: A list of strings to stop generation when encountered.\n        Returns:\n            The generated text.\n        Example:\n            .. code-block:: python\n                from langchain.llms import TextGen\n                llm = TextGen(model_url=\"http://localhost:5000\")\n                llm(\"Write a story about llamas.\")\n        \"\"\"\n        if self.streaming:\n            combined_text_output = \"\"\n            async for chunk in self._astream(\n                prompt=prompt, stop=stop, run_manager=run_manager, **kwargs\n            ):\n                combined_text_output += chunk.text\n            result = combined_text_output\n        else:\n            url = f\"{self.model_url}/api/v1/generate\"\n            params = self._get_parameters(stop)\n            request = params.copy()\n            request[\"prompt\"] = prompt\n            response = requests.post(url, json=request)\n            if response.status_code == 200:\n                result = response.json()[\"results\"][0][\"text\"]\n            else:\n                print(f\"ERROR: response: {response}\")\n                result = \"\"\n        return result\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html"}
{"id": "a8c3a00041c0-6", "text": "**kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        \"\"\"Yields results objects as they are generated in real time.\n        It also calls the callback manager's on_llm_new_token event with\n        similar parameters to the OpenAI LLM class method of the same name.\n        Args:\n            prompt: The prompts to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            A generator representing the stream of tokens being generated.\n        Yields:\n            A dictionary like objects containing a string token and metadata.\n            See text-generation-webui docs and below for more.\n        Example:\n            .. code-block:: python\n                from langchain.llms import TextGen\n                llm = TextGen(\n                    model_url = \"ws://localhost:5005\"\n                    streaming=True\n                )\n                for chunk in llm.stream(\"Ask 'Hi, how are you?' like a pirate:'\",\n                        stop=[\"'\",\"\\n\"]):\n                    print(chunk, end='', flush=True)\n        \"\"\"\n        try:\n            import websocket\n        except ImportError:\n            raise ImportError(\n                \"The `websocket-client` package is required for streaming.\"\n            )\n        params = {**self._get_parameters(stop), **kwargs}\n        url = f\"{self.model_url}/api/v1/stream\"\n        request = params.copy()\n        request[\"prompt\"] = prompt\n        websocket_client = websocket.WebSocket()\n        websocket_client.connect(url)\n        websocket_client.send(json.dumps(request))\n        while True:\n            result = websocket_client.recv()\n            result = json.loads(result)\n            if result[\"event\"] == \"text_stream\":\n                chunk = GenerationChunk(\n                    text=result[\"text\"],\n                    generation_info=None,\n                )\n                yield chunk", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html"}
{"id": "a8c3a00041c0-7", "text": "text=result[\"text\"],\n                    generation_info=None,\n                )\n                yield chunk\n            elif result[\"event\"] == \"stream_end\":\n                websocket_client.close()\n                return\n            if run_manager:\n                run_manager.on_llm_new_token(token=chunk.text)\n    async def _astream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[GenerationChunk]:\n        \"\"\"Yields results objects as they are generated in real time.\n        It also calls the callback manager's on_llm_new_token event with\n        similar parameters to the OpenAI LLM class method of the same name.\n        Args:\n            prompt: The prompts to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            A generator representing the stream of tokens being generated.\n        Yields:\n            A dictionary like objects containing a string token and metadata.\n            See text-generation-webui docs and below for more.\n        Example:\n            .. code-block:: python\n                from langchain.llms import TextGen\n                llm = TextGen(\n                    model_url = \"ws://localhost:5005\"\n                    streaming=True\n                )\n                for chunk in llm.stream(\"Ask 'Hi, how are you?' like a pirate:'\",\n                        stop=[\"'\",\"\\n\"]):\n                    print(chunk, end='', flush=True)\n        \"\"\"\n        try:\n            import websocket\n        except ImportError:\n            raise ImportError(\n                \"The `websocket-client` package is required for streaming.\"\n            )\n        params = {**self._get_parameters(stop), **kwargs}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html"}
{"id": "a8c3a00041c0-8", "text": ")\n        params = {**self._get_parameters(stop), **kwargs}\n        url = f\"{self.model_url}/api/v1/stream\"\n        request = params.copy()\n        request[\"prompt\"] = prompt\n        websocket_client = websocket.WebSocket()\n        websocket_client.connect(url)\n        websocket_client.send(json.dumps(request))\n        while True:\n            result = websocket_client.recv()\n            result = json.loads(result)\n            if result[\"event\"] == \"text_stream\":\n                chunk = GenerationChunk(\n                    text=result[\"text\"],\n                    generation_info=None,\n                )\n                yield chunk\n            elif result[\"event\"] == \"stream_end\":\n                websocket_client.close()\n                return\n            if run_manager:\n                await run_manager.on_llm_new_token(token=chunk.text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html"}
{"id": "1bb0135bde89-0", "text": "Source code for langchain.llms.huggingface_pipeline\nfrom __future__ import annotations\nimport importlib.util\nimport logging\nfrom typing import Any, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import BaseLLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra\nfrom langchain.schema import Generation, LLMResult\nDEFAULT_MODEL_ID = \"gpt2\"\nDEFAULT_TASK = \"text-generation\"\nVALID_TASKS = (\"text2text-generation\", \"text-generation\", \"summarization\")\nDEFAULT_BATCH_SIZE = 4\nlogger = logging.getLogger(__name__)\n[docs]class HuggingFacePipeline(BaseLLM):\n    \"\"\"HuggingFace Pipeline API.\n    To use, you should have the ``transformers`` python package installed.\n    Only supports `text-generation`, `text2text-generation` and `summarization` for now.\n    Example using from_model_id:\n        .. code-block:: python\n            from langchain.llms import HuggingFacePipeline\n            hf = HuggingFacePipeline.from_model_id(\n                model_id=\"gpt2\",\n                task=\"text-generation\",\n                pipeline_kwargs={\"max_new_tokens\": 10},\n            )\n    Example passing pipeline in directly:\n        .. code-block:: python\n            from langchain.llms import HuggingFacePipeline\n            from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline\n            model_id = \"gpt2\"\n            tokenizer = AutoTokenizer.from_pretrained(model_id)\n            model = AutoModelForCausalLM.from_pretrained(model_id)\n            pipe = pipeline(\n                \"text-generation\", model=model, tokenizer=tokenizer, max_new_tokens=10\n            )\n            hf = HuggingFacePipeline(pipeline=pipe)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html"}
{"id": "1bb0135bde89-1", "text": ")\n            hf = HuggingFacePipeline(pipeline=pipe)\n    \"\"\"\n    pipeline: Any  #: :meta private:\n    model_id: str = DEFAULT_MODEL_ID\n    \"\"\"Model name to use.\"\"\"\n    model_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments passed to the model.\"\"\"\n    pipeline_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments passed to the pipeline.\"\"\"\n    batch_size: int = DEFAULT_BATCH_SIZE\n    \"\"\"Batch size to use when passing multiple documents to generate.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n[docs]    @classmethod\n    def from_model_id(\n        cls,\n        model_id: str,\n        task: str,\n        device: Optional[int] = -1,\n        device_map: Optional[str] = None,\n        model_kwargs: Optional[dict] = None,\n        pipeline_kwargs: Optional[dict] = None,\n        batch_size: int = DEFAULT_BATCH_SIZE,\n        **kwargs: Any,\n    ) -> HuggingFacePipeline:\n        \"\"\"Construct the pipeline object from model_id and task.\"\"\"\n        try:\n            from transformers import (\n                AutoModelForCausalLM,\n                AutoModelForSeq2SeqLM,\n                AutoTokenizer,\n            )\n            from transformers import pipeline as hf_pipeline\n        except ImportError:\n            raise ValueError(\n                \"Could not import transformers python package. \"\n                \"Please install it with `pip install transformers`.\"\n            )\n        _model_kwargs = model_kwargs or {}\n        tokenizer = AutoTokenizer.from_pretrained(model_id, **_model_kwargs)\n        try:\n            if task == \"text-generation\":\n                model = AutoModelForCausalLM.from_pretrained(model_id, **_model_kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html"}
{"id": "1bb0135bde89-2", "text": "elif task in (\"text2text-generation\", \"summarization\"):\n                model = AutoModelForSeq2SeqLM.from_pretrained(model_id, **_model_kwargs)\n            else:\n                raise ValueError(\n                    f\"Got invalid task {task}, \"\n                    f\"currently only {VALID_TASKS} are supported\"\n                )\n        except ImportError as e:\n            raise ValueError(\n                f\"Could not load the {task} model due to missing dependencies.\"\n            ) from e\n        if tokenizer.pad_token is None:\n            tokenizer.pad_token_id = model.config.eos_token_id\n        if (\n            getattr(model, \"is_loaded_in_4bit\", False)\n            or getattr(model, \"is_loaded_in_8bit\", False)\n        ) and device is not None:\n            logger.warning(\n                f\"Setting the `device` argument to None from {device} to avoid \"\n                \"the error caused by attempting to move the model that was already \"\n                \"loaded on the GPU using the Accelerate module to the same or \"\n                \"another device.\"\n            )\n            device = None\n        if device is not None and importlib.util.find_spec(\"torch\") is not None:\n            import torch\n            cuda_device_count = torch.cuda.device_count()\n            if device < -1 or (device >= cuda_device_count):\n                raise ValueError(\n                    f\"Got device=={device}, \"\n                    f\"device is required to be within [-1, {cuda_device_count})\"\n                )\n            if device_map is not None and device < 0:\n                device = None\n            if device is not None and device < 0 and cuda_device_count > 0:\n                logger.warning(\n                    \"Device has %d GPUs available. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html"}
{"id": "1bb0135bde89-3", "text": "logger.warning(\n                    \"Device has %d GPUs available. \"\n                    \"Provide device={deviceId} to `from_model_id` to use available\"\n                    \"GPUs for execution. deviceId is -1 (default) for CPU and \"\n                    \"can be a positive integer associated with CUDA device id.\",\n                    cuda_device_count,\n                )\n        if \"trust_remote_code\" in _model_kwargs:\n            _model_kwargs = {\n                k: v for k, v in _model_kwargs.items() if k != \"trust_remote_code\"\n            }\n        _pipeline_kwargs = pipeline_kwargs or {}\n        pipeline = hf_pipeline(\n            task=task,\n            model=model,\n            tokenizer=tokenizer,\n            device=device,\n            device_map=device_map,\n            batch_size=batch_size,\n            model_kwargs=_model_kwargs,\n            **_pipeline_kwargs,\n        )\n        if pipeline.task not in VALID_TASKS:\n            raise ValueError(\n                f\"Got invalid task {pipeline.task}, \"\n                f\"currently only {VALID_TASKS} are supported\"\n            )\n        return cls(\n            pipeline=pipeline,\n            model_id=model_id,\n            model_kwargs=_model_kwargs,\n            pipeline_kwargs=_pipeline_kwargs,\n            batch_size=batch_size,\n            **kwargs,\n        )\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"model_id\": self.model_id,\n            \"model_kwargs\": self.model_kwargs,\n            \"pipeline_kwargs\": self.pipeline_kwargs,\n        }\n    @property\n    def _llm_type(self) -> str:\n        return \"huggingface_pipeline\"\n    def _generate(\n        self,\n        prompts: List[str],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html"}
{"id": "1bb0135bde89-4", "text": "def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        # List to hold all results\n        text_generations: List[str] = []\n        for i in range(0, len(prompts), self.batch_size):\n            batch_prompts = prompts[i : i + self.batch_size]\n            # Process batch of prompts\n            responses = self.pipeline(batch_prompts)\n            # Process each response in the batch\n            for j, response in enumerate(responses):\n                if isinstance(response, list):\n                    # if model returns multiple generations, pick the top one\n                    response = response[0]\n                if self.pipeline.task == \"text-generation\":\n                    try:\n                        from transformers.pipelines.text_generation import ReturnType\n                        remove_prompt = (\n                            self.pipeline._postprocess_params.get(\"return_type\")\n                            != ReturnType.NEW_TEXT\n                        )\n                    except Exception as e:\n                        logger.warning(\n                            f\"Unable to extract pipeline return_type. \"\n                            f\"Received error:\\n\\n{e}\"\n                        )\n                        remove_prompt = True\n                    if remove_prompt:\n                        text = response[\"generated_text\"][len(batch_prompts[j]) :]\n                    else:\n                        text = response[\"generated_text\"]\n                elif self.pipeline.task == \"text2text-generation\":\n                    text = response[\"generated_text\"]\n                elif self.pipeline.task == \"summarization\":\n                    text = response[\"summary_text\"]\n                else:\n                    raise ValueError(\n                        f\"Got invalid task {self.pipeline.task}, \"\n                        f\"currently only {VALID_TASKS} are supported\"\n                    )\n                if stop:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html"}
{"id": "1bb0135bde89-5", "text": ")\n                if stop:\n                    # Enforce stop tokens\n                    text = enforce_stop_tokens(text, stop)\n                # Append the processed text to results\n                text_generations.append(text)\n        return LLMResult(\n            generations=[[Generation(text=text)] for text in text_generations]\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html"}
{"id": "9e987a642600-0", "text": "Source code for langchain.llms.gigachat\nfrom __future__ import annotations\nimport logging\nfrom functools import cached_property\nfrom typing import Any, AsyncIterator, Dict, Iterator, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import BaseLLM\nfrom langchain.load.serializable import Serializable\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema.output import Generation, GenerationChunk, LLMResult\nlogger = logging.getLogger(__name__)\nclass _BaseGigaChat(Serializable):\n    base_url: Optional[str] = None\n    \"\"\" Base API URL \"\"\"\n    auth_url: Optional[str] = None\n    \"\"\" Auth URL \"\"\"\n    credentials: Optional[str] = None\n    \"\"\" Auth Token \"\"\"\n    scope: Optional[str] = None\n    \"\"\" Permission scope for access token \"\"\"\n    access_token: Optional[str] = None\n    \"\"\" Access token for GigaChat \"\"\"\n    model: Optional[str] = None\n    \"\"\"Model name to use.\"\"\"\n    user: Optional[str] = None\n    \"\"\" Username for authenticate \"\"\"\n    password: Optional[str] = None\n    \"\"\" Password for authenticate \"\"\"\n    timeout: Optional[float] = None\n    \"\"\" Timeout for request \"\"\"\n    verify_ssl_certs: Optional[bool] = None\n    \"\"\" Check certificates for all requests \"\"\"\n    ca_bundle_file: Optional[str] = None\n    cert_file: Optional[str] = None\n    key_file: Optional[str] = None\n    key_file_password: Optional[str] = None\n    # Support for connection to GigaChat through SSL certificates\n    profanity: bool = True\n    \"\"\" Check for profanity \"\"\"\n    streaming: bool = False\n    \"\"\" Whether to stream the results or not. \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gigachat.html"}
{"id": "9e987a642600-1", "text": "streaming: bool = False\n    \"\"\" Whether to stream the results or not. \"\"\"\n    temperature: Optional[float] = None\n    \"\"\"What sampling temperature to use.\"\"\"\n    max_tokens: Optional[int] = None\n    \"\"\" Maximum number of tokens to generate \"\"\"\n    @property\n    def _llm_type(self) -> str:\n        return \"giga-chat-model\"\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\n            \"credentials\": \"GIGACHAT_CREDENTIALS\",\n            \"access_token\": \"GIGACHAT_ACCESS_TOKEN\",\n            \"password\": \"GIGACHAT_PASSWORD\",\n            \"key_file_password\": \"GIGACHAT_KEY_FILE_PASSWORD\",\n        }\n    @property\n    def lc_serializable(self) -> bool:\n        return True\n    @cached_property\n    def _client(self) -> Any:\n        \"\"\"Returns GigaChat API client\"\"\"\n        import gigachat\n        return gigachat.GigaChat(\n            base_url=self.base_url,\n            auth_url=self.auth_url,\n            credentials=self.credentials,\n            scope=self.scope,\n            access_token=self.access_token,\n            model=self.model,\n            user=self.user,\n            password=self.password,\n            timeout=self.timeout,\n            verify_ssl_certs=self.verify_ssl_certs,\n            ca_bundle_file=self.ca_bundle_file,\n            cert_file=self.cert_file,\n            key_file=self.key_file,\n            key_file_password=self.key_file_password,\n        )\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate authenticate data in environment and python package is installed.\"\"\"\n        try:\n            import gigachat  # noqa: F401\n        except ImportError:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gigachat.html"}
{"id": "9e987a642600-2", "text": "except ImportError:\n            raise ImportError(\n                \"Could not import gigachat python package. \"\n                \"Please install it with `pip install gigachat`.\"\n            )\n        return values\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"temperature\": self.temperature,\n            \"model\": self.model,\n            \"profanity\": self.profanity,\n            \"streaming\": self.streaming,\n            \"max_tokens\": self.max_tokens,\n        }\n[docs]class GigaChat(_BaseGigaChat, BaseLLM):\n    \"\"\"`GigaChat` large language models API.\n    To use, you should pass login and password to access GigaChat API or use token.\n    Example:\n        .. code-block:: python\n            from langchain.llms import GigaChat\n            giga = GigaChat(credentials=..., verify_ssl_certs=False)\n    \"\"\"\n    def _build_payload(self, messages: List[str]) -> Dict[str, Any]:\n        payload: Dict[str, Any] = {\n            \"messages\": [{\"role\": \"user\", \"content\": m} for m in messages],\n            \"profanity_check\": self.profanity,\n        }\n        if self.temperature is not None:\n            payload[\"temperature\"] = self.temperature\n        if self.max_tokens is not None:\n            payload[\"max_tokens\"] = self.max_tokens\n        if self.model:\n            payload[\"model\"] = self.model\n        if self.verbose:\n            logger.info(\"Giga request: %s\", payload)\n        return payload\n    def _create_llm_result(self, response: Any) -> LLMResult:\n        generations = []\n        for res in response.choices:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gigachat.html"}
{"id": "9e987a642600-3", "text": "generations = []\n        for res in response.choices:\n            finish_reason = res.finish_reason\n            gen = Generation(\n                text=res.message.content,\n                generation_info={\"finish_reason\": finish_reason},\n            )\n            generations.append([gen])\n            if finish_reason != \"stop\":\n                logger.warning(\n                    \"Giga generation stopped with reason: %s\",\n                    finish_reason,\n                )\n            if self.verbose:\n                logger.info(\"Giga response: %s\", res.message.content)\n        token_usage = response.usage\n        llm_output = {\"token_usage\": token_usage, \"model_name\": response.model}\n        return LLMResult(generations=generations, llm_output=llm_output)\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        should_stream = stream if stream is not None else self.streaming\n        if should_stream:\n            generation: Optional[GenerationChunk] = None\n            stream_iter = self._stream(\n                prompts[0], stop=stop, run_manager=run_manager, **kwargs\n            )\n            for chunk in stream_iter:\n                if generation is None:\n                    generation = chunk\n                else:\n                    generation += chunk\n            assert generation is not None\n            return LLMResult(generations=[[generation]])\n        payload = self._build_payload(prompts)\n        response = self._client.chat(payload)\n        return self._create_llm_result(response)\n    async def _agenerate(\n        self,\n        prompts: List[str],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gigachat.html"}
{"id": "9e987a642600-4", "text": "async def _agenerate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        stream: Optional[bool] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        should_stream = stream if stream is not None else self.streaming\n        if should_stream:\n            generation: Optional[GenerationChunk] = None\n            stream_iter = self._astream(\n                prompts[0], stop=stop, run_manager=run_manager, **kwargs\n            )\n            async for chunk in stream_iter:\n                if generation is None:\n                    generation = chunk\n                else:\n                    generation += chunk\n            assert generation is not None\n            return LLMResult(generations=[[generation]])\n        payload = self._build_payload(prompts)\n        response = await self._client.achat(payload)\n        return self._create_llm_result(response)\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        payload = self._build_payload([prompt])\n        for chunk in self._client.stream(payload):\n            if chunk.choices:\n                content = chunk.choices[0].delta.content\n                yield GenerationChunk(text=content)\n                if run_manager:\n                    run_manager.on_llm_new_token(content)\n    async def _astream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gigachat.html"}
{"id": "9e987a642600-5", "text": "**kwargs: Any,\n    ) -> AsyncIterator[GenerationChunk]:\n        payload = self._build_payload([prompt])\n        async for chunk in self._client.astream(payload):\n            if chunk.choices:\n                content = chunk.choices[0].delta.content\n                yield GenerationChunk(text=content)\n                if run_manager:\n                    await run_manager.on_llm_new_token(content)\n[docs]    def get_num_tokens(self, text: str) -> int:\n        \"\"\"Count approximate number of tokens\"\"\"\n        return round(len(text) / 4.6)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gigachat.html"}
{"id": "d3adf7627ac8-0", "text": "Source code for langchain.llms.titan_takeoff\nfrom typing import Any, Iterator, List, Mapping, Optional\nimport requests\nfrom requests.exceptions import ConnectionError\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.schema.output import GenerationChunk\n[docs]class TitanTakeoff(LLM):\n    \"\"\"Wrapper around Titan Takeoff APIs.\"\"\"\n    base_url: str = \"http://localhost:8000\"\n    \"\"\"Specifies the baseURL to use for the Titan Takeoff API. \n    Default = http://localhost:8000.\n    \"\"\"\n    generate_max_length: int = 128\n    \"\"\"Maximum generation length. Default = 128.\"\"\"\n    sampling_topk: int = 1\n    \"\"\"Sample predictions from the top K most probable candidates. Default = 1.\"\"\"\n    sampling_topp: float = 1.0\n    \"\"\"Sample from predictions whose cumulative probability exceeds this value.\n    Default = 1.0.\n    \"\"\"\n    sampling_temperature: float = 1.0\n    \"\"\"Sample with randomness. Bigger temperatures are associated with \n    more randomness and 'creativity'. Default = 1.0.\n    \"\"\"\n    repetition_penalty: float = 1.0\n    \"\"\"Penalise the generation of tokens that have been generated before. \n    Set to > 1 to penalize. Default = 1 (no penalty).\n    \"\"\"\n    no_repeat_ngram_size: int = 0\n    \"\"\"Prevent repetitions of ngrams of this size. Default = 0 (turned off).\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the output. Default = False.\"\"\"\n    @property\n    def _default_params(self) -> Mapping[str, Any]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff.html"}
{"id": "d3adf7627ac8-1", "text": "@property\n    def _default_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the default parameters for calling Titan Takeoff Server.\"\"\"\n        params = {\n            \"generate_max_length\": self.generate_max_length,\n            \"sampling_topk\": self.sampling_topk,\n            \"sampling_topp\": self.sampling_topp,\n            \"sampling_temperature\": self.sampling_temperature,\n            \"repetition_penalty\": self.repetition_penalty,\n            \"no_repeat_ngram_size\": self.no_repeat_ngram_size,\n        }\n        return params\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"titan_takeoff\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Titan Takeoff generate endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                prompt = \"What is the capital of the United Kingdom?\"\n                response = model(prompt)\n        \"\"\"\n        try:\n            if self.streaming:\n                text_output = \"\"\n                for chunk in self._stream(\n                    prompt=prompt,\n                    stop=stop,\n                    run_manager=run_manager,\n                ):\n                    text_output += chunk.text\n                return text_output\n            url = f\"{self.base_url}/generate\"\n            params = {\"text\": prompt, **self._default_params}\n            response = requests.post(url, json=params)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff.html"}
{"id": "d3adf7627ac8-2", "text": "response = requests.post(url, json=params)\n            response.raise_for_status()\n            response.encoding = \"utf-8\"\n            text = \"\"\n            if \"message\" in response.json():\n                text = response.json()[\"message\"]\n            else:\n                raise ValueError(\"Something went wrong.\")\n            if stop is not None:\n                text = enforce_stop_tokens(text, stop)\n            return text\n        except ConnectionError:\n            raise ConnectionError(\n                \"Could not connect to Titan Takeoff server. \\\n                Please make sure that the server is running.\"\n            )\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        \"\"\"Call out to Titan Takeoff stream endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Yields:\n            A dictionary like object containing a string token.\n        Example:\n            .. code-block:: python\n                prompt = \"What is the capital of the United Kingdom?\"\n                response = model(prompt)\n        \"\"\"\n        url = f\"{self.base_url}/generate_stream\"\n        params = {\"text\": prompt, **self._default_params}\n        response = requests.post(url, json=params, stream=True)\n        response.encoding = \"utf-8\"\n        for text in response.iter_content(chunk_size=1, decode_unicode=True):\n            if text:\n                chunk = GenerationChunk(text=text)\n                yield chunk\n                if run_manager:\n                    run_manager.on_llm_new_token(token=chunk.text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff.html"}
{"id": "d3adf7627ac8-3", "text": "if run_manager:\n                    run_manager.on_llm_new_token(token=chunk.text)\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\"base_url\": self.base_url, **{}, **self._default_params}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff.html"}
{"id": "363e03dcb9c2-0", "text": "Source code for langchain.llms.promptlayer_openai\nimport datetime\nfrom typing import Any, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.openai import OpenAI, OpenAIChat\nfrom langchain.schema import LLMResult\n[docs]class PromptLayerOpenAI(OpenAI):\n    \"\"\"PromptLayer OpenAI large language models.\n    To use, you should have the ``openai`` and ``promptlayer`` python\n    package installed, and the environment variable ``OPENAI_API_KEY``\n    and ``PROMPTLAYER_API_KEY`` set with your openAI API key and\n    promptlayer key respectively.\n    All parameters that can be passed to the OpenAI LLM can also\n    be passed here. The PromptLayerOpenAI LLM adds two optional\n    parameters:\n        ``pl_tags``: List of strings to tag the request with.\n        ``return_pl_id``: If True, the PromptLayer request ID will be\n            returned in the ``generation_info`` field of the\n            ``Generation`` object.\n    Example:\n        .. code-block:: python\n            from langchain.llms import PromptLayerOpenAI\n            openai = PromptLayerOpenAI(model_name=\"text-davinci-003\")\n    \"\"\"\n    pl_tags: Optional[List[str]]\n    return_pl_id: Optional[bool] = False\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Call OpenAI generate and then call PromptLayer API to log the request.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html"}
{"id": "363e03dcb9c2-1", "text": "\"\"\"Call OpenAI generate and then call PromptLayer API to log the request.\"\"\"\n        from promptlayer.utils import get_api_key, promptlayer_api_request\n        request_start_time = datetime.datetime.now().timestamp()\n        generated_responses = super()._generate(prompts, stop, run_manager)\n        request_end_time = datetime.datetime.now().timestamp()\n        for i in range(len(prompts)):\n            prompt = prompts[i]\n            generation = generated_responses.generations[i][0]\n            resp = {\n                \"text\": generation.text,\n                \"llm_output\": generated_responses.llm_output,\n            }\n            params = {**self._identifying_params, **kwargs}\n            pl_request_id = promptlayer_api_request(\n                \"langchain.PromptLayerOpenAI\",\n                \"langchain\",\n                [prompt],\n                params,\n                self.pl_tags,\n                resp,\n                request_start_time,\n                request_end_time,\n                get_api_key(),\n                return_pl_id=self.return_pl_id,\n            )\n            if self.return_pl_id:\n                if generation.generation_info is None or not isinstance(\n                    generation.generation_info, dict\n                ):\n                    generation.generation_info = {}\n                generation.generation_info[\"pl_request_id\"] = pl_request_id\n        return generated_responses\n    async def _agenerate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        from promptlayer.utils import get_api_key, promptlayer_api_request_async\n        request_start_time = datetime.datetime.now().timestamp()\n        generated_responses = await super()._agenerate(prompts, stop, run_manager)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html"}
{"id": "363e03dcb9c2-2", "text": "generated_responses = await super()._agenerate(prompts, stop, run_manager)\n        request_end_time = datetime.datetime.now().timestamp()\n        for i in range(len(prompts)):\n            prompt = prompts[i]\n            generation = generated_responses.generations[i][0]\n            resp = {\n                \"text\": generation.text,\n                \"llm_output\": generated_responses.llm_output,\n            }\n            params = {**self._identifying_params, **kwargs}\n            pl_request_id = await promptlayer_api_request_async(\n                \"langchain.PromptLayerOpenAI.async\",\n                \"langchain\",\n                [prompt],\n                params,\n                self.pl_tags,\n                resp,\n                request_start_time,\n                request_end_time,\n                get_api_key(),\n                return_pl_id=self.return_pl_id,\n            )\n            if self.return_pl_id:\n                if generation.generation_info is None or not isinstance(\n                    generation.generation_info, dict\n                ):\n                    generation.generation_info = {}\n                generation.generation_info[\"pl_request_id\"] = pl_request_id\n        return generated_responses\n[docs]class PromptLayerOpenAIChat(OpenAIChat):\n    \"\"\"Wrapper around OpenAI large language models.\n    To use, you should have the ``openai`` and ``promptlayer`` python\n    package installed, and the environment variable ``OPENAI_API_KEY``\n    and ``PROMPTLAYER_API_KEY`` set with your openAI API key and\n    promptlayer key respectively.\n    All parameters that can be passed to the OpenAIChat LLM can also\n    be passed here. The PromptLayerOpenAIChat adds two optional\n    parameters:\n        ``pl_tags``: List of strings to tag the request with.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html"}
{"id": "363e03dcb9c2-3", "text": "parameters:\n        ``pl_tags``: List of strings to tag the request with.\n        ``return_pl_id``: If True, the PromptLayer request ID will be\n            returned in the ``generation_info`` field of the\n            ``Generation`` object.\n    Example:\n        .. code-block:: python\n            from langchain.llms import PromptLayerOpenAIChat\n            openaichat = PromptLayerOpenAIChat(model_name=\"gpt-3.5-turbo\")\n    \"\"\"\n    pl_tags: Optional[List[str]]\n    return_pl_id: Optional[bool] = False\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Call OpenAI generate and then call PromptLayer API to log the request.\"\"\"\n        from promptlayer.utils import get_api_key, promptlayer_api_request\n        request_start_time = datetime.datetime.now().timestamp()\n        generated_responses = super()._generate(prompts, stop, run_manager)\n        request_end_time = datetime.datetime.now().timestamp()\n        for i in range(len(prompts)):\n            prompt = prompts[i]\n            generation = generated_responses.generations[i][0]\n            resp = {\n                \"text\": generation.text,\n                \"llm_output\": generated_responses.llm_output,\n            }\n            params = {**self._identifying_params, **kwargs}\n            pl_request_id = promptlayer_api_request(\n                \"langchain.PromptLayerOpenAIChat\",\n                \"langchain\",\n                [prompt],\n                params,\n                self.pl_tags,\n                resp,\n                request_start_time,\n                request_end_time,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html"}
{"id": "363e03dcb9c2-4", "text": "resp,\n                request_start_time,\n                request_end_time,\n                get_api_key(),\n                return_pl_id=self.return_pl_id,\n            )\n            if self.return_pl_id:\n                if generation.generation_info is None or not isinstance(\n                    generation.generation_info, dict\n                ):\n                    generation.generation_info = {}\n                generation.generation_info[\"pl_request_id\"] = pl_request_id\n        return generated_responses\n    async def _agenerate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        from promptlayer.utils import get_api_key, promptlayer_api_request_async\n        request_start_time = datetime.datetime.now().timestamp()\n        generated_responses = await super()._agenerate(prompts, stop, run_manager)\n        request_end_time = datetime.datetime.now().timestamp()\n        for i in range(len(prompts)):\n            prompt = prompts[i]\n            generation = generated_responses.generations[i][0]\n            resp = {\n                \"text\": generation.text,\n                \"llm_output\": generated_responses.llm_output,\n            }\n            params = {**self._identifying_params, **kwargs}\n            pl_request_id = await promptlayer_api_request_async(\n                \"langchain.PromptLayerOpenAIChat.async\",\n                \"langchain\",\n                [prompt],\n                params,\n                self.pl_tags,\n                resp,\n                request_start_time,\n                request_end_time,\n                get_api_key(),\n                return_pl_id=self.return_pl_id,\n            )\n            if self.return_pl_id:\n                if generation.generation_info is None or not isinstance(\n                    generation.generation_info, dict", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html"}
{"id": "363e03dcb9c2-5", "text": "generation.generation_info, dict\n                ):\n                    generation.generation_info = {}\n                generation.generation_info[\"pl_request_id\"] = pl_request_id\n        return generated_responses", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html"}
{"id": "c860d32942c2-0", "text": "Source code for langchain.llms.manifest\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Extra, root_validator\n[docs]class ManifestWrapper(LLM):\n    \"\"\"HazyResearch's Manifest library.\"\"\"\n    client: Any  #: :meta private:\n    llm_kwargs: Optional[Dict] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that python package exists in environment.\"\"\"\n        try:\n            from manifest import Manifest\n            if not isinstance(values[\"client\"], Manifest):\n                raise ValueError\n        except ImportError:\n            raise ImportError(\n                \"Could not import manifest python package. \"\n                \"Please install it with `pip install manifest-ml`.\"\n            )\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        kwargs = self.llm_kwargs or {}\n        return {\n            **self.client.client_pool.get_current_client().get_model_params(),\n            **kwargs,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"manifest\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to LLM through Manifest.\"\"\"\n        if stop is not None and len(stop) != 1:\n            raise NotImplementedError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/manifest.html"}
{"id": "c860d32942c2-1", "text": "if stop is not None and len(stop) != 1:\n            raise NotImplementedError(\n                f\"Manifest currently only supports a single stop token, got {stop}\"\n            )\n        params = self.llm_kwargs or {}\n        params = {**params, **kwargs}\n        if stop is not None:\n            params[\"stop_token\"] = stop\n        return self.client.run(prompt, **params)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/manifest.html"}
{"id": "02030726671a-0", "text": "Source code for langchain.llms.ai21\nfrom typing import Any, Dict, List, Optional, cast\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import BaseModel, Extra, SecretStr, root_validator\nfrom langchain.utils import convert_to_secret_str, get_from_dict_or_env\n[docs]class AI21PenaltyData(BaseModel):\n    \"\"\"Parameters for AI21 penalty data.\"\"\"\n    scale: int = 0\n    applyToWhitespaces: bool = True\n    applyToPunctuations: bool = True\n    applyToNumbers: bool = True\n    applyToStopwords: bool = True\n    applyToEmojis: bool = True\n[docs]class AI21(LLM):\n    \"\"\"AI21 large language models.\n    To use, you should have the environment variable ``AI21_API_KEY``\n    set with your API key or pass it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.llms import AI21\n            ai21 = AI21(ai21_api_key=\"my-api-key\", model=\"j2-jumbo-instruct\")\n    \"\"\"\n    model: str = \"j2-jumbo-instruct\"\n    \"\"\"Model name to use.\"\"\"\n    temperature: float = 0.7\n    \"\"\"What sampling temperature to use.\"\"\"\n    maxTokens: int = 256\n    \"\"\"The maximum number of tokens to generate in the completion.\"\"\"\n    minTokens: int = 0\n    \"\"\"The minimum number of tokens to generate in the completion.\"\"\"\n    topP: float = 1.0\n    \"\"\"Total probability mass of tokens to consider at each step.\"\"\"\n    presencePenalty: AI21PenaltyData = AI21PenaltyData()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html"}
{"id": "02030726671a-1", "text": "presencePenalty: AI21PenaltyData = AI21PenaltyData()\n    \"\"\"Penalizes repeated tokens.\"\"\"\n    countPenalty: AI21PenaltyData = AI21PenaltyData()\n    \"\"\"Penalizes repeated tokens according to count.\"\"\"\n    frequencyPenalty: AI21PenaltyData = AI21PenaltyData()\n    \"\"\"Penalizes repeated tokens according to frequency.\"\"\"\n    numResults: int = 1\n    \"\"\"How many completions to generate for each prompt.\"\"\"\n    logitBias: Optional[Dict[str, float]] = None\n    \"\"\"Adjust the probability of specific tokens being generated.\"\"\"\n    ai21_api_key: Optional[SecretStr] = None\n    stop: Optional[List[str]] = None\n    base_url: Optional[str] = None\n    \"\"\"Base url to use, if None decides based on model name.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key exists in environment.\"\"\"\n        ai21_api_key = convert_to_secret_str(\n            get_from_dict_or_env(values, \"ai21_api_key\", \"AI21_API_KEY\")\n        )\n        values[\"ai21_api_key\"] = ai21_api_key\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling AI21 API.\"\"\"\n        return {\n            \"temperature\": self.temperature,\n            \"maxTokens\": self.maxTokens,\n            \"minTokens\": self.minTokens,\n            \"topP\": self.topP,\n            \"presencePenalty\": self.presencePenalty.dict(),\n            \"countPenalty\": self.countPenalty.dict(),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html"}
{"id": "02030726671a-2", "text": "\"countPenalty\": self.countPenalty.dict(),\n            \"frequencyPenalty\": self.frequencyPenalty.dict(),\n            \"numResults\": self.numResults,\n            \"logitBias\": self.logitBias,\n        }\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model\": self.model}, **self._default_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"ai21\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to AI21's complete endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = ai21(\"Tell me a joke.\")\n        \"\"\"\n        if self.stop is not None and stop is not None:\n            raise ValueError(\"`stop` found in both the input and default params.\")\n        elif self.stop is not None:\n            stop = self.stop\n        elif stop is None:\n            stop = []\n        if self.base_url is not None:\n            base_url = self.base_url\n        else:\n            if self.model in (\"j1-grande-instruct\",):\n                base_url = \"https://api.ai21.com/studio/v1/experimental\"\n            else:\n                base_url = \"https://api.ai21.com/studio/v1\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html"}
{"id": "02030726671a-3", "text": "base_url = \"https://api.ai21.com/studio/v1\"\n        params = {**self._default_params, **kwargs}\n        self.ai21_api_key = cast(SecretStr, self.ai21_api_key)\n        response = requests.post(\n            url=f\"{base_url}/{self.model}/complete\",\n            headers={\"Authorization\": f\"Bearer {self.ai21_api_key.get_secret_value()}\"},\n            json={\"prompt\": prompt, \"stopSequences\": stop, **params},\n        )\n        if response.status_code != 200:\n            optional_detail = response.json().get(\"error\")\n            raise ValueError(\n                f\"AI21 /complete call failed with status code {response.status_code}.\"\n                f\" Details: {optional_detail}\"\n            )\n        response_json = response.json()\n        return response_json[\"completions\"][0][\"data\"][\"text\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html"}
{"id": "0e61e5288e31-0", "text": "Source code for langchain.llms.mlflow_ai_gateway\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import BaseModel, Extra\n# Ignoring type because below is valid pydantic code\n# Unexpected keyword argument \"extra\" for \"__init_subclass__\" of \"object\"\n[docs]class Params(BaseModel, extra=Extra.allow):  # type: ignore[call-arg]\n    \"\"\"Parameters for the MLflow AI Gateway LLM.\"\"\"\n    temperature: float = 0.0\n    candidate_count: int = 1\n    \"\"\"The number of candidates to return.\"\"\"\n    stop: Optional[List[str]] = None\n    max_tokens: Optional[int] = None\n[docs]class MlflowAIGateway(LLM):\n    \"\"\"\n    Wrapper around completions LLMs in the MLflow AI Gateway.\n    To use, you should have the ``mlflow[gateway]`` python package installed.\n    For more information, see https://mlflow.org/docs/latest/gateway/index.html.\n    Example:\n        .. code-block:: python\n            from langchain.llms import MlflowAIGateway\n            completions = MlflowAIGateway(\n                gateway_uri=\"<your-mlflow-ai-gateway-uri>\",\n                route=\"<your-mlflow-ai-gateway-completions-route>\",\n                params={\n                    \"temperature\": 0.1\n                }\n            )\n    \"\"\"\n    route: str\n    gateway_uri: Optional[str] = None\n    params: Optional[Params] = None\n    def __init__(self, **kwargs: Any):\n        try:\n            import mlflow.gateway", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mlflow_ai_gateway.html"}
{"id": "0e61e5288e31-1", "text": "try:\n            import mlflow.gateway\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import `mlflow.gateway` module. \"\n                \"Please install it with `pip install mlflow[gateway]`.\"\n            ) from e\n        super().__init__(**kwargs)\n        if self.gateway_uri:\n            mlflow.gateway.set_gateway_uri(self.gateway_uri)\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        params: Dict[str, Any] = {\n            \"gateway_uri\": self.gateway_uri,\n            \"route\": self.route,\n            **(self.params.dict() if self.params else {}),\n        }\n        return params\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        return self._default_params\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        try:\n            import mlflow.gateway\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import `mlflow.gateway` module. \"\n                \"Please install it with `pip install mlflow[gateway]`.\"\n            ) from e\n        data: Dict[str, Any] = {\n            \"prompt\": prompt,\n            **(self.params.dict() if self.params else {}),\n        }\n        if s := (stop or (self.params.stop if self.params else None)):\n            data[\"stop\"] = s\n        resp = mlflow.gateway.query(self.route, data=data)\n        return resp[\"candidates\"][0][\"text\"]\n    @property\n    def _llm_type(self) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mlflow_ai_gateway.html"}
{"id": "0e61e5288e31-2", "text": "@property\n    def _llm_type(self) -> str:\n        return \"mlflow-ai-gateway\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mlflow_ai_gateway.html"}
{"id": "3f746b5cba90-0", "text": "Source code for langchain.llms.mosaicml\nfrom typing import Any, Dict, List, Mapping, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\nINSTRUCTION_KEY = \"### Instruction:\"\nRESPONSE_KEY = \"### Response:\"\nINTRO_BLURB = (\n    \"Below is an instruction that describes a task. \"\n    \"Write a response that appropriately completes the request.\"\n)\nPROMPT_FOR_GENERATION_FORMAT = \"\"\"{intro}\n{instruction_key}\n{instruction}\n{response_key}\n\"\"\".format(\n    intro=INTRO_BLURB,\n    instruction_key=INSTRUCTION_KEY,\n    instruction=\"{instruction}\",\n    response_key=RESPONSE_KEY,\n)\n[docs]class MosaicML(LLM):\n    \"\"\"MosaicML LLM service.\n    To use, you should have the\n    environment variable ``MOSAICML_API_TOKEN`` set with your API token, or pass\n    it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.llms import MosaicML\n            endpoint_url = (\n                \"https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict\"\n            )\n            mosaic_llm = MosaicML(\n                endpoint_url=endpoint_url,\n                mosaicml_api_token=\"my-api-key\"\n            )\n    \"\"\"\n    endpoint_url: str = (\n        \"https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict\"\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html"}
{"id": "3f746b5cba90-1", "text": ")\n    \"\"\"Endpoint URL to use.\"\"\"\n    inject_instruction_format: bool = False\n    \"\"\"Whether to inject the instruction format into the prompt.\"\"\"\n    model_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    retry_sleep: float = 1.0\n    \"\"\"How long to try sleeping for if a rate limit is encountered\"\"\"\n    mosaicml_api_token: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        mosaicml_api_token = get_from_dict_or_env(\n            values, \"mosaicml_api_token\", \"MOSAICML_API_TOKEN\"\n        )\n        values[\"mosaicml_api_token\"] = mosaicml_api_token\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {\n            **{\"endpoint_url\": self.endpoint_url},\n            **{\"model_kwargs\": _model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"mosaic\"\n    def _transform_prompt(self, prompt: str) -> str:\n        \"\"\"Transform prompt.\"\"\"\n        if self.inject_instruction_format:\n            prompt = PROMPT_FOR_GENERATION_FORMAT.format(\n                instruction=prompt,\n            )\n        return prompt\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html"}
{"id": "3f746b5cba90-2", "text": "prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        is_retry: bool = False,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to a MosaicML LLM inference endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = mosaic_llm(\"Tell me a joke.\")\n        \"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        prompt = self._transform_prompt(prompt)\n        payload = {\"inputs\": [prompt]}\n        payload.update(_model_kwargs)\n        payload.update(kwargs)\n        # HTTP headers for authorization\n        headers = {\n            \"Authorization\": f\"{self.mosaicml_api_token}\",\n            \"Content-Type\": \"application/json\",\n        }\n        # send request\n        try:\n            response = requests.post(self.endpoint_url, headers=headers, json=payload)\n        except requests.exceptions.RequestException as e:\n            raise ValueError(f\"Error raised by inference endpoint: {e}\")\n        try:\n            if response.status_code == 429:\n                if not is_retry:\n                    import time\n                    time.sleep(self.retry_sleep)\n                    return self._call(prompt, stop, run_manager, is_retry=True)\n                raise ValueError(\n                    f\"Error raised by inference API: rate limit exceeded.\\nResponse: \"\n                    f\"{response.text}\"\n                )\n            parsed_response = response.json()\n            # The inference API has changed a couple of times, so we add some handling\n            # to be robust to multiple response formats.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html"}
{"id": "3f746b5cba90-3", "text": "# to be robust to multiple response formats.\n            if isinstance(parsed_response, dict):\n                output_keys = [\"data\", \"output\", \"outputs\"]\n                for key in output_keys:\n                    if key in parsed_response:\n                        output_item = parsed_response[key]\n                        break\n                else:\n                    raise ValueError(\n                        f\"No valid key ({', '.join(output_keys)}) in response:\"\n                        f\" {parsed_response}\"\n                    )\n                if isinstance(output_item, list):\n                    text = output_item[0]\n                else:\n                    text = output_item\n            else:\n                raise ValueError(f\"Unexpected response type: {parsed_response}\")\n            # Older versions of the API include the input in the output response\n            if text.startswith(prompt):\n                text = text[len(prompt) :]\n        except requests.exceptions.JSONDecodeError as e:\n            raise ValueError(\n                f\"Error raised by inference API: {e}.\\nResponse: {response.text}\"\n            )\n        # TODO: replace when MosaicML supports custom stop tokens natively\n        if stop is not None:\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html"}
{"id": "4d2648316a32-0", "text": "Source code for langchain.llms.gradient_ai\nimport asyncio\nimport logging\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import Any, Dict, List, Mapping, Optional, Sequence, TypedDict\nimport aiohttp\nimport requests\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import BaseLLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.schema import Generation, LLMResult\nfrom langchain.utils import get_from_dict_or_env\n[docs]class TrainResult(TypedDict):\n    \"\"\"Train result.\"\"\"\n    loss: float\n[docs]class GradientLLM(BaseLLM):\n    \"\"\"Gradient.ai LLM Endpoints.\n    GradientLLM is a class to interact with LLMs on gradient.ai\n    To use, set the environment variable ``GRADIENT_ACCESS_TOKEN`` with your\n    API token and ``GRADIENT_WORKSPACE_ID`` for your gradient workspace,\n    or alternatively provide them as keywords to the constructor of this class.\n    Example:\n        .. code-block:: python\n            from langchain.llms import GradientLLM\n            GradientLLM(\n                model=\"99148c6d-c2a0-4fbe-a4a7-e7c05bdb8a09_base_ml_model\",\n                model_kwargs={\n                    \"max_generated_token_count\": 128,\n                    \"temperature\": 0.75,\n                    \"top_p\": 0.95,\n                    \"top_k\": 20,\n                    \"stop\": [],\n                },\n                gradient_workspace_id=\"12345614fc0_workspace\",\n                gradient_access_token=\"gradientai-access_token\",\n            )\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html"}
{"id": "4d2648316a32-1", "text": "gradient_access_token=\"gradientai-access_token\",\n            )\n    \"\"\"\n    model_id: str = Field(alias=\"model\", min_length=2)\n    \"Underlying gradient.ai model id (base or fine-tuned).\"\n    gradient_workspace_id: Optional[str] = None\n    \"Underlying gradient.ai workspace_id.\"\n    gradient_access_token: Optional[str] = None\n    \"\"\"gradient.ai API Token, which can be generated by going to\n        https://auth.gradient.ai/select-workspace\n        and selecting \"Access tokens\" under the profile drop-down.\n    \"\"\"\n    model_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    gradient_api_url: str = \"https://api.gradient.ai/api\"\n    \"\"\"Endpoint URL to use.\"\"\"\n    aiosession: Optional[aiohttp.ClientSession] = None  #: :meta private:\n    \"\"\"ClientSession, private, subject to change in upcoming releases.\"\"\"\n    # LLM call kwargs\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        allow_population_by_field_name = True\n        extra = Extra.forbid\n    @root_validator(allow_reuse=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"gradient_access_token\"] = get_from_dict_or_env(\n            values, \"gradient_access_token\", \"GRADIENT_ACCESS_TOKEN\"\n        )\n        values[\"gradient_workspace_id\"] = get_from_dict_or_env(\n            values, \"gradient_workspace_id\", \"GRADIENT_WORKSPACE_ID\"\n        )\n        if (\n            values[\"gradient_access_token\"] is None\n            or len(values[\"gradient_access_token\"]) < 10\n        ):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html"}
{"id": "4d2648316a32-2", "text": "or len(values[\"gradient_access_token\"]) < 10\n        ):\n            raise ValueError(\"env variable `GRADIENT_ACCESS_TOKEN` must be set\")\n        if (\n            values[\"gradient_workspace_id\"] is None\n            or len(values[\"gradient_access_token\"]) < 3\n        ):\n            raise ValueError(\"env variable `GRADIENT_WORKSPACE_ID` must be set\")\n        if values[\"model_kwargs\"]:\n            kw = values[\"model_kwargs\"]\n            if not 0 <= kw.get(\"temperature\", 0.5) <= 1:\n                raise ValueError(\"`temperature` must be in the range [0.0, 1.0]\")\n            if not 0 <= kw.get(\"top_p\", 0.5) <= 1:\n                raise ValueError(\"`top_p` must be in the range [0.0, 1.0]\")\n            if 0 >= kw.get(\"top_k\", 0.5):\n                raise ValueError(\"`top_k` must be positive\")\n            if 0 >= kw.get(\"max_generated_token_count\", 1):\n                raise ValueError(\"`max_generated_token_count` must be positive\")\n        values[\"gradient_api_url\"] = get_from_dict_or_env(\n            values, \"gradient_api_url\", \"GRADIENT_API_URL\"\n        )\n        try:\n            import gradientai  # noqa\n        except ImportError:\n            logging.warning(\n                \"DeprecationWarning: `GradientLLM` will use \"\n                \"`pip install gradientai` in future releases of langchain.\"\n            )\n        except Exception:\n            pass\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html"}
{"id": "4d2648316a32-3", "text": "_model_kwargs = self.model_kwargs or {}\n        return {\n            **{\"gradient_api_url\": self.gradient_api_url},\n            **{\"model_kwargs\": _model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"gradient\"\n    def _kwargs_post_fine_tune_request(\n        self, inputs: Sequence[str], kwargs: Mapping[str, Any]\n    ) -> Mapping[str, Any]:\n        \"\"\"Build the kwargs for the Post request, used by sync\n        Args:\n            prompt (str): prompt used in query\n            kwargs (dict): model kwargs in payload\n        Returns:\n            Dict[str, Union[str,dict]]: _description_\n        \"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        _params = {**_model_kwargs, **kwargs}\n        multipliers = _params.get(\"multipliers\", None)\n        return dict(\n            url=f\"{self.gradient_api_url}/models/{self.model_id}/fine-tune\",\n            headers={\n                \"authorization\": f\"Bearer {self.gradient_access_token}\",\n                \"x-gradient-workspace-id\": f\"{self.gradient_workspace_id}\",\n                \"accept\": \"application/json\",\n                \"content-type\": \"application/json\",\n            },\n            json=dict(\n                samples=tuple(\n                    {\n                        \"inputs\": input,\n                    }\n                    for input in inputs\n                )\n                if multipliers is None\n                else tuple(\n                    {\n                        \"inputs\": input,\n                        \"fineTuningParameters\": {\n                            \"multiplier\": multiplier,\n                        },\n                    }\n                    for input, multiplier in zip(inputs, multipliers)\n                ),\n            ),\n        )\n    def _kwargs_post_request(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html"}
{"id": "4d2648316a32-4", "text": "),\n            ),\n        )\n    def _kwargs_post_request(\n        self, prompt: str, kwargs: Mapping[str, Any]\n    ) -> Mapping[str, Any]:\n        \"\"\"Build the kwargs for the Post request, used by sync\n        Args:\n            prompt (str): prompt used in query\n            kwargs (dict): model kwargs in payload\n        Returns:\n            Dict[str, Union[str,dict]]: _description_\n        \"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        _params = {**_model_kwargs, **kwargs}\n        return dict(\n            url=f\"{self.gradient_api_url}/models/{self.model_id}/complete\",\n            headers={\n                \"authorization\": f\"Bearer {self.gradient_access_token}\",\n                \"x-gradient-workspace-id\": f\"{self.gradient_workspace_id}\",\n                \"accept\": \"application/json\",\n                \"content-type\": \"application/json\",\n            },\n            json=dict(\n                query=prompt,\n                maxGeneratedTokenCount=_params.get(\"max_generated_token_count\", None),\n                temperature=_params.get(\"temperature\", None),\n                topK=_params.get(\"top_k\", None),\n                topP=_params.get(\"top_p\", None),\n            ),\n        )\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call to Gradients API `model/{id}/complete`.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        \"\"\"\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html"}
{"id": "4d2648316a32-5", "text": "Returns:\n            The string generated by the model.\n        \"\"\"\n        try:\n            response = requests.post(**self._kwargs_post_request(prompt, kwargs))\n            if response.status_code != 200:\n                raise Exception(\n                    f\"Gradient returned an unexpected response with status \"\n                    f\"{response.status_code}: {response.text}\"\n                )\n        except requests.exceptions.RequestException as e:\n            raise Exception(f\"RequestException while calling Gradient Endpoint: {e}\")\n        text = response.json()[\"generatedOutput\"]\n        if stop is not None:\n            # Apply stop tokens when making calls to Gradient\n            text = enforce_stop_tokens(text, stop)\n        return text\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Async Call to Gradients API `model/{id}/complete`.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        \"\"\"\n        if not self.aiosession:\n            async with aiohttp.ClientSession() as session:\n                async with session.post(\n                    **self._kwargs_post_request(prompt=prompt, kwargs=kwargs)\n                ) as response:\n                    if response.status != 200:\n                        raise Exception(\n                            f\"Gradient returned an unexpected response with status \"\n                            f\"{response.status}: {response.text}\"\n                        )\n                    text = (await response.json())[\"generatedOutput\"]\n        else:\n            async with self.aiosession.post(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html"}
{"id": "4d2648316a32-6", "text": "else:\n            async with self.aiosession.post(\n                **self._kwargs_post_request(prompt=prompt, kwargs=kwargs)\n            ) as response:\n                if response.status != 200:\n                    raise Exception(\n                        f\"Gradient returned an unexpected response with status \"\n                        f\"{response.status}: {response.text}\"\n                    )\n                text = (await response.json())[\"generatedOutput\"]\n        if stop is not None:\n            # Apply stop tokens when making calls to Gradient\n            text = enforce_stop_tokens(text, stop)\n        return text\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Run the LLM on the given prompt and input.\"\"\"\n        # same thing with threading\n        def _inner_generate(prompt: str) -> List[Generation]:\n            return [\n                Generation(\n                    text=self._call(\n                        prompt=prompt, stop=stop, run_manager=run_manager, **kwargs\n                    )\n                )\n            ]\n        if len(prompts) <= 1:\n            generations = list(map(_inner_generate, prompts))\n        else:\n            with ThreadPoolExecutor(min(8, len(prompts))) as p:\n                generations = list(p.map(_inner_generate, prompts))\n        return LLMResult(generations=generations)\n    async def _agenerate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html"}
{"id": "4d2648316a32-7", "text": "**kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Run the LLM on the given prompt and input.\"\"\"\n        generations = []\n        for generation in asyncio.gather(\n            [self._acall(prompt, stop=stop, run_manager=run_manager, **kwargs)]\n            for prompt in prompts\n        ):\n            generations.append([Generation(text=generation)])\n        return LLMResult(generations=generations)\n[docs]    def train_unsupervised(\n        self,\n        inputs: Sequence[str],\n        **kwargs: Any,\n    ) -> TrainResult:\n        try:\n            response = requests.post(\n                **self._kwargs_post_fine_tune_request(inputs, kwargs)\n            )\n            if response.status_code != 200:\n                raise Exception(\n                    f\"Gradient returned an unexpected response with status \"\n                    f\"{response.status_code}: {response.text}\"\n                )\n        except requests.exceptions.RequestException as e:\n            raise Exception(f\"RequestException while calling Gradient Endpoint: {e}\")\n        response_json = response.json()\n        loss = response_json[\"sumLoss\"] / response_json[\"numberOfTrainableTokens\"]\n        return TrainResult(loss=loss)\n[docs]    async def atrain_unsupervised(\n        self,\n        inputs: Sequence[str],\n        **kwargs: Any,\n    ) -> TrainResult:\n        if not self.aiosession:\n            async with aiohttp.ClientSession() as session:\n                async with session.post(\n                    **self._kwargs_post_fine_tune_request(inputs, kwargs)\n                ) as response:\n                    if response.status != 200:\n                        raise Exception(\n                            f\"Gradient returned an unexpected response with status \"\n                            f\"{response.status}: {response.text}\"\n                        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html"}
{"id": "4d2648316a32-8", "text": "f\"{response.status}: {response.text}\"\n                        )\n                    response_json = await response.json()\n                    loss = (\n                        response_json[\"sumLoss\"]\n                        / response_json[\"numberOfTrainableTokens\"]\n                    )\n        else:\n            async with self.aiosession.post(\n                **self._kwargs_post_fine_tune_request(inputs, kwargs)\n            ) as response:\n                if response.status != 200:\n                    raise Exception(\n                        f\"Gradient returned an unexpected response with status \"\n                        f\"{response.status}: {response.text}\"\n                    )\n                response_json = await response.json()\n                loss = (\n                    response_json[\"sumLoss\"] / response_json[\"numberOfTrainableTokens\"]\n                )\n        return TrainResult(loss=loss)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html"}
{"id": "bb51a9ee8dd6-0", "text": "Source code for langchain.llms.bedrock\nimport json\nimport warnings\nfrom abc import ABC\nfrom typing import Any, Dict, Iterator, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\nfrom langchain.schema.output import GenerationChunk\nfrom langchain.utilities.anthropic import (\n    get_num_tokens_anthropic,\n    get_token_ids_anthropic,\n)\nfrom langchain.utils import get_from_dict_or_env\nHUMAN_PROMPT = \"\\n\\nHuman:\"\nASSISTANT_PROMPT = \"\\n\\nAssistant:\"\nALTERNATION_ERROR = (\n    \"Error: Prompt must alternate between '\\n\\nHuman:' and '\\n\\nAssistant:'.\"\n)\ndef _add_newlines_before_ha(input_text: str) -> str:\n    new_text = input_text\n    for word in [\"Human:\", \"Assistant:\"]:\n        new_text = new_text.replace(word, \"\\n\\n\" + word)\n        for i in range(2):\n            new_text = new_text.replace(\"\\n\\n\\n\" + word, \"\\n\\n\" + word)\n    return new_text\ndef _human_assistant_format(input_text: str) -> str:\n    if input_text.count(\"Human:\") == 0 or (\n        input_text.find(\"Human:\") > input_text.find(\"Assistant:\")\n        and \"Assistant:\" in input_text\n    ):\n        input_text = HUMAN_PROMPT + \" \" + input_text  # SILENT CORRECTION\n    if input_text.count(\"Assistant:\") == 0:\n        input_text = input_text + ASSISTANT_PROMPT  # SILENT CORRECTION", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html"}
{"id": "bb51a9ee8dd6-1", "text": "if input_text[: len(\"Human:\")] == \"Human:\":\n        input_text = \"\\n\\n\" + input_text\n    input_text = _add_newlines_before_ha(input_text)\n    count = 0\n    # track alternation\n    for i in range(len(input_text)):\n        if input_text[i : i + len(HUMAN_PROMPT)] == HUMAN_PROMPT:\n            if count % 2 == 0:\n                count += 1\n            else:\n                warnings.warn(ALTERNATION_ERROR + f\" Received {input_text}\")\n        if input_text[i : i + len(ASSISTANT_PROMPT)] == ASSISTANT_PROMPT:\n            if count % 2 == 1:\n                count += 1\n            else:\n                warnings.warn(ALTERNATION_ERROR + f\" Received {input_text}\")\n    if count % 2 == 1:  # Only saw Human, no Assistant\n        input_text = input_text + ASSISTANT_PROMPT  # SILENT CORRECTION\n    return input_text\n[docs]class LLMInputOutputAdapter:\n    \"\"\"Adapter class to prepare the inputs from Langchain to a format\n    that LLM model expects.\n    It also provides helper function to extract\n    the generated text from the model response.\"\"\"\n    provider_to_output_key_map = {\n        \"anthropic\": \"completion\",\n        \"amazon\": \"outputText\",\n        \"cohere\": \"text\",\n    }\n[docs]    @classmethod\n    def prepare_input(\n        cls, provider: str, prompt: str, model_kwargs: Dict[str, Any]\n    ) -> Dict[str, Any]:\n        input_body = {**model_kwargs}\n        if provider == \"anthropic\":\n            input_body[\"prompt\"] = _human_assistant_format(prompt)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html"}
{"id": "bb51a9ee8dd6-2", "text": "input_body[\"prompt\"] = _human_assistant_format(prompt)\n        elif provider == \"ai21\" or provider == \"cohere\":\n            input_body[\"prompt\"] = prompt\n        elif provider == \"amazon\":\n            input_body = dict()\n            input_body[\"inputText\"] = prompt\n            input_body[\"textGenerationConfig\"] = {**model_kwargs}\n        else:\n            input_body[\"inputText\"] = prompt\n        if provider == \"anthropic\" and \"max_tokens_to_sample\" not in input_body:\n            input_body[\"max_tokens_to_sample\"] = 256\n        return input_body\n[docs]    @classmethod\n    def prepare_output(cls, provider: str, response: Any) -> str:\n        if provider == \"anthropic\":\n            response_body = json.loads(response.get(\"body\").read().decode())\n            return response_body.get(\"completion\")\n        else:\n            response_body = json.loads(response.get(\"body\").read())\n        if provider == \"ai21\":\n            return response_body.get(\"completions\")[0].get(\"data\").get(\"text\")\n        elif provider == \"cohere\":\n            return response_body.get(\"generations\")[0].get(\"text\")\n        else:\n            return response_body.get(\"results\")[0].get(\"outputText\")\n[docs]    @classmethod\n    def prepare_output_stream(\n        cls, provider: str, response: Any, stop: Optional[List[str]] = None\n    ) -> Iterator[GenerationChunk]:\n        stream = response.get(\"body\")\n        if not stream:\n            return\n        if provider not in cls.provider_to_output_key_map:\n            raise ValueError(\n                f\"Unknown streaming response output key for provider: {provider}\"\n            )\n        for event in stream:\n            chunk = event.get(\"chunk\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html"}
{"id": "bb51a9ee8dd6-3", "text": ")\n        for event in stream:\n            chunk = event.get(\"chunk\")\n            if chunk:\n                chunk_obj = json.loads(chunk.get(\"bytes\").decode())\n                if provider == \"cohere\" and (\n                    chunk_obj[\"is_finished\"]\n                    or chunk_obj[cls.provider_to_output_key_map[provider]]\n                    == \"<EOS_TOKEN>\"\n                ):\n                    return\n                # chunk obj format varies with provider\n                yield GenerationChunk(\n                    text=chunk_obj[cls.provider_to_output_key_map[provider]]\n                )\n[docs]class BedrockBase(BaseModel, ABC):\n    \"\"\"Base class for Bedrock models.\"\"\"\n    client: Any  #: :meta private:\n    region_name: Optional[str] = None\n    \"\"\"The aws region e.g., `us-west-2`. Fallsback to AWS_DEFAULT_REGION env variable\n    or region specified in ~/.aws/config in case it is not provided here.\n    \"\"\"\n    credentials_profile_name: Optional[str] = None\n    \"\"\"The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which\n    has either access keys or role information specified.\n    If not specified, the default credential profile or, if on an EC2 instance,\n    credentials from IMDS will be used.\n    See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\n    \"\"\"\n    model_id: str\n    \"\"\"Id of the model to call, e.g., amazon.titan-text-express-v1, this is\n    equivalent to the modelId property in the list-foundation-models api\"\"\"\n    model_kwargs: Optional[Dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    endpoint_url: Optional[str] = None\n    \"\"\"Needed if you don't want to default to us-east-1 endpoint\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html"}
{"id": "bb51a9ee8dd6-4", "text": "\"\"\"Needed if you don't want to default to us-east-1 endpoint\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results.\"\"\"\n    provider_stop_sequence_key_name_map: Mapping[str, str] = {\n        \"anthropic\": \"stop_sequences\",\n        \"amazon\": \"stopSequences\",\n        \"ai21\": \"stop_sequences\",\n        \"cohere\": \"stop_sequences\",\n    }\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that AWS credentials to and python package exists in environment.\"\"\"\n        # Skip creating new client if passed in constructor\n        if values[\"client\"] is not None:\n            return values\n        try:\n            import boto3\n            if values[\"credentials_profile_name\"] is not None:\n                session = boto3.Session(profile_name=values[\"credentials_profile_name\"])\n            else:\n                # use default credentials\n                session = boto3.Session()\n            values[\"region_name\"] = get_from_dict_or_env(\n                values,\n                \"region_name\",\n                \"AWS_DEFAULT_REGION\",\n                default=None,\n            )\n            client_params = {}\n            if values[\"region_name\"]:\n                client_params[\"region_name\"] = values[\"region_name\"]\n            if values[\"endpoint_url\"]:\n                client_params[\"endpoint_url\"] = values[\"endpoint_url\"]\n            values[\"client\"] = session.client(\"bedrock-runtime\", **client_params)\n        except ImportError:\n            raise ModuleNotFoundError(\n                \"Could not import boto3 python package. \"\n                \"Please install it with `pip install boto3`.\"\n            )\n        except Exception as e:\n            raise ValueError(\n                \"Could not load credentials to authenticate with AWS client. \"\n                \"Please check that credentials in the specified \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html"}
{"id": "bb51a9ee8dd6-5", "text": "\"Please check that credentials in the specified \"\n                \"profile name are valid.\"\n            ) from e\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {\n            **{\"model_kwargs\": _model_kwargs},\n        }\n    def _get_provider(self) -> str:\n        return self.model_id.split(\".\")[0]\n    @property\n    def _model_is_anthropic(self) -> bool:\n        return self._get_provider() == \"anthropic\"\n    def _prepare_input_and_invoke(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        _model_kwargs = self.model_kwargs or {}\n        provider = self._get_provider()\n        params = {**_model_kwargs, **kwargs}\n        input_body = LLMInputOutputAdapter.prepare_input(provider, prompt, params)\n        body = json.dumps(input_body)\n        accept = \"application/json\"\n        contentType = \"application/json\"\n        try:\n            response = self.client.invoke_model(\n                body=body, modelId=self.model_id, accept=accept, contentType=contentType\n            )\n            text = LLMInputOutputAdapter.prepare_output(provider, response)\n        except Exception as e:\n            raise ValueError(f\"Error raised by bedrock service: {e}\")\n        if stop is not None:\n            text = enforce_stop_tokens(text, stop)\n        return text\n    def _prepare_input_and_invoke_stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html"}
{"id": "bb51a9ee8dd6-6", "text": "prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        _model_kwargs = self.model_kwargs or {}\n        provider = self._get_provider()\n        if stop:\n            if provider not in self.provider_stop_sequence_key_name_map:\n                raise ValueError(\n                    f\"Stop sequence key name for {provider} is not supported.\"\n                )\n            # stop sequence from _generate() overrides\n            # stop sequences in the class attribute\n            _model_kwargs[self.provider_stop_sequence_key_name_map.get(provider)] = stop\n        if provider == \"cohere\":\n            _model_kwargs[\"stream\"] = True\n        params = {**_model_kwargs, **kwargs}\n        input_body = LLMInputOutputAdapter.prepare_input(provider, prompt, params)\n        body = json.dumps(input_body)\n        try:\n            response = self.client.invoke_model_with_response_stream(\n                body=body,\n                modelId=self.model_id,\n                accept=\"application/json\",\n                contentType=\"application/json\",\n            )\n        except Exception as e:\n            raise ValueError(f\"Error raised by bedrock service: {e}\")\n        for chunk in LLMInputOutputAdapter.prepare_output_stream(\n            provider, response, stop\n        ):\n            yield chunk\n            if run_manager is not None:\n                run_manager.on_llm_new_token(chunk.text, chunk=chunk)\n[docs]class Bedrock(LLM, BedrockBase):\n    \"\"\"Bedrock models.\n    To authenticate, the AWS client uses the following methods to\n    automatically load credentials:\n    https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html"}
{"id": "bb51a9ee8dd6-7", "text": "https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\n    If a specific credential profile should be used, you must pass\n    the name of the profile from the ~/.aws/credentials file that is to be used.\n    Make sure the credentials / roles used have the required policies to\n    access the Bedrock service.\n    \"\"\"\n    \"\"\"\n    Example:\n        .. code-block:: python\n            from bedrock_langchain.bedrock_llm import BedrockLLM\n            llm = BedrockLLM(\n                credentials_profile_name=\"default\",\n                model_id=\"amazon.titan-text-express-v1\",\n                streaming=True\n            )\n    \"\"\"\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"amazon_bedrock\"\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        \"\"\"Return whether this model can be serialized by Langchain.\"\"\"\n        return True\n    @property\n    def lc_attributes(self) -> Dict[str, Any]:\n        attributes: Dict[str, Any] = {}\n        if self.region_name:\n            attributes[\"region_name\"] = self.region_name\n        return attributes\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        \"\"\"Call out to Bedrock service with streaming.\n        Args:\n            prompt (str): The prompt to pass into the model\n            stop (Optional[List[str]], optional): Stop sequences. These will", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html"}
{"id": "bb51a9ee8dd6-8", "text": "stop (Optional[List[str]], optional): Stop sequences. These will\n                override any stop sequences in the `model_kwargs` attribute.\n                Defaults to None.\n            run_manager (Optional[CallbackManagerForLLMRun], optional): Callback\n                run managers used to process the output. Defaults to None.\n        Returns:\n            Iterator[GenerationChunk]: Generator that yields the streamed responses.\n        Yields:\n            Iterator[GenerationChunk]: Responses from the model.\n        \"\"\"\n        return self._prepare_input_and_invoke_stream(\n            prompt=prompt, stop=stop, run_manager=run_manager, **kwargs\n        )\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Bedrock service model.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = llm(\"Tell me a joke.\")\n        \"\"\"\n        if self.streaming:\n            completion = \"\"\n            for chunk in self._stream(\n                prompt=prompt, stop=stop, run_manager=run_manager, **kwargs\n            ):\n                completion += chunk.text\n            return completion\n        return self._prepare_input_and_invoke(prompt=prompt, stop=stop, **kwargs)\n[docs]    def get_num_tokens(self, text: str) -> int:\n        if self._model_is_anthropic:\n            return get_num_tokens_anthropic(text)\n        else:\n            return super().get_num_tokens(text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html"}
{"id": "bb51a9ee8dd6-9", "text": "else:\n            return super().get_num_tokens(text)\n[docs]    def get_token_ids(self, text: str) -> List[int]:\n        if self._model_is_anthropic:\n            return get_token_ids_anthropic(text)\n        else:\n            return super().get_token_ids(text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html"}
{"id": "a76b5c517262-0", "text": "Source code for langchain.llms.openllm\nfrom __future__ import annotations\nimport copy\nimport json\nimport logging\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Dict,\n    List,\n    Literal,\n    Optional,\n    TypedDict,\n    Union,\n    overload,\n)\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import PrivateAttr\nif TYPE_CHECKING:\n    import openllm\nServerType = Literal[\"http\", \"grpc\"]\n[docs]class IdentifyingParams(TypedDict):\n    \"\"\"Parameters for identifying a model as a typed dict.\"\"\"\n    model_name: str\n    model_id: Optional[str]\n    server_url: Optional[str]\n    server_type: Optional[ServerType]\n    embedded: bool\n    llm_kwargs: Dict[str, Any]\nlogger = logging.getLogger(__name__)\n[docs]class OpenLLM(LLM):\n    \"\"\"OpenLLM, supporting both in-process model\n    instance and remote OpenLLM servers.\n    To use, you should have the openllm library installed:\n    .. code-block:: bash\n        pip install openllm\n    Learn more at: https://github.com/bentoml/openllm\n    Example running an LLM model locally managed by OpenLLM:\n        .. code-block:: python\n            from langchain.llms import OpenLLM\n            llm = OpenLLM(\n                model_name='flan-t5',\n                model_id='google/flan-t5-large',\n            )\n            llm(\"What is the difference between a duck and a goose?\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html"}
{"id": "a76b5c517262-1", "text": ")\n            llm(\"What is the difference between a duck and a goose?\")\n    For all available supported models, you can run 'openllm models'.\n    If you have a OpenLLM server running, you can also use it remotely:\n        .. code-block:: python\n            from langchain.llms import OpenLLM\n            llm = OpenLLM(server_url='http://localhost:3000')\n            llm(\"What is the difference between a duck and a goose?\")\n    \"\"\"\n    model_name: Optional[str] = None\n    \"\"\"Model name to use. See 'openllm models' for all available models.\"\"\"\n    model_id: Optional[str] = None\n    \"\"\"Model Id to use. If not provided, will use the default model for the model name.\n    See 'openllm models' for all available model variants.\"\"\"\n    server_url: Optional[str] = None\n    \"\"\"Optional server URL that currently runs a LLMServer with 'openllm start'.\"\"\"\n    server_type: ServerType = \"http\"\n    \"\"\"Optional server type. Either 'http' or 'grpc'.\"\"\"\n    embedded: bool = True\n    \"\"\"Initialize this LLM instance in current process by default. Should\n    only set to False when using in conjunction with BentoML Service.\"\"\"\n    llm_kwargs: Dict[str, Any]\n    \"\"\"Keyword arguments to be passed to openllm.LLM\"\"\"\n    _runner: Optional[openllm.LLMRunner] = PrivateAttr(default=None)\n    _client: Union[\n        openllm.client.HTTPClient, openllm.client.GrpcClient, None\n    ] = PrivateAttr(default=None)\n    class Config:\n        extra = \"forbid\"\n    @overload\n    def __init__(\n        self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html"}
{"id": "a76b5c517262-2", "text": "@overload\n    def __init__(\n        self,\n        model_name: Optional[str] = ...,\n        *,\n        model_id: Optional[str] = ...,\n        embedded: Literal[True, False] = ...,\n        **llm_kwargs: Any,\n    ) -> None:\n        ...\n    @overload\n    def __init__(\n        self,\n        *,\n        server_url: str = ...,\n        server_type: Literal[\"grpc\", \"http\"] = ...,\n        **llm_kwargs: Any,\n    ) -> None:\n        ...\n    def __init__(\n        self,\n        model_name: Optional[str] = None,\n        *,\n        model_id: Optional[str] = None,\n        server_url: Optional[str] = None,\n        server_type: Literal[\"grpc\", \"http\"] = \"http\",\n        embedded: bool = True,\n        **llm_kwargs: Any,\n    ):\n        try:\n            import openllm\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import openllm. Make sure to install it with \"\n                \"'pip install openllm.'\"\n            ) from e\n        llm_kwargs = llm_kwargs or {}\n        if server_url is not None:\n            logger.debug(\"'server_url' is provided, returning a openllm.Client\")\n            assert (\n                model_id is None and model_name is None\n            ), \"'server_url' and {'model_id', 'model_name'} are mutually exclusive\"\n            client_cls = (\n                openllm.client.HTTPClient\n                if server_type == \"http\"\n                else openllm.client.GrpcClient\n            )\n            client = client_cls(server_url)\n            super().__init__(\n                **{\n                    \"server_url\": server_url,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html"}
{"id": "a76b5c517262-3", "text": "super().__init__(\n                **{\n                    \"server_url\": server_url,\n                    \"server_type\": server_type,\n                    \"llm_kwargs\": llm_kwargs,\n                }\n            )\n            self._runner = None  # type: ignore\n            self._client = client\n        else:\n            assert model_name is not None, \"Must provide 'model_name' or 'server_url'\"\n            # since the LLM are relatively huge, we don't actually want to convert the\n            # Runner with embedded when running the server. Instead, we will only set\n            # the init_local here so that LangChain users can still use the LLM\n            # in-process. Wrt to BentoML users, setting embedded=False is the expected\n            # behaviour to invoke the runners remotely.\n            # We need to also enable ensure_available to download and setup the model.\n            runner = openllm.Runner(\n                model_name=model_name,\n                model_id=model_id,\n                init_local=embedded,\n                ensure_available=True,\n                **llm_kwargs,\n            )\n            super().__init__(\n                **{\n                    \"model_name\": model_name,\n                    \"model_id\": model_id,\n                    \"embedded\": embedded,\n                    \"llm_kwargs\": llm_kwargs,\n                }\n            )\n            self._client = None  # type: ignore\n            self._runner = runner\n    @property\n    def runner(self) -> openllm.LLMRunner:\n        \"\"\"\n        Get the underlying openllm.LLMRunner instance for integration with BentoML.\n        Example:\n        .. code-block:: python\n            llm = OpenLLM(\n                model_name='flan-t5',\n                model_id='google/flan-t5-large',\n                embedded=False,\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html"}
{"id": "a76b5c517262-4", "text": "model_id='google/flan-t5-large',\n                embedded=False,\n            )\n            tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm)\n            agent = initialize_agent(\n                tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION\n            )\n            svc = bentoml.Service(\"langchain-openllm\", runners=[llm.runner])\n            @svc.api(input=Text(), output=Text())\n            def chat(input_text: str):\n                return agent.run(input_text)\n        \"\"\"\n        if self._runner is None:\n            raise ValueError(\"OpenLLM must be initialized locally with 'model_name'\")\n        return self._runner\n    @property\n    def _identifying_params(self) -> IdentifyingParams:\n        \"\"\"Get the identifying parameters.\"\"\"\n        if self._client is not None:\n            self.llm_kwargs.update(self._client._config())\n            model_name = self._client._metadata()[\"model_name\"]\n            model_id = self._client._metadata()[\"model_id\"]\n        else:\n            if self._runner is None:\n                raise ValueError(\"Runner must be initialized.\")\n            model_name = self.model_name\n            model_id = self.model_id\n            try:\n                self.llm_kwargs.update(\n                    json.loads(self._runner.identifying_params[\"configuration\"])\n                )\n            except (TypeError, json.JSONDecodeError):\n                pass\n        return IdentifyingParams(\n            server_url=self.server_url,\n            server_type=self.server_type,\n            embedded=self.embedded,\n            llm_kwargs=self.llm_kwargs,\n            model_name=model_name,\n            model_id=model_id,\n        )\n    @property\n    def _llm_type(self) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html"}
{"id": "a76b5c517262-5", "text": ")\n    @property\n    def _llm_type(self) -> str:\n        return \"openllm_client\" if self._client else \"openllm\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        try:\n            import openllm\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import openllm. Make sure to install it with \"\n                \"'pip install openllm'.\"\n            ) from e\n        copied = copy.deepcopy(self.llm_kwargs)\n        copied.update(kwargs)\n        config = openllm.AutoConfig.for_model(\n            self._identifying_params[\"model_name\"], **copied\n        )\n        if self._client:\n            res = self._client.generate(\n                prompt, **config.model_dump(flatten=True)\n            ).responses[0]\n        else:\n            assert self._runner is not None\n            res = self._runner(prompt, **config.model_dump(flatten=True))\n        if isinstance(res, dict) and \"text\" in res:\n            return res[\"text\"]\n        elif isinstance(res, str):\n            return res\n        else:\n            raise ValueError(\n                \"Expected result to be a dict with key 'text' or a string. \"\n                f\"Received {res}\"\n            )\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html"}
{"id": "a76b5c517262-6", "text": "**kwargs: Any,\n    ) -> str:\n        try:\n            import openllm\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import openllm. Make sure to install it with \"\n                \"'pip install openllm'.\"\n            ) from e\n        copied = copy.deepcopy(self.llm_kwargs)\n        copied.update(kwargs)\n        config = openllm.AutoConfig.for_model(\n            self._identifying_params[\"model_name\"], **copied\n        )\n        if self._client:\n            async_client = openllm.client.AsyncHTTPClient(self.server_url)\n            res = (\n                await async_client.generate(prompt, **config.model_dump(flatten=True))\n            ).responses[0]\n        else:\n            assert self._runner is not None\n            (\n                prompt,\n                generate_kwargs,\n                postprocess_kwargs,\n            ) = self._runner.llm.sanitize_parameters(prompt, **kwargs)\n            generated_result = await self._runner.generate.async_run(\n                prompt, **generate_kwargs\n            )\n            res = self._runner.llm.postprocess_generate(\n                prompt, generated_result, **postprocess_kwargs\n            )\n        if isinstance(res, dict) and \"text\" in res:\n            return res[\"text\"]\n        elif isinstance(res, str):\n            return res\n        else:\n            raise ValueError(\n                \"Expected result to be a dict with key 'text' or a string. \"\n                f\"Received {res}\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html"}
{"id": "357fa1908d5c-0", "text": "Source code for langchain.llms.bananadev\nimport logging\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class Banana(LLM):\n    \"\"\"Banana large language models.\n    To use, you should have the ``banana-dev`` python package installed,\n    and the environment variable ``BANANA_API_KEY`` set with your API key.\n    This is the team API key available in the Banana dashboard.\n    Any parameters that are valid to be passed to the call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.llms import Banana\n            banana = Banana(model_key=\"\", model_url_slug=\"\")\n    \"\"\"\n    model_key: str = \"\"\n    \"\"\"model key to use\"\"\"\n    model_url_slug: str = \"\"\n    \"\"\"model endpoint to use\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not\n    explicitly specified.\"\"\"\n    banana_api_key: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic config.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = {field.alias for field in cls.__fields__.values()}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html"}
{"id": "357fa1908d5c-1", "text": "all_required_field_names = {field.alias for field in cls.__fields__.values()}\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name not in all_required_field_names:\n                if field_name in extra:\n                    raise ValueError(f\"Found {field_name} supplied twice.\")\n                logger.warning(\n                    f\"\"\"{field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        banana_api_key = get_from_dict_or_env(\n            values, \"banana_api_key\", \"BANANA_API_KEY\"\n        )\n        values[\"banana_api_key\"] = banana_api_key\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"model_key\": self.model_key},\n            **{\"model_url_slug\": self.model_url_slug},\n            **{\"model_kwargs\": self.model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"bananadev\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call to Banana endpoint.\"\"\"\n        try:\n            from banana_dev import Client\n        except ImportError:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html"}
{"id": "357fa1908d5c-2", "text": "try:\n            from banana_dev import Client\n        except ImportError:\n            raise ImportError(\n                \"Could not import banana-dev python package. \"\n                \"Please install it with `pip install banana-dev`.\"\n            )\n        params = self.model_kwargs or {}\n        params = {**params, **kwargs}\n        api_key = self.banana_api_key\n        model_key = self.model_key\n        model_url_slug = self.model_url_slug\n        model_inputs = {\n            # a json specific to your model.\n            \"prompt\": prompt,\n            **params,\n        }\n        model = Client(\n            # Found in main dashboard\n            api_key=api_key,\n            # Both found in model details page\n            model_key=model_key,\n            url=f\"https://{model_url_slug}.run.banana.dev\",\n        )\n        response, meta = model.call(\"/\", model_inputs)\n        try:\n            text = response[\"outputs\"]\n        except (KeyError, TypeError):\n            raise ValueError(\n                \"Response should be of schema: {'outputs': 'text'}.\"\n                \"\\nTo fix this:\"\n                \"\\n- fork the source repo of the Banana model\"\n                \"\\n- modify app.py to return the above schema\"\n                \"\\n- deploy that as a custom repo\"\n            )\n        if stop is not None:\n            # I believe this is required since the stop tokens\n            # are not enforced by the model parameters\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html"}
{"id": "58dde93ed5bc-0", "text": "Source code for langchain.llms.modal\nimport logging\nfrom typing import Any, Dict, List, Mapping, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nlogger = logging.getLogger(__name__)\n[docs]class Modal(LLM):\n    \"\"\"Modal large language models.\n    To use, you should have the ``modal-client`` python package installed.\n    Any parameters that are valid to be passed to the call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.llms import Modal\n            modal = Modal(endpoint_url=\"\")\n    \"\"\"\n    endpoint_url: str = \"\"\n    \"\"\"model endpoint to use\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not\n    explicitly specified.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic config.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = {field.alias for field in cls.__fields__.values()}\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name not in all_required_field_names:\n                if field_name in extra:\n                    raise ValueError(f\"Found {field_name} supplied twice.\")\n                logger.warning(\n                    f\"\"\"{field_name} was transferred to model_kwargs.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/modal.html"}
{"id": "58dde93ed5bc-1", "text": "logger.warning(\n                    f\"\"\"{field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        values[\"model_kwargs\"] = extra\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"endpoint_url\": self.endpoint_url},\n            **{\"model_kwargs\": self.model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"modal\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call to Modal endpoint.\"\"\"\n        params = self.model_kwargs or {}\n        params = {**params, **kwargs}\n        response = requests.post(\n            url=self.endpoint_url,\n            headers={\n                \"Content-Type\": \"application/json\",\n            },\n            json={\"prompt\": prompt, **params},\n        )\n        try:\n            if prompt in response.json()[\"prompt\"]:\n                response_json = response.json()\n        except KeyError:\n            raise KeyError(\"LangChain requires 'prompt' key in response.\")\n        text = response_json[\"prompt\"]\n        if stop is not None:\n            # I believe this is required since the stop tokens\n            # are not enforced by the model parameters\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/modal.html"}
{"id": "a3b831e1cafd-0", "text": "Source code for langchain.llms.base\n\"\"\"Base interface for large language models to expose.\"\"\"\nfrom __future__ import annotations\nimport asyncio\nimport functools\nimport inspect\nimport json\nimport logging\nimport warnings\nfrom abc import ABC, abstractmethod\nfrom functools import partial\nfrom pathlib import Path\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Callable,\n    Dict,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Sequence,\n    Tuple,\n    Type,\n    Union,\n    cast,\n)\nimport yaml\nfrom tenacity import (\n    RetryCallState,\n    before_sleep_log,\n    retry,\n    retry_base,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.callbacks.base import BaseCallbackManager\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManager,\n    AsyncCallbackManagerForLLMRun,\n    CallbackManager,\n    CallbackManagerForLLMRun,\n    Callbacks,\n)\nfrom langchain.globals import get_llm_cache\nfrom langchain.load.dump import dumpd\nfrom langchain.prompts.base import StringPromptValue\nfrom langchain.prompts.chat import ChatPromptValue\nfrom langchain.pydantic_v1 import Field, root_validator, validator\nfrom langchain.schema import Generation, LLMResult, PromptValue, RunInfo\nfrom langchain.schema.language_model import BaseLanguageModel, LanguageModelInput\nfrom langchain.schema.messages import AIMessage, BaseMessage, get_buffer_string\nfrom langchain.schema.output import GenerationChunk\nfrom langchain.schema.runnable import RunnableConfig\nfrom langchain.schema.runnable.config import get_config_list\nlogger = logging.getLogger(__name__)\ndef _get_verbosity() -> bool:\n    from langchain.globals import get_verbose\n    return get_verbose()", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-1", "text": "from langchain.globals import get_verbose\n    return get_verbose()\n@functools.lru_cache\ndef _log_error_once(msg: str) -> None:\n    \"\"\"Log an error once.\"\"\"\n    logger.error(msg)\n[docs]def create_base_retry_decorator(\n    error_types: List[Type[BaseException]],\n    max_retries: int = 1,\n    run_manager: Optional[\n        Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]\n    ] = None,\n) -> Callable[[Any], Any]:\n    \"\"\"Create a retry decorator for a given LLM and provided list of error types.\"\"\"\n    _logging = before_sleep_log(logger, logging.WARNING)\n    def _before_sleep(retry_state: RetryCallState) -> None:\n        _logging(retry_state)\n        if run_manager:\n            if isinstance(run_manager, AsyncCallbackManagerForLLMRun):\n                coro = run_manager.on_retry(retry_state)\n                try:\n                    loop = asyncio.get_event_loop()\n                    if loop.is_running():\n                        loop.create_task(coro)\n                    else:\n                        asyncio.run(coro)\n                except Exception as e:\n                    _log_error_once(f\"Error in on_retry: {e}\")\n            else:\n                run_manager.on_retry(retry_state)\n        return None\n    min_seconds = 4\n    max_seconds = 10\n    # Wait 2^x * 1 second between each retry starting with\n    # 4 seconds, then up to 10 seconds, then 10 seconds afterwards\n    retry_instance: \"retry_base\" = retry_if_exception_type(error_types[0])\n    for error in error_types[1:]:\n        retry_instance = retry_instance | retry_if_exception_type(error)\n    return retry(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-2", "text": "retry_instance = retry_instance | retry_if_exception_type(error)\n    return retry(\n        reraise=True,\n        stop=stop_after_attempt(max_retries),\n        wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),\n        retry=retry_instance,\n        before_sleep=_before_sleep,\n    )\n[docs]def get_prompts(\n    params: Dict[str, Any], prompts: List[str]\n) -> Tuple[Dict[int, List], str, List[int], List[str]]:\n    \"\"\"Get prompts that are already cached.\"\"\"\n    llm_string = str(sorted([(k, v) for k, v in params.items()]))\n    missing_prompts = []\n    missing_prompt_idxs = []\n    existing_prompts = {}\n    llm_cache = get_llm_cache()\n    for i, prompt in enumerate(prompts):\n        if llm_cache is not None:\n            cache_val = llm_cache.lookup(prompt, llm_string)\n            if isinstance(cache_val, list):\n                existing_prompts[i] = cache_val\n            else:\n                missing_prompts.append(prompt)\n                missing_prompt_idxs.append(i)\n    return existing_prompts, llm_string, missing_prompt_idxs, missing_prompts\n[docs]def update_cache(\n    existing_prompts: Dict[int, List],\n    llm_string: str,\n    missing_prompt_idxs: List[int],\n    new_results: LLMResult,\n    prompts: List[str],\n) -> Optional[dict]:\n    \"\"\"Update the cache and get the LLM output.\"\"\"\n    llm_cache = get_llm_cache()\n    for i, result in enumerate(new_results.generations):\n        existing_prompts[missing_prompt_idxs[i]] = result\n        prompt = prompts[missing_prompt_idxs[i]]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-3", "text": "prompt = prompts[missing_prompt_idxs[i]]\n        if llm_cache is not None:\n            llm_cache.update(prompt, llm_string, result)\n    llm_output = new_results.llm_output\n    return llm_output\n[docs]class BaseLLM(BaseLanguageModel[str], ABC):\n    \"\"\"Base LLM abstract interface.\n    It should take in a prompt and return a string.\"\"\"\n    cache: Optional[bool] = None\n    verbose: bool = Field(default_factory=_get_verbosity)\n    \"\"\"Whether to print out response text.\"\"\"\n    callbacks: Callbacks = Field(default=None, exclude=True)\n    callback_manager: Optional[BaseCallbackManager] = Field(default=None, exclude=True)\n    tags: Optional[List[str]] = Field(default=None, exclude=True)\n    \"\"\"Tags to add to the run trace.\"\"\"\n    metadata: Optional[Dict[str, Any]] = Field(default=None, exclude=True)\n    \"\"\"Metadata to add to the run trace.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        arbitrary_types_allowed = True\n    @root_validator()\n    def raise_deprecation(cls, values: Dict) -> Dict:\n        \"\"\"Raise deprecation warning if callback_manager is used.\"\"\"\n        if values.get(\"callback_manager\") is not None:\n            warnings.warn(\n                \"callback_manager is deprecated. Please use callbacks instead.\",\n                DeprecationWarning,\n            )\n            values[\"callbacks\"] = values.pop(\"callback_manager\", None)\n        return values\n    @validator(\"verbose\", pre=True, always=True)\n    def set_verbose(cls, verbose: Optional[bool]) -> bool:\n        \"\"\"If verbose is None, set it.\n        This allows users to pass in None as verbose to access the global setting.\n        \"\"\"\n        if verbose is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-4", "text": "\"\"\"\n        if verbose is None:\n            return _get_verbosity()\n        else:\n            return verbose\n    # --- Runnable methods ---\n    @property\n    def OutputType(self) -> Type[str]:\n        \"\"\"Get the input type for this runnable.\"\"\"\n        return str\n    def _convert_input(self, input: LanguageModelInput) -> PromptValue:\n        if isinstance(input, PromptValue):\n            return input\n        elif isinstance(input, str):\n            return StringPromptValue(text=input)\n        elif isinstance(input, list):\n            return ChatPromptValue(messages=input)\n        else:\n            raise ValueError(\n                f\"Invalid input type {type(input)}. \"\n                \"Must be a PromptValue, str, or list of BaseMessages.\"\n            )\n[docs]    def invoke(\n        self,\n        input: LanguageModelInput,\n        config: Optional[RunnableConfig] = None,\n        *,\n        stop: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> str:\n        config = config or {}\n        return (\n            self.generate_prompt(\n                [self._convert_input(input)],\n                stop=stop,\n                callbacks=config.get(\"callbacks\"),\n                tags=config.get(\"tags\"),\n                metadata=config.get(\"metadata\"),\n                run_name=config.get(\"run_name\"),\n                **kwargs,\n            )\n            .generations[0][0]\n            .text\n        )\n[docs]    async def ainvoke(\n        self,\n        input: LanguageModelInput,\n        config: Optional[RunnableConfig] = None,\n        *,\n        stop: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> str:\n        config = config or {}\n        llm_result = await self.agenerate_prompt(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-5", "text": "config = config or {}\n        llm_result = await self.agenerate_prompt(\n            [self._convert_input(input)],\n            stop=stop,\n            callbacks=config.get(\"callbacks\"),\n            tags=config.get(\"tags\"),\n            metadata=config.get(\"metadata\"),\n            run_name=config.get(\"run_name\"),\n            **kwargs,\n        )\n        return llm_result.generations[0][0].text\n[docs]    def batch(\n        self,\n        inputs: List[LanguageModelInput],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Any,\n    ) -> List[str]:\n        if not inputs:\n            return []\n        config = get_config_list(config, len(inputs))\n        max_concurrency = config[0].get(\"max_concurrency\")\n        if max_concurrency is None:\n            try:\n                llm_result = self.generate_prompt(\n                    [self._convert_input(input) for input in inputs],\n                    callbacks=[c.get(\"callbacks\") for c in config],\n                    tags=[c.get(\"tags\") for c in config],\n                    metadata=[c.get(\"metadata\") for c in config],\n                    run_name=[c.get(\"run_name\") for c in config],\n                    **kwargs,\n                )\n                return [g[0].text for g in llm_result.generations]\n            except Exception as e:\n                if return_exceptions:\n                    return cast(List[str], [e for _ in inputs])\n                else:\n                    raise e\n        else:\n            batches = [\n                inputs[i : i + max_concurrency]\n                for i in range(0, len(inputs), max_concurrency)\n            ]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-6", "text": "for i in range(0, len(inputs), max_concurrency)\n            ]\n            config = [{**c, \"max_concurrency\": None} for c in config]  # type: ignore[misc]\n            return [\n                output\n                for i, batch in enumerate(batches)\n                for output in self.batch(\n                    batch,\n                    config=config[i * max_concurrency : (i + 1) * max_concurrency],\n                    return_exceptions=return_exceptions,\n                    **kwargs,\n                )\n            ]\n[docs]    async def abatch(\n        self,\n        inputs: List[LanguageModelInput],\n        config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,\n        *,\n        return_exceptions: bool = False,\n        **kwargs: Any,\n    ) -> List[str]:\n        if not inputs:\n            return []\n        config = get_config_list(config, len(inputs))\n        max_concurrency = config[0].get(\"max_concurrency\")\n        if max_concurrency is None:\n            try:\n                llm_result = await self.agenerate_prompt(\n                    [self._convert_input(input) for input in inputs],\n                    callbacks=[c.get(\"callbacks\") for c in config],\n                    tags=[c.get(\"tags\") for c in config],\n                    metadata=[c.get(\"metadata\") for c in config],\n                    run_name=[c.get(\"run_name\") for c in config],\n                    **kwargs,\n                )\n                return [g[0].text for g in llm_result.generations]\n            except Exception as e:\n                if return_exceptions:\n                    return cast(List[str], [e for _ in inputs])\n                else:\n                    raise e\n        else:\n            batches = [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-7", "text": "else:\n                    raise e\n        else:\n            batches = [\n                inputs[i : i + max_concurrency]\n                for i in range(0, len(inputs), max_concurrency)\n            ]\n            config = [{**c, \"max_concurrency\": None} for c in config]  # type: ignore[misc]\n            return [\n                output\n                for i, batch in enumerate(batches)\n                for output in await self.abatch(\n                    batch,\n                    config=config[i * max_concurrency : (i + 1) * max_concurrency],\n                    return_exceptions=return_exceptions,\n                    **kwargs,\n                )\n            ]\n[docs]    def stream(\n        self,\n        input: LanguageModelInput,\n        config: Optional[RunnableConfig] = None,\n        *,\n        stop: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Iterator[str]:\n        if type(self)._stream == BaseLLM._stream:\n            # model doesn't implement streaming, so use default implementation\n            yield self.invoke(input, config=config, stop=stop, **kwargs)\n        else:\n            prompt = self._convert_input(input).to_string()\n            config = config or {}\n            params = self.dict()\n            params[\"stop\"] = stop\n            params = {**params, **kwargs}\n            options = {\"stop\": stop}\n            callback_manager = CallbackManager.configure(\n                config.get(\"callbacks\"),\n                self.callbacks,\n                self.verbose,\n                config.get(\"tags\"),\n                self.tags,\n                config.get(\"metadata\"),\n                self.metadata,\n            )\n            (run_manager,) = callback_manager.on_llm_start(\n                dumpd(self),\n                [prompt],\n                invocation_params=params,\n                options=options,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-8", "text": "[prompt],\n                invocation_params=params,\n                options=options,\n                name=config.get(\"run_name\"),\n            )\n            try:\n                generation: Optional[GenerationChunk] = None\n                for chunk in self._stream(\n                    prompt, stop=stop, run_manager=run_manager, **kwargs\n                ):\n                    yield chunk.text\n                    if generation is None:\n                        generation = chunk\n                    else:\n                        generation += chunk\n                assert generation is not None\n            except BaseException as e:\n                run_manager.on_llm_error(e)\n                raise e\n            else:\n                run_manager.on_llm_end(LLMResult(generations=[[generation]]))\n[docs]    async def astream(\n        self,\n        input: LanguageModelInput,\n        config: Optional[RunnableConfig] = None,\n        *,\n        stop: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[str]:\n        if type(self)._astream == BaseLLM._astream:\n            # model doesn't implement streaming, so use default implementation\n            yield await self.ainvoke(input, config=config, stop=stop, **kwargs)\n        else:\n            prompt = self._convert_input(input).to_string()\n            config = config or {}\n            params = self.dict()\n            params[\"stop\"] = stop\n            params = {**params, **kwargs}\n            options = {\"stop\": stop}\n            callback_manager = AsyncCallbackManager.configure(\n                config.get(\"callbacks\"),\n                self.callbacks,\n                self.verbose,\n                config.get(\"tags\"),\n                self.tags,\n                config.get(\"metadata\"),\n                self.metadata,\n            )\n            (run_manager,) = await callback_manager.on_llm_start(\n                dumpd(self),\n                [prompt],", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-9", "text": "dumpd(self),\n                [prompt],\n                invocation_params=params,\n                options=options,\n                name=config.get(\"run_name\"),\n            )\n            try:\n                generation: Optional[GenerationChunk] = None\n                async for chunk in self._astream(\n                    prompt, stop=stop, run_manager=run_manager, **kwargs\n                ):\n                    yield chunk.text\n                    if generation is None:\n                        generation = chunk\n                    else:\n                        generation += chunk\n                assert generation is not None\n            except BaseException as e:\n                await run_manager.on_llm_error(e)\n                raise e\n            else:\n                await run_manager.on_llm_end(LLMResult(generations=[[generation]]))\n    # --- Custom methods ---\n    @abstractmethod\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Run the LLM on the given prompts.\"\"\"\n    async def _agenerate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Run the LLM on the given prompts.\"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, partial(self._generate, **kwargs), prompts, stop, run_manager\n        )\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-10", "text": "run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        raise NotImplementedError()\n    def _astream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[GenerationChunk]:\n        raise NotImplementedError()\n[docs]    def generate_prompt(\n        self,\n        prompts: List[PromptValue],\n        stop: Optional[List[str]] = None,\n        callbacks: Optional[Union[Callbacks, List[Callbacks]]] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        prompt_strings = [p.to_string() for p in prompts]\n        return self.generate(prompt_strings, stop=stop, callbacks=callbacks, **kwargs)\n[docs]    async def agenerate_prompt(\n        self,\n        prompts: List[PromptValue],\n        stop: Optional[List[str]] = None,\n        callbacks: Optional[Union[Callbacks, List[Callbacks]]] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        prompt_strings = [p.to_string() for p in prompts]\n        return await self.agenerate(\n            prompt_strings, stop=stop, callbacks=callbacks, **kwargs\n        )\n    def _generate_helper(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]],\n        run_managers: List[CallbackManagerForLLMRun],\n        new_arg_supported: bool,\n        **kwargs: Any,\n    ) -> LLMResult:\n        try:\n            output = (\n                self._generate(\n                    prompts,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-11", "text": "try:\n            output = (\n                self._generate(\n                    prompts,\n                    stop=stop,\n                    # TODO: support multiple run managers\n                    run_manager=run_managers[0] if run_managers else None,\n                    **kwargs,\n                )\n                if new_arg_supported\n                else self._generate(prompts, stop=stop)\n            )\n        except BaseException as e:\n            for run_manager in run_managers:\n                run_manager.on_llm_error(e)\n            raise e\n        flattened_outputs = output.flatten()\n        for manager, flattened_output in zip(run_managers, flattened_outputs):\n            manager.on_llm_end(flattened_output)\n        if run_managers:\n            output.run = [\n                RunInfo(run_id=run_manager.run_id) for run_manager in run_managers\n            ]\n        return output\n[docs]    def generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        callbacks: Optional[Union[Callbacks, List[Callbacks]]] = None,\n        *,\n        tags: Optional[Union[List[str], List[List[str]]]] = None,\n        metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None,\n        run_name: Optional[Union[str, List[str]]] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Run the LLM on the given prompt and input.\"\"\"\n        if not isinstance(prompts, list):\n            raise ValueError(\n                \"Argument 'prompts' is expected to be of type List[str], received\"\n                f\" argument of type {type(prompts)}.\"\n            )\n        # Create callback managers\n        if (\n            isinstance(callbacks, list)\n            and callbacks", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-12", "text": "if (\n            isinstance(callbacks, list)\n            and callbacks\n            and (\n                isinstance(callbacks[0], (list, BaseCallbackManager))\n                or callbacks[0] is None\n            )\n        ):\n            # We've received a list of callbacks args to apply to each input\n            assert len(callbacks) == len(prompts)\n            assert tags is None or (\n                isinstance(tags, list) and len(tags) == len(prompts)\n            )\n            assert metadata is None or (\n                isinstance(metadata, list) and len(metadata) == len(prompts)\n            )\n            assert run_name is None or (\n                isinstance(run_name, list) and len(run_name) == len(prompts)\n            )\n            callbacks = cast(List[Callbacks], callbacks)\n            tags_list = cast(List[Optional[List[str]]], tags or ([None] * len(prompts)))\n            metadata_list = cast(\n                List[Optional[Dict[str, Any]]], metadata or ([{}] * len(prompts))\n            )\n            run_name_list = run_name or cast(\n                List[Optional[str]], ([None] * len(prompts))\n            )\n            callback_managers = [\n                CallbackManager.configure(\n                    callback,\n                    self.callbacks,\n                    self.verbose,\n                    tag,\n                    self.tags,\n                    meta,\n                    self.metadata,\n                )\n                for callback, tag, meta in zip(callbacks, tags_list, metadata_list)\n            ]\n        else:\n            # We've received a single callbacks arg to apply to all inputs\n            callback_managers = [\n                CallbackManager.configure(\n                    cast(Callbacks, callbacks),\n                    self.callbacks,\n                    self.verbose,\n                    cast(List[str], tags),\n                    self.tags,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-13", "text": "self.verbose,\n                    cast(List[str], tags),\n                    self.tags,\n                    cast(Dict[str, Any], metadata),\n                    self.metadata,\n                )\n            ] * len(prompts)\n            run_name_list = [cast(Optional[str], run_name)] * len(prompts)\n        params = self.dict()\n        params[\"stop\"] = stop\n        options = {\"stop\": stop}\n        (\n            existing_prompts,\n            llm_string,\n            missing_prompt_idxs,\n            missing_prompts,\n        ) = get_prompts(params, prompts)\n        disregard_cache = self.cache is not None and not self.cache\n        new_arg_supported = inspect.signature(self._generate).parameters.get(\n            \"run_manager\"\n        )\n        if get_llm_cache() is None or disregard_cache:\n            if self.cache is not None and self.cache:\n                raise ValueError(\n                    \"Asked to cache, but no cache found at `langchain.cache`.\"\n                )\n            run_managers = [\n                callback_manager.on_llm_start(\n                    dumpd(self),\n                    [prompt],\n                    invocation_params=params,\n                    options=options,\n                    name=run_name,\n                )[0]\n                for callback_manager, prompt, run_name in zip(\n                    callback_managers, prompts, run_name_list\n                )\n            ]\n            output = self._generate_helper(\n                prompts, stop, run_managers, bool(new_arg_supported), **kwargs\n            )\n            return output\n        if len(missing_prompts) > 0:\n            run_managers = [\n                callback_managers[idx].on_llm_start(\n                    dumpd(self),\n                    [prompts[idx]],\n                    invocation_params=params,\n                    options=options,\n                    name=run_name_list[idx],\n                )[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-14", "text": "options=options,\n                    name=run_name_list[idx],\n                )[0]\n                for idx in missing_prompt_idxs\n            ]\n            new_results = self._generate_helper(\n                missing_prompts, stop, run_managers, bool(new_arg_supported), **kwargs\n            )\n            llm_output = update_cache(\n                existing_prompts, llm_string, missing_prompt_idxs, new_results, prompts\n            )\n            run_info = (\n                [RunInfo(run_id=run_manager.run_id) for run_manager in run_managers]\n                if run_managers\n                else None\n            )\n        else:\n            llm_output = {}\n            run_info = None\n        generations = [existing_prompts[i] for i in range(len(prompts))]\n        return LLMResult(generations=generations, llm_output=llm_output, run=run_info)\n    async def _agenerate_helper(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]],\n        run_managers: List[AsyncCallbackManagerForLLMRun],\n        new_arg_supported: bool,\n        **kwargs: Any,\n    ) -> LLMResult:\n        try:\n            output = (\n                await self._agenerate(\n                    prompts,\n                    stop=stop,\n                    run_manager=run_managers[0] if run_managers else None,\n                    **kwargs,\n                )\n                if new_arg_supported\n                else await self._agenerate(prompts, stop=stop)\n            )\n        except BaseException as e:\n            await asyncio.gather(\n                *[run_manager.on_llm_error(e) for run_manager in run_managers]\n            )\n            raise e\n        flattened_outputs = output.flatten()\n        await asyncio.gather(\n            *[", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-15", "text": "flattened_outputs = output.flatten()\n        await asyncio.gather(\n            *[\n                run_manager.on_llm_end(flattened_output)\n                for run_manager, flattened_output in zip(\n                    run_managers, flattened_outputs\n                )\n            ]\n        )\n        if run_managers:\n            output.run = [\n                RunInfo(run_id=run_manager.run_id) for run_manager in run_managers\n            ]\n        return output\n[docs]    async def agenerate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        callbacks: Optional[Union[Callbacks, List[Callbacks]]] = None,\n        *,\n        tags: Optional[Union[List[str], List[List[str]]]] = None,\n        metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None,\n        run_name: Optional[Union[str, List[str]]] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Run the LLM on the given prompt and input.\"\"\"\n        # Create callback managers\n        if isinstance(callbacks, list) and (\n            isinstance(callbacks[0], (list, BaseCallbackManager))\n            or callbacks[0] is None\n        ):\n            # We've received a list of callbacks args to apply to each input\n            assert len(callbacks) == len(prompts)\n            assert tags is None or (\n                isinstance(tags, list) and len(tags) == len(prompts)\n            )\n            assert metadata is None or (\n                isinstance(metadata, list) and len(metadata) == len(prompts)\n            )\n            assert run_name is None or (\n                isinstance(run_name, list) and len(run_name) == len(prompts)\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-16", "text": ")\n            callbacks = cast(List[Callbacks], callbacks)\n            tags_list = cast(List[Optional[List[str]]], tags or ([None] * len(prompts)))\n            metadata_list = cast(\n                List[Optional[Dict[str, Any]]], metadata or ([{}] * len(prompts))\n            )\n            run_name_list = run_name or cast(\n                List[Optional[str]], ([None] * len(prompts))\n            )\n            callback_managers = [\n                AsyncCallbackManager.configure(\n                    callback,\n                    self.callbacks,\n                    self.verbose,\n                    tag,\n                    self.tags,\n                    meta,\n                    self.metadata,\n                )\n                for callback, tag, meta in zip(callbacks, tags_list, metadata_list)\n            ]\n        else:\n            # We've received a single callbacks arg to apply to all inputs\n            callback_managers = [\n                AsyncCallbackManager.configure(\n                    cast(Callbacks, callbacks),\n                    self.callbacks,\n                    self.verbose,\n                    cast(List[str], tags),\n                    self.tags,\n                    cast(Dict[str, Any], metadata),\n                    self.metadata,\n                )\n            ] * len(prompts)\n            run_name_list = [cast(Optional[str], run_name)] * len(prompts)\n        params = self.dict()\n        params[\"stop\"] = stop\n        options = {\"stop\": stop}\n        (\n            existing_prompts,\n            llm_string,\n            missing_prompt_idxs,\n            missing_prompts,\n        ) = get_prompts(params, prompts)\n        disregard_cache = self.cache is not None and not self.cache\n        new_arg_supported = inspect.signature(self._agenerate).parameters.get(\n            \"run_manager\"\n        )\n        if get_llm_cache() is None or disregard_cache:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-17", "text": ")\n        if get_llm_cache() is None or disregard_cache:\n            if self.cache is not None and self.cache:\n                raise ValueError(\n                    \"Asked to cache, but no cache found at `langchain.cache`.\"\n                )\n            run_managers = await asyncio.gather(\n                *[\n                    callback_manager.on_llm_start(\n                        dumpd(self),\n                        [prompt],\n                        invocation_params=params,\n                        options=options,\n                        name=run_name,\n                    )\n                    for callback_manager, prompt, run_name in zip(\n                        callback_managers, prompts, run_name_list\n                    )\n                ]\n            )\n            run_managers = [r[0] for r in run_managers]\n            output = await self._agenerate_helper(\n                prompts, stop, run_managers, bool(new_arg_supported), **kwargs\n            )\n            return output\n        if len(missing_prompts) > 0:\n            run_managers = await asyncio.gather(\n                *[\n                    callback_managers[idx].on_llm_start(\n                        dumpd(self),\n                        [prompts[idx]],\n                        invocation_params=params,\n                        options=options,\n                        name=run_name_list[idx],\n                    )\n                    for idx in missing_prompt_idxs\n                ]\n            )\n            run_managers = [r[0] for r in run_managers]\n            new_results = await self._agenerate_helper(\n                missing_prompts, stop, run_managers, bool(new_arg_supported), **kwargs\n            )\n            llm_output = update_cache(\n                existing_prompts, llm_string, missing_prompt_idxs, new_results, prompts\n            )\n            run_info = (\n                [RunInfo(run_id=run_manager.run_id) for run_manager in run_managers]\n                if run_managers", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-18", "text": "if run_managers\n                else None\n            )\n        else:\n            llm_output = {}\n            run_info = None\n        generations = [existing_prompts[i] for i in range(len(prompts))]\n        return LLMResult(generations=generations, llm_output=llm_output, run=run_info)\n[docs]    def __call__(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        callbacks: Callbacks = None,\n        *,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Check Cache and run the LLM on the given prompt and input.\"\"\"\n        if not isinstance(prompt, str):\n            raise ValueError(\n                \"Argument `prompt` is expected to be a string. Instead found \"\n                f\"{type(prompt)}. If you want to run the LLM on multiple prompts, use \"\n                \"`generate` instead.\"\n            )\n        return (\n            self.generate(\n                [prompt],\n                stop=stop,\n                callbacks=callbacks,\n                tags=tags,\n                metadata=metadata,\n                **kwargs,\n            )\n            .generations[0][0]\n            .text\n        )\n    async def _call_async(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        callbacks: Callbacks = None,\n        *,\n        tags: Optional[List[str]] = None,\n        metadata: Optional[Dict[str, Any]] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Check Cache and run the LLM on the given prompt and input.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-19", "text": "\"\"\"Check Cache and run the LLM on the given prompt and input.\"\"\"\n        result = await self.agenerate(\n            [prompt],\n            stop=stop,\n            callbacks=callbacks,\n            tags=tags,\n            metadata=metadata,\n            **kwargs,\n        )\n        return result.generations[0][0].text\n[docs]    def predict(\n        self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any\n    ) -> str:\n        if stop is None:\n            _stop = None\n        else:\n            _stop = list(stop)\n        return self(text, stop=_stop, **kwargs)\n[docs]    def predict_messages(\n        self,\n        messages: List[BaseMessage],\n        *,\n        stop: Optional[Sequence[str]] = None,\n        **kwargs: Any,\n    ) -> BaseMessage:\n        text = get_buffer_string(messages)\n        if stop is None:\n            _stop = None\n        else:\n            _stop = list(stop)\n        content = self(text, stop=_stop, **kwargs)\n        return AIMessage(content=content)\n[docs]    async def apredict(\n        self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any\n    ) -> str:\n        if stop is None:\n            _stop = None\n        else:\n            _stop = list(stop)\n        return await self._call_async(text, stop=_stop, **kwargs)\n[docs]    async def apredict_messages(\n        self,\n        messages: List[BaseMessage],\n        *,\n        stop: Optional[Sequence[str]] = None,\n        **kwargs: Any,\n    ) -> BaseMessage:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-20", "text": "**kwargs: Any,\n    ) -> BaseMessage:\n        text = get_buffer_string(messages)\n        if stop is None:\n            _stop = None\n        else:\n            _stop = list(stop)\n        content = await self._call_async(text, stop=_stop, **kwargs)\n        return AIMessage(content=content)\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {}\n    def __str__(self) -> str:\n        \"\"\"Get a string representation of the object for printing.\"\"\"\n        cls_name = f\"\\033[1m{self.__class__.__name__}\\033[0m\"\n        return f\"{cls_name}\\nParams: {self._identifying_params}\"\n    @property\n    @abstractmethod\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n[docs]    def dict(self, **kwargs: Any) -> Dict:\n        \"\"\"Return a dictionary of the LLM.\"\"\"\n        starter_dict = dict(self._identifying_params)\n        starter_dict[\"_type\"] = self._llm_type\n        return starter_dict\n[docs]    def save(self, file_path: Union[Path, str]) -> None:\n        \"\"\"Save the LLM.\n        Args:\n            file_path: Path to file to save the LLM to.\n        Example:\n        .. code-block:: python\n            llm.save(file_path=\"path/llm.yaml\")\n        \"\"\"\n        # Convert file to Path object.\n        if isinstance(file_path, str):\n            save_path = Path(file_path)\n        else:\n            save_path = file_path\n        directory_path = save_path.parent\n        directory_path.mkdir(parents=True, exist_ok=True)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-21", "text": "directory_path.mkdir(parents=True, exist_ok=True)\n        # Fetch dictionary to save\n        prompt_dict = self.dict()\n        if save_path.suffix == \".json\":\n            with open(file_path, \"w\") as f:\n                json.dump(prompt_dict, f, indent=4)\n        elif save_path.suffix == \".yaml\":\n            with open(file_path, \"w\") as f:\n                yaml.dump(prompt_dict, f, default_flow_style=False)\n        else:\n            raise ValueError(f\"{save_path} must be json or yaml\")\n[docs]class LLM(BaseLLM):\n    \"\"\"Base LLM abstract class.\n    The purpose of this class is to expose a simpler interface for working\n    with LLMs, rather than expect the user to implement the full _generate method.\n    \"\"\"\n    @abstractmethod\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Run the LLM on the given prompt and input.\"\"\"\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Run the LLM on the given prompt and input.\"\"\"\n        return await asyncio.get_running_loop().run_in_executor(\n            None, partial(self._call, **kwargs), prompt, stop, run_manager\n        )\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "a3b831e1cafd-22", "text": "prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Run the LLM on the given prompt and input.\"\"\"\n        # TODO: add caching here.\n        generations = []\n        new_arg_supported = inspect.signature(self._call).parameters.get(\"run_manager\")\n        for prompt in prompts:\n            text = (\n                self._call(prompt, stop=stop, run_manager=run_manager, **kwargs)\n                if new_arg_supported\n                else self._call(prompt, stop=stop, **kwargs)\n            )\n            generations.append([Generation(text=text)])\n        return LLMResult(generations=generations)\n    async def _agenerate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Run the LLM on the given prompt and input.\"\"\"\n        generations = []\n        new_arg_supported = inspect.signature(self._acall).parameters.get(\"run_manager\")\n        for prompt in prompts:\n            text = (\n                await self._acall(prompt, stop=stop, run_manager=run_manager, **kwargs)\n                if new_arg_supported\n                else await self._acall(prompt, stop=stop, **kwargs)\n            )\n            generations.append([Generation(text=text)])\n        return LLMResult(generations=generations)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html"}
{"id": "58fc1b637108-0", "text": "Source code for langchain.llms.llamacpp\nfrom __future__ import annotations\nimport logging\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Union\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema.output import GenerationChunk\nfrom langchain.utils import get_pydantic_field_names\nfrom langchain.utils.utils import build_extra_kwargs\nif TYPE_CHECKING:\n    from llama_cpp import LlamaGrammar\nlogger = logging.getLogger(__name__)\n[docs]class LlamaCpp(LLM):\n    \"\"\"llama.cpp model.\n    To use, you should have the llama-cpp-python library installed, and provide the\n    path to the Llama model as a named parameter to the constructor.\n    Check out: https://github.com/abetlen/llama-cpp-python\n    Example:\n        .. code-block:: python\n            from langchain.llms import LlamaCpp\n            llm = LlamaCpp(model_path=\"/path/to/llama/model\")\n    \"\"\"\n    client: Any  #: :meta private:\n    model_path: str\n    \"\"\"The path to the Llama model file.\"\"\"\n    lora_base: Optional[str] = None\n    \"\"\"The path to the Llama LoRA base model.\"\"\"\n    lora_path: Optional[str] = None\n    \"\"\"The path to the Llama LoRA. If None, no LoRa is loaded.\"\"\"\n    n_ctx: int = Field(512, alias=\"n_ctx\")\n    \"\"\"Token context window.\"\"\"\n    n_parts: int = Field(-1, alias=\"n_parts\")\n    \"\"\"Number of parts to split the model into.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html"}
{"id": "58fc1b637108-1", "text": "\"\"\"Number of parts to split the model into.\n    If -1, the number of parts is automatically determined.\"\"\"\n    seed: int = Field(-1, alias=\"seed\")\n    \"\"\"Seed. If -1, a random seed is used.\"\"\"\n    f16_kv: bool = Field(True, alias=\"f16_kv\")\n    \"\"\"Use half-precision for key/value cache.\"\"\"\n    logits_all: bool = Field(False, alias=\"logits_all\")\n    \"\"\"Return logits for all tokens, not just the last token.\"\"\"\n    vocab_only: bool = Field(False, alias=\"vocab_only\")\n    \"\"\"Only load the vocabulary, no weights.\"\"\"\n    use_mlock: bool = Field(False, alias=\"use_mlock\")\n    \"\"\"Force system to keep model in RAM.\"\"\"\n    n_threads: Optional[int] = Field(None, alias=\"n_threads\")\n    \"\"\"Number of threads to use.\n    If None, the number of threads is automatically determined.\"\"\"\n    n_batch: Optional[int] = Field(8, alias=\"n_batch\")\n    \"\"\"Number of tokens to process in parallel.\n    Should be a number between 1 and n_ctx.\"\"\"\n    n_gpu_layers: Optional[int] = Field(None, alias=\"n_gpu_layers\")\n    \"\"\"Number of layers to be loaded into gpu memory. Default None.\"\"\"\n    suffix: Optional[str] = Field(None)\n    \"\"\"A suffix to append to the generated text. If None, no suffix is appended.\"\"\"\n    max_tokens: Optional[int] = 256\n    \"\"\"The maximum number of tokens to generate.\"\"\"\n    temperature: Optional[float] = 0.8\n    \"\"\"The temperature to use for sampling.\"\"\"\n    top_p: Optional[float] = 0.95\n    \"\"\"The top-p value to use for sampling.\"\"\"\n    logprobs: Optional[int] = Field(None)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html"}
{"id": "58fc1b637108-2", "text": "logprobs: Optional[int] = Field(None)\n    \"\"\"The number of logprobs to return. If None, no logprobs are returned.\"\"\"\n    echo: Optional[bool] = False\n    \"\"\"Whether to echo the prompt.\"\"\"\n    stop: Optional[List[str]] = []\n    \"\"\"A list of strings to stop generation when encountered.\"\"\"\n    repeat_penalty: Optional[float] = 1.1\n    \"\"\"The penalty to apply to repeated tokens.\"\"\"\n    top_k: Optional[int] = 40\n    \"\"\"The top-k value to use for sampling.\"\"\"\n    last_n_tokens_size: Optional[int] = 64\n    \"\"\"The number of tokens to look back when applying the repeat_penalty.\"\"\"\n    use_mmap: Optional[bool] = True\n    \"\"\"Whether to keep the model loaded in RAM\"\"\"\n    rope_freq_scale: float = 1.0\n    \"\"\"Scale factor for rope sampling.\"\"\"\n    rope_freq_base: float = 10000.0\n    \"\"\"Base frequency for rope sampling.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Any additional parameters to pass to llama_cpp.Llama.\"\"\"\n    streaming: bool = True\n    \"\"\"Whether to stream the results, token by token.\"\"\"\n    grammar_path: Optional[Union[str, Path]] = None\n    \"\"\"\n    grammar_path: Path to the .gbnf file that defines formal grammars\n    for constraining model outputs. For instance, the grammar can be used\n    to force the model to generate valid JSON or to speak exclusively in emojis. At most\n    one of grammar_path and grammar should be passed in.\n    \"\"\"\n    grammar: Optional[Union[str, LlamaGrammar]] = None\n    \"\"\"\n    grammar: formal grammar for constraining model outputs. For instance, the grammar", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html"}
{"id": "58fc1b637108-3", "text": "grammar: formal grammar for constraining model outputs. For instance, the grammar \n    can be used to force the model to generate valid JSON or to speak exclusively in \n    emojis. At most one of grammar_path and grammar should be passed in.\n    \"\"\"\n    verbose: bool = True\n    \"\"\"Print verbose output to stderr.\"\"\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that llama-cpp-python library is installed.\"\"\"\n        try:\n            from llama_cpp import Llama, LlamaGrammar\n        except ImportError:\n            raise ImportError(\n                \"Could not import llama-cpp-python library. \"\n                \"Please install the llama-cpp-python library to \"\n                \"use this embedding model: pip install llama-cpp-python\"\n            )\n        model_path = values[\"model_path\"]\n        model_param_names = [\n            \"rope_freq_scale\",\n            \"rope_freq_base\",\n            \"lora_path\",\n            \"lora_base\",\n            \"n_ctx\",\n            \"n_parts\",\n            \"seed\",\n            \"f16_kv\",\n            \"logits_all\",\n            \"vocab_only\",\n            \"use_mlock\",\n            \"n_threads\",\n            \"n_batch\",\n            \"use_mmap\",\n            \"last_n_tokens_size\",\n            \"verbose\",\n        ]\n        model_params = {k: values[k] for k in model_param_names}\n        # For backwards compatibility, only include if non-null.\n        if values[\"n_gpu_layers\"] is not None:\n            model_params[\"n_gpu_layers\"] = values[\"n_gpu_layers\"]\n        model_params.update(values[\"model_kwargs\"])\n        try:\n            values[\"client\"] = Llama(model_path, **model_params)\n        except Exception as e:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html"}
{"id": "58fc1b637108-4", "text": "except Exception as e:\n            raise ValueError(\n                f\"Could not load Llama model from path: {model_path}. \"\n                f\"Received error {e}\"\n            )\n        if values[\"grammar\"] and values[\"grammar_path\"]:\n            grammar = values[\"grammar\"]\n            grammar_path = values[\"grammar_path\"]\n            raise ValueError(\n                \"Can only pass in one of grammar and grammar_path. Received \"\n                f\"{grammar=} and {grammar_path=}.\"\n            )\n        elif isinstance(values[\"grammar\"], str):\n            values[\"grammar\"] = LlamaGrammar.from_string(values[\"grammar\"])\n        elif values[\"grammar_path\"]:\n            values[\"grammar\"] = LlamaGrammar.from_file(values[\"grammar_path\"])\n        else:\n            pass\n        return values\n    @root_validator(pre=True)\n    def build_model_kwargs(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = get_pydantic_field_names(cls)\n        extra = values.get(\"model_kwargs\", {})\n        values[\"model_kwargs\"] = build_extra_kwargs(\n            extra, values, all_required_field_names\n        )\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling llama_cpp.\"\"\"\n        params = {\n            \"suffix\": self.suffix,\n            \"max_tokens\": self.max_tokens,\n            \"temperature\": self.temperature,\n            \"top_p\": self.top_p,\n            \"logprobs\": self.logprobs,\n            \"echo\": self.echo,\n            \"stop_sequences\": self.stop,  # key here is convention among LLM classes\n            \"repeat_penalty\": self.repeat_penalty,\n            \"top_k\": self.top_k,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html"}
{"id": "58fc1b637108-5", "text": "\"repeat_penalty\": self.repeat_penalty,\n            \"top_k\": self.top_k,\n        }\n        if self.grammar:\n            params[\"grammar\"] = self.grammar\n        return params\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model_path\": self.model_path}, **self._default_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"llamacpp\"\n    def _get_parameters(self, stop: Optional[List[str]] = None) -> Dict[str, Any]:\n        \"\"\"\n        Performs sanity check, preparing parameters in format needed by llama_cpp.\n        Args:\n            stop (Optional[List[str]]): List of stop sequences for llama_cpp.\n        Returns:\n            Dictionary containing the combined parameters.\n        \"\"\"\n        # Raise error if stop sequences are in both input and default params\n        if self.stop and stop is not None:\n            raise ValueError(\"`stop` found in both the input and default params.\")\n        params = self._default_params\n        # llama_cpp expects the \"stop\" key not this, so we remove it:\n        params.pop(\"stop_sequences\")\n        # then sets it as configured, or default to an empty list:\n        params[\"stop\"] = self.stop or stop or []\n        return params\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call the Llama model and return the output.\n        Args:\n            prompt: The prompt to use for generation.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html"}
{"id": "58fc1b637108-6", "text": "Args:\n            prompt: The prompt to use for generation.\n            stop: A list of strings to stop generation when encountered.\n        Returns:\n            The generated text.\n        Example:\n            .. code-block:: python\n                from langchain.llms import LlamaCpp\n                llm = LlamaCpp(model_path=\"/path/to/local/llama/model.bin\")\n                llm(\"This is a prompt.\")\n        \"\"\"\n        if self.streaming:\n            # If streaming is enabled, we use the stream\n            # method that yields as they are generated\n            # and return the combined strings from the first choices's text:\n            combined_text_output = \"\"\n            for chunk in self._stream(\n                prompt=prompt,\n                stop=stop,\n                run_manager=run_manager,\n                **kwargs,\n            ):\n                combined_text_output += chunk.text\n            return combined_text_output\n        else:\n            params = self._get_parameters(stop)\n            params = {**params, **kwargs}\n            result = self.client(prompt=prompt, **params)\n            return result[\"choices\"][0][\"text\"]\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        \"\"\"Yields results objects as they are generated in real time.\n        It also calls the callback manager's on_llm_new_token event with\n        similar parameters to the OpenAI LLM class method of the same name.\n        Args:\n            prompt: The prompts to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            A generator representing the stream of tokens being generated.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html"}
{"id": "58fc1b637108-7", "text": "Returns:\n            A generator representing the stream of tokens being generated.\n        Yields:\n            A dictionary like objects containing a string token and metadata.\n            See llama-cpp-python docs and below for more.\n        Example:\n            .. code-block:: python\n                from langchain.llms import LlamaCpp\n                llm = LlamaCpp(\n                    model_path=\"/path/to/local/model.bin\",\n                    temperature = 0.5\n                )\n                for chunk in llm.stream(\"Ask 'Hi, how are you?' like a pirate:'\",\n                        stop=[\"'\",\"\\n\"]):\n                    result = chunk[\"choices\"][0]\n                    print(result[\"text\"], end='', flush=True)\n        \"\"\"\n        params = {**self._get_parameters(stop), **kwargs}\n        result = self.client(prompt=prompt, stream=True, **params)\n        for part in result:\n            logprobs = part[\"choices\"][0].get(\"logprobs\", None)\n            chunk = GenerationChunk(\n                text=part[\"choices\"][0][\"text\"],\n                generation_info={\"logprobs\": logprobs},\n            )\n            yield chunk\n            if run_manager:\n                run_manager.on_llm_new_token(\n                    token=chunk.text, verbose=self.verbose, log_probs=logprobs\n                )\n[docs]    def get_num_tokens(self, text: str) -> int:\n        tokenized_text = self.client.tokenize(text.encode(\"utf-8\"))\n        return len(tokenized_text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html"}
{"id": "50b0d8486905-0", "text": "Source code for langchain.llms.sagemaker_endpoint\n\"\"\"Sagemaker InvokeEndpoint API.\"\"\"\nimport io\nimport json\nfrom abc import abstractmethod\nfrom typing import Any, Dict, Generic, Iterator, List, Mapping, Optional, TypeVar, Union\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, root_validator\nINPUT_TYPE = TypeVar(\"INPUT_TYPE\", bound=Union[str, List[str]])\nOUTPUT_TYPE = TypeVar(\"OUTPUT_TYPE\", bound=Union[str, List[List[float]], Iterator])\n[docs]class LineIterator:\n    \"\"\"\n    A helper class for parsing the byte stream input.\n    The output of the model will be in the following format:\n    b'{\"outputs\": [\" a\"]}\\n'\n    b'{\"outputs\": [\" challenging\"]}\\n'\n    b'{\"outputs\": [\" problem\"]}\\n'\n    ...\n    While usually each PayloadPart event from the event stream will\n    contain a byte array with a full json, this is not guaranteed\n    and some of the json objects may be split acrossPayloadPart events.\n    For example:\n    {'PayloadPart': {'Bytes': b'{\"outputs\": '}}\n    {'PayloadPart': {'Bytes': b'[\" problem\"]}\\n'}}\n    This class accounts for this by concatenating bytes written via the 'write' function\n    and then exposing a method which will return lines (ending with a '\\n' character)\n    within the buffer via the 'scan_lines' function.\n    It maintains the position of the last read position to ensure\n    that previous bytes are not exposed again.\n    For more details see:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html"}
{"id": "50b0d8486905-1", "text": "that previous bytes are not exposed again.\n    For more details see:\n    https://aws.amazon.com/blogs/machine-learning/elevating-the-generative-ai-experience-introducing-streaming-support-in-amazon-sagemaker-hosting/\n    \"\"\"\n[docs]    def __init__(self, stream: Any) -> None:\n        self.byte_iterator = iter(stream)\n        self.buffer = io.BytesIO()\n        self.read_pos = 0\n    def __iter__(self) -> \"LineIterator\":\n        return self\n    def __next__(self) -> Any:\n        while True:\n            self.buffer.seek(self.read_pos)\n            line = self.buffer.readline()\n            if line and line[-1] == ord(\"\\n\"):\n                self.read_pos += len(line)\n                return line[:-1]\n            try:\n                chunk = next(self.byte_iterator)\n            except StopIteration:\n                if self.read_pos < self.buffer.getbuffer().nbytes:\n                    continue\n                raise\n            if \"PayloadPart\" not in chunk:\n                # Unknown Event Type\n                continue\n            self.buffer.seek(0, io.SEEK_END)\n            self.buffer.write(chunk[\"PayloadPart\"][\"Bytes\"])\n[docs]class ContentHandlerBase(Generic[INPUT_TYPE, OUTPUT_TYPE]):\n    \"\"\"A handler class to transform input from LLM to a\n    format that SageMaker endpoint expects.\n    Similarly, the class handles transforming output from the\n    SageMaker endpoint to a format that LLM class expects.\n    \"\"\"\n    \"\"\"\n    Example:\n        .. code-block:: python\n            class ContentHandler(ContentHandlerBase):\n                content_type = \"application/json\"\n                accepts = \"application/json\"\n                def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html"}
{"id": "50b0d8486905-2", "text": "def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes:\n                    input_str = json.dumps({prompt: prompt, **model_kwargs})\n                    return input_str.encode('utf-8')\n                \n                def transform_output(self, output: bytes) -> str:\n                    response_json = json.loads(output.read().decode(\"utf-8\"))\n                    return response_json[0][\"generated_text\"]\n    \"\"\"\n    content_type: Optional[str] = \"text/plain\"\n    \"\"\"The MIME type of the input data passed to endpoint\"\"\"\n    accepts: Optional[str] = \"text/plain\"\n    \"\"\"The MIME type of the response data returned from endpoint\"\"\"\n[docs]    @abstractmethod\n    def transform_input(self, prompt: INPUT_TYPE, model_kwargs: Dict) -> bytes:\n        \"\"\"Transforms the input to a format that model can accept\n        as the request Body. Should return bytes or seekable file\n        like object in the format specified in the content_type\n        request header.\n        \"\"\"\n[docs]    @abstractmethod\n    def transform_output(self, output: bytes) -> OUTPUT_TYPE:\n        \"\"\"Transforms the output from the model to string that\n        the LLM class expects.\n        \"\"\"\n[docs]class LLMContentHandler(ContentHandlerBase[str, str]):\n    \"\"\"Content handler for LLM class.\"\"\"\n[docs]class SagemakerEndpoint(LLM):\n    \"\"\"Sagemaker Inference Endpoint models.\n    To use, you must supply the endpoint name from your deployed\n    Sagemaker model & the region where it is deployed.\n    To authenticate, the AWS client uses the following methods to\n    automatically load credentials:\n    https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\n    If a specific credential profile should be used, you must pass", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html"}
{"id": "50b0d8486905-3", "text": "If a specific credential profile should be used, you must pass\n    the name of the profile from the ~/.aws/credentials file that is to be used.\n    Make sure the credentials / roles used have the required policies to\n    access the Sagemaker endpoint.\n    See: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html\n    \"\"\"\n    \"\"\"\n    Args:        \n        region_name: The aws region e.g., `us-west-2`.\n            Fallsback to AWS_DEFAULT_REGION env variable\n            or region specified in ~/.aws/config.\n        credentials_profile_name: The name of the profile in the ~/.aws/credentials\n            or ~/.aws/config files, which has either access keys or role information\n            specified. If not specified, the default credential profile or, if on an\n            EC2 instance, credentials from IMDS will be used.\n        client: boto3 client for Sagemaker Endpoint\n        content_handler: Implementation for model specific LLMContentHandler \n    Example:\n        .. code-block:: python\n            from langchain.llms import SagemakerEndpoint\n            endpoint_name = (\n                \"my-endpoint-name\"\n            )\n            region_name = (\n                \"us-west-2\"\n            )\n            credentials_profile_name = (\n                \"default\"\n            )\n            se = SagemakerEndpoint(\n                endpoint_name=endpoint_name,\n                region_name=region_name,\n                credentials_profile_name=credentials_profile_name\n            )\n        #Use with boto3 client\n            client = boto3.client(\n                        \"sagemaker-runtime\",\n                        region_name=region_name\n                    )\n            se = SagemakerEndpoint(\n                endpoint_name=endpoint_name,\n                client=client\n            )\n    \"\"\"\n    client: Any = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html"}
{"id": "50b0d8486905-4", "text": "client=client\n            )\n    \"\"\"\n    client: Any = None\n    \"\"\"Boto3 client for sagemaker runtime\"\"\"\n    endpoint_name: str = \"\"\n    \"\"\"The name of the endpoint from the deployed Sagemaker model.\n    Must be unique within an AWS Region.\"\"\"\n    region_name: str = \"\"\n    \"\"\"The aws region where the Sagemaker model is deployed, eg. `us-west-2`.\"\"\"\n    credentials_profile_name: Optional[str] = None\n    \"\"\"The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which\n    has either access keys or role information specified.\n    If not specified, the default credential profile or, if on an EC2 instance,\n    credentials from IMDS will be used.\n    See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\n    \"\"\"\n    content_handler: LLMContentHandler\n    \"\"\"The content handler class that provides an input and\n    output transform functions to handle formats between LLM\n    and the endpoint.\n    \"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results.\"\"\"\n    \"\"\"\n     Example:\n        .. code-block:: python\n        from langchain.llms.sagemaker_endpoint import LLMContentHandler\n        class ContentHandler(LLMContentHandler):\n                content_type = \"application/json\"\n                accepts = \"application/json\"\n                def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes:\n                    input_str = json.dumps({prompt: prompt, **model_kwargs})\n                    return input_str.encode('utf-8')\n                \n                def transform_output(self, output: bytes) -> str:\n                    response_json = json.loads(output.read().decode(\"utf-8\"))\n                    return response_json[0][\"generated_text\"]\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html"}
{"id": "50b0d8486905-5", "text": "return response_json[0][\"generated_text\"]\n    \"\"\"\n    model_kwargs: Optional[Dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    endpoint_kwargs: Optional[Dict] = None\n    \"\"\"Optional attributes passed to the invoke_endpoint\n    function. See `boto3`_. docs for more info.\n    .. _boto3: <https://boto3.amazonaws.com/v1/documentation/api/latest/index.html>\n    \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Dont do anything if client provided externally\"\"\"\n        if values.get(\"client\") is not None:\n            return values\n        \"\"\"Validate that AWS credentials to and python package exists in environment.\"\"\"\n        try:\n            import boto3\n            try:\n                if values[\"credentials_profile_name\"] is not None:\n                    session = boto3.Session(\n                        profile_name=values[\"credentials_profile_name\"]\n                    )\n                else:\n                    # use default credentials\n                    session = boto3.Session()\n                values[\"client\"] = session.client(\n                    \"sagemaker-runtime\", region_name=values[\"region_name\"]\n                )\n            except Exception as e:\n                raise ValueError(\n                    \"Could not load credentials to authenticate with AWS client. \"\n                    \"Please check that credentials in the specified \"\n                    \"profile name are valid.\"\n                ) from e\n        except ImportError:\n            raise ImportError(\n                \"Could not import boto3 python package. \"\n                \"Please install it with `pip install boto3`.\"\n            )\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html"}
{"id": "50b0d8486905-6", "text": "@property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {\n            **{\"endpoint_name\": self.endpoint_name},\n            **{\"model_kwargs\": _model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"sagemaker_endpoint\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Sagemaker inference endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = se(\"Tell me a joke.\")\n        \"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        _model_kwargs = {**_model_kwargs, **kwargs}\n        _endpoint_kwargs = self.endpoint_kwargs or {}\n        body = self.content_handler.transform_input(prompt, _model_kwargs)\n        content_type = self.content_handler.content_type\n        accepts = self.content_handler.accepts\n        if self.streaming and run_manager:\n            try:\n                resp = self.client.invoke_endpoint_with_response_stream(\n                    EndpointName=self.endpoint_name,\n                    Body=body,\n                    ContentType=self.content_handler.content_type,\n                    **_endpoint_kwargs,\n                )\n                iterator = LineIterator(resp[\"Body\"])\n                current_completion: str = \"\"\n                for line in iterator:\n                    resp = json.loads(line)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html"}
{"id": "50b0d8486905-7", "text": "for line in iterator:\n                    resp = json.loads(line)\n                    resp_output = resp.get(\"outputs\")[0]\n                    if stop is not None:\n                        # Uses same approach as below\n                        resp_output = enforce_stop_tokens(resp_output, stop)\n                    current_completion += resp_output\n                    run_manager.on_llm_new_token(resp_output)\n                return current_completion\n            except Exception as e:\n                raise ValueError(f\"Error raised by streaming inference endpoint: {e}\")\n        else:\n            try:\n                response = self.client.invoke_endpoint(\n                    EndpointName=self.endpoint_name,\n                    Body=body,\n                    ContentType=content_type,\n                    Accept=accepts,\n                    **_endpoint_kwargs,\n                )\n            except Exception as e:\n                raise ValueError(f\"Error raised by inference endpoint: {e}\")\n            text = self.content_handler.transform_output(response[\"Body\"])\n            if stop is not None:\n                # This is a bit hacky, but I can't figure out a better way to enforce\n                # stop tokens when making calls to the sagemaker endpoint.\n                text = enforce_stop_tokens(text, stop)\n            return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html"}
{"id": "76cbe0573d07-0", "text": "Source code for langchain.llms.pai_eas_endpoint\nimport json\nimport logging\nfrom typing import Any, Dict, Iterator, List, Mapping, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import root_validator\nfrom langchain.schema.output import GenerationChunk\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class PaiEasEndpoint(LLM):\n    \"\"\"Langchain LLM class to help to access eass llm service.\n        To use this endpoint, must have a deployed eas chat llm service on PAI AliCloud.\n    One can set the environment variable ``eas_service_url`` and ``eas_service_token``.\n    The environment variables can set with your eas service url and service token.\n    Example:\n        .. code-block:: python\n            from langchain.llms.pai_eas_endpoint import PaiEasEndpoint\n            eas_chat_endpoint = PaiEasChatEndpoint(\n                eas_service_url=\"your_service_url\",\n                eas_service_token=\"your_service_token\"\n            )\n    \"\"\"\n    \"\"\"PAI-EAS Service URL\"\"\"\n    eas_service_url: str\n    \"\"\"PAI-EAS Service TOKEN\"\"\"\n    eas_service_token: str\n    \"\"\"PAI-EAS Service Infer Params\"\"\"\n    max_new_tokens: Optional[int] = 512\n    temperature: Optional[float] = 0.95\n    top_p: Optional[float] = 0.1\n    top_k: Optional[int] = 0\n    stop_sequences: Optional[List[str]] = None\n    \"\"\"Enable stream chat mode.\"\"\"\n    streaming: bool = False", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pai_eas_endpoint.html"}
{"id": "76cbe0573d07-1", "text": "\"\"\"Enable stream chat mode.\"\"\"\n    streaming: bool = False\n    \"\"\"Key/value arguments to pass to the model. Reserved for future use\"\"\"\n    model_kwargs: Optional[dict] = None\n    version: Optional[str] = \"2.0\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"eas_service_url\"] = get_from_dict_or_env(\n            values, \"eas_service_url\", \"EAS_SERVICE_URL\"\n        )\n        values[\"eas_service_token\"] = get_from_dict_or_env(\n            values, \"eas_service_token\", \"EAS_SERVICE_TOKEN\"\n        )\n        return values\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"pai_eas_endpoint\"\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Cohere API.\"\"\"\n        return {\n            \"max_new_tokens\": self.max_new_tokens,\n            \"temperature\": self.temperature,\n            \"top_k\": self.top_k,\n            \"top_p\": self.top_p,\n            \"stop_sequences\": [],\n        }\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {\n            \"eas_service_url\": self.eas_service_url,\n            \"eas_service_token\": self.eas_service_token,\n            **_model_kwargs,\n        }\n    def _invocation_params(\n        self, stop_sequences: Optional[List[str]], **kwargs: Any\n    ) -> dict:\n        params = self._default_params", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pai_eas_endpoint.html"}
{"id": "76cbe0573d07-2", "text": ") -> dict:\n        params = self._default_params\n        if self.stop_sequences is not None and stop_sequences is not None:\n            raise ValueError(\"`stop` found in both the input and default params.\")\n        elif self.stop_sequences is not None:\n            params[\"stop\"] = self.stop_sequences\n        else:\n            params[\"stop\"] = stop_sequences\n        if self.model_kwargs:\n            params.update(self.model_kwargs)\n        return {**params, **kwargs}\n    @staticmethod\n    def _process_response(\n        response: Any, stop: Optional[List[str]], version: Optional[str]\n    ) -> str:\n        if version == \"1.0\":\n            text = response\n        else:\n            text = response[\"response\"]\n        if stop:\n            text = enforce_stop_tokens(text, stop)\n        return \"\".join(text)\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        params = self._invocation_params(stop, **kwargs)\n        prompt = prompt.strip()\n        response = None\n        try:\n            if self.streaming:\n                completion = \"\"\n                for chunk in self._stream(prompt, stop, run_manager, **params):\n                    completion += chunk.text\n                return completion\n            else:\n                response = self._call_eas(prompt, params)\n                _stop = params.get(\"stop\")\n                return self._process_response(response, _stop, self.version)\n        except Exception as error:\n            raise ValueError(f\"Error raised by the service: {error}\")\n    def _call_eas(self, prompt: str = \"\", params: Dict = {}) -> Any:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pai_eas_endpoint.html"}
{"id": "76cbe0573d07-3", "text": "\"\"\"Generate text from the eas service.\"\"\"\n        headers = {\n            \"Content-Type\": \"application/json\",\n            \"Authorization\": f\"{self.eas_service_token}\",\n        }\n        if self.version == \"1.0\":\n            body = {\n                \"input_ids\": f\"{prompt}\",\n            }\n        else:\n            body = {\n                \"prompt\": f\"{prompt}\",\n            }\n        # add params to body\n        for key, value in params.items():\n            body[key] = value\n        # make request\n        response = requests.post(self.eas_service_url, headers=headers, json=body)\n        if response.status_code != 200:\n            raise Exception(\n                f\"Request failed with status code {response.status_code}\"\n                f\" and message {response.text}\"\n            )\n        try:\n            return json.loads(response.text)\n        except Exception as e:\n            if isinstance(e, json.decoder.JSONDecodeError):\n                return response.text\n            raise e\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        invocation_params = self._invocation_params(stop, **kwargs)\n        headers = {\n            \"User-Agent\": \"Test Client\",\n            \"Authorization\": f\"{self.eas_service_token}\",\n        }\n        if self.version == \"1.0\":\n            pload = {\"input_ids\": prompt, **invocation_params}\n            response = requests.post(\n                self.eas_service_url, headers=headers, json=pload, stream=True\n            )\n            res = GenerationChunk(text=response.text)\n            if run_manager:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pai_eas_endpoint.html"}
{"id": "76cbe0573d07-4", "text": ")\n            res = GenerationChunk(text=response.text)\n            if run_manager:\n                run_manager.on_llm_new_token(res.text)\n            # yield text, if any\n            yield res\n        else:\n            pload = {\"prompt\": prompt, \"use_stream_chat\": \"True\", **invocation_params}\n            response = requests.post(\n                self.eas_service_url, headers=headers, json=pload, stream=True\n            )\n            for chunk in response.iter_lines(\n                chunk_size=8192, decode_unicode=False, delimiter=b\"\\0\"\n            ):\n                if chunk:\n                    data = json.loads(chunk.decode(\"utf-8\"))\n                    output = data[\"response\"]\n                    # identify stop sequence in generated text, if any\n                    stop_seq_found: Optional[str] = None\n                    for stop_seq in invocation_params[\"stop\"]:\n                        if stop_seq in output:\n                            stop_seq_found = stop_seq\n                    # identify text to yield\n                    text: Optional[str] = None\n                    if stop_seq_found:\n                        text = output[: output.index(stop_seq_found)]\n                    else:\n                        text = output\n                    # yield text, if any\n                    if text:\n                        res = GenerationChunk(text=text)\n                        yield res\n                        if run_manager:\n                            run_manager.on_llm_new_token(res.text)\n                    # break if stop sequence found\n                    if stop_seq_found:\n                        break", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pai_eas_endpoint.html"}
{"id": "b589661046c3-0", "text": "Source code for langchain.llms.huggingface_text_gen_inference\nimport logging\nfrom typing import Any, AsyncIterator, Dict, Iterator, List, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.schema.output import GenerationChunk\nfrom langchain.utils import get_pydantic_field_names\nlogger = logging.getLogger(__name__)\n[docs]class HuggingFaceTextGenInference(LLM):\n    \"\"\"\n    HuggingFace text generation API.\n    To use, you should have the `text-generation` python package installed and\n    a text-generation server running.\n    Example:\n        .. code-block:: python\n            # Basic Example (no streaming)\n            llm = HuggingFaceTextGenInference(\n                inference_server_url=\"http://localhost:8010/\",\n                max_new_tokens=512,\n                top_k=10,\n                top_p=0.95,\n                typical_p=0.95,\n                temperature=0.01,\n                repetition_penalty=1.03,\n            )\n            print(llm(\"What is Deep Learning?\"))\n            # Streaming response example\n            from langchain.callbacks import streaming_stdout\n            callbacks = [streaming_stdout.StreamingStdOutCallbackHandler()]\n            llm = HuggingFaceTextGenInference(\n                inference_server_url=\"http://localhost:8010/\",\n                max_new_tokens=512,\n                top_k=10,\n                top_p=0.95,\n                typical_p=0.95,\n                temperature=0.01,\n                repetition_penalty=1.03,\n                callbacks=callbacks,\n                streaming=True\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html"}
{"id": "b589661046c3-1", "text": "callbacks=callbacks,\n                streaming=True\n            )\n            print(llm(\"What is Deep Learning?\"))\n    \"\"\"\n    max_new_tokens: int = 512\n    \"\"\"Maximum number of generated tokens\"\"\"\n    top_k: Optional[int] = None\n    \"\"\"The number of highest probability vocabulary tokens to keep for\n    top-k-filtering.\"\"\"\n    top_p: Optional[float] = 0.95\n    \"\"\"If set to < 1, only the smallest set of most probable tokens with probabilities\n    that add up to `top_p` or higher are kept for generation.\"\"\"\n    typical_p: Optional[float] = 0.95\n    \"\"\"Typical Decoding mass. See [Typical Decoding for Natural Language\n    Generation](https://arxiv.org/abs/2202.00666) for more information.\"\"\"\n    temperature: Optional[float] = 0.8\n    \"\"\"The value used to module the logits distribution.\"\"\"\n    repetition_penalty: Optional[float] = None\n    \"\"\"The parameter for repetition penalty. 1.0 means no penalty.\n    See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.\"\"\"\n    return_full_text: bool = False\n    \"\"\"Whether to prepend the prompt to the generated text\"\"\"\n    truncate: Optional[int] = None\n    \"\"\"Truncate inputs tokens to the given size\"\"\"\n    stop_sequences: List[str] = Field(default_factory=list)\n    \"\"\"Stop generating tokens if a member of `stop_sequences` is generated\"\"\"\n    seed: Optional[int] = None\n    \"\"\"Random sampling seed\"\"\"\n    inference_server_url: str = \"\"\n    \"\"\"text-generation-inference instance base url\"\"\"\n    timeout: int = 120\n    \"\"\"Timeout in seconds\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to generate a stream of tokens asynchronously\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html"}
{"id": "b589661046c3-2", "text": "streaming: bool = False\n    \"\"\"Whether to generate a stream of tokens asynchronously\"\"\"\n    do_sample: bool = False\n    \"\"\"Activate logits sampling\"\"\"\n    watermark: bool = False\n    \"\"\"Watermarking with [A Watermark for Large Language Models]\n    (https://arxiv.org/abs/2301.10226)\"\"\"\n    server_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any text-generation-inference server parameters not explicitly specified\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `call` not explicitly specified\"\"\"\n    client: Any\n    async_client: Any\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = get_pydantic_field_names(cls)\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name in extra:\n                raise ValueError(f\"Found {field_name} supplied twice.\")\n            if field_name not in all_required_field_names:\n                logger.warning(\n                    f\"\"\"WARNING! {field_name} is not default parameter.\n                    {field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        invalid_model_kwargs = all_required_field_names.intersection(extra.keys())\n        if invalid_model_kwargs:\n            raise ValueError(\n                f\"Parameters {invalid_model_kwargs} should be specified explicitly. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html"}
{"id": "b589661046c3-3", "text": "f\"Parameters {invalid_model_kwargs} should be specified explicitly. \"\n                f\"Instead they were passed in as part of `model_kwargs` parameter.\"\n            )\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that python package exists in environment.\"\"\"\n        try:\n            import text_generation\n            values[\"client\"] = text_generation.Client(\n                values[\"inference_server_url\"],\n                timeout=values[\"timeout\"],\n                **values[\"server_kwargs\"],\n            )\n            values[\"async_client\"] = text_generation.AsyncClient(\n                values[\"inference_server_url\"],\n                timeout=values[\"timeout\"],\n                **values[\"server_kwargs\"],\n            )\n        except ImportError:\n            raise ImportError(\n                \"Could not import text_generation python package. \"\n                \"Please install it with `pip install text_generation`.\"\n            )\n        return values\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"huggingface_textgen_inference\"\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling text generation inference API.\"\"\"\n        return {\n            \"max_new_tokens\": self.max_new_tokens,\n            \"top_k\": self.top_k,\n            \"top_p\": self.top_p,\n            \"typical_p\": self.typical_p,\n            \"temperature\": self.temperature,\n            \"repetition_penalty\": self.repetition_penalty,\n            \"return_full_text\": self.return_full_text,\n            \"truncate\": self.truncate,\n            \"stop_sequences\": self.stop_sequences,\n            \"seed\": self.seed,\n            \"do_sample\": self.do_sample,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html"}
{"id": "b589661046c3-4", "text": "\"seed\": self.seed,\n            \"do_sample\": self.do_sample,\n            \"watermark\": self.watermark,\n            **self.model_kwargs,\n        }\n    def _invocation_params(\n        self, runtime_stop: Optional[List[str]], **kwargs: Any\n    ) -> Dict[str, Any]:\n        params = {**self._default_params, **kwargs}\n        params[\"stop_sequences\"] = params[\"stop_sequences\"] + (runtime_stop or [])\n        return params\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        if self.streaming:\n            completion = \"\"\n            for chunk in self._stream(prompt, stop, run_manager, **kwargs):\n                completion += chunk.text\n            return completion\n        invocation_params = self._invocation_params(stop, **kwargs)\n        res = self.client.generate(prompt, **invocation_params)\n        # remove stop sequences from the end of the generated text\n        for stop_seq in invocation_params[\"stop_sequences\"]:\n            if stop_seq in res.generated_text:\n                res.generated_text = res.generated_text[\n                    : res.generated_text.index(stop_seq)\n                ]\n        return res.generated_text\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        if self.streaming:\n            completion = \"\"\n            async for chunk in self._astream(prompt, stop, run_manager, **kwargs):\n                completion += chunk.text\n            return completion", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html"}
{"id": "b589661046c3-5", "text": "completion += chunk.text\n            return completion\n        invocation_params = self._invocation_params(stop, **kwargs)\n        res = await self.async_client.generate(prompt, **invocation_params)\n        # remove stop sequences from the end of the generated text\n        for stop_seq in invocation_params[\"stop_sequences\"]:\n            if stop_seq in res.generated_text:\n                res.generated_text = res.generated_text[\n                    : res.generated_text.index(stop_seq)\n                ]\n        return res.generated_text\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        invocation_params = self._invocation_params(stop, **kwargs)\n        for res in self.client.generate_stream(prompt, **invocation_params):\n            # identify stop sequence in generated text, if any\n            stop_seq_found: Optional[str] = None\n            for stop_seq in invocation_params[\"stop_sequences\"]:\n                if stop_seq in res.token.text:\n                    stop_seq_found = stop_seq\n            # identify text to yield\n            text: Optional[str] = None\n            if res.token.special:\n                text = None\n            elif stop_seq_found:\n                text = res.token.text[: res.token.text.index(stop_seq_found)]\n            else:\n                text = res.token.text\n            # yield text, if any\n            if text:\n                chunk = GenerationChunk(text=text)\n                yield chunk\n                if run_manager:\n                    run_manager.on_llm_new_token(chunk.text)\n            # break if stop sequence found\n            if stop_seq_found:\n                break\n    async def _astream(\n        self,\n        prompt: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html"}
{"id": "b589661046c3-6", "text": "async def _astream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[GenerationChunk]:\n        invocation_params = self._invocation_params(stop, **kwargs)\n        async for res in self.async_client.generate_stream(prompt, **invocation_params):\n            # identify stop sequence in generated text, if any\n            stop_seq_found: Optional[str] = None\n            for stop_seq in invocation_params[\"stop_sequences\"]:\n                if stop_seq in res.token.text:\n                    stop_seq_found = stop_seq\n            # identify text to yield\n            text: Optional[str] = None\n            if res.token.special:\n                text = None\n            elif stop_seq_found:\n                text = res.token.text[: res.token.text.index(stop_seq_found)]\n            else:\n                text = res.token.text\n            # yield text, if any\n            if text:\n                chunk = GenerationChunk(text=text)\n                yield chunk\n                if run_manager:\n                    await run_manager.on_llm_new_token(chunk.text)\n            # break if stop sequence found\n            if stop_seq_found:\n                break", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html"}
{"id": "beda28bd3e53-0", "text": "Source code for langchain.llms.arcee\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utilities.arcee import ArceeWrapper, DALMFilter\nfrom langchain.utils import get_from_dict_or_env\n[docs]class Arcee(LLM):\n    \"\"\"Arcee's Domain Adapted Language Models (DALMs).\n    To use, set the ``ARCEE_API_KEY`` environment variable with your Arcee API key,\n    or pass ``arcee_api_key`` as a named parameter.\n    Example:\n        .. code-block:: python\n            from langchain.llms import Arcee\n            arcee = Arcee(\n                model=\"DALM-PubMed\",\n                arcee_api_key=\"ARCEE-API-KEY\"\n            )\n            response = arcee(\"AI-driven music therapy\")\n    \"\"\"\n    _client: Optional[ArceeWrapper] = None  #: :meta private:\n    \"\"\"Arcee _client.\"\"\"\n    arcee_api_key: str = \"\"\n    \"\"\"Arcee API Key\"\"\"\n    model: str\n    \"\"\"Arcee DALM name\"\"\"\n    arcee_api_url: str = \"https://api.arcee.ai\"\n    \"\"\"Arcee API URL\"\"\"\n    arcee_api_version: str = \"v2\"\n    \"\"\"Arcee API Version\"\"\"\n    arcee_app_url: str = \"https://app.arcee.ai\"\n    \"\"\"Arcee App URL\"\"\"\n    model_id: str = \"\"\n    \"\"\"Arcee Model ID\"\"\"\n    model_kwargs: Optional[Dict[str, Any]] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    class Config:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/arcee.html"}
{"id": "beda28bd3e53-1", "text": "\"\"\"Keyword arguments to pass to the model.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n        underscore_attrs_are_private = True\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"arcee\"\n    def __init__(self, **data: Any) -> None:\n        \"\"\"Initializes private fields.\"\"\"\n        super().__init__(**data)\n        self._client = None\n        self._client = ArceeWrapper(\n            arcee_api_key=self.arcee_api_key,\n            arcee_api_url=self.arcee_api_url,\n            arcee_api_version=self.arcee_api_version,\n            model_kwargs=self.model_kwargs,\n            model_name=self.model,\n        )\n        self._client.validate_model_training_status()\n    @root_validator()\n    def validate_environments(cls, values: Dict) -> Dict:\n        \"\"\"Validate Arcee environment variables.\"\"\"\n        # validate env vars\n        values[\"arcee_api_key\"] = get_from_dict_or_env(\n            values,\n            \"arcee_api_key\",\n            \"ARCEE_API_KEY\",\n        )\n        values[\"arcee_api_url\"] = get_from_dict_or_env(\n            values,\n            \"arcee_api_url\",\n            \"ARCEE_API_URL\",\n        )\n        values[\"arcee_app_url\"] = get_from_dict_or_env(\n            values,\n            \"arcee_app_url\",\n            \"ARCEE_APP_URL\",\n        )\n        values[\"arcee_api_version\"] = get_from_dict_or_env(\n            values,\n            \"arcee_api_version\",\n            \"ARCEE_API_VERSION\",\n        )\n        # validate model kwargs\n        if values[\"model_kwargs\"]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/arcee.html"}
{"id": "beda28bd3e53-2", "text": ")\n        # validate model kwargs\n        if values[\"model_kwargs\"]:\n            kw = values[\"model_kwargs\"]\n            # validate size\n            if kw.get(\"size\") is not None:\n                if not kw.get(\"size\") >= 0:\n                    raise ValueError(\"`size` must be positive\")\n            # validate filters\n            if kw.get(\"filters\") is not None:\n                if not isinstance(kw.get(\"filters\"), List):\n                    raise ValueError(\"`filters` must be a list\")\n                for f in kw.get(\"filters\"):\n                    DALMFilter(**f)\n        return values\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Generate text from Arcee DALM.\n        Args:\n            prompt: Prompt to generate text from.\n            size: The max number of context results to retrieve.\n            Defaults to 3. (Can be less if filters are provided).\n            filters: Filters to apply to the context dataset.\n        \"\"\"\n        try:\n            if not self._client:\n                raise ValueError(\"Client is not initialized.\")\n            return self._client.generate(prompt=prompt, **kwargs)\n        except Exception as e:\n            raise Exception(f\"Failed to generate text: {e}\") from e", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/arcee.html"}
{"id": "780809a1d861-0", "text": "Source code for langchain.llms.utils\n\"\"\"Common utility functions for LLM APIs.\"\"\"\nimport re\nfrom typing import List\n[docs]def enforce_stop_tokens(text: str, stop: List[str]) -> str:\n    \"\"\"Cut off the text as soon as any stop words occur.\"\"\"\n    return re.split(\"|\".join(stop), text, maxsplit=1)[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/utils.html"}
{"id": "b105c5230567-0", "text": "Source code for langchain.llms.predibase\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Field\n[docs]class Predibase(LLM):\n    \"\"\"Use your Predibase models with Langchain.\n    To use, you should have the ``predibase`` python package installed,\n    and have your Predibase API key.\n    \"\"\"\n    model: str\n    predibase_api_key: str\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    @property\n    def _llm_type(self) -> str:\n        return \"predibase\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        try:\n            from predibase import PredibaseClient\n            pc = PredibaseClient(token=self.predibase_api_key)\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import Predibase Python package. \"\n                \"Please install it with `pip install predibase`.\"\n            ) from e\n        except ValueError as e:\n            raise ValueError(\"Your API key is not correct. Please try again\") from e\n        # load model and version\n        results = pc.prompt(prompt, model_name=self.model)\n        return results[0].response\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"model_kwargs\": self.model_kwargs},\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/predibase.html"}
{"id": "17b28a4d92cb-0", "text": "Source code for langchain.llms.forefrontai\nfrom typing import Any, Dict, List, Mapping, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class ForefrontAI(LLM):\n    \"\"\"ForefrontAI large language models.\n    To use, you should have the environment variable ``FOREFRONTAI_API_KEY``\n    set with your API key.\n    Example:\n        .. code-block:: python\n            from langchain.llms import ForefrontAI\n            forefrontai = ForefrontAI(endpoint_url=\"\")\n    \"\"\"\n    endpoint_url: str = \"\"\n    \"\"\"Model name to use.\"\"\"\n    temperature: float = 0.7\n    \"\"\"What sampling temperature to use.\"\"\"\n    length: int = 256\n    \"\"\"The maximum number of tokens to generate in the completion.\"\"\"\n    top_p: float = 1.0\n    \"\"\"Total probability mass of tokens to consider at each step.\"\"\"\n    top_k: int = 40\n    \"\"\"The number of highest probability vocabulary tokens to\n    keep for top-k-filtering.\"\"\"\n    repetition_penalty: int = 1\n    \"\"\"Penalizes repeated tokens according to frequency.\"\"\"\n    forefrontai_api_key: Optional[str] = None\n    base_url: Optional[str] = None\n    \"\"\"Base url to use, if None decides based on model name.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key exists in environment.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html"}
{"id": "17b28a4d92cb-1", "text": "\"\"\"Validate that api key exists in environment.\"\"\"\n        forefrontai_api_key = get_from_dict_or_env(\n            values, \"forefrontai_api_key\", \"FOREFRONTAI_API_KEY\"\n        )\n        values[\"forefrontai_api_key\"] = forefrontai_api_key\n        return values\n    @property\n    def _default_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the default parameters for calling ForefrontAI API.\"\"\"\n        return {\n            \"temperature\": self.temperature,\n            \"length\": self.length,\n            \"top_p\": self.top_p,\n            \"top_k\": self.top_k,\n            \"repetition_penalty\": self.repetition_penalty,\n        }\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"endpoint_url\": self.endpoint_url}, **self._default_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"forefrontai\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to ForefrontAI's complete endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = ForefrontAI(\"Tell me a joke.\")\n        \"\"\"\n        response = requests.post(\n            url=self.endpoint_url,\n            headers={", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html"}
{"id": "17b28a4d92cb-2", "text": "response = requests.post(\n            url=self.endpoint_url,\n            headers={\n                \"Authorization\": f\"Bearer {self.forefrontai_api_key}\",\n                \"Content-Type\": \"application/json\",\n            },\n            json={\"text\": prompt, **self._default_params, **kwargs},\n        )\n        response_json = response.json()\n        text = response_json[\"result\"][0][\"completion\"]\n        if stop is not None:\n            # I believe this is required since the stop tokens\n            # are not enforced by the model parameters\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html"}
{"id": "b1b951170b9d-0", "text": "Source code for langchain.llms.aviary\nimport dataclasses\nimport os\nfrom typing import Any, Dict, List, Mapping, Optional, Union, cast\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\nTIMEOUT = 60\n[docs]@dataclasses.dataclass\nclass AviaryBackend:\n    \"\"\"Aviary backend.\n    Attributes:\n        backend_url: The URL for the Aviary backend.\n        bearer: The bearer token for the Aviary backend.\n    \"\"\"\n    backend_url: str\n    bearer: str\n    def __post_init__(self) -> None:\n        self.header = {\"Authorization\": self.bearer}\n[docs]    @classmethod\n    def from_env(cls) -> \"AviaryBackend\":\n        aviary_url = os.getenv(\"AVIARY_URL\")\n        assert aviary_url, \"AVIARY_URL must be set\"\n        aviary_token = os.getenv(\"AVIARY_TOKEN\", \"\")\n        bearer = f\"Bearer {aviary_token}\" if aviary_token else \"\"\n        aviary_url += \"/\" if not aviary_url.endswith(\"/\") else \"\"\n        return cls(aviary_url, bearer)\n[docs]def get_models() -> List[str]:\n    \"\"\"List available models\"\"\"\n    backend = AviaryBackend.from_env()\n    request_url = backend.backend_url + \"-/routes\"\n    response = requests.get(request_url, headers=backend.header, timeout=TIMEOUT)\n    try:\n        result = response.json()\n    except requests.JSONDecodeError as e:\n        raise RuntimeError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html"}
{"id": "b1b951170b9d-1", "text": "except requests.JSONDecodeError as e:\n        raise RuntimeError(\n            f\"Error decoding JSON from {request_url}. Text response: {response.text}\"\n        ) from e\n    result = sorted(\n        [k.lstrip(\"/\").replace(\"--\", \"/\") for k in result.keys() if \"--\" in k]\n    )\n    return result\n[docs]def get_completions(\n    model: str,\n    prompt: str,\n    use_prompt_format: bool = True,\n    version: str = \"\",\n) -> Dict[str, Union[str, float, int]]:\n    \"\"\"Get completions from Aviary models.\"\"\"\n    backend = AviaryBackend.from_env()\n    url = backend.backend_url + model.replace(\"/\", \"--\") + \"/\" + version + \"query\"\n    response = requests.post(\n        url,\n        headers=backend.header,\n        json={\"prompt\": prompt, \"use_prompt_format\": use_prompt_format},\n        timeout=TIMEOUT,\n    )\n    try:\n        return response.json()\n    except requests.JSONDecodeError as e:\n        raise RuntimeError(\n            f\"Error decoding JSON from {url}. Text response: {response.text}\"\n        ) from e\n[docs]class Aviary(LLM):\n    \"\"\"Aviary hosted models.\n    Aviary is a backend for hosted models. You can\n    find out more about aviary at\n    http://github.com/ray-project/aviary\n    To get a list of the models supported on an\n    aviary, follow the instructions on the website to\n    install the aviary CLI and then use:\n    `aviary models`\n    AVIARY_URL and AVIARY_TOKEN environment variables must be set.\n    Attributes:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html"}
{"id": "b1b951170b9d-2", "text": "Attributes:\n        model: The name of the model to use. Defaults to \"amazon/LightGPT\".\n        aviary_url: The URL for the Aviary backend. Defaults to None.\n        aviary_token: The bearer token for the Aviary backend. Defaults to None.\n        use_prompt_format: If True, the prompt template for the model will be ignored.\n            Defaults to True.\n        version: API version to use for Aviary. Defaults to None.\n    Example:\n        .. code-block:: python\n            from langchain.llms import Aviary\n            os.environ[\"AVIARY_URL\"] = \"<URL>\"\n            os.environ[\"AVIARY_TOKEN\"] = \"<TOKEN>\"\n            light = Aviary(model='amazon/LightGPT')\n            output = light('How do you make fried rice?')\n    \"\"\"\n    model: str = \"amazon/LightGPT\"\n    aviary_url: Optional[str] = None\n    aviary_token: Optional[str] = None\n    # If True the prompt template for the model will be ignored.\n    use_prompt_format: bool = True\n    # API version to use for Aviary\n    version: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        aviary_url = get_from_dict_or_env(values, \"aviary_url\", \"AVIARY_URL\")\n        aviary_token = get_from_dict_or_env(values, \"aviary_token\", \"AVIARY_TOKEN\")\n        # Set env viarables for aviary sdk\n        os.environ[\"AVIARY_URL\"] = aviary_url", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html"}
{"id": "b1b951170b9d-3", "text": "os.environ[\"AVIARY_URL\"] = aviary_url\n        os.environ[\"AVIARY_TOKEN\"] = aviary_token\n        try:\n            aviary_models = get_models()\n        except requests.exceptions.RequestException as e:\n            raise ValueError(e)\n        model = values.get(\"model\")\n        if model and model not in aviary_models:\n            raise ValueError(f\"{aviary_url} does not support model {values['model']}.\")\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"model_name\": self.model,\n            \"aviary_url\": self.aviary_url,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return f\"aviary-{self.model.replace('/', '-')}\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Aviary\n        Args:\n            prompt: The prompt to pass into the model.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = aviary(\"Tell me a joke.\")\n        \"\"\"\n        kwargs = {\"use_prompt_format\": self.use_prompt_format}\n        if self.version:\n            kwargs[\"version\"] = self.version\n        output = get_completions(\n            model=self.model,\n            prompt=prompt,\n            **kwargs,\n        )\n        text = cast(str, output[\"generated_text\"])\n        if stop:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html"}
{"id": "b1b951170b9d-4", "text": ")\n        text = cast(str, output[\"generated_text\"])\n        if stop:\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html"}
{"id": "eee6a94c5ba7-0", "text": "Source code for langchain.llms.loading\n\"\"\"Base interface for loading large language model APIs.\"\"\"\nimport json\nfrom pathlib import Path\nfrom typing import Union\nimport yaml\nfrom langchain.llms import get_type_to_cls_dict\nfrom langchain.llms.base import BaseLLM\n[docs]def load_llm_from_config(config: dict) -> BaseLLM:\n    \"\"\"Load LLM from Config Dict.\"\"\"\n    if \"_type\" not in config:\n        raise ValueError(\"Must specify an LLM Type in config\")\n    config_type = config.pop(\"_type\")\n    type_to_cls_dict = get_type_to_cls_dict()\n    if config_type not in type_to_cls_dict:\n        raise ValueError(f\"Loading {config_type} LLM not supported\")\n    llm_cls = type_to_cls_dict[config_type]()\n    return llm_cls(**config)\n[docs]def load_llm(file: Union[str, Path]) -> BaseLLM:\n    \"\"\"Load LLM from file.\"\"\"\n    # Convert file to Path object.\n    if isinstance(file, str):\n        file_path = Path(file)\n    else:\n        file_path = file\n    # Load from either json or yaml.\n    if file_path.suffix == \".json\":\n        with open(file_path) as f:\n            config = json.load(f)\n    elif file_path.suffix == \".yaml\":\n        with open(file_path, \"r\") as f:\n            config = yaml.safe_load(f)\n    else:\n        raise ValueError(\"File type must be json or yaml\")\n    # Load the LLM from the config now.\n    return load_llm_from_config(config)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/loading.html"}
{"id": "a9f9581add47-0", "text": "Source code for langchain.llms.aleph_alpha\nfrom typing import Any, Dict, List, Optional, Sequence\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utils import convert_to_secret_str, get_from_dict_or_env\n[docs]class AlephAlpha(LLM):\n    \"\"\"Aleph Alpha large language models.\n    To use, you should have the ``aleph_alpha_client`` python package installed, and the\n    environment variable ``ALEPH_ALPHA_API_KEY`` set with your API key, or pass\n    it as a named parameter to the constructor.\n    Parameters are explained more in depth here:\n    https://github.com/Aleph-Alpha/aleph-alpha-client/blob/c14b7dd2b4325c7da0d6a119f6e76385800e097b/aleph_alpha_client/completion.py#L10\n    Example:\n        .. code-block:: python\n            from langchain.llms import AlephAlpha\n            aleph_alpha = AlephAlpha(aleph_alpha_api_key=\"my-api-key\")\n    \"\"\"\n    client: Any  #: :meta private:\n    model: Optional[str] = \"luminous-base\"\n    \"\"\"Model name to use.\"\"\"\n    maximum_tokens: int = 64\n    \"\"\"The maximum number of tokens to be generated.\"\"\"\n    temperature: float = 0.0\n    \"\"\"A non-negative float that tunes the degree of randomness in generation.\"\"\"\n    top_k: int = 0\n    \"\"\"Number of most likely tokens to consider at each step.\"\"\"\n    top_p: float = 0.0\n    \"\"\"Total probability mass of tokens to consider at each step.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html"}
{"id": "a9f9581add47-1", "text": "\"\"\"Total probability mass of tokens to consider at each step.\"\"\"\n    presence_penalty: float = 0.0\n    \"\"\"Penalizes repeated tokens.\"\"\"\n    frequency_penalty: float = 0.0\n    \"\"\"Penalizes repeated tokens according to frequency.\"\"\"\n    repetition_penalties_include_prompt: Optional[bool] = False\n    \"\"\"Flag deciding whether presence penalty or frequency penalty are\n    updated from the prompt.\"\"\"\n    use_multiplicative_presence_penalty: Optional[bool] = False\n    \"\"\"Flag deciding whether presence penalty is applied\n    multiplicatively (True) or additively (False).\"\"\"\n    penalty_bias: Optional[str] = None\n    \"\"\"Penalty bias for the completion.\"\"\"\n    penalty_exceptions: Optional[List[str]] = None\n    \"\"\"List of strings that may be generated without penalty,\n    regardless of other penalty settings\"\"\"\n    penalty_exceptions_include_stop_sequences: Optional[bool] = None\n    \"\"\"Should stop_sequences be included in penalty_exceptions.\"\"\"\n    best_of: Optional[int] = None\n    \"\"\"returns the one with the \"best of\" results\n    (highest log probability per token)\n    \"\"\"\n    n: int = 1\n    \"\"\"How many completions to generate for each prompt.\"\"\"\n    logit_bias: Optional[Dict[int, float]] = None\n    \"\"\"The logit bias allows to influence the likelihood of generating tokens.\"\"\"\n    log_probs: Optional[int] = None\n    \"\"\"Number of top log probabilities to be returned for each generated token.\"\"\"\n    tokens: Optional[bool] = False\n    \"\"\"return tokens of completion.\"\"\"\n    disable_optimizations: Optional[bool] = False\n    minimum_tokens: Optional[int] = 0\n    \"\"\"Generate at least this number of tokens.\"\"\"\n    echo: bool = False\n    \"\"\"Echo the prompt in the completion.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html"}
{"id": "a9f9581add47-2", "text": "echo: bool = False\n    \"\"\"Echo the prompt in the completion.\"\"\"\n    use_multiplicative_frequency_penalty: bool = False\n    sequence_penalty: float = 0.0\n    sequence_penalty_min_length: int = 2\n    use_multiplicative_sequence_penalty: bool = False\n    completion_bias_inclusion: Optional[Sequence[str]] = None\n    completion_bias_inclusion_first_token_only: bool = False\n    completion_bias_exclusion: Optional[Sequence[str]] = None\n    completion_bias_exclusion_first_token_only: bool = False\n    \"\"\"Only consider the first token for the completion_bias_exclusion.\"\"\"\n    contextual_control_threshold: Optional[float] = None\n    \"\"\"If set to None, attention control parameters only apply to those tokens that have\n    explicitly been set in the request.\n    If set to a non-None value, control parameters are also applied to similar tokens.\n    \"\"\"\n    control_log_additive: Optional[bool] = True\n    \"\"\"True: apply control by adding the log(control_factor) to attention scores.\n    False: (attention_scores - - attention_scores.min(-1)) * control_factor\n    \"\"\"\n    repetition_penalties_include_completion: bool = True\n    \"\"\"Flag deciding whether presence penalty or frequency penalty\n    are updated from the completion.\"\"\"\n    raw_completion: bool = False\n    \"\"\"Force the raw completion of the model to be returned.\"\"\"\n    stop_sequences: Optional[List[str]] = None\n    \"\"\"Stop sequences to use.\"\"\"\n    # Client params\n    aleph_alpha_api_key: Optional[str] = None\n    \"\"\"API key for Aleph Alpha API.\"\"\"\n    host: str = \"https://api.aleph-alpha.com\"\n    \"\"\"The hostname of the API host. \n    The default one is \"https://api.aleph-alpha.com\")\"\"\"\n    hosting: Optional[str] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html"}
{"id": "a9f9581add47-3", "text": "hosting: Optional[str] = None\n    \"\"\"Determines in which datacenters the request may be processed.\n    You can either set the parameter to \"aleph-alpha\" or omit it (defaulting to None).\n    Not setting this value, or setting it to None, gives us maximal \n    flexibility in processing your request in our\n    own datacenters and on servers hosted with other providers. \n    Choose this option for maximal availability.\n    Setting it to \"aleph-alpha\" allows us to only process the \n    request in our own datacenters.\n    Choose this option for maximal data privacy.\"\"\"\n    request_timeout_seconds: int = 305\n    \"\"\"Client timeout that will be set for HTTP requests in the \n    `requests` library's API calls.\n    Server will close all requests after 300 seconds with an internal server error.\"\"\"\n    total_retries: int = 8\n    \"\"\"The number of retries made in case requests fail with certain retryable \n    status codes. If the last\n    retry fails a corresponding exception is raised. Note, that between retries\n    an exponential backoff\n    is applied, starting with 0.5 s after the first retry and doubling for\n    each retry made. So with the\n    default setting of 8 retries a total wait time of 63.5 s is added \n    between the retries.\"\"\"\n    nice: bool = False\n    \"\"\"Setting this to True, will signal to the API that you intend to be \n    nice to other users\n    by de-prioritizing your request below concurrent ones.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html"}
{"id": "a9f9581add47-4", "text": "\"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"aleph_alpha_api_key\"] = convert_to_secret_str(\n            get_from_dict_or_env(values, \"aleph_alpha_api_key\", \"ALEPH_ALPHA_API_KEY\")\n        )\n        try:\n            from aleph_alpha_client import Client\n            values[\"client\"] = Client(\n                token=values[\"aleph_alpha_api_key\"].get_secret_value(),\n                host=values[\"host\"],\n                hosting=values[\"hosting\"],\n                request_timeout_seconds=values[\"request_timeout_seconds\"],\n                total_retries=values[\"total_retries\"],\n                nice=values[\"nice\"],\n            )\n        except ImportError:\n            raise ImportError(\n                \"Could not import aleph_alpha_client python package. \"\n                \"Please install it with `pip install aleph_alpha_client`.\"\n            )\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling the Aleph Alpha API.\"\"\"\n        return {\n            \"maximum_tokens\": self.maximum_tokens,\n            \"temperature\": self.temperature,\n            \"top_k\": self.top_k,\n            \"top_p\": self.top_p,\n            \"presence_penalty\": self.presence_penalty,\n            \"frequency_penalty\": self.frequency_penalty,\n            \"n\": self.n,\n            \"repetition_penalties_include_prompt\": self.repetition_penalties_include_prompt,  # noqa: E501\n            \"use_multiplicative_presence_penalty\": self.use_multiplicative_presence_penalty,  # noqa: E501\n            \"penalty_bias\": self.penalty_bias,\n            \"penalty_exceptions\": self.penalty_exceptions,\n            \"penalty_exceptions_include_stop_sequences\": self.penalty_exceptions_include_stop_sequences,  # noqa: E501", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html"}
{"id": "a9f9581add47-5", "text": "\"best_of\": self.best_of,\n            \"logit_bias\": self.logit_bias,\n            \"log_probs\": self.log_probs,\n            \"tokens\": self.tokens,\n            \"disable_optimizations\": self.disable_optimizations,\n            \"minimum_tokens\": self.minimum_tokens,\n            \"echo\": self.echo,\n            \"use_multiplicative_frequency_penalty\": self.use_multiplicative_frequency_penalty,  # noqa: E501\n            \"sequence_penalty\": self.sequence_penalty,\n            \"sequence_penalty_min_length\": self.sequence_penalty_min_length,\n            \"use_multiplicative_sequence_penalty\": self.use_multiplicative_sequence_penalty,  # noqa: E501\n            \"completion_bias_inclusion\": self.completion_bias_inclusion,\n            \"completion_bias_inclusion_first_token_only\": self.completion_bias_inclusion_first_token_only,  # noqa: E501\n            \"completion_bias_exclusion\": self.completion_bias_exclusion,\n            \"completion_bias_exclusion_first_token_only\": self.completion_bias_exclusion_first_token_only,  # noqa: E501\n            \"contextual_control_threshold\": self.contextual_control_threshold,\n            \"control_log_additive\": self.control_log_additive,\n            \"repetition_penalties_include_completion\": self.repetition_penalties_include_completion,  # noqa: E501\n            \"raw_completion\": self.raw_completion,\n        }\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model\": self.model}, **self._default_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"aleph_alpha\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html"}
{"id": "a9f9581add47-6", "text": "prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Aleph Alpha's completion endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = aleph_alpha(\"Tell me a joke.\")\n        \"\"\"\n        from aleph_alpha_client import CompletionRequest, Prompt\n        params = self._default_params\n        if self.stop_sequences is not None and stop is not None:\n            raise ValueError(\n                \"stop sequences found in both the input and default params.\"\n            )\n        elif self.stop_sequences is not None:\n            params[\"stop_sequences\"] = self.stop_sequences\n        else:\n            params[\"stop_sequences\"] = stop\n        params = {**params, **kwargs}\n        request = CompletionRequest(prompt=Prompt.from_text(prompt), **params)\n        response = self.client.complete(model=self.model, request=request)\n        text = response.completions[0].completion\n        # If stop tokens are provided, Aleph Alpha's endpoint returns them.\n        # In order to make this consistent with other endpoints, we strip them.\n        if stop is not None or self.stop_sequences is not None:\n            text = enforce_stop_tokens(text, params[\"stop_sequences\"])\n        return text\nif __name__ == \"__main__\":\n    aa = AlephAlpha()\n    print(aa(\"How are you?\"))", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html"}
{"id": "01a04567bd2a-0", "text": "Source code for langchain.llms.vllm\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import BaseLLM\nfrom langchain.llms.openai import BaseOpenAI\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema.output import Generation, LLMResult\n[docs]class VLLM(BaseLLM):\n    \"\"\"VLLM language model.\"\"\"\n    model: str = \"\"\n    \"\"\"The name or path of a HuggingFace Transformers model.\"\"\"\n    tensor_parallel_size: Optional[int] = 1\n    \"\"\"The number of GPUs to use for distributed execution with tensor parallelism.\"\"\"\n    trust_remote_code: Optional[bool] = False\n    \"\"\"Trust remote code (e.g., from HuggingFace) when downloading the model \n    and tokenizer.\"\"\"\n    n: int = 1\n    \"\"\"Number of output sequences to return for the given prompt.\"\"\"\n    best_of: Optional[int] = None\n    \"\"\"Number of output sequences that are generated from the prompt.\"\"\"\n    presence_penalty: float = 0.0\n    \"\"\"Float that penalizes new tokens based on whether they appear in the \n    generated text so far\"\"\"\n    frequency_penalty: float = 0.0\n    \"\"\"Float that penalizes new tokens based on their frequency in the \n    generated text so far\"\"\"\n    temperature: float = 1.0\n    \"\"\"Float that controls the randomness of the sampling.\"\"\"\n    top_p: float = 1.0\n    \"\"\"Float that controls the cumulative probability of the top tokens to consider.\"\"\"\n    top_k: int = -1\n    \"\"\"Integer that controls the number of top tokens to consider.\"\"\"\n    use_beam_search: bool = False\n    \"\"\"Whether to use beam search instead of sampling.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vllm.html"}
{"id": "01a04567bd2a-1", "text": "\"\"\"Whether to use beam search instead of sampling.\"\"\"\n    stop: Optional[List[str]] = None\n    \"\"\"List of strings that stop the generation when they are generated.\"\"\"\n    ignore_eos: bool = False\n    \"\"\"Whether to ignore the EOS token and continue generating tokens after \n    the EOS token is generated.\"\"\"\n    max_new_tokens: int = 512\n    \"\"\"Maximum number of tokens to generate per output sequence.\"\"\"\n    logprobs: Optional[int] = None\n    \"\"\"Number of log probabilities to return per output token.\"\"\"\n    dtype: str = \"auto\"\n    \"\"\"The data type for the model weights and activations.\"\"\"\n    download_dir: Optional[str] = None\n    \"\"\"Directory to download and load the weights. (Default to the default \n    cache dir of huggingface)\"\"\"\n    vllm_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `vllm.LLM` call not explicitly specified.\"\"\"\n    client: Any  #: :meta private:\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that python package exists in environment.\"\"\"\n        try:\n            from vllm import LLM as VLLModel\n        except ImportError:\n            raise ImportError(\n                \"Could not import vllm python package. \"\n                \"Please install it with `pip install vllm`.\"\n            )\n        values[\"client\"] = VLLModel(\n            model=values[\"model\"],\n            tensor_parallel_size=values[\"tensor_parallel_size\"],\n            trust_remote_code=values[\"trust_remote_code\"],\n            dtype=values[\"dtype\"],\n            download_dir=values[\"download_dir\"],\n            **values[\"vllm_kwargs\"],\n        )\n        return values\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vllm.html"}
{"id": "01a04567bd2a-2", "text": ")\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling vllm.\"\"\"\n        return {\n            \"n\": self.n,\n            \"best_of\": self.best_of,\n            \"max_tokens\": self.max_new_tokens,\n            \"top_k\": self.top_k,\n            \"top_p\": self.top_p,\n            \"temperature\": self.temperature,\n            \"presence_penalty\": self.presence_penalty,\n            \"frequency_penalty\": self.frequency_penalty,\n            \"stop\": self.stop,\n            \"ignore_eos\": self.ignore_eos,\n            \"use_beam_search\": self.use_beam_search,\n            \"logprobs\": self.logprobs,\n        }\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Run the LLM on the given prompt and input.\"\"\"\n        from vllm import SamplingParams\n        # build sampling parameters\n        params = {**self._default_params, **kwargs, \"stop\": stop}\n        sampling_params = SamplingParams(**params)\n        # call the model\n        outputs = self.client.generate(prompts, sampling_params)\n        generations = []\n        for output in outputs:\n            text = output.outputs[0].text\n            generations.append([Generation(text=text)])\n        return LLMResult(generations=generations)\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"vllm\"\n[docs]class VLLMOpenAI(BaseOpenAI):", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vllm.html"}
{"id": "01a04567bd2a-3", "text": "[docs]class VLLMOpenAI(BaseOpenAI):\n    \"\"\"vLLM OpenAI-compatible API client\"\"\"\n    @property\n    def _invocation_params(self) -> Dict[str, Any]:\n        \"\"\"Get the parameters used to invoke the model.\"\"\"\n        openai_creds: Dict[str, Any] = {\n            \"api_key\": self.openai_api_key,\n            \"api_base\": self.openai_api_base,\n        }\n        return {\n            \"model\": self.model_name,\n            **openai_creds,\n            **self._default_params,\n            \"logit_bias\": None,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"vllm-openai\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vllm.html"}
{"id": "efc815370e4b-0", "text": "Source code for langchain.llms.gooseai\nimport logging\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Extra, Field, SecretStr, root_validator\nfrom langchain.utils import convert_to_secret_str, get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class GooseAI(LLM):\n    \"\"\"GooseAI large language models.\n    To use, you should have the ``openai`` python package installed, and the\n    environment variable ``GOOSEAI_API_KEY`` set with your API key.\n    Any parameters that are valid to be passed to the openai.create call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.llms import GooseAI\n            gooseai = GooseAI(model_name=\"gpt-neo-20b\")\n    \"\"\"\n    client: Any\n    model_name: str = \"gpt-neo-20b\"\n    \"\"\"Model name to use\"\"\"\n    temperature: float = 0.7\n    \"\"\"What sampling temperature to use\"\"\"\n    max_tokens: int = 256\n    \"\"\"The maximum number of tokens to generate in the completion.\n    -1 returns as many tokens as possible given the prompt and\n    the models maximal context size.\"\"\"\n    top_p: float = 1\n    \"\"\"Total probability mass of tokens to consider at each step.\"\"\"\n    min_tokens: int = 1\n    \"\"\"The minimum number of tokens to generate in the completion.\"\"\"\n    frequency_penalty: float = 0\n    \"\"\"Penalizes repeated tokens according to frequency.\"\"\"\n    presence_penalty: float = 0\n    \"\"\"Penalizes repeated tokens.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html"}
{"id": "efc815370e4b-1", "text": "presence_penalty: float = 0\n    \"\"\"Penalizes repeated tokens.\"\"\"\n    n: int = 1\n    \"\"\"How many completions to generate for each prompt.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not explicitly specified.\"\"\"\n    logit_bias: Optional[Dict[str, float]] = Field(default_factory=dict)\n    \"\"\"Adjust the probability of specific tokens being generated.\"\"\"\n    gooseai_api_key: Optional[SecretStr] = None\n    class Config:\n        \"\"\"Configuration for this pydantic config.\"\"\"\n        extra = Extra.ignore\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = {field.alias for field in cls.__fields__.values()}\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name not in all_required_field_names:\n                if field_name in extra:\n                    raise ValueError(f\"Found {field_name} supplied twice.\")\n                logger.warning(\n                    f\"\"\"WARNING! {field_name} is not default parameter.\n                    {field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        gooseai_api_key = convert_to_secret_str(\n            get_from_dict_or_env(values, \"gooseai_api_key\", \"GOOSEAI_API_KEY\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html"}
{"id": "efc815370e4b-2", "text": ")\n        values[\"gooseai_api_key\"] = gooseai_api_key\n        try:\n            import openai\n            openai.api_key = gooseai_api_key.get_secret_value()\n            openai.api_base = \"https://api.goose.ai/v1\"\n            values[\"client\"] = openai.Completion\n        except ImportError:\n            raise ImportError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\"\n            )\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling GooseAI API.\"\"\"\n        normal_params = {\n            \"temperature\": self.temperature,\n            \"max_tokens\": self.max_tokens,\n            \"top_p\": self.top_p,\n            \"min_tokens\": self.min_tokens,\n            \"frequency_penalty\": self.frequency_penalty,\n            \"presence_penalty\": self.presence_penalty,\n            \"n\": self.n,\n            \"logit_bias\": self.logit_bias,\n        }\n        return {**normal_params, **self.model_kwargs}\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model_name\": self.model_name}, **self._default_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"gooseai\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call the GooseAI API.\"\"\"\n        params = self._default_params", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html"}
{"id": "efc815370e4b-3", "text": "\"\"\"Call the GooseAI API.\"\"\"\n        params = self._default_params\n        if stop is not None:\n            if \"stop\" in params:\n                raise ValueError(\"`stop` found in both the input and default params.\")\n            params[\"stop\"] = stop\n        params = {**params, **kwargs}\n        response = self.client.create(engine=self.model_name, prompt=prompt, **params)\n        text = response.choices[0].text\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html"}
{"id": "3bad0e72466d-0", "text": "Source code for langchain.llms.koboldai\nimport logging\nfrom typing import Any, Dict, List, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nlogger = logging.getLogger(__name__)\n[docs]def clean_url(url: str) -> str:\n    \"\"\"Remove trailing slash and /api from url if present.\"\"\"\n    if url.endswith(\"/api\"):\n        return url[:-4]\n    elif url.endswith(\"/\"):\n        return url[:-1]\n    else:\n        return url\n[docs]class KoboldApiLLM(LLM):\n    \"\"\"Kobold API language model.\n    It includes several fields that can be used to control the text generation process.\n    To use this class, instantiate it with the required parameters and call it with a\n    prompt to generate text. For example:\n        kobold = KoboldApiLLM(endpoint=\"http://localhost:5000\")\n        result = kobold(\"Write a story about a dragon.\")\n    This will send a POST request to the Kobold API with the provided prompt and\n    generate text.\n    \"\"\"\n    endpoint: str\n    \"\"\"The API endpoint to use for generating text.\"\"\"\n    use_story: Optional[bool] = False\n    \"\"\" Whether or not to use the story from the KoboldAI GUI when generating text. \"\"\"\n    use_authors_note: Optional[bool] = False\n    \"\"\"Whether to use the author's note from the KoboldAI GUI when generating text.\n    \n    This has no effect unless use_story is also enabled.\n    \"\"\"\n    use_world_info: Optional[bool] = False\n    \"\"\"Whether to use the world info from the KoboldAI GUI when generating text.\"\"\"\n    use_memory: Optional[bool] = False", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html"}
{"id": "3bad0e72466d-1", "text": "use_memory: Optional[bool] = False\n    \"\"\"Whether to use the memory from the KoboldAI GUI when generating text.\"\"\"\n    max_context_length: Optional[int] = 1600\n    \"\"\"Maximum number of tokens to send to the model.\n    \n    minimum: 1\n    \"\"\"\n    max_length: Optional[int] = 80\n    \"\"\"Number of tokens to generate.\n    \n    maximum: 512\n    minimum: 1\n    \"\"\"\n    rep_pen: Optional[float] = 1.12\n    \"\"\"Base repetition penalty value.\n    \n    minimum: 1\n    \"\"\"\n    rep_pen_range: Optional[int] = 1024\n    \"\"\"Repetition penalty range.\n    \n    minimum: 0\n    \"\"\"\n    rep_pen_slope: Optional[float] = 0.9\n    \"\"\"Repetition penalty slope.\n    \n    minimum: 0\n    \"\"\"\n    temperature: Optional[float] = 0.6\n    \"\"\"Temperature value.\n    \n    exclusiveMinimum: 0\n    \"\"\"\n    tfs: Optional[float] = 0.9\n    \"\"\"Tail free sampling value.\n    \n    maximum: 1\n    minimum: 0\n    \"\"\"\n    top_a: Optional[float] = 0.9\n    \"\"\"Top-a sampling value.\n    \n    minimum: 0\n    \"\"\"\n    top_p: Optional[float] = 0.95\n    \"\"\"Top-p sampling value.\n    \n    maximum: 1\n    minimum: 0\n    \"\"\"\n    top_k: Optional[int] = 0\n    \"\"\"Top-k sampling value.\n    \n    minimum: 0\n    \"\"\"\n    typical: Optional[float] = 0.5\n    \"\"\"Typical sampling value.\n    \n    maximum: 1", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html"}
{"id": "3bad0e72466d-2", "text": "\"\"\"Typical sampling value.\n    \n    maximum: 1\n    minimum: 0\n    \"\"\"\n    @property\n    def _llm_type(self) -> str:\n        return \"koboldai\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call the API and return the output.\n        Args:\n            prompt: The prompt to use for generation.\n            stop: A list of strings to stop generation when encountered.\n        Returns:\n            The generated text.\n        Example:\n            .. code-block:: python\n                from langchain.llms import KoboldApiLLM\n                llm = KoboldApiLLM(endpoint=\"http://localhost:5000\")\n                llm(\"Write a story about dragons.\")\n        \"\"\"\n        data: Dict[str, Any] = {\n            \"prompt\": prompt,\n            \"use_story\": self.use_story,\n            \"use_authors_note\": self.use_authors_note,\n            \"use_world_info\": self.use_world_info,\n            \"use_memory\": self.use_memory,\n            \"max_context_length\": self.max_context_length,\n            \"max_length\": self.max_length,\n            \"rep_pen\": self.rep_pen,\n            \"rep_pen_range\": self.rep_pen_range,\n            \"rep_pen_slope\": self.rep_pen_slope,\n            \"temperature\": self.temperature,\n            \"tfs\": self.tfs,\n            \"top_a\": self.top_a,\n            \"top_p\": self.top_p,\n            \"top_k\": self.top_k,\n            \"typical\": self.typical,\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html"}
{"id": "3bad0e72466d-3", "text": "\"typical\": self.typical,\n        }\n        if stop is not None:\n            data[\"stop_sequence\"] = stop\n        response = requests.post(\n            f\"{clean_url(self.endpoint)}/api/v1/generate\", json=data\n        )\n        response.raise_for_status()\n        json_response = response.json()\n        if (\n            \"results\" in json_response\n            and len(json_response[\"results\"]) > 0\n            and \"text\" in json_response[\"results\"][0]\n        ):\n            text = json_response[\"results\"][0][\"text\"].strip()\n            if stop is not None:\n                for sequence in stop:\n                    if text.endswith(sequence):\n                        text = text[: -len(sequence)].rstrip()\n            return text\n        else:\n            raise ValueError(\n                f\"Unexpected response format from Kobold API:  {json_response}\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html"}
{"id": "3d7109fddf31-0", "text": "Source code for langchain.llms.predictionguard\nimport logging\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class PredictionGuard(LLM):\n    \"\"\"Prediction Guard large language models.\n    To use, you should have the ``predictionguard`` python package installed, and the\n    environment variable ``PREDICTIONGUARD_TOKEN`` set with your access token, or pass\n    it as a named parameter to the constructor. To use Prediction Guard's API along\n    with OpenAI models, set the environment variable ``OPENAI_API_KEY`` with your\n    OpenAI API key as well.\n    Example:\n        .. code-block:: python\n            pgllm = PredictionGuard(model=\"MPT-7B-Instruct\",\n                                    token=\"my-access-token\",\n                                    output={\n                                        \"type\": \"boolean\"\n                                    })\n    \"\"\"\n    client: Any  #: :meta private:\n    model: Optional[str] = \"MPT-7B-Instruct\"\n    \"\"\"Model name to use.\"\"\"\n    output: Optional[Dict[str, Any]] = None\n    \"\"\"The output type or structure for controlling the LLM output.\"\"\"\n    max_tokens: int = 256\n    \"\"\"Denotes the number of tokens to predict per generation.\"\"\"\n    temperature: float = 0.75\n    \"\"\"A non-negative float that tunes the degree of randomness in generation.\"\"\"\n    token: Optional[str] = None\n    \"\"\"Your Prediction Guard access token.\"\"\"\n    stop: Optional[List[str]] = None\n    class Config:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html"}
{"id": "3d7109fddf31-1", "text": "stop: Optional[List[str]] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the access token and python package exists in environment.\"\"\"\n        token = get_from_dict_or_env(values, \"token\", \"PREDICTIONGUARD_TOKEN\")\n        try:\n            import predictionguard as pg\n            values[\"client\"] = pg.Client(token=token)\n        except ImportError:\n            raise ImportError(\n                \"Could not import predictionguard python package. \"\n                \"Please install it with `pip install predictionguard`.\"\n            )\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling the Prediction Guard API.\"\"\"\n        return {\n            \"max_tokens\": self.max_tokens,\n            \"temperature\": self.temperature,\n        }\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model\": self.model}, **self._default_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"predictionguard\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Prediction Guard's model API.\n        Args:\n            prompt: The prompt to pass into the model.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html"}
{"id": "3d7109fddf31-2", "text": "The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = pgllm(\"Tell me a joke.\")\n        \"\"\"\n        import predictionguard as pg\n        params = self._default_params\n        if self.stop is not None and stop is not None:\n            raise ValueError(\"`stop` found in both the input and default params.\")\n        elif self.stop is not None:\n            params[\"stop_sequences\"] = self.stop\n        else:\n            params[\"stop_sequences\"] = stop\n        response = pg.Completion.create(\n            model=self.model,\n            prompt=prompt,\n            output=self.output,\n            temperature=params[\"temperature\"],\n            max_tokens=params[\"max_tokens\"],\n            **kwargs,\n        )\n        text = response[\"choices\"][0][\"text\"]\n        # If stop tokens are provided, Prediction Guard's endpoint returns them.\n        # In order to make this consistent with other endpoints, we strip them.\n        if stop is not None or self.stop is not None:\n            text = enforce_stop_tokens(text, params[\"stop_sequences\"])\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html"}
{"id": "ac751badc772-0", "text": "Source code for langchain.llms.ctranslate2\nfrom typing import Any, Dict, List, Optional, Union\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import BaseLLM\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema.output import Generation, LLMResult\n[docs]class CTranslate2(BaseLLM):\n    \"\"\"CTranslate2 language model.\"\"\"\n    model_path: str = \"\"\n    \"\"\"Path to the CTranslate2 model directory.\"\"\"\n    tokenizer_name: str = \"\"\n    \"\"\"Name of the original Hugging Face model needed to load the proper tokenizer.\"\"\"\n    device: str = \"cpu\"\n    \"\"\"Device to use (possible values are: cpu, cuda, auto).\"\"\"\n    device_index: Union[int, List[int]] = 0\n    \"\"\"Device IDs where to place this generator on.\"\"\"\n    compute_type: Union[str, Dict[str, str]] = \"default\"\n    \"\"\"\n    Model computation type or a dictionary mapping a device name to the computation type\n    (possible values are: default, auto, int8, int8_float32, int8_float16,\n    int8_bfloat16, int16, float16, bfloat16, float32).\n    \"\"\"\n    max_length: int = 512\n    \"\"\"Maximum generation length.\"\"\"\n    sampling_topk: int = 1\n    \"\"\"Randomly sample predictions from the top K candidates.\"\"\"\n    sampling_topp: float = 1\n    \"\"\"Keep the most probable tokens whose cumulative probability exceeds this value.\"\"\"\n    sampling_temperature: float = 1\n    \"\"\"Sampling temperature to generate more random samples.\"\"\"\n    client: Any  #: :meta private:\n    tokenizer: Any  #: :meta private:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ctranslate2.html"}
{"id": "ac751badc772-1", "text": "tokenizer: Any  #: :meta private:\n    ctranslate2_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"\n    Holds any model parameters valid for `ctranslate2.Generator` call not \n    explicitly specified.\n    \"\"\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that python package exists in environment.\"\"\"\n        try:\n            import ctranslate2\n        except ImportError:\n            raise ImportError(\n                \"Could not import ctranslate2 python package. \"\n                \"Please install it with `pip install ctranslate2`.\"\n            )\n        try:\n            import transformers\n        except ImportError:\n            raise ImportError(\n                \"Could not import transformers python package. \"\n                \"Please install it with `pip install transformers`.\"\n            )\n        values[\"client\"] = ctranslate2.Generator(\n            model_path=values[\"model_path\"],\n            device=values[\"device\"],\n            device_index=values[\"device_index\"],\n            compute_type=values[\"compute_type\"],\n            **values[\"ctranslate2_kwargs\"],\n        )\n        values[\"tokenizer\"] = transformers.AutoTokenizer.from_pretrained(\n            values[\"tokenizer_name\"]\n        )\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters.\"\"\"\n        return {\n            \"max_length\": self.max_length,\n            \"sampling_topk\": self.sampling_topk,\n            \"sampling_topp\": self.sampling_topp,\n            \"sampling_temperature\": self.sampling_temperature,\n        }\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ctranslate2.html"}
{"id": "ac751badc772-2", "text": "prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        # build sampling parameters\n        params = {**self._default_params, **kwargs}\n        # call the model\n        encoded_prompts = self.tokenizer(prompts)[\"input_ids\"]\n        tokenized_prompts = [\n            self.tokenizer.convert_ids_to_tokens(encoded_prompt)\n            for encoded_prompt in encoded_prompts\n        ]\n        results = self.client.generate_batch(tokenized_prompts, **params)\n        sequences = [result.sequences_ids[0] for result in results]\n        decoded_sequences = [self.tokenizer.decode(seq) for seq in sequences]\n        generations = []\n        for text in decoded_sequences:\n            generations.append([Generation(text=text)])\n        return LLMResult(generations=generations)\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"ctranslate2\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ctranslate2.html"}
{"id": "e798e15a2de7-0", "text": "Source code for langchain.llms.self_hosted_hugging_face\nimport importlib.util\nimport logging\nfrom typing import Any, Callable, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.self_hosted import SelfHostedPipeline\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra\nDEFAULT_MODEL_ID = \"gpt2\"\nDEFAULT_TASK = \"text-generation\"\nVALID_TASKS = (\"text2text-generation\", \"text-generation\", \"summarization\")\nlogger = logging.getLogger(__name__)\ndef _generate_text(\n    pipeline: Any,\n    prompt: str,\n    *args: Any,\n    stop: Optional[List[str]] = None,\n    **kwargs: Any,\n) -> str:\n    \"\"\"Inference function to send to the remote hardware.\n    Accepts a Hugging Face pipeline (or more likely,\n    a key pointing to such a pipeline on the cluster's object store)\n    and returns generated text.\n    \"\"\"\n    response = pipeline(prompt, *args, **kwargs)\n    if pipeline.task == \"text-generation\":\n        # Text generation return includes the starter text.\n        text = response[0][\"generated_text\"][len(prompt) :]\n    elif pipeline.task == \"text2text-generation\":\n        text = response[0][\"generated_text\"]\n    elif pipeline.task == \"summarization\":\n        text = response[0][\"summary_text\"]\n    else:\n        raise ValueError(\n            f\"Got invalid task {pipeline.task}, \"\n            f\"currently only {VALID_TASKS} are supported\"\n        )\n    if stop is not None:\n        text = enforce_stop_tokens(text, stop)\n    return text\ndef _load_transformer(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html"}
{"id": "e798e15a2de7-1", "text": "return text\ndef _load_transformer(\n    model_id: str = DEFAULT_MODEL_ID,\n    task: str = DEFAULT_TASK,\n    device: int = 0,\n    model_kwargs: Optional[dict] = None,\n) -> Any:\n    \"\"\"Inference function to send to the remote hardware.\n    Accepts a huggingface model_id and returns a pipeline for the task.\n    \"\"\"\n    from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer\n    from transformers import pipeline as hf_pipeline\n    _model_kwargs = model_kwargs or {}\n    tokenizer = AutoTokenizer.from_pretrained(model_id, **_model_kwargs)\n    try:\n        if task == \"text-generation\":\n            model = AutoModelForCausalLM.from_pretrained(model_id, **_model_kwargs)\n        elif task in (\"text2text-generation\", \"summarization\"):\n            model = AutoModelForSeq2SeqLM.from_pretrained(model_id, **_model_kwargs)\n        else:\n            raise ValueError(\n                f\"Got invalid task {task}, \"\n                f\"currently only {VALID_TASKS} are supported\"\n            )\n    except ImportError as e:\n        raise ValueError(\n            f\"Could not load the {task} model due to missing dependencies.\"\n        ) from e\n    if importlib.util.find_spec(\"torch\") is not None:\n        import torch\n        cuda_device_count = torch.cuda.device_count()\n        if device < -1 or (device >= cuda_device_count):\n            raise ValueError(\n                f\"Got device=={device}, \"\n                f\"device is required to be within [-1, {cuda_device_count})\"\n            )\n        if device < 0 and cuda_device_count > 0:\n            logger.warning(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html"}
{"id": "e798e15a2de7-2", "text": "if device < 0 and cuda_device_count > 0:\n            logger.warning(\n                \"Device has %d GPUs available. \"\n                \"Provide device={deviceId} to `from_model_id` to use available\"\n                \"GPUs for execution. deviceId is -1 for CPU and \"\n                \"can be a positive integer associated with CUDA device id.\",\n                cuda_device_count,\n            )\n    pipeline = hf_pipeline(\n        task=task,\n        model=model,\n        tokenizer=tokenizer,\n        device=device,\n        model_kwargs=_model_kwargs,\n    )\n    if pipeline.task not in VALID_TASKS:\n        raise ValueError(\n            f\"Got invalid task {pipeline.task}, \"\n            f\"currently only {VALID_TASKS} are supported\"\n        )\n    return pipeline\n[docs]class SelfHostedHuggingFaceLLM(SelfHostedPipeline):\n    \"\"\"HuggingFace Pipeline API to run on self-hosted remote hardware.\n    Supported hardware includes auto-launched instances on AWS, GCP, Azure,\n    and Lambda, as well as servers specified\n    by IP address and SSH credentials (such as on-prem, or another cloud\n    like Paperspace, Coreweave, etc.).\n    To use, you should have the ``runhouse`` python package installed.\n    Only supports `text-generation`, `text2text-generation` and `summarization` for now.\n    Example using from_model_id:\n        .. code-block:: python\n            from langchain.llms import SelfHostedHuggingFaceLLM\n            import runhouse as rh\n            gpu = rh.cluster(name=\"rh-a10x\", instance_type=\"A100:1\")\n            hf = SelfHostedHuggingFaceLLM(\n                model_id=\"google/flan-t5-large\", task=\"text2text-generation\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html"}
{"id": "e798e15a2de7-3", "text": "model_id=\"google/flan-t5-large\", task=\"text2text-generation\",\n                hardware=gpu\n            )\n    Example passing fn that generates a pipeline (bc the pipeline is not serializable):\n        .. code-block:: python\n            from langchain.llms import SelfHostedHuggingFaceLLM\n            from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline\n            import runhouse as rh\n            def get_pipeline():\n                model_id = \"gpt2\"\n                tokenizer = AutoTokenizer.from_pretrained(model_id)\n                model = AutoModelForCausalLM.from_pretrained(model_id)\n                pipe = pipeline(\n                    \"text-generation\", model=model, tokenizer=tokenizer\n                )\n                return pipe\n            hf = SelfHostedHuggingFaceLLM(\n                model_load_fn=get_pipeline, model_id=\"gpt2\", hardware=gpu)\n    \"\"\"\n    model_id: str = DEFAULT_MODEL_ID\n    \"\"\"Hugging Face model_id to load the model.\"\"\"\n    task: str = DEFAULT_TASK\n    \"\"\"Hugging Face task (\"text-generation\", \"text2text-generation\" or\n    \"summarization\").\"\"\"\n    device: int = 0\n    \"\"\"Device to use for inference. -1 for CPU, 0 for GPU, 1 for second GPU, etc.\"\"\"\n    model_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    hardware: Any\n    \"\"\"Remote hardware to send the inference function to.\"\"\"\n    model_reqs: List[str] = [\"./\", \"transformers\", \"torch\"]\n    \"\"\"Requirements to install on hardware to inference the model.\"\"\"\n    model_load_fn: Callable = _load_transformer\n    \"\"\"Function to load the model remotely on the server.\"\"\"\n    inference_fn: Callable = _generate_text  #: :meta private:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html"}
{"id": "e798e15a2de7-4", "text": "inference_fn: Callable = _generate_text  #: :meta private:\n    \"\"\"Inference function to send to the remote hardware.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    def __init__(self, **kwargs: Any):\n        \"\"\"Construct the pipeline remotely using an auxiliary function.\n        The load function needs to be importable to be imported\n        and run on the server, i.e. in a module and not a REPL or closure.\n        Then, initialize the remote inference function.\n        \"\"\"\n        load_fn_kwargs = {\n            \"model_id\": kwargs.get(\"model_id\", DEFAULT_MODEL_ID),\n            \"task\": kwargs.get(\"task\", DEFAULT_TASK),\n            \"device\": kwargs.get(\"device\", 0),\n            \"model_kwargs\": kwargs.get(\"model_kwargs\", None),\n        }\n        super().__init__(load_fn_kwargs=load_fn_kwargs, **kwargs)\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"model_id\": self.model_id},\n            **{\"model_kwargs\": self.model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        return \"selfhosted_huggingface_pipeline\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        return self.client(\n            pipeline=self.pipeline_ref, prompt=prompt, stop=stop, **kwargs\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html"}
{"id": "e9f100163e72-0", "text": "Source code for langchain.llms.replicate\nfrom __future__ import annotations\nimport logging\nfrom typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.schema.output import GenerationChunk\nfrom langchain.utils import get_from_dict_or_env\nif TYPE_CHECKING:\n    from replicate.prediction import Prediction\nlogger = logging.getLogger(__name__)\n[docs]class Replicate(LLM):\n    \"\"\"Replicate models.\n    To use, you should have the ``replicate`` python package installed,\n    and the environment variable ``REPLICATE_API_TOKEN`` set with your API token.\n    You can find your token here: https://replicate.com/account\n    The model param is required, but any other model parameters can also\n    be passed in with the format model_kwargs={model_param: value, ...}\n    Example:\n        .. code-block:: python\n            from langchain.llms import Replicate\n            replicate = Replicate(\n                model=(\n                    \"stability-ai/stable-diffusion: \"\n                    \"27b93a2413e7f36cd83da926f3656280b2931564ff050bf9575f1fdf9bcd7478\",\n                ),\n                model_kwargs={\"image_dimensions\": \"512x512\"}\n            )\n    \"\"\"\n    model: str\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict, alias=\"input\")\n    replicate_api_token: Optional[str] = None\n    prompt_key: Optional[str] = None\n    version_obj: Any = Field(default=None, exclude=True)\n    \"\"\"Optionally pass in the model version object during initialization to avoid", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html"}
{"id": "e9f100163e72-1", "text": "\"\"\"Optionally pass in the model version object during initialization to avoid \n        having to make an extra API call to retrieve it during streaming. NOTE: not\n        serializable, is excluded from serialization.\n    \"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results.\"\"\"\n    stop: List[str] = Field(default_factory=list)\n    \"\"\"Stop sequences to early-terminate generation.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic config.\"\"\"\n        allow_population_by_field_name = True\n        extra = Extra.forbid\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"replicate_api_token\": \"REPLICATE_API_TOKEN\"}\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = {field.alias for field in cls.__fields__.values()}\n        input = values.pop(\"input\", {})\n        if input:\n            logger.warning(\n                \"Init param `input` is deprecated, please use `model_kwargs` instead.\"\n            )\n        extra = {**values.pop(\"model_kwargs\", {}), **input}\n        for field_name in list(values):\n            if field_name not in all_required_field_names:\n                if field_name in extra:\n                    raise ValueError(f\"Found {field_name} supplied twice.\")\n                logger.warning(\n                    f\"\"\"{field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        values[\"model_kwargs\"] = extra\n        return values", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html"}
{"id": "e9f100163e72-2", "text": "values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        replicate_api_token = get_from_dict_or_env(\n            values, \"replicate_api_token\", \"REPLICATE_API_TOKEN\"\n        )\n        values[\"replicate_api_token\"] = replicate_api_token\n        return values\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"model\": self.model,\n            \"model_kwargs\": self.model_kwargs,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of model.\"\"\"\n        return \"replicate\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call to replicate endpoint.\"\"\"\n        if self.streaming:\n            completion: Optional[str] = None\n            for chunk in self._stream(\n                prompt, stop=stop, run_manager=run_manager, **kwargs\n            ):\n                if completion is None:\n                    completion = chunk.text\n                else:\n                    completion += chunk.text\n        else:\n            prediction = self._create_prediction(prompt, **kwargs)\n            prediction.wait()\n            if prediction.status == \"failed\":\n                raise RuntimeError(prediction.error)\n            if isinstance(prediction.output, str):\n                completion = prediction.output\n            else:\n                completion = \"\".join(prediction.output)\n        assert completion is not None\n        stop_conditions = stop or self.stop\n        for s in stop_conditions:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html"}
{"id": "e9f100163e72-3", "text": "stop_conditions = stop or self.stop\n        for s in stop_conditions:\n            if s in completion:\n                completion = completion[: completion.find(s)]\n        return completion\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        prediction = self._create_prediction(prompt, **kwargs)\n        stop_conditions = stop or self.stop\n        stop_condition_reached = False\n        current_completion: str = \"\"\n        for output in prediction.output_iterator():\n            current_completion += output\n            # test for stop conditions, if specified\n            for s in stop_conditions:\n                if s in current_completion:\n                    prediction.cancel()\n                    stop_condition_reached = True\n                    # Potentially some tokens that should still be yielded before ending\n                    # stream.\n                    stop_index = max(output.find(s), 0)\n                    output = output[:stop_index]\n                    if not output:\n                        break\n            if output:\n                yield GenerationChunk(text=output)\n                if run_manager:\n                    run_manager.on_llm_new_token(\n                        output,\n                        verbose=self.verbose,\n                    )\n            if stop_condition_reached:\n                break\n    def _create_prediction(self, prompt: str, **kwargs: Any) -> Prediction:\n        try:\n            import replicate as replicate_python\n        except ImportError:\n            raise ImportError(\n                \"Could not import replicate python package. \"\n                \"Please install it with `pip install replicate`.\"\n            )\n        # get the model and version\n        if self.version_obj is None:\n            model_str, version_str = self.model.split(\":\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html"}
{"id": "e9f100163e72-4", "text": "model_str, version_str = self.model.split(\":\")\n            model = replicate_python.models.get(model_str)\n            self.version_obj = model.versions.get(version_str)\n        if self.prompt_key is None:\n            # sort through the openapi schema to get the name of the first input\n            input_properties = sorted(\n                self.version_obj.openapi_schema[\"components\"][\"schemas\"][\"Input\"][\n                    \"properties\"\n                ].items(),\n                key=lambda item: item[1].get(\"x-order\", 0),\n            )\n            self.prompt_key = input_properties[0][0]\n        input_: Dict = {\n            self.prompt_key: prompt,\n            **self.model_kwargs,\n            **kwargs,\n        }\n        return replicate_python.predictions.create(\n            version=self.version_obj, input=input_\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html"}
{"id": "0b46a35545aa-0", "text": "Source code for langchain.llms.octoai_endpoint\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class OctoAIEndpoint(LLM):\n    \"\"\"OctoAI LLM Endpoints.\n    OctoAIEndpoint is a class to interact with OctoAI\n     Compute Service large language model endpoints.\n    To use, you should have the ``octoai`` python package installed, and the\n    environment variable ``OCTOAI_API_TOKEN`` set with your API token, or pass\n    it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.llms.octoai_endpoint  import OctoAIEndpoint\n            OctoAIEndpoint(\n                octoai_api_token=\"octoai-api-key\",\n                endpoint_url=\"https://mpt-7b-demo-f1kzsig6xes9.octoai.run/generate\",\n                model_kwargs={\n                    \"max_new_tokens\": 200,\n                    \"temperature\": 0.75,\n                    \"top_p\": 0.95,\n                    \"repetition_penalty\": 1,\n                    \"seed\": None,\n                    \"stop\": [],\n                },\n            )\n            from langchain.llms.octoai_endpoint  import OctoAIEndpoint\n            OctoAIEndpoint(\n                octoai_api_token=\"octoai-api-key\",", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html"}
{"id": "0b46a35545aa-1", "text": "octoai_api_token=\"octoai-api-key\",\n                endpoint_url=\"https://llama-2-7b-chat-demo-kk0powt97tmb.octoai.run/v1/chat/completions\",\n                model_kwargs={\n                    \"model\": \"llama-2-7b-chat\",\n                    \"messages\": [\n                        {\n                            \"role\": \"system\",\n                            \"content\": \"Below is an instruction that describes a task.\n                                Write a response that completes the request.\"\n                        }\n                    ],\n                    \"stream\": False,\n                    \"max_tokens\": 256\n                }\n            )\n    \"\"\"\n    endpoint_url: Optional[str] = None\n    \"\"\"Endpoint URL to use.\"\"\"\n    model_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    octoai_api_token: Optional[str] = None\n    \"\"\"OCTOAI API Token\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to generate a stream of tokens asynchronously\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator(allow_reuse=True)\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        octoai_api_token = get_from_dict_or_env(\n            values, \"octoai_api_token\", \"OCTOAI_API_TOKEN\"\n        )\n        values[\"endpoint_url\"] = get_from_dict_or_env(\n            values, \"endpoint_url\", \"ENDPOINT_URL\"\n        )\n        values[\"octoai_api_token\"] = octoai_api_token\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html"}
{"id": "0b46a35545aa-2", "text": "\"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {\n            **{\"endpoint_url\": self.endpoint_url},\n            **{\"model_kwargs\": _model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"octoai_endpoint\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to OctoAI's inference endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        \"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        try:\n            # Initialize the OctoAI client\n            from octoai import client\n            octoai_client = client.Client(token=self.octoai_api_token)\n            if \"model\" in _model_kwargs:\n                parameter_payload = _model_kwargs\n                parameter_payload[\"messages\"].append(\n                    {\"role\": \"user\", \"content\": prompt}\n                )\n                # Send the request using the OctoAI client\n                output = octoai_client.infer(self.endpoint_url, parameter_payload)\n                text = output.get(\"choices\")[0].get(\"message\").get(\"content\")\n            else:\n                # Prepare the payload JSON\n                parameter_payload = {\"inputs\": prompt, \"parameters\": _model_kwargs}\n                # Send the request using the OctoAI client\n                resp_json = octoai_client.infer(self.endpoint_url, parameter_payload)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html"}
{"id": "0b46a35545aa-3", "text": "resp_json = octoai_client.infer(self.endpoint_url, parameter_payload)\n                text = resp_json[\"generated_text\"]\n        except Exception as e:\n            # Handle any errors raised by the inference endpoint\n            raise ValueError(f\"Error raised by the inference endpoint: {e}\") from e\n        if stop is not None:\n            # Apply stop tokens when making calls to OctoAI\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html"}
{"id": "b4044a8354f7-0", "text": "Source code for langchain.llms.baidu_qianfan_endpoint\nfrom __future__ import annotations\nimport logging\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Dict,\n    Iterator,\n    List,\n    Optional,\n)\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema.output import GenerationChunk\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class QianfanLLMEndpoint(LLM):\n    \"\"\"Baidu Qianfan hosted open source or customized models.\n    To use, you should have the ``qianfan`` python package installed, and\n    the environment variable ``qianfan_ak`` and ``qianfan_sk`` set with\n    your API key and Secret Key.\n    ak, sk are required parameters which you could get from\n    https://cloud.baidu.com/product/wenxinworkshop\n    Example:\n        .. code-block:: python\n            from langchain.llms import QianfanLLMEndpoint\n            qianfan_model = QianfanLLMEndpoint(model=\"ERNIE-Bot\",\n                endpoint=\"your_endpoint\", qianfan_ak=\"your_ak\", qianfan_sk=\"your_sk\")\n    \"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    client: Any\n    qianfan_ak: Optional[str] = None\n    qianfan_sk: Optional[str] = None\n    streaming: Optional[bool] = False\n    \"\"\"Whether to stream the results or not.\"\"\"\n    model: str = \"ERNIE-Bot-turbo\"\n    \"\"\"Model name.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baidu_qianfan_endpoint.html"}
{"id": "b4044a8354f7-1", "text": "\"\"\"Model name. \n    you could get from https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu\n    \n    preset models are mapping to an endpoint.\n    `model` will be ignored if `endpoint` is set\n    \"\"\"\n    endpoint: Optional[str] = None\n    \"\"\"Endpoint of the Qianfan LLM, required if custom model used.\"\"\"\n    request_timeout: Optional[int] = 60\n    \"\"\"request timeout for chat http requests\"\"\"\n    top_p: Optional[float] = 0.8\n    temperature: Optional[float] = 0.95\n    penalty_score: Optional[float] = 1\n    \"\"\"Model params, only supported in ERNIE-Bot and ERNIE-Bot-turbo.\n    In the case of other model, passing these params will not affect the result.\n    \"\"\"\n    @root_validator()\n    def validate_enviroment(cls, values: Dict) -> Dict:\n        values[\"qianfan_ak\"] = get_from_dict_or_env(\n            values,\n            \"qianfan_ak\",\n            \"QIANFAN_AK\",\n        )\n        values[\"qianfan_sk\"] = get_from_dict_or_env(\n            values,\n            \"qianfan_sk\",\n            \"QIANFAN_SK\",\n        )\n        params = {\n            \"ak\": values[\"qianfan_ak\"],\n            \"sk\": values[\"qianfan_sk\"],\n            \"model\": values[\"model\"],\n        }\n        if values[\"endpoint\"] is not None and values[\"endpoint\"] != \"\":\n            params[\"endpoint\"] = values[\"endpoint\"]\n        try:\n            import qianfan\n            values[\"client\"] = qianfan.Completion(**params)\n        except ImportError:\n            raise ImportError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baidu_qianfan_endpoint.html"}
{"id": "b4044a8354f7-2", "text": "except ImportError:\n            raise ImportError(\n                \"qianfan package not found, please install it with \"\n                \"`pip install qianfan`\"\n            )\n        return values\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        return {\n            **{\"endpoint\": self.endpoint, \"model\": self.model},\n            **super()._identifying_params,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"baidu-qianfan-endpoint\"\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Qianfan API.\"\"\"\n        normal_params = {\n            \"model\": self.model,\n            \"endpoint\": self.endpoint,\n            \"stream\": self.streaming,\n            \"request_timeout\": self.request_timeout,\n            \"top_p\": self.top_p,\n            \"temperature\": self.temperature,\n            \"penalty_score\": self.penalty_score,\n        }\n        return {**normal_params, **self.model_kwargs}\n    def _convert_prompt_msg_params(\n        self,\n        prompt: str,\n        **kwargs: Any,\n    ) -> dict:\n        if \"streaming\" in kwargs:\n            kwargs[\"stream\"] = kwargs.pop(\"streaming\")\n        return {\n            **{\"prompt\": prompt, \"model\": self.model},\n            **self._default_params,\n            **kwargs,\n        }\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baidu_qianfan_endpoint.html"}
{"id": "b4044a8354f7-3", "text": "**kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to an qianfan models endpoint for each generation with a prompt.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = qianfan_model(\"Tell me a joke.\")\n        \"\"\"\n        if self.streaming:\n            completion = \"\"\n            for chunk in self._stream(prompt, stop, run_manager, **kwargs):\n                completion += chunk.text\n            return completion\n        params = self._convert_prompt_msg_params(prompt, **kwargs)\n        response_payload = self.client.do(**params)\n        return response_payload[\"result\"]\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        if self.streaming:\n            completion = \"\"\n            async for chunk in self._astream(prompt, stop, run_manager, **kwargs):\n                completion += chunk.text\n            return completion\n        params = self._convert_prompt_msg_params(prompt, **kwargs)\n        response_payload = await self.client.ado(**params)\n        return response_payload[\"result\"]\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        params = self._convert_prompt_msg_params(prompt, **{**kwargs, \"stream\": True})", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baidu_qianfan_endpoint.html"}
{"id": "b4044a8354f7-4", "text": "for res in self.client.do(**params):\n            if res:\n                chunk = GenerationChunk(text=res[\"result\"])\n                yield chunk\n                if run_manager:\n                    run_manager.on_llm_new_token(chunk.text)\n    async def _astream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[GenerationChunk]:\n        params = self._convert_prompt_msg_params(prompt, **{**kwargs, \"stream\": True})\n        async for res in await self.client.ado(**params):\n            if res:\n                chunk = GenerationChunk(text=res[\"result\"])\n                yield chunk\n                if run_manager:\n                    await run_manager.on_llm_new_token(chunk.text)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baidu_qianfan_endpoint.html"}
{"id": "ae2fa920f223-0", "text": "Source code for langchain.llms.javelin_ai_gateway\nfrom __future__ import annotations\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import BaseModel, Extra\n# Ignoring type because below is valid pydantic code\n# Unexpected keyword argument \"extra\" for \"__init_subclass__\" of \"object\"\n[docs]class Params(BaseModel, extra=Extra.allow):  # type: ignore[call-arg]\n    \"\"\"Parameters for the Javelin AI Gateway LLM.\"\"\"\n    temperature: float = 0.0\n    stop: Optional[List[str]] = None\n    max_tokens: Optional[int] = None\n[docs]class JavelinAIGateway(LLM):\n    \"\"\"Javelin AI Gateway LLMs.\n    To use, you should have the ``javelin_sdk`` python package installed.\n    For more information, see https://docs.getjavelin.io\n    Example:\n        .. code-block:: python\n            from langchain.llms import JavelinAIGateway\n            completions = JavelinAIGateway(\n                gateway_uri=\"<your-javelin-ai-gateway-uri>\",\n                route=\"<your-javelin-ai-gateway-completions-route>\",\n                params={\n                    \"temperature\": 0.1\n                }\n            )\n    \"\"\"\n    route: str\n    \"\"\"The route to use for the Javelin AI Gateway API.\"\"\"\n    client: Optional[Any] = None\n    \"\"\"The Javelin AI Gateway client.\"\"\"\n    gateway_uri: Optional[str] = None\n    \"\"\"The URI of the Javelin AI Gateway API.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/javelin_ai_gateway.html"}
{"id": "ae2fa920f223-1", "text": "\"\"\"The URI of the Javelin AI Gateway API.\"\"\"\n    params: Optional[Params] = None\n    \"\"\"Parameters for the Javelin AI Gateway API.\"\"\"\n    javelin_api_key: Optional[str] = None\n    \"\"\"The API key for the Javelin AI Gateway API.\"\"\"\n    def __init__(self, **kwargs: Any):\n        try:\n            from javelin_sdk import (\n                JavelinClient,\n                UnauthorizedError,\n            )\n        except ImportError:\n            raise ImportError(\n                \"Could not import javelin_sdk python package. \"\n                \"Please install it with `pip install javelin_sdk`.\"\n            )\n        super().__init__(**kwargs)\n        if self.gateway_uri:\n            try:\n                self.client = JavelinClient(\n                    base_url=self.gateway_uri, api_key=self.javelin_api_key\n                )\n            except UnauthorizedError as e:\n                raise ValueError(\"Javelin: Incorrect API Key.\") from e\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Javelin AI Gateway API.\"\"\"\n        params: Dict[str, Any] = {\n            \"gateway_uri\": self.gateway_uri,\n            \"route\": self.route,\n            \"javelin_api_key\": self.javelin_api_key,\n            **(self.params.dict() if self.params else {}),\n        }\n        return params\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return self._default_params\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/javelin_ai_gateway.html"}
{"id": "ae2fa920f223-2", "text": "run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call the Javelin AI Gateway API.\"\"\"\n        data: Dict[str, Any] = {\n            \"prompt\": prompt,\n            **(self.params.dict() if self.params else {}),\n        }\n        if s := (stop or (self.params.stop if self.params else None)):\n            data[\"stop\"] = s\n        if self.client is not None:\n            resp = self.client.query_route(self.route, query_body=data)\n        else:\n            raise ValueError(\"Javelin client is not initialized.\")\n        resp_dict = resp.dict()\n        try:\n            return resp_dict[\"llm_response\"][\"choices\"][0][\"text\"]\n        except KeyError:\n            return \"\"\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call async the Javelin AI Gateway API.\"\"\"\n        data: Dict[str, Any] = {\n            \"prompt\": prompt,\n            **(self.params.dict() if self.params else {}),\n        }\n        if s := (stop or (self.params.stop if self.params else None)):\n            data[\"stop\"] = s\n        if self.client is not None:\n            resp = await self.client.aquery_route(self.route, query_body=data)\n        else:\n            raise ValueError(\"Javelin client is not initialized.\")\n        resp_dict = resp.dict()\n        try:\n            return resp_dict[\"llm_response\"][\"choices\"][0][\"text\"]\n        except KeyError:\n            return \"\"\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/javelin_ai_gateway.html"}
{"id": "ae2fa920f223-3", "text": "except KeyError:\n            return \"\"\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"javelin-ai-gateway\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/javelin_ai_gateway.html"}
{"id": "06e439f79de9-0", "text": "Source code for langchain.llms.self_hosted\nimport importlib.util\nimport logging\nimport pickle\nfrom typing import Any, Callable, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra\nlogger = logging.getLogger(__name__)\ndef _generate_text(\n    pipeline: Any,\n    prompt: str,\n    *args: Any,\n    stop: Optional[List[str]] = None,\n    **kwargs: Any,\n) -> str:\n    \"\"\"Inference function to send to the remote hardware.\n    Accepts a pipeline callable (or, more likely,\n    a key pointing to the model on the cluster's object store)\n    and returns text predictions for each document\n    in the batch.\n    \"\"\"\n    text = pipeline(prompt, *args, **kwargs)\n    if stop is not None:\n        text = enforce_stop_tokens(text, stop)\n    return text\ndef _send_pipeline_to_device(pipeline: Any, device: int) -> Any:\n    \"\"\"Send a pipeline to a device on the cluster.\"\"\"\n    if isinstance(pipeline, str):\n        with open(pipeline, \"rb\") as f:\n            pipeline = pickle.load(f)\n    if importlib.util.find_spec(\"torch\") is not None:\n        import torch\n        cuda_device_count = torch.cuda.device_count()\n        if device < -1 or (device >= cuda_device_count):\n            raise ValueError(\n                f\"Got device=={device}, \"\n                f\"device is required to be within [-1, {cuda_device_count})\"\n            )\n        if device < 0 and cuda_device_count > 0:\n            logger.warning(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html"}
{"id": "06e439f79de9-1", "text": "if device < 0 and cuda_device_count > 0:\n            logger.warning(\n                \"Device has %d GPUs available. \"\n                \"Provide device={deviceId} to `from_model_id` to use available\"\n                \"GPUs for execution. deviceId is -1 for CPU and \"\n                \"can be a positive integer associated with CUDA device id.\",\n                cuda_device_count,\n            )\n        pipeline.device = torch.device(device)\n        pipeline.model = pipeline.model.to(pipeline.device)\n    return pipeline\n[docs]class SelfHostedPipeline(LLM):\n    \"\"\"Model inference on self-hosted remote hardware.\n    Supported hardware includes auto-launched instances on AWS, GCP, Azure,\n    and Lambda, as well as servers specified\n    by IP address and SSH credentials (such as on-prem, or another\n    cloud like Paperspace, Coreweave, etc.).\n    To use, you should have the ``runhouse`` python package installed.\n    Example for custom pipeline and inference functions:\n        .. code-block:: python\n            from langchain.llms import SelfHostedPipeline\n            from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline\n            import runhouse as rh\n            def load_pipeline():\n                tokenizer = AutoTokenizer.from_pretrained(\"gpt2\")\n                model = AutoModelForCausalLM.from_pretrained(\"gpt2\")\n                return pipeline(\n                    \"text-generation\", model=model, tokenizer=tokenizer,\n                    max_new_tokens=10\n                )\n            def inference_fn(pipeline, prompt, stop = None):\n                return pipeline(prompt)[0][\"generated_text\"]\n            gpu = rh.cluster(name=\"rh-a10x\", instance_type=\"A100:1\")\n            llm = SelfHostedPipeline(\n                model_load_fn=load_pipeline,\n                hardware=gpu,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html"}
{"id": "06e439f79de9-2", "text": "model_load_fn=load_pipeline,\n                hardware=gpu,\n                model_reqs=model_reqs, inference_fn=inference_fn\n            )\n    Example for <2GB model (can be serialized and sent directly to the server):\n        .. code-block:: python\n            from langchain.llms import SelfHostedPipeline\n            import runhouse as rh\n            gpu = rh.cluster(name=\"rh-a10x\", instance_type=\"A100:1\")\n            my_model = ...\n            llm = SelfHostedPipeline.from_pipeline(\n                pipeline=my_model,\n                hardware=gpu,\n                model_reqs=[\"./\", \"torch\", \"transformers\"],\n            )\n    Example passing model path for larger models:\n        .. code-block:: python\n            from langchain.llms import SelfHostedPipeline\n            import runhouse as rh\n            import pickle\n            from transformers import pipeline\n            generator = pipeline(model=\"gpt2\")\n            rh.blob(pickle.dumps(generator), path=\"models/pipeline.pkl\"\n                ).save().to(gpu, path=\"models\")\n            llm = SelfHostedPipeline.from_pipeline(\n                pipeline=\"models/pipeline.pkl\",\n                hardware=gpu,\n                model_reqs=[\"./\", \"torch\", \"transformers\"],\n            )\n    \"\"\"\n    pipeline_ref: Any  #: :meta private:\n    client: Any  #: :meta private:\n    inference_fn: Callable = _generate_text  #: :meta private:\n    \"\"\"Inference function to send to the remote hardware.\"\"\"\n    hardware: Any\n    \"\"\"Remote hardware to send the inference function to.\"\"\"\n    model_load_fn: Callable\n    \"\"\"Function to load the model remotely on the server.\"\"\"\n    load_fn_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments to pass to the model load function.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html"}
{"id": "06e439f79de9-3", "text": "\"\"\"Keyword arguments to pass to the model load function.\"\"\"\n    model_reqs: List[str] = [\"./\", \"torch\"]\n    \"\"\"Requirements to install on hardware to inference the model.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    def __init__(self, **kwargs: Any):\n        \"\"\"Init the pipeline with an auxiliary function.\n        The load function must be in global scope to be imported\n        and run on the server, i.e. in a module and not a REPL or closure.\n        Then, initialize the remote inference function.\n        \"\"\"\n        super().__init__(**kwargs)\n        try:\n            import runhouse as rh\n        except ImportError:\n            raise ImportError(\n                \"Could not import runhouse python package. \"\n                \"Please install it with `pip install runhouse`.\"\n            )\n        remote_load_fn = rh.function(fn=self.model_load_fn).to(\n            self.hardware, reqs=self.model_reqs\n        )\n        _load_fn_kwargs = self.load_fn_kwargs or {}\n        self.pipeline_ref = remote_load_fn.remote(**_load_fn_kwargs)\n        self.client = rh.function(fn=self.inference_fn).to(\n            self.hardware, reqs=self.model_reqs\n        )\n[docs]    @classmethod\n    def from_pipeline(\n        cls,\n        pipeline: Any,\n        hardware: Any,\n        model_reqs: Optional[List[str]] = None,\n        device: int = 0,\n        **kwargs: Any,\n    ) -> LLM:\n        \"\"\"Init the SelfHostedPipeline from a pipeline object or string.\"\"\"\n        if not isinstance(pipeline, str):\n            logger.warning(\n                \"Serializing pipeline to send to remote hardware. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html"}
{"id": "06e439f79de9-4", "text": "logger.warning(\n                \"Serializing pipeline to send to remote hardware. \"\n                \"Note, it can be quite slow\"\n                \"to serialize and send large models with each execution. \"\n                \"Consider sending the pipeline\"\n                \"to the cluster and passing the path to the pipeline instead.\"\n            )\n        load_fn_kwargs = {\"pipeline\": pipeline, \"device\": device}\n        return cls(\n            load_fn_kwargs=load_fn_kwargs,\n            model_load_fn=_send_pipeline_to_device,\n            hardware=hardware,\n            model_reqs=[\"transformers\", \"torch\"] + (model_reqs or []),\n            **kwargs,\n        )\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"hardware\": self.hardware},\n        }\n    @property\n    def _llm_type(self) -> str:\n        return \"self_hosted_llm\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        return self.client(\n            pipeline=self.pipeline_ref, prompt=prompt, stop=stop, **kwargs\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html"}
{"id": "408339a0d5d8-0", "text": "Source code for langchain.llms.nlpcloud\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class NLPCloud(LLM):\n    \"\"\"NLPCloud large language models.\n    To use, you should have the ``nlpcloud`` python package installed, and the\n    environment variable ``NLPCLOUD_API_KEY`` set with your API key.\n    Example:\n        .. code-block:: python\n            from langchain.llms import NLPCloud\n            nlpcloud = NLPCloud(model=\"finetuned-gpt-neox-20b\")\n    \"\"\"\n    client: Any  #: :meta private:\n    model_name: str = \"finetuned-gpt-neox-20b\"\n    \"\"\"Model name to use.\"\"\"\n    gpu: bool = True\n    \"\"\"Whether to use a GPU or not\"\"\"\n    lang: str = \"en\"\n    \"\"\"Language to use (multilingual addon)\"\"\"\n    temperature: float = 0.7\n    \"\"\"What sampling temperature to use.\"\"\"\n    max_length: int = 256\n    \"\"\"The maximum number of tokens to generate in the completion.\"\"\"\n    length_no_input: bool = True\n    \"\"\"Whether min_length and max_length should include the length of the input.\"\"\"\n    remove_input: bool = True\n    \"\"\"Remove input text from API response\"\"\"\n    remove_end_sequence: bool = True\n    \"\"\"Whether or not to remove the end sequence token.\"\"\"\n    bad_words: List[str] = []\n    \"\"\"List of tokens not allowed to be generated.\"\"\"\n    top_p: int = 1", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html"}
{"id": "408339a0d5d8-1", "text": "top_p: int = 1\n    \"\"\"Total probability mass of tokens to consider at each step.\"\"\"\n    top_k: int = 50\n    \"\"\"The number of highest probability tokens to keep for top-k filtering.\"\"\"\n    repetition_penalty: float = 1.0\n    \"\"\"Penalizes repeated tokens. 1.0 means no penalty.\"\"\"\n    num_beams: int = 1\n    \"\"\"Number of beams for beam search.\"\"\"\n    num_return_sequences: int = 1\n    \"\"\"How many completions to generate for each prompt.\"\"\"\n    nlpcloud_api_key: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        nlpcloud_api_key = get_from_dict_or_env(\n            values, \"nlpcloud_api_key\", \"NLPCLOUD_API_KEY\"\n        )\n        try:\n            import nlpcloud\n            values[\"client\"] = nlpcloud.Client(\n                values[\"model_name\"],\n                nlpcloud_api_key,\n                gpu=values[\"gpu\"],\n                lang=values[\"lang\"],\n            )\n        except ImportError:\n            raise ImportError(\n                \"Could not import nlpcloud python package. \"\n                \"Please install it with `pip install nlpcloud`.\"\n            )\n        return values\n    @property\n    def _default_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the default parameters for calling NLPCloud API.\"\"\"\n        return {\n            \"temperature\": self.temperature,\n            \"max_length\": self.max_length,\n            \"length_no_input\": self.length_no_input,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html"}
{"id": "408339a0d5d8-2", "text": "\"length_no_input\": self.length_no_input,\n            \"remove_input\": self.remove_input,\n            \"remove_end_sequence\": self.remove_end_sequence,\n            \"bad_words\": self.bad_words,\n            \"top_p\": self.top_p,\n            \"top_k\": self.top_k,\n            \"repetition_penalty\": self.repetition_penalty,\n            \"num_beams\": self.num_beams,\n            \"num_return_sequences\": self.num_return_sequences,\n        }\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"model_name\": self.model_name},\n            **{\"gpu\": self.gpu},\n            **{\"lang\": self.lang},\n            **self._default_params,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"nlpcloud\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to NLPCloud's create endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Not supported by this interface (pass in init method)\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = nlpcloud(\"Tell me a joke.\")\n        \"\"\"\n        if stop and len(stop) > 1:\n            raise ValueError(\n                \"NLPCloud only supports a single stop sequence per generation.\"\n                \"Pass in a list of length 1.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html"}
{"id": "408339a0d5d8-3", "text": "\"Pass in a list of length 1.\"\n            )\n        elif stop and len(stop) == 1:\n            end_sequence = stop[0]\n        else:\n            end_sequence = None\n        params = {**self._default_params, **kwargs}\n        response = self.client.generation(prompt, end_sequence=end_sequence, **params)\n        return response[\"generated_text\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html"}
{"id": "a43f1f289360-0", "text": "Source code for langchain.llms.anyscale\n\"\"\"Wrapper around Anyscale Endpoint\"\"\"\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Dict,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Set,\n    Tuple,\n    cast,\n)\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.openai import (\n    BaseOpenAI,\n    acompletion_with_retry,\n    completion_with_retry,\n)\nfrom langchain.pydantic_v1 import Field, SecretStr, root_validator\nfrom langchain.schema import Generation, LLMResult\nfrom langchain.schema.output import GenerationChunk\nfrom langchain.utils import convert_to_secret_str, get_from_dict_or_env\n[docs]def update_token_usage(\n    keys: Set[str], response: Dict[str, Any], token_usage: Dict[str, Any]\n) -> None:\n    \"\"\"Update token usage.\"\"\"\n    _keys_to_use = keys.intersection(response[\"usage\"])\n    for _key in _keys_to_use:\n        if _key not in token_usage:\n            token_usage[_key] = response[\"usage\"][_key]\n        else:\n            token_usage[_key] += response[\"usage\"][_key]\n[docs]def create_llm_result(\n    choices: Any, prompts: List[str], token_usage: Dict[str, int], model_name: str\n) -> LLMResult:\n    \"\"\"Create the LLMResult from the choices and prompts.\"\"\"\n    generations = []\n    for i, _ in enumerate(prompts):\n        choice = choices[i]\n        generations.append(\n            [\n                Generation(\n                    text=choice[\"message\"][\"content\"],\n                    generation_info=dict(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html"}
{"id": "a43f1f289360-1", "text": "Generation(\n                    text=choice[\"message\"][\"content\"],\n                    generation_info=dict(\n                        finish_reason=choice.get(\"finish_reason\"),\n                        logprobs=choice.get(\"logprobs\"),\n                    ),\n                )\n            ]\n        )\n    llm_output = {\"token_usage\": token_usage, \"model_name\": model_name}\n    return LLMResult(generations=generations, llm_output=llm_output)\n[docs]class Anyscale(BaseOpenAI):\n    \"\"\"Anyscale large language models.\n    To use, you should have the environment variable ``ANYSCALE_API_BASE`` and\n    ``ANYSCALE_API_KEY``set with your Anyscale Endpoint, or pass it as a named\n    parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.llms import Anyscale\n            anyscalellm = Anyscale(anyscale_api_base=\"ANYSCALE_API_BASE\",\n                                   anyscale_api_key=\"ANYSCALE_API_KEY\",\n                                   model_name=\"meta-llama/Llama-2-7b-chat-hf\")\n            # To leverage Ray for parallel processing\n            @ray.remote(num_cpus=1)\n            def send_query(llm, text):\n                resp = llm(text)\n                return resp\n            futures = [send_query.remote(anyscalellm, text) for text in texts]\n            results = ray.get(futures)\n    \"\"\"\n    \"\"\"Key word arguments to pass to the model.\"\"\"\n    anyscale_api_base: Optional[str] = None\n    anyscale_api_key: Optional[SecretStr] = None\n    prefix_messages: List = Field(default_factory=list)\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html"}
{"id": "a43f1f289360-2", "text": "\"\"\"Validate that api key and python package exists in environment.\"\"\"\n        values[\"anyscale_api_base\"] = get_from_dict_or_env(\n            values, \"anyscale_api_base\", \"ANYSCALE_API_BASE\"\n        )\n        values[\"anyscale_api_key\"] = convert_to_secret_str(\n            get_from_dict_or_env(values, \"anyscale_api_key\", \"ANYSCALE_API_KEY\")\n        )\n        try:\n            import openai\n            ## Always create ChatComplete client, replacing the legacy Complete client\n            values[\"client\"] = openai.ChatCompletion\n        except ImportError:\n            raise ImportError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\"\n            )\n        if values[\"streaming\"] and values[\"n\"] > 1:\n            raise ValueError(\"Cannot stream results when n > 1.\")\n        if values[\"streaming\"] and values[\"best_of\"] > 1:\n            raise ValueError(\"Cannot stream results when best_of > 1.\")\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"model_name\": self.model_name},\n            **super()._identifying_params,\n        }\n    @property\n    def _invocation_params(self) -> Dict[str, Any]:\n        \"\"\"Get the parameters used to invoke the model.\"\"\"\n        openai_creds: Dict[str, Any] = {\n            \"api_key\": cast(SecretStr, self.anyscale_api_key).get_secret_value(),\n            \"api_base\": self.anyscale_api_base,\n        }\n        return {**openai_creds, **{\"model\": self.model_name}, **super()._default_params}\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html"}
{"id": "a43f1f289360-3", "text": "@property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"Anyscale LLM\"\n    def _get_chat_messages(\n        self, prompts: List[str], stop: Optional[List[str]] = None\n    ) -> Tuple:\n        if len(prompts) > 1:\n            raise ValueError(\n                f\"Anyscale currently only supports single prompt, got {prompts}\"\n            )\n        messages = self.prefix_messages + [{\"role\": \"user\", \"content\": prompts[0]}]\n        params: Dict[str, Any] = self._invocation_params\n        if stop is not None:\n            if \"stop\" in params:\n                raise ValueError(\"`stop` found in both the input and default params.\")\n            params[\"stop\"] = stop\n        if params.get(\"max_tokens\") == -1:\n            # for Chat api, omitting max_tokens is equivalent to having no limit\n            del params[\"max_tokens\"]\n        return messages, params\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        messages, params = self._get_chat_messages([prompt], stop)\n        params = {**params, **kwargs, \"stream\": True}\n        for stream_resp in completion_with_retry(\n            self, messages=messages, run_manager=run_manager, **params\n        ):\n            token = stream_resp[\"choices\"][0][\"delta\"].get(\"content\", \"\")\n            chunk = GenerationChunk(text=token)\n            yield chunk\n            if run_manager:\n                run_manager.on_llm_new_token(token, chunk=chunk)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html"}
{"id": "a43f1f289360-4", "text": "run_manager.on_llm_new_token(token, chunk=chunk)\n    async def _astream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[GenerationChunk]:\n        messages, params = self._get_chat_messages([prompt], stop)\n        params = {**params, **kwargs, \"stream\": True}\n        async for stream_resp in await acompletion_with_retry(\n            self, messages=messages, run_manager=run_manager, **params\n        ):\n            token = stream_resp[\"choices\"][0][\"delta\"].get(\"content\", \"\")\n            chunk = GenerationChunk(text=token)\n            yield chunk\n            if run_manager:\n                await run_manager.on_llm_new_token(token, chunk=chunk)\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        choices = []\n        token_usage: Dict[str, int] = {}\n        _keys = {\"completion_tokens\", \"prompt_tokens\", \"total_tokens\"}\n        for prompt in prompts:\n            if self.streaming:\n                generation: Optional[GenerationChunk] = None\n                for chunk in self._stream(prompt, stop, run_manager, **kwargs):\n                    if generation is None:\n                        generation = chunk\n                    else:\n                        generation += chunk\n                assert generation is not None\n                choices.append(\n                    {\n                        \"message\": {\"content\": generation.text},\n                        \"finish_reason\": generation.generation_info.get(\"finish_reason\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html"}
{"id": "a43f1f289360-5", "text": "\"finish_reason\": generation.generation_info.get(\"finish_reason\")\n                        if generation.generation_info\n                        else None,\n                        \"logprobs\": generation.generation_info.get(\"logprobs\")\n                        if generation.generation_info\n                        else None,\n                    }\n                )\n            else:\n                messages, params = self._get_chat_messages([prompt], stop)\n                params = {**params, **kwargs}\n                response = completion_with_retry(\n                    self, messages=messages, run_manager=run_manager, **params\n                )\n                choices.extend(response[\"choices\"])\n                update_token_usage(_keys, response, token_usage)\n        return create_llm_result(choices, prompts, token_usage, self.model_name)\n    async def _agenerate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        choices = []\n        token_usage: Dict[str, int] = {}\n        _keys = {\"completion_tokens\", \"prompt_tokens\", \"total_tokens\"}\n        for prompt in prompts:\n            messages = self.prefix_messages + [{\"role\": \"user\", \"content\": prompt}]\n            if self.streaming:\n                generation: Optional[GenerationChunk] = None\n                async for chunk in self._astream(prompt, stop, run_manager, **kwargs):\n                    if generation is None:\n                        generation = chunk\n                    else:\n                        generation += chunk\n                assert generation is not None\n                choices.append(\n                    {\n                        \"message\": {\"content\": generation.text},\n                        \"finish_reason\": generation.generation_info.get(\"finish_reason\")\n                        if generation.generation_info\n                        else None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html"}
{"id": "a43f1f289360-6", "text": "if generation.generation_info\n                        else None,\n                        \"logprobs\": generation.generation_info.get(\"logprobs\")\n                        if generation.generation_info\n                        else None,\n                    }\n                )\n            else:\n                messages, params = self._get_chat_messages([prompt], stop)\n                params = {**params, **kwargs}\n                response = await acompletion_with_retry(\n                    self, messages=messages, run_manager=run_manager, **params\n                )\n                choices.extend(response[\"choices\"])\n                update_token_usage(_keys, response, token_usage)\n        return create_llm_result(choices, prompts, token_usage, self.model_name)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html"}
{"id": "f4f64394878b-0", "text": "Source code for langchain.llms.symblai_nebula\nimport json\nimport logging\nfrom typing import Any, Callable, Dict, List, Mapping, Optional\nimport requests\nfrom requests import ConnectTimeout, ReadTimeout, RequestException\nfrom tenacity import (\n    before_sleep_log,\n    retry,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, SecretStr, root_validator\nfrom langchain.utils import convert_to_secret_str\nfrom langchain.utils.env import get_from_dict_or_env\nDEFAULT_NEBULA_SERVICE_URL = \"https://api-nebula.symbl.ai\"\nDEFAULT_NEBULA_SERVICE_PATH = \"/v1/model/generate\"\nlogger = logging.getLogger(__name__)\n[docs]class Nebula(LLM):\n    \"\"\"Nebula Service models.\n    To use, you should have the environment variable ``NEBULA_SERVICE_URL``,\n    ``NEBULA_SERVICE_PATH`` and ``NEBULA_API_KEY`` set with your Nebula\n    Service, or pass it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.llms import Nebula\n            nebula = Nebula(\n                nebula_service_url=\"NEBULA_SERVICE_URL\",\n                nebula_service_path=\"NEBULA_SERVICE_PATH\",\n                nebula_api_key=\"NEBULA_API_KEY\",\n            )\n    \"\"\"  # noqa: E501\n    \"\"\"Key/value arguments to pass to the model. Reserved for future use\"\"\"\n    model_kwargs: Optional[dict] = None\n    \"\"\"Optional\"\"\"\n    nebula_service_url: Optional[str] = None", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html"}
{"id": "f4f64394878b-1", "text": "\"\"\"Optional\"\"\"\n    nebula_service_url: Optional[str] = None\n    nebula_service_path: Optional[str] = None\n    nebula_api_key: Optional[SecretStr] = None\n    model: Optional[str] = None\n    max_new_tokens: Optional[int] = 128\n    temperature: Optional[float] = 0.6\n    top_p: Optional[float] = 0.95\n    repetition_penalty: Optional[float] = 1.0\n    top_k: Optional[int] = 0\n    penalty_alpha: Optional[float] = 0.0\n    stop_sequences: Optional[List[str]] = None\n    max_retries: Optional[int] = 10\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        nebula_service_url = get_from_dict_or_env(\n            values,\n            \"nebula_service_url\",\n            \"NEBULA_SERVICE_URL\",\n            DEFAULT_NEBULA_SERVICE_URL,\n        )\n        nebula_service_path = get_from_dict_or_env(\n            values,\n            \"nebula_service_path\",\n            \"NEBULA_SERVICE_PATH\",\n            DEFAULT_NEBULA_SERVICE_PATH,\n        )\n        nebula_api_key = convert_to_secret_str(\n            get_from_dict_or_env(values, \"nebula_api_key\", \"NEBULA_API_KEY\", None)\n        )\n        if nebula_service_url.endswith(\"/\"):\n            nebula_service_url = nebula_service_url[:-1]\n        if not nebula_service_path.startswith(\"/\"):\n            nebula_service_path = \"/\" + nebula_service_path", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html"}
{"id": "f4f64394878b-2", "text": "nebula_service_path = \"/\" + nebula_service_path\n        values[\"nebula_service_url\"] = nebula_service_url\n        values[\"nebula_service_path\"] = nebula_service_path\n        values[\"nebula_api_key\"] = nebula_api_key\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Cohere API.\"\"\"\n        return {\n            \"max_new_tokens\": self.max_new_tokens,\n            \"temperature\": self.temperature,\n            \"top_k\": self.top_k,\n            \"top_p\": self.top_p,\n            \"repetition_penalty\": self.repetition_penalty,\n            \"penalty_alpha\": self.penalty_alpha,\n        }\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {\n            \"nebula_service_url\": self.nebula_service_url,\n            \"nebula_service_path\": self.nebula_service_path,\n            **{\"model_kwargs\": _model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"nebula\"\n    def _invocation_params(\n        self, stop_sequences: Optional[List[str]], **kwargs: Any\n    ) -> dict:\n        params = self._default_params\n        if self.stop_sequences is not None and stop_sequences is not None:\n            raise ValueError(\"`stop` found in both the input and default params.\")\n        elif self.stop_sequences is not None:\n            params[\"stop_sequences\"] = self.stop_sequences\n        else:\n            params[\"stop_sequences\"] = stop_sequences\n        return {**params, **kwargs}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html"}
{"id": "f4f64394878b-3", "text": "params[\"stop_sequences\"] = stop_sequences\n        return {**params, **kwargs}\n    @staticmethod\n    def _process_response(response: Any, stop: Optional[List[str]]) -> str:\n        text = response[\"output\"][\"text\"]\n        if stop:\n            text = enforce_stop_tokens(text, stop)\n        return text\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Nebula Service endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = nebula(\"Tell me a joke.\")\n        \"\"\"\n        params = self._invocation_params(stop, **kwargs)\n        prompt = prompt.strip()\n        if \"\\n\" in prompt:\n            instruction = prompt.split(\"\\n\")[0]\n            conversation = \"\\n\".join(prompt.split(\"\\n\")[1:])\n        else:\n            raise ValueError(\"Prompt must contain instruction and conversation.\")\n        response = completion_with_retry(\n            self,\n            instruction=instruction,\n            conversation=conversation,\n            params=params,\n            url=f\"{self.nebula_service_url}{self.nebula_service_path}\",\n        )\n        _stop = params.get(\"stop_sequences\")\n        return self._process_response(response, _stop)\n[docs]def make_request(\n    self: Nebula,\n    instruction: str,\n    conversation: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html"}
{"id": "f4f64394878b-4", "text": "self: Nebula,\n    instruction: str,\n    conversation: str,\n    url: str = f\"{DEFAULT_NEBULA_SERVICE_URL}{DEFAULT_NEBULA_SERVICE_PATH}\",\n    params: Optional[Dict] = None,\n) -> Any:\n    \"\"\"Generate text from the model.\"\"\"\n    params = params or {}\n    api_key = None\n    if self.nebula_api_key is not None:\n        api_key = self.nebula_api_key.get_secret_value()\n    headers = {\n        \"Content-Type\": \"application/json\",\n        \"ApiKey\": f\"{api_key}\",\n    }\n    body = {\n        \"prompt\": {\n            \"instruction\": instruction,\n            \"conversation\": {\"text\": f\"{conversation}\"},\n        }\n    }\n    # add params to body\n    for key, value in params.items():\n        body[key] = value\n    # make request\n    response = requests.post(url, headers=headers, json=body)\n    if response.status_code != 200:\n        raise Exception(\n            f\"Request failed with status code {response.status_code}\"\n            f\" and message {response.text}\"\n        )\n    return json.loads(response.text)\ndef _create_retry_decorator(llm: Nebula) -> Callable[[Any], Any]:\n    min_seconds = 4\n    max_seconds = 10\n    # Wait 2^x * 1 second between each retry starting with\n    # 4 seconds, then up to 10 seconds, then 10 seconds afterward\n    max_retries = llm.max_retries if llm.max_retries is not None else 3\n    return retry(\n        reraise=True,\n        stop=stop_after_attempt(max_retries),", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html"}
{"id": "f4f64394878b-5", "text": "reraise=True,\n        stop=stop_after_attempt(max_retries),\n        wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),\n        retry=(\n            retry_if_exception_type((RequestException, ConnectTimeout, ReadTimeout))\n        ),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\n[docs]def completion_with_retry(llm: Nebula, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    retry_decorator = _create_retry_decorator(llm)\n    @retry_decorator\n    def _completion_with_retry(**_kwargs: Any) -> Any:\n        return make_request(llm, **_kwargs)\n    return _completion_with_retry(**kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html"}
{"id": "9071be2a5a55-0", "text": "Source code for langchain.llms.rwkv\n\"\"\"RWKV models.\nBased on https://github.com/saharNooby/rwkv.cpp/blob/master/rwkv/chat_with_bot.py\n         https://github.com/BlinkDL/ChatRWKV/blob/main/v2/chat.py\n\"\"\"\nfrom typing import Any, Dict, List, Mapping, Optional, Set\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import BaseModel, Extra, root_validator\n[docs]class RWKV(LLM, BaseModel):\n    \"\"\"RWKV language models.\n    To use, you should have the ``rwkv`` python package installed, the\n    pre-trained model file, and the model's config information.\n    Example:\n        .. code-block:: python\n            from langchain.llms import RWKV\n            model = RWKV(model=\"./models/rwkv-3b-fp16.bin\", strategy=\"cpu fp32\")\n            # Simplest invocation\n            response = model(\"Once upon a time, \")\n    \"\"\"\n    model: str\n    \"\"\"Path to the pre-trained RWKV model file.\"\"\"\n    tokens_path: str\n    \"\"\"Path to the RWKV tokens file.\"\"\"\n    strategy: str = \"cpu fp32\"\n    \"\"\"Token context window.\"\"\"\n    rwkv_verbose: bool = True\n    \"\"\"Print debug information.\"\"\"\n    temperature: float = 1.0\n    \"\"\"The temperature to use for sampling.\"\"\"\n    top_p: float = 0.5\n    \"\"\"The top-p value to use for sampling.\"\"\"\n    penalty_alpha_frequency: float = 0.4\n    \"\"\"Positive values penalize new tokens based on their existing frequency", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html"}
{"id": "9071be2a5a55-1", "text": "\"\"\"Positive values penalize new tokens based on their existing frequency\n    in the text so far, decreasing the model's likelihood to repeat the same\n    line verbatim..\"\"\"\n    penalty_alpha_presence: float = 0.4\n    \"\"\"Positive values penalize new tokens based on whether they appear\n    in the text so far, increasing the model's likelihood to talk about\n    new topics..\"\"\"\n    CHUNK_LEN: int = 256\n    \"\"\"Batch size for prompt processing.\"\"\"\n    max_tokens_per_generation: int = 256\n    \"\"\"Maximum number of tokens to generate.\"\"\"\n    client: Any = None  #: :meta private:\n    tokenizer: Any = None  #: :meta private:\n    pipeline: Any = None  #: :meta private:\n    model_tokens: Any = None  #: :meta private:\n    model_state: Any = None  #: :meta private:\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"verbose\": self.verbose,\n            \"top_p\": self.top_p,\n            \"temperature\": self.temperature,\n            \"penalty_alpha_frequency\": self.penalty_alpha_frequency,\n            \"penalty_alpha_presence\": self.penalty_alpha_presence,\n            \"CHUNK_LEN\": self.CHUNK_LEN,\n            \"max_tokens_per_generation\": self.max_tokens_per_generation,\n        }\n    @staticmethod\n    def _rwkv_param_names() -> Set[str]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"verbose\",\n        }\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the python package exists in the environment.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html"}
{"id": "9071be2a5a55-2", "text": "\"\"\"Validate that the python package exists in the environment.\"\"\"\n        try:\n            import tokenizers\n        except ImportError:\n            raise ImportError(\n                \"Could not import tokenizers python package. \"\n                \"Please install it with `pip install tokenizers`.\"\n            )\n        try:\n            from rwkv.model import RWKV as RWKVMODEL\n            from rwkv.utils import PIPELINE\n            values[\"tokenizer\"] = tokenizers.Tokenizer.from_file(values[\"tokens_path\"])\n            rwkv_keys = cls._rwkv_param_names()\n            model_kwargs = {k: v for k, v in values.items() if k in rwkv_keys}\n            model_kwargs[\"verbose\"] = values[\"rwkv_verbose\"]\n            values[\"client\"] = RWKVMODEL(\n                values[\"model\"], strategy=values[\"strategy\"], **model_kwargs\n            )\n            values[\"pipeline\"] = PIPELINE(values[\"client\"], values[\"tokens_path\"])\n        except ImportError:\n            raise ImportError(\n                \"Could not import rwkv python package. \"\n                \"Please install it with `pip install rwkv`.\"\n            )\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"model\": self.model,\n            **self._default_params,\n            **{k: v for k, v in self.__dict__.items() if k in RWKV._rwkv_param_names()},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return the type of llm.\"\"\"\n        return \"rwkv\"\n[docs]    def run_rnn(self, _tokens: List[str], newline_adj: int = 0) -> Any:\n        AVOID_REPEAT_TOKENS = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html"}
{"id": "9071be2a5a55-3", "text": "AVOID_REPEAT_TOKENS = []\n        AVOID_REPEAT = \"\uff0c\uff1a\uff1f\uff01\"\n        for i in AVOID_REPEAT:\n            dd = self.pipeline.encode(i)\n            assert len(dd) == 1\n            AVOID_REPEAT_TOKENS += dd\n        tokens = [int(x) for x in _tokens]\n        self.model_tokens += tokens\n        out: Any = None\n        while len(tokens) > 0:\n            out, self.model_state = self.client.forward(\n                tokens[: self.CHUNK_LEN], self.model_state\n            )\n            tokens = tokens[self.CHUNK_LEN :]\n        END_OF_LINE = 187\n        out[END_OF_LINE] += newline_adj  # adjust \\n probability\n        if self.model_tokens[-1] in AVOID_REPEAT_TOKENS:\n            out[self.model_tokens[-1]] = -999999999\n        return out\n[docs]    def rwkv_generate(self, prompt: str) -> str:\n        self.model_state = None\n        self.model_tokens = []\n        logits = self.run_rnn(self.tokenizer.encode(prompt).ids)\n        begin = len(self.model_tokens)\n        out_last = begin\n        occurrence: Dict = {}\n        decoded = \"\"\n        for i in range(self.max_tokens_per_generation):\n            for n in occurrence:\n                logits[n] -= (\n                    self.penalty_alpha_presence\n                    + occurrence[n] * self.penalty_alpha_frequency\n                )\n            token = self.pipeline.sample_logits(\n                logits, temperature=self.temperature, top_p=self.top_p\n            )\n            END_OF_TEXT = 0\n            if token == END_OF_TEXT:\n                break\n            if token not in occurrence:\n                occurrence[token] = 1\n            else:\n                occurrence[token] += 1\n            logits = self.run_rnn([token])", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html"}
{"id": "9071be2a5a55-4", "text": "occurrence[token] += 1\n            logits = self.run_rnn([token])\n            xxx = self.tokenizer.decode(self.model_tokens[out_last:])\n            if \"\\ufffd\" not in xxx:  # avoid utf-8 display issues\n                decoded += xxx\n                out_last = begin + i + 1\n                if i >= self.max_tokens_per_generation - 100:\n                    break\n        return decoded\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        r\"\"\"RWKV generation\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: A list of strings to stop generation when encountered.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                prompt = \"Once upon a time, \"\n                response = model(prompt, n_predict=55)\n        \"\"\"\n        text = self.rwkv_generate(prompt)\n        if stop is not None:\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html"}
{"id": "d2060c7ad336-0", "text": "Source code for langchain.llms.cohere\nfrom __future__ import annotations\nimport logging\nfrom typing import Any, Callable, Dict, List, Optional\nfrom tenacity import (\n    before_sleep_log,\n    retry,\n    retry_if_exception_type,\n    stop_after_attempt,\n    wait_exponential,\n)\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.load.serializable import Serializable\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\ndef _create_retry_decorator(llm: Cohere) -> Callable[[Any], Any]:\n    import cohere\n    min_seconds = 4\n    max_seconds = 10\n    # Wait 2^x * 1 second between each retry starting with\n    # 4 seconds, then up to 10 seconds, then 10 seconds afterwards\n    return retry(\n        reraise=True,\n        stop=stop_after_attempt(llm.max_retries),\n        wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),\n        retry=(retry_if_exception_type(cohere.error.CohereError)),\n        before_sleep=before_sleep_log(logger, logging.WARNING),\n    )\n[docs]def completion_with_retry(llm: Cohere, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    retry_decorator = _create_retry_decorator(llm)\n    @retry_decorator\n    def _completion_with_retry(**kwargs: Any) -> Any:\n        return llm.client.generate(**kwargs)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html"}
{"id": "d2060c7ad336-1", "text": "return llm.client.generate(**kwargs)\n    return _completion_with_retry(**kwargs)\n[docs]def acompletion_with_retry(llm: Cohere, **kwargs: Any) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    retry_decorator = _create_retry_decorator(llm)\n    @retry_decorator\n    async def _completion_with_retry(**kwargs: Any) -> Any:\n        return await llm.async_client.generate(**kwargs)\n    return _completion_with_retry(**kwargs)\n[docs]class BaseCohere(Serializable):\n    \"\"\"Base class for Cohere models.\"\"\"\n    client: Any  #: :meta private:\n    async_client: Any  #: :meta private:\n    model: Optional[str] = Field(default=None)\n    \"\"\"Model name to use.\"\"\"\n    temperature: float = 0.75\n    \"\"\"A non-negative float that tunes the degree of randomness in generation.\"\"\"\n    cohere_api_key: Optional[str] = None\n    stop: Optional[List[str]] = None\n    streaming: bool = Field(default=False)\n    \"\"\"Whether to stream the results.\"\"\"\n    user_agent: str = \"langchain\"\n    \"\"\"Identifier for the application making the request.\"\"\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        try:\n            import cohere\n        except ImportError:\n            raise ImportError(\n                \"Could not import cohere python package. \"\n                \"Please install it with `pip install cohere`.\"\n            )\n        else:\n            cohere_api_key = get_from_dict_or_env(\n                values, \"cohere_api_key\", \"COHERE_API_KEY\"\n            )\n            client_name = values[\"user_agent\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html"}
{"id": "d2060c7ad336-2", "text": ")\n            client_name = values[\"user_agent\"]\n            values[\"client\"] = cohere.Client(cohere_api_key, client_name=client_name)\n            values[\"async_client\"] = cohere.AsyncClient(\n                cohere_api_key, client_name=client_name\n            )\n        return values\n[docs]class Cohere(LLM, BaseCohere):\n    \"\"\"Cohere large language models.\n    To use, you should have the ``cohere`` python package installed, and the\n    environment variable ``COHERE_API_KEY`` set with your API key, or pass\n    it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.llms import Cohere\n            cohere = Cohere(model=\"gptd-instruct-tft\", cohere_api_key=\"my-api-key\")\n    \"\"\"\n    max_tokens: int = 256\n    \"\"\"Denotes the number of tokens to predict per generation.\"\"\"\n    k: int = 0\n    \"\"\"Number of most likely tokens to consider at each step.\"\"\"\n    p: int = 1\n    \"\"\"Total probability mass of tokens to consider at each step.\"\"\"\n    frequency_penalty: float = 0.0\n    \"\"\"Penalizes repeated tokens according to frequency. Between 0 and 1.\"\"\"\n    presence_penalty: float = 0.0\n    \"\"\"Penalizes repeated tokens. Between 0 and 1.\"\"\"\n    truncate: Optional[str] = None\n    \"\"\"Specify how the client handles inputs longer than the maximum token\n    length: Truncate from START, END or NONE\"\"\"\n    max_retries: int = 10\n    \"\"\"Maximum number of retries to make when generating.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html"}
{"id": "d2060c7ad336-3", "text": "extra = Extra.forbid\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Cohere API.\"\"\"\n        return {\n            \"max_tokens\": self.max_tokens,\n            \"temperature\": self.temperature,\n            \"k\": self.k,\n            \"p\": self.p,\n            \"frequency_penalty\": self.frequency_penalty,\n            \"presence_penalty\": self.presence_penalty,\n            \"truncate\": self.truncate,\n        }\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"cohere_api_key\": \"COHERE_API_KEY\"}\n    @property\n    def _identifying_params(self) -> Dict[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model\": self.model}, **self._default_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"cohere\"\n    def _invocation_params(self, stop: Optional[List[str]], **kwargs: Any) -> dict:\n        params = self._default_params\n        if self.stop is not None and stop is not None:\n            raise ValueError(\"`stop` found in both the input and default params.\")\n        elif self.stop is not None:\n            params[\"stop_sequences\"] = self.stop\n        else:\n            params[\"stop_sequences\"] = stop\n        return {**params, **kwargs}\n    def _process_response(self, response: Any, stop: Optional[List[str]]) -> str:\n        text = response.generations[0].text\n        # If stop tokens are provided, Cohere's endpoint returns them.\n        # In order to make this consistent with other endpoints, we strip them.\n        if stop:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html"}
{"id": "d2060c7ad336-4", "text": "if stop:\n            text = enforce_stop_tokens(text, stop)\n        return text\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Cohere's generate endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = cohere(\"Tell me a joke.\")\n        \"\"\"\n        params = self._invocation_params(stop, **kwargs)\n        response = completion_with_retry(\n            self, model=self.model, prompt=prompt, **params\n        )\n        _stop = params.get(\"stop_sequences\")\n        return self._process_response(response, _stop)\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Async call out to Cohere's generate endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = await cohere(\"Tell me a joke.\")\n        \"\"\"\n        params = self._invocation_params(stop, **kwargs)\n        response = await acompletion_with_retry(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html"}
{"id": "d2060c7ad336-5", "text": "response = await acompletion_with_retry(\n            self, model=self.model, prompt=prompt, **params\n        )\n        _stop = params.get(\"stop_sequences\")\n        return self._process_response(response, _stop)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html"}
{"id": "71e1fdf62f7e-0", "text": "Source code for langchain.llms.human\nfrom typing import Any, Callable, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Field\ndef _display_prompt(prompt: str) -> None:\n    \"\"\"Displays the given prompt to the user.\"\"\"\n    print(f\"\\n{prompt}\")\ndef _collect_user_input(\n    separator: Optional[str] = None, stop: Optional[List[str]] = None\n) -> str:\n    \"\"\"Collects and returns user input as a single string.\"\"\"\n    separator = separator or \"\\n\"\n    lines = []\n    while True:\n        line = input()\n        if not line:\n            break\n        lines.append(line)\n        if stop and any(seq in line for seq in stop):\n            break\n    # Combine all lines into a single string\n    multi_line_input = separator.join(lines)\n    return multi_line_input\n[docs]class HumanInputLLM(LLM):\n    \"\"\"\n    It returns user input as the response.\n    \"\"\"\n    input_func: Callable = Field(default_factory=lambda: _collect_user_input)\n    prompt_func: Callable[[str], None] = Field(default_factory=lambda: _display_prompt)\n    separator: str = \"\\n\"\n    input_kwargs: Mapping[str, Any] = {}\n    prompt_kwargs: Mapping[str, Any] = {}\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"\n        Returns an empty dictionary as there are no identifying parameters.\n        \"\"\"\n        return {}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Returns the type of LLM.\"\"\"\n        return \"human-input\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/human.html"}
{"id": "71e1fdf62f7e-1", "text": "\"\"\"Returns the type of LLM.\"\"\"\n        return \"human-input\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"\n        Displays the prompt to the user and returns their input as a response.\n        Args:\n            prompt (str): The prompt to be displayed to the user.\n            stop (Optional[List[str]]): A list of stop strings.\n            run_manager (Optional[CallbackManagerForLLMRun]): Currently not used.\n        Returns:\n            str: The user's input as a response.\n        \"\"\"\n        self.prompt_func(prompt, **self.prompt_kwargs)\n        user_input = self.input_func(\n            separator=self.separator, stop=stop, **self.input_kwargs\n        )\n        if stop is not None:\n            # I believe this is required since the stop tokens\n            # are not enforced by the human themselves\n            user_input = enforce_stop_tokens(user_input, stop)\n        return user_input", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/human.html"}
{"id": "aafb9f5590ae-0", "text": "Source code for langchain.llms.fireworks\nimport asyncio\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import Any, AsyncIterator, Callable, Dict, Iterator, List, Optional, Union\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import BaseLLM, create_base_retry_decorator\nfrom langchain.pydantic_v1 import Field, SecretStr, root_validator\nfrom langchain.schema.output import Generation, GenerationChunk, LLMResult\nfrom langchain.utils import convert_to_secret_str\nfrom langchain.utils.env import get_from_dict_or_env\ndef _stream_response_to_generation_chunk(\n    stream_response: Any,\n) -> GenerationChunk:\n    \"\"\"Convert a stream response to a generation chunk.\"\"\"\n    return GenerationChunk(\n        text=stream_response.choices[0].text,\n        generation_info=dict(\n            finish_reason=stream_response.choices[0].finish_reason,\n            logprobs=stream_response.choices[0].logprobs,\n        ),\n    )\n[docs]class Fireworks(BaseLLM):\n    \"\"\"Fireworks models.\"\"\"\n    model: str = \"accounts/fireworks/models/llama-v2-7b-chat\"\n    model_kwargs: dict = Field(\n        default_factory=lambda: {\n            \"temperature\": 0.7,\n            \"max_tokens\": 512,\n            \"top_p\": 1,\n        }.copy()\n    )\n    fireworks_api_key: Optional[SecretStr] = None\n    max_retries: int = 20\n    batch_size: int = 20\n    use_retry: bool = True\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"fireworks_api_key\": \"FIREWORKS_API_KEY\"}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html"}
{"id": "aafb9f5590ae-1", "text": "return {\"fireworks_api_key\": \"FIREWORKS_API_KEY\"}\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key in environment.\"\"\"\n        try:\n            import fireworks.client\n        except ImportError as e:\n            raise ImportError(\n                \"Could not import fireworks-ai python package. \"\n                \"Please install it with `pip install fireworks-ai`.\"\n            ) from e\n        fireworks_api_key = convert_to_secret_str(\n            get_from_dict_or_env(values, \"fireworks_api_key\", \"FIREWORKS_API_KEY\")\n        )\n        fireworks.client.api_key = fireworks_api_key.get_secret_value()\n        return values\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"fireworks\"\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Call out to Fireworks endpoint with k unique prompts.\n        Args:\n            prompts: The prompts to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The full LLM output.\n        \"\"\"\n        params = {\n            \"model\": self.model,\n            **self.model_kwargs,\n        }\n        sub_prompts = self.get_batch_prompts(prompts)\n        choices = []\n        for _prompts in sub_prompts:\n            response = completion_with_retry_batching(\n                self,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html"}
{"id": "aafb9f5590ae-2", "text": "response = completion_with_retry_batching(\n                self,\n                self.use_retry,\n                prompt=_prompts,\n                run_manager=run_manager,\n                stop=stop,\n                **params,\n            )\n            choices.extend(response)\n        return self.create_llm_result(choices, prompts)\n    async def _agenerate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Call out to Fireworks endpoint async with k unique prompts.\"\"\"\n        params = {\n            \"model\": self.model,\n            **self.model_kwargs,\n        }\n        sub_prompts = self.get_batch_prompts(prompts)\n        choices = []\n        for _prompts in sub_prompts:\n            response = await acompletion_with_retry_batching(\n                self,\n                self.use_retry,\n                prompt=_prompts,\n                run_manager=run_manager,\n                stop=stop,\n                **params,\n            )\n            choices.extend(response)\n        return self.create_llm_result(choices, prompts)\n[docs]    def get_batch_prompts(\n        self,\n        prompts: List[str],\n    ) -> List[List[str]]:\n        \"\"\"Get the sub prompts for llm call.\"\"\"\n        sub_prompts = [\n            prompts[i : i + self.batch_size]\n            for i in range(0, len(prompts), self.batch_size)\n        ]\n        return sub_prompts\n[docs]    def create_llm_result(self, choices: Any, prompts: List[str]) -> LLMResult:\n        \"\"\"Create the LLMResult from the choices and prompts.\"\"\"\n        generations = []", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html"}
{"id": "aafb9f5590ae-3", "text": "\"\"\"Create the LLMResult from the choices and prompts.\"\"\"\n        generations = []\n        for i, _ in enumerate(prompts):\n            sub_choices = choices[i : (i + 1)]\n            generations.append(\n                [\n                    Generation(\n                        text=choice.__dict__[\"choices\"][0].text,\n                    )\n                    for choice in sub_choices\n                ]\n            )\n        llm_output = {\"model\": self.model}\n        return LLMResult(generations=generations, llm_output=llm_output)\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        params = {\n            \"model\": self.model,\n            \"prompt\": prompt,\n            \"stream\": True,\n            **self.model_kwargs,\n        }\n        for stream_resp in completion_with_retry(\n            self, self.use_retry, run_manager=run_manager, stop=stop, **params\n        ):\n            chunk = _stream_response_to_generation_chunk(stream_resp)\n            yield chunk\n            if run_manager:\n                run_manager.on_llm_new_token(chunk.text, chunk=chunk)\n    async def _astream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[GenerationChunk]:\n        params = {\n            \"model\": self.model,\n            \"prompt\": prompt,\n            \"stream\": True,\n            **self.model_kwargs,\n        }", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html"}
{"id": "aafb9f5590ae-4", "text": "\"stream\": True,\n            **self.model_kwargs,\n        }\n        async for stream_resp in await acompletion_with_retry_streaming(\n            self, self.use_retry, run_manager=run_manager, stop=stop, **params\n        ):\n            chunk = _stream_response_to_generation_chunk(stream_resp)\n            yield chunk\n            if run_manager:\n                await run_manager.on_llm_new_token(chunk.text, chunk=chunk)\n[docs]def conditional_decorator(\n    condition: bool, decorator: Callable[[Any], Any]\n) -> Callable[[Any], Any]:\n    def actual_decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:\n        if condition:\n            return decorator(func)\n        return func\n    return actual_decorator\n[docs]def completion_with_retry(\n    llm: Fireworks,\n    use_retry: bool,\n    *,\n    run_manager: Optional[CallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    import fireworks.client\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @conditional_decorator(use_retry, retry_decorator)\n    def _completion_with_retry(**kwargs: Any) -> Any:\n        return fireworks.client.Completion.create(\n            **kwargs,\n        )\n    return _completion_with_retry(**kwargs)\n[docs]async def acompletion_with_retry(\n    llm: Fireworks,\n    use_retry: bool,\n    *,\n    run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    import fireworks.client", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html"}
{"id": "aafb9f5590ae-5", "text": "\"\"\"Use tenacity to retry the completion call.\"\"\"\n    import fireworks.client\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @conditional_decorator(use_retry, retry_decorator)\n    async def _completion_with_retry(**kwargs: Any) -> Any:\n        return await fireworks.client.Completion.acreate(\n            **kwargs,\n        )\n    return await _completion_with_retry(**kwargs)\n[docs]def completion_with_retry_batching(\n    llm: Fireworks,\n    use_retry: bool,\n    *,\n    run_manager: Optional[CallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    import fireworks.client\n    prompt = kwargs[\"prompt\"]\n    del kwargs[\"prompt\"]\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @conditional_decorator(use_retry, retry_decorator)\n    def _completion_with_retry(prompt: str) -> Any:\n        return fireworks.client.Completion.create(**kwargs, prompt=prompt)\n    def batch_sync_run() -> List:\n        with ThreadPoolExecutor() as executor:\n            results = list(executor.map(_completion_with_retry, prompt))\n        return results\n    return batch_sync_run()\n[docs]async def acompletion_with_retry_batching(\n    llm: Fireworks,\n    use_retry: bool,\n    *,\n    run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    import fireworks.client\n    prompt = kwargs[\"prompt\"]\n    del kwargs[\"prompt\"]\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html"}
{"id": "aafb9f5590ae-6", "text": "retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @conditional_decorator(use_retry, retry_decorator)\n    async def _completion_with_retry(prompt: str) -> Any:\n        return await fireworks.client.Completion.acreate(**kwargs, prompt=prompt)\n    def run_coroutine_in_new_loop(\n        coroutine_func: Any, *args: Dict, **kwargs: Dict\n    ) -> Any:\n        new_loop = asyncio.new_event_loop()\n        try:\n            asyncio.set_event_loop(new_loop)\n            return new_loop.run_until_complete(coroutine_func(*args, **kwargs))\n        finally:\n            new_loop.close()\n    async def batch_sync_run() -> List:\n        with ThreadPoolExecutor() as executor:\n            results = list(\n                executor.map(\n                    run_coroutine_in_new_loop,\n                    [_completion_with_retry] * len(prompt),\n                    prompt,\n                )\n            )\n        return results\n    return await batch_sync_run()\n[docs]async def acompletion_with_retry_streaming(\n    llm: Fireworks,\n    use_retry: bool,\n    *,\n    run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the completion call for streaming.\"\"\"\n    import fireworks.client\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @conditional_decorator(use_retry, retry_decorator)\n    async def _completion_with_retry(**kwargs: Any) -> Any:\n        return fireworks.client.Completion.acreate(\n            **kwargs,\n        )\n    return await _completion_with_retry(**kwargs)\ndef _create_retry_decorator(\n    llm: Fireworks,\n    *,\n    run_manager: Optional[", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html"}
{"id": "aafb9f5590ae-7", "text": "llm: Fireworks,\n    *,\n    run_manager: Optional[\n        Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]\n    ] = None,\n) -> Callable[[Any], Any]:\n    \"\"\"Define retry mechanism.\"\"\"\n    import fireworks.client\n    errors = [\n        fireworks.client.error.RateLimitError,\n        fireworks.client.error.InternalServerError,\n        fireworks.client.error.BadGatewayError,\n        fireworks.client.error.ServiceUnavailableError,\n    ]\n    return create_base_retry_decorator(\n        error_types=errors, max_retries=llm.max_retries, run_manager=run_manager\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html"}
{"id": "d6d7968870bb-0", "text": "Source code for langchain.llms.huggingface_endpoint\nfrom typing import Any, Dict, List, Mapping, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\nVALID_TASKS = (\"text2text-generation\", \"text-generation\", \"summarization\")\n[docs]class HuggingFaceEndpoint(LLM):\n    \"\"\"HuggingFace Endpoint models.\n    To use, you should have the ``huggingface_hub`` python package installed, and the\n    environment variable ``HUGGINGFACEHUB_API_TOKEN`` set with your API token, or pass\n    it as a named parameter to the constructor.\n    Only supports `text-generation` and `text2text-generation` for now.\n    Example:\n        .. code-block:: python\n            from langchain.llms import HuggingFaceEndpoint\n            endpoint_url = (\n                \"https://abcdefghijklmnop.us-east-1.aws.endpoints.huggingface.cloud\"\n            )\n            hf = HuggingFaceEndpoint(\n                endpoint_url=endpoint_url,\n                huggingfacehub_api_token=\"my-api-key\"\n            )\n    \"\"\"\n    endpoint_url: str = \"\"\n    \"\"\"Endpoint URL to use.\"\"\"\n    task: Optional[str] = None\n    \"\"\"Task to call the model with.\n    Should be a task that returns `generated_text` or `summary_text`.\"\"\"\n    model_kwargs: Optional[dict] = None\n    \"\"\"Keyword arguments to pass to the model.\"\"\"\n    huggingfacehub_api_token: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html"}
{"id": "d6d7968870bb-1", "text": "\"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        huggingfacehub_api_token = get_from_dict_or_env(\n            values, \"huggingfacehub_api_token\", \"HUGGINGFACEHUB_API_TOKEN\"\n        )\n        try:\n            from huggingface_hub.hf_api import HfApi\n            try:\n                HfApi(\n                    endpoint=\"https://huggingface.co\",  # Can be a Private Hub endpoint.\n                    token=huggingfacehub_api_token,\n                ).whoami()\n            except Exception as e:\n                raise ValueError(\n                    \"Could not authenticate with huggingface_hub. \"\n                    \"Please check your API token.\"\n                ) from e\n        except ImportError:\n            raise ImportError(\n                \"Could not import huggingface_hub python package. \"\n                \"Please install it with `pip install huggingface_hub`.\"\n            )\n        values[\"huggingfacehub_api_token\"] = huggingfacehub_api_token\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        return {\n            **{\"endpoint_url\": self.endpoint_url, \"task\": self.task},\n            **{\"model_kwargs\": _model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"huggingface_endpoint\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html"}
{"id": "d6d7968870bb-2", "text": "prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to HuggingFace Hub's inference endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = hf(\"Tell me a joke.\")\n        \"\"\"\n        _model_kwargs = self.model_kwargs or {}\n        # payload samples\n        params = {**_model_kwargs, **kwargs}\n        parameter_payload = {\"inputs\": prompt, \"parameters\": params}\n        # HTTP headers for authorization\n        headers = {\n            \"Authorization\": f\"Bearer {self.huggingfacehub_api_token}\",\n            \"Content-Type\": \"application/json\",\n        }\n        # send request\n        try:\n            response = requests.post(\n                self.endpoint_url, headers=headers, json=parameter_payload\n            )\n        except requests.exceptions.RequestException as e:  # This is the correct syntax\n            raise ValueError(f\"Error raised by inference endpoint: {e}\")\n        generated_text = response.json()\n        if \"error\" in generated_text:\n            raise ValueError(\n                f\"Error raised by inference API: {generated_text['error']}\"\n            )\n        if self.task == \"text-generation\":\n            text = generated_text[0][\"generated_text\"]\n            # Remove prompt if included in generated text.\n            if text.startswith(prompt):\n                text = text[len(prompt) :]\n        elif self.task == \"text2text-generation\":\n            text = generated_text[0][\"generated_text\"]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html"}
{"id": "d6d7968870bb-3", "text": "text = generated_text[0][\"generated_text\"]\n        elif self.task == \"summarization\":\n            text = generated_text[0][\"summary_text\"]\n        else:\n            raise ValueError(\n                f\"Got invalid task {self.task}, \"\n                f\"currently only {VALID_TASKS} are supported\"\n            )\n        if stop is not None:\n            # This is a bit hacky, but I can't figure out a better way to enforce\n            # stop tokens when making calls to huggingface_hub.\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html"}
{"id": "906298c27593-0", "text": "Source code for langchain.llms.databricks\nimport os\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Callable, Dict, List, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import (\n    BaseModel,\n    Extra,\n    Field,\n    PrivateAttr,\n    root_validator,\n    validator,\n)\n__all__ = [\"Databricks\"]\nclass _DatabricksClientBase(BaseModel, ABC):\n    \"\"\"A base JSON API client that talks to Databricks.\"\"\"\n    api_url: str\n    api_token: str\n    def post_raw(self, request: Any) -> Any:\n        headers = {\"Authorization\": f\"Bearer {self.api_token}\"}\n        response = requests.post(self.api_url, headers=headers, json=request)\n        # TODO: error handling and automatic retries\n        if not response.ok:\n            raise ValueError(f\"HTTP {response.status_code} error: {response.text}\")\n        return response.json()\n    @abstractmethod\n    def post(self, request: Any) -> Any:\n        ...\nclass _DatabricksServingEndpointClient(_DatabricksClientBase):\n    \"\"\"An API client that talks to a Databricks serving endpoint.\"\"\"\n    host: str\n    endpoint_name: str\n    @root_validator(pre=True)\n    def set_api_url(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        if \"api_url\" not in values:\n            host = values[\"host\"]\n            endpoint_name = values[\"endpoint_name\"]\n            api_url = f\"https://{host}/serving-endpoints/{endpoint_name}/invocations\"\n            values[\"api_url\"] = api_url\n        return values", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html"}
{"id": "906298c27593-1", "text": "values[\"api_url\"] = api_url\n        return values\n    def post(self, request: Any) -> Any:\n        # See https://docs.databricks.com/machine-learning/model-serving/score-model-serving-endpoints.html\n        wrapped_request = {\"dataframe_records\": [request]}\n        response = self.post_raw(wrapped_request)[\"predictions\"]\n        # For a single-record query, the result is not a list.\n        if isinstance(response, list):\n            response = response[0]\n        return response\nclass _DatabricksClusterDriverProxyClient(_DatabricksClientBase):\n    \"\"\"An API client that talks to a Databricks cluster driver proxy app.\"\"\"\n    host: str\n    cluster_id: str\n    cluster_driver_port: str\n    @root_validator(pre=True)\n    def set_api_url(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        if \"api_url\" not in values:\n            host = values[\"host\"]\n            cluster_id = values[\"cluster_id\"]\n            port = values[\"cluster_driver_port\"]\n            api_url = f\"https://{host}/driver-proxy-api/o/0/{cluster_id}/{port}\"\n            values[\"api_url\"] = api_url\n        return values\n    def post(self, request: Any) -> Any:\n        return self.post_raw(request)\n[docs]def get_repl_context() -> Any:\n    \"\"\"Gets the notebook REPL context if running inside a Databricks notebook.\n    Returns None otherwise.\n    \"\"\"\n    try:\n        from dbruntime.databricks_repl_context import get_context\n        return get_context()\n    except ImportError:\n        raise ImportError(\n            \"Cannot access dbruntime, not running inside a Databricks notebook.\"\n        )\n[docs]def get_default_host() -> str:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html"}
{"id": "906298c27593-2", "text": ")\n[docs]def get_default_host() -> str:\n    \"\"\"Gets the default Databricks workspace hostname.\n    Raises an error if the hostname cannot be automatically determined.\n    \"\"\"\n    host = os.getenv(\"DATABRICKS_HOST\")\n    if not host:\n        try:\n            host = get_repl_context().browserHostName\n            if not host:\n                raise ValueError(\"context doesn't contain browserHostName.\")\n        except Exception as e:\n            raise ValueError(\n                \"host was not set and cannot be automatically inferred. Set \"\n                f\"environment variable 'DATABRICKS_HOST'. Received error: {e}\"\n            )\n    # TODO: support Databricks CLI profile\n    host = host.lstrip(\"https://\").lstrip(\"http://\").rstrip(\"/\")\n    return host\n[docs]def get_default_api_token() -> str:\n    \"\"\"Gets the default Databricks personal access token.\n    Raises an error if the token cannot be automatically determined.\n    \"\"\"\n    if api_token := os.getenv(\"DATABRICKS_TOKEN\"):\n        return api_token\n    try:\n        api_token = get_repl_context().apiToken\n        if not api_token:\n            raise ValueError(\"context doesn't contain apiToken.\")\n    except Exception as e:\n        raise ValueError(\n            \"api_token was not set and cannot be automatically inferred. Set \"\n            f\"environment variable 'DATABRICKS_TOKEN'. Received error: {e}\"\n        )\n    # TODO: support Databricks CLI profile\n    return api_token\n[docs]class Databricks(LLM):\n    \"\"\"Databricks serving endpoint or a cluster driver proxy app for LLM.\n    It supports two endpoint types:\n    * **Serving endpoint** (recommended for both production and development).", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html"}
{"id": "906298c27593-3", "text": "* **Serving endpoint** (recommended for both production and development).\n      We assume that an LLM was registered and deployed to a serving endpoint.\n      To wrap it as an LLM you must have \"Can Query\" permission to the endpoint.\n      Set ``endpoint_name`` accordingly and do not set ``cluster_id`` and\n      ``cluster_driver_port``.\n      The expected model signature is:\n      * inputs::\n          [{\"name\": \"prompt\", \"type\": \"string\"},\n           {\"name\": \"stop\", \"type\": \"list[string]\"}]\n      * outputs: ``[{\"type\": \"string\"}]``\n    * **Cluster driver proxy app** (recommended for interactive development).\n      One can load an LLM on a Databricks interactive cluster and start a local HTTP\n      server on the driver node to serve the model at ``/`` using HTTP POST method\n      with JSON input/output.\n      Please use a port number between ``[3000, 8000]`` and let the server listen to\n      the driver IP address or simply ``0.0.0.0`` instead of localhost only.\n      To wrap it as an LLM you must have \"Can Attach To\" permission to the cluster.\n      Set ``cluster_id`` and ``cluster_driver_port`` and do not set ``endpoint_name``.\n      The expected server schema (using JSON schema) is:\n      * inputs::\n          {\"type\": \"object\",\n           \"properties\": {\n              \"prompt\": {\"type\": \"string\"},\n              \"stop\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}},\n           \"required\": [\"prompt\"]}`\n      * outputs: ``{\"type\": \"string\"}``\n    If the endpoint model signature is different or you want to set extra params,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html"}
{"id": "906298c27593-4", "text": "If the endpoint model signature is different or you want to set extra params,\n    you can use `transform_input_fn` and `transform_output_fn` to apply necessary\n    transformations before and after the query.\n    \"\"\"\n    host: str = Field(default_factory=get_default_host)\n    \"\"\"Databricks workspace hostname.\n    If not provided, the default value is determined by\n    * the ``DATABRICKS_HOST`` environment variable if present, or\n    * the hostname of the current Databricks workspace if running inside\n      a Databricks notebook attached to an interactive cluster in \"single user\"\n      or \"no isolation shared\" mode.\n    \"\"\"\n    api_token: str = Field(default_factory=get_default_api_token)\n    \"\"\"Databricks personal access token.\n    If not provided, the default value is determined by\n    * the ``DATABRICKS_TOKEN`` environment variable if present, or\n    * an automatically generated temporary token if running inside a Databricks\n      notebook attached to an interactive cluster in \"single user\" or\n      \"no isolation shared\" mode.\n    \"\"\"\n    endpoint_name: Optional[str] = None\n    \"\"\"Name of the model serving endpoint.\n    You must specify the endpoint name to connect to a model serving endpoint.\n    You must not set both ``endpoint_name`` and ``cluster_id``.\n    \"\"\"\n    cluster_id: Optional[str] = None\n    \"\"\"ID of the cluster if connecting to a cluster driver proxy app.\n    If neither ``endpoint_name`` nor ``cluster_id`` is not provided and the code runs\n    inside a Databricks notebook attached to an interactive cluster in \"single user\"\n    or \"no isolation shared\" mode, the current cluster ID is used as default.\n    You must not set both ``endpoint_name`` and ``cluster_id``.\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html"}
{"id": "906298c27593-5", "text": "You must not set both ``endpoint_name`` and ``cluster_id``.\n    \"\"\"\n    cluster_driver_port: Optional[str] = None\n    \"\"\"The port number used by the HTTP server running on the cluster driver node.\n    The server should listen on the driver IP address or simply ``0.0.0.0`` to connect.\n    We recommend the server using a port number between ``[3000, 8000]``.\n    \"\"\"\n    model_kwargs: Optional[Dict[str, Any]] = None\n    \"\"\"Extra parameters to pass to the endpoint.\"\"\"\n    transform_input_fn: Optional[Callable] = None\n    \"\"\"A function that transforms ``{prompt, stop, **kwargs}`` into a JSON-compatible\n    request object that the endpoint accepts.\n    For example, you can apply a prompt template to the input prompt.\n    \"\"\"\n    transform_output_fn: Optional[Callable[..., str]] = None\n    \"\"\"A function that transforms the output from the endpoint to the generated text.\n    \"\"\"\n    _client: _DatabricksClientBase = PrivateAttr()\n    class Config:\n        extra = Extra.forbid\n        underscore_attrs_are_private = True\n    @validator(\"cluster_id\", always=True)\n    def set_cluster_id(cls, v: Any, values: Dict[str, Any]) -> Optional[str]:\n        if v and values[\"endpoint_name\"]:\n            raise ValueError(\"Cannot set both endpoint_name and cluster_id.\")\n        elif values[\"endpoint_name\"]:\n            return None\n        elif v:\n            return v\n        else:\n            try:\n                if v := get_repl_context().clusterId:\n                    return v\n                raise ValueError(\"Context doesn't contain clusterId.\")\n            except Exception as e:\n                raise ValueError(\n                    \"Neither endpoint_name nor cluster_id was set. \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html"}
{"id": "906298c27593-6", "text": "raise ValueError(\n                    \"Neither endpoint_name nor cluster_id was set. \"\n                    \"And the cluster_id cannot be automatically determined. Received\"\n                    f\" error: {e}\"\n                )\n    @validator(\"cluster_driver_port\", always=True)\n    def set_cluster_driver_port(cls, v: Any, values: Dict[str, Any]) -> Optional[str]:\n        if v and values[\"endpoint_name\"]:\n            raise ValueError(\"Cannot set both endpoint_name and cluster_driver_port.\")\n        elif values[\"endpoint_name\"]:\n            return None\n        elif v is None:\n            raise ValueError(\n                \"Must set cluster_driver_port to connect to a cluster driver.\"\n            )\n        elif int(v) <= 0:\n            raise ValueError(f\"Invalid cluster_driver_port: {v}\")\n        else:\n            return v\n    @validator(\"model_kwargs\", always=True)\n    def set_model_kwargs(cls, v: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:\n        if v:\n            assert \"prompt\" not in v, \"model_kwargs must not contain key 'prompt'\"\n            assert \"stop\" not in v, \"model_kwargs must not contain key 'stop'\"\n        return v\n    def __init__(self, **data: Any):\n        super().__init__(**data)\n        if self.endpoint_name:\n            self._client = _DatabricksServingEndpointClient(\n                host=self.host,\n                api_token=self.api_token,\n                endpoint_name=self.endpoint_name,\n            )\n        elif self.cluster_id and self.cluster_driver_port:\n            self._client = _DatabricksClusterDriverProxyClient(\n                host=self.host,\n                api_token=self.api_token,\n                cluster_id=self.cluster_id,\n                cluster_driver_port=self.cluster_driver_port,\n            )\n        else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html"}
{"id": "906298c27593-7", "text": "cluster_driver_port=self.cluster_driver_port,\n            )\n        else:\n            raise ValueError(\n                \"Must specify either endpoint_name or cluster_id/cluster_driver_port.\"\n            )\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"databricks\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Queries the LLM endpoint with the given prompt and stop sequence.\"\"\"\n        # TODO: support callbacks\n        request = {\"prompt\": prompt, \"stop\": stop}\n        request.update(kwargs)\n        if self.model_kwargs:\n            request.update(self.model_kwargs)\n        if self.transform_input_fn:\n            request = self.transform_input_fn(**request)\n        response = self._client.post(request)\n        if self.transform_output_fn:\n            response = self.transform_output_fn(response)\n        return response", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html"}
{"id": "b466c108fddb-0", "text": "Source code for langchain.llms.openlm\nfrom typing import Any, Dict\nfrom langchain.llms.openai import BaseOpenAI\nfrom langchain.pydantic_v1 import root_validator\n[docs]class OpenLM(BaseOpenAI):\n    \"\"\"OpenLM models.\"\"\"\n    @property\n    def _invocation_params(self) -> Dict[str, Any]:\n        return {**{\"model\": self.model_name}, **super()._invocation_params}\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        try:\n            import openlm\n            values[\"client\"] = openlm.Completion\n        except ImportError:\n            raise ImportError(\n                \"Could not import openlm python package. \"\n                \"Please install it with `pip install openlm`.\"\n            )\n        if values[\"streaming\"]:\n            raise ValueError(\"Streaming not supported with openlm\")\n        return values", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openlm.html"}
{"id": "27c523d08f3a-0", "text": "Source code for langchain.llms.pipelineai\nimport logging\nfrom typing import Any, Dict, List, Mapping, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class PipelineAI(LLM, BaseModel):\n    \"\"\"PipelineAI large language models.\n    To use, you should have the ``pipeline-ai`` python package installed,\n    and the environment variable ``PIPELINE_API_KEY`` set with your API key.\n    Any parameters that are valid to be passed to the call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.llms import PipelineAI\n            pipeline = PipelineAI(pipeline_key=\"\")\n    \"\"\"\n    pipeline_key: str = \"\"\n    \"\"\"The id or tag of the target pipeline\"\"\"\n    pipeline_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any pipeline parameters valid for `create` call not\n    explicitly specified.\"\"\"\n    pipeline_api_key: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic config.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = {field.alias for field in cls.__fields__.values()}\n        extra = values.get(\"pipeline_kwargs\", {})\n        for field_name in list(values):\n            if field_name not in all_required_field_names:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html"}
{"id": "27c523d08f3a-1", "text": "if field_name not in all_required_field_names:\n                if field_name in extra:\n                    raise ValueError(f\"Found {field_name} supplied twice.\")\n                logger.warning(\n                    f\"\"\"{field_name} was transferred to pipeline_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        values[\"pipeline_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        pipeline_api_key = get_from_dict_or_env(\n            values, \"pipeline_api_key\", \"PIPELINE_API_KEY\"\n        )\n        values[\"pipeline_api_key\"] = pipeline_api_key\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"pipeline_key\": self.pipeline_key},\n            **{\"pipeline_kwargs\": self.pipeline_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"pipeline_ai\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call to Pipeline Cloud endpoint.\"\"\"\n        try:\n            from pipeline import PipelineCloud\n        except ImportError:\n            raise ImportError(\n                \"Could not import pipeline-ai python package. \"\n                \"Please install it with `pip install pipeline-ai`.\"\n            )\n        client = PipelineCloud(token=self.pipeline_api_key)", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html"}
{"id": "27c523d08f3a-2", "text": ")\n        client = PipelineCloud(token=self.pipeline_api_key)\n        params = self.pipeline_kwargs or {}\n        params = {**params, **kwargs}\n        run = client.run_pipeline(self.pipeline_key, [prompt, params])\n        try:\n            text = run.result_preview[0][0]\n        except AttributeError:\n            raise AttributeError(\n                f\"A pipeline run should have a `result_preview` attribute.\"\n                f\"Run was: {run}\"\n            )\n        if stop is not None:\n            # I believe this is required since the stop tokens\n            # are not enforced by the pipeline parameters\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html"}
{"id": "87313c360275-0", "text": "Source code for langchain.llms.writer\nfrom typing import Any, Dict, List, Mapping, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.utils import get_from_dict_or_env\n[docs]class Writer(LLM):\n    \"\"\"Writer large language models.\n    To use, you should have the environment variable ``WRITER_API_KEY`` and\n    ``WRITER_ORG_ID`` set with your API key and organization ID respectively.\n    Example:\n        .. code-block:: python\n            from langchain.llms import Writer\n            writer = Writer(model_id=\"palmyra-base\")\n    \"\"\"\n    writer_org_id: Optional[str] = None\n    \"\"\"Writer organization ID.\"\"\"\n    model_id: str = \"palmyra-instruct\"\n    \"\"\"Model name to use.\"\"\"\n    min_tokens: Optional[int] = None\n    \"\"\"Minimum number of tokens to generate.\"\"\"\n    max_tokens: Optional[int] = None\n    \"\"\"Maximum number of tokens to generate.\"\"\"\n    temperature: Optional[float] = None\n    \"\"\"What sampling temperature to use.\"\"\"\n    top_p: Optional[float] = None\n    \"\"\"Total probability mass of tokens to consider at each step.\"\"\"\n    stop: Optional[List[str]] = None\n    \"\"\"Sequences when completion generation will stop.\"\"\"\n    presence_penalty: Optional[float] = None\n    \"\"\"Penalizes repeated tokens regardless of frequency.\"\"\"\n    repetition_penalty: Optional[float] = None\n    \"\"\"Penalizes repeated tokens according to frequency.\"\"\"\n    best_of: Optional[int] = None\n    \"\"\"Generates this many completions server-side and returns the \"best\".\"\"\"\n    logprobs: bool = False", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html"}
{"id": "87313c360275-1", "text": "logprobs: bool = False\n    \"\"\"Whether to return log probabilities.\"\"\"\n    n: Optional[int] = None\n    \"\"\"How many completions to generate.\"\"\"\n    writer_api_key: Optional[str] = None\n    \"\"\"Writer API key.\"\"\"\n    base_url: Optional[str] = None\n    \"\"\"Base url to use, if None decides based on model name.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and organization id exist in environment.\"\"\"\n        writer_api_key = get_from_dict_or_env(\n            values, \"writer_api_key\", \"WRITER_API_KEY\"\n        )\n        values[\"writer_api_key\"] = writer_api_key\n        writer_org_id = get_from_dict_or_env(values, \"writer_org_id\", \"WRITER_ORG_ID\")\n        values[\"writer_org_id\"] = writer_org_id\n        return values\n    @property\n    def _default_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the default parameters for calling Writer API.\"\"\"\n        return {\n            \"minTokens\": self.min_tokens,\n            \"maxTokens\": self.max_tokens,\n            \"temperature\": self.temperature,\n            \"topP\": self.top_p,\n            \"stop\": self.stop,\n            \"presencePenalty\": self.presence_penalty,\n            \"repetitionPenalty\": self.repetition_penalty,\n            \"bestOf\": self.best_of,\n            \"logprobs\": self.logprobs,\n            \"n\": self.n,\n        }\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html"}
{"id": "87313c360275-2", "text": "\"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"model_id\": self.model_id, \"writer_org_id\": self.writer_org_id},\n            **self._default_params,\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"writer\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to Writer's completions endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = Writer(\"Tell me a joke.\")\n        \"\"\"\n        if self.base_url is not None:\n            base_url = self.base_url\n        else:\n            base_url = (\n                \"https://enterprise-api.writer.com/llm\"\n                f\"/organization/{self.writer_org_id}\"\n                f\"/model/{self.model_id}/completions\"\n            )\n        params = {**self._default_params, **kwargs}\n        response = requests.post(\n            url=base_url,\n            headers={\n                \"Authorization\": f\"{self.writer_api_key}\",\n                \"Content-Type\": \"application/json\",\n                \"Accept\": \"application/json\",\n            },\n            json={\"prompt\": prompt, **params},\n        )\n        text = response.text\n        if stop is not None:\n            # I believe this is required since the stop tokens\n            # are not enforced by the model parameters", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html"}
{"id": "87313c360275-3", "text": "# are not enforced by the model parameters\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html"}
{"id": "7a120056efaa-0", "text": "Source code for langchain.llms.ollama\nimport json\nfrom typing import Any, Dict, Iterator, List, Mapping, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import BaseLLM\nfrom langchain.pydantic_v1 import Extra\nfrom langchain.schema import LLMResult\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.schema.output import GenerationChunk\ndef _stream_response_to_generation_chunk(\n    stream_response: str,\n) -> GenerationChunk:\n    \"\"\"Convert a stream response to a generation chunk.\"\"\"\n    parsed_response = json.loads(stream_response)\n    generation_info = parsed_response if parsed_response.get(\"done\") is True else None\n    return GenerationChunk(\n        text=parsed_response.get(\"response\", \"\"), generation_info=generation_info\n    )\nclass _OllamaCommon(BaseLanguageModel):\n    base_url: str = \"http://localhost:11434\"\n    \"\"\"Base url the model is hosted under.\"\"\"\n    model: str = \"llama2\"\n    \"\"\"Model name to use.\"\"\"\n    mirostat: Optional[int] = None\n    \"\"\"Enable Mirostat sampling for controlling perplexity.\n    (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\"\"\"\n    mirostat_eta: Optional[float] = None\n    \"\"\"Influences how quickly the algorithm responds to feedback\n    from the generated text. A lower learning rate will result in\n    slower adjustments, while a higher learning rate will make\n    the algorithm more responsive. (Default: 0.1)\"\"\"\n    mirostat_tau: Optional[float] = None\n    \"\"\"Controls the balance between coherence and diversity\n    of the output. A lower value will result in more focused and", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html"}
{"id": "7a120056efaa-1", "text": "of the output. A lower value will result in more focused and\n    coherent text. (Default: 5.0)\"\"\"\n    num_ctx: Optional[int] = None\n    \"\"\"Sets the size of the context window used to generate the\n    next token. (Default: 2048)\t\"\"\"\n    num_gpu: Optional[int] = None\n    \"\"\"The number of GPUs to use. On macOS it defaults to 1 to\n    enable metal support, 0 to disable.\"\"\"\n    num_thread: Optional[int] = None\n    \"\"\"Sets the number of threads to use during computation.\n    By default, Ollama will detect this for optimal performance.\n    It is recommended to set this value to the number of physical\n    CPU cores your system has (as opposed to the logical number of cores).\"\"\"\n    repeat_last_n: Optional[int] = None\n    \"\"\"Sets how far back for the model to look back to prevent\n    repetition. (Default: 64, 0 = disabled, -1 = num_ctx)\"\"\"\n    repeat_penalty: Optional[float] = None\n    \"\"\"Sets how strongly to penalize repetitions. A higher value (e.g., 1.5)\n    will penalize repetitions more strongly, while a lower value (e.g., 0.9)\n    will be more lenient. (Default: 1.1)\"\"\"\n    temperature: Optional[float] = None\n    \"\"\"The temperature of the model. Increasing the temperature will\n    make the model answer more creatively. (Default: 0.8)\"\"\"\n    stop: Optional[List[str]] = None\n    \"\"\"Sets the stop tokens to use.\"\"\"\n    tfs_z: Optional[float] = None\n    \"\"\"Tail free sampling is used to reduce the impact of less probable", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html"}
{"id": "7a120056efaa-2", "text": "\"\"\"Tail free sampling is used to reduce the impact of less probable\n    tokens from the output. A higher value (e.g., 2.0) will reduce the\n    impact more, while a value of 1.0 disables this setting. (default: 1)\"\"\"\n    top_k: Optional[int] = None\n    \"\"\"Reduces the probability of generating nonsense. A higher value (e.g. 100)\n    will give more diverse answers, while a lower value (e.g. 10)\n    will be more conservative. (Default: 40)\"\"\"\n    top_p: Optional[int] = None\n    \"\"\"Works together with top-k. A higher value (e.g., 0.95) will lead\n    to more diverse text, while a lower value (e.g., 0.5) will\n    generate more focused and conservative text. (Default: 0.9)\"\"\"\n    system: Optional[str] = None\n    \"\"\"system prompt (overrides what is defined in the Modelfile)\"\"\"\n    template: Optional[str] = None\n    \"\"\"full prompt or prompt template (overrides what is defined in the Modelfile)\"\"\"\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling Ollama.\"\"\"\n        return {\n            \"model\": self.model,\n            \"options\": {\n                \"mirostat\": self.mirostat,\n                \"mirostat_eta\": self.mirostat_eta,\n                \"mirostat_tau\": self.mirostat_tau,\n                \"num_ctx\": self.num_ctx,\n                \"num_gpu\": self.num_gpu,\n                \"num_thread\": self.num_thread,\n                \"repeat_last_n\": self.repeat_last_n,\n                \"repeat_penalty\": self.repeat_penalty,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html"}
{"id": "7a120056efaa-3", "text": "\"repeat_penalty\": self.repeat_penalty,\n                \"temperature\": self.temperature,\n                \"stop\": self.stop,\n                \"tfs_z\": self.tfs_z,\n                \"top_k\": self.top_k,\n                \"top_p\": self.top_p,\n            },\n            \"system\": self.system,\n            \"template\": self.template,\n        }\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model\": self.model}, **self._default_params}\n    def _create_stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        **kwargs: Any,\n    ) -> Iterator[str]:\n        if self.stop is not None and stop is not None:\n            raise ValueError(\"`stop` found in both the input and default params.\")\n        elif self.stop is not None:\n            stop = self.stop\n        elif stop is None:\n            stop = []\n        params = self._default_params\n        if \"model\" in kwargs:\n            params[\"model\"] = kwargs[\"model\"]\n        if \"options\" in kwargs:\n            params[\"options\"] = kwargs[\"options\"]\n        else:\n            params[\"options\"] = {\n                **params[\"options\"],\n                \"stop\": stop,\n                **kwargs,\n            }\n        response = requests.post(\n            url=f\"{self.base_url}/api/generate/\",\n            headers={\"Content-Type\": \"application/json\"},\n            json={\"prompt\": prompt, **params},\n            stream=True,\n        )\n        response.encoding = \"utf-8\"\n        if response.status_code != 200:\n            optional_detail = response.json().get(\"error\")\n            raise ValueError(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html"}
{"id": "7a120056efaa-4", "text": "optional_detail = response.json().get(\"error\")\n            raise ValueError(\n                f\"Ollama call failed with status code {response.status_code}.\"\n                f\" Details: {optional_detail}\"\n            )\n        return response.iter_lines(decode_unicode=True)\n    def _stream_with_aggregation(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        verbose: bool = False,\n        **kwargs: Any,\n    ) -> GenerationChunk:\n        final_chunk: Optional[GenerationChunk] = None\n        for stream_resp in self._create_stream(prompt, stop, **kwargs):\n            if stream_resp:\n                chunk = _stream_response_to_generation_chunk(stream_resp)\n                if final_chunk is None:\n                    final_chunk = chunk\n                else:\n                    final_chunk += chunk\n                if run_manager:\n                    run_manager.on_llm_new_token(\n                        chunk.text,\n                        verbose=verbose,\n                    )\n        if final_chunk is None:\n            raise ValueError(\"No data received from Ollama stream.\")\n        return final_chunk\n[docs]class Ollama(BaseLLM, _OllamaCommon):\n    \"\"\"Ollama locally runs large language models.\n    To use, follow the instructions at https://ollama.ai/.\n    Example:\n        .. code-block:: python\n            from langchain.llms import Ollama\n            ollama = Ollama(model=\"llama2\")\n    \"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"ollama-llm\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html"}
{"id": "7a120056efaa-5", "text": "\"\"\"Return type of llm.\"\"\"\n        return \"ollama-llm\"\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Call out to Ollama's generate endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = ollama(\"Tell me a joke.\")\n        \"\"\"\n        # TODO: add caching here.\n        generations = []\n        for prompt in prompts:\n            final_chunk = super()._stream_with_aggregation(\n                prompt,\n                stop=stop,\n                run_manager=run_manager,\n                verbose=self.verbose,\n                **kwargs,\n            )\n            generations.append([final_chunk])\n        return LLMResult(generations=generations)\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        for stream_resp in self._create_stream(prompt, stop, **kwargs):\n            if stream_resp:\n                chunk = _stream_response_to_generation_chunk(stream_resp)\n                yield chunk\n                if run_manager:\n                    run_manager.on_llm_new_token(\n                        chunk.text,\n                        verbose=self.verbose,\n                    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html"}
{"id": "9859d0efff2b-0", "text": "Source code for langchain.llms.edenai\n\"\"\"Wrapper around EdenAI's Generation API.\"\"\"\nimport logging\nfrom typing import Any, Dict, List, Literal, Optional\nfrom aiohttp import ClientSession\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.utilities.requests import Requests\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class EdenAI(LLM):\n    \"\"\"Wrapper around edenai models.\n    To use, you should have\n    the environment variable ``EDENAI_API_KEY`` set with your API token.\n    You can find your token here: https://app.edenai.run/admin/account/settings\n    `feature` and `subfeature` are required, but any other model parameters can also be\n    passed in with the format params={model_param: value, ...}\n    for api reference check edenai documentation: http://docs.edenai.co.\n    \"\"\"\n    base_url: str = \"https://api.edenai.run/v2\"\n    edenai_api_key: Optional[str] = None\n    feature: Literal[\"text\", \"image\"] = \"text\"\n    \"\"\"Which generative feature to use, use text by default\"\"\"\n    subfeature: Literal[\"generation\"] = \"generation\"\n    \"\"\"Subfeature of above feature, use generation by default\"\"\"\n    provider: str\n    \"\"\"Generative provider to use (eg: openai,stabilityai,cohere,google etc.)\"\"\"\n    model: Optional[str] = None\n    \"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/edenai.html"}
{"id": "9859d0efff2b-1", "text": "model: Optional[str] = None\n    \"\"\"\n    model name for above provider (eg: 'text-davinci-003' for openai)\n    available models are shown on https://docs.edenai.co/ under 'available providers'\n    \"\"\"\n    # Optional parameters to add depending of chosen feature\n    # see api reference for more infos\n    temperature: Optional[float] = Field(default=None, ge=0, le=1)  # for text\n    max_tokens: Optional[int] = Field(default=None, ge=0)  # for text\n    resolution: Optional[Literal[\"256x256\", \"512x512\", \"1024x1024\"]] = None  # for image\n    params: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"\n    DEPRECATED: use temperature, max_tokens, resolution directly\n    optional parameters to pass to api\n    \"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"extra parameters\"\"\"\n    stop_sequences: Optional[List[str]] = None\n    \"\"\"Stop sequences to use.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key exists in environment.\"\"\"\n        values[\"edenai_api_key\"] = get_from_dict_or_env(\n            values, \"edenai_api_key\", \"EDENAI_API_KEY\"\n        )\n        return values\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = {field.alias for field in cls.__fields__.values()}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/edenai.html"}
{"id": "9859d0efff2b-2", "text": "all_required_field_names = {field.alias for field in cls.__fields__.values()}\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name not in all_required_field_names:\n                if field_name in extra:\n                    raise ValueError(f\"Found {field_name} supplied twice.\")\n                logger.warning(\n                    f\"\"\"{field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        values[\"model_kwargs\"] = extra\n        return values\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of model.\"\"\"\n        return \"edenai\"\n    def _format_output(self, output: dict) -> str:\n        if self.feature == \"text\":\n            return output[self.provider][\"generated_text\"]\n        else:\n            return output[self.provider][\"items\"][0][\"image\"]\n[docs]    @staticmethod\n    def get_user_agent() -> str:\n        from langchain import __version__\n        return f\"langchain/{__version__}\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to EdenAI's text generation endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n        Returns:\n            json formatted str response.\n        \"\"\"\n        stops = None\n        if self.stop_sequences is not None and stop is not None:\n            raise ValueError(\n                \"stop sequences found in both the input and default params.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/edenai.html"}
{"id": "9859d0efff2b-3", "text": "\"stop sequences found in both the input and default params.\"\n            )\n        elif self.stop_sequences is not None:\n            stops = self.stop_sequences\n        else:\n            stops = stop\n        url = f\"{self.base_url}/{self.feature}/{self.subfeature}\"\n        headers = {\n            \"Authorization\": f\"Bearer {self.edenai_api_key}\",\n            \"User-Agent\": self.get_user_agent(),\n        }\n        payload: Dict[str, Any] = {\n            \"providers\": self.provider,\n            \"text\": prompt,\n            \"max_tokens\": self.max_tokens,\n            \"temperature\": self.temperature,\n            \"resolution\": self.resolution,\n            **self.params,\n            **kwargs,\n            \"num_images\": 1,  # always limit to 1 (ignored for text)\n        }\n        # filter None values to not pass them to the http payload\n        payload = {k: v for k, v in payload.items() if v is not None}\n        if self.model is not None:\n            payload[\"settings\"] = {self.provider: self.model}\n        request = Requests(headers=headers)\n        response = request.post(url=url, data=payload)\n        if response.status_code >= 500:\n            raise Exception(f\"EdenAI Server: Error {response.status_code}\")\n        elif response.status_code >= 400:\n            raise ValueError(f\"EdenAI received an invalid payload: {response.text}\")\n        elif response.status_code != 200:\n            raise Exception(\n                f\"EdenAI returned an unexpected response with status \"\n                f\"{response.status_code}: {response.text}\"\n            )\n        data = response.json()\n        provider_response = data[self.provider]\n        if provider_response.get(\"status\") == \"fail\":", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/edenai.html"}
{"id": "9859d0efff2b-4", "text": "if provider_response.get(\"status\") == \"fail\":\n            err_msg = provider_response.get(\"error\", {}).get(\"message\")\n            raise Exception(err_msg)\n        output = self._format_output(data)\n        if stops is not None:\n            output = enforce_stop_tokens(output, stops)\n        return output\n    async def _acall(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call EdenAi model to get predictions based on the prompt.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: A list of stop words (optional).\n            run_manager: A callback manager for async interaction with LLMs.\n        Returns:\n            The string generated by the model.\n        \"\"\"\n        stops = None\n        if self.stop_sequences is not None and stop is not None:\n            raise ValueError(\n                \"stop sequences found in both the input and default params.\"\n            )\n        elif self.stop_sequences is not None:\n            stops = self.stop_sequences\n        else:\n            stops = stop\n        url = f\"{self.base_url}/{self.feature}/{self.subfeature}\"\n        headers = {\n            \"Authorization\": f\"Bearer {self.edenai_api_key}\",\n            \"User-Agent\": self.get_user_agent(),\n        }\n        payload: Dict[str, Any] = {\n            \"providers\": self.provider,\n            \"text\": prompt,\n            \"max_tokens\": self.max_tokens,\n            \"temperature\": self.temperature,\n            \"resolution\": self.resolution,\n            **self.params,\n            **kwargs,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/edenai.html"}
{"id": "9859d0efff2b-5", "text": "\"resolution\": self.resolution,\n            **self.params,\n            **kwargs,\n            \"num_images\": 1,  # always limit to 1 (ignored for text)\n        }\n        # filter `None` values to not pass them to the http payload as null\n        payload = {k: v for k, v in payload.items() if v is not None}\n        if self.model is not None:\n            payload[\"settings\"] = {self.provider: self.model}\n        async with ClientSession() as session:\n            async with session.post(url, json=payload, headers=headers) as response:\n                if response.status >= 500:\n                    raise Exception(f\"EdenAI Server: Error {response.status}\")\n                elif response.status >= 400:\n                    raise ValueError(\n                        f\"EdenAI received an invalid payload: {response.text}\"\n                    )\n                elif response.status != 200:\n                    raise Exception(\n                        f\"EdenAI returned an unexpected response with status \"\n                        f\"{response.status}: {response.text}\"\n                    )\n                response_json = await response.json()\n                provider_response = response_json[self.provider]\n                if provider_response.get(\"status\") == \"fail\":\n                    err_msg = provider_response.get(\"error\", {}).get(\"message\")\n                    raise Exception(err_msg)\n                output = self._format_output(response_json)\n                if stops is not None:\n                    output = enforce_stop_tokens(output, stops)\n                return output", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/edenai.html"}
{"id": "946006102fcb-0", "text": "Source code for langchain.llms.gpt4all\nfrom functools import partial\nfrom typing import Any, Dict, List, Mapping, Optional, Set\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\n[docs]class GPT4All(LLM):\n    \"\"\"GPT4All language models.\n    To use, you should have the ``gpt4all`` python package installed, the\n    pre-trained model file, and the model's config information.\n    Example:\n        .. code-block:: python\n            from langchain.llms import GPT4All\n            model = GPT4All(model=\"./models/gpt4all-model.bin\", n_threads=8)\n            # Simplest invocation\n            response = model(\"Once upon a time, \")\n    \"\"\"\n    model: str\n    \"\"\"Path to the pre-trained GPT4All model file.\"\"\"\n    backend: Optional[str] = Field(None, alias=\"backend\")\n    max_tokens: int = Field(200, alias=\"max_tokens\")\n    \"\"\"Token context window.\"\"\"\n    n_parts: int = Field(-1, alias=\"n_parts\")\n    \"\"\"Number of parts to split the model into. \n    If -1, the number of parts is automatically determined.\"\"\"\n    seed: int = Field(0, alias=\"seed\")\n    \"\"\"Seed. If -1, a random seed is used.\"\"\"\n    f16_kv: bool = Field(False, alias=\"f16_kv\")\n    \"\"\"Use half-precision for key/value cache.\"\"\"\n    logits_all: bool = Field(False, alias=\"logits_all\")\n    \"\"\"Return logits for all tokens, not just the last token.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html"}
{"id": "946006102fcb-1", "text": "\"\"\"Return logits for all tokens, not just the last token.\"\"\"\n    vocab_only: bool = Field(False, alias=\"vocab_only\")\n    \"\"\"Only load the vocabulary, no weights.\"\"\"\n    use_mlock: bool = Field(False, alias=\"use_mlock\")\n    \"\"\"Force system to keep model in RAM.\"\"\"\n    embedding: bool = Field(False, alias=\"embedding\")\n    \"\"\"Use embedding mode only.\"\"\"\n    n_threads: Optional[int] = Field(4, alias=\"n_threads\")\n    \"\"\"Number of threads to use.\"\"\"\n    n_predict: Optional[int] = 256\n    \"\"\"The maximum number of tokens to generate.\"\"\"\n    temp: Optional[float] = 0.7\n    \"\"\"The temperature to use for sampling.\"\"\"\n    top_p: Optional[float] = 0.1\n    \"\"\"The top-p value to use for sampling.\"\"\"\n    top_k: Optional[int] = 40\n    \"\"\"The top-k value to use for sampling.\"\"\"\n    echo: Optional[bool] = False\n    \"\"\"Whether to echo the prompt.\"\"\"\n    stop: Optional[List[str]] = []\n    \"\"\"A list of strings to stop generation when encountered.\"\"\"\n    repeat_last_n: Optional[int] = 64\n    \"Last n tokens to penalize\"\n    repeat_penalty: Optional[float] = 1.18\n    \"\"\"The penalty to apply to repeated tokens.\"\"\"\n    n_batch: int = Field(8, alias=\"n_batch\")\n    \"\"\"Batch size for prompt processing.\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results or not.\"\"\"\n    allow_download: bool = False\n    \"\"\"If model does not exist in ~/.cache/gpt4all/, download it.\"\"\"\n    device: Optional[str] = Field(\"cpu\", alias=\"device\")", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html"}
{"id": "946006102fcb-2", "text": "device: Optional[str] = Field(\"cpu\", alias=\"device\")\n    \"\"\"Device name: cpu, gpu, nvidia, intel, amd or DeviceName.\"\"\"\n    client: Any = None  #: :meta private:\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @staticmethod\n    def _model_param_names() -> Set[str]:\n        return {\n            \"max_tokens\",\n            \"n_predict\",\n            \"top_k\",\n            \"top_p\",\n            \"temp\",\n            \"n_batch\",\n            \"repeat_penalty\",\n            \"repeat_last_n\",\n        }\n    def _default_params(self) -> Dict[str, Any]:\n        return {\n            \"max_tokens\": self.max_tokens,\n            \"n_predict\": self.n_predict,\n            \"top_k\": self.top_k,\n            \"top_p\": self.top_p,\n            \"temp\": self.temp,\n            \"n_batch\": self.n_batch,\n            \"repeat_penalty\": self.repeat_penalty,\n            \"repeat_last_n\": self.repeat_last_n,\n        }\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that the python package exists in the environment.\"\"\"\n        try:\n            from gpt4all import GPT4All as GPT4AllModel\n        except ImportError:\n            raise ImportError(\n                \"Could not import gpt4all python package. \"\n                \"Please install it with `pip install gpt4all`.\"\n            )\n        full_path = values[\"model\"]\n        model_path, delimiter, model_name = full_path.rpartition(\"/\")\n        model_path += delimiter\n        values[\"client\"] = GPT4AllModel(\n            model_name,\n            model_path=model_path or None,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html"}
{"id": "946006102fcb-3", "text": "model_name,\n            model_path=model_path or None,\n            model_type=values[\"backend\"],\n            allow_download=values[\"allow_download\"],\n            device=values[\"device\"],\n        )\n        if values[\"n_threads\"] is not None:\n            # set n_threads\n            values[\"client\"].model.set_thread_count(values[\"n_threads\"])\n        try:\n            values[\"backend\"] = values[\"client\"].model_type\n        except AttributeError:\n            # The below is for compatibility with GPT4All Python bindings <= 0.2.3.\n            values[\"backend\"] = values[\"client\"].model.model_type\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            \"model\": self.model,\n            **self._default_params(),\n            **{\n                k: v for k, v in self.__dict__.items() if k in self._model_param_names()\n            },\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return the type of llm.\"\"\"\n        return \"gpt4all\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        r\"\"\"Call out to GPT4All's generate method.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: A list of strings to stop generation when encountered.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                prompt = \"Once upon a time, \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html"}
{"id": "946006102fcb-4", "text": ".. code-block:: python\n                prompt = \"Once upon a time, \"\n                response = model(prompt, n_predict=55)\n        \"\"\"\n        text_callback = None\n        if run_manager:\n            text_callback = partial(run_manager.on_llm_new_token, verbose=self.verbose)\n        text = \"\"\n        params = {**self._default_params(), **kwargs}\n        for token in self.client.generate(prompt, **params):\n            if text_callback:\n                text_callback(token)\n            text += token\n        if stop is not None:\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html"}
{"id": "dc417efc9b34-0", "text": "Source code for langchain.llms.openai\nfrom __future__ import annotations\nimport logging\nimport os\nimport sys\nimport warnings\nfrom typing import (\n    AbstractSet,\n    Any,\n    AsyncIterator,\n    Callable,\n    Collection,\n    Dict,\n    Iterator,\n    List,\n    Literal,\n    Mapping,\n    Optional,\n    Set,\n    Tuple,\n    Union,\n)\nfrom langchain.callbacks.manager import (\n    AsyncCallbackManagerForLLMRun,\n    CallbackManagerForLLMRun,\n)\nfrom langchain.llms.base import BaseLLM, create_base_retry_decorator\nfrom langchain.pydantic_v1 import Field, root_validator\nfrom langchain.schema import Generation, LLMResult\nfrom langchain.schema.output import GenerationChunk\nfrom langchain.utils import get_from_dict_or_env, get_pydantic_field_names\nfrom langchain.utils.openai import is_openai_v1\nfrom langchain.utils.utils import build_extra_kwargs\nlogger = logging.getLogger(__name__)\n[docs]def update_token_usage(\n    keys: Set[str], response: Dict[str, Any], token_usage: Dict[str, Any]\n) -> None:\n    \"\"\"Update token usage.\"\"\"\n    _keys_to_use = keys.intersection(response[\"usage\"])\n    for _key in _keys_to_use:\n        if _key not in token_usage:\n            token_usage[_key] = response[\"usage\"][_key]\n        else:\n            token_usage[_key] += response[\"usage\"][_key]\ndef _stream_response_to_generation_chunk(\n    stream_response: Dict[str, Any],\n) -> GenerationChunk:\n    \"\"\"Convert a stream response to a generation chunk.\"\"\"\n    if not stream_response[\"choices\"]:\n        return GenerationChunk(text=\"\")\n    return GenerationChunk(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-1", "text": "return GenerationChunk(text=\"\")\n    return GenerationChunk(\n        text=stream_response[\"choices\"][0][\"text\"],\n        generation_info=dict(\n            finish_reason=stream_response[\"choices\"][0].get(\"finish_reason\", None),\n            logprobs=stream_response[\"choices\"][0].get(\"logprobs\", None),\n        ),\n    )\ndef _update_response(response: Dict[str, Any], stream_response: Dict[str, Any]) -> None:\n    \"\"\"Update response from the stream response.\"\"\"\n    response[\"choices\"][0][\"text\"] += stream_response[\"choices\"][0][\"text\"]\n    response[\"choices\"][0][\"finish_reason\"] = stream_response[\"choices\"][0].get(\n        \"finish_reason\", None\n    )\n    response[\"choices\"][0][\"logprobs\"] = stream_response[\"choices\"][0][\"logprobs\"]\ndef _streaming_response_template() -> Dict[str, Any]:\n    return {\n        \"choices\": [\n            {\n                \"text\": \"\",\n                \"finish_reason\": None,\n                \"logprobs\": None,\n            }\n        ]\n    }\ndef _create_retry_decorator(\n    llm: Union[BaseOpenAI, OpenAIChat],\n    run_manager: Optional[\n        Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]\n    ] = None,\n) -> Callable[[Any], Any]:\n    import openai\n    errors = [\n        openai.error.Timeout,\n        openai.error.APIError,\n        openai.error.APIConnectionError,\n        openai.error.RateLimitError,\n        openai.error.ServiceUnavailableError,\n    ]\n    return create_base_retry_decorator(\n        error_types=errors, max_retries=llm.max_retries, run_manager=run_manager\n    )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-2", "text": ")\n[docs]def completion_with_retry(\n    llm: Union[BaseOpenAI, OpenAIChat],\n    run_manager: Optional[CallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the completion call.\"\"\"\n    if is_openai_v1():\n        return llm.client.create(**kwargs)\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @retry_decorator\n    def _completion_with_retry(**kwargs: Any) -> Any:\n        return llm.client.create(**kwargs)\n    return _completion_with_retry(**kwargs)\n[docs]async def acompletion_with_retry(\n    llm: Union[BaseOpenAI, OpenAIChat],\n    run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n    **kwargs: Any,\n) -> Any:\n    \"\"\"Use tenacity to retry the async completion call.\"\"\"\n    if is_openai_v1():\n        return await llm.async_client.create(**kwargs)\n    retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)\n    @retry_decorator\n    async def _completion_with_retry(**kwargs: Any) -> Any:\n        # Use OpenAI's async api https://github.com/openai/openai-python#async-api\n        return await llm.client.acreate(**kwargs)\n    return await _completion_with_retry(**kwargs)\n[docs]class BaseOpenAI(BaseLLM):\n    \"\"\"Base OpenAI large language model class.\"\"\"\n    @property\n    def lc_secrets(self) -> Dict[str, str]:\n        return {\"openai_api_key\": \"OPENAI_API_KEY\"}\n    @property\n    def lc_attributes(self) -> Dict[str, Any]:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-3", "text": "@property\n    def lc_attributes(self) -> Dict[str, Any]:\n        attributes: Dict[str, Any] = {}\n        if self.openai_api_base:\n            attributes[\"openai_api_base\"] = self.openai_api_base\n        if self.openai_organization:\n            attributes[\"openai_organization\"] = self.openai_organization\n        if self.openai_proxy:\n            attributes[\"openai_proxy\"] = self.openai_proxy\n        return attributes\n[docs]    @classmethod\n    def is_lc_serializable(cls) -> bool:\n        return True\n    client: Any = Field(default=None, exclude=True)  #: :meta private:\n    async_client: Any = Field(default=None, exclude=True)  #: :meta private:\n    model_name: str = Field(default=\"text-davinci-003\", alias=\"model\")\n    \"\"\"Model name to use.\"\"\"\n    temperature: float = 0.7\n    \"\"\"What sampling temperature to use.\"\"\"\n    max_tokens: int = 256\n    \"\"\"The maximum number of tokens to generate in the completion.\n    -1 returns as many tokens as possible given the prompt and\n    the models maximal context size.\"\"\"\n    top_p: float = 1\n    \"\"\"Total probability mass of tokens to consider at each step.\"\"\"\n    frequency_penalty: float = 0\n    \"\"\"Penalizes repeated tokens according to frequency.\"\"\"\n    presence_penalty: float = 0\n    \"\"\"Penalizes repeated tokens.\"\"\"\n    n: int = 1\n    \"\"\"How many completions to generate for each prompt.\"\"\"\n    best_of: int = 1\n    \"\"\"Generates best_of completions server-side and returns the \"best\".\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not explicitly specified.\"\"\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-4", "text": "\"\"\"Holds any model parameters valid for `create` call not explicitly specified.\"\"\"\n    # When updating this to use a SecretStr\n    # Check for classes that derive from this class (as some of them\n    # may assume openai_api_key is a str)\n    openai_api_key: Optional[str] = Field(default=None, alias=\"api_key\")\n    \"\"\"Automatically inferred from env var `OPENAI_API_KEY` if not provided.\"\"\"\n    openai_api_base: Optional[str] = Field(default=None, alias=\"base_url\")\n    \"\"\"Base URL path for API requests, leave blank if not using a proxy or service \n        emulator.\"\"\"\n    openai_organization: Optional[str] = Field(default=None, alias=\"organization\")\n    \"\"\"Automatically inferred from env var `OPENAI_ORG_ID` if not provided.\"\"\"\n    # to support explicit proxy for OpenAI\n    openai_proxy: Optional[str] = None\n    batch_size: int = 20\n    \"\"\"Batch size to use when passing multiple documents to generate.\"\"\"\n    request_timeout: Union[float, Tuple[float, float], Any, None] = Field(\n        default=None, alias=\"timeout\"\n    )\n    \"\"\"Timeout for requests to OpenAI completion API. Can be float, httpx.Timeout or \n        None.\"\"\"\n    logit_bias: Optional[Dict[str, float]] = Field(default_factory=dict)\n    \"\"\"Adjust the probability of specific tokens being generated.\"\"\"\n    max_retries: int = 2\n    \"\"\"Maximum number of retries to make when generating.\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results or not.\"\"\"\n    allowed_special: Union[Literal[\"all\"], AbstractSet[str]] = set()\n    \"\"\"Set of special tokens that are allowed\u3002\"\"\"\n    disallowed_special: Union[Literal[\"all\"], Collection[str]] = \"all\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-5", "text": "disallowed_special: Union[Literal[\"all\"], Collection[str]] = \"all\"\n    \"\"\"Set of special tokens that are not allowed\u3002\"\"\"\n    tiktoken_model_name: Optional[str] = None\n    \"\"\"The model name to pass to tiktoken when using this class. \n    Tiktoken is used to count the number of tokens in documents to constrain \n    them to be under a certain limit. By default, when set to None, this will \n    be the same as the embedding model name. However, there are some cases \n    where you may want to use this Embedding class with a model name not \n    supported by tiktoken. This can include when using Azure embeddings or \n    when using one of the many model providers that expose an OpenAI-like \n    API but with different models. In those cases, in order to avoid erroring \n    when tiktoken is called, you can specify a model name to use here.\"\"\"\n    default_headers: Union[Mapping[str, str], None] = None\n    default_query: Union[Mapping[str, object], None] = None\n    # Configure a custom httpx client. See the\n    # [httpx documentation](https://www.python-httpx.org/api/#client) for more details.\n    http_client: Union[Any, None] = None\n    \"\"\"Optional httpx.Client.\"\"\"\n    def __new__(cls, **data: Any) -> Union[OpenAIChat, BaseOpenAI]:  # type: ignore\n        \"\"\"Initialize the OpenAI object.\"\"\"\n        model_name = data.get(\"model_name\", \"\")\n        if (\n            model_name.startswith(\"gpt-3.5-turbo\") or model_name.startswith(\"gpt-4\")\n        ) and \"-instruct\" not in model_name:\n            warnings.warn(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-6", "text": ") and \"-instruct\" not in model_name:\n            warnings.warn(\n                \"You are trying to use a chat model. This way of initializing it is \"\n                \"no longer supported. Instead, please use: \"\n                \"`from langchain.chat_models import ChatOpenAI`\"\n            )\n            return OpenAIChat(**data)\n        return super().__new__(cls)\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        allow_population_by_field_name = True\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = get_pydantic_field_names(cls)\n        extra = values.get(\"model_kwargs\", {})\n        values[\"model_kwargs\"] = build_extra_kwargs(\n            extra, values, all_required_field_names\n        )\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        if values[\"n\"] < 1:\n            raise ValueError(\"n must be at least 1.\")\n        if values[\"streaming\"] and values[\"n\"] > 1:\n            raise ValueError(\"Cannot stream results when n > 1.\")\n        if values[\"streaming\"] and values[\"best_of\"] > 1:\n            raise ValueError(\"Cannot stream results when best_of > 1.\")\n        values[\"openai_api_key\"] = get_from_dict_or_env(\n            values, \"openai_api_key\", \"OPENAI_API_KEY\"\n        )\n        values[\"openai_api_base\"] = values[\"openai_api_base\"] or os.getenv(\n            \"OPENAI_API_BASE\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-7", "text": "\"OPENAI_API_BASE\"\n        )\n        values[\"openai_proxy\"] = get_from_dict_or_env(\n            values,\n            \"openai_proxy\",\n            \"OPENAI_PROXY\",\n            default=\"\",\n        )\n        values[\"openai_organization\"] = (\n            values[\"openai_organization\"]\n            or os.getenv(\"OPENAI_ORG_ID\")\n            or os.getenv(\"OPENAI_ORGANIZATION\")\n        )\n        try:\n            import openai\n        except ImportError:\n            raise ImportError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\"\n            )\n        if is_openai_v1():\n            client_params = {\n                \"api_key\": values[\"openai_api_key\"],\n                \"organization\": values[\"openai_organization\"],\n                \"base_url\": values[\"openai_api_base\"],\n                \"timeout\": values[\"request_timeout\"],\n                \"max_retries\": values[\"max_retries\"],\n                \"default_headers\": values[\"default_headers\"],\n                \"default_query\": values[\"default_query\"],\n                \"http_client\": values[\"http_client\"],\n            }\n            if not values.get(\"client\"):\n                values[\"client\"] = openai.OpenAI(**client_params).completions\n            if not values.get(\"async_client\"):\n                values[\"async_client\"] = openai.AsyncOpenAI(**client_params).completions\n        elif not values.get(\"client\"):\n            values[\"client\"] = openai.Completion\n        else:\n            pass\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling OpenAI API.\"\"\"\n        normal_params: Dict[str, Any] = {\n            \"temperature\": self.temperature,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-8", "text": "normal_params: Dict[str, Any] = {\n            \"temperature\": self.temperature,\n            \"top_p\": self.top_p,\n            \"frequency_penalty\": self.frequency_penalty,\n            \"presence_penalty\": self.presence_penalty,\n            \"n\": self.n,\n            \"logit_bias\": self.logit_bias,\n        }\n        if self.max_tokens is not None:\n            normal_params[\"max_tokens\"] = self.max_tokens\n        if self.request_timeout is not None and not is_openai_v1():\n            normal_params[\"request_timeout\"] = self.request_timeout\n        # Azure gpt-35-turbo doesn't support best_of\n        # don't specify best_of if it is 1\n        if self.best_of > 1:\n            normal_params[\"best_of\"] = self.best_of\n        return {**normal_params, **self.model_kwargs}\n    def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        params = {**self._invocation_params, **kwargs, \"stream\": True}\n        self.get_sub_prompts(params, [prompt], stop)  # this mutates params\n        for stream_resp in completion_with_retry(\n            self, prompt=prompt, run_manager=run_manager, **params\n        ):\n            if not isinstance(stream_resp, dict):\n                stream_resp = stream_resp.dict()\n            chunk = _stream_response_to_generation_chunk(stream_resp)\n            yield chunk\n            if run_manager:\n                run_manager.on_llm_new_token(\n                    chunk.text,\n                    chunk=chunk,\n                    verbose=self.verbose,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-9", "text": "chunk.text,\n                    chunk=chunk,\n                    verbose=self.verbose,\n                    logprobs=chunk.generation_info[\"logprobs\"]\n                    if chunk.generation_info\n                    else None,\n                )\n    async def _astream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[GenerationChunk]:\n        params = {**self._invocation_params, **kwargs, \"stream\": True}\n        self.get_sub_prompts(params, [prompt], stop)  # this mutate params\n        async for stream_resp in await acompletion_with_retry(\n            self, prompt=prompt, run_manager=run_manager, **params\n        ):\n            if not isinstance(stream_resp, dict):\n                stream_resp = stream_resp.dict()\n            chunk = _stream_response_to_generation_chunk(stream_resp)\n            yield chunk\n            if run_manager:\n                await run_manager.on_llm_new_token(\n                    chunk.text,\n                    chunk=chunk,\n                    verbose=self.verbose,\n                    logprobs=chunk.generation_info[\"logprobs\"]\n                    if chunk.generation_info\n                    else None,\n                )\n    def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Call out to OpenAI's endpoint with k unique prompts.\n        Args:\n            prompts: The prompts to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The full LLM output.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-10", "text": "Returns:\n            The full LLM output.\n        Example:\n            .. code-block:: python\n                response = openai.generate([\"Tell me a joke.\"])\n        \"\"\"\n        # TODO: write a unit test for this\n        params = self._invocation_params\n        params = {**params, **kwargs}\n        sub_prompts = self.get_sub_prompts(params, prompts, stop)\n        choices = []\n        token_usage: Dict[str, int] = {}\n        # Get the token usage from the response.\n        # Includes prompt, completion, and total tokens used.\n        _keys = {\"completion_tokens\", \"prompt_tokens\", \"total_tokens\"}\n        system_fingerprint: Optional[str] = None\n        for _prompts in sub_prompts:\n            if self.streaming:\n                if len(_prompts) > 1:\n                    raise ValueError(\"Cannot stream results with multiple prompts.\")\n                generation: Optional[GenerationChunk] = None\n                for chunk in self._stream(_prompts[0], stop, run_manager, **kwargs):\n                    if generation is None:\n                        generation = chunk\n                    else:\n                        generation += chunk\n                assert generation is not None\n                choices.append(\n                    {\n                        \"text\": generation.text,\n                        \"finish_reason\": generation.generation_info.get(\"finish_reason\")\n                        if generation.generation_info\n                        else None,\n                        \"logprobs\": generation.generation_info.get(\"logprobs\")\n                        if generation.generation_info\n                        else None,\n                    }\n                )\n            else:\n                response = completion_with_retry(\n                    self, prompt=_prompts, run_manager=run_manager, **params\n                )\n                if not isinstance(response, dict):\n                    # V1 client returns the response in an PyDantic object instead of", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-11", "text": "# V1 client returns the response in an PyDantic object instead of\n                    # dict. For the transition period, we deep convert it to dict.\n                    response = response.dict()\n                choices.extend(response[\"choices\"])\n                update_token_usage(_keys, response, token_usage)\n                if not system_fingerprint:\n                    system_fingerprint = response.get(\"system_fingerprint\")\n        return self.create_llm_result(\n            choices,\n            prompts,\n            token_usage,\n            system_fingerprint=system_fingerprint,\n        )\n    async def _agenerate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        \"\"\"Call out to OpenAI's endpoint async with k unique prompts.\"\"\"\n        params = self._invocation_params\n        params = {**params, **kwargs}\n        sub_prompts = self.get_sub_prompts(params, prompts, stop)\n        choices = []\n        token_usage: Dict[str, int] = {}\n        # Get the token usage from the response.\n        # Includes prompt, completion, and total tokens used.\n        _keys = {\"completion_tokens\", \"prompt_tokens\", \"total_tokens\"}\n        system_fingerprint: Optional[str] = None\n        for _prompts in sub_prompts:\n            if self.streaming:\n                if len(_prompts) > 1:\n                    raise ValueError(\"Cannot stream results with multiple prompts.\")\n                generation: Optional[GenerationChunk] = None\n                async for chunk in self._astream(\n                    _prompts[0], stop, run_manager, **kwargs\n                ):\n                    if generation is None:\n                        generation = chunk\n                    else:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-12", "text": "):\n                    if generation is None:\n                        generation = chunk\n                    else:\n                        generation += chunk\n                assert generation is not None\n                choices.append(\n                    {\n                        \"text\": generation.text,\n                        \"finish_reason\": generation.generation_info.get(\"finish_reason\")\n                        if generation.generation_info\n                        else None,\n                        \"logprobs\": generation.generation_info.get(\"logprobs\")\n                        if generation.generation_info\n                        else None,\n                    }\n                )\n            else:\n                response = await acompletion_with_retry(\n                    self, prompt=_prompts, run_manager=run_manager, **params\n                )\n                if not isinstance(response, dict):\n                    response = response.dict()\n                choices.extend(response[\"choices\"])\n                update_token_usage(_keys, response, token_usage)\n        return self.create_llm_result(\n            choices,\n            prompts,\n            token_usage,\n            system_fingerprint=system_fingerprint,\n        )\n[docs]    def get_sub_prompts(\n        self,\n        params: Dict[str, Any],\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n    ) -> List[List[str]]:\n        \"\"\"Get the sub prompts for llm call.\"\"\"\n        if stop is not None:\n            if \"stop\" in params:\n                raise ValueError(\"`stop` found in both the input and default params.\")\n            params[\"stop\"] = stop\n        if params[\"max_tokens\"] == -1:\n            if len(prompts) != 1:\n                raise ValueError(\n                    \"max_tokens set to -1 not supported for multiple inputs.\"\n                )\n            params[\"max_tokens\"] = self.max_tokens_for_prompt(prompts[0])\n        sub_prompts = [", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-13", "text": "sub_prompts = [\n            prompts[i : i + self.batch_size]\n            for i in range(0, len(prompts), self.batch_size)\n        ]\n        return sub_prompts\n[docs]    def create_llm_result(\n        self,\n        choices: Any,\n        prompts: List[str],\n        token_usage: Dict[str, int],\n        *,\n        system_fingerprint: Optional[str] = None,\n    ) -> LLMResult:\n        \"\"\"Create the LLMResult from the choices and prompts.\"\"\"\n        generations = []\n        for i, _ in enumerate(prompts):\n            sub_choices = choices[i * self.n : (i + 1) * self.n]\n            generations.append(\n                [\n                    Generation(\n                        text=choice[\"text\"],\n                        generation_info=dict(\n                            finish_reason=choice.get(\"finish_reason\"),\n                            logprobs=choice.get(\"logprobs\"),\n                        ),\n                    )\n                    for choice in sub_choices\n                ]\n            )\n        llm_output = {\"token_usage\": token_usage, \"model_name\": self.model_name}\n        if system_fingerprint:\n            llm_output[\"system_fingerprint\"] = system_fingerprint\n        return LLMResult(generations=generations, llm_output=llm_output)\n    @property\n    def _invocation_params(self) -> Dict[str, Any]:\n        \"\"\"Get the parameters used to invoke the model.\"\"\"\n        openai_creds: Dict[str, Any] = {}\n        if not is_openai_v1():\n            openai_creds.update(\n                {\n                    \"api_key\": self.openai_api_key,\n                    \"api_base\": self.openai_api_base,\n                    \"organization\": self.openai_organization,\n                }\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-14", "text": "\"organization\": self.openai_organization,\n                }\n            )\n        if self.openai_proxy:\n            import openai\n            openai.proxy = {\"http\": self.openai_proxy, \"https\": self.openai_proxy}  # type: ignore[assignment]  # noqa: E501\n        return {**openai_creds, **self._default_params}\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model_name\": self.model_name}, **self._default_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"openai\"\n[docs]    def get_token_ids(self, text: str) -> List[int]:\n        \"\"\"Get the token IDs using the tiktoken package.\"\"\"\n        # tiktoken NOT supported for Python < 3.8\n        if sys.version_info[1] < 8:\n            return super().get_num_tokens(text)\n        try:\n            import tiktoken\n        except ImportError:\n            raise ImportError(\n                \"Could not import tiktoken python package. \"\n                \"This is needed in order to calculate get_num_tokens. \"\n                \"Please install it with `pip install tiktoken`.\"\n            )\n        model_name = self.tiktoken_model_name or self.model_name\n        try:\n            enc = tiktoken.encoding_for_model(model_name)\n        except KeyError:\n            logger.warning(\"Warning: model not found. Using cl100k_base encoding.\")\n            model = \"cl100k_base\"\n            enc = tiktoken.get_encoding(model)\n        return enc.encode(\n            text,\n            allowed_special=self.allowed_special,\n            disallowed_special=self.disallowed_special,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-15", "text": "disallowed_special=self.disallowed_special,\n        )\n[docs]    @staticmethod\n    def modelname_to_contextsize(modelname: str) -> int:\n        \"\"\"Calculate the maximum number of tokens possible to generate for a model.\n        Args:\n            modelname: The modelname we want to know the context size for.\n        Returns:\n            The maximum context size\n        Example:\n            .. code-block:: python\n                max_tokens = openai.modelname_to_contextsize(\"text-davinci-003\")\n        \"\"\"\n        model_token_mapping = {\n            \"gpt-4\": 8192,\n            \"gpt-4-0314\": 8192,\n            \"gpt-4-0613\": 8192,\n            \"gpt-4-32k\": 32768,\n            \"gpt-4-32k-0314\": 32768,\n            \"gpt-4-32k-0613\": 32768,\n            \"gpt-3.5-turbo\": 4096,\n            \"gpt-3.5-turbo-0301\": 4096,\n            \"gpt-3.5-turbo-0613\": 4096,\n            \"gpt-3.5-turbo-16k\": 16385,\n            \"gpt-3.5-turbo-16k-0613\": 16385,\n            \"gpt-3.5-turbo-instruct\": 4096,\n            \"text-ada-001\": 2049,\n            \"ada\": 2049,\n            \"text-babbage-001\": 2040,\n            \"babbage\": 2049,\n            \"text-curie-001\": 2049,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-16", "text": "\"text-curie-001\": 2049,\n            \"curie\": 2049,\n            \"davinci\": 2049,\n            \"text-davinci-003\": 4097,\n            \"text-davinci-002\": 4097,\n            \"code-davinci-002\": 8001,\n            \"code-davinci-001\": 8001,\n            \"code-cushman-002\": 2048,\n            \"code-cushman-001\": 2048,\n        }\n        # handling finetuned models\n        if \"ft-\" in modelname:\n            modelname = modelname.split(\":\")[0]\n        context_size = model_token_mapping.get(modelname, None)\n        if context_size is None:\n            raise ValueError(\n                f\"Unknown model: {modelname}. Please provide a valid OpenAI model name.\"\n                \"Known models are: \" + \", \".join(model_token_mapping.keys())\n            )\n        return context_size\n    @property\n    def max_context_size(self) -> int:\n        \"\"\"Get max context size for this model.\"\"\"\n        return self.modelname_to_contextsize(self.model_name)\n[docs]    def max_tokens_for_prompt(self, prompt: str) -> int:\n        \"\"\"Calculate the maximum number of tokens possible to generate for a prompt.\n        Args:\n            prompt: The prompt to pass into the model.\n        Returns:\n            The maximum number of tokens to generate for a prompt.\n        Example:\n            .. code-block:: python\n                max_tokens = openai.max_token_for_prompt(\"Tell me a joke.\")\n        \"\"\"\n        num_tokens = self.get_num_tokens(prompt)\n        return self.max_context_size - num_tokens\n[docs]class OpenAI(BaseOpenAI):\n    \"\"\"OpenAI large language models.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-17", "text": "[docs]class OpenAI(BaseOpenAI):\n    \"\"\"OpenAI large language models.\n    To use, you should have the ``openai`` python package installed, and the\n    environment variable ``OPENAI_API_KEY`` set with your API key.\n    Any parameters that are valid to be passed to the openai.create call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.llms import OpenAI\n            openai = OpenAI(model_name=\"text-davinci-003\")\n    \"\"\"\n    @property\n    def _invocation_params(self) -> Dict[str, Any]:\n        return {**{\"model\": self.model_name}, **super()._invocation_params}\n[docs]class AzureOpenAI(BaseOpenAI):\n    \"\"\"Azure-specific OpenAI large language models.\n    To use, you should have the ``openai`` python package installed, and the\n    environment variable ``OPENAI_API_KEY`` set with your API key.\n    Any parameters that are valid to be passed to the openai.create call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.llms import AzureOpenAI\n            openai = AzureOpenAI(model_name=\"text-davinci-003\")\n    \"\"\"\n    azure_endpoint: Union[str, None] = None\n    \"\"\"Your Azure endpoint, including the resource.\n        Automatically inferred from env var `AZURE_OPENAI_ENDPOINT` if not provided.\n        Example: `https://example-resource.azure.openai.com/`\n    \"\"\"\n    deployment_name: Union[str, None] = Field(default=None, alias=\"azure_deployment\")\n    \"\"\"A model deployment.", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-18", "text": "\"\"\"A model deployment. \n        If given sets the base client URL to include `/deployments/{azure_deployment}`.\n        Note: this means you won't be able to use non-deployment endpoints.\n    \"\"\"\n    openai_api_version: str = Field(default=\"\", alias=\"api_version\")\n    \"\"\"Automatically inferred from env var `OPENAI_API_VERSION` if not provided.\"\"\"\n    openai_api_key: Union[str, None] = Field(default=None, alias=\"api_key\")\n    \"\"\"Automatically inferred from env var `AZURE_OPENAI_API_KEY` if not provided.\"\"\"\n    azure_ad_token: Union[str, None] = None\n    \"\"\"Your Azure Active Directory token.\n        Automatically inferred from env var `AZURE_OPENAI_AD_TOKEN` if not provided.\n        For more: \n        https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id.\n    \"\"\"  # noqa: E501\n    azure_ad_token_provider: Union[str, None] = None\n    \"\"\"A function that returns an Azure Active Directory token.\n        Will be invoked on every request.\n    \"\"\"\n    openai_api_type: str = \"\"\n    \"\"\"Legacy, for openai<1.0.0 support.\"\"\"\n    validate_base_url: bool = True\n    \"\"\"For backwards compatibility. If legacy val openai_api_base is passed in, try to \n        infer if it is a base_url or azure_endpoint and update accordingly.\n    \"\"\"\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        if values[\"n\"] < 1:\n            raise ValueError(\"n must be at least 1.\")\n        if values[\"streaming\"] and values[\"n\"] > 1:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-19", "text": "if values[\"streaming\"] and values[\"n\"] > 1:\n            raise ValueError(\"Cannot stream results when n > 1.\")\n        if values[\"streaming\"] and values[\"best_of\"] > 1:\n            raise ValueError(\"Cannot stream results when best_of > 1.\")\n        # Check OPENAI_KEY for backwards compatibility.\n        # TODO: Remove OPENAI_API_KEY support to avoid possible conflict when using\n        # other forms of azure credentials.\n        values[\"openai_api_key\"] = (\n            values[\"openai_api_key\"]\n            or os.getenv(\"AZURE_OPENAI_API_KEY\")\n            or os.getenv(\"OPENAI_API_KEY\")\n        )\n        values[\"azure_endpoint\"] = values[\"azure_endpoint\"] or os.getenv(\n            \"AZURE_OPENAI_ENDPOINT\"\n        )\n        values[\"azure_ad_token\"] = values[\"azure_ad_token\"] or os.getenv(\n            \"AZURE_OPENAI_AD_TOKEN\"\n        )\n        values[\"openai_api_base\"] = values[\"openai_api_base\"] or os.getenv(\n            \"OPENAI_API_BASE\"\n        )\n        values[\"openai_proxy\"] = get_from_dict_or_env(\n            values,\n            \"openai_proxy\",\n            \"OPENAI_PROXY\",\n            default=\"\",\n        )\n        values[\"openai_organization\"] = (\n            values[\"openai_organization\"]\n            or os.getenv(\"OPENAI_ORG_ID\")\n            or os.getenv(\"OPENAI_ORGANIZATION\")\n        )\n        values[\"openai_api_version\"] = values[\"openai_api_version\"] or os.getenv(\n            \"OPENAI_API_VERSION\"\n        )\n        values[\"openai_api_type\"] = get_from_dict_or_env(\n            values, \"openai_api_type\", \"OPENAI_API_TYPE\", default=\"azure\"\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-20", "text": ")\n        try:\n            import openai\n        except ImportError:\n            raise ImportError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\"\n            )\n        if is_openai_v1():\n            # For backwards compatibility. Before openai v1, no distinction was made\n            # between azure_endpoint and base_url (openai_api_base).\n            openai_api_base = values[\"openai_api_base\"]\n            if openai_api_base and values[\"validate_base_url\"]:\n                if \"/openai\" not in openai_api_base:\n                    values[\"openai_api_base\"] = (\n                        values[\"openai_api_base\"].rstrip(\"/\") + \"/openai\"\n                    )\n                    warnings.warn(\n                        \"As of openai>=1.0.0, Azure endpoints should be specified via \"\n                        f\"the `azure_endpoint` param not `openai_api_base` \"\n                        f\"(or alias `base_url`). Updating `openai_api_base` from \"\n                        f\"{openai_api_base} to {values['openai_api_base']}.\"\n                    )\n                if values[\"deployment_name\"]:\n                    warnings.warn(\n                        \"As of openai>=1.0.0, if `deployment_name` (or alias \"\n                        \"`azure_deployment`) is specified then \"\n                        \"`openai_api_base` (or alias `base_url`) should not be. \"\n                        \"Instead use `deployment_name` (or alias `azure_deployment`) \"\n                        \"and `azure_endpoint`.\"\n                    )\n                    if values[\"deployment_name\"] not in values[\"openai_api_base\"]:\n                        warnings.warn(\n                            \"As of openai>=1.0.0, if `openai_api_base` \"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-21", "text": "\"(or alias `base_url`) is specified it is expected to be \"\n                            \"of the form \"\n                            \"https://example-resource.azure.openai.com/openai/deployments/example-deployment. \"  # noqa: E501\n                            f\"Updating {openai_api_base} to \"\n                            f\"{values['openai_api_base']}.\"\n                        )\n                        values[\"openai_api_base\"] += (\n                            \"/deployments/\" + values[\"deployment_name\"]\n                        )\n                    values[\"deployment_name\"] = None\n            client_params = {\n                \"api_version\": values[\"openai_api_version\"],\n                \"azure_endpoint\": values[\"azure_endpoint\"],\n                \"azure_deployment\": values[\"deployment_name\"],\n                \"api_key\": values[\"openai_api_key\"],\n                \"azure_ad_token\": values[\"azure_ad_token\"],\n                \"azure_ad_token_provider\": values[\"azure_ad_token_provider\"],\n                \"organization\": values[\"openai_organization\"],\n                \"base_url\": values[\"openai_api_base\"],\n                \"timeout\": values[\"request_timeout\"],\n                \"max_retries\": values[\"max_retries\"],\n                \"default_headers\": values[\"default_headers\"],\n                \"default_query\": values[\"default_query\"],\n                \"http_client\": values[\"http_client\"],\n            }\n            values[\"client\"] = openai.AzureOpenAI(**client_params).completions\n            values[\"async_client\"] = openai.AsyncAzureOpenAI(\n                **client_params\n            ).completions\n        else:\n            values[\"client\"] = openai.Completion\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        return {\n            **{\"deployment_name\": self.deployment_name},\n            **super()._identifying_params,\n        }\n    @property", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-22", "text": "**super()._identifying_params,\n        }\n    @property\n    def _invocation_params(self) -> Dict[str, Any]:\n        if is_openai_v1():\n            openai_params = {\"model\": self.deployment_name}\n        else:\n            openai_params = {\n                \"engine\": self.deployment_name,\n                \"api_type\": self.openai_api_type,\n                \"api_version\": self.openai_api_version,\n            }\n        return {**openai_params, **super()._invocation_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"azure\"\n    @property\n    def lc_attributes(self) -> Dict[str, Any]:\n        return {\n            \"openai_api_type\": self.openai_api_type,\n            \"openai_api_version\": self.openai_api_version,\n        }\n[docs]class OpenAIChat(BaseLLM):\n    \"\"\"OpenAI Chat large language models.\n    To use, you should have the ``openai`` python package installed, and the\n    environment variable ``OPENAI_API_KEY`` set with your API key.\n    Any parameters that are valid to be passed to the openai.create call can be passed\n    in, even if not explicitly saved on this class.\n    Example:\n        .. code-block:: python\n            from langchain.llms import OpenAIChat\n            openaichat = OpenAIChat(model_name=\"gpt-3.5-turbo\")\n    \"\"\"\n    client: Any = Field(default=None, exclude=True)  #: :meta private:\n    async_client: Any = Field(default=None, exclude=True)  #: :meta private:\n    model_name: str = \"gpt-3.5-turbo\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-23", "text": "model_name: str = \"gpt-3.5-turbo\"\n    \"\"\"Model name to use.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not explicitly specified.\"\"\"\n    # When updating this to use a SecretStr\n    # Check for classes that derive from this class (as some of them\n    # may assume openai_api_key is a str)\n    openai_api_key: Optional[str] = Field(default=None, alias=\"api_key\")\n    \"\"\"Automatically inferred from env var `OPENAI_API_KEY` if not provided.\"\"\"\n    openai_api_base: Optional[str] = Field(default=None, alias=\"base_url\")\n    \"\"\"Base URL path for API requests, leave blank if not using a proxy or service \n        emulator.\"\"\"\n    # to support explicit proxy for OpenAI\n    openai_proxy: Optional[str] = None\n    max_retries: int = 6\n    \"\"\"Maximum number of retries to make when generating.\"\"\"\n    prefix_messages: List = Field(default_factory=list)\n    \"\"\"Series of messages for Chat input.\"\"\"\n    streaming: bool = False\n    \"\"\"Whether to stream the results or not.\"\"\"\n    allowed_special: Union[Literal[\"all\"], AbstractSet[str]] = set()\n    \"\"\"Set of special tokens that are allowed\u3002\"\"\"\n    disallowed_special: Union[Literal[\"all\"], Collection[str]] = \"all\"\n    \"\"\"Set of special tokens that are not allowed\u3002\"\"\"\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = {field.alias for field in cls.__fields__.values()}\n        extra = values.get(\"model_kwargs\", {})", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-24", "text": "extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name not in all_required_field_names:\n                if field_name in extra:\n                    raise ValueError(f\"Found {field_name} supplied twice.\")\n                extra[field_name] = values.pop(field_name)\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key and python package exists in environment.\"\"\"\n        openai_api_key = get_from_dict_or_env(\n            values, \"openai_api_key\", \"OPENAI_API_KEY\"\n        )\n        openai_api_base = get_from_dict_or_env(\n            values,\n            \"openai_api_base\",\n            \"OPENAI_API_BASE\",\n            default=\"\",\n        )\n        openai_proxy = get_from_dict_or_env(\n            values,\n            \"openai_proxy\",\n            \"OPENAI_PROXY\",\n            default=\"\",\n        )\n        openai_organization = get_from_dict_or_env(\n            values, \"openai_organization\", \"OPENAI_ORGANIZATION\", default=\"\"\n        )\n        try:\n            import openai\n            openai.api_key = openai_api_key\n            if openai_api_base:\n                openai.api_base = openai_api_base\n            if openai_organization:\n                openai.organization = openai_organization\n            if openai_proxy:\n                openai.proxy = {\"http\": openai_proxy, \"https\": openai_proxy}  # type: ignore[assignment]  # noqa: E501\n        except ImportError:\n            raise ImportError(\n                \"Could not import openai python package. \"\n                \"Please install it with `pip install openai`.\"\n            )\n        try:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-25", "text": ")\n        try:\n            values[\"client\"] = openai.ChatCompletion\n        except AttributeError:\n            raise ValueError(\n                \"`openai` has no `ChatCompletion` attribute, this is likely \"\n                \"due to an old version of the openai package. Try upgrading it \"\n                \"with `pip install --upgrade openai`.\"\n            )\n        warnings.warn(\n            \"You are trying to use a chat model. This way of initializing it is \"\n            \"no longer supported. Instead, please use: \"\n            \"`from langchain.chat_models import ChatOpenAI`\"\n        )\n        return values\n    @property\n    def _default_params(self) -> Dict[str, Any]:\n        \"\"\"Get the default parameters for calling OpenAI API.\"\"\"\n        return self.model_kwargs\n    def _get_chat_params(\n        self, prompts: List[str], stop: Optional[List[str]] = None\n    ) -> Tuple:\n        if len(prompts) > 1:\n            raise ValueError(\n                f\"OpenAIChat currently only supports single prompt, got {prompts}\"\n            )\n        messages = self.prefix_messages + [{\"role\": \"user\", \"content\": prompts[0]}]\n        params: Dict[str, Any] = {**{\"model\": self.model_name}, **self._default_params}\n        if stop is not None:\n            if \"stop\" in params:\n                raise ValueError(\"`stop` found in both the input and default params.\")\n            params[\"stop\"] = stop\n        if params.get(\"max_tokens\") == -1:\n            # for ChatGPT api, omitting max_tokens is equivalent to having no limit\n            del params[\"max_tokens\"]\n        return messages, params\n    def _stream(\n        self,\n        prompt: str,", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-26", "text": "def _stream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> Iterator[GenerationChunk]:\n        messages, params = self._get_chat_params([prompt], stop)\n        params = {**params, **kwargs, \"stream\": True}\n        for stream_resp in completion_with_retry(\n            self, messages=messages, run_manager=run_manager, **params\n        ):\n            if not isinstance(stream_resp, dict):\n                stream_resp = stream_resp.dict()\n            token = stream_resp[\"choices\"][0][\"delta\"].get(\"content\", \"\")\n            chunk = GenerationChunk(text=token)\n            yield chunk\n            if run_manager:\n                run_manager.on_llm_new_token(token, chunk=chunk)\n    async def _astream(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> AsyncIterator[GenerationChunk]:\n        messages, params = self._get_chat_params([prompt], stop)\n        params = {**params, **kwargs, \"stream\": True}\n        async for stream_resp in await acompletion_with_retry(\n            self, messages=messages, run_manager=run_manager, **params\n        ):\n            if not isinstance(stream_resp, dict):\n                stream_resp = stream_resp.dict()\n            token = stream_resp[\"choices\"][0][\"delta\"].get(\"content\", \"\")\n            chunk = GenerationChunk(text=token)\n            yield chunk\n            if run_manager:\n                await run_manager.on_llm_new_token(token, chunk=chunk)\n    def _generate(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-27", "text": "def _generate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        if self.streaming:\n            generation: Optional[GenerationChunk] = None\n            for chunk in self._stream(prompts[0], stop, run_manager, **kwargs):\n                if generation is None:\n                    generation = chunk\n                else:\n                    generation += chunk\n            assert generation is not None\n            return LLMResult(generations=[[generation]])\n        messages, params = self._get_chat_params(prompts, stop)\n        params = {**params, **kwargs}\n        full_response = completion_with_retry(\n            self, messages=messages, run_manager=run_manager, **params\n        )\n        if not isinstance(full_response, dict):\n            full_response = full_response.dict()\n        llm_output = {\n            \"token_usage\": full_response[\"usage\"],\n            \"model_name\": self.model_name,\n        }\n        return LLMResult(\n            generations=[\n                [Generation(text=full_response[\"choices\"][0][\"message\"][\"content\"])]\n            ],\n            llm_output=llm_output,\n        )\n    async def _agenerate(\n        self,\n        prompts: List[str],\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> LLMResult:\n        if self.streaming:\n            generation: Optional[GenerationChunk] = None\n            async for chunk in self._astream(prompts[0], stop, run_manager, **kwargs):\n                if generation is None:", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-28", "text": "if generation is None:\n                    generation = chunk\n                else:\n                    generation += chunk\n            assert generation is not None\n            return LLMResult(generations=[[generation]])\n        messages, params = self._get_chat_params(prompts, stop)\n        params = {**params, **kwargs}\n        full_response = await acompletion_with_retry(\n            self, messages=messages, run_manager=run_manager, **params\n        )\n        if not isinstance(full_response, dict):\n            full_response = full_response.dict()\n        llm_output = {\n            \"token_usage\": full_response[\"usage\"],\n            \"model_name\": self.model_name,\n        }\n        return LLMResult(\n            generations=[\n                [Generation(text=full_response[\"choices\"][0][\"message\"][\"content\"])]\n            ],\n            llm_output=llm_output,\n        )\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {**{\"model_name\": self.model_name}, **self._default_params}\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"openai-chat\"\n[docs]    def get_token_ids(self, text: str) -> List[int]:\n        \"\"\"Get the token IDs using the tiktoken package.\"\"\"\n        # tiktoken NOT supported for Python < 3.8\n        if sys.version_info[1] < 8:\n            return super().get_token_ids(text)\n        try:\n            import tiktoken\n        except ImportError:\n            raise ImportError(\n                \"Could not import tiktoken python package. \"\n                \"This is needed in order to calculate get_num_tokens. \"\n                \"Please install it with `pip install tiktoken`.\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "dc417efc9b34-29", "text": "\"Please install it with `pip install tiktoken`.\"\n            )\n        enc = tiktoken.encoding_for_model(self.model_name)\n        return enc.encode(\n            text,\n            allowed_special=self.allowed_special,\n            disallowed_special=self.disallowed_special,\n        )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html"}
{"id": "8f1a119c5bf4-0", "text": "Source code for langchain.llms.opaqueprompts\nimport logging\nfrom typing import Any, Dict, List, Optional\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.pydantic_v1 import Extra, root_validator\nfrom langchain.schema.language_model import BaseLanguageModel\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class OpaquePrompts(LLM):\n    \"\"\"An LLM wrapper that uses OpaquePrompts to sanitize prompts.\n    Wraps another LLM and sanitizes prompts before passing it to the LLM, then\n        de-sanitizes the response.\n    To use, you should have the ``opaqueprompts`` python package installed,\n    and the environment variable ``OPAQUEPROMPTS_API_KEY`` set with\n    your API key, or pass it as a named parameter to the constructor.\n    Example:\n        .. code-block:: python\n            from langchain.llms import OpaquePrompts\n            from langchain.chat_models import ChatOpenAI\n            op_llm = OpaquePrompts(base_llm=ChatOpenAI())\n    \"\"\"\n    base_llm: BaseLanguageModel\n    \"\"\"The base LLM to use.\"\"\"\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validates that the OpaquePrompts API key and the Python package exist.\"\"\"\n        try:\n            import opaqueprompts as op\n        except ImportError:\n            raise ImportError(\n                \"Could not import the `opaqueprompts` Python package, \"\n                \"please install it with `pip install opaqueprompts`.\"\n            )", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/opaqueprompts.html"}
{"id": "8f1a119c5bf4-1", "text": "\"please install it with `pip install opaqueprompts`.\"\n            )\n        if op.__package__ is None:\n            raise ValueError(\n                \"Could not properly import `opaqueprompts`, \"\n                \"opaqueprompts.__package__ is None.\"\n            )\n        api_key = get_from_dict_or_env(\n            values, \"opaqueprompts_api_key\", \"OPAQUEPROMPTS_API_KEY\", default=\"\"\n        )\n        if not api_key:\n            raise ValueError(\n                \"Could not find OPAQUEPROMPTS_API_KEY in the environment. \"\n                \"Please set it to your OpaquePrompts API key.\"\n                \"You can get it by creating an account on the OpaquePrompts website: \"\n                \"https://opaqueprompts.opaque.co/ .\"\n            )\n        return values\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call base LLM with sanitization before and de-sanitization after.\n        Args:\n            prompt: The prompt to pass into the model.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = op_llm(\"Tell me a joke.\")\n        \"\"\"\n        import opaqueprompts as op\n        _run_manager = run_manager or CallbackManagerForLLMRun.get_noop_manager()\n        # sanitize the prompt by replacing the sensitive information with a placeholder\n        sanitize_response: op.SanitizeResponse = op.sanitize([prompt])\n        sanitized_prompt_value_str = sanitize_response.sanitized_texts[0]", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/opaqueprompts.html"}
{"id": "8f1a119c5bf4-2", "text": "sanitized_prompt_value_str = sanitize_response.sanitized_texts[0]\n        # TODO: Add in callbacks once child runs for LLMs are supported by LangSmith.\n        # call the LLM with the sanitized prompt and get the response\n        llm_response = self.base_llm.predict(\n            sanitized_prompt_value_str,\n            stop=stop,\n        )\n        # desanitize the response by restoring the original sensitive information\n        desanitize_response: op.DesanitizeResponse = op.desanitize(\n            llm_response,\n            secure_context=sanitize_response.secure_context,\n        )\n        return desanitize_response.desanitized_text\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of LLM.\n        This is an override of the base class method.\n        \"\"\"\n        return \"opaqueprompts\"", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/opaqueprompts.html"}
{"id": "4777622cb657-0", "text": "Source code for langchain.llms.stochasticai\nimport logging\nimport time\nfrom typing import Any, Dict, List, Mapping, Optional\nimport requests\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms.base import LLM\nfrom langchain.llms.utils import enforce_stop_tokens\nfrom langchain.pydantic_v1 import Extra, Field, root_validator\nfrom langchain.utils import get_from_dict_or_env\nlogger = logging.getLogger(__name__)\n[docs]class StochasticAI(LLM):\n    \"\"\"StochasticAI large language models.\n    To use, you should have the environment variable ``STOCHASTICAI_API_KEY``\n    set with your API key.\n    Example:\n        .. code-block:: python\n            from langchain.llms import StochasticAI\n            stochasticai = StochasticAI(api_url=\"\")\n    \"\"\"\n    api_url: str = \"\"\n    \"\"\"Model name to use.\"\"\"\n    model_kwargs: Dict[str, Any] = Field(default_factory=dict)\n    \"\"\"Holds any model parameters valid for `create` call not\n    explicitly specified.\"\"\"\n    stochasticai_api_key: Optional[str] = None\n    class Config:\n        \"\"\"Configuration for this pydantic object.\"\"\"\n        extra = Extra.forbid\n    @root_validator(pre=True)\n    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Build extra kwargs from additional params that were passed in.\"\"\"\n        all_required_field_names = {field.alias for field in cls.__fields__.values()}\n        extra = values.get(\"model_kwargs\", {})\n        for field_name in list(values):\n            if field_name not in all_required_field_names:\n                if field_name in extra:\n                    raise ValueError(f\"Found {field_name} supplied twice.\")\n                logger.warning(", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html"}
{"id": "4777622cb657-1", "text": "raise ValueError(f\"Found {field_name} supplied twice.\")\n                logger.warning(\n                    f\"\"\"{field_name} was transferred to model_kwargs.\n                    Please confirm that {field_name} is what you intended.\"\"\"\n                )\n                extra[field_name] = values.pop(field_name)\n        values[\"model_kwargs\"] = extra\n        return values\n    @root_validator()\n    def validate_environment(cls, values: Dict) -> Dict:\n        \"\"\"Validate that api key exists in environment.\"\"\"\n        stochasticai_api_key = get_from_dict_or_env(\n            values, \"stochasticai_api_key\", \"STOCHASTICAI_API_KEY\"\n        )\n        values[\"stochasticai_api_key\"] = stochasticai_api_key\n        return values\n    @property\n    def _identifying_params(self) -> Mapping[str, Any]:\n        \"\"\"Get the identifying parameters.\"\"\"\n        return {\n            **{\"endpoint_url\": self.api_url},\n            **{\"model_kwargs\": self.model_kwargs},\n        }\n    @property\n    def _llm_type(self) -> str:\n        \"\"\"Return type of llm.\"\"\"\n        return \"stochasticai\"\n    def _call(\n        self,\n        prompt: str,\n        stop: Optional[List[str]] = None,\n        run_manager: Optional[CallbackManagerForLLMRun] = None,\n        **kwargs: Any,\n    ) -> str:\n        \"\"\"Call out to StochasticAI's complete endpoint.\n        Args:\n            prompt: The prompt to pass into the model.\n            stop: Optional list of stop words to use when generating.\n        Returns:\n            The string generated by the model.\n        Example:\n            .. code-block:: python\n                response = StochasticAI(\"Tell me a joke.\")\n        \"\"\"\n        params = self.model_kwargs or {}", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html"}
{"id": "4777622cb657-2", "text": "\"\"\"\n        params = self.model_kwargs or {}\n        params = {**params, **kwargs}\n        response_post = requests.post(\n            url=self.api_url,\n            json={\"prompt\": prompt, \"params\": params},\n            headers={\n                \"apiKey\": f\"{self.stochasticai_api_key}\",\n                \"Accept\": \"application/json\",\n                \"Content-Type\": \"application/json\",\n            },\n        )\n        response_post.raise_for_status()\n        response_post_json = response_post.json()\n        completed = False\n        while not completed:\n            response_get = requests.get(\n                url=response_post_json[\"data\"][\"responseUrl\"],\n                headers={\n                    \"apiKey\": f\"{self.stochasticai_api_key}\",\n                    \"Accept\": \"application/json\",\n                    \"Content-Type\": \"application/json\",\n                },\n            )\n            response_get.raise_for_status()\n            response_get_json = response_get.json()[\"data\"]\n            text = response_get_json.get(\"completion\")\n            completed = text is not None\n            time.sleep(0.5)\n        text = text[0]\n        if stop is not None:\n            # I believe this is required since the stop tokens\n            # are not enforced by the model parameters\n            text = enforce_stop_tokens(text, stop)\n        return text", "source": "lang/api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html"}
{"id": "7a6292de207a-0", "text": "langchain_experimental.fallacy_removal.base.FallacyChain\u00b6\nclass langchain_experimental.fallacy_removal.base.FallacyChain[source]\u00b6\nBases: Chain\nChain for applying logical fallacy evaluations, modeled after Constitutional AI     and in same format, but applying logical fallacies as generalized rules to remove     in output\nExample\nfrom langchain.llms import OpenAI\nfrom langchain.chains import LLMChain\nfrom langchain_experimental.fallacy import FallacyChain\nfrom langchain_experimental.fallacy_removal.models import LogicalFallacy\nllm = OpenAI()\nqa_prompt = PromptTemplate(\n    template=\"Q: {question} A:\",\n    input_variables=[\"question\"],\n)\nqa_chain = LLMChain(llm=llm, prompt=qa_prompt)\nfallacy_chain = FallacyChain.from_llm(\n    llm=llm,\n    chain=qa_chain,\n    logical_fallacies=[\n        LogicalFallacy(\n            fallacy_critique_request=\"Tell if this answer meets criteria.\",\n            fallacy_revision_request=                        \"Give an answer that meets better criteria.\",\n        )\n    ],\n)\nfallacy_chain.run(question=\"How do I know if the earth is round?\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-1", "text": "Each custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam chain: LLMChain [Required]\u00b6\nparam fallacy_critique_chain: LLMChain [Required]\u00b6\nparam fallacy_revision_chain: LLMChain [Required]\u00b6\nparam logical_fallacies: List[LogicalFallacy] [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam return_intermediate_steps: bool = False\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-2", "text": "accessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-4", "text": "Returns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-5", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-6", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-8", "text": "classmethod from_llm(llm: BaseLanguageModel, chain: LLMChain, fallacy_critique_prompt: BasePromptTemplate = FewShotPromptTemplate(input_variables=['fallacy_critique_request', 'input_prompt', 'output_from_model'], examples=[{'input_prompt': \"If everyone says the Earth is round,\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 how do I know that's correct?\", 'output_from_model': 'The earth is round because your\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 teacher says it is', 'fallacy_critique_request': 'Identify specific ways in\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 which the model\u2019s previous response had a logical fallacy.\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Also point out potential logical fallacies in the human\u2019s\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 questions and responses. Examples of logical fallacies\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 include but are not limited to ad hominem, ad populum,\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 appeal to emotion and false causality.', 'fallacy_critique': 'This statement contains the logical\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 fallacy of Ad Verecundiam or Appeal to Authority. It is\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 a fallacy because it asserts something to be true purely\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 based on the authority of the source making the claim,\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 without any actual evidence to support it.\u00a0 Fallacy\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Critique Needed', 'fallacy_revision': 'The earth is round based on\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 evidence from observations of its curvature from high\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 altitudes, photos from space showing its spherical shape,\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 circumnavigation, and the fact that we see its rounded\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 shadow on the moon during lunar eclipses.'}, {'input_prompt': 'Should we invest more in our school\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 music program? After all, studies show students\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 involved in music perform better academically.', 'output_from_model': \"I don't think we should invest\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 more in the music program. Playing the piccolo won't\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 teach someone better math skills.\", 'fallacy_critique_request': 'Identify specific ways\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 in which the model\u2019s previous response had a logical\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 fallacy. Also point out potential logical fallacies\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 in the human\u2019s questions and responses. Examples of", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-9", "text": "Also point out potential logical fallacies\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 in the human\u2019s questions and responses. Examples of\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 logical fallacies include but are not limited to ad\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 homimem, ad populum, appeal to emotion and false\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 causality.', 'fallacy_critique': 'This answer commits the division\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 fallacy by rejecting the argument based on assuming\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 capabilities true of the parts (playing an instrument\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 like piccolo) also apply to the whole\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 (the full music program). The answer focuses only on\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 part of the music program rather than considering it\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 as a whole.\u00a0 Fallacy Critique Needed.', 'fallacy_revision': 'While playing an instrument may\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 teach discipline, more evidence is needed on whether\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 music education courses improve critical thinking\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 skills across subjects before determining if increased\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 investment in the whole music program is warranted.'}], example_prompt=PromptTemplate(input_variables=['fallacy_critique', 'fallacy_critique_request', 'input_prompt', 'output_from_model'], template='Human: {input_prompt}\\n\\nModel: {output_from_model}\\n\\nFallacy Critique Request: {fallacy_critique_request}\\n\\nFallacy Critique: {fallacy_critique}'), suffix='Human: {input_prompt}\\nModel: {output_from_model}\\n\\nFallacy Critique Request: {fallacy_critique_request}\\n\\nFallacy Critique:', example_separator='\\n === \\n', prefix=\"Below is a conversation between a human and an\u00a0\u00a0\u00a0\u00a0 AI assistant. If there is no material critique of the\u00a0\u00a0\u00a0\u00a0 model output, append to the end of the Fallacy Critique:\u00a0\u00a0\u00a0\u00a0 'No fallacy critique needed.' If there is material\u00a0\u00a0\u00a0\u00a0 critique\u00a0\u00a0\u00a0\u00a0 of the model output, append to the end of the Fallacy\u00a0\u00a0\u00a0\u00a0 Critique: 'Fallacy Critique needed.'\"), fallacy_revision_prompt: BasePromptTemplate = FewShotPromptTemplate(input_variables=['fallacy_critique', 'fallacy_critique_request',", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-10", "text": "= FewShotPromptTemplate(input_variables=['fallacy_critique', 'fallacy_critique_request', 'fallacy_revision_request', 'input_prompt', 'output_from_model'], examples=[{'input_prompt': \"If everyone says the Earth is round,\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 how do I know that's correct?\", 'output_from_model': 'The earth is round because your\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 teacher says it is', 'fallacy_critique_request': 'Identify specific ways in\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 which the model\u2019s previous response had a logical fallacy.\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Also point out potential logical fallacies in the human\u2019s\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 questions and responses. Examples of logical fallacies\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 include but are not limited to ad hominem, ad populum,\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 appeal to emotion and false causality.', 'fallacy_critique': 'This statement contains the logical\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 fallacy of Ad Verecundiam or Appeal to Authority. It is\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 a fallacy because it asserts something to be true purely\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 based on the authority of the source making the claim,\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 without any actual evidence to support it.\u00a0 Fallacy\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Critique Needed', 'fallacy_revision_request': 'Please rewrite the model\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 response to remove all logical fallacies, and to\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 politely point out any logical fallacies from the\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 human.', 'fallacy_revision': 'The earth is round based on\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 evidence from observations of its curvature from high\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 altitudes, photos from space showing its spherical shape,\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 circumnavigation, and the fact that we see its rounded\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 shadow on the moon during lunar eclipses.'}, {'input_prompt': 'Should we invest more in our school\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 music program? After all, studies show students\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 involved in music perform better academically.', 'output_from_model': \"I don't think we should invest\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 more in the music program. Playing the piccolo won't\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 teach someone better math skills.\", 'fallacy_critique_request': 'Identify specific ways\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 in which the model\u2019s previous response had a logical", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-11", "text": "'Identify specific ways\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 in which the model\u2019s previous response had a logical\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 fallacy. Also point out potential logical fallacies\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 in the human\u2019s questions and responses. Examples of\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 logical fallacies include but are not limited to ad\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 homimem, ad populum, appeal to emotion and false\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 causality.', 'fallacy_critique': 'This answer commits the division\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 fallacy by rejecting the argument based on assuming\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 capabilities true of the parts (playing an instrument\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 like piccolo) also apply to the whole\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 (the full music program). The answer focuses only on\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 part of the music program rather than considering it\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 as a whole.\u00a0 Fallacy Critique Needed.', 'fallacy_revision_request': 'Please rewrite the model\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 response to remove all logical fallacies, and to\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 politely point out any logical fallacies from the human.', 'fallacy_revision': 'While playing an instrument may\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 teach discipline, more evidence is needed on whether\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 music education courses improve critical thinking\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 skills across subjects before determining if increased\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 investment in the whole music program is warranted.'}], example_prompt=PromptTemplate(input_variables=['fallacy_critique', 'fallacy_critique_request', 'input_prompt', 'output_from_model'], template='Human: {input_prompt}\\n\\nModel: {output_from_model}\\n\\nFallacy Critique Request: {fallacy_critique_request}\\n\\nFallacy Critique: {fallacy_critique}'), suffix='Human: {input_prompt}\\n\\nModel: {output_from_model}\\n\\nFallacy Critique Request: {fallacy_critique_request}\\n\\nFallacy Critique: {fallacy_critique}\\n\\nIf the fallacy critique does not identify anything worth changing, ignore the Fallacy Revision Request and do not make any revisions. Instead, return \"No revisions needed\".\\n\\nIf the fallacy critique does identify something worth changing, please revise the model response based on", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-12", "text": "the fallacy critique does identify something worth changing, please revise the model response based on the Fallacy Revision Request.\\n\\nFallacy Revision Request: {fallacy_revision_request}\\n\\nFallacy Revision:', example_separator='\\n === \\n', prefix='Below is a conversation between a human and\u00a0\u00a0\u00a0\u00a0 an AI assistant.'), **kwargs: Any) \u2192 FallacyChain[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-13", "text": "Create a chain from an LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_fallacies(names: Optional[List[str]] = None) \u2192 List[LogicalFallacy][source]\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-14", "text": "Parameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-15", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-16", "text": "sole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-17", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-18", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nInput keys.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "7a6292de207a-19", "text": "Input keys.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nOutput keys.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html"}
{"id": "d64d5da1fffa-0", "text": "langchain_experimental.fallacy_removal.models.LogicalFallacy\u00b6\nclass langchain_experimental.fallacy_removal.models.LogicalFallacy[source]\u00b6\nBases: BaseModel\nClass for a logical fallacy.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam fallacy_critique_request: str [Required]\u00b6\nparam fallacy_revision_request: str [Required]\u00b6\nparam name: str = 'Logical Fallacy'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.models.LogicalFallacy.html"}
{"id": "d64d5da1fffa-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.models.LogicalFallacy.html"}
{"id": "d64d5da1fffa-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.models.LogicalFallacy.html"}
{"id": "e7a831cdfd5a-0", "text": "langchain.docstore.base.AddableMixin\u00b6\nclass langchain.docstore.base.AddableMixin[source]\u00b6\nMixin class that supports adding texts.\nMethods\n__init__()\nadd(texts)\nAdd more documents.\n__init__()\u00b6\nabstract add(texts: Dict[str, Document]) \u2192 None[source]\u00b6\nAdd more documents.", "source": "lang/api.python.langchain.com/en/latest/docstore/langchain.docstore.base.AddableMixin.html"}
{"id": "74110d2d2db8-0", "text": "langchain.docstore.in_memory.InMemoryDocstore\u00b6\nclass langchain.docstore.in_memory.InMemoryDocstore(_dict: Optional[Dict[str, Document]] = None)[source]\u00b6\nSimple in memory docstore in the form of a dict.\nInitialize with dict.\nMethods\n__init__([_dict])\nInitialize with dict.\nadd(texts)\nAdd texts to in memory dictionary.\ndelete(ids)\nDeleting IDs from in memory dictionary.\nsearch(search)\nSearch via direct lookup.\n__init__(_dict: Optional[Dict[str, Document]] = None)[source]\u00b6\nInitialize with dict.\nadd(texts: Dict[str, Document]) \u2192 None[source]\u00b6\nAdd texts to in memory dictionary.\nParameters\ntexts \u2013 dictionary of id -> document.\nReturns\nNone\ndelete(ids: List) \u2192 None[source]\u00b6\nDeleting IDs from in memory dictionary.\nsearch(search: str) \u2192 Union[str, Document][source]\u00b6\nSearch via direct lookup.\nParameters\nsearch \u2013 id of a document to search for.\nReturns\nDocument if found, else error message.\nExamples using InMemoryDocstore\u00b6\nAnnoy\nAgents\nAutoGPT\nBabyAGI User Guide\nBabyAGI with Tools\n!pip install bs4\nGenerative Agents in LangChain", "source": "lang/api.python.langchain.com/en/latest/docstore/langchain.docstore.in_memory.InMemoryDocstore.html"}
{"id": "b59520dd80b1-0", "text": "langchain.docstore.base.Docstore\u00b6\nclass langchain.docstore.base.Docstore[source]\u00b6\nInterface to access to place that stores documents.\nMethods\n__init__()\ndelete(ids)\nDeleting IDs from in memory dictionary.\nsearch(search)\nSearch for document.\n__init__()\u00b6\ndelete(ids: List) \u2192 None[source]\u00b6\nDeleting IDs from in memory dictionary.\nabstract search(search: str) \u2192 Union[str, Document][source]\u00b6\nSearch for document.\nIf page exists, return the page summary, and a Document object.\nIf page does not exist, return similar entries.", "source": "lang/api.python.langchain.com/en/latest/docstore/langchain.docstore.base.Docstore.html"}
{"id": "9f3215f34f46-0", "text": "langchain.docstore.arbitrary_fn.DocstoreFn\u00b6\nclass langchain.docstore.arbitrary_fn.DocstoreFn(lookup_fn: Callable[[str], Union[Document, str]])[source]\u00b6\nLangchain Docstore via arbitrary lookup function.\nThis is useful when:\nit\u2019s expensive to construct an InMemoryDocstore/dict\nyou retrieve documents from remote sources\nyou just want to reuse existing objects\nMethods\n__init__(lookup_fn)\ndelete(ids)\nDeleting IDs from in memory dictionary.\nsearch(search)\nSearch for a document.\n__init__(lookup_fn: Callable[[str], Union[Document, str]])[source]\u00b6\ndelete(ids: List) \u2192 None\u00b6\nDeleting IDs from in memory dictionary.\nsearch(search: str) \u2192 Document[source]\u00b6\nSearch for a document.\nParameters\nsearch \u2013 search string\nReturns\nDocument if found, else error message.", "source": "lang/api.python.langchain.com/en/latest/docstore/langchain.docstore.arbitrary_fn.DocstoreFn.html"}
{"id": "3829d822dc8a-0", "text": "langchain.docstore.wikipedia.Wikipedia\u00b6\nclass langchain.docstore.wikipedia.Wikipedia[source]\u00b6\nWrapper around wikipedia API.\nCheck that wikipedia package is installed.\nMethods\n__init__()\nCheck that wikipedia package is installed.\ndelete(ids)\nDeleting IDs from in memory dictionary.\nsearch(search)\nTry to search for wiki page.\n__init__() \u2192 None[source]\u00b6\nCheck that wikipedia package is installed.\ndelete(ids: List) \u2192 None\u00b6\nDeleting IDs from in memory dictionary.\nsearch(search: str) \u2192 Union[str, Document][source]\u00b6\nTry to search for wiki page.\nIf page exists, return the page summary, and a PageWithLookups object.\nIf page does not exist, return similar entries.\nParameters\nsearch \u2013 search string.\nReturns: a Document object or error message.", "source": "lang/api.python.langchain.com/en/latest/docstore/langchain.docstore.wikipedia.Wikipedia.html"}
{"id": "1fe204349dd6-0", "text": "langchain_experimental.open_clip.open_clip.OpenCLIPEmbeddings\u00b6\nclass langchain_experimental.open_clip.open_clip.OpenCLIPEmbeddings[source]\u00b6\nBases: BaseModel, Embeddings\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam model: Any = None\u00b6\nparam preprocess: Any = None\u00b6\nparam tokenizer: Any = None\u00b6\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float]\u00b6\nAsynchronous Embed query text.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/open_clip/langchain_experimental.open_clip.open_clip.OpenCLIPEmbeddings.html"}
{"id": "1fe204349dd6-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed search docs.\nembed_image(uris: List[str]) \u2192 List[List[float]][source]\u00b6\nembed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed query text.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/open_clip/langchain_experimental.open_clip.open_clip.OpenCLIPEmbeddings.html"}
{"id": "1fe204349dd6-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/open_clip/langchain_experimental.open_clip.open_clip.OpenCLIPEmbeddings.html"}
{"id": "0362f69c3592-0", "text": "langchain.text_splitter.Language\u00b6\nclass langchain.text_splitter.Language(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nEnum of the programming languages.\nCPP = 'cpp'\u00b6\nGO = 'go'\u00b6\nJAVA = 'java'\u00b6\nKOTLIN = 'kotlin'\u00b6\nJS = 'js'\u00b6\nTS = 'ts'\u00b6\nPHP = 'php'\u00b6\nPROTO = 'proto'\u00b6\nPYTHON = 'python'\u00b6\nRST = 'rst'\u00b6\nRUBY = 'ruby'\u00b6\nRUST = 'rust'\u00b6\nSCALA = 'scala'\u00b6\nSWIFT = 'swift'\u00b6\nMARKDOWN = 'markdown'\u00b6\nLATEX = 'latex'\u00b6\nHTML = 'html'\u00b6\nSOL = 'sol'\u00b6\nCSHARP = 'csharp'\u00b6\nCOBOL = 'cobol'\u00b6\nExamples using Language\u00b6\nSource Code\nSet env var OPENAI_API_KEY or load from a .env file", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.Language.html"}
{"id": "00baf3a322a5-0", "text": "langchain.text_splitter.TextSplitter\u00b6\nclass langchain.text_splitter.TextSplitter(chunk_size: int = 4000, chunk_overlap: int = 200, length_function: ~typing.Callable[[str], int] = <built-in function len>, keep_separator: bool = False, add_start_index: bool = False, strip_whitespace: bool = True)[source]\u00b6\nInterface for splitting text into chunks.\nCreate a new TextSplitter.\nParameters\nchunk_size \u2013 Maximum size of chunks to return\nchunk_overlap \u2013 Overlap in characters between chunks\nlength_function \u2013 Function that measures the length of given chunks\nkeep_separator \u2013 Whether to keep the separator in the chunks\nadd_start_index \u2013 If True, includes chunk\u2019s start index in metadata\nstrip_whitespace \u2013 If True, strips whitespace from the start and end of\nevery document\nMethods\n__init__([chunk_size,\u00a0chunk_overlap,\u00a0...])\nCreate a new TextSplitter.\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts[,\u00a0metadatas])\nCreate documents from a list of texts.\nfrom_huggingface_tokenizer(tokenizer,\u00a0**kwargs)\nText splitter that uses HuggingFace tokenizer to count length.\nfrom_tiktoken_encoder([encoding_name,\u00a0...])\nText splitter that uses tiktoken encoder to count length.\nsplit_documents(documents)\nSplit documents.\nsplit_text(text)\nSplit text into multiple components.\ntransform_documents(documents,\u00a0**kwargs)\nTransform sequence of documents by splitting them.", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.TextSplitter.html"}
{"id": "00baf3a322a5-1", "text": "transform_documents(documents,\u00a0**kwargs)\nTransform sequence of documents by splitting them.\n__init__(chunk_size: int = 4000, chunk_overlap: int = 200, length_function: ~typing.Callable[[str], int] = <built-in function len>, keep_separator: bool = False, add_start_index: bool = False, strip_whitespace: bool = True) \u2192 None[source]\u00b6\nCreate a new TextSplitter.\nParameters\nchunk_size \u2013 Maximum size of chunks to return\nchunk_overlap \u2013 Overlap in characters between chunks\nlength_function \u2013 Function that measures the length of given chunks\nkeep_separator \u2013 Whether to keep the separator in the chunks\nadd_start_index \u2013 If True, includes chunk\u2019s start index in metadata\nstrip_whitespace \u2013 If True, strips whitespace from the start and end of\nevery document\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts: List[str], metadatas: Optional[List[dict]] = None) \u2192 List[Document][source]\u00b6\nCreate documents from a list of texts.\nclassmethod from_huggingface_tokenizer(tokenizer: Any, **kwargs: Any) \u2192 TextSplitter[source]\u00b6\nText splitter that uses HuggingFace tokenizer to count length.\nclassmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any) \u2192 TS[source]\u00b6\nText splitter that uses tiktoken encoder to count length.\nsplit_documents(documents: Iterable[Document]) \u2192 List[Document][source]\u00b6\nSplit documents.", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.TextSplitter.html"}
{"id": "00baf3a322a5-2", "text": "Split documents.\nabstract split_text(text: str) \u2192 List[str][source]\u00b6\nSplit text into multiple components.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nTransform sequence of documents by splitting them.", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.TextSplitter.html"}
{"id": "fd1b208157a2-0", "text": "langchain.text_splitter.MarkdownTextSplitter\u00b6\nclass langchain.text_splitter.MarkdownTextSplitter(**kwargs: Any)[source]\u00b6\nAttempts to split the text along Markdown-formatted headings.\nInitialize a MarkdownTextSplitter.\nMethods\n__init__(**kwargs)\nInitialize a MarkdownTextSplitter.\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts[,\u00a0metadatas])\nCreate documents from a list of texts.\nfrom_huggingface_tokenizer(tokenizer,\u00a0**kwargs)\nText splitter that uses HuggingFace tokenizer to count length.\nfrom_language(language,\u00a0**kwargs)\nfrom_tiktoken_encoder([encoding_name,\u00a0...])\nText splitter that uses tiktoken encoder to count length.\nget_separators_for_language(language)\nsplit_documents(documents)\nSplit documents.\nsplit_text(text)\nSplit text into multiple components.\ntransform_documents(documents,\u00a0**kwargs)\nTransform sequence of documents by splitting them.\n__init__(**kwargs: Any) \u2192 None[source]\u00b6\nInitialize a MarkdownTextSplitter.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts: List[str], metadatas: Optional[List[dict]] = None) \u2192 List[Document]\u00b6\nCreate documents from a list of texts.\nclassmethod from_huggingface_tokenizer(tokenizer: Any, **kwargs: Any) \u2192 TextSplitter\u00b6\nText splitter that uses HuggingFace tokenizer to count length.\nclassmethod from_language(language: Language, **kwargs: Any) \u2192 RecursiveCharacterTextSplitter\u00b6", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.MarkdownTextSplitter.html"}
{"id": "fd1b208157a2-1", "text": "classmethod from_language(language: Language, **kwargs: Any) \u2192 RecursiveCharacterTextSplitter\u00b6\nclassmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any) \u2192 TS\u00b6\nText splitter that uses tiktoken encoder to count length.\nstatic get_separators_for_language(language: Language) \u2192 List[str]\u00b6\nsplit_documents(documents: Iterable[Document]) \u2192 List[Document]\u00b6\nSplit documents.\nsplit_text(text: str) \u2192 List[str]\u00b6\nSplit text into multiple components.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nTransform sequence of documents by splitting them.", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.MarkdownTextSplitter.html"}
{"id": "e72e3766df8b-0", "text": "langchain.text_splitter.RecursiveCharacterTextSplitter\u00b6\nclass langchain.text_splitter.RecursiveCharacterTextSplitter(separators: Optional[List[str]] = None, keep_separator: bool = True, is_separator_regex: bool = False, **kwargs: Any)[source]\u00b6\nSplitting text by recursively look at characters.\nRecursively tries to split by different characters to find one\nthat works.\nCreate a new TextSplitter.\nMethods\n__init__([separators,\u00a0keep_separator,\u00a0...])\nCreate a new TextSplitter.\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts[,\u00a0metadatas])\nCreate documents from a list of texts.\nfrom_huggingface_tokenizer(tokenizer,\u00a0**kwargs)\nText splitter that uses HuggingFace tokenizer to count length.\nfrom_language(language,\u00a0**kwargs)\nfrom_tiktoken_encoder([encoding_name,\u00a0...])\nText splitter that uses tiktoken encoder to count length.\nget_separators_for_language(language)\nsplit_documents(documents)\nSplit documents.\nsplit_text(text)\nSplit text into multiple components.\ntransform_documents(documents,\u00a0**kwargs)\nTransform sequence of documents by splitting them.\n__init__(separators: Optional[List[str]] = None, keep_separator: bool = True, is_separator_regex: bool = False, **kwargs: Any) \u2192 None[source]\u00b6\nCreate a new TextSplitter.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts: List[str], metadatas: Optional[List[dict]] = None) \u2192 List[Document]\u00b6\nCreate documents from a list of texts.", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.RecursiveCharacterTextSplitter.html"}
{"id": "e72e3766df8b-1", "text": "Create documents from a list of texts.\nclassmethod from_huggingface_tokenizer(tokenizer: Any, **kwargs: Any) \u2192 TextSplitter\u00b6\nText splitter that uses HuggingFace tokenizer to count length.\nclassmethod from_language(language: Language, **kwargs: Any) \u2192 RecursiveCharacterTextSplitter[source]\u00b6\nclassmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any) \u2192 TS\u00b6\nText splitter that uses tiktoken encoder to count length.\nstatic get_separators_for_language(language: Language) \u2192 List[str][source]\u00b6\nsplit_documents(documents: Iterable[Document]) \u2192 List[Document]\u00b6\nSplit documents.\nsplit_text(text: str) \u2192 List[str][source]\u00b6\nSplit text into multiple components.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nTransform sequence of documents by splitting them.\nExamples using RecursiveCharacterTextSplitter\u00b6\nRePhraseQueryRetriever\nCohere Reranker\nOllama\nZep\nyour local model path\nLoading documents from a YouTube url\nSource Code\nSet env var OPENAI_API_KEY or load from a .env file:\nSet env var OPENAI_API_KEY or load from a .env file\nQuestion Answering\nPerform context-aware text splitting\nUse local LLMs\nQA using Activeloop\u2019s DeepLake\n!pip install bs4\nMultiVector Retriever\nMultiQueryRetriever\nParent Document Retriever\nMarkdownHeaderTextSplitter", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.RecursiveCharacterTextSplitter.html"}
{"id": "fc8a473f9cca-0", "text": "langchain.text_splitter.MarkdownHeaderTextSplitter\u00b6\nclass langchain.text_splitter.MarkdownHeaderTextSplitter(headers_to_split_on: List[Tuple[str, str]], return_each_line: bool = False)[source]\u00b6\nSplitting markdown files based on specified headers.\nCreate a new MarkdownHeaderTextSplitter.\nParameters\nheaders_to_split_on \u2013 Headers we want to track\nreturn_each_line \u2013 Return each line w/ associated headers\nMethods\n__init__(headers_to_split_on[,\u00a0return_each_line])\nCreate a new MarkdownHeaderTextSplitter.\naggregate_lines_to_chunks(lines)\nCombine lines with common metadata into chunks :param lines: Line of text / associated header metadata\nsplit_text(text)\nSplit markdown file :param text: Markdown file\n__init__(headers_to_split_on: List[Tuple[str, str]], return_each_line: bool = False)[source]\u00b6\nCreate a new MarkdownHeaderTextSplitter.\nParameters\nheaders_to_split_on \u2013 Headers we want to track\nreturn_each_line \u2013 Return each line w/ associated headers\naggregate_lines_to_chunks(lines: List[LineType]) \u2192 List[Document][source]\u00b6\nCombine lines with common metadata into chunks\n:param lines: Line of text / associated header metadata\nsplit_text(text: str) \u2192 List[Document][source]\u00b6\nSplit markdown file\n:param text: Markdown file\nExamples using MarkdownHeaderTextSplitter\u00b6\nPerform context-aware text splitting\nMarkdownHeaderTextSplitter", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.MarkdownHeaderTextSplitter.html"}
{"id": "e7f32e57f238-0", "text": "langchain.text_splitter.LineType\u00b6\nclass langchain.text_splitter.LineType[source]\u00b6\nLine type as typed dict.\nmetadata: Dict[str, str]\u00b6\ncontent: str\u00b6", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.LineType.html"}
{"id": "e86cb026a162-0", "text": "langchain.text_splitter.HTMLHeaderTextSplitter\u00b6\nclass langchain.text_splitter.HTMLHeaderTextSplitter(headers_to_split_on: List[Tuple[str, str]], return_each_element: bool = False)[source]\u00b6\nSplitting HTML files based on specified headers.\nRequires lxml package.\nCreate a new HTMLHeaderTextSplitter.\nParameters\nheaders_to_split_on \u2013 list of tuples of headers we want to track mapped to\n(arbitrary) keys for metadata. Allowed header values: h1, h2, h3, h4,\nh5, h6 e.g. [(\u201ch1\u201d, \u201cHeader 1\u201d), (\u201ch2\u201d, \u201cHeader 2)].\nreturn_each_element \u2013 Return each element w/ associated headers.\nMethods\n__init__(headers_to_split_on[,\u00a0...])\nCreate a new HTMLHeaderTextSplitter.\naggregate_elements_to_chunks(elements)\nCombine elements with common metadata into chunks\nsplit_text(text)\nSplit HTML text string\nsplit_text_from_file(file)\nSplit HTML file\nsplit_text_from_url(url)\nSplit HTML from web URL\n__init__(headers_to_split_on: List[Tuple[str, str]], return_each_element: bool = False)[source]\u00b6\nCreate a new HTMLHeaderTextSplitter.\nParameters\nheaders_to_split_on \u2013 list of tuples of headers we want to track mapped to\n(arbitrary) keys for metadata. Allowed header values: h1, h2, h3, h4,\nh5, h6 e.g. [(\u201ch1\u201d, \u201cHeader 1\u201d), (\u201ch2\u201d, \u201cHeader 2)].\nreturn_each_element \u2013 Return each element w/ associated headers.\naggregate_elements_to_chunks(elements: List[ElementType]) \u2192 List[Document][source]\u00b6\nCombine elements with common metadata into chunks\nParameters\nelements \u2013 HTML element content with associated identifying info and metadata\nsplit_text(text: str) \u2192 List[Document][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.HTMLHeaderTextSplitter.html"}
{"id": "e86cb026a162-1", "text": "split_text(text: str) \u2192 List[Document][source]\u00b6\nSplit HTML text string\nParameters\ntext \u2013 HTML text\nsplit_text_from_file(file: Any) \u2192 List[Document][source]\u00b6\nSplit HTML file\nParameters\nfile \u2013 HTML file\nsplit_text_from_url(url: str) \u2192 List[Document][source]\u00b6\nSplit HTML from web URL\nParameters\nurl \u2013 web URL", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.HTMLHeaderTextSplitter.html"}
{"id": "c68b94aa74d4-0", "text": "langchain.text_splitter.SentenceTransformersTokenTextSplitter\u00b6\nclass langchain.text_splitter.SentenceTransformersTokenTextSplitter(chunk_overlap: int = 50, model_name: str = 'sentence-transformers/all-mpnet-base-v2', tokens_per_chunk: Optional[int] = None, **kwargs: Any)[source]\u00b6\nSplitting text to tokens using sentence model tokenizer.\nCreate a new TextSplitter.\nMethods\n__init__([chunk_overlap,\u00a0model_name,\u00a0...])\nCreate a new TextSplitter.\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a sequence of documents by splitting them.\ncount_tokens(*,\u00a0text)\ncreate_documents(texts[,\u00a0metadatas])\nCreate documents from a list of texts.\nfrom_huggingface_tokenizer(tokenizer,\u00a0**kwargs)\nText splitter that uses HuggingFace tokenizer to count length.\nfrom_tiktoken_encoder([encoding_name,\u00a0...])\nText splitter that uses tiktoken encoder to count length.\nsplit_documents(documents)\nSplit documents.\nsplit_text(text)\nSplit text into multiple components.\ntransform_documents(documents,\u00a0**kwargs)\nTransform sequence of documents by splitting them.\n__init__(chunk_overlap: int = 50, model_name: str = 'sentence-transformers/all-mpnet-base-v2', tokens_per_chunk: Optional[int] = None, **kwargs: Any) \u2192 None[source]\u00b6\nCreate a new TextSplitter.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nAsynchronously transform a sequence of documents by splitting them.\ncount_tokens(*, text: str) \u2192 int[source]\u00b6\ncreate_documents(texts: List[str], metadatas: Optional[List[dict]] = None) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.SentenceTransformersTokenTextSplitter.html"}
{"id": "c68b94aa74d4-1", "text": "Create documents from a list of texts.\nclassmethod from_huggingface_tokenizer(tokenizer: Any, **kwargs: Any) \u2192 TextSplitter\u00b6\nText splitter that uses HuggingFace tokenizer to count length.\nclassmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any) \u2192 TS\u00b6\nText splitter that uses tiktoken encoder to count length.\nsplit_documents(documents: Iterable[Document]) \u2192 List[Document]\u00b6\nSplit documents.\nsplit_text(text: str) \u2192 List[str][source]\u00b6\nSplit text into multiple components.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nTransform sequence of documents by splitting them.\nExamples using SentenceTransformersTokenTextSplitter\u00b6\nSplit by tokens", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.SentenceTransformersTokenTextSplitter.html"}
{"id": "65763b265155-0", "text": "langchain.text_splitter.PythonCodeTextSplitter\u00b6\nclass langchain.text_splitter.PythonCodeTextSplitter(**kwargs: Any)[source]\u00b6\nAttempts to split the text along Python syntax.\nInitialize a PythonCodeTextSplitter.\nMethods\n__init__(**kwargs)\nInitialize a PythonCodeTextSplitter.\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts[,\u00a0metadatas])\nCreate documents from a list of texts.\nfrom_huggingface_tokenizer(tokenizer,\u00a0**kwargs)\nText splitter that uses HuggingFace tokenizer to count length.\nfrom_language(language,\u00a0**kwargs)\nfrom_tiktoken_encoder([encoding_name,\u00a0...])\nText splitter that uses tiktoken encoder to count length.\nget_separators_for_language(language)\nsplit_documents(documents)\nSplit documents.\nsplit_text(text)\nSplit text into multiple components.\ntransform_documents(documents,\u00a0**kwargs)\nTransform sequence of documents by splitting them.\n__init__(**kwargs: Any) \u2192 None[source]\u00b6\nInitialize a PythonCodeTextSplitter.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts: List[str], metadatas: Optional[List[dict]] = None) \u2192 List[Document]\u00b6\nCreate documents from a list of texts.\nclassmethod from_huggingface_tokenizer(tokenizer: Any, **kwargs: Any) \u2192 TextSplitter\u00b6\nText splitter that uses HuggingFace tokenizer to count length.\nclassmethod from_language(language: Language, **kwargs: Any) \u2192 RecursiveCharacterTextSplitter\u00b6", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.PythonCodeTextSplitter.html"}
{"id": "65763b265155-1", "text": "classmethod from_language(language: Language, **kwargs: Any) \u2192 RecursiveCharacterTextSplitter\u00b6\nclassmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any) \u2192 TS\u00b6\nText splitter that uses tiktoken encoder to count length.\nstatic get_separators_for_language(language: Language) \u2192 List[str]\u00b6\nsplit_documents(documents: Iterable[Document]) \u2192 List[Document]\u00b6\nSplit documents.\nsplit_text(text: str) \u2192 List[str]\u00b6\nSplit text into multiple components.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nTransform sequence of documents by splitting them.", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.PythonCodeTextSplitter.html"}
{"id": "082d37da4b5f-0", "text": "langchain.text_splitter.SpacyTextSplitter\u00b6\nclass langchain.text_splitter.SpacyTextSplitter(separator: str = '\\n\\n', pipeline: str = 'en_core_web_sm', **kwargs: Any)[source]\u00b6\nSplitting text using Spacy package.\nPer default, Spacy\u2019s en_core_web_sm model is used. For a faster, but\npotentially less accurate splitting, you can use pipeline=\u2019sentencizer\u2019.\nInitialize the spacy text splitter.\nMethods\n__init__([separator,\u00a0pipeline])\nInitialize the spacy text splitter.\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts[,\u00a0metadatas])\nCreate documents from a list of texts.\nfrom_huggingface_tokenizer(tokenizer,\u00a0**kwargs)\nText splitter that uses HuggingFace tokenizer to count length.\nfrom_tiktoken_encoder([encoding_name,\u00a0...])\nText splitter that uses tiktoken encoder to count length.\nsplit_documents(documents)\nSplit documents.\nsplit_text(text)\nSplit incoming text and return chunks.\ntransform_documents(documents,\u00a0**kwargs)\nTransform sequence of documents by splitting them.\n__init__(separator: str = '\\n\\n', pipeline: str = 'en_core_web_sm', **kwargs: Any) \u2192 None[source]\u00b6\nInitialize the spacy text splitter.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts: List[str], metadatas: Optional[List[dict]] = None) \u2192 List[Document]\u00b6\nCreate documents from a list of texts.\nclassmethod from_huggingface_tokenizer(tokenizer: Any, **kwargs: Any) \u2192 TextSplitter\u00b6", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.SpacyTextSplitter.html"}
{"id": "082d37da4b5f-1", "text": "Text splitter that uses HuggingFace tokenizer to count length.\nclassmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any) \u2192 TS\u00b6\nText splitter that uses tiktoken encoder to count length.\nsplit_documents(documents: Iterable[Document]) \u2192 List[Document]\u00b6\nSplit documents.\nsplit_text(text: str) \u2192 List[str][source]\u00b6\nSplit incoming text and return chunks.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nTransform sequence of documents by splitting them.\nExamples using SpacyTextSplitter\u00b6\nspaCy\nAtlas\nSplit by tokens", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.SpacyTextSplitter.html"}
{"id": "2c4976b39995-0", "text": "langchain.text_splitter.NLTKTextSplitter\u00b6\nclass langchain.text_splitter.NLTKTextSplitter(separator: str = '\\n\\n', language: str = 'english', **kwargs: Any)[source]\u00b6\nSplitting text using NLTK package.\nInitialize the NLTK splitter.\nMethods\n__init__([separator,\u00a0language])\nInitialize the NLTK splitter.\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts[,\u00a0metadatas])\nCreate documents from a list of texts.\nfrom_huggingface_tokenizer(tokenizer,\u00a0**kwargs)\nText splitter that uses HuggingFace tokenizer to count length.\nfrom_tiktoken_encoder([encoding_name,\u00a0...])\nText splitter that uses tiktoken encoder to count length.\nsplit_documents(documents)\nSplit documents.\nsplit_text(text)\nSplit incoming text and return chunks.\ntransform_documents(documents,\u00a0**kwargs)\nTransform sequence of documents by splitting them.\n__init__(separator: str = '\\n\\n', language: str = 'english', **kwargs: Any) \u2192 None[source]\u00b6\nInitialize the NLTK splitter.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts: List[str], metadatas: Optional[List[dict]] = None) \u2192 List[Document]\u00b6\nCreate documents from a list of texts.\nclassmethod from_huggingface_tokenizer(tokenizer: Any, **kwargs: Any) \u2192 TextSplitter\u00b6\nText splitter that uses HuggingFace tokenizer to count length.", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.NLTKTextSplitter.html"}
{"id": "2c4976b39995-1", "text": "Text splitter that uses HuggingFace tokenizer to count length.\nclassmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any) \u2192 TS\u00b6\nText splitter that uses tiktoken encoder to count length.\nsplit_documents(documents: Iterable[Document]) \u2192 List[Document]\u00b6\nSplit documents.\nsplit_text(text: str) \u2192 List[str][source]\u00b6\nSplit incoming text and return chunks.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nTransform sequence of documents by splitting them.\nExamples using NLTKTextSplitter\u00b6\nSplit by tokens", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.NLTKTextSplitter.html"}
{"id": "7ddb0f2dd656-0", "text": "langchain.text_splitter.LatexTextSplitter\u00b6\nclass langchain.text_splitter.LatexTextSplitter(**kwargs: Any)[source]\u00b6\nAttempts to split the text along Latex-formatted layout elements.\nInitialize a LatexTextSplitter.\nMethods\n__init__(**kwargs)\nInitialize a LatexTextSplitter.\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts[,\u00a0metadatas])\nCreate documents from a list of texts.\nfrom_huggingface_tokenizer(tokenizer,\u00a0**kwargs)\nText splitter that uses HuggingFace tokenizer to count length.\nfrom_language(language,\u00a0**kwargs)\nfrom_tiktoken_encoder([encoding_name,\u00a0...])\nText splitter that uses tiktoken encoder to count length.\nget_separators_for_language(language)\nsplit_documents(documents)\nSplit documents.\nsplit_text(text)\nSplit text into multiple components.\ntransform_documents(documents,\u00a0**kwargs)\nTransform sequence of documents by splitting them.\n__init__(**kwargs: Any) \u2192 None[source]\u00b6\nInitialize a LatexTextSplitter.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts: List[str], metadatas: Optional[List[dict]] = None) \u2192 List[Document]\u00b6\nCreate documents from a list of texts.\nclassmethod from_huggingface_tokenizer(tokenizer: Any, **kwargs: Any) \u2192 TextSplitter\u00b6\nText splitter that uses HuggingFace tokenizer to count length.\nclassmethod from_language(language: Language, **kwargs: Any) \u2192 RecursiveCharacterTextSplitter\u00b6", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.LatexTextSplitter.html"}
{"id": "7ddb0f2dd656-1", "text": "classmethod from_language(language: Language, **kwargs: Any) \u2192 RecursiveCharacterTextSplitter\u00b6\nclassmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any) \u2192 TS\u00b6\nText splitter that uses tiktoken encoder to count length.\nstatic get_separators_for_language(language: Language) \u2192 List[str]\u00b6\nsplit_documents(documents: Iterable[Document]) \u2192 List[Document]\u00b6\nSplit documents.\nsplit_text(text: str) \u2192 List[str]\u00b6\nSplit text into multiple components.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nTransform sequence of documents by splitting them.", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.LatexTextSplitter.html"}
{"id": "07cd57351492-0", "text": "langchain.text_splitter.Tokenizer\u00b6\nclass langchain.text_splitter.Tokenizer(chunk_overlap: int, tokens_per_chunk: int, decode: Callable[[List[int]], str], encode: Callable[[str], List[int]])[source]\u00b6\nTokenizer data class.\nAttributes\nchunk_overlap\nOverlap in tokens between chunks\ntokens_per_chunk\nMaximum number of tokens per chunk\ndecode\nFunction to decode a list of token ids to a string\nencode\nFunction to encode a string to a list of token ids\nMethods\n__init__(chunk_overlap,\u00a0tokens_per_chunk,\u00a0...)\n__init__(chunk_overlap: int, tokens_per_chunk: int, decode: Callable[[List[int]], str], encode: Callable[[str], List[int]]) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.Tokenizer.html"}
{"id": "ac102e292f04-0", "text": "langchain.text_splitter.TokenTextSplitter\u00b6\nclass langchain.text_splitter.TokenTextSplitter(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any)[source]\u00b6\nSplitting text to tokens using model tokenizer.\nCreate a new TextSplitter.\nMethods\n__init__([encoding_name,\u00a0model_name,\u00a0...])\nCreate a new TextSplitter.\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts[,\u00a0metadatas])\nCreate documents from a list of texts.\nfrom_huggingface_tokenizer(tokenizer,\u00a0**kwargs)\nText splitter that uses HuggingFace tokenizer to count length.\nfrom_tiktoken_encoder([encoding_name,\u00a0...])\nText splitter that uses tiktoken encoder to count length.\nsplit_documents(documents)\nSplit documents.\nsplit_text(text)\nSplit text into multiple components.\ntransform_documents(documents,\u00a0**kwargs)\nTransform sequence of documents by splitting them.\n__init__(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any) \u2192 None[source]\u00b6\nCreate a new TextSplitter.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts: List[str], metadatas: Optional[List[dict]] = None) \u2192 List[Document]\u00b6", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.TokenTextSplitter.html"}
{"id": "ac102e292f04-1", "text": "Create documents from a list of texts.\nclassmethod from_huggingface_tokenizer(tokenizer: Any, **kwargs: Any) \u2192 TextSplitter\u00b6\nText splitter that uses HuggingFace tokenizer to count length.\nclassmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any) \u2192 TS\u00b6\nText splitter that uses tiktoken encoder to count length.\nsplit_documents(documents: Iterable[Document]) \u2192 List[Document]\u00b6\nSplit documents.\nsplit_text(text: str) \u2192 List[str][source]\u00b6\nSplit text into multiple components.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nTransform sequence of documents by splitting them.\nExamples using TokenTextSplitter\u00b6\nStarRocks\nSplit by tokens", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.TokenTextSplitter.html"}
{"id": "9fbbb3514599-0", "text": "langchain.text_splitter.ElementType\u00b6\nclass langchain.text_splitter.ElementType[source]\u00b6\nElement type as typed dict.\nurl: str\u00b6\nxpath: str\u00b6\ncontent: str\u00b6\nmetadata: Dict[str, str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.ElementType.html"}
{"id": "8e0c909da5fb-0", "text": "langchain.text_splitter.HeaderType\u00b6\nclass langchain.text_splitter.HeaderType[source]\u00b6\nHeader type as typed dict.\nlevel: int\u00b6\nname: str\u00b6\ndata: str\u00b6", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.HeaderType.html"}
{"id": "102b9a581418-0", "text": "langchain.text_splitter.split_text_on_tokens\u00b6\nlangchain.text_splitter.split_text_on_tokens(*, text: str, tokenizer: Tokenizer) \u2192 List[str][source]\u00b6\nSplit incoming text and return chunks using tokenizer.", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.split_text_on_tokens.html"}
{"id": "bc4fa8ec001f-0", "text": "langchain.text_splitter.CharacterTextSplitter\u00b6\nclass langchain.text_splitter.CharacterTextSplitter(separator: str = '\\n\\n', is_separator_regex: bool = False, **kwargs: Any)[source]\u00b6\nSplitting text that looks at characters.\nCreate a new TextSplitter.\nMethods\n__init__([separator,\u00a0is_separator_regex])\nCreate a new TextSplitter.\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts[,\u00a0metadatas])\nCreate documents from a list of texts.\nfrom_huggingface_tokenizer(tokenizer,\u00a0**kwargs)\nText splitter that uses HuggingFace tokenizer to count length.\nfrom_tiktoken_encoder([encoding_name,\u00a0...])\nText splitter that uses tiktoken encoder to count length.\nsplit_documents(documents)\nSplit documents.\nsplit_text(text)\nSplit incoming text and return chunks.\ntransform_documents(documents,\u00a0**kwargs)\nTransform sequence of documents by splitting them.\n__init__(separator: str = '\\n\\n', is_separator_regex: bool = False, **kwargs: Any) \u2192 None[source]\u00b6\nCreate a new TextSplitter.\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nAsynchronously transform a sequence of documents by splitting them.\ncreate_documents(texts: List[str], metadatas: Optional[List[dict]] = None) \u2192 List[Document]\u00b6\nCreate documents from a list of texts.\nclassmethod from_huggingface_tokenizer(tokenizer: Any, **kwargs: Any) \u2192 TextSplitter\u00b6\nText splitter that uses HuggingFace tokenizer to count length.", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.CharacterTextSplitter.html"}
{"id": "bc4fa8ec001f-1", "text": "Text splitter that uses HuggingFace tokenizer to count length.\nclassmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any) \u2192 TS\u00b6\nText splitter that uses tiktoken encoder to count length.\nsplit_documents(documents: Iterable[Document]) \u2192 List[Document]\u00b6\nSplit documents.\nsplit_text(text: str) \u2192 List[str][source]\u00b6\nSplit incoming text and return chunks.\ntransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document]\u00b6\nTransform sequence of documents by splitting them.\nExamples using CharacterTextSplitter\u00b6\nConfident\nHugging Face\nOpenAI\nElasticsearch\nVectara Text Generation\nDocument Comparison\nVectorstore\nLanceDB\nsqlite-vss\nWeaviate\nDashVector\nScaNN\nXata\nVectara\nPGVector\nRockset\nDingoDB\nZilliz\nSingleStoreDB\nAnnoy\nTypesense\nActiveloop Deep Lake\nNeo4j Vector Index\nTair\nChroma\nAlibaba Cloud OpenSearch\nBaidu Cloud VectorSearch\nStarRocks\nscikit-learn\nTencent Cloud VectorDB\nDocArray HnswSearch\nMyScale\nClickHouse\nQdrant\nTigris\nAwaDB\nSupabase (Postgres)\nOpenSearch\nPinecone\nBagelDB\nAzure Cognitive Search\nCassandra\nUSearch\nMilvus\nMarqo\nDocArray InMemorySearch\nPostgres Embedding\nFaiss\nEpsilla\nAnalyticDB\nHologres\nMongoDB Atlas\nMeilisearch\nFigma\nPsychic\nManifest", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.CharacterTextSplitter.html"}
{"id": "bc4fa8ec001f-2", "text": "MongoDB Atlas\nMeilisearch\nFigma\nPsychic\nManifest\nLLM Caching integrations\nSet env var OPENAI_API_KEY or load from a .env file\nConversational Retrieval Agent\nRetrieve from vector stores directly\nImprove document indexing with HyDE\nAnalysis of Twitter the-algorithm source code with LangChain, GPT4 and Activeloop\u2019s Deep Lake\nUse LangChain, GPT and Activeloop\u2019s Deep Lake to work with code base\nStructure answers with OpenAI functions\nQA using Activeloop\u2019s DeepLake\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nIndexing\nCaching\nSplit by tokens \nMemory in the Multi-Input Chain\nCombine agents and vector stores\nLoading from LangChainHub", "source": "lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.CharacterTextSplitter.html"}
{"id": "4f5a09aef4b4-0", "text": "langchain.hub.pull\u00b6\nlangchain.hub.pull(owner_repo_commit: str, *, api_url: Optional[str] = None, api_key: Optional[str] = None) \u2192 Any[source]\u00b6\nPulls an object from the hub and returns it as a LangChain object.\nParameters\nowner_repo_commit \u2013 The full name of the repo to pull from in the format of\nowner/repo:commit_hash.\napi_url \u2013 The URL of the LangChain Hub API. Defaults to the hosted API service\nif you have an api key set, or a localhost instance if not.\napi_key \u2013 The API key to use to authenticate with the LangChain Hub API.", "source": "lang/api.python.langchain.com/en/latest/hub/langchain.hub.pull.html"}
{"id": "884cb0457d4d-0", "text": "langchain.hub.push\u00b6\nlangchain.hub.push(repo_full_name: str, object: Any, *, api_url: Optional[str] = None, api_key: Optional[str] = None, parent_commit_hash: Optional[str] = 'latest', new_repo_is_public: bool = True, new_repo_description: str = '') \u2192 str[source]\u00b6\nPushes an object to the hub and returns the URL it can be viewed at in a browser.\nParameters\nrepo_full_name \u2013 The full name of the repo to push to in the format of\nowner/repo.\nobject \u2013 The LangChain to serialize and push to the hub.\napi_url \u2013 The URL of the LangChain Hub API. Defaults to the hosted API service\nif you have an api key set, or a localhost instance if not.\napi_key \u2013 The API key to use to authenticate with the LangChain Hub API.\nparent_commit_hash \u2013 The commit hash of the parent commit to push to. Defaults\nto the latest commit automatically.\nnew_repo_is_public \u2013 Whether the repo should be public. Defaults to\nTrue (Public by default).\nnew_repo_description \u2013 The description of the repo. Defaults to an empty\nstring.", "source": "lang/api.python.langchain.com/en/latest/hub/langchain.hub.push.html"}
{"id": "f5f8e22590b4-0", "text": "langchain.smith.evaluation.runner_utils.TestResult\u00b6\nclass langchain.smith.evaluation.runner_utils.TestResult[source]\u00b6\nA dictionary of the results of a single test run.\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nget_aggregate_feedback([quantiles])\nReturn quantiles for the feedback scores.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nto_dataframe()\nConvert the results to a dataframe.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.runner_utils.TestResult.html"}
{"id": "f5f8e22590b4-1", "text": "Return the value for key if key is in the dictionary, else default.\nget_aggregate_feedback(quantiles: Optional[Sequence[float]] = None) \u2192 pd.DataFrame[source]\u00b6\nReturn quantiles for the feedback scores.\nThis method calculates and prints the quantiles for the feedback scores\nacross all feedback keys.\nReturns\nA DataFrame containing the quantiles for each feedback key.\nitems() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nto_dataframe() \u2192 pd.DataFrame[source]\u00b6\nConvert the results to a dataframe.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.runner_utils.TestResult.html"}
{"id": "b7b6d8b0c672-0", "text": "langchain.smith.evaluation.config.EvalConfig\u00b6\nclass langchain.smith.evaluation.config.EvalConfig[source]\u00b6\nBases: BaseModel\nConfiguration for a given run evaluator.\nParameters\nevaluator_type (EvaluatorType) \u2013 The type of evaluator to use.\nget_kwargs()[source]\u00b6\nGet the keyword arguments for the evaluator configuration.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.EvalConfig.html"}
{"id": "b7b6d8b0c672-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any][source]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.EvalConfig.html"}
{"id": "b7b6d8b0c672-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.EvalConfig.html"}
{"id": "c6bee0e41e99-0", "text": "langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain\u00b6\nclass langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain[source]\u00b6\nBases: Chain, RunEvaluator\nEvaluate Run and optional examples.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam example_mapper: Optional[StringExampleMapper] = None\u00b6\nMaps the Example (dataset row) to a dictionary\nwith a \u2018reference\u2019 string.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam name: str [Required]\u00b6\nThe name of the evaluation metric.\nparam run_mapper: StringRunMapper [Required]\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-1", "text": "The name of the evaluation metric.\nparam run_mapper: StringRunMapper [Required]\u00b6\nMaps the Run to a dictionary with \u2018input\u2019 and \u2018prediction\u2019 strings.\nparam string_evaluator: StringEvaluator [Required]\u00b6\nThe evaluation chain.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-2", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-3", "text": "response. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync aevaluate_run(run: Run, example: Optional[Example] = None) \u2192 EvaluationResult[source]\u00b6\nEvaluate an example.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-4", "text": "Convenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nevaluate_run(run: Run, example: Optional[Example] = None) \u2192 EvaluationResult[source]\u00b6\nEvaluate an example.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_run_and_data_type(evaluator: StringEvaluator, run_type: str, data_type: DataType, input_key: Optional[str] = None, prediction_key: Optional[str] = None, reference_key: Optional[str] = None, tags: Optional[List[str]] = None) \u2192 StringRunEvaluatorChain[source]\u00b6\nCreate a StringRunEvaluatorChain from an evaluator and the run and dataset types.\nThis method provides an easy way to instantiate a StringRunEvaluatorChain, by\ntaking an evaluator and information about the type of run and the data.\nThe method supports LLM and chain runs.\nParameters\nevaluator (StringEvaluator) \u2013 The string evaluator to use.\nrun_type (str) \u2013 The type of run being evaluated.\nSupported types are LLM and Chain.\ndata_type (DataType) \u2013 The type of dataset used in the run.\ninput_key (str, optional) \u2013 The key used to map the input from the run.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-8", "text": "input_key (str, optional) \u2013 The key used to map the input from the run.\nprediction_key (str, optional) \u2013 The key used to map the prediction from the run.\nreference_key (str, optional) \u2013 The key used to map the reference from the dataset.\ntags (List[str], optional) \u2013 List of tags to attach to the evaluation chain.\nReturns\nThe instantiated evaluation chain.\nReturn type\nStringRunEvaluatorChain\nRaises\nValueError \u2013 If the run type is not supported, or if the evaluator requires a\n    reference from the dataset but the reference key is not provided.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-9", "text": "This method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-10", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-11", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-12", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-13", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "c6bee0e41e99-14", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nKeys expected to be in the chain input.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nKeys expected to be in the chain output.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunEvaluatorChain.html"}
{"id": "d878661438b2-0", "text": "langchain.smith.evaluation.string_run_evaluator.ChainStringRunMapper\u00b6\nclass langchain.smith.evaluation.string_run_evaluator.ChainStringRunMapper[source]\u00b6\nBases: StringRunMapper\nExtract items to evaluate from the run object from a chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam input_key: Optional[str] = None\u00b6\nThe key from the model Run\u2019s inputs to use as the eval input.\nIf not provided, will use the only input key or raise an\nerror if there are multiple.\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the model Run\u2019s outputs to use as the eval prediction.\nIf not provided, will use the only output key or raise an error\nif there are multiple.\n__call__(run: Run) \u2192 Dict[str, str]\u00b6\nMaps the Run to a dictionary.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.ChainStringRunMapper.html"}
{"id": "d878661438b2-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.ChainStringRunMapper.html"}
{"id": "d878661438b2-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap(run: Run) \u2192 Dict[str, str][source]\u00b6\nMaps the Run to a dictionary.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.ChainStringRunMapper.html"}
{"id": "d878661438b2-3", "text": "For example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nThe keys to extract from the run.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.ChainStringRunMapper.html"}
{"id": "c1d39b3b03e1-0", "text": "langchain.smith.evaluation.string_run_evaluator.LLMStringRunMapper\u00b6\nclass langchain.smith.evaluation.string_run_evaluator.LLMStringRunMapper[source]\u00b6\nBases: StringRunMapper\nExtract items to evaluate from the run object.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\n__call__(run: Run) \u2192 Dict[str, str]\u00b6\nMaps the Run to a dictionary.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.LLMStringRunMapper.html"}
{"id": "c1d39b3b03e1-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.LLMStringRunMapper.html"}
{"id": "c1d39b3b03e1-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap(run: Run) \u2192 Dict[str, str][source]\u00b6\nMaps the Run to a dictionary.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nserialize_chat_messages(messages: List[Dict]) \u2192 str[source]\u00b6\nExtract the input messages from the run.\nserialize_inputs(inputs: Dict) \u2192 str[source]\u00b6\nserialize_outputs(outputs: Dict) \u2192 str[source]\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.LLMStringRunMapper.html"}
{"id": "c1d39b3b03e1-3", "text": "property output_keys: List[str]\u00b6\nThe keys to extract from the run.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.LLMStringRunMapper.html"}
{"id": "3ccdfd4e760f-0", "text": "langchain.smith.evaluation.config.RunEvalConfig\u00b6\nclass langchain.smith.evaluation.config.RunEvalConfig[source]\u00b6\nBases: BaseModel\nConfiguration for a run evaluation.\nParameters\nevaluators (List[Union[EvaluatorType, EvalConfig]]) \u2013 Configurations for which evaluators to apply to the dataset run.\nEach can be the string of an EvaluatorType, such\nas EvaluatorType.QA, the evaluator type string (\u201cqa\u201d), or a configuration for a\ngiven evaluator (e.g., RunEvalConfig.QA).\ncustom_evaluators (Optional[List[Union[RunEvaluator, StringEvaluator]]]) \u2013 Custom evaluators to apply to the dataset run.\nreference_key (Optional[str]) \u2013 The key in the dataset run to use as the reference string.\nIf not provided, it will be inferred automatically.\nprediction_key (Optional[str]) \u2013 The key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\ninput_key (Optional[str]) \u2013 The key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\neval_llm (Optional[BaseLanguageModel]) \u2013 The language model to pass to any evaluators that use a language model.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam custom_evaluators: Optional[List[Union[langsmith.evaluation.evaluator.RunEvaluator, langchain.evaluation.schema.StringEvaluator]]] = None\u00b6\nCustom evaluators to apply to the dataset run.\nparam eval_llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nThe language model to pass to any evaluators that require one.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-1", "text": "The language model to pass to any evaluators that require one.\nparam evaluators: List[Union[langchain.evaluation.schema.EvaluatorType, str, langchain.smith.evaluation.config.EvalConfig]] [Optional]\u00b6\nConfigurations for which evaluators to apply to the dataset run.\nEach can be the string of an\nEvaluatorType, such\nas EvaluatorType.QA, the evaluator type string (\u201cqa\u201d), or a configuration for a\ngiven evaluator\n(e.g.,\nRunEvalConfig.QA).\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclass CoTQA[source]\u00b6\nBases: SingleKeyEvalConfig\nConfiguration for a context-based QA evaluator.\nParameters\nprompt (Optional[BasePromptTemplate]) \u2013 The prompt template to use for generating the question.\nllm (Optional[BaseLanguageModel]) \u2013 The language model to use for the evaluation chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType = EvaluatorType.CONTEXT_QA\u00b6\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-2", "text": "input. If not provided, it will be inferred automatically.\nparam llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam prompt: Optional[langchain.schema.prompt_template.BasePromptTemplate] = None\u00b6\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-3", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-4", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclass ContextQA[source]\u00b6\nBases: SingleKeyEvalConfig\nConfiguration for a context-based QA evaluator.\nParameters\nprompt (Optional[BasePromptTemplate]) \u2013 The prompt template to use for generating the question.\nllm (Optional[BaseLanguageModel]) \u2013 The language model to use for the evaluation chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType = EvaluatorType.CONTEXT_QA\u00b6\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\nparam llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam prompt: Optional[langchain.schema.prompt_template.BasePromptTemplate] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-5", "text": "param prompt: Optional[langchain.schema.prompt_template.BasePromptTemplate] = None\u00b6\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-6", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-7", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclass Criteria[source]\u00b6\nBases: SingleKeyEvalConfig\nConfiguration for a reference-free criteria evaluator.\nParameters\ncriteria (Optional[CRITERIA_TYPE]) \u2013 The criteria to evaluate.\nllm (Optional[BaseLanguageModel]) \u2013 The language model to use for the evaluation chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam criteria: Optional[Union[Mapping[str, str], langchain.evaluation.criteria.eval_chain.Criteria, langchain.chains.constitutional_ai.models.ConstitutionalPrinciple]] = None\u00b6\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType = EvaluatorType.CRITERIA\u00b6\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\nparam llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-8", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-9", "text": "The keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclass EmbeddingDistance[source]\u00b6\nBases: SingleKeyEvalConfig\nConfiguration for an embedding distance evaluator.\nParameters", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-10", "text": "Bases: SingleKeyEvalConfig\nConfiguration for an embedding distance evaluator.\nParameters\nembeddings (Optional[Embeddings]) \u2013 The embeddings to use for computing the distance.\ndistance_metric (Optional[EmbeddingDistanceEnum]) \u2013 The distance metric to use for computing the distance.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam distance_metric: Optional[langchain.evaluation.embedding_distance.base.EmbeddingDistance] = None\u00b6\nparam embeddings: Optional[langchain.schema.embeddings.Embeddings] = None\u00b6\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType = EvaluatorType.EMBEDDING_DISTANCE\u00b6\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-11", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-12", "text": "The keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclass ExactMatch[source]\u00b6\nBases: SingleKeyEvalConfig\nConfiguration for an exact match string evaluator.\nParameters", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-13", "text": "Bases: SingleKeyEvalConfig\nConfiguration for an exact match string evaluator.\nParameters\nignore_case (bool) \u2013 Whether to ignore case when comparing strings.\nignore_punctuation (bool) \u2013 Whether to ignore punctuation when comparing strings.\nignore_numbers (bool) \u2013 Whether to ignore numbers when comparing strings.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType = EvaluatorType.STRING_DISTANCE\u00b6\nparam ignore_case: bool = False\u00b6\nparam ignore_numbers: bool = False\u00b6\nparam ignore_punctuation: bool = False\u00b6\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-14", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-15", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclass JsonEqualityEvaluator[source]\u00b6\nBases: EvalConfig\nConfiguration for a json equality evaluator.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType = EvaluatorType.JSON_EQUALITY\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-16", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-17", "text": "The keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclass JsonValidity[source]\u00b6\nBases: SingleKeyEvalConfig\nConfiguration for a json validity evaluator.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-18", "text": "Bases: SingleKeyEvalConfig\nConfiguration for a json validity evaluator.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType = EvaluatorType.JSON_VALIDITY\u00b6\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-19", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-20", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclass LabeledCriteria[source]\u00b6\nBases: SingleKeyEvalConfig\nConfiguration for a labeled (with references) criteria evaluator.\nParameters\ncriteria (Optional[CRITERIA_TYPE]) \u2013 The criteria to evaluate.\nllm (Optional[BaseLanguageModel]) \u2013 The language model to use for the evaluation chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam criteria: Optional[Union[Mapping[str, str], langchain.evaluation.criteria.eval_chain.Criteria, langchain.chains.constitutional_ai.models.ConstitutionalPrinciple]] = None\u00b6\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType = EvaluatorType.LABELED_CRITERIA\u00b6\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\nparam llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nparam prediction_key: Optional[str] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-21", "text": "param prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-22", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-23", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclass LabeledScoreString[source]\u00b6\nBases: ScoreString\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam criteria: Optional[Union[Mapping[str, str], langchain.evaluation.criteria.eval_chain.Criteria, langchain.chains.constitutional_ai.models.ConstitutionalPrinciple]] = None\u00b6\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType = EvaluatorType.LABELED_SCORE_STRING\u00b6\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\nparam llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nparam normalize_by: Optional[float] = None\u00b6\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam prompt: Optional[langchain.schema.prompt_template.BasePromptTemplate] = None\u00b6\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-24", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-25", "text": "The keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclass QA[source]\u00b6\nBases: SingleKeyEvalConfig\nConfiguration for a QA evaluator.\nParameters", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-26", "text": "Bases: SingleKeyEvalConfig\nConfiguration for a QA evaluator.\nParameters\nprompt (Optional[BasePromptTemplate]) \u2013 The prompt template to use for generating the question.\nllm (Optional[BaseLanguageModel]) \u2013 The language model to use for the evaluation chain.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType = EvaluatorType.QA\u00b6\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\nparam llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam prompt: Optional[langchain.schema.prompt_template.BasePromptTemplate] = None\u00b6\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-27", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-28", "text": "The keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclass RegexMatch[source]\u00b6\nBases: SingleKeyEvalConfig\nConfiguration for a regex match string evaluator.\nParameters", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-29", "text": "Bases: SingleKeyEvalConfig\nConfiguration for a regex match string evaluator.\nParameters\nflags (int) \u2013 The flags to pass to the regex. Example: re.IGNORECASE.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType = EvaluatorType.REGEX_MATCH\u00b6\nparam flags: int = 0\u00b6\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-30", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-31", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclass ScoreString[source]\u00b6\nBases: SingleKeyEvalConfig\nConfiguration for a score string evaluator.\nThis is like the criteria evaluator but it is configured by\ndefault to return a score on the scale from 1-10.\nIt is recommended to normalize these scores\nby setting normalize_by to 10.\nParameters\ncriteria (Optional[CRITERIA_TYPE]) \u2013 The criteria to evaluate.\nllm (Optional[BaseLanguageModel]) \u2013 The language model to use for the evaluation chain.\nnormalize_by (Optional[int] = None) \u2013 If you want to normalize the score, the denominator to use.\nIf not provided, the score will be between 1 and 10 (by default).\nprompt (Optional[BasePromptTemplate]) \u2013 \nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-32", "text": "Raises ValidationError if the input data cannot be parsed to form a valid model.\nparam criteria: Optional[Union[Mapping[str, str], langchain.evaluation.criteria.eval_chain.Criteria, langchain.chains.constitutional_ai.models.ConstitutionalPrinciple]] = None\u00b6\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType = EvaluatorType.SCORE_STRING\u00b6\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\nparam llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nparam normalize_by: Optional[float] = None\u00b6\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam prompt: Optional[langchain.schema.prompt_template.BasePromptTemplate] = None\u00b6\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-33", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-34", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclass StringDistance[source]\u00b6\nBases: SingleKeyEvalConfig\nConfiguration for a string distance evaluator.\nParameters\ndistance (Optional[StringDistanceEnum]) \u2013 The string distance metric to use.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam distance: Optional[langchain.evaluation.string_distance.base.StringDistance] = None\u00b6\nThe string distance metric to use.\ndamerau_levenshtein: The Damerau-Levenshtein distance.\nlevenshtein: The Levenshtein distance.\njaro: The Jaro distance.\njaro_winkler: The Jaro-Winkler distance.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-35", "text": "jaro_winkler: The Jaro-Winkler distance.\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType = EvaluatorType.STRING_DISTANCE\u00b6\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\nparam normalize_score: bool = True\u00b6\nWhether to normalize the distance to between 0 and 1.\nApplies only to the Levenshtein and Damerau-Levenshtein distances.\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-36", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-37", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-38", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "3ccdfd4e760f-39", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using RunEvalConfig\u00b6\nLangSmith Walkthrough", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.RunEvalConfig.html"}
{"id": "766d1815d98c-0", "text": "langchain.smith.evaluation.name_generation.random_name\u00b6\nlangchain.smith.evaluation.name_generation.random_name(prefix: str = 'test') \u2192 str[source]\u00b6\nGenerate a random name.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.name_generation.random_name.html"}
{"id": "1a27feef601f-0", "text": "langchain.smith.evaluation.runner_utils.InputFormatError\u00b6\nclass langchain.smith.evaluation.runner_utils.InputFormatError[source]\u00b6\nRaised when the input format is invalid.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.runner_utils.InputFormatError.html"}
{"id": "79ac78b174f0-0", "text": "langchain.smith.evaluation.string_run_evaluator.ToolStringRunMapper\u00b6\nclass langchain.smith.evaluation.string_run_evaluator.ToolStringRunMapper[source]\u00b6\nBases: StringRunMapper\nMap an input to the tool.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\n__call__(run: Run) \u2192 Dict[str, str]\u00b6\nMaps the Run to a dictionary.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.ToolStringRunMapper.html"}
{"id": "79ac78b174f0-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.ToolStringRunMapper.html"}
{"id": "79ac78b174f0-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap(run: Run) \u2192 Dict[str, str][source]\u00b6\nMaps the Run to a dictionary.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nThe keys to extract from the run.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.ToolStringRunMapper.html"}
{"id": "b6d03b595ad1-0", "text": "langchain.smith.evaluation.runner_utils.run_on_dataset\u00b6\nlangchain.smith.evaluation.runner_utils.run_on_dataset(client: Optional[Client], dataset_name: str, llm_or_chain_factory: Union[Callable[[], Union[Chain, Runnable]], BaseLanguageModel, Callable[[dict], Any], Runnable, Chain], *, evaluation: Optional[RunEvalConfig] = None, concurrency_level: int = 5, project_name: Optional[str] = None, project_metadata: Optional[Dict[str, Any]] = None, verbose: bool = False, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 Dict[str, Any][source]\u00b6\nRun the Chain or language model on a dataset and store traces\nto the specified project name.\nParameters\ndataset_name \u2013 Name of the dataset to run the chain on.\nllm_or_chain_factory \u2013 Language model or Chain constructor to run\nover the dataset. The Chain constructor is used to permit\nindependent calls on each example without carrying over state.\nevaluation \u2013 Configuration for evaluators to run on the\nresults of the chain\nconcurrency_level \u2013 The number of async tasks to run concurrently.\nproject_name \u2013 Name of the project to store the traces in.\nDefaults to {dataset_name}-{chain class name}-{datetime}.\nproject_metadata \u2013 Optional metadata to add to the project.\nUseful for storing information the test variant.\n(prompt version, model version, etc.)\nclient \u2013 LangSmith client to use to access the dataset and to\nlog feedback and run traces.\nverbose \u2013 Whether to print progress.\ntags \u2013 Tags to add to each run in the project.\nReturns\nA dictionary containing the run\u2019s project name and the resulting model outputs.\nFor the (usually faster) async version of this function, see arun_on_dataset().\nExamples\nfrom langsmith import Client\nfrom langchain.chat_models import ChatOpenAI", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.runner_utils.run_on_dataset.html"}
{"id": "b6d03b595ad1-1", "text": "Examples\nfrom langsmith import Client\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.chains import LLMChain\nfrom langchain.smith import smith_eval.RunEvalConfig, run_on_dataset\n# Chains may have memory. Passing in a constructor function lets the\n# evaluation framework avoid cross-contamination between runs.\ndef construct_chain():\n    llm = ChatOpenAI(temperature=0)\n    chain = LLMChain.from_string(\n        llm,\n        \"What's the answer to {your_input_key}\"\n    )\n    return chain\n# Load off-the-shelf evaluators via config or the EvaluatorType (string or enum)\nevaluation_config = smith_eval.RunEvalConfig(\n    evaluators=[\n        \"qa\",  # \"Correctness\" against a reference answer\n        \"embedding_distance\",\n        smith_eval.RunEvalConfig.Criteria(\"helpfulness\"),\n        smith_eval.RunEvalConfig.Criteria({\n            \"fifth-grader-score\": \"Do you have to be smarter than a fifth grader to answer this question?\"\n        }),\n    ]\n)\nclient = Client()\nrun_on_dataset(\n    client,\n    \"<my_dataset_name>\",\n    construct_chain,\n    evaluation=evaluation_config,\n)\nYou can also create custom evaluators by subclassing the\nStringEvaluator\nor LangSmith\u2019s RunEvaluator classes.\nfrom typing import Optional\nfrom langchain.evaluation import StringEvaluator\nclass MyStringEvaluator(StringEvaluator):\n    @property\n    def requires_input(self) -> bool:\n        return False\n    @property\n    def requires_reference(self) -> bool:\n        return True\n    @property\n    def evaluation_name(self) -> str:\n        return \"exact_match\"\n    def _evaluate_strings(self, prediction, reference=None, input=None, **kwargs) -> dict:", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.runner_utils.run_on_dataset.html"}
{"id": "b6d03b595ad1-2", "text": "return {\"score\": prediction == reference}\nevaluation_config = smith_eval.RunEvalConfig(\n    custom_evaluators = [MyStringEvaluator()],\n)\nrun_on_dataset(\n    client,\n    \"<my_dataset_name>\",\n    construct_chain,\n    evaluation=evaluation_config,\n)\nExamples using run_on_dataset\u00b6\nLangSmith Walkthrough", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.runner_utils.run_on_dataset.html"}
{"id": "059b12f8d400-0", "text": "langchain.smith.evaluation.runner_utils.arun_on_dataset\u00b6\nasync langchain.smith.evaluation.runner_utils.arun_on_dataset(client: Optional[Client], dataset_name: str, llm_or_chain_factory: Union[Callable[[], Union[Chain, Runnable]], BaseLanguageModel, Callable[[dict], Any], Runnable, Chain], *, evaluation: Optional[RunEvalConfig] = None, concurrency_level: int = 5, project_name: Optional[str] = None, project_metadata: Optional[Dict[str, Any]] = None, verbose: bool = False, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 Dict[str, Any][source]\u00b6\nRun the Chain or language model on a dataset and store traces\nto the specified project name.\nParameters\ndataset_name \u2013 Name of the dataset to run the chain on.\nllm_or_chain_factory \u2013 Language model or Chain constructor to run\nover the dataset. The Chain constructor is used to permit\nindependent calls on each example without carrying over state.\nevaluation \u2013 Configuration for evaluators to run on the\nresults of the chain\nconcurrency_level \u2013 The number of async tasks to run concurrently.\nproject_name \u2013 Name of the project to store the traces in.\nDefaults to {dataset_name}-{chain class name}-{datetime}.\nproject_metadata \u2013 Optional metadata to add to the project.\nUseful for storing information the test variant.\n(prompt version, model version, etc.)\nclient \u2013 LangSmith client to use to access the dataset and to\nlog feedback and run traces.\nverbose \u2013 Whether to print progress.\ntags \u2013 Tags to add to each run in the project.\nReturns\nA dictionary containing the run\u2019s project name and the resulting model outputs.\nFor the (usually faster) async version of this function, see arun_on_dataset().\nExamples\nfrom langsmith import Client\nfrom langchain.chat_models import ChatOpenAI", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.runner_utils.arun_on_dataset.html"}
{"id": "059b12f8d400-1", "text": "Examples\nfrom langsmith import Client\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.chains import LLMChain\nfrom langchain.smith import smith_eval.RunEvalConfig, run_on_dataset\n# Chains may have memory. Passing in a constructor function lets the\n# evaluation framework avoid cross-contamination between runs.\ndef construct_chain():\n    llm = ChatOpenAI(temperature=0)\n    chain = LLMChain.from_string(\n        llm,\n        \"What's the answer to {your_input_key}\"\n    )\n    return chain\n# Load off-the-shelf evaluators via config or the EvaluatorType (string or enum)\nevaluation_config = smith_eval.RunEvalConfig(\n    evaluators=[\n        \"qa\",  # \"Correctness\" against a reference answer\n        \"embedding_distance\",\n        smith_eval.RunEvalConfig.Criteria(\"helpfulness\"),\n        smith_eval.RunEvalConfig.Criteria({\n            \"fifth-grader-score\": \"Do you have to be smarter than a fifth grader to answer this question?\"\n        }),\n    ]\n)\nclient = Client()\nawait arun_on_dataset(\n    client,\n    \"<my_dataset_name>\",\n    construct_chain,\n    evaluation=evaluation_config,\n)\nYou can also create custom evaluators by subclassing the\nStringEvaluator\nor LangSmith\u2019s RunEvaluator classes.\nfrom typing import Optional\nfrom langchain.evaluation import StringEvaluator\nclass MyStringEvaluator(StringEvaluator):\n    @property\n    def requires_input(self) -> bool:\n        return False\n    @property\n    def requires_reference(self) -> bool:\n        return True\n    @property\n    def evaluation_name(self) -> str:\n        return \"exact_match\"\n    def _evaluate_strings(self, prediction, reference=None, input=None, **kwargs) -> dict:", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.runner_utils.arun_on_dataset.html"}
{"id": "059b12f8d400-2", "text": "return {\"score\": prediction == reference}\nevaluation_config = smith_eval.RunEvalConfig(\n    custom_evaluators = [MyStringEvaluator()],\n)\nawait arun_on_dataset(\n    client,\n    \"<my_dataset_name>\",\n    construct_chain,\n    evaluation=evaluation_config,\n)\nExamples using arun_on_dataset\u00b6\nLangSmith Walkthrough", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.runner_utils.arun_on_dataset.html"}
{"id": "927239efe8b0-0", "text": "langchain.smith.evaluation.string_run_evaluator.StringRunMapper\u00b6\nclass langchain.smith.evaluation.string_run_evaluator.StringRunMapper[source]\u00b6\nBases: Serializable\nExtract items to evaluate from the run object.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\n__call__(run: Run) \u2192 Dict[str, str][source]\u00b6\nMaps the Run to a dictionary.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunMapper.html"}
{"id": "927239efe8b0-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunMapper.html"}
{"id": "927239efe8b0-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nabstract map(run: Run) \u2192 Dict[str, str][source]\u00b6\nMaps the Run to a dictionary.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nThe keys to extract from the run.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringRunMapper.html"}
{"id": "6bf59dc7fa0b-0", "text": "langchain.smith.evaluation.progress.ProgressBarCallback\u00b6\nclass langchain.smith.evaluation.progress.ProgressBarCallback(total: int, ncols: int = 50, **kwargs: Any)[source]\u00b6\nA simple progress bar for the console.\nInitialize the progress bar.\nParameters\ntotal \u2013 int, the total number of items to be processed.\nncols \u2013 int, the character width of the progress bar.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(total[,\u00a0ncols])\nInitialize the progress bar.\nincrement()\nIncrement the counter and update the progress bar.\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain ends running.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM ends running.\non_llm_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM errors.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.progress.ProgressBarCallback.html"}
{"id": "6bf59dc7fa0b-1", "text": "on_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool ends running.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\n__init__(total: int, ncols: int = 50, **kwargs: Any)[source]\u00b6\nInitialize the progress bar.\nParameters\ntotal \u2013 int, the total number of items to be processed.\nncols \u2013 int, the character width of the progress bar.\nincrement() \u2192 None[source]\u00b6\nIncrement the counter and update the progress bar.\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.progress.ProgressBarCallback.html"}
{"id": "6bf59dc7fa0b-2", "text": "Run on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on new LLM token. Only available when streaming is enabled.\nParameters", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.progress.ProgressBarCallback.html"}
{"id": "6bf59dc7fa0b-3", "text": "Run on new LLM token. Only available when streaming is enabled.\nParameters\ntoken (str) \u2013 The new token.\nchunk (GenerationChunk | ChatGenerationChunk) \u2013 The new generated chunk,\ninformation. (containing content and other) \u2013 \non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM starts running.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.progress.ProgressBarCallback.html"}
{"id": "6bf59dc7fa0b-4", "text": "Run on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool starts running.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.progress.ProgressBarCallback.html"}
{"id": "250271cdfbb1-0", "text": "langchain.smith.evaluation.config.SingleKeyEvalConfig\u00b6\nclass langchain.smith.evaluation.config.SingleKeyEvalConfig[source]\u00b6\nBases: EvalConfig\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam evaluator_type: langchain.evaluation.schema.EvaluatorType [Required]\u00b6\nparam input_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s inputs dictionary to use to represent the\ninput. If not provided, it will be inferred automatically.\nparam prediction_key: Optional[str] = None\u00b6\nThe key from the traced run\u2019s outputs dictionary to use to\nrepresent the prediction. If not provided, it will be inferred\nautomatically.\nparam reference_key: Optional[str] = None\u00b6\nThe key in the dataset run to use as the reference string.\nIf not provided, we will attempt to infer automatically.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.SingleKeyEvalConfig.html"}
{"id": "250271cdfbb1-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_kwargs() \u2192 Dict[str, Any][source]\u00b6\nGet the keyword arguments for the load_evaluator call.\nReturns\nThe keyword arguments for the load_evaluator call.\nReturn type\nDict[str, Any]\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.SingleKeyEvalConfig.html"}
{"id": "250271cdfbb1-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.config.SingleKeyEvalConfig.html"}
{"id": "8c63148cc78e-0", "text": "langchain.smith.evaluation.string_run_evaluator.StringExampleMapper\u00b6\nclass langchain.smith.evaluation.string_run_evaluator.StringExampleMapper[source]\u00b6\nBases: Serializable\nMap an example, or row in the dataset, to the inputs of an evaluation.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam reference_key: Optional[str] = None\u00b6\n__call__(example: Example) \u2192 Dict[str, str][source]\u00b6\nMaps the Run and Example to a dictionary.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringExampleMapper.html"}
{"id": "8c63148cc78e-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringExampleMapper.html"}
{"id": "8c63148cc78e-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap(example: Example) \u2192 Dict[str, str][source]\u00b6\nMaps the Example, or dataset row to a dictionary.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nserialize_chat_messages(messages: List[Dict]) \u2192 str[source]\u00b6\nExtract the input messages from the run.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nThe keys to extract from the run.", "source": "lang/api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.string_run_evaluator.StringExampleMapper.html"}
{"id": "f1e568bf69f9-0", "text": "langchain.prompts.base.get_template_variables\u00b6\nlangchain.prompts.base.get_template_variables(template: str, template_format: str) \u2192 List[str][source]\u00b6\nGet the variables from the template.\nParameters\ntemplate \u2013 The template string.\ntemplate_format \u2013 The template format. Should be one of \u201cf-string\u201d or \u201cjinja2\u201d.\nReturns\nThe variables from the template.\nRaises\nValueError \u2013 If the template format is not supported.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.get_template_variables.html"}
{"id": "15a4d7c690db-0", "text": "langchain.prompts.chat.BaseChatPromptTemplate\u00b6\nclass langchain.prompts.chat.BaseChatPromptTemplate[source]\u00b6\nBases: BasePromptTemplate, ABC\nBase class for chat prompt templates.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam input_types: Dict[str, Any] [Optional]\u00b6\nA dictionary of the types of the variables the prompt template expects.\nIf not provided, all variables are assumed to be strings.\nparam input_variables: List[str] [Required]\u00b6\nA list of the names of the variables the prompt template expects.\nparam output_parser: Optional[BaseOutputParser] = None\u00b6\nHow to parse the output of calling an LLM on this formatted prompt.\nparam partial_variables: Mapping[str, Union[str, Callable[[], str]]] [Optional]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseChatPromptTemplate.html"}
{"id": "15a4d7c690db-1", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseChatPromptTemplate.html"}
{"id": "15a4d7c690db-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseChatPromptTemplate.html"}
{"id": "15a4d7c690db-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of prompt.\nformat(**kwargs: Any) \u2192 str[source]\u00b6\nFormat the chat template into a string.\nParameters\n**kwargs \u2013 keyword arguments to use for filling in template variables\nin all the template messages in this chat template.\nReturns\nformatted string\nabstract format_messages(**kwargs: Any) \u2192 List[BaseMessage][source]\u00b6\nFormat kwargs into a list of messages.\nformat_prompt(**kwargs: Any) \u2192 PromptValue[source]\u00b6\nFormat prompt. Should return a PromptValue.\n:param **kwargs: Keyword arguments to use for formatting.\nReturns\nPromptValue.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseChatPromptTemplate.html"}
{"id": "15a4d7c690db-4", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict, config: Optional[RunnableConfig] = None) \u2192 PromptValue\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseChatPromptTemplate.html"}
{"id": "15a4d7c690db-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npartial(**kwargs: Union[str, Callable[[], str]]) \u2192 BasePromptTemplate\u00b6\nReturn a partial of the prompt template.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the prompt.\nParameters", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseChatPromptTemplate.html"}
{"id": "15a4d7c690db-6", "text": "Save the prompt.\nParameters\nfile_path \u2013 Path to directory to save prompt to.\nExample:\n.. code-block:: python\nprompt.save(file_path=\u201dpath/prompt.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseChatPromptTemplate.html"}
{"id": "15a4d7c690db-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseChatPromptTemplate.html"}
{"id": "15a4d7c690db-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Any\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nReturn a list of attribute names that should be included in the\nserialized kwargs. These attributes must be accepted by the\nconstructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseChatPromptTemplate.html"}
{"id": "88b7e5376a32-0", "text": "langchain.prompts.loading.load_prompt\u00b6\nlangchain.prompts.loading.load_prompt(path: Union[str, Path]) \u2192 BasePromptTemplate[source]\u00b6\nUnified method for loading a prompt from LangChainHub or local fs.\nExamples using load_prompt\u00b6\nAmazon Comprehend Moderation Chain\nSerialization", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.loading.load_prompt.html"}
{"id": "d6367679850f-0", "text": "langchain.prompts.example_selector.base.BaseExampleSelector\u00b6\nclass langchain.prompts.example_selector.base.BaseExampleSelector[source]\u00b6\nInterface for selecting examples to include in prompts.\nMethods\n__init__()\nadd_example(example)\nAdd new example to store for a key.\nselect_examples(input_variables)\nSelect which examples to use based on the inputs.\n__init__()\u00b6\nabstract add_example(example: Dict[str, str]) \u2192 Any[source]\u00b6\nAdd new example to store for a key.\nabstract select_examples(input_variables: Dict[str, str]) \u2192 List[dict][source]\u00b6\nSelect which examples to use based on the inputs.\nExamples using BaseExampleSelector\u00b6\nCustom example selector", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.base.BaseExampleSelector.html"}
{"id": "2b6bd3282da2-0", "text": "langchain.prompts.example_selector.ngram_overlap.ngram_overlap_score\u00b6\nlangchain.prompts.example_selector.ngram_overlap.ngram_overlap_score(source: List[str], example: List[str]) \u2192 float[source]\u00b6\nCompute ngram overlap score of source and example as sentence_bleu score.\nUse sentence_bleu with method1 smoothing function and auto reweighting.\nReturn float value between 0.0 and 1.0 inclusive.\nhttps://www.nltk.org/_modules/nltk/translate/bleu_score.html\nhttps://aclanthology.org/P02-1040.pdf", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.ngram_overlap.ngram_overlap_score.html"}
{"id": "1748b302ba94-0", "text": "langchain.prompts.base.validate_jinja2\u00b6\nlangchain.prompts.base.validate_jinja2(template: str, input_variables: List[str]) \u2192 None[source]\u00b6\nValidate that the input variables are valid for the template.\nIssues a warning if missing or extra variables are found.\nParameters\ntemplate \u2013 The template string.\ninput_variables \u2013 The input variables.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.validate_jinja2.html"}
{"id": "25b90a939f5c-0", "text": "langchain.prompts.pipeline.PipelinePromptTemplate\u00b6\nclass langchain.prompts.pipeline.PipelinePromptTemplate[source]\u00b6\nBases: BasePromptTemplate\nA prompt template for composing multiple prompt templates together.\nThis can be useful when you want to reuse parts of prompts.\nA PipelinePrompt consists of two main parts:\nfinal_prompt: This is the final prompt that is returned\npipeline_prompts: This is a list of tuples, consistingof a string (name) and a Prompt Template.\nEach PromptTemplate will be formatted and then passed\nto future prompt templates as a variable with\nthe same name as name\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam final_prompt: langchain.schema.prompt_template.BasePromptTemplate [Required]\u00b6\nThe final prompt that is returned.\nparam input_types: Dict[str, Any] [Optional]\u00b6\nA dictionary of the types of the variables the prompt template expects.\nIf not provided, all variables are assumed to be strings.\nparam input_variables: List[str] [Required]\u00b6\nA list of the names of the variables the prompt template expects.\nparam output_parser: Optional[BaseOutputParser] = None\u00b6\nHow to parse the output of calling an LLM on this formatted prompt.\nparam partial_variables: Mapping[str, Union[str, Callable[[], str]]] [Optional]\u00b6\nparam pipeline_prompts: List[Tuple[str, langchain.schema.prompt_template.BasePromptTemplate]] [Required]\u00b6\nA list of tuples, consisting of a string (name) and a Prompt Template.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.pipeline.PipelinePromptTemplate.html"}
{"id": "25b90a939f5c-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.pipeline.PipelinePromptTemplate.html"}
{"id": "25b90a939f5c-2", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.pipeline.PipelinePromptTemplate.html"}
{"id": "25b90a939f5c-3", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of prompt.\nformat(**kwargs: Any) \u2192 str[source]\u00b6\nFormat the prompt with the inputs.\nParameters\nkwargs \u2013 Any arguments to be passed to the prompt template.\nReturns\nA formatted string.\nExample:\nprompt.format(variable1=\"foo\")\nformat_prompt(**kwargs: Any) \u2192 PromptValue[source]\u00b6\nCreate Chat Messages.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.pipeline.PipelinePromptTemplate.html"}
{"id": "25b90a939f5c-4", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict, config: Optional[RunnableConfig] = None) \u2192 PromptValue\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.pipeline.PipelinePromptTemplate.html"}
{"id": "25b90a939f5c-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npartial(**kwargs: Union[str, Callable[[], str]]) \u2192 BasePromptTemplate\u00b6\nReturn a partial of the prompt template.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the prompt.\nParameters", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.pipeline.PipelinePromptTemplate.html"}
{"id": "25b90a939f5c-6", "text": "Save the prompt.\nParameters\nfile_path \u2013 Path to directory to save prompt to.\nExample:\n.. code-block:: python\nprompt.save(file_path=\u201dpath/prompt.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.pipeline.PipelinePromptTemplate.html"}
{"id": "25b90a939f5c-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.pipeline.PipelinePromptTemplate.html"}
{"id": "25b90a939f5c-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Any\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.pipeline.PipelinePromptTemplate.html"}
{"id": "d313b1c83a41-0", "text": "langchain.prompts.base.jinja2_formatter\u00b6\nlangchain.prompts.base.jinja2_formatter(template: str, **kwargs: Any) \u2192 str[source]\u00b6\nFormat a template using jinja2.\nSecurity warning: As of LangChain 0.0.329, this method uses Jinja2\u2019sSandboxedEnvironment by default. However, this sand-boxing should\nbe treated as a best-effort approach rather than a guarantee of security.\nDo not accept jinja2 templates from untrusted sources as they may lead\nto arbitrary Python code execution.\nhttps://jinja.palletsprojects.com/en/3.1.x/sandbox/", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.jinja2_formatter.html"}
{"id": "fac8f870698f-0", "text": "langchain.prompts.few_shot_with_templates.FewShotPromptWithTemplates\u00b6\nclass langchain.prompts.few_shot_with_templates.FewShotPromptWithTemplates[source]\u00b6\nBases: StringPromptTemplate\nPrompt template that contains few shot examples.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam example_prompt: langchain.prompts.prompt.PromptTemplate [Required]\u00b6\nPromptTemplate used to format an individual example.\nparam example_selector: Optional[langchain.prompts.example_selector.base.BaseExampleSelector] = None\u00b6\nExampleSelector to choose the examples to format into the prompt.\nEither this or examples should be provided.\nparam example_separator: str = '\\n\\n'\u00b6\nString separator used to join the prefix, the examples, and suffix.\nparam examples: Optional[List[dict]] = None\u00b6\nExamples to format into the prompt.\nEither this or example_selector should be provided.\nparam input_types: Dict[str, Any] [Optional]\u00b6\nA dictionary of the types of the variables the prompt template expects.\nIf not provided, all variables are assumed to be strings.\nparam input_variables: List[str] [Required]\u00b6\nA list of the names of the variables the prompt template expects.\nparam output_parser: Optional[BaseOutputParser] = None\u00b6\nHow to parse the output of calling an LLM on this formatted prompt.\nparam partial_variables: Mapping[str, Union[str, Callable[[], str]]] [Optional]\u00b6\nparam prefix: Optional[langchain.prompts.base.StringPromptTemplate] = None\u00b6\nA PromptTemplate to put before the examples.\nparam suffix: langchain.prompts.base.StringPromptTemplate [Required]\u00b6\nA PromptTemplate to put after the examples.\nparam template_format: str = 'f-string'\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot_with_templates.FewShotPromptWithTemplates.html"}
{"id": "fac8f870698f-1", "text": "param template_format: str = 'f-string'\u00b6\nThe format of the prompt template. Options are: \u2018f-string\u2019, \u2018jinja2\u2019.\nparam validate_template: bool = False\u00b6\nWhether or not to try validating the template.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot_with_templates.FewShotPromptWithTemplates.html"}
{"id": "fac8f870698f-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot_with_templates.FewShotPromptWithTemplates.html"}
{"id": "fac8f870698f-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot_with_templates.FewShotPromptWithTemplates.html"}
{"id": "fac8f870698f-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of prompt.\nformat(**kwargs: Any) \u2192 str[source]\u00b6\nFormat the prompt with the inputs.\nParameters\nkwargs \u2013 Any arguments to be passed to the prompt template.\nReturns\nA formatted string.\nExample:\nprompt.format(variable1=\"foo\")\nformat_prompt(**kwargs: Any) \u2192 PromptValue\u00b6\nCreate Chat Messages.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot_with_templates.FewShotPromptWithTemplates.html"}
{"id": "fac8f870698f-5", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict, config: Optional[RunnableConfig] = None) \u2192 PromptValue\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot_with_templates.FewShotPromptWithTemplates.html"}
{"id": "fac8f870698f-6", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npartial(**kwargs: Union[str, Callable[[], str]]) \u2192 BasePromptTemplate\u00b6\nReturn a partial of the prompt template.\nsave(file_path: Union[Path, str]) \u2192 None[source]\u00b6\nSave the prompt.\nParameters\nfile_path \u2013 Path to directory to save prompt to.\nExample:\n.. code-block:: python\nprompt.save(file_path=\u201dpath/prompt.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot_with_templates.FewShotPromptWithTemplates.html"}
{"id": "fac8f870698f-7", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot_with_templates.FewShotPromptWithTemplates.html"}
{"id": "fac8f870698f-8", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Any\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot_with_templates.FewShotPromptWithTemplates.html"}
{"id": "fac8f870698f-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot_with_templates.FewShotPromptWithTemplates.html"}
{"id": "fe4e284ec39b-0", "text": "langchain.prompts.chat.BaseMessagePromptTemplate\u00b6\nclass langchain.prompts.chat.BaseMessagePromptTemplate[source]\u00b6\nBases: Serializable, ABC\nBase class for message prompt templates.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseMessagePromptTemplate.html"}
{"id": "fe4e284ec39b-1", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nabstract format_messages(**kwargs: Any) \u2192 List[BaseMessage][source]\u00b6\nFormat messages from kwargs. Should return a list of BaseMessages.\nParameters\n**kwargs \u2013 Keyword arguments to use for formatting.\nReturns\nList of BaseMessages.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseMessagePromptTemplate.html"}
{"id": "fe4e284ec39b-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nabstract property input_variables: List[str]\u00b6\nInput variables for this prompt template.\nReturns\nList of input variables.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseMessagePromptTemplate.html"}
{"id": "b724c5932392-0", "text": "langchain.prompts.chat.BaseStringMessagePromptTemplate\u00b6\nclass langchain.prompts.chat.BaseStringMessagePromptTemplate[source]\u00b6\nBases: BaseMessagePromptTemplate, ABC\nBase class for message prompt templates that use a string prompt template.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAdditional keyword arguments to pass to the prompt template.\nparam prompt: langchain.prompts.base.StringPromptTemplate [Required]\u00b6\nString prompt template.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseStringMessagePromptTemplate.html"}
{"id": "b724c5932392-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nabstract format(**kwargs: Any) \u2192 BaseMessage[source]\u00b6\nFormat the prompt template.\nParameters\n**kwargs \u2013 Keyword arguments to use for formatting.\nReturns\nFormatted message.\nformat_messages(**kwargs: Any) \u2192 List[BaseMessage][source]\u00b6\nFormat messages from kwargs.\nParameters\n**kwargs \u2013 Keyword arguments to use for formatting.\nReturns\nList of BaseMessages.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_template(template: str, template_format: str = 'f-string', **kwargs: Any) \u2192 MessagePromptTemplateT[source]\u00b6\nCreate a class from a string template.\nParameters\ntemplate \u2013 a template.\ntemplate_format \u2013 format of the template.\n**kwargs \u2013 keyword arguments to pass to the constructor.\nReturns\nA new instance of this class.\nclassmethod from_template_file(template_file: Union[str, Path], input_variables: List[str], **kwargs: Any) \u2192 MessagePromptTemplateT[source]\u00b6\nCreate a class from a template file.\nParameters\ntemplate_file \u2013 path to a template file. String or Path.\ninput_variables \u2013 list of input variables.\n**kwargs \u2013 keyword arguments to pass to the constructor.\nReturns\nA new instance of this class.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseStringMessagePromptTemplate.html"}
{"id": "b724c5932392-2", "text": "A new instance of this class.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseStringMessagePromptTemplate.html"}
{"id": "b724c5932392-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty input_variables: List[str]\u00b6\nInput variables for this prompt template.\nReturns\nList of input variable names.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.BaseStringMessagePromptTemplate.html"}
{"id": "7fcb9c30e975-0", "text": "langchain.prompts.loading.load_prompt_from_config\u00b6\nlangchain.prompts.loading.load_prompt_from_config(config: dict) \u2192 BasePromptTemplate[source]\u00b6\nLoad prompt from Config Dict.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.loading.load_prompt_from_config.html"}
{"id": "418924db01b9-0", "text": "langchain.prompts.chat.HumanMessagePromptTemplate\u00b6\nclass langchain.prompts.chat.HumanMessagePromptTemplate[source]\u00b6\nBases: BaseStringMessagePromptTemplate\nHuman message prompt template. This is a message sent from the user.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAdditional keyword arguments to pass to the prompt template.\nparam prompt: langchain.prompts.base.StringPromptTemplate [Required]\u00b6\nString prompt template.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.HumanMessagePromptTemplate.html"}
{"id": "418924db01b9-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nformat(**kwargs: Any) \u2192 BaseMessage[source]\u00b6\nFormat the prompt template.\nParameters\n**kwargs \u2013 Keyword arguments to use for formatting.\nReturns\nFormatted message.\nformat_messages(**kwargs: Any) \u2192 List[BaseMessage]\u00b6\nFormat messages from kwargs.\nParameters\n**kwargs \u2013 Keyword arguments to use for formatting.\nReturns\nList of BaseMessages.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_template(template: str, template_format: str = 'f-string', **kwargs: Any) \u2192 MessagePromptTemplateT\u00b6\nCreate a class from a string template.\nParameters\ntemplate \u2013 a template.\ntemplate_format \u2013 format of the template.\n**kwargs \u2013 keyword arguments to pass to the constructor.\nReturns\nA new instance of this class.\nclassmethod from_template_file(template_file: Union[str, Path], input_variables: List[str], **kwargs: Any) \u2192 MessagePromptTemplateT\u00b6\nCreate a class from a template file.\nParameters\ntemplate_file \u2013 path to a template file. String or Path.\ninput_variables \u2013 list of input variables.\n**kwargs \u2013 keyword arguments to pass to the constructor.\nReturns\nA new instance of this class.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.HumanMessagePromptTemplate.html"}
{"id": "418924db01b9-2", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.HumanMessagePromptTemplate.html"}
{"id": "418924db01b9-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty input_variables: List[str]\u00b6\nInput variables for this prompt template.\nReturns\nList of input variable names.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using HumanMessagePromptTemplate\u00b6\nAnthropic\n\ud83d\ude85 LiteLLM\nKonko\nOpenAI\nGoogle Cloud Platform Vertex AI PaLM \nJinaChat\nContext\nFigma\nFireworks\nSet env var OPENAI_API_KEY or load from a .env file:\nStructure answers with OpenAI functions\nCAMEL Role-Playing Autonomous Cooperative Agents\nMulti-agent authoritarian speaker selection\nMemory in LLMChain\nRetry parser\nPydantic (JSON) parser\nPrompt pipelining\nUsing OpenAI functions\nCode writing", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.HumanMessagePromptTemplate.html"}
{"id": "62ca70213344-0", "text": "langchain.prompts.base.StringPromptTemplate\u00b6\nclass langchain.prompts.base.StringPromptTemplate[source]\u00b6\nBases: BasePromptTemplate, ABC\nString prompt that exposes the format method, returning a prompt.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam input_types: Dict[str, Any] [Optional]\u00b6\nA dictionary of the types of the variables the prompt template expects.\nIf not provided, all variables are assumed to be strings.\nparam input_variables: List[str] [Required]\u00b6\nA list of the names of the variables the prompt template expects.\nparam output_parser: Optional[BaseOutputParser] = None\u00b6\nHow to parse the output of calling an LLM on this formatted prompt.\nparam partial_variables: Mapping[str, Union[str, Callable[[], str]]] [Optional]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.StringPromptTemplate.html"}
{"id": "62ca70213344-1", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.StringPromptTemplate.html"}
{"id": "62ca70213344-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.StringPromptTemplate.html"}
{"id": "62ca70213344-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of prompt.\nabstract format(**kwargs: Any) \u2192 str\u00b6\nFormat the prompt with the inputs.\nParameters\nkwargs \u2013 Any arguments to be passed to the prompt template.\nReturns\nA formatted string.\nExample:\nprompt.format(variable1=\"foo\")\nformat_prompt(**kwargs: Any) \u2192 PromptValue[source]\u00b6\nCreate Chat Messages.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.StringPromptTemplate.html"}
{"id": "62ca70213344-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict, config: Optional[RunnableConfig] = None) \u2192 PromptValue\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.StringPromptTemplate.html"}
{"id": "62ca70213344-5", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npartial(**kwargs: Union[str, Callable[[], str]]) \u2192 BasePromptTemplate\u00b6\nReturn a partial of the prompt template.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the prompt.\nParameters\nfile_path \u2013 Path to directory to save prompt to.\nExample:\n.. code-block:: python\nprompt.save(file_path=\u201dpath/prompt.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.StringPromptTemplate.html"}
{"id": "62ca70213344-6", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.StringPromptTemplate.html"}
{"id": "62ca70213344-7", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Any\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.StringPromptTemplate.html"}
{"id": "62ca70213344-8", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using StringPromptTemplate\u00b6\nPlug-and-Plai\nWikibase Agent\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nCustom Agent with PlugIn Retrieval\nCustom agent with tool retrieval\nCustom prompt template\nConnecting to a Feature Store", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.StringPromptTemplate.html"}
{"id": "1d3005096236-0", "text": "langchain.prompts.example_selector.ngram_overlap.NGramOverlapExampleSelector\u00b6\nclass langchain.prompts.example_selector.ngram_overlap.NGramOverlapExampleSelector[source]\u00b6\nBases: BaseExampleSelector, BaseModel\nSelect and order examples based on ngram overlap score (sentence_bleu score).\nhttps://www.nltk.org/_modules/nltk/translate/bleu_score.html\nhttps://aclanthology.org/P02-1040.pdf\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam example_prompt: langchain.prompts.prompt.PromptTemplate [Required]\u00b6\nPrompt template used to format the examples.\nparam examples: List[dict] [Required]\u00b6\nA list of the examples that the prompt template expects.\nparam threshold: float = -1.0\u00b6\nThreshold at which algorithm stops. Set to -1.0 by default.\nFor negative threshold:\nselect_examples sorts examples by ngram_overlap_score, but excludes none.\nFor threshold greater than 1.0:\nselect_examples excludes all examples, and returns an empty list.\nFor threshold equal to 0.0:\nselect_examples sorts examples by ngram_overlap_score,\nand excludes examples with no ngram overlap with input.\nadd_example(example: Dict[str, str]) \u2192 None[source]\u00b6\nAdd new example to list.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.ngram_overlap.NGramOverlapExampleSelector.html"}
{"id": "1d3005096236-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.ngram_overlap.NGramOverlapExampleSelector.html"}
{"id": "1d3005096236-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nselect_examples(input_variables: Dict[str, str]) \u2192 List[dict][source]\u00b6\nReturn list of examples sorted by ngram_overlap_score with input.\nDescending order.\nExcludes any examples with ngram_overlap_score less than or equal to threshold.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.ngram_overlap.NGramOverlapExampleSelector.html"}
{"id": "1d3005096236-3", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using NGramOverlapExampleSelector\u00b6\nSelect by n-gram overlap", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.ngram_overlap.NGramOverlapExampleSelector.html"}
{"id": "a821a27cfc82-0", "text": "langchain.prompts.example_selector.semantic_similarity.SemanticSimilarityExampleSelector\u00b6\nclass langchain.prompts.example_selector.semantic_similarity.SemanticSimilarityExampleSelector[source]\u00b6\nBases: BaseExampleSelector, BaseModel\nExample selector that selects examples based on SemanticSimilarity.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam example_keys: Optional[List[str]] = None\u00b6\nOptional keys to filter examples to.\nparam input_keys: Optional[List[str]] = None\u00b6\nOptional keys to filter input to. If provided, the search is based on\nthe input variables instead of all variables.\nparam k: int = 4\u00b6\nNumber of examples to select.\nparam vectorstore: langchain.schema.vectorstore.VectorStore [Required]\u00b6\nVectorStore than contains information about examples.\nadd_example(example: Dict[str, str]) \u2192 str[source]\u00b6\nAdd new example to vectorstore.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.semantic_similarity.SemanticSimilarityExampleSelector.html"}
{"id": "a821a27cfc82-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_examples(examples: List[dict], embeddings: Embeddings, vectorstore_cls: Type[VectorStore], k: int = 4, input_keys: Optional[List[str]] = None, **vectorstore_cls_kwargs: Any) \u2192 SemanticSimilarityExampleSelector[source]\u00b6\nCreate k-shot example selector using example list and embeddings.\nReshuffles examples dynamically based on query similarity.\nParameters\nexamples \u2013 List of examples to use in the prompt.\nembeddings \u2013 An initialized embedding API interface, e.g. OpenAIEmbeddings().\nvectorstore_cls \u2013 A vector store DB interface class, e.g. FAISS.\nk \u2013 Number of examples to select\ninput_keys \u2013 If provided, the search is based on the input variables\ninstead of all variables.\nvectorstore_cls_kwargs \u2013 optional kwargs containing url for vector store\nReturns\nThe ExampleSelector instantiated, backed by a vector store.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.semantic_similarity.SemanticSimilarityExampleSelector.html"}
{"id": "a821a27cfc82-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nselect_examples(input_variables: Dict[str, str]) \u2192 List[dict][source]\u00b6\nSelect which examples to use based on semantic similarity.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using SemanticSimilarityExampleSelector\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.semantic_similarity.SemanticSimilarityExampleSelector.html"}
{"id": "a821a27cfc82-3", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nExamples using SemanticSimilarityExampleSelector\u00b6\nSelect by maximal marginal relevance (MMR)\nFew-shot examples for chat models", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.semantic_similarity.SemanticSimilarityExampleSelector.html"}
{"id": "b638ce3dc8d5-0", "text": "langchain.prompts.few_shot.FewShotPromptTemplate\u00b6\nclass langchain.prompts.few_shot.FewShotPromptTemplate[source]\u00b6\nBases: _FewShotPromptTemplateMixin, StringPromptTemplate\nPrompt template that contains few shot examples.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam example_prompt: PromptTemplate [Required]\u00b6\nPromptTemplate used to format an individual example.\nparam example_selector: Optional[BaseExampleSelector] = None\u00b6\nExampleSelector to choose the examples to format into the prompt.\nEither this or examples should be provided.\nparam example_separator: str = '\\n\\n'\u00b6\nString separator used to join the prefix, the examples, and suffix.\nparam examples: Optional[List[dict]] = None\u00b6\nExamples to format into the prompt.\nEither this or example_selector should be provided.\nparam input_types: Dict[str, Any] [Optional]\u00b6\nA dictionary of the types of the variables the prompt template expects.\nIf not provided, all variables are assumed to be strings.\nparam input_variables: List[str] [Required]\u00b6\nA list of the names of the variables the prompt template expects.\nparam output_parser: Optional[BaseOutputParser] = None\u00b6\nHow to parse the output of calling an LLM on this formatted prompt.\nparam partial_variables: Mapping[str, Union[str, Callable[[], str]]] [Optional]\u00b6\nparam prefix: str = ''\u00b6\nA prompt template string to put before the examples.\nparam suffix: str [Required]\u00b6\nA prompt template string to put after the examples.\nparam template_format: Union[Literal['f-string'], Literal['jinja2']] = 'f-string'\u00b6\nThe format of the prompt template. Options are: \u2018f-string\u2019, \u2018jinja2\u2019.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotPromptTemplate.html"}
{"id": "b638ce3dc8d5-1", "text": "The format of the prompt template. Options are: \u2018f-string\u2019, \u2018jinja2\u2019.\nparam validate_template: bool = False\u00b6\nWhether or not to try validating the template.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotPromptTemplate.html"}
{"id": "b638ce3dc8d5-2", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotPromptTemplate.html"}
{"id": "b638ce3dc8d5-3", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of prompt.\nformat(**kwargs: Any) \u2192 str[source]\u00b6\nFormat the prompt with the inputs.\nParameters\n**kwargs \u2013 Any arguments to be passed to the prompt template.\nReturns\nA formatted string.\nExample:", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotPromptTemplate.html"}
{"id": "b638ce3dc8d5-4", "text": "Returns\nA formatted string.\nExample:\nprompt.format(variable1=\"foo\")\nformat_prompt(**kwargs: Any) \u2192 PromptValue\u00b6\nCreate Chat Messages.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict, config: Optional[RunnableConfig] = None) \u2192 PromptValue\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotPromptTemplate.html"}
{"id": "b638ce3dc8d5-5", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotPromptTemplate.html"}
{"id": "b638ce3dc8d5-6", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npartial(**kwargs: Union[str, Callable[[], str]]) \u2192 BasePromptTemplate\u00b6\nReturn a partial of the prompt template.\nsave(file_path: Union[Path, str]) \u2192 None[source]\u00b6\nSave the prompt.\nParameters\nfile_path \u2013 Path to directory to save prompt to.\nExample:\n.. code-block:: python\nprompt.save(file_path=\u201dpath/prompt.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotPromptTemplate.html"}
{"id": "b638ce3dc8d5-7", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotPromptTemplate.html"}
{"id": "b638ce3dc8d5-8", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Any\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using FewShotPromptTemplate\u00b6\nSelect by maximal marginal relevance (MMR)\nSelect by n-gram overlap", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotPromptTemplate.html"}
{"id": "a41c962d8d89-0", "text": "langchain.prompts.prompt.PromptTemplate\u00b6\nclass langchain.prompts.prompt.PromptTemplate[source]\u00b6\nBases: StringPromptTemplate\nA prompt template for a language model.\nA prompt template consists of a string template. It accepts a set of parameters\nfrom the user that can be used to generate a prompt for a language model.\nThe template can be formatted using either f-strings (default) or jinja2 syntax.\nSecurity warning: Prefer using template_format=\u201df-string\u201d instead oftemplate_format=\u201djinja2\u201d, or make sure to NEVER accept jinja2 templates\nfrom untrusted sources as they may lead to arbitrary Python code execution.\nAs of LangChain 0.0.329, Jinja2 templates will be rendered using\nJinja2\u2019s SandboxedEnvironment by default. This sand-boxing should\nbe treated as a best-effort approach rather than a guarantee of security,\nas it is an opt-out rather than opt-in approach.\nDespite the sand-boxing, we recommend to never use jinja2 templates\nfrom untrusted sources.\nExample\nfrom langchain.prompts import PromptTemplate\n# Instantiation using from_template (recommended)\nprompt = PromptTemplate.from_template(\"Say {foo}\")\nprompt.format(foo=\"bar\")\n# Instantiation using initializer\nprompt = PromptTemplate(input_variables=[\"foo\"], template=\"Say {foo}\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam input_types: Dict[str, Any] [Optional]\u00b6\nA dictionary of the types of the variables the prompt template expects.\nIf not provided, all variables are assumed to be strings.\nparam input_variables: List[str] [Required]\u00b6\nA list of the names of the variables the prompt template expects.\nparam output_parser: Optional[BaseOutputParser] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.prompt.PromptTemplate.html"}
{"id": "a41c962d8d89-1", "text": "param output_parser: Optional[BaseOutputParser] = None\u00b6\nHow to parse the output of calling an LLM on this formatted prompt.\nparam partial_variables: Mapping[str, Union[str, Callable[[], str]]] [Optional]\u00b6\nparam template: str [Required]\u00b6\nThe prompt template.\nparam template_format: Union[Literal['f-string'], Literal['jinja2']] = 'f-string'\u00b6\nThe format of the prompt template. Options are: \u2018f-string\u2019, \u2018jinja2\u2019.\nparam validate_template: bool = False\u00b6\nWhether or not to try validating the template.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.prompt.PromptTemplate.html"}
{"id": "a41c962d8d89-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.prompt.PromptTemplate.html"}
{"id": "a41c962d8d89-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.prompt.PromptTemplate.html"}
{"id": "a41c962d8d89-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of prompt.\nformat(**kwargs: Any) \u2192 str[source]\u00b6\nFormat the prompt with the inputs.\nParameters\nkwargs \u2013 Any arguments to be passed to the prompt template.\nReturns\nA formatted string.\nExample\nprompt.format(variable1=\"foo\")\nformat_prompt(**kwargs: Any) \u2192 PromptValue\u00b6\nCreate Chat Messages.\nclassmethod from_examples(examples: List[str], suffix: str, input_variables: List[str], example_separator: str = '\\n\\n', prefix: str = '', **kwargs: Any) \u2192 PromptTemplate[source]\u00b6\nTake examples in list format with prefix and suffix to create a prompt.\nIntended to be used as a way to dynamically create a prompt from examples.\nParameters\nexamples \u2013 List of examples to use in the prompt.\nsuffix \u2013 String to go after the list of examples. Should generally\nset up the user\u2019s input.\ninput_variables \u2013 A list of variable names the final prompt template\nwill expect.\nexample_separator \u2013 The separator to use in between examples. Defaults\nto two new line characters.\nprefix \u2013 String that should go before any examples. Generally includes\nexamples. Default to an empty string.\nReturns\nThe final prompt generated.\nclassmethod from_file(template_file: Union[str, Path], input_variables: List[str], **kwargs: Any) \u2192 PromptTemplate[source]\u00b6\nLoad a prompt from a file.\nParameters\ntemplate_file \u2013 The path to the file containing the prompt template.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.prompt.PromptTemplate.html"}
{"id": "a41c962d8d89-5", "text": "Parameters\ntemplate_file \u2013 The path to the file containing the prompt template.\ninput_variables \u2013 A list of variable names the final prompt template\nwill expect.\nReturns\nThe prompt loaded from the file.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_template(template: str, *, template_format: str = 'f-string', partial_variables: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 PromptTemplate[source]\u00b6\nLoad a prompt template from a template.\nSecurity warning: Prefer using template_format=\u201df-string\u201d instead oftemplate_format=\u201djinja2\u201d, or make sure to NEVER accept jinja2 templates\nfrom untrusted sources as they may lead to arbitrary Python code execution.\nAs of LangChain 0.0.329, Jinja2 templates will be rendered using\nJinja2\u2019s SandboxedEnvironment by default. This sand-boxing should\nbe treated as a best-effort approach rather than a guarantee of security,\nas it is an opt-out rather than opt-in approach.\nDespite the sand-boxing, we recommend to never use jinja2 templates\nfrom untrusted sources.\nParameters\ntemplate \u2013 The template to load.\ntemplate_format \u2013 The format of the template. Use jinja2 for jinja2,\nand f-string or None for f-strings.\npartial_variables \u2013 \nA dictionary of variables that can be used to partiallyfill in the template. For example, if the template is\n\u201d{variable1} {variable2}\u201d, and partial_variables is\n{\u201cvariable1\u201d: \u201cfoo\u201d}, then the final prompt will be\n\u201cfoo {variable2}\u201d.\nReturns\nThe prompt template loaded from the template.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.prompt.PromptTemplate.html"}
{"id": "a41c962d8d89-6", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict, config: Optional[RunnableConfig] = None) \u2192 PromptValue\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.prompt.PromptTemplate.html"}
{"id": "a41c962d8d89-7", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npartial(**kwargs: Union[str, Callable[[], str]]) \u2192 BasePromptTemplate\u00b6\nReturn a partial of the prompt template.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the prompt.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.prompt.PromptTemplate.html"}
{"id": "a41c962d8d89-8", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the prompt.\nParameters\nfile_path \u2013 Path to directory to save prompt to.\nExample:\n.. code-block:: python\nprompt.save(file_path=\u201dpath/prompt.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.prompt.PromptTemplate.html"}
{"id": "a41c962d8d89-9", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.prompt.PromptTemplate.html"}
{"id": "a41c962d8d89-10", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Any\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using PromptTemplate\u00b6\nRePhraseQueryRetriever\nZapier Natural Language Actions\nDall-E Image Generator\nStreamlit Chat Message History\nContext\nArgilla\nComet\nAim\nWeights & Biases\nSageMaker Tracking\nRebuff\nMLflow\nFlyte\nVectara Text Generation\nNatural Language APIs\nyour local model path\nGoogle Drive\nGoogle Vertex AI PaLM \nPredibase\nHugging Face Local Pipelines\nEden AI\nFallbacks\nReversible data anonymization with Microsoft Presidio\nData anonymization with Microsoft Presidio\nRemoving logical fallacies from model output\nAmazon Comprehend Moderation Chain\nPairwise String Comparison\nCriteria Evaluation\nSet env var OPENAI_API_KEY or load from a .env file", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.prompt.PromptTemplate.html"}
{"id": "a41c962d8d89-11", "text": "Criteria Evaluation\nSet env var OPENAI_API_KEY or load from a .env file\nSet env var OPENAI_API_KEY or load from a .env file:\nQuestion Answering\nRetrieve from vector stores directly\nImprove document indexing with HyDE\nStructure answers with OpenAI functions\nNeo4j DB QA chain\nMulti-agent authoritarian speaker selection\nAgent Debates with Tools\nBash chain\nHow to use a SmartLLMChain\nElasticsearch\nSQL\nMultiQueryRetriever\nWebResearchRetriever\nLost in the middle: The problem with long contexts\nCustom Memory\nMemory in the Multi-Input Chain\nMemory in LLMChain\nMultiple Memory classes\nCustomizing Conversational Memory\nConversation Knowledge Graph\nLogging to file\nRetry parser\nDatetime parser\nPydantic (JSON) parser\nSelect by maximal marginal relevance (MMR)\nSelect by n-gram overlap\nPrompt pipelining\nTemplate formats\nConnecting to a Feature Store\nRouter\nTransformation\nCustom chain\nAsync API\nFirst we add a step to load memory\nConfigure Runnable traces", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.prompt.PromptTemplate.html"}
{"id": "d0f7c007259e-0", "text": "langchain.prompts.example_selector.semantic_similarity.sorted_values\u00b6\nlangchain.prompts.example_selector.semantic_similarity.sorted_values(values: Dict[str, str]) \u2192 List[Any][source]\u00b6\nReturn a list of values in dict sorted by key.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.semantic_similarity.sorted_values.html"}
{"id": "228d0547a61d-0", "text": "langchain.prompts.chat.SystemMessagePromptTemplate\u00b6\nclass langchain.prompts.chat.SystemMessagePromptTemplate[source]\u00b6\nBases: BaseStringMessagePromptTemplate\nSystem message prompt template.\nThis is a message that is not sent to the user.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAdditional keyword arguments to pass to the prompt template.\nparam prompt: langchain.prompts.base.StringPromptTemplate [Required]\u00b6\nString prompt template.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.SystemMessagePromptTemplate.html"}
{"id": "228d0547a61d-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nformat(**kwargs: Any) \u2192 BaseMessage[source]\u00b6\nFormat the prompt template.\nParameters\n**kwargs \u2013 Keyword arguments to use for formatting.\nReturns\nFormatted message.\nformat_messages(**kwargs: Any) \u2192 List[BaseMessage]\u00b6\nFormat messages from kwargs.\nParameters\n**kwargs \u2013 Keyword arguments to use for formatting.\nReturns\nList of BaseMessages.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_template(template: str, template_format: str = 'f-string', **kwargs: Any) \u2192 MessagePromptTemplateT\u00b6\nCreate a class from a string template.\nParameters\ntemplate \u2013 a template.\ntemplate_format \u2013 format of the template.\n**kwargs \u2013 keyword arguments to pass to the constructor.\nReturns\nA new instance of this class.\nclassmethod from_template_file(template_file: Union[str, Path], input_variables: List[str], **kwargs: Any) \u2192 MessagePromptTemplateT\u00b6\nCreate a class from a template file.\nParameters\ntemplate_file \u2013 path to a template file. String or Path.\ninput_variables \u2013 list of input variables.\n**kwargs \u2013 keyword arguments to pass to the constructor.\nReturns\nA new instance of this class.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.SystemMessagePromptTemplate.html"}
{"id": "228d0547a61d-2", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.SystemMessagePromptTemplate.html"}
{"id": "228d0547a61d-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty input_variables: List[str]\u00b6\nInput variables for this prompt template.\nReturns\nList of input variable names.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using SystemMessagePromptTemplate\u00b6\nAnthropic\n\ud83d\ude85 LiteLLM\nKonko\nOpenAI\nGoogle Cloud Platform Vertex AI PaLM \nJinaChat\nFigma\nSet env var OPENAI_API_KEY or load from a .env file:\nCAMEL Role-Playing Autonomous Cooperative Agents\nCode writing", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.SystemMessagePromptTemplate.html"}
{"id": "2328dbb19939-0", "text": "langchain.prompts.example_selector.semantic_similarity.MaxMarginalRelevanceExampleSelector\u00b6\nclass langchain.prompts.example_selector.semantic_similarity.MaxMarginalRelevanceExampleSelector[source]\u00b6\nBases: SemanticSimilarityExampleSelector\nExampleSelector that selects examples based on Max Marginal Relevance.\nThis was shown to improve performance in this paper:\nhttps://arxiv.org/pdf/2211.13892.pdf\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam example_keys: Optional[List[str]] = None\u00b6\nOptional keys to filter examples to.\nparam fetch_k: int = 20\u00b6\nNumber of examples to fetch to rerank.\nparam input_keys: Optional[List[str]] = None\u00b6\nOptional keys to filter input to. If provided, the search is based on\nthe input variables instead of all variables.\nparam k: int = 4\u00b6\nNumber of examples to select.\nparam vectorstore: langchain.schema.vectorstore.VectorStore [Required]\u00b6\nVectorStore than contains information about examples.\nadd_example(example: Dict[str, str]) \u2192 str\u00b6\nAdd new example to vectorstore.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.semantic_similarity.MaxMarginalRelevanceExampleSelector.html"}
{"id": "2328dbb19939-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_examples(examples: List[dict], embeddings: Embeddings, vectorstore_cls: Type[VectorStore], k: int = 4, input_keys: Optional[List[str]] = None, fetch_k: int = 20, **vectorstore_cls_kwargs: Any) \u2192 MaxMarginalRelevanceExampleSelector[source]\u00b6\nCreate k-shot example selector using example list and embeddings.\nReshuffles examples dynamically based on query similarity.\nParameters\nexamples \u2013 List of examples to use in the prompt.\nembeddings \u2013 An iniialized embedding API interface, e.g. OpenAIEmbeddings().\nvectorstore_cls \u2013 A vector store DB interface class, e.g. FAISS.\nk \u2013 Number of examples to select\ninput_keys \u2013 If provided, the search is based on the input variables\ninstead of all variables.\nvectorstore_cls_kwargs \u2013 optional kwargs containing url for vector store\nReturns\nThe ExampleSelector instantiated, backed by a vector store.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.semantic_similarity.MaxMarginalRelevanceExampleSelector.html"}
{"id": "2328dbb19939-2", "text": "Returns\nThe ExampleSelector instantiated, backed by a vector store.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nselect_examples(input_variables: Dict[str, str]) \u2192 List[dict][source]\u00b6\nSelect which examples to use based on semantic similarity.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.semantic_similarity.MaxMarginalRelevanceExampleSelector.html"}
{"id": "2328dbb19939-3", "text": "Try to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using MaxMarginalRelevanceExampleSelector\u00b6\nSelect by maximal marginal relevance (MMR)", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.semantic_similarity.MaxMarginalRelevanceExampleSelector.html"}
{"id": "307c03107c3a-0", "text": "langchain.prompts.base.check_valid_template\u00b6\nlangchain.prompts.base.check_valid_template(template: str, template_format: str, input_variables: List[str]) \u2192 None[source]\u00b6\nCheck that template string is valid.\nParameters\ntemplate \u2013 The template string.\ntemplate_format \u2013 The template format. Should be one of \u201cf-string\u201d or \u201cjinja2\u201d.\ninput_variables \u2013 The input variables.\nRaises\nValueError \u2013 If the template format is not supported.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.check_valid_template.html"}
{"id": "c8286ec5c23e-0", "text": "langchain.prompts.chat.ChatPromptTemplate\u00b6\nclass langchain.prompts.chat.ChatPromptTemplate[source]\u00b6\nBases: BaseChatPromptTemplate\nA prompt template for chat models.\nUse to create flexible templated prompts for chat models.\nExamples\nfrom langchain.prompts import ChatPromptTemplate\ntemplate = ChatPromptTemplate.from_messages([\n    (\"system\", \"You are a helpful AI bot. Your name is {name}.\"),\n    (\"human\", \"Hello, how are you doing?\"),\n    (\"ai\", \"I'm doing well, thanks!\"),\n    (\"human\", \"{user_input}\"),\n])\nmessages = template.format_messages(\n    name=\"Bob\",\n    user_input=\"What is your name?\"\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam input_types: Dict[str, Any] [Optional]\u00b6\nA dictionary of the types of the variables the prompt template expects.\nIf not provided, all variables are assumed to be strings.\nparam input_variables: List[str] [Required]\u00b6\nList of input variables in template messages. Used for validation.\nparam messages: List[MessageLike] [Required]\u00b6\nList of messages consisting of either message prompt templates or messages.\nparam output_parser: Optional[BaseOutputParser] = None\u00b6\nHow to parse the output of calling an LLM on this formatted prompt.\nparam partial_variables: Mapping[str, Union[str, Callable[[], str]]] [Optional]\u00b6\nparam validate_template: bool = False\u00b6\nWhether or not to try validating the template.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptTemplate.html"}
{"id": "c8286ec5c23e-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nappend(message: Union[BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate, Tuple[str, str], Tuple[Type, str], str]) \u2192 None[source]\u00b6\nAppend message to the end of the chat template.\nParameters\nmessage \u2013 representation of a message to append.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptTemplate.html"}
{"id": "c8286ec5c23e-2", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptTemplate.html"}
{"id": "c8286ec5c23e-3", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of prompt.\nextend(messages: Sequence[Union[BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate, Tuple[str, str], Tuple[Type, str], str]]) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptTemplate.html"}
{"id": "c8286ec5c23e-4", "text": "Extend the chat template with a sequence of messages.\nformat(**kwargs: Any) \u2192 str[source]\u00b6\nFormat the chat template into a string.\nParameters\n**kwargs \u2013 keyword arguments to use for filling in template variables\nin all the template messages in this chat template.\nReturns\nformatted string\nformat_messages(**kwargs: Any) \u2192 List[BaseMessage][source]\u00b6\nFormat the chat template into a list of finalized messages.\nParameters\n**kwargs \u2013 keyword arguments to use for filling in template variables\nin all the template messages in this chat template.\nReturns\nlist of formatted messages\nformat_prompt(**kwargs: Any) \u2192 PromptValue\u00b6\nFormat prompt. Should return a PromptValue.\n:param **kwargs: Keyword arguments to use for formatting.\nReturns\nPromptValue.\nclassmethod from_messages(messages: Sequence[Union[BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate, Tuple[str, str], Tuple[Type, str], str]]) \u2192 ChatPromptTemplate[source]\u00b6\nCreate a chat prompt template from a variety of message formats.\nExamples\nInstantiation from a list of message templates:\ntemplate = ChatPromptTemplate.from_messages([\n    (\"human\", \"Hello, how are you?\"),\n    (\"ai\", \"I'm doing well, thanks!\"),\n    (\"human\", \"That's good to hear.\"),\n])\nInstantiation from mixed message formats:\ntemplate = ChatPromptTemplate.from_messages([\n    SystemMessage(content=\"hello\"),\n    (\"human\", \"Hello, how are you?\"),\n])\nParameters\nmessages \u2013 sequence of message representations.\nA message can be represented using the following formats:\n(1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of\n(message type, template); e.g., (\u201chuman\u201d, \u201c{user_input}\u201d),", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptTemplate.html"}
{"id": "c8286ec5c23e-5", "text": "(message type, template); e.g., (\u201chuman\u201d, \u201c{user_input}\u201d),\n(4) 2-tuple of (message class, template), (4) a string which is\nshorthand for (\u201chuman\u201d, template); e.g., \u201c{user_input}\u201d\nReturns\na chat prompt template\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_role_strings(string_messages: List[Tuple[str, str]]) \u2192 ChatPromptTemplate[source]\u00b6\n[Deprecated]  Create a chat prompt template from a list of (role, template) tuples.\nParameters\nstring_messages \u2013 list of (role, template) tuples.\nstring_messages \u2013 list of (role, template) tuples.\nReturns\na chat prompt template[Deprecated] Create a chat prompt template from a list of (role, template) tuples.\nReturns\na chat prompt template\nNotes\nDeprecated since version 0.0.260: Use from_messages classmethod instead.\nclassmethod from_strings(string_messages: List[Tuple[Type[BaseMessagePromptTemplate], str]]) \u2192 ChatPromptTemplate[source]\u00b6\n[Deprecated]  Create a chat prompt template from a list of (role class, template) tuples.\nParameters\nstring_messages \u2013 list of (role class, template) tuples.\nstring_messages \u2013 list of (role class, template) tuples.\nReturns\na chat prompt template[Deprecated] Create a chat prompt template from a list of (role class, template) tuples.\nReturns\na chat prompt template\nNotes\nDeprecated since version 0.0.260: Use from_messages classmethod instead.\nclassmethod from_template(template: str, **kwargs: Any) \u2192 ChatPromptTemplate[source]\u00b6\nCreate a chat prompt template from a template string.\nCreates a chat template consisting of a single message assumed to be from\nthe human.\nParameters\ntemplate \u2013 template string", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptTemplate.html"}
{"id": "c8286ec5c23e-6", "text": "the human.\nParameters\ntemplate \u2013 template string\n**kwargs \u2013 keyword arguments to pass to the constructor.\nReturns\nA new instance of this class.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict, config: Optional[RunnableConfig] = None) \u2192 PromptValue\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptTemplate.html"}
{"id": "c8286ec5c23e-7", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptTemplate.html"}
{"id": "c8286ec5c23e-8", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npartial(**kwargs: Union[str, Callable[[], str]]) \u2192 ChatPromptTemplate[source]\u00b6\nGet a new ChatPromptTemplate with some input variables already filled in.\nParameters\n**kwargs \u2013 keyword arguments to use for filling in template variables. Ought\nto be a subset of the input variables.\nReturns\nA new ChatPromptTemplate.\nExample\nfrom langchain.prompts import ChatPromptTemplate\ntemplate = ChatPromptTemplate.from_messages(\n    [\n        (\"system\", \"You are an AI assistant named {name}.\"),\n        (\"human\", \"Hi I'm {user}\"),\n        (\"ai\", \"Hi there, {user}, I'm {name}.\"),\n        (\"human\", \"{input}\"),\n    ]\n)\ntemplate2 = template.partial(user=\"Lucy\", name=\"R2D2\")\ntemplate2.format_messages(input=\"hello\")\nsave(file_path: Union[Path, str]) \u2192 None[source]\u00b6\nSave prompt to file.\nParameters\nfile_path \u2013 path to file.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptTemplate.html"}
{"id": "c8286ec5c23e-9", "text": "to_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptTemplate.html"}
{"id": "c8286ec5c23e-10", "text": "on_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Any\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nReturn a list of attribute names that should be included in the\nserialized kwargs. These attributes must be accepted by the\nconstructor.\nproperty lc_secrets: Dict[str, str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptTemplate.html"}
{"id": "c8286ec5c23e-11", "text": "constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ChatPromptTemplate\u00b6\nFacebook Messenger\nChat loaders\niMessage\nAnthropic\n\ud83d\ude85 LiteLLM\nKonko\nOpenAI\nGoogle Cloud Platform Vertex AI PaLM \nJinaChat\nContext\nOpenAI Functions Metadata Tagger\nFigma\nFireworks\nFallbacks\nSet env var OPENAI_API_KEY or load from a .env file:\nMultiple Retrieval Sources\nStructure answers with OpenAI functions\nMulti-agent authoritarian speaker selection\nMultiVector Retriever\nMemory in LLMChain\nRetry parser\nPydantic (JSON) parser\nFew-shot examples for chat models\nPrompt pipelining\nUsing OpenAI functions\ninterface.md\nFirst we add a step to load memory\nsql_db.md\nprompt_llm_parser.md\nAdding memory\nmultiple_chains.md\nCode writing\nUsing tools\nAdding moderation", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptTemplate.html"}
{"id": "b88a9a252e64-0", "text": "langchain.prompts.chat.MessagesPlaceholder\u00b6\nclass langchain.prompts.chat.MessagesPlaceholder[source]\u00b6\nBases: BaseMessagePromptTemplate\nPrompt template that assumes variable is already list of messages.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam variable_name: str [Required]\u00b6\nName of variable to use as messages.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.MessagesPlaceholder.html"}
{"id": "b88a9a252e64-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nformat_messages(**kwargs: Any) \u2192 List[BaseMessage][source]\u00b6\nFormat messages from kwargs.\nParameters\n**kwargs \u2013 Keyword arguments to use for formatting.\nReturns\nList of BaseMessage.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.MessagesPlaceholder.html"}
{"id": "b88a9a252e64-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty input_variables: List[str]\u00b6\nInput variables for this prompt template.\nReturns\nList of input variable names.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.MessagesPlaceholder.html"}
{"id": "b88a9a252e64-3", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using MessagesPlaceholder\u00b6\nSet env var OPENAI_API_KEY or load from a .env file:\nConversational Retrieval Agent\nAgents\nMemory in LLMChain\nAdd Memory to OpenAI Functions Agent\nTypes of `MessagePromptTemplate`\nAdding memory", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.MessagesPlaceholder.html"}
{"id": "632130a7d9b0-0", "text": "langchain.prompts.prompt.Prompt\u00b6\nlangchain.prompts.prompt.Prompt\u00b6\nalias of PromptTemplate", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.prompt.Prompt.html"}
{"id": "4cab35cd0c9e-0", "text": "langchain.prompts.base.StringPromptValue\u00b6\nclass langchain.prompts.base.StringPromptValue[source]\u00b6\nBases: PromptValue\nString prompt value.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam text: str [Required]\u00b6\nPrompt text.\nparam type: Literal['StringPromptValue'] = 'StringPromptValue'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.StringPromptValue.html"}
{"id": "4cab35cd0c9e-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.StringPromptValue.html"}
{"id": "4cab35cd0c9e-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nto_messages() \u2192 List[BaseMessage][source]\u00b6\nReturn prompt as messages.\nto_string() \u2192 str[source]\u00b6\nReturn prompt as string.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.base.StringPromptValue.html"}
{"id": "316f0fe83fdd-0", "text": "langchain.prompts.few_shot.FewShotChatMessagePromptTemplate\u00b6\nclass langchain.prompts.few_shot.FewShotChatMessagePromptTemplate[source]\u00b6\nBases: BaseChatPromptTemplate, _FewShotPromptTemplateMixin\nChat prompt template that supports few-shot examples.\nThe high level structure of produced by this prompt template is a list of messages\nconsisting of prefix message(s), example message(s), and suffix message(s).\nThis structure enables creating a conversation with intermediate examples like:\nSystem: You are a helpful AI Assistant\nHuman: What is 2+2?\nAI: 4\nHuman: What is 2+3?\nAI: 5\nHuman: What is 4+4?\nThis prompt template can be used to generate a fixed list of examples or else\nto dynamically select examples based on the input.\nExamples\nPrompt template with a fixed list of examples (matching the sample\nconversation above):\nfrom langchain.prompts import (\n    FewShotChatMessagePromptTemplate,\n    ChatPromptTemplate\n)\nexamples = [\n    {\"input\": \"2+2\", \"output\": \"4\"},\n    {\"input\": \"2+3\", \"output\": \"5\"},\n]\nexample_prompt = ChatPromptTemplate.from_messages(\n    [('human', '{input}'), ('ai', '{output}')]\n)\nfew_shot_prompt = FewShotChatMessagePromptTemplate(\n    examples=examples,\n    # This is a prompt template used to format each individual example.\n    example_prompt=example_prompt,\n)\nfinal_prompt = ChatPromptTemplate.from_messages(\n    [\n        ('system', 'You are a helpful AI Assistant'),\n        few_shot_prompt,\n        ('human', '{input}'),\n    ]\n)\nfinal_prompt.format(input=\"What is 4+4?\")\nPrompt template with dynamically selected examples:", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotChatMessagePromptTemplate.html"}
{"id": "316f0fe83fdd-1", "text": "Prompt template with dynamically selected examples:\nfrom langchain.prompts import SemanticSimilarityExampleSelector\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import Chroma\nexamples = [\n    {\"input\": \"2+2\", \"output\": \"4\"},\n    {\"input\": \"2+3\", \"output\": \"5\"},\n    {\"input\": \"2+4\", \"output\": \"6\"},\n    # ...\n]\nto_vectorize = [\n    \" \".join(example.values())\n    for example in examples\n]\nembeddings = OpenAIEmbeddings()\nvectorstore = Chroma.from_texts(\n    to_vectorize, embeddings, metadatas=examples\n)\nexample_selector = SemanticSimilarityExampleSelector(\n    vectorstore=vectorstore\n)\nfrom langchain.schema import SystemMessage\nfrom langchain.prompts import HumanMessagePromptTemplate\nfrom langchain.prompts.few_shot import FewShotChatMessagePromptTemplate\nfew_shot_prompt = FewShotChatMessagePromptTemplate(\n    # Which variable(s) will be passed to the example selector.\n    input_variables=[\"input\"],\n    example_selector=example_selector,\n    # Define how each example will be formatted.\n    # In this case, each example will become 2 messages:\n    # 1 human, and 1 AI\n    example_prompt=(\n        HumanMessagePromptTemplate.from_template(\"{input}\")\n        + AIMessagePromptTemplate.from_template(\"{output}\")\n    ),\n)\n# Define the overall prompt.\nfinal_prompt = (\n    SystemMessagePromptTemplate.from_template(\n        \"You are a helpful AI Assistant\"\n    )\n    + few_shot_prompt\n    + HumanMessagePromptTemplate.from_template(\"{input}\")\n)\n# Show the prompt\nprint(final_prompt.format_messages(input=\"What's 3+3?\"))", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotChatMessagePromptTemplate.html"}
{"id": "316f0fe83fdd-2", "text": "print(final_prompt.format_messages(input=\"What's 3+3?\"))\n# Use within an LLM\nfrom langchain.chat_models import ChatAnthropic\nchain = final_prompt | ChatAnthropic()\nchain.invoke({\"input\": \"What's 3+3?\"})\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam example_prompt: Union[BaseMessagePromptTemplate, BaseChatPromptTemplate] [Required]\u00b6\nThe class to format each example.\nparam example_selector: Optional[BaseExampleSelector] = None\u00b6\nExampleSelector to choose the examples to format into the prompt.\nEither this or examples should be provided.\nparam examples: Optional[List[dict]] = None\u00b6\nExamples to format into the prompt.\nEither this or example_selector should be provided.\nparam input_types: Dict[str, Any] [Optional]\u00b6\nA dictionary of the types of the variables the prompt template expects.\nIf not provided, all variables are assumed to be strings.\nparam input_variables: List[str] [Optional]\u00b6\nA list of the names of the variables the prompt template will use\nto pass to the example_selector, if provided.\nparam output_parser: Optional[BaseOutputParser] = None\u00b6\nHow to parse the output of calling an LLM on this formatted prompt.\nparam partial_variables: Mapping[str, Union[str, Callable[[], str]]] [Optional]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotChatMessagePromptTemplate.html"}
{"id": "316f0fe83fdd-3", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotChatMessagePromptTemplate.html"}
{"id": "316f0fe83fdd-4", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotChatMessagePromptTemplate.html"}
{"id": "316f0fe83fdd-5", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of prompt.\nformat(**kwargs: Any) \u2192 str[source]\u00b6\nFormat the prompt with inputs generating a string.\nUse this method to generate a string representation of a prompt consisting\nof chat messages.\nUseful for feeding into a string based completion language model or debugging.\nParameters\n**kwargs \u2013 keyword arguments to use for formatting.\nReturns\nA string representation of the prompt\nformat_messages(**kwargs: Any) \u2192 List[BaseMessage][source]\u00b6\nFormat kwargs into a list of messages.\nParameters\n**kwargs \u2013 keyword arguments to use for filling in templates in messages.\nReturns\nA list of formatted messages with all template variables filled in.\nformat_prompt(**kwargs: Any) \u2192 PromptValue\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotChatMessagePromptTemplate.html"}
{"id": "316f0fe83fdd-6", "text": "format_prompt(**kwargs: Any) \u2192 PromptValue\u00b6\nFormat prompt. Should return a PromptValue.\n:param **kwargs: Keyword arguments to use for formatting.\nReturns\nPromptValue.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict, config: Optional[RunnableConfig] = None) \u2192 PromptValue\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotChatMessagePromptTemplate.html"}
{"id": "316f0fe83fdd-7", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotChatMessagePromptTemplate.html"}
{"id": "316f0fe83fdd-8", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npartial(**kwargs: Union[str, Callable[[], str]]) \u2192 BasePromptTemplate\u00b6\nReturn a partial of the prompt template.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the prompt.\nParameters\nfile_path \u2013 Path to directory to save prompt to.\nExample:\n.. code-block:: python\nprompt.save(file_path=\u201dpath/prompt.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotChatMessagePromptTemplate.html"}
{"id": "316f0fe83fdd-9", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotChatMessagePromptTemplate.html"}
{"id": "316f0fe83fdd-10", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Any\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nReturn a list of attribute names that should be included in the\nserialized kwargs. These attributes must be accepted by the\nconstructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using FewShotChatMessagePromptTemplate\u00b6\nFew-shot examples for chat models", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.few_shot.FewShotChatMessagePromptTemplate.html"}
{"id": "e158bf434da6-0", "text": "langchain.prompts.chat.ChatMessagePromptTemplate\u00b6\nclass langchain.prompts.chat.ChatMessagePromptTemplate[source]\u00b6\nBases: BaseStringMessagePromptTemplate\nChat message prompt template.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAdditional keyword arguments to pass to the prompt template.\nparam prompt: langchain.prompts.base.StringPromptTemplate [Required]\u00b6\nString prompt template.\nparam role: str [Required]\u00b6\nRole of the message.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatMessagePromptTemplate.html"}
{"id": "e158bf434da6-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nformat(**kwargs: Any) \u2192 BaseMessage[source]\u00b6\nFormat the prompt template.\nParameters\n**kwargs \u2013 Keyword arguments to use for formatting.\nReturns\nFormatted message.\nformat_messages(**kwargs: Any) \u2192 List[BaseMessage]\u00b6\nFormat messages from kwargs.\nParameters\n**kwargs \u2013 Keyword arguments to use for formatting.\nReturns\nList of BaseMessages.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_template(template: str, template_format: str = 'f-string', **kwargs: Any) \u2192 MessagePromptTemplateT\u00b6\nCreate a class from a string template.\nParameters\ntemplate \u2013 a template.\ntemplate_format \u2013 format of the template.\n**kwargs \u2013 keyword arguments to pass to the constructor.\nReturns\nA new instance of this class.\nclassmethod from_template_file(template_file: Union[str, Path], input_variables: List[str], **kwargs: Any) \u2192 MessagePromptTemplateT\u00b6\nCreate a class from a template file.\nParameters\ntemplate_file \u2013 path to a template file. String or Path.\ninput_variables \u2013 list of input variables.\n**kwargs \u2013 keyword arguments to pass to the constructor.\nReturns\nA new instance of this class.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatMessagePromptTemplate.html"}
{"id": "e158bf434da6-2", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatMessagePromptTemplate.html"}
{"id": "e158bf434da6-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty input_variables: List[str]\u00b6\nInput variables for this prompt template.\nReturns\nList of input variable names.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using ChatMessagePromptTemplate\u00b6\nTypes of `MessagePromptTemplate`", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatMessagePromptTemplate.html"}
{"id": "2a25265685fc-0", "text": "langchain.prompts.chat.ChatPromptValue\u00b6\nclass langchain.prompts.chat.ChatPromptValue[source]\u00b6\nBases: PromptValue\nChat prompt value.\nA type of a prompt value that is built from messages.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam messages: Sequence[langchain.schema.messages.BaseMessage] [Required]\u00b6\nList of messages.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptValue.html"}
{"id": "2a25265685fc-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptValue.html"}
{"id": "2a25265685fc-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nto_messages() \u2192 List[BaseMessage][source]\u00b6\nReturn prompt as a list of messages.\nto_string() \u2192 str[source]\u00b6\nReturn prompt as string.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptValue.html"}
{"id": "0ca8e1ab4f6b-0", "text": "langchain.prompts.chat.ChatPromptValueConcrete\u00b6\nclass langchain.prompts.chat.ChatPromptValueConcrete[source]\u00b6\nBases: ChatPromptValue\nChat prompt value which explicitly lists out the message types it accepts.\nFor use in external schemas.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam messages: Sequence[Union[langchain.schema.messages.AIMessage, langchain.schema.messages.HumanMessage, langchain.schema.messages.ChatMessage, langchain.schema.messages.SystemMessage, langchain.schema.messages.FunctionMessage, langchain.schema.messages.ToolMessage]] [Required]\u00b6\nList of messages.\nparam type: Literal['ChatPromptValueConcrete'] = 'ChatPromptValueConcrete'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptValueConcrete.html"}
{"id": "0ca8e1ab4f6b-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptValueConcrete.html"}
{"id": "0ca8e1ab4f6b-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nto_messages() \u2192 List[BaseMessage]\u00b6\nReturn prompt as a list of messages.\nto_string() \u2192 str\u00b6\nReturn prompt as string.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.ChatPromptValueConcrete.html"}
{"id": "dff309f0c02b-0", "text": "langchain.prompts.example_selector.length_based.LengthBasedExampleSelector\u00b6\nclass langchain.prompts.example_selector.length_based.LengthBasedExampleSelector[source]\u00b6\nBases: BaseExampleSelector, BaseModel\nSelect examples based on length.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam example_prompt: langchain.prompts.prompt.PromptTemplate [Required]\u00b6\nPrompt template used to format the examples.\nparam examples: List[dict] [Required]\u00b6\nA list of the examples that the prompt template expects.\nparam get_text_length: Callable[[str], int] = <function _get_length_based>\u00b6\nFunction to measure prompt length. Defaults to word count.\nparam max_length: int = 2048\u00b6\nMax length for the prompt, beyond which examples are cut.\nadd_example(example: Dict[str, str]) \u2192 None[source]\u00b6\nAdd new example to list.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.length_based.LengthBasedExampleSelector.html"}
{"id": "dff309f0c02b-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.length_based.LengthBasedExampleSelector.html"}
{"id": "dff309f0c02b-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nselect_examples(input_variables: Dict[str, str]) \u2192 List[dict][source]\u00b6\nSelect which examples to use based on the input lengths.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.example_selector.length_based.LengthBasedExampleSelector.html"}
{"id": "01608b002030-0", "text": "langchain.prompts.chat.AIMessagePromptTemplate\u00b6\nclass langchain.prompts.chat.AIMessagePromptTemplate[source]\u00b6\nBases: BaseStringMessagePromptTemplate\nAI message prompt template. This is a message sent from the AI.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAdditional keyword arguments to pass to the prompt template.\nparam prompt: langchain.prompts.base.StringPromptTemplate [Required]\u00b6\nString prompt template.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.AIMessagePromptTemplate.html"}
{"id": "01608b002030-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nformat(**kwargs: Any) \u2192 BaseMessage[source]\u00b6\nFormat the prompt template.\nParameters\n**kwargs \u2013 Keyword arguments to use for formatting.\nReturns\nFormatted message.\nformat_messages(**kwargs: Any) \u2192 List[BaseMessage]\u00b6\nFormat messages from kwargs.\nParameters\n**kwargs \u2013 Keyword arguments to use for formatting.\nReturns\nList of BaseMessages.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_template(template: str, template_format: str = 'f-string', **kwargs: Any) \u2192 MessagePromptTemplateT\u00b6\nCreate a class from a string template.\nParameters\ntemplate \u2013 a template.\ntemplate_format \u2013 format of the template.\n**kwargs \u2013 keyword arguments to pass to the constructor.\nReturns\nA new instance of this class.\nclassmethod from_template_file(template_file: Union[str, Path], input_variables: List[str], **kwargs: Any) \u2192 MessagePromptTemplateT\u00b6\nCreate a class from a template file.\nParameters\ntemplate_file \u2013 path to a template file. String or Path.\ninput_variables \u2013 list of input variables.\n**kwargs \u2013 keyword arguments to pass to the constructor.\nReturns\nA new instance of this class.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.AIMessagePromptTemplate.html"}
{"id": "01608b002030-2", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.AIMessagePromptTemplate.html"}
{"id": "01608b002030-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty input_variables: List[str]\u00b6\nInput variables for this prompt template.\nReturns\nList of input variable names.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using AIMessagePromptTemplate\u00b6\nAnthropic\n\ud83d\ude85 LiteLLM\nKonko\nOpenAI\nJinaChat\nFigma", "source": "lang/api.python.langchain.com/en/latest/prompts/langchain.prompts.chat.AIMessagePromptTemplate.html"}
{"id": "77b39f033514-0", "text": "langchain_experimental.comprehend_moderation.prompt_safety.ComprehendPromptSafety\u00b6\nclass langchain_experimental.comprehend_moderation.prompt_safety.ComprehendPromptSafety(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None)[source]\u00b6\nMethods\n__init__(client[,\u00a0callback,\u00a0unique_id,\u00a0chain_id])\nvalidate(prompt_value[,\u00a0config])\nCheck and validate the safety of the given prompt text.\n__init__(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None) \u2192 None[source]\u00b6\nvalidate(prompt_value: str, config: Any = None) \u2192 str[source]\u00b6\nCheck and validate the safety of the given prompt text.\nParameters\nprompt_value (str) \u2013 The input text to be checked for unsafe text.\nconfig (Dict[str, Any]) \u2013 Configuration settings for prompt safety checks.\nRaises\nValueError \u2013 If unsafe prompt is found in the prompt text based\non the specified threshold. \u2013 \nReturns\nThe input prompt_value.\nReturn type\nstr\nNote\nThis function checks the safety of the provided prompt text using\nComprehend\u2019s classify_document API and raises an error if unsafe\ntext is detected with a score above the specified threshold.\nExample\ncomprehend_client = boto3.client(\u2018comprehend\u2019)\nprompt_text = \u201cPlease tell me your credit card information.\u201d\nconfig = {\u201cthreshold\u201d: 0.7}\nchecked_prompt = check_prompt_safety(comprehend_client, prompt_text, config)", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.prompt_safety.ComprehendPromptSafety.html"}
{"id": "078f752d7889-0", "text": "langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPromptSafetyConfig\u00b6\nclass langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPromptSafetyConfig[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam threshold: float = 0.5\u00b6\nThreshold for Prompt Safety classification\nconfidence score, defaults to 0.5 i.e. 50%\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPromptSafetyConfig.html"}
{"id": "078f752d7889-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPromptSafetyConfig.html"}
{"id": "078f752d7889-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPromptSafetyConfig.html"}
{"id": "886c70fc64e6-0", "text": "langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain\u00b6\nclass langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain[source]\u00b6\nBases: Chain\nA subclass of Chain, designed to apply moderation to LLMs.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam client: Optional[Any] = None\u00b6\nboto3 client object for connection to Amazon Comprehend\nparam credentials_profile_name: Optional[str] = None\u00b6\nThe name of the profile in the ~/.aws/credentials or ~/.aws/config files, which\nhas either access keys or role information specified.\nIf not specified, the default credential profile or, if on an EC2 instance,\ncredentials from IMDS will be used.\nSee: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\nparam input_key: str = 'input'\u00b6\nKey used to fetch/store the input in data containers. Defaults to input\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-1", "text": "and at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam moderation_callback: Optional[langchain_experimental.comprehend_moderation.base_moderation_callbacks.BaseModerationCallbackHandler] = None\u00b6\nCallback handler for moderation, this is different\nfrom regular callbacks which can be used in addition to this.\nparam moderation_config: langchain_experimental.comprehend_moderation.base_moderation_config.BaseModerationConfig = BaseModerationConfig(filters=[ModerationPiiConfig(threshold=0.5, labels=[], redact=False, mask_character='*'), ModerationToxicityConfig(threshold=0.5, labels=[]), ModerationPromptSafetyConfig(threshold=0.5)])\u00b6\nConfiguration settings for moderation,\ndefaults to BaseModerationConfig with default values\nparam output_key: str = 'output'\u00b6\nKey used to fetch/store the output in data containers. Defaults to output\nparam region_name: Optional[str] = None\u00b6\nThe aws region e.g., us-west-2. Fallsback to AWS_DEFAULT_REGION env variable\nor region specified in ~/.aws/config in case it is not provided here.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-2", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam unique_id: Optional[str] = None\u00b6\nA unique id that can be used to identify or group a user or session\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-3", "text": "metadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-4", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-5", "text": "callbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-6", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-7", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-8", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-9", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-10", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-11", "text": "Returns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-12", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-13", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-14", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nReturns a list of input keys expected by the prompt.\nThis method defines the input keys that the prompt expects in order to perform\nits processing. It ensures that the specified keys are available for providing\ninput to the prompt.\nReturns\nA list of input keys.\nReturn type\nList[str]\nNote\nThis method is considered private and may not be intended for direct\nexternal use.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nReturns a list of output keys.\nThis method defines the output keys that will be used to access the output\nvalues produced by the chain or function. It ensures that the specified keys\nare available to access the outputs.\nReturns\nA list of output keys.\nReturn type\nList[str]\nNote\nThis method is considered private and may not be intended for direct\nexternal use.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "886c70fc64e6-15", "text": "external use.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain.html"}
{"id": "7f0051eff250-0", "text": "langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPiiConfig\u00b6\nclass langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPiiConfig[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam labels: List[str] = []\u00b6\nList of PII Universal Labels.\nDefaults to list[]\nparam mask_character: str = '*'\u00b6\nRedaction mask character in case redact=True, defaults to asterisk (*)\nparam redact: bool = False\u00b6\nWhether to perform redaction of detected PII entities\nparam threshold: float = 0.5\u00b6\nThreshold for PII confidence score, defaults to 0.5 i.e. 50%\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPiiConfig.html"}
{"id": "7f0051eff250-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPiiConfig.html"}
{"id": "7f0051eff250-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPiiConfig.html"}
{"id": "f79129b2e0bf-0", "text": "langchain_experimental.comprehend_moderation.pii.ComprehendPII\u00b6\nclass langchain_experimental.comprehend_moderation.pii.ComprehendPII(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None)[source]\u00b6\nMethods\n__init__(client[,\u00a0callback,\u00a0unique_id,\u00a0chain_id])\nvalidate(prompt_value[,\u00a0config])\n__init__(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None) \u2192 None[source]\u00b6\nvalidate(prompt_value: str, config: Any = None) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.pii.ComprehendPII.html"}
{"id": "7a8241cc14f2-0", "text": "langchain_experimental.comprehend_moderation.base_moderation_config.BaseModerationConfig\u00b6\nclass langchain_experimental.comprehend_moderation.base_moderation_config.BaseModerationConfig[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam filters: List[Union[langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPiiConfig, langchain_experimental.comprehend_moderation.base_moderation_config.ModerationToxicityConfig, langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPromptSafetyConfig]] = [ModerationPiiConfig(threshold=0.5, labels=[], redact=False, mask_character='*'), ModerationToxicityConfig(threshold=0.5, labels=[]), ModerationPromptSafetyConfig(threshold=0.5)]\u00b6\nFilters applied to the moderation chain, defaults to\n[ModerationPiiConfig(), ModerationToxicityConfig(),\nModerationPromptSafetyConfig()]\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_config.BaseModerationConfig.html"}
{"id": "7a8241cc14f2-1", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_config.BaseModerationConfig.html"}
{"id": "7a8241cc14f2-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_config.BaseModerationConfig.html"}
{"id": "6d0163f3530b-0", "text": "langchain_experimental.comprehend_moderation.base_moderation_exceptions.ModerationPiiError\u00b6\nclass langchain_experimental.comprehend_moderation.base_moderation_exceptions.ModerationPiiError(message: str = 'The prompt contains PII entities and cannot be processed')[source]\u00b6\nException raised if PII entities are detected.\nmessage -- explanation of the error", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_exceptions.ModerationPiiError.html"}
{"id": "cb6a5ed8564e-0", "text": "langchain_experimental.comprehend_moderation.toxicity.ComprehendToxicity\u00b6\nclass langchain_experimental.comprehend_moderation.toxicity.ComprehendToxicity(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None)[source]\u00b6\nMethods\n__init__(client[,\u00a0callback,\u00a0unique_id,\u00a0chain_id])\nvalidate(prompt_value[,\u00a0config])\nCheck the toxicity of a given text prompt using AWS Comprehend service and apply actions based on configuration.\n__init__(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None) \u2192 None[source]\u00b6\nvalidate(prompt_value: str, config: Any = None) \u2192 str[source]\u00b6\nCheck the toxicity of a given text prompt using AWS\nComprehend service and apply actions based on configuration.\n:param prompt_value: The text content to be checked for toxicity.\n:type prompt_value: str\n:param config: Configuration for toxicity checks and actions.\n:type config: Dict[str, Any]\nReturns\nThe original prompt_value if allowed or no toxicity found.\nReturn type\nstr\nRaises\nValueError \u2013 If the prompt contains toxic labels and cannot be\nprocessed based on the configuration. \u2013", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.toxicity.ComprehendToxicity.html"}
{"id": "c35135b28f61-0", "text": "langchain_experimental.comprehend_moderation.base_moderation_exceptions.ModerationPromptSafetyError\u00b6\nclass langchain_experimental.comprehend_moderation.base_moderation_exceptions.ModerationPromptSafetyError(message: str = 'The prompt is unsafe and cannot be processed')[source]\u00b6\nException raised if Intention entities are detected.\nmessage -- explanation of the error", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_exceptions.ModerationPromptSafetyError.html"}
{"id": "033f8b006061-0", "text": "langchain_experimental.comprehend_moderation.base_moderation_config.ModerationToxicityConfig\u00b6\nclass langchain_experimental.comprehend_moderation.base_moderation_config.ModerationToxicityConfig[source]\u00b6\nBases: BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam labels: List[str] = []\u00b6\nList of toxic labels, defaults to list[]\nparam threshold: float = 0.5\u00b6\nThreshold for Toxic label confidence score, defaults to 0.5 i.e. 50%\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_config.ModerationToxicityConfig.html"}
{"id": "033f8b006061-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_config.ModerationToxicityConfig.html"}
{"id": "033f8b006061-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_config.ModerationToxicityConfig.html"}
{"id": "2e0fed39c2d5-0", "text": "langchain_experimental.comprehend_moderation.base_moderation.BaseModeration\u00b6\nclass langchain_experimental.comprehend_moderation.base_moderation.BaseModeration(client: Any, config: Optional[Any] = None, moderation_callback: Optional[Any] = None, unique_id: Optional[str] = None, run_manager: Optional[CallbackManagerForChainRun] = None)[source]\u00b6\nMethods\n__init__(client[,\u00a0config,\u00a0...])\nmoderate(prompt)\n__init__(client: Any, config: Optional[Any] = None, moderation_callback: Optional[Any] = None, unique_id: Optional[str] = None, run_manager: Optional[CallbackManagerForChainRun] = None)[source]\u00b6\nmoderate(prompt: Any) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation.BaseModeration.html"}
{"id": "2ec8f6663184-0", "text": "langchain_experimental.comprehend_moderation.base_moderation_callbacks.BaseModerationCallbackHandler\u00b6\nclass langchain_experimental.comprehend_moderation.base_moderation_callbacks.BaseModerationCallbackHandler[source]\u00b6\nAttributes\npii_callback\nprompt_safety_callback\ntoxicity_callback\nMethods\n__init__()\non_after_pii(moderation_beacon,\u00a0unique_id,\u00a0...)\nRun after PII validation is complete.\non_after_prompt_safety(moderation_beacon,\u00a0...)\nRun after Prompt Safety validation is complete.\non_after_toxicity(moderation_beacon,\u00a0...)\nRun after Toxicity validation is complete.\n__init__() \u2192 None[source]\u00b6\nasync on_after_pii(moderation_beacon: Dict[str, Any], unique_id: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun after PII validation is complete.\nasync on_after_prompt_safety(moderation_beacon: Dict[str, Any], unique_id: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun after Prompt Safety validation is complete.\nasync on_after_toxicity(moderation_beacon: Dict[str, Any], unique_id: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun after Toxicity validation is complete.", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_callbacks.BaseModerationCallbackHandler.html"}
{"id": "dba22dade3f5-0", "text": "langchain_experimental.comprehend_moderation.base_moderation_exceptions.ModerationToxicityError\u00b6\nclass langchain_experimental.comprehend_moderation.base_moderation_exceptions.ModerationToxicityError(message: str = 'The prompt contains toxic content and cannot be processed')[source]\u00b6\nException raised if Toxic entities are detected.\nmessage -- explanation of the error", "source": "lang/api.python.langchain.com/en/latest/comprehend_moderation/langchain_experimental.comprehend_moderation.base_moderation_exceptions.ModerationToxicityError.html"}
{"id": "bb78cb1e1d74-0", "text": "langchain_experimental.smart_llm.base.SmartLLMChain\u00b6\nclass langchain_experimental.smart_llm.base.SmartLLMChain[source]\u00b6\nBases: Chain\nGeneralized implementation of SmartGPT (origin: https://youtu.be/wVzuvf9D9BU)\nA SmartLLMChain is an LLMChain that instead of simply passing the prompt to the LLM\nperforms these 3 steps:\n1. Ideate: Pass the user prompt to an ideation LLM n_ideas times,\neach result is an \u201cidea\u201d\nCritique: Pass the ideas to a critique LLM which looks for flaws in the ideas\n& picks the best one\nResolve: Pass the critique to a resolver LLM which improves upon the best idea\n& outputs only the (improved version of) the best output\nIn total, SmartLLMChain pass will use n_ideas+2 LLM calls\nNote that SmartLLMChain will only improve results (compared to a basic LLMChain),\nwhen the underlying models have the capability for reflection, which smaller models\noften don\u2019t.\nFinally, a SmartLLMChain assumes that each underlying LLM outputs exactly 1 result.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-1", "text": "Each custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam critique_llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nLLM to use in critique step. If None given, \u2018llm\u2019 will be used.\nparam history: langchain_experimental.smart_llm.base.SmartLLMChain.SmartLLMChainHistory = <langchain_experimental.smart_llm.base.SmartLLMChain.SmartLLMChainHistory object>\u00b6\nparam ideation_llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nLLM to use in ideation step. If None given, \u2018llm\u2019 will be used.\nparam llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nLLM to use for each steps, if no specific llm for that step is given.\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam n_ideas: int = 3\u00b6\nNumber of ideas to generate in idea step\nparam prompt: langchain.schema.prompt_template.BasePromptTemplate [Required]\u00b6\nPrompt object to use.", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-2", "text": "Prompt object to use.\nparam resolver_llm: Optional[langchain.schema.language_model.BaseLanguageModel] = None\u00b6\nLLM to use in resolve step. If None given, \u2018llm\u2019 will be used.\nparam return_intermediate_steps: bool = False\u00b6\nWhether to return ideas and critique, in addition to resolution.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\nclass SmartLLMChainHistory[source]\u00b6\nBases: object\ncritique_prompt_inputs() \u2192 Dict[str, Any][source]\u00b6\nideation_prompt_inputs() \u2192 Dict[str, Any][source]\u00b6\nresolve_prompt_inputs() \u2192 Dict[str, Any][source]\u00b6\ncritique: str = ''\u00b6\nideas: List[str] = []\u00b6\nproperty n_ideas: int\u00b6\nquestion: str = ''\u00b6\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-3", "text": "only one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-4", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-5", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-6", "text": "# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-7", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-8", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncritique_prompt() \u2192 ChatPromptTemplate[source]\u00b6\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-9", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_prompt_strings(stage: str) \u2192 List[Tuple[Type[BaseMessagePromptTemplate], str]][source]\u00b6\nideation_prompt() \u2192 ChatPromptTemplate[source]\u00b6\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-11", "text": "Parameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nprep_prompts(inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None) \u2192 Tuple[PromptValue, Optional[List[str]]][source]\u00b6\nPrepare prompts from inputs.\nresolve_prompt() \u2192 ChatPromptTemplate[source]\u00b6\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-12", "text": "addition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-13", "text": "Subclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-14", "text": "on_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nDefines the input keys.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "bb78cb1e1d74-15", "text": "property lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_keys: List[str]\u00b6\nDefines the output keys.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/smart_llm/langchain_experimental.smart_llm.base.SmartLLMChain.html"}
{"id": "8d5b453c2c64-0", "text": "langchain.storage.encoder_backed.EncoderBackedStore\u00b6\nclass langchain.storage.encoder_backed.EncoderBackedStore(store: BaseStore[str, Any], key_encoder: Callable[[K], str], value_serializer: Callable[[V], bytes], value_deserializer: Callable[[Any], V])[source]\u00b6\nWraps a store with key and value encoders/decoders.\nExamples that uses JSON for encoding/decoding:\nimport json\ndef key_encoder(key: int) -> str:\n    return json.dumps(key)\ndef value_serializer(value: float) -> str:\n    return json.dumps(value)\ndef value_deserializer(serialized_value: str) -> float:\n    return json.loads(serialized_value)\n# Create an instance of the abstract store\nabstract_store = MyCustomStore()\n# Create an instance of the encoder-backed store\nstore = EncoderBackedStore(\n    store=abstract_store,\n    key_encoder=key_encoder,\n    value_serializer=value_serializer,\n    value_deserializer=value_deserializer\n)\n# Use the encoder-backed store methods\nstore.mset([(1, 3.14), (2, 2.718)])\nvalues = store.mget([1, 2])  # Retrieves [3.14, 2.718]\nstore.mdelete([1, 2])  # Deletes the keys 1 and 2\nInitialize an EncodedStore.\nMethods\n__init__(store,\u00a0key_encoder,\u00a0...)\nInitialize an EncodedStore.\nmdelete(keys)\nDelete the given keys and their associated values.\nmget(keys)\nGet the values associated with the given keys.\nmset(key_value_pairs)\nSet the values for the given keys.\nyield_keys(*[,\u00a0prefix])\nGet an iterator over keys that match the given prefix.", "source": "lang/api.python.langchain.com/en/latest/storage/langchain.storage.encoder_backed.EncoderBackedStore.html"}
{"id": "8d5b453c2c64-1", "text": "yield_keys(*[,\u00a0prefix])\nGet an iterator over keys that match the given prefix.\n__init__(store: BaseStore[str, Any], key_encoder: Callable[[K], str], value_serializer: Callable[[V], bytes], value_deserializer: Callable[[Any], V]) \u2192 None[source]\u00b6\nInitialize an EncodedStore.\nmdelete(keys: Sequence[K]) \u2192 None[source]\u00b6\nDelete the given keys and their associated values.\nmget(keys: Sequence[K]) \u2192 List[Optional[V]][source]\u00b6\nGet the values associated with the given keys.\nmset(key_value_pairs: Sequence[Tuple[K, V]]) \u2192 None[source]\u00b6\nSet the values for the given keys.\nyield_keys(*, prefix: Optional[str] = None) \u2192 Union[Iterator[K], Iterator[str]][source]\u00b6\nGet an iterator over keys that match the given prefix.", "source": "lang/api.python.langchain.com/en/latest/storage/langchain.storage.encoder_backed.EncoderBackedStore.html"}
{"id": "b95956eebac7-0", "text": "langchain.storage.exceptions.InvalidKeyException\u00b6\nclass langchain.storage.exceptions.InvalidKeyException[source]\u00b6\nRaised when a key is invalid; e.g., uses incorrect characters.", "source": "lang/api.python.langchain.com/en/latest/storage/langchain.storage.exceptions.InvalidKeyException.html"}
{"id": "cdac9d96bbde-0", "text": "langchain.storage.upstash_redis.UpstashRedisStore\u00b6\nclass langchain.storage.upstash_redis.UpstashRedisStore(*, client: Any = None, url: Optional[str] = None, token: Optional[str] = None, ttl: Optional[int] = None, namespace: Optional[str] = None)[source]\u00b6\nBaseStore implementation using Upstash Redis as the underlying store.\nInitialize the UpstashRedisStore with HTTP API.\nMust provide either an Upstash Redis client or a url.\nParameters\nclient \u2013 An Upstash Redis instance\nurl \u2013 UPSTASH_REDIS_REST_URL\ntoken \u2013 UPSTASH_REDIS_REST_TOKEN\nttl \u2013 time to expire keys in seconds if provided,\nif None keys will never expire\nnamespace \u2013 if provided, all keys will be prefixed with this namespace\nMethods\n__init__(*[,\u00a0client,\u00a0url,\u00a0token,\u00a0ttl,\u00a0namespace])\nInitialize the UpstashRedisStore with HTTP API.\nmdelete(keys)\nDelete the given keys.\nmget(keys)\nGet the values associated with the given keys.\nmset(key_value_pairs)\nSet the given key-value pairs.\nyield_keys(*[,\u00a0prefix])\nYield keys in the store.\n__init__(*, client: Any = None, url: Optional[str] = None, token: Optional[str] = None, ttl: Optional[int] = None, namespace: Optional[str] = None) \u2192 None[source]\u00b6\nInitialize the UpstashRedisStore with HTTP API.\nMust provide either an Upstash Redis client or a url.\nParameters\nclient \u2013 An Upstash Redis instance\nurl \u2013 UPSTASH_REDIS_REST_URL\ntoken \u2013 UPSTASH_REDIS_REST_TOKEN\nttl \u2013 time to expire keys in seconds if provided,\nif None keys will never expire\nnamespace \u2013 if provided, all keys will be prefixed with this namespace", "source": "lang/api.python.langchain.com/en/latest/storage/langchain.storage.upstash_redis.UpstashRedisStore.html"}
{"id": "cdac9d96bbde-1", "text": "namespace \u2013 if provided, all keys will be prefixed with this namespace\nmdelete(keys: Sequence[str]) \u2192 None[source]\u00b6\nDelete the given keys.\nmget(keys: Sequence[str]) \u2192 List[Optional[str]][source]\u00b6\nGet the values associated with the given keys.\nmset(key_value_pairs: Sequence[Tuple[str, str]]) \u2192 None[source]\u00b6\nSet the given key-value pairs.\nyield_keys(*, prefix: Optional[str] = None) \u2192 Iterator[str][source]\u00b6\nYield keys in the store.", "source": "lang/api.python.langchain.com/en/latest/storage/langchain.storage.upstash_redis.UpstashRedisStore.html"}
{"id": "8e24a93086ed-0", "text": "langchain.storage.in_memory.InMemoryStore\u00b6\nclass langchain.storage.in_memory.InMemoryStore[source]\u00b6\nIn-memory implementation of the BaseStore using a dictionary.\nstore\u00b6\nThe underlying dictionary that stores\nthe key-value pairs.\nType\nDict[str, Any]\nExamples\nfrom langchain.storage import InMemoryStore\nstore = InMemoryStore()\nstore.mset([('key1', 'value1'), ('key2', 'value2')])\nstore.mget(['key1', 'key2'])\n# ['value1', 'value2']\nstore.mdelete(['key1'])\nlist(store.yield_keys())\n# ['key2']\nlist(store.yield_keys(prefix='k'))\n# ['key2']\nInitialize an empty store.\nMethods\n__init__()\nInitialize an empty store.\nmdelete(keys)\nDelete the given keys and their associated values.\nmget(keys)\nGet the values associated with the given keys.\nmset(key_value_pairs)\nSet the values for the given keys.\nyield_keys([prefix])\nGet an iterator over keys that match the given prefix.\n__init__() \u2192 None[source]\u00b6\nInitialize an empty store.\nmdelete(keys: Sequence[str]) \u2192 None[source]\u00b6\nDelete the given keys and their associated values.\nParameters\nkeys (Sequence[str]) \u2013 A sequence of keys to delete.\nmget(keys: Sequence[str]) \u2192 List[Optional[Any]][source]\u00b6\nGet the values associated with the given keys.\nParameters\nkeys (Sequence[str]) \u2013 A sequence of keys.\nReturns\nA sequence of optional values associated with the keys.\nIf a key is not found, the corresponding value will be None.\nmset(key_value_pairs: Sequence[Tuple[str, Any]]) \u2192 None[source]\u00b6\nSet the values for the given keys.\nParameters", "source": "lang/api.python.langchain.com/en/latest/storage/langchain.storage.in_memory.InMemoryStore.html"}
{"id": "8e24a93086ed-1", "text": "Set the values for the given keys.\nParameters\nkey_value_pairs (Sequence[Tuple[str, V]]) \u2013 A sequence of key-value pairs.\nReturns\nNone\nyield_keys(prefix: Optional[str] = None) \u2192 Iterator[str][source]\u00b6\nGet an iterator over keys that match the given prefix.\nParameters\nprefix (str, optional) \u2013 The prefix to match. Defaults to None.\nReturns\nAn iterator over keys that match the given prefix.\nReturn type\nIterator[str]\nExamples using InMemoryStore\u00b6\nCaching\nMultiVector Retriever\nParent Document Retriever", "source": "lang/api.python.langchain.com/en/latest/storage/langchain.storage.in_memory.InMemoryStore.html"}
{"id": "e1f0f80ccab6-0", "text": "langchain.storage.file_system.LocalFileStore\u00b6\nclass langchain.storage.file_system.LocalFileStore(root_path: Union[str, Path])[source]\u00b6\nBaseStore interface that works on the local file system.\nExamples\nCreate a LocalFileStore instance and perform operations on it:\nfrom langchain.storage import LocalFileStore\n# Instantiate the LocalFileStore with the root path\nfile_store = LocalFileStore(\"/path/to/root\")\n# Set values for keys\nfile_store.mset([(\"key1\", b\"value1\"), (\"key2\", b\"value2\")])\n# Get values for keys\nvalues = file_store.mget([\"key1\", \"key2\"])  # Returns [b\"value1\", b\"value2\"]\n# Delete keys\nfile_store.mdelete([\"key1\"])\n# Iterate over keys\nfor key in file_store.yield_keys():\n    print(key)\nImplement the BaseStore interface for the local file system.\nParameters\nroot_path (Union[str, Path]) \u2013 The root path of the file store. All keys are\ninterpreted as paths relative to this root.\nMethods\n__init__(root_path)\nImplement the BaseStore interface for the local file system.\nmdelete(keys)\nDelete the given keys and their associated values.\nmget(keys)\nGet the values associated with the given keys.\nmset(key_value_pairs)\nSet the values for the given keys.\nyield_keys([prefix])\nGet an iterator over keys that match the given prefix.\n__init__(root_path: Union[str, Path]) \u2192 None[source]\u00b6\nImplement the BaseStore interface for the local file system.\nParameters\nroot_path (Union[str, Path]) \u2013 The root path of the file store. All keys are\ninterpreted as paths relative to this root.\nmdelete(keys: Sequence[str]) \u2192 None[source]\u00b6\nDelete the given keys and their associated values.\nParameters", "source": "lang/api.python.langchain.com/en/latest/storage/langchain.storage.file_system.LocalFileStore.html"}
{"id": "e1f0f80ccab6-1", "text": "Delete the given keys and their associated values.\nParameters\nkeys (Sequence[str]) \u2013 A sequence of keys to delete.\nReturns\nNone\nmget(keys: Sequence[str]) \u2192 List[Optional[bytes]][source]\u00b6\nGet the values associated with the given keys.\nParameters\nkeys \u2013 A sequence of keys.\nReturns\nA sequence of optional values associated with the keys.\nIf a key is not found, the corresponding value will be None.\nmset(key_value_pairs: Sequence[Tuple[str, bytes]]) \u2192 None[source]\u00b6\nSet the values for the given keys.\nParameters\nkey_value_pairs \u2013 A sequence of key-value pairs.\nReturns\nNone\nyield_keys(prefix: Optional[str] = None) \u2192 Iterator[str][source]\u00b6\nGet an iterator over keys that match the given prefix.\nParameters\nprefix (Optional[str]) \u2013 The prefix to match.\nReturns\nAn iterator over keys that match the given prefix.\nReturn type\nIterator[str]\nExamples using LocalFileStore\u00b6\nCaching", "source": "lang/api.python.langchain.com/en/latest/storage/langchain.storage.file_system.LocalFileStore.html"}
{"id": "8bb910f670a1-0", "text": "langchain.storage.redis.RedisStore\u00b6\nclass langchain.storage.redis.RedisStore(*, client: Any = None, redis_url: Optional[str] = None, client_kwargs: Optional[dict] = None, ttl: Optional[int] = None, namespace: Optional[str] = None)[source]\u00b6\nBaseStore implementation using Redis as the underlying store.\nExamples\nCreate a RedisStore instance and perform operations on it:\n# Instantiate the RedisStore with a Redis connection\nfrom langchain.storage import RedisStore\nfrom langchain.utilities.redis import get_client\nclient = get_client('redis://localhost:6379')\nredis_store = RedisStore(client)\n# Set values for keys\nredis_store.mset([(\"key1\", b\"value1\"), (\"key2\", b\"value2\")])\n# Get values for keys\nvalues = redis_store.mget([\"key1\", \"key2\"])\n# [b\"value1\", b\"value2\"]\n# Delete keys\nredis_store.mdelete([\"key1\"])\n# Iterate over keys\nfor key in redis_store.yield_keys():\n    print(key)\nInitialize the RedisStore with a Redis connection.\nMust provide either a Redis client or a redis_url with optional client_kwargs.\nParameters\nclient \u2013 A Redis connection instance\nredis_url \u2013 redis url\nclient_kwargs \u2013 Keyword arguments to pass to the Redis client\nttl \u2013 time to expire keys in seconds if provided,\nif None keys will never expire\nnamespace \u2013 if provided, all keys will be prefixed with this namespace\nMethods\n__init__(*[,\u00a0client,\u00a0redis_url,\u00a0...])\nInitialize the RedisStore with a Redis connection.\nmdelete(keys)\nDelete the given keys.\nmget(keys)\nGet the values associated with the given keys.\nmset(key_value_pairs)\nSet the given key-value pairs.\nyield_keys(*[,\u00a0prefix])\nYield keys in the store.", "source": "lang/api.python.langchain.com/en/latest/storage/langchain.storage.redis.RedisStore.html"}
{"id": "8bb910f670a1-1", "text": "yield_keys(*[,\u00a0prefix])\nYield keys in the store.\n__init__(*, client: Any = None, redis_url: Optional[str] = None, client_kwargs: Optional[dict] = None, ttl: Optional[int] = None, namespace: Optional[str] = None) \u2192 None[source]\u00b6\nInitialize the RedisStore with a Redis connection.\nMust provide either a Redis client or a redis_url with optional client_kwargs.\nParameters\nclient \u2013 A Redis connection instance\nredis_url \u2013 redis url\nclient_kwargs \u2013 Keyword arguments to pass to the Redis client\nttl \u2013 time to expire keys in seconds if provided,\nif None keys will never expire\nnamespace \u2013 if provided, all keys will be prefixed with this namespace\nmdelete(keys: Sequence[str]) \u2192 None[source]\u00b6\nDelete the given keys.\nmget(keys: Sequence[str]) \u2192 List[Optional[bytes]][source]\u00b6\nGet the values associated with the given keys.\nmset(key_value_pairs: Sequence[Tuple[str, bytes]]) \u2192 None[source]\u00b6\nSet the given key-value pairs.\nyield_keys(*, prefix: Optional[str] = None) \u2192 Iterator[str][source]\u00b6\nYield keys in the store.\nExamples using RedisStore\u00b6\nCaching", "source": "lang/api.python.langchain.com/en/latest/storage/langchain.storage.redis.RedisStore.html"}
{"id": "fecdc9b60418-0", "text": "langchain.agents.format_scratchpad.log.format_log_to_str\u00b6\nlangchain.agents.format_scratchpad.log.format_log_to_str(intermediate_steps: List[Tuple[AgentAction, str]], observation_prefix: str = 'Observation: ', llm_prefix: str = 'Thought: ') \u2192 str[source]\u00b6\nConstruct the scratchpad that lets the agent continue its thought process.", "source": "lang/api.python.langchain.com/en/latest/agents.format_scratchpad/langchain.agents.format_scratchpad.log.format_log_to_str.html"}
{"id": "0af5685a05d2-0", "text": "langchain.agents.format_scratchpad.log_to_messages.format_log_to_messages\u00b6\nlangchain.agents.format_scratchpad.log_to_messages.format_log_to_messages(intermediate_steps: List[Tuple[AgentAction, str]], template_tool_response: str = '{observation}') \u2192 List[BaseMessage][source]\u00b6\nConstruct the scratchpad that lets the agent continue its thought process.", "source": "lang/api.python.langchain.com/en/latest/agents.format_scratchpad/langchain.agents.format_scratchpad.log_to_messages.format_log_to_messages.html"}
{"id": "73cb3a0be3c2-0", "text": "langchain.agents.format_scratchpad.openai_functions.format_to_openai_function_messages\u00b6\nlangchain.agents.format_scratchpad.openai_functions.format_to_openai_function_messages(intermediate_steps: Sequence[Tuple[AgentAction, str]]) \u2192 List[BaseMessage][source]\u00b6\nConvert (AgentAction, tool output) tuples into FunctionMessages.\nParameters\nintermediate_steps \u2013 Steps the LLM has taken to date, along with observations\nReturns\nlist of messages to send to the LLM for the next prediction", "source": "lang/api.python.langchain.com/en/latest/agents.format_scratchpad/langchain.agents.format_scratchpad.openai_functions.format_to_openai_function_messages.html"}
{"id": "a225ea3598e8-0", "text": "langchain.agents.format_scratchpad.xml.format_xml\u00b6\nlangchain.agents.format_scratchpad.xml.format_xml(intermediate_steps: List[Tuple[AgentAction, str]]) \u2192 str[source]\u00b6\nFormat the intermediate steps as XML.\nParameters\nintermediate_steps \u2013 The intermediate steps.\nReturns\nThe intermediate steps as XML.", "source": "lang/api.python.langchain.com/en/latest/agents.format_scratchpad/langchain.agents.format_scratchpad.xml.format_xml.html"}
{"id": "c38314461eee-0", "text": "langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint\u00b6\nclass langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint[source]\u00b6\nBases: BaseChatModel\nBaidu Qianfan chat models.\nTo use, you should have the qianfan python package installed, and\nthe environment variable qianfan_ak and qianfan_sk set with your\nAPI key and Secret Key.\nak, sk are required parameters\nwhich you could get from  https://cloud.baidu.com/product/wenxinworkshop\nExample\nfrom langchain.chat_models import QianfanChatEndpoint\nqianfan_chat = QianfanChatEndpoint(model=\"ERNIE-Bot\",\n    endpoint=\"your_endpoint\", qianfan_ak=\"your_ak\", qianfan_sk=\"your_sk\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam client: Any = None\u00b6\nparam endpoint: Optional[str] = None\u00b6\nEndpoint of the Qianfan LLM, required if custom model used.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str = 'ERNIE-Bot-turbo'\u00b6\nModel name.\nyou could get from https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu\npreset models are mapping to an endpoint.\nmodel will be ignored if endpoint is set.\nDefault is ERNIE-Bot-turbo.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "c38314461eee-1", "text": "Default is ERNIE-Bot-turbo.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nparam penalty_score: Optional[float] = 1\u00b6\nModel params, only supported in ERNIE-Bot and ERNIE-Bot-turbo.\nIn the case of other model, passing these params will not affect the result.\nparam qianfan_ak: Optional[str] = None\u00b6\nparam qianfan_sk: Optional[str] = None\u00b6\nparam request_timeout: Optional[int] = 60\u00b6\nrequest timeout for chat http requests\nparam streaming: Optional[bool] = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = 0.95\u00b6\nparam top_p: Optional[float] = 0.8\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "c38314461eee-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "c38314461eee-3", "text": "async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "c38314461eee-4", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "c38314461eee-5", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "c38314461eee-6", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "c38314461eee-7", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "c38314461eee-8", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "c38314461eee-9", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "c38314461eee-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "c38314461eee-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "c38314461eee-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "c38314461eee-13", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using QianfanChatEndpoint\u00b6\nBaidu Qianfan", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.QianfanChatEndpoint.html"}
{"id": "ba0a3c536927-0", "text": "langchain.chat_models.cohere.ChatCohere\u00b6\nclass langchain.chat_models.cohere.ChatCohere[source]\u00b6\nBases: BaseChatModel, BaseCohere\nCohere chat large language models.\nTo use, you should have the cohere python package installed, and the\nenvironment variable COHERE_API_KEY set with your API key, or pass\nit as a named parameter to the constructor.\nExample\nfrom langchain.chat_models import ChatCohere\nfrom langchain.schema import HumanMessage\nchat = ChatCohere(model=\"foo\")\nresult = chat([HumanMessage(content=\"Hello\")])\nprint(result.content)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam cohere_api_key: Optional[str] = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: Optional[str] = None\u00b6\nModel name to use.\nparam stop: Optional[List[str]] = None\u00b6\nparam streaming: bool = False\u00b6\nWhether to stream the results.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.75\u00b6\nA non-negative float that tunes the degree of randomness in generation.\nparam user_agent: str = 'langchain'\u00b6\nIdentifier for the application making the request.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.ChatCohere.html"}
{"id": "ba0a3c536927-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.ChatCohere.html"}
{"id": "ba0a3c536927-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.ChatCohere.html"}
{"id": "ba0a3c536927-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.ChatCohere.html"}
{"id": "ba0a3c536927-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.ChatCohere.html"}
{"id": "ba0a3c536927-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.ChatCohere.html"}
{"id": "ba0a3c536927-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.ChatCohere.html"}
{"id": "ba0a3c536927-7", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int[source]\u00b6\nCalculate number of tokens.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.ChatCohere.html"}
{"id": "ba0a3c536927-8", "text": "Parameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.ChatCohere.html"}
{"id": "ba0a3c536927-9", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.ChatCohere.html"}
{"id": "ba0a3c536927-10", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.ChatCohere.html"}
{"id": "ba0a3c536927-11", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.ChatCohere.html"}
{"id": "ba0a3c536927-12", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.ChatCohere.html"}
{"id": "32fbee5e9608-0", "text": "langchain.chat_models.fireworks.convert_dict_to_message\u00b6\nlangchain.chat_models.fireworks.convert_dict_to_message(_dict: Any) \u2192 BaseMessage[source]\u00b6\nConvert a dict response to a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.convert_dict_to_message.html"}
{"id": "f871d18d01c3-0", "text": "langchain.chat_models.tongyi.ChatTongyi\u00b6\nclass langchain.chat_models.tongyi.ChatTongyi[source]\u00b6\nBases: BaseChatModel\nAlibaba Tongyi Qwen chat models API.\nTo use, you should have the dashscope python package installed,\nand set env DASHSCOPE_API_KEY with your API key, or pass\nit as a named parameter to the constructor.\nExample\nfrom langchain.chat_models import Tongyi\nTongyi_chat = ChatTongyi()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam dashscope_api_key: Optional[str] = None\u00b6\nDashscope api key provide by alicloud.\nparam max_retries: int = 10\u00b6\nMaximum number of retries to make when generating.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nparam model_name: str = 'qwen-turbo' (alias 'model')\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam prefix_messages: List [Optional]\u00b6\nSeries of messages for Chat input.\nparam result_format: str = 'message'\u00b6\nReturn result format\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "f871d18d01c3-1", "text": "param tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam top_p: float = 0.8\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "f871d18d01c3-2", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "f871d18d01c3-3", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "f871d18d01c3-4", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\ncompletion_with_retry(run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "f871d18d01c3-5", "text": "The type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "f871d18d01c3-6", "text": "Returns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "f871d18d01c3-7", "text": "to the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "f871d18d01c3-8", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "f871d18d01c3-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "f871d18d01c3-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "f871d18d01c3-11", "text": "Subclasses should override this method if they support streaming output.\nstream_completion_with_retry(run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "f871d18d01c3-12", "text": "Bind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "f871d18d01c3-13", "text": "List of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty lc_serializable: bool\u00b6\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.ChatTongyi.html"}
{"id": "27e062735ae5-0", "text": "langchain.chat_models.anthropic.convert_messages_to_prompt_anthropic\u00b6\nlangchain.chat_models.anthropic.convert_messages_to_prompt_anthropic(messages: List[BaseMessage], *, human_prompt: str = '\\n\\nHuman:', ai_prompt: str = '\\n\\nAssistant:') \u2192 str[source]\u00b6\nFormat a list of messages into a full prompt for the Anthropic model\nArgs:messages (List[BaseMessage]): List of BaseMessage to combine.\nhuman_prompt (str, optional): Human prompt tag. Defaults to \u201c\nHuman:\u201d.ai_prompt (str, optional): AI prompt tag. Defaults to \u201c\nAssistant:\u201d.\nReturns:str: Combined string with necessary human_prompt and ai_prompt tags.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.convert_messages_to_prompt_anthropic.html"}
{"id": "2b629bb98d29-0", "text": "langchain.chat_models.fireworks.ChatFireworks\u00b6\nclass langchain.chat_models.fireworks.ChatFireworks[source]\u00b6\nBases: BaseChatModel\nFireworks Chat models.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam fireworks_api_key: Optional[pydantic.types.SecretStr] = None\u00b6\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nparam max_retries: int = 20\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str = 'accounts/fireworks/models/llama-v2-7b-chat'\u00b6\nparam model_kwargs: dict [Optional]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam use_retry: bool = True\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.ChatFireworks.html"}
{"id": "2b629bb98d29-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.ChatFireworks.html"}
{"id": "2b629bb98d29-2", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.ChatFireworks.html"}
{"id": "2b629bb98d29-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.ChatFireworks.html"}
{"id": "2b629bb98d29-4", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.ChatFireworks.html"}
{"id": "2b629bb98d29-5", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.ChatFireworks.html"}
{"id": "2b629bb98d29-6", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.ChatFireworks.html"}
{"id": "2b629bb98d29-7", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.ChatFireworks.html"}
{"id": "2b629bb98d29-8", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.ChatFireworks.html"}
{"id": "2b629bb98d29-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.ChatFireworks.html"}
{"id": "2b629bb98d29-10", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.ChatFireworks.html"}
{"id": "2b629bb98d29-11", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.ChatFireworks.html"}
{"id": "2b629bb98d29-12", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.ChatFireworks.html"}
{"id": "a6834ad372fe-0", "text": "langchain.chat_models.base.BaseChatModel\u00b6\nclass langchain.chat_models.base.BaseChatModel[source]\u00b6\nBases: BaseLanguageModel[BaseMessage], ABC\nBase class for Chat models.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[langchain.schema.callbacks.base.BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Optional[Union[List[langchain.schema.callbacks.base.BaseCallbackHandler], langchain.schema.callbacks.base.BaseCallbackManager]] = None\u00b6\nCallbacks to add to the run trace.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage[source]\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.BaseChatModel.html"}
{"id": "a6834ad372fe-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult[source]\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult[source]\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.BaseChatModel.html"}
{"id": "a6834ad372fe-2", "text": "async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage[source]\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.BaseChatModel.html"}
{"id": "a6834ad372fe-3", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.BaseChatModel.html"}
{"id": "a6834ad372fe-4", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.BaseChatModel.html"}
{"id": "a6834ad372fe-5", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict[source]\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult[source]\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult[source]\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.BaseChatModel.html"}
{"id": "a6834ad372fe-6", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.BaseChatModel.html"}
{"id": "a6834ad372fe-7", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.BaseChatModel.html"}
{"id": "a6834ad372fe-8", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.BaseChatModel.html"}
{"id": "a6834ad372fe-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage[source]\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.BaseChatModel.html"}
{"id": "a6834ad372fe-10", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.BaseChatModel.html"}
{"id": "a6834ad372fe-11", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.BaseChatModel.html"}
{"id": "a6834ad372fe-12", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.BaseChatModel.html"}
{"id": "655a72473bb7-0", "text": "langchain.chat_models.openai.ChatOpenAI\u00b6\nclass langchain.chat_models.openai.ChatOpenAI[source]\u00b6\nBases: BaseChatModel\nOpenAI Chat large language models API.\nTo use, you should have the openai python package installed, and the\nenvironment variable OPENAI_API_KEY set with your API key.\nAny parameters that are valid to be passed to the openai.create call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.chat_models import ChatOpenAI\nopenai = ChatOpenAI(model_name=\"gpt-3.5-turbo\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam default_headers: Union[Mapping[str, str], None] = None\u00b6\nparam default_query: Union[Mapping[str, object], None] = None\u00b6\nparam http_client: Union[Any, None] = None\u00b6\nOptional httpx.Client.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: Optional[int] = None\u00b6\nMaximum number of tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'gpt-3.5-turbo' (alias 'model')\u00b6\nModel name to use.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-1", "text": "Model name to use.\nparam n: int = 1\u00b6\nNumber of chat completions to generate for each prompt.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Optional[str] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var OPENAI_API_KEY if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-2", "text": "API but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-3", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-4", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-5", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nbind_functions(functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]], function_call: Optional[str] = None, **kwargs: Any) \u2192 Runnable[Union[PromptValue, str, List[BaseMessage]], BaseMessage][source]\u00b6\nBind functions (and other objects) to this chat model.\nParameters\nfunctions \u2013 A list of function definitions to bind to this chat model.\nCan be  a dictionary, pydantic model, or callable. Pydantic", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-6", "text": "Can be  a dictionary, pydantic model, or callable. Pydantic\nmodels and callables will be automatically converted to\ntheir schema dictionary representation.\nfunction_call \u2013 Which function to require the model to call.\nMust be the name of the single provided function or\n\u201cauto\u201d to automatically determine which function to call\n(if any).\nkwargs \u2013 Any additional parameters to pass to the\nRunnable constructor.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\ncompletion_with_retry(run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-7", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-8", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-9", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int[source]\u00b6\nCalculate num tokens for gpt-3.5-turbo and gpt-4 with tiktoken package.\nOfficial documentation: https://github.com/openai/openai-cookbook/blob/\nmain/examples/How_to_format_inputs_to_ChatGPT_models.ipynb\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int][source]\u00b6\nGet the tokens present in the text with tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-10", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this model can be serialized by Langchain.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-11", "text": "predict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-12", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-13", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-14", "text": "List of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ChatOpenAI\u00b6\nFacebook Messenger\nSlack\nWhatsApp\niMessage\nTelegram\nDiscord\nRePhraseQueryRetriever\nWikipedia\nArxiv\nChatGPT Plugins\nHuman as a tool\nYahoo Finance News\nArXiv\nMetaphor Search\nShell (bash)\nXata chat memory\nDynamodb Chat Message History\nOpenAI\nLLMonitor\nContext\nLabel Studio\nPromptLayer\nCnosDB\nLog10\nFlyte\nArthur\nCSV\nDocument Comparison\nPython\nPowerBI Dataset\nSQL Database\nAirbyte Question Answering\nGithub\nSpark SQL\nAINetwork\nPandas Dataframe\nNeo4j Vector Index\nOpenAI Functions Metadata Tagger\nLoading documents from a YouTube url\nFigma\nFallbacks\nDebugging\nLangSmith Walkthrough\nReversible data anonymization with Microsoft Presidio\nData anonymization with Microsoft Presidio\nComparing Chain Outputs\nAgent Trajectory\nCustom Trajectory Evaluator\nSet env var OPENAI_API_KEY or load from a .env file:\nSet env var OPENAI_API_KEY or load from a .env file\nQuestion Answering\nPerform context-aware text splitting\nConversational Retrieval Agent\nMultiple Retrieval Sources\nCite sources\nRetrieve as you generate with FLARE\nAnalysis of Twitter the-algorithm source code with LangChain, GPT4 and Activeloop\u2019s Deep Lake", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "655a72473bb7-15", "text": "Use LangChain, GPT and Activeloop\u2019s Deep Lake to work with code base\nStructure answers with OpenAI functions\nQA using Activeloop\u2019s DeepLake\nNeptune Open Cypher QA Chain\nNebulaGraphQAChain\nMemgraph QA chain\nKuzuQAChain\nHugeGraph QA Chain\nGraphSparqlQAChain\nDiffbot Graph Transformer\nArangoDB QA chain\nNeo4j DB QA chain\nFalkorDBQAChain\nAgents\nAutoGPT\n!pip install bs4\nWikibase Agent\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nCAMEL Role-Playing Autonomous Cooperative Agents\nMulti-Agent Simulated Environment: Petting Zoo\nMulti-agent decentralized speaker selection\nMulti-agent authoritarian speaker selection\nGenerative Agents in LangChain\nTwo-Player Dungeons & Dragons\nMulti-Player Dungeons & Dragons\nSimulated Environment: Gymnasium\nAgent Debates with Tools\nHow to use a SmartLLMChain\nVector SQL Retriever with MyScale\nElasticsearch\nSQL\nMultiVector Retriever\nMultiQueryRetriever\nWebResearchRetriever\nMemory in LLMChain\nCustom callback handlers\nAsync callbacks\nDefining Custom Tools\nTools as OpenAI Functions\nOpenAI Multi Functions Agent\nHandle parsing errors\nRunning Agent as an Iterator\nAdd Memory to OpenAI Functions Agent\nCustom functions with OpenAI Functions Agent\nUse ToolKits with OpenAI Functions\nRetry parser\nPydantic (JSON) parser\nPrompt pipelining\nConnecting to a Feature Store\nCustom chain\nUsing OpenAI functions\ninterface.md\nFirst we add a step to load memory\nsql_db.md\nprompt_llm_parser.md\nAdding memory\nmultiple_chains.md\nCode writing\nUsing tools\nConfigure Runnable traces", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html"}
{"id": "7e6a7dcc4d8f-0", "text": "langchain_experimental.chat_models.llm_wrapper.Llama2Chat\u00b6\nclass langchain_experimental.chat_models.llm_wrapper.Llama2Chat[source]\u00b6\nBases: ChatWrapper\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_n_beg: str = ' '\u00b6\nparam ai_n_end: str = ' </s>'\u00b6\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam llm: LLM [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam sys_beg: str = '<s>[INST] <<SYS>>\\n'\u00b6\nparam sys_end: str = '\\n<</SYS>>\\n\\n'\u00b6\nparam system_message: SystemMessage = SystemMessage(content=\"You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\\n\\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\")\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam usr_0_beg: str = ''\u00b6\nparam usr_0_end: str = ' [/INST]'\u00b6\nparam usr_n_beg: str = '<s>[INST] '\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Llama2Chat.html"}
{"id": "7e6a7dcc4d8f-1", "text": "param usr_n_beg: str = '<s>[INST] '\u00b6\nparam usr_n_end: str = ' [/INST]'\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Llama2Chat.html"}
{"id": "7e6a7dcc4d8f-2", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Llama2Chat.html"}
{"id": "7e6a7dcc4d8f-3", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Llama2Chat.html"}
{"id": "7e6a7dcc4d8f-4", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Llama2Chat.html"}
{"id": "7e6a7dcc4d8f-5", "text": "Parameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Llama2Chat.html"}
{"id": "7e6a7dcc4d8f-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Llama2Chat.html"}
{"id": "7e6a7dcc4d8f-7", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Llama2Chat.html"}
{"id": "7e6a7dcc4d8f-8", "text": "Returns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Llama2Chat.html"}
{"id": "7e6a7dcc4d8f-9", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Llama2Chat.html"}
{"id": "7e6a7dcc4d8f-10", "text": "Parameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Llama2Chat.html"}
{"id": "7e6a7dcc4d8f-11", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Llama2Chat.html"}
{"id": "7e6a7dcc4d8f-12", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Llama2Chat.html"}
{"id": "71e49b13b22b-0", "text": "langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint\u00b6\nclass langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint[source]\u00b6\nBases: SimpleChatModel\nAzureML Chat models API.\nExample\nazure_chat = AzureMLChatOnlineEndpoint(\n    endpoint_url=\"https://<your-endpoint>.<your_region>.inference.ml.azure.com/score\",\n    endpoint_api_key=\"my-api-key\",\n    content_formatter=content_formatter,\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam content_formatter: Any = None\u00b6\nThe content formatter that provides an input and output\ntransform function to handle formats between the LLM and\nthe endpoint\nparam endpoint_api_key: pydantic.types.SecretStr = SecretStr('')\u00b6\nAuthentication Key for Endpoint. Should be passed to constructor or specified as\nenv var AZUREML_ENDPOINT_API_KEY.\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nparam endpoint_url: str = ''\u00b6\nURL of pre-existing Endpoint. Should be passed to constructor or specified as\nenv var AZUREML_ENDPOINT_URL.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint.html"}
{"id": "71e49b13b22b-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint.html"}
{"id": "71e49b13b22b-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint.html"}
{"id": "71e49b13b22b-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint.html"}
{"id": "71e49b13b22b-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint.html"}
{"id": "71e49b13b22b-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint.html"}
{"id": "71e49b13b22b-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint.html"}
{"id": "71e49b13b22b-7", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint.html"}
{"id": "71e49b13b22b-8", "text": "Returns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint.html"}
{"id": "71e49b13b22b-9", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint.html"}
{"id": "71e49b13b22b-10", "text": "Parameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint.html"}
{"id": "71e49b13b22b-11", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint.html"}
{"id": "71e49b13b22b-12", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using AzureMLChatOnlineEndpoint\u00b6\nAzureML Chat Online Endpoint", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.AzureMLChatOnlineEndpoint.html"}
{"id": "129f66a90403-0", "text": "langchain.chat_models.google_palm.achat_with_retry\u00b6\nasync langchain.chat_models.google_palm.achat_with_retry(llm: ChatGooglePalm, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the async completion call.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.achat_with_retry.html"}
{"id": "ce756d12e413-0", "text": "langchain_experimental.chat_models.llm_wrapper.Vicuna\u00b6\nclass langchain_experimental.chat_models.llm_wrapper.Vicuna[source]\u00b6\nBases: ChatWrapper\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_n_beg: str = 'ASSISTANT: '\u00b6\nparam ai_n_end: str = ' </s>'\u00b6\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam llm: LLM [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam sys_beg: str = ''\u00b6\nparam sys_end: str = ' '\u00b6\nparam system_message: SystemMessage = SystemMessage(content=\"You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\\n\\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\")\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam usr_0_beg: Optional[str] = None\u00b6\nparam usr_0_end: Optional[str] = None\u00b6\nparam usr_n_beg: str = 'USER: '\u00b6\nparam usr_n_end: str = ' '\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Vicuna.html"}
{"id": "ce756d12e413-1", "text": "param usr_n_end: str = ' '\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Vicuna.html"}
{"id": "ce756d12e413-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Vicuna.html"}
{"id": "ce756d12e413-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Vicuna.html"}
{"id": "ce756d12e413-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Vicuna.html"}
{"id": "ce756d12e413-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Vicuna.html"}
{"id": "ce756d12e413-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Vicuna.html"}
{"id": "ce756d12e413-7", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Vicuna.html"}
{"id": "ce756d12e413-8", "text": "Returns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Vicuna.html"}
{"id": "ce756d12e413-9", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Vicuna.html"}
{"id": "ce756d12e413-10", "text": "Parameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Vicuna.html"}
{"id": "ce756d12e413-11", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Vicuna.html"}
{"id": "ce756d12e413-12", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Vicuna.html"}
{"id": "1eb2c7a6e5e1-0", "text": "langchain.chat_models.baichuan.ChatBaichuan\u00b6\nclass langchain.chat_models.baichuan.ChatBaichuan[source]\u00b6\nBases: BaseChatModel\nBaichuan chat models API by Baichuan Intelligent Technology.\nFor more information, see https://platform.baichuan-ai.com/docs/api\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam baichuan_api_base: str = 'https://api.baichuan-ai.com/v1'\u00b6\nBaichuan custom endpoints\nparam baichuan_api_key: Optional[str] = None\u00b6\nBaichuan API Key\nparam baichuan_secret_key: Optional[pydantic.types.SecretStr] = None\u00b6\nBaichuan Secret Key\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model = 'Baichuan2-53B'\u00b6\nmodel name of Baichuan, default is Baichuan2-53B.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for API call not explicitly specified.\nparam request_timeout: int = 60\u00b6\nrequest timeout for chat http requests\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.3\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "1eb2c7a6e5e1-1", "text": "Tags to add to the run trace.\nparam temperature: float = 0.3\u00b6\nWhat sampling temperature to use.\nparam top_k: int = 5\u00b6\nWhat search sampling control to use.\nparam top_p: float = 0.85\u00b6\nWhat probability mass to use.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\nparam with_search_enhance: bool = False\u00b6\nWhether to use search enhance, default is False.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "1eb2c7a6e5e1-2", "text": "Asynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "1eb2c7a6e5e1-3", "text": "Parameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "1eb2c7a6e5e1-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "1eb2c7a6e5e1-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "1eb2c7a6e5e1-6", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "1eb2c7a6e5e1-7", "text": "text generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "1eb2c7a6e5e1-8", "text": "Useful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "1eb2c7a6e5e1-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "1eb2c7a6e5e1-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "1eb2c7a6e5e1-11", "text": "Subclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "1eb2c7a6e5e1-12", "text": "on_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "1eb2c7a6e5e1-13", "text": "property lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty lc_serializable: bool\u00b6\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baichuan.ChatBaichuan.html"}
{"id": "a8f5bc0fb7a9-0", "text": "langchain.chat_models.cohere.get_cohere_chat_request\u00b6\nlangchain.chat_models.cohere.get_cohere_chat_request(messages: List[BaseMessage], *, connectors: Optional[List[Dict[str, str]]] = None, **kwargs: Any) \u2192 Dict[str, Any][source]\u00b6\nGet the request for the Cohere chat API.\nParameters\nmessages \u2013 The messages.\nconnectors \u2013 The connectors.\n**kwargs \u2013 The keyword arguments.\nReturns\nThe request for the Cohere chat API.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.get_cohere_chat_request.html"}
{"id": "48dcc23c781c-0", "text": "langchain.chat_models.ollama.ChatOllama\u00b6\nclass langchain.chat_models.ollama.ChatOllama[source]\u00b6\nBases: BaseChatModel, _OllamaCommon\nOllama locally runs large language models.\nTo use, follow the instructions at https://ollama.ai/.\nExample\nfrom langchain.chat_models import ChatOllama\nollama = ChatOllama(model=\"llama2\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam base_url: str = 'http://localhost:11434'\u00b6\nBase url the model is hosted under.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam mirostat: Optional[int] = None\u00b6\nEnable Mirostat sampling for controlling perplexity.\n(default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\nparam mirostat_eta: Optional[float] = None\u00b6\nInfluences how quickly the algorithm responds to feedback\nfrom the generated text. A lower learning rate will result in\nslower adjustments, while a higher learning rate will make\nthe algorithm more responsive. (Default: 0.1)\nparam mirostat_tau: Optional[float] = None\u00b6\nControls the balance between coherence and diversity\nof the output. A lower value will result in more focused and\ncoherent text. (Default: 5.0)", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-1", "text": "coherent text. (Default: 5.0)\nparam model: str = 'llama2'\u00b6\nModel name to use.\nparam num_ctx: Optional[int] = None\u00b6\nSets the size of the context window used to generate the\nnext token. (Default: 2048)\nparam num_gpu: Optional[int] = None\u00b6\nThe number of GPUs to use. On macOS it defaults to 1 to\nenable metal support, 0 to disable.\nparam num_thread: Optional[int] = None\u00b6\nSets the number of threads to use during computation.\nBy default, Ollama will detect this for optimal performance.\nIt is recommended to set this value to the number of physical\nCPU cores your system has (as opposed to the logical number of cores).\nparam repeat_last_n: Optional[int] = None\u00b6\nSets how far back for the model to look back to prevent\nrepetition. (Default: 64, 0 = disabled, -1 = num_ctx)\nparam repeat_penalty: Optional[float] = None\u00b6\nSets how strongly to penalize repetitions. A higher value (e.g., 1.5)\nwill penalize repetitions more strongly, while a lower value (e.g., 0.9)\nwill be more lenient. (Default: 1.1)\nparam stop: Optional[List[str]] = None\u00b6\nSets the stop tokens to use.\nparam system: Optional[str] = None\u00b6\nsystem prompt (overrides what is defined in the Modelfile)\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = None\u00b6\nThe temperature of the model. Increasing the temperature will\nmake the model answer more creatively. (Default: 0.8)\nparam template: Optional[str] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-2", "text": "param template: Optional[str] = None\u00b6\nfull prompt or prompt template (overrides what is defined in the Modelfile)\nparam tfs_z: Optional[float] = None\u00b6\nTail free sampling is used to reduce the impact of less probable\ntokens from the output. A higher value (e.g., 2.0) will reduce the\nimpact more, while a value of 1.0 disables this setting. (default: 1)\nparam top_k: Optional[int] = None\u00b6\nReduces the probability of generating nonsense. A higher value (e.g. 100)\nwill give more diverse answers, while a lower value (e.g. 10)\nwill be more conservative. (Default: 40)\nparam top_p: Optional[int] = None\u00b6\nWorks together with top-k. A higher value (e.g., 0.95) will lead\nto more diverse text, while a lower value (e.g., 0.5) will\ngenerate more focused and conservative text. (Default: 0.9)\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-3", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-4", "text": "to the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-5", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-6", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-7", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-8", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-9", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-10", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this model can be serialized by Langchain.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-11", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-12", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-13", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "48dcc23c781c-14", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ChatOllama\u00b6\nOllama", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ollama.ChatOllama.html"}
{"id": "f5e302ad1bf1-0", "text": "langchain.chat_models.everlyai.ChatEverlyAI\u00b6\nclass langchain.chat_models.everlyai.ChatEverlyAI[source]\u00b6\nBases: ChatOpenAI\nEverlyAI Chat large language models.\nTo use, you should have the openai python package installed, and the\nenvironment variable EVERLYAI_API_KEY set with your API key.\nAlternatively, you can use the everlyai_api_key keyword argument.\nAny parameters that are valid to be passed to the openai.create call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.chat_models import ChatEverlyAI\nchat = ChatEverlyAI(model_name=\"meta-llama/Llama-2-7b-chat-hf\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam available_models: Optional[Set[str]] = None\u00b6\nAvailable models from EverlyAI API.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam default_headers: Union[Mapping[str, str], None] = None\u00b6\nparam default_query: Union[Mapping[str, object], None] = None\u00b6\nparam everlyai_api_base: str = 'https://everlyai.xyz/hosted'\u00b6\nBase URL path for API requests.\nparam everlyai_api_key: Optional[str] = None\u00b6\nEverlyAI Endpoints API keys.\nparam http_client: Union[Any, None] = None\u00b6\nOptional httpx.Client.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-1", "text": "Maximum number of retries to make when generating.\nparam max_tokens: Optional[int] = None\u00b6\nMaximum number of tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'meta-llama/Llama-2-7b-chat-hf' (alias 'model')\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nNumber of chat completions to generate for each prompt.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Optional[str] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var OPENAI_API_KEY if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-2", "text": "Tiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-3", "text": "Top Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-4", "text": "Subclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nbind_functions(functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]], function_call: Optional[str] = None, **kwargs: Any) \u2192 Runnable[Union[PromptValue, str, List[BaseMessage]], BaseMessage]\u00b6\nBind functions (and other objects) to this chat model.\nParameters\nfunctions \u2013 A list of function definitions to bind to this chat model.\nCan be  a dictionary, pydantic model, or callable. Pydantic\nmodels and callables will be automatically converted to\ntheir schema dictionary representation.\nfunction_call \u2013 Which function to require the model to call.\nMust be the name of the single provided function or\n\u201cauto\u201d to automatically determine which function to call\n(if any).\nkwargs \u2013 Any additional parameters to pass to the\nRunnable constructor.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\ncompletion_with_retry(run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any\u00b6\nUse tenacity to retry the completion call.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-7", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-8", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nstatic get_available_models() \u2192 Set[str][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-9", "text": "static get_available_models() \u2192 Set[str][source]\u00b6\nGet available models from EverlyAI API.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: list[langchain.schema.messages.BaseMessage]) \u2192 int[source]\u00b6\nCalculate num tokens with tiktoken package.\nOfficial documentation: https://github.com/openai/openai-cookbook/blob/\nmain/examples/How_to_format_inputs_to_ChatGPT_models.ipynb\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-10", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nGet the tokens present in the text with tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this model can be serialized by Langchain.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-11", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-12", "text": "Pass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-13", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "f5e302ad1bf1-14", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.everlyai.ChatEverlyAI.html"}
{"id": "ca8e0f8f4346-0", "text": "langchain.chat_models.vertexai.ChatVertexAI\u00b6\nclass langchain.chat_models.vertexai.ChatVertexAI[source]\u00b6\nBases: _VertexAICommon, BaseChatModel\nVertex AI Chat large language models API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam credentials: Any = None\u00b6\nThe default custom credentials (google.auth.credentials.Credentials) to use\nparam examples: Optional[List[BaseMessage]] = None\u00b6\nparam location: str = 'us-central1'\u00b6\nThe default location to use when making API calls.\nparam max_output_tokens: int = 128\u00b6\nToken limit determines the maximum amount of text output from one prompt.\nparam max_retries: int = 6\u00b6\nThe maximum number of retries to make when generating.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_name: str = 'chat-bison'\u00b6\nUnderlying model name.\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam project: Optional[str] = None\u00b6\nThe default GCP project to use when making Vertex API calls.\nparam request_parallelism: int = 5\u00b6\nThe amount of parallelism allowed for requests issued to VertexAI models.\nparam stop: Optional[List[str]] = None\u00b6\nOptional list of stop words to use when generating.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "ca8e0f8f4346-1", "text": "param streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.0\u00b6\nSampling temperature, it controls the degree of randomness in token selection.\nparam top_k: int = 40\u00b6\nHow the model selects tokens for output, the next token is selected from\nparam top_p: float = 0.95\u00b6\nTokens are selected from most probable to least until the sum of their\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "ca8e0f8f4346-2", "text": "Top Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "ca8e0f8f4346-3", "text": "Subclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "ca8e0f8f4346-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "ca8e0f8f4346-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "ca8e0f8f4346-6", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "ca8e0f8f4346-7", "text": "text generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "ca8e0f8f4346-8", "text": "Useful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "ca8e0f8f4346-9", "text": "classmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "ca8e0f8f4346-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "ca8e0f8f4346-11", "text": "Subclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "ca8e0f8f4346-12", "text": "on_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_codey_model: bool\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "ca8e0f8f4346-13", "text": "These attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\ntask_executor: ClassVar[Optional[Executor]] = FieldInfo(exclude=True, extra={})\u00b6\nExamples using ChatVertexAI\u00b6\nGoogle Cloud Platform Vertex AI PaLM", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.vertexai.ChatVertexAI.html"}
{"id": "a6d656e65025-0", "text": "langchain.chat_models.mlflow_ai_gateway.ChatParams\u00b6\nclass langchain.chat_models.mlflow_ai_gateway.ChatParams[source]\u00b6\nBases: BaseModel\nParameters for the MLflow AI Gateway LLM.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam candidate_count: int = 1\u00b6\nThe number of candidates to return.\nparam max_tokens: Optional[int] = None\u00b6\nparam stop: Optional[List[str]] = None\u00b6\nparam temperature: float = 0.0\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatParams.html"}
{"id": "a6d656e65025-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatParams.html"}
{"id": "a6d656e65025-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatParams.html"}
{"id": "1d86c670c9dc-0", "text": "langchain.chat_models.google_palm.ChatGooglePalmError\u00b6\nclass langchain.chat_models.google_palm.ChatGooglePalmError[source]\u00b6\nError with the Google PaLM API.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalmError.html"}
{"id": "763d0ed616ee-0", "text": "langchain.chat_models.fake.FakeListChatModel\u00b6\nclass langchain.chat_models.fake.FakeListChatModel[source]\u00b6\nBases: SimpleChatModel\nFake ChatModel for testing purposes.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam i: int = 0\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam responses: List [Required]\u00b6\nparam sleep: Optional[float] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeListChatModel.html"}
{"id": "763d0ed616ee-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeListChatModel.html"}
{"id": "763d0ed616ee-2", "text": "async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeListChatModel.html"}
{"id": "763d0ed616ee-3", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeListChatModel.html"}
{"id": "763d0ed616ee-4", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeListChatModel.html"}
{"id": "763d0ed616ee-5", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeListChatModel.html"}
{"id": "763d0ed616ee-6", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeListChatModel.html"}
{"id": "763d0ed616ee-7", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeListChatModel.html"}
{"id": "763d0ed616ee-8", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeListChatModel.html"}
{"id": "763d0ed616ee-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeListChatModel.html"}
{"id": "763d0ed616ee-10", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeListChatModel.html"}
{"id": "763d0ed616ee-11", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeListChatModel.html"}
{"id": "763d0ed616ee-12", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeListChatModel.html"}
{"id": "65077844837a-0", "text": "langchain.chat_models.anthropic.ChatAnthropic\u00b6\nclass langchain.chat_models.anthropic.ChatAnthropic[source]\u00b6\nBases: BaseChatModel, _AnthropicCommon\nAnthropic chat large language models.\nTo use, you should have the anthropic python package installed, and the\nenvironment variable ANTHROPIC_API_KEY set with your API key, or pass\nit as a named parameter to the constructor.\nExample\nimport anthropic\nfrom langchain.chat_models import ChatAnthropic\nmodel = ChatAnthropic(model=\"<model_name>\", anthropic_api_key=\"my-api-key\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam AI_PROMPT: Optional[str] = None\u00b6\nparam HUMAN_PROMPT: Optional[str] = None\u00b6\nparam anthropic_api_key: Optional[SecretStr] = None\u00b6\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nparam anthropic_api_url: Optional[str] = None\u00b6\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam count_tokens: Optional[Callable[[str], int]] = None\u00b6\nparam default_request_timeout: Optional[float] = None\u00b6\nTimeout for requests to Anthropic Completion API. Default is 600 seconds.\nparam max_tokens_to_sample: int = 256 (alias 'max_tokens')\u00b6\nDenotes the number of tokens to predict per generation.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str = 'claude-2' (alias 'model_name')\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "65077844837a-1", "text": "param model: str = 'claude-2' (alias 'model_name')\u00b6\nModel name to use.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nparam streaming: bool = False\u00b6\nWhether to stream the results.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = None\u00b6\nA non-negative float that tunes the degree of randomness in generation.\nparam top_k: Optional[int] = None\u00b6\nNumber of most likely tokens to consider at each step.\nparam top_p: Optional[float] = None\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "65077844837a-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "65077844837a-3", "text": "async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "65077844837a-4", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "65077844837a-5", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "65077844837a-6", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\nconvert_prompt(prompt: PromptValue) \u2192 str[source]\u00b6\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "65077844837a-7", "text": "This method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "65077844837a-8", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int[source]\u00b6\nCalculate number of tokens.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "65077844837a-9", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this model can be serialized by Langchain.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "65077844837a-10", "text": "predict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "65077844837a-11", "text": "Default implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "65077844837a-12", "text": "on_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "65077844837a-13", "text": "These attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ChatAnthropic\u00b6\nAnthropic\nLog10\nPlayWright Browser\nFallbacks\nAgent Trajectory\nCustom Pairwise Evaluator\nPairwise String Comparison\nCriteria Evaluation\nXML Agent\nFew-shot examples for chat models\nAgents", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anthropic.ChatAnthropic.html"}
{"id": "7d47e8c97445-0", "text": "langchain.chat_models.gigachat.GigaChat\u00b6\nclass langchain.chat_models.gigachat.GigaChat[source]\u00b6\nBases: _BaseGigaChat, BaseChatModel\nGigaChat large language models API.\nTo use, you should pass login and password to access GigaChat API or use token.\nExample\nfrom langchain.chat_models import GigaChat\ngiga = GigaChat(credentials=..., verify_ssl_certs=False)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam access_token: Optional[str] = None\u00b6\nAccess token for GigaChat\nparam auth_url: Optional[str] = None\u00b6\nAuth URL\nparam base_url: Optional[str] = None\u00b6\nBase API URL\nparam ca_bundle_file: Optional[str] = None\u00b6\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam cert_file: Optional[str] = None\u00b6\nparam credentials: Optional[str] = None\u00b6\nAuth Token\nparam key_file: Optional[str] = None\u00b6\nparam key_file_password: Optional[str] = None\u00b6\nparam max_tokens: Optional[int] = None\u00b6\nMaximum number of tokens to generate\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: Optional[str] = None\u00b6\nModel name to use.\nparam password: Optional[str] = None\u00b6\nPassword for authenticate\nparam profanity: bool = True\u00b6\nCheck for profanity\nparam scope: Optional[str] = None\u00b6\nPermission scope for access token", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "7d47e8c97445-1", "text": "param scope: Optional[str] = None\u00b6\nPermission scope for access token\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = None\u00b6\nWhat sampling temperature to use.\nparam timeout: Optional[float] = None\u00b6\nTimeout for request\nparam user: Optional[str] = None\u00b6\nUsername for authenticate\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\nparam verify_ssl_certs: Optional[bool] = None\u00b6\nCheck certificates for all requests\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "7d47e8c97445-2", "text": "Top Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "7d47e8c97445-3", "text": "Subclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "7d47e8c97445-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "7d47e8c97445-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "7d47e8c97445-6", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "7d47e8c97445-7", "text": "text generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int[source]\u00b6\nCount approximate number of tokens\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "7d47e8c97445-8", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "7d47e8c97445-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "7d47e8c97445-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "7d47e8c97445-11", "text": "Subclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "7d47e8c97445-12", "text": "on_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "7d47e8c97445-13", "text": "property lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty lc_serializable: bool\u00b6\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.gigachat.GigaChat.html"}
{"id": "2a495b86660f-0", "text": "langchain.chat_models.konko.ChatKonko\u00b6\nclass langchain.chat_models.konko.ChatKonko[source]\u00b6\nBases: BaseChatModel\nChatKonko Chat large language models API.\nTo use, you should have the konko python package installed, and the\nenvironment variable KONKO_API_KEY and OPENAI_API_KEY set with your API key.\nAny parameters that are valid to be passed to the konko.create call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.chat_models import ChatKonko\nllm = ChatKonko(model=\"meta-llama/Llama-2-13b-chat-hf\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam konko_api_key: Optional[str] = None\u00b6\nparam max_retries: int = 6\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: int = 20\u00b6\nMaximum number of tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str = 'meta-llama/Llama-2-13b-chat-hf'\u00b6\nModel name to use.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam n: int = 1\u00b6\nNumber of chat completions to generate for each prompt.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "2a495b86660f-1", "text": "Number of chat completions to generate for each prompt.\nparam openai_api_key: Optional[str] = None\u00b6\nparam request_timeout: Optional[Union[float, Tuple[float, float]]] = None\u00b6\nTimeout for requests to Konko completion API.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "2a495b86660f-2", "text": "Top Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "2a495b86660f-3", "text": "Subclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "2a495b86660f-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "2a495b86660f-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\ncompletion_with_retry(run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "2a495b86660f-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "2a495b86660f-7", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nstatic get_available_models(konko_api_key: Optional[str] = None, openai_api_key: Optional[str] = None, konko_api_base: str = 'https://api.konko.ai/v1') \u2192 Set[str][source]\u00b6\nGet available models from Konko API.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "2a495b86660f-8", "text": "classmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "2a495b86660f-9", "text": "invoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this model can be serialized by Langchain.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "2a495b86660f-10", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "2a495b86660f-11", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "2a495b86660f-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "2a495b86660f-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ChatKonko\u00b6\nKonko", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.konko.ChatKonko.html"}
{"id": "0e349f3a1a0d-0", "text": "langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway\u00b6\nclass langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway[source]\u00b6\nBases: BaseChatModel\nJavelin AI Gateway chat models API.\nTo use, you should have the javelin_sdk python package installed.\nFor more information, see https://docs.getjavelin.io\nExample\nfrom langchain.chat_models import ChatJavelinAIGateway\nchat = ChatJavelinAIGateway(\n    gateway_uri=\"<javelin-ai-gateway-uri>\",\n    route=\"<javelin-ai-gateway-chat-route>\",\n    params={\n        \"temperature\": 0.1\n    }\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam client: Any = None\u00b6\njavelin client.\nparam gateway_uri: Optional[str] = None\u00b6\nThe URI for the Javelin AI Gateway API.\nparam javelin_api_key: Optional[pydantic.types.SecretStr] = None\u00b6\nThe API key for the Javelin AI Gateway.\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam params: Optional[langchain.chat_models.javelin_ai_gateway.ChatParams] = None\u00b6\nParameters for the Javelin AI Gateway LLM.\nparam route: str [Required]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway.html"}
{"id": "0e349f3a1a0d-1", "text": "param route: str [Required]\u00b6\nThe route to use for the Javelin AI Gateway API.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway.html"}
{"id": "0e349f3a1a0d-2", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway.html"}
{"id": "0e349f3a1a0d-3", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway.html"}
{"id": "0e349f3a1a0d-4", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway.html"}
{"id": "0e349f3a1a0d-5", "text": "Parameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway.html"}
{"id": "0e349f3a1a0d-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway.html"}
{"id": "0e349f3a1a0d-7", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway.html"}
{"id": "0e349f3a1a0d-8", "text": "Returns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway.html"}
{"id": "0e349f3a1a0d-9", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway.html"}
{"id": "0e349f3a1a0d-10", "text": "Parameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway.html"}
{"id": "0e349f3a1a0d-11", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway.html"}
{"id": "0e349f3a1a0d-12", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatJavelinAIGateway.html"}
{"id": "063f1739bed3-0", "text": "langchain.chat_models.yandex.ChatYandexGPT\u00b6\nclass langchain.chat_models.yandex.ChatYandexGPT[source]\u00b6\nBases: _BaseYandexGPT, BaseChatModel\nWrapper around YandexGPT large language models.\nThere are two authentication options for the service account\nwith the ai.languageModels.user role:\nYou can specify the token in a constructor parameter iam_token\nor in an environment variable YC_IAM_TOKEN.\n- You can specify the key in a constructor parameter api_key\nor in an environment variable YC_API_KEY.\nExample\nfrom langchain.chat_models import ChatYandexGPT\nchat_model = ChatYandexGPT(iam_token=\"t1.9eu...\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_key: str = ''\u00b6\nYandex Cloud Api Key for service account\nwith the ai.languageModels.user role\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam iam_token: str = ''\u00b6\nYandex Cloud IAM token for service account\nwith the ai.languageModels.user role\nparam max_tokens: int = 7400\u00b6\nSets the maximum limit on the total number of tokens\nused for both the input prompt and the generated response.\nMust be greater than zero and not exceed 7400 tokens.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_name: str = 'general'\u00b6\nModel name to use.\nparam stop: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "063f1739bed3-1", "text": "Model name to use.\nparam stop: Optional[List[str]] = None\u00b6\nSequences when completion generation will stop.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.6\u00b6\nWhat sampling temperature to use.\nShould be a double number between 0 (inclusive) and 1 (inclusive).\nparam url: str = 'llm.api.cloud.yandex.net:443'\u00b6\nThe url of the API.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "063f1739bed3-2", "text": "Top Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "063f1739bed3-3", "text": "Subclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "063f1739bed3-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "063f1739bed3-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "063f1739bed3-6", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "063f1739bed3-7", "text": "text generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "063f1739bed3-8", "text": "Useful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "063f1739bed3-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "063f1739bed3-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "063f1739bed3-11", "text": "Subclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "063f1739bed3-12", "text": "on_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "063f1739bed3-13", "text": "property lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.yandex.ChatYandexGPT.html"}
{"id": "eddf05ea8c69-0", "text": "langchain.chat_models.fireworks.completion_with_retry\u00b6\nlangchain.chat_models.fireworks.completion_with_retry(llm: ChatFireworks, use_retry: bool, *, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.completion_with_retry.html"}
{"id": "0e8f429a1d47-0", "text": "langchain.chat_models.anyscale.ChatAnyscale\u00b6\nclass langchain.chat_models.anyscale.ChatAnyscale[source]\u00b6\nBases: ChatOpenAI\nAnyscale Chat large language models.\nSee https://www.anyscale.com/ for information about Anyscale.\nTo use, you should have the openai python package installed, and the\nenvironment variable ANYSCALE_API_KEY set with your API key.\nAlternatively, you can use the anyscale_api_key keyword argument.\nAny parameters that are valid to be passed to the openai.create call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.chat_models import ChatAnyscale\nchat = ChatAnyscale(model_name=\"meta-llama/Llama-2-7b-chat-hf\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam anyscale_api_base: str = 'https://api.endpoints.anyscale.com/v1'\u00b6\nBase URL path for API requests,\nleave blank if not using a proxy or service emulator.\nparam anyscale_api_key: SecretStr [Required]\u00b6\nAnyScale Endpoints API keys.\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nparam anyscale_proxy: Optional[str] = None\u00b6\nTo support explicit proxy for Anyscale.\nparam available_models: Optional[Set[str]] = None\u00b6\nAvailable models from Anyscale API.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam default_headers: Union[Mapping[str, str], None] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-1", "text": "param default_headers: Union[Mapping[str, str], None] = None\u00b6\nparam default_query: Union[Mapping[str, object], None] = None\u00b6\nparam http_client: Union[Any, None] = None\u00b6\nOptional httpx.Client.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: Optional[int] = None\u00b6\nMaximum number of tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'meta-llama/Llama-2-7b-chat-hf' (alias 'model')\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nNumber of chat completions to generate for each prompt.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Optional[str] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var OPENAI_API_KEY if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-2", "text": "Whether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-4", "text": "async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-5", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-6", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nbind_functions(functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]], function_call: Optional[str] = None, **kwargs: Any) \u2192 Runnable[Union[PromptValue, str, List[BaseMessage]], BaseMessage]\u00b6\nBind functions (and other objects) to this chat model.\nParameters\nfunctions \u2013 A list of function definitions to bind to this chat model.\nCan be  a dictionary, pydantic model, or callable. Pydantic\nmodels and callables will be automatically converted to\ntheir schema dictionary representation.\nfunction_call \u2013 Which function to require the model to call.\nMust be the name of the single provided function or\n\u201cauto\u201d to automatically determine which function to call\n(if any).\nkwargs \u2013 Any additional parameters to pass to the\nRunnable constructor.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\ncompletion_with_retry(run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any\u00b6\nUse tenacity to retry the completion call.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-7", "text": "The type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-8", "text": "Returns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-9", "text": "to the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nstatic get_available_models(anyscale_api_key: Optional[str] = None, anyscale_api_base: str = 'https://api.endpoints.anyscale.com/v1') \u2192 Set[str][source]\u00b6\nGet available models from Anyscale API.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: list[langchain.schema.messages.BaseMessage]) \u2192 int[source]\u00b6\nCalculate num tokens with tiktoken package.\nOfficial documentation: https://github.com/openai/openai-cookbook/blob/\nmain/examples/How_to_format_inputs_to_ChatGPT_models.ipynb", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-10", "text": "main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nGet the tokens present in the text with tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this model can be serialized by Langchain.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-11", "text": "Return whether this model can be serialized by Langchain.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-12", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-13", "text": "Subclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-14", "text": "on_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "0e8f429a1d47-15", "text": "property lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ChatAnyscale\u00b6\nAnyscale", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.anyscale.ChatAnyscale.html"}
{"id": "5657b76cc42c-0", "text": "langchain.chat_models.human.HumanInputChatModel\u00b6\nclass langchain.chat_models.human.HumanInputChatModel[source]\u00b6\nBases: BaseChatModel\nChatModel which returns user input as the response.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam input_func: Callable [Optional]\u00b6\nparam input_kwargs: Mapping[str, Any] = {}\u00b6\nparam message_func: Callable [Optional]\u00b6\nparam message_kwargs: Mapping[str, Any] = {}\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam separator: str = '\\n'\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.human.HumanInputChatModel.html"}
{"id": "5657b76cc42c-1", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.human.HumanInputChatModel.html"}
{"id": "5657b76cc42c-2", "text": "to the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.human.HumanInputChatModel.html"}
{"id": "5657b76cc42c-3", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.human.HumanInputChatModel.html"}
{"id": "5657b76cc42c-4", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.human.HumanInputChatModel.html"}
{"id": "5657b76cc42c-5", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.human.HumanInputChatModel.html"}
{"id": "5657b76cc42c-6", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.human.HumanInputChatModel.html"}
{"id": "5657b76cc42c-7", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.human.HumanInputChatModel.html"}
{"id": "5657b76cc42c-8", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.human.HumanInputChatModel.html"}
{"id": "5657b76cc42c-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.human.HumanInputChatModel.html"}
{"id": "5657b76cc42c-10", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.human.HumanInputChatModel.html"}
{"id": "5657b76cc42c-11", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.human.HumanInputChatModel.html"}
{"id": "5657b76cc42c-12", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using HumanInputChatModel\u00b6\nHuman input chat model", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.human.HumanInputChatModel.html"}
{"id": "5fd2ca05c7f7-0", "text": "langchain.chat_models.baidu_qianfan_endpoint.convert_message_to_dict\u00b6\nlangchain.chat_models.baidu_qianfan_endpoint.convert_message_to_dict(message: BaseMessage) \u2192 dict[source]\u00b6\nConvert a message to a dictionary that can be passed to the API.\nExamples using convert_message_to_dict\u00b6\nTwitter (via Apify)", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.baidu_qianfan_endpoint.convert_message_to_dict.html"}
{"id": "a4f73a187f15-0", "text": "langchain.chat_models.ernie.ErnieBotChat\u00b6\nclass langchain.chat_models.ernie.ErnieBotChat[source]\u00b6\nBases: BaseChatModel\nERNIE-Bot large language model.\nERNIE-Bot is a large language model developed by Baidu,\ncovering a huge amount of Chinese data.\nTo use, you should have the ernie_client_id and ernie_client_secret set,\nor set the environment variable ERNIE_CLIENT_ID and ERNIE_CLIENT_SECRET.\nNote:\naccess_token will be automatically generated based on client_id and client_secret,\nand will be regenerated after expiration (30 days).\nDefault model is ERNIE-Bot-turbo,\ncurrently supported models are ERNIE-Bot-turbo, ERNIE-Bot\nExample\nfrom langchain.chat_models import ErnieBotChat\nchat = ErnieBotChat(model_name='ERNIE-Bot')\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam access_token: Optional[str] = None\u00b6\naccess token is generated by client id and client secret,\nsetting this value directly will cause an error\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam ernie_api_base: Optional[str] = None\u00b6\nBaidu application custom endpoints\nparam ernie_client_id: Optional[str] = None\u00b6\nBaidu application client id\nparam ernie_client_secret: Optional[str] = None\u00b6\nBaidu application client secret\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "a4f73a187f15-1", "text": "Metadata to add to the run trace.\nparam model_name: str = 'ERNIE-Bot-turbo'\u00b6\nmodel name of ernie, default is ERNIE-Bot-turbo.\nCurrently supported ERNIE-Bot-turbo, ERNIE-Bot\nparam penalty_score: Optional[float] = 1\u00b6\nparam request_timeout: Optional[int] = 60\u00b6\nrequest timeout for chat http requests\nparam streaming: Optional[bool] = False\u00b6\nstreaming mode. not supported yet.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = 0.95\u00b6\nparam top_p: Optional[float] = 0.8\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "a4f73a187f15-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "a4f73a187f15-3", "text": "async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "a4f73a187f15-4", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "a4f73a187f15-5", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "a4f73a187f15-6", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "a4f73a187f15-7", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "a4f73a187f15-8", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "a4f73a187f15-9", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "a4f73a187f15-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "a4f73a187f15-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "a4f73a187f15-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "a4f73a187f15-13", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ErnieBotChat\u00b6\nERNIE-Bot Chat", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.ernie.ErnieBotChat.html"}
{"id": "d84d8cd615a3-0", "text": "langchain.chat_models.bedrock.BedrockChat\u00b6\nclass langchain.chat_models.bedrock.BedrockChat[source]\u00b6\nBases: BaseChatModel, BedrockBase\nA chat model that uses the Bedrock API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam credentials_profile_name: Optional[str] = None\u00b6\nThe name of the profile in the ~/.aws/credentials or ~/.aws/config files, which\nhas either access keys or role information specified.\nIf not specified, the default credential profile or, if on an EC2 instance,\ncredentials from IMDS will be used.\nSee: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\nparam endpoint_url: Optional[str] = None\u00b6\nNeeded if you don\u2019t want to default to us-east-1 endpoint\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_id: str [Required]\u00b6\nId of the model to call, e.g., amazon.titan-text-express-v1, this is\nequivalent to the modelId property in the list-foundation-models api\nparam model_kwargs: Optional[Dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam provider_stop_sequence_key_name_map: Mapping[str, str] = {'ai21': 'stop_sequences', 'amazon': 'stopSequences', 'anthropic': 'stop_sequences', 'cohere': 'stop_sequences'}\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "d84d8cd615a3-1", "text": "param region_name: Optional[str] = None\u00b6\nThe aws region e.g., us-west-2. Fallsback to AWS_DEFAULT_REGION env variable\nor region specified in ~/.aws/config in case it is not provided here.\nparam streaming: bool = False\u00b6\nWhether to stream the results.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "d84d8cd615a3-2", "text": "Asynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "d84d8cd615a3-3", "text": "Parameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "d84d8cd615a3-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "d84d8cd615a3-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "d84d8cd615a3-6", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "d84d8cd615a3-7", "text": "text generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int[source]\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "d84d8cd615a3-8", "text": "Useful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int][source]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this model can be serialized by Langchain.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "d84d8cd615a3-9", "text": "Return whether this model can be serialized by Langchain.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "d84d8cd615a3-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "d84d8cd615a3-11", "text": "Subclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "d84d8cd615a3-12", "text": "on_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "d84d8cd615a3-13", "text": "property lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using BedrockChat\u00b6\nBedrock Chat", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.BedrockChat.html"}
{"id": "c5efb603dd11-0", "text": "langchain.chat_models.litellm.acompletion_with_retry\u00b6\nasync langchain.chat_models.litellm.acompletion_with_retry(llm: ChatLiteLLM, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the async completion call.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.acompletion_with_retry.html"}
{"id": "0c7215a9c546-0", "text": "langchain.chat_models.cohere.get_role\u00b6\nlangchain.chat_models.cohere.get_role(message: BaseMessage) \u2192 str[source]\u00b6\nGet the role of the message.\nParameters\nmessage \u2013 The message.\nReturns\nThe role of the message.\nRaises\nValueError \u2013 If the message is of an unknown type.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.cohere.get_role.html"}
{"id": "627764212183-0", "text": "langchain.chat_models.fake.FakeMessagesListChatModel\u00b6\nclass langchain.chat_models.fake.FakeMessagesListChatModel[source]\u00b6\nBases: BaseChatModel\nFake ChatModel for testing purposes.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam i: int = 0\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam responses: List[langchain.schema.messages.BaseMessage] [Required]\u00b6\nparam sleep: Optional[float] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeMessagesListChatModel.html"}
{"id": "627764212183-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeMessagesListChatModel.html"}
{"id": "627764212183-2", "text": "async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeMessagesListChatModel.html"}
{"id": "627764212183-3", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeMessagesListChatModel.html"}
{"id": "627764212183-4", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeMessagesListChatModel.html"}
{"id": "627764212183-5", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeMessagesListChatModel.html"}
{"id": "627764212183-6", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeMessagesListChatModel.html"}
{"id": "627764212183-7", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeMessagesListChatModel.html"}
{"id": "627764212183-8", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeMessagesListChatModel.html"}
{"id": "627764212183-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeMessagesListChatModel.html"}
{"id": "627764212183-10", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeMessagesListChatModel.html"}
{"id": "627764212183-11", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeMessagesListChatModel.html"}
{"id": "627764212183-12", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fake.FakeMessagesListChatModel.html"}
{"id": "3924dc4b55fb-0", "text": "langchain.chat_models.fireworks.acompletion_with_retry\u00b6\nasync langchain.chat_models.fireworks.acompletion_with_retry(llm: ChatFireworks, use_retry: bool, *, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the async completion call.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.acompletion_with_retry.html"}
{"id": "20c9c7ef591f-0", "text": "langchain.chat_models.hunyuan.ChatHunyuan\u00b6\nclass langchain.chat_models.hunyuan.ChatHunyuan[source]\u00b6\nBases: BaseChatModel\nTencent Hunyuan chat models API by Tencent.\nFor more information, see https://cloud.tencent.com/document/product/1729\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam hunyuan_api_base: str = 'https://hunyuan.cloud.tencent.com'\u00b6\nHunyuan custom endpoints\nparam hunyuan_app_id: Optional[str] = None\u00b6\nHunyuan App ID\nparam hunyuan_secret_id: Optional[str] = None\u00b6\nHunyuan Secret ID\nparam hunyuan_secret_key: Optional[pydantic.types.SecretStr] = None\u00b6\nHunyuan Secret Key\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for API call not explicitly specified.\nparam query_id: Optional[str] = None\u00b6\nQuery id for troubleshooting\nparam request_timeout: int = 60\u00b6\nTimeout for requests to Hunyuan API. Default is 60 seconds.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "20c9c7ef591f-1", "text": "Whether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 1.0\u00b6\nWhat sampling temperature to use.\nparam top_p: float = 1.0\u00b6\nWhat probability mass to use.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "20c9c7ef591f-2", "text": "Asynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "20c9c7ef591f-3", "text": "Parameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "20c9c7ef591f-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "20c9c7ef591f-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "20c9c7ef591f-6", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "20c9c7ef591f-7", "text": "text generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "20c9c7ef591f-8", "text": "Useful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "20c9c7ef591f-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "20c9c7ef591f-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "20c9c7ef591f-11", "text": "Subclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "20c9c7ef591f-12", "text": "on_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "20c9c7ef591f-13", "text": "property lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty lc_serializable: bool\u00b6\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.hunyuan.ChatHunyuan.html"}
{"id": "b9457ba01024-0", "text": "langchain.chat_models.azureml_endpoint.LlamaContentFormatter\u00b6\nclass langchain.chat_models.azureml_endpoint.LlamaContentFormatter[source]\u00b6\nContent formatter for LLaMA.\nAttributes\nSUPPORTED_ROLES\naccepts\nThe MIME type of the response data returned from the endpoint\ncontent_type\nThe MIME type of the input data passed to the endpoint\nMethods\n__init__()\nescape_special_characters(prompt)\nEscapes any special characters in prompt\nformat_request_payload(prompt,\u00a0model_kwargs)\nFormats the request according to the chosen api\nformat_response_payload(output)\nFormats response\n__init__()\u00b6\nstatic escape_special_characters(prompt: str) \u2192 str\u00b6\nEscapes any special characters in prompt\nformat_request_payload(prompt: str, model_kwargs: Dict) \u2192 bytes[source]\u00b6\nFormats the request according to the chosen api\nformat_response_payload(output: bytes) \u2192 str[source]\u00b6\nFormats response\nExamples using LlamaContentFormatter\u00b6\nAzureML Chat Online Endpoint", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azureml_endpoint.LlamaContentFormatter.html"}
{"id": "238d0c0e87b0-0", "text": "langchain.chat_models.google_palm.ChatGooglePalm\u00b6\nclass langchain.chat_models.google_palm.ChatGooglePalm[source]\u00b6\nBases: BaseChatModel, BaseModel\nGoogle PaLM Chat models API.\nTo use you must have the google.generativeai Python package installed and\neither:\nThe GOOGLE_API_KEY` environment variable set with your API key, or\nPass your API key using the google_api_key kwarg to the ChatGoogle\nconstructor.\nExample\nfrom langchain.chat_models import ChatGooglePalm\nchat = ChatGooglePalm()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam google_api_key: Optional[str] = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_name: str = 'models/chat-bison-001'\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nNumber of chat completions to generate for each prompt. Note that the API may\nnot return the full n completions if duplicates are generated.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = None\u00b6\nRun inference with this temperature. Must by in the closed\ninterval [0.0, 1.0].\nparam top_k: Optional[int] = None\u00b6\nDecode using top-k sampling: consider the set of top_k most probable tokens.\nMust be positive.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "238d0c0e87b0-1", "text": "Must be positive.\nparam top_p: Optional[float] = None\u00b6\nDecode using nucleus sampling: consider the smallest set of tokens whose\nprobability sum is at least top_p. Must be in the closed interval [0.0, 1.0].\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "238d0c0e87b0-2", "text": "This method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "238d0c0e87b0-3", "text": "Parameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "238d0c0e87b0-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "238d0c0e87b0-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "238d0c0e87b0-6", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "238d0c0e87b0-7", "text": "text generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "238d0c0e87b0-8", "text": "Useful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "238d0c0e87b0-9", "text": "classmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "238d0c0e87b0-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "238d0c0e87b0-11", "text": "Subclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "238d0c0e87b0-12", "text": "on_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "238d0c0e87b0-13", "text": "property lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.ChatGooglePalm.html"}
{"id": "b82fbb5085c8-0", "text": "langchain_experimental.chat_models.llm_wrapper.Orca\u00b6\nclass langchain_experimental.chat_models.llm_wrapper.Orca[source]\u00b6\nBases: ChatWrapper\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_n_beg: str = '### Assistant:\\n'\u00b6\nparam ai_n_end: str = '\\n\\n'\u00b6\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam llm: LLM [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam sys_beg: str = '### System:\\n'\u00b6\nparam sys_end: str = '\\n\\n'\u00b6\nparam system_message: SystemMessage = SystemMessage(content=\"You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\\n\\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\")\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam usr_0_beg: Optional[str] = None\u00b6\nparam usr_0_end: Optional[str] = None\u00b6\nparam usr_n_beg: str = '### User:\\n'\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Orca.html"}
{"id": "b82fbb5085c8-1", "text": "param usr_n_beg: str = '### User:\\n'\u00b6\nparam usr_n_end: str = '\\n\\n'\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Orca.html"}
{"id": "b82fbb5085c8-2", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Orca.html"}
{"id": "b82fbb5085c8-3", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Orca.html"}
{"id": "b82fbb5085c8-4", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Orca.html"}
{"id": "b82fbb5085c8-5", "text": "Parameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Orca.html"}
{"id": "b82fbb5085c8-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Orca.html"}
{"id": "b82fbb5085c8-7", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Orca.html"}
{"id": "b82fbb5085c8-8", "text": "Returns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Orca.html"}
{"id": "b82fbb5085c8-9", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Orca.html"}
{"id": "b82fbb5085c8-10", "text": "Parameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Orca.html"}
{"id": "b82fbb5085c8-11", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Orca.html"}
{"id": "b82fbb5085c8-12", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.Orca.html"}
{"id": "69ed275e1382-0", "text": "langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI\u00b6\nclass langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI[source]\u00b6\nBases: ChatOpenAI\nPromptLayer and OpenAI Chat large language models API.\nTo use, you should have the openai and promptlayer python\npackage installed, and the environment variable OPENAI_API_KEY\nand PROMPTLAYER_API_KEY set with your openAI API key and\npromptlayer key respectively.\nAll parameters that can be passed to the OpenAI LLM can also\nbe passed here. The PromptLayerChatOpenAI adds to optional\nParameters\npl_tags \u2013 List of strings to tag the request with.\nreturn_pl_id \u2013 If True, the PromptLayer request ID will be\nreturned in the generation_info field of the\nGeneration object.\nExample\nfrom langchain.chat_models import PromptLayerChatOpenAI\nopenai = PromptLayerChatOpenAI(model_name=\"gpt-3.5-turbo\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam default_headers: Union[Mapping[str, str], None] = None\u00b6\nparam default_query: Union[Mapping[str, object], None] = None\u00b6\nparam http_client: Union[Any, None] = None\u00b6\nOptional httpx.Client.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: Optional[int] = None\u00b6\nMaximum number of tokens to generate.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-1", "text": "param max_tokens: Optional[int] = None\u00b6\nMaximum number of tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'gpt-3.5-turbo' (alias 'model')\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nNumber of chat completions to generate for each prompt.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Optional[str] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var OPENAI_API_KEY if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam pl_tags: Optional[List[str]] = None\u00b6\nparam request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam return_pl_id: Optional[bool] = False\u00b6\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-2", "text": "The model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-4", "text": "async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-5", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-6", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nbind_functions(functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]], function_call: Optional[str] = None, **kwargs: Any) \u2192 Runnable[Union[PromptValue, str, List[BaseMessage]], BaseMessage]\u00b6\nBind functions (and other objects) to this chat model.\nParameters\nfunctions \u2013 A list of function definitions to bind to this chat model.\nCan be  a dictionary, pydantic model, or callable. Pydantic\nmodels and callables will be automatically converted to\ntheir schema dictionary representation.\nfunction_call \u2013 Which function to require the model to call.\nMust be the name of the single provided function or\n\u201cauto\u201d to automatically determine which function to call\n(if any).\nkwargs \u2013 Any additional parameters to pass to the\nRunnable constructor.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\ncompletion_with_retry(run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any\u00b6\nUse tenacity to retry the completion call.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-7", "text": "The type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-8", "text": "Returns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-9", "text": "to the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nCalculate num tokens for gpt-3.5-turbo and gpt-4 with tiktoken package.\nOfficial documentation: https://github.com/openai/openai-cookbook/blob/\nmain/examples/How_to_format_inputs_to_ChatGPT_models.ipynb\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-10", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nGet the tokens present in the text with tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this model can be serialized by Langchain.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-11", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-12", "text": "Pass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-13", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "69ed275e1382-14", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using PromptLayerChatOpenAI\u00b6\nPromptLayer ChatOpenAI", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.promptlayer_openai.PromptLayerChatOpenAI.html"}
{"id": "10bc2d1e3045-0", "text": "langchain.chat_models.fireworks.conditional_decorator\u00b6\nlangchain.chat_models.fireworks.conditional_decorator(condition: bool, decorator: Callable[[Any], Any]) \u2192 Callable[[Any], Any][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.conditional_decorator.html"}
{"id": "9fd2ada99805-0", "text": "langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint\u00b6\nclass langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint[source]\u00b6\nBases: BaseChatModel\nEas LLM Service chat model API.\nTo use, must have a deployed eas chat llm service on AliCloud. One can set the\nenvironment variable eas_service_url and eas_service_token set with your eas\nservice url and service token.\nExample\nfrom langchain.chat_models import PaiEasChatEndpoint\neas_chat_endpoint = PaiEasChatEndpoint(\n    eas_service_url=\"your_service_url\",\n    eas_service_token=\"your_service_token\"\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam do_sample: Optional[bool] = False\u00b6\nparam eas_service_token: str [Required]\u00b6\nPAI-EAS Service Infer Params\nparam eas_service_url: str [Required]\u00b6\nPAI-EAS Service TOKEN\nparam max_new_tokens: Optional[int] = 512\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Optional[dict] = None\u00b6\nparam stop_sequences: Optional[List[str]] = None\u00b6\nEnable stream chat mode.\nparam streaming: bool = False\u00b6\nKey/value arguments to pass to the model. Reserved for future use\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "9fd2ada99805-1", "text": "param tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = 0.8\u00b6\nparam timeout: Optional[int] = 5000\u00b6\nparam top_k: Optional[int] = 10\u00b6\nparam top_p: Optional[float] = 0.1\u00b6\nparam use_cache: Optional[bool] = True\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\nparam version: Optional[str] = '2.0'\u00b6\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "9fd2ada99805-2", "text": "Top Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "9fd2ada99805-3", "text": "Subclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "9fd2ada99805-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "9fd2ada99805-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "9fd2ada99805-6", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nformat_request_payload(messages: List[BaseMessage], **model_kwargs: Any) \u2192 dict[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "9fd2ada99805-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "9fd2ada99805-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "9fd2ada99805-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "9fd2ada99805-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "9fd2ada99805-11", "text": "Subclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "9fd2ada99805-12", "text": "on_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "9fd2ada99805-13", "text": "property lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.pai_eas_endpoint.PaiEasChatEndpoint.html"}
{"id": "71ff23d09db4-0", "text": "langchain.chat_models.litellm.ChatLiteLLM\u00b6\nclass langchain.chat_models.litellm.ChatLiteLLM[source]\u00b6\nBases: BaseChatModel\nA chat model that uses the LiteLLM API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam anthropic_api_key: Optional[str] = None\u00b6\nparam api_base: Optional[str] = None\u00b6\nparam azure_api_key: Optional[str] = None\u00b6\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam cohere_api_key: Optional[str] = None\u00b6\nparam custom_llm_provider: Optional[str] = None\u00b6\nparam max_retries: int = 6\u00b6\nparam max_tokens: int = 256\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str = 'gpt-3.5-turbo'\u00b6\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nRun inference with this temperature. Must by in the closed\ninterval [0.0, 1.0].\nparam model_name: Optional[str] = None\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nNumber of chat completions to generate for each prompt. Note that the API may\nnot return the full n completions if duplicates are generated.\nparam openai_api_key: Optional[str] = None\u00b6\nparam openrouter_api_key: Optional[str] = None\u00b6\nparam organization: Optional[str] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "71ff23d09db4-1", "text": "param organization: Optional[str] = None\u00b6\nparam replicate_api_key: Optional[str] = None\u00b6\nparam request_timeout: Optional[Union[float, Tuple[float, float]]] = None\u00b6\nparam streaming: bool = False\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = 1\u00b6\nparam top_k: Optional[int] = None\u00b6\nDecode using top-k sampling: consider the set of top_k most probable tokens.\nMust be positive.\nparam top_p: Optional[float] = None\u00b6\nDecode using nucleus sampling: consider the smallest set of tokens whose\nprobability sum is at least top_p. Must be in the closed interval [0.0, 1.0].\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "71ff23d09db4-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "71ff23d09db4-3", "text": "async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "71ff23d09db4-4", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "71ff23d09db4-5", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\ncompletion_with_retry(run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "71ff23d09db4-6", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "71ff23d09db4-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "71ff23d09db4-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "71ff23d09db4-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "71ff23d09db4-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "71ff23d09db4-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "71ff23d09db4-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "71ff23d09db4-13", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ChatLiteLLM\u00b6\n\ud83d\ude85 LiteLLM", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLM.html"}
{"id": "b72d31c8c866-0", "text": "langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway\u00b6\nclass langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway[source]\u00b6\nBases: BaseChatModel\nMLflow AI Gateway chat models API.\nTo use, you should have the mlflow[gateway] python package installed.\nFor more information, see https://mlflow.org/docs/latest/gateway/index.html.\nExample\nfrom langchain.chat_models import ChatMLflowAIGateway\nchat = ChatMLflowAIGateway(\n    gateway_uri=\"<your-mlflow-ai-gateway-uri>\",\n    route=\"<your-mlflow-ai-gateway-chat-route>\",\n    params={\n        \"temperature\": 0.1\n    }\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam gateway_uri: Optional[str] = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam params: Optional[langchain.chat_models.mlflow_ai_gateway.ChatParams] = None\u00b6\nparam route: str [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway.html"}
{"id": "b72d31c8c866-1", "text": "Call self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway.html"}
{"id": "b72d31c8c866-2", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway.html"}
{"id": "b72d31c8c866-3", "text": "Use this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway.html"}
{"id": "b72d31c8c866-4", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway.html"}
{"id": "b72d31c8c866-5", "text": "configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway.html"}
{"id": "b72d31c8c866-6", "text": "Top Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway.html"}
{"id": "b72d31c8c866-7", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway.html"}
{"id": "b72d31c8c866-8", "text": "invoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway.html"}
{"id": "b72d31c8c866-9", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway.html"}
{"id": "b72d31c8c866-10", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway.html"}
{"id": "b72d31c8c866-11", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway.html"}
{"id": "b72d31c8c866-12", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ChatMLflowAIGateway\u00b6\nMLflow AI Gateway", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.mlflow_ai_gateway.ChatMLflowAIGateway.html"}
{"id": "1ab25bb031f5-0", "text": "langchain.chat_models.openai.acompletion_with_retry\u00b6\nasync langchain.chat_models.openai.acompletion_with_retry(llm: ChatOpenAI, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the async completion call.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.acompletion_with_retry.html"}
{"id": "ef62163882be-0", "text": "langchain.chat_models.jinachat.acompletion_with_retry\u00b6\nasync langchain.chat_models.jinachat.acompletion_with_retry(llm: JinaChat, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the async completion call.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.acompletion_with_retry.html"}
{"id": "e57b4faeb89a-0", "text": "langchain.chat_models.tongyi.convert_dict_to_message\u00b6\nlangchain.chat_models.tongyi.convert_dict_to_message(_dict: Mapping[str, Any]) \u2192 BaseMessage[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.convert_dict_to_message.html"}
{"id": "262081ef6b37-0", "text": "langchain.chat_models.litellm.ChatLiteLLMException\u00b6\nclass langchain.chat_models.litellm.ChatLiteLLMException[source]\u00b6\nError with the LiteLLM I/O library", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.litellm.ChatLiteLLMException.html"}
{"id": "19f692f3dae9-0", "text": "langchain.chat_models.base.SimpleChatModel\u00b6\nclass langchain.chat_models.base.SimpleChatModel[source]\u00b6\nBases: BaseChatModel\nSimple Chat Model.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[langchain.schema.callbacks.base.BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Optional[Union[List[langchain.schema.callbacks.base.BaseCallbackHandler], langchain.schema.callbacks.base.BaseCallbackManager]] = None\u00b6\nCallbacks to add to the run trace.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.SimpleChatModel.html"}
{"id": "19f692f3dae9-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.SimpleChatModel.html"}
{"id": "19f692f3dae9-2", "text": "async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.SimpleChatModel.html"}
{"id": "19f692f3dae9-3", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.SimpleChatModel.html"}
{"id": "19f692f3dae9-4", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.SimpleChatModel.html"}
{"id": "19f692f3dae9-5", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.SimpleChatModel.html"}
{"id": "19f692f3dae9-6", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.SimpleChatModel.html"}
{"id": "19f692f3dae9-7", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.SimpleChatModel.html"}
{"id": "19f692f3dae9-8", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.SimpleChatModel.html"}
{"id": "19f692f3dae9-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.SimpleChatModel.html"}
{"id": "19f692f3dae9-10", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.SimpleChatModel.html"}
{"id": "19f692f3dae9-11", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.SimpleChatModel.html"}
{"id": "19f692f3dae9-12", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.base.SimpleChatModel.html"}
{"id": "f08cf4d83bdc-0", "text": "langchain.chat_models.google_palm.chat_with_retry\u00b6\nlangchain.chat_models.google_palm.chat_with_retry(llm: ChatGooglePalm, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.google_palm.chat_with_retry.html"}
{"id": "1703b1c0cef9-0", "text": "langchain_experimental.chat_models.llm_wrapper.ChatWrapper\u00b6\nclass langchain_experimental.chat_models.llm_wrapper.ChatWrapper[source]\u00b6\nBases: BaseChatModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai_n_beg: str [Required]\u00b6\nparam ai_n_end: str [Required]\u00b6\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam llm: langchain.llms.base.LLM [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam sys_beg: str [Required]\u00b6\nparam sys_end: str [Required]\u00b6\nparam system_message: langchain.schema.messages.SystemMessage = SystemMessage(content=\"You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\\n\\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\")\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam usr_0_beg: Optional[str] = None\u00b6\nparam usr_0_end: Optional[str] = None\u00b6\nparam usr_n_beg: str [Required]\u00b6\nparam usr_n_end: str [Required]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.ChatWrapper.html"}
{"id": "1703b1c0cef9-1", "text": "param usr_n_end: str [Required]\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.ChatWrapper.html"}
{"id": "1703b1c0cef9-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.ChatWrapper.html"}
{"id": "1703b1c0cef9-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.ChatWrapper.html"}
{"id": "1703b1c0cef9-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.ChatWrapper.html"}
{"id": "1703b1c0cef9-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.ChatWrapper.html"}
{"id": "1703b1c0cef9-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.ChatWrapper.html"}
{"id": "1703b1c0cef9-7", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.ChatWrapper.html"}
{"id": "1703b1c0cef9-8", "text": "Returns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.ChatWrapper.html"}
{"id": "1703b1c0cef9-9", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.ChatWrapper.html"}
{"id": "1703b1c0cef9-10", "text": "Parameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.ChatWrapper.html"}
{"id": "1703b1c0cef9-11", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.ChatWrapper.html"}
{"id": "1703b1c0cef9-12", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain_experimental.chat_models.llm_wrapper.ChatWrapper.html"}
{"id": "c724ea6bffc4-0", "text": "langchain.chat_models.javelin_ai_gateway.ChatParams\u00b6\nclass langchain.chat_models.javelin_ai_gateway.ChatParams[source]\u00b6\nBases: BaseModel\nParameters for the Javelin AI Gateway LLM.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam max_tokens: Optional[int] = None\u00b6\nparam stop: Optional[List[str]] = None\u00b6\nparam temperature: float = 0.0\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatParams.html"}
{"id": "c724ea6bffc4-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatParams.html"}
{"id": "c724ea6bffc4-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.javelin_ai_gateway.ChatParams.html"}
{"id": "41b41ed61022-0", "text": "langchain.chat_models.tongyi.convert_message_to_dict\u00b6\nlangchain.chat_models.tongyi.convert_message_to_dict(message: BaseMessage) \u2192 dict[source]\u00b6\nExamples using convert_message_to_dict\u00b6\nTwitter (via Apify)", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.tongyi.convert_message_to_dict.html"}
{"id": "22449ede29f6-0", "text": "langchain.chat_models.jinachat.JinaChat\u00b6\nclass langchain.chat_models.jinachat.JinaChat[source]\u00b6\nBases: BaseChatModel\nJina AI Chat models API.\nTo use, you should have the openai python package installed, and the\nenvironment variable JINACHAT_API_KEY set to your API key, which you\ncan generate at https://chat.jina.ai/api.\nAny parameters that are valid to be passed to the openai.create call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.chat_models import JinaChat\nchat = JinaChat()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam jinachat_api_key: Optional[str] = None\u00b6\nBase URL path for API requests,\nleave blank if not using a proxy or service emulator.\nparam max_retries: int = 6\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: Optional[int] = None\u00b6\nMaximum number of tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam request_timeout: Optional[Union[float, Tuple[float, float]]] = None\u00b6\nTimeout for requests to JinaChat completion API. Default is 600 seconds.\nparam streaming: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "22449ede29f6-1", "text": "param streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "22449ede29f6-2", "text": "This method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "22449ede29f6-3", "text": "Parameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "22449ede29f6-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "22449ede29f6-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\ncompletion_with_retry(**kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "22449ede29f6-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "22449ede29f6-7", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "22449ede29f6-8", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "22449ede29f6-9", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this model can be serialized by Langchain.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "22449ede29f6-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "22449ede29f6-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "22449ede29f6-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "22449ede29f6-13", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using JinaChat\u00b6\nJinaChat", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.jinachat.JinaChat.html"}
{"id": "78c9503636e4-0", "text": "langchain.chat_models.bedrock.ChatPromptAdapter\u00b6\nclass langchain.chat_models.bedrock.ChatPromptAdapter[source]\u00b6\nAdapter class to prepare the inputs from Langchain to prompt format\nthat Chat model expects.\nMethods\n__init__()\nconvert_messages_to_prompt(provider,\u00a0messages)\n__init__()\u00b6\nclassmethod convert_messages_to_prompt(provider: str, messages: List[BaseMessage]) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.bedrock.ChatPromptAdapter.html"}
{"id": "13dd0c5bbf33-0", "text": "langchain.chat_models.fireworks.acompletion_with_retry_streaming\u00b6\nasync langchain.chat_models.fireworks.acompletion_with_retry_streaming(llm: ChatFireworks, use_retry: bool, *, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call for streaming.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.fireworks.acompletion_with_retry_streaming.html"}
{"id": "878159846395-0", "text": "langchain.chat_models.minimax.MiniMaxChat\u00b6\nclass langchain.chat_models.minimax.MiniMaxChat[source]\u00b6\nBases: MinimaxCommon, BaseChatModel\nWrapper around Minimax large language models.\nTo use, you should have the environment variable MINIMAX_GROUP_ID and\nMINIMAX_API_KEY set with your API token, or pass it as a named parameter to\nthe constructor.\nExample\nfrom langchain.chat_models import MiniMaxChat\nllm = MiniMaxChat(model_name=\"abab5-chat\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam max_tokens: int = 256\u00b6\nDenotes the number of tokens to predict per generation.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam minimax_api_host: Optional[str] = None\u00b6\nparam minimax_api_key: Optional[str] = None\u00b6\nparam minimax_group_id: Optional[str] = None\u00b6\nparam model: str = 'abab5.5-chat'\u00b6\nModel name to use.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nA non-negative float that tunes the degree of randomness in generation.\nparam top_p: float = 0.95\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.minimax.MiniMaxChat.html"}
{"id": "878159846395-1", "text": "param top_p: float = 0.95\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.minimax.MiniMaxChat.html"}
{"id": "878159846395-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.minimax.MiniMaxChat.html"}
{"id": "878159846395-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.minimax.MiniMaxChat.html"}
{"id": "878159846395-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.minimax.MiniMaxChat.html"}
{"id": "878159846395-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.minimax.MiniMaxChat.html"}
{"id": "878159846395-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.minimax.MiniMaxChat.html"}
{"id": "878159846395-7", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.minimax.MiniMaxChat.html"}
{"id": "878159846395-8", "text": "Returns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.minimax.MiniMaxChat.html"}
{"id": "878159846395-9", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.minimax.MiniMaxChat.html"}
{"id": "878159846395-10", "text": "Parameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.minimax.MiniMaxChat.html"}
{"id": "878159846395-11", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.minimax.MiniMaxChat.html"}
{"id": "878159846395-12", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.minimax.MiniMaxChat.html"}
{"id": "50d1a460c5aa-0", "text": "langchain.chat_models.azure_openai.AzureChatOpenAI\u00b6\nclass langchain.chat_models.azure_openai.AzureChatOpenAI[source]\u00b6\nBases: ChatOpenAI\nAzure OpenAI Chat Completion API.\nTo use this class you\nmust have a deployed model on Azure OpenAI. Use deployment_name in the\nconstructor to refer to the \u201cModel deployment name\u201d in the Azure portal.\nIn addition, you should have the openai python package installed, and the\nfollowing environment variables set or passed in constructor in lower case:\n- AZURE_OPENAI_API_KEY\n- AZURE_OPENAI_API_ENDPOINT\n- AZURE_OPENAI_AD_TOKEN\n- OPENAI_API_VERSION\n- OPENAI_PROXY\nFor example, if you have gpt-35-turbo deployed, with the deployment name\n35-turbo-dev, the constructor should look like:\nAzureChatOpenAI(\n    azure_deployment=\"35-turbo-dev\",\n    openai_api_version=\"2023-05-15\",\n)\nBe aware the API version may change.\nYou can also specify the version of the model using model_version constructor\nparameter, as Azure OpenAI doesn\u2019t return model version with the response.\nDefault is empty. When you specify the version, it will be appended to the\nmodel name in the response. Setting correct version will help you to calculate the\ncost properly. Model version is not validated, so make sure you set it correctly\nto get the correct cost.\nAny parameters that are valid to be passed to the openai.create call can be passed\nin, even if not explicitly saved on this class.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam azure_ad_token: Union[str, None] = None\u00b6\nYour Azure Active Directory token.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-1", "text": "Your Azure Active Directory token.\nAutomatically inferred from env var AZURE_OPENAI_AD_TOKEN if not provided.\nFor more:\nhttps://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id.\nparam azure_ad_token_provider: Union[str, None] = None\u00b6\nA function that returns an Azure Active Directory token.\nWill be invoked on every request.\nparam azure_endpoint: Union[str, None] = None\u00b6\nYour Azure endpoint, including the resource.\nAutomatically inferred from env var AZURE_OPENAI_ENDPOINT if not provided.\nExample: https://example-resource.azure.openai.com/\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam default_headers: Union[Mapping[str, str], None] = None\u00b6\nparam default_query: Union[Mapping[str, object], None] = None\u00b6\nparam deployment_name: Union[str, None] = None (alias 'azure_deployment')\u00b6\nA model deployment.\nIf given sets the base client URL to include /deployments/{azure_deployment}.\nNote: this means you won\u2019t be able to use non-deployment endpoints.\nparam http_client: Union[Any, None] = None\u00b6\nOptional httpx.Client.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: Optional[int] = None\u00b6\nMaximum number of tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-2", "text": "Holds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'gpt-3.5-turbo' (alias 'model')\u00b6\nModel name to use.\nparam model_version: str = ''\u00b6\nLegacy, for openai<1.0.0 support.\nparam n: int = 1\u00b6\nNumber of chat completions to generate for each prompt.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Union[str, None] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var AZURE_OPENAI_API_KEY if not provided.\nparam openai_api_type: str = ''\u00b6\nLegacy, for openai<1.0.0 support.\nparam openai_api_version: str = '' (alias 'api_version')\u00b6\nAutomatically inferred from env var OPENAI_API_VERSION if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-3", "text": "The model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nparam validate_base_url: bool = True\u00b6\nFor backwards compatibility. If legacy val openai_api_base is passed in, try to\ninfer if it is a base_url or azure_endpoint and update accordingly.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-4", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-5", "text": "async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-6", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-7", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nbind_functions(functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]], function_call: Optional[str] = None, **kwargs: Any) \u2192 Runnable[Union[PromptValue, str, List[BaseMessage]], BaseMessage]\u00b6\nBind functions (and other objects) to this chat model.\nParameters\nfunctions \u2013 A list of function definitions to bind to this chat model.\nCan be  a dictionary, pydantic model, or callable. Pydantic\nmodels and callables will be automatically converted to\ntheir schema dictionary representation.\nfunction_call \u2013 Which function to require the model to call.\nMust be the name of the single provided function or\n\u201cauto\u201d to automatically determine which function to call\n(if any).\nkwargs \u2013 Any additional parameters to pass to the\nRunnable constructor.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\ncompletion_with_retry(run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any\u00b6\nUse tenacity to retry the completion call.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-8", "text": "The type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-9", "text": "Returns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-10", "text": "to the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nCalculate num tokens for gpt-3.5-turbo and gpt-4 with tiktoken package.\nOfficial documentation: https://github.com/openai/openai-cookbook/blob/\nmain/examples/How_to_format_inputs_to_ChatGPT_models.ipynb\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-11", "text": "Runnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nGet the tokens present in the text with tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this model can be serialized by Langchain.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-12", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-13", "text": "Pass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-14", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "50d1a460c5aa-15", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using AzureChatOpenAI\u00b6\nAzure\nAzure OpenAI", "source": "lang/api.python.langchain.com/en/latest/chat_models/langchain.chat_models.azure_openai.AzureChatOpenAI.html"}
{"id": "a784db12ddd4-0", "text": "langchain.chat_loaders.imessage.IMessageChatLoader\u00b6\nclass langchain.chat_loaders.imessage.IMessageChatLoader(path: Optional[Union[str, Path]] = None)[source]\u00b6\nLoad chat sessions from the iMessage chat.db SQLite file.\nIt only works on macOS when you have iMessage enabled and have the chat.db file.\nThe chat.db file is likely located at ~/Library/Messages/chat.db. However, your\nterminal may not have permission to access this file. To resolve this, you can\ncopy the file to a different location, change the permissions of the file, or\ngrant full disk access for your terminal emulator\nin System Settings > Security and Privacy > Full Disk Access.\nInitialize the IMessageChatLoader.\nParameters\npath (str or Path, optional) \u2013 Path to the chat.db SQLite file.\nDefaults to None, in which case the default path\n~/Library/Messages/chat.db will be used.\nMethods\n__init__([path])\nInitialize the IMessageChatLoader.\nlazy_load()\nLazy load the chat sessions from the iMessage chat.db and yield them in the required format.\nload()\nEagerly load the chat sessions into memory.\n__init__(path: Optional[Union[str, Path]] = None)[source]\u00b6\nInitialize the IMessageChatLoader.\nParameters\npath (str or Path, optional) \u2013 Path to the chat.db SQLite file.\nDefaults to None, in which case the default path\n~/Library/Messages/chat.db will be used.\nlazy_load() \u2192 Iterator[ChatSession][source]\u00b6\nLazy load the chat sessions from the iMessage chat.db\nand yield them in the required format.\nYields\nChatSession \u2013 Loaded chat session.\nload() \u2192 List[ChatSession]\u00b6\nEagerly load the chat sessions into memory.\nExamples using IMessageChatLoader\u00b6\niMessage", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.imessage.IMessageChatLoader.html"}
{"id": "8cb9e8b0278a-0", "text": "langchain.chat_loaders.utils.merge_chat_runs_in_session\u00b6\nlangchain.chat_loaders.utils.merge_chat_runs_in_session(chat_session: ChatSession, delimiter: str = '\\n\\n') \u2192 ChatSession[source]\u00b6\nMerge chat runs together in a chat session.\nA chat run is a sequence of messages from the same sender.\nParameters\nchat_session \u2013 A chat session.\nReturns\nA chat session with merged chat runs.", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.utils.merge_chat_runs_in_session.html"}
{"id": "a320ebde5e83-0", "text": "langchain.chat_loaders.facebook_messenger.SingleFileFacebookMessengerChatLoader\u00b6\nclass langchain.chat_loaders.facebook_messenger.SingleFileFacebookMessengerChatLoader(path: Union[Path, str])[source]\u00b6\nLoad Facebook Messenger chat data from a single file.\nParameters\npath (Union[Path, str]) \u2013 The path to the chat file.\npath\u00b6\nThe path to the chat file.\nType\nPath\nMethods\n__init__(path)\nlazy_load()\nLazy loads the chat data from the file.\nload()\nEagerly load the chat sessions into memory.\n__init__(path: Union[Path, str]) \u2192 None[source]\u00b6\nlazy_load() \u2192 Iterator[ChatSession][source]\u00b6\nLazy loads the chat data from the file.\nYields\nChatSession \u2013 A chat session containing the loaded messages.\nload() \u2192 List[ChatSession]\u00b6\nEagerly load the chat sessions into memory.\nExamples using SingleFileFacebookMessengerChatLoader\u00b6\nFacebook Messenger", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.facebook_messenger.SingleFileFacebookMessengerChatLoader.html"}
{"id": "a6e14632bc6f-0", "text": "langchain.chat_loaders.gmail.GMailLoader\u00b6\nclass langchain.chat_loaders.gmail.GMailLoader(creds: Any, n: int = 100, raise_error: bool = False)[source]\u00b6\nLoad data from GMail.\nThere are many ways you could want to load data from GMail.\nThis loader is currently fairly opinionated in how to do so.\nThe way it does it is it first looks for all messages that you have sent.\nIt then looks for messages where you are responding to a previous email.\nIt then fetches that previous email, and creates a training example\nof that email, followed by your email.\nNote that there are clear limitations here. For example,\nall examples created are only looking at the previous email for context.\nTo use:\nSet up a Google Developer Account:Go to the Google Developer Console, create a project,\nand enable the Gmail API for that project.\nThis will give you a credentials.json file that you\u2019ll need later.\nMethods\n__init__(creds[,\u00a0n,\u00a0raise_error])\nlazy_load()\nLazy load the chat sessions.\nload()\nEagerly load the chat sessions into memory.\n__init__(creds: Any, n: int = 100, raise_error: bool = False) \u2192 None[source]\u00b6\nlazy_load() \u2192 Iterator[ChatSession][source]\u00b6\nLazy load the chat sessions.\nload() \u2192 List[ChatSession]\u00b6\nEagerly load the chat sessions into memory.\nExamples using GMailLoader\u00b6\nGMail", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.gmail.GMailLoader.html"}
{"id": "5873ffb75469-0", "text": "langchain.chat_loaders.telegram.TelegramChatLoader\u00b6\nclass langchain.chat_loaders.telegram.TelegramChatLoader(path: Union[str, Path])[source]\u00b6\nLoad telegram conversations to LangChain chat messages.\nTo export, use the Telegram Desktop app from\nhttps://desktop.telegram.org/, select a conversation, click the three dots\nin the top right corner, and select \u201cExport chat history\u201d. Then select\n\u201cMachine-readable JSON\u201d (preferred) to export. Note: the \u2018lite\u2019 versions of\nthe desktop app (like \u201cTelegram for MacOS\u201d) do not support exporting chat\nhistory.\nInitialize the TelegramChatLoader.\nParameters\npath (Union[str, Path]) \u2013 Path to the exported Telegram chat zip,\ndirectory, json, or HTML file.\nMethods\n__init__(path)\nInitialize the TelegramChatLoader.\nlazy_load()\nLazy load the messages from the chat file and yield them in as chat sessions.\nload()\nEagerly load the chat sessions into memory.\n__init__(path: Union[str, Path])[source]\u00b6\nInitialize the TelegramChatLoader.\nParameters\npath (Union[str, Path]) \u2013 Path to the exported Telegram chat zip,\ndirectory, json, or HTML file.\nlazy_load() \u2192 Iterator[ChatSession][source]\u00b6\nLazy load the messages from the chat file and yield them\nin as chat sessions.\nYields\nChatSession \u2013 The loaded chat session.\nload() \u2192 List[ChatSession]\u00b6\nEagerly load the chat sessions into memory.\nExamples using TelegramChatLoader\u00b6\nTelegram", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.telegram.TelegramChatLoader.html"}
{"id": "040a03f9d70a-0", "text": "langchain.chat_loaders.slack.SlackChatLoader\u00b6\nclass langchain.chat_loaders.slack.SlackChatLoader(path: Union[str, Path])[source]\u00b6\nLoad Slack conversations from a dump zip file.\nInitialize the chat loader with the path to the exported Slack dump zip file.\nParameters\npath \u2013 Path to the exported Slack dump zip file.\nMethods\n__init__(path)\nInitialize the chat loader with the path to the exported Slack dump zip file.\nlazy_load()\nLazy load the chat sessions from the Slack dump file and yield them in the required format.\nload()\nEagerly load the chat sessions into memory.\n__init__(path: Union[str, Path])[source]\u00b6\nInitialize the chat loader with the path to the exported Slack dump zip file.\nParameters\npath \u2013 Path to the exported Slack dump zip file.\nlazy_load() \u2192 Iterator[ChatSession][source]\u00b6\nLazy load the chat sessions from the Slack dump file and yield them\nin the required format.\nReturns\nIterator of chat sessions containing messages.\nload() \u2192 List[ChatSession]\u00b6\nEagerly load the chat sessions into memory.\nExamples using SlackChatLoader\u00b6\nSlack", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.slack.SlackChatLoader.html"}
{"id": "89bcaa648e1c-0", "text": "langchain.chat_loaders.whatsapp.WhatsAppChatLoader\u00b6\nclass langchain.chat_loaders.whatsapp.WhatsAppChatLoader(path: str)[source]\u00b6\nLoad WhatsApp conversations from a dump zip file or directory.\nInitialize the WhatsAppChatLoader.\nParameters\npath (str) \u2013 Path to the exported WhatsApp chat\nzip directory, folder, or file.\nTo generate the dump, open the chat, click the three dots in the top\nright corner, and select \u201cMore\u201d. Then select \u201cExport chat\u201d and\nchoose \u201cWithout media\u201d.\nMethods\n__init__(path)\nInitialize the WhatsAppChatLoader.\nlazy_load()\nLazy load the messages from the chat file and yield them as chat sessions.\nload()\nEagerly load the chat sessions into memory.\n__init__(path: str)[source]\u00b6\nInitialize the WhatsAppChatLoader.\nParameters\npath (str) \u2013 Path to the exported WhatsApp chat\nzip directory, folder, or file.\nTo generate the dump, open the chat, click the three dots in the top\nright corner, and select \u201cMore\u201d. Then select \u201cExport chat\u201d and\nchoose \u201cWithout media\u201d.\nlazy_load() \u2192 Iterator[ChatSession][source]\u00b6\nLazy load the messages from the chat file and yield\nthem as chat sessions.\nYields\nIterator[ChatSession] \u2013 The loaded chat sessions.\nload() \u2192 List[ChatSession]\u00b6\nEagerly load the chat sessions into memory.\nExamples using WhatsAppChatLoader\u00b6\nWhatsApp\nWhatsApp Chat", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.whatsapp.WhatsAppChatLoader.html"}
{"id": "e43afedd7eb3-0", "text": "langchain.chat_loaders.facebook_messenger.FolderFacebookMessengerChatLoader\u00b6\nclass langchain.chat_loaders.facebook_messenger.FolderFacebookMessengerChatLoader(path: Union[str, Path])[source]\u00b6\nLoad Facebook Messenger chat data from a folder.\nParameters\npath (Union[str, Path]) \u2013 The path to the directory\ncontaining the chat files.\npath\u00b6\nThe path to the directory containing the chat files.\nType\nPath\nMethods\n__init__(path)\nlazy_load()\nLazy loads the chat data from the folder.\nload()\nEagerly load the chat sessions into memory.\n__init__(path: Union[str, Path]) \u2192 None[source]\u00b6\nlazy_load() \u2192 Iterator[ChatSession][source]\u00b6\nLazy loads the chat data from the folder.\nYields\nChatSession \u2013 A chat session containing the loaded messages.\nload() \u2192 List[ChatSession]\u00b6\nEagerly load the chat sessions into memory.\nExamples using FolderFacebookMessengerChatLoader\u00b6\nFacebook Messenger\nChat loaders", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.facebook_messenger.FolderFacebookMessengerChatLoader.html"}
{"id": "db0b9c1afb76-0", "text": "langchain.chat_loaders.utils.map_ai_messages_in_session\u00b6\nlangchain.chat_loaders.utils.map_ai_messages_in_session(chat_sessions: ChatSession, sender: str) \u2192 ChatSession[source]\u00b6\nConvert messages from the specified \u2018sender\u2019 to AI messages.\nThis is useful for fine-tuning the AI to adapt to your voice.", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.utils.map_ai_messages_in_session.html"}
{"id": "68a57d230eb4-0", "text": "langchain.chat_loaders.base.BaseChatLoader\u00b6\nclass langchain.chat_loaders.base.BaseChatLoader[source]\u00b6\nBase class for chat loaders.\nMethods\n__init__()\nlazy_load()\nLazy load the chat sessions.\nload()\nEagerly load the chat sessions into memory.\n__init__()\u00b6\nabstract lazy_load() \u2192 Iterator[ChatSession][source]\u00b6\nLazy load the chat sessions.\nload() \u2192 List[ChatSession][source]\u00b6\nEagerly load the chat sessions into memory.", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.base.BaseChatLoader.html"}
{"id": "abeafee5c022-0", "text": "langchain.chat_loaders.utils.merge_chat_runs\u00b6\nlangchain.chat_loaders.utils.merge_chat_runs(chat_sessions: Iterable[ChatSession]) \u2192 Iterator[ChatSession][source]\u00b6\nMerge chat runs together.\nA chat run is a sequence of messages from the same sender.\nParameters\nchat_sessions \u2013 A list of chat sessions.\nReturns\nA list of chat sessions with merged chat runs.\nExamples using merge_chat_runs\u00b6\nFacebook Messenger\nSlack\nWhatsApp\niMessage\nTelegram\nDiscord", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.utils.merge_chat_runs.html"}
{"id": "66c5516fabd9-0", "text": "langchain.chat_loaders.utils.map_ai_messages\u00b6\nlangchain.chat_loaders.utils.map_ai_messages(chat_sessions: Iterable[ChatSession], sender: str) \u2192 Iterator[ChatSession][source]\u00b6\nConvert messages from the specified \u2018sender\u2019 to AI messages.\nThis is useful for fine-tuning the AI to adapt to your voice.\nExamples using map_ai_messages\u00b6\nFacebook Messenger\nGMail\nSlack\nWhatsApp\niMessage\nTelegram\nDiscord", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.utils.map_ai_messages.html"}
{"id": "0f64d3ee668c-0", "text": "langchain.chat_loaders.langsmith.LangSmithDatasetChatLoader\u00b6\nclass langchain.chat_loaders.langsmith.LangSmithDatasetChatLoader(*, dataset_name: str, client: Optional['Client'] = None)[source]\u00b6\nLoad chat sessions from a LangSmith dataset with the \u201cchat\u201d data type.\ndataset_name\u00b6\nThe name of the LangSmith dataset.\nType\nstr\nclient\u00b6\nInstance of LangSmith client for fetching data.\nType\nClient\nInitialize a new LangSmithChatDatasetLoader instance.\nParameters\ndataset_name \u2013 The name of the LangSmith dataset.\nclient \u2013 An instance of LangSmith client; if not provided,\na new client instance will be created.\nMethods\n__init__(*,\u00a0dataset_name[,\u00a0client])\nInitialize a new LangSmithChatDatasetLoader instance.\nlazy_load()\nLazy load the chat sessions from the specified LangSmith dataset.\nload()\nEagerly load the chat sessions into memory.\n__init__(*, dataset_name: str, client: Optional['Client'] = None)[source]\u00b6\nInitialize a new LangSmithChatDatasetLoader instance.\nParameters\ndataset_name \u2013 The name of the LangSmith dataset.\nclient \u2013 An instance of LangSmith client; if not provided,\na new client instance will be created.\nlazy_load() \u2192 Iterator[ChatSession][source]\u00b6\nLazy load the chat sessions from the specified LangSmith dataset.\nThis method fetches the chat data from the dataset and\nconverts each data point to chat sessions on-the-fly,\nyielding one session at a time.\nReturns\nIterator of chat sessions containing messages.\nload() \u2192 List[ChatSession]\u00b6\nEagerly load the chat sessions into memory.", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.langsmith.LangSmithDatasetChatLoader.html"}
{"id": "8202a5fb4333-0", "text": "langchain.chat_loaders.langsmith.LangSmithRunChatLoader\u00b6\nclass langchain.chat_loaders.langsmith.LangSmithRunChatLoader(runs: Iterable[Union[str, Run]], client: Optional['Client'] = None)[source]\u00b6\nLoad chat sessions from a list of LangSmith \u201cllm\u201d runs.\nruns\u00b6\nThe list of LLM run IDs or run objects.\nType\nIterable[Union[str, Run]]\nclient\u00b6\nInstance of LangSmith client for fetching data.\nType\nClient\nInitialize a new LangSmithRunChatLoader instance.\nParameters\nruns \u2013 List of LLM run IDs or run objects.\nclient \u2013 An instance of LangSmith client, if not provided,\na new client instance will be created.\nMethods\n__init__(runs[,\u00a0client])\nInitialize a new LangSmithRunChatLoader instance.\nlazy_load()\nLazy load the chat sessions from the iterable of run IDs.\nload()\nEagerly load the chat sessions into memory.\n__init__(runs: Iterable[Union[str, Run]], client: Optional['Client'] = None)[source]\u00b6\nInitialize a new LangSmithRunChatLoader instance.\nParameters\nruns \u2013 List of LLM run IDs or run objects.\nclient \u2013 An instance of LangSmith client, if not provided,\na new client instance will be created.\nlazy_load() \u2192 Iterator[ChatSession][source]\u00b6\nLazy load the chat sessions from the iterable of run IDs.\nThis method fetches the runs and converts them to chat sessions on-the-fly,\nyielding one session at a time.\nReturns\nIterator of chat sessions containing messages.\nload() \u2192 List[ChatSession]\u00b6\nEagerly load the chat sessions into memory.", "source": "lang/api.python.langchain.com/en/latest/chat_loaders/langchain.chat_loaders.langsmith.LangSmithRunChatLoader.html"}
{"id": "0305acca9815-0", "text": "langchain_experimental.rl_chain.base.embed_dict_type\u00b6\nlangchain_experimental.rl_chain.base.embed_dict_type(item: Dict, model: Any) \u2192 Dict[str, Any][source]\u00b6\nHelper function to embed a dictionary item.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.embed_dict_type.html"}
{"id": "262a0cb7d104-0", "text": "langchain_experimental.rl_chain.pick_best_chain.PickBestSelected\u00b6\nclass langchain_experimental.rl_chain.pick_best_chain.PickBestSelected(index: Optional[int] = None, probability: Optional[float] = None, score: Optional[float] = None)[source]\u00b6\nAttributes\nindex\nprobability\nscore\nMethods\n__init__([index,\u00a0probability,\u00a0score])\n__init__(index: Optional[int] = None, probability: Optional[float] = None, score: Optional[float] = None)[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBestSelected.html"}
{"id": "eae2e12d96b2-0", "text": "langchain_experimental.rl_chain.base.ToSelectFrom\u00b6\nlangchain_experimental.rl_chain.base.ToSelectFrom(anything: Any) \u2192 _ToSelectFrom[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.ToSelectFrom.html"}
{"id": "aee80cad87de-0", "text": "langchain_experimental.rl_chain.base.get_based_on_and_to_select_from\u00b6\nlangchain_experimental.rl_chain.base.get_based_on_and_to_select_from(inputs: Dict[str, Any]) \u2192 Tuple[Dict, Dict][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.get_based_on_and_to_select_from.html"}
{"id": "940acd484191-0", "text": "langchain_experimental.rl_chain.pick_best_chain.PickBest\u00b6\nclass langchain_experimental.rl_chain.pick_best_chain.PickBest[source]\u00b6\nBases: RLChain[PickBestEvent]\nPickBest is a class designed to leverage the Vowpal Wabbit (VW) model for reinforcement learning with a context, with the goal of modifying the prompt before the LLM call.\nEach invocation of the chain\u2019s run() method should be equipped with a set of potential actions (ToSelectFrom) and will result in the selection of a specific action based on the BasedOn input. This chosen action then informs the LLM (Language Model) prompt for the subsequent response generation.\nThe standard operation flow of this Chain includes:\nThe Chain is invoked with inputs containing the BasedOn criteria and a list of potential actions (ToSelectFrom).\nAn action is selected based on the BasedOn input.\nThe LLM is called with the dynamic prompt, producing a response.\nIf a selection_scorer is provided, it is used to score the selection.\nThe internal Vowpal Wabbit model is updated with the BasedOn input, the chosen ToSelectFrom action, and the resulting score from the scorer.\nThe final response is returned.\nExpected input dictionary format:\nAt least one variable encapsulated within BasedOn to serve as the selection criteria.\nA single list variable within ToSelectFrom, representing potential actions for the VW model. This list can take the form of:\nA list of strings, e.g., action = ToSelectFrom([\u201caction1\u201d, \u201caction2\u201d, \u201caction3\u201d])\nA list of list of strings e.g. action = ToSelectFrom([[\u201caction1\u201d, \u201canother identifier of action1\u201d], [\u201caction2\u201d, \u201canother identifier of action2\u201d]])", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-1", "text": "A list of dictionaries, where each dictionary represents an action with namespace names as keys and corresponding action strings as values. For instance, action = ToSelectFrom([{\u201cnamespace1\u201d: [\u201caction1\u201d, \u201canother identifier of action1\u201d], \u201cnamespace2\u201d: \u201caction2\u201d}, {\u201cnamespace1\u201d: \u201caction3\u201d, \u201cnamespace2\u201d: \u201caction4\u201d}]).\nExtends:RLChain\nfeature_embedder\u00b6\nIs an advanced attribute. Responsible for embedding the BasedOn and ToSelectFrom inputs. If omitted, a default embedder is utilized.\nType\nPickBestFeatureEmbedder, optional\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam active_policy: Policy = <langchain_experimental.rl_chain.base.RLChain._NoOpPolicy object>\u00b6\nparam auto_embed: bool = False\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm_chain: Chain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-2", "text": "for the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam metrics: Optional[Union[MetricsTrackerRollingWindow, MetricsTrackerAverage]] = None\u00b6\nparam prompt: BasePromptTemplate [Required]\u00b6\nparam selection_scorer: Union[SelectionScorer, None] = None\u00b6\nparam selection_scorer_activated: bool = True\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-3", "text": "Chain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-4", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nactivate_selection_scorer() \u2192 None\u00b6\nActivates the selection scorer, meaning that the chain will attempt to use the selection scorer to score responses.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-5", "text": "async ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-6", "text": "directly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-7", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-8", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndeactivate_selection_scorer() \u2192 None\u00b6\nDeactivates the selection scorer, meaning that the chain will no longer attempt to use the selection scorer to score responses.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-9", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: ~langchain.schema.language_model.BaseLanguageModel, prompt: ~langchain.schema.prompt_template.BasePromptTemplate, selection_scorer: ~typing.Union[~langchain_experimental.rl_chain.base.AutoSelectionScorer, object] = <object object>, **kwargs: ~typing.Any) \u2192 PickBest[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-10", "text": "Returns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-11", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-12", "text": "The main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nsave_progress() \u2192 None\u00b6\nThis function should be called to save the state of the learned policy model.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-13", "text": "This function should be called to save the state of the learned policy model.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nupdate_with_delayed_score(score: float, chain_response: Dict[str, Any], force_score: bool = False) \u2192 None\u00b6\nUpdates the learned policy with the score provided.\nWill raise an error if selection_scorer is set, and force_score=True was not provided during the method call\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-14", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "940acd484191-15", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nExpect input key.\n:meta private:\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBest.html"}
{"id": "9c69c7e0334a-0", "text": "langchain_experimental.rl_chain.base.Policy\u00b6\nclass langchain_experimental.rl_chain.base.Policy(**kwargs: Any)[source]\u00b6\nMethods\n__init__(**kwargs)\nlearn(event)\nlog(event)\npredict(event)\nsave()\n__init__(**kwargs: Any)[source]\u00b6\nabstract learn(event: TEvent) \u2192 None[source]\u00b6\nabstract log(event: TEvent) \u2192 None[source]\u00b6\nabstract predict(event: TEvent) \u2192 Any[source]\u00b6\nsave() \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.Policy.html"}
{"id": "3e1fcaaaa373-0", "text": "langchain_experimental.rl_chain.base.VwPolicy\u00b6\nclass langchain_experimental.rl_chain.base.VwPolicy(model_repo: ModelRepository, vw_cmd: List[str], feature_embedder: Embedder, vw_logger: VwLogger, *args: Any, **kwargs: Any)[source]\u00b6\nMethods\n__init__(model_repo,\u00a0vw_cmd,\u00a0...)\nlearn(event)\nlog(event)\npredict(event)\nsave()\n__init__(model_repo: ModelRepository, vw_cmd: List[str], feature_embedder: Embedder, vw_logger: VwLogger, *args: Any, **kwargs: Any)[source]\u00b6\nlearn(event: TEvent) \u2192 None[source]\u00b6\nlog(event: TEvent) \u2192 None[source]\u00b6\npredict(event: TEvent) \u2192 Any[source]\u00b6\nsave() \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.VwPolicy.html"}
{"id": "d653fe19cee9-0", "text": "langchain_experimental.rl_chain.base.prepare_inputs_for_autoembed\u00b6\nlangchain_experimental.rl_chain.base.prepare_inputs_for_autoembed(inputs: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\ngo over all the inputs and if something is either wrapped in _ToSelectFrom or _BasedOn, and if their inner values are not already _Embed,\nthen wrap them in EmbedAndKeep while retaining their _ToSelectFrom or _BasedOn status", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.prepare_inputs_for_autoembed.html"}
{"id": "29844a900e07-0", "text": "langchain_experimental.rl_chain.model_repository.ModelRepository\u00b6\nclass langchain_experimental.rl_chain.model_repository.ModelRepository(folder: Union[str, PathLike], with_history: bool = True, reset: bool = False)[source]\u00b6\nMethods\n__init__(folder[,\u00a0with_history,\u00a0reset])\nget_tag()\nhas_history()\nload(commandline)\nsave(workspace)\n__init__(folder: Union[str, PathLike], with_history: bool = True, reset: bool = False)[source]\u00b6\nget_tag() \u2192 str[source]\u00b6\nhas_history() \u2192 bool[source]\u00b6\nload(commandline: List[str]) \u2192 vw.Workspace[source]\u00b6\nsave(workspace: vw.Workspace) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.model_repository.ModelRepository.html"}
{"id": "c9b8cf473fcd-0", "text": "langchain_experimental.rl_chain.pick_best_chain.PickBestRandomPolicy\u00b6\nclass langchain_experimental.rl_chain.pick_best_chain.PickBestRandomPolicy(feature_embedder: Embedder, **kwargs: Any)[source]\u00b6\nMethods\n__init__(feature_embedder,\u00a0**kwargs)\nlearn(event)\nlog(event)\npredict(event)\nsave()\n__init__(feature_embedder: Embedder, **kwargs: Any)[source]\u00b6\nlearn(event: PickBestEvent) \u2192 None[source]\u00b6\nlog(event: PickBestEvent) \u2192 None[source]\u00b6\npredict(event: PickBestEvent) \u2192 List[Tuple[int, float]][source]\u00b6\nsave() \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBestRandomPolicy.html"}
{"id": "7a9b0eec93c5-0", "text": "langchain_experimental.rl_chain.base.stringify_embedding\u00b6\nlangchain_experimental.rl_chain.base.stringify_embedding(embedding: List) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.stringify_embedding.html"}
{"id": "9aa4eeaa2394-0", "text": "langchain_experimental.rl_chain.base.Selected\u00b6\nclass langchain_experimental.rl_chain.base.Selected[source]\u00b6\nMethods\n__init__()\n__init__()\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.Selected.html"}
{"id": "3528c277ac77-0", "text": "langchain_experimental.rl_chain.base.parse_lines\u00b6\nlangchain_experimental.rl_chain.base.parse_lines(parser: vw.TextFormatParser, input_str: str) \u2192 List['vw.Example'][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.parse_lines.html"}
{"id": "e718f1d80b16-0", "text": "langchain_experimental.rl_chain.metrics.MetricsTrackerRollingWindow\u00b6\nclass langchain_experimental.rl_chain.metrics.MetricsTrackerRollingWindow(window_size: int, step: int)[source]\u00b6\nAttributes\nscore\nMethods\n__init__(window_size,\u00a0step)\non_decision()\non_feedback(value)\nto_pandas()\n__init__(window_size: int, step: int)[source]\u00b6\non_decision() \u2192 None[source]\u00b6\non_feedback(value: float) \u2192 None[source]\u00b6\nto_pandas() \u2192 pd.DataFrame[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.metrics.MetricsTrackerRollingWindow.html"}
{"id": "384d38dbb928-0", "text": "langchain_experimental.rl_chain.metrics.MetricsTrackerAverage\u00b6\nclass langchain_experimental.rl_chain.metrics.MetricsTrackerAverage(step: int)[source]\u00b6\nAttributes\nscore\nMethods\n__init__(step)\non_decision()\non_feedback(score)\nto_pandas()\n__init__(step: int)[source]\u00b6\non_decision() \u2192 None[source]\u00b6\non_feedback(score: float) \u2192 None[source]\u00b6\nto_pandas() \u2192 pd.DataFrame[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.metrics.MetricsTrackerAverage.html"}
{"id": "a55edf129336-0", "text": "langchain_experimental.rl_chain.base.BasedOn\u00b6\nlangchain_experimental.rl_chain.base.BasedOn(anything: Any) \u2192 _BasedOn[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.BasedOn.html"}
{"id": "52b364e26b2f-0", "text": "langchain_experimental.rl_chain.pick_best_chain.PickBestFeatureEmbedder\u00b6\nclass langchain_experimental.rl_chain.pick_best_chain.PickBestFeatureEmbedder(auto_embed: bool, model: Optional[Any] = None, *args: Any, **kwargs: Any)[source]\u00b6\nText Embedder class that embeds the BasedOn and ToSelectFrom inputs into a format that can be used by the learning policy\nmodel name\nThe type of embeddings to be used for feature representation. Defaults to BERT SentenceTransformer.\nType\nAny, optional\nMethods\n__init__(auto_embed[,\u00a0model])\nformat(event)\nformat_auto_embed_off(event)\nConverts the BasedOn and ToSelectFrom into a format that can be used by VW\nformat_auto_embed_on(event)\nget_context_and_action_embeddings(event)\nget_indexed_dot_product(context_emb,\u00a0action_embs)\nget_label(event)\n__init__(auto_embed: bool, model: Optional[Any] = None, *args: Any, **kwargs: Any)[source]\u00b6\nformat(event: PickBestEvent) \u2192 str[source]\u00b6\nformat_auto_embed_off(event: PickBestEvent) \u2192 str[source]\u00b6\nConverts the BasedOn and ToSelectFrom into a format that can be used by VW\nformat_auto_embed_on(event: PickBestEvent) \u2192 str[source]\u00b6\nget_context_and_action_embeddings(event: PickBestEvent) \u2192 tuple[source]\u00b6\nget_indexed_dot_product(context_emb: List, action_embs: List) \u2192 Dict[source]\u00b6\nget_label(event: PickBestEvent) \u2192 tuple[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBestFeatureEmbedder.html"}
{"id": "51ad3f944a36-0", "text": "langchain_experimental.rl_chain.vw_logger.VwLogger\u00b6\nclass langchain_experimental.rl_chain.vw_logger.VwLogger(path: Optional[Union[str, PathLike]])[source]\u00b6\nMethods\n__init__(path)\nlog(vw_ex)\nlogging_enabled()\n__init__(path: Optional[Union[str, PathLike]])[source]\u00b6\nlog(vw_ex: str) \u2192 None[source]\u00b6\nlogging_enabled() \u2192 bool[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.vw_logger.VwLogger.html"}
{"id": "a0b6520316a2-0", "text": "langchain_experimental.rl_chain.base.AutoSelectionScorer\u00b6\nclass langchain_experimental.rl_chain.base.AutoSelectionScorer[source]\u00b6\nBases: SelectionScorer[Event], BaseModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam llm_chain: langchain.chains.llm.LLMChain [Required]\u00b6\nparam prompt: Optional[langchain.schema.prompt_template.BasePromptTemplate] = None\u00b6\nparam scoring_criteria_template_str: Optional[str] = None\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.AutoSelectionScorer.html"}
{"id": "a0b6520316a2-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nstatic get_default_prompt() \u2192 ChatPromptTemplate[source]\u00b6\nstatic get_default_system_prompt() \u2192 SystemMessagePromptTemplate[source]\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.AutoSelectionScorer.html"}
{"id": "a0b6520316a2-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nscore_response(inputs: Dict[str, Any], llm_response: str, event: Event) \u2192 float[source]\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.AutoSelectionScorer.html"}
{"id": "9fb2f2cbc456-0", "text": "langchain_experimental.rl_chain.base.is_stringtype_instance\u00b6\nlangchain_experimental.rl_chain.base.is_stringtype_instance(item: Any) \u2192 bool[source]\u00b6\nHelper function to check if an item is a string.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.is_stringtype_instance.html"}
{"id": "620e00b2bebc-0", "text": "langchain_experimental.rl_chain.base.Embed\u00b6\nlangchain_experimental.rl_chain.base.Embed(anything: Any, keep: bool = False) \u2192 Any[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.Embed.html"}
{"id": "000fca84a00b-0", "text": "langchain_experimental.rl_chain.base.embed_list_type\u00b6\nlangchain_experimental.rl_chain.base.embed_list_type(item: list, model: Any, namespace: Optional[str] = None) \u2192 List[Dict[str, Union[str, List[str]]]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.embed_list_type.html"}
{"id": "6bfcced260ee-0", "text": "langchain_experimental.rl_chain.base.RLChain\u00b6\nclass langchain_experimental.rl_chain.base.RLChain[source]\u00b6\nBases: Chain, Generic[TEvent]\nThe RLChain class leverages the Vowpal Wabbit (VW) model as a learned policy for reinforcement learning.\n- llm_chain\nRepresents the underlying Language Model chain.\nType\nChain\n- prompt\nThe template for the base prompt.\nType\nBasePromptTemplate\n- selection_scorer\nScorer for the selection. Can be set to None.\nType\nUnion[SelectionScorer, None]\n- policy\nThe policy used by the chain to learn to populate a dynamic prompt.\nType\nOptional[Policy]\n- auto_embed\nDetermines if embedding should be automatic. Default is False.\nType\nbool\n- metrics\nTracker for metrics, can be set to None.\nType\nOptional[Union[MetricsTrackerRollingWindow, MetricsTrackerAverage]]\nInitialization Attributes:\nfeature_embedder (Embedder): Embedder used for the BasedOn and ToSelectFrom inputs.\nmodel_save_dir (str, optional): Directory for saving the VW model. Default is the current directory.\nreset_model (bool): If set to True, the model starts training from scratch. Default is False.\nvw_cmd (List[str], optional): Command line arguments for the VW model.\npolicy (Type[VwPolicy]): Policy used by the chain.\nvw_logs (Optional[Union[str, os.PathLike]]): Path for the VW logs.\nmetrics_step (int): Step for the metrics tracker. Default is -1. If set without metrics_window_size, average metrics will be tracked, otherwise rolling window metrics will be tracked.\nmetrics_window_size (int): Window size for the metrics tracker. Default is -1. If set, rolling window metrics will be tracked.\nNotes", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-1", "text": "Notes\nThe class initializes the VW model using the provided arguments. If selection_scorer is not provided, a warning is logged, indicating that no reinforcement learning will occur unless the update_with_delayed_score method is called.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam active_policy: Policy = <langchain_experimental.rl_chain.base.RLChain._NoOpPolicy object>\u00b6\nparam auto_embed: bool = False\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm_chain: Chain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam metrics: Optional[Union[MetricsTrackerRollingWindow, MetricsTrackerAverage]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-2", "text": "param prompt: BasePromptTemplate [Required]\u00b6\nparam selection_scorer: Union[SelectionScorer, None] = None\u00b6\nparam selection_scorer_activated: bool = True\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-3", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-4", "text": "returned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nactivate_selection_scorer() \u2192 None[source]\u00b6\nActivates the selection scorer, meaning that the chain will attempt to use the selection scorer to score responses.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-5", "text": "Convenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-6", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-7", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-8", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndeactivate_selection_scorer() \u2192 None[source]\u00b6\nDeactivates the selection scorer, meaning that the chain will no longer attempt to use the selection scorer to score responses.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-9", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-10", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nprep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-11", "text": "memory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-12", "text": "context = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nsave_progress() \u2192 None[source]\u00b6\nThis function should be called to save the state of the learned policy model.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nupdate_with_delayed_score(score: float, chain_response: Dict[str, Any], force_score: bool = False) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-13", "text": "Updates the learned policy with the score provided.\nWill raise an error if selection_scorer is set, and force_score=True was not provided during the method call\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-14", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_keys: List[str]\u00b6\nExpect input key.\n:meta private:\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "6bfcced260ee-15", "text": "For example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.RLChain.html"}
{"id": "1b186a0339cb-0", "text": "langchain_experimental.rl_chain.base.EmbedAndKeep\u00b6\nlangchain_experimental.rl_chain.base.EmbedAndKeep(anything: Any) \u2192 Any[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.EmbedAndKeep.html"}
{"id": "1d5ca4a23516-0", "text": "langchain_experimental.rl_chain.base.embed\u00b6\nlangchain_experimental.rl_chain.base.embed(to_embed: Union[str, _Embed, Dict, List[Union[str, _Embed]], List[Dict]], model: Any, namespace: Optional[str] = None) \u2192 List[Dict[str, Union[str, List[str]]]][source]\u00b6\nEmbeds the actions or context using the SentenceTransformer model (or a model that has an encode function)\nlangchain_experimental.rl_chain.base.to_embed\u00b6\n(Union[Union(str, _Embed(str)), Dict, List[Union(str, _Embed(str))], List[Dict]], required) The text to be embedded, either a string, a list of strings or a dictionary or a list of dictionaries.\nlangchain_experimental.rl_chain.base.namespace\u00b6\n(str, optional) The default namespace to use when dictionary or list of dictionaries not provided.\nlangchain_experimental.rl_chain.base.model\u00b6\n(Any, required) The model to use for embedding\nReturns\nA list of dictionaries where each dictionary has the namespace as the key and the embedded string as the value\nReturn type\nList[Dict[str, str]]", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.embed.html"}
{"id": "04257fc99cad-0", "text": "langchain_experimental.rl_chain.base.Event\u00b6\nclass langchain_experimental.rl_chain.base.Event(inputs: Dict[str, Any], selected: Optional[TSelected] = None)[source]\u00b6\nAttributes\ninputs\nselected\nMethods\n__init__(inputs[,\u00a0selected])\n__init__(inputs: Dict[str, Any], selected: Optional[TSelected] = None)[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.Event.html"}
{"id": "11ad6015ca22-0", "text": "langchain_experimental.rl_chain.base.embed_string_type\u00b6\nlangchain_experimental.rl_chain.base.embed_string_type(item: Union[str, _Embed], model: Any, namespace: Optional[str] = None) \u2192 Dict[str, Union[str, List[str]]][source]\u00b6\nHelper function to embed a string or an _Embed object.", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.embed_string_type.html"}
{"id": "a79f4e0f21c0-0", "text": "langchain_experimental.rl_chain.base.SelectionScorer\u00b6\nclass langchain_experimental.rl_chain.base.SelectionScorer[source]\u00b6\nBases: Generic[TEvent], ABC, BaseModel\nAbstract method to grade the chosen selection or the response of the llm\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.SelectionScorer.html"}
{"id": "a79f4e0f21c0-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.SelectionScorer.html"}
{"id": "a79f4e0f21c0-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nabstract score_response(inputs: Dict[str, Any], llm_response: str, event: TEvent) \u2192 float[source]\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.SelectionScorer.html"}
{"id": "1f857a3736a1-0", "text": "langchain_experimental.rl_chain.base.Embedder\u00b6\nclass langchain_experimental.rl_chain.base.Embedder(*args: Any, **kwargs: Any)[source]\u00b6\nMethods\n__init__(*args,\u00a0**kwargs)\nformat(event)\n__init__(*args: Any, **kwargs: Any)[source]\u00b6\nabstract format(event: TEvent) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.base.Embedder.html"}
{"id": "2ee58f334796-0", "text": "langchain_experimental.rl_chain.pick_best_chain.PickBestEvent\u00b6\nclass langchain_experimental.rl_chain.pick_best_chain.PickBestEvent(inputs: Dict[str, Any], to_select_from: Dict[str, Any], based_on: Dict[str, Any], selected: Optional[PickBestSelected] = None)[source]\u00b6\nAttributes\nMethods\n__init__(inputs,\u00a0to_select_from,\u00a0based_on[,\u00a0...])\n__init__(inputs: Dict[str, Any], to_select_from: Dict[str, Any], based_on: Dict[str, Any], selected: Optional[PickBestSelected] = None)[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/rl_chain/langchain_experimental.rl_chain.pick_best_chain.PickBestEvent.html"}
{"id": "8f43f39ee656-0", "text": "langchain_experimental.prompt_injection_identifier.hugging_face_identifier.HuggingFaceInjectionIdentifier\u00b6\nclass langchain_experimental.prompt_injection_identifier.hugging_face_identifier.HuggingFaceInjectionIdentifier[source]\u00b6\nBases: BaseTool\nTool that uses deberta-v3-base-injection to detect prompt injection attacks.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam args_schema: Optional[Type[BaseModel]] = None\u00b6\nPydantic model class to validate and parse the tool\u2019s input arguments.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated. Please use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to be called during tool execution.\nparam description: str = 'A wrapper around HuggingFace Prompt Injection security model. Useful for when you need to ensure that prompt is free of injection attacks. Input should be any message from the user.'\u00b6\nUsed to tell the model how/when/why to use the tool.\nYou can provide few-shot examples as a part of the description.\nparam handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False\u00b6\nHandle the content of the ToolException thrown.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the tool. Defaults to None\nThis metadata will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam model: Pipeline [Optional]\u00b6\nparam name: str = 'hugging_face_injection_identifier'\u00b6\nThe unique name of the tool that clearly communicates its purpose.\nparam return_direct: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompt_injection_identifier/langchain_experimental.prompt_injection_identifier.hugging_face_identifier.HuggingFaceInjectionIdentifier.html"}
{"id": "8f43f39ee656-1", "text": "param return_direct: bool = False\u00b6\nWhether to return the tool\u2019s output directly. Setting this to True means\nthat after the tool is called, the AgentExecutor will stop looping.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the tool. Defaults to None\nThese tags will be associated with each call to this tool,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a tool with its use case.\nparam verbose: bool = False\u00b6\nWhether to log the tool\u2019s progress.\n__call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 str\u00b6\nMake tool callable.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/prompt_injection_identifier/langchain_experimental.prompt_injection_identifier.hugging_face_identifier.HuggingFaceInjectionIdentifier.html"}
{"id": "8f43f39ee656-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/prompt_injection_identifier/langchain_experimental.prompt_injection_identifier.hugging_face_identifier.HuggingFaceInjectionIdentifier.html"}
{"id": "8f43f39ee656-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompt_injection_identifier/langchain_experimental.prompt_injection_identifier.hugging_face_identifier.HuggingFaceInjectionIdentifier.html"}
{"id": "8f43f39ee656-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nThe tool\u2019s input schema.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.", "source": "lang/api.python.langchain.com/en/latest/prompt_injection_identifier/langchain_experimental.prompt_injection_identifier.hugging_face_identifier.HuggingFaceInjectionIdentifier.html"}
{"id": "8f43f39ee656-5", "text": "Get the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, Dict], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Any\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/prompt_injection_identifier/langchain_experimental.prompt_injection_identifier.hugging_face_identifier.HuggingFaceInjectionIdentifier.html"}
{"id": "8f43f39ee656-6", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/prompt_injection_identifier/langchain_experimental.prompt_injection_identifier.hugging_face_identifier.HuggingFaceInjectionIdentifier.html"}
{"id": "8f43f39ee656-7", "text": "run(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 Any\u00b6\nRun the tool.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/prompt_injection_identifier/langchain_experimental.prompt_injection_identifier.hugging_face_identifier.HuggingFaceInjectionIdentifier.html"}
{"id": "8f43f39ee656-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/prompt_injection_identifier/langchain_experimental.prompt_injection_identifier.hugging_face_identifier.HuggingFaceInjectionIdentifier.html"}
{"id": "8f43f39ee656-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty args: dict\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_single_input: bool\u00b6\nWhether the tool only accepts a single input.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/prompt_injection_identifier/langchain_experimental.prompt_injection_identifier.hugging_face_identifier.HuggingFaceInjectionIdentifier.html"}
{"id": "d735943224a0-0", "text": "langchain.agents.output_parsers.self_ask.SelfAskOutputParser\u00b6\nclass langchain.agents.output_parsers.self_ask.SelfAskOutputParser[source]\u00b6\nBases: AgentOutputParser\nParses self-ask style LLM calls.\nExpects output to be in one of two formats.\nIf the output signals that an action should be taken,\nshould be in the below format. This will result in an AgentAction\nbeing returned.\n`\nThoughts go here...\nFollow up: what is the temperature in SF?\n`\nIf the output signals that a final answer should be given,\nshould be in the below format. This will result in an AgentFinish\nbeing returned.\n`\nThoughts go here...\nSo the final answer is: The temperature is 100 degrees\n`\nparam finish_string: str = 'So the final answer is: '\u00b6\nparam followups: Sequence[str] = ('Follow up:', 'Followup:')\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "d735943224a0-1", "text": "Subclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "d735943224a0-2", "text": "step, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "d735943224a0-3", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "d735943224a0-4", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "d735943224a0-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "d735943224a0-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "d735943224a0-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "d735943224a0-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "d735943224a0-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.self_ask.SelfAskOutputParser.html"}
{"id": "6afc2b6322b9-0", "text": "langchain.agents.output_parsers.openai_tools.OpenAIToolAgentAction\u00b6\nclass langchain.agents.output_parsers.openai_tools.OpenAIToolAgentAction[source]\u00b6\nBases: AgentActionMessageLog\nOverride init to support instantiation by position for backward compat.\nparam log: str [Required]\u00b6\nAdditional information to log about the action.\nThis log can be used in a few ways. First, it can be used to audit\nwhat exactly the LLM predicted to lead to this (tool, tool_input).\nSecond, it can be used in future iterations to show the LLMs prior\nthoughts. This is useful when (tool, tool_input) does not contain\nfull information about the LLM prediction (for example, any thought\nbefore the tool/tool_input).\nparam message_log: Sequence[BaseMessage] [Required]\u00b6\nSimilar to log, this can be used to pass along extra\ninformation about what exact messages were predicted by the LLM\nbefore parsing out the (tool, tool_input). This is again useful\nif (tool, tool_input) cannot be used to fully recreate the LLM\nprediction, and you need that LLM prediction (for future agent iteration).\nCompared to log, this is useful when the underlying LLM is a\nChatModel (and therefore returns messages rather than a string).\nparam tool: str [Required]\u00b6\nThe name of the Tool to execute.\nparam tool_call_id: str [Required]\u00b6\nTool call that this message is responding to.\nparam tool_input: Union[str, dict] [Required]\u00b6\nThe input to pass in to the Tool.\nparam type: Literal['AgentActionMessageLog'] = 'AgentActionMessageLog'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.OpenAIToolAgentAction.html"}
{"id": "6afc2b6322b9-1", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.OpenAIToolAgentAction.html"}
{"id": "6afc2b6322b9-2", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.OpenAIToolAgentAction.html"}
{"id": "6afc2b6322b9-3", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.OpenAIToolAgentAction.html"}
{"id": "40559f6609f4-0", "text": "langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser\u00b6\nclass langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser[source]\u00b6\nBases: AgentOutputParser\nParses a message into agent action/finish.\nIs meant to be used with OpenAI models, as it relies on the specific\nfunction_call parameter from OpenAI to convey what tools to use.\nIf a function_call parameter is passed, then that is used to get\nthe tool and tool input.\nIf one is not passed, then the AIMessage is assumed to be the final output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 Union[AgentAction, AgentFinish][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "40559f6609f4-1", "text": "Parse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "40559f6609f4-2", "text": "Subclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "40559f6609f4-3", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "40559f6609f4-4", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "40559f6609f4-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "40559f6609f4-6", "text": "The prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "40559f6609f4-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "40559f6609f4-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser.html"}
{"id": "f1f08eb2c0c8-0", "text": "langchain.agents.output_parsers.json.JSONAgentOutputParser\u00b6\nclass langchain.agents.output_parsers.json.JSONAgentOutputParser[source]\u00b6\nBases: AgentOutputParser\nParses tool invocations and final answers in JSON format.\nExpects output to be in one of two formats.\nIf the output signals that an action should be taken,\nshould be in the below format. This will result in an AgentAction\nbeing returned.\n```\n{\n\u201caction\u201d: \u201csearch\u201d,\n\u201caction_input\u201d: \u201c2+2\u201d\nIf the output signals that a final answer should be given,\nshould be in the below format. This will result in an AgentFinish\nbeing returned.\n```\n{\n\u201caction\u201d: \u201cFinal Answer\u201d,\n\u201caction_input\u201d: \u201c4\u201d\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "f1f08eb2c0c8-1", "text": "Parameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "f1f08eb2c0c8-2", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "f1f08eb2c0c8-3", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "f1f08eb2c0c8-4", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "f1f08eb2c0c8-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "f1f08eb2c0c8-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "f1f08eb2c0c8-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "f1f08eb2c0c8-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "f1f08eb2c0c8-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.json.JSONAgentOutputParser.html"}
{"id": "f3ad796ad9ca-0", "text": "langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser\u00b6\nclass langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser[source]\u00b6\nBases: AgentOutputParser\nParses ReAct-style LLM calls that have a single tool input.\nExpects output to be in one of two formats.\nIf the output signals that an action should be taken,\nshould be in the below format. This will result in an AgentAction\nbeing returned.\n`\nThought: agent thought here\nAction: search\nAction Input: what is the temperature in SF?\n`\nIf the output signals that a final answer should be given,\nshould be in the below format. This will result in an AgentFinish\nbeing returned.\n`\nThought: agent thought here\nFinal Answer: The temperature is 100 degrees\n`\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "f3ad796ad9ca-1", "text": "Parse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "f3ad796ad9ca-2", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "f3ad796ad9ca-3", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "f3ad796ad9ca-4", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "f3ad796ad9ca-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "f3ad796ad9ca-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "f3ad796ad9ca-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "f3ad796ad9ca-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "f3ad796ad9ca-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_single_input.ReActSingleInputOutputParser.html"}
{"id": "3339f048648b-0", "text": "langchain.agents.output_parsers.openai_tools.parse_ai_message_to_openai_tool_action\u00b6\nlangchain.agents.output_parsers.openai_tools.parse_ai_message_to_openai_tool_action(message: BaseMessage) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6\nParse an AI message potentially containing tool_calls.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.parse_ai_message_to_openai_tool_action.html"}
{"id": "fed50b40666d-0", "text": "langchain.agents.output_parsers.xml.XMLAgentOutputParser\u00b6\nclass langchain.agents.output_parsers.xml.XMLAgentOutputParser[source]\u00b6\nBases: AgentOutputParser\nParses tool invocations and final answers in XML format.\nExpects output to be in one of two formats.\nIf the output signals that an action should be taken,\nshould be in the below format. This will result in an AgentAction\nbeing returned.\n`\n<tool>search</tool>\n<tool_input>what is 2 + 2</tool_input>\n`\nIf the output signals that a final answer should be given,\nshould be in the below format. This will result in an AgentFinish\nbeing returned.\n`\n<final_answer>Foo</final_answer>\n`\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "fed50b40666d-1", "text": "Parameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "fed50b40666d-2", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "fed50b40666d-3", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "fed50b40666d-4", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "fed50b40666d-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "fed50b40666d-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "fed50b40666d-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "fed50b40666d-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "fed50b40666d-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.xml.XMLAgentOutputParser.html"}
{"id": "db4536a520c5-0", "text": "langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser\u00b6\nclass langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser[source]\u00b6\nBases: MultiActionAgentOutputParser\nParses a message into agent actions/finish.\nIs meant to be used with OpenAI models, as it relies on the specific\ntool_calls parameter from OpenAI to convey what tools to use.\nIf a tool_calls parameter is passed, then that is used to get\nthe tool names and tool inputs.\nIf one is not passed, then the AIMessage is assumed to be the final output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "db4536a520c5-1", "text": "Parse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "db4536a520c5-2", "text": "Subclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "db4536a520c5-3", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "db4536a520c5-4", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "db4536a520c5-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6\nParse text into agent actions/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 Union[List[AgentAction], AgentFinish][source]\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "db4536a520c5-6", "text": "The prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "db4536a520c5-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "db4536a520c5-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.openai_tools.OpenAIToolsAgentOutputParser.html"}
{"id": "b318815982c0-0", "text": "langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser\u00b6\nclass langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser[source]\u00b6\nBases: AgentOutputParser\nParses ReAct-style LLM calls that have a single tool input in json format.\nExpects output to be in one of two formats.\nIf the output signals that an action should be taken,\nshould be in the below format. This will result in an AgentAction\nbeing returned.\n`\nThought: agent thought here\nAction:\n`\n{\n\u201caction\u201d: \u201csearch\u201d,\n\u201caction_input\u201d: \u201cwhat is the temperature in SF\u201d\n```\nIf the output signals that a final answer should be given,\nshould be in the below format. This will result in an AgentFinish\nbeing returned.\n`\nThought: agent thought here\nFinal Answer: The temperature is 100 degrees\n`\nparam pattern = re.compile('^.*?`{3}(?:json)?\\\\n(.*?)`{3}.*?$', re.DOTALL)\u00b6\nRegex pattern to parse the output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "b318815982c0-1", "text": "Default implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "b318815982c0-2", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "b318815982c0-3", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "b318815982c0-4", "text": "Instructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "b318815982c0-5", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 Union[AgentAction, AgentFinish][source]\u00b6\nParse text into agent action/finish.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "b318815982c0-6", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "b318815982c0-7", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "b318815982c0-8", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "b318815982c0-9", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/agents.output_parsers/langchain.agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser.html"}
{"id": "d77c10d6ec3d-0", "text": "langchain.schema.callbacks.manager.trace_as_chain_group\u00b6\nlangchain.schema.callbacks.manager.trace_as_chain_group(group_name: str, callback_manager: Optional[CallbackManager] = None, *, inputs: Optional[Dict[str, Any]] = None, project_name: Optional[str] = None, example_id: Optional[Union[str, UUID]] = None, run_id: Optional[UUID] = None, tags: Optional[List[str]] = None) \u2192 Generator[CallbackManagerForChainGroup, None, None][source]\u00b6\nGet a callback manager for a chain group in a context manager.\nUseful for grouping different calls together as a single run even if\nthey aren\u2019t composed in a single chain.\nParameters\ngroup_name (str) \u2013 The name of the chain group.\ncallback_manager (CallbackManager, optional) \u2013 The callback manager to use.\ninputs (Dict[str, Any], optional) \u2013 The inputs to the chain group.\nproject_name (str, optional) \u2013 The name of the project.\nDefaults to None.\nexample_id (str or UUID, optional) \u2013 The ID of the example.\nDefaults to None.\nrun_id (UUID, optional) \u2013 The ID of the run.\ntags (List[str], optional) \u2013 The inheritable tags to apply to all runs.\nDefaults to None.\nNote: must have LANGCHAIN_TRACING_V2 env var set to true to see the trace in LangSmith.\nReturns\nThe callback manager for the chain group.\nReturn type\nCallbackManagerForChainGroup\nExample\nllm_input = \"Foo\"\nwith trace_as_chain_group(\"group_name\", inputs={\"input\": llm_input}) as manager:\n    # Use the callback manager for the chain group\n    res = llm.predict(llm_input, callbacks=manager)\n    manager.on_chain_end({\"output\": res})", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.trace_as_chain_group.html"}
{"id": "806cbac008e0-0", "text": "langchain.schema.runnable.utils.IsLocalDict\u00b6\nclass langchain.schema.runnable.utils.IsLocalDict(name: str, keys: Set[str])[source]\u00b6\nCheck if a name is a local dict.\nMethods\n__init__(name,\u00a0keys)\ngeneric_visit(node)\nCalled if no explicit visitor function exists for a node.\nvisit(node)\nVisit a node.\nvisit_Call(node)\nvisit_Constant(node)\nvisit_Subscript(node)\n__init__(name: str, keys: Set[str]) \u2192 None[source]\u00b6\ngeneric_visit(node)\u00b6\nCalled if no explicit visitor function exists for a node.\nvisit(node)\u00b6\nVisit a node.\nvisit_Call(node: Call) \u2192 Any[source]\u00b6\nvisit_Constant(node)\u00b6\nvisit_Subscript(node: Subscript) \u2192 Any[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.IsLocalDict.html"}
{"id": "649399f3430c-0", "text": "langchain.schema.callbacks.tracers.langchain.LangChainTracer\u00b6\nclass langchain.schema.callbacks.tracers.langchain.LangChainTracer(example_id: Optional[Union[str, UUID]] = None, project_name: Optional[str] = None, client: Optional[Client] = None, tags: Optional[List[str]] = None, use_threading: bool = True, **kwargs: Any)[source]\u00b6\nAn implementation of the SharedTracer that POSTS to the langchain endpoint.\nInitialize the LangChain tracer.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([example_id,\u00a0project_name,\u00a0client,\u00a0...])\nInitialize the LangChain tracer.\nget_run_url()\nGet the LangSmith root run URL\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0inputs])\nEnd a trace for a chain run.\non_chain_error(error,\u00a0*[,\u00a0inputs])\nHandle an error for a chain run.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nStart a trace for a chain run.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nStart a trace for an LLM run.\non_llm_end(response,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for an LLM run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain.LangChainTracer.html"}
{"id": "649399f3430c-1", "text": "End a trace for an LLM run.\non_llm_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for an LLM run.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nStart a trace for an LLM run.\non_retriever_end(documents,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for a tool run.\non_tool_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for a tool run.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nStart a trace for a tool run.\nwait_for_futures()\nWait for the given futures to complete.\n__init__(example_id: Optional[Union[str, UUID]] = None, project_name: Optional[str] = None, client: Optional[Client] = None, tags: Optional[List[str]] = None, use_threading: bool = True, **kwargs: Any) \u2192 None[source]\u00b6\nInitialize the LangChain tracer.\nget_run_url() \u2192 str[source]\u00b6\nGet the LangSmith root run URL", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain.LangChainTracer.html"}
{"id": "649399f3430c-2", "text": "get_run_url() \u2192 str[source]\u00b6\nGet the LangSmith root run URL\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, inputs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a chain run.\non_chain_error(error: BaseException, *, inputs: Optional[Dict[str, Any]] = None, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a chain run.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, run_type: Optional[str] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a chain run.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\nStart a trace for an LLM run.\non_llm_end(response: LLMResult, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain.LangChainTracer.html"}
{"id": "649399f3430c-3", "text": "End a trace for an LLM run.\non_llm_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for an LLM run.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Run\u00b6\nRun on new LLM token. Only available when streaming is enabled.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for an LLM run.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun on a retry event.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain.LangChainTracer.html"}
{"id": "649399f3430c-4", "text": "Run on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a tool run.\non_tool_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a tool run.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a tool run.\nwait_for_futures() \u2192 None[source]\u00b6\nWait for the given futures to complete.\nExamples using LangChainTracer\u00b6\nAsync API", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain.LangChainTracer.html"}
{"id": "e46e10139714-0", "text": "langchain.schema.callbacks.tracers.stdout.FunctionCallbackHandler\u00b6\nclass langchain.schema.callbacks.tracers.stdout.FunctionCallbackHandler(function: Callable[[str], None], **kwargs: Any)[source]\u00b6\nTracer that calls a function with a single str parameter.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nname\nraise_error\nrun_inline\nMethods\n__init__(function,\u00a0**kwargs)\nget_breadcrumbs(run)\nget_parents(run)\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0inputs])\nEnd a trace for a chain run.\non_chain_error(error,\u00a0*[,\u00a0inputs])\nHandle an error for a chain run.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nStart a trace for a chain run.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for an LLM run.\non_llm_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for an LLM run.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nStart a trace for an LLM run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.stdout.FunctionCallbackHandler.html"}
{"id": "e46e10139714-1", "text": "Start a trace for an LLM run.\non_retriever_end(documents,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for a tool run.\non_tool_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for a tool run.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nStart a trace for a tool run.\n__init__(function: Callable[[str], None], **kwargs: Any) \u2192 None[source]\u00b6\nget_breadcrumbs(run: Run) \u2192 str[source]\u00b6\nget_parents(run: Run) \u2192 List[Run][source]\u00b6\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, inputs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a chain run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.stdout.FunctionCallbackHandler.html"}
{"id": "e46e10139714-2", "text": "End a trace for a chain run.\non_chain_error(error: BaseException, *, inputs: Optional[Dict[str, Any]] = None, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a chain run.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, run_type: Optional[str] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a chain run.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for an LLM run.\non_llm_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for an LLM run.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Run\u00b6\nRun on new LLM token. Only available when streaming is enabled.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.stdout.FunctionCallbackHandler.html"}
{"id": "e46e10139714-3", "text": "Run on new LLM token. Only available when streaming is enabled.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for an LLM run.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a tool run.\non_tool_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a tool run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.stdout.FunctionCallbackHandler.html"}
{"id": "e46e10139714-4", "text": "Handle an error for a tool run.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a tool run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.stdout.FunctionCallbackHandler.html"}
{"id": "8482c4a99c14-0", "text": "langchain.schema.runnable.utils.get_function_first_arg_dict_keys\u00b6\nlangchain.schema.runnable.utils.get_function_first_arg_dict_keys(func: Callable) \u2192 Optional[List[str]][source]\u00b6\nGet the keys of the first argument of a function if it is a dict.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.get_function_first_arg_dict_keys.html"}
{"id": "8ba1b0ca347f-0", "text": "langchain.schema.callbacks.manager.AsyncParentRunManager\u00b6\nclass langchain.schema.callbacks.manager.AsyncParentRunManager(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nAsync Parent Run Manager.\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nMethods\n__init__(*,\u00a0run_id,\u00a0handlers,\u00a0...[,\u00a0...])\nInitialize the run manager.\nget_child([tag])\nGet a child callback manager.\nget_noop_manager()\nReturn a manager that doesn't perform any operations.\non_retry(retry_state,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when text is received.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncParentRunManager.html"}
{"id": "8ba1b0ca347f-1", "text": "on_text(text,\u00a0**kwargs)\nRun when text is received.\n__init__(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nget_child(tag: Optional[str] = None) \u2192 AsyncCallbackManager[source]\u00b6\nGet a child callback manager.\nParameters\ntag (str, optional) \u2013 The tag for the child callback manager.\nDefaults to None.\nReturns\nThe child callback manager.\nReturn type\nAsyncCallbackManager\nclassmethod get_noop_manager() \u2192 BRM\u00b6\nReturn a manager that doesn\u2019t perform any operations.\nReturns\nThe noop manager.\nReturn type\nBaseRunManager\nasync on_retry(retry_state: RetryCallState, **kwargs: Any) \u2192 None\u00b6\nRun on a retry event.\nasync on_text(text: str, **kwargs: Any) \u2192 Any\u00b6\nRun when text is received.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncParentRunManager.html"}
{"id": "8ba1b0ca347f-2", "text": "Run when text is received.\nParameters\ntext (str) \u2013 The received text.\nReturns\nThe result of the callback.\nReturn type\nAny", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncParentRunManager.html"}
{"id": "e84c2eea98ae-0", "text": "langchain.schema.output.ChatGenerationChunk\u00b6\nclass langchain.schema.output.ChatGenerationChunk[source]\u00b6\nBases: ChatGeneration\nA ChatGeneration chunk, which can be concatenated with otherChatGeneration chunks.\nmessage\u00b6\nThe message chunk output by the chat model.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam generation_info: Optional[Dict[str, Any]] = None\u00b6\nRaw response from the provider. May include things like the\nreason for finishing or token log probabilities.\nparam message: langchain.schema.messages.BaseMessageChunk [Required]\u00b6\nThe message output by the chat model.\nparam text: str = ''\u00b6\nSHOULD NOT BE SET DIRECTLY The text contents of the output message.\nparam type: Literal['ChatGenerationChunk'] = 'ChatGenerationChunk'\u00b6\nType is used exclusively for serialization purposes.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.ChatGenerationChunk.html"}
{"id": "e84c2eea98ae-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.ChatGenerationChunk.html"}
{"id": "e84c2eea98ae-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.ChatGenerationChunk.html"}
{"id": "82e88f71c59d-0", "text": "langchain.schema.runnable.utils.gated_coro\u00b6\nasync langchain.schema.runnable.utils.gated_coro(semaphore: Semaphore, coro: Coroutine) \u2192 Any[source]\u00b6\nRun a coroutine with a semaphore.\n:param semaphore: The semaphore to use.\n:param coro: The coroutine to run.\nReturns\nThe result of the coroutine.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.gated_coro.html"}
{"id": "54f7fb9158d6-0", "text": "langchain.schema.runnable.utils.indent_lines_after_first\u00b6\nlangchain.schema.runnable.utils.indent_lines_after_first(text: str, prefix: str) \u2192 str[source]\u00b6\nIndent all lines of text after the first line.\nParameters\ntext \u2013 The text to indent\nprefix \u2013 Used to determine the number of spaces to indent\nReturns\nThe indented text\nReturn type\nstr", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.indent_lines_after_first.html"}
{"id": "4ed11b473592-0", "text": "langchain.schema.callbacks.tracers.log_stream.LogEntry\u00b6\nclass langchain.schema.callbacks.tracers.log_stream.LogEntry[source]\u00b6\nA single entry in the run log.\nid: str\u00b6\nID of the sub-run.\nname: str\u00b6\nName of the object being run.\ntype: str\u00b6\nType of the object being run, eg. prompt, chain, llm, etc.\ntags: List[str]\u00b6\nList of tags for the run.\nmetadata: Dict[str, Any]\u00b6\nKey-value pairs of metadata for the run.\nstart_time: str\u00b6\nISO-8601 timestamp of when the run started.\nstreamed_output_str: List[str]\u00b6\nList of LLM tokens streamed by this run, if applicable.\nfinal_output: Optional[Any]\u00b6\nFinal output of this run.\nOnly available after the run has finished successfully.\nend_time: Optional[str]\u00b6\nISO-8601 timestamp of when the run ended.\nOnly available after the run has finished.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.log_stream.LogEntry.html"}
{"id": "ac39b52bb443-0", "text": "langchain.schema.output_parser.BaseGenerationOutputParser\u00b6\nclass langchain.schema.output_parser.BaseGenerationOutputParser[source]\u00b6\nBases: BaseLLMOutputParser, RunnableSerializable[Union[str, BaseMessage], T]\nBase class to parse the output of an LLM call.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseGenerationOutputParser.html"}
{"id": "ac39b52bb443-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseGenerationOutputParser.html"}
{"id": "ac39b52bb443-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseGenerationOutputParser.html"}
{"id": "ac39b52bb443-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseGenerationOutputParser.html"}
{"id": "ac39b52bb443-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseGenerationOutputParser.html"}
{"id": "ac39b52bb443-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nabstract parse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseGenerationOutputParser.html"}
{"id": "ac39b52bb443-6", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseGenerationOutputParser.html"}
{"id": "ac39b52bb443-7", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseGenerationOutputParser.html"}
{"id": "ac39b52bb443-8", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseGenerationOutputParser.html"}
{"id": "53b90d26f80a-0", "text": "langchain.schema.document.BaseDocumentTransformer\u00b6\nclass langchain.schema.document.BaseDocumentTransformer[source]\u00b6\nAbstract base class for document transformation systems.\nA document transformation system takes a sequence of Documents and returns a\nsequence of transformed Documents.\nExample\nclass EmbeddingsRedundantFilter(BaseDocumentTransformer, BaseModel):\n    embeddings: Embeddings\n    similarity_fn: Callable = cosine_similarity\n    similarity_threshold: float = 0.95\n    class Config:\n        arbitrary_types_allowed = True\n    def transform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        stateful_documents = get_stateful_documents(documents)\n        embedded_documents = _get_embeddings_from_stateful_docs(\n            self.embeddings, stateful_documents\n        )\n        included_idxs = _filter_similar_embeddings(\n            embedded_documents, self.similarity_fn, self.similarity_threshold\n        )\n        return [stateful_documents[i] for i in sorted(included_idxs)]\n    async def atransform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        raise NotImplementedError\nMethods\n__init__()\natransform_documents(documents,\u00a0**kwargs)\nAsynchronously transform a list of documents.\ntransform_documents(documents,\u00a0**kwargs)\nTransform a list of documents.\n__init__()\u00b6\nasync atransform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nAsynchronously transform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.\nabstract transform_documents(documents: Sequence[Document], **kwargs: Any) \u2192 Sequence[Document][source]\u00b6\nTransform a list of documents.\nParameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.document.BaseDocumentTransformer.html"}
{"id": "53b90d26f80a-1", "text": "Parameters\ndocuments \u2013 A sequence of Documents to be transformed.\nReturns\nA list of transformed Documents.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.document.BaseDocumentTransformer.html"}
{"id": "b27d905d128a-0", "text": "langchain.schema.runnable.base.RunnableEachBase\u00b6\nclass langchain.schema.runnable.base.RunnableEachBase[source]\u00b6\nBases: RunnableSerializable[List[Input], List[Output]]\nA runnable that delegates calls to another runnable\nwith each element of the input sequence.\nUse only if creating a new RunnableEach subclass with different __init__ args.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bound: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: List[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 List[Output][source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "b27d905d128a-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "b27d905d128a-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "b27d905d128a-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "b27d905d128a-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: List[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 List[Output][source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "b27d905d128a-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "b27d905d128a-6", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "b27d905d128a-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[List[langchain.schema.runnable.utils.Output]]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "b27d905d128a-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEachBase.html"}
{"id": "359bf2f927bf-0", "text": "langchain.schema.output_parser.StrOutputParser\u00b6\nclass langchain.schema.output_parser.StrOutputParser[source]\u00b6\nBases: BaseTransformOutputParser[str]\nOutputParser that parses LLMResult into the top likely string.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.StrOutputParser.html"}
{"id": "359bf2f927bf-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[T]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.StrOutputParser.html"}
{"id": "359bf2f927bf-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.StrOutputParser.html"}
{"id": "359bf2f927bf-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.StrOutputParser.html"}
{"id": "359bf2f927bf-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.StrOutputParser.html"}
{"id": "359bf2f927bf-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nparse(text: str) \u2192 str[source]\u00b6\nReturns the input text with no changes.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.StrOutputParser.html"}
{"id": "359bf2f927bf-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[T]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.StrOutputParser.html"}
{"id": "359bf2f927bf-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.StrOutputParser.html"}
{"id": "359bf2f927bf-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using StrOutputParser\u00b6\nFacebook Messenger\nChat loaders\niMessage\nOpaquePrompts\nFallbacks\nMultiVector Retriever\nFirst we add a step to load memory\nsql_db.md\nprompt_llm_parser.md\nmultiple_chains.md\nCode writing\nUsing tools\nConfigure Runnable traces", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.StrOutputParser.html"}
{"id": "7389048d7103-0", "text": "langchain.schema.cache.BaseCache\u00b6\nclass langchain.schema.cache.BaseCache[source]\u00b6\nBase interface for cache.\nMethods\n__init__()\nclear(**kwargs)\nClear cache that can take additional keyword arguments.\nlookup(prompt,\u00a0llm_string)\nLook up based on prompt and llm_string.\nupdate(prompt,\u00a0llm_string,\u00a0return_val)\nUpdate cache based on prompt and llm_string.\n__init__()\u00b6\nabstract clear(**kwargs: Any) \u2192 None[source]\u00b6\nClear cache that can take additional keyword arguments.\nabstract lookup(prompt: str, llm_string: str) \u2192 Optional[Sequence[Generation]][source]\u00b6\nLook up based on prompt and llm_string.\nabstract update(prompt: str, llm_string: str, return_val: Sequence[Generation]) \u2192 None[source]\u00b6\nUpdate cache based on prompt and llm_string.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.cache.BaseCache.html"}
{"id": "5e722430aa12-0", "text": "langchain.schema.messages.AIMessage\u00b6\nclass langchain.schema.messages.AIMessage[source]\u00b6\nBases: BaseMessage\nA Message from an AI.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam example: bool = False\u00b6\nWhether this Message is being passed in to the model as part of an example\nconversation.\nparam type: Literal['ai'] = 'ai'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.AIMessage.html"}
{"id": "5e722430aa12-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.AIMessage.html"}
{"id": "5e722430aa12-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using AIMessage\u00b6\nTwitter (via Apify)\nZep\nZep Memory\nSQL Chat Message History\nAnthropic\n\ud83d\ude85 LiteLLM\nKonko\nOpenAI\nJinaChat\nSet env var OPENAI_API_KEY or load from a .env file:\nCAMEL Role-Playing Autonomous Cooperative Agents\nMulti-agent decentralized speaker selection\nMulti-agent authoritarian speaker selection", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.AIMessage.html"}
{"id": "5e722430aa12-3", "text": "Multi-agent decentralized speaker selection\nMulti-agent authoritarian speaker selection\nMulti-Player Dungeons & Dragons\nSimulated Environment: Gymnasium\nAgent Debates with Tools\nPrompt pipelining", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.AIMessage.html"}
{"id": "92a45df9d2b1-0", "text": "langchain.schema.callbacks.tracers.schemas.TracerSessionV1Base\u00b6\nclass langchain.schema.callbacks.tracers.schemas.TracerSessionV1Base[source]\u00b6\nBases: BaseModel\nBase class for TracerSessionV1.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam extra: Optional[Dict[str, Any]] = None\u00b6\nparam name: Optional[str] = None\u00b6\nparam start_time: datetime.datetime [Optional]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSessionV1Base.html"}
{"id": "92a45df9d2b1-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSessionV1Base.html"}
{"id": "92a45df9d2b1-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSessionV1Base.html"}
{"id": "7578f9963a5a-0", "text": "langchain.schema.memory.BaseMemory\u00b6\nclass langchain.schema.memory.BaseMemory[source]\u00b6\nBases: Serializable, ABC\nAbstract base class for memory in Chains.\nMemory refers to state in Chains. Memory can be used to store information aboutpast executions of a Chain and inject that information into the inputs of\nfuture executions of the Chain. For example, for conversational Chains Memory\ncan be used to store conversations and automatically add them to future model\nprompts so that the model has the necessary context to respond coherently to\nthe latest input.\nExample\nclass SimpleMemory(BaseMemory):\n    memories: Dict[str, Any] = dict()\n    @property\n    def memory_variables(self) -> List[str]:\n        return list(self.memories.keys())\n    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:\n        return self.memories\n    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:\n        pass\n    def clear(self) -> None:\n        pass\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nabstract clear() \u2192 None[source]\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.memory.BaseMemory.html"}
{"id": "7578f9963a5a-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.memory.BaseMemory.html"}
{"id": "7578f9963a5a-2", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nabstract load_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nReturn key-value pairs given the text input to the chain.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nabstract save_context(inputs: Dict[str, Any], outputs: Dict[str, str]) \u2192 None[source]\u00b6\nSave the context of this chain run to memory.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.memory.BaseMemory.html"}
{"id": "7578f9963a5a-3", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nabstract property memory_variables: List[str]\u00b6\nThe string keys this memory class will add to chain inputs.\nExamples using BaseMemory\u00b6\nCustom Memory", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.memory.BaseMemory.html"}
{"id": "3583c0a8cacb-0", "text": "langchain.schema.runnable.utils.ConfigurableFieldMultiOption\u00b6\nclass langchain.schema.runnable.utils.ConfigurableFieldMultiOption(id: str, options: Mapping[str, Any], default: Sequence[str], name: Optional[str] = None, description: Optional[str] = None)[source]\u00b6\nA field that can be configured by the user with multiple default values.\nCreate new instance of ConfigurableFieldMultiOption(id, options, default, name, description)\nAttributes\ndefault\nAlias for field number 2\ndescription\nAlias for field number 4\nid\nAlias for field number 0\nname\nAlias for field number 3\noptions\nAlias for field number 1\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.ConfigurableFieldMultiOption.html"}
{"id": "b5a5b2b71656-0", "text": "langchain.schema.runnable.base.RunnableMap\u00b6\nlangchain.schema.runnable.base.RunnableMap\u00b6\nalias of RunnableParallel\nExamples using RunnableMap\u00b6\nOpaquePrompts\ninterface.md\nFirst we add a step to load memory\nsql_db.md\nprompt_llm_parser.md\nAdding memory\nmultiple_chains.md", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableMap.html"}
{"id": "1b3923dc3425-0", "text": "langchain.schema.runnable.utils.add\u00b6\nlangchain.schema.runnable.utils.add(addables: Iterable[Addable]) \u2192 Optional[Addable][source]\u00b6\nAdd a sequence of addable objects together.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.add.html"}
{"id": "63e373c6943c-0", "text": "langchain.schema.runnable.utils.accepts_config\u00b6\nlangchain.schema.runnable.utils.accepts_config(callable: Callable[[...], Any]) \u2192 bool[source]\u00b6\nCheck if a callable accepts a config argument.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.accepts_config.html"}
{"id": "687869cf286b-0", "text": "langchain.schema.runnable.base.RunnableBinding\u00b6\nclass langchain.schema.runnable.base.RunnableBinding[source]\u00b6\nBases: RunnableBindingBase[Input, Output]\nA runnable that delegates calls to another runnable with a set of kwargs.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bound: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nparam config: langchain.schema.runnable.config.RunnableConfig [Optional]\u00b6\nparam config_factories: List[Callable[[langchain.schema.runnable.config.RunnableConfig], langchain.schema.runnable.config.RunnableConfig]] [Optional]\u00b6\nparam custom_input_type: Optional[Any] = None\u00b6\nparam custom_output_type: Optional[Any] = None\u00b6\nparam kwargs: Mapping[str, Any] [Optional]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "687869cf286b-1", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "687869cf286b-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output][source]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "687869cf286b-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "687869cf286b-4", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "687869cf286b-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "687869cf286b-6", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output][source]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output][source]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "687869cf286b-7", "text": "added to the run.\nwith_retry(**kwargs: Any) \u2192 Runnable[Input, Output][source]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(input_type: Optional[Union[Type[Input], BaseModel]] = None, output_type: Optional[Union[Type[Output], BaseModel]] = None) \u2192 Runnable[Input, Output][source]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBinding.html"}
{"id": "bcfcc031859c-0", "text": "langchain.schema.callbacks.tracers.schemas.TracerSessionV1\u00b6\nclass langchain.schema.callbacks.tracers.schemas.TracerSessionV1[source]\u00b6\nBases: TracerSessionV1Base\nTracerSessionV1 schema.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam extra: Optional[Dict[str, Any]] = None\u00b6\nparam id: int [Required]\u00b6\nparam name: Optional[str] = None\u00b6\nparam start_time: datetime.datetime [Optional]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSessionV1.html"}
{"id": "bcfcc031859c-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSessionV1.html"}
{"id": "bcfcc031859c-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSessionV1.html"}
{"id": "5491566e8a1d-0", "text": "langchain.schema.agent.AgentActionMessageLog\u00b6\nclass langchain.schema.agent.AgentActionMessageLog[source]\u00b6\nBases: AgentAction\nOverride init to support instantiation by position for backward compat.\nparam log: str [Required]\u00b6\nAdditional information to log about the action.\nThis log can be used in a few ways. First, it can be used to audit\nwhat exactly the LLM predicted to lead to this (tool, tool_input).\nSecond, it can be used in future iterations to show the LLMs prior\nthoughts. This is useful when (tool, tool_input) does not contain\nfull information about the LLM prediction (for example, any thought\nbefore the tool/tool_input).\nparam message_log: Sequence[langchain.schema.messages.BaseMessage] [Required]\u00b6\nSimilar to log, this can be used to pass along extra\ninformation about what exact messages were predicted by the LLM\nbefore parsing out the (tool, tool_input). This is again useful\nif (tool, tool_input) cannot be used to fully recreate the LLM\nprediction, and you need that LLM prediction (for future agent iteration).\nCompared to log, this is useful when the underlying LLM is a\nChatModel (and therefore returns messages rather than a string).\nparam tool: str [Required]\u00b6\nThe name of the Tool to execute.\nparam tool_input: Union[str, dict] [Required]\u00b6\nThe input to pass in to the Tool.\nparam type: Literal['AgentActionMessageLog'] = 'AgentActionMessageLog'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.agent.AgentActionMessageLog.html"}
{"id": "5491566e8a1d-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether or not the class is serializable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.agent.AgentActionMessageLog.html"}
{"id": "5491566e8a1d-2", "text": "Return whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.agent.AgentActionMessageLog.html"}
{"id": "5491566e8a1d-3", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.agent.AgentActionMessageLog.html"}
{"id": "b7403cc4ca4b-0", "text": "langchain.schema.callbacks.manager.RunManager\u00b6\nclass langchain.schema.callbacks.manager.RunManager(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nSync Run Manager.\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nMethods\n__init__(*,\u00a0run_id,\u00a0handlers,\u00a0...[,\u00a0...])\nInitialize the run manager.\nget_noop_manager()\nReturn a manager that doesn't perform any operations.\non_retry(retry_state,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when text is received.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.RunManager.html"}
{"id": "b7403cc4ca4b-1", "text": "on_text(text,\u00a0**kwargs)\nRun when text is received.\n__init__(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nclassmethod get_noop_manager() \u2192 BRM\u00b6\nReturn a manager that doesn\u2019t perform any operations.\nReturns\nThe noop manager.\nReturn type\nBaseRunManager\non_retry(retry_state: RetryCallState, **kwargs: Any) \u2192 None[source]\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when text is received.\nParameters\ntext (str) \u2013 The received text.\nReturns\nThe result of the callback.\nReturn type\nAny", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.RunManager.html"}
{"id": "372595142933-0", "text": "langchain.schema.callbacks.manager.AsyncCallbackManagerForChainRun\u00b6\nclass langchain.schema.callbacks.manager.AsyncCallbackManagerForChainRun(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nAsync callback manager for chain run.\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nMethods\n__init__(*,\u00a0run_id,\u00a0handlers,\u00a0...[,\u00a0...])\nInitialize the run manager.\nget_child([tag])\nGet a child callback manager.\nget_noop_manager()\nReturn a manager that doesn't perform any operations.\non_agent_action(action,\u00a0**kwargs)\nRun when agent action is received.\non_agent_finish(finish,\u00a0**kwargs)\nRun when agent finish is received.\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends running.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_retry(retry_state,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForChainRun.html"}
{"id": "372595142933-1", "text": "Run when chain errors.\non_retry(retry_state,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when text is received.\n__init__(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nget_child(tag: Optional[str] = None) \u2192 AsyncCallbackManager\u00b6\nGet a child callback manager.\nParameters\ntag (str, optional) \u2013 The tag for the child callback manager.\nDefaults to None.\nReturns\nThe child callback manager.\nReturn type\nAsyncCallbackManager\nclassmethod get_noop_manager() \u2192 BRM\u00b6\nReturn a manager that doesn\u2019t perform any operations.\nReturns\nThe noop manager.\nReturn type\nBaseRunManager\nasync on_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when agent action is received.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForChainRun.html"}
{"id": "372595142933-2", "text": "Run when agent action is received.\nParameters\naction (AgentAction) \u2013 The agent action.\nReturns\nThe result of the callback.\nReturn type\nAny\nasync on_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when agent finish is received.\nParameters\nfinish (AgentFinish) \u2013 The agent finish.\nReturns\nThe result of the callback.\nReturn type\nAny\nasync on_chain_end(outputs: Union[Dict[str, Any], Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends running.\nParameters\noutputs (Union[Dict[str, Any], Any]) \u2013 The outputs of the chain.\nasync on_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.\nParameters\nerror (Exception or KeyboardInterrupt) \u2013 The error.\nasync on_retry(retry_state: RetryCallState, **kwargs: Any) \u2192 None\u00b6\nRun on a retry event.\nasync on_text(text: str, **kwargs: Any) \u2192 Any\u00b6\nRun when text is received.\nParameters\ntext (str) \u2013 The received text.\nReturns\nThe result of the callback.\nReturn type\nAny\nExamples using AsyncCallbackManagerForChainRun\u00b6\nCustom chain", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForChainRun.html"}
{"id": "354488b97572-0", "text": "langchain.schema.callbacks.manager.ParentRunManager\u00b6\nclass langchain.schema.callbacks.manager.ParentRunManager(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nSync Parent Run Manager.\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nMethods\n__init__(*,\u00a0run_id,\u00a0handlers,\u00a0...[,\u00a0...])\nInitialize the run manager.\nget_child([tag])\nGet a child callback manager.\nget_noop_manager()\nReturn a manager that doesn't perform any operations.\non_retry(retry_state,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when text is received.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.ParentRunManager.html"}
{"id": "354488b97572-1", "text": "on_text(text,\u00a0**kwargs)\nRun when text is received.\n__init__(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nget_child(tag: Optional[str] = None) \u2192 CallbackManager[source]\u00b6\nGet a child callback manager.\nParameters\ntag (str, optional) \u2013 The tag for the child callback manager.\nDefaults to None.\nReturns\nThe child callback manager.\nReturn type\nCallbackManager\nclassmethod get_noop_manager() \u2192 BRM\u00b6\nReturn a manager that doesn\u2019t perform any operations.\nReturns\nThe noop manager.\nReturn type\nBaseRunManager\non_retry(retry_state: RetryCallState, **kwargs: Any) \u2192 None\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 Any\u00b6\nRun when text is received.\nParameters\ntext (str) \u2013 The received text.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.ParentRunManager.html"}
{"id": "354488b97572-2", "text": "Run when text is received.\nParameters\ntext (str) \u2013 The received text.\nReturns\nThe result of the callback.\nReturn type\nAny", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.ParentRunManager.html"}
{"id": "22dcb5d47e39-0", "text": "langchain.schema.output_parser.BaseCumulativeTransformOutputParser\u00b6\nclass langchain.schema.output_parser.BaseCumulativeTransformOutputParser[source]\u00b6\nBases: BaseTransformOutputParser[T]\nBase class for an output parser that can handle streaming input.\nparam diff: bool = False\u00b6\nIn streaming mode, whether to yield diffs between the previous and current\nparsed output, or just the current parsed output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseCumulativeTransformOutputParser.html"}
{"id": "22dcb5d47e39-1", "text": "Parameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[T]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseCumulativeTransformOutputParser.html"}
{"id": "22dcb5d47e39-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseCumulativeTransformOutputParser.html"}
{"id": "22dcb5d47e39-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseCumulativeTransformOutputParser.html"}
{"id": "22dcb5d47e39-4", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseCumulativeTransformOutputParser.html"}
{"id": "22dcb5d47e39-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nabstract parse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseCumulativeTransformOutputParser.html"}
{"id": "22dcb5d47e39-6", "text": "The prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[T]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseCumulativeTransformOutputParser.html"}
{"id": "22dcb5d47e39-7", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseCumulativeTransformOutputParser.html"}
{"id": "22dcb5d47e39-8", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseCumulativeTransformOutputParser.html"}
{"id": "32bb8a026f25-0", "text": "langchain.schema.callbacks.tracers.langchain.log_error_once\u00b6\nlangchain.schema.callbacks.tracers.langchain.log_error_once(method: str, exception: Exception) \u2192 None[source]\u00b6\nLog an error once.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain.log_error_once.html"}
{"id": "a434c360bd26-0", "text": "langchain.schema.runnable.passthrough.RunnablePassthrough\u00b6\nclass langchain.schema.runnable.passthrough.RunnablePassthrough[source]\u00b6\nBases: RunnableSerializable[Other, Other]\nA runnable to passthrough inputs unchanged or with additional keys.\nThis runnable behaves almost like the identity function, except that it\ncan be configured to add additional keys to the output, if the input is a\ndict.\nThe examples below demonstrate this runnable works using a few simple\nchains. The chains rely on simple lambdas to make the examples easy to execute\nand experiment with.\nExamples\nfrom langchain.schema.runnable import RunnablePassthrough, RunnableParallel\nrunnable = RunnableParallel(\n    origin=RunnablePassthrough(),\n    modified=lambda x: x+1\n)\nrunnable.invoke(1) # {'origin': 1, 'modified': 2}\n def fake_llm(prompt: str) -> str: # Fake LLM for the example\n    return \"completion\"\nchain = RunnableLambda(fake_llm) | {\n    'original': RunnablePassthrough(), # Original LLM output\n    'parsed': lambda text: text[::-1] # Parsing logic\n}\nchain.invoke('hello') # {'original': 'completion', 'parsed': 'noitelpmoc'}\nIn some cases, it may be useful to pass the input through while adding some\nkeys to the output. In this case, you can use the assign method:\nfrom langchain.schema.runnable import RunnablePassthrough, RunnableParallel\n def fake_llm(prompt: str) -> str: # Fake LLM for the example\n    return \"completion\"\nrunnable = {\n    'llm1':  fake_llm,\n    'llm2':  fake_llm,\n}\n| RunnablePassthrough.assign(", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "a434c360bd26-1", "text": "}\n| RunnablePassthrough.assign(\n    total_chars=lambda inputs: len(inputs['llm1'] + inputs['llm2'])\n  )\nrunnable.invoke('hello')\n# {'llm1': 'completion', 'llm2': 'completion', 'total_chars': 20}\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam afunc: Optional[Union[Callable[[langchain.schema.runnable.base.Other], Awaitable[None]], Callable[[langchain.schema.runnable.base.Other, langchain.schema.runnable.config.RunnableConfig], Awaitable[None]]]] = None\u00b6\nparam func: Optional[Union[Callable[[langchain.schema.runnable.base.Other], None], Callable[[langchain.schema.runnable.base.Other, langchain.schema.runnable.config.RunnableConfig], None]]] = None\u00b6\nparam input_type: Optional[Type[langchain.schema.runnable.base.Other]] = None\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Other, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Other[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "a434c360bd26-2", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nclassmethod assign(**kwargs: Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any], Mapping[str, Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any]]]]) \u2192 RunnableAssign[source]\u00b6\nMerge the Dict input with the output produced by the mapping argument.\nParameters\nmapping \u2013 A mapping from keys to runnables or callables.\nReturns\nA runnable that merges the Dict input with the output produced by the\nmapping argument.\nasync astream(input: Other, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Other][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "a434c360bd26-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Other], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Other][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "a434c360bd26-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "a434c360bd26-5", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Other, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Other[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "a434c360bd26-6", "text": "for more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "a434c360bd26-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Other, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Other][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Other], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Other][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "a434c360bd26-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Any\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "a434c360bd26-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using RunnablePassthrough\u00b6\nFirst we add a step to load memory\nprompt_llm_parser.md\nmultiple_chains.md", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnablePassthrough.html"}
{"id": "e9db1caac566-0", "text": "langchain.schema.callbacks.manager.tracing_v2_enabled\u00b6\nlangchain.schema.callbacks.manager.tracing_v2_enabled(project_name: Optional[str] = None, *, example_id: Optional[Union[str, UUID]] = None, tags: Optional[List[str]] = None, client: Optional[LangSmithClient] = None) \u2192 Generator[LangChainTracer, None, None][source]\u00b6\nInstruct LangChain to log all runs in context to LangSmith.\nParameters\nproject_name (str, optional) \u2013 The name of the project.\nDefaults to \u201cdefault\u201d.\nexample_id (str or UUID, optional) \u2013 The ID of the example.\nDefaults to None.\ntags (List[str], optional) \u2013 The tags to add to the run.\nDefaults to None.\nReturns\nNone\nExample\n>>> with tracing_v2_enabled():\n...     # LangChain code will automatically be traced\nYou can use this to fetch the LangSmith run URL:\n>>> with tracing_v2_enabled() as cb:\n...     chain.invoke(\"foo\")\n...     run_url = cb.get_run_url()\nExamples using tracing_v2_enabled\u00b6\nLangSmith Walkthrough", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.tracing_v2_enabled.html"}
{"id": "86ba57802f9e-0", "text": "langchain.schema.callbacks.tracers.stdout.try_json_stringify\u00b6\nlangchain.schema.callbacks.tracers.stdout.try_json_stringify(obj: Any, fallback: str) \u2192 str[source]\u00b6\nTry to stringify an object to JSON.\n:param obj: Object to stringify.\n:param fallback: Fallback string to return if the object cannot be stringified.\nReturns\nA JSON string if the object can be stringified, otherwise the fallback string.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.stdout.try_json_stringify.html"}
{"id": "ad768a3fd453-0", "text": "langchain.schema.runnable.utils.get_lambda_source\u00b6\nlangchain.schema.runnable.utils.get_lambda_source(func: Callable) \u2192 Optional[str][source]\u00b6\nGet the source code of a lambda function.\nParameters\nfunc \u2013 a callable that can be a lambda function\nReturns\nthe source code of the lambda function\nReturn type\nstr", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.get_lambda_source.html"}
{"id": "f0b97704b20a-0", "text": "langchain.schema.callbacks.tracers.run_collector.RunCollectorCallbackHandler\u00b6\nclass langchain.schema.callbacks.tracers.run_collector.RunCollectorCallbackHandler(example_id: Optional[Union[UUID, str]] = None, **kwargs: Any)[source]\u00b6\nA tracer that collects all nested runs in a list.\nThis tracer is useful for inspection and evaluation purposes.\nParameters\nexample_id (Optional[Union[UUID, str]], default=None) \u2013 The ID of the example being traced. It can be either a UUID or a string.\nInitialize the RunCollectorCallbackHandler.\nParameters\nexample_id (Optional[Union[UUID, str]], default=None) \u2013 The ID of the example being traced. It can be either a UUID or a string.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nname\nraise_error\nrun_inline\nMethods\n__init__([example_id])\nInitialize the RunCollectorCallbackHandler.\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0inputs])\nEnd a trace for a chain run.\non_chain_error(error,\u00a0*[,\u00a0inputs])\nHandle an error for a chain run.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nStart a trace for a chain run.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.run_collector.RunCollectorCallbackHandler.html"}
{"id": "f0b97704b20a-1", "text": "Run when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for an LLM run.\non_llm_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for an LLM run.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nStart a trace for an LLM run.\non_retriever_end(documents,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for a tool run.\non_tool_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for a tool run.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nStart a trace for a tool run.\n__init__(example_id: Optional[Union[UUID, str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nInitialize the RunCollectorCallbackHandler.\nParameters\nexample_id (Optional[Union[UUID, str]], default=None) \u2013 The ID of the example being traced. It can be either a UUID or a string.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.run_collector.RunCollectorCallbackHandler.html"}
{"id": "f0b97704b20a-2", "text": "on_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, inputs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a chain run.\non_chain_error(error: BaseException, *, inputs: Optional[Dict[str, Any]] = None, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a chain run.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, run_type: Optional[str] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a chain run.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for an LLM run.\non_llm_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.run_collector.RunCollectorCallbackHandler.html"}
{"id": "f0b97704b20a-3", "text": "Handle an error for an LLM run.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Run\u00b6\nRun on new LLM token. Only available when streaming is enabled.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for an LLM run.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.run_collector.RunCollectorCallbackHandler.html"}
{"id": "f0b97704b20a-4", "text": "End a trace for a tool run.\non_tool_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a tool run.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a tool run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.run_collector.RunCollectorCallbackHandler.html"}
{"id": "ee7898967507-0", "text": "langchain.schema.messages.ChatMessageChunk\u00b6\nclass langchain.schema.messages.ChatMessageChunk[source]\u00b6\nBases: ChatMessage, BaseMessageChunk\nA Chat Message chunk.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam role: str [Required]\u00b6\nThe speaker / role of the Message.\nparam type: Literal['ChatMessageChunk'] = 'ChatMessageChunk'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.ChatMessageChunk.html"}
{"id": "ee7898967507-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.ChatMessageChunk.html"}
{"id": "ee7898967507-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.ChatMessageChunk.html"}
{"id": "e459db521ea1-0", "text": "langchain.schema.chat_history.BaseChatMessageHistory\u00b6\nclass langchain.schema.chat_history.BaseChatMessageHistory[source]\u00b6\nAbstract base class for storing chat message history.\nSee ChatMessageHistory for default implementation.\nExample\nclass FileChatMessageHistory(BaseChatMessageHistory):\n    storage_path:  str\n    session_id: str\n   @property\n   def messages(self):\n       with open(os.path.join(storage_path, session_id), 'r:utf-8') as f:\n           messages = json.loads(f.read())\n        return messages_from_dict(messages)\n   def add_message(self, message: BaseMessage) -> None:\n       messages = self.messages.append(_message_to_dict(message))\n       with open(os.path.join(storage_path, session_id), 'w') as f:\n           json.dump(f, messages)\n   def clear(self):\n       with open(os.path.join(storage_path, session_id), 'w') as f:\n           f.write(\"[]\")\nAttributes\nmessages\nA list of Messages stored in-memory.\nMethods\n__init__()\nadd_ai_message(message)\nConvenience method for adding an AI message string to the store.\nadd_message(message)\nAdd a Message object to the store.\nadd_user_message(message)\nConvenience method for adding a human message string to the store.\nclear()\nRemove all messages from the store\n__init__()\u00b6\nadd_ai_message(message: str) \u2192 None[source]\u00b6\nConvenience method for adding an AI message string to the store.\nParameters\nmessage \u2013 The string contents of an AI message.\nabstract add_message(message: BaseMessage) \u2192 None[source]\u00b6\nAdd a Message object to the store.\nParameters\nmessage \u2013 A BaseMessage object to store.\nadd_user_message(message: str) \u2192 None[source]\u00b6\nConvenience method for adding a human message string to the store.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.chat_history.BaseChatMessageHistory.html"}
{"id": "e459db521ea1-1", "text": "Convenience method for adding a human message string to the store.\nParameters\nmessage \u2013 The string contents of a human message.\nabstract clear() \u2192 None[source]\u00b6\nRemove all messages from the store", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.chat_history.BaseChatMessageHistory.html"}
{"id": "ace0f11e7ae8-0", "text": "langchain.schema.prompt_template.BasePromptTemplate\u00b6\nclass langchain.schema.prompt_template.BasePromptTemplate[source]\u00b6\nBases: RunnableSerializable[Dict, PromptValue], ABC\nBase class for all prompt templates, returning a prompt.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam input_types: Dict[str, Any] [Optional]\u00b6\nA dictionary of the types of the variables the prompt template expects.\nIf not provided, all variables are assumed to be strings.\nparam input_variables: List[str] [Required]\u00b6\nA list of the names of the variables the prompt template expects.\nparam output_parser: Optional[langchain.schema.output_parser.BaseOutputParser] = None\u00b6\nHow to parse the output of calling an LLM on this formatted prompt.\nparam partial_variables: Mapping[str, Union[str, Callable[[], str]]] [Optional]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.prompt_template.BasePromptTemplate.html"}
{"id": "ace0f11e7ae8-1", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.prompt_template.BasePromptTemplate.html"}
{"id": "ace0f11e7ae8-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.prompt_template.BasePromptTemplate.html"}
{"id": "ace0f11e7ae8-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict[source]\u00b6\nReturn dictionary representation of prompt.\nabstract format(**kwargs: Any) \u2192 str[source]\u00b6\nFormat the prompt with the inputs.\nParameters\nkwargs \u2013 Any arguments to be passed to the prompt template.\nReturns\nA formatted string.\nExample:\nprompt.format(variable1=\"foo\")\nabstract format_prompt(**kwargs: Any) \u2192 PromptValue[source]\u00b6\nCreate Chat Messages.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.prompt_template.BasePromptTemplate.html"}
{"id": "ace0f11e7ae8-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict, config: Optional[RunnableConfig] = None) \u2192 PromptValue[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.prompt_template.BasePromptTemplate.html"}
{"id": "ace0f11e7ae8-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npartial(**kwargs: Union[str, Callable[[], str]]) \u2192 BasePromptTemplate[source]\u00b6\nReturn a partial of the prompt template.\nsave(file_path: Union[Path, str]) \u2192 None[source]\u00b6\nSave the prompt.\nParameters\nfile_path \u2013 Path to directory to save prompt to.\nExample:\n.. code-block:: python\nprompt.save(file_path=\u201dpath/prompt.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.prompt_template.BasePromptTemplate.html"}
{"id": "ace0f11e7ae8-6", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.prompt_template.BasePromptTemplate.html"}
{"id": "ace0f11e7ae8-7", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Any\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.prompt_template.BasePromptTemplate.html"}
{"id": "ace0f11e7ae8-8", "text": "A map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using BasePromptTemplate\u00b6\nCustom chain", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.prompt_template.BasePromptTemplate.html"}
{"id": "9fef55613407-0", "text": "langchain.schema.runnable.branch.RunnableBranch\u00b6\nclass langchain.schema.runnable.branch.RunnableBranch[source]\u00b6\nBases: RunnableSerializable[Input, Output]\nA Runnable that selects which branch to run based on a condition.\nThe runnable is initialized with a list of (condition, runnable) pairs and\na default branch.\nWhen operating on an input, the first condition that evaluates to True is\nselected, and the corresponding runnable is run on the input.\nIf no condition evaluates to True, the default branch is run on the input.\nExamples\nfrom langchain.schema.runnable import RunnableBranch\nbranch = RunnableBranch(\n    (lambda x: isinstance(x, str), lambda x: x.upper()),\n    (lambda x: isinstance(x, int), lambda x: x + 1),\n    (lambda x: isinstance(x, float), lambda x: x * 2),\n    lambda x: \"goodbye\",\n)\nbranch.invoke(\"hello\") # \"HELLO\"\nbranch.invoke(None) # \"goodbye\"\nA Runnable that runs one of two branches based on a condition.\nparam branches: Sequence[Tuple[langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, bool], langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output]]] [Required]\u00b6\nparam default: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "9fef55613407-1", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nAsync version of invoke.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "9fef55613407-2", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "9fef55613407-3", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "9fef55613407-4", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nThe namespace of a RunnableBranch is the namespace of its default branch.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nFirst evaluates the condition, then delegate to true or false branch.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nRunnableBranch is serializable if all its branches are serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "9fef55613407-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "9fef55613407-6", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "9fef55613407-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "9fef55613407-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.branch.RunnableBranch.html"}
{"id": "a82f75d7df0e-0", "text": "langchain.schema.runnable.config.get_async_callback_manager_for_config\u00b6\nlangchain.schema.runnable.config.get_async_callback_manager_for_config(config: RunnableConfig) \u2192 AsyncCallbackManager[source]\u00b6\nGet an async callback manager for a config.\nParameters\nconfig (RunnableConfig) \u2013 The config.\nReturns\nThe async callback manager.\nReturn type\nAsyncCallbackManager", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.config.get_async_callback_manager_for_config.html"}
{"id": "b198ac934c61-0", "text": "langchain.schema.messages.SystemMessage\u00b6\nclass langchain.schema.messages.SystemMessage[source]\u00b6\nBases: BaseMessage\nA Message for priming AI behavior, usually passed in as the first of a sequence\nof input messages.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam type: Literal['system'] = 'system'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.SystemMessage.html"}
{"id": "b198ac934c61-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.SystemMessage.html"}
{"id": "b198ac934c61-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using SystemMessage\u00b6\nMetaphor Search\nSQL Chat Message History\nAnthropic\n\ud83d\ude85 LiteLLM\nKonko\nOpenAI\nGoogle Cloud Platform Vertex AI PaLM \nJinaChat\nAnyscale\nLLMonitor\nContext\nLabel Studio\nMLflow AI Gateway\nSet env var OPENAI_API_KEY or load from a .env file:\nConversational Retrieval Agent", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.SystemMessage.html"}
{"id": "b198ac934c61-3", "text": "Conversational Retrieval Agent\nStructure answers with OpenAI functions\nAgents\nCAMEL Role-Playing Autonomous Cooperative Agents\nMulti-Agent Simulated Environment: Petting Zoo\nMulti-agent decentralized speaker selection\nMulti-agent authoritarian speaker selection\nTwo-Player Dungeons & Dragons\nMulti-Player Dungeons & Dragons\nSimulated Environment: Gymnasium\nAgent Debates with Tools\nMemory in LLMChain\nUse ToolKits with OpenAI Functions\nPrompt pipelining\nUsing OpenAI functions", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.SystemMessage.html"}
{"id": "648ffcd4af6b-0", "text": "langchain.schema.runnable.router.RouterRunnable\u00b6\nclass langchain.schema.runnable.router.RouterRunnable[source]\u00b6\nBases: RunnableSerializable[RouterInput, Output]\nA runnable that routes to a set of runnables based on Input[\u2018key\u2019].\nReturns the output of the selected runnable.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam runnables: Mapping[str, langchain.schema.runnable.base.Runnable[Any, langchain.schema.runnable.utils.Output]] [Required]\u00b6\nasync abatch(inputs: List[RouterInput], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: RouterInput, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: RouterInput, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "648ffcd4af6b-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[RouterInput], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "648ffcd4af6b-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "648ffcd4af6b-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "648ffcd4af6b-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: RouterInput, config: Optional[RunnableConfig] = None) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "648ffcd4af6b-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: RouterInput, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "648ffcd4af6b-6", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "648ffcd4af6b-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "648ffcd4af6b-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.router.RouterRunnable.html"}
{"id": "ff650f87153e-0", "text": "langchain.schema.runnable.utils.accepts_run_manager\u00b6\nlangchain.schema.runnable.utils.accepts_run_manager(callable: Callable[[...], Any]) \u2192 bool[source]\u00b6\nCheck if a callable accepts a run_manager argument.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.accepts_run_manager.html"}
{"id": "ec300a401f1c-0", "text": "langchain.schema.output_parser.BaseLLMOutputParser\u00b6\nclass langchain.schema.output_parser.BaseLLMOutputParser[source]\u00b6\nAbstract base class for parsing the outputs of a model.\nMethods\n__init__()\naparse_result(result,\u00a0*[,\u00a0partial])\nParse a list of candidate model Generations into a specific format.\nparse_result(result,\u00a0*[,\u00a0partial])\nParse a list of candidate model Generations into a specific format.\n__init__()\u00b6\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T[source]\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nabstract parse_result(result: List[Generation], *, partial: bool = False) \u2192 T[source]\u00b6\nParse a list of candidate model Generations into a specific format.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseLLMOutputParser.html"}
{"id": "42967315e201-0", "text": "langchain.schema.callbacks.manager.AsyncRunManager\u00b6\nclass langchain.schema.callbacks.manager.AsyncRunManager(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nAsync Run Manager.\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nMethods\n__init__(*,\u00a0run_id,\u00a0handlers,\u00a0...[,\u00a0...])\nInitialize the run manager.\nget_noop_manager()\nReturn a manager that doesn't perform any operations.\non_retry(retry_state,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when text is received.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncRunManager.html"}
{"id": "42967315e201-1", "text": "on_text(text,\u00a0**kwargs)\nRun when text is received.\n__init__(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nclassmethod get_noop_manager() \u2192 BRM\u00b6\nReturn a manager that doesn\u2019t perform any operations.\nReturns\nThe noop manager.\nReturn type\nBaseRunManager\nasync on_retry(retry_state: RetryCallState, **kwargs: Any) \u2192 None[source]\u00b6\nRun on a retry event.\nasync on_text(text: str, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when text is received.\nParameters\ntext (str) \u2013 The received text.\nReturns\nThe result of the callback.\nReturn type\nAny", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncRunManager.html"}
{"id": "0c81c75ba89d-0", "text": "langchain.schema.runnable.utils.AddableDict\u00b6\nclass langchain.schema.runnable.utils.AddableDict[source]\u00b6\nDictionary that can be added to another dictionary.\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.AddableDict.html"}
{"id": "0c81c75ba89d-1", "text": "pop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.AddableDict.html"}
{"id": "c4b5aacb3c58-0", "text": "langchain.schema.callbacks.manager.CallbackManager\u00b6\nclass langchain.schema.callbacks.manager.CallbackManager(handlers: List[BaseCallbackHandler], inheritable_handlers: Optional[List[BaseCallbackHandler]] = None, parent_run_id: Optional[UUID] = None, *, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nCallback manager that handles callbacks from LangChain.\nInitialize callback manager.\nAttributes\nis_async\nWhether the callback manager is async.\nMethods\n__init__(handlers[,\u00a0inheritable_handlers,\u00a0...])\nInitialize callback manager.\nadd_handler(handler[,\u00a0inherit])\nAdd a handler to the callback manager.\nadd_metadata(metadata[,\u00a0inherit])\nadd_tags(tags[,\u00a0inherit])\nconfigure([inheritable_callbacks,\u00a0...])\nConfigure the callback manager.\ncopy()\nCopy the callback manager.\non_chain_start(serialized,\u00a0inputs[,\u00a0run_id])\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0...)\nRun when LLM starts running.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts running.\non_retriever_start(serialized,\u00a0query[,\u00a0...])\nRun when retriever starts running.\non_tool_start(serialized,\u00a0input_str[,\u00a0...])\nRun when tool starts running.\nremove_handler(handler)\nRemove a handler from the callback manager.\nremove_metadata(keys)\nremove_tags(tags)\nset_handler(handler[,\u00a0inherit])\nSet handler as the only handler on the callback manager.\nset_handlers(handlers[,\u00a0inherit])\nSet handlers as the only handlers on the callback manager.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManager.html"}
{"id": "c4b5aacb3c58-1", "text": "Set handlers as the only handlers on the callback manager.\n__init__(handlers: List[BaseCallbackHandler], inheritable_handlers: Optional[List[BaseCallbackHandler]] = None, parent_run_id: Optional[UUID] = None, *, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize callback manager.\nadd_handler(handler: BaseCallbackHandler, inherit: bool = True) \u2192 None\u00b6\nAdd a handler to the callback manager.\nadd_metadata(metadata: Dict[str, Any], inherit: bool = True) \u2192 None\u00b6\nadd_tags(tags: List[str], inherit: bool = True) \u2192 None\u00b6\nclassmethod configure(inheritable_callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, local_callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, verbose: bool = False, inheritable_tags: Optional[List[str]] = None, local_tags: Optional[List[str]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None, local_metadata: Optional[Dict[str, Any]] = None) \u2192 CallbackManager[source]\u00b6\nConfigure the callback manager.\nParameters\ninheritable_callbacks (Optional[Callbacks], optional) \u2013 The inheritable\ncallbacks. Defaults to None.\nlocal_callbacks (Optional[Callbacks], optional) \u2013 The local callbacks.\nDefaults to None.\nverbose (bool, optional) \u2013 Whether to enable verbose mode. Defaults to False.\ninheritable_tags (Optional[List[str]], optional) \u2013 The inheritable tags.\nDefaults to None.\nlocal_tags (Optional[List[str]], optional) \u2013 The local tags.\nDefaults to None.\ninheritable_metadata (Optional[Dict[str, Any]], optional) \u2013 The inheritable", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManager.html"}
{"id": "c4b5aacb3c58-2", "text": "inheritable_metadata (Optional[Dict[str, Any]], optional) \u2013 The inheritable\nmetadata. Defaults to None.\nlocal_metadata (Optional[Dict[str, Any]], optional) \u2013 The local metadata.\nDefaults to None.\nReturns\nThe configured callback manager.\nReturn type\nCallbackManager\ncopy() \u2192 T\u00b6\nCopy the callback manager.\non_chain_start(serialized: Dict[str, Any], inputs: Union[Dict[str, Any], Any], run_id: Optional[UUID] = None, **kwargs: Any) \u2192 CallbackManagerForChainRun[source]\u00b6\nRun when chain starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized chain.\ninputs (Union[Dict[str, Any], Any]) \u2013 The inputs to the chain.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nReturns\nThe callback manager for the chain run.\nReturn type\nCallbackManagerForChainRun\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], **kwargs: Any) \u2192 List[CallbackManagerForLLMRun][source]\u00b6\nRun when LLM starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized LLM.\nmessages (List[List[BaseMessage]]) \u2013 The list of messages.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nReturns\nA callback manager for eachlist of messages as an LLM run.\nReturn type\nList[CallbackManagerForLLMRun]\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 List[CallbackManagerForLLMRun][source]\u00b6\nRun when LLM starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized LLM.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManager.html"}
{"id": "c4b5aacb3c58-3", "text": "Parameters\nserialized (Dict[str, Any]) \u2013 The serialized LLM.\nprompts (List[str]) \u2013 The list of prompts.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nReturns\nA callback manager for eachprompt as an LLM run.\nReturn type\nList[CallbackManagerForLLMRun]\non_retriever_start(serialized: Dict[str, Any], query: str, run_id: Optional[UUID] = None, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 CallbackManagerForRetrieverRun[source]\u00b6\nRun when retriever starts running.\non_tool_start(serialized: Dict[str, Any], input_str: str, run_id: Optional[UUID] = None, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 CallbackManagerForToolRun[source]\u00b6\nRun when tool starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized tool.\ninput_str (str) \u2013 The input to the tool.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run. Defaults to None.\nReturns\nThe callback manager for the tool run.\nReturn type\nCallbackManagerForToolRun\nremove_handler(handler: BaseCallbackHandler) \u2192 None\u00b6\nRemove a handler from the callback manager.\nremove_metadata(keys: List[str]) \u2192 None\u00b6\nremove_tags(tags: List[str]) \u2192 None\u00b6\nset_handler(handler: BaseCallbackHandler, inherit: bool = True) \u2192 None\u00b6\nSet handler as the only handler on the callback manager.\nset_handlers(handlers: List[BaseCallbackHandler], inherit: bool = True) \u2192 None\u00b6\nSet handlers as the only handlers on the callback manager.\nExamples using CallbackManager\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManager.html"}
{"id": "c4b5aacb3c58-4", "text": "Set handlers as the only handlers on the callback manager.\nExamples using CallbackManager\u00b6\nAnthropic\n\ud83d\ude85 LiteLLM\nOllama\nLlama.cpp\nTitan Takeoff\nRun LLMs locally\nSet env var OPENAI_API_KEY or load from a .env file\nUse local LLMs\nWebResearchRetriever", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManager.html"}
{"id": "85e26bae34f9-0", "text": "langchain.schema.runnable.config.get_executor_for_config\u00b6\nlangchain.schema.runnable.config.get_executor_for_config(config: RunnableConfig) \u2192 Generator[Executor, None, None][source]\u00b6\nGet an executor for a config.\nParameters\nconfig (RunnableConfig) \u2013 The config.\nYields\nGenerator[Executor, None, None] \u2013 The executor.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.config.get_executor_for_config.html"}
{"id": "5d6f488fc59e-0", "text": "langchain.schema.output.LLMResult\u00b6\nclass langchain.schema.output.LLMResult[source]\u00b6\nBases: BaseModel\nClass that contains all results for a batched LLM call.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam generations: List[List[langchain.schema.output.Generation]] [Required]\u00b6\nList of generated outputs. This is a List[List[]] because\neach input could have multiple candidate generations.\nparam llm_output: Optional[dict] = None\u00b6\nArbitrary LLM provider-specific output.\nparam run: Optional[List[langchain.schema.output.RunInfo]] = None\u00b6\nList of metadata info for model call for each input.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.LLMResult.html"}
{"id": "5d6f488fc59e-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nflatten() \u2192 List[LLMResult][source]\u00b6\nFlatten generations into a single list.\nUnpack List[List[Generation]] -> List[LLMResult] where each returned LLMResultcontains only a single Generation. If token usage information is available,\nit is kept only for the LLMResult corresponding to the top-choice\nGeneration, to avoid over-counting of token usage downstream.\nReturns\nList of LLMResults where each returned LLMResult contains a singleGeneration.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.LLMResult.html"}
{"id": "5d6f488fc59e-2", "text": "classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nExamples using LLMResult\u00b6\nOllama\nAsync callbacks", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.LLMResult.html"}
{"id": "6d72cc75a2ac-0", "text": "langchain.schema.runnable.utils.get_unique_config_specs\u00b6\nlangchain.schema.runnable.utils.get_unique_config_specs(specs: Iterable[ConfigurableFieldSpec]) \u2192 List[ConfigurableFieldSpec][source]\u00b6\nGet the unique config specs from a sequence of config specs.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.get_unique_config_specs.html"}
{"id": "33b8b595a510-0", "text": "langchain.schema.messages.ToolMessage\u00b6\nclass langchain.schema.messages.ToolMessage[source]\u00b6\nBases: BaseMessage\nA Message for passing the result of executing a tool back to a model.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam tool_call_id: str [Required]\u00b6\nTool call that this message is responding to.\nparam type: Literal['tool'] = 'tool'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.ToolMessage.html"}
{"id": "33b8b595a510-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.ToolMessage.html"}
{"id": "33b8b595a510-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.ToolMessage.html"}
{"id": "8bd517e55242-0", "text": "langchain.schema.callbacks.manager.AsyncCallbackManagerForRetrieverRun\u00b6\nclass langchain.schema.callbacks.manager.AsyncCallbackManagerForRetrieverRun(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nAsync callback manager for retriever run.\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nMethods\n__init__(*,\u00a0run_id,\u00a0handlers,\u00a0...[,\u00a0...])\nInitialize the run manager.\nget_child([tag])\nGet a child callback manager.\nget_noop_manager()\nReturn a manager that doesn't perform any operations.\non_retriever_end(documents,\u00a0**kwargs)\nRun when retriever ends running.\non_retriever_error(error,\u00a0**kwargs)\nRun when retriever errors.\non_retry(retry_state,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when text is received.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForRetrieverRun.html"}
{"id": "8bd517e55242-1", "text": "on_text(text,\u00a0**kwargs)\nRun when text is received.\n__init__(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nget_child(tag: Optional[str] = None) \u2192 AsyncCallbackManager\u00b6\nGet a child callback manager.\nParameters\ntag (str, optional) \u2013 The tag for the child callback manager.\nDefaults to None.\nReturns\nThe child callback manager.\nReturn type\nAsyncCallbackManager\nclassmethod get_noop_manager() \u2192 BRM\u00b6\nReturn a manager that doesn\u2019t perform any operations.\nReturns\nThe noop manager.\nReturn type\nBaseRunManager\nasync on_retriever_end(documents: Sequence[Document], **kwargs: Any) \u2192 None[source]\u00b6\nRun when retriever ends running.\nasync on_retriever_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when retriever errors.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForRetrieverRun.html"}
{"id": "8bd517e55242-2", "text": "Run when retriever errors.\nasync on_retry(retry_state: RetryCallState, **kwargs: Any) \u2192 None\u00b6\nRun on a retry event.\nasync on_text(text: str, **kwargs: Any) \u2192 Any\u00b6\nRun when text is received.\nParameters\ntext (str) \u2013 The received text.\nReturns\nThe result of the callback.\nReturn type\nAny\nExamples using AsyncCallbackManagerForRetrieverRun\u00b6\nRetrieve as you generate with FLARE", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForRetrieverRun.html"}
{"id": "4d48ab55c38c-0", "text": "langchain.schema.callbacks.tracers.langchain_v1.LangChainTracerV1\u00b6\nclass langchain.schema.callbacks.tracers.langchain_v1.LangChainTracerV1(**kwargs: Any)[source]\u00b6\nAn implementation of the SharedTracer that POSTS to the langchain endpoint.\nInitialize the LangChain tracer.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(**kwargs)\nInitialize the LangChain tracer.\nload_default_session()\nLoad the default tracing session and set it as the Tracer's session.\nload_session(session_name)\nLoad a session with the given name from the tracer.\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0inputs])\nEnd a trace for a chain run.\non_chain_error(error,\u00a0*[,\u00a0inputs])\nHandle an error for a chain run.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nStart a trace for a chain run.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for an LLM run.\non_llm_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for an LLM run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain_v1.LangChainTracerV1.html"}
{"id": "4d48ab55c38c-1", "text": "Handle an error for an LLM run.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nStart a trace for an LLM run.\non_retriever_end(documents,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for a tool run.\non_tool_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for a tool run.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nStart a trace for a tool run.\n__init__(**kwargs: Any) \u2192 None[source]\u00b6\nInitialize the LangChain tracer.\nload_default_session() \u2192 Union[TracerSessionV1, TracerSession][source]\u00b6\nLoad the default tracing session and set it as the Tracer\u2019s session.\nload_session(session_name: str) \u2192 Union[TracerSessionV1, TracerSession][source]\u00b6\nLoad a session with the given name from the tracer.\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain_v1.LangChainTracerV1.html"}
{"id": "4d48ab55c38c-2", "text": "Run on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, inputs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a chain run.\non_chain_error(error: BaseException, *, inputs: Optional[Dict[str, Any]] = None, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a chain run.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, run_type: Optional[str] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a chain run.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for an LLM run.\non_llm_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for an LLM run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain_v1.LangChainTracerV1.html"}
{"id": "4d48ab55c38c-3", "text": "Handle an error for an LLM run.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Run\u00b6\nRun on new LLM token. Only available when streaming is enabled.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for an LLM run.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain_v1.LangChainTracerV1.html"}
{"id": "4d48ab55c38c-4", "text": "End a trace for a tool run.\non_tool_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a tool run.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a tool run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain_v1.LangChainTracerV1.html"}
{"id": "158dbe5a0b0f-0", "text": "langchain.schema.callbacks.tracers.log_stream.RunState\u00b6\nclass langchain.schema.callbacks.tracers.log_stream.RunState[source]\u00b6\nState of the run.\nid: str\u00b6\nID of the run.\nstreamed_output: List[Any]\u00b6\nList of output chunks streamed by Runnable.stream()\nfinal_output: Optional[Any]\u00b6\nFinal output of the run, usually the result of aggregating (+) streamed_output.\nOnly available after the run has finished successfully.\nlogs: Dict[str, langchain.schema.callbacks.tracers.log_stream.LogEntry]\u00b6\nMap of run names to sub-runs. If filters were supplied, this list will\ncontain only the runs that matched the filters.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.log_stream.RunState.html"}
{"id": "fe55b4110643-0", "text": "langchain.schema.runnable.config.call_func_with_variable_args\u00b6\nlangchain.schema.runnable.config.call_func_with_variable_args(func: Union[Callable[[Input], Output], Callable[[Input, RunnableConfig], Output], Callable[[Input, CallbackManagerForChainRun], Output], Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]], input: Input, config: RunnableConfig, run_manager: Optional[CallbackManagerForChainRun] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nCall function that may optionally accept a run_manager and/or config.\nParameters\n(Union[Callable[[Input] (func) \u2013 Callable[[Input, CallbackManagerForChainRun], Output],\nCallable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]]):\nThe function to call.\nOutput] \u2013 Callable[[Input, CallbackManagerForChainRun], Output],\nCallable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]]):\nThe function to call.\n:paramCallable[[Input, CallbackManagerForChainRun], Output],\nCallable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]]):The function to call.\nParameters\ninput (Input) \u2013 The input to the function.\nrun_manager (CallbackManagerForChainRun) \u2013 The run manager to\npass to the function.\nconfig (RunnableConfig) \u2013 The config to pass to the function.\n**kwargs (Any) \u2013 The keyword arguments to pass to the function.\nReturns\nThe output of the function.\nReturn type\nOutput", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.config.call_func_with_variable_args.html"}
{"id": "30e1e4601905-0", "text": "langchain.schema.callbacks.tracers.log_stream.LogStreamCallbackHandler\u00b6\nclass langchain.schema.callbacks.tracers.log_stream.LogStreamCallbackHandler(*, auto_close: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None)[source]\u00b6\nA tracer that streams run logs to a stream.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(*[,\u00a0auto_close,\u00a0include_names,\u00a0...])\ninclude_run(run)\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0inputs])\nEnd a trace for a chain run.\non_chain_error(error,\u00a0*[,\u00a0inputs])\nHandle an error for a chain run.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nStart a trace for a chain run.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for an LLM run.\non_llm_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.log_stream.LogStreamCallbackHandler.html"}
{"id": "30e1e4601905-1", "text": "on_llm_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for an LLM run.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nStart a trace for an LLM run.\non_retriever_end(documents,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for a tool run.\non_tool_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for a tool run.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nStart a trace for a tool run.\n__init__(*, auto_close: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None) \u2192 None[source]\u00b6\ninclude_run(run: Run) \u2192 bool[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.log_stream.LogStreamCallbackHandler.html"}
{"id": "30e1e4601905-2", "text": "include_run(run: Run) \u2192 bool[source]\u00b6\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, inputs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a chain run.\non_chain_error(error: BaseException, *, inputs: Optional[Dict[str, Any]] = None, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a chain run.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, run_type: Optional[str] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a chain run.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for an LLM run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.log_stream.LogStreamCallbackHandler.html"}
{"id": "30e1e4601905-3", "text": "End a trace for an LLM run.\non_llm_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for an LLM run.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Run\u00b6\nRun on new LLM token. Only available when streaming is enabled.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for an LLM run.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun on a retry event.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.log_stream.LogStreamCallbackHandler.html"}
{"id": "30e1e4601905-4", "text": "Run on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a tool run.\non_tool_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a tool run.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a tool run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.log_stream.LogStreamCallbackHandler.html"}
{"id": "38bda6ab957c-0", "text": "langchain.schema.messages.BaseMessageChunk\u00b6\nclass langchain.schema.messages.BaseMessageChunk[source]\u00b6\nBases: BaseMessage\nA Message chunk, which can be concatenated with other Message chunks.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam type: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.BaseMessageChunk.html"}
{"id": "38bda6ab957c-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.BaseMessageChunk.html"}
{"id": "38bda6ab957c-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.BaseMessageChunk.html"}
{"id": "ad88c9c8f2ea-0", "text": "langchain.schema.runnable.router.RouterInput\u00b6\nclass langchain.schema.runnable.router.RouterInput[source]\u00b6\nA Router input.\nkey\u00b6\nThe key to route on.\nType\nstr\ninput\u00b6\nThe input to pass to the selected runnable.\nType\nAny\nAttributes\nkey\ninput\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.router.RouterInput.html"}
{"id": "ad88c9c8f2ea-1", "text": "items() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.router.RouterInput.html"}
{"id": "7d8db8dea3f1-0", "text": "langchain.schema.callbacks.manager.CallbackManagerForLLMRun\u00b6\nclass langchain.schema.callbacks.manager.CallbackManagerForLLMRun(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nCallback manager for LLM run.\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nMethods\n__init__(*,\u00a0run_id,\u00a0handlers,\u00a0...[,\u00a0...])\nInitialize the run manager.\nget_noop_manager()\nReturn a manager that doesn't perform any operations.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0*[,\u00a0chunk])\nRun when LLM generates a new token.\non_retry(retry_state,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when text is received.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForLLMRun.html"}
{"id": "7d8db8dea3f1-1", "text": "on_text(text,\u00a0**kwargs)\nRun when text is received.\n__init__(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nclassmethod get_noop_manager() \u2192 BRM\u00b6\nReturn a manager that doesn\u2019t perform any operations.\nReturns\nThe noop manager.\nReturn type\nBaseRunManager\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\nParameters\nresponse (LLMResult) \u2013 The LLM result.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM errors.\nParameters\nerror (Exception or KeyboardInterrupt) \u2013 The error.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, **kwargs: Any) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForLLMRun.html"}
{"id": "7d8db8dea3f1-2", "text": "Run when LLM generates a new token.\nParameters\ntoken (str) \u2013 The new token.\non_retry(retry_state: RetryCallState, **kwargs: Any) \u2192 None\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 Any\u00b6\nRun when text is received.\nParameters\ntext (str) \u2013 The received text.\nReturns\nThe result of the callback.\nReturn type\nAny\nExamples using CallbackManagerForLLMRun\u00b6\nCustom LLM", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForLLMRun.html"}
{"id": "e558f6b8edbd-0", "text": "langchain.schema.runnable.utils.IsFunctionArgDict\u00b6\nclass langchain.schema.runnable.utils.IsFunctionArgDict[source]\u00b6\nCheck if the first argument of a function is a dict.\nMethods\n__init__()\ngeneric_visit(node)\nCalled if no explicit visitor function exists for a node.\nvisit(node)\nVisit a node.\nvisit_AsyncFunctionDef(node)\nvisit_Constant(node)\nvisit_FunctionDef(node)\nvisit_Lambda(node)\n__init__() \u2192 None[source]\u00b6\ngeneric_visit(node)\u00b6\nCalled if no explicit visitor function exists for a node.\nvisit(node)\u00b6\nVisit a node.\nvisit_AsyncFunctionDef(node: AsyncFunctionDef) \u2192 Any[source]\u00b6\nvisit_Constant(node)\u00b6\nvisit_FunctionDef(node: FunctionDef) \u2192 Any[source]\u00b6\nvisit_Lambda(node: Lambda) \u2192 Any[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.IsFunctionArgDict.html"}
{"id": "f6dccca5caae-0", "text": "langchain.schema.callbacks.manager.AsyncCallbackManagerForLLMRun\u00b6\nclass langchain.schema.callbacks.manager.AsyncCallbackManagerForLLMRun(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nAsync callback manager for LLM run.\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nMethods\n__init__(*,\u00a0run_id,\u00a0handlers,\u00a0...[,\u00a0...])\nInitialize the run manager.\nget_noop_manager()\nReturn a manager that doesn't perform any operations.\non_llm_end(response,\u00a0**kwargs)\nRun when LLM ends running.\non_llm_error(error,\u00a0**kwargs)\nRun when LLM errors.\non_llm_new_token(token,\u00a0*[,\u00a0chunk])\nRun when LLM generates a new token.\non_retry(retry_state,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when text is received.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForLLMRun.html"}
{"id": "f6dccca5caae-1", "text": "on_text(text,\u00a0**kwargs)\nRun when text is received.\n__init__(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nclassmethod get_noop_manager() \u2192 BRM\u00b6\nReturn a manager that doesn\u2019t perform any operations.\nReturns\nThe noop manager.\nReturn type\nBaseRunManager\nasync on_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\nParameters\nresponse (LLMResult) \u2013 The LLM result.\nasync on_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM errors.\nParameters\nerror (Exception or KeyboardInterrupt) \u2013 The error.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForLLMRun.html"}
{"id": "f6dccca5caae-2", "text": "Run when LLM errors.\nParameters\nerror (Exception or KeyboardInterrupt) \u2013 The error.\nasync on_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM generates a new token.\nParameters\ntoken (str) \u2013 The new token.\nasync on_retry(retry_state: RetryCallState, **kwargs: Any) \u2192 None\u00b6\nRun on a retry event.\nasync on_text(text: str, **kwargs: Any) \u2192 Any\u00b6\nRun when text is received.\nParameters\ntext (str) \u2013 The received text.\nReturns\nThe result of the callback.\nReturn type\nAny", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForLLMRun.html"}
{"id": "1752d97e2e1e-0", "text": "langchain.schema.callbacks.tracers.schemas.TracerSessionV1Create\u00b6\nclass langchain.schema.callbacks.tracers.schemas.TracerSessionV1Create[source]\u00b6\nBases: TracerSessionV1Base\nCreate class for TracerSessionV1.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam extra: Optional[Dict[str, Any]] = None\u00b6\nparam name: Optional[str] = None\u00b6\nparam start_time: datetime.datetime [Optional]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSessionV1Create.html"}
{"id": "1752d97e2e1e-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSessionV1Create.html"}
{"id": "1752d97e2e1e-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSessionV1Create.html"}
{"id": "f0289bc8ffaa-0", "text": "langchain.schema.callbacks.manager.CallbackManagerForChainRun\u00b6\nclass langchain.schema.callbacks.manager.CallbackManagerForChainRun(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nCallback manager for chain run.\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nMethods\n__init__(*,\u00a0run_id,\u00a0handlers,\u00a0...[,\u00a0...])\nInitialize the run manager.\nget_child([tag])\nGet a child callback manager.\nget_noop_manager()\nReturn a manager that doesn't perform any operations.\non_agent_action(action,\u00a0**kwargs)\nRun when agent action is received.\non_agent_finish(finish,\u00a0**kwargs)\nRun when agent finish is received.\non_chain_end(outputs,\u00a0**kwargs)\nRun when chain ends running.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_retry(retry_state,\u00a0**kwargs)\nRun on a retry event.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForChainRun.html"}
{"id": "f0289bc8ffaa-1", "text": "on_retry(retry_state,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when text is received.\n__init__(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nget_child(tag: Optional[str] = None) \u2192 CallbackManager\u00b6\nGet a child callback manager.\nParameters\ntag (str, optional) \u2013 The tag for the child callback manager.\nDefaults to None.\nReturns\nThe child callback manager.\nReturn type\nCallbackManager\nclassmethod get_noop_manager() \u2192 BRM\u00b6\nReturn a manager that doesn\u2019t perform any operations.\nReturns\nThe noop manager.\nReturn type\nBaseRunManager\non_agent_action(action: AgentAction, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when agent action is received.\nParameters\naction (AgentAction) \u2013 The agent action.\nReturns", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForChainRun.html"}
{"id": "f0289bc8ffaa-2", "text": "Parameters\naction (AgentAction) \u2013 The agent action.\nReturns\nThe result of the callback.\nReturn type\nAny\non_agent_finish(finish: AgentFinish, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when agent finish is received.\nParameters\nfinish (AgentFinish) \u2013 The agent finish.\nReturns\nThe result of the callback.\nReturn type\nAny\non_chain_end(outputs: Union[Dict[str, Any], Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends running.\nParameters\noutputs (Union[Dict[str, Any], Any]) \u2013 The outputs of the chain.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.\nParameters\nerror (Exception or KeyboardInterrupt) \u2013 The error.\non_retry(retry_state: RetryCallState, **kwargs: Any) \u2192 None\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 Any\u00b6\nRun when text is received.\nParameters\ntext (str) \u2013 The received text.\nReturns\nThe result of the callback.\nReturn type\nAny\nExamples using CallbackManagerForChainRun\u00b6\nCustom chain", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForChainRun.html"}
{"id": "e45dc5e40fe8-0", "text": "langchain.schema.runnable.base.RunnableParallel\u00b6\nclass langchain.schema.runnable.base.RunnableParallel[source]\u00b6\nBases: RunnableSerializable[Input, Dict[str, Any]]\nA runnable that runs a mapping of runnables in parallel,\nand returns a mapping of their outputs.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam steps: Mapping[str, langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, Any]] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Dict[str, Any][source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Dict[str, Any]][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "e45dc5e40fe8-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Dict[str, Any]][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "e45dc5e40fe8-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "e45dc5e40fe8-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "e45dc5e40fe8-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None) \u2192 Dict[str, Any][source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "e45dc5e40fe8-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Dict[str, Any]][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Dict[str, Any]][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "e45dc5e40fe8-6", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "e45dc5e40fe8-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "e45dc5e40fe8-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableParallel.html"}
{"id": "b359b53f948e-0", "text": "langchain.schema.runnable.utils.gather_with_concurrency\u00b6\nasync langchain.schema.runnable.utils.gather_with_concurrency(n: Optional[int], *coros: Coroutine) \u2192 list[source]\u00b6\nGather coroutines with a limit on the number of concurrent coroutines.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.gather_with_concurrency.html"}
{"id": "6c54e8ef2417-0", "text": "langchain.schema.runnable.utils.ConfigurableFieldSpec\u00b6\nclass langchain.schema.runnable.utils.ConfigurableFieldSpec(id: str, name: Optional[str], description: Optional[str], default: Any, annotation: Any)[source]\u00b6\nA field that can be configured by the user. It is a specification of a field.\nCreate new instance of ConfigurableFieldSpec(id, name, description, default, annotation)\nAttributes\nannotation\nAlias for field number 4\ndefault\nAlias for field number 3\ndescription\nAlias for field number 2\nid\nAlias for field number 0\nname\nAlias for field number 1\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.ConfigurableFieldSpec.html"}
{"id": "450205991b21-0", "text": "langchain.schema.runnable.fallbacks.RunnableWithFallbacks\u00b6\nclass langchain.schema.runnable.fallbacks.RunnableWithFallbacks[source]\u00b6\nBases: RunnableSerializable[Input, Output]\nA Runnable that can fallback to other Runnables if it fails.\nExternal APIs (e.g., APIs for a language model) may at times experience\ndegraded performance or even downtime.\nIn these cases, it can be useful to have a fallback runnable that can be\nused in place of the original runnable (e.g., fallback to another LLM provider).\nFallbacks can be defined at the level of a single runnable, or at the level\nof a chain of runnables. Fallbacks are tried in order until one succeeds or\nall fail.\nWhile you can instantiate a RunnableWithFallbacks directly, it is usually\nmore convenient to use the with_fallbacks method on a runnable.\nExample\nfrom langchain.chat_models.openai import ChatOpenAI\nfrom langchain.chat_models.anthropic import ChatAnthropic\nmodel = ChatAnthropic().with_fallbacks([ChatOpenAI()])\n# Will usually use ChatAnthropic, but fallback to ChatOpenAI\n# if ChatAnthropic fails.\nmodel.invoke('hello')\n# And you can also use fallbacks at the level of a chain.\n# Here if both LLM providers fail, we'll fallback to a good hardcoded\n# response.\nfrom langchain.prompts import PromptTemplate\nfrom langchain.schema.output_parser import StrOutputParser\nfrom langchain.schema.runnable import RunnableLambda\ndef when_all_is_lost(inputs):\n    return (\"Looks like our LLM providers are down. \"\n            \"Here's a nice \ud83e\udd9c\ufe0f emoji for you instead.\")\nchain_with_fallback = (\n    PromptTemplate.from_template('Tell me a joke about {topic}')\n    | model", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "450205991b21-1", "text": "PromptTemplate.from_template('Tell me a joke about {topic}')\n    | model\n    | StrOutputParser()\n).with_fallbacks([RunnableLambda(when_all_is_lost)])\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)\u00b6\nThe exceptions on which fallbacks should be tried.\nAny exception that is not a subclass of these exceptions will be raised immediately.\nparam fallbacks: Sequence[langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output]] [Required]\u00b6\nA sequence of fallbacks to try.\nparam runnable: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nThe runnable to run first.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "450205991b21-2", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "450205991b21-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "450205991b21-4", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "450205991b21-5", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "450205991b21-6", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "450205991b21-7", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "450205991b21-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "450205991b21-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty runnables: Iterator[langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.fallbacks.RunnableWithFallbacks.html"}
{"id": "b6cfd88bc0d3-0", "text": "langchain.schema.callbacks.tracers.log_stream.RunLog\u00b6\nclass langchain.schema.callbacks.tracers.log_stream.RunLog(*ops: Dict[str, Any], state: RunState)[source]\u00b6\nA run log.\nAttributes\nstate\nCurrent state of the log, obtained from applying all ops in sequence.\nMethods\n__init__(*ops,\u00a0state)\n__init__(*ops: Dict[str, Any], state: RunState) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.log_stream.RunLog.html"}
{"id": "3dce2a10d570-0", "text": "langchain.schema.runnable.passthrough.identity\u00b6\nlangchain.schema.runnable.passthrough.identity(x: Other) \u2192 Other[source]\u00b6\nAn identity function", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.identity.html"}
{"id": "90d0744029c6-0", "text": "langchain.schema.runnable.config.RunnableConfig\u00b6\nclass langchain.schema.runnable.config.RunnableConfig[source]\u00b6\nConfiguration for a Runnable.\nAttributes\ntags\nTags for this call and any sub-calls (eg.\nmetadata\nMetadata for this call and any sub-calls (eg.\ncallbacks\nCallbacks for this call and any sub-calls (eg.\nrun_name\nName for the tracer run for this call.\nmax_concurrency\nMaximum number of parallel calls to make.\nrecursion_limit\nMaximum number of times a call can recurse.\nconfigurable\nRuntime values for attributes previously made configurable on this Runnable, or sub-Runnables, through .configurable_fields() or .configurable_alternatives().\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.config.RunnableConfig.html"}
{"id": "90d0744029c6-1", "text": "values()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6\nExamples using RunnableConfig\u00b6\nRun arbitrary functions", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.config.RunnableConfig.html"}
{"id": "f9ef8ef73296-0", "text": "langchain.schema.callbacks.stdout.StdOutCallbackHandler\u00b6\nclass langchain.schema.callbacks.stdout.StdOutCallbackHandler(color: Optional[str] = None)[source]\u00b6\nCallback Handler that prints to std out.\nInitialize callback handler.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__([color])\nInitialize callback handler.\non_agent_action(action[,\u00a0color])\nRun on agent action.\non_agent_finish(finish[,\u00a0color])\nRun on agent end.\non_chain_end(outputs,\u00a0**kwargs)\nPrint out that we finished a chain.\non_chain_error(error,\u00a0**kwargs)\nDo nothing.\non_chain_start(serialized,\u00a0inputs,\u00a0**kwargs)\nPrint out that we are entering a chain.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0**kwargs)\nDo nothing.\non_llm_error(error,\u00a0**kwargs)\nDo nothing.\non_llm_new_token(token,\u00a0**kwargs)\nDo nothing.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nPrint out the prompts.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.stdout.StdOutCallbackHandler.html"}
{"id": "f9ef8ef73296-1", "text": "Run when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text[,\u00a0color,\u00a0end])\nRun when agent ends.\non_tool_end(output[,\u00a0color,\u00a0...])\nIf not the final action, print out observation.\non_tool_error(error,\u00a0**kwargs)\nDo nothing.\non_tool_start(serialized,\u00a0input_str,\u00a0**kwargs)\nDo nothing.\n__init__(color: Optional[str] = None) \u2192 None[source]\u00b6\nInitialize callback handler.\non_agent_action(action: AgentAction, color: Optional[str] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, color: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nPrint out that we finished a chain.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) \u2192 None[source]\u00b6\nPrint out that we are entering a chain.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.stdout.StdOutCallbackHandler.html"}
{"id": "f9ef8ef73296-2", "text": "Do nothing.\non_llm_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing.\non_llm_new_token(token: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 None[source]\u00b6\nPrint out the prompts.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, color: Optional[str] = None, end: str = '', **kwargs: Any) \u2192 None[source]\u00b6\nRun when agent ends.\non_tool_end(output: str, color: Optional[str] = None, observation_prefix: Optional[str] = None, llm_prefix: Optional[str] = None, **kwargs: Any) \u2192 None[source]\u00b6\nIf not the final action, print out observation.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.stdout.StdOutCallbackHandler.html"}
{"id": "f9ef8ef73296-3", "text": "If not the final action, print out observation.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing.\non_tool_start(serialized: Dict[str, Any], input_str: str, **kwargs: Any) \u2192 None[source]\u00b6\nDo nothing.\nExamples using StdOutCallbackHandler\u00b6\nArgilla\nComet\nAim\nWeights & Biases\nClearML\nOpaquePrompts\nVector SQL Retriever with MyScale\nAsync API\nCustom chain", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.stdout.StdOutCallbackHandler.html"}
{"id": "6c0024d2fe7f-0", "text": "langchain.schema.callbacks.tracers.schemas.TracerSessionBase\u00b6\nclass langchain.schema.callbacks.tracers.schemas.TracerSessionBase[source]\u00b6\nBases: TracerSessionV1Base\nBase class for TracerSession.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam extra: Optional[Dict[str, Any]] = None\u00b6\nparam name: Optional[str] = None\u00b6\nparam start_time: datetime.datetime [Optional]\u00b6\nparam tenant_id: uuid.UUID [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSessionBase.html"}
{"id": "6c0024d2fe7f-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSessionBase.html"}
{"id": "6c0024d2fe7f-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSessionBase.html"}
{"id": "da74605e0f31-0", "text": "langchain.schema.runnable.base.RunnableSequence\u00b6\nclass langchain.schema.runnable.base.RunnableSequence[source]\u00b6\nBases: RunnableSerializable[Input, Output]\nA sequence of runnables, where the output of each is the input of the next.\nRunnableSequence is the most important composition operator in LangChain as it is\nused in virtually every chain.\nA RunnableSequence can be instantiated directly or more commonly by using the |\noperator where either the left or right operands (or both) must be a Runnable.\nAny RunnableSequence automatically supports sync, async, batch.\nThe default implementations of batch and abatch utilize threadpools and\nasyncio gather and will be faster than naive invocation of invoke or ainvoke\nfor IO bound runnables.\nBatching is implemented by invoking the batch method on each component of the\nRunnableSequence in order.\nA RunnableSequence preserves the streaming properties of its components, so if all\ncomponents of the sequence implement a transform method \u2013 which\nis the method that implements the logic to map a streaming input to a streaming\noutput \u2013 then the sequence will be able to stream input to output!\nIf any component of the sequence does not implement transform then the\nstreaming will only begin after this component is run. If there are\nmultiple blocking components, streaming begins after the last one.\nPlease note: RunnableLambdas do not support transform by default! So ifyou need to use a RunnableLambdas be careful about where you place them in a\nRunnableSequence (if you need to use the .stream()/.astream() methods).\nIf you need arbitrary logic and need streaming, you can subclass\nRunnable, and implement transform for whatever logic you need.\nHere is a simple example that uses simple functions to illustrate the use of\nRunnableSequence:\nfrom langchain.schema.runnable import RunnableLambda\ndef add_one(x: int) -> int:", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "da74605e0f31-1", "text": "def add_one(x: int) -> int:\n    return x + 1\ndef mul_two(x: int) -> int:\n    return x * 2\nrunnable_1 = RunnableLambda(add_one)\nrunnable_2 = RunnableLambda(mul_two)\nsequence = runnable_1 | runnable_2\n# Or equivalently:\n# sequence = RunnableSequence(first=runnable_1, last=runnable_2)\nsequence.invoke(1)\nawait runnable.ainvoke(1)\nsequence.batch([1, 2, 3])\nawait sequence.abatch([1, 2, 3])\nHere\u2019s an example that uses streams JSON output generated by an LLM:\nfrom langchain.output_parsers.json import SimpleJsonOutputParser\nfrom langchain.chat_models.openai import ChatOpenAI\nprompt = PromptTemplate.from_template(\n    'In JSON format, give me a list of {topic} and their '\n    'corresponding names in French, Spanish and in a '\n    'Cat Language.'\n)\nmodel = ChatOpenAI()\nchain = prompt | model | SimpleJsonOutputParser()\nasync for chunk in chain.astream({'topic': 'colors'}):\n    print('-')\n    print(chunk, sep='', flush=True)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam first: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, Any] [Required]\u00b6\nThe first runnable in the sequence.\nparam last: langchain.schema.runnable.base.Runnable[Any, langchain.schema.runnable.utils.Output] [Required]\u00b6\nThe last runnable in the sequence.\nparam middle: List[langchain.schema.runnable.base.Runnable[Any, Any]] [Optional]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "da74605e0f31-2", "text": "The middle runnables in the sequence.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "da74605e0f31-3", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "da74605e0f31-4", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "da74605e0f31-5", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "da74605e0f31-6", "text": "This method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "da74605e0f31-7", "text": "Return a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "da74605e0f31-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "da74605e0f31-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty steps: List[langchain.schema.runnable.base.Runnable[Any, Any]]\u00b6\nAll the runnables that make up the sequence in order.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSequence.html"}
{"id": "4108ac0d5bbf-0", "text": "langchain.schema.runnable.base.coerce_to_runnable\u00b6\nlangchain.schema.runnable.base.coerce_to_runnable(thing: Union[Runnable[Input, Output], Callable[[Input], Output], Callable[[Input], Awaitable[Output]], Callable[[Iterator[Input]], Iterator[Output]], Callable[[AsyncIterator[Input]], AsyncIterator[Output]], Mapping[str, Any]]) \u2192 Runnable[Input, Output][source]\u00b6\nCoerce a runnable-like object into a Runnable.\nParameters\nthing \u2013 A runnable-like object.\nReturns\nA Runnable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.coerce_to_runnable.html"}
{"id": "1dea8168a532-0", "text": "langchain.schema.callbacks.tracers.langchain.wait_for_all_tracers\u00b6\nlangchain.schema.callbacks.tracers.langchain.wait_for_all_tracers() \u2192 None[source]\u00b6\nWait for all tracers to finish.\nExamples using wait_for_all_tracers\u00b6\nLangSmith Walkthrough", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain.wait_for_all_tracers.html"}
{"id": "9291e561746b-0", "text": "langchain.schema.messages.messages_from_dict\u00b6\nlangchain.schema.messages.messages_from_dict(messages: List[dict]) \u2192 List[BaseMessage][source]\u00b6\nConvert a sequence of messages from dicts to Message objects.\nParameters\nmessages \u2013 Sequence of messages (as dicts) to convert.\nReturns\nList of messages (BaseMessages).", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.messages_from_dict.html"}
{"id": "e0c81b2f553c-0", "text": "langchain.schema.runnable.config.EmptyDict\u00b6\nclass langchain.schema.runnable.config.EmptyDict[source]\u00b6\nEmpty dict type.\nMethods\n__init__(*args,\u00a0**kwargs)\nclear()\ncopy()\nfromkeys([value])\nCreate a new dictionary with keys from iterable and values set to value.\nget(key[,\u00a0default])\nReturn the value for key if key is in the dictionary, else default.\nitems()\nkeys()\npop(k[,d])\nIf the key is not found, return the default if given; otherwise, raise a KeyError.\npopitem()\nRemove and return a (key, value) pair as a 2-tuple.\nsetdefault(key[,\u00a0default])\nInsert key with a value of default if key is not in the dictionary.\nupdate([E,\u00a0]**F)\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]\nvalues()\n__init__(*args, **kwargs)\u00b6\nclear() \u2192 None.\u00a0 Remove all items from D.\u00b6\ncopy() \u2192 a shallow copy of D\u00b6\nfromkeys(value=None, /)\u00b6\nCreate a new dictionary with keys from iterable and values set to value.\nget(key, default=None, /)\u00b6\nReturn the value for key if key is in the dictionary, else default.\nitems() \u2192 a set-like object providing a view on D's items\u00b6\nkeys() \u2192 a set-like object providing a view on D's keys\u00b6\npop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.config.EmptyDict.html"}
{"id": "e0c81b2f553c-1", "text": "pop(k[, d]) \u2192 v, remove specified key and return the corresponding value.\u00b6\nIf the key is not found, return the default if given; otherwise,\nraise a KeyError.\npopitem()\u00b6\nRemove and return a (key, value) pair as a 2-tuple.\nPairs are returned in LIFO (last-in, first-out) order.\nRaises KeyError if the dict is empty.\nsetdefault(key, default=None, /)\u00b6\nInsert key with a value of default if key is not in the dictionary.\nReturn the value for key if key is in the dictionary, else default.\nupdate([E, ]**F) \u2192 None.\u00a0 Update D from dict/iterable E and F.\u00b6\nIf E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\nIf E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\nIn either case, this is followed by: for k in F:  D[k] = F[k]\nvalues() \u2192 an object providing a view on D's values\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.config.EmptyDict.html"}
{"id": "31f4493a812a-0", "text": "langchain.schema.output.ChatGeneration\u00b6\nclass langchain.schema.output.ChatGeneration[source]\u00b6\nBases: Generation\nA single chat generation output.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam generation_info: Optional[Dict[str, Any]] = None\u00b6\nRaw response from the provider. May include things like the\nreason for finishing or token log probabilities.\nparam message: langchain.schema.messages.BaseMessage [Required]\u00b6\nThe message output by the chat model.\nparam text: str = ''\u00b6\nSHOULD NOT BE SET DIRECTLY The text contents of the output message.\nparam type: Literal['ChatGeneration'] = 'ChatGeneration'\u00b6\nType is used exclusively for serialization purposes.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.ChatGeneration.html"}
{"id": "31f4493a812a-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.ChatGeneration.html"}
{"id": "31f4493a812a-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.ChatGeneration.html"}
{"id": "8f2d1a70ec78-0", "text": "langchain.schema.callbacks.tracers.schemas.BaseRun\u00b6\nclass langchain.schema.callbacks.tracers.schemas.BaseRun[source]\u00b6\nBases: BaseModel\nBase class for Run.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam child_execution_order: int [Required]\u00b6\nparam end_time: datetime.datetime [Optional]\u00b6\nparam error: Optional[str] = None\u00b6\nparam execution_order: int [Required]\u00b6\nparam extra: Optional[Dict[str, Any]] = None\u00b6\nparam parent_uuid: Optional[str] = None\u00b6\nparam serialized: Dict[str, Any] [Required]\u00b6\nparam session_id: int [Required]\u00b6\nparam start_time: datetime.datetime [Optional]\u00b6\nparam uuid: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.BaseRun.html"}
{"id": "8f2d1a70ec78-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.BaseRun.html"}
{"id": "8f2d1a70ec78-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.BaseRun.html"}
{"id": "6452eacbb973-0", "text": "langchain.schema.runnable.utils.aadd\u00b6\nasync langchain.schema.runnable.utils.aadd(addables: AsyncIterable[Addable]) \u2192 Optional[Addable][source]\u00b6\nAsynchronously add a sequence of addable objects together.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.aadd.html"}
{"id": "73127e01efc3-0", "text": "langchain.schema.runnable.config.ensure_config\u00b6\nlangchain.schema.runnable.config.ensure_config(config: Optional[RunnableConfig] = None) \u2192 RunnableConfig[source]\u00b6\nEnsure that a config is a dict with all keys present.\nParameters\nconfig (Optional[RunnableConfig], optional) \u2013 The config to ensure.\nDefaults to None.\nReturns\nThe ensured config.\nReturn type\nRunnableConfig", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.config.ensure_config.html"}
{"id": "6ca4b12e8ca8-0", "text": "langchain.schema.output.GenerationChunk\u00b6\nclass langchain.schema.output.GenerationChunk[source]\u00b6\nBases: Generation\nA Generation chunk, which can be concatenated with other Generation chunks.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam generation_info: Optional[Dict[str, Any]] = None\u00b6\nRaw response from the provider. May include things like the\nreason for finishing or token log probabilities.\nparam text: str [Required]\u00b6\nGenerated text output.\nparam type: Literal['Generation'] = 'Generation'\u00b6\nType is used exclusively for serialization purposes.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.GenerationChunk.html"}
{"id": "6ca4b12e8ca8-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.GenerationChunk.html"}
{"id": "6ca4b12e8ca8-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.GenerationChunk.html"}
{"id": "b041dea9f01d-0", "text": "langchain.schema.messages.FunctionMessage\u00b6\nclass langchain.schema.messages.FunctionMessage[source]\u00b6\nBases: BaseMessage\nA Message for passing the result of executing a function back to a model.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam name: str [Required]\u00b6\nThe name of the function that was executed.\nparam type: Literal['function'] = 'function'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.FunctionMessage.html"}
{"id": "b041dea9f01d-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.FunctionMessage.html"}
{"id": "b041dea9f01d-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.FunctionMessage.html"}
{"id": "ecd3f7d27cf9-0", "text": "langchain.schema.runnable.retry.RunnableRetry\u00b6\nclass langchain.schema.runnable.retry.RunnableRetry[source]\u00b6\nBases: RunnableBindingBase[Input, Output]\nRetry a Runnable if it fails.\nA RunnableRetry helps can be used to add retry logic to any object\nthat subclasses the base Runnable.\nSuch retries are especially useful for network calls that may fail\ndue to transient errors.\nThe RunnableRetry is implemented as a RunnableBinding. The easiest\nway to use it is through the .with_retry() method on all Runnables.\nExample:\nHere\u2019s an example that uses a RunnableLambda to raise an exception\nimport time\ndef foo(input) -> None:\n    '''Fake function that raises an exception.'''\n    raise ValueError(\"Invoking foo failed. At time {time.time()}\")\nrunnable = RunnableLambda(foo)\nrunnable_with_retries = runnable.with_retry(\n    retry_exception_types=(ValueError,), # Retry only on ValueError\n    wait_exponential_jitter=True, # Add jitter to the exponential backoff\n    max_attempt_number=2, # Try twice\n)\n# The method invocation above is equivalent to the longer form below:\nrunnable_with_retries = RunnableRetry(\n    bound=runnable,\n    retry_exception_types=(ValueError,),\n    max_attempt_number=2,\n    wait_exponential_jitter=True\n)\nThis logic can be used to retry any Runnable, including a chain of Runnables,\nbut in general it\u2019s best practice to keep the scope of the retry as small as\npossible. For example, if you have a chain of Runnables, you should only retry\nthe Runnable that is likely to fail, not the entire chain.\nExample\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.prompts import PromptTemplate", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "ecd3f7d27cf9-1", "text": "from langchain.chat_models import ChatOpenAI\nfrom langchain.prompts import PromptTemplate\ntemplate = PromptTemplate.from_template(\"tell me a joke about {topic}.\")\nmodel = ChatOpenAI(temperature=0.5)\n# Good\nchain = template | model.with_retry()\n# Bad\nchain = template | model\nretryable_chain = chain.with_retry()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bound: Runnable[Input, Output] [Required]\u00b6\nparam config: RunnableConfig [Optional]\u00b6\nparam config_factories: List[Callable[[RunnableConfig], RunnableConfig]] [Optional]\u00b6\nparam custom_input_type: Optional[Any] = None\u00b6\nparam custom_output_type: Optional[Any] = None\u00b6\nparam kwargs: Mapping[str, Any] [Optional]\u00b6\nparam max_attempt_number: int = 3\u00b6\nThe maximum number of attempts to retry the runnable.\nparam retry_exception_types: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)\u00b6\nThe exception types to retry on. By default all exceptions are retried.\nIn general you should only retry on exceptions that are likely to be\ntransient, such as network errors.\nGood exceptions to retry are all server errors (5xx) and selected client\nerrors (4xx) such as 429 Too Many Requests.\nparam wait_exponential_jitter: bool = True\u00b6\nWhether to add jitter to the exponential backoff.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "ecd3f7d27cf9-2", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "ecd3f7d27cf9-3", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[Output][source]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "ecd3f7d27cf9-4", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "ecd3f7d27cf9-5", "text": "Get a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "ecd3f7d27cf9-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "ecd3f7d27cf9-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "ecd3f7d27cf9-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "ecd3f7d27cf9-9", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.retry.RunnableRetry.html"}
{"id": "130068305dea-0", "text": "langchain.schema.chat.ChatSession\u00b6\nclass langchain.schema.chat.ChatSession[source]\u00b6\nChat Session represents a single\nconversation, channel, or other group of messages.\nmessages: Sequence[langchain.schema.messages.BaseMessage]\u00b6\nThe LangChain chat messages loaded from the source.\nfunctions: Sequence[dict]\u00b6\nThe function calling specs for the messages.\nExamples using ChatSession\u00b6\nSlack\nWhatsApp\niMessage\nTelegram\nDiscord", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.chat.ChatSession.html"}
{"id": "8b30b7e5e4ff-0", "text": "langchain.schema.language_model.BaseLanguageModel\u00b6\nclass langchain.schema.language_model.BaseLanguageModel[source]\u00b6\nBases: RunnableSerializable[Union[PromptValue, str, List[BaseMessage]], LanguageModelOutput], ABC\nAbstract base class for interfacing with language models.\nAll language model wrappers inherit from BaseLanguageModel.\nExposes three main methods:\n- generate_prompt: generate language model outputs for a sequence of prompt\nvalues. A prompt value is a model input that can be converted to any language\nmodel input format (string or messages).\npredict: pass in a single string to a language model and return a stringprediction.\npredict_messages: pass in a sequence of BaseMessages (corresponding to a singlemodel call) to a language model and return a BaseMessage prediction.\nEach of these has an equivalent asynchronous method.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nabstract async agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Callbacks = None, **kwargs: Any) \u2192 LLMResult[source]\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.language_model.BaseLanguageModel.html"}
{"id": "8b30b7e5e4ff-1", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nabstract async apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.language_model.BaseLanguageModel.html"}
{"id": "8b30b7e5e4ff-2", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nabstract async apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage[source]\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.language_model.BaseLanguageModel.html"}
{"id": "8b30b7e5e4ff-3", "text": "Output is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.language_model.BaseLanguageModel.html"}
{"id": "8b30b7e5e4ff-4", "text": "configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.language_model.BaseLanguageModel.html"}
{"id": "8b30b7e5e4ff-5", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\nabstract generate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Callbacks = None, **kwargs: Any) \u2192 LLMResult[source]\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.language_model.BaseLanguageModel.html"}
{"id": "8b30b7e5e4ff-6", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int[source]\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int[source]\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int][source]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.language_model.BaseLanguageModel.html"}
{"id": "8b30b7e5e4ff-7", "text": "abstract invoke(input: Input, config: Optional[RunnableConfig] = None) \u2192 Output\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.language_model.BaseLanguageModel.html"}
{"id": "8b30b7e5e4ff-8", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nabstract predict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nabstract predict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage[source]\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.language_model.BaseLanguageModel.html"}
{"id": "8b30b7e5e4ff-9", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.language_model.BaseLanguageModel.html"}
{"id": "8b30b7e5e4ff-10", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.language_model.BaseLanguageModel.html"}
{"id": "8b30b7e5e4ff-11", "text": "property InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using BaseLanguageModel\u00b6\nCustom chain", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.language_model.BaseLanguageModel.html"}
{"id": "a343556478a7-0", "text": "langchain.schema.callbacks.manager.CallbackManagerForRetrieverRun\u00b6\nclass langchain.schema.callbacks.manager.CallbackManagerForRetrieverRun(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nCallback manager for retriever run.\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nMethods\n__init__(*,\u00a0run_id,\u00a0handlers,\u00a0...[,\u00a0...])\nInitialize the run manager.\nget_child([tag])\nGet a child callback manager.\nget_noop_manager()\nReturn a manager that doesn't perform any operations.\non_retriever_end(documents,\u00a0**kwargs)\nRun when retriever ends running.\non_retriever_error(error,\u00a0**kwargs)\nRun when retriever errors.\non_retry(retry_state,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when text is received.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForRetrieverRun.html"}
{"id": "a343556478a7-1", "text": "on_text(text,\u00a0**kwargs)\nRun when text is received.\n__init__(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nget_child(tag: Optional[str] = None) \u2192 CallbackManager\u00b6\nGet a child callback manager.\nParameters\ntag (str, optional) \u2013 The tag for the child callback manager.\nDefaults to None.\nReturns\nThe child callback manager.\nReturn type\nCallbackManager\nclassmethod get_noop_manager() \u2192 BRM\u00b6\nReturn a manager that doesn\u2019t perform any operations.\nReturns\nThe noop manager.\nReturn type\nBaseRunManager\non_retriever_end(documents: Sequence[Document], **kwargs: Any) \u2192 None[source]\u00b6\nRun when retriever ends running.\non_retriever_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when retriever errors.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForRetrieverRun.html"}
{"id": "a343556478a7-2", "text": "Run when retriever errors.\non_retry(retry_state: RetryCallState, **kwargs: Any) \u2192 None\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 Any\u00b6\nRun when text is received.\nParameters\ntext (str) \u2013 The received text.\nReturns\nThe result of the callback.\nReturn type\nAny\nExamples using CallbackManagerForRetrieverRun\u00b6\nRetrieve as you generate with FLARE", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForRetrieverRun.html"}
{"id": "29ac32343a6a-0", "text": "langchain.schema.callbacks.tracers.base.BaseTracer\u00b6\nclass langchain.schema.callbacks.tracers.base.BaseTracer(**kwargs: Any)[source]\u00b6\nBase interface for tracers.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(**kwargs)\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0inputs])\nEnd a trace for a chain run.\non_chain_error(error,\u00a0*[,\u00a0inputs])\nHandle an error for a chain run.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nStart a trace for a chain run.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for an LLM run.\non_llm_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for an LLM run.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nStart a trace for an LLM run.\non_retriever_end(documents,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever ends running.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.base.BaseTracer.html"}
{"id": "29ac32343a6a-1", "text": "Run when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for a tool run.\non_tool_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for a tool run.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nStart a trace for a tool run.\n__init__(**kwargs: Any) \u2192 None[source]\u00b6\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, inputs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Run[source]\u00b6\nEnd a trace for a chain run.\non_chain_error(error: BaseException, *, inputs: Optional[Dict[str, Any]] = None, run_id: UUID, **kwargs: Any) \u2192 Run[source]\u00b6\nHandle an error for a chain run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.base.BaseTracer.html"}
{"id": "29ac32343a6a-2", "text": "Handle an error for a chain run.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, run_type: Optional[str] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run[source]\u00b6\nStart a trace for a chain run.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, **kwargs: Any) \u2192 Run[source]\u00b6\nEnd a trace for an LLM run.\non_llm_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run[source]\u00b6\nHandle an error for an LLM run.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Run[source]\u00b6\nRun on new LLM token. Only available when streaming is enabled.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.base.BaseTracer.html"}
{"id": "29ac32343a6a-3", "text": "Start a trace for an LLM run.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, **kwargs: Any) \u2192 Run[source]\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run[source]\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run[source]\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, **kwargs: Any) \u2192 Run[source]\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, **kwargs: Any) \u2192 Run[source]\u00b6\nEnd a trace for a tool run.\non_tool_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run[source]\u00b6\nHandle an error for a tool run.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run[source]\u00b6\nStart a trace for a tool run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.base.BaseTracer.html"}
{"id": "c59ee4ccf988-0", "text": "langchain.schema.callbacks.manager.handle_event\u00b6\nlangchain.schema.callbacks.manager.handle_event(handlers: List[BaseCallbackHandler], event_name: str, ignore_condition_name: Optional[str], *args: Any, **kwargs: Any) \u2192 None[source]\u00b6\nGeneric event handler for CallbackManager.\nNote: This function is used by langserve to handle events.\nParameters\nhandlers \u2013 The list of handlers that will handle the event\nevent_name \u2013 The name of the event (e.g., \u201con_llm_start\u201d)\nignore_condition_name \u2013 Name of the attribute defined on handler\nthat if True will cause the handler to be skipped for the given event\n*args \u2013 The arguments to pass to the event handler\n**kwargs \u2013 The keyword arguments to pass to the event handler", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.handle_event.html"}
{"id": "1c42795eb5dd-0", "text": "langchain.schema.messages.get_buffer_string\u00b6\nlangchain.schema.messages.get_buffer_string(messages: Sequence[BaseMessage], human_prefix: str = 'Human', ai_prefix: str = 'AI') \u2192 str[source]\u00b6\nConvert sequence of Messages to strings and concatenate them into one string.\nArgs:messages: Messages to be converted to strings.\nhuman_prefix: The prefix to prepend to contents of HumanMessages.\nai_prefix: THe prefix to prepend to contents of AIMessages.\nReturns:A single string concatenation of all input messages.\nExample:from langchain.schema import AIMessage, HumanMessage\nmessages = [\n    HumanMessage(content=\"Hi, how are you?\"),\n    AIMessage(content=\"Good, how are you?\"),\n]\nget_buffer_string(messages)\n# -> \"Human: Hi, how are you?\nAI: Good, how are you?\u201d", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.get_buffer_string.html"}
{"id": "2bf196a59c74-0", "text": "langchain.schema.messages.FunctionMessageChunk\u00b6\nclass langchain.schema.messages.FunctionMessageChunk[source]\u00b6\nBases: FunctionMessage, BaseMessageChunk\nA Function Message chunk.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam name: str [Required]\u00b6\nThe name of the function that was executed.\nparam type: Literal['FunctionMessageChunk'] = 'FunctionMessageChunk'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.FunctionMessageChunk.html"}
{"id": "2bf196a59c74-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.FunctionMessageChunk.html"}
{"id": "2bf196a59c74-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.FunctionMessageChunk.html"}
{"id": "2f3197cef53f-0", "text": "langchain.schema.callbacks.tracers.langchain_v1.get_headers\u00b6\nlangchain.schema.callbacks.tracers.langchain_v1.get_headers() \u2192 Dict[str, Any][source]\u00b6\nGet the headers for the LangChain API.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain_v1.get_headers.html"}
{"id": "a8e14fa9a6c5-0", "text": "langchain.schema.runnable.config.get_callback_manager_for_config\u00b6\nlangchain.schema.runnable.config.get_callback_manager_for_config(config: RunnableConfig) \u2192 CallbackManager[source]\u00b6\nGet a callback manager for a config.\nParameters\nconfig (RunnableConfig) \u2013 The config.\nReturns\nThe callback manager.\nReturn type\nCallbackManager", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.config.get_callback_manager_for_config.html"}
{"id": "a2716685f162-0", "text": "langchain.schema.callbacks.tracers.schemas.ToolRun\u00b6\nclass langchain.schema.callbacks.tracers.schemas.ToolRun[source]\u00b6\nBases: BaseRun\nClass for ToolRun.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam action: str [Required]\u00b6\nparam child_chain_runs: List[langchain.schema.callbacks.tracers.schemas.ChainRun] [Optional]\u00b6\nparam child_execution_order: int [Required]\u00b6\nparam child_llm_runs: List[langchain.schema.callbacks.tracers.schemas.LLMRun] [Optional]\u00b6\nparam child_tool_runs: List[langchain.schema.callbacks.tracers.schemas.ToolRun] [Optional]\u00b6\nparam end_time: datetime.datetime [Optional]\u00b6\nparam error: Optional[str] = None\u00b6\nparam execution_order: int [Required]\u00b6\nparam extra: Optional[Dict[str, Any]] = None\u00b6\nparam output: Optional[str] = None\u00b6\nparam parent_uuid: Optional[str] = None\u00b6\nparam serialized: Dict[str, Any] [Required]\u00b6\nparam session_id: int [Required]\u00b6\nparam start_time: datetime.datetime [Optional]\u00b6\nparam tool_input: str [Required]\u00b6\nparam uuid: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.ToolRun.html"}
{"id": "a2716685f162-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.ToolRun.html"}
{"id": "a2716685f162-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.ToolRun.html"}
{"id": "306fb54c6095-0", "text": "langchain.schema.callbacks.tracers.log_stream.RunLogPatch\u00b6\nclass langchain.schema.callbacks.tracers.log_stream.RunLogPatch(*ops: Dict[str, Any])[source]\u00b6\nA patch to the run log.\nAttributes\nops\nList of jsonpatch operations, which describe how to create the run state from an empty dict.\nMethods\n__init__(*ops)\n__init__(*ops: Dict[str, Any]) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.log_stream.RunLogPatch.html"}
{"id": "7e7197cb7d3e-0", "text": "langchain.schema.runnable.config.patch_config\u00b6\nlangchain.schema.runnable.config.patch_config(config: Optional[RunnableConfig], *, callbacks: Optional[BaseCallbackManager] = None, recursion_limit: Optional[int] = None, max_concurrency: Optional[int] = None, run_name: Optional[str] = None, configurable: Optional[Dict[str, Any]] = None) \u2192 RunnableConfig[source]\u00b6\nPatch a config with new values.\nParameters\nconfig (Optional[RunnableConfig]) \u2013 The config to patch.\ncopy_locals (bool, optional) \u2013 Whether to copy locals. Defaults to False.\ncallbacks (Optional[BaseCallbackManager], optional) \u2013 The callbacks to set.\nDefaults to None.\nrecursion_limit (Optional[int], optional) \u2013 The recursion limit to set.\nDefaults to None.\nmax_concurrency (Optional[int], optional) \u2013 The max concurrency to set.\nDefaults to None.\nrun_name (Optional[str], optional) \u2013 The run name to set. Defaults to None.\nconfigurable (Optional[Dict[str, Any]], optional) \u2013 The configurable to set.\nDefaults to None.\nReturns\nThe patched config.\nReturn type\nRunnableConfig", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.config.patch_config.html"}
{"id": "16449014e5d1-0", "text": "langchain.schema.agent.AgentAction\u00b6\nclass langchain.schema.agent.AgentAction[source]\u00b6\nBases: Serializable\nA full description of an action for an ActionAgent to execute.\nOverride init to support instantiation by position for backward compat.\nparam log: str [Required]\u00b6\nAdditional information to log about the action.\nThis log can be used in a few ways. First, it can be used to audit\nwhat exactly the LLM predicted to lead to this (tool, tool_input).\nSecond, it can be used in future iterations to show the LLMs prior\nthoughts. This is useful when (tool, tool_input) does not contain\nfull information about the LLM prediction (for example, any thought\nbefore the tool/tool_input).\nparam tool: str [Required]\u00b6\nThe name of the Tool to execute.\nparam tool_input: Union[str, dict] [Required]\u00b6\nThe input to pass in to the Tool.\nparam type: Literal['AgentAction'] = 'AgentAction'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.agent.AgentAction.html"}
{"id": "16449014e5d1-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.agent.AgentAction.html"}
{"id": "16449014e5d1-2", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using AgentAction\u00b6\nCustom Trajectory Evaluator\nAgents\nPlug-and-Plai\nWikibase Agent", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.agent.AgentAction.html"}
{"id": "16449014e5d1-3", "text": "Custom Trajectory Evaluator\nAgents\nPlug-and-Plai\nWikibase Agent\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nCustom Agent with PlugIn Retrieval\nMultiple callback handlers\nCustom multi-action agent\nCustom agent\nCustom agent with tool retrieval", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.agent.AgentAction.html"}
{"id": "56eb57d54868-0", "text": "langchain.schema.callbacks.base.AsyncCallbackHandler\u00b6\nclass langchain.schema.callbacks.base.AsyncCallbackHandler[source]\u00b6\nAsync callback handler that handles callbacks from LangChain.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__()\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when chain ends running.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when LLM ends running.\non_llm_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when LLM errors.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on retriever end.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on retriever error.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.AsyncCallbackHandler.html"}
{"id": "56eb57d54868-1", "text": "Run on retriever error.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun on retriever start.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id,\u00a0tags])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when tool ends running.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\n__init__()\u00b6\nasync on_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun on agent action.\nasync on_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun on agent end.\nasync on_chain_end(outputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain ends running.\nasync on_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.AsyncCallbackHandler.html"}
{"id": "56eb57d54868-2", "text": "Run when chain errors.\nasync on_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain starts running.\nasync on_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when a chat model starts running.\nasync on_llm_end(response: LLMResult, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM ends running.\nasync on_llm_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM errors.\nasync on_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun on new LLM token. Only available when streaming is enabled.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.AsyncCallbackHandler.html"}
{"id": "56eb57d54868-3", "text": "Run on new LLM token. Only available when streaming is enabled.\nasync on_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when LLM starts running.\nasync on_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun on retriever end.\nasync on_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun on retriever error.\nasync on_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun on retriever start.\nasync on_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on a retry event.\nasync on_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun on arbitrary text.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.AsyncCallbackHandler.html"}
{"id": "56eb57d54868-4", "text": "Run on arbitrary text.\nasync on_tool_end(output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.\nasync on_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool errors.\nasync on_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool starts running.\nExamples using AsyncCallbackHandler\u00b6\nAsync callbacks", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.AsyncCallbackHandler.html"}
{"id": "d7c80d791d8d-0", "text": "langchain.schema.runnable.config.acall_func_with_variable_args\u00b6\nasync langchain.schema.runnable.config.acall_func_with_variable_args(func: Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]], input: Input, config: RunnableConfig, run_manager: Optional[AsyncCallbackManagerForChainRun] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nCall function that may optionally accept a run_manager and/or config.\nParameters\n(Union[Callable[[Input] (func) \u2013 AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,\nAsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):\nThe function to call.\nAwaitable[Output]] \u2013 AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,\nAsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):\nThe function to call.\nCallable[[Input \u2013 AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,\nAsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):\nThe function to call.\n:paramAsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):\nThe function to call.\nParameters\ninput (Input) \u2013 The input to the function.\nrun_manager (AsyncCallbackManagerForChainRun) \u2013 The run manager\nto pass to the function.\nconfig (RunnableConfig) \u2013 The config to pass to the function.\n**kwargs (Any) \u2013 The keyword arguments to pass to the function.\nReturns\nThe output of the function.\nReturn type\nOutput", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.config.acall_func_with_variable_args.html"}
{"id": "c6efaf936362-0", "text": "langchain.schema.output_parser.OutputParserException\u00b6\nclass langchain.schema.output_parser.OutputParserException(error: Any, observation: Optional[str] = None, llm_output: Optional[str] = None, send_to_llm: bool = False)[source]\u00b6\nException that output parsers should raise to signify a parsing error.\nThis exists to differentiate parsing errors from other code or execution errors\nthat also may arise inside the output parser. OutputParserExceptions will be\navailable to catch and handle in ways to fix the parsing error, while other\nerrors will be raised.\nParameters\nerror \u2013 The error that\u2019s being re-raised or an error message.\nobservation \u2013 String explanation of error which can be passed to a\nmodel to try and remediate the issue.\nllm_output \u2013 String model output which is error-ing.\nsend_to_llm \u2013 Whether to send the observation and llm_output back to an Agent\nafter an OutputParserException has been raised. This gives the underlying\nmodel driving the agent the context that the previous output was improperly\nstructured, in the hopes that it will update the output to the correct\nformat.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.OutputParserException.html"}
{"id": "5a8e3a679f7a-0", "text": "langchain.schema.runnable.config.get_config_list\u00b6\nlangchain.schema.runnable.config.get_config_list(config: Optional[Union[RunnableConfig, List[RunnableConfig]]], length: int) \u2192 List[RunnableConfig][source]\u00b6\nGet a list of configs from a single config or a list of configs.\nIt is useful for subclasses overriding batch() or abatch().\nParameters\nconfig (Optional[Union[RunnableConfig, List[RunnableConfig]]]) \u2013 The config or list of configs.\nlength (int) \u2013 The length of the list.\nReturns\nThe list of configs.\nReturn type\nList[RunnableConfig]\nRaises\nValueError \u2013 If the length of the list is not equal to the length of the inputs.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.config.get_config_list.html"}
{"id": "08af5e063a05-0", "text": "langchain.schema.storage.BaseStore\u00b6\nclass langchain.schema.storage.BaseStore[source]\u00b6\nAbstract interface for a key-value store.\nMethods\n__init__()\nmdelete(keys)\nDelete the given keys and their associated values.\nmget(keys)\nGet the values associated with the given keys.\nmset(key_value_pairs)\nSet the values for the given keys.\nyield_keys(*[,\u00a0prefix])\nGet an iterator over keys that match the given prefix.\n__init__()\u00b6\nabstract mdelete(keys: Sequence[K]) \u2192 None[source]\u00b6\nDelete the given keys and their associated values.\nParameters\nkeys (Sequence[K]) \u2013 A sequence of keys to delete.\nabstract mget(keys: Sequence[K]) \u2192 List[Optional[V]][source]\u00b6\nGet the values associated with the given keys.\nParameters\nkeys (Sequence[K]) \u2013 A sequence of keys.\nReturns\nA sequence of optional values associated with the keys.\nIf a key is not found, the corresponding value will be None.\nabstract mset(key_value_pairs: Sequence[Tuple[K, V]]) \u2192 None[source]\u00b6\nSet the values for the given keys.\nParameters\nkey_value_pairs (Sequence[Tuple[K, V]]) \u2013 A sequence of key-value pairs.\nabstract yield_keys(*, prefix: Optional[str] = None) \u2192 Union[Iterator[K], Iterator[str]][source]\u00b6\nGet an iterator over keys that match the given prefix.\nParameters\nprefix (str) \u2013 The prefix to match.\nReturns\nAn iterator over keys that match the given prefix.\nThis method is allowed to return an iterator over either K or str\ndepending on what makes more sense for the given store.\nReturn type\nIterator[K | str]", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.storage.BaseStore.html"}
{"id": "345b08b5d37b-0", "text": "langchain.schema.callbacks.tracers.schemas.Run\u00b6\nclass langchain.schema.callbacks.tracers.schemas.Run[source]\u00b6\nBases: RunBase\nRun schema for the V2 API in the Tracer.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam child_execution_order: int [Required]\u00b6\nparam child_runs: List[langchain.schema.callbacks.tracers.schemas.Run] [Optional]\u00b6\nparam end_time: Optional[<module 'datetime' from '/home/docs/.asdf/installs/python/3.11.6/lib/python3.11/datetime.py'>] = None\u00b6\nEnd time of the run, if applicable.\nparam error: Optional[str] = None\u00b6\nError message, if the run encountered any issues.\nparam events: List[Dict[str, Any]] [Optional]\u00b6\nList of events associated with the run, like\nstart and end events.\nparam execution_order: int [Required]\u00b6\nparam extra: Optional[dict] = None\u00b6\nAdditional metadata or settings related to the run.\nparam id: uuid.UUID [Required]\u00b6\nUnique identifier for the run.\nparam inputs: dict [Required]\u00b6\nInputs used for the run.\nparam name: str [Required]\u00b6\nHuman-readable name for the run.\nparam outputs: Optional[dict] = None\u00b6\nOutputs generated by the run, if any.\nparam parent_run_id: Optional[uuid.UUID] = None\u00b6\nIdentifier for a parent run, if this run is a sub-run.\nparam reference_example_id: Optional[uuid.UUID] = None\u00b6\nReference to an example that this run may be based on.\nparam run_type: str [Required]\u00b6\nThe type of run, such as tool, chain, llm, retriever,", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.Run.html"}
{"id": "345b08b5d37b-1", "text": "The type of run, such as tool, chain, llm, retriever,\nembedding, prompt, parser.\nparam serialized: Optional[dict] = None\u00b6\nSerialized object that executed the run for potential reuse.\nparam start_time: <module 'datetime' from '/home/docs/.asdf/installs/python/3.11.6/lib/python3.11/datetime.py'> [Required]\u00b6\nStart time of the run.\nparam tags: Optional[List[str]] [Optional]\u00b6\nTags for categorizing or annotating the run.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.Run.html"}
{"id": "345b08b5d37b-2", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.Run.html"}
{"id": "345b08b5d37b-3", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.Run.html"}
{"id": "d407a2a79f4f-0", "text": "langchain.schema.runnable.utils.SupportsAdd\u00b6\nclass langchain.schema.runnable.utils.SupportsAdd(*args, **kwargs)[source]\u00b6\nProtocol for objects that support addition.\nMethods\n__init__(*args,\u00a0**kwargs)\n__init__(*args, **kwargs)\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.SupportsAdd.html"}
{"id": "077154bdb8a5-0", "text": "langchain.schema.callbacks.tracers.stdout.ConsoleCallbackHandler\u00b6\nclass langchain.schema.callbacks.tracers.stdout.ConsoleCallbackHandler(**kwargs: Any)[source]\u00b6\nTracer that prints to the console.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nname\nraise_error\nrun_inline\nMethods\n__init__(**kwargs)\nget_breadcrumbs(run)\nget_parents(run)\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0inputs])\nEnd a trace for a chain run.\non_chain_error(error,\u00a0*[,\u00a0inputs])\nHandle an error for a chain run.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nStart a trace for a chain run.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for an LLM run.\non_llm_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for an LLM run.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nStart a trace for an LLM run.\non_retriever_end(documents,\u00a0*,\u00a0run_id,\u00a0**kwargs)", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.stdout.ConsoleCallbackHandler.html"}
{"id": "077154bdb8a5-1", "text": "on_retriever_end(documents,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for a tool run.\non_tool_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for a tool run.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nStart a trace for a tool run.\n__init__(**kwargs: Any) \u2192 None[source]\u00b6\nget_breadcrumbs(run: Run) \u2192 str\u00b6\nget_parents(run: Run) \u2192 List[Run]\u00b6\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, inputs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a chain run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.stdout.ConsoleCallbackHandler.html"}
{"id": "077154bdb8a5-2", "text": "End a trace for a chain run.\non_chain_error(error: BaseException, *, inputs: Optional[Dict[str, Any]] = None, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a chain run.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, run_type: Optional[str] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a chain run.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for an LLM run.\non_llm_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for an LLM run.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Run\u00b6\nRun on new LLM token. Only available when streaming is enabled.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.stdout.ConsoleCallbackHandler.html"}
{"id": "077154bdb8a5-3", "text": "Run on new LLM token. Only available when streaming is enabled.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for an LLM run.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a tool run.\non_tool_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a tool run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.stdout.ConsoleCallbackHandler.html"}
{"id": "077154bdb8a5-4", "text": "Handle an error for a tool run.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a tool run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.stdout.ConsoleCallbackHandler.html"}
{"id": "4788775d9d4a-0", "text": "langchain.schema.callbacks.manager.AsyncCallbackManagerForToolRun\u00b6\nclass langchain.schema.callbacks.manager.AsyncCallbackManagerForToolRun(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nAsync callback manager for tool run.\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nMethods\n__init__(*,\u00a0run_id,\u00a0handlers,\u00a0...[,\u00a0...])\nInitialize the run manager.\nget_child([tag])\nGet a child callback manager.\nget_noop_manager()\nReturn a manager that doesn't perform any operations.\non_retry(retry_state,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when text is received.\non_tool_end(output,\u00a0**kwargs)\nRun when tool ends running.\non_tool_error(error,\u00a0**kwargs)\nRun when tool errors.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForToolRun.html"}
{"id": "4788775d9d4a-1", "text": "on_tool_error(error,\u00a0**kwargs)\nRun when tool errors.\n__init__(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nget_child(tag: Optional[str] = None) \u2192 AsyncCallbackManager\u00b6\nGet a child callback manager.\nParameters\ntag (str, optional) \u2013 The tag for the child callback manager.\nDefaults to None.\nReturns\nThe child callback manager.\nReturn type\nAsyncCallbackManager\nclassmethod get_noop_manager() \u2192 BRM\u00b6\nReturn a manager that doesn\u2019t perform any operations.\nReturns\nThe noop manager.\nReturn type\nBaseRunManager\nasync on_retry(retry_state: RetryCallState, **kwargs: Any) \u2192 None\u00b6\nRun on a retry event.\nasync on_text(text: str, **kwargs: Any) \u2192 Any\u00b6\nRun when text is received.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForToolRun.html"}
{"id": "4788775d9d4a-2", "text": "Run when text is received.\nParameters\ntext (str) \u2013 The received text.\nReturns\nThe result of the callback.\nReturn type\nAny\nasync on_tool_end(output: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.\nParameters\noutput (str) \u2013 The output of the tool.\nasync on_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool errors.\nParameters\nerror (Exception or KeyboardInterrupt) \u2013 The error.\nExamples using AsyncCallbackManagerForToolRun\u00b6\nDefining Custom Tools", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForToolRun.html"}
{"id": "1863bad0f0d1-0", "text": "langchain.schema.runnable.configurable.RunnableConfigurableAlternatives\u00b6\nclass langchain.schema.runnable.configurable.RunnableConfigurableAlternatives[source]\u00b6\nBases: DynamicRunnable[Input, Output]\nA Runnable that can be dynamically configured.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam alternatives: Dict[str, Union[langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output], Callable[[], langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output]]]] [Required]\u00b6\nparam default: langchain.schema.runnable.base.RunnableSerializable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nparam default_key: str = 'default'\u00b6\nparam which: langchain.schema.runnable.utils.ConfigurableField [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "1863bad0f0d1-1", "text": "Subclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "1863bad0f0d1-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output][source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "1863bad0f0d1-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "1863bad0f0d1-4", "text": "namespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "1863bad0f0d1-5", "text": "Generate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "1863bad0f0d1-6", "text": "Default implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "1863bad0f0d1-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "1863bad0f0d1-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableAlternatives.html"}
{"id": "3305019b9fdd-0", "text": "langchain.schema.callbacks.manager.env_var_is_set\u00b6\nlangchain.schema.callbacks.manager.env_var_is_set(env_var: str) \u2192 bool[source]\u00b6\nCheck if an environment variable is set.\nParameters\nenv_var (str) \u2013 The name of the environment variable.\nReturns\nTrue if the environment variable is set, False otherwise.\nReturn type\nbool", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.env_var_is_set.html"}
{"id": "d65f69a1bb98-0", "text": "langchain.schema.embeddings.Embeddings\u00b6\nclass langchain.schema.embeddings.Embeddings[source]\u00b6\nInterface for embedding models.\nMethods\n__init__()\naembed_documents(texts)\nAsynchronous Embed search docs.\naembed_query(text)\nAsynchronous Embed query text.\nembed_documents(texts)\nEmbed search docs.\nembed_query(text)\nEmbed query text.\n__init__()\u00b6\nasync aembed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nAsynchronous Embed search docs.\nasync aembed_query(text: str) \u2192 List[float][source]\u00b6\nAsynchronous Embed query text.\nabstract embed_documents(texts: List[str]) \u2192 List[List[float]][source]\u00b6\nEmbed search docs.\nabstract embed_query(text: str) \u2192 List[float][source]\u00b6\nEmbed query text.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.embeddings.Embeddings.html"}
{"id": "806a65b18166-0", "text": "langchain.schema.callbacks.tracers.base.TracerException\u00b6\nclass langchain.schema.callbacks.tracers.base.TracerException[source]\u00b6\nBase class for exceptions in tracers module.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.base.TracerException.html"}
{"id": "9fb51039a255-0", "text": "langchain.schema.runnable.base.RunnableLambda\u00b6\nclass langchain.schema.runnable.base.RunnableLambda(func: Union[Union[Callable[[Input], Output], Callable[[Input, RunnableConfig], Output], Callable[[Input, CallbackManagerForChainRun], Output], Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]], Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]], afunc: Optional[Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]] = None)[source]\u00b6\nRunnableLambda converts a python callable into a Runnable.\nWrapping a callable in a RunnableLambda makes the callable usable\nwithin either a sync or async context.\nRunnableLambda can be composed as any other Runnable and provides\nseamless integration with LangChain tracing.\nExamples\n# This is a RunnableLambda\nfrom langchain.schema.runnable import RunnableLambda\ndef add_one(x: int) -> int:\n    return x + 1\nrunnable = RunnableLambda(add_one)\nrunnable.invoke(1) # returns 2\nrunnable.batch([1, 2, 3]) # returns [2, 3, 4]\n# Async is supported by default by delegating to the sync implementation\nawait runnable.ainvoke(1) # returns 2\nawait runnable.abatch([1, 2, 3]) # returns [2, 3, 4]\n# Alternatively, can provide both synd and sync implementations", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "9fb51039a255-1", "text": "# Alternatively, can provide both synd and sync implementations\nasync def add_one_async(x: int) -> int:\n    return x + 1\nrunnable = RunnableLambda(add_one, afunc=add_one_async)\nrunnable.invoke(1) # Uses add_one\nawait runnable.ainvoke(1) # Uses add_one_async\nCreate a RunnableLambda from a callable, and async callable or both.\nAccepts both sync and async variants to allow providing efficient\nimplementations for sync and async execution.\nParameters\nfunc \u2013 Either sync or async callable\nafunc \u2013 An async callable that takes an input and returns an output.\nAttributes\nInputType\nThe type of the input to this runnable.\nOutputType\nThe type of the output of this runnable as a type annotation.\nconfig_specs\nList configurable fields for this runnable.\ninput_schema\nThe type of input this runnable accepts specified as a pydantic model.\noutput_schema\nThe type of output this runnable produces specified as a pydantic model.\nMethods\n__init__(func[,\u00a0afunc])\nCreate a RunnableLambda from a callable, and async callable or both.\nabatch(inputs[,\u00a0config,\u00a0return_exceptions])\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nainvoke(input[,\u00a0config])\nInvoke this runnable asynchronously.\nastream(input[,\u00a0config])\nDefault implementation of astream, which calls ainvoke.\nastream_log(input[,\u00a0config,\u00a0diff,\u00a0...])\nStream all output from a runnable, as reported to the callback system.\natransform(input[,\u00a0config])\nDefault implementation of atransform, which buffers input and calls astream.\nbatch(inputs[,\u00a0config,\u00a0return_exceptions])\nDefault implementation runs invoke in parallel using a thread pool executor.\nbind(**kwargs)\nBind arguments to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "9fb51039a255-2", "text": "bind(**kwargs)\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*[,\u00a0include])\nThe type of config this runnable accepts specified as a pydantic model.\nget_input_schema([config])\nThe pydantic schema for the input to this runnable.\nget_output_schema([config])\nGet a pydantic model that can be used to validate output to the runnable.\ninvoke(input[,\u00a0config])\nInvoke this runnable synchronously.\nmap()\nReturn a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input.\nstream(input[,\u00a0config])\nDefault implementation of stream, which calls invoke.\ntransform(input[,\u00a0config])\nDefault implementation of transform, which buffers input and then calls stream.\nwith_config([config])\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks,\u00a0*[,\u00a0...])\nAdd fallbacks to a runnable, returning a new Runnable.\nwith_listeners(*[,\u00a0on_start,\u00a0on_end,\u00a0on_error])\nBind lifecycle listeners to a Runnable, returning a new Runnable.\nwith_retry(*[,\u00a0retry_if_exception_type,\u00a0...])\nCreate a new Runnable that retries the original runnable on exceptions.\nwith_types(*[,\u00a0input_type,\u00a0output_type])\nBind input and output types to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "9fb51039a255-3", "text": "Bind input and output types to a Runnable, returning a new Runnable.\n__init__(func: Union[Union[Callable[[Input], Output], Callable[[Input, RunnableConfig], Output], Callable[[Input, CallbackManagerForChainRun], Output], Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]], Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]], afunc: Optional[Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]] = None) \u2192 None[source]\u00b6\nCreate a RunnableLambda from a callable, and async callable or both.\nAccepts both sync and async variants to allow providing efficient\nimplementations for sync and async execution.\nParameters\nfunc \u2013 Either sync or async callable\nafunc \u2013 An async callable that takes an input and returns an output.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nInvoke this runnable asynchronously.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "9fb51039a255-4", "text": "Invoke this runnable asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "9fb51039a255-5", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nThe pydantic schema for the input to this runnable.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nInvoke this runnable synchronously.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "9fb51039a255-6", "text": "Return a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "9fb51039a255-7", "text": "on_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nExamples using RunnableLambda\u00b6\nsql_db.md\nRun arbitrary functions", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableLambda.html"}
{"id": "715ff46443bb-0", "text": "langchain.schema.runnable.base.RunnableEach\u00b6\nclass langchain.schema.runnable.base.RunnableEach[source]\u00b6\nBases: RunnableEachBase[Input, Output]\nA runnable that delegates calls to another runnable\nwith each element of the input sequence.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bound: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: List[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 List[Output]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "715ff46443bb-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "715ff46443bb-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 RunnableEach[Input, Output][source]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "715ff46443bb-3", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "715ff46443bb-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: List[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 List[Output]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "715ff46443bb-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "715ff46443bb-6", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 RunnableEach[Input, Output][source]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 RunnableEach[Input, Output][source]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "715ff46443bb-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[List[langchain.schema.runnable.utils.Output]]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "715ff46443bb-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableEach.html"}
{"id": "a499d952c09c-0", "text": "langchain.schema.callbacks.base.RetrieverManagerMixin\u00b6\nclass langchain.schema.callbacks.base.RetrieverManagerMixin[source]\u00b6\nMixin for Retriever callbacks.\nMethods\n__init__()\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\n__init__()\u00b6\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when Retriever errors.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.RetrieverManagerMixin.html"}
{"id": "e24e88c2b1b5-0", "text": "langchain.schema.messages.ChatMessage\u00b6\nclass langchain.schema.messages.ChatMessage[source]\u00b6\nBases: BaseMessage\nA Message that can be assigned an arbitrary speaker (i.e. role).\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam role: str [Required]\u00b6\nThe speaker / role of the Message.\nparam type: Literal['chat'] = 'chat'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.ChatMessage.html"}
{"id": "e24e88c2b1b5-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.ChatMessage.html"}
{"id": "e24e88c2b1b5-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.ChatMessage.html"}
{"id": "49972fbaffdb-0", "text": "langchain.schema.runnable.utils.ConfigurableFieldSingleOption\u00b6\nclass langchain.schema.runnable.utils.ConfigurableFieldSingleOption(id: str, options: Mapping[str, Any], default: str, name: Optional[str] = None, description: Optional[str] = None)[source]\u00b6\nA field that can be configured by the user with a default value.\nCreate new instance of ConfigurableFieldSingleOption(id, options, default, name, description)\nAttributes\ndefault\nAlias for field number 2\ndescription\nAlias for field number 4\nid\nAlias for field number 0\nname\nAlias for field number 3\noptions\nAlias for field number 1\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.ConfigurableFieldSingleOption.html"}
{"id": "030d98063c34-0", "text": "langchain.schema.runnable.configurable.StrEnum\u00b6\nclass langchain.schema.runnable.configurable.StrEnum(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]\u00b6\nA string enum.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.StrEnum.html"}
{"id": "90fac4f44fa8-0", "text": "langchain.schema.callbacks.manager.tracing_enabled\u00b6\nlangchain.schema.callbacks.manager.tracing_enabled(session_name: str = 'default') \u2192 Generator[TracerSessionV1, None, None][source]\u00b6\nGet the Deprecated LangChainTracer in a context manager.\nParameters\nsession_name (str, optional) \u2013 The name of the session.\nDefaults to \u201cdefault\u201d.\nReturns\nThe LangChainTracer session.\nReturn type\nTracerSessionV1\nExample\n>>> with tracing_enabled() as session:\n...     # Use the LangChainTracer session\nExamples using tracing_enabled\u00b6\nMultiple callback handlers", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.tracing_enabled.html"}
{"id": "90cc1e30c50a-0", "text": "langchain.schema.callbacks.tracers.evaluation.wait_for_all_evaluators\u00b6\nlangchain.schema.callbacks.tracers.evaluation.wait_for_all_evaluators() \u2192 None[source]\u00b6\nWait for all tracers to finish.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.evaluation.wait_for_all_evaluators.html"}
{"id": "68caf26aa64f-0", "text": "langchain.schema.retriever.BaseRetriever\u00b6\nclass langchain.schema.retriever.BaseRetriever[source]\u00b6\nBases: RunnableSerializable[str, List[Document]], ABC\nAbstract base class for a Document retrieval system.\nA retrieval system is defined as something that can take string queries and returnthe most \u2018relevant\u2019 Documents from some source.\nExample\nclass TFIDFRetriever(BaseRetriever, BaseModel):\n    vectorizer: Any\n    docs: List[Document]\n    tfidf_array: Any\n    k: int = 4\n    class Config:\n        arbitrary_types_allowed = True\n    def get_relevant_documents(self, query: str) -> List[Document]:\n        from sklearn.metrics.pairwise import cosine_similarity\n        # Ip -- (n_docs,x), Op -- (n_docs,n_Feats)\n        query_vec = self.vectorizer.transform([query])\n        # Op -- (n_docs,1) -- Cosine Sim with each doc\n        results = cosine_similarity(self.tfidf_array, query_vec).reshape((-1,))\n        return [self.docs[i] for i in results.argsort()[-self.k :][::-1]]\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.retriever.BaseRetriever.html"}
{"id": "68caf26aa64f-1", "text": "These tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document][source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.retriever.BaseRetriever.html"}
{"id": "68caf26aa64f-2", "text": "The default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.retriever.BaseRetriever.html"}
{"id": "68caf26aa64f-3", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.retriever.BaseRetriever.html"}
{"id": "68caf26aa64f-4", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.retriever.BaseRetriever.html"}
{"id": "68caf26aa64f-5", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document][source]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.retriever.BaseRetriever.html"}
{"id": "68caf26aa64f-6", "text": "and passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document][source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.retriever.BaseRetriever.html"}
{"id": "68caf26aa64f-7", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.retriever.BaseRetriever.html"}
{"id": "68caf26aa64f-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.retriever.BaseRetriever.html"}
{"id": "68caf26aa64f-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using BaseRetriever\u00b6\nRetrieve as you generate with FLARE", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.retriever.BaseRetriever.html"}
{"id": "530c49dec829-0", "text": "langchain.schema.messages.AIMessageChunk\u00b6\nclass langchain.schema.messages.AIMessageChunk[source]\u00b6\nBases: AIMessage, BaseMessageChunk\nA Message chunk from an AI.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam example: bool = False\u00b6\nWhether this Message is being passed in to the model as part of an example\nconversation.\nparam type: Literal['AIMessageChunk'] = 'AIMessageChunk'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.AIMessageChunk.html"}
{"id": "530c49dec829-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.AIMessageChunk.html"}
{"id": "530c49dec829-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.AIMessageChunk.html"}
{"id": "eb030bbef4cd-0", "text": "langchain.schema.messages.ToolMessageChunk\u00b6\nclass langchain.schema.messages.ToolMessageChunk[source]\u00b6\nBases: ToolMessage, BaseMessageChunk\nA Tool Message chunk.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam tool_call_id: str [Required]\u00b6\nTool call that this message is responding to.\nparam type: Literal['ToolMessageChunk'] = 'ToolMessageChunk'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.ToolMessageChunk.html"}
{"id": "eb030bbef4cd-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.ToolMessageChunk.html"}
{"id": "eb030bbef4cd-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.ToolMessageChunk.html"}
{"id": "e4260059832e-0", "text": "langchain.schema.runnable.configurable.DynamicRunnable\u00b6\nclass langchain.schema.runnable.configurable.DynamicRunnable[source]\u00b6\nBases: RunnableSerializable[Input, Output]\nA Serializable Runnable that can be dynamically configured.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam default: langchain.schema.runnable.base.RunnableSerializable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "e4260059832e-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "e4260059832e-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "e4260059832e-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "e4260059832e-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "e4260059832e-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "e4260059832e-6", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "e4260059832e-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "e4260059832e-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.DynamicRunnable.html"}
{"id": "c2ce2a5d4738-0", "text": "langchain.schema.callbacks.base.BaseCallbackHandler\u00b6\nclass langchain.schema.callbacks.base.BaseCallbackHandler[source]\u00b6\nBase callback handler that handles callbacks from LangChain.\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__()\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain ends running.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM ends running.\non_llm_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM errors.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nRun when LLM starts running.\non_retriever_end(documents,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.BaseCallbackHandler.html"}
{"id": "c2ce2a5d4738-1", "text": "on_retriever_error(error,\u00a0*,\u00a0run_id[,\u00a0...])\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool ends running.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool errors.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\n__init__()\u00b6\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain errors.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.BaseCallbackHandler.html"}
{"id": "c2ce2a5d4738-2", "text": "Run when chain errors.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on new LLM token. Only available when streaming is enabled.\nParameters\ntoken (str) \u2013 The new token.\nchunk (GenerationChunk | ChatGenerationChunk) \u2013 The new generated chunk,\ninformation. (containing content and other) \u2013", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.BaseCallbackHandler.html"}
{"id": "c2ce2a5d4738-3", "text": "information. (containing content and other) \u2013 \non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM starts running.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool ends running.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.BaseCallbackHandler.html"}
{"id": "c2ce2a5d4738-4", "text": "Run when tool ends running.\non_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool errors.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool starts running.\nExamples using BaseCallbackHandler\u00b6\nOllama\nCustom callback handlers\nMultiple callback handlers\nAsync callbacks\nStreaming final agent output", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.BaseCallbackHandler.html"}
{"id": "0e58252a72f4-0", "text": "langchain.schema.runnable.utils.ConfigurableField\u00b6\nclass langchain.schema.runnable.utils.ConfigurableField(id: str, name: Optional[str] = None, description: Optional[str] = None, annotation: Optional[Any] = None)[source]\u00b6\nA field that can be configured by the user.\nCreate new instance of ConfigurableField(id, name, description, annotation)\nAttributes\nannotation\nAlias for field number 3\ndescription\nAlias for field number 2\nid\nAlias for field number 0\nname\nAlias for field number 1\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.ConfigurableField.html"}
{"id": "ff24b8906c64-0", "text": "langchain.schema.callbacks.tracers.root_listeners.RootListenersTracer\u00b6\nclass langchain.schema.callbacks.tracers.root_listeners.RootListenersTracer(*, config: RunnableConfig, on_start: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]], on_end: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]], on_error: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]])[source]\u00b6\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nraise_error\nrun_inline\nMethods\n__init__(*,\u00a0config,\u00a0on_start,\u00a0on_end,\u00a0on_error)\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0inputs])\nEnd a trace for a chain run.\non_chain_error(error,\u00a0*[,\u00a0inputs])\nHandle an error for a chain run.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nStart a trace for a chain run.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for an LLM run.\non_llm_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for an LLM run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.root_listeners.RootListenersTracer.html"}
{"id": "ff24b8906c64-1", "text": "Handle an error for an LLM run.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nStart a trace for an LLM run.\non_retriever_end(documents,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for a tool run.\non_tool_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for a tool run.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nStart a trace for a tool run.\n__init__(*, config: RunnableConfig, on_start: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]], on_end: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]], on_error: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]) \u2192 None[source]\u00b6\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.root_listeners.RootListenersTracer.html"}
{"id": "ff24b8906c64-2", "text": "Run on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, inputs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a chain run.\non_chain_error(error: BaseException, *, inputs: Optional[Dict[str, Any]] = None, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a chain run.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, run_type: Optional[str] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a chain run.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for an LLM run.\non_llm_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for an LLM run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.root_listeners.RootListenersTracer.html"}
{"id": "ff24b8906c64-3", "text": "Handle an error for an LLM run.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Run\u00b6\nRun on new LLM token. Only available when streaming is enabled.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for an LLM run.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.root_listeners.RootListenersTracer.html"}
{"id": "ff24b8906c64-4", "text": "End a trace for a tool run.\non_tool_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a tool run.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a tool run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.root_listeners.RootListenersTracer.html"}
{"id": "a2692859ae3c-0", "text": "langchain.schema.runnable.base.RunnableBindingBase\u00b6\nclass langchain.schema.runnable.base.RunnableBindingBase[source]\u00b6\nBases: RunnableSerializable[Input, Output]\nA runnable that delegates calls to another runnable with a set of kwargs.\nUse only if creating a new RunnableBinding subclass with different __init__ args.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bound: langchain.schema.runnable.base.Runnable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nparam config: langchain.schema.runnable.config.RunnableConfig [Optional]\u00b6\nparam config_factories: List[Callable[[langchain.schema.runnable.config.RunnableConfig], langchain.schema.runnable.config.RunnableConfig]] [Optional]\u00b6\nparam custom_input_type: Optional[Any] = None\u00b6\nparam custom_output_type: Optional[Any] = None\u00b6\nparam kwargs: Mapping[str, Any] [Optional]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "a2692859ae3c-1", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "a2692859ae3c-2", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "a2692859ae3c-3", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "a2692859ae3c-4", "text": "Parameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "a2692859ae3c-5", "text": "classmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "a2692859ae3c-6", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "a2692859ae3c-7", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "a2692859ae3c-8", "text": "The type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableBindingBase.html"}
{"id": "32585d5b92fa-0", "text": "langchain.schema.callbacks.tracers.schemas.TracerSession\u00b6\nclass langchain.schema.callbacks.tracers.schemas.TracerSession[source]\u00b6\nBases: TracerSessionBase\nTracerSessionV1 schema for the V2 API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam extra: Optional[Dict[str, Any]] = None\u00b6\nparam id: uuid.UUID [Required]\u00b6\nparam name: Optional[str] = None\u00b6\nparam start_time: datetime.datetime [Optional]\u00b6\nparam tenant_id: uuid.UUID [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSession.html"}
{"id": "32585d5b92fa-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSession.html"}
{"id": "32585d5b92fa-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.TracerSession.html"}
{"id": "97b2dc44420f-0", "text": "langchain.schema.callbacks.manager.CallbackManagerForToolRun\u00b6\nclass langchain.schema.callbacks.manager.CallbackManagerForToolRun(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nCallback manager for tool run.\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nMethods\n__init__(*,\u00a0run_id,\u00a0handlers,\u00a0...[,\u00a0...])\nInitialize the run manager.\nget_child([tag])\nGet a child callback manager.\nget_noop_manager()\nReturn a manager that doesn't perform any operations.\non_retry(retry_state,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0**kwargs)\nRun when text is received.\non_tool_end(output,\u00a0**kwargs)\nRun when tool ends running.\non_tool_error(error,\u00a0**kwargs)\nRun when tool errors.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForToolRun.html"}
{"id": "97b2dc44420f-1", "text": "on_tool_error(error,\u00a0**kwargs)\nRun when tool errors.\n__init__(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nget_child(tag: Optional[str] = None) \u2192 CallbackManager\u00b6\nGet a child callback manager.\nParameters\ntag (str, optional) \u2013 The tag for the child callback manager.\nDefaults to None.\nReturns\nThe child callback manager.\nReturn type\nCallbackManager\nclassmethod get_noop_manager() \u2192 BRM\u00b6\nReturn a manager that doesn\u2019t perform any operations.\nReturns\nThe noop manager.\nReturn type\nBaseRunManager\non_retry(retry_state: RetryCallState, **kwargs: Any) \u2192 None\u00b6\nRun on a retry event.\non_text(text: str, **kwargs: Any) \u2192 Any\u00b6\nRun when text is received.\nParameters\ntext (str) \u2013 The received text.\nReturns", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForToolRun.html"}
{"id": "97b2dc44420f-2", "text": "Parameters\ntext (str) \u2013 The received text.\nReturns\nThe result of the callback.\nReturn type\nAny\non_tool_end(output: str, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool ends running.\nParameters\noutput (str) \u2013 The output of the tool.\non_tool_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when tool errors.\nParameters\nerror (Exception or KeyboardInterrupt) \u2013 The error.\nExamples using CallbackManagerForToolRun\u00b6\nDefining Custom Tools", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForToolRun.html"}
{"id": "f81b10bbaf77-0", "text": "langchain.schema.callbacks.tracers.stdout.elapsed\u00b6\nlangchain.schema.callbacks.tracers.stdout.elapsed(run: Any) \u2192 str[source]\u00b6\nGet the elapsed time of a run.\nParameters\nrun \u2013 any object with a start_time and end_time attribute.\nReturns\nA string with the elapsed time in seconds ormilliseconds if time is less than a second.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.stdout.elapsed.html"}
{"id": "30a27caa4509-0", "text": "langchain.schema.runnable.passthrough.aidentity\u00b6\nasync langchain.schema.runnable.passthrough.aidentity(x: Other) \u2192 Other[source]\u00b6\nAn async identity function", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.aidentity.html"}
{"id": "b355b3d2debf-0", "text": "langchain.schema.callbacks.manager.register_configure_hook\u00b6\nlangchain.schema.callbacks.manager.register_configure_hook(context_var: ContextVar[Optional[Any]], inheritable: bool, handle_class: Optional[Type[BaseCallbackHandler]] = None, env_var: Optional[str] = None) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.register_configure_hook.html"}
{"id": "898c686070f0-0", "text": "langchain.schema.callbacks.tracers.schemas.RunTypeEnum\u00b6\nlangchain.schema.callbacks.tracers.schemas.RunTypeEnum() \u2192 Type[RunTypeEnum][source]\u00b6\nRunTypeEnum.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.RunTypeEnum.html"}
{"id": "8309aefcf681-0", "text": "langchain.schema.messages.HumanMessageChunk\u00b6\nclass langchain.schema.messages.HumanMessageChunk[source]\u00b6\nBases: HumanMessage, BaseMessageChunk\nA Human Message chunk.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam example: bool = False\u00b6\nWhether this Message is being passed in to the model as part of an example\nconversation.\nparam type: Literal['HumanMessageChunk'] = 'HumanMessageChunk'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.HumanMessageChunk.html"}
{"id": "8309aefcf681-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.HumanMessageChunk.html"}
{"id": "8309aefcf681-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.HumanMessageChunk.html"}
{"id": "6aee00a28c67-0", "text": "langchain.schema.callbacks.base.ChainManagerMixin\u00b6\nclass langchain.schema.callbacks.base.ChainManagerMixin[source]\u00b6\nMixin for chain callbacks.\nMethods\n__init__()\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain ends running.\non_chain_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when chain errors.\n__init__()\u00b6\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when chain ends running.\non_chain_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when chain errors.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.ChainManagerMixin.html"}
{"id": "fa8df3b787e1-0", "text": "langchain.schema.output.Generation\u00b6\nclass langchain.schema.output.Generation[source]\u00b6\nBases: Serializable\nA single text generation output.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam generation_info: Optional[Dict[str, Any]] = None\u00b6\nRaw response from the provider. May include things like the\nreason for finishing or token log probabilities.\nparam text: str [Required]\u00b6\nGenerated text output.\nparam type: Literal['Generation'] = 'Generation'\u00b6\nType is used exclusively for serialization purposes.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.Generation.html"}
{"id": "fa8df3b787e1-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.Generation.html"}
{"id": "fa8df3b787e1-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.Generation.html"}
{"id": "b28ec5a1711c-0", "text": "langchain.schema.agent.AgentFinish\u00b6\nclass langchain.schema.agent.AgentFinish[source]\u00b6\nBases: Serializable\nThe final return value of an ActionAgent.\nOverride init to support instantiation by position for backward compat.\nparam log: str [Required]\u00b6\nAdditional information to log about the return value.\nThis is used to pass along the full LLM prediction, not just the parsed out\nreturn value. For example, if the full LLM prediction was\nFinal Answer: 2 you may want to just return 2 as a return value, but pass\nalong the full string as a log (for debugging or observability purposes).\nparam return_values: dict [Required]\u00b6\nDictionary of return values.\nparam type: Literal['AgentFinish'] = 'AgentFinish'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.agent.AgentFinish.html"}
{"id": "b28ec5a1711c-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether or not the class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.agent.AgentFinish.html"}
{"id": "b28ec5a1711c-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using AgentFinish\u00b6\nAgents\nPlug-and-Plai\nWikibase Agent\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nCustom Agent with PlugIn Retrieval\nCustom multi-action agent\nRunning Agent as an Iterator\nCustom agent\nCustom agent with tool retrieval", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.agent.AgentFinish.html"}
{"id": "cd8c9f253aea-0", "text": "langchain.schema.callbacks.tracers.schemas.ChainRun\u00b6\nclass langchain.schema.callbacks.tracers.schemas.ChainRun[source]\u00b6\nBases: BaseRun\nClass for ChainRun.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam child_chain_runs: List[langchain.schema.callbacks.tracers.schemas.ChainRun] [Optional]\u00b6\nparam child_execution_order: int [Required]\u00b6\nparam child_llm_runs: List[langchain.schema.callbacks.tracers.schemas.LLMRun] [Optional]\u00b6\nparam child_tool_runs: List[langchain.schema.callbacks.tracers.schemas.ToolRun] [Optional]\u00b6\nparam end_time: datetime.datetime [Optional]\u00b6\nparam error: Optional[str] = None\u00b6\nparam execution_order: int [Required]\u00b6\nparam extra: Optional[Dict[str, Any]] = None\u00b6\nparam inputs: Dict[str, Any] [Required]\u00b6\nparam outputs: Optional[Dict[str, Any]] = None\u00b6\nparam parent_uuid: Optional[str] = None\u00b6\nparam serialized: Dict[str, Any] [Required]\u00b6\nparam session_id: int [Required]\u00b6\nparam start_time: datetime.datetime [Optional]\u00b6\nparam uuid: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.ChainRun.html"}
{"id": "cd8c9f253aea-1", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.ChainRun.html"}
{"id": "cd8c9f253aea-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.ChainRun.html"}
{"id": "442fcab0706a-0", "text": "langchain.schema.callbacks.manager.CallbackManagerForChainGroup\u00b6\nclass langchain.schema.callbacks.manager.CallbackManagerForChainGroup(handlers: List[BaseCallbackHandler], inheritable_handlers: Optional[List[BaseCallbackHandler]] = None, parent_run_id: Optional[UUID] = None, *, parent_run_manager: CallbackManagerForChainRun, **kwargs: Any)[source]\u00b6\nCallback manager for the chain group.\nInitialize callback manager.\nAttributes\nis_async\nWhether the callback manager is async.\nMethods\n__init__(handlers[,\u00a0inheritable_handlers,\u00a0...])\nInitialize callback manager.\nadd_handler(handler[,\u00a0inherit])\nAdd a handler to the callback manager.\nadd_metadata(metadata[,\u00a0inherit])\nadd_tags(tags[,\u00a0inherit])\nconfigure([inheritable_callbacks,\u00a0...])\nConfigure the callback manager.\ncopy()\nCopy the callback manager.\non_chain_end(outputs,\u00a0**kwargs)\nRun when traced chain group ends.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs[,\u00a0run_id])\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0...)\nRun when LLM starts running.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts running.\non_retriever_start(serialized,\u00a0query[,\u00a0...])\nRun when retriever starts running.\non_tool_start(serialized,\u00a0input_str[,\u00a0...])\nRun when tool starts running.\nremove_handler(handler)\nRemove a handler from the callback manager.\nremove_metadata(keys)\nremove_tags(tags)\nset_handler(handler[,\u00a0inherit])\nSet handler as the only handler on the callback manager.\nset_handlers(handlers[,\u00a0inherit])\nSet handlers as the only handlers on the callback manager.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForChainGroup.html"}
{"id": "442fcab0706a-1", "text": "Set handlers as the only handlers on the callback manager.\n__init__(handlers: List[BaseCallbackHandler], inheritable_handlers: Optional[List[BaseCallbackHandler]] = None, parent_run_id: Optional[UUID] = None, *, parent_run_manager: CallbackManagerForChainRun, **kwargs: Any) \u2192 None[source]\u00b6\nInitialize callback manager.\nadd_handler(handler: BaseCallbackHandler, inherit: bool = True) \u2192 None\u00b6\nAdd a handler to the callback manager.\nadd_metadata(metadata: Dict[str, Any], inherit: bool = True) \u2192 None\u00b6\nadd_tags(tags: List[str], inherit: bool = True) \u2192 None\u00b6\nclassmethod configure(inheritable_callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, local_callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, verbose: bool = False, inheritable_tags: Optional[List[str]] = None, local_tags: Optional[List[str]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None, local_metadata: Optional[Dict[str, Any]] = None) \u2192 CallbackManager\u00b6\nConfigure the callback manager.\nParameters\ninheritable_callbacks (Optional[Callbacks], optional) \u2013 The inheritable\ncallbacks. Defaults to None.\nlocal_callbacks (Optional[Callbacks], optional) \u2013 The local callbacks.\nDefaults to None.\nverbose (bool, optional) \u2013 Whether to enable verbose mode. Defaults to False.\ninheritable_tags (Optional[List[str]], optional) \u2013 The inheritable tags.\nDefaults to None.\nlocal_tags (Optional[List[str]], optional) \u2013 The local tags.\nDefaults to None.\ninheritable_metadata (Optional[Dict[str, Any]], optional) \u2013 The inheritable\nmetadata. Defaults to None.\nlocal_metadata (Optional[Dict[str, Any]], optional) \u2013 The local metadata.\nDefaults to None.\nReturns", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForChainGroup.html"}
{"id": "442fcab0706a-2", "text": "Defaults to None.\nReturns\nThe configured callback manager.\nReturn type\nCallbackManager\ncopy() \u2192 CallbackManagerForChainGroup[source]\u00b6\nCopy the callback manager.\non_chain_end(outputs: Union[Dict[str, Any], Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when traced chain group ends.\nParameters\noutputs (Union[Dict[str, Any], Any]) \u2013 The outputs of the chain.\non_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.\nParameters\nerror (Exception or KeyboardInterrupt) \u2013 The error.\non_chain_start(serialized: Dict[str, Any], inputs: Union[Dict[str, Any], Any], run_id: Optional[UUID] = None, **kwargs: Any) \u2192 CallbackManagerForChainRun\u00b6\nRun when chain starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized chain.\ninputs (Union[Dict[str, Any], Any]) \u2013 The inputs to the chain.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nReturns\nThe callback manager for the chain run.\nReturn type\nCallbackManagerForChainRun\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], **kwargs: Any) \u2192 List[CallbackManagerForLLMRun]\u00b6\nRun when LLM starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized LLM.\nmessages (List[List[BaseMessage]]) \u2013 The list of messages.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nReturns\nA callback manager for eachlist of messages as an LLM run.\nReturn type\nList[CallbackManagerForLLMRun]", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForChainGroup.html"}
{"id": "442fcab0706a-3", "text": "Return type\nList[CallbackManagerForLLMRun]\non_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 List[CallbackManagerForLLMRun]\u00b6\nRun when LLM starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized LLM.\nprompts (List[str]) \u2013 The list of prompts.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nReturns\nA callback manager for eachprompt as an LLM run.\nReturn type\nList[CallbackManagerForLLMRun]\non_retriever_start(serialized: Dict[str, Any], query: str, run_id: Optional[UUID] = None, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 CallbackManagerForRetrieverRun\u00b6\nRun when retriever starts running.\non_tool_start(serialized: Dict[str, Any], input_str: str, run_id: Optional[UUID] = None, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 CallbackManagerForToolRun\u00b6\nRun when tool starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized tool.\ninput_str (str) \u2013 The input to the tool.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run. Defaults to None.\nReturns\nThe callback manager for the tool run.\nReturn type\nCallbackManagerForToolRun\nremove_handler(handler: BaseCallbackHandler) \u2192 None\u00b6\nRemove a handler from the callback manager.\nremove_metadata(keys: List[str]) \u2192 None\u00b6\nremove_tags(tags: List[str]) \u2192 None\u00b6\nset_handler(handler: BaseCallbackHandler, inherit: bool = True) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForChainGroup.html"}
{"id": "442fcab0706a-4", "text": "set_handler(handler: BaseCallbackHandler, inherit: bool = True) \u2192 None\u00b6\nSet handler as the only handler on the callback manager.\nset_handlers(handlers: List[BaseCallbackHandler], inherit: bool = True) \u2192 None\u00b6\nSet handlers as the only handlers on the callback manager.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.CallbackManagerForChainGroup.html"}
{"id": "75a9888927ba-0", "text": "langchain.schema.messages.HumanMessage\u00b6\nclass langchain.schema.messages.HumanMessage[source]\u00b6\nBases: BaseMessage\nA Message from a human.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam example: bool = False\u00b6\nWhether this Message is being passed in to the model as part of an example\nconversation.\nparam type: Literal['human'] = 'human'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.HumanMessage.html"}
{"id": "75a9888927ba-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.HumanMessage.html"}
{"id": "75a9888927ba-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using HumanMessage\u00b6\nZep\nZep Memory\nSQL Chat Message History\nAzureML Chat Online Endpoint\nAnthropic\n\ud83d\ude85 LiteLLM\nKonko\nOpenAI\nGoogle Cloud Platform Vertex AI PaLM \nBedrock Chat\nJinaChat\nOllama\nAzure\nBaidu Qianfan\nERNIE-Bot Chat\nPromptLayer ChatOpenAI\nAnyscale", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.HumanMessage.html"}
{"id": "75a9888927ba-3", "text": "ERNIE-Bot Chat\nPromptLayer ChatOpenAI\nAnyscale\nAnthropic Functions\nLLMonitor\nContext\nLabel Studio\nPromptLayer\nLog10\nMLflow AI Gateway\nFlyte\nArthur\nSet env var OPENAI_API_KEY or load from a .env file:\nStructure answers with OpenAI functions\nCAMEL Role-Playing Autonomous Cooperative Agents\nMulti-Agent Simulated Environment: Petting Zoo\nMulti-agent decentralized speaker selection\nMulti-agent authoritarian speaker selection\nTwo-Player Dungeons & Dragons\nMulti-Player Dungeons & Dragons\nSimulated Environment: Gymnasium\nAgent Debates with Tools\nCustom callback handlers\nAsync callbacks\nTools as OpenAI Functions\nPrompt pipelining\nUsing OpenAI functions", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.HumanMessage.html"}
{"id": "2bb59a6e1512-0", "text": "langchain.schema.exceptions.LangChainException\u00b6\nclass langchain.schema.exceptions.LangChainException[source]\u00b6\nGeneral LangChain exception.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.exceptions.LangChainException.html"}
{"id": "2054847c72c7-0", "text": "langchain.schema.vectorstore.VectorStore\u00b6\nclass langchain.schema.vectorstore.VectorStore[source]\u00b6\nInterface for vector store.\nAttributes\nembeddings\nAccess the query embedding object if available.\nMethods\n__init__()\naadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\naadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents,\u00a0**kwargs)\nRun more documents through the embeddings and add to the vectorstore.\nadd_texts(texts[,\u00a0metadatas])\nRun more texts through the embeddings and add to the vectorstore.\nadelete([ids])\nDelete by vector ID or other criteria.\nafrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nafrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\namax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\namax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs)\nReturn VectorStoreRetriever initialized from this VectorStore.\nasearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nasimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nasimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nasimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1], asynchronously.\nasimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance asynchronously.\ndelete([ids])", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStore.html"}
{"id": "2054847c72c7-1", "text": "Run similarity search with distance asynchronously.\ndelete([ids])\nDelete by vector ID or other criteria.\nfrom_documents(documents,\u00a0embedding,\u00a0**kwargs)\nReturn VectorStore initialized from documents and embeddings.\nfrom_texts(texts,\u00a0embedding[,\u00a0metadatas])\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query[,\u00a0k,\u00a0...])\nReturn docs selected using the maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(...)\nReturn docs selected using the maximal marginal relevance.\nsearch(query,\u00a0search_type,\u00a0**kwargs)\nReturn docs most similar to query using specified search type.\nsimilarity_search(query[,\u00a0k])\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding[,\u00a0k])\nReturn docs most similar to embedding vector.\nsimilarity_search_with_relevance_scores(query)\nReturn docs and relevance scores in the range [0, 1].\nsimilarity_search_with_score(*args,\u00a0**kwargs)\nRun similarity search with distance.\n__init__()\u00b6\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nasync aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more documents through the embeddings and add to the vectorstore.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStore.html"}
{"id": "2054847c72c7-2", "text": "Run more documents through the embeddings and add to the vectorstore.\nParameters\n(List[Document] (documents) \u2013 Documents to add to the vectorstore.\nReturns\nList of IDs of the added texts.\nReturn type\nList[str]\nabstract add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 List[str][source]\u00b6\nRun more texts through the embeddings and add to the vectorstore.\nParameters\ntexts \u2013 Iterable of strings to add to the vectorstore.\nmetadatas \u2013 Optional list of metadatas associated with the texts.\nkwargs \u2013 vectorstore specific parameters\nReturns\nList of ids from adding the texts into the vectorstore.\nasync adelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nasync classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST[source]\u00b6\nReturn VectorStore initialized from documents and embeddings.\nasync classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nasync amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStore.html"}
{"id": "2054847c72c7-3", "text": "Return docs selected using the maximal marginal relevance.\nasync amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nas_retriever(**kwargs: Any) \u2192 VectorStoreRetriever[source]\u00b6\nReturn VectorStoreRetriever initialized from this VectorStore.\nParameters\nsearch_type (Optional[str]) \u2013 Defines the type of search that\nthe Retriever should perform.\nCan be \u201csimilarity\u201d (default), \u201cmmr\u201d, or\n\u201csimilarity_score_threshold\u201d.\nsearch_kwargs (Optional[Dict]) \u2013 Keyword arguments to pass to the\nsearch function. Can include things like:\nk: Amount of documents to return (Default: 4)\nscore_threshold: Minimum relevance threshold\nfor similarity_score_threshold\nfetch_k: Amount of documents to pass to MMR algorithm (Default: 20)\nlambda_mult: Diversity of results returned by MMR;\n1 for minimum diversity and 0 for maximum. (Default: 0.5)\nfilter: Filter by document metadata\nReturns\nRetriever class for VectorStore.\nReturn type\nVectorStoreRetriever\nExamples:\n# Retrieve more documents with higher diversity\n# Useful if your dataset has many similar documents\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 6, 'lambda_mult': 0.25}\n)\n# Fetch more documents for the MMR algorithm to consider\n# But only return the top 5\ndocsearch.as_retriever(\n    search_type=\"mmr\",\n    search_kwargs={'k': 5, 'fetch_k': 50}\n)", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStore.html"}
{"id": "2054847c72c7-4", "text": "search_kwargs={'k': 5, 'fetch_k': 50}\n)\n# Only retrieve documents that have a relevance score\n# Above a certain threshold\ndocsearch.as_retriever(\n    search_type=\"similarity_score_threshold\",\n    search_kwargs={'score_threshold': 0.8}\n)\n# Only get the single most similar document from the dataset\ndocsearch.as_retriever(search_kwargs={'k': 1})\n# Use a filter to only retrieve documents from a specific paper\ndocsearch.as_retriever(\n    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}\n)\nasync asearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query using specified search type.\nasync asimilarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nasync asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nasync asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nReturn docs and relevance scores in the range [0, 1], asynchronously.\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStore.html"}
{"id": "2054847c72c7-5", "text": "Returns\nList of Tuples of (doc, similarity_score)\nasync asimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with distance asynchronously.\ndelete(ids: Optional[List[str]] = None, **kwargs: Any) \u2192 Optional[bool][source]\u00b6\nDelete by vector ID or other criteria.\nParameters\nids \u2013 List of ids to delete.\n**kwargs \u2013 Other keyword arguments that subclasses might use.\nReturns\nTrue if deletion is successful,\nFalse otherwise, None if not implemented.\nReturn type\nOptional[bool]\nclassmethod from_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) \u2192 VST[source]\u00b6\nReturn VectorStore initialized from documents and embeddings.\nabstract classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) \u2192 VST[source]\u00b6\nReturn VectorStore initialized from texts and embeddings.\nmax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nquery \u2013 Text to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStore.html"}
{"id": "2054847c72c7-6", "text": "Defaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nmax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs selected using the maximal marginal relevance.\nMaximal marginal relevance optimizes for similarity to query AND diversity\namong selected documents.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nfetch_k \u2013 Number of Documents to fetch to pass to MMR algorithm.\nlambda_mult \u2013 Number between 0 and 1 that determines the degree\nof diversity among the results with 0 corresponding\nto maximum diversity and 1 to minimum diversity.\nDefaults to 0.5.\nReturns\nList of Documents selected by maximal marginal relevance.\nsearch(query: str, search_type: str, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query using specified search type.\nabstract similarity_search(query: str, k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to query.\nsimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) \u2192 List[Document][source]\u00b6\nReturn docs most similar to embedding vector.\nParameters\nembedding \u2013 Embedding to look up documents similar to.\nk \u2013 Number of Documents to return. Defaults to 4.\nReturns\nList of Documents most similar to the query vector.\nsimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStore.html"}
{"id": "2054847c72c7-7", "text": "Return docs and relevance scores in the range [0, 1].\n0 is dissimilar, 1 is most similar.\nParameters\nquery \u2013 input text\nk \u2013 Number of Documents to return. Defaults to 4.\n**kwargs \u2013 kwargs to be passed to similarity search. Should include:\nscore_threshold: Optional, a floating point value between 0 to 1 to\nfilter the resulting set of retrieved docs\nReturns\nList of Tuples of (doc, similarity_score)\nsimilarity_search_with_score(*args: Any, **kwargs: Any) \u2192 List[Tuple[Document, float]][source]\u00b6\nRun similarity search with distance.\nExamples using VectorStore\u00b6\nBabyAGI User Guide\nBabyAGI with Tools", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStore.html"}
{"id": "f1a8fd16af41-0", "text": "langchain.schema.callbacks.base.CallbackManagerMixin\u00b6\nclass langchain.schema.callbacks.base.CallbackManagerMixin[source]\u00b6\nMixin for callback manager.\nMethods\n__init__()\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nRun when LLM starts running.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\n__init__()\u00b6\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when a chat model starts running.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when LLM starts running.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.CallbackManagerMixin.html"}
{"id": "f1a8fd16af41-1", "text": "Run when LLM starts running.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when Retriever starts running.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when tool starts running.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.CallbackManagerMixin.html"}
{"id": "0eb2135728c3-0", "text": "langchain.schema.messages.messages_to_dict\u00b6\nlangchain.schema.messages.messages_to_dict(messages: Sequence[BaseMessage]) \u2192 List[dict][source]\u00b6\nConvert a sequence of Messages to a list of dictionaries.\nParameters\nmessages \u2013 Sequence of messages (as BaseMessages) to convert.\nReturns\nList of messages as dicts.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.messages_to_dict.html"}
{"id": "a99f075858b1-0", "text": "langchain.schema.output_parser.NoOpOutputParser\u00b6\nlangchain.schema.output_parser.NoOpOutputParser\u00b6\nalias of StrOutputParser", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.NoOpOutputParser.html"}
{"id": "7a551cfc5944-0", "text": "langchain.schema.callbacks.manager.atrace_as_chain_group\u00b6\nlangchain.schema.callbacks.manager.atrace_as_chain_group(group_name: str, callback_manager: Optional[AsyncCallbackManager] = None, *, inputs: Optional[Dict[str, Any]] = None, project_name: Optional[str] = None, example_id: Optional[Union[str, UUID]] = None, run_id: Optional[UUID] = None, tags: Optional[List[str]] = None) \u2192 AsyncGenerator[AsyncCallbackManagerForChainGroup, None][source]\u00b6\nGet an async callback manager for a chain group in a context manager.\nUseful for grouping different async calls together as a single run even if\nthey aren\u2019t composed in a single chain.\nParameters\ngroup_name (str) \u2013 The name of the chain group.\ncallback_manager (AsyncCallbackManager, optional) \u2013 The async callback manager to use,\nwhich manages tracing and other callback behavior.\nproject_name (str, optional) \u2013 The name of the project.\nDefaults to None.\nexample_id (str or UUID, optional) \u2013 The ID of the example.\nDefaults to None.\nrun_id (UUID, optional) \u2013 The ID of the run.\ntags (List[str], optional) \u2013 The inheritable tags to apply to all runs.\nDefaults to None.\nReturns\nThe async callback manager for the chain group.\nReturn type\nAsyncCallbackManager\nNote: must have LANGCHAIN_TRACING_V2 env var set to true to see the trace in LangSmith.\nExample\nllm_input = \"Foo\"\nasync with atrace_as_chain_group(\"group_name\", inputs={\"input\": llm_input}) as manager:\n    # Use the async callback manager for the chain group\n    res = await llm.apredict(llm_input, callbacks=manager)\n    await manager.on_chain_end({\"output\": res})", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.atrace_as_chain_group.html"}
{"id": "780ee3a3fdb2-0", "text": "langchain.schema.output.ChatResult\u00b6\nclass langchain.schema.output.ChatResult[source]\u00b6\nBases: BaseModel\nClass that contains all results for a single chat model call.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam generations: List[langchain.schema.output.ChatGeneration] [Required]\u00b6\nList of the chat generations. This is a List because an input can have multiple\ncandidate generations.\nparam llm_output: Optional[dict] = None\u00b6\nFor arbitrary LLM provider specific output.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.ChatResult.html"}
{"id": "780ee3a3fdb2-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.ChatResult.html"}
{"id": "780ee3a3fdb2-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.ChatResult.html"}
{"id": "8405d655de0b-0", "text": "langchain.schema.output_parser.BaseOutputParser\u00b6\nclass langchain.schema.output_parser.BaseOutputParser[source]\u00b6\nBases: BaseLLMOutputParser, RunnableSerializable[Union[str, BaseMessage], T]\nBase class to parse the output of an LLM call.\nOutput parsers help structure language model responses.\nExample\nclass BooleanOutputParser(BaseOutputParser[bool]):\n    true_val: str = \"YES\"\n    false_val: str = \"NO\"\n    def parse(self, text: str) -> bool:\n        cleaned_text = text.strip().upper()\n        if cleaned_text not in (self.true_val.upper(), self.false_val.upper()):\n            raise OutputParserException(\n                f\"BooleanOutputParser expected output value to either be \"\n                f\"{self.true_val} or {self.false_val} (case-insensitive). \"\n                f\"Received {cleaned_text}.\"\n            )\n        return cleaned_text == self.true_val.upper()\n        @property\n        def _type(self) -> str:\n                return \"boolean_output_parser\"\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseOutputParser.html"}
{"id": "8405d655de0b-1", "text": "The default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T[source]\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseOutputParser.html"}
{"id": "8405d655de0b-2", "text": "Output is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseOutputParser.html"}
{"id": "8405d655de0b-3", "text": "configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict[source]\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str[source]\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseOutputParser.html"}
{"id": "8405d655de0b-4", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseOutputParser.html"}
{"id": "8405d655de0b-5", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nabstract parse(text: str) \u2192 T[source]\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseOutputParser.html"}
{"id": "8405d655de0b-6", "text": "parse_result(result: List[Generation], *, partial: bool = False) \u2192 T[source]\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any[source]\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseOutputParser.html"}
{"id": "8405d655de0b-7", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseOutputParser.html"}
{"id": "8405d655de0b-8", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseOutputParser.html"}
{"id": "8405d655de0b-9", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseOutputParser.html"}
{"id": "bbd8aed39e98-0", "text": "langchain.schema.callbacks.tracers.schemas.LLMRun\u00b6\nclass langchain.schema.callbacks.tracers.schemas.LLMRun[source]\u00b6\nBases: BaseRun\nClass for LLMRun.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam child_execution_order: int [Required]\u00b6\nparam end_time: datetime.datetime [Optional]\u00b6\nparam error: Optional[str] = None\u00b6\nparam execution_order: int [Required]\u00b6\nparam extra: Optional[Dict[str, Any]] = None\u00b6\nparam parent_uuid: Optional[str] = None\u00b6\nparam prompts: List[str] [Required]\u00b6\nparam response: Optional[langchain.schema.output.LLMResult] = None\u00b6\nparam serialized: Dict[str, Any] [Required]\u00b6\nparam session_id: int [Required]\u00b6\nparam start_time: datetime.datetime [Optional]\u00b6\nparam uuid: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.LLMRun.html"}
{"id": "bbd8aed39e98-1", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.LLMRun.html"}
{"id": "bbd8aed39e98-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.schemas.LLMRun.html"}
{"id": "c6045c57fe7d-0", "text": "langchain.schema.output.RunInfo\u00b6\nclass langchain.schema.output.RunInfo[source]\u00b6\nBases: BaseModel\nClass that contains metadata for a single execution of a Chain or model.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam run_id: uuid.UUID [Required]\u00b6\nA unique identifier for the model or chain run.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.RunInfo.html"}
{"id": "c6045c57fe7d-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.RunInfo.html"}
{"id": "c6045c57fe7d-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output.RunInfo.html"}
{"id": "f9f9777e4b1c-0", "text": "langchain.schema.messages.merge_content\u00b6\nlangchain.schema.messages.merge_content(first_content: Union[str, List[Union[str, Dict]]], second_content: Union[str, List[Union[str, Dict]]]) \u2192 Union[str, List[Union[str, Dict]]][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.merge_content.html"}
{"id": "8395adadeacb-0", "text": "langchain.schema.runnable.utils.GetLambdaSource\u00b6\nclass langchain.schema.runnable.utils.GetLambdaSource[source]\u00b6\nGet the source code of a lambda function.\nInitialize the visitor.\nMethods\n__init__()\nInitialize the visitor.\ngeneric_visit(node)\nCalled if no explicit visitor function exists for a node.\nvisit(node)\nVisit a node.\nvisit_Constant(node)\nvisit_Lambda(node)\nVisit a lambda function.\n__init__() \u2192 None[source]\u00b6\nInitialize the visitor.\ngeneric_visit(node)\u00b6\nCalled if no explicit visitor function exists for a node.\nvisit(node)\u00b6\nVisit a node.\nvisit_Constant(node)\u00b6\nvisit_Lambda(node: Lambda) \u2192 Any[source]\u00b6\nVisit a lambda function.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.utils.GetLambdaSource.html"}
{"id": "5e693f824335-0", "text": "langchain.schema.callbacks.manager.AsyncCallbackManager\u00b6\nclass langchain.schema.callbacks.manager.AsyncCallbackManager(handlers: List[BaseCallbackHandler], inheritable_handlers: Optional[List[BaseCallbackHandler]] = None, parent_run_id: Optional[UUID] = None, *, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nAsync callback manager that handles callbacks from LangChain.\nInitialize callback manager.\nAttributes\nis_async\nReturn whether the handler is async.\nMethods\n__init__(handlers[,\u00a0inheritable_handlers,\u00a0...])\nInitialize callback manager.\nadd_handler(handler[,\u00a0inherit])\nAdd a handler to the callback manager.\nadd_metadata(metadata[,\u00a0inherit])\nadd_tags(tags[,\u00a0inherit])\nconfigure([inheritable_callbacks,\u00a0...])\nConfigure the async callback manager.\ncopy()\nCopy the callback manager.\non_chain_start(serialized,\u00a0inputs[,\u00a0run_id])\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0...)\nRun when LLM starts running.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts running.\non_retriever_start(serialized,\u00a0query[,\u00a0...])\nRun when retriever starts running.\non_tool_start(serialized,\u00a0input_str[,\u00a0...])\nRun when tool starts running.\nremove_handler(handler)\nRemove a handler from the callback manager.\nremove_metadata(keys)\nremove_tags(tags)\nset_handler(handler[,\u00a0inherit])\nSet handler as the only handler on the callback manager.\nset_handlers(handlers[,\u00a0inherit])\nSet handlers as the only handlers on the callback manager.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManager.html"}
{"id": "5e693f824335-1", "text": "Set handlers as the only handlers on the callback manager.\n__init__(handlers: List[BaseCallbackHandler], inheritable_handlers: Optional[List[BaseCallbackHandler]] = None, parent_run_id: Optional[UUID] = None, *, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None\u00b6\nInitialize callback manager.\nadd_handler(handler: BaseCallbackHandler, inherit: bool = True) \u2192 None\u00b6\nAdd a handler to the callback manager.\nadd_metadata(metadata: Dict[str, Any], inherit: bool = True) \u2192 None\u00b6\nadd_tags(tags: List[str], inherit: bool = True) \u2192 None\u00b6\nclassmethod configure(inheritable_callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, local_callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, verbose: bool = False, inheritable_tags: Optional[List[str]] = None, local_tags: Optional[List[str]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None, local_metadata: Optional[Dict[str, Any]] = None) \u2192 AsyncCallbackManager[source]\u00b6\nConfigure the async callback manager.\nParameters\ninheritable_callbacks (Optional[Callbacks], optional) \u2013 The inheritable\ncallbacks. Defaults to None.\nlocal_callbacks (Optional[Callbacks], optional) \u2013 The local callbacks.\nDefaults to None.\nverbose (bool, optional) \u2013 Whether to enable verbose mode. Defaults to False.\ninheritable_tags (Optional[List[str]], optional) \u2013 The inheritable tags.\nDefaults to None.\nlocal_tags (Optional[List[str]], optional) \u2013 The local tags.\nDefaults to None.\ninheritable_metadata (Optional[Dict[str, Any]], optional) \u2013 The inheritable", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManager.html"}
{"id": "5e693f824335-2", "text": "inheritable_metadata (Optional[Dict[str, Any]], optional) \u2013 The inheritable\nmetadata. Defaults to None.\nlocal_metadata (Optional[Dict[str, Any]], optional) \u2013 The local metadata.\nDefaults to None.\nReturns\nThe configured async callback manager.\nReturn type\nAsyncCallbackManager\ncopy() \u2192 T\u00b6\nCopy the callback manager.\nasync on_chain_start(serialized: Dict[str, Any], inputs: Union[Dict[str, Any], Any], run_id: Optional[UUID] = None, **kwargs: Any) \u2192 AsyncCallbackManagerForChainRun[source]\u00b6\nRun when chain starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized chain.\ninputs (Union[Dict[str, Any], Any]) \u2013 The inputs to the chain.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nReturns\nThe async callback managerfor the chain run.\nReturn type\nAsyncCallbackManagerForChainRun\nasync on_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], **kwargs: Any) \u2192 List[AsyncCallbackManagerForLLMRun][source]\u00b6\nRun when LLM starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized LLM.\nmessages (List[List[BaseMessage]]) \u2013 The list of messages.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nReturns\nThe list ofasync callback managers, one for each LLM Run\ncorresponding to each inner  message list.\nReturn type\nList[AsyncCallbackManagerForLLMRun]\nasync on_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 List[AsyncCallbackManagerForLLMRun][source]\u00b6\nRun when LLM starts running.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManager.html"}
{"id": "5e693f824335-3", "text": "Run when LLM starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized LLM.\nprompts (List[str]) \u2013 The list of prompts.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nReturns\nThe list of asynccallback managers, one for each LLM Run corresponding\nto each prompt.\nReturn type\nList[AsyncCallbackManagerForLLMRun]\nasync on_retriever_start(serialized: Dict[str, Any], query: str, run_id: Optional[UUID] = None, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 AsyncCallbackManagerForRetrieverRun[source]\u00b6\nRun when retriever starts running.\nasync on_tool_start(serialized: Dict[str, Any], input_str: str, run_id: Optional[UUID] = None, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 AsyncCallbackManagerForToolRun[source]\u00b6\nRun when tool starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized tool.\ninput_str (str) \u2013 The input to the tool.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\nReturns\nThe async callback managerfor the tool run.\nReturn type\nAsyncCallbackManagerForToolRun\nremove_handler(handler: BaseCallbackHandler) \u2192 None\u00b6\nRemove a handler from the callback manager.\nremove_metadata(keys: List[str]) \u2192 None\u00b6\nremove_tags(tags: List[str]) \u2192 None\u00b6\nset_handler(handler: BaseCallbackHandler, inherit: bool = True) \u2192 None\u00b6\nSet handler as the only handler on the callback manager.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManager.html"}
{"id": "5e693f824335-4", "text": "Set handler as the only handler on the callback manager.\nset_handlers(handlers: List[BaseCallbackHandler], inherit: bool = True) \u2192 None\u00b6\nSet handlers as the only handlers on the callback manager.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManager.html"}
{"id": "6f2a7a6feb14-0", "text": "langchain.schema.runnable.passthrough.RunnableAssign\u00b6\nclass langchain.schema.runnable.passthrough.RunnableAssign[source]\u00b6\nBases: RunnableSerializable[Dict[str, Any], Dict[str, Any]]\nA runnable that assigns key-value pairs to Dict[str, Any] inputs.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam mapper: langchain.schema.runnable.base.RunnableParallel[Dict[str, Any]] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any][source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Dict[str, Any]][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "6f2a7a6feb14-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Dict[str, Any]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Dict[str, Any]][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "6f2a7a6feb14-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "6f2a7a6feb14-3", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str][source]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "6f2a7a6feb14-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any][source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "6f2a7a6feb14-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Dict[str, Any]][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Dict[str, Any]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Dict[str, Any]][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "6f2a7a6feb14-6", "text": "input is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "6f2a7a6feb14-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "6f2a7a6feb14-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.passthrough.RunnableAssign.html"}
{"id": "2f9898eef758-0", "text": "langchain.schema.runnable.base.RunnableGenerator\u00b6\nclass langchain.schema.runnable.base.RunnableGenerator(transform: Union[Callable[[Iterator[Input]], Iterator[Output]], Callable[[AsyncIterator[Input]], AsyncIterator[Output]]], atransform: Optional[Callable[[AsyncIterator[Input]], AsyncIterator[Output]]] = None)[source]\u00b6\nA runnable that runs a generator function.\nAttributes\nInputType\nThe type of input this runnable accepts specified as a type annotation.\nOutputType\nThe type of output this runnable produces specified as a type annotation.\nconfig_specs\nList configurable fields for this runnable.\ninput_schema\nThe type of input this runnable accepts specified as a pydantic model.\noutput_schema\nThe type of output this runnable produces specified as a pydantic model.\nMethods\n__init__(transform[,\u00a0atransform])\nabatch(inputs[,\u00a0config,\u00a0return_exceptions])\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nainvoke(input[,\u00a0config])\nDefault implementation of ainvoke, calls invoke from a thread.\nastream(input[,\u00a0config])\nDefault implementation of astream, which calls ainvoke.\nastream_log(input[,\u00a0config,\u00a0diff,\u00a0...])\nStream all output from a runnable, as reported to the callback system.\natransform(input[,\u00a0config])\nDefault implementation of atransform, which buffers input and calls astream.\nbatch(inputs[,\u00a0config,\u00a0return_exceptions])\nDefault implementation runs invoke in parallel using a thread pool executor.\nbind(**kwargs)\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*[,\u00a0include])\nThe type of config this runnable accepts specified as a pydantic model.\nget_input_schema([config])\nGet a pydantic model that can be used to validate input to the runnable.\nget_output_schema([config])", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "2f9898eef758-1", "text": "get_output_schema([config])\nGet a pydantic model that can be used to validate output to the runnable.\ninvoke(input[,\u00a0config])\nTransform a single input into an output.\nmap()\nReturn a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input.\nstream(input[,\u00a0config])\nDefault implementation of stream, which calls invoke.\ntransform(input[,\u00a0config])\nDefault implementation of transform, which buffers input and then calls stream.\nwith_config([config])\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks,\u00a0*[,\u00a0...])\nAdd fallbacks to a runnable, returning a new Runnable.\nwith_listeners(*[,\u00a0on_start,\u00a0on_end,\u00a0on_error])\nBind lifecycle listeners to a Runnable, returning a new Runnable.\nwith_retry(*[,\u00a0retry_if_exception_type,\u00a0...])\nCreate a new Runnable that retries the original runnable on exceptions.\nwith_types(*[,\u00a0input_type,\u00a0output_type])\nBind input and output types to a Runnable, returning a new Runnable.\n__init__(transform: Union[Callable[[Iterator[Input]], Iterator[Output]], Callable[[AsyncIterator[Input]], AsyncIterator[Output]]], atransform: Optional[Callable[[AsyncIterator[Input]], AsyncIterator[Output]]] = None) \u2192 None[source]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "2f9898eef758-2", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nastream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "2f9898eef758-3", "text": "The jsonpatch ops can be applied in order to construct state.\natransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "2f9898eef758-4", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "2f9898eef758-5", "text": "Subclasses should override this method if they support streaming output.\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "2f9898eef758-6", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableGenerator.html"}
{"id": "2af7a0dcc0fb-0", "text": "langchain.schema.vectorstore.VectorStoreRetriever\u00b6\nclass langchain.schema.vectorstore.VectorStoreRetriever[source]\u00b6\nBases: BaseRetriever\nBase Retriever class for VectorStore.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam search_kwargs: dict [Optional]\u00b6\nKeyword arguments to pass to the search function.\nparam search_type: str = 'similarity'\u00b6\nType of search to perform. Defaults to \u201csimilarity\u201d.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a retriever with its\nuse case.\nparam vectorstore: langchain.schema.vectorstore.VectorStore [Required]\u00b6\nVectorStore to use for retrieval.\nasync aadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd documents to vectorstore.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStoreRetriever.html"}
{"id": "2af7a0dcc0fb-1", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nadd_documents(documents: List[Document], **kwargs: Any) \u2192 List[str][source]\u00b6\nAdd documents to vectorstore.\nasync aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nAsynchronously get documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\nasync ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 List[Document]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStoreRetriever.html"}
{"id": "2af7a0dcc0fb-2", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStoreRetriever.html"}
{"id": "2af7a0dcc0fb-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStoreRetriever.html"}
{"id": "2af7a0dcc0fb-4", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStoreRetriever.html"}
{"id": "2af7a0dcc0fb-5", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 List[Document]\u00b6\nRetrieve documents relevant to a query.\n:param query: string to find relevant documents for\n:param callbacks: Callback manager or list of callbacks\n:param tags: Optional list of tags associated with the retriever. Defaults to None\nThese tags will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nParameters\nmetadata \u2013 Optional metadata associated with the retriever. Defaults to None\nThis metadata will be associated with each call to this retriever,\nand passed as arguments to the handlers defined in callbacks.\nReturns\nList of relevant documents\ninvoke(input: str, config: Optional[RunnableConfig] = None) \u2192 List[Document]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStoreRetriever.html"}
{"id": "2af7a0dcc0fb-6", "text": "Returns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStoreRetriever.html"}
{"id": "2af7a0dcc0fb-7", "text": "classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStoreRetriever.html"}
{"id": "2af7a0dcc0fb-8", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStoreRetriever.html"}
{"id": "2af7a0dcc0fb-9", "text": "The type of output this runnable produces specified as a type annotation.\nallowed_search_types: ClassVar[Collection[str]] = ('similarity', 'similarity_score_threshold', 'mmr')\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.vectorstore.VectorStoreRetriever.html"}
{"id": "fb0bd07445b4-0", "text": "langchain.schema.messages.SystemMessageChunk\u00b6\nclass langchain.schema.messages.SystemMessageChunk[source]\u00b6\nBases: SystemMessage, BaseMessageChunk\nA System Message chunk.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam type: Literal['SystemMessageChunk'] = 'SystemMessageChunk'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.SystemMessageChunk.html"}
{"id": "fb0bd07445b4-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.SystemMessageChunk.html"}
{"id": "fb0bd07445b4-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.SystemMessageChunk.html"}
{"id": "7a4eb30f624c-0", "text": "langchain.schema.callbacks.base.RunManagerMixin\u00b6\nclass langchain.schema.callbacks.base.RunManagerMixin[source]\u00b6\nMixin for run manager.\nMethods\n__init__()\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\n__init__()\u00b6\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on arbitrary text.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.RunManagerMixin.html"}
{"id": "b412c6d75167-0", "text": "langchain.schema.output_parser.BaseTransformOutputParser\u00b6\nclass langchain.schema.output_parser.BaseTransformOutputParser[source]\u00b6\nBases: BaseOutputParser[T]\nBase class for an output parser that can handle streaming input.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: str | langchain.schema.messages.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 T\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync aparse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nasync aparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseTransformOutputParser.html"}
{"id": "b412c6d75167-1", "text": "to be different candidate outputs for a single model input.\nReturns\nStructured output.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[T][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseTransformOutputParser.html"}
{"id": "b412c6d75167-2", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseTransformOutputParser.html"}
{"id": "b412c6d75167-3", "text": "Duplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn dictionary representation of output parser.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_format_instructions() \u2192 str\u00b6\nInstructions on how the LLM output should be formatted.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseTransformOutputParser.html"}
{"id": "b412c6d75167-4", "text": "methods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) \u2192 T\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseTransformOutputParser.html"}
{"id": "b412c6d75167-5", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nabstract parse(text: str) \u2192 T\u00b6\nParse a single string model output into some structure.\nParameters\ntext \u2013 String output of a language model.\nReturns\nStructured output.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nparse_result(result: List[Generation], *, partial: bool = False) \u2192 T\u00b6\nParse a list of candidate model Generations into a specific format.\nThe return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation.\nParameters\nresult \u2013 A list of Generations to be parsed. The Generations are assumed\nto be different candidate outputs for a single model input.\nReturns\nStructured output.\nparse_with_prompt(completion: str, prompt: PromptValue) \u2192 Any\u00b6\nParse the output of an LLM call with the input prompt for context.\nThe prompt is largely provided in the event the OutputParser wants\nto retry or fix the output in some way, and needs information from\nthe prompt to do so.\nParameters\ncompletion \u2013 String output of a language model.\nprompt \u2013 Input PromptValue.\nReturns\nStructured output", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseTransformOutputParser.html"}
{"id": "b412c6d75167-6", "text": "prompt \u2013 Input PromptValue.\nReturns\nStructured output\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[T][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseTransformOutputParser.html"}
{"id": "b412c6d75167-7", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Any\u00b6\nThe type of input this runnable accepts specified as a type annotation.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseTransformOutputParser.html"}
{"id": "b412c6d75167-8", "text": "The type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.output_parser.T]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.output_parser.BaseTransformOutputParser.html"}
{"id": "247eb6c86f27-0", "text": "langchain.schema.runnable.configurable.make_options_spec\u00b6\nlangchain.schema.runnable.configurable.make_options_spec(spec: Union[ConfigurableFieldSingleOption, ConfigurableFieldMultiOption], description: Optional[str]) \u2192 ConfigurableFieldSpec[source]\u00b6\nMake a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or\nConfigurableFieldMultiOption.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.make_options_spec.html"}
{"id": "407b928c17a0-0", "text": "langchain.schema.callbacks.manager.BaseRunManager\u00b6\nclass langchain.schema.callbacks.manager.BaseRunManager(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nBase class for run manager (a bound callback manager).\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nMethods\n__init__(*,\u00a0run_id,\u00a0handlers,\u00a0...[,\u00a0...])\nInitialize the run manager.\nget_noop_manager()\nReturn a manager that doesn't perform any operations.\non_retry(retry_state,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.BaseRunManager.html"}
{"id": "407b928c17a0-1", "text": "Run on arbitrary text.\n__init__(*, run_id: UUID, handlers: List[BaseCallbackHandler], inheritable_handlers: List[BaseCallbackHandler], parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None[source]\u00b6\nInitialize the run manager.\nParameters\nrun_id (UUID) \u2013 The ID of the run.\nhandlers (List[BaseCallbackHandler]) \u2013 The list of handlers.\ninheritable_handlers (List[BaseCallbackHandler]) \u2013 The list of inheritable handlers.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\ntags (Optional[List[str]]) \u2013 The list of tags.\ninheritable_tags (Optional[List[str]]) \u2013 The list of inheritable tags.\nmetadata (Optional[Dict[str, Any]]) \u2013 The metadata.\ninheritable_metadata (Optional[Dict[str, Any]]) \u2013 The inheritable metadata.\nclassmethod get_noop_manager() \u2192 BRM[source]\u00b6\nReturn a manager that doesn\u2019t perform any operations.\nReturns\nThe noop manager.\nReturn type\nBaseRunManager\non_retry(retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.BaseRunManager.html"}
{"id": "6ffbebc44863-0", "text": "langchain.schema.runnable.configurable.RunnableConfigurableFields\u00b6\nclass langchain.schema.runnable.configurable.RunnableConfigurableFields[source]\u00b6\nBases: DynamicRunnable[Input, Output]\nA Runnable that can be dynamically configured.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam default: langchain.schema.runnable.base.RunnableSerializable[langchain.schema.runnable.utils.Input, langchain.schema.runnable.utils.Output] [Required]\u00b6\nparam fields: Dict[str, Union[langchain.schema.runnable.utils.ConfigurableField, langchain.schema.runnable.utils.ConfigurableFieldSingleOption, langchain.schema.runnable.utils.ConfigurableFieldMultiOption]] [Required]\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "6ffbebc44863-1", "text": "Default implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "6ffbebc44863-2", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output][source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "6ffbebc44863-3", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "6ffbebc44863-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "6ffbebc44863-5", "text": "classmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "6ffbebc44863-6", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "6ffbebc44863-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "6ffbebc44863-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.configurable.RunnableConfigurableFields.html"}
{"id": "1cfd434b98ed-0", "text": "langchain.schema.prompt.PromptValue\u00b6\nclass langchain.schema.prompt.PromptValue[source]\u00b6\nBases: Serializable, ABC\nBase abstract class for inputs to any language model.\nPromptValues can be converted to both LLM (pure text-generation) inputs andChatModel inputs.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.prompt.PromptValue.html"}
{"id": "1cfd434b98ed-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.prompt.PromptValue.html"}
{"id": "1cfd434b98ed-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nabstract to_messages() \u2192 List[BaseMessage][source]\u00b6\nReturn prompt as a list of Messages.\nabstract to_string() \u2192 str[source]\u00b6\nReturn prompt value as string.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.prompt.PromptValue.html"}
{"id": "746fba206249-0", "text": "langchain.schema.document.Document\u00b6\nclass langchain.schema.document.Document[source]\u00b6\nBases: Serializable\nClass for storing a piece of text and associated metadata.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam metadata: dict [Optional]\u00b6\nArbitrary metadata about the page content (e.g., source, relationships to other\ndocuments, etc.).\nparam page_content: str [Required]\u00b6\nString text.\nparam type: Literal['Document'] = 'Document'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.document.Document.html"}
{"id": "746fba206249-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.document.Document.html"}
{"id": "746fba206249-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using Document\u00b6\nChatGPT Plugin\nWeaviate Hybrid Search\nBM25\nTF-IDF\nApify\nVectara Text Generation\nPGVector\nAnnoy\nNeo4j Vector Index\nPostgres Embedding\nFaiss\nNuclia Understanding API document transformer\nOpenAI Functions Metadata Tagger\nDoctran Extract Properties\nDoctran Interrogate Documents", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.document.Document.html"}
{"id": "746fba206249-3", "text": "OpenAI Functions Metadata Tagger\nDoctran Extract Properties\nDoctran Interrogate Documents\nDoctran Translate Documents\nTensorFlow Datasets\nAirbyte Salesforce\nAirbyte CDK\nAirbyte Stripe\nCopy Paste\nAirbyte Typeform\nApify Dataset\nDocugami\nAirbyte Hubspot\nAirbyte Gong\nAirbyte Shopify\nAirbyte Zendesk Support\nSageMakerEndpoint\nLLM Caching integrations\nRetrieve from vector stores directly\nMultiple Retrieval Sources\nRetrieve as you generate with FLARE\n!pip install bs4\nPlug-and-Plai\nCustom Agent with PlugIn Retrieval\nSet env var OPENAI_API_KEY or load from a .env file\nSQL\nIndexing\nMultiVector Retriever\nMilvus\nWeaviate\nVectara\nDashVector\nElasticsearch\nChroma\nPinecone\nSupabase\nRedis\nMyScale\nDeep Lake\nQdrant\nMemory in the Multi-Input Chain\nCustom agent with tool retrieval", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.document.Document.html"}
{"id": "17b4d5287f0f-0", "text": "langchain.schema.callbacks.manager.collect_runs\u00b6\nlangchain.schema.callbacks.manager.collect_runs() \u2192 Generator[RunCollectorCallbackHandler, None, None][source]\u00b6\nCollect all run traces in context.\nReturns\nThe run collector callback handler.\nReturn type\nrun_collector.RunCollectorCallbackHandler\nExample\n>>> with collect_runs() as runs_cb:\n        chain.invoke(\"foo\")\n        run_id = runs_cb.traced_runs[0].id", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.collect_runs.html"}
{"id": "f70d3ceee8d4-0", "text": "langchain.schema.callbacks.base.BaseCallbackManager\u00b6\nclass langchain.schema.callbacks.base.BaseCallbackManager(handlers: List[BaseCallbackHandler], inheritable_handlers: Optional[List[BaseCallbackHandler]] = None, parent_run_id: Optional[UUID] = None, *, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None)[source]\u00b6\nBase callback manager that handles callbacks from LangChain.\nInitialize callback manager.\nAttributes\nis_async\nWhether the callback manager is async.\nMethods\n__init__(handlers[,\u00a0inheritable_handlers,\u00a0...])\nInitialize callback manager.\nadd_handler(handler[,\u00a0inherit])\nAdd a handler to the callback manager.\nadd_metadata(metadata[,\u00a0inherit])\nadd_tags(tags[,\u00a0inherit])\ncopy()\nCopy the callback manager.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nRun when LLM starts running.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nRun when tool starts running.\nremove_handler(handler)\nRemove a handler from the callback manager.\nremove_metadata(keys)\nremove_tags(tags)\nset_handler(handler[,\u00a0inherit])\nSet handler as the only handler on the callback manager.\nset_handlers(handlers[,\u00a0inherit])\nSet handlers as the only handlers on the callback manager.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.BaseCallbackManager.html"}
{"id": "f70d3ceee8d4-1", "text": "Set handlers as the only handlers on the callback manager.\n__init__(handlers: List[BaseCallbackHandler], inheritable_handlers: Optional[List[BaseCallbackHandler]] = None, parent_run_id: Optional[UUID] = None, *, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None) \u2192 None[source]\u00b6\nInitialize callback manager.\nadd_handler(handler: BaseCallbackHandler, inherit: bool = True) \u2192 None[source]\u00b6\nAdd a handler to the callback manager.\nadd_metadata(metadata: Dict[str, Any], inherit: bool = True) \u2192 None[source]\u00b6\nadd_tags(tags: List[str], inherit: bool = True) \u2192 None[source]\u00b6\ncopy() \u2192 T[source]\u00b6\nCopy the callback manager.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when chain starts running.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.BaseCallbackManager.html"}
{"id": "f70d3ceee8d4-2", "text": "Run when a chat model starts running.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when LLM starts running.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when Retriever starts running.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when tool starts running.\nremove_handler(handler: BaseCallbackHandler) \u2192 None[source]\u00b6\nRemove a handler from the callback manager.\nremove_metadata(keys: List[str]) \u2192 None[source]\u00b6\nremove_tags(tags: List[str]) \u2192 None[source]\u00b6\nset_handler(handler: BaseCallbackHandler, inherit: bool = True) \u2192 None[source]\u00b6\nSet handler as the only handler on the callback manager.\nset_handlers(handlers: List[BaseCallbackHandler], inherit: bool = True) \u2192 None[source]\u00b6\nSet handlers as the only handlers on the callback manager.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.BaseCallbackManager.html"}
{"id": "4addce59f87f-0", "text": "langchain.schema.callbacks.base.LLMManagerMixin\u00b6\nclass langchain.schema.callbacks.base.LLMManagerMixin[source]\u00b6\nMixin for LLM callbacks.\nMethods\n__init__()\non_llm_end(response,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM ends running.\non_llm_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when LLM errors.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\n__init__()\u00b6\non_llm_end(response: LLMResult, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when LLM ends running.\non_llm_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when LLM errors.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun on new LLM token. Only available when streaming is enabled.\nParameters\ntoken (str) \u2013 The new token.\nchunk (GenerationChunk | ChatGenerationChunk) \u2013 The new generated chunk,\ninformation. (containing content and other) \u2013", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.LLMManagerMixin.html"}
{"id": "18dfe483f4ce-0", "text": "langchain.schema.callbacks.tracers.langchain.get_client\u00b6\nlangchain.schema.callbacks.tracers.langchain.get_client() \u2192 Client[source]\u00b6\nGet the client.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.langchain.get_client.html"}
{"id": "aadded79a865-0", "text": "langchain.schema.runnable.base.Runnable\u00b6\nclass langchain.schema.runnable.base.Runnable[source]\u00b6\nA unit of work that can be invoked, batched, streamed, transformed and composed.\ninvoke/ainvoke: Transforms a single input into an output.\nbatch/abatch: Efficiently transforms multiple inputs into outputs.\nstream/astream: Streams output from a single input as it\u2019s produced.\nastream_log: Streams output and selected intermediate results from an input.\nBuilt-in optimizations:\nBatch: By default, batch runs invoke() in parallel using a thread pool executor.Override to optimize batching.\nAsync: Methods with \u201ca\u201d suffix are asynchronous. By default, they executethe sync counterpart using asyncio\u2019s thread pool.\nOverride for native async.\nAll methods accept an optional config argument, which can be used to configure\nexecution, add tags and metadata for tracing and debugging etc.\nRunnables expose schematic information about their input, output and config via\nthe input_schema property, the output_schema property and config_schema method.\nThe LangChain Expression Language (LCEL) is a declarative way to compose Runnables\ninto chains. Any chain constructed this way will automatically have sync, async,\nbatch, and streaming support.\nThe main composition primitives are RunnableSequence and RunnableParallel.\nRunnableSequence invokes a series of runnables sequentially, with one runnable\u2019s\noutput serving as the next\u2019s input. Construct using the | operator or by\npassing a list of runnables to RunnableSequence.\nRunnableParallel invokes runnables concurrently, providing the same input\nto each. Construct it using a dict literal within a sequence or by passing a\ndict to RunnableParallel.\nFor example,\nfrom langchain.schema.runnable import RunnableLambda\n# A RunnableSequence constructed using the `|` operator", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.Runnable.html"}
{"id": "aadded79a865-1", "text": "# A RunnableSequence constructed using the `|` operator\nsequence = RunnableLambda(lambda x: x + 1) | RunnableLambda(lambda x: x * 2)\nsequence.invoke(1) # 4\nsequence.batch([1, 2, 3]) # [4, 6, 8]\n# A sequence that contains a RunnableParallel constructed using a dict literal\nsequence = RunnableLambda(lambda x: x + 1) | {\n    'mul_2': RunnableLambda(lambda x: x * 2),\n    'mul_5': RunnableLambda(lambda x: x * 5)\n}\nsequence.invoke(1) # {'mul_2': 4, 'mul_5': 10}\nAll Runnables expose additional methods that can be used to modify their behavior\n(e.g., add a retry policy, add lifecycle listeners, make them configurable, etc.).\nThese methods will work on any Runnable, including Runnable chains constructed\nby composing other Runnables. See the individual methods for details.\nFor example,\nfrom langchain.schema.runnable import RunnableLambda\nimport random\ndef add_one(x: int) -> int:\n    return x + 1\ndef buggy_double(y: int) -> int:\n    '''Buggy code that will fail 70% of the time'''\n    if random.random() > 0.3:\n        print('This code failed, and will probably be retried!')\n        raise ValueError('Triggered buggy code')\n    return y * 2\nsequence = (\n    RunnableLambda(add_one) |\n    RunnableLambda(buggy_double).with_retry( # Retry on failure\n        stop_after_attempt=10,\n        wait_exponential_jitter=False\n    )\n)\nprint(sequence.input_schema.schema()) # Show inferred input schema\nprint(sequence.output_schema.schema()) # Show inferred output schema", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.Runnable.html"}
{"id": "aadded79a865-2", "text": "print(sequence.output_schema.schema()) # Show inferred output schema\nprint(sequence.invoke(2)) # invoke the sequence (note the retry above!!)\nAs the chains get longer, it can be useful to be able to see intermediate results\nto debug and trace the chain.\nYou can set the global debug flag to True to enable debug output for all chains:\nfrom langchain.globals import set_debug\nset_debug(True)\nAlternatively, you can pass existing or custom callbacks to any given chain:\n\u2026 code-block:: python\nfrom langchain.callbacks.tracers import ConsoleCallbackHandler\nchain.invoke(\u2026,\nconfig={\u2018callbacks\u2019: [ConsoleCallbackHandler()]}\n)\nFor a UI (and much more) checkout LangSmith: https://docs.smith.langchain.com/\nAttributes\nInputType\nThe type of input this runnable accepts specified as a type annotation.\nOutputType\nThe type of output this runnable produces specified as a type annotation.\nconfig_specs\nList configurable fields for this runnable.\ninput_schema\nThe type of input this runnable accepts specified as a pydantic model.\noutput_schema\nThe type of output this runnable produces specified as a pydantic model.\nMethods\n__init__()\nabatch(inputs[,\u00a0config,\u00a0return_exceptions])\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nainvoke(input[,\u00a0config])\nDefault implementation of ainvoke, calls invoke from a thread.\nastream(input[,\u00a0config])\nDefault implementation of astream, which calls ainvoke.\nastream_log()\nStream all output from a runnable, as reported to the callback system.\natransform(input[,\u00a0config])\nDefault implementation of atransform, which buffers input and calls astream.\nbatch(inputs[,\u00a0config,\u00a0return_exceptions])\nDefault implementation runs invoke in parallel using a thread pool executor.\nbind(**kwargs)", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.Runnable.html"}
{"id": "aadded79a865-3", "text": "Default implementation runs invoke in parallel using a thread pool executor.\nbind(**kwargs)\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*[,\u00a0include])\nThe type of config this runnable accepts specified as a pydantic model.\nget_input_schema([config])\nGet a pydantic model that can be used to validate input to the runnable.\nget_output_schema([config])\nGet a pydantic model that can be used to validate output to the runnable.\ninvoke(input[,\u00a0config])\nTransform a single input into an output.\nmap()\nReturn a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input.\nstream(input[,\u00a0config])\nDefault implementation of stream, which calls invoke.\ntransform(input[,\u00a0config])\nDefault implementation of transform, which buffers input and then calls stream.\nwith_config([config])\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks,\u00a0*[,\u00a0...])\nAdd fallbacks to a runnable, returning a new Runnable.\nwith_listeners(*[,\u00a0on_start,\u00a0on_end,\u00a0on_error])\nBind lifecycle listeners to a Runnable, returning a new Runnable.\nwith_retry(*[,\u00a0retry_if_exception_type,\u00a0...])\nCreate a new Runnable that retries the original runnable on exceptions.\nwith_types(*[,\u00a0input_type,\u00a0output_type])\nBind input and output types to a Runnable, returning a new Runnable.\n__init__()\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.Runnable.html"}
{"id": "aadded79a865-4", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: Literal[True] = 'True', include_names: Optional[Sequence[str]] = 'None', include_types: Optional[Sequence[str]] = 'None', include_tags: Optional[Sequence[str]] = 'None', exclude_names: Optional[Sequence[str]] = 'None', exclude_types: Optional[Sequence[str]] = 'None', exclude_tags: Optional[Sequence[str]] = 'None', **kwargs: Optional[Any]) \u2192 AsyncIterator[RunLogPatch][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.Runnable.html"}
{"id": "aadded79a865-5", "text": "async astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: Literal[False], include_names: Optional[Sequence[str]] = 'None', include_types: Optional[Sequence[str]] = 'None', include_tags: Optional[Sequence[str]] = 'None', exclude_names: Optional[Sequence[str]] = 'None', exclude_types: Optional[Sequence[str]] = 'None', exclude_tags: Optional[Sequence[str]] = 'None', **kwargs: Optional[Any]) \u2192 AsyncIterator[RunLog]\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output][source]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output][source]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.Runnable.html"}
{"id": "aadded79a865-6", "text": "bind(**kwargs: Any) \u2192 Runnable[Input, Output][source]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel][source]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nabstract invoke(input: Input, config: Optional[RunnableConfig] = None) \u2192 Output[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.Runnable.html"}
{"id": "aadded79a865-7", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nmap() \u2192 Runnable[List[Input], List[Output]][source]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output][source]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output][source]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output][source]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.Runnable.html"}
{"id": "aadded79a865-8", "text": "exceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output][source]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output][source]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output][source]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.Runnable.html"}
{"id": "ec4971e8f79b-0", "text": "langchain.schema.callbacks.manager.AsyncCallbackManagerForChainGroup\u00b6\nclass langchain.schema.callbacks.manager.AsyncCallbackManagerForChainGroup(handlers: List[BaseCallbackHandler], inheritable_handlers: Optional[List[BaseCallbackHandler]] = None, parent_run_id: Optional[UUID] = None, *, parent_run_manager: AsyncCallbackManagerForChainRun, **kwargs: Any)[source]\u00b6\nAsync callback manager for the chain group.\nInitialize callback manager.\nAttributes\nis_async\nReturn whether the handler is async.\nMethods\n__init__(handlers[,\u00a0inheritable_handlers,\u00a0...])\nInitialize callback manager.\nadd_handler(handler[,\u00a0inherit])\nAdd a handler to the callback manager.\nadd_metadata(metadata[,\u00a0inherit])\nadd_tags(tags[,\u00a0inherit])\nconfigure([inheritable_callbacks,\u00a0...])\nConfigure the async callback manager.\ncopy()\nCopy the callback manager.\non_chain_end(outputs,\u00a0**kwargs)\nRun when traced chain group ends.\non_chain_error(error,\u00a0**kwargs)\nRun when chain errors.\non_chain_start(serialized,\u00a0inputs[,\u00a0run_id])\nRun when chain starts running.\non_chat_model_start(serialized,\u00a0messages,\u00a0...)\nRun when LLM starts running.\non_llm_start(serialized,\u00a0prompts,\u00a0**kwargs)\nRun when LLM starts running.\non_retriever_start(serialized,\u00a0query[,\u00a0...])\nRun when retriever starts running.\non_tool_start(serialized,\u00a0input_str[,\u00a0...])\nRun when tool starts running.\nremove_handler(handler)\nRemove a handler from the callback manager.\nremove_metadata(keys)\nremove_tags(tags)\nset_handler(handler[,\u00a0inherit])\nSet handler as the only handler on the callback manager.\nset_handlers(handlers[,\u00a0inherit])\nSet handlers as the only handlers on the callback manager.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForChainGroup.html"}
{"id": "ec4971e8f79b-1", "text": "Set handlers as the only handlers on the callback manager.\n__init__(handlers: List[BaseCallbackHandler], inheritable_handlers: Optional[List[BaseCallbackHandler]] = None, parent_run_id: Optional[UUID] = None, *, parent_run_manager: AsyncCallbackManagerForChainRun, **kwargs: Any) \u2192 None[source]\u00b6\nInitialize callback manager.\nadd_handler(handler: BaseCallbackHandler, inherit: bool = True) \u2192 None\u00b6\nAdd a handler to the callback manager.\nadd_metadata(metadata: Dict[str, Any], inherit: bool = True) \u2192 None\u00b6\nadd_tags(tags: List[str], inherit: bool = True) \u2192 None\u00b6\nclassmethod configure(inheritable_callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, local_callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, verbose: bool = False, inheritable_tags: Optional[List[str]] = None, local_tags: Optional[List[str]] = None, inheritable_metadata: Optional[Dict[str, Any]] = None, local_metadata: Optional[Dict[str, Any]] = None) \u2192 AsyncCallbackManager\u00b6\nConfigure the async callback manager.\nParameters\ninheritable_callbacks (Optional[Callbacks], optional) \u2013 The inheritable\ncallbacks. Defaults to None.\nlocal_callbacks (Optional[Callbacks], optional) \u2013 The local callbacks.\nDefaults to None.\nverbose (bool, optional) \u2013 Whether to enable verbose mode. Defaults to False.\ninheritable_tags (Optional[List[str]], optional) \u2013 The inheritable tags.\nDefaults to None.\nlocal_tags (Optional[List[str]], optional) \u2013 The local tags.\nDefaults to None.\ninheritable_metadata (Optional[Dict[str, Any]], optional) \u2013 The inheritable\nmetadata. Defaults to None.\nlocal_metadata (Optional[Dict[str, Any]], optional) \u2013 The local metadata.\nDefaults to None.\nReturns", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForChainGroup.html"}
{"id": "ec4971e8f79b-2", "text": "Defaults to None.\nReturns\nThe configured async callback manager.\nReturn type\nAsyncCallbackManager\ncopy() \u2192 AsyncCallbackManagerForChainGroup[source]\u00b6\nCopy the callback manager.\nasync on_chain_end(outputs: Union[Dict[str, Any], Any], **kwargs: Any) \u2192 None[source]\u00b6\nRun when traced chain group ends.\nParameters\noutputs (Union[Dict[str, Any], Any]) \u2013 The outputs of the chain.\nasync on_chain_error(error: BaseException, **kwargs: Any) \u2192 None[source]\u00b6\nRun when chain errors.\nParameters\nerror (Exception or KeyboardInterrupt) \u2013 The error.\nasync on_chain_start(serialized: Dict[str, Any], inputs: Union[Dict[str, Any], Any], run_id: Optional[UUID] = None, **kwargs: Any) \u2192 AsyncCallbackManagerForChainRun\u00b6\nRun when chain starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized chain.\ninputs (Union[Dict[str, Any], Any]) \u2013 The inputs to the chain.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nReturns\nThe async callback managerfor the chain run.\nReturn type\nAsyncCallbackManagerForChainRun\nasync on_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], **kwargs: Any) \u2192 List[AsyncCallbackManagerForLLMRun]\u00b6\nRun when LLM starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized LLM.\nmessages (List[List[BaseMessage]]) \u2013 The list of messages.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nReturns\nThe list ofasync callback managers, one for each LLM Run\ncorresponding to each inner  message list.\nReturn type\nList[AsyncCallbackManagerForLLMRun]", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForChainGroup.html"}
{"id": "ec4971e8f79b-3", "text": "Return type\nList[AsyncCallbackManagerForLLMRun]\nasync on_llm_start(serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) \u2192 List[AsyncCallbackManagerForLLMRun]\u00b6\nRun when LLM starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized LLM.\nprompts (List[str]) \u2013 The list of prompts.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nReturns\nThe list of asynccallback managers, one for each LLM Run corresponding\nto each prompt.\nReturn type\nList[AsyncCallbackManagerForLLMRun]\nasync on_retriever_start(serialized: Dict[str, Any], query: str, run_id: Optional[UUID] = None, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 AsyncCallbackManagerForRetrieverRun\u00b6\nRun when retriever starts running.\nasync on_tool_start(serialized: Dict[str, Any], input_str: str, run_id: Optional[UUID] = None, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 AsyncCallbackManagerForToolRun\u00b6\nRun when tool starts running.\nParameters\nserialized (Dict[str, Any]) \u2013 The serialized tool.\ninput_str (str) \u2013 The input to the tool.\nrun_id (UUID, optional) \u2013 The ID of the run. Defaults to None.\nparent_run_id (UUID, optional) \u2013 The ID of the parent run.\nDefaults to None.\nReturns\nThe async callback managerfor the tool run.\nReturn type\nAsyncCallbackManagerForToolRun\nremove_handler(handler: BaseCallbackHandler) \u2192 None\u00b6\nRemove a handler from the callback manager.\nremove_metadata(keys: List[str]) \u2192 None\u00b6\nremove_tags(tags: List[str]) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForChainGroup.html"}
{"id": "ec4971e8f79b-4", "text": "remove_tags(tags: List[str]) \u2192 None\u00b6\nset_handler(handler: BaseCallbackHandler, inherit: bool = True) \u2192 None\u00b6\nSet handler as the only handler on the callback manager.\nset_handlers(handlers: List[BaseCallbackHandler], inherit: bool = True) \u2192 None\u00b6\nSet handlers as the only handlers on the callback manager.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.AsyncCallbackManagerForChainGroup.html"}
{"id": "fa1666fb221e-0", "text": "langchain.schema.runnable.history.RunnableWithMessageHistory\u00b6\nclass langchain.schema.runnable.history.RunnableWithMessageHistory[source]\u00b6\nBases: RunnableBindingBase\nA runnable that manages chat message history for another runnable.\nBase runnable must have inputs and outputs that can be converted to a list ofBaseMessages.\nRunnableWithMessageHistory must always be called with a config that contains session_id, e.g.:{\"configurable\": {\"session_id\": \"<SESSION_ID>\"}}\nExample (dict input):from typing import Optional\nfrom langchain.chat_models import ChatAnthropic\nfrom langchain.memory.chat_message_histories import RedisChatMessageHistory\nfrom langchain.prompts import ChatPromptTemplate, MessagesPlaceholder\nfrom langchain.schema.runnable.history import RunnableWithMessageHistory\nprompt = ChatPromptTemplate.from_messages([\n    (\"system\", \"You're an assistant who's good at {ability}\"),\n    MessagesPlaceholder(variable_name=\"history\"),\n    (\"human\", \"{question}\"),\n])\nchain = prompt | ChatAnthropic(model=\"claude-2\")\nchain_with_history = RunnableWithMessageHistory(\n    chain,\n    RedisChatMessageHistory,\n    input_messages_key=\"question\",\n    history_messages_key=\"history\",\n)\nchain_with_history.invoke(\n    {\"ability\": \"math\", \"question\": \"What does cosine mean?\"},\n    config={\"configurable\": {\"session_id\": \"foo\"}}\n)\n# -> \"Cosine is ...\"\nchain_with_history.invoke(\n    {\"ability\": \"math\", \"question\": \"What's its inverse\"},\n    config={\"configurable\": {\"session_id\": \"foo\"}}\n)\n# -> \"The inverse of cosine is called arccosine ...\"\nInitialize RunnableWithMessageHistory.\nParameters\nrunnable \u2013 The base Runnable to be wrapped.\nMust take as input one of:\n- A sequence of BaseMessages", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "fa1666fb221e-1", "text": "Must take as input one of:\n- A sequence of BaseMessages\n- A dict with one key for all messages\n- A dict with one key for the current input string/message(s) and\na separate key for historical messages. If the input key points\nto a string, it will be treated as a HumanMessage in history.\nMust return as output one of:\n- A string which can be treated as an AIMessage\n- A BaseMessage or sequence of BaseMessages\n- A dict with a key for a BaseMessage or sequence of BaseMessages\nget_session_history \u2013 Function that returns a new BaseChatMessageHistory\ngiven a session id. Should take a single\npositional argument session_id which is a string and a named argument\nuser_id which can be a string or None. e.g.:\n```python\ndef get_session_history(\nsession_id: str,\n*,\nuser_id: Optional[str]=None\n) -> BaseChatMessageHistory:\u2026\n```\ninput_messages_key \u2013 Must be specified if the base runnable accepts a dict\nas input.\noutput_messages_key \u2013 Must be specified if the base runnable returns a dict\nas output.\nhistory_messages_key \u2013 Must be specified if the base runnable accepts a dict\nas input and expects a separate key for historical messages.\n**kwargs \u2013 Arbitrary additional kwargs to pass to parent class\nRunnableBindingBase init.\nparam bound: Runnable[Input, Output] [Required]\u00b6\nparam config: RunnableConfig [Optional]\u00b6\nparam config_factories: List[Callable[[RunnableConfig], RunnableConfig]] [Optional]\u00b6\nparam custom_input_type: Optional[Any] = None\u00b6\nparam custom_output_type: Optional[Any] = None\u00b6\nparam get_session_history: GetSessionHistoryCallable [Required]\u00b6\nparam history_messages_key: Optional[str] = None\u00b6\nparam input_messages_key: Optional[str] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "fa1666fb221e-2", "text": "param input_messages_key: Optional[str] = None\u00b6\nparam kwargs: Mapping[str, Any] [Optional]\u00b6\nparam output_messages_key: Optional[str] = None\u00b6\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "fa1666fb221e-3", "text": "Stream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "fa1666fb221e-4", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "fa1666fb221e-5", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel][source]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "fa1666fb221e-6", "text": "This method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Output\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "fa1666fb221e-7", "text": "Return a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "fa1666fb221e-8", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "fa1666fb221e-9", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.history.RunnableWithMessageHistory.html"}
{"id": "c716287601dc-0", "text": "langchain.schema.prompt_template.format_document\u00b6\nlangchain.schema.prompt_template.format_document(doc: Document, prompt: BasePromptTemplate) \u2192 str[source]\u00b6\nFormat a document into a string based on a prompt template.\nFirst, this pulls information from the document from two sources:\npage_content:This takes the information from the document.page_content\nand assigns it to a variable named page_content.\nmetadata:This takes information from document.metadata and assigns\nit to variables of the same name.\nThose variables are then passed into the prompt to produce a formatted string.\nParameters\ndoc \u2013 Document, the page_content and metadata will be used to create\nthe final string.\nprompt \u2013 BasePromptTemplate, will be used to format the page_content\nand metadata into the final string.\nReturns\nstring of the document formatted.\nExample\nfrom langchain.schema import Document\nfrom langchain.prompts import PromptTemplate\ndoc = Document(page_content=\"This is a joke\", metadata={\"page\": \"1\"})\nprompt = PromptTemplate.from_template(\"Page {page}: {page_content}\")\nformat_document(doc, prompt)\n>>> \"Page 1: This is a joke\"\nExamples using format_document\u00b6\nFirst we add a step to load memory", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.prompt_template.format_document.html"}
{"id": "f197a8fd57c2-0", "text": "langchain.schema.runnable.config.merge_configs\u00b6\nlangchain.schema.runnable.config.merge_configs(*configs: Optional[RunnableConfig]) \u2192 RunnableConfig[source]\u00b6\nMerge multiple configs into one.\nParameters\n*configs (Optional[RunnableConfig]) \u2013 The configs to merge.\nReturns\nThe merged config.\nReturn type\nRunnableConfig", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.config.merge_configs.html"}
{"id": "876c27268dc1-0", "text": "langchain.schema.callbacks.manager.ahandle_event\u00b6\nasync langchain.schema.callbacks.manager.ahandle_event(handlers: List[BaseCallbackHandler], event_name: str, ignore_condition_name: Optional[str], *args: Any, **kwargs: Any) \u2192 None[source]\u00b6\nGeneric event handler for AsyncCallbackManager.\nNote: This function is used by langserve to handle events.\nParameters\nhandlers \u2013 The list of handlers that will handle the event\nevent_name \u2013 The name of the event (e.g., \u201con_llm_start\u201d)\nignore_condition_name \u2013 Name of the attribute defined on handler\nthat if True will cause the handler to be skipped for the given event\n*args \u2013 The arguments to pass to the event handler\n**kwargs \u2013 The keyword arguments to pass to the event handler", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.manager.ahandle_event.html"}
{"id": "b75bae1cf445-0", "text": "langchain.schema.callbacks.base.ToolManagerMixin\u00b6\nclass langchain.schema.callbacks.base.ToolManagerMixin[source]\u00b6\nMixin for tool callbacks.\nMethods\n__init__()\non_tool_end(output,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool ends running.\non_tool_error(error,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun when tool errors.\n__init__()\u00b6\non_tool_end(output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when tool ends running.\non_tool_error(error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nRun when tool errors.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.base.ToolManagerMixin.html"}
{"id": "b74edacdc0a7-0", "text": "langchain.schema.callbacks.tracers.evaluation.EvaluatorCallbackHandler\u00b6\nclass langchain.schema.callbacks.tracers.evaluation.EvaluatorCallbackHandler(evaluators: Sequence[RunEvaluator], client: Optional[Client] = None, example_id: Optional[Union[str, UUID]] = None, skip_unfinished: bool = True, project_name: Optional[str] = 'evaluators', max_concurrency: Optional[int] = None, **kwargs: Any)[source]\u00b6\nA tracer that runs a run evaluator whenever a run is persisted.\nParameters\nevaluators (Sequence[RunEvaluator]) \u2013 The run evaluators to apply to all top level runs.\nclient (LangSmith Client, optional) \u2013 The LangSmith client instance to use for evaluating the runs.\nIf not specified, a new instance will be created.\nexample_id (Union[UUID, str], optional) \u2013 The example ID to be associated with the runs.\nproject_name (str, optional) \u2013 The LangSmith project name to be organize eval chain runs under.\nexample_id\u00b6\nThe example ID associated with the runs.\nType\nUnion[UUID, None]\nclient\u00b6\nThe LangSmith client instance used for evaluating the runs.\nType\nClient\nevaluators\u00b6\nThe sequence of run evaluators to be executed.\nType\nSequence[RunEvaluator]\nexecutor\u00b6\nThe thread pool executor used for running the evaluators.\nType\nThreadPoolExecutor\nfutures\u00b6\nThe set of futures representing the running evaluators.\nType\nSet[Future]\nskip_unfinished\u00b6\nWhether to skip runs that are not finished or raised\nan error.\nType\nbool\nproject_name\u00b6\nThe LangSmith project name to be organize eval chain runs under.\nType\nOptional[str]\nAttributes\nignore_agent\nWhether to ignore agent callbacks.\nignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.evaluation.EvaluatorCallbackHandler.html"}
{"id": "b74edacdc0a7-1", "text": "ignore_chain\nWhether to ignore chain callbacks.\nignore_chat_model\nWhether to ignore chat model callbacks.\nignore_llm\nWhether to ignore LLM callbacks.\nignore_retriever\nWhether to ignore retriever callbacks.\nignore_retry\nWhether to ignore retry callbacks.\nname\nraise_error\nrun_inline\nMethods\n__init__(evaluators[,\u00a0client,\u00a0example_id,\u00a0...])\non_agent_action(action,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent action.\non_agent_finish(finish,\u00a0*,\u00a0run_id[,\u00a0...])\nRun on agent end.\non_chain_end(outputs,\u00a0*,\u00a0run_id[,\u00a0inputs])\nEnd a trace for a chain run.\non_chain_error(error,\u00a0*[,\u00a0inputs])\nHandle an error for a chain run.\non_chain_start(serialized,\u00a0inputs,\u00a0*,\u00a0run_id)\nStart a trace for a chain run.\non_chat_model_start(serialized,\u00a0messages,\u00a0*,\u00a0...)\nRun when a chat model starts running.\non_llm_end(response,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for an LLM run.\non_llm_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for an LLM run.\non_llm_new_token(token,\u00a0*[,\u00a0chunk,\u00a0...])\nRun on new LLM token.\non_llm_start(serialized,\u00a0prompts,\u00a0*,\u00a0run_id)\nStart a trace for an LLM run.\non_retriever_end(documents,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever ends running.\non_retriever_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun when Retriever errors.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.evaluation.EvaluatorCallbackHandler.html"}
{"id": "b74edacdc0a7-2", "text": "Run when Retriever errors.\non_retriever_start(serialized,\u00a0query,\u00a0*,\u00a0run_id)\nRun when Retriever starts running.\non_retry(retry_state,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nRun on a retry event.\non_text(text,\u00a0*,\u00a0run_id[,\u00a0parent_run_id])\nRun on arbitrary text.\non_tool_end(output,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nEnd a trace for a tool run.\non_tool_error(error,\u00a0*,\u00a0run_id,\u00a0**kwargs)\nHandle an error for a tool run.\non_tool_start(serialized,\u00a0input_str,\u00a0*,\u00a0run_id)\nStart a trace for a tool run.\nwait_for_futures()\nWait for all futures to complete.\n__init__(evaluators: Sequence[RunEvaluator], client: Optional[Client] = None, example_id: Optional[Union[str, UUID]] = None, skip_unfinished: bool = True, project_name: Optional[str] = 'evaluators', max_concurrency: Optional[int] = None, **kwargs: Any) \u2192 None[source]\u00b6\non_agent_action(action: AgentAction, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent action.\non_agent_finish(finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on agent end.\non_chain_end(outputs: Dict[str, Any], *, run_id: UUID, inputs: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a chain run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.evaluation.EvaluatorCallbackHandler.html"}
{"id": "b74edacdc0a7-3", "text": "End a trace for a chain run.\non_chain_error(error: BaseException, *, inputs: Optional[Dict[str, Any]] = None, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a chain run.\non_chain_start(serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, run_type: Optional[str] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a chain run.\non_chat_model_start(serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nRun when a chat model starts running.\non_llm_end(response: LLMResult, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for an LLM run.\non_llm_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for an LLM run.\non_llm_new_token(token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Run\u00b6\nRun on new LLM token. Only available when streaming is enabled.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.evaluation.EvaluatorCallbackHandler.html"}
{"id": "b74edacdc0a7-4", "text": "Run on new LLM token. Only available when streaming is enabled.\non_llm_start(serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for an LLM run.\non_retriever_end(documents: Sequence[Document], *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever ends running.\non_retriever_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever errors.\non_retriever_start(serialized: Dict[str, Any], query: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nRun when Retriever starts running.\non_retry(retry_state: RetryCallState, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nRun on a retry event.\non_text(text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) \u2192 Any\u00b6\nRun on arbitrary text.\non_tool_end(output: str, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nEnd a trace for a tool run.\non_tool_error(error: BaseException, *, run_id: UUID, **kwargs: Any) \u2192 Run\u00b6\nHandle an error for a tool run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.evaluation.EvaluatorCallbackHandler.html"}
{"id": "b74edacdc0a7-5", "text": "Handle an error for a tool run.\non_tool_start(serialized: Dict[str, Any], input_str: str, *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any) \u2192 Run\u00b6\nStart a trace for a tool run.\nwait_for_futures() \u2192 None[source]\u00b6\nWait for all futures to complete.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.callbacks.tracers.evaluation.EvaluatorCallbackHandler.html"}
{"id": "c6f4ab900c6d-0", "text": "langchain.schema.runnable.base.RunnableSerializable\u00b6\nclass langchain.schema.runnable.base.RunnableSerializable[source]\u00b6\nBases: Serializable, Runnable[Input, Output]\nA Runnable that can be serialized to JSON.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Output\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "c6f4ab900c6d-1", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "c6f4ab900c6d-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output][source]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output][source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "c6f4ab900c6d-3", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "c6f4ab900c6d-4", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nabstract invoke(input: Input, config: Optional[RunnableConfig] = None) \u2192 Output\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "c6f4ab900c6d-5", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "c6f4ab900c6d-6", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "c6f4ab900c6d-7", "text": "added to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "c6f4ab900c6d-8", "text": "property output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.runnable.base.RunnableSerializable.html"}
{"id": "8209bf40ac13-0", "text": "langchain.schema.messages.BaseMessage\u00b6\nclass langchain.schema.messages.BaseMessage[source]\u00b6\nBases: Serializable\nThe base abstract Message class.\nMessages are the inputs and outputs of ChatModels.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam additional_kwargs: dict [Optional]\u00b6\nAny additional information.\nparam content: Union[str, List[Union[str, Dict]]] [Required]\u00b6\nThe string contents of the message.\nparam type: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.BaseMessage.html"}
{"id": "8209bf40ac13-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this class is serializable.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.BaseMessage.html"}
{"id": "8209bf40ac13-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nExamples using BaseMessage\u00b6\nSQL Chat Message History\nCAMEL Role-Playing Autonomous Cooperative Agents\nMulti-agent decentralized speaker selection\nMulti-agent authoritarian speaker selection\nMulti-Player Dungeons & Dragons\nSimulated Environment: Gymnasium\nAgent Debates with Tools", "source": "lang/api.python.langchain.com/en/latest/schema/langchain.schema.messages.BaseMessage.html"}
{"id": "0d6e7b01bb24-0", "text": "langchain.graphs.rdf_graph.RdfGraph\u00b6\nclass langchain.graphs.rdf_graph.RdfGraph(source_file: Optional[str] = None, serialization: Optional[str] = 'ttl', query_endpoint: Optional[str] = None, update_endpoint: Optional[str] = None, standard: Optional[str] = 'rdf', local_copy: Optional[str] = None)[source]\u00b6\nRDFlib wrapper for graph operations.\nModes:\n* local: Local file - can be queried and changed\n* online: Online file - can only be queried, changes can be stored locally\n* store: Triple store - can be queried and changed if update_endpoint available\nTogether with a source file, the serialization should be specified.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nSet up the RDFlib graph\nParameters\nsource_file \u2013 either a path for a local file or a URL\nserialization \u2013 serialization of the input\nquery_endpoint \u2013 SPARQL endpoint for queries, read access\nupdate_endpoint \u2013 SPARQL endpoint for UPDATE queries, write access\nstandard \u2013 RDF, RDFS, or OWL\nlocal_copy \u2013 new local copy for storing changes\nAttributes\nget_schema\nReturns the schema of the graph database.\nMethods\n__init__([source_file,\u00a0serialization,\u00a0...])\nSet up the RDFlib graph\nload_schema()\nLoad the graph schema information.\nquery(query)\nQuery the graph.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.rdf_graph.RdfGraph.html"}
{"id": "0d6e7b01bb24-1", "text": "load_schema()\nLoad the graph schema information.\nquery(query)\nQuery the graph.\nupdate(query)\nUpdate the graph.\n__init__(source_file: Optional[str] = None, serialization: Optional[str] = 'ttl', query_endpoint: Optional[str] = None, update_endpoint: Optional[str] = None, standard: Optional[str] = 'rdf', local_copy: Optional[str] = None) \u2192 None[source]\u00b6\nSet up the RDFlib graph\nParameters\nsource_file \u2013 either a path for a local file or a URL\nserialization \u2013 serialization of the input\nquery_endpoint \u2013 SPARQL endpoint for queries, read access\nupdate_endpoint \u2013 SPARQL endpoint for UPDATE queries, write access\nstandard \u2013 RDF, RDFS, or OWL\nlocal_copy \u2013 new local copy for storing changes\nload_schema() \u2192 None[source]\u00b6\nLoad the graph schema information.\nquery(query: str) \u2192 List[rdflib.query.ResultRow][source]\u00b6\nQuery the graph.\nupdate(query: str) \u2192 None[source]\u00b6\nUpdate the graph.\nExamples using RdfGraph\u00b6\nGraphSparqlQAChain", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.rdf_graph.RdfGraph.html"}
{"id": "6eef03a5a44e-0", "text": "langchain.graphs.graph_document.GraphDocument\u00b6\nclass langchain.graphs.graph_document.GraphDocument[source]\u00b6\nBases: Serializable\nRepresents a graph document consisting of nodes and relationships.\nnodes\u00b6\nA list of nodes in the graph.\nType\nList[Node]\nrelationships\u00b6\nA list of relationships in the graph.\nType\nList[Relationship]\nsource\u00b6\nThe document from which the graph information is derived.\nType\nDocument\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam nodes: List[langchain.graphs.graph_document.Node] [Required]\u00b6\nparam relationships: List[langchain.graphs.graph_document.Relationship] [Required]\u00b6\nparam source: langchain.schema.document.Document [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.graph_document.GraphDocument.html"}
{"id": "6eef03a5a44e-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.graph_document.GraphDocument.html"}
{"id": "6eef03a5a44e-2", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.graph_document.GraphDocument.html"}
{"id": "8513d83af50e-0", "text": "langchain.graphs.falkordb_graph.FalkorDBGraph\u00b6\nclass langchain.graphs.falkordb_graph.FalkorDBGraph(database: str, host: str = 'localhost', port: int = 6379, username: Optional[str] = None, password: Optional[str] = None, ssl: bool = False)[source]\u00b6\nFalkorDB wrapper for graph operations.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new FalkorDB graph wrapper instance.\nAttributes\nget_schema\nReturns the schema of the FalkorDB database\nget_structured_schema\nReturns the structured schema of the Graph\nMethods\n__init__(database[,\u00a0host,\u00a0port,\u00a0username,\u00a0...])\nCreate a new FalkorDB graph wrapper instance.\nadd_graph_documents(graph_documents[,\u00a0...])\nTake GraphDocument as input as uses it to construct a graph.\nquery(query[,\u00a0params])\nQuery FalkorDB database.\nrefresh_schema()\nRefreshes the schema of the FalkorDB database\n__init__(database: str, host: str = 'localhost', port: int = 6379, username: Optional[str] = None, password: Optional[str] = None, ssl: bool = False) \u2192 None[source]\u00b6\nCreate a new FalkorDB graph wrapper instance.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.falkordb_graph.FalkorDBGraph.html"}
{"id": "8513d83af50e-1", "text": "Create a new FalkorDB graph wrapper instance.\nadd_graph_documents(graph_documents: List[GraphDocument], include_source: bool = False) \u2192 None[source]\u00b6\nTake GraphDocument as input as uses it to construct a graph.\nquery(query: str, params: dict = {}) \u2192 List[Dict[str, Any]][source]\u00b6\nQuery FalkorDB database.\nrefresh_schema() \u2192 None[source]\u00b6\nRefreshes the schema of the FalkorDB database\nExamples using FalkorDBGraph\u00b6\nFalkorDBQAChain", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.falkordb_graph.FalkorDBGraph.html"}
{"id": "f1caadfcdd6b-0", "text": "langchain.graphs.neo4j_graph.Neo4jGraph\u00b6\nclass langchain.graphs.neo4j_graph.Neo4jGraph(url: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None, database: str = 'neo4j')[source]\u00b6\nNeo4j wrapper for graph operations.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new Neo4j graph wrapper instance.\nAttributes\nget_schema\nReturns the schema of the Graph\nget_structured_schema\nReturns the structured schema of the Graph\nMethods\n__init__([url,\u00a0username,\u00a0password,\u00a0database])\nCreate a new Neo4j graph wrapper instance.\nadd_graph_documents(graph_documents[,\u00a0...])\nTake GraphDocument as input as uses it to construct a graph.\nquery(query[,\u00a0params])\nQuery Neo4j database.\nrefresh_schema()\nRefreshes the Neo4j graph schema information.\n__init__(url: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None, database: str = 'neo4j') \u2192 None[source]\u00b6\nCreate a new Neo4j graph wrapper instance.\nadd_graph_documents(graph_documents: List[GraphDocument], include_source: bool = False) \u2192 None[source]\u00b6\nTake GraphDocument as input as uses it to construct a graph.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.neo4j_graph.Neo4jGraph.html"}
{"id": "f1caadfcdd6b-1", "text": "Take GraphDocument as input as uses it to construct a graph.\nquery(query: str, params: dict = {}) \u2192 List[Dict[str, Any]][source]\u00b6\nQuery Neo4j database.\nrefresh_schema() \u2192 None[source]\u00b6\nRefreshes the Neo4j graph schema information.\nExamples using Neo4jGraph\u00b6\nNeo4j\nDiffbot Graph Transformer\nNeo4j DB QA chain", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.neo4j_graph.Neo4jGraph.html"}
{"id": "cc77fedc2afc-0", "text": "langchain.graphs.networkx_graph.NetworkxEntityGraph\u00b6\nclass langchain.graphs.networkx_graph.NetworkxEntityGraph(graph: Optional[Any] = None)[source]\u00b6\nNetworkx wrapper for entity graph operations.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new graph.\nMethods\n__init__([graph])\nCreate a new graph.\nadd_triple(knowledge_triple)\nAdd a triple to the graph.\nclear()\nClear the graph.\ndelete_triple(knowledge_triple)\nDelete a triple from the graph.\ndraw_graphviz(**kwargs)\nProvides better drawing\nfrom_gml(gml_path)\nget_entity_knowledge(entity[,\u00a0depth])\nGet information about an entity.\nget_topological_sort()\nGet a list of entity names in the graph sorted by causal dependence.\nget_triples()\nGet all triples in the graph.\nwrite_to_gml(path)\n__init__(graph: Optional[Any] = None) \u2192 None[source]\u00b6\nCreate a new graph.\nadd_triple(knowledge_triple: KnowledgeTriple) \u2192 None[source]\u00b6\nAdd a triple to the graph.\nclear() \u2192 None[source]\u00b6\nClear the graph.\ndelete_triple(knowledge_triple: KnowledgeTriple) \u2192 None[source]\u00b6\nDelete a triple from the graph.\ndraw_graphviz(**kwargs: Any) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.networkx_graph.NetworkxEntityGraph.html"}
{"id": "cc77fedc2afc-1", "text": "draw_graphviz(**kwargs: Any) \u2192 None[source]\u00b6\nProvides better drawing\nUsage in a jupyter notebook:\n>>> from IPython.display import SVG\n>>> self.draw_graphviz_svg(layout=\"dot\", filename=\"web.svg\")\n>>> SVG('web.svg')\nclassmethod from_gml(gml_path: str) \u2192 NetworkxEntityGraph[source]\u00b6\nget_entity_knowledge(entity: str, depth: int = 1) \u2192 List[str][source]\u00b6\nGet information about an entity.\nget_topological_sort() \u2192 List[str][source]\u00b6\nGet a list of entity names in the graph sorted by causal dependence.\nget_triples() \u2192 List[Tuple[str, str, str]][source]\u00b6\nGet all triples in the graph.\nwrite_to_gml(path: str) \u2192 None[source]\u00b6\nExamples using NetworkxEntityGraph\u00b6\nGraph QA", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.networkx_graph.NetworkxEntityGraph.html"}
{"id": "77fe050102bc-0", "text": "langchain.graphs.memgraph_graph.MemgraphGraph\u00b6\nclass langchain.graphs.memgraph_graph.MemgraphGraph(url: str, username: str, password: str, *, database: str = 'memgraph')[source]\u00b6\nMemgraph wrapper for graph operations.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new Memgraph graph wrapper instance.\nAttributes\nget_schema\nReturns the schema of the Graph\nget_structured_schema\nReturns the structured schema of the Graph\nMethods\n__init__(url,\u00a0username,\u00a0password,\u00a0*[,\u00a0database])\nCreate a new Memgraph graph wrapper instance.\nadd_graph_documents(graph_documents[,\u00a0...])\nTake GraphDocument as input as uses it to construct a graph.\nquery(query[,\u00a0params])\nQuery Neo4j database.\nrefresh_schema()\nRefreshes the Memgraph graph schema information.\n__init__(url: str, username: str, password: str, *, database: str = 'memgraph') \u2192 None[source]\u00b6\nCreate a new Memgraph graph wrapper instance.\nadd_graph_documents(graph_documents: List[GraphDocument], include_source: bool = False) \u2192 None\u00b6\nTake GraphDocument as input as uses it to construct a graph.\nquery(query: str, params: dict = {}) \u2192 List[Dict[str, Any]]\u00b6\nQuery Neo4j database.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.memgraph_graph.MemgraphGraph.html"}
{"id": "77fe050102bc-1", "text": "Query Neo4j database.\nrefresh_schema() \u2192 None[source]\u00b6\nRefreshes the Memgraph graph schema information.\nExamples using MemgraphGraph\u00b6\nMemgraph QA chain", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.memgraph_graph.MemgraphGraph.html"}
{"id": "6767b6c855b8-0", "text": "langchain.graphs.graph_document.Relationship\u00b6\nclass langchain.graphs.graph_document.Relationship[source]\u00b6\nBases: Serializable\nRepresents a directed relationship between two nodes in a graph.\nsource\u00b6\nThe source node of the relationship.\nType\nNode\ntarget\u00b6\nThe target node of the relationship.\nType\nNode\ntype\u00b6\nThe type of the relationship.\nType\nstr\nproperties\u00b6\nAdditional properties associated with the relationship.\nType\ndict\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam properties: dict [Optional]\u00b6\nparam source: langchain.graphs.graph_document.Node [Required]\u00b6\nparam target: langchain.graphs.graph_document.Node [Required]\u00b6\nparam type: str [Required]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.graph_document.Relationship.html"}
{"id": "6767b6c855b8-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.graph_document.Relationship.html"}
{"id": "6767b6c855b8-2", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.graph_document.Relationship.html"}
{"id": "4db7acbbd147-0", "text": "langchain.graphs.neptune_graph.NeptuneQueryException\u00b6\nclass langchain.graphs.neptune_graph.NeptuneQueryException(exception: Union[str, Dict])[source]\u00b6\nA class to handle queries that fail to execute", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.neptune_graph.NeptuneQueryException.html"}
{"id": "25ef9fd27952-0", "text": "langchain.graphs.graph_store.GraphStore\u00b6\nclass langchain.graphs.graph_store.GraphStore[source]\u00b6\nAn abstract class wrapper for graph operations.\nAttributes\nget_schema\nReturns the schema of the Graph database\nget_structured_schema\nReturns the schema of the Graph database\nMethods\n__init__()\nadd_graph_documents(graph_documents[,\u00a0...])\nTake GraphDocument as input as uses it to construct a graph.\nquery(query[,\u00a0params])\nQuery the graph.\nrefresh_schema()\nRefreshes the graph schema information.\n__init__()\u00b6\nabstract add_graph_documents(graph_documents: List[GraphDocument], include_source: bool = False) \u2192 None[source]\u00b6\nTake GraphDocument as input as uses it to construct a graph.\nabstract query(query: str, params: dict = {}) \u2192 List[Dict[str, Any]][source]\u00b6\nQuery the graph.\nabstract refresh_schema() \u2192 None[source]\u00b6\nRefreshes the graph schema information.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.graph_store.GraphStore.html"}
{"id": "2220aa1b9347-0", "text": "langchain.graphs.graph_document.Node\u00b6\nclass langchain.graphs.graph_document.Node[source]\u00b6\nBases: Serializable\nRepresents a node in a graph with associated properties.\nid\u00b6\nA unique identifier for the node.\nType\nUnion[str, int]\ntype\u00b6\nThe type or label of the node, default is \u201cNode\u201d.\nType\nstr\nproperties\u00b6\nAdditional properties and metadata associated with the node.\nType\ndict\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam id: Union[str, int] [Required]\u00b6\nparam properties: dict [Optional]\u00b6\nparam type: str = 'Node'\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.graph_document.Node.html"}
{"id": "2220aa1b9347-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.graph_document.Node.html"}
{"id": "2220aa1b9347-2", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.graph_document.Node.html"}
{"id": "964dfea21381-0", "text": "langchain.graphs.networkx_graph.get_entities\u00b6\nlangchain.graphs.networkx_graph.get_entities(entity_str: str) \u2192 List[str][source]\u00b6\nExtract entities from entity string.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.networkx_graph.get_entities.html"}
{"id": "be0ddd3d8afd-0", "text": "langchain.graphs.networkx_graph.parse_triples\u00b6\nlangchain.graphs.networkx_graph.parse_triples(knowledge_str: str) \u2192 List[KnowledgeTriple][source]\u00b6\nParse knowledge triples from the knowledge string.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.networkx_graph.parse_triples.html"}
{"id": "0fa31c184a0f-0", "text": "langchain.graphs.arangodb_graph.get_arangodb_client\u00b6\nlangchain.graphs.arangodb_graph.get_arangodb_client(url: Optional[str] = None, dbname: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None) \u2192 Any[source]\u00b6\nGet the Arango DB client from credentials.\nParameters\nurl \u2013 Arango DB url. Can be passed in as named arg or set as environment\nvar ARANGODB_URL. Defaults to \u201chttp://localhost:8529\u201d.\ndbname \u2013 Arango DB name. Can be passed in as named arg or set as\nenvironment var ARANGODB_DBNAME. Defaults to \u201c_system\u201d.\nusername \u2013 Can be passed in as named arg or set as environment var\nARANGODB_USERNAME. Defaults to \u201croot\u201d.\npassword \u2013 Can be passed ni as named arg or set as environment var\nARANGODB_PASSWORD. Defaults to \u201c\u201d.\nReturns\nAn arango.database.StandardDatabase.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.arangodb_graph.get_arangodb_client.html"}
{"id": "b7684ba0a1a4-0", "text": "langchain.graphs.nebula_graph.NebulaGraph\u00b6\nclass langchain.graphs.nebula_graph.NebulaGraph(space: str, username: str = 'root', password: str = 'nebula', address: str = '127.0.0.1', port: int = 9669, session_pool_size: int = 30)[source]\u00b6\nNebulaGraph wrapper for graph operations.\nNebulaGraph inherits methods from Neo4jGraph to bring ease to the user space.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new NebulaGraph wrapper instance.\nAttributes\nget_schema\nReturns the schema of the NebulaGraph database\nMethods\n__init__(space[,\u00a0username,\u00a0password,\u00a0...])\nCreate a new NebulaGraph wrapper instance.\nexecute(query[,\u00a0params,\u00a0retry])\nQuery NebulaGraph database.\nquery(query[,\u00a0retry])\nrefresh_schema()\nRefreshes the NebulaGraph schema information.\n__init__(space: str, username: str = 'root', password: str = 'nebula', address: str = '127.0.0.1', port: int = 9669, session_pool_size: int = 30) \u2192 None[source]\u00b6\nCreate a new NebulaGraph wrapper instance.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.nebula_graph.NebulaGraph.html"}
{"id": "b7684ba0a1a4-1", "text": "Create a new NebulaGraph wrapper instance.\nexecute(query: str, params: Optional[dict] = None, retry: int = 0) \u2192 Any[source]\u00b6\nQuery NebulaGraph database.\nquery(query: str, retry: int = 0) \u2192 Dict[str, Any][source]\u00b6\nrefresh_schema() \u2192 None[source]\u00b6\nRefreshes the NebulaGraph schema information.\nExamples using NebulaGraph\u00b6\nNebulaGraphQAChain", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.nebula_graph.NebulaGraph.html"}
{"id": "42a6bca9ef73-0", "text": "langchain.graphs.kuzu_graph.KuzuGraph\u00b6\nclass langchain.graphs.kuzu_graph.KuzuGraph(db: Any, database: str = 'kuzu')[source]\u00b6\nK\u00f9zu wrapper for graph operations.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nAttributes\nget_schema\nReturns the schema of the K\u00f9zu database\nMethods\n__init__(db[,\u00a0database])\nquery(query[,\u00a0params])\nQuery K\u00f9zu database\nrefresh_schema()\nRefreshes the K\u00f9zu graph schema information\n__init__(db: Any, database: str = 'kuzu') \u2192 None[source]\u00b6\nquery(query: str, params: dict = {}) \u2192 List[Dict[str, Any]][source]\u00b6\nQuery K\u00f9zu database\nrefresh_schema() \u2192 None[source]\u00b6\nRefreshes the K\u00f9zu graph schema information\nExamples using KuzuGraph\u00b6\nKuzuQAChain", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.kuzu_graph.KuzuGraph.html"}
{"id": "ff765c3a274d-0", "text": "langchain.graphs.hugegraph.HugeGraph\u00b6\nclass langchain.graphs.hugegraph.HugeGraph(username: str = 'default', password: str = 'default', address: str = '127.0.0.1', port: int = 8081, graph: str = 'hugegraph')[source]\u00b6\nHugeGraph wrapper for graph operations.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new HugeGraph wrapper instance.\nAttributes\nget_schema\nReturns the schema of the HugeGraph database\nMethods\n__init__([username,\u00a0password,\u00a0address,\u00a0...])\nCreate a new HugeGraph wrapper instance.\nquery(query)\nrefresh_schema()\nRefreshes the HugeGraph schema information.\n__init__(username: str = 'default', password: str = 'default', address: str = '127.0.0.1', port: int = 8081, graph: str = 'hugegraph') \u2192 None[source]\u00b6\nCreate a new HugeGraph wrapper instance.\nquery(query: str) \u2192 List[Dict[str, Any]][source]\u00b6\nrefresh_schema() \u2192 None[source]\u00b6\nRefreshes the HugeGraph schema information.\nExamples using HugeGraph\u00b6\nHugeGraph QA Chain", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.hugegraph.HugeGraph.html"}
{"id": "60d9c90a9acb-0", "text": "langchain.graphs.arangodb_graph.ArangoGraph\u00b6\nclass langchain.graphs.arangodb_graph.ArangoGraph(db: Any)[source]\u00b6\nArangoDB wrapper for graph operations.\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new ArangoDB graph wrapper instance.\nAttributes\ndb\nschema\nMethods\n__init__(db)\nCreate a new ArangoDB graph wrapper instance.\nfrom_db_credentials([url,\u00a0dbname,\u00a0username,\u00a0...])\nConvenience constructor that builds Arango DB from credentials.\ngenerate_schema([sample_ratio])\nGenerates the schema of the ArangoDB Database and returns it User can specify a sample_ratio (0 to 1) to determine the ratio of documents/edges used (in relation to the Collection size) to render each Collection Schema.\nquery(query[,\u00a0top_k])\nQuery the ArangoDB database.\nset_db(db)\nset_schema([schema])\nSet the schema of the ArangoDB Database.\n__init__(db: Any) \u2192 None[source]\u00b6\nCreate a new ArangoDB graph wrapper instance.\nclassmethod from_db_credentials(url: Optional[str] = None, dbname: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None) \u2192 Any[source]\u00b6\nConvenience constructor that builds Arango DB from credentials.\nParameters", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.arangodb_graph.ArangoGraph.html"}
{"id": "60d9c90a9acb-1", "text": "Convenience constructor that builds Arango DB from credentials.\nParameters\nurl \u2013 Arango DB url. Can be passed in as named arg or set as environment\nvar ARANGODB_URL. Defaults to \u201chttp://localhost:8529\u201d.\ndbname \u2013 Arango DB name. Can be passed in as named arg or set as\nenvironment var ARANGODB_DBNAME. Defaults to \u201c_system\u201d.\nusername \u2013 Can be passed in as named arg or set as environment var\nARANGODB_USERNAME. Defaults to \u201croot\u201d.\npassword \u2013 Can be passed ni as named arg or set as environment var\nARANGODB_PASSWORD. Defaults to \u201c\u201d.\nReturns\nAn arango.database.StandardDatabase.\ngenerate_schema(sample_ratio: float = 0) \u2192 Dict[str, List[Dict[str, Any]]][source]\u00b6\nGenerates the schema of the ArangoDB Database and returns it\nUser can specify a sample_ratio (0 to 1) to determine the\nratio of documents/edges used (in relation to the Collection size)\nto render each Collection Schema.\nquery(query: str, top_k: Optional[int] = None, **kwargs: Any) \u2192 List[Dict[str, Any]][source]\u00b6\nQuery the ArangoDB database.\nset_db(db: Any) \u2192 None[source]\u00b6\nset_schema(schema: Optional[Dict[str, Any]] = None) \u2192 None[source]\u00b6\nSet the schema of the ArangoDB Database.\nAuto-generates Schema if schema is None.\nExamples using ArangoGraph\u00b6\nArangoDB QA chain", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.arangodb_graph.ArangoGraph.html"}
{"id": "1a9522a35e73-0", "text": "langchain.graphs.neptune_graph.NeptuneGraph\u00b6\nclass langchain.graphs.neptune_graph.NeptuneGraph(host: str, port: int = 8182, use_https: bool = True, client: Any = None, credentials_profile_name: Optional[str] = None, region_name: Optional[str] = None, service: str = 'neptunedata', sign: bool = True)[source]\u00b6\nNeptune wrapper for graph operations.\nParameters\nhost \u2013 endpoint for the database instance\nport \u2013 port number for the database instance, default is 8182\nuse_https \u2013 whether to use secure connection, default is True\nclient \u2013 optional boto3 Neptune client\ncredentials_profile_name \u2013 optional AWS profile name\nregion_name \u2013 optional AWS region, e.g., us-west-2\nservice \u2013 optional service name, default is neptunedata\nsign \u2013 optional, whether to sign the request payload, default is True\nExample\ngraph = NeptuneGraph(host=\u2019<my-cluster>\u2019,\nport=8182\n)\nSecurity note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.\nFailure to do so may result in data corruption or loss, since the calling\ncode may attempt commands that would result in deletion, mutation\nof data if appropriately prompted or reading sensitive data if such\ndata is present in the database.\nThe best way to guard against such negative outcomes is to (as appropriate)\nlimit the permissions granted to the credentials used with this tool.\nSee https://python.langchain.com/docs/security for more information.\nCreate a new Neptune graph wrapper instance.\nAttributes\nget_schema\nReturns the schema of the Neptune database\nMethods\n__init__(host[,\u00a0port,\u00a0use_https,\u00a0client,\u00a0...])\nCreate a new Neptune graph wrapper instance.\nquery(query[,\u00a0params])\nQuery Neptune database.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.neptune_graph.NeptuneGraph.html"}
{"id": "1a9522a35e73-1", "text": "query(query[,\u00a0params])\nQuery Neptune database.\n__init__(host: str, port: int = 8182, use_https: bool = True, client: Any = None, credentials_profile_name: Optional[str] = None, region_name: Optional[str] = None, service: str = 'neptunedata', sign: bool = True) \u2192 None[source]\u00b6\nCreate a new Neptune graph wrapper instance.\nquery(query: str, params: dict = {}) \u2192 Dict[str, Any][source]\u00b6\nQuery Neptune database.\nExamples using NeptuneGraph\u00b6\nNeptune Open Cypher QA Chain", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.neptune_graph.NeptuneGraph.html"}
{"id": "84654b042bf6-0", "text": "langchain.graphs.networkx_graph.KnowledgeTriple\u00b6\nclass langchain.graphs.networkx_graph.KnowledgeTriple(subject: str, predicate: str, object_: str)[source]\u00b6\nA triple in the graph.\nCreate new instance of KnowledgeTriple(subject, predicate, object_)\nAttributes\nobject_\nAlias for field number 2\npredicate\nAlias for field number 1\nsubject\nAlias for field number 0\nMethods\n__init__()\ncount(value,\u00a0/)\nReturn number of occurrences of value.\nfrom_string(triple_string)\nCreate a KnowledgeTriple from a string.\nindex(value[,\u00a0start,\u00a0stop])\nReturn first index of value.\n__init__()\u00b6\ncount(value, /)\u00b6\nReturn number of occurrences of value.\nclassmethod from_string(triple_string: str) \u2192 KnowledgeTriple[source]\u00b6\nCreate a KnowledgeTriple from a string.\nindex(value, start=0, stop=9223372036854775807, /)\u00b6\nReturn first index of value.\nRaises ValueError if the value is not present.", "source": "lang/api.python.langchain.com/en/latest/graphs/langchain.graphs.networkx_graph.KnowledgeTriple.html"}
{"id": "c70b98bdb4cd-0", "text": "langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain\u00b6\nclass langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain[source]\u00b6\nBases: Chain\nChain that interprets a prompt and executes python code to do symbolic math.\nExample\nfrom langchain.chains import LLMSymbolicMathChain\nfrom langchain.llms import OpenAI\nllm_symbolic_math = LLMSymbolicMathChain.from_llm(OpenAI())\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nDeprecated, use callbacks instead.\nparam callbacks: Callbacks = None\u00b6\nOptional list of callback handlers (or callback manager). Defaults to None.\nCallback handlers are called throughout the lifecycle of a call to a chain,\nstarting with on_chain_start, ending with on_chain_end or on_chain_error.\nEach custom chain can optionally call additional callback methods, see Callback docs\nfor full details.\nparam llm_chain: LLMChain [Required]\u00b6\nparam memory: Optional[BaseMemory] = None\u00b6\nOptional memory object. Defaults to None.\nMemory is a class that gets called at the start\nand at the end of every chain. At the start, memory loads variables and passes\nthem along in the chain. At the end, it saves any returned variables.\nThere are many different types of memory - please see memory docs\nfor the full catalog.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nOptional metadata associated with the chain. Defaults to None.\nThis metadata will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-1", "text": "and passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam tags: Optional[List[str]] = None\u00b6\nOptional list of tags associated with the chain. Defaults to None.\nThese tags will be associated with each call to this chain,\nand passed as arguments to the handlers defined in callbacks.\nYou can use these to eg identify a specific instance of a chain with its use case.\nparam verbose: bool [Optional]\u00b6\nWhether or not run in verbose mode. In verbose mode, some intermediate logs\nwill be printed to the console. Defaults to the global verbose value,\naccessible via langchain.globals.get_verbose().\n__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nExecute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-2", "text": "tags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) \u2192 Dict[str, Any]\u00b6\nAsynchronously execute the chain.\nParameters\ninputs \u2013 Dictionary of inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nreturn_only_outputs \u2013 Whether to return only outputs in the\nresponse. If True, only new keys generated by this chain will be\nreturned. If False, both input keys and new keys generated by this\nchain will be returned. Defaults to False.", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-3", "text": "chain will be returned. Defaults to False.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\nmetadata \u2013 Optional metadata associated with the chain. Defaults to None\ninclude_run_info \u2013 Whether to include run info in the response. Defaults\nto False.\nReturns\nA dict of named outputs. Should contain all outputs specified inChain.output_keys.\nasync ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) \u2192 List[Dict[str, str]]\u00b6\nCall the chain on all inputs in the list.\nasync arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-4", "text": "with all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nawait chain.arun(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nawait chain.arun(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nasync astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nDictionary representation of chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\n**kwargs \u2013 Keyword arguments passed to default pydantic.BaseModel.dict\nmethod.\nReturns\nA dictionary representation of the chain.\nExample\nchain.dict(exclude_unset=True)\n# -> {\"_type\": \"foo\", \"verbose\": False, ...}", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-8", "text": "# -> {\"_type\": \"foo\", \"verbose\": False, ...}\nclassmethod from_llm(llm: BaseLanguageModel, prompt: BasePromptTemplate = PromptTemplate(input_variables=['question'], template='Translate a math problem into a expression that can be executed using Python\\'s SymPy library. Use the output of running this code to answer the question.\\n\\nQuestion: ${{Question with math problem.}}\\n```text\\n${{single line sympy expression that solves the problem}}\\n```\\n...sympy.sympify(text, evaluate=True)...\\n```output\\n${{Output of running the code}}\\n```\\nAnswer: ${{Answer}}\\n\\nBegin.\\n\\nQuestion: What is the limit of sin(x) / x as x goes to 0\\n```text\\nlimit(sin(x)/x, x, 0)\\n```\\n...sympy.sympify(\"limit(sin(x)/x, x, 0)\")...\\n```output\\n1\\n```\\nAnswer: 1\\n\\nQuestion: What is the integral of e^-x from 0 to infinity\\n```text\\nintegrate(exp(-x), (x, 0, oo))\\n```\\n...sympy.sympify(\"integrate(exp(-x), (x, 0, oo))\")...\\n```output\\n1\\n```\\n\\nQuestion: What are the solutions to this equation x**2 - x?\\n```text\\nsolveset(x**2 - x, x)\\n```\\n...sympy.sympify(\"solveset(x**2 - x, x)\")...\\n```output\\n[0, 1]\\n```\\nQuestion: {question}\\n'), **kwargs: Any) \u2192 LLMSymbolicMathChain[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-9", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\ninvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Dict[str, Any]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-10", "text": "purposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-11", "text": "prep_inputs(inputs: Union[Dict[str, Any], Any]) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain inputs, including adding inputs from memory.\nParameters\ninputs \u2013 Dictionary of raw inputs, or single input if chain expects\nonly one param. Should contain all inputs specified in\nChain.input_keys except for inputs that will be set by the chain\u2019s\nmemory.\nReturns\nA dictionary of all inputs, including those added by the chain\u2019s memory.\nprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) \u2192 Dict[str, str]\u00b6\nValidate and prepare chain outputs, and save info about this run to memory.\nParameters\ninputs \u2013 Dictionary of chain inputs, including any inputs added by chain\nmemory.\noutputs \u2013 Dictionary of initial chain outputs.\nreturn_only_outputs \u2013 Whether to only return the chain outputs. If False,\ninputs are also added to the final outputs.\nReturns\nA dict of the final chain outputs.\nrun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 Any\u00b6\nConvenience method for executing chain.\nThe main difference between this method and Chain.__call__ is that this\nmethod expects inputs to be passed directly in as positional arguments or\nkeyword arguments, whereas Chain.__call__ expects a single input dictionary\nwith all the inputs\nParameters\n*args \u2013 If the chain expects a single input, it can be passed in as the\nsole positional argument.\ncallbacks \u2013 Callbacks to use for this chain run. These will be called in\naddition to callbacks passed to the chain during construction, but only\nthese runtime callbacks will propagate to calls to other objects.", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-12", "text": "these runtime callbacks will propagate to calls to other objects.\ntags \u2013 List of string tags to pass to all callbacks. These will be passed in\naddition to tags passed to the chain during construction, but only\nthese runtime tags will propagate to calls to other objects.\n**kwargs \u2013 If the chain expects multiple inputs, they can be passed in\ndirectly as keyword arguments.\nReturns\nThe chain output.\nExample\n# Suppose we have a single-input chain that takes a 'question' string:\nchain.run(\"What's the temperature in Boise, Idaho?\")\n# -> \"The temperature in Boise is...\"\n# Suppose we have a multi-input chain that takes a 'question' string\n# and 'context' string:\nquestion = \"What's the temperature in Boise, Idaho?\"\ncontext = \"Weather report for Boise, Idaho on 07/03/23...\"\nchain.run(question=question, context=context)\n# -> \"The temperature in Boise is...\"\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the chain.\nExpects Chain._chain_type property to be implemented and for memory to benull.\nParameters\nfile_path \u2013 Path to file to save the chain to.\nExample\nchain.save(file_path=\"path/chain.yaml\")\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-13", "text": "to_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-14", "text": "on_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: Type[langchain.schema.runnable.utils.Input]\u00b6\nThe type of input this runnable accepts specified as a type annotation.\nproperty OutputType: Type[langchain.schema.runnable.utils.Output]\u00b6\nThe type of output this runnable produces specified as a type annotation.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "c70b98bdb4cd-15", "text": "These attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using LLMSymbolicMathChain\u00b6\nLLM Symbolic Math", "source": "lang/api.python.langchain.com/en/latest/llm_symbolic_math/langchain_experimental.llm_symbolic_math.base.LLMSymbolicMathChain.html"}
{"id": "ddd8366112fb-0", "text": "langchain.cache.FullLLMCache\u00b6\nclass langchain.cache.FullLLMCache(**kwargs)[source]\u00b6\nSQLite table for full LLM Cache (all generations).\nA simple constructor that allows initialization from kwargs.\nSets attributes on the constructed instance using the names and\nvalues in kwargs.\nOnly keys that are present as\nattributes of the instance\u2019s class are allowed. These could be,\nfor example, any mapped columns or relationships.\nAttributes\nidx\nllm\nmetadata\nprompt\nregistry\nresponse\nMethods\n__init__(**kwargs)\nA simple constructor that allows initialization from kwargs.\n__init__(**kwargs)\u00b6\nA simple constructor that allows initialization from kwargs.\nSets attributes on the constructed instance using the names and\nvalues in kwargs.\nOnly keys that are present as\nattributes of the instance\u2019s class are allowed. These could be,\nfor example, any mapped columns or relationships.", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.FullLLMCache.html"}
{"id": "41363e5a12be-0", "text": "langchain.cache.FullMd5LLMCache\u00b6\nclass langchain.cache.FullMd5LLMCache(**kwargs)[source]\u00b6\nSQLite table for full LLM Cache (all generations).\nA simple constructor that allows initialization from kwargs.\nSets attributes on the constructed instance using the names and\nvalues in kwargs.\nOnly keys that are present as\nattributes of the instance\u2019s class are allowed. These could be,\nfor example, any mapped columns or relationships.\nAttributes\nid\nidx\nllm\nmetadata\nprompt\nprompt_md5\nregistry\nresponse\nMethods\n__init__(**kwargs)\nA simple constructor that allows initialization from kwargs.\n__init__(**kwargs)\u00b6\nA simple constructor that allows initialization from kwargs.\nSets attributes on the constructed instance using the names and\nvalues in kwargs.\nOnly keys that are present as\nattributes of the instance\u2019s class are allowed. These could be,\nfor example, any mapped columns or relationships.", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.FullMd5LLMCache.html"}
{"id": "454bc31da1b8-0", "text": "langchain.cache.RedisSemanticCache\u00b6\nclass langchain.cache.RedisSemanticCache(redis_url: str, embedding: Embeddings, score_threshold: float = 0.2)[source]\u00b6\nCache that uses Redis as a vector-store backend.\nInitialize by passing in the init GPTCache func\nParameters\nredis_url (str) \u2013 URL to connect to Redis.\nembedding (Embedding) \u2013 Embedding provider for semantic encoding and search.\nscore_threshold (float, 0.2) \u2013 \nExample:\nfrom langchain.globals import set_llm_cache\nfrom langchain.cache import RedisSemanticCache\nfrom langchain.embeddings import OpenAIEmbeddings\nset_llm_cache(RedisSemanticCache(\n    redis_url=\"redis://localhost:6379\",\n    embedding=OpenAIEmbeddings()\n))\nAttributes\nDEFAULT_SCHEMA\nMethods\n__init__(redis_url,\u00a0embedding[,\u00a0score_threshold])\nInitialize by passing in the init GPTCache func\nclear(**kwargs)\nClear semantic cache for a given llm_string.\nlookup(prompt,\u00a0llm_string)\nLook up based on prompt and llm_string.\nupdate(prompt,\u00a0llm_string,\u00a0return_val)\nUpdate cache based on prompt and llm_string.\n__init__(redis_url: str, embedding: Embeddings, score_threshold: float = 0.2)[source]\u00b6\nInitialize by passing in the init GPTCache func\nParameters\nredis_url (str) \u2013 URL to connect to Redis.\nembedding (Embedding) \u2013 Embedding provider for semantic encoding and search.\nscore_threshold (float, 0.2) \u2013 \nExample:\nfrom langchain.globals import set_llm_cache\nfrom langchain.cache import RedisSemanticCache\nfrom langchain.embeddings import OpenAIEmbeddings\nset_llm_cache(RedisSemanticCache(", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.RedisSemanticCache.html"}
{"id": "454bc31da1b8-1", "text": "set_llm_cache(RedisSemanticCache(\n    redis_url=\"redis://localhost:6379\",\n    embedding=OpenAIEmbeddings()\n))\nclear(**kwargs: Any) \u2192 None[source]\u00b6\nClear semantic cache for a given llm_string.\nlookup(prompt: str, llm_string: str) \u2192 Optional[Sequence[Generation]][source]\u00b6\nLook up based on prompt and llm_string.\nupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) \u2192 None[source]\u00b6\nUpdate cache based on prompt and llm_string.\nExamples using RedisSemanticCache\u00b6\nRedis\nLLM Caching integrations", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.RedisSemanticCache.html"}
{"id": "6b64fd0beea2-0", "text": "langchain.cache.CassandraCache\u00b6\nclass langchain.cache.CassandraCache(session: Optional[CassandraSession] = None, keyspace: Optional[str] = None, table_name: str = 'langchain_llm_cache', ttl_seconds: Optional[int] = None, skip_provisioning: bool = False)[source]\u00b6\nCache that uses Cassandra / Astra DB as a backend.\nIt uses a single Cassandra table.\nThe lookup keys (which get to form the primary key) are:\nprompt, a string\nllm_string, a deterministic str representation of the model parameters.\n(needed to prevent collisions same-prompt-different-model collisions)\nInitialize with a ready session and a keyspace name.\n:param session: an open Cassandra session\n:type session: cassandra.cluster.Session\n:param keyspace: the keyspace to use for storing the cache\n:type keyspace: str\n:param table_name: name of the Cassandra table to use as cache\n:type table_name: str\n:param ttl_seconds: time-to-live for cache entries\n(default: None, i.e. forever)\nMethods\n__init__([session,\u00a0keyspace,\u00a0table_name,\u00a0...])\nInitialize with a ready session and a keyspace name. :param session: an open Cassandra session :type session: cassandra.cluster.Session :param keyspace: the keyspace to use for storing the cache :type keyspace: str :param table_name: name of the Cassandra table to use as cache :type table_name: str :param ttl_seconds: time-to-live for cache entries                     (default: None, i.e. forever) :type ttl_seconds: optional int.\nclear(**kwargs)\nClear cache.\ndelete(prompt,\u00a0llm_string)\nEvict from cache if there's an entry.\ndelete_through_llm(prompt,\u00a0llm[,\u00a0stop])\nA wrapper around delete with the LLM being passed.", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.CassandraCache.html"}
{"id": "6b64fd0beea2-1", "text": "A wrapper around delete with the LLM being passed.\nlookup(prompt,\u00a0llm_string)\nLook up based on prompt and llm_string.\nupdate(prompt,\u00a0llm_string,\u00a0return_val)\nUpdate cache based on prompt and llm_string.\n__init__(session: Optional[CassandraSession] = None, keyspace: Optional[str] = None, table_name: str = 'langchain_llm_cache', ttl_seconds: Optional[int] = None, skip_provisioning: bool = False)[source]\u00b6\nInitialize with a ready session and a keyspace name.\n:param session: an open Cassandra session\n:type session: cassandra.cluster.Session\n:param keyspace: the keyspace to use for storing the cache\n:type keyspace: str\n:param table_name: name of the Cassandra table to use as cache\n:type table_name: str\n:param ttl_seconds: time-to-live for cache entries\n(default: None, i.e. forever)\nclear(**kwargs: Any) \u2192 None[source]\u00b6\nClear cache. This is for all LLMs at once.\ndelete(prompt: str, llm_string: str) \u2192 None[source]\u00b6\nEvict from cache if there\u2019s an entry.\ndelete_through_llm(prompt: str, llm: LLM, stop: Optional[List[str]] = None) \u2192 None[source]\u00b6\nA wrapper around delete with the LLM being passed.\nIn case the llm(prompt) calls have a stop param, you should pass it here\nlookup(prompt: str, llm_string: str) \u2192 Optional[Sequence[Generation]][source]\u00b6\nLook up based on prompt and llm_string.\nupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) \u2192 None[source]\u00b6\nUpdate cache based on prompt and llm_string.", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.CassandraCache.html"}
{"id": "602ded01a747-0", "text": "langchain.cache.SQLAlchemyMd5Cache\u00b6\nclass langchain.cache.SQLAlchemyMd5Cache(engine: ~sqlalchemy.engine.base.Engine, cache_schema: ~typing.Type[~langchain.cache.FullMd5LLMCache] = <class 'langchain.cache.FullMd5LLMCache'>)[source]\u00b6\nCache that uses SQAlchemy as a backend.\nInitialize by creating all tables.\nMethods\n__init__(engine[,\u00a0cache_schema])\nInitialize by creating all tables.\nclear(**kwargs)\nClear cache.\nget_md5(input_string)\nlookup(prompt,\u00a0llm_string)\nLook up based on prompt and llm_string.\nupdate(prompt,\u00a0llm_string,\u00a0return_val)\nUpdate based on prompt and llm_string.\n__init__(engine: ~sqlalchemy.engine.base.Engine, cache_schema: ~typing.Type[~langchain.cache.FullMd5LLMCache] = <class 'langchain.cache.FullMd5LLMCache'>)[source]\u00b6\nInitialize by creating all tables.\nclear(**kwargs: Any) \u2192 None[source]\u00b6\nClear cache.\nstatic get_md5(input_string: str) \u2192 str[source]\u00b6\nlookup(prompt: str, llm_string: str) \u2192 Optional[Sequence[Generation]][source]\u00b6\nLook up based on prompt and llm_string.\nupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) \u2192 None[source]\u00b6\nUpdate based on prompt and llm_string.", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.SQLAlchemyMd5Cache.html"}
{"id": "25ae951a9068-0", "text": "langchain.cache.MomentoCache\u00b6\nclass langchain.cache.MomentoCache(cache_client: momento.CacheClient, cache_name: str, *, ttl: Optional[timedelta] = None, ensure_cache_exists: bool = True)[source]\u00b6\nCache that uses Momento as a backend. See https://gomomento.com/\nInstantiate a prompt cache using Momento as a backend.\nNote: to instantiate the cache client passed to MomentoCache,\nyou must have a Momento account. See https://gomomento.com/.\nParameters\ncache_client (CacheClient) \u2013 The Momento cache client.\ncache_name (str) \u2013 The name of the cache to use to store the data.\nttl (Optional[timedelta], optional) \u2013 The time to live for the cache items.\nDefaults to None, ie use the client default TTL.\nensure_cache_exists (bool, optional) \u2013 Create the cache if it doesn\u2019t\nexist. Defaults to True.\nRaises\nImportError \u2013 Momento python package is not installed.\nTypeError \u2013 cache_client is not of type momento.CacheClientObject\nValueError \u2013 ttl is non-null and non-negative\nMethods\n__init__(cache_client,\u00a0cache_name,\u00a0*[,\u00a0ttl,\u00a0...])\nInstantiate a prompt cache using Momento as a backend.\nclear(**kwargs)\nClear the cache.\nfrom_client_params(cache_name,\u00a0ttl,\u00a0*[,\u00a0...])\nConstruct cache from CacheClient parameters.\nlookup(prompt,\u00a0llm_string)\nLookup llm generations in cache by prompt and associated model and settings.\nupdate(prompt,\u00a0llm_string,\u00a0return_val)\nStore llm generations in cache.\n__init__(cache_client: momento.CacheClient, cache_name: str, *, ttl: Optional[timedelta] = None, ensure_cache_exists: bool = True)[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.MomentoCache.html"}
{"id": "25ae951a9068-1", "text": "Instantiate a prompt cache using Momento as a backend.\nNote: to instantiate the cache client passed to MomentoCache,\nyou must have a Momento account. See https://gomomento.com/.\nParameters\ncache_client (CacheClient) \u2013 The Momento cache client.\ncache_name (str) \u2013 The name of the cache to use to store the data.\nttl (Optional[timedelta], optional) \u2013 The time to live for the cache items.\nDefaults to None, ie use the client default TTL.\nensure_cache_exists (bool, optional) \u2013 Create the cache if it doesn\u2019t\nexist. Defaults to True.\nRaises\nImportError \u2013 Momento python package is not installed.\nTypeError \u2013 cache_client is not of type momento.CacheClientObject\nValueError \u2013 ttl is non-null and non-negative\nclear(**kwargs: Any) \u2192 None[source]\u00b6\nClear the cache.\nRaises\nSdkException \u2013 Momento service or network error\nclassmethod from_client_params(cache_name: str, ttl: timedelta, *, configuration: Optional[momento.config.Configuration] = None, api_key: Optional[str] = None, auth_token: Optional[str] = None, **kwargs: Any) \u2192 MomentoCache[source]\u00b6\nConstruct cache from CacheClient parameters.\nlookup(prompt: str, llm_string: str) \u2192 Optional[Sequence[Generation]][source]\u00b6\nLookup llm generations in cache by prompt and associated model and settings.\nParameters\nprompt (str) \u2013 The prompt run through the language model.\nllm_string (str) \u2013 The language model version and settings.\nRaises\nSdkException \u2013 Momento service or network error\nReturns\nA list of language model generations.\nReturn type\nOptional[RETURN_VAL_TYPE]\nupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) \u2192 None[source]\u00b6\nStore llm generations in cache.\nParameters", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.MomentoCache.html"}
{"id": "25ae951a9068-2", "text": "Store llm generations in cache.\nParameters\nprompt (str) \u2013 The prompt run through the language model.\nllm_string (str) \u2013 The language model string.\nreturn_val (RETURN_VAL_TYPE) \u2013 A list of language model generations.\nRaises\nSdkException \u2013 Momento service or network error\nException \u2013 Unexpected response\nExamples using MomentoCache\u00b6\nMomento\nLLM Caching integrations", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.MomentoCache.html"}
{"id": "887cf4117a62-0", "text": "langchain.cache.GPTCache\u00b6\nclass langchain.cache.GPTCache(init_func: Optional[Union[Callable[[Any, str], None], Callable[[Any], None]]] = None)[source]\u00b6\nCache that uses GPTCache as a backend.\nInitialize by passing in init function (default: None).\nParameters\ninit_func (Optional[Callable[[Any], None]]) \u2013 init GPTCache function\n(default \u2013 None)\nExample:\n.. code-block:: python\n# Initialize GPTCache with a custom init function\nimport gptcache\nfrom gptcache.processor.pre import get_prompt\nfrom gptcache.manager.factory import get_data_manager\nfrom langchain.globals import set_llm_cache\n# Avoid multiple caches using the same file,\ncausing different llm model caches to affect each other\ndef init_gptcache(cache_obj: gptcache.Cache, llm str):\ncache_obj.init(pre_embedding_func=get_prompt,\ndata_manager=manager_factory(\nmanager=\u201dmap\u201d,\ndata_dir=f\u201dmap_cache_{llm}\u201d\n),\n)\nset_llm_cache(GPTCache(init_gptcache))\nMethods\n__init__([init_func])\nInitialize by passing in init function (default: None).\nclear(**kwargs)\nClear cache.\nlookup(prompt,\u00a0llm_string)\nLook up the cache data.\nupdate(prompt,\u00a0llm_string,\u00a0return_val)\nUpdate cache.\n__init__(init_func: Optional[Union[Callable[[Any, str], None], Callable[[Any], None]]] = None)[source]\u00b6\nInitialize by passing in init function (default: None).\nParameters\ninit_func (Optional[Callable[[Any], None]]) \u2013 init GPTCache function\n(default \u2013 None)\nExample:\n.. code-block:: python\n# Initialize GPTCache with a custom init function\nimport gptcache", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.GPTCache.html"}
{"id": "887cf4117a62-1", "text": "# Initialize GPTCache with a custom init function\nimport gptcache\nfrom gptcache.processor.pre import get_prompt\nfrom gptcache.manager.factory import get_data_manager\nfrom langchain.globals import set_llm_cache\n# Avoid multiple caches using the same file,\ncausing different llm model caches to affect each other\ndef init_gptcache(cache_obj: gptcache.Cache, llm str):\ncache_obj.init(pre_embedding_func=get_prompt,\ndata_manager=manager_factory(\nmanager=\u201dmap\u201d,\ndata_dir=f\u201dmap_cache_{llm}\u201d\n),\n)\nset_llm_cache(GPTCache(init_gptcache))\nclear(**kwargs: Any) \u2192 None[source]\u00b6\nClear cache.\nlookup(prompt: str, llm_string: str) \u2192 Optional[Sequence[Generation]][source]\u00b6\nLook up the cache data.\nFirst, retrieve the corresponding cache object using the llm_string parameter,\nand then retrieve the data from the cache based on the prompt.\nupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) \u2192 None[source]\u00b6\nUpdate cache.\nFirst, retrieve the corresponding cache object using the llm_string parameter,\nand then store the prompt and return_val in the cache object.\nExamples using GPTCache\u00b6\nLLM Caching integrations", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.GPTCache.html"}
{"id": "f9be7f5666ca-0", "text": "langchain.cache.InMemoryCache\u00b6\nclass langchain.cache.InMemoryCache[source]\u00b6\nCache that stores things in memory.\nInitialize with empty cache.\nMethods\n__init__()\nInitialize with empty cache.\nclear(**kwargs)\nClear cache.\nlookup(prompt,\u00a0llm_string)\nLook up based on prompt and llm_string.\nupdate(prompt,\u00a0llm_string,\u00a0return_val)\nUpdate cache based on prompt and llm_string.\n__init__() \u2192 None[source]\u00b6\nInitialize with empty cache.\nclear(**kwargs: Any) \u2192 None[source]\u00b6\nClear cache.\nlookup(prompt: str, llm_string: str) \u2192 Optional[Sequence[Generation]][source]\u00b6\nLook up based on prompt and llm_string.\nupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) \u2192 None[source]\u00b6\nUpdate cache based on prompt and llm_string.\nExamples using InMemoryCache\u00b6\nLLM Caching integrations", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.InMemoryCache.html"}
{"id": "d303a8a6e5c3-0", "text": "langchain.cache.SQLiteCache\u00b6\nclass langchain.cache.SQLiteCache(database_path: str = '.langchain.db')[source]\u00b6\nCache that uses SQLite as a backend.\nInitialize by creating the engine and all tables.\nMethods\n__init__([database_path])\nInitialize by creating the engine and all tables.\nclear(**kwargs)\nClear cache.\nlookup(prompt,\u00a0llm_string)\nLook up based on prompt and llm_string.\nupdate(prompt,\u00a0llm_string,\u00a0return_val)\nUpdate based on prompt and llm_string.\n__init__(database_path: str = '.langchain.db')[source]\u00b6\nInitialize by creating the engine and all tables.\nclear(**kwargs: Any) \u2192 None\u00b6\nClear cache.\nlookup(prompt: str, llm_string: str) \u2192 Optional[Sequence[Generation]]\u00b6\nLook up based on prompt and llm_string.\nupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) \u2192 None\u00b6\nUpdate based on prompt and llm_string.\nExamples using SQLiteCache\u00b6\nLLM Caching integrations", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.SQLiteCache.html"}
{"id": "0042dc44a83b-0", "text": "langchain.cache.RedisCache\u00b6\nclass langchain.cache.RedisCache(redis_: Any, *, ttl: Optional[int] = None)[source]\u00b6\nCache that uses Redis as a backend.\nInitialize an instance of RedisCache.\nThis method initializes an object with Redis caching capabilities.\nIt takes a redis_ parameter, which should be an instance of a Redis\nclient class, allowing the object to interact with a Redis\nserver for caching purposes.\nParameters\nredis (Any) \u2013 An instance of a Redis client class\n(e.g., redis.Redis) used for caching.\nThis allows the object to communicate with a\nRedis server for caching operations.\nttl (int, optional) \u2013 Time-to-live (TTL) for cached items in seconds.\nIf provided, it sets the time duration for how long cached\nitems will remain valid. If not provided, cached items will not\nhave an automatic expiration.\nMethods\n__init__(redis_,\u00a0*[,\u00a0ttl])\nInitialize an instance of RedisCache.\nclear(**kwargs)\nClear cache.\nlookup(prompt,\u00a0llm_string)\nLook up based on prompt and llm_string.\nupdate(prompt,\u00a0llm_string,\u00a0return_val)\nUpdate cache based on prompt and llm_string.\n__init__(redis_: Any, *, ttl: Optional[int] = None)[source]\u00b6\nInitialize an instance of RedisCache.\nThis method initializes an object with Redis caching capabilities.\nIt takes a redis_ parameter, which should be an instance of a Redis\nclient class, allowing the object to interact with a Redis\nserver for caching purposes.\nParameters\nredis (Any) \u2013 An instance of a Redis client class\n(e.g., redis.Redis) used for caching.\nThis allows the object to communicate with a\nRedis server for caching operations.\nttl (int, optional) \u2013 Time-to-live (TTL) for cached items in seconds.", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.RedisCache.html"}
{"id": "0042dc44a83b-1", "text": "If provided, it sets the time duration for how long cached\nitems will remain valid. If not provided, cached items will not\nhave an automatic expiration.\nclear(**kwargs: Any) \u2192 None[source]\u00b6\nClear cache. If asynchronous is True, flush asynchronously.\nlookup(prompt: str, llm_string: str) \u2192 Optional[Sequence[Generation]][source]\u00b6\nLook up based on prompt and llm_string.\nupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) \u2192 None[source]\u00b6\nUpdate cache based on prompt and llm_string.\nExamples using RedisCache\u00b6\nRedis\nLLM Caching integrations", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.RedisCache.html"}
{"id": "a84e5779f7af-0", "text": "langchain.cache.UpstashRedisCache\u00b6\nclass langchain.cache.UpstashRedisCache(redis_: Any, *, ttl: Optional[int] = None)[source]\u00b6\nCache that uses Upstash Redis as a backend.\nInitialize an instance of UpstashRedisCache.\nThis method initializes an object with Upstash Redis caching capabilities.\nIt takes a redis_ parameter, which should be an instance of an Upstash Redis\nclient class, allowing the object to interact with Upstash Redis\nserver for caching purposes.\nParameters\nredis \u2013 An instance of Upstash Redis client class\n(e.g., Redis) used for caching.\nThis allows the object to communicate with\nRedis server for caching operations on.\nttl (int, optional) \u2013 Time-to-live (TTL) for cached items in seconds.\nIf provided, it sets the time duration for how long cached\nitems will remain valid. If not provided, cached items will not\nhave an automatic expiration.\nMethods\n__init__(redis_,\u00a0*[,\u00a0ttl])\nInitialize an instance of UpstashRedisCache.\nclear(**kwargs)\nClear cache.\nlookup(prompt,\u00a0llm_string)\nLook up based on prompt and llm_string.\nupdate(prompt,\u00a0llm_string,\u00a0return_val)\nUpdate cache based on prompt and llm_string.\n__init__(redis_: Any, *, ttl: Optional[int] = None)[source]\u00b6\nInitialize an instance of UpstashRedisCache.\nThis method initializes an object with Upstash Redis caching capabilities.\nIt takes a redis_ parameter, which should be an instance of an Upstash Redis\nclient class, allowing the object to interact with Upstash Redis\nserver for caching purposes.\nParameters\nredis \u2013 An instance of Upstash Redis client class\n(e.g., Redis) used for caching.\nThis allows the object to communicate with\nRedis server for caching operations on.", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.UpstashRedisCache.html"}
{"id": "a84e5779f7af-1", "text": "This allows the object to communicate with\nRedis server for caching operations on.\nttl (int, optional) \u2013 Time-to-live (TTL) for cached items in seconds.\nIf provided, it sets the time duration for how long cached\nitems will remain valid. If not provided, cached items will not\nhave an automatic expiration.\nclear(**kwargs: Any) \u2192 None[source]\u00b6\nClear cache. If asynchronous is True, flush asynchronously.\nThis flushes the whole db.\nlookup(prompt: str, llm_string: str) \u2192 Optional[Sequence[Generation]][source]\u00b6\nLook up based on prompt and llm_string.\nupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) \u2192 None[source]\u00b6\nUpdate cache based on prompt and llm_string.", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.UpstashRedisCache.html"}
{"id": "95b051bd9b2e-0", "text": "langchain.cache.SQLAlchemyCache\u00b6\nclass langchain.cache.SQLAlchemyCache(engine: ~sqlalchemy.engine.base.Engine, cache_schema: ~typing.Type[~langchain.cache.FullLLMCache] = <class 'langchain.cache.FullLLMCache'>)[source]\u00b6\nCache that uses SQAlchemy as a backend.\nInitialize by creating all tables.\nMethods\n__init__(engine[,\u00a0cache_schema])\nInitialize by creating all tables.\nclear(**kwargs)\nClear cache.\nlookup(prompt,\u00a0llm_string)\nLook up based on prompt and llm_string.\nupdate(prompt,\u00a0llm_string,\u00a0return_val)\nUpdate based on prompt and llm_string.\n__init__(engine: ~sqlalchemy.engine.base.Engine, cache_schema: ~typing.Type[~langchain.cache.FullLLMCache] = <class 'langchain.cache.FullLLMCache'>)[source]\u00b6\nInitialize by creating all tables.\nclear(**kwargs: Any) \u2192 None[source]\u00b6\nClear cache.\nlookup(prompt: str, llm_string: str) \u2192 Optional[Sequence[Generation]][source]\u00b6\nLook up based on prompt and llm_string.\nupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) \u2192 None[source]\u00b6\nUpdate based on prompt and llm_string.\nExamples using SQLAlchemyCache\u00b6\nLLM Caching integrations", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.SQLAlchemyCache.html"}
{"id": "86502af505b3-0", "text": "langchain.cache.CassandraSemanticCache\u00b6\nclass langchain.cache.CassandraSemanticCache(session: Optional[CassandraSession], keyspace: Optional[str], embedding: Embeddings, table_name: str = 'langchain_llm_semantic_cache', distance_metric: str = 'dot', score_threshold: float = 0.85, ttl_seconds: Optional[int] = None, skip_provisioning: bool = False)[source]\u00b6\nCache that uses Cassandra as a vector-store backend for semantic\n(i.e. similarity-based) lookup.\nIt uses a single (vector) Cassandra table and stores, in principle,\ncached values from several LLMs, so the LLM\u2019s llm_string is part\nof the rows\u2019 primary keys.\nThe similarity is based on one of several distance metrics (default: \u201cdot\u201d).\nIf choosing another metric, the default threshold is to be re-tuned accordingly.\nInitialize the cache with all relevant parameters.\n:param session: an open Cassandra session\n:type session: cassandra.cluster.Session\n:param keyspace: the keyspace to use for storing the cache\n:type keyspace: str\n:param embedding: Embedding provider for semantic\nencoding and search.\nParameters\ntable_name (str) \u2013 name of the Cassandra (vector) table\nto use as cache\ndistance_metric (str, 'dot') \u2013 which measure to adopt for\nsimilarity searches\nscore_threshold (optional float) \u2013 numeric value to use as\ncutoff for the similarity searches\nttl_seconds (optional int) \u2013 time-to-live for cache entries\n(default: None, i.e. forever)\nThe default score threshold is tuned to the default metric.\nTune it carefully yourself if switching to another distance metric.\nMethods\n__init__(session,\u00a0keyspace,\u00a0embedding[,\u00a0...])", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.CassandraSemanticCache.html"}
{"id": "86502af505b3-1", "text": "Methods\n__init__(session,\u00a0keyspace,\u00a0embedding[,\u00a0...])\nInitialize the cache with all relevant parameters. :param session: an open Cassandra session :type session: cassandra.cluster.Session :param keyspace: the keyspace to use for storing the cache :type keyspace: str :param embedding: Embedding provider for semantic                   encoding and search. :type embedding: Embedding :param table_name: name of the Cassandra (vector) table                    to use as cache :type table_name: str :param distance_metric: which measure to adopt for                         similarity searches :type distance_metric: str, 'dot' :param score_threshold: numeric value to use as                         cutoff for the similarity searches :type score_threshold: optional float :param ttl_seconds: time-to-live for cache entries                     (default: None, i.e. forever) :type ttl_seconds: optional int.\nclear(**kwargs)\nClear the whole semantic cache.\ndelete_by_document_id(document_id)\nGiven this is a \"similarity search\" cache, an invalidation pattern that makes sense is first a lookup to get an ID, and then deleting with that ID.\nlookup(prompt,\u00a0llm_string)\nLook up based on prompt and llm_string.\nlookup_with_id(prompt,\u00a0llm_string)\nLook up based on prompt and llm_string.\nlookup_with_id_through_llm(prompt,\u00a0llm[,\u00a0stop])\nupdate(prompt,\u00a0llm_string,\u00a0return_val)\nUpdate cache based on prompt and llm_string.\n__init__(session: Optional[CassandraSession], keyspace: Optional[str], embedding: Embeddings, table_name: str = 'langchain_llm_semantic_cache', distance_metric: str = 'dot', score_threshold: float = 0.85, ttl_seconds: Optional[int] = None, skip_provisioning: bool = False)[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.CassandraSemanticCache.html"}
{"id": "86502af505b3-2", "text": "Initialize the cache with all relevant parameters.\n:param session: an open Cassandra session\n:type session: cassandra.cluster.Session\n:param keyspace: the keyspace to use for storing the cache\n:type keyspace: str\n:param embedding: Embedding provider for semantic\nencoding and search.\nParameters\ntable_name (str) \u2013 name of the Cassandra (vector) table\nto use as cache\ndistance_metric (str, 'dot') \u2013 which measure to adopt for\nsimilarity searches\nscore_threshold (optional float) \u2013 numeric value to use as\ncutoff for the similarity searches\nttl_seconds (optional int) \u2013 time-to-live for cache entries\n(default: None, i.e. forever)\nThe default score threshold is tuned to the default metric.\nTune it carefully yourself if switching to another distance metric.\nclear(**kwargs: Any) \u2192 None[source]\u00b6\nClear the whole semantic cache.\ndelete_by_document_id(document_id: str) \u2192 None[source]\u00b6\nGiven this is a \u201csimilarity search\u201d cache, an invalidation pattern\nthat makes sense is first a lookup to get an ID, and then deleting\nwith that ID. This is for the second step.\nlookup(prompt: str, llm_string: str) \u2192 Optional[Sequence[Generation]][source]\u00b6\nLook up based on prompt and llm_string.\nlookup_with_id(prompt: str, llm_string: str) \u2192 Optional[Tuple[str, Sequence[Generation]]][source]\u00b6\nLook up based on prompt and llm_string.\nIf there are hits, return (document_id, cached_entry)\nlookup_with_id_through_llm(prompt: str, llm: LLM, stop: Optional[List[str]] = None) \u2192 Optional[Tuple[str, Sequence[Generation]]][source]\u00b6\nupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.CassandraSemanticCache.html"}
{"id": "86502af505b3-3", "text": "Update cache based on prompt and llm_string.", "source": "lang/api.python.langchain.com/en/latest/cache/langchain.cache.CassandraSemanticCache.html"}
{"id": "ee177465870a-0", "text": "langchain.llms.base.get_prompts\u00b6\nlangchain.llms.base.get_prompts(params: Dict[str, Any], prompts: List[str]) \u2192 Tuple[Dict[int, List], str, List[int], List[str]][source]\u00b6\nGet prompts that are already cached.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.get_prompts.html"}
{"id": "1f2fea10ccf9-0", "text": "langchain.llms.beam.Beam\u00b6\nclass langchain.llms.beam.Beam[source]\u00b6\nBases: LLM\nBeam API for gpt2 large language model.\nTo use, you should have the beam-sdk python package installed,\nand the environment variable BEAM_CLIENT_ID set with your client id\nand BEAM_CLIENT_SECRET set with your client secret. Information on how\nto get this is available here: https://docs.beam.cloud/account/api-keys.\nThe wrapper can then be called as follows, where the name, cpu, memory, gpu,\npython version, and python packages can be updated accordingly. Once deployed,\nthe instance can be called.\nExample\nllm = Beam(model_name=\"gpt2\",\n    name=\"langchain-gpt2\",\n    cpu=8,\n    memory=\"32Gi\",\n    gpu=\"A10G\",\n    python_version=\"python3.8\",\n    python_packages=[\n        \"diffusers[torch]>=0.10\",\n        \"transformers\",\n        \"torch\",\n        \"pillow\",\n        \"accelerate\",\n        \"safetensors\",\n        \"xformers\",],\n    max_length=50)\nllm._deploy()\ncall_result = llm._call(input)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam app_id: Optional[str] = None\u00b6\nparam beam_client_id: str = ''\u00b6\nparam beam_client_secret: str = ''\u00b6\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam cpu: str = ''\u00b6\nparam gpu: str = ''\u00b6\nparam max_length: str = ''\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "1f2fea10ccf9-1", "text": "param gpu: str = ''\u00b6\nparam max_length: str = ''\u00b6\nparam memory: str = ''\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not\nexplicitly specified.\nparam model_name: str = ''\u00b6\nparam name: str = ''\u00b6\nparam python_packages: List[str] = []\u00b6\nparam python_version: str = ''\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam url: str = ''\u00b6\nmodel endpoint to use\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "1f2fea10ccf9-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "1f2fea10ccf9-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\napp_creation() \u2192 None[source]\u00b6\nCreates a Python file which will contain your Beam app definition.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "1f2fea10ccf9-4", "text": "Parameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "1f2fea10ccf9-5", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "1f2fea10ccf9-6", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "1f2fea10ccf9-7", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "1f2fea10ccf9-8", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "1f2fea10ccf9-9", "text": "Parameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "1f2fea10ccf9-10", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "1f2fea10ccf9-11", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nrun_creation() \u2192 None[source]\u00b6\nCreates a Python file which will be deployed on beam.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "1f2fea10ccf9-12", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "1f2fea10ccf9-13", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty authorization: str\u00b6\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Beam\u00b6\nBeam", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.beam.Beam.html"}
{"id": "b0652f76899c-0", "text": "langchain.llms.cohere.completion_with_retry\u00b6\nlangchain.llms.cohere.completion_with_retry(llm: Cohere, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.completion_with_retry.html"}
{"id": "2087e80acaa0-0", "text": "langchain.llms.amazon_api_gateway.AmazonAPIGateway\u00b6\nclass langchain.llms.amazon_api_gateway.AmazonAPIGateway[source]\u00b6\nBases: LLM\nAmazon API Gateway to access LLM models hosted on AWS.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_url: str [Required]\u00b6\nAPI Gateway URL\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam content_handler: langchain.llms.amazon_api_gateway.ContentHandlerAmazonAPIGateway = <langchain.llms.amazon_api_gateway.ContentHandlerAmazonAPIGateway object>\u00b6\nThe content handler class that provides an input and\noutput transform functions to handle formats between LLM\nand the endpoint.\nparam headers: Optional[Dict] = None\u00b6\nAPI Gateway HTTP Headers to send, e.g. for authentication\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Optional[Dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "2087e80acaa0-1", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "2087e80acaa0-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "2087e80acaa0-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "2087e80acaa0-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "2087e80acaa0-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "2087e80acaa0-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "2087e80acaa0-7", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "2087e80acaa0-8", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "2087e80acaa0-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "2087e80acaa0-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "2087e80acaa0-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "2087e80acaa0-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "2087e80acaa0-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using AmazonAPIGateway\u00b6\nAmazon API Gateway", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.AmazonAPIGateway.html"}
{"id": "24a0fd319905-0", "text": "langchain.llms.minimax.Minimax\u00b6\nclass langchain.llms.minimax.Minimax[source]\u00b6\nBases: MinimaxCommon, LLM\nWrapper around Minimax large language models.\nTo use, you should have the environment variable\nMINIMAX_API_KEY and MINIMAX_GROUP_ID set with your API key,\nor pass them as a named parameter to the constructor.\n.. rubric:: Example\n. code-block:: pythonfrom langchain.llms.minimax import Minimax\nminimax = Minimax(model=\u201d<model_name>\u201d, minimax_api_key=\u201dmy-api-key\u201d,\nminimax_group_id=\u201dmy-group-id\u201d)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam max_tokens: int = 256\u00b6\nDenotes the number of tokens to predict per generation.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam minimax_api_host: Optional[str] = None\u00b6\nparam minimax_api_key: Optional[str] = None\u00b6\nparam minimax_group_id: Optional[str] = None\u00b6\nparam model: str = 'abab5.5-chat'\u00b6\nModel name to use.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nA non-negative float that tunes the degree of randomness in generation.\nparam top_p: float = 0.95\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "24a0fd319905-1", "text": "param top_p: float = 0.95\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "24a0fd319905-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "24a0fd319905-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "24a0fd319905-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "24a0fd319905-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "24a0fd319905-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "24a0fd319905-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "24a0fd319905-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "24a0fd319905-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "24a0fd319905-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "24a0fd319905-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "24a0fd319905-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "24a0fd319905-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Minimax\u00b6\nMinimax", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.Minimax.html"}
{"id": "21b382c71a25-0", "text": "langchain.llms.self_hosted.SelfHostedPipeline\u00b6\nclass langchain.llms.self_hosted.SelfHostedPipeline[source]\u00b6\nBases: LLM\nModel inference on self-hosted remote hardware.\nSupported hardware includes auto-launched instances on AWS, GCP, Azure,\nand Lambda, as well as servers specified\nby IP address and SSH credentials (such as on-prem, or another\ncloud like Paperspace, Coreweave, etc.).\nTo use, you should have the runhouse python package installed.\nExample for custom pipeline and inference functions:from langchain.llms import SelfHostedPipeline\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, pipeline\nimport runhouse as rh\ndef load_pipeline():\n    tokenizer = AutoTokenizer.from_pretrained(\"gpt2\")\n    model = AutoModelForCausalLM.from_pretrained(\"gpt2\")\n    return pipeline(\n        \"text-generation\", model=model, tokenizer=tokenizer,\n        max_new_tokens=10\n    )\ndef inference_fn(pipeline, prompt, stop = None):\n    return pipeline(prompt)[0][\"generated_text\"]\ngpu = rh.cluster(name=\"rh-a10x\", instance_type=\"A100:1\")\nllm = SelfHostedPipeline(\n    model_load_fn=load_pipeline,\n    hardware=gpu,\n    model_reqs=model_reqs, inference_fn=inference_fn\n)\nExample for <2GB model (can be serialized and sent directly to the server):from langchain.llms import SelfHostedPipeline\nimport runhouse as rh\ngpu = rh.cluster(name=\"rh-a10x\", instance_type=\"A100:1\")\nmy_model = ...\nllm = SelfHostedPipeline.from_pipeline(\n    pipeline=my_model,\n    hardware=gpu,\n    model_reqs=[\"./\", \"torch\", \"transformers\"],", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-1", "text": "model_reqs=[\"./\", \"torch\", \"transformers\"],\n)\nExample passing model path for larger models:from langchain.llms import SelfHostedPipeline\nimport runhouse as rh\nimport pickle\nfrom transformers import pipeline\ngenerator = pipeline(model=\"gpt2\")\nrh.blob(pickle.dumps(generator), path=\"models/pipeline.pkl\"\n    ).save().to(gpu, path=\"models\")\nllm = SelfHostedPipeline.from_pipeline(\n    pipeline=\"models/pipeline.pkl\",\n    hardware=gpu,\n    model_reqs=[\"./\", \"torch\", \"transformers\"],\n)\nInit the pipeline with an auxiliary function.\nThe load function must be in global scope to be imported\nand run on the server, i.e. in a module and not a REPL or closure.\nThen, initialize the remote inference function.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam hardware: Any = None\u00b6\nRemote hardware to send the inference function to.\nparam inference_fn: Callable = <function _generate_text>\u00b6\nInference function to send to the remote hardware.\nparam load_fn_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model load function.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_load_fn: Callable [Required]\u00b6\nFunction to load the model remotely on the server.\nparam model_reqs: List[str] = ['./', 'torch']\u00b6\nRequirements to install on hardware to inference the model.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-2", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-3", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-4", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_pipeline(pipeline: Any, hardware: Any, model_reqs: Optional[List[str]] = None, device: int = 0, **kwargs: Any) \u2192 LLM[source]\u00b6\nInit the SelfHostedPipeline from a pipeline object or string.\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-8", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-9", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-10", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-11", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-12", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-13", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "21b382c71a25-14", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using SelfHostedPipeline\u00b6\nRunhouse", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted.SelfHostedPipeline.html"}
{"id": "af68ea5598cc-0", "text": "langchain.llms.bedrock.BedrockBase\u00b6\nclass langchain.llms.bedrock.BedrockBase[source]\u00b6\nBases: BaseModel, ABC\nBase class for Bedrock models.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam credentials_profile_name: Optional[str] = None\u00b6\nThe name of the profile in the ~/.aws/credentials or ~/.aws/config files, which\nhas either access keys or role information specified.\nIf not specified, the default credential profile or, if on an EC2 instance,\ncredentials from IMDS will be used.\nSee: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\nparam endpoint_url: Optional[str] = None\u00b6\nNeeded if you don\u2019t want to default to us-east-1 endpoint\nparam model_id: str [Required]\u00b6\nId of the model to call, e.g., amazon.titan-text-express-v1, this is\nequivalent to the modelId property in the list-foundation-models api\nparam model_kwargs: Optional[Dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam provider_stop_sequence_key_name_map: Mapping[str, str] = {'ai21': 'stop_sequences', 'amazon': 'stopSequences', 'anthropic': 'stop_sequences', 'cohere': 'stop_sequences'}\u00b6\nparam region_name: Optional[str] = None\u00b6\nThe aws region e.g., us-west-2. Fallsback to AWS_DEFAULT_REGION env variable\nor region specified in ~/.aws/config in case it is not provided here.\nparam streaming: bool = False\u00b6\nWhether to stream the results.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.BedrockBase.html"}
{"id": "af68ea5598cc-1", "text": "Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.BedrockBase.html"}
{"id": "af68ea5598cc-2", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.BedrockBase.html"}
{"id": "a7fa929c3a9e-0", "text": "langchain.llms.titan_takeoff_pro.TitanTakeoffPro\u00b6\nclass langchain.llms.titan_takeoff_pro.TitanTakeoffPro[source]\u00b6\nBases: LLM\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam base_url: Optional[str] = 'http://localhost:3000'\u00b6\nSpecifies the baseURL to use for the Titan Takeoff Pro API.\nDefault = http://localhost:3000.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam max_new_tokens: Optional[int] = None\u00b6\nMaximum tokens generated.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam min_new_tokens: Optional[int] = None\u00b6\nMinimum tokens generated.\nparam no_repeat_ngram_size: Optional[int] = None\u00b6\nPrevent repetitions of ngrams of this size. Default = 0 (turned off).\nparam regex_string: Optional[str] = None\u00b6\nA regex string for constrained generation.\nparam repetition_penalty: Optional[float] = None\u00b6\nPenalise the generation of tokens that have been generated before.\nSet to > 1 to penalize.\nparam sampling_temperature: Optional[float] = None\u00b6\nSample with randomness. Bigger temperatures are associated with\nmore randomness and \u2018creativity\u2019.\nparam sampling_topk: Optional[int] = None\u00b6\nSample predictions from the top K most probable candidates.\nparam sampling_topp: Optional[float] = None\u00b6\nSample from predictions whose cumulative probability exceeds this value.\nparam streaming: bool = False\u00b6\nWhether to stream the output. Default = False.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "a7fa929c3a9e-1", "text": "param tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "a7fa929c3a9e-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "a7fa929c3a9e-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "a7fa929c3a9e-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "a7fa929c3a9e-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "a7fa929c3a9e-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "a7fa929c3a9e-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "a7fa929c3a9e-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "a7fa929c3a9e-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "a7fa929c3a9e-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "a7fa929c3a9e-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "a7fa929c3a9e-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "a7fa929c3a9e-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff_pro.TitanTakeoffPro.html"}
{"id": "01e51829ac17-0", "text": "langchain.llms.fake.FakeStreamingListLLM\u00b6\nclass langchain.llms.fake.FakeStreamingListLLM[source]\u00b6\nBases: FakeListLLM\nFake streaming list LLM for testing purposes.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam i: int = 0\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam responses: List[str] [Required]\u00b6\nparam sleep: Optional[float] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeStreamingListLLM.html"}
{"id": "01e51829ac17-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeStreamingListLLM.html"}
{"id": "01e51829ac17-2", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeStreamingListLLM.html"}
{"id": "01e51829ac17-3", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeStreamingListLLM.html"}
{"id": "01e51829ac17-4", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeStreamingListLLM.html"}
{"id": "01e51829ac17-5", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeStreamingListLLM.html"}
{"id": "01e51829ac17-6", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeStreamingListLLM.html"}
{"id": "01e51829ac17-7", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeStreamingListLLM.html"}
{"id": "01e51829ac17-8", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeStreamingListLLM.html"}
{"id": "01e51829ac17-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeStreamingListLLM.html"}
{"id": "01e51829ac17-10", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeStreamingListLLM.html"}
{"id": "01e51829ac17-11", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeStreamingListLLM.html"}
{"id": "01e51829ac17-12", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeStreamingListLLM.html"}
{"id": "538ae211d0b6-0", "text": "langchain.llms.google_palm.generate_with_retry\u00b6\nlangchain.llms.google_palm.generate_with_retry(llm: GooglePalm, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.generate_with_retry.html"}
{"id": "1274bd5b0547-0", "text": "langchain_experimental.llms.anthropic_functions.AnthropicFunctions\u00b6\nclass langchain_experimental.llms.anthropic_functions.AnthropicFunctions[source]\u00b6\nBases: BaseChatModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam llm: langchain.chat_models.base.BaseChatModel [Required]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.AnthropicFunctions.html"}
{"id": "1274bd5b0547-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.AnthropicFunctions.html"}
{"id": "1274bd5b0547-2", "text": "async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.AnthropicFunctions.html"}
{"id": "1274bd5b0547-3", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.AnthropicFunctions.html"}
{"id": "1274bd5b0547-4", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.AnthropicFunctions.html"}
{"id": "1274bd5b0547-5", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.AnthropicFunctions.html"}
{"id": "1274bd5b0547-6", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.AnthropicFunctions.html"}
{"id": "1274bd5b0547-7", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.AnthropicFunctions.html"}
{"id": "1274bd5b0547-8", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.AnthropicFunctions.html"}
{"id": "1274bd5b0547-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.AnthropicFunctions.html"}
{"id": "1274bd5b0547-10", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.AnthropicFunctions.html"}
{"id": "1274bd5b0547-11", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.AnthropicFunctions.html"}
{"id": "1274bd5b0547-12", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty model: langchain.chat_models.base.BaseChatModel\u00b6\nFor backwards compatibility.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.AnthropicFunctions.html"}
{"id": "a2e8438656f9-0", "text": "langchain.llms.human.HumanInputLLM\u00b6\nclass langchain.llms.human.HumanInputLLM[source]\u00b6\nBases: LLM\nIt returns user input as the response.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam input_func: Callable [Optional]\u00b6\nparam input_kwargs: Mapping[str, Any] = {}\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam prompt_func: Callable[[str], None] [Optional]\u00b6\nparam prompt_kwargs: Mapping[str, Any] = {}\u00b6\nparam separator: str = '\\n'\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.human.HumanInputLLM.html"}
{"id": "a2e8438656f9-1", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.human.HumanInputLLM.html"}
{"id": "a2e8438656f9-2", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.human.HumanInputLLM.html"}
{"id": "a2e8438656f9-3", "text": "Use this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.human.HumanInputLLM.html"}
{"id": "a2e8438656f9-4", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.human.HumanInputLLM.html"}
{"id": "a2e8438656f9-5", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.human.HumanInputLLM.html"}
{"id": "a2e8438656f9-6", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.human.HumanInputLLM.html"}
{"id": "a2e8438656f9-7", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.human.HumanInputLLM.html"}
{"id": "a2e8438656f9-8", "text": "Parameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.human.HumanInputLLM.html"}
{"id": "a2e8438656f9-9", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.human.HumanInputLLM.html"}
{"id": "a2e8438656f9-10", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.human.HumanInputLLM.html"}
{"id": "a2e8438656f9-11", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.human.HumanInputLLM.html"}
{"id": "a2e8438656f9-12", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using HumanInputLLM\u00b6\nHuman input LLM", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.human.HumanInputLLM.html"}
{"id": "9f0555870886-0", "text": "langchain_experimental.llms.llamaapi.ChatLlamaAPI\u00b6\nclass langchain_experimental.llms.llamaapi.ChatLlamaAPI[source]\u00b6\nBases: BaseChatModel\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nWhether to cache the response.\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nCallback manager to add to the run trace.\nparam callbacks: Callbacks = None\u00b6\nCallbacks to add to the run trace.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nCall self as a function.\nasync abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.llamaapi.ChatLlamaAPI.html"}
{"id": "9f0555870886-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.llamaapi.ChatLlamaAPI.html"}
{"id": "9f0555870886-2", "text": "async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.llamaapi.ChatLlamaAPI.html"}
{"id": "9f0555870886-3", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[BaseMessageChunk]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.llamaapi.ChatLlamaAPI.html"}
{"id": "9f0555870886-4", "text": "input is still being generated.\nbatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) \u2192 List[Output]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\ncall_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.llamaapi.ChatLlamaAPI.html"}
{"id": "9f0555870886-5", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nTop Level call\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.llamaapi.ChatLlamaAPI.html"}
{"id": "9f0555870886-6", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.llamaapi.ChatLlamaAPI.html"}
{"id": "9f0555870886-7", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.llamaapi.ChatLlamaAPI.html"}
{"id": "9f0555870886-8", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.llamaapi.ChatLlamaAPI.html"}
{"id": "9f0555870886-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.llamaapi.ChatLlamaAPI.html"}
{"id": "9f0555870886-10", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[BaseMessageChunk]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.llamaapi.ChatLlamaAPI.html"}
{"id": "9f0555870886-11", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Any\u00b6\nGet the output type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.llamaapi.ChatLlamaAPI.html"}
{"id": "9f0555870886-12", "text": "List configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.llamaapi.ChatLlamaAPI.html"}
{"id": "76c18831d9d4-0", "text": "langchain.llms.gradient_ai.GradientLLM\u00b6\nclass langchain.llms.gradient_ai.GradientLLM[source]\u00b6\nBases: BaseLLM\nGradient.ai LLM Endpoints.\nGradientLLM is a class to interact with LLMs on gradient.ai\nTo use, set the environment variable GRADIENT_ACCESS_TOKEN with your\nAPI token and GRADIENT_WORKSPACE_ID for your gradient workspace,\nor alternatively provide them as keywords to the constructor of this class.\nExample\nfrom langchain.llms import GradientLLM\nGradientLLM(\n    model=\"99148c6d-c2a0-4fbe-a4a7-e7c05bdb8a09_base_ml_model\",\n    model_kwargs={\n        \"max_generated_token_count\": 128,\n        \"temperature\": 0.75,\n        \"top_p\": 0.95,\n        \"top_k\": 20,\n        \"stop\": [],\n    },\n    gradient_workspace_id=\"12345614fc0_workspace\",\n    gradient_access_token=\"gradientai-access_token\",\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aiosession: Optional[aiohttp.client.ClientSession] = None\u00b6\nClientSession, private, subject to change in upcoming releases.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam gradient_access_token: Optional[str] = None\u00b6\ngradient.ai API Token, which can be generated by going to\nhttps://auth.gradient.ai/select-workspace\nand selecting \u201cAccess tokens\u201d under the profile drop-down.\nparam gradient_api_url: str = 'https://api.gradient.ai/api'\u00b6\nEndpoint URL to use.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "76c18831d9d4-1", "text": "Endpoint URL to use.\nparam gradient_workspace_id: Optional[str] = None\u00b6\nUnderlying gradient.ai workspace_id.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_id: str [Required] (alias 'model')\u00b6\nUnderlying gradient.ai model id (base or fine-tuned).\nConstraints\nminLength = 2\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "76c18831d9d4-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "76c18831d9d4-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "76c18831d9d4-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atrain_unsupervised(inputs: Sequence[str], **kwargs: Any) \u2192 TrainResult[source]\u00b6\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "76c18831d9d4-5", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "76c18831d9d4-6", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "76c18831d9d4-7", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "76c18831d9d4-8", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "76c18831d9d4-9", "text": "Parameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "76c18831d9d4-10", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "76c18831d9d4-11", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntrain_unsupervised(inputs: Sequence[str], **kwargs: Any) \u2192 TrainResult[source]\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "76c18831d9d4-12", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "76c18831d9d4-13", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.GradientLLM.html"}
{"id": "14f2d4aa4caa-0", "text": "langchain.llms.vllm.VLLM\u00b6\nclass langchain.llms.vllm.VLLM[source]\u00b6\nBases: BaseLLM\nVLLM language model.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam best_of: Optional[int] = None\u00b6\nNumber of output sequences that are generated from the prompt.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam download_dir: Optional[str] = None\u00b6\nDirectory to download and load the weights. (Default to the default\ncache dir of huggingface)\nparam dtype: str = 'auto'\u00b6\nThe data type for the model weights and activations.\nparam frequency_penalty: float = 0.0\u00b6\nFloat that penalizes new tokens based on their frequency in the\ngenerated text so far\nparam ignore_eos: bool = False\u00b6\nWhether to ignore the EOS token and continue generating tokens after\nthe EOS token is generated.\nparam logprobs: Optional[int] = None\u00b6\nNumber of log probabilities to return per output token.\nparam max_new_tokens: int = 512\u00b6\nMaximum number of tokens to generate per output sequence.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str = ''\u00b6\nThe name or path of a HuggingFace Transformers model.\nparam n: int = 1\u00b6\nNumber of output sequences to return for the given prompt.\nparam presence_penalty: float = 0.0\u00b6\nFloat that penalizes new tokens based on whether they appear in the\ngenerated text so far\nparam stop: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "14f2d4aa4caa-1", "text": "generated text so far\nparam stop: Optional[List[str]] = None\u00b6\nList of strings that stop the generation when they are generated.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 1.0\u00b6\nFloat that controls the randomness of the sampling.\nparam tensor_parallel_size: Optional[int] = 1\u00b6\nThe number of GPUs to use for distributed execution with tensor parallelism.\nparam top_k: int = -1\u00b6\nInteger that controls the number of top tokens to consider.\nparam top_p: float = 1.0\u00b6\nFloat that controls the cumulative probability of the top tokens to consider.\nparam trust_remote_code: Optional[bool] = False\u00b6\nTrust remote code (e.g., from HuggingFace) when downloading the model\nand tokenizer.\nparam use_beam_search: bool = False\u00b6\nWhether to use beam search instead of sampling.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\nparam vllm_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for vllm.LLM call not explicitly specified.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "14f2d4aa4caa-2", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "14f2d4aa4caa-3", "text": "text generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "14f2d4aa4caa-4", "text": "Asynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "14f2d4aa4caa-5", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "14f2d4aa4caa-6", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "14f2d4aa4caa-7", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "14f2d4aa4caa-8", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "14f2d4aa4caa-9", "text": "Parameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "14f2d4aa4caa-10", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "14f2d4aa4caa-11", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "14f2d4aa4caa-12", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "14f2d4aa4caa-13", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using VLLM\u00b6\nvLLM", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLM.html"}
{"id": "72cc19efb8e2-0", "text": "langchain.llms.manifest.ManifestWrapper\u00b6\nclass langchain.llms.manifest.ManifestWrapper[source]\u00b6\nBases: LLM\nHazyResearch\u2019s Manifest library.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam llm_kwargs: Optional[Dict] = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.manifest.ManifestWrapper.html"}
{"id": "72cc19efb8e2-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.manifest.ManifestWrapper.html"}
{"id": "72cc19efb8e2-2", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.manifest.ManifestWrapper.html"}
{"id": "72cc19efb8e2-3", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.manifest.ManifestWrapper.html"}
{"id": "72cc19efb8e2-4", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.manifest.ManifestWrapper.html"}
{"id": "72cc19efb8e2-5", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.manifest.ManifestWrapper.html"}
{"id": "72cc19efb8e2-6", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.manifest.ManifestWrapper.html"}
{"id": "72cc19efb8e2-7", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.manifest.ManifestWrapper.html"}
{"id": "72cc19efb8e2-8", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.manifest.ManifestWrapper.html"}
{"id": "72cc19efb8e2-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.manifest.ManifestWrapper.html"}
{"id": "72cc19efb8e2-10", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.manifest.ManifestWrapper.html"}
{"id": "72cc19efb8e2-11", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.manifest.ManifestWrapper.html"}
{"id": "72cc19efb8e2-12", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ManifestWrapper\u00b6\nHazy Research\nManifest", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.manifest.ManifestWrapper.html"}
{"id": "5fa2d37221af-0", "text": "langchain.llms.koboldai.KoboldApiLLM\u00b6\nclass langchain.llms.koboldai.KoboldApiLLM[source]\u00b6\nBases: LLM\nKobold API language model.\nIt includes several fields that can be used to control the text generation process.\nTo use this class, instantiate it with the required parameters and call it with a\nprompt to generate text. For example:\nkobold = KoboldApiLLM(endpoint=\u201dhttp://localhost:5000\u201d)\nresult = kobold(\u201cWrite a story about a dragon.\u201d)\nThis will send a POST request to the Kobold API with the provided prompt and\ngenerate text.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam endpoint: str [Required]\u00b6\nThe API endpoint to use for generating text.\nparam max_context_length: Optional[int] = 1600\u00b6\nMaximum number of tokens to send to the model.\nminimum: 1\nparam max_length: Optional[int] = 80\u00b6\nNumber of tokens to generate.\nmaximum: 512\nminimum: 1\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam rep_pen: Optional[float] = 1.12\u00b6\nBase repetition penalty value.\nminimum: 1\nparam rep_pen_range: Optional[int] = 1024\u00b6\nRepetition penalty range.\nminimum: 0\nparam rep_pen_slope: Optional[float] = 0.9\u00b6\nRepetition penalty slope.\nminimum: 0\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-1", "text": "minimum: 0\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = 0.6\u00b6\nTemperature value.\nexclusiveMinimum: 0\nparam tfs: Optional[float] = 0.9\u00b6\nTail free sampling value.\nmaximum: 1\nminimum: 0\nparam top_a: Optional[float] = 0.9\u00b6\nTop-a sampling value.\nminimum: 0\nparam top_k: Optional[int] = 0\u00b6\nTop-k sampling value.\nminimum: 0\nparam top_p: Optional[float] = 0.95\u00b6\nTop-p sampling value.\nmaximum: 1\nminimum: 0\nparam typical: Optional[float] = 0.5\u00b6\nTypical sampling value.\nmaximum: 1\nminimum: 0\nparam use_authors_note: Optional[bool] = False\u00b6\nWhether to use the author\u2019s note from the KoboldAI GUI when generating text.\nThis has no effect unless use_story is also enabled.\nparam use_memory: Optional[bool] = False\u00b6\nWhether to use the memory from the KoboldAI GUI when generating text.\nparam use_story: Optional[bool] = False\u00b6\nWhether or not to use the story from the KoboldAI GUI when generating text.\nparam use_world_info: Optional[bool] = False\u00b6\nWhether to use the world info from the KoboldAI GUI when generating text.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-2", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-3", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-4", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-5", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-6", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-7", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-8", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-9", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-11", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-12", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-13", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "5fa2d37221af-14", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using KoboldApiLLM\u00b6\nKoboldAI API", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.KoboldApiLLM.html"}
{"id": "c00608d860e6-0", "text": "langchain.llms.openai.AzureOpenAI\u00b6\nclass langchain.llms.openai.AzureOpenAI[source]\u00b6\nBases: BaseOpenAI\nAzure-specific OpenAI large language models.\nTo use, you should have the openai python package installed, and the\nenvironment variable OPENAI_API_KEY set with your API key.\nAny parameters that are valid to be passed to the openai.create call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.llms import AzureOpenAI\nopenai = AzureOpenAI(model_name=\"text-davinci-003\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_special: Union[Literal['all'], AbstractSet[str]] = {}\u00b6\nSet of special tokens that are allowed\u3002\nparam azure_ad_token: Union[str, None] = None\u00b6\nYour Azure Active Directory token.\nAutomatically inferred from env var AZURE_OPENAI_AD_TOKEN if not provided.\nFor more:\nhttps://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id.\nparam azure_ad_token_provider: Union[str, None] = None\u00b6\nA function that returns an Azure Active Directory token.\nWill be invoked on every request.\nparam azure_endpoint: Union[str, None] = None\u00b6\nYour Azure endpoint, including the resource.\nAutomatically inferred from env var AZURE_OPENAI_ENDPOINT if not provided.\nExample: https://example-resource.azure.openai.com/\nparam batch_size: int = 20\u00b6\nBatch size to use when passing multiple documents to generate.\nparam best_of: int = 1\u00b6\nGenerates best_of completions server-side and returns the \u201cbest\u201d.\nparam cache: Optional[bool] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-1", "text": "param cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam default_headers: Union[Mapping[str, str], None] = None\u00b6\nparam default_query: Union[Mapping[str, object], None] = None\u00b6\nparam deployment_name: Union[str, None] = None (alias 'azure_deployment')\u00b6\nA model deployment.\nIf given sets the base client URL to include /deployments/{azure_deployment}.\nNote: this means you won\u2019t be able to use non-deployment endpoints.\nparam disallowed_special: Union[Literal['all'], Collection[str]] = 'all'\u00b6\nSet of special tokens that are not allowed\u3002\nparam frequency_penalty: float = 0\u00b6\nPenalizes repeated tokens according to frequency.\nparam http_client: Union[Any, None] = None\u00b6\nOptional httpx.Client.\nparam logit_bias: Optional[Dict[str, float]] [Optional]\u00b6\nAdjust the probability of specific tokens being generated.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: int = 256\u00b6\nThe maximum number of tokens to generate in the completion.\n-1 returns as many tokens as possible given the prompt and\nthe models maximal context size.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'text-davinci-003' (alias 'model')\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-2", "text": "param n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Union[str, None] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var AZURE_OPENAI_API_KEY if not provided.\nparam openai_api_type: str = ''\u00b6\nLegacy, for openai<1.0.0 support.\nparam openai_api_version: str = '' (alias 'api_version')\u00b6\nAutomatically inferred from env var OPENAI_API_VERSION if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam presence_penalty: float = 0\u00b6\nPenalizes repeated tokens.\nparam request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-3", "text": "be the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nparam top_p: float = 1\u00b6\nTotal probability mass of tokens to consider at each step.\nparam validate_base_url: bool = True\u00b6\nFor backwards compatibility. If legacy val openai_api_base is passed in, try to\ninfer if it is a base_url or azure_endpoint and update accordingly.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-4", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-5", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-6", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-7", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-8", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_llm_result(choices: Any, prompts: List[str], token_usage: Dict[str, int], *, system_fingerprint: Optional[str] = None) \u2192 LLMResult\u00b6\nCreate the LLMResult from the choices and prompts.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-9", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-10", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_sub_prompts(params: Dict[str, Any], prompts: List[str], stop: Optional[List[str]] = None) \u2192 List[List[str]]\u00b6\nGet the sub prompts for llm call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-11", "text": "Get the sub prompts for llm call.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nGet the token IDs using the tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-12", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nmax_tokens_for_prompt(prompt: str) \u2192 int\u00b6\nCalculate the maximum number of tokens possible to generate for a prompt.\nParameters\nprompt \u2013 The prompt to pass into the model.\nReturns\nThe maximum number of tokens to generate for a prompt.\nExample\nmax_tokens = openai.max_token_for_prompt(\"Tell me a joke.\")\nstatic modelname_to_contextsize(modelname: str) \u2192 int\u00b6\nCalculate the maximum number of tokens possible to generate for a model.\nParameters\nmodelname \u2013 The modelname we want to know the context size for.\nReturns\nThe maximum context size\nExample\nmax_tokens = openai.modelname_to_contextsize(\"text-davinci-003\")\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-13", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-14", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-15", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "c00608d860e6-16", "text": "For example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty max_context_size: int\u00b6\nGet max context size for this model.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using AzureOpenAI\u00b6\nAzure OpenAI\nOpenAI", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.AzureOpenAI.html"}
{"id": "9eeff4678579-0", "text": "langchain.llms.loading.load_llm\u00b6\nlangchain.llms.loading.load_llm(file: Union[str, Path]) \u2192 BaseLLM[source]\u00b6\nLoad LLM from file.\nExamples using load_llm\u00b6\nAzure ML\nSerialization", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.loading.load_llm.html"}
{"id": "6c4f34195d31-0", "text": "langchain.llms.tongyi.stream_generate_with_retry\u00b6\nlangchain.llms.tongyi.stream_generate_with_retry(llm: Tongyi, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.stream_generate_with_retry.html"}
{"id": "9a890ba64757-0", "text": "langchain.llms.opaqueprompts.OpaquePrompts\u00b6\nclass langchain.llms.opaqueprompts.OpaquePrompts[source]\u00b6\nBases: LLM\nAn LLM wrapper that uses OpaquePrompts to sanitize prompts.\nWraps another LLM and sanitizes prompts before passing it to the LLM, thende-sanitizes the response.\nTo use, you should have the opaqueprompts python package installed,\nand the environment variable OPAQUEPROMPTS_API_KEY set with\nyour API key, or pass it as a named parameter to the constructor.\nExample\nfrom langchain.llms import OpaquePrompts\nfrom langchain.chat_models import ChatOpenAI\nop_llm = OpaquePrompts(base_llm=ChatOpenAI())\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam base_llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nThe base LLM to use.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "9a890ba64757-1", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "9a890ba64757-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "9a890ba64757-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "9a890ba64757-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "9a890ba64757-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "9a890ba64757-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "9a890ba64757-7", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "9a890ba64757-8", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "9a890ba64757-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "9a890ba64757-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "9a890ba64757-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "9a890ba64757-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "9a890ba64757-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using OpaquePrompts\u00b6\nOpaquePrompts", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.opaqueprompts.OpaquePrompts.html"}
{"id": "f5a4e85b7022-0", "text": "langchain.llms.cerebriumai.CerebriumAI\u00b6\nclass langchain.llms.cerebriumai.CerebriumAI[source]\u00b6\nBases: LLM\nCerebriumAI large language models.\nTo use, you should have the cerebrium python package installed, and the\nenvironment variable CEREBRIUMAI_API_KEY set with your API key.\nAny parameters that are valid to be passed to the call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.llms import CerebriumAI\ncerebrium = CerebriumAI(endpoint_url=\"\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam cerebriumai_api_key: Optional[str] = None\u00b6\nparam endpoint_url: str = ''\u00b6\nmodel endpoint to use\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not\nexplicitly specified.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "f5a4e85b7022-1", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "f5a4e85b7022-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "f5a4e85b7022-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "f5a4e85b7022-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "f5a4e85b7022-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "f5a4e85b7022-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "f5a4e85b7022-7", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "f5a4e85b7022-8", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "f5a4e85b7022-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "f5a4e85b7022-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "f5a4e85b7022-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "f5a4e85b7022-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "f5a4e85b7022-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using CerebriumAI\u00b6\nCerebriumAI", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cerebriumai.CerebriumAI.html"}
{"id": "b9729ea03a1c-0", "text": "langchain_experimental.llms.rellm_decoder.RELLM\u00b6\nclass langchain_experimental.llms.rellm_decoder.RELLM[source]\u00b6\nBases: HuggingFacePipeline\nRELLM wrapped LLM using HuggingFace Pipeline API.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam batch_size: int = 4\u00b6\nBatch size to use when passing multiple documents to generate.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam max_new_tokens: int = 200\u00b6\nMaximum number of new tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_id: str = 'gpt2'\u00b6\nModel name to use.\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments passed to the model.\nparam pipeline_kwargs: Optional[dict] = None\u00b6\nKeyword arguments passed to the pipeline.\nparam regex: RegexPattern [Required]\u00b6\nThe structured format to complete.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "b9729ea03a1c-1", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "b9729ea03a1c-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "b9729ea03a1c-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "b9729ea03a1c-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "b9729ea03a1c-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "b9729ea03a1c-6", "text": "dict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_model_id(model_id: str, task: str, device: Optional[int] = - 1, device_map: Optional[str] = None, model_kwargs: Optional[dict] = None, pipeline_kwargs: Optional[dict] = None, batch_size: int = 4, **kwargs: Any) \u2192 HuggingFacePipeline\u00b6\nConstruct the pipeline object from model_id and task.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "b9729ea03a1c-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "b9729ea03a1c-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "b9729ea03a1c-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "b9729ea03a1c-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "b9729ea03a1c-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "b9729ea03a1c-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "b9729ea03a1c-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.RELLM.html"}
{"id": "aa13693b6f7c-0", "text": "langchain.llms.anyscale.update_token_usage\u00b6\nlangchain.llms.anyscale.update_token_usage(keys: Set[str], response: Dict[str, Any], token_usage: Dict[str, Any]) \u2192 None[source]\u00b6\nUpdate token usage.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.update_token_usage.html"}
{"id": "b473f29c745f-0", "text": "langchain.llms.gigachat.GigaChat\u00b6\nclass langchain.llms.gigachat.GigaChat[source]\u00b6\nBases: _BaseGigaChat, BaseLLM\nGigaChat large language models API.\nTo use, you should pass login and password to access GigaChat API or use token.\nExample\nfrom langchain.llms import GigaChat\ngiga = GigaChat(credentials=..., verify_ssl_certs=False)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam access_token: Optional[str] = None\u00b6\nAccess token for GigaChat\nparam auth_url: Optional[str] = None\u00b6\nAuth URL\nparam base_url: Optional[str] = None\u00b6\nBase API URL\nparam ca_bundle_file: Optional[str] = None\u00b6\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam cert_file: Optional[str] = None\u00b6\nparam credentials: Optional[str] = None\u00b6\nAuth Token\nparam key_file: Optional[str] = None\u00b6\nparam key_file_password: Optional[str] = None\u00b6\nparam max_tokens: Optional[int] = None\u00b6\nMaximum number of tokens to generate\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: Optional[str] = None\u00b6\nModel name to use.\nparam password: Optional[str] = None\u00b6\nPassword for authenticate\nparam profanity: bool = True\u00b6\nCheck for profanity\nparam scope: Optional[str] = None\u00b6\nPermission scope for access token\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "b473f29c745f-1", "text": "Whether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = None\u00b6\nWhat sampling temperature to use.\nparam timeout: Optional[float] = None\u00b6\nTimeout for request\nparam user: Optional[str] = None\u00b6\nUsername for authenticate\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\nparam verify_ssl_certs: Optional[bool] = None\u00b6\nCheck certificates for all requests\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "b473f29c745f-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "b473f29c745f-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "b473f29c745f-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "b473f29c745f-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "b473f29c745f-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "b473f29c745f-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "b473f29c745f-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int[source]\u00b6\nCount approximate number of tokens\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "b473f29c745f-9", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "b473f29c745f-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "b473f29c745f-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "b473f29c745f-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "b473f29c745f-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty lc_serializable: bool\u00b6\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gigachat.GigaChat.html"}
{"id": "14957f6f5050-0", "text": "langchain.llms.anyscale.Anyscale\u00b6\nclass langchain.llms.anyscale.Anyscale[source]\u00b6\nBases: BaseOpenAI\nAnyscale large language models.\nTo use, you should have the environment variable ANYSCALE_API_BASE and\n``ANYSCALE_API_KEY``set with your Anyscale Endpoint, or pass it as a named\nparameter to the constructor.\nExample\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_special: Union[Literal['all'], AbstractSet[str]] = {}\u00b6\nSet of special tokens that are allowed\u3002\nparam anyscale_api_base: Optional[str] = None\u00b6\nparam anyscale_api_key: Optional[pydantic.types.SecretStr] = None\u00b6\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nparam batch_size: int = 20\u00b6\nBatch size to use when passing multiple documents to generate.\nparam best_of: int = 1\u00b6\nGenerates best_of completions server-side and returns the \u201cbest\u201d.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam default_headers: Union[Mapping[str, str], None] = None\u00b6\nparam default_query: Union[Mapping[str, object], None] = None\u00b6\nparam disallowed_special: Union[Literal['all'], Collection[str]] = 'all'\u00b6\nSet of special tokens that are not allowed\u3002\nparam frequency_penalty: float = 0\u00b6\nPenalizes repeated tokens according to frequency.\nparam http_client: Union[Any, None] = None\u00b6\nOptional httpx.Client.\nparam logit_bias: Optional[Dict[str, float]] [Optional]\u00b6\nAdjust the probability of specific tokens being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-1", "text": "Adjust the probability of specific tokens being generated.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: int = 256\u00b6\nThe maximum number of tokens to generate in the completion.\n-1 returns as many tokens as possible given the prompt and\nthe models maximal context size.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'text-davinci-003' (alias 'model')\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Optional[str] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var OPENAI_API_KEY if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam prefix_messages: List [Optional]\u00b6\nparam presence_penalty: float = 0\u00b6\nPenalizes repeated tokens.\nparam request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-2", "text": "param tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nparam top_p: float = 1\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-3", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-4", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-5", "text": "Use this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-6", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_llm_result(choices: Any, prompts: List[str], token_usage: Dict[str, int], *, system_fingerprint: Optional[str] = None) \u2192 LLMResult\u00b6\nCreate the LLMResult from the choices and prompts.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-8", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-9", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-10", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_sub_prompts(params: Dict[str, Any], prompts: List[str], stop: Optional[List[str]] = None) \u2192 List[List[str]]\u00b6\nGet the sub prompts for llm call.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nGet the token IDs using the tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-11", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nmax_tokens_for_prompt(prompt: str) \u2192 int\u00b6\nCalculate the maximum number of tokens possible to generate for a prompt.\nParameters\nprompt \u2013 The prompt to pass into the model.\nReturns\nThe maximum number of tokens to generate for a prompt.\nExample\nmax_tokens = openai.max_token_for_prompt(\"Tell me a joke.\")\nstatic modelname_to_contextsize(modelname: str) \u2192 int\u00b6\nCalculate the maximum number of tokens possible to generate for a model.\nParameters\nmodelname \u2013 The modelname we want to know the context size for.\nReturns\nThe maximum context size\nExample\nmax_tokens = openai.modelname_to_contextsize(\"text-davinci-003\")", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-12", "text": "max_tokens = openai.modelname_to_contextsize(\"text-davinci-003\")\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-13", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-14", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "14957f6f5050-15", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty max_context_size: int\u00b6\nGet max context size for this model.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Anyscale\u00b6\nAnyscale", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.Anyscale.html"}
{"id": "b2dc5e2fd8d6-0", "text": "langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint\u00b6\nclass langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint[source]\u00b6\nBases: LLM\nBaidu Qianfan hosted open source or customized models.\nTo use, you should have the qianfan python package installed, and\nthe environment variable qianfan_ak and qianfan_sk set with\nyour API key and Secret Key.\nak, sk are required parameters which you could get from\nhttps://cloud.baidu.com/product/wenxinworkshop\nExample\nfrom langchain.llms import QianfanLLMEndpoint\nqianfan_model = QianfanLLMEndpoint(model=\"ERNIE-Bot\",\n    endpoint=\"your_endpoint\", qianfan_ak=\"your_ak\", qianfan_sk=\"your_sk\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam client: Any = None\u00b6\nparam endpoint: Optional[str] = None\u00b6\nEndpoint of the Qianfan LLM, required if custom model used.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str = 'ERNIE-Bot-turbo'\u00b6\nModel name.\nyou could get from https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu\npreset models are mapping to an endpoint.\nmodel will be ignored if endpoint is set\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nparam penalty_score: Optional[float] = 1\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "b2dc5e2fd8d6-1", "text": "param penalty_score: Optional[float] = 1\u00b6\nModel params, only supported in ERNIE-Bot and ERNIE-Bot-turbo.\nIn the case of other model, passing these params will not affect the result.\nparam qianfan_ak: Optional[str] = None\u00b6\nparam qianfan_sk: Optional[str] = None\u00b6\nparam request_timeout: Optional[int] = 60\u00b6\nrequest timeout for chat http requests\nparam streaming: Optional[bool] = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = 0.95\u00b6\nparam top_p: Optional[float] = 0.8\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "b2dc5e2fd8d6-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "b2dc5e2fd8d6-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "b2dc5e2fd8d6-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "b2dc5e2fd8d6-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "b2dc5e2fd8d6-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "b2dc5e2fd8d6-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "b2dc5e2fd8d6-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "b2dc5e2fd8d6-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "b2dc5e2fd8d6-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "b2dc5e2fd8d6-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "b2dc5e2fd8d6-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "b2dc5e2fd8d6-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using QianfanLLMEndpoint\u00b6\nBaidu Qianfan", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baidu_qianfan_endpoint.QianfanLLMEndpoint.html"}
{"id": "472e1836a72d-0", "text": "langchain.llms.huggingface_hub.HuggingFaceHub\u00b6\nclass langchain.llms.huggingface_hub.HuggingFaceHub[source]\u00b6\nBases: LLM\nHuggingFaceHub  models.\nTo use, you should have the huggingface_hub python package installed, and the\nenvironment variable HUGGINGFACEHUB_API_TOKEN set with your API token, or pass\nit as a named parameter to the constructor.\nOnly supports text-generation, text2text-generation and summarization for now.\nExample\nfrom langchain.llms import HuggingFaceHub\nhf = HuggingFaceHub(repo_id=\"gpt2\", huggingfacehub_api_token=\"my-api-key\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam huggingfacehub_api_token: Optional[str] = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam repo_id: str = 'gpt2'\u00b6\nModel name to use.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam task: Optional[str] = None\u00b6\nTask to call the model with.\nShould be a task that returns generated_text or summary_text.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "472e1836a72d-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "472e1836a72d-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "472e1836a72d-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "472e1836a72d-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "472e1836a72d-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "472e1836a72d-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "472e1836a72d-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "472e1836a72d-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "472e1836a72d-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "472e1836a72d-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "472e1836a72d-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "472e1836a72d-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "472e1836a72d-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using HuggingFaceHub\u00b6\nHugging Face", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_hub.HuggingFaceHub.html"}
{"id": "bc4aeac948c5-0", "text": "langchain.llms.openlm.OpenLM\u00b6\nclass langchain.llms.openlm.OpenLM[source]\u00b6\nBases: BaseOpenAI\nOpenLM models.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_special: Union[Literal['all'], AbstractSet[str]] = {}\u00b6\nSet of special tokens that are allowed\u3002\nparam batch_size: int = 20\u00b6\nBatch size to use when passing multiple documents to generate.\nparam best_of: int = 1\u00b6\nGenerates best_of completions server-side and returns the \u201cbest\u201d.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam default_headers: Union[Mapping[str, str], None] = None\u00b6\nparam default_query: Union[Mapping[str, object], None] = None\u00b6\nparam disallowed_special: Union[Literal['all'], Collection[str]] = 'all'\u00b6\nSet of special tokens that are not allowed\u3002\nparam frequency_penalty: float = 0\u00b6\nPenalizes repeated tokens according to frequency.\nparam http_client: Union[Any, None] = None\u00b6\nOptional httpx.Client.\nparam logit_bias: Optional[Dict[str, float]] [Optional]\u00b6\nAdjust the probability of specific tokens being generated.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: int = 256\u00b6\nThe maximum number of tokens to generate in the completion.\n-1 returns as many tokens as possible given the prompt and\nthe models maximal context size.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-1", "text": "Metadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'text-davinci-003' (alias 'model')\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Optional[str] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var OPENAI_API_KEY if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam presence_penalty: float = 0\u00b6\nPenalizes repeated tokens.\nparam request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-2", "text": "be the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nparam top_p: float = 1\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-4", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-5", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-6", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-7", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_llm_result(choices: Any, prompts: List[str], token_usage: Dict[str, int], *, system_fingerprint: Optional[str] = None) \u2192 LLMResult\u00b6\nCreate the LLMResult from the choices and prompts.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-8", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-9", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_sub_prompts(params: Dict[str, Any], prompts: List[str], stop: Optional[List[str]] = None) \u2192 List[List[str]]\u00b6\nGet the sub prompts for llm call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-10", "text": "Get the sub prompts for llm call.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nGet the token IDs using the tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-11", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nmax_tokens_for_prompt(prompt: str) \u2192 int\u00b6\nCalculate the maximum number of tokens possible to generate for a prompt.\nParameters\nprompt \u2013 The prompt to pass into the model.\nReturns\nThe maximum number of tokens to generate for a prompt.\nExample\nmax_tokens = openai.max_token_for_prompt(\"Tell me a joke.\")\nstatic modelname_to_contextsize(modelname: str) \u2192 int\u00b6\nCalculate the maximum number of tokens possible to generate for a model.\nParameters\nmodelname \u2013 The modelname we want to know the context size for.\nReturns\nThe maximum context size\nExample\nmax_tokens = openai.modelname_to_contextsize(\"text-davinci-003\")\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-12", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-13", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-14", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "bc4aeac948c5-15", "text": "For example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty max_context_size: int\u00b6\nGet max context size for this model.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using OpenLM\u00b6\nOpenLM", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openlm.OpenLM.html"}
{"id": "343962c61522-0", "text": "langchain.llms.openai.BaseOpenAI\u00b6\nclass langchain.llms.openai.BaseOpenAI[source]\u00b6\nBases: BaseLLM\nBase OpenAI large language model class.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_special: Union[Literal['all'], AbstractSet[str]] = {}\u00b6\nSet of special tokens that are allowed\u3002\nparam batch_size: int = 20\u00b6\nBatch size to use when passing multiple documents to generate.\nparam best_of: int = 1\u00b6\nGenerates best_of completions server-side and returns the \u201cbest\u201d.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam default_headers: Union[Mapping[str, str], None] = None\u00b6\nparam default_query: Union[Mapping[str, object], None] = None\u00b6\nparam disallowed_special: Union[Literal['all'], Collection[str]] = 'all'\u00b6\nSet of special tokens that are not allowed\u3002\nparam frequency_penalty: float = 0\u00b6\nPenalizes repeated tokens according to frequency.\nparam http_client: Union[Any, None] = None\u00b6\nOptional httpx.Client.\nparam logit_bias: Optional[Dict[str, float]] [Optional]\u00b6\nAdjust the probability of specific tokens being generated.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: int = 256\u00b6\nThe maximum number of tokens to generate in the completion.\n-1 returns as many tokens as possible given the prompt and\nthe models maximal context size.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-1", "text": "Metadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'text-davinci-003' (alias 'model')\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Optional[str] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var OPENAI_API_KEY if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam presence_penalty: float = 0\u00b6\nPenalizes repeated tokens.\nparam request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-2", "text": "be the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nparam top_p: float = 1\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-4", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-5", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-6", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-7", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_llm_result(choices: Any, prompts: List[str], token_usage: Dict[str, int], *, system_fingerprint: Optional[str] = None) \u2192 LLMResult[source]\u00b6\nCreate the LLMResult from the choices and prompts.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-8", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-9", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_sub_prompts(params: Dict[str, Any], prompts: List[str], stop: Optional[List[str]] = None) \u2192 List[List[str]][source]\u00b6\nGet the sub prompts for llm call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-10", "text": "Get the sub prompts for llm call.\nget_token_ids(text: str) \u2192 List[int][source]\u00b6\nGet the token IDs using the tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-11", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nmax_tokens_for_prompt(prompt: str) \u2192 int[source]\u00b6\nCalculate the maximum number of tokens possible to generate for a prompt.\nParameters\nprompt \u2013 The prompt to pass into the model.\nReturns\nThe maximum number of tokens to generate for a prompt.\nExample\nmax_tokens = openai.max_token_for_prompt(\"Tell me a joke.\")\nstatic modelname_to_contextsize(modelname: str) \u2192 int[source]\u00b6\nCalculate the maximum number of tokens possible to generate for a model.\nParameters\nmodelname \u2013 The modelname we want to know the context size for.\nReturns\nThe maximum context size\nExample\nmax_tokens = openai.modelname_to_contextsize(\"text-davinci-003\")\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-12", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-13", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-14", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "343962c61522-15", "text": "For example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty max_context_size: int\u00b6\nGet max context size for this model.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.BaseOpenAI.html"}
{"id": "79933c6a99ac-0", "text": "langchain.llms.vertexai.completion_with_retry\u00b6\nlangchain.llms.vertexai.completion_with_retry(llm: VertexAI, *args: Any, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.completion_with_retry.html"}
{"id": "a8af0bb016aa-0", "text": "langchain.llms.gooseai.GooseAI\u00b6\nclass langchain.llms.gooseai.GooseAI[source]\u00b6\nBases: LLM\nGooseAI large language models.\nTo use, you should have the openai python package installed, and the\nenvironment variable GOOSEAI_API_KEY set with your API key.\nAny parameters that are valid to be passed to the openai.create call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.llms import GooseAI\ngooseai = GooseAI(model_name=\"gpt-neo-20b\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam client: Any = None\u00b6\nparam frequency_penalty: float = 0\u00b6\nPenalizes repeated tokens according to frequency.\nparam gooseai_api_key: Optional[pydantic.types.SecretStr] = None\u00b6\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nparam logit_bias: Optional[Dict[str, float]] [Optional]\u00b6\nAdjust the probability of specific tokens being generated.\nparam max_tokens: int = 256\u00b6\nThe maximum number of tokens to generate in the completion.\n-1 returns as many tokens as possible given the prompt and\nthe models maximal context size.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam min_tokens: int = 1\u00b6\nThe minimum number of tokens to generate in the completion.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "a8af0bb016aa-1", "text": "Holds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'gpt-neo-20b'\u00b6\nModel name to use\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam presence_penalty: float = 0\u00b6\nPenalizes repeated tokens.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use\nparam top_p: float = 1\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "a8af0bb016aa-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "a8af0bb016aa-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "a8af0bb016aa-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "a8af0bb016aa-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "a8af0bb016aa-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "a8af0bb016aa-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "a8af0bb016aa-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "a8af0bb016aa-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "a8af0bb016aa-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "a8af0bb016aa-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "a8af0bb016aa-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "a8af0bb016aa-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using GooseAI\u00b6\nGooseAI", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gooseai.GooseAI.html"}
{"id": "97cd3865470f-0", "text": "langchain.llms.edenai.EdenAI\u00b6\nclass langchain.llms.edenai.EdenAI[source]\u00b6\nBases: LLM\nWrapper around edenai models.\nTo use, you should have\nthe environment variable EDENAI_API_KEY set with your API token.\nYou can find your token here: https://app.edenai.run/admin/account/settings\nfeature and subfeature are required, but any other model parameters can also be\npassed in with the format params={model_param: value, \u2026}\nfor api reference check edenai documentation: http://docs.edenai.co.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam base_url: str = 'https://api.edenai.run/v2'\u00b6\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam edenai_api_key: Optional[str] = None\u00b6\nparam feature: Literal['text', 'image'] = 'text'\u00b6\nWhich generative feature to use, use text by default\nparam max_tokens: Optional[int] = None\u00b6\nConstraints\nminimum = 0\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: Optional[str] = None\u00b6\nmodel name for above provider (eg: \u2018text-davinci-003\u2019 for openai)\navailable models are shown on https://docs.edenai.co/ under \u2018available providers\u2019\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nextra parameters\nparam params: Dict[str, Any] [Optional]\u00b6\nDEPRECATED: use temperature, max_tokens, resolution directly\noptional parameters to pass to api", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "97cd3865470f-1", "text": "DEPRECATED: use temperature, max_tokens, resolution directly\noptional parameters to pass to api\nparam provider: str [Required]\u00b6\nGenerative provider to use (eg: openai,stabilityai,cohere,google etc.)\nparam resolution: Optional[Literal['256x256', '512x512', '1024x1024']] = None\u00b6\nparam stop_sequences: Optional[List[str]] = None\u00b6\nStop sequences to use.\nparam subfeature: Literal['generation'] = 'generation'\u00b6\nSubfeature of above feature, use generation by default\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = None\u00b6\nConstraints\nminimum = 0\nmaximum = 1\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "97cd3865470f-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "97cd3865470f-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "97cd3865470f-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "97cd3865470f-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "97cd3865470f-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "97cd3865470f-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "97cd3865470f-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\nstatic get_user_agent() \u2192 str[source]\u00b6\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "97cd3865470f-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "97cd3865470f-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "97cd3865470f-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "97cd3865470f-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "97cd3865470f-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using EdenAI\u00b6\nEden AI", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.edenai.EdenAI.html"}
{"id": "abc571a5ff66-0", "text": "langchain_experimental.llms.jsonformer_decoder.import_jsonformer\u00b6\nlangchain_experimental.llms.jsonformer_decoder.import_jsonformer() \u2192 jsonformer[source]\u00b6\nLazily import jsonformer.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.import_jsonformer.html"}
{"id": "c83584502c94-0", "text": "langchain.llms.minimax.MinimaxCommon\u00b6\nclass langchain.llms.minimax.MinimaxCommon[source]\u00b6\nBases: BaseModel\nCommon parameters for Minimax large language models.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam max_tokens: int = 256\u00b6\nDenotes the number of tokens to predict per generation.\nparam minimax_api_host: Optional[str] = None\u00b6\nparam minimax_api_key: Optional[str] = None\u00b6\nparam minimax_group_id: Optional[str] = None\u00b6\nparam model: str = 'abab5.5-chat'\u00b6\nModel name to use.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam temperature: float = 0.7\u00b6\nA non-negative float that tunes the degree of randomness in generation.\nparam top_p: float = 0.95\u00b6\nTotal probability mass of tokens to consider at each step.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.MinimaxCommon.html"}
{"id": "c83584502c94-1", "text": "Parameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.MinimaxCommon.html"}
{"id": "c83584502c94-2", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.minimax.MinimaxCommon.html"}
{"id": "b2021a78bf52-0", "text": "langchain.llms.openai.acompletion_with_retry\u00b6\nasync langchain.llms.openai.acompletion_with_retry(llm: Union[BaseOpenAI, OpenAIChat], run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the async completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.acompletion_with_retry.html"}
{"id": "e38848f1443f-0", "text": "langchain.llms.vertexai.acompletion_with_retry\u00b6\nasync langchain.llms.vertexai.acompletion_with_retry(llm: VertexAI, *args: Any, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.acompletion_with_retry.html"}
{"id": "c9896efd112e-0", "text": "langchain.llms.anyscale.create_llm_result\u00b6\nlangchain.llms.anyscale.create_llm_result(choices: Any, prompts: List[str], token_usage: Dict[str, int], model_name: str) \u2192 LLMResult[source]\u00b6\nCreate the LLMResult from the choices and prompts.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anyscale.create_llm_result.html"}
{"id": "eed0054d9789-0", "text": "langchain.llms.openai.update_token_usage\u00b6\nlangchain.llms.openai.update_token_usage(keys: Set[str], response: Dict[str, Any], token_usage: Dict[str, Any]) \u2192 None[source]\u00b6\nUpdate token usage.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.update_token_usage.html"}
{"id": "06a231346fbf-0", "text": "langchain.llms.aviary.get_completions\u00b6\nlangchain.llms.aviary.get_completions(model: str, prompt: str, use_prompt_format: bool = True, version: str = '') \u2192 Dict[str, Union[str, float, int]][source]\u00b6\nGet completions from Aviary models.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.get_completions.html"}
{"id": "7e67ca242254-0", "text": "langchain.llms.bittensor.NIBittensorLLM\u00b6\nclass langchain.llms.bittensor.NIBittensorLLM[source]\u00b6\nBases: LLM\nNIBittensor LLMs\nNIBittensorLLM is created by Neural Internet (https://neuralinternet.ai/),\npowered by Bittensor, a decentralized network full of different AI models.\nTo analyze API_KEYS and logs of your usage visithttps://api.neuralinternet.ai/api-keys\nhttps://api.neuralinternet.ai/logs\nExample\nfrom langchain.llms import NIBittensorLLM\nllm = NIBittensorLLM()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam system_prompt: Optional[str] = None\u00b6\nProvide system prompt that you want to supply it to model before every prompt\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam top_responses: Optional[int] = 0\u00b6\nProvide top_responses to get Top N miner responses on one request.May get delayed\nDon\u2019t use in Production\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "7e67ca242254-1", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "7e67ca242254-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "7e67ca242254-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "7e67ca242254-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "7e67ca242254-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "7e67ca242254-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "7e67ca242254-7", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "7e67ca242254-8", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "7e67ca242254-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "7e67ca242254-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "7e67ca242254-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "7e67ca242254-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "7e67ca242254-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using NIBittensorLLM\u00b6\nNIBittensor\nBittensor", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bittensor.NIBittensorLLM.html"}
{"id": "c1d6f9d875e0-0", "text": "langchain.llms.vertexai.is_codey_model\u00b6\nlangchain.llms.vertexai.is_codey_model(model_name: str) \u2192 bool[source]\u00b6\nReturns True if the model name is a Codey model.\nParameters\nmodel_name \u2013 The model name to check.\nReturns: True if the model name is a Codey model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.is_codey_model.html"}
{"id": "53dcc2adc77b-0", "text": "langchain.llms.aviary.get_models\u00b6\nlangchain.llms.aviary.get_models() \u2192 List[str][source]\u00b6\nList available models", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.get_models.html"}
{"id": "4cc413362a29-0", "text": "langchain.llms.fireworks.completion_with_retry_batching\u00b6\nlangchain.llms.fireworks.completion_with_retry_batching(llm: Fireworks, use_retry: bool, *, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.completion_with_retry_batching.html"}
{"id": "93542bfc799f-0", "text": "langchain.llms.aviary.AviaryBackend\u00b6\nclass langchain.llms.aviary.AviaryBackend(backend_url: str, bearer: str)[source]\u00b6\nAviary backend.\nbackend_url\u00b6\nThe URL for the Aviary backend.\nType\nstr\nbearer\u00b6\nThe bearer token for the Aviary backend.\nType\nstr\nAttributes\nbackend_url\nbearer\nMethods\n__init__(backend_url,\u00a0bearer)\nfrom_env()\n__init__(backend_url: str, bearer: str) \u2192 None\u00b6\nclassmethod from_env() \u2192 AviaryBackend[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.AviaryBackend.html"}
{"id": "4bee6d12759f-0", "text": "langchain.llms.huggingface_pipeline.HuggingFacePipeline\u00b6\nclass langchain.llms.huggingface_pipeline.HuggingFacePipeline[source]\u00b6\nBases: BaseLLM\nHuggingFace Pipeline API.\nTo use, you should have the transformers python package installed.\nOnly supports text-generation, text2text-generation and summarization for now.\nExample using from_model_id:from langchain.llms import HuggingFacePipeline\nhf = HuggingFacePipeline.from_model_id(\n    model_id=\"gpt2\",\n    task=\"text-generation\",\n    pipeline_kwargs={\"max_new_tokens\": 10},\n)\nExample passing pipeline in directly:from langchain.llms import HuggingFacePipeline\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, pipeline\nmodel_id = \"gpt2\"\ntokenizer = AutoTokenizer.from_pretrained(model_id)\nmodel = AutoModelForCausalLM.from_pretrained(model_id)\npipe = pipeline(\n    \"text-generation\", model=model, tokenizer=tokenizer, max_new_tokens=10\n)\nhf = HuggingFacePipeline(pipeline=pipe)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam batch_size: int = 4\u00b6\nBatch size to use when passing multiple documents to generate.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_id: str = 'gpt2'\u00b6\nModel name to use.\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments passed to the model.\nparam pipeline_kwargs: Optional[dict] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "4bee6d12759f-1", "text": "Keyword arguments passed to the model.\nparam pipeline_kwargs: Optional[dict] = None\u00b6\nKeyword arguments passed to the pipeline.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "4bee6d12759f-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "4bee6d12759f-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "4bee6d12759f-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "4bee6d12759f-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "4bee6d12759f-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_model_id(model_id: str, task: str, device: Optional[int] = - 1, device_map: Optional[str] = None, model_kwargs: Optional[dict] = None, pipeline_kwargs: Optional[dict] = None, batch_size: int = 4, **kwargs: Any) \u2192 HuggingFacePipeline[source]\u00b6\nConstruct the pipeline object from model_id and task.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "4bee6d12759f-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "4bee6d12759f-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "4bee6d12759f-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "4bee6d12759f-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "4bee6d12759f-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "4bee6d12759f-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "4bee6d12759f-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using HuggingFacePipeline\u00b6\nHugging Face\nHugging Face Local Pipelines\nRELLM\nJSONFormer", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_pipeline.HuggingFacePipeline.html"}
{"id": "3308dda14ad3-0", "text": "langchain.llms.javelin_ai_gateway.Params\u00b6\nclass langchain.llms.javelin_ai_gateway.Params[source]\u00b6\nBases: BaseModel\nParameters for the Javelin AI Gateway LLM.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam max_tokens: Optional[int] = None\u00b6\nparam stop: Optional[List[str]] = None\u00b6\nparam temperature: float = 0.0\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.Params.html"}
{"id": "3308dda14ad3-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.Params.html"}
{"id": "3308dda14ad3-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.Params.html"}
{"id": "cb6b2e428eb2-0", "text": "langchain.llms.aleph_alpha.AlephAlpha\u00b6\nclass langchain.llms.aleph_alpha.AlephAlpha[source]\u00b6\nBases: LLM\nAleph Alpha large language models.\nTo use, you should have the aleph_alpha_client python package installed, and the\nenvironment variable ALEPH_ALPHA_API_KEY set with your API key, or pass\nit as a named parameter to the constructor.\nParameters are explained more in depth here:\nhttps://github.com/Aleph-Alpha/aleph-alpha-client/blob/c14b7dd2b4325c7da0d6a119f6e76385800e097b/aleph_alpha_client/completion.py#L10\nExample\nfrom langchain.llms import AlephAlpha\naleph_alpha = AlephAlpha(aleph_alpha_api_key=\"my-api-key\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aleph_alpha_api_key: Optional[str] = None\u00b6\nAPI key for Aleph Alpha API.\nparam best_of: Optional[int] = None\u00b6\nreturns the one with the \u201cbest of\u201d results\n(highest log probability per token)\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam completion_bias_exclusion: Optional[Sequence[str]] = None\u00b6\nparam completion_bias_exclusion_first_token_only: bool = False\u00b6\nOnly consider the first token for the completion_bias_exclusion.\nparam completion_bias_inclusion: Optional[Sequence[str]] = None\u00b6\nparam completion_bias_inclusion_first_token_only: bool = False\u00b6\nparam contextual_control_threshold: Optional[float] = None\u00b6\nIf set to None, attention control parameters only apply to those tokens that have", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-1", "text": "If set to None, attention control parameters only apply to those tokens that have\nexplicitly been set in the request.\nIf set to a non-None value, control parameters are also applied to similar tokens.\nparam control_log_additive: Optional[bool] = True\u00b6\nTrue: apply control by adding the log(control_factor) to attention scores.\nFalse: (attention_scores - - attention_scores.min(-1)) * control_factor\nparam disable_optimizations: Optional[bool] = False\u00b6\nparam echo: bool = False\u00b6\nEcho the prompt in the completion.\nparam frequency_penalty: float = 0.0\u00b6\nPenalizes repeated tokens according to frequency.\nparam host: str = 'https://api.aleph-alpha.com'\u00b6\nThe hostname of the API host.\nThe default one is \u201chttps://api.aleph-alpha.com\u201d)\nparam hosting: Optional[str] = None\u00b6\nDetermines in which datacenters the request may be processed.\nYou can either set the parameter to \u201caleph-alpha\u201d or omit it (defaulting to None).\nNot setting this value, or setting it to None, gives us maximal\nflexibility in processing your request in our\nown datacenters and on servers hosted with other providers.\nChoose this option for maximal availability.\nSetting it to \u201caleph-alpha\u201d allows us to only process the\nrequest in our own datacenters.\nChoose this option for maximal data privacy.\nparam log_probs: Optional[int] = None\u00b6\nNumber of top log probabilities to be returned for each generated token.\nparam logit_bias: Optional[Dict[int, float]] = None\u00b6\nThe logit bias allows to influence the likelihood of generating tokens.\nparam maximum_tokens: int = 64\u00b6\nThe maximum number of tokens to be generated.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-2", "text": "param metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam minimum_tokens: Optional[int] = 0\u00b6\nGenerate at least this number of tokens.\nparam model: Optional[str] = 'luminous-base'\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam nice: bool = False\u00b6\nSetting this to True, will signal to the API that you intend to be\nnice to other users\nby de-prioritizing your request below concurrent ones.\nparam penalty_bias: Optional[str] = None\u00b6\nPenalty bias for the completion.\nparam penalty_exceptions: Optional[List[str]] = None\u00b6\nList of strings that may be generated without penalty,\nregardless of other penalty settings\nparam penalty_exceptions_include_stop_sequences: Optional[bool] = None\u00b6\nShould stop_sequences be included in penalty_exceptions.\nparam presence_penalty: float = 0.0\u00b6\nPenalizes repeated tokens.\nparam raw_completion: bool = False\u00b6\nForce the raw completion of the model to be returned.\nparam repetition_penalties_include_completion: bool = True\u00b6\nFlag deciding whether presence penalty or frequency penalty\nare updated from the completion.\nparam repetition_penalties_include_prompt: Optional[bool] = False\u00b6\nFlag deciding whether presence penalty or frequency penalty are\nupdated from the prompt.\nparam request_timeout_seconds: int = 305\u00b6\nClient timeout that will be set for HTTP requests in the\nrequests library\u2019s API calls.\nServer will close all requests after 300 seconds with an internal server error.\nparam sequence_penalty: float = 0.0\u00b6\nparam sequence_penalty_min_length: int = 2\u00b6\nparam stop_sequences: Optional[List[str]] = None\u00b6\nStop sequences to use.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-3", "text": "Stop sequences to use.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.0\u00b6\nA non-negative float that tunes the degree of randomness in generation.\nparam tokens: Optional[bool] = False\u00b6\nreturn tokens of completion.\nparam top_k: int = 0\u00b6\nNumber of most likely tokens to consider at each step.\nparam top_p: float = 0.0\u00b6\nTotal probability mass of tokens to consider at each step.\nparam total_retries: int = 8\u00b6\nThe number of retries made in case requests fail with certain retryable\nstatus codes. If the last\nretry fails a corresponding exception is raised. Note, that between retries\nan exponential backoff\nis applied, starting with 0.5 s after the first retry and doubling for\neach retry made. So with the\ndefault setting of 8 retries a total wait time of 63.5 s is added\nbetween the retries.\nparam use_multiplicative_frequency_penalty: bool = False\u00b6\nparam use_multiplicative_presence_penalty: Optional[bool] = False\u00b6\nFlag deciding whether presence penalty is applied\nmultiplicatively (True) or additively (False).\nparam use_multiplicative_sequence_penalty: bool = False\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-4", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-5", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-6", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-7", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-8", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-9", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-10", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-11", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-12", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-13", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-14", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-15", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "cb6b2e428eb2-16", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using AlephAlpha\u00b6\nAleph Alpha", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aleph_alpha.AlephAlpha.html"}
{"id": "417552ad3e52-0", "text": "langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint\u00b6\nclass langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint[source]\u00b6\nBases: LLM, BaseModel\nAzure ML Online Endpoint models.\nExample\nazure_llm = AzureMLOnlineEndpoint(\n    endpoint_url=\"https://<your-endpoint>.<your_region>.inference.ml.azure.com/score\",\n    endpoint_api_key=\"my-api-key\",\n    content_formatter=content_formatter,\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam content_formatter: Any = None\u00b6\nThe content formatter that provides an input and output\ntransform function to handle formats between the LLM and\nthe endpoint\nparam deployment_name: str = ''\u00b6\nDeployment Name for Endpoint. NOT REQUIRED to call endpoint. Should be passed\nto constructor or specified as env var AZUREML_DEPLOYMENT_NAME.\nparam endpoint_api_key: str = ''\u00b6\nAuthentication Key for Endpoint. Should be passed to constructor or specified as\nenv var AZUREML_ENDPOINT_API_KEY.\nparam endpoint_url: str = ''\u00b6\nURL of pre-existing Endpoint. Should be passed to constructor or specified as\nenv var AZUREML_ENDPOINT_URL.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "417552ad3e52-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "417552ad3e52-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "417552ad3e52-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "417552ad3e52-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "417552ad3e52-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "417552ad3e52-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "417552ad3e52-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "417552ad3e52-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "417552ad3e52-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "417552ad3e52-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "417552ad3e52-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "417552ad3e52-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "417552ad3e52-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using AzureMLOnlineEndpoint\u00b6\nAzure ML", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLOnlineEndpoint.html"}
{"id": "a2dcf9b37a4b-0", "text": "langchain.llms.huggingface_endpoint.HuggingFaceEndpoint\u00b6\nclass langchain.llms.huggingface_endpoint.HuggingFaceEndpoint[source]\u00b6\nBases: LLM\nHuggingFace Endpoint models.\nTo use, you should have the huggingface_hub python package installed, and the\nenvironment variable HUGGINGFACEHUB_API_TOKEN set with your API token, or pass\nit as a named parameter to the constructor.\nOnly supports text-generation and text2text-generation for now.\nExample\nfrom langchain.llms import HuggingFaceEndpoint\nendpoint_url = (\n    \"https://abcdefghijklmnop.us-east-1.aws.endpoints.huggingface.cloud\"\n)\nhf = HuggingFaceEndpoint(\n    endpoint_url=endpoint_url,\n    huggingfacehub_api_token=\"my-api-key\"\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam endpoint_url: str = ''\u00b6\nEndpoint URL to use.\nparam huggingfacehub_api_token: Optional[str] = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam task: Optional[str] = None\u00b6\nTask to call the model with.\nShould be a task that returns generated_text or summary_text.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "a2dcf9b37a4b-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "a2dcf9b37a4b-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "a2dcf9b37a4b-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "a2dcf9b37a4b-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "a2dcf9b37a4b-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "a2dcf9b37a4b-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "a2dcf9b37a4b-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "a2dcf9b37a4b-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "a2dcf9b37a4b-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "a2dcf9b37a4b-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "a2dcf9b37a4b-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "a2dcf9b37a4b-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "a2dcf9b37a4b-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_endpoint.HuggingFaceEndpoint.html"}
{"id": "6dd1eb9a53c8-0", "text": "langchain.llms.cohere.Cohere\u00b6\nclass langchain.llms.cohere.Cohere[source]\u00b6\nBases: LLM, BaseCohere\nCohere large language models.\nTo use, you should have the cohere python package installed, and the\nenvironment variable COHERE_API_KEY set with your API key, or pass\nit as a named parameter to the constructor.\nExample\nfrom langchain.llms import Cohere\ncohere = Cohere(model=\"gptd-instruct-tft\", cohere_api_key=\"my-api-key\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam cohere_api_key: Optional[str] = None\u00b6\nparam frequency_penalty: float = 0.0\u00b6\nPenalizes repeated tokens according to frequency. Between 0 and 1.\nparam k: int = 0\u00b6\nNumber of most likely tokens to consider at each step.\nparam max_retries: int = 10\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: int = 256\u00b6\nDenotes the number of tokens to predict per generation.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: Optional[str] = None\u00b6\nModel name to use.\nparam p: int = 1\u00b6\nTotal probability mass of tokens to consider at each step.\nparam presence_penalty: float = 0.0\u00b6\nPenalizes repeated tokens. Between 0 and 1.\nparam stop: Optional[List[str]] = None\u00b6\nparam streaming: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "6dd1eb9a53c8-1", "text": "param stop: Optional[List[str]] = None\u00b6\nparam streaming: bool = False\u00b6\nWhether to stream the results.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.75\u00b6\nA non-negative float that tunes the degree of randomness in generation.\nparam truncate: Optional[str] = None\u00b6\nSpecify how the client handles inputs longer than the maximum token\nlength: Truncate from START, END or NONE\nparam user_agent: str = 'langchain'\u00b6\nIdentifier for the application making the request.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "6dd1eb9a53c8-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "6dd1eb9a53c8-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "6dd1eb9a53c8-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "6dd1eb9a53c8-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "6dd1eb9a53c8-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "6dd1eb9a53c8-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "6dd1eb9a53c8-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "6dd1eb9a53c8-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "6dd1eb9a53c8-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "6dd1eb9a53c8-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "6dd1eb9a53c8-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "6dd1eb9a53c8-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Cohere\u00b6\nCohere", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.Cohere.html"}
{"id": "8ce84ada46b3-0", "text": "langchain.llms.vllm.VLLMOpenAI\u00b6\nclass langchain.llms.vllm.VLLMOpenAI[source]\u00b6\nBases: BaseOpenAI\nvLLM OpenAI-compatible API client\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_special: Union[Literal['all'], AbstractSet[str]] = {}\u00b6\nSet of special tokens that are allowed\u3002\nparam batch_size: int = 20\u00b6\nBatch size to use when passing multiple documents to generate.\nparam best_of: int = 1\u00b6\nGenerates best_of completions server-side and returns the \u201cbest\u201d.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam default_headers: Union[Mapping[str, str], None] = None\u00b6\nparam default_query: Union[Mapping[str, object], None] = None\u00b6\nparam disallowed_special: Union[Literal['all'], Collection[str]] = 'all'\u00b6\nSet of special tokens that are not allowed\u3002\nparam frequency_penalty: float = 0\u00b6\nPenalizes repeated tokens according to frequency.\nparam http_client: Union[Any, None] = None\u00b6\nOptional httpx.Client.\nparam logit_bias: Optional[Dict[str, float]] [Optional]\u00b6\nAdjust the probability of specific tokens being generated.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: int = 256\u00b6\nThe maximum number of tokens to generate in the completion.\n-1 returns as many tokens as possible given the prompt and\nthe models maximal context size.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-1", "text": "param metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'text-davinci-003' (alias 'model')\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Optional[str] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var OPENAI_API_KEY if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam presence_penalty: float = 0\u00b6\nPenalizes repeated tokens.\nparam request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-2", "text": "them to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nparam top_p: float = 1\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-4", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-5", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-6", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-7", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_llm_result(choices: Any, prompts: List[str], token_usage: Dict[str, int], *, system_fingerprint: Optional[str] = None) \u2192 LLMResult\u00b6\nCreate the LLMResult from the choices and prompts.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-8", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-9", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_sub_prompts(params: Dict[str, Any], prompts: List[str], stop: Optional[List[str]] = None) \u2192 List[List[str]]\u00b6\nGet the sub prompts for llm call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-10", "text": "Get the sub prompts for llm call.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nGet the token IDs using the tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-11", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nmax_tokens_for_prompt(prompt: str) \u2192 int\u00b6\nCalculate the maximum number of tokens possible to generate for a prompt.\nParameters\nprompt \u2013 The prompt to pass into the model.\nReturns\nThe maximum number of tokens to generate for a prompt.\nExample\nmax_tokens = openai.max_token_for_prompt(\"Tell me a joke.\")\nstatic modelname_to_contextsize(modelname: str) \u2192 int\u00b6\nCalculate the maximum number of tokens possible to generate for a model.\nParameters\nmodelname \u2013 The modelname we want to know the context size for.\nReturns\nThe maximum context size\nExample\nmax_tokens = openai.modelname_to_contextsize(\"text-davinci-003\")\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-12", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-13", "text": "to_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-14", "text": "The Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "8ce84ada46b3-15", "text": "For example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty max_context_size: int\u00b6\nGet max context size for this model.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using VLLMOpenAI\u00b6\nvLLM", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vllm.VLLMOpenAI.html"}
{"id": "76fb1c9bc58f-0", "text": "langchain.llms.rwkv.RWKV\u00b6\nclass langchain.llms.rwkv.RWKV[source]\u00b6\nBases: LLM, BaseModel\nRWKV language models.\nTo use, you should have the rwkv python package installed, the\npre-trained model file, and the model\u2019s config information.\nExample\nfrom langchain.llms import RWKV\nmodel = RWKV(model=\"./models/rwkv-3b-fp16.bin\", strategy=\"cpu fp32\")\n# Simplest invocation\nresponse = model(\"Once upon a time, \")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam CHUNK_LEN: int = 256\u00b6\nBatch size for prompt processing.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam max_tokens_per_generation: int = 256\u00b6\nMaximum number of tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str [Required]\u00b6\nPath to the pre-trained RWKV model file.\nparam penalty_alpha_frequency: float = 0.4\u00b6\nPositive values penalize new tokens based on their existing frequency\nin the text so far, decreasing the model\u2019s likelihood to repeat the same\nline verbatim..\nparam penalty_alpha_presence: float = 0.4\u00b6\nPositive values penalize new tokens based on whether they appear\nin the text so far, increasing the model\u2019s likelihood to talk about\nnew topics..\nparam rwkv_verbose: bool = True\u00b6\nPrint debug information.\nparam strategy: str = 'cpu fp32'\u00b6\nToken context window.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "76fb1c9bc58f-1", "text": "Token context window.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 1.0\u00b6\nThe temperature to use for sampling.\nparam tokens_path: str [Required]\u00b6\nPath to the RWKV tokens file.\nparam top_p: float = 0.5\u00b6\nThe top-p value to use for sampling.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "76fb1c9bc58f-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "76fb1c9bc58f-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "76fb1c9bc58f-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "76fb1c9bc58f-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "76fb1c9bc58f-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "76fb1c9bc58f-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "76fb1c9bc58f-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "76fb1c9bc58f-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "76fb1c9bc58f-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nrun_rnn(_tokens: List[str], newline_adj: int = 0) \u2192 Any[source]\u00b6\nrwkv_generate(prompt: str) \u2192 str[source]\u00b6\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "76fb1c9bc58f-11", "text": "Save the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "76fb1c9bc58f-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "76fb1c9bc58f-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using RWKV\u00b6\nRWKV-4", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.rwkv.RWKV.html"}
{"id": "666273585653-0", "text": "langchain.llms.together.Together\u00b6\nclass langchain.llms.together.Together[source]\u00b6\nBases: LLM\nWrapper around Together AI models.\nTo use, you\u2019ll need an API key which you can find here:\nhttps://api.together.xyz/settings/api-keys. This can be passed in as init param\ntogether_api_key or set as environment variable TOGETHER_API_KEY.\nTogether AI API reference: https://docs.together.ai/reference/inference\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam base_url: str = 'https://api.together.xyz/inference'\u00b6\nBase inference API URL.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam logprobs: Optional[int] = None\u00b6\nAn integer that specifies how many top token log probabilities are included in\nthe response for each token generation step.\nparam max_tokens: Optional[int] = None\u00b6\nThe maximum number of tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str [Required]\u00b6\nModel name. Available models listed here:\nhttps://docs.together.ai/docs/inference-models\nparam repetition_penalty: Optional[float] = None\u00b6\nA number that controls the diversity of generated text by reducing the\nlikelihood of repeated sequences. Higher values decrease repetition.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = None\u00b6\nModel temperature.\nparam together_api_key: str [Required]\u00b6\nTogether AI API key. Get it here: https://api.together.xyz/settings/api-keys", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "666273585653-1", "text": "Together AI API key. Get it here: https://api.together.xyz/settings/api-keys\nparam top_k: Optional[int] = None\u00b6\nUsed to limit the number of choices for the next predicted word or token. It\nspecifies the maximum number of tokens to consider at each step, based on their\nprobability of occurrence. This technique helps to speed up the generation\nprocess and can improve the quality of the generated text by focusing on the\nmost likely options.\nparam top_p: Optional[float] = None\u00b6\nUsed to dynamically adjust the number of choices for each predicted token based\non the cumulative probabilities. A value of 1 will always yield the same\noutput. A temperature less than 1 favors more correctness and is appropriate\nfor question answering or summarization. A value greater than 1 introduces more\nrandomness in the output.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "666273585653-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "666273585653-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "666273585653-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "666273585653-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "666273585653-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "666273585653-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "666273585653-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\nstatic get_user_agent() \u2192 str[source]\u00b6\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "666273585653-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "666273585653-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "666273585653-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "666273585653-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "666273585653-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty default_params: Dict[str, Any]\u00b6\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.together.Together.html"}
{"id": "bc8b12cf41eb-0", "text": "langchain.llms.textgen.TextGen\u00b6\nclass langchain.llms.textgen.TextGen[source]\u00b6\nBases: LLM\ntext-generation-webui models.\nTo use, you should have the text-generation-webui installed, a model loaded,\nand \u2013api added as a command-line option.\nSuggested installation, use one-click installer for your OS:\nhttps://github.com/oobabooga/text-generation-webui#one-click-installers\nParameters below taken from text-generation-webui api example:\nhttps://github.com/oobabooga/text-generation-webui/blob/main/api-examples/api-example.py\nExample\nfrom langchain.llms import TextGen\nllm = TextGen(model_url=\"http://localhost:8500\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam add_bos_token: bool = True\u00b6\nAdd the bos_token to the beginning of prompts.\nDisabling this can make the replies more creative.\nparam ban_eos_token: bool = False\u00b6\nBan the eos_token. Forces the model to never end the generation prematurely.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam do_sample: bool = True\u00b6\nDo sample\nparam early_stopping: bool = False\u00b6\nEarly stopping\nparam epsilon_cutoff: Optional[float] = 0\u00b6\nEpsilon cutoff\nparam eta_cutoff: Optional[float] = 0\u00b6\nETA cutoff\nparam length_penalty: Optional[float] = 1\u00b6\nLength Penalty\nparam max_new_tokens: Optional[int] = 250\u00b6\nThe maximum number of tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-1", "text": "Metadata to add to the run trace.\nparam min_length: Optional[int] = 0\u00b6\nMinimum generation length in tokens.\nparam model_url: str [Required]\u00b6\nThe full URL to the textgen webui including http[s]://host:port\nparam no_repeat_ngram_size: Optional[int] = 0\u00b6\nIf not set to 0, specifies the length of token sets that are completely blocked\nfrom repeating at all. Higher values = blocks larger phrases,\nlower values = blocks words or letters from repeating.\nOnly 0 or high values are a good idea in most cases.\nparam num_beams: Optional[int] = 1\u00b6\nNumber of beams\nparam penalty_alpha: Optional[float] = 0\u00b6\nPenalty Alpha\nparam preset: Optional[str] = None\u00b6\nThe preset to use in the textgen webui\nparam repetition_penalty: Optional[float] = 1.18\u00b6\nExponential penalty factor for repeating prior tokens. 1 means no penalty,\nhigher value = less repetition, lower value = more repetition.\nparam seed: int = -1\u00b6\nSeed (-1 for random)\nparam skip_special_tokens: bool = True\u00b6\nSkip special tokens. Some specific models need this unset.\nparam stopping_strings: Optional[List[str]] = []\u00b6\nA list of strings to stop generation when encountered.\nparam streaming: bool = False\u00b6\nWhether to stream the results, token by token.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = 1.3\u00b6\nPrimary factor to control randomness of outputs. 0 = deterministic\n(only the most likely token is used). Higher value = more randomness.\nparam top_k: Optional[float] = 40\u00b6\nSimilar to top_p, but select instead only the top_k most likely tokens.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-2", "text": "Similar to top_p, but select instead only the top_k most likely tokens.\nHigher value = higher range of possible random results.\nparam top_p: Optional[float] = 0.1\u00b6\nIf not set to 1, select tokens with probabilities adding up to less than this\nnumber. Higher value = higher range of possible random results.\nparam truncation_length: Optional[int] = 2048\u00b6\nTruncate the prompt up to this length. The leftmost tokens are removed if\nthe prompt exceeds this length. Most models require this to be at most 2048.\nparam typical_p: Optional[float] = 1\u00b6\nIf not set to 1, select only tokens that are at least this much more likely to\nappear than random tokens, given the prior text.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-4", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-5", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-6", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-7", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-8", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-9", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-10", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-11", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-12", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-13", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "bc8b12cf41eb-14", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using TextGen\u00b6\nTextGen", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.textgen.TextGen.html"}
{"id": "d946a896f476-0", "text": "langchain.llms.octoai_endpoint.OctoAIEndpoint\u00b6\nclass langchain.llms.octoai_endpoint.OctoAIEndpoint[source]\u00b6\nBases: LLM\nOctoAI LLM Endpoints.\nOctoAIEndpoint is a class to interact with OctoAICompute Service large language model endpoints.\nTo use, you should have the octoai python package installed, and the\nenvironment variable OCTOAI_API_TOKEN set with your API token, or pass\nit as a named parameter to the constructor.\nExample\nfrom langchain.llms.octoai_endpoint  import OctoAIEndpoint\nOctoAIEndpoint(\n    octoai_api_token=\"octoai-api-key\",\n    endpoint_url=\"https://mpt-7b-demo-f1kzsig6xes9.octoai.run/generate\",\n    model_kwargs={\n        \"max_new_tokens\": 200,\n        \"temperature\": 0.75,\n        \"top_p\": 0.95,\n        \"repetition_penalty\": 1,\n        \"seed\": None,\n        \"stop\": [],\n    },\n)\nfrom langchain.llms.octoai_endpoint  import OctoAIEndpoint\nOctoAIEndpoint(\n    octoai_api_token=\"octoai-api-key\",\n    endpoint_url=\"https://llama-2-7b-chat-demo-kk0powt97tmb.octoai.run/v1/chat/completions\",\n    model_kwargs={\n        \"model\": \"llama-2-7b-chat\",\n        \"messages\": [\n            {\n                \"role\": \"system\",\n                \"content\": \"Below is an instruction that describes a task.\n                    Write a response that completes the request.\"\n            }\n        ],\n        \"stream\": False,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "d946a896f476-1", "text": "}\n        ],\n        \"stream\": False,\n        \"max_tokens\": 256\n    }\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam endpoint_url: Optional[str] = None\u00b6\nEndpoint URL to use.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam octoai_api_token: Optional[str] = None\u00b6\nOCTOAI API Token\nparam streaming: bool = False\u00b6\nWhether to generate a stream of tokens asynchronously\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "d946a896f476-2", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "d946a896f476-3", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "d946a896f476-4", "text": "Use this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "d946a896f476-5", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "d946a896f476-6", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "d946a896f476-7", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "d946a896f476-8", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "d946a896f476-9", "text": "Parameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "d946a896f476-10", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "d946a896f476-11", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "d946a896f476-12", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "d946a896f476-13", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using OctoAIEndpoint\u00b6\nOctoAI", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.octoai_endpoint.OctoAIEndpoint.html"}
{"id": "0a778628f004-0", "text": "langchain.llms.tongyi.Tongyi\u00b6\nclass langchain.llms.tongyi.Tongyi[source]\u00b6\nBases: LLM\nTongyi Qwen large language models.\nTo use, you should have the dashscope python package installed, and the\nenvironment variable DASHSCOPE_API_KEY set with your API key, or pass\nit as a named parameter to the constructor.\nExample\nfrom langchain.llms import Tongyi\nTongyi = tongyi()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam dashscope_api_key: Optional[str] = None\u00b6\nDashscope api key provide by alicloud.\nparam max_retries: int = 10\u00b6\nMaximum number of retries to make when generating.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nparam model_name: str = 'qwen-plus-v1'\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam prefix_messages: List [Optional]\u00b6\nSeries of messages for Chat input.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam top_p: float = 0.8\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "0a778628f004-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "0a778628f004-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "0a778628f004-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "0a778628f004-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "0a778628f004-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "0a778628f004-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "0a778628f004-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "0a778628f004-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "0a778628f004-9", "text": "The output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "0a778628f004-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "0a778628f004-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "0a778628f004-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "0a778628f004-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Tongyi\u00b6\nTongyi Qwen\nDashVector", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.Tongyi.html"}
{"id": "3af2edcd8333-0", "text": "langchain.llms.symblai_nebula.make_request\u00b6\nlangchain.llms.symblai_nebula.make_request(self: Nebula, instruction: str, conversation: str, url: str = 'https://api-nebula.symbl.ai/v1/model/generate', params: Optional[Dict] = None) \u2192 Any[source]\u00b6\nGenerate text from the model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.make_request.html"}
{"id": "a91361fafc09-0", "text": "langchain.llms.databricks.get_repl_context\u00b6\nlangchain.llms.databricks.get_repl_context() \u2192 Any[source]\u00b6\nGets the notebook REPL context if running inside a Databricks notebook.\nReturns None otherwise.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.get_repl_context.html"}
{"id": "cfda562cb94c-0", "text": "langchain.llms.stochasticai.StochasticAI\u00b6\nclass langchain.llms.stochasticai.StochasticAI[source]\u00b6\nBases: LLM\nStochasticAI large language models.\nTo use, you should have the environment variable STOCHASTICAI_API_KEY\nset with your API key.\nExample\nfrom langchain.llms import StochasticAI\nstochasticai = StochasticAI(api_url=\"\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_url: str = ''\u00b6\nModel name to use.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not\nexplicitly specified.\nparam stochasticai_api_key: Optional[str] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "cfda562cb94c-1", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "cfda562cb94c-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "cfda562cb94c-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "cfda562cb94c-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "cfda562cb94c-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "cfda562cb94c-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "cfda562cb94c-7", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "cfda562cb94c-8", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "cfda562cb94c-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "cfda562cb94c-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "cfda562cb94c-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "cfda562cb94c-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "cfda562cb94c-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using StochasticAI\u00b6\nStochasticAI", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.stochasticai.StochasticAI.html"}
{"id": "dcf882eef8df-0", "text": "langchain.llms.ollama.Ollama\u00b6\nclass langchain.llms.ollama.Ollama[source]\u00b6\nBases: BaseLLM, _OllamaCommon\nOllama locally runs large language models.\nTo use, follow the instructions at https://ollama.ai/.\nExample\nfrom langchain.llms import Ollama\nollama = Ollama(model=\"llama2\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam base_url: str = 'http://localhost:11434'\u00b6\nBase url the model is hosted under.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam mirostat: Optional[int] = None\u00b6\nEnable Mirostat sampling for controlling perplexity.\n(default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\nparam mirostat_eta: Optional[float] = None\u00b6\nInfluences how quickly the algorithm responds to feedback\nfrom the generated text. A lower learning rate will result in\nslower adjustments, while a higher learning rate will make\nthe algorithm more responsive. (Default: 0.1)\nparam mirostat_tau: Optional[float] = None\u00b6\nControls the balance between coherence and diversity\nof the output. A lower value will result in more focused and\ncoherent text. (Default: 5.0)\nparam model: str = 'llama2'\u00b6\nModel name to use.\nparam num_ctx: Optional[int] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-1", "text": "Model name to use.\nparam num_ctx: Optional[int] = None\u00b6\nSets the size of the context window used to generate the\nnext token. (Default: 2048)\nparam num_gpu: Optional[int] = None\u00b6\nThe number of GPUs to use. On macOS it defaults to 1 to\nenable metal support, 0 to disable.\nparam num_thread: Optional[int] = None\u00b6\nSets the number of threads to use during computation.\nBy default, Ollama will detect this for optimal performance.\nIt is recommended to set this value to the number of physical\nCPU cores your system has (as opposed to the logical number of cores).\nparam repeat_last_n: Optional[int] = None\u00b6\nSets how far back for the model to look back to prevent\nrepetition. (Default: 64, 0 = disabled, -1 = num_ctx)\nparam repeat_penalty: Optional[float] = None\u00b6\nSets how strongly to penalize repetitions. A higher value (e.g., 1.5)\nwill penalize repetitions more strongly, while a lower value (e.g., 0.9)\nwill be more lenient. (Default: 1.1)\nparam stop: Optional[List[str]] = None\u00b6\nSets the stop tokens to use.\nparam system: Optional[str] = None\u00b6\nsystem prompt (overrides what is defined in the Modelfile)\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = None\u00b6\nThe temperature of the model. Increasing the temperature will\nmake the model answer more creatively. (Default: 0.8)\nparam template: Optional[str] = None\u00b6\nfull prompt or prompt template (overrides what is defined in the Modelfile)\nparam tfs_z: Optional[float] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-2", "text": "param tfs_z: Optional[float] = None\u00b6\nTail free sampling is used to reduce the impact of less probable\ntokens from the output. A higher value (e.g., 2.0) will reduce the\nimpact more, while a value of 1.0 disables this setting. (default: 1)\nparam top_k: Optional[int] = None\u00b6\nReduces the probability of generating nonsense. A higher value (e.g. 100)\nwill give more diverse answers, while a lower value (e.g. 10)\nwill be more conservative. (Default: 40)\nparam top_p: Optional[int] = None\u00b6\nWorks together with top-k. A higher value (e.g., 0.95) will lead\nto more diverse text, while a lower value (e.g., 0.5) will\ngenerate more focused and conservative text. (Default: 0.9)\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-3", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-4", "text": "first occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-5", "text": "Parameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-6", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-7", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-8", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-9", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-10", "text": "Parameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-11", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-12", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-13", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "dcf882eef8df-14", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Ollama\u00b6\nOllama\nRun LLMs locally", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ollama.Ollama.html"}
{"id": "6d786bc3e525-0", "text": "langchain.llms.databricks.get_default_host\u00b6\nlangchain.llms.databricks.get_default_host() \u2192 str[source]\u00b6\nGets the default Databricks workspace hostname.\nRaises an error if the hostname cannot be automatically determined.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.get_default_host.html"}
{"id": "1bac6a303fa7-0", "text": "langchain.llms.ai21.AI21\u00b6\nclass langchain.llms.ai21.AI21[source]\u00b6\nBases: LLM\nAI21 large language models.\nTo use, you should have the environment variable AI21_API_KEY\nset with your API key or pass it as a named parameter to the constructor.\nExample\nfrom langchain.llms import AI21\nai21 = AI21(ai21_api_key=\"my-api-key\", model=\"j2-jumbo-instruct\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam ai21_api_key: Optional[pydantic.types.SecretStr] = None\u00b6\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nparam base_url: Optional[str] = None\u00b6\nBase url to use, if None decides based on model name.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam countPenalty: langchain.llms.ai21.AI21PenaltyData = AI21PenaltyData(scale=0, applyToWhitespaces=True, applyToPunctuations=True, applyToNumbers=True, applyToStopwords=True, applyToEmojis=True)\u00b6\nPenalizes repeated tokens according to count.\nparam frequencyPenalty: langchain.llms.ai21.AI21PenaltyData = AI21PenaltyData(scale=0, applyToWhitespaces=True, applyToPunctuations=True, applyToNumbers=True, applyToStopwords=True, applyToEmojis=True)\u00b6\nPenalizes repeated tokens according to frequency.\nparam logitBias: Optional[Dict[str, float]] = None\u00b6\nAdjust the probability of specific tokens being generated.\nparam maxTokens: int = 256\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-1", "text": "Adjust the probability of specific tokens being generated.\nparam maxTokens: int = 256\u00b6\nThe maximum number of tokens to generate in the completion.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam minTokens: int = 0\u00b6\nThe minimum number of tokens to generate in the completion.\nparam model: str = 'j2-jumbo-instruct'\u00b6\nModel name to use.\nparam numResults: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam presencePenalty: langchain.llms.ai21.AI21PenaltyData = AI21PenaltyData(scale=0, applyToWhitespaces=True, applyToPunctuations=True, applyToNumbers=True, applyToStopwords=True, applyToEmojis=True)\u00b6\nPenalizes repeated tokens.\nparam stop: Optional[List[str]] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam topP: float = 1.0\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-2", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-3", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-4", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-5", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-6", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-7", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-8", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-9", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-11", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-12", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-13", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "1bac6a303fa7-14", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using AI21\u00b6\nAI21 Labs\nAI21", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21.html"}
{"id": "3144618d6fe2-0", "text": "langchain.llms.sagemaker_endpoint.ContentHandlerBase\u00b6\nclass langchain.llms.sagemaker_endpoint.ContentHandlerBase[source]\u00b6\nA handler class to transform input from LLM to a\nformat that SageMaker endpoint expects.\nSimilarly, the class handles transforming output from the\nSageMaker endpoint to a format that LLM class expects.\nAttributes\naccepts\nThe MIME type of the response data returned from endpoint\ncontent_type\nThe MIME type of the input data passed to endpoint\nMethods\n__init__()\ntransform_input(prompt,\u00a0model_kwargs)\nTransforms the input to a format that model can accept as the request Body.\ntransform_output(output)\nTransforms the output from the model to string that the LLM class expects.\n__init__()\u00b6\nabstract transform_input(prompt: INPUT_TYPE, model_kwargs: Dict) \u2192 bytes[source]\u00b6\nTransforms the input to a format that model can accept\nas the request Body. Should return bytes or seekable file\nlike object in the format specified in the content_type\nrequest header.\nabstract transform_output(output: bytes) \u2192 OUTPUT_TYPE[source]\u00b6\nTransforms the output from the model to string that\nthe LLM class expects.\nExamples using ContentHandlerBase\u00b6\nSageMaker Endpoint", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.ContentHandlerBase.html"}
{"id": "2a28b7afacdf-0", "text": "langchain.llms.sagemaker_endpoint.LLMContentHandler\u00b6\nclass langchain.llms.sagemaker_endpoint.LLMContentHandler[source]\u00b6\nContent handler for LLM class.\nAttributes\naccepts\nThe MIME type of the response data returned from endpoint\ncontent_type\nThe MIME type of the input data passed to endpoint\nMethods\n__init__()\ntransform_input(prompt,\u00a0model_kwargs)\nTransforms the input to a format that model can accept as the request Body.\ntransform_output(output)\nTransforms the output from the model to string that the LLM class expects.\n__init__()\u00b6\nabstract transform_input(prompt: INPUT_TYPE, model_kwargs: Dict) \u2192 bytes\u00b6\nTransforms the input to a format that model can accept\nas the request Body. Should return bytes or seekable file\nlike object in the format specified in the content_type\nrequest header.\nabstract transform_output(output: bytes) \u2192 OUTPUT_TYPE\u00b6\nTransforms the output from the model to string that\nthe LLM class expects.\nExamples using LLMContentHandler\u00b6\nSageMaker Endpoint\nSageMakerEndpoint\nAmazon Comprehend Moderation Chain", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.LLMContentHandler.html"}
{"id": "8b712a73cdba-0", "text": "langchain.llms.fireworks.acompletion_with_retry_streaming\u00b6\nasync langchain.llms.fireworks.acompletion_with_retry_streaming(llm: Fireworks, use_retry: bool, *, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call for streaming.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.acompletion_with_retry_streaming.html"}
{"id": "cf7082912544-0", "text": "langchain.llms.base.update_cache\u00b6\nlangchain.llms.base.update_cache(existing_prompts: Dict[int, List], llm_string: str, missing_prompt_idxs: List[int], new_results: LLMResult, prompts: List[str]) \u2192 Optional[dict][source]\u00b6\nUpdate the cache and get the LLM output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.update_cache.html"}
{"id": "27f5ed23cfab-0", "text": "langchain.llms.nlpcloud.NLPCloud\u00b6\nclass langchain.llms.nlpcloud.NLPCloud[source]\u00b6\nBases: LLM\nNLPCloud large language models.\nTo use, you should have the nlpcloud python package installed, and the\nenvironment variable NLPCLOUD_API_KEY set with your API key.\nExample\nfrom langchain.llms import NLPCloud\nnlpcloud = NLPCloud(model=\"finetuned-gpt-neox-20b\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam bad_words: List[str] = []\u00b6\nList of tokens not allowed to be generated.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam gpu: bool = True\u00b6\nWhether to use a GPU or not\nparam lang: str = 'en'\u00b6\nLanguage to use (multilingual addon)\nparam length_no_input: bool = True\u00b6\nWhether min_length and max_length should include the length of the input.\nparam max_length: int = 256\u00b6\nThe maximum number of tokens to generate in the completion.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_name: str = 'finetuned-gpt-neox-20b'\u00b6\nModel name to use.\nparam nlpcloud_api_key: Optional[str] = None\u00b6\nparam num_beams: int = 1\u00b6\nNumber of beams for beam search.\nparam num_return_sequences: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam remove_end_sequence: bool = True\u00b6\nWhether or not to remove the end sequence token.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "27f5ed23cfab-1", "text": "Whether or not to remove the end sequence token.\nparam remove_input: bool = True\u00b6\nRemove input text from API response\nparam repetition_penalty: float = 1.0\u00b6\nPenalizes repeated tokens. 1.0 means no penalty.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam top_k: int = 50\u00b6\nThe number of highest probability tokens to keep for top-k filtering.\nparam top_p: int = 1\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "27f5ed23cfab-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "27f5ed23cfab-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "27f5ed23cfab-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "27f5ed23cfab-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "27f5ed23cfab-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "27f5ed23cfab-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "27f5ed23cfab-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "27f5ed23cfab-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "27f5ed23cfab-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "27f5ed23cfab-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "27f5ed23cfab-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "27f5ed23cfab-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using NLPCloud\u00b6\nNLPCloud\nNLP Cloud", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.nlpcloud.NLPCloud.html"}
{"id": "f28f26dc9a26-0", "text": "langchain.llms.fake.FakeListLLM\u00b6\nclass langchain.llms.fake.FakeListLLM[source]\u00b6\nBases: LLM\nFake LLM for testing purposes.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam i: int = 0\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam responses: List[str] [Required]\u00b6\nparam sleep: Optional[float] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeListLLM.html"}
{"id": "f28f26dc9a26-1", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeListLLM.html"}
{"id": "f28f26dc9a26-2", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeListLLM.html"}
{"id": "f28f26dc9a26-3", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeListLLM.html"}
{"id": "f28f26dc9a26-4", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeListLLM.html"}
{"id": "f28f26dc9a26-5", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeListLLM.html"}
{"id": "f28f26dc9a26-6", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeListLLM.html"}
{"id": "f28f26dc9a26-7", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeListLLM.html"}
{"id": "f28f26dc9a26-8", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeListLLM.html"}
{"id": "f28f26dc9a26-9", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeListLLM.html"}
{"id": "f28f26dc9a26-10", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeListLLM.html"}
{"id": "f28f26dc9a26-11", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeListLLM.html"}
{"id": "f28f26dc9a26-12", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using FakeListLLM\u00b6\nAmazon Comprehend Moderation Chain\nFake LLM", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fake.FakeListLLM.html"}
{"id": "8d0823577673-0", "text": "langchain.llms.mosaicml.MosaicML\u00b6\nclass langchain.llms.mosaicml.MosaicML[source]\u00b6\nBases: LLM\nMosaicML LLM service.\nTo use, you should have the\nenvironment variable MOSAICML_API_TOKEN set with your API token, or pass\nit as a named parameter to the constructor.\nExample\nfrom langchain.llms import MosaicML\nendpoint_url = (\n    \"https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict\"\n)\nmosaic_llm = MosaicML(\n    endpoint_url=endpoint_url,\n    mosaicml_api_token=\"my-api-key\"\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam endpoint_url: str = 'https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict'\u00b6\nEndpoint URL to use.\nparam inject_instruction_format: bool = False\u00b6\nWhether to inject the instruction format into the prompt.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam mosaicml_api_token: Optional[str] = None\u00b6\nparam retry_sleep: float = 1.0\u00b6\nHow long to try sleeping for if a rate limit is encountered\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "8d0823577673-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "8d0823577673-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "8d0823577673-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "8d0823577673-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "8d0823577673-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "8d0823577673-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "8d0823577673-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "8d0823577673-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "8d0823577673-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "8d0823577673-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "8d0823577673-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "8d0823577673-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "8d0823577673-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using MosaicML\u00b6\nMosaicML", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mosaicml.MosaicML.html"}
{"id": "31c9685bf68f-0", "text": "langchain.llms.azureml_endpoint.GPT2ContentFormatter\u00b6\nclass langchain.llms.azureml_endpoint.GPT2ContentFormatter[source]\u00b6\nContent handler for GPT2\nAttributes\naccepts\nThe MIME type of the response data returned from the endpoint\ncontent_type\nThe MIME type of the input data passed to the endpoint\nMethods\n__init__()\nescape_special_characters(prompt)\nEscapes any special characters in prompt\nformat_request_payload(prompt,\u00a0model_kwargs)\nFormats the request body according to the input schema of the model.\nformat_response_payload(output)\nFormats the response body according to the output schema of the model.\n__init__()\u00b6\nstatic escape_special_characters(prompt: str) \u2192 str\u00b6\nEscapes any special characters in prompt\nformat_request_payload(prompt: str, model_kwargs: Dict) \u2192 bytes[source]\u00b6\nFormats the request body according to the input schema of\nthe model. Returns bytes or seekable file like object in the\nformat specified in the content_type request header.\nformat_response_payload(output: bytes) \u2192 str[source]\u00b6\nFormats the response body according to the output\nschema of the model. Returns the data type that is\nreceived from the response.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.GPT2ContentFormatter.html"}
{"id": "4b402619f693-0", "text": "langchain.llms.loading.load_llm_from_config\u00b6\nlangchain.llms.loading.load_llm_from_config(config: dict) \u2192 BaseLLM[source]\u00b6\nLoad LLM from Config Dict.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.loading.load_llm_from_config.html"}
{"id": "594df3596ecc-0", "text": "langchain.llms.openai.completion_with_retry\u00b6\nlangchain.llms.openai.completion_with_retry(llm: Union[BaseOpenAI, OpenAIChat], run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.completion_with_retry.html"}
{"id": "741309fd62ca-0", "text": "langchain.llms.ai21.AI21PenaltyData\u00b6\nclass langchain.llms.ai21.AI21PenaltyData[source]\u00b6\nBases: BaseModel\nParameters for AI21 penalty data.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam applyToEmojis: bool = True\u00b6\nparam applyToNumbers: bool = True\u00b6\nparam applyToPunctuations: bool = True\u00b6\nparam applyToStopwords: bool = True\u00b6\nparam applyToWhitespaces: bool = True\u00b6\nparam scale: int = 0\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21PenaltyData.html"}
{"id": "741309fd62ca-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21PenaltyData.html"}
{"id": "741309fd62ca-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ai21.AI21PenaltyData.html"}
{"id": "011de82ba1f1-0", "text": "langchain.llms.bedrock.Bedrock\u00b6\nclass langchain.llms.bedrock.Bedrock[source]\u00b6\nBases: LLM, BedrockBase\nBedrock models.\nTo authenticate, the AWS client uses the following methods to\nautomatically load credentials:\nhttps://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\nIf a specific credential profile should be used, you must pass\nthe name of the profile from the ~/.aws/credentials file that is to be used.\nMake sure the credentials / roles used have the required policies to\naccess the Bedrock service.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam credentials_profile_name: Optional[str] = None\u00b6\nThe name of the profile in the ~/.aws/credentials or ~/.aws/config files, which\nhas either access keys or role information specified.\nIf not specified, the default credential profile or, if on an EC2 instance,\ncredentials from IMDS will be used.\nSee: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\nparam endpoint_url: Optional[str] = None\u00b6\nNeeded if you don\u2019t want to default to us-east-1 endpoint\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_id: str [Required]\u00b6\nId of the model to call, e.g., amazon.titan-text-express-v1, this is\nequivalent to the modelId property in the list-foundation-models api\nparam model_kwargs: Optional[Dict] = None\u00b6\nKeyword arguments to pass to the model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "011de82ba1f1-1", "text": "Keyword arguments to pass to the model.\nparam provider_stop_sequence_key_name_map: Mapping[str, str] = {'ai21': 'stop_sequences', 'amazon': 'stopSequences', 'anthropic': 'stop_sequences', 'cohere': 'stop_sequences'}\u00b6\nparam region_name: Optional[str] = None\u00b6\nThe aws region e.g., us-west-2. Fallsback to AWS_DEFAULT_REGION env variable\nor region specified in ~/.aws/config in case it is not provided here.\nparam streaming: bool = False\u00b6\nWhether to stream the results.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "011de82ba1f1-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "011de82ba1f1-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "011de82ba1f1-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "011de82ba1f1-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "011de82ba1f1-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "011de82ba1f1-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "011de82ba1f1-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int[source]\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int][source]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "011de82ba1f1-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nReturn whether this model can be serialized by Langchain.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "011de82ba1f1-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "011de82ba1f1-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "011de82ba1f1-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "011de82ba1f1-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Bedrock\u00b6\nBedrock", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.Bedrock.html"}
{"id": "dca083f41fef-0", "text": "langchain.llms.symblai_nebula.Nebula\u00b6\nclass langchain.llms.symblai_nebula.Nebula[source]\u00b6\nBases: LLM\nNebula Service models.\nTo use, you should have the environment variable NEBULA_SERVICE_URL,\nNEBULA_SERVICE_PATH and NEBULA_API_KEY set with your Nebula\nService, or pass it as a named parameter to the constructor.\nExample\nfrom langchain.llms import Nebula\nnebula = Nebula(\n    nebula_service_url=\"NEBULA_SERVICE_URL\",\n    nebula_service_path=\"NEBULA_SERVICE_PATH\",\n    nebula_api_key=\"NEBULA_API_KEY\",\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam max_new_tokens: Optional[int] = 128\u00b6\nparam max_retries: Optional[int] = 10\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: Optional[str] = None\u00b6\nparam model_kwargs: Optional[dict] = None\u00b6\nOptional\nparam nebula_api_key: Optional[pydantic.types.SecretStr] = None\u00b6\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nparam nebula_service_path: Optional[str] = None\u00b6\nparam nebula_service_url: Optional[str] = None\u00b6\nparam penalty_alpha: Optional[float] = 0.0\u00b6\nparam repetition_penalty: Optional[float] = 1.0\u00b6\nparam stop_sequences: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "dca083f41fef-1", "text": "param stop_sequences: Optional[List[str]] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = 0.6\u00b6\nparam top_k: Optional[int] = 0\u00b6\nparam top_p: Optional[float] = 0.95\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "dca083f41fef-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "dca083f41fef-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "dca083f41fef-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "dca083f41fef-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "dca083f41fef-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "dca083f41fef-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "dca083f41fef-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "dca083f41fef-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "dca083f41fef-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "dca083f41fef-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "dca083f41fef-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "dca083f41fef-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Nebula\u00b6\nNebula\nNebula (Symbl.ai)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.Nebula.html"}
{"id": "4c898a7372c0-0", "text": "langchain.llms.aviary.Aviary\u00b6\nclass langchain.llms.aviary.Aviary[source]\u00b6\nBases: LLM\nAviary hosted models.\nAviary is a backend for hosted models. You can\nfind out more about aviary at\nhttp://github.com/ray-project/aviary\nTo get a list of the models supported on an\naviary, follow the instructions on the website to\ninstall the aviary CLI and then use:\naviary models\nAVIARY_URL and AVIARY_TOKEN environment variables must be set.\nmodel\u00b6\nThe name of the model to use. Defaults to \u201camazon/LightGPT\u201d.\naviary_url\u00b6\nThe URL for the Aviary backend. Defaults to None.\naviary_token\u00b6\nThe bearer token for the Aviary backend. Defaults to None.\nuse_prompt_format\u00b6\nIf True, the prompt template for the model will be ignored.\nDefaults to True.\nversion\u00b6\nAPI version to use for Aviary. Defaults to None.\nExample\nfrom langchain.llms import Aviary\nos.environ[\"AVIARY_URL\"] = \"<URL>\"\nos.environ[\"AVIARY_TOKEN\"] = \"<TOKEN>\"\nlight = Aviary(model='amazon/LightGPT')\noutput = light('How do you make fried rice?')\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam aviary_token: Optional[str] = None\u00b6\nparam aviary_url: Optional[str] = None\u00b6\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "4c898a7372c0-1", "text": "Metadata to add to the run trace.\nparam model: str = 'amazon/LightGPT'\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam use_prompt_format: bool = True\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\nparam version: Optional[str] = None\u00b6\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "4c898a7372c0-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "4c898a7372c0-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "4c898a7372c0-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "4c898a7372c0-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "4c898a7372c0-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "4c898a7372c0-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "4c898a7372c0-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "4c898a7372c0-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "4c898a7372c0-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "4c898a7372c0-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "4c898a7372c0-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "4c898a7372c0-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.aviary.Aviary.html"}
{"id": "15f86738a3c3-0", "text": "langchain.llms.cohere.acompletion_with_retry\u00b6\nlangchain.llms.cohere.acompletion_with_retry(llm: Cohere, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.acompletion_with_retry.html"}
{"id": "27bb91f30b2e-0", "text": "langchain.llms.cohere.BaseCohere\u00b6\nclass langchain.llms.cohere.BaseCohere[source]\u00b6\nBases: Serializable\nBase class for Cohere models.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cohere_api_key: Optional[str] = None\u00b6\nparam model: Optional[str] = None\u00b6\nModel name to use.\nparam stop: Optional[List[str]] = None\u00b6\nparam streaming: bool = False\u00b6\nWhether to stream the results.\nparam temperature: float = 0.75\u00b6\nA non-negative float that tunes the degree of randomness in generation.\nparam user_agent: str = 'langchain'\u00b6\nIdentifier for the application making the request.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.BaseCohere.html"}
{"id": "27bb91f30b2e-1", "text": "the new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.BaseCohere.html"}
{"id": "27bb91f30b2e-2", "text": "A unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.cohere.BaseCohere.html"}
{"id": "a81f3799e879-0", "text": "langchain.llms.azureml_endpoint.ContentFormatterBase\u00b6\nclass langchain.llms.azureml_endpoint.ContentFormatterBase[source]\u00b6\nTransform request and response of AzureML endpoint to match with\nrequired schema.\nAttributes\naccepts\nThe MIME type of the response data returned from the endpoint\ncontent_type\nThe MIME type of the input data passed to the endpoint\nMethods\n__init__()\nescape_special_characters(prompt)\nEscapes any special characters in prompt\nformat_request_payload(prompt,\u00a0model_kwargs)\nFormats the request body according to the input schema of the model.\nformat_response_payload(output)\nFormats the response body according to the output schema of the model.\n__init__()\u00b6\nstatic escape_special_characters(prompt: str) \u2192 str[source]\u00b6\nEscapes any special characters in prompt\nabstract format_request_payload(prompt: str, model_kwargs: Dict) \u2192 bytes[source]\u00b6\nFormats the request body according to the input schema of\nthe model. Returns bytes or seekable file like object in the\nformat specified in the content_type request header.\nabstract format_response_payload(output: bytes) \u2192 str[source]\u00b6\nFormats the response body according to the output\nschema of the model. Returns the data type that is\nreceived from the response.\nExamples using ContentFormatterBase\u00b6\nAzure ML", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.ContentFormatterBase.html"}
{"id": "eab137140c45-0", "text": "langchain.llms.titan_takeoff.TitanTakeoff\u00b6\nclass langchain.llms.titan_takeoff.TitanTakeoff[source]\u00b6\nBases: LLM\nWrapper around Titan Takeoff APIs.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam base_url: str = 'http://localhost:8000'\u00b6\nSpecifies the baseURL to use for the Titan Takeoff API.\nDefault = http://localhost:8000.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam generate_max_length: int = 128\u00b6\nMaximum generation length. Default = 128.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam no_repeat_ngram_size: int = 0\u00b6\nPrevent repetitions of ngrams of this size. Default = 0 (turned off).\nparam repetition_penalty: float = 1.0\u00b6\nPenalise the generation of tokens that have been generated before.\nSet to > 1 to penalize. Default = 1 (no penalty).\nparam sampling_temperature: float = 1.0\u00b6\nSample with randomness. Bigger temperatures are associated with\nmore randomness and \u2018creativity\u2019. Default = 1.0.\nparam sampling_topk: int = 1\u00b6\nSample predictions from the top K most probable candidates. Default = 1.\nparam sampling_topp: float = 1.0\u00b6\nSample from predictions whose cumulative probability exceeds this value.\nDefault = 1.0.\nparam streaming: bool = False\u00b6\nWhether to stream the output. Default = False.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "eab137140c45-1", "text": "param tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "eab137140c45-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "eab137140c45-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "eab137140c45-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "eab137140c45-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "eab137140c45-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "eab137140c45-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "eab137140c45-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "eab137140c45-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "eab137140c45-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "eab137140c45-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "eab137140c45-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "eab137140c45-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using TitanTakeoff\u00b6\nTitan Takeoff", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.titan_takeoff.TitanTakeoff.html"}
{"id": "34e96fce1a12-0", "text": "langchain_experimental.llms.lmformatenforcer_decoder.import_lmformatenforcer\u00b6\nlangchain_experimental.llms.lmformatenforcer_decoder.import_lmformatenforcer() \u2192 lmformatenforcer[source]\u00b6\nLazily import lmformatenforcer.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.import_lmformatenforcer.html"}
{"id": "c735e3e740ec-0", "text": "langchain.llms.baseten.Baseten\u00b6\nclass langchain.llms.baseten.Baseten[source]\u00b6\nBases: LLM\nBaseten models.\nTo use, you should have the baseten python package installed,\nand run baseten.login() with your Baseten API key.\nThe required model param can be either a model id or model\nversion id. Using a model version ID will result in\nslightly faster invocation.\nAny other model parameters can also\nbe passed in with the format input={model_param: value, \u2026}\nThe Baseten model must accept a dictionary of input with the key\n\u201cprompt\u201d and return a dictionary with a key \u201cdata\u201d which maps\nto a list of response strings.\nExample\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam input: Dict[str, Any] [Optional]\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str [Required]\u00b6\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "c735e3e740ec-1", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "c735e3e740ec-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "c735e3e740ec-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "c735e3e740ec-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "c735e3e740ec-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "c735e3e740ec-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "c735e3e740ec-7", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "c735e3e740ec-8", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "c735e3e740ec-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "c735e3e740ec-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "c735e3e740ec-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "c735e3e740ec-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "c735e3e740ec-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Baseten\u00b6\nBaseten", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.baseten.Baseten.html"}
{"id": "1f81b0e5312a-0", "text": "langchain.llms.anthropic.Anthropic\u00b6\nclass langchain.llms.anthropic.Anthropic[source]\u00b6\nBases: LLM, _AnthropicCommon\nAnthropic large language models.\nTo use, you should have the anthropic python package installed, and the\nenvironment variable ANTHROPIC_API_KEY set with your API key, or pass\nit as a named parameter to the constructor.\nExample\nimport anthropic\nfrom langchain.llms import Anthropic\nmodel = Anthropic(model=\"<model_name>\", anthropic_api_key=\"my-api-key\")\n# Simplest invocation, automatically wrapped with HUMAN_PROMPT\n# and AI_PROMPT.\nresponse = model(\"What are the biggest risks facing humanity?\")\n# Or if you want to use the chat mode, build a few-shot-prompt, or\n# put words in the Assistant's mouth, use HUMAN_PROMPT and AI_PROMPT:\nraw_prompt = \"What are the biggest risks facing humanity?\"\nprompt = f\"{anthropic.HUMAN_PROMPT} {prompt}{anthropic.AI_PROMPT}\"\nresponse = model(prompt)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam AI_PROMPT: Optional[str] = None\u00b6\nparam HUMAN_PROMPT: Optional[str] = None\u00b6\nparam anthropic_api_key: Optional[SecretStr] = None\u00b6\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nparam anthropic_api_url: Optional[str] = None\u00b6\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam count_tokens: Optional[Callable[[str], int]] = None\u00b6\nparam default_request_timeout: Optional[float] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "1f81b0e5312a-1", "text": "param default_request_timeout: Optional[float] = None\u00b6\nTimeout for requests to Anthropic Completion API. Default is 600 seconds.\nparam max_tokens_to_sample: int = 256 (alias 'max_tokens')\u00b6\nDenotes the number of tokens to predict per generation.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str = 'claude-2' (alias 'model_name')\u00b6\nModel name to use.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nparam streaming: bool = False\u00b6\nWhether to stream the results.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = None\u00b6\nA non-negative float that tunes the degree of randomness in generation.\nparam top_k: Optional[int] = None\u00b6\nNumber of most likely tokens to consider at each step.\nparam top_p: Optional[float] = None\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "1f81b0e5312a-2", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "1f81b0e5312a-3", "text": "text generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "1f81b0e5312a-4", "text": "Asynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "1f81b0e5312a-5", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "1f81b0e5312a-6", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\nconvert_prompt(prompt: PromptValue) \u2192 str[source]\u00b6\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "1f81b0e5312a-7", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "1f81b0e5312a-8", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int[source]\u00b6\nCalculate number of tokens.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "1f81b0e5312a-9", "text": "invoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "1f81b0e5312a-10", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "1f81b0e5312a-11", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "1f81b0e5312a-12", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "1f81b0e5312a-13", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.anthropic.Anthropic.html"}
{"id": "ee5a1d7f183f-0", "text": "langchain.llms.openai.OpenAIChat\u00b6\nclass langchain.llms.openai.OpenAIChat[source]\u00b6\nBases: BaseLLM\nOpenAI Chat large language models.\nTo use, you should have the openai python package installed, and the\nenvironment variable OPENAI_API_KEY set with your API key.\nAny parameters that are valid to be passed to the openai.create call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.llms import OpenAIChat\nopenaichat = OpenAIChat(model_name=\"gpt-3.5-turbo\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_special: Union[Literal['all'], AbstractSet[str]] = {}\u00b6\nSet of special tokens that are allowed\u3002\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam disallowed_special: Union[Literal['all'], Collection[str]] = 'all'\u00b6\nSet of special tokens that are not allowed\u3002\nparam max_retries: int = 6\u00b6\nMaximum number of retries to make when generating.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'gpt-3.5-turbo'\u00b6\nModel name to use.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "ee5a1d7f183f-1", "text": "emulator.\nparam openai_api_key: Optional[str] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var OPENAI_API_KEY if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam prefix_messages: List [Optional]\u00b6\nSeries of messages for Chat input.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "ee5a1d7f183f-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "ee5a1d7f183f-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "ee5a1d7f183f-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "ee5a1d7f183f-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "ee5a1d7f183f-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "ee5a1d7f183f-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "ee5a1d7f183f-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int][source]\u00b6\nGet the token IDs using the tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "ee5a1d7f183f-9", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "ee5a1d7f183f-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "ee5a1d7f183f-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "ee5a1d7f183f-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "ee5a1d7f183f-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using OpenAIChat\u00b6\nActiveloop Deep Lake", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAIChat.html"}
{"id": "14d6da678166-0", "text": "langchain.llms.predibase.Predibase\u00b6\nclass langchain.llms.predibase.Predibase[source]\u00b6\nBases: LLM\nUse your Predibase models with Langchain.\nTo use, you should have the predibase python package installed,\nand have your Predibase API key.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str [Required]\u00b6\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nparam predibase_api_key: str [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predibase.Predibase.html"}
{"id": "14d6da678166-1", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predibase.Predibase.html"}
{"id": "14d6da678166-2", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predibase.Predibase.html"}
{"id": "14d6da678166-3", "text": "Use this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predibase.Predibase.html"}
{"id": "14d6da678166-4", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predibase.Predibase.html"}
{"id": "14d6da678166-5", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predibase.Predibase.html"}
{"id": "14d6da678166-6", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predibase.Predibase.html"}
{"id": "14d6da678166-7", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predibase.Predibase.html"}
{"id": "14d6da678166-8", "text": "Parameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predibase.Predibase.html"}
{"id": "14d6da678166-9", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predibase.Predibase.html"}
{"id": "14d6da678166-10", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predibase.Predibase.html"}
{"id": "14d6da678166-11", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predibase.Predibase.html"}
{"id": "14d6da678166-12", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Predibase\u00b6\nPredibase", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predibase.Predibase.html"}
{"id": "6a13c62565f3-0", "text": "langchain.llms.petals.Petals\u00b6\nclass langchain.llms.petals.Petals[source]\u00b6\nBases: LLM\nPetals Bloom models.\nTo use, you should have the petals python package installed, and the\nenvironment variable HUGGINGFACE_API_KEY set with your API key.\nAny parameters that are valid to be passed to the call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.llms import petals\npetals = Petals()\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam client: Any = None\u00b6\nThe client to use for the API calls.\nparam do_sample: bool = True\u00b6\nWhether or not to use sampling; use greedy decoding otherwise.\nparam huggingface_api_key: Optional[str] = None\u00b6\nparam max_length: Optional[int] = None\u00b6\nThe maximum length of the sequence to be generated.\nparam max_new_tokens: int = 256\u00b6\nThe maximum number of new tokens to generate in the completion.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call\nnot explicitly specified.\nparam model_name: str = 'bigscience/bloom-petals'\u00b6\nThe model to use.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use\nparam tokenizer: Any = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "6a13c62565f3-1", "text": "What sampling temperature to use\nparam tokenizer: Any = None\u00b6\nThe tokenizer to use for the API calls.\nparam top_k: Optional[int] = None\u00b6\nThe number of highest probability vocabulary tokens\nto keep for top-k-filtering.\nparam top_p: float = 0.9\u00b6\nThe cumulative probability for top-p sampling.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "6a13c62565f3-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "6a13c62565f3-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "6a13c62565f3-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "6a13c62565f3-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "6a13c62565f3-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "6a13c62565f3-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "6a13c62565f3-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "6a13c62565f3-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "6a13c62565f3-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "6a13c62565f3-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "6a13c62565f3-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "6a13c62565f3-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Petals\u00b6\nPetals", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.petals.Petals.html"}
{"id": "eca685dc96ef-0", "text": "langchain.llms.mlflow_ai_gateway.MlflowAIGateway\u00b6\nclass langchain.llms.mlflow_ai_gateway.MlflowAIGateway[source]\u00b6\nBases: LLM\nWrapper around completions LLMs in the MLflow AI Gateway.\nTo use, you should have the mlflow[gateway] python package installed.\nFor more information, see https://mlflow.org/docs/latest/gateway/index.html.\nExample\nfrom langchain.llms import MlflowAIGateway\ncompletions = MlflowAIGateway(\n    gateway_uri=\"<your-mlflow-ai-gateway-uri>\",\n    route=\"<your-mlflow-ai-gateway-completions-route>\",\n    params={\n        \"temperature\": 0.1\n    }\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam gateway_uri: Optional[str] = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam params: Optional[Params] = None\u00b6\nparam route: str [Required]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "eca685dc96ef-1", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "eca685dc96ef-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "eca685dc96ef-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "eca685dc96ef-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "eca685dc96ef-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "eca685dc96ef-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "eca685dc96ef-7", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "eca685dc96ef-8", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "eca685dc96ef-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "eca685dc96ef-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "eca685dc96ef-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "eca685dc96ef-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "eca685dc96ef-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using MlflowAIGateway\u00b6\nMLflow AI Gateway", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.MlflowAIGateway.html"}
{"id": "f8692fb3149d-0", "text": "langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer\u00b6\nclass langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer[source]\u00b6\nBases: HuggingFacePipeline\nLMFormatEnforcer wrapped LLM using HuggingFace Pipeline API.\nThis pipeline is experimental and not yet stable.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam batch_size: int = 4\u00b6\nBatch size to use when passing multiple documents to generate.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam json_schema: Optional[dict] = None\u00b6\nThe JSON Schema to complete.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_id: str = 'gpt2'\u00b6\nModel name to use.\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments passed to the model.\nparam pipeline_kwargs: Optional[dict] = None\u00b6\nKeyword arguments passed to the pipeline.\nparam regex: Optional[str] = None\u00b6\nThe regular expression to complete.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "f8692fb3149d-1", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "f8692fb3149d-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "f8692fb3149d-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "f8692fb3149d-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "f8692fb3149d-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "f8692fb3149d-6", "text": "dict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_model_id(model_id: str, task: str, device: Optional[int] = - 1, device_map: Optional[str] = None, model_kwargs: Optional[dict] = None, pipeline_kwargs: Optional[dict] = None, batch_size: int = 4, **kwargs: Any) \u2192 HuggingFacePipeline\u00b6\nConstruct the pipeline object from model_id and task.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "f8692fb3149d-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "f8692fb3149d-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "f8692fb3149d-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "f8692fb3149d-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "f8692fb3149d-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "f8692fb3149d-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "f8692fb3149d-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.lmformatenforcer_decoder.LMFormatEnforcer.html"}
{"id": "3ee836c585c9-0", "text": "langchain.llms.predictionguard.PredictionGuard\u00b6\nclass langchain.llms.predictionguard.PredictionGuard[source]\u00b6\nBases: LLM\nPrediction Guard large language models.\nTo use, you should have the predictionguard python package installed, and the\nenvironment variable PREDICTIONGUARD_TOKEN set with your access token, or pass\nit as a named parameter to the constructor. To use Prediction Guard\u2019s API along\nwith OpenAI models, set the environment variable OPENAI_API_KEY with your\nOpenAI API key as well.\nExample\npgllm = PredictionGuard(model=\"MPT-7B-Instruct\",\n                        token=\"my-access-token\",\n                        output={\n                            \"type\": \"boolean\"\n                        })\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam max_tokens: int = 256\u00b6\nDenotes the number of tokens to predict per generation.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: Optional[str] = 'MPT-7B-Instruct'\u00b6\nModel name to use.\nparam output: Optional[Dict[str, Any]] = None\u00b6\nThe output type or structure for controlling the LLM output.\nparam stop: Optional[List[str]] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.75\u00b6\nA non-negative float that tunes the degree of randomness in generation.\nparam token: Optional[str] = None\u00b6\nYour Prediction Guard access token.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "3ee836c585c9-1", "text": "param token: Optional[str] = None\u00b6\nYour Prediction Guard access token.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "3ee836c585c9-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "3ee836c585c9-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "3ee836c585c9-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "3ee836c585c9-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "3ee836c585c9-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "3ee836c585c9-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "3ee836c585c9-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "3ee836c585c9-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "3ee836c585c9-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "3ee836c585c9-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "3ee836c585c9-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "3ee836c585c9-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using PredictionGuard\u00b6\nPrediction Guard", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.predictionguard.PredictionGuard.html"}
{"id": "6fcbd4f912c5-0", "text": "langchain.llms.azureml_endpoint.HFContentFormatter\u00b6\nclass langchain.llms.azureml_endpoint.HFContentFormatter[source]\u00b6\nContent handler for LLMs from the HuggingFace catalog.\nAttributes\naccepts\nThe MIME type of the response data returned from the endpoint\ncontent_type\nThe MIME type of the input data passed to the endpoint\nMethods\n__init__()\nescape_special_characters(prompt)\nEscapes any special characters in prompt\nformat_request_payload(prompt,\u00a0model_kwargs)\nFormats the request body according to the input schema of the model.\nformat_response_payload(output)\nFormats the response body according to the output schema of the model.\n__init__()\u00b6\nstatic escape_special_characters(prompt: str) \u2192 str\u00b6\nEscapes any special characters in prompt\nformat_request_payload(prompt: str, model_kwargs: Dict) \u2192 bytes[source]\u00b6\nFormats the request body according to the input schema of\nthe model. Returns bytes or seekable file like object in the\nformat specified in the content_type request header.\nformat_response_payload(output: bytes) \u2192 str[source]\u00b6\nFormats the response body according to the output\nschema of the model. Returns the data type that is\nreceived from the response.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.HFContentFormatter.html"}
{"id": "a7f028cf9900-0", "text": "langchain.llms.azureml_endpoint.DollyContentFormatter\u00b6\nclass langchain.llms.azureml_endpoint.DollyContentFormatter[source]\u00b6\nContent handler for the Dolly-v2-12b model\nAttributes\naccepts\nThe MIME type of the response data returned from the endpoint\ncontent_type\nThe MIME type of the input data passed to the endpoint\nMethods\n__init__()\nescape_special_characters(prompt)\nEscapes any special characters in prompt\nformat_request_payload(prompt,\u00a0model_kwargs)\nFormats the request body according to the input schema of the model.\nformat_response_payload(output)\nFormats the response body according to the output schema of the model.\n__init__()\u00b6\nstatic escape_special_characters(prompt: str) \u2192 str\u00b6\nEscapes any special characters in prompt\nformat_request_payload(prompt: str, model_kwargs: Dict) \u2192 bytes[source]\u00b6\nFormats the request body according to the input schema of\nthe model. Returns bytes or seekable file like object in the\nformat specified in the content_type request header.\nformat_response_payload(output: bytes) \u2192 str[source]\u00b6\nFormats the response body according to the output\nschema of the model. Returns the data type that is\nreceived from the response.\nExamples using DollyContentFormatter\u00b6\nAzure ML", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.DollyContentFormatter.html"}
{"id": "832c4950f25c-0", "text": "langchain.llms.promptlayer_openai.PromptLayerOpenAIChat\u00b6\nclass langchain.llms.promptlayer_openai.PromptLayerOpenAIChat[source]\u00b6\nBases: OpenAIChat\nWrapper around OpenAI large language models.\nTo use, you should have the openai and promptlayer python\npackage installed, and the environment variable OPENAI_API_KEY\nand PROMPTLAYER_API_KEY set with your openAI API key and\npromptlayer key respectively.\nAll parameters that can be passed to the OpenAIChat LLM can also\nbe passed here. The PromptLayerOpenAIChat adds two optional\nParameters\npl_tags \u2013 List of strings to tag the request with.\nreturn_pl_id \u2013 If True, the PromptLayer request ID will be\nreturned in the generation_info field of the\nGeneration object.\nExample\nfrom langchain.llms import PromptLayerOpenAIChat\nopenaichat = PromptLayerOpenAIChat(model_name=\"gpt-3.5-turbo\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_special: Union[Literal['all'], AbstractSet[str]] = {}\u00b6\nSet of special tokens that are allowed\u3002\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam disallowed_special: Union[Literal['all'], Collection[str]] = 'all'\u00b6\nSet of special tokens that are not allowed\u3002\nparam max_retries: int = 6\u00b6\nMaximum number of retries to make when generating.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "832c4950f25c-1", "text": "param model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'gpt-3.5-turbo'\u00b6\nModel name to use.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Optional[str] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var OPENAI_API_KEY if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam pl_tags: Optional[List[str]] = None\u00b6\nparam prefix_messages: List [Optional]\u00b6\nSeries of messages for Chat input.\nparam return_pl_id: Optional[bool] = False\u00b6\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "832c4950f25c-2", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "832c4950f25c-3", "text": "text generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "832c4950f25c-4", "text": "Asynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "832c4950f25c-5", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "832c4950f25c-6", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "832c4950f25c-7", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "832c4950f25c-8", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nGet the token IDs using the tiktoken package.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "832c4950f25c-9", "text": "Get the token IDs using the tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "832c4950f25c-10", "text": "by calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "832c4950f25c-11", "text": "save(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "832c4950f25c-12", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "832c4950f25c-13", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAIChat.html"}
{"id": "536f7b890692-0", "text": "langchain.llms.base.create_base_retry_decorator\u00b6\nlangchain.llms.base.create_base_retry_decorator(error_types: List[Type[BaseException]], max_retries: int = 1, run_manager: Optional[Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]] = None) \u2192 Callable[[Any], Any][source]\u00b6\nCreate a retry decorator for a given LLM and provided list of error types.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.create_base_retry_decorator.html"}
{"id": "5b6abf4e6121-0", "text": "langchain.llms.openllm.OpenLLM\u00b6\nclass langchain.llms.openllm.OpenLLM[source]\u00b6\nBases: LLM\nOpenLLM, supporting both in-process model\ninstance and remote OpenLLM servers.\nTo use, you should have the openllm library installed:\npip install openllm\nLearn more at: https://github.com/bentoml/openllm\nExample running an LLM model locally managed by OpenLLM:from langchain.llms import OpenLLM\nllm = OpenLLM(\n    model_name='flan-t5',\n    model_id='google/flan-t5-large',\n)\nllm(\"What is the difference between a duck and a goose?\")\nFor all available supported models, you can run \u2018openllm models\u2019.\nIf you have a OpenLLM server running, you can also use it remotely:from langchain.llms import OpenLLM\nllm = OpenLLM(server_url='http://localhost:3000')\nllm(\"What is the difference between a duck and a goose?\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam embedded: bool = True\u00b6\nInitialize this LLM instance in current process by default. Should\nonly set to False when using in conjunction with BentoML Service.\nparam llm_kwargs: Dict[str, Any] [Required]\u00b6\nKeyword arguments to be passed to openllm.LLM\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_id: Optional[str] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "5b6abf4e6121-1", "text": "Metadata to add to the run trace.\nparam model_id: Optional[str] = None\u00b6\nModel Id to use. If not provided, will use the default model for the model name.\nSee \u2018openllm models\u2019 for all available model variants.\nparam model_name: Optional[str] = None\u00b6\nModel name to use. See \u2018openllm models\u2019 for all available models.\nparam server_type: ServerType = 'http'\u00b6\nOptional server type. Either \u2018http\u2019 or \u2018grpc\u2019.\nparam server_url: Optional[str] = None\u00b6\nOptional server URL that currently runs a LLMServer with \u2018openllm start\u2019.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "5b6abf4e6121-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "5b6abf4e6121-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "5b6abf4e6121-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "5b6abf4e6121-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "5b6abf4e6121-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "5b6abf4e6121-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "5b6abf4e6121-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "5b6abf4e6121-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "5b6abf4e6121-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "5b6abf4e6121-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "5b6abf4e6121-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "5b6abf4e6121-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nproperty runner: openllm.LLMRunner\u00b6\nGet the underlying openllm.LLMRunner instance for integration with BentoML.\nExample:\n.. code-block:: python\nllm = OpenLLM(model_name=\u2019flan-t5\u2019,\nmodel_id=\u2019google/flan-t5-large\u2019,\nembedded=False,\n)\ntools = load_tools([\u201cserpapi\u201d, \u201cllm-math\u201d], llm=llm)\nagent = initialize_agent(\ntools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION\n)\nsvc = bentoml.Service(\u201clangchain-openllm\u201d, runners=[llm.runner])\n@svc.api(input=Text(), output=Text())\ndef chat(input_text: str):\nreturn agent.run(input_text)\nExamples using OpenLLM\u00b6\nOpenLLM", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.OpenLLM.html"}
{"id": "8c989646f17c-0", "text": "langchain.llms.forefrontai.ForefrontAI\u00b6\nclass langchain.llms.forefrontai.ForefrontAI[source]\u00b6\nBases: LLM\nForefrontAI large language models.\nTo use, you should have the environment variable FOREFRONTAI_API_KEY\nset with your API key.\nExample\nfrom langchain.llms import ForefrontAI\nforefrontai = ForefrontAI(endpoint_url=\"\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam base_url: Optional[str] = None\u00b6\nBase url to use, if None decides based on model name.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam endpoint_url: str = ''\u00b6\nModel name to use.\nparam forefrontai_api_key: Optional[str] = None\u00b6\nparam length: int = 256\u00b6\nThe maximum number of tokens to generate in the completion.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam repetition_penalty: int = 1\u00b6\nPenalizes repeated tokens according to frequency.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam top_k: int = 40\u00b6\nThe number of highest probability vocabulary tokens to\nkeep for top-k-filtering.\nparam top_p: float = 1.0\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "8c989646f17c-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "8c989646f17c-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "8c989646f17c-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "8c989646f17c-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "8c989646f17c-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "8c989646f17c-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "8c989646f17c-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "8c989646f17c-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "8c989646f17c-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "8c989646f17c-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "8c989646f17c-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "8c989646f17c-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "8c989646f17c-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ForefrontAI\u00b6\nForefrontAI", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.forefrontai.ForefrontAI.html"}
{"id": "7d95d0f9bdd8-0", "text": "langchain.llms.amazon_api_gateway.ContentHandlerAmazonAPIGateway\u00b6\nclass langchain.llms.amazon_api_gateway.ContentHandlerAmazonAPIGateway[source]\u00b6\nAdapter to prepare the inputs from Langchain to a format\nthat LLM model expects.\nIt also provides helper function to extract\nthe generated text from the model response.\nMethods\n__init__()\ntransform_input(prompt,\u00a0model_kwargs)\ntransform_output(response)\n__init__()\u00b6\nclassmethod transform_input(prompt: str, model_kwargs: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nclassmethod transform_output(response: Any) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.amazon_api_gateway.ContentHandlerAmazonAPIGateway.html"}
{"id": "3327ed8f97cd-0", "text": "langchain.llms.pai_eas_endpoint.PaiEasEndpoint\u00b6\nclass langchain.llms.pai_eas_endpoint.PaiEasEndpoint[source]\u00b6\nBases: LLM\nLangchain LLM class to help to access eass llm service.\nTo use this endpoint, must have a deployed eas chat llm service on PAI AliCloud.\nOne can set the environment variable eas_service_url and eas_service_token.\nThe environment variables can set with your eas service url and service token.\nExample\nfrom langchain.llms.pai_eas_endpoint import PaiEasEndpoint\neas_chat_endpoint = PaiEasChatEndpoint(\n    eas_service_url=\"your_service_url\",\n    eas_service_token=\"your_service_token\"\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam eas_service_token: str [Required]\u00b6\nPAI-EAS Service Infer Params\nparam eas_service_url: str [Required]\u00b6\nPAI-EAS Service TOKEN\nparam max_new_tokens: Optional[int] = 512\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Optional[dict] = None\u00b6\nparam stop_sequences: Optional[List[str]] = None\u00b6\nEnable stream chat mode.\nparam streaming: bool = False\u00b6\nKey/value arguments to pass to the model. Reserved for future use\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = 0.95\u00b6\nparam top_k: Optional[int] = 0\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "3327ed8f97cd-1", "text": "param top_k: Optional[int] = 0\u00b6\nparam top_p: Optional[float] = 0.1\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\nparam version: Optional[str] = '2.0'\u00b6\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "3327ed8f97cd-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "3327ed8f97cd-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "3327ed8f97cd-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "3327ed8f97cd-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "3327ed8f97cd-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "3327ed8f97cd-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "3327ed8f97cd-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "3327ed8f97cd-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "3327ed8f97cd-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "3327ed8f97cd-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "3327ed8f97cd-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "3327ed8f97cd-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pai_eas_endpoint.PaiEasEndpoint.html"}
{"id": "5eeeaa0b60d0-0", "text": "langchain.llms.symblai_nebula.completion_with_retry\u00b6\nlangchain.llms.symblai_nebula.completion_with_retry(llm: Nebula, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.symblai_nebula.completion_with_retry.html"}
{"id": "11c2f5e89783-0", "text": "langchain.llms.koboldai.clean_url\u00b6\nlangchain.llms.koboldai.clean_url(url: str) \u2192 str[source]\u00b6\nRemove trailing slash and /api from url if present.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.koboldai.clean_url.html"}
{"id": "1e4880f40f7b-0", "text": "langchain.llms.sagemaker_endpoint.SagemakerEndpoint\u00b6\nclass langchain.llms.sagemaker_endpoint.SagemakerEndpoint[source]\u00b6\nBases: LLM\nSagemaker Inference Endpoint models.\nTo use, you must supply the endpoint name from your deployed\nSagemaker model & the region where it is deployed.\nTo authenticate, the AWS client uses the following methods to\nautomatically load credentials:\nhttps://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\nIf a specific credential profile should be used, you must pass\nthe name of the profile from the ~/.aws/credentials file that is to be used.\nMake sure the credentials / roles used have the required policies to\naccess the Sagemaker endpoint.\nSee: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam client: Any = None\u00b6\nBoto3 client for sagemaker runtime\nparam content_handler: langchain.llms.sagemaker_endpoint.LLMContentHandler [Required]\u00b6\nThe content handler class that provides an input and\noutput transform functions to handle formats between LLM\nand the endpoint.\nparam credentials_profile_name: Optional[str] = None\u00b6\nThe name of the profile in the ~/.aws/credentials or ~/.aws/config files, which\nhas either access keys or role information specified.\nIf not specified, the default credential profile or, if on an EC2 instance,\ncredentials from IMDS will be used.\nSee: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "1e4880f40f7b-1", "text": "See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\nparam endpoint_kwargs: Optional[Dict] = None\u00b6\nOptional attributes passed to the invoke_endpoint\nfunction. See `boto3`_. docs for more info.\n.. _boto3: <https://boto3.amazonaws.com/v1/documentation/api/latest/index.html>\nparam endpoint_name: str = ''\u00b6\nThe name of the endpoint from the deployed Sagemaker model.\nMust be unique within an AWS Region.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Optional[Dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam region_name: str = ''\u00b6\nThe aws region where the Sagemaker model is deployed, eg. us-west-2.\nparam streaming: bool = False\u00b6\nWhether to stream the results.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "1e4880f40f7b-2", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "1e4880f40f7b-3", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "1e4880f40f7b-4", "text": "Use this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "1e4880f40f7b-5", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "1e4880f40f7b-6", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "1e4880f40f7b-7", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "1e4880f40f7b-8", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "1e4880f40f7b-9", "text": "Parameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "1e4880f40f7b-10", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "1e4880f40f7b-11", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "1e4880f40f7b-12", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "1e4880f40f7b-13", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.SagemakerEndpoint.html"}
{"id": "0fbc1e22704e-0", "text": "langchain.llms.vertexai.VertexAIModelGarden\u00b6\nclass langchain.llms.vertexai.VertexAIModelGarden[source]\u00b6\nBases: _VertexAIBase, BaseLLM\nLarge language models served from Vertex AI Model Garden.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_model_args: Optional[List[str]] = None\u00b6\nAllowed optional args to be passed to the model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam endpoint_id: str [Required]\u00b6\nA name of an endpoint where the model has been deployed.\nparam location: str = 'us-central1'\u00b6\nThe default location to use when making API calls.\nparam max_retries: int = 6\u00b6\nThe maximum number of retries to make when generating.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_name: Optional[str] = None\u00b6\nUnderlying model name.\nparam project: Optional[str] = None\u00b6\nThe default GCP project to use when making Vertex API calls.\nparam prompt_arg: str = 'prompt'\u00b6\nparam request_parallelism: int = 5\u00b6\nThe amount of parallelism allowed for requests issued to VertexAI models.\nparam result_arg: str = 'generated_text'\u00b6\nparam stop: Optional[List[str]] = None\u00b6\nOptional list of stop words to use when generating.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "0fbc1e22704e-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "0fbc1e22704e-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "0fbc1e22704e-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "0fbc1e22704e-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "0fbc1e22704e-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "0fbc1e22704e-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "0fbc1e22704e-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "0fbc1e22704e-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "0fbc1e22704e-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "0fbc1e22704e-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "0fbc1e22704e-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "0fbc1e22704e-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "0fbc1e22704e-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\ntask_executor: ClassVar[Optional[Executor]] = FieldInfo(exclude=True, extra={})\u00b6\nExamples using VertexAIModelGarden\u00b6\nGoogle Vertex AI PaLM", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAIModelGarden.html"}
{"id": "6a5f39b35657-0", "text": "langchain.llms.deepsparse.DeepSparse\u00b6\nclass langchain.llms.deepsparse.DeepSparse[source]\u00b6\nBases: LLM\nNeural Magic DeepSparse LLM interface.\nTo use, you should have the deepsparse or deepsparse-nightly\npython package installed. See https://github.com/neuralmagic/deepsparse\nThis interface let\u2019s you deploy optimized LLMs straight from the\n[SparseZoo](https://sparsezoo.neuralmagic.com/?useCase=text_generation)\n.. rubric:: Example\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam generation_config: Union[None, str, Dict] = None\u00b6\nGenerationConfig dictionary consisting of parameters used to control\nsequences generated for each prompt. Common parameters are:\nmax_length, max_new_tokens, num_return_sequences, output_scores,\ntop_p, top_k, repetition_penalty.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str [Required]\u00b6\nThe path to a model file or directory or the name of a SparseZoo model stub.\nparam model_config: Optional[Dict[str, Any]] = None\u00b6\nKeyword arguments passed to the pipeline construction.\nCommon parameters are sequence_length, prompt_sequence_length\nparam streaming: bool = False\u00b6\nWhether to stream the results, token by token.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "6a5f39b35657-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "6a5f39b35657-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "6a5f39b35657-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "6a5f39b35657-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "6a5f39b35657-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "6a5f39b35657-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "6a5f39b35657-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "6a5f39b35657-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "6a5f39b35657-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "6a5f39b35657-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "6a5f39b35657-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "6a5f39b35657-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "6a5f39b35657-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using DeepSparse\u00b6\nDeepSparse", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepsparse.DeepSparse.html"}
{"id": "30a9a2265349-0", "text": "langchain.llms.clarifai.Clarifai\u00b6\nclass langchain.llms.clarifai.Clarifai[source]\u00b6\nBases: LLM\nClarifai large language models.\nTo use, you should have an account on the Clarifai platform,\nthe clarifai python package installed, and the\nenvironment variable CLARIFAI_PAT set with your PAT key,\nor pass it as a named parameter to the constructor.\nExample\nfrom langchain.llms import Clarifai\nclarifai_llm = Clarifai(pat=CLARIFAI_PAT,                 user_id=USER_ID, app_id=APP_ID, model_id=MODEL_ID)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_base: str = 'https://api.clarifai.com'\u00b6\nparam app_id: Optional[str] = None\u00b6\nClarifai application id to use.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_id: Optional[str] = None\u00b6\nModel id to use.\nparam model_version_id: Optional[str] = None\u00b6\nModel version id to use.\nparam pat: Optional[str] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam userDataObject: Any = None\u00b6\nparam user_id: Optional[str] = None\u00b6\nClarifai user id to use.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "30a9a2265349-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "30a9a2265349-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "30a9a2265349-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "30a9a2265349-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "30a9a2265349-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "30a9a2265349-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "30a9a2265349-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "30a9a2265349-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "30a9a2265349-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "30a9a2265349-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "30a9a2265349-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "30a9a2265349-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "30a9a2265349-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Clarifai\u00b6\nClarifai", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.clarifai.Clarifai.html"}
{"id": "f0115ec36bb1-0", "text": "langchain.llms.utils.enforce_stop_tokens\u00b6\nlangchain.llms.utils.enforce_stop_tokens(text: str, stop: List[str]) \u2192 str[source]\u00b6\nCut off the text as soon as any stop words occur.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.utils.enforce_stop_tokens.html"}
{"id": "3b9e7845dcfd-0", "text": "langchain.llms.javelin_ai_gateway.JavelinAIGateway\u00b6\nclass langchain.llms.javelin_ai_gateway.JavelinAIGateway[source]\u00b6\nBases: LLM\nJavelin AI Gateway LLMs.\nTo use, you should have the javelin_sdk python package installed.\nFor more information, see https://docs.getjavelin.io\nExample\nfrom langchain.llms import JavelinAIGateway\ncompletions = JavelinAIGateway(\n    gateway_uri=\"<your-javelin-ai-gateway-uri>\",\n    route=\"<your-javelin-ai-gateway-completions-route>\",\n    params={\n        \"temperature\": 0.1\n    }\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam client: Optional[Any] = None\u00b6\nThe Javelin AI Gateway client.\nparam gateway_uri: Optional[str] = None\u00b6\nThe URI of the Javelin AI Gateway API.\nparam javelin_api_key: Optional[str] = None\u00b6\nThe API key for the Javelin AI Gateway API.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam params: Optional[Params] = None\u00b6\nParameters for the Javelin AI Gateway API.\nparam route: str [Required]\u00b6\nThe route to use for the Javelin AI Gateway API.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "3b9e7845dcfd-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "3b9e7845dcfd-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "3b9e7845dcfd-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "3b9e7845dcfd-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "3b9e7845dcfd-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "3b9e7845dcfd-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "3b9e7845dcfd-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "3b9e7845dcfd-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "3b9e7845dcfd-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "3b9e7845dcfd-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "3b9e7845dcfd-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "3b9e7845dcfd-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "3b9e7845dcfd-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.javelin_ai_gateway.JavelinAIGateway.html"}
{"id": "ba0c60d8d3ea-0", "text": "langchain.llms.google_palm.GooglePalm\u00b6\nclass langchain.llms.google_palm.GooglePalm[source]\u00b6\nBases: BaseLLM, BaseModel\nGoogle PaLM models.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam google_api_key: Optional[str] = None\u00b6\nparam max_output_tokens: Optional[int] = None\u00b6\nMaximum number of tokens to include in a candidate. Must be greater than zero.\nIf unset, will default to 64.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_name: str = 'models/text-bison-001'\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nNumber of chat completions to generate for each prompt. Note that the API may\nnot return the full n completions if duplicates are generated.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nRun inference with this temperature. Must by in the closed interval\n[0.0, 1.0].\nparam top_k: Optional[int] = None\u00b6\nDecode using top-k sampling: consider the set of top_k most probable tokens.\nMust be positive.\nparam top_p: Optional[float] = None\u00b6\nDecode using nucleus sampling: consider the smallest set of tokens whose\nprobability sum is at least top_p. Must be in the closed interval [0.0, 1.0].\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "ba0c60d8d3ea-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "ba0c60d8d3ea-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "ba0c60d8d3ea-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "ba0c60d8d3ea-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "ba0c60d8d3ea-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "ba0c60d8d3ea-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "ba0c60d8d3ea-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "ba0c60d8d3ea-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "ba0c60d8d3ea-9", "text": "The output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "ba0c60d8d3ea-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "ba0c60d8d3ea-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "ba0c60d8d3ea-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "ba0c60d8d3ea-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.google_palm.GooglePalm.html"}
{"id": "a937f2ab323d-0", "text": "langchain.llms.vertexai.VertexAI\u00b6\nclass langchain.llms.vertexai.VertexAI[source]\u00b6\nBases: _VertexAICommon, BaseLLM\nGoogle Vertex AI large language models.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam credentials: Any = None\u00b6\nThe default custom credentials (google.auth.credentials.Credentials) to use\nparam location: str = 'us-central1'\u00b6\nThe default location to use when making API calls.\nparam max_output_tokens: int = 128\u00b6\nToken limit determines the maximum amount of text output from one prompt.\nparam max_retries: int = 6\u00b6\nThe maximum number of retries to make when generating.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_name: str = 'text-bison'\u00b6\nThe name of the Vertex AI large language model.\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam project: Optional[str] = None\u00b6\nThe default GCP project to use when making Vertex API calls.\nparam request_parallelism: int = 5\u00b6\nThe amount of parallelism allowed for requests issued to VertexAI models.\nparam stop: Optional[List[str]] = None\u00b6\nOptional list of stop words to use when generating.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.0\u00b6\nSampling temperature, it controls the degree of randomness in token selection.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "a937f2ab323d-1", "text": "Sampling temperature, it controls the degree of randomness in token selection.\nparam top_k: int = 40\u00b6\nHow the model selects tokens for output, the next token is selected from\nparam top_p: float = 0.95\u00b6\nTokens are selected from most probable to least until the sum of their\nparam tuned_model_name: Optional[str] = None\u00b6\nThe name of a tuned model. If provided, model_name is ignored.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "a937f2ab323d-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "a937f2ab323d-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "a937f2ab323d-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "a937f2ab323d-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "a937f2ab323d-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "a937f2ab323d-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "a937f2ab323d-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int[source]\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "a937f2ab323d-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "a937f2ab323d-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "a937f2ab323d-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "a937f2ab323d-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "a937f2ab323d-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty is_codey_model: bool\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\ntask_executor: ClassVar[Optional[Executor]] = FieldInfo(exclude=True, extra={})\u00b6\nExamples using VertexAI\u00b6\nGoogle Vertex AI PaLM", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.VertexAI.html"}
{"id": "60931656dc0f-0", "text": "langchain.llms.fireworks.acompletion_with_retry\u00b6\nasync langchain.llms.fireworks.acompletion_with_retry(llm: Fireworks, use_retry: bool, *, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.acompletion_with_retry.html"}
{"id": "a017e346fe55-0", "text": "langchain.llms.mlflow_ai_gateway.Params\u00b6\nclass langchain.llms.mlflow_ai_gateway.Params[source]\u00b6\nBases: BaseModel\nParameters for the MLflow AI Gateway LLM.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam candidate_count: int = 1\u00b6\nThe number of candidates to return.\nparam max_tokens: Optional[int] = None\u00b6\nparam stop: Optional[List[str]] = None\u00b6\nparam temperature: float = 0.0\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.Params.html"}
{"id": "a017e346fe55-1", "text": "deep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.Params.html"}
{"id": "a017e346fe55-2", "text": "classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.mlflow_ai_gateway.Params.html"}
{"id": "c2de4c43b5e1-0", "text": "langchain.llms.llamacpp.LlamaCpp\u00b6\nclass langchain.llms.llamacpp.LlamaCpp[source]\u00b6\nBases: LLM\nllama.cpp model.\nTo use, you should have the llama-cpp-python library installed, and provide the\npath to the Llama model as a named parameter to the constructor.\nCheck out: https://github.com/abetlen/llama-cpp-python\nExample\nfrom langchain.llms import LlamaCpp\nllm = LlamaCpp(model_path=\"/path/to/llama/model\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam echo: Optional[bool] = False\u00b6\nWhether to echo the prompt.\nparam f16_kv: bool = True\u00b6\nUse half-precision for key/value cache.\nparam grammar: Optional[Union[str, LlamaGrammar]] = None\u00b6\ngrammar: formal grammar for constraining model outputs. For instance, the grammar\ncan be used to force the model to generate valid JSON or to speak exclusively in\nemojis. At most one of grammar_path and grammar should be passed in.\nparam grammar_path: Optional[Union[str, Path]] = None\u00b6\ngrammar_path: Path to the .gbnf file that defines formal grammars\nfor constraining model outputs. For instance, the grammar can be used\nto force the model to generate valid JSON or to speak exclusively in emojis. At most\none of grammar_path and grammar should be passed in.\nparam last_n_tokens_size: Optional[int] = 64\u00b6\nThe number of tokens to look back when applying the repeat_penalty.\nparam logits_all: bool = False\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-1", "text": "param logits_all: bool = False\u00b6\nReturn logits for all tokens, not just the last token.\nparam logprobs: Optional[int] = None\u00b6\nThe number of logprobs to return. If None, no logprobs are returned.\nparam lora_base: Optional[str] = None\u00b6\nThe path to the Llama LoRA base model.\nparam lora_path: Optional[str] = None\u00b6\nThe path to the Llama LoRA. If None, no LoRa is loaded.\nparam max_tokens: Optional[int] = 256\u00b6\nThe maximum number of tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nAny additional parameters to pass to llama_cpp.Llama.\nparam model_path: str [Required]\u00b6\nThe path to the Llama model file.\nparam n_batch: Optional[int] = 8\u00b6\nNumber of tokens to process in parallel.\nShould be a number between 1 and n_ctx.\nparam n_ctx: int = 512\u00b6\nToken context window.\nparam n_gpu_layers: Optional[int] = None\u00b6\nNumber of layers to be loaded into gpu memory. Default None.\nparam n_parts: int = -1\u00b6\nNumber of parts to split the model into.\nIf -1, the number of parts is automatically determined.\nparam n_threads: Optional[int] = None\u00b6\nNumber of threads to use.\nIf None, the number of threads is automatically determined.\nparam repeat_penalty: Optional[float] = 1.1\u00b6\nThe penalty to apply to repeated tokens.\nparam rope_freq_base: float = 10000.0\u00b6\nBase frequency for rope sampling.\nparam rope_freq_scale: float = 1.0\u00b6\nScale factor for rope sampling.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-2", "text": "param rope_freq_scale: float = 1.0\u00b6\nScale factor for rope sampling.\nparam seed: int = -1\u00b6\nSeed. If -1, a random seed is used.\nparam stop: Optional[List[str]] = []\u00b6\nA list of strings to stop generation when encountered.\nparam streaming: bool = True\u00b6\nWhether to stream the results, token by token.\nparam suffix: Optional[str] = None\u00b6\nA suffix to append to the generated text. If None, no suffix is appended.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = 0.8\u00b6\nThe temperature to use for sampling.\nparam top_k: Optional[int] = 40\u00b6\nThe top-k value to use for sampling.\nparam top_p: Optional[float] = 0.95\u00b6\nThe top-p value to use for sampling.\nparam use_mlock: bool = False\u00b6\nForce system to keep model in RAM.\nparam use_mmap: Optional[bool] = True\u00b6\nWhether to keep the model loaded in RAM\nparam verbose: bool = True\u00b6\nPrint verbose output to stderr.\nparam vocab_only: bool = False\u00b6\nOnly load the vocabulary, no weights.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-3", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-4", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-5", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-6", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-7", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-8", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-9", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int[source]\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-10", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-11", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-12", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-13", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-14", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "c2de4c43b5e1-15", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using LlamaCpp\u00b6\nLlama.cpp\nRun LLMs locally\nSet env var OPENAI_API_KEY or load from a .env file\nUse local LLMs\nWebResearchRetriever", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.llamacpp.LlamaCpp.html"}
{"id": "08901c9d408e-0", "text": "langchain.llms.base.LLM\u00b6\nclass langchain.llms.base.LLM[source]\u00b6\nBases: BaseLLM\nBase LLM abstract class.\nThe purpose of this class is to expose a simpler interface for working\nwith LLMs, rather than expect the user to implement the full _generate method.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[langchain.schema.callbacks.base.BaseCallbackManager] = None\u00b6\nparam callbacks: Optional[Union[List[langchain.schema.callbacks.base.BaseCallbackHandler], langchain.schema.callbacks.base.BaseCallbackManager]] = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.LLM.html"}
{"id": "08901c9d408e-1", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.LLM.html"}
{"id": "08901c9d408e-2", "text": "first occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.LLM.html"}
{"id": "08901c9d408e-3", "text": "Parameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.LLM.html"}
{"id": "08901c9d408e-4", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.LLM.html"}
{"id": "08901c9d408e-5", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.LLM.html"}
{"id": "08901c9d408e-6", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.LLM.html"}
{"id": "08901c9d408e-7", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.LLM.html"}
{"id": "08901c9d408e-8", "text": "Parameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.LLM.html"}
{"id": "08901c9d408e-9", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.LLM.html"}
{"id": "08901c9d408e-10", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.LLM.html"}
{"id": "08901c9d408e-11", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.LLM.html"}
{"id": "08901c9d408e-12", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using LLM\u00b6\nCustom LLM", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.LLM.html"}
{"id": "d99a087c6844-0", "text": "langchain.llms.deepinfra.DeepInfra\u00b6\nclass langchain.llms.deepinfra.DeepInfra[source]\u00b6\nBases: LLM\nDeepInfra models.\nTo use, you should have the environment variable DEEPINFRA_API_TOKEN\nset with your API token, or pass it as a named parameter to the\nconstructor.\nOnly supports text-generation and text2text-generation for now.\nExample\nfrom langchain.llms import DeepInfra\ndi = DeepInfra(model_id=\"google/flan-t5-xl\",\n                    deepinfra_api_token=\"my-api-key\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam deepinfra_api_token: Optional[str] = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_id: str = 'google/flan-t5-xl'\u00b6\nparam model_kwargs: Optional[Dict] = None\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "d99a087c6844-1", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "d99a087c6844-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "d99a087c6844-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "d99a087c6844-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "d99a087c6844-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "d99a087c6844-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "d99a087c6844-7", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "d99a087c6844-8", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "d99a087c6844-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "d99a087c6844-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "d99a087c6844-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "d99a087c6844-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "d99a087c6844-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using DeepInfra\u00b6\nDeepInfra", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.deepinfra.DeepInfra.html"}
{"id": "76b3ec910532-0", "text": "langchain.llms.fireworks.acompletion_with_retry_batching\u00b6\nasync langchain.llms.fireworks.acompletion_with_retry_batching(llm: Fireworks, use_retry: bool, *, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.acompletion_with_retry_batching.html"}
{"id": "729cab65e107-0", "text": "langchain_experimental.llms.anthropic_functions.TagParser\u00b6\nclass langchain_experimental.llms.anthropic_functions.TagParser[source]\u00b6\nA heavy-handed solution, but it\u2019s fast for prototyping.\nMight be re-implemented later to restrict scope to the limited grammar, and\nmore efficiency.\nUses an HTML parser to parse a limited grammar that allows\nfor syntax of the form:\nINPUT -> JUNK? VALUE*\nJUNK -> JUNK_CHARACTER+\nJUNK_CHARACTER -> whitespace | ,\nVALUE -> <IDENTIFIER>DATA</IDENTIFIER> | OBJECT\nOBJECT -> <IDENTIFIER>VALUE+</IDENTIFIER>\nIDENTIFIER -> [a-Z][a-Z0-9_]*\nDATA -> .*\nInterprets the data to allow repetition of tags and recursion\nto support representation of complex types.\n^ Just another approximately wrong grammar specification.\nAttributes\nCDATA_CONTENT_ELEMENTS\nMethods\n__init__()\nA heavy-handed solution, but it's fast for prototyping.\ncheck_for_whole_start_tag(i)\nclear_cdata_mode()\nclose()\nHandle any buffered data.\nfeed(data)\nFeed data to the parser.\nget_starttag_text()\nReturn full source of start tag: '<...>'.\ngetpos()\nReturn current line number and offset.\ngoahead(end)\nhandle_charref(name)\nhandle_comment(data)\nhandle_data(data)\nHook when handling data.\nhandle_decl(decl)\nhandle_endtag(tag)\nHook when a tag is closed.\nhandle_entityref(name)\nhandle_pi(data)\nhandle_startendtag(tag,\u00a0attrs)\nhandle_starttag(tag,\u00a0attrs)\nHook when a new tag is encountered.\nparse_bogus_comment(i[,\u00a0report])\nparse_comment(i[,\u00a0report])\nparse_declaration(i)\nparse_endtag(i)\nparse_html_declaration(i)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.TagParser.html"}
{"id": "729cab65e107-1", "text": "parse_declaration(i)\nparse_endtag(i)\nparse_html_declaration(i)\nparse_marked_section(i[,\u00a0report])\nparse_pi(i)\nparse_starttag(i)\nreset()\nReset this instance.\nset_cdata_mode(elem)\nunknown_decl(data)\nupdatepos(i,\u00a0j)\n__init__() \u2192 None[source]\u00b6\nA heavy-handed solution, but it\u2019s fast for prototyping.\nMight be re-implemented later to restrict scope to the limited grammar, and\nmore efficiency.\nUses an HTML parser to parse a limited grammar that allows\nfor syntax of the form:\nINPUT -> JUNK? VALUE*\nJUNK -> JUNK_CHARACTER+\nJUNK_CHARACTER -> whitespace | ,\nVALUE -> <IDENTIFIER>DATA</IDENTIFIER> | OBJECT\nOBJECT -> <IDENTIFIER>VALUE+</IDENTIFIER>\nIDENTIFIER -> [a-Z][a-Z0-9_]*\nDATA -> .*\nInterprets the data to allow repetition of tags and recursion\nto support representation of complex types.\n^ Just another approximately wrong grammar specification.\ncheck_for_whole_start_tag(i)\u00b6\nclear_cdata_mode()\u00b6\nclose()\u00b6\nHandle any buffered data.\nfeed(data)\u00b6\nFeed data to the parser.\nCall this as often as you want, with as little or as much text\nas you want (may include \u2018n\u2019).\nget_starttag_text()\u00b6\nReturn full source of start tag: \u2018<\u2026>\u2019.\ngetpos()\u00b6\nReturn current line number and offset.\ngoahead(end)\u00b6\nhandle_charref(name)\u00b6\nhandle_comment(data)\u00b6\nhandle_data(data: str) \u2192 None[source]\u00b6\nHook when handling data.\nhandle_decl(decl)\u00b6\nhandle_endtag(tag: str) \u2192 None[source]\u00b6\nHook when a tag is closed.\nhandle_entityref(name)\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.TagParser.html"}
{"id": "729cab65e107-2", "text": "Hook when a tag is closed.\nhandle_entityref(name)\u00b6\nhandle_pi(data)\u00b6\nhandle_startendtag(tag, attrs)\u00b6\nhandle_starttag(tag: str, attrs: Any) \u2192 None[source]\u00b6\nHook when a new tag is encountered.\nparse_bogus_comment(i, report=1)\u00b6\nparse_comment(i, report=1)\u00b6\nparse_declaration(i)\u00b6\nparse_endtag(i)\u00b6\nparse_html_declaration(i)\u00b6\nparse_marked_section(i, report=1)\u00b6\nparse_pi(i)\u00b6\nparse_starttag(i)\u00b6\nreset()\u00b6\nReset this instance.  Loses all unprocessed data.\nset_cdata_mode(elem)\u00b6\nunknown_decl(data)\u00b6\nupdatepos(i, j)\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.anthropic_functions.TagParser.html"}
{"id": "b95e605181f3-0", "text": "langchain.llms.openllm.IdentifyingParams\u00b6\nclass langchain.llms.openllm.IdentifyingParams[source]\u00b6\nParameters for identifying a model as a typed dict.\nmodel_name: str\u00b6\nmodel_id: Optional[str]\u00b6\nserver_url: Optional[str]\u00b6\nserver_type: Optional[Literal['http', 'grpc']]\u00b6\nembedded: bool\u00b6\nllm_kwargs: Dict[str, Any]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openllm.IdentifyingParams.html"}
{"id": "21f9ea84acea-0", "text": "langchain.llms.bananadev.Banana\u00b6\nclass langchain.llms.bananadev.Banana[source]\u00b6\nBases: LLM\nBanana large language models.\nTo use, you should have the banana-dev python package installed,\nand the environment variable BANANA_API_KEY set with your API key.\nThis is the team API key available in the Banana dashboard.\nAny parameters that are valid to be passed to the call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.llms import Banana\nbanana = Banana(model_key=\"\", model_url_slug=\"\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam banana_api_key: Optional[str] = None\u00b6\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_key: str = ''\u00b6\nmodel key to use\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not\nexplicitly specified.\nparam model_url_slug: str = ''\u00b6\nmodel endpoint to use\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "21f9ea84acea-1", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "21f9ea84acea-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "21f9ea84acea-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "21f9ea84acea-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "21f9ea84acea-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "21f9ea84acea-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "21f9ea84acea-7", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "21f9ea84acea-8", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "21f9ea84acea-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "21f9ea84acea-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "21f9ea84acea-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "21f9ea84acea-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "21f9ea84acea-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Banana\u00b6\nBanana", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bananadev.Banana.html"}
{"id": "f646ec599be7-0", "text": "langchain.llms.openai.OpenAI\u00b6\nclass langchain.llms.openai.OpenAI[source]\u00b6\nBases: BaseOpenAI\nOpenAI large language models.\nTo use, you should have the openai python package installed, and the\nenvironment variable OPENAI_API_KEY set with your API key.\nAny parameters that are valid to be passed to the openai.create call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.llms import OpenAI\nopenai = OpenAI(model_name=\"text-davinci-003\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_special: Union[Literal['all'], AbstractSet[str]] = {}\u00b6\nSet of special tokens that are allowed\u3002\nparam batch_size: int = 20\u00b6\nBatch size to use when passing multiple documents to generate.\nparam best_of: int = 1\u00b6\nGenerates best_of completions server-side and returns the \u201cbest\u201d.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam default_headers: Union[Mapping[str, str], None] = None\u00b6\nparam default_query: Union[Mapping[str, object], None] = None\u00b6\nparam disallowed_special: Union[Literal['all'], Collection[str]] = 'all'\u00b6\nSet of special tokens that are not allowed\u3002\nparam frequency_penalty: float = 0\u00b6\nPenalizes repeated tokens according to frequency.\nparam http_client: Union[Any, None] = None\u00b6\nOptional httpx.Client.\nparam logit_bias: Optional[Dict[str, float]] [Optional]\u00b6\nAdjust the probability of specific tokens being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-1", "text": "Adjust the probability of specific tokens being generated.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: int = 256\u00b6\nThe maximum number of tokens to generate in the completion.\n-1 returns as many tokens as possible given the prompt and\nthe models maximal context size.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'text-davinci-003' (alias 'model')\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Optional[str] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var OPENAI_API_KEY if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6\nparam presence_penalty: float = 0\u00b6\nPenalizes repeated tokens.\nparam request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-2", "text": "param tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nparam top_p: float = 1\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-3", "text": "The default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-4", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-5", "text": "Use this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-6", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_llm_result(choices: Any, prompts: List[str], token_usage: Dict[str, int], *, system_fingerprint: Optional[str] = None) \u2192 LLMResult\u00b6\nCreate the LLMResult from the choices and prompts.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-8", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-9", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-10", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_sub_prompts(params: Dict[str, Any], prompts: List[str], stop: Optional[List[str]] = None) \u2192 List[List[str]]\u00b6\nGet the sub prompts for llm call.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nGet the token IDs using the tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-11", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nmax_tokens_for_prompt(prompt: str) \u2192 int\u00b6\nCalculate the maximum number of tokens possible to generate for a prompt.\nParameters\nprompt \u2013 The prompt to pass into the model.\nReturns\nThe maximum number of tokens to generate for a prompt.\nExample\nmax_tokens = openai.max_token_for_prompt(\"Tell me a joke.\")\nstatic modelname_to_contextsize(modelname: str) \u2192 int\u00b6\nCalculate the maximum number of tokens possible to generate for a model.\nParameters\nmodelname \u2013 The modelname we want to know the context size for.\nReturns\nThe maximum context size\nExample\nmax_tokens = openai.modelname_to_contextsize(\"text-davinci-003\")", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-12", "text": "max_tokens = openai.modelname_to_contextsize(\"text-davinci-003\")\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-13", "text": "to the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-14", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-15", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty max_context_size: int\u00b6\nGet max context size for this model.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using OpenAI\u00b6\nCohere Reranker\nGoogle Serper\nHuman as a tool\nOpenWeatherMap\nSearch Tools\nZapier Natural Language Actions\nGradio\nSceneXplain\nDall-E Image Generator\nEntity Memory with SQLite storage\nStreamlit Chat Message History\nConfident\nLLMonitor\nLabel Studio\nArgilla\nPromptLayer\nStreamlit\nInfino\nComet\nAim\nWeights & Biases\nSageMaker Tracking", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-16", "text": "Infino\nComet\nAim\nWeights & Biases\nSageMaker Tracking\nOpenAI\nRebuff\nMLflow\nHelicone\nShale Protocol\nWhyLabs\nWandB Tracing\nClearML\nRay Serve\nLog, Trace, and Monitor\nPortkey\nChat Over Documents with Vectara\nVectara Text Generation\nCSV\nXorbits\nJira\nSpark Dataframe\nPython\nSQL Database\nNatural Language APIs\nJSON\nGithub\nPandas Dataframe\nOpenAPI\nGitlab\nVectara\nPsychic\nDocugami\nAmazon Textract \nOpaquePrompts\nLLM Caching integrations\nFallbacks\nRemoving logical fallacies from model output\nSet env var OPENAI_API_KEY or load from a .env file:\nPerform context-aware text splitting\nRetrieve from vector stores directly\nRetrieve as you generate with FLARE\nImprove document indexing with HyDE\nQA using Activeloop\u2019s DeepLake\nGraph QA\nTree of Thought (ToT) example\nHuggingGPT\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\nAgent Debates with Tools\nBash chain\nLLM Symbolic Math \nSummarization checker chain\nSelf-checking chain\nSet env var OPENAI_API_KEY or load from a .env file\nVector SQL Retriever with MyScale\nSQL\nMilvus\nWeaviate\nElasticsearch\nChroma\nPinecone\nSupabase\nRedis\nMyScale\nDeep Lake\nQdrant\nLost in the middle: The problem with long contexts\nMemory in the Multi-Input Chain\nMemory in LLMChain\nMultiple Memory classes\nCustomizing Conversational Memory\nConversation Knowledge Graph\nConversation Token Buffer\nConversation Summary Buffer\nMultiple callback handlers\nToken counting\nLogging to file\nMulti-Input Tools\nDefining Custom Tools\nTool Input Schema\nHuman-in-the-loop Tool Validation", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "f646ec599be7-17", "text": "Defining Custom Tools\nTool Input Schema\nHuman-in-the-loop Tool Validation\nCombine agents and vector stores\nAccess intermediate steps\nTimeouts for agents\nStreaming final agent output\nCap the max number of iterations\nAsync API\nTracking token usage\nSerialization\nRetry parser\nDatetime parser\nPydantic (JSON) parser\nRouter\nTransformation\nAdding moderation", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.openai.OpenAI.html"}
{"id": "cf14e2a818fd-0", "text": "langchain.llms.chatglm.ChatGLM\u00b6\nclass langchain.llms.chatglm.ChatGLM[source]\u00b6\nBases: LLM\nChatGLM LLM service.\nExample\nfrom langchain.llms import ChatGLM\nendpoint_url = (\n    \"http://127.0.0.1:8000\"\n)\nChatGLM_llm = ChatGLM(\n    endpoint_url=endpoint_url\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam endpoint_url: str = 'http://127.0.0.1:8000/'\u00b6\nEndpoint URL to use.\nparam history: List[List] = []\u00b6\nHistory of the conversation\nparam max_token: int = 20000\u00b6\nMax token allowed to pass to the model.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.1\u00b6\nLLM model temperature from 0 to 10.\nparam top_p: float = 0.7\u00b6\nTop P for nucleus sampling from 0 to 1\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\nparam with_history: bool = False\u00b6\nWhether to use history or not", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "cf14e2a818fd-1", "text": "param with_history: bool = False\u00b6\nWhether to use history or not\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "cf14e2a818fd-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "cf14e2a818fd-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "cf14e2a818fd-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "cf14e2a818fd-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "cf14e2a818fd-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "cf14e2a818fd-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "cf14e2a818fd-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "cf14e2a818fd-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "cf14e2a818fd-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "cf14e2a818fd-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "cf14e2a818fd-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "cf14e2a818fd-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using ChatGLM\u00b6\nChatGLM", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.chatglm.ChatGLM.html"}
{"id": "24987967aa20-0", "text": "langchain_experimental.llms.jsonformer_decoder.JsonFormer\u00b6\nclass langchain_experimental.llms.jsonformer_decoder.JsonFormer[source]\u00b6\nBases: HuggingFacePipeline\nJsonformer wrapped LLM using HuggingFace Pipeline API.\nThis pipeline is experimental and not yet stable.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam batch_size: int = 4\u00b6\nBatch size to use when passing multiple documents to generate.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam debug: bool = False\u00b6\nDebug mode.\nparam json_schema: dict [Required]\u00b6\nThe JSON Schema to complete.\nparam max_new_tokens: int = 200\u00b6\nMaximum number of new tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_id: str = 'gpt2'\u00b6\nModel name to use.\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments passed to the model.\nparam pipeline_kwargs: Optional[dict] = None\u00b6\nKeyword arguments passed to the pipeline.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "24987967aa20-1", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "24987967aa20-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "24987967aa20-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "24987967aa20-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "24987967aa20-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "24987967aa20-6", "text": "dict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_model_id(model_id: str, task: str, device: Optional[int] = - 1, device_map: Optional[str] = None, model_kwargs: Optional[dict] = None, pipeline_kwargs: Optional[dict] = None, batch_size: int = 4, **kwargs: Any) \u2192 HuggingFacePipeline\u00b6\nConstruct the pipeline object from model_id and task.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "24987967aa20-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "24987967aa20-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "24987967aa20-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "24987967aa20-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "24987967aa20-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "24987967aa20-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "24987967aa20-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.jsonformer_decoder.JsonFormer.html"}
{"id": "a69c2c1fa0e2-0", "text": "langchain.llms.writer.Writer\u00b6\nclass langchain.llms.writer.Writer[source]\u00b6\nBases: LLM\nWriter large language models.\nTo use, you should have the environment variable WRITER_API_KEY and\nWRITER_ORG_ID set with your API key and organization ID respectively.\nExample\nfrom langchain.llms import Writer\nwriter = Writer(model_id=\"palmyra-base\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam base_url: Optional[str] = None\u00b6\nBase url to use, if None decides based on model name.\nparam best_of: Optional[int] = None\u00b6\nGenerates this many completions server-side and returns the \u201cbest\u201d.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam logprobs: bool = False\u00b6\nWhether to return log probabilities.\nparam max_tokens: Optional[int] = None\u00b6\nMaximum number of tokens to generate.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam min_tokens: Optional[int] = None\u00b6\nMinimum number of tokens to generate.\nparam model_id: str = 'palmyra-instruct'\u00b6\nModel name to use.\nparam n: Optional[int] = None\u00b6\nHow many completions to generate.\nparam presence_penalty: Optional[float] = None\u00b6\nPenalizes repeated tokens regardless of frequency.\nparam repetition_penalty: Optional[float] = None\u00b6\nPenalizes repeated tokens according to frequency.\nparam stop: Optional[List[str]] = None\u00b6\nSequences when completion generation will stop.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "a69c2c1fa0e2-1", "text": "param tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = None\u00b6\nWhat sampling temperature to use.\nparam top_p: Optional[float] = None\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\nparam writer_api_key: Optional[str] = None\u00b6\nWriter API key.\nparam writer_org_id: Optional[str] = None\u00b6\nWriter organization ID.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "a69c2c1fa0e2-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "a69c2c1fa0e2-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "a69c2c1fa0e2-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "a69c2c1fa0e2-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "a69c2c1fa0e2-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "a69c2c1fa0e2-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "a69c2c1fa0e2-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "a69c2c1fa0e2-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "a69c2c1fa0e2-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "a69c2c1fa0e2-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "a69c2c1fa0e2-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "a69c2c1fa0e2-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Writer\u00b6\nWriter", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.writer.Writer.html"}
{"id": "6e25aa6fd3d9-0", "text": "langchain.llms.fireworks.conditional_decorator\u00b6\nlangchain.llms.fireworks.conditional_decorator(condition: bool, decorator: Callable[[Any], Any]) \u2192 Callable[[Any], Any][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.conditional_decorator.html"}
{"id": "d872b61439aa-0", "text": "langchain.llms.ctransformers.CTransformers\u00b6\nclass langchain.llms.ctransformers.CTransformers[source]\u00b6\nBases: LLM\nC Transformers LLM models.\nTo use, you should have the ctransformers python package installed.\nSee https://github.com/marella/ctransformers\nExample\nfrom langchain.llms import CTransformers\nllm = CTransformers(model=\"/path/to/ggml-gpt-2.bin\", model_type=\"gpt2\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam config: Optional[Dict[str, Any]] = None\u00b6\nThe config parameters.\nSee https://github.com/marella/ctransformers#config\nparam lib: Optional[str] = None\u00b6\nThe path to a shared library or one of avx2, avx, basic.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str [Required]\u00b6\nThe path to a model file or directory or the name of a Hugging Face Hub\nmodel repo.\nparam model_file: Optional[str] = None\u00b6\nThe name of the model file in repo or directory.\nparam model_type: Optional[str] = None\u00b6\nThe model type.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "d872b61439aa-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "d872b61439aa-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "d872b61439aa-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "d872b61439aa-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "d872b61439aa-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "d872b61439aa-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "d872b61439aa-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "d872b61439aa-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "d872b61439aa-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "d872b61439aa-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "d872b61439aa-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "d872b61439aa-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "d872b61439aa-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using CTransformers\u00b6\nC Transformers", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctransformers.CTransformers.html"}
{"id": "a8109838f8aa-0", "text": "langchain.llms.promptlayer_openai.PromptLayerOpenAI\u00b6\nclass langchain.llms.promptlayer_openai.PromptLayerOpenAI[source]\u00b6\nBases: OpenAI\nPromptLayer OpenAI large language models.\nTo use, you should have the openai and promptlayer python\npackage installed, and the environment variable OPENAI_API_KEY\nand PROMPTLAYER_API_KEY set with your openAI API key and\npromptlayer key respectively.\nAll parameters that can be passed to the OpenAI LLM can also\nbe passed here. The PromptLayerOpenAI LLM adds two optional\nParameters\npl_tags \u2013 List of strings to tag the request with.\nreturn_pl_id \u2013 If True, the PromptLayer request ID will be\nreturned in the generation_info field of the\nGeneration object.\nExample\nfrom langchain.llms import PromptLayerOpenAI\nopenai = PromptLayerOpenAI(model_name=\"text-davinci-003\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allowed_special: Union[Literal['all'], AbstractSet[str]] = {}\u00b6\nSet of special tokens that are allowed\u3002\nparam async_client: Any = None\u00b6\nparam batch_size: int = 20\u00b6\nBatch size to use when passing multiple documents to generate.\nparam best_of: int = 1\u00b6\nGenerates best_of completions server-side and returns the \u201cbest\u201d.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam client: Any = None\u00b6\nparam default_headers: Union[Mapping[str, str], None] = None\u00b6\nparam default_query: Union[Mapping[str, object], None] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-1", "text": "param default_query: Union[Mapping[str, object], None] = None\u00b6\nparam disallowed_special: Union[Literal['all'], Collection[str]] = 'all'\u00b6\nSet of special tokens that are not allowed\u3002\nparam frequency_penalty: float = 0\u00b6\nPenalizes repeated tokens according to frequency.\nparam http_client: Union[Any, None] = None\u00b6\nOptional httpx.Client.\nparam logit_bias: Optional[Dict[str, float]] [Optional]\u00b6\nAdjust the probability of specific tokens being generated.\nparam max_retries: int = 2\u00b6\nMaximum number of retries to make when generating.\nparam max_tokens: int = 256\u00b6\nThe maximum number of tokens to generate in the completion.\n-1 returns as many tokens as possible given the prompt and\nthe models maximal context size.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not explicitly specified.\nparam model_name: str = 'text-davinci-003' (alias 'model')\u00b6\nModel name to use.\nparam n: int = 1\u00b6\nHow many completions to generate for each prompt.\nparam openai_api_base: Optional[str] = None (alias 'base_url')\u00b6\nBase URL path for API requests, leave blank if not using a proxy or service\nemulator.\nparam openai_api_key: Optional[str] = None (alias 'api_key')\u00b6\nAutomatically inferred from env var OPENAI_API_KEY if not provided.\nparam openai_organization: Optional[str] = None (alias 'organization')\u00b6\nAutomatically inferred from env var OPENAI_ORG_ID if not provided.\nparam openai_proxy: Optional[str] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-2", "text": "param openai_proxy: Optional[str] = None\u00b6\nparam pl_tags: Optional[List[str]] = None\u00b6\nparam presence_penalty: float = 0\u00b6\nPenalizes repeated tokens.\nparam request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')\u00b6\nTimeout for requests to OpenAI completion API. Can be float, httpx.Timeout or\nNone.\nparam return_pl_id: Optional[bool] = False\u00b6\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.7\u00b6\nWhat sampling temperature to use.\nparam tiktoken_model_name: Optional[str] = None\u00b6\nThe model name to pass to tiktoken when using this class.\nTiktoken is used to count the number of tokens in documents to constrain\nthem to be under a certain limit. By default, when set to None, this will\nbe the same as the embedding model name. However, there are some cases\nwhere you may want to use this Embedding class with a model name not\nsupported by tiktoken. This can include when using Azure embeddings or\nwhen using one of the many model providers that expose an OpenAI-like\nAPI but with different models. In those cases, in order to avoid erroring\nwhen tiktoken is called, you can specify a model name to use here.\nparam top_p: float = 1\u00b6\nTotal probability mass of tokens to consider at each step.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-3", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-4", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-5", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-6", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-7", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-8", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_llm_result(choices: Any, prompts: List[str], token_usage: Dict[str, int], *, system_fingerprint: Optional[str] = None) \u2192 LLMResult\u00b6\nCreate the LLMResult from the choices and prompts.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-9", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-10", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_sub_prompts(params: Dict[str, Any], prompts: List[str], stop: Optional[List[str]] = None) \u2192 List[List[str]]\u00b6\nGet the sub prompts for llm call.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nGet the token IDs using the tiktoken package.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-11", "text": "config \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nmax_tokens_for_prompt(prompt: str) \u2192 int\u00b6\nCalculate the maximum number of tokens possible to generate for a prompt.\nParameters\nprompt \u2013 The prompt to pass into the model.\nReturns\nThe maximum number of tokens to generate for a prompt.\nExample\nmax_tokens = openai.max_token_for_prompt(\"Tell me a joke.\")", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-12", "text": "Example\nmax_tokens = openai.max_token_for_prompt(\"Tell me a joke.\")\nstatic modelname_to_contextsize(modelname: str) \u2192 int\u00b6\nCalculate the maximum number of tokens possible to generate for a model.\nParameters\nmodelname \u2013 The modelname we want to know the context size for.\nReturns\nThe maximum context size\nExample\nmax_tokens = openai.modelname_to_contextsize(\"text-davinci-003\")\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-13", "text": "Parameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-14", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "a8109838f8aa-15", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict[str, Any]\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty max_context_size: int\u00b6\nGet max context size for this model.\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using PromptLayerOpenAI\u00b6\nPromptLayer\nPromptLayer OpenAI", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.promptlayer_openai.PromptLayerOpenAI.html"}
{"id": "35eecd157f80-0", "text": "langchain.llms.replicate.Replicate\u00b6\nclass langchain.llms.replicate.Replicate[source]\u00b6\nBases: LLM\nReplicate models.\nTo use, you should have the replicate python package installed,\nand the environment variable REPLICATE_API_TOKEN set with your API token.\nYou can find your token here: https://replicate.com/account\nThe model param is required, but any other model parameters can also\nbe passed in with the format model_kwargs={model_param: value, \u2026}\nExample\nfrom langchain.llms import Replicate\nreplicate = Replicate(\n    model=(\n        \"stability-ai/stable-diffusion: \"\n        \"27b93a2413e7f36cd83da926f3656280b2931564ff050bf9575f1fdf9bcd7478\",\n    ),\n    model_kwargs={\"image_dimensions\": \"512x512\"}\n)\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str [Required]\u00b6\nparam model_kwargs: Dict[str, Any] [Optional] (alias 'input')\u00b6\nparam prompt_key: Optional[str] = None\u00b6\nparam replicate_api_token: Optional[str] = None\u00b6\nparam stop: List[str] [Optional]\u00b6\nStop sequences to early-terminate generation.\nparam streaming: bool = False\u00b6\nWhether to stream the results.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "35eecd157f80-1", "text": "param tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\nparam version_obj: Any = None\u00b6\nOptionally pass in the model version object during initialization to avoid\nhaving to make an extra API call to retrieve it during streaming. NOTE: not\nserializable, is excluded from serialization.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "35eecd157f80-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "35eecd157f80-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "35eecd157f80-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "35eecd157f80-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "35eecd157f80-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "35eecd157f80-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "35eecd157f80-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "35eecd157f80-9", "text": "The output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "35eecd157f80-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "35eecd157f80-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "35eecd157f80-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "35eecd157f80-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Replicate\u00b6\nReplicate", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.replicate.Replicate.html"}
{"id": "95eb0036ea29-0", "text": "langchain.llms.yandex.YandexGPT\u00b6\nclass langchain.llms.yandex.YandexGPT[source]\u00b6\nBases: _BaseYandexGPT, LLM\nYandex large language models.\nTo use, you should have the yandexcloud python package installed.\nThere are two authentication options for the service account\nwith the ai.languageModels.user role:\nYou can specify the token in a constructor parameter iam_token\nor in an environment variable YC_IAM_TOKEN.\n- You can specify the key in a constructor parameter api_key\nor in an environment variable YC_API_KEY.\nExample\nfrom langchain.llms import YandexGPT\nyandex_gpt = YandexGPT(iam_token=\"t1.9eu...\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_key: str = ''\u00b6\nYandex Cloud Api Key for service account\nwith the ai.languageModels.user role\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam iam_token: str = ''\u00b6\nYandex Cloud IAM token for service account\nwith the ai.languageModels.user role\nparam max_tokens: int = 7400\u00b6\nSets the maximum limit on the total number of tokens\nused for both the input prompt and the generated response.\nMust be greater than zero and not exceed 7400 tokens.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_name: str = 'general'\u00b6\nModel name to use.\nparam stop: Optional[List[str]] = None\u00b6\nSequences when completion generation will stop.\nparam tags: Optional[List[str]] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "95eb0036ea29-1", "text": "Sequences when completion generation will stop.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: float = 0.6\u00b6\nWhat sampling temperature to use.\nShould be a double number between 0 (inclusive) and 1 (inclusive).\nparam url: str = 'llm.api.cloud.yandex.net:443'\u00b6\nThe url of the API.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "95eb0036ea29-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "95eb0036ea29-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "95eb0036ea29-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "95eb0036ea29-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "95eb0036ea29-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "95eb0036ea29-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "95eb0036ea29-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "95eb0036ea29-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "95eb0036ea29-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "95eb0036ea29-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "95eb0036ea29-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "95eb0036ea29-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.yandex.YandexGPT.html"}
{"id": "2cafb08a6ad9-0", "text": "langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference\u00b6\nclass langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference[source]\u00b6\nBases: LLM\nHuggingFace text generation API.\nTo use, you should have the text-generation python package installed and\na text-generation server running.\nExample\n# Basic Example (no streaming)\nllm = HuggingFaceTextGenInference(\n    inference_server_url=\"http://localhost:8010/\",\n    max_new_tokens=512,\n    top_k=10,\n    top_p=0.95,\n    typical_p=0.95,\n    temperature=0.01,\n    repetition_penalty=1.03,\n)\nprint(llm(\"What is Deep Learning?\"))\n# Streaming response example\nfrom langchain.callbacks import streaming_stdout\ncallbacks = [streaming_stdout.StreamingStdOutCallbackHandler()]\nllm = HuggingFaceTextGenInference(\n    inference_server_url=\"http://localhost:8010/\",\n    max_new_tokens=512,\n    top_k=10,\n    top_p=0.95,\n    typical_p=0.95,\n    temperature=0.01,\n    repetition_penalty=1.03,\n    callbacks=callbacks,\n    streaming=True\n)\nprint(llm(\"What is Deep Learning?\"))\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam async_client: Any = None\u00b6\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam client: Any = None\u00b6\nparam do_sample: bool = False\u00b6\nActivate logits sampling", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-1", "text": "param do_sample: bool = False\u00b6\nActivate logits sampling\nparam inference_server_url: str = ''\u00b6\ntext-generation-inference instance base url\nparam max_new_tokens: int = 512\u00b6\nMaximum number of generated tokens\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for call not explicitly specified\nparam repetition_penalty: Optional[float] = None\u00b6\nThe parameter for repetition penalty. 1.0 means no penalty.\nSee [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.\nparam return_full_text: bool = False\u00b6\nWhether to prepend the prompt to the generated text\nparam seed: Optional[int] = None\u00b6\nRandom sampling seed\nparam server_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any text-generation-inference server parameters not explicitly specified\nparam stop_sequences: List[str] [Optional]\u00b6\nStop generating tokens if a member of stop_sequences is generated\nparam streaming: bool = False\u00b6\nWhether to generate a stream of tokens asynchronously\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temperature: Optional[float] = 0.8\u00b6\nThe value used to module the logits distribution.\nparam timeout: int = 120\u00b6\nTimeout in seconds\nparam top_k: Optional[int] = None\u00b6\nThe number of highest probability vocabulary tokens to keep for\ntop-k-filtering.\nparam top_p: Optional[float] = 0.95\u00b6\nIf set to < 1, only the smallest set of most probable tokens with probabilities\nthat add up to top_p or higher are kept for generation.\nparam truncate: Optional[int] = None\u00b6\nTruncate inputs tokens to the given size", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-2", "text": "param truncate: Optional[int] = None\u00b6\nTruncate inputs tokens to the given size\nparam typical_p: Optional[float] = 0.95\u00b6\nTypical Decoding mass. See [Typical Decoding for Natural Language\nGeneration](https://arxiv.org/abs/2202.00666) for more information.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\nparam watermark: bool = False\u00b6\nWatermarking with [A Watermark for Large Language Models]\n(https://arxiv.org/abs/2301.10226)\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-3", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-4", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-5", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-6", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-7", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-8", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-9", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-10", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-11", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-12", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-13", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "2cafb08a6ad9-14", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using HuggingFaceTextGenInference\u00b6\nHuggingface TextGen Inference", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.huggingface_text_gen_inference.HuggingFaceTextGenInference.html"}
{"id": "cce49921704a-0", "text": "langchain.llms.azureml_endpoint.LlamaContentFormatter\u00b6\nclass langchain.llms.azureml_endpoint.LlamaContentFormatter[source]\u00b6\nContent formatter for LLaMa\nAttributes\naccepts\nThe MIME type of the response data returned from the endpoint\ncontent_type\nThe MIME type of the input data passed to the endpoint\nMethods\n__init__()\nescape_special_characters(prompt)\nEscapes any special characters in prompt\nformat_request_payload(prompt,\u00a0model_kwargs)\nFormats the request according to the chosen api\nformat_response_payload(output)\nFormats response\n__init__()\u00b6\nstatic escape_special_characters(prompt: str) \u2192 str\u00b6\nEscapes any special characters in prompt\nformat_request_payload(prompt: str, model_kwargs: Dict) \u2192 bytes[source]\u00b6\nFormats the request according to the chosen api\nformat_response_payload(output: bytes) \u2192 str[source]\u00b6\nFormats response\nExamples using LlamaContentFormatter\u00b6\nAzureML Chat Online Endpoint", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.LlamaContentFormatter.html"}
{"id": "525b43da5bba-0", "text": "langchain.llms.sagemaker_endpoint.LineIterator\u00b6\nclass langchain.llms.sagemaker_endpoint.LineIterator(stream: Any)[source]\u00b6\nA helper class for parsing the byte stream input.\nThe output of the model will be in the following format:\nb\u2019{\u201coutputs\u201d: [\u201d a\u201d]}\n\u2018b\u2019{\u201coutputs\u201d: [\u201d challenging\u201d]}\n\u2018b\u2019{\u201coutputs\u201d: [\u201d problem\u201d]}\n\u2018\u2026\nWhile usually each PayloadPart event from the event stream will\ncontain a byte array with a full json, this is not guaranteed\nand some of the json objects may be split acrossPayloadPart events.\nFor example:\n{\u2018PayloadPart\u2019: {\u2018Bytes\u2019: b\u2019{\u201coutputs\u201d: \u2018}}\n{\u2018PayloadPart\u2019: {\u2018Bytes\u2019: b\u2019[\u201d problem\u201d]}\n\u2018}}\nThis class accounts for this by concatenating bytes written via the \u2018write\u2019 function\nand then exposing a method which will return lines (ending with a \u2018\n\u2018 character)within the buffer via the \u2018scan_lines\u2019 function.\nIt maintains the position of the last read position to ensure\nthat previous bytes are not exposed again.\nFor more details see:\nhttps://aws.amazon.com/blogs/machine-learning/elevating-the-generative-ai-experience-introducing-streaming-support-in-amazon-sagemaker-hosting/\nMethods\n__init__(stream)\n__init__(stream: Any) \u2192 None[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.sagemaker_endpoint.LineIterator.html"}
{"id": "180798377838-0", "text": "langchain.llms.pipelineai.PipelineAI\u00b6\nclass langchain.llms.pipelineai.PipelineAI[source]\u00b6\nBases: LLM, BaseModel\nPipelineAI large language models.\nTo use, you should have the pipeline-ai python package installed,\nand the environment variable PIPELINE_API_KEY set with your API key.\nAny parameters that are valid to be passed to the call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.llms import PipelineAI\npipeline = PipelineAI(pipeline_key=\"\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam pipeline_api_key: Optional[str] = None\u00b6\nparam pipeline_key: str = ''\u00b6\nThe id or tag of the target pipeline\nparam pipeline_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any pipeline parameters valid for create call not\nexplicitly specified.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "180798377838-1", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "180798377838-2", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "180798377838-3", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "180798377838-4", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "180798377838-5", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "180798377838-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "180798377838-7", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "180798377838-8", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "180798377838-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "180798377838-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "180798377838-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "180798377838-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "180798377838-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using PipelineAI\u00b6\nPipelineAI", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.pipelineai.PipelineAI.html"}
{"id": "147d1ac83cfa-0", "text": "langchain.llms.databricks.get_default_api_token\u00b6\nlangchain.llms.databricks.get_default_api_token() \u2192 str[source]\u00b6\nGets the default Databricks personal access token.\nRaises an error if the token cannot be automatically determined.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.get_default_api_token.html"}
{"id": "ec234dbaa88e-0", "text": "langchain.llms.tongyi.generate_with_retry\u00b6\nlangchain.llms.tongyi.generate_with_retry(llm: Tongyi, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.tongyi.generate_with_retry.html"}
{"id": "09674692c137-0", "text": "langchain.llms.xinference.Xinference\u00b6\nclass langchain.llms.xinference.Xinference[source]\u00b6\nBases: LLM\nWrapper for accessing Xinference\u2019s large-scale model inference service.\nTo use, you should have the xinference library installed:\npip install \"xinference[all]\"\nCheck out: https://github.com/xorbitsai/inference\nTo run, you need to start a Xinference supervisor on one server and Xinference workers on the other servers\nExample\nTo start a local instance of Xinference, run\n$ xinference\nYou can also deploy Xinference in a distributed cluster. Here are the steps:\nStarting the supervisor:\n$ xinference-supervisor\nStarting the worker:\n$ xinference-worker\nThen, launch a model using command line interface (CLI).\nExample:\n$ xinference launch -n orca -s 3 -q q4_0\nIt will return a model UID. Then, you can use Xinference with LangChain.\nExample:\nfrom langchain.llms import Xinference\nllm = Xinference(\n    server_url=\"http://0.0.0.0:9997\",\n    model_uid = {model_uid} # replace model_uid with the model UID return from launching the model\n)\nllm(\n    prompt=\"Q: where can we visit in the capital of France? A:\",\n    generate_config={\"max_tokens\": 1024, \"stream\": True},\n)\nTo view all the supported builtin models, run:\n$ xinference list --all\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "09674692c137-1", "text": "param callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam client: Any = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Required]\u00b6\nKeyword arguments to be passed to xinference.LLM\nparam model_uid: Optional[str] = None\u00b6\nUID of the launched model\nparam server_url: Optional[str] = None\u00b6\nURL of the xinference server\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "09674692c137-2", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "09674692c137-3", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "09674692c137-4", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "09674692c137-5", "text": "input is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "09674692c137-6", "text": "Behaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "09674692c137-7", "text": "Pass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "09674692c137-8", "text": "For example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "09674692c137-9", "text": "Transform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "09674692c137-10", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "09674692c137-11", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "09674692c137-12", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "09674692c137-13", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Xinference\u00b6\nXorbits Inference (Xinference)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.xinference.Xinference.html"}
{"id": "d26a797910e6-0", "text": "langchain.llms.ctranslate2.CTranslate2\u00b6\nclass langchain.llms.ctranslate2.CTranslate2[source]\u00b6\nBases: BaseLLM\nCTranslate2 language model.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam compute_type: Union[str, Dict[str, str]] = 'default'\u00b6\nModel computation type or a dictionary mapping a device name to the computation type\n(possible values are: default, auto, int8, int8_float32, int8_float16,\nint8_bfloat16, int16, float16, bfloat16, float32).\nparam ctranslate2_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for ctranslate2.Generator call not\nexplicitly specified.\nparam device: str = 'cpu'\u00b6\nDevice to use (possible values are: cpu, cuda, auto).\nparam device_index: Union[int, List[int]] = 0\u00b6\nDevice IDs where to place this generator on.\nparam max_length: int = 512\u00b6\nMaximum generation length.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_path: str = ''\u00b6\nPath to the CTranslate2 model directory.\nparam sampling_temperature: float = 1\u00b6\nSampling temperature to generate more random samples.\nparam sampling_topk: int = 1\u00b6\nRandomly sample predictions from the top K candidates.\nparam sampling_topp: float = 1\u00b6\nKeep the most probable tokens whose cumulative probability exceeds this value.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "d26a797910e6-1", "text": "Keep the most probable tokens whose cumulative probability exceeds this value.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam tokenizer_name: str = ''\u00b6\nName of the original Hugging Face model needed to load the proper tokenizer.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "d26a797910e6-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "d26a797910e6-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "d26a797910e6-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "d26a797910e6-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "d26a797910e6-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "d26a797910e6-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "d26a797910e6-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "d26a797910e6-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "d26a797910e6-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "d26a797910e6-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "d26a797910e6-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "d26a797910e6-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using CTranslate2\u00b6\nCTranslate2", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.ctranslate2.CTranslate2.html"}
{"id": "67944cc350cc-0", "text": "langchain.llms.databricks.Databricks\u00b6\nclass langchain.llms.databricks.Databricks[source]\u00b6\nBases: LLM\nDatabricks serving endpoint or a cluster driver proxy app for LLM.\nIt supports two endpoint types:\nServing endpoint (recommended for both production and development).\nWe assume that an LLM was registered and deployed to a serving endpoint.\nTo wrap it as an LLM you must have \u201cCan Query\u201d permission to the endpoint.\nSet endpoint_name accordingly and do not set cluster_id and\ncluster_driver_port.\nThe expected model signature is:\ninputs:\n[{\"name\": \"prompt\", \"type\": \"string\"},\n {\"name\": \"stop\", \"type\": \"list[string]\"}]\noutputs: [{\"type\": \"string\"}]\nCluster driver proxy app (recommended for interactive development).\nOne can load an LLM on a Databricks interactive cluster and start a local HTTP\nserver on the driver node to serve the model at / using HTTP POST method\nwith JSON input/output.\nPlease use a port number between [3000, 8000] and let the server listen to\nthe driver IP address or simply 0.0.0.0 instead of localhost only.\nTo wrap it as an LLM you must have \u201cCan Attach To\u201d permission to the cluster.\nSet cluster_id and cluster_driver_port and do not set endpoint_name.\nThe expected server schema (using JSON schema) is:\ninputs:\n{\"type\": \"object\",\n \"properties\": {\n    \"prompt\": {\"type\": \"string\"},\n    \"stop\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}},\n \"required\": [\"prompt\"]}`\noutputs: {\"type\": \"string\"}\nIf the endpoint model signature is different or you want to set extra params,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-1", "text": "If the endpoint model signature is different or you want to set extra params,\nyou can use transform_input_fn and transform_output_fn to apply necessary\ntransformations before and after the query.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam api_token: str [Optional]\u00b6\nDatabricks personal access token.\nIf not provided, the default value is determined by\nthe DATABRICKS_TOKEN environment variable if present, or\nan automatically generated temporary token if running inside a Databricks\nnotebook attached to an interactive cluster in \u201csingle user\u201d or\n\u201cno isolation shared\u201d mode.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam cluster_driver_port: Optional[str] = None\u00b6\nThe port number used by the HTTP server running on the cluster driver node.\nThe server should listen on the driver IP address or simply 0.0.0.0 to connect.\nWe recommend the server using a port number between [3000, 8000].\nparam cluster_id: Optional[str] = None\u00b6\nID of the cluster if connecting to a cluster driver proxy app.\nIf neither endpoint_name nor cluster_id is not provided and the code runs\ninside a Databricks notebook attached to an interactive cluster in \u201csingle user\u201d\nor \u201cno isolation shared\u201d mode, the current cluster ID is used as default.\nYou must not set both endpoint_name and cluster_id.\nparam endpoint_name: Optional[str] = None\u00b6\nName of the model serving endpoint.\nYou must specify the endpoint name to connect to a model serving endpoint.\nYou must not set both endpoint_name and cluster_id.\nparam host: str [Optional]\u00b6\nDatabricks workspace hostname.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-2", "text": "param host: str [Optional]\u00b6\nDatabricks workspace hostname.\nIf not provided, the default value is determined by\nthe DATABRICKS_HOST environment variable if present, or\nthe hostname of the current Databricks workspace if running inside\na Databricks notebook attached to an interactive cluster in \u201csingle user\u201d\nor \u201cno isolation shared\u201d mode.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Optional[Dict[str, Any]] = None\u00b6\nExtra parameters to pass to the endpoint.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam transform_input_fn: Optional[Callable] = None\u00b6\nA function that transforms {prompt, stop, **kwargs} into a JSON-compatible\nrequest object that the endpoint accepts.\nFor example, you can apply a prompt template to the input prompt.\nparam transform_output_fn: Optional[Callable[[...], str]] = None\u00b6\nA function that transforms the output from the endpoint to the generated text.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-3", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-4", "text": "text generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-5", "text": "Asynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-6", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-7", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-8", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-9", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-10", "text": "Parameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-11", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-12", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-13", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "67944cc350cc-14", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Databricks\u00b6\nDatabricks", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.databricks.Databricks.html"}
{"id": "8872550373c8-0", "text": "langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM\u00b6\nclass langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM[source]\u00b6\nBases: SelfHostedPipeline\nHuggingFace Pipeline API to run on self-hosted remote hardware.\nSupported hardware includes auto-launched instances on AWS, GCP, Azure,\nand Lambda, as well as servers specified\nby IP address and SSH credentials (such as on-prem, or another cloud\nlike Paperspace, Coreweave, etc.).\nTo use, you should have the runhouse python package installed.\nOnly supports text-generation, text2text-generation and summarization for now.\nExample using from_model_id:from langchain.llms import SelfHostedHuggingFaceLLM\nimport runhouse as rh\ngpu = rh.cluster(name=\"rh-a10x\", instance_type=\"A100:1\")\nhf = SelfHostedHuggingFaceLLM(\n    model_id=\"google/flan-t5-large\", task=\"text2text-generation\",\n    hardware=gpu\n)\nExample passing fn that generates a pipeline (bc the pipeline is not serializable):from langchain.llms import SelfHostedHuggingFaceLLM\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, pipeline\nimport runhouse as rh\ndef get_pipeline():\n    model_id = \"gpt2\"\n    tokenizer = AutoTokenizer.from_pretrained(model_id)\n    model = AutoModelForCausalLM.from_pretrained(model_id)\n    pipe = pipeline(\n        \"text-generation\", model=model, tokenizer=tokenizer\n    )\n    return pipe\nhf = SelfHostedHuggingFaceLLM(\n    model_load_fn=get_pipeline, model_id=\"gpt2\", hardware=gpu)\nConstruct the pipeline remotely using an auxiliary function.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-1", "text": "Construct the pipeline remotely using an auxiliary function.\nThe load function needs to be importable to be imported\nand run on the server, i.e. in a module and not a REPL or closure.\nThen, initialize the remote inference function.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam device: int = 0\u00b6\nDevice to use for inference. -1 for CPU, 0 for GPU, 1 for second GPU, etc.\nparam hardware: Any = None\u00b6\nRemote hardware to send the inference function to.\nparam inference_fn: Callable = <function _generate_text>\u00b6\nInference function to send to the remote hardware.\nparam load_fn_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model load function.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_id: str = 'gpt2'\u00b6\nHugging Face model_id to load the model.\nparam model_kwargs: Optional[dict] = None\u00b6\nKeyword arguments to pass to the model.\nparam model_load_fn: Callable = <function _load_transformer>\u00b6\nFunction to load the model remotely on the server.\nparam model_reqs: List[str] = ['./', 'transformers', 'torch']\u00b6\nRequirements to install on hardware to inference the model.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam task: str = 'text-generation'\u00b6\nHugging Face task (\u201ctext-generation\u201d, \u201ctext2text-generation\u201d or\n\u201csummarization\u201d).\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-2", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-3", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-4", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-5", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-6", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-7", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod from_pipeline(pipeline: Any, hardware: Any, model_reqs: Optional[List[str]] = None, device: int = 0, **kwargs: Any) \u2192 LLM\u00b6\nInit the SelfHostedPipeline from a pipeline object or string.\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-8", "text": "API.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-9", "text": "get_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-10", "text": "The config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-11", "text": "classmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-12", "text": ".. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-13", "text": "Add fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "8872550373c8-14", "text": "Bind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using SelfHostedHuggingFaceLLM\u00b6\nRunhouse", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.self_hosted_hugging_face.SelfHostedHuggingFaceLLM.html"}
{"id": "c9f36f9d3ae5-0", "text": "langchain.llms.azureml_endpoint.OSSContentFormatter\u00b6\nclass langchain.llms.azureml_endpoint.OSSContentFormatter[source]\u00b6\nDeprecated: Kept for backwards compatibility\nContent handler for LLMs from the OSS catalog.\nAttributes\naccepts\nThe MIME type of the response data returned from the endpoint\ncontent_formatter\ncontent_type\nThe MIME type of the input data passed to the endpoint\nMethods\n__init__()\nescape_special_characters(prompt)\nEscapes any special characters in prompt\nformat_request_payload(prompt,\u00a0model_kwargs)\nFormats the request body according to the input schema of the model.\nformat_response_payload(output)\nFormats the response body according to the output schema of the model.\n__init__() \u2192 None[source]\u00b6\nstatic escape_special_characters(prompt: str) \u2192 str\u00b6\nEscapes any special characters in prompt\nformat_request_payload(prompt: str, model_kwargs: Dict) \u2192 bytes\u00b6\nFormats the request body according to the input schema of\nthe model. Returns bytes or seekable file like object in the\nformat specified in the content_type request header.\nformat_response_payload(output: bytes) \u2192 str\u00b6\nFormats the response body according to the output\nschema of the model. Returns the data type that is\nreceived from the response.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.OSSContentFormatter.html"}
{"id": "ed75cca15371-0", "text": "langchain.llms.fireworks.completion_with_retry\u00b6\nlangchain.llms.fireworks.completion_with_retry(llm: Fireworks, use_retry: bool, *, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.completion_with_retry.html"}
{"id": "85bda5713254-0", "text": "langchain.llms.base.BaseLLM\u00b6\nclass langchain.llms.base.BaseLLM[source]\u00b6\nBases: BaseLanguageModel[str], ABC\nBase LLM abstract interface.\nIt should take in a prompt and return a string.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[langchain.schema.callbacks.base.BaseCallbackManager] = None\u00b6\nparam callbacks: Optional[Union[List[langchain.schema.callbacks.base.BaseCallbackHandler], langchain.schema.callbacks.base.BaseCallbackManager]] = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str][source]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.BaseLLM.html"}
{"id": "85bda5713254-1", "text": "Subclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult[source]\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult[source]\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.BaseLLM.html"}
{"id": "85bda5713254-2", "text": "first occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage[source]\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.BaseLLM.html"}
{"id": "85bda5713254-3", "text": "Parameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str][source]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.BaseLLM.html"}
{"id": "85bda5713254-4", "text": "Default implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str][source]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.BaseLLM.html"}
{"id": "85bda5713254-5", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict[source]\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult[source]\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.BaseLLM.html"}
{"id": "85bda5713254-6", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult[source]\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.BaseLLM.html"}
{"id": "85bda5713254-7", "text": "methods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.BaseLLM.html"}
{"id": "85bda5713254-8", "text": "Return the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.BaseLLM.html"}
{"id": "85bda5713254-9", "text": "The unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str[source]\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage[source]\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.BaseLLM.html"}
{"id": "85bda5713254-10", "text": "stop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None[source]\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str][source]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.BaseLLM.html"}
{"id": "85bda5713254-11", "text": "classmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.BaseLLM.html"}
{"id": "85bda5713254-12", "text": "Create a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using BaseLLM\u00b6\nBabyAGI User Guide\nBabyAGI with Tools\nSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.base.BaseLLM.html"}
{"id": "1a3149bcf9a5-0", "text": "langchain.llms.vertexai.stream_completion_with_retry\u00b6\nlangchain.llms.vertexai.stream_completion_with_retry(llm: VertexAI, *args: Any, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) \u2192 Any[source]\u00b6\nUse tenacity to retry the completion call.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.vertexai.stream_completion_with_retry.html"}
{"id": "4403e137fc63-0", "text": "langchain.llms.azureml_endpoint.AzureMLEndpointClient\u00b6\nclass langchain.llms.azureml_endpoint.AzureMLEndpointClient(endpoint_url: str, endpoint_api_key: str, deployment_name: str = '')[source]\u00b6\nAzureML Managed Endpoint client.\nInitialize the class.\nMethods\n__init__(endpoint_url,\u00a0endpoint_api_key[,\u00a0...])\nInitialize the class.\ncall(body,\u00a0**kwargs)\ncall.\n__init__(endpoint_url: str, endpoint_api_key: str, deployment_name: str = '') \u2192 None[source]\u00b6\nInitialize the class.\ncall(body: bytes, **kwargs: Any) \u2192 bytes[source]\u00b6\ncall.\nExamples using AzureMLEndpointClient\u00b6\nAzure ML", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.azureml_endpoint.AzureMLEndpointClient.html"}
{"id": "7b1676530787-0", "text": "langchain.llms.fireworks.Fireworks\u00b6\nclass langchain.llms.fireworks.Fireworks[source]\u00b6\nBases: BaseLLM\nFireworks models.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam batch_size: int = 20\u00b6\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam fireworks_api_key: Optional[pydantic.types.SecretStr] = None\u00b6\nConstraints\ntype = string\nwriteOnly = True\nformat = password\nparam max_retries: int = 20\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str = 'accounts/fireworks/models/llama-v2-7b-chat'\u00b6\nparam model_kwargs: dict [Optional]\u00b6\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam use_retry: bool = True\u00b6\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "7b1676530787-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "7b1676530787-2", "text": "text generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "7b1676530787-3", "text": "Asynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "7b1676530787-4", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "7b1676530787-5", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ncreate_llm_result(choices: Any, prompts: List[str]) \u2192 LLMResult[source]\u00b6\nCreate the LLMResult from the choices and prompts.\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "7b1676530787-6", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "7b1676530787-7", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_batch_prompts(prompts: List[str]) \u2192 List[List[str]][source]\u00b6\nGet the sub prompts for llm call.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "7b1676530787-8", "text": "Returns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "7b1676530787-9", "text": "classmethod is_lc_serializable() \u2192 bool[source]\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "7b1676530787-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "7b1676530787-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "7b1676530787-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "7b1676530787-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Fireworks\u00b6\nFireworks", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.fireworks.Fireworks.html"}
{"id": "c93bbdcae8bb-0", "text": "langchain_experimental.llms.rellm_decoder.import_rellm\u00b6\nlangchain_experimental.llms.rellm_decoder.import_rellm() \u2192 rellm[source]\u00b6\nLazily import rellm.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain_experimental.llms.rellm_decoder.import_rellm.html"}
{"id": "a171589e8c8d-0", "text": "langchain.llms.modal.Modal\u00b6\nclass langchain.llms.modal.Modal[source]\u00b6\nBases: LLM\nModal large language models.\nTo use, you should have the modal-client python package installed.\nAny parameters that are valid to be passed to the call can be passed\nin, even if not explicitly saved on this class.\nExample\nfrom langchain.llms import Modal\nmodal = Modal(endpoint_url=\"\")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam endpoint_url: str = ''\u00b6\nmodel endpoint to use\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model_kwargs: Dict[str, Any] [Optional]\u00b6\nHolds any model parameters valid for create call not\nexplicitly specified.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.modal.Modal.html"}
{"id": "a171589e8c8d-1", "text": "Default implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.modal.Modal.html"}
{"id": "a171589e8c8d-2", "text": "text generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.modal.Modal.html"}
{"id": "a171589e8c8d-3", "text": "Asynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.modal.Modal.html"}
{"id": "a171589e8c8d-4", "text": "The jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.modal.Modal.html"}
{"id": "a171589e8c8d-5", "text": "classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.modal.Modal.html"}
{"id": "a171589e8c8d-6", "text": "Run the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.modal.Modal.html"}
{"id": "a171589e8c8d-7", "text": "This method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.modal.Modal.html"}
{"id": "a171589e8c8d-8", "text": "Parameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.modal.Modal.html"}
{"id": "a171589e8c8d-9", "text": "to the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.modal.Modal.html"}
{"id": "a171589e8c8d-10", "text": "first occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nstream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.modal.Modal.html"}
{"id": "a171589e8c8d-11", "text": "Bind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.modal.Modal.html"}
{"id": "a171589e8c8d-12", "text": "between retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using Modal\u00b6\nModal", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.modal.Modal.html"}
{"id": "752871a00972-0", "text": "langchain.llms.arcee.Arcee\u00b6\nclass langchain.llms.arcee.Arcee[source]\u00b6\nBases: LLM\nArcee\u2019s Domain Adapted Language Models (DALMs).\nTo use, set the ARCEE_API_KEY environment variable with your Arcee API key,\nor pass arcee_api_key as a named parameter.\nExample\nfrom langchain.llms import Arcee\narcee = Arcee(\n    model=\"DALM-PubMed\",\n    arcee_api_key=\"ARCEE-API-KEY\"\n)\nresponse = arcee(\"AI-driven music therapy\")\nInitializes private fields.\nparam arcee_api_key: str = ''\u00b6\nArcee API Key\nparam arcee_api_url: str = 'https://api.arcee.ai'\u00b6\nArcee API URL\nparam arcee_api_version: str = 'v2'\u00b6\nArcee API Version\nparam arcee_app_url: str = 'https://app.arcee.ai'\u00b6\nArcee App URL\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str [Required]\u00b6\nArcee DALM name\nparam model_id: str = ''\u00b6\nArcee Model ID\nparam model_kwargs: Optional[Dict[str, Any]] = None\u00b6\nKeyword arguments to pass to the model.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "752871a00972-1", "text": "param verbose: bool [Optional]\u00b6\nWhether to print out response text.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6\nCheck Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "752871a00972-2", "text": "Run the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "752871a00972-3", "text": "the runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "752871a00972-4", "text": "Subclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "752871a00972-5", "text": "e.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "752871a00972-6", "text": "exclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "752871a00972-7", "text": "Parameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "752871a00972-8", "text": "get_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "752871a00972-9", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "752871a00972-10", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "752871a00972-11", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "752871a00972-12", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "752871a00972-13", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.arcee.Arcee.html"}
{"id": "80af13ff513b-0", "text": "langchain.llms.gpt4all.GPT4All\u00b6\nclass langchain.llms.gpt4all.GPT4All[source]\u00b6\nBases: LLM\nGPT4All language models.\nTo use, you should have the gpt4all python package installed, the\npre-trained model file, and the model\u2019s config information.\nExample\nfrom langchain.llms import GPT4All\nmodel = GPT4All(model=\"./models/gpt4all-model.bin\", n_threads=8)\n# Simplest invocation\nresponse = model(\"Once upon a time, \")\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam allow_download: bool = False\u00b6\nIf model does not exist in ~/.cache/gpt4all/, download it.\nparam backend: Optional[str] = None\u00b6\nparam cache: Optional[bool] = None\u00b6\nparam callback_manager: Optional[BaseCallbackManager] = None\u00b6\nparam callbacks: Callbacks = None\u00b6\nparam device: Optional[str] = 'cpu'\u00b6\nDevice name: cpu, gpu, nvidia, intel, amd or DeviceName.\nparam echo: Optional[bool] = False\u00b6\nWhether to echo the prompt.\nparam embedding: bool = False\u00b6\nUse embedding mode only.\nparam f16_kv: bool = False\u00b6\nUse half-precision for key/value cache.\nparam logits_all: bool = False\u00b6\nReturn logits for all tokens, not just the last token.\nparam max_tokens: int = 200\u00b6\nToken context window.\nparam metadata: Optional[Dict[str, Any]] = None\u00b6\nMetadata to add to the run trace.\nparam model: str [Required]\u00b6\nPath to the pre-trained GPT4All model file.\nparam n_batch: int = 8\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-1", "text": "param n_batch: int = 8\u00b6\nBatch size for prompt processing.\nparam n_parts: int = -1\u00b6\nNumber of parts to split the model into.\nIf -1, the number of parts is automatically determined.\nparam n_predict: Optional[int] = 256\u00b6\nThe maximum number of tokens to generate.\nparam n_threads: Optional[int] = 4\u00b6\nNumber of threads to use.\nparam repeat_last_n: Optional[int] = 64\u00b6\nLast n tokens to penalize\nparam repeat_penalty: Optional[float] = 1.18\u00b6\nThe penalty to apply to repeated tokens.\nparam seed: int = 0\u00b6\nSeed. If -1, a random seed is used.\nparam stop: Optional[List[str]] = []\u00b6\nA list of strings to stop generation when encountered.\nparam streaming: bool = False\u00b6\nWhether to stream the results or not.\nparam tags: Optional[List[str]] = None\u00b6\nTags to add to the run trace.\nparam temp: Optional[float] = 0.7\u00b6\nThe temperature to use for sampling.\nparam top_k: Optional[int] = 40\u00b6\nThe top-k value to use for sampling.\nparam top_p: Optional[float] = 0.1\u00b6\nThe top-p value to use for sampling.\nparam use_mlock: bool = False\u00b6\nForce system to keep model in RAM.\nparam verbose: bool [Optional]\u00b6\nWhether to print out response text.\nparam vocab_only: bool = False\u00b6\nOnly load the vocabulary, no weights.\n__call__(prompt: str, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) \u2192 str\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-2", "text": "Check Cache and run the LLM on the given prompt and input.\nasync abatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs ainvoke in parallel using asyncio.gather.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nasync agenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\nasync agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nAsynchronously pass a sequence of prompts and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-3", "text": "need more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nasync ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nDefault implementation of ainvoke, calls invoke from a thread.\nThe default implementation allows usage of async code even if\nthe runnable did not implement a native async version of invoke.\nSubclasses should override this method if they can run asynchronously.\nasync apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nAsynchronously pass a string to the model and return a string prediction.\nUse this method when calling pure text generation models and only the topcandidate generation is needed.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-4", "text": "**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\nasync apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nAsynchronously pass messages to the model and return a message prediction.\nUse this method when calling chat models and only the topcandidate generation is needed.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nasync astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 AsyncIterator[str]\u00b6\nDefault implementation of astream, which calls ainvoke.\nSubclasses should override this method if they support streaming output.\nasync astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) \u2192 Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]\u00b6\nStream all output from a runnable, as reported to the callback system.\nThis includes all inner runs of LLMs, Retrievers, Tools, etc.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-5", "text": "This includes all inner runs of LLMs, Retrievers, Tools, etc.\nOutput is streamed as Log objects, which include a list of\njsonpatch ops that describe how the state of the run has changed in each\nstep, and the final state of the run.\nThe jsonpatch ops can be applied in order to construct state.\nasync atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 AsyncIterator[Output]\u00b6\nDefault implementation of atransform, which buffers input and calls astream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nbatch(inputs: List[Union[PromptValue, str, List[BaseMessage]]], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Any) \u2192 List[str]\u00b6\nDefault implementation runs invoke in parallel using a thread pool executor.\nThe default implementation of batch works well for IO bound runnables.\nSubclasses should override this method if they can batch more efficiently;\ne.g., if the underlying runnable uses an API which supports a batch mode.\nbind(**kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind arguments to a Runnable, returning a new Runnable.\nconfig_schema(*, include: Optional[Sequence[str]] = None) \u2192 Type[BaseModel]\u00b6\nThe type of config this runnable accepts specified as a pydantic model.\nTo mark a field as configurable, see the configurable_fields\nand configurable_alternatives methods.\nParameters\ninclude \u2013 A list of fields to include in the config schema.\nReturns\nA pydantic model that can be used to validate config.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-6", "text": "Returns\nA pydantic model that can be used to validate config.\nconfigurable_alternatives(which: ConfigurableField, default_key: str = 'default', **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) \u2192 RunnableSerializable[Input, Output]\u00b6\nconfigurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) \u2192 RunnableSerializable[Input, Output]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(**kwargs: Any) \u2192 Dict\u00b6\nReturn a dictionary of the LLM.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-7", "text": "classmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate(prompts: List[str], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, *, tags: Optional[Union[List[str], List[List[str]]]] = None, metadata: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, run_name: Optional[Union[str, List[str]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nRun the LLM on the given prompt and input.\ngenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Union[List[BaseCallbackHandler], BaseCallbackManager, None, List[Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]]] = None, **kwargs: Any) \u2192 LLMResult\u00b6\nPass a sequence of prompts to the model and return model generations.\nThis method should make use of batched calls for models that expose a batched\nAPI.\nUse this method when you want to:\ntake advantage of batched calls,\nneed more output from the model than just the top generated value,\nare building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).\nParameters\nprompts \u2013 List of PromptValues. A PromptValue is an object that can be\nconverted to match the format of any language model (string for pure\ntext generation models and BaseMessages for chat models).\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\ncallbacks \u2013 Callbacks to pass through. Used for executing additional\nfunctionality, such as logging or streaming, throughout generation.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-8", "text": "functionality, such as logging or streaming, throughout generation.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nAn LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.\nget_input_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6\nGet a pydantic model that can be used to validate input to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic input schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an input schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate input.\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nget_num_tokens(text: str) \u2192 int\u00b6\nGet the number of tokens present in the text.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nThe integer number of tokens in the text.\nget_num_tokens_from_messages(messages: List[BaseMessage]) \u2192 int\u00b6\nGet the number of tokens in the messages.\nUseful for checking if an input will fit in a model\u2019s context window.\nParameters\nmessages \u2013 The message inputs to tokenize.\nReturns\nThe sum of the number of tokens across the messages.\nget_output_schema(config: Optional[RunnableConfig] = None) \u2192 Type[BaseModel]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-9", "text": "Get a pydantic model that can be used to validate output to the runnable.\nRunnables that leverage the configurable_fields and configurable_alternatives\nmethods will have a dynamic output schema that depends on which\nconfiguration the runnable is invoked with.\nThis method allows to get an output schema for a specific configuration.\nParameters\nconfig \u2013 A config to use when generating the schema.\nReturns\nA pydantic model that can be used to validate output.\nget_token_ids(text: str) \u2192 List[int]\u00b6\nReturn the ordered ids of the tokens in a text.\nParameters\ntext \u2013 The string input to tokenize.\nReturns\nA list of ids corresponding to the tokens in the text, in order they occurin the text.\ninvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 str\u00b6\nTransform a single input into an output. Override to implement.\nParameters\ninput \u2013 The input to the runnable.\nconfig \u2013 A config to use when invoking the runnable.\nThe config supports standard keys like \u2018tags\u2019, \u2018metadata\u2019 for tracing\npurposes, \u2018max_concurrency\u2019 for controlling how much work to do\nin parallel, and other keys. Please refer to the RunnableConfig\nfor more details.\nReturns\nThe output of the runnable.\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-10", "text": "classmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nmap() \u2192 Runnable[List[Input], List[Output]]\u00b6\nReturn a new Runnable that maps a list of inputs to a list of outputs,\nby calling invoke() with each input.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 str\u00b6\nPass a single string input to the model and return a string prediction.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-11", "text": "Pass a single string input to the model and return a string prediction.\nUse this method when passing in raw text. If you want to pass in specifictypes of chat messages, use predict_messages.\nParameters\ntext \u2013 String input to pass to the model.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a string.\npredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) \u2192 BaseMessage\u00b6\nPass a message sequence to the model and return a message prediction.\nUse this method when passing in chat messages. If you want to pass in raw text,use predict.\nParameters\nmessages \u2013 A sequence of chat messages corresponding to a single model input.\nstop \u2013 Stop words to use when generating. Model output is cut off at the\nfirst occurrence of any of these substrings.\n**kwargs \u2013 Arbitrary additional keyword arguments. These are usually passed\nto the model provider API call.\nReturns\nTop model prediction as a message.\nsave(file_path: Union[Path, str]) \u2192 None\u00b6\nSave the LLM.\nParameters\nfile_path \u2013 Path to file to save the LLM to.\nExample:\n.. code-block:: python\nllm.save(file_path=\u201dpath/llm.yaml\u201d)\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-12", "text": "stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) \u2192 Iterator[str]\u00b6\nDefault implementation of stream, which calls invoke.\nSubclasses should override this method if they support streaming output.\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\ntransform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) \u2192 Iterator[Output]\u00b6\nDefault implementation of transform, which buffers input and then calls stream.\nSubclasses should override this method if they can start producing output while\ninput is still being generated.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nwith_config(config: Optional[RunnableConfig] = None, **kwargs: Any) \u2192 Runnable[Input, Output]\u00b6\nBind config to a Runnable, returning a new Runnable.\nwith_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) \u2192 RunnableWithFallbacksT[Input, Output]\u00b6\nAdd fallbacks to a runnable, returning a new Runnable.\nParameters\nfallbacks \u2013 A sequence of runnables to try if the original runnable fails.\nexceptions_to_handle \u2013 A tuple of exception types to handle.\nReturns\nA new Runnable that will try the original runnable, and then each\nfallback in order, upon failures.", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-13", "text": "fallback in order, upon failures.\nwith_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) \u2192 Runnable[Input, Output]\u00b6\nBind lifecycle listeners to a Runnable, returning a new Runnable.\non_start: Called before the runnable starts running, with the Run object.\non_end: Called after the runnable finishes running, with the Run object.\non_error: Called if the runnable throws an error, with the Run object.\nThe Run object contains information about the run, including its id,\ntype, input, output, error, start_time, end_time, and any tags or metadata\nadded to the run.\nwith_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) \u2192 Runnable[Input, Output]\u00b6\nCreate a new Runnable that retries the original runnable on exceptions.\nParameters\nretry_if_exception_type \u2013 A tuple of exception types to retry on\nwait_exponential_jitter \u2013 Whether to add jitter to the wait time\nbetween retries\nstop_after_attempt \u2013 The maximum number of attempts to make before giving up\nReturns\nA new Runnable that retries the original runnable on exceptions.\nwith_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) \u2192 Runnable[Input, Output]\u00b6\nBind input and output types to a Runnable, returning a new Runnable.\nproperty InputType: TypeAlias\u00b6\nGet the input type for this runnable.\nproperty OutputType: Type[str]\u00b6\nGet the input type for this runnable.\nproperty config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "80af13ff513b-14", "text": "property config_specs: List[langchain.schema.runnable.utils.ConfigurableFieldSpec]\u00b6\nList configurable fields for this runnable.\nproperty input_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of input this runnable accepts specified as a pydantic model.\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty output_schema: Type[pydantic.main.BaseModel]\u00b6\nThe type of output this runnable produces specified as a pydantic model.\nExamples using GPT4All\u00b6\nPromptLayer\nGPT4All\nRun LLMs locally\nUse local LLMs", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gpt4all.GPT4All.html"}
{"id": "23e3e3edbba9-0", "text": "langchain.llms.bedrock.LLMInputOutputAdapter\u00b6\nclass langchain.llms.bedrock.LLMInputOutputAdapter[source]\u00b6\nAdapter class to prepare the inputs from Langchain to a format\nthat LLM model expects.\nIt also provides helper function to extract\nthe generated text from the model response.\nAttributes\nprovider_to_output_key_map\nMethods\n__init__()\nprepare_input(provider,\u00a0prompt,\u00a0model_kwargs)\nprepare_output(provider,\u00a0response)\nprepare_output_stream(provider,\u00a0response[,\u00a0stop])\n__init__()\u00b6\nclassmethod prepare_input(provider: str, prompt: str, model_kwargs: Dict[str, Any]) \u2192 Dict[str, Any][source]\u00b6\nclassmethod prepare_output(provider: str, response: Any) \u2192 str[source]\u00b6\nclassmethod prepare_output_stream(provider: str, response: Any, stop: Optional[List[str]] = None) \u2192 Iterator[GenerationChunk][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.bedrock.LLMInputOutputAdapter.html"}
{"id": "e74707f2ebbe-0", "text": "langchain.llms.gradient_ai.TrainResult\u00b6\nclass langchain.llms.gradient_ai.TrainResult[source]\u00b6\nTrain result.\nloss: float\u00b6", "source": "lang/api.python.langchain.com/en/latest/llms/langchain.llms.gradient_ai.TrainResult.html"}
{"id": "5c81f3a01aad-0", "text": "langchain_experimental.graph_transformers.diffbot.NodesList\u00b6\nclass langchain_experimental.graph_transformers.diffbot.NodesList[source]\u00b6\nManages a list of nodes with associated properties.\nnodes\u00b6\nStores nodes as keys and their properties as values.\nEach key is a tuple where the first element is the\nnode ID and the second is the node type.\nType\nDict[Tuple, Any]\nMethods\n__init__()\nadd_node_property(node,\u00a0properties)\nAdds or updates node properties.\nreturn_node_list()\nReturns the nodes as a list of Node objects.\n__init__() \u2192 None[source]\u00b6\nadd_node_property(node: Tuple[Union[str, int], str], properties: Dict[str, Any]) \u2192 None[source]\u00b6\nAdds or updates node properties.\nIf the node does not exist in the list, it\u2019s added along with its properties.\nIf the node already exists, its properties are updated with the new values.\nParameters\nnode (Tuple) \u2013 A tuple containing the node ID and node type.\nproperties (Dict) \u2013 A dictionary of properties to add or update for the node.\nreturn_node_list() \u2192 List[Node][source]\u00b6\nReturns the nodes as a list of Node objects.\nEach Node object will have its ID, type, and properties populated.\nReturns\nA list of Node objects.\nReturn type\nList[Node]", "source": "lang/api.python.langchain.com/en/latest/graph_transformers/langchain_experimental.graph_transformers.diffbot.NodesList.html"}
{"id": "99b2056ba95d-0", "text": "langchain_experimental.graph_transformers.diffbot.SimplifiedSchema\u00b6\nclass langchain_experimental.graph_transformers.diffbot.SimplifiedSchema[source]\u00b6\nProvides functionality for working with a simplified schema mapping.\nschema\u00b6\nA dictionary containing the mapping to simplified schema types.\nType\nDict\nInitializes the schema dictionary based on the predefined list.\nMethods\n__init__()\nInitializes the schema dictionary based on the predefined list.\nget_type(type)\nRetrieves the simplified schema type for a given original type.\n__init__() \u2192 None[source]\u00b6\nInitializes the schema dictionary based on the predefined list.\nget_type(type: str) \u2192 str[source]\u00b6\nRetrieves the simplified schema type for a given original type.\nParameters\ntype (str) \u2013 The original schema type to find the simplified type for.\nReturns\nThe simplified schema type if it exists;otherwise, returns the original type.\nReturn type\nstr", "source": "lang/api.python.langchain.com/en/latest/graph_transformers/langchain_experimental.graph_transformers.diffbot.SimplifiedSchema.html"}
{"id": "ce0aa7fae373-0", "text": "langchain_experimental.graph_transformers.diffbot.DiffbotGraphTransformer\u00b6\nclass langchain_experimental.graph_transformers.diffbot.DiffbotGraphTransformer(diffbot_api_key: Optional[str] = None, fact_confidence_threshold: float = 0.7, include_qualifiers: bool = True, include_evidence: bool = True, simplified_schema: bool = True)[source]\u00b6\nTransforms documents into graph documents using Diffbot\u2019s NLP API.\nA graph document transformation system takes a sequence of Documents and returns a\nsequence of Graph Documents.\nExample\nclass DiffbotGraphTransformer(BaseGraphDocumentTransformer):\n    def transform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[GraphDocument]:\n        results = []\n        for document in documents:\n            raw_results = self.nlp_request(document.page_content)\n            graph_document = self.process_response(raw_results, document)\n            results.append(graph_document)\n        return results\n    async def atransform_documents(\n        self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        raise NotImplementedError\nInitialize the graph transformer with various options.\nParameters\ndiffbot_api_key (str) \u2013 The API key for Diffbot\u2019s NLP services.\nfact_confidence_threshold (float) \u2013 Minimum confidence level for facts to be included.\ninclude_qualifiers (bool) \u2013 Whether to include qualifiers in the relationships.\ninclude_evidence (bool) \u2013 Whether to include evidence for the relationships.\nsimplified_schema (bool) \u2013 Whether to use a simplified schema for relationships.\nMethods\n__init__([diffbot_api_key,\u00a0...])\nInitialize the graph transformer with various options.\nconvert_to_graph_documents(documents)\nConvert a sequence of documents into graph documents.\nnlp_request(text)\nMake an API request to the Diffbot NLP endpoint.", "source": "lang/api.python.langchain.com/en/latest/graph_transformers/langchain_experimental.graph_transformers.diffbot.DiffbotGraphTransformer.html"}
{"id": "ce0aa7fae373-1", "text": "nlp_request(text)\nMake an API request to the Diffbot NLP endpoint.\nprocess_response(payload,\u00a0document)\nTransform the Diffbot NLP response into a GraphDocument.\n__init__(diffbot_api_key: Optional[str] = None, fact_confidence_threshold: float = 0.7, include_qualifiers: bool = True, include_evidence: bool = True, simplified_schema: bool = True) \u2192 None[source]\u00b6\nInitialize the graph transformer with various options.\nParameters\ndiffbot_api_key (str) \u2013 The API key for Diffbot\u2019s NLP services.\nfact_confidence_threshold (float) \u2013 Minimum confidence level for facts to be included.\ninclude_qualifiers (bool) \u2013 Whether to include qualifiers in the relationships.\ninclude_evidence (bool) \u2013 Whether to include evidence for the relationships.\nsimplified_schema (bool) \u2013 Whether to use a simplified schema for relationships.\nconvert_to_graph_documents(documents: Sequence[Document]) \u2192 List[GraphDocument][source]\u00b6\nConvert a sequence of documents into graph documents.\nParameters\ndocuments (Sequence[Document]) \u2013 The original documents.\n**kwargs \u2013 Additional keyword arguments.\nReturns\nThe transformed documents as graphs.\nReturn type\nSequence[GraphDocument]\nnlp_request(text: str) \u2192 Dict[str, Any][source]\u00b6\nMake an API request to the Diffbot NLP endpoint.\nParameters\ntext (str) \u2013 The text to be processed.\nReturns\nThe JSON response from the API.\nReturn type\nDict[str, Any]\nprocess_response(payload: Dict[str, Any], document: Document) \u2192 GraphDocument[source]\u00b6\nTransform the Diffbot NLP response into a GraphDocument.\nParameters\npayload (Dict[str, Any]) \u2013 The JSON response from Diffbot\u2019s NLP API.\ndocument (Document) \u2013 The original document.\nReturns", "source": "lang/api.python.langchain.com/en/latest/graph_transformers/langchain_experimental.graph_transformers.diffbot.DiffbotGraphTransformer.html"}
{"id": "ce0aa7fae373-2", "text": "document (Document) \u2013 The original document.\nReturns\nThe transformed document as a graph.\nReturn type\nGraphDocument", "source": "lang/api.python.langchain.com/en/latest/graph_transformers/langchain_experimental.graph_transformers.diffbot.DiffbotGraphTransformer.html"}
{"id": "508ed3ea8828-0", "text": "langchain_experimental.graph_transformers.diffbot.format_property_key\u00b6\nlangchain_experimental.graph_transformers.diffbot.format_property_key(s: str) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/graph_transformers/langchain_experimental.graph_transformers.diffbot.format_property_key.html"}
{"id": "a5be391302b0-0", "text": "langchain_experimental.generative_agents.memory.GenerativeAgentMemory\u00b6\nclass langchain_experimental.generative_agents.memory.GenerativeAgentMemory[source]\u00b6\nBases: BaseMemory\nMemory for the generative agent.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam add_memory_key: str = 'add_memory'\u00b6\nparam aggregate_importance: float = 0.0\u00b6\nTrack the sum of the \u2018importance\u2019 of recent memories.\nTriggers reflection when it reaches reflection_threshold.\nparam current_plan: List[str] = []\u00b6\nThe current plan of the agent.\nparam importance_weight: float = 0.15\u00b6\nHow much weight to assign the memory importance.\nparam llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nThe core language model.\nparam max_tokens_limit: int = 1200\u00b6\nparam memory_retriever: langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever [Required]\u00b6\nThe retriever to fetch related memories.\nparam most_recent_memories_key: str = 'most_recent_memories'\u00b6\nparam most_recent_memories_token_key: str = 'recent_memories_token'\u00b6\nparam now_key: str = 'now'\u00b6\nparam queries_key: str = 'queries'\u00b6\nparam reflecting: bool = False\u00b6\nparam reflection_threshold: Optional[float] = None\u00b6\nWhen aggregate_importance exceeds reflection_threshold, stop to reflect.\nparam relevant_memories_key: str = 'relevant_memories'\u00b6\nparam relevant_memories_simple_key: str = 'relevant_memories_simple'\u00b6\nparam verbose: bool = False\u00b6\nadd_memories(memory_content: str, now: Optional[datetime] = None) \u2192 List[str][source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/generative_agents/langchain_experimental.generative_agents.memory.GenerativeAgentMemory.html"}
{"id": "a5be391302b0-1", "text": "Add an observations or memories to the agent\u2019s memory.\nadd_memory(memory_content: str, now: Optional[datetime] = None) \u2192 List[str][source]\u00b6\nAdd an observation or memory to the agent\u2019s memory.\nchain(prompt: PromptTemplate) \u2192 LLMChain[source]\u00b6\nclear() \u2192 None[source]\u00b6\nClear memory contents.\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6", "source": "lang/api.python.langchain.com/en/latest/generative_agents/langchain_experimental.generative_agents.memory.GenerativeAgentMemory.html"}
{"id": "a5be391302b0-2", "text": "Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nfetch_memories(observation: str, now: Optional[datetime] = None) \u2192 List[Document][source]\u00b6\nFetch related memories.\nformat_memories_detail(relevant_memories: List[Document]) \u2192 str[source]\u00b6\nformat_memories_simple(relevant_memories: List[Document]) \u2192 str[source]\u00b6\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\nclassmethod get_lc_namespace() \u2192 List[str]\u00b6\nGet the namespace of the langchain object.\nFor example, if the class is langchain.llms.openai.OpenAI, then the\nnamespace is [\u201clangchain\u201d, \u201cllms\u201d, \u201copenai\u201d]\nclassmethod is_lc_serializable() \u2192 bool\u00b6\nIs this class serializable?\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod lc_id() \u2192 List[str]\u00b6\nA unique identifier for this class for serialization purposes.\nThe unique identifier is a list of strings that describes the path\nto the object.\nload_memory_variables(inputs: Dict[str, Any]) \u2192 Dict[str, str][source]\u00b6\nReturn key-value pairs given the text input to the chain.", "source": "lang/api.python.langchain.com/en/latest/generative_agents/langchain_experimental.generative_agents.memory.GenerativeAgentMemory.html"}
{"id": "a5be391302b0-3", "text": "Return key-value pairs given the text input to the chain.\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\npause_to_reflect(now: Optional[datetime] = None) \u2192 List[str][source]\u00b6\nReflect on recent observations and generate \u2018insights\u2019.\nsave_context(inputs: Dict[str, Any], outputs: Dict[str, Any]) \u2192 None[source]\u00b6\nSave the context of this model run to memory.\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nto_json() \u2192 Union[SerializedConstructor, SerializedNotImplemented]\u00b6\nto_json_not_implemented() \u2192 SerializedNotImplemented\u00b6\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6\nproperty lc_attributes: Dict\u00b6\nList of attribute names that should be included in the serialized kwargs.\nThese attributes must be accepted by the constructor.\nproperty lc_secrets: Dict[str, str]\u00b6\nA map of constructor argument names to secret ids.\nFor example,{\u201copenai_api_key\u201d: \u201cOPENAI_API_KEY\u201d}\nproperty memory_variables: List[str]\u00b6\nInput keys this memory class will load dynamically.", "source": "lang/api.python.langchain.com/en/latest/generative_agents/langchain_experimental.generative_agents.memory.GenerativeAgentMemory.html"}
{"id": "62b4d8483fa0-0", "text": "langchain_experimental.generative_agents.generative_agent.GenerativeAgent\u00b6\nclass langchain_experimental.generative_agents.generative_agent.GenerativeAgent[source]\u00b6\nBases: BaseModel\nAn Agent as a character with memory and innate characteristics.\nCreate a new model by parsing and validating input data from keyword arguments.\nRaises ValidationError if the input data cannot be parsed to form a valid model.\nparam age: Optional[int] = None\u00b6\nThe optional age of the character.\nparam daily_summaries: List[str] [Optional]\u00b6\nSummary of the events in the plan that the agent took.\nparam last_refreshed: datetime.datetime [Optional]\u00b6\nThe last time the character\u2019s summary was regenerated.\nparam llm: langchain.schema.language_model.BaseLanguageModel [Required]\u00b6\nThe underlying language model.\nparam memory: langchain_experimental.generative_agents.memory.GenerativeAgentMemory [Required]\u00b6\nThe memory object that combines relevance, recency, and \u2018importance\u2019.\nparam name: str [Required]\u00b6\nThe character\u2019s name.\nparam status: str [Required]\u00b6\nThe traits of the character you wish not to change.\nparam summary: str = ''\u00b6\nStateful self-summary generated via reflection on the character\u2019s memory.\nparam summary_refresh_seconds: int = 3600\u00b6\nHow frequently to re-generate the summary.\nparam traits: str = 'N/A'\u00b6\nPermanent traits to ascribe to the character.\nparam verbose: bool = False\u00b6\nchain(prompt: PromptTemplate) \u2192 LLMChain[source]\u00b6\nclassmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) \u2192 Model\u00b6\nCreates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.\nDefault values are respected, but no other validation is performed.", "source": "lang/api.python.langchain.com/en/latest/generative_agents/langchain_experimental.generative_agents.generative_agent.GenerativeAgent.html"}
{"id": "62b4d8483fa0-1", "text": "Default values are respected, but no other validation is performed.\nBehaves as if Config.extra = \u2018allow\u2019 was set since it adds all passed values\ncopy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) \u2192 Model\u00b6\nDuplicate a model, optionally choose which fields to include, exclude and change.\nParameters\ninclude \u2013 fields to include in new model\nexclude \u2013 fields to exclude from new model, as with values this takes precedence over include\nupdate \u2013 values to change/add in the new model. Note: the data is not validated before creating\nthe new model: you should trust this data\ndeep \u2013 set to True to make a deep copy of the model\nReturns\nnew model instance\ndict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) \u2192 DictStrAny\u00b6\nGenerate a dictionary representation of the model, optionally specifying which fields to include or exclude.\nclassmethod from_orm(obj: Any) \u2192 Model\u00b6\ngenerate_dialogue_response(observation: str, now: Optional[datetime] = None) \u2192 Tuple[bool, str][source]\u00b6\nReact to a given observation.\ngenerate_reaction(observation: str, now: Optional[datetime] = None) \u2192 Tuple[bool, str][source]\u00b6\nReact to a given observation.\nget_full_header(force_refresh: bool = False, now: Optional[datetime] = None) \u2192 str[source]\u00b6", "source": "lang/api.python.langchain.com/en/latest/generative_agents/langchain_experimental.generative_agents.generative_agent.GenerativeAgent.html"}
{"id": "62b4d8483fa0-2", "text": "Return a full header of the agent\u2019s status, summary, and current time.\nget_summary(force_refresh: bool = False, now: Optional[datetime] = None) \u2192 str[source]\u00b6\nReturn a descriptive summary of the agent.\njson(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) \u2192 unicode\u00b6\nGenerate a JSON representation of the model, include and exclude arguments as per dict().\nencoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().\nclassmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod parse_obj(obj: Any) \u2192 Model\u00b6\nclassmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) \u2192 Model\u00b6\nclassmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') \u2192 DictStrAny\u00b6\nclassmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) \u2192 unicode\u00b6\nsummarize_related_memories(observation: str) \u2192 str[source]\u00b6\nSummarize memories that are most relevant to an observation.\nclassmethod update_forward_refs(**localns: Any) \u2192 None\u00b6", "source": "lang/api.python.langchain.com/en/latest/generative_agents/langchain_experimental.generative_agents.generative_agent.GenerativeAgent.html"}
{"id": "62b4d8483fa0-3", "text": "classmethod update_forward_refs(**localns: Any) \u2192 None\u00b6\nTry to update ForwardRefs on fields based on this Model, globalns and localns.\nclassmethod validate(value: Any) \u2192 Model\u00b6", "source": "lang/api.python.langchain.com/en/latest/generative_agents/langchain_experimental.generative_agents.generative_agent.GenerativeAgent.html"}
